From d659526b5ae3363de6dc7691a782a45aaf781a46 Mon Sep 17 00:00:00 2001 From: Koha Development Team <> Date: Mon, 27 Jan 2025 13:21:28 +0100 Subject: [PATCH] Bug 38664: Tidy the whole codebase This commit is generated using: % perl misc/devel/tidy.pl *within* ktd, to get the same version of perltidy than what will be used by our CI (currently v20230309). Signed-off-by: Katrin Fischer --- .prettierrc.js | 4 +- C4/Accounts.pm | 28 +- C4/Acquisition.pm | 1022 +- C4/Auth.pm | 845 +- C4/Auth_with_cas.pm | 77 +- C4/Auth_with_ldap.pm | 317 +- C4/Auth_with_shibboleth.pm | 82 +- C4/AuthoritiesMarc.pm | 1326 +- C4/AuthoritiesMarc/MARC21.pm | 16 +- C4/AuthoritiesMarc/UNIMARC.pm | 4 +- C4/Barcodes.pm | 288 +- C4/Barcodes/EAN13.pm | 10 +- C4/Barcodes/ValueBuilder.pm | 31 +- C4/Barcodes/annual.pm | 87 +- C4/Barcodes/hbyymmincr.pm | 104 +- C4/Biblio.pm | 998 +- C4/Breeding.pm | 480 +- C4/Budgets.pm | 746 +- C4/Calendar.pm | 334 +- C4/Charset.pm | 1237 +- C4/Circulation.pm | 2293 +- C4/ClassSortRoutine.pm | 26 +- C4/ClassSortRoutine/Dewey.pm | 30 +- C4/ClassSortRoutine/Generic.pm | 6 +- C4/ClassSortRoutine/LCC.pm | 8 +- C4/ClassSource.pm | 35 +- C4/ClassSplitRoutine.pm | 7 +- C4/ClassSplitRoutine/Dewey.pm | 10 +- C4/ClassSplitRoutine/Generic.pm | 7 +- C4/ClassSplitRoutine/LCC.pm | 10 +- C4/ClassSplitRoutine/RegEx.pm | 6 +- C4/Context.pm | 210 +- C4/Contract.pm | 31 +- C4/CourseReserves.pm | 188 +- C4/Creators.pm | 60 +- C4/Creators/Batch.pm | 182 +- C4/Creators/Layout.pm | 137 +- C4/Creators/Lib.pm | 387 +- C4/Creators/PDF.pm | 101 +- C4/Creators/Profile.pm | 157 +- C4/Creators/Template.pm | 258 +- C4/External/Amazon.pm | 8 +- C4/External/BakerTaylor.pm | 89 +- C4/External/OverDrive.pm | 34 +- C4/External/Syndetics.pm | 169 +- C4/Form/MessagingPreferences.pm | 45 +- C4/HTML5Media.pm | 185 +- C4/Heading.pm | 53 +- C4/Heading/MARC21.pm | 121 +- C4/Heading/UNIMARC.pm | 33 +- C4/HoldsQueue.pm | 247 +- C4/ILSDI/Services.pm | 204 +- C4/ImportBatch.pm | 957 +- C4/ImportExportFramework.pm | 777 +- C4/InstallAuth.pm | 104 +- C4/Installer.pm | 387 +- C4/Installer/PerlModules.pm | 34 +- C4/Installer/UpgradeBackup.pm | 47 +- C4/ItemCirculationAlertPreference.pm | 92 +- C4/Items.pm | 646 +- C4/Koha.pm | 414 +- C4/Labels/Batch.pm | 10 +- C4/Labels/Label.pm | 494 +- C4/Labels/Layout.pm | 10 +- C4/Labels/Profile.pm | 10 +- C4/Labels/Template.pm | 1 - C4/Languages.pm | 445 +- C4/Letters.pm | 807 +- C4/Linker.pm | 12 +- C4/Linker/Default.pm | 55 +- C4/Linker/FirstMatch.pm | 6 +- C4/Linker/LastMatch.pm | 6 +- C4/MarcModificationTemplates.pm | 732 +- C4/Matcher.pm | 412 +- C4/Members.pm | 174 +- C4/Members/Messaging.pm | 67 +- C4/Members/Statistics.pm | 41 +- C4/Message.pm | 69 +- C4/OAI/Sets.pm | 156 +- C4/Output.pm | 156 +- C4/Output/JSONStream.pm | 8 +- C4/Overdues.pm | 267 +- C4/Patroncards.pm | 32 +- C4/Patroncards/Batch.pm | 10 +- C4/Patroncards/Layout.pm | 10 +- C4/Patroncards/Lib.pm | 118 +- C4/Patroncards/Patroncard.pm | 334 +- C4/Patroncards/Profile.pm | 10 +- C4/Patroncards/Template.pm | 1 - C4/Record.pm | 565 +- C4/Reports.pm | 11 +- C4/Reports/Guided.pm | 586 +- C4/Reserves.pm | 947 +- C4/Ris.pm | 1052 +- C4/RotatingCollections.pm | 89 +- C4/SIP/ILS.pm | 413 +- C4/SIP/ILS/Item.pm | 243 +- C4/SIP/ILS/Patron.pm | 340 +- C4/SIP/ILS/Transaction.pm | 65 +- C4/SIP/ILS/Transaction/Checkin.pm | 147 +- C4/SIP/ILS/Transaction/Checkout.pm | 85 +- C4/SIP/ILS/Transaction/FeePayment.pm | 17 +- C4/SIP/ILS/Transaction/Hold.pm | 77 +- C4/SIP/ILS/Transaction/Renew.pm | 34 +- C4/SIP/ILS/Transaction/RenewAll.pm | 9 +- C4/SIP/SIPServer.pm | 254 +- C4/SIP/Sip.pm | 91 +- C4/SIP/Sip/Checksum.pm | 21 +- C4/SIP/Sip/Configuration.pm | 17 +- C4/SIP/Sip/Constants.pm | 253 +- C4/SIP/Sip/MsgType.pm | 429 +- C4/SIP/Trapper.pm | 5 +- C4/SMS.pm | 22 +- C4/Scheduler.pm | 29 +- C4/Scrubber.pm | 4 +- C4/Search.pm | 1712 +- C4/Search/History.pm | 75 +- C4/Search/PazPar2.pm | 88 +- C4/Serials.pm | 985 +- C4/Serials/Frequency.pm | 70 +- C4/Serials/Numberpattern.pm | 110 +- C4/Service.pm | 40 +- C4/ShelfBrowser.pm | 83 +- C4/SocialData.pm | 47 +- C4/Stats.pm | 7 +- C4/TTParser.pm | 158 +- C4/Tags.pm | 719 +- C4/Templates.pm | 178 +- C4/TmplToken.pm | 35 +- C4/TmplTokenType.pm | 56 +- C4/UsageStats.pm | 30 +- C4/Utils/DataTables/TablesSettings.pm | 46 +- C4/Utils/DataTables/VirtualShelves.pm | 56 +- C4/XISBN.pm | 81 +- C4/XSLT.pm | 227 +- Koha/Account.pm | 155 +- Koha/Account/Credits.pm | 2 +- Koha/Account/Debits.pm | 2 +- Koha/Account/Line.pm | 343 +- Koha/Account/Lines.pm | 25 +- Koha/Account/Offset.pm | 9 +- Koha/Account/Offsets.pm | 13 +- Koha/Acquisition/Basket.pm | 48 +- Koha/Acquisition/Bookseller.pm | 24 +- Koha/Acquisition/Bookseller/Contact.pm | 1 - Koha/Acquisition/Bookseller/Contacts.pm | 1 - Koha/Acquisition/Bookseller/Interface.pm | 4 +- Koha/Acquisition/Currencies.pm | 3 +- Koha/Acquisition/Currency.pm | 28 +- Koha/Acquisition/Fund.pm | 4 +- Koha/Acquisition/Invoice.pm | 9 +- Koha/Acquisition/Invoice/Adjustment.pm | 9 +- Koha/Acquisition/Invoice/Adjustments.pm | 1 - Koha/Acquisition/Order.pm | 205 +- Koha/Acquisition/Order/Claim.pm | 1 - Koha/Acquisition/Order/Claims.pm | 1 - Koha/Acquisition/Orders.pm | 76 +- Koha/AdditionalContents.pm | 27 +- Koha/AdditionalField.pm | 6 +- Koha/AdditionalFieldValue.pm | 2 +- Koha/AdditionalFieldValues.pm | 2 +- Koha/AdditionalFields.pm | 2 +- Koha/AdvancedEditorMacro.pm | 8 +- Koha/AdvancedEditorMacros.pm | 1 - Koha/ApiKey.pm | 11 +- Koha/ApiKeys.pm | 1 - Koha/App/Intranet.pm | 14 +- Koha/App/Opac.pm | 16 +- Koha/App/Plugin/CGIBinKoha.pm | 76 +- Koha/App/Plugin/RESTV1.pm | 4 +- Koha/ArticleRequest.pm | 42 +- Koha/ArticleRequests.pm | 12 +- Koha/AudioAlert.pm | 1 - Koha/AudioAlerts.pm | 10 +- Koha/Auth/Client.pm | 18 +- Koha/Auth/Client/OAuth.pm | 14 +- Koha/Auth/Identity/Provider.pm | 21 +- Koha/Auth/Identity/Provider/OAuth.pm | 8 +- Koha/Auth/Identity/Provider/OIDC.pm | 6 +- Koha/Auth/Permissions.pm | 30 +- Koha/Auth/TwoFactorAuth.pm | 39 +- Koha/AuthUtils.pm | 57 +- Koha/AuthorisedValue.pm | 7 +- Koha/AuthorisedValueCategories.pm | 1 - Koha/AuthorisedValueCategory.pm | 3 +- Koha/AuthorisedValues.pm | 34 +- Koha/Authorities.pm | 19 +- Koha/Authority.pm | 40 +- Koha/Authority/ControlledIndicators.pm | 59 +- Koha/Authority/MergeRequest.pm | 27 +- Koha/Authority/MergeRequests.pm | 22 +- Koha/Authority/Type.pm | 3 +- Koha/Authority/Types.pm | 1 - Koha/BackgroundJob.pm | 80 +- Koha/BackgroundJob/BatchCancelHold.pm | 39 +- Koha/BackgroundJob/BatchDeleteAuthority.pm | 46 +- Koha/BackgroundJob/BatchDeleteBiblio.pm | 87 +- Koha/BackgroundJob/BatchDeleteItem.pm | 70 +- Koha/BackgroundJob/BatchUpdateAuthority.pm | 43 +- Koha/BackgroundJob/BatchUpdateBiblio.pm | 51 +- .../BatchUpdateBiblioHoldsQueue.pm | 33 +- Koha/BackgroundJob/BatchUpdateItem.pm | 30 +- .../CreateEHoldingsFromBiblios.pm | 109 +- Koha/BackgroundJob/ImportKBARTFile.pm | 14 +- Koha/BackgroundJob/MARCImportCommitBatch.pm | 66 +- Koha/BackgroundJob/MARCImportRevertBatch.pm | 29 +- Koha/BackgroundJob/StageMARCForImport.pm | 16 +- Koha/BackgroundJob/UpdateElasticIndex.pm | 17 +- Koha/BackgroundJobs.pm | 13 +- Koha/Biblio.pm | 459 +- Koha/Biblio/ItemGroup.pm | 27 +- Koha/Biblio/Metadata.pm | 45 +- Koha/Biblio/Metadatas.pm | 1 - Koha/BiblioFramework.pm | 1 - Koha/BiblioFrameworks.pm | 1 - Koha/BiblioUtils.pm | 33 +- Koha/Biblioitem.pm | 37 +- Koha/Biblioitems.pm | 1 - Koha/Biblios.pm | 14 +- Koha/Booking.pm | 1 + Koha/Cache.pm | 108 +- Koha/Cache/Memory/Lite.pm | 4 +- Koha/Cache/Object.pm | 32 +- Koha/Caches.pm | 4 +- Koha/Calendar.pm | 127 +- Koha/Cash/Register.pm | 38 +- Koha/Cash/Register/Action.pm | 1 - Koha/Cash/Register/Actions.pm | 1 - Koha/Cash/Register/Cashup.pm | 67 +- Koha/Cash/Register/Cashups.pm | 5 +- Koha/Cash/Registers.pm | 1 - Koha/Charges/Fees.pm | 45 +- Koha/Charges/Sales.pm | 66 +- Koha/Checkout.pm | 59 +- Koha/Checkouts.pm | 3 - Koha/Checkouts/Renewal.pm | 6 +- Koha/Checkouts/Renewals.pm | 1 - Koha/Checkouts/ReturnClaim.pm | 16 +- Koha/Checkouts/ReturnClaims.pm | 5 +- Koha/CirculationRule.pm | 4 +- Koha/CirculationRules.pm | 151 +- Koha/Cities.pm | 1 - Koha/City.pm | 1 - Koha/ClassSortRule.pm | 1 - Koha/ClassSortRules.pm | 1 - Koha/ClassSource.pm | 3 +- Koha/ClassSources.pm | 1 - Koha/ClassSplitRule.pm | 8 +- Koha/Club.pm | 1 - Koha/Club/Enrollment.pm | 13 +- Koha/Club/Enrollment/Field.pm | 1 - Koha/Club/Enrollment/Fields.pm | 1 - Koha/Club/Enrollments.pm | 1 - Koha/Club/Field.pm | 3 +- Koha/Club/Fields.pm | 1 - Koha/Club/Hold.pm | 74 +- Koha/Club/Hold/PatronHold.pm | 1 - Koha/Club/Hold/PatronHolds.pm | 1 - Koha/Club/Holds.pm | 1 - Koha/Club/Template.pm | 1 - Koha/Club/Template/EnrollmentField.pm | 1 - Koha/Club/Template/EnrollmentFields.pm | 1 - Koha/Club/Template/Field.pm | 1 - Koha/Club/Template/Fields.pm | 1 - Koha/Club/Templates.pm | 1 - Koha/Clubs.pm | 1 - Koha/CodeList/Unimarc/MediumOfPerformance.pm | 66 +- Koha/Config.pm | 52 +- Koha/Config/SysPref.pm | 2 - Koha/Config/SysPrefs.pm | 1 - Koha/CookieManager.pm | 31 +- Koha/Course/Instructor.pm | 1 - Koha/Course/Instructors.pm | 1 - Koha/Course/Item.pm | 7 +- Koha/Course/Items.pm | 1 - Koha/Course/Reserves.pm | 1 - Koha/Courses.pm | 1 - Koha/CoverImage.pm | 38 +- Koha/CoverImages.pm | 9 +- Koha/CsvProfile.pm | 1 - Koha/CsvProfiles.pm | 1 - Koha/CurbsidePickup.pm | 110 +- Koha/CurbsidePickupIssue.pm | 2 +- Koha/CurbsidePickupPolicy.pm | 38 +- Koha/CurbsidePickups.pm | 10 +- Koha/Database.pm | 43 +- Koha/Database/Auditor.pm | 6 +- Koha/Database/Commenter.pm | 108 +- Koha/DateUtils.pm | 156 +- Koha/Desk.pm | 1 - Koha/Desks.pm | 2 - Koha/EDI.pm | 298 +- Koha/ERM/Agreement.pm | 36 +- Koha/ERM/Agreement/License.pm | 4 +- Koha/ERM/Agreement/Licenses.pm | 1 - Koha/ERM/Agreement/Periods.pm | 1 - Koha/ERM/Agreement/Relationship.pm | 4 +- Koha/ERM/Agreement/Relationships.pm | 1 - Koha/ERM/Agreements.pm | 11 +- Koha/ERM/Documents.pm | 34 +- Koha/ERM/EHoldings/Package.pm | 6 +- Koha/ERM/EHoldings/Package/Agreement.pm | 4 +- Koha/ERM/EHoldings/Packages.pm | 1 - Koha/ERM/EHoldings/Resource.pm | 7 +- Koha/ERM/EHoldings/Titles.pm | 1 - Koha/ERM/EUsage/CounterLog.pm | 1 - Koha/ERM/EUsage/SushiCounter.pm | 14 +- Koha/ERM/License.pm | 6 +- Koha/ERM/Licenses.pm | 1 - Koha/ERM/Providers/EBSCO.pm | 112 +- Koha/ERM/UserRole.pm | 2 +- Koha/ERM/UserRoles.pm | 1 - Koha/Edifact.pm | 26 +- Koha/Edifact/Line.pm | 151 +- Koha/Edifact/Message.pm | 12 +- Koha/Edifact/Order.pm | 114 +- Koha/Edifact/Segment.pm | 13 +- Koha/Edifact/Transport.pm | 123 +- Koha/Email.pm | 30 +- Koha/Encryption.pm | 4 +- Koha/Exception.pm | 12 +- Koha/Exceptions.pm | 38 +- Koha/Exceptions/Authentication.pm | 4 +- Koha/Exceptions/Authorization.pm | 4 +- Koha/Exceptions/BackgroundJob.pm | 2 +- Koha/Exceptions/Checkouts/ReturnClaims.pm | 2 +- Koha/Exceptions/ClubHold.pm | 2 +- Koha/Exceptions/Config.pm | 2 +- Koha/Exceptions/Hold.pm | 6 +- Koha/Exceptions/Ill.pm | 6 +- Koha/Exceptions/Library.pm | 2 +- Koha/Exceptions/MarcOverlayRule.pm | 4 +- Koha/Exceptions/Metadata.pm | 10 +- Koha/Exceptions/Object.pm | 43 +- Koha/Exceptions/Password.pm | 18 +- Koha/Exceptions/Patron.pm | 8 +- Koha/Exceptions/Patron/Attribute/Type.pm | 11 +- Koha/Exceptions/Patron/Category.pm | 6 +- Koha/Exceptions/Patron/MessagePreference.pm | 47 +- .../Patron/MessagePreference/Transport.pm | 8 +- Koha/Exceptions/Patron/Modification.pm | 4 +- Koha/Exceptions/Plugin.pm | 21 +- Koha/Exceptions/SysPref.pm | 2 +- Koha/Exceptions/Token.pm | 4 +- Koha/Exceptions/TransferLimit.pm | 2 +- Koha/Exceptions/Virtualshelf.pm | 14 +- Koha/Exceptions/XSLT.pm | 4 +- Koha/Exporter/Record.pm | 56 +- Koha/ExternalContent.pm | 26 +- Koha/ExternalContent/OverDrive.pm | 129 +- Koha/Filter/MARC/EmbedItemsAvailability.pm | 32 +- Koha/Filter/MARC/EmbedSeeFromHeadings.pm | 12 +- Koha/Filter/MARC/ExpandCodedFields.pm | 28 +- Koha/Filter/MARC/Null.pm | 3 +- Koha/Filter/MARC/ViewPolicy.pm | 19 +- Koha/FrameworkPlugin.pm | 192 +- Koha/Hold.pm | 197 +- Koha/Hold/CancellationRequests.pm | 1 - Koha/Hold/HoldsQueueItem.pm | 12 +- Koha/Holds.pm | 41 +- Koha/I18N.pm | 76 +- Koha/ILL/Backend/Standard.pm | 17 +- Koha/ILL/Comment.pm | 6 +- Koha/ILL/Request.pm | 721 +- Koha/ILL/Request/Attributes.pm | 2 +- Koha/ILL/Request/Config.pm | 115 +- Koha/ILL/Request/Logger.pm | 101 +- Koha/ILL/Request/SupplierUpdate.pm | 14 +- Koha/ILL/Request/Workflow.pm | 3 +- Koha/ILL/Request/Workflow/Availability.pm | 22 +- Koha/ILL/Request/Workflow/TypeDisclaimer.pm | 4 +- Koha/ILL/Requests.pm | 22 +- Koha/Import/Record.pm | 33 +- Koha/Import/Record/Match.pm | 5 +- Koha/Import/Record/Matches.pm | 4 +- Koha/ImportBatch.pm | 3 +- Koha/ImportBatchProfile.pm | 6 +- Koha/ImportBatchProfiles.pm | 2 +- Koha/ImportBatches.pm | 2 +- Koha/Indexer/Utils.pm | 131 +- Koha/Item.pm | 587 +- Koha/Item/Attributes.pm | 29 +- Koha/Item/Search/Field.pm | 37 +- Koha/Item/Template.pm | 4 +- Koha/Item/Templates.pm | 5 +- Koha/Item/Transfer.pm | 27 +- Koha/Item/Transfer/Limit.pm | 1 - Koha/Item/Transfers.pm | 3 +- Koha/ItemTypes.pm | 9 +- Koha/Items.pm | 313 +- Koha/KeyboardShortcut.pm | 1 - Koha/KeyboardShortcuts.pm | 1 - Koha/Language.pm | 4 +- Koha/Libraries.pm | 7 +- Koha/Library.pm | 104 +- Koha/Library/Group.pm | 24 +- Koha/Library/Groups.pm | 5 +- Koha/Library/OverDriveInfo.pm | 1 - Koha/Library/OverDriveInfos.pm | 1 - Koha/List/Patron.pm | 35 +- Koha/Localization.pm | 8 +- Koha/Logger.pm | 42 +- Koha/Manual.pm | 54 +- Koha/MarcOverlayRules.pm | 171 +- Koha/MarcSubfieldStructure.pm | 1 - Koha/MarcSubfieldStructures.pm | 1 - Koha/MetaSearcher.pm | 185 +- Koha/MetadataRecord.pm | 11 +- Koha/MetadataRecord/Authority.pm | 95 +- Koha/Middleware/RealIP.pm | 16 +- Koha/Middleware/SetEnv.pm | 3 +- Koha/Misc/Files.pm | 8 +- Koha/MoreUtils.pm | 2 +- Koha/Notice/Messages.pm | 1 - Koha/Notice/Templates.pm | 7 +- Koha/Notice/Util.pm | 42 +- Koha/Number/Price.pm | 26 +- Koha/OAI/Server/DeletedRecord.pm | 14 +- Koha/OAI/Server/Description.pm | 14 +- Koha/OAI/Server/GetRecord.pm | 46 +- Koha/OAI/Server/Identify.pm | 25 +- Koha/OAI/Server/ListBase.pm | 85 +- Koha/OAI/Server/ListIdentifiers.pm | 4 +- Koha/OAI/Server/ListMetadataFormats.pm | 60 +- Koha/OAI/Server/ListRecords.pm | 4 +- Koha/OAI/Server/ListSets.pm | 20 +- Koha/OAI/Server/Record.pm | 45 +- Koha/OAI/Server/Repository.pm | 70 +- Koha/OAI/Server/ResumptionToken.pm | 58 +- Koha/OAIServer.pm | 1 - Koha/OAIServers.pm | 1 - Koha/OAuth.pm | 38 +- Koha/Object.pm | 202 +- Koha/Object/Limit/Library.pm | 36 +- Koha/Object/Message.pm | 2 +- Koha/Object/Mixin/AdditionalFields.pm | 36 +- Koha/Objects.pm | 94 +- Koha/Objects/Limit/Library.pm | 15 +- Koha/Objects/Mixin/AdditionalFields.pm | 6 +- Koha/Objects/Record/Collections.pm | 20 +- Koha/Old/Checkout.pm | 24 +- Koha/Old/Checkouts.pm | 26 +- Koha/Old/Holds.pm | 2 +- Koha/Patron.pm | 615 +- Koha/Patron/Attribute/Type.pm | 12 +- Koha/Patron/Attributes.pm | 40 +- Koha/Patron/Category.pm | 36 +- Koha/Patron/Debarments.pm | 30 +- Koha/Patron/Discharge.pm | 97 +- Koha/Patron/Files.pm | 7 +- Koha/Patron/HouseboundProfile.pm | 5 +- Koha/Patron/HouseboundVisit.pm | 8 +- Koha/Patron/HouseboundVisits.pm | 16 +- Koha/Patron/Image.pm | 1 - Koha/Patron/Images.pm | 1 - Koha/Patron/Message.pm | 16 +- Koha/Patron/MessagePreference.pm | 282 +- Koha/Patron/MessagePreferences.pm | 52 +- Koha/Patron/Messages.pm | 3 +- Koha/Patron/Modification.pm | 49 +- Koha/Patron/Modifications.pm | 27 +- Koha/Patron/Password/Recovery.pm | 71 +- Koha/Patron/Relationship.pm | 17 +- Koha/Patron/Relationships.pm | 7 +- Koha/Patron/Restriction.pm | 1 + Koha/Patron/Restriction/Type.pm | 10 +- Koha/Patrons.pm | 226 +- Koha/Patrons/Import.pm | 476 +- Koha/Plugins.pm | 62 +- Koha/Plugins/Base.pm | 43 +- Koha/Plugins/Handler.pm | 36 +- Koha/Plugins/Method.pm | 1 - Koha/Plugins/Methods.pm | 1 - Koha/Plugins/Tab.pm | 11 +- Koha/Preservation/Processing/Attributes.pm | 1 - Koha/Preservation/Train/Item.pm | 1 - Koha/ProblemReport.pm | 4 +- Koha/PseudonymizedTransaction.pm | 18 +- Koha/PseudonymizedTransactions.pm | 1 - Koha/Quotes.pm | 33 +- Koha/REST/Plugin/Auth/IdP.pm | 14 +- Koha/REST/Plugin/Exceptions.pm | 4 +- Koha/REST/Plugin/Objects.pm | 46 +- Koha/REST/Plugin/Pagination.pm | 39 +- Koha/REST/Plugin/PluginRoutes.pm | 51 +- Koha/REST/V1.pm | 39 +- Koha/REST/V1/Acquisitions/Funds.pm | 15 +- Koha/REST/V1/Acquisitions/Orders.pm | 39 +- Koha/REST/V1/Acquisitions/Vendors.pm | 13 +- Koha/REST/V1/AdvancedEditorMacro.pm | 136 +- Koha/REST/V1/ArticleRequests.pm | 2 +- Koha/REST/V1/Auth.pm | 322 +- .../REST/V1/Auth/Identity/Provider/Domains.pm | 2 +- Koha/REST/V1/Auth/Identity/Providers.pm | 24 +- Koha/REST/V1/Auth/Password.pm | 2 +- Koha/REST/V1/AuthorisedValueCategories.pm | 3 +- Koha/REST/V1/AuthorisedValues.pm | 2 +- Koha/REST/V1/Authorities.pm | 42 +- Koha/REST/V1/BackgroundJobs.pm | 12 +- Koha/REST/V1/Biblios.pm | 169 +- Koha/REST/V1/Biblios/ItemGroups.pm | 21 +- Koha/REST/V1/Biblios/ItemGroups/Items.pm | 33 +- Koha/REST/V1/CashRegisters/Cashups.pm | 6 +- Koha/REST/V1/Checkouts.pm | 79 +- Koha/REST/V1/CirculationRules.pm | 2 +- Koha/REST/V1/Cities.pm | 12 +- Koha/REST/V1/Clubs/Holds.pm | 38 +- Koha/REST/V1/Config/SMTP/Servers.pm | 14 +- Koha/REST/V1/ERM.pm | 14 +- Koha/REST/V1/ERM/Agreements.pm | 65 +- Koha/REST/V1/ERM/Documents.pm | 7 +- Koha/REST/V1/ERM/EHoldings/Packages.pm | 4 +- Koha/REST/V1/ERM/EHoldings/Packages/EBSCO.pm | 50 +- Koha/REST/V1/ERM/EHoldings/Packages/Local.pm | 58 +- Koha/REST/V1/ERM/EHoldings/Resources.pm | 2 +- Koha/REST/V1/ERM/EHoldings/Resources/EBSCO.pm | 93 +- Koha/REST/V1/ERM/EHoldings/Resources/Local.pm | 18 +- Koha/REST/V1/ERM/EHoldings/Titles.pm | 5 +- Koha/REST/V1/ERM/EHoldings/Titles/EBSCO.pm | 38 +- Koha/REST/V1/ERM/EHoldings/Titles/Local.pm | 64 +- Koha/REST/V1/ERM/EUsage/CounterFiles.pm | 2 +- Koha/REST/V1/ERM/EUsage/CounterLogs.pm | 2 +- Koha/REST/V1/ERM/EUsage/CounterRegistry.pm | 4 +- Koha/REST/V1/ERM/EUsage/UsageDataProviders.pm | 17 +- Koha/REST/V1/ERM/Licenses.pm | 62 +- Koha/REST/V1/Holds.pm | 133 +- Koha/REST/V1/ILL/Requests.pm | 41 +- Koha/REST/V1/ImportBatchProfiles.pm | 13 +- Koha/REST/V1/ImportRecordMatches.pm | 44 +- Koha/REST/V1/Items.pm | 79 +- Koha/REST/V1/Libraries.pm | 16 +- Koha/REST/V1/OAuth.pm | 27 +- Koha/REST/V1/OAuth/Client.pm | 32 +- Koha/REST/V1/Patrons.pm | 113 +- Koha/REST/V1/Patrons/Account.pm | 49 +- Koha/REST/V1/Patrons/Attributes.pm | 79 +- Koha/REST/V1/Patrons/Holds.pm | 5 +- Koha/REST/V1/Patrons/Password.pm | 22 +- Koha/REST/V1/Patrons/Password/Expiration.pm | 9 +- Koha/REST/V1/Quotes.pm | 15 +- Koha/REST/V1/ReturnClaims.pm | 16 +- Koha/REST/V1/SearchFilter.pm | 11 +- Koha/REST/V1/Static.pm | 30 +- Koha/REST/V1/StockRotation/Stage.pm | 3 +- Koha/REST/V1/Suggestions.pm | 41 +- Koha/REST/V1/Tickets.pm | 43 +- Koha/REST/V1/TransferLimits.pm | 26 +- Koha/REST/V1/TwoFactorAuth.pm | 28 +- Koha/Rating.pm | 4 +- Koha/Ratings.pm | 3 +- Koha/Recall.pm | 153 +- Koha/Recalls.pm | 86 +- Koha/RecordProcessor.pm | 47 +- Koha/RecordProcessor/Base.pm | 15 +- Koha/Report.pm | 33 +- Koha/Reports.pm | 1 - Koha/Result/Boolean.pm | 14 +- Koha/Review.pm | 5 +- Koha/Reviews.pm | 4 +- Koha/SMS/Provider.pm | 3 +- Koha/SMS/Providers.pm | 1 - Koha/SMTP/Server.pm | 8 +- Koha/SMTP/Servers.pm | 25 +- Koha/Schema.pm | 3 +- Koha/Schema/Loader/mysql.pm | 2 +- Koha/Script.pm | 28 +- Koha/SearchEngine.pm | 1 + Koha/SearchEngine/Elasticsearch.pm | 668 +- Koha/SearchEngine/Elasticsearch/Browse.pm | 17 +- Koha/SearchEngine/Elasticsearch/Indexer.pm | 93 +- .../Elasticsearch/QueryBuilder.pm | 636 +- Koha/SearchEngine/Elasticsearch/Search.pm | 211 +- Koha/SearchEngine/Indexer.pm | 4 +- Koha/SearchEngine/QueryBuilder.pm | 4 +- Koha/SearchEngine/Search.pm | 40 +- Koha/SearchEngine/Zebra/Indexer.pm | 8 +- Koha/SearchEngine/Zebra/QueryBuilder.pm | 16 +- Koha/SearchEngine/Zebra/Search.pm | 20 +- Koha/SearchField.pm | 17 +- Koha/SearchFields.pm | 1 - Koha/SearchFilter.pm | 19 +- Koha/SearchFilters.pm | 1 - Koha/SearchMarcMap.pm | 3 +- Koha/SearchMarcMaps.pm | 1 - Koha/Serial.pm | 1 - Koha/Serial/Item.pm | 1 - Koha/Serial/Items.pm | 1 - Koha/Serials.pm | 1 - Koha/SharedContent.pm | 74 +- Koha/SimpleMARC.pm | 451 +- Koha/Sitemapper.pm | 18 +- Koha/Sitemapper/Writer.pm | 70 +- Koha/Statistic.pm | 2 +- Koha/Statistics.pm | 1 - Koha/StockRotationItem.pm | 108 +- Koha/StockRotationItems.pm | 32 +- Koha/StockRotationRota.pm | 43 +- Koha/StockRotationRotas.pm | 4 +- Koha/StockRotationStage.pm | 119 +- Koha/Subscription.pm | 54 +- Koha/Subscription/Frequencies.pm | 1 - Koha/Subscription/Frequency.pm | 1 - Koha/Subscription/Histories.pm | 1 - Koha/Subscription/History.pm | 1 - Koha/Subscription/Numberpatterns.pm | 22 +- Koha/Subscription/Routinglist.pm | 5 +- Koha/Subscription/Routinglists.pm | 1 - Koha/Subscriptions.pm | 1 - Koha/Suggestion.pm | 25 +- Koha/SuggestionEngine.pm | 25 +- Koha/SuggestionEngine/Plugin/AuthorityFile.pm | 8 +- Koha/SuggestionEngine/Plugin/ExplodedTerms.pm | 2 +- .../Plugin/LibrisSpellcheck.pm | 32 +- Koha/SuggestionEngine/Plugin/Null.pm | 2 +- Koha/Suggestions.pm | 7 +- Koha/Tag.pm | 1 - Koha/Tags.pm | 1 - Koha/Tags/Approval.pm | 1 - Koha/Tags/Approvals.pm | 1 - Koha/Tags/Index.pm | 1 - Koha/Tags/Indexes.pm | 1 - Koha/Template/Plugin/Asset.pm | 26 +- Koha/Template/Plugin/AudioAlerts.pm | 2 +- Koha/Template/Plugin/AuthClient.pm | 12 +- Koha/Template/Plugin/AuthorisedValues.pm | 22 +- Koha/Template/Plugin/Biblio.pm | 2 +- Koha/Template/Plugin/Branches.pm | 18 +- Koha/Template/Plugin/Categories.pm | 6 +- Koha/Template/Plugin/CirculationRules.pm | 9 +- Koha/Template/Plugin/ClassSources.pm | 8 +- Koha/Template/Plugin/Desks.pm | 14 +- Koha/Template/Plugin/Frameworks.pm | 1 - Koha/Template/Plugin/HtmlId.pm | 2 +- Koha/Template/Plugin/HtmlTags.pm | 2 +- Koha/Template/Plugin/I18N.pm | 34 +- Koha/Template/Plugin/ItemTypes.pm | 12 +- Koha/Template/Plugin/JSConsents.pm | 6 +- Koha/Template/Plugin/Koha.pm | 3 +- Koha/Template/Plugin/KohaDates.pm | 21 +- Koha/Template/Plugin/KohaPlugins.pm | 35 +- Koha/Template/Plugin/Languages.pm | 6 +- Koha/Template/Plugin/NoticeTemplates.pm | 1 + Koha/Template/Plugin/Price.pm | 4 +- Koha/Template/Plugin/Registers.pm | 21 +- Koha/Template/Plugin/TablesSettings.pm | 8 +- Koha/Template/Plugin/To.pm | 4 +- Koha/Token.pm | 99 +- Koha/TrackedLink.pm | 1 - Koha/TrackedLinks.pm | 1 - Koha/UI/Form/Builder/Biblio.pm | 247 +- Koha/UI/Form/Builder/Item.pm | 267 +- Koha/UI/Table/Builder/Items.pm | 26 +- Koha/UploadedFile.pm | 29 +- Koha/UploadedFiles.pm | 51 +- Koha/Uploader.pm | 145 +- Koha/Util/FrameworkPlugin.pm | 26 +- Koha/Util/MARC.pm | 102 +- Koha/Util/Navigation.pm | 16 +- Koha/Util/Normalize.pm | 44 +- Koha/Util/OpenDocument.pm | 10 +- Koha/Util/StockRotation.pm | 44 +- Koha/Virtualshelfcontent.pm | 1 - Koha/Virtualshelfcontents.pm | 1 - Koha/Virtualshelfshare.pm | 18 +- Koha/Virtualshelfshares.pm | 1 - Koha/Virtualshelves.pm | 72 +- Koha/XSLT/Base.pm | 96 +- Koha/XSLT/HTTPS.pm | 13 +- Koha/XSLT/Security.pm | 96 +- Koha/Z3950Responder.pm | 66 +- Koha/Z3950Responder/GenericSession.pm | 43 +- Koha/Z3950Responder/RPN.pm | 68 +- Koha/Z3950Responder/Session.pm | 59 +- Koha/Z3950Responder/ZebraSession.pm | 29 +- Koha/Z3950Server.pm | 1 - Koha/Z3950Servers.pm | 1 - Koha/pdfformat/layout2pages.pm | 272 +- Koha/pdfformat/layout2pagesde.pm | 271 +- Koha/pdfformat/layout3pages.pm | 557 +- Koha/pdfformat/layout3pagesfr.pm | 533 +- about.pl | 434 +- acqui/addorderiso2709.pl | 66 +- acqui/ajax-getauthvaluedropbox.pl | 18 +- acqui/basket.pl | 375 +- acqui/basketgroup.pl | 361 +- acqui/basketheader.pl | 102 +- acqui/booksellers.pl | 70 +- acqui/cancelorder.pl | 47 +- acqui/check_budget_total.pl | 20 +- acqui/check_uniqueness.pl | 14 +- acqui/duplicate_orders.pl | 59 +- acqui/edifactmsgs.pl | 12 +- acqui/edimsg.pl | 13 +- acqui/finishreceive.pl | 156 +- acqui/histsearch.pl | 32 +- acqui/invoice-files.pl | 50 +- acqui/invoice.pl | 195 +- acqui/invoices.pl | 28 +- acqui/lateorders-export.pl | 77 +- acqui/lateorders.pl | 63 +- acqui/moddeliverydate.pl | 55 +- acqui/modordernotes.pl | 62 +- acqui/neworderempty.pl | 291 +- acqui/newordersubscription.pl | 35 +- acqui/newordersuggestion.pl | 50 +- acqui/ordered.pl | 37 +- acqui/orderreceive.pl | 73 +- acqui/parcel.pl | 100 +- acqui/parcels.pl | 125 +- acqui/showorder.pl | 22 +- acqui/spent.pl | 49 +- acqui/supplier.pl | 55 +- acqui/transferorder.pl | 114 +- acqui/uncertainprice.pl | 95 +- acqui/vendor_issues.pl | 2 +- acqui/z3950_search.pl | 103 +- admin/additional-fields.pl | 46 +- admin/admin-home.pl | 4 +- admin/adveditorshortcuts.pl | 22 +- admin/aqbudgetperiods.pl | 171 +- admin/aqbudgets.pl | 208 +- admin/aqcontract.pl | 93 +- admin/aqplan.pl | 138 +- admin/audio_alerts.pl | 2 +- admin/auth_subfields_structure.pl | 247 +- admin/auth_tag_structure.pl | 275 +- admin/authorised_values.pl | 177 +- admin/authtypes.pl | 20 +- admin/background_jobs.pl | 31 +- admin/biblio_framework.pl | 20 +- admin/branch_transfer_limits.pl | 97 +- admin/branches.pl | 84 +- admin/cash_registers.pl | 54 +- admin/categories.pl | 59 +- admin/check_budget_parent.pl | 11 +- admin/check_parent_total.pl | 38 +- admin/checkmarc.pl | 230 +- admin/cities.pl | 28 +- admin/classsources.pl | 133 +- admin/clone-rules.pl | 35 +- admin/columns_settings.pl | 24 +- admin/credit_types.pl | 53 +- admin/curbside_pickup.pl | 28 +- admin/currency.pl | 37 +- admin/debit_types.pl | 55 +- admin/desks.pl | 30 +- admin/didyoumean.pl | 22 +- admin/edi_accounts.pl | 51 +- admin/edi_ean_accounts.pl | 22 +- admin/identity_providers.pl | 212 +- admin/import_export_authtype.pl | 69 +- admin/import_export_framework.pl | 65 +- admin/item_circulation_alerts.pl | 49 +- admin/items_search_field.pl | 26 +- admin/items_search_fields.pl | 30 +- admin/koha2marclinks.pl | 59 +- admin/library_groups.pl | 36 +- admin/localization.pl | 17 +- admin/marc-overlay-rules.pl | 58 +- admin/marc_subfields_structure.pl | 116 +- admin/marctagstructure.pl | 418 +- admin/matching-rules.pl | 206 +- admin/oai_set_mappings.pl | 47 +- admin/oai_sets.pl | 89 +- admin/overdrive.pl | 41 +- admin/patron-attr-types.pl | 129 +- admin/preferences.pl | 205 +- admin/restrictions.pl | 53 +- admin/search_filters.pl | 22 +- admin/searchengine/elasticsearch/mappings.pl | 84 +- admin/share_content.pl | 48 +- admin/smart-rules.pl | 279 +- admin/sms_providers.pl | 21 +- admin/smtp_servers.pl | 83 +- admin/sru_modmapping.pl | 24 +- admin/systempreferences.pl | 103 +- admin/transfer_limits.pl | 4 +- admin/transport-cost-matrix.pl | 68 +- admin/usage_statistics.pl | 49 +- admin/z3950servers.pl | 62 +- authorities/auth_finder.pl | 77 +- authorities/authorities-home.pl | 121 +- authorities/authorities.pl | 404 +- authorities/blinddetail-biblio-search.pl | 62 +- authorities/detail-biblio-search.pl | 113 +- authorities/detail.pl | 209 +- authorities/export.pl | 24 +- authorities/merge.pl | 86 +- authorities/merge_ajax.pl | 18 +- authorities/ysearch.pl | 89 +- basket/basket.pl | 72 +- basket/downloadcart.pl | 60 +- basket/sendbasket.pl | 17 +- bookings/list.pl | 2 +- catalogue/ISBDdetail.pl | 56 +- catalogue/MARCdetail.pl | 179 +- catalogue/detail.pl | 276 +- catalogue/export.pl | 137 +- catalogue/getitem-ajax.pl | 42 +- catalogue/image.pl | 21 +- catalogue/imageviewer.pl | 29 +- catalogue/issuehistory.pl | 33 +- catalogue/item-export.pl | 40 +- catalogue/itemsearch.pl | 158 +- catalogue/labeledMARCdetail.pl | 98 +- catalogue/moredetail.pl | 178 +- catalogue/search-history.pl | 72 +- catalogue/search.pl | 568 +- catalogue/showelastic.pl | 40 +- catalogue/showmarc.pl | 49 +- catalogue/stockrotation.pl | 83 +- catalogue/updateitem.pl | 67 +- cataloguing/addbiblio.pl | 571 +- cataloguing/addbooks.pl | 61 +- cataloguing/cataloging-home.pl | 14 +- cataloguing/concerns.pl | 10 +- cataloguing/editor.pl | 37 +- cataloguing/linkitem.pl | 45 +- cataloguing/merge.pl | 111 +- cataloguing/merge_ajax.pl | 16 +- cataloguing/moveitem.pl | 41 +- cataloguing/plugin_launcher.pl | 12 +- cataloguing/value_builder/EXAMPLE.pl | 27 +- cataloguing/value_builder/barcode.pl | 55 +- cataloguing/value_builder/barcode_manual.pl | 36 +- cataloguing/value_builder/callnumber-KU.pl | 64 +- cataloguing/value_builder/callnumber.pl | 61 +- cataloguing/value_builder/cn_browser.pl | 42 +- cataloguing/value_builder/dateaccessioned.pl | 6 +- cataloguing/value_builder/marc21_field_005.pl | 12 +- cataloguing/value_builder/marc21_field_006.pl | 55 +- cataloguing/value_builder/marc21_field_007.pl | 39 +- cataloguing/value_builder/marc21_field_008.pl | 62 +- .../marc21_field_008_authorities.pl | 56 +- .../marc21_field_008_classifications.pl | 50 +- .../value_builder/marc21_field_245h.pl | 7 +- .../value_builder/marc21_field_260b.pl | 6 +- cataloguing/value_builder/marc21_leader.pl | 19 +- .../marc21_leader_authorities.pl | 21 +- .../value_builder/marc21_linking_section.pl | 61 +- cataloguing/value_builder/marc21_orgcode.pl | 8 +- cataloguing/value_builder/stocknumber.pl | 21 +- cataloguing/value_builder/stocknumberAV.pl | 36 +- cataloguing/value_builder/stocknumberam123.pl | 44 +- .../value_builder/unimarc_field_009_ppn.pl | 42 +- .../value_builder/unimarc_field_010.pl | 90 +- .../value_builder/unimarc_field_100.pl | 44 +- .../unimarc_field_100_authorities.pl | 63 +- .../value_builder/unimarc_field_105.pl | 104 +- .../value_builder/unimarc_field_106.pl | 47 +- .../value_builder/unimarc_field_110.pl | 86 +- .../value_builder/unimarc_field_115a.pl | 68 +- .../value_builder/unimarc_field_115b.pl | 42 +- .../value_builder/unimarc_field_116.pl | 41 +- .../value_builder/unimarc_field_117.pl | 66 +- .../value_builder/unimarc_field_120.pl | 90 +- .../value_builder/unimarc_field_121a.pl | 77 +- .../value_builder/unimarc_field_121b.pl | 69 +- .../value_builder/unimarc_field_122.pl | 61 +- .../value_builder/unimarc_field_123a.pl | 45 +- .../value_builder/unimarc_field_123defg.pl | 57 +- .../value_builder/unimarc_field_123i.pl | 57 +- .../value_builder/unimarc_field_123j.pl | 57 +- .../value_builder/unimarc_field_124.pl | 57 +- .../value_builder/unimarc_field_124a.pl | 41 +- .../value_builder/unimarc_field_124b.pl | 45 +- .../value_builder/unimarc_field_124c.pl | 45 +- .../value_builder/unimarc_field_124d.pl | 45 +- .../value_builder/unimarc_field_124e.pl | 45 +- .../value_builder/unimarc_field_124f.pl | 45 +- .../value_builder/unimarc_field_124g.pl | 45 +- .../value_builder/unimarc_field_125.pl | 57 +- .../value_builder/unimarc_field_125a.pl | 47 +- .../value_builder/unimarc_field_125b.pl | 48 +- .../value_builder/unimarc_field_126.pl | 57 +- .../value_builder/unimarc_field_126a.pl | 110 +- .../value_builder/unimarc_field_126b.pl | 54 +- .../value_builder/unimarc_field_127.pl | 53 +- .../value_builder/unimarc_field_128a.pl | 45 +- .../value_builder/unimarc_field_128b.pl | 48 +- .../value_builder/unimarc_field_128c.pl | 45 +- .../value_builder/unimarc_field_130.pl | 82 +- .../value_builder/unimarc_field_135a.pl | 81 +- .../value_builder/unimarc_field_140.pl | 147 +- .../value_builder/unimarc_field_141.pl | 74 +- .../value_builder/unimarc_field_146a.pl | 24 +- .../value_builder/unimarc_field_146b.pl | 109 +- .../value_builder/unimarc_field_146c.pl | 111 +- .../value_builder/unimarc_field_146d.pl | 72 +- .../value_builder/unimarc_field_146e.pl | 111 +- .../value_builder/unimarc_field_146f.pl | 107 +- .../value_builder/unimarc_field_146h.pl | 32 +- .../value_builder/unimarc_field_146i.pl | 32 +- .../value_builder/unimarc_field_181-2.pl | 30 +- .../value_builder/unimarc_field_181a.pl | 32 +- .../value_builder/unimarc_field_181b.pl | 32 +- .../value_builder/unimarc_field_181c.pl | 31 +- .../value_builder/unimarc_field_182-2.pl | 29 +- .../value_builder/unimarc_field_182a.pl | 32 +- .../value_builder/unimarc_field_182c.pl | 30 +- .../value_builder/unimarc_field_183-2.pl | 28 +- .../value_builder/unimarc_field_183a.pl | 28 +- .../value_builder/unimarc_field_210c.pl | 149 +- .../value_builder/unimarc_field_210c_bis.pl | 25 +- .../value_builder/unimarc_field_225a.pl | 71 +- .../value_builder/unimarc_field_225a_bis.pl | 20 +- .../value_builder/unimarc_field_283-2.pl | 28 +- .../value_builder/unimarc_field_283a.pl | 30 +- .../value_builder/unimarc_field_325h.pl | 34 +- .../value_builder/unimarc_field_325j.pl | 38 +- .../value_builder/unimarc_field_4XX.pl | 300 +- .../value_builder/unimarc_field_686a.pl | 43 +- cataloguing/value_builder/unimarc_leader.pl | 32 +- .../unimarc_leader_authorities.pl | 28 +- cataloguing/value_builder/upload.pl | 4 +- cataloguing/ysearch.pl | 10 +- cataloguing/z3950_auth_search.pl | 129 +- cataloguing/z3950_search.pl | 132 +- changelanguage.pl | 4 +- circ/article-request-slip.pl | 16 +- circ/article-requests.pl | 13 +- circ/bookcount.pl | 74 +- circ/branchoverdues.pl | 42 +- circ/branchtransfers.pl | 177 +- circ/checkout-notes.pl | 25 +- circ/circulation-home.pl | 18 +- circ/curbside_pickups.pl | 74 +- circ/del_message.pl | 19 +- circ/hold-transfer-slip.pl | 32 +- circ/on-site_checkouts.pl | 14 +- circ/pendingreserves.pl | 166 +- circ/renew.pl | 55 +- circ/request-article.pl | 44 +- circ/reserveratios.pl | 97 +- circ/returns.pl | 368 +- circ/set-library.pl | 40 +- circ/transfer-slip.pl | 32 +- circ/transfers_to_send.pl | 2 +- circ/transferstoreceive.pl | 55 +- circ/view_holdsqueue.pl | 21 +- circ/waitingreserves.pl | 81 +- clubs/club-enrollments.pl | 20 +- clubs/clubs-add-modify.pl | 32 +- clubs/clubs.pl | 18 +- clubs/patron-clubs-tab.pl | 10 +- clubs/patron-enroll.pl | 13 +- clubs/templates-add-modify.pl | 43 +- course_reserves/add_items.pl | 91 +- course_reserves/batch_add_items.pl | 53 +- course_reserves/batch_rm_items.pl | 49 +- course_reserves/course-reserves.pl | 10 +- course_reserves/course.pl | 13 +- docs/CAS/CASProxy/examples/koha_webservice.pl | 8 +- docs/CAS/CASProxy/examples/proxy_cas.pl | 41 +- .../CASProxy/examples/proxy_cas_callback.pl | 16 +- docs/CAS/CASProxy/examples/proxy_cas_data.pl | 46 +- erm/erm.pl | 6 +- errors/400.pl | 7 +- errors/401.pl | 7 +- errors/402.pl | 8 +- errors/403.pl | 12 +- errors/404.pl | 7 +- errors/500.pl | 8 +- gulpfile.js | 499 +- help.pl | 8 +- ill/ill-requests.pl | 330 +- installer/data/mysql/backfill_statistics.pl | 99 +- installer/data/mysql/db_revs/210600000.pl | 8 +- installer/data/mysql/db_revs/210600001.pl | 6 +- installer/data/mysql/db_revs/210600002.pl | 30 +- installer/data/mysql/db_revs/210600003.pl | 6 +- installer/data/mysql/db_revs/210600004.pl | 18 +- installer/data/mysql/db_revs/210600005.pl | 12 +- installer/data/mysql/db_revs/210600006.pl | 22 +- installer/data/mysql/db_revs/210600007.pl | 24 +- installer/data/mysql/db_revs/210600008.pl | 12 +- installer/data/mysql/db_revs/210600009.pl | 22 +- installer/data/mysql/db_revs/210600010.pl | 12 +- installer/data/mysql/db_revs/210600011.pl | 53 +- installer/data/mysql/db_revs/210600012.pl | 72 +- installer/data/mysql/db_revs/210600013.pl | 20 +- installer/data/mysql/db_revs/210600014.pl | 22 +- installer/data/mysql/db_revs/210600015.pl | 10 +- installer/data/mysql/db_revs/210600016.pl | 125 +- installer/data/mysql/db_revs/210600017.pl | 16 +- installer/data/mysql/db_revs/210600018.pl | 37 +- installer/data/mysql/db_revs/210600019.pl | 14 +- installer/data/mysql/db_revs/210600020.pl | 25 +- installer/data/mysql/db_revs/210600021.pl | 14 +- installer/data/mysql/db_revs/210600022.pl | 24 +- installer/data/mysql/db_revs/210600023.pl | 22 +- installer/data/mysql/db_revs/210600024.pl | 14 +- installer/data/mysql/db_revs/210600025.pl | 14 +- installer/data/mysql/db_revs/210600026.pl | 20 +- installer/data/mysql/db_revs/210600027.pl | 14 +- installer/data/mysql/db_revs/210600028.pl | 42 +- installer/data/mysql/db_revs/210600029.pl | 32 +- installer/data/mysql/db_revs/210600030.pl | 14 +- installer/data/mysql/db_revs/210600031.pl | 12 +- installer/data/mysql/db_revs/210600032.pl | 14 +- installer/data/mysql/db_revs/210600033.pl | 16 +- installer/data/mysql/db_revs/210600034.pl | 14 +- installer/data/mysql/db_revs/210600035.pl | 40 +- installer/data/mysql/db_revs/210600036.pl | 8 +- installer/data/mysql/db_revs/210600037.pl | 20 +- installer/data/mysql/db_revs/210600038.pl | 26 +- installer/data/mysql/db_revs/210600039.pl | 31 +- installer/data/mysql/db_revs/210600040.pl | 14 +- installer/data/mysql/db_revs/210600041.pl | 16 +- installer/data/mysql/db_revs/210600042.pl | 29 +- installer/data/mysql/db_revs/210600043.pl | 14 +- installer/data/mysql/db_revs/210600044.pl | 14 +- installer/data/mysql/db_revs/210600045.pl | 22 +- installer/data/mysql/db_revs/210600046.pl | 22 +- installer/data/mysql/db_revs/210600047.pl | 38 +- installer/data/mysql/db_revs/210600048.pl | 19 +- installer/data/mysql/db_revs/210600049.pl | 8 +- installer/data/mysql/db_revs/211100000.pl | 6 +- installer/data/mysql/db_revs/211200000.pl | 8 +- installer/data/mysql/db_revs/211200001.pl | 20 +- installer/data/mysql/db_revs/211200002.pl | 20 +- installer/data/mysql/db_revs/211200003.pl | 11 +- installer/data/mysql/db_revs/211200004.pl | 12 +- installer/data/mysql/db_revs/211200005.pl | 17 +- installer/data/mysql/db_revs/211200006.pl | 16 +- installer/data/mysql/db_revs/211200007.pl | 14 +- installer/data/mysql/db_revs/211200008.pl | 12 +- installer/data/mysql/db_revs/211200009.pl | 12 +- installer/data/mysql/db_revs/211200010.pl | 22 +- installer/data/mysql/db_revs/211200012.pl | 29 +- installer/data/mysql/db_revs/211200013.pl | 61 +- installer/data/mysql/db_revs/211200014.pl | 52 +- installer/data/mysql/db_revs/211200015.pl | 12 +- installer/data/mysql/db_revs/211200016.pl | 45 +- installer/data/mysql/db_revs/211200017.pl | 13 +- installer/data/mysql/db_revs/211200018.pl | 50 +- installer/data/mysql/db_revs/211200019.pl | 9 +- installer/data/mysql/db_revs/211200020.pl | 28 +- installer/data/mysql/db_revs/211200021.pl | 12 +- installer/data/mysql/db_revs/211200022.pl | 13 +- installer/data/mysql/db_revs/211200023.pl | 13 +- installer/data/mysql/db_revs/211200024.pl | 13 +- installer/data/mysql/db_revs/211200025.pl | 10 +- installer/data/mysql/db_revs/211200026.pl | 10 +- installer/data/mysql/db_revs/211200027.pl | 18 +- installer/data/mysql/db_revs/211200028.pl | 12 +- installer/data/mysql/db_revs/211200029.pl | 20 +- installer/data/mysql/db_revs/211200030.pl | 12 +- installer/data/mysql/db_revs/211200031.pl | 13 +- installer/data/mysql/db_revs/211200032.pl | 10 +- installer/data/mysql/db_revs/211200033.pl | 18 +- installer/data/mysql/db_revs/211200034.pl | 19 +- installer/data/mysql/db_revs/211200035.pl | 12 +- installer/data/mysql/db_revs/211200036.pl | 44 +- installer/data/mysql/db_revs/211200037.pl | 40 +- installer/data/mysql/db_revs/211200038.pl | 26 +- installer/data/mysql/db_revs/211200039.pl | 12 +- installer/data/mysql/db_revs/211200040.pl | 21 +- installer/data/mysql/db_revs/211200041.pl | 40 +- installer/data/mysql/db_revs/211200042.pl | 13 +- installer/data/mysql/db_revs/211200043.pl | 12 +- installer/data/mysql/db_revs/211200044.pl | 12 +- installer/data/mysql/db_revs/211200045.pl | 12 +- installer/data/mysql/db_revs/211200046.pl | 14 +- installer/data/mysql/db_revs/211200047.pl | 13 +- installer/data/mysql/db_revs/211200048.pl | 8 +- installer/data/mysql/db_revs/211200049.pl | 12 +- installer/data/mysql/db_revs/211200050.pl | 30 +- installer/data/mysql/db_revs/211200051.pl | 12 +- installer/data/mysql/db_revs/211200052.pl | 12 +- installer/data/mysql/db_revs/211200053.pl | 13 +- installer/data/mysql/db_revs/211200054.pl | 14 +- installer/data/mysql/db_revs/211200055.pl | 14 +- installer/data/mysql/db_revs/211200056.pl | 10 +- installer/data/mysql/db_revs/211200057.pl | 12 +- installer/data/mysql/db_revs/220500000.pl | 6 +- installer/data/mysql/db_revs/220600000.pl | 8 +- installer/data/mysql/db_revs/220600001.pl | 12 +- installer/data/mysql/db_revs/220600002.pl | 10 +- installer/data/mysql/db_revs/220600003.pl | 10 +- installer/data/mysql/db_revs/220600004.pl | 16 +- installer/data/mysql/db_revs/220600005.pl | 10 +- installer/data/mysql/db_revs/220600006.pl | 60 +- installer/data/mysql/db_revs/220600007.pl | 11 +- installer/data/mysql/db_revs/220600008.pl | 12 +- installer/data/mysql/db_revs/220600009.pl | 14 +- installer/data/mysql/db_revs/220600010.pl | 6 +- installer/data/mysql/db_revs/220600011.pl | 22 +- installer/data/mysql/db_revs/220600012.pl | 30 +- installer/data/mysql/db_revs/220600013.pl | 12 +- installer/data/mysql/db_revs/220600014.pl | 30 +- installer/data/mysql/db_revs/220600015.pl | 30 +- installer/data/mysql/db_revs/220600016.pl | 14 +- installer/data/mysql/db_revs/220600017.pl | 12 +- installer/data/mysql/db_revs/220600018.pl | 12 +- installer/data/mysql/db_revs/220600019.pl | 18 +- installer/data/mysql/db_revs/220600020.pl | 45 +- installer/data/mysql/db_revs/220600021.pl | 12 +- installer/data/mysql/db_revs/220600022.pl | 60 +- installer/data/mysql/db_revs/220600023.pl | 29 +- installer/data/mysql/db_revs/220600025.pl | 18 +- installer/data/mysql/db_revs/220600026.pl | 14 +- installer/data/mysql/db_revs/220600027.pl | 12 +- installer/data/mysql/db_revs/220600028.pl | 12 +- installer/data/mysql/db_revs/220600029.pl | 22 +- installer/data/mysql/db_revs/220600030.pl | 10 +- installer/data/mysql/db_revs/220600031.pl | 12 +- installer/data/mysql/db_revs/220600032.pl | 12 +- installer/data/mysql/db_revs/220600033.pl | 12 +- installer/data/mysql/db_revs/220600034.pl | 12 +- installer/data/mysql/db_revs/220600035.pl | 12 +- installer/data/mysql/db_revs/220600036.pl | 20 +- installer/data/mysql/db_revs/220600037.pl | 40 +- installer/data/mysql/db_revs/220600038.pl | 18 +- installer/data/mysql/db_revs/220600039.pl | 12 +- installer/data/mysql/db_revs/220600040.pl | 13 +- installer/data/mysql/db_revs/220600041.pl | 40 +- installer/data/mysql/db_revs/220600042.pl | 10 +- installer/data/mysql/db_revs/220600043.pl | 14 +- installer/data/mysql/db_revs/220600044.pl | 14 +- installer/data/mysql/db_revs/220600045.pl | 16 +- installer/data/mysql/db_revs/220600046.pl | 10 +- installer/data/mysql/db_revs/220600047.pl | 13 +- installer/data/mysql/db_revs/220600048.pl | 18 +- installer/data/mysql/db_revs/220600049.pl | 20 +- installer/data/mysql/db_revs/220600050.pl | 16 +- installer/data/mysql/db_revs/220600051.pl | 14 +- installer/data/mysql/db_revs/220600052.pl | 10 +- installer/data/mysql/db_revs/220600053.pl | 31 +- installer/data/mysql/db_revs/220600054.pl | 17 +- installer/data/mysql/db_revs/220600055.pl | 12 +- installer/data/mysql/db_revs/220600056.pl | 26 +- installer/data/mysql/db_revs/220600057.pl | 12 +- installer/data/mysql/db_revs/220600058.pl | 12 +- installer/data/mysql/db_revs/220600059.pl | 18 +- installer/data/mysql/db_revs/220600060.pl | 32 +- installer/data/mysql/db_revs/220600061.pl | 10 +- installer/data/mysql/db_revs/220600062.pl | 82 +- installer/data/mysql/db_revs/220600063.pl | 8 +- installer/data/mysql/db_revs/220600064.pl | 28 +- installer/data/mysql/db_revs/220600065.pl | 12 +- installer/data/mysql/db_revs/220600066.pl | 12 +- installer/data/mysql/db_revs/220600067.pl | 28 +- installer/data/mysql/db_revs/220600068.pl | 12 +- installer/data/mysql/db_revs/220600069.pl | 159 +- installer/data/mysql/db_revs/220600070.pl | 14 +- installer/data/mysql/db_revs/220600071.pl | 10 +- installer/data/mysql/db_revs/220600072.pl | 83 +- installer/data/mysql/db_revs/220600073.pl | 12 +- installer/data/mysql/db_revs/220600074.pl | 10 +- installer/data/mysql/db_revs/220600075.pl | 10 +- installer/data/mysql/db_revs/220600076.pl | 12 +- installer/data/mysql/db_revs/220600077.pl | 12 +- installer/data/mysql/db_revs/220600078.pl | 22 +- installer/data/mysql/db_revs/220600079.pl | 152 +- installer/data/mysql/db_revs/220600080.pl | 10 +- installer/data/mysql/db_revs/220600081.pl | 26 +- installer/data/mysql/db_revs/220600082.pl | 12 +- installer/data/mysql/db_revs/220600083.pl | 20 +- installer/data/mysql/db_revs/220600084.pl | 20 +- installer/data/mysql/db_revs/220600085.pl | 14 +- installer/data/mysql/db_revs/221100000.pl | 6 +- installer/data/mysql/db_revs/221200000.pl | 8 +- installer/data/mysql/db_revs/221200001.pl | 30 +- installer/data/mysql/db_revs/221200002.pl | 6 +- installer/data/mysql/db_revs/221200003.pl | 26 +- installer/data/mysql/db_revs/221200004.pl | 18 +- installer/data/mysql/db_revs/221200005.pl | 10 +- installer/data/mysql/db_revs/221200006.pl | 12 +- installer/data/mysql/db_revs/221200007.pl | 22 +- installer/data/mysql/db_revs/221200008.pl | 9 +- installer/data/mysql/db_revs/221200009.pl | 14 +- installer/data/mysql/db_revs/221200010.pl | 38 +- installer/data/mysql/db_revs/221200011.pl | 22 +- installer/data/mysql/db_revs/221200012.pl | 20 +- installer/data/mysql/db_revs/221200013.pl | 14 +- installer/data/mysql/db_revs/221200014.pl | 12 +- installer/data/mysql/db_revs/221200015.pl | 12 +- installer/data/mysql/db_revs/221200016.pl | 10 +- installer/data/mysql/db_revs/221200017.pl | 12 +- installer/data/mysql/db_revs/221200018.pl | 11 +- installer/data/mysql/db_revs/221200019.pl | 24 +- installer/data/mysql/db_revs/221200020.pl | 12 +- installer/data/mysql/db_revs/221200021.pl | 12 +- installer/data/mysql/db_revs/221200022.pl | 16 +- installer/data/mysql/db_revs/221200023.pl | 33 +- installer/data/mysql/db_revs/221200024.pl | 307 +- installer/data/mysql/db_revs/221200025.pl | 12 +- installer/data/mysql/db_revs/221200026.pl | 22 +- installer/data/mysql/db_revs/221200027.pl | 6 +- installer/data/mysql/db_revs/221200028.pl | 24 +- installer/data/mysql/db_revs/221200029.pl | 6 +- installer/data/mysql/db_revs/221200030.pl | 18 +- installer/data/mysql/db_revs/221200031.pl | 6 +- installer/data/mysql/db_revs/221200032.pl | 16 +- installer/data/mysql/db_revs/221200033.pl | 19 +- installer/data/mysql/db_revs/221200034.pl | 12 +- installer/data/mysql/db_revs/221200035.pl | 12 +- installer/data/mysql/db_revs/221200036.pl | 12 +- installer/data/mysql/db_revs/221200037.pl | 18 +- installer/data/mysql/db_revs/221200038.pl | 7 +- installer/data/mysql/db_revs/221200039.pl | 12 +- installer/data/mysql/db_revs/221200040.pl | 7 +- installer/data/mysql/db_revs/221200041.pl | 10 +- installer/data/mysql/db_revs/221200042.pl | 16 +- installer/data/mysql/db_revs/221200043.pl | 12 +- installer/data/mysql/db_revs/221200044.pl | 12 +- installer/data/mysql/db_revs/221200045.pl | 33 +- installer/data/mysql/db_revs/221200046.pl | 10 +- installer/data/mysql/db_revs/221200047.pl | 53 +- installer/data/mysql/db_revs/221200048.pl | 12 +- installer/data/mysql/db_revs/230500000.pl | 6 +- installer/data/mysql/db_revs/230600000.pl | 8 +- installer/data/mysql/db_revs/230600001.pl | 15 +- installer/data/mysql/db_revs/230600002.pl | 45 +- installer/data/mysql/db_revs/230600003.pl | 10 +- installer/data/mysql/db_revs/230600004.pl | 13 +- installer/data/mysql/db_revs/230600005.pl | 12 +- installer/data/mysql/db_revs/230600006.pl | 9 +- installer/data/mysql/db_revs/230600008.pl | 14 +- installer/data/mysql/db_revs/230600014.pl | 12 +- installer/data/mysql/db_revs/230600015.pl | 6 +- installer/data/mysql/db_revs/230600017.pl | 10 +- installer/data/mysql/db_revs/230600024.pl | 4 +- installer/data/mysql/db_revs/230600029.pl | 9 +- installer/data/mysql/db_revs/230600038.pl | 60 +- installer/data/mysql/db_revs/231100000.pl | 6 +- installer/data/mysql/db_revs/231200020.pl | 3 +- installer/data/mysql/db_revs/231200036.pl | 2 +- installer/data/mysql/db_revs/231200059.pl | 4 +- installer/data/mysql/db_revs/240500000.pl | 6 +- installer/data/mysql/db_revs/240600014.pl | 8 +- installer/data/mysql/db_revs/240600029.pl | 2 +- installer/data/mysql/db_revs/240600040.pl | 2 +- installer/data/mysql/db_revs/240600044.pl | 10 +- installer/data/mysql/db_revs/240600050.pl | 4 +- installer/data/mysql/db_revs/240600062.pl | 10 +- installer/data/mysql/db_revs/240600064.pl | 6 +- installer/data/mysql/db_revs/241100000.pl | 6 +- installer/data/mysql/db_revs/241200001.pl | 4 +- ...fix_unclosed_nonaccruing_fines_bug17135.pl | 119 +- installer/data/mysql/labels_upgrade.pl | 128 +- installer/data/mysql/patroncards_upgrade.pl | 80 +- installer/data/mysql/update22to30.pl | 6643 +++--- installer/data/mysql/updatedatabase.pl | 19666 ++++++++++------ installer/install.pl | 299 +- installer/onboarding.pl | 123 +- koha-tmpl/intranet-tmpl/js/coce.js | 38 +- koha-tmpl/intranet-tmpl/js/i18n.js | 50 +- .../prog/en/includes/about-team.inc | 533 +- .../prog/en/includes/accounts.inc | 117 +- .../includes/acquisitions-add-to-basket.inc | 39 +- .../prog/en/includes/acquisitions-search.inc | 1 - .../prog/en/includes/acquisitions-toolbar.inc | 56 +- .../prog/en/includes/action-logs.inc | 263 +- .../en/includes/additional-fields-display.inc | 40 +- .../en/includes/additional-fields-entry.inc | 193 +- .../prog/en/includes/admin-icon-selection.inc | 16 +- .../admin-items-search-field-form.inc | 2 +- .../prog/en/includes/admin-menu.inc | 359 +- .../prog/en/includes/auth-finder-search.inc | 367 +- .../includes/authorities-search-results.inc | 233 +- .../prog/en/includes/authorities-search.inc | 1 - .../prog/en/includes/authorities-toolbar.inc | 14 +- .../prog/en/includes/authorities.inc | 16 +- .../prog/en/includes/authorities_js.inc | 138 +- .../prog/en/includes/av-build-dropbox.inc | 32 +- .../batch_authority_record_deletion.inc | 12 +- .../batch_authority_record_modification.inc | 6 +- .../batch_biblio_record_deletion.inc | 12 +- .../batch_biblio_record_modification.inc | 2 +- .../background_jobs/batch_hold_cancel.inc | 13 +- .../batch_item_record_deletion.inc | 33 +- .../batch_item_record_modification.inc | 3 +- .../create_eholdings_from_biblios.inc | 12 +- .../background_jobs/erm_sushi_harvester.inc | 53 +- .../import_from_kbart_file.inc | 5 +- .../pseudonymize_statistic.inc | 16 +- .../background_jobs/stage_marc_for_import.inc | 13 +- .../background_jobs/update_elastic_index.inc | 15 +- .../update_holds_queue_for_biblios.inc | 5 +- .../prog/en/includes/biblio-title-head.inc | 3 +- .../prog/en/includes/biblio-title.inc | 49 +- .../prog/en/includes/biblio-view-menu.inc | 74 +- .../prog/en/includes/blocked-fines.inc | 6 +- .../prog/en/includes/blocking_errors.inc | 6 +- .../prog/en/includes/branch-selector.inc | 30 +- .../prog/en/includes/budget_planning.inc | 16 +- .../prog/en/includes/budgets-admin-search.inc | 3 +- .../en/includes/budgets-admin-toolbar.inc | 102 +- .../prog/en/includes/calendar.inc | 528 +- .../prog/en/includes/cat-menu.inc | 212 +- .../prog/en/includes/cat-toolbar.inc | 462 +- .../prog/en/includes/cataloging-search.inc | 26 +- .../prog/en/includes/catalogue-search-box.inc | 3 +- .../catalogue/itemsearch_item.csv.inc | 51 +- .../catalogue/itemsearch_item.json.inc | 58 +- .../prog/en/includes/cateditor-ui.inc | 2595 +- .../en/includes/cateditor-widgets-marc21.inc | 466 +- .../intranet-tmpl/prog/en/includes/chart.inc | 6 +- .../prog/en/includes/checkin-search-box.inc | 2 +- .../en/includes/checkouts-table-footer.inc | 12 +- .../prog/en/includes/checkouts-table.inc | 25 +- .../prog/en/includes/circ-menu.inc | 103 +- .../prog/en/includes/circ-nav.inc | 245 +- .../prog/en/includes/circ-search.inc | 1 - .../prog/en/includes/cities-admin-search.inc | 1 - .../prog/en/includes/clubs-table.inc | 31 +- .../prog/en/includes/columns_settings.inc | 581 +- .../en/includes/contracts-admin-search.inc | 2 +- .../prog/en/includes/country-list.inc | 219 +- .../en/includes/currencies-admin-search.inc | 1 - .../prog/en/includes/delimiter_text.inc | 18 +- .../prog/en/includes/desks-admin-search.inc | 24 +- .../prog/en/includes/doc-head-close.inc | 24 +- .../prog/en/includes/doc-head-open.inc | 4 +- .../intranet-tmpl/prog/en/includes/facets.inc | 34 +- .../prog/en/includes/filter-orders.inc | 59 +- .../prog/en/includes/format_price.inc | 1 - .../prog/en/includes/guided-reports-view.inc | 41 +- .../intranet-tmpl/prog/en/includes/header.inc | 45 +- .../prog/en/includes/holds_table.inc | 224 +- .../en/includes/html-customization-help.inc | 130 +- .../prog/en/includes/html_helpers.inc | 531 +- .../tables/items/catalogue_detail.inc | 1622 +- .../en/includes/ill-availability-table.inc | 3 +- .../en/includes/ill-batch-modal-strings.inc | 22 +- .../prog/en/includes/ill-batch-modal.inc | 16 +- .../prog/en/includes/ill-batch.inc | 43 +- .../prog/en/includes/ill-filter.inc | 8 +- .../prog/en/includes/ill-list-table.inc | 17 +- .../prog/en/includes/ill-request-log.inc | 2 +- .../prog/en/includes/ill-toolbar.inc | 66 +- .../en/includes/installer-doc-head-close.inc | 8 +- .../en/includes/installer-intranet-bottom.inc | 44 +- .../prog/en/includes/installer-strings.inc | 10 +- .../prog/en/includes/intranet-bottom.inc | 46 +- .../prog/en/includes/item-status.inc | 21 +- .../prog/en/includes/job_progress.inc | 3 +- .../prog/en/includes/js-biblio-format.inc | 55 +- .../prog/en/includes/js-date-format.inc | 1 - .../prog/en/includes/js-patron-format.inc | 75 +- .../prog/en/includes/js_includes.inc | 37 +- .../prog/en/includes/keyboard_shortcuts.inc | 48 +- .../prog/en/includes/langmenu-staff-top.inc | 71 +- .../prog/en/includes/last-borrower.inc | 5 +- .../prog/en/includes/letters-search.inc | 2 +- .../prog/en/includes/main-container.inc | 54 +- .../en/includes/mana/mana-comment-status.inc | 8 +- .../mana/mana-report-search-result.inc | 107 +- .../en/includes/mana/mana-share-report.inc | 26 +- .../mana/mana-subscription-search-result.inc | 31 +- .../en/includes/member-alt-address-style.inc | 14 +- .../en/includes/member-alt-contact-style.inc | 4 +- .../includes/member-display-address-style.inc | 33 +- .../member-display-alt-address-style.inc | 17 +- .../en/includes/member-main-address-style.inc | 8 +- .../prog/en/includes/member-search-box.inc | 16 +- .../en/includes/members-patron-selections.inc | 3 +- .../prog/en/includes/members-toolbar.inc | 43 +- .../prog/en/includes/merge-record.inc | 70 +- .../en/includes/messaging-preference-form.inc | 548 +- .../prog/en/includes/modal-claims.inc | 122 +- .../includes/modals/add_catalog_concern.inc | 29 +- .../en/includes/modals/bundle_contents.inc | 30 +- .../en/includes/modals/cancel_booking.inc | 24 +- .../en/includes/modals/cashup_summary.inc | 21 +- .../includes/modals/cataloguing_create_av.inc | 9 +- .../en/includes/modals/checkout_renewals.inc | 18 +- .../en/includes/modals/display_ticket.inc | 91 +- .../modals/edit_authority_preview.inc | 9 +- .../prog/en/includes/modals/place_booking.inc | 34 +- .../includes/modals/resolve_return_claim.inc | 71 +- .../modals/serials_multi_receiving.inc | 4 +- .../includes/modals/serials_skip_issues.inc | 4 +- .../prog/en/includes/noadd-warnings.inc | 8 +- .../prog/en/includes/oai-admin-search.inc | 13 +- .../prog/en/includes/onboarding_messages.inc | 67 +- .../prog/en/includes/page-numbers.inc | 33 +- .../prog/en/includes/patron-age.inc | 4 +- .../en/includes/patron-article-requests.inc | 58 +- .../prog/en/includes/patron-detail-tabs.inc | 8 +- .../en/includes/patron-restrictions-tab.inc | 48 +- .../prog/en/includes/patron-search-box.inc | 2 +- .../prog/en/includes/patron-search.inc | 1408 +- .../prog/en/includes/patron-title.inc | 28 +- .../prog/en/includes/patron-toolbar.inc | 39 +- .../prog/en/includes/patron_messages.inc | 201 +- .../prog/en/includes/patroncards-errors.inc | 107 +- .../prog/en/includes/patronfields.inc | 238 +- .../prog/en/includes/permissions.inc | 660 +- .../prog/en/includes/popup-bottom.inc | 8 +- .../prog/en/includes/pos-menu.inc | 34 +- .../prog/en/includes/prefs-admin-search.inc | 2 +- .../prog/en/includes/prefs-menu.inc | 40 +- .../prog/en/includes/preservation-search.inc | 8 +- .../prog/en/includes/preservation-toolbar.inc | 4 +- .../prog/en/includes/recalls.inc | 224 +- .../prog/en/includes/renew-search-box.inc | 2 +- .../prog/en/includes/renew_strings.inc | 2 +- .../prog/en/includes/reports-menu.inc | 44 +- .../prog/en/includes/reports-toolbar.inc | 114 +- .../prog/en/includes/resort_form.inc | 126 +- .../prog/en/includes/restriction-types.inc | 16 +- .../includes/rotating-collections-toolbar.inc | 4 +- .../prog/en/includes/serial-status.inc | 14 +- .../prog/en/includes/serials-advsearch.inc | 6 +- .../prog/en/includes/serials-menu.inc | 13 +- .../prog/en/includes/serials-search.inc | 11 +- .../prog/en/includes/serials-toolbar.inc | 133 +- .../prog/en/includes/slip-print.inc | 26 +- .../includes/str/import_from_kbart_file.inc | 2 +- .../prog/en/includes/str/job_progress.inc | 8 +- .../prog/en/includes/str/tinymce_i18n.inc | 364 +- .../prog/en/includes/subscriptions-search.inc | 80 +- .../prog/en/includes/subtype_limits.inc | 148 +- .../prog/en/includes/subtypes_unimarc.inc | 308 +- .../en/includes/suggestions-add-search.inc | 2 +- .../prog/en/includes/tags-filter.inc | 48 +- .../prog/en/includes/tools-item-action.inc | 17 +- .../prog/en/includes/tools-menu.inc | 6 +- .../prog/en/includes/tools-nomatch-action.inc | 6 +- .../prog/en/includes/tools-overlay-action.inc | 9 +- .../prog/en/includes/transaction_types.inc | 4 +- .../prog/en/includes/transfer_reasons.inc | 31 +- .../prog/en/includes/validator-strings.inc | 4 +- .../prog/en/includes/vendor-menu.inc | 28 +- .../en/includes/virtualshelves-toolbar.inc | 61 +- .../prog/en/includes/waiting_holds.inc | 53 +- .../en/includes/wrapper-staff-tool-plugin.inc | 44 +- .../prog/en/includes/xslt-handler.inc | 28 +- .../intranet-tmpl/prog/en/modules/about.tt | 636 +- .../prog/en/modules/acqui/acqui-home.tt | 313 +- .../prog/en/modules/acqui/addorder.tt | 62 +- .../prog/en/modules/acqui/addorderiso2709.tt | 1165 +- .../prog/en/modules/acqui/basket.tt | 1918 +- .../prog/en/modules/acqui/basketgroup.tt | 647 +- .../prog/en/modules/acqui/basketheader.tt | 304 +- .../prog/en/modules/acqui/booksellers.tt | 428 +- .../prog/en/modules/acqui/cancelorder.tt | 77 +- .../prog/en/modules/acqui/csv/basket.tt | 25 +- .../prog/en/modules/acqui/csv/basketgroup.tt | 46 +- .../prog/en/modules/acqui/csv/lateorders.tt | 17 +- .../prog/en/modules/acqui/duplicate_orders.tt | 512 +- .../prog/en/modules/acqui/edifactmsgs.tt | 52 +- .../prog/en/modules/acqui/edimsg.tt | 35 +- .../prog/en/modules/acqui/histsearch.tt | 215 +- .../prog/en/modules/acqui/invoice-files.tt | 162 +- .../prog/en/modules/acqui/invoice.tt | 875 +- .../prog/en/modules/acqui/invoices.tt | 383 +- .../prog/en/modules/acqui/lateorders.tt | 553 +- .../prog/en/modules/acqui/moddeliverydate.tt | 31 +- .../prog/en/modules/acqui/modordernotes.tt | 44 +- .../prog/en/modules/acqui/neworderempty.tt | 1369 +- .../modules/acqui/neworderempty_duplicate.tt | 102 +- .../en/modules/acqui/newordersubscription.tt | 174 +- .../en/modules/acqui/newordersuggestion.tt | 118 +- .../prog/en/modules/acqui/ordered.tt | 145 +- .../prog/en/modules/acqui/orderreceive.tt | 700 +- .../prog/en/modules/acqui/parcel.tt | 560 +- .../prog/en/modules/acqui/parcels.tt | 451 +- .../prog/en/modules/acqui/showorder.tt | 63 +- .../prog/en/modules/acqui/spent.tt | 206 +- .../prog/en/modules/acqui/supplier.tt | 568 +- .../prog/en/modules/acqui/transferorder.tt | 270 +- .../prog/en/modules/acqui/uncertainprice.tt | 114 +- .../prog/en/modules/acqui/vendor_issues.tt | 313 +- .../prog/en/modules/acqui/z3950_search.tt | 547 +- .../en/modules/admin/additional-fields.tt | 177 +- .../prog/en/modules/admin/admin-home.tt | 216 +- .../en/modules/admin/adveditorshortcuts.tt | 81 +- .../prog/en/modules/admin/aqbudgetperiods.tt | 853 +- .../prog/en/modules/admin/aqbudgets.tt | 897 +- .../prog/en/modules/admin/aqcontract.tt | 278 +- .../prog/en/modules/admin/aqplan.tt | 487 +- .../prog/en/modules/admin/audio_alerts.tt | 296 +- .../modules/admin/auth_subfields_structure.tt | 672 +- .../en/modules/admin/auth_tag_structure.tt | 391 +- .../en/modules/admin/authorised_values.tt | 882 +- .../prog/en/modules/admin/authtypes.tt | 509 +- .../prog/en/modules/admin/background_jobs.tt | 177 +- .../prog/en/modules/admin/biblio_framework.tt | 650 +- .../modules/admin/branch_transfer_limits.tt | 188 +- .../prog/en/modules/admin/branches.tt | 1079 +- .../prog/en/modules/admin/cash_registers.tt | 405 +- .../prog/en/modules/admin/categories.tt | 1473 +- .../prog/en/modules/admin/checkmarc.tt | 555 +- .../prog/en/modules/admin/cities.tt | 298 +- .../prog/en/modules/admin/classsources.tt | 777 +- .../prog/en/modules/admin/clone-rules.tt | 33 +- .../prog/en/modules/admin/columns_settings.tt | 301 +- .../prog/en/modules/admin/credit_types.tt | 411 +- .../prog/en/modules/admin/curbside_pickup.tt | 241 +- .../prog/en/modules/admin/currency.tt | 408 +- .../prog/en/modules/admin/debit_types.tt | 441 +- .../prog/en/modules/admin/desks.tt | 316 +- .../prog/en/modules/admin/didyoumean.tt | 138 +- .../prog/en/modules/admin/edi_accounts.tt | 659 +- .../prog/en/modules/admin/edi_ean_accounts.tt | 318 +- .../admin/identity_provider_domains.tt | 231 +- .../en/modules/admin/identity_providers.tt | 418 +- .../en/modules/admin/ill_batch_statuses.tt | 206 +- .../modules/admin/item_circulation_alerts.tt | 204 +- .../en/modules/admin/items_search_field.tt | 112 +- .../en/modules/admin/items_search_fields.tt | 191 +- .../prog/en/modules/admin/itemtypes.tt | 870 +- .../prog/en/modules/admin/koha2marclinks.tt | 147 +- .../prog/en/modules/admin/library_groups.tt | 738 +- .../prog/en/modules/admin/localization.tt | 180 +- .../en/modules/admin/marc-overlay-rules.tt | 929 +- .../en/modules/admin/marc_order_accounts.tt | 556 +- .../modules/admin/marc_subfields_structure.tt | 792 +- .../prog/en/modules/admin/marctagstructure.tt | 482 +- .../prog/en/modules/admin/matching-rules.tt | 1046 +- .../prog/en/modules/admin/oai_servers.tt | 248 +- .../prog/en/modules/admin/oai_set_mappings.tt | 196 +- .../prog/en/modules/admin/oai_sets.tt | 153 +- .../prog/en/modules/admin/overdrive.tt | 89 +- .../en/modules/admin/patron-attr-types.tt | 731 +- .../prog/en/modules/admin/preferences.tt | 36 +- .../prog/en/modules/admin/record_sources.tt | 15 +- .../prog/en/modules/admin/restrictions.tt | 365 +- .../prog/en/modules/admin/search_filters.tt | 237 +- .../searchengine/elasticsearch/mappings.tt | 285 +- .../prog/en/modules/admin/share_content.tt | 242 +- .../prog/en/modules/admin/smart-rules.tt | 2993 ++- .../prog/en/modules/admin/sms_providers.tt | 144 +- .../prog/en/modules/admin/smtp_servers.tt | 524 +- .../prog/en/modules/admin/sru_modmapping.tt | 39 +- .../en/modules/admin/sru_modmapping_auth.tt | 39 +- .../en/modules/admin/systempreferences.tt | 691 +- .../prog/en/modules/admin/transfer_limits.tt | 193 +- .../en/modules/admin/transport-cost-matrix.tt | 176 +- .../prog/en/modules/admin/usage_statistics.tt | 142 +- .../prog/en/modules/admin/z3950servers.tt | 406 +- .../intranet-tmpl/prog/en/modules/auth.tt | 515 +- .../en/modules/authorities/auth_finder.tt | 20 +- .../modules/authorities/authorities-home.tt | 26 +- .../en/modules/authorities/authorities.tt | 328 +- .../authorities/blinddetail-biblio-search.tt | 14 +- .../prog/en/modules/authorities/detail.tt | 250 +- .../prog/en/modules/authorities/merge.tt | 240 +- .../authorities/searchresultlist-auth.tt | 95 +- .../modules/authorities/searchresultlist.tt | 224 +- .../prog/en/modules/basket/basket.tt | 632 +- .../prog/en/modules/basket/downloadcart.tt | 54 +- .../prog/en/modules/basket/sendbasketform.tt | 107 +- .../prog/en/modules/batch/print-notices.tt | 20 +- .../prog/en/modules/bookings/list.tt | 770 +- .../prog/en/modules/catalogue/ISBDdetail.tt | 69 +- .../prog/en/modules/catalogue/MARCdetail.tt | 314 +- .../prog/en/modules/catalogue/advsearch.tt | 545 +- .../prog/en/modules/catalogue/detail.tt | 2240 +- .../prog/en/modules/catalogue/imageviewer.tt | 178 +- .../prog/en/modules/catalogue/issuehistory.tt | 173 +- .../prog/en/modules/catalogue/itemsearch.tt | 530 +- .../en/modules/catalogue/itemsearch_json.tt | 13 +- .../en/modules/catalogue/labeledMARCdetail.tt | 119 +- .../prog/en/modules/catalogue/moredetail.tt | 922 +- .../prog/en/modules/catalogue/results.tt | 1484 +- .../en/modules/catalogue/search-history.tt | 529 +- .../prog/en/modules/catalogue/showelastic.tt | 22 +- .../prog/en/modules/catalogue/showmarc.tt | 13 +- .../en/modules/catalogue/stockrotation.tt | 315 +- .../prog/en/modules/cataloguing/addbiblio.tt | 1543 +- .../prog/en/modules/cataloguing/addbooks.tt | 465 +- .../prog/en/modules/cataloguing/additem.tt | 699 +- .../en/modules/cataloguing/cataloging-home.tt | 460 +- .../prog/en/modules/cataloguing/concerns.tt | 87 +- .../prog/en/modules/cataloguing/editor.tt | 323 +- .../prog/en/modules/cataloguing/linkitem.tt | 99 +- .../prog/en/modules/cataloguing/merge.tt | 327 +- .../prog/en/modules/cataloguing/moveitem.tt | 152 +- .../cataloguing/value_builder/EXAMPLE.tt | 43 +- .../cataloguing/value_builder/cn_browser.tt | 131 +- .../value_builder/marc21_field_006.tt | 17 +- .../value_builder/marc21_field_007.tt | 19105 +++++++-------- .../value_builder/marc21_field_008.tt | 20 +- .../marc21_field_008_authorities.tt | 68 +- .../marc21_field_008_classifications.tt | 392 +- .../value_builder/marc21_leader.tt | 682 +- .../marc21_leader_authorities.tt | 251 +- .../value_builder/marc21_linking_section.tt | 261 +- .../value_builder/unimarc_field_100.tt | 1527 +- .../unimarc_field_100_authorities.tt | 587 +- .../value_builder/unimarc_field_105.tt | 2192 +- .../value_builder/unimarc_field_106.tt | 178 +- .../value_builder/unimarc_field_110.tt | 1283 +- .../value_builder/unimarc_field_115a.tt | 2321 +- .../value_builder/unimarc_field_115b.tt | 1233 +- .../value_builder/unimarc_field_116.tt | 3006 ++- .../value_builder/unimarc_field_117.tt | 1537 +- .../value_builder/unimarc_field_120.tt | 2272 +- .../value_builder/unimarc_field_121a.tt | 694 +- .../value_builder/unimarc_field_121b.tt | 498 +- .../value_builder/unimarc_field_122.tt | 99 +- .../value_builder/unimarc_field_123a.tt | 86 +- .../value_builder/unimarc_field_123defg.tt | 118 +- .../value_builder/unimarc_field_123i_j.tt | 99 +- .../value_builder/unimarc_field_124a.tt | 86 +- .../value_builder/unimarc_field_124b.tt | 167 +- .../value_builder/unimarc_field_124c.tt | 277 +- .../value_builder/unimarc_field_124d.tt | 86 +- .../value_builder/unimarc_field_124e.tt | 87 +- .../value_builder/unimarc_field_124f.tt | 56 +- .../value_builder/unimarc_field_124g.tt | 157 +- .../value_builder/unimarc_field_125a.tt | 290 +- .../value_builder/unimarc_field_125b.tt | 276 +- .../value_builder/unimarc_field_126a.tt | 2084 +- .../value_builder/unimarc_field_126b.tt | 364 +- .../value_builder/unimarc_field_127.tt | 90 +- .../value_builder/unimarc_field_128a.tt | 756 +- .../value_builder/unimarc_field_128b.tt | 946 +- .../value_builder/unimarc_field_128c.tt | 936 +- .../value_builder/unimarc_field_130.tt | 678 +- .../value_builder/unimarc_field_135a.tt | 910 +- .../value_builder/unimarc_field_140.tt | 388 +- .../value_builder/unimarc_field_141.tt | 444 +- .../value_builder/unimarc_field_146a.tt | 89 +- .../value_builder/unimarc_field_146b.tt | 237 +- .../value_builder/unimarc_field_146c.tt | 226 +- .../value_builder/unimarc_field_146d.tt | 188 +- .../value_builder/unimarc_field_146e.tt | 247 +- .../value_builder/unimarc_field_146f.tt | 247 +- .../value_builder/unimarc_field_146h.tt | 107 +- .../value_builder/unimarc_field_146i.tt | 107 +- .../value_builder/unimarc_field_181-2.tt | 99 +- .../value_builder/unimarc_field_181a.tt | 244 +- .../value_builder/unimarc_field_181b.tt | 441 +- .../value_builder/unimarc_field_181c.tt | 312 +- .../value_builder/unimarc_field_182-2.tt | 100 +- .../value_builder/unimarc_field_182a.tt | 60 +- .../value_builder/unimarc_field_182c.tt | 161 +- .../value_builder/unimarc_field_183-2.tt | 99 +- .../value_builder/unimarc_field_183a.tt | 667 +- .../value_builder/unimarc_field_210c.tt | 145 +- .../value_builder/unimarc_field_210c_bis.tt | 77 +- .../value_builder/unimarc_field_225a.tt | 55 +- .../value_builder/unimarc_field_225a_bis.tt | 30 +- .../value_builder/unimarc_field_283-2.tt | 99 +- .../value_builder/unimarc_field_283a.tt | 667 +- .../value_builder/unimarc_field_325h.tt | 89 +- .../value_builder/unimarc_field_325j.tt | 249 +- .../value_builder/unimarc_field_4XX.tt | 286 +- .../value_builder/unimarc_field_686a.tt | 142 +- .../value_builder/unimarc_leader.tt | 553 +- .../unimarc_leader_authorities.tt | 342 +- .../modules/cataloguing/z3950_auth_search.tt | 441 +- .../en/modules/cataloguing/z3950_search.tt | 470 +- .../prog/en/modules/circ/article-requests.tt | 787 +- .../prog/en/modules/circ/bookcount.tt | 101 +- .../prog/en/modules/circ/branchoverdues.tt | 105 +- .../prog/en/modules/circ/branchtransfers.tt | 478 +- .../prog/en/modules/circ/checkout-notes.tt | 203 +- .../prog/en/modules/circ/circulation-home.tt | 310 +- .../prog/en/modules/circ/circulation.tt | 1828 +- .../circ/circulation_batch_checkouts.tt | 584 +- .../prog/en/modules/circ/curbside_pickups.tt | 775 +- .../prog/en/modules/circ/on-site_checkouts.tt | 93 +- .../prog/en/modules/circ/overdue.tt | 487 +- .../prog/en/modules/circ/pendingbookings.tt | 483 +- .../prog/en/modules/circ/pendingreserves.tt | 494 +- .../prog/en/modules/circ/printslip.tt | 67 +- .../prog/en/modules/circ/renew.tt | 392 +- .../prog/en/modules/circ/request-article.tt | 468 +- .../prog/en/modules/circ/reserveratios.tt | 335 +- .../prog/en/modules/circ/returns.tt | 2723 +-- .../prog/en/modules/circ/set-library.tt | 136 +- .../prog/en/modules/circ/transfers_to_send.tt | 118 +- .../en/modules/circ/transferstoreceive.tt | 132 +- .../prog/en/modules/circ/view_holdsqueue.tt | 446 +- .../prog/en/modules/circ/waitingreserves.tt | 296 +- .../prog/en/modules/clubs/club-enrollments.tt | 112 +- .../prog/en/modules/clubs/clubs-add-modify.tt | 192 +- .../prog/en/modules/clubs/clubs.tt | 277 +- .../prog/en/modules/clubs/patron-clubs-tab.tt | 80 +- .../prog/en/modules/clubs/patron-enroll.tt | 135 +- .../en/modules/clubs/templates-add-modify.tt | 312 +- .../course_reserves/add_items-step1.tt | 92 +- .../course_reserves/add_items-step2.tt | 136 +- .../course_reserves/batch_add_items.tt | 338 +- .../modules/course_reserves/batch_rm_items.tt | 114 +- .../modules/course_reserves/course-details.tt | 535 +- .../course_reserves/course-reserves.tt | 120 +- .../prog/en/modules/course_reserves/course.tt | 312 +- .../modules/course_reserves/invalid-course.tt | 20 +- .../intranet-tmpl/prog/en/modules/erm/erm.tt | 75 +- .../prog/en/modules/errors/errorpage.tt | 45 +- .../prog/en/modules/ill/ill-requests.tt | 1441 +- .../prog/en/modules/ill/log/patron_notice.tt | 2 +- .../prog/en/modules/ill/log/status_change.tt | 2 +- .../prog/en/modules/installer/auth.tt | 134 +- .../prog/en/modules/installer/step1.tt | 308 +- .../prog/en/modules/installer/step2.tt | 172 +- .../prog/en/modules/installer/step3.tt | 789 +- .../prog/en/modules/intranet-main.tt | 370 +- .../prog/en/modules/labels/barcode-print.tt | 149 +- .../en/modules/labels/label-bib-search.tt | 53 +- .../en/modules/labels/label-edit-batch.tt | 342 +- .../en/modules/labels/label-edit-layout.tt | 383 +- .../en/modules/labels/label-edit-profile.tt | 195 +- .../en/modules/labels/label-edit-range.tt | 129 +- .../en/modules/labels/label-edit-template.tt | 277 +- .../prog/en/modules/labels/label-home.tt | 21 +- .../prog/en/modules/labels/label-manage.tt | 205 +- .../prog/en/modules/labels/label-print.tt | 272 +- .../prog/en/modules/labels/result.tt | 179 +- .../prog/en/modules/labels/search.tt | 288 +- .../prog/en/modules/labels/spinelabel-home.tt | 48 +- .../en/modules/labels/spinelabel-print.tt | 89 +- .../modules/mana/mana-report-search-result.tt | 2 +- .../mana/mana-subscription-search-result.tt | 2 +- .../en/modules/members/accountline-details.tt | 338 +- .../en/modules/members/alert-subscriptions.tt | 118 +- .../prog/en/modules/members/apikeys.tt | 206 +- .../prog/en/modules/members/boraccount.tt | 687 +- .../prog/en/modules/members/deletemem.tt | 38 +- .../prog/en/modules/members/discharge.tt | 102 +- .../prog/en/modules/members/discharges.tt | 85 +- .../prog/en/modules/members/files.tt | 159 +- .../prog/en/modules/members/holdshistory.tt | 167 +- .../prog/en/modules/members/housebound.tt | 760 +- .../prog/en/modules/members/ill-requests.tt | 58 +- .../prog/en/modules/members/mancredit.tt | 146 +- .../prog/en/modules/members/maninvoice.tt | 90 +- .../prog/en/modules/members/member-flags.tt | 163 +- .../en/modules/members/member-password.tt | 159 +- .../prog/en/modules/members/member.tt | 355 +- .../prog/en/modules/members/memberentrygen.tt | 2909 +-- .../prog/en/modules/members/members-update.tt | 370 +- .../prog/en/modules/members/merge-patrons.tt | 459 +- .../en/modules/members/moremember-brief.tt | 182 +- .../en/modules/members/moremember-print.tt | 193 +- .../prog/en/modules/members/moremember.tt | 1412 +- .../prog/en/modules/members/notices.tt | 309 +- .../prog/en/modules/members/pay.tt | 355 +- .../prog/en/modules/members/paycollect.tt | 653 +- .../prog/en/modules/members/printfeercpt.tt | 32 +- .../prog/en/modules/members/printinvoice.tt | 32 +- .../prog/en/modules/members/printnotice.tt | 27 +- .../modules/members/purchase-suggestions.tt | 197 +- .../prog/en/modules/members/readingrec.tt | 96 +- .../prog/en/modules/members/recallshistory.tt | 45 +- .../prog/en/modules/members/routing-lists.tt | 123 +- .../prog/en/modules/members/statistics.tt | 90 +- .../en/modules/members/two_factor_auth.tt | 84 +- .../prog/en/modules/members/update-child.tt | 118 +- .../en/modules/offline_circ/enqueue_koc.tt | 37 +- .../prog/en/modules/offline_circ/list.tt | 116 +- .../en/modules/offline_circ/process_koc.tt | 164 +- .../en/modules/onboarding/onboardingstep1.tt | 103 +- .../en/modules/onboarding/onboardingstep2.tt | 257 +- .../en/modules/onboarding/onboardingstep3.tt | 235 +- .../en/modules/onboarding/onboardingstep4.tt | 124 +- .../en/modules/onboarding/onboardingstep5.tt | 322 +- .../en/modules/patron_lists/add-modify.tt | 122 +- .../prog/en/modules/patron_lists/list.tt | 278 +- .../prog/en/modules/patron_lists/lists.tt | 86 +- .../modules/patron_lists/patron-lists-tab.tt | 185 +- .../prog/en/modules/patroncards/edit-batch.tt | 297 +- .../en/modules/patroncards/edit-layout.tt | 935 +- .../en/modules/patroncards/edit-profile.tt | 214 +- .../en/modules/patroncards/edit-template.tt | 339 +- .../prog/en/modules/patroncards/home.tt | 26 +- .../en/modules/patroncards/image-manage.tt | 255 +- .../prog/en/modules/patroncards/manage.tt | 287 +- .../prog/en/modules/patroncards/print.tt | 206 +- .../en/modules/plugins/plugins-disabled.tt | 48 +- .../prog/en/modules/plugins/plugins-home.tt | 270 +- .../prog/en/modules/plugins/plugins-upload.tt | 113 +- .../intranet-tmpl/prog/en/modules/pos/pay.tt | 678 +- .../prog/en/modules/pos/printreceipt.tt | 28 +- .../prog/en/modules/pos/register.tt | 628 +- .../prog/en/modules/pos/registers.tt | 399 +- .../prog/en/modules/preservation/home.tt | 47 +- .../en/modules/recalls/recalls_old_queue.tt | 26 +- .../en/modules/recalls/recalls_overdue.tt | 48 +- .../prog/en/modules/recalls/recalls_queue.tt | 49 +- .../en/modules/recalls/recalls_to_pull.tt | 123 +- .../en/modules/recalls/recalls_waiting.tt | 251 +- .../prog/en/modules/recalls/request.tt | 22 +- .../en/modules/reports/acquisitions_stats.tt | 583 +- .../prog/en/modules/reports/bor_issues_top.tt | 315 +- .../prog/en/modules/reports/borrowers_out.tt | 201 +- .../en/modules/reports/borrowers_stats.tt | 546 +- .../en/modules/reports/cash_register_stats.tt | 223 +- .../prog/en/modules/reports/cat_issues_top.tt | 346 +- .../prog/en/modules/reports/catalogue_out.tt | 363 +- .../en/modules/reports/catalogue_stats.tt | 580 +- .../prog/en/modules/reports/convert_report.tt | 53 +- .../reports/csv/cash_register_stats.tt | 2 +- .../modules/reports/csv/orders_by_budget.tt | 2 +- .../prog/en/modules/reports/dictionary.tt | 439 +- .../modules/reports/guided_reports_start.tt | 735 +- .../en/modules/reports/issues_avg_stats.tt | 425 +- .../prog/en/modules/reports/issues_stats.tt | 724 +- .../prog/en/modules/reports/itemslost.tt | 281 +- .../prog/en/modules/reports/itemtypes.tt | 113 +- .../en/modules/reports/orders_by_budget.tt | 232 +- .../prog/en/modules/reports/reports-home.tt | 193 +- .../prog/en/modules/reports/reserves_stats.tt | 649 +- .../prog/en/modules/reports/serials_stats.tt | 222 +- .../prog/en/modules/reserve/request.tt | 2233 +- .../prog/en/modules/reviews/reviewswaiting.tt | 193 +- .../modules/rotating_collections/addItems.tt | 169 +- .../rotating_collections/editCollections.tt | 234 +- .../rotatingCollections.tt | 112 +- .../transferCollection.tt | 104 +- .../en/modules/serials/acqui-search-result.tt | 114 +- .../prog/en/modules/serials/acqui-search.tt | 19 +- .../en/modules/serials/checkexpiration.tt | 235 +- .../prog/en/modules/serials/claims.tt | 396 +- .../prog/en/modules/serials/result.tt | 126 +- .../modules/serials/routing-preview-slip.tt | 114 +- .../en/modules/serials/routing-preview.tt | 98 +- .../prog/en/modules/serials/routing.tt | 209 +- .../en/modules/serials/serials-collection.tt | 557 +- .../prog/en/modules/serials/serials-edit.tt | 1043 +- .../prog/en/modules/serials/serials-home.tt | 27 +- .../prog/en/modules/serials/serials-search.tt | 501 +- .../modules/serials/showpredictionpattern.tt | 124 +- .../en/modules/serials/subscription-add.tt | 1050 +- .../modules/serials/subscription-batchedit.tt | 282 +- .../serials/subscription-bib-search.tt | 104 +- .../en/modules/serials/subscription-detail.tt | 742 +- .../serials/subscription-frequencies.tt | 204 +- .../modules/serials/subscription-history.tt | 91 +- .../serials/subscription-numberpatterns.tt | 462 +- .../en/modules/serials/subscription-renew.tt | 239 +- .../prog/en/modules/serials/viewalerts.tt | 58 +- .../en/modules/services/itemrecorddisplay.tt | 60 +- .../prog/en/modules/suggestion/suggestion.tt | 2329 +- .../prog/en/modules/tags/list.tt | 178 +- .../prog/en/modules/tags/review.tt | 492 +- .../prog/en/modules/tools/access_files.tt | 82 +- .../en/modules/tools/additional-contents.tt | 452 +- .../automatic_item_modification_by_age.tt | 461 +- .../prog/en/modules/tools/batchMod-del.tt | 251 +- .../prog/en/modules/tools/batchMod-edit.tt | 624 +- .../prog/en/modules/tools/batchMod.tt | 101 +- .../en/modules/tools/batch_delete_records.tt | 387 +- .../modules/tools/batch_extend_due_dates.tt | 451 +- .../tools/batch_record_modification.tt | 556 +- .../prog/en/modules/tools/cleanborrowers.tt | 391 +- .../prog/en/modules/tools/csv-profiles.tt | 591 +- .../prog/en/modules/tools/export.tt | 582 +- .../prog/en/modules/tools/holidays.tt | 730 +- .../prog/en/modules/tools/import_borrowers.tt | 678 +- .../prog/en/modules/tools/inventory.tt | 656 +- .../prog/en/modules/tools/letter.tt | 1223 +- .../en/modules/tools/manage-marc-import.tt | 816 +- .../tools/marc_modification_templates.tt | 555 +- .../prog/en/modules/tools/modborrowers.tt | 748 +- .../prog/en/modules/tools/overduerules.tt | 290 +- .../prog/en/modules/tools/page.tt | 39 +- .../prog/en/modules/tools/picture-upload.tt | 272 +- .../prog/en/modules/tools/preview_letter.tt | 166 +- .../prog/en/modules/tools/problem-reports.tt | 251 +- .../prog/en/modules/tools/quotes-upload.tt | 714 +- .../prog/en/modules/tools/quotes.tt | 372 +- .../prog/en/modules/tools/scheduler.tt | 159 +- .../prog/en/modules/tools/showdiffmarc.tt | 104 +- .../en/modules/tools/stage-marc-import.tt | 412 +- .../prog/en/modules/tools/stockrotation.tt | 1137 +- .../prog/en/modules/tools/tools-home.tt | 316 +- .../prog/en/modules/tools/upload-images.tt | 367 +- .../prog/en/modules/tools/upload.tt | 326 +- .../prog/en/modules/tools/viewlog.tt | 524 +- .../virtualshelves/addbybiblionumber.tt | 213 +- .../modules/virtualshelves/downloadshelf.tt | 59 +- .../modules/virtualshelves/sendshelfform.tt | 102 +- .../prog/en/modules/virtualshelves/shelves.tt | 867 +- .../virtualshelves/tables/shelves_results.tt | 127 +- koha-tmpl/intranet-tmpl/prog/js/acq.js | 417 +- .../prog/js/acquisitions-menu.js | 20 +- koha-tmpl/intranet-tmpl/prog/js/additem.js | 434 +- .../prog/js/additional-fields-entry.js | 2 +- .../intranet-tmpl/prog/js/addorderiso2709.js | 150 +- koha-tmpl/intranet-tmpl/prog/js/admin-menu.js | 32 +- koha-tmpl/intranet-tmpl/prog/js/ajax.js | 124 +- .../intranet-tmpl/prog/js/audio_alerts.js | 38 +- .../prog/js/auth-finder-search.js | 145 +- .../prog/js/authorities-detail-modal.js | 41 +- koha-tmpl/intranet-tmpl/prog/js/authtype.js | 116 +- .../js/automatic_item_modification_by_age.js | 112 +- koha-tmpl/intranet-tmpl/prog/js/basket.js | 331 +- .../intranet-tmpl/prog/js/biblio_framework.js | 180 +- koha-tmpl/intranet-tmpl/prog/js/browser.js | 186 +- koha-tmpl/intranet-tmpl/prog/js/calendar.js | 123 +- koha-tmpl/intranet-tmpl/prog/js/cart.js | 105 +- .../intranet-tmpl/prog/js/cashup_modal.js | 77 +- koha-tmpl/intranet-tmpl/prog/js/catalog.js | 164 +- koha-tmpl/intranet-tmpl/prog/js/cataloging.js | 818 +- .../prog/js/cataloging_additem.js | 187 +- koha-tmpl/intranet-tmpl/prog/js/charts.js | 62 +- .../prog/js/checkout_renewals_modal.js | 70 +- koha-tmpl/intranet-tmpl/prog/js/checkouts.js | 2207 +- .../intranet-tmpl/prog/js/cookieconsent.js | 120 +- koha-tmpl/intranet-tmpl/prog/js/datatables.js | 1321 +- .../prog/js/elasticsearch-mappings.js | 254 +- .../intranet-tmpl/prog/js/file-upload.js | 46 +- .../intranet-tmpl/prog/js/funds_sorts.js | 142 +- koha-tmpl/intranet-tmpl/prog/js/holds.js | 819 +- .../prog/js/ill-availability-partner.js | 34 +- .../intranet-tmpl/prog/js/ill-availability.js | 190 +- .../intranet-tmpl/prog/js/ill-batch-modal.js | 667 +- .../intranet-tmpl/prog/js/ill-batch-table.js | 142 +- koha-tmpl/intranet-tmpl/prog/js/ill-batch.js | 33 +- .../intranet-tmpl/prog/js/ill-list-table.js | 906 +- .../prog/js/item_search_fields.js | 25 +- .../intranet-tmpl/prog/js/job_progress.js | 63 +- koha-tmpl/intranet-tmpl/prog/js/letter.js | 239 +- .../intranet-tmpl/prog/js/localcovers.js | 18 +- koha-tmpl/intranet-tmpl/prog/js/mana.js | 62 +- .../prog/js/marc_modification_templates.js | 380 +- .../prog/js/marc_subfields_structure.js | 279 +- .../intranet-tmpl/prog/js/members-menu.js | 211 +- .../prog/js/members-patron-selections.js | 58 +- koha-tmpl/intranet-tmpl/prog/js/members.js | 325 +- .../intranet-tmpl/prog/js/merge-record.js | 299 +- .../prog/js/messaging-preference-form.js | 112 +- .../intranet-tmpl/prog/js/modal_printer.js | 35 +- koha-tmpl/intranet-tmpl/prog/js/onboarding.js | 180 +- .../intranet-tmpl/prog/js/pages/addbiblio.js | 2 +- .../intranet-tmpl/prog/js/pages/batchMod.js | 116 +- .../prog/js/pages/circulation.js | 105 +- .../intranet-tmpl/prog/js/pages/results.js | 421 +- .../prog/js/pages/stockrotation.js | 134 +- .../prog/js/pages/tags-review.js | 251 +- .../intranet-tmpl/prog/js/patron-webcam.js | 160 +- koha-tmpl/intranet-tmpl/prog/js/recalls.js | 269 +- .../prog/js/resolve_claim_modal.js | 73 +- .../intranet-tmpl/prog/js/restrictiontypes.js | 81 +- .../prog/js/rotating-collections.js | 38 +- koha-tmpl/intranet-tmpl/prog/js/select2.js | 76 +- .../intranet-tmpl/prog/js/serials-toolbar.js | 37 +- .../prog/js/showpredictionpattern.js | 16 +- .../intranet-tmpl/prog/js/sms_providers.js | 59 +- .../intranet-tmpl/prog/js/staff-global.js | 189 +- .../intranet-tmpl/prog/js/subscription-add.js | 725 +- koha-tmpl/intranet-tmpl/prog/js/tools-menu.js | 72 +- .../intranet-tmpl/prog/js/upload-images.js | 215 +- koha-tmpl/intranet-tmpl/prog/js/viewlog.js | 158 +- .../intranet-tmpl/prog/js/xmlControlfield.js | 436 +- .../intranet-tmpl/prog/js/z3950_search.js | 163 +- .../bootstrap/en/includes/account-table.inc | 65 +- .../bootstrap/en/includes/accounts.inc | 129 +- .../includes/authorities-search-results.inc | 127 +- .../en/includes/authority-information.inc | 31 +- .../en/includes/av-build-dropbox.inc | 20 +- .../en/includes/biblio-title-head.inc | 3 +- .../bootstrap/en/includes/biblio-title.inc | 49 +- .../bootstrap/en/includes/bodytag.inc | 2 +- .../bootstrap/en/includes/calendar.inc | 190 +- .../en/includes/columns_settings.inc | 275 +- .../bootstrap/en/includes/cover-images.inc | 33 +- .../en/includes/display-library-address.inc | 39 +- .../bootstrap/en/includes/doc-head-close.inc | 7 +- .../bootstrap/en/includes/doc-head-open.inc | 4 +- .../bootstrap/en/includes/holds-table.inc | 58 +- .../bootstrap/en/includes/html_helpers.inc | 42 +- .../en/includes/ill-availability-table.inc | 3 +- .../bootstrap/en/includes/item-status.inc | 14 +- .../en/includes/js-biblio-format.inc | 42 +- .../bootstrap/en/includes/js-date-format.inc | 1 - .../bootstrap/en/includes/langmenu.inc | 30 +- .../bootstrap/en/includes/masthead-sci.inc | 20 +- .../bootstrap/en/includes/masthead-sco.inc | 16 +- .../bootstrap/en/includes/masthead.inc | 993 +- .../en/includes/modals/catalog_cite.inc | 4 +- .../en/includes/modals/catalog_concern.inc | 26 +- .../bootstrap/en/includes/modals/checkout.inc | 21 +- .../en/includes/opac-authorities.inc | 74 +- .../bootstrap/en/includes/opac-bottom.inc | 98 +- .../en/includes/opac-detail-sidebar.inc | 107 +- .../bootstrap/en/includes/opac-facets.inc | 145 +- .../bootstrap/en/includes/opac-note.inc | 4 +- .../bootstrap/en/includes/opac-topissues.inc | 122 +- .../en/includes/overdrive-checkout.inc | 15 +- .../bootstrap/en/includes/overdrive-login.inc | 20 +- .../bootstrap/en/includes/page-numbers.inc | 36 +- .../bootstrap/en/includes/password_check.inc | 2 +- .../bootstrap/en/includes/patron-title.inc | 6 +- .../en/includes/result-batch-controls.inc | 23 +- .../bootstrap/en/includes/serial-status.inc | 14 +- .../bootstrap/en/includes/shelfbrowser.inc | 48 +- .../bootstrap/en/includes/slip-print.inc | 22 +- .../en/includes/subtypes_unimarc.inc | 126 +- .../en/includes/title-actions-menu.inc | 58 +- .../en/includes/user-star-ratings.inc | 10 +- .../bootstrap/en/includes/usermenu.inc | 59 +- .../en/includes/validator-strings.inc | 4 +- .../bootstrap/en/includes/xslt-handler.inc | 28 +- .../bootstrap/en/modules/clubs/clubs-tab.tt | 113 +- .../bootstrap/en/modules/clubs/enroll.tt | 79 +- .../bootstrap/en/modules/errors/errorpage.tt | 156 +- .../opac-tmpl/bootstrap/en/modules/ilsdi.tt | 951 +- .../bootstrap/en/modules/maintenance.tt | 92 +- .../bootstrap/en/modules/opac-ISBDdetail.tt | 57 +- .../bootstrap/en/modules/opac-MARCdetail.tt | 164 +- .../en/modules/opac-account-pay-error.tt | 41 +- .../bootstrap/en/modules/opac-account.tt | 238 +- .../en/modules/opac-addbybiblionumber.tt | 236 +- .../bootstrap/en/modules/opac-advsearch.tt | 375 +- .../en/modules/opac-alert-subscribe.tt | 134 +- .../en/modules/opac-alert-subscriptions.tt | 92 +- .../en/modules/opac-auth-MARCdetail.tt | 129 +- .../bootstrap/en/modules/opac-auth-detail.tt | 408 +- .../bootstrap/en/modules/opac-auth.tt | 373 +- .../en/modules/opac-authorities-home.tt | 175 +- .../opac-authoritiessearchresultlist.tt | 204 +- .../bootstrap/en/modules/opac-basket.tt | 948 +- .../bootstrap/en/modules/opac-blocked.tt | 23 +- .../bootstrap/en/modules/opac-browse.tt | 178 +- .../bootstrap/en/modules/opac-browser.tt | 88 +- .../en/modules/opac-course-details.tt | 45 +- .../en/modules/opac-course-reserves.tt | 39 +- .../en/modules/opac-curbside-pickups.tt | 73 +- .../bootstrap/en/modules/opac-detail.tt | 935 +- .../bootstrap/en/modules/opac-discharge.tt | 38 +- .../bootstrap/en/modules/opac-downloadcart.tt | 69 +- .../en/modules/opac-downloadshelf.tt | 220 +- .../en/modules/opac-full-serial-issues.tt | 273 +- .../bootstrap/en/modules/opac-holdshistory.tt | 206 +- .../bootstrap/en/modules/opac-ics.tt | 8 +- .../bootstrap/en/modules/opac-idref.tt | 120 +- .../bootstrap/en/modules/opac-illrequests.tt | 95 +- .../bootstrap/en/modules/opac-imageviewer.tt | 144 +- .../bootstrap/en/modules/opac-issue-note.tt | 66 +- .../bootstrap/en/modules/opac-library.tt | 107 +- .../bootstrap/en/modules/opac-main.tt | 520 +- .../opac-memberentry-update-submitted.tt | 73 +- .../bootstrap/en/modules/opac-memberentry.tt | 2239 +- .../bootstrap/en/modules/opac-messaging.tt | 346 +- .../bootstrap/en/modules/opac-mymessages.tt | 42 +- .../bootstrap/en/modules/opac-news-rss.tt | 29 +- .../bootstrap/en/modules/opac-opensearch.tt | 173 +- .../en/modules/opac-overdrive-search.tt | 96 +- .../bootstrap/en/modules/opac-page.tt | 45 +- .../bootstrap/en/modules/opac-passwd.tt | 44 +- .../en/modules/opac-password-recovery.tt | 172 +- .../en/modules/opac-patron-consent.tt | 58 +- .../bootstrap/en/modules/opac-privacy.tt | 65 +- .../en/modules/opac-readingrecord.tt | 156 +- .../bootstrap/en/modules/opac-recall.tt | 210 +- .../bootstrap/en/modules/opac-recalls.tt | 70 +- .../modules/opac-registration-confirmation.tt | 112 +- .../modules/opac-registration-email-sent.tt | 69 +- .../en/modules/opac-registration-invalid.tt | 83 +- .../en/modules/opac-reportproblem.tt | 86 +- .../en/modules/opac-request-article.tt | 201 +- .../bootstrap/en/modules/opac-reserve.tt | 881 +- .../en/modules/opac-reset-password.tt | 172 +- .../en/modules/opac-restrictedpage.tt | 25 +- .../bootstrap/en/modules/opac-results.tt | 446 +- .../en/modules/opac-retrieve-file.tt | 4 +- .../bootstrap/en/modules/opac-review.tt | 128 +- .../en/modules/opac-routing-lists.tt | 40 +- .../en/modules/opac-search-history.tt | 252 +- .../en/modules/opac-sendbasketform.tt | 109 +- .../en/modules/opac-sendshelfform.tt | 108 +- .../en/modules/opac-serial-issues.tt | 318 +- .../bootstrap/en/modules/opac-shareshelf.tt | 88 +- .../bootstrap/en/modules/opac-shelves-rss.tt | 34 +- .../bootstrap/en/modules/opac-shelves.tt | 900 +- .../bootstrap/en/modules/opac-showmarc.tt | 2 +- .../en/modules/opac-showreviews-rss.tt | 83 +- .../bootstrap/en/modules/opac-showreviews.tt | 284 +- .../bootstrap/en/modules/opac-suggestions.tt | 737 +- .../bootstrap/en/modules/opac-tags.tt | 456 +- .../bootstrap/en/modules/opac-tags_subject.tt | 101 +- .../bootstrap/en/modules/opac-topissues.tt | 226 +- .../bootstrap/en/modules/opac-user.tt | 924 +- .../bootstrap/en/modules/opac-virtual-card.tt | 16 +- .../bootstrap/en/modules/sci/sci-main.tt | 441 +- .../bootstrap/en/modules/sco/help.tt | 81 +- .../bootstrap/en/modules/sco/printslip.tt | 22 +- .../bootstrap/en/modules/sco/sco-main.tt | 875 +- .../bootstrap/en/modules/svc/suggestion.tt | 35 +- koha-tmpl/opac-tmpl/bootstrap/js/Gettext.js | 473 +- .../opac-tmpl/bootstrap/js/amazonimages.js | 28 +- .../opac-tmpl/bootstrap/js/authtoresults.js | 5 +- koha-tmpl/opac-tmpl/bootstrap/js/autofill.js | 172 +- .../bootstrap/js/bakertaylorimages.js | 10 +- .../bootstrap/js/barcode-generator.js | 28 +- koha-tmpl/opac-tmpl/bootstrap/js/basket.js | 346 +- koha-tmpl/opac-tmpl/bootstrap/js/browse.js | 105 +- koha-tmpl/opac-tmpl/bootstrap/js/coce.js | 42 +- .../opac-tmpl/bootstrap/js/cookieconsent.js | 118 +- .../opac-tmpl/bootstrap/js/datatables.js | 122 +- koha-tmpl/opac-tmpl/bootstrap/js/global.js | 27 +- .../opac-tmpl/bootstrap/js/google-jackets.js | 49 +- koha-tmpl/opac-tmpl/bootstrap/js/i18n.js | 50 +- .../bootstrap/js/ill-availability.js | 129 +- .../opac-tmpl/bootstrap/js/localcovers.js | 150 +- .../bootstrap/js/modals/catalog_concern.js | 94 +- .../opac-tmpl/bootstrap/js/modals/checkout.js | 351 +- .../opac-tmpl/bootstrap/js/openlibrary.js | 132 +- koha-tmpl/opac-tmpl/bootstrap/js/overdrive.js | 455 +- koha-tmpl/opac-tmpl/bootstrap/js/privacy.js | 18 +- koha-tmpl/opac-tmpl/bootstrap/js/ratings.js | 66 +- .../opac-tmpl/bootstrap/js/results-list.js | 153 +- .../bootstrap/js/show-password-toggle.js | 47 +- koha-tmpl/opac-tmpl/bootstrap/js/tags.js | 121 +- koha-tmpl/opac-tmpl/bootstrap/js/verovio.js | 233 +- kohaversion.pl | 1 + labels/barcode-print.pl | 13 +- labels/label-create-csv.pl | 55 +- labels/label-create-pdf.pl | 173 +- labels/label-create-xml.pl | 62 +- labels/label-edit-batch.pl | 131 +- labels/label-edit-layout.pl | 85 +- labels/label-edit-profile.pl | 80 +- labels/label-edit-range.pl | 10 +- labels/label-edit-template.pl | 167 +- labels/label-home.pl | 12 +- labels/label-item-search.pl | 95 +- labels/label-manage.pl | 133 +- labels/label-print.pl | 220 +- labels/spinelabel-home.pl | 13 +- labels/spinelabel-print.pl | 21 +- lib/CGI/Session/Serialize/yamlxs.pm | 8 +- mainpage.pl | 61 +- members/accountline-details.pl | 29 +- members/alert-subscriptions.pl | 2 +- members/apikeys.pl | 40 +- members/boraccount.pl | 96 +- members/cancel-charge.pl | 4 +- members/default_messageprefs.pl | 6 +- members/deletemem.pl | 76 +- members/discharge.pl | 67 +- members/discharges.pl | 42 +- members/files.pl | 39 +- members/holdshistory.pl | 34 +- members/housebound.pl | 113 +- members/ill-requests.pl | 23 +- members/mancredit.pl | 39 +- members/maninvoice.pl | 72 +- members/member-flags.pl | 151 +- members/member-password.pl | 43 +- members/member.pl | 32 +- members/memberentry.pl | 590 +- members/members-home.pl | 60 +- members/members-update-do.pl | 21 +- members/members-update.pl | 21 +- members/merge-patrons.pl | 25 +- members/mod_debarment.pl | 11 +- members/moremember.pl | 145 +- members/notices.pl | 49 +- members/patronimage.pl | 24 +- members/pay.pl | 124 +- members/paycollect.pl | 161 +- members/print_overdues.pl | 25 +- members/printfeercpt.pl | 4 +- members/printinvoice.pl | 4 +- members/printnotice.pl | 10 +- members/printslip.pl | 32 +- members/purchase-suggestions.pl | 30 +- members/readingrec.pl | 42 +- members/recallshistory.pl | 28 +- members/routing-lists.pl | 31 +- members/setstatus.pl | 23 +- members/statistics.pl | 84 +- members/summary-print.pl | 37 +- members/two_factor_auth.pl | 8 +- members/update-child.pl | 37 +- misc/add_date_fields_to_marc_records.pl | 45 +- misc/add_statistics_borrowers_categorycode.pl | 62 +- misc/admin/set_password.pl | 40 +- misc/batchCompareMARCvsFrameworks.pl | 67 +- misc/batchDeleteUnusedSubfields.pl | 69 +- misc/batchImportMARCWithBiblionumbers.pl | 87 +- misc/batchRebuildBiblioTables.pl | 41 +- misc/batchRebuildItemsTables.pl | 19 +- misc/batchRepairMissingBiblionumbers.pl | 14 +- misc/batchdeletebiblios.pl | 15 +- misc/check_sysprefs.pl | 3 +- misc/commit_file.pl | 64 +- misc/cronjobs/advance_notices.pl | 445 +- misc/cronjobs/archive_purchase_suggestions.pl | 59 +- misc/cronjobs/automatic_checkin.pl | 6 +- .../automatic_item_modification_by_age.pl | 23 +- misc/cronjobs/batch_anonymise.pl | 31 +- misc/cronjobs/build_browser_and_cloud.pl | 2836 +-- misc/cronjobs/cart_to_shelf.pl | 12 +- misc/cronjobs/check-url-quick.pl | 31 +- misc/cronjobs/cleanup_database.pl | 1 - misc/cronjobs/cloud-kw.pl | 162 +- misc/cronjobs/create_koc_db.pl | 115 +- misc/cronjobs/delete_items.pl | 60 +- misc/cronjobs/delete_patrons.pl | 81 +- misc/cronjobs/delete_records_via_leader.pl | 31 +- misc/cronjobs/erm_run_harvester.pl | 2 +- misc/cronjobs/fines.pl | 78 +- misc/cronjobs/gather_print_notices.pl | 203 +- misc/cronjobs/holds/auto_unsuspend_holds.pl | 8 +- misc/cronjobs/holds/build_holds_queue.pl | 4 +- misc/cronjobs/holds/cancel_expired_holds.pl | 8 +- misc/cronjobs/holds/cancel_unfilled_holds.pl | 49 +- misc/cronjobs/holds/holds_reminder.pl | 127 +- misc/cronjobs/longoverdue.pl | 204 +- misc/cronjobs/membership_expiry.pl | 22 +- misc/cronjobs/merge_authorities.pl | 43 +- .../notice_unprocessed_suggestions.pl | 8 +- misc/cronjobs/overdue_notices.pl | 449 +- misc/cronjobs/patron_emailer.pl | 96 +- misc/cronjobs/purge_suggestions.pl | 10 +- misc/cronjobs/recalls/expire_recalls.pl | 43 +- misc/cronjobs/recalls/overdue_recalls.pl | 14 +- misc/cronjobs/reconcile_balances.pl | 55 +- misc/cronjobs/remove_temporary_edifiles.pl | 7 +- misc/cronjobs/rss/rss.pl | 6 +- misc/cronjobs/runreport.pl | 122 +- misc/cronjobs/serialsUpdate.pl | 22 +- .../share_usage_with_koha_community.pl | 12 +- misc/cronjobs/sitemap.pl | 18 +- .../social_data/update_social_data.pl | 13 +- misc/cronjobs/staticfines.pl | 121 +- misc/cronjobs/stockrotation.pl | 119 +- .../thirdparty/TalkingTech_itiva_inbound.pl | 21 +- .../thirdparty/TalkingTech_itiva_outbound.pl | 64 +- misc/cronjobs/writeoff_debts.pl | 29 +- misc/devel/add_missing_filters.pl | 23 +- misc/devel/auto_rebase.pl | 14 +- misc/devel/coverage.pl | 14 +- misc/devel/get_prepared_letter.pl | 10 +- misc/devel/install_plugins.pl | 42 +- misc/devel/koha_perl_deps.pl | 81 +- misc/devel/update_dbix_class_files.pl | 30 +- misc/export_borrowers.pl | 46 +- misc/exportauth.pl | 19 +- misc/import_patrons.pl | 2 +- misc/link_bibs_to_authorities.pl | 74 +- misc/load_yaml.pl | 16 +- .../UNIMARC_fix_collectiontitle.pl | 16 +- ...MARC_sync_date_created_with_marc_biblio.pl | 76 +- misc/maintenance/auth_show_hidden_data.pl | 48 +- .../borrowers-force-messaging-defaults.pl | 22 +- misc/maintenance/check_syspref_cache.pl | 16 +- misc/maintenance/cmp_sysprefs.pl | 19 +- misc/maintenance/compare_es_to_db.pl | 34 +- misc/maintenance/fix_accountlines_date.pl | 57 +- .../fix_accountlines_rmdupfines_bug8253.pl | 20 +- misc/maintenance/fix_mysql_constraints.pl | 36 +- misc/maintenance/fix_tags_weight.pl | 16 +- misc/maintenance/generate_MARC21Languages.pl | 17 +- .../process_record_through_filter.pl | 6 +- misc/maintenance/pseudonymize_statistics.pl | 1 - .../remove_items_from_biblioitems.pl | 31 +- misc/maintenance/sanitize_records.pl | 40 +- .../search_for_data_inconsistencies.pl | 178 +- misc/maintenance/sync_db_comments.pl | 47 +- misc/maintenance/touch_all_biblios.pl | 55 +- misc/maintenance/touch_all_items.pl | 63 +- misc/maintenance/update_authorities.pl | 61 +- .../22_to_30/convert_to_utf8.pl | 2 +- .../22_to_30/export_Authorities.pl | 88 +- .../22_to_30/export_Authorities_xml.pl | 65 +- .../22_to_30/missing090field.pl | 67 +- .../22_to_30/move_marc_to_authheader.pl | 168 +- .../22_to_30/move_marc_to_biblioitems.pl | 109 +- .../22_to_30/rebuild_leader.pl | 64 +- .../22_to_30/rebuild_unimarc_100.pl | 66 +- misc/migration_tools/buildCOUNTRY.pl | 81 +- misc/migration_tools/buildEDITORS.pl | 185 +- misc/migration_tools/buildLANG.pl | 195 +- misc/migration_tools/build_oai_sets.pl | 65 +- misc/migration_tools/bulkmarcimport.pl | 1 + .../migration_tools/checkNonIndexedBiblios.pl | 36 +- misc/migration_tools/create_analytical_rel.pl | 57 +- misc/migration_tools/ifla/update.pl | 208 +- misc/migration_tools/import_lexile.pl | 25 +- misc/migration_tools/koha-svc.pl | 12 +- misc/migration_tools/rebuild_zebra.pl | 441 +- .../remove_unused_authorities.pl | 55 +- .../switch_marc21_series_info.pl | 96 +- misc/migration_tools/upgradeitems.pl | 53 +- misc/mod_zebraqueue.pl | 2 +- misc/process_ill_updates.pl | 80 +- misc/recreateIssueStatistics.pl | 231 +- misc/sax_parser_print.pl | 9 +- misc/sax_parser_test.pl | 17 +- .../export_elasticsearch_mappings.pl | 8 +- misc/search_tools/rebuild_elasticsearch.pl | 97 +- misc/sip_cli_emulator.pl | 234 +- misc/stage_file.pl | 107 +- misc/translator/LangInstaller.pm | 298 +- misc/translator/TmplTokenizer.pm | 492 +- misc/translator/VerboseWarnings.pm | 61 +- misc/translator/tmpl_process3.pl | 384 +- misc/translator/xgettext.pl | 254 +- misc/workers/background_jobs_worker.pl | 32 +- misc/workers/es_indexer_daemon.pl | 52 +- misc/z3950_responder.pl | 61 +- offline_circ/enqueue_koc.pl | 51 +- offline_circ/list.pl | 34 +- offline_circ/process.pl | 28 +- offline_circ/process_koc.pl | 164 +- offline_circ/service.pl | 39 +- opac/clubs/clubs-tab.pl | 10 +- opac/clubs/enroll.pl | 8 +- opac/errors/400.pl | 8 +- opac/errors/401.pl | 8 +- opac/errors/402.pl | 8 +- opac/errors/403.pl | 12 +- opac/errors/404.pl | 8 +- opac/errors/500.pl | 8 +- opac/external/overdrive/auth.pl | 22 +- opac/ilsdi.pl | 60 +- opac/maintenance.pl | 17 +- opac/oai.pl | 26 +- opac/opac-ISBDdetail.pl | 83 +- opac/opac-MARCdetail.pl | 153 +- opac/opac-account-pay-return.pl | 3 +- opac/opac-account-pay.pl | 11 +- opac/opac-account.pl | 38 +- opac/opac-addbybiblionumber.pl | 85 +- opac/opac-alert-subscribe.pl | 4 +- opac/opac-alert-subscriptions.pl | 2 +- opac/opac-article-request-cancel.pl | 13 +- opac/opac-authorities-home.pl | 134 +- opac/opac-authoritiesdetail.pl | 78 +- opac/opac-basket.pl | 91 +- opac/opac-blocked.pl | 4 +- opac/opac-browse.pl | 35 +- opac/opac-browser.pl | 32 +- opac/opac-changelanguage.pl | 4 +- opac/opac-course-details.pl | 7 +- opac/opac-course-reserves.pl | 5 +- opac/opac-curbside-pickups.pl | 53 +- opac/opac-detail.pl | 1234 +- opac/opac-discharge.pl | 68 +- opac/opac-dismiss-message.pl | 13 +- opac/opac-downloadcart.pl | 72 +- opac/opac-downloadshelf.pl | 83 +- opac/opac-export.pl | 145 +- opac/opac-holdshistory.pl | 37 +- opac/opac-ics.pl | 37 +- opac/opac-idref.pl | 32 +- opac/opac-illrequests.pl | 97 +- opac/opac-image.pl | 21 +- opac/opac-imageviewer.pl | 15 +- opac/opac-issue-note.pl | 55 +- opac/opac-library.pl | 12 +- opac/opac-main.pl | 72 +- opac/opac-memberentry.pl | 324 +- opac/opac-messaging.pl | 47 +- opac/opac-modrequest-suspend.pl | 11 +- opac/opac-modrequest.pl | 31 +- opac/opac-mymessages.pl | 20 +- opac/opac-news-rss.pl | 8 +- opac/opac-overdrive-search.pl | 8 +- opac/opac-page.pl | 14 +- opac/opac-passwd.pl | 37 +- opac/opac-password-recovery.pl | 125 +- opac/opac-patron-consent.pl | 45 +- opac/opac-patron-image.pl | 16 +- opac/opac-privacy.pl | 37 +- opac/opac-ratings.pl | 16 +- opac/opac-readingrecord.pl | 54 +- opac/opac-recall.pl | 116 +- opac/opac-recalls.pl | 22 +- opac/opac-registration-verify.pl | 54 +- opac/opac-renew.pl | 38 +- opac/opac-reportproblem.pl | 64 +- opac/opac-request-article.pl | 69 +- opac/opac-reserve.pl | 275 +- opac/opac-reset-password.pl | 43 +- opac/opac-restrictedpage.pl | 9 +- opac/opac-retrieve-file.pl | 33 +- opac/opac-review.pl | 59 +- opac/opac-routing-lists.pl | 12 +- opac/opac-search-history.pl | 131 +- opac/opac-search.pl | 636 +- opac/opac-sendbasket.pl | 11 +- opac/opac-sendshelf.pl | 28 +- opac/opac-serial-issues.pl | 27 +- opac/opac-shareshelf.pl | 97 +- opac/opac-shelves.pl | 248 +- opac/opac-showmarc.pl | 41 +- opac/opac-showreviews.pl | 211 +- opac/opac-suggestions.pl | 190 +- opac/opac-tags.pl | 269 +- opac/opac-tags_subject.pl | 25 +- opac/opac-topissues.pl | 36 +- opac/opac-user.pl | 187 +- opac/sci/sci-main.pl | 33 +- opac/sco/help.pl | 21 +- opac/sco/printslip.pl | 48 +- opac/sco/sco-main.pl | 2 +- opac/sco/sco-patron-image.pl | 18 +- opac/svc/auth/googleopenidconnect | 176 +- opac/svc/checkout_notes | 78 +- opac/svc/club/cancel_enrollment | 4 +- opac/svc/overdrive | 186 +- opac/svc/overdrive_proxy | 35 +- opac/svc/report | 46 +- opac/svc/shelfbrowser.pl | 16 +- opac/svc/suggestion | 16 +- opac/tracklinks.pl | 33 +- patron_lists/add-modify.pl | 20 +- patron_lists/list.pl | 39 +- patron_lists/lists.pl | 10 +- patron_lists/patrons.pl | 13 +- patroncards/create-pdf.pl | 451 +- patroncards/edit-batch.pl | 129 +- patroncards/edit-layout.pl | 311 +- patroncards/edit-profile.pl | 78 +- patroncards/edit-template.pl | 130 +- patroncards/home.pl | 10 +- patroncards/image-manage.pl | 178 +- patroncards/manage.pl | 163 +- patroncards/print.pl | 204 +- plugins/plugins-enable.pl | 16 +- plugins/plugins-home.pl | 38 +- plugins/plugins-uninstall.pl | 9 +- plugins/plugins-upload.pl | 6 +- plugins/run.pl | 13 +- pos/pay.pl | 12 +- pos/printreceipt.pl | 6 +- pos/register.pl | 35 +- pos/registers.pl | 11 +- preservation/print_slip.pl | 2 +- recalls/recall_pickup_slip.pl | 30 +- recalls/recalls_old_queue.pl | 20 +- recalls/recalls_overdue.pl | 29 +- recalls/recalls_queue.pl | 31 +- recalls/recalls_to_pull.pl | 99 +- recalls/recalls_waiting.pl | 46 +- recalls/request.pl | 34 +- reports/acquisitions_stats.pl | 203 +- reports/bor_issues_top.pl | 405 +- reports/borrowers_out.pl | 311 +- reports/borrowers_stats.pl | 580 +- reports/cash_register_stats.pl | 159 +- reports/cat_issues_top.pl | 491 +- reports/catalog_by_itemtype.pl | 2 +- reports/catalogue_out.pl | 41 +- reports/catalogue_stats.pl | 222 +- reports/dictionary.pl | 70 +- reports/guided_reports.pl | 916 +- reports/issues_avg_stats.pl | 664 +- reports/issues_stats.pl | 433 +- reports/itemslost.pl | 54 +- reports/orders_by_fund.pl | 181 +- reports/reports-home.pl | 4 +- reports/reserves_stats.pl | 460 +- reports/serials_stats.pl | 162 +- reserve/modrequest.pl | 62 +- reserve/modrequest_suspendall.pl | 13 +- reserve/request.pl | 342 +- reviews/reviewswaiting.pl | 56 +- rotating_collections/addItems.pl | 36 +- rotating_collections/editCollections.pl | 27 +- rotating_collections/rotatingCollections.pl | 10 +- rotating_collections/transferCollection.pl | 26 +- serials/acqui-search-result.pl | 55 +- serials/acqui-search.pl | 13 +- serials/checkexpiration.pl | 50 +- serials/claims.pl | 66 +- serials/create-numberpattern.pl | 25 +- serials/lateissues-export.pl | 30 +- serials/reorder_members.pl | 7 +- serials/routing-preview.pl | 87 +- serials/routing.pl | 83 +- serials/serials-collection.pl | 267 +- serials/serials-edit.pl | 264 +- serials/serials-home.pl | 15 +- serials/serials-search.pl | 174 +- serials/showpredictionpattern.pl | 145 +- serials/subscription-add.pl | 430 +- serials/subscription-batchedit.pl | 3 +- serials/subscription-bib-search.pl | 77 +- serials/subscription-detail.pl | 146 +- serials/subscription-frequencies.pl | 45 +- serials/subscription-frequency.pl | 18 +- serials/subscription-history.pl | 59 +- serials/subscription-numberpattern.pl | 22 +- serials/subscription-numberpatterns.pl | 86 +- serials/subscription-renew.pl | 71 +- serials/viewalerts.pl | 20 +- services/itemrecorddisplay.pl | 30 +- suggestion/suggestion.pl | 321 +- svc/article_request | 34 +- svc/authentication | 8 +- svc/authorised_values | 4 +- svc/barcode | 20 +- svc/bib | 85 +- svc/bib_framework | 38 +- svc/bib_profile | 67 +- svc/cataloguing/automatic_linker.pl | 22 +- svc/cataloguing/control_num_sequences | 16 +- svc/cataloguing/framework | 37 +- svc/cataloguing/metasearch | 50 +- svc/checkin | 13 +- svc/checkout_notes | 20 +- svc/checkouts | 76 +- svc/club/cancel_enrollment | 4 +- svc/club/delete | 4 +- svc/club/enroll | 2 +- svc/club/template/delete | 4 +- svc/config/systempreferences | 26 +- svc/convert_report | 24 +- svc/cover_images | 29 +- svc/creator_batches | 23 +- svc/holds | 53 +- svc/import_bib | 61 +- svc/letters/get | 8 +- svc/letters/preview | 145 +- svc/localization | 66 +- svc/mana/increment | 8 +- svc/mana/search | 30 +- svc/mana/share | 16 +- svc/mana/use | 19 +- svc/members/add_to_list | 21 +- svc/new_bib | 50 +- svc/problem_reports | 18 +- svc/recall | 43 +- svc/records/preview | 31 +- svc/renew | 29 +- svc/report | 54 +- svc/return_claims | 35 +- svc/split_callnumbers | 10 +- svc/virtualshelves/search | 44 +- t/00-check-atomic-updates.t | 2 +- t/00-deprecated.t | 21 +- t/00-load.t | 52 +- t/00-merge-conflict-markers.t | 53 +- t/00-testcritic.t | 2 +- t/00-valid-xml.t | 35 +- t/Acquisition/CanUserManageBasket.t | 167 +- t/Auth.t | 30 +- t/AuthoritiesMarc_MARC21.t | 64 +- t/AuthoritiesMarc_UNIMARC.t | 6 +- t/Barcodes_EAN13.t | 2 +- t/Barcodes_annual.t | 4 +- t/Barcodes_hbyymmincr.t | 4 +- t/Barcodes_incremental.t | 4 +- t/Biblio.t | 112 +- t/Biblio/TransformHtmlToXml.t | 24 +- t/Biblio2.t | 46 +- t/Budgets.t | 4 +- t/Budgets/CanUserModifyBudget.t | 375 +- t/Budgets/CanUserUseBudget.t | 240 +- t/Charset.t | 47 +- t/Circulation/AgeRestrictionMarkers.t | 10 +- t/Circulation_barcodedecode.t | 49 +- t/ClassSortRoutine.t | 4 +- t/ClassSortRoutine_Dewey.t | 40 +- t/ClassSortRoutine_Generic.t | 14 +- t/ClassSortRoutine_LCC.t | 27 +- t/ClassSource.t | 4 +- t/Context.t | 138 +- t/Contract.t | 4 +- t/CookieManager.t | 110 +- t/Creators.t | 64 +- t/DateUtils.t | 246 +- t/EdiInvoice.t | 28 +- t/Edifact.t | 34 +- t/Ediorder.t | 43 +- t/Ediordrsp.t | 27 +- t/External/BakerTaylor.t | 32 +- t/External/Syndetics.t | 4 +- t/Form_MessagingPreferences.t | 4 +- t/HtmlTags.t | 11 +- t/ImportBatch.t | 39 +- t/Installer_PerlModules.t | 24 +- t/ItemCirculationAlertPreference.t | 4 +- t/Koha/Auth/Permissions.t | 4 +- t/Koha/Authority/ControlledIndicators.t | 154 +- t/Koha/Config.t | 232 +- t/Koha/Database/Columns.t | 4 +- t/Koha/Email.t | 139 +- t/Koha/Exceptions.t | 205 +- t/Koha/I18N.t | 74 +- t/Koha/Middleware/RealIP.t | 114 +- t/Koha/Object/Message.t | 27 +- t/Koha/Plugins/Tab.t | 6 +- t/Koha/REST/Plugin/Query.t | 359 +- t/Koha/Result/Boolean.t | 84 +- t/Koha/Script.t | 9 +- .../SearchEngine/Elasticsearch/QueryBuilder.t | 175 +- t/Koha/SearchEngine/Elasticsearch/Search.t | 6 +- t/Koha/SearchEngine/Search.t | 78 +- t/Koha/SearchEngine/Zebra/QueryBuilder.t | 38 +- t/Koha/Util/MARC.t | 64 +- t/Koha/Util/Navigation.t | 37 +- t/Koha/Util/Normalize.t | 25 +- t/Koha/Z3950responder.t | 4 +- t/Koha/sleep.pl | 2 +- t/Koha/wait.pl | 4 +- t/Koha_MetadataRecord.t | 100 +- t/Koha_SearchEngine_Elasticsearch_Browse.t | 66 +- t/Koha_Template_Plugin_HtmlId.t | 7 +- t/Koha_Template_Plugin_Koha.t | 81 +- t/Koha_Util_FrameworkPlugin.t | 12 +- t/Koha_Util_MARC.t | 27 +- t/Koha_XSLT_HTTPS.t | 22 +- t/Labels.t | 52 +- t/Labels_split_Regex.t | 12 +- t/Labels_split_ccn.t | 35 +- t/Labels_split_ddcn.t | 29 +- t/Labels_split_lccn.t | 27 +- t/Languages.t | 32 +- t/Logger.t | 29 +- t/Makefile.t | 6 +- t/Members_Messaging.t | 4 +- t/Number/Price.t | 185 +- t/OpenLibrarySearch.t | 2 +- t/Output.t | 48 +- t/Output_JSONStream.t | 30 +- t/Patroncards.t | 4 +- t/Patroncards_Batch.t | 4 +- t/Patroncards_Lib.t | 4 +- t/Patroncards_Patroncard.t | 4 +- t/Patroncards_Profile.t | 4 +- t/Patroncards_Template.t | 4 +- t/RecordProcessor.t | 89 +- t/Ris.t | 10 +- t/SIP/Sip.t | 30 +- t/Scheduler.t | 14 +- t/Scrubber.t | 46 +- t/Search.t | 174 +- t/Search/History.t | 32 +- t/Search/buildQuery.t | 457 +- t/Search_PazPar2.t | 30 +- t/Serials/GetNextSeq.t | 362 +- t/Serials/ModSerialStatus.t | 16 +- t/SimpleMARC.t | 597 +- t/SuggestionEngine.t | 41 +- t/SuggestionEngine_AuthorityFile.t | 48 +- t/Test/Dates.t | 20 +- t/TmplToken.t | 41 +- t/Token.t | 98 +- t/cypress/plugins/index.js | 12 +- t/cypress/plugins/mockData.js | 11 +- t/cypress/support/e2e.js | 777 +- t/db_dependent/00-strict.t | 8 +- t/db_dependent/Accounts.t | 963 +- t/db_dependent/Acquisition.t | 871 +- t/db_dependent/Acquisition/CancelReceipt.t | 78 +- .../Acquisition/FillWithDefaultValues.t | 19 +- t/db_dependent/Acquisition/GetBasketAsCSV.t | 93 +- .../Acquisition/GetBasketGroupAsCSV.t | 44 +- .../Acquisition/GetBasketsInfosByBookseller.t | 167 +- .../Acquisition/GetOrdersByBiblionumber.t | 48 +- t/db_dependent/Acquisition/Invoices.t | 150 +- t/db_dependent/Acquisition/NewOrder.t | 61 +- .../Acquisition/OrderFromSubscription.t | 128 +- t/db_dependent/Acquisition/OrderUsers.t | 95 +- t/db_dependent/Acquisition/StandingOrders.t | 118 +- t/db_dependent/Acquisition/TransferOrder.t | 117 +- .../Acquisition/close_reopen_basket.t | 88 +- .../Acquisition/populate_order_with_prices.t | 261 +- t/db_dependent/Amazon.t | 34 +- t/db_dependent/ArticleRequests.t | 96 +- t/db_dependent/AudioAlerts.t | 12 +- t/db_dependent/Auth.t | 559 +- t/db_dependent/Auth/haspermission.t | 34 +- t/db_dependent/AuthUtils.t | 46 +- t/db_dependent/Auth_with_cas.t | 64 +- t/db_dependent/Auth_with_ldap.t | 232 +- t/db_dependent/Auth_with_shibboleth.t | 255 +- t/db_dependent/AuthorisedValues.t | 114 +- t/db_dependent/AuthoritiesMarc.t | 222 +- t/db_dependent/AuthoritiesMarc/MARC21.t | 117 +- .../AuthoritiesMarc_GetTagsLabels.t | 22 +- t/db_dependent/Authority/Merge.t | 566 +- t/db_dependent/Authority/MergeRequests.t | 36 +- t/db_dependent/Authority/Subfields.t | 25 +- t/db_dependent/Authority/Tags.t | 23 +- t/db_dependent/Barcodes.t | 224 +- t/db_dependent/Barcodes_ValueBuilder.t | 70 +- t/db_dependent/Biblio.t | 750 +- t/db_dependent/Biblio/Isbd.t | 22 +- t/db_dependent/Biblio/MarcOverlayRules.t | 493 +- t/db_dependent/Biblio/ModBiblioMarc.t | 21 +- t/db_dependent/Biblio/TransformHtmlToMarc.t | 142 +- t/db_dependent/Biblio/TransformKohaToMarc.t | 141 +- t/db_dependent/Biblio/TransformMarcToKoha.t | 133 +- t/db_dependent/Biblio_holdsqueue.t | 46 +- t/db_dependent/Breeding.t | 222 +- t/db_dependent/Breeding_Auth.t | 6 +- t/db_dependent/Budgets.t | 1478 +- t/db_dependent/Budgets/CloneBudgetHierarchy.t | 25 +- t/db_dependent/Cache.t | 181 +- t/db_dependent/Calendar.t | 6 +- t/db_dependent/Charset.t | 42 +- t/db_dependent/Circulation.t | 3269 +-- t/db_dependent/Circulation/Branch.t | 252 +- t/db_dependent/Circulation/CalcDateDue.t | 323 +- t/db_dependent/Circulation/CalcFine.t | 121 +- .../Circulation/CheckIfIssuedToPatron.t | 56 +- .../Circulation/CheckValidBarcode.t | 22 +- t/db_dependent/Circulation/GetHardDueDate.t | 32 +- .../Circulation/GetPendingOnSiteCheckouts.t | 39 +- t/db_dependent/Circulation/GetTopIssues.t | 127 +- t/db_dependent/Circulation/IsItemIssued.t | 45 +- .../Circulation/MarkIssueReturned.t | 102 +- .../Circulation/NoIssuesChargeGuarantees.t | 16 +- .../Circulation/OfflineCirculation.t | 4 +- t/db_dependent/Circulation/OfflineOperation.t | 49 +- t/db_dependent/Circulation/ReturnClaims.t | 44 +- t/db_dependent/Circulation/Returns.t | 301 +- .../Circulation/StoreLastBorrower.t | 28 +- .../Circulation/SwitchOnSiteCheckouts.t | 74 +- t/db_dependent/Circulation/TooMany.t | 364 +- .../Circulation/_CalculateAndUpdateFine.t | 103 +- t/db_dependent/Circulation/dateexpiry.t | 60 +- t/db_dependent/Circulation/issue.t | 368 +- .../Circulation/maxsuspensiondays.t | 112 +- t/db_dependent/Circulation/transferbook.t | 305 +- t/db_dependent/Circulation/transfers.t | 106 +- t/db_dependent/Circulation_holdsqueue.t | 31 +- t/db_dependent/Clubs.t | 109 +- t/db_dependent/Context.t | 115 +- t/db_dependent/Contract.t | 98 +- t/db_dependent/CourseReserves.t | 44 +- t/db_dependent/CourseReserves/CourseItems.t | 429 +- t/db_dependent/Creators/Lib.t | 563 +- t/db_dependent/DecreaseLoanHighHolds.t | 141 +- t/db_dependent/Exporter/Record.t | 194 +- t/db_dependent/Filter_MARC_ViewPolicy.t | 78 +- t/db_dependent/Fines.t | 10 +- t/db_dependent/FrameworkPlugin.t | 225 +- t/db_dependent/Heading.t | 192 +- t/db_dependent/Heading_MARC21.t | 28 +- t/db_dependent/Hold.t | 200 +- t/db_dependent/Holds.t | 1075 +- t/db_dependent/Holds/ExpireReservesAutoFill.t | 105 +- t/db_dependent/Holds/HoldFulfillmentPolicy.t | 118 +- t/db_dependent/Holds/HoldItemtypeLimit.t | 82 +- t/db_dependent/Holds/LocalHoldsPriority.t | 134 +- t/db_dependent/Holds/RevertWaitingStatus.t | 29 +- t/db_dependent/Holds/WaitingReserves.t | 284 +- t/db_dependent/HoldsQueue.t | 1223 +- t/db_dependent/Holidays.t | 69 +- t/db_dependent/ILSDI_Services.t | 790 +- t/db_dependent/ImportBatch.t | 287 +- t/db_dependent/ImportExportFramework.t | 65 +- t/db_dependent/Installer.t | 42 +- t/db_dependent/Items.t | 652 +- .../Items/AutomaticItemModificationByAge.t | 151 +- t/db_dependent/Items/GetItemsForInventory.t | 106 +- t/db_dependent/Koha.t | 165 +- t/db_dependent/Koha/Account.t | 697 +- t/db_dependent/Koha/Account/DebitType.t | 24 +- t/db_dependent/Koha/Account/DebitTypes.t | 16 +- t/db_dependent/Koha/Account/Line.t | 807 +- t/db_dependent/Koha/Account/Lines.t | 112 +- t/db_dependent/Koha/Account/Offsets.t | 47 +- t/db_dependent/Koha/Acquisition/Basket.t | 184 +- t/db_dependent/Koha/Acquisition/Baskets.t | 41 +- t/db_dependent/Koha/Acquisition/Booksellers.t | 44 +- t/db_dependent/Koha/Acquisition/Budgets.t | 31 +- t/db_dependent/Koha/Acquisition/Currencies.t | 43 +- t/db_dependent/Koha/Acquisition/Fund.t | 19 +- t/db_dependent/Koha/Acquisition/Funds.t | 6 +- t/db_dependent/Koha/Acquisition/Invoice.t | 12 +- .../Koha/Acquisition/Invoice/Adjustments.t | 72 +- t/db_dependent/Koha/Acquisition/Order.t | 306 +- t/db_dependent/Koha/Acquisition/Orders.t | 36 +- t/db_dependent/Koha/ActionLogs.t | 39 +- t/db_dependent/Koha/AdditionalContents.t | 240 +- t/db_dependent/Koha/AdditionalField.t | 46 +- t/db_dependent/Koha/ApiKey.t | 42 +- t/db_dependent/Koha/ArticleRequest.t | 22 +- t/db_dependent/Koha/ArticleRequests.t | 14 +- t/db_dependent/Koha/Auth/Client.t | 161 +- t/db_dependent/Koha/Auth/Identity/Provider.t | 34 +- t/db_dependent/Koha/Auth/TwoFactorAuth.t | 58 +- t/db_dependent/Koha/Authorities.t | 151 +- t/db_dependent/Koha/BackgroundJob.t | 92 +- .../Koha/BackgroundJob/BatchUpdateAuthority.t | 3 +- .../BatchUpdateBiblioHoldsQueue.t | 5 +- .../CreateEHoldingsFromBiblios.t | 18 +- .../Koha/BackgroundJob/ImportKBARTFile.t | 8 +- .../BackgroundJob/MARCImportCommitBatch.t | 7 +- .../BackgroundJob/MARCImportRevertBatch.t | 7 +- .../Koha/BackgroundJob/StageMARCForImport.t | 2 +- .../Koha/BackgroundJob/UpdateElasticIndex.t | 7 +- t/db_dependent/Koha/BackgroundJobs.t | 42 +- .../Koha/BackgroundJobs/BatchDeleteBiblio.t | 32 +- .../Koha/BackgroundJobs/BatchDeleteItem.t | 17 +- .../Koha/BackgroundJobs/BatchUpdateBiblio.t | 13 +- .../Koha/BackgroundJobs/StageMARCForImport.t | 2 +- t/db_dependent/Koha/Biblio.t | 664 +- t/db_dependent/Koha/Biblio/ItemGroups.t | 28 +- t/db_dependent/Koha/Biblio/Metadata.t | 95 +- t/db_dependent/Koha/Biblio/host_record.t | 39 +- t/db_dependent/Koha/BiblioFrameworks.t | 25 +- t/db_dependent/Koha/Biblios.t | 227 +- t/db_dependent/Koha/Cash/Register.t | 146 +- t/db_dependent/Koha/Cash/Register/Action.t | 25 +- t/db_dependent/Koha/Cash/Register/Cashup.t | 139 +- t/db_dependent/Koha/Cash/Register/Cashups.t | 7 +- t/db_dependent/Koha/Charges/Fees.t | 121 +- t/db_dependent/Koha/Charges/Sales.t | 97 +- t/db_dependent/Koha/Checkout.t | 32 +- t/db_dependent/Koha/Checkouts.t | 170 +- t/db_dependent/Koha/Checkouts/Renewal.t | 77 +- t/db_dependent/Koha/Checkouts/ReturnClaim.t | 135 +- t/db_dependent/Koha/CirculationRules.t | 750 +- .../guess_article_requestable_itemtypes.t | 56 +- t/db_dependent/Koha/Cities.t | 32 +- t/db_dependent/Koha/ClassSortRules.t | 38 +- t/db_dependent/Koha/ClassSources.t | 47 +- t/db_dependent/Koha/ClassSplitRules.t | 14 +- t/db_dependent/Koha/Club/Enrollment.t | 13 +- t/db_dependent/Koha/Club/Hold.t | 44 +- t/db_dependent/Koha/Config/SysPrefs.t | 16 +- t/db_dependent/Koha/CoverImages.t | 25 +- t/db_dependent/Koha/CsvProfiles.t | 42 +- t/db_dependent/Koha/CurbsidePickups.t | 123 +- t/db_dependent/Koha/Database.t | 10 +- t/db_dependent/Koha/Database/Commenter.t | 52 +- t/db_dependent/Koha/Desks.t | 28 +- t/db_dependent/Koha/ERM/Agreements.t | 18 +- .../Koha/ERM/EUsage/UsageDataProvider.t | 8 +- t/db_dependent/Koha/Edifact/Order.t | 178 +- t/db_dependent/Koha/Encryption.t | 6 +- t/db_dependent/Koha/Filter/EmbedItems.t | 12 +- .../Koha/Filter/EmbedItemsAvailability.t | 43 +- .../Koha/Filter/ExpandCodedFields.t | 45 +- t/db_dependent/Koha/Hold.t | 351 +- t/db_dependent/Koha/Holds.t | 551 +- t/db_dependent/Koha/ILL/Request/Config.t | 322 +- t/db_dependent/Koha/ILL/Request/Logger.t | 57 +- .../Koha/ILL/Request/SupplierUpdate.t | 29 +- .../ILL/Request/SupplierUpdateProcessor.t | 3 +- .../Koha/ILL/Request/Workflow/Availability.t | 28 +- .../ILL/Request/Workflow/TypeDisclaimer.t | 26 +- t/db_dependent/Koha/ILL/Requests.t | 2194 +- t/db_dependent/Koha/Import/Record/Auths.t | 14 +- t/db_dependent/Koha/Import/Record/Biblios.t | 24 +- t/db_dependent/Koha/Import/Record/Items.t | 14 +- t/db_dependent/Koha/Import/Record/Matches.t | 31 +- t/db_dependent/Koha/Import/Records.t | 150 +- t/db_dependent/Koha/Item.t | 1277 +- t/db_dependent/Koha/Item/Attributes.t | 45 +- t/db_dependent/Koha/Item/Search/Field.t | 33 +- t/db_dependent/Koha/Item/Template.t | 5 +- t/db_dependent/Koha/Item/Templates.t | 4 +- t/db_dependent/Koha/Item/Transfer.t | 70 +- t/db_dependent/Koha/Item/Transfers.t | 47 +- t/db_dependent/Koha/ItemTypes.t | 53 +- t/db_dependent/Koha/Items.t | 983 +- t/db_dependent/Koha/Items/BatchUpdate.t | 209 +- t/db_dependent/Koha/KeyboardShortcuts.t | 10 +- t/db_dependent/Koha/Libraries.t | 327 +- t/db_dependent/Koha/Library.t | 68 +- t/db_dependent/Koha/Library/OverDriveInfos.t | 36 +- t/db_dependent/Koha/MarcSubfieldStructures.t | 36 +- t/db_dependent/Koha/Notice_Util.t | 115 +- t/db_dependent/Koha/Notices.t | 51 +- .../Koha/Object/Mixin/AdditionalFields.t | 40 +- t/db_dependent/Koha/Objects.t | 697 +- .../Koha/Objects/Mixin/AdditionalFields.t | 197 +- t/db_dependent/Koha/Old.t | 17 +- t/db_dependent/Koha/Old/Checkout.t | 32 +- t/db_dependent/Koha/Old/Checkouts.t | 46 +- t/db_dependent/Koha/Old/Hold.t | 30 +- t/db_dependent/Koha/Old/Holds.t | 53 +- t/db_dependent/Koha/Patron.t | 714 +- t/db_dependent/Koha/Patron/Attribute.t | 169 +- t/db_dependent/Koha/Patron/Attribute/Types.t | 129 +- t/db_dependent/Koha/Patron/Categories.t | 137 +- t/db_dependent/Koha/Patron/Category.t | 112 +- t/db_dependent/Koha/Patron/Consents.t | 26 +- t/db_dependent/Koha/Patron/Images.t | 26 +- .../Patron/MessagePreference/Attributes.t | 60 +- .../MessagePreference/Transport/Preferences.t | 153 +- .../MessagePreference/Transport/Types.t | 19 +- .../Patron/MessagePreference/Transports.t | 79 +- .../Koha/Patron/MessagePreferences.t | 1295 +- t/db_dependent/Koha/Patron/Messages.t | 91 +- t/db_dependent/Koha/Patron/Modifications.t | 361 +- t/db_dependent/Koha/Patron/Relationship.t | 41 +- t/db_dependent/Koha/Patron/Restriction/Type.t | 14 +- t/db_dependent/Koha/Patron_generate_userid.t | 68 +- t/db_dependent/Koha/Patrons.t | 1695 +- t/db_dependent/Koha/Patrons/Import.t | 24 +- t/db_dependent/Koha/Plugins/Account_hooks.t | 9 +- t/db_dependent/Koha/Plugins/BackgroundJob.t | 8 +- .../Koha/Plugins/Barcode_transform_hooks.t | 13 +- .../Plugins/Biblio_and_Items_plugin_hooks.t | 29 +- .../Koha/Plugins/Circulation_hooks.t | 25 +- t/db_dependent/Koha/Plugins/Holds_hooks.t | 58 +- t/db_dependent/Koha/Plugins/Patron.t | 17 +- t/db_dependent/Koha/Plugins/Plugins.t | 214 +- t/db_dependent/Koha/Plugins/Recall_hooks.t | 63 +- t/db_dependent/Koha/Plugins/authority_hooks.t | 16 +- t/db_dependent/Koha/Quotes.t | 94 +- t/db_dependent/Koha/REST/Plugin/Auth/IdP.t | 40 +- t/db_dependent/Koha/REST/Plugin/Objects.t | 561 +- t/db_dependent/Koha/REST/Plugin/Pagination.t | 259 +- .../Koha/REST/Plugin/PluginRoutes.t | 73 +- t/db_dependent/Koha/REST/V1.t | 9 +- t/db_dependent/Koha/Ratings.t | 28 +- t/db_dependent/Koha/Recall.t | 199 +- t/db_dependent/Koha/Recalls.t | 208 +- t/db_dependent/Koha/Reports.t | 73 +- t/db_dependent/Koha/Reviews.t | 80 +- t/db_dependent/Koha/SMS_Providers.t | 38 +- t/db_dependent/Koha/SMTP/Server.t | 23 +- t/db_dependent/Koha/SMTP/Servers.t | 20 +- .../Koha/SearchEngine/Elasticsearch.t | 1086 +- .../SearchEngine/Elasticsearch/ExportConfig.t | 94 +- .../SearchEngine/Elasticsearch/QueryBuilder.t | 777 +- .../Koha/SearchEngine/Elasticsearch/Reset.t | 38 +- .../Koha/SearchEngine/Elasticsearch/Search.t | 101 +- t/db_dependent/Koha/SearchEngine/Indexer.t | 388 +- t/db_dependent/Koha/SearchEngine/Search.t | 16 +- .../Koha/SearchEngine/Zebra/QueryBuilder.t | 187 +- t/db_dependent/Koha/SearchField.t | 188 +- t/db_dependent/Koha/SharedContent.t | 301 +- t/db_dependent/Koha/Subscription.t | 74 +- .../Koha/Subscription/Numberpatterns.t | 94 +- .../Koha/Subscription/Routinglists.t | 34 +- t/db_dependent/Koha/Suggestion.t | 6 +- t/db_dependent/Koha/Suggestions.t | 164 +- t/db_dependent/Koha/Tags.t | 6 +- t/db_dependent/Koha/Tags/Approvals.t | 6 +- t/db_dependent/Koha/Tags/Indexes.t | 6 +- t/db_dependent/Koha/Template/Plugin/Asset.t | 70 +- .../Koha/Template/Plugin/ClassSources.t | 70 +- .../Koha/Template/Plugin/ItemTypes.t | 39 +- .../Koha/Template/Plugin/JSConsents.t | 2 +- .../Koha/Template/Plugin/KohaPlugins.t | 61 +- .../Koha/Template/Plugin/Registers.t | 127 +- .../Koha/Template/Plugin/TablesSettings.t | 12 +- t/db_dependent/Koha/Ticket.t | 93 +- t/db_dependent/Koha/Ticket/Update.t | 16 +- t/db_dependent/Koha/UI/Form/Builder/Biblio.t | 115 +- t/db_dependent/Koha/UI/Form/Builder/Item.t | 248 +- t/db_dependent/Koha/Virtualshelves.t | 52 +- t/db_dependent/Koha/XSLT/Base.t | 145 +- t/db_dependent/Koha/XSLT/Security.t | 47 +- .../Koha/Z3950Responder/GenericSession.t | 171 +- t/db_dependent/Koha/Z3950Responder/Session.t | 25 +- t/db_dependent/Koha/Z3950Responder/Session2.t | 63 +- .../Koha/Z3950Responder/ZebraSession.t | 150 +- t/db_dependent/Koha/Z3950Servers.t | 71 +- t/db_dependent/Koha_Database.t | 34 +- t/db_dependent/Koha_Elasticsearch.t | 172 +- .../Koha_ExternalContent_OverDrive.t | 26 +- .../Koha_MetadataRecord_Authority.t | 52 +- t/db_dependent/Koha_Misc_Files.t | 88 +- t/db_dependent/LDAP/test_ldap_add.pl | 122 +- t/db_dependent/Labels/t_Batch.t | 62 +- t/db_dependent/Labels/t_Layout.t | 53 +- t/db_dependent/Labels/t_Profile.t | 88 +- t/db_dependent/Labels/t_Template.t | 162 +- t/db_dependent/Languages.t | 89 +- t/db_dependent/Letters.t | 1101 +- t/db_dependent/Letters/GetLetterTemplates.t | 55 +- .../Letters/GetLettersAvailableForALibrary.t | 121 +- t/db_dependent/Letters/TemplateToolkit.t | 429 +- t/db_dependent/LibraryGroups.t | 112 +- t/db_dependent/Linker_Default.t | 95 +- t/db_dependent/Linker_FirstMatch.t | 21 +- t/db_dependent/Log.t | 108 +- t/db_dependent/MarcModificationTemplates.t | 786 +- t/db_dependent/Matcher.t | 453 +- t/db_dependent/Members.t | 506 +- t/db_dependent/Members/IssueSlip.t | 155 +- t/db_dependent/Members/Statistics.t | 7 +- t/db_dependent/Message.t | 29 +- t/db_dependent/MungeMarcPrice.t | 49 +- t/db_dependent/OAI/AndSets.t | 125 +- t/db_dependent/OAI/Server.t | 604 +- t/db_dependent/OAI/Sets.t | 540 +- t/db_dependent/Overdues.t | 263 +- t/db_dependent/Passwordrecovery.t | 163 +- t/db_dependent/Patron/Borrower_Debarments.t | 181 +- t/db_dependent/Patron/Borrower_Discharge.t | 159 +- t/db_dependent/Patron/Borrower_Files.t | 56 +- t/db_dependent/Patron/Borrower_PrevCheckout.t | 322 +- t/db_dependent/Patron/Housebound.t | 19 +- t/db_dependent/Patron/HouseboundProfiles.t | 36 +- t/db_dependent/Patron/HouseboundRoles.t | 57 +- t/db_dependent/Patron/HouseboundVisits.t | 23 +- t/db_dependent/Patron/Messages.t | 25 +- t/db_dependent/Patron/Messaging.t | 38 +- t/db_dependent/Patron/Relationships.t | 114 +- t/db_dependent/PatronLists.t | 32 +- t/db_dependent/Patrons.t | 327 +- t/db_dependent/Prices.t | 178 +- t/db_dependent/Record.t | 85 +- t/db_dependent/Record/Record.t | 104 +- t/db_dependent/Record/marcrecord2csv.t | 138 +- .../RecordProcessor_EmbedSeeFromHeadings.t | 70 +- t/db_dependent/Reports.t | 8 +- t/db_dependent/Reports/Guided.t | 372 +- t/db_dependent/Reserves.t | 1138 +- .../Reserves/AutoUnsuspendReserves.t | 86 +- .../Reserves/CancelExpiredReserves.t | 278 +- t/db_dependent/Reserves/GetReserveFee.t | 199 +- t/db_dependent/Reserves/MultiplePerRecord.t | 47 +- t/db_dependent/Reserves/ReserveSlip.t | 49 +- t/db_dependent/RotatingCollections.t | 202 +- t/db_dependent/SIP/ILS.t | 141 +- t/db_dependent/SIP/Message.t | 1318 +- t/db_dependent/SIP/Patron.t | 238 +- t/db_dependent/SIP/SIPServer.t | 27 +- t/db_dependent/SIP/Transaction.t | 18 +- t/db_dependent/Search.t | 1448 +- t/db_dependent/Search/History.t | 653 +- t/db_dependent/Serials.t | 496 +- t/db_dependent/Serials/Claims.t | 124 +- t/db_dependent/Serials/Frequency.t | 79 +- .../Serials/GetFictiveIssueNumber.t | 254 +- t/db_dependent/Serials/GetNextDate.t | 571 +- t/db_dependent/Serials/GetNextSeq.t | 369 +- t/db_dependent/Serials/Numberpattern.t | 81 +- t/db_dependent/Serials/ReNewSubscription.t | 130 +- t/db_dependent/Serials/updateClaim.t | 27 +- t/db_dependent/Serials_2.t | 339 +- t/db_dependent/Service.t | 4 +- t/db_dependent/ShelfBrowser.t | 186 +- t/db_dependent/Sitemapper.t | 11 +- t/db_dependent/SocialData.t | 26 +- t/db_dependent/StockRotationItems.t | 585 +- t/db_dependent/StockRotationRotas.t | 145 +- t/db_dependent/StockRotationStages.t | 299 +- .../SuggestionEngine_ExplodedTerms.t | 10 +- t/db_dependent/Suggestions.t | 573 +- t/db_dependent/TablesSettings.t | 45 +- t/db_dependent/Tags.t | 125 +- .../Template/Plugin/AdditionalContents.t | 2 +- .../Template/Plugin/AuthorisedValues.t | 61 +- t/db_dependent/Template/Plugin/Branches.t | 205 +- t/db_dependent/Template/Plugin/Categories.t | 36 +- .../Template/Plugin/CirculationRules.t | 45 +- t/db_dependent/Template/Plugin/Frameworks.t | 2 +- t/db_dependent/Template/Plugin/KohaDates.t | 19 +- t/db_dependent/Templates.t | 119 +- t/db_dependent/TestBuilder.t | 391 +- t/db_dependent/Upload.t | 301 +- t/db_dependent/UsageStats.t | 22 +- .../Utils/Datatables_Virtualshelves.t | 152 +- t/db_dependent/Virtualshelves.t | 1345 +- t/db_dependent/XISBN.t | 75 +- t/db_dependent/XSLT.t | 224 +- t/db_dependent/api/v1/acquisitions_baskets.t | 20 +- t/db_dependent/api/v1/acquisitions_funds.t | 82 +- t/db_dependent/api/v1/acquisitions_orders.t | 322 +- t/db_dependent/api/v1/acquisitions_vendors.t | 270 +- .../api/v1/advanced_editor_macros.t | 562 +- t/db_dependent/api/v1/article_requests.t | 60 +- t/db_dependent/api/v1/auth.t | 68 +- .../api/v1/auth_authenticate_api_request.t | 152 +- t/db_dependent/api/v1/auth_basic.t | 27 +- t/db_dependent/api/v1/authorised_values.t | 47 +- t/db_dependent/api/v1/authorities.t | 231 +- t/db_dependent/api/v1/biblios.t | 633 +- t/db_dependent/api/v1/bookings.t | 4 +- t/db_dependent/api/v1/cashups.t | 54 +- t/db_dependent/api/v1/checkouts.t | 233 +- t/db_dependent/api/v1/cities.t | 148 +- t/db_dependent/api/v1/clubs_holds.t | 198 +- t/db_dependent/api/v1/erm_agreements.t | 217 +- t/db_dependent/api/v1/erm_custom_reports.t | 2 +- t/db_dependent/api/v1/erm_documents.t | 30 +- .../api/v1/erm_eholdings_packages.t | 167 +- .../api/v1/erm_eholdings_resources.t | 58 +- t/db_dependent/api/v1/erm_eholdings_titles.t | 286 +- t/db_dependent/api/v1/erm_licenses.t | 217 +- t/db_dependent/api/v1/erm_users.t | 8 +- t/db_dependent/api/v1/holds.t | 693 +- t/db_dependent/api/v1/idp.t | 30 +- t/db_dependent/api/v1/ill_backends.t | 38 +- t/db_dependent/api/v1/ill_batchstatuses.t | 11 +- t/db_dependent/api/v1/ill_requests.t | 136 +- t/db_dependent/api/v1/import_batch_profiles.t | 109 +- t/db_dependent/api/v1/import_record_matches.t | 105 +- t/db_dependent/api/v1/item_groups.t | 215 +- t/db_dependent/api/v1/items.t | 380 +- t/db_dependent/api/v1/jobs.t | 56 +- t/db_dependent/api/v1/libraries.t | 216 +- t/db_dependent/api/v1/oauth.t | 110 +- t/db_dependent/api/v1/pagination.t | 152 +- t/db_dependent/api/v1/password_validation.t | 25 +- t/db_dependent/api/v1/patrons.t | 540 +- t/db_dependent/api/v1/patrons_accounts.t | 141 +- .../api/v1/patrons_extended_attributes.t | 324 +- t/db_dependent/api/v1/patrons_holds.t | 25 +- t/db_dependent/api/v1/patrons_password.t | 118 +- .../api/v1/patrons_password_expiration.t | 39 +- t/db_dependent/api/v1/patrons_recalls.t | 3 +- .../api/v1/preservation_Processings.t | 4 +- t/db_dependent/api/v1/query.t | 53 +- t/db_dependent/api/v1/return_claims.t | 60 +- t/db_dependent/api/v1/search_filters.t | 333 +- t/db_dependent/api/v1/smtp_servers.t | 134 +- t/db_dependent/api/v1/stockrotationstage.t | 94 +- t/db_dependent/api/v1/suggestions.t | 148 +- t/db_dependent/api/v1/ticket_updates.t | 141 +- t/db_dependent/api/v1/tickets.t | 119 +- t/db_dependent/api/v1/transfer_limits.t | 103 +- t/db_dependent/api/v1/two_factor_auth.t | 59 +- t/db_dependent/api/v1/unhandled_exceptions.t | 12 +- t/db_dependent/check_kohastructure.t | 7 +- t/db_dependent/check_sysprefs.t | 13 +- .../cronjobs/advance_notices_digest.t | 230 +- t/db_dependent/db_structure.t | 25 +- .../misc/translator/xgettext-installer.t | 15 +- .../misc/translator/xgettext-pref.t | 15 +- t/db_dependent/misc/translator/xgettext-tt2.t | 32 +- t/db_dependent/rollingloans.t | 28 +- t/db_dependent/selenium/00-onboarding.t | 59 +- t/db_dependent/selenium/01-installation.t | 59 +- .../selenium/administration_tasks.t | 140 +- t/db_dependent/selenium/authentication.t | 151 +- t/db_dependent/selenium/authentication_2fa.t | 134 +- t/db_dependent/selenium/basic_workflow.t | 208 +- .../selenium/batch_item_modification.t | 27 +- t/db_dependent/selenium/patrons_search.t | 293 +- t/db_dependent/selenium/regressions.t | 169 +- t/db_dependent/selenium/remove_from_cart.t | 51 +- t/db_dependent/selenium/self_registration.t | 19 +- .../selenium/system_preferences_search.t | 53 +- .../selenium/update_child_to_adult.t | 63 +- t/db_dependent/sysprefs.t | 8 +- t/db_dependent/www/auth_values_input_www.t | 111 +- t/db_dependent/www/batch.t | 50 +- t/db_dependent/www/history.t | 27 +- t/db_dependent/www/regressions.t | 92 +- t/db_dependent/www/rest_api.t | 14 +- t/db_dependent/www/search_utf8.t | 92 +- t/db_dependent/yaml.t | 2 +- t/db_dependent/zebra_config.pl | 36 +- t/etc/schema.pl | 7 +- t/lib/Bootstrap.pm | 21 +- t/lib/Dates.pm | 2 +- t/lib/IdP/ExternalIdP.pm | 244 +- t/lib/Koha/BackgroundJob/BatchTest.pm | 28 +- t/lib/Mocks.pm | 74 +- t/lib/Mocks/Logger.pm | 70 +- t/lib/Mocks/Zebra.pm | 107 +- t/lib/QA/TemplateFilters.pm | 89 +- t/lib/Selenium.pm | 80 +- t/lib/TestBuilder.pm | 419 +- .../bad_plugins/Koha/Plugin/BrokenInstall.pm | 2 +- .../bad_plugins/Koha/Plugin/BrokenUpgrade.pm | 2 +- t/lib/plugins/Koha/Plugin/BadAPIRoute.pm | 2 +- t/lib/plugins/Koha/Plugin/MarcFieldValues.pm | 40 +- t/lib/plugins/Koha/Plugin/Test.pm | 74 +- .../Koha/Plugin/TestItemBarcodeTransform.pm | 6 +- .../prog/en/includes/accounts.inc | 117 +- .../intranet-tmpl/prog/en/modules/about.tt | 2413 +- .../prog/fr-CA/includes/accounts.inc | 141 +- .../intranet-tmpl/prog/fr-CA/modules/about.tt | 2429 +- t/template_filters.t | 39 +- t/timezones.t | 11 +- tags/list.pl | 23 +- tags/review.pl | 177 +- tools/access_files.pl | 108 +- tools/additional-contents.pl | 80 +- tools/ajax-inventory.pl | 8 +- tools/automatic_item_modification_by_age.pl | 32 +- tools/batchMod.pl | 211 +- tools/batch_delete_records.pl | 77 +- tools/batch_extend_due_dates.pl | 75 +- tools/batch_record_modification.pl | 92 +- tools/batch_records_ajax.pl | 70 +- tools/cleanborrowers.pl | 128 +- tools/copy-holidays.pl | 15 +- tools/csv-profiles.pl | 30 +- tools/exceptionHolidays.pl | 172 +- tools/export.pl | 203 +- tools/holidays.pl | 115 +- tools/import_borrowers.pl | 57 +- tools/inventory.pl | 370 +- tools/letter.pl | 231 +- tools/manage-marc-import.pl | 361 +- tools/marc_modification_templates.pl | 119 +- tools/newHolidays.pl | 142 +- tools/overduerules.pl | 284 +- tools/page.pl | 18 +- tools/picture-upload.pl | 199 +- tools/problem-reports.pl | 16 +- tools/quotes-upload.pl | 8 +- tools/quotes.pl | 23 +- tools/scheduler.pl | 30 +- tools/showdiffmarc.pl | 46 +- tools/stage-marc-import.pl | 34 +- tools/stockrotation.pl | 227 +- tools/tools-home.pl | 26 +- tools/upload-cover-image.pl | 122 +- tools/upload-file.pl | 47 +- tools/upload.pl | 89 +- tools/viewlog.pl | 138 +- virtualshelves/addbybiblionumber.pl | 37 +- virtualshelves/downloadshelf.pl | 61 +- virtualshelves/sendshelf.pl | 23 +- virtualshelves/shelves.pl | 194 +- webpack.config.js | 81 +- xt/api.t | 8 +- xt/author/Text_CSV_Various.t | 60 +- xt/author/icondirectories.t | 34 +- xt/author/podcorrectness.t | 3 +- xt/author/show-template-structure.pl | 19 +- xt/author/valid-templates.t | 41 +- xt/check_makefile.t | 6 +- xt/find-license-problems.t | 30 +- xt/find-misplaced-executables.t | 9 +- xt/find-missing-csrf.t | 11 +- xt/find-missing-filters.t | 6 +- xt/find-missing-op-in-forms.t | 6 +- xt/single_quotes.t | 12 +- xt/verify-debian-docbook.t | 8 +- xt/verify_bib1.att.t | 4 +- xt/yaml_valid.pl | 3 +- xt/yaml_valid.t | 4 +- 3215 files changed, 264951 insertions(+), 236423 deletions(-) diff --git a/.prettierrc.js b/.prettierrc.js index f73eb183a8..56742a86de 100644 --- a/.prettierrc.js +++ b/.prettierrc.js @@ -17,7 +17,7 @@ module.exports = { trailingComma: "es5", arrowParens: "avoid", semi: false, - } + }, }, { files: ["*.tt", "*.inc"], @@ -29,4 +29,4 @@ module.exports = { }, }, ], -} +}; diff --git a/C4/Accounts.pm b/C4/Accounts.pm index ad4bd86d76..7e5973b0fd 100644 --- a/C4/Accounts.pm +++ b/C4/Accounts.pm @@ -17,7 +17,6 @@ package C4::Accounts; # You should have received a copy of the GNU General Public License # along with Koha; if not, see . - use Modern::Perl; use C4::Context; use C4::Stats; @@ -27,15 +26,14 @@ use Koha::Account::Lines; use Koha::Account::Offsets; use Koha::Items; - use vars qw(@ISA @EXPORT); BEGIN { require Exporter; @ISA = qw(Exporter); @EXPORT = qw( - chargelostitem - purge_zero_balance_fees + chargelostitem + purge_zero_balance_fees ); } @@ -69,25 +67,27 @@ FIXME : if no replacement price, borrower just doesn't get charged? sub chargelostitem { my $dbh = C4::Context->dbh(); - my ($borrowernumber, $itemnumber, $replacementprice, $description) = @_; + my ( $borrowernumber, $itemnumber, $replacementprice, $description ) = @_; my $item = Koha::Items->find($itemnumber); my $itype = $item->itemtype; $replacementprice //= 0; - my $defaultreplacecost = $itype->defaultreplacecost; - my $processfee = $itype->processfee; + my $defaultreplacecost = $itype->defaultreplacecost; + my $processfee = $itype->processfee; my $usedefaultreplacementcost = C4::Context->preference("useDefaultReplacementCost"); - my $processingfeenote = C4::Context->preference("ProcessingFeeNote"); - if ($usedefaultreplacementcost && $replacementprice == 0 && $defaultreplacecost){ + my $processingfeenote = C4::Context->preference("ProcessingFeeNote"); + + if ( $usedefaultreplacementcost && $replacementprice == 0 && $defaultreplacecost ) { $replacementprice = $defaultreplacecost; } - my $checkout = Koha::Checkouts->find({ itemnumber => $itemnumber }); + my $checkout = Koha::Checkouts->find( { itemnumber => $itemnumber } ); if ( !$checkout && $item->in_bundle ) { my $host = $item->bundle_host; $checkout = $host->checkout; } my $issue_id = $checkout ? $checkout->issue_id : undef; - my $account = Koha::Account->new({ patron_id => $borrowernumber }); + my $account = Koha::Account->new( { patron_id => $borrowernumber } ); + # first make sure the borrower hasn't already been charged for this item (for this issuance) my $existing_charges = $account->lines->search( { @@ -99,8 +99,9 @@ sub chargelostitem { # OK, they haven't unless ($existing_charges) { + #add processing fee - if ($processfee && $processfee > 0){ + if ( $processfee && $processfee > 0 ) { my $accountline = $account->add_debit( { amount => $processfee, @@ -115,8 +116,9 @@ sub chargelostitem { } ); } + #add replace cost - if ($replacementprice > 0){ + if ( $replacementprice > 0 ) { my $accountline = $account->add_debit( { amount => $replacementprice, diff --git a/C4/Acquisition.pm b/C4/Acquisition.pm index f15de778e2..a81a6b9acd 100644 --- a/C4/Acquisition.pm +++ b/C4/Acquisition.pm @@ -17,16 +17,15 @@ package C4::Acquisition; # You should have received a copy of the GNU General Public License # along with Koha; if not, see . - use Modern::Perl; use Carp qw( carp croak ); use Text::CSV_XS; use C4::Context; use C4::Suggestions qw( GetSuggestion GetSuggestionFromBiblionumber ModSuggestion ); -use C4::Biblio qw( GetMarcFromKohaField GetMarcStructure IsMarcStructureInternal ); -use C4::Contract qw( GetContract ); -use C4::Log qw( logaction ); -use C4::Templates qw(gettemplate); +use C4::Biblio qw( GetMarcFromKohaField GetMarcStructure IsMarcStructureInternal ); +use C4::Contract qw( GetContract ); +use C4::Log qw( logaction ); +use C4::Templates qw(gettemplate); use Koha::DateUtils qw( dt_from_string ); use Koha::Acquisition::Baskets; use Koha::Acquisition::Booksellers; @@ -46,60 +45,56 @@ use C4::Koha; use MARC::Field; use JSON qw( to_json ); +our ( @ISA, @EXPORT_OK ); -our (@ISA, @EXPORT_OK); BEGIN { require Exporter; @ISA = qw(Exporter); @EXPORT_OK = qw( - GetBasket NewBasket ReopenBasket ModBasket - GetBasketAsCSV GetBasketGroupAsCSV - GetBasketsByBookseller GetBasketsByBasketgroup - GetBasketsInfosByBookseller + GetBasket NewBasket ReopenBasket ModBasket + GetBasketAsCSV GetBasketGroupAsCSV + GetBasketsByBookseller GetBasketsByBasketgroup + GetBasketsInfosByBookseller - GetBasketUsers ModBasketUsers - CanUserManageBasket + GetBasketUsers ModBasketUsers + CanUserManageBasket - ModBasketHeader + ModBasketHeader - ModBasketgroup NewBasketgroup DelBasketgroup GetBasketgroup CloseBasketgroup - GetBasketgroups ReOpenBasketgroup + ModBasketgroup NewBasketgroup DelBasketgroup GetBasketgroup CloseBasketgroup + GetBasketgroups ReOpenBasketgroup - ModOrder GetOrder GetOrders GetOrdersByBiblionumber - GetOrderFromItemnumber - SearchOrders GetHistory GetRecentAcqui - ModReceiveOrder CancelReceipt - TransferOrder - ModItemOrder + ModOrder GetOrder GetOrders GetOrdersByBiblionumber + GetOrderFromItemnumber + SearchOrders GetHistory GetRecentAcqui + ModReceiveOrder CancelReceipt + TransferOrder + ModItemOrder - GetInvoices - GetInvoice - GetInvoiceDetails - AddInvoice - ModInvoice - CloseInvoice - ReopenInvoice - DelInvoice - MergeInvoices + GetInvoices + GetInvoice + GetInvoiceDetails + AddInvoice + ModInvoice + CloseInvoice + ReopenInvoice + DelInvoice + MergeInvoices - AddClaim - GetBiblioCountByBasketno + AddClaim + GetBiblioCountByBasketno - GetOrderUsers - ModOrderUsers - NotifyOrderUsers + GetOrderUsers + ModOrderUsers + NotifyOrderUsers - FillWithDefaultValues + FillWithDefaultValues - get_rounded_price - get_rounding_sql + get_rounded_price + get_rounding_sql ); } - - - - sub GetOrderFromItemnumber { my ($itemnumber) = @_; my $dbh = C4::Context->dbh; @@ -111,12 +106,12 @@ sub GetOrderFromItemnumber { my $sth = $dbh->prepare($query); -# $sth->trace(3); + # $sth->trace(3); $sth->execute($itemnumber); my $order = $sth->fetchrow_hashref; - return ( $order ); + return ($order); } @@ -150,17 +145,17 @@ B informations for a given basket returned as a hashref. sub GetBasket { my ($basketno) = @_; my $dbh = C4::Context->dbh; - my $query = " + my $query = " SELECT aqbasket.*, concat( b.firstname,' ',b.surname) AS authorisedbyname FROM aqbasket LEFT JOIN borrowers b ON aqbasket.authorisedby=b.borrowernumber WHERE basketno=? "; - my $sth=$dbh->prepare($query); + my $sth = $dbh->prepare($query); $sth->execute($basketno); my $basket = $sth->fetchrow_hashref; - return ( $basket ); + return ($basket); } #------------------------------------------------------------# @@ -185,33 +180,35 @@ The other parameters are optional, see ModBasketHeader for more info on them. =cut sub NewBasket { - my ( $booksellerid, $authorisedby, $basketname, $basketnote, + my ( + $booksellerid, $authorisedby, $basketname, $basketnote, $basketbooksellernote, $basketcontractnumber, $deliveryplace, - $billingplace, $is_standing, $create_items ) = @_; - my $dbh = C4::Context->dbh; - my $query = - 'INSERT INTO aqbasket (creationdate,booksellerid,authorisedby) ' - . 'VALUES (now(),?,?)'; + $billingplace, $is_standing, $create_items + ) = @_; + my $dbh = C4::Context->dbh; + my $query = 'INSERT INTO aqbasket (creationdate,booksellerid,authorisedby) ' . 'VALUES (now(),?,?)'; $dbh->do( $query, {}, $booksellerid, $authorisedby ); my $basket = $dbh->{mysql_insertid}; - $basketname ||= q{}; # default to empty strings + $basketname ||= q{}; # default to empty strings $basketnote ||= q{}; $basketbooksellernote ||= q{}; # Log the basket creation - if (C4::Context->preference("AcquisitionLog")) { - my $created = Koha::Acquisition::Baskets->find( $basket ); + if ( C4::Context->preference("AcquisitionLog") ) { + my $created = Koha::Acquisition::Baskets->find($basket); logaction( 'ACQUISITIONS', 'ADD_BASKET', $basket, - to_json($created->unblessed) + to_json( $created->unblessed ) ); } - ModBasketHeader( $basket, $basketname, $basketnote, $basketbooksellernote, - $basketcontractnumber, $booksellerid, $deliveryplace, $billingplace, $is_standing, $create_items ); + ModBasketHeader( + $basket, $basketname, $basketnote, $basketbooksellernote, + $basketcontractnumber, $booksellerid, $deliveryplace, $billingplace, $is_standing, $create_items + ); return $basket; } @@ -226,24 +223,26 @@ reopen a basket sub ReopenBasket { my ($basketno) = @_; - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; $dbh->do( q{UPDATE aqbasket SET closedate=NULL WHERE basketno=?}, {}, $basketno ); - $dbh->do( q{ + $dbh->do( + q{ UPDATE aqorders SET orderstatus = 'new' WHERE basketno = ? AND orderstatus NOT IN ( 'complete', 'cancelled' ) - }, {}, $basketno); + }, {}, $basketno + ); # Log the basket reopening - if (C4::Context->preference("AcquisitionLog")) { - my $reopened = Koha::Acquisition::Baskets->find( $basketno ); + if ( C4::Context->preference("AcquisitionLog") ) { + my $reopened = Koha::Acquisition::Baskets->find($basketno); logaction( 'ACQUISITIONS', 'REOPEN_BASKET', $basketno, - to_json($reopened->unblessed) + to_json( $reopened->unblessed ) ); } return; @@ -262,18 +261,16 @@ $cgi parameter is needed for column name translation =cut sub GetBasketAsCSV { - my ($basketno, $cgi, $csv_profile_id) = @_; - my $basket = GetBasket($basketno); - my @orders = GetOrders($basketno); - my $contract = GetContract({ - contractnumber => $basket->{'contractnumber'} - }); + my ( $basketno, $cgi, $csv_profile_id ) = @_; + my $basket = GetBasket($basketno); + my @orders = GetOrders($basketno); + my $contract = GetContract( { contractnumber => $basket->{'contractnumber'} } ); - my $template = C4::Templates::gettemplate("acqui/csv/basket.tt", "intranet", $cgi); + my $template = C4::Templates::gettemplate( "acqui/csv/basket.tt", "intranet", $cgi ); my @rows; if ($csv_profile_id) { - my $csv_profile = Koha::CsvProfiles->find( $csv_profile_id ); - Koha::Exceptions::ObjectNotFound->throw( 'There is no valid csv profile given') unless $csv_profile; + my $csv_profile = Koha::CsvProfiles->find($csv_profile_id); + Koha::Exceptions::ObjectNotFound->throw('There is no valid csv profile given') unless $csv_profile; my $delimiter = $csv_profile->csv_separator; $delimiter = "\t" if $delimiter eq "\\t"; @@ -288,45 +285,46 @@ sub GetBasketAsCSV { ); my $csv_profile_content = $csv_profile->content; my ( @headers, @fields ); - while ( $csv_profile_content =~ / + while ( + $csv_profile_content =~ / ([^=\|]+) # header =? ([^\|]*) # fieldname (table.row or row) \|? /gxms - ) { + ) + { my $header = $1; - my $field = ($2 eq '') ? $1 : $2; + my $field = ( $2 eq '' ) ? $1 : $2; - $header =~ s/^\s+|\s+$//g; # Trim whitespaces + $header =~ s/^\s+|\s+$//g; # Trim whitespaces push @headers, $header; - $field =~ s/[^\.]*\.{1}//; # Remove the table name if exists. - $field =~ s/^\s+|\s+$//g; # Trim whitespaces + $field =~ s/[^\.]*\.{1}//; # Remove the table name if exists. + $field =~ s/^\s+|\s+$//g; # Trim whitespaces push @fields, $field; } for my $order (@orders) { my @row; - my $biblio = Koha::Biblios->find( $order->{biblionumber} ); + my $biblio = Koha::Biblios->find( $order->{biblionumber} ); my $biblioitem = $biblio->biblioitem; $order = { %$order, %{ $biblioitem->unblessed } }; if ($contract) { - $order = {%$order, %$contract}; + $order = { %$order, %$contract }; } - $order = {%$order, %$basket, %{ $biblio->unblessed }}; + $order = { %$order, %$basket, %{ $biblio->unblessed } }; for my $field (@fields) { push @row, $order->{$field}; } push @rows, \@row; } my $content = join( $delimiter, @headers ) . "\n"; - for my $row ( @rows ) { + for my $row (@rows) { $csv->combine(@$row); my $string = $csv->string; $content .= $string . "\n"; } return $content; - } - else { + } else { foreach my $order (@orders) { my $biblio = Koha::Biblios->find( $order->{biblionumber} ); my $biblioitem; @@ -347,34 +345,36 @@ sub GetBasketAsCSV { quantity => $order->{'quantity'}, rrp => $order->{'rrp'}, }; - for my $place ( qw( deliveryplace billingplace ) ) { + for my $place (qw( deliveryplace billingplace )) { if ( my $library = Koha::Libraries->find( $row->{deliveryplace} ) ) { - $row->{$place} = $library->branchname + $row->{$place} = $library->branchname; } } - foreach(qw( + foreach ( + qw( contractname author title publishercode collectiontitle notes deliveryplace billingplace - ) ) { + ) + ) + { # Double the quotes to not be interpreted as a field end $row->{$_} =~ s/"/""/g if $row->{$_}; } push @rows, $row; - } + } @rows = sort { - if(defined $a->{publishercode} and defined $b->{publishercode}) { + if ( defined $a->{publishercode} and defined $b->{publishercode} ) { $a->{publishercode} cmp $b->{publishercode}; } } @rows; - $template->param(rows => \@rows); + $template->param( rows => \@rows ); return $template->output; } } - =head3 GetBasketGroupAsCSV &GetBasketGroupAsCSV($basketgroupid); @@ -386,18 +386,16 @@ $cgi parameter is needed for column name translation =cut sub GetBasketGroupAsCSV { - my ($basketgroupid, $cgi) = @_; + my ( $basketgroupid, $cgi ) = @_; my $baskets = GetBasketsByBasketgroup($basketgroupid); - my $template = C4::Templates::gettemplate('acqui/csv/basketgroup.tt', 'intranet', $cgi); + my $template = C4::Templates::gettemplate( 'acqui/csv/basketgroup.tt', 'intranet', $cgi ); my @rows; for my $basket (@$baskets) { - my @orders = GetOrders( $basket->{basketno} ); - my $contract = GetContract({ - contractnumber => $basket->{contractnumber} - }); - my $bookseller = Koha::Acquisition::Booksellers->find( $basket->{booksellerid} ); + my @orders = GetOrders( $basket->{basketno} ); + my $contract = GetContract( { contractnumber => $basket->{contractnumber} } ); + my $bookseller = Koha::Acquisition::Booksellers->find( $basket->{booksellerid} ); my $basketgroup = GetBasketgroup( $$basket{basketgroupid} ); foreach my $order (@orders) { @@ -436,24 +434,29 @@ sub GetBasketGroupAsCSV { basketdeliveryplace => $basket->{deliveryplace}, basketbillingplace => $basket->{billingplace}, }; - for my $place (qw( basketgroupdeliveryplace basketgroupbillingplace basketdeliveryplace basketbillingplace )) { + for my $place ( + qw( basketgroupdeliveryplace basketgroupbillingplace basketdeliveryplace basketbillingplace )) + { if ( my $library = Koha::Libraries->find( $temp->{$place} ) ) { $row->{$place} = $library->branchname; } } - foreach(qw( + foreach ( + qw( basketname author title publishercode collectiontitle notes booksellername bookselleraddress booksellerpostal contractname basketgroupdeliveryplace basketgroupbillingplace basketdeliveryplace basketbillingplace - ) ) { + ) + ) + { # Double the quotes to not be interpreted as a field end $row->{$_} =~ s/"/""/g if $row->{$_}; } push @rows, $row; - } - } - $template->param(rows => \@rows); + } + } + $template->param( rows => \@rows ); return $template->output; @@ -469,12 +472,12 @@ close a basketgroup sub CloseBasketgroup { my ($basketgroupno) = @_; - my $dbh = C4::Context->dbh; - my $sth = $dbh->prepare(" + my $dbh = C4::Context->dbh; + my $sth = $dbh->prepare( " UPDATE aqbasketgroups SET closed=1 WHERE id=? - "); + " ); $sth->execute($basketgroupno); } @@ -490,12 +493,12 @@ reopen a basketgroup sub ReOpenBasketgroup { my ($basketgroupno) = @_; - my $dbh = C4::Context->dbh; - my $sth = $dbh->prepare(" + my $dbh = C4::Context->dbh; + my $sth = $dbh->prepare( " UPDATE aqbasketgroups SET closed=0 WHERE id=? - "); + " ); $sth->execute($basketgroupno); } @@ -517,36 +520,35 @@ Modifies a basket, using a hashref $basketinfo for the relevant information, onl sub ModBasket { my $basketinfo = shift; - my $query = "UPDATE aqbasket SET "; + my $query = "UPDATE aqbasket SET "; my @params; - foreach my $key (keys %$basketinfo){ - if ($key ne 'basketno'){ + foreach my $key ( keys %$basketinfo ) { + if ( $key ne 'basketno' ) { $query .= "$key=?, "; - push(@params, $basketinfo->{$key} || undef ); + push( @params, $basketinfo->{$key} || undef ); } } -# get rid of the "," at the end of $query - if (substr($query, length($query)-2) eq ', '){ + + # get rid of the "," at the end of $query + if ( substr( $query, length($query) - 2 ) eq ', ' ) { chop($query); chop($query); $query .= ' '; } $query .= "WHERE basketno=?"; - push(@params, $basketinfo->{'basketno'}); + push( @params, $basketinfo->{'basketno'} ); my $dbh = C4::Context->dbh; my $sth = $dbh->prepare($query); $sth->execute(@params); # Log the basket update - if (C4::Context->preference("AcquisitionLog")) { - my $modified = Koha::Acquisition::Baskets->find( - $basketinfo->{basketno} - ); + if ( C4::Context->preference("AcquisitionLog") ) { + my $modified = Koha::Acquisition::Baskets->find( $basketinfo->{basketno} ); logaction( 'ACQUISITIONS', 'MODIFY_BASKET', $basketinfo->{basketno}, - to_json($modified->unblessed) + to_json( $modified->unblessed ) ); } @@ -589,7 +591,10 @@ case the AcqCreateItem syspref takes precedence). =cut sub ModBasketHeader { - my ($basketno, $basketname, $note, $booksellernote, $contractnumber, $booksellerid, $deliveryplace, $billingplace, $is_standing, $create_items) = @_; + my ( + $basketno, $basketname, $note, $booksellernote, $contractnumber, $booksellerid, $deliveryplace, $billingplace, + $is_standing, $create_items + ) = @_; $is_standing ||= 0; my $query = qq{ @@ -600,24 +605,25 @@ sub ModBasketHeader { my $dbh = C4::Context->dbh; my $sth = $dbh->prepare($query); - $sth->execute($basketname, $note, $booksellernote, $booksellerid, $deliveryplace, $billingplace, $is_standing, $create_items || undef, $basketno); + $sth->execute( + $basketname, $note, $booksellernote, $booksellerid, $deliveryplace, $billingplace, $is_standing, + $create_items || undef, $basketno + ); - if ( $contractnumber ) { - my $query2 ="UPDATE aqbasket SET contractnumber=? WHERE basketno=?"; - my $sth2 = $dbh->prepare($query2); - $sth2->execute($contractnumber,$basketno); + if ($contractnumber) { + my $query2 = "UPDATE aqbasket SET contractnumber=? WHERE basketno=?"; + my $sth2 = $dbh->prepare($query2); + $sth2->execute( $contractnumber, $basketno ); } # Log the basket update - if (C4::Context->preference("AcquisitionLog")) { - my $modified = Koha::Acquisition::Baskets->find( - $basketno - ); + if ( C4::Context->preference("AcquisitionLog") ) { + my $modified = Koha::Acquisition::Baskets->find($basketno); logaction( 'ACQUISITIONS', 'MODIFY_BASKET_HEADER', $basketno, - to_json($modified->unblessed) + to_json( $modified->unblessed ) ); } @@ -648,23 +654,23 @@ Returns a list of hashes of all the baskets that belong to bookseller 'bookselle =cut sub GetBasketsByBookseller { - my ($booksellerid, $extra) = @_; + my ( $booksellerid, $extra ) = @_; my $query = "SELECT * FROM aqbasket WHERE booksellerid=?"; - if ($extra){ - if ($extra->{groupby}) { + if ($extra) { + if ( $extra->{groupby} ) { $query .= " GROUP by $extra->{groupby}"; } - if ($extra->{orderby}){ + if ( $extra->{orderby} ) { $query .= " ORDER by $extra->{orderby}"; } - if ($extra->{limit}){ + if ( $extra->{limit} ) { $query .= " LIMIT $extra->{limit}"; } } my $dbh = C4::Context->dbh; my $sth = $dbh->prepare($query); $sth->execute($booksellerid); - return $sth->fetchall_arrayref({}); + return $sth->fetchall_arrayref( {} ); } =head3 GetBasketsInfosByBookseller @@ -683,11 +689,11 @@ Returns in a arrayref of hashref all about booksellers baskets, plus: =cut sub GetBasketsInfosByBookseller { - my ($supplierid, $allbaskets) = @_; + my ( $supplierid, $allbaskets ) = @_; return unless $supplierid; - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $query = q{ SELECT aqbasket.basketno, aqbasket.basketname, aqbasket.note, aqbasket.booksellernote, aqbasket.contractnumber, aqbasket.creationdate, aqbasket.closedate, aqbasket.booksellerid, aqbasket.authorisedby, aqbasket.booksellerinvoicenumber, aqbasket.basketgroupid, aqbasket.deliveryplace, aqbasket.billingplace, aqbasket.branch, aqbasket.is_standing, aqbasket.create_items, SUM(aqorders.quantity) AS total_items, @@ -706,11 +712,13 @@ sub GetBasketsInfosByBookseller { LEFT JOIN aqorders ON aqorders.basketno = aqbasket.basketno WHERE booksellerid = ?}; - $query.=" GROUP BY aqbasket.basketno, aqbasket.basketname, aqbasket.note, aqbasket.booksellernote, aqbasket.contractnumber, aqbasket.creationdate, aqbasket.closedate, aqbasket.booksellerid, aqbasket.authorisedby, aqbasket.booksellerinvoicenumber, aqbasket.basketgroupid, aqbasket.deliveryplace, aqbasket.billingplace, aqbasket.branch, aqbasket.is_standing, aqbasket.create_items"; + $query .= + " GROUP BY aqbasket.basketno, aqbasket.basketname, aqbasket.note, aqbasket.booksellernote, aqbasket.contractnumber, aqbasket.creationdate, aqbasket.closedate, aqbasket.booksellerid, aqbasket.authorisedby, aqbasket.booksellerinvoicenumber, aqbasket.basketgroupid, aqbasket.deliveryplace, aqbasket.billingplace, aqbasket.branch, aqbasket.is_standing, aqbasket.create_items"; + + unless ($allbaskets) { - unless ( $allbaskets ) { # Don't show the basket if it's NOT CLOSED or is FULLY RECEIVED - $query.=" HAVING (closedate IS NULL OR ( + $query .= " HAVING (closedate IS NULL OR ( SUM( IF(aqorders.datereceived IS NULL AND aqorders.datecancellationprinted IS NULL @@ -721,20 +729,21 @@ sub GetBasketsInfosByBookseller { my $sth = $dbh->prepare($query); $sth->execute($supplierid); - my $baskets = $sth->fetchall_arrayref({}); + my $baskets = $sth->fetchall_arrayref( {} ); # Retrieve the number of biblios cancelled - my $cancelled_biblios = $dbh->selectall_hashref( q| + my $cancelled_biblios = $dbh->selectall_hashref( + q| SELECT COUNT(DISTINCT(biblionumber)) AS total_biblios_cancelled, aqbasket.basketno FROM aqbasket LEFT JOIN aqorders ON aqorders.basketno = aqbasket.basketno WHERE booksellerid = ? AND aqorders.orderstatus = 'cancelled' GROUP BY aqbasket.basketno - |, 'basketno', {}, $supplierid ); - map { - $_->{total_biblios_cancelled} = $cancelled_biblios->{$_->{basketno}}{total_biblios_cancelled} || 0 - } @$baskets; + |, 'basketno', {}, $supplierid + ); + map { $_->{total_biblios_cancelled} = $cancelled_biblios->{ $_->{basketno} }{total_biblios_cancelled} || 0 } + @$baskets; return $baskets; } @@ -781,11 +790,11 @@ to this users list. =cut sub ModBasketUsers { - my ($basketno, @basketusers_ids) = @_; + my ( $basketno, @basketusers_ids ) = @_; return unless $basketno; - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $query = qq{ DELETE FROM aqbasketusers WHERE basketno = ? @@ -799,19 +808,21 @@ sub ModBasketUsers { }; $sth = $dbh->prepare($query); foreach my $basketuser_id (@basketusers_ids) { - $sth->execute($basketno, $basketuser_id); + $sth->execute( $basketno, $basketuser_id ); } # Log the basket update - if (C4::Context->preference("AcquisitionLog")) { + if ( C4::Context->preference("AcquisitionLog") ) { logaction( 'ACQUISITIONS', 'MODIFY_BASKET_USERS', $basketno, - to_json({ - basketno => $basketno, - basketusers => @basketusers_ids - }) + to_json( + { + basketno => $basketno, + basketusers => @basketusers_ids + } + ) ); } @@ -842,56 +853,61 @@ Otherwise returns 0. =cut sub CanUserManageBasket { - my ($borrower, $basket, $userflags) = @_; + my ( $borrower, $basket, $userflags ) = @_; + + if ( !ref $borrower ) { - if (!ref $borrower) { # FIXME This needs to be replaced # We should not accept both scalar and array # Tests need to be updated - $borrower = Koha::Patrons->find( $borrower )->unblessed; + $borrower = Koha::Patrons->find($borrower)->unblessed; } - if (!ref $basket) { + if ( !ref $basket ) { $basket = GetBasket($basket); } - return 0 unless ($basket and $borrower); + return 0 unless ( $basket and $borrower ); my $borrowernumber = $borrower->{borrowernumber}; - my $basketno = $basket->{basketno}; + my $basketno = $basket->{basketno}; my $AcqViewBaskets = C4::Context->preference('AcqViewBaskets'); - if (!defined $userflags) { + if ( !defined $userflags ) { my $dbh = C4::Context->dbh; my $sth = $dbh->prepare("SELECT flags FROM borrowers WHERE borrowernumber = ?"); $sth->execute($borrowernumber); my ($flags) = $sth->fetchrow_array; $sth->finish; - $userflags = C4::Auth::getuserflags($flags, $borrower->{userid}, $dbh); + $userflags = C4::Auth::getuserflags( $flags, $borrower->{userid}, $dbh ); } - unless ($userflags->{superlibrarian} - || (ref $userflags->{acquisition} && $userflags->{acquisition}->{order_manage_all}) - || (!ref $userflags->{acquisition} && $userflags->{acquisition})) + unless ( $userflags->{superlibrarian} + || ( ref $userflags->{acquisition} && $userflags->{acquisition}->{order_manage_all} ) + || ( !ref $userflags->{acquisition} && $userflags->{acquisition} ) ) { - if (not exists $userflags->{acquisition}) { + if ( not exists $userflags->{acquisition} ) { return 0; } - if ( (ref $userflags->{acquisition} && !$userflags->{acquisition}->{order_manage}) - || (!ref $userflags->{acquisition} && !$userflags->{acquisition}) ) { + if ( ( ref $userflags->{acquisition} && !$userflags->{acquisition}->{order_manage} ) + || ( !ref $userflags->{acquisition} && !$userflags->{acquisition} ) ) + { return 0; } - if ($AcqViewBaskets eq 'user' - && $basket->{authorisedby} != $borrowernumber - && ! grep { $borrowernumber eq $_ } GetBasketUsers($basketno)) { - return 0; + if ( $AcqViewBaskets eq 'user' + && $basket->{authorisedby} != $borrowernumber + && !grep { $borrowernumber eq $_ } GetBasketUsers($basketno) ) + { + return 0; } - if ($AcqViewBaskets eq 'branch' && defined $basket->{branch} - && $basket->{branch} ne $borrower->{branchcode}) { + if ( $AcqViewBaskets eq 'branch' + && defined $basket->{branch} + && $basket->{branch} ne $borrower->{branchcode} ) + { return 0; } } @@ -911,7 +927,7 @@ Returns a reference to all baskets that belong to basketgroup $basketgroupid. sub GetBasketsByBasketgroup { my $basketgroupid = shift; - my $query = qq{ + my $query = qq{ SELECT *, aqbasket.booksellerid as booksellerid FROM aqbasket LEFT JOIN aqcontract USING(contractnumber) WHERE basketgroupid=? @@ -919,7 +935,7 @@ sub GetBasketsByBasketgroup { my $dbh = C4::Context->dbh; my $sth = $dbh->prepare($query); $sth->execute($basketgroupid); - return $sth->fetchall_arrayref({}); + return $sth->fetchall_arrayref( {} ); } #------------------------------------------------------------# @@ -956,7 +972,7 @@ sub NewBasketgroup { foreach my $field (qw(name billingplace deliveryplace freedeliveryplace deliverycomment closed)) { if ( defined $basketgroupinfo->{$field} ) { $query .= "$field, "; - push(@params, $basketgroupinfo->{$field}); + push( @params, $basketgroupinfo->{$field} ); } } $query .= "booksellerid) VALUES ("; @@ -964,16 +980,16 @@ sub NewBasketgroup { $query .= "?, "; } $query .= "?)"; - push(@params, $basketgroupinfo->{'booksellerid'}); + push( @params, $basketgroupinfo->{'booksellerid'} ); my $dbh = C4::Context->dbh; my $sth = $dbh->prepare($query); $sth->execute(@params); my $basketgroupid = $dbh->{'mysql_insertid'}; - if( $basketgroupinfo->{'basketlist'} ) { - foreach my $basketno (@{$basketgroupinfo->{'basketlist'}}) { + if ( $basketgroupinfo->{'basketlist'} ) { + foreach my $basketno ( @{ $basketgroupinfo->{'basketlist'} } ) { my $query2 = "UPDATE aqbasket SET basketgroupid=? WHERE basketno=?"; - my $sth2 = $dbh->prepare($query2); - $sth2->execute($basketgroupid, $basketno); + my $sth2 = $dbh->prepare($query2); + $sth2->execute( $basketgroupid, $basketno ); } } return $basketgroupid; @@ -1008,29 +1024,29 @@ $hashref->{'closed'} is the 'closed' field of the aqbasketgroups table, it is fa sub ModBasketgroup { my $basketgroupinfo = shift; die "basketgroup id is required to edit a basketgroup" unless $basketgroupinfo->{'id'}; - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $query = "UPDATE aqbasketgroups SET "; my @params; foreach my $field (qw(name billingplace deliveryplace freedeliveryplace deliverycomment closed)) { if ( defined $basketgroupinfo->{$field} ) { $query .= "$field=?, "; - push(@params, $basketgroupinfo->{$field}); + push( @params, $basketgroupinfo->{$field} ); } } chop($query); chop($query); $query .= " WHERE id=?"; - push(@params, $basketgroupinfo->{'id'}); + push( @params, $basketgroupinfo->{'id'} ); my $sth = $dbh->prepare($query); $sth->execute(@params); $sth = $dbh->prepare('UPDATE aqbasket SET basketgroupid = NULL WHERE basketgroupid = ?'); - $sth->execute($basketgroupinfo->{'id'}); + $sth->execute( $basketgroupinfo->{'id'} ); - if($basketgroupinfo->{'basketlist'} && @{$basketgroupinfo->{'basketlist'}}){ + if ( $basketgroupinfo->{'basketlist'} && @{ $basketgroupinfo->{'basketlist'} } ) { $sth = $dbh->prepare("UPDATE aqbasket SET basketgroupid=? WHERE basketno=?"); - foreach my $basketno (@{$basketgroupinfo->{'basketlist'}}) { - $sth->execute($basketgroupinfo->{'id'}, $basketno); + foreach my $basketno ( @{ $basketgroupinfo->{'basketlist'} } ) { + $sth->execute( $basketgroupinfo->{'id'}, $basketno ); } } return; @@ -1056,15 +1072,14 @@ sub DelBasketgroup { my $basketgroupid = shift; die "basketgroup id is required to edit a basketgroup" unless $basketgroupid; my $query = "DELETE FROM aqbasketgroups WHERE id=?"; - my $dbh = C4::Context->dbh; - my $sth = $dbh->prepare($query); + my $dbh = C4::Context->dbh; + my $sth = $dbh->prepare($query); $sth->execute($basketgroupid); return; } #------------------------------------------------------------# - =head2 FUNCTIONS ABOUT ORDERS =head3 GetBasketgroup @@ -1078,7 +1093,7 @@ Returns a reference to the hash containing all information about the basketgroup sub GetBasketgroup { my $basketgroupid = shift; die "basketgroup id is required to edit a basketgroup" unless $basketgroupid; - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $result_set = $dbh->selectall_arrayref( 'SELECT * FROM aqbasketgroups WHERE id=?', { Slice => {} }, @@ -1101,10 +1116,10 @@ sub GetBasketgroups { my $booksellerid = shift; die 'bookseller id is required to edit a basketgroup' unless $booksellerid; my $query = 'SELECT * FROM aqbasketgroups WHERE booksellerid=? ORDER BY id DESC'; - my $dbh = C4::Context->dbh; - my $sth = $dbh->prepare($query); + my $dbh = C4::Context->dbh; + my $sth = $dbh->prepare($query); $sth->execute($booksellerid); - return $sth->fetchall_arrayref({}); + return $sth->fetchall_arrayref( {} ); } #------------------------------------------------------------# @@ -1127,7 +1142,7 @@ sub GetOrders { return () unless $basketno; - my $orderby = $params->{orderby}; + my $orderby = $params->{orderby}; my $cancelled = $params->{cancelled} || 0; my $dbh = C4::Context->dbh; @@ -1137,11 +1152,11 @@ sub GetOrders { aqbudgets.*, |; $query .= $cancelled - ? q| + ? q| aqorders_transfers.ordernumber_to AS transferred_to, aqorders_transfers.timestamp AS transferred_to_timestamp | - : q| + : q| aqorders_transfers.ordernumber_from AS transferred_from, aqorders_transfers.timestamp AS transferred_from_timestamp |; @@ -1152,10 +1167,10 @@ sub GetOrders { LEFT JOIN biblioitems ON biblioitems.biblionumber =biblio.biblionumber |; $query .= $cancelled - ? q| + ? q| LEFT JOIN aqorders_transfers ON aqorders_transfers.ordernumber_from = aqorders.ordernumber | - : q| + : q| LEFT JOIN aqorders_transfers ON aqorders_transfers.ordernumber_to = aqorders.ordernumber |; @@ -1168,10 +1183,8 @@ sub GetOrders { $query .= q| AND datecancellationprinted IS NOT NULL |; - } - else { - $orderby ||= - q|aqorders.datecancellationprinted desc, aqorders.timestamp desc|; + } else { + $orderby ||= q|aqorders.datecancellationprinted desc, aqorders.timestamp desc|; $query .= q| AND datecancellationprinted IS NULL |; @@ -1179,7 +1192,7 @@ sub GetOrders { $query .= " ORDER BY $orderby"; my $orders = - $dbh->selectall_arrayref( $query, { Slice => {} }, $basketno ); + $dbh->selectall_arrayref( $query, { Slice => {} }, $basketno ); return @{$orders}; } @@ -1203,7 +1216,7 @@ sub GetOrdersByBiblionumber { my $biblionumber = shift; return unless $biblionumber; my $dbh = C4::Context->dbh; - my $query =" + my $query = " SELECT biblio.*,biblioitems.*, aqorders.*, aqbudgets.* @@ -1214,7 +1227,7 @@ sub GetOrdersByBiblionumber { WHERE aqorders.biblionumber=? "; my $result_set = - $dbh->selectall_arrayref( $query, { Slice => {} }, $biblionumber ); + $dbh->selectall_arrayref( $query, { Slice => {} }, $biblionumber ); return @{$result_set}; } @@ -1236,7 +1249,7 @@ sub GetOrder { my ($ordernumber) = @_; return unless $ordernumber; - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $query = qq{SELECT aqorders.*, biblio.title, @@ -1269,7 +1282,7 @@ sub GetOrder { WHERE aqorders.basketno = aqbasket.basketno AND ordernumber=?}; my $result_set = - $dbh->selectall_arrayref( $query, { Slice => {} }, $ordernumber ); + $dbh->selectall_arrayref( $query, { Slice => {} }, $ordernumber ); # result_set assumed to contain 1 match return $result_set->[0]; @@ -1295,28 +1308,30 @@ sub ModOrder { my @params; # update uncertainprice to an integer, just in case (under FF, checked boxes have the value "ON" by default) - $orderinfo->{uncertainprice}=1 if $orderinfo->{uncertainprice}; + $orderinfo->{uncertainprice} = 1 if $orderinfo->{uncertainprice}; -# delete($orderinfo->{'branchcode'}); + # delete($orderinfo->{'branchcode'}); # the hash contains a lot of entries not in aqorders, so get the columns ... my $sth = $dbh->prepare("SELECT * FROM aqorders LIMIT 1;"); $sth->execute; my $colnames = $sth->{NAME}; - #FIXME Be careful. If aqorders would have columns with diacritics, - #you should need to decode what you get back from NAME. - #See report 10110 and guided_reports.pl + + #FIXME Be careful. If aqorders would have columns with diacritics, + #you should need to decode what you get back from NAME. + #See report 10110 and guided_reports.pl my $query = "UPDATE aqorders SET "; - foreach my $orderinfokey (grep(!/ordernumber/, keys %$orderinfo)){ + foreach my $orderinfokey ( grep( !/ordernumber/, keys %$orderinfo ) ) { + # ... and skip hash entries that are not in the aqorders table # FIXME : probably not the best way to do it (would be better to have a correct hash) next unless grep { $_ eq $orderinfokey } @$colnames; - $query .= "$orderinfokey=?, "; - push(@params, $orderinfo->{$orderinfokey}); + $query .= "$orderinfokey=?, "; + push( @params, $orderinfo->{$orderinfokey} ); } $query .= "timestamp=NOW() WHERE ordernumber=?"; - push(@params, $orderinfo->{'ordernumber'} ); + push( @params, $orderinfo->{'ordernumber'} ); $sth = $dbh->prepare($query); $sth->execute(@params); return; @@ -1333,18 +1348,18 @@ Modifies the ordernumber of an item in aqorders_items. =cut sub ModItemOrder { - my ($itemnumber, $ordernumber) = @_; + my ( $itemnumber, $ordernumber ) = @_; - return unless ($itemnumber and $ordernumber); + return unless ( $itemnumber and $ordernumber ); - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $query = qq{ UPDATE aqorders_items SET ordernumber = ? WHERE itemnumber = ? }; my $sth = $dbh->prepare($query); - return $sth->execute($ordernumber, $itemnumber); + return $sth->execute( $ordernumber, $itemnumber ); } #------------------------------------------------------------# @@ -1374,11 +1389,10 @@ C<$order->{ordernumber}>. =cut - sub ModReceiveOrder { my ($params) = @_; my $biblionumber = $params->{biblionumber}; - my $order = { %{ $params->{order} } }; # Copy the order, we don't want to modify it + my $order = { %{ $params->{order} } }; # Copy the order, we don't want to modify it my $invoice = $params->{invoice}; my $quantrec = $params->{quantityreceived}; my $user = $params->{user}; @@ -1387,28 +1401,33 @@ sub ModReceiveOrder { my $received_items = $params->{received_items}; my $dbh = C4::Context->dbh; - $datereceived = $datereceived ? dt_from_string( $datereceived ) : dt_from_string; + $datereceived = $datereceived ? dt_from_string($datereceived) : dt_from_string; $datereceived = $datereceived->ymd; $order->{invoice_unitprice} ||= $order->{unitprice}; $order->{invoice_currency} ||= Koha::Acquisition::Currencies->get_active->currency; - my $suggestionid = GetSuggestionFromBiblionumber( $biblionumber ); + my $suggestionid = GetSuggestionFromBiblionumber($biblionumber); if ($suggestionid) { - ModSuggestion( {suggestionid=>$suggestionid, - STATUS=>'AVAILABLE', - biblionumber=> $biblionumber} - ); + ModSuggestion( + { + suggestionid => $suggestionid, + STATUS => 'AVAILABLE', + biblionumber => $biblionumber + } + ); } my $result_set = $dbh->selectrow_arrayref( - q{SELECT aqbasket.is_standing + q{SELECT aqbasket.is_standing FROM aqbasket - WHERE basketno=?},{ Slice => {} }, $order->{basketno}); - my $is_standing = $result_set->[0]; # we assume we have a unique basket + WHERE basketno=?}, { Slice => {} }, $order->{basketno} + ); + my $is_standing = $result_set->[0]; # we assume we have a unique basket my $new_ordernumber = $order->{ordernumber}; if ( $is_standing || $order->{quantity} > $quantrec ) { + # Split order line in two parts: the first is the original order line # without received items (the quantity is decreased), # the second part is a new order line with quantity=quantityrec @@ -1421,7 +1440,7 @@ sub ModReceiveOrder { my $sth = $dbh->prepare($query); $sth->execute( - ( $is_standing ? 1 : ($order->{quantity} - $quantrec) ), + ( $is_standing ? 1 : ( $order->{quantity} - $quantrec ) ), $order->{ordernumber} ); @@ -1429,13 +1448,14 @@ sub ModReceiveOrder { $query = q| UPDATE aqorders SET - tax_value_on_ordering = quantity * | . get_rounding_sql(q|ecost_tax_excluded|) . q| * tax_rate_on_ordering, - tax_value_on_receiving = quantity * | . get_rounding_sql(q|unitprice_tax_excluded|) . q| * tax_rate_on_receiving + tax_value_on_ordering = quantity * | + . get_rounding_sql(q|ecost_tax_excluded|) . q| * tax_rate_on_ordering, + tax_value_on_receiving = quantity * | + . get_rounding_sql(q|unitprice_tax_excluded|) . q| * tax_rate_on_receiving |; my @params; - if ( not $order->{subscriptionid} && defined $order->{order_internalnote} ) - { + if ( not $order->{subscriptionid} && defined $order->{order_internalnote} ) { $query .= q|, order_internalnote = ?|; push @params, $order->{order_internalnote}; } @@ -1447,26 +1467,30 @@ sub ModReceiveOrder { WHERE ordernumber = ? |; - $dbh->do($query, undef, @params, $order->{ordernumber}); + $dbh->do( $query, undef, @params, $order->{ordernumber} ); delete $order->{ordernumber}; - $order->{budget_id} = ( $budget_id || $order->{budget_id} ); - $order->{quantity} = $quantrec; + $order->{budget_id} = ( $budget_id || $order->{budget_id} ); + $order->{quantity} = $quantrec; $order->{quantityreceived} = $quantrec; - $order->{ecost_tax_excluded} //= 0; - $order->{tax_rate_on_ordering} //= 0; + $order->{ecost_tax_excluded} //= 0; + $order->{tax_rate_on_ordering} //= 0; $order->{unitprice_tax_excluded} //= 0; - $order->{tax_rate_on_receiving} //= 0; - $order->{tax_value_on_ordering} = $order->{quantity} * get_rounded_price($order->{ecost_tax_excluded}) * $order->{tax_rate_on_ordering}; - $order->{tax_value_on_receiving} = $order->{quantity} * get_rounded_price($order->{unitprice_tax_excluded}) * $order->{tax_rate_on_receiving}; + $order->{tax_rate_on_receiving} //= 0; + $order->{tax_value_on_ordering} = + $order->{quantity} * get_rounded_price( $order->{ecost_tax_excluded} ) * $order->{tax_rate_on_ordering}; + $order->{tax_value_on_receiving} = + $order->{quantity} * + get_rounded_price( $order->{unitprice_tax_excluded} ) * + $order->{tax_rate_on_receiving}; $order->{datereceived} = $datereceived; - $order->{invoiceid} = $invoice->{invoiceid}; - $order->{orderstatus} = 'complete'; - $new_ordernumber = Koha::Acquisition::Order->new($order)->store->ordernumber; # TODO What if the store fails? + $order->{invoiceid} = $invoice->{invoiceid}; + $order->{orderstatus} = 'complete'; + $new_ordernumber = Koha::Acquisition::Order->new($order)->store->ordernumber; # TODO What if the store fails? if ($received_items) { foreach my $itemnumber (@$received_items) { - ModItemOrder($itemnumber, $new_ordernumber); + ModItemOrder( $itemnumber, $new_ordernumber ); } } } else { @@ -1505,8 +1529,9 @@ sub ModReceiveOrder { $query .= q| where biblionumber=? and ordernumber=?|; - my $sth = $dbh->prepare( $query ); - my @params = ( $quantrec, $datereceived, $invoice->{invoiceid}, ( $budget_id ? $budget_id : $order->{budget_id} ) ); + my $sth = $dbh->prepare($query); + my @params = + ( $quantrec, $datereceived, $invoice->{invoiceid}, ( $budget_id ? $budget_id : $order->{budget_id} ) ); if ( defined $order->{replacementprice} ) { push @params, $order->{replacementprice}; @@ -1532,13 +1557,13 @@ sub ModReceiveOrder { push @params, ( $biblionumber, $order->{ordernumber} ); - $sth->execute( @params ); + $sth->execute(@params); # All items have been received, sent a notification to users NotifyOrderUsers( $order->{ordernumber} ); } - return ($datereceived, $new_ordernumber); + return ( $datereceived, $new_ordernumber ); } =head3 CancelReceipt @@ -1557,7 +1582,7 @@ sub CancelReceipt { return unless $ordernumber; - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $query = qq{ SELECT datereceived, parent_ordernumber, quantity FROM aqorders @@ -1566,21 +1591,22 @@ sub CancelReceipt { my $sth = $dbh->prepare($query); $sth->execute($ordernumber); my $order = $sth->fetchrow_hashref; - unless($order) { + unless ($order) { warn "CancelReceipt: order $ordernumber does not exist"; return; } - unless($order->{'datereceived'}) { + unless ( $order->{'datereceived'} ) { warn "CancelReceipt: order $ordernumber is not received"; return; } my $parent_ordernumber = $order->{'parent_ordernumber'}; - my $order_obj = Koha::Acquisition::Orders->find( $ordernumber ); # FIXME rewrite all this subroutine using this object + my $order_obj = Koha::Acquisition::Orders->find($ordernumber); # FIXME rewrite all this subroutine using this object my @itemnumbers = $order_obj->items->get_column('itemnumber'); - if($parent_ordernumber == $ordernumber || not $parent_ordernumber) { + if ( $parent_ordernumber == $ordernumber || not $parent_ordernumber ) { + # The order line has no parent, just mark it as not received $query = qq{ UPDATE aqorders @@ -1591,9 +1617,10 @@ sub CancelReceipt { WHERE ordernumber = ? }; $sth = $dbh->prepare($query); - $sth->execute(0, undef, undef, $ordernumber); - _cancel_items_receipt( $order_obj ); + $sth->execute( 0, undef, undef, $ordernumber ); + _cancel_items_receipt($order_obj); } else { + # The order line has a parent, increase parent quantity and delete # the order line. unless ( $order_obj->basket->is_standing ) { @@ -1605,13 +1632,12 @@ sub CancelReceipt { $sth = $dbh->prepare($query); $sth->execute($parent_ordernumber); my $parent_order = $sth->fetchrow_hashref; - unless($parent_order) { + unless ($parent_order) { warn "Parent order $parent_ordernumber does not exist."; return; } - if($parent_order->{'datereceived'}) { - warn "CancelReceipt: parent order is received.". - " Can't cancel receipt."; + if ( $parent_order->{'datereceived'} ) { + warn "CancelReceipt: parent order is received." . " Can't cancel receipt."; return; } $query = qq{ @@ -1625,23 +1651,27 @@ sub CancelReceipt { $order->{'quantity'} + $parent_order->{'quantity'}, $parent_ordernumber ); - unless($rv) { - warn "Cannot update parent order line, so do not cancel". - " receipt"; + unless ($rv) { + warn "Cannot update parent order line, so do not cancel" . " receipt"; return; } # Recalculate tax_value - $dbh->do(q| + $dbh->do( + q| UPDATE aqorders SET - tax_value_on_ordering = quantity * | . get_rounding_sql(q|ecost_tax_excluded|) . q| * tax_rate_on_ordering, - tax_value_on_receiving = quantity * | . get_rounding_sql(q|unitprice_tax_excluded|) . q| * tax_rate_on_receiving + tax_value_on_ordering = quantity * | + . get_rounding_sql(q|ecost_tax_excluded|) . q| * tax_rate_on_ordering, + tax_value_on_receiving = quantity * | + . get_rounding_sql(q|unitprice_tax_excluded|) . q| * tax_rate_on_receiving WHERE ordernumber = ? - |, undef, $parent_ordernumber); + |, undef, $parent_ordernumber + ); } _cancel_items_receipt( $order_obj, $parent_ordernumber ); + # Delete order line $query = qq{ DELETE FROM aqorders @@ -1652,15 +1682,16 @@ sub CancelReceipt { } - if( $order_obj->basket->effective_create_items eq 'ordering' ) { + if ( $order_obj->basket->effective_create_items eq 'ordering' ) { my @affects = split q{\|}, C4::Context->preference("AcqItemSetSubfieldsWhenReceiptIsCancelled"); - if ( @affects ) { - for my $in ( @itemnumbers ) { - my $item = Koha::Items->find( $in ); # FIXME We do not need that, we already have Koha::Items from $order_obj->items - my $biblio = $item->biblio; - my ( $itemfield ) = GetMarcFromKohaField( 'items.itemnumber' ); - my $item_marc = C4::Items::GetMarcItem( $biblio->biblionumber, $in ); - for my $affect ( @affects ) { + if (@affects) { + for my $in (@itemnumbers) { + my $item = Koha::Items->find($in) + ; # FIXME We do not need that, we already have Koha::Items from $order_obj->items + my $biblio = $item->biblio; + my ($itemfield) = GetMarcFromKohaField('items.itemnumber'); + my $item_marc = C4::Items::GetMarcItem( $biblio->biblionumber, $in ); + for my $affect (@affects) { my ( $sf, $v ) = split q{=}, $affect, 2; foreach ( $item_marc->field($itemfield) ) { $_->update( $sf => $v ); @@ -1680,6 +1711,7 @@ sub _cancel_items_receipt { my $items = $order->items; if ( $order->basket->effective_create_items eq 'receiving' ) { + # Remove items that were created at receipt my $query = qq{ DELETE FROM items, aqorders_items @@ -1689,12 +1721,13 @@ sub _cancel_items_receipt { my $dbh = C4::Context->dbh; my $sth = $dbh->prepare($query); while ( my $item = $items->next ) { - $sth->execute($item->itemnumber, $item->itemnumber); + $sth->execute( $item->itemnumber, $item->itemnumber ); } } else { + # Update items while ( my $item = $items->next ) { - ModItemOrder($item->itemnumber, $parent_ordernumber); + ModItemOrder( $item->itemnumber, $parent_ordernumber ); } } } @@ -1733,22 +1766,22 @@ from aqorders, biblio, biblioitems and aqbasket tables. =cut sub SearchOrders { - my ( $params ) = @_; - my $ordernumber = $params->{ordernumber}; - my $search = $params->{search}; - my $ean = $params->{ean}; - my $booksellerid = $params->{booksellerid}; - my $basketno = $params->{basketno}; - my $basketname = $params->{basketname}; + my ($params) = @_; + my $ordernumber = $params->{ordernumber}; + my $search = $params->{search}; + my $ean = $params->{ean}; + my $booksellerid = $params->{booksellerid}; + my $basketno = $params->{basketno}; + my $basketname = $params->{basketname}; my $basketgroupname = $params->{basketgroupname}; - my $owner = $params->{owner}; - my $pending = $params->{pending}; - my $ordered = $params->{ordered}; - my $biblionumber = $params->{biblionumber}; - my $budget_id = $params->{budget_id}; + my $owner = $params->{owner}; + my $pending = $params->{pending}; + my $ordered = $params->{ordered}; + my $biblionumber = $params->{biblionumber}; + my $budget_id = $params->{budget_id}; - my $dbh = C4::Context->dbh; - my @args = (); + my $dbh = C4::Context->dbh; + my @args = (); my $query = q{ SELECT aqbasket.basketno, borrowers.surname, @@ -1791,7 +1824,7 @@ sub SearchOrders { ( quantity > quantityreceived OR quantityreceived is NULL ) }; - if ( $ordered ) { + if ($ordered) { $query .= q{ AND aqorders.orderstatus IN ( "ordered", "partial" )}; } $query .= q{ @@ -1813,45 +1846,45 @@ sub SearchOrders { } } - if ( $ordernumber ) { + if ($ordernumber) { $query .= ' AND ( aqorders.ordernumber = ? OR aqorders_transfers.ordernumber_from = ? ) '; push @args, ( $ordernumber, $ordernumber ); } - if ( $biblionumber ) { + if ($biblionumber) { $query .= 'AND aqorders.biblionumber = ?'; push @args, $biblionumber; } - if( $search ) { + if ($search) { $query .= ' AND (biblio.title LIKE ? OR biblio.author LIKE ? OR biblioitems.isbn LIKE ?)'; - push @args, ("%$search%","%$search%","%$search%"); + push @args, ( "%$search%", "%$search%", "%$search%" ); } - if ( $ean ) { + if ($ean) { $query .= ' AND biblioitems.ean = ?'; push @args, $ean; } - if ( $booksellerid ) { + if ($booksellerid) { $query .= 'AND aqbasket.booksellerid = ?'; push @args, $booksellerid; } - if( $basketno ) { + if ($basketno) { $query .= 'AND aqbasket.basketno = ?'; push @args, $basketno; } - if( $basketname ) { + if ($basketname) { $query .= 'AND aqbasket.basketname LIKE ?'; push @args, "%$basketname%"; } - if( $basketgroupname ) { + if ($basketgroupname) { $query .= ' AND aqbasketgroups.name LIKE ?'; push @args, "%$basketgroupname%"; } - if ( $owner ) { + if ($owner) { $query .= ' AND aqbasket.authorisedby=? '; push @args, $userenv->{'number'}; } - if ( $budget_id ) { + if ($budget_id) { $query .= ' AND aqorders.budget_id = ?'; push @args, $budget_id; } @@ -1860,7 +1893,7 @@ sub SearchOrders { my $sth = $dbh->prepare($query); $sth->execute(@args); - return $sth->fetchall_arrayref({}); + return $sth->fetchall_arrayref( {} ); } #------------------------------------------------------------# @@ -1880,11 +1913,11 @@ Return the ordernumber of created order. =cut sub TransferOrder { - my ($ordernumber, $basketno) = @_; + my ( $ordernumber, $basketno ) = @_; - return unless ($ordernumber and $basketno); + return unless ( $ordernumber and $basketno ); - my $order = Koha::Acquisition::Orders->find( $ordernumber ) or return; + my $order = Koha::Acquisition::Orders->find($ordernumber) or return; return if $order->datereceived; my $orderhash = $order->unblessed; @@ -1893,7 +1926,7 @@ sub TransferOrder { return unless $basket; my $dbh = C4::Context->dbh; - my ($query, $sth, $rv); + my ( $query, $sth, $rv ); $query = q{ UPDATE aqorders @@ -1901,13 +1934,13 @@ sub TransferOrder { WHERE ordernumber = ? }; $sth = $dbh->prepare($query); - $rv = $sth->execute('cancelled', $ordernumber); + $rv = $sth->execute( 'cancelled', $ordernumber ); delete $orderhash->{ordernumber}; delete $orderhash->{parent_ordernumber}; $orderhash->{basketno} = $basketno; - my $neworder = Koha::Acquisition::Order->new($orderhash); + my $neworder = Koha::Acquisition::Order->new($orderhash); my $newordernumber = $neworder->store->ordernumber; $query = q{ @@ -1916,22 +1949,24 @@ sub TransferOrder { WHERE ordernumber = ? }; $sth = $dbh->prepare($query); - $sth->execute($newordernumber, $ordernumber); + $sth->execute( $newordernumber, $ordernumber ); $query = q{ INSERT INTO aqorders_transfers (ordernumber_from, ordernumber_to) VALUES (?, ?) }; $sth = $dbh->prepare($query); - $sth->execute($ordernumber, $newordernumber); + $sth->execute( $ordernumber, $newordernumber ); # Copy additional fields values - foreach my $afv ($order->additional_field_values->as_list) { - Koha::AdditionalFieldValue->new({ - field_id => $afv->field_id, - record_id => $newordernumber, - value => $afv->value, - })->store; + foreach my $afv ( $order->additional_field_values->as_list ) { + Koha::AdditionalFieldValue->new( + { + field_id => $afv->field_id, + record_id => $newordernumber, + value => $afv->value, + } + )->store; } return $newordernumber; @@ -1946,9 +1981,9 @@ returns the correct SQL routine based on OrderPriceRounding system preference. =cut sub get_rounding_sql { - my ( $round_string ) = @_; + my ($round_string) = @_; my $rounding_pref = C4::Context->preference('OrderPriceRounding') // q{}; - if ( $rounding_pref eq "nearest_cent" ) { + if ( $rounding_pref eq "nearest_cent" ) { return "CAST($round_string*100 AS SIGNED)/100"; } return $round_string; @@ -1963,10 +1998,10 @@ returns a price rounded as specified in OrderPriceRounding system preference. =cut sub get_rounded_price { - my ( $price ) = @_; + my ($price) = @_; my $rounding_pref = C4::Context->preference('OrderPriceRounding') // q{}; - if( $rounding_pref eq 'nearest_cent' ) { - return Koha::Number::Price->new( $price )->round(); + if ( $rounding_pref eq 'nearest_cent' ) { + return Koha::Number::Price->new($price)->round(); } return $price; } @@ -2021,33 +2056,34 @@ returns: =cut sub GetHistory { -# don't run the query if there are no parameters (list would be too long for sure !) + + # don't run the query if there are no parameters (list would be too long for sure !) croak "No search params" unless @_; - my %params = @_; - my $title = $params{title}; - my $author = $params{author}; - my $isbn = $params{isbn}; - my $issn = $params{issn}; - my $ean = $params{ean}; - my $name = $params{name}; - my $internalnote = $params{internalnote}; - my $vendornote = $params{vendornote}; - my $from_placed_on = $params{from_placed_on}; - my $to_placed_on = $params{to_placed_on}; - my $basket = $params{basket}; + my %params = @_; + my $title = $params{title}; + my $author = $params{author}; + my $isbn = $params{isbn}; + my $issn = $params{issn}; + my $ean = $params{ean}; + my $name = $params{name}; + my $internalnote = $params{internalnote}; + my $vendornote = $params{vendornote}; + my $from_placed_on = $params{from_placed_on}; + my $to_placed_on = $params{to_placed_on}; + my $basket = $params{basket}; my $booksellerinvoicenumber = $params{booksellerinvoicenumber}; - my $basketgroupname = $params{basketgroupname}; - my $budget = $params{budget}; - my $orderstatus = $params{orderstatus}; - my $is_standing = $params{is_standing}; - my $biblionumber = $params{biblionumber}; - my $get_canceled_order = $params{get_canceled_order} || 0; - my $ordernumber = $params{ordernumber}; - my $search_children_too = $params{search_children_too} || 0; - my $created_by = $params{created_by} || []; - my $managing_library = $params{managing_library}; - my $ordernumbers = $params{ordernumbers} || []; - my $additional_fields = $params{additional_fields} // []; + my $basketgroupname = $params{basketgroupname}; + my $budget = $params{budget}; + my $orderstatus = $params{orderstatus}; + my $is_standing = $params{is_standing}; + my $biblionumber = $params{biblionumber}; + my $get_canceled_order = $params{get_canceled_order} || 0; + my $ordernumber = $params{ordernumber}; + my $search_children_too = $params{search_children_too} || 0; + my $created_by = $params{created_by} || []; + my $managing_library = $params{managing_library}; + my $ordernumbers = $params{ordernumbers} || []; + my $additional_fields = $params{additional_fields} // []; my $total_qty = 0; my $total_qtyreceived = 0; @@ -2056,15 +2092,15 @@ sub GetHistory { #get variation of isbn my @isbn_params; my @isbns; - if ($isbn){ - if ( C4::Context->preference("SearchWithISBNVariations") ){ - @isbns = C4::Koha::GetVariationsOfISBN( $isbn ); - foreach my $isb (@isbns){ + if ($isbn) { + if ( C4::Context->preference("SearchWithISBNVariations") ) { + @isbns = C4::Koha::GetVariationsOfISBN($isbn); + foreach my $isb (@isbns) { push @isbn_params, '?'; } } - unless (@isbns){ - push @isbns, $isbn; + unless (@isbns) { + push @isbns, $isbn; push @isbn_params, '?'; } } @@ -2072,19 +2108,19 @@ sub GetHistory { #get variation of issn my @issn_params; my @issns; - if ($issn){ - if ( C4::Context->preference("SearchWithISSNVariations") ){ - @issns = C4::Koha::GetVariationsOfISSN( $issn ); + if ($issn) { + if ( C4::Context->preference("SearchWithISSNVariations") ) { + @issns = C4::Koha::GetVariationsOfISSN($issn); push @issn_params, ('?') x @issns; } - unless (@issns){ - push @issns, $issn; + unless (@issns) { + push @issns, $issn; push @issn_params, '?'; } } my $dbh = C4::Context->dbh; - my $query =" + my $query = " SELECT COALESCE(biblio.title, deletedbiblio.title) AS title, COALESCE(biblio.author, deletedbiblio.author) AS author, @@ -2132,78 +2168,78 @@ sub GetHistory { $query .= " WHERE 1 "; - unless ($get_canceled_order or (defined $orderstatus and $orderstatus eq 'cancelled')) { + unless ( $get_canceled_order or ( defined $orderstatus and $orderstatus eq 'cancelled' ) ) { $query .= " AND datecancellationprinted IS NULL "; } - my @query_params = (); + my @query_params = (); - if ( $biblionumber ) { + if ($biblionumber) { $query .= " AND biblio.biblionumber = ?"; push @query_params, $biblionumber; } - if ( $title ) { + if ($title) { $query .= " AND biblio.title LIKE ? "; $title =~ s/\s+/%/g; push @query_params, "%$title%"; } - if ( $author ) { + if ($author) { $query .= " AND biblio.author LIKE ? "; push @query_params, "%$author%"; } - if ( @isbns ) { - $query .= " AND ( biblioitems.isbn LIKE " . join (" OR biblioitems.isbn LIKE ", @isbn_params ) . ")"; - foreach my $isb (@isbns){ + if (@isbns) { + $query .= " AND ( biblioitems.isbn LIKE " . join( " OR biblioitems.isbn LIKE ", @isbn_params ) . ")"; + foreach my $isb (@isbns) { push @query_params, "%$isb%"; } } - if ( @issns ) { - $query .= " AND ( biblioitems.issn LIKE " . join (" OR biblioitems.issn LIKE ", @issn_params ) . ")"; - foreach my $isn (@issns){ + if (@issns) { + $query .= " AND ( biblioitems.issn LIKE " . join( " OR biblioitems.issn LIKE ", @issn_params ) . ")"; + foreach my $isn (@issns) { push @query_params, "%$isn%"; } } - if ( $ean ) { + if ($ean) { $query .= " AND biblioitems.ean = ? "; push @query_params, "$ean"; } - if ( $name ) { + if ($name) { $query .= " AND aqbooksellers.name LIKE ? "; push @query_params, "%$name%"; } - if ( $budget ) { + if ($budget) { $query .= " AND aqbudgets.budget_id = ? "; push @query_params, "$budget"; } - if ( $from_placed_on ) { + if ($from_placed_on) { $query .= " AND creationdate >= ? "; push @query_params, $from_placed_on; } - if ( $to_placed_on ) { + if ($to_placed_on) { $query .= " AND creationdate <= ? "; push @query_params, $to_placed_on; } - if ( defined $orderstatus and $orderstatus ne '' and $orderstatus ne 'any') { + if ( defined $orderstatus and $orderstatus ne '' and $orderstatus ne 'any' ) { $query .= " AND aqorders.orderstatus = ? "; push @query_params, "$orderstatus"; } - if ( $is_standing ) { + if ($is_standing) { $query .= " AND is_standing = ? "; push @query_params, $is_standing; } if ($basket) { - if ($basket =~ m/^\d+$/) { + if ( $basket =~ m/^\d+$/ ) { $query .= " AND aqorders.basketno = ? "; push @query_params, $basket; } else { @@ -2212,12 +2248,12 @@ sub GetHistory { } } - if ( $internalnote ) { + if ($internalnote) { $query .= " AND aqorders.order_internalnote LIKE ? "; push @query_params, "%$internalnote%"; } - if ( $vendornote ) { + if ($vendornote) { $query .= " AND aqorders.order_vendornote LIKE ?"; push @query_params, "%$vendornote%"; } @@ -2242,21 +2278,21 @@ sub GetHistory { $query .= ") "; } - if ( @$created_by ) { + if (@$created_by) { $query .= ' AND aqbasket.authorisedby IN ( ' . join( ',', ('?') x @$created_by ) . ')'; push @query_params, @$created_by; } - if ( $managing_library ) { + if ($managing_library) { $query .= " AND aqbasket.branch = ? "; push @query_params, $managing_library; } - if ( @$ordernumbers ) { - $query .= ' AND (aqorders.ordernumber IN ( ' . join (',', ('?') x @$ordernumbers ) . '))'; + if (@$ordernumbers) { + $query .= ' AND (aqorders.ordernumber IN ( ' . join( ',', ('?') x @$ordernumbers ) . '))'; push @query_params, @$ordernumbers; } - if ( @$additional_fields ) { + if (@$additional_fields) { my @baskets = Koha::Acquisition::Baskets->filter_by_additional_fields($additional_fields)->as_list; return [] unless @baskets; @@ -2285,17 +2321,17 @@ C<$results> is a ref to a table which contains hashref =cut sub GetRecentAcqui { - my $limit = shift; - my $dbh = C4::Context->dbh; + my $limit = shift; + my $dbh = C4::Context->dbh; my $query = " SELECT * FROM biblio ORDER BY timestamp DESC - LIMIT 0,".$limit; + LIMIT 0," . $limit; my $sth = $dbh->prepare($query); $sth->execute; - my $results = $sth->fetchall_arrayref({}); + my $results = $sth->fetchall_arrayref( {} ); return $results; } @@ -2311,8 +2347,8 @@ Add a claim for an order sub AddClaim { my ($ordernumber) = @_; - my $dbh = C4::Context->dbh; - my $query = " + my $dbh = C4::Context->dbh; + my $query = " UPDATE aqorders SET claims_count = claims_count + 1, claimed_date = CURDATE() @@ -2354,22 +2390,20 @@ asc is the default if omitted sub GetInvoices { my %args = @_; - my $additional_fields = $args{additional_fields} // []; + my $additional_fields = $args{additional_fields} // []; my $matching_invoice_ids_for_additional_fields = []; - if ( @$additional_fields ) { + if (@$additional_fields) { my @invoices = Koha::Acquisition::Invoices->filter_by_additional_fields($additional_fields)->as_list; return () unless @invoices; - $matching_invoice_ids_for_additional_fields = [ map { - $_->id - } @invoices ]; + $matching_invoice_ids_for_additional_fields = [ map { $_->id } @invoices ]; } my @columns = qw(invoicenumber booksellerid shipmentdate billingdate closedate shipmentcost shipmentcost_budgetid); - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $query = qq{ SELECT aqinvoices.invoiceid, aqinvoices.invoicenumber, aqinvoices.booksellerid, aqinvoices.shipmentdate, aqinvoices.billingdate, aqinvoices.closedate, aqinvoices.shipmentcost, aqinvoices.shipmentcost_budgetid, aqinvoices.message_id, aqbooksellers.name AS suppliername, @@ -2400,59 +2434,61 @@ sub GetInvoices { my @bind_args; my @bind_strs; - if($args{supplierid}) { + if ( $args{supplierid} ) { push @bind_strs, " aqinvoices.booksellerid = ? "; push @bind_args, $args{supplierid}; } - if($args{invoicenumber}) { + if ( $args{invoicenumber} ) { push @bind_strs, " aqinvoices.invoicenumber LIKE ? "; push @bind_args, "%$args{invoicenumber}%"; } - if($args{suppliername}) { + if ( $args{suppliername} ) { push @bind_strs, " aqbooksellers.name LIKE ? "; push @bind_args, "%$args{suppliername}%"; } - if($args{shipmentdatefrom}) { + if ( $args{shipmentdatefrom} ) { push @bind_strs, " aqinvoices.shipmentdate >= ? "; push @bind_args, $args{shipmentdatefrom}; } - if($args{shipmentdateto}) { + if ( $args{shipmentdateto} ) { push @bind_strs, " aqinvoices.shipmentdate <= ? "; push @bind_args, $args{shipmentdateto}; } - if($args{billingdatefrom}) { + if ( $args{billingdatefrom} ) { push @bind_strs, " aqinvoices.billingdate >= ? "; push @bind_args, $args{billingdatefrom}; } - if($args{billingdateto}) { + if ( $args{billingdateto} ) { push @bind_strs, " aqinvoices.billingdate <= ? "; push @bind_args, $args{billingdateto}; } - if($args{isbneanissn}) { - push @bind_strs, " (biblioitems.isbn LIKE CONCAT('%', ?, '%') OR biblioitems.ean LIKE CONCAT('%', ?, '%') OR biblioitems.issn LIKE CONCAT('%', ?, '%') ) "; + if ( $args{isbneanissn} ) { + push @bind_strs, + " (biblioitems.isbn LIKE CONCAT('%', ?, '%') OR biblioitems.ean LIKE CONCAT('%', ?, '%') OR biblioitems.issn LIKE CONCAT('%', ?, '%') ) "; push @bind_args, $args{isbneanissn}, $args{isbneanissn}, $args{isbneanissn}; } - if($args{title}) { + if ( $args{title} ) { push @bind_strs, " biblio.title LIKE CONCAT('%', ?, '%') "; push @bind_args, $args{title}; } - if($args{author}) { + if ( $args{author} ) { push @bind_strs, " biblio.author LIKE CONCAT('%', ?, '%') "; push @bind_args, $args{author}; } - if($args{publisher}) { + if ( $args{publisher} ) { push @bind_strs, " biblioitems.publishercode LIKE CONCAT('%', ?, '%') "; push @bind_args, $args{publisher}; } - if($args{publicationyear}) { - push @bind_strs, " ((biblioitems.publicationyear LIKE CONCAT('%', ?, '%')) OR (biblio.copyrightdate LIKE CONCAT('%', ?, '%'))) "; + if ( $args{publicationyear} ) { + push @bind_strs, + " ((biblioitems.publicationyear LIKE CONCAT('%', ?, '%')) OR (biblio.copyrightdate LIKE CONCAT('%', ?, '%'))) "; push @bind_args, $args{publicationyear}, $args{publicationyear}; } - if($args{branchcode}) { + if ( $args{branchcode} ) { push @bind_strs, " borrowers.branchcode = ? "; push @bind_args, $args{branchcode}; } - if($args{message_id}) { + if ( $args{message_id} ) { push @bind_strs, " aqinvoices.message_id = ? "; push @bind_args, $args{message_id}; } @@ -2465,24 +2501,24 @@ sub GetInvoices { } } - $query .= " WHERE " . join(" AND ", @bind_strs) if @bind_strs; + $query .= " WHERE " . join( " AND ", @bind_strs ) if @bind_strs; # Handle additional fields filtering - if ( @$additional_fields ) { + if (@$additional_fields) { my $operator = ' WHERE'; - if ( @bind_strs ) { # there's a WHERE already + if (@bind_strs) { # there's a WHERE already $operator = ' AND'; } - $query .= "$operator aqinvoices.invoiceid IN (" - . join( ', ', @$matching_invoice_ids_for_additional_fields ) - . ')'; + $query .= + "$operator aqinvoices.invoiceid IN (" . join( ', ', @$matching_invoice_ids_for_additional_fields ) . ')'; } - $query .= " GROUP BY aqinvoices.invoiceid, aqinvoices.invoicenumber, aqinvoices.booksellerid, aqinvoices.shipmentdate, aqinvoices.billingdate, aqinvoices.closedate, aqinvoices.shipmentcost, aqinvoices.shipmentcost_budgetid, aqinvoices.message_id, aqbooksellers.name"; + $query .= + " GROUP BY aqinvoices.invoiceid, aqinvoices.invoicenumber, aqinvoices.booksellerid, aqinvoices.shipmentdate, aqinvoices.billingdate, aqinvoices.closedate, aqinvoices.shipmentcost, aqinvoices.shipmentcost_budgetid, aqinvoices.message_id, aqbooksellers.name"; - if($args{order_by}) { - my ($column, $direction) = split / /, $args{order_by}; - if(grep { $_ eq $column } @columns) { + if ( $args{order_by} ) { + my ( $column, $direction ) = split / /, $args{order_by}; + if ( grep { $_ eq $column } @columns ) { $direction ||= 'ASC'; $query .= " ORDER BY $column $direction"; } @@ -2491,7 +2527,7 @@ sub GetInvoices { my $sth = $dbh->prepare($query); $sth->execute(@bind_args); - my $results = $sth->fetchall_arrayref({}); + my $results = $sth->fetchall_arrayref( {} ); return @$results; } @@ -2511,7 +2547,7 @@ sub GetInvoice { return unless $invoiceid; - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $query = qq{ SELECT * FROM aqinvoices @@ -2542,7 +2578,7 @@ sub GetInvoiceDetails { return; } - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $query = q{ SELECT aqinvoices.*, aqbooksellers.name AS suppliername FROM aqinvoices @@ -2573,8 +2609,8 @@ sub GetInvoiceDetails { }; $sth = $dbh->prepare($query); $sth->execute($invoiceid); - $invoice->{orders} = $sth->fetchall_arrayref({}); - $invoice->{orders} ||= []; # force an empty arrayref if fetchall_arrayref fails + $invoice->{orders} = $sth->fetchall_arrayref( {} ); + $invoice->{orders} ||= []; # force an empty arrayref if fetchall_arrayref fails return $invoice; } @@ -2598,29 +2634,29 @@ Create a new invoice and return its id or undef if it fails. sub AddInvoice { my %invoice = @_; - return unless(%invoice and $invoice{invoicenumber}); + return unless ( %invoice and $invoice{invoicenumber} ); my @columns = qw(invoicenumber booksellerid shipmentdate billingdate closedate shipmentcost shipmentcost_budgetid message_id); my @set_strs; my @set_args; - foreach my $key (keys %invoice) { - if(0 < grep { $_ eq $key } @columns) { + foreach my $key ( keys %invoice ) { + if ( 0 < grep { $_ eq $key } @columns ) { push @set_strs, "$key = ?"; - push @set_args, ($invoice{$key} || undef); + push @set_args, ( $invoice{$key} || undef ); } } my $rv; - if(@set_args > 0) { - my $dbh = C4::Context->dbh; + if ( @set_args > 0 ) { + my $dbh = C4::Context->dbh; my $query = "INSERT INTO aqinvoices SET "; - $query .= join (",", @set_strs); + $query .= join( ",", @set_strs ); my $sth = $dbh->prepare($query); $rv = $sth->execute(@set_args); - if($rv) { - $rv = $dbh->last_insert_id(undef, undef, 'aqinvoices', undef); + if ($rv) { + $rv = $dbh->last_insert_id( undef, undef, 'aqinvoices', undef ); } } return $rv; @@ -2648,27 +2684,27 @@ Return undef if it fails. sub ModInvoice { my %invoice = @_; - return unless(%invoice and $invoice{invoiceid}); + return unless ( %invoice and $invoice{invoiceid} ); my @columns = qw(invoicenumber booksellerid shipmentdate billingdate closedate shipmentcost shipmentcost_budgetid); my @set_strs; my @set_args; - foreach my $key (keys %invoice) { - if(0 < grep { $_ eq $key } @columns) { + foreach my $key ( keys %invoice ) { + if ( 0 < grep { $_ eq $key } @columns ) { push @set_strs, "$key = ?"; - push @set_args, ($invoice{$key} || undef); + push @set_args, ( $invoice{$key} || undef ); } } - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $query = "UPDATE aqinvoices SET "; - $query .= join(",", @set_strs); + $query .= join( ",", @set_strs ); $query .= " WHERE invoiceid = ?"; my $sth = $dbh->prepare($query); - $sth->execute(@set_args, $invoice{invoiceid}); + $sth->execute( @set_args, $invoice{invoiceid} ); } =head3 CloseInvoice @@ -2686,7 +2722,7 @@ sub CloseInvoice { return unless $invoiceid; - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $query = qq{ UPDATE aqinvoices SET closedate = CAST(NOW() AS DATE) @@ -2711,7 +2747,7 @@ sub ReopenInvoice { return unless $invoiceid; - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $query = qq{ UPDATE aqinvoices SET closedate = NULL @@ -2764,17 +2800,17 @@ the invoice identified by $invoiceid. =cut sub MergeInvoices { - my ($invoiceid, $sourceids) = @_; + my ( $invoiceid, $sourceids ) = @_; return unless $invoiceid; foreach my $sourceid (@$sourceids) { next if $sourceid == $invoiceid; my $source = GetInvoiceDetails($sourceid); - foreach my $order (@{$source->{'orders'}}) { + foreach my $order ( @{ $source->{'orders'} } ) { $order->{'invoiceid'} = $invoiceid; ModOrder($order); } - DelInvoice($source->{'invoiceid'}); + DelInvoice( $source->{'invoiceid'} ); } return; } @@ -2791,8 +2827,8 @@ Returns a quantity sub GetBiblioCountByBasketno { my ($basketno) = @_; - my $dbh = C4::Context->dbh; - my $query = " + my $dbh = C4::Context->dbh; + my $query = " SELECT COUNT( DISTINCT( biblionumber ) ) FROM aqorders WHERE basketno = ? @@ -2874,29 +2910,29 @@ sub NotifyOrderUsers { my @borrowernumbers = GetOrderUsers($ordernumber); return unless @borrowernumbers; - my $order = GetOrder( $ordernumber ); + my $order = GetOrder($ordernumber); for my $borrowernumber (@borrowernumbers) { - my $patron = Koha::Patrons->find( $borrowernumber ); + my $patron = Koha::Patrons->find($borrowernumber); my $library = $patron->library->unblessed; - my $biblio = Koha::Biblios->find( $order->{biblionumber} )->unblessed; - my $letter = C4::Letters::GetPreparedLetter( + my $biblio = Koha::Biblios->find( $order->{biblionumber} )->unblessed; + my $letter = C4::Letters::GetPreparedLetter( module => 'acquisition', letter_code => 'ACQ_NOTIF_ON_RECEIV', branchcode => $library->{branchcode}, lang => $patron->lang, tables => { - 'branches' => $library, - 'borrowers' => $patron->unblessed, - 'biblio' => $biblio, - 'aqorders' => $order, + 'branches' => $library, + 'borrowers' => $patron->unblessed, + 'biblio' => $biblio, + 'aqorders' => $order, }, ); - if ( $letter ) { + if ($letter) { C4::Letters::EnqueueLetter( { - letter => $letter, - borrowernumber => $borrowernumber, - LibraryName => C4::Context->preference("LibraryName"), + letter => $letter, + borrowernumber => $borrowernumber, + LibraryName => C4::Context->preference("LibraryName"), message_transport_type => 'email', } ) or warn "can't enqueue letter $letter"; @@ -2920,15 +2956,14 @@ defaults are being applied to the record. sub FillWithDefaultValues { my ( $record, $params ) = @_; my $mandatory = $params->{only_mandatory}; - my $tagslib = C4::Biblio::GetMarcStructure( 1, 'ACQ', { unsafe => 1 } ); + my $tagslib = C4::Biblio::GetMarcStructure( 1, 'ACQ', { unsafe => 1 } ); if ($tagslib) { - my ($itemfield) = - C4::Biblio::GetMarcFromKohaField( 'items.itemnumber' ); + my ($itemfield) = C4::Biblio::GetMarcFromKohaField('items.itemnumber'); for my $tag ( sort keys %$tagslib ) { next unless $tag; next if $tag == $itemfield; for my $subfield ( sort keys %{ $tagslib->{$tag} } ) { - next if IsMarcStructureInternal($tagslib->{$tag}{$subfield}); + next if IsMarcStructureInternal( $tagslib->{$tag}{$subfield} ); next if $mandatory && !$tagslib->{$tag}{$subfield}{mandatory}; my $defaultvalue = $tagslib->{$tag}{$subfield}{defaultvalue}; if ( defined $defaultvalue and $defaultvalue ne '' ) { @@ -2937,27 +2972,16 @@ sub FillWithDefaultValues { for my $field (@fields) { if ( $field->is_control_field ) { $field->update($defaultvalue) if not defined $field->data; - } - elsif ( not defined $field->subfield($subfield) ) { - $field->add_subfields( - $subfield => $defaultvalue ); + } elsif ( not defined $field->subfield($subfield) ) { + $field->add_subfields( $subfield => $defaultvalue ); } } - } - else { - if ( $tag < 10 ) { # is_control_field + } else { + if ( $tag < 10 ) { # is_control_field + $record->insert_fields_ordered( MARC::Field->new( $tag, $defaultvalue ) ); + } else { $record->insert_fields_ordered( - MARC::Field->new( - $tag, $defaultvalue - ) - ); - } - else { - $record->insert_fields_ordered( - MARC::Field->new( - $tag, '', '', $subfield => $defaultvalue - ) - ); + MARC::Field->new( $tag, '', '', $subfield => $defaultvalue ) ); } } } diff --git a/C4/Auth.pm b/C4/Auth.pm index b13f2589a6..2443db5c62 100644 --- a/C4/Auth.pm +++ b/C4/Auth.pm @@ -60,16 +60,16 @@ use Koha::Session; # use utf8; use vars qw($ldap $cas $caslogout); -our (@ISA, @EXPORT_OK); +our ( @ISA, @EXPORT_OK ); #NOTE: The utility of keeping the safe_exit function is that it can be easily re-defined in unit tests and plugins sub safe_exit { + # It's fine for us to "exit" because CGI::Compile (used in Plack::App::WrapCGI) redefines "exit" for us automatically. # Since we only seem to use C4::Auth::safe_exit in a CGI context, we don't actually need PSGI detection at all here. exit; } - BEGIN { C4::Context->set_remote_address; @@ -87,7 +87,8 @@ BEGIN { if ($cas) { require C4::Auth_with_cas; # no import - import C4::Auth_with_cas qw(check_api_auth_cas checkpw_cas login_cas logout_cas login_cas_url logout_if_required multipleAuth getMultipleAuth); + import C4::Auth_with_cas + qw(check_api_auth_cas checkpw_cas login_cas logout_cas login_cas_url logout_if_required multipleAuth getMultipleAuth); } } @@ -164,7 +165,7 @@ sub get_template_and_user { my $cookie_mgr = Koha::CookieManager->new; # Get shibboleth login attribute - my $shib = C4::Context->config('useshibboleth') && shib_ok(); + my $shib = C4::Context->config('useshibboleth') && shib_ok(); my $shib_login = $shib ? get_login_shib() : undef; C4::Context->interface( $in->{type} ); @@ -210,79 +211,87 @@ sub get_template_and_user { # If we enforce GDPR and the user did not consent, redirect # Exceptions for consent page itself and SCI/SCO system - if( $in->{type} eq 'opac' && $user && - $in->{'template_name'} !~ /^(opac-page|opac-patron-consent|sc[io]\/)/ && - C4::Context->preference('PrivacyPolicyConsent') eq 'Enforced' ) + if ( $in->{type} eq 'opac' + && $user + && $in->{'template_name'} !~ /^(opac-page|opac-patron-consent|sc[io]\/)/ + && C4::Context->preference('PrivacyPolicyConsent') eq 'Enforced' ) { - my $consent = Koha::Patron::Consents->search({ - borrowernumber => getborrowernumber($user), - type => 'GDPR_PROCESSING', - given_on => { '!=', undef }, - })->next; - if( !$consent ) { - print $in->{query}->redirect(-uri => '/cgi-bin/koha/opac-patron-consent.pl', -cookie => $cookie); + my $consent = Koha::Patron::Consents->search( + { + borrowernumber => getborrowernumber($user), + type => 'GDPR_PROCESSING', + given_on => { '!=', undef }, + } + )->next; + if ( !$consent ) { + print $in->{query}->redirect( -uri => '/cgi-bin/koha/opac-patron-consent.pl', -cookie => $cookie ); safe_exit; } } if ( $in->{type} eq 'opac' && $user ) { my $is_sco_user; - if ($session){ + if ($session) { $is_sco_user = $session->param('sco_user'); } my $kick_out; if ( -# If the user logged in is the SCO user and they try to go out of the SCO module, -# log the user out removing the CGISESSID cookie - $in->{template_name} !~ m|sco/| && $in->{template_name} !~ m|errors/errorpage.tt| + # If the user logged in is the SCO user and they try to go out of the SCO module, + # log the user out removing the CGISESSID cookie + $in->{template_name} !~ m|sco/| + && $in->{template_name} !~ m|errors/errorpage.tt| && ( - $is_sco_user || - ( - C4::Context->preference('AutoSelfCheckID') - && $user eq C4::Context->preference('AutoSelfCheckID') - ) + $is_sco_user + || ( C4::Context->preference('AutoSelfCheckID') + && $user eq C4::Context->preference('AutoSelfCheckID') ) + ) ) - ) { $kick_out = 1; - } - elsif ( -# If the user logged in is the SCI user and they try to go out of the SCI module, -# kick them out unless it is SCO with a valid permission -# or they are a superlibrarian - $in->{template_name} !~ m|sci/| && $in->{template_name} !~ m|errors/errorpage.tt| + } elsif ( + + # If the user logged in is the SCI user and they try to go out of the SCI module, + # kick them out unless it is SCO with a valid permission + # or they are a superlibrarian + $in->{template_name} !~ m|sci/| + && $in->{template_name} !~ m|errors/errorpage.tt| && haspermission( $user, { self_check => 'self_checkin_module' } ) - && !( - $in->{template_name} =~ m|sco/| && haspermission( - $user, { self_check => 'self_checkout_module' } - ) + && !( $in->{template_name} =~ m|sco/| && haspermission( $user, { self_check => 'self_checkout_module' } ) ) + && $flags + && $flags->{superlibrarian} != 1 ) - && $flags && $flags->{superlibrarian} != 1 - ) { $kick_out = 1; } if ($kick_out) { - $template = C4::Templates::gettemplate( 'opac-auth.tt', 'opac', - $in->{query} ); - $cookie = $cookie_mgr->replace_in_list( $cookie, $in->{query}->cookie( - -name => 'CGISESSID', - -value => '', - -HttpOnly => 1, - -secure => ( C4::Context->https_enabled() ? 1 : 0 ), - -sameSite => 'Lax', - )); + $template = C4::Templates::gettemplate( + 'opac-auth.tt', 'opac', + $in->{query} + ); + $cookie = $cookie_mgr->replace_in_list( + $cookie, + $in->{query}->cookie( + -name => 'CGISESSID', + -value => '', + -HttpOnly => 1, + -secure => ( C4::Context->https_enabled() ? 1 : 0 ), + -sameSite => 'Lax', + ) + ); #NOTE: This JWT should only be used by the self-check controllers - $cookie = $cookie_mgr->replace_in_list( $cookie, $in->{query}->cookie( - -name => 'JWT', - -value => '', - -HttpOnly => 1, - -secure => ( C4::Context->https_enabled() ? 1 : 0 ), - -sameSite => 'Lax', - )); + $cookie = $cookie_mgr->replace_in_list( + $cookie, + $in->{query}->cookie( + -name => 'JWT', + -value => '', + -HttpOnly => 1, + -secure => ( C4::Context->https_enabled() ? 1 : 0 ), + -sameSite => 'Lax', + ) + ); my $auth_error = $in->{query}->param('auth_error'); @@ -299,8 +308,8 @@ sub get_template_and_user { cookie => $cookie, 'X-Frame-Options' => 'SAMEORIGIN' } - ), - $template->output; + ), + $template->output; safe_exit; } } @@ -314,7 +323,7 @@ sub get_template_and_user { # as SSL certs against an email address) $borrowernumber = getborrowernumber($user) if defined($user); if ( !defined($borrowernumber) && defined($user) ) { - $patron = Koha::Patrons->find( $user ); + $patron = Koha::Patrons->find($user); if ($patron) { $borrowernumber = $user; @@ -323,7 +332,8 @@ sub get_template_and_user { $user = $patron->firstname . ' ' . $patron->surname; } } else { - $patron = Koha::Patrons->find( $borrowernumber ); + $patron = Koha::Patrons->find($borrowernumber); + # FIXME What to do if $patron does not exist? } @@ -349,8 +359,8 @@ sub get_template_and_user { # We are going to use the $flags returned by checkauth # to create the template's parameters that will indicate # which menus the user can access. - my $authz = Koha::Auth::Permissions->get_authz_from_flags({ flags => $flags }); - foreach my $permission ( keys %{ $authz } ){ + my $authz = Koha::Auth::Permissions->get_authz_from_flags( { flags => $flags } ); + foreach my $permission ( keys %{$authz} ) { $template->param( $permission => $authz->{$permission} ); } @@ -368,8 +378,8 @@ sub get_template_and_user { # We show the link in opac $template->param( EnableOpacSearchHistory => 1 ); } - if (C4::Context->preference('LoadSearchHistoryToTheFirstLoggedUser')) - { + if ( C4::Context->preference('LoadSearchHistoryToTheFirstLoggedUser') ) { + # And if there are searches performed when the user was not logged in, # we add them to the logged-in search history my @recentSearches = C4::Search::History::get_from_session( { cgi => $in->{'query'} } ); @@ -379,7 +389,8 @@ sub get_template_and_user { VALUES (?, ?, ?, ?, ?, ?, ?) }; my $sth = $dbh->prepare($query); - $sth->execute( $borrowernumber, + $sth->execute( + $borrowernumber, $in->{query}->cookie("CGISESSID"), $_->{query_desc}, $_->{query_cgi}, @@ -390,21 +401,21 @@ sub get_template_and_user { # clear out the search history from the session now that # we've saved it to the database - } - } - C4::Search::History::set_to_session( { cgi => $in->{'query'}, search_history => [] } ); + } + } + C4::Search::History::set_to_session( { cgi => $in->{'query'}, search_history => [] } ); } elsif ( $in->{type} eq 'intranet' and C4::Context->preference('EnableSearchHistory') ) { $template->param( EnableSearchHistory => 1 ); } - } - else { # if this is an anonymous session, setup to display public lists... + } else { # if this is an anonymous session, setup to display public lists... # If shibboleth is enabled, and we're in an anonymous session, we should allow # the user to attempt login via shibboleth. if ($shib) { - $template->param( shibbolethAuthentication => $shib, - shibbolethLoginUrl => login_shib_url( $in->{'query'} ), + $template->param( + shibbolethAuthentication => $shib, + shibbolethLoginUrl => login_shib_url( $in->{'query'} ), ); # If shibboleth is enabled and we have a shibboleth login attribute, @@ -415,7 +426,7 @@ sub get_template_and_user { } } - if ( $in->{'type'} eq 'opac' ){ + if ( $in->{'type'} eq 'opac' ) { require Koha::Virtualshelves; my $some_public_shelves = Koha::Virtualshelves->get_some_shelves( { @@ -423,7 +434,7 @@ sub get_template_and_user { } ); $template->param( - some_public_shelves => $some_public_shelves, + some_public_shelves => $some_public_shelves, ); # Set default branch if one has been passed by the environment. @@ -435,19 +446,19 @@ sub get_template_and_user { # Note that value must be defined in order to override via ENV foreach my $syspref ( qw( - OPACUserCSS - OPACUserJS - IntranetUserCSS - IntranetUserJS - OpacAdditionalStylesheet - opaclayoutstylesheet - intranetcolorstylesheet - intranetstylesheet + OPACUserCSS + OPACUserJS + IntranetUserCSS + IntranetUserJS + OpacAdditionalStylesheet + opaclayoutstylesheet + intranetcolorstylesheet + intranetstylesheet + ) ) - ) { $ENV{"OVERRIDE_SYSPREF_$syspref"} = q{} - if $in->{'query'}->param("DISABLE_SYSPREF_$syspref"); + if $in->{'query'}->param("DISABLE_SYSPREF_$syspref"); } # Anonymous opac search history @@ -463,29 +474,29 @@ sub get_template_and_user { $template->param( dateformat => C4::Context->preference('dateformat') ); } - $template->param(auth_forwarded_hash => scalar $in->{'query'}->param('auth_forwarded_hash')); + $template->param( auth_forwarded_hash => scalar $in->{'query'}->param('auth_forwarded_hash') ); # these template parameters are set the same regardless of $in->{'type'} my $minPasswordLength = C4::Context->preference('minPasswordLength'); $minPasswordLength = 3 if not $minPasswordLength or $minPasswordLength < 3; $template->param( - EnhancedMessagingPreferences => C4::Context->preference('EnhancedMessagingPreferences'), - GoogleJackets => C4::Context->preference("GoogleJackets"), - OpenLibraryCovers => C4::Context->preference("OpenLibraryCovers"), - KohaAdminEmailAddress => "" . C4::Context->preference("KohaAdminEmailAddress"), - LoginFirstname => ( C4::Context->userenv ? C4::Context->userenv->{"firstname"} : "Bel" ), - LoginSurname => C4::Context->userenv ? C4::Context->userenv->{"surname"} : "Inconnu", - emailaddress => C4::Context->userenv ? C4::Context->userenv->{"emailaddress"} : undef, - TagsEnabled => C4::Context->preference("TagsEnabled"), - hide_marc => C4::Context->preference("hide_marc"), - item_level_itypes => C4::Context->preference('item-level_itypes'), - patronimages => C4::Context->preference("patronimages"), - singleBranchMode => ( Koha::Libraries->search->count == 1 ), - noItemTypeImages => C4::Context->preference("noItemTypeImages"), - marcflavour => C4::Context->preference("marcflavour"), - OPACBaseURL => C4::Context->preference('OPACBaseURL'), - minPasswordLength => $minPasswordLength, + EnhancedMessagingPreferences => C4::Context->preference('EnhancedMessagingPreferences'), + GoogleJackets => C4::Context->preference("GoogleJackets"), + OpenLibraryCovers => C4::Context->preference("OpenLibraryCovers"), + KohaAdminEmailAddress => "" . C4::Context->preference("KohaAdminEmailAddress"), + LoginFirstname => ( C4::Context->userenv ? C4::Context->userenv->{"firstname"} : "Bel" ), + LoginSurname => C4::Context->userenv ? C4::Context->userenv->{"surname"} : "Inconnu", + emailaddress => C4::Context->userenv ? C4::Context->userenv->{"emailaddress"} : undef, + TagsEnabled => C4::Context->preference("TagsEnabled"), + hide_marc => C4::Context->preference("hide_marc"), + item_level_itypes => C4::Context->preference('item-level_itypes'), + patronimages => C4::Context->preference("patronimages"), + singleBranchMode => ( Koha::Libraries->search->count == 1 ), + noItemTypeImages => C4::Context->preference("noItemTypeImages"), + marcflavour => C4::Context->preference("marcflavour"), + OPACBaseURL => C4::Context->preference('OPACBaseURL'), + minPasswordLength => $minPasswordLength, ); if ( $in->{'type'} eq "intranet" ) { @@ -520,8 +531,7 @@ sub get_template_and_user { useDischarge => C4::Context->preference('useDischarge'), virtualshelves => C4::Context->preference("virtualshelves"), ); - } - else { + } else { warn "template type should be OPAC, here it is=[" . $in->{'type'} . "]" unless ( $in->{'type'} eq 'opac' ); #TODO : replace LibraryName syspref with 'system name', and remove this html processing @@ -533,7 +543,8 @@ sub get_template_and_user { # if the page is not opac-detail and not the "add to list" page # and not the "edit comments" page if ( C4::Context->preference("OpacBrowseResults") - && $in->{'template_name'} =~ /opac-(.+)\.(?:tt|tmpl)$/ ) { + && $in->{'template_name'} =~ /opac-(.+)\.(?:tt|tmpl)$/ ) + { my $pagename = $1; unless ( $pagename =~ /^(?:MARC|ISBD)?detail$/ or $pagename =~ /^showmarc$/ @@ -548,15 +559,17 @@ sub get_template_and_user { my $opac_search_limit = $ENV{'OPAC_SEARCH_LIMIT'}; my $opac_limit_override = $ENV{'OPAC_LIMIT_OVERRIDE'}; my $opac_name = ''; - if ( - ( $opac_limit_override && $opac_search_limit && $opac_search_limit =~ /^branch:([\w-]+)/ ) || - ( $in->{'query'}->param('limit') && $in->{'query'}->param('limit') =~ /^branch:([\w-]+)/ ) || - ( $in->{'query'}->param('limit') && $in->{'query'}->param('limit') =~ /^multibranchlimit:(\w+)/ ) - ) { + if ( ( $opac_limit_override && $opac_search_limit && $opac_search_limit =~ /^branch:([\w-]+)/ ) + || ( $in->{'query'}->param('limit') && $in->{'query'}->param('limit') =~ /^branch:([\w-]+)/ ) + || ( $in->{'query'}->param('limit') && $in->{'query'}->param('limit') =~ /^multibranchlimit:(\w+)/ ) ) + { $opac_name = $1; # opac_search_limit is a branch, so we use it. } elsif ( $in->{'query'}->param('multibranchlimit') ) { $opac_name = $in->{'query'}->param('multibranchlimit'); - } elsif ( C4::Context->preference("SearchMyLibraryFirst") && C4::Context->userenv && C4::Context->userenv->{'branch'} ) { + } elsif ( C4::Context->preference("SearchMyLibraryFirst") + && C4::Context->userenv + && C4::Context->userenv->{'branch'} ) + { $opac_name = C4::Context->userenv->{'branch'}; } @@ -565,36 +578,39 @@ sub get_template_and_user { if ( C4::Context->preference('Suggestion') && C4::Context->preference('AnonSuggestions') ) { $can_make_suggestions = 1; } elsif ( C4::Context->userenv && C4::Context->userenv->{'number'} ) { - $can_make_suggestions = Koha::Patrons->find(C4::Context->userenv->{'number'})->category->can_make_suggestions; + $can_make_suggestions = + Koha::Patrons->find( C4::Context->userenv->{'number'} )->category->can_make_suggestions; } - my @search_groups = Koha::Library::Groups->get_search_groups({ interface => 'opac' })->as_list; + my @search_groups = Koha::Library::Groups->get_search_groups( { interface => 'opac' } )->as_list; $template->param( - AnonSuggestions => "" . C4::Context->preference("AnonSuggestions"), - LibrarySearchGroups => \@search_groups, - opac_name => $opac_name, - LibraryName => "" . C4::Context->preference("LibraryName"), - LibraryNameTitle => "" . $LibraryNameTitle, - OPACAmazonCoverImages => C4::Context->preference("OPACAmazonCoverImages"), - OPACFRBRizeEditions => C4::Context->preference("OPACFRBRizeEditions"), - OpacHighlightedWords => C4::Context->preference("OpacHighlightedWords"), - OPACShelfBrowser => "" . C4::Context->preference("OPACShelfBrowser"), - OPACURLOpenInNewWindow => "" . C4::Context->preference("OPACURLOpenInNewWindow"), - OpacAuthorities => C4::Context->preference("OpacAuthorities"), - opac_css_override => $ENV{'OPAC_CSS_OVERRIDE'}, - opac_search_limit => $opac_search_limit, - opac_limit_override => $opac_limit_override, - OpacBrowser => C4::Context->preference("OpacBrowser"), - OpacCloud => C4::Context->preference("OpacCloud"), - OpacKohaUrl => C4::Context->preference("OpacKohaUrl"), - OpacPasswordChange => C4::Context->preference("OpacPasswordChange"), - OPACPatronDetails => C4::Context->preference("OPACPatronDetails"), - OPACPrivacy => C4::Context->preference("OPACPrivacy"), - OPACFinesTab => C4::Context->preference("OPACFinesTab"), - OpacTopissue => C4::Context->preference("OpacTopissue"), - 'Version' => C4::Context->preference('Version'), - hidelostitems => C4::Context->preference("hidelostitems"), - mylibraryfirst => ( C4::Context->preference("SearchMyLibraryFirst") && C4::Context->userenv ) ? C4::Context->userenv->{'branch'} : '', + AnonSuggestions => "" . C4::Context->preference("AnonSuggestions"), + LibrarySearchGroups => \@search_groups, + opac_name => $opac_name, + LibraryName => "" . C4::Context->preference("LibraryName"), + LibraryNameTitle => "" . $LibraryNameTitle, + OPACAmazonCoverImages => C4::Context->preference("OPACAmazonCoverImages"), + OPACFRBRizeEditions => C4::Context->preference("OPACFRBRizeEditions"), + OpacHighlightedWords => C4::Context->preference("OpacHighlightedWords"), + OPACShelfBrowser => "" . C4::Context->preference("OPACShelfBrowser"), + OPACURLOpenInNewWindow => "" . C4::Context->preference("OPACURLOpenInNewWindow"), + OpacAuthorities => C4::Context->preference("OpacAuthorities"), + opac_css_override => $ENV{'OPAC_CSS_OVERRIDE'}, + opac_search_limit => $opac_search_limit, + opac_limit_override => $opac_limit_override, + OpacBrowser => C4::Context->preference("OpacBrowser"), + OpacCloud => C4::Context->preference("OpacCloud"), + OpacKohaUrl => C4::Context->preference("OpacKohaUrl"), + OpacPasswordChange => C4::Context->preference("OpacPasswordChange"), + OPACPatronDetails => C4::Context->preference("OPACPatronDetails"), + OPACPrivacy => C4::Context->preference("OPACPrivacy"), + OPACFinesTab => C4::Context->preference("OPACFinesTab"), + OpacTopissue => C4::Context->preference("OpacTopissue"), + 'Version' => C4::Context->preference('Version'), + hidelostitems => C4::Context->preference("hidelostitems"), + mylibraryfirst => ( C4::Context->preference("SearchMyLibraryFirst") && C4::Context->userenv ) + ? C4::Context->userenv->{'branch'} + : '', opacbookbag => "" . C4::Context->preference("opacbookbag"), OpacFavicon => C4::Context->preference("OpacFavicon"), opaclanguagesdisplay => "" . C4::Context->preference("opaclanguagesdisplay"), @@ -621,7 +637,7 @@ sub get_template_and_user { OPACLocalCoverImages => C4::Context->preference("OPACLocalCoverImages"), PatronSelfRegistration => C4::Context->preference("PatronSelfRegistration"), PatronSelfRegistrationDefaultCategory => C4::Context->preference("PatronSelfRegistrationDefaultCategory"), - useDischarge => C4::Context->preference('useDischarge'), + useDischarge => C4::Context->preference('useDischarge'), ); $template->param( OpacPublic => '1' ) if ( $user || C4::Context->preference("OpacPublic") ); @@ -632,16 +648,18 @@ sub get_template_and_user { # Extract the language, let C4::Languages::getlanguage choose # what to do - my $language = C4::Languages::getlanguage( $in->{'query'} ); + my $language = C4::Languages::getlanguage( $in->{'query'} ); my $languagecookie = C4::Templates::getlanguagecookie( $in->{'query'}, $language ); $cookie = $cookie_mgr->replace_in_list( $cookie, $languagecookie ); } # user info - $template->param( loggedinusername => $user ); # OBSOLETE - Do not reuse this in template, use logged_in_user.userid instead - $template->param( loggedinusernumber => $borrowernumber ); # FIXME Should be replaced with logged_in_user.borrowernumber - $template->param( logged_in_user => $patron ); - $template->param( sessionID => $sessionID ); + $template->param( loggedinusername => $user ) + ; # OBSOLETE - Do not reuse this in template, use logged_in_user.userid instead + $template->param( loggedinusernumber => $borrowernumber ) + ; # FIXME Should be replaced with logged_in_user.borrowernumber + $template->param( logged_in_user => $patron ); + $template->param( sessionID => $sessionID ); return ( $template, $borrowernumber, $cookie, $flags ); } @@ -772,17 +790,17 @@ sub _version_check { sub _timeout_syspref { my $default_timeout = 600; - my $timeout = C4::Context->preference('timeout') || $default_timeout; + my $timeout = C4::Context->preference('timeout') || $default_timeout; # value in days, convert in seconds if ( $timeout =~ /^(\d+)[dD]$/ ) { $timeout = $1 * 86400; } + # value in hours, convert in seconds elsif ( $timeout =~ /^(\d+)[hH]$/ ) { $timeout = $1 * 3600; - } - elsif ( $timeout !~ m/^\d+$/ ) { + } elsif ( $timeout !~ m/^\d+$/ ) { warn "The value of the system preference 'timeout' is not correct, defaulting to $default_timeout"; $timeout = $default_timeout; } @@ -794,7 +812,7 @@ sub checkauth { my $query = shift; # Get shibboleth login attribute - my $shib = C4::Context->config('useshibboleth') && shib_ok(); + my $shib = C4::Context->config('useshibboleth') && shib_ok(); my $shib_login = $shib ? get_login_shib() : undef; # $authnotrequired will be set for scripts which will run without authentication @@ -803,7 +821,7 @@ sub checkauth { my $type = shift; my $emailaddress = shift; my $template_name = shift; - my $params = shift || {}; # do_not_print, skip_csrf_check + my $params = shift || {}; # do_not_print, skip_csrf_check my $skip_csrf_check = $params->{skip_csrf_check} || 0; $type = 'opac' unless $type; @@ -818,8 +836,7 @@ sub checkauth { opac-reset-password.tt ilsdi.tt ); - $authnotrequired = 0 unless grep { $_ eq $template_name } - @allowed_scripts_for_private_opac; + $authnotrequired = 0 unless grep { $_ eq $template_name } @allowed_scripts_for_private_opac; } my $timeout = _timeout_syspref(); @@ -837,6 +854,7 @@ sub checkauth { my $anon_search_history; my $cas_ticket = ''; + # This parameter is the name of the CAS server we want to authenticate against, # when using authentication against multiple CAS servers, as configured in Auth_cas_servers.yaml my $casparam = $query->param('cas'); @@ -844,10 +862,11 @@ sub checkauth { my $session; my $invalid_otp_token; - my $require_2FA = - ( $type ne "opac" # Only available for the staff interface - && C4::Context->preference('TwoFactorAuthentication') ne "disabled" ) # If "enabled" or "enforced" - ? 1 : 0; + my $require_2FA = ( + $type ne "opac" # Only available for the staff interface + && C4::Context->preference('TwoFactorAuthentication') ne "disabled" + ) # If "enabled" or "enforced" + ? 1 : 0; # Basic authentication is incompatible with the use of Shibboleth, # as Shibboleth may return REMOTE_USER as a Shibboleth attribute, @@ -861,21 +880,25 @@ sub checkauth { if ( !$shib and defined( $ENV{'REMOTE_USER'} ) and $ENV{'REMOTE_USER'} ne '' and $userid = $ENV{'REMOTE_USER'} ) { # Using Basic Authentication, no cookies required - $cookie = $cookie_mgr->replace_in_list( $cookie, $query->cookie( - -name => 'CGISESSID', - -value => '', - -HttpOnly => 1, - -secure => ( C4::Context->https_enabled() ? 1 : 0 ), - -sameSite => 'Lax', - )); - } - elsif ( $emailaddress) { + $cookie = $cookie_mgr->replace_in_list( + $cookie, + $query->cookie( + -name => 'CGISESSID', + -value => '', + -HttpOnly => 1, + -secure => ( C4::Context->https_enabled() ? 1 : 0 ), + -sameSite => 'Lax', + ) + ); + } elsif ($emailaddress) { + # the Google OpenID Connect passes an email address - } - elsif ( $sessionID = $query->cookie("CGISESSID") ) { # assignment, not comparison + } elsif ( $sessionID = $query->cookie("CGISESSID") ) { # assignment, not comparison my ( $return, $more_info ); + # NOTE: $flags in the following call is still undefined ! - ( $return, $session, $more_info ) = check_cookie_auth( $sessionID, $flags, + ( $return, $session, $more_info ) = check_cookie_auth( + $sessionID, $flags, { remote_addr => $ENV{REMOTE_ADDR}, skip_version_check => 1 } ); @@ -884,9 +907,9 @@ sub checkauth { } $auth_state = - $return eq 'ok' ? 'completed' - : $return eq 'additional-auth-needed' ? 'additional-auth-needed' - : 'failed'; + $return eq 'ok' ? 'completed' + : $return eq 'additional-auth-needed' ? 'additional-auth-needed' + : 'failed'; # We are at the second screen if the waiting-for-2FA is set in session # and otp_token param has been passed @@ -894,33 +917,36 @@ sub checkauth { && $auth_state eq 'additional-auth-needed' && ( my $otp_token = $query->param('otp_token') ) ) { - my $patron = Koha::Patrons->find( { userid => $userid } ); - my $auth = Koha::Auth::TwoFactorAuth->new( { patron => $patron } ); + my $patron = Koha::Patrons->find( { userid => $userid } ); + my $auth = Koha::Auth::TwoFactorAuth->new( { patron => $patron } ); my $verified = $auth->verify($otp_token); $auth->clear; - if ( $verified ) { + if ($verified) { + # The token is correct, the user is fully logged in! $auth_state = 'completed'; - $session->param( 'waiting-for-2FA', 0 ); + $session->param( 'waiting-for-2FA', 0 ); $session->param( 'waiting-for-2FA-setup', 0 ); - # This is an ugly trick to pass the test - # $query->param('koha_login_context') && ( $q_userid ne $userid ) - # few lines later + # This is an ugly trick to pass the test + # $query->param('koha_login_context') && ( $q_userid ne $userid ) + # few lines later $q_userid = $userid; - } - else { + } else { $invalid_otp_token = 1; } } if ( $auth_state eq 'completed' ) { - Koha::Logger->get->debug(sprintf "AUTH_SESSION: (%s)\t%s %s - %s", map { $session->param($_) || q{} } qw(cardnumber firstname surname branch)); + Koha::Logger->get->debug( + sprintf "AUTH_SESSION: (%s)\t%s %s - %s", + map { $session->param($_) || q{} } qw(cardnumber firstname surname branch) + ); - if ( ( $query->param('koha_login_context') && ( $q_userid ne $userid ) ) + if ( ( $query->param('koha_login_context') && ( $q_userid ne $userid ) ) || ( $cas && $query->param('ticket') && !C4::Context->userenv->{'id'} ) - || ( $shib && $shib_login && !$logout && !C4::Context->userenv->{'id'} ) - ) { + || ( $shib && $shib_login && !$logout && !C4::Context->userenv->{'id'} ) ) + { #if a user enters an id ne to the id in the current session, we need to log them in... #first we need to clear the anonymous session... @@ -930,20 +956,23 @@ sub checkauth { $cookie = $cookie_mgr->clear_unless( $query->cookie, @$cookie ); C4::Context::unset_userenv(); $sessionID = undef; - undef $userid; # IMPORTANT: this assures us a new session in code below + undef $userid; # IMPORTANT: this assures us a new session in code below $auth_state = 'failed'; - } elsif (!$logout) { + } elsif ( !$logout ) { - $cookie = $cookie_mgr->replace_in_list( $cookie, $query->cookie( - -name => 'CGISESSID', - -value => $session->id, - -HttpOnly => 1, - -secure => ( C4::Context->https_enabled() ? 1 : 0 ), - -sameSite => 'Lax', - )); + $cookie = $cookie_mgr->replace_in_list( + $cookie, + $query->cookie( + -name => 'CGISESSID', + -value => $session->id, + -HttpOnly => 1, + -secure => ( C4::Context->https_enabled() ? 1 : 0 ), + -sameSite => 'Lax', + ) + ); $flags = haspermission( $userid, $flagsrequired ); - unless ( $flags ) { + unless ($flags) { $auth_state = 'failed'; $info{'nopermission'} = 1; } @@ -973,29 +1002,30 @@ sub checkauth { # voluntary logout the user # check wether the user was using their shibboleth session or a local one my $shibSuccess = C4::Context->userenv ? C4::Context->userenv->{'shibboleth'} : undef; - if ( $session ) { + if ($session) { $session->delete(); $session->flush; } C4::Context::unset_userenv(); $cookie = $cookie_mgr->clear_unless( $query->cookie, @$cookie ); - if ($cas and $caslogout) { - logout_cas($query, $type); + if ( $cas and $caslogout ) { + logout_cas( $query, $type ); } # If we are in a shibboleth session (shibboleth is enabled, a shibboleth match attribute is set and matches koha matchpoint) - if ( $shib and $shib_login and $shibSuccess) { + if ( $shib and $shib_login and $shibSuccess ) { logout_shib($query); } - $session = undef; + $session = undef; $auth_state = 'logout'; } - unless ( $userid ) { + unless ($userid) { + #we initiate a session prior to checking for a username to allow for anonymous sessions... - if( !$session or !$sessionID ) { # if we cleared sessionID, we need a new session + if ( !$session or !$sessionID ) { # if we cleared sessionID, we need a new session $session = get_session() or die "Auth ERROR: Cannot get_session()"; } @@ -1007,19 +1037,22 @@ sub checkauth { } $sessionID = $session->id; - $cookie = $cookie_mgr->replace_in_list( $cookie, $query->cookie( - -name => 'CGISESSID', - -value => $sessionID, - -HttpOnly => 1, - -secure => ( C4::Context->https_enabled() ? 1 : 0 ), - -sameSite => 'Lax', - )); + $cookie = $cookie_mgr->replace_in_list( + $cookie, + $query->cookie( + -name => 'CGISESSID', + -value => $sessionID, + -HttpOnly => 1, + -secure => ( C4::Context->https_enabled() ? 1 : 0 ), + -sameSite => 'Lax', + ) + ); my $pki_field = C4::Context->preference('AllowPKIAuth'); if ( !defined($pki_field) ) { print STDERR "ERROR: Missing system preference AllowPKIAuth.\n"; $pki_field = 'None'; } - if ( ( $cas && $query->param('ticket') ) + if ( ( $cas && $query->param('ticket') ) || $q_userid || ( $shib && $shib_login ) || $pki_field ne 'None' @@ -1035,8 +1068,8 @@ sub checkauth { # Do not pass password here, else shib will not be checked in checkpw. ( $return, $cardnumber, $retuserid ) = checkpw( $q_userid, undef, $query ); - $userid = $retuserid; - $shibSuccess = $return; + $userid = $retuserid; + $shibSuccess = $return; $info{'invalidShibLogin'} = 1 unless ($return); } @@ -1046,20 +1079,19 @@ sub checkauth { my $retuserid; my $patron; ( $return, $cardnumber, $retuserid, $patron, $cas_ticket ) = - checkpw( $userid, $password, $query, $type ); + checkpw( $userid, $password, $query, $type ); $userid = $retuserid; $info{'invalidCasLogin'} = 1 unless ($return); - } - elsif ( $emailaddress ) { + } elsif ($emailaddress) { my $value = $emailaddress; # If we're looking up the email, there's a chance that the person # doesn't have a userid. So if there is none, we pass along the # borrower number, and the bits of code that need to know the user # ID will have to be smart enough to handle that. - my $patrons = Koha::Patrons->search({ email => $value }); - if ($patrons->count) { + my $patrons = Koha::Patrons->search( { email => $value } ); + if ( $patrons->count ) { # First the userid, then the borrowernum my $patron = $patrons->next; @@ -1069,27 +1101,25 @@ sub checkauth { } $return = $value ? 1 : 0; $userid = $value; - } - elsif ( + } elsif ( ( $pki_field eq 'Common Name' && $ENV{'SSL_CLIENT_S_DN_CN'} ) - || ( $pki_field eq 'emailAddress' + || ( $pki_field eq 'emailAddress' && $ENV{'SSL_CLIENT_S_DN_Email'} ) - ) + ) { my $value; if ( $pki_field eq 'Common Name' ) { $value = $ENV{'SSL_CLIENT_S_DN_CN'}; - } - elsif ( $pki_field eq 'emailAddress' ) { + } elsif ( $pki_field eq 'emailAddress' ) { $value = $ENV{'SSL_CLIENT_S_DN_Email'}; # If we're looking up the email, there's a chance that the person # doesn't have a userid. So if there is none, we pass along the # borrower number, and the bits of code that need to know the user # ID will have to be smart enough to handle that. - my $patrons = Koha::Patrons->search({ email => $value }); - if ($patrons->count) { + my $patrons = Koha::Patrons->search( { email => $value } ); + if ( $patrons->count ) { # First the userid, then the borrowernum my $patron = $patrons->next; @@ -1102,20 +1132,19 @@ sub checkauth { $return = $value ? 1 : 0; $userid = $value; - } - else { + } else { my $retuserid; if ( $request_method eq 'POST' || ( C4::Context->preference('AutoSelfCheckID') && $q_userid eq C4::Context->preference('AutoSelfCheckID') ) - ) + ) { my $patron; ( $return, $cardnumber, $retuserid, $patron, $cas_ticket ) = - checkpw( $q_userid, $password, $query, $type ); + checkpw( $q_userid, $password, $query, $type ); $userid = $retuserid if ($retuserid); $info{'invalid_username_or_password'} = 1 unless ($return); } @@ -1127,26 +1156,23 @@ sub checkauth { $shib && !$shibSuccess && ( - ( - ( $type eq 'opac' ) - && C4::Context->preference('OPACShibOnly') - ) + ( ( $type eq 'opac' ) && C4::Context->preference('OPACShibOnly') ) || ( ( $type ne 'opac' ) && C4::Context->preference('staffShibOnly') ) ) - ) + ) { $return = 0; } # $return: 1 = valid user - if( $return && $return > 0 ) { + if ( $return && $return > 0 ) { if ( $flags = haspermission( $userid, $flagsrequired ) ) { $auth_state = "logged_in"; - } - else { + } else { $auth_state = 'failed'; + # FIXME We could add $return = 0; or even delete the session? # Currently return == 1 and we will fill session info later on, # although we do present an authorization failure. (Yes, the @@ -1154,9 +1180,11 @@ sub checkauth { $info{'nopermission'} = 1; C4::Context::unset_userenv(); } - my ( $borrowernumber, $firstname, $surname, $userflags, - $branchcode, $branchname, $emailaddress, $desk_id, - $desk_name, $register_id, $register_name ); + my ( + $borrowernumber, $firstname, $surname, $userflags, + $branchcode, $branchname, $emailaddress, $desk_id, + $desk_name, $register_id, $register_name + ); if ( $return == 1 ) { my $select = " @@ -1177,8 +1205,10 @@ sub checkauth { } } if ( $sth->rows ) { - ( $borrowernumber, $firstname, $surname, $userflags, - $branchcode, $branchname, $emailaddress ) = $sth->fetchrow; + ( + $borrowernumber, $firstname, $surname, $userflags, + $branchcode, $branchname, $emailaddress + ) = $sth->fetchrow; } # launch a sequence to check if we have a ip for the branch, i @@ -1187,11 +1217,13 @@ sub checkauth { my $ip = $ENV{'REMOTE_ADDR'}; # if they specify at login, use that - my $patron = Koha::Patrons->find({userid => $userid}); - if ( $query->param('branch') && ( haspermission($userid, { 'loggedinlibrary'=> 1 }) || $patron->is_superlibrarian ) ) { + my $patron = Koha::Patrons->find( { userid => $userid } ); + if ( $query->param('branch') + && ( haspermission( $userid, { 'loggedinlibrary' => 1 } ) || $patron->is_superlibrarian ) ) + { $branchcode = $query->param('branch'); my $library = Koha::Libraries->find($branchcode); - $branchname = $library? $library->branchname: ''; + $branchname = $library ? $library->branchname : ''; } if ( $query->param('desk_id') ) { $desk_id = $query->param('desk_id'); @@ -1200,29 +1232,34 @@ sub checkauth { } if ( C4::Context->preference('UseCashRegisters') ) { my $register = - $query->param('register_id') - ? Koha::Cash::Registers->find($query->param('register_id')) - : Koha::Cash::Registers->search( + $query->param('register_id') + ? Koha::Cash::Registers->find( $query->param('register_id') ) + : Koha::Cash::Registers->search( { branch => $branchcode, branch_default => 1 }, - { rows => 1 } )->single; + { rows => 1 } + )->single; $register_id = $register->id if ($register); $register_name = $register->name if ($register); } if ( $type ne 'opac' ) { my $branches = { map { $_->branchcode => $_->unblessed } Koha::Libraries->search->as_list }; if ( C4::Context->preference('StaffLoginRestrictLibraryByIP') ) { + # we have to check they are coming from the right ip range my $domain = $branches->{$branchcode}->{'branchip'} // q{}; $domain =~ s|\.\*||g; $domain =~ s/\s+//g; if ( $domain && $ip !~ /^$domain/ ) { - $cookie = $cookie_mgr->replace_in_list( $cookie, $query->cookie( - -name => 'CGISESSID', - -value => '', - -HttpOnly => 1, - -secure => ( C4::Context->https_enabled() ? 1 : 0 ), - -sameSite => 'Lax', - )); + $cookie = $cookie_mgr->replace_in_list( + $cookie, + $query->cookie( + -name => 'CGISESSID', + -value => '', + -HttpOnly => 1, + -secure => ( C4::Context->https_enabled() ? 1 : 0 ), + -sameSite => 'Lax', + ) + ); $info{'wrongip'} = 1; $auth_state = "failed"; } @@ -1260,30 +1297,30 @@ sub checkauth { } my $is_sco_user = 0; - if ( $query->param('sco_user_login') && ( $query->param('sco_user_login') eq '1' ) ){ + if ( $query->param('sco_user_login') && ( $query->param('sco_user_login') eq '1' ) ) { $is_sco_user = 1; } - $session->param( 'number', $borrowernumber ); - $session->param( 'id', $userid ); - $session->param( 'cardnumber', $cardnumber ); - $session->param( 'firstname', $firstname ); - $session->param( 'surname', $surname ); - $session->param( 'branch', $branchcode ); - $session->param( 'branchname', $branchname ); - $session->param( 'desk_id', $desk_id); - $session->param( 'desk_name', $desk_name); - $session->param( 'flags', $userflags ); - $session->param( 'emailaddress', $emailaddress ); - $session->param( 'ip', $session->remote_addr() ); - $session->param( 'lasttime', time() ); - $session->param( 'interface', $type); - $session->param( 'shibboleth', $shibSuccess ); - $session->param( 'register_id', $register_id ); - $session->param( 'register_name', $register_name ); - $session->param( 'sco_user', $is_sco_user ); + $session->param( 'number', $borrowernumber ); + $session->param( 'id', $userid ); + $session->param( 'cardnumber', $cardnumber ); + $session->param( 'firstname', $firstname ); + $session->param( 'surname', $surname ); + $session->param( 'branch', $branchcode ); + $session->param( 'branchname', $branchname ); + $session->param( 'desk_id', $desk_id ); + $session->param( 'desk_name', $desk_name ); + $session->param( 'flags', $userflags ); + $session->param( 'emailaddress', $emailaddress ); + $session->param( 'ip', $session->remote_addr() ); + $session->param( 'lasttime', time() ); + $session->param( 'interface', $type ); + $session->param( 'shibboleth', $shibSuccess ); + $session->param( 'register_id', $register_id ); + $session->param( 'register_name', $register_name ); + $session->param( 'sco_user', $is_sco_user ); } - $session->param('cas_ticket', $cas_ticket) if $cas_ticket; + $session->param( 'cas_ticket', $cas_ticket ) if $cas_ticket; C4::Context->set_userenv( $session->param('number'), $session->param('id'), $session->param('cardnumber'), $session->param('firstname'), @@ -1295,6 +1332,7 @@ sub checkauth { ); } + # $return: 0 = invalid user # reset to anonymous session else { @@ -1302,10 +1340,10 @@ sub checkauth { $info{'invalid_username_or_password'} = 1; C4::Context::unset_userenv(); } - $session->param( 'lasttime', time() ); - $session->param( 'ip', $session->remote_addr() ); + $session->param( 'lasttime', time() ); + $session->param( 'ip', $session->remote_addr() ); $session->param( 'sessiontype', 'anon' ); - $session->param( 'interface', $type); + $session->param( 'interface', $type ); } } # END if ( $q_userid elsif ( $type eq "opac" ) { @@ -1316,45 +1354,51 @@ sub checkauth { $session->param( 'ip', $session->remote_addr() ); $session->param( 'lasttime', time() ); $session->param( 'sessiontype', 'anon' ); - $session->param( 'interface', $type); + $session->param( 'interface', $type ); } $session->flush; } # END unless ($userid) - if ( $auth_state eq 'logged_in' ) { $auth_state = 'completed'; # Auth is completed unless an additional auth is needed - if ( $require_2FA ) { - my $patron = Koha::Patrons->find({userid => $userid}); - if ( C4::Context->preference('TwoFactorAuthentication') eq "enforced" && $patron->auth_method eq 'password' ) { + if ($require_2FA) { + my $patron = Koha::Patrons->find( { userid => $userid } ); + if ( C4::Context->preference('TwoFactorAuthentication') eq "enforced" + && $patron->auth_method eq 'password' ) + { $auth_state = 'setup-additional-auth-needed'; - $session->param('waiting-for-2FA-setup', 1); - %info = ();# We remove the warnings/errors we may have set incorrectly before + $session->param( 'waiting-for-2FA-setup', 1 ); + %info = (); # We remove the warnings/errors we may have set incorrectly before } elsif ( $patron->auth_method eq 'two-factor' ) { + # Ask for the OTP token $auth_state = 'additional-auth-needed'; - $session->param('waiting-for-2FA', 1); - %info = ();# We remove the warnings/errors we may have set incorrectly before + $session->param( 'waiting-for-2FA', 1 ); + %info = (); # We remove the warnings/errors we may have set incorrectly before } } } # finished authentification, now respond if ( $auth_state eq 'completed' || $authnotrequired ) { + # successful login unless (@$cookie) { - $cookie = $cookie_mgr->replace_in_list( $cookie, $query->cookie( - -name => 'CGISESSID', - -value => '', - -HttpOnly => 1, - -secure => ( C4::Context->https_enabled() ? 1 : 0 ), - -sameSite => 'Lax', - )); + $cookie = $cookie_mgr->replace_in_list( + $cookie, + $query->cookie( + -name => 'CGISESSID', + -value => '', + -HttpOnly => 1, + -secure => ( C4::Context->https_enabled() ? 1 : 0 ), + -sameSite => 'Lax', + ) + ); } - my $patron = $userid ? Koha::Patrons->find({ userid => $userid }) : undef; + my $patron = $userid ? Koha::Patrons->find( { userid => $userid } ) : undef; $patron->update_lastseen('login') if $patron; # FIXME This is only needed for scripts not using plack @@ -1364,7 +1408,6 @@ sub checkauth { if $request_method eq 'GET'; } - if ( !$skip_csrf_check && $query->param('invalid_csrf_token') ) { Koha::Exceptions::Token::WrongCSRFToken->throw; } @@ -1372,8 +1415,13 @@ sub checkauth { # In case, that this request was a login attempt, we want to prevent that users can repost the opac login # request. We therefore redirect the user to the requested page again without the login parameters. # See Post/Redirect/Get (PRG) design pattern: https://en.wikipedia.org/wiki/Post/Redirect/Get - if ( $type eq "opac" && $query->param('koha_login_context') && $query->param('koha_login_context') ne 'sco' && $query->param('login_password') && $query->param('login_userid') ) { - my $uri = URI->new($query->url(-relative=>1, -query_string=>1)); + if ( $type eq "opac" + && $query->param('koha_login_context') + && $query->param('koha_login_context') ne 'sco' + && $query->param('login_password') + && $query->param('login_userid') ) + { + my $uri = URI->new( $query->url( -relative => 1, -query_string => 1 ) ); $uri->query_param_delete('login_userid'); $uri->query_param_delete('login_password'); $uri->query_param_delete('koha_login_context'); @@ -1394,10 +1442,10 @@ sub checkauth { # # - my $patron = Koha::Patrons->find({ userid => $q_userid }); # Not necessary logged in! + my $patron = Koha::Patrons->find( { userid => $q_userid } ); # Not necessary logged in! # get the inputs from the incoming query - my @inputs = (); + my @inputs = (); my @inputs_to_clean = qw( login_userid login_password ticket logout.x otp_token ); foreach my $name ( param $query) { next if grep { $name eq $_ } @inputs_to_clean; @@ -1409,9 +1457,9 @@ sub checkauth { $LibraryNameTitle =~ s/<(?:\/?)(?:br|p)\s*(?:\/?)>/ /sgi; $LibraryNameTitle =~ s/<(?:[^<>'"]|'(?:[^']*)'|"(?:[^"]*)")*>//sg; - my $auth_error = $query->param('auth_error'); + my $auth_error = $query->param('auth_error'); my $auth_template_name = ( $type eq 'opac' ) ? 'opac-auth.tt' : 'auth.tt'; - my $template = C4::Templates::gettemplate( $auth_template_name, $type, $query ); + my $template = C4::Templates::gettemplate( $auth_template_name, $type, $query ); my $borrowernumber = $patron and $patron->borrowernumber; my $anonymous_patron = C4::Context->preference('AnonymousPatron'); @@ -1451,22 +1499,22 @@ sub checkauth { opac_css_override => $ENV{'OPAC_CSS_OVERRIDE'}, too_many_login_attempts => ( $patron and $patron->account_locked ), password_has_expired => ( $patron and $patron->password_expired ), - is_anonymous_patron => ( $is_anonymous_patron ), + is_anonymous_patron => ($is_anonymous_patron), password_expiration_date => ( $patron and $patron->password_expiration_date ), date_enrolled => ( $patron and $patron->dateenrolled ), auth_error => $auth_error, ); - $template->param( SCO_login => 1 ) if ( $query->param('sco_user_login') ); - $template->param( SCI_login => 1 ) if ( $query->param('sci_user_login') ); - $template->param( OpacPublic => C4::Context->preference("OpacPublic") ); + $template->param( SCO_login => 1 ) if ( $query->param('sco_user_login') ); + $template->param( SCI_login => 1 ) if ( $query->param('sci_user_login') ); + $template->param( OpacPublic => C4::Context->preference("OpacPublic") ); $template->param( loginprompt => 1 ) unless $info{'nopermission'}; if ( $auth_state eq 'additional-auth-needed' ) { my $patron = Koha::Patrons->find( { userid => $userid } ); $template->param( - TwoFA_prompt => 1, - invalid_otp_token => $invalid_otp_token, - notice_email_address => $patron->notice_email_address, # We could also pass logged_in_user if necessary + TwoFA_prompt => 1, + invalid_otp_token => $invalid_otp_token, + notice_email_address => $patron->notice_email_address, # We could also pass logged_in_user if necessary ); } @@ -1484,7 +1532,7 @@ sub checkauth { } ); $template->param( - some_public_shelves => $some_public_shelves, + some_public_shelves => $some_public_shelves, ); } @@ -1498,24 +1546,23 @@ sub checkauth { foreach my $key ( keys %$casservers ) { push @tmplservers, { name => $key, value => login_cas_url( $query, $key, $type ) . "?cas=$key" }; } - $template->param( - casServersLoop => \@tmplservers - ); + $template->param( casServersLoop => \@tmplservers ); } else { $template->param( - casServerUrl => login_cas_url($query, undef, $type), + casServerUrl => login_cas_url( $query, undef, $type ), ); } - $template->param( - invalidCasLogin => $info{'invalidCasLogin'} - ); + $template->param( invalidCasLogin => $info{'invalidCasLogin'} ); } if ($shib) { + #If shibOnly is enabled just go ahead and redirect directly - if ( (($type eq 'opac') && C4::Context->preference('OPACShibOnly')) || (($type ne 'opac') && C4::Context->preference('staffShibOnly')) ) { - my $redirect_url = login_shib_url( $query ); + if ( ( ( $type eq 'opac' ) && C4::Context->preference('OPACShibOnly') ) + || ( ( $type ne 'opac' ) && C4::Context->preference('staffShibOnly') ) ) + { + my $redirect_url = login_shib_url($query); print $query->redirect( -uri => "$redirect_url", -status => 303 ); safe_exit; } @@ -1526,10 +1573,10 @@ sub checkauth { ); } - if (C4::Context->preference('GoogleOpenIDConnect')) { - if ($query->param("OpenIDConnectFailed")) { + if ( C4::Context->preference('GoogleOpenIDConnect') ) { + if ( $query->param("OpenIDConnectFailed") ) { my $reason = $query->param('OpenIDConnectFailed'); - $template->param(invalidGoogleOpenIDConnectLogin => $reason); + $template->param( invalidGoogleOpenIDConnectLogin => $reason ); } } @@ -1540,19 +1587,21 @@ sub checkauth { ); if ( $params->{do_not_print} ) { + # This must be used for testing purpose only! return ( undef, undef, undef, undef, $template ); } print $query->header( - { type => 'text/html', + { + type => 'text/html', charset => 'utf-8', cookie => $cookie, 'X-Frame-Options' => 'SAMEORIGIN', - -sameSite => 'Lax' + -sameSite => 'Lax' } - ), - $template->output; + ), + $template->output; safe_exit; } @@ -1598,7 +1647,7 @@ sub check_api_auth { my $query = shift; my $flagsrequired = shift; - my $timeout = _timeout_syspref(); + my $timeout = _timeout_syspref(); unless ( C4::Context->preference('Version') ) { @@ -1622,20 +1671,20 @@ sub check_api_auth { if ( $sessionID && not( $cas && $query->param('PT') ) ) { my $return; - ( $return, $session, undef ) = check_cookie_auth( - $sessionID, $flagsrequired, { remote_addr => $ENV{REMOTE_ADDR} } ); + ( $return, $session, undef ) = + check_cookie_auth( $sessionID, $flagsrequired, { remote_addr => $ENV{REMOTE_ADDR} } ); - return ( $return, undef, undef ) # Cookie auth failed + return ( $return, undef, undef ) # Cookie auth failed if $return ne "ok"; my $cookie = $query->cookie( -name => 'CGISESSID', -value => $session->id, -HttpOnly => 1, - -secure => ( C4::Context->https_enabled() ? 1 : 0 ), + -secure => ( C4::Context->https_enabled() ? 1 : 0 ), -sameSite => 'Lax' ); - return ( $return, $cookie, $session->id ); # return == 'ok' here + return ( $return, $cookie, $session->id ); # return == 'ok' here } else { @@ -1669,11 +1718,11 @@ sub check_api_auth { return ( "failed", undef, undef ) unless $session; my $sessionID = $session->id; - my $cookie = $query->cookie( + my $cookie = $query->cookie( -name => 'CGISESSID', -value => $sessionID, -HttpOnly => 1, - -secure => ( C4::Context->https_enabled() ? 1 : 0 ), + -secure => ( C4::Context->https_enabled() ? 1 : 0 ), -sameSite => 'Lax' ); if ( $return == 1 ) { @@ -1684,33 +1733,39 @@ sub check_api_auth { ); my $dbh = C4::Context->dbh; my $sth = - $dbh->prepare( -"select borrowernumber, firstname, surname, flags, borrowers.branchcode, branches.branchname as branchname, email from borrowers left join branches on borrowers.branchcode=branches.branchcode where userid=?" - ); + $dbh->prepare( + "select borrowernumber, firstname, surname, flags, borrowers.branchcode, branches.branchname as branchname, email from borrowers left join branches on borrowers.branchcode=branches.branchcode where userid=?" + ); $sth->execute($userid); ( $borrowernumber, $firstname, $surname, $userflags, $branchcode, $branchname, $emailaddress - ) = $sth->fetchrow if ( $sth->rows ); + ) + = $sth->fetchrow + if ( $sth->rows ); unless ( $sth->rows ) { my $sth = $dbh->prepare( -"select borrowernumber, firstname, surname, flags, borrowers.branchcode, branches.branchname as branchname, email from borrowers left join branches on borrowers.branchcode=branches.branchcode where cardnumber=?" + "select borrowernumber, firstname, surname, flags, borrowers.branchcode, branches.branchname as branchname, email from borrowers left join branches on borrowers.branchcode=branches.branchcode where cardnumber=?" ); $sth->execute($cardnumber); ( $borrowernumber, $firstname, $surname, $userflags, $branchcode, $branchname, $emailaddress - ) = $sth->fetchrow if ( $sth->rows ); + ) + = $sth->fetchrow + if ( $sth->rows ); unless ( $sth->rows ) { $sth->execute($userid); ( - $borrowernumber, $firstname, $surname, $userflags, + $borrowernumber, $firstname, $surname, $userflags, $branchcode, $branchname, $emailaddress - ) = $sth->fetchrow if ( $sth->rows ); + ) + = $sth->fetchrow + if ( $sth->rows ); } } @@ -1720,7 +1775,7 @@ sub check_api_auth { if ( $query->param('branch') ) { $branchcode = $query->param('branch'); my $library = Koha::Libraries->find($branchcode); - $branchname = $library? $library->branchname: ''; + $branchname = $library ? $library->branchname : ''; } my $branches = { map { $_->branchcode => $_->unblessed } Koha::Libraries->search->as_list }; foreach my $br ( keys %$branches ) { @@ -1731,7 +1786,7 @@ sub check_api_auth { $branchcode = $branches->{$br}->{'branchcode'}; # new op dev : add the branchname to the cookie - $branchname = $branches->{$br}->{'branchname'}; + $branchname = $branches->{$br}->{'branchname'}; } } $session->param( 'number', $borrowernumber ); @@ -1745,9 +1800,9 @@ sub check_api_auth { $session->param( 'emailaddress', $emailaddress ); $session->param( 'ip', $session->remote_addr() ); $session->param( 'lasttime', time() ); - $session->param( 'interface', 'api' ); + $session->param( 'interface', 'api' ); } - $session->param( 'cas_ticket', $cas_ticket); + $session->param( 'cas_ticket', $cas_ticket ); C4::Context->set_userenv( $session->param('number'), $session->param('id'), $session->param('cardnumber'), $session->param('firstname'), @@ -1806,9 +1861,9 @@ sub check_cookie_auth { my $remote_addr = $params->{remote_addr} || $ENV{REMOTE_ADDR}; - my $skip_version_check = $params->{skip_version_check}; # Only for checkauth + my $skip_version_check = $params->{skip_version_check}; # Only for checkauth - unless ( $skip_version_check ) { + unless ($skip_version_check) { unless ( C4::Context->preference('Version') ) { # database has not been installed yet @@ -1829,47 +1884,50 @@ sub check_cookie_auth { # however, if a userid parameter is present (i.e., from # a form submission, assume that any current cookie # is to be ignored - unless ( $sessionID ) { + unless ($sessionID) { return ( "failed", undef ); } C4::Context::unset_userenv(); - my $session = get_session($sessionID); + my $session = get_session($sessionID); if ($session) { my $userid = $session->param('id'); my $ip = $session->param('ip'); my $lasttime = $session->param('lasttime'); - my $timeout = _timeout_syspref(); + my $timeout = _timeout_syspref(); if ( !$lasttime || ( $lasttime < time() - $timeout ) ) { + # time out $session->delete(); $session->flush; - return ("expired", undef); + return ( "expired", undef ); } elsif ( C4::Context->preference('SessionRestrictionByIP') && $ip ne $remote_addr ) { + # IP address changed $session->delete(); $session->flush; - return ( "restricted", undef, { old_ip => $ip, new_ip => $remote_addr}); + return ( "restricted", undef, { old_ip => $ip, new_ip => $remote_addr } ); - } elsif ( $userid ) { + } elsif ($userid) { $session->param( 'lasttime', time() ); - my $patron = Koha::Patrons->find({ userid => $userid }); + my $patron = Koha::Patrons->find( { userid => $userid } ); # If the user modify their own userid # Better than 500 but we could do better - unless ( $patron ) { + unless ($patron) { $session->delete(); $session->flush; - return ("expired", undef); + return ( "expired", undef ); } - $patron = Koha::Patrons->find({ cardnumber => $userid }) - unless $patron; - return ("password_expired", undef ) if $patron->password_expired; + $patron = Koha::Patrons->find( { cardnumber => $userid } ) + unless $patron; + return ( "password_expired", undef ) if $patron->password_expired; my $flags = defined($flagsrequired) ? haspermission( $userid, $flagsrequired ) : 1; if ($flags) { if ( !C4::Context->interface ) { + # No need to override the interface, most often set by get_template_and_user C4::Context->interface( $session->param('interface') ); } @@ -1898,7 +1956,7 @@ sub check_cookie_auth { } } else { - C4::Context->interface($session->param('interface')); + C4::Context->interface( $session->param('interface') ); C4::Context->set_userenv( undef, q{} ); return ( "anon", $session ); } @@ -1962,12 +2020,11 @@ sub create_basic_session { $session->param( 'emailaddress', $patron->email ); $session->param( 'ip', $session->remote_addr() ); $session->param( 'lasttime', time() ); - $session->param( 'interface', $interface); + $session->param( 'interface', $interface ); return $session; } - # FIXME no_set_userenv may be replaced with force_branchcode_for_userenv # (or something similar) # Currently it's only passed from C4::SIP::ILS::Patron::check_password, but @@ -2008,7 +2065,7 @@ sub checkpw { # In case of a CAS authentication, we use the ticket instead of the password my $ticket = $query->param('ticket'); - $query->delete('ticket'); # remove ticket to come back to original URL + $query->delete('ticket'); # remove ticket to come back to original URL my ( $retval, $retcard, $retuserid, $cas_ticket ); ( $retval, $retcard, $retuserid, $cas_ticket, $patron ) = checkpw_cas( $ticket, $query, $type ); # EXTERNAL AUTH if ($retval) { @@ -2061,7 +2118,7 @@ sub checkpw { @return = (); } elsif ($passwd_ok) { $patron->update( { login_attempts => 0 } ); - if ( defined($anonymous_patron) && ($patron->borrowernumber eq $anonymous_patron) ) { + if ( defined($anonymous_patron) && ( $patron->borrowernumber eq $anonymous_patron ) ) { @return = ( -3, $patron ); } elsif ( $patron->password_expired ) { @return = ( -2, $patron ); @@ -2092,7 +2149,7 @@ sub checkpw_internal { if ( checkpw_hash( $password, $patron->password ) ) { my $borrowernumber = $patron->borrowernumber; C4::Context->set_userenv( - "$borrowernumber", $patron->userid, $patron->cardnumber, + "$borrowernumber", $patron->userid, $patron->cardnumber, $patron->firstname, $patron->surname, $patron->branchcode, $patron->library->branchname, $patron->flags ) unless $no_set_userenv; return 1, $patron->cardnumber, $patron->userid, $patron; @@ -2103,7 +2160,7 @@ sub checkpw_internal { if ( checkpw_hash( $password, $patron->password ) ) { my $borrowernumber = $patron->borrowernumber; C4::Context->set_userenv( - "$borrowernumber", $patron->userid, $patron->cardnumber, + "$borrowernumber", $patron->userid, $patron->cardnumber, $patron->firstname, $patron->surname, $patron->branchcode, $patron->library->branchname, $patron->flags ) unless $no_set_userenv; return 1, $patron->cardnumber, $patron->userid, $patron; @@ -2157,8 +2214,7 @@ sub getuserflags { while ( my ( $bit, $flag, $defaulton ) = $sth->fetchrow ) { if ( ( $flags & ( 2**$bit ) ) || $defaulton ) { $userflags->{$flag} = 1; - } - else { + } else { $userflags->{$flag} = 0; } } @@ -2202,12 +2258,14 @@ sub get_user_subpermissions { my $userid = shift; my $dbh = C4::Context->dbh; - my $sth = $dbh->prepare( "SELECT flag, user_permissions.code + my $sth = $dbh->prepare( + "SELECT flag, user_permissions.code FROM user_permissions JOIN permissions USING (module_bit, code) JOIN userflags ON (module_bit = bit) JOIN borrowers USING (borrowernumber) - WHERE userid = ?" ); + WHERE userid = ?" + ); $sth->execute($userid); my $user_perms = {}; @@ -2231,9 +2289,11 @@ of the subpermission. sub get_all_subpermissions { my $dbh = C4::Context->dbh; - my $sth = $dbh->prepare( "SELECT flag, code + my $sth = $dbh->prepare( + "SELECT flag, code FROM permissions - JOIN userflags ON (module_bit = bit)" ); + JOIN userflags ON (module_bit = bit)" + ); $sth->execute(); my $all_perms = {}; @@ -2299,29 +2359,29 @@ Returns member's flags or 0 if a permission is not met. =cut sub _dispatch { - my ($required, $flags) = @_; + my ( $required, $flags ) = @_; my $ref = ref($required); - if ($ref eq '') { - if ($required eq '*') { - return 0 unless ( $flags or ref( $flags ) ); + if ( $ref eq '' ) { + if ( $required eq '*' ) { + return 0 unless ( $flags or ref($flags) ); } else { - return 0 unless ( $flags and (!ref( $flags ) || $flags->{$required} )); + return 0 unless ( $flags and ( !ref($flags) || $flags->{$required} ) ); } - } elsif ($ref eq 'HASH') { - foreach my $key (keys %{$required}) { + } elsif ( $ref eq 'HASH' ) { + foreach my $key ( keys %{$required} ) { next if $flags == 1; my $require = $required->{$key}; my $rflags = $flags->{$key}; - return 0 unless _dispatch($require, $rflags); + return 0 unless _dispatch( $require, $rflags ); } - } elsif ($ref eq 'ARRAY') { + } elsif ( $ref eq 'ARRAY' ) { my $satisfied = 0; foreach my $require ( @{$required} ) { my $rflags = - ( ref($flags) && !ref($require) && ( $require ne '*' ) ) - ? $flags->{$require} - : $flags; + ( ref($flags) && !ref($require) && ( $require ne '*' ) ) + ? $flags->{$require} + : $flags; $satisfied++ if _dispatch( $require, $rflags ); } return 0 unless $satisfied; @@ -2330,7 +2390,7 @@ sub _dispatch { } return $flags; -}; +} sub haspermission { my ( $userid, $flagsrequired ) = @_; @@ -2340,12 +2400,12 @@ sub haspermission { my $sth = C4::Context->dbh->prepare("SELECT flags FROM borrowers WHERE userid=?"); $sth->execute($userid); - my $row = $sth->fetchrow(); + my $row = $sth->fetchrow(); my $flags = getuserflags( $row, $userid ); return $flags unless defined($flagsrequired); return $flags if $flags->{superlibrarian}; - return _dispatch($flagsrequired, $flags); + return _dispatch( $flagsrequired, $flags ); #FIXME - This fcn should return the failed permission so a suitable error msg can be delivered. } @@ -2361,15 +2421,17 @@ Returns 1 if the remote address is in the provided iprange, or 0 otherwise. =cut sub in_iprange { - my ($iprange) = @_; - my $result = 1; - my @allowedipranges = $iprange ? split(' ', $iprange) : (); - if (scalar @allowedipranges > 0) { + my ($iprange) = @_; + my $result = 1; + my @allowedipranges = $iprange ? split( ' ', $iprange ) : (); + if ( scalar @allowedipranges > 0 ) { my @rangelist; - eval { @rangelist = Net::CIDR::range2cidr(@allowedipranges); }; return 0 if $@; - eval { $result = Net::CIDR::cidrlookup($ENV{'REMOTE_ADDR'}, @rangelist) } || Koha::Logger->get->warn('cidrlookup failed for ' . join(' ',@rangelist) ); - } - return $result ? 1 : 0; + eval { @rangelist = Net::CIDR::range2cidr(@allowedipranges); }; + return 0 if $@; + eval { $result = Net::CIDR::cidrlookup( $ENV{'REMOTE_ADDR'}, @rangelist ) } + || Koha::Logger->get->warn( 'cidrlookup failed for ' . join( ' ', @rangelist ) ); + } + return $result ? 1 : 0; } sub getborrowernumber { @@ -2380,8 +2442,7 @@ sub getborrowernumber { } my $dbh = C4::Context->dbh; for my $field ( 'userid', 'cardnumber' ) { - my $sth = - $dbh->prepare("select borrowernumber from borrowers where $field=?"); + my $sth = $dbh->prepare("select borrowernumber from borrowers where $field=?"); $sth->execute($userid); if ( $sth->rows ) { my ($bnumber) = $sth->fetchrow; diff --git a/C4/Auth_with_cas.pm b/C4/Auth_with_cas.pm index 68c2c48a47..b107ca7e3a 100644 --- a/C4/Auth_with_cas.pm +++ b/C4/Auth_with_cas.pm @@ -29,26 +29,27 @@ use URI::Escape; use Koha::Logger; -our (@ISA, @EXPORT_OK); +our ( @ISA, @EXPORT_OK ); BEGIN { require Exporter; - @ISA = qw(Exporter); - @EXPORT_OK = qw(check_api_auth_cas checkpw_cas login_cas logout_cas login_cas_url logout_if_required multipleAuth getMultipleAuth); + @ISA = qw(Exporter); + @EXPORT_OK = + qw(check_api_auth_cas checkpw_cas login_cas logout_cas login_cas_url logout_if_required multipleAuth getMultipleAuth); } my $defaultcasserver; my $casservers; my $yamlauthfile = C4::Context->config('intranetdir') . "/C4/Auth_cas_servers.yaml"; - # If there's a configuration for multiple cas servers, then we get it -if (multipleAuth()) { - ($defaultcasserver, $casservers) = YAML::XS::LoadFile($yamlauthfile); +if ( multipleAuth() ) { + ( $defaultcasserver, $casservers ) = YAML::XS::LoadFile($yamlauthfile); $defaultcasserver = $defaultcasserver->{'default'}; } else { -# Else, we fall back to casServerUrl syspref + + # Else, we fall back to casServerUrl syspref $defaultcasserver = 'default'; - $casservers = { 'default' => C4::Context->preference('casServerUrl') }; + $casservers = { 'default' => C4::Context->preference('casServerUrl') }; } =head1 Subroutines @@ -57,12 +58,12 @@ if (multipleAuth()) { # Is there a configuration file for multiple cas servers? sub multipleAuth { - return (-e qq($yamlauthfile)); + return ( -e qq($yamlauthfile) ); } # Returns configured CAS servers' list if multiple authentication is enabled sub getMultipleAuth { - return $casservers; + return $casservers; } # Logout from CAS @@ -76,17 +77,16 @@ sub logout_cas { my $logout_url = $cas->logout_url( url => $uri ); $logout_url =~ s/url=/service=/ - if C4::Context->preference('casServerVersion') eq '3'; + if C4::Context->preference('casServerVersion') eq '3'; print $query->redirect($logout_url); } - # Login to CAS sub login_cas { - my ($query, $type) = @_; - my ( $cas, $uri ) = _get_cas_and_service($query, undef, $type); - print $query->redirect( $cas->login_url($uri)); + my ( $query, $type ) = @_; + my ( $cas, $uri ) = _get_cas_and_service( $query, undef, $type ); + print $query->redirect( $cas->login_url($uri) ); } # Returns CAS login URL with callback to the requesting URL @@ -99,15 +99,15 @@ sub login_cas_url { # Checks for password correctness # In our case : is there a ticket, is it valid and does it match one of our users ? sub checkpw_cas { - my ($ticket, $query, $type) = @_; + my ( $ticket, $query, $type ) = @_; my $retnumber; - my ( $cas, $uri ) = _get_cas_and_service($query, undef, $type); + my ( $cas, $uri ) = _get_cas_and_service( $query, undef, $type ); # If we got a ticket if ($ticket) { # We try to validate it - my $val = $cas->service_validate($uri, $ticket ); + my $val = $cas->service_validate( $uri, $ticket ); # If it's valid if ( $val->is_success() ) { @@ -133,9 +133,9 @@ sub checkpw_cas { } else { my $logger = Koha::Logger->get; $logger->debug("Problem when validating ticket : $ticket"); - $logger->debug("Authen::CAS::Client::Response::Error: " . $val->error()) if $val->is_error(); - $logger->debug("Authen::CAS::Client::Response::Failure: " . $val->message()) if $val->is_failure(); - $logger->debug(Data::Dumper::Dumper($@)) if $val->is_error() or $val->is_failure(); + $logger->debug( "Authen::CAS::Client::Response::Error: " . $val->error() ) if $val->is_error(); + $logger->debug( "Authen::CAS::Client::Response::Failure: " . $val->message() ) if $val->is_failure(); + $logger->debug( Data::Dumper::Dumper($@) ) if $val->is_error() or $val->is_failure(); return 0; } } @@ -144,9 +144,9 @@ sub checkpw_cas { # Proxy CAS auth sub check_api_auth_cas { - my ($PT, $query, $type) = @_; + my ( $PT, $query, $type ) = @_; my $retnumber; - my ( $cas, $uri ) = _get_cas_and_service($query, undef, $type); + my ( $cas, $uri ) = _get_cas_and_service( $query, undef, $type ); # If we have a Proxy Ticket if ($PT) { @@ -193,11 +193,11 @@ sub _get_cas_and_service { my $key = shift; # optional my $type = shift; - my $uri = _url_with_get_params($query, $type); + my $uri = _url_with_get_params( $query, $type ); my $casparam = $defaultcasserver; $casparam = $query->param('cas') if defined $query->param('cas'); - $casparam = $key if defined $key; + $casparam = $key if defined $key; my $cas = Authen::CAS::Client->new( $casservers->{$casparam} ); return ( $cas, $uri ); @@ -207,23 +207,24 @@ sub _get_cas_and_service { # This method replaces $query->url() which will give both GET and POST params sub _url_with_get_params { my $query = shift; - my $type = shift; + my $type = shift; my $uri_base_part = - ( $type eq 'opac' ) - ? C4::Context->preference('OPACBaseURL') - : C4::Context->preference('staffClientBaseURL'); + ( $type eq 'opac' ) + ? C4::Context->preference('OPACBaseURL') + : C4::Context->preference('staffClientBaseURL'); $uri_base_part .= get_script_name(); my $uri_params_part = ''; foreach my $param ( $query->url_param() ) { + # url_param() always returns parameters that were deleted by delete() # This additional check ensure that parameter was not deleted. my $uriPiece = $query->param($param); if ($uriPiece) { $uri_params_part .= '&' if $uri_params_part; $uri_params_part .= $param . '='; - $uri_params_part .= URI::Escape::uri_escape( $uriPiece ); + $uri_params_part .= URI::Escape::uri_escape($uriPiece); } } $uri_base_part .= '?' if $uri_params_part; @@ -238,14 +239,16 @@ sub _url_with_get_params { =cut sub logout_if_required { - my ( $query ) = @_; + my ($query) = @_; + # Check we havent been hit by a logout call my $xml = $query->param('logoutRequest'); return 0 unless $xml; - my $dom = XML::LibXML->load_xml(string => $xml); + my $dom = XML::LibXML->load_xml( string => $xml ); my $ticket; - foreach my $node ($dom->findnodes('/samlp:LogoutRequest')){ + foreach my $node ( $dom->findnodes('/samlp:LogoutRequest') ) { + # We got a cas single logout request from a cas server; $ticket = $node->findvalue('./samlp:SessionIndex'); } @@ -253,8 +256,8 @@ sub logout_if_required { return 0 unless $ticket; # We've been called as part of the single logout destroy the session associated with the cas ticket - my $params = C4::Auth::_get_session_params(); - my $success = CGI::Session->find( $params->{dsn}, sub {delete_cas_session(@_, $ticket)}, $params->{dsn_args} ); + my $params = C4::Auth::_get_session_params(); + my $success = CGI::Session->find( $params->{dsn}, sub { delete_cas_session( @_, $ticket ) }, $params->{dsn_args} ); print $query->header; exit; @@ -262,8 +265,8 @@ sub logout_if_required { sub delete_cas_session { my $session = shift; - my $ticket = shift; - if ($session->param('cas_ticket') && $session->param('cas_ticket') eq $ticket ) { + my $ticket = shift; + if ( $session->param('cas_ticket') && $session->param('cas_ticket') eq $ticket ) { $session->delete; $session->flush; } diff --git a/C4/Auth_with_ldap.pm b/C4/Auth_with_ldap.pm index 406e0d9a19..7f0d9f7f5d 100644 --- a/C4/Auth_with_ldap.pm +++ b/C4/Auth_with_ldap.pm @@ -22,99 +22,107 @@ use Carp qw( croak ); use C4::Context; use C4::Members::Messaging; -use C4::Auth qw( checkpw_internal ); +use C4::Auth qw( checkpw_internal ); use C4::Letters qw( GetPreparedLetter EnqueueLetter SendQueuedMessages ); use Koha::Patrons; use Koha::AuthUtils qw( hash_password ); use Net::LDAP; use Net::LDAP::Filter; -our (@ISA, @EXPORT_OK); +our ( @ISA, @EXPORT_OK ); + BEGIN { - require Exporter; - @ISA = qw(Exporter); - @EXPORT_OK = qw( checkpw_ldap ); + require Exporter; + @ISA = qw(Exporter); + @EXPORT_OK = qw( checkpw_ldap ); } # Redefine checkpw_ldap: # connect to LDAP (named or anonymous) # ~ retrieves $userid from KOHA_CONF mapping -# ~ then compares $password with userPassword +# ~ then compares $password with userPassword # ~ then gets the LDAP entry # ~ and calls the memberadd if necessary sub ldapserver_error { - return sprintf('No ldapserver "%s" defined in KOHA_CONF: ' . $ENV{KOHA_CONF}, shift); + return sprintf( 'No ldapserver "%s" defined in KOHA_CONF: ' . $ENV{KOHA_CONF}, shift ); } use vars qw($mapping @ldaphosts $base $ldapname $ldappassword); my $ldap = C4::Context->config("ldapserver") or die 'No "ldapserver" in server hash from KOHA_CONF: ' . $ENV{KOHA_CONF}; + # since Bug 28278 we need to skip id in which generates additional hash level if ( exists $ldap->{ldapserver} ) { - $ldap = $ldap->{ldapserver} or die ldapserver_error('id="ldapserver"'); + $ldap = $ldap->{ldapserver} or die ldapserver_error('id="ldapserver"'); } -my $prefhost = $ldap->{hostname} or die ldapserver_error('hostname'); -my $base = $ldap->{base} or die ldapserver_error('base'); -$ldapname = $ldap->{user} ; -$ldappassword = $ldap->{pass} ; -our %mapping = %{$ldap->{mapping}}; # FIXME dpavlin -- don't die because of || (); from 6eaf8511c70eb82d797c941ef528f4310a15e9f9 +my $prefhost = $ldap->{hostname} or die ldapserver_error('hostname'); +my $base = $ldap->{base} or die ldapserver_error('base'); +$ldapname = $ldap->{user}; +$ldappassword = $ldap->{pass}; +our %mapping = + %{ $ldap->{mapping} }; # FIXME dpavlin -- don't die because of || (); from 6eaf8511c70eb82d797c941ef528f4310a15e9f9 my @mapkeys = keys %mapping; + #warn "Got ", scalar(@mapkeys), " ldap mapkeys ( total ): ", join ' ', @mapkeys, "\n"; -@mapkeys = grep {defined $mapping{$_}->{is}} @mapkeys; +@mapkeys = grep { defined $mapping{$_}->{is} } @mapkeys; + #warn "Got ", scalar(@mapkeys), " ldap mapkeys (populated): ", join ' ', @mapkeys, "\n"; my %categorycode_conversions; my $default_categorycode; -if(defined $ldap->{categorycode_mapping}) { +if ( defined $ldap->{categorycode_mapping} ) { $default_categorycode = $ldap->{categorycode_mapping}->{default}; - foreach my $cat (@{$ldap->{categorycode_mapping}->{categorycode}}) { - $categorycode_conversions{$cat->{value}} = $cat->{content}; + foreach my $cat ( @{ $ldap->{categorycode_mapping}->{categorycode} } ) { + $categorycode_conversions{ $cat->{value} } = $cat->{content}; } } my %config = ( - anonymous => defined ($ldap->{anonymous_bind}) ? $ldap->{anonymous_bind} : 1, - replicate => defined($ldap->{replicate}) ? $ldap->{replicate} : 1, # add from LDAP to Koha database for new user - welcome => defined($ldap->{welcome}) ? $ldap->{welcome} : 0, # send welcome notice when patron is added via replicate - update => defined($ldap->{update}) ? $ldap->{update} : 1, # update from LDAP to Koha database for existing user + anonymous => defined( $ldap->{anonymous_bind} ) ? $ldap->{anonymous_bind} : 1, + replicate => defined( $ldap->{replicate} ) + ? $ldap->{replicate} + : 1, # add from LDAP to Koha database for new user + welcome => defined( $ldap->{welcome} ) + ? $ldap->{welcome} + : 0, # send welcome notice when patron is added via replicate + update => defined( $ldap->{update} ) ? $ldap->{update} : 1, # update from LDAP to Koha database for existing user ); sub description { - my $result = shift or return; - return "LDAP error #" . $result->code - . ": " . $result->error_name . "\n" - . "# " . $result->error_text . "\n"; + my $result = shift or return; + return "LDAP error #" . $result->code . ": " . $result->error_name . "\n" . "# " . $result->error_text . "\n"; } sub search_method { - my $db = shift or return; - my $userid = shift or return; - my $uid_field = $mapping{userid}->{is} or die ldapserver_error("mapping for 'userid'"); - my $filter = Net::LDAP::Filter->new("$uid_field=$userid") or die "Failed to create new Net::LDAP::Filter"; - my $search = $db->search( - base => $base, - filter => $filter, - # attrs => ['*'], + my $db = shift or return; + my $userid = shift or return; + my $uid_field = $mapping{userid}->{is} or die ldapserver_error("mapping for 'userid'"); + my $filter = Net::LDAP::Filter->new("$uid_field=$userid") or die "Failed to create new Net::LDAP::Filter"; + my $search = $db->search( + base => $base, + filter => $filter, + + # attrs => ['*'], ); die "LDAP search failed to return object : " . $search->error if $search->code; - my $count = $search->count; - if ($search->code > 0) { - warn sprintf("LDAP Auth rejected : %s gets %d hits\n", $filter->as_string, $count) . description($search); - return 0; - } - if ($count == 0) { - warn sprintf("LDAP Auth rejected : search with filter '%s' returns no hit\n", $filter->as_string); + my $count = $search->count; + if ( $search->code > 0 ) { + warn sprintf( "LDAP Auth rejected : %s gets %d hits\n", $filter->as_string, $count ) . description($search); + return 0; + } + if ( $count == 0 ) { + warn sprintf( "LDAP Auth rejected : search with filter '%s' returns no hit\n", $filter->as_string ); return 0; } return $search; } sub checkpw_ldap { - my ($userid, $password) = @_; - my @hosts = split(',', $prefhost); - my $db = Net::LDAP->new(\@hosts); - unless ( $db ) { + my ( $userid, $password ) = @_; + my @hosts = split( ',', $prefhost ); + my $db = Net::LDAP->new( \@hosts ); + unless ($db) { warn "LDAP connexion failed"; return 0; } @@ -135,16 +143,14 @@ sub checkpw_ldap { # Perform a LDAP search for the given username my $search = search_method( $db, $userid ) - or return 0; # warnings are in the sub - $userldapentry = $search->shift_entry; + or return 0; # warnings are in the sub + $userldapentry = $search->shift_entry; $principal_name = $userldapentry->dn; - } - else { + } else { $principal_name = $ldap->{principal_name}; if ( $principal_name and $principal_name =~ /\%/ ) { $principal_name = sprintf( $principal_name, $userid ); - } - else { + } else { $principal_name = $userid; } } @@ -153,12 +159,14 @@ sub checkpw_ldap { my $res = $db->bind( $principal_name, password => $password ); if ( $res->code ) { if ( $config{anonymous} ) { + # With anonymous_bind approach we can be sure we have found the correct user # and that any 'code' response indicates a 'bad' user (be that blocked, banned # or password changed). We should not fall back to local accounts in this case. warn "LDAP bind failed as kohauser $userid: " . description($res); return -1; } else { + # Without a anonymous_bind, we cannot be sure we are looking at a valid ldap user # at all, and thus we should fall back to local logins to restore previous behaviour # see bug 12831 @@ -173,19 +181,19 @@ sub checkpw_ldap { $userldapentry = $search->shift_entry; } } else { - my $res = ($config{anonymous}) ? $db->bind : $db->bind($ldapname, password=>$ldappassword); - if ($res->code) { # connection refused - warn "LDAP bind failed as ldapuser " . ($ldapname || '[ANONYMOUS]') . ": " . description($res); - return 0; - } - my $search = search_method($db, $userid) or return 0; # warnings are in the sub - # Handle multiple branches. Same login exists several times in different branches. + my $res = ( $config{anonymous} ) ? $db->bind : $db->bind( $ldapname, password => $ldappassword ); + if ( $res->code ) { # connection refused + warn "LDAP bind failed as ldapuser " . ( $ldapname || '[ANONYMOUS]' ) . ": " . description($res); + return 0; + } + my $search = search_method( $db, $userid ) or return 0; # warnings are in the sub + # Handle multiple branches. Same login exists several times in different branches. my $bind_ok = 0; - while (my $entry = $search->shift_entry) { - my $user_ldap_bind_ret = $db->bind($entry->dn, password => $password); - unless ($user_ldap_bind_ret->code) { + while ( my $entry = $search->shift_entry ) { + my $user_ldap_bind_ret = $db->bind( $entry->dn, password => $password ); + unless ( $user_ldap_bind_ret->code ) { $userldapentry = $entry; - $bind_ok = 1; + $bind_ok = 1; last; } } @@ -195,19 +203,20 @@ sub checkpw_ldap { return -1; } - } # To get here, LDAP has accepted our user's login attempt. # But we still have work to do. See perldoc below for detailed breakdown. my (%borrower); - my ($borrowernumber,$cardnumber,$local_userid,$savedpw) = exists_local($userid); + my ( $borrowernumber, $cardnumber, $local_userid, $savedpw ) = exists_local($userid); my $patron; - if (( $borrowernumber and $config{update} ) or - (!$borrowernumber and $config{replicate}) ) { - %borrower = ldap_entry_2_hash($userldapentry,$cardnumber); + if ( ( $borrowernumber and $config{update} ) + or ( !$borrowernumber and $config{replicate} ) ) + { + %borrower = ldap_entry_2_hash( $userldapentry, $cardnumber ); + #warn "checkpw_ldap received \%borrower w/ " . keys(%borrower), " keys: ", join(' ', keys %borrower), "\n"; } @@ -220,13 +229,10 @@ sub checkpw_ldap { my $patron = Koha::Patrons->find($borrowernumber); return ( 1, $cardnumber, $local_userid, $patron ); } - } elsif ($config{replicate}) { # A2, C2 + } elsif ( $config{replicate} ) { # A2, C2 my @columns = Koha::Patrons->columns; - $patron = Koha::Patron->new( - { - map { exists( $borrower{$_} ) ? ( $_ => $borrower{$_} ) : () } @columns - } - )->store; + $patron = + Koha::Patron->new( { map { exists( $borrower{$_} ) ? ( $_ => $borrower{$_} ) : () } @columns } )->store; $patron->discard_changes; die "Insert of new patron failed" unless $patron; $borrowernumber = $patron->borrowernumber; @@ -267,30 +273,33 @@ sub checkpw_ldap { C4::Letters::SendQueuedMessages( { message_id => $message_id } ) if $message_id; } } - } else { - return 0; # B2, D2 + } else { + return 0; # B2, D2 } - if (C4::Context->preference('ExtendedPatronAttributes') && $borrowernumber && ($config{update} ||$config{replicate})) { - my $library_id = C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef; - my $attribute_types = Koha::Patron::Attribute::Types->search_with_library_limits({}, {}, $library_id); + if ( C4::Context->preference('ExtendedPatronAttributes') + && $borrowernumber + && ( $config{update} || $config{replicate} ) ) + { + my $library_id = C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef; + my $attribute_types = Koha::Patron::Attribute::Types->search_with_library_limits( {}, {}, $library_id ); while ( my $attribute_type = $attribute_types->next ) { my $code = $attribute_type->code; - unless (exists($borrower{$code}) && $borrower{$code} !~ m/^\s*$/ ) { + unless ( exists( $borrower{$code} ) && $borrower{$code} !~ m/^\s*$/ ) { next; } $patron = Koha::Patrons->find($borrowernumber); - if ( $patron ) { # Should not be needed, but we are in C4::Auth LDAP... + if ($patron) { # Should not be needed, but we are in C4::Auth LDAP... eval { - my $attribute = Koha::Patron::Attribute->new({code => $code, attribute => $borrower{$code}}); - $patron->extended_attributes([$attribute->unblessed]); + my $attribute = Koha::Patron::Attribute->new( { code => $code, attribute => $borrower{$code} } ); + $patron->extended_attributes( [ $attribute->unblessed ] ); }; - if ($@) { # FIXME Test if Koha::Exceptions::Patron::Attribute::NonRepeatable + if ($@) { # FIXME Test if Koha::Exceptions::Patron::Attribute::NonRepeatable warn "ERROR_extended_unique_id_failed $code $borrower{$code}"; } } } } - return(1, $cardnumber, $userid, $patron); + return ( 1, $cardnumber, $userid, $patron ); } # Pass LDAP entry object and local cardnumber (userid). @@ -299,68 +308,71 @@ sub checkpw_ldap { # Ensure that mandatory fields are correctly filled! # sub ldap_entry_2_hash { - my $userldapentry = shift; - my %borrower = ( cardnumber => shift ); - my %memberhash; - $userldapentry->exists('uid'); # This is bad, but required! By side-effect, this initializes the attrs hash. - #foreach (keys %$userldapentry) { - # print STDERR "\n\nLDAP key: $_\t", sprintf('(%s)', ref $userldapentry->{$_}), "\n"; - #} - my $x = $userldapentry->{attrs} or return; - foreach (keys %$x) { - $memberhash{$_} = join ' ', @{$x->{$_}}; + my $userldapentry = shift; + my %borrower = ( cardnumber => shift ); + my %memberhash; + $userldapentry->exists('uid'); # This is bad, but required! By side-effect, this initializes the attrs hash. + #foreach (keys %$userldapentry) { + # print STDERR "\n\nLDAP key: $_\t", sprintf('(%s)', ref $userldapentry->{$_}), "\n"; + #} + my $x = $userldapentry->{attrs} or return; + + foreach ( keys %$x ) { + $memberhash{$_} = join ' ', @{ $x->{$_} }; + #warn sprintf("building \$memberhash{%s} = ", $_, join(' ', @{$x->{$_}})), "\n"; - } + } + #warn "Finished \%memberhash has ", scalar(keys %memberhash), " keys\n", "Referencing \%mapping with ", scalar(keys %mapping), " keys\n"; - foreach my $key (keys %mapping) { - my $data = $memberhash{ lc($mapping{$key}->{is}) }; # Net::LDAP returns all names in lowercase - #warn "mapping %20s ==> %-20s (%s)\n", $key, $mapping{$key}->{is}, $data; - unless (defined $data) { + foreach my $key ( keys %mapping ) { + my $data = $memberhash{ lc( $mapping{$key}->{is} ) }; # Net::LDAP returns all names in lowercase + #warn "mapping %20s ==> %-20s (%s)\n", $key, $mapping{$key}->{is}, $data; + unless ( defined $data ) { $data = $mapping{$key}->{content} || undef; - } + } $borrower{$key} = $data; - } - $borrower{initials} = $memberhash{initials} || - ( substr($borrower{'firstname'},0,1) - . substr($borrower{ 'surname' },0,1) - . " "); + } + $borrower{initials} = $memberhash{initials} + || ( substr( $borrower{'firstname'}, 0, 1 ) . substr( $borrower{'surname'}, 0, 1 ) . " " ); # categorycode conversions - if(defined $categorycode_conversions{$borrower{categorycode}}) { - $borrower{categorycode} = $categorycode_conversions{$borrower{categorycode}}; - } - elsif($default_categorycode) { + if ( defined $categorycode_conversions{ $borrower{categorycode} } ) { + $borrower{categorycode} = $categorycode_conversions{ $borrower{categorycode} }; + } elsif ($default_categorycode) { $borrower{categorycode} = $default_categorycode; } - # check if categorycode exists, if not, fallback to default from koha-conf.xml - my $dbh = C4::Context->dbh; - my $sth = $dbh->prepare("SELECT categorycode FROM categories WHERE categorycode = ?"); - $sth->execute( uc($borrower{'categorycode'}) ); - unless ( my $row = $sth->fetchrow_hashref ) { - my $default = $mapping{'categorycode'}->{content}; - #warn "Can't find ", $borrower{'categorycode'}, " default to: $default for ", $borrower{userid}; - $borrower{'categorycode'} = $default - } + # check if categorycode exists, if not, fallback to default from koha-conf.xml + my $dbh = C4::Context->dbh; + my $sth = $dbh->prepare("SELECT categorycode FROM categories WHERE categorycode = ?"); + $sth->execute( uc( $borrower{'categorycode'} ) ); + unless ( my $row = $sth->fetchrow_hashref ) { + my $default = $mapping{'categorycode'}->{content}; - return %borrower; + #warn "Can't find ", $borrower{'categorycode'}, " default to: $default for ", $borrower{userid}; + $borrower{'categorycode'} = $default; + } + + return %borrower; } sub exists_local { - my $arg = shift; - my $dbh = C4::Context->dbh; - my $select = "SELECT borrowernumber,cardnumber,userid,password FROM borrowers "; + my $arg = shift; + my $dbh = C4::Context->dbh; + my $select = "SELECT borrowernumber,cardnumber,userid,password FROM borrowers "; + + my $sth = $dbh->prepare("$select WHERE userid=?"); # was cardnumber=? + $sth->execute($arg); - my $sth = $dbh->prepare("$select WHERE userid=?"); # was cardnumber=? - $sth->execute($arg); #warn "Userid '$arg' exists_local? %s\n", $sth->rows; - ($sth->rows == 1) and return $sth->fetchrow; + ( $sth->rows == 1 ) and return $sth->fetchrow; + + $sth = $dbh->prepare("$select WHERE cardnumber=?"); + $sth->execute($arg); - $sth = $dbh->prepare("$select WHERE cardnumber=?"); - $sth->execute($arg); #warn "Cardnumber '$arg' exists_local? %s\n", $sth->rows; - ($sth->rows == 1) and return $sth->fetchrow; - return 0; + ( $sth->rows == 1 ) and return $sth->fetchrow; + return 0; } # This function performs a password update, given the userid, borrowerid, @@ -373,30 +385,27 @@ sub exists_local { # Note: if the LDAP config has the update_password tag set to a false value, # then this will not update the password, it will simply return the cardnumber. sub _do_changepassword { - my ($userid, $borrowerid, $password) = @_; + my ( $userid, $borrowerid, $password ) = @_; if ( exists( $ldap->{update_password} ) && !$ldap->{update_password} ) { # We don't store the password in the database - my $sth = C4::Context->dbh->prepare( - 'SELECT cardnumber FROM borrowers WHERE borrowernumber=?'); + my $sth = C4::Context->dbh->prepare('SELECT cardnumber FROM borrowers WHERE borrowernumber=?'); $sth->execute($borrowerid); - die "Unable to access borrowernumber " - . "with userid=$userid, " - . "borrowernumber=$borrowerid" - if !$sth->rows; + die "Unable to access borrowernumber " . "with userid=$userid, " . "borrowernumber=$borrowerid" + if !$sth->rows; my ($cardnum) = $sth->fetchrow; - $sth = C4::Context->dbh->prepare( - 'UPDATE borrowers SET password = null WHERE borrowernumber=?'); + $sth = C4::Context->dbh->prepare('UPDATE borrowers SET password = null WHERE borrowernumber=?'); $sth->execute($borrowerid); return $cardnum; } my $digest = hash_password($password); - #warn "changing local password for borrowernumber=$borrowerid to '$digest'\n"; - Koha::Patrons->find($borrowerid)->set_password({ password => $password, skip_validation => 1 }); - my ($ok, $cardnum) = checkpw_internal($userid, $password); + #warn "changing local password for borrowernumber=$borrowerid to '$digest'\n"; + Koha::Patrons->find($borrowerid)->set_password( { password => $password, skip_validation => 1 } ); + + my ( $ok, $cardnum ) = checkpw_internal( $userid, $password ); return $cardnum if $ok; warn "Password mismatch after update to borrowernumber=$borrowerid"; @@ -411,29 +420,27 @@ sub update_local { # skip extended patron attributes in 'borrowers' attribute update my @keys = keys %$borrower; - if (C4::Context->preference('ExtendedPatronAttributes')) { - my $library_id = C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef; - my $attribute_types = Koha::Patron::Attribute::Types->search_with_library_limits({}, {}, $library_id); + if ( C4::Context->preference('ExtendedPatronAttributes') ) { + my $library_id = C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef; + my $attribute_types = Koha::Patron::Attribute::Types->search_with_library_limits( {}, {}, $library_id ); while ( my $attribute_type = $attribute_types->next ) { - my $code = $attribute_type->code; - @keys = grep { $_ ne $code } @keys; - #warn "ignoring extended patron attribute '%s' in update_local()\n", $code; + my $code = $attribute_type->code; + @keys = grep { $_ ne $code } @keys; + + #warn "ignoring extended patron attribute '%s' in update_local()\n", $code; } } - my $dbh = C4::Context->dbh; - my $query = "UPDATE borrowers\nSET " . - join(',', map {"$_=?"} @keys) . - "\nWHERE borrowernumber=? "; - my $sth = $dbh->prepare($query); + my $dbh = C4::Context->dbh; + my $query = "UPDATE borrowers\nSET " . join( ',', map { "$_=?" } @keys ) . "\nWHERE borrowernumber=? "; + my $sth = $dbh->prepare($query); + #warn $query, "\n", join "\n", map {"$_ = '" . $borrower->{$_} . "'"} @keys; #warn "\nuserid = $userid\n"; - $sth->execute( - ((map {$borrower->{$_}} @keys), $borrowerid) - ); + $sth->execute( ( ( map { $borrower->{$_} } @keys ), $borrowerid ) ); # MODIFY PASSWORD/LOGIN if password was mapped - _do_changepassword($userid, $borrowerid, $password) if exists( $borrower->{'password'} ); + _do_changepassword( $userid, $borrowerid, $password ) if exists( $borrower->{'password'} ); } 1; diff --git a/C4/Auth_with_shibboleth.pm b/C4/Auth_with_shibboleth.pm index e3eb281cfc..decf28f6a3 100644 --- a/C4/Auth_with_shibboleth.pm +++ b/C4/Auth_with_shibboleth.pm @@ -25,17 +25,17 @@ use Koha::Database; use Koha::Patrons; use C4::Letters qw( GetPreparedLetter EnqueueLetter SendQueuedMessages ); use C4::Members::Messaging; -use Carp qw( carp ); +use Carp qw( carp ); use List::MoreUtils qw( any ); use Koha::Logger; -our (@ISA, @EXPORT_OK); +our ( @ISA, @EXPORT_OK ); + BEGIN { require Exporter; - @ISA = qw(Exporter); - @EXPORT_OK = - qw(shib_ok logout_shib login_shib_url checkpw_shib get_login_shib); + @ISA = qw(Exporter); + @EXPORT_OK = qw(shib_ok logout_shib login_shib_url checkpw_shib get_login_shib); } # Check that shib config is not malformed @@ -52,8 +52,8 @@ sub shib_ok { # Logout from Shibboleth sub logout_shib { my ($query) = @_; - my $uri = _get_uri(); - my $return = _get_return($query); + my $uri = _get_uri(); + my $return = _get_return($query); print $query->redirect( $uri . "/Shibboleth.sso/Logout?return=$return" ); } @@ -62,7 +62,7 @@ sub login_shib_url { my ($query) = @_; my $target = _get_return($query); - my $uri = _get_uri() . "/Shibboleth.sso/Login?target=" . $target; + my $uri = _get_uri() . "/Shibboleth.sso/Login?target=" . $target; return $uri; } @@ -70,12 +70,12 @@ sub login_shib_url { # Returns shibboleth user login sub get_login_shib { -# In case of a Shibboleth authentication, we expect a shibboleth user attribute -# to contain the login match point of the shibboleth-authenticated user. This match -# point is configured in koha-conf.xml + # In case of a Shibboleth authentication, we expect a shibboleth user attribute + # to contain the login match point of the shibboleth-authenticated user. This match + # point is configured in koha-conf.xml -# Shibboleth attributes are mapped into http environmement variables, so we're getting -# the match point of the user this way + # Shibboleth attributes are mapped into http environmement variables, so we're getting + # the match point of the user this way # Get shibboleth config my $config = _get_shib_config(); @@ -83,9 +83,9 @@ sub get_login_shib { my $matchAttribute = $config->{mapping}->{ $config->{matchpoint} }->{is}; if ( C4::Context->psgi_env ) { - return $ENV{"HTTP_".uc($matchAttribute)} || ''; + return $ENV{ "HTTP_" . uc($matchAttribute) } || ''; } else { - return $ENV{$matchAttribute} || ''; + return $ENV{$matchAttribute} || ''; } } @@ -93,21 +93,23 @@ sub get_login_shib { # In our case : does the given attribute match one of our users ? sub checkpw_shib { - my ( $match ) = @_; + my ($match) = @_; my $config = _get_shib_config(); # Does the given shibboleth attribute value ($match) match a valid koha user ? my $borrowers = Koha::Patrons->search( { $config->{matchpoint} => $match } ); - if ( $borrowers->count > 1 ){ + if ( $borrowers->count > 1 ) { + # If we have more than 1 borrower the matchpoint is not unique # we cannot know which patron is the correct one, so we should fail - Koha::Logger->get->warn("There are several users with $config->{matchpoint} of $match, matchpoints must be unique"); + Koha::Logger->get->warn( + "There are several users with $config->{matchpoint} of $match, matchpoints must be unique"); return 0; } my $borrower = $borrowers->next; if ( defined($borrower) ) { - if ($config->{'sync'}) { - _sync($borrower->borrowernumber, $config, $match); + if ( $config->{'sync'} ) { + _sync( $borrower->borrowernumber, $config, $match ); } return ( 1, $borrower->get_column('cardnumber'), $borrower->get_column('userid'), $borrower ); } @@ -115,6 +117,7 @@ sub checkpw_shib { if ( $config->{'autocreate'} ) { return _autocreate( $config, $match ); } else { + # If we reach this point, the user is not a valid koha user Koha::Logger->get->info("No users with $config->{matchpoint} of $match found and autocreate is disabled"); return 0; @@ -126,9 +129,9 @@ sub _autocreate { my %borrower = ( $config->{matchpoint} => $match ); - while ( my ( $key, $entry ) = each %{$config->{'mapping'}} ) { + while ( my ( $key, $entry ) = each %{ $config->{'mapping'} } ) { if ( C4::Context->psgi_env ) { - $borrower{$key} = ( $entry->{'is'} && $ENV{"HTTP_" . uc($entry->{'is'}) } ) || $entry->{'content'} || ''; + $borrower{$key} = ( $entry->{'is'} && $ENV{ "HTTP_" . uc( $entry->{'is'} ) } ) || $entry->{'content'} || ''; } else { $borrower{$key} = ( $entry->{'is'} && $ENV{ $entry->{'is'} } ) || $entry->{'content'} || ''; } @@ -178,37 +181,37 @@ sub _autocreate { } sub _sync { - my ($borrowernumber, $config, $match ) = @_; + my ( $borrowernumber, $config, $match ) = @_; my %borrower; $borrower{'borrowernumber'} = $borrowernumber; - while ( my ( $key, $entry ) = each %{$config->{'mapping'}} ) { + while ( my ( $key, $entry ) = each %{ $config->{'mapping'} } ) { if ( C4::Context->psgi_env ) { - $borrower{$key} = ( $entry->{'is'} && $ENV{"HTTP_" . uc($entry->{'is'}) } ) || $entry->{'content'} || ''; + $borrower{$key} = ( $entry->{'is'} && $ENV{ "HTTP_" . uc( $entry->{'is'} ) } ) || $entry->{'content'} || ''; } else { $borrower{$key} = ( $entry->{'is'} && $ENV{ $entry->{'is'} } ) || $entry->{'content'} || ''; } } - my $patron = Koha::Patrons->find( $borrowernumber ); - $patron->set(\%borrower)->store; + my $patron = Koha::Patrons->find($borrowernumber); + $patron->set( \%borrower )->store; } sub _get_uri { - my $protocol = "https://"; + my $protocol = "https://"; my $interface = C4::Context->interface; my $uri = - $interface eq 'intranet' - ? C4::Context->preference('staffClientBaseURL') - : C4::Context->preference('OPACBaseURL'); + $interface eq 'intranet' + ? C4::Context->preference('staffClientBaseURL') + : C4::Context->preference('OPACBaseURL'); - $uri or Koha::Logger->get->warn("Syspref staffClientBaseURL or OPACBaseURL not set!"); # FIXME We should die here + $uri or Koha::Logger->get->warn("Syspref staffClientBaseURL or OPACBaseURL not set!"); # FIXME We should die here $uri ||= ""; - if ($uri =~ /(.*):\/\/(.*)/) { + if ( $uri =~ /(.*):\/\/(.*)/ ) { my $oldprotocol = $1; - if ($oldprotocol ne 'https') { + if ( $oldprotocol ne 'https' ) { Koha::Logger->get->warn('Shibboleth requires OPACBaseURL/staffClientBaseURL to use the https protocol!'); } $uri = $2; @@ -224,6 +227,7 @@ sub _get_return { my $uri_params_part = ''; foreach my $param ( sort $query->url_param() ) { + # url_param() always returns parameters that were deleted by delete() # This additional check ensure that parameter was not deleted. my $uriPiece = $query->param($param); @@ -250,15 +254,13 @@ sub _get_shib_config { && defined( $config->{mapping}->{ $config->{matchpoint} }->{is} ) ) { my $logger = Koha::Logger->get; - $logger->debug("koha borrower field to match: " . $config->{matchpoint}); - $logger->debug("shibboleth attribute to match: " . $config->{mapping}->{ $config->{matchpoint} }->{is}); + $logger->debug( "koha borrower field to match: " . $config->{matchpoint} ); + $logger->debug( "shibboleth attribute to match: " . $config->{mapping}->{ $config->{matchpoint} }->{is} ); return $config; - } - else { + } else { if ( !$config->{matchpoint} ) { carp 'shibboleth matchpoint not defined'; - } - else { + } else { carp 'shibboleth matchpoint not mapped'; } return 0; diff --git a/C4/AuthoritiesMarc.pm b/C4/AuthoritiesMarc.pm index 4fe55cd34b..6c8a6688a7 100644 --- a/C4/AuthoritiesMarc.pm +++ b/C4/AuthoritiesMarc.pm @@ -28,7 +28,7 @@ use C4::Search qw( FindDuplicate new_record_from_zebra ); use C4::AuthoritiesMarc::MARC21; use C4::AuthoritiesMarc::UNIMARC; use C4::Charset qw( SetUTF8Flag ); -use C4::Log qw( logaction ); +use C4::Log qw( logaction ); use Koha::MetadataRecord::Authority; use Koha::Authorities; use Koha::Authority::MergeRequests; @@ -40,42 +40,42 @@ use Koha::SearchEngine; use Koha::SearchEngine::Indexer; use Koha::SearchEngine::Search; -our (@ISA, @EXPORT_OK); +our ( @ISA, @EXPORT_OK ); + BEGIN { require Exporter; @ISA = qw(Exporter); @EXPORT_OK = qw( - GetTagsLabels - GetAuthMARCFromKohaField + GetTagsLabels + GetAuthMARCFromKohaField - AddAuthority - ModAuthority - DelAuthority - GetAuthority - GetAuthorityXML - GetAuthorizedHeading + AddAuthority + ModAuthority + DelAuthority + GetAuthority + GetAuthorityXML + GetAuthorizedHeading - SearchAuthorities + SearchAuthorities - BuildSummary - BuildAuthHierarchies - BuildAuthHierarchy - GenerateHierarchy - GetHeaderAuthority - AddAuthorityTrees - CompareFieldWithAuthority + BuildSummary + BuildAuthHierarchies + BuildAuthHierarchy + GenerateHierarchy + GetHeaderAuthority + AddAuthorityTrees + CompareFieldWithAuthority - merge - FindDuplicateAuthority + merge + FindDuplicateAuthority - GuessAuthTypeCode - GuessAuthId - compare_fields + GuessAuthTypeCode + GuessAuthId + compare_fields ); } - =head1 NAME C4::AuthoritiesMarc @@ -92,16 +92,18 @@ Suppose Kohafield is only linked to ONE subfield =cut sub GetAuthMARCFromKohaField { -#AUTHfind_marc_from_kohafield - my ( $kohafield,$authtypecode ) = @_; - my $dbh=C4::Context->dbh; - return 0, 0 unless $kohafield; - $authtypecode="" unless $authtypecode; - my $sth = $dbh->prepare("select tagfield,tagsubfield from auth_subfield_structure where kohafield= ? and authtypecode=? "); - $sth->execute($kohafield,$authtypecode); - my ($tagfield,$tagsubfield) = $sth->fetchrow; - - return ($tagfield,$tagsubfield); + + #AUTHfind_marc_from_kohafield + my ( $kohafield, $authtypecode ) = @_; + my $dbh = C4::Context->dbh; + return 0, 0 unless $kohafield; + $authtypecode = "" unless $authtypecode; + my $sth = $dbh->prepare( + "select tagfield,tagsubfield from auth_subfield_structure where kohafield= ? and authtypecode=? "); + $sth->execute( $kohafield, $authtypecode ); + my ( $tagfield, $tagsubfield ) = $sth->fetchrow; + + return ( $tagfield, $tagsubfield ); } =head2 SearchAuthorities @@ -115,33 +117,35 @@ returns ref to array result and count of results returned =cut sub SearchAuthorities { - my ($tags, $and_or, $excluding, $operator, $value, $offset,$length,$authtypecode,$sortby,$skipmetadata) = @_; + my ( $tags, $and_or, $excluding, $operator, $value, $offset, $length, $authtypecode, $sortby, $skipmetadata ) = @_; + # warn Dumper($tags, $and_or, $excluding, $operator, $value, $offset,$length,$authtypecode,$sortby); - my $dbh=C4::Context->dbh; - $sortby="" unless $sortby; + my $dbh = C4::Context->dbh; + $sortby = "" unless $sortby; my $query; my $qpquery = ''; - my $attr = ''; - # the marclist may contain "mainentry". In this case, search the tag_to_report, that depends on - # the authtypecode. Then, search on $a of this tag_to_report - # also store main entry MARC tag, to extract it at end of search + my $attr = ''; + + # the marclist may contain "mainentry". In this case, search the tag_to_report, that depends on + # the authtypecode. Then, search on $a of this tag_to_report + # also store main entry MARC tag, to extract it at end of search ##first set the authtype search and may be multiple authorities if ($authtypecode) { - my $n=0; + my $n = 0; my @authtypecode; - my @auths=split / /,$authtypecode ; - foreach my $auth (@auths){ - $query .=" \@attr 1=authtype \@attr 5=100 ".$auth; ##No truncation on authtype - push @authtypecode ,$auth; + my @auths = split / /, $authtypecode; + foreach my $auth (@auths) { + $query .= " \@attr 1=authtype \@attr 5=100 " . $auth; ##No truncation on authtype + push @authtypecode, $auth; $n++; } - if ($n>1){ - while ($n>1){$query= "\@or ".$query;$n--;} + if ( $n > 1 ) { + while ( $n > 1 ) { $query = "\@or " . $query; $n--; } } } my $dosearch; - my $and=" \@and " ; + my $and = " \@and "; my $q2; my $attr_cnt = 0; for ( my $i = 0 ; $i <= $#{$value} ; $i++ ) { @@ -149,58 +153,44 @@ sub SearchAuthorities { if ( @$tags[$i] ) { if ( @$tags[$i] eq "mainmainentry" ) { $attr = " \@attr 1=Heading-Main "; - } - elsif ( @$tags[$i] eq "mainentry" ) { + } elsif ( @$tags[$i] eq "mainentry" ) { $attr = " \@attr 1=Heading "; - } - elsif ( @$tags[$i] eq "match" ) { + } elsif ( @$tags[$i] eq "match" ) { $attr = " \@attr 1=Match "; - } - elsif ( @$tags[$i] eq "match-heading" ) { + } elsif ( @$tags[$i] eq "match-heading" ) { $attr = " \@attr 1=Match-heading "; - } - elsif ( @$tags[$i] eq "see-from" ) { + } elsif ( @$tags[$i] eq "see-from" ) { $attr = " \@attr 1=Match-heading-see-from "; - } - elsif ( @$tags[$i] eq "thesaurus" ) { + } elsif ( @$tags[$i] eq "thesaurus" ) { $attr = " \@attr 1=Subject-heading-thesaurus "; - } - elsif ( @$tags[$i] eq "all" ) { + } elsif ( @$tags[$i] eq "all" ) { $attr = " \@attr 1=Any "; - } - else { # Use the index passed in params + } else { # Use the index passed in params $attr = " \@attr 1=" . @$tags[$i] . " "; } - } #if @$tags[$i] + } #if @$tags[$i] else { # Assume any if no index was specified $attr = " \@attr 1=Any "; } my $operator = @$operator[$i]; if ( $operator and $operator eq 'is' ) { - $attr .= " \@attr 4=1 \@attr 5=100 " - ; ##Phrase, No truncation,all of subfield field must match - } - elsif ( $operator and $operator eq "=" ) { - $attr .= " \@attr 4=107 "; #Number Exact match - } - elsif ( $operator and $operator eq "start" ) { + $attr .= " \@attr 4=1 \@attr 5=100 "; ##Phrase, No truncation,all of subfield field must match + } elsif ( $operator and $operator eq "=" ) { + $attr .= " \@attr 4=107 "; #Number Exact match + } elsif ( $operator and $operator eq "start" ) { $attr .= " \@attr 3=2 \@attr 4=1 \@attr 5=1 \@attr 6=3 " - ; #Firstinfield Phrase, Right truncated, Complete field - } - elsif ( $operator and $operator eq "exact" ) { - $attr .= " \@attr 4=1 \@attr 5=100 \@attr 6=3 " - ; ##Phrase, No truncation,all of subfield field must match - } - else { - $attr .= " \@attr 5=1 \@attr 4=6 " - ; ## Word list, right truncated, anywhere + ; #Firstinfield Phrase, Right truncated, Complete field + } elsif ( $operator and $operator eq "exact" ) { + $attr .= + " \@attr 4=1 \@attr 5=100 \@attr 6=3 "; ##Phrase, No truncation,all of subfield field must match + } else { + $attr .= " \@attr 5=1 \@attr 4=6 "; ## Word list, right truncated, anywhere if ( $sortby eq 'Relevance' ) { $attr .= "\@attr 2=102 "; } } - @$value[$i] =~ - s/"/\\"/g; # Escape the double-quotes in the search value + @$value[$i] =~ s/"/\\"/g; # Escape the double-quotes in the search value $attr = $attr . "\"" . @$value[$i] . "\""; $q2 .= $attr; $dosearch = 1; @@ -209,22 +199,28 @@ sub SearchAuthorities { } ##Add how many queries generated if ( defined $query && $query =~ /\S+/ ) { + #NOTE: This code path is used by authority search in cataloguing plugins... #FIXME: This does not quite work the way the author probably intended. #It creates a ($query prefix) AND (query 1) AND (query 2) structure instead of #($query prefix) AND (query 1 AND query 2) $query = $and x $attr_cnt . $query . ( defined $q2 ? $q2 : '' ); } else { + #NOTE: This code path is used by authority search in authority home and record matching rules... my $op_prefix = ''; + #NOTE: Without the following code, multiple queries will never be joined together #with a Boolean operator. if ( $attr_cnt > 1 ) { + #NOTE: We always need 1 less operator than we have operands, #so long as there is more than 1 operand my $or_cnt = $attr_cnt - 1; + #NOTE: We hard-code OR here because that's what Elasticsearch does $op_prefix = ' @or ' x $or_cnt; + #NOTE: This evaluates to a logical structure like (query 1) OR (query 2) OR (query 3) } $query = $op_prefix . $q2; @@ -232,129 +228,132 @@ sub SearchAuthorities { ## Adding order #$query=' @or @attr 7=2 @attr 1=Heading 0 @or @attr 7=1 @attr 1=Heading 1'.$query if ($sortby eq "HeadingDsc"); my $orderstring; - if ($sortby eq 'HeadingAsc') { + if ( $sortby eq 'HeadingAsc' ) { $orderstring = '@attr 7=1 @attr 1=Heading 0'; - } elsif ($sortby eq 'HeadingDsc') { + } elsif ( $sortby eq 'HeadingDsc' ) { $orderstring = '@attr 7=2 @attr 1=Heading 0'; - } elsif ($sortby eq 'AuthidAsc') { + } elsif ( $sortby eq 'AuthidAsc' ) { $orderstring = '@attr 7=1 @attr 4=109 @attr 1=Local-Number 0'; - } elsif ($sortby eq 'AuthidDsc') { + } elsif ( $sortby eq 'AuthidDsc' ) { $orderstring = '@attr 7=2 @attr 4=109 @attr 1=Local-Number 0'; } - $query=($query?$query:"\@attr 1=_ALLRECORDS \@attr 2=103 ''"); - $query="\@or $orderstring $query" if $orderstring; + $query = ( $query ? $query : "\@attr 1=_ALLRECORDS \@attr 2=103 ''" ); + $query = "\@or $orderstring $query" if $orderstring; $offset = 0 if not defined $offset or $offset < 0; my $counter = $offset; - $length=10 unless $length; + $length = 10 unless $length; my @oAuth; my $i; - $oAuth[0]=C4::Context->Zconn("authorityserver" , 1); - my $Anewq= ZOOM::Query::PQF->new($query,$oAuth[0]); + $oAuth[0] = C4::Context->Zconn( "authorityserver", 1 ); + my $Anewq = ZOOM::Query::PQF->new( $query, $oAuth[0] ); my $oAResult; - $oAResult= $oAuth[0]->search($Anewq) ; - while (($i = ZOOM::event(\@oAuth)) != 0) { - my $ev = $oAuth[$i-1]->last_event(); + $oAResult = $oAuth[0]->search($Anewq); + + while ( ( $i = ZOOM::event( \@oAuth ) ) != 0 ) { + my $ev = $oAuth[ $i - 1 ]->last_event(); last if $ev == ZOOM::Event::ZEND; } - my($error, $errmsg, $addinfo, $diagset) = $oAuth[0]->error_x(); + my ( $error, $errmsg, $addinfo, $diagset ) = $oAuth[0]->error_x(); if ($error) { - warn "oAuth error: $errmsg ($error) $addinfo $diagset\n"; + warn "oAuth error: $errmsg ($error) $addinfo $diagset\n"; goto NOLUCK; } my $nbresults; - $nbresults=$oAResult->size(); - my $nremains=$nbresults; - my @result = (); + $nbresults = $oAResult->size(); + my $nremains = $nbresults; + my @result = (); my @finalresult = (); - if ($nbresults>0){ + if ( $nbresults > 0 ) { - ##Find authid and linkid fields - ##we may be searching multiple authoritytypes. - ## FIXME this assumes that all authid and linkid fields are the same for all authority types - # my ($authidfield,$authidsubfield)=GetAuthMARCFromKohaField($dbh,"auth_header.authid",$authtypecode[0]); - # my ($linkidfield,$linkidsubfield)=GetAuthMARCFromKohaField($dbh,"auth_header.linkid",$authtypecode[0]); - while (($counter < $nbresults) && ($counter < ($offset + $length))) { - - ##Here we have to extract MARC record and $authid from ZEBRA AUTHORITIES - my $rec=$oAResult->record($counter); - my $separator=C4::Context->preference('AuthoritySeparator'); - my $authrecord = C4::Search::new_record_from_zebra( - 'authorityserver', - $rec->raw() - ); + ##Find authid and linkid fields + ##we may be searching multiple authoritytypes. + ## FIXME this assumes that all authid and linkid fields are the same for all authority types + # my ($authidfield,$authidsubfield)=GetAuthMARCFromKohaField($dbh,"auth_header.authid",$authtypecode[0]); + # my ($linkidfield,$linkidsubfield)=GetAuthMARCFromKohaField($dbh,"auth_header.linkid",$authtypecode[0]); + while ( ( $counter < $nbresults ) && ( $counter < ( $offset + $length ) ) ) { - if ( !defined $authrecord or !defined $authrecord->field('001') ) { + ##Here we have to extract MARC record and $authid from ZEBRA AUTHORITIES + my $rec = $oAResult->record($counter); + my $separator = C4::Context->preference('AuthoritySeparator'); + my $authrecord = C4::Search::new_record_from_zebra( + 'authorityserver', + $rec->raw() + ); + + if ( !defined $authrecord or !defined $authrecord->field('001') ) { + $counter++; + next; + } + + SetUTF8Flag($authrecord); + + my $authid = $authrecord->field('001')->data(); + my %newline; + $newline{authid} = $authid; + if ( !$skipmetadata ) { + my ( $auth_tag_to_report, $reported_tag, $mainentry ); + if ($authtypecode) { + $auth_tag_to_report = Koha::Authority::Types->find($authtypecode)->auth_tag_to_report; + $mainentry = $authrecord->field($auth_tag_to_report) if $auth_tag_to_report; + } + if ($mainentry) { + $reported_tag = q{}; + foreach ( $mainentry->subfields() ) { + $reported_tag .= '$' . $_->[0] . $_->[1]; + } + } + + my ( $thisauthtype, $thisauthtypecode ); + if ( my $authority = Koha::Authorities->find($authid) ) { + $thisauthtypecode = $authority->authtypecode; + $thisauthtype = Koha::Authority::Types->find($thisauthtypecode); + } + unless ( defined $thisauthtype ) { + $thisauthtypecode = $authtypecode; + $thisauthtype = Koha::Authority::Types->find($thisauthtypecode); + } + my $summary = BuildSummary( $authrecord, $authid, $thisauthtypecode ); + + if ( C4::Context->preference('ShowHeadingUse') ) { + + # checking valid heading use + my $f008 = $authrecord->field('008'); + if ($f008) { + my $pos14to16 = substr( $f008->data, 14, 3 ); + my $main = substr( $pos14to16, 0, 1 ); + $newline{main} = 1 if $main eq 'a'; + my $subject = substr( $pos14to16, 1, 1 ); + $newline{subject} = 1 if $subject eq 'a'; + my $series = substr( $pos14to16, 2, 1 ); + $newline{series} = 1 if $series eq 'a'; + } + } + $newline{authtype} = defined($thisauthtype) ? $thisauthtype->authtypetext : ''; + $newline{summary} = $summary; + $newline{even} = $counter % 2; + $newline{reported_tag} = $reported_tag; + } $counter++; - next; - } - - SetUTF8Flag( $authrecord ); - - my $authid=$authrecord->field('001')->data(); - my %newline; - $newline{authid} = $authid; - if ( !$skipmetadata ) { - my ( $auth_tag_to_report, $reported_tag, $mainentry ); - if ( $authtypecode ) { - $auth_tag_to_report = Koha::Authority::Types->find($authtypecode)->auth_tag_to_report; - $mainentry = $authrecord->field($auth_tag_to_report) if $auth_tag_to_report; - } - if ($mainentry) { - $reported_tag = q{}; - foreach ( $mainentry->subfields() ) { - $reported_tag .= '$' . $_->[0] . $_->[1]; - } - } - - my ( $thisauthtype, $thisauthtypecode ); - if ( my $authority = Koha::Authorities->find($authid) ) { - $thisauthtypecode = $authority->authtypecode; - $thisauthtype = Koha::Authority::Types->find($thisauthtypecode); - } - unless (defined $thisauthtype) { - $thisauthtypecode = $authtypecode; - $thisauthtype = Koha::Authority::Types->find($thisauthtypecode); - } - my $summary = BuildSummary( $authrecord, $authid, $thisauthtypecode ); - - if ( C4::Context->preference('ShowHeadingUse') ) { - # checking valid heading use - my $f008 = $authrecord->field('008'); - if ($f008) { - my $pos14to16 = substr( $f008->data, 14, 3 ); - my $main = substr( $pos14to16, 0, 1 ); - $newline{main} = 1 if $main eq 'a'; - my $subject = substr( $pos14to16, 1, 1 ); - $newline{subject} = 1 if $subject eq 'a'; - my $series = substr( $pos14to16, 2, 1 ); - $newline{series} = 1 if $series eq 'a'; - } - } - $newline{authtype} = defined($thisauthtype) ? $thisauthtype->authtypetext : ''; - $newline{summary} = $summary; - $newline{even} = $counter % 2; - $newline{reported_tag} = $reported_tag; - } - $counter++; - push @finalresult, \%newline; - }## while counter + push @finalresult, \%newline; + } ## while counter ### - if (! $skipmetadata) { - for (my $z=0; $z<@finalresult; $z++){ - my $count = Koha::Authorities->get_usage_count({ authid => $finalresult[$z]{authid} }); - $finalresult[$z]{used}=$count; - }# all $z's + if ( !$skipmetadata ) { + for ( my $z = 0 ; $z < @finalresult ; $z++ ) { + my $count = Koha::Authorities->get_usage_count( { authid => $finalresult[$z]{authid} } ); + $finalresult[$z]{used} = $count; + } # all $z's } - }## if nbresult - NOLUCK: + } ## if nbresult +NOLUCK: $oAResult->destroy(); + # $oAuth[0]->destroy(); - return (\@finalresult, $nbresults); + return ( \@finalresult, $nbresults ); } =head2 GuessAuthTypeCode @@ -366,70 +365,72 @@ Get the record and tries to guess the adequate authtypecode from its content. =cut sub GuessAuthTypeCode { - my ($record, $heading_fields) = @_; + my ( $record, $heading_fields ) = @_; return unless defined $record; $heading_fields //= { - "MARC21"=>{ - '100'=>{authtypecode=>'PERSO_NAME'}, - '110'=>{authtypecode=>'CORPO_NAME'}, - '111'=>{authtypecode=>'MEETI_NAME'}, - '130'=>{authtypecode=>'UNIF_TITLE'}, - '147'=>{authtypecode=>'NAME_EVENT'}, - '148'=>{authtypecode=>'CHRON_TERM'}, - '150'=>{authtypecode=>'TOPIC_TERM'}, - '151'=>{authtypecode=>'GEOGR_NAME'}, - '155'=>{authtypecode=>'GENRE/FORM'}, - '162'=>{authtypecode=>'MED_PERFRM'}, - '180'=>{authtypecode=>'GEN_SUBDIV'}, - '181'=>{authtypecode=>'GEO_SUBDIV'}, - '182'=>{authtypecode=>'CHRON_SUBD'}, - '185'=>{authtypecode=>'FORM_SUBD'}, - }, -#200 Personal name 700, 701, 702 4-- with embedded 700, 701, 702 600 -# 604 with embedded 700, 701, 702 -#210 Corporate or meeting name 710, 711, 712 4-- with embedded 710, 711, 712 601 604 with embedded 710, 711, 712 -#215 Territorial or geographic name 710, 711, 712 4-- with embedded 710, 711, 712 601, 607 604 with embedded 710, 711, 712 -#216 Trademark 716 [Reserved for future use] -#220 Family name 720, 721, 722 4-- with embedded 720, 721, 722 602 604 with embedded 720, 721, 722 -#230 Title 500 4-- with embedded 500 605 -#240 Name and title (embedded 200, 210, 215, or 220 and 230) 4-- with embedded 7-- and 500 7-- 604 with embedded 7-- and 500 500 -#245 Name and collective title (embedded 200, 210, 215, or 220 and 235) 4-- with embedded 7-- and 501 604 with embedded 7-- and 501 7-- 501 -#250 Topical subject 606 -#260 Place access 620 -#280 Form, genre or physical characteristics 608 -# -# -# Could also be represented with : -#leader position 9 -#a = personal name entry -#b = corporate name entry -#c = territorial or geographical name -#d = trademark -#e = family name -#f = uniform title -#g = collective uniform title -#h = name/title -#i = name/collective uniform title -#j = topical subject -#k = place access -#l = form, genre or physical characteristics - "UNIMARC"=>{ - '200'=>{authtypecode=>'NP'}, - '210'=>{authtypecode=>'CO'}, - '215'=>{authtypecode=>'SNG'}, - '216'=>{authtypecode=>'TM'}, - '220'=>{authtypecode=>'FAM'}, - '230'=>{authtypecode=>'TU'}, - '235'=>{authtypecode=>'CO_UNI_TI'}, - '240'=>{authtypecode=>'SAUTTIT'}, - '245'=>{authtypecode=>'NAME_COL'}, - '250'=>{authtypecode=>'SNC'}, - '260'=>{authtypecode=>'PA'}, - '280'=>{authtypecode=>'GENRE/FORM'}, - } -}; - foreach my $field (keys %{$heading_fields->{uc(C4::Context->preference('marcflavour'))} }) { - return $heading_fields->{uc(C4::Context->preference('marcflavour'))}->{$field}->{'authtypecode'} if (defined $record->field($field)); + "MARC21" => { + '100' => { authtypecode => 'PERSO_NAME' }, + '110' => { authtypecode => 'CORPO_NAME' }, + '111' => { authtypecode => 'MEETI_NAME' }, + '130' => { authtypecode => 'UNIF_TITLE' }, + '147' => { authtypecode => 'NAME_EVENT' }, + '148' => { authtypecode => 'CHRON_TERM' }, + '150' => { authtypecode => 'TOPIC_TERM' }, + '151' => { authtypecode => 'GEOGR_NAME' }, + '155' => { authtypecode => 'GENRE/FORM' }, + '162' => { authtypecode => 'MED_PERFRM' }, + '180' => { authtypecode => 'GEN_SUBDIV' }, + '181' => { authtypecode => 'GEO_SUBDIV' }, + '182' => { authtypecode => 'CHRON_SUBD' }, + '185' => { authtypecode => 'FORM_SUBD' }, + }, + + #200 Personal name 700, 701, 702 4-- with embedded 700, 701, 702 600 + # 604 with embedded 700, 701, 702 + #210 Corporate or meeting name 710, 711, 712 4-- with embedded 710, 711, 712 601 604 with embedded 710, 711, 712 + #215 Territorial or geographic name 710, 711, 712 4-- with embedded 710, 711, 712 601, 607 604 with embedded 710, 711, 712 + #216 Trademark 716 [Reserved for future use] + #220 Family name 720, 721, 722 4-- with embedded 720, 721, 722 602 604 with embedded 720, 721, 722 + #230 Title 500 4-- with embedded 500 605 + #240 Name and title (embedded 200, 210, 215, or 220 and 230) 4-- with embedded 7-- and 500 7-- 604 with embedded 7-- and 500 500 + #245 Name and collective title (embedded 200, 210, 215, or 220 and 235) 4-- with embedded 7-- and 501 604 with embedded 7-- and 501 7-- 501 + #250 Topical subject 606 + #260 Place access 620 + #280 Form, genre or physical characteristics 608 + # + # + # Could also be represented with : + #leader position 9 + #a = personal name entry + #b = corporate name entry + #c = territorial or geographical name + #d = trademark + #e = family name + #f = uniform title + #g = collective uniform title + #h = name/title + #i = name/collective uniform title + #j = topical subject + #k = place access + #l = form, genre or physical characteristics + "UNIMARC" => { + '200' => { authtypecode => 'NP' }, + '210' => { authtypecode => 'CO' }, + '215' => { authtypecode => 'SNG' }, + '216' => { authtypecode => 'TM' }, + '220' => { authtypecode => 'FAM' }, + '230' => { authtypecode => 'TU' }, + '235' => { authtypecode => 'CO_UNI_TI' }, + '240' => { authtypecode => 'SAUTTIT' }, + '245' => { authtypecode => 'NAME_COL' }, + '250' => { authtypecode => 'SNC' }, + '260' => { authtypecode => 'PA' }, + '280' => { authtypecode => 'GENRE/FORM' }, + } + }; + foreach my $field ( keys %{ $heading_fields->{ uc( C4::Context->preference('marcflavour') ) } } ) { + return $heading_fields->{ uc( C4::Context->preference('marcflavour') ) }->{$field}->{'authtypecode'} + if ( defined $record->field($field) ); } return; } @@ -444,11 +445,12 @@ Get the record and tries to guess the adequate authtypecode from its content. sub GuessAuthId { my ($record) = @_; - return unless ($record && $record->field('001')); -# my $authtypecode=GuessAuthTypeCode($record); -# my ($tag,$subfield)=GetAuthMARCFromKohaField("auth_header.authid",$authtypecode); -# if ($tag > 010) {return $record->subfield($tag,$subfield)} -# else {return $record->field($tag)->data} + return unless ( $record && $record->field('001') ); + + # my $authtypecode=GuessAuthTypeCode($record); + # my ($tag,$subfield)=GetAuthMARCFromKohaField("auth_header.authid",$authtypecode); + # if ($tag > 010) {return $record->subfield($tag,$subfield)} + # else {return $record->field($tag)->data} return $record->field('001')->data; } @@ -480,36 +482,35 @@ where attribute takes values in : =cut sub GetTagsLabels { - my ($forlibrarian,$authtypecode)= @_; - my $dbh=C4::Context->dbh; - $authtypecode="" unless $authtypecode; - my $sth; - my $libfield = ($forlibrarian) ? 'liblibrarian' : 'libopac'; + my ( $forlibrarian, $authtypecode ) = @_; + my $dbh = C4::Context->dbh; + $authtypecode = "" unless $authtypecode; + my $sth; + my $libfield = ($forlibrarian) ? 'liblibrarian' : 'libopac'; - - # check that authority exists - $sth=$dbh->prepare("SELECT count(*) FROM auth_tag_structure WHERE authtypecode=?"); - $sth->execute($authtypecode); - my ($total) = $sth->fetchrow; - $authtypecode="" unless ($total >0); - $sth= $dbh->prepare( -"SELECT auth_tag_structure.tagfield,auth_tag_structure.liblibrarian,auth_tag_structure.libopac,auth_tag_structure.mandatory,auth_tag_structure.repeatable + # check that authority exists + $sth = $dbh->prepare("SELECT count(*) FROM auth_tag_structure WHERE authtypecode=?"); + $sth->execute($authtypecode); + my ($total) = $sth->fetchrow; + $authtypecode = "" unless ( $total > 0 ); + $sth = $dbh->prepare( + "SELECT auth_tag_structure.tagfield,auth_tag_structure.liblibrarian,auth_tag_structure.libopac,auth_tag_structure.mandatory,auth_tag_structure.repeatable FROM auth_tag_structure WHERE authtypecode=? ORDER BY tagfield" ); - $sth->execute($authtypecode); - my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable ); + $sth->execute($authtypecode); + my ( $liblibrarian, $libopac, $tag, $res, $tab, $mandatory, $repeatable ); - while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable ) = $sth->fetchrow ) { - $res->{$tag}->{lib} = ($forlibrarian or !$libopac)?$liblibrarian:$libopac; - $res->{$tag}->{tab} = " "; # XXX + while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable ) = $sth->fetchrow ) { + $res->{$tag}->{lib} = ( $forlibrarian or !$libopac ) ? $liblibrarian : $libopac; + $res->{$tag}->{tab} = " "; # XXX $res->{$tag}->{mandatory} = $mandatory; $res->{$tag}->{repeatable} = $repeatable; - } - $sth= $dbh->prepare( -"SELECT tagfield,tagsubfield,liblibrarian,libopac,tab, mandatory, repeatable,authorised_value,frameworkcode as authtypecode,value_builder,kohafield,seealso,hidden,isurl,defaultvalue, display_order + } + $sth = $dbh->prepare( + "SELECT tagfield,tagsubfield,liblibrarian,libopac,tab, mandatory, repeatable,authorised_value,frameworkcode as authtypecode,value_builder,kohafield,seealso,hidden,isurl,defaultvalue, display_order FROM auth_subfield_structure WHERE authtypecode=? ORDER BY tagfield, display_order, tagsubfield" @@ -527,15 +528,17 @@ ORDER BY tagfield, display_order, tagsubfield" my $display_order; while ( - ( $tag, $subfield, $liblibrarian, , $libopac, $tab, - $mandatory, $repeatable, $authorised_value, $authtypecode, - $value_builder, $kohafield, $seealso, $hidden, - $isurl, $defaultvalue, $display_order ) + ( + $tag, $subfield, $liblibrarian,, $libopac, $tab, + $mandatory, $repeatable, $authorised_value, $authtypecode, + $value_builder, $kohafield, $seealso, $hidden, + $isurl, $defaultvalue, $display_order + ) = $sth->fetchrow - ) + ) { $res->{$tag}->{$subfield}->{subfield} = $subfield; - $res->{$tag}->{$subfield}->{lib} = ($forlibrarian or !$libopac)?$liblibrarian:$libopac; + $res->{$tag}->{$subfield}->{lib} = ( $forlibrarian or !$libopac ) ? $liblibrarian : $libopac; $res->{$tag}->{$subfield}->{tab} = $tab; $res->{$tag}->{$subfield}->{mandatory} = $mandatory; $res->{$tag}->{$subfield}->{repeatable} = $repeatable; @@ -688,6 +691,7 @@ sub AddAuthority { $action = 'modify'; $authority = Koha::Authorities->find($authid); $authority->authtypecode($authtypecode); + # In the case we are changing type we need to set this to ensure heading field is correctly chosen } @@ -729,26 +733,26 @@ skip_record_index will skip the indexation step. =cut sub DelAuthority { - my ( $params ) = @_; - my $authid = $params->{authid} || return; - my $skip_merge = $params->{skip_merge}; + my ($params) = @_; + my $authid = $params->{authid} || return; + my $skip_merge = $params->{skip_merge}; my $skip_record_index = $params->{skip_record_index} || 0; my $dbh = C4::Context->dbh; # Remove older pending merge requests for $authid to itself. (See bug 22437) - my $condition = { authid => $authid, authid_new => [undef, 0, $authid], done => 0 }; + my $condition = { authid => $authid, authid_new => [ undef, 0, $authid ], done => 0 }; Koha::Authority::MergeRequests->search($condition)->delete; - merge({ mergefrom => $authid }) if !$skip_merge; + merge( { mergefrom => $authid } ) if !$skip_merge; $dbh->do( "DELETE FROM auth_header WHERE authid=?", undef, $authid ); logaction( "AUTHORITIES", "DELETE", $authid, "authority" ) if C4::Context->preference("AuthoritiesLog"); - unless ( $skip_record_index ) { - my $indexer = Koha::SearchEngine::Indexer->new({ index => $Koha::SearchEngine::AUTHORITIES_INDEX }); + unless ($skip_record_index) { + my $indexer = Koha::SearchEngine::Indexer->new( { index => $Koha::SearchEngine::AUTHORITIES_INDEX } ); $indexer->index_records( $authid, "recordDelete", "authorityserver", undef ); } - _after_authority_action_hooks({ action => 'delete', authority_id => $authid }); + _after_authority_action_hooks( { action => 'delete', authority_id => $authid } ); } =head2 ModAuthority @@ -768,10 +772,13 @@ sub ModAuthority { my $skip_record_index = $params->{skip_record_index} || 0; my $oldrecord = GetAuthority($authid); + #Now rewrite the $record to table with an add - $authid = AddAuthority($record, $authid, $authtypecode, { skip_record_index => $skip_record_index }); - merge({ mergefrom => $authid, MARCfrom => $oldrecord, mergeto => $authid, MARCto => $record }) if !$params->{skip_merge}; - logaction( "AUTHORITIES", "MODIFY", $authid, "authority BEFORE=>" . $oldrecord->as_formatted ) if C4::Context->preference("AuthoritiesLog"); + $authid = AddAuthority( $record, $authid, $authtypecode, { skip_record_index => $skip_record_index } ); + merge( { mergefrom => $authid, MARCfrom => $oldrecord, mergeto => $authid, MARCto => $record } ) + if !$params->{skip_merge}; + logaction( "AUTHORITIES", "MODIFY", $authid, "authority BEFORE=>" . $oldrecord->as_formatted ) + if C4::Context->preference("AuthoritiesLog"); return $authid; } @@ -784,25 +791,26 @@ returns xml form of record $authid =cut sub GetAuthorityXML { - # Returns MARC::XML of the authority passed in parameter. - my ( $authid ) = @_; - if (uc(C4::Context->preference('marcflavour')) eq 'UNIMARC') { - my $dbh=C4::Context->dbh; - my $sth = $dbh->prepare("select marcxml from auth_header where authid=? " ); - $sth->execute($authid); - my ($marcxml)=$sth->fetchrow; - return $marcxml; - } - else { - # for MARC21, call GetAuthority instead of - # getting the XML directly since we may - # need to fix up the location of the authority - # code -- note that this is reasonably safe - # because GetAuthorityXML is used only by the - # indexing processes like zebraqueue_start.pl - my $record = GetAuthority($authid); - return $record->as_xml_record('MARC21'); - } + + # Returns MARC::XML of the authority passed in parameter. + my ($authid) = @_; + if ( uc( C4::Context->preference('marcflavour') ) eq 'UNIMARC' ) { + my $dbh = C4::Context->dbh; + my $sth = $dbh->prepare("select marcxml from auth_header where authid=? "); + $sth->execute($authid); + my ($marcxml) = $sth->fetchrow; + return $marcxml; + } else { + + # for MARC21, call GetAuthority instead of + # getting the XML directly since we may + # need to fix up the location of the authority + # code -- note that this is reasonably safe + # because GetAuthorityXML is used only by the + # indexing processes like zebraqueue_start.pl + my $record = GetAuthority($authid); + return $record->as_xml_record('MARC21'); + } } =head2 GetAuthority @@ -814,10 +822,10 @@ Returns MARC::Record of the authority passed in parameter. =cut sub GetAuthority { - my ($authid)=@_; + my ($authid) = @_; my $authority = Koha::MetadataRecord::Authority->get_from_authid($authid); return unless $authority; - return ($authority->record); + return ( $authority->record ); } =head2 FindDuplicateAuthority @@ -832,28 +840,33 @@ Comments : an improvement would be to return All the records that match. sub FindDuplicateAuthority { - my ($record,$authtypecode)=@_; - my $dbh = C4::Context->dbh; + my ( $record, $authtypecode ) = @_; + my $dbh = C4::Context->dbh; my $auth_tag_to_report = Koha::Authority::Types->find($authtypecode)->auth_tag_to_report; + # build a request for SearchAuthorities - my $op = 'AND'; - my $query='at:"'.$authtypecode.'" '; # Quote authtype code to avoid unescaping slash in GENRE/FORM later - my $filtervalues=qr([\001-\040\Q!'"`#$%&*+,-./:;<=>?@(){[}_|~\E\]]); - if ($record->field($auth_tag_to_report)) { - foreach ($record->field($auth_tag_to_report)->subfields()) { - $_->[1]=~s/$filtervalues/ /g; $query.= " $op he:\"".$_->[1]."\"" if ($_->[0]=~/[A-z]/); + my $op = 'AND'; + my $query = 'at:"' . $authtypecode . '" '; # Quote authtype code to avoid unescaping slash in GENRE/FORM later + my $filtervalues = qr([\001-\040\Q!'"`#$%&*+,-./:;<=>?@(){[}_|~\E\]]); + if ( $record->field($auth_tag_to_report) ) { + foreach ( $record->field($auth_tag_to_report)->subfields() ) { + $_->[1] =~ s/$filtervalues/ /g; + $query .= " $op he:\"" . $_->[1] . "\"" if ( $_->[0] =~ /[A-z]/ ); } } - my $searcher = Koha::SearchEngine::Search->new({index => $Koha::SearchEngine::AUTHORITIES_INDEX}); - my ($error, $results, $total_hits) = $searcher->simple_search_compat( $query, 0, 1, [ 'authorityserver' ] ); + my $searcher = Koha::SearchEngine::Search->new( { index => $Koha::SearchEngine::AUTHORITIES_INDEX } ); + my ( $error, $results, $total_hits ) = $searcher->simple_search_compat( $query, 0, 1, ['authorityserver'] ); + # there is at least 1 result => return the 1st one - if (!defined $error && @{$results} ) { + if ( !defined $error && @{$results} ) { my $marcrecord = C4::Search::new_record_from_zebra( 'authorityserver', $results->[0] ); - return $marcrecord->field('001')->data,BuildSummary($marcrecord,$marcrecord->field('001')->data,$authtypecode); + return $marcrecord->field('001')->data, + BuildSummary( $marcrecord, $marcrecord->field('001')->data, $authtypecode ); } + # no result, returns nothing return; } @@ -872,28 +885,31 @@ Would it be interesting to delete those things. sub BuildSummary { ## give this a Marc record to return summary - my ($record,$authid,$authtypecode)=@_; - my $dbh=C4::Context->dbh; + my ( $record, $authid, $authtypecode ) = @_; + my $dbh = C4::Context->dbh; my %summary; my $summary_template; + # handle $authtypecode is NULL or eq "" if ($authtypecode) { my $authref = Koha::Authority::Types->find($authtypecode); - if ( $authref ) { + if ($authref) { $summary{authtypecode} = $authref->authtypecode; - $summary{type} = $authref->authtypetext; - $summary_template = $authref->summary; + $summary{type} = $authref->authtypetext; + $summary_template = $authref->summary; + # for MARC21, the authority type summary displays a label meant for # display - if (C4::Context->preference('marcflavour') ne 'UNIMARC') { + if ( C4::Context->preference('marcflavour') ne 'UNIMARC' ) { $summary{label} = $authref->summary; } else { $summary{summary} = $authref->summary; } } } - my $marc21subfields = 'abcdfghjklmnopqrstuvxyz68'; - my %marc21controlrefs = ( 'a' => 'earlier', + my $marc21subfields = 'abcdfghjklmnopqrstuvxyz68'; + my %marc21controlrefs = ( + 'a' => 'earlier', 'b' => 'later', 'd' => 'acronym', 'f' => 'musical', @@ -909,45 +925,47 @@ sub BuildSummary { a => 'seealso', ); my %thesaurus; - $thesaurus{'1'}="Peuples"; - $thesaurus{'2'}="Anthroponymes"; - $thesaurus{'3'}="Oeuvres"; - $thesaurus{'4'}="Chronologie"; - $thesaurus{'5'}="Lieux"; - $thesaurus{'6'}="Sujets"; + $thesaurus{'1'} = "Peuples"; + $thesaurus{'2'} = "Anthroponymes"; + $thesaurus{'3'} = "Oeuvres"; + $thesaurus{'4'} = "Chronologie"; + $thesaurus{'5'} = "Lieux"; + $thesaurus{'6'} = "Sujets"; + #thesaurus a remplir my $reported_tag; -# if the library has a summary defined, use it. Otherwise, build a standard one -# FIXME - it appears that the summary field in the authority frameworks -# can work as a display template. However, this doesn't -# suit the MARC21 version, so for now the "templating" -# feature will be enabled only for UNIMARC for backwards -# compatibility. - if ($summary{summary} and C4::Context->preference('marcflavour') eq 'UNIMARC') { - my @matches = ($summary{summary} =~ m/\[(.*?)(\d{3})([\*a-z0-9])(.*?)\]/g); - my (@textbefore, @tag, @subtag, @textafter); - for(my $i = 0; $i < scalar @matches; $i++){ - push @textbefore, $matches[$i] if($i%4 == 0); - push @tag, $matches[$i] if($i%4 == 1); - push @subtag, $matches[$i] if($i%4 == 2); - push @textafter, $matches[$i] if($i%4 == 3); + + # if the library has a summary defined, use it. Otherwise, build a standard one + # FIXME - it appears that the summary field in the authority frameworks + # can work as a display template. However, this doesn't + # suit the MARC21 version, so for now the "templating" + # feature will be enabled only for UNIMARC for backwards + # compatibility. + if ( $summary{summary} and C4::Context->preference('marcflavour') eq 'UNIMARC' ) { + my @matches = ( $summary{summary} =~ m/\[(.*?)(\d{3})([\*a-z0-9])(.*?)\]/g ); + my ( @textbefore, @tag, @subtag, @textafter ); + for ( my $i = 0 ; $i < scalar @matches ; $i++ ) { + push @textbefore, $matches[$i] if ( $i % 4 == 0 ); + push @tag, $matches[$i] if ( $i % 4 == 1 ); + push @subtag, $matches[$i] if ( $i % 4 == 2 ); + push @textafter, $matches[$i] if ( $i % 4 == 3 ); } - for(my $i = scalar @tag; $i >= 0; $i--){ + for ( my $i = scalar @tag ; $i >= 0 ; $i-- ) { my $textbefore = $textbefore[$i] || ''; - my $tag = $tag[$i] || ''; - my $subtag = $subtag[$i] || ''; - my $textafter = $textafter[$i] || ''; - my $value = ''; - my $field = $record->field($tag); - if ( $field ) { - if($subtag eq '*') { - if($tag < 10) { + my $tag = $tag[$i] || ''; + my $subtag = $subtag[$i] || ''; + my $textafter = $textafter[$i] || ''; + my $value = ''; + my $field = $record->field($tag); + if ($field) { + if ( $subtag eq '*' ) { + if ( $tag < 10 ) { $value = $textbefore . $field->data() . $textafter; } } else { my @subfields = $field->subfield($subtag); - if(@subfields > 0) { - $value = $textbefore . join (" - ", @subfields) . $textafter; + if ( @subfields > 0 ) { + $value = $textbefore . join( " - ", @subfields ) . $textafter; } } } @@ -962,22 +980,24 @@ sub BuildSummary { my @otherscript; my @equalterm; - if (C4::Context->preference('marcflavour') eq 'UNIMARC') { -# construct UNIMARC summary, that is quite different from MARC21 one -# accepted form - foreach my $field ($record->field('2..')) { + if ( C4::Context->preference('marcflavour') eq 'UNIMARC' ) { + + # construct UNIMARC summary, that is quite different from MARC21 one + # accepted form + foreach my $field ( $record->field('2..') ) { push @authorized, { heading => $field->as_string('abcdefghijlmnopqrstuvwxyz'), hemain => ( $field->subfield('a') // undef ), field => $field->tag(), }; } -# rejected form(s) - foreach my $field ($record->field('3..')) { + + # rejected form(s) + foreach my $field ( $record->field('3..') ) { push @notes, { note => $field->subfield('a'), field => $field->tag() }; } - foreach my $field ($record->field('4..')) { - my $thesaurus = $field->subfield('2') ? "thes. : ".$thesaurus{"$field->subfield('2')"}." : " : ''; + foreach my $field ( $record->field('4..') ) { + my $thesaurus = $field->subfield('2') ? "thes. : " . $thesaurus{"$field->subfield('2')"} . " : " : ''; push @seefrom, { heading => $thesaurus . $field->as_string('abcdefghijlmnopqrstuvwxyz'), hemain => ( $field->subfield('a') // undef ), @@ -988,7 +1008,7 @@ sub BuildSummary { # see : @seealso = map { - my $type = $unimarc_relation_from_code{$_->subfield('5') || 'a'}; + my $type = $unimarc_relation_from_code{ $_->subfield('5') || 'a' }; my $heading = $_->as_string('abcdefgjxyz'); { field => $_->tag, @@ -1001,14 +1021,17 @@ sub BuildSummary { } $record->field('5..'); # Other forms - @otherscript = map { { - lang => length ($_->subfield('8')) == 6 ? substr ($_->subfield('8'), 3, 3) : $_->subfield('8') || '', - term => $_->subfield('a') . ($_->subfield('b') ? ', ' . $_->subfield('b') : ''), - direction => 'ltr', - field => $_->tag, - } } $record->field('7..'); + @otherscript = map { + { + lang => length( $_->subfield('8') ) == 6 ? substr( $_->subfield('8'), 3, 3 ) : $_->subfield('8') || '', + term => $_->subfield('a') . ( $_->subfield('b') ? ', ' . $_->subfield('b') : '' ), + direction => 'ltr', + field => $_->tag, + } + } $record->field('7..'); } else { + # construct MARC21 summary # FIXME - looping over 1XX is questionable # since MARC21 authority should have only one 1XX @@ -1017,167 +1040,172 @@ sub BuildSummary { my $subfields_to_report; my $delimiter = C4::Context->preference('AuthoritySeparator'); - foreach my $field ($record->field('1..')) { + foreach my $field ( $record->field('1..') ) { my $tag = $field->tag(); next if "152" eq $tag; -# FIXME - 152 is not a good tag to use -# in MARC21 -- purely local tags really ought to be -# 9XX + + # FIXME - 152 is not a good tag to use + # in MARC21 -- purely local tags really ought to be + # 9XX $subfields_to_report = $handler->get_auth_heading_subfields_to_report($tag); if ($subfields_to_report) { push @authorized, { heading => $field->as_string($subfields_to_report), - hemain => ( $field->subfield( substr($subfields_to_report, 0, 1) ) // undef ), + hemain => ( $field->subfield( substr( $subfields_to_report, 0, 1 ) ) // undef ), field => $tag, }; } else { push @authorized, { heading => $field->as_string(), - hemain => ( $field->subfield( 'a' ) // undef ), + hemain => ( $field->subfield('a') // undef ), field => $tag, }; } } - foreach my $field ($record->field('4..')) { #See From + foreach my $field ( $record->field('4..') ) { #See From my $type = 'seefrom'; - $type = ($marc21controlrefs{substr $field->subfield('w'), 0, 1} || '') if ($field->subfield('w')); - if ($type eq 'notapplicable') { + $type = ( $marc21controlrefs{ substr $field->subfield('w'), 0, 1 } || '' ) if ( $field->subfield('w') ); + if ( $type eq 'notapplicable' ) { $type = substr $field->subfield('w'), 2, 1; $type = 'earlier' if $type && $type ne 'n'; } - if ($type eq 'subfi') { + if ( $type eq 'subfi' ) { push @seefrom, { heading => $field->as_string($marc21subfields), - hemain => scalar $field->subfield( substr($marc21subfields, 0, 1) ), - type => ($field->subfield('i') || ''), + hemain => scalar $field->subfield( substr( $marc21subfields, 0, 1 ) ), + type => ( $field->subfield('i') || '' ), field => $field->tag(), }; } else { push @seefrom, { heading => $field->as_string($marc21subfields), - hemain => scalar $field->subfield( substr($marc21subfields, 0, 1) ), + hemain => scalar $field->subfield( substr( $marc21subfields, 0, 1 ) ), type => $type, field => $field->tag(), }; } } - foreach my $field ($record->field('5..')) { #See Also + foreach my $field ( $record->field('5..') ) { #See Also my $type = 'seealso'; - $type = ($marc21controlrefs{substr $field->subfield('w'), 0, 1} || '') if ($field->subfield('w')); - if ($type eq 'notapplicable') { + $type = ( $marc21controlrefs{ substr $field->subfield('w'), 0, 1 } || '' ) if ( $field->subfield('w') ); + if ( $type eq 'notapplicable' ) { $type = substr $field->subfield('w'), 2, 1; $type = 'earlier' if $type && $type ne 'n'; } - if ($type eq 'subfi') { + if ( $type eq 'subfi' ) { push @seealso, { heading => $field->as_string($marc21subfields), - hemain => scalar $field->subfield( substr($marc21subfields, 0, 1) ), + hemain => scalar $field->subfield( substr( $marc21subfields, 0, 1 ) ), type => scalar $field->subfield('i'), field => $field->tag(), search => $field->as_string($marc21subfields) || '', - authid => $field->subfield('9') || '' + authid => $field->subfield('9') || '' }; } else { push @seealso, { heading => $field->as_string($marc21subfields), - hemain => scalar $field->subfield( substr($marc21subfields, 0, 1) ), + hemain => scalar $field->subfield( substr( $marc21subfields, 0, 1 ) ), type => $type, field => $field->tag(), search => $field->as_string($marc21subfields) || '', - authid => $field->subfield('9') || '' + authid => $field->subfield('9') || '' }; } } - foreach my $field ($record->field('6..')) { + foreach my $field ( $record->field('6..') ) { push @notes, { note => $field->as_string(), field => $field->tag() }; } - foreach my $field ( $record->field('7..') ) { - my $subfields_to_subdivision; - my $tag = $field->tag(); + foreach my $field ( $record->field('7..') ) { + my $subfields_to_subdivision; + my $tag = $field->tag(); - if ( $tag eq '700' ) { - $subfields_to_report = 'abcdefghjklmnopqrst'; - $subfields_to_subdivision = 'vxyz'; - } elsif ( $tag eq '710' ) { - $subfields_to_report = 'abcdefghklmnoprst'; - $subfields_to_subdivision = 'vxyz'; - } elsif ( $tag eq '711' ) { - $subfields_to_report = 'acdefghklnpqst'; - $subfields_to_subdivision = 'vxyz'; - } elsif ( $tag eq '730' ) { - $subfields_to_report = 'adfghklmnoprst'; - $subfields_to_subdivision = 'vxyz'; - } elsif ( $tag eq '748' ) { - $subfields_to_report = 'ab'; - $subfields_to_subdivision = 'vxyz'; - } elsif ( $tag eq '750' ) { - $subfields_to_report = 'ab'; - $subfields_to_subdivision = 'vxyz'; - } elsif ( $tag eq '751' ) { - $subfields_to_report = 'a'; - $subfields_to_subdivision = 'vxyz'; - } elsif ( $tag eq '755' ) { - $subfields_to_report = 'abvxyz'; - $subfields_to_subdivision = 'vxyz'; - } elsif ( $tag eq '780' ) { - $subfields_to_report = 'vxyz'; - $delimiter = " "; - } elsif ( $tag eq '781' ) { - $subfields_to_report = 'vxyz'; - $delimiter = " "; - } elsif ( $tag eq '782' ) { - $subfields_to_report = 'vxyz'; - $delimiter = " "; - } elsif ( $tag eq '785' ) { - $subfields_to_report = 'vxyz'; - $delimiter = " "; - } + if ( $tag eq '700' ) { + $subfields_to_report = 'abcdefghjklmnopqrst'; + $subfields_to_subdivision = 'vxyz'; + } elsif ( $tag eq '710' ) { + $subfields_to_report = 'abcdefghklmnoprst'; + $subfields_to_subdivision = 'vxyz'; + } elsif ( $tag eq '711' ) { + $subfields_to_report = 'acdefghklnpqst'; + $subfields_to_subdivision = 'vxyz'; + } elsif ( $tag eq '730' ) { + $subfields_to_report = 'adfghklmnoprst'; + $subfields_to_subdivision = 'vxyz'; + } elsif ( $tag eq '748' ) { + $subfields_to_report = 'ab'; + $subfields_to_subdivision = 'vxyz'; + } elsif ( $tag eq '750' ) { + $subfields_to_report = 'ab'; + $subfields_to_subdivision = 'vxyz'; + } elsif ( $tag eq '751' ) { + $subfields_to_report = 'a'; + $subfields_to_subdivision = 'vxyz'; + } elsif ( $tag eq '755' ) { + $subfields_to_report = 'abvxyz'; + $subfields_to_subdivision = 'vxyz'; + } elsif ( $tag eq '780' ) { + $subfields_to_report = 'vxyz'; + $delimiter = " "; + } elsif ( $tag eq '781' ) { + $subfields_to_report = 'vxyz'; + $delimiter = " "; + } elsif ( $tag eq '782' ) { + $subfields_to_report = 'vxyz'; + $delimiter = " "; + } elsif ( $tag eq '785' ) { + $subfields_to_report = 'vxyz'; + $delimiter = " "; + } - my $heading = $field->as_string($subfields_to_report); + my $heading = $field->as_string($subfields_to_report); - if ($subfields_to_subdivision) { - my $subheading = $field->as_string( $subfields_to_subdivision, $delimiter ); - if ( length $subheading > 0 ) { - $heading .= $delimiter . $subheading; + if ($subfields_to_subdivision) { + my $subheading = $field->as_string( $subfields_to_subdivision, $delimiter ); + if ( length $subheading > 0 ) { + $heading .= $delimiter . $subheading; + } + } + + if ($subfields_to_report) { + push @equalterm, { + heading => $heading, + hemain => ( $field->subfield( substr( $subfields_to_report, 0, 1 ) ) // undef ), + field => $tag, + }; + } else { + push @equalterm, { + heading => $field->as_string(), + hemain => ( $field->subfield('a') // undef ), + field => $tag, + }; } } - if ($subfields_to_report) { - push @equalterm, { - heading => $heading, - hemain => ( $field->subfield( substr( $subfields_to_report, 0, 1 ) ) // undef ), - field => $tag, - }; - } else { - push @equalterm, { - heading => $field->as_string(), - hemain => ( $field->subfield('a') // undef ), - field => $tag, - }; - } - } - - foreach my $field ($record->field('880')) { - my $linkage = $field->subfield('6'); + foreach my $field ( $record->field('880') ) { + my $linkage = $field->subfield('6'); my $category = substr $linkage, 0, 1; - if ($category eq '1') { + if ( $category eq '1' ) { $category = 'preferred'; - } elsif ($category eq '4') { + } elsif ( $category eq '4' ) { $category = 'seefrom'; - } elsif ($category eq '5') { + } elsif ( $category eq '5' ) { $category = 'seealso'; } my $type; - if ($field->subfield('w')) { - $type = $marc21controlrefs{substr $field->subfield('w'), '0'}; + if ( $field->subfield('w') ) { + $type = $marc21controlrefs{ substr $field->subfield('w'), '0' }; } else { $type = $category; } my $direction = $linkage =~ m#/r$# ? 'rtl' : 'ltr'; - push @otherscript, { term => $field->as_string($subfields_to_report), category => $category, type => $type, direction => $direction, linkage => $linkage }; + push @otherscript, + { + term => $field->as_string($subfields_to_report), category => $category, type => $type, + direction => $direction, linkage => $linkage + }; } } $summary{mainentry} = $authorized[0]->{heading}; @@ -1205,23 +1233,24 @@ data from C4::AuthoritiesMarc to the object-oriented Koha::*::Authority. sub GetAuthorizedHeading { my $args = shift; my $record; - unless ($record = $args->{record}) { + unless ( $record = $args->{record} ) { return unless $args->{authid}; - $record = GetAuthority($args->{authid}); + $record = GetAuthority( $args->{authid} ); } - return unless (ref $record eq 'MARC::Record'); - if (C4::Context->preference('marcflavour') eq 'UNIMARC') { -# construct UNIMARC summary, that is quite different from MARC21 one -# accepted form - foreach my $field ($record->field('2..')) { + return unless ( ref $record eq 'MARC::Record' ); + if ( C4::Context->preference('marcflavour') eq 'UNIMARC' ) { + + # construct UNIMARC summary, that is quite different from MARC21 one + # accepted form + foreach my $field ( $record->field('2..') ) { return $field->as_string('abcdefghijlmnopqrstuvwxyz'); } } else { use C4::Heading::MARC21; my $handler = C4::Heading::MARC21->new(); - foreach my $field ($record->field('1..')) { - my $subfields = $handler->get_valid_bib_heading_subfields($field->tag()); + foreach my $field ( $record->field('1..') ) { + my $subfields = $handler->get_valid_bib_heading_subfields( $field->tag() ); return $field->as_string($subfields) if ($subfields); } } @@ -1239,20 +1268,21 @@ Takes a MARC::Field from a bibliographic record and an authid, and returns true sub CompareFieldWithAuthority { my $args = shift; - my $record = GetAuthority($args->{authid}); - return unless (ref $record eq 'MARC::Record'); - if (C4::Context->preference('marcflavour') eq 'UNIMARC') { + my $record = GetAuthority( $args->{authid} ); + return unless ( ref $record eq 'MARC::Record' ); + if ( C4::Context->preference('marcflavour') eq 'UNIMARC' ) { + # UNIMARC has same subfields for bibs and authorities - foreach my $field ($record->field('2..')) { - return compare_fields($field, $args->{field}, 'abcdefghijlmnopqrstuvwxyz'); + foreach my $field ( $record->field('2..') ) { + return compare_fields( $field, $args->{field}, 'abcdefghijlmnopqrstuvwxyz' ); } } else { use C4::Heading::MARC21; my $handler = C4::Heading::MARC21->new(); - foreach my $field ($record->field('1..')) { - my $subfields = $handler->get_valid_bib_heading_subfields($field->tag()); - return compare_fields($field, $args->{field}, $subfields) if ($subfields); + foreach my $field ( $record->field('1..') ) { + my $subfields = $handler->get_valid_bib_heading_subfields( $field->tag() ); + return compare_fields( $field, $args->{field}, $subfields ) if ($subfields); } } return 0; @@ -1270,53 +1300,65 @@ Example of text: =cut -sub BuildAuthHierarchies{ +sub BuildAuthHierarchies { my $authid = shift @_; -# warn "authid : $authid"; - my $force = shift @_ || (C4::Context->preference('marcflavour') eq 'UNIMARC' ? 0 : 1); + + # warn "authid : $authid"; + my $force = shift @_ || ( C4::Context->preference('marcflavour') eq 'UNIMARC' ? 0 : 1 ); my @globalresult; - my $dbh=C4::Context->dbh; + my $dbh = C4::Context->dbh; my $hierarchies; my $data = GetHeaderAuthority($authid); - if ($data->{'authtrees'} and not $force){ + if ( $data->{'authtrees'} and not $force ) { return $data->{'authtrees'}; -# } elsif ($data->{'authtrees'}){ -# $hierarchies=$data->{'authtrees'}; + + # } elsif ($data->{'authtrees'}){ + # $hierarchies=$data->{'authtrees'}; } else { my $record = GetAuthority($authid); my $found; return unless $record; - foreach my $field ($record->field('5..')){ + foreach my $field ( $record->field('5..') ) { my $broader = 0; - $broader = 1 if ( - (C4::Context->preference('marcflavour') eq 'UNIMARC' && $field->subfield('5') && $field->subfield('5') eq 'g') || - (C4::Context->preference('marcflavour') ne 'UNIMARC' && $field->subfield('w') && substr($field->subfield('w'), 0, 1) eq 'g')); + $broader = 1 + if ( + ( + C4::Context->preference('marcflavour') eq 'UNIMARC' + && $field->subfield('5') + && $field->subfield('5') eq 'g' + ) + || ( C4::Context->preference('marcflavour') ne 'UNIMARC' + && $field->subfield('w') + && substr( $field->subfield('w'), 0, 1 ) eq 'g' ) + ); if ($broader) { - my $subfauthid=_get_authid_subfield($field) || ''; - next if ($subfauthid eq $authid); + my $subfauthid = _get_authid_subfield($field) || ''; + next if ( $subfauthid eq $authid ); my $parentrecord = GetAuthority($subfauthid); next unless $parentrecord; - my $localresult=$hierarchies; + my $localresult = $hierarchies; my $trees; $trees = BuildAuthHierarchies($subfauthid); my @trees; - if ($trees=~/;/){ - @trees = split(/;/,$trees); + + if ( $trees =~ /;/ ) { + @trees = split( /;/, $trees ); } else { push @trees, $trees; } - foreach (@trees){ - $_.= ",$authid"; + foreach (@trees) { + $_ .= ",$authid"; } - @globalresult = (@globalresult,@trees); - $found=1; + @globalresult = ( @globalresult, @trees ); + $found = 1; } - $hierarchies=join(";",@globalresult); + $hierarchies = join( ";", @globalresult ); } -#Unless there is no ancestor, I am alone. - $hierarchies="$authid" unless ($hierarchies); + + #Unless there is no ancestor, I am alone. + $hierarchies = "$authid" unless ($hierarchies); } - AddAuthorityTrees($authid,$hierarchies); + AddAuthorityTrees( $authid, $hierarchies ); return $hierarchies; } @@ -1335,36 +1377,41 @@ return a hashref in order to display hierarchy for record and final Authid $auth =cut -sub BuildAuthHierarchy{ - my $record = shift @_; - my $class = shift @_; +sub BuildAuthHierarchy { + my $record = shift @_; + my $class = shift @_; my $authid_constructed = shift @_; - return unless ($record && $record->field('001')); - my $authid=$record->field('001')->data(); + return unless ( $record && $record->field('001') ); + my $authid = $record->field('001')->data(); my %cell; - my $parents=""; my $children=""; - my (@loopparents,@loopchildren); - my $marcflavour = C4::Context->preference('marcflavour'); + my $parents = ""; + my $children = ""; + my ( @loopparents, @loopchildren ); + my $marcflavour = C4::Context->preference('marcflavour'); my $relationshipsf = $marcflavour eq 'UNIMARC' ? '5' : 'w'; - foreach my $field ($record->field('5..')){ - my $subfauthid=_get_authid_subfield($field); - if ($subfauthid && $field->subfield($relationshipsf) && $field->subfield('a')){ - my $relationship = substr($field->subfield($relationshipsf), 0, 1); - if ($relationship eq 'h'){ - push @loopchildren, { "authid"=>$subfauthid,"value"=>$field->subfield('a')}; + + foreach my $field ( $record->field('5..') ) { + my $subfauthid = _get_authid_subfield($field); + if ( $subfauthid && $field->subfield($relationshipsf) && $field->subfield('a') ) { + my $relationship = substr( $field->subfield($relationshipsf), 0, 1 ); + if ( $relationship eq 'h' ) { + push @loopchildren, { "authid" => $subfauthid, "value" => $field->subfield('a') }; + } elsif ( $relationship eq 'g' ) { + push @loopparents, { "authid" => $subfauthid, "value" => $field->subfield('a') }; } - elsif ($relationship eq 'g'){ - push @loopparents, { "authid"=>$subfauthid,"value"=>$field->subfield('a')}; - } -# brothers could get in there with an else + + # brothers could get in there with an else } } - $cell{"parents"}=\@loopparents; - $cell{"children"}=\@loopchildren; - $cell{"class"}=$class; - $cell{"authid"}=$authid; - $cell{"current_value"} =1 if ($authid eq $authid_constructed); - $cell{"value"}=C4::Context->preference('marcflavour') eq 'UNIMARC' ? $record->subfield('2..',"a") : $record->subfield('1..', 'a'); + $cell{"parents"} = \@loopparents; + $cell{"children"} = \@loopchildren; + $cell{"class"} = $class; + $cell{"authid"} = $authid; + $cell{"current_value"} = 1 if ( $authid eq $authid_constructed ); + $cell{"value"} = + C4::Context->preference('marcflavour') eq 'UNIMARC' + ? $record->subfield( '2..', "a" ) + : $record->subfield( '1..', 'a' ); return \%cell; } @@ -1383,25 +1430,26 @@ don't ever pass in anything but zero to it). =cut sub BuildAuthHierarchyBranch { - my ($tree, $authid, $cnt) = @_; + my ( $tree, $authid, $cnt ) = @_; $cnt |= 0; - my $elementdata = GetAuthority(shift @$tree); - my $branch = BuildAuthHierarchy($elementdata,"child".$cnt, $authid); - if (scalar @$tree > 0) { - my $nextBranch = BuildAuthHierarchyBranch($tree, $authid, ++$cnt); + my $elementdata = GetAuthority( shift @$tree ); + my $branch = BuildAuthHierarchy( $elementdata, "child" . $cnt, $authid ); + if ( scalar @$tree > 0 ) { + my $nextBranch = BuildAuthHierarchyBranch( $tree, $authid, ++$cnt ); my $nextAuthid = $nextBranch->{authid}; my $found; + # If we already have the next branch listed as a child, let's # replace the old listing with the new one. If not, we will add # the branch at the end. - foreach my $cell (@{$branch->{children}}) { - if ($cell->{authid} eq $nextAuthid) { - $cell = $nextBranch; + foreach my $cell ( @{ $branch->{children} } ) { + if ( $cell->{authid} eq $nextAuthid ) { + $cell = $nextBranch; $found = 1; last; } } - push @{$branch->{children}}, $nextBranch unless $found; + push @{ $branch->{children} }, $nextBranch unless $found; } return $branch; } @@ -1418,21 +1466,21 @@ authority hierarchies. sub GenerateHierarchy { my ($authid) = @_; my $trees = BuildAuthHierarchies($authid); - my @trees = split /;/,$trees ; - push @trees,$trees unless (@trees); + my @trees = split /;/, $trees; + push @trees, $trees unless (@trees); my @loophierarchies; - foreach my $tree (@trees){ - my @tree=split /,/,$tree; + foreach my $tree (@trees) { + my @tree = split /,/, $tree; push @tree, $tree unless (@tree); - my $branch = BuildAuthHierarchyBranch(\@tree, $authid); - push @loophierarchies, [ $branch ]; + my $branch = BuildAuthHierarchyBranch( \@tree, $authid ); + push @loophierarchies, [$branch]; } return \@loophierarchies; } -sub _get_authid_subfield{ - my ($field)=@_; - return $field->subfield('9')||$field->subfield('3'); +sub _get_authid_subfield { + my ($field) = @_; + return $field->subfield('9') || $field->subfield('3'); } =head2 GetHeaderAuthority @@ -1443,14 +1491,14 @@ return a hashref in order auth_header table data =cut -sub GetHeaderAuthority{ - my $authid = shift @_; - my $sql= "SELECT * from auth_header WHERE authid = ?"; - my $dbh=C4::Context->dbh; - my $rq= $dbh->prepare($sql); - $rq->execute($authid); - my $data= $rq->fetchrow_hashref; - return $data; +sub GetHeaderAuthority { + my $authid = shift @_; + my $sql = "SELECT * from auth_header WHERE authid = ?"; + my $dbh = C4::Context->dbh; + my $rq = $dbh->prepare($sql); + $rq->execute($authid); + my $data = $rq->fetchrow_hashref; + return $data; } =head2 AddAuthorityTrees @@ -1461,13 +1509,13 @@ return success or failure =cut -sub AddAuthorityTrees{ - my $authid = shift @_; - my $trees = shift @_; - my $sql= "UPDATE IGNORE auth_header set authtrees=? WHERE authid = ?"; - my $dbh=C4::Context->dbh; - my $rq= $dbh->prepare($sql); - return $rq->execute($trees,$authid); +sub AddAuthorityTrees { + my $authid = shift @_; + my $trees = shift @_; + my $sql = "UPDATE IGNORE auth_header set authtrees=? WHERE authid = ?"; + my $dbh = C4::Context->dbh; + my $rq = $dbh->prepare($sql); + return $rq->execute( $trees, $authid ); } =head2 merge @@ -1503,69 +1551,76 @@ authority type, merge also supports moving to another authority type. =cut sub merge { - my ( $params ) = @_; - my $mergefrom = $params->{mergefrom} || return; - my $MARCfrom = $params->{MARCfrom}; - my $mergeto = $params->{mergeto}; - my $MARCto = $params->{MARCto}; + my ($params) = @_; + my $mergefrom = $params->{mergefrom} || return; + my $MARCfrom = $params->{MARCfrom}; + my $mergeto = $params->{mergeto}; + my $MARCto = $params->{MARCto}; my $override_limit = $params->{override_limit}; # If we do not have biblionumbers, we get all linked biblios if the # number of linked records does not exceed the limit UNLESS we override. my @biblionumbers; - if( $params->{biblionumbers} ) { + if ( $params->{biblionumbers} ) { @biblionumbers = @{ $params->{biblionumbers} }; - } elsif( $override_limit ) { - @biblionumbers = Koha::Authorities->linked_biblionumbers({ authid => $mergefrom }); - } else { # now first check number of linked records - my $max = C4::Context->preference('AuthorityMergeLimit') // 0; - my $hits = Koha::Authorities->get_usage_count({ authid => $mergefrom }); - if( $hits > 0 && $hits <= $max ) { - @biblionumbers = Koha::Authorities->linked_biblionumbers({ authid => $mergefrom }); - } elsif( $hits > $max ) { #postpone this merge to the cron job - Koha::Authority::MergeRequest->new({ - authid => $mergefrom, - oldrecord => $MARCfrom, - authid_new => $mergeto, - })->store; + } elsif ($override_limit) { + @biblionumbers = Koha::Authorities->linked_biblionumbers( { authid => $mergefrom } ); + } else { # now first check number of linked records + my $max = C4::Context->preference('AuthorityMergeLimit') // 0; + my $hits = Koha::Authorities->get_usage_count( { authid => $mergefrom } ); + if ( $hits > 0 && $hits <= $max ) { + @biblionumbers = Koha::Authorities->linked_biblionumbers( { authid => $mergefrom } ); + } elsif ( $hits > $max ) { #postpone this merge to the cron job + Koha::Authority::MergeRequest->new( + { + authid => $mergefrom, + oldrecord => $MARCfrom, + authid_new => $mergeto, + } + )->store; } } return 0 if !@biblionumbers; # Search authtypes and reporting tags my $authfrom = Koha::Authorities->find($mergefrom); - my $authto = Koha::Authorities->find($mergeto); + my $authto = Koha::Authorities->find($mergeto); my $authtypefrom; - my $authtypeto = $authto ? Koha::Authority::Types->find($authto->authtypecode) : undef; - if( $mergeto && $mergefrom == $mergeto && $MARCfrom ) { + my $authtypeto = $authto ? Koha::Authority::Types->find( $authto->authtypecode ) : undef; + if ( $mergeto && $mergefrom == $mergeto && $MARCfrom ) { + # bulkmarcimport may have changed the authtype; see BZ 19693 - my $old_type = $MARCfrom->subfield( get_auth_type_location() ); # going via default - if( $old_type && $authto && $old_type ne $authto->authtypecode ) { + my $old_type = $MARCfrom->subfield( get_auth_type_location() ); # going via default + if ( $old_type && $authto && $old_type ne $authto->authtypecode ) { + # Type change: handled by simulating a postponed merge where the auth record has been deleted already # This triggers a walk through all auth controlled tags undef $authfrom; } } - $authtypefrom = Koha::Authority::Types->find($authfrom->authtypecode) if $authfrom; + $authtypefrom = Koha::Authority::Types->find( $authfrom->authtypecode ) if $authfrom; my $auth_tag_to_report_from = $authtypefrom ? $authtypefrom->auth_tag_to_report : ''; - my $auth_tag_to_report_to = $authtypeto ? $authtypeto->auth_tag_to_report : ''; + my $auth_tag_to_report_to = $authtypeto ? $authtypeto->auth_tag_to_report : ''; my @record_to; - @record_to = $MARCto->field($auth_tag_to_report_to)->subfields() if $auth_tag_to_report_to && $MARCto && $MARCto->field($auth_tag_to_report_to); + @record_to = $MARCto->field($auth_tag_to_report_to)->subfields() + if $auth_tag_to_report_to && $MARCto && $MARCto->field($auth_tag_to_report_to); + # Exceptional: If MARCto and authtypeto exist but $auth_tag_to_report_to # is empty, make sure that $9 and $a remain (instead of clearing the # reference) in order to allow for data recovery. # Note: We need $a too, since a single $9 does not pass ModBiblio. - if( $MARCto && $authtypeto && !@record_to ) { - push @record_to, [ 'a', ' ' ]; # do not remove the space + if ( $MARCto && $authtypeto && !@record_to ) { + push @record_to, [ 'a', ' ' ]; # do not remove the space } my @record_from; - if( !$authfrom && $MARCfrom && $MARCfrom->field('1..','2..') ) { - # postponed merge, authfrom was deleted and MARCfrom only contains the old reporting tag (and possibly a 100 for UNIMARC) - # 2XX is for UNIMARC; we use -1 in order to skip 100 in UNIMARC; this will not impact MARC21, since there is only one tag - @record_from = ( $MARCfrom->field('1..','2..') )[-1]->subfields; - } elsif( $auth_tag_to_report_from && $MARCfrom && $MARCfrom->field($auth_tag_to_report_from) ) { + if ( !$authfrom && $MARCfrom && $MARCfrom->field( '1..', '2..' ) ) { + + # postponed merge, authfrom was deleted and MARCfrom only contains the old reporting tag (and possibly a 100 for UNIMARC) + # 2XX is for UNIMARC; we use -1 in order to skip 100 in UNIMARC; this will not impact MARC21, since there is only one tag + @record_from = ( $MARCfrom->field( '1..', '2..' ) )[-1]->subfields; + } elsif ( $auth_tag_to_report_from && $MARCfrom && $MARCfrom->field($auth_tag_to_report_from) ) { @record_from = $MARCfrom->field($auth_tag_to_report_from)->subfields; } @@ -1574,14 +1629,19 @@ sub merge { # For a deleted authority record, we scan all auth controlled fields my $dbh = C4::Context->dbh; my $sql = "SELECT DISTINCT tagfield FROM marc_subfield_structure WHERE authtypecode=?"; - my $tags_using_authtype = $authtypefrom && $authtypefrom->authtypecode ? $dbh->selectcol_arrayref( $sql, undef, ( $authtypefrom->authtypecode )) : $dbh->selectcol_arrayref( "SELECT DISTINCT tagfield FROM marc_subfield_structure WHERE authtypecode IS NOT NULL AND authtypecode<>''" ); + my $tags_using_authtype = + $authtypefrom && $authtypefrom->authtypecode + ? $dbh->selectcol_arrayref( $sql, undef, ( $authtypefrom->authtypecode ) ) + : $dbh->selectcol_arrayref( + "SELECT DISTINCT tagfield FROM marc_subfield_structure WHERE authtypecode IS NOT NULL AND authtypecode<>''"); my $tags_new; - if( $authtypeto && ( !$authtypefrom || $authtypeto->authtypecode ne $authtypefrom->authtypecode )) { - $tags_new = $dbh->selectcol_arrayref( $sql, undef, ( $authtypeto->authtypecode )); - } + if ( $authtypeto && ( !$authtypefrom || $authtypeto->authtypecode ne $authtypefrom->authtypecode ) ) { + $tags_new = $dbh->selectcol_arrayref( $sql, undef, ( $authtypeto->authtypecode ) ); + } - my $overwrite = C4::Context->preference( 'AuthorityMergeMode' ) eq 'strict'; + my $overwrite = C4::Context->preference('AuthorityMergeMode') eq 'strict'; my $skip_subfields = $overwrite + # This hash contains all subfields from the authority report fields # Including $MARCfrom as well as $MARCto # We only need it in loose merge mode; replaces the former $exclude @@ -1590,11 +1650,11 @@ sub merge { my $counteditedbiblio = 0; - my $biblios = Koha::Biblios->search({ biblionumber => { -in => \@biblionumbers } }); + my $biblios = Koha::Biblios->search( { biblionumber => { -in => \@biblionumbers } } ); while ( my $biblio = $biblios->next ) { my $marcrecord = $biblio->metadata->record; - my $update = 0; + my $update = 0; foreach my $tagfield (@$tags_using_authtype) { my $countfrom = 0; # used in strict mode to remove duplicates foreach my $field ( $marcrecord->field($tagfield) ) { @@ -1602,33 +1662,38 @@ sub merge { my $tag = $field->tag(); next if !defined($auth_number) || $auth_number ne $mergefrom; $countfrom++; - if ( !$mergeto || !@record_to || - ( $overwrite && $countfrom > 1 ) ) { + if ( !$mergeto + || !@record_to + || ( $overwrite && $countfrom > 1 ) ) + { # !mergeto or !record_to indicates a delete # Other condition: remove this duplicate in strict mode $marcrecord->delete_field($field); $update = 1; next; } - my $newtag = $tags_new && @$tags_new - ? _merge_newtag( $tag, $tags_new ) - : $tag; - my $controlled_ind = $authto->controlled_indicators({ record => $MARCto, biblio_tag => $newtag }); - my $field_to = MARC::Field->new( + my $newtag = + $tags_new && @$tags_new + ? _merge_newtag( $tag, $tags_new ) + : $tag; + my $controlled_ind = $authto->controlled_indicators( { record => $MARCto, biblio_tag => $newtag } ); + my $field_to = MARC::Field->new( $newtag, $controlled_ind->{ind1} // $field->indicator(1), $controlled_ind->{ind2} // $field->indicator(2), - 9 => $mergeto, # Needed to create field, will be moved + 9 => $mergeto, # Needed to create field, will be moved ); my ( @prefix, @postfix ); if ( !$overwrite ) { + # add subfields back in loose mode, check skip_subfields # The first extra subfields will be in front of the # controlled block, the rest at the end. my $prefix_flag = 1; foreach my $subfield ( $field->subfields ) { - next if $subfield->[0] eq '9'; # skip but leave flag + next if $subfield->[0] eq '9'; # skip but leave flag if ( $skip_subfields->{ $subfield->[0] } ) { + # This marks the beginning of the controlled block $prefix_flag = 0; next; @@ -1641,22 +1706,25 @@ sub merge { } } foreach my $subfield ( @prefix, @record_to, @postfix ) { - $field_to->add_subfields($subfield->[0] => $subfield->[1]); + $field_to->add_subfields( $subfield->[0] => $subfield->[1] ); } - if( exists $controlled_ind->{sub2} ) { # thesaurus info - if( defined $controlled_ind->{sub2} ) { + if ( exists $controlled_ind->{sub2} ) { # thesaurus info + if ( defined $controlled_ind->{sub2} ) { + # Add or replace $field_to->update( 2 => $controlled_ind->{sub2} ); } else { + # Key alerts us here to remove $2 $field_to->delete_subfield( code => '2' ); } } + # Move $9 to the end $field_to->delete_subfield( code => '9' ); $field_to->add_subfields( 9 => $mergeto ); - if ($tags_new && @$tags_new) { + if ( $tags_new && @$tags_new ) { $marcrecord->delete_field($field); append_fields_ordered( $marcrecord, $field_to ); } else { @@ -1673,16 +1741,18 @@ sub merge { } sub _merge_newtag { -# Routine is only called for an (exceptional) authtypecode change -# Fixes old behavior of returning the first tag found + + # Routine is only called for an (exceptional) authtypecode change + # Fixes old behavior of returning the first tag found my ( $oldtag, $new_tags ) = @_; # If we e.g. have 650 and 151,651,751 try 651 and check presence my $prefix = substr( $oldtag, 0, 1 ); - my $guess = $prefix . substr( $new_tags->[0], -2 ); - if( grep { $_ eq $guess } @$new_tags ) { + my $guess = $prefix . substr( $new_tags->[0], -2 ); + if ( grep { $_ eq $guess } @$new_tags ) { return $guess; } + # Otherwise return one from the same block e.g. 6XX for 650 # If not there too, fall back to first new tag (old behavior!) my @same_block = grep { /^$prefix/ } @$new_tags; @@ -1690,13 +1760,14 @@ sub _merge_newtag { } sub append_fields_ordered { -# while we lack this function in MARC::Record -# we do not want insert_fields_ordered since it inserts before + + # while we lack this function in MARC::Record + # we do not want insert_fields_ordered since it inserts before my ( $record, $field ) = @_; - if( my @flds = $record->field( $field->tag ) ) { + if ( my @flds = $record->field( $field->tag ) ) { $record->insert_fields_after( pop @flds, $field ); - } else { # now fallback to insert_fields_ordered - $record->insert_fields_ordered( $field ); + } else { # now fallback to insert_fields_ordered + $record->insert_fields_ordered($field); } } @@ -1719,11 +1790,11 @@ specific to the MARC format. sub get_auth_type_location { my $auth_type_code = @_ ? shift : ''; - my ($tag, $subfield) = GetAuthMARCFromKohaField('auth_header.authtypecode', $auth_type_code); - if (defined $tag and defined $subfield and $tag != 0 and $subfield ne '' and $subfield ne ' ') { - return ($tag, $subfield); + my ( $tag, $subfield ) = GetAuthMARCFromKohaField( 'auth_header.authtypecode', $auth_type_code ); + if ( defined $tag and defined $subfield and $tag != 0 and $subfield ne '' and $subfield ne ' ' ) { + return ( $tag, $subfield ); } else { - if (C4::Context->preference('marcflavour') eq "MARC21") { + if ( C4::Context->preference('marcflavour') eq "MARC21" ) { return C4::AuthoritiesMarc::MARC21::default_auth_type_location(); } else { return C4::AuthoritiesMarc::UNIMARC::default_auth_type_location(); @@ -1740,9 +1811,9 @@ Compares the listed subfields of both fields and return true if they all match =cut sub compare_fields { - my ($field1, $field2, $subfields) = @_; + my ( $field1, $field2, $subfields ) = @_; - foreach my $subfield (split(//, $subfields)) { + foreach my $subfield ( split( //, $subfields ) ) { my $subfield1 = $field1->subfield($subfield) // ''; my $subfield2 = $field2->subfield($subfield) // ''; return 0 unless $subfield1 eq $subfield2; @@ -1750,7 +1821,6 @@ sub compare_fields { return 1; } - =head2 _after_authority_action_hooks Helper method that takes care of calling all plugin hooks @@ -1758,11 +1828,11 @@ Helper method that takes care of calling all plugin hooks =cut sub _after_authority_action_hooks { - my ( $args ) = @_; # hash keys: action, authority_id + my ($args) = @_; # hash keys: action, authority_id return Koha::Plugins->call( 'after_authority_action', $args ); } -END { } # module clean-up code here (global destructor) +END { } # module clean-up code here (global destructor) 1; __END__ diff --git a/C4/AuthoritiesMarc/MARC21.pm b/C4/AuthoritiesMarc/MARC21.pm index c3c6f84730..9e52023ed3 100644 --- a/C4/AuthoritiesMarc/MARC21.pm +++ b/C4/AuthoritiesMarc/MARC21.pm @@ -1,7 +1,7 @@ package C4::AuthoritiesMarc::MARC21; # Copyright (C) 2007 LibLime -# +# # This file is part of Koha. # # Koha is free software; you can redistribute it and/or modify it @@ -64,7 +64,7 @@ this defaults to 942$a. =cut sub default_auth_type_location { - return ('942', 'a'); + return ( '942', 'a' ); } =head2 fix_marc21_auth_type_location @@ -91,15 +91,15 @@ FIXME: This function should be removed once it's determined =cut sub fix_marc21_auth_type_location { - my ($auth_marc, $auth_type_tag, $auth_type_subfield) = @_; + my ( $auth_marc, $auth_type_tag, $auth_type_subfield ) = @_; my $auth_type_code; - return unless $auth_type_code = $auth_marc->subfield('152', 'b'); - $auth_marc->delete_field($auth_marc->field('152')); - unless ($auth_marc->field($auth_type_tag) && $auth_marc->subfield($auth_type_tag, $auth_type_subfield)) { - $auth_marc->add_fields($auth_type_tag,'','', $auth_type_subfield=>$auth_type_code); + return unless $auth_type_code = $auth_marc->subfield( '152', 'b' ); + $auth_marc->delete_field( $auth_marc->field('152') ); + unless ( $auth_marc->field($auth_type_tag) && $auth_marc->subfield( $auth_type_tag, $auth_type_subfield ) ) { + $auth_marc->add_fields( $auth_type_tag, '', '', $auth_type_subfield => $auth_type_code ); } - + } =head1 AUTHOR diff --git a/C4/AuthoritiesMarc/UNIMARC.pm b/C4/AuthoritiesMarc/UNIMARC.pm index ebeaccc0d1..ca54e0d413 100644 --- a/C4/AuthoritiesMarc/UNIMARC.pm +++ b/C4/AuthoritiesMarc/UNIMARC.pm @@ -1,7 +1,7 @@ package C4::AuthoritiesMarc::UNIMARC; # Copyright (C) 2007 LibLime -# +# # This file is part of Koha. # # Koha is free software; you can redistribute it and/or modify it @@ -64,7 +64,7 @@ this defaults to 152$b. =cut sub default_auth_type_location { - return ('152', 'b'); + return ( '152', 'b' ); } =head1 AUTHOR diff --git a/C4/Barcodes.pm b/C4/Barcodes.pm index 333a8eb8bc..9a04cc1ce5 100644 --- a/C4/Barcodes.pm +++ b/C4/Barcodes.pm @@ -31,68 +31,77 @@ use C4::Barcodes::EAN13; use vars qw($max $prefformat); sub _prefformat { - unless (defined $prefformat) { - unless ($prefformat = C4::Context->preference('autoBarcode')) { - carp "The autoBarcode syspref is missing/undefined. Assuming 'incremental'."; - $prefformat = 'incremental'; - } - } - return $prefformat; + unless ( defined $prefformat ) { + unless ( $prefformat = C4::Context->preference('autoBarcode') ) { + carp "The autoBarcode syspref is missing/undefined. Assuming 'incremental'."; + $prefformat = 'incremental'; + } + } + return $prefformat; } sub initial { - return '0000001'; + return '0000001'; } + sub width { - return; + return; } -sub process_head { # (self,head,whole,specific) - my $self = shift; - return shift; # Default: just return the head unchanged. + +sub process_head { # (self,head,whole,specific) + my $self = shift; + return shift; # Default: just return the head unchanged. } -sub process_tail { # (self,tail,whole,specific) - my $self = shift; - return shift; # Default: just return the tail unchanged. + +sub process_tail { # (self,tail,whole,specific) + my $self = shift; + return shift; # Default: just return the tail unchanged. } + sub is_max { - my $self = shift; - ref($self) or carp "Called is_max on a non-object: '$self'"; - (@_) and $self->{is_max} = shift; - return $self->{is_max} || 0; + my $self = shift; + ref($self) or carp "Called is_max on a non-object: '$self'"; + (@_) and $self->{is_max} = shift; + return $self->{is_max} || 0; } + sub value { - my $self = shift; - if (@_) { - my $value = shift; + my $self = shift; + if (@_) { + my $value = shift; warn "Error: UNDEF argument to value" unless defined $value; - $self->{value} = $value; - } - return $self->{value}; + $self->{value} = $value; + } + return $self->{value}; } + sub autoBarcode { - (@_) or return _prefformat; - my $self = shift; - my $value = $self->{autoBarcode} or return _prefformat; - $value =~ s/^.*:://; # in case we get C4::Barcodes::incremental, we just want 'incremental' - return $value; + (@_) or return _prefformat; + my $self = shift; + my $value = $self->{autoBarcode} or return _prefformat; + $value =~ s/^.*:://; # in case we get C4::Barcodes::incremental, we just want 'incremental' + return $value; } -sub parse { # return 3 parts of barcode: non-incrementing, incrementing, non-incrementing - my $self = shift; - my $barcode = (@_) ? shift : $self->value; - unless ($barcode =~ /(.*?)(\d+)$/) { # non-greedy match in first part - carp "Barcode '$barcode' has no incrementing part!"; - return ($barcode,undef,undef); - } - return ($1,$2,''); # the third part is in anticipation of barcodes that include checkdigits + +sub parse { # return 3 parts of barcode: non-incrementing, incrementing, non-incrementing + my $self = shift; + my $barcode = (@_) ? shift : $self->value; + unless ( $barcode =~ /(.*?)(\d+)$/ ) { # non-greedy match in first part + carp "Barcode '$barcode' has no incrementing part!"; + return ( $barcode, undef, undef ); + } + return ( $1, $2, '' ); # the third part is in anticipation of barcodes that include checkdigits } + sub max { - my $self = shift; - if ($self->{is_max}) { - return $self->value; - } - return $self->db_max; + my $self = shift; + if ( $self->{is_max} ) { + return $self->value; + } + return $self->db_max; } + sub db_max { my $self = shift; my $query = "SELECT max(abs(CAST(barcode AS UNSIGNED))) FROM items LIMIT 1" @@ -101,117 +110,124 @@ sub db_max { $sth->execute(); return $sth->fetchrow_array || $self->initial; } -sub next_value { - my $self = shift; - my $specific = (scalar @_) ? 1 : 0; - my $max = $specific ? shift : $self->max; # optional argument, i.e. next_value after X - unless ($max) { - warn "No max barcode ($self->autoBarcode format) found. Using initial value."; - return $self->initial; - } - my ($head,$incr,$tail) = $self->parse($max); # for incremental, you'd get ('',the_whole_barcode,'') - unless (defined $incr) { - warn "No incrementing part of barcode ($max) returned by parse."; - return; - } - my $x = length($incr); # number of digits - $incr =~ /^9+$/ and $x++; # if they're all 9's, we need an extra. - # Note, this enlargement might be undesirable for some barcode formats. - # Those should override next_value() to work accordingly. - $incr++; - $head = $self->process_head($head,$max,$specific); - $tail = $self->process_tail($tail,$incr,$specific); # XXX use $incr and not $max! - my $next_value = $head . $incr . $tail; - return $next_value; +sub next_value { + my $self = shift; + my $specific = ( scalar @_ ) ? 1 : 0; + my $max = $specific ? shift : $self->max; # optional argument, i.e. next_value after X + unless ($max) { + warn "No max barcode ($self->autoBarcode format) found. Using initial value."; + return $self->initial; + } + my ( $head, $incr, $tail ) = $self->parse($max); # for incremental, you'd get ('',the_whole_barcode,'') + unless ( defined $incr ) { + warn "No incrementing part of barcode ($max) returned by parse."; + return; + } + my $x = length($incr); # number of digits + $incr =~ /^9+$/ and $x++; # if they're all 9's, we need an extra. + # Note, this enlargement might be undesirable for some barcode formats. + # Those should override next_value() to work accordingly. + $incr++; + + $head = $self->process_head( $head, $max, $specific ); + $tail = $self->process_tail( $tail, $incr, $specific ); # XXX use $incr and not $max! + my $next_value = $head . $incr . $tail; + return $next_value; } + sub next { - my $self = shift or return; - (@_) and $self->{next} = shift; - return $self->{next}; + my $self = shift or return; + (@_) and $self->{next} = shift; + return $self->{next}; } + sub previous { - my $self = shift or return; - (@_) and $self->{previous} = shift; - return $self->{previous}; + my $self = shift or return; + (@_) and $self->{previous} = shift; + return $self->{previous}; } + sub serial { - my $self = shift or return; - (@_) and $self->{serial} = shift; - return $self->{serial}; + my $self = shift or return; + (@_) and $self->{serial} = shift; + return $self->{serial}; } + sub default_self { - (@_) or carp "default_self called with no argument. Reverting to _prefformat."; - my $autoBarcode = (@_) ? shift : _prefformat; - $autoBarcode =~ s/^.*:://; # in case we get C4::Barcodes::incremental, we just want 'incremental' - return { - is_max => 0, - autoBarcode => $autoBarcode, - value => undef, - previous => undef, - 'next' => undef, - serial => 1 - }; + (@_) or carp "default_self called with no argument. Reverting to _prefformat."; + my $autoBarcode = (@_) ? shift : _prefformat; + $autoBarcode =~ s/^.*:://; # in case we get C4::Barcodes::incremental, we just want 'incremental' + return { + is_max => 0, + autoBarcode => $autoBarcode, + value => undef, + previous => undef, + 'next' => undef, + serial => 1 + }; } our $types = { - annual => sub {C4::Barcodes::annual->new_object(@_); }, - incremental => sub {C4::Barcodes::incremental->new_object(@_);}, - hbyymmincr => sub {C4::Barcodes::hbyymmincr->new_object(@_); }, - OFF => sub {C4::Barcodes::OFF->new_object(@_); }, - EAN13 => sub {C4::Barcodes::EAN13->new_object(@_); }, + annual => sub { C4::Barcodes::annual->new_object(@_); }, + incremental => sub { C4::Barcodes::incremental->new_object(@_); }, + hbyymmincr => sub { C4::Barcodes::hbyymmincr->new_object(@_); }, + OFF => sub { C4::Barcodes::OFF->new_object(@_); }, + EAN13 => sub { C4::Barcodes::EAN13->new_object(@_); }, }; sub new { - my $class_or_object = shift; - my $type = ref($class_or_object) || $class_or_object; - my $from_obj = ref($class_or_object) ? 1 : 0; # are we building off another Barcodes object? - my $autoBarcodeType = (@_) ? shift : $from_obj ? $class_or_object->autoBarcode : _prefformat; - $autoBarcodeType =~ s/^.*:://; # in case we get C4::Barcodes::incremental, we just want 'incremental' - unless ($autoBarcodeType) { - carp "No autoBarcode format found."; - return; - } - unless (defined $types->{$autoBarcodeType}) { - carp "The autoBarcode format '$autoBarcodeType' is unrecognized."; - return; - } - my $self; - if ($autoBarcodeType eq 'OFF') { - $self = $class_or_object->default_self($autoBarcodeType); - return bless $self, $class_or_object; - } elsif ($from_obj) { - $class_or_object->autoBarcode eq $autoBarcodeType - or carp "Cannot create Barcodes object (type '$autoBarcodeType') from " . $class_or_object->autoBarcode . " object!"; - $self = $class_or_object->new_object(@_); - $self->serial($class_or_object->serial + 1); - if ($class_or_object->is_max) { - $self->previous($class_or_object); - $class_or_object->next($self); - $self->value($self->next_value($class_or_object->value)); - $self->is_max(1) and $class_or_object->is_max(0); # new object is max, old object is no longer max - } else { - $self->value($self->next_value); - } - } else { - $self = &{$types->{$autoBarcodeType}} (@_); - $self->value($self->next_value) and $self->is_max(1); - $self->serial(1); - } - if ($self) { - return $self; - } - carp "Failed new C4::Barcodes::$autoBarcodeType"; - return; + my $class_or_object = shift; + my $type = ref($class_or_object) || $class_or_object; + my $from_obj = ref($class_or_object) ? 1 : 0; # are we building off another Barcodes object? + my $autoBarcodeType = (@_) ? shift : $from_obj ? $class_or_object->autoBarcode : _prefformat; + $autoBarcodeType =~ s/^.*:://; # in case we get C4::Barcodes::incremental, we just want 'incremental' + unless ($autoBarcodeType) { + carp "No autoBarcode format found."; + return; + } + unless ( defined $types->{$autoBarcodeType} ) { + carp "The autoBarcode format '$autoBarcodeType' is unrecognized."; + return; + } + my $self; + if ( $autoBarcodeType eq 'OFF' ) { + $self = $class_or_object->default_self($autoBarcodeType); + return bless $self, $class_or_object; + } elsif ($from_obj) { + $class_or_object->autoBarcode eq $autoBarcodeType + or carp "Cannot create Barcodes object (type '$autoBarcodeType') from " + . $class_or_object->autoBarcode + . " object!"; + $self = $class_or_object->new_object(@_); + $self->serial( $class_or_object->serial + 1 ); + if ( $class_or_object->is_max ) { + $self->previous($class_or_object); + $class_or_object->next($self); + $self->value( $self->next_value( $class_or_object->value ) ); + $self->is_max(1) and $class_or_object->is_max(0); # new object is max, old object is no longer max + } else { + $self->value( $self->next_value ); + } + } else { + $self = &{ $types->{$autoBarcodeType} }(@_); + $self->value( $self->next_value ) and $self->is_max(1); + $self->serial(1); + } + if ($self) { + return $self; + } + carp "Failed new C4::Barcodes::$autoBarcodeType"; + return; } sub new_object { - my $class_or_object = shift; - my $type = ref($class_or_object) || $class_or_object; - my $from_obj = ref($class_or_object) ? 1 : 0; # are we building off another Barcodes object? - my $self = $class_or_object->default_self($from_obj ? $class_or_object->autoBarcode : 'incremental'); - bless $self, $type; - return $self; + my $class_or_object = shift; + my $type = ref($class_or_object) || $class_or_object; + my $from_obj = ref($class_or_object) ? 1 : 0; # are we building off another Barcodes object? + my $self = $class_or_object->default_self( $from_obj ? $class_or_object->autoBarcode : 'incremental' ); + bless $self, $type; + return $self; } 1; __END__ diff --git a/C4/Barcodes/EAN13.pm b/C4/Barcodes/EAN13.pm index 7927d19536..9b68fb95b2 100644 --- a/C4/Barcodes/EAN13.pm +++ b/C4/Barcodes/EAN13.pm @@ -23,7 +23,7 @@ use warnings; use C4::Context; use Algorithm::CheckDigits qw( CheckDigits ); -use Carp qw( carp ); +use Carp qw( carp ); use vars qw(@ISA); @@ -32,9 +32,9 @@ BEGIN { } sub parse { - my $self = shift; + my $self = shift; my $barcode = (@_) ? shift : $self->value; - my $ean = CheckDigits('ean'); + my $ean = CheckDigits('ean'); if ( $ean->is_valid($barcode) ) { return ( '', $ean->basenumber($barcode), $ean->checkdigit($barcode) ); } else { @@ -44,8 +44,8 @@ sub parse { } sub process_tail { - my ( $self,$tail,$whole,$specific ) = @_; - my $ean = CheckDigits('ean'); + my ( $self, $tail, $whole, $specific ) = @_; + my $ean = CheckDigits('ean'); my $full = $ean->complete($whole); my $chk = $ean->checkdigit($full); return $chk; diff --git a/C4/Barcodes/ValueBuilder.pm b/C4/Barcodes/ValueBuilder.pm index 8e861193ee..b4684103bf 100644 --- a/C4/Barcodes/ValueBuilder.pm +++ b/C4/Barcodes/ValueBuilder.pm @@ -25,11 +25,12 @@ use C4::Context; sub get_barcode { my ($args) = @_; my $nextnum; + # not the best, two catalogers could add the same barcode easily this way :/ my $query = "select max(cast(barcode as unsigned)) from items"; - my $sth = C4::Context->dbh->prepare($query); + my $sth = C4::Context->dbh->prepare($query); $sth->execute(); - while (my ($count)= $sth->fetchrow_array) { + while ( my ($count) = $sth->fetchrow_array ) { $nextnum = $count; } $nextnum++; @@ -42,19 +43,19 @@ package C4::Barcodes::ValueBuilder::hbyymmincr; use C4::Context; sub get_barcode { - my ($args) = @_; + my ($args) = @_; my $nextnum = 0; - my $year = substr($args->{year}, -2); - my $month = $args->{mon}; - my $query = "SELECT MAX(CAST(SUBSTRING(barcode,-4) AS signed)) AS number FROM items WHERE barcode REGEXP ?"; - my $sth = C4::Context->dbh->prepare($query); + my $year = substr( $args->{year}, -2 ); + my $month = $args->{mon}; + my $query = "SELECT MAX(CAST(SUBSTRING(barcode,-4) AS signed)) AS number FROM items WHERE barcode REGEXP ?"; + my $sth = C4::Context->dbh->prepare($query); $sth->execute("^[-a-zA-Z]{1,}$year$month"); - while (my ($count)= $sth->fetchrow_array) { + while ( my ($count) = $sth->fetchrow_array ) { $nextnum = $count if $count; - $nextnum = 0 if $nextnum == 9999; # this sequence only allows for cataloging 9999 items per month + $nextnum = 0 if $nextnum == 9999; # this sequence only allows for cataloging 9999 items per month } $nextnum++; - $nextnum = sprintf("%0*d", "4",$nextnum); + $nextnum = sprintf( "%0*d", "4", $nextnum ); $nextnum = $year . $month . $nextnum; my $scr = qq~ let elt = \$("#"+id); @@ -73,7 +74,6 @@ sub get_barcode { return $nextnum, $scr; } - package C4::Barcodes::ValueBuilder::annual; use C4::Context; @@ -81,20 +81,19 @@ sub get_barcode { my ($args) = @_; my $nextnum; my $query = "select max(cast( substring_index(barcode, '-',-1) as signed)) from items where barcode like ?"; - my $sth=C4::Context->dbh->prepare($query); - $sth->execute($args->{year} . '-%'); - while (my ($count)= $sth->fetchrow_array) { + my $sth = C4::Context->dbh->prepare($query); + $sth->execute( $args->{year} . '-%' ); + while ( my ($count) = $sth->fetchrow_array ) { $nextnum = $count if $count; } $nextnum++; - $nextnum = sprintf("%0*d", "4",$nextnum); + $nextnum = sprintf( "%0*d", "4", $nextnum ); $nextnum = "$args->{year}-$nextnum"; return $nextnum; } 1; - =head1 Barcodes::ValueBuilder This module is intended as a shim to ease the eventual transition from diff --git a/C4/Barcodes/annual.pm b/C4/Barcodes/annual.pm index 215b3d840c..ea7443c0d5 100644 --- a/C4/Barcodes/annual.pm +++ b/C4/Barcodes/annual.pm @@ -31,62 +31,71 @@ use vars qw(@ISA); use vars qw($width); BEGIN { - @ISA = qw(C4::Barcodes); - $width = 4; + @ISA = qw(C4::Barcodes); + $width = 4; } sub db_max { - my $self = shift; - my $query = "SELECT substring_index(barcode,'-',-1) AS chunk,barcode FROM items WHERE barcode LIKE ? ORDER BY chunk DESC LIMIT 1"; - # FIXME: unreasonably expensive query on large datasets (I think removal of group by does this?) - my $sth = C4::Context->dbh->prepare($query); - my ($iso); - if (@_) { - my $input = shift; - $iso = output_pref({ dt => dt_from_string( $input, 'iso' ), dateformat => 'iso', dateonly => 1 }); # try to set the date w/ 2nd arg - unless ($iso) { - warn "Failed to create 'iso' Dates object with input '$input'. Reverting to today's date."; - $iso = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 }); # failover back to today - } - } else { - $iso = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 }); - } - my $year = substr($iso,0,4); # YYYY - $sth->execute("$year-%"); - my $row = $sth->fetchrow_hashref; - return $row->{barcode}; + my $self = shift; + my $query = + "SELECT substring_index(barcode,'-',-1) AS chunk,barcode FROM items WHERE barcode LIKE ? ORDER BY chunk DESC LIMIT 1"; + + # FIXME: unreasonably expensive query on large datasets (I think removal of group by does this?) + my $sth = C4::Context->dbh->prepare($query); + my ($iso); + if (@_) { + my $input = shift; + $iso = output_pref( { dt => dt_from_string( $input, 'iso' ), dateformat => 'iso', dateonly => 1 } ) + ; # try to set the date w/ 2nd arg + unless ($iso) { + warn "Failed to create 'iso' Dates object with input '$input'. Reverting to today's date."; + $iso = output_pref( { dt => dt_from_string, dateformat => 'iso', dateonly => 1 } ); # failover back to today + } + } else { + $iso = output_pref( { dt => dt_from_string, dateformat => 'iso', dateonly => 1 } ); + } + my $year = substr( $iso, 0, 4 ); # YYYY + $sth->execute("$year-%"); + my $row = $sth->fetchrow_hashref; + return $row->{barcode}; } sub initial () { - my $self = shift; - return substr(output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 }), 0, 4 ) .'-'. sprintf('%'."$width.$width".'d', 1); + my $self = shift; + return + substr( output_pref( { dt => dt_from_string, dateformat => 'iso', dateonly => 1 } ), 0, 4 ) . '-' + . sprintf( '%' . "$width.$width" . 'd', 1 ); } sub parse { - my $self = shift; + my $self = shift; my $barcode = (@_) ? shift : $self->value; - unless ($barcode =~ /(\d{4}-)(\d+)$/) { # non-greedy match in first part - carp "Barcode '$barcode' has no incrementing part!"; - return ($barcode,undef,undef); - } - return ($1,$2,''); # the third part is in anticipation of barcodes that include checkdigits + unless ( $barcode =~ /(\d{4}-)(\d+)$/ ) { # non-greedy match in first part + carp "Barcode '$barcode' has no incrementing part!"; + return ( $barcode, undef, undef ); + } + return ( $1, $2, '' ); # the third part is in anticipation of barcodes that include checkdigits } + sub width { - my $self = shift; - (@_) and $width = shift; # hitting the class variable. - return $width; + my $self = shift; + (@_) and $width = shift; # hitting the class variable. + return $width; } + sub process_head { - my ($self,$head,$whole,$specific) = @_; - $specific and return $head; # if this is built off an existing barcode, just return the head unchanged. - return substr(output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 }), 0, 4 ) . '-'; # else get new YYYY- + my ( $self, $head, $whole, $specific ) = @_; + $specific and return $head; # if this is built off an existing barcode, just return the head unchanged. + return + substr( output_pref( { dt => dt_from_string, dateformat => 'iso', dateonly => 1 } ), 0, 4 ) + . '-'; # else get new YYYY- } sub new_object { - my $class = shift; - my $type = ref($class) || $class; - my $self = $type->default_self('annual'); - return bless $self, $type; + my $class = shift; + my $type = ref($class) || $class; + my $self = $type->default_self('annual'); + return bless $self, $type; } 1; diff --git a/C4/Barcodes/hbyymmincr.pm b/C4/Barcodes/hbyymmincr.pm index 9b067864b6..72d648166d 100644 --- a/C4/Barcodes/hbyymmincr.pm +++ b/C4/Barcodes/hbyymmincr.pm @@ -26,7 +26,7 @@ use C4::Context; # FIXME We should certainly remove output_pref from here use Koha::DateUtils qw( dt_from_string output_pref ); -use constant WIDTH => 4; # FIXME: too small for sizeable or multi-branch libraries? +use constant WIDTH => 4; # FIXME: too small for sizeable or multi-branch libraries? use vars qw(@ISA); @@ -38,57 +38,61 @@ BEGIN { # increment resets yearly -fbcit sub db_max { - my $self = shift; + my $self = shift; my $width = WIDTH; - my $query = "SELECT SUBSTRING(barcode,-$width) AS chunk, barcode FROM items WHERE barcode REGEXP ? ORDER BY chunk DESC LIMIT 1"; - my $sth = C4::Context->dbh->prepare($query); - my ($iso); - if (@_) { - my $input = shift; - $iso = output_pref({ dt => dt_from_string( $input, 'iso' ), dateformat => 'iso', dateonly => 1 }); # try to set the date w/ 2nd arg - unless ($iso) { - warn "Failed to create 'iso' Dates object with input '$input'. Reverting to today's date."; - $iso = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 }); # failover back to today - } - } else { - $iso = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 }); + my $query = + "SELECT SUBSTRING(barcode,-$width) AS chunk, barcode FROM items WHERE barcode REGEXP ? ORDER BY chunk DESC LIMIT 1"; + my $sth = C4::Context->dbh->prepare($query); + my ($iso); + if (@_) { + my $input = shift; + $iso = output_pref( { dt => dt_from_string( $input, 'iso' ), dateformat => 'iso', dateonly => 1 } ) + ; # try to set the date w/ 2nd arg + unless ($iso) { + warn "Failed to create 'iso' Dates object with input '$input'. Reverting to today's date."; + $iso = output_pref( { dt => dt_from_string, dateformat => 'iso', dateonly => 1 } ); # failover back to today } - my $year = substr($iso,2,2); # i.e. "08" for 2008 - my $andtwo = $width+2; - $sth->execute("^[a-zA-Z]{1,}" . $year . "[0-9]{$andtwo}"); # the extra two digits are the month. we don't care what they are, just that they are there. - unless ($sth->rows) { - warn "No existing hbyymmincr barcodes found. Reverting to initial value."; - return $self->initial; - } - my ($row) = $sth->fetchrow_hashref; - my $max = $row->{barcode}; - return ($max || 0); + } else { + $iso = output_pref( { dt => dt_from_string, dateformat => 'iso', dateonly => 1 } ); + } + my $year = substr( $iso, 2, 2 ); # i.e. "08" for 2008 + my $andtwo = $width + 2; + $sth->execute( "^[a-zA-Z]{1,}" . $year . "[0-9]{$andtwo}" ) + ; # the extra two digits are the month. we don't care what they are, just that they are there. + unless ( $sth->rows ) { + warn "No existing hbyymmincr barcodes found. Reverting to initial value."; + return $self->initial; + } + my ($row) = $sth->fetchrow_hashref; + my $max = $row->{barcode}; + return ( $max || 0 ); } sub initial { - my $self = shift; - # FIXME: populated branch? - my $iso = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 }); # like "2008-07-02" + my $self = shift; + + # FIXME: populated branch? + my $iso = output_pref( { dt => dt_from_string, dateformat => 'iso', dateonly => 1 } ); # like "2008-07-02" warn "HBYYMM Barcode was not passed a branch, default is blank" if ( $self->branch eq '' ); my $width = WIDTH; - return $self->branch . substr($iso,2,2) . substr($iso,5,2) . sprintf('%' . "$width.$width" . 'd',1); + return $self->branch . substr( $iso, 2, 2 ) . substr( $iso, 5, 2 ) . sprintf( '%' . "$width.$width" . 'd', 1 ); } -sub parse { # return 3 parts of barcode: non-incrementing, incrementing, non-incrementing - my $self = shift; - my $barcode = (@_) ? shift : $self->value; - my $branch = $self->branch; - unless ($barcode =~ /($branch\d{4})(\d+)$/) { - carp "Barcode '$barcode' has no incrementing part!"; - return ($barcode,undef,undef); - } - return ($1,$2,''); # the third part is in anticipation of barcodes that include checkdigits +sub parse { # return 3 parts of barcode: non-incrementing, incrementing, non-incrementing + my $self = shift; + my $barcode = (@_) ? shift : $self->value; + my $branch = $self->branch; + unless ( $barcode =~ /($branch\d{4})(\d+)$/ ) { + carp "Barcode '$barcode' has no incrementing part!"; + return ( $barcode, undef, undef ); + } + return ( $1, $2, '' ); # the third part is in anticipation of barcodes that include checkdigits } sub branch { - my $self = shift; - (@_) and $self->{branch} = shift; - return $self->{branch}; + my $self = shift; + (@_) and $self->{branch} = shift; + return $self->{branch}; } # Commented out (BZ 16635) @@ -98,12 +102,12 @@ sub branch { # return $width; #} -sub process_head { # (self,head,whole,specific) - my ($self,$head,$whole,$specific) = @_; - $specific and return $head; # if this is built off an existing barcode, just return the head unchanged. - $head =~ s/\d{4}$//; # else strip the old yymm - my $iso = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 }); # like "2008-07-02" - return $head . substr($iso,2,2) . substr($iso,5,2); +sub process_head { # (self,head,whole,specific) + my ( $self, $head, $whole, $specific ) = @_; + $specific and return $head; # if this is built off an existing barcode, just return the head unchanged. + $head =~ s/\d{4}$//; # else strip the old yymm + my $iso = output_pref( { dt => dt_from_string, dateformat => 'iso', dateonly => 1 } ); # like "2008-07-02" + return $head . substr( $iso, 2, 2 ) . substr( $iso, 5, 2 ); } sub new_object { @@ -112,11 +116,11 @@ sub new_object { my $type = ref($class_or_object) || $class_or_object; my $from_obj = - ref($class_or_object) - ? 1 - : 0; # are we building off another Barcodes object? + ref($class_or_object) + ? 1 + : 0; # are we building off another Barcodes object? - my $self = $class_or_object->default_self('hbyymmincr'); + my $self = $class_or_object->default_self('hbyymmincr'); bless $self, $type; $self->branch( @_ ? shift : $from_obj ? $class_or_object->branch : '' ); diff --git a/C4/Biblio.pm b/C4/Biblio.pm index 6f36813c98..21cb96741a 100644 --- a/C4/Biblio.pm +++ b/C4/Biblio.pm @@ -22,6 +22,7 @@ package C4::Biblio; use Modern::Perl; use vars qw(@ISA @EXPORT_OK); + BEGIN { require Exporter; @ISA = qw(Exporter); @@ -69,11 +70,11 @@ BEGIN { # they are useful in a few circumstances, so they are exported, # but don't use them unless you are a core developer ;-) push @EXPORT_OK, qw( - ModBiblioMarc + ModBiblioMarc ); } -use Carp qw( carp ); +use Carp qw( carp ); use Try::Tiny qw( catch try ); use Encode; @@ -81,14 +82,14 @@ use List::MoreUtils qw( uniq ); use MARC::Record; use MARC::File::USMARC; use MARC::File::XML; -use POSIX qw( strftime ); +use POSIX qw( strftime ); use Module::Load::Conditional qw( can_load ); use C4::Koha; use C4::Log qw( logaction ); # logaction use C4::Budgets; use C4::ClassSource qw( GetClassSort GetClassSource ); -use C4::Charset qw( +use C4::Charset qw( nsb_clean SetMarcUnicodeFlag SetUTF8Flag @@ -395,7 +396,7 @@ sub ModBiblio { ) }; - if (!$record) { + if ( !$record ) { carp 'No record passed to ModBiblio'; return 0; } @@ -420,9 +421,10 @@ sub ModBiblio { # Cleaning up invalid fields must be done early or SetUTF8Flag is liable to # throw an exception which probably won't be handled. - foreach my $field ($record->fields()) { - if (! $field->is_control_field()) { - if (scalar($field->subfields()) == 0 || (scalar($field->subfields()) == 1 && $field->subfield('9'))) { + foreach my $field ( $record->fields() ) { + if ( !$field->is_control_field() ) { + if ( scalar( $field->subfields() ) == 0 || ( scalar( $field->subfields() ) == 1 && $field->subfield('9') ) ) + { $record->delete_field($field); } } @@ -431,9 +433,9 @@ sub ModBiblio { SetUTF8Flag($record); my $dbh = C4::Context->dbh; - $frameworkcode = "" if !$frameworkcode || $frameworkcode eq "Default"; # XXX + $frameworkcode = "" if !$frameworkcode || $frameworkcode eq "Default"; # XXX - _strip_item_fields($record, $frameworkcode); + _strip_item_fields( $record, $frameworkcode ); # apply overlay rules if ( C4::Context->preference('MARCOverlayRules') @@ -459,7 +461,7 @@ sub ModBiblio { _koha_marc_update_bib_ids( $record, $frameworkcode, $biblionumber, $biblioitemnumber ); # load the koha-table data object - my $oldbiblio = TransformMarcToKoha({ record => $record }); + my $oldbiblio = TransformMarcToKoha( { record => $record } ); # update MARC subfield that stores biblioitems.cn_sort _koha_marc_update_biblioitem_cn_sort( $record, $oldbiblio, $frameworkcode ); @@ -471,18 +473,16 @@ sub ModBiblio { _koha_modify_biblio( $dbh, $oldbiblio, $frameworkcode ); _koha_modify_biblioitem_nonmarc( $dbh, $oldbiblio ); - _after_biblio_action_hooks({ action => 'modify', biblio_id => $biblionumber }); + _after_biblio_action_hooks( { action => 'modify', biblio_id => $biblionumber } ); # update OAI-PMH sets - if(C4::Context->preference("OAI-PMH:AutoUpdateSets")) { - C4::OAI::Sets::UpdateOAISetsBiblio($biblionumber, $record); + if ( C4::Context->preference("OAI-PMH:AutoUpdateSets") ) { + C4::OAI::Sets::UpdateOAISetsBiblio( $biblionumber, $record ); } - Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue->new->enqueue( - { - biblio_ids => [ $biblionumber ] - } - ) unless $options->{skip_holds_queue} or !C4::Context->preference('RealTimeHoldsQueue'); + Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue->new->enqueue( { biblio_ids => [$biblionumber] } ) + unless $options->{skip_holds_queue} + or !C4::Context->preference('RealTimeHoldsQueue'); return 1; } @@ -497,10 +497,11 @@ MARC bib. =cut sub _strip_item_fields { - my $record = shift; + my $record = shift; my $frameworkcode = shift; + # get the items before and append them to the biblio before updating the record, atm we just have the biblio - my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField( "items.itemnumber" ); + my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber"); # delete any item fields from incoming record to avoid # duplication or incorrect data - use AddItem() or ModItem() @@ -533,13 +534,13 @@ I<$params> is a hashref containing extra parameters. Valid keys are: =cut sub DelBiblio { - my ($biblionumber, $params) = @_; + my ( $biblionumber, $params ) = @_; - my $biblio = Koha::Biblios->find( $biblionumber ); - return unless $biblio; # Should we throw an exception instead? + my $biblio = Koha::Biblios->find($biblionumber); + return unless $biblio; # Should we throw an exception instead? my $dbh = C4::Context->dbh; - my $error; # for error handling + my $error; # for error handling # First make sure this biblio has no items attached my $sth = $dbh->prepare("SELECT itemnumber FROM items WHERE biblionumber=?"); @@ -565,12 +566,13 @@ sub DelBiblio { # We update any existing orders my $orders = $biblio->orders; - $orders->update({ deleted_biblionumber => $biblionumber}, { no_triggers => 1 }); - # Update related ILL requests - $biblio->ill_requests->update({ deleted_biblio_id => $biblio->id, biblio_id => undef }); + $orders->update( { deleted_biblionumber => $biblionumber }, { no_triggers => 1 } ); - unless ( $params->{skip_record_index} ){ - my $indexer = Koha::SearchEngine::Indexer->new({ index => $Koha::SearchEngine::BIBLIOS_INDEX }); + # Update related ILL requests + $biblio->ill_requests->update( { deleted_biblio_id => $biblio->id, biblio_id => undef } ); + + unless ( $params->{skip_record_index} ) { + my $indexer = Koha::SearchEngine::Indexer->new( { index => $Koha::SearchEngine::BIBLIOS_INDEX } ); $indexer->index_records( $biblionumber, "recordDelete", "biblioserver" ); } @@ -584,27 +586,23 @@ sub DelBiblio { return $error if $error; } - # delete biblio from Koha tables and save in deletedbiblio # must do this *after* _koha_delete_biblioitems, otherwise # delete cascade will prevent deletedbiblioitems rows # from being generated by _koha_delete_biblioitems $error = _koha_delete_biblio( $dbh, $biblionumber ); - _after_biblio_action_hooks({ action => 'delete', biblio_id => $biblionumber }); + _after_biblio_action_hooks( { action => 'delete', biblio_id => $biblionumber } ); logaction( "CATALOGUING", "DELETE", $biblionumber, "biblio" ) if C4::Context->preference("CataloguingLog"); - Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue->new->enqueue( - { - biblio_ids => [ $biblionumber ] - } - ) unless $params->{skip_holds_queue} or !C4::Context->preference('RealTimeHoldsQueue'); + Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue->new->enqueue( { biblio_ids => [$biblionumber] } ) + unless $params->{skip_holds_queue} + or !C4::Context->preference('RealTimeHoldsQueue'); return; } - =head2 BiblioAutoLink my $headings_linked = BiblioAutoLink($record, $frameworkcode) @@ -618,16 +616,15 @@ Returns the number of headings changed sub BiblioAutoLink { my $record = shift; my $frameworkcode = shift; - my $verbose = shift; + my $verbose = shift; - if (!$record) { + if ( !$record ) { carp('Undefined record passed to BiblioAutoLink'); return 0; } my ( $num_headings_changed, %results ); - my $linker_module = - "C4::Linker::" . ( C4::Context->preference("LinkerModule") || 'Default' ); + my $linker_module = "C4::Linker::" . ( C4::Context->preference("LinkerModule") || 'Default' ); unless ( can_load( modules => { $linker_module => undef } ) ) { $linker_module = 'C4::Linker::Default'; unless ( can_load( modules => { $linker_module => undef } ) ) { @@ -635,10 +632,12 @@ sub BiblioAutoLink { } } - my $linker = $linker_module->new( - { 'options' => C4::Context->preference("LinkerOptions") } ); - my ( $headings_changed, $results ) = - LinkBibHeadingsToAuthorities( $linker, $record, $frameworkcode, C4::Context->preference("CatalogModuleRelink") || '', undef, $verbose ); + my $linker = $linker_module->new( { 'options' => C4::Context->preference("LinkerOptions") } ); + my ( $headings_changed, $results ) = LinkBibHeadingsToAuthorities( + $linker, $record, $frameworkcode, + C4::Context->preference("CatalogModuleRelink") || '', undef, $verbose + ); + # By default we probably don't want to relink things when cataloging return $headings_changed, $results; } @@ -666,14 +665,15 @@ sub LinkBibHeadingsToAuthorities { my $linker = shift; my $bib = shift; my $frameworkcode = shift; - my $allowrelink = shift; + my $allowrelink = shift; my $tagtolink = shift; - my $verbose = shift; + my $verbose = shift; my %results; my $memory_cache = Koha::Cache::Memory::Lite->get_instance(); - if (!$bib) { + + if ( !$bib ) { carp 'LinkBibHeadingsToAuthorities called on undefined bib record'; - return ( 0, {}); + return ( 0, {} ); } require C4::Heading; require C4::AuthoritiesMarc; @@ -682,7 +682,7 @@ sub LinkBibHeadingsToAuthorities { my $num_headings_changed = 0; foreach my $field ( $bib->fields() ) { if ( defined $tagtolink ) { - next unless $field->tag() == $tagtolink ; + next unless $field->tag() == $tagtolink; } my $heading = C4::Heading->new_from_field( $field, $frameworkcode ); next unless defined $heading; @@ -690,28 +690,30 @@ sub LinkBibHeadingsToAuthorities { # check existing $9 my $current_link = $field->subfield('9'); - if ( defined $current_link && (!$allowrelink || !C4::Context->preference('LinkerRelink')) ) - { + if ( defined $current_link && ( !$allowrelink || !C4::Context->preference('LinkerRelink') ) ) { $results{'linked'}->{ $heading->display_form() }++; - push(@{$results{'details'}}, { tag => $field->tag(), authid => $current_link, status => 'UNCHANGED'}) if $verbose; + push( @{ $results{'details'} }, { tag => $field->tag(), authid => $current_link, status => 'UNCHANGED' } ) + if $verbose; next; } my ( $authid, $fuzzy, $match_count ) = $linker->get_link($heading); if ($authid) { - $results{ $fuzzy ? 'fuzzy' : 'linked' } - ->{ $heading->display_form() }++; - if(defined $current_link and $current_link == $authid) { - push(@{$results{'details'}}, { tag => $field->tag(), authid => $current_link, status => 'UNCHANGED'}) if $verbose; + $results{ $fuzzy ? 'fuzzy' : 'linked' }->{ $heading->display_form() }++; + if ( defined $current_link and $current_link == $authid ) { + push( + @{ $results{'details'} }, + { tag => $field->tag(), authid => $current_link, status => 'UNCHANGED' } + ) if $verbose; next; } $field->delete_subfield( code => '9' ) if defined $current_link; $field->add_subfields( '9', $authid ); $num_headings_changed++; - push(@{$results{'details'}}, { tag => $field->tag(), authid => $authid, status => 'LOCAL_FOUND'}) if $verbose; - } - else { + push( @{ $results{'details'} }, { tag => $field->tag(), authid => $authid, status => 'LOCAL_FOUND' } ) + if $verbose; + } else { my $authority_type = $memory_cache->get_from_cache( "LinkBibHeadingsToAuthorities:AuthorityType:" . $heading->auth_type() ); unless ($authority_type) { @@ -722,17 +724,25 @@ sub LinkBibHeadingsToAuthorities { ); } if ( defined $current_link - && (!$allowrelink || C4::Context->preference('LinkerKeepStale')) ) + && ( !$allowrelink || C4::Context->preference('LinkerKeepStale') ) ) { $results{'fuzzy'}->{ $heading->display_form() }++; - push(@{$results{'details'}}, { tag => $field->tag(), authid => $current_link, status => 'UNCHANGED'}) if $verbose; - } - elsif ( C4::Context->preference('AutoCreateAuthorities') ) { + push( + @{ $results{'details'} }, + { tag => $field->tag(), authid => $current_link, status => 'UNCHANGED' } + ) if $verbose; + } elsif ( C4::Context->preference('AutoCreateAuthorities') ) { if ( _check_valid_auth_link( $current_link, $field ) ) { $results{'linked'}->{ $heading->display_form() }++; } elsif ( $match_count > 1 ) { $results{'unlinked'}->{ $heading->display_form() }++; - push(@{$results{'details'}}, { tag => $field->tag(), authid => undef, status => 'MULTIPLE_MATCH', auth_type => $heading->auth_type(), tag_to_report => $authority_type->auth_tag_to_report}) if $verbose; + push( + @{ $results{'details'} }, + { + tag => $field->tag(), authid => undef, status => 'MULTIPLE_MATCH', + auth_type => $heading->auth_type(), tag_to_report => $authority_type->auth_tag_to_report + } + ) if $verbose; } elsif ( !$match_count ) { my $marcrecordauth = MARC::Record->new(); if ( C4::Context->preference('marcflavour') eq 'MARC21' ) { @@ -740,31 +750,31 @@ sub LinkBibHeadingsToAuthorities { SetMarcUnicodeFlag( $marcrecordauth, 'MARC21' ); } $field->delete_subfield( code => '9' ) - if defined $current_link; + if defined $current_link; my @auth_subfields; - foreach my $subfield ( $field->subfields() ){ + foreach my $subfield ( $field->subfields() ) { if ( $subfield->[0] =~ /[A-z]/ - && C4::Heading::valid_heading_subfield( - $field->tag, $subfield->[0] ) - ){ + && C4::Heading::valid_heading_subfield( $field->tag, $subfield->[0] ) ) + { push @auth_subfields, $subfield->[0] => $subfield->[1]; } } + # Bib headings contain some ending punctuation that should NOT # be included in the authority record. Strip those before creation - next unless @auth_subfields; # Don't try to create a record if we have no fields; + next unless @auth_subfields; # Don't try to create a record if we have no fields; my $last_sub = pop @auth_subfields; $last_sub =~ s/[\s]*[,.:=;!%\/][\s]*$//; push @auth_subfields, $last_sub; my $authfield = MARC::Field->new( $authority_type->auth_tag_to_report, '', '', @auth_subfields ); $marcrecordauth->insert_fields_ordered($authfield); -# bug 2317: ensure new authority knows it's using UTF-8; currently -# only need to do this for MARC21, as MARC::Record->as_xml_record() handles -# automatically for UNIMARC (by not transcoding) -# FIXME: AddAuthority() instead should simply explicitly require that the MARC::Record -# use UTF-8, but as of 2008-08-05, did not want to introduce that kind -# of change to a core API just before the 3.0 release. + # bug 2317: ensure new authority knows it's using UTF-8; currently + # only need to do this for MARC21, as MARC::Record->as_xml_record() handles + # automatically for UNIMARC (by not transcoding) + # FIXME: AddAuthority() instead should simply explicitly require that the MARC::Record + # use UTF-8, but as of 2008-08-05, did not want to introduce that kind + # of change to a core API just before the 3.0 release. if ( C4::Context->preference('marcflavour') eq 'MARC21' ) { my $userenv = C4::Context->userenv; @@ -778,57 +788,72 @@ sub LinkBibHeadingsToAuthorities { 'a' => C4::Context->preference('GenerateAuthorityField667') ) ); - my $cite = - $bib->author() . ", " - . $bib->title_proper() . ", " - . $bib->publication_date() . " "; + my $cite = $bib->author() . ", " . $bib->title_proper() . ", " . $bib->publication_date() . " "; $cite =~ s/^[\s\,]*//; $cite =~ s/[\s\,]*$//; $cite = C4::Context->preference('GenerateAuthorityField670') . ": (" - . ( $library ? $library->get_effective_marcorgcode : C4::Context->preference('MARCOrgCode') ) . ")" - . $bib->subfield( '999', 'c' ) . ": " - . $cite; - $marcrecordauth->insert_fields_ordered( - MARC::Field->new( '670', '', '', 'a' => $cite ) ); + . ( + $library ? $library->get_effective_marcorgcode : C4::Context->preference('MARCOrgCode') ) + . ")" + . $bib->subfield( '999', 'c' ) . ": " + . $cite; + $marcrecordauth->insert_fields_ordered( MARC::Field->new( '670', '', '', 'a' => $cite ) ); } - # warn "AUTH RECORD ADDED : ".$marcrecordauth->as_formatted; + # warn "AUTH RECORD ADDED : ".$marcrecordauth->as_formatted; - $authid = - C4::AuthoritiesMarc::AddAuthority( $marcrecordauth, '', - $heading->auth_type() ); + $authid = C4::AuthoritiesMarc::AddAuthority( + $marcrecordauth, '', + $heading->auth_type() + ); $field->add_subfields( '9', $authid ); $num_headings_changed++; - $linker->update_cache($heading, $authid); + $linker->update_cache( $heading, $authid ); $results{'added'}->{ $heading->display_form() }++; - push(@{$results{'details'}}, { tag => $field->tag(), authid => $authid, status => 'CREATED'}) if $verbose; + push( @{ $results{'details'} }, { tag => $field->tag(), authid => $authid, status => 'CREATED' } ) + if $verbose; } - } - elsif ( defined $current_link ) { + } elsif ( defined $current_link ) { if ( _check_valid_auth_link( $current_link, $field ) ) { $results{'linked'}->{ $heading->display_form() }++; - push(@{$results{'details'}}, { tag => $field->tag(), authid => $authid, status => 'UNCHANGED'}) if $verbose; - } - else { + push( @{ $results{'details'} }, { tag => $field->tag(), authid => $authid, status => 'UNCHANGED' } ) + if $verbose; + } else { $field->delete_subfield( code => '9' ); $num_headings_changed++; $results{'unlinked'}->{ $heading->display_form() }++; - push(@{$results{'details'}}, { tag => $field->tag(), authid => undef, status => 'NONE_FOUND', auth_type => $heading->auth_type(), tag_to_report => $authority_type->auth_tag_to_report}) if $verbose; + push( + @{ $results{'details'} }, + { + tag => $field->tag(), authid => undef, status => 'NONE_FOUND', + auth_type => $heading->auth_type(), tag_to_report => $authority_type->auth_tag_to_report + } + ) if $verbose; } - } - elsif ( $match_count > 1 ) { + } elsif ( $match_count > 1 ) { $results{'unlinked'}->{ $heading->display_form() }++; - push(@{$results{'details'}}, { tag => $field->tag(), authid => undef, status => 'MULTIPLE_MATCH', auth_type => $heading->auth_type(), tag_to_report => $authority_type->auth_tag_to_report}) if $verbose; - } - else { + push( + @{ $results{'details'} }, + { + tag => $field->tag(), authid => undef, status => 'MULTIPLE_MATCH', + auth_type => $heading->auth_type(), tag_to_report => $authority_type->auth_tag_to_report + } + ) if $verbose; + } else { $results{'unlinked'}->{ $heading->display_form() }++; - push(@{$results{'details'}}, { tag => $field->tag(), authid => undef, status => 'NONE_FOUND', auth_type => $heading->auth_type(), tag_to_report => $authority_type->auth_tag_to_report}) if $verbose; + push( + @{ $results{'details'} }, + { + tag => $field->tag(), authid => undef, status => 'NONE_FOUND', + auth_type => $heading->auth_type(), tag_to_report => $authority_type->auth_tag_to_report + } + ) if $verbose; } } } - push(@{$results{'details'}}, { tag => '', authid => undef, status => 'UNCHANGED'}) unless %results; + push( @{ $results{'details'} }, { tag => '', authid => undef, status => 'UNCHANGED' } ) unless %results; return $num_headings_changed, \%results; } @@ -900,17 +925,17 @@ Return the ISBD view which can be included in opac and intranet =cut sub GetISBDView { - my ( $params ) = @_; + my ($params) = @_; # Expecting record WITH items. - my $record = $params->{record}; + my $record = $params->{record}; return unless defined $record; - my $template = $params->{template} // q{}; + my $template = $params->{template} // q{}; my $sysprefname = $template eq 'opac' ? 'opacisbd' : 'isbd'; - my $framework = $params->{framework}; - my $itemtype = $framework; - my ( $holdingbrtagf, $holdingbrtagsubf ) = &GetMarcFromKohaField( "items.holdingbranch" ); + my $framework = $params->{framework}; + my $itemtype = $framework; + my ( $holdingbrtagf, $holdingbrtagsubf ) = &GetMarcFromKohaField("items.holdingbranch"); my $tagslib = GetMarcStructure( 1, $itemtype, { unsafe => 1 } ); my $ISBD = C4::Context->preference($sysprefname); @@ -922,9 +947,9 @@ sub GetISBDView { # $isbdfield= /(.?.?.?)/; $isbdfield =~ /(\d\d\d)([^\|])?\|(.*)\|(.*)\|(.*)/; - my $fieldvalue = $1 || 0; - my $subfvalue = $2 || ""; - my $textbefore = $3; + my $fieldvalue = $1 || 0; + my $subfvalue = $2 || ""; + my $textbefore = $3; my $analysestring = $4; my $textafter = $5; @@ -933,14 +958,16 @@ sub GetISBDView { if ( $fieldvalue > 0 ) { my $hasputtextbefore = 0; my @fieldslist = $record->field($fieldvalue); - @fieldslist = sort { $a->subfield($holdingbrtagsubf) cmp $b->subfield($holdingbrtagsubf) } @fieldslist if ( $fieldvalue eq $holdingbrtagf ); + @fieldslist = sort { $a->subfield($holdingbrtagsubf) cmp $b->subfield($holdingbrtagsubf) } @fieldslist + if ( $fieldvalue eq $holdingbrtagf ); # warn "ERROR IN ISBD DEFINITION at : $isbdfield" unless $fieldvalue; # warn "FV : $fieldvalue"; if ( $subfvalue ne "" ) { + # OPAC hidden subfield next - if ( ( $template eq 'opac' ) + if ( ( $template eq 'opac' ) && ( $tagslib->{$fieldvalue}->{$subfvalue}->{'hidden'} || 0 ) > 0 ); foreach my $field (@fieldslist) { foreach my $subfield ( $field->subfield($subfvalue) ) { @@ -949,9 +976,11 @@ sub GetISBDView { if ( $tag < 10 ) { } else { my $subfieldvalue = GetAuthorisedValueDesc( $tag, $subfvalue, $subfield, '', $tagslib ); - my $tagsubf = $tag . $subfvalue; + my $tagsubf = $tag . $subfvalue; $calculated =~ s/\{(.?.?.?.?)$tagsubf(.*?)\}/$1$subfieldvalue$2\{$1$tagsubf$2\}/g; - if ( $template eq "opac" ) { $calculated =~ s#/cgi-bin/koha/[^/]+/([^.]*.pl\?.*)$#opac-$1#g; } + if ( $template eq "opac" ) { + $calculated =~ s#/cgi-bin/koha/[^/]+/([^.]*.pl\?.*)$#opac-$1#g; + } # field builded, store the result if ( $calculated && !$hasputtextbefore ) { # put textbefore if not done @@ -975,14 +1004,16 @@ sub GetISBDView { } else { my @subf = $field->subfields; for my $i ( 0 .. $#subf ) { - my $valuecode = $subf[$i][1]; - my $subfieldcode = $subf[$i][0]; + my $valuecode = $subf[$i][1]; + my $subfieldcode = $subf[$i][0]; + # OPAC hidden subfield next - if ( ( $template eq 'opac' ) + if ( ( $template eq 'opac' ) && ( $tagslib->{$fieldvalue}->{$subfieldcode}->{'hidden'} || 0 ) > 0 ); - my $subfieldvalue = GetAuthorisedValueDesc( $tag, $subf[$i][0], $subf[$i][1], '', $tagslib ); - my $tagsubf = $tag . $subfieldcode; + my $subfieldvalue = + GetAuthorisedValueDesc( $tag, $subf[$i][0], $subf[$i][1], '', $tagslib ); + my $tagsubf = $tag . $subfieldcode; $calculated =~ s/ # replace all {{}} codes by the value code. \{\{$tagsubf\}\} # catch the {{actualcode}} @@ -991,7 +1022,9 @@ sub GetISBDView { /gx; $calculated =~ s/\{(.?.?.?.?)$tagsubf(.*?)\}/$1$subfieldvalue$2\{$1$tagsubf$2\}/g; - if ( $template eq "opac" ) { $calculated =~ s#/cgi-bin/koha/[^/]+/([^.]*.pl\?.*)$#opac-$1#g; } + if ( $template eq "opac" ) { + $calculated =~ s#/cgi-bin/koha/[^/]+/([^.]*.pl\?.*)$#opac-$1#g; + } } # field builded, store the result @@ -1042,7 +1075,7 @@ These different values should not be processed as valid subfields. =cut sub IsMarcStructureInternal { - my ( $subfield ) = @_; + my ($subfield) = @_; return ref $subfield ? 0 : 1; } @@ -1066,10 +1099,10 @@ sub GetMarcStructure { $frameworkcode = "" unless $frameworkcode; $forlibrarian = $forlibrarian ? 1 : 0; - my $unsafe = ($params && $params->{unsafe})? 1: 0; - my $cache = Koha::Caches->get_instance(); + my $unsafe = ( $params && $params->{unsafe} ) ? 1 : 0; + my $cache = Koha::Caches->get_instance(); my $cache_key = "MarcStructure-$forlibrarian-$frameworkcode"; - my $cached = $cache->get_from_cache($cache_key, { unsafe => $unsafe }); + my $cached = $cache->get_from_cache( $cache_key, { unsafe => $unsafe } ); return $cached if $cached; my $dbh = C4::Context->dbh; @@ -1080,28 +1113,34 @@ sub GetMarcStructure { ORDER BY tagfield" ); $sth->execute($frameworkcode); - my ( $liblibrarian, $libopac, $tag, $res, $mandatory, $repeatable, $important, $ind1_defaultvalue, $ind2_defaultvalue ); + my ( + $liblibrarian, $libopac, $tag, $res, $mandatory, $repeatable, $important, $ind1_defaultvalue, + $ind2_defaultvalue + ); - while ( ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable, $important, $ind1_defaultvalue, $ind2_defaultvalue ) = $sth->fetchrow ) { - $res->{$tag}->{lib} = ( $forlibrarian or !$libopac ) ? $liblibrarian : $libopac; - $res->{$tag}->{tab} = ""; - $res->{$tag}->{mandatory} = $mandatory; - $res->{$tag}->{important} = $important; - $res->{$tag}->{repeatable} = $repeatable; - $res->{$tag}->{ind1_defaultvalue} = $ind1_defaultvalue; - $res->{$tag}->{ind2_defaultvalue} = $ind2_defaultvalue; + while ( + ( $tag, $liblibrarian, $libopac, $mandatory, $repeatable, $important, $ind1_defaultvalue, $ind2_defaultvalue ) + = $sth->fetchrow ) + { + $res->{$tag}->{lib} = ( $forlibrarian or !$libopac ) ? $liblibrarian : $libopac; + $res->{$tag}->{tab} = ""; + $res->{$tag}->{mandatory} = $mandatory; + $res->{$tag}->{important} = $important; + $res->{$tag}->{repeatable} = $repeatable; + $res->{$tag}->{ind1_defaultvalue} = $ind1_defaultvalue; + $res->{$tag}->{ind2_defaultvalue} = $ind2_defaultvalue; } my $mss = Koha::MarcSubfieldStructures->search( { frameworkcode => $frameworkcode } )->unblessed; for my $m (@$mss) { $res->{ $m->{tagfield} }->{ $m->{tagsubfield} } = { - lib => ( $forlibrarian or !$m->{libopac} ) ? $m->{liblibrarian} : $m->{libopac}, + lib => ( $forlibrarian or !$m->{libopac} ) ? $m->{liblibrarian} : $m->{libopac}, subfield => $m->{tagsubfield}, %$m }; } - $cache->set_in_cache($cache_key, $res); + $cache->set_in_cache( $cache_key, $res ); return $res; } @@ -1121,7 +1160,7 @@ C<$frameworkcode> is the framework code. sub GetUsedMarcStructure { my $frameworkcode = shift || ''; - my $query = q{ + my $query = q{ SELECT * FROM marc_subfield_structure WHERE tab > -1 @@ -1180,23 +1219,27 @@ sub GetMarcSubfieldStructure { my $cache = Koha::Caches->get_instance(); my $cache_key = "MarcSubfieldStructure-$frameworkcode"; - my $cached = $cache->get_from_cache($cache_key, { unsafe => ($params && $params->{unsafe}) }); + my $cached = $cache->get_from_cache( $cache_key, { unsafe => ( $params && $params->{unsafe} ) } ); return $cached if $cached; my $dbh = C4::Context->dbh; + # We moved to selectall_arrayref since selectall_hashref does not # keep duplicate mappings on kohafield (like place in 260 vs 264) - my $subfield_aref = $dbh->selectall_arrayref( q| + my $subfield_aref = $dbh->selectall_arrayref( + q| SELECT * FROM marc_subfield_structure WHERE frameworkcode = ? AND kohafield > '' ORDER BY frameworkcode, tagfield, display_order, tagsubfield - |, { Slice => {} }, $frameworkcode ); + |, { Slice => {} }, $frameworkcode + ); + # Now map the output to a hash structure my $subfield_structure = {}; - foreach my $row ( @$subfield_aref ) { - push @{ $subfield_structure->{ $row->{kohafield} }}, $row; + foreach my $row (@$subfield_aref) { + push @{ $subfield_structure->{ $row->{kohafield} } }, $row; } $cache->set_in_cache( $cache_key, $subfield_structure ); return $subfield_structure; @@ -1225,9 +1268,9 @@ sub GetMarcFromKohaField { # The next call uses the Default framework since it is AUTHORITATIVE # for all Koha to MARC mappings. - my $mss = GetMarcSubfieldStructure( '', { unsafe => 1 } ); # Do not change framework + my $mss = GetMarcSubfieldStructure( '', { unsafe => 1 } ); # Do not change framework my @retval; - foreach( @{ $mss->{$kohafield} } ) { + foreach ( @{ $mss->{$kohafield} } ) { push @retval, $_->{tagfield}, $_->{tagsubfield}; } return @retval; @@ -1250,13 +1293,13 @@ sub GetMarcFromKohaField { =cut sub GetMarcSubfieldStructureFromKohaField { - my ( $kohafield ) = @_; + my ($kohafield) = @_; return unless $kohafield; # The next call uses the Default framework since it is AUTHORITATIVE # for all Koha to MARC mappings. - my $mss = GetMarcSubfieldStructure( '', { unsafe => 1 } ); # Do not change framework + my $mss = GetMarcSubfieldStructure( '', { unsafe => 1 } ); # Do not change framework return $mss->{$kohafield} // []; } @@ -1297,32 +1340,33 @@ an unrecognized marc format sub GetMarcPrice { my ( $record, $marcflavour ) = @_; - if (!$record) { + if ( !$record ) { carp 'GetMarcPrice called on undefined record'; return; } my @listtags; my $subfield; - + if ( $marcflavour eq "MARC21" ) { - @listtags = ('345', '020'); - $subfield="c"; + @listtags = ( '345', '020' ); + $subfield = "c"; } elsif ( $marcflavour eq "UNIMARC" ) { - @listtags = ('345', '010'); - $subfield="d"; + @listtags = ( '345', '010' ); + $subfield = "d"; } else { return; } - + for my $field ( $record->field(@listtags) ) { - for my $subfield_value ($field->subfield($subfield)){ + for my $subfield_value ( $field->subfield($subfield) ) { + #check value - $subfield_value = MungeMarcPrice( $subfield_value ); + $subfield_value = MungeMarcPrice($subfield_value); return $subfield_value if ($subfield_value); } } - return 0; # no price found + return 0; # no price found } =head2 MungeMarcPrice @@ -1332,16 +1376,18 @@ Return the best guess at what the actual price is from a price field. =cut sub MungeMarcPrice { - my ( $price ) = @_; - return unless ( $price =~ m/\d/ ); ## No digits means no price. - # Look for the currency symbol and the normalized code of the active currency, if it's there, + my ($price) = @_; + return unless ( $price =~ m/\d/ ); ## No digits means no price. + # Look for the currency symbol and the normalized code of the active currency, if it's there, my $active_currency = Koha::Acquisition::Currencies->get_active; - my $symbol = $active_currency->symbol; - my $isocode = $active_currency->isocode; + my $symbol = $active_currency->symbol; + my $isocode = $active_currency->isocode; $isocode = $active_currency->currency unless defined $isocode; my $localprice; - if ( $symbol ) { - my @matches =($price=~ / + + if ($symbol) { + my @matches = ( + $price =~ / \s? ( # start of capturing parenthesis (?: @@ -1356,35 +1402,38 @@ sub MungeMarcPrice { \s?\p{L}{0,4}\s? # followed or not by a whitespace. \p{L}{0,4}\s? are for cases like '$9.50 USD' ) # end of capturing parenthesis (?:\p{P}|\z) # followed by a punctuation sign or by the end of the string - /gx); + /gx + ); - if ( @matches ) { - foreach ( @matches ) { - $localprice = $_ and last if index($_, $isocode)>=0; + if (@matches) { + foreach (@matches) { + $localprice = $_ and last if index( $_, $isocode ) >= 0; } if ( !$localprice ) { - foreach ( @matches ) { - $localprice = $_ and last if $_=~ /(^|[^\p{Sc}\p{L}\/])\Q$symbol\E([^\p{Sc}\p{L}\/]+\z|\z)/; + foreach (@matches) { + $localprice = $_ and last if $_ =~ /(^|[^\p{Sc}\p{L}\/])\Q$symbol\E([^\p{Sc}\p{L}\/]+\z|\z)/; } } } } - if ( $localprice ) { + if ($localprice) { $price = $localprice; } else { ## Grab the first number in the string ( can use commas or periods for thousands separator and/or decimal separator ) - ( $price ) = $price =~ m/([\d\,\.]+[[\,\.]\d\d]?)/; + ($price) = $price =~ m/([\d\,\.]+[[\,\.]\d\d]?)/; } + # eliminate symbol/isocode, space and any final dot from the string $price =~ s/[\p{Sc}\p{L}\/ ]|\.$//g; + # remove comma,dot when used as separators from hundreds - $price =~s/[\,\.](\d{3})/$1/g; + $price =~ s/[\,\.](\d{3})/$1/g; + # convert comma to dot to ensure correct display of decimals if existing - $price =~s/,/./; + $price =~ s/,/./; return $price; } - =head2 GetMarcQuantity return the quantity of a book. Used in acquisition only, when importing a file an iso2709 from a bookseller @@ -1398,38 +1447,39 @@ an unrecognized marc format sub GetMarcQuantity { my ( $record, $marcflavour ) = @_; - if (!$record) { + if ( !$record ) { carp 'GetMarcQuantity called on undefined record'; return; } my @listtags; my $subfield; - + if ( $marcflavour eq "MARC21" ) { - return 0 + return 0; } elsif ( $marcflavour eq "UNIMARC" ) { @listtags = ('969'); - $subfield="a"; + $subfield = "a"; } else { return; } - + for my $field ( $record->field(@listtags) ) { - for my $subfield_value ($field->subfield($subfield)){ + for my $subfield_value ( $field->subfield($subfield) ) { + #check value if ($subfield_value) { - # in France, the cents separator is the , but sometimes, ppl use a . - # in this case, the price will be x100 when unformatted ! Replace the . by a , to get a proper price calculation + + # in France, the cents separator is the , but sometimes, ppl use a . + # in this case, the price will be x100 when unformatted ! Replace the . by a , to get a proper price calculation $subfield_value =~ s/\./,/ if C4::Context->preference("CurrencyFormat") eq "FR"; return $subfield_value; } } } - return 0; # no price found + return 0; # no price found } - =head2 GetAuthorisedValueDesc my $subfieldvalue =get_authorised_value_desc( @@ -1452,7 +1502,7 @@ sub GetAuthorisedValueDesc { return q{} unless defined($value); - my $cache = Koha::Caches->get_instance(); + my $cache = Koha::Caches->get_instance(); my $cache_key; if ( !$category ) { @@ -1464,12 +1514,12 @@ sub GetAuthorisedValueDesc { my $libraries = $cache->get_from_cache( $cache_key, { unsafe => 1 } ); if ( !$libraries ) { $libraries = { - map { $_->branchcode => $_->branchname } - Koha::Libraries->search( {}, - { columns => [ 'branchcode', 'branchname' ] } ) - ->as_list + map { $_->branchcode => $_->branchname } Koha::Libraries->search( + {}, + { columns => [ 'branchcode', 'branchname' ] } + )->as_list }; - $cache->set_in_cache($cache_key, $libraries); + $cache->set_in_cache( $cache_key, $libraries ); } return $libraries->{$value}; } @@ -1481,9 +1531,7 @@ sub GetAuthorisedValueDesc { $cache_key = 'itemtype:description:' . $lang; my $itypes = $cache->get_from_cache( $cache_key, { unsafe => 1 } ); if ( !$itypes ) { - $itypes = - { map { $_->itemtype => $_->translated_description } - Koha::ItemTypes->search()->as_list }; + $itypes = { map { $_->itemtype => $_->translated_description } Koha::ItemTypes->search()->as_list }; $cache->set_in_cache( $cache_key, $itypes ); } return $itypes->{$value}; @@ -1494,12 +1542,12 @@ sub GetAuthorisedValueDesc { my $cn_sources = $cache->get_from_cache( $cache_key, { unsafe => 1 } ); if ( !$cn_sources ) { $cn_sources = { - map { $_->cn_source => $_->description } - Koha::ClassSources->search( {}, - { columns => [ 'cn_source', 'description' ] } ) - ->as_list + map { $_->cn_source => $_->description } Koha::ClassSources->search( + {}, + { columns => [ 'cn_source', 'description' ] } + )->as_list }; - $cache->set_in_cache($cache_key, $cn_sources); + $cache->set_in_cache( $cache_key, $cn_sources ); } return $cn_sources->{$value}; } @@ -1514,21 +1562,17 @@ sub GetAuthorisedValueDesc { my $av_descriptions = $cache->get_from_cache( $cache_key, { unsafe => 1 } ); if ( !$av_descriptions ) { $av_descriptions = { - map { - $_->authorised_value => - { lib => $_->lib, lib_opac => $_->lib_opac } - } Koha::AuthorisedValues->search( + map { $_->authorised_value => { lib => $_->lib, lib_opac => $_->lib_opac } } + Koha::AuthorisedValues->search( { category => $category }, - { - columns => [ 'authorised_value', 'lib_opac', 'lib' ] - } + { columns => [ 'authorised_value', 'lib_opac', 'lib' ] } )->as_list }; - $cache->set_in_cache($cache_key, $av_descriptions); + $cache->set_in_cache( $cache_key, $av_descriptions ); } return ( $opac && $av_descriptions->{$value}->{'lib_opac'} ) - ? $av_descriptions->{$value}->{'lib_opac'} - : $av_descriptions->{$value}->{'lib'}; + ? $av_descriptions->{$value}->{'lib_opac'} + : $av_descriptions->{$value}->{'lib'}; } else { return $value; # if nothing is found return the original value } @@ -1545,7 +1589,7 @@ ISBNs stored in different fields depending on MARC flavour sub GetMarcISBN { my ( $record, $marcflavour ) = @_; - if (!$record) { + if ( !$record ) { carp 'GetMarcISBN called on undefined record'; return; } @@ -1558,7 +1602,7 @@ sub GetMarcISBN { my @marcisbns; foreach my $field ( $record->field($scope) ) { - my $isbn = $field->subfield( 'a' ); + my $isbn = $field->subfield('a'); if ( $isbn && $isbn ne "" ) { push @marcisbns, $isbn; } @@ -1567,7 +1611,6 @@ sub GetMarcISBN { return \@marcisbns; } # end GetMarcISBN - =head2 GetMarcISSN $marcissnsarray = GetMarcISSN( $record, $marcflavour ); @@ -1579,21 +1622,20 @@ ISSNs are stored in different fields depending on MARC flavour sub GetMarcISSN { my ( $record, $marcflavour ) = @_; - if (!$record) { + if ( !$record ) { carp 'GetMarcISSN called on undefined record'; return; } my $scope; if ( $marcflavour eq "UNIMARC" ) { $scope = '011'; - } - else { # assume MARC21 + } else { # assume MARC21 $scope = '022'; } my @marcissns; foreach my $field ( $record->field($scope) ) { - push @marcissns, $field->subfield( 'a' ) - if ( $field->subfield( 'a' ) ne "" ); + push @marcissns, $field->subfield('a') + if ( $field->subfield('a') ne "" ); } return \@marcissns; } # end GetMarcISSN @@ -1609,28 +1651,28 @@ The subjects are stored in different fields depending on MARC flavour sub GetMarcSubjects { my ( $record, $marcflavour ) = @_; - if (!$record) { + if ( !$record ) { carp 'GetMarcSubjects called on undefined record'; return; } my ( $mintag, $maxtag, $fields_filter ); if ( $marcflavour eq "UNIMARC" ) { - $mintag = "600"; - $maxtag = "611"; + $mintag = "600"; + $maxtag = "611"; $fields_filter = '6..'; - } else { # marc21 - $mintag = "600"; - $maxtag = "699"; + } else { # marc21 + $mintag = "600"; + $maxtag = "699"; $fields_filter = '6..'; } my @marcsubjects; - my $subject_limit = C4::Context->preference("TraceCompleteSubfields") ? 'su,complete-subfield' : 'su'; + my $subject_limit = C4::Context->preference("TraceCompleteSubfields") ? 'su,complete-subfield' : 'su'; my $AuthoritySeparator = C4::Context->preference('AuthoritySeparator'); foreach my $field ( $record->field($fields_filter) ) { - next unless ($field->tag() >= $mintag && $field->tag() <= $maxtag); + next unless ( $field->tag() >= $mintag && $field->tag() <= $maxtag ); my @subfields_loop; my @subfields = $field->subfields(); my @link_loop; @@ -1641,8 +1683,8 @@ sub GetMarcSubjects { if ($subfield9) { my $linkvalue = $subfield9; $linkvalue =~ s/(\(|\))//g; - @link_loop = ( { limit => 'an', 'link' => $linkvalue } ); - $authoritylink = $linkvalue + @link_loop = ( { limit => 'an', 'link' => $linkvalue } ); + $authoritylink = $linkvalue; } # other subfields @@ -1651,6 +1693,7 @@ sub GetMarcSubjects { # don't load unimarc subfields 3,4,5 next if ( ( $marcflavour eq "UNIMARC" ) and ( $subject_subfield->[0] =~ /2|3|4|5/ ) ); + # don't load MARC21 subfields 2 (FIXME: any more subfields??) next if ( ( $marcflavour eq "MARC21" ) and ( $subject_subfield->[0] =~ /2/ ) ); @@ -1658,29 +1701,31 @@ sub GetMarcSubjects { my $value = $subject_subfield->[1]; my $linkvalue = $value; $linkvalue =~ s/(\(|\))//g; + # if no authority link, build a search query unless ($subfield9) { push @link_loop, { limit => $subject_limit, 'link' => $linkvalue, - operator => (scalar @link_loop) ? ' AND ' : undef + operator => ( scalar @link_loop ) ? ' AND ' : undef }; } my @this_link_loop = @link_loop; + # do not display $0 unless ( $code eq '0' ) { push @subfields_loop, { code => $code, value => $value, link_loop => \@this_link_loop, - separator => (scalar @subfields_loop) ? $AuthoritySeparator : '' + separator => ( scalar @subfields_loop ) ? $AuthoritySeparator : '' }; } } push @marcsubjects, { MARCSUBJECT_SUBFIELDS_LOOP => \@subfields_loop, - authoritylink => $authoritylink, + authoritylink => $authoritylink, } if $authoritylink || @subfields_loop; } @@ -1698,7 +1743,7 @@ Assumes web resources (not uncommon in MARC21 to omit resource type ind) sub GetMarcUrls { my ( $record, $marcflavour ) = @_; - if (!$record) { + if ( !$record ) { carp 'GetMarcUrls called on undefined record'; return; } @@ -1711,7 +1756,7 @@ sub GetMarcUrls { } my @urls = $field->subfield('u'); foreach my $url (@urls) { - $url =~ s/^\s+|\s+$//g; # trim + $url =~ s/^\s+|\s+$//g; # trim my $marcurl; if ( $marcflavour eq 'MARC21' ) { my $s3 = $field->subfield('3'); @@ -1735,11 +1780,11 @@ sub GetMarcUrls { notes => \@notes, }; $marcurl->{'linktext'} = $link || $s3 || C4::Context->preference('URLLinkText') || $url; - $marcurl->{'part'} = $s3 if ($link); - $marcurl->{'toc'} = 1 if ( defined($s3) && $s3 =~ /^[Tt]able/ ); + $marcurl->{'part'} = $s3 if ($link); + $marcurl->{'toc'} = 1 if ( defined($s3) && $s3 =~ /^[Tt]able/ ); } else { $marcurl->{'linktext'} = $field->subfield('2') || C4::Context->preference('URLLinkText') || $url; - $marcurl->{'MARCURL'} = $url; + $marcurl->{'MARCURL'} = $url; } push @marcurls, $marcurl; } @@ -1758,19 +1803,19 @@ The series are stored in different fields depending on MARC flavour sub GetMarcSeries { my ( $record, $marcflavour ) = @_; - if (!$record) { + if ( !$record ) { carp 'GetMarcSeries called on undefined record'; return; } my ( $mintag, $maxtag, $fields_filter ); if ( $marcflavour eq "UNIMARC" ) { - $mintag = "225"; - $maxtag = "225"; + $mintag = "225"; + $maxtag = "225"; $fields_filter = '2..'; } else { # marc21 - $mintag = "440"; - $maxtag = "490"; + $mintag = "440"; + $maxtag = "490"; $fields_filter = '4..'; } @@ -1800,8 +1845,8 @@ sub GetMarcSeries { } push @link_loop, { - 'link' => $linkvalue, - operator => (scalar @link_loop) ? ' AND ' : undef + 'link' => $linkvalue, + operator => ( scalar @link_loop ) ? ' AND ' : undef }; if ($volume_number) { @@ -1811,9 +1856,9 @@ sub GetMarcSeries { code => $code, value => $value, link_loop => \@link_loop, - separator => (scalar @subfields_loop) ? $AuthoritySeparator : '', + separator => ( scalar @subfields_loop ) ? $AuthoritySeparator : '', volumenum => $volume_number, - } + }; } } push @marcseries, { MARCSERIES_SUBFIELDS_LOOP => \@subfields_loop }; @@ -1829,15 +1874,14 @@ sub GetMarcSeries { =cut sub UpsertMarcSubfield { - my ($record, $tag, $code, $content) = @_; + my ( $record, $tag, $code, $content ) = @_; my $f = $record->field($tag); if ($f) { $f->update( $code => $content ); - } - else { - my $f = MARC::Field->new( $tag, '', '', $code => $content); - $record->insert_fields_ordered( $f ); + } else { + my $f = MARC::Field->new( $tag, '', '', $code => $content ); + $record->insert_fields_ordered($f); } } @@ -1848,16 +1892,15 @@ sub UpsertMarcSubfield { =cut sub UpsertMarcControlField { - my ($record, $tag, $content) = @_; - die "UpsertMarcControlField() \$tag '$tag' is not a control field\n" unless 0+$tag < 10; + my ( $record, $tag, $content ) = @_; + die "UpsertMarcControlField() \$tag '$tag' is not a control field\n" unless 0 + $tag < 10; my $f = $record->field($tag); if ($f) { - $f->update( $content ); - } - else { - my $f = MARC::Field->new($tag, $content); - $record->insert_fields_ordered( $f ); + $f->update($content); + } else { + my $f = MARC::Field->new( $tag, $content ); + $record->insert_fields_ordered($f); } } @@ -1876,7 +1919,8 @@ sub GetFrameworkCode { my $dbh = C4::Context->dbh; ($frameworkcode) = $dbh->selectrow_array( "SELECT frameworkcode FROM biblio WHERE biblionumber=?", - undef, $biblionumber ); + undef, $biblionumber + ); $cache->set_in_cache( $cache_key, $frameworkcode ); } return $frameworkcode; @@ -1895,7 +1939,6 @@ entry from user entry. =cut - sub TransformKohaToMarc { my ( $hash, $params ) = @_; my $record = MARC::Record->new(); @@ -1903,52 +1946,55 @@ sub TransformKohaToMarc { # In the next call we use the Default framework, since it is considered # authoritative for Koha to Marc mappings. - my $mss = GetMarcSubfieldStructure( '', { unsafe => 1 } ); # do not change framework + my $mss = GetMarcSubfieldStructure( '', { unsafe => 1 } ); # do not change framework my $tag_hr = {}; - while ( my ($kohafield, $value) = each %$hash ) { + while ( my ( $kohafield, $value ) = each %$hash ) { foreach my $fld ( @{ $mss->{$kohafield} } ) { my $tagfield = $fld->{tagfield}; my $tagsubfield = $fld->{tagsubfield}; next if !$tagfield; # BZ 21800: split value if field is repeatable. - my @values = _check_split($params, $fld, $value) - ? split(/\s?\|\s?/, $value, -1) - : ( $value ); - foreach my $value ( @values ) { + my @values = + _check_split( $params, $fld, $value ) + ? split( /\s?\|\s?/, $value, -1 ) + : ($value); + foreach my $value (@values) { next if $value eq ''; $tag_hr->{$tagfield} //= []; - push @{$tag_hr->{$tagfield}}, [($tagsubfield, $value)]; + push @{ $tag_hr->{$tagfield} }, [ ( $tagsubfield, $value ) ]; } } } - foreach my $tag (sort keys %$tag_hr) { - my @sfl = @{$tag_hr->{$tag}}; + foreach my $tag ( sort keys %$tag_hr ) { + my @sfl = @{ $tag_hr->{$tag} }; @sfl = sort { $a->[0] cmp $b->[0]; } @sfl; - @sfl = map { @{$_}; } @sfl; + @sfl = map { @{$_}; } @sfl; + # Special care for control fields: remove the subfield indication @ # and do not insert indicators. my @ind = $tag < 10 ? () : ( " ", " " ); @sfl = grep { $_ ne '@' } @sfl if $tag < 10; - $record->insert_fields_ordered( MARC::Field->new($tag, @ind, @sfl) ); + $record->insert_fields_ordered( MARC::Field->new( $tag, @ind, @sfl ) ); } return $record; } sub _check_split { -# Checks if $value must be split; may consult passed framework - my ($params, $fld, $value) = @_; - return if index($value,'|') == -1; # nothing to worry about + + # Checks if $value must be split; may consult passed framework + my ( $params, $fld, $value ) = @_; + return if index( $value, '|' ) == -1; # nothing to worry about return if $params->{no_split}; # if we did not get a specific framework, check default in $mss return $fld->{repeatable} if !$params->{framework}; # here we need to check the specific framework - my $mss = GetMarcSubfieldStructure($params->{framework}, { unsafe => 1 }); + my $mss = GetMarcSubfieldStructure( $params->{framework}, { unsafe => 1 } ); foreach my $fld2 ( @{ $mss->{ $fld->{kohafield} } } ) { - next if $fld2->{tagfield} ne $fld->{tagfield}; - next if $fld2->{tagsubfield} ne $fld->{tagsubfield}; + next if $fld2->{tagfield} ne $fld->{tagfield}; + next if $fld2->{tagsubfield} ne $fld->{tagsubfield}; return 1 if $fld2->{repeatable}; } return; @@ -1963,73 +2009,71 @@ This function returns a host field populated with data from the host record, the =cut sub PrepHostMarcField { - my ($hostbiblionumber,$hostitemnumber, $marcflavour) = @_; - $marcflavour ||="MARC21"; + my ( $hostbiblionumber, $hostitemnumber, $marcflavour ) = @_; + $marcflavour ||= "MARC21"; - my $biblio = Koha::Biblios->find($hostbiblionumber); + my $biblio = Koha::Biblios->find($hostbiblionumber); my $hostrecord = $biblio->metadata->record; - my $item = Koha::Items->find($hostitemnumber); + my $item = Koha::Items->find($hostitemnumber); - my $hostmarcfield; + my $hostmarcfield; if ( $marcflavour eq "MARC21" ) { - + #main entry my $mainentry; - if ($hostrecord->subfield('100','a')){ - $mainentry = $hostrecord->subfield('100','a'); - } elsif ($hostrecord->subfield('110','a')){ - $mainentry = $hostrecord->subfield('110','a'); + if ( $hostrecord->subfield( '100', 'a' ) ) { + $mainentry = $hostrecord->subfield( '100', 'a' ); + } elsif ( $hostrecord->subfield( '110', 'a' ) ) { + $mainentry = $hostrecord->subfield( '110', 'a' ); } else { - $mainentry = $hostrecord->subfield('111','a'); + $mainentry = $hostrecord->subfield( '111', 'a' ); } - + # qualification info my $qualinfo; - if (my $field260 = $hostrecord->field('260')){ - $qualinfo = $field260->as_string( 'abc' ); + if ( my $field260 = $hostrecord->field('260') ) { + $qualinfo = $field260->as_string('abc'); } - - #other fields - my $ed = $hostrecord->subfield('250','a'); + #other fields + my $ed = $hostrecord->subfield( '250', 'a' ); my $barcode = $item->barcode; - my $title = $hostrecord->subfield('245','a'); + my $title = $hostrecord->subfield( '245', 'a' ); # record control number, 001 with 003 and prefix my $recctrlno; - if ($hostrecord->field('001')){ + if ( $hostrecord->field('001') ) { $recctrlno = $hostrecord->field('001')->data(); - if ($hostrecord->field('003')){ - $recctrlno = '('.$hostrecord->field('003')->data().')'.$recctrlno; + if ( $hostrecord->field('003') ) { + $recctrlno = '(' . $hostrecord->field('003')->data() . ')' . $recctrlno; } } # issn/isbn - my $issn = $hostrecord->subfield('022','a'); - my $isbn = $hostrecord->subfield('020','a'); - + my $issn = $hostrecord->subfield( '022', 'a' ); + my $isbn = $hostrecord->subfield( '020', 'a' ); $hostmarcfield = MARC::Field->new( - 773, '0', '', - '0' => $hostbiblionumber, - '9' => $hostitemnumber, - 'a' => $mainentry, - 'b' => $ed, - 'd' => $qualinfo, - 'o' => $barcode, - 't' => $title, - 'w' => $recctrlno, - 'x' => $issn, - 'z' => $isbn - ); - } elsif ($marcflavour eq "UNIMARC") { + 773, '0', '', + '0' => $hostbiblionumber, + '9' => $hostitemnumber, + 'a' => $mainentry, + 'b' => $ed, + 'd' => $qualinfo, + 'o' => $barcode, + 't' => $title, + 'w' => $recctrlno, + 'x' => $issn, + 'z' => $isbn + ); + } elsif ( $marcflavour eq "UNIMARC" ) { $hostmarcfield = MARC::Field->new( 461, '', '', '0' => $hostbiblionumber, - 't' => $hostrecord->subfield('200','a'), + 't' => $hostrecord->subfield( '200', 'a' ), '9' => $hostitemnumber - ); - }; + ); + } return $hostmarcfield; } @@ -2055,13 +2099,14 @@ $auth_type contains : sub TransformHtmlToXml { my ( $tags, $subfields, $values, $indicator, $ind_tag, $auth_type ) = @_; + # NOTE: The parameter $ind_tag is NOT USED -- BZ 11247 - my ( $perm_loc_tag, $perm_loc_subfield ) = C4::Biblio::GetMarcFromKohaField( "items.permanent_location" ); + my ( $perm_loc_tag, $perm_loc_subfield ) = C4::Biblio::GetMarcFromKohaField("items.permanent_location"); my $xml = MARC::File::XML::header('UTF-8'); $xml .= "\n"; - $auth_type = C4::Context->preference('marcflavour') unless $auth_type; # FIXME auth_type must be removed + $auth_type = C4::Context->preference('marcflavour') unless $auth_type; # FIXME auth_type must be removed MARC::File::XML->default_record_format($auth_type); # in UNIMARC, field 100 contains the encoding @@ -2093,24 +2138,25 @@ sub TransformHtmlToXml { my $skip = @$values[$i] eq q{}; $skip = 0 - if $perm_loc_tag - && $perm_loc_subfield - && @$tags[$i] eq $perm_loc_tag - && @$subfields[$i] eq $perm_loc_subfield; + if $perm_loc_tag + && $perm_loc_subfield + && @$tags[$i] eq $perm_loc_tag + && @$subfields[$i] eq $perm_loc_subfield; if ( ( @$tags[$i] ne $prevtag ) ) { $close_last_tag = 0; $j++ unless ( @$tags[$i] eq "" ); - my $str = ( $indicator->[$j] // q{} ) . ' '; # extra space prevents substr outside of string warn + my $str = ( $indicator->[$j] // q{} ) . ' '; # extra space prevents substr outside of string warn my $ind1 = _default_ind_to_space( substr( $str, 0, 1 ) ); my $ind2 = _default_ind_to_space( substr( $str, 1, 1 ) ); if ( !$first ) { $xml .= "\n"; if ( ( @$tags[$i] && @$tags[$i] > 10 ) - && ( !$skip ) ) { + && ( !$skip ) ) + { $xml .= "\n"; $xml .= "@$values[$i]\n"; - $first = 0; + $first = 0; $close_last_tag = 1; } else { $first = 1; @@ -2130,7 +2176,7 @@ sub TransformHtmlToXml { } else { $xml .= "\n"; $xml .= "@$values[$i]\n"; - $first = 0; + $first = 0; $close_last_tag = 1; } } @@ -2138,11 +2184,11 @@ sub TransformHtmlToXml { } else { # @$tags[$i] eq $prevtag if ( !$skip ) { if ($first) { - my $str = ( $indicator->[$j] // q{} ) . ' '; # extra space prevents substr outside of string warn + my $str = ( $indicator->[$j] // q{} ) . ' '; # extra space prevents substr outside of string warn my $ind1 = _default_ind_to_space( substr( $str, 0, 1 ) ); my $ind2 = _default_ind_to_space( substr( $str, 1, 1 ) ); $xml .= "\n"; - $first = 0; + $first = 0; $close_last_tag = 1; } $xml .= "@$values[$i]\n"; @@ -2158,7 +2204,7 @@ sub TransformHtmlToXml { # set 50 to position 26 is biblios, 13 if authorities my $pos = 26; - $pos = 13 if $auth_type eq 'UNIMARCAUTH'; + $pos = 13 if $auth_type eq 'UNIMARCAUTH'; $string = sprintf( "%-*s", 35, $string ); substr( $string, $pos, 6, "50" ); $xml .= "\n"; @@ -2210,7 +2256,7 @@ sub _default_ind_to_space { =cut sub TransformHtmlToMarc { - my ($cgi, $isbiblio) = @_; + my ( $cgi, $isbiblio ) = @_; my @params = $cgi->multi_param(); @@ -2221,8 +2267,8 @@ sub TransformHtmlToMarc { foreach my $param_name ( keys %$cgi_params ) { if ( $param_name =~ /^tag_/ ) { my $param_value = $cgi_params->{$param_name}; - unless ( Encode::is_utf8( $param_value ) ) { - $cgi_params->{$param_name} = Encode::decode('UTF-8', $param_value ); + unless ( Encode::is_utf8($param_value) ) { + $cgi_params->{$param_name} = Encode::decode( 'UTF-8', $param_value ); } } } @@ -2230,10 +2276,11 @@ sub TransformHtmlToMarc { # creating a new record my $record = MARC::Record->new(); my @fields; - my ($biblionumbertagfield, $biblionumbertagsubfield) = (-1, -1); + my ( $biblionumbertagfield, $biblionumbertagsubfield ) = ( -1, -1 ); ( $biblionumbertagfield, $biblionumbertagsubfield ) = &GetMarcFromKohaField("biblio.biblionumber") if $isbiblio; -#FIXME This code assumes that the CGI params will be in the same order as the fields in the template; this is no absolute guarantee! - for (my $i = 0; $params[$i]; $i++ ) { # browse all CGI params + + #FIXME This code assumes that the CGI params will be in the same order as the fields in the template; this is no absolute guarantee! + for ( my $i = 0 ; $params[$i] ; $i++ ) { # browse all CGI params my $param = $params[$i]; my $newfield = 0; @@ -2242,30 +2289,34 @@ sub TransformHtmlToMarc { if ( $biblionumbertagfield < 10 ) { $newfield = MARC::Field->new( $biblionumbertagfield, scalar $cgi->param($param), ); } else { - $newfield = MARC::Field->new( $biblionumbertagfield, '', '', "$biblionumbertagsubfield" => scalar $cgi->param($param), ); + $newfield = MARC::Field->new( + $biblionumbertagfield, '', '', + "$biblionumbertagsubfield" => scalar $cgi->param($param), + ); } push @fields, $newfield if ($newfield); - } elsif ( $param =~ /^tag_(\d*)_indicator1_/ ) { # new field start when having 'input name="..._indicator1_..." + } elsif ( $param =~ /^tag_(\d*)_indicator1_/ ) { # new field start when having 'input name="..._indicator1_..." my $tag = $1; - my $ind1 = _default_ind_to_space( substr( $cgi->param($param), 0, 1 ) ); + my $ind1 = _default_ind_to_space( substr( $cgi->param($param), 0, 1 ) ); my $ind2 = _default_ind_to_space( substr( $cgi->param( $params[ $i + 1 ] ), 0, 1 ) ); $newfield = 0; my $j = $i + 2; - if ( $tag < 10 ) { # no code for theses fields - # in MARC editor, 000 contains the leader. + if ( $tag < 10 ) { # no code for theses fields + # in MARC editor, 000 contains the leader. next if $tag == $biblionumbertagfield; - my $fval= $cgi->param($params[$j+1]); + my $fval = $cgi->param( $params[ $j + 1 ] ); if ( $tag eq '000' ) { + # Force a fake leader even if not provided to avoid crashing # during decoding MARC record containing UTF-8 characters $record->leader( - length( $fval ) == 24 + length($fval) == 24 ? $fval : ' nam a22 4500' - ) - ; + ); + # between 001 and 009 (included) } elsif ( $fval ne '' ) { $fval = StripNonXmlChars($fval); #Strip out any non-XML characters like control characters @@ -2274,28 +2325,31 @@ sub TransformHtmlToMarc { # > 009, deal with subfields } else { + # browse subfields for this tag (reason for _code_ match) - while(defined $params[$j] && $params[$j] =~ /_code_/) { - last unless defined $params[$j+1]; - $j += 2 and next - if $tag == $biblionumbertagfield and - $cgi->param($params[$j]) eq $biblionumbertagsubfield; + while ( defined $params[$j] && $params[$j] =~ /_code_/ ) { + last unless defined $params[ $j + 1 ]; + $j += 2 + and next + if $tag == $biblionumbertagfield + and $cgi->param( $params[$j] ) eq $biblionumbertagsubfield; + #if next param ne subfield, then it was probably empty #try next param by incrementing j - if($params[$j+1]!~/_subfield_/) {$j++; next; } - my $fkey= $cgi->param($params[$j]); - my $fval= $cgi->param($params[$j+1]); + if ( $params[ $j + 1 ] !~ /_subfield_/ ) { $j++; next; } + my $fkey = $cgi->param( $params[$j] ); + my $fval = $cgi->param( $params[ $j + 1 ] ); + #check if subfield value not empty and field exists - if($fval ne '' && $newfield) { - $newfield->add_subfields( $fkey => $fval); - } - elsif($fval ne '') { + if ( $fval ne '' && $newfield ) { + $newfield->add_subfields( $fkey => $fval ); + } elsif ( $fval ne '' ) { $fval = StripNonXmlChars($fval); #Strip out any non-XML characters like control characters $newfield = MARC::Field->new( $tag, $ind1, $ind2, $fkey => $fval ); } $j += 2; - } #end-of-while - $i= $j-1; #update i for outer loop accordingly + } #end-of-while + $i = $j - 1; #update i for outer loop accordingly } push @fields, $newfield if ($newfield); } @@ -2319,50 +2373,50 @@ hash_ref. =cut sub TransformMarcToKoha { - my ( $params ) = @_; + my ($params) = @_; - my $record = $params->{record}; + my $record = $params->{record}; my $limit_table = $params->{limit_table} // q{}; - my $kohafields = $params->{kohafields}; + my $kohafields = $params->{kohafields}; my $result = {}; - if (!defined $record) { + if ( !defined $record ) { carp('TransformMarcToKoha called with undefined record'); return $result; } my %tables = ( biblio => 1, biblioitems => 1, items => 1 ); - if( $limit_table eq 'items' ) { + if ( $limit_table eq 'items' ) { %tables = ( items => 1 ); - } elsif ( $limit_table eq 'no_items' ){ + } elsif ( $limit_table eq 'no_items' ) { %tables = ( biblio => 1, biblioitems => 1 ); } # The next call acknowledges Default as the authoritative framework # for Koha to MARC mappings. - my $mss = GetMarcSubfieldStructure( '', { unsafe => 1 } ); # Do not change framework - @{$kohafields} = keys %{ $mss } unless $kohafields; + my $mss = GetMarcSubfieldStructure( '', { unsafe => 1 } ); # Do not change framework + @{$kohafields} = keys %{$mss} unless $kohafields; foreach my $kohafield ( @{$kohafields} ) { my ( $table, $column ) = split /[.]/, $kohafield, 2; next unless $tables{$table}; my ( $value, @values ); - foreach my $fldhash ( @{$mss->{$kohafield}} ) { + foreach my $fldhash ( @{ $mss->{$kohafield} } ) { my $tag = $fldhash->{tagfield}; my $sub = $fldhash->{tagsubfield}; foreach my $fld ( $record->field($tag) ) { - if( $sub eq '@' || $fld->is_control_field ) { + if ( $sub eq '@' || $fld->is_control_field ) { push @values, $fld->data if $fld->data; } else { push @values, grep { $_ } $fld->subfield($sub); } } } - if ( @values ){ + if (@values) { $value = join ' | ', uniq(@values); # Additional polishing for individual kohafields - if( $kohafield =~ /copyrightdate|publicationyear/ ) { - $value = _adjust_pubyear( $value ); + if ( $kohafield =~ /copyrightdate|publicationyear/ ) { + $value = _adjust_pubyear($value); } } @@ -2420,16 +2474,18 @@ sub _disambiguate { sub _adjust_pubyear { my $retval = shift; + # modify return value to keep only the 1st year found - if( $retval =~ m/c(\d\d\d\d)/ and $1 > 0 ) { # search cYYYY first + if ( $retval =~ m/c(\d\d\d\d)/ and $1 > 0 ) { # search cYYYY first $retval = $1; - } elsif( $retval =~ m/(\d\d\d\d)/ && $1 > 0 ) { + } elsif ( $retval =~ m/(\d\d\d\d)/ && $1 > 0 ) { $retval = $1; - } elsif( $retval =~ m/(?\d{1,3})[.Xx?-]/ ) { + } elsif ( $retval =~ m/(?\d{1,3})[.Xx?-]/ ) { + # See also bug 24674: enough to look at one unknown year char like .Xx-? # At this point in code 1234? or 1234- already passed the earlier regex # Things like 2-, 1xx, 1??? are now converted to a four positions-year. - $retval = $+{year} * ( 10 ** (4-length($+{year})) ); + $retval = $+{year} * ( 10**( 4 - length( $+{year} ) ) ); } else { $retval = undef; } @@ -2445,7 +2501,9 @@ sub _adjust_pubyear { sub CountItemsIssued { my ($biblionumber) = @_; my $dbh = C4::Context->dbh; - my $sth = $dbh->prepare('SELECT COUNT(*) as issuedCount FROM items, issues WHERE items.itemnumber = issues.itemnumber AND items.biblionumber = ?'); + my $sth = $dbh->prepare( + 'SELECT COUNT(*) as issuedCount FROM items, issues WHERE items.itemnumber = issues.itemnumber AND items.biblionumber = ?' + ); $sth->execute($biblionumber); my $row = $sth->fetchrow_hashref(); return $row->{'issuedCount'}; @@ -2503,26 +2561,26 @@ the MARC XML. sub _koha_marc_update_bib_ids { my ( $record, $frameworkcode, $biblionumber, $biblioitemnumber ) = @_; - my ( $biblio_tag, $biblio_subfield ) = GetMarcFromKohaField( "biblio.biblionumber" ); + my ( $biblio_tag, $biblio_subfield ) = GetMarcFromKohaField("biblio.biblionumber"); die qq{No biblionumber tag for framework "$frameworkcode"} unless $biblio_tag; - my ( $biblioitem_tag, $biblioitem_subfield ) = GetMarcFromKohaField( "biblioitems.biblioitemnumber" ); + my ( $biblioitem_tag, $biblioitem_subfield ) = GetMarcFromKohaField("biblioitems.biblioitemnumber"); die qq{No biblioitemnumber tag for framework "$frameworkcode"} unless $biblioitem_tag; if ( $biblio_tag < 10 ) { C4::Biblio::UpsertMarcControlField( $record, $biblio_tag, $biblionumber ); } else { - C4::Biblio::UpsertMarcSubfield($record, $biblio_tag, $biblio_subfield, $biblionumber); + C4::Biblio::UpsertMarcSubfield( $record, $biblio_tag, $biblio_subfield, $biblionumber ); } if ( $biblioitem_tag < 10 ) { C4::Biblio::UpsertMarcControlField( $record, $biblioitem_tag, $biblioitemnumber ); } else { - C4::Biblio::UpsertMarcSubfield($record, $biblioitem_tag, $biblioitem_subfield, $biblioitemnumber); + C4::Biblio::UpsertMarcSubfield( $record, $biblioitem_tag, $biblioitem_subfield, $biblioitemnumber ); } # update the control number (001) in MARC - if(C4::Context->preference('autoControlNumber') eq 'biblionumber'){ - unless($record->field('001')){ - $record->insert_fields_ordered(MARC::Field->new('001', $biblionumber)); + if ( C4::Context->preference('autoControlNumber') eq 'biblionumber' ) { + unless ( $record->field('001') ) { + $record->insert_fields_ordered( MARC::Field->new( '001', $biblionumber ) ); } } } @@ -2541,10 +2599,11 @@ sub _koha_marc_update_biblioitem_cn_sort { my $biblioitem = shift; my $frameworkcode = shift; - my ( $biblioitem_tag, $biblioitem_subfield ) = GetMarcFromKohaField( "biblioitems.cn_sort" ); + my ( $biblioitem_tag, $biblioitem_subfield ) = GetMarcFromKohaField("biblioitems.cn_sort"); return unless $biblioitem_tag; - my ($cn_sort) = GetClassSort( $biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} ); + my ($cn_sort) = + GetClassSort( $biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} ); if ( my $field = $marc->field($biblioitem_tag) ) { $field->delete_subfield( code => $biblioitem_subfield ); @@ -2557,7 +2616,8 @@ sub _koha_marc_update_biblioitem_cn_sort { # we'll create it if $cn_sort is not empty -- this would be # an odd combination of events, however if ($cn_sort) { - $marc->insert_grouped_field( MARC::Field->new( $biblioitem_tag, ' ', ' ', $biblioitem_subfield => $cn_sort ) ); + $marc->insert_grouped_field( + MARC::Field->new( $biblioitem_tag, ' ', ' ', $biblioitem_subfield => $cn_sort ) ); } } } @@ -2591,18 +2651,19 @@ sub _koha_modify_biblio { abstract = ? WHERE biblionumber = ? " - ; + ; my $sth = $dbh->prepare($query); $sth->execute( - $frameworkcode, $biblio->{'author'}, $biblio->{'title'}, $biblio->{'subtitle'}, - $biblio->{'medium'}, $biblio->{'part_number'}, $biblio->{'part_name'}, $biblio->{'unititle'}, - $biblio->{'notes'}, $biblio->{'serial'}, $biblio->{'seriestitle'}, $biblio->{'copyrightdate'} ? int($biblio->{'copyrightdate'}) : undef, + $frameworkcode, $biblio->{'author'}, $biblio->{'title'}, $biblio->{'subtitle'}, + $biblio->{'medium'}, $biblio->{'part_number'}, $biblio->{'part_name'}, $biblio->{'unititle'}, + $biblio->{'notes'}, $biblio->{'serial'}, $biblio->{'seriestitle'}, + $biblio->{'copyrightdate'} ? int( $biblio->{'copyrightdate'} ) : undef, $biblio->{'abstract'}, $biblio->{'biblionumber'} ) if $biblio->{'biblionumber'}; my $cache = Koha::Cache::Memory::Lite->get_instance(); - $cache->clear_from_cache("FrameworkCode-" . $biblio->{biblionumber}); + $cache->clear_from_cache( "FrameworkCode-" . $biblio->{biblionumber} ); if ( $dbh->errstr || !$biblio->{'biblionumber'} ) { $error .= "ERROR in _koha_modify_biblio $query" . $dbh->errstr; @@ -2622,7 +2683,8 @@ sub _koha_modify_biblioitem_nonmarc { my $error; # re-calculate the cn_sort, it may have changed - my ($cn_sort) = GetClassSort( $biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} ); + my ($cn_sort) = + GetClassSort( $biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, $biblioitem->{'cn_item'} ); my $query = "UPDATE biblioitems SET biblionumber = ?, @@ -2659,14 +2721,16 @@ sub _koha_modify_biblioitem_nonmarc { "; my $sth = $dbh->prepare($query); $sth->execute( - $biblioitem->{'biblionumber'}, $biblioitem->{'volume'}, $biblioitem->{'number'}, $biblioitem->{'itemtype'}, - $biblioitem->{'isbn'}, $biblioitem->{'issn'}, $biblioitem->{'publicationyear'}, $biblioitem->{'publishercode'}, - $biblioitem->{'volumedate'}, $biblioitem->{'volumedesc'}, $biblioitem->{'collectiontitle'}, $biblioitem->{'collectionissn'}, - $biblioitem->{'collectionvolume'}, $biblioitem->{'editionstatement'}, $biblioitem->{'editionresponsibility'}, $biblioitem->{'illus'}, - $biblioitem->{'pages'}, $biblioitem->{'bnotes'}, $biblioitem->{'size'}, $biblioitem->{'place'}, - $biblioitem->{'lccn'}, $biblioitem->{'url'}, $biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, - $biblioitem->{'cn_item'}, $biblioitem->{'cn_suffix'}, $cn_sort, $biblioitem->{'totalissues'}, - $biblioitem->{'ean'}, $biblioitem->{'agerestriction'}, $biblioitem->{'biblioitemnumber'} + $biblioitem->{'biblionumber'}, $biblioitem->{'volume'}, $biblioitem->{'number'}, $biblioitem->{'itemtype'}, + $biblioitem->{'isbn'}, $biblioitem->{'issn'}, $biblioitem->{'publicationyear'}, $biblioitem->{'publishercode'}, + $biblioitem->{'volumedate'}, $biblioitem->{'volumedesc'}, $biblioitem->{'collectiontitle'}, + $biblioitem->{'collectionissn'}, + $biblioitem->{'collectionvolume'}, $biblioitem->{'editionstatement'}, $biblioitem->{'editionresponsibility'}, + $biblioitem->{'illus'}, + $biblioitem->{'pages'}, $biblioitem->{'bnotes'}, $biblioitem->{'size'}, $biblioitem->{'place'}, + $biblioitem->{'lccn'}, $biblioitem->{'url'}, $biblioitem->{'biblioitems.cn_source'}, $biblioitem->{'cn_class'}, + $biblioitem->{'cn_item'}, $biblioitem->{'cn_suffix'}, $cn_sort, $biblioitem->{'totalissues'}, + $biblioitem->{'ean'}, $biblioitem->{'agerestriction'}, $biblioitem->{'biblioitemnumber'} ); if ( $dbh->errstr ) { $error .= "ERROR in _koha_modify_biblioitem_nonmarc $query" . $dbh->errstr; @@ -2715,13 +2779,14 @@ sub _koha_delete_biblio { $bkup_sth->execute(@bind); $bkup_sth->finish; - _koha_delete_biblio_metadata( $biblionumber ); + _koha_delete_biblio_metadata($biblionumber); # delete the biblio my $sth2 = $dbh->prepare("DELETE FROM biblio WHERE biblionumber=?"); $sth2->execute($biblionumber); + # update the timestamp (Bugzilla 7146) - $sth2= $dbh->prepare("UPDATE deletedbiblio SET timestamp=NOW() WHERE biblionumber=?"); + $sth2 = $dbh->prepare("UPDATE deletedbiblio SET timestamp=NOW() WHERE biblionumber=?"); $sth2->execute($biblionumber); $sth2->finish; } @@ -2769,8 +2834,9 @@ sub _koha_delete_biblioitems { # delete the biblioitem my $sth2 = $dbh->prepare("DELETE FROM biblioitems WHERE biblioitemnumber=?"); $sth2->execute($biblioitemnumber); + # update the timestamp (Bugzilla 7146) - $sth2= $dbh->prepare("UPDATE deletedbiblioitems SET timestamp=NOW() WHERE biblioitemnumber=?"); + $sth2 = $dbh->prepare("UPDATE deletedbiblioitems SET timestamp=NOW() WHERE biblioitemnumber=?"); $sth2->execute($biblioitemnumber); $sth2->finish; } @@ -2793,12 +2859,16 @@ sub _koha_delete_biblio_metadata { my $schema = Koha::Database->new->schema; $schema->txn_do( sub { - $dbh->do( q| + $dbh->do( + q| INSERT INTO deletedbiblio_metadata (biblionumber, format, `schema`, metadata) SELECT biblionumber, format, `schema`, metadata FROM biblio_metadata WHERE biblionumber=? - |, undef, $biblionumber ); - $dbh->do( q|DELETE FROM biblio_metadata WHERE biblionumber=?|, - undef, $biblionumber ); + |, undef, $biblionumber + ); + $dbh->do( + q|DELETE FROM biblio_metadata WHERE biblionumber=?|, + undef, $biblionumber + ); } ); } @@ -2826,6 +2896,7 @@ The C<$options> argument is a hashref with additional parameters: =cut sub ModBiblioMarc { + # pass the MARC::Record to this function, and it will create the records in # the marcxml field my ( $record, $biblionumber, $options ) = @_; @@ -2840,14 +2911,14 @@ sub ModBiblioMarc { # Clone record as it gets modified $record = $record->clone(); - my $dbh = C4::Context->dbh; - my @fields = $record->fields(); + my $dbh = C4::Context->dbh; + my @fields = $record->fields(); my $encoding = C4::Context->preference("marcflavour"); # deal with UNIMARC field 100 (encoding) : create it if needed & set encoding to unicode if ( $encoding eq "UNIMARC" ) { - my $defaultlanguage = C4::Context->preference("UNIMARCField100Language"); - $defaultlanguage = "fre" if (!$defaultlanguage || length($defaultlanguage) != 3); + my $defaultlanguage = C4::Context->preference("UNIMARCField100Language"); + $defaultlanguage = "fre" if ( !$defaultlanguage || length($defaultlanguage) != 3 ); my $string = $record->subfield( 100, "a" ); if ( ($string) && ( length( $record->subfield( 100, "a" ) ) == 36 ) ) { my $f100 = $record->field(100); @@ -2856,7 +2927,7 @@ sub ModBiblioMarc { $string = POSIX::strftime( "%Y%m%d", localtime ); $string =~ s/\-//g; $string = sprintf( "%-*s", 35, $string ); - substr ( $string, 22, 3, $defaultlanguage); + substr( $string, 22, 3, $defaultlanguage ); } substr( $string, 25, 3, "y50" ); unless ( $record->subfield( 100, "a" ) ) { @@ -2865,7 +2936,7 @@ sub ModBiblioMarc { } # Insert/update transaction time (005) for marc21/unimarc - if($encoding =~ /MARC21|UNIMARC/) { + if ( $encoding =~ /MARC21|UNIMARC/ ) { Koha::SimpleMARC::update_last_transaction_time( { record => $record } ); } @@ -2879,21 +2950,26 @@ sub ModBiblioMarc { format => 'marcxml', schema => C4::Context->preference('marcflavour'), }; - $record->as_usmarc; # Bug 20126/10455 This triggers field length calculation + $record->as_usmarc; # Bug 20126/10455 This triggers field length calculation - my $m_rs = Koha::Biblio::Metadatas->find($metadata) // - Koha::Biblio::Metadata->new($metadata); + my $m_rs = Koha::Biblio::Metadatas->find($metadata) // Koha::Biblio::Metadata->new($metadata); my $userenv = C4::Context->userenv; if ($userenv) { my $borrowernumber = $userenv->{number}; - my $borrowername = join ' ', map { $_ // q{} } @$userenv{qw(firstname surname)}; - unless ($m_rs->in_storage) { - Koha::Util::MARC::set_marc_field($record, C4::Context->preference('MarcFieldForCreatorId'), $borrowernumber); - Koha::Util::MARC::set_marc_field($record, C4::Context->preference('MarcFieldForCreatorName'), $borrowername); + my $borrowername = join ' ', map { $_ // q{} } @$userenv{qw(firstname surname)}; + unless ( $m_rs->in_storage ) { + Koha::Util::MARC::set_marc_field( + $record, C4::Context->preference('MarcFieldForCreatorId'), + $borrowernumber + ); + Koha::Util::MARC::set_marc_field( + $record, C4::Context->preference('MarcFieldForCreatorName'), + $borrowername + ); } - Koha::Util::MARC::set_marc_field($record, C4::Context->preference('MarcFieldForModifierId'), $borrowernumber); - Koha::Util::MARC::set_marc_field($record, C4::Context->preference('MarcFieldForModifierName'), $borrowername); + Koha::Util::MARC::set_marc_field( $record, C4::Context->preference('MarcFieldForModifierId'), $borrowernumber ); + Koha::Util::MARC::set_marc_field( $record, C4::Context->preference('MarcFieldForModifierName'), $borrowername ); } Koha::Plugins->call( @@ -2912,8 +2988,8 @@ sub ModBiblioMarc { } )->store; - unless ( $skip_record_index ) { - my $indexer = Koha::SearchEngine::Indexer->new({ index => $Koha::SearchEngine::BIBLIOS_INDEX }); + unless ($skip_record_index) { + my $indexer = Koha::SearchEngine::Indexer->new( { index => $Koha::SearchEngine::BIBLIOS_INDEX } ); $indexer->index_records( $biblionumber, "specialUpdate", "biblioserver" ); } @@ -2932,7 +3008,8 @@ sub prepare_host_field { $marcflavour ||= C4::Context->preference('marcflavour'); my $biblio = Koha::Biblios->find($hostbiblio); - my $host = $biblio->metadata->record; + my $host = $biblio->metadata->record; + # unfortunately as_string does not 'do the right thing' # if field returns undef my %sfd; @@ -2980,8 +3057,8 @@ sub prepare_host_field { } $host_field = MARC::Field->new( 773, '0', ' ', %sfd ); return $host_field; - } - elsif ( $marcflavour eq 'UNIMARC' ) { + } elsif ( $marcflavour eq 'UNIMARC' ) { + #author if ( $field = $host->field('700') || $host->field('710') || $host->field('720') ) { my $s = $field->as_string('ab'); @@ -2989,6 +3066,7 @@ sub prepare_host_field { $sfd{a} = $s; } } + #title if ( $field = $host->field('200') ) { my $s = $field->as_string('a'); @@ -2996,6 +3074,7 @@ sub prepare_host_field { $sfd{t} = $s; } } + #place of publicaton if ( $field = $host->field('210') ) { my $s = $field->as_string('a'); @@ -3003,6 +3082,7 @@ sub prepare_host_field { $sfd{c} = $s; } } + #date of publication if ( $field = $host->field('210') ) { my $s = $field->as_string('d'); @@ -3010,6 +3090,7 @@ sub prepare_host_field { $sfd{d} = $s; } } + #edition statement if ( $field = $host->field('205') ) { my $s = $field->as_string(); @@ -3017,6 +3098,7 @@ sub prepare_host_field { $sfd{e} = $s; } } + #URL if ( $field = $host->field('856') ) { my $s = $field->as_string('u'); @@ -3024,6 +3106,7 @@ sub prepare_host_field { $sfd{u} = $s; } } + #ISSN if ( $field = $host->field('011') ) { my $s = $field->as_string('a'); @@ -3031,6 +3114,7 @@ sub prepare_host_field { $sfd{x} = $s; } } + #ISBN if ( $field = $host->field('010') ) { my $s = $field->as_string('a'); @@ -3047,7 +3131,6 @@ sub prepare_host_field { return; } - =head2 UpdateTotalIssues UpdateTotalIssues($biblionumber, $increase, [$value]) @@ -3069,7 +3152,7 @@ Update the total issue count for a particular bib record. =cut sub UpdateTotalIssues { - my ($biblionumber, $increase, $value, $skip_holds_queue) = @_; + my ( $biblionumber, $increase, $value, $skip_holds_queue ) = @_; my $totalissues; my $biblio = Koha::Biblios->find($biblionumber); @@ -3088,29 +3171,31 @@ sub UpdateTotalIssues { return -1; } my $biblioitem = $biblio->biblioitem; - my ($totalissuestag, $totalissuessubfield) = GetMarcFromKohaField( 'biblioitems.totalissues' ); + my ( $totalissuestag, $totalissuessubfield ) = GetMarcFromKohaField('biblioitems.totalissues'); unless ($totalissuestag) { - return 0; # There is nothing to do + return 0; # There is nothing to do } my $current_issues = $biblioitem->totalissues // 0; - if (defined $value) { + if ( defined $value ) { $totalissues = $value; } else { $totalissues = $biblioitem->totalissues + $increase; } return 0 if $current_issues == $totalissues; # No need to update if no changes - my $field = $record->field($totalissuestag); - if (defined $field) { - $field->update( $totalissuessubfield => $totalissues ); - } else { - $field = MARC::Field->new($totalissuestag, '0', '0', - $totalissuessubfield => $totalissues); - $record->insert_grouped_field($field); - } + my $field = $record->field($totalissuestag); + if ( defined $field ) { + $field->update( $totalissuessubfield => $totalissues ); + } else { + $field = MARC::Field->new( + $totalissuestag, '0', '0', + $totalissuessubfield => $totalissues + ); + $record->insert_grouped_field($field); + } - return ModBiblio($record, $biblionumber, $biblio->frameworkcode, { skip_holds_queue => $skip_holds_queue }); + return ModBiblio( $record, $biblionumber, $biblio->frameworkcode, { skip_holds_queue => $skip_holds_queue } ); } =head2 RemoveAllNsb @@ -3123,23 +3208,23 @@ Removes all nsb/nse chars from a record sub RemoveAllNsb { my $record = shift; - if (!$record) { + if ( !$record ) { carp 'RemoveAllNsb called with undefined record'; return; } SetUTF8Flag($record); - foreach my $field ($record->fields()) { - if ($field->is_control_field()) { - $field->update(nsb_clean($field->data())); + foreach my $field ( $record->fields() ) { + if ( $field->is_control_field() ) { + $field->update( nsb_clean( $field->data() ) ); } else { my @subfields = $field->subfields(); my @new_subfields; foreach my $subfield (@subfields) { - push @new_subfields, $subfield->[0] => nsb_clean($subfield->[1]); + push @new_subfields, $subfield->[0] => nsb_clean( $subfield->[1] ); } - if (scalar(@new_subfields) > 0) { + if ( scalar(@new_subfields) > 0 ) { my $new_field; eval { $new_field = MARC::Field->new( @@ -3200,24 +3285,24 @@ fields with this field tag from C. =cut sub ApplyMarcOverlayRules { - my ($params) = @_; - my $biblionumber = $params->{biblionumber}; + my ($params) = @_; + my $biblionumber = $params->{biblionumber}; my $incoming_record = $params->{record}; - if (!$biblionumber) { + if ( !$biblionumber ) { carp 'ApplyMarcOverlayRules called on undefined biblionumber'; return; } - if (!$incoming_record) { + if ( !$incoming_record ) { carp 'ApplyMarcOverlayRules called on undefined record'; return; } - my $biblio = Koha::Biblios->find($biblionumber); + my $biblio = Koha::Biblios->find($biblionumber); my $old_record = $biblio->metadata->record; # Skip overlay rules if called with no context - if ($old_record && defined $params->{overlay_context}) { - return Koha::MarcOverlayRules->merge_records($old_record, $incoming_record, $params->{overlay_context}); + if ( $old_record && defined $params->{overlay_context} ) { + return Koha::MarcOverlayRules->merge_records( $old_record, $incoming_record, $params->{overlay_context} ); } return $incoming_record; } @@ -3243,6 +3328,7 @@ sub _after_biblio_action_hooks { biblio => $biblio, biblio_id => $biblio_id, }, + # NOTE: Deprecate these duplicate params for 24.11.00 biblio => $biblio, biblio_id => $biblio_id, diff --git a/C4/Breeding.pm b/C4/Breeding.pm index 86c5cbb588..538436d9a0 100644 --- a/C4/Breeding.pm +++ b/C4/Breeding.pm @@ -21,18 +21,19 @@ package C4::Breeding; use strict; use warnings; -use C4::Biblio qw(TransformMarcToKoha); -use C4::Koha qw( GetVariationsOfISBN ); +use C4::Biblio qw(TransformMarcToKoha); +use C4::Koha qw( GetVariationsOfISBN ); use C4::Charset qw( MarcToUTF8Record SetUTF8Flag ); use MARC::File::USMARC; use MARC::Field; -use C4::ImportBatch qw( GetZ3950BatchId AddBiblioToBatch AddAuthToBatch ); +use C4::ImportBatch qw( GetZ3950BatchId AddBiblioToBatch AddAuthToBatch ); use C4::AuthoritiesMarc qw( GuessAuthTypeCode GetAuthorizedHeading ); use C4::Languages; use Koha::Database; use Koha::XSLT::Base; -our (@ISA, @EXPORT_OK); +our ( @ISA, @EXPORT_OK ); + BEGIN { require Exporter; @ISA = qw(Exporter); @@ -67,16 +68,16 @@ C tables of the Koha database. sub BreedingSearch { my ($term) = @_; - my $dbh = C4::Context->dbh; - my $count = 0; - my ($query,@bind); + my $dbh = C4::Context->dbh; + my $count = 0; + my ( $query, @bind ); my $sth; my @results; my $authortitle = $term; - $authortitle =~ s/(\s+)/\%/g; #Replace spaces with wildcard - $authortitle = "%" . $authortitle . "%"; #Add wildcard to start and end of string - # normalise ISBN like at import + $authortitle =~ s/(\s+)/\%/g; #Replace spaces with wildcard + $authortitle = "%" . $authortitle . "%"; #Add wildcard to start and end of string + # normalise ISBN like at import my @isbns = C4::Koha::GetVariationsOfISBN($term); $query = "SELECT import_biblios.import_record_id, @@ -88,25 +89,25 @@ sub BreedingSearch { FROM import_biblios JOIN import_records USING (import_record_id) JOIN import_batches USING (import_batch_id) - WHERE title LIKE ? OR author LIKE ? OR isbn IN (" . join(',',('?') x @isbns) . ")"; - @bind=( $authortitle, $authortitle, @isbns ); - $sth = $dbh->prepare($query); + WHERE title LIKE ? OR author LIKE ? OR isbn IN (" . join( ',', ('?') x @isbns ) . ")"; + @bind = ( $authortitle, $authortitle, @isbns ); + $sth = $dbh->prepare($query); $sth->execute(@bind); - while (my $data = $sth->fetchrow_hashref) { - $results[$count] = $data; - # FIXME - hack to reflect difference in name - # of columns in old marc_breeding and import_records - # There needs to be more separation between column names and - # field names used in the templates - $data->{'file'} = $data->{'file_name'}; - $data->{'id'} = $data->{'import_record_id'}; - $count++; - } # while + while ( my $data = $sth->fetchrow_hashref ) { + $results[$count] = $data; + + # FIXME - hack to reflect difference in name + # of columns in old marc_breeding and import_records + # There needs to be more separation between column names and + # field names used in the templates + $data->{'file'} = $data->{'file_name'}; + $data->{'id'} = $data->{'import_record_id'}; + $count++; + } # while $sth->finish; - return($count, @results); -} # sub breedingsearch - + return ( $count, @results ); +} # sub breedingsearch =head2 Z3950Search @@ -120,41 +121,40 @@ The second parameter $template is a Template object. The routine uses this param =cut sub Z3950Search { - my ($pars, $template)= @_; + my ( $pars, $template ) = @_; - my @id= @{$pars->{id}}; - my $page= $pars->{page}; - my $biblionumber= $pars->{biblionumber}; + my @id = @{ $pars->{id} }; + my $page = $pars->{page}; + my $biblionumber = $pars->{biblionumber}; - my $show_next = 0; - my $total_pages = 0; + my $show_next = 0; + my $total_pages = 0; my @results; my @breeding_loop = (); my @oConnection; my @oResult; my @errconn; - my $s = 0; - my $imported=0; + my $s = 0; + my $imported = 0; - my ( $zquery, $squery ) = _bib_build_query( $pars ); + my ( $zquery, $squery ) = _bib_build_query($pars); my $schema = Koha::Database->new()->schema(); - my $rs = $schema->resultset('Z3950server')->search( - { id => [ @id ] }, + my $rs = $schema->resultset('Z3950server')->search( + { id => [@id] }, { result_class => 'DBIx::Class::ResultClass::HashRefInflator' }, ); my @servers = $rs->all; - foreach my $server ( @servers ) { + foreach my $server (@servers) { my $server_zquery = $zquery; - if(my $attributes = $server->{attributes}){ + if ( my $attributes = $server->{attributes} ) { $server_zquery = "$attributes $zquery"; } - $oConnection[$s] = _create_connection( $server ); + $oConnection[$s] = _create_connection($server); $oResult[$s] = - $server->{servertype} eq 'zed'? - $oConnection[$s]->search_pqf( $server_zquery ): - $oConnection[$s]->search(ZOOM::Query::CQL->new( - _translate_query( $server, $squery ))); + $server->{servertype} eq 'zed' + ? $oConnection[$s]->search_pqf($server_zquery) + : $oConnection[$s]->search( ZOOM::Query::CQL->new( _translate_query( $server, $squery ) ) ); $s++; } my $xslh = Koha::XSLT::Base->new; @@ -170,28 +170,40 @@ sub Z3950Search { if ( $k != 0 ) { $k--; - my ($error)= $oConnection[$k]->error_x(); #ignores errmsg, addinfo, diagset + my ($error) = $oConnection[$k]->error_x(); #ignores errmsg, addinfo, diagset if ($error) { - if ($error =~ m/^(10000|10007)$/ ) { - push(@errconn, { server => $servers[$k]->{host}, error => $error } ); + if ( $error =~ m/^(10000|10007)$/ ) { + push( @errconn, { server => $servers[$k]->{host}, error => $error } ); } - } - else { + } else { my $numresults = $oResult[$k]->size(); my $i; my $res; - if ( $numresults > 0 and $numresults >= (($page-1)*20)) { - $show_next = 1 if $numresults >= ($page*20); - $total_pages = int($numresults/20)+1 if $total_pages < ($numresults/20); - for ($i = ($page-1)*20; $i < (($numresults < ($page*20)) ? $numresults : ($page*20)); $i++) { + if ( $numresults > 0 and $numresults >= ( ( $page - 1 ) * 20 ) ) { + $show_next = 1 if $numresults >= ( $page * 20 ); + $total_pages = int( $numresults / 20 ) + 1 if $total_pages < ( $numresults / 20 ); + for ( + $i = ( $page - 1 ) * 20 ; + $i < ( ( $numresults < ( $page * 20 ) ) ? $numresults : ( $page * 20 ) ) ; + $i++ + ) + { if ( $oResult[$k]->record($i) ) { undef $error; - ( $res, $error ) = _handle_one_result( $oResult[$k]->record($i), $servers[$k], ++$imported, $biblionumber, $xslh ); #ignores error in sequence numbering + ( $res, $error ) = _handle_one_result( + $oResult[$k]->record($i), $servers[$k], ++$imported, $biblionumber, + $xslh + ); #ignores error in sequence numbering push @breeding_loop, $res if $res; - push @errconn, { server => $servers[$k]->{servername}, error => $error, seq => $i+1 } if $error; - } - else { - push @errconn, { 'server' => $servers[$k]->{servername}, error => ( ( $oConnection[$k]->error_x() )[0] ), error_msg => ( ( $oConnection[$k]->error_x() )[1] ), seq => $i+1 }; + push @errconn, { server => $servers[$k]->{servername}, error => $error, seq => $i + 1 } + if $error; + } else { + push @errconn, + { + 'server' => $servers[$k]->{servername}, + error => ( ( $oConnection[$k]->error_x() )[0] ), + error_msg => ( ( $oConnection[$k]->error_x() )[1] ), seq => $i + 1 + }; } } } #if $numresults @@ -199,42 +211,42 @@ sub Z3950Search { } # if $k !=0 $template->param( - numberpending => $nremaining, - current_page => $page, - total_pages => $total_pages, - show_nextbutton => $show_next?1:0, - show_prevbutton => $page!=1, + numberpending => $nremaining, + current_page => $page, + total_pages => $total_pages, + show_nextbutton => $show_next ? 1 : 0, + show_prevbutton => $page != 1, ); - } # while nremaining + } # while nremaining #close result sets and connections - foreach(0..$s-1) { + foreach ( 0 .. $s - 1 ) { $oResult[$_]->destroy(); $oConnection[$_]->destroy(); } $template->param( breeding_loop => \@breeding_loop, - servers => \@servers, + servers => \@servers, errconn => \@errconn ); } sub _auth_build_query { - my ( $pars ) = @_; + my ($pars) = @_; my $qry_build = { - nameany => '@attr 1=1002 "#term" ', - authorany => '@attr 1=1003 "#term" ', - authorcorp => '@attr 1=2 "#term" ', - authorpersonal => '@attr 1=1 "#term" ', - authormeetingcon => '@attr 1=3 "#term" ', - subject => '@attr 1=21 "#term" ', - subjectsubdiv => '@attr 1=47 "#term" ', - title => '@attr 1=4 "#term" ', - uniformtitle => '@attr 1=6 "#term" ', - srchany => '@attr 1=1016 "#term" ', - controlnumber => '@attr 1=12 "#term" ', + nameany => '@attr 1=1002 "#term" ', + authorany => '@attr 1=1003 "#term" ', + authorcorp => '@attr 1=2 "#term" ', + authorpersonal => '@attr 1=1 "#term" ', + authormeetingcon => '@attr 1=3 "#term" ', + subject => '@attr 1=21 "#term" ', + subjectsubdiv => '@attr 1=47 "#term" ', + title => '@attr 1=4 "#term" ', + uniformtitle => '@attr 1=6 "#term" ', + srchany => '@attr 1=1016 "#term" ', + controlnumber => '@attr 1=12 "#term" ', }; return _build_query( $pars, $qry_build ); @@ -242,20 +254,19 @@ sub _auth_build_query { sub _bib_build_query { - my ( $pars ) = @_; + my ($pars) = @_; my $qry_build = { - isbn => '@attr 1=7 @attr 5=1 "#term" ', - issn => '@attr 1=8 @attr 5=1 "#term" ', - title => '@attr 1=4 "#term" ', - author => '@attr 1=1003 "#term" ', - dewey => '@attr 1=16 "#term" ', - subject => '@attr 1=21 "#term" ', - lccall => '@attr 1=16 @attr 2=3 @attr 3=1 @attr 4=1 @attr 5=1 '. - '@attr 6=1 "#term" ', - controlnumber => '@attr 1=12 "#term" ', - srchany => '@attr 1=1016 "#term" ', - stdid => '@attr 1=1007 "#term" ', + isbn => '@attr 1=7 @attr 5=1 "#term" ', + issn => '@attr 1=8 @attr 5=1 "#term" ', + title => '@attr 1=4 "#term" ', + author => '@attr 1=1003 "#term" ', + dewey => '@attr 1=16 "#term" ', + subject => '@attr 1=21 "#term" ', + lccall => '@attr 1=16 @attr 2=3 @attr 3=1 @attr 4=1 @attr 5=1 ' . '@attr 6=1 "#term" ', + controlnumber => '@attr 1=12 "#term" ', + srchany => '@attr 1=1016 "#term" ', + stdid => '@attr 1=1007 "#term" ', publicationyear => '@attr 1=31 "#term" ' }; @@ -266,54 +277,63 @@ sub _build_query { my ( $pars, $qry_build ) = @_; - my $zquery=''; - my $squery=''; - my $nterms=0; + my $zquery = ''; + my $squery = ''; + my $nterms = 0; foreach my $k ( sort keys %$pars ) { - #note that the sort keys forces an identical result under Perl 5.18 - #one of the unit tests is based on that assumption - if( ( my $val=$pars->{$k} ) && $qry_build->{$k} ) { + + #note that the sort keys forces an identical result under Perl 5.18 + #one of the unit tests is based on that assumption + if ( ( my $val = $pars->{$k} ) && $qry_build->{$k} ) { $qry_build->{$k} =~ s/#term/$val/g; $zquery .= $qry_build->{$k}; $squery .= "[$k]=\"$val\" and "; $nterms++; } } - $zquery = "\@and " . $zquery for 2..$nterms; + $zquery = "\@and " . $zquery for 2 .. $nterms; $squery =~ s/ and $//; return ( $zquery, $squery ); } sub _handle_one_result { - my ( $zoomrec, $servhref, $seq, $bib, $xslh )= @_; + my ( $zoomrec, $servhref, $seq, $bib, $xslh ) = @_; - my $raw= $zoomrec->raw(); + my $raw = $zoomrec->raw(); my $marcrecord; - if( $servhref->{servertype} eq 'sru' ) { - $marcrecord= MARC::Record->new_from_xml( $raw, 'UTF-8', - $servhref->{syntax} ); + if ( $servhref->{servertype} eq 'sru' ) { + $marcrecord = MARC::Record->new_from_xml( + $raw, 'UTF-8', + $servhref->{syntax} + ); $marcrecord->encoding('UTF-8'); } else { - ($marcrecord) = MarcToUTF8Record($raw, C4::Context->preference('marcflavour'), $servhref->{encoding} // "iso-5426" ); #ignores charset return values + ($marcrecord) = + MarcToUTF8Record( $raw, C4::Context->preference('marcflavour'), $servhref->{encoding} // "iso-5426" ) + ; #ignores charset return values } SetUTF8Flag($marcrecord); my $error; - ( $marcrecord, $error ) = _do_xslt_proc($marcrecord, $servhref, $xslh); + ( $marcrecord, $error ) = _do_xslt_proc( $marcrecord, $servhref, $xslh ); - my $batch_id = GetZ3950BatchId($servhref->{servername}); - my $breedingid = AddBiblioToBatch($batch_id, $seq, $marcrecord, 'UTF-8', 0); - #Last zero indicates: no update for batch record counts + my $batch_id = GetZ3950BatchId( $servhref->{servername} ); + my $breedingid = AddBiblioToBatch( $batch_id, $seq, $marcrecord, 'UTF-8', 0 ); + + #Last zero indicates: no update for batch record counts my $row; - if( $breedingid ){ - my @kohafields = ('biblio.title','biblio.author','biblioitems.isbn','biblioitems.lccn','biblioitems.editionstatement'); - push @kohafields, C4::Context->preference('marcflavour') eq "MARC21" ? 'biblio.copyrightdate' : 'biblioitems.publicationyear'; - $row = C4::Biblio::TransformMarcToKoha({ record => $marcrecord, kohafields => \@kohafields, limit_table => 'no_items' }); - $row->{date} = $row->{copyrightdate} // $row->{publicationyear}; + if ($breedingid) { + my @kohafields = + ( 'biblio.title', 'biblio.author', 'biblioitems.isbn', 'biblioitems.lccn', 'biblioitems.editionstatement' ); + push @kohafields, + C4::Context->preference('marcflavour') eq "MARC21" ? 'biblio.copyrightdate' : 'biblioitems.publicationyear'; + $row = C4::Biblio::TransformMarcToKoha( + { record => $marcrecord, kohafields => \@kohafields, limit_table => 'no_items' } ); + $row->{date} = $row->{copyrightdate} // $row->{publicationyear}; $row->{biblionumber} = $bib; $row->{server} = $servhref->{servername}; $row->{breedingid} = $breedingid; - $row->{isbn}=_isbn_replace($row->{isbn}); + $row->{isbn} = _isbn_replace( $row->{isbn} ); my $pref_newtags = C4::Context->preference('AdditionalFieldsInZ3950ResultSearch'); $row = _add_custom_field_rowdata( $row, $marcrecord, $pref_newtags ); } @@ -325,27 +345,27 @@ sub _do_xslt_proc { return $marc if !$server->{add_xslt}; my $htdocs = C4::Context->config('intrahtdocs'); - my $theme = C4::Context->preference("template"); #staff - my $lang = C4::Languages::getlanguage() || 'en'; + my $theme = C4::Context->preference("template"); #staff + my $lang = C4::Languages::getlanguage() || 'en'; - my @files= split ',', $server->{add_xslt}; - my $xml = $marc->as_xml; - foreach my $f ( @files ) { - $f =~ s/^\s+//; $f =~ s/\s+$//; next if !$f; - $f = C4::XSLT::_get_best_default_xslt_filename( - $htdocs, $theme, $lang, $f ) unless $f =~ /^\//; + my @files = split ',', $server->{add_xslt}; + my $xml = $marc->as_xml; + foreach my $f (@files) { + $f =~ s/^\s+//; + $f =~ s/\s+$//; + next if !$f; + $f = C4::XSLT::_get_best_default_xslt_filename( $htdocs, $theme, $lang, $f ) unless $f =~ /^\//; $xml = $xslh->transform( $xml, $f ); - last if $xslh->err; #skip other files + last if $xslh->err; #skip other files } - if( !$xslh->err ) { - return MARC::Record->new_from_xml($xml, 'UTF-8'); + if ( !$xslh->err ) { + return MARC::Record->new_from_xml( $xml, 'UTF-8' ); } else { - return ( $marc, $xslh->err ); #original record in case of errors + return ( $marc, $xslh->err ); #original record in case of errors } } -sub _add_custom_field_rowdata -{ +sub _add_custom_field_rowdata { my ( $row, $record, $pref_newtags ) = @_; $pref_newtags //= ''; my $pref_flavour = C4::Context->preference('MarcFlavour'); @@ -355,22 +375,22 @@ sub _add_custom_field_rowdata my @addnumberfields; - foreach my $field (split /\,/, $pref_newtags) { - $field =~ s/^\s+|\s+$//g ; # trim whitespace - my ($tag, $subtags) = split(/\$/, $field); + foreach my $field ( split /\,/, $pref_newtags ) { + $field =~ s/^\s+|\s+$//g; # trim whitespace + my ( $tag, $subtags ) = split( /\$/, $field ); if ( $record->field($tag) ) { my @content = (); - for my $marcfield ($record->field($tag)) { - if ( $subtags ) { + for my $marcfield ( $record->field($tag) ) { + if ($subtags) { my $str = ''; - for my $code (split //, $subtags) { + for my $code ( split //, $subtags ) { if ( $marcfield->subfield($code) ) { $str .= $marcfield->subfield($code) . ' '; } } - if ( not $str eq '') { + if ( not $str eq '' ) { push @content, $str; } } elsif ( $tag == 10 ) { @@ -382,7 +402,7 @@ sub _add_custom_field_rowdata } } - if ( @content ) { + if (@content) { $row->{$field} = \@content; push( @addnumberfields, $field ); } @@ -404,61 +424,66 @@ sub _isbn_replace { } sub _create_connection { - my ( $server ) = @_; - my $option1= ZOOM::Options->new(); + my ($server) = @_; + my $option1 = ZOOM::Options->new(); $option1->option( 'async' => 1 ); - $option1->option( 'elementSetName', 'F' ); + $option1->option( 'elementSetName', 'F' ); $option1->option( 'preferredRecordSyntax', $server->{syntax} ); - $option1->option( 'timeout', $server->{timeout} ) if $server->{timeout}; + $option1->option( 'timeout', $server->{timeout} ) if $server->{timeout}; + + if ( $server->{servertype} eq 'sru' ) { + foreach ( split ',', $server->{sru_options} // '' ) { - if( $server->{servertype} eq 'sru' ) { - foreach( split ',', $server->{sru_options}//'' ) { #first remove surrounding spaces at comma and equals-sign s/^\s+|\s+$//g; - my @temp= split '=', $_, 2; - @temp= map { my $c=$_; $c=~s/^\s+|\s+$//g; $c; } @temp; + my @temp = split '=', $_, 2; + @temp = map { my $c = $_; $c =~ s/^\s+|\s+$//g; $c; } @temp; $option1->option( $temp[0] => $temp[1] ) if @temp; } - } elsif( $server->{servertype} eq 'zed' ) { - $option1->option( 'databaseName', $server->{db} ); - $option1->option( 'user', $server->{userid} ) if $server->{userid}; - $option1->option( 'password', $server->{password} ) if $server->{password}; + } elsif ( $server->{servertype} eq 'zed' ) { + $option1->option( 'databaseName', $server->{db} ); + $option1->option( 'user', $server->{userid} ) if $server->{userid}; + $option1->option( 'password', $server->{password} ) if $server->{password}; } - my $obj= ZOOM::Connection->create($option1); - if( $server->{servertype} eq 'sru' ) { - my $host= $server->{host}; - if( $host !~ /^https?:\/\// ) { + my $obj = ZOOM::Connection->create($option1); + if ( $server->{servertype} eq 'sru' ) { + my $host = $server->{host}; + if ( $host !~ /^https?:\/\// ) { + #Normally, host will not be prefixed by protocol. #In that case we can (safely) assume http. #In case someone prefixed with https, give it a try.. $host = 'http://' . $host; } - $obj->connect( $host.':'.$server->{port}.'/'.$server->{db} ); + $obj->connect( $host . ':' . $server->{port} . '/' . $server->{db} ); } else { $obj->connect( $server->{host}, $server->{port} ); } return $obj; } -sub _translate_query { #SRU query adjusted per server cf. srufields column - my ($server, $query) = @_; +sub _translate_query { #SRU query adjusted per server cf. srufields column + my ( $server, $query ) = @_; #sru_fields is in format title=field,isbn=field,... #if a field doesn't exist, try anywhere or remove [field]= - my @parts= split(',', $server->{sru_fields} ); - my %trans= map { if( /=/ ) { ( $`,$' ) } else { () } } @parts; - my $any= $trans{srchany}?$trans{srchany}.'=':''; + my @parts = split( ',', $server->{sru_fields} ); + my %trans = map { + if (/=/) { ( $`, $' ) } + else { () } + } @parts; + my $any = $trans{srchany} ? $trans{srchany} . '=' : ''; - my $q=$query; - foreach my $key (keys %trans) { - my $f=$trans{$key}; - if( $f ) { - $q=~s/\[$key\]/$f/g; + my $q = $query; + foreach my $key ( keys %trans ) { + my $f = $trans{$key}; + if ($f) { + $q =~ s/\[$key\]/$f/g; } else { - $q=~s/\[$key\]=/$any/g; + $q =~ s/\[$key\]=/$any/g; } } - $q=~s/\[\w+\]=/$any/g; # remove remaining fields (not found in field list) + $q =~ s/\[\w+\]=/$any/g; # remove remaining fields (not found in field list) return $q; } @@ -475,15 +500,16 @@ sub ImportBreedingAuth { my $dbh = C4::Context->dbh; my $batch_id = GetZ3950BatchId($filename); - my $searchbreeding = $dbh->prepare("select import_record_id from import_auths where control_number=? and authorized_heading=?"); + my $searchbreeding = + $dbh->prepare("select import_record_id from import_auths where control_number=? and authorized_heading=?"); my $controlnumber = $marcrecord->field('001')->data; - $searchbreeding->execute($controlnumber,$heading); + $searchbreeding->execute( $controlnumber, $heading ); my ($breedingid) = $searchbreeding->fetchrow; return $breedingid if $breedingid; - $breedingid = AddAuthToBatch($batch_id, 0, $marcrecord, $encoding); + $breedingid = AddAuthToBatch( $batch_id, 0, $marcrecord, $encoding ); return $breedingid; } @@ -500,15 +526,14 @@ The second parameter $template is a Template object. The routine uses this param =cut sub Z3950SearchAuth { - my ($pars, $template)= @_; + my ( $pars, $template ) = @_; - my $dbh = C4::Context->dbh; - my @id= @{$pars->{id}}; - my $page= $pars->{page} // 1; + my $dbh = C4::Context->dbh; + my @id = @{ $pars->{id} }; + my $page = $pars->{page} // 1; - - my $show_next = 0; - my $total_pages = 0; + my $show_next = 0; + my $total_pages = 0; my @encoding; my @results; my @breeding_loop = (); @@ -518,36 +543,34 @@ sub Z3950SearchAuth { my @servers; my $s = 0; my $query; - my $nterms=0; + my $nterms = 0; my $marcflavour = C4::Context->preference('marcflavour'); - my $marc_type = $marcflavour eq 'UNIMARC' ? 'UNIMARCAUTH' : $marcflavour; - my $authid= $pars->{authid}; - my ( $zquery, $squery ) = _auth_build_query( $pars ); + my $marc_type = $marcflavour eq 'UNIMARC' ? 'UNIMARCAUTH' : $marcflavour; + my $authid = $pars->{authid}; + my ( $zquery, $squery ) = _auth_build_query($pars); foreach my $servid (@id) { my $sth = $dbh->prepare("select * from z3950servers where id=?"); $sth->execute($servid); while ( my $server = $sth->fetchrow_hashref ) { - $oConnection[$s] = _create_connection( $server ); + $oConnection[$s] = _create_connection($server); if ( $server->{servertype} eq 'zed' ) { my $server_zquery = $zquery; if ( my $attributes = $server->{attributes} ) { $server_zquery = "$attributes $zquery"; } - $oResult[$s] = $oConnection[$s]->search_pqf( $server_zquery ); + $oResult[$s] = $oConnection[$s]->search_pqf($server_zquery); + } else { + $oResult[$s] = + $oConnection[$s]->search( ZOOM::Query::CQL->new( _translate_query( $server, $squery ) ) ); } - else { - $oResult[$s] = $oConnection[$s]->search( - ZOOM::Query::CQL->new(_translate_query( $server, $squery )) - ); - } - $encoding[$s] = ($server->{encoding}?$server->{encoding}:"iso-5426"); - $servers[$s] = $server; + $encoding[$s] = ( $server->{encoding} ? $server->{encoding} : "iso-5426" ); + $servers[$s] = $server; $s++; - } ## while fetch + } ## while fetch } # foreach - my $nremaining = $s; + my $nremaining = $s; while ( $nremaining-- ) { my $k; @@ -559,43 +582,52 @@ sub Z3950SearchAuth { if ( $k != 0 ) { $k--; - my ($error )= $oConnection[$k]->error_x(); #ignores errmsg, addinfo, diagset + my ($error) = $oConnection[$k]->error_x(); #ignores errmsg, addinfo, diagset if ($error) { - if ($error =~ m/^(10000|10007)$/ ) { + if ( $error =~ m/^(10000|10007)$/ ) { push @errconn, { server => $servers[$k]->{host} }; } - } - else { + } else { my $numresults = $oResult[$k]->size(); my $i; my $result = ''; - if ( $numresults > 0 and $numresults >= (($page-1)*20)) { - $show_next = 1 if $numresults >= ($page*20); - $total_pages = int($numresults/20)+1 if $total_pages < ($numresults/20); - for ($i = ($page-1)*20; $i < (($numresults < ($page*20)) ? $numresults : ($page*20)); $i++) { + if ( $numresults > 0 and $numresults >= ( ( $page - 1 ) * 20 ) ) { + $show_next = 1 if $numresults >= ( $page * 20 ); + $total_pages = int( $numresults / 20 ) + 1 if $total_pages < ( $numresults / 20 ); + for ( + $i = ( $page - 1 ) * 20 ; + $i < ( ( $numresults < ( $page * 20 ) ) ? $numresults : ( $page * 20 ) ) ; + $i++ + ) + { my $rec = $oResult[$k]->record($i); if ($rec) { my $marcdata = $rec->raw(); my $marcrecord; - if( $servers[$k]->{servertype} eq 'sru' ) { - $marcrecord = eval { MARC::Record->new_from_xml( $marcdata, 'UTF-8', $servers[$k]->{syntax} ) }; - if( !$marcrecord || $@ ) { + if ( $servers[$k]->{servertype} eq 'sru' ) { + $marcrecord = + eval { MARC::Record->new_from_xml( $marcdata, 'UTF-8', $servers[$k]->{syntax} ) }; + if ( !$marcrecord || $@ ) { _dump_conversion_error( $servers[$k]->{servername}, $marcdata, $@ ); - next; # skip this one + next; # skip this one } } else { - my ($charset_result, $charset_errors); - ( $marcrecord, $charset_result, $charset_errors ) = MarcToUTF8Record( $marcdata, $marc_type, $encoding[$k] ); - if( !$marcrecord || @$charset_errors ) { - _dump_conversion_error( $servers[$k]->{servername}, $marcdata, $charset_result, $charset_errors ); - next; # skip this one + my ( $charset_result, $charset_errors ); + ( $marcrecord, $charset_result, $charset_errors ) = + MarcToUTF8Record( $marcdata, $marc_type, $encoding[$k] ); + if ( !$marcrecord || @$charset_errors ) { + _dump_conversion_error( + $servers[$k]->{servername}, $marcdata, $charset_result, + $charset_errors + ); + next; # skip this one } } $marcrecord->encoding('UTF-8'); SetUTF8Flag($marcrecord); my $heading_authtype_code = GuessAuthTypeCode($marcrecord) or next; - my $heading = GetAuthorizedHeading({ record => $marcrecord }); + my $heading = GetAuthorizedHeading( { record => $marcrecord } ); my $breedingid = ImportBreedingAuth( $marcrecord, $servers[$k]->{host}, 'UTF-8', $heading ); my %row_data; $row_data{server} = $servers[$k]->{'servername'}; @@ -604,13 +636,19 @@ sub Z3950SearchAuth { $row_data{authid} = $authid; $row_data{heading_code} = $heading_authtype_code; $row_data{row} = _add_custom_field_rowdata( - { %row_data }, $marcrecord, + {%row_data}, $marcrecord, C4::Context->preference('AdditionalFieldsInZ3950ResultAuthSearch') ) if C4::Context->preference('AdditionalFieldsInZ3950ResultAuthSearch'); push( @breeding_loop, \%row_data ); - } - else { - push(@breeding_loop,{'server'=>$servers[$k]->{'servername'},'title'=>join(': ',$oConnection[$k]->error_x()),'breedingid'=>-1,'authid'=>-1}); + } else { + push( + @breeding_loop, + { + 'server' => $servers[$k]->{'servername'}, + 'title' => join( ': ', $oConnection[$k]->error_x() ), 'breedingid' => -1, + 'authid' => -1 + } + ); } } } #if $numresults @@ -618,34 +656,34 @@ sub Z3950SearchAuth { } # if $k !=0 $template->param( - numberpending => $nremaining, - current_page => $page, - total_pages => $total_pages, - show_nextbutton => $show_next?1:0, - show_prevbutton => $page!=1, + numberpending => $nremaining, + current_page => $page, + total_pages => $total_pages, + show_nextbutton => $show_next ? 1 : 0, + show_prevbutton => $page != 1, ); - } # while nremaining + } # while nremaining #close result sets and connections - foreach(0..$s-1) { + foreach ( 0 .. $s - 1 ) { $oResult[$_]->destroy(); $oConnection[$_]->destroy(); } @servers = (); foreach my $id (@id) { - push @servers, {id => $id}; + push @servers, { id => $id }; } $template->param( breeding_loop => \@breeding_loop, - servers => \@servers, + servers => \@servers, errconn => \@errconn ); } sub _dump_conversion_error { require Data::Dumper; - warn Data::Dumper->new([ 'Z3950SearchAuth conversion error', @_ ])->Indent(0)->Dump; + warn Data::Dumper->new( [ 'Z3950SearchAuth conversion error', @_ ] )->Indent(0)->Dump; } 1; diff --git a/C4/Budgets.pm b/C4/Budgets.pm index 26e4c49143..c40b25519d 100644 --- a/C4/Budgets.pm +++ b/C4/Budgets.pm @@ -26,60 +26,61 @@ use Koha::Acquisition::Invoice::Adjustments; use C4::Acquisition; use C4::Log qw(logaction); -our (@ISA, @EXPORT_OK); +our ( @ISA, @EXPORT_OK ); + BEGIN { require Exporter; @ISA = qw(Exporter); @EXPORT_OK = qw( - GetBudget - GetBudgetByOrderNumber - GetBudgetByCode - GetBudgets - BudgetsByActivity - GetBudgetsReport - GetBudgetReport - GetBudgetsByActivity - GetBudgetHierarchy - AddBudget - ModBudget - DelBudget - GetBudgetSpent - GetBudgetOrdered - GetBudgetName - GetPeriodsCount - GetBudgetHierarchySpent - GetBudgetHierarchyOrdered + GetBudget + GetBudgetByOrderNumber + GetBudgetByCode + GetBudgets + BudgetsByActivity + GetBudgetsReport + GetBudgetReport + GetBudgetsByActivity + GetBudgetHierarchy + AddBudget + ModBudget + DelBudget + GetBudgetSpent + GetBudgetOrdered + GetBudgetName + GetPeriodsCount + GetBudgetHierarchySpent + GetBudgetHierarchyOrdered - GetBudgetUsers - ModBudgetUsers - CanUserUseBudget - CanUserModifyBudget + GetBudgetUsers + ModBudgetUsers + CanUserUseBudget + CanUserModifyBudget - GetBudgetPeriod - GetBudgetPeriods - ModBudgetPeriod - AddBudgetPeriod - DelBudgetPeriod + GetBudgetPeriod + GetBudgetPeriods + ModBudgetPeriod + AddBudgetPeriod + DelBudgetPeriod - ModBudgetPlan + ModBudgetPlan - GetBudgetsPlanCell - AddBudgetPlanValue - GetBudgetAuthCats - BudgetHasChildren - GetBudgetChildren - SetOwnerToFundHierarchy - CheckBudgetParent - CheckBudgetParentPerm + GetBudgetsPlanCell + AddBudgetPlanValue + GetBudgetAuthCats + BudgetHasChildren + GetBudgetChildren + SetOwnerToFundHierarchy + CheckBudgetParent + CheckBudgetParentPerm - HideCols - GetCols + HideCols + GetCols - CloneBudgetPeriod - CloneBudgetHierarchy - MoveOrders - FieldsForCalculatingFundValues + CloneBudgetPeriod + CloneBudgetHierarchy + MoveOrders + FieldsForCalculatingFundValues ); } @@ -100,8 +101,9 @@ sub HideCols { AND authvalue = ? | ); foreach my $authvalue (@hide_cols) { -# $sth1->{TraceLevel} = 3; - $sth1->execute( $authcat, $authvalue ); + + # $sth1->{TraceLevel} = 3; + $sth1->execute( $authcat, $authvalue ); } } @@ -116,17 +118,17 @@ sub GetCols { AND authvalue = ? and display = 0 | ); -# $sth->{TraceLevel} = 3; + # $sth->{TraceLevel} = 3; $sth->execute( $authcat, $authvalue ); - my $res = $sth->fetchrow_hashref; + my $res = $sth->fetchrow_hashref; - return $res->{cnt} > 0 ? 0: 1 + return $res->{cnt} > 0 ? 0 : 1; } sub CheckBudgetParentPerm { my ( $budget, $borrower_id ) = @_; - my $depth = $budget->{depth}; + my $depth = $budget->{depth}; my $parent_id = $budget->{budget_parent_id}; while ($depth) { my $parent = GetBudget($parent_id); @@ -134,24 +136,25 @@ sub CheckBudgetParentPerm { if ( $parent->{budget_owner_id} == $borrower_id ) { return 1; } - $depth-- + $depth--; } return 0; } sub AddBudgetPeriod { my ($budgetperiod) = @_; - return unless($budgetperiod->{budget_period_startdate} && $budgetperiod->{budget_period_enddate}); + return unless ( $budgetperiod->{budget_period_startdate} && $budgetperiod->{budget_period_enddate} ); undef $budgetperiod->{budget_period_id}; my $resultset = Koha::Database->new()->schema->resultset('Aqbudgetperiod'); return $resultset->create($budgetperiod)->id; } + # ------------------------------------------------------------------- sub GetPeriodsCount { my $dbh = C4::Context->dbh; - my $sth = $dbh->prepare(" - SELECT COUNT(*) AS sum FROM aqbudgetperiods "); + my $sth = $dbh->prepare( " + SELECT COUNT(*) AS sum FROM aqbudgetperiods " ); $sth->execute(); my $res = $sth->fetchrow_hashref; return $res->{'sum'}; @@ -166,9 +169,11 @@ sub CheckBudgetParent { my $parent_id_tmp = $new_parent_id; # check new-parent is not a child (or a child's child ;) - my $sth = $dbh->prepare(qq| + my $sth = $dbh->prepare( + qq| SELECT budget_parent_id FROM - aqbudgets where budget_id = ? | ); + aqbudgets where budget_id = ? | + ); while (1) { $sth->execute($parent_id_tmp); my $res = $sth->fetchrow_hashref; @@ -184,82 +189,97 @@ sub CheckBudgetParent { # ------------------------------------------------------------------- sub BudgetHasChildren { - my ( $budget_id ) = @_; - my $dbh = C4::Context->dbh; - my $sth = $dbh->prepare(qq| + my ($budget_id) = @_; + my $dbh = C4::Context->dbh; + my $sth = $dbh->prepare( + qq| SELECT count(*) as sum FROM aqbudgets - WHERE budget_parent_id = ? | ); - $sth->execute( $budget_id ); + WHERE budget_parent_id = ? | + ); + $sth->execute($budget_id); my $sum = $sth->fetchrow_hashref; return $sum->{'sum'}; } sub GetBudgetChildren { - my ( $budget_id ) = @_; + my ($budget_id) = @_; my $dbh = C4::Context->dbh; - return $dbh->selectall_arrayref(q| + return $dbh->selectall_arrayref( + q| SELECT * FROM aqbudgets WHERE budget_parent_id = ? - |, { Slice => {} }, $budget_id ); + |, { Slice => {} }, $budget_id + ); } sub SetOwnerToFundHierarchy { my ( $budget_id, $borrowernumber ) = @_; - my $budget = GetBudget( $budget_id ); + my $budget = GetBudget($budget_id); $budget->{budget_owner_id} = $borrowernumber; - ModBudget( $budget ); - my $children = GetBudgetChildren( $budget_id ); - for my $child ( @$children ) { + ModBudget($budget); + my $children = GetBudgetChildren($budget_id); + for my $child (@$children) { SetOwnerToFundHierarchy( $child->{budget_id}, $borrowernumber ); } } # ------------------------------------------------------------------- sub GetBudgetsPlanCell { - my ( $cell, $period, $budget ) = @_; #FIXME we don't use $period - my ($actual, $sth); - my $dbh = C4::Context->dbh; + my ( $cell, $period, $budget ) = @_; #FIXME we don't use $period + my ( $actual, $sth ); + my $dbh = C4::Context->dbh; my $roundsql = C4::Acquisition::get_rounding_sql(qq|ecost_tax_included|); if ( $cell->{'authcat'} eq 'MONTHS' ) { + # get the actual amount # FIXME we should consider quantity - $sth = $dbh->prepare( qq| + $sth = $dbh->prepare( + qq| - SELECT SUM(| . $roundsql . qq|) AS actual FROM aqorders + SELECT SUM(| . $roundsql . qq|) AS actual FROM aqorders WHERE budget_id = ? AND entrydate like "$cell->{'authvalue'}%" | ); $sth->execute( $cell->{'budget_id'} ); } elsif ( $cell->{'authcat'} eq 'BRANCHES' ) { + # get the actual amount # FIXME we should consider quantity - $sth = $dbh->prepare( qq| + $sth = $dbh->prepare( + qq| SELECT SUM(| . $roundsql . qq|) FROM aqorders LEFT JOIN aqorders_items ON (aqorders.ordernumber = aqorders_items.ordernumber) LEFT JOIN items ON (aqorders_items.itemnumber = items.itemnumber) - WHERE budget_id = ? AND homebranch = ? | ); + WHERE budget_id = ? AND homebranch = ? | + ); $sth->execute( $cell->{'budget_id'}, $cell->{'authvalue'} ); } elsif ( $cell->{'authcat'} eq 'ITEMTYPES' ) { + # get the actual amount - $sth = $dbh->prepare( qq| + $sth = $dbh->prepare( + qq| SELECT SUM( | . $roundsql . qq| * quantity) AS actual FROM aqorders JOIN biblioitems ON (biblioitems.biblionumber = aqorders.biblionumber ) WHERE aqorders.budget_id = ? and itemtype = ? | ); - $sth->execute( $cell->{'budget_id'}, - $cell->{'authvalue'} ); + $sth->execute( + $cell->{'budget_id'}, + $cell->{'authvalue'} + ); } + # ELSE GENERIC ORDERS SORT1/SORT2 STAT COUNT. else { # get the actual amount - $sth = $dbh->prepare( qq| + $sth = $dbh->prepare( + qq| SELECT SUM(| . $roundsql . qq| * quantity) AS actual FROM aqorders @@ -268,17 +288,19 @@ sub GetBudgetsPlanCell { ((aqbudgets.sort1_authcat = ? AND sort1 =?) OR (aqbudgets.sort2_authcat = ? AND sort2 =?)) | ); - $sth->execute( $cell->{'budget_id'}, - $budget->{'sort1_authcat'}, - $cell->{'authvalue'}, - $budget->{'sort2_authcat'}, - $cell->{'authvalue'} + $sth->execute( + $cell->{'budget_id'}, + $budget->{'sort1_authcat'}, + $cell->{'authvalue'}, + $budget->{'sort2_authcat'}, + $cell->{'authvalue'} ); } $actual = $sth->fetchrow_array; # get the estimated amount - $sth = $dbh->prepare( qq| + $sth = $dbh->prepare( + qq| SELECT estimated_amount AS estimated, display FROM aqbudgets_planning WHERE budget_period_id = ? AND @@ -286,18 +308,18 @@ sub GetBudgetsPlanCell { authvalue = ? AND authcat = ? | ); - $sth->execute( $cell->{'budget_period_id'}, - $cell->{'budget_id'}, - $cell->{'authvalue'}, - $cell->{'authcat'}, + $sth->execute( + $cell->{'budget_period_id'}, + $cell->{'budget_id'}, + $cell->{'authvalue'}, + $cell->{'authcat'}, ); + my $res = $sth->fetchrow_hashref; - my $res = $sth->fetchrow_hashref; - # my $display = $res->{'display'}; + # my $display = $res->{'display'}; my $estimated = $res->{'estimated'}; - return $actual, $estimated; } @@ -307,18 +329,21 @@ sub ModBudgetPlan { my $dbh = C4::Context->dbh; foreach my $buds (@$budget_plan) { my $lines = $buds->{lines}; - my $sth = $dbh->prepare( qq| + my $sth = $dbh->prepare( + qq| DELETE FROM aqbudgets_planning WHERE budget_period_id = ? AND budget_id = ? AND authcat = ? | ); - #delete a aqplan line of cells, then insert new cells, - # these could be UPDATES rather than DEL/INSERTS... - $sth->execute( $budget_period_id, $lines->[0]{budget_id} , $authcat ); + + #delete a aqplan line of cells, then insert new cells, + # these could be UPDATES rather than DEL/INSERTS... + $sth->execute( $budget_period_id, $lines->[0]{budget_id}, $authcat ); foreach my $cell (@$lines) { - my $sth = $dbh->prepare( qq| + my $sth = $dbh->prepare( + qq| INSERT INTO aqbudgets_planning SET budget_id = ?, @@ -328,11 +353,11 @@ sub ModBudgetPlan { authvalue = ? | ); $sth->execute( - $cell->{'budget_id'}, - $cell->{'budget_period_id'}, - $cell->{'authcat'}, - $cell->{'estimated_amount'}, - $cell->{'authvalue'}, + $cell->{'budget_id'}, + $cell->{'budget_period_id'}, + $cell->{'authcat'}, + $cell->{'estimated_amount'}, + $cell->{'authvalue'}, ); } } @@ -346,27 +371,36 @@ sub GetBudgetSpent { # Choose correct unitprice and ecost fields my ( $unitprice_field, $ecost_field ) = FieldsForCalculatingFundValues(); - my $sth = $dbh->prepare(qq| - SELECT SUM( | . C4::Acquisition::get_rounding_sql("COALESCE($unitprice_field, $ecost_field)") . qq| * quantity ) AS sum FROM aqorders + my $sth = $dbh->prepare( + qq| + SELECT SUM( | + . C4::Acquisition::get_rounding_sql("COALESCE($unitprice_field, $ecost_field)") + . qq| * quantity ) AS sum FROM aqorders WHERE budget_id = ? AND quantityreceived > 0 AND datecancellationprinted IS NULL - |); + | + ); $sth->execute($budget_id); my $sum = ( $sth->fetchrow_array || 0 ) + 0; - $sth = $dbh->prepare(qq| + $sth = $dbh->prepare( + qq| SELECT SUM(shipmentcost) AS sum FROM aqinvoices WHERE shipmentcost_budgetid = ? - |); + | + ); $sth->execute($budget_id); my ($shipmentcost_sum) = $sth->fetchrow_array; $sum += ( $shipmentcost_sum || 0 ) + 0; - my $adjustments = Koha::Acquisition::Invoice::Adjustments->search({budget_id => $budget_id, closedate => { '!=' => undef } },{ join => 'invoiceid' }); - while ( my $adj = $adjustments->next ){ + my $adjustments = Koha::Acquisition::Invoice::Adjustments->search( + { budget_id => $budget_id, closedate => { '!=' => undef } }, + { join => 'invoiceid' } + ); + while ( my $adj = $adjustments->next ) { $sum += $adj->adjustment; } @@ -381,17 +415,20 @@ sub GetBudgetOrdered { # Get correct unitprice and ecost prices as possible my ( $unitprice_field, $ecost_field ) = FieldsForCalculatingFundValues(); - my $sth = $dbh->prepare(qq| + my $sth = $dbh->prepare( + qq| SELECT SUM(| . C4::Acquisition::get_rounding_sql(qq|$ecost_field|) . qq| * quantity) AS sum FROM aqorders WHERE budget_id = ? AND quantityreceived = 0 AND datecancellationprinted IS NULL - |); + | + ); $sth->execute($budget_id); - my $sum = ( $sth->fetchrow_array || 0 ) + 0; + my $sum = ( $sth->fetchrow_array || 0 ) + 0; - my $adjustments = Koha::Acquisition::Invoice::Adjustments->search({budget_id => $budget_id, encumber_open => 1, closedate => undef},{ join => 'invoiceid' }); - while ( my $adj = $adjustments->next ){ + my $adjustments = Koha::Acquisition::Invoice::Adjustments->search( + { budget_id => $budget_id, encumber_open => 1, closedate => undef }, { join => 'invoiceid' } ); + while ( my $adj = $adjustments->next ) { $sum += $adj->adjustment; } @@ -407,14 +444,15 @@ get the budget_name for a given budget_id =cut sub GetBudgetName { - my ( $budget_id ) = @_; + my ($budget_id) = @_; my $dbh = C4::Context->dbh; my $sth = $dbh->prepare( qq| SELECT budget_name FROM aqbudgets WHERE budget_id = ? - |); + | + ); $sth->execute($budget_id); return $sth->fetchrow_array; @@ -428,35 +466,38 @@ Return the list of authcat for a given budget_period_id =cut -sub GetBudgetAuthCats { +sub GetBudgetAuthCats { my ($budget_period_id) = shift; + # now, populate the auth_cats_loop used in the budget planning button # we must retrieve all auth values used by at least one budget my $dbh = C4::Context->dbh; - my $sth=$dbh->prepare("SELECT sort1_authcat,sort2_authcat FROM aqbudgets WHERE budget_period_id=?"); + my $sth = $dbh->prepare("SELECT sort1_authcat,sort2_authcat FROM aqbudgets WHERE budget_period_id=?"); $sth->execute($budget_period_id); my %authcats; - while (my ($sort1_authcat,$sort2_authcat) = $sth->fetchrow) { - $authcats{$sort1_authcat}=1 if $sort1_authcat; - $authcats{$sort2_authcat}=1 if $sort2_authcat; + while ( my ( $sort1_authcat, $sort2_authcat ) = $sth->fetchrow ) { + $authcats{$sort1_authcat} = 1 if $sort1_authcat; + $authcats{$sort2_authcat} = 1 if $sort2_authcat; } return [ sort keys %authcats ]; } # ------------------------------------------------------------------- sub GetBudgetPeriods { - my ($filters,$orderby) = @_; + my ( $filters, $orderby ) = @_; my $rs = Koha::Database->new()->schema->resultset('Aqbudgetperiod'); $rs = $rs->search( $filters, { order_by => $orderby } ); $rs->result_class('DBIx::Class::ResultClass::HashRefInflator'); return [ $rs->all ]; } + # ------------------------------------------------------------------- sub GetBudgetPeriod { my ($budget_period_id) = @_; - my $dbh = C4::Context->dbh; - my $sth = $dbh->prepare( qq| + my $dbh = C4::Context->dbh; + my $sth = $dbh->prepare( + qq| SELECT * FROM aqbudgetperiods WHERE budget_period_id=? | @@ -465,26 +506,27 @@ sub GetBudgetPeriod { return $sth->fetchrow_hashref; } -sub DelBudgetPeriod{ - my ($budget_period_id) = @_; - my $dbh = C4::Context->dbh; - ; ## $total = number of records linked to the record that must be deleted +sub DelBudgetPeriod { + my ($budget_period_id) = @_; + my $dbh = C4::Context->dbh; + ; ## $total = number of records linked to the record that must be deleted my $total = 0; - ## get information about the record that will be deleted - my $sth = $dbh->prepare(qq| + ## get information about the record that will be deleted + my $sth = $dbh->prepare( + qq| DELETE FROM aqbudgetperiods WHERE budget_period_id=? | - ); - return $sth->execute($budget_period_id); + ); + return $sth->execute($budget_period_id); } # ------------------------------------------------------------------- sub ModBudgetPeriod { my ($budget_period) = @_; my $result = Koha::Database->new()->schema->resultset('Aqbudgetperiod')->find($budget_period); - return unless($result); + return unless ($result); $result = $result->update($budget_period); return $result->in_storage; @@ -502,33 +544,36 @@ sub GetBudgetHierarchy { LEFT JOIN borrowers b on b.borrowernumber = aqbudgets.budget_owner_id JOIN aqbudgetperiods USING (budget_period_id)|; - my @where_strings; + my @where_strings; + # show only period X if requested if ($budget_period_id) { - push @where_strings," aqbudgets.budget_period_id = ?"; - push @bind_params, $budget_period_id; + push @where_strings, " aqbudgets.budget_period_id = ?"; + push @bind_params, $budget_period_id; } - # show only budgets owned by me, my branch or everyone + + # show only budgets owned by me, my branch or everyone if ($owner) { if ($branchcode) { push @where_strings, - qq{ (budget_owner_id = ? OR budget_branchcode = ? OR ((budget_branchcode IS NULL or budget_branchcode="") AND (budget_owner_id IS NULL OR budget_owner_id="")))}; + qq{ (budget_owner_id = ? OR budget_branchcode = ? OR ((budget_branchcode IS NULL or budget_branchcode="") AND (budget_owner_id IS NULL OR budget_owner_id="")))}; push @bind_params, ( $owner, $branchcode ); } else { push @where_strings, ' (budget_owner_id = ? OR budget_owner_id IS NULL or budget_owner_id ="") '; - push @bind_params, $owner; + push @bind_params, $owner; } } else { if ($branchcode) { - push @where_strings," (budget_branchcode =? or budget_branchcode is NULL OR budget_branchcode='')"; - push @bind_params, $branchcode; + push @where_strings, " (budget_branchcode =? or budget_branchcode is NULL OR budget_branchcode='')"; + push @bind_params, $branchcode; } } - $query.=" WHERE ".join(' AND ', @where_strings) if @where_strings; - my $sth = $dbh->prepare($query); - $sth->execute(@bind_params); + $query .= " WHERE " . join( ' AND ', @where_strings ) if @where_strings; + my $sth = $dbh->prepare($query); + $sth->execute(@bind_params); my %links; + # create hash with budget_id has key while ( my $data = $sth->fetchrow_hashref ) { $links{ $data->{'budget_id'} } = $data; @@ -537,14 +582,16 @@ sub GetBudgetHierarchy { # link child to parent my @first_parents; foreach my $budget ( sort { $a->{budget_code} cmp $b->{budget_code} } values %links ) { - my $child = $links{$budget->{budget_id}}; + my $child = $links{ $budget->{budget_id} }; if ( $child->{'budget_parent_id'} ) { my $parent = $links{ $child->{'budget_parent_id'} }; if ($parent) { unless ( $parent->{'children'} ) { + # init child arrayref $parent->{'children'} = []; } + # add as child push @{ $parent->{'children'} }, $child; } @@ -555,55 +602,70 @@ sub GetBudgetHierarchy { my @sort = (); foreach my $first_parent (@first_parents) { - _add_budget_children(\@sort, $first_parent, 0); + _add_budget_children( \@sort, $first_parent, 0 ); } # Get correct unitprice and ecost prices as possible my ( $unitprice_field, $ecost_field ) = FieldsForCalculatingFundValues(); - if (!$skiptotals) { + if ( !$skiptotals ) { + # Get all the budgets totals in as few queries as possible - my $hr_budget_spent = $dbh->selectall_hashref(q| + my $hr_budget_spent = $dbh->selectall_hashref( + q| SELECT aqorders.budget_id, aqbudgets.budget_parent_id, - SUM( | . C4::Acquisition::get_rounding_sql(qq|COALESCE($unitprice_field, $ecost_field)|) . q| * quantity ) AS budget_spent + SUM( | + . C4::Acquisition::get_rounding_sql(qq|COALESCE($unitprice_field, $ecost_field)|) + . q| * quantity ) AS budget_spent FROM aqorders JOIN aqbudgets USING (budget_id) WHERE quantityreceived > 0 AND datecancellationprinted IS NULL GROUP BY budget_id, budget_parent_id - |, 'budget_id'); - my $hr_budget_ordered = $dbh->selectall_hashref(q| + |, 'budget_id' + ); + my $hr_budget_ordered = $dbh->selectall_hashref( + q| SELECT aqorders.budget_id, aqbudgets.budget_parent_id, SUM( | . C4::Acquisition::get_rounding_sql(qq|$ecost_field|) . q| * quantity) AS budget_ordered FROM aqorders JOIN aqbudgets USING (budget_id) WHERE quantityreceived = 0 AND datecancellationprinted IS NULL GROUP BY budget_id, budget_parent_id - |, 'budget_id'); - my $hr_budget_spent_shipment = $dbh->selectall_hashref(q| + |, 'budget_id' + ); + my $hr_budget_spent_shipment = $dbh->selectall_hashref( + q| SELECT shipmentcost_budgetid as budget_id, SUM(shipmentcost) as shipmentcost FROM aqinvoices GROUP BY shipmentcost_budgetid - |, 'budget_id'); - my $hr_budget_spent_adjustment = $dbh->selectall_hashref(q| + |, 'budget_id' + ); + my $hr_budget_spent_adjustment = $dbh->selectall_hashref( + q| SELECT budget_id, SUM(adjustment) as adjustments FROM aqinvoice_adjustments JOIN aqinvoices USING (invoiceid) WHERE closedate IS NOT NULL GROUP BY budget_id - |, 'budget_id'); - my $hr_budget_ordered_adjustment = $dbh->selectall_hashref(q| + |, 'budget_id' + ); + my $hr_budget_ordered_adjustment = $dbh->selectall_hashref( + q| SELECT budget_id, SUM(adjustment) as adjustments FROM aqinvoice_adjustments JOIN aqinvoices USING (invoiceid) WHERE closedate IS NULL AND encumber_open = 1 GROUP BY budget_id - |, 'budget_id'); - + |, 'budget_id' + ); foreach my $budget (@sort) { if ( not defined $budget->{budget_parent_id} ) { - _recursiveAdd( $budget, undef, $hr_budget_spent, $hr_budget_spent_shipment, $hr_budget_ordered, $hr_budget_spent_adjustment, $hr_budget_ordered_adjustment ); + _recursiveAdd( + $budget, undef, $hr_budget_spent, $hr_budget_spent_shipment, $hr_budget_ordered, + $hr_budget_spent_adjustment, $hr_budget_ordered_adjustment + ); } } } @@ -611,37 +673,43 @@ sub GetBudgetHierarchy { } sub _recursiveAdd { - my ($budget, $parent, $hr_budget_spent, $hr_budget_spent_shipment, $hr_budget_ordered, $hr_budget_spent_adjustment, $hr_budget_ordered_adjustment ) = @_; + my ( + $budget, $parent, $hr_budget_spent, $hr_budget_spent_shipment, $hr_budget_ordered, + $hr_budget_spent_adjustment, $hr_budget_ordered_adjustment + ) = @_; - foreach my $child (@{$budget->{children}}){ - _recursiveAdd($child, $budget, $hr_budget_spent, $hr_budget_spent_shipment, $hr_budget_ordered, $hr_budget_spent_adjustment, $hr_budget_ordered_adjustment ); + foreach my $child ( @{ $budget->{children} } ) { + _recursiveAdd( + $child, $budget, $hr_budget_spent, $hr_budget_spent_shipment, $hr_budget_ordered, + $hr_budget_spent_adjustment, $hr_budget_ordered_adjustment + ); } - $budget->{budget_spent} += $hr_budget_spent->{$budget->{budget_id}}->{budget_spent} || 0; - $budget->{budget_spent} += $hr_budget_spent_shipment->{$budget->{budget_id}}->{shipmentcost} || 0; - $budget->{budget_spent} += $hr_budget_spent_adjustment->{$budget->{budget_id}}->{adjustments} || 0; - $budget->{budget_ordered} += $hr_budget_ordered->{$budget->{budget_id}}->{budget_ordered} || 0; - $budget->{budget_ordered} += $hr_budget_ordered_adjustment->{$budget->{budget_id}}->{adjustments} || 0; + $budget->{budget_spent} += $hr_budget_spent->{ $budget->{budget_id} }->{budget_spent} || 0; + $budget->{budget_spent} += $hr_budget_spent_shipment->{ $budget->{budget_id} }->{shipmentcost} || 0; + $budget->{budget_spent} += $hr_budget_spent_adjustment->{ $budget->{budget_id} }->{adjustments} || 0; + $budget->{budget_ordered} += $hr_budget_ordered->{ $budget->{budget_id} }->{budget_ordered} || 0; + $budget->{budget_ordered} += $hr_budget_ordered_adjustment->{ $budget->{budget_id} }->{adjustments} || 0; - $budget->{total_spent} += $budget->{budget_spent}; + $budget->{total_spent} += $budget->{budget_spent}; $budget->{total_ordered} += $budget->{budget_ordered}; if ($parent) { - $parent->{total_spent} += $budget->{total_spent}; + $parent->{total_spent} += $budget->{total_spent}; $parent->{total_ordered} += $budget->{total_ordered}; } } # Recursive method to add a budget and its chidren to an array sub _add_budget_children { - my $res = shift; + my $res = shift; my $budget = shift; $budget->{budget_level} = shift; push @$res, $budget; my $children = $budget->{'children'} || []; - return unless @$children; # break recursivity + return unless @$children; # break recursivity foreach my $child (@$children) { - _add_budget_children($res, $child, $budget->{budget_level} + 1); + _add_budget_children( $res, $child, $budget->{budget_level} + 1 ); } } @@ -651,13 +719,13 @@ sub AddBudget { my ($budget) = @_; return unless ($budget); - undef $budget->{budget_encumb} if defined $budget->{budget_encumb} && $budget->{budget_encumb} eq ''; + undef $budget->{budget_encumb} if defined $budget->{budget_encumb} && $budget->{budget_encumb} eq ''; undef $budget->{budget_owner_id} if defined $budget->{budget_owner_id} && $budget->{budget_owner_id} eq ''; my $resultset = Koha::Database->new()->schema->resultset('Aqbudget'); - my $id = $resultset->create($budget)->id; + my $id = $resultset->create($budget)->id; # Log the addition - if (C4::Context->preference("AcquisitionLog")) { + if ( C4::Context->preference("AcquisitionLog") ) { my $infos = { budget_amount => $budget->{budget_amount}, budget_encumb => $budget->{budget_encumb}, @@ -678,10 +746,10 @@ sub AddBudget { sub ModBudget { my ($budget) = @_; my $result = Koha::Database->new()->schema->resultset('Aqbudget')->find($budget); - return unless($result); + return unless ($result); # Log this modification - if (C4::Context->preference("AcquisitionLog")) { + if ( C4::Context->preference("AcquisitionLog") ) { my $infos = { budget_amount_new => $budget->{budget_amount}, budget_encumb_new => $budget->{budget_encumb}, @@ -689,7 +757,7 @@ sub ModBudget { budget_amount_old => $result->budget_amount, budget_encumb_old => $result->budget_encumb, budget_expend_old => $result->budget_expend, - budget_amount_change => 0 - ($result->budget_amount - $budget->{budget_amount}) + budget_amount_change => 0 - ( $result->budget_amount - $budget->{budget_amount} ) }; logaction( 'ACQUISITIONS', @@ -699,7 +767,7 @@ sub ModBudget { ); } - undef $budget->{budget_encumb} if defined $budget->{budget_encumb} && $budget->{budget_encumb} eq ''; + undef $budget->{budget_encumb} if defined $budget->{budget_encumb} && $budget->{budget_encumb} eq ''; undef $budget->{budget_owner_id} if defined $budget->{budget_owner_id} && $budget->{budget_owner_id} eq ''; $result = $result->update($budget); return $result->in_storage; @@ -708,22 +776,22 @@ sub ModBudget { # ------------------------------------------------------------------- # FIXME Must be replaced by Koha::Acquisition::Fund->delete sub DelBudget { - my ($budget_id) = @_; - my $dbh = C4::Context->dbh; - my $sth = $dbh->prepare("delete from aqbudgets where budget_id=?"); - my $rc = $sth->execute($budget_id); + my ($budget_id) = @_; + my $dbh = C4::Context->dbh; + my $sth = $dbh->prepare("delete from aqbudgets where budget_id=?"); + my $rc = $sth->execute($budget_id); + # Log the deletion - if (C4::Context->preference("AcquisitionLog")) { + if ( C4::Context->preference("AcquisitionLog") ) { logaction( 'ACQUISITIONS', 'DELETE_FUND', $budget_id ); } - return $rc; + return $rc; } - # ------------------------------------------------------------------- =head2 GetBudget @@ -735,15 +803,15 @@ get a specific budget =cut sub GetBudget { - my ( $budget_id ) = @_; - my $dbh = C4::Context->dbh; - my $query = " + my ($budget_id) = @_; + my $dbh = C4::Context->dbh; + my $query = " SELECT * FROM aqbudgets WHERE budget_id=? "; my $sth = $dbh->prepare($query); - $sth->execute( $budget_id ); + $sth->execute($budget_id); my $result = $sth->fetchrow_hashref; return $result; } @@ -759,16 +827,16 @@ get a specific budget by order number =cut sub GetBudgetByOrderNumber { - my ( $ordernumber ) = @_; - my $dbh = C4::Context->dbh; - my $query = " + my ($ordernumber) = @_; + my $dbh = C4::Context->dbh; + my $query = " SELECT aqbudgets.* FROM aqbudgets, aqorders WHERE ordernumber=? AND aqorders.budget_id = aqbudgets.budget_id "; my $sth = $dbh->prepare($query); - $sth->execute( $ordernumber ); + $sth->execute($ordernumber); my $result = $sth->fetchrow_hashref; return $result; } @@ -785,9 +853,9 @@ Returns an array of hashrefs. # -------------------------------------------------------------------- sub GetBudgetReport { - my ( $budget_id ) = @_; - my $dbh = C4::Context->dbh; - my $query = ' + my ($budget_id) = @_; + my $dbh = C4::Context->dbh; + my $query = ' SELECT o.*, b.budget_name FROM aqbudgets b INNER JOIN aqorders o @@ -797,7 +865,7 @@ sub GetBudgetReport { ORDER BY b.budget_name'; my $sth = $dbh->prepare($query); - $sth->execute( $budget_id ); + $sth->execute($budget_id); my @results = (); while ( my $data = $sth->fetchrow_hashref ) { @@ -820,9 +888,9 @@ of the parameter. # -------------------------------------------------------------------- sub GetBudgetsByActivity { - my ( $budget_period_active ) = @_; - my $dbh = C4::Context->dbh; - my $query = " + my ($budget_period_active) = @_; + my $dbh = C4::Context->dbh; + my $query = " SELECT DISTINCT b.* FROM aqbudgetperiods bp INNER JOIN aqbudgets b @@ -830,13 +898,14 @@ sub GetBudgetsByActivity { WHERE bp.budget_period_active=? "; my $sth = $dbh->prepare($query); - $sth->execute( $budget_period_active ); + $sth->execute($budget_period_active); my @results = (); while ( my $data = $sth->fetchrow_hashref ) { push( @results, $data ); } return @results; } + # -------------------------------------------------------------------- =head2 GetBudgetsReport @@ -856,8 +925,8 @@ Returns an array of hashrefs. sub GetBudgetsReport { my ($activity) = @_; - my $dbh = C4::Context->dbh; - my $query = ' + my $dbh = C4::Context->dbh; + my $query = ' SELECT o.*, b.budget_name FROM aqbudgetperiods bp INNER JOIN aqbudgets b @@ -873,8 +942,7 @@ sub GetBudgetsReport { my $sth = $dbh->prepare($query); if ( $activity && $activity ne '' ) { $sth->execute($activity); - } - else{ + } else { $sth->execute; } my @results = (); @@ -894,9 +962,9 @@ given budget_code =cut sub GetBudgetByCode { - my ( $budget_code ) = @_; + my ($budget_code) = @_; - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $query = qq{ SELECT aqbudgets.* FROM aqbudgets @@ -905,8 +973,8 @@ sub GetBudgetByCode { ORDER BY budget_period_active DESC, budget_id DESC LIMIT 1 }; - my $sth = $dbh->prepare( $query ); - $sth->execute( $budget_code ); + my $sth = $dbh->prepare($query); + $sth->execute($budget_code); return $sth->fetchrow_hashref; } @@ -919,17 +987,19 @@ Gets the total spent of the level and sublevels of $budget_id =cut sub GetBudgetHierarchySpent { - my ( $budget_id ) = @_; - my $dbh = C4::Context->dbh; - my $children_ids = $dbh->selectcol_arrayref(q| + my ($budget_id) = @_; + my $dbh = C4::Context->dbh; + my $children_ids = $dbh->selectcol_arrayref( + q| SELECT budget_id FROM aqbudgets WHERE budget_parent_id = ? - |, {}, $budget_id ); + |, {}, $budget_id + ); - my $total_spent = GetBudgetSpent( $budget_id ); - for my $child_id ( @$children_ids ) { - $total_spent += GetBudgetHierarchySpent( $child_id ); + my $total_spent = GetBudgetSpent($budget_id); + for my $child_id (@$children_ids) { + $total_spent += GetBudgetHierarchySpent($child_id); } return $total_spent; } @@ -943,17 +1013,19 @@ Gets the total ordered of the level and sublevels of $budget_id =cut sub GetBudgetHierarchyOrdered { - my ( $budget_id ) = @_; - my $dbh = C4::Context->dbh; - my $children_ids = $dbh->selectcol_arrayref(q| + my ($budget_id) = @_; + my $dbh = C4::Context->dbh; + my $children_ids = $dbh->selectcol_arrayref( + q| SELECT budget_id FROM aqbudgets WHERE budget_parent_id = ? - |, {}, $budget_id ); + |, {}, $budget_id + ); - my $total_ordered = GetBudgetOrdered( $budget_id ); - for my $child_id ( @$children_ids ) { - $total_ordered += GetBudgetHierarchyOrdered( $child_id ); + my $total_ordered = GetBudgetOrdered($budget_id); + for my $child_id (@$children_ids) { + $total_ordered += GetBudgetHierarchyOrdered($child_id); } return $total_ordered; } @@ -968,13 +1040,13 @@ gets all budgets # ------------------------------------------------------------------- sub GetBudgets { - my ($filters, $orderby) = @_; - $orderby = 'budget_name' unless($orderby); + my ( $filters, $orderby ) = @_; + $orderby = 'budget_name' unless ($orderby); my $rs = Koha::Database->new()->schema->resultset('Aqbudget'); $rs = $rs->search( $filters, { order_by => $orderby } ); $rs->result_class('DBIx::Class::ResultClass::HashRefInflator'); - return [ $rs->all ]; + return [ $rs->all ]; } =head2 GetBudgetUsers @@ -988,7 +1060,7 @@ Return the list of borrowernumbers linked to a budget sub GetBudgetUsers { my ($budget_id) = @_; - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $query = qq{ SELECT borrowernumber FROM aqbudgetborrowers @@ -998,8 +1070,8 @@ sub GetBudgetUsers { $sth->execute($budget_id); my @borrowernumbers; - while (my ($borrowernumber) = $sth->fetchrow_array) { - push @borrowernumbers, $borrowernumber + while ( my ($borrowernumber) = $sth->fetchrow_array ) { + push @borrowernumbers, $borrowernumber; } return @borrowernumbers; @@ -1014,13 +1086,13 @@ Modify the list of borrowernumbers linked to a budget =cut sub ModBudgetUsers { - my ($budget_id, @budget_users_id) = @_; + my ( $budget_id, @budget_users_id ) = @_; return unless $budget_id; - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $query = "DELETE FROM aqbudgetborrowers WHERE budget_id = ?"; - my $sth = $dbh->prepare($query); + my $sth = $dbh->prepare($query); $sth->execute($budget_id); $query = qq{ @@ -1030,39 +1102,43 @@ sub ModBudgetUsers { $sth = $dbh->prepare($query); foreach my $borrowernumber (@budget_users_id) { next unless $borrowernumber; - $sth->execute($budget_id, $borrowernumber); + $sth->execute( $budget_id, $borrowernumber ); } } sub CanUserUseBudget { - my ($borrower, $budget, $userflags) = @_; + my ( $borrower, $budget, $userflags ) = @_; - if (not ref $borrower) { - $borrower = Koha::Patrons->find( $borrower ); + if ( not ref $borrower ) { + $borrower = Koha::Patrons->find($borrower); return 0 unless $borrower; $borrower = $borrower->unblessed; } - if (not ref $budget) { + if ( not ref $budget ) { $budget = GetBudget($budget); } - return 0 unless ($borrower and $budget); + return 0 unless ( $borrower and $budget ); - if (not defined $userflags) { - $userflags = C4::Auth::getuserflags($borrower->{flags}, - $borrower->{userid}); + if ( not defined $userflags ) { + $userflags = C4::Auth::getuserflags( + $borrower->{flags}, + $borrower->{userid} + ); } - unless ($userflags->{superlibrarian} - || (ref $userflags->{acquisition} - && $userflags->{acquisition}->{budget_manage_all}) - || (!ref $userflags->{acquisition} && $userflags->{acquisition})) + unless ( + $userflags->{superlibrarian} + || ( ref $userflags->{acquisition} + && $userflags->{acquisition}->{budget_manage_all} ) + || ( !ref $userflags->{acquisition} && $userflags->{acquisition} ) + ) { - if (not exists $userflags->{acquisition}) { + if ( not exists $userflags->{acquisition} ) { return 0; } - if (!ref $userflags->{acquisition} && !$userflags->{acquisition}) { + if ( !ref $userflags->{acquisition} && !$userflags->{acquisition} ) { return 0; } @@ -1081,17 +1157,13 @@ sub CanUserUseBudget { if ( ( - $budget->{budget_owner_id} - and $budget->{budget_owner_id} != - $borrower->{borrowernumber} + $budget->{budget_owner_id} and $budget->{budget_owner_id} != $borrower->{borrowernumber} or not $budget->{budget_owner_id} ) - and ( 0 == grep { $borrower->{borrowernumber} == $_ } - @budget_users ) + and ( 0 == grep { $borrower->{borrowernumber} == $_ } @budget_users ) and defined $budget->{budget_branchcode} - and $budget->{budget_branchcode} ne - C4::Context->userenv->{branch} - ) + and $budget->{budget_branchcode} ne C4::Context->userenv->{branch} + ) { return 0; } @@ -1102,14 +1174,11 @@ sub CanUserUseBudget { my @budget_users = GetBudgetUsers( $budget->{budget_id} ); if ( ( - $budget->{budget_owner_id} - and $budget->{budget_owner_id} != - $borrower->{borrowernumber} + $budget->{budget_owner_id} and $budget->{budget_owner_id} != $borrower->{borrowernumber} or not $budget->{budget_owner_id} ) - and ( 0 == grep { $borrower->{borrowernumber} == $_ } - @budget_users ) - ) + and ( 0 == grep { $borrower->{borrowernumber} == $_ } @budget_users ) + ) { return 0; } @@ -1120,35 +1189,40 @@ sub CanUserUseBudget { } sub CanUserModifyBudget { - my ($borrower, $budget, $userflags) = @_; + my ( $borrower, $budget, $userflags ) = @_; - if (not ref $borrower) { - $borrower = Koha::Patrons->find( $borrower ); + if ( not ref $borrower ) { + $borrower = Koha::Patrons->find($borrower); return 0 unless $borrower; $borrower = $borrower->unblessed; } - if (not ref $budget) { + if ( not ref $budget ) { $budget = GetBudget($budget); } - return 0 unless ($borrower and $budget); + return 0 unless ( $borrower and $budget ); - if (not defined $userflags) { - $userflags = C4::Auth::getuserflags($borrower->{flags}, - $borrower->{userid}); + if ( not defined $userflags ) { + $userflags = C4::Auth::getuserflags( + $borrower->{flags}, + $borrower->{userid} + ); } - unless ($userflags->{superlibrarian} - || (ref $userflags->{acquisition} - && $userflags->{acquisition}->{budget_manage_all}) - || (!ref $userflags->{acquisition} && $userflags->{acquisition})) + unless ( + $userflags->{superlibrarian} + || ( ref $userflags->{acquisition} + && $userflags->{acquisition}->{budget_manage_all} ) + || ( !ref $userflags->{acquisition} && $userflags->{acquisition} ) + ) { - if (!CanUserUseBudget($borrower, $budget, $userflags)) { + if ( !CanUserUseBudget( $borrower, $budget, $userflags ) ) { return 0; } - if (ref $userflags->{acquisition} - && !$userflags->{acquisition}->{budget_modify}) { + if ( ref $userflags->{acquisition} + && !$userflags->{acquisition}->{budget_modify} ) + { return 0; } } @@ -1157,10 +1231,10 @@ sub CanUserModifyBudget { } sub _round { - my ($value, $increment) = @_; + my ( $value, $increment ) = @_; - if ($increment && $increment != 0) { - $value = int($value / $increment) * $increment; + if ( $increment && $increment != 0 ) { + $value = int( $value / $increment ) * $increment; } return $value; @@ -1186,35 +1260,35 @@ amounts will be reset. =cut sub CloneBudgetPeriod { - my ($params) = @_; - my $budget_period_id = $params->{budget_period_id}; - my $budget_period_startdate = $params->{budget_period_startdate}; - my $budget_period_enddate = $params->{budget_period_enddate}; - my $budget_period_description = $params->{budget_period_description}; - my $amount_change_percentage = $params->{amount_change_percentage}; - my $amount_change_round_increment = $params->{amount_change_round_increment}; - my $mark_original_budget_as_inactive = - $params->{mark_original_budget_as_inactive} || 0; - my $reset_all_budgets = $params->{reset_all_budgets} || 0; + my ($params) = @_; + my $budget_period_id = $params->{budget_period_id}; + my $budget_period_startdate = $params->{budget_period_startdate}; + my $budget_period_enddate = $params->{budget_period_enddate}; + my $budget_period_description = $params->{budget_period_description}; + my $amount_change_percentage = $params->{amount_change_percentage}; + my $amount_change_round_increment = $params->{amount_change_round_increment}; + my $mark_original_budget_as_inactive = $params->{mark_original_budget_as_inactive} || 0; + my $reset_all_budgets = $params->{reset_all_budgets} || 0; my $budget_period = GetBudgetPeriod($budget_period_id); $budget_period->{budget_period_startdate} = $budget_period_startdate; $budget_period->{budget_period_enddate} = $budget_period_enddate; $budget_period->{budget_period_description} = $budget_period_description; + # The new budget (budget_period) should be active by default - $budget_period->{budget_period_active} = 1; + $budget_period->{budget_period_active} = 1; if ($amount_change_percentage) { my $total = $budget_period->{budget_period_total}; $total += $total * $amount_change_percentage / 100; - $total = _round($total, $amount_change_round_increment); + $total = _round( $total, $amount_change_round_increment ); $budget_period->{budget_period_total} = $total; } my $original_budget_period_id = $budget_period->{budget_period_id}; delete $budget_period->{budget_period_id}; - my $new_budget_period_id = AddBudgetPeriod( $budget_period ); + my $new_budget_period_id = AddBudgetPeriod($budget_period); my $budgets = GetBudgetHierarchy($budget_period_id); CloneBudgetHierarchy( @@ -1233,20 +1307,20 @@ sub CloneBudgetPeriod { ); } - if ( $reset_all_budgets ) { - my $budgets = GetBudgets({ budget_period_id => $new_budget_period_id }); - for my $budget ( @$budgets ) { + if ($reset_all_budgets) { + my $budgets = GetBudgets( { budget_period_id => $new_budget_period_id } ); + for my $budget (@$budgets) { $budget->{budget_amount} = 0; - ModBudget( $budget ); + ModBudget($budget); } } elsif ($amount_change_percentage) { - my $budgets = GetBudgets({ budget_period_id => $new_budget_period_id }); - for my $budget ( @$budgets ) { + my $budgets = GetBudgets( { budget_period_id => $new_budget_period_id } ); + for my $budget (@$budgets) { my $amount = $budget->{budget_amount}; $amount += $amount * $amount_change_percentage / 100; - $amount = _round($amount, $amount_change_round_increment); + $amount = _round( $amount, $amount_change_round_increment ); $budget->{budget_amount} = $amount; - ModBudget( $budget ); + ModBudget($budget); } } @@ -1274,20 +1348,19 @@ sub CloneBudgetHierarchy { my $new_parent_id = $params->{new_parent_id}; my @first_level_budgets = - ( not defined $children_of ) - ? map { ( not $_->{budget_parent_id} ) ? $_ : () } @$budgets - : map { ( defined $_->{budget_parent_id} && $_->{budget_parent_id} == $children_of ) ? $_ : () } @$budgets; + ( not defined $children_of ) + ? map { ( not $_->{budget_parent_id} ) ? $_ : () } @$budgets + : map { ( defined $_->{budget_parent_id} && $_->{budget_parent_id} == $children_of ) ? $_ : () } @$budgets; # get only the columns of aqbudgets my @columns = Koha::Database->new()->schema->source('Aqbudget')->columns; - for my $budget ( sort { $a->{budget_id} <=> $b->{budget_id} } - @first_level_budgets ) - { + for my $budget ( sort { $a->{budget_id} <=> $b->{budget_id} } @first_level_budgets ) { - my $tidy_budget = - { map { join( ' ', @columns ) =~ /$_/ ? ( $_ => $budget->{$_} ) : () } - keys %$budget }; + my $tidy_budget = { + map { join( ' ', @columns ) =~ /$_/ ? ( $_ => $budget->{$_} ) : () } + keys %$budget + }; delete $tidy_budget->{timestamp}; my $new_budget_id = AddBudget( { @@ -1297,8 +1370,8 @@ sub CloneBudgetHierarchy { budget_period_id => $new_budget_period_id } ); - my @borrowernumbers = GetBudgetUsers($budget->{budget_id}); - ModBudgetUsers($new_budget_id, @borrowernumbers); + my @borrowernumbers = GetBudgetUsers( $budget->{budget_id} ); + ModBudgetUsers( $new_budget_id, @borrowernumbers ); CloneBudgetHierarchy( { budgets => $budgets, @@ -1322,21 +1395,21 @@ Move orders from one budget period to another. =cut sub MoveOrders { - my ($params) = @_; - my $from_budget_period_id = $params->{from_budget_period_id}; - my $to_budget_period_id = $params->{to_budget_period_id}; + my ($params) = @_; + my $from_budget_period_id = $params->{from_budget_period_id}; + my $to_budget_period_id = $params->{to_budget_period_id}; my $move_remaining_unspent = $params->{move_remaining_unspent}; return - if not $from_budget_period_id - or not $to_budget_period_id - or $from_budget_period_id == $to_budget_period_id; + if not $from_budget_period_id + or not $to_budget_period_id + or $from_budget_period_id == $to_budget_period_id; # Can't move orders to an inactive budget (budgetperiod) my $budget_period = GetBudgetPeriod($to_budget_period_id); return unless $budget_period->{budget_period_active}; my @report; - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $sth_update_aqorders = $dbh->prepare( q| UPDATE aqorders @@ -1352,6 +1425,7 @@ sub MoveOrders { | ); my $from_budgets = GetBudgetHierarchy($from_budget_period_id); + for my $from_budget (@$from_budgets) { my $new_budget_id = $dbh->selectcol_arrayref( q| @@ -1362,14 +1436,14 @@ sub MoveOrders { |, {}, $to_budget_period_id, $from_budget->{budget_code} ); $new_budget_id = $new_budget_id->[0]; - my $new_budget = GetBudget( $new_budget_id ); - unless ( $new_budget ) { + my $new_budget = GetBudget($new_budget_id); + unless ($new_budget) { push @report, - { - moved => 0, - budget => $from_budget, - error => 'budget_code_not_exists', - }; + { + moved => 0, + budget => $from_budget, + error => 'budget_code_not_exists', + }; next; } my $orders_to_move = C4::Acquisition::SearchOrders( @@ -1387,25 +1461,27 @@ sub MoveOrders { my $unspent_moved = 0; if ($move_remaining_unspent) { - my $spent = GetBudgetHierarchySpent( $from_budget->{budget_id} ); - my $unspent = $from_budget->{budget_amount} - $spent; + my $spent = GetBudgetHierarchySpent( $from_budget->{budget_id} ); + my $unspent = $from_budget->{budget_amount} - $spent; my $new_budget_amount = $new_budget->{budget_amount}; if ( $unspent > 0 ) { $new_budget_amount += $unspent; $unspent_moved = $unspent; } $new_budget->{budget_amount} = $new_budget_amount; - $sth_update_budget_amount->execute( $new_budget_amount, - $new_budget->{budget_id} ); + $sth_update_budget_amount->execute( + $new_budget_amount, + $new_budget->{budget_id} + ); } push @report, - { + { budget => $new_budget, orders_moved => \@orders_moved, moved => 1, unspent_moved => $unspent_moved, - }; + }; } return \@report; } @@ -1426,11 +1502,11 @@ sub FieldsForCalculatingFundValues { my $ecost_field = 'ecost_tax_included'; if ( !C4::Context->preference('CalculateFundValuesIncludingTax') ) { - $unitprice_field = 'unitprice_tax_excluded'; - $ecost_field = 'ecost_tax_excluded'; + $unitprice_field = 'unitprice_tax_excluded'; + $ecost_field = 'ecost_tax_excluded'; } - return ( $unitprice_field, $ecost_field); + return ( $unitprice_field, $ecost_field ); } END { } # module clean-up code here (global destructor) diff --git a/C4/Calendar.pm b/C4/Calendar.pm index 6344bedd1e..e8b75a25d0 100644 --- a/C4/Calendar.pm +++ b/C4/Calendar.pm @@ -19,7 +19,7 @@ use strict; use warnings; use vars qw(@EXPORT); -use Carp qw( croak ); +use Carp qw( croak ); use Date::Calc qw( Today ); use C4::Context; @@ -53,66 +53,72 @@ C<$branchcode> specifies which Calendar you want. sub new { my $classname = shift @_; - my %options = @_; - my $self = bless({}, $classname); - foreach my $optionName (keys %options) { - $self->{lc($optionName)} = $options{$optionName}; + my %options = @_; + my $self = bless( {}, $classname ); + foreach my $optionName ( keys %options ) { + $self->{ lc($optionName) } = $options{$optionName}; } - defined($self->{branchcode}) or croak "No branchcode argument to new. Should be C4::Calendar->new(branchcode => \$branchcode)"; - $self->_init($self->{branchcode}); + defined( $self->{branchcode} ) + or croak "No branchcode argument to new. Should be C4::Calendar->new(branchcode => \$branchcode)"; + $self->_init( $self->{branchcode} ); return $self; } sub _init { - my $self = shift @_; + my $self = shift @_; my $branch = shift; - defined($branch) or die "No branchcode sent to _init"; # must test for defined here and above to allow "" - my $dbh = C4::Context->dbh(); - my $repeatable = $dbh->prepare( 'SELECT * + defined($branch) or die "No branchcode sent to _init"; # must test for defined here and above to allow "" + my $dbh = C4::Context->dbh(); + my $repeatable = $dbh->prepare( + 'SELECT * FROM repeatable_holidays WHERE ( branchcode = ? ) - AND (ISNULL(weekday) = ?)' ); - $repeatable->execute($branch,0); + AND (ISNULL(weekday) = ?)' + ); + $repeatable->execute( $branch, 0 ); my %week_days_holidays; - while (my $row = $repeatable->fetchrow_hashref) { + + while ( my $row = $repeatable->fetchrow_hashref ) { my $key = $row->{weekday}; $week_days_holidays{$key}{title} = $row->{title}; $week_days_holidays{$key}{description} = $row->{description}; } $self->{'week_days_holidays'} = \%week_days_holidays; - $repeatable->execute($branch,1); + $repeatable->execute( $branch, 1 ); my %day_month_holidays; - while (my $row = $repeatable->fetchrow_hashref) { + while ( my $row = $repeatable->fetchrow_hashref ) { my $key = $row->{month} . "/" . $row->{day}; $day_month_holidays{$key}{title} = $row->{title}; $day_month_holidays{$key}{description} = $row->{description}; - $day_month_holidays{$key}{day} = sprintf("%02d", $row->{day}); - $day_month_holidays{$key}{month} = sprintf("%02d", $row->{month}); + $day_month_holidays{$key}{day} = sprintf( "%02d", $row->{day} ); + $day_month_holidays{$key}{month} = sprintf( "%02d", $row->{month} ); } $self->{'day_month_holidays'} = \%day_month_holidays; - my $special = $dbh->prepare( 'SELECT day, month, year, title, description + my $special = $dbh->prepare( + 'SELECT day, month, year, title, description FROM special_holidays WHERE ( branchcode = ? ) - AND (isexception = ?)' ); - $special->execute($branch,1); + AND (isexception = ?)' + ); + $special->execute( $branch, 1 ); my %exception_holidays; - while (my ($day, $month, $year, $title, $description) = $special->fetchrow) { - $exception_holidays{"$year/$month/$day"}{title} = $title; + while ( my ( $day, $month, $year, $title, $description ) = $special->fetchrow ) { + $exception_holidays{"$year/$month/$day"}{title} = $title; $exception_holidays{"$year/$month/$day"}{description} = $description; - $exception_holidays{"$year/$month/$day"}{date} = - sprintf(ISO_DATE_FORMAT, $year, $month, $day); + $exception_holidays{"$year/$month/$day"}{date} = + sprintf( ISO_DATE_FORMAT, $year, $month, $day ); } $self->{'exception_holidays'} = \%exception_holidays; - $special->execute($branch,0); + $special->execute( $branch, 0 ); my %single_holidays; - while (my ($day, $month, $year, $title, $description) = $special->fetchrow) { - $single_holidays{"$year/$month/$day"}{title} = $title; + while ( my ( $day, $month, $year, $title, $description ) = $special->fetchrow ) { + $single_holidays{"$year/$month/$day"}{title} = $title; $single_holidays{"$year/$month/$day"}{description} = $description; - $single_holidays{"$year/$month/$day"}{date} = - sprintf(ISO_DATE_FORMAT, $year, $month, $day); + $single_holidays{"$year/$month/$day"}{date} = + sprintf( ISO_DATE_FORMAT, $year, $month, $day ); } $self->{'single_holidays'} = \%single_holidays; return $self; @@ -127,7 +133,7 @@ Returns a hash reference to week days holidays. =cut sub get_week_days_holidays { - my $self = shift @_; + my $self = shift @_; my $week_days_holidays = $self->{'week_days_holidays'}; return $week_days_holidays; } @@ -141,7 +147,7 @@ Returns a hash reference to day month holidays. =cut sub get_day_month_holidays { - my $self = shift @_; + my $self = shift @_; my $day_month_holidays = $self->{'day_month_holidays'}; return $day_month_holidays; } @@ -157,7 +163,7 @@ date. =cut sub get_exception_holidays { - my $self = shift @_; + my $self = shift @_; my $exception_holidays = $self->{'exception_holidays'}; return $exception_holidays; } @@ -172,7 +178,7 @@ happened just one time. =cut sub get_single_holidays { - my $self = shift @_; + my $self = shift @_; my $single_holidays = $self->{'single_holidays'}; return $single_holidays; } @@ -194,16 +200,18 @@ C<$description> Is the description to store for the holiday formed by $year/$mon =cut sub insert_week_day_holiday { - my $self = shift @_; + my $self = shift @_; my %options = @_; my $weekday = $options{weekday}; croak "Invalid weekday $weekday" unless $weekday =~ m/^[0-6]$/; - my $dbh = C4::Context->dbh(); - my $insertHoliday = $dbh->prepare("insert into repeatable_holidays (branchcode,weekday,day,month,title,description) values ( ?,?,NULL,NULL,?,? )"); - $insertHoliday->execute( $self->{branchcode}, $weekday, $options{title}, $options{description}); - $self->{'week_days_holidays'}->{$weekday}{title} = $options{title}; + my $dbh = C4::Context->dbh(); + my $insertHoliday = $dbh->prepare( + "insert into repeatable_holidays (branchcode,weekday,day,month,title,description) values ( ?,?,NULL,NULL,?,? )" + ); + $insertHoliday->execute( $self->{branchcode}, $weekday, $options{title}, $options{description} ); + $self->{'week_days_holidays'}->{$weekday}{title} = $options{title}; $self->{'week_days_holidays'}->{$weekday}{description} = $options{description}; return $self; } @@ -228,13 +236,18 @@ C<$description> Is the description to store for the holiday formed by $year/$mon =cut sub insert_day_month_holiday { - my $self = shift @_; + my $self = shift @_; my %options = @_; - my $dbh = C4::Context->dbh(); - my $insertHoliday = $dbh->prepare("insert into repeatable_holidays (branchcode,weekday,day,month,title,description) values (?, NULL, ?, ?, ?,? )"); - $insertHoliday->execute( $self->{branchcode}, $options{day},$options{month},$options{title}, $options{description}); - $self->{'day_month_holidays'}->{"$options{month}/$options{day}"}{title} = $options{title}; + my $dbh = C4::Context->dbh(); + my $insertHoliday = $dbh->prepare( + "insert into repeatable_holidays (branchcode,weekday,day,month,title,description) values (?, NULL, ?, ?, ?,? )" + ); + $insertHoliday->execute( + $self->{branchcode}, $options{day}, $options{month}, $options{title}, + $options{description} + ); + $self->{'day_month_holidays'}->{"$options{month}/$options{day}"}{title} = $options{title}; $self->{'day_month_holidays'}->{"$options{month}/$options{day}"}{description} = $options{description}; return $self; } @@ -262,19 +275,23 @@ C<$description> Is the description to store for the holiday formed by $year/$mon =cut sub insert_single_holiday { - my $self = shift @_; + my $self = shift @_; my %options = @_; @options{qw(year month day)} = ( $options{date} =~ m/(\d+)-(\d+)-(\d+)/o ) - if $options{date} && !$options{day}; + if $options{date} && !$options{day}; - my $dbh = C4::Context->dbh(); - my $isexception = 0; - my $insertHoliday = $dbh->prepare("insert into special_holidays (branchcode,day,month,year,isexception,title,description) values (?,?,?,?,?,?,?)"); - $insertHoliday->execute( $self->{branchcode}, $options{day},$options{month},$options{year}, $isexception, $options{title}, $options{description}); - $self->{'single_holidays'}->{"$options{year}/$options{month}/$options{day}"}{title} = $options{title}; + my $dbh = C4::Context->dbh(); + my $isexception = 0; + my $insertHoliday = $dbh->prepare( + "insert into special_holidays (branchcode,day,month,year,isexception,title,description) values (?,?,?,?,?,?,?)" + ); + $insertHoliday->execute( + $self->{branchcode}, $options{day}, $options{month}, $options{year}, $isexception, + $options{title}, $options{description} + ); + $self->{'single_holidays'}->{"$options{year}/$options{month}/$options{day}"}{title} = $options{title}; $self->{'single_holidays'}->{"$options{year}/$options{month}/$options{day}"}{description} = $options{description}; - # changed the 'single_holidays' table, lets force/reset its cache my $cache = Koha::Caches->get_instance(); my $key = $self->{branchcode} . "_holidays"; @@ -307,18 +324,24 @@ C<$description> Is the description to store for the holiday formed by $year/$mon =cut sub insert_exception_holiday { - my $self = shift @_; + my $self = shift @_; my %options = @_; @options{qw(year month day)} = ( $options{date} =~ m/(\d+)-(\d+)-(\d+)/o ) - if $options{date} && !$options{day}; + if $options{date} && !$options{day}; - my $dbh = C4::Context->dbh(); - my $isexception = 1; - my $insertException = $dbh->prepare("insert into special_holidays (branchcode,day,month,year,isexception,title,description) values (?,?,?,?,?,?,?)"); - $insertException->execute( $self->{branchcode}, $options{day},$options{month},$options{year}, $isexception, $options{title}, $options{description}); + my $dbh = C4::Context->dbh(); + my $isexception = 1; + my $insertException = $dbh->prepare( + "insert into special_holidays (branchcode,day,month,year,isexception,title,description) values (?,?,?,?,?,?,?)" + ); + $insertException->execute( + $self->{branchcode}, $options{day}, $options{month}, $options{year}, $isexception, + $options{title}, $options{description} + ); $self->{'exception_holidays'}->{"$options{year}/$options{month}/$options{day}"}{title} = $options{title}; - $self->{'exception_holidays'}->{"$options{year}/$options{month}/$options{day}"}{description} = $options{description}; + $self->{'exception_holidays'}->{"$options{year}/$options{month}/$options{day}"}{description} = + $options{description}; # changed the 'single_holidays' table, lets force/reset its cache my $cache = Koha::Caches->get_instance(); @@ -343,14 +366,15 @@ C<$description> Is the description to update for the holiday. =cut sub ModWeekdayholiday { - my $self = shift @_; + my $self = shift @_; my %options = @_; my $dbh = C4::Context->dbh(); - my $updateHoliday = $dbh->prepare("UPDATE repeatable_holidays SET title = ?, description = ? WHERE branchcode = ? AND weekday = ?"); - $updateHoliday->execute( $options{title},$options{description},$self->{branchcode},$options{weekday}); - $self->{'week_days_holidays'}->{$options{weekday}}{title} = $options{title}; - $self->{'week_days_holidays'}->{$options{weekday}}{description} = $options{description}; + my $updateHoliday = + $dbh->prepare("UPDATE repeatable_holidays SET title = ?, description = ? WHERE branchcode = ? AND weekday = ?"); + $updateHoliday->execute( $options{title}, $options{description}, $self->{branchcode}, $options{weekday} ); + $self->{'week_days_holidays'}->{ $options{weekday} }{title} = $options{title}; + $self->{'week_days_holidays'}->{ $options{weekday} }{description} = $options{description}; return $self; } @@ -374,13 +398,17 @@ C<$description> The description to be update for the holiday. =cut sub ModDaymonthholiday { - my $self = shift @_; + my $self = shift @_; my %options = @_; - my $dbh = C4::Context->dbh(); - my $updateHoliday = $dbh->prepare("UPDATE repeatable_holidays SET title = ?, description = ? WHERE month = ? AND day = ? AND branchcode = ?"); - $updateHoliday->execute( $options{title},$options{description},$options{month},$options{day},$self->{branchcode}); - $self->{'day_month_holidays'}->{"$options{month}/$options{day}"}{title} = $options{title}; + my $dbh = C4::Context->dbh(); + my $updateHoliday = $dbh->prepare( + "UPDATE repeatable_holidays SET title = ?, description = ? WHERE month = ? AND day = ? AND branchcode = ?"); + $updateHoliday->execute( + $options{title}, $options{description}, $options{month}, $options{day}, + $self->{branchcode} + ); + $self->{'day_month_holidays'}->{"$options{month}/$options{day}"}{title} = $options{title}; $self->{'day_month_holidays'}->{"$options{month}/$options{day}"}{description} = $options{description}; return $self; } @@ -408,17 +436,20 @@ C<$description> Is the description to update for the holiday formed by $year/$mo =cut sub ModSingleholiday { - my $self = shift @_; + my $self = shift @_; my %options = @_; - my $dbh = C4::Context->dbh(); + my $dbh = C4::Context->dbh(); my $isexception = 0; - my $updateHoliday = $dbh->prepare(" + my $updateHoliday = $dbh->prepare( " UPDATE special_holidays SET title = ?, description = ? - WHERE day = ? AND month = ? AND year = ? AND branchcode = ? AND isexception = ?"); - $updateHoliday->execute($options{title},$options{description},$options{day},$options{month},$options{year},$self->{branchcode},$isexception); - $self->{'single_holidays'}->{"$options{year}/$options{month}/$options{day}"}{title} = $options{title}; + WHERE day = ? AND month = ? AND year = ? AND branchcode = ? AND isexception = ?" ); + $updateHoliday->execute( + $options{title}, $options{description}, $options{day}, $options{month}, $options{year}, + $self->{branchcode}, $isexception + ); + $self->{'single_holidays'}->{"$options{year}/$options{month}/$options{day}"}{title} = $options{title}; $self->{'single_holidays'}->{"$options{year}/$options{month}/$options{day}"}{description} = $options{description}; # changed the 'single_holidays' table, lets force/reset its cache @@ -452,17 +483,21 @@ C<$description> Is the description to be modified for the holiday formed by $yea =cut sub ModExceptionholiday { - my $self = shift @_; + my $self = shift @_; my %options = @_; - my $dbh = C4::Context->dbh(); - my $isexception = 1; - my $updateHoliday = $dbh->prepare(" + my $dbh = C4::Context->dbh(); + my $isexception = 1; + my $updateHoliday = $dbh->prepare( " UPDATE special_holidays SET title = ?, description = ? - WHERE day = ? AND month = ? AND year = ? AND branchcode = ? AND isexception = ?"); - $updateHoliday->execute($options{title},$options{description},$options{day},$options{month},$options{year},$self->{branchcode},$isexception); + WHERE day = ? AND month = ? AND year = ? AND branchcode = ? AND isexception = ?" ); + $updateHoliday->execute( + $options{title}, $options{description}, $options{day}, $options{month}, $options{year}, + $self->{branchcode}, $isexception + ); $self->{'exception_holidays'}->{"$options{year}/$options{month}/$options{day}"}{title} = $options{title}; - $self->{'exception_holidays'}->{"$options{year}/$options{month}/$options{day}"}{description} = $options{description}; + $self->{'exception_holidays'}->{"$options{year}/$options{month}/$options{day}"}{description} = + $options{description}; # changed the 'single_holidays' table, lets force/reset its cache my $cache = Koha::Caches->get_instance(); @@ -492,7 +527,7 @@ C<$year> Is year to make the date to delete. =cut sub delete_holiday { - my $self = shift @_; + my $self = shift @_; my %options = @_; # Verify what kind of holiday that day is. For example, if it is @@ -500,47 +535,53 @@ sub delete_holiday { # for that holiday rule. Otherwise, if it is a regular holiday, it´s # ok just deleting it. - my $dbh = C4::Context->dbh(); - my $isSingleHoliday = $dbh->prepare("SELECT id FROM special_holidays WHERE (branchcode = ?) AND (day = ?) AND (month = ?) AND (year = ?)"); - $isSingleHoliday->execute($self->{branchcode}, $options{day}, $options{month}, $options{year}); - if ($isSingleHoliday->rows) { + my $dbh = C4::Context->dbh(); + my $isSingleHoliday = $dbh->prepare( + "SELECT id FROM special_holidays WHERE (branchcode = ?) AND (day = ?) AND (month = ?) AND (year = ?)"); + $isSingleHoliday->execute( $self->{branchcode}, $options{day}, $options{month}, $options{year} ); + if ( $isSingleHoliday->rows ) { my $id = $isSingleHoliday->fetchrow; - $isSingleHoliday->finish; # Close the last query + $isSingleHoliday->finish; # Close the last query my $deleteHoliday = $dbh->prepare("DELETE FROM special_holidays WHERE id = ?"); $deleteHoliday->execute($id); - delete($self->{'single_holidays'}->{"$options{year}/$options{month}/$options{day}"}); + delete( $self->{'single_holidays'}->{"$options{year}/$options{month}/$options{day}"} ); } else { - $isSingleHoliday->finish; # Close the last query + $isSingleHoliday->finish; # Close the last query my $isWeekdayHoliday = $dbh->prepare("SELECT id FROM repeatable_holidays WHERE branchcode = ? AND weekday = ?"); - $isWeekdayHoliday->execute($self->{branchcode}, $options{weekday}); - if ($isWeekdayHoliday->rows) { + $isWeekdayHoliday->execute( $self->{branchcode}, $options{weekday} ); + if ( $isWeekdayHoliday->rows ) { my $id = $isWeekdayHoliday->fetchrow; - $isWeekdayHoliday->finish; # Close the last query + $isWeekdayHoliday->finish; # Close the last query - my $updateExceptions = $dbh->prepare("UPDATE special_holidays SET isexception = 0 WHERE (WEEKDAY(CONCAT(special_holidays.year,'-',special_holidays.month,'-',special_holidays.day)) = ?) AND (branchcode = ?)"); - $updateExceptions->execute($options{weekday}, $self->{branchcode}); - $updateExceptions->finish; # Close the last query + my $updateExceptions = $dbh->prepare( + "UPDATE special_holidays SET isexception = 0 WHERE (WEEKDAY(CONCAT(special_holidays.year,'-',special_holidays.month,'-',special_holidays.day)) = ?) AND (branchcode = ?)" + ); + $updateExceptions->execute( $options{weekday}, $self->{branchcode} ); + $updateExceptions->finish; # Close the last query my $deleteHoliday = $dbh->prepare("DELETE FROM repeatable_holidays WHERE id = ?"); $deleteHoliday->execute($id); - delete($self->{'week_days_holidays'}->{$options{weekday}}); + delete( $self->{'week_days_holidays'}->{ $options{weekday} } ); } else { - $isWeekdayHoliday->finish; # Close the last query + $isWeekdayHoliday->finish; # Close the last query - my $isDayMonthHoliday = $dbh->prepare("SELECT id FROM repeatable_holidays WHERE (branchcode = ?) AND (day = ?) AND (month = ?)"); - $isDayMonthHoliday->execute($self->{branchcode}, $options{day}, $options{month}); - if ($isDayMonthHoliday->rows) { + my $isDayMonthHoliday = $dbh->prepare( + "SELECT id FROM repeatable_holidays WHERE (branchcode = ?) AND (day = ?) AND (month = ?)"); + $isDayMonthHoliday->execute( $self->{branchcode}, $options{day}, $options{month} ); + if ( $isDayMonthHoliday->rows ) { my $id = $isDayMonthHoliday->fetchrow; $isDayMonthHoliday->finish; - my $updateExceptions = $dbh->prepare("UPDATE special_holidays SET isexception = 0 WHERE (special_holidays.branchcode = ?) AND (special_holidays.day = ?) and (special_holidays.month = ?)"); - $updateExceptions->execute($self->{branchcode}, $options{day}, $options{month}); - $updateExceptions->finish; # Close the last query + my $updateExceptions = $dbh->prepare( + "UPDATE special_holidays SET isexception = 0 WHERE (special_holidays.branchcode = ?) AND (special_holidays.day = ?) and (special_holidays.month = ?)" + ); + $updateExceptions->execute( $self->{branchcode}, $options{day}, $options{month} ); + $updateExceptions->finish; # Close the last query my $deleteHoliday = $dbh->prepare("DELETE FROM repeatable_holidays WHERE (id = ?)"); $deleteHoliday->execute($id); - delete($self->{'day_month_holidays'}->{"$options{month}/$options{day}"}); + delete( $self->{'day_month_holidays'}->{"$options{month}/$options{day}"} ); } } } @@ -552,6 +593,7 @@ sub delete_holiday { return $self; } + =head2 delete_holiday_range delete_holiday_range(day => $day, @@ -569,12 +611,13 @@ C<$year> Is year to make the date to delete. =cut sub delete_holiday_range { - my $self = shift; + my $self = shift; my %options = @_; my $dbh = C4::Context->dbh(); - my $sth = $dbh->prepare("DELETE FROM special_holidays WHERE (branchcode = ?) AND (day = ?) AND (month = ?) AND (year = ?)"); - $sth->execute($self->{branchcode}, $options{day}, $options{month}, $options{year}); + my $sth = $dbh->prepare( + "DELETE FROM special_holidays WHERE (branchcode = ?) AND (day = ?) AND (month = ?) AND (year = ?)"); + $sth->execute( $self->{branchcode}, $options{day}, $options{month}, $options{year} ); # changed the 'single_holidays' table, lets force/reset its cache my $cache = Koha::Caches->get_instance(); @@ -597,12 +640,12 @@ C<$month> Is month to make the date to delete. =cut sub delete_holiday_range_repeatable { - my $self = shift; + my $self = shift; my %options = @_; my $dbh = C4::Context->dbh(); my $sth = $dbh->prepare("DELETE FROM repeatable_holidays WHERE (branchcode = ?) AND (day = ?) AND (month = ?)"); - $sth->execute($self->{branchcode}, $options{day}, $options{month}); + $sth->execute( $self->{branchcode}, $options{day}, $options{month} ); # changed the 'single_holidays' table, lets force/reset its cache my $cache = Koha::Caches->get_instance(); @@ -628,12 +671,14 @@ C<$year> Is year to make the date to delete. =cut sub delete_exception_holiday_range { - my $self = shift; + my $self = shift; my %options = @_; my $dbh = C4::Context->dbh(); - my $sth = $dbh->prepare("DELETE FROM special_holidays WHERE (branchcode = ?) AND (isexception = 1) AND (day = ?) AND (month = ?) AND (year = ?)"); - $sth->execute($self->{branchcode}, $options{day}, $options{month}, $options{year}); + my $sth = $dbh->prepare( + "DELETE FROM special_holidays WHERE (branchcode = ?) AND (isexception = 1) AND (day = ?) AND (month = ?) AND (year = ?)" + ); + $sth->execute( $self->{branchcode}, $options{day}, $options{month}, $options{year} ); # changed the 'single_holidays' table, lets force/reset its cache my $cache = Koha::Caches->get_instance(); @@ -654,22 +699,25 @@ C<$year> Is the year to check whether if is a holiday or not. =cut sub isHoliday { - my ($self, $day, $month, $year) = @_; - # FIXME - date strings are stored in non-padded metric format. should change to iso. - $month=$month+0; - $year=$year+0; - $day=$day+0; - my $weekday = &Date::Calc::Day_of_Week($year, $month, $day) % 7; + my ( $self, $day, $month, $year ) = @_; + + # FIXME - date strings are stored in non-padded metric format. should change to iso. + $month = $month + 0; + $year = $year + 0; + $day = $day + 0; + my $weekday = &Date::Calc::Day_of_Week( $year, $month, $day ) % 7; my $weekDays = $self->get_week_days_holidays(); my $dayMonths = $self->get_day_month_holidays(); my $exceptions = $self->get_exception_holidays(); my $singles = $self->get_single_holidays(); - if (defined($exceptions->{"$year/$month/$day"})) { + + if ( defined( $exceptions->{"$year/$month/$day"} ) ) { return 0; } else { - if ((exists($weekDays->{$weekday})) || - (exists($dayMonths->{"$month/$day"})) || - (exists($singles->{"$year/$month/$day"}))) { + if ( ( exists( $weekDays->{$weekday} ) ) + || ( exists( $dayMonths->{"$month/$day"} ) ) + || ( exists( $singles->{"$year/$month/$day"} ) ) ) + { return 1; } else { return 0; @@ -685,44 +733,44 @@ sub isHoliday { =cut sub copy_to_branch { - my ($self, $target_branch) = @_; + my ( $self, $target_branch ) = @_; croak "No target_branch" unless $target_branch; - my $target_calendar = C4::Calendar->new(branchcode => $target_branch); + my $target_calendar = C4::Calendar->new( branchcode => $target_branch ); - my ($y, $m, $d) = Today(); - my $today = sprintf ISO_DATE_FORMAT, $y,$m,$d; + my ( $y, $m, $d ) = Today(); + my $today = sprintf ISO_DATE_FORMAT, $y, $m, $d; - my $wdh = $self->get_week_days_holidays; + my $wdh = $self->get_week_days_holidays; my $target_wdh = $target_calendar->get_week_days_holidays; - foreach my $key (keys %$wdh) { - unless (grep { $_ eq $key } keys %$target_wdh) { - $target_calendar->insert_week_day_holiday( weekday => $key, %{ $wdh->{$key} } ) + foreach my $key ( keys %$wdh ) { + unless ( grep { $_ eq $key } keys %$target_wdh ) { + $target_calendar->insert_week_day_holiday( weekday => $key, %{ $wdh->{$key} } ); } } - my $dmh = $self->get_day_month_holidays; + my $dmh = $self->get_day_month_holidays; my $target_dmh = $target_calendar->get_day_month_holidays; - foreach my $values (values %$dmh) { - unless (grep { $_->{day} eq $values->{day} && $_->{month} eq $values->{month} } values %$target_dmh) { - $target_calendar->insert_day_month_holiday(%{ $values }); + foreach my $values ( values %$dmh ) { + unless ( grep { $_->{day} eq $values->{day} && $_->{month} eq $values->{month} } values %$target_dmh ) { + $target_calendar->insert_day_month_holiday( %{$values} ); } } my $exception_holidays = $self->get_exception_holidays; - my $target_exceptions = $target_calendar->get_exception_holidays; - foreach my $values ( grep {$_->{date} gt $today} values %{ $exception_holidays }) { - unless ( grep { $_->{date} eq $values->{date} } values %$target_exceptions) { - $target_calendar->insert_exception_holiday(%{ $values }); + my $target_exceptions = $target_calendar->get_exception_holidays; + foreach my $values ( grep { $_->{date} gt $today } values %{$exception_holidays} ) { + unless ( grep { $_->{date} eq $values->{date} } values %$target_exceptions ) { + $target_calendar->insert_exception_holiday( %{$values} ); } } my $single_holidays = $self->get_single_holidays; - my $target_singles = $target_calendar->get_single_holidays; - foreach my $values ( grep {$_->{date} gt $today} values %{ $single_holidays }) { - unless ( grep { $_->{date} eq $values->{date} } values %$target_singles){ - $target_calendar->insert_single_holiday(%{ $values }); + my $target_singles = $target_calendar->get_single_holidays; + foreach my $values ( grep { $_->{date} gt $today } values %{$single_holidays} ) { + unless ( grep { $_->{date} eq $values->{date} } values %$target_singles ) { + $target_calendar->insert_single_holiday( %{$values} ); } } diff --git a/C4/Charset.pm b/C4/Charset.pm index 969ecc66e5..f506509d74 100644 --- a/C4/Charset.pm +++ b/C4/Charset.pm @@ -26,10 +26,11 @@ use Encode; use Koha::Logger; -our (@ISA, @EXPORT_OK); +our ( @ISA, @EXPORT_OK ); + BEGIN { require Exporter; - @ISA = qw(Exporter); + @ISA = qw(Exporter); @EXPORT_OK = qw( NormalizeString IsStringUTF8ish @@ -109,7 +110,7 @@ sub IsStringUTF8ish { my $str = shift; return 1 if Encode::is_utf8($str); - return utf8::decode( $str ); + return utf8::decode($str); } =head2 SetUTF8Flag @@ -131,22 +132,22 @@ But since it handles charset, and MARC::Record, it finds its way in that package =cut -sub SetUTF8Flag{ - my ($record, $nfd)=@_; - return unless ($record && $record->fields()); - foreach my $field ($record->fields()){ - if ($field->tag()>=10){ +sub SetUTF8Flag { + my ( $record, $nfd ) = @_; + return unless ( $record && $record->fields() ); + foreach my $field ( $record->fields() ) { + if ( $field->tag() >= 10 ) { my @subfields; - foreach my $subfield ($field->subfields()){ - push @subfields,($$subfield[0],NormalizeString($$subfield[1],$nfd)); + foreach my $subfield ( $field->subfields() ) { + push @subfields, ( $$subfield[0], NormalizeString( $$subfield[1], $nfd ) ); } eval { - my $newfield=MARC::Field->new( - $field->tag(), - $field->indicator(1), - $field->indicator(2), - @subfields - ); + my $newfield = MARC::Field->new( + $field->tag(), + $field->indicator(1), + $field->indicator(2), + @subfields + ); $field->replace_with($newfield); }; warn "ERROR occurred in SetUTF8Flag $@" if $@; @@ -173,24 +174,23 @@ Sample code : =cut +sub NormalizeString { + my ( $string, $nfd, $transform ) = @_; + return $string unless defined($string); # force scalar context return. + $string = Encode::decode( 'UTF-8', $string ) unless ( Encode::is_utf8($string) ); + if ($nfd) { + $string = NFD($string); + } else { + $string = NFC($string); + } + if ($transform) { + $string =~ s/\<|\>|\^|\;|\.|\?|,|\-|\(|\)|\[|\]|\{|\}|\$|\%|\!|\*|\:|\\|\/|\&|\"|\'/ /g; -sub NormalizeString{ - my ($string,$nfd,$transform)=@_; - return $string unless defined($string); # force scalar context return. - $string = Encode::decode('UTF-8', $string) unless (Encode::is_utf8($string)); - if ($nfd){ - $string= NFD($string); - } - else { - $string=NFC($string); - } - if ($transform){ - $string=~s/\<|\>|\^|\;|\.|\?|,|\-|\(|\)|\[|\]|\{|\}|\$|\%|\!|\*|\:|\\|\/|\&|\"|\'/ /g; - #removing one letter words "d'" "l'" was changed into "d " "l " - $string=~s/\b\S\b//g; - $string=~s/\s+$//g; - } - return $string; + #removing one letter words "d'" "l'" was changed into "d " "l " + $string =~ s/\b\S\b//g; + $string =~ s/\s+$//g; + } + return $string; } =head2 MarcToUTF8Record @@ -215,18 +215,19 @@ conversion is returned in C<$converted_from>. =cut sub MarcToUTF8Record { - my $marc = shift; - my $marc_flavour = shift; + my $marc = shift; + my $marc_flavour = shift; my $source_encoding = shift; my $marc_record; my $marc_blob_is_utf8 = 0; - if (ref($marc) eq 'MARC::Record') { + if ( ref($marc) eq 'MARC::Record' ) { my $marc_blob = $marc->as_usmarc(); $marc_blob_is_utf8 = IsStringUTF8ish($marc_blob); - $marc_record = $marc; + $marc_record = $marc; } else { + # dealing with a MARC blob - + # remove any ersatz whitespace from the beginning and # end of the MARC blob -- these can creep into MARC # files produced by several sources -- caller really @@ -234,19 +235,17 @@ sub MarcToUTF8Record { $marc =~ s/^\s+//; $marc =~ s/\s+$//; $marc_blob_is_utf8 = IsStringUTF8ish($marc); - eval { - $marc_record = MARC::Record->new_from_usmarc($marc); - }; + eval { $marc_record = MARC::Record->new_from_usmarc($marc); }; if ($@) { + # if we fail the first time, one likely problem # is that we have a MARC21 record that says that it's # UTF-8 (Leader/09 = 'a') but contains non-UTF-8 characters. # We'll try parsing it again. - substr($marc, 9, 1) = ' '; - eval { - $marc_record = MARC::Record->new_from_usmarc($marc); - }; + substr( $marc, 9, 1 ) = ' '; + eval { $marc_record = MARC::Record->new_from_usmarc($marc); }; if ($@) { + # it's hopeless; return an empty MARC::Record return MARC::Record->new(), 'failed', ['could not parse MARC blob']; } @@ -260,45 +259,48 @@ sub MarcToUTF8Record { # a. record is MARC-8 # b. record is ISO-8859-1 # 3. If MARC flavor is UNIMARC, then - if (not defined $source_encoding) { + if ( not defined $source_encoding ) { if ($marc_blob_is_utf8) { + # note that for MARC21 we are not bothering to check # if the Leader/09 is set to 'a' or not -- because # of problems with various ILSs (including Koha in the # past, alas), this just is not trustworthy. - SetMarcUnicodeFlag($marc_record, $marc_flavour); + SetMarcUnicodeFlag( $marc_record, $marc_flavour ); return $marc_record, 'UTF-8', []; } else { - if ($marc_flavour eq 'MARC21') { - return _default_marc21_charconv_to_utf8($marc_record, $marc_flavour); - } elsif ($marc_flavour =~/UNIMARC/) { - return _default_unimarc_charconv_to_utf8($marc_record, $marc_flavour); + if ( $marc_flavour eq 'MARC21' ) { + return _default_marc21_charconv_to_utf8( $marc_record, $marc_flavour ); + } elsif ( $marc_flavour =~ /UNIMARC/ ) { + return _default_unimarc_charconv_to_utf8( $marc_record, $marc_flavour ); } else { - return _default_marc21_charconv_to_utf8($marc_record, $marc_flavour); + return _default_marc21_charconv_to_utf8( $marc_record, $marc_flavour ); } } } else { + # caller knows the character encoding my $original_marc_record = $marc_record->clone(); my @errors; - if ($source_encoding =~ /utf-?8/i) { + if ( $source_encoding =~ /utf-?8/i ) { if ($marc_blob_is_utf8) { - SetMarcUnicodeFlag($marc_record, $marc_flavour); + SetMarcUnicodeFlag( $marc_record, $marc_flavour ); return $marc_record, 'UTF-8', []; } else { push @errors, 'specified UTF-8 => UTF-8 conversion, but record is not in UTF-8'; } - } elsif ($source_encoding =~ /marc-?8/i) { - @errors = _marc_marc8_to_utf8($marc_record, $marc_flavour); - } elsif ($source_encoding =~ /5426/) { - @errors = _marc_iso5426_to_utf8($marc_record, $marc_flavour); + } elsif ( $source_encoding =~ /marc-?8/i ) { + @errors = _marc_marc8_to_utf8( $marc_record, $marc_flavour ); + } elsif ( $source_encoding =~ /5426/ ) { + @errors = _marc_iso5426_to_utf8( $marc_record, $marc_flavour ); } else { + # assume any other character encoding is for Text::Iconv - @errors = _marc_to_utf8_via_text_iconv($marc_record, $marc_flavour, $source_encoding); + @errors = _marc_to_utf8_via_text_iconv( $marc_record, $marc_flavour, $source_encoding ); } if (@errors) { - _marc_to_utf8_replacement_char($original_marc_record, $marc_flavour); + _marc_to_utf8_replacement_char( $original_marc_record, $marc_flavour ); return $original_marc_record, 'failed', \@errors; } else { return $marc_record, $source_encoding, []; @@ -320,39 +322,36 @@ any actual character conversion. =cut sub SetMarcUnicodeFlag { - my $marc_record = shift; - my $marc_flavour = shift; # || C4::Context->preference("marcflavour"); + my $marc_record = shift; + my $marc_flavour = shift; # || C4::Context->preference("marcflavour"); $marc_record->encoding('UTF-8'); - if ($marc_flavour eq 'MARC21') { + if ( $marc_flavour eq 'MARC21' ) { my $leader = $marc_record->leader(); - substr($leader, 9, 1) = 'a'; - $marc_record->leader($leader); - } elsif ($marc_flavour =~/UNIMARC/) { + substr( $leader, 9, 1 ) = 'a'; + $marc_record->leader($leader); + } elsif ( $marc_flavour =~ /UNIMARC/ ) { require C4::Context; - my $defaultlanguage = C4::Context->preference("UNIMARCField100Language"); - $defaultlanguage = "fre" if (!$defaultlanguage || length($defaultlanguage) != 3); - my $string; - my ($subflength,$encodingposition)=($marc_flavour=~/AUTH/?(21,12):(36,25)); - $string=$marc_record->subfield( 100, "a" ); - if (defined $string && length($string)==$subflength) { - $string = substr $string, 0,$subflength if (length($string)>$subflength); - } - else { - $string = POSIX::strftime( "%Y%m%d", localtime ); - $string =~ s/\-//g; + my $defaultlanguage = C4::Context->preference("UNIMARCField100Language"); + $defaultlanguage = "fre" if ( !$defaultlanguage || length($defaultlanguage) != 3 ); + my $string; + my ( $subflength, $encodingposition ) = ( $marc_flavour =~ /AUTH/ ? ( 21, 12 ) : ( 36, 25 ) ); + $string = $marc_record->subfield( 100, "a" ); + if ( defined $string && length($string) == $subflength ) { + $string = substr $string, 0, $subflength if ( length($string) > $subflength ); + } else { + $string = POSIX::strftime( "%Y%m%d", localtime ); + $string =~ s/\-//g; $string = sprintf( "%-*s", $subflength, $string ); - substr ( $string, ($encodingposition - 3), 3, $defaultlanguage); - } - substr( $string, $encodingposition, 3, "y50" ); - if ( $marc_record->subfield( 100, "a" ) ) { - $marc_record->field('100')->update(a=>$string); - } - else { - $marc_record->insert_grouped_field( - MARC::Field->new( 100, '', '', "a" => $string ) ); + substr( $string, ( $encodingposition - 3 ), 3, $defaultlanguage ); } - Koha::Logger->get->debug("encodage: ", substr( $marc_record->subfield(100, 'a'), $encodingposition, 3 )); + substr( $string, $encodingposition, 3, "y50" ); + if ( $marc_record->subfield( 100, "a" ) ) { + $marc_record->field('100')->update( a => $string ); + } else { + $marc_record->insert_grouped_field( MARC::Field->new( 100, '', '', "a" => $string ) ); + } + Koha::Logger->get->debug( "encodage: ", substr( $marc_record->subfield( 100, 'a' ), $encodingposition, 3 ) ); } else { warn "Unrecognized marcflavour: $marc_flavour"; } @@ -385,15 +384,13 @@ to work, at the possible risk of some data loss. sub StripNonXmlChars { my $str = shift; - if (!defined($str) || $str eq ""){ + if ( !defined($str) || $str eq "" ) { return ""; } $str =~ s/[^\x09\x0A\x0D\x{0020}-\x{D7FF}\x{E000}-\x{FFFD}\x{10000}-\x{10FFFF}]//g; return $str; } - - =head2 nsb_clean =over 4 @@ -405,24 +402,24 @@ nsb_clean($string); Removes Non Sorting Block characters =cut + sub nsb_clean { - my $NSB = '\x88' ; # NSB : begin Non Sorting Block - my $NSE = '\x89' ; # NSE : Non Sorting Block end - my $NSB2 = '\x98' ; # NSB : begin Non Sorting Block - my $NSE2 = '\x9C' ; # NSE : Non Sorting Block end - my $C2 = '\xC2' ; # What is this char ? It is sometimes left by the regexp after removing NSB / NSE + my $NSB = '\x88'; # NSB : begin Non Sorting Block + my $NSE = '\x89'; # NSE : Non Sorting Block end + my $NSB2 = '\x98'; # NSB : begin Non Sorting Block + my $NSE2 = '\x9C'; # NSE : Non Sorting Block end + my $C2 = '\xC2'; # What is this char ? It is sometimes left by the regexp after removing NSB / NSE # handles non sorting blocks - my ($string) = @_ ; - $_ = $string ; - s/($C2){0,1}($NSB|$NSB2)//g ; - s/($C2){0,1}($NSE|$NSE2)//g ; - $string = $_ ; + my ($string) = @_; + $_ = $string; + s/($C2){0,1}($NSB|$NSB2)//g; + s/($C2){0,1}($NSE|$NSE2)//g; + $string = $_; - return($string) ; + return ($string); } - =head2 SanitizeRecord SanitizeRecord($marcrecord); @@ -438,22 +435,20 @@ sub SanitizeRecord { my $string; my $record_modified = 0; my $frameworkcode = C4::Biblio::GetFrameworkCode($biblionumber); - my ( $url_field, $url_subfield ) = - C4::Biblio::GetMarcFromKohaField( 'biblioitems.url' ); + my ( $url_field, $url_subfield ) = C4::Biblio::GetMarcFromKohaField('biblioitems.url'); foreach my $field ( $record->fields() ) { if ( $field->is_control_field() ) { my $value = $field->data(); my $sanitized_value = _clean_ampersand($value); $record_modified = 1 if $sanitized_value ne $value; $field->update($sanitized_value); - } - else { + } else { my @subfields = $field->subfields(); my @new_subfields; foreach my $subfield (@subfields) { next - if $url_field eq $field->tag() - and $url_subfield eq $subfield->[0]; + if $url_field eq $field->tag() + and $url_subfield eq $subfield->[0]; my $value = $subfield->[1]; my $sanitized_value = _clean_ampersand($value); push @new_subfields, $subfield->[0] => $sanitized_value; @@ -468,8 +463,7 @@ sub SanitizeRecord { }; if ($@) { warn "error : $@"; - } - else { + } else { $field->replace_with($new_field); } @@ -505,28 +499,28 @@ this is 'failed'. =cut sub _default_marc21_charconv_to_utf8 { - my $marc_record = shift; + my $marc_record = shift; my $marc_flavour = shift; my $trial_marc8 = $marc_record->clone(); - my @all_errors = (); - my @errors = _marc_marc8_to_utf8($trial_marc8, $marc_flavour); + my @all_errors = (); + my @errors = _marc_marc8_to_utf8( $trial_marc8, $marc_flavour ); unless (@errors) { return $trial_marc8, 'MARC-8', []; } push @all_errors, @errors; - + my $trial_8859_1 = $marc_record->clone(); - @errors = _marc_to_utf8_via_text_iconv($trial_8859_1, $marc_flavour, 'iso-8859-1'); + @errors = _marc_to_utf8_via_text_iconv( $trial_8859_1, $marc_flavour, 'iso-8859-1' ); unless (@errors) { - return $trial_8859_1, 'iso-8859-1', []; # note -- we could return \@all_errors - # instead if we wanted to report details - # of the failed attempt at MARC-8 => UTF-8 + return $trial_8859_1, 'iso-8859-1', []; # note -- we could return \@all_errors + # instead if we wanted to report details + # of the failed attempt at MARC-8 => UTF-8 } push @all_errors, @errors; - + my $default_converted = $marc_record->clone(); - _marc_to_utf8_replacement_char($default_converted, $marc_flavour); + _marc_to_utf8_replacement_char( $default_converted, $marc_flavour ); return $default_converted, 'failed', \@all_errors; } @@ -547,26 +541,26 @@ this is 'failed'. =cut sub _default_unimarc_charconv_to_utf8 { - my $marc_record = shift; + my $marc_record = shift; my $marc_flavour = shift; my $trial_marc8 = $marc_record->clone(); - my @all_errors = (); - my @errors = _marc_iso5426_to_utf8($trial_marc8, $marc_flavour); + my @all_errors = (); + my @errors = _marc_iso5426_to_utf8( $trial_marc8, $marc_flavour ); unless (@errors) { return $trial_marc8, 'iso-5426'; } push @all_errors, @errors; - + my $trial_8859_1 = $marc_record->clone(); - @errors = _marc_to_utf8_via_text_iconv($trial_8859_1, $marc_flavour, 'iso-8859-1'); + @errors = _marc_to_utf8_via_text_iconv( $trial_8859_1, $marc_flavour, 'iso-8859-1' ); unless (@errors) { return $trial_8859_1, 'iso-8859-1'; } push @all_errors, @errors; - + my $default_converted = $marc_record->clone(); - _marc_to_utf8_replacement_char($default_converted, $marc_flavour); + _marc_to_utf8_replacement_char( $default_converted, $marc_flavour ); return $default_converted, 'failed', \@all_errors; } @@ -582,17 +576,18 @@ C<@errors> array. =cut sub _marc_marc8_to_utf8 { - my $marc_record = shift; + my $marc_record = shift; my $marc_flavour = shift; - my $prev_ignore = MARC::Charset->ignore_errors(); + my $prev_ignore = MARC::Charset->ignore_errors(); MARC::Charset->ignore_errors(1); # trap warnings raised by MARC::Charset my @errors = (); local $SIG{__WARN__} = sub { my $msg = $_[0]; - if ($msg =~ /MARC.Charset/) { + if ( $msg =~ /MARC.Charset/ ) { + # FIXME - purpose of this regexp is to strip out the # line reference to MARC/Charset.pm, but as it # exists probably won't work quite on Windows -- @@ -601,20 +596,22 @@ sub _marc_marc8_to_utf8 { $msg =~ s/at [\/].*?.MARC.Charset\.pm line \d+\.\n$//; push @errors, $msg; } else { + # if warning doesn't come from MARC::Charset, just # pass it on warn $msg; } }; - foreach my $field ($marc_record->fields()) { - if ($field->is_control_field()) { - ; # do nothing -- control fields should not contain non-ASCII characters + foreach my $field ( $marc_record->fields() ) { + if ( $field->is_control_field() ) { + ; # do nothing -- control fields should not contain non-ASCII characters } else { my @converted_subfields; - foreach my $subfield ($field->subfields()) { - my $utf8sf = MARC::Charset::marc8_to_utf8($subfield->[1]); - unless (IsStringUTF8ish($utf8sf)) { + foreach my $subfield ( $field->subfields() ) { + my $utf8sf = MARC::Charset::marc8_to_utf8( $subfield->[1] ); + unless ( IsStringUTF8ish($utf8sf) ) { + # Because of a bug in MARC::Charset 0.98, if the string # has (a) one or more diacritics that (b) are only in character positions # 128 to 255 inclusive, the resulting converted string is not in @@ -622,21 +619,23 @@ sub _marc_marc8_to_utf8 { # occurs, upgrade the string in place. Moral of the story seems to be # that pack("U", ...) is better than chr(...) if you need to guarantee # that the resulting string is UTF-8. - $utf8sf = Encode::encode('UTF-8', $utf8sf); + $utf8sf = Encode::encode( 'UTF-8', $utf8sf ); } push @converted_subfields, $subfield->[0], $utf8sf; } - $field->replace_with(MARC::Field->new( - $field->tag(), $field->indicator(1), $field->indicator(2), - @converted_subfields) - ); + $field->replace_with( + MARC::Field->new( + $field->tag(), $field->indicator(1), $field->indicator(2), + @converted_subfields + ) + ); } } MARC::Charset->ignore_errors($prev_ignore); - SetMarcUnicodeFlag($marc_record, $marc_flavour); + SetMarcUnicodeFlag( $marc_record, $marc_flavour ); return @errors; } @@ -656,29 +655,31 @@ that C can be used instead? =cut sub _marc_iso5426_to_utf8 { - my $marc_record = shift; + my $marc_record = shift; my $marc_flavour = shift; my @errors = (); - foreach my $field ($marc_record->fields()) { - if ($field->is_control_field()) { - ; # do nothing -- control fields should not contain non-ASCII characters + foreach my $field ( $marc_record->fields() ) { + if ( $field->is_control_field() ) { + ; # do nothing -- control fields should not contain non-ASCII characters } else { my @converted_subfields; - foreach my $subfield ($field->subfields()) { - my $utf8sf = char_decode5426($subfield->[1]); + foreach my $subfield ( $field->subfields() ) { + my $utf8sf = char_decode5426( $subfield->[1] ); push @converted_subfields, $subfield->[0], $utf8sf; } - $field->replace_with(MARC::Field->new( - $field->tag(), $field->indicator(1), $field->indicator(2), - @converted_subfields) - ); + $field->replace_with( + MARC::Field->new( + $field->tag(), $field->indicator(1), $field->indicator(2), + @converted_subfields + ) + ); } } - SetMarcUnicodeFlag($marc_record, $marc_flavour); + SetMarcUnicodeFlag( $marc_record, $marc_flavour ); return @errors; } @@ -698,13 +699,13 @@ C<@errors> array. =cut sub _marc_to_utf8_via_text_iconv { - my $marc_record = shift; - my $marc_flavour = shift; + my $marc_record = shift; + my $marc_flavour = shift; my $source_encoding = shift; my @errors = (); my $decoder; - eval { $decoder = Text::Iconv->new($source_encoding, 'utf8'); }; + eval { $decoder = Text::Iconv->new( $source_encoding, 'utf8' ); }; if ($@) { push @errors, "Could not initialze $source_encoding => utf8 converter: $@"; return @errors; @@ -713,19 +714,19 @@ sub _marc_to_utf8_via_text_iconv { my $prev_raise_error = Text::Iconv->raise_error(); Text::Iconv->raise_error(1); - foreach my $field ($marc_record->fields()) { - if ($field->is_control_field()) { - ; # do nothing -- control fields should not contain non-ASCII characters + foreach my $field ( $marc_record->fields() ) { + if ( $field->is_control_field() ) { + ; # do nothing -- control fields should not contain non-ASCII characters } else { my @converted_subfields; - foreach my $subfield ($field->subfields()) { + foreach my $subfield ( $field->subfields() ) { my $converted_value; my $conversion_ok = 1; - eval { $converted_value = $decoder->convert($subfield->[1]); }; + eval { $converted_value = $decoder->convert( $subfield->[1] ); }; if ($@) { $conversion_ok = 0; push @errors, $@; - } elsif (not defined $converted_value) { + } elsif ( not defined $converted_value ) { $conversion_ok = 0; push @errors, "Text::Iconv conversion failed - retval is " . $decoder->retval(); } @@ -739,14 +740,16 @@ sub _marc_to_utf8_via_text_iconv { } } - $field->replace_with(MARC::Field->new( - $field->tag(), $field->indicator(1), $field->indicator(2), - @converted_subfields) - ); + $field->replace_with( + MARC::Field->new( + $field->tag(), $field->indicator(1), $field->indicator(2), + @converted_subfields + ) + ); } } - SetMarcUnicodeFlag($marc_record, $marc_flavour); + SetMarcUnicodeFlag( $marc_record, $marc_flavour ); Text::Iconv->raise_error($prev_raise_error); return @errors; @@ -767,28 +770,30 @@ until they find the right one. =cut sub _marc_to_utf8_replacement_char { - my $marc_record = shift; + my $marc_record = shift; my $marc_flavour = shift; - foreach my $field ($marc_record->fields()) { - if ($field->is_control_field()) { - ; # do nothing -- control fields should not contain non-ASCII characters + foreach my $field ( $marc_record->fields() ) { + if ( $field->is_control_field() ) { + ; # do nothing -- control fields should not contain non-ASCII characters } else { my @converted_subfields; - foreach my $subfield ($field->subfields()) { + foreach my $subfield ( $field->subfields() ) { my $value = $subfield->[1]; $value =~ s/[\200-\377]/\xef\xbf\xbd/g; push @converted_subfields, $subfield->[0], $value; } - $field->replace_with(MARC::Field->new( - $field->tag(), $field->indicator(1), $field->indicator(2), - @converted_subfields) - ); + $field->replace_with( + MARC::Field->new( + $field->tag(), $field->indicator(1), $field->indicator(2), + @converted_subfields + ) + ); } } - SetMarcUnicodeFlag($marc_record, $marc_flavour); + SetMarcUnicodeFlag( $marc_record, $marc_flavour ); } =head2 char_decode5426 @@ -799,472 +804,484 @@ Converts a string from ISO-5426 to UTF-8. =cut - my %chars; #### ## 0xb -$chars{0xb0}=0x0101;#3/0ayn[ain] -$chars{0xb1}=0x0623;#3/1alif/hamzah[alefwithhamzaabove] +$chars{0xb0} = 0x0101; #3/0ayn[ain] +$chars{0xb1} = 0x0623; #3/1alif/hamzah[alefwithhamzaabove] + #$chars{0xb2}=0x00e0;#'à'; -$chars{0xb2}=0x00e0;#3/2leftlowsinglequotationmark +$chars{0xb2} = 0x00e0; #3/2leftlowsinglequotationmark + #$chars{0xb3}=0x00e7;#'ç'; -$chars{0xb3}=0x00e7;#3/2leftlowsinglequotationmark +$chars{0xb3} = 0x00e7; #3/2leftlowsinglequotationmark + # $chars{0xb4}='è'; -$chars{0xb4}=0x00e8; +$chars{0xb4} = 0x00e8; + # $chars{0xb5}='é'; -$chars{0xb5}=0x00e9; -$chars{0xb6}=0x2021; # double dagger -$chars{0xb7}=0x00b7; # middle dot -$chars{0xb8}=0x2033; # double prime -$chars{0xb9}=0x2019; # right single quotation mark -$chars{0xba}=0x201d; # right double quotation mark -$chars{0xbb}=0x00bb; # right-pointing double angle quotation mark -$chars{0xbc}=0x266f; # music sharp sign -$chars{0xbd}=0x02b9; # modifier letter prime -$chars{0xbe}=0x02ba; # modifier letter double prime -$chars{0xbf}=0x00bf; # inverted question mark +$chars{0xb5} = 0x00e9; +$chars{0xb6} = 0x2021; # double dagger +$chars{0xb7} = 0x00b7; # middle dot +$chars{0xb8} = 0x2033; # double prime +$chars{0xb9} = 0x2019; # right single quotation mark +$chars{0xba} = 0x201d; # right double quotation mark +$chars{0xbb} = 0x00bb; # right-pointing double angle quotation mark +$chars{0xbc} = 0x266f; # music sharp sign +$chars{0xbd} = 0x02b9; # modifier letter prime +$chars{0xbe} = 0x02ba; # modifier letter double prime +$chars{0xbf} = 0x00bf; # inverted question mark #### ## 0xe -$chars{0xe1}=0x00c6; # latin capital letter ae -$chars{0xe2}=0x0110; # latin capital letter d with stroke -$chars{0xe6}=0x0132; # latin capital ligature ij -$chars{0xe8}=0x0141; # latin capital letter l with stroke -$chars{0xe9}=0x00d8; # latin capital letter o with stroke -$chars{0xea}=0x0152; # latin capital ligature oe -$chars{0xec}=0x00de; # latin capital letter thorn +$chars{0xe1} = 0x00c6; # latin capital letter ae +$chars{0xe2} = 0x0110; # latin capital letter d with stroke +$chars{0xe6} = 0x0132; # latin capital ligature ij +$chars{0xe8} = 0x0141; # latin capital letter l with stroke +$chars{0xe9} = 0x00d8; # latin capital letter o with stroke +$chars{0xea} = 0x0152; # latin capital ligature oe +$chars{0xec} = 0x00de; # latin capital letter thorn #### ## 0xf -$chars{0xf1}=0x00e6; # latin small letter ae -$chars{0xf2}=0x0111; # latin small letter d with stroke -$chars{0xf3}=0x00f0; # latin small letter eth -$chars{0xf5}=0x0131; # latin small letter dotless i -$chars{0xf6}=0x0133; # latin small ligature ij -$chars{0xf8}=0x0142; # latin small letter l with stroke -$chars{0xf9}=0x00f8; # latin small letter o with stroke -$chars{0xfa}=0x0153; # latin small ligature oe -$chars{0xfb}=0x00df; # latin small letter sharp s -$chars{0xfc}=0x00fe; # latin small letter thorn +$chars{0xf1} = 0x00e6; # latin small letter ae +$chars{0xf2} = 0x0111; # latin small letter d with stroke +$chars{0xf3} = 0x00f0; # latin small letter eth +$chars{0xf5} = 0x0131; # latin small letter dotless i +$chars{0xf6} = 0x0133; # latin small ligature ij +$chars{0xf8} = 0x0142; # latin small letter l with stroke +$chars{0xf9} = 0x00f8; # latin small letter o with stroke +$chars{0xfa} = 0x0153; # latin small ligature oe +$chars{0xfb} = 0x00df; # latin small letter sharp s +$chars{0xfc} = 0x00fe; # latin small letter thorn #### ## Others -$chars{0x97}=0x003c;#3/2leftlowsinglequotationmark -$chars{0x98}=0x003e;#3/2leftlowsinglequotationmark +$chars{0x97} = 0x003c; #3/2leftlowsinglequotationmark +$chars{0x98} = 0x003e; #3/2leftlowsinglequotationmark + #$chars{0x81d1}=0x00b0; # FIXME useless #### ## combined characters iso5426 -$chars{0xc041}=0x1ea2; # capital a with hook above -$chars{0xc045}=0x1eba; # capital e with hook above -$chars{0xc049}=0x1ec8; # capital i with hook above -$chars{0xc04f}=0x1ece; # capital o with hook above -$chars{0xc055}=0x1ee6; # capital u with hook above -$chars{0xc059}=0x1ef6; # capital y with hook above -$chars{0xc061}=0x1ea3; # small a with hook above -$chars{0xc065}=0x1ebb; # small e with hook above -$chars{0xc069}=0x1ec9; # small i with hook above -$chars{0xc06f}=0x1ecf; # small o with hook above -$chars{0xc075}=0x1ee7; # small u with hook above -$chars{0xc079}=0x1ef7; # small y with hook above - - # 4/1 grave accent -$chars{0xc141}=0x00c0; # capital a with grave accent -$chars{0xc145}=0x00c8; # capital e with grave accent -$chars{0xc149}=0x00cc; # capital i with grave accent -$chars{0xc14f}=0x00d2; # capital o with grave accent -$chars{0xc155}=0x00d9; # capital u with grave accent -$chars{0xc157}=0x1e80; # capital w with grave -$chars{0xc159}=0x1ef2; # capital y with grave -$chars{0xc161}=0x00e0; # small a with grave accent -$chars{0xc165}=0x00e8; # small e with grave accent -$chars{0xc169}=0x00ec; # small i with grave accent -$chars{0xc16f}=0x00f2; # small o with grave accent -$chars{0xc175}=0x00f9; # small u with grave accent -$chars{0xc177}=0x1e81; # small w with grave -$chars{0xc179}=0x1ef3; # small y with grave - # 4/2 acute accent -$chars{0xc241}=0x00c1; # capital a with acute accent -$chars{0xc243}=0x0106; # capital c with acute accent -$chars{0xc245}=0x00c9; # capital e with acute accent -$chars{0xc247}=0x01f4; # capital g with acute -$chars{0xc249}=0x00cd; # capital i with acute accent -$chars{0xc24b}=0x1e30; # capital k with acute -$chars{0xc24c}=0x0139; # capital l with acute accent -$chars{0xc24d}=0x1e3e; # capital m with acute -$chars{0xc24e}=0x0143; # capital n with acute accent -$chars{0xc24f}=0x00d3; # capital o with acute accent -$chars{0xc250}=0x1e54; # capital p with acute -$chars{0xc252}=0x0154; # capital r with acute accent -$chars{0xc253}=0x015a; # capital s with acute accent -$chars{0xc255}=0x00da; # capital u with acute accent -$chars{0xc257}=0x1e82; # capital w with acute -$chars{0xc259}=0x00dd; # capital y with acute accent -$chars{0xc25a}=0x0179; # capital z with acute accent -$chars{0xc261}=0x00e1; # small a with acute accent -$chars{0xc263}=0x0107; # small c with acute accent -$chars{0xc265}=0x00e9; # small e with acute accent -$chars{0xc267}=0x01f5; # small g with acute -$chars{0xc269}=0x00ed; # small i with acute accent -$chars{0xc26b}=0x1e31; # small k with acute -$chars{0xc26c}=0x013a; # small l with acute accent -$chars{0xc26d}=0x1e3f; # small m with acute -$chars{0xc26e}=0x0144; # small n with acute accent -$chars{0xc26f}=0x00f3; # small o with acute accent -$chars{0xc270}=0x1e55; # small p with acute -$chars{0xc272}=0x0155; # small r with acute accent -$chars{0xc273}=0x015b; # small s with acute accent -$chars{0xc275}=0x00fa; # small u with acute accent -$chars{0xc277}=0x1e83; # small w with acute -$chars{0xc279}=0x00fd; # small y with acute accent -$chars{0xc27a}=0x017a; # small z with acute accent -$chars{0xc2e1}=0x01fc; # capital ae with acute -$chars{0xc2f1}=0x01fd; # small ae with acute - # 4/3 circumflex accent -$chars{0xc341}=0x00c2; # capital a with circumflex accent -$chars{0xc343}=0x0108; # capital c with circumflex -$chars{0xc345}=0x00ca; # capital e with circumflex accent -$chars{0xc347}=0x011c; # capital g with circumflex -$chars{0xc348}=0x0124; # capital h with circumflex -$chars{0xc349}=0x00ce; # capital i with circumflex accent -$chars{0xc34a}=0x0134; # capital j with circumflex -$chars{0xc34f}=0x00d4; # capital o with circumflex accent -$chars{0xc353}=0x015c; # capital s with circumflex -$chars{0xc355}=0x00db; # capital u with circumflex -$chars{0xc357}=0x0174; # capital w with circumflex -$chars{0xc359}=0x0176; # capital y with circumflex -$chars{0xc35a}=0x1e90; # capital z with circumflex -$chars{0xc361}=0x00e2; # small a with circumflex accent -$chars{0xc363}=0x0109; # small c with circumflex -$chars{0xc365}=0x00ea; # small e with circumflex accent -$chars{0xc367}=0x011d; # small g with circumflex -$chars{0xc368}=0x0125; # small h with circumflex -$chars{0xc369}=0x00ee; # small i with circumflex accent -$chars{0xc36a}=0x0135; # small j with circumflex -$chars{0xc36e}=0x00f1; # small n with tilde -$chars{0xc36f}=0x00f4; # small o with circumflex accent -$chars{0xc373}=0x015d; # small s with circumflex -$chars{0xc375}=0x00fb; # small u with circumflex -$chars{0xc377}=0x0175; # small w with circumflex -$chars{0xc379}=0x0177; # small y with circumflex -$chars{0xc37a}=0x1e91; # small z with circumflex - # 4/4 tilde -$chars{0xc441}=0x00c3; # capital a with tilde -$chars{0xc445}=0x1ebc; # capital e with tilde -$chars{0xc449}=0x0128; # capital i with tilde -$chars{0xc44e}=0x00d1; # capital n with tilde -$chars{0xc44f}=0x00d5; # capital o with tilde -$chars{0xc455}=0x0168; # capital u with tilde -$chars{0xc456}=0x1e7c; # capital v with tilde -$chars{0xc459}=0x1ef8; # capital y with tilde -$chars{0xc461}=0x00e3; # small a with tilde -$chars{0xc465}=0x1ebd; # small e with tilde -$chars{0xc469}=0x0129; # small i with tilde -$chars{0xc46e}=0x00f1; # small n with tilde -$chars{0xc46f}=0x00f5; # small o with tilde -$chars{0xc475}=0x0169; # small u with tilde -$chars{0xc476}=0x1e7d; # small v with tilde -$chars{0xc479}=0x1ef9; # small y with tilde - # 4/5 macron -$chars{0xc541}=0x0100; # capital a with macron -$chars{0xc545}=0x0112; # capital e with macron -$chars{0xc547}=0x1e20; # capital g with macron -$chars{0xc549}=0x012a; # capital i with macron -$chars{0xc54f}=0x014c; # capital o with macron -$chars{0xc555}=0x016a; # capital u with macron -$chars{0xc561}=0x0101; # small a with macron -$chars{0xc565}=0x0113; # small e with macron -$chars{0xc567}=0x1e21; # small g with macron -$chars{0xc569}=0x012b; # small i with macron -$chars{0xc56f}=0x014d; # small o with macron -$chars{0xc575}=0x016b; # small u with macron -$chars{0xc572}=0x0159; # small r with macron -$chars{0xc5e1}=0x01e2; # capital ae with macron -$chars{0xc5f1}=0x01e3; # small ae with macron - # 4/6 breve -$chars{0xc641}=0x0102; # capital a with breve -$chars{0xc645}=0x0114; # capital e with breve -$chars{0xc647}=0x011e; # capital g with breve -$chars{0xc649}=0x012c; # capital i with breve -$chars{0xc64f}=0x014e; # capital o with breve -$chars{0xc655}=0x016c; # capital u with breve -$chars{0xc661}=0x0103; # small a with breve -$chars{0xc665}=0x0115; # small e with breve -$chars{0xc667}=0x011f; # small g with breve -$chars{0xc669}=0x012d; # small i with breve -$chars{0xc66f}=0x014f; # small o with breve -$chars{0xc675}=0x016d; # small u with breve - # 4/7 dot above -$chars{0xc7b0}=0x01e1; # Ain with dot above -$chars{0xc742}=0x1e02; # capital b with dot above -$chars{0xc743}=0x010a; # capital c with dot above -$chars{0xc744}=0x1e0a; # capital d with dot above -$chars{0xc745}=0x0116; # capital e with dot above -$chars{0xc746}=0x1e1e; # capital f with dot above -$chars{0xc747}=0x0120; # capital g with dot above -$chars{0xc748}=0x1e22; # capital h with dot above -$chars{0xc749}=0x0130; # capital i with dot above -$chars{0xc74d}=0x1e40; # capital m with dot above -$chars{0xc74e}=0x1e44; # capital n with dot above -$chars{0xc750}=0x1e56; # capital p with dot above -$chars{0xc752}=0x1e58; # capital r with dot above -$chars{0xc753}=0x1e60; # capital s with dot above -$chars{0xc754}=0x1e6a; # capital t with dot above -$chars{0xc757}=0x1e86; # capital w with dot above -$chars{0xc758}=0x1e8a; # capital x with dot above -$chars{0xc759}=0x1e8e; # capital y with dot above -$chars{0xc75a}=0x017b; # capital z with dot above -$chars{0xc761}=0x0227; # small b with dot above -$chars{0xc762}=0x1e03; # small b with dot above -$chars{0xc763}=0x010b; # small c with dot above -$chars{0xc764}=0x1e0b; # small d with dot above -$chars{0xc765}=0x0117; # small e with dot above -$chars{0xc766}=0x1e1f; # small f with dot above -$chars{0xc767}=0x0121; # small g with dot above -$chars{0xc768}=0x1e23; # small h with dot above -$chars{0xc76d}=0x1e41; # small m with dot above -$chars{0xc76e}=0x1e45; # small n with dot above -$chars{0xc770}=0x1e57; # small p with dot above -$chars{0xc772}=0x1e59; # small r with dot above -$chars{0xc773}=0x1e61; # small s with dot above -$chars{0xc774}=0x1e6b; # small t with dot above -$chars{0xc777}=0x1e87; # small w with dot above -$chars{0xc778}=0x1e8b; # small x with dot above -$chars{0xc779}=0x1e8f; # small y with dot above -$chars{0xc77a}=0x017c; # small z with dot above - # 4/8 trema, diaresis -$chars{0xc820}=0x00a8; # diaeresis -$chars{0xc841}=0x00c4; # capital a with diaeresis -$chars{0xc845}=0x00cb; # capital e with diaeresis -$chars{0xc848}=0x1e26; # capital h with diaeresis -$chars{0xc849}=0x00cf; # capital i with diaeresis -$chars{0xc84f}=0x00d6; # capital o with diaeresis -$chars{0xc855}=0x00dc; # capital u with diaeresis -$chars{0xc857}=0x1e84; # capital w with diaeresis -$chars{0xc858}=0x1e8c; # capital x with diaeresis -$chars{0xc859}=0x0178; # capital y with diaeresis -$chars{0xc861}=0x00e4; # small a with diaeresis -$chars{0xc865}=0x00eb; # small e with diaeresis -$chars{0xc868}=0x1e27; # small h with diaeresis -$chars{0xc869}=0x00ef; # small i with diaeresis -$chars{0xc86f}=0x00f6; # small o with diaeresis -$chars{0xc874}=0x1e97; # small t with diaeresis -$chars{0xc875}=0x00fc; # small u with diaeresis -$chars{0xc877}=0x1e85; # small w with diaeresis -$chars{0xc878}=0x1e8d; # small x with diaeresis -$chars{0xc879}=0x00ff; # small y with diaeresis - # 4/9 umlaut -$chars{0xc920}=0x00a8; # [diaeresis] -$chars{0xc961}=0x00e4; # a with umlaut -$chars{0xc965}=0x00eb; # e with umlaut -$chars{0xc969}=0x00ef; # i with umlaut -$chars{0xc96f}=0x00f6; # o with umlaut -$chars{0xc975}=0x00fc; # u with umlaut - # 4/10 circle above -$chars{0xca41}=0x00c5; # capital a with ring above -$chars{0xcaad}=0x016e; # capital u with ring above -$chars{0xca61}=0x00e5; # small a with ring above -$chars{0xca75}=0x016f; # small u with ring above -$chars{0xca77}=0x1e98; # small w with ring above -$chars{0xca79}=0x1e99; # small y with ring above - # 4/11 high comma off centre - # 4/12 inverted high comma centred - # 4/13 double acute accent -$chars{0xcd4f}=0x0150; # capital o with double acute -$chars{0xcd55}=0x0170; # capital u with double acute -$chars{0xcd6f}=0x0151; # small o with double acute -$chars{0xcd75}=0x0171; # small u with double acute - # 4/14 horn -$chars{0xce54}=0x01a0; # latin capital letter o with horn -$chars{0xce55}=0x01af; # latin capital letter u with horn -$chars{0xce74}=0x01a1; # latin small letter o with horn -$chars{0xce75}=0x01b0; # latin small letter u with horn - # 4/15 caron (hacek -$chars{0xcf41}=0x01cd; # capital a with caron -$chars{0xcf43}=0x010c; # capital c with caron -$chars{0xcf44}=0x010e; # capital d with caron -$chars{0xcf45}=0x011a; # capital e with caron -$chars{0xcf47}=0x01e6; # capital g with caron -$chars{0xcf49}=0x01cf; # capital i with caron -$chars{0xcf4b}=0x01e8; # capital k with caron -$chars{0xcf4c}=0x013d; # capital l with caron -$chars{0xcf4e}=0x0147; # capital n with caron -$chars{0xcf4f}=0x01d1; # capital o with caron -$chars{0xcf52}=0x0158; # capital r with caron -$chars{0xcf53}=0x0160; # capital s with caron -$chars{0xcf54}=0x0164; # capital t with caron -$chars{0xcf55}=0x01d3; # capital u with caron -$chars{0xcf5a}=0x017d; # capital z with caron -$chars{0xcf61}=0x01ce; # small a with caron -$chars{0xcf63}=0x010d; # small c with caron -$chars{0xcf64}=0x010f; # small d with caron -$chars{0xcf65}=0x011b; # small e with caron -$chars{0xcf67}=0x01e7; # small g with caron -$chars{0xcf69}=0x01d0; # small i with caron -$chars{0xcf6a}=0x01f0; # small j with caron -$chars{0xcf6b}=0x01e9; # small k with caron -$chars{0xcf6c}=0x013e; # small l with caron -$chars{0xcf6e}=0x0148; # small n with caron -$chars{0xcf6f}=0x01d2; # small o with caron -$chars{0xcf72}=0x0159; # small r with caron -$chars{0xcf73}=0x0161; # small s with caron -$chars{0xcf74}=0x0165; # small t with caron -$chars{0xcf75}=0x01d4; # small u with caron -$chars{0xcf7a}=0x017e; # small z with caron - # 5/0 cedilla -$chars{0xd020}=0x00b8; # cedilla -$chars{0xd043}=0x00c7; # capital c with cedilla -$chars{0xd044}=0x1e10; # capital d with cedilla -$chars{0xd047}=0x0122; # capital g with cedilla -$chars{0xd048}=0x1e28; # capital h with cedilla -$chars{0xd04b}=0x0136; # capital k with cedilla -$chars{0xd04c}=0x013b; # capital l with cedilla -$chars{0xd04e}=0x0145; # capital n with cedilla -$chars{0xd052}=0x0156; # capital r with cedilla -$chars{0xd053}=0x015e; # capital s with cedilla -$chars{0xd054}=0x0162; # capital t with cedilla -$chars{0xd063}=0x00e7; # small c with cedilla -$chars{0xd064}=0x1e11; # small d with cedilla -$chars{0xd065}=0x0119; # small e with cedilla -$chars{0xd067}=0x0123; # small g with cedilla -$chars{0xd068}=0x1e29; # small h with cedilla -$chars{0xd06b}=0x0137; # small k with cedilla -$chars{0xd06c}=0x013c; # small l with cedilla -$chars{0xd06e}=0x0146; # small n with cedilla -$chars{0xd072}=0x0157; # small r with cedilla -$chars{0xd073}=0x015f; # small s with cedilla -$chars{0xd074}=0x0163; # small t with cedilla - # 5/1 rude - # 5/2 hook to left - # 5/3 ogonek (hook to right -$chars{0xd320}=0x02db; # ogonek -$chars{0xd341}=0x0104; # capital a with ogonek -$chars{0xd345}=0x0118; # capital e with ogonek -$chars{0xd349}=0x012e; # capital i with ogonek -$chars{0xd34f}=0x01ea; # capital o with ogonek -$chars{0xd355}=0x0172; # capital u with ogonek -$chars{0xd361}=0x0105; # small a with ogonek -$chars{0xd365}=0x0119; # small e with ogonek -$chars{0xd369}=0x012f; # small i with ogonek -$chars{0xd36f}=0x01eb; # small o with ogonek -$chars{0xd375}=0x0173; # small u with ogonek - # 5/4 circle below -$chars{0xd441}=0x1e00; # capital a with ring below -$chars{0xd461}=0x1e01; # small a with ring below - # 5/5 half circle below -$chars{0xd548}=0x1e2a; # capital h with breve below -$chars{0xd568}=0x1e2b; # small h with breve below - # 5/6 dot below -$chars{0xd641}=0x1ea0; # capital a with dot below -$chars{0xd642}=0x1e04; # capital b with dot below -$chars{0xd644}=0x1e0c; # capital d with dot below -$chars{0xd645}=0x1eb8; # capital e with dot below -$chars{0xd648}=0x1e24; # capital h with dot below -$chars{0xd649}=0x1eca; # capital i with dot below -$chars{0xd64b}=0x1e32; # capital k with dot below -$chars{0xd64c}=0x1e36; # capital l with dot below -$chars{0xd64d}=0x1e42; # capital m with dot below -$chars{0xd64e}=0x1e46; # capital n with dot below -$chars{0xd64f}=0x1ecc; # capital o with dot below -$chars{0xd652}=0x1e5a; # capital r with dot below -$chars{0xd653}=0x1e62; # capital s with dot below -$chars{0xd654}=0x1e6c; # capital t with dot below -$chars{0xd655}=0x1ee4; # capital u with dot below -$chars{0xd656}=0x1e7e; # capital v with dot below -$chars{0xd657}=0x1e88; # capital w with dot below -$chars{0xd659}=0x1ef4; # capital y with dot below -$chars{0xd65a}=0x1e92; # capital z with dot below -$chars{0xd661}=0x1ea1; # small a with dot below -$chars{0xd662}=0x1e05; # small b with dot below -$chars{0xd664}=0x1e0d; # small d with dot below -$chars{0xd665}=0x1eb9; # small e with dot below -$chars{0xd668}=0x1e25; # small h with dot below -$chars{0xd669}=0x1ecb; # small i with dot below -$chars{0xd66b}=0x1e33; # small k with dot below -$chars{0xd66c}=0x1e37; # small l with dot below -$chars{0xd66d}=0x1e43; # small m with dot below -$chars{0xd66e}=0x1e47; # small n with dot below -$chars{0xd66f}=0x1ecd; # small o with dot below -$chars{0xd672}=0x1e5b; # small r with dot below -$chars{0xd673}=0x1e63; # small s with dot below -$chars{0xd674}=0x1e6d; # small t with dot below -$chars{0xd675}=0x1ee5; # small u with dot below -$chars{0xd676}=0x1e7f; # small v with dot below -$chars{0xd677}=0x1e89; # small w with dot below -$chars{0xd679}=0x1ef5; # small y with dot below -$chars{0xd67a}=0x1e93; # small z with dot below - # 5/7 double dot below -$chars{0xd755}=0x1e72; # capital u with diaeresis below -$chars{0xd775}=0x1e73; # small u with diaeresis below - # 5/8 underline -$chars{0xd820}=0x005f; # underline - # 5/9 double underline -$chars{0xd920}=0x2017; # double underline - # 5/10 small low vertical bar -$chars{0xda20}=0x02cc; # - # 5/11 circumflex below - # 5/12 (this position shall not be used) - # 5/13 left half of ligature sign and of double tilde - # 5/14 right half of ligature sign - # 5/15 right half of double tilde +$chars{0xc041} = 0x1ea2; # capital a with hook above +$chars{0xc045} = 0x1eba; # capital e with hook above +$chars{0xc049} = 0x1ec8; # capital i with hook above +$chars{0xc04f} = 0x1ece; # capital o with hook above +$chars{0xc055} = 0x1ee6; # capital u with hook above +$chars{0xc059} = 0x1ef6; # capital y with hook above +$chars{0xc061} = 0x1ea3; # small a with hook above +$chars{0xc065} = 0x1ebb; # small e with hook above +$chars{0xc069} = 0x1ec9; # small i with hook above +$chars{0xc06f} = 0x1ecf; # small o with hook above +$chars{0xc075} = 0x1ee7; # small u with hook above +$chars{0xc079} = 0x1ef7; # small y with hook above + +# 4/1 grave accent +$chars{0xc141} = 0x00c0; # capital a with grave accent +$chars{0xc145} = 0x00c8; # capital e with grave accent +$chars{0xc149} = 0x00cc; # capital i with grave accent +$chars{0xc14f} = 0x00d2; # capital o with grave accent +$chars{0xc155} = 0x00d9; # capital u with grave accent +$chars{0xc157} = 0x1e80; # capital w with grave +$chars{0xc159} = 0x1ef2; # capital y with grave +$chars{0xc161} = 0x00e0; # small a with grave accent +$chars{0xc165} = 0x00e8; # small e with grave accent +$chars{0xc169} = 0x00ec; # small i with grave accent +$chars{0xc16f} = 0x00f2; # small o with grave accent +$chars{0xc175} = 0x00f9; # small u with grave accent +$chars{0xc177} = 0x1e81; # small w with grave +$chars{0xc179} = 0x1ef3; # small y with grave + # 4/2 acute accent +$chars{0xc241} = 0x00c1; # capital a with acute accent +$chars{0xc243} = 0x0106; # capital c with acute accent +$chars{0xc245} = 0x00c9; # capital e with acute accent +$chars{0xc247} = 0x01f4; # capital g with acute +$chars{0xc249} = 0x00cd; # capital i with acute accent +$chars{0xc24b} = 0x1e30; # capital k with acute +$chars{0xc24c} = 0x0139; # capital l with acute accent +$chars{0xc24d} = 0x1e3e; # capital m with acute +$chars{0xc24e} = 0x0143; # capital n with acute accent +$chars{0xc24f} = 0x00d3; # capital o with acute accent +$chars{0xc250} = 0x1e54; # capital p with acute +$chars{0xc252} = 0x0154; # capital r with acute accent +$chars{0xc253} = 0x015a; # capital s with acute accent +$chars{0xc255} = 0x00da; # capital u with acute accent +$chars{0xc257} = 0x1e82; # capital w with acute +$chars{0xc259} = 0x00dd; # capital y with acute accent +$chars{0xc25a} = 0x0179; # capital z with acute accent +$chars{0xc261} = 0x00e1; # small a with acute accent +$chars{0xc263} = 0x0107; # small c with acute accent +$chars{0xc265} = 0x00e9; # small e with acute accent +$chars{0xc267} = 0x01f5; # small g with acute +$chars{0xc269} = 0x00ed; # small i with acute accent +$chars{0xc26b} = 0x1e31; # small k with acute +$chars{0xc26c} = 0x013a; # small l with acute accent +$chars{0xc26d} = 0x1e3f; # small m with acute +$chars{0xc26e} = 0x0144; # small n with acute accent +$chars{0xc26f} = 0x00f3; # small o with acute accent +$chars{0xc270} = 0x1e55; # small p with acute +$chars{0xc272} = 0x0155; # small r with acute accent +$chars{0xc273} = 0x015b; # small s with acute accent +$chars{0xc275} = 0x00fa; # small u with acute accent +$chars{0xc277} = 0x1e83; # small w with acute +$chars{0xc279} = 0x00fd; # small y with acute accent +$chars{0xc27a} = 0x017a; # small z with acute accent +$chars{0xc2e1} = 0x01fc; # capital ae with acute +$chars{0xc2f1} = 0x01fd; # small ae with acute + # 4/3 circumflex accent +$chars{0xc341} = 0x00c2; # capital a with circumflex accent +$chars{0xc343} = 0x0108; # capital c with circumflex +$chars{0xc345} = 0x00ca; # capital e with circumflex accent +$chars{0xc347} = 0x011c; # capital g with circumflex +$chars{0xc348} = 0x0124; # capital h with circumflex +$chars{0xc349} = 0x00ce; # capital i with circumflex accent +$chars{0xc34a} = 0x0134; # capital j with circumflex +$chars{0xc34f} = 0x00d4; # capital o with circumflex accent +$chars{0xc353} = 0x015c; # capital s with circumflex +$chars{0xc355} = 0x00db; # capital u with circumflex +$chars{0xc357} = 0x0174; # capital w with circumflex +$chars{0xc359} = 0x0176; # capital y with circumflex +$chars{0xc35a} = 0x1e90; # capital z with circumflex +$chars{0xc361} = 0x00e2; # small a with circumflex accent +$chars{0xc363} = 0x0109; # small c with circumflex +$chars{0xc365} = 0x00ea; # small e with circumflex accent +$chars{0xc367} = 0x011d; # small g with circumflex +$chars{0xc368} = 0x0125; # small h with circumflex +$chars{0xc369} = 0x00ee; # small i with circumflex accent +$chars{0xc36a} = 0x0135; # small j with circumflex +$chars{0xc36e} = 0x00f1; # small n with tilde +$chars{0xc36f} = 0x00f4; # small o with circumflex accent +$chars{0xc373} = 0x015d; # small s with circumflex +$chars{0xc375} = 0x00fb; # small u with circumflex +$chars{0xc377} = 0x0175; # small w with circumflex +$chars{0xc379} = 0x0177; # small y with circumflex +$chars{0xc37a} = 0x1e91; # small z with circumflex + # 4/4 tilde +$chars{0xc441} = 0x00c3; # capital a with tilde +$chars{0xc445} = 0x1ebc; # capital e with tilde +$chars{0xc449} = 0x0128; # capital i with tilde +$chars{0xc44e} = 0x00d1; # capital n with tilde +$chars{0xc44f} = 0x00d5; # capital o with tilde +$chars{0xc455} = 0x0168; # capital u with tilde +$chars{0xc456} = 0x1e7c; # capital v with tilde +$chars{0xc459} = 0x1ef8; # capital y with tilde +$chars{0xc461} = 0x00e3; # small a with tilde +$chars{0xc465} = 0x1ebd; # small e with tilde +$chars{0xc469} = 0x0129; # small i with tilde +$chars{0xc46e} = 0x00f1; # small n with tilde +$chars{0xc46f} = 0x00f5; # small o with tilde +$chars{0xc475} = 0x0169; # small u with tilde +$chars{0xc476} = 0x1e7d; # small v with tilde +$chars{0xc479} = 0x1ef9; # small y with tilde + # 4/5 macron +$chars{0xc541} = 0x0100; # capital a with macron +$chars{0xc545} = 0x0112; # capital e with macron +$chars{0xc547} = 0x1e20; # capital g with macron +$chars{0xc549} = 0x012a; # capital i with macron +$chars{0xc54f} = 0x014c; # capital o with macron +$chars{0xc555} = 0x016a; # capital u with macron +$chars{0xc561} = 0x0101; # small a with macron +$chars{0xc565} = 0x0113; # small e with macron +$chars{0xc567} = 0x1e21; # small g with macron +$chars{0xc569} = 0x012b; # small i with macron +$chars{0xc56f} = 0x014d; # small o with macron +$chars{0xc575} = 0x016b; # small u with macron +$chars{0xc572} = 0x0159; # small r with macron +$chars{0xc5e1} = 0x01e2; # capital ae with macron +$chars{0xc5f1} = 0x01e3; # small ae with macron + # 4/6 breve +$chars{0xc641} = 0x0102; # capital a with breve +$chars{0xc645} = 0x0114; # capital e with breve +$chars{0xc647} = 0x011e; # capital g with breve +$chars{0xc649} = 0x012c; # capital i with breve +$chars{0xc64f} = 0x014e; # capital o with breve +$chars{0xc655} = 0x016c; # capital u with breve +$chars{0xc661} = 0x0103; # small a with breve +$chars{0xc665} = 0x0115; # small e with breve +$chars{0xc667} = 0x011f; # small g with breve +$chars{0xc669} = 0x012d; # small i with breve +$chars{0xc66f} = 0x014f; # small o with breve +$chars{0xc675} = 0x016d; # small u with breve + # 4/7 dot above +$chars{0xc7b0} = 0x01e1; # Ain with dot above +$chars{0xc742} = 0x1e02; # capital b with dot above +$chars{0xc743} = 0x010a; # capital c with dot above +$chars{0xc744} = 0x1e0a; # capital d with dot above +$chars{0xc745} = 0x0116; # capital e with dot above +$chars{0xc746} = 0x1e1e; # capital f with dot above +$chars{0xc747} = 0x0120; # capital g with dot above +$chars{0xc748} = 0x1e22; # capital h with dot above +$chars{0xc749} = 0x0130; # capital i with dot above +$chars{0xc74d} = 0x1e40; # capital m with dot above +$chars{0xc74e} = 0x1e44; # capital n with dot above +$chars{0xc750} = 0x1e56; # capital p with dot above +$chars{0xc752} = 0x1e58; # capital r with dot above +$chars{0xc753} = 0x1e60; # capital s with dot above +$chars{0xc754} = 0x1e6a; # capital t with dot above +$chars{0xc757} = 0x1e86; # capital w with dot above +$chars{0xc758} = 0x1e8a; # capital x with dot above +$chars{0xc759} = 0x1e8e; # capital y with dot above +$chars{0xc75a} = 0x017b; # capital z with dot above +$chars{0xc761} = 0x0227; # small b with dot above +$chars{0xc762} = 0x1e03; # small b with dot above +$chars{0xc763} = 0x010b; # small c with dot above +$chars{0xc764} = 0x1e0b; # small d with dot above +$chars{0xc765} = 0x0117; # small e with dot above +$chars{0xc766} = 0x1e1f; # small f with dot above +$chars{0xc767} = 0x0121; # small g with dot above +$chars{0xc768} = 0x1e23; # small h with dot above +$chars{0xc76d} = 0x1e41; # small m with dot above +$chars{0xc76e} = 0x1e45; # small n with dot above +$chars{0xc770} = 0x1e57; # small p with dot above +$chars{0xc772} = 0x1e59; # small r with dot above +$chars{0xc773} = 0x1e61; # small s with dot above +$chars{0xc774} = 0x1e6b; # small t with dot above +$chars{0xc777} = 0x1e87; # small w with dot above +$chars{0xc778} = 0x1e8b; # small x with dot above +$chars{0xc779} = 0x1e8f; # small y with dot above +$chars{0xc77a} = 0x017c; # small z with dot above + # 4/8 trema, diaresis +$chars{0xc820} = 0x00a8; # diaeresis +$chars{0xc841} = 0x00c4; # capital a with diaeresis +$chars{0xc845} = 0x00cb; # capital e with diaeresis +$chars{0xc848} = 0x1e26; # capital h with diaeresis +$chars{0xc849} = 0x00cf; # capital i with diaeresis +$chars{0xc84f} = 0x00d6; # capital o with diaeresis +$chars{0xc855} = 0x00dc; # capital u with diaeresis +$chars{0xc857} = 0x1e84; # capital w with diaeresis +$chars{0xc858} = 0x1e8c; # capital x with diaeresis +$chars{0xc859} = 0x0178; # capital y with diaeresis +$chars{0xc861} = 0x00e4; # small a with diaeresis +$chars{0xc865} = 0x00eb; # small e with diaeresis +$chars{0xc868} = 0x1e27; # small h with diaeresis +$chars{0xc869} = 0x00ef; # small i with diaeresis +$chars{0xc86f} = 0x00f6; # small o with diaeresis +$chars{0xc874} = 0x1e97; # small t with diaeresis +$chars{0xc875} = 0x00fc; # small u with diaeresis +$chars{0xc877} = 0x1e85; # small w with diaeresis +$chars{0xc878} = 0x1e8d; # small x with diaeresis +$chars{0xc879} = 0x00ff; # small y with diaeresis + # 4/9 umlaut +$chars{0xc920} = 0x00a8; # [diaeresis] +$chars{0xc961} = 0x00e4; # a with umlaut +$chars{0xc965} = 0x00eb; # e with umlaut +$chars{0xc969} = 0x00ef; # i with umlaut +$chars{0xc96f} = 0x00f6; # o with umlaut +$chars{0xc975} = 0x00fc; # u with umlaut + # 4/10 circle above +$chars{0xca41} = 0x00c5; # capital a with ring above +$chars{0xcaad} = 0x016e; # capital u with ring above +$chars{0xca61} = 0x00e5; # small a with ring above +$chars{0xca75} = 0x016f; # small u with ring above +$chars{0xca77} = 0x1e98; # small w with ring above +$chars{0xca79} = 0x1e99; # small y with ring above + # 4/11 high comma off centre + # 4/12 inverted high comma centred + # 4/13 double acute accent +$chars{0xcd4f} = 0x0150; # capital o with double acute +$chars{0xcd55} = 0x0170; # capital u with double acute +$chars{0xcd6f} = 0x0151; # small o with double acute +$chars{0xcd75} = 0x0171; # small u with double acute + # 4/14 horn +$chars{0xce54} = 0x01a0; # latin capital letter o with horn +$chars{0xce55} = 0x01af; # latin capital letter u with horn +$chars{0xce74} = 0x01a1; # latin small letter o with horn +$chars{0xce75} = 0x01b0; # latin small letter u with horn + # 4/15 caron (hacek +$chars{0xcf41} = 0x01cd; # capital a with caron +$chars{0xcf43} = 0x010c; # capital c with caron +$chars{0xcf44} = 0x010e; # capital d with caron +$chars{0xcf45} = 0x011a; # capital e with caron +$chars{0xcf47} = 0x01e6; # capital g with caron +$chars{0xcf49} = 0x01cf; # capital i with caron +$chars{0xcf4b} = 0x01e8; # capital k with caron +$chars{0xcf4c} = 0x013d; # capital l with caron +$chars{0xcf4e} = 0x0147; # capital n with caron +$chars{0xcf4f} = 0x01d1; # capital o with caron +$chars{0xcf52} = 0x0158; # capital r with caron +$chars{0xcf53} = 0x0160; # capital s with caron +$chars{0xcf54} = 0x0164; # capital t with caron +$chars{0xcf55} = 0x01d3; # capital u with caron +$chars{0xcf5a} = 0x017d; # capital z with caron +$chars{0xcf61} = 0x01ce; # small a with caron +$chars{0xcf63} = 0x010d; # small c with caron +$chars{0xcf64} = 0x010f; # small d with caron +$chars{0xcf65} = 0x011b; # small e with caron +$chars{0xcf67} = 0x01e7; # small g with caron +$chars{0xcf69} = 0x01d0; # small i with caron +$chars{0xcf6a} = 0x01f0; # small j with caron +$chars{0xcf6b} = 0x01e9; # small k with caron +$chars{0xcf6c} = 0x013e; # small l with caron +$chars{0xcf6e} = 0x0148; # small n with caron +$chars{0xcf6f} = 0x01d2; # small o with caron +$chars{0xcf72} = 0x0159; # small r with caron +$chars{0xcf73} = 0x0161; # small s with caron +$chars{0xcf74} = 0x0165; # small t with caron +$chars{0xcf75} = 0x01d4; # small u with caron +$chars{0xcf7a} = 0x017e; # small z with caron + # 5/0 cedilla +$chars{0xd020} = 0x00b8; # cedilla +$chars{0xd043} = 0x00c7; # capital c with cedilla +$chars{0xd044} = 0x1e10; # capital d with cedilla +$chars{0xd047} = 0x0122; # capital g with cedilla +$chars{0xd048} = 0x1e28; # capital h with cedilla +$chars{0xd04b} = 0x0136; # capital k with cedilla +$chars{0xd04c} = 0x013b; # capital l with cedilla +$chars{0xd04e} = 0x0145; # capital n with cedilla +$chars{0xd052} = 0x0156; # capital r with cedilla +$chars{0xd053} = 0x015e; # capital s with cedilla +$chars{0xd054} = 0x0162; # capital t with cedilla +$chars{0xd063} = 0x00e7; # small c with cedilla +$chars{0xd064} = 0x1e11; # small d with cedilla +$chars{0xd065} = 0x0119; # small e with cedilla +$chars{0xd067} = 0x0123; # small g with cedilla +$chars{0xd068} = 0x1e29; # small h with cedilla +$chars{0xd06b} = 0x0137; # small k with cedilla +$chars{0xd06c} = 0x013c; # small l with cedilla +$chars{0xd06e} = 0x0146; # small n with cedilla +$chars{0xd072} = 0x0157; # small r with cedilla +$chars{0xd073} = 0x015f; # small s with cedilla +$chars{0xd074} = 0x0163; # small t with cedilla + # 5/1 rude + # 5/2 hook to left + # 5/3 ogonek (hook to right +$chars{0xd320} = 0x02db; # ogonek +$chars{0xd341} = 0x0104; # capital a with ogonek +$chars{0xd345} = 0x0118; # capital e with ogonek +$chars{0xd349} = 0x012e; # capital i with ogonek +$chars{0xd34f} = 0x01ea; # capital o with ogonek +$chars{0xd355} = 0x0172; # capital u with ogonek +$chars{0xd361} = 0x0105; # small a with ogonek +$chars{0xd365} = 0x0119; # small e with ogonek +$chars{0xd369} = 0x012f; # small i with ogonek +$chars{0xd36f} = 0x01eb; # small o with ogonek +$chars{0xd375} = 0x0173; # small u with ogonek + # 5/4 circle below +$chars{0xd441} = 0x1e00; # capital a with ring below +$chars{0xd461} = 0x1e01; # small a with ring below + # 5/5 half circle below +$chars{0xd548} = 0x1e2a; # capital h with breve below +$chars{0xd568} = 0x1e2b; # small h with breve below + # 5/6 dot below +$chars{0xd641} = 0x1ea0; # capital a with dot below +$chars{0xd642} = 0x1e04; # capital b with dot below +$chars{0xd644} = 0x1e0c; # capital d with dot below +$chars{0xd645} = 0x1eb8; # capital e with dot below +$chars{0xd648} = 0x1e24; # capital h with dot below +$chars{0xd649} = 0x1eca; # capital i with dot below +$chars{0xd64b} = 0x1e32; # capital k with dot below +$chars{0xd64c} = 0x1e36; # capital l with dot below +$chars{0xd64d} = 0x1e42; # capital m with dot below +$chars{0xd64e} = 0x1e46; # capital n with dot below +$chars{0xd64f} = 0x1ecc; # capital o with dot below +$chars{0xd652} = 0x1e5a; # capital r with dot below +$chars{0xd653} = 0x1e62; # capital s with dot below +$chars{0xd654} = 0x1e6c; # capital t with dot below +$chars{0xd655} = 0x1ee4; # capital u with dot below +$chars{0xd656} = 0x1e7e; # capital v with dot below +$chars{0xd657} = 0x1e88; # capital w with dot below +$chars{0xd659} = 0x1ef4; # capital y with dot below +$chars{0xd65a} = 0x1e92; # capital z with dot below +$chars{0xd661} = 0x1ea1; # small a with dot below +$chars{0xd662} = 0x1e05; # small b with dot below +$chars{0xd664} = 0x1e0d; # small d with dot below +$chars{0xd665} = 0x1eb9; # small e with dot below +$chars{0xd668} = 0x1e25; # small h with dot below +$chars{0xd669} = 0x1ecb; # small i with dot below +$chars{0xd66b} = 0x1e33; # small k with dot below +$chars{0xd66c} = 0x1e37; # small l with dot below +$chars{0xd66d} = 0x1e43; # small m with dot below +$chars{0xd66e} = 0x1e47; # small n with dot below +$chars{0xd66f} = 0x1ecd; # small o with dot below +$chars{0xd672} = 0x1e5b; # small r with dot below +$chars{0xd673} = 0x1e63; # small s with dot below +$chars{0xd674} = 0x1e6d; # small t with dot below +$chars{0xd675} = 0x1ee5; # small u with dot below +$chars{0xd676} = 0x1e7f; # small v with dot below +$chars{0xd677} = 0x1e89; # small w with dot below +$chars{0xd679} = 0x1ef5; # small y with dot below +$chars{0xd67a} = 0x1e93; # small z with dot below + # 5/7 double dot below +$chars{0xd755} = 0x1e72; # capital u with diaeresis below +$chars{0xd775} = 0x1e73; # small u with diaeresis below + # 5/8 underline +$chars{0xd820} = 0x005f; # underline + # 5/9 double underline +$chars{0xd920} = 0x2017; # double underline + # 5/10 small low vertical bar +$chars{0xda20} = 0x02cc; # + # 5/11 circumflex below + # 5/12 (this position shall not be used) + # 5/13 left half of ligature sign and of double tilde + # 5/14 right half of ligature sign + # 5/15 right half of double tilde + # map {printf "%x :%x\n",$_,$chars{$_};}keys %chars; sub char_decode5426 { - my ( $string) = @_; + my ($string) = @_; my $result; - my @data = unpack("C*", $string); + my @data = unpack( "C*", $string ); my @characters; - my $length=scalar(@data); - for (my $i = 0; $i < scalar(@data); $i++) { - my $char= $data[$i]; - if ($char >= 0x00 && $char <= 0x7F){ - #IsAscii - - push @characters,$char unless ($char<0x02 ||$char== 0x0F); - }elsif (($char >= 0xC0 && $char <= 0xDF)) { - #Combined Char - my $convchar ; - if ($chars{$char*256+$data[$i+1]}) { - $convchar= $chars{$char * 256 + $data[$i+1]}; - $i++; -# printf "char %x $char, char to convert %x , converted %x\n",$char,$char * 256 + $data[$i - 1],$convchar; - } elsif ($chars{$char}) { - $convchar= $chars{$char}; -# printf "0xC char %x, converted %x\n",$char,$chars{$char}; - }else { - $convchar=$char; - } - push @characters,$convchar; - } else { - my $convchar; - if ($chars{$char}) { - $convchar= $chars{$char}; -# printf "char %x, converted %x\n",$char,$chars{$char}; - }else { -# printf "char %x $char\n",$char; - $convchar=$char; - } - push @characters,$convchar; - } + my $length = scalar(@data); + for ( my $i = 0 ; $i < scalar(@data) ; $i++ ) { + my $char = $data[$i]; + if ( $char >= 0x00 && $char <= 0x7F ) { + + #IsAscii + + push @characters, $char unless ( $char < 0x02 || $char == 0x0F ); + } elsif ( ( $char >= 0xC0 && $char <= 0xDF ) ) { + + #Combined Char + my $convchar; + if ( $chars{ $char * 256 + $data[ $i + 1 ] } ) { + $convchar = $chars{ $char * 256 + $data[ $i + 1 ] }; + $i++; + + # printf "char %x $char, char to convert %x , converted %x\n",$char,$char * 256 + $data[$i - 1],$convchar; + } elsif ( $chars{$char} ) { + $convchar = $chars{$char}; + + # printf "0xC char %x, converted %x\n",$char,$chars{$char}; + } else { + $convchar = $char; + } + push @characters, $convchar; + } else { + my $convchar; + if ( $chars{$char} ) { + $convchar = $chars{$char}; + + # printf "char %x, converted %x\n",$char,$chars{$char}; + } else { + + # printf "char %x $char\n",$char; + $convchar = $char; + } + push @characters, $convchar; + } } - $result=pack "U*",@characters; -# $result=~s/\x01//; -# $result=~s/\x00//; - $result=~s/\x0f//; - $result=~s/\x1b.//; - $result=~s/\x0e//; - $result=~s/\x1b\x5b//; -# map{printf "%x",$_} @characters; -# printf "\n"; - return $result; + $result = pack "U*", @characters; + + # $result=~s/\x01//; + # $result=~s/\x00//; + $result =~ s/\x0f//; + $result =~ s/\x1b.//; + $result =~ s/\x0e//; + $result =~ s/\x1b\x5b//; + + # map{printf "%x",$_} @characters; + # printf "\n"; + return $result; } 1; - =head1 AUTHOR Koha Development Team diff --git a/C4/Circulation.pm b/C4/Circulation.pm index 80cead8a96..d546bc04f3 100644 --- a/C4/Circulation.pm +++ b/C4/Circulation.pm @@ -25,16 +25,17 @@ use Encode; use C4::Context; use C4::Stats qw( UpdateStats ); -use C4::Reserves qw( CheckReserves CanItemBeReserved MoveReserve ModReserve ModReserveMinusPriority RevertWaitingStatus IsAvailableForItemLevelRequest ); +use C4::Reserves + qw( CheckReserves CanItemBeReserved MoveReserve ModReserve ModReserveMinusPriority RevertWaitingStatus IsAvailableForItemLevelRequest ); use C4::Biblio qw( UpdateTotalIssues ); -use C4::Items qw( ModItemTransfer ModDateLastSeen CartToShelf ); +use C4::Items qw( ModItemTransfer ModDateLastSeen CartToShelf ); use C4::Accounts; use C4::ItemCirculationAlertPreference; use C4::Message; -use C4::Log qw( logaction ); # logaction +use C4::Log qw( logaction ); # logaction use C4::Overdues; use C4::RotatingCollections qw(GetCollectionItemBranches); -use Algorithm::CheckDigits qw( CheckDigits ); +use Algorithm::CheckDigits qw( CheckDigits ); use Data::Dumper qw( Dumper ); use Koha::Account; @@ -63,11 +64,12 @@ use Koha::Exceptions::Checkout; use Koha::Plugins; use Koha::Recalls; use Koha::Library::Hours; -use Carp qw( carp ); +use Carp qw( carp ); use List::MoreUtils qw( any ); -use Scalar::Util qw( looks_like_number blessed ); -use Date::Calc qw( Date_to_Days ); -our (@ISA, @EXPORT_OK); +use Scalar::Util qw( looks_like_number blessed ); +use Date::Calc qw( Date_to_Days ); +our ( @ISA, @EXPORT_OK ); + BEGIN { require Exporter; @@ -75,52 +77,52 @@ BEGIN { # FIXME subs that should probably be elsewhere push @EXPORT_OK, qw( - barcodedecode - LostItem - ReturnLostItem - GetPendingOnSiteCheckouts + barcodedecode + LostItem + ReturnLostItem + GetPendingOnSiteCheckouts - CanBookBeIssued - checkHighHolds - CanBookBeRenewed - AddIssue - GetLoanLength - GetHardDueDate - AddRenewal - GetRenewCount - GetSoonestRenewDate - GetLatestAutoRenewDate - GetIssuingCharges - AddIssuingCharge - GetBranchBorrowerCircRule - GetBranchItemRule - GetBiblioIssues - GetUpcomingDueIssues - CheckIfIssuedToPatron - IsItemIssued - GetAgeRestriction - GetTopIssues + CanBookBeIssued + checkHighHolds + CanBookBeRenewed + AddIssue + GetLoanLength + GetHardDueDate + AddRenewal + GetRenewCount + GetSoonestRenewDate + GetLatestAutoRenewDate + GetIssuingCharges + AddIssuingCharge + GetBranchBorrowerCircRule + GetBranchItemRule + GetBiblioIssues + GetUpcomingDueIssues + CheckIfIssuedToPatron + IsItemIssued + GetAgeRestriction + GetTopIssues - AddReturn - MarkIssueReturned + AddReturn + MarkIssueReturned - transferbook - TooMany - GetTransfersFromTo - CalcDateDue - CheckValidBarcode - IsBranchTransferAllowed - CreateBranchTransferLimit - DeleteBranchTransferLimits - TransferSlip + transferbook + TooMany + GetTransfersFromTo + CalcDateDue + CheckValidBarcode + IsBranchTransferAllowed + CreateBranchTransferLimit + DeleteBranchTransferLimits + TransferSlip - GetOfflineOperations - GetOfflineOperation - AddOfflineOperation - DeleteOfflineOperation - ProcessOfflineOperation - ProcessOfflinePayment - ProcessOfflineIssue + GetOfflineOperations + GetOfflineOperation + AddOfflineOperation + DeleteOfflineOperation + ProcessOfflineOperation + ProcessOfflinePayment + ProcessOfflineIssue ); push @EXPORT_OK, '_GetCircControlBranch'; # This is wrong! } @@ -163,48 +165,51 @@ System Pref options. # FIXME -- these plugins should be moved out of Circulation.pm # sub barcodedecode { - my ($barcode, $filter) = @_; + my ( $barcode, $filter ) = @_; return unless defined $barcode; my $branch = C4::Context::mybranch(); $barcode =~ s/^\s+|\s+$//g; $filter = C4::Context->preference('itemBarcodeInputFilter') unless $filter; - Koha::Plugins->call('item_barcode_transform', \$barcode ); - $filter or return $barcode; # ensure filter is defined, else return untouched barcode - if ($filter eq 'whitespace') { - $barcode =~ s/\s//g; - } elsif ($filter eq 'cuecat') { - chomp($barcode); - my @fields = split( /\./, $barcode ); - my @results = map( C4::Circulation::_decode($_), @fields[ 1 .. $#fields ] ); - ($#results == 2) and return $results[2]; - } elsif ($filter eq 'T-prefix') { - if ($barcode =~ /^[Tt](\d)/) { - (defined($1) and $1 eq '0') and return $barcode; - $barcode = substr($barcode, 2) + 0; # FIXME: probably should be substr($barcode, 1) - } - return sprintf("T%07d", $barcode); + Koha::Plugins->call( 'item_barcode_transform', \$barcode ); + $filter or return $barcode; # ensure filter is defined, else return untouched barcode + if ( $filter eq 'whitespace' ) { + $barcode =~ s/\s//g; + } elsif ( $filter eq 'cuecat' ) { + chomp($barcode); + my @fields = split( /\./, $barcode ); + my @results = map( C4::Circulation::_decode($_), @fields[ 1 .. $#fields ] ); + ( $#results == 2 ) and return $results[2]; + } elsif ( $filter eq 'T-prefix' ) { + if ( $barcode =~ /^[Tt](\d)/ ) { + ( defined($1) and $1 eq '0' ) and return $barcode; + $barcode = substr( $barcode, 2 ) + 0; # FIXME: probably should be substr($barcode, 1) + } + return sprintf( "T%07d", $barcode ); + # FIXME: $barcode could be "T1", causing warning: substr outside of string # Why drop the nonzero digit after the T? # Why pass non-digits (or empty string) to "T%07d"? - } elsif ($filter eq 'libsuite8') { - unless($barcode =~ m/^($branch)-/i){ #if barcode starts with branch code its in Koha style. Skip it. - if($barcode =~ m/^(\d)/i){ #Some barcodes even start with 0's & numbers and are assumed to have b as the item type in the libsuite8 software - $barcode =~ s/^[0]*(\d+)$/$branch-b-$1/i; - }else{ - $barcode =~ s/^(\D+)[0]*(\d+)$/$branch-$1-$2/i; - } - } - } elsif ($filter eq 'EAN13') { + } elsif ( $filter eq 'libsuite8' ) { + unless ( $barcode =~ m/^($branch)-/i ) { #if barcode starts with branch code its in Koha style. Skip it. + if ( $barcode =~ m/^(\d)/i ) + { #Some barcodes even start with 0's & numbers and are assumed to have b as the item type in the libsuite8 software + $barcode =~ s/^[0]*(\d+)$/$branch-b-$1/i; + } else { + $barcode =~ s/^(\D+)[0]*(\d+)$/$branch-$1-$2/i; + } + } + } elsif ( $filter eq 'EAN13' ) { my $ean = CheckDigits('ean'); if ( $ean->is_valid($barcode) ) { + #$barcode = sprintf('%013d',$barcode); # this doesn't work on 32-bit systems $barcode = '0' x ( 13 - length($barcode) ) . $barcode; } else { warn "# [$barcode] not valid EAN-13/UPC-A\n"; } - } + } return $barcode; # return barcode, modified or not } @@ -222,12 +227,12 @@ or Javascript based decoding on the client side. sub _decode { my ($encoded) = @_; - my $seq = - 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+-'; - my @s = map { index( $seq, $_ ); } split( //, $encoded ); - my $l = ( $#s + 1 ) % 4; + my $seq = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+-'; + my @s = map { index( $seq, $_ ); } split( //, $encoded ); + my $l = ( $#s + 1 ) % 4; if ($l) { if ( $l == 1 ) { + # warn "Error: Cuecat decode parsing failed!"; return; } @@ -237,10 +242,7 @@ sub _decode { my $r = ''; while ( $#s >= 0 ) { my $n = ( ( $s[0] << 6 | $s[1] ) << 6 | $s[2] ) << 6 | $s[3]; - $r .= - chr( ( $n >> 16 ) ^ 67 ) - .chr( ( $n >> 8 & 255 ) ^ 67 ) - .chr( ( $n & 255 ) ^ 67 ); + $r .= chr( ( $n >> 16 ) ^ 67 ) . chr( ( $n >> 8 & 255 ) ^ 67 ) . chr( ( $n & 255 ) ^ 67 ); @s = @s[ 4 .. $#s ]; } $r = substr( $r, 0, length($r) - $l ); @@ -318,44 +320,48 @@ A recall for this item was found, and the item needs to be transferred to the re =cut sub transferbook { - my $params = shift; + my $params = shift; my $tbr = $params->{to_branch}; my $fbr = $params->{from_branch}; my $ignoreRs = $params->{ignore_reserves}; my $barcode = $params->{barcode}; my $trigger = $params->{trigger}; my $messages; - my $dotransfer = 1; - my $item = $barcode ? Koha::Items->find( { barcode => $barcode } ) : undef; + my $dotransfer = 1; + my $item = $barcode ? Koha::Items->find( { barcode => $barcode } ) : undef; - Koha::Exceptions::MissingParameter->throw( - "Missing mandatory parameter: from_branch") - unless $fbr; + Koha::Exceptions::MissingParameter->throw("Missing mandatory parameter: from_branch") + unless $fbr; - Koha::Exceptions::MissingParameter->throw( - "Missing mandatory parameter: to_branch") - unless $tbr; + Koha::Exceptions::MissingParameter->throw("Missing mandatory parameter: to_branch") + unless $tbr; # bad barcode.. - unless ( $item ) { + unless ($item) { $messages->{'BadBarcode'} = $barcode; $dotransfer = 0; return ( $dotransfer, $messages ); } my $itemnumber = $item->itemnumber; + # get branches of book... my $hbr = $item->homebranch; # if using Branch Transfer Limits if ( C4::Context->preference("UseBranchTransferLimits") == 1 ) { - my $code = C4::Context->preference("BranchTransferLimitsType") eq 'ccode' ? $item->ccode : $item->biblio->biblioitem->itemtype; # BranchTransferLimitsType is 'ccode' or 'itemtype' - if ( C4::Context->preference("item-level_itypes") && C4::Context->preference("BranchTransferLimitsType") eq 'itemtype' ) { - if ( ! IsBranchTransferAllowed( $tbr, $fbr, $item->itype ) ) { + my $code = + C4::Context->preference("BranchTransferLimitsType") eq 'ccode' + ? $item->ccode + : $item->biblio->biblioitem->itemtype; # BranchTransferLimitsType is 'ccode' or 'itemtype' + if ( C4::Context->preference("item-level_itypes") + && C4::Context->preference("BranchTransferLimitsType") eq 'itemtype' ) + { + if ( !IsBranchTransferAllowed( $tbr, $fbr, $item->itype ) ) { $messages->{'NotAllowed'} = $tbr . "::" . $item->itype; $dotransfer = 0; } - } elsif ( ! IsBranchTransferAllowed( $tbr, $fbr, $code ) ) { + } elsif ( !IsBranchTransferAllowed( $tbr, $fbr, $code ) ) { $messages->{'NotAllowed'} = $tbr . "::" . $code; $dotransfer = 0; } @@ -369,25 +375,25 @@ sub transferbook { # check if it is still issued to someone, return it... my $issue = $item->checkout; - if ( $issue ) { + if ($issue) { AddReturn( $barcode, $fbr ); $messages->{'WasReturned'} = $issue->borrowernumber; } # find reserves..... # That'll save a database query. - my ( $resfound, $resrec, undef ) = - C4::Reserves::CheckReserves( $item ); - if ( $resfound ) { - $resrec->{'ResFound'} = $resfound; + my ( $resfound, $resrec, undef ) = C4::Reserves::CheckReserves($item); + if ($resfound) { + $resrec->{'ResFound'} = $resfound; $messages->{'ResFound'} = $resrec; - $dotransfer = 0 unless $ignoreRs; + $dotransfer = 0 unless $ignoreRs; } # find recall if ( C4::Context->preference('UseRecalls') ) { - my $recall = Koha::Recalls->find({ item_id => $itemnumber, status => 'in_transit' }); + my $recall = Koha::Recalls->find( { item_id => $itemnumber, status => 'in_transit' } ); if ( defined $recall ) { + # do a transfer if the recall branch is different to the item holding branch if ( $recall->pickup_library_id eq $fbr ) { $dotransfer = 0; @@ -407,25 +413,26 @@ sub transferbook { $messages->{'WasTransfered'} = $tbr; } - ModDateLastSeen( $itemnumber ); + ModDateLastSeen($itemnumber); return ( $dotransfer, $messages ); } - sub TooMany { - my ($patron, $item, $params) = @_; - my $onsite_checkout = $params->{onsite_checkout} || 0; + my ( $patron, $item, $params ) = @_; + my $onsite_checkout = $params->{onsite_checkout} || 0; my $switch_onsite_checkout = $params->{switch_onsite_checkout} || 0; - my $cat_borrower = $patron->categorycode; - my $dbh = C4::Context->dbh; - # Get which branchcode we need - my $branch = _GetCircControlBranch($item, $patron); - my $type = $item->effective_itemtype; + my $cat_borrower = $patron->categorycode; + my $dbh = C4::Context->dbh; - my ($type_object, $parent_type, $parent_maxissueqty_rule); - $type_object = Koha::ItemTypes->find( $type ); + # Get which branchcode we need + my $branch = _GetCircControlBranch( $item, $patron ); + my $type = $item->effective_itemtype; + + my ( $type_object, $parent_type, $parent_maxissueqty_rule ); + $type_object = Koha::ItemTypes->find($type); $parent_type = $type_object->parent_type if $type_object; - my $child_types = Koha::ItemTypes->search({ parent_type => $type }); + my $child_types = Koha::ItemTypes->search( { parent_type => $type } ); + # Find any children if we are a parent_type; # given branch, patron category, and item type, determine @@ -439,6 +446,7 @@ sub TooMany { rule_name => 'maxissueqty', } ) if $parent_type; + # If the parent rule is for default type we discount it $parent_maxissueqty_rule = undef if $parent_maxissueqty_rule && !defined $parent_maxissueqty_rule->itemtype; @@ -463,53 +471,55 @@ sub TooMany { # if a rule is found and has a loan limit set, count # how many loans the patron already has that meet that # rule - if (defined($maxissueqty_rule) and $maxissueqty_rule->rule_value ne "") { + if ( defined($maxissueqty_rule) and $maxissueqty_rule->rule_value ne "" ) { my $checkouts; if ( $maxissueqty_rule->branchcode ) { if ( C4::Context->preference('CircControl') eq 'PickupLibrary' ) { - $checkouts = $patron->checkouts->search( - { 'me.branchcode' => $maxissueqty_rule->branchcode } ); - } elsif (C4::Context->preference('CircControl') eq 'PatronLibrary') { + $checkouts = $patron->checkouts->search( { 'me.branchcode' => $maxissueqty_rule->branchcode } ); + } elsif ( C4::Context->preference('CircControl') eq 'PatronLibrary' ) { $checkouts = $patron->checkouts; # if branch is the patron's home branch, then count all loans by patron } else { my $branch_type = C4::Context->preference('HomeOrHoldingBranch') || 'homebranch'; - $checkouts = $patron->checkouts->search( - { "item.$branch_type" => $maxissueqty_rule->branchcode } ); + $checkouts = $patron->checkouts->search( { "item.$branch_type" => $maxissueqty_rule->branchcode } ); } } else { - $checkouts = $patron->checkouts; # if rule is not branch specific then count all loans by patron + $checkouts = $patron->checkouts; # if rule is not branch specific then count all loans by patron } - $checkouts = $checkouts->search(undef, { prefetch => 'item' }); + $checkouts = $checkouts->search( undef, { prefetch => 'item' } ); my $sum_checkouts; my $rule_itemtype = $maxissueqty_rule->itemtype; my @types; unless ( $rule_itemtype || $parent_maxissueqty_rule ) { + # matching rule has the default item type, so count only # those existing loans that don't fall under a more # specific rule @types = Koha::CirculationRules->search( { - branchcode => $maxissueqty_rule->branchcode, + branchcode => $maxissueqty_rule->branchcode, categorycode => [ $maxissueqty_rule->categorycode, $cat_borrower ], - itemtype => { '!=' => undef }, - rule_name => 'maxissueqty' + itemtype => { '!=' => undef }, + rule_name => 'maxissueqty' } )->get_column('itemtype'); } else { - if ( $parent_maxissueqty_rule ) { + if ($parent_maxissueqty_rule) { + # if we have a parent item type then we count loans of the # specific item type or its siblings or parent - my $children = Koha::ItemTypes->search({ parent_type => $parent_type }); + my $children = Koha::ItemTypes->search( { parent_type => $parent_type } ); @types = $children->get_column('itemtype'); push @types, $parent_type; - } elsif ( $child_types ) { + } elsif ($child_types) { + # If we are a parent type, we need to count all child types and our own type @types = $child_types->get_column('itemtype'); - push @types, $type; # And don't forget to count our own types + push @types, $type; # And don't forget to count our own types } else { + # Otherwise only count the specific itemtype push @types, $type; } @@ -519,9 +529,9 @@ sub TooMany { my $itemtype = $c->item->effective_itemtype; unless ( $rule_itemtype || $parent_maxissueqty_rule ) { - next if grep {$_ eq $itemtype} @types; + next if grep { $_ eq $itemtype } @types; } else { - next unless grep {$_ eq $itemtype} @types; + next unless grep { $_ eq $itemtype } @types; } $sum_checkouts->{total}++; @@ -529,29 +539,33 @@ sub TooMany { $sum_checkouts->{itemtype}->{$itemtype}++; } - my $checkout_count_type = $sum_checkouts->{itemtype}->{$type} || 0; - my $checkout_count = $sum_checkouts->{total} || 0; - my $onsite_checkout_count = $sum_checkouts->{onsite_checkouts} || 0; + my $checkout_count_type = $sum_checkouts->{itemtype}->{$type} || 0; + my $checkout_count = $sum_checkouts->{total} || 0; + my $onsite_checkout_count = $sum_checkouts->{onsite_checkouts} || 0; my $checkout_rules = { checkout_count => $checkout_count, onsite_checkout_count => $onsite_checkout_count, onsite_checkout => $onsite_checkout, - max_checkouts_allowed => $maxissueqty_rule ? $maxissueqty_rule->rule_value : undef, + max_checkouts_allowed => $maxissueqty_rule ? $maxissueqty_rule->rule_value : undef, max_onsite_checkouts_allowed => $maxonsiteissueqty_rule ? $maxonsiteissueqty_rule->rule_value : undef, switch_onsite_checkout => $switch_onsite_checkout, circulation_rule => $maxissueqty_rule, onsite_circulation_rule => $maxonsiteissueqty_rule, }; + # If parent rules exists - if ( defined($parent_maxissueqty_rule) and defined($parent_maxissueqty_rule->rule_value) ){ - $checkout_rules->{max_checkouts_allowed} = $parent_maxissueqty_rule ? $parent_maxissueqty_rule->rule_value : undef; + if ( defined($parent_maxissueqty_rule) and defined( $parent_maxissueqty_rule->rule_value ) ) { + $checkout_rules->{max_checkouts_allowed} = + $parent_maxissueqty_rule ? $parent_maxissueqty_rule->rule_value : undef; my $qty_over = _check_max_qty($checkout_rules); return $qty_over if defined $qty_over; # If the parent rule is less than or equal to the child, we only need check the parent - if( $maxissueqty_rule->rule_value < $parent_maxissueqty_rule->rule_value && defined($maxissueqty_rule->itemtype) ) { - $checkout_rules->{checkout_count} = $checkout_count_type; + if ( $maxissueqty_rule->rule_value < $parent_maxissueqty_rule->rule_value + && defined( $maxissueqty_rule->itemtype ) ) + { + $checkout_rules->{checkout_count} = $checkout_count_type; $checkout_rules->{max_checkouts_allowed} = $maxissueqty_rule ? $maxissueqty_rule->rule_value : undef; my $qty_over = _check_max_qty($checkout_rules); return $qty_over if defined $qty_over; @@ -563,24 +577,26 @@ sub TooMany { } # Now count total loans against the limit for the branch - my $branch_borrower_circ_rule = GetBranchBorrowerCircRule($branch, $cat_borrower); - if (defined($branch_borrower_circ_rule->{patron_maxissueqty}) and $branch_borrower_circ_rule->{patron_maxissueqty} ne '') { + my $branch_borrower_circ_rule = GetBranchBorrowerCircRule( $branch, $cat_borrower ); + if ( defined( $branch_borrower_circ_rule->{patron_maxissueqty} ) + and $branch_borrower_circ_rule->{patron_maxissueqty} ne '' ) + { my $checkouts; if ( C4::Context->preference('CircControl') eq 'PickupLibrary' ) { - $checkouts = $patron->checkouts->search( - { 'me.branchcode' => $branch} ); - } elsif (C4::Context->preference('CircControl') eq 'PatronLibrary') { - $checkouts = $patron->checkouts; # if branch is the patron's home branch, then count all loans by patron + $checkouts = $patron->checkouts->search( { 'me.branchcode' => $branch } ); + } elsif ( C4::Context->preference('CircControl') eq 'PatronLibrary' ) { + $checkouts = $patron->checkouts; # if branch is the patron's home branch, then count all loans by patron } else { my $branch_type = C4::Context->preference('HomeOrHoldingBranch') || 'homebranch'; $checkouts = $patron->checkouts->search( - { "item.$branch_type" => $branch}, - { prefetch => 'item' } ); + { "item.$branch_type" => $branch }, + { prefetch => 'item' } + ); } - my $checkout_count = $checkouts->count; - my $onsite_checkout_count = $checkouts->search({ onsite_checkout => 1 })->count; - my $max_checkouts_allowed = $branch_borrower_circ_rule->{patron_maxissueqty}; + my $checkout_count = $checkouts->count; + my $onsite_checkout_count = $checkouts->search( { onsite_checkout => 1 } )->count; + my $max_checkouts_allowed = $branch_borrower_circ_rule->{patron_maxissueqty}; my $max_onsite_checkouts_allowed = $branch_borrower_circ_rule->{patron_maxonsiteissueqty} || undef; my $qty_over = _check_max_qty( @@ -597,7 +613,7 @@ sub TooMany { return $qty_over if defined $qty_over; } - if ( not defined( $maxissueqty_rule ) and not defined($branch_borrower_circ_rule->{patron_maxissueqty}) ) { + if ( not defined($maxissueqty_rule) and not defined( $branch_borrower_circ_rule->{patron_maxissueqty} ) ) { return { reason => 'NO_RULE_DEFINED', max_allowed => 0 }; } @@ -638,12 +654,9 @@ sub _check_max_qty { circulation_rule => $circulation_rule, }; } - } - elsif ( not $onsite_checkout ) { + } elsif ( not $onsite_checkout ) { if ( $max_checkouts_allowed eq '' ) { return; } - if ( - $checkout_count - $onsite_checkout_count >= $max_checkouts_allowed ) - { + if ( $checkout_count - $onsite_checkout_count >= $max_checkouts_allowed ) { return { reason => 'TOO_MANY_CHECKOUTS', count => $checkout_count - $onsite_checkout_count, @@ -780,38 +793,37 @@ sub CanBookBeIssued { my $onsite_checkout = $params->{onsite_checkout} || 0; my $override_high_holds = $params->{override_high_holds} || 0; - my $item_object = !$barcode ? undef : $params->{item} - // Koha::Items->find( { barcode => $barcode } ); + my $item_object = !$barcode ? undef : $params->{item} // Koha::Items->find( { barcode => $barcode } ); # MANDATORY CHECKS - unless item exists, nothing else matters - unless ( $item_object ) { + unless ($item_object) { $issuingimpossible{UNKNOWN_BARCODE} = 1; } return ( \%issuingimpossible, \%needsconfirmation ) if %issuingimpossible; - my $item_unblessed = $item_object->unblessed; # Transition... - my $issue = $item_object->checkout; - my $biblio = $item_object->biblio; + my $item_unblessed = $item_object->unblessed; # Transition... + my $issue = $item_object->checkout; + my $biblio = $item_object->biblio; - my $biblioitem = $biblio->biblioitem; + my $biblioitem = $biblio->biblioitem; my $effective_itemtype = $item_object->effective_itemtype; - my $dbh = C4::Context->dbh; - my $patron_unblessed = $patron->unblessed; + my $dbh = C4::Context->dbh; + my $patron_unblessed = $patron->unblessed; - my $circ_library = Koha::Libraries->find( _GetCircControlBranch($item_object, $patron) ); + my $circ_library = Koha::Libraries->find( _GetCircControlBranch( $item_object, $patron ) ); my $now = dt_from_string(); $duedate ||= CalcDateDue( $now, $effective_itemtype, $circ_library->branchcode, $patron ); - if (DateTime->compare($duedate,$now) == -1 ) { # duedate cannot be before now - $needsconfirmation{INVALID_DATE} = $duedate; + if ( DateTime->compare( $duedate, $now ) == -1 ) { # duedate cannot be before now + $needsconfirmation{INVALID_DATE} = $duedate; } my $fees = Koha::Charges::Fees->new( { - patron => $patron, - library => $circ_library, - item => $item_object, - to_date => $duedate, + patron => $patron, + library => $circ_library, + item => $item_object, + to_date => $duedate, } ); @@ -819,7 +831,8 @@ sub CanBookBeIssued { # BORROWER STATUS # my $patron_borrowing_status = $patron->can_checkout(); - if ( $patron->category->category_type eq 'X' && ( $item_object->barcode )) { + if ( $patron->category->category_type eq 'X' && ( $item_object->barcode ) ) { + # stats only borrower -- add entry to statistics table, and return issuingimpossible{STATS} = 1 . C4::Stats::UpdateStats( { @@ -859,12 +872,12 @@ sub CanBookBeIssued { # # DEBTS - my $account = $patron->account; - my $balance = $account->balance; + my $account = $patron->account; + my $balance = $account->balance; my $non_issues_charges = $account->non_issues_charges; - my $other_charges = $balance - $non_issues_charges; + my $other_charges = $balance - $non_issues_charges; - my $allowfineoverride = C4::Context->preference("AllowFineOverride"); + my $allowfineoverride = C4::Context->preference("AllowFineOverride"); my $allfinesneedoverride = C4::Context->preference("AllFinesNeedOverride"); # Check the debt of this patrons guarantees @@ -927,28 +940,27 @@ sub CanBookBeIssued { } } - - if ($balance > 0 && $other_charges > 0) { + if ( $balance > 0 && $other_charges > 0 ) { $alerts{OTHER_CHARGES} = sprintf( "%.2f", $other_charges ); } - $patron = Koha::Patrons->find( $patron->borrowernumber ); # FIXME Refetch just in case, to avoid regressions. But must not be needed + $patron = Koha::Patrons->find( $patron->borrowernumber ) + ; # FIXME Refetch just in case, to avoid regressions. But must not be needed $patron_unblessed = $patron->unblessed; if ( my $debarred_date = $patron->is_debarred ) { - # patron has accrued fine days or has a restriction. $count is a date - if ($debarred_date eq '9999-12-31') { + + # patron has accrued fine days or has a restriction. $count is a date + if ( $debarred_date eq '9999-12-31' ) { $issuingimpossible{USERBLOCKEDNOENDDATE} = $debarred_date; - } - else { + } else { $issuingimpossible{USERBLOCKEDWITHENDDATE} = $debarred_date; } } elsif ( my $num_overdues = $patron->has_overdues ) { ## patron has outstanding overdue loans - if ( C4::Context->preference("OverduesBlockCirc") eq 'block'){ + if ( C4::Context->preference("OverduesBlockCirc") eq 'block' ) { $issuingimpossible{USERBLOCKEDOVERDUE} = $num_overdues; - } - elsif ( C4::Context->preference("OverduesBlockCirc") eq 'confirmation'){ + } elsif ( C4::Context->preference("OverduesBlockCirc") eq 'confirmation' ) { $needsconfirmation{USERBLOCKEDOVERDUE} = $num_overdues; } } @@ -963,31 +975,29 @@ sub CanBookBeIssued { # # CHECK IF BOOK ALREADY ISSUED TO THIS BORROWER # - if ( $issue && $issue->borrowernumber eq $patron->borrowernumber ){ + if ( $issue && $issue->borrowernumber eq $patron->borrowernumber ) { # Already issued to current borrower. # If it is an on-site checkout if it can be switched to a normal checkout # or ask whether the loan should be renewed if ( $issue->onsite_checkout - and C4::Context->preference('SwitchOnSiteCheckouts') ) { + and C4::Context->preference('SwitchOnSiteCheckouts') ) + { $messages{ONSITE_CHECKOUT_WILL_BE_SWITCHED} = 1; } else { - my ($CanBookBeRenewed,$renewerror) = CanBookBeRenewed($patron, $issue); + my ( $CanBookBeRenewed, $renewerror ) = CanBookBeRenewed( $patron, $issue ); if ( $CanBookBeRenewed == 0 ) { # no more renewals allowed if ( $renewerror eq 'onsite_checkout' ) { $issuingimpossible{NO_RENEWAL_FOR_ONSITE_CHECKOUTS} = 1; - } - else { + } else { $issuingimpossible{NO_MORE_RENEWALS} = 1; } - } - else { + } else { $needsconfirmation{RENEW_ISSUE} = 1; } } - } - elsif ( $issue ) { + } elsif ($issue) { # issued to someone else @@ -997,16 +1007,15 @@ sub CanBookBeIssued { if ( !$can_be_returned ) { $issuingimpossible{RETURN_IMPOSSIBLE} = 1; - $issuingimpossible{branch_to_return} = $message; + $issuingimpossible{branch_to_return} = $message; } else { if ( C4::Context->preference('AutoReturnCheckedOutItems') ) { $alerts{RETURNED_FROM_ANOTHER} = { patron => $patron }; - } - else { - $needsconfirmation{ISSUED_TO_ANOTHER} = 1; - $needsconfirmation{issued_firstname} = $patron->firstname; - $needsconfirmation{issued_surname} = $patron->surname; - $needsconfirmation{issued_cardnumber} = $patron->cardnumber; + } else { + $needsconfirmation{ISSUED_TO_ANOTHER} = 1; + $needsconfirmation{issued_firstname} = $patron->firstname; + $needsconfirmation{issued_surname} = $patron->surname; + $needsconfirmation{issued_cardnumber} = $patron->cardnumber; $needsconfirmation{issued_borrowernumber} = $patron->borrowernumber; } } @@ -1014,12 +1023,16 @@ sub CanBookBeIssued { # JB34 CHECKS IF BORROWERS DON'T HAVE ISSUE TOO MANY BOOKS # - my $switch_onsite_checkout = ( - C4::Context->preference('SwitchOnSiteCheckouts') - and $issue - and $issue->onsite_checkout - and $issue->borrowernumber == $patron->borrowernumber ? 1 : 0 ); - my $toomany = TooMany( $patron, $item_object, { onsite_checkout => $onsite_checkout, switch_onsite_checkout => $switch_onsite_checkout, } ); + my $switch_onsite_checkout = + ( C4::Context->preference('SwitchOnSiteCheckouts') + and $issue + and $issue->onsite_checkout + and $issue->borrowernumber == $patron->borrowernumber ? 1 : 0 ); + my $toomany = TooMany( + $patron, $item_object, + { onsite_checkout => $onsite_checkout, switch_onsite_checkout => $switch_onsite_checkout, } + ); + # if TooMany max_allowed returns 0 the user doesn't have permission to check out this book if ( $toomany && not exists $needsconfirmation{RENEW_ISSUE} ) { if ( $toomany->{max_allowed} == 0 ) { @@ -1042,7 +1055,8 @@ sub CanBookBeIssued { # # CHECKPREVCHECKOUT: CHECK IF ITEM HAS EVER BEEN LENT TO PATRON # - $patron = Koha::Patrons->find( $patron->borrowernumber ); # FIXME Refetch just in case, to avoid regressions. But must not be needed + $patron = Koha::Patrons->find( $patron->borrowernumber ) + ; # FIXME Refetch just in case, to avoid regressions. But must not be needed if ( $patron->wants_check_for_previous_checkout && $patron->do_check_for_previous_checkout($item_unblessed) ) { $needsconfirmation{PREVISSUE} = 1; } @@ -1050,48 +1064,46 @@ sub CanBookBeIssued { # # ITEM CHECKING # - if ( $item_object->notforloan ) - { - if(!C4::Context->preference("AllowNotForLoanOverride")){ - $issuingimpossible{NOT_FOR_LOAN} = 1; + if ( $item_object->notforloan ) { + if ( !C4::Context->preference("AllowNotForLoanOverride") ) { + $issuingimpossible{NOT_FOR_LOAN} = 1; $issuingimpossible{item_notforloan} = $item_object->notforloan; - }else{ + } else { $needsconfirmation{NOT_FOR_LOAN_FORCING} = 1; - $needsconfirmation{item_notforloan} = $item_object->notforloan; + $needsconfirmation{item_notforloan} = $item_object->notforloan; } - } - else { + } else { + # we have to check itemtypes.notforloan also - if (C4::Context->preference('item-level_itypes')){ + if ( C4::Context->preference('item-level_itypes') ) { + # this should probably be a subroutine my $sth = $dbh->prepare("SELECT notforloan FROM itemtypes WHERE itemtype = ?"); $sth->execute($effective_itemtype); - my $notforloan=$sth->fetchrow_hashref(); - if ($notforloan->{'notforloan'}) { - if (!C4::Context->preference("AllowNotForLoanOverride")) { - $issuingimpossible{NOT_FOR_LOAN} = 1; + my $notforloan = $sth->fetchrow_hashref(); + if ( $notforloan->{'notforloan'} ) { + if ( !C4::Context->preference("AllowNotForLoanOverride") ) { + $issuingimpossible{NOT_FOR_LOAN} = 1; $issuingimpossible{itemtype_notforloan} = $effective_itemtype; } else { $needsconfirmation{NOT_FOR_LOAN_FORCING} = 1; - $needsconfirmation{itemtype_notforloan} = $effective_itemtype; + $needsconfirmation{itemtype_notforloan} = $effective_itemtype; } } - } - else { - my $itemtype = Koha::ItemTypes->find($biblioitem->itemtype); - if ( $itemtype && defined $itemtype->notforloan && $itemtype->notforloan == 1){ - if (!C4::Context->preference("AllowNotForLoanOverride")) { - $issuingimpossible{NOT_FOR_LOAN} = 1; + } else { + my $itemtype = Koha::ItemTypes->find( $biblioitem->itemtype ); + if ( $itemtype && defined $itemtype->notforloan && $itemtype->notforloan == 1 ) { + if ( !C4::Context->preference("AllowNotForLoanOverride") ) { + $issuingimpossible{NOT_FOR_LOAN} = 1; $issuingimpossible{itemtype_notforloan} = $effective_itemtype; } else { $needsconfirmation{NOT_FOR_LOAN_FORCING} = 1; - $needsconfirmation{itemtype_notforloan} = $effective_itemtype; + $needsconfirmation{itemtype_notforloan} = $effective_itemtype; } } } } - if ( $item_object->withdrawn && $item_object->withdrawn > 0 ) - { + if ( $item_object->withdrawn && $item_object->withdrawn > 0 ) { $issuingimpossible{WTHDRAWN} = 1; } if ( $item_object->restricted @@ -1100,21 +1112,21 @@ sub CanBookBeIssued { $issuingimpossible{RESTRICTED} = 1; } if ( $item_object->itemlost && C4::Context->preference("IssueLostItem") ne 'nothing' ) { - my $av = Koha::AuthorisedValues->search({ category => 'LOST', authorised_value => $item_object->itemlost }); + my $av = Koha::AuthorisedValues->search( { category => 'LOST', authorised_value => $item_object->itemlost } ); my $code = $av->count ? $av->next->lib : ''; $needsconfirmation{ITEM_LOST} = $code if ( C4::Context->preference("IssueLostItem") eq 'confirm' ); - $alerts{ITEM_LOST} = $code if ( C4::Context->preference("IssueLostItem") eq 'alert' ); + $alerts{ITEM_LOST} = $code if ( C4::Context->preference("IssueLostItem") eq 'alert' ); } if ( C4::Context->preference("IndependentBranches") ) { my $userenv = C4::Context->userenv; unless ( C4::Context->IsSuperLibrarian() ) { my $HomeOrHoldingBranch = C4::Context->preference("HomeOrHoldingBranch"); - if ( $item_object->$HomeOrHoldingBranch ne $userenv->{branch} ){ + if ( $item_object->$HomeOrHoldingBranch ne $userenv->{branch} ) { $issuingimpossible{ITEMNOTSAMEBRANCH} = 1; - $issuingimpossible{'itemhomebranch'} = $item_object->$HomeOrHoldingBranch; + $issuingimpossible{'itemhomebranch'} = $item_object->$HomeOrHoldingBranch; } $needsconfirmation{BORRNOTSAMEBRANCH} = $patron->branchcode - if ( $patron->branchcode ne $userenv->{branch} ); + if ( $patron->branchcode ne $userenv->{branch} ); } } @@ -1139,40 +1151,43 @@ sub CanBookBeIssued { } my $recall; + # CHECK IF ITEM HAS BEEN RECALLED BY ANOTHER PATRON # Only bother doing this if UseRecalls is enabled and the item is recallable # Don't look at recalls that are in transit if ( C4::Context->preference('UseRecalls') and $item_object->can_be_waiting_recall ) { - my @recalls = $biblio->recalls({},{ order_by => { -asc => 'created_date' } })->filter_by_current->as_list; + my @recalls = $biblio->recalls( {}, { order_by => { -asc => 'created_date' } } )->filter_by_current->as_list; - foreach my $r ( @recalls ) { - if ( $r->item_id and - $r->item_id == $item_object->itemnumber and - $r->patron_id == $patron->borrowernumber and - ( $r->waiting or $r->requested ) ) { + foreach my $r (@recalls) { + if ( $r->item_id + and $r->item_id == $item_object->itemnumber + and $r->patron_id == $patron->borrowernumber + and ( $r->waiting or $r->requested ) ) + { $messages{RECALLED} = $r->id; $recall = $r; + # this item is recalled by or already waiting for this borrower and the recall can be fulfilled last; - } - elsif ( $r->item_id and - $r->item_id == $item_object->itemnumber and - $r->in_transit ) { + } elsif ( $r->item_id + and $r->item_id == $item_object->itemnumber + and $r->in_transit ) + { # recalled item is in transit $issuingimpossible{RECALLED_INTRANSIT} = $r->pickup_library_id; - } - elsif ( $r->item_level and - $r->item_id == $item_object->itemnumber and - $r->patron_id != $patron->borrowernumber and - !$r->in_transit ) { + } elsif ( $r->item_level + and $r->item_id == $item_object->itemnumber + and $r->patron_id != $patron->borrowernumber + and !$r->in_transit ) + { # this specific item has been recalled by a different patron $needsconfirmation{RECALLED} = $r; $recall = $r; last; - } - elsif ( !$r->item_level and - $r->patron_id != $patron->borrowernumber and - !$r->in_transit ) { + } elsif ( !$r->item_level + and $r->patron_id != $patron->borrowernumber + and !$r->in_transit ) + { # a different patron has placed a biblio-level recall and this item is eligible to fill it $needsconfirmation{RECALLED} = $r; $recall = $r; @@ -1182,57 +1197,58 @@ sub CanBookBeIssued { } unless ( $ignore_reserves || $recall ) { + # See if the item is on reserve. - my ( $restype, $res ) = C4::Reserves::CheckReserves( $item_object ); + my ( $restype, $res ) = C4::Reserves::CheckReserves($item_object); if ($restype) { my $resbor = $res->{'borrowernumber'}; if ( $resbor ne $patron->borrowernumber ) { - my $patron = Koha::Patrons->find( $resbor ); - if ( $restype eq "Waiting" ) - { + my $patron = Koha::Patrons->find($resbor); + if ( $restype eq "Waiting" ) { + # The item is on reserve and waiting, but has been # reserved by some other patron. - $needsconfirmation{RESERVE_WAITING} = 1; - $needsconfirmation{'resfirstname'} = $patron->firstname; - $needsconfirmation{'ressurname'} = $patron->surname; - $needsconfirmation{'rescardnumber'} = $patron->cardnumber; + $needsconfirmation{RESERVE_WAITING} = 1; + $needsconfirmation{'resfirstname'} = $patron->firstname; + $needsconfirmation{'ressurname'} = $patron->surname; + $needsconfirmation{'rescardnumber'} = $patron->cardnumber; $needsconfirmation{'resborrowernumber'} = $patron->borrowernumber; - $needsconfirmation{'resbranchcode'} = $res->{branchcode}; - $needsconfirmation{'reswaitingdate'} = $res->{'waitingdate'}; - $needsconfirmation{'reserve_id'} = $res->{reserve_id}; - } - elsif ( $restype eq "Reserved" ) { + $needsconfirmation{'resbranchcode'} = $res->{branchcode}; + $needsconfirmation{'reswaitingdate'} = $res->{'waitingdate'}; + $needsconfirmation{'reserve_id'} = $res->{reserve_id}; + } elsif ( $restype eq "Reserved" ) { + # The item is on reserve for someone else. - $needsconfirmation{RESERVED} = 1; - $needsconfirmation{'resfirstname'} = $patron->firstname; - $needsconfirmation{'ressurname'} = $patron->surname; - $needsconfirmation{'rescardnumber'} = $patron->cardnumber; + $needsconfirmation{RESERVED} = 1; + $needsconfirmation{'resfirstname'} = $patron->firstname; + $needsconfirmation{'ressurname'} = $patron->surname; + $needsconfirmation{'rescardnumber'} = $patron->cardnumber; $needsconfirmation{'resborrowernumber'} = $patron->borrowernumber; - $needsconfirmation{'resbranchcode'} = $res->{branchcode}; - $needsconfirmation{'resreservedate'} = $res->{reservedate}; - $needsconfirmation{'reserve_id'} = $res->{reserve_id}; - } - elsif ( $restype eq "Transferred" ) { + $needsconfirmation{'resbranchcode'} = $res->{branchcode}; + $needsconfirmation{'resreservedate'} = $res->{reservedate}; + $needsconfirmation{'reserve_id'} = $res->{reserve_id}; + } elsif ( $restype eq "Transferred" ) { + # The item is determined hold being transferred for someone else. - $needsconfirmation{TRANSFERRED} = 1; - $needsconfirmation{'resfirstname'} = $patron->firstname; - $needsconfirmation{'ressurname'} = $patron->surname; - $needsconfirmation{'rescardnumber'} = $patron->cardnumber; + $needsconfirmation{TRANSFERRED} = 1; + $needsconfirmation{'resfirstname'} = $patron->firstname; + $needsconfirmation{'ressurname'} = $patron->surname; + $needsconfirmation{'rescardnumber'} = $patron->cardnumber; $needsconfirmation{'resborrowernumber'} = $patron->borrowernumber; - $needsconfirmation{'resbranchcode'} = $res->{branchcode}; - $needsconfirmation{'resreservedate'} = $res->{reservedate}; - $needsconfirmation{'reserve_id'} = $res->{reserve_id}; - } - elsif ( $restype eq "Processing" ) { + $needsconfirmation{'resbranchcode'} = $res->{branchcode}; + $needsconfirmation{'resreservedate'} = $res->{reservedate}; + $needsconfirmation{'reserve_id'} = $res->{reserve_id}; + } elsif ( $restype eq "Processing" ) { + # The item is determined hold being processed for someone else. - $needsconfirmation{PROCESSING} = 1; - $needsconfirmation{'resfirstname'} = $patron->firstname; - $needsconfirmation{'ressurname'} = $patron->surname; - $needsconfirmation{'rescardnumber'} = $patron->cardnumber; + $needsconfirmation{PROCESSING} = 1; + $needsconfirmation{'resfirstname'} = $patron->firstname; + $needsconfirmation{'ressurname'} = $patron->surname; + $needsconfirmation{'rescardnumber'} = $patron->cardnumber; $needsconfirmation{'resborrowernumber'} = $patron->borrowernumber; - $needsconfirmation{'resbranchcode'} = $res->{branchcode}; - $needsconfirmation{'resreservedate'} = $res->{reservedate}; - $needsconfirmation{'reserve_id'} = $res->{reserve_id}; + $needsconfirmation{'resbranchcode'} = $res->{branchcode}; + $needsconfirmation{'resreservedate'} = $res->{reservedate}; + $needsconfirmation{'reserve_id'} = $res->{reserve_id}; } } } @@ -1271,13 +1287,12 @@ sub CanBookBeIssued { } ## CHECK AGE RESTRICTION - my $agerestriction = $biblioitem->agerestriction; - my $restriction_age = GetAgeRestriction( $agerestriction ); + my $agerestriction = $biblioitem->agerestriction; + my $restriction_age = GetAgeRestriction($agerestriction); if ( $restriction_age && $patron->dateofbirth && $restriction_age > $patron->get_age() ) { if ( C4::Context->preference('AgeRestrictionOverride') ) { $needsconfirmation{AGE_RESTRICTION} = "$agerestriction"; - } - else { + } else { $issuingimpossible{AGE_RESTRICTION} = "$agerestriction"; } } @@ -1294,26 +1309,28 @@ sub CanBookBeIssued { }; if ($override_high_holds) { $alerts{HIGHHOLDS} = $highholds; - } - else { + } else { $needsconfirmation{HIGHHOLDS} = $highholds; } } } if ( - !C4::Context->preference('AllowMultipleIssuesOnABiblio') && + !C4::Context->preference('AllowMultipleIssuesOnABiblio') + && + # don't do the multiple loans per bib check if we've # already determined that we've got a loan on the same item - !$issuingimpossible{NO_MORE_RENEWALS} && - !$needsconfirmation{RENEW_ISSUE} - ) { + !$issuingimpossible{NO_MORE_RENEWALS} && !$needsconfirmation{RENEW_ISSUE} + ) + { # Check if borrower has already issued an item from the same biblio # Only if it's not a subscription my $biblionumber = $item_object->biblionumber; require C4::Serials; my $is_a_subscription = C4::Serials::CountSubscriptionFromBiblionumber($biblionumber); unless ($is_a_subscription) { + # FIXME Should be $patron->checkouts($args); my $checkouts = Koha::Checkouts->search( { @@ -1324,6 +1341,7 @@ sub CanBookBeIssued { join => 'item', } ); + # if we get here, we don't already have a loan on this item, # so if there are any loans on this bib, ask for confirmation if ( $checkouts->count ) { @@ -1362,26 +1380,29 @@ Returns: =cut sub CanBookBeReturned { - my ($item, $branch) = @_; - my $allowreturntobranch = C4::Context->preference("AllowReturnToBranch") || 'anywhere'; + my ( $item, $branch ) = @_; + my $allowreturntobranch = C4::Context->preference("AllowReturnToBranch") || 'anywhere'; - # assume return is allowed to start - my $allowed = 1; - my $message; + # assume return is allowed to start + my $allowed = 1; + my $message; - # identify all cases where return is forbidden - if ($allowreturntobranch eq 'homebranch' && $branch ne $item->{'homebranch'}) { - $allowed = 0; - $message = $item->{'homebranch'}; - } elsif ($allowreturntobranch eq 'holdingbranch' && $branch ne $item->{'holdingbranch'}) { - $allowed = 0; - $message = $item->{'holdingbranch'}; - } elsif ($allowreturntobranch eq 'homeorholdingbranch' && $branch ne $item->{'homebranch'} && $branch ne $item->{'holdingbranch'}) { - $allowed = 0; - $message = $item->{'homebranch'}; # FIXME: choice of homebranch is arbitrary - } + # identify all cases where return is forbidden + if ( $allowreturntobranch eq 'homebranch' && $branch ne $item->{'homebranch'} ) { + $allowed = 0; + $message = $item->{'homebranch'}; + } elsif ( $allowreturntobranch eq 'holdingbranch' && $branch ne $item->{'holdingbranch'} ) { + $allowed = 0; + $message = $item->{'holdingbranch'}; + } elsif ( $allowreturntobranch eq 'homeorholdingbranch' + && $branch ne $item->{'homebranch'} + && $branch ne $item->{'holdingbranch'} ) + { + $allowed = 0; + $message = $item->{'homebranch'}; # FIXME: choice of homebranch is arbitrary + } - return ($allowed, $message); + return ( $allowed, $message ); } =head2 CheckHighHolds @@ -1403,12 +1424,13 @@ sub checkHighHolds { due_date => undef, }; - # Count holds on this record, ignoring the borrowers own holds as they would be filled by the checkout - my $holds = Koha::Holds->search({ - biblionumber => $item->biblionumber, - borrowernumber => { '!=' => $patron->borrowernumber } - }); + my $holds = Koha::Holds->search( + { + biblionumber => $item->biblionumber, + borrowernumber => { '!=' => $patron->borrowernumber } + } + ); if ( $holds->count() ) { $return_data->{outstanding} = $holds->count(); @@ -1427,8 +1449,7 @@ sub checkHighHolds { if ( $holds->count() <= $decreaseLoanHighHoldsValue ) { return $return_data; } - } - elsif ( $decreaseLoanHighHoldsControl eq 'dynamic' ) { + } elsif ( $decreaseLoanHighHoldsControl eq 'dynamic' ) { # dynamic means X more than the number of holdable items on the record @@ -1443,7 +1464,9 @@ sub checkHighHolds { # Remove any items that are not holdable for this patron # We need to ignore hold counts as the borrower's own hold that will be filled by the checkout # could prevent them from placing further holds - @items = grep { C4::Reserves::CanItemBeReserved( $patron, $_, undef, { ignore_hold_counts => 1 } )->{status} eq 'OK' } @items; + @items = grep { + C4::Reserves::CanItemBeReserved( $patron, $_, undef, { ignore_hold_counts => 1 } )->{status} eq 'OK' + } @items; my $items_count = scalar @items; @@ -1458,7 +1481,7 @@ sub checkHighHolds { my $issuedate = dt_from_string(); - my $itype = $item->effective_itemtype; + my $itype = $item->effective_itemtype; my $daysmode = Koha::CirculationRules->get_effective_daysmode( { categorycode => $patron->categorycode, @@ -1480,15 +1503,16 @@ sub checkHighHolds { ); my $duration; - if ( defined($rule) && $rule ne '' ){ + if ( defined($rule) && $rule ne '' ) { + # overrides decreaseLoanHighHoldsDuration syspref $duration = $rule; } else { $duration = C4::Context->preference('decreaseLoanHighHoldsDuration'); } my $reduced_datedue = $calendar->addDuration( $issuedate, $duration ); - $reduced_datedue->set_hour($orig_due->hour); - $reduced_datedue->set_minute($orig_due->minute); + $reduced_datedue->set_hour( $orig_due->hour ); + $reduced_datedue->set_minute( $orig_due->minute ); $reduced_datedue->truncate( to => 'minute' ); if ( DateTime->compare( $reduced_datedue, $orig_due ) == -1 ) { @@ -1546,13 +1570,13 @@ AddIssue does the following things : sub AddIssue { my ( $patron, $barcode, $datedue, $cancelreserve, $issuedate, $sipmode, $params ) = @_; - my $onsite_checkout = $params && $params->{onsite_checkout} ? 1 : 0; + my $onsite_checkout = $params && $params->{onsite_checkout} ? 1 : 0; my $switch_onsite_checkout = $params && $params->{switch_onsite_checkout}; - my $auto_renew = $params && $params->{auto_renew}; - my $cancel_recall = $params && $params->{cancel_recall}; - my $recall_id = $params && $params->{recall_id}; - my $dbh = C4::Context->dbh; - my $barcodecheck = CheckValidBarcode($barcode); + my $auto_renew = $params && $params->{auto_renew}; + my $cancel_recall = $params && $params->{cancel_recall}; + my $recall_id = $params && $params->{recall_id}; + my $dbh = C4::Context->dbh; + my $barcodecheck = CheckValidBarcode($barcode); my $issue; @@ -1563,8 +1587,7 @@ sub AddIssue { # $issuedate defaults to today. if ( !defined $issuedate ) { $issuedate = dt_from_string(); - } - else { + } else { if ( ref $issuedate ne 'DateTime' ) { $issuedate = dt_from_string($issuedate); @@ -1573,9 +1596,10 @@ sub AddIssue { # Stop here if the patron or barcode doesn't exist if ( $patron && $barcode && $barcodecheck ) { + # find which item we issue - my $item_object = Koha::Items->find({ barcode => $barcode }) - or return; # if we don't get an Item, abort. + my $item_object = Koha::Items->find( { barcode => $barcode } ) + or return; # if we don't get an Item, abort. my $item_unblessed = $item_object->unblessed; my $branchcode = _GetCircControlBranch( $item_object, $patron ); @@ -1584,21 +1608,21 @@ sub AddIssue { my $actualissue = $item_object->checkout; # check if we just renew the issue. - if ( $actualissue and $actualissue->borrowernumber eq $patron->borrowernumber - and not $switch_onsite_checkout ) { + if ( $actualissue + and $actualissue->borrowernumber eq $patron->borrowernumber + and not $switch_onsite_checkout ) + { $datedue = AddRenewal( { - borrowernumber => $patron->borrowernumber, - itemnumber => $item_object->itemnumber, - branch => $branchcode, - datedue => $datedue, - lastreneweddate => - $issuedate, # here interpreted as the renewal date + borrowernumber => $patron->borrowernumber, + itemnumber => $item_object->itemnumber, + branch => $branchcode, + datedue => $datedue, + lastreneweddate => $issuedate, # here interpreted as the renewal date } ); $issue = $item_object->checkout->get_from_storage; - } - else { + } else { unless ($datedue) { my $itype = $item_object->effective_itemtype; @@ -1608,13 +1632,16 @@ sub AddIssue { # Check if we need to use an exact due date set by the ILL module if ( C4::Context->preference('ILLModule') ) { + # Check if there is an ILL connected with the biblio of the item we are issuing - my $ill_request = Koha::ILL::Requests->search({ - biblio_id => $item_object->biblionumber, - borrowernumber => $patron->borrowernumber, - completed => undef, - due_date => { '!=', undef }, - })->next; + my $ill_request = Koha::ILL::Requests->search( + { + biblio_id => $item_object->biblionumber, + borrowernumber => $patron->borrowernumber, + completed => undef, + due_date => { '!=', undef }, + } + )->next; if ( $ill_request and length( $ill_request->due_date ) > 0 ) { my $ill_dt = dt_from_string( $ill_request->due_date ); @@ -1626,23 +1653,25 @@ sub AddIssue { $datedue->truncate( to => 'minute' ); - my $library = Koha::Libraries->find( $branchcode ); - my $fees = Koha::Charges::Fees->new( + my $library = Koha::Libraries->find($branchcode); + my $fees = Koha::Charges::Fees->new( { - patron => $patron, - library => $library, - item => $item_object, - to_date => $datedue, + patron => $patron, + library => $library, + item => $item_object, + to_date => $datedue, } ); # it's NOT a renewal if ( $actualissue and not $switch_onsite_checkout ) { + # This book is currently on loan, but not to the person # who wants to borrow it now. mark it returned before issuing to the new borrower my ( $allowed, $message ) = CanBookBeReturned( $item_unblessed, C4::Context->userenv->{branch} ); return unless $allowed; AddReturn( $item_object->barcode, C4::Context->userenv->{'branch'} ); + # AddReturn certainly has side-effects, like onloan => undef $item_object->discard_changes; } @@ -1662,6 +1691,7 @@ sub AddIssue { # Starting process for transfer job (checking transfert and validate it if we have one) if ( my $transfer = $item_object->get_transfer ) { + # updating line of branchtranfert to finish it, and changing the to branch value, implement a comment for visibility of this case (maybe for stats ....) $transfer->set( { @@ -1672,9 +1702,9 @@ sub AddIssue { )->store; if ( $transfer->reason && $transfer->reason eq 'Reserve' ) { my $hold = $item_object->holds->search( { found => 'T' } )->next; - if ( $hold ) { # Is this really needed? + if ($hold) { # Is this really needed? $hold->set( { found => undef } )->store; - C4::Reserves::ModReserveMinusPriority($item_object->itemnumber, $hold->reserve_id); + C4::Reserves::ModReserveMinusPriority( $item_object->itemnumber, $hold->reserve_id ); } } } @@ -1706,8 +1736,8 @@ sub AddIssue { # no user session exists and C4::Context->userenv() returns # the scalar '0'. Only do this if the syspref says so if ( C4::Context->preference('RecordStaffUserOnCheckout') ) { - my $userenv = C4::Context->userenv(); - my $usernumber = (ref($userenv) eq 'HASH') ? $userenv->{'number'} : undef; + my $userenv = C4::Context->userenv(); + my $usernumber = ( ref($userenv) eq 'HASH' ) ? $userenv->{'number'} : undef; if ($usernumber) { $issue_attributes->{issuer_id} = $usernumber; } @@ -1718,8 +1748,7 @@ sub AddIssue { $issue = Koha::Checkouts->find( { itemnumber => $item_object->itemnumber } ); if ($issue) { $issue->set($issue_attributes)->store; - } - else { + } else { $issue = Koha::Checkout->new( { itemnumber => $item_object->itemnumber, @@ -1735,14 +1764,16 @@ sub AddIssue { } $issue->discard_changes; $patron->update_lastseen('check_out'); - if ( $item_object->location && $item_object->location eq 'CART' - && ( !$item_object->permanent_location || $item_object->permanent_location ne 'CART' ) ) { - ## Item was moved to cart via UpdateItemLocationOnCheckin, anything issued should be taken off the cart. + if ( $item_object->location + && $item_object->location eq 'CART' + && ( !$item_object->permanent_location || $item_object->permanent_location ne 'CART' ) ) + { + ## Item was moved to cart via UpdateItemLocationOnCheckin, anything issued should be taken off the cart. CartToShelf( $item_object->itemnumber ); } # Update item location - $item_object->location_update_trigger( 'checkout' ); + $item_object->location_update_trigger('checkout'); if ( C4::Context->preference('UpdateTotalIssuesOnCirc') ) { UpdateTotalIssues( $item_object->biblionumber, 1, undef, { skip_holds_queue => 1 } ); @@ -1751,10 +1782,10 @@ sub AddIssue { # Record if item was lost my $was_lost = $item_object->itemlost; - $item_object->issues( ( $item_object->issues || 0 ) + 1); - $item_object->holdingbranch(C4::Context->userenv->{'branch'}); + $item_object->issues( ( $item_object->issues || 0 ) + 1 ); + $item_object->holdingbranch( C4::Context->userenv->{'branch'} ); $item_object->itemlost(0); - $item_object->onloan($datedue->ymd()); + $item_object->onloan( $datedue->ymd() ); $item_object->datelastborrowed( dt_from_string()->ymd() ); $item_object->datelastseen( dt_from_string() ); $item_object->store( { log_action => 0, skip_holds_queue => 1 } ); @@ -1780,8 +1811,10 @@ sub AddIssue { return_date => $issuedate } ); - _FixOverduesOnReturn( $patron->borrowernumber, - $item_object->itemnumber, undef, 'RENEWED' ); + _FixOverduesOnReturn( + $patron->borrowernumber, + $item_object->itemnumber, undef, 'RENEWED' + ); } } @@ -1792,7 +1825,7 @@ sub AddIssue { } my $itemtype_object = Koha::ItemTypes->find( $item_object->effective_itemtype ); - if ( $itemtype_object ) { + if ($itemtype_object) { my $accumulate_charge = $fees->accumulate_rentalcharge(); if ( $accumulate_charge > 0 ) { AddIssuingCharge( $issue, $accumulate_charge, 'RENT_DAILY' ); @@ -1805,7 +1838,8 @@ sub AddIssue { if ($rules) { foreach my $key ( keys %$rules ) { if ( $item_object->notforloan eq $key ) { - $item_object->notforloan($rules->{$key})->store({ log_action => 0, skip_record_index => 1 }); + $item_object->notforloan( $rules->{$key} ) + ->store( { log_action => 0, skip_record_index => 1 } ); last; } } @@ -1814,8 +1848,8 @@ sub AddIssue { # Record the fact that this book was issued. C4::Stats::UpdateStats( { - branch => C4::Context->userenv->{'branch'}, - type => ( $onsite_checkout ? 'onsite_checkout' : 'issue' ), + branch => C4::Context->userenv->{'branch'}, + type => ( $onsite_checkout ? 'onsite_checkout' : 'issue' ), amount => $charge, other => ( $sipmode ? "SIP-$sipmode" : '' ), itemnumber => $item_object->itemnumber, @@ -1851,19 +1885,20 @@ sub AddIssue { $item_object->itemnumber, ) if C4::Context->preference("IssueLog"); - Koha::Plugins->call('after_circ_action', { - action => 'checkout', - payload => { - type => ( $onsite_checkout ? 'onsite_checkout' : 'issue' ), - checkout => $issue->get_from_storage + Koha::Plugins->call( + 'after_circ_action', + { + action => 'checkout', + payload => { + type => ( $onsite_checkout ? 'onsite_checkout' : 'issue' ), + checkout => $issue->get_from_storage + } } - }); + ); Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue->new->enqueue( - { - biblio_ids => [ $item_object->biblionumber ] - } - ) if C4::Context->preference('RealTimeHoldsQueue'); + { biblio_ids => [ $item_object->biblionumber ] } ) + if C4::Context->preference('RealTimeHoldsQueue'); } } return $issue; @@ -1887,26 +1922,27 @@ sub GetLoanLength { lengthunit => 'days', }; - my $found = Koha::CirculationRules->get_effective_rules( { - branchcode => $branchcode, - categorycode => $categorycode, - itemtype => $itemtype, - rules => [ - 'issuelength', - 'renewalperiod', - 'lengthunit' - ], - } ); + my $found = Koha::CirculationRules->get_effective_rules( + { + branchcode => $branchcode, + categorycode => $categorycode, + itemtype => $itemtype, + rules => [ + 'issuelength', + 'renewalperiod', + 'lengthunit' + ], + } + ); # Search for rules! - foreach my $rule_name (keys %$found) { + foreach my $rule_name ( keys %$found ) { $rules->{$rule_name} = $found->{$rule_name}; } return $rules; } - =head2 GetHardDueDate my ($hardduedate,$hardduedatecompare) = &GetHardDueDate($borrowertype,$itemtype,branchcode) @@ -1930,8 +1966,7 @@ sub GetHardDueDate { if ( defined( $rules->{hardduedate} ) ) { if ( $rules->{hardduedate} ) { return ( dt_from_string( $rules->{hardduedate}, 'iso' ), $rules->{hardduedatecompare} ); - } - else { + } else { return ( undef, undef ); } } @@ -2027,14 +2062,16 @@ sub GetBranchItemRule { my ( $branchcode, $itemtype ) = @_; # Search for rules! - my $rules = Koha::CirculationRules->get_effective_rules({ - branchcode => $branchcode, - itemtype => $itemtype, - rules => ['holdallowed', 'hold_fulfillment_policy'] - }); + my $rules = Koha::CirculationRules->get_effective_rules( + { + branchcode => $branchcode, + itemtype => $itemtype, + rules => [ 'holdallowed', 'hold_fulfillment_policy' ] + } + ); # built-in default circulation rule - $rules->{holdallowed} //= 'from_any_library'; + $rules->{holdallowed} //= 'from_any_library'; $rules->{hold_fulfillment_policy} //= 'any'; return $rules; @@ -2128,40 +2165,43 @@ patron who last borrowed the book. sub AddReturn { my ( $barcode, $branch, $exemptfine, $return_date, $skip_localuse ) = @_; - if ($branch and not Koha::Libraries->find($branch)) { + if ( $branch and not Koha::Libraries->find($branch) ) { warn "AddReturn error: branch '$branch' not found. Reverting to " . C4::Context->userenv->{'branch'}; undef $branch; } - $branch = C4::Context->userenv->{'branch'} unless $branch; # we trust userenv to be a safe fallback/default + $branch = C4::Context->userenv->{'branch'} unless $branch; # we trust userenv to be a safe fallback/default my $return_date_specified = !!$return_date; $return_date //= dt_from_string(); my $messages; my $patron; - my $doreturn = 1; + my $doreturn = 1; my $validTransfer = 1; - my $stat_type = 'return'; + my $stat_type = 'return'; # get information on item - my $item = Koha::Items->find({ barcode => $barcode }); + my $item = Koha::Items->find( { barcode => $barcode } ); unless ($item) { return ( 0, { BadBarcode => $barcode } ); # no barcode means no item or borrower. bail out. } - my $itemnumber = $item->itemnumber; - my $itemtype = $item->effective_itemtype; + my $itemnumber = $item->itemnumber; + my $itemtype = $item->effective_itemtype; my $localuse_count = $item->localuse || 0; - my $issue = $item->checkout; - if ( $issue ) { + my $issue = $item->checkout; + if ($issue) { $patron = $issue->patron - or die "Data inconsistency: barcode $barcode (itemnumber:$itemnumber) claims to be issued to non-existent borrowernumber '" . $issue->borrowernumber . "'\n" - . Dumper($issue->unblessed) . "\n"; + or die + "Data inconsistency: barcode $barcode (itemnumber:$itemnumber) claims to be issued to non-existent borrowernumber '" + . $issue->borrowernumber . "'\n" + . Dumper( $issue->unblessed ) . "\n"; } else { $messages->{'NotIssued'} = $barcode; $item->onloan(undef)->store( { skip_record_index => 1, skip_holds_queue => 1 } ) if defined $item->onloan; # even though item is not on loan, it may still be transferred; therefore, get current branch info $doreturn = 0; + # No issue, no borrowernumber. ONLY if $doreturn, *might* you have a $borrower later. # Record this as a local use, instead of a return, if the RecordLocalUseOnReturn is on if ( C4::Context->preference("RecordLocalUseOnReturn") ) { @@ -2172,16 +2212,15 @@ sub AddReturn { } } - if ( $item->withdrawn ) { # book has been cancelled + if ( $item->withdrawn ) { # book has been cancelled $messages->{'withdrawn'} = 1; # In the case where we block return of withdrawn, we should completely block the return # without updating item statuses, so we exit early - return ( 0, $messages, $issue, ( $patron ? $patron->unblessed : {} )) + return ( 0, $messages, $issue, ( $patron ? $patron->unblessed : {} ) ) if C4::Context->preference("BlockReturnOfWithdrawnItems"); } - # full item data, but no borrowernumber or checkout info (no issue) my $hbr = Koha::CirculationRules->get_return_branch_policy($item); @@ -2205,13 +2244,13 @@ sub AddReturn { # if $hbr was "noreturn" or any other non-item table value, then it should 'float' (i.e. stay at this branch) my $transfer_trigger = $hbr eq 'homebranch' ? 'ReturnToHome' : $hbr eq 'holdingbranch' ? 'ReturnToHolding' : undef; - my $borrowernumber = $patron ? $patron->borrowernumber : undef; # we don't know if we had a borrower or not - my $patron_unblessed = $patron ? $patron->unblessed : {}; + my $borrowernumber = $patron ? $patron->borrowernumber : undef; # we don't know if we had a borrower or not + my $patron_unblessed = $patron ? $patron->unblessed : {}; # Update item location - my $loc_messages = $item->location_update_trigger( 'checkin' ); + my $loc_messages = $item->location_update_trigger('checkin'); foreach my $loc_msg_key ( keys %$loc_messages ) { - $messages->{ $loc_msg_key } = $loc_messages->{ $loc_msg_key }; + $messages->{$loc_msg_key} = $loc_messages->{$loc_msg_key}; } my $rules = C4::Context->yaml_preference('UpdateNotForLoanStatusOnCheckin'); @@ -2242,16 +2281,16 @@ sub AddReturn { } # check if the return is allowed at this branch - my ($returnallowed, $message) = CanBookBeReturned($item->unblessed, $branch); - unless ($returnallowed){ + my ( $returnallowed, $message ) = CanBookBeReturned( $item->unblessed, $branch ); + unless ($returnallowed) { $messages->{'Wrongbranch'} = { Wrongbranch => $branch, Rightbranch => $message }; $doreturn = 0; - my $indexer = Koha::SearchEngine::Indexer->new({ index => $Koha::SearchEngine::BIBLIOS_INDEX }); + my $indexer = Koha::SearchEngine::Indexer->new( { index => $Koha::SearchEngine::BIBLIOS_INDEX } ); $indexer->index_records( $item->biblionumber, "specialUpdate", "biblioserver" ); - return ( $doreturn, $messages, $issue, $patron_unblessed); + return ( $doreturn, $messages, $issue, $patron_unblessed ); } if ( $item->itemlost and C4::Context->preference("BlockReturnOfLostItems") ) { @@ -2260,28 +2299,38 @@ sub AddReturn { # case of a return of document (deal with issues and holdingbranch) if ($doreturn) { - die "The item is not issed and cannot be returned" unless $issue; # Just in case... + die "The item is not issed and cannot be returned" unless $issue; # Just in case... $patron or warn "AddReturn without current borrower"; if ($patron) { eval { - MarkIssueReturned( $borrowernumber, $item->itemnumber, $return_date, $patron->privacy, { skip_record_index => 1, skip_holds_queue => 1} ); + MarkIssueReturned( + $borrowernumber, $item->itemnumber, $return_date, $patron->privacy, + { skip_record_index => 1, skip_holds_queue => 1 } + ); }; - unless ( $@ ) { + unless ($@) { if ( ( C4::Context->preference('CalculateFinesOnReturn') || ( $return_date_specified && C4::Context->preference('CalculateFinesOnBackdate') ) ) && !$item->itemlost - ) + ) { - _CalculateAndUpdateFine( { issue => $issue, item => $item->unblessed, borrower => $patron_unblessed, return_date => $return_date } ); + _CalculateAndUpdateFine( + { + issue => $issue, item => $item->unblessed, borrower => $patron_unblessed, + return_date => $return_date + } + ); } } else { - carp "The checkin for the following issue failed, Please go to the about page and check all messages on the 'System information' to see if there are configuration / data issues ($@)" . Dumper( $issue->unblessed ); + carp + "The checkin for the following issue failed, Please go to the about page and check all messages on the 'System information' to see if there are configuration / data issues ($@)" + . Dumper( $issue->unblessed ); - my $indexer = Koha::SearchEngine::Indexer->new({ index => $Koha::SearchEngine::BIBLIOS_INDEX }); + my $indexer = Koha::SearchEngine::Indexer->new( { index => $Koha::SearchEngine::BIBLIOS_INDEX } ); $indexer->index_records( $item->biblionumber, "specialUpdate", "biblioserver" ); return ( 0, { WasReturned => 0, DataCorrupted => 1 }, $issue, $patron_unblessed ); @@ -2291,19 +2340,21 @@ sub AddReturn { $messages->{'WasReturned'} = 1; } else { - $item->onloan(undef)->store({ log_action => 0 , skip_record_index => 1, skip_holds_queue => 1 }); + $item->onloan(undef)->store( { log_action => 0, skip_record_index => 1, skip_holds_queue => 1 } ); } } # the holdingbranch is updated if the document is returned to another location. # this is always done regardless of whether the item was on loan or not - if ($item->holdingbranch ne $branch) { - $item->holdingbranch($branch)->store({ log_action => 0, skip_record_index => 1, skip_holds_queue => 1 }); + if ( $item->holdingbranch ne $branch ) { + $item->holdingbranch($branch)->store( { log_action => 0, skip_record_index => 1, skip_holds_queue => 1 } ); } - my $item_was_lost = $item->itemlost; + my $item_was_lost = $item->itemlost; my $leave_item_lost = C4::Context->preference("BlockReturnOfLostItems") ? 1 : 0; - my $updated_item = ModDateLastSeen( $item->itemnumber, $leave_item_lost, { skip_record_index => 1, skip_holds_queue => 1 } ); # will unset itemlost if needed + my $updated_item = + ModDateLastSeen( $item->itemnumber, $leave_item_lost, { skip_record_index => 1, skip_holds_queue => 1 } ) + ; # will unset itemlost if needed # fix up the accounts..... if ($item_was_lost) { @@ -2337,8 +2388,10 @@ sub AddReturn { return_date => $return_date } ); - _FixOverduesOnReturn( $patron_unblessed->{borrowernumber}, - $item->itemnumber, undef, 'RETURNED' ); + _FixOverduesOnReturn( + $patron_unblessed->{borrowernumber}, + $item->itemnumber, undef, 'RETURNED' + ); $messages->{'LostItemFeeCharged'} = 1; } } @@ -2355,24 +2408,23 @@ sub AddReturn { if ( $transfer->tobranch eq $branch ) { $transfer->receive; $messages->{'TransferArrived'} = $transfer->frombranch; + # validTransfer=1 allows us returning the item back if the reserve is cancelled $validTransfer = 1 - if defined $transfer->reason && $transfer->reason eq 'Reserve'; - } - else { + if defined $transfer->reason && $transfer->reason eq 'Reserve'; + } else { $messages->{'WrongTransfer'} = $transfer->tobranch; $messages->{'WrongTransferItem'} = $item->itemnumber; $messages->{'TransferTrigger'} = $transfer->reason; } - } - else { + } else { if ( $transfer->tobranch eq $branch ) { $transfer->receive; $messages->{'TransferArrived'} = $transfer->frombranch; + # validTransfer=1 allows us returning the item back if the reserve is cancelled $validTransfer = 1 if $transfer->reason eq 'Reserve'; - } - else { + } else { $messages->{'TransferTrigger'} = $transfer->reason; if ( $transfer->frombranch eq $branch ) { $messages->{'TransferTo'} = $transfer->tobranch; @@ -2388,46 +2440,53 @@ sub AddReturn { # fix up the overdues in accounts... if ($borrowernumber) { my $fix = _FixOverduesOnReturn( $borrowernumber, $item->itemnumber, $exemptfine, 'RETURNED' ); - defined($fix) or warn "_FixOverduesOnReturn($borrowernumber, ".$item->itemnumber."...) failed!"; # zero is OK, check defined + defined($fix) + or warn "_FixOverduesOnReturn($borrowernumber, " + . $item->itemnumber + . "...) failed!"; # zero is OK, check defined if ( $issue and $issue->is_overdue($return_date) ) { - # fix fine days - my ($debardate,$reminder) = _debar_user_on_return( $patron, $item, dt_from_string($issue->date_due), $return_date ); - if ($debardate and $debardate ne "9999-12-31") { - if ($reminder){ + + # fix fine days + my ( $debardate, $reminder ) = + _debar_user_on_return( $patron, $item, dt_from_string( $issue->date_due ), $return_date ); + if ( $debardate and $debardate ne "9999-12-31" ) { + if ($reminder) { $messages->{'PrevDebarred'} = $debardate; } else { $messages->{'Debarred'} = $debardate; } - } elsif ($patron->debarred) { - if ( $patron->debarred eq "9999-12-31") { + } elsif ( $patron->debarred ) { + if ( $patron->debarred eq "9999-12-31" ) { $messages->{'ForeverDebarred'} = $patron->debarred; } else { my $borrower_debar_dt = dt_from_string( $patron->debarred ); - $borrower_debar_dt->truncate(to => 'day'); - my $today_dt = $return_date->clone()->truncate(to => 'day'); + $borrower_debar_dt->truncate( to => 'day' ); + my $today_dt = $return_date->clone()->truncate( to => 'day' ); if ( DateTime->compare( $borrower_debar_dt, $today_dt ) != -1 ) { $messages->{'PrevDebarred'} = $patron->debarred; } } } - # there's no overdue on the item but borrower had been previously debarred + + # there's no overdue on the item but borrower had been previously debarred } elsif ( $issue->date_due and $patron->debarred ) { - if ( $patron->debarred eq "9999-12-31") { + if ( $patron->debarred eq "9999-12-31" ) { $messages->{'ForeverDebarred'} = $patron->debarred; - } else { - my $borrower_debar_dt = dt_from_string( $patron->debarred ); - $borrower_debar_dt->truncate(to => 'day'); - my $today_dt = $return_date->clone()->truncate(to => 'day'); - if ( DateTime->compare( $borrower_debar_dt, $today_dt ) != -1 ) { - $messages->{'PrevDebarred'} = $patron->debarred; - } - } + } else { + my $borrower_debar_dt = dt_from_string( $patron->debarred ); + $borrower_debar_dt->truncate( to => 'day' ); + my $today_dt = $return_date->clone()->truncate( to => 'day' ); + if ( DateTime->compare( $borrower_debar_dt, $today_dt ) != -1 ) { + $messages->{'PrevDebarred'} = $patron->debarred; + } + } } } # find recalls... if ( C4::Context->preference('UseRecalls') ) { + # check if this item is recallable first, which includes checking if UseRecalls syspref is enabled my $recall = undef; $recall = $item->check_recalls if $item->can_be_waiting_recall; @@ -2441,54 +2500,59 @@ sub AddReturn { # find reserves..... # launch the Checkreserves routine to find any holds - my ($resfound, $resrec); - my $lookahead= C4::Context->preference('ConfirmFutureHolds'); #number of days to look for future holds - ($resfound, $resrec, undef) = C4::Reserves::CheckReserves( $item, $lookahead ) unless ( $item->withdrawn ); + my ( $resfound, $resrec ); + my $lookahead = C4::Context->preference('ConfirmFutureHolds'); #number of days to look for future holds + ( $resfound, $resrec, undef ) = C4::Reserves::CheckReserves( $item, $lookahead ) unless ( $item->withdrawn ); + # if a hold is found and is waiting at another branch, change the priority back to 1 and trigger the hold (this will trigger a transfer and update the hold status properly) if ( $resfound and $resfound eq "Waiting" and $branch ne $resrec->{branchcode} ) { my $hold = C4::Reserves::RevertWaitingStatus( { itemnumber => $item->itemnumber } ); $resfound = 'Reserved'; - $resrec = $hold->unblessed; + $resrec = $hold->unblessed; } if ($resfound) { - $resrec->{'ResFound'} = $resfound; + $resrec->{'ResFound'} = $resfound; $messages->{'ResFound'} = $resrec; } # Record the fact that this book was returned. my $categorycode = $patron_unblessed ? $patron_unblessed->{categorycode} : undef; - C4::Stats::UpdateStats({ - branch => $branch, - type => $stat_type, - itemnumber => $itemnumber, - itemtype => $itemtype, - location => $item->location, - borrowernumber => $borrowernumber, - ccode => $item->ccode, - categorycode => $categorycode, - interface => C4::Context->interface, - }) unless ( $skip_localuse && !$issue ); + C4::Stats::UpdateStats( + { + branch => $branch, + type => $stat_type, + itemnumber => $itemnumber, + itemtype => $itemtype, + location => $item->location, + borrowernumber => $borrowernumber, + ccode => $item->ccode, + categorycode => $categorycode, + interface => C4::Context->interface, + } + ) unless ( $skip_localuse && !$issue ); # Send a check-in slip. # NOTE: borrower may be undef. Do not try to send messages then. - if ( $patron ) { + if ($patron) { my $circulation_alert = 'C4::ItemCirculationAlertPreference'; - my %conditions = ( + my %conditions = ( branchcode => $branch, categorycode => $patron->categorycode, item_type => $itemtype, notification => 'CHECKIN', ); - if ($doreturn && $circulation_alert->is_enabled_for(\%conditions)) { - SendCirculationAlert({ - type => 'CHECKIN', - item => $item->unblessed, - borrower => $patron->unblessed, - branch => $branch, - issue => $issue - }); + if ( $doreturn && $circulation_alert->is_enabled_for( \%conditions ) ) { + SendCirculationAlert( + { + type => 'CHECKIN', + item => $item->unblessed, + borrower => $patron->unblessed, + branch => $branch, + issue => $issue + } + ); } - logaction("CIRCULATION", "RETURN", $borrowernumber, $item->itemnumber) + logaction( "CIRCULATION", "RETURN", $borrowernumber, $item->itemnumber ) if C4::Context->preference("ReturnLog"); #Update borrowers.lastseen @@ -2497,16 +2561,15 @@ sub AddReturn { # Check if this item belongs to a biblio record that is attached to an # ILL request, if it is we need to update the ILL request's status - if ( $doreturn and C4::Context->preference('CirculateILL')) { - my $request = Koha::ILL::Requests->find( - { biblio_id => $item->biblio->biblionumber } - ); + if ( $doreturn and C4::Context->preference('CirculateILL') ) { + my $request = Koha::ILL::Requests->find( { biblio_id => $item->biblio->biblionumber } ); $request->status('RET') if $request; } if ( C4::Context->preference('UseRecalls') ) { + # all recalls that have triggered a transfer will have an allocated itemnumber - my $transfer_recall = Koha::Recalls->find({ item_id => $item->itemnumber, status => 'in_transit' }); + my $transfer_recall = Koha::Recalls->find( { item_id => $item->itemnumber, status => 'in_transit' } ); if ( $transfer_recall and $transfer_recall->pickup_library_id eq $branch ) { $messages->{TransferredRecall} = $transfer_recall; } @@ -2517,7 +2580,8 @@ sub AddReturn { } # Transfer to returnbranch if Automatic transfer set or append message NeedsTransfer - if ( $validTransfer && !C4::RotatingCollections::isItemInAnyCollection( $item->itemnumber ) + if ( $validTransfer + && !C4::RotatingCollections::isItemInAnyCollection( $item->itemnumber ) && ( $doreturn or $messages->{'NotIssued'} ) and !$resfound and ( $branch ne $returnbranch ) @@ -2526,17 +2590,23 @@ sub AddReturn { and not $messages->{TransferredRecall} and not $messages->{RecallNeedsTransfer} ) { - my $BranchTransferLimitsType = C4::Context->preference("BranchTransferLimitsType") eq 'itemtype' ? 'effective_itemtype' : 'ccode'; - if (C4::Context->preference("AutomaticItemReturn" ) or - (C4::Context->preference("UseBranchTransferLimits") and - ! IsBranchTransferAllowed($branch, $returnbranch, $item->$BranchTransferLimitsType ) - )) { - my $transfer = ModItemTransfer($item->itemnumber, $branch, $returnbranch, $transfer_trigger, { skip_record_index => 1 }); - $messages->{'TransferTo'} = $returnbranch; - $messages->{'WasTransfered'} = $transfer->id; + my $BranchTransferLimitsType = + C4::Context->preference("BranchTransferLimitsType") eq 'itemtype' ? 'effective_itemtype' : 'ccode'; + if ( + C4::Context->preference("AutomaticItemReturn") + or ( C4::Context->preference("UseBranchTransferLimits") + and !IsBranchTransferAllowed( $branch, $returnbranch, $item->$BranchTransferLimitsType ) ) + ) + { + my $transfer = ModItemTransfer( + $item->itemnumber, $branch, $returnbranch, $transfer_trigger, + { skip_record_index => 1 } + ); + $messages->{'TransferTo'} = $returnbranch; + $messages->{'WasTransfered'} = $transfer->id; $messages->{'TransferTrigger'} = $transfer_trigger; } else { - $messages->{'NeedsTransfer'} = $returnbranch; + $messages->{'NeedsTransfer'} = $returnbranch; $messages->{'TransferTrigger'} = $transfer_trigger; } } @@ -2575,27 +2645,25 @@ sub AddReturn { $messages->{InBundle} = $host; } - my $indexer = Koha::SearchEngine::Indexer->new({ index => $Koha::SearchEngine::BIBLIOS_INDEX }); + my $indexer = Koha::SearchEngine::Indexer->new( { index => $Koha::SearchEngine::BIBLIOS_INDEX } ); $indexer->index_records( $item->biblionumber, "specialUpdate", "biblioserver" ); if ( $doreturn and $issue ) { - my $checkin = Koha::Old::Checkouts->find($issue->id); + my $checkin = Koha::Old::Checkouts->find( $issue->id ); - Koha::Plugins->call('after_circ_action', { - action => 'checkin', - payload => { - checkout=> $checkin - } - }); - - Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue->new->enqueue( + Koha::Plugins->call( + 'after_circ_action', { - biblio_ids => [ $item->biblionumber ] + action => 'checkin', + payload => { checkout => $checkin } } - ) if C4::Context->preference('RealTimeHoldsQueue'); + ); + + Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue->new->enqueue( { biblio_ids => [ $item->biblionumber ] } ) + if C4::Context->preference('RealTimeHoldsQueue'); } - return ( $doreturn, $messages, $issue, ( $patron ? $patron->unblessed : {} )); + return ( $doreturn, $messages, $issue, ( $patron ? $patron->unblessed : {} ) ); } =head2 MarkIssueReturned @@ -2624,69 +2692,74 @@ sub MarkIssueReturned { my ( $borrowernumber, $itemnumber, $returndate, $privacy, $params ) = @_; # Retrieve the issue - my $issue = Koha::Checkouts->find( { itemnumber => $itemnumber } ) or return; + my $issue = Koha::Checkouts->find( { itemnumber => $itemnumber } ) or return; my $issue_branchcode = $issue->branchcode; - return unless $issue->borrowernumber == $borrowernumber; # If the item is checked out to another patron we do not return it + return + unless $issue->borrowernumber == + $borrowernumber; # If the item is checked out to another patron we do not return it my $issue_id = $issue->issue_id; my $schema = Koha::Database->schema; # FIXME Improve the return value and handle it from callers - $schema->txn_do(sub { + $schema->txn_do( + sub { - my $patron = Koha::Patrons->find( $borrowernumber ); + my $patron = Koha::Patrons->find($borrowernumber); - # Update the returndate value - if ( $returndate ) { - $issue->returndate( $returndate )->store->discard_changes; # update and refetch - } - else { - $issue->returndate( \'NOW()' )->store->discard_changes; # update and refetch - } - - $issue->checkin_library(C4::Context->userenv->{'branch'}); - # Create the old_issues entry - my $old_checkout = Koha::Old::Checkout->new($issue->unblessed)->store; - - # Update accountlines - my $accountlines = Koha::Account::Lines->search( { issue_id => $issue->issue_id } ); - $accountlines->update( { old_issue_id => $issue->issue_id, issue_id => undef } ); - - # anonymise patron checkout immediately if $privacy set to 2 and AnonymousPatron is set to a valid borrowernumber - if ( $privacy && $privacy == 2) { - $old_checkout->anonymize; - } - - # And finally delete the issue - $issue->delete; - - $issue->item->onloan(undef)->store( - { log_action => 0, - skip_record_index => $params->{skip_record_index}, - skip_holds_queue => $params->{skip_holds_queue} + # Update the returndate value + if ($returndate) { + $issue->returndate($returndate)->store->discard_changes; # update and refetch + } else { + $issue->returndate( \'NOW()' )->store->discard_changes; # update and refetch } - ); - if ( C4::Context->preference('StoreLastBorrower') ) { - my $item = Koha::Items->find( $itemnumber ); - $item->last_returned_by( $patron->borrowernumber )->store; - } + $issue->checkin_library( C4::Context->userenv->{'branch'} ); - # Possibly remove any OVERDUES related debarment - my $overdue_restrictions = $patron->restrictions->search( { type => 'OVERDUES' } ); - if ( C4::Context->preference('AutoRemoveOverduesRestrictions') ne 'no' && $patron->is_debarred ) { - my $remove_restrictions = - C4::Context->preference('AutoRemoveOverduesRestrictions') eq 'when_no_overdue_causing_debarment' - ? !$patron->has_restricting_overdues( { issue_branchcode => $issue_branchcode } ) - : !$patron->has_overdues; - if ( $remove_restrictions && $overdue_restrictions->count ) { - DelUniqueDebarment( { borrowernumber => $borrowernumber, type => 'OVERDUES' } ); + # Create the old_issues entry + my $old_checkout = Koha::Old::Checkout->new( $issue->unblessed )->store; + + # Update accountlines + my $accountlines = Koha::Account::Lines->search( { issue_id => $issue->issue_id } ); + $accountlines->update( { old_issue_id => $issue->issue_id, issue_id => undef } ); + + # anonymise patron checkout immediately if $privacy set to 2 and AnonymousPatron is set to a valid borrowernumber + if ( $privacy && $privacy == 2 ) { + $old_checkout->anonymize; } - } - }); + # And finally delete the issue + $issue->delete; + + $issue->item->onloan(undef)->store( + { + log_action => 0, + skip_record_index => $params->{skip_record_index}, + skip_holds_queue => $params->{skip_holds_queue} + } + ); + + if ( C4::Context->preference('StoreLastBorrower') ) { + my $item = Koha::Items->find($itemnumber); + $item->last_returned_by( $patron->borrowernumber )->store; + } + + # Possibly remove any OVERDUES related debarment + my $overdue_restrictions = $patron->restrictions->search( { type => 'OVERDUES' } ); + if ( C4::Context->preference('AutoRemoveOverduesRestrictions') ne 'no' && $patron->is_debarred ) { + my $remove_restrictions = + C4::Context->preference('AutoRemoveOverduesRestrictions') eq 'when_no_overdue_causing_debarment' + ? !$patron->has_restricting_overdues( { issue_branchcode => $issue_branchcode } ) + : !$patron->has_overdues; + if ( $remove_restrictions && $overdue_restrictions->count ) { + DelUniqueDebarment( { borrowernumber => $borrowernumber, type => 'OVERDUES' } ); + } + } + + } + ); return $issue_id; } @@ -2716,13 +2789,14 @@ to ease testing. sub _calculate_new_debar_dt { my ( $patron, $item, $dt_due, $return_date ) = @_; - my $branchcode = _GetCircControlBranch( $item, $patron ); - my $circcontrol = C4::Context->preference('CircControl'); + my $branchcode = _GetCircControlBranch( $item, $patron ); + my $circcontrol = C4::Context->preference('CircControl'); my $issuing_rule = Koha::CirculationRules->get_effective_rules( - { categorycode => $patron->categorycode, + { + categorycode => $patron->categorycode, itemtype => $item->effective_itemtype, branchcode => $branchcode, - rules => [ + rules => [ 'finedays', 'lengthunit', 'firstremind', @@ -2731,9 +2805,9 @@ sub _calculate_new_debar_dt { ] } ); - my $finedays = $issuing_rule ? $issuing_rule->{finedays} : undef; - my $unit = $issuing_rule ? $issuing_rule->{lengthunit} : undef; - my $chargeable_units = C4::Overdues::get_chargeable_units($unit, $dt_due, $return_date, $branchcode); + my $finedays = $issuing_rule ? $issuing_rule->{finedays} : undef; + my $unit = $issuing_rule ? $issuing_rule->{lengthunit} : undef; + my $chargeable_units = C4::Overdues::get_chargeable_units( $unit, $dt_due, $return_date, $branchcode ); return unless $finedays; @@ -2742,42 +2816,40 @@ sub _calculate_new_debar_dt { $finedays = $finedays * 24 if ( $unit eq 'hours' ); # grace period is measured in the same units as the loan - my $grace = - DateTime::Duration->new( $unit => $issuing_rule->{firstremind} // 0); + my $grace = DateTime::Duration->new( $unit => $issuing_rule->{firstremind} // 0 ); - my $deltadays = DateTime::Duration->new( - days => $chargeable_units - ); + my $deltadays = DateTime::Duration->new( days => $chargeable_units ); if ( $deltadays->subtract($grace)->is_positive() ) { my $suspension_days = $deltadays * $finedays; if ( defined $issuing_rule->{suspension_chargeperiod} && $issuing_rule->{suspension_chargeperiod} > 1 ) { + # No need to / 1 and do not consider / 0 $suspension_days = DateTime::Duration->new( - days => floor( $suspension_days->in_units('days') / $issuing_rule->{suspension_chargeperiod} ) - ); + days => floor( $suspension_days->in_units('days') / $issuing_rule->{suspension_chargeperiod} ) ); } # If the max suspension days is < than the suspension days # the suspension days is limited to this maximum period. my $max_sd = $issuing_rule->{maxsuspensiondays}; if ( defined $max_sd && $max_sd ne '' ) { - $max_sd = DateTime::Duration->new( days => $max_sd ); + $max_sd = DateTime::Duration->new( days => $max_sd ); $suspension_days = $max_sd - if DateTime::Duration->compare( $max_sd, $suspension_days ) < 0; + if DateTime::Duration->compare( $max_sd, $suspension_days ) < 0; } - my ( $has_been_extended ); + my ($has_been_extended); if ( C4::Context->preference('CumulativeRestrictionPeriods') and $patron->is_debarred ) { - my $debarment = $patron->restrictions->search({type => 'SUSPENSION' },{rows => 1})->single; - if ( $debarment ) { - $return_date = dt_from_string( $debarment->expiration, 'sql' ); + my $debarment = $patron->restrictions->search( { type => 'SUSPENSION' }, { rows => 1 } )->single; + if ($debarment) { + $return_date = dt_from_string( $debarment->expiration, 'sql' ); $has_been_extended = 1; } } my $new_debar_dt; + # Use the calendar or not to calculate the debarment date if ( C4::Context->preference('SuspensionsCalendar') eq 'noSuspensionsWhenClosed' ) { my $calendar = Koha::Calendar->new( @@ -2785,8 +2857,7 @@ sub _calculate_new_debar_dt { days_mode => 'Calendar' ); $new_debar_dt = $calendar->addDuration( $return_date, $suspension_days ); - } - else { + } else { $new_debar_dt = $return_date->clone()->add_duration($suspension_days); } return $new_debar_dt; @@ -2799,23 +2870,27 @@ sub _debar_user_on_return { $return_date //= dt_from_string(); - my $new_debar_dt = _calculate_new_debar_dt($patron, $item, $dt_due, $return_date); + my $new_debar_dt = _calculate_new_debar_dt( $patron, $item, $dt_due, $return_date ); return unless $new_debar_dt; - Koha::Patron::Debarments::AddUniqueDebarment({ - borrowernumber => $patron->borrowernumber, - expiration => $new_debar_dt->ymd(), - type => 'SUSPENSION', - }); + Koha::Patron::Debarments::AddUniqueDebarment( + { + borrowernumber => $patron->borrowernumber, + expiration => $new_debar_dt->ymd(), + type => 'SUSPENSION', + } + ); + # if borrower was already debarred but does not get an extra debarment - my ($new_debarment_str, $is_a_reminder); + my ( $new_debarment_str, $is_a_reminder ); if ( $patron->is_debarred ) { - $is_a_reminder = 1; + $is_a_reminder = 1; $new_debarment_str = $patron->debarred; } else { $new_debarment_str = $new_debar_dt->ymd(); } + # FIXME Should return a DateTime object return $new_debarment_str, $is_a_reminder; } @@ -2838,15 +2913,15 @@ Internal function sub _FixOverduesOnReturn { my ( $borrowernumber, $item, $exemptfine, $status ) = @_; - unless( $borrowernumber ) { + unless ($borrowernumber) { warn "_FixOverduesOnReturn() not supplied valid borrowernumber"; return; } - unless( $item ) { + unless ($item) { warn "_FixOverduesOnReturn() not supplied valid itemnumber"; return; } - unless( $status ) { + unless ($status) { warn "_FixOverduesOnReturn() not supplied valid status"; return; } @@ -2864,18 +2939,18 @@ sub _FixOverduesOnReturn { status => 'UNRETURNED' } ); - return 0 unless $accountlines->count; # no warning, there's just nothing to fix + return 0 unless $accountlines->count; # no warning, there's just nothing to fix my $accountline = $accountlines->next; - my $payments = $accountline->credits; + my $payments = $accountline->credits; my $amountoutstanding = $accountline->amountoutstanding; if ( $accountline->amount == 0 && $payments->count == 0 ) { $accountline->delete; - return 0; # no warning, we've just removed a zero value fine (backdated return) - } elsif ($exemptfine && ($amountoutstanding != 0)) { - my $account = Koha::Account->new({patron_id => $borrowernumber}); - my $credit = $account->add_credit( + return 0; # no warning, we've just removed a zero value fine (backdated return) + } elsif ( $exemptfine && ( $amountoutstanding != 0 ) ) { + my $account = Koha::Account->new( { patron_id => $borrowernumber } ); + my $credit = $account->add_credit( { amount => $amountoutstanding, user_id => C4::Context->userenv ? C4::Context->userenv->{'number'} : undef, @@ -2886,10 +2961,10 @@ sub _FixOverduesOnReturn { } ); - $credit->apply({ debits => [ $accountline ] }); + $credit->apply( { debits => [$accountline] } ); - if (C4::Context->preference("FinesLog")) { - &logaction("FINES", 'MODIFY',$borrowernumber,"Overdue forgiven: item $item"); + if ( C4::Context->preference("FinesLog") ) { + &logaction( "FINES", 'MODIFY', $borrowernumber, "Overdue forgiven: item $item" ); } } @@ -2918,20 +2993,21 @@ C<$patron> is a patron object. =cut sub _GetCircControlBranch { - my ($item, $patron) = @_; + my ( $item, $patron ) = @_; my $circcontrol = C4::Context->preference('CircControl'); my $branch; - if ($circcontrol eq 'PickupLibrary' and (C4::Context->userenv and C4::Context->userenv->{'branch'}) ) { + if ( $circcontrol eq 'PickupLibrary' and ( C4::Context->userenv and C4::Context->userenv->{'branch'} ) ) { $branch = C4::Context->userenv->{'branch'}; - } elsif ($circcontrol eq 'PatronLibrary') { + } elsif ( $circcontrol eq 'PatronLibrary' ) { $branch = $patron->branchcode; } else { my $branchfield = C4::Context->preference('HomeOrHoldingBranch') || 'homebranch'; $branch = $item->get_column($branchfield); + # default to item home branch if holdingbranch is used # and is not defined - if (!defined($branch) && $branchfield eq 'holdingbranch') { + if ( !defined($branch) && $branchfield eq 'holdingbranch' ) { $branch = $item->homebranch; } } @@ -2959,10 +3035,10 @@ sub GetUpcomingDueIssues { $statement .= $params->{'owning_library'} ? " items.homebranch " : " issues.branchcode "; $statement .= " WHERE returndate is NULL AND TO_DAYS( date_due )-TO_DAYS( NOW() ) BETWEEN 0 AND ?"; my @bind_parameters = ( $params->{'days_in_advance'} ); - - my $sth = $dbh->prepare( $statement ); - $sth->execute( @bind_parameters ); - my $upcoming_dues = $sth->fetchall_arrayref({}); + + my $sth = $dbh->prepare($statement); + $sth->execute(@bind_parameters); + my $upcoming_dues = $sth->fetchall_arrayref( {} ); return $upcoming_dues; } @@ -3003,38 +3079,41 @@ sub CanBookBeRenewed { my $soonest; my $item = $issue->item; - return ( 0, 'no_item' ) unless $item; + return ( 0, 'no_item' ) unless $item; return ( 0, 'no_checkout' ) unless $issue; - return ( 0, 'onsite_checkout' ) if $issue->onsite_checkout; - return ( 0, 'item_issued_to_other_patron') if $issue->borrowernumber != $patron->borrowernumber; - return ( 0, 'item_denied_renewal') if $item->is_denied_renewal; + return ( 0, 'onsite_checkout' ) if $issue->onsite_checkout; + return ( 0, 'item_issued_to_other_patron' ) if $issue->borrowernumber != $patron->borrowernumber; + return ( 0, 'item_denied_renewal' ) if $item->is_denied_renewal; my $final_renewal = 0; my $final_unseen_renewal = 0; # override_limit will override anything else except on_reserve my $branchcode = _GetCircControlBranch( $item, $patron ); - unless ( $override_limit ){ + unless ($override_limit) { - ( $auto_renew, $soonest ) = _CanBookBeAutoRenewed({ - patron => $patron, - item => $item, - branchcode => $branchcode, - issue => $issue - }); + ( $auto_renew, $soonest ) = _CanBookBeAutoRenewed( + { + patron => $patron, + item => $item, + branchcode => $branchcode, + issue => $issue + } + ); return ( 0, $auto_renew, { soonest_renew_date => $soonest } ) if $auto_renew =~ 'auto_too_soon' && $cron; + # cron wants 'too_soon' over 'on_reserve' for performance and to avoid # extra notices being sent. Cron also implies no override - return ( 0, $auto_renew ) if $auto_renew =~ 'auto_account_expired'; - return ( 0, $auto_renew ) if $auto_renew =~ 'auto_too_late'; - return ( 0, $auto_renew ) if $auto_renew =~ 'auto_too_much_oweing'; + return ( 0, $auto_renew ) if $auto_renew =~ 'auto_account_expired'; + return ( 0, $auto_renew ) if $auto_renew =~ 'auto_too_late'; + return ( 0, $auto_renew ) if $auto_renew =~ 'auto_too_much_oweing'; my $issuing_rule = Koha::CirculationRules->get_effective_rules( { categorycode => $patron->categorycode, itemtype => $item->effective_itemtype, branchcode => $branchcode, - rules => [ + rules => [ 'renewalsallowed', 'lengthunit', 'unseen_renewals_allowed' @@ -3043,26 +3122,29 @@ sub CanBookBeRenewed { ); return ( 0, "too_many" ) - if not $issuing_rule->{renewalsallowed} or $issuing_rule->{renewalsallowed} <= $issue->renewals_count; + if not $issuing_rule->{renewalsallowed} + or $issuing_rule->{renewalsallowed} <= $issue->renewals_count; return ( 0, "too_unseen" ) - if C4::Context->preference('UnseenRenewals') && - looks_like_number($issuing_rule->{unseen_renewals_allowed}) && - $issuing_rule->{unseen_renewals_allowed} <= $issue->unseen_renewals; + if C4::Context->preference('UnseenRenewals') + && looks_like_number( $issuing_rule->{unseen_renewals_allowed} ) + && $issuing_rule->{unseen_renewals_allowed} <= $issue->unseen_renewals; $final_renewal = $issuing_rule->{renewalsallowed} == ( $issue->renewals_count + 1 ) ? 1 : 0; $final_unseen_renewal = ( C4::Context->preference('UnseenRenewals') && $issuing_rule->{unseen_renewals_allowed} == ( $issue->unseen_renewals + 1 ) ) ? 1 : 0; - my $overduesblockrenewing = C4::Context->preference('OverduesBlockRenewing'); + my $overduesblockrenewing = C4::Context->preference('OverduesBlockRenewing'); my $restrictionblockrenewing = C4::Context->preference('RestrictionBlockRenewing'); - my $restricted = $patron->is_debarred; - my $hasoverdues = $patron->has_overdues; + my $restricted = $patron->is_debarred; + my $hasoverdues = $patron->has_overdues; if ( $restricted and $restrictionblockrenewing ) { - return ( 0, 'restriction'); - } elsif ( ($hasoverdues and $overduesblockrenewing eq 'block') || ($issue->is_overdue and $overduesblockrenewing eq 'blockitem') ) { - return ( 0, 'overdue'); + return ( 0, 'restriction' ); + } elsif ( ( $hasoverdues and $overduesblockrenewing eq 'block' ) + || ( $issue->is_overdue and $overduesblockrenewing eq 'blockitem' ) ) + { + return ( 0, 'overdue' ); } } @@ -3072,9 +3154,11 @@ sub CanBookBeRenewed { $recall = $item->check_recalls if $item->can_be_waiting_recall; if ( defined $recall ) { if ( $recall->item_level ) { + # item-level recall. check if this item is the recalled item, otherwise renewal will be allowed return ( 0, 'recalled' ) if ( $recall->item_id == $item->itemnumber ); } else { + # biblio-level recall, so only disallow renewal if the biblio-level recall has been fulfilled by a different item return ( 0, 'recalled' ) unless ( $recall->waiting ); } @@ -3083,48 +3167,54 @@ sub CanBookBeRenewed { # There is an item level hold on this item, no other item can fill the hold return ( 0, "on_reserve" ) - if ( $item->current_holds->search( { non_priority => 0 } )->count ); - + if ( $item->current_holds->search( { non_priority => 0 } )->count ); my ( $status, $matched_reserve, $possible_holds ) = C4::Reserves::CheckReserves($item); my @fillable_holds = (); foreach my $possible_hold ( @{$possible_holds} ) { push @fillable_holds, $possible_hold unless $possible_hold->{non_priority}; } - if ( @fillable_holds ) { + if (@fillable_holds) { if ( C4::Context->preference('AllowRenewalIfOtherItemsAvailable') ) { # Get all other items that could possibly fill reserves # FIXME We could join reserves (or more tables) here to eliminate some checks later - my @other_items = Koha::Items->search({ - biblionumber => $item->biblionumber, - onloan => undef, - notforloan => 0, - -not => { itemnumber => $item->itemnumber } })->as_list; + my @other_items = Koha::Items->search( + { + biblionumber => $item->biblionumber, + onloan => undef, + notforloan => 0, + -not => { itemnumber => $item->itemnumber } + } + )->as_list; - return ( 0, "on_reserve" ) if @fillable_holds && (scalar @other_items < scalar @fillable_holds ); + return ( 0, "on_reserve" ) if @fillable_holds && ( scalar @other_items < scalar @fillable_holds ); my %matched_items; - foreach my $possible_hold ( @fillable_holds ) { - my $fillable = 0; - my $patron_with_reserve = Koha::Patrons->find($possible_hold->{borrowernumber}); + foreach my $possible_hold (@fillable_holds) { + my $fillable = 0; + my $patron_with_reserve = Koha::Patrons->find( $possible_hold->{borrowernumber} ); foreach my $other_item (@other_items) { - next if defined $matched_items{$other_item->itemnumber}; - next if $other_item->holds->filter_by_found->count; - next unless IsAvailableForItemLevelRequest($other_item, $patron_with_reserve, undef); - next unless CanItemBeReserved($patron_with_reserve,$other_item,undef,{ignore_hold_counts=>1})->{status} eq 'OK'; - # NOTE: At checkin we call 'CheckReserves' which checks hold 'policy' - # CanItemBeReserved checks 'rules' and 'policies' which means - # items will fill holds at checkin that are rejected here - $fillable = 1; - $matched_items{$other_item->itemnumber} = 1; - last; + next if defined $matched_items{ $other_item->itemnumber }; + next if $other_item->holds->filter_by_found->count; + next unless IsAvailableForItemLevelRequest( $other_item, $patron_with_reserve, undef ); + next + unless CanItemBeReserved( + $patron_with_reserve, $other_item, undef, + { ignore_hold_counts => 1 } + )->{status} eq 'OK'; + + # NOTE: At checkin we call 'CheckReserves' which checks hold 'policy' + # CanItemBeReserved checks 'rules' and 'policies' which means + # items will fill holds at checkin that are rejected here + $fillable = 1; + $matched_items{ $other_item->itemnumber } = 1; + last; } return ( 0, "on_reserve" ) unless $fillable; } - } - else { + } else { return ( 0, "on_reserve" ) if $status; } } @@ -3159,12 +3249,13 @@ sub CanBookBeRenewed { } } - $soonest = GetSoonestRenewDate($patron, $issue); - if ( $soonest > dt_from_string() ){ - return (0, "too_soon", { soonest_renew_date => $soonest } ) unless $override_limit; + $soonest = GetSoonestRenewDate( $patron, $issue ); + if ( $soonest > dt_from_string() ) { + return ( 0, "too_soon", { soonest_renew_date => $soonest } ) unless $override_limit; } - my $auto_renew_code = $final_renewal ? 'auto_renew_final' : $final_unseen_renewal ? 'auto_unseen_final' : 'auto_renew'; + my $auto_renew_code = + $final_renewal ? 'auto_renew_final' : $final_unseen_renewal ? 'auto_unseen_final' : 'auto_renew'; return ( 1, $auto_renew_code ) if $auto_renew eq "ok" || $auto_renew eq "auto_too_soon" && !$override_limit; return ( 1, undef ); @@ -3221,8 +3312,8 @@ should be skipped for this renewal. sub AddRenewal { my $params = shift; - my $borrowernumber = $params->{borrowernumber}; - my $itemnumber = $params->{itemnumber}; + my $borrowernumber = $params->{borrowernumber}; + my $itemnumber = $params->{itemnumber}; return unless $itemnumber; my $branch = $params->{branch}; @@ -3236,9 +3327,9 @@ sub AddRenewal { # Fallback on a 'seen' renewal $seen = defined $seen && $seen == 0 ? 0 : 1; - my $item_object = Koha::Items->find($itemnumber) or return; - my $biblio = $item_object->biblio; - my $issue = $item_object->checkout; + my $item_object = Koha::Items->find($itemnumber) or return; + my $biblio = $item_object->biblio; + my $issue = $item_object->checkout; my $item_unblessed = $item_object->unblessed; my $renewal_type = $automatic ? "Automatic" : "Manual"; @@ -3250,175 +3341,189 @@ sub AddRenewal { $borrowernumber ||= $issue->borrowernumber; if ( defined $datedue && ref $datedue ne 'DateTime' ) { - $datedue = dt_from_string($datedue, 'sql'); + $datedue = dt_from_string( $datedue, 'sql' ); } - my $patron = Koha::Patrons->find( $borrowernumber ) or return; # FIXME Should do more than just return + my $patron = Koha::Patrons->find($borrowernumber) or return; # FIXME Should do more than just return my $patron_unblessed = $patron->unblessed; - my $circ_library = Koha::Libraries->find( _GetCircControlBranch($item_object, $patron) ); + my $circ_library = Koha::Libraries->find( _GetCircControlBranch( $item_object, $patron ) ); my $schema = Koha::Database->schema; - $schema->txn_do(sub{ + $schema->txn_do( + sub { - if ( !$skipfinecalc && C4::Context->preference('CalculateFinesOnReturn') ) { - _CalculateAndUpdateFine( { issue => $issue, item => $item_unblessed, borrower => $patron_unblessed } ); - } - _FixOverduesOnReturn( $borrowernumber, $itemnumber, undef, 'RENEWED' ); - - # If the due date wasn't specified, calculate it by adding the - # book's loan length to today's date or the current due date - # based on the value of the RenewalPeriodBase syspref. - my $itemtype = $item_object->effective_itemtype; - unless ($datedue) { - - $datedue = (C4::Context->preference('RenewalPeriodBase') eq 'date_due') ? - dt_from_string( $issue->date_due, 'sql' ) : - dt_from_string(); - $datedue = CalcDateDue($datedue, $itemtype, $circ_library->branchcode, $patron, 'is a renewal'); - } - - my $fees = Koha::Charges::Fees->new( - { - patron => $patron, - library => $circ_library, - item => $item_object, - from_date => dt_from_string( $issue->date_due, 'sql' ), - to_date => dt_from_string($datedue), + if ( !$skipfinecalc && C4::Context->preference('CalculateFinesOnReturn') ) { + _CalculateAndUpdateFine( { issue => $issue, item => $item_unblessed, borrower => $patron_unblessed } ); } - ); + _FixOverduesOnReturn( $borrowernumber, $itemnumber, undef, 'RENEWED' ); - # Increment the unseen renewals, if appropriate - # We only do so if the syspref is enabled and - # a maximum value has been set in the circ rules - my $unseen_renewals = $issue->unseen_renewals; - if (C4::Context->preference('UnseenRenewals')) { - my $rule = Koha::CirculationRules->get_effective_rule( - { categorycode => $patron->categorycode, - itemtype => $item_object->effective_itemtype, - branchcode => $circ_library->branchcode, - rule_name => 'unseen_renewals_allowed' + # If the due date wasn't specified, calculate it by adding the + # book's loan length to today's date or the current due date + # based on the value of the RenewalPeriodBase syspref. + my $itemtype = $item_object->effective_itemtype; + unless ($datedue) { + + $datedue = + ( C4::Context->preference('RenewalPeriodBase') eq 'date_due' ) + ? dt_from_string( $issue->date_due, 'sql' ) + : dt_from_string(); + $datedue = CalcDateDue( $datedue, $itemtype, $circ_library->branchcode, $patron, 'is a renewal' ); + } + + my $fees = Koha::Charges::Fees->new( + { + patron => $patron, + library => $circ_library, + item => $item_object, + from_date => dt_from_string( $issue->date_due, 'sql' ), + to_date => dt_from_string($datedue), } ); - if (!$seen && $rule && looks_like_number($rule->rule_value)) { - $unseen_renewals++; - } else { - # If the renewal is seen, unseen should revert to 0 - $unseen_renewals = 0; - } - } - # Update the issues record to have the new due date, and a new count - # of how many times it has been renewed. - my $renews = ( $issue->renewals_count || 0 ) + 1; - my $sth = $dbh->prepare("UPDATE issues SET date_due = ?, renewals_count = ?, unseen_renewals = ?, lastreneweddate = ? WHERE issue_id = ?"); - - eval{ - $sth->execute( $datedue->strftime('%Y-%m-%d %H:%M'), $renews, $unseen_renewals, $lastreneweddate, $issue->issue_id ); - }; - if( $sth->err ){ - Koha::Exceptions::Checkout::FailedRenewal->throw( - error => 'Update of issue# ' . $issue->issue_id . ' failed with error: ' . $sth->errstr - ); - } - - # Update the renewal count on the item, and tell zebra to reindex - $renews = ( $item_object->renewals || 0 ) + 1; - $item_object->renewals($renews); - $item_object->onloan($datedue); - # Don't index as we are in a transaction, skip hardcoded here - $item_object->store({ log_action => 0, skip_record_index => 1 }); - - # Charge a new rental fee, if applicable - my ( $charge, $type ) = GetIssuingCharges( $itemnumber, $borrowernumber ); - if ( $charge > 0 ) { - AddIssuingCharge($issue, $charge, 'RENT_RENEW'); - } - - # Charge a new accumulate rental fee, if applicable - my $itemtype_object = Koha::ItemTypes->find( $itemtype ); - if ( $itemtype_object ) { - my $accumulate_charge = $fees->accumulate_rentalcharge(); - if ( $accumulate_charge > 0 ) { - AddIssuingCharge( $issue, $accumulate_charge, 'RENT_DAILY_RENEW' ) - } - $charge += $accumulate_charge; - } - - # Send a renewal slip according to checkout alert preferencei - if ( C4::Context->preference('RenewalSendNotice') eq '1' ) { - my $circulation_alert = 'C4::ItemCirculationAlertPreference'; - my %conditions = ( - branchcode => $branch, - categorycode => $patron->categorycode, - item_type => $itemtype, - notification => 'CHECKOUT', - ); - if ( $circulation_alert->is_enabled_for( \%conditions ) ) { - SendCirculationAlert( + # Increment the unseen renewals, if appropriate + # We only do so if the syspref is enabled and + # a maximum value has been set in the circ rules + my $unseen_renewals = $issue->unseen_renewals; + if ( C4::Context->preference('UnseenRenewals') ) { + my $rule = Koha::CirculationRules->get_effective_rule( { - type => 'RENEWAL', - item => $item_unblessed, - borrower => $patron->unblessed, - branch => $branch, + categorycode => $patron->categorycode, + itemtype => $item_object->effective_itemtype, + branchcode => $circ_library->branchcode, + rule_name => 'unseen_renewals_allowed' } ); + if ( !$seen && $rule && looks_like_number( $rule->rule_value ) ) { + $unseen_renewals++; + } else { + + # If the renewal is seen, unseen should revert to 0 + $unseen_renewals = 0; + } } - } - # Remove any OVERDUES related debarment if the borrower has no overdues - my $overdue_restrictions = $patron->restrictions->search({ type => 'OVERDUES' }); - if ( $patron - && $patron->is_debarred - && ! $patron->has_overdues - && $overdue_restrictions->count - ) { - DelUniqueDebarment({ borrowernumber => $borrowernumber, type => 'OVERDUES' }); - } + # Update the issues record to have the new due date, and a new count + # of how many times it has been renewed. + my $renews = ( $issue->renewals_count || 0 ) + 1; + my $sth = $dbh->prepare( + "UPDATE issues SET date_due = ?, renewals_count = ?, unseen_renewals = ?, lastreneweddate = ? WHERE issue_id = ?" + ); - # Add renewal record - my $renewal = Koha::Checkouts::Renewal->new( + eval { + $sth->execute( + $datedue->strftime('%Y-%m-%d %H:%M'), $renews, $unseen_renewals, $lastreneweddate, + $issue->issue_id + ); + }; + if ( $sth->err ) { + Koha::Exceptions::Checkout::FailedRenewal->throw( + error => 'Update of issue# ' . $issue->issue_id . ' failed with error: ' . $sth->errstr ); + } + + # Update the renewal count on the item, and tell zebra to reindex + $renews = ( $item_object->renewals || 0 ) + 1; + $item_object->renewals($renews); + $item_object->onloan($datedue); + + # Don't index as we are in a transaction, skip hardcoded here + $item_object->store( { log_action => 0, skip_record_index => 1 } ); + + # Charge a new rental fee, if applicable + my ( $charge, $type ) = GetIssuingCharges( $itemnumber, $borrowernumber ); + if ( $charge > 0 ) { + AddIssuingCharge( $issue, $charge, 'RENT_RENEW' ); + } + + # Charge a new accumulate rental fee, if applicable + my $itemtype_object = Koha::ItemTypes->find($itemtype); + if ($itemtype_object) { + my $accumulate_charge = $fees->accumulate_rentalcharge(); + if ( $accumulate_charge > 0 ) { + AddIssuingCharge( $issue, $accumulate_charge, 'RENT_DAILY_RENEW' ); + } + $charge += $accumulate_charge; + } + + # Send a renewal slip according to checkout alert preferencei + if ( C4::Context->preference('RenewalSendNotice') eq '1' ) { + my $circulation_alert = 'C4::ItemCirculationAlertPreference'; + my %conditions = ( + branchcode => $branch, + categorycode => $patron->categorycode, + item_type => $itemtype, + notification => 'CHECKOUT', + ); + if ( $circulation_alert->is_enabled_for( \%conditions ) ) { + SendCirculationAlert( + { + type => 'RENEWAL', + item => $item_unblessed, + borrower => $patron->unblessed, + branch => $branch, + } + ); + } + } + + # Remove any OVERDUES related debarment if the borrower has no overdues + my $overdue_restrictions = $patron->restrictions->search( { type => 'OVERDUES' } ); + if ( $patron + && $patron->is_debarred + && !$patron->has_overdues + && $overdue_restrictions->count ) { - checkout_id => $issue->issue_id, - interface => C4::Context->interface, - renewal_type => $renewal_type, - renewer_id => C4::Context->userenv ? C4::Context->userenv->{'number'} : undef, - seen => $seen, + DelUniqueDebarment( { borrowernumber => $borrowernumber, type => 'OVERDUES' } ); } - )->store(); - # Add the renewal to stats - C4::Stats::UpdateStats( - { - branch => $item_object->renewal_branchcode({branch => $branch}), - type => 'renew', - amount => $charge, - itemnumber => $itemnumber, - itemtype => $itemtype, - location => $item_object->location, - borrowernumber => $borrowernumber, - ccode => $item_object->ccode, - categorycode => $patron->categorycode, - interface => C4::Context->interface, - } - ); - #Update borrowers.lastseen - $patron->update_lastseen('renewal'); + # Add renewal record + my $renewal = Koha::Checkouts::Renewal->new( + { + checkout_id => $issue->issue_id, + interface => C4::Context->interface, + renewal_type => $renewal_type, + renewer_id => C4::Context->userenv ? C4::Context->userenv->{'number'} : undef, + seen => $seen, + } + )->store(); - #Log the renewal - logaction("CIRCULATION", "RENEWAL", $borrowernumber, $itemnumber) if C4::Context->preference("RenewalLog"); + # Add the renewal to stats + C4::Stats::UpdateStats( + { + branch => $item_object->renewal_branchcode( { branch => $branch } ), + type => 'renew', + amount => $charge, + itemnumber => $itemnumber, + itemtype => $itemtype, + location => $item_object->location, + borrowernumber => $borrowernumber, + ccode => $item_object->ccode, + categorycode => $patron->categorycode, + interface => C4::Context->interface, + } + ); - Koha::Plugins->call('after_circ_action', { - action => 'renewal', - payload => { - checkout => $issue->get_from_storage - } - }); - }); + #Update borrowers.lastseen + $patron->update_lastseen('renewal'); + + #Log the renewal + logaction( "CIRCULATION", "RENEWAL", $borrowernumber, $itemnumber ) + if C4::Context->preference("RenewalLog"); + + Koha::Plugins->call( + 'after_circ_action', + { + action => 'renewal', + payload => { checkout => $issue->get_from_storage } + } + ); + } + ); + + unless ($skip_record_index) { - unless( $skip_record_index ){ # We index now, after the transaction is committed - my $indexer = Koha::SearchEngine::Indexer->new({ index => $Koha::SearchEngine::BIBLIOS_INDEX }); + my $indexer = Koha::SearchEngine::Indexer->new( { index => $Koha::SearchEngine::BIBLIOS_INDEX } ); $indexer->index_records( $item_object->biblionumber, "specialUpdate", "biblioserver" ); } @@ -3426,37 +3531,40 @@ sub AddRenewal { } sub GetRenewCount { + # check renewal status my ( $borrowernumber_or_patron, $itemnumber_or_item ) = @_; my $dbh = C4::Context->dbh; my $renewcount = 0; - my $unseencount = 0; + my $unseencount = 0; my $renewsallowed = 0; my $unseenallowed = 0; my $renewsleft = 0; my $unseenleft = 0; - my $patron = blessed $borrowernumber_or_patron ? - $borrowernumber_or_patron : Koha::Patrons->find($borrowernumber_or_patron); - my $item = blessed $itemnumber_or_item ? - $itemnumber_or_item : Koha::Items->find($itemnumber_or_item); + my $patron = + blessed $borrowernumber_or_patron ? $borrowernumber_or_patron : Koha::Patrons->find($borrowernumber_or_patron); + my $item = blessed $itemnumber_or_item ? $itemnumber_or_item : Koha::Items->find($itemnumber_or_item); - return (0, 0, 0, 0, 0, 0) unless $patron or $item; # Wrong call, no renewal allowed + return ( 0, 0, 0, 0, 0, 0 ) unless $patron or $item; # Wrong call, no renewal allowed # Look in the issues table for this item, lent to this borrower, # and not yet returned. # FIXME - I think this function could be redone to use only one SQL call. - my $sth = $dbh->prepare(q{ + my $sth = $dbh->prepare( + q{ SELECT * FROM issues WHERE (borrowernumber = ?) AND (itemnumber = ?) - }); + } + ); $sth->execute( $patron->borrowernumber, $item->itemnumber ); my $data = $sth->fetchrow_hashref; - $renewcount = $data->{'renewals_count'} if $data->{'renewals_count'}; + $renewcount = $data->{'renewals_count'} if $data->{'renewals_count'}; $unseencount = $data->{'unseen_renewals'} if $data->{'unseen_renewals'}; + # $item and $borrower should be calculated - my $branchcode = _GetCircControlBranch($item, $patron); + my $branchcode = _GetCircControlBranch( $item, $patron ); my $rules = Koha::CirculationRules->get_effective_rules( { @@ -3467,13 +3575,14 @@ sub GetRenewCount { } ); $renewsallowed = $rules ? $rules->{renewalsallowed} : 0; - $unseenallowed = $rules->{unseen_renewals_allowed} ? - $rules->{unseen_renewals_allowed} : - 0; - $renewsleft = $renewsallowed - $renewcount; - $unseenleft = $unseenallowed - $unseencount; - if($renewsleft < 0){ $renewsleft = 0; } - if($unseenleft < 0){ $unseenleft = 0; } + $unseenallowed = + $rules->{unseen_renewals_allowed} + ? $rules->{unseen_renewals_allowed} + : 0; + $renewsleft = $renewsallowed - $renewcount; + $unseenleft = $unseenallowed - $unseencount; + if ( $renewsleft < 0 ) { $renewsleft = 0; } + if ( $unseenleft < 0 ) { $unseenleft = 0; } return ( $renewcount, $renewsallowed, @@ -3516,12 +3625,13 @@ sub GetSoonestRenewDate { my $dbh = C4::Context->dbh; - my $branchcode = _GetCircControlBranch( $item, $patron ); + my $branchcode = _GetCircControlBranch( $item, $patron ); my $issuing_rule = Koha::CirculationRules->get_effective_rules( - { categorycode => $patron->categorycode, + { + categorycode => $patron->categorycode, itemtype => $item->effective_itemtype, branchcode => $branchcode, - rules => [ + rules => [ $circ_rule, 'lengthunit', ] @@ -3534,8 +3644,7 @@ sub GetSoonestRenewDate { and $issuing_rule->{$circ_rule} ne "" ) { my $soonestrenewal = - dt_from_string( $issue->date_due )->subtract( - $issuing_rule->{lengthunit} => $issuing_rule->{$circ_rule} ); + dt_from_string( $issue->date_due )->subtract( $issuing_rule->{lengthunit} => $issuing_rule->{$circ_rule} ); if ( C4::Context->preference('NoRenewalBeforePrecision') eq 'date' and $issuing_rule->{lengthunit} eq 'days' ) @@ -3544,6 +3653,7 @@ sub GetSoonestRenewDate { } return $soonestrenewal; } elsif ( $is_auto && $issue->auto_renew && $patron->autorenew_checkouts ) { + # Checkouts with auto-renewing fall back to due date if noautorenewalbefore is undef my $soonestrenewal = dt_from_string( $issue->date_due ); if ( C4::Context->preference('NoRenewalBeforePrecision') eq 'date' @@ -3582,7 +3692,7 @@ sub GetLatestAutoRenewDate { my $item = $issue->item; return unless $item; - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $branchcode = _GetCircControlBranch( $item, $patron ); my $circulation_rules = Koha::CirculationRules->get_effective_rules( @@ -3590,7 +3700,7 @@ sub GetLatestAutoRenewDate { categorycode => $patron->categorycode, itemtype => $item->effective_itemtype, branchcode => $branchcode, - rules => [ + rules => [ 'no_auto_renewal_after', 'no_auto_renewal_after_hard_limit', 'lengthunit', @@ -3600,17 +3710,15 @@ sub GetLatestAutoRenewDate { return unless $circulation_rules; return - if ( not $circulation_rules->{no_auto_renewal_after} - or $circulation_rules->{no_auto_renewal_after} eq '' ) - and ( not $circulation_rules->{no_auto_renewal_after_hard_limit} - or $circulation_rules->{no_auto_renewal_after_hard_limit} eq '' ); + if ( not $circulation_rules->{no_auto_renewal_after} + or $circulation_rules->{no_auto_renewal_after} eq '' ) + and ( not $circulation_rules->{no_auto_renewal_after_hard_limit} + or $circulation_rules->{no_auto_renewal_after_hard_limit} eq '' ); my $maximum_renewal_date; if ( $circulation_rules->{no_auto_renewal_after} ) { - $maximum_renewal_date = dt_from_string($issue->issuedate); - $maximum_renewal_date->add( - $circulation_rules->{lengthunit} => $circulation_rules->{no_auto_renewal_after} - ); + $maximum_renewal_date = dt_from_string( $issue->issuedate ); + $maximum_renewal_date->add( $circulation_rules->{lengthunit} => $circulation_rules->{no_auto_renewal_after} ); } if ( $circulation_rules->{no_auto_renewal_after_hard_limit} ) { @@ -3620,7 +3728,6 @@ sub GetLatestAutoRenewDate { return $maximum_renewal_date; } - =head2 GetIssuingCharges ($charge, $item_type) = &GetIssuingCharges($itemnumber, $borrowernumber); @@ -3649,7 +3756,8 @@ sub GetIssuingCharges { # Get the book's item type and rental charge (via its biblioitem). my $charge_query = 'SELECT itemtypes.itemtype,rentalcharge FROM items LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber'; - $charge_query .= (C4::Context->preference('item-level_itypes')) + $charge_query .= + ( C4::Context->preference('item-level_itypes') ) ? ' LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype' : ' LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype'; @@ -3662,19 +3770,22 @@ sub GetIssuingCharges { $item_type = $item_data->{itemtype}; $charge = $item_data->{rentalcharge}; if ($charge) { + # FIXME This should follow CircControl my $branch = C4::Context::mybranch(); - $patron //= Koha::Patrons->find( $borrowernumber ); - my $discount = Koha::CirculationRules->get_effective_rule({ - categorycode => $patron->categorycode, - branchcode => $branch, - itemtype => $item_type, - rule_name => 'rentaldiscount' - }); + $patron //= Koha::Patrons->find($borrowernumber); + my $discount = Koha::CirculationRules->get_effective_rule( + { + categorycode => $patron->categorycode, + branchcode => $branch, + itemtype => $item_type, + rule_name => 'rentaldiscount' + } + ); if ($discount) { $charge = ( $charge * ( 100 - $discount->rule_value ) ) / 100; } - $charge = sprintf '%.2f', $charge; # ensure no fractions of a penny returned + $charge = sprintf '%.2f', $charge; # ensure no fractions of a penny returned } } @@ -3692,17 +3803,17 @@ sub AddIssuingCharge { # FIXME What if checkout does not exist? - my $account = Koha::Account->new({ patron_id => $checkout->borrowernumber }); + my $account = Koha::Account->new( { patron_id => $checkout->borrowernumber } ); my $accountline = $account->add_debit( { - amount => $charge, - note => undef, - user_id => C4::Context->userenv ? C4::Context->userenv->{'number'} : undef, - library_id => C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef, - interface => C4::Context->interface, - type => $type, - item_id => $checkout->itemnumber, - issue_id => $checkout->issue_id, + amount => $charge, + note => undef, + user_id => C4::Context->userenv ? C4::Context->userenv->{'number'} : undef, + library_id => C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef, + interface => C4::Context->interface, + type => $type, + item_id => $checkout->itemnumber, + issue_id => $checkout->issue_id, } ); } @@ -3777,21 +3888,22 @@ B: sub SendCirculationAlert { my ($opts) = @_; - my ($type, $item, $borrower, $branch, $issue) = - ($opts->{type}, $opts->{item}, $opts->{borrower}, $opts->{branch}, $opts->{issue}); + my ( $type, $item, $borrower, $branch, $issue ) = + ( $opts->{type}, $opts->{item}, $opts->{borrower}, $opts->{branch}, $opts->{issue} ); my %message_name = ( CHECKIN => 'Item_Check_in', CHECKOUT => 'Item_Checkout', RENEWAL => 'Item_Checkout', ); - my $borrower_preferences = C4::Members::Messaging::GetMessagingPreferences({ - borrowernumber => $borrower->{borrowernumber}, - message_name => $message_name{$type}, - }); - + my $borrower_preferences = C4::Members::Messaging::GetMessagingPreferences( + { + borrowernumber => $borrower->{borrowernumber}, + message_name => $message_name{$type}, + } + ); my $tables = { - items => $item->{itemnumber}, + items => $item->{itemnumber}, biblio => $item->{biblionumber}, biblioitems => $item->{biblionumber}, borrowers => $borrower, @@ -3800,13 +3912,13 @@ sub SendCirculationAlert { # TODO: Currently, we need to pass an issue_id as identifier for old_issues, but still an itemnumber for issues. # See C4::Letters:: _parseletter_sth - if( $type eq 'CHECKIN' ){ + if ( $type eq 'CHECKIN' ) { $tables->{old_issues} = $issue->issue_id; } else { $tables->{issues} = $item->{itemnumber}; } - my $schema = Koha::Database->new->schema; + my $schema = Koha::Database->new->schema; my @transports = keys %{ $borrower_preferences->{transports} }; # From the MySQL doc: @@ -3816,22 +3928,22 @@ sub SendCirculationAlert { my $do_not_lock = ( exists $ENV{_} && $ENV{_} =~ m|prove| ) || $ENV{KOHA_TESTING}; for my $mtt (@transports) { - my $letter = C4::Letters::GetPreparedLetter ( - module => 'circulation', - letter_code => $type, - branchcode => $branch, + my $letter = C4::Letters::GetPreparedLetter( + module => 'circulation', + letter_code => $type, + branchcode => $branch, message_transport_type => $mtt, - lang => $borrower->{lang}, - tables => $tables, + lang => $borrower->{lang}, + tables => $tables, ) or next; - C4::Context->dbh->do(q|LOCK TABLE message_queue READ|) unless $do_not_lock; + C4::Context->dbh->do(q|LOCK TABLE message_queue READ|) unless $do_not_lock; C4::Context->dbh->do(q|LOCK TABLE message_queue WRITE|) unless $do_not_lock; - my $message = C4::Message->find_last_message($borrower, $type, $mtt); - unless ( $message ) { + my $message = C4::Message->find_last_message( $borrower, $type, $mtt ); + unless ($message) { C4::Context->dbh->do(q|UNLOCK TABLES|) unless $do_not_lock; - my $patron = Koha::Patrons->find($borrower->{borrowernumber}); - C4::Message->enqueue($letter, $patron, $mtt); + my $patron = Koha::Patrons->find( $borrower->{borrowernumber} ); + C4::Message->enqueue( $letter, $patron, $mtt ); } else { $message->append($letter); $message->update; @@ -3862,16 +3974,16 @@ sub CalcDateDue { $isrenewal ||= 0; # loanlength now a href - my $loanlength = - GetLoanLength( $patron->categorycode, $itemtype, $branch ); + my $loanlength = GetLoanLength( $patron->categorycode, $itemtype, $branch ); - my $length_key = ( $isrenewal and defined $loanlength->{renewalperiod} and $loanlength->{renewalperiod} ne q{} ) - ? qq{renewalperiod} - : qq{issuelength}; + my $length_key = + ( $isrenewal and defined $loanlength->{renewalperiod} and $loanlength->{renewalperiod} ne q{} ) + ? qq{renewalperiod} + : qq{issuelength}; my $datedue; - if ( $startdate ) { - if (ref $startdate ne 'DateTime' ) { + if ($startdate) { + if ( ref $startdate ne 'DateTime' ) { $datedue = dt_from_string($datedue); } else { $datedue = $startdate->clone; @@ -3880,7 +3992,6 @@ sub CalcDateDue { $datedue = dt_from_string()->truncate( to => 'minute' ); } - my $daysmode = Koha::CirculationRules->get_effective_daysmode( { categorycode => $patron->categorycode, @@ -3892,9 +4003,9 @@ sub CalcDateDue { my $considerlibraryhours = C4::Context->preference('ConsiderLibraryHoursInCirculation'); # starter vars so don't do calculations directly to $datedue - my $potential_datedue = $datedue->clone; - my $library_close = $datedue->clone; - my $dayofweek = $datedue->day_of_week; + my $potential_datedue = $datedue->clone; + my $library_close = $datedue->clone; + my $dayofweek = $datedue->day_of_week; # Representation fix # DateTime object dow (1-7) where Monday is 1 @@ -3926,10 +4037,13 @@ sub CalcDateDue { } # calculate the datedue as normal - if ( $daysmode eq 'Days' ) - { # ignoring calendar + if ( $daysmode eq 'Days' ) { # ignoring calendar if ( $loanlength->{lengthunit} eq 'hours' ) { - if ( $considerlibraryhours ne 'ignore' and $potential_datedue > $library_close and $todayhours->close_time and $tomorrowhours->open_time ) { + if ( $considerlibraryhours ne 'ignore' + and $potential_datedue > $library_close + and $todayhours->close_time + and $tomorrowhours->open_time ) + { if ( $considerlibraryhours eq 'close' ) { # datedue will be after the library closes on that day @@ -3957,8 +4071,12 @@ sub CalcDateDue { } } else { my $dur; - if ($loanlength->{lengthunit} eq 'hours') { - if ( $considerlibraryhours ne 'ignore' and $potential_datedue > $library_close and $todayhours->close_time and $tomorrowhours->open_time ) { + if ( $loanlength->{lengthunit} eq 'hours' ) { + if ( $considerlibraryhours ne 'ignore' + and $potential_datedue > $library_close + and $todayhours->close_time + and $tomorrowhours->open_time ) + { if ( $considerlibraryhours eq 'close' ) { # datedue will be after the library closes on that day @@ -3980,30 +4098,28 @@ sub CalcDateDue { # due time doesn't conflict with library open hours, don't need to check $dur = DateTime::Duration->new( hours => $loanlength->{$length_key} ); } - } - else { # days + } else { # days $dur = DateTime::Duration->new( days => $loanlength->{$length_key} ); } my $calendar = Koha::Calendar->new( branchcode => $branch, days_mode => $daysmode ); $datedue = $calendar->addDuration( $datedue, $dur, $loanlength->{lengthunit} ) if $dur; - if ($loanlength->{lengthunit} eq 'days') { + if ( $loanlength->{lengthunit} eq 'days' ) { $datedue->set_hour(23); $datedue->set_minute(59); } } # if Hard Due Dates are used, retrieve them and apply as necessary - my ( $hardduedate, $hardduedatecompare ) = - GetHardDueDate( $patron->categorycode, $itemtype, $branch ); + my ( $hardduedate, $hardduedatecompare ) = GetHardDueDate( $patron->categorycode, $itemtype, $branch ); if ($hardduedate) { # hardduedates are currently dates $hardduedate->truncate( to => 'minute' ); $hardduedate->set_hour(23); $hardduedate->set_minute(59); my $cmp = DateTime->compare( $hardduedate, $datedue ); -# if the calculated due date is after the 'before' Hard Due Date (ceiling), override -# if the calculated date is before the 'after' Hard Due Date (floor), override -# if the hard due date is set to 'exactly', overrride + # if the calculated due date is after the 'before' Hard Due Date (ceiling), override + # if the calculated date is before the 'after' Hard Due Date (floor), override + # if the hard due date is set to 'exactly', overrride if ( $hardduedatecompare == 0 || $hardduedatecompare == $cmp ) { $datedue = $hardduedate->clone; } @@ -4014,38 +4130,38 @@ sub CalcDateDue { # if ReturnBeforeExpiry ON the datedue can't be after borrower expirydate if ( C4::Context->preference('ReturnBeforeExpiry') ) { - my $expiry_dt = dt_from_string( $patron->dateexpiry, 'iso', 'floating'); - if( $expiry_dt ) { #skip empty expiry date.. - $expiry_dt->set( hour => 23, minute => 59); - my $d1= $datedue->clone->set_time_zone('floating'); + my $expiry_dt = dt_from_string( $patron->dateexpiry, 'iso', 'floating' ); + if ($expiry_dt) { #skip empty expiry date.. + $expiry_dt->set( hour => 23, minute => 59 ); + my $d1 = $datedue->clone->set_time_zone('floating'); if ( DateTime->compare( $d1, $expiry_dt ) == 1 ) { $datedue = $expiry_dt->clone->set_time_zone( C4::Context->tz ); } } if ( $daysmode ne 'Days' ) { - my $calendar = Koha::Calendar->new( branchcode => $branch, days_mode => $daysmode ); - if ( $calendar->is_holiday($datedue) ) { - # Don't return on a closed day - $datedue = $calendar->prev_open_days( $datedue, 1 ); - } + my $calendar = Koha::Calendar->new( branchcode => $branch, days_mode => $daysmode ); + if ( $calendar->is_holiday($datedue) ) { + + # Don't return on a closed day + $datedue = $calendar->prev_open_days( $datedue, 1 ); + } } } return $datedue; } - -sub CheckValidBarcode{ -my ($barcode) = @_; -my $dbh = C4::Context->dbh; -my $query=qq|SELECT count(*) +sub CheckValidBarcode { + my ($barcode) = @_; + my $dbh = C4::Context->dbh; + my $query = qq|SELECT count(*) FROM items WHERE barcode=? |; -my $sth = $dbh->prepare($query); -$sth->execute($barcode); -my $exist=$sth->fetchrow ; -return $exist; + my $sth = $dbh->prepare($query); + $sth->execute($barcode); + my $exist = $sth->fetchrow; + return $exist; } =head2 IsBranchTransferAllowed @@ -4060,24 +4176,25 @@ Koha::Item->can_be_transferred. =cut sub IsBranchTransferAllowed { - my ( $toBranch, $fromBranch, $code ) = @_; + my ( $toBranch, $fromBranch, $code ) = @_; - if ( $toBranch eq $fromBranch ) { return 1; } ## Short circuit for speed. - - my $limitType = C4::Context->preference("BranchTransferLimitsType"); - my $dbh = C4::Context->dbh; - - my $sth = $dbh->prepare("SELECT * FROM branch_transfer_limits WHERE toBranch = ? AND fromBranch = ? AND $limitType = ?"); - $sth->execute( $toBranch, $fromBranch, $code ); - my $limit = $sth->fetchrow_hashref(); - - ## If a row is found, then that combination is not allowed, if no matching row is found, then the combination *is allowed* - if ( $limit->{'limitId'} ) { - return 0; - } else { - return 1; - } -} + if ( $toBranch eq $fromBranch ) { return 1; } ## Short circuit for speed. + + my $limitType = C4::Context->preference("BranchTransferLimitsType"); + my $dbh = C4::Context->dbh; + + my $sth = + $dbh->prepare("SELECT * FROM branch_transfer_limits WHERE toBranch = ? AND fromBranch = ? AND $limitType = ?"); + $sth->execute( $toBranch, $fromBranch, $code ); + my $limit = $sth->fetchrow_hashref(); + + ## If a row is found, then that combination is not allowed, if no matching row is found, then the combination *is allowed* + if ( $limit->{'limitId'} ) { + return 0; + } else { + return 1; + } +} =head2 CreateBranchTransferLimit @@ -4090,14 +4207,15 @@ Deprecated in favor of Koha::Item::Transfer::Limit->new. =cut sub CreateBranchTransferLimit { - my ( $toBranch, $fromBranch, $code ) = @_; - return unless defined($toBranch) && defined($fromBranch); - my $limitType = C4::Context->preference("BranchTransferLimitsType"); - - my $dbh = C4::Context->dbh; - - my $sth = $dbh->prepare("INSERT INTO branch_transfer_limits ( $limitType, toBranch, fromBranch ) VALUES ( ?, ?, ? )"); - return $sth->execute( $code, $toBranch, $fromBranch ); + my ( $toBranch, $fromBranch, $code ) = @_; + return unless defined($toBranch) && defined($fromBranch); + my $limitType = C4::Context->preference("BranchTransferLimitsType"); + + my $dbh = C4::Context->dbh; + + my $sth = + $dbh->prepare("INSERT INTO branch_transfer_limits ( $limitType, toBranch, fromBranch ) VALUES ( ?, ?, ? )"); + return $sth->execute( $code, $toBranch, $fromBranch ); } =head2 DeleteBranchTransferLimits @@ -4117,12 +4235,12 @@ Deprecated in favor of Koha::Item::Transfer::Limits->search({ sub DeleteBranchTransferLimits { my $branch = shift; return unless defined $branch; - my $dbh = C4::Context->dbh; - my $sth = $dbh->prepare("DELETE FROM branch_transfer_limits WHERE fromBranch = ?"); + my $dbh = C4::Context->dbh; + my $sth = $dbh->prepare("DELETE FROM branch_transfer_limits WHERE fromBranch = ?"); return $sth->execute($branch); } -sub ReturnLostItem{ +sub ReturnLostItem { my ( $borrowernumber, $itemnum ) = @_; MarkIssueReturned( $borrowernumber, $itemnum ); } @@ -4142,16 +4260,17 @@ $params: =cut -sub LostItem{ - my ($itemnumber, $mark_lost_from, $force_mark_returned, $params) = @_; +sub LostItem { + my ( $itemnumber, $mark_lost_from, $force_mark_returned, $params ) = @_; + + unless ($mark_lost_from) { - unless ( $mark_lost_from ) { # Temporary check to avoid regressions die q|LostItem called without $mark_lost_from, check the API.|; } my $mark_returned; - if ( $force_mark_returned ) { + if ($force_mark_returned) { $mark_returned = 1; } else { my $pref = C4::Context->preference('MarkLostItemsAsReturned') // q{}; @@ -4159,52 +4278,60 @@ sub LostItem{ } my $dbh = C4::Context->dbh(); - my $sth=$dbh->prepare("SELECT issues.*,items.*,biblio.title + my $sth = $dbh->prepare( + "SELECT issues.*,items.*,biblio.title FROM issues JOIN items USING (itemnumber) JOIN biblio USING (biblionumber) - WHERE issues.itemnumber=?"); + WHERE issues.itemnumber=?" + ); $sth->execute($itemnumber); - my $issues=$sth->fetchrow_hashref(); + my $issues = $sth->fetchrow_hashref(); # If a borrower lost the item, add a replacement cost to the their record - if ( my $borrowernumber = $issues->{borrowernumber} ){ - my $patron = Koha::Patrons->find( $borrowernumber ); + if ( my $borrowernumber = $issues->{borrowernumber} ) { + my $patron = Koha::Patrons->find($borrowernumber); - my $fix = _FixOverduesOnReturn($borrowernumber, $itemnumber, C4::Context->preference('WhenLostForgiveFine'), 'LOST'); - defined($fix) or warn "_FixOverduesOnReturn($borrowernumber, $itemnumber...) failed!"; # zero is OK, check defined + my $fix = _FixOverduesOnReturn( + $borrowernumber, $itemnumber, C4::Context->preference('WhenLostForgiveFine'), + 'LOST' + ); + defined($fix) + or warn "_FixOverduesOnReturn($borrowernumber, $itemnumber...) failed!"; # zero is OK, check defined - if (C4::Context->preference('WhenLostChargeReplacementFee')){ + if ( C4::Context->preference('WhenLostChargeReplacementFee') ) { C4::Accounts::chargelostitem( $borrowernumber, $itemnumber, $issues->{'replacementprice'}, - sprintf( "%s %s %s", + sprintf( + "%s %s %s", $issues->{'title'} || q{}, $issues->{'barcode'} || q{}, $issues->{'itemcallnumber'} || q{}, ), ); + #FIXME : Should probably have a way to distinguish this from an item that really was returned. #warn " $issues->{'borrowernumber'} / $itemnumber "; } - MarkIssueReturned($borrowernumber,$itemnumber,undef,$patron->privacy,$params) if $mark_returned; + MarkIssueReturned( $borrowernumber, $itemnumber, undef, $patron->privacy, $params ) if $mark_returned; } # When an item is marked as lost, we should automatically cancel its outstanding transfers. - my $item = Koha::Items->find($itemnumber); + my $item = Koha::Items->find($itemnumber); my $transfers = $item->get_transfers; - while (my $transfer = $transfers->next) { - $transfer->cancel({ reason => 'ItemLost', force => 1 }); + while ( my $transfer = $transfers->next ) { + $transfer->cancel( { reason => 'ItemLost', force => 1 } ); } } sub GetOfflineOperations { my $dbh = C4::Context->dbh; my $sth = $dbh->prepare("SELECT * FROM pending_offline_operations WHERE branchcode=? ORDER BY timestamp"); - $sth->execute(C4::Context->userenv->{'branch'}); - my $results = $sth->fetchall_arrayref({}); + $sth->execute( C4::Context->userenv->{'branch'} ); + my $results = $sth->fetchall_arrayref( {} ); return $results; } @@ -4213,14 +4340,16 @@ sub GetOfflineOperation { return unless $operationid; my $dbh = C4::Context->dbh; my $sth = $dbh->prepare("SELECT * FROM pending_offline_operations WHERE operationid=?"); - $sth->execute( $operationid ); + $sth->execute($operationid); return $sth->fetchrow_hashref; } sub AddOfflineOperation { my ( $userid, $branchcode, $timestamp, $action, $barcode, $cardnumber, $amount ) = @_; my $dbh = C4::Context->dbh; - my $sth = $dbh->prepare("INSERT INTO pending_offline_operations (userid, branchcode, timestamp, action, barcode, cardnumber, amount) VALUES(?,?,?,?,?,?,?)"); + my $sth = $dbh->prepare( + "INSERT INTO pending_offline_operations (userid, branchcode, timestamp, action, barcode, cardnumber, amount) VALUES(?,?,?,?,?,?,?)" + ); $sth->execute( $userid, $branchcode, $timestamp, $action, $barcode, $cardnumber, $amount ); return "Added."; } @@ -4228,7 +4357,7 @@ sub AddOfflineOperation { sub DeleteOfflineOperation { my $dbh = C4::Context->dbh; my $sth = $dbh->prepare("DELETE FROM pending_offline_operations WHERE operationid=?"); - $sth->execute( shift ); + $sth->execute(shift); return "Deleted."; } @@ -4237,11 +4366,11 @@ sub ProcessOfflineOperation { my $report; if ( $operation->{action} eq 'return' ) { - $report = ProcessOfflineReturn( $operation ); + $report = ProcessOfflineReturn($operation); } elsif ( $operation->{action} eq 'issue' ) { - $report = ProcessOfflineIssue( $operation ); + $report = ProcessOfflineIssue($operation); } elsif ( $operation->{action} eq 'payment' ) { - $report = ProcessOfflinePayment( $operation ); + $report = ProcessOfflinePayment($operation); } DeleteOfflineOperation( $operation->{operationid} ) if $operation->{operationid}; @@ -4252,12 +4381,12 @@ sub ProcessOfflineOperation { sub ProcessOfflineReturn { my $operation = shift; - my $item = Koha::Items->find({barcode => $operation->{barcode}}); + my $item = Koha::Items->find( { barcode => $operation->{barcode} } ); - if ( $item ) { + if ($item) { my $itemnumber = $item->itemnumber; - my $issue = $item->checkout; - if ( $issue ) { + my $issue = $item->checkout; + if ($issue) { my $leave_item_lost = C4::Context->preference("BlockReturnOfLostItems") ? 1 : 0; ModDateLastSeen( $itemnumber, $leave_item_lost ); MarkIssueReturned( @@ -4266,7 +4395,7 @@ sub ProcessOfflineReturn { $operation->{timestamp}, ); $item->onloan(undef); - $item->store({ log_action => 0 }); + $item->store( { log_action => 0 } ); return "Success."; } else { return "Item not issued."; @@ -4282,15 +4411,16 @@ sub ProcessOfflineIssue { my $patron = Koha::Patrons->find( { cardnumber => $operation->{cardnumber} } ); $patron ||= Koha::Patrons->find( { userid => $operation->{cardnumber} } ); - if ( $patron ) { - my $item = Koha::Items->find({ barcode => $operation->{barcode} }); + if ($patron) { + my $item = Koha::Items->find( { barcode => $operation->{barcode} } ); unless ($item) { return "Barcode not found."; } my $itemnumber = $item->itemnumber; - my $issue = $item->checkout; + my $issue = $item->checkout; - if ( $issue and ( $issue->borrowernumber ne $patron->borrowernumber ) ) { # Item already issued to another patron mark it returned + if ( $issue and ( $issue->borrowernumber ne $patron->borrowernumber ) ) + { # Item already issued to another patron mark it returned MarkIssueReturned( $issue->borrowernumber, $itemnumber, @@ -4337,23 +4467,23 @@ sub ProcessOfflinePayment { =cut sub TransferSlip { - my ($branch, $itemnumber, $barcode, $to_branch) = @_; + my ( $branch, $itemnumber, $barcode, $to_branch ) = @_; my $item = - $itemnumber - ? Koha::Items->find($itemnumber) - : Koha::Items->find( { barcode => $barcode } ); + $itemnumber + ? Koha::Items->find($itemnumber) + : Koha::Items->find( { barcode => $barcode } ); $item or return; - return C4::Letters::GetPreparedLetter ( - module => 'circulation', + return C4::Letters::GetPreparedLetter( + module => 'circulation', letter_code => 'TRANSFERSLIP', - branchcode => $branch, - tables => { - 'branches' => $to_branch, - 'biblio' => $item->biblionumber, - 'items' => $item->unblessed, + branchcode => $branch, + tables => { + 'branches' => $to_branch, + 'biblio' => $item->biblionumber, + 'items' => $item->unblessed, }, ); } @@ -4367,16 +4497,16 @@ sub TransferSlip { =cut sub CheckIfIssuedToPatron { - my ($borrowernumber, $biblionumber) = @_; + my ( $borrowernumber, $biblionumber ) = @_; - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $query = q| SELECT COUNT(*) FROM issues LEFT JOIN items ON items.itemnumber = issues.itemnumber WHERE items.biblionumber = ? AND issues.borrowernumber = ? |; - my $is_issued = $dbh->selectrow_array($query, {}, $biblionumber, $borrowernumber ); + my $is_issued = $dbh->selectrow_array( $query, {}, $biblionumber, $borrowernumber ); return 1 if $is_issued; return; } @@ -4391,12 +4521,14 @@ sub CheckIfIssuedToPatron { sub IsItemIssued { my $itemnumber = shift; - my $dbh = C4::Context->dbh; - my $sth = $dbh->prepare(q{ + my $dbh = C4::Context->dbh; + my $sth = $dbh->prepare( + q{ SELECT COUNT(*) FROM issues WHERE itemnumber = ? - }); + } + ); $sth->execute($itemnumber); return $sth->fetchrow; } @@ -4415,6 +4547,7 @@ sub GetAgeRestriction { my $markers = C4::Context->preference('AgeRestrictionMarker'); return unless $record_restrictions; + # Split $record_restrictions to something like FSK 16 or PEGI 6 my @values = split ' ', uc($record_restrictions); return unless @values; @@ -4435,8 +4568,7 @@ sub GetAgeRestriction { $restriction_year += $values[$index]; } last; - } - elsif ( $value =~ /^\Q$marker\E(\d+)$/ ) { + } elsif ( $value =~ /^\Q$marker\E(\d+)$/ ) { # Perhaps it is something like "K16" (as in Finland) $restriction_year += $1; @@ -4449,14 +4581,14 @@ sub GetAgeRestriction { return $restriction_year; } - =head2 GetPendingOnSiteCheckouts =cut sub GetPendingOnSiteCheckouts { my $dbh = C4::Context->dbh; - return $dbh->selectall_arrayref(q| + return $dbh->selectall_arrayref( + q| SELECT items.barcode, items.biblionumber, @@ -4478,16 +4610,16 @@ sub GetPendingOnSiteCheckouts { LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber WHERE issues.onsite_checkout = 1 - |, { Slice => {} } ); + |, { Slice => {} } + ); } sub GetTopIssues { my ($params) = @_; - my ($count, $branch, $itemtype, $ccode, $newness) - = @$params{qw(count branch itemtype ccode newness)}; + my ( $count, $branch, $itemtype, $ccode, $newness ) = @$params{qw(count branch itemtype ccode newness)}; - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $query = q{ SELECT * FROM ( SELECT b.biblionumber, b.title, b.author, bi.itemtype, bi.publishercode, @@ -4498,14 +4630,14 @@ sub GetTopIssues { LEFT JOIN biblioitems bi ON (bi.biblionumber = b.biblionumber) }; - my (@where_strs, @where_args); + my ( @where_strs, @where_args ); if ($branch) { push @where_strs, 'i.homebranch = ?'; push @where_args, $branch; } if ($itemtype) { - if (C4::Context->preference('item-level_itypes')){ + if ( C4::Context->preference('item-level_itypes') ) { push @where_strs, 'i.itype = ?'; push @where_args, $itemtype; } else { @@ -4523,7 +4655,7 @@ sub GetTopIssues { } if (@where_strs) { - $query .= 'WHERE ' . join(' AND ', @where_strs); + $query .= 'WHERE ' . join( ' AND ', @where_strs ); } $query .= q{ @@ -4535,11 +4667,11 @@ sub GetTopIssues { $query .= q{ ) xxx WHERE count > 0 }; $count = int($count); - if ($count > 0) { + if ( $count > 0 ) { $query .= "LIMIT $count"; } - my $rows = $dbh->selectall_arrayref($query, { Slice => {} }, @where_args); + my $rows = $dbh->selectall_arrayref( $query, { Slice => {} }, @where_args ); return @$rows; } @@ -4564,50 +4696,53 @@ sub _CalculateAndUpdateFine { # we only need to calculate and change the fines if we want to do that on return # Should be on for hourly loans - my $control = C4::Context->preference('CircControl'); + my $control = C4::Context->preference('CircControl'); my $branch_type = C4::Context->preference('HomeOrHoldingBranch') || 'homebranch'; my $control_branchcode = - ( $control eq 'ItemHomeLibrary' ) ? $item->{$branch_type} - : ( $control eq 'PatronLibrary' ) ? $borrower->{branchcode} - : $issue->branchcode; + ( $control eq 'ItemHomeLibrary' ) ? $item->{$branch_type} + : ( $control eq 'PatronLibrary' ) ? $borrower->{branchcode} + : $issue->branchcode; my $date_returned = $return_date ? $return_date : dt_from_string(); - my ( $amount, $unitcounttotal, $unitcount ) = - C4::Overdues::CalcFine( $item, $borrower->{categorycode}, $control_branchcode, $datedue, $date_returned ); + my ( $amount, $unitcounttotal, $unitcount ) = + C4::Overdues::CalcFine( $item, $borrower->{categorycode}, $control_branchcode, $datedue, $date_returned ); if ( C4::Context->preference('finesMode') eq 'production' ) { if ( $amount > 0 ) { - C4::Overdues::UpdateFine({ - issue_id => $issue->issue_id, - itemnumber => $issue->itemnumber, - borrowernumber => $issue->borrowernumber, - amount => $amount, - due => $datedue, - }); - } - elsif ($return_date) { + C4::Overdues::UpdateFine( + { + issue_id => $issue->issue_id, + itemnumber => $issue->itemnumber, + borrowernumber => $issue->borrowernumber, + amount => $amount, + due => $datedue, + } + ); + } elsif ($return_date) { # Backdated returns may have fines that shouldn't exist, # so in this case, we need to drop those fines to 0 - C4::Overdues::UpdateFine({ - issue_id => $issue->issue_id, - itemnumber => $issue->itemnumber, - borrowernumber => $issue->borrowernumber, - amount => 0, - due => $datedue, - }); + C4::Overdues::UpdateFine( + { + issue_id => $issue->issue_id, + itemnumber => $issue->itemnumber, + borrowernumber => $issue->borrowernumber, + amount => 0, + due => $datedue, + } + ); } } } sub _CanBookBeAutoRenewed { - my ( $params ) = @_; - my $patron = $params->{patron}; - my $item = $params->{item}; + my ($params) = @_; + my $patron = $params->{patron}; + my $item = $params->{item}; my $branchcode = $params->{branchcode}; - my $issue = $params->{issue}; + my $issue = $params->{issue}; return "no" unless $issue->auto_renew && $patron->autorenew_checkouts; @@ -4616,7 +4751,7 @@ sub _CanBookBeAutoRenewed { categorycode => $patron->categorycode, itemtype => $item->effective_itemtype, branchcode => $branchcode, - rules => [ + rules => [ 'no_auto_renewal_after', 'no_auto_renewal_after_hard_limit', 'lengthunit', @@ -4630,20 +4765,20 @@ sub _CanBookBeAutoRenewed { } if ( defined $issuing_rule->{no_auto_renewal_after} - and $issuing_rule->{no_auto_renewal_after} ne "" ) { + and $issuing_rule->{no_auto_renewal_after} ne "" ) + { # Get issue_date and add no_auto_renewal_after # If this is greater than today, it's too late for renewal. - my $maximum_renewal_date = dt_from_string($issue->issuedate, 'sql'); - $maximum_renewal_date->add( - $issuing_rule->{lengthunit} => $issuing_rule->{no_auto_renewal_after} - ); + my $maximum_renewal_date = dt_from_string( $issue->issuedate, 'sql' ); + $maximum_renewal_date->add( $issuing_rule->{lengthunit} => $issuing_rule->{no_auto_renewal_after} ); my $now = dt_from_string; if ( $now >= $maximum_renewal_date ) { return "auto_too_late"; } } if ( defined $issuing_rule->{no_auto_renewal_after_hard_limit} - and $issuing_rule->{no_auto_renewal_after_hard_limit} ne "" ) { + and $issuing_rule->{no_auto_renewal_after_hard_limit} ne "" ) + { # If no_auto_renewal_after_hard_limit is >= today, it's also too late for renewal if ( dt_from_string >= dt_from_string( $issuing_rule->{no_auto_renewal_after_hard_limit} ) ) { return "auto_too_late"; @@ -4653,24 +4788,22 @@ sub _CanBookBeAutoRenewed { if ( C4::Context->preference('OPACFineNoRenewalsBlockAutoRenew') ) { my $fine_no_renewals = C4::Context->preference("OPACFineNoRenewals"); my $amountoutstanding = - C4::Context->preference("OPACFineNoRenewalsIncludeCredit") - ? $patron->account->balance - : $patron->account->outstanding_debits->total_outstanding; + C4::Context->preference("OPACFineNoRenewalsIncludeCredit") + ? $patron->account->balance + : $patron->account->outstanding_debits->total_outstanding; if ( $amountoutstanding and $amountoutstanding > $fine_no_renewals ) { return "auto_too_much_oweing"; } } my $soonest = GetSoonestRenewDate( $patron, $issue, 1 ); - if ( $soonest > dt_from_string() ) - { + if ( $soonest > dt_from_string() ) { return ( "auto_too_soon", $soonest ); } return "ok"; } - 1; __END__ diff --git a/C4/ClassSortRoutine.pm b/C4/ClassSortRoutine.pm index dc530790b2..d3d830cd68 100644 --- a/C4/ClassSortRoutine.pm +++ b/C4/ClassSortRoutine.pm @@ -21,13 +21,14 @@ use Modern::Perl; use Class::Factory::Util; -our (@ISA, @EXPORT_OK); +our ( @ISA, @EXPORT_OK ); + BEGIN { require Exporter; - @ISA = qw(Exporter); + @ISA = qw(Exporter); @EXPORT_OK = qw( - GetSortRoutineNames - GetClassSortKey + GetSortRoutineNames + GetClassSortKey ); } @@ -46,12 +47,12 @@ use C4::ClassSortRoutine; # initialization code my %loaded_routines = (); -my @sort_routines = GetSortRoutineNames(); +my @sort_routines = GetSortRoutineNames(); foreach my $sort_routine (@sort_routines) { - if (eval "require C4::ClassSortRoutine::$sort_routine") { + if ( eval "require C4::ClassSortRoutine::$sort_routine" ) { my $ref; $ref = \&{"C4::ClassSortRoutine::${sort_routine}::get_class_sort_key"}; - if (eval { $ref->("a", "b") }) { + if ( eval { $ref->( "a", "b" ) } ) { $loaded_routines{$sort_routine} = $ref; } else { $loaded_routines{$sort_routine} = \&_get_class_sort_key; @@ -87,17 +88,18 @@ normalization routine. =cut sub GetClassSortKey { - my ($sort_routine, $cn_class, $cn_item) = @_; - unless (exists $loaded_routines{$sort_routine}) { + my ( $sort_routine, $cn_class, $cn_item ) = @_; + unless ( exists $loaded_routines{$sort_routine} ) { warn "attempting to use non-existent class sorting routine $sort_routine\n"; $loaded_routines{$sort_routine} = \&_get_class_sort_key; } - my $key = $loaded_routines{$sort_routine}->($cn_class, $cn_item); + my $key = $loaded_routines{$sort_routine}->( $cn_class, $cn_item ); + # FIXME -- hardcoded length for cn_sort # should replace with some way of getting column widths from # the DB schema -- since doing this should ideally be # independent of the DBMS, deferring for the moment. - return substr($key, 0, 255); + return substr( $key, 0, 255 ); } =head2 _get_class_sort_key @@ -110,7 +112,7 @@ letter characters. =cut sub _get_class_sort_key { - my ($cn_class, $cn_item) = @_; + my ( $cn_class, $cn_item ) = @_; my $key = uc "$cn_class $cn_item"; $key =~ s/\s+/_/; $key =~ s/[^A-Z_0-9]//g; diff --git a/C4/ClassSortRoutine/Dewey.pm b/C4/ClassSortRoutine/Dewey.pm index eedf4ed768..d729901c26 100644 --- a/C4/ClassSortRoutine/Dewey.pm +++ b/C4/ClassSortRoutine/Dewey.pm @@ -1,7 +1,7 @@ package C4::ClassSortRoutine::Dewey; # Copyright (C) 2007 LibLime -# +# # This file is part of Koha. # # Koha is free software; you can redistribute it and/or modify it @@ -20,8 +20,6 @@ package C4::ClassSortRoutine::Dewey; use strict; use warnings; - - =head1 NAME C4::ClassSortRoutine::Dewey - generic call number sorting key routine @@ -53,7 +51,7 @@ Generates sorting key using the following rules: =cut sub get_class_sort_key { - my ($cn_class, $cn_item) = @_; + my ( $cn_class, $cn_item ) = @_; $cn_class = '' unless defined $cn_class; $cn_item = '' unless defined $cn_item; @@ -63,30 +61,32 @@ sub get_class_sort_key { $init =~ s/\// /g; $init =~ s!/!!g; $init =~ s/^([\p{IsAlpha}]+)/$1 /; - my @tokens = split /\.|\s+/, $init; + my @tokens = split /\.|\s+/, $init; my $digit_group_count = 0; my $first_digit_group_idx; - for (my $i = 0; $i <= $#tokens; $i++) { - if ($tokens[$i] =~ /^\d+$/) { + + for ( my $i = 0 ; $i <= $#tokens ; $i++ ) { + if ( $tokens[$i] =~ /^\d+$/ ) { $digit_group_count++; - if (1 == $digit_group_count) { + if ( 1 == $digit_group_count ) { $first_digit_group_idx = $i; } - if (2 == $digit_group_count) { - if ($i - $first_digit_group_idx == 1) { - $tokens[$i] = sprintf("%-15.15s", $tokens[$i]); + if ( 2 == $digit_group_count ) { + if ( $i - $first_digit_group_idx == 1 ) { + $tokens[$i] = sprintf( "%-15.15s", $tokens[$i] ); $tokens[$i] =~ tr/ /0/; } else { - $tokens[$first_digit_group_idx] .= '_000000000000000' + $tokens[$first_digit_group_idx] .= '_000000000000000'; } } } } + # Pad the first digit_group if there was only one - if (1 == $digit_group_count) { - $tokens[$first_digit_group_idx] .= '_000000000000000' + if ( 1 == $digit_group_count ) { + $tokens[$first_digit_group_idx] .= '_000000000000000'; } - my $key = join("_", @tokens); + my $key = join( "_", @tokens ); $key =~ s/[^\p{IsAlnum}_]//g; return $key; diff --git a/C4/ClassSortRoutine/Generic.pm b/C4/ClassSortRoutine/Generic.pm index 665dd53ca6..1f7dc7ecaf 100644 --- a/C4/ClassSortRoutine/Generic.pm +++ b/C4/ClassSortRoutine/Generic.pm @@ -1,7 +1,7 @@ package C4::ClassSortRoutine::Generic; # Copyright (C) 2007 LibLime -# +# # This file is part of Koha. # # Koha is free software; you can redistribute it and/or modify it @@ -20,8 +20,6 @@ package C4::ClassSortRoutine::Generic; use strict; use warnings; - - =head1 NAME C4::ClassSortRoutine::Generic - generic call number sorting key routine @@ -48,7 +46,7 @@ Generates sorting key using the following rules: =cut sub get_class_sort_key { - my ($cn_class, $cn_item) = @_; + my ( $cn_class, $cn_item ) = @_; $cn_class = '' unless defined $cn_class; $cn_item = '' unless defined $cn_item; diff --git a/C4/ClassSortRoutine/LCC.pm b/C4/ClassSortRoutine/LCC.pm index b943fb683e..d4844f1471 100644 --- a/C4/ClassSortRoutine/LCC.pm +++ b/C4/ClassSortRoutine/LCC.pm @@ -2,7 +2,7 @@ package C4::ClassSortRoutine::LCC; # Copyright (C) 2007 LibLime # Copyright (C) 2012 Equinox Software, Inc. -# +# # This file is part of Koha. # # Koha is free software; you can redistribute it and/or modify it @@ -22,8 +22,6 @@ use strict; use warnings; use Library::CallNumber::LC; - - =head1 NAME C4::ClassSortRoutine::LCC - generic call number sorting key routine @@ -45,11 +43,11 @@ Generates sorting key for LC call numbers. =cut sub get_class_sort_key { - my ($cn_class, $cn_item) = @_; + my ( $cn_class, $cn_item ) = @_; $cn_class = '' unless defined $cn_class; $cn_item = '' unless defined $cn_item; - my $call_number = Library::CallNumber::LC->new(uc "$cn_class $cn_item"); + my $call_number = Library::CallNumber::LC->new( uc "$cn_class $cn_item" ); return '' unless defined $call_number; my $key = $call_number->normalize(); $key = '' unless defined $key; diff --git a/C4/ClassSource.pm b/C4/ClassSource.pm index 7aea957874..0488b45b02 100644 --- a/C4/ClassSource.pm +++ b/C4/ClassSource.pm @@ -23,10 +23,11 @@ use C4::ClassSortRoutine qw( GetClassSortKey ); use Koha::Cache::Memory::Lite; -our (@ISA, @EXPORT_OK); +our ( @ISA, @EXPORT_OK ); + BEGIN { require Exporter; - @ISA = qw(Exporter); + @ISA = qw(Exporter); @EXPORT_OK = qw( GetClassSources GetClassSource @@ -78,13 +79,13 @@ foreach my $cn_source (sort keys %$sources) { sub GetClassSources { - my $memory_cache = Koha::Cache::Memory::Lite->get_instance(); - my $class_sources = $memory_cache->get_from_cache( "GetClassSource:All" );; - unless( $class_sources ){ + my $memory_cache = Koha::Cache::Memory::Lite->get_instance(); + my $class_sources = $memory_cache->get_from_cache("GetClassSource:All"); + unless ($class_sources) { my $dbh = C4::Context->dbh; my $sth = $dbh->prepare("SELECT * FROM `class_sources`"); $sth->execute(); - while (my $source = $sth->fetchrow_hashref) { + while ( my $source = $sth->fetchrow_hashref ) { $class_sources->{ $source->{'cn_source'} } = $source; } $memory_cache->set_in_cache( "GetClassSource:All", $class_sources ); @@ -107,7 +108,7 @@ sub GetClassSource { return unless $cn_source; my $memory_cache = Koha::Cache::Memory::Lite->get_instance(); my $class_source = $memory_cache->get_from_cache( "GetClassSource:" . $cn_source ); - unless( $class_source ){ + unless ($class_source) { my $dbh = C4::Context->dbh; my $sth = $dbh->prepare("SELECT * FROM `class_sources` WHERE cn_source = ?"); $sth->execute($cn_source); @@ -129,9 +130,9 @@ sub GetClassSortRule { my ($class_sort_rule) = (@_); return unless $class_sort_rule; - my $memory_cache = Koha::Cache::Memory::Lite->get_instance(); + my $memory_cache = Koha::Cache::Memory::Lite->get_instance(); my $class_sort_rules = $memory_cache->get_from_cache( "GetClassSortRule:" . $class_sort_rule ); - unless( $class_sort_rules ){ + unless ($class_sort_rules) { my $dbh = C4::Context->dbh; my $sth = $dbh->prepare("SELECT * FROM `class_sort_rules` WHERE `class_sort_rule` = ?"); $sth->execute($class_sort_rule); @@ -152,21 +153,21 @@ and the defined call number source. sub GetClassSort { - my ($cn_source, $cn_class, $cn_item) = @_; + my ( $cn_source, $cn_class, $cn_item ) = @_; my $source_ref = GetClassSource($cn_source); - unless (defined $source_ref) { - $source_ref = GetClassSource(C4::Context->preference("DefaultClassificationSource")); + unless ( defined $source_ref ) { + $source_ref = GetClassSource( C4::Context->preference("DefaultClassificationSource") ); } my $routine = ""; - if (defined $source_ref) { - my $rule_ref = GetClassSortRule($source_ref->{'class_sort_rule'}); - if (defined $rule_ref) { + if ( defined $source_ref ) { + my $rule_ref = GetClassSortRule( $source_ref->{'class_sort_rule'} ); + if ( defined $rule_ref ) { $routine = $rule_ref->{'sort_routine'}; } - } + } - return GetClassSortKey($routine, $cn_class, $cn_item); + return GetClassSortKey( $routine, $cn_class, $cn_item ); } diff --git a/C4/ClassSplitRoutine.pm b/C4/ClassSplitRoutine.pm index 2da560d71c..7ea7ab4282 100644 --- a/C4/ClassSplitRoutine.pm +++ b/C4/ClassSplitRoutine.pm @@ -21,12 +21,13 @@ use Modern::Perl; use Class::Factory::Util; -our (@ISA, @EXPORT_OK); +our ( @ISA, @EXPORT_OK ); + BEGIN { require Exporter; - @ISA = qw(Exporter); + @ISA = qw(Exporter); @EXPORT_OK = qw( - GetSplitRoutineNames + GetSplitRoutineNames ); } diff --git a/C4/ClassSplitRoutine/Dewey.pm b/C4/ClassSplitRoutine/Dewey.pm index de97e486b1..cdf0d2d615 100644 --- a/C4/ClassSplitRoutine/Dewey.pm +++ b/C4/ClassSplitRoutine/Dewey.pm @@ -40,11 +40,10 @@ my $cn_split = C4::ClassSplitRoutine::Dewey::split_callnumber($cn_item); sub split_callnumber { my ($cn_item) = @_; - my $possible_decimal = - qr/\d{3,}(?:\.\d+)?/; # at least three digits for a DDCN + my $possible_decimal = qr/\d{3,}(?:\.\d+)?/; # at least three digits for a DDCN $cn_item =~ s/\///g - ; # in theory we should be able to simply remove all segmentation markers and arrive at the correct call number... + ; # in theory we should be able to simply remove all segmentation markers and arrive at the correct call number... my (@lines) = $cn_item =~ m/ ^([-a-zA-Z]*\s?(?:$possible_decimal)?) # R220.3 CD-ROM 787.87 # will require extra splitting \s+ @@ -57,13 +56,12 @@ sub split_callnumber { } if ( $lines[0] =~ /^([-a-zA-Z]+)\s?($possible_decimal)$/ ) { - shift @lines; # pull off the mathching first element, like example 1 + shift @lines; # pull off the mathching first element, like example 1 unshift @lines, $1, $2; # replace it with the two pieces } push @lines, split /\s+/, - pop @lines - ; # split the last piece into an arbitrary number of pieces at spaces + pop @lines; # split the last piece into an arbitrary number of pieces at spaces return @lines; } diff --git a/C4/ClassSplitRoutine/Generic.pm b/C4/ClassSplitRoutine/Generic.pm index 48aa85a419..f18a935c98 100644 --- a/C4/ClassSplitRoutine/Generic.pm +++ b/C4/ClassSplitRoutine/Generic.pm @@ -46,11 +46,10 @@ sub split_callnumber { my @lines; # Split call numbers based on spaces - push @lines, split /\s+/, $cn_item - ; # split the call number into an arbitrary number of pieces at spaces + push @lines, split /\s+/, $cn_item; # split the call number into an arbitrary number of pieces at spaces if ( $lines[-1] !~ /^.*\d-\d.*$/ && $lines[-1] =~ /^(.*\d+)(\D.*)$/ ) { - pop @lines; # pull off the matching last element - push @lines, $1, $2; # replace it with the two pieces + pop @lines; # pull off the matching last element + push @lines, $1, $2; # replace it with the two pieces } unless ( scalar @lines ) { warn sprintf( 'regexp failed to match string: %s', $cn_item ); diff --git a/C4/ClassSplitRoutine/LCC.pm b/C4/ClassSplitRoutine/LCC.pm index 98bcab79e5..12901ba3e3 100644 --- a/C4/ClassSplitRoutine/LCC.pm +++ b/C4/ClassSplitRoutine/LCC.pm @@ -42,14 +42,16 @@ my $cn_split = C4::ClassSplitRoutine::LCC::split_callnumber($cn_item); sub split_callnumber { my ($cn_item) = @_; + # lccn examples: 'HE8700.7 .P6T44 1983', 'BS2545.E8 H39 1996'; my @lines = Library::CallNumber::LC->new($cn_item)->components(); - unless (scalar @lines && defined $lines[0]) { - Koha::Logger->get->debug(sprintf('regexp failed to match string: %s', $cn_item)); - @lines = $cn_item; # if no match, just use the whole string. + unless ( scalar @lines && defined $lines[0] ) { + Koha::Logger->get->debug( sprintf( 'regexp failed to match string: %s', $cn_item ) ); + @lines = $cn_item; # if no match, just use the whole string. } my $LastPiece = pop @lines; - push @lines, split /\s+/, $LastPiece if $LastPiece; # split the last piece into an arbitrary number of pieces at spaces + push @lines, split /\s+/, $LastPiece + if $LastPiece; # split the last piece into an arbitrary number of pieces at spaces return @lines; } diff --git a/C4/ClassSplitRoutine/RegEx.pm b/C4/ClassSplitRoutine/RegEx.pm index d6e669999a..29fefd31da 100644 --- a/C4/ClassSplitRoutine/RegEx.pm +++ b/C4/ClassSplitRoutine/RegEx.pm @@ -38,10 +38,10 @@ my $cn_sort = C4::ClassSplitRoutine::RegEx::split_callnumber($cn_item, $regexs); =cut sub split_callnumber { - my ($cn_item, $regexs) = @_; + my ( $cn_item, $regexs ) = @_; - for my $regex ( @$regexs ) { - eval "\$cn_item =~ $regex"; ## no critic (StringyEval) + for my $regex (@$regexs) { + eval "\$cn_item =~ $regex"; ## no critic (StringyEval) } my @lines = split "\n", $cn_item; diff --git a/C4/Context.pm b/C4/Context.pm index 8d49feda7c..bb3080ffde 100644 --- a/C4/Context.pm +++ b/C4/Context.pm @@ -20,8 +20,9 @@ package C4::Context; use Modern::Perl; use vars qw($AUTOLOAD $context); + BEGIN { - if ( $ENV{'HTTP_USER_AGENT'} ) { # Only hit when plack is not enabled + if ( $ENV{'HTTP_USER_AGENT'} ) { # Only hit when plack is not enabled # Redefine multi_param if cgi version is < 4.08 # Remove the "CGI::param called in list context" warning in this case @@ -33,7 +34,7 @@ BEGIN { $CGI::LIST_CONTEXT_WARN = 0; } } -}; +} use Carp qw( carp ); use DateTime::TimeZone; @@ -100,9 +101,10 @@ environment variable to the pathname of a configuration file to use. # Zconn # A connection object for the Zebra server -$context = undef; # Initially, no context is set +$context = undef; # Initially, no context is set sub import { + # Create the default context ($C4::Context::Context) # the first time the module is called # (a config file can be optionaly passed) @@ -111,7 +113,7 @@ sub import { return if $context; # no ? so load it! - my ($pkg,$config_file) = @_ ; + my ( $pkg, $config_file ) = @_; my $new_ctx = __PACKAGE__->new($config_file); return unless $new_ctx; @@ -142,16 +144,17 @@ that, use C<&set_context>. # Revision History: # 2004-08-10 A. Tarallo: Added check if the conf file is not empty sub new { - my $class = shift; - my $conf_fname = shift; # Config file to load + my $class = shift; + my $conf_fname = shift; # Config file to load # check that the specified config file exists and is not empty - undef $conf_fname unless - (defined $conf_fname && -s $conf_fname); + undef $conf_fname + unless ( defined $conf_fname && -s $conf_fname ); + # Figure out a good config file to load if none was specified. unless ( defined $conf_fname ) { $conf_fname = Koha::Config->guess_koha_conf; - unless ( $conf_fname ) { + unless ($conf_fname) { warn "unable to locate Koha configuration file koha-conf.xml"; return; } @@ -164,10 +167,10 @@ sub new { return; } - $self->{"Zconn"} = undef; # Zebra Connections - $self->{"userenv"} = undef; # User env + $self->{"Zconn"} = undef; # Zebra Connections + $self->{"userenv"} = undef; # User env $self->{"shelves"} = undef; - $self->{tz} = undef; # local timezone object + $self->{tz} = undef; # local timezone object bless $self, $class; return $self; @@ -183,8 +186,7 @@ or =cut #' -sub set_context -{ +sub set_context { my $self = shift; my $new_context; # The context to set @@ -197,11 +199,12 @@ sub set_context # break this assumption by playing silly buggers, but that's # harder to do than doing it properly, and harder to check # for. - if (ref($self) eq "") - { + if ( ref($self) eq "" ) { + # Class method. The new context is the next argument. $new_context = shift; } else { + # Instance method. The new context is $self. $new_context = $self; } @@ -220,18 +223,19 @@ from which the current context was created. =cut sub _common_config { - my ($var, $term) = @_; + my ( $var, $term ) = @_; return unless defined $context and defined $context->{config}; - return $context->{config}->get($var, $term); + return $context->{config}->get( $var, $term ); } sub config { - return _common_config($_[1],'config'); + return _common_config( $_[1], 'config' ); } + sub zebraconfig { - return _common_config($_[1],'server'); + return _common_config( $_[1], 'server' ); } =head2 preference @@ -251,18 +255,19 @@ with this method. =cut my $use_syspref_cache = 1; + sub preference { my $self = shift; my $var = shift; # The system preference to return - return Encode::decode_utf8($ENV{"OVERRIDE_SYSPREF_$var"}) + return Encode::decode_utf8( $ENV{"OVERRIDE_SYSPREF_$var"} ) if defined $ENV{"OVERRIDE_SYSPREF_$var"}; $var = lc $var; if ($use_syspref_cache) { my $syspref_cache = Koha::Caches->get_instance('syspref'); - my $cached_var = $syspref_cache->get_from_cache("syspref_$var"); + my $cached_var = $syspref_cache->get_from_cache("syspref_$var"); return $cached_var if defined $cached_var; } @@ -270,9 +275,9 @@ sub preference { eval { $syspref = Koha::Config::SysPrefs->find( lc $var ) }; my $value = $syspref ? $syspref->value() : undef; - if ( $use_syspref_cache ) { + if ($use_syspref_cache) { my $syspref_cache = Koha::Caches->get_instance('syspref'); - $syspref_cache->set_in_cache("syspref_$var", $value); + $syspref_cache->set_in_cache( "syspref_$var", $value ); } return $value; } @@ -288,14 +293,17 @@ the value cannot be properly decoded as YAML. sub yaml_preference { my ( $self, $preference ) = @_; - my $yaml = eval { YAML::XS::Load( Encode::encode_utf8( $self->preference( $preference ) // '' ) ); }; + my $yaml = eval { YAML::XS::Load( Encode::encode_utf8( $self->preference($preference) // '' ) ); }; if ($@) { warn "Unable to parse $preference syspref : $@"; return; } # TODO Remove next line when enforced elsewhere - if( $yaml && lc($preference) eq 'itemsdeniedrenewal' and ref($yaml) ne 'HASH' ) { warn "Hashref expected for $preference"; return; } + if ( $yaml && lc($preference) eq 'itemsdeniedrenewal' and ref($yaml) ne 'HASH' ) { + warn "Hashref expected for $preference"; + return; + } return $yaml; } @@ -327,6 +335,7 @@ default behavior. sub enable_syspref_cache { my ($self) = @_; $use_syspref_cache = 1; + # We need to clear the cache to have it up-to-date $self->clear_syspref_cache(); } @@ -381,9 +390,9 @@ sub set_preference { my $syspref = Koha::Config::SysPrefs->find($variable); $type = - $type ? $type - : $syspref ? $syspref->type - : undef; + $type ? $type + : $syspref ? $syspref->type + : undef; $value = 0 if ( $type && $type eq 'YesNo' && $value eq '' ); @@ -394,7 +403,8 @@ sub set_preference { if ($syspref) { $syspref->set( - { ( defined $value ? ( value => $value ) : () ), + { + ( defined $value ? ( value => $value ) : () ), ( $explanation ? ( explanation => $explanation ) : () ), ( $type ? ( type => $type ) : () ), ( $options ? ( options => $options ) : () ), @@ -402,7 +412,8 @@ sub set_preference { )->store; } else { $syspref = Koha::Config::SysPref->new( - { variable => $variable_case, + { + variable => $variable_case, value => $value, explanation => $explanation || undef, type => $type, @@ -411,7 +422,7 @@ sub set_preference { )->store(); } - if ( $use_syspref_cache ) { + if ($use_syspref_cache) { my $syspref_cache = Koha::Caches->get_instance('syspref'); $syspref_cache->set_in_cache( "syspref_$variable", $value ); } @@ -433,8 +444,8 @@ sub delete_preference { my ( $self, $var ) = @_; $var = lc $var; - if ( Koha::Config::SysPrefs->find( $var )->delete ) { - if ( $use_syspref_cache ) { + if ( Koha::Config::SysPrefs->find($var)->delete ) { + if ($use_syspref_cache) { my $syspref_cache = Koha::Caches->get_instance('syspref'); $syspref_cache->clear_from_cache("syspref_$var"); } @@ -511,13 +522,17 @@ C<$async> whether this is a asynchronous connection =cut sub Zconn { - my ($self, $server, $async ) = @_; - my $cache_key = join ('::', (map { $_ // '' } ($server, $async ))); - if ( (!defined($ENV{GATEWAY_INTERFACE})) && defined($context->{"Zconn"}->{$cache_key}) && (0 == $context->{"Zconn"}->{$cache_key}->errcode()) ) { + my ( $self, $server, $async ) = @_; + my $cache_key = join( '::', ( map { $_ // '' } ( $server, $async ) ) ); + if ( ( !defined( $ENV{GATEWAY_INTERFACE} ) ) + && defined( $context->{"Zconn"}->{$cache_key} ) + && ( 0 == $context->{"Zconn"}->{$cache_key}->errcode() ) ) + { # if we are running the script from the commandline, lets try to use the caching return $context->{"Zconn"}->{$cache_key}; } - $context->{"Zconn"}->{$cache_key}->destroy() if defined($context->{"Zconn"}->{$cache_key}); #destroy old connection before making a new one + $context->{"Zconn"}->{$cache_key}->destroy() + if defined( $context->{"Zconn"}->{$cache_key} ); #destroy old connection before making a new one $context->{"Zconn"}->{$cache_key} = &_new_Zconn( $server, $async ); return $context->{"Zconn"}->{$cache_key}; } @@ -539,43 +554,43 @@ C<$auth> whether this connection has rw access (1) or just r access (0 or NULL) sub _new_Zconn { my ( $server, $async ) = @_; - my $tried=0; # first attempt - my $Zconn; # connection object + my $tried = 0; # first attempt + my $Zconn; # connection object my $elementSetName; my $syntax; $server //= "biblioserver"; - $syntax = 'xml'; + $syntax = 'xml'; $elementSetName = 'marcxml'; - my $host = _common_config($server, 'listen')->{content}; - my $serverinfo = _common_config($server, 'serverinfo'); - my $user = $serverinfo->{user}; - my $password = $serverinfo->{password}; + my $host = _common_config( $server, 'listen' )->{content}; + my $serverinfo = _common_config( $server, 'serverinfo' ); + my $user = $serverinfo->{user}; + my $password = $serverinfo->{password}; eval { # set options my $o = ZOOM::Options->new(); - $o->option(user => $user) if $user && $password; - $o->option(password => $password) if $user && $password; - $o->option(async => 1) if $async; - $o->option(cqlfile=> _common_config($server, 'server')->{cql2rpn}); - $o->option(cclfile=> $serverinfo->{ccl2rpn}); - $o->option(preferredRecordSyntax => $syntax); - $o->option(elementSetName => $elementSetName) if $elementSetName; - $o->option(databaseName => _common_config($server, 'config') || 'biblios'); + $o->option( user => $user ) if $user && $password; + $o->option( password => $password ) if $user && $password; + $o->option( async => 1 ) if $async; + $o->option( cqlfile => _common_config( $server, 'server' )->{cql2rpn} ); + $o->option( cclfile => $serverinfo->{ccl2rpn} ); + $o->option( preferredRecordSyntax => $syntax ); + $o->option( elementSetName => $elementSetName ) if $elementSetName; + $o->option( databaseName => _common_config( $server, 'config' ) || 'biblios' ); my $timeout = C4::Context->config('zebra_connection_timeout') || 30; - $o->option(timeout => $timeout); + $o->option( timeout => $timeout ); # create a new connection object - $Zconn= create ZOOM::Connection($o); + $Zconn = create ZOOM::Connection($o); # forge to server - $Zconn->connect($host, 0); + $Zconn->connect( $host, 0 ); # check for errors and warn - if ($Zconn->errcode() !=0) { - warn "something wrong with the connection: ". $Zconn->errmsg(); + if ( $Zconn->errcode() != 0 ) { + warn "something wrong with the connection: " . $Zconn->errmsg(); } }; return $Zconn; @@ -585,10 +600,9 @@ sub _new_Zconn { # Internal helper function (not a method!). This creates a new # database connection from the data given in the current context, and # returns it. -sub _new_dbh -{ +sub _new_dbh { - Koha::Database->schema({ new => 1 })->storage->dbh; + Koha::Database->schema( { new => 1 } )->storage->dbh; } =head2 dbh @@ -601,16 +615,15 @@ creates one, and connects to the database. =cut -sub dbh -{ - my $self = shift; +sub dbh { + my $self = shift; my $params = shift; unless ( $params->{new} ) { return Koha::Database->schema->storage->dbh; } - return Koha::Database->schema({ new => 1 })->storage->dbh; + return Koha::Database->schema( { new => 1 } )->storage->dbh; } =head2 new_dbh @@ -627,11 +640,10 @@ connect to so that the caller doesn't have to know. =cut #' -sub new_dbh -{ +sub new_dbh { my $self = shift; - return &dbh({ new => 1 }); + return &dbh( { new => 1 } ); } =head2 userenv @@ -701,12 +713,10 @@ Destroys user environment variables. =cut -sub unset_userenv -{ +sub unset_userenv { $context->{userenv} = undef; } - =head2 get_versions C4::Context->get_versions @@ -720,22 +730,22 @@ Gets various version info, for core Koha packages, Currently called from carp ha # A little example sub to show more debugging info for CGI::Carp sub get_versions { my ( %versions, $mysqlVersion ); - $versions{kohaVersion} = Koha::version(); + $versions{kohaVersion} = Koha::version(); $versions{kohaDbVersion} = C4::Context->preference('version'); - $versions{osVersion} = join(" ", POSIX::uname()); - $versions{perlVersion} = $]; + $versions{osVersion} = join( " ", POSIX::uname() ); + $versions{perlVersion} = $]; my $dbh = C4::Context->dbh; - $mysqlVersion = $dbh->get_info(18) if $dbh; # SQL_DBMS_VER + $mysqlVersion = $dbh->get_info(18) if $dbh; # SQL_DBMS_VER { - no warnings qw(exec); # suppress warnings if unable to find a program in $PATH - $mysqlVersion ||= `mysql -V`; # fallback to sql client version? + no warnings qw(exec); # suppress warnings if unable to find a program in $PATH + $mysqlVersion ||= `mysql -V`; # fallback to sql client version? $versions{apacheVersion} = (`apache2ctl -v`)[0]; - $versions{apacheVersion} = `httpd -v` unless $versions{apacheVersion} ; - $versions{apacheVersion} = `httpd2 -v` unless $versions{apacheVersion} ; - $versions{apacheVersion} = `apache2 -v` unless $versions{apacheVersion} ; - $versions{apacheVersion} = `/usr/sbin/apache2 -v` unless $versions{apacheVersion} ; + $versions{apacheVersion} = `httpd -v` unless $versions{apacheVersion}; + $versions{apacheVersion} = `httpd2 -v` unless $versions{apacheVersion}; + $versions{apacheVersion} = `apache2 -v` unless $versions{apacheVersion}; + $versions{apacheVersion} = `/usr/sbin/apache2 -v` unless $versions{apacheVersion}; } $versions{mysqlVersion} = $mysqlVersion; return %versions; @@ -751,14 +761,13 @@ sub get_versions { sub tz { my $self = shift; - if (!defined $context->{tz}) { + if ( !defined $context->{tz} ) { my $timezone = $context->{config}->timezone; - $context->{tz} = DateTime::TimeZone->new(name => $timezone); + $context->{tz} = DateTime::TimeZone->new( name => $timezone ); } return $context->{tz}; } - =head2 IsSuperLibrarian C4::Context->IsSuperLibrarian(); @@ -769,6 +778,7 @@ sub IsSuperLibrarian { my $userenv = C4::Context->userenv; unless ( $userenv and exists $userenv->{flags} ) { + # If we reach this without a user environment, # assume that we're running from a command-line script, # and act as a superlibrarian. @@ -776,7 +786,7 @@ sub IsSuperLibrarian { return 1; } - return ($userenv->{flags}//0) % 2; + return ( $userenv->{flags} // 0 ) % 2; } =head2 interface @@ -790,9 +800,9 @@ Sets the current interface for later retrieval in any Perl module =cut sub interface { - my ($class, $interface) = @_; + my ( $class, $interface ) = @_; - if (defined $interface) { + if ( defined $interface ) { $interface = lc $interface; if ( $interface eq 'api' || $interface eq 'opac' @@ -812,7 +822,7 @@ sub interface { # always returns a string for OK comparison via "eq" or "ne" sub mybranch { - C4::Context->userenv or return ''; + C4::Context->userenv or return ''; return C4::Context->userenv->{branch} || ''; } @@ -827,10 +837,10 @@ sub mybranch { sub only_my_library { return - C4::Context->preference('IndependentBranches') - && C4::Context->userenv - && !C4::Context->IsSuperLibrarian() - && C4::Context->userenv->{branch}; + C4::Context->preference('IndependentBranches') + && C4::Context->userenv + && !C4::Context->IsSuperLibrarian() + && C4::Context->userenv->{branch}; } =head3 temporary_directory @@ -840,7 +850,7 @@ Returns root directory for temporary storage =cut sub temporary_directory { - my ( $class ) = @_; + my ($class) = @_; return C4::Context->config('tmp_path') || File::Spec->tmpdir; } @@ -881,9 +891,9 @@ We are relying on the convention of the value being "on" or "ON" here. sub https_enabled { my $https_enabled = 0; - my $env_https = $ENV{HTTPS}; - if ($env_https){ - if ($env_https =~ /^ON$/i){ + my $env_https = $ENV{HTTPS}; + if ($env_https) { + if ( $env_https =~ /^ON$/i ) { $https_enabled = 1; } } @@ -902,7 +912,7 @@ This method returns a boolean representing the install status of the Koha instan sub needs_install { my ($self) = @_; - return ($self->preference('Version')) ? 0 : 1; + return ( $self->preference('Version') ) ? 0 : 1; } =head3 psgi_env @@ -914,7 +924,7 @@ this is a PSGI app or a CGI app, and implementing code as appropriate. =cut sub psgi_env { - my ( $self ) = @_; + my ($self) = @_; return any { /^(psgi\.|plack\.|PLACK_ENV$)/i } keys %ENV; } @@ -928,9 +938,9 @@ app #NOTE: This is not a very robust method but it's the best we have so far sub is_internal_PSGI_request { - my ( $self ) = @_; + my ($self) = @_; my $is_internal = 0; - if( $self->psgi_env && ( $ENV{REQUEST_URI} !~ /^(\/intranet|\/opac)/ ) ) { + if ( $self->psgi_env && ( $ENV{REQUEST_URI} !~ /^(\/intranet|\/opac)/ ) ) { $is_internal = 1; } return $is_internal; diff --git a/C4/Contract.pm b/C4/Contract.pm index 2630af403e..d18fd295ca 100644 --- a/C4/Contract.pm +++ b/C4/Contract.pm @@ -27,11 +27,11 @@ BEGIN { require Exporter; @ISA = qw(Exporter); @EXPORT = qw( - GetContracts - GetContract - AddContract - ModContract - DelContract + GetContracts + GetContract + AddContract + ModContract + DelContract ); } @@ -51,7 +51,6 @@ a contract. =cut - =head2 GetContracts $contractlist = GetContracts({ @@ -75,8 +74,8 @@ Returns a list of contracts sub GetContracts { my ($filters) = @_; - if( $filters->{activeonly} ) { - $filters->{contractenddate} = {'>=' => \'now()'}; + if ( $filters->{activeonly} ) { + $filters->{contractenddate} = { '>=' => \'now()' }; delete $filters->{activeonly}; } @@ -102,15 +101,17 @@ sub GetContract { return unless $contractnumber; - my $contracts = GetContracts({ - contractnumber => $contractnumber, - }); + my $contracts = GetContracts( + { + contractnumber => $contractnumber, + } + ); return $contracts->[0]; } sub AddContract { my ($contract) = @_; - return unless($contract->{booksellerid}); + return unless ( $contract->{booksellerid} ); my $rs = Koha::Database->new()->schema->resultset('Aqcontract'); return $rs->create($contract)->id; @@ -119,7 +120,7 @@ sub AddContract { sub ModContract { my ($contract) = @_; my $result = Koha::Database->new()->schema->resultset('Aqcontract')->find($contract); - return unless($result); + return unless ($result); $result = $result->update($contract); return $result->in_storage; @@ -127,10 +128,10 @@ sub ModContract { sub DelContract { my ($contract) = @_; - return unless($contract->{contractnumber}); + return unless ( $contract->{contractnumber} ); my $result = Koha::Database->new()->schema->resultset('Aqcontract')->find($contract); - return unless($result); + return unless ($result); eval { $result->delete }; return !( $result->in_storage ); diff --git a/C4/CourseReserves.pm b/C4/CourseReserves.pm index fac8b849e2..994aadb2dc 100644 --- a/C4/CourseReserves.pm +++ b/C4/CourseReserves.pm @@ -28,30 +28,31 @@ use Koha::Course::Reserves; use Koha::Checkouts; use vars qw(@FIELDS); -our (@ISA, @EXPORT_OK); +our ( @ISA, @EXPORT_OK ); + BEGIN { require Exporter; @ISA = qw(Exporter); @EXPORT_OK = qw( - GetCourse - ModCourse - GetCourses - DelCourse + GetCourse + ModCourse + GetCourses + DelCourse - GetCourseInstructors - ModCourseInstructors + GetCourseInstructors + ModCourseInstructors - GetCourseItem - ModCourseItem + GetCourseItem + ModCourseItem - GetCourseReserve - ModCourseReserve - GetCourseReserves - DelCourseReserve + GetCourseReserve + ModCourseReserve + GetCourseReserves + DelCourseReserve - SearchCourses + SearchCourses - GetItemCourseReservesInfo + GetItemCourseReservesInfo ); @FIELDS = ( 'itype', 'ccode', 'homebranch', 'holdingbranch', 'location' ); @@ -80,11 +81,11 @@ This module deals with course reserves. sub GetCourse { my ($course_id) = @_; - my $course = Koha::Courses->find( $course_id ); + my $course = Koha::Courses->find($course_id); return unless $course; $course = $course->unblessed; - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $query = " SELECT b.* FROM course_instructors ci LEFT JOIN borrowers b ON ( ci.borrowernumber = b.borrowernumber ) @@ -136,7 +137,7 @@ sub ModCourse { $dbh->do( $query, undef, @query_values ); $course_id = $course_id - || $dbh->last_insert_id( undef, undef, 'courses', 'course_id' ); + || $dbh->last_insert_id( undef, undef, 'courses', 'course_id' ); EnableOrDisableCourseItems( course_id => $course_id, @@ -177,7 +178,8 @@ sub GetCourses { $query .= join( ' AND ', @query_keys ); } - $query .= " GROUP BY c.course_id, c.department, c.course_number, c.section, c.course_name, c.term, c.staff_note, c.public_note, c.students_count, c.enabled, c.timestamp "; + $query .= + " GROUP BY c.course_id, c.department, c.course_number, c.section, c.course_name, c.term, c.staff_note, c.public_note, c.students_count, c.enabled, c.timestamp "; my $dbh = C4::Context->dbh; my $sth = $dbh->prepare($query); @@ -238,7 +240,7 @@ sub EnableOrDisableCourseItems { my (%params) = @_; my $course_id = $params{'course_id'}; - my $enabled = $params{'enabled'} || 0; + my $enabled = $params{'enabled'} || 0; my $lookfor = ( $enabled eq 'yes' ) ? 'no' : 'yes'; @@ -249,13 +251,15 @@ sub EnableOrDisableCourseItems { if ( $enabled eq 'yes' ) { foreach my $course_reserve (@$course_reserves) { - if (CountCourseReservesForItem( + if ( + CountCourseReservesForItem( ci_id => $course_reserve->{'ci_id'}, enabled => 'yes' ) - ) { + ) + { EnableOrDisableCourseItem( - ci_id => $course_reserve->{'ci_id'}, + ci_id => $course_reserve->{'ci_id'}, ); } } @@ -267,9 +271,10 @@ sub EnableOrDisableCourseItems { ci_id => $course_reserve->{'ci_id'}, enabled => 'yes' ) - ) { + ) + { EnableOrDisableCourseItem( - ci_id => $course_reserve->{'ci_id'}, + ci_id => $course_reserve->{'ci_id'}, ); } } @@ -285,13 +290,16 @@ sub EnableOrDisableCourseItems { sub EnableOrDisableCourseItem { my (%params) = @_; - my $ci_id = $params{'ci_id'}; + my $ci_id = $params{'ci_id'}; - return unless ( $ci_id ); + return unless ($ci_id); my $course_item = GetCourseItem( ci_id => $ci_id ); - my $info = $course_item->{itemnumber} ? GetItemCourseReservesInfo( itemnumber => $course_item->{itemnumber} ) : GetItemCourseReservesInfo( biblionumber => $course_item->{biblionumber} ); + my $info = + $course_item->{itemnumber} + ? GetItemCourseReservesInfo( itemnumber => $course_item->{itemnumber} ) + : GetItemCourseReservesInfo( biblionumber => $course_item->{biblionumber} ); my $enabled = any { $_->{course}->{enabled} eq 'yes' } @$info; $enabled = $enabled ? 'yes' : 'no'; @@ -300,7 +308,7 @@ sub EnableOrDisableCourseItem { ## or disable and already disabled item, ## as that would cause the fields to swap if ( $course_item->{'enabled'} ne $enabled ) { - _SwapAllFields($ci_id, $enabled ); + _SwapAllFields( $ci_id, $enabled ); my $query = " UPDATE course_items @@ -358,25 +366,25 @@ sub ModCourseInstructors { return unless ($course_id); return - unless ( $mode eq 'replace' + unless ( $mode eq 'replace' || $mode eq 'add' || $mode eq 'delete' ); return unless ( $cardnumbers || $borrowernumbers ); return if ( $cardnumbers && $borrowernumbers ); my ( @cardnumbers, @borrowernumbers ); - @cardnumbers = @$cardnumbers if ( ref($cardnumbers) eq 'ARRAY' ); + @cardnumbers = @$cardnumbers if ( ref($cardnumbers) eq 'ARRAY' ); @borrowernumbers = @$borrowernumbers - if ( ref($borrowernumbers) eq 'ARRAY' ); + if ( ref($borrowernumbers) eq 'ARRAY' ); - my $field = (@cardnumbers) ? 'cardnumber' : 'borrowernumber'; - my @fields = (@cardnumbers) ? @cardnumbers : @borrowernumbers; + my $field = (@cardnumbers) ? 'cardnumber' : 'borrowernumber'; + my @fields = (@cardnumbers) ? @cardnumbers : @borrowernumbers; my $placeholders = join( ',', ('?') x scalar @fields ); my $dbh = C4::Context->dbh; $dbh->do( "DELETE FROM course_instructors WHERE course_id = ?", undef, $course_id ) - if ( $mode eq 'replace' ); + if ( $mode eq 'replace' ); my $query; @@ -415,17 +423,17 @@ sub ModCourseInstructors { sub GetCourseItem { my (%params) = @_; - my $ci_id = $params{'ci_id'}; - my $itemnumber = $params{'itemnumber'}; + my $ci_id = $params{'ci_id'}; + my $itemnumber = $params{'itemnumber'}; my $biblionumber = $params{'biblionumber'}; return unless ( $itemnumber xor $biblionumber xor $ci_id ); my ( $field, $value ); - if ( $itemnumber ) { + if ($itemnumber) { $field = 'itemnumber'; $value = $itemnumber; - } elsif ( $biblionumber ) { + } elsif ($biblionumber) { $field = 'biblionumber'; $value = $biblionumber; } else { @@ -447,7 +455,7 @@ sub GetCourseItem { my $course_reserves = $sth->fetchall_arrayref( {} ); $course_item->{'course_reserves'} = $course_reserves - if ($course_reserves); + if ($course_reserves); } return $course_item; } @@ -463,15 +471,16 @@ sub GetCourseItem { sub ModCourseItem { my (%params) = @_; - my $itemnumber = $params{'itemnumber'}; + my $itemnumber = $params{'itemnumber'}; my $biblionumber = $params{'biblionumber'}; - return unless ($itemnumber xor $biblionumber); + return unless ( $itemnumber xor $biblionumber ); - my $course_item = $itemnumber ? GetCourseItem( itemnumber => $itemnumber ) : GetCourseItem( biblionumber => $biblionumber ); + my $course_item = + $itemnumber ? GetCourseItem( itemnumber => $itemnumber ) : GetCourseItem( biblionumber => $biblionumber ); if ( $itemnumber and !$biblionumber ) { - $biblionumber = Koha::Items->find( $itemnumber )->biblionumber; + $biblionumber = Koha::Items->find($itemnumber)->biblionumber; $params{biblionumber} = $biblionumber; } @@ -502,15 +511,15 @@ sub ModCourseItem { sub _AddCourseItem { my (%params) = @_; - $params{homebranch} ||= undef; # Can't be empty string, FK constraint - $params{holdingbranch} ||= undef; # Can't be empty string, FK constraint + $params{homebranch} ||= undef; # Can't be empty string, FK constraint + $params{holdingbranch} ||= undef; # Can't be empty string, FK constraint - my %data = map { $_ => $params{$_} } @FIELDS; + my %data = map { $_ => $params{$_} } @FIELDS; my %enabled = map { $_ . "_enabled" => $params{ $_ . "_enabled" } } @FIELDS; my $ci = Koha::Course::Item->new( { - itemnumber => $params{itemnumber}, + itemnumber => $params{itemnumber}, biblionumber => $params{biblionumber}, %data, %enabled, @@ -529,20 +538,21 @@ sub _AddCourseItem { sub _UpdateCourseItem { my (%params) = @_; - my $ci_id = $params{'ci_id'}; - my $course_item = $params{'course_item'}; + my $ci_id = $params{'ci_id'}; + my $course_item = $params{'course_item'}; - $params{homebranch} ||= undef; # Can't be empty string, FK constraint - $params{holdingbranch} ||= undef; # Can't be empty string, FK constraint + $params{homebranch} ||= undef; # Can't be empty string, FK constraint + $params{holdingbranch} ||= undef; # Can't be empty string, FK constraint return unless ( $ci_id || $course_item ); $course_item = Koha::Course::Items->find( $ci_id || $course_item->{ci_id} ); - my %data = map { $_ => $params{$_} } @FIELDS; + my %data = map { $_ => $params{$_} } @FIELDS; my %enabled = map { $_ . "_enabled" => $params{ $_ . "_enabled" } } @FIELDS; if ( $course_item->itemnumber ) { + # biblio-level course items don't store any of these fields my $item = Koha::Items->find( $course_item->itemnumber ); @@ -550,7 +560,7 @@ sub _UpdateCourseItem { if ( $course_item->is_enabled ) { my $item_fields = {}; - for my $field ( @FIELDS ) { + for my $field (@FIELDS) { my $field_enabled = $field . '_enabled'; my $field_storage = $field . '_storage'; @@ -558,21 +568,23 @@ sub _UpdateCourseItem { # Find newly enabled field and add item value to storage if ( $params{$field_enabled} && !$course_item->$field_enabled ) { $enabled{$field_storage} = $item->$field; - $item_fields->{$field} = $params{$field}; + $item_fields->{$field} = $params{$field}; } + # Find newly disabled field and copy the storage value to the item, unset storage value elsif ( !$params{$field_enabled} && $course_item->$field_enabled ) { - $item_fields->{$field} = $course_item->$field_storage; + $item_fields->{$field} = $course_item->$field_storage; $enabled{$field_storage} = undef; } + # The field was already enabled, copy the incoming value to the item. # The "original" ( when not on course reserve ) value is already in the storage field - elsif ( $course_item->$field_enabled) { + elsif ( $course_item->$field_enabled ) { $item_fields->{$field} = $params{$field}; } } - $item->set( $item_fields )->store + $item->set($item_fields)->store if keys %$item_fields; } } @@ -596,18 +608,16 @@ sub _RevertFields { return unless $ci_id; - my $course_item = Koha::Course::Items->find( $ci_id ); + my $course_item = Koha::Course::Items->find($ci_id); my $item_fields = {}; $item_fields->{itype} = $course_item->itype_storage if $course_item->itype_enabled; $item_fields->{ccode} = $course_item->ccode_storage if $course_item->ccode_enabled; $item_fields->{location} = $course_item->location_storage if $course_item->location_enabled; - $item_fields->{homebranch} = $course_item->homebranch_storage if $course_item->homebranch_enabled; + $item_fields->{homebranch} = $course_item->homebranch_storage if $course_item->homebranch_enabled; $item_fields->{holdingbranch} = $course_item->holdingbranch_storage if $course_item->holdingbranch_enabled; - Koha::Items->find( $course_item->itemnumber ) - ->set( $item_fields ) - ->store + Koha::Items->find( $course_item->itemnumber )->set($item_fields)->store if keys %$item_fields; $course_item->itype_storage(undef); @@ -627,10 +637,10 @@ sub _RevertFields { sub _SwapAllFields { my ( $ci_id, $enabled ) = @_; - my $course_item = Koha::Course::Items->find( $ci_id ); - my $item = Koha::Items->find( $course_item->itemnumber ); + my $course_item = Koha::Course::Items->find($ci_id); + my $item = Koha::Items->find( $course_item->itemnumber ); - if ( $enabled eq 'yes' ) { # Copy item fields to course item storage, course item fields to item + if ( $enabled eq 'yes' ) { # Copy item fields to course item storage, course item fields to item $course_item->itype_storage( $item->effective_itemtype ) if $course_item->itype_enabled; $course_item->ccode_storage( $item->ccode ) if $course_item->ccode_enabled; $course_item->location_storage( $item->location ) if $course_item->location_enabled; @@ -645,12 +655,10 @@ sub _SwapAllFields { $item_fields->{homebranch} = $course_item->homebranch if $course_item->homebranch_enabled; $item_fields->{holdingbranch} = $course_item->holdingbranch if $course_item->holdingbranch_enabled; - Koha::Items->find( $course_item->itemnumber ) - ->set( $item_fields ) - ->store + Koha::Items->find( $course_item->itemnumber )->set($item_fields)->store if keys %$item_fields; - } else { # Copy course item storage to item + } else { # Copy course item storage to item my $item_fields = {}; $item_fields->{itype} = $course_item->itype_storage if $course_item->itype_enabled; $item_fields->{ccode} = $course_item->ccode_storage if $course_item->ccode_enabled; @@ -658,9 +666,7 @@ sub _SwapAllFields { $item_fields->{homebranch} = $course_item->homebranch_storage if $course_item->homebranch_enabled; $item_fields->{holdingbranch} = $course_item->holdingbranch_storage if $course_item->holdingbranch_enabled; - Koha::Items->find( $course_item->itemnumber ) - ->set( $item_fields ) - ->store + Koha::Items->find( $course_item->itemnumber )->set($item_fields)->store if keys %$item_fields; $course_item->itype_storage(undef); @@ -726,7 +732,7 @@ sub DelCourseItem { return unless ($ci_id); - my $course_item = Koha::Course::Items->find( $ci_id ); + my $course_item = Koha::Course::Items->find($ci_id); return unless $course_item; _RevertFields( ci_id => $ci_id ) if $course_item->enabled eq 'yes'; @@ -819,7 +825,7 @@ sub ModCourseReserve { } EnableOrDisableCourseItem( - ci_id => $params{'ci_id'}, + ci_id => $params{'ci_id'}, ); return $cr_id; @@ -866,14 +872,17 @@ sub GetCourseReserves { if ($include_items) { foreach my $cr (@$course_reserves) { - my $item = Koha::Items->find( $cr->{itemnumber}, { prefetch => ['biblio','biblioitem'] }); - my $biblio = $cr->{itemnumber} ? $item->biblio : Koha::Biblios->find( $cr->{biblionumber}, { prefetch => ['biblioitem'] }); + my $item = Koha::Items->find( $cr->{itemnumber}, { prefetch => [ 'biblio', 'biblioitem' ] } ); + my $biblio = + $cr->{itemnumber} + ? $item->biblio + : Koha::Biblios->find( $cr->{biblionumber}, { prefetch => ['biblioitem'] } ); my $biblioitem = $biblio->biblioitem; $cr->{'course_item'} = GetCourseItem( ci_id => $cr->{'ci_id'} ); $cr->{'item'} = $item; $cr->{'biblio'} = $biblio; $cr->{'biblioitem'} = $biblioitem; - $cr->{'issue'} = Koha::Checkouts->find({ itemnumber => $cr->{'itemnumber'} }); + $cr->{'issue'} = Koha::Checkouts->find( { itemnumber => $cr->{'itemnumber'} } ); } } @@ -885,7 +894,10 @@ sub GetCourseReserves { if ($include_courses) { foreach my $cr (@$course_reserves) { - $cr->{'courses'} = $cr->{itemnumber} ? GetCourses( itemnumber => $cr->{'itemnumber'} ) : GetCourses( biblionumber => $cr->{biblionumber} ); + $cr->{'courses'} = + $cr->{itemnumber} + ? GetCourses( itemnumber => $cr->{'itemnumber'} ) + : GetCourses( biblionumber => $cr->{biblionumber} ); } } @@ -936,12 +948,13 @@ sub DelCourseReserve { sub GetItemCourseReservesInfo { my (%params) = @_; - my $itemnumber = $params{'itemnumber'}; + my $itemnumber = $params{'itemnumber'}; my $biblionumber = $params{'biblionumber'}; - return unless ($itemnumber xor $biblionumber); + return unless ( $itemnumber xor $biblionumber ); - my $course_item = $itemnumber ? GetCourseItem( itemnumber => $itemnumber ) : GetCourseItem( biblionumber => $biblionumber ); + my $course_item = + $itemnumber ? GetCourseItem( itemnumber => $itemnumber ) : GetCourseItem( biblionumber => $biblionumber ); return unless ( keys %$course_item ); @@ -973,14 +986,17 @@ sub GetItemCourseReservesInfo { sub CountCourseReservesForItem { my (%params) = @_; - my $ci_id = $params{'ci_id'}; - my $itemnumber = $params{'itemnumber'}; - my $enabled = $params{'enabled'}; + my $ci_id = $params{'ci_id'}; + my $itemnumber = $params{'itemnumber'}; + my $enabled = $params{'enabled'}; my $biblionumber = $params{'biblionumber'}; return unless ( $ci_id xor $itemnumber xor $biblionumber ); - my $course_item = GetCourseItem( ci_id => $ci_id ) || GetCourseItem( itemnumber => $itemnumber ) || GetCourseItem( biblionumber => $biblionumber ); + my $course_item = + GetCourseItem( ci_id => $ci_id ) + || GetCourseItem( itemnumber => $itemnumber ) + || GetCourseItem( biblionumber => $biblionumber ); my @params = ( $course_item->{'ci_id'} ); push( @params, $enabled ) if ($enabled); diff --git a/C4/Creators.pm b/C4/Creators.pm index de81a8bc39..a730356bb2 100644 --- a/C4/Creators.pm +++ b/C4/Creators.pm @@ -23,38 +23,38 @@ BEGIN { use vars qw(@EXPORT @ISA); @ISA = qw(Exporter); our @EXPORT = qw(get_all_templates - get_all_layouts - get_all_profiles - get_all_image_names - get_batch_summary - get_label_summary - get_card_summary - get_barcode_types - get_label_types - get_font_types - get_text_justification_types - get_output_formats - get_table_names - get_unit_values - html_table + get_all_layouts + get_all_profiles + get_all_image_names + get_batch_summary + get_label_summary + get_card_summary + get_barcode_types + get_label_types + get_font_types + get_text_justification_types + get_output_formats + get_table_names + get_unit_values + html_table ); use C4::Creators::Lib qw( - get_all_image_names - get_all_layouts - get_all_profiles - get_all_templates - get_barcode_types - get_batch_summary - get_card_summary - get_font_types - get_label_summary - get_label_types - get_output_formats - get_table_names - get_text_justification_types - get_unit_values - html_table -); + get_all_image_names + get_all_layouts + get_all_profiles + get_all_templates + get_barcode_types + get_batch_summary + get_card_summary + get_font_types + get_label_summary + get_label_types + get_output_formats + get_table_names + get_text_justification_types + get_unit_values + html_table + ); use C4::Creators::PDF; } diff --git a/C4/Creators/Batch.pm b/C4/Creators/Batch.pm index 41a7c0c035..011507b94d 100644 --- a/C4/Creators/Batch.pm +++ b/C4/Creators/Batch.pm @@ -8,8 +8,8 @@ use autouse 'Data::Dumper' => qw(Dumper); use C4::Context; sub _check_params { - my $given_params = {}; - my $exit_code = 0; + my $given_params = {}; + my $exit_code = 0; my @valid_template_params = ( 'label_id', 'batch_id', @@ -19,18 +19,17 @@ sub _check_params { 'branch_code', 'creator', ); - if (scalar(@_) >1) { + if ( scalar(@_) > 1 ) { $given_params = {@_}; - foreach my $key (keys %{$given_params}) { - if (!(grep m/$key/, @valid_template_params)) { - warn sprintf('Unrecognized parameter type of "%s".', $key); + foreach my $key ( keys %{$given_params} ) { + if ( !( grep m/$key/, @valid_template_params ) ) { + warn sprintf( 'Unrecognized parameter type of "%s".', $key ); $exit_code = 1; } } - } - else { - if (!(grep m/$_/, @valid_template_params)) { - warn sprintf('Unrecognized parameter type of %s', $_); + } else { + if ( !( grep m/$_/, @valid_template_params ) ) { + warn sprintf( 'Unrecognized parameter type of %s', $_ ); $exit_code = 1; } } @@ -39,64 +38,67 @@ sub _check_params { sub new { my ($invocant) = shift; - my $type = ref($invocant) || $invocant; - my $self = { - batch_id => 0, - description => '', - items => [], - branch_code => 'NB', - batch_stat => 0, # False if any data has changed and the db has not been updated + my $type = ref($invocant) || $invocant; + my $self = { + batch_id => 0, + description => '', + items => [], + branch_code => 'NB', + batch_stat => 0, # False if any data has changed and the db has not been updated @_, }; - bless ($self, $type); + bless( $self, $type ); return $self; } sub add_item { - my $self = shift; + my $self = shift; my $number = shift; ref($self) =~ m/C4::(.+)::.+$/; - my $number_type = ($1 eq 'Patroncards' ? 'borrower_number' : 'item_number'); - if ($self->{'batch_id'} == 0){ #if this is a new batch batch_id must be created + my $number_type = ( $1 eq 'Patroncards' ? 'borrower_number' : 'item_number' ); + if ( $self->{'batch_id'} == 0 ) { #if this is a new batch batch_id must be created my $sth = C4::Context->dbh->prepare("SELECT MAX(batch_id) FROM creator_batches;"); $sth->execute(); my $batch_id = $sth->fetchrow_array; - $self->{'batch_id'}= ++$batch_id; + $self->{'batch_id'} = ++$batch_id; } - my $query = "INSERT INTO creator_batches (batch_id, description, $number_type, branch_code, creator) VALUES (?,?,?,?,?);"; + my $query = + "INSERT INTO creator_batches (batch_id, description, $number_type, branch_code, creator) VALUES (?,?,?,?,?);"; my $sth = C4::Context->dbh->prepare($query); -# $sth->{'TraceLevel'} = 3; - $sth->execute($self->{'batch_id'}, $self->{'description'}, $number, $self->{'branch_code'}, $1); - if ($sth->err) { - warn sprintf('Database returned the following error on attempted INSERT: %s', $sth->errstr); + + # $sth->{'TraceLevel'} = 3; + $sth->execute( $self->{'batch_id'}, $self->{'description'}, $number, $self->{'branch_code'}, $1 ); + if ( $sth->err ) { + warn sprintf( 'Database returned the following error on attempted INSERT: %s', $sth->errstr ); return -1; } $query = "SELECT max(label_id) FROM creator_batches WHERE batch_id=? AND $number_type=? AND branch_code=?;"; my $sth1 = C4::Context->dbh->prepare($query); - $sth1->execute($self->{'batch_id'}, $number, $self->{'branch_code'}); + $sth1->execute( $self->{'batch_id'}, $number, $self->{'branch_code'} ); my $label_id = $sth1->fetchrow_array; - push (@{$self->{'items'}}, {$number_type => $number, label_id => $label_id}); + push( @{ $self->{'items'} }, { $number_type => $number, label_id => $label_id } ); $self->{'batch_stat'} = 1; return 0; } sub get_attr { my $self = shift; - return $self->{$_[0]}; + return $self->{ $_[0] }; } sub remove_item { - my $self = shift; + my $self = shift; my $label_id = shift; - my $query = "DELETE FROM creator_batches WHERE label_id=? AND batch_id=?;"; - my $sth = C4::Context->dbh->prepare($query); -# $sth->{'TraceLevel'} = 3; - $sth->execute($label_id, $self->{'batch_id'}); - if ($sth->err) { - warn sprintf('Database returned the following error on attempted DELETE: %s', $sth->errstr); + my $query = "DELETE FROM creator_batches WHERE label_id=? AND batch_id=?;"; + my $sth = C4::Context->dbh->prepare($query); + + # $sth->{'TraceLevel'} = 3; + $sth->execute( $label_id, $self->{'batch_id'} ); + if ( $sth->err ) { + warn sprintf( 'Database returned the following error on attempted DELETE: %s', $sth->errstr ); return -1; } - @{$self->{'items'}} = grep{$_->{'label_id'} != $label_id} @{$self->{'items'}}; + @{ $self->{'items'} } = grep { $_->{'label_id'} != $label_id } @{ $self->{'items'} }; $self->{'batch_stat'} = 1; return 0; } @@ -133,85 +135,91 @@ sub remove_item { sub retrieve { my $invocant = shift; - my %opts = @_; - my $type = ref($invocant) || $invocant; + my %opts = @_; + my $type = ref($invocant) || $invocant; $type =~ m/C4::(.+)::.+$/; - my $number_type = ($1 eq 'Patroncards' ? 'borrower_number' : 'item_number'); + my $number_type = ( $1 eq 'Patroncards' ? 'borrower_number' : 'item_number' ); my $record_flag = 0; - my $query = "SELECT * FROM creator_batches WHERE batch_id = ? ORDER BY label_id"; - my $sth = C4::Context->dbh->prepare($query); -# $sth->{'TraceLevel'} = 3; - $sth->execute($opts{'batch_id'}); + my $query = "SELECT * FROM creator_batches WHERE batch_id = ? ORDER BY label_id"; + my $sth = C4::Context->dbh->prepare($query); + + # $sth->{'TraceLevel'} = 3; + $sth->execute( $opts{'batch_id'} ); my $self = { - batch_id => $opts{'batch_id'}, - items => [], + batch_id => $opts{'batch_id'}, + items => [], }; - while (my $record = $sth->fetchrow_hashref) { + while ( my $record = $sth->fetchrow_hashref ) { $self->{'branch_code'} = $record->{'branch_code'}; - $self->{'creator'} = $record->{'creator'}; + $self->{'creator'} = $record->{'creator'}; $self->{'description'} = $record->{'description'}; - push (@{$self->{'items'}}, {$number_type => $record->{$number_type}, label_id => $record->{'label_id'}}); - $record_flag = 1; # true if one or more rows were retrieved + push( @{ $self->{'items'} }, { $number_type => $record->{$number_type}, label_id => $record->{'label_id'} } ); + $record_flag = 1; # true if one or more rows were retrieved } - return -2 if $record_flag == 0; # a hackish sort of way of indicating no such record exists - if ($sth->err) { - warn sprintf('Database returned the following error on attempted SELECT: %s', $sth->errstr); + return -2 if $record_flag == 0; # a hackish sort of way of indicating no such record exists + if ( $sth->err ) { + warn sprintf( 'Database returned the following error on attempted SELECT: %s', $sth->errstr ); return -1; } $self->{'batch_stat'} = 1; - bless ($self, $type); + bless( $self, $type ); return $self; } sub delete { - my $self = {}; - my %opts = (); - my $call_type = ''; + my $self = {}; + my %opts = (); + my $call_type = ''; my @query_params = (); - if (ref($_[0])) { - $self = shift; # check to see if this is a method call - $call_type = 'C4::Labels::Batch->delete'; # seems hackish - @query_params = ($self->{'batch_id'}, $self->{'branch_code'}); - } - else { + if ( ref( $_[0] ) ) { + $self = shift; # check to see if this is a method call + $call_type = 'C4::Labels::Batch->delete'; # seems hackish + @query_params = ( $self->{'batch_id'}, $self->{'branch_code'} ); + } else { shift @_; - %opts = @_; - $call_type = 'C4::Labels::Batch::delete'; - @query_params = ($opts{'batch_id'}, $opts{'branch_code'}); + %opts = @_; + $call_type = 'C4::Labels::Batch::delete'; + @query_params = ( $opts{'batch_id'}, $opts{'branch_code'} ); } - if ($query_params[0] eq '') { # If there is no template id then we cannot delete it - warn sprintf('%s : Cannot delete batch as the batch ID is invalid or non-existent.', $call_type); + if ( $query_params[0] eq '' ) { # If there is no template id then we cannot delete it + warn sprintf( '%s : Cannot delete batch as the batch ID is invalid or non-existent.', $call_type ); return -1; } my $query = "DELETE FROM creator_batches WHERE batch_id = ? AND branch_code =?"; - my $sth = C4::Context->dbh->prepare($query); -# $sth->{'TraceLevel'} = 3; + my $sth = C4::Context->dbh->prepare($query); + + # $sth->{'TraceLevel'} = 3; $sth->execute(@query_params); - if ($sth->err) { - warn sprintf('%s : Database returned the following error on attempted INSERT: %s', $call_type, $sth->errstr); + if ( $sth->err ) { + warn sprintf( '%s : Database returned the following error on attempted INSERT: %s', $call_type, $sth->errstr ); return -1; } return 0; } sub remove_duplicates { - my $self = shift; - my %seen=(); - my $query = "DELETE FROM creator_batches WHERE label_id = ?;"; # ORDER BY timestamp ASC LIMIT ?;"; - my $sth = C4::Context->dbh->prepare($query); - my @duplicate_items = grep{ - $_->{'item_number'} - ? $seen{$_->{'item_number'}}++ - : $seen{$_->{'borrower_number'}}++ - } @{$self->{'items'}}; + my $self = shift; + my %seen = (); + my $query = "DELETE FROM creator_batches WHERE label_id = ?;"; # ORDER BY timestamp ASC LIMIT ?;"; + my $sth = C4::Context->dbh->prepare($query); + my @duplicate_items = + grep { $_->{'item_number'} ? $seen{ $_->{'item_number'} }++ : $seen{ $_->{'borrower_number'} }++ } + @{ $self->{'items'} }; foreach my $item (@duplicate_items) { - $sth->execute($item->{'label_id'}); - if ($sth->err) { - warn sprintf('Database returned the following error on attempted DELETE for label_id %s: %s', $item->{'label_id'}, $sth->errstr); + $sth->execute( $item->{'label_id'} ); + if ( $sth->err ) { + warn sprintf( + 'Database returned the following error on attempted DELETE for label_id %s: %s', + $item->{'label_id'}, $sth->errstr + ); return -1; } - $sth->finish(); # Per DBI.pm docs: "If execute() is called on a statement handle that's still active ($sth->{Active} is true) then it should effectively call finish() to tidy up the previous execution results before starting this new execution." - @{$self->{'items'}} = grep{$_->{'label_id'} != $item->{'label_id'}} @{$self->{'items'}}; # the correct label/item must be removed from the current batch object as well; this should be done *after* each sql DELETE in case the DELETE fails + $sth->finish() + ; # Per DBI.pm docs: "If execute() is called on a statement handle that's still active ($sth->{Active} is true) then it should effectively call finish() to tidy up the previous execution results before starting this new execution." + @{ $self->{'items'} } = + grep { $_->{'label_id'} != $item->{'label_id'} } + @{ $self->{'items'} } + ; # the correct label/item must be removed from the current batch object as well; this should be done *after* each sql DELETE in case the DELETE fails } return scalar(@duplicate_items); } diff --git a/C4/Creators/Layout.pm b/C4/Creators/Layout.pm index a8fd56f5d1..9a43a130da 100644 --- a/C4/Creators/Layout.pm +++ b/C4/Creators/Layout.pm @@ -21,7 +21,7 @@ use C4::Creators::PDF; # } sub _check_params { - my $exit_code = 0; + my $exit_code = 0; my @valtmpl_id_params = ( 'layout_id', 'barcode_type', @@ -41,18 +41,17 @@ sub _check_params { 'units', 'start_label', ); - if (scalar(@_) >1) { + if ( scalar(@_) > 1 ) { my %given_params = @_; - foreach my $key (keys %given_params) { - if (!(grep m/$key/, @valtmpl_id_params)) { - warn sprintf('(Multiple parameters) Unrecognized parameter type of "%s".', $key); + foreach my $key ( keys %given_params ) { + if ( !( grep m/$key/, @valtmpl_id_params ) ) { + warn sprintf( '(Multiple parameters) Unrecognized parameter type of "%s".', $key ); $exit_code = 1; } } - } - else { - if (!(grep m/$_/, @valtmpl_id_params)) { - warn sprintf('(Single parameter) Unrecognized parameter type of "%s".', $_); + } else { + if ( !( grep m/$_/, @valtmpl_id_params ) ) { + warn sprintf( '(Single parameter) Unrecognized parameter type of "%s".', $_ ); $exit_code = 1; } } @@ -60,10 +59,11 @@ sub _check_params { } use constant PRESET_FIELDS => [qw(title author isbn issn itemtype barcode itemcallnumber)]; + sub new { my $invocant = shift; - my $self = ''; - if (_check_params(@_) eq 1) { + my $self = ''; + if ( _check_params(@_) eq 1 ) { return -1; } my $type = ref($invocant) || $invocant; @@ -86,104 +86,104 @@ sub new { format_string => join( ', ', @{ PRESET_FIELDS() } ), @_, }; - } - elsif (grep {$_ eq 'Patroncards'} @_) { + } elsif ( grep { $_ eq 'Patroncards' } @_ ) { $self = { layout_xml => 'Default Layout', @_, - } + }; } - bless ($self, $type); + bless( $self, $type ); return $self; } sub retrieve { my $invocant = shift; - my %opts = @_; - my $type = ref($invocant) || $invocant; - my $query = "SELECT * FROM creator_layouts WHERE layout_id = ? AND creator = ?"; - my $sth = C4::Context->dbh->prepare($query); - $sth->execute($opts{'layout_id'}, $opts{'creator'}); - if ($sth->err) { - warn sprintf('Database returned the following error: %s', $sth->errstr); + my %opts = @_; + my $type = ref($invocant) || $invocant; + my $query = "SELECT * FROM creator_layouts WHERE layout_id = ? AND creator = ?"; + my $sth = C4::Context->dbh->prepare($query); + $sth->execute( $opts{'layout_id'}, $opts{'creator'} ); + if ( $sth->err ) { + warn sprintf( 'Database returned the following error: %s', $sth->errstr ); return -1; } my $self = $sth->fetchrow_hashref; - bless ($self, $type); + bless( $self, $type ); return $self; } sub delete { - my $self = {}; - my %opts = (); + my $self = {}; + my %opts = (); my $call_type = ''; - my @params = (); - if (ref($_[0])) { - $self = shift; # check to see if this is a method call + my @params = (); + if ( ref( $_[0] ) ) { + $self = shift; # check to see if this is a method call $call_type = 'C4::Labels::Layout->delete'; push @params, $self->{'layout_id'}, $self->{'creator'}; - } - else { + } else { my $class = shift; - %opts = @_; + %opts = @_; $call_type = $class . '::delete'; push @params, $opts{'layout_id'}, $opts{'creator'}; } - if (scalar(@params) < 2) { # If there is no layout id or creator type then we cannot delete it - warn sprintf('%s : Cannot delete layout as the profile ID is invalid or non-existent.', $call_type) if !$params[0]; - warn sprintf('%s : Cannot delete layout as the creator type is invalid or non-existent.', $call_type) if !$params[1]; + if ( scalar(@params) < 2 ) { # If there is no layout id or creator type then we cannot delete it + warn sprintf( '%s : Cannot delete layout as the profile ID is invalid or non-existent.', $call_type ) + if !$params[0]; + warn sprintf( '%s : Cannot delete layout as the creator type is invalid or non-existent.', $call_type ) + if !$params[1]; return -1; } my $query = "DELETE FROM creator_layouts WHERE layout_id = ? AND creator = ?"; - my $sth = C4::Context->dbh->prepare($query); + my $sth = C4::Context->dbh->prepare($query); $sth->execute(@params); - if ($sth->err) { - warn sprintf('Database returned the following error on attempted DELETE: %s', $sth->errstr); + if ( $sth->err ) { + warn sprintf( 'Database returned the following error on attempted DELETE: %s', $sth->errstr ); return -1; } } sub save { my $self = shift; - if ($self->{'layout_id'}) { # if we have an id, the record exists and needs UPDATE + if ( $self->{'layout_id'} ) { # if we have an id, the record exists and needs UPDATE my @params; my $query = "UPDATE creator_layouts SET "; - foreach my $key (keys %{$self}) { - next if ($key eq 'layout_id') || ($key eq 'creator'); - push (@params, $self->{$key}); + foreach my $key ( keys %{$self} ) { + next if ( $key eq 'layout_id' ) || ( $key eq 'creator' ); + push( @params, $self->{$key} ); $query .= "$key=?, "; } - $query = substr($query, 0, (length($query)-2)); + $query = substr( $query, 0, ( length($query) - 2 ) ); $query .= " WHERE layout_id=? AND creator = ?;"; - push (@params, $self->{'layout_id'}, $self->{'creator'}); + push( @params, $self->{'layout_id'}, $self->{'creator'} ); my $sth = C4::Context->dbh->prepare($query); + #local $sth->{TraceLevel} = "3"; # enable DBI trace and set level; outputs to STDERR $sth->execute(@params); - if ($sth->err) { - warn sprintf('Database returned the following error: %s', $sth->errstr); + if ( $sth->err ) { + warn sprintf( 'Database returned the following error: %s', $sth->errstr ); return -1; } return $self->{'layout_id'}; - } - else { # otherwise create a new record + } else { # otherwise create a new record my @params; - delete $self->{layout_id}; # Could be an empty string + delete $self->{layout_id}; # Could be an empty string my $query = "INSERT INTO creator_layouts ("; - foreach my $key (keys %{$self}) { - push (@params, $self->{$key}); + foreach my $key ( keys %{$self} ) { + push( @params, $self->{$key} ); $query .= "$key, "; } - $query = substr($query, 0, (length($query)-2)); + $query = substr( $query, 0, ( length($query) - 2 ) ); $query .= ") VALUES ("; - for (my $i=1; $i<=(scalar keys %$self); $i++) { + for ( my $i = 1 ; $i <= ( scalar keys %$self ) ; $i++ ) { $query .= "?,"; } - $query = substr($query, 0, (length($query)-1)); + $query = substr( $query, 0, ( length($query) - 1 ) ); $query .= ");"; my $sth = C4::Context->dbh->prepare($query); $sth->execute(@params); - if ($sth->err) { - warn sprintf('Database returned the following error: %s', $sth->errstr); + if ( $sth->err ) { + warn sprintf( 'Database returned the following error: %s', $sth->errstr ); return -1; } my $sth1 = C4::Context->dbh->prepare("SELECT MAX(layout_id) FROM creator_layouts;"); @@ -196,14 +196,13 @@ sub save { sub get_attr { my $self = shift; - if (_check_params(@_) eq 1) { + if ( _check_params(@_) eq 1 ) { return -1; } my ($attr) = @_; - if (exists($self->{$attr})) { + if ( exists( $self->{$attr} ) ) { return $self->{$attr}; - } - else { + } else { return -1; } return; @@ -211,26 +210,26 @@ sub get_attr { sub set_attr { my $self = shift; - if (_check_params(@_) eq 1) { + if ( _check_params(@_) eq 1 ) { return -1; } my %attrs = @_; - foreach my $attrib (keys(%attrs)) { + foreach my $attrib ( keys(%attrs) ) { $self->{$attrib} = $attrs{$attrib}; - }; + } return 0; } sub get_text_wrap_cols { - my $self = shift; - my %params = @_; - my $string = ''; - my $strwidth = 0; + my $self = shift; + my %params = @_; + my $string = ''; + my $strwidth = 0; my $col_count = 0; - my $textlimit = $params{'label_width'} - (( 3 * $params{'left_text_margin'} ) || 13.5 ); + my $textlimit = $params{'label_width'} - ( ( 3 * $params{'left_text_margin'} ) || 13.5 ); - while ($strwidth < $textlimit) { - $string .= '8'; # using '8' as filling char instead of '0' + while ( $strwidth < $textlimit ) { + $string .= '8'; # using '8' as filling char instead of '0' $col_count++; $strwidth = C4::Creators::PDF->StrWidth( $string, $self->{'font'}, $self->{'font_size'} ); } diff --git a/C4/Creators/Lib.pm b/C4/Creators/Lib.pm index c8a83b26a3..74a83745c3 100644 --- a/C4/Creators/Lib.pm +++ b/C4/Creators/Lib.pm @@ -27,20 +27,20 @@ use C4::Context; BEGIN { use base qw(Exporter); our @EXPORT = qw(get_all_templates - get_all_layouts - get_all_profiles - get_all_image_names - get_batch_summary - get_label_summary - get_card_summary - get_barcode_types - get_label_types - get_font_types - get_text_justification_types - get_output_formats - get_table_names - get_unit_values - html_table + get_all_layouts + get_all_profiles + get_all_image_names + get_batch_summary + get_label_summary + get_card_summary + get_barcode_types + get_label_types + get_font_types + get_text_justification_types + get_output_formats + get_table_names + get_unit_values + html_table ); } @@ -65,106 +65,144 @@ C4::Creators::Lib #=cut sub _SELECT { - my @params = @_; - my $fieldname = _add_backtics($params[0]); - my $query = "SELECT $fieldname FROM $params[1]"; + my @params = @_; + my $fieldname = _add_backtics( $params[0] ); + my $query = "SELECT $fieldname FROM $params[1]"; $params[2] ? $query .= " WHERE $params[2];" : $query .= ';'; my $sth = C4::Context->dbh->prepare($query); -# $sth->{'TraceLevel'} = 3; + + # $sth->{'TraceLevel'} = 3; $sth->execute(); - if ($sth->err) { - warn sprintf('Database returned the following error: %s', $sth->errstr); + if ( $sth->err ) { + warn sprintf( 'Database returned the following error: %s', $sth->errstr ); return 1; } my $record_set = []; - while (my $row = $sth->fetchrow_hashref()) { - push(@$record_set, $row); + while ( my $row = $sth->fetchrow_hashref() ) { + push( @$record_set, $row ); } return $record_set; } sub _add_backtics { - my ( @args ) = @_; + my (@args) = @_; s/(?:^|\b)(\w+)(?:\b|$)/`$1`/g for @args; + # Too bad that we need to correct a few exceptions: aggregate functions - my @aggregates = ( 'COUNT', 'MAX', 'MIN', 'SUM' ); # add when needed.. + my @aggregates = ( 'COUNT', 'MAX', 'MIN', 'SUM' ); # add when needed.. foreach my $aggr (@aggregates) { s/`$aggr`\(/$aggr\(/gi for @args; } + # And correct aliases s/(`|\))\s+`AS`\s+`/$1 AS `/gi for @args; return wantarray ? @args : $args[0]; } my $barcode_types = [ - {type => 'CODE39', name => 'Code 39', desc => 'Translates the characters 0-9, A-Z, \'-\', \'*\', \'+\', \'$\', \'%\', \'/\', \'.\' and \' \' to a barcode pattern.', selected => 0}, - {type => 'CODE39MOD', name => 'Code 39 + Modulo43', desc => 'Translates the characters 0-9, A-Z, \'-\', \'*\', \'+\', \'$\', \'%\', \'/\', \'.\' and \' \' to a barcode pattern. Encodes Mod 43 checksum.', selected => 0}, - {type => 'CODE39MOD10', name => 'Code 39 + Modulo10', desc => 'Translates the characters 0-9, A-Z, \'-\', \'*\', \'+\', \'$\', \'%\', \'/\', \'.\' and \' \' to a barcode pattern. Encodes Mod 10 checksum.', selected => 0}, - {type => 'COOP2OF5', name => 'COOP2of5', desc => 'Creates COOP2of5 barcodes from a string consisting of the numeric characters 0-9', selected => 0}, - {type => 'EAN13', name => 'EAN13', desc => 'Creates EAN13 barcodes from a string of 12 or 13 digits. The check number (the 13:th digit) is calculated if not supplied.', selected => 0}, -# {type => 'EAN8', name => 'EAN8', desc => 'Translates a string of 7 or 8 digits to EAN8 barcodes. The check number (the 8:th digit) is calculated if not supplied.', selected => 0}, -# {type => 'IATA2of5', name => 'IATA2of5', desc => 'Creates IATA2of5 barcodes from a string consisting of the numeric characters 0-9', selected => 0}, - {type => 'INDUSTRIAL2OF5', name => 'Industrial2of5', desc => 'Creates Industrial2of5 barcodes from a string consisting of the numeric characters 0-9', selected => 0}, -# {type => 'ITF', name => 'Interleaved2of5', desc => 'Translates the characters 0-9 to a barcodes. These barcodes could also be called 'Interleaved2of5'.', selected => 0}, -# {type => 'MATRIX2OF5', name => 'Matrix2of5', desc => 'Creates Matrix2of5 barcodes from a string consisting of the numeric characters 0-9', selected => 0}, -# {type => 'NW7', name => 'NW7', desc => 'Creates a NW7 barcodes from a string consisting of the numeric characters 0-9', selected => 0}, -# {type => 'UPCA', name => 'UPCA', desc => 'Translates a string of 11 or 12 digits to UPCA barcodes. The check number (the 12:th digit) is calculated if not supplied.', selected => 0}, -# {type => 'UPCE', name => 'UPCE', desc => 'Translates a string of 6, 7 or 8 digits to UPCE barcodes. If the string is 6 digits long, '0' is added first in the string. The check number (the 8:th digit) is calculated if not supplied.', selected => 0}, + { + type => 'CODE39', name => 'Code 39', + desc => + 'Translates the characters 0-9, A-Z, \'-\', \'*\', \'+\', \'$\', \'%\', \'/\', \'.\' and \' \' to a barcode pattern.', + selected => 0 + }, + { + type => 'CODE39MOD', name => 'Code 39 + Modulo43', + desc => + 'Translates the characters 0-9, A-Z, \'-\', \'*\', \'+\', \'$\', \'%\', \'/\', \'.\' and \' \' to a barcode pattern. Encodes Mod 43 checksum.', + selected => 0 + }, + { + type => 'CODE39MOD10', name => 'Code 39 + Modulo10', + desc => + 'Translates the characters 0-9, A-Z, \'-\', \'*\', \'+\', \'$\', \'%\', \'/\', \'.\' and \' \' to a barcode pattern. Encodes Mod 10 checksum.', + selected => 0 + }, + { + type => 'COOP2OF5', name => 'COOP2of5', + desc => 'Creates COOP2of5 barcodes from a string consisting of the numeric characters 0-9', selected => 0 + }, + { + type => 'EAN13', name => 'EAN13', + desc => + 'Creates EAN13 barcodes from a string of 12 or 13 digits. The check number (the 13:th digit) is calculated if not supplied.', + selected => 0 + }, + + # {type => 'EAN8', name => 'EAN8', desc => 'Translates a string of 7 or 8 digits to EAN8 barcodes. The check number (the 8:th digit) is calculated if not supplied.', selected => 0}, + # {type => 'IATA2of5', name => 'IATA2of5', desc => 'Creates IATA2of5 barcodes from a string consisting of the numeric characters 0-9', selected => 0}, + { + type => 'INDUSTRIAL2OF5', name => 'Industrial2of5', + desc => 'Creates Industrial2of5 barcodes from a string consisting of the numeric characters 0-9', selected => 0 + }, + + # {type => 'ITF', name => 'Interleaved2of5', desc => 'Translates the characters 0-9 to a barcodes. These barcodes could also be called 'Interleaved2of5'.', selected => 0}, + # {type => 'MATRIX2OF5', name => 'Matrix2of5', desc => 'Creates Matrix2of5 barcodes from a string consisting of the numeric characters 0-9', selected => 0}, + # {type => 'NW7', name => 'NW7', desc => 'Creates a NW7 barcodes from a string consisting of the numeric characters 0-9', selected => 0}, + # {type => 'UPCA', name => 'UPCA', desc => 'Translates a string of 11 or 12 digits to UPCA barcodes. The check number (the 12:th digit) is calculated if not supplied.', selected => 0}, + # {type => 'UPCE', name => 'UPCE', desc => 'Translates a string of 6, 7 or 8 digits to UPCE barcodes. If the string is 6 digits long, '0' is added first in the string. The check number (the 8:th digit) is calculated if not supplied.', selected => 0}, ]; my $label_types = [ - {type => 'BIB', name => 'Biblio', desc => 'Only the bibliographic data is printed.', selected => 0}, - {type => 'BARBIB', name => 'Barcode/Biblio', desc => 'Barcode proceeds bibliographic data.', selected => 0}, - {type => 'BIBBAR', name => 'Biblio/Barcode', desc => 'Bibliographic data proceeds barcode.', selected => 0}, - {type => 'ALT', name => 'Alternating', desc => 'Barcode and bibliographic data are printed on alternating labels.', selected => 0}, - {type => 'BAR', name => 'Barcode', desc => 'Only the barcode is printed.', selected => 0}, + { type => 'BIB', name => 'Biblio', desc => 'Only the bibliographic data is printed.', selected => 0 }, + { type => 'BARBIB', name => 'Barcode/Biblio', desc => 'Barcode proceeds bibliographic data.', selected => 0 }, + { type => 'BIBBAR', name => 'Biblio/Barcode', desc => 'Bibliographic data proceeds barcode.', selected => 0 }, + { + type => 'ALT', name => 'Alternating', + desc => 'Barcode and bibliographic data are printed on alternating labels.', selected => 0 + }, + { type => 'BAR', name => 'Barcode', desc => 'Only the barcode is printed.', selected => 0 }, ]; my $font_types = [ - {type => 'TR', name => 'Times-Roman', selected => 0}, - {type => 'TB', name => 'Times-Bold', selected => 0}, - {type => 'TI', name => 'Times-Italic', selected => 0}, - {type => 'TBI', name => 'Times-Bold-Italic', selected => 0}, - {type => 'C', name => 'Courier', selected => 0}, - {type => 'CB', name => 'Courier-Bold', selected => 0}, - {type => 'CO', name => 'Courier-Oblique', selected => 0}, - {type => 'CBO', name => 'Courier-Bold-Oblique', selected => 0}, - {type => 'H', name => 'Helvetica', selected => 0}, - {type => 'HO', name => 'Helvetica-Oblique', selected => 0}, - {type => 'HB', name => 'Helvetica-Bold', selected => 0}, - {type => 'HBO', name => 'Helvetica-Bold-Oblique', selected => 0}, + { type => 'TR', name => 'Times-Roman', selected => 0 }, + { type => 'TB', name => 'Times-Bold', selected => 0 }, + { type => 'TI', name => 'Times-Italic', selected => 0 }, + { type => 'TBI', name => 'Times-Bold-Italic', selected => 0 }, + { type => 'C', name => 'Courier', selected => 0 }, + { type => 'CB', name => 'Courier-Bold', selected => 0 }, + { type => 'CO', name => 'Courier-Oblique', selected => 0 }, + { type => 'CBO', name => 'Courier-Bold-Oblique', selected => 0 }, + { type => 'H', name => 'Helvetica', selected => 0 }, + { type => 'HO', name => 'Helvetica-Oblique', selected => 0 }, + { type => 'HB', name => 'Helvetica-Bold', selected => 0 }, + { type => 'HBO', name => 'Helvetica-Bold-Oblique', selected => 0 }, ]; my $text_justification_types = [ - {type => 'L', name => 'Left', selected => 0}, - {type => 'C', name => 'Center', selected => 0}, - {type => 'R', name => 'Right', selected => 0}, -# {type => 'F', name => 'Full', selected => 0}, + { type => 'L', name => 'Left', selected => 0 }, + { type => 'C', name => 'Center', selected => 0 }, + { type => 'R', name => 'Right', selected => 0 }, + + # {type => 'F', name => 'Full', selected => 0}, ]; my $unit_values = [ - {type => 'POINT', desc => 'PostScript Points', value => 1, selected => 0}, - {type => 'AGATE', desc => 'Adobe Agates', value => 5.1428571, selected => 0}, - {type => 'INCH', desc => 'US Inches', value => 72, selected => 0}, - {type => 'MM', desc => 'SI Millimeters', value => 2.83464567, selected => 0}, - {type => 'CM', desc => 'SI Centimeters', value => 28.3464567, selected => 0}, + { type => 'POINT', desc => 'PostScript Points', value => 1, selected => 0 }, + { type => 'AGATE', desc => 'Adobe Agates', value => 5.1428571, selected => 0 }, + { type => 'INCH', desc => 'US Inches', value => 72, selected => 0 }, + { type => 'MM', desc => 'SI Millimeters', value => 2.83464567, selected => 0 }, + { type => 'CM', desc => 'SI Centimeters', value => 28.3464567, selected => 0 }, ]; my $output_formats = [ - {type => 'pdf', desc => 'PDF File'}, - {type => 'csv', desc => 'CSV File'}, + { type => 'pdf', desc => 'PDF File' }, + { type => 'csv', desc => 'CSV File' }, ]; sub _build_query { my ( $params, $table ) = @_; my @fields = exists $params->{fields} ? _add_backtics( @{ $params->{fields} } ) : ('*'); - my $query = "SELECT " . join(', ', @fields ) . " FROM $table"; + my $query = "SELECT " . join( ', ', @fields ) . " FROM $table"; my @where_args; if ( exists $params->{filters} ) { $query .= ' WHERE 1 '; while ( my ( $field, $values ) = each %{ $params->{filters} } ) { - if ( ref( $values ) ) { - $query .= " AND `$field` IN ( " . ( ('?,') x (@$values-1) ) . "? ) "; # a comma separates elements in a list... + if ( ref($values) ) { + $query .= + " AND `$field` IN ( " + . ( ('?,') x ( @$values - 1 ) ) + . "? ) "; # a comma separates elements in a list... push @where_args, @$values; } else { $query .= " AND `$field` = ? "; @@ -172,7 +210,7 @@ sub _build_query { } } } - $query .= (exists $params->{orderby} ? " ORDER BY $params->{orderby} " : ''); + $query .= ( exists $params->{orderby} ? " ORDER BY $params->{orderby} " : '' ); return ( $query, @where_args ); } @@ -185,18 +223,18 @@ This function returns a reference to a hash containing all templates upon succes =cut sub get_all_templates { - my ( $params ) = @_; + my ($params) = @_; my @templates = (); my ( $query, @where_args ) = _build_query( $params, 'creator_templates' ); my $sth = C4::Context->dbh->prepare($query); - $sth->execute( @where_args ); - if ($sth->err) { - warn sprintf('Database returned the following error: %s', $sth->errstr); + $sth->execute(@where_args); + if ( $sth->err ) { + warn sprintf( 'Database returned the following error: %s', $sth->errstr ); return -1; } - ADD_TEMPLATES: - while (my $template = $sth->fetchrow_hashref) { - push(@templates, $template); +ADD_TEMPLATES: + while ( my $template = $sth->fetchrow_hashref ) { + push( @templates, $template ); } return \@templates; } @@ -210,18 +248,18 @@ This function returns a reference to a hash containing all layouts upon success =cut sub get_all_layouts { - my ( $params ) = @_; + my ($params) = @_; my @layouts = (); my ( $query, @where_args ) = _build_query( $params, 'creator_layouts' ); my $sth = C4::Context->dbh->prepare($query); - $sth->execute( @where_args ); - if ($sth->err) { - warn sprintf('Database returned the following error: %s', $sth->errstr); + $sth->execute(@where_args); + if ( $sth->err ) { + warn sprintf( 'Database returned the following error: %s', $sth->errstr ); return -1; } - ADD_LAYOUTS: - while (my $layout = $sth->fetchrow_hashref) { - push(@layouts, $layout); +ADD_LAYOUTS: + while ( my $layout = $sth->fetchrow_hashref ) { + push( @layouts, $layout ); } return \@layouts; } @@ -241,18 +279,18 @@ NOTE: Do not pass in the keyword 'WHERE.' =cut sub get_all_profiles { - my ( $params ) = @_; + my ($params) = @_; my @profiles = (); my ( $query, @where_args ) = _build_query( $params, 'printers_profile' ); my $sth = C4::Context->dbh->prepare($query); - $sth->execute( @where_args ); - if ($sth->err) { - warn sprintf('Database returned the following error: %s', $sth->errstr); + $sth->execute(@where_args); + if ( $sth->err ) { + warn sprintf( 'Database returned the following error: %s', $sth->errstr ); return -1; } - ADD_PROFILES: - while (my $profile = $sth->fetchrow_hashref) { - push(@profiles, $profile); +ADD_PROFILES: + while ( my $profile = $sth->fetchrow_hashref ) { + push( @profiles, $profile ); } return \@profiles; } @@ -263,14 +301,14 @@ sub get_all_profiles { sub get_all_image_names { my $image_names = []; - my $query = "SELECT image_name FROM creator_images"; - my $sth = C4::Context->dbh->prepare($query); + my $query = "SELECT image_name FROM creator_images"; + my $sth = C4::Context->dbh->prepare($query); $sth->execute(); - if ($sth->err) { - warn sprintf('Database returned the following error: %s', $sth->errstr); + if ( $sth->err ) { + warn sprintf( 'Database returned the following error: %s', $sth->errstr ); return -1; } - grep {push @$image_names, {type => $$_[0], name => $$_[0], selected => 0}} @{$sth->fetchall_arrayref([0])}; + grep { push @$image_names, { type => $$_[0], name => $$_[0], selected => 0 } } @{ $sth->fetchall_arrayref( [0] ) }; return $image_names; } @@ -289,19 +327,19 @@ NOTE: Do not pass in the keyword 'WHERE.' =cut sub get_batch_summary { - my ( $params ) = @_; + my ($params) = @_; my @batches = (); - $params->{fields} = ['batch_id', 'description', 'count(batch_id) as _item_count']; + $params->{fields} = [ 'batch_id', 'description', 'count(batch_id) as _item_count' ]; my ( $query, @where_args ) = _build_query( $params, 'creator_batches' ); $query .= " GROUP BY batch_id, description"; my $sth = C4::Context->dbh->prepare($query); - $sth->execute( @where_args ); - if ($sth->err) { - warn sprintf('Database returned the following error on attempted SELECT: %s', $sth->errstr); + $sth->execute(@where_args); + if ( $sth->err ) { + warn sprintf( 'Database returned the following error on attempted SELECT: %s', $sth->errstr ); return -1; } - while (my $batch = $sth->fetchrow_hashref) { - push(@batches, $batch); + while ( my $batch = $sth->fetchrow_hashref ) { + push( @batches, $batch ); } return \@batches; } @@ -321,8 +359,8 @@ NOTE: Do not pass in the keyword 'WHERE.' =cut sub get_label_summary { - my %params = @_; - my $label_number = 0; + my %params = @_; + my $label_number = 0; my @label_summaries = (); my $query = " SELECT b.title, b.author, bi.itemtype, i.barcode, i.itemcallnumber, i.biblionumber, i.itype FROM creator_batches AS c LEFT JOIN items AS i ON (c.item_number=i.itemnumber) @@ -331,27 +369,30 @@ sub get_label_summary { WHERE itemnumber=? AND batch_id=?; "; my $sth = C4::Context->dbh->prepare($query); - foreach my $item (@{$params{'items'}}) { + foreach my $item ( @{ $params{'items'} } ) { $label_number++; - $sth->execute($item->{'item_number'}, $params{'batch_id'}); - if ($sth->err) { - warn sprintf('Database returned the following error on attempted SELECT: %s', $sth->errstr); + $sth->execute( $item->{'item_number'}, $params{'batch_id'} ); + if ( $sth->err ) { + warn sprintf( 'Database returned the following error on attempted SELECT: %s', $sth->errstr ); return -1; } my $record = $sth->fetchrow_hashref; my $label_summary; $label_summary->{'_label_number'} = $label_number; - $record->{'author'} =~ s/[^\.|\w]$// if $record->{'author'}; # strip off ugly trailing chars... but not periods or word chars - $record->{'title'} =~ s/\W*$//; # strip off ugly trailing chars - # FIXME contructing staff interface URLs should be done *much* higher up the stack - for the most part, C4 module code - # should not know that it's part of a web app - $label_summary->{'_summary'} = { title => $record->{title}, author => $record->{author}, biblionumber => $record->{biblionumber} }; - $label_summary->{'_item_type'} = C4::Context->preference("item-level_itypes") ? $record->{'itype'} : $record->{'itemtype'}; - $label_summary->{'_barcode'} = $record->{'barcode'}; + $record->{'author'} =~ s/[^\.|\w]$// + if $record->{'author'}; # strip off ugly trailing chars... but not periods or word chars + $record->{'title'} =~ s/\W*$//; # strip off ugly trailing chars + # FIXME contructing staff interface URLs should be done *much* higher up the stack - for the most part, C4 module code + # should not know that it's part of a web app + $label_summary->{'_summary'} = + { title => $record->{title}, author => $record->{author}, biblionumber => $record->{biblionumber} }; + $label_summary->{'_item_type'} = + C4::Context->preference("item-level_itypes") ? $record->{'itype'} : $record->{'itemtype'}; + $label_summary->{'_barcode'} = $record->{'barcode'}; $label_summary->{'_item_number'} = $item->{'item_number'}; - $label_summary->{'_item_cn'} = $record->{'itemcallnumber'}; - $label_summary->{'_label_id'} = $item->{'label_id'}; - push (@label_summaries, $label_summary); + $label_summary->{'_item_cn'} = $record->{'itemcallnumber'}; + $label_summary->{'_label_id'} = $item->{'label_id'}; + push( @label_summaries, $label_summary ); } return \@label_summaries; } @@ -371,24 +412,24 @@ NOTE: Do not pass in the keyword 'WHERE.' =cut sub get_card_summary { - my %params = @_; - my $card_number = 0; + my %params = @_; + my $card_number = 0; my @card_summaries = (); my $query = "SELECT CONCAT_WS(', ', surname, firstname) AS name, cardnumber FROM borrowers WHERE borrowernumber=?;"; - my $sth = C4::Context->dbh->prepare($query); - foreach my $item (@{$params{'items'}}) { + my $sth = C4::Context->dbh->prepare($query); + foreach my $item ( @{ $params{'items'} } ) { $card_number++; - $sth->execute($item->{'borrower_number'}); - if ($sth->err) { - warn sprintf('Database returned the following error on attempted SELECT: %s', $sth->errstr); + $sth->execute( $item->{'borrower_number'} ); + if ( $sth->err ) { + warn sprintf( 'Database returned the following error on attempted SELECT: %s', $sth->errstr ); return -1; } my $record = $sth->fetchrow_hashref; my $card_summary->{'_card_number'} = $card_number; - $card_summary->{'_summary'} = $record->{'name'}; + $card_summary->{'_summary'} = $record->{'name'}; $card_summary->{'borrowernumber'} = $item->{'borrower_number'}; - $card_summary->{'_label_id'} = $item->{'label_id'}; - push (@card_summaries, $card_summary); + $card_summary->{'_label_id'} = $item->{'label_id'}; + push( @card_summaries, $card_summary ); } return \@card_summaries; } @@ -467,7 +508,6 @@ sub get_output_formats { return dclone $output_formats; } - =head2 C4::Creators::Lib::get_table_names($search_term) Return an arrayref of an array containing the table names which contain the supplied search term. @@ -476,11 +516,11 @@ Return an arrayref of an array containing the table names which contain the supp sub get_table_names { my $search_term = shift; - my $dbh = C4::Context->dbh(); + my $dbh = C4::Context->dbh(); my $table_names = []; - my $sth = $dbh->table_info(undef,undef,"%$search_term%"); - while (my $info = $sth->fetchrow_hashref()){ - push (@$table_names, $info->{'TABLE_NAME'}); + my $sth = $dbh->table_info( undef, undef, "%$search_term%" ); + while ( my $info = $sth->fetchrow_hashref() ) { + push( @$table_names, $info->{'TABLE_NAME'} ); } return $table_names; } @@ -523,61 +563,76 @@ be passed off as a template parameter and used to build an html table. sub html_table { my $headers = shift; - my $data = shift; - return if scalar(@$data) == 0; # no need to generate a table if there is not data to display - my $table = []; - my $fields = []; + my $data = shift; + return if scalar(@$data) == 0; # no need to generate a table if there is not data to display + my $table = []; + my $fields = []; my @table_columns = (); - my ($row_index, $col_index) = (0,0); - my $cols = 0; # number of columns to wrap on - my $field_count = 0; + my ( $row_index, $col_index ) = ( 0, 0 ); + my $cols = 0; # number of columns to wrap on + my $field_count = 0; my $select_value = undef; - my $link_field = undef; - POPULATE_HEADER: + my $link_field = undef; +POPULATE_HEADER: + foreach my $header (@$headers) { my @key = keys %$header; - if ($key[0] eq 'select' ) { - push (@table_columns, $key[0]); - $$fields[$col_index] = {hidden => 0, select_field => 0, field_name => ($key[0]), field_label => $header->{$key[0]}{'label'}}; + if ( $key[0] eq 'select' ) { + push( @table_columns, $key[0] ); + $$fields[$col_index] = { + hidden => 0, select_field => 0, field_name => ( $key[0] ), + field_label => $header->{ $key[0] }{'label'} + }; + # do special formatting stuff.... - $select_value = $header->{$key[0]}{'value'}; - } - else { + $select_value = $header->{ $key[0] }{'value'}; + } else { + # do special formatting stuff.... - $link_field->{$key[0]} = ($header->{$key[0]}{'link_field'} == 1 ? 1 : 0); - push (@table_columns, $key[0]); - $$fields[$col_index] = {hidden => 0, select_field => 0, field_name => ($key[0]), field_label => $header->{$key[0]}{'label'}}; + $link_field->{ $key[0] } = ( $header->{ $key[0] }{'link_field'} == 1 ? 1 : 0 ); + push( @table_columns, $key[0] ); + $$fields[$col_index] = { + hidden => 0, select_field => 0, field_name => ( $key[0] ), + field_label => $header->{ $key[0] }{'label'} + }; } $field_count++; $col_index++; } - $$table[0] = {header_fields => $fields}; + $$table[0] = { header_fields => $fields }; $cols = $col_index; - $field_count *= scalar(@$data); # total fields to be displayed in the table + $field_count *= scalar(@$data); # total fields to be displayed in the table $col_index = 0; $row_index++; $fields = []; - POPULATE_TABLE: +POPULATE_TABLE: + foreach my $db_row (@$data) { - POPULATE_ROW: + POPULATE_ROW: foreach my $table_column (@table_columns) { - if (grep {$table_column eq $_} keys %$db_row) { - $$fields[$col_index] = {hidden => 0, link_field => $link_field->{$table_column}, select_field => 0, field_name => ($table_column . "_tbl"), field_value => $db_row->{$table_column}}; + if ( grep { $table_column eq $_ } keys %$db_row ) { + $$fields[$col_index] = { + hidden => 0, link_field => $link_field->{$table_column}, select_field => 0, + field_name => ( $table_column . "_tbl" ), field_value => $db_row->{$table_column} + }; $col_index++; next POPULATE_ROW; - } - elsif ($table_column =~ m/^_((.*)_(.*$))/) { # this a special case - my $table_name = get_table_names('creator_'.$2); #Bug 14143 fix to remove ambiguity with table 'club_template_enrollment_fields' - my $record_set = _SELECT($1, @$table_name[0], $2 . "_id = " . $db_row->{$2 . "_id"}); - $$fields[$col_index] = {hidden => 0, link_field => $link_field->{$table_column}, select_field => 0, field_name => ($table_column . "_tbl"), field_value => $$record_set[0]{$1}}; + } elsif ( $table_column =~ m/^_((.*)_(.*$))/ ) { # this a special case + my $table_name = get_table_names( 'creator_' . $2 ) + ; #Bug 14143 fix to remove ambiguity with table 'club_template_enrollment_fields' + my $record_set = _SELECT( $1, @$table_name[0], $2 . "_id = " . $db_row->{ $2 . "_id" } ); + $$fields[$col_index] = { + hidden => 0, link_field => $link_field->{$table_column}, select_field => 0, + field_name => ( $table_column . "_tbl" ), field_value => $$record_set[0]{$1} + }; $col_index++; next POPULATE_ROW; - } - elsif ($table_column eq 'select' ) { - $$fields[$col_index] = {hidden => 0, select_field => 1, field_name => 'select', field_value => $db_row->{$select_value}}; + } elsif ( $table_column eq 'select' ) { + $$fields[$col_index] = + { hidden => 0, select_field => 1, field_name => 'select', field_value => $db_row->{$select_value} }; } } - $$table[$row_index] = {text_fields => $fields}; + $$table[$row_index] = { text_fields => $fields }; $col_index = 0; $row_index++; $fields = []; diff --git a/C4/Creators/PDF.pm b/C4/Creators/PDF.pm index e90b0bd3d7..8dbbf01795 100644 --- a/C4/Creators/PDF.pm +++ b/C4/Creators/PDF.pm @@ -55,30 +55,29 @@ use PDF::Reuse::Barcode; use File::Temp; use List::Util qw( first ); - sub _InitVars { - my $self = shift; + my $self = shift; my $param = shift; prInitVars($param); } sub new { my $invocant = shift; - my $type = ref($invocant) || $invocant; - my %opts = @_; - my $self = {}; - _InitVars() if ($opts{InitVars} == 0); - _InitVars($opts{InitVars}) if ($opts{InitVars} > 0); - delete($opts{InitVars}); - prDocDir($opts{'DocDir'}) if $opts{'DocDir'}; - delete($opts{'DocDir'}); + my $type = ref($invocant) || $invocant; + my %opts = @_; + my $self = {}; + _InitVars() if ( $opts{InitVars} == 0 ); + _InitVars( $opts{InitVars} ) if ( $opts{InitVars} > 0 ); + delete( $opts{InitVars} ); + prDocDir( $opts{'DocDir'} ) if $opts{'DocDir'}; + delete( $opts{'DocDir'} ); my $fh = File::Temp->new( UNLINK => 0, SUFFIX => '.pdf' ); - $opts{Name} = $self->{filename} = "$fh"; # filename - close $fh; # we need just filename + $opts{Name} = $self->{filename} = "$fh"; # filename + close $fh; # we need just filename - prFile(\%opts); - bless ($self, $type); + prFile( \%opts ); + bless( $self, $type ); return $self; } @@ -89,64 +88,64 @@ sub End { # slurp temporary filename and print it out for plack to pick up local $/ = undef; - open(my $fh, '<', $self->{filename}) || die "$self->{filename}: $!"; + open( my $fh, '<', $self->{filename} ) || die "$self->{filename}: $!"; print <$fh>; close $fh; unlink $self->{filename}; } sub Add { - my $self = shift; + my $self = shift; my $string = shift; prAdd($string); } sub Bookmark { - my $self = shift; + my $self = shift; my $reference = shift; prBookmark($reference); } sub Compress { - my $self = shift; + my $self = shift; my $directive = shift; prCompress($directive); } sub Doc { - my $self = shift; + my $self = shift; my %params = @_; prDoc(%params); } sub DocForm { - my $self = shift; + my $self = shift; my %params = @_; return prDocForm(%params); } sub Extract { my $self = shift; - my ($pdfFile, $pageNo, $oldInternalName) = @_; - return prExtract($pdfFile, $pageNo, $oldInternalName); + my ( $pdfFile, $pageNo, $oldInternalName ) = @_; + return prExtract( $pdfFile, $pageNo, $oldInternalName ); } sub Field { my $self = shift; - my ($fieldName, $value) = @_; - prField($fieldName, $value); + my ( $fieldName, $value ) = @_; + prField( $fieldName, $value ); } sub Font { - my $self = shift; + my $self = shift; my $fontName = shift; my $ttf = C4::Context->config('ttf'); - if ( $ttf ) { + if ($ttf) { my $ttf_path = first { $_->{type} eq $fontName } @{ $ttf->{font} }; if ( -e $ttf_path->{content} ) { - return prTTFont($ttf_path->{content}); + return prTTFont( $ttf_path->{content} ); } else { warn "ERROR in koha-conf.xml -- missing /path/to/font.ttf"; } @@ -161,7 +160,7 @@ sub FontSize { } sub Form { - my $self = shift; + my $self = shift; my %params = @_; return prForm(%params); } @@ -172,91 +171,95 @@ sub GetLogBuffer { } sub GraphState { - my $self = shift; + my $self = shift; my $string = shift; prGraphState($string); } sub Image { - my $self = shift; + my $self = shift; my %params = @_; return prImage(%params); } sub Init { my $self = shift; - my ($string, $duplicateCode) = @_; - prInit($string, $duplicateCode); + my ( $string, $duplicateCode ) = @_; + prInit( $string, $duplicateCode ); } sub AltJpeg { my $self = shift; - my ($imageData, $width, $height, $imageFormat, $altImageData, $altImageWidth, $altImageHeight, $altImageFormat) = @_; - return prAltJpeg($imageData, $width, $height, $imageFormat, $altImageData, $altImageWidth, $altImageHeight, $altImageFormat); + my ( $imageData, $width, $height, $imageFormat, $altImageData, $altImageWidth, $altImageHeight, $altImageFormat ) = + @_; + return prAltJpeg( + $imageData, $width, $height, $imageFormat, $altImageData, $altImageWidth, $altImageHeight, + $altImageFormat + ); } sub Jpeg { my $self = shift; - my ($imageData, $width, $height, $imageFormat) = @_; - return prJpeg($imageData, $width, $height, $imageFormat); + my ( $imageData, $width, $height, $imageFormat ) = @_; + return prJpeg( $imageData, $width, $height, $imageFormat ); } sub Js { - my $self = shift; + my $self = shift; my $string_or_fileName = shift; prJs($string_or_fileName); } sub Link { - my $self = shift; + my $self = shift; my %params = @_; prLink(%params); } sub Log { - my $self = shift; + my $self = shift; my $string = shift; prLog($string); } sub LogDir { - my $self = shift; + my $self = shift; my $directory = shift; prLogDir($directory); } sub Mbox { my $self = shift; - my ($lowerLeftX, $lowerLeftY, $upperRightX, $upperRightY) = @_; - prMbox($lowerLeftX, $lowerLeftY, $upperRightX, $upperRightY); + my ( $lowerLeftX, $lowerLeftY, $upperRightX, $upperRightY ) = @_; + prMbox( $lowerLeftX, $lowerLeftY, $upperRightX, $upperRightY ); } sub Page { - my $self = shift; + my $self = shift; my $noLog = shift; prPage($noLog); } sub SinglePage { my $self = shift; - my ($file, $pageNumber) = @_; - return prSinglePage($file, $pageNumber); + my ( $file, $pageNumber ) = @_; + return prSinglePage( $file, $pageNumber ); } sub StrWidth { my $self = shift; - my ($string, $font, $fontSize) = @_; + my ( $string, $font, $fontSize ) = @_; # replace font code with correct internal font $font = C4::Creators::PDF->Font($font); - return prStrWidth($string, $font, $fontSize); + return prStrWidth( $string, $font, $fontSize ); } sub Text { my $self = shift; - my ($x, $y, $string, $align, $rotation) = @_; - return prText($x, $y, $string, $align, $rotation); + my ( $x, $y, $string, $align, $rotation ) = @_; + return prText( $x, $y, $string, $align, $rotation ); } sub TTFont { diff --git a/C4/Creators/Profile.pm b/C4/Creators/Profile.pm index d9b84ca77a..37270286a0 100644 --- a/C4/Creators/Profile.pm +++ b/C4/Creators/Profile.pm @@ -8,10 +8,9 @@ use autouse 'Data::Dumper' => qw(Dumper); use C4::Context; use C4::Creators::Lib qw( get_unit_values ); - sub _check_params { - my $given_params = {}; - my $exit_code = 0; + my $given_params = {}; + my $exit_code = 0; my @valid_profile_params = ( 'printer_name', 'template_id', @@ -23,18 +22,17 @@ sub _check_params { 'units', 'creator', ); - if (scalar(@_) >1) { + if ( scalar(@_) > 1 ) { $given_params = {@_}; - foreach my $key (keys %{$given_params}) { - if (!(grep m/$key/, @valid_profile_params)) { - warn sprintf('Unrecognized parameter type of "%s".', $key); + foreach my $key ( keys %{$given_params} ) { + if ( !( grep m/$key/, @valid_profile_params ) ) { + warn sprintf( 'Unrecognized parameter type of "%s".', $key ); $exit_code = 1; } } - } - else { - if (!(grep m/$_/, @valid_profile_params)) { - warn sprintf('Unrecognized parameter type of "%s".', $_); + } else { + if ( !( grep m/$_/, @valid_profile_params ) ) { + warn sprintf( 'Unrecognized parameter type of "%s".', $_ ); $exit_code = 1; } } @@ -42,80 +40,82 @@ sub _check_params { } sub _conv_points { - my $self = shift; - my @unit_value = grep {$_->{'type'} eq $self->{units}} @{get_unit_values()}; - $self->{offset_horz} = $self->{offset_horz} * $unit_value[0]->{'value'}; - $self->{offset_vert} = $self->{offset_vert} * $unit_value[0]->{'value'}; - $self->{creep_horz} = $self->{creep_horz} * $unit_value[0]->{'value'}; - $self->{creep_vert} = $self->{creep_vert} * $unit_value[0]->{'value'}; + my $self = shift; + my @unit_value = grep { $_->{'type'} eq $self->{units} } @{ get_unit_values() }; + $self->{offset_horz} = $self->{offset_horz} * $unit_value[0]->{'value'}; + $self->{offset_vert} = $self->{offset_vert} * $unit_value[0]->{'value'}; + $self->{creep_horz} = $self->{creep_horz} * $unit_value[0]->{'value'}; + $self->{creep_vert} = $self->{creep_vert} * $unit_value[0]->{'value'}; return $self; } sub new { my $invocant = shift; - if (_check_params(@_) eq 1) { + if ( _check_params(@_) eq 1 ) { return -1; } my $type = ref($invocant) || $invocant; my $self = { - printer_name => 'Default Printer', - template_id => 0, - paper_bin => 'Tray 1', - offset_horz => 0, - offset_vert => 0, - creep_horz => 0, - creep_vert => 0, - units => 'POINT', + printer_name => 'Default Printer', + template_id => 0, + paper_bin => 'Tray 1', + offset_horz => 0, + offset_vert => 0, + creep_horz => 0, + creep_vert => 0, + units => 'POINT', @_, }; - bless ($self, $type); + bless( $self, $type ); return $self; } sub retrieve { my $invocant = shift; - my %opts = @_; - my $type = ref($invocant) || $invocant; - my $query = "SELECT * FROM printers_profile WHERE profile_id = ? AND creator = ?"; - my $sth = C4::Context->dbh->prepare($query); - $sth->execute($opts{'profile_id'}, $opts{'creator'}); - if ($sth->err) { - warn sprintf('Database returned the following error: %s', $sth->errstr); + my %opts = @_; + my $type = ref($invocant) || $invocant; + my $query = "SELECT * FROM printers_profile WHERE profile_id = ? AND creator = ?"; + my $sth = C4::Context->dbh->prepare($query); + $sth->execute( $opts{'profile_id'}, $opts{'creator'} ); + if ( $sth->err ) { + warn sprintf( 'Database returned the following error: %s', $sth->errstr ); return -1; } my $self = $sth->fetchrow_hashref; - $self = _conv_points($self) if ($opts{convert} && $opts{convert} == 1); - bless ($self, $type); + $self = _conv_points($self) if ( $opts{convert} && $opts{convert} == 1 ); + bless( $self, $type ); return $self; } sub delete { - my $self = {}; - my %opts = (); + my $self = {}; + my %opts = (); my $call_type = ''; - my @params = (); - if (ref($_[0])) { - $self = shift; # check to see if this is a method call - $call_type = 'C4::'. $self->{'creator'} .'::Profile->delete'; + my @params = (); + if ( ref( $_[0] ) ) { + $self = shift; # check to see if this is a method call + $call_type = 'C4::' . $self->{'creator'} . '::Profile->delete'; push @params, $self->{'profile_id'}, $self->{'creator'}; - } - else { - my $class = shift; #XXX: is this too hackish? - %opts = @_; + } else { + my $class = shift; #XXX: is this too hackish? + %opts = @_; $call_type = $class . "::delete"; push @params, $opts{'profile_id'}, $opts{'creator'}; } - if (scalar(@params) < 2) { # If there is no profile id or creator type then we cannot delete it - warn sprintf('%s : Cannot delete profile as the profile ID is invalid or non-existent.', $call_type) if !$params[0]; - warn sprintf('%s : Cannot delete profile as the creator type is invalid or non-existent.', $call_type) if !$params[1]; + if ( scalar(@params) < 2 ) { # If there is no profile id or creator type then we cannot delete it + warn sprintf( '%s : Cannot delete profile as the profile ID is invalid or non-existent.', $call_type ) + if !$params[0]; + warn sprintf( '%s : Cannot delete profile as the creator type is invalid or non-existent.', $call_type ) + if !$params[1]; return -1; } my $query = "DELETE FROM printers_profile WHERE profile_id = ? AND creator = ?"; - my $sth = C4::Context->dbh->prepare($query); -# $sth->{'TraceLevel'} = 3; + my $sth = C4::Context->dbh->prepare($query); + + # $sth->{'TraceLevel'} = 3; $sth->execute(@params); - if ($sth->err) { - warn sprintf('Database returned the following error on attempted DELETE: %s', $sth->errstr); + if ( $sth->err ) { + warn sprintf( 'Database returned the following error on attempted DELETE: %s', $sth->errstr ); return -1; } return 0; @@ -123,44 +123,44 @@ sub delete { sub save { my $self = shift; - if ($self->{'profile_id'}) { # if we have an profile_id, the record exists and needs UPDATE + if ( $self->{'profile_id'} ) { # if we have an profile_id, the record exists and needs UPDATE my @params; my $query = "UPDATE printers_profile SET "; - foreach my $key (keys %{$self}) { - next if ($key eq 'profile_id') || ($key eq 'creator'); - push (@params, $self->{$key}); + foreach my $key ( keys %{$self} ) { + next if ( $key eq 'profile_id' ) || ( $key eq 'creator' ); + push( @params, $self->{$key} ); $query .= "$key=?, "; } - $query = substr($query, 0, (length($query)-2)); - push (@params, $self->{'profile_id'}, $self->{'creator'}); + $query = substr( $query, 0, ( length($query) - 2 ) ); + push( @params, $self->{'profile_id'}, $self->{'creator'} ); $query .= " WHERE profile_id=? AND creator=?;"; my $sth = C4::Context->dbh->prepare($query); -# $sth->{'TraceLevel'} = 3; + + # $sth->{'TraceLevel'} = 3; $sth->execute(@params); - if ($sth->err) { - warn sprintf('Database returned the following error on attempted UPDATE: %s', $sth->errstr); + if ( $sth->err ) { + warn sprintf( 'Database returned the following error on attempted UPDATE: %s', $sth->errstr ); return -1; } return $self->{'profile_id'}; - } - else { # otherwise create a new record + } else { # otherwise create a new record my @params; my $query = "INSERT INTO printers_profile ("; - foreach my $key (keys %{$self}) { - push (@params, $self->{$key}); + foreach my $key ( keys %{$self} ) { + push( @params, $self->{$key} ); $query .= "$key, "; } - $query = substr($query, 0, (length($query)-2)); + $query = substr( $query, 0, ( length($query) - 2 ) ); $query .= ") VALUES ("; - for (my $i=1; $i<=(scalar keys %$self); $i++) { + for ( my $i = 1 ; $i <= ( scalar keys %$self ) ; $i++ ) { $query .= "?,"; } - $query = substr($query, 0, (length($query)-1)); + $query = substr( $query, 0, ( length($query) - 1 ) ); $query .= ");"; my $sth = C4::Context->dbh->prepare($query); $sth->execute(@params); - if ($sth->err) { - warn sprintf('Database returned the following error on attempted INSERT: %s', $sth->errstr); + if ( $sth->err ) { + warn sprintf( 'Database returned the following error on attempted INSERT: %s', $sth->errstr ); return -1; } my $sth1 = C4::Context->dbh->prepare("SELECT MAX(profile_id) FROM printers_profile;"); @@ -172,28 +172,27 @@ sub save { sub get_attr { my $self = shift; - if (_check_params(@_) eq 1) { + if ( _check_params(@_) eq 1 ) { return -1; } my ($attr) = @_; - if (exists($self->{$attr})) { + if ( exists( $self->{$attr} ) ) { return $self->{$attr}; - } - else { - warn sprintf('%s is currently undefined.', $attr); + } else { + warn sprintf( '%s is currently undefined.', $attr ); return -1; } } sub set_attr { my $self = shift; - if (_check_params(@_) eq 1) { + if ( _check_params(@_) eq 1 ) { return -1; } my %attrs = @_; - foreach my $attrib (keys(%attrs)) { + foreach my $attrib ( keys(%attrs) ) { $self->{$attrib} = $attrs{$attrib}; - }; + } return 0; } diff --git a/C4/Creators/Template.pm b/C4/Creators/Template.pm index 2699886361..412efbcfc3 100644 --- a/C4/Creators/Template.pm +++ b/C4/Creators/Template.pm @@ -9,11 +9,10 @@ use C4::Context; use C4::Creators::Profile; use C4::Creators::Lib qw( get_unit_values ); - sub _check_params { - shift if $_[0] =~ m/::/; # this seems a bit hackish - my $given_params = {}; - my $exit_code = 0; + shift if $_[0] =~ m/::/; # this seems a bit hackish + my $given_params = {}; + my $exit_code = 0; my @valid_template_params = ( 'profile_id', 'template_code', @@ -36,18 +35,17 @@ sub _check_params { 'creator', 'current_label', ); - if (scalar(@_) >1) { + if ( scalar(@_) > 1 ) { $given_params = {@_}; - foreach my $key (keys %{$given_params}) { - if (!(grep m/$key/, @valid_template_params)) { - warn sprintf('Unrecognized parameter type of "%s".', $key); + foreach my $key ( keys %{$given_params} ) { + if ( !( grep m/$key/, @valid_template_params ) ) { + warn sprintf( 'Unrecognized parameter type of "%s".', $key ); $exit_code = 1; } } - } - else { - if (!(grep m/$_/, @valid_template_params)) { - warn sprintf('Unrecognized parameter type of "%s".', $_); + } else { + if ( !( grep m/$_/, @valid_template_params ) ) { + warn sprintf( 'Unrecognized parameter type of "%s".', $_ ); $exit_code = 1; } } @@ -55,103 +53,106 @@ sub _check_params { } sub _conv_points { - my $self = shift; - my @unit_value = grep {$_->{'type'} eq $self->{'units'}} @{get_unit_values()}; - $self->{'page_width'} = $self->{'page_width'} * $unit_value[0]->{'value'}; - $self->{'page_height'} = $self->{'page_height'} * $unit_value[0]->{'value'}; - $self->{'label_width'} = $self->{'label_width'} * $unit_value[0]->{'value'}; - $self->{'label_height'} = $self->{'label_height'} * $unit_value[0]->{'value'}; - $self->{'top_text_margin'} = $self->{'top_text_margin'} * $unit_value[0]->{'value'}; - $self->{'left_text_margin'} = $self->{'left_text_margin'} * $unit_value[0]->{'value'}; - $self->{'top_margin'} = $self->{'top_margin'} * $unit_value[0]->{'value'}; - $self->{'left_margin'} = $self->{'left_margin'} * $unit_value[0]->{'value'}; - $self->{'col_gap'} = $self->{'col_gap'} * $unit_value[0]->{'value'}; - $self->{'row_gap'} = $self->{'row_gap'} * $unit_value[0]->{'value'}; + my $self = shift; + my @unit_value = grep { $_->{'type'} eq $self->{'units'} } @{ get_unit_values() }; + $self->{'page_width'} = $self->{'page_width'} * $unit_value[0]->{'value'}; + $self->{'page_height'} = $self->{'page_height'} * $unit_value[0]->{'value'}; + $self->{'label_width'} = $self->{'label_width'} * $unit_value[0]->{'value'}; + $self->{'label_height'} = $self->{'label_height'} * $unit_value[0]->{'value'}; + $self->{'top_text_margin'} = $self->{'top_text_margin'} * $unit_value[0]->{'value'}; + $self->{'left_text_margin'} = $self->{'left_text_margin'} * $unit_value[0]->{'value'}; + $self->{'top_margin'} = $self->{'top_margin'} * $unit_value[0]->{'value'}; + $self->{'left_margin'} = $self->{'left_margin'} * $unit_value[0]->{'value'}; + $self->{'col_gap'} = $self->{'col_gap'} * $unit_value[0]->{'value'}; + $self->{'row_gap'} = $self->{'row_gap'} * $unit_value[0]->{'value'}; return $self; } sub _apply_profile { - my $self = shift; + my $self = shift; my $creator = shift; - my $profile = C4::Creators::Profile->retrieve(profile_id => $self->{'profile_id'}, creator => $creator, convert => 1); - $self->{'top_margin'} = $self->{'top_margin'} + $profile->get_attr('offset_vert'); # controls vertical offset - $self->{'left_margin'} = $self->{'left_margin'} + $profile->get_attr('offset_horz'); # controls horizontal offset + my $profile = + C4::Creators::Profile->retrieve( profile_id => $self->{'profile_id'}, creator => $creator, convert => 1 ); + $self->{'top_margin'} = $self->{'top_margin'} + $profile->get_attr('offset_vert'); # controls vertical offset + $self->{'left_margin'} = $self->{'left_margin'} + $profile->get_attr('offset_horz'); # controls horizontal offset $self->{'label_height'} = $self->{'label_height'} + $profile->get_attr('creep_vert'); # controls vertical creep - $self->{'label_width'} = $self->{'label_width'} + $profile->get_attr('creep_horz'); # controls horizontal creep + $self->{'label_width'} = $self->{'label_width'} + $profile->get_attr('creep_horz'); # controls horizontal creep return $self; } sub new { my $invocant = shift; - my $type = ref($invocant) || $invocant; - if (_check_params(@_) eq 1) { + my $type = ref($invocant) || $invocant; + if ( _check_params(@_) eq 1 ) { return -1; } my $self = { - profile_id => 0, - template_code => 'DEFAULT TEMPLATE', - template_desc => 'Default description', - page_width => 0, - page_height => 0, - label_width => 0, - label_height => 0, - top_text_margin => 0, - left_text_margin => 0, - top_margin => 0, - left_margin => 0, - cols => 0, - rows => 0, - col_gap => 0, - row_gap => 0, - units => 'POINT', - template_stat => 0, # false if any data has changed and the db has not been updated + profile_id => 0, + template_code => 'DEFAULT TEMPLATE', + template_desc => 'Default description', + page_width => 0, + page_height => 0, + label_width => 0, + label_height => 0, + top_text_margin => 0, + left_text_margin => 0, + top_margin => 0, + left_margin => 0, + cols => 0, + rows => 0, + col_gap => 0, + row_gap => 0, + units => 'POINT', + template_stat => 0, # false if any data has changed and the db has not been updated @_, }; - bless ($self, $type); + bless( $self, $type ); return $self; } sub retrieve { my $invocant = shift; - my %opts = @_; - my $type = ref($invocant) || $invocant; - my $query = "SELECT * FROM " . $opts{'table_name'} . " WHERE template_id = ? AND creator = ?"; - my $sth = C4::Context->dbh->prepare($query); - $sth->execute($opts{'template_id'}, $opts{'creator'}); - if ($sth->err) { - warn sprintf('Database returned the following error: %s', $sth->errstr); + my %opts = @_; + my $type = ref($invocant) || $invocant; + my $query = "SELECT * FROM " . $opts{'table_name'} . " WHERE template_id = ? AND creator = ?"; + my $sth = C4::Context->dbh->prepare($query); + $sth->execute( $opts{'template_id'}, $opts{'creator'} ); + if ( $sth->err ) { + warn sprintf( 'Database returned the following error: %s', $sth->errstr ); return -1; } my $self = $sth->fetchrow_hashref; - $self = _conv_points($self) if (($opts{convert} && $opts{convert} == 1) || $opts{profile_id}); - $self = _apply_profile($self, $opts{'creator'}) if $opts{profile_id} && $self->{'profile_id'}; # don't bother if there is no profile_id + $self = _conv_points($self) if ( ( $opts{convert} && $opts{convert} == 1 ) || $opts{profile_id} ); + $self = _apply_profile( $self, $opts{'creator'} ) + if $opts{profile_id} && $self->{'profile_id'}; # don't bother if there is no profile_id $self->{'template_stat'} = 1; - bless ($self, $type); + bless( $self, $type ); return $self; } sub delete { - my $self = {}; - my %opts = (); - my $call_type = ''; + my $self = {}; + my %opts = (); + my $call_type = ''; my @query_params = (); - if (ref($_[0])) { - $self = shift; # check to see if this is a method call + if ( ref( $_[0] ) ) { + $self = shift; # check to see if this is a method call $call_type = 'C4::Labels::Template->delete'; push @query_params, $self->{'template_id'}, $self->{'creator'}; - } - else { - %opts = @_; + } else { + %opts = @_; $call_type = 'C4::Labels::Template::delete'; push @query_params, $opts{'template_id'}, $opts{'creator'}; } - if (scalar(@query_params) < 2) { # If there is no template id or creator type then we cannot delete it - warn sprintf('%s : Cannot delete template as the template ID is invalid or non-existent.', $call_type) if !$query_params[0]; - warn sprintf('%s : Cannot delete template as the creator type is invalid or non-existent.', $call_type) if !$query_params[1]; + if ( scalar(@query_params) < 2 ) { # If there is no template id or creator type then we cannot delete it + warn sprintf( '%s : Cannot delete template as the template ID is invalid or non-existent.', $call_type ) + if !$query_params[0]; + warn sprintf( '%s : Cannot delete template as the creator type is invalid or non-existent.', $call_type ) + if !$query_params[1]; return -1; } my $query = "DELETE FROM creator_templates WHERE template_id = ? AND creator = ?"; - my $sth = C4::Context->dbh->prepare($query); + my $sth = C4::Context->dbh->prepare($query); $sth->execute(@query_params); $self->{'template_stat'} = 0; } @@ -159,51 +160,50 @@ sub delete { sub save { my $self = shift; my %opts = @_; - if ($self->{'template_id'}) { # if we have an template_id, the record exists and needs UPDATE + if ( $self->{'template_id'} ) { # if we have an template_id, the record exists and needs UPDATE my @params; my $query = "UPDATE " . $opts{'table_name'} . " SET "; - foreach my $key (keys %{$self}) { - next if ($key eq 'template_id') || ($key eq 'template_stat') || ($key eq 'creator'); - push (@params, $self->{$key}); + foreach my $key ( keys %{$self} ) { + next if ( $key eq 'template_id' ) || ( $key eq 'template_stat' ) || ( $key eq 'creator' ); + push( @params, $self->{$key} ); $query .= "`$key`=?, "; } - $query = substr($query, 0, (length($query)-2)); - push (@params, $self->{'template_id'}, $self->{'creator'}); + $query = substr( $query, 0, ( length($query) - 2 ) ); + push( @params, $self->{'template_id'}, $self->{'creator'} ); $query .= " WHERE template_id=? AND creator=?;"; my $sth = C4::Context->dbh->prepare($query); $sth->execute(@params); - if ($sth->err) { - warn sprintf('Database returned the following error: %s', $sth->errstr); + if ( $sth->err ) { + warn sprintf( 'Database returned the following error: %s', $sth->errstr ); return -1; } $self->{'template_stat'} = 1; return $self->{'template_id'}; - } - else { # otherwise create a new record + } else { # otherwise create a new record my @params; - my $query = "INSERT INTO " . $opts{'table_name'} ." ("; - foreach my $key (keys %{$self}) { + my $query = "INSERT INTO " . $opts{'table_name'} . " ("; + foreach my $key ( keys %{$self} ) { next if $key eq 'template_stat'; - push (@params, $self->{$key}); + push( @params, $self->{$key} ); $query .= "`$key`, "; } - $query = substr($query, 0, (length($query)-2)); + $query = substr( $query, 0, ( length($query) - 2 ) ); $query .= ") VALUES ("; - for (my $i=1; $i<=((scalar keys %$self) - 1); $i++) { # key count less keys not db related... + for ( my $i = 1 ; $i <= ( ( scalar keys %$self ) - 1 ) ; $i++ ) { # key count less keys not db related... $query .= "?,"; } - $query = substr($query, 0, (length($query)-1)); + $query = substr( $query, 0, ( length($query) - 1 ) ); $query .= ");"; my $sth = C4::Context->dbh->prepare($query); $sth->execute(@params); - if ($sth->err) { - warn sprintf('Database returned the following error: %s', $sth->errstr); + if ( $sth->err ) { + warn sprintf( 'Database returned the following error: %s', $sth->errstr ); return -1; } - my $sth1 = C4::Context->dbh->prepare("SELECT MAX(template_id) FROM " . $opts{'table_name'} . ";"); + my $sth1 = C4::Context->dbh->prepare( "SELECT MAX(template_id) FROM " . $opts{'table_name'} . ";" ); $sth1->execute(); my $template_id = $sth1->fetchrow_array; - $self->{'template_id'} = $template_id; + $self->{'template_id'} = $template_id; $self->{'template_stat'} = 1; return $template_id; } @@ -211,72 +211,84 @@ sub save { sub get_attr { my $self = shift; - if (_check_params(@_) eq 1) { + if ( _check_params(@_) eq 1 ) { return -1; } my ($attr) = @_; - if (exists($self->{$attr})) { + if ( exists( $self->{$attr} ) ) { return $self->{$attr}; - } - else { + } else { return -1; } } sub set_attr { my $self = shift; - if (_check_params(@_) eq 1) { + if ( _check_params(@_) eq 1 ) { return -1; } my %attrs = @_; - foreach my $attrib (keys(%attrs)) { + foreach my $attrib ( keys(%attrs) ) { $self->{$attrib} = $attrs{$attrib}; - }; + } } sub get_label_position { - my ($self, $start_label) = @_; + my ( $self, $start_label ) = @_; my $current_label = $self->{'current_label'}; - if ($start_label eq 1) { + if ( $start_label eq 1 ) { $current_label->{'row_count'} = 1; $current_label->{'col_count'} = 1; - $current_label->{'llx'} = $self->{'left_margin'}; - $current_label->{'lly'} = ($self->{'page_height'} - $self->{'top_margin'} - $self->{'label_height'}); + $current_label->{'llx'} = $self->{'left_margin'}; + $current_label->{'lly'} = ( $self->{'page_height'} - $self->{'top_margin'} - $self->{'label_height'} ); + $self->{'current_label'} = $current_label; + return ( + $current_label->{'row_count'}, $current_label->{'col_count'}, $current_label->{'llx'}, + $current_label->{'lly'} + ); + } else { + $current_label->{'row_count'} = ceil( $start_label / $self->{'cols'} ); + $current_label->{'col_count'} = ( $start_label - ( ( $current_label->{'row_count'} - 1 ) * $self->{'cols'} ) ); + $current_label->{'llx'} = + $self->{'left_margin'} + + ( $self->{'label_width'} * ( $current_label->{'col_count'} - 1 ) ) + + ( $self->{'col_gap'} * ( $current_label->{'col_count'} - 1 ) ); + $current_label->{'lly'} = + $self->{'page_height'} - + $self->{'top_margin'} - + ( $self->{'label_height'} * $current_label->{'row_count'} ) - + ( $self->{'row_gap'} * ( $current_label->{'row_count'} - 1 ) ); $self->{'current_label'} = $current_label; - return ($current_label->{'row_count'}, $current_label->{'col_count'}, $current_label->{'llx'}, $current_label->{'lly'}); - } - else { - $current_label->{'row_count'} = ceil($start_label / $self->{'cols'}); - $current_label->{'col_count'} = ($start_label - (($current_label->{'row_count'} - 1) * $self->{'cols'})); - $current_label->{'llx'} = $self->{'left_margin'} + ($self->{'label_width'} * ($current_label->{'col_count'} - 1)) + ($self->{'col_gap'} * ($current_label->{'col_count'} - 1)); - $current_label->{'lly'} = $self->{'page_height'} - $self->{'top_margin'} - ($self->{'label_height'} * $current_label->{'row_count'}) - ($self->{'row_gap'} * ($current_label->{'row_count'} - 1)); - $self->{'current_label'} = $current_label; - return ($current_label->{'row_count'}, $current_label->{'col_count'}, $current_label->{'llx'}, $current_label->{'lly'}); + return ( + $current_label->{'row_count'}, $current_label->{'col_count'}, $current_label->{'llx'}, + $current_label->{'lly'} + ); } } sub get_next_label_pos { - my $self = shift; + my $self = shift; my $current_label = $self->{'current_label'}; - my $new_page = 0; - if ($current_label->{'col_count'} lt $self->get_attr('cols')) { - $current_label->{'llx'} = ($current_label->{'llx'} + $self->get_attr('label_width') + $self->get_attr('col_gap')); + my $new_page = 0; + if ( $current_label->{'col_count'} lt $self->get_attr('cols') ) { + $current_label->{'llx'} = + ( $current_label->{'llx'} + $self->get_attr('label_width') + $self->get_attr('col_gap') ); $current_label->{'col_count'}++; - } - else { + } else { $current_label->{'llx'} = $self->get_attr('left_margin'); - if ($current_label->{'row_count'} eq $self->get_attr('rows')) { + if ( $current_label->{'row_count'} eq $self->get_attr('rows') ) { $new_page = 1; - $current_label->{'lly'} = ($self->get_attr('page_height') - $self->get_attr('top_margin') - $self->get_attr('label_height')); + $current_label->{'lly'} = + ( $self->get_attr('page_height') - $self->get_attr('top_margin') - $self->get_attr('label_height') ); $current_label->{'row_count'} = 1; - } - else { - $current_label->{'lly'} = ($current_label->{'lly'} - $self->get_attr('row_gap') - $self->get_attr('label_height')); + } else { + $current_label->{'lly'} = + ( $current_label->{'lly'} - $self->get_attr('row_gap') - $self->get_attr('label_height') ); $current_label->{'row_count'}++; } $current_label->{'col_count'} = 1; } - return ($current_label->{'llx'}, $current_label->{'lly'}, $new_page); + return ( $current_label->{'llx'}, $current_label->{'lly'}, $new_page ); } 1; diff --git a/C4/External/Amazon.pm b/C4/External/Amazon.pm index 644d3ba145..34e1147d59 100644 --- a/C4/External/Amazon.pm +++ b/C4/External/Amazon.pm @@ -1,4 +1,5 @@ package C4::External::Amazon; + # Copyright (C) 2006 LibLime # # @@ -17,7 +18,6 @@ package C4::External::Amazon; # You should have received a copy of the GNU General Public License # along with Koha; if not, see . - use strict; use warnings; @@ -25,13 +25,12 @@ use vars qw(@ISA @EXPORT); BEGIN { require Exporter; - @ISA = qw(Exporter); + @ISA = qw(Exporter); @EXPORT = qw( get_amazon_tld ); } - sub get_amazon_tld { my %tld = ( CA => '.ca', @@ -44,11 +43,10 @@ sub get_amazon_tld { ); my $locale = C4::Context->preference('AmazonLocale'); - my $tld = $tld{ $locale } || '.com'; # default top level domain is .com + my $tld = $tld{$locale} || '.com'; # default top level domain is .com return $tld; } - =head1 NAME C4::External::Amazon - Functions for retrieving Amazon.com content in Koha diff --git a/C4/External/BakerTaylor.pm b/C4/External/BakerTaylor.pm index 13b2b5302e..d3db6145af 100644 --- a/C4/External/BakerTaylor.pm +++ b/C4/External/BakerTaylor.pm @@ -26,12 +26,12 @@ use C4::Context; use Modern::Perl; use vars qw(%EXPORT_TAGS $VERSION); -our (@ISA, @EXPORT_OK); +our ( @ISA, @EXPORT_OK ); BEGIN { require Exporter; - @ISA = qw(Exporter); - $VERSION = 3.07.00.049; + @ISA = qw(Exporter); + $VERSION = 3.07.00.049; @EXPORT_OK = qw(availability content_cafe_url image_url link_url http_jacket_link); } @@ -39,65 +39,70 @@ BEGIN { my ( $user, $pass, $agent, $image_url, $link_url ); sub _initialize { - $user = (@_ ? shift : C4::Context->preference('BakerTaylorUsername') ) || ''; # LL17984 - $pass = (@_ ? shift : C4::Context->preference('BakerTaylorPassword') ) || ''; # CC82349 - $link_url = (@_ ? shift : C4::Context->preference('BakerTaylorBookstoreURL')); - $image_url = "https://contentcafe2.btol.com/ContentCafe/Jacket.aspx?UserID=$user&Password=$pass&Options=Y&Return=T&Type=S&Value="; - $agent = "Koha/$VERSION [en] (Linux)"; - #"Mozilla/4.76 [en] (Win98; U)", # if for some reason you want to go stealth, you might prefer this + $user = ( @_ ? shift : C4::Context->preference('BakerTaylorUsername') ) || ''; # LL17984 + $pass = ( @_ ? shift : C4::Context->preference('BakerTaylorPassword') ) || ''; # CC82349 + $link_url = ( @_ ? shift : C4::Context->preference('BakerTaylorBookstoreURL') ); + $image_url = + "https://contentcafe2.btol.com/ContentCafe/Jacket.aspx?UserID=$user&Password=$pass&Options=Y&Return=T&Type=S&Value="; + $agent = "Koha/$VERSION [en] (Linux)"; + + #"Mozilla/4.76 [en] (Win98; U)", # if for some reason you want to go stealth, you might prefer this } sub image_url { _initialize(); - ($user and $pass) or return; - my $isbn = (@_ ? shift : ''); - $isbn =~ s/(p|-)//g; # sanitize - return $image_url . $isbn; + ( $user and $pass ) or return; + my $isbn = ( @_ ? shift : '' ); + $isbn =~ s/(p|-)//g; # sanitize + return $image_url . $isbn; } sub link_url { _initialize(); - my $isbn = (@_ ? shift : ''); - $isbn =~ s/(p|-)//g; # sanitize - $link_url or return; - return $link_url . $isbn; + my $isbn = ( @_ ? shift : '' ); + $isbn =~ s/(p|-)//g; # sanitize + $link_url or return; + return $link_url . $isbn; } sub content_cafe_url { _initialize(); - ($user and $pass) or return; - my $isbn = (@_ ? shift : ''); - $isbn =~ s/(p|-)//g; # sanitize - return "https://contentcafe2.btol.com/ContentCafeClient/ContentCafe.aspx?UserID=$user&Password=$pass&Options=Y&ItemKey=$isbn"; + ( $user and $pass ) or return; + my $isbn = ( @_ ? shift : '' ); + $isbn =~ s/(p|-)//g; # sanitize + return + "https://contentcafe2.btol.com/ContentCafeClient/ContentCafe.aspx?UserID=$user&Password=$pass&Options=Y&ItemKey=$isbn"; } sub http_jacket_link { _initialize(); - my $isbn = shift or return; - $isbn =~ s/(p|-)//g; # sanitize - my $image = availability($isbn); - my $alt = "Buy this book"; - $image and $image = qq($alt); - my $link = &link_url($isbn); - unless ($link) {return $image || '';} - return sprintf qq(%s),$link,($image||$alt); + my $isbn = shift or return; + $isbn =~ s/(p|-)//g; # sanitize + my $image = availability($isbn); + my $alt = "Buy this book"; + $image and $image = qq($alt); + my $link = &link_url($isbn); + unless ($link) { return $image || ''; } + return sprintf qq(%s), $link, ( $image || $alt ); } sub availability { _initialize(); - my $isbn = shift or return; - ($user and $pass) or return; - $isbn =~ s/(p|-)//g; # sanitize - my $url = "https://contentcafe2.btol.com/ContentCafe/InventoryAvailability.asmx/CheckInventory?UserID=$user&Password=$pass&Value=$isbn"; - my $content = get($url); - warn "could not retrieve $url" unless $content; - my $xmlsimple = XML::Simple->new(); - my $result = $xmlsimple->XMLin($content); - if ($result->{Error}) { - warn "Error returned to " . __PACKAGE__ . " : " . $result->{Error}; - } - my $avail = $result->{Availability}; - return ($avail and $avail !~ /^false$/i) ? &image_url($isbn) : 0; + my $isbn = shift or return; + ( $user and $pass ) or return; + $isbn =~ s/(p|-)//g; # sanitize + my $url = + "https://contentcafe2.btol.com/ContentCafe/InventoryAvailability.asmx/CheckInventory?UserID=$user&Password=$pass&Value=$isbn"; + my $content = get($url); + warn "could not retrieve $url" unless $content; + my $xmlsimple = XML::Simple->new(); + my $result = $xmlsimple->XMLin($content); + + if ( $result->{Error} ) { + warn "Error returned to " . __PACKAGE__ . " : " . $result->{Error}; + } + my $avail = $result->{Availability}; + return ( $avail and $avail !~ /^false$/i ) ? &image_url($isbn) : 0; } 1; diff --git a/C4/External/OverDrive.pm b/C4/External/OverDrive.pm index efc663f893..adf16dacda 100644 --- a/C4/External/OverDrive.pm +++ b/C4/External/OverDrive.pm @@ -30,21 +30,19 @@ use LWP::UserAgent; BEGIN { require Exporter; - our @ISA = qw( Exporter ) ; + our @ISA = qw( Exporter ); our @EXPORT = qw( GetOverDriveToken ); } sub _request { - my ( $request ) = @_; + my ($request) = @_; my $ua = LWP::UserAgent->new( agent => "Koha " . $Koha::VERSION ); my $response; - eval { - $response = $ua->request( $request ) ; - }; - if ( $@ ) { + eval { $response = $ua->request($request); }; + if ($@) { warn "OverDrive request failed: $@"; return; } @@ -74,24 +72,23 @@ Returns the token ( as "bearer ..." ) or undef on failure. =cut sub GetOverDriveToken { - my $key = C4::Context->preference( 'OverDriveClientKey' ); - my $secret = C4::Context->preference( 'OverDriveClientSecret' ); + my $key = C4::Context->preference('OverDriveClientKey'); + my $secret = C4::Context->preference('OverDriveClientSecret'); - return unless ( $key && $secret ) ; + return unless ( $key && $secret ); my $cache; eval { $cache = Koha::Caches->get_instance() }; my $token; - $cache and $token = $cache->get_from_cache( "overdrive_token" ) and return $token; + $cache and $token = $cache->get_from_cache("overdrive_token") and return $token; - my $request = HTTP::Request::Common::POST( 'https://oauth.overdrive.com/token', [ - grant_type => 'client_credentials' - ] ) ; + my $request = + HTTP::Request::Common::POST( 'https://oauth.overdrive.com/token', [ grant_type => 'client_credentials' ] ); $request->header( Authorization => LWP::Authen::Basic->auth_header( $key, $secret ) ); - my $response = _request( $request ) or return; + my $response = _request($request) or return; if ( $response->header('Content-Type') !~ m!application/json! ) { warn "Could not connect to OverDrive: " . $response->message; return; @@ -99,7 +96,8 @@ sub GetOverDriveToken { my $contents = from_json( $response->decoded_content ); if ( !$response->is_success ) { - warn "Could not log into OverDrive: " . ( $contents ? $contents->{'error_description'} : $response->decoded_content ); + warn "Could not log into OverDrive: " + . ( $contents ? $contents->{'error_description'} : $response->decoded_content ); return; } @@ -107,8 +105,10 @@ sub GetOverDriveToken { # Fudge factor to prevent spurious failures $cache - and $cache->set_in_cache( 'overdrive_token', $token, - { expiry => $contents->{'expires_in'} - 5 } ); + and $cache->set_in_cache( + 'overdrive_token', $token, + { expiry => $contents->{'expires_in'} - 5 } + ); return $token; } diff --git a/C4/External/Syndetics.pm b/C4/External/Syndetics.pm index 7788ee5f51..6f9d5517bc 100644 --- a/C4/External/Syndetics.pm +++ b/C4/External/Syndetics.pm @@ -1,4 +1,5 @@ package C4::External::Syndetics; + # Copyright (C) 2006 LibLime # # @@ -29,7 +30,7 @@ use vars qw(@ISA @EXPORT); BEGIN { require Exporter; - @ISA = qw(Exporter); + @ISA = qw(Exporter); @EXPORT = qw( get_syndetics_index get_syndetics_summary @@ -65,20 +66,25 @@ sub get_syndetics_index { return unless ( $isbn || $upc || $oclc ); - my $response = _fetch_syndetics_content('INDEX.XML', $isbn, $upc, $oclc); - unless ($response->content_type =~ /xml/) { + my $response = _fetch_syndetics_content( 'INDEX.XML', $isbn, $upc, $oclc ); + unless ( $response->content_type =~ /xml/ ) { return; } - my $content = $response->content; + my $content = $response->content; my $xmlsimple = XML::Simple->new(); $response = $xmlsimple->XMLin( $content, ) unless !$content; my $syndetics_elements; - for my $available_type ('SUMMARY','TOC','FICTION','AWARDS1','SERIES1','SPSUMMARY','SPREVIEW', 'AVPROFILE', 'AVSUMMARY','DBCHAPTER','LJREVIEW','PWREVIEW','SLJREVIEW','CHREVIEW','BLREVIEW','HBREVIEW','KIREVIEW','CRITICASREVIEW','ANOTES') { - if (exists $response->{$available_type} && $response->{$available_type} =~ /$available_type/) { + for my $available_type ( + 'SUMMARY', 'TOC', 'FICTION', 'AWARDS1', 'SERIES1', 'SPSUMMARY', 'SPREVIEW', 'AVPROFILE', + 'AVSUMMARY', 'DBCHAPTER', 'LJREVIEW', 'PWREVIEW', 'SLJREVIEW', 'CHREVIEW', 'BLREVIEW', 'HBREVIEW', 'KIREVIEW', + 'CRITICASREVIEW', 'ANOTES' + ) + { + if ( exists $response->{$available_type} && $response->{$available_type} =~ /$available_type/ ) { $syndetics_elements->{$available_type} = $available_type; } } @@ -89,16 +95,16 @@ sub get_syndetics_index { sub get_syndetics_summary { my ( $isbn, $upc, $oclc, $syndetics_elements ) = @_; - my $summary_type = exists($syndetics_elements->{'AVSUMMARY'}) ? 'AVSUMMARY.XML' : 'SUMMARY.XML'; - my $response = _fetch_syndetics_content($summary_type, $isbn, $upc, $oclc); - unless ($response->content_type =~ /xml/) { + my $summary_type = exists( $syndetics_elements->{'AVSUMMARY'} ) ? 'AVSUMMARY.XML' : 'SUMMARY.XML'; + my $response = _fetch_syndetics_content( $summary_type, $isbn, $upc, $oclc ); + unless ( $response->content_type =~ /xml/ ) { return; - } + } my $content = $response->content; my $summary; - eval { + eval { my $doc = $parser->parse_string($content); $summary = $doc->findvalue('//Fld520'); }; @@ -109,76 +115,81 @@ sub get_syndetics_summary { } sub get_syndetics_toc { - my ( $isbn,$upc,$oclc ) = @_; + my ( $isbn, $upc, $oclc ) = @_; - my $response = _fetch_syndetics_content('TOC.XML', $isbn, $upc, $oclc); - unless ($response->content_type =~ /xml/) { + my $response = _fetch_syndetics_content( 'TOC.XML', $isbn, $upc, $oclc ); + unless ( $response->content_type =~ /xml/ ) { return; - } + } - my $content = $response->content; + my $content = $response->content; my $xmlsimple = XML::Simple->new(); $response = $xmlsimple->XMLin( $content, - forcearray => [ qw(Fld970) ], + forcearray => [qw(Fld970)], ) unless !$content; + # manipulate response USMARC VarFlds VarDFlds Notes Fld520 a my $toc; - $toc = \@{$response->{VarFlds}->{VarDFlds}->{SSIFlds}->{Fld970}} if $response; - return $toc if $toc; + $toc = \@{ $response->{VarFlds}->{VarDFlds}->{SSIFlds}->{Fld970} } if $response; + return $toc if $toc; } sub get_syndetics_excerpt { - my ( $isbn,$upc,$oclc ) = @_; + my ( $isbn, $upc, $oclc ) = @_; - my $response = _fetch_syndetics_content('DBCHAPTER.XML', $isbn, $upc, $oclc); - unless ($response->content_type =~ /xml/) { + my $response = _fetch_syndetics_content( 'DBCHAPTER.XML', $isbn, $upc, $oclc ); + unless ( $response->content_type =~ /xml/ ) { return; - } - - my $content = $response->content; + } + + my $content = $response->content; my $xmlsimple = XML::Simple->new(); $response = $xmlsimple->XMLin( $content, - forcearray => [ qw(Fld520) ], + forcearray => [qw(Fld520)], ) unless !$content; + # manipulate response USMARC VarFlds VarDFlds Notes Fld520 a my $excerpt; - $excerpt = \@{$response->{VarFlds}->{VarDFlds}->{Notes}->{Fld520}} if $response; - return XMLout($excerpt, NoEscape => 1) if $excerpt; + $excerpt = \@{ $response->{VarFlds}->{VarDFlds}->{Notes}->{Fld520} } if $response; + return XMLout( $excerpt, NoEscape => 1 ) if $excerpt; } sub get_syndetics_reviews { - my ( $isbn,$upc,$oclc,$syndetics_elements ) = @_; + my ( $isbn, $upc, $oclc, $syndetics_elements ) = @_; my @reviews; my $review_sources = [ - {title => 'Library Journal Review', file => 'LJREVIEW.XML', element => 'LJREVIEW'}, - {title => 'Publishers Weekly Review', file => 'PWREVIEW.XML', element => 'PWREVIEW'}, - {title => 'School Library Journal Review', file => 'SLJREVIEW.XML', element => 'SLJREVIEW'}, - {title => 'CHOICE Review', file => 'CHREVIEW.XML', element => 'CHREVIEW'}, - {title => 'Booklist Review', file => 'BLREVIEW.XML', element => 'BLREVIEW'}, - {title => 'Horn Book Review', file => 'HBREVIEW.XML', element => 'HBREVIEW'}, - {title => 'Kirkus Book Review', file => 'KIREVIEW.XML', element => 'KIREVIEW'}, - {title => 'Criticas Review', file => 'CRITICASREVIEW.XML', element => 'CRITICASREVIEW'}, - {title => 'Spanish Review', file => 'SPREVIEW.XML', element => 'SPREVIEW'}, + { title => 'Library Journal Review', file => 'LJREVIEW.XML', element => 'LJREVIEW' }, + { title => 'Publishers Weekly Review', file => 'PWREVIEW.XML', element => 'PWREVIEW' }, + { title => 'School Library Journal Review', file => 'SLJREVIEW.XML', element => 'SLJREVIEW' }, + { title => 'CHOICE Review', file => 'CHREVIEW.XML', element => 'CHREVIEW' }, + { title => 'Booklist Review', file => 'BLREVIEW.XML', element => 'BLREVIEW' }, + { title => 'Horn Book Review', file => 'HBREVIEW.XML', element => 'HBREVIEW' }, + { title => 'Kirkus Book Review', file => 'KIREVIEW.XML', element => 'KIREVIEW' }, + { title => 'Criticas Review', file => 'CRITICASREVIEW.XML', element => 'CRITICASREVIEW' }, + { title => 'Spanish Review', file => 'SPREVIEW.XML', element => 'SPREVIEW' }, ]; for my $source (@$review_sources) { - if ($syndetics_elements->{$source->{element}} and $source->{element} =~ $syndetics_elements->{$source->{element}}) { + if ( $syndetics_elements->{ $source->{element} } + and $source->{element} =~ $syndetics_elements->{ $source->{element} } ) + { } else { + #warn "Skipping $source->{element} doesn't match $syndetics_elements->{$source->{element}} \n"; next; } - my $response = _fetch_syndetics_content($source->{file}, $isbn, $upc, $oclc); - unless ($response->content_type =~ /xml/) { + my $response = _fetch_syndetics_content( $source->{file}, $isbn, $upc, $oclc ); + unless ( $response->content_type =~ /xml/ ) { next; } my $content = $response->content; - - eval { + + eval { my $doc = $parser->parse_string($content); # note that using findvalue strips any HTML elements embedded @@ -188,7 +199,7 @@ sub get_syndetics_reviews { # may be present in the reviews, but does mean that any # and tags used to format the review are also gone. my $result = $doc->findvalue('//Fld520'); - push @reviews, {title => $source->{title}, reviews => [ { content => $result } ]} if $result; + push @reviews, { title => $source->{title}, reviews => [ { content => $result } ] } if $result; }; if ($@) { warn "Error parsing Syndetics $source->{title} review"; @@ -198,31 +209,10 @@ sub get_syndetics_reviews { } sub get_syndetics_editions { - my ( $isbn,$upc,$oclc ) = @_; + my ( $isbn, $upc, $oclc ) = @_; - my $response = _fetch_syndetics_content('FICTION.XML', $isbn, $upc, $oclc); - unless ($response->content_type =~ /xml/) { - return; - } - - my $content = $response->content; - - my $xmlsimple = XML::Simple->new(); - $response = $xmlsimple->XMLin( - $content, - forcearray => [ qw(Fld020) ], - ) unless !$content; - # manipulate response USMARC VarFlds VarDFlds Notes Fld520 a - my $similar_items; - $similar_items = \@{$response->{VarFlds}->{VarDFlds}->{NumbCode}->{Fld020}} if $response; - return $similar_items if $similar_items; -} - -sub get_syndetics_anotes { - my ( $isbn,$upc,$oclc) = @_; - - my $response = _fetch_syndetics_content('ANOTES.XML', $isbn, $upc, $oclc); - unless ($response->content_type =~ /xml/) { + my $response = _fetch_syndetics_content( 'FICTION.XML', $isbn, $upc, $oclc ); + unless ( $response->content_type =~ /xml/ ) { return; } @@ -231,20 +221,42 @@ sub get_syndetics_anotes { my $xmlsimple = XML::Simple->new(); $response = $xmlsimple->XMLin( $content, - forcearray => [ qw(Fld980) ], + forcearray => [qw(Fld020)], + ) unless !$content; + + # manipulate response USMARC VarFlds VarDFlds Notes Fld520 a + my $similar_items; + $similar_items = \@{ $response->{VarFlds}->{VarDFlds}->{NumbCode}->{Fld020} } if $response; + return $similar_items if $similar_items; +} + +sub get_syndetics_anotes { + my ( $isbn, $upc, $oclc ) = @_; + + my $response = _fetch_syndetics_content( 'ANOTES.XML', $isbn, $upc, $oclc ); + unless ( $response->content_type =~ /xml/ ) { + return; + } + + my $content = $response->content; + + my $xmlsimple = XML::Simple->new(); + $response = $xmlsimple->XMLin( + $content, + forcearray => [qw(Fld980)], ForceContent => 1, ) unless !$content; my @anotes; - for my $fld980 (@{$response->{VarFlds}->{VarDFlds}->{SSIFlds}->{Fld980}}) { + for my $fld980 ( @{ $response->{VarFlds}->{VarDFlds}->{SSIFlds}->{Fld980} } ) { + # this is absurd, but sometimes this data serializes differently - if(ref($fld980->{a}->{content}) eq 'ARRAY') { - for my $content (@{$fld980->{a}->{content}}) { - push @anotes, {content => $content}; - + if ( ref( $fld980->{a}->{content} ) eq 'ARRAY' ) { + for my $content ( @{ $fld980->{a}->{content} } ) { + push @anotes, { content => $content }; + } - } - else { - push @anotes, {content => $fld980->{a}->{content}}; + } else { + push @anotes, { content => $fld980->{a}->{content} }; } } return \@anotes; @@ -259,7 +271,8 @@ sub _fetch_syndetics_content { my $syndetics_client_code = C4::Context->preference('SyndeticsClientCode'); - my $url = "http://www.syndetics.com/index.aspx?isbn=$isbn/$element&client=$syndetics_client_code&type=xw10&upc=$upc&oclc=$oclc"; + my $url = + "http://www.syndetics.com/index.aspx?isbn=$isbn/$element&client=$syndetics_client_code&type=xw10&upc=$upc&oclc=$oclc"; my $ua = LWP::UserAgent->new; $ua->timeout(10); $ua->env_proxy; diff --git a/C4/Form/MessagingPreferences.pm b/C4/Form/MessagingPreferences.pm index 1322c6e260..bf1a89c3b4 100644 --- a/C4/Form/MessagingPreferences.pm +++ b/C4/Form/MessagingPreferences.pm @@ -71,20 +71,23 @@ adds a settings_updated template variable. =cut sub handle_form_action { - my ($query, $target_params, $template, $insert, $categorycode) = @_; + my ( $query, $target_params, $template, $insert, $categorycode ) = @_; my $messaging_options = C4::Members::Messaging::GetMessagingOptions(); + # TODO: If a "NONE" box and another are checked somehow (javascript failed), we should pay attention to the "NONE" box my $prefs_set = 0; - OPTION: foreach my $option ( @$messaging_options ) { - my $updater = { %{ $target_params }, - message_attribute_id => $option->{'message_attribute_id'} }; - +OPTION: foreach my $option (@$messaging_options) { + my $updater = { + %{$target_params}, + message_attribute_id => $option->{'message_attribute_id'} + }; + # find the desired transports - @{$updater->{'message_transport_types'}} = $query->multi_param( $option->{'message_attribute_id'} ); + @{ $updater->{'message_transport_types'} } = $query->multi_param( $option->{'message_attribute_id'} ); next OPTION unless $updater->{'message_transport_types'}; if ( $option->{'has_digest'} ) { - if ( List::Util::first { $_ == $option->{'message_attribute_id'} } $query->multi_param( 'digest' ) ) { + if ( List::Util::first { $_ == $option->{'message_attribute_id'} } $query->multi_param('digest') ) { $updater->{'wants_digest'} = 1; } } @@ -95,8 +98,9 @@ sub handle_form_action { } } - C4::Members::Messaging::SetMessagingPreference( $updater ); + C4::Members::Messaging::SetMessagingPreference($updater); } + # show the success message $template->param( settings_updated => 1 ); } @@ -116,27 +120,32 @@ C<$template> is the Template::Toolkit object for the response. =cut sub set_form_values { - my ($target_params, $template) = @_; + my ( $target_params, $template ) = @_; + # walk through the options and update them with these borrower_preferences my $messaging_options = C4::Members::Messaging::GetMessagingOptions(); - PREF: foreach my $option ( @$messaging_options ) { - my $pref = C4::Members::Messaging::GetMessagingPreferences( { %{ $target_params }, message_name => $option->{'message_name'} } ); +PREF: foreach my $option (@$messaging_options) { + my $pref = C4::Members::Messaging::GetMessagingPreferences( + { %{$target_params}, message_name => $option->{'message_name'} } ); $option->{ $option->{'message_name'} } = 1; + # make a hashref of the days, selecting one. if ( $option->{'takes_days'} ) { my $days_in_advance = $pref->{'days_in_advance'} ? $pref->{'days_in_advance'} : 0; $option->{days_in_advance} = $days_in_advance; - @{$option->{'select_days'}} = map { { - day => $_, - selected => $_ == $days_in_advance } - } ( 0..MAX_DAYS_IN_ADVANCE ); + @{ $option->{'select_days'} } = map { + { + day => $_, + selected => $_ == $days_in_advance + } + } ( 0 .. MAX_DAYS_IN_ADVANCE ); } - foreach my $transport ( keys %{$pref->{'transports'}} ) { - $option->{'transports_'.$transport} = 1; + foreach my $transport ( keys %{ $pref->{'transports'} } ) { + $option->{ 'transports_' . $transport } = 1; } $option->{'digest'} = 1 if $pref->{'wants_digest'}; } - $template->param(messaging_preferences => $messaging_options); + $template->param( messaging_preferences => $messaging_options ); } =head1 TODO diff --git a/C4/HTML5Media.pm b/C4/HTML5Media.pm index 2c5a878650..b130f24e4c 100644 --- a/C4/HTML5Media.pm +++ b/C4/HTML5Media.pm @@ -41,114 +41,127 @@ Get all relevant data from field 856. Takes a $record in the subroutine call, se =cut sub gethtml5media { - my $self = shift; - my $record = shift; - my @HTML5Media_sets = (); + my $self = shift; + my $record = shift; + my @HTML5Media_sets = (); my @HTML5Media_fields = $record->field(856); my $HTML5MediaParent; my $HTML5MediaWidth; my @HTML5MediaExtensions = split( /\|/, C4::Context->preference("HTML5MediaExtensions") ); my $HTML5MediaYouTube = C4::Context->preference("HTML5MediaYouTube"); my $marcflavour = C4::Context->preference("marcflavour"); + foreach my $HTML5Media_field (@HTML5Media_fields) { - my $is_youtube = 0; + my $is_youtube = 0; my %HTML5Media; + # protocol if ( $HTML5Media_field->indicator(1) eq '1' ) { $HTML5Media{protocol} = 'ftp'; - } - elsif ( $HTML5Media_field->indicator(1) eq '4' ) { + } elsif ( $HTML5Media_field->indicator(1) eq '4' ) { $HTML5Media{protocol} = 'http'; - } - elsif ( $HTML5Media_field->indicator(1) eq '7' ) { - if ($marcflavour eq 'MARC21') { + } elsif ( $HTML5Media_field->indicator(1) eq '7' ) { + if ( $marcflavour eq 'MARC21' ) { $HTML5Media{protocol} = $HTML5Media_field->subfield('2'); - } - elsif ($marcflavour eq 'UNIMARC') { + } elsif ( $marcflavour eq 'UNIMARC' ) { $HTML5Media{protocol} = $HTML5Media_field->subfield('y'); } - } - else { + } else { $HTML5Media{protocol} = 'http'; } + # user if ( $HTML5Media_field->subfield('l') ) { - $HTML5Media{username} = $HTML5Media_field->subfield('l'); # yes, that is arbitrary if h and l are not the same. originally i flipped a coin in that case. - } - elsif ( $HTML5Media_field->subfield('h') ) { + $HTML5Media{username} = $HTML5Media_field->subfield('l') + ; # yes, that is arbitrary if h and l are not the same. originally i flipped a coin in that case. + } elsif ( $HTML5Media_field->subfield('h') ) { $HTML5Media{username} = $HTML5Media_field->subfield('h'); } + # user/pass if ( $HTML5Media{username} && $HTML5Media_field->subfield('k') ) { $HTML5Media{loginblock} = $HTML5Media{username} . ':' . $HTML5Media_field->subfield('k') . '@'; - } - elsif ( $HTML5Media{username} ) { + } elsif ( $HTML5Media{username} ) { $HTML5Media{loginblock} = $HTML5Media{username} . '@'; - } - else { + } else { $HTML5Media{loginblock} = ''; } + # port if ( $HTML5Media_field->subfield('p') ) { $HTML5Media{portblock} = ':' . $HTML5Media_field->subfield('k'); - } - else { + } else { $HTML5Media{portblock} = ''; } + # src if ( $HTML5Media_field->subfield('u') ) { $HTML5Media{srcblock} = $HTML5Media_field->subfield('u'); - if (grep /youtu\.?be/, $HTML5Media_field->subfield('u') ) { - if ($HTML5MediaYouTube == 1) { + if ( grep /youtu\.?be/, $HTML5Media_field->subfield('u') ) { + if ( $HTML5MediaYouTube == 1 ) { my $url = $HTML5Media_field->subfield('u'); + # Credit for regex goes to https://stackoverflow.com/questions/3452546/how-do-i-get-the-youtube-video-id-from-a-url next unless $url =~ m{^.*(youtu\.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*}; my $video_id = $2; - next unless length($video_id) == 11; # Youtube video ids are 11 chars length - $HTML5Media{srcblock} = sprintf 'https://www.youtube.com/embed/%s', $video_id; + next unless length($video_id) == 11; # Youtube video ids are 11 chars length + $HTML5Media{srcblock} = sprintf 'https://www.youtube.com/embed/%s', $video_id; $HTML5Media{is_youtube} = 1; - $is_youtube = 1; + $is_youtube = 1; + } else { + next; # do not embed youtube videos } - else { - next; # do not embed youtube videos - } } + } elsif ( $HTML5Media_field->subfield('a') + && $HTML5Media_field->subfield('d') + && $HTML5Media_field->subfield('f') ) + { + $HTML5Media{host} = $HTML5Media_field->subfield('a'); + $HTML5Media{host} =~ s/(^\/|\/$)//g; + $HTML5Media{path} = $HTML5Media_field->subfield('d'); + $HTML5Media{path} =~ + s/(^\/|\/$)//g; # TODO we could check for youtube here too, but nobody uses these fields anyway… + $HTML5Media{file} = $HTML5Media_field->subfield('f'); + $HTML5Media{srcblock} = + $HTML5Media{protocol} . '://' + . $HTML5Media{loginblock} + . $HTML5Media{host} + . $HTML5Media{portblock} . '/' + . $HTML5Media{path} . '/' + . $HTML5Media{file}; + } else { + next; # no file to play } - elsif ( $HTML5Media_field->subfield('a') && $HTML5Media_field->subfield('d') && $HTML5Media_field->subfield('f') ) { - $HTML5Media{host} = $HTML5Media_field->subfield('a'); - $HTML5Media{host} =~ s/(^\/|\/$)//g; - $HTML5Media{path} = $HTML5Media_field->subfield('d'); - $HTML5Media{path} =~ s/(^\/|\/$)//g; # TODO we could check for youtube here too, but nobody uses these fields anyway… - $HTML5Media{file} = $HTML5Media_field->subfield('f'); - $HTML5Media{srcblock} = $HTML5Media{protocol} . '://' . $HTML5Media{loginblock} . $HTML5Media{host} . $HTML5Media{portblock} . '/' . $HTML5Media{path} . '/' . $HTML5Media{file}; - } - else { - next; # no file to play - } + # extension # check uploaded files if ( $HTML5Media{srcblock} =~ /\Qopac-retrieve-file.pl\E/ ) { my ( undef, $id ) = split /id=/, $HTML5Media{srcblock}; next if !$id; - my %public = ( ( caller )[1] =~ /opac/ ) ? ( public => 1 ): (); - my $upload = Koha::UploadedFiles->search({ - hashvalue => $id, %public, - })->next; + my %public = ( (caller)[1] =~ /opac/ ) ? ( public => 1 ) : (); + my $upload = Koha::UploadedFiles->search( + { + hashvalue => $id, %public, + } + )->next; next if !$upload || $upload->filename !~ /\./; $HTML5Media{extension} = ( $upload->filename =~ m/([^.]+)$/ )[0]; } + # check remote files else { - $HTML5Media{extension} = ($HTML5Media{srcblock} =~ m/([^.]+)$/)[0]; + $HTML5Media{extension} = ( $HTML5Media{srcblock} =~ m/([^.]+)$/ )[0]; } - if ( ( !grep /\Q$HTML5Media{extension}\E/, @HTML5MediaExtensions ) && ( $is_youtube != 1) ) { - next; # not a specified media file + if ( ( !grep /\Q$HTML5Media{extension}\E/, @HTML5MediaExtensions ) && ( $is_youtube != 1 ) ) { + next; # not a specified media file } + # youtube - if ($is_youtube == 1) { + if ( $is_youtube == 1 ) { $HTML5Media{mime} = 'video/webm'; $HTML5Media{type} = 'video'; } + # mime if ( $HTML5Media_field->subfield('c') ) { $HTML5Media{codecs} = $HTML5Media_field->subfield('c'); @@ -161,98 +174,92 @@ sub gethtml5media { elsif ( $HTML5Media{codecs} ) { if ( $HTML5Media{codecs} =~ /theora.*vorbis/ ) { $HTML5Media{mime} = 'video/ogg'; - } - elsif ( $HTML5Media{codecs} =~ /vp8.*vorbis/ ) { + } elsif ( $HTML5Media{codecs} =~ /vp8.*vorbis/ ) { $HTML5Media{mime} = 'video/webm'; - } - elsif ( ($HTML5Media{codecs} =~ /^vorbis$/) && ($HTML5Media{extension} eq 'ogg') ) { + } elsif ( ( $HTML5Media{codecs} =~ /^vorbis$/ ) && ( $HTML5Media{extension} eq 'ogg' ) ) { $HTML5Media{mime} = 'audio/ogg'; - } - elsif ( ($HTML5Media{codecs} =~ /^vorbis$/) && ($HTML5Media{extension} eq 'webm') ) { + } elsif ( ( $HTML5Media{codecs} =~ /^vorbis$/ ) && ( $HTML5Media{extension} eq 'webm' ) ) { $HTML5Media{mime} = 'audio/webm'; } } ### …or just from file extension else { if ( $HTML5Media{extension} eq 'ogv' ) { - $HTML5Media{mime} = 'video/ogg'; + $HTML5Media{mime} = 'video/ogg'; $HTML5Media{codecs} = 'theora,vorbis'; } if ( $HTML5Media{extension} eq 'oga' ) { - $HTML5Media{mime} = 'audio/ogg'; + $HTML5Media{mime} = 'audio/ogg'; $HTML5Media{codecs} = 'vorbis'; - } - elsif ( $HTML5Media{extension} eq 'spx' ) { - $HTML5Media{mime} = 'audio/ogg'; + } elsif ( $HTML5Media{extension} eq 'spx' ) { + $HTML5Media{mime} = 'audio/ogg'; $HTML5Media{codecs} = 'speex'; - } - elsif ( $HTML5Media{extension} eq 'opus' ) { - $HTML5Media{mime} = 'audio/ogg'; + } elsif ( $HTML5Media{extension} eq 'opus' ) { + $HTML5Media{mime} = 'audio/ogg'; $HTML5Media{codecs} = 'opus'; - } - elsif ( $HTML5Media{extension} eq 'vtt' ) { + } elsif ( $HTML5Media{extension} eq 'vtt' ) { $HTML5Media{mime} = 'text/vtt'; } } + # codecs if ( $HTML5Media{codecs} ) { $HTML5Media{codecblock} = '; codecs="' . $HTML5Media{codecs} . '"'; - } - else { + } else { $HTML5Media{codecblock} = ''; } + # type if ( $HTML5Media{mime} ) { $HTML5Media{typeblock} = ' type=\'' . $HTML5Media{mime} . $HTML5Media{codecblock} . '\''; + } else { + $HTML5Media{typeblock} = ''; } - else { - $HTML5Media{typeblock} = ''; - } + # element if ( $HTML5Media{mime} =~ /audio/ ) { $HTML5Media{type} = 'audio'; - } - elsif ( $HTML5Media{mime} =~ /video/ ) { + } elsif ( $HTML5Media{mime} =~ /video/ ) { $HTML5Media{type} = 'video'; - } - elsif ( $HTML5Media{mime} =~ /text/ ) { + } elsif ( $HTML5Media{mime} =~ /text/ ) { $HTML5Media{type} = 'track'; } + # push if ( $HTML5Media{srcblock} && $HTML5Media{type} ) { - push (@HTML5Media_sets, \%HTML5Media); + push( @HTML5Media_sets, \%HTML5Media ); } } + # parent element - for my $media ( @HTML5Media_sets ) { - if ( ($media->{mime}) && ($media->{mime} =~ /audio/) ) { + for my $media (@HTML5Media_sets) { + if ( ( $media->{mime} ) && ( $media->{mime} =~ /audio/ ) ) { if ( $HTML5MediaParent ne 'video' ) { $HTML5MediaParent = 'audio'; - $HTML5MediaWidth = ''; + $HTML5MediaWidth = ''; } - } - elsif ( ($media->{mime}) && ($media->{mime} =~ /video/) ) { + } elsif ( ( $media->{mime} ) && ( $media->{mime} =~ /video/ ) ) { $HTML5MediaParent = 'video'; - $HTML5MediaWidth = ' width="480"'; + $HTML5MediaWidth = ' width="480"'; } } + # child element - for my $media ( @HTML5Media_sets ) { - if ( ($media->{type}) && ( ($media->{type} eq 'video') || ($media->{type} eq 'audio') ) ) { + for my $media (@HTML5Media_sets) { + if ( ( $media->{type} ) && ( ( $media->{type} eq 'video' ) || ( $media->{type} eq 'audio' ) ) ) { if ( $media->{type} eq $HTML5MediaParent ) { $media->{child} = 'source'; } - } - else { + } else { $media->{child} = $media->{type}; } } return ( - HTML5MediaEnabled => ( (scalar(@HTML5Media_sets) > 0) && ($HTML5MediaParent) ), - HTML5MediaSets => \@HTML5Media_sets, - HTML5MediaParent => $HTML5MediaParent, - HTML5MediaWidth => $HTML5MediaWidth, + HTML5MediaEnabled => ( ( scalar(@HTML5Media_sets) > 0 ) && ($HTML5MediaParent) ), + HTML5MediaSets => \@HTML5Media_sets, + HTML5MediaParent => $HTML5MediaParent, + HTML5MediaWidth => $HTML5MediaWidth, ); } diff --git a/C4/Heading.pm b/C4/Heading.pm index 9a491c8a89..79001ecf62 100644 --- a/C4/Heading.pm +++ b/C4/Heading.pm @@ -22,7 +22,7 @@ use Modern::Perl; use MARC::Field; use C4::Context; use Module::Load qw( load ); -use List::Util qw( none ); +use List::Util qw( none ); =head1 NAME @@ -61,10 +61,10 @@ is returned. sub new_from_field { my $class = shift; my $field = shift; - my $frameworkcode = shift; #FIXME this is not used? + my $frameworkcode = shift; #FIXME this is not used? my $auth = shift; my $marcflavour = C4::Context->preference('marcflavour'); - my $marc_handler = _marc_format_handler($marcflavour); + my $marc_handler = _marc_format_handler($marcflavour); return unless $field; my $tag = $field->tag(); @@ -76,7 +76,7 @@ sub new_from_field { $self->{'auth_type'}, $self->{'thesaurus'}, $self->{'search_form'}, $self->{'display_form'}, $self->{'match_type'} - ) = $marc_handler->parse_heading($field, $auth ); + ) = $marc_handler->parse_heading( $field, $auth ); bless $self, $class; return $self; @@ -160,10 +160,10 @@ Check if the given subfield is valid for the given field. =cut sub valid_heading_subfield { - my $tag = shift; - my $subfield = shift; - my $marcflavour = C4::Context->preference('marcflavour'); - my $auth = shift; + my $tag = shift; + my $subfield = shift; + my $marcflavour = C4::Context->preference('marcflavour'); + my $auth = shift; my $marc_handler = _marc_format_handler($marcflavour); return $marc_handler->valid_heading_subfield( $tag, $subfield, $auth ); @@ -176,10 +176,10 @@ sub valid_heading_subfield { =cut sub _search { - my $self = shift; - my $index = shift || undef; - my $skipmetadata = shift || undef; - my $thesaurus = $self->{thesaurus}; + my $self = shift; + my $index = shift || undef; + my $skipmetadata = shift || undef; + my $thesaurus = $self->{thesaurus}; my $subject_heading_thesaurus = ''; my @marclist; my @and_or; @@ -199,11 +199,11 @@ sub _search { } if ( $check_thesaurus && $thesaurus ) { - push @marclist, 'thesaurus'; - push @and_or, 'and'; + push @marclist, 'thesaurus'; + push @and_or, 'and'; push @excluding, ''; - push @operator, 'is'; - push @value, $thesaurus; + push @operator, 'is'; + push @value, $thesaurus; } require Koha::SearchEngine::QueryBuilder; @@ -212,10 +212,8 @@ sub _search { # Use state variables to avoid recreating the objects every time. # With Elasticsearch this also avoids creating a massive amount of # ES connectors that would eventually run out of file descriptors. - state $builder = Koha::SearchEngine::QueryBuilder->new( - { index => $Koha::SearchEngine::AUTHORITIES_INDEX } ); - state $searcher = Koha::SearchEngine::Search->new( - {index => $Koha::SearchEngine::AUTHORITIES_INDEX} ); + state $builder = Koha::SearchEngine::QueryBuilder->new( { index => $Koha::SearchEngine::AUTHORITIES_INDEX } ); + state $searcher = Koha::SearchEngine::Search->new( { index => $Koha::SearchEngine::AUTHORITIES_INDEX } ); my $search_query = $builder->build_authorities_query_compat( \@marclist, \@and_or, \@excluding, \@operator, @@ -224,6 +222,7 @@ sub _search { ); my ( $matched_auths, $total ) = $searcher->search_auth_compat( $search_query, 0, 20, $skipmetadata ); + # Some auth records may not contain the 040$f to specify their source # This is legal, so we do a fallback search if ( @@ -235,16 +234,16 @@ sub _search { 'notspecified', 'cash', 'rvm', 'sears', 'aat' ) - ) + ) { pop @value; push @value, 'notdefined'; - $search_query = - $builder->build_authorities_query_compat( \@marclist, \@and_or, + $search_query = $builder->build_authorities_query_compat( + \@marclist, \@and_or, \@excluding, \@operator, \@value, $self->{'auth_type'}, - 'AuthidAsc' ); - ( $matched_auths, $total ) = - $searcher->search_auth_compat( $search_query, 0, 20, $skipmetadata ); + 'AuthidAsc' + ); + ( $matched_auths, $total ) = $searcher->search_auth_compat( $search_query, 0, 20, $skipmetadata ); } return ( $matched_auths, $total ); @@ -261,7 +260,7 @@ depending on the selected MARC flavour. sub _marc_format_handler { my $marcflavour = uc shift; - my $pname = "C4::Heading::$marcflavour"; + my $pname = "C4::Heading::$marcflavour"; load $pname; return $pname->new(); } diff --git a/C4/Heading/MARC21.pm b/C4/Heading/MARC21.pm index 40a0d15199..df39192297 100644 --- a/C4/Heading/MARC21.pm +++ b/C4/Heading/MARC21.pm @@ -21,7 +21,6 @@ use strict; use warnings; use MARC::Field; - =head1 NAME C4::Heading::MARC21 @@ -68,33 +67,33 @@ my $bib_heading_fields = { main_entry => 1 }, '147' => { - auth_type => 'NAME_EVENT', - subfields => 'acdgvxyz68', + auth_type => 'NAME_EVENT', + subfields => 'acdgvxyz68', main_entry => 1 }, '148' => { - auth_type => 'CHRON_TERM', - subfields => 'abvxyz68', + auth_type => 'CHRON_TERM', + subfields => 'abvxyz68', main_entry => 1 }, '150' => { - auth_type => 'TOPIC_TERM', - subfields => 'abgvxyz68', + auth_type => 'TOPIC_TERM', + subfields => 'abgvxyz68', main_entry => 1 }, '151' => { - auth_type => 'GEOGR_NAME', - subfields => 'avxyz68', + auth_type => 'GEOGR_NAME', + subfields => 'avxyz68', main_entry => 1 }, '155' => { - auth_type => 'GENRE/FORM', - subfields => 'abvxyz68', + auth_type => 'GENRE/FORM', + subfields => 'abvxyz68', main_entry => 1 }, '162' => { - auth_type => 'MED_PERFRM', - subfields => 'a68', + auth_type => 'MED_PERFRM', + subfields => 'a68', main_entry => 1 }, '180' => { @@ -158,10 +157,8 @@ my $bib_heading_fields = { subfields => 'abcdfghklmnoprst', series => 1 }, - '811' => - { auth_type => 'MEETI_NAME', subfields => 'acdefghklnpqst', series => 1 }, - '830' => - { auth_type => 'UNIF_TITLE', subfields => 'adfghklmnoprst', series => 1 }, + '811' => { auth_type => 'MEETI_NAME', subfields => 'acdefghklnpqst', series => 1 }, + '830' => { auth_type => 'UNIF_TITLE', subfields => 'adfghklmnoprst', series => 1 }, }; my $auth_heading_fields = { @@ -262,16 +259,15 @@ sub new { =cut sub valid_heading_tag { - my $self = shift; - my $tag = shift; - my $frameworkcode = shift; - my $auth = shift; - my $heading_fields = $auth ? { %$auth_heading_fields } : { %$bib_heading_fields }; + my $self = shift; + my $tag = shift; + my $frameworkcode = shift; + my $auth = shift; + my $heading_fields = $auth ? {%$auth_heading_fields} : {%$bib_heading_fields}; if ( exists $heading_fields->{$tag} ) { return 1; - } - else { + } else { return 0; } @@ -282,15 +278,15 @@ sub valid_heading_tag { =cut sub valid_heading_subfield { - my $self = shift; - my $tag = shift; - my $subfield = shift; - my $auth = shift; + my $self = shift; + my $tag = shift; + my $subfield = shift; + my $auth = shift; - my $heading_fields = $auth ? { %$auth_heading_fields } : { %$bib_heading_fields }; + my $heading_fields = $auth ? {%$auth_heading_fields} : {%$bib_heading_fields}; if ( exists $heading_fields->{$tag} ) { - return 1 if ($heading_fields->{$tag}->{subfields} =~ /$subfield/); + return 1 if ( $heading_fields->{$tag}->{subfields} =~ /$subfield/ ); } return 0; } @@ -300,8 +296,8 @@ sub valid_heading_subfield { =cut sub get_valid_bib_heading_subfields { - my $self = shift; - my $tag = shift; + my $self = shift; + my $tag = shift; return $bib_heading_fields->{$tag}->{subfields} // undef; } @@ -311,8 +307,8 @@ sub get_valid_bib_heading_subfields { =cut sub get_auth_heading_subfields_to_report { - my $self = shift; - my $tag = shift; + my $self = shift; + my $tag = shift; my $subfields = $auth_heading_fields->{$tag}->{subfields} // ''; $subfields =~ s/[68]//; @@ -331,21 +327,21 @@ sub parse_heading { my $field = shift; my $auth = shift; - my $tag = $field->tag; - my $heading_fields = $auth ? { %$auth_heading_fields } : { %$bib_heading_fields }; + my $tag = $field->tag; + my $heading_fields = $auth ? {%$auth_heading_fields} : {%$bib_heading_fields}; my $field_info = $heading_fields->{$tag}; - my $auth_type = $field_info->{'auth_type'}; + my $auth_type = $field_info->{'auth_type'}; my $thesaurus = - $tag =~ m/6../ - ? _get_subject_thesaurus($field) - : undef; # We can't know the thesaurus for non-subject fields - my $search_heading = - _get_search_heading( $field, $field_info->{'subfields'} ); - my $display_heading = - _get_display_heading( $field, $field_info->{'subfields'} ); - return ( $auth_type, $thesaurus, $search_heading, $display_heading, - 'exact' ); + $tag =~ m/6../ + ? _get_subject_thesaurus($field) + : undef; # We can't know the thesaurus for non-subject fields + my $search_heading = _get_search_heading( $field, $field_info->{'subfields'} ); + my $display_heading = _get_display_heading( $field, $field_info->{'subfields'} ); + return ( + $auth_type, $thesaurus, $search_heading, $display_heading, + 'exact' + ); } =head1 INTERNAL FUNCTIONS @@ -366,26 +362,19 @@ sub _get_subject_thesaurus { my $thesaurus = "notdefined"; if ( $ind2 eq '0' ) { $thesaurus = "lcsh"; - } - elsif ( $ind2 eq '1' ) { + } elsif ( $ind2 eq '1' ) { $thesaurus = "lcac"; - } - elsif ( $ind2 eq '2' ) { + } elsif ( $ind2 eq '2' ) { $thesaurus = "mesh"; - } - elsif ( $ind2 eq '3' ) { + } elsif ( $ind2 eq '3' ) { $thesaurus = "nal"; - } - elsif ( $ind2 eq '4' ) { + } elsif ( $ind2 eq '4' ) { $thesaurus = "notspecified"; - } - elsif ( $ind2 eq '5' ) { + } elsif ( $ind2 eq '5' ) { $thesaurus = "cash"; - } - elsif ( $ind2 eq '6' ) { + } elsif ( $ind2 eq '6' ) { $thesaurus = "rvm"; - } - elsif ( $ind2 eq '7' ) { + } elsif ( $ind2 eq '7' ) { my $sf2 = $field->subfield('2'); $thesaurus = $sf2 if defined($sf2); } @@ -415,12 +404,10 @@ sub _get_search_heading { if ($first) { $first = 0; $heading = $value; - } - else { + } else { if ( exists $subdivisions{$code} ) { $heading .= " $subdivisions{$code} $value"; - } - else { + } else { $heading .= " $value"; } } @@ -453,12 +440,10 @@ sub _get_display_heading { if ($first) { $first = 0; $heading = $value; - } - else { + } else { if ( exists $subdivisions{$code} ) { $heading .= "--$value"; - } - else { + } else { $heading .= " $value"; } } diff --git a/C4/Heading/UNIMARC.pm b/C4/Heading/UNIMARC.pm index a0a8a3edda..1021f06aa1 100644 --- a/C4/Heading/UNIMARC.pm +++ b/C4/Heading/UNIMARC.pm @@ -23,7 +23,6 @@ use warnings; use MARC::Field; use C4::Context; - =head1 NAME C4::Heading::UNIMARC @@ -102,12 +101,12 @@ sub valid_heading_tag { =cut sub valid_heading_subfield { - my $self = shift; - my $tag = shift; - my $subfield = shift; + my $self = shift; + my $tag = shift; + my $subfield = shift; if ( exists $bib_heading_fields->{$tag} ) { - return 1 if ($bib_heading_fields->{$tag}->{subfields} =~ /$subfield/); + return 1 if ( $bib_heading_fields->{$tag}->{subfields} =~ /$subfield/ ); } return 0; } @@ -119,13 +118,11 @@ sub valid_heading_subfield { sub parse_heading { my ( $self, $field ) = @_; - my $tag = $field->tag; - my $field_info = $bib_heading_fields->{$tag}; - my $auth_type = $field_info->{'auth_type'}; - my $search_heading = - _get_search_heading( $field, $field_info->{'subfields'} ); - my $display_heading = - _get_display_heading( $field, $field_info->{'subfields'} ); + my $tag = $field->tag; + my $field_info = $bib_heading_fields->{$tag}; + my $auth_type = $field_info->{'auth_type'}; + my $search_heading = _get_search_heading( $field, $field_info->{'subfields'} ); + my $display_heading = _get_display_heading( $field, $field_info->{'subfields'} ); return ( $auth_type, undef, $search_heading, $display_heading, 'exact' ); } @@ -166,12 +163,10 @@ sub _get_search_heading { if ($first) { $first = 0; $heading = $value; - } - else { + } else { if ( exists $subdivisions{$code} ) { $heading .= " $subdivisions{$code} $value"; - } - else { + } else { $heading .= " $value"; } } @@ -202,12 +197,10 @@ sub _get_display_heading { if ($first) { $first = 0; $heading = $value; - } - else { + } else { if ( exists $subdivisions{$code} ) { $heading .= "--$value"; - } - else { + } else { $heading .= " $value"; } } diff --git a/C4/HoldsQueue.pm b/C4/HoldsQueue.pm index 3f3f3d22f9..93cc6ce750 100644 --- a/C4/HoldsQueue.pm +++ b/C4/HoldsQueue.pm @@ -31,14 +31,15 @@ use Koha::Libraries; use Koha::Logger; use Koha::Patrons; -use List::Util qw( shuffle ); -use List::MoreUtils qw( any ); +use List::Util qw( shuffle ); +use List::MoreUtils qw( any ); use Algorithm::Munkres qw(); -our (@ISA, @EXPORT_OK); +our ( @ISA, @EXPORT_OK ); + BEGIN { require Exporter; - @ISA = qw(Exporter); + @ISA = qw(Exporter); @EXPORT_OK = qw( CreateQueue GetHoldsQueueItems @@ -48,10 +49,9 @@ BEGIN { GetPendingHoldRequestsForBib load_branches_to_pull_from update_queue_for_biblio - ); + ); } - =head1 FUNCTIONS =head2 TransportCostMatrix @@ -63,10 +63,10 @@ Returns Transport Cost Matrix as a hashref => dbh; - my $transport_costs = $dbh->selectall_arrayref("SELECT * FROM transport_cost",{ Slice => {} }); + my $dbh = C4::Context->dbh; + my $transport_costs = $dbh->selectall_arrayref( "SELECT * FROM transport_cost", { Slice => {} } ); my $today = dt_from_string(); my %transport_cost_matrix; @@ -95,20 +95,20 @@ Records: { frombranch => , tobranch => , cost =>
, disable_t sub UpdateTransportCostMatrix { my ($records) = @_; - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; - my $sth = $dbh->prepare("INSERT INTO transport_cost (frombranch, tobranch, cost, disable_transfer) VALUES (?, ?, ?, ?)"); + my $sth = + $dbh->prepare("INSERT INTO transport_cost (frombranch, tobranch, cost, disable_transfer) VALUES (?, ?, ?, ?)"); $dbh->do("DELETE FROM transport_cost"); foreach (@$records) { my $cost = $_->{cost}; my $from = $_->{frombranch}; - my $to = $_->{tobranch}; - if ($_->{disable_transfer}) { + my $to = $_->{tobranch}; + if ( $_->{disable_transfer} ) { $cost ||= 0; - } - elsif ( !defined ($cost) || ($cost !~ m/(0|[1-9][0-9]*)(\.[0-9]*)?/o) ) { - warn "Invalid $from -> $to cost $cost - must be a number >= 0, disabling"; + } elsif ( !defined($cost) || ( $cost !~ m/(0|[1-9][0-9]*)(\.[0-9]*)?/o ) ) { + warn "Invalid $from -> $to cost $cost - must be a number >= 0, disabling"; $cost = 0; $_->{disable_transfer} = 1; } @@ -126,13 +126,13 @@ Returns hold queue for a holding branch. If branch is omitted, then whole queue sub GetHoldsQueueItems { my $params = shift; - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $search_params; - $search_params->{'me.holdingbranch'} = $params->{branchlimit} if $params->{branchlimit}; - $search_params->{'itype'} = $params->{itemtypeslimit} if $params->{itemtypeslimit}; - $search_params->{'ccode'} = $params->{ccodeslimit} if $params->{ccodeslimit}; - $search_params->{'location'} = $params->{locationslimit} if $params->{locationslimit}; + $search_params->{'me.holdingbranch'} = $params->{branchlimit} if $params->{branchlimit}; + $search_params->{'itype'} = $params->{itemtypeslimit} if $params->{itemtypeslimit}; + $search_params->{'ccode'} = $params->{ccodeslimit} if $params->{ccodeslimit}; + $search_params->{'location'} = $params->{locationslimit} if $params->{locationslimit}; my $results = Koha::Hold::HoldsQueueItems->search( $search_params, @@ -143,11 +143,7 @@ sub GetHoldsQueueItems { prefetch => [ 'biblio', 'biblioitem', - { - 'item' => { - 'item_group_item' => 'item_group' - } - } + { 'item' => { 'item_group_item' => 'item_group' } } ], order_by => [ 'ccode', 'location', 'item.cn_sort', 'author', @@ -242,7 +238,6 @@ sub CreateQueue { } } - =head2 GetBibsWithPendingHoldRequests my $biblionumber_aref = GetBibsWithPendingHoldRequests(); @@ -313,7 +308,7 @@ sub GetPendingHoldRequestsForBib { my $sth = $dbh->prepare($request_query); $sth->execute($biblionumber); - my $requests = $sth->fetchall_arrayref({}); + my $requests = $sth->fetchall_arrayref( {} ); return $requests; } @@ -337,9 +332,9 @@ to fill a hold request if and only if: =cut sub GetItemsAvailableToFillHoldRequestsForBib { - my ($biblionumber, $branches_to_use) = @_; + my ( $biblionumber, $branches_to_use ) = @_; - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $items_query = "SELECT items.itemnumber, homebranch, holdingbranch, itemtypes.itemtype AS itype FROM items "; @@ -375,20 +370,22 @@ sub GetItemsAvailableToFillHoldRequestsForBib { AND items.biblionumber = ? AND branchtransfers.itemnumber IS NULL"; - my @params = ($biblionumber, $biblionumber, $biblionumber); - if ($branches_to_use && @$branches_to_use) { - $items_query .= " AND holdingbranch IN (" . join (",", map { "?" } @$branches_to_use) . ")"; + my @params = ( $biblionumber, $biblionumber, $biblionumber ); + if ( $branches_to_use && @$branches_to_use ) { + $items_query .= " AND holdingbranch IN (" . join( ",", map { "?" } @$branches_to_use ) . ")"; push @params, @$branches_to_use; } my $sth = $dbh->prepare($items_query); $sth->execute(@params); - my $itm = $sth->fetchall_arrayref({}); - return [ grep { - my $rule = C4::Circulation::GetBranchItemRule($_->{homebranch}, $_->{itype}); - $_->{holdallowed} = $rule->{holdallowed}; - $_->{hold_fulfillment_policy} = $rule->{hold_fulfillment_policy}; - } @{$itm} ]; + my $itm = $sth->fetchall_arrayref( {} ); + return [ + grep { + my $rule = C4::Circulation::GetBranchItemRule( $_->{homebranch}, $_->{itype} ); + $_->{holdallowed} = $rule->{holdallowed}; + $_->{hold_fulfillment_policy} = $rule->{hold_fulfillment_policy}; + } @{$itm} + ]; } =head2 _checkHoldPolicy @@ -598,10 +595,11 @@ RETRY: # end. $inf = $max * $num_tasks + 1; - my @m0 = map {[(undef) x $num_tasks]} (1..$num_agents); + my @m0 = map { [ (undef) x $num_tasks ] } ( 1 .. $num_agents ); for ( my $i = 0 ; $i < $num_agents ; $i++ ) { for ( my $j = 0 ; $j < $num_tasks ; $j++ ) { if ( $m[$i][$j] < 0 ) { + # Bias towards not allocating items to holds closer to # the end of the queue in the queue if not all holds # can be filled by representing infinity with @@ -711,7 +709,7 @@ RETRY: =cut sub MapItemsToHoldRequests { - my ($hold_requests, $available_items, $branches_to_use, $transport_cost_matrix) = @_; + my ( $hold_requests, $available_items, $branches_to_use, $transport_cost_matrix ) = @_; # handle trival cases return unless scalar(@$hold_requests) > 0; @@ -719,7 +717,7 @@ sub MapItemsToHoldRequests { map { $_->{_object} = Koha::Items->find( $_->{itemnumber} ) } @$available_items; my $libraries = {}; - map { $libraries->{$_->id} = $_ } Koha::Libraries->search->as_list; + map { $libraries->{ $_->id } = $_ } Koha::Libraries->search->as_list; # group available items by itemnumber my %items_by_itemnumber = map { $_->{itemnumber} => $_ } @$available_items; @@ -735,14 +733,12 @@ sub MapItemsToHoldRequests { # Look for Local Holds Priority matches first if ( C4::Context->preference('LocalHoldsPriority') ) { - my $LocalHoldsPriorityPatronControl = - C4::Context->preference('LocalHoldsPriorityPatronControl'); - my $LocalHoldsPriorityItemControl = - C4::Context->preference('LocalHoldsPriorityItemControl'); + my $LocalHoldsPriorityPatronControl = C4::Context->preference('LocalHoldsPriorityPatronControl'); + my $LocalHoldsPriorityItemControl = C4::Context->preference('LocalHoldsPriorityItemControl'); foreach my $request (@$hold_requests) { last if $num_items_remaining == 0; - my $patron = Koha::Patrons->find($request->{borrowernumber}); + my $patron = Koha::Patrons->find( $request->{borrowernumber} ); next if $patron->category->exclude_from_local_holds_priority; my $local_hold_match; @@ -753,31 +749,26 @@ sub MapItemsToHoldRequests { next if $request->{itemnumber} && $request->{itemnumber} != $item->{itemnumber}; - my $local_holds_priority_item_branchcode = - $item->{$LocalHoldsPriorityItemControl}; + my $local_holds_priority_item_branchcode = $item->{$LocalHoldsPriorityItemControl}; my $local_holds_priority_patron_branchcode = - ( $LocalHoldsPriorityPatronControl eq 'PickupLibrary' ) - ? $request->{branchcode} - : ( $LocalHoldsPriorityPatronControl eq 'HomeLibrary' ) - ? $request->{borrowerbranch} - : undef; + ( $LocalHoldsPriorityPatronControl eq 'PickupLibrary' ) ? $request->{branchcode} + : ( $LocalHoldsPriorityPatronControl eq 'HomeLibrary' ) ? $request->{borrowerbranch} + : undef; - $local_hold_match = - $local_holds_priority_item_branchcode eq - $local_holds_priority_patron_branchcode; + $local_hold_match = $local_holds_priority_item_branchcode eq $local_holds_priority_patron_branchcode; if ($local_hold_match) { - if ( exists $items_by_itemnumber{ $item->{itemnumber} } + if ( exists $items_by_itemnumber{ $item->{itemnumber} } and not exists $allocated_items{ $item->{itemnumber} } - and not $request->{allocated}) + and not $request->{allocated} ) { $item_map{ $item->{itemnumber} } = { borrowernumber => $request->{borrowernumber}, biblionumber => $request->{biblionumber}, holdingbranch => $item->{holdingbranch}, pickup_branch => $request->{branchcode} - || $request->{borrowerbranch}, + || $request->{borrowerbranch}, reserve_id => $request->{reserve_id}, item_level => $request->{item_level_hold}, reservedate => $request->{reservedate}, @@ -801,7 +792,8 @@ sub MapItemsToHoldRequests { next if $request->{allocated}; # is this an item-level request? - if (defined($request->{itemnumber})) { + if ( defined( $request->{itemnumber} ) ) { + # fill it if possible; if not skip it if ( exists $items_by_itemnumber{ $request->{itemnumber} } and not exists $allocated_items{ $request->{itemnumber} } @@ -822,6 +814,7 @@ sub MapItemsToHoldRequests { $num_items_remaining--; } } else { + # it's title-level request that will take up one item $num_items_remaining--; } @@ -845,17 +838,17 @@ sub MapItemsToHoldRequests { next unless $item->{holdallowed} ne 'not_allowed'; push @{ $items_by_branch{ $item->{holdingbranch} } }, $item - unless exists $allocated_items{ $item->{itemnumber} }; + unless exists $allocated_items{ $item->{itemnumber} }; } return \%item_map unless keys %items_by_branch; # now handle the title-level requests - $num_items_remaining = scalar(@$available_items) - scalar(keys %allocated_items); + $num_items_remaining = scalar(@$available_items) - scalar( keys %allocated_items ); my $pull_branches; foreach my $request (@$hold_requests) { last if $num_items_remaining == 0; next if $request->{allocated}; - next if defined($request->{itemnumber}); # already handled these + next if defined( $request->{itemnumber} ); # already handled these # HoldsQueuePrioritizeBranch check # ******************************** @@ -880,20 +873,20 @@ sub MapItemsToHoldRequests { last; } } + # End HoldsQueuePrioritizeBranch check # ******************************** - # Not found yet, fall back to basics unless ($itemnumber) { if ($branches_to_use) { $pull_branches = $branches_to_use; } else { - $pull_branches = [keys %items_by_branch]; + $pull_branches = [ keys %items_by_branch ]; } $holdingbranch ||= $pull_branches->[0]; # We set this as the first from the list of pull branches - # unless we set it above to the pickupbranch or the least cost branch - # FIXME: The intention is to follow StaticHoldsQueueWeight, but we don't check that pref + # unless we set it above to the pickupbranch or the least cost branch + # FIXME: The intention is to follow StaticHoldsQueueWeight, but we don't check that pref # Try picking items where the home and pickup branch match first foreach my $branch (@$pull_branches) { @@ -913,24 +906,24 @@ sub MapItemsToHoldRequests { } # Now try items from the least cost branch based on the transport cost matrix or StaticHoldsQueueWeight - unless ( $itemnumber || !$holdingbranch) { + unless ( $itemnumber || !$holdingbranch ) { foreach my $current_item ( @{ $items_by_branch{$holdingbranch} } ) { next unless _can_item_fill_request( $current_item, $request, $libraries ); $itemnumber = $current_item->{itemnumber}; - last; # quit this loop as soon as we have a suitable item + last; # quit this loop as soon as we have a suitable item } } # Now try for items for any item that can fill this hold - unless ( $itemnumber ) { + unless ($itemnumber) { foreach my $branch (@$pull_branches) { my $holding_branch_items = $items_by_branch{$branch} - or next; + or next; foreach my $item (@$holding_branch_items) { - if( _can_item_fill_request( $item, $request, $libraries ) ){ - $itemnumber = $item->{itemnumber}; + if ( _can_item_fill_request( $item, $request, $libraries ) ) { + $itemnumber = $item->{itemnumber}; $holdingbranch = $branch; last; } @@ -942,19 +935,19 @@ sub MapItemsToHoldRequests { if ($itemnumber) { my $holding_branch_items = $items_by_branch{$holdingbranch} - or die "Have $itemnumber, $holdingbranch, but no items!"; + or die "Have $itemnumber, $holdingbranch, but no items!"; @$holding_branch_items = grep { $_->{itemnumber} != $itemnumber } @$holding_branch_items; delete $items_by_branch{$holdingbranch} unless @$holding_branch_items; $item_map{$itemnumber} = { borrowernumber => $request->{borrowernumber}, - biblionumber => $request->{biblionumber}, - holdingbranch => $holdingbranch, - pickup_branch => $pickup_branch, - reserve_id => $request->{reserve_id}, - item_level => $request->{item_level_hold}, - reservedate => $request->{reservedate}, - reservenotes => $request->{reservenotes}, + biblionumber => $request->{biblionumber}, + holdingbranch => $holdingbranch, + pickup_branch => $pickup_branch, + reserve_id => $request->{reserve_id}, + item_level => $request->{item_level_hold}, + reservedate => $request->{reservedate}, + reservenotes => $request->{reservenotes}, }; $num_items_remaining--; } @@ -962,7 +955,6 @@ sub MapItemsToHoldRequests { return \%item_map; } - =head2 _can_item_fill_request my $bool = _can_item_fill_request( $item, $request, $libraries ); @@ -996,8 +988,6 @@ sub _can_item_fill_request { return 1; } - - =head2 CreatePickListFromItemMap =cut @@ -1007,39 +997,41 @@ sub CreatePicklistFromItemMap { my $dbh = C4::Context->dbh; - my $sth_load=$dbh->prepare(" + my $sth_load = $dbh->prepare( " INSERT INTO tmp_holdsqueue (biblionumber,itemnumber,barcode,surname,firstname,phone,borrowernumber, cardnumber,reservedate,title, itemcallnumber, holdingbranch,pickbranch,notes, item_level_request) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) - "); + " ); - foreach my $itemnumber (sort keys %$item_map) { - my $mapped_item = $item_map->{$itemnumber}; - my $biblionumber = $mapped_item->{biblionumber}; + foreach my $itemnumber ( sort keys %$item_map ) { + my $mapped_item = $item_map->{$itemnumber}; + my $biblionumber = $mapped_item->{biblionumber}; my $borrowernumber = $mapped_item->{borrowernumber}; - my $pickbranch = $mapped_item->{pickup_branch}; - my $holdingbranch = $mapped_item->{holdingbranch}; - my $reservedate = $mapped_item->{reservedate}; - my $reservenotes = $mapped_item->{reservenotes}; - my $item_level = $mapped_item->{item_level}; + my $pickbranch = $mapped_item->{pickup_branch}; + my $holdingbranch = $mapped_item->{holdingbranch}; + my $reservedate = $mapped_item->{reservedate}; + my $reservenotes = $mapped_item->{reservenotes}; + my $item_level = $mapped_item->{item_level}; - my $item = Koha::Items->find($itemnumber); - my $barcode = $item->barcode; + my $item = Koha::Items->find($itemnumber); + my $barcode = $item->barcode; my $itemcallnumber = $item->itemcallnumber; - my $patron = Koha::Patrons->find( $borrowernumber ); + my $patron = Koha::Patrons->find($borrowernumber); my $cardnumber = $patron->cardnumber; - my $surname = $patron->surname; - my $firstname = $patron->firstname; - my $phone = $patron->phone; + my $surname = $patron->surname; + my $firstname = $patron->firstname; + my $phone = $patron->phone; - my $biblio = Koha::Biblios->find( $biblionumber ); - my $title = $biblio->title; + my $biblio = Koha::Biblios->find($biblionumber); + my $title = $biblio->title; - $sth_load->execute($biblionumber, $itemnumber, $barcode, $surname, $firstname, $phone, $borrowernumber, - $cardnumber, $reservedate, $title, $itemcallnumber, - $holdingbranch, $pickbranch, $reservenotes, $item_level); + $sth_load->execute( + $biblionumber, $itemnumber, $barcode, $surname, $firstname, $phone, $borrowernumber, + $cardnumber, $reservedate, $title, $itemcallnumber, + $holdingbranch, $pickbranch, $reservenotes, $item_level + ); } } @@ -1086,26 +1078,21 @@ sub load_branches_to_pull_from { my @branches_to_use; - unless ( $use_transport_cost_matrix ) { + unless ($use_transport_cost_matrix) { my $static_branch_list = C4::Context->preference("StaticHoldsQueueWeight"); @branches_to_use = map { _trim($_) } split( /,/, $static_branch_list ) - if $static_branch_list; + if $static_branch_list; } - @branches_to_use = - Koha::Database->new()->schema()->resultset('Branch') - ->get_column('branchcode')->all() - unless (@branches_to_use); + @branches_to_use = Koha::Database->new()->schema()->resultset('Branch')->get_column('branchcode')->all() + unless (@branches_to_use); @branches_to_use = shuffle(@branches_to_use) - if C4::Context->preference("RandomizeHoldsQueueWeight"); + if C4::Context->preference("RandomizeHoldsQueueWeight"); my $today = dt_from_string(); if ( C4::Context->preference('HoldsQueueSkipClosed') ) { - @branches_to_use = grep { - !Koha::Calendar->new( branchcode => $_ ) - ->is_holiday( $today ) - } @branches_to_use; + @branches_to_use = grep { !Koha::Calendar->new( branchcode => $_ )->is_holiday($today) } @branches_to_use; } return \@branches_to_use; @@ -1114,25 +1101,25 @@ sub load_branches_to_pull_from { sub least_cost_branch { #$from - arrayref - my ($to, $from, $transport_cost_matrix) = @_; + my ( $to, $from, $transport_cost_matrix ) = @_; # Nothing really spectacular: supply to branch, a list of potential from branches # and find the minimum from - to value from the transport_cost_matrix - return $from->[0] if ( @$from == 1 && $transport_cost_matrix->{$to}{$from->[0]}->{disable_transfer} != 1 ); + return $from->[0] if ( @$from == 1 && $transport_cost_matrix->{$to}{ $from->[0] }->{disable_transfer} != 1 ); # If the pickup library is in the list of libraries to pull from, # return that library right away, it is obviously the least costly return ($to) if any { $_ eq $to } @$from; - my ($least_cost, @branch); + my ( $least_cost, @branch ); foreach (@$from) { my $cell = $transport_cost_matrix->{$to}{$_}; next if $cell->{disable_transfer}; my $cost = $cell->{cost}; - next unless defined $cost; # XXX should this be reported? + next unless defined $cost; # XXX should this be reported? - unless (defined $least_cost) { + unless ( defined $least_cost ) { $least_cost = $cost; push @branch, $_; next; @@ -1140,12 +1127,12 @@ sub least_cost_branch { next if $cost > $least_cost; - if ($cost == $least_cost) { + if ( $cost == $least_cost ) { push @branch, $_; next; } - @branch = ($_); + @branch = ($_); $least_cost = $cost; } @@ -1217,16 +1204,20 @@ sub update_queue_for_biblio { $dbh->do("DELETE FROM hold_fill_targets WHERE biblionumber=$biblio_id"); } - my $hold_requests = GetPendingHoldRequestsForBib({ biblionumber => $biblio_id, unallocated => $args->{unallocated} }); + my $hold_requests = + GetPendingHoldRequestsForBib( { biblionumber => $biblio_id, unallocated => $args->{unallocated} } ); $result->{requests} = scalar( @{$hold_requests} ); + # No need to check anything else if there are no holds to fill return $result unless $result->{requests}; - my $branches_to_use = $args->{branches_to_use} // load_branches_to_pull_from( C4::Context->preference('UseTransportCostMatrix') ); + my $branches_to_use = $args->{branches_to_use} + // load_branches_to_pull_from( C4::Context->preference('UseTransportCostMatrix') ); my $transport_cost_matrix; if ( !exists $args->{transport_cost_matrix} - && C4::Context->preference('UseTransportCostMatrix') ) { + && C4::Context->preference('UseTransportCostMatrix') ) + { $transport_cost_matrix = TransportCostMatrix(); } else { $transport_cost_matrix = $args->{transport_cost_matrix}; @@ -1234,7 +1225,7 @@ sub update_queue_for_biblio { my $available_items = GetItemsAvailableToFillHoldRequestsForBib( $biblio_id, $branches_to_use ); - $result->{available_items} = scalar( @{$available_items} ); + $result->{available_items} = scalar( @{$available_items} ); my $item_map = MapItemsToHoldRequests( $hold_requests, $available_items, $branches_to_use, $transport_cost_matrix ); $result->{mapped_items} = scalar( keys %{$item_map} ); diff --git a/C4/ILSDI/Services.pm b/C4/ILSDI/Services.pm index afe9f28f0c..4f80c8e6b8 100644 --- a/C4/ILSDI/Services.pm +++ b/C4/ILSDI/Services.pm @@ -21,7 +21,7 @@ use strict; use warnings; use C4::Members; -use C4::Items qw( get_hostitemnumbers_of ); +use C4::Items qw( get_hostitemnumbers_of ); use C4::Circulation qw( CanBookBeRenewed barcodedecode CanBookBeIssued AddRenewal ); use C4::Accounts; use C4::Reserves qw( CanBookBeReserved IsAvailableForItemLevelRequest CalculatePriority AddReserve CanItemBeReserved ); @@ -30,7 +30,7 @@ use C4::Auth; use CGI qw ( -utf8 ); use DateTime; use C4::Auth; -use Koha::DateUtils qw( dt_from_string ); +use Koha::DateUtils qw( dt_from_string ); use C4::AuthoritiesMarc qw( GetAuthorityXML ); use Koha::Biblios; @@ -130,7 +130,10 @@ sub GetAvailability { $out .= " " . $status . "\n"; if ($msg) { $out .= " " . $msg . "\n"; } if ($location) { $out .= " " . $location . "\n"; } - if ($itemcallnumber) { $out .= " " . $itemcallnumber. "\n"; } + + if ($itemcallnumber) { + $out .= " " . $itemcallnumber . "\n"; + } $out .= " \n"; $out .= " \n"; $out .= " \n"; @@ -138,12 +141,14 @@ sub GetAvailability { } else { my $status; my $msg; - my $items = Koha::Items->search({ biblionumber => $id }); - if ($items->count) { + my $items = Koha::Items->search( { biblionumber => $id } ); + if ( $items->count ) { + # Open XML $out .= " \n"; - $out .= " \n"; + $out .= " \n"; $out .= " \n"; + # We loop over the items to clean them while ( my $item = $items->next ) { my $itemnumber = $item->itemnumber; @@ -154,10 +159,14 @@ sub GetAvailability { $out .= " " . $status . "\n"; if ($msg) { $out .= " " . $msg . "\n"; } if ($location) { $out .= " " . $location . "\n"; } - if ($itemcallnumber) { $out .= " " . $itemcallnumber. "\n"; } + + if ($itemcallnumber) { + $out .= " " . $itemcallnumber . "\n"; + } $out .= " \n"; $out .= " \n"; } + # Close XML $out .= " \n"; $out .= " \n"; @@ -210,8 +219,8 @@ sub GetRecords { foreach my $biblionumber ( split( / /, $cgi->param('id') ) ) { # Get the biblioitem from the biblionumber - my $biblio = Koha::Biblios->find( $biblionumber ); - unless ( $biblio ) { + my $biblio = Koha::Biblios->find($biblionumber); + unless ($biblio) { push @records, { code => "RecordNotFound" }; next; } @@ -225,10 +234,10 @@ sub GetRecords { # Get most of the needed data my $biblioitemnumber = $biblioitem->{'biblioitemnumber'}; - my $checkouts = Koha::Checkouts->search( + my $checkouts = Koha::Checkouts->search( { biblionumber => $biblionumber }, { - join => 'item', + join => 'item', '+select' => ['item.barcode'], '+as' => ['barcode'], } @@ -236,7 +245,7 @@ sub GetRecords { foreach my $checkout (@$checkouts) { delete $checkout->{'borrowernumber'}; } - my @items = $biblio->items->filter_by_visible_in_opac->as_list; + my @items = $biblio->items->filter_by_visible_in_opac->as_list; $biblioitem->{items}->{item} = []; @@ -253,15 +262,16 @@ sub GetRecords { $item{'homebranchname'} = $home_library ? $home_library->branchname : ''; $item{'holdingbranchname'} = $holding_library ? $holding_library->branchname : ''; - if ($item->location) { - my $authorised_value = Koha::AuthorisedValues->get_description_by_koha_field({frameworkcode => '', kohafield => 'items.location', authorised_value => $item->location }); + if ( $item->location ) { + my $authorised_value = Koha::AuthorisedValues->get_description_by_koha_field( + { frameworkcode => '', kohafield => 'items.location', authorised_value => $item->location } ); if ($authorised_value) { $item{location_description} = $authorised_value->{opac_description}; } } - if ($item->itype) { - my $itemtype = Koha::ItemTypes->find($item->itype); + if ( $item->itype ) { + my $itemtype = Koha::ItemTypes->find( $item->itype ); if ($itemtype) { $item{itype_description} = $itemtype->description; } @@ -270,9 +280,9 @@ sub GetRecords { my $transfer = $item->get_transfer; if ($transfer) { $item{transfer} = { - datesent => $transfer->datesent, + datesent => $transfer->datesent, frombranch => $transfer->frombranch, - tobranch => $transfer->tobranch, + tobranch => $transfer->tobranch, }; } @@ -353,20 +363,23 @@ Parameters: sub LookupPatron { my ($cgi) = @_; - my $id = $cgi->param('id'); - if(!$id) { + my $id = $cgi->param('id'); + if ( !$id ) { return { message => 'PatronNotFound' }; } my $patrons; my $passed_id_type = $cgi->param('id_type'); - if($passed_id_type) { + if ($passed_id_type) { $patrons = Koha::Patrons->search( { $passed_id_type => $id } ); } else { - foreach my $id_type ('cardnumber', 'userid', 'email', 'borrowernumber', - 'surname', 'firstname') { + foreach my $id_type ( + 'cardnumber', 'userid', 'email', 'borrowernumber', + 'surname', 'firstname' + ) + { $patrons = Koha::Patrons->search( { $id_type => $id } ); - last if($patrons->count); + last if ( $patrons->count ); } } unless ( $patrons->count ) { @@ -391,19 +404,18 @@ Parameters: =cut sub AuthenticatePatron { - my ($cgi) = @_; + my ($cgi) = @_; my $username = $cgi->param('username'); my $password = $cgi->param('password'); - my ($status, $cardnumber, $userid, $patron) = C4::Auth::checkpw( $username, $password ); + my ( $status, $cardnumber, $userid, $patron ) = C4::Auth::checkpw( $username, $password ); if ( $status == 1 ) { + # Track the login $patron->update_lastseen('connection'); return { id => $patron->borrowernumber }; - } - elsif ( $status == -2 ){ + } elsif ( $status == -2 ) { return { code => 'PasswordExpired' }; - } - else { + } else { return { code => 'PatronNotFound' }; } } @@ -437,12 +449,13 @@ sub GetPatronInfo { # Get Member details my $borrowernumber = $cgi->param('patron_id'); - my $patron = Koha::Patrons->find( $borrowernumber ); + my $patron = Koha::Patrons->find($borrowernumber); return { code => 'PatronNotFound' } unless $patron; # Cleaning the borrower hashref my $borrower = $patron->unblessed; - $borrower->{charges} = sprintf "%.02f", $patron->account->non_issues_charges; # FIXME Formatting should not be done here + $borrower->{charges} = sprintf "%.02f", + $patron->account->non_issues_charges; # FIXME Formatting should not be done here my $library = Koha::Libraries->find( $borrower->{branchcode} ); $borrower->{'branchname'} = $library ? $library->branchname : ''; delete $borrower->{'userid'}; @@ -453,10 +466,11 @@ sub GetPatronInfo { # Define contact fields my @contactfields = ( - 'email', 'emailpro', 'fax', 'mobile', 'phone', 'phonepro', - 'streetnumber', 'zipcode', 'city', 'streettype', 'B_address', 'B_city', - 'B_email', 'B_phone', 'B_zipcode', 'address', 'address2', 'altcontactaddress1', - 'altcontactaddress2', 'altcontactaddress3', 'altcontactfirstname', 'altcontactphone', 'altcontactsurname', 'altcontactzipcode' + 'email', 'emailpro', 'fax', 'mobile', 'phone', 'phonepro', + 'streetnumber', 'zipcode', 'city', 'streettype', 'B_address', 'B_city', + 'B_email', 'B_phone', 'B_zipcode', 'address', 'address2', 'altcontactaddress1', + 'altcontactaddress2', 'altcontactaddress3', 'altcontactfirstname', 'altcontactphone', 'altcontactsurname', + 'altcontactzipcode' ); # and delete them @@ -478,6 +492,7 @@ sub GetPatronInfo { while ( my $hold = $holds->next ) { my ( $item, $biblio, $biblioitem ) = ( {}, {}, {} ); + # Get additional informations if ( $hold->itemnumber ) { # item level holds $item = Koha::Items->find( $hold->itemnumber ); @@ -493,12 +508,12 @@ sub GetPatronInfo { # Add additional fields my $unblessed_hold = $hold->unblessed; - $unblessed_hold->{item} = { %$item, %$biblio, %$biblioitem }; - my $library = Koha::Libraries->find( $hold->branchcode ); + $unblessed_hold->{item} = { %$item, %$biblio, %$biblioitem }; + my $library = Koha::Libraries->find( $hold->branchcode ); my $branchname = $library ? $library->branchname : ''; $unblessed_hold->{branchname} = $branchname; - $biblio = Koha::Biblios->find( $hold->biblionumber ); # Should be $hold->get_biblio - $unblessed_hold->{title} = $biblio ? $biblio->title : ''; # Just in case, but should not be needed + $biblio = Koha::Biblios->find( $hold->biblionumber ); # Should be $hold->get_biblio + $unblessed_hold->{title} = $biblio ? $biblio->title : ''; # Just in case, but should not be needed push @{ $borrower->{holds}{hold} }, $unblessed_hold; @@ -508,22 +523,26 @@ sub GetPatronInfo { # Issues management if ( $cgi->param('show_loans') && $cgi->param('show_loans') eq "1" ) { my $per_page = $cgi->param('loans_per_page'); - my $page = $cgi->param('loans_page'); + my $page = $cgi->param('loans_page'); my $pending_checkouts = $patron->pending_checkouts; - if ($page || $per_page) { - $page ||= 1; + if ( $page || $per_page ) { + $page ||= 1; $per_page ||= 10; $borrower->{total_loans} = $pending_checkouts->count(); - $pending_checkouts = $pending_checkouts->search(undef, { - rows => $per_page, - page => $page, - }); + $pending_checkouts = $pending_checkouts->search( + undef, + { + rows => $per_page, + page => $page, + } + ); } my @checkouts; while ( my $c = $pending_checkouts->next ) { + # FIXME We should only retrieve what is needed in the template my $issue = $c->unblessed_all_relateds; delete $issue->{'more_subfields_xml'}; @@ -534,25 +553,26 @@ sub GetPatronInfo { # Is the record (next available item) on hold by another user? $issue->{'holds_on_record'} = Koha::Holds->search( { biblionumber => $issue->{'biblionumber'} } )->count; - push @checkouts, $issue + push @checkouts, $issue; } $borrower->{'loans'}->{'loan'} = \@checkouts; } my $show_attributes = $cgi->param('show_attributes'); if ( $show_attributes && $show_attributes eq "1" ) { + # FIXME Regression expected here, we do not retrieve the same field as previously # Waiting for answer on bug 14257 comment 15 $borrower->{'attributes'} = [ map { $_->type->opac_display - ? { + ? { %{ $_->unblessed }, %{ $_->type->unblessed }, - value => $_->attribute, # Backward compatibility - value_description => $_->description, # Awkward retro-compability... - } - : () + value => $_->attribute, # Backward compatibility + value_description => $_->description, # Awkward retro-compability... + } + : () } $patron->extended_attributes->search->as_list ]; } @@ -579,13 +599,13 @@ sub GetPatronStatus { # Get Member details my $borrowernumber = $cgi->param('patron_id'); - my $patron = Koha::Patrons->find( $borrowernumber ); + my $patron = Koha::Patrons->find($borrowernumber); return { code => 'PatronNotFound' } unless $patron; # Return the results return { type => $patron->categorycode, - status => 0, # TODO + status => 0, # TODO expiry => $patron->dateexpiry, }; } @@ -609,23 +629,24 @@ sub GetServices { # Get the member, or return an error code if not found my $borrowernumber = $cgi->param('patron_id'); - my $patron = Koha::Patrons->find( $borrowernumber ); + my $patron = Koha::Patrons->find($borrowernumber); return { code => 'PatronNotFound' } unless $patron; my $borrower = $patron->unblessed; + # Get the item, or return an error code if not found my $itemnumber = $cgi->param('item_id'); - my $item = Koha::Items->find($itemnumber); + my $item = Koha::Items->find($itemnumber); return { code => 'RecordNotFound' } unless $item; my @availablefor; # Reserve level management - my $biblionumber = $item->biblionumber; + my $biblionumber = $item->biblionumber; my $canbookbereserved = CanBookBeReserved( $borrower, $biblionumber ); - if ($canbookbereserved->{status} eq 'OK') { + if ( $canbookbereserved->{status} eq 'OK' ) { push @availablefor, 'title level hold'; - my $canitembereserved = IsAvailableForItemLevelRequest($item, $patron); + my $canitembereserved = IsAvailableForItemLevelRequest( $item, $patron ); if ($canitembereserved) { push @availablefor, 'item level hold'; } @@ -634,7 +655,7 @@ sub GetServices { # Reserve cancellation management my $holds = $patron->holds; my @reserveditems; - while ( my $hold = $holds->next ) { # FIXME This could be improved + while ( my $hold = $holds->next ) { # FIXME This could be improved push @reserveditems, $hold->itemnumber; } if ( grep { $itemnumber eq $_ } @reserveditems ) { @@ -642,7 +663,7 @@ sub GetServices { } # Renewal management - my @renewal = CanBookBeRenewed( $patron, $item->checkout ); # TODO: Error if issue not found? + my @renewal = CanBookBeRenewed( $patron, $item->checkout ); # TODO: Error if issue not found? if ( $renewal[0] ) { push @availablefor, 'loan renewal'; } @@ -682,17 +703,17 @@ sub RenewLoan { # Get borrower infos or return an error code my $borrowernumber = $cgi->param('patron_id'); - my $patron = Koha::Patrons->find( $borrowernumber ); + my $patron = Koha::Patrons->find($borrowernumber); return { code => 'PatronNotFound' } unless $patron; # Get the item, or return an error code - my $itemnumber = $cgi->param('item_id'); # TODO: Refactor and send issue_id instead? - my $item = Koha::Items->find($itemnumber); + my $itemnumber = $cgi->param('item_id'); # TODO: Refactor and send issue_id instead? + my $item = Koha::Items->find($itemnumber); return { code => 'RecordNotFound' } unless $item; my $issue = $item->checkout; - return unless $issue; # FIXME should be handled + return unless $issue; # FIXME should be handled # Add renewal if possible my @renewal = CanBookBeRenewed( $patron, $issue ); @@ -709,10 +730,11 @@ sub RenewLoan { # Hashref building my $out; $out->{'renewals'} = $issue->renewals_count; + # FIXME Unusual date formatting - $out->{date_due} = dt_from_string($issue->date_due)->strftime('%Y-%m-%d %H:%M'); - $out->{'success'} = $renewal[0]; - $out->{'error'} = $renewal[1]; + $out->{date_due} = dt_from_string( $issue->date_due )->strftime('%Y-%m-%d %H:%M'); + $out->{'success'} = $renewal[0]; + $out->{'error'} = $renewal[1]; return $out; } @@ -743,10 +765,9 @@ sub HoldTitle { # Get the borrower or return an error code my $borrowernumber = $cgi->param('patron_id'); - my $patron = Koha::Patrons->find( $borrowernumber ); + my $patron = Koha::Patrons->find($borrowernumber); return { code => 'PatronNotFound' } unless $patron; - # If borrower is restricted return an error code return { code => 'PatronRestricted' } if $patron->is_debarred; @@ -756,16 +777,17 @@ sub HoldTitle { # Get the biblio record, or return an error code my $biblionumber = $cgi->param('bib_id'); - my $biblio = Koha::Biblios->find( $biblionumber ); + my $biblio = Koha::Biblios->find($biblionumber); return { code => 'RecordNotFound' } unless $biblio; my @hostitems = get_hostitemnumbers_of($biblionumber); my @itemnumbers; - if (@hostitems){ - push(@itemnumbers, @hostitems); + if (@hostitems) { + push( @itemnumbers, @hostitems ); } - my $items = Koha::Items->search({ -or => { biblionumber => $biblionumber, itemnumber => { in => \@itemnumbers } } }); + my $items = + Koha::Items->search( { -or => { biblionumber => $biblionumber, itemnumber => { in => \@itemnumbers } } } ); unless ( $items->count ) { return { code => 'NoItems' }; @@ -783,13 +805,13 @@ sub HoldTitle { if ( $cgi->param('pickup_location') ) { $branch = $cgi->param('pickup_location'); return { code => 'LocationNotFound' } unless Koha::Libraries->find($branch); - } else { # if the request provide no branch, use the borrower's branch + } else { # if the request provide no branch, use the borrower's branch $branch = $patron->branchcode; } my $destination = Koha::Libraries->find($branch); return { code => 'libraryNotPickupLocation' } unless $destination->pickup_location; - return { code => 'cannotBeTransferred' } unless $biblio->can_be_transferred({ to => $destination }); + return { code => 'cannotBeTransferred' } unless $biblio->can_be_transferred( { to => $destination } ); my $resdate = $cgi->param('start_date'); my $expdate = $cgi->param('expiry_date'); @@ -798,7 +820,7 @@ sub HoldTitle { # $branch, $borrowernumber, $biblionumber, # $constraint, $bibitems, $priority, $resdate, $expdate, $notes, # $title, $checkitem, $found - my $priority= C4::Reserves::CalculatePriority( $biblionumber ); + my $priority = C4::Reserves::CalculatePriority($biblionumber); AddReserve( { branchcode => $branch, @@ -813,8 +835,8 @@ sub HoldTitle { # Hashref building my $out; - $out->{'title'} = $title; - my $library = Koha::Libraries->find( $branch ); + $out->{'title'} = $title; + my $library = Koha::Libraries->find($branch); $out->{'pickup_location'} = $library ? $library->branchname : ''; # TODO $out->{'date_available'} = ''; @@ -849,7 +871,7 @@ sub HoldItem { # Get the borrower or return an error code my $borrowernumber = $cgi->param('patron_id'); - my $patron = Koha::Patrons->find( $borrowernumber ); + my $patron = Koha::Patrons->find($borrowernumber); return { code => 'PatronNotFound' } unless $patron; # If borrower is restricted return an error code @@ -861,14 +883,14 @@ sub HoldItem { # Get the biblio or return an error code my $biblionumber = $cgi->param('bib_id'); - my $biblio = Koha::Biblios->find( $biblionumber ); + my $biblio = Koha::Biblios->find($biblionumber); return { code => 'RecordNotFound' } unless $biblio; my $title = $biblio ? $biblio->title : ''; # Get the item or return an error code my $itemnumber = $cgi->param('item_id'); - my $item = Koha::Items->find($itemnumber); + my $item = Koha::Items->find($itemnumber); return { code => 'RecordNotFound' } unless $item; # If the biblio does not match the item, return an error code @@ -879,7 +901,7 @@ sub HoldItem { if ( $cgi->param('pickup_location') ) { $branch = $cgi->param('pickup_location'); return { code => 'LocationNotFound' } unless Koha::Libraries->find($branch); - } else { # if the request provide no branch, use the borrower's branch + } else { # if the request provide no branch, use the borrower's branch $branch = $patron->branchcode; } @@ -907,7 +929,7 @@ sub HoldItem { # Hashref building my $out; - my $library = Koha::Libraries->find( $branch ); + my $library = Koha::Libraries->find($branch); $out->{'pickup_location'} = $library ? $library->branchname : ''; # TODO $out->{'date_available'} = ''; @@ -933,12 +955,12 @@ sub CancelHold { # Get the borrower or return an error code my $borrowernumber = $cgi->param('patron_id'); - my $patron = Koha::Patrons->find( $borrowernumber ); + my $patron = Koha::Patrons->find($borrowernumber); return { code => 'PatronNotFound' } unless $patron; # Get the reserve or return an error code my $reserve_id = $cgi->param('item_id'); - my $hold = Koha::Holds->find( $reserve_id ); + my $hold = Koha::Holds->find($reserve_id); return { code => 'RecordNotFound' } unless $hold; # Check if reserve belongs to the borrower and if it is in a state which allows cancellation @@ -962,13 +984,13 @@ sub _availability { my ($itemnumber) = @_; my $item = Koha::Items->find($itemnumber); - unless ( $item ) { + unless ($item) { return ( undef, __('unknown'), __('Error: could not retrieve availability for this ID'), undef ); } - my $biblionumber = $item->biblioitemnumber; - my $library = Koha::Libraries->find( $item->holdingbranch ); - my $location = $library ? $library->branchname : ''; + my $biblionumber = $item->biblioitemnumber; + my $library = Koha::Libraries->find( $item->holdingbranch ); + my $location = $library ? $library->branchname : ''; my $itemcallnumber = $item->itemcallnumber; if ( $item->effective_not_for_loan_status ) { diff --git a/C4/ImportBatch.pm b/C4/ImportBatch.pm index 5aebaafacf..b476da0e51 100644 --- a/C4/ImportBatch.pm +++ b/C4/ImportBatch.pm @@ -21,7 +21,7 @@ use strict; use warnings; use C4::Context; -use C4::Koha qw( GetNormalizedISBN ); +use C4::Koha qw( GetNormalizedISBN ); use C4::Biblio qw( AddBiblio DelBiblio @@ -30,9 +30,10 @@ use C4::Biblio qw( ModBiblio TransformMarcToKoha ); -use C4::Items qw( AddItemFromMarc ModItemFromMarc ); +use C4::Items qw( AddItemFromMarc ModItemFromMarc ); use C4::Charset qw( MarcToUTF8Record SetUTF8Flag StripNonXmlChars ); -use C4::AuthoritiesMarc qw( AddAuthority GuessAuthTypeCode GetAuthorityXML ModAuthority DelAuthority GetAuthorizedHeading ); +use C4::AuthoritiesMarc + qw( AddAuthority GuessAuthTypeCode GetAuthorityXML ModAuthority DelAuthority GetAuthorizedHeading ); use C4::MarcModificationTemplates qw( ModifyRecordWithTemplate ); use Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue; use Koha::Items; @@ -41,57 +42,58 @@ use Koha::SearchEngine::Indexer; use Koha::Plugins::Handler; use Koha::Logger; -our (@ISA, @EXPORT_OK); +our ( @ISA, @EXPORT_OK ); + BEGIN { require Exporter; @ISA = qw(Exporter); @EXPORT_OK = qw( - GetZ3950BatchId - GetWebserviceBatchId - GetImportRecordMarc - AddImportBatch - GetImportBatch - AddAuthToBatch - AddBiblioToBatch - AddItemsToImportBiblio - ModAuthorityInBatch + GetZ3950BatchId + GetWebserviceBatchId + GetImportRecordMarc + AddImportBatch + GetImportBatch + AddAuthToBatch + AddBiblioToBatch + AddItemsToImportBiblio + ModAuthorityInBatch - BatchStageMarcRecords - BatchFindDuplicates - BatchCommitRecords - BatchRevertRecords - CleanBatch - DeleteBatch + BatchStageMarcRecords + BatchFindDuplicates + BatchCommitRecords + BatchRevertRecords + CleanBatch + DeleteBatch - GetAllImportBatches - GetStagedWebserviceBatches - GetImportBatchRangeDesc - GetNumberOfNonZ3950ImportBatches - GetImportBiblios - GetImportRecordsRange - GetItemNumbersFromImportBatch + GetAllImportBatches + GetStagedWebserviceBatches + GetImportBatchRangeDesc + GetNumberOfNonZ3950ImportBatches + GetImportBiblios + GetImportRecordsRange + GetItemNumbersFromImportBatch - GetImportBatchStatus - SetImportBatchStatus - GetImportBatchOverlayAction - SetImportBatchOverlayAction - GetImportBatchNoMatchAction - SetImportBatchNoMatchAction - GetImportBatchItemAction - SetImportBatchItemAction - GetImportBatchMatcher - SetImportBatchMatcher - GetImportRecordOverlayStatus - SetImportRecordOverlayStatus - GetImportRecordStatus - SetImportRecordStatus - SetMatchedBiblionumber - GetImportRecordMatches - SetImportRecordMatches + GetImportBatchStatus + SetImportBatchStatus + GetImportBatchOverlayAction + SetImportBatchOverlayAction + GetImportBatchNoMatchAction + SetImportBatchNoMatchAction + GetImportBatchItemAction + SetImportBatchItemAction + GetImportBatchMatcher + SetImportBatchMatcher + GetImportRecordOverlayStatus + SetImportRecordOverlayStatus + GetImportRecordStatus + SetImportRecordStatus + SetMatchedBiblionumber + GetImportRecordMatches + SetImportRecordMatches - RecordsFromMARCXMLFile - RecordsFromISO2709File - RecordsFromMarcPlugin + RecordsFromMARCXMLFile + RecordsFromISO2709File + RecordsFromMarcPlugin ); } @@ -119,24 +121,28 @@ sub GetZ3950BatchId { my ($z3950server) = @_; my $dbh = C4::Context->dbh; - my $sth = $dbh->prepare("SELECT import_batch_id FROM import_batches + my $sth = $dbh->prepare( + "SELECT import_batch_id FROM import_batches WHERE batch_type = 'z3950' - AND file_name = ?"); + AND file_name = ?" + ); $sth->execute($z3950server); my $rowref = $sth->fetchrow_arrayref(); $sth->finish(); - if (defined $rowref) { + if ( defined $rowref ) { return $rowref->[0]; } else { - my $batch_id = AddImportBatch( { + my $batch_id = AddImportBatch( + { overlay_action => 'create_new', - import_status => 'staged', - batch_type => 'z3950', - file_name => $z3950server, - } ); + import_status => 'staged', + batch_type => 'z3950', + file_name => $z3950server, + } + ); return $batch_id; } - + } =head2 GetWebserviceBatchId @@ -153,6 +159,7 @@ SELECT import_batch_id FROM import_batches WHERE batch_type = 'webservice' AND import_status = 'staged' EOQ + sub GetWebserviceBatchId { my ($params) = @_; @@ -160,15 +167,15 @@ sub GetWebserviceBatchId { my $sql = $WEBSERVICE_BASE_QRY; my @args; foreach my $field (qw(matcher_id overlay_action nomatch_action item_action)) { - if (my $val = $params->{$field}) { + if ( my $val = $params->{$field} ) { $sql .= " AND $field = ?"; push @args, $val; } } - my $id = $dbh->selectrow_array($sql, undef, @args); + my $id = $dbh->selectrow_array( $sql, undef, @args ); return $id if $id; - $params->{batch_type} = 'webservice'; + $params->{batch_type} = 'webservice'; $params->{import_status} = 'staged'; return AddImportBatch($params); } @@ -183,11 +190,13 @@ sub GetImportRecordMarc { my ($import_record_id) = @_; my $dbh = C4::Context->dbh; - my ( $marc, $encoding ) = $dbh->selectrow_array(q| + my ( $marc, $encoding ) = $dbh->selectrow_array( + q| SELECT marc, encoding FROM import_records WHERE import_record_id = ? - |, undef, $import_record_id ); + |, undef, $import_record_id + ); return $marc, $encoding; } @@ -201,20 +210,25 @@ sub GetImportRecordMarc { sub AddImportBatch { my ($params) = @_; - my (@fields, @vals); - foreach (qw( matcher_id template_id branchcode - overlay_action nomatch_action item_action - import_status batch_type file_name comments record_type )) { - if (exists $params->{$_}) { + my ( @fields, @vals ); + foreach ( + qw( matcher_id template_id branchcode + overlay_action nomatch_action item_action + import_status batch_type file_name comments record_type ) + ) + { + if ( exists $params->{$_} ) { push @fields, $_; - push @vals, $params->{$_}; + push @vals, $params->{$_}; } } my $dbh = C4::Context->dbh; - $dbh->do("INSERT INTO import_batches (".join( ',', @fields).") - VALUES (".join( ',', map '?', @fields).")", - undef, - @vals); + $dbh->do( + "INSERT INTO import_batches (" . join( ',', @fields ) . ") + VALUES (" . join( ',', map '?', @fields ) . ")", + undef, + @vals + ); return $dbh->{'mysql_insertid'}; } @@ -230,8 +244,10 @@ sub GetImportBatch { my ($batch_id) = @_; my $dbh = C4::Context->dbh; - my $sth = $dbh->prepare_cached("SELECT b.*, p.name as profile FROM import_batches b LEFT JOIN import_batch_profiles p ON p.id = b.profile_id WHERE import_batch_id = ?"); - $sth->bind_param(1, $batch_id); + my $sth = $dbh->prepare_cached( + "SELECT b.*, p.name as profile FROM import_batches b LEFT JOIN import_batch_profiles p ON p.id = b.profile_id WHERE import_batch_id = ?" + ); + $sth->bind_param( 1, $batch_id ); $sth->execute(); my $result = $sth->fetchrow_hashref; $sth->finish(); @@ -247,14 +263,17 @@ sub GetImportBatch { =cut sub AddBiblioToBatch { - my $batch_id = shift; + my $batch_id = shift; my $record_sequence = shift; - my $marc_record = shift; - my $encoding = shift; - my $update_counts = @_ ? shift : 1; + my $marc_record = shift; + my $encoding = shift; + my $update_counts = @_ ? shift : 1; - my $import_record_id = _create_import_record($batch_id, $record_sequence, $marc_record, 'biblio', $encoding, C4::Context->preference('marcflavour')); - _add_biblio_fields($import_record_id, $marc_record); + my $import_record_id = _create_import_record( + $batch_id, $record_sequence, $marc_record, 'biblio', $encoding, + C4::Context->preference('marcflavour') + ); + _add_biblio_fields( $import_record_id, $marc_record ); _update_batch_record_counts($batch_id) if $update_counts; return $import_record_id; } @@ -267,17 +286,18 @@ sub AddBiblioToBatch { =cut sub AddAuthToBatch { - my $batch_id = shift; + my $batch_id = shift; my $record_sequence = shift; - my $marc_record = shift; - my $encoding = shift; - my $update_counts = @_ ? shift : 1; - my $marc_type = shift || C4::Context->preference('marcflavour'); + my $marc_record = shift; + my $encoding = shift; + my $update_counts = @_ ? shift : 1; + my $marc_type = shift || C4::Context->preference('marcflavour'); $marc_type = 'UNIMARCAUTH' if $marc_type eq 'UNIMARC'; - my $import_record_id = _create_import_record($batch_id, $record_sequence, $marc_record, 'auth', $encoding, $marc_type); - _add_auth_fields($import_record_id, $marc_record); + my $import_record_id = + _create_import_record( $batch_id, $record_sequence, $marc_record, 'auth', $encoding, $marc_type ); + _add_auth_fields( $import_record_id, $marc_record ); _update_batch_record_counts($batch_id) if $update_counts; return $import_record_id; } @@ -297,59 +317,61 @@ sub AddAuthToBatch { =cut sub BatchStageMarcRecords { - my $record_type = shift; - my $encoding = shift; - my $marc_records = shift; - my $file_name = shift; + my $record_type = shift; + my $encoding = shift; + my $marc_records = shift; + my $file_name = shift; my $marc_modification_template = shift; - my $comments = shift; - my $branch_code = shift; - my $parse_items = shift; - my $leave_as_staging = shift; + my $comments = shift; + my $branch_code = shift; + my $parse_items = shift; + my $leave_as_staging = shift; - # optional callback to monitor status + # optional callback to monitor status # of job my $progress_interval = 0; my $progress_callback = undef; - if ($#_ == 1) { + if ( $#_ == 1 ) { $progress_interval = shift; $progress_callback = shift; $progress_interval = 0 unless $progress_interval =~ /^\d+$/ and $progress_interval > 0; $progress_interval = 0 unless 'CODE' eq ref $progress_callback; - } - - my $batch_id = AddImportBatch( { - overlay_action => 'create_new', - import_status => 'staging', - batch_type => 'batch', - file_name => $file_name, - comments => $comments, - record_type => $record_type, - } ); - if ($parse_items) { - SetImportBatchItemAction($batch_id, 'always_add'); - } else { - SetImportBatchItemAction($batch_id, 'ignore'); } + my $batch_id = AddImportBatch( + { + overlay_action => 'create_new', + import_status => 'staging', + batch_type => 'batch', + file_name => $file_name, + comments => $comments, + record_type => $record_type, + } + ); + if ($parse_items) { + SetImportBatchItemAction( $batch_id, 'always_add' ); + } else { + SetImportBatchItemAction( $batch_id, 'ignore' ); + } my $marc_type = C4::Context->preference('marcflavour'); - $marc_type .= 'AUTH' if ($marc_type eq 'UNIMARC' && $record_type eq 'auth'); + $marc_type .= 'AUTH' if ( $marc_type eq 'UNIMARC' && $record_type eq 'auth' ); my @invalid_records = (); - my $num_valid = 0; - my $num_items = 0; + my $num_valid = 0; + my $num_items = 0; + # FIXME - for now, we're dealing only with bibs my $rec_num = 0; foreach my $marc_record (@$marc_records) { $rec_num++; - if ($progress_interval and (0 == ($rec_num % $progress_interval))) { + if ( $progress_interval and ( 0 == ( $rec_num % $progress_interval ) ) ) { &$progress_callback($rec_num); } - ModifyRecordWithTemplate( $marc_modification_template, $marc_record ) if ( $marc_modification_template ); + ModifyRecordWithTemplate( $marc_modification_template, $marc_record ) if ($marc_modification_template); my $import_record_id; - if (scalar($marc_record->fields()) == 0) { + if ( scalar( $marc_record->fields() ) == 0 ) { push @invalid_records, $marc_record; } else { @@ -357,27 +379,28 @@ sub BatchStageMarcRecords { SetUTF8Flag($marc_record); $num_valid++; - if ($record_type eq 'biblio') { - $import_record_id = AddBiblioToBatch($batch_id, $rec_num, $marc_record, $encoding, 0); + if ( $record_type eq 'biblio' ) { + $import_record_id = AddBiblioToBatch( $batch_id, $rec_num, $marc_record, $encoding, 0 ); if ($parse_items) { - my @import_items_ids = AddItemsToImportBiblio($batch_id, $import_record_id, $marc_record, 0); + my @import_items_ids = AddItemsToImportBiblio( $batch_id, $import_record_id, $marc_record, 0 ); $num_items += scalar(@import_items_ids); } - } elsif ($record_type eq 'auth') { - $import_record_id = AddAuthToBatch($batch_id, $rec_num, $marc_record, $encoding, 0, $marc_type); + } elsif ( $record_type eq 'auth' ) { + $import_record_id = AddAuthToBatch( $batch_id, $rec_num, $marc_record, $encoding, 0, $marc_type ); } } } unless ($leave_as_staging) { - SetImportBatchStatus($batch_id, 'staged'); + SetImportBatchStatus( $batch_id, 'staged' ); } + # FIXME branch_code, number of bibs, number of items _update_batch_record_counts($batch_id); - if ($progress_interval){ + if ($progress_interval) { &$progress_callback($rec_num); } - return ($batch_id, $num_valid, $num_items, @invalid_records); + return ( $batch_id, $num_valid, $num_items, @invalid_records ); } =head2 AddItemsToImportBiblio @@ -388,31 +411,33 @@ sub BatchStageMarcRecords { =cut sub AddItemsToImportBiblio { - my $batch_id = shift; + my $batch_id = shift; my $import_record_id = shift; - my $marc_record = shift; - my $update_counts = @_ ? shift : 0; + my $marc_record = shift; + my $update_counts = @_ ? shift : 0; my @import_items_ids = (); - - my $dbh = C4::Context->dbh; - my ($item_tag,$item_subfield) = &GetMarcFromKohaField( "items.itemnumber" ); - foreach my $item_field ($marc_record->field($item_tag)) { + + my $dbh = C4::Context->dbh; + my ( $item_tag, $item_subfield ) = &GetMarcFromKohaField("items.itemnumber"); + foreach my $item_field ( $marc_record->field($item_tag) ) { my $item_marc = MARC::Record->new(); - $item_marc->leader("00000 a "); # must set Leader/09 to 'a' + $item_marc->leader("00000 a "); # must set Leader/09 to 'a' $item_marc->append_fields($item_field); $marc_record->delete_field($item_field); - my $sth = $dbh->prepare_cached("INSERT INTO import_items (import_record_id, status, marcxml) - VALUES (?, ?, ?)"); - $sth->bind_param(1, $import_record_id); - $sth->bind_param(2, 'staged'); - $sth->bind_param(3, $item_marc->as_xml("USMARC")); + my $sth = $dbh->prepare_cached( + "INSERT INTO import_items (import_record_id, status, marcxml) + VALUES (?, ?, ?)" + ); + $sth->bind_param( 1, $import_record_id ); + $sth->bind_param( 2, 'staged' ); + $sth->bind_param( 3, $item_marc->as_xml("USMARC") ); $sth->execute(); push @import_items_ids, $dbh->{'mysql_insertid'}; $sth->finish(); } - if ($#import_items_ids > -1) { + if ( $#import_items_ids > -1 ) { _update_batch_record_counts($batch_id) if $update_counts; } return @import_items_ids; @@ -439,15 +464,15 @@ singular argument. =cut sub BatchFindDuplicates { - my $batch_id = shift; - my $matcher = shift; + my $batch_id = shift; + my $matcher = shift; my $max_matches = @_ ? shift : 10; - # optional callback to monitor status + # optional callback to monitor status # of job my $progress_interval = 0; my $progress_callback = undef; - if ($#_ == 1) { + if ( $#_ == 1 ) { $progress_interval = shift; $progress_callback = shift; $progress_interval = 0 unless $progress_interval =~ /^\d+$/ and $progress_interval > 0; @@ -456,33 +481,35 @@ sub BatchFindDuplicates { my $dbh = C4::Context->dbh; - my $sth = $dbh->prepare("SELECT import_record_id, record_type, marc + my $sth = $dbh->prepare( + "SELECT import_record_id, record_type, marc FROM import_records - WHERE import_batch_id = ?"); + WHERE import_batch_id = ?" + ); $sth->execute($batch_id); my $num_with_matches = 0; - my $rec_num = 0; - while (my $rowref = $sth->fetchrow_hashref) { + my $rec_num = 0; + while ( my $rowref = $sth->fetchrow_hashref ) { $rec_num++; - if ($progress_interval and (0 == ($rec_num % $progress_interval))) { + if ( $progress_interval and ( 0 == ( $rec_num % $progress_interval ) ) ) { &$progress_callback($rec_num); } - my $marc_record = MARC::Record->new_from_usmarc($rowref->{'marc'}); - my @matches = (); - if (defined $matcher) { - @matches = $matcher->get_matches($marc_record, $max_matches); + my $marc_record = MARC::Record->new_from_usmarc( $rowref->{'marc'} ); + my @matches = (); + if ( defined $matcher ) { + @matches = $matcher->get_matches( $marc_record, $max_matches ); } - if (scalar(@matches) > 0) { + if ( scalar(@matches) > 0 ) { $num_with_matches++; - SetImportRecordMatches($rowref->{'import_record_id'}, @matches); - SetImportRecordOverlayStatus($rowref->{'import_record_id'}, 'auto_match'); + SetImportRecordMatches( $rowref->{'import_record_id'}, @matches ); + SetImportRecordOverlayStatus( $rowref->{'import_record_id'}, 'auto_match' ); } else { - SetImportRecordMatches($rowref->{'import_record_id'}, ()); - SetImportRecordOverlayStatus($rowref->{'import_record_id'}, 'no_match'); + SetImportRecordMatches( $rowref->{'import_record_id'}, () ); + SetImportRecordOverlayStatus( $rowref->{'import_record_id'}, 'no_match' ); } } - if ($progress_interval){ + if ($progress_interval) { &$progress_callback($rec_num); } @@ -506,7 +533,7 @@ sub BatchFindDuplicates { =cut sub BatchCommitRecords { - my $params = shift; + my $params = shift; my $batch_id = $params->{batch_id}; my $framework = $params->{framework}; my $overlay_framework = $params->{overlay_framework}; @@ -518,110 +545,119 @@ sub BatchCommitRecords { my $schema = Koha::Database->schema; my $record_type; - my $num_added = 0; - my $num_updated = 0; - my $num_items_added = 0; + my $num_added = 0; + my $num_updated = 0; + my $num_items_added = 0; my $num_items_replaced = 0; - my $num_items_errored = 0; - my $num_ignored = 0; + my $num_items_errored = 0; + my $num_ignored = 0; + # commit (i.e., save, all records in the batch) my $overlay_action = GetImportBatchOverlayAction($batch_id); my $nomatch_action = GetImportBatchNoMatchAction($batch_id); - my $item_action = GetImportBatchItemAction($batch_id); + my $item_action = GetImportBatchItemAction($batch_id); my $item_tag; my $item_subfield; my $dbh = C4::Context->dbh; - my $sth = $dbh->prepare("SELECT import_records.import_record_id, record_type, status, overlay_status, marc, encoding + my $sth = $dbh->prepare( + "SELECT import_records.import_record_id, record_type, status, overlay_status, marc, encoding FROM import_records LEFT JOIN import_auths ON (import_records.import_record_id=import_auths.import_record_id) LEFT JOIN import_biblios ON (import_records.import_record_id=import_biblios.import_record_id) - WHERE import_batch_id = ?"); + WHERE import_batch_id = ?" + ); $sth->execute($batch_id); my $marcflavour = C4::Context->preference('marcflavour'); - my $userenv = C4::Context->userenv; + my $userenv = C4::Context->userenv; my $logged_in_patron = Koha::Patrons->find( $userenv->{number} ); my $rec_num = 0; my @biblio_ids; my @updated_ids; - while (my $rowref = $sth->fetchrow_hashref) { + while ( my $rowref = $sth->fetchrow_hashref ) { $schema->txn_begin; $record_type = $rowref->{'record_type'}; $rec_num++; - if ($progress_interval and (0 == ($rec_num % $progress_interval))) { + if ( $progress_interval and ( 0 == ( $rec_num % $progress_interval ) ) ) { + # report progress - &$progress_callback( $rec_num ); + &$progress_callback($rec_num); } - if ($rowref->{'status'} eq 'error' or $rowref->{'status'} eq 'imported') { + if ( $rowref->{'status'} eq 'error' or $rowref->{'status'} eq 'imported' ) { $num_ignored++; next; } my $marc_type; - if ($marcflavour eq 'UNIMARC' && $record_type eq 'auth') { + if ( $marcflavour eq 'UNIMARC' && $record_type eq 'auth' ) { $marc_type = 'UNIMARCAUTH'; - } elsif ($marcflavour eq 'UNIMARC') { + } elsif ( $marcflavour eq 'UNIMARC' ) { $marc_type = 'UNIMARC'; } else { $marc_type = 'USMARC'; } - my $marc_record = MARC::Record->new_from_usmarc($rowref->{'marc'}); + my $marc_record = MARC::Record->new_from_usmarc( $rowref->{'marc'} ); + + if ( $record_type eq 'biblio' ) { - if ($record_type eq 'biblio') { # remove any item tags - rely on _batchCommitItems - ($item_tag,$item_subfield) = &GetMarcFromKohaField( "items.itemnumber" ); - foreach my $item_field ($marc_record->field($item_tag)) { + ( $item_tag, $item_subfield ) = &GetMarcFromKohaField("items.itemnumber"); + foreach my $item_field ( $marc_record->field($item_tag) ) { $marc_record->delete_field($item_field); } - if(C4::Context->preference('autoControlNumber') eq 'biblionumber'){ + if ( C4::Context->preference('autoControlNumber') eq 'biblionumber' ) { my @control_num = $marc_record->field('001'); $marc_record->delete_fields(@control_num); } } - my ($record_result, $item_result, $record_match) = - _get_commit_action($overlay_action, $nomatch_action, $item_action, - $rowref->{'overlay_status'}, $rowref->{'import_record_id'}, $record_type); + my ( $record_result, $item_result, $record_match ) = _get_commit_action( + $overlay_action, $nomatch_action, $item_action, + $rowref->{'overlay_status'}, $rowref->{'import_record_id'}, $record_type + ); my $recordid; my $query; - if ($record_result eq 'create_new') { + if ( $record_result eq 'create_new' ) { $num_added++; - if ($record_type eq 'biblio') { + if ( $record_type eq 'biblio' ) { my $biblioitemnumber; - ($recordid, $biblioitemnumber) = AddBiblio($marc_record, $framework, { skip_record_index => 1 }); + ( $recordid, $biblioitemnumber ) = AddBiblio( $marc_record, $framework, { skip_record_index => 1 } ); push @biblio_ids, $recordid if $recordid; - $query = "UPDATE import_biblios SET matched_biblionumber = ? WHERE import_record_id = ?"; # FIXME call SetMatchedBiblionumber instead - if ($item_result eq 'create_new' || $item_result eq 'replace') { - my ($bib_items_added, $bib_items_replaced, $bib_items_errored) = _batchCommitItems($rowref->{'import_record_id'}, $recordid, $item_result, $biblioitemnumber); - $num_items_added += $bib_items_added; + $query = "UPDATE import_biblios SET matched_biblionumber = ? WHERE import_record_id = ?" + ; # FIXME call SetMatchedBiblionumber instead + if ( $item_result eq 'create_new' || $item_result eq 'replace' ) { + my ( $bib_items_added, $bib_items_replaced, $bib_items_errored ) = + _batchCommitItems( $rowref->{'import_record_id'}, $recordid, $item_result, $biblioitemnumber ); + $num_items_added += $bib_items_added; $num_items_replaced += $bib_items_replaced; - $num_items_errored += $bib_items_errored; + $num_items_errored += $bib_items_errored; } } else { - $recordid = AddAuthority($marc_record, undef, GuessAuthTypeCode($marc_record)); - $query = "UPDATE import_auths SET matched_authid = ? WHERE import_record_id = ?"; + $recordid = AddAuthority( $marc_record, undef, GuessAuthTypeCode($marc_record) ); + $query = "UPDATE import_auths SET matched_authid = ? WHERE import_record_id = ?"; } my $sth = $dbh->prepare_cached($query); - $sth->execute($recordid, $rowref->{'import_record_id'}); + $sth->execute( $recordid, $rowref->{'import_record_id'} ); $sth->finish(); - SetImportRecordStatus($rowref->{'import_record_id'}, 'imported'); - } elsif ($record_result eq 'replace') { + SetImportRecordStatus( $rowref->{'import_record_id'}, 'imported' ); + } elsif ( $record_result eq 'replace' ) { $num_updated++; $recordid = $record_match; my $oldxml; - if ($record_type eq 'biblio') { - my $oldbiblio = Koha::Biblios->find( $recordid ); + if ( $record_type eq 'biblio' ) { + my $oldbiblio = Koha::Biblios->find($recordid); $oldxml = GetXmlBiblio($recordid); # remove item fields so that they don't get # added again if record is reverted # FIXME: GetXmlBiblio output should not contain item info any more! So the next foreach should not be needed. Does not hurt either; may remove old 952s that should not have been there anymore. - my $old_marc = MARC::Record->new_from_xml(StripNonXmlChars($oldxml), 'UTF-8', $rowref->{'encoding'}, $marc_type); - foreach my $item_field ($old_marc->field($item_tag)) { + my $old_marc = + MARC::Record->new_from_xml( StripNonXmlChars($oldxml), 'UTF-8', $rowref->{'encoding'}, $marc_type ); + foreach my $item_field ( $old_marc->field($item_tag) ) { $old_marc->delete_field($item_field); } $oldxml = $old_marc->as_xml($marc_type); @@ -629,7 +665,7 @@ sub BatchCommitRecords { my $context = { source => 'batchimport' }; if ($logged_in_patron) { $context->{categorycode} = $logged_in_patron->categorycode; - $context->{userid} = $logged_in_patron->userid; + $context->{userid} = $logged_in_patron->userid; } ModBiblio( @@ -642,57 +678,67 @@ sub BatchCommitRecords { skip_holds_queue => 1, } ); - push @biblio_ids, $recordid; + push @biblio_ids, $recordid; push @updated_ids, $recordid; - $query = "UPDATE import_biblios SET matched_biblionumber = ? WHERE import_record_id = ?"; # FIXME call SetMatchedBiblionumber instead + $query = "UPDATE import_biblios SET matched_biblionumber = ? WHERE import_record_id = ?" + ; # FIXME call SetMatchedBiblionumber instead - if ($item_result eq 'create_new' || $item_result eq 'replace') { - my ($bib_items_added, $bib_items_replaced, $bib_items_errored) = _batchCommitItems($rowref->{'import_record_id'}, $recordid, $item_result); - $num_items_added += $bib_items_added; + if ( $item_result eq 'create_new' || $item_result eq 'replace' ) { + my ( $bib_items_added, $bib_items_replaced, $bib_items_errored ) = + _batchCommitItems( $rowref->{'import_record_id'}, $recordid, $item_result ); + $num_items_added += $bib_items_added; $num_items_replaced += $bib_items_replaced; - $num_items_errored += $bib_items_errored; + $num_items_errored += $bib_items_errored; } } else { $oldxml = GetAuthorityXML($recordid); - ModAuthority($recordid, $marc_record, GuessAuthTypeCode($marc_record)); + ModAuthority( $recordid, $marc_record, GuessAuthTypeCode($marc_record) ); $query = "UPDATE import_auths SET matched_authid = ? WHERE import_record_id = ?"; } + # Combine xml update, SetImportRecordOverlayStatus, and SetImportRecordStatus updates into a single update for efficiency, especially in a transaction - my $sth = $dbh->prepare_cached("UPDATE import_records SET marcxml_old = ?, status = ?, overlay_status = ? WHERE import_record_id = ?"); + my $sth = $dbh->prepare_cached( + "UPDATE import_records SET marcxml_old = ?, status = ?, overlay_status = ? WHERE import_record_id = ?"); $sth->execute( $oldxml, 'imported', 'match_applied', $rowref->{'import_record_id'} ); $sth->finish(); my $sth2 = $dbh->prepare_cached($query); - $sth2->execute($recordid, $rowref->{'import_record_id'}); + $sth2->execute( $recordid, $rowref->{'import_record_id'} ); $sth2->finish(); - } elsif ($record_result eq 'ignore') { + } elsif ( $record_result eq 'ignore' ) { $recordid = $record_match; $num_ignored++; - if ($record_type eq 'biblio' and defined $recordid and ( $item_result eq 'create_new' || $item_result eq 'replace' ) ) { - my ($bib_items_added, $bib_items_replaced, $bib_items_errored) = _batchCommitItems($rowref->{'import_record_id'}, $recordid, $item_result); + if ( $record_type eq 'biblio' + and defined $recordid + and ( $item_result eq 'create_new' || $item_result eq 'replace' ) ) + { + my ( $bib_items_added, $bib_items_replaced, $bib_items_errored ) = + _batchCommitItems( $rowref->{'import_record_id'}, $recordid, $item_result ); push @biblio_ids, $recordid if $bib_items_added || $bib_items_replaced; - $num_items_added += $bib_items_added; - $num_items_replaced += $bib_items_replaced; - $num_items_errored += $bib_items_errored; + $num_items_added += $bib_items_added; + $num_items_replaced += $bib_items_replaced; + $num_items_errored += $bib_items_errored; + # still need to record the matched biblionumber so that the # items can be reverted - my $sth2 = $dbh->prepare_cached("UPDATE import_biblios SET matched_biblionumber = ? WHERE import_record_id = ?"); # FIXME call SetMatchedBiblionumber instead - $sth2->execute($recordid, $rowref->{'import_record_id'}); - SetImportRecordOverlayStatus($rowref->{'import_record_id'}, 'match_applied'); + my $sth2 = $dbh->prepare_cached( + "UPDATE import_biblios SET matched_biblionumber = ? WHERE import_record_id = ?") + ; # FIXME call SetMatchedBiblionumber instead + $sth2->execute( $recordid, $rowref->{'import_record_id'} ); + SetImportRecordOverlayStatus( $rowref->{'import_record_id'}, 'match_applied' ); } - SetImportRecordStatus($rowref->{'import_record_id'}, 'ignored'); + SetImportRecordStatus( $rowref->{'import_record_id'}, 'ignored' ); } $schema->txn_commit; } - if ($progress_interval){ + if ($progress_interval) { &$progress_callback($rec_num); } $sth->finish(); - SetImportBatchStatus($batch_id, 'imported'); - + SetImportBatchStatus( $batch_id, 'imported' ); if (@biblio_ids) { my $indexer = Koha::SearchEngine::Indexer->new( { index => $Koha::SearchEngine::BIBLIOS_INDEX } ); @@ -701,7 +747,7 @@ sub BatchCommitRecords { Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue->new->enqueue( { biblio_ids => \@updated_ids } ) if ( @updated_ids && C4::Context->preference('RealTimeHoldsQueue') ); - return ($num_added, $num_updated, $num_items_added, $num_items_replaced, $num_items_errored, $num_ignored); + return ( $num_added, $num_updated, $num_items_added, $num_items_replaced, $num_items_errored, $num_ignored ); } =head2 _batchCommitItems @@ -718,8 +764,8 @@ sub _batchCommitItems { my $dbh = C4::Context->dbh; - my $num_items_added = 0; - my $num_items_errored = 0; + my $num_items_added = 0; + my $num_items_errored = 0; my $num_items_replaced = 0; my $sth = $dbh->prepare( " @@ -733,26 +779,28 @@ sub _batchCommitItems { $sth->execute(); while ( my $row = $sth->fetchrow_hashref() ) { - my $item_marc = MARC::Record->new_from_xml( StripNonXmlChars( $row->{'marcxml'} ), 'UTF-8', $row->{'encoding'} ); + my $item_marc = + MARC::Record->new_from_xml( StripNonXmlChars( $row->{'marcxml'} ), 'UTF-8', $row->{'encoding'} ); # Delete date_due subfield as to not accidentally delete item checkout due dates - my ( $MARCfield, $MARCsubfield ) = GetMarcFromKohaField( 'items.onloan' ); + my ( $MARCfield, $MARCsubfield ) = GetMarcFromKohaField('items.onloan'); $item_marc->field($MARCfield)->delete_subfield( code => $MARCsubfield ); - my $item = TransformMarcToKoha({ record => $item_marc, kohafields => ['items.barcode','items.itemnumber'] }); + my $item = + TransformMarcToKoha( { record => $item_marc, kohafields => [ 'items.barcode', 'items.itemnumber' ] } ); my $item_match; - my $duplicate_barcode = exists( $item->{'barcode'} ); + my $duplicate_barcode = exists( $item->{'barcode'} ); my $duplicate_itemnumber = exists( $item->{'itemnumber'} ); # We assume that when replacing items we do not want to move them - the onus is on the importer to # ensure the correct items/records are being updated - my $updsth = $dbh->prepare("UPDATE import_items SET status = ?, itemnumber = ?, import_error = ? WHERE import_items_id = ?"); - if ( - $action eq "replace" && - $duplicate_itemnumber && - ( $item_match = Koha::Items->find( $item->{itemnumber} )) - ) { + my $updsth = $dbh->prepare( + "UPDATE import_items SET status = ?, itemnumber = ?, import_error = ? WHERE import_items_id = ?"); + if ( $action eq "replace" + && $duplicate_itemnumber + && ( $item_match = Koha::Items->find( $item->{itemnumber} ) ) ) + { # Duplicate itemnumbers have precedence, that way we can update barcodes by overlaying ModItemFromMarc( $item_marc, $item_match->biblionumber, $item->{itemnumber}, { skip_record_index => 1 } ); $updsth->bind_param( 1, 'imported' ); @@ -762,12 +810,14 @@ sub _batchCommitItems { $updsth->execute(); $updsth->finish(); $num_items_replaced++; - } elsif ( - $action eq "replace" && - $duplicate_barcode && - ( $item_match = Koha::Items->find({ barcode => $item->{'barcode'} }) ) - ) { - ModItemFromMarc( $item_marc, $item_match->biblionumber, $item_match->itemnumber, { skip_record_index => 1 } ); + } elsif ( $action eq "replace" + && $duplicate_barcode + && ( $item_match = Koha::Items->find( { barcode => $item->{'barcode'} } ) ) ) + { + ModItemFromMarc( + $item_marc, $item_match->biblionumber, $item_match->itemnumber, + { skip_record_index => 1 } + ); $updsth->bind_param( 1, 'imported' ); $updsth->bind_param( 2, $item->{itemnumber} ); $updsth->bind_param( 3, undef ); @@ -776,10 +826,11 @@ sub _batchCommitItems { $updsth->finish(); $num_items_replaced++; } elsif ( + # We aren't replacing, but the incoming file has a barcode, we need to check if it exists - $duplicate_barcode && - ( $item_match = Koha::Items->find({ barcode => $item->{'barcode'} }) ) - ) { + $duplicate_barcode && ( $item_match = Koha::Items->find( { barcode => $item->{'barcode'} } ) ) + ) + { $updsth->bind_param( 1, 'error' ); $updsth->bind_param( 2, undef ); $updsth->bind_param( 3, 'duplicate item barcode' ); @@ -787,12 +838,16 @@ sub _batchCommitItems { $updsth->execute(); $num_items_errored++; } else { + # Remove the itemnumber if it exists, we want to create a new item - my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField( "items.itemnumber" ); + my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber"); $item_marc->field($itemtag)->delete_subfield( code => $itemsubfield ); - my ( $item_biblionumber, $biblioitemnumber, $itemnumber ) = AddItemFromMarc( $item_marc, $biblionumber, { biblioitemnumber => $biblioitemnumber, skip_record_index => 1 } ); - if( $itemnumber ) { + my ( $item_biblionumber, $biblioitemnumber, $itemnumber ) = AddItemFromMarc( + $item_marc, $biblionumber, + { biblioitemnumber => $biblioitemnumber, skip_record_index => 1 } + ); + if ($itemnumber) { $updsth->bind_param( 1, 'imported' ); $updsth->bind_param( 2, $itemnumber ); $updsth->bind_param( 3, undef ); @@ -822,92 +877,107 @@ sub BatchRevertRecords { $logger->trace("C4::ImportBatch::BatchRevertRecords( $batch_id )"); my $record_type; - my $num_deleted = 0; - my $num_errors = 0; - my $num_reverted = 0; - my $num_ignored = 0; + my $num_deleted = 0; + my $num_errors = 0; + my $num_reverted = 0; + my $num_ignored = 0; my $num_items_deleted = 0; + # commit (i.e., save, all records in the batch) - SetImportBatchStatus($batch_id, 'reverting'); + SetImportBatchStatus( $batch_id, 'reverting' ); my $overlay_action = GetImportBatchOverlayAction($batch_id); my $nomatch_action = GetImportBatchNoMatchAction($batch_id); - my $dbh = C4::Context->dbh; - my $sth = $dbh->prepare("SELECT import_records.import_record_id, record_type, status, overlay_status, marcxml_old, encoding, matched_biblionumber, matched_authid + my $dbh = C4::Context->dbh; + my $sth = $dbh->prepare( + "SELECT import_records.import_record_id, record_type, status, overlay_status, marcxml_old, encoding, matched_biblionumber, matched_authid FROM import_records LEFT JOIN import_auths ON (import_records.import_record_id=import_auths.import_record_id) LEFT JOIN import_biblios ON (import_records.import_record_id=import_biblios.import_record_id) - WHERE import_batch_id = ?"); + WHERE import_batch_id = ?" + ); $sth->execute($batch_id); my $marc_type; my $marcflavour = C4::Context->preference('marcflavour'); - while (my $rowref = $sth->fetchrow_hashref) { + + while ( my $rowref = $sth->fetchrow_hashref ) { $record_type = $rowref->{'record_type'}; - if ($rowref->{'status'} eq 'error' or $rowref->{'status'} eq 'reverted') { + if ( $rowref->{'status'} eq 'error' or $rowref->{'status'} eq 'reverted' ) { $num_ignored++; next; } - if ($marcflavour eq 'UNIMARC' && $record_type eq 'auth') { + if ( $marcflavour eq 'UNIMARC' && $record_type eq 'auth' ) { $marc_type = 'UNIMARCAUTH'; - } elsif ($marcflavour eq 'UNIMARC') { + } elsif ( $marcflavour eq 'UNIMARC' ) { $marc_type = 'UNIMARC'; } else { $marc_type = 'USMARC'; } - my $record_result = _get_revert_action($overlay_action, $rowref->{'overlay_status'}, $rowref->{'status'}); + my $record_result = _get_revert_action( $overlay_action, $rowref->{'overlay_status'}, $rowref->{'status'} ); - if ($record_result eq 'delete') { + if ( $record_result eq 'delete' ) { my $error = undef; - if ($record_type eq 'biblio') { - $num_items_deleted += BatchRevertItems($rowref->{'import_record_id'}, $rowref->{'matched_biblionumber'}); - $error = DelBiblio($rowref->{'matched_biblionumber'}); + if ( $record_type eq 'biblio' ) { + $num_items_deleted += + BatchRevertItems( $rowref->{'import_record_id'}, $rowref->{'matched_biblionumber'} ); + $error = DelBiblio( $rowref->{'matched_biblionumber'} ); } else { - DelAuthority({ authid => $rowref->{'matched_authid'} }); + DelAuthority( { authid => $rowref->{'matched_authid'} } ); } - if (defined $error) { + if ( defined $error ) { $num_errors++; } else { $num_deleted++; - SetImportRecordStatus($rowref->{'import_record_id'}, 'reverted'); + SetImportRecordStatus( $rowref->{'import_record_id'}, 'reverted' ); } - } elsif ($record_result eq 'restore') { + } elsif ( $record_result eq 'restore' ) { $num_reverted++; - my $old_record = MARC::Record->new_from_xml(StripNonXmlChars($rowref->{'marcxml_old'}), 'UTF-8', $rowref->{'encoding'}, $marc_type); - if ($record_type eq 'biblio') { + my $old_record = MARC::Record->new_from_xml( + StripNonXmlChars( $rowref->{'marcxml_old'} ), 'UTF-8', + $rowref->{'encoding'}, $marc_type + ); + if ( $record_type eq 'biblio' ) { my $biblionumber = $rowref->{'matched_biblionumber'}; - my $oldbiblio = Koha::Biblios->find( $biblionumber ); + my $oldbiblio = Koha::Biblios->find($biblionumber); - $logger->info("C4::ImportBatch::BatchRevertRecords: Biblio record $biblionumber does not exist, restoration of this record was skipped") unless $oldbiblio; - next unless $oldbiblio; # Record has since been deleted. Deleted records should stay deleted. + $logger->info( + "C4::ImportBatch::BatchRevertRecords: Biblio record $biblionumber does not exist, restoration of this record was skipped" + ) unless $oldbiblio; + next unless $oldbiblio; # Record has since been deleted. Deleted records should stay deleted. - $num_items_deleted += BatchRevertItems($rowref->{'import_record_id'}, $rowref->{'matched_biblionumber'}); - ModBiblio($old_record, $biblionumber, $oldbiblio->frameworkcode); + $num_items_deleted += + BatchRevertItems( $rowref->{'import_record_id'}, $rowref->{'matched_biblionumber'} ); + ModBiblio( $old_record, $biblionumber, $oldbiblio->frameworkcode ); } else { my $authid = $rowref->{'matched_authid'}; - ModAuthority($authid, $old_record, GuessAuthTypeCode($old_record)); + ModAuthority( $authid, $old_record, GuessAuthTypeCode($old_record) ); } - SetImportRecordStatus($rowref->{'import_record_id'}, 'reverted'); - } elsif ($record_result eq 'ignore') { - if ($record_type eq 'biblio') { - $num_items_deleted += BatchRevertItems($rowref->{'import_record_id'}, $rowref->{'matched_biblionumber'}); + SetImportRecordStatus( $rowref->{'import_record_id'}, 'reverted' ); + } elsif ( $record_result eq 'ignore' ) { + if ( $record_type eq 'biblio' ) { + $num_items_deleted += + BatchRevertItems( $rowref->{'import_record_id'}, $rowref->{'matched_biblionumber'} ); } - SetImportRecordStatus($rowref->{'import_record_id'}, 'reverted'); + SetImportRecordStatus( $rowref->{'import_record_id'}, 'reverted' ); } my $query; - if ($record_type eq 'biblio') { + if ( $record_type eq 'biblio' ) { + # remove matched_biblionumber only if there is no 'imported' item left - $query = "UPDATE import_biblios SET matched_biblionumber = NULL WHERE import_record_id = ?"; # FIXME Remove me - $query = "UPDATE import_biblios SET matched_biblionumber = NULL WHERE import_record_id = ? AND NOT EXISTS (SELECT * FROM import_items WHERE import_items.import_record_id=import_biblios.import_record_id and status='imported')"; + $query = + "UPDATE import_biblios SET matched_biblionumber = NULL WHERE import_record_id = ?"; # FIXME Remove me + $query = + "UPDATE import_biblios SET matched_biblionumber = NULL WHERE import_record_id = ? AND NOT EXISTS (SELECT * FROM import_items WHERE import_items.import_record_id=import_biblios.import_record_id and status='imported')"; } else { $query = "UPDATE import_auths SET matched_authid = NULL WHERE import_record_id = ?"; } my $sth2 = $dbh->prepare_cached($query); - $sth2->execute($rowref->{'import_record_id'}); + $sth2->execute( $rowref->{'import_record_id'} ); } $sth->finish(); - SetImportBatchStatus($batch_id, 'reverted'); - return ($num_deleted, $num_errors, $num_reverted, $num_items_deleted, $num_ignored); + SetImportBatchStatus( $batch_id, 'reverted' ); + return ( $num_deleted, $num_errors, $num_reverted, $num_items_deleted, $num_ignored ); } =head2 BatchRevertItems @@ -917,28 +987,29 @@ sub BatchRevertRecords { =cut sub BatchRevertItems { - my ($import_record_id, $biblionumber) = @_; + my ( $import_record_id, $biblionumber ) = @_; - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $num_items_deleted = 0; - my $sth = $dbh->prepare_cached("SELECT import_items_id, itemnumber + my $sth = $dbh->prepare_cached( + "SELECT import_items_id, itemnumber FROM import_items JOIN items USING (itemnumber) - WHERE import_record_id = ?"); - $sth->bind_param(1, $import_record_id); + WHERE import_record_id = ?" + ); + $sth->bind_param( 1, $import_record_id ); $sth->execute(); - while (my $row = $sth->fetchrow_hashref()) { - my $item = Koha::Items->find($row->{itemnumber}); - if ($item->safe_delete){ + while ( my $row = $sth->fetchrow_hashref() ) { + my $item = Koha::Items->find( $row->{itemnumber} ); + if ( $item->safe_delete ) { my $updsth = $dbh->prepare("UPDATE import_items SET status = ? WHERE import_items_id = ?"); - $updsth->bind_param(1, 'reverted'); - $updsth->bind_param(2, $row->{'import_items_id'}); + $updsth->bind_param( 1, 'reverted' ); + $updsth->bind_param( 2, $row->{'import_items_id'} ); $updsth->execute(); $updsth->finish(); $num_items_deleted++; - } - else { + } else { next; } } @@ -961,8 +1032,8 @@ sub CleanBatch { my $batch_id = shift; return unless defined $batch_id; - C4::Context->dbh->do('DELETE FROM import_records WHERE import_batch_id = ?', {}, $batch_id); - SetImportBatchStatus($batch_id, 'cleaned'); + C4::Context->dbh->do( 'DELETE FROM import_records WHERE import_batch_id = ?', {}, $batch_id ); + SetImportBatchStatus( $batch_id, 'cleaned' ); } =head2 DeleteBatch @@ -980,7 +1051,7 @@ sub DeleteBatch { my $dbh = C4::Context->dbh; my $sth = $dbh->prepare('DELETE FROM import_batches WHERE import_batch_id = ?'); - $sth->execute( $batch_id ); + $sth->execute($batch_id); } =head2 GetAllImportBatches @@ -993,15 +1064,17 @@ ascending order by import_batch_id. =cut -sub GetAllImportBatches { +sub GetAllImportBatches { my $dbh = C4::Context->dbh; - my $sth = $dbh->prepare_cached("SELECT * FROM import_batches + my $sth = $dbh->prepare_cached( + "SELECT * FROM import_batches WHERE batch_type IN ('batch', 'webservice') - ORDER BY import_batch_id ASC"); + ORDER BY import_batch_id ASC" + ); my $results = []; $sth->execute(); - while (my $row = $sth->fetchrow_hashref) { + while ( my $row = $sth->fetchrow_hashref ) { push @$results, $row; } $sth->finish(); @@ -1022,7 +1095,8 @@ SELECT import_batch_id FROM import_batches WHERE batch_type = 'webservice' AND import_status = 'staged' EOQ -sub GetStagedWebserviceBatches { + +sub GetStagedWebserviceBatches { my $dbh = C4::Context->dbh; return $dbh->selectcol_arrayref($PENDING_WEBSERVICE_BATCHES_QRY); } @@ -1038,26 +1112,26 @@ start at the given offset. =cut sub GetImportBatchRangeDesc { - my ($offset, $results_per_group) = @_; + my ( $offset, $results_per_group ) = @_; - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $query = "SELECT b.*, p.name as profile FROM import_batches b LEFT JOIN import_batch_profiles p ON b.profile_id = p.id WHERE b.batch_type IN ('batch', 'webservice') ORDER BY b.import_batch_id DESC"; my @params; - if ($results_per_group){ + if ($results_per_group) { $query .= " LIMIT ?"; - push(@params, $results_per_group); + push( @params, $results_per_group ); } - if ($offset){ + if ($offset) { $query .= " OFFSET ?"; - push(@params, $offset); + push( @params, $offset ); } my $sth = $dbh->prepare_cached($query); $sth->execute(@params); - my $results = $sth->fetchall_arrayref({}); + my $results = $sth->fetchall_arrayref( {} ); $sth->finish(); return $results; } @@ -1070,15 +1144,15 @@ sub GetImportBatchRangeDesc { sub GetItemNumbersFromImportBatch { my ($batch_id) = @_; - my $dbh = C4::Context->dbh; - my $sql = q| + my $dbh = C4::Context->dbh; + my $sql = q| SELECT itemnumber FROM import_items INNER JOIN items USING (itemnumber) INNER JOIN import_records USING (import_record_id) WHERE import_batch_id = ?|; - my $sth = $dbh->prepare( $sql ); + my $sth = $dbh->prepare($sql); $sth->execute($batch_id); - my @items ; + my @items; while ( my ($itm) = $sth->fetchrow_array ) { push @items, $itm; } @@ -1109,7 +1183,7 @@ sub GetNumberOfNonZ3950ImportBatches { sub GetImportBiblios { my ($import_record_id) = @_; - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $query = "SELECT * FROM import_biblios WHERE import_record_id = ?"; return $dbh->selectall_arrayref( $query, @@ -1135,10 +1209,10 @@ sub GetImportRecordsRange { my $dbh = C4::Context->dbh; my $order_by = $parameters->{order_by} || 'import_record_id'; - ( $order_by ) = grep( { $_ eq $order_by } qw( import_record_id title status overlay_status ) ) ? $order_by : 'import_record_id'; + ($order_by) = + grep( { $_ eq $order_by } qw( import_record_id title status overlay_status ) ) ? $order_by : 'import_record_id'; - my $order_by_direction = - uc( $parameters->{order_by_direction} // 'ASC' ) eq 'DESC' ? 'DESC' : 'ASC'; + my $order_by_direction = uc( $parameters->{order_by_direction} // 'ASC' ) eq 'DESC' ? 'DESC' : 'ASC'; $order_by .= " $order_by_direction, authorized_heading" if $order_by eq 'title'; @@ -1150,25 +1224,25 @@ sub GetImportRecordsRange { LEFT JOIN import_biblios ON (import_records.import_record_id=import_biblios.import_record_id) WHERE import_batch_id = ?"; my @params; - push(@params, $batch_id); + push( @params, $batch_id ); if ($status) { $query .= " AND status=?"; - push(@params,$status); + push( @params, $status ); } - $query.=" ORDER BY $order_by $order_by_direction"; + $query .= " ORDER BY $order_by $order_by_direction"; - if($results_per_group){ + if ($results_per_group) { $query .= " LIMIT ?"; - push(@params, $results_per_group); + push( @params, $results_per_group ); } - if($offset){ + if ($offset) { $query .= " OFFSET ?"; - push(@params, $offset); + push( @params, $offset ); } my $sth = $dbh->prepare_cached($query); $sth->execute(@params); - my $results = $sth->fetchall_arrayref({}); + my $results = $sth->fetchall_arrayref( {} ); $sth->finish(); return $results; @@ -1184,7 +1258,8 @@ sub GetBestRecordMatch { my ($import_record_id) = @_; my $dbh = C4::Context->dbh; - my $sth = $dbh->prepare("SELECT candidate_match_id + my $sth = $dbh->prepare( + "SELECT candidate_match_id FROM import_record_matches JOIN import_records ON ( import_record_matches.import_record_id = import_records.import_record_id ) LEFT JOIN biblio ON ( candidate_match_id = biblio.biblionumber ) @@ -1193,7 +1268,8 @@ sub GetBestRecordMatch { ( (import_records.record_type = 'biblio' AND biblio.biblionumber IS NOT NULL) OR (import_records.record_type = 'auth' AND auth_header.authid IS NOT NULL) ) AND chosen = 1 - ORDER BY score DESC, candidate_match_id DESC"); + ORDER BY score DESC, candidate_match_id DESC" + ); $sth->execute($import_record_id); my ($record_id) = $sth->fetchrow_array(); $sth->finish(); @@ -1225,11 +1301,11 @@ sub GetImportBatchStatus { =cut sub SetImportBatchStatus { - my ($batch_id, $new_status) = @_; + my ( $batch_id, $new_status ) = @_; my $dbh = C4::Context->dbh; my $sth = $dbh->prepare("UPDATE import_batches SET import_status = ? WHERE import_batch_id = ?"); - $sth->execute($new_status, $batch_id); + $sth->execute( $new_status, $batch_id ); $sth->finish(); } @@ -1241,7 +1317,7 @@ sub SetImportBatchStatus { =cut sub SetMatchedBiblionumber { - my ($import_record_id, $biblionumber) = @_; + my ( $import_record_id, $biblionumber ) = @_; my $dbh = C4::Context->dbh; $dbh->do( @@ -1268,7 +1344,6 @@ sub GetImportBatchOverlayAction { } - =head2 SetImportBatchOverlayAction SetImportBatchOverlayAction($batch_id, $new_overlay_action); @@ -1276,11 +1351,11 @@ sub GetImportBatchOverlayAction { =cut sub SetImportBatchOverlayAction { - my ($batch_id, $new_overlay_action) = @_; + my ( $batch_id, $new_overlay_action ) = @_; my $dbh = C4::Context->dbh; my $sth = $dbh->prepare("UPDATE import_batches SET overlay_action = ? WHERE import_batch_id = ?"); - $sth->execute($new_overlay_action, $batch_id); + $sth->execute( $new_overlay_action, $batch_id ); $sth->finish(); } @@ -1303,7 +1378,6 @@ sub GetImportBatchNoMatchAction { } - =head2 SetImportBatchNoMatchAction SetImportBatchNoMatchAction($batch_id, $new_nomatch_action); @@ -1311,11 +1385,11 @@ sub GetImportBatchNoMatchAction { =cut sub SetImportBatchNoMatchAction { - my ($batch_id, $new_nomatch_action) = @_; + my ( $batch_id, $new_nomatch_action ) = @_; my $dbh = C4::Context->dbh; my $sth = $dbh->prepare("UPDATE import_batches SET nomatch_action = ? WHERE import_batch_id = ?"); - $sth->execute($new_nomatch_action, $batch_id); + $sth->execute( $new_nomatch_action, $batch_id ); $sth->finish(); } @@ -1338,7 +1412,6 @@ sub GetImportBatchItemAction { } - =head2 SetImportBatchItemAction SetImportBatchItemAction($batch_id, $new_item_action); @@ -1346,11 +1419,11 @@ sub GetImportBatchItemAction { =cut sub SetImportBatchItemAction { - my ($batch_id, $new_item_action) = @_; + my ( $batch_id, $new_item_action ) = @_; my $dbh = C4::Context->dbh; my $sth = $dbh->prepare("UPDATE import_batches SET item_action = ? WHERE import_batch_id = ?"); - $sth->execute($new_item_action, $batch_id); + $sth->execute( $new_item_action, $batch_id ); $sth->finish(); } @@ -1373,7 +1446,6 @@ sub GetImportBatchMatcher { } - =head2 SetImportBatchMatcher SetImportBatchMatcher($batch_id, $new_matcher_id); @@ -1381,11 +1453,11 @@ sub GetImportBatchMatcher { =cut sub SetImportBatchMatcher { - my ($batch_id, $new_matcher_id) = @_; + my ( $batch_id, $new_matcher_id ) = @_; my $dbh = C4::Context->dbh; my $sth = $dbh->prepare("UPDATE import_batches SET matcher_id = ? WHERE import_batch_id = ?"); - $sth->execute($new_matcher_id, $batch_id); + $sth->execute( $new_matcher_id, $batch_id ); $sth->finish(); } @@ -1408,7 +1480,6 @@ sub GetImportRecordOverlayStatus { } - =head2 SetImportRecordOverlayStatus SetImportRecordOverlayStatus($import_record_id, $new_overlay_status); @@ -1416,11 +1487,11 @@ sub GetImportRecordOverlayStatus { =cut sub SetImportRecordOverlayStatus { - my ($import_record_id, $new_overlay_status) = @_; + my ( $import_record_id, $new_overlay_status ) = @_; my $dbh = C4::Context->dbh; my $sth = $dbh->prepare("UPDATE import_records SET overlay_status = ? WHERE import_record_id = ?"); - $sth->execute($new_overlay_status, $import_record_id); + $sth->execute( $new_overlay_status, $import_record_id ); $sth->finish(); } @@ -1443,7 +1514,6 @@ sub GetImportRecordStatus { } - =head2 SetImportRecordStatus SetImportRecordStatus($import_record_id, $new_status); @@ -1451,11 +1521,11 @@ sub GetImportRecordStatus { =cut sub SetImportRecordStatus { - my ($import_record_id, $new_status) = @_; + my ( $import_record_id, $new_status ) = @_; my $dbh = C4::Context->dbh; my $sth = $dbh->prepare("UPDATE import_records SET status = ? WHERE import_record_id = ?"); - $sth->execute($new_status, $import_record_id); + $sth->execute( $new_status, $import_record_id ); $sth->finish(); } @@ -1468,33 +1538,36 @@ sub SetImportRecordStatus { sub GetImportRecordMatches { my $import_record_id = shift; - my $best_only = @_ ? shift : 0; + my $best_only = @_ ? shift : 0; my $dbh = C4::Context->dbh; + # FIXME currently biblio only - my $sth = $dbh->prepare_cached("SELECT title, author, biblionumber, + my $sth = $dbh->prepare_cached( + "SELECT title, author, biblionumber, candidate_match_id, score, record_type, chosen FROM import_records JOIN import_record_matches USING (import_record_id) LEFT JOIN biblio ON (biblionumber = candidate_match_id) WHERE import_record_id = ? - ORDER BY score DESC, biblionumber DESC"); - $sth->bind_param(1, $import_record_id); + ORDER BY score DESC, biblionumber DESC" + ); + $sth->bind_param( 1, $import_record_id ); my $results = []; $sth->execute(); - while (my $row = $sth->fetchrow_hashref) { - if ($row->{'record_type'} eq 'auth') { + while ( my $row = $sth->fetchrow_hashref ) { + if ( $row->{'record_type'} eq 'auth' ) { $row->{'authorized_heading'} = GetAuthorizedHeading( { authid => $row->{'candidate_match_id'} } ); } - next if ($row->{'record_type'} eq 'biblio' && not $row->{'biblionumber'}); + next if ( $row->{'record_type'} eq 'biblio' && not $row->{'biblionumber'} ); push @$results, $row; last if $best_only; } $sth->finish(); return $results; - + } =head2 SetImportRecordMatches @@ -1505,19 +1578,21 @@ sub GetImportRecordMatches { sub SetImportRecordMatches { my $import_record_id = shift; - my @matches = @_; + my @matches = @_; - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $delsth = $dbh->prepare("DELETE FROM import_record_matches WHERE import_record_id = ?"); $delsth->execute($import_record_id); $delsth->finish(); - my $sth = $dbh->prepare("INSERT INTO import_record_matches (import_record_id, candidate_match_id, score, chosen) - VALUES (?, ?, ?, ?)"); - my $chosen = 1; #The first match is defaulted to be chosen + my $sth = $dbh->prepare( + "INSERT INTO import_record_matches (import_record_id, candidate_match_id, score, chosen) + VALUES (?, ?, ?, ?)" + ); + my $chosen = 1; #The first match is defaulted to be chosen foreach my $match (@matches) { - $sth->execute($import_record_id, $match->{'record_id'}, $match->{'score'}, $chosen); - $chosen = 0; #After the first we do not default to other matches + $sth->execute( $import_record_id, $match->{'record_id'}, $match->{'score'}, $chosen ); + $chosen = 0; #After the first we do not default to other matches } } @@ -1536,11 +1611,11 @@ Returns two array refs. =cut sub RecordsFromISO2709File { - my ($input_file, $record_type, $encoding) = @_; + my ( $input_file, $record_type, $encoding ) = @_; my @errors; my $marc_type = C4::Context->preference('marcflavour'); - $marc_type .= 'AUTH' if ($marc_type eq 'UNIMARC' && $record_type eq 'auth'); + $marc_type .= 'AUTH' if ( $marc_type eq 'UNIMARC' && $record_type eq 'auth' ); open my $fh, '<', $input_file or die "$0: cannot open input file $input_file: $!\n"; my @marc_records; @@ -1548,11 +1623,11 @@ sub RecordsFromISO2709File { while (<$fh>) { s/^\s+//; s/\s+$//; - next unless $_; # skip if record has only whitespace, as might occur - # if file includes newlines between each MARC record - my ($marc_record, $charset_guessed, $char_errors) = MarcToUTF8Record($_, $marc_type, $encoding); + next unless $_; # skip if record has only whitespace, as might occur + # if file includes newlines between each MARC record + my ( $marc_record, $charset_guessed, $char_errors ) = MarcToUTF8Record( $_, $marc_type, $encoding ); push @marc_records, $marc_record; - if ($charset_guessed ne $encoding) { + if ( $charset_guessed ne $encoding ) { push @errors, "Unexpected charset $charset_guessed, expecting $encoding"; } @@ -1576,16 +1651,16 @@ Returns two array refs. sub RecordsFromMARCXMLFile { my ( $filename, $encoding ) = @_; - my $batch = MARC::File::XML->in( $filename ); + my $batch = MARC::File::XML->in($filename); my ( @marcRecords, @errors, $record ); do { - eval { $record = $batch->next( $encoding ); }; + eval { $record = $batch->next($encoding); }; if ($@) { push @errors, $@; } push @marcRecords, $record if $record; - } while( $record ); - return (\@errors, \@marcRecords); + } while ($record); + return ( \@errors, \@marcRecords ); } =head2 RecordsFromMarcPlugin @@ -1595,7 +1670,7 @@ sub RecordsFromMARCXMLFile { =cut sub RecordsFromMarcPlugin { - my ($input_file, $plugin_class, $encoding) = @_; + my ( $input_file, $plugin_class, $encoding ) = @_; my ( $text, @return ); return \@return if !$input_file || !$plugin_class; @@ -1611,18 +1686,20 @@ sub RecordsFromMarcPlugin { close $fh; # Convert to large MARC blob with plugin - $text = Koha::Plugins::Handler->run({ - class => $plugin_class, - method => 'to_marc', - params => { data => $text }, - }) if $text; + $text = Koha::Plugins::Handler->run( + { + class => $plugin_class, + method => 'to_marc', + params => { data => $text }, + } + ) if $text; # Convert to array of MARC records - if( $text ) { + if ($text) { my $marc_type = C4::Context->preference('marcflavour'); - foreach my $blob ( split(/\x1D/, $text) ) { + foreach my $blob ( split( /\x1D/, $text ) ) { next if $blob =~ /^\s*$/; - my ($marcrecord) = MarcToUTF8Record($blob, $marc_type, $encoding); + my ($marcrecord) = MarcToUTF8Record( $blob, $marc_type, $encoding ); push @return, $marcrecord; } } @@ -1632,68 +1709,83 @@ sub RecordsFromMarcPlugin { # internal functions sub _create_import_record { - my ($batch_id, $record_sequence, $marc_record, $record_type, $encoding, $marc_type) = @_; + my ( $batch_id, $record_sequence, $marc_record, $record_type, $encoding, $marc_type ) = @_; my $dbh = C4::Context->dbh; - my $sth = $dbh->prepare("INSERT INTO import_records (import_batch_id, record_sequence, marc, marcxml, marcxml_old, + my $sth = $dbh->prepare( + "INSERT INTO import_records (import_batch_id, record_sequence, marc, marcxml, marcxml_old, record_type, encoding) - VALUES (?, ?, ?, ?, ?, ?, ?)"); - $sth->execute($batch_id, $record_sequence, $marc_record->as_usmarc(), $marc_record->as_xml($marc_type), '', - $record_type, $encoding); + VALUES (?, ?, ?, ?, ?, ?, ?)" + ); + $sth->execute( + $batch_id, $record_sequence, $marc_record->as_usmarc(), $marc_record->as_xml($marc_type), '', + $record_type, $encoding + ); my $import_record_id = $dbh->{'mysql_insertid'}; $sth->finish(); return $import_record_id; } sub _add_auth_fields { - my ($import_record_id, $marc_record) = @_; + my ( $import_record_id, $marc_record ) = @_; my $controlnumber; - if ($marc_record->field('001')) { + if ( $marc_record->field('001') ) { $controlnumber = $marc_record->field('001')->data(); } - my $authorized_heading = GetAuthorizedHeading({ record => $marc_record }); - my $dbh = C4::Context->dbh; - my $sth = $dbh->prepare("INSERT INTO import_auths (import_record_id, control_number, authorized_heading) VALUES (?, ?, ?)"); - $sth->execute($import_record_id, $controlnumber, $authorized_heading); + my $authorized_heading = GetAuthorizedHeading( { record => $marc_record } ); + my $dbh = C4::Context->dbh; + my $sth = $dbh->prepare( + "INSERT INTO import_auths (import_record_id, control_number, authorized_heading) VALUES (?, ?, ?)"); + $sth->execute( $import_record_id, $controlnumber, $authorized_heading ); $sth->finish(); } sub _add_biblio_fields { - my ($import_record_id, $marc_record) = @_; + my ( $import_record_id, $marc_record ) = @_; - my ($title, $author, $isbn, $issn) = _parse_biblio_fields($marc_record); + my ( $title, $author, $isbn, $issn ) = _parse_biblio_fields($marc_record); my $dbh = C4::Context->dbh; + # FIXME no controlnumber, originalsource $isbn = C4::Koha::GetNormalizedISBN($isbn); - my $sth = $dbh->prepare("INSERT INTO import_biblios (import_record_id, title, author, isbn, issn) VALUES (?, ?, ?, ?, ?)"); - $sth->execute($import_record_id, $title, $author, $isbn, $issn) or die $sth->errstr; + my $sth = $dbh->prepare( + "INSERT INTO import_biblios (import_record_id, title, author, isbn, issn) VALUES (?, ?, ?, ?, ?)"); + $sth->execute( $import_record_id, $title, $author, $isbn, $issn ) or die $sth->errstr; $sth->finish(); - + } sub _update_biblio_fields { - my ($import_record_id, $marc_record) = @_; + my ( $import_record_id, $marc_record ) = @_; - my ($title, $author, $isbn, $issn) = _parse_biblio_fields($marc_record); + my ( $title, $author, $isbn, $issn ) = _parse_biblio_fields($marc_record); my $dbh = C4::Context->dbh; + # FIXME no controlnumber, originalsource # FIXME 2 - should regularize normalization of ISBN wherever it is done $isbn =~ s/\(.*$//; $isbn =~ tr/ -_//; $isbn = uc $isbn; - my $sth = $dbh->prepare("UPDATE import_biblios SET title = ?, author = ?, isbn = ?, issn = ? - WHERE import_record_id = ?"); - $sth->execute($title, $author, $isbn, $issn, $import_record_id); + my $sth = $dbh->prepare( + "UPDATE import_biblios SET title = ?, author = ?, isbn = ?, issn = ? + WHERE import_record_id = ?" + ); + $sth->execute( $title, $author, $isbn, $issn, $import_record_id ); $sth->finish(); } sub _parse_biblio_fields { my ($marc_record) = @_; - my $dbh = C4::Context->dbh; - my $bibliofields = TransformMarcToKoha({ record => $marc_record, kohafields => ['biblio.title','biblio.author','biblioitems.isbn','biblioitems.issn'] }); - return ($bibliofields->{'title'}, $bibliofields->{'author'}, $bibliofields->{'isbn'}, $bibliofields->{'issn'}); + my $dbh = C4::Context->dbh; + my $bibliofields = TransformMarcToKoha( + { + record => $marc_record, + kohafields => [ 'biblio.title', 'biblio.author', 'biblioitems.isbn', 'biblioitems.issn' ] + } + ); + return ( $bibliofields->{'title'}, $bibliofields->{'author'}, $bibliofields->{'isbn'}, $bibliofields->{'issn'} ); } @@ -1701,17 +1793,21 @@ sub _update_batch_record_counts { my ($batch_id) = @_; my $dbh = C4::Context->dbh; - my ( $num_records ) = $dbh->selectrow_array(q| + my ($num_records) = $dbh->selectrow_array( + q| SELECT COUNT(*) FROM import_records WHERE import_batch_id = ? - |, undef, $batch_id ); - my ( $num_items ) = $dbh->selectrow_array(q| + |, undef, $batch_id + ); + my ($num_items) = $dbh->selectrow_array( + q| SELECT COUNT(*) FROM import_records JOIN import_items USING (import_record_id) WHERE import_batch_id = ? AND record_type = 'biblio' - |, undef, $batch_id ); + |, undef, $batch_id + ); $dbh->do( "UPDATE import_batches SET num_records=?, num_items=? WHERE import_batch_id=?", undef, @@ -1722,19 +1818,19 @@ sub _update_batch_record_counts { } sub _get_commit_action { - my ($overlay_action, $nomatch_action, $item_action, $overlay_status, $import_record_id, $record_type) = @_; - - if ($record_type eq 'biblio') { - my ($bib_result, $bib_match, $item_result); + my ( $overlay_action, $nomatch_action, $item_action, $overlay_status, $import_record_id, $record_type ) = @_; + + if ( $record_type eq 'biblio' ) { + my ( $bib_result, $bib_match, $item_result ); $bib_match = GetBestRecordMatch($import_record_id); - if ($overlay_status ne 'no_match' && defined($bib_match)) { + if ( $overlay_status ne 'no_match' && defined($bib_match) ) { $bib_result = $overlay_action; - if($item_action eq 'always_add' or $item_action eq 'add_only_for_matches'){ + if ( $item_action eq 'always_add' or $item_action eq 'add_only_for_matches' ) { $item_result = 'create_new'; - } elsif($item_action eq 'replace'){ + } elsif ( $item_action eq 'replace' ) { $item_result = 'replace'; } else { $item_result = 'ignore'; @@ -1742,36 +1838,37 @@ sub _get_commit_action { } else { $bib_result = $nomatch_action; - $item_result = ($item_action eq 'always_add' or $item_action eq 'add_only_for_new') ? 'create_new' : 'ignore'; + $item_result = + ( $item_action eq 'always_add' or $item_action eq 'add_only_for_new' ) ? 'create_new' : 'ignore'; } - return ($bib_result, $item_result, $bib_match); - } else { # must be auths - my ($auth_result, $auth_match); + return ( $bib_result, $item_result, $bib_match ); + } else { # must be auths + my ( $auth_result, $auth_match ); $auth_match = GetBestRecordMatch($import_record_id); - if ($overlay_status ne 'no_match' && defined($auth_match)) { + if ( $overlay_status ne 'no_match' && defined($auth_match) ) { $auth_result = $overlay_action; } else { $auth_result = $nomatch_action; } - return ($auth_result, undef, $auth_match); + return ( $auth_result, undef, $auth_match ); } } sub _get_revert_action { - my ($overlay_action, $overlay_status, $status) = @_; + my ( $overlay_action, $overlay_status, $status ) = @_; my $bib_result; - if ($status eq 'ignored') { + if ( $status eq 'ignored' ) { $bib_result = 'ignore'; } else { - if ($overlay_action eq 'create_new') { + if ( $overlay_action eq 'create_new' ) { $bib_result = 'delete'; } else { - $bib_result = ($overlay_status eq 'match_applied') ? 'restore' : 'delete'; + $bib_result = ( $overlay_status eq 'match_applied' ) ? 'restore' : 'delete'; } } return $bib_result; diff --git a/C4/ImportExportFramework.pm b/C4/ImportExportFramework.pm index ad626b679f..f6a7628bc7 100644 --- a/C4/ImportExportFramework.pm +++ b/C4/ImportExportFramework.pm @@ -29,10 +29,11 @@ use List::MoreUtils qw( indexes ); use C4::Context; use Koha::Logger; -our (@ISA, @EXPORT_OK); +our ( @ISA, @EXPORT_OK ); + BEGIN { require Exporter; - @ISA = qw(Exporter); + @ISA = qw(Exporter); @EXPORT_OK = qw( ExportFramework ImportFramework @@ -40,7 +41,6 @@ BEGIN { ); } - use constant XMLSTR => ' ' '; - use constant ODSSTR => ' @@ -82,7 +81,6 @@ use constant ODSSTR => ' '; - use constant ODS_STYLES_STR => ' @@ -91,7 +89,6 @@ use constant ODS_STYLES_STR => ' '; - use constant ODS_SETTINGS_STR => ' @@ -147,7 +144,6 @@ use constant ODS_SETTINGS_STR => ' '; - use constant ODS_MANIFEST_STR => ' @@ -168,7 +164,6 @@ use constant ODS_MANIFEST_STR => ' '; - =head1 NAME C4::ImportExportFramework - Import/Export Framework to Excel-xml/ODS Module Functions @@ -200,22 +195,21 @@ succes =cut -sub ExportFramework -{ - my ($frameworkcode, $xmlStrRef, $mode, $frameworktype) = @_; +sub ExportFramework { + my ( $frameworkcode, $xmlStrRef, $mode, $frameworktype ) = @_; my $dbh = C4::Context->dbh; if ($dbh) { my $dom; my $root; my $elementSS; - if ($mode eq 'ods' || $mode eq 'excel') { + if ( $mode eq 'ods' || $mode eq 'excel' ) { eval { my $parser = XML::LibXML->new(); - $dom = $parser->parse_string(($mode && $mode eq 'ods')?ODSSTR:XMLSTR); + $dom = $parser->parse_string( ( $mode && $mode eq 'ods' ) ? ODSSTR : XMLSTR ); if ($dom) { $root = $dom->documentElement(); - if ($mode && $mode eq 'ods') { + if ( $mode && $mode eq 'ods' ) { my $elementBody = $dom->createElement('office:body'); $root->appendChild($elementBody); $elementSS = $dom->createElement('office:spreadsheet'); @@ -229,65 +223,73 @@ sub ExportFramework } } - my $table = 'marc_tag_structure'; + my $table = 'marc_tag_structure'; my $subtable = 'marc_subfield_structure'; - if ($frameworktype eq "authority") { - $table = 'auth_tag_structure'; + if ( $frameworktype eq "authority" ) { + $table = 'auth_tag_structure'; $subtable = 'auth_subfield_structure'; } - if (_export_table($table, $dbh, ($mode eq 'csv')?$xmlStrRef:$dom, ($mode eq 'ods')?$elementSS:$root, $frameworkcode, $mode, $frameworktype)) { - if (_export_table($subtable, $dbh, ($mode eq 'csv')?$xmlStrRef:$dom, ($mode eq 'ods')?$elementSS:$root, $frameworkcode, $mode, $frameworktype)) { - $$xmlStrRef = $dom->toString(1) if ($mode eq 'ods' || $mode eq 'excel'); + if ( + _export_table( + $table, $dbh, ( $mode eq 'csv' ) ? $xmlStrRef : $dom, ( $mode eq 'ods' ) ? $elementSS : $root, + $frameworkcode, $mode, $frameworktype + ) + ) + { + if ( + _export_table( + $subtable, $dbh, ( $mode eq 'csv' ) ? $xmlStrRef : $dom, ( $mode eq 'ods' ) ? $elementSS : $root, + $frameworkcode, $mode, $frameworktype + ) + ) + { + $$xmlStrRef = $dom->toString(1) if ( $mode eq 'ods' || $mode eq 'excel' ); return 1; } } } return 0; -}#ExportFramework - - - +} #ExportFramework # Export all the data from a mysql table to an spreadsheet. -sub _export_table -{ - my ($table, $dbh, $dom, $root, $frameworkcode, $mode, $frameworktype) = @_; - if ($mode eq 'csv') { - _export_table_csv($table, $dbh, $dom, $root, $frameworkcode, $frameworktype); - } elsif ($mode eq 'ods') { - _export_table_ods($table, $dbh, $dom, $root, $frameworkcode, $frameworktype); +sub _export_table { + my ( $table, $dbh, $dom, $root, $frameworkcode, $mode, $frameworktype ) = @_; + if ( $mode eq 'csv' ) { + _export_table_csv( $table, $dbh, $dom, $root, $frameworkcode, $frameworktype ); + } elsif ( $mode eq 'ods' ) { + _export_table_ods( $table, $dbh, $dom, $root, $frameworkcode, $frameworktype ); } else { - _export_table_excel($table, $dbh, $dom, $root, $frameworkcode, $frameworktype); + _export_table_excel( $table, $dbh, $dom, $root, $frameworkcode, $frameworktype ); } } # Export the mysql table to an csv file -sub _export_table_csv -{ - my ($table, $dbh, $strCSV, $root, $frameworkcode, $frameworktype) = @_; +sub _export_table_csv { + my ( $table, $dbh, $strCSV, $root, $frameworkcode, $frameworktype ) = @_; eval { # First row with the name of the columns my $query = 'SHOW COLUMNS FROM ' . $table; - my $sth = $dbh->prepare($query); + my $sth = $dbh->prepare($query); $sth->execute(); my @fields = (); - while (my $hashRef = $sth->fetchrow_hashref) { + while ( my $hashRef = $sth->fetchrow_hashref ) { $$strCSV .= '"' . $hashRef->{Field} . '",'; push @fields, $hashRef->{Field}; } chop $$strCSV; $$strCSV .= chr(10); + # Populate rows with the data from mysql $query = 'SELECT * FROM ' . $table . ' WHERE frameworkcode=?'; - if ($frameworktype eq "authority") { + if ( $frameworktype eq "authority" ) { $query = 'SELECT * FROM ' . $table . ' WHERE authtypecode=?'; } $sth = $dbh->prepare($query); $sth->execute($frameworkcode); my $data; - while (my $hashRef = $sth->fetchrow_hashref) { + while ( my $hashRef = $sth->fetchrow_hashref ) { for my $field (@fields) { my $value = $hashRef->{$field} // q||; $value =~ s/[\r\n]//g; @@ -299,6 +301,7 @@ sub _export_table_csv } $$strCSV .= chr(10); for (@fields) { + # Separator for change of table $$strCSV .= '"#-#",'; } @@ -311,63 +314,63 @@ sub _export_table_csv return 0; } return 1; -}#_export_table_csv - +} #_export_table_csv # Export the mysql table to an ods file -sub _export_table_ods -{ - my ($table, $dbh, $dom, $root, $frameworkcode, $frameworktype) = @_; +sub _export_table_ods { + my ( $table, $dbh, $dom, $root, $frameworkcode, $frameworktype ) = @_; eval { my $elementTable = $dom->createElement('table:table'); - $elementTable->setAttribute('table:name', $table); - $elementTable->setAttribute('table:print', 'false'); + $elementTable->setAttribute( 'table:name', $table ); + $elementTable->setAttribute( 'table:print', 'false' ); $root->appendChild($elementTable); my $elementRow = $dom->createElement('table:table-row'); $elementTable->appendChild($elementRow); my $elementCell; my $elementData; + # First row with the name of the columns my $query = 'SHOW COLUMNS FROM ' . $table; - my $sth = $dbh->prepare($query); + my $sth = $dbh->prepare($query); $sth->execute(); my @fields = (); - while (my $hashRef = $sth->fetchrow_hashref) { + while ( my $hashRef = $sth->fetchrow_hashref ) { $elementCell = $dom->createElement('table:table-cell'); - $elementCell->setAttribute('office:value-type', 'string'); - $elementCell->setAttribute('office:value', $hashRef->{Field}); + $elementCell->setAttribute( 'office:value-type', 'string' ); + $elementCell->setAttribute( 'office:value', $hashRef->{Field} ); $elementRow->appendChild($elementCell); $elementData = $dom->createElement('text:p'); $elementCell->appendChild($elementData); - $elementData->appendTextNode($hashRef->{Field}); - push @fields, {name => $hashRef->{Field}, type => ($hashRef->{Type} =~ /int/i)?'float':'string'}; + $elementData->appendTextNode( $hashRef->{Field} ); + push @fields, { name => $hashRef->{Field}, type => ( $hashRef->{Type} =~ /int/i ) ? 'float' : 'string' }; } + # Populate rows with the data from mysql $query = 'SELECT * FROM ' . $table . ' WHERE frameworkcode=?'; - if ($frameworktype eq "authority") { + if ( $frameworktype eq "authority" ) { $query = 'SELECT * FROM ' . $table . ' WHERE authtypecode=?'; } $sth = $dbh->prepare($query); $sth->execute($frameworkcode); my $data; - while (my $hashRef = $sth->fetchrow_hashref) { + while ( my $hashRef = $sth->fetchrow_hashref ) { $elementRow = $dom->createElement('table:table-row'); $elementTable->appendChild($elementRow); for (@fields) { - $data = $hashRef->{$_->{name}}; - if ($_->{type} eq 'float' && !defined($data)) { + $data = $hashRef->{ $_->{name} }; + if ( $_->{type} eq 'float' && !defined($data) ) { $data = '0'; - } elsif ($_->{type} eq 'string' && !defined($data)) { + } elsif ( $_->{type} eq 'string' && !defined($data) ) { $data = q{}; - } elsif ($_->{type} eq 'string' && (!$data && $data ne '0')) { + } elsif ( $_->{type} eq 'string' && ( !$data && $data ne '0' ) ) { $data = '#'; } - $data = _parseContent2Xml($data) if ($_->{type} eq 'string'); + $data = _parseContent2Xml($data) if ( $_->{type} eq 'string' ); $elementCell = $dom->createElement('table:table-cell'); - $elementCell->setAttribute('office:value-type', $_->{type}); - $elementCell->setAttribute('office:value', $data); + $elementCell->setAttribute( 'office:value-type', $_->{type} ); + $elementCell->setAttribute( 'office:value', $data ); $elementRow->appendChild($elementCell); $elementData = $dom->createElement('text:p'); $elementCell->appendChild($elementData); @@ -380,17 +383,15 @@ sub _export_table_ods return 0; } return 1; -}#_export_table_ods - +} #_export_table_ods # Export the mysql table to an excel-xml (openoffice/libreoffice compatible) file -sub _export_table_excel -{ - my ($table, $dbh, $dom, $root, $frameworkcode, $frameworktype) = @_; +sub _export_table_excel { + my ( $table, $dbh, $dom, $root, $frameworkcode, $frameworktype ) = @_; eval { my $elementWS = $dom->createElement('Worksheet'); - $elementWS->setAttribute('ss:Name', $table); + $elementWS->setAttribute( 'ss:Name', $table ); $root->appendChild($elementWS); my $elementTable = $dom->createElement('ss:Table'); $elementWS->appendChild($elementTable); @@ -401,45 +402,46 @@ sub _export_table_excel my $elementCell; my $elementData; my $query = 'SHOW COLUMNS FROM ' . $table; - my $sth = $dbh->prepare($query); + my $sth = $dbh->prepare($query); $sth->execute(); my @fields = (); - while (my $hashRef = $sth->fetchrow_hashref) { + while ( my $hashRef = $sth->fetchrow_hashref ) { $elementCell = $dom->createElement('ss:Cell'); - $elementCell->setAttribute('ss:StyleID', 's27'); + $elementCell->setAttribute( 'ss:StyleID', 's27' ); $elementRow->appendChild($elementCell); $elementData = $dom->createElement('ss:Data'); - $elementData->setAttribute('ss:Type', 'String'); + $elementData->setAttribute( 'ss:Type', 'String' ); $elementCell->appendChild($elementData); - $elementData->appendTextNode($hashRef->{Field}); - push @fields, {name => $hashRef->{Field}, type => ($hashRef->{Type} =~ /int/i)?'Number':'String'}; + $elementData->appendTextNode( $hashRef->{Field} ); + push @fields, { name => $hashRef->{Field}, type => ( $hashRef->{Type} =~ /int/i ) ? 'Number' : 'String' }; } + # Populate rows with the data from mysql $query = 'SELECT * FROM ' . $table . ' WHERE frameworkcode=?'; - if ($frameworktype eq "authority") { + if ( $frameworktype eq "authority" ) { $query = 'SELECT * FROM ' . $table . ' WHERE authtypecode=?'; } $sth = $dbh->prepare($query); $sth->execute($frameworkcode); my $data; - while (my $hashRef = $sth->fetchrow_hashref) { + while ( my $hashRef = $sth->fetchrow_hashref ) { $elementRow = $dom->createElement('ss:Row'); $elementTable->appendChild($elementRow); for (@fields) { $elementCell = $dom->createElement('ss:Cell'); $elementRow->appendChild($elementCell); $elementData = $dom->createElement('ss:Data'); - $elementData->setAttribute('ss:Type', $_->{type}); + $elementData->setAttribute( 'ss:Type', $_->{type} ); $elementCell->appendChild($elementData); - $data = $hashRef->{$_->{name}}; - if ($_->{type} eq 'Number' && !defined($data)) { + $data = $hashRef->{ $_->{name} }; + if ( $_->{type} eq 'Number' && !defined($data) ) { $data = '0'; - } elsif ($_->{type} eq 'String' && !defined($data)) { + } elsif ( $_->{type} eq 'String' && !defined($data) ) { $data = q{}; - } elsif ($_->{type} eq 'String' && (!$data && $data ne '0')) { + } elsif ( $_->{type} eq 'String' && ( !$data && $data ne '0' ) ) { $data = '#'; } - $elementData->appendTextNode(($_->{type} eq 'String')?_parseContent2Xml($data):$data); + $elementData->appendTextNode( ( $_->{type} eq 'String' ) ? _parseContent2Xml($data) : $data ); } } }; @@ -448,51 +450,44 @@ sub _export_table_excel return 0; } return 1; -}#_export_table_excel +} #_export_table_excel # Format chars problematics to a correct format for xml. -sub _parseContent2Xml -{ +sub _parseContent2Xml { my $content = shift; $content =~ s/\&(?![a-zA-Z#0-9]{1,4};)/&/g; $content =~ s//>/g; return $content; -}#_parseContent2Xml - +} #_parseContent2Xml # Get the tmp directory on the system -sub _getTmp -{ +sub _getTmp { my $tmp = '/tmp'; - if ($ENV{'TMP'} && -d $ENV{'TMP'}) { + if ( $ENV{'TMP'} && -d $ENV{'TMP'} ) { $tmp = $ENV{'TMP'}; - } elsif ($ENV{'TMPDIR'} && -d $ENV{'TMPDIR'}) { + } elsif ( $ENV{'TMPDIR'} && -d $ENV{'TMPDIR'} ) { $tmp = $ENV{'TMPDIR'}; - } elsif ($ENV{'TEMP'} && -d $ENV{'TEMP'}) { + } elsif ( $ENV{'TEMP'} && -d $ENV{'TEMP'} ) { $tmp = $ENV{'TEMP'}; } return $tmp; -}#_getTmp - +} #_getTmp # Create our tempdir directory for the ods process -sub _createTmpDir -{ +sub _createTmpDir { my $tmp = shift; - my $tempdir = (-d $tmp)?$tmp . '/':'./'; - $tempdir .= 'tmp_ods_' . Digest::MD5::md5_hex(Digest::MD5::md5_hex(time().{}.rand().{}.$$)); - eval { - mkdir $tempdir; - }; + my $tempdir = ( -d $tmp ) ? $tmp . '/' : './'; + $tempdir .= 'tmp_ods_' . Digest::MD5::md5_hex( Digest::MD5::md5_hex( time() . {} . rand() . {} . $$ ) ); + eval { mkdir $tempdir; }; if ($@) { return; } else { return $tempdir; } -}#_createTmpDir +} #_createTmpDir =head2 createODS @@ -503,58 +498,58 @@ success =cut -sub createODS -{ - my ($strContent, $lang, $strODSRef) = @_; +sub createODS { + my ( $strContent, $lang, $strODSRef ) = @_; - my $tmp = _getTmp(); + my $tmp = _getTmp(); my $tempModule = 1; my $tempdir; eval { require File::Temp; import File::Temp qw/ tempfile tempdir /; - $tempdir = tempdir ( 'tmp_ods_' . $$ . '_XXXXXXXX', DIR => (-d $tmp)?$tmp:'.', CLEANUP => 1); + $tempdir = tempdir( 'tmp_ods_' . $$ . '_XXXXXXXX', DIR => ( -d $tmp ) ? $tmp : '.', CLEANUP => 1 ); }; if ($@) { $tempModule = 0; - $tempdir = _createTmpDir($tmp); + $tempdir = _createTmpDir($tmp); } if ($tempdir) { my $fh; + # populate tempdir directory with the ods elements eval { - if (open($fh, '>', "$tempdir/content.xml")) { + if ( open( $fh, '>', "$tempdir/content.xml" ) ) { print {$fh} $strContent; close($fh); } - if (open($fh, '>', "$tempdir/mimetype")) { + if ( open( $fh, '>', "$tempdir/mimetype" ) ) { print {$fh} 'application/vnd.oasis.opendocument.spreadsheet'; close($fh); } - if (open($fh, '>', "$tempdir/meta.xml")) { + if ( open( $fh, '>', "$tempdir/meta.xml" ) ) { print {$fh} _getMeta($lang); close($fh); } - if (open($fh, '>', "$tempdir/styles.xml")) { + if ( open( $fh, '>', "$tempdir/styles.xml" ) ) { print {$fh} ODS_STYLES_STR; close($fh); } - if (open($fh, '>', "$tempdir/settings.xml")) { + if ( open( $fh, '>', "$tempdir/settings.xml" ) ) { print {$fh} ODS_SETTINGS_STR; close($fh); } - mkdir($tempdir.'/META-INF/'); - mkdir($tempdir.'/Configurations2/'); - mkdir($tempdir.'/Configurations2/acceleator/'); - mkdir($tempdir.'/Configurations2/images/'); - mkdir($tempdir.'/Configurations2/popupmenu/'); - mkdir($tempdir.'/Configurations2/statusbar/'); - mkdir($tempdir.'/Configurations2/floater/'); - mkdir($tempdir.'/Configurations2/menubar/'); - mkdir($tempdir.'/Configurations2/progressbar/'); - mkdir($tempdir.'/Configurations2/toolbar/'); + mkdir( $tempdir . '/META-INF/' ); + mkdir( $tempdir . '/Configurations2/' ); + mkdir( $tempdir . '/Configurations2/acceleator/' ); + mkdir( $tempdir . '/Configurations2/images/' ); + mkdir( $tempdir . '/Configurations2/popupmenu/' ); + mkdir( $tempdir . '/Configurations2/statusbar/' ); + mkdir( $tempdir . '/Configurations2/floater/' ); + mkdir( $tempdir . '/Configurations2/menubar/' ); + mkdir( $tempdir . '/Configurations2/progressbar/' ); + mkdir( $tempdir . '/Configurations2/toolbar/' ); - if (open($fh, '>', "$tempdir/META-INF/manifest.xml")) { + if ( open( $fh, '>', "$tempdir/META-INF/manifest.xml" ) ) { print {$fh} ODS_MANIFEST_STR; close($fh); } @@ -562,35 +557,38 @@ sub createODS if ($@) { Koha::Logger->get->warn("Error createODS $@"); } else { + # create ods file from tempdir directory eval { require Archive::Zip; import Archive::Zip qw( :ERROR_CODES :CONSTANTS ); my $zip = Archive::Zip->new(); $zip->addTree( $tempdir, '' ); - $zip->writeToFileNamed($tempdir . '/new.ods'); + $zip->writeToFileNamed( $tempdir . '/new.ods' ); }; if ($@) { my $cmd = qx(which zip 2>/dev/null || whereis zip); chomp $cmd; - $cmd = 'zip' if (!$cmd || !-x $cmd); + $cmd = 'zip' if ( !$cmd || !-x $cmd ); system("cd $tempdir && $cmd -r new.ods ./"); } my $ok = 0; + # read ods file and return as a string - if (-f "$tempdir/new.ods") { - if (open ($fh, '<', "$tempdir/new.ods")) { + if ( -f "$tempdir/new.ods" ) { + if ( open( $fh, '<', "$tempdir/new.ods" ) ) { binmode $fh; my $buffer; - while (read ($fh, $buffer, 65536)) { + while ( read( $fh, $buffer, 65536 ) ) { $$strODSRef .= $buffer; } close($fh); $ok = 1; } } + # delete tempdir directory - if (!$tempModule && $tempdir) { + if ( !$tempModule && $tempdir ) { eval { require File::Path; import File::Temp qw/ rmtree /; @@ -604,16 +602,14 @@ sub createODS } } return 0; -}#createODS - +} #createODS # return Meta content for ods file -sub _getMeta -{ +sub _getMeta { my $lang = shift; - my $myDate = strftime ("%Y-%m-%dT%H:%M:%S", localtime(time())); - my $meta = ' + my $myDate = strftime( "%Y-%m-%dT%H:%M:%S", localtime( time() ) ); + my $meta = ' ods-php @@ -629,8 +625,7 @@ sub _getMeta '; return $meta; -}#_getMeta - +} #_getMeta =head2 ImportFramework @@ -641,29 +636,29 @@ success =cut -sub ImportFramework -{ - my ($filename, $frameworkcode, $deleteFilename, $frameworktype) = @_; +sub ImportFramework { + my ( $filename, $frameworkcode, $deleteFilename, $frameworktype ) = @_; my $tempdir; - my $ok = -1; + my $ok = -1; my $dbh = C4::Context->dbh; $frameworktype ||= ''; - if (-r $filename && $dbh) { + if ( -r $filename && $dbh ) { my $extension = ''; - if ($filename =~ /\.(csv|ods|xml)$/i) { + if ( $filename =~ /\.(csv|ods|xml)$/i ) { $extension = lc($1); } else { - unlink ($filename) if ($deleteFilename); # remove temporary file + unlink($filename) if ($deleteFilename); # remove temporary file return -1; } - if ($extension eq 'ods') { - ($tempdir, $filename) = _openODS($filename, $deleteFilename); + if ( $extension eq 'ods' ) { + ( $tempdir, $filename ) = _openODS( $filename, $deleteFilename ); } if ($filename) { my $dom; eval { - if ($extension eq 'ods' || $extension eq 'xml') { + if ( $extension eq 'ods' || $extension eq 'xml' ) { + # They have xml structure, so read it on a dom object my $parser = XML::LibXML->new(); $dom = $parser->parse_file($filename); @@ -671,35 +666,69 @@ sub ImportFramework my $root = $dom->documentElement(); } } else { + # They are text files, so open it to read - open($dom, '<', $filename); + open( $dom, '<', $filename ); } - my $table = 'marc_tag_structure'; + my $table = 'marc_tag_structure'; my $subtable = 'marc_subfield_structure'; - if ($frameworktype eq "authority") { - $table = 'auth_tag_structure'; + if ( $frameworktype eq "authority" ) { + $table = 'auth_tag_structure'; $subtable = 'auth_subfield_structure'; } if ($dom) { + # Process both tables - my $numDeleted = 0; + my $numDeleted = 0; my $numDeletedAux = 0; - if ($frameworktype eq "authority"){ - if (($numDeletedAux = _import_table($dbh, $table, $frameworkcode, $dom, ['authtypecode', 'tagfield'], $extension, $frameworktype)) >= 0) { - $numDeleted += $numDeletedAux if ($numDeletedAux > 0); - if (($numDeletedAux = _import_table($dbh, $subtable, $frameworkcode, $dom, ['authtypecode', 'tagfield', 'tagsubfield'], $extension, $frameworktype)) >= 0) { - $numDeleted += $numDeletedAux if ($numDeletedAux > 0); - $ok = ($numDeleted > 0)?$numDeleted:0; + if ( $frameworktype eq "authority" ) { + if ( + ( + $numDeletedAux = _import_table( + $dbh, $table, $frameworkcode, $dom, [ 'authtypecode', 'tagfield' ], $extension, + $frameworktype + ) + ) >= 0 + ) + { + $numDeleted += $numDeletedAux if ( $numDeletedAux > 0 ); + if ( + ( + $numDeletedAux = _import_table( + $dbh, $subtable, $frameworkcode, $dom, + [ 'authtypecode', 'tagfield', 'tagsubfield' ], $extension, $frameworktype + ) + ) >= 0 + ) + { + $numDeleted += $numDeletedAux if ( $numDeletedAux > 0 ); + $ok = ( $numDeleted > 0 ) ? $numDeleted : 0; } } } else { - if (($numDeletedAux = _import_table($dbh, $table, $frameworkcode, $dom, ['frameworkcode', 'tagfield'], $extension, $frameworktype)) >= 0) { - $numDeleted += $numDeletedAux if ($numDeletedAux > 0); - if (($numDeletedAux = _import_table($dbh, $subtable, $frameworkcode, $dom, ['frameworkcode', 'tagfield', 'tagsubfield'], $extension, $frameworktype)) >= 0) { - $numDeleted += $numDeletedAux if ($numDeletedAux > 0); - $ok = ($numDeleted > 0)?$numDeleted:0; + if ( + ( + $numDeletedAux = _import_table( + $dbh, $table, $frameworkcode, $dom, [ 'frameworkcode', 'tagfield' ], $extension, + $frameworktype + ) + ) >= 0 + ) + { + $numDeleted += $numDeletedAux if ( $numDeletedAux > 0 ); + if ( + ( + $numDeletedAux = _import_table( + $dbh, $subtable, $frameworkcode, $dom, + [ 'frameworkcode', 'tagfield', 'tagsubfield' ], $extension, $frameworktype + ) + ) >= 0 + ) + { + $numDeleted += $numDeletedAux if ( $numDeletedAux > 0 ); + $ok = ( $numDeleted > 0 ) ? $numDeleted : 0; } } } @@ -710,16 +739,16 @@ sub ImportFramework if ($@) { Koha::Logger->get->warn("Error ImportFramework $@"); } else { - if ($extension eq 'csv') { + if ( $extension eq 'csv' ) { close($dom) if ($dom); } } } - unlink ($filename) if ($deleteFilename); # remove temporary file + unlink($filename) if ($deleteFilename); # remove temporary file } else { Koha::Logger->get->warn("Error ImportFramework no conex to database or not readeable $filename"); } - if ($deleteFilename && $tempdir && -d $tempdir && -w $tempdir) { + if ( $deleteFilename && $tempdir && -d $tempdir && -w $tempdir ) { eval { require File::Path; import File::Temp qw/ rmtree /; @@ -730,71 +759,68 @@ sub ImportFramework } } return $ok; -}#ImportFramework +} #ImportFramework # Open (uncompress) ods file and return the content.xml file -sub _openODS -{ - my ($filename, $deleteFilename) = @_; +sub _openODS { + my ( $filename, $deleteFilename ) = @_; - my $tmp = _getTmp(); + my $tmp = _getTmp(); my $tempModule = 1; my $tempdir; eval { require File::Temp; import File::Temp qw/ tempfile tempdir /; - $tempdir = tempdir ( 'tmp_ods_' . $$ . '_XXXXXXXX', DIR => (-d $tmp)?$tmp:'.', CLEANUP => 1); + $tempdir = tempdir( 'tmp_ods_' . $$ . '_XXXXXXXX', DIR => ( -d $tmp ) ? $tmp : '.', CLEANUP => 1 ); }; if ($@) { $tempModule = 0; - $tempdir = _createTmpDir($tmp); + $tempdir = _createTmpDir($tmp); } if ($tempdir) { eval { require Archive::Zip; import Archive::Zip qw( :ERROR_CODES :CONSTANTS ); my $zip = Archive::Zip->new($filename); - foreach my $file ($zip->members) { - next if ($file->isDirectory); - (my $extractName = $file->fileName) =~ s{.*/}{}; - next unless ($extractName eq 'content.xml'); + foreach my $file ( $zip->members ) { + next if ( $file->isDirectory ); + ( my $extractName = $file->fileName ) =~ s{.*/}{}; + next unless ( $extractName eq 'content.xml' ); $file->extractToFileNamed("$tempdir/$extractName"); } }; if ($@) { my $cmd = qx(which unzip 2>/dev/null || whereis unzip); chomp $cmd; - $cmd = 'unzip' if (!$cmd || !-x $cmd); + $cmd = 'unzip' if ( !$cmd || !-x $cmd ); system("$cmd $filename -d $tempdir"); } - if (-f "$tempdir/content.xml") { - unlink ($filename) if ($deleteFilename); - return ($tempdir, "$tempdir/content.xml"); + if ( -f "$tempdir/content.xml" ) { + unlink($filename) if ($deleteFilename); + return ( $tempdir, "$tempdir/content.xml" ); } } - unlink ($filename) if ($deleteFilename); - return ($tempdir, undef); -}#_openODS - - + unlink($filename) if ($deleteFilename); + return ( $tempdir, undef ); +} #_openODS # Check the table and columns corresponds with worksheet -sub _check_validity_worksheet -{ - my ($dbh, $table, $nodeFields, $fieldsA, $format) = @_; +sub _check_validity_worksheet { + my ( $dbh, $table, $nodeFields, $fieldsA, $format ) = @_; my $ret = 0; eval { my $query = 'DESCRIBE ' . $table; - my $sth = $dbh->prepare($query); + my $sth = $dbh->prepare($query); $sth->execute(); $sth->finish; $query = 'SHOW COLUMNS FROM ' . $table; - $sth = $dbh->prepare($query); + $sth = $dbh->prepare($query); $sth->execute(); my $fields = {}; - while (my $hashRef = $sth->fetchrow_hashref) { - $fields->{$hashRef->{Field}} = $hashRef->{Field}; + + while ( my $hashRef = $sth->fetchrow_hashref ) { + $fields->{ $hashRef->{Field} } = $hashRef->{Field}; } my @fields; my $fieldsR; @@ -802,40 +828,39 @@ sub _check_validity_worksheet $fieldsR = $fieldsA; } else { $fieldsR = \@fields; - _getFields($nodeFields, $fieldsR, $format); + _getFields( $nodeFields, $fieldsR, $format ); } $ret = 1; for (@$fieldsR) { - unless (exists($fields->{$_})) { + unless ( exists( $fields->{$_} ) ) { $ret = 0; last; } } }; return $ret; -}#_check_validity_worksheet - +} #_check_validity_worksheet # Import the data from an excel-xml/ods to mysql tables. -sub _import_table -{ - my ($dbh, $table, $frameworkcode, $dom, $PKArray, $format, $frameworktype) = @_; +sub _import_table { + my ( $dbh, $table, $frameworkcode, $dom, $PKArray, $format, $frameworktype ) = @_; my %fields2Delete; my $query; my @fields; $frameworktype ||= ''; + # Create hash with all elements defined by primary key to know which ones to delete after parsing the spreadsheet eval { @fields = @$PKArray; shift @fields; - $query = 'SELECT ' . join(',', @fields) . ' FROM ' . $table . ' WHERE frameworkcode=?'; - if ($frameworktype eq "authority") { - $query = 'SELECT ' . join(',', @fields) . ' FROM ' . $table . ' WHERE authtypecode=?'; + $query = 'SELECT ' . join( ',', @fields ) . ' FROM ' . $table . ' WHERE frameworkcode=?'; + if ( $frameworktype eq "authority" ) { + $query = 'SELECT ' . join( ',', @fields ) . ' FROM ' . $table . ' WHERE authtypecode=?'; } my $sth = $dbh->prepare($query); $sth->execute($frameworkcode); my $field; - while (my $hashRef = $sth->fetchrow_hashref) { + while ( my $hashRef = $sth->fetchrow_hashref ) { $field = ''; map { $field .= $hashRef->{$_} . '_'; } @fields; chop $field; @@ -844,52 +869,55 @@ sub _import_table $sth->finish; }; my $ok = 0; - if ($format eq 'csv') { + if ( $format eq 'csv' ) { my @fieldsName = (); eval { my $query = 'SHOW COLUMNS FROM ' . $table; - my $sth = $dbh->prepare($query); + my $sth = $dbh->prepare($query); $sth->execute(); - while (my $hashRef = $sth->fetchrow_hashref) { + while ( my $hashRef = $sth->fetchrow_hashref ) { push @fieldsName, $hashRef->{Field}; } }; - $ok = _import_table_csv($dbh, $table, $frameworkcode, $dom, $PKArray, \%fields2Delete, \@fieldsName, $frameworktype); - } elsif ($format eq 'ods') { - $ok = _import_table_ods($dbh, $table, $frameworkcode, $dom, $PKArray, \%fields2Delete, $frameworktype); + $ok = _import_table_csv( + $dbh, $table, $frameworkcode, $dom, $PKArray, \%fields2Delete, \@fieldsName, + $frameworktype + ); + } elsif ( $format eq 'ods' ) { + $ok = _import_table_ods( $dbh, $table, $frameworkcode, $dom, $PKArray, \%fields2Delete, $frameworktype ); } else { - $ok = _import_table_excel($dbh, $table, $frameworkcode, $dom, $PKArray, \%fields2Delete, $frameworktype); + $ok = _import_table_excel( $dbh, $table, $frameworkcode, $dom, $PKArray, \%fields2Delete, $frameworktype ); } if ($ok) { - if (($ok = scalar(keys %fields2Delete)) > 0) { + if ( ( $ok = scalar( keys %fields2Delete ) ) > 0 ) { $query = 'DELETE FROM ' . $table . ' WHERE '; - map {$query .= $_ . '=? AND ';} @$PKArray; - $query = substr($query, 0, -4); + map { $query .= $_ . '=? AND '; } @$PKArray; + $query = substr( $query, 0, -4 ); my $sth = $dbh->prepare($query); - for (keys %fields2Delete) { - eval { - $sth->execute(($frameworkcode, split('_', $_))); - }; + for ( keys %fields2Delete ) { + eval { $sth->execute( ( $frameworkcode, split( '_', $_ ) ) ); }; } } } else { $ok = -1; } return $ok; -}#_import_table - +} #_import_table # Insert/Update the row from the spreadsheet in the database -sub _processRow_DB -{ - my ($dbh, $table, $fields, $dataStr, $updateStr, $dataFields, $dataFieldsHash, $PKArray, $fieldsPK, $fields2Delete) = @_; +sub _processRow_DB { + my ( + $dbh, $table, $fields, $dataStr, $updateStr, $dataFields, $dataFieldsHash, $PKArray, $fieldsPK, + $fields2Delete + ) = @_; my $ok = 0; my $query; - $query = 'INSERT INTO ' . $table . ' (' . $fields . ') VALUES (' . $dataStr . ') ON DUPLICATE KEY UPDATE ' . $updateStr; + $query = + 'INSERT INTO ' . $table . ' (' . $fields . ') VALUES (' . $dataStr . ') ON DUPLICATE KEY UPDATE ' . $updateStr; eval { my $sth = $dbh->prepare($query); - $sth->execute((@$dataFields, @$dataFields)); + $sth->execute( ( @$dataFields, @$dataFields ) ); }; if ($@) { Koha::Logger->get->warn("Error _processRow_DB $@"); @@ -900,46 +928,60 @@ sub _processRow_DB my $field = ''; map { $field .= $dataFieldsHash->{$_} . '_'; } @$fieldsPK; chop $field; - delete $fields2Delete->{$field} if (exists($fields2Delete->{$field})); + delete $fields2Delete->{$field} if ( exists( $fields2Delete->{$field} ) ); } return $ok; -}#_processRow_DB - +} #_processRow_DB # Process the rows of a worksheet and insert/update them in a mysql table. -sub _processRows_Table -{ - my ($dbh, $frameworkcode, $nodeR, $table, $PKArray, $format, $fields2Delete, $frameworktype) = @_; +sub _processRows_Table { + my ( $dbh, $frameworkcode, $nodeR, $table, $PKArray, $format, $fields2Delete, $frameworktype ) = @_; my $query; - my @fields = (); - my $fields = ''; - my $dataStr = ''; + my @fields = (); + my $fields = ''; + my $dataStr = ''; my $updateStr = ''; - my $j = 0; - my $ok = 0; - my @fieldsPK = @$PKArray; + my $j = 0; + my $ok = 0; + my @fieldsPK = @$PKArray; shift @fieldsPK; + while ($nodeR) { - if ($nodeR->nodeType == 1 && (($format && $format eq 'ods' && $nodeR->nodeName =~ /(?:table:)?table-row/) || ($nodeR->nodeName =~ /(?:ss:)?Row/)) && $nodeR->hasChildNodes()) { - if ($j == 0) { + if ( + $nodeR->nodeType == 1 + && ( ( $format && $format eq 'ods' && $nodeR->nodeName =~ /(?:table:)?table-row/ ) + || ( $nodeR->nodeName =~ /(?:ss:)?Row/ ) ) + && $nodeR->hasChildNodes() + ) + { + if ( $j == 0 ) { + # Get name columns - _getFields($nodeR, \@fields, $format); - return 0 unless _check_validity_worksheet($dbh, $table, $nodeR, \@fields, $format); - $fields = join(',', @fields); + _getFields( $nodeR, \@fields, $format ); + return 0 unless _check_validity_worksheet( $dbh, $table, $nodeR, \@fields, $format ); + $fields = join( ',', @fields ); $dataStr = ''; - map { $dataStr .= '?,';} @fields; + map { $dataStr .= '?,'; } @fields; chop($dataStr) if ($dataStr); $updateStr = ''; - map { $updateStr .= $_ . '=?,';} @fields; + map { $updateStr .= $_ . '=?,'; } @fields; chop($updateStr) if ($updateStr); } else { + # Get data from row - my ($dataFields, $dataFieldsR) = _getDataFields($frameworkcode, $nodeR, \@fields, $format, $frameworktype); - if (scalar(@fields) == scalar(@$dataFieldsR)) { - $ok = _processRow_DB($dbh, $table, $fields, $dataStr, $updateStr, $dataFieldsR, $dataFields, $PKArray, \@fieldsPK, $fields2Delete); + my ( $dataFields, $dataFieldsR ) = + _getDataFields( $frameworkcode, $nodeR, \@fields, $format, $frameworktype ); + if ( scalar(@fields) == scalar(@$dataFieldsR) ) { + $ok = _processRow_DB( + $dbh, $table, $fields, $dataStr, $updateStr, $dataFieldsR, $dataFields, + $PKArray, \@fieldsPK, $fields2Delete + ); } else { - warn "$j don't match number of fields " . scalar(@fields) . ' vs ' . scalar(@$dataFieldsR) . "($dataStr)"; + warn "$j don't match number of fields " + . scalar(@fields) . ' vs ' + . scalar(@$dataFieldsR) + . "($dataStr)"; } } $j++; @@ -947,244 +989,246 @@ sub _processRows_Table $nodeR = $nodeR->nextSibling; } return 1; -}#_processRows_Table - - - +} #_processRows_Table # Import worksheet from the csv file to the mysql table -sub _import_table_csv -{ - my ($dbh, $table, $frameworkcode, $dom, $PKArray, $fields2Delete, $fields, $frameworktype) = @_; - my $row = ''; - my $partialRow = ''; - my $numFields = @$fields; +sub _import_table_csv { + my ( $dbh, $table, $frameworkcode, $dom, $PKArray, $fields2Delete, $fields, $frameworktype ) = @_; + my $row = ''; + my $partialRow = ''; + my $numFields = @$fields; my $fieldsNameRead = 0; my @arrData; - my ($fieldsStr, $dataStr, $updateStr, @empty_indexes); + my ( $fieldsStr, $dataStr, $updateStr, @empty_indexes ); my @fieldsPK = @$PKArray; shift @fieldsPK; - my $ok = 0; + my $ok = 0; my $pos = 0; my $csv = Text::CSV_XS->new( { binary => 1, formula => "empty" } ); + while ( my $row = $csv->getline($dom) ) { my @fields = @$row; @arrData = @fields; - next if scalar @arrData == grep { $_ eq '' } @arrData; # Emtpy lines - #$arrData[0] = substr($arrData[0], 1) if ($arrData[0] =~ /^"/); - #$arrData[$#arrData] =~ s/[\r\n]+$//; - #chop $arrData[$#arrData] if ($arrData[$#arrData] =~ /"$/); + next if scalar @arrData == grep { $_ eq '' } @arrData; # Emtpy lines + #$arrData[0] = substr($arrData[0], 1) if ($arrData[0] =~ /^"/); + #$arrData[$#arrData] =~ s/[\r\n]+$//; + #chop $arrData[$#arrData] if ($arrData[$#arrData] =~ /"$/); if (@arrData) { - if ($arrData[0] eq '#-#' && $arrData[$#arrData] eq '#-#') { + if ( $arrData[0] eq '#-#' && $arrData[$#arrData] eq '#-#' ) { + # Change of table with separators #-# return 1; - } elsif ($fieldsNameRead && $arrData[0] eq 'tagfield') { + } elsif ( $fieldsNameRead && $arrData[0] eq 'tagfield' ) { + # Change of table because we begin with field name with former field names read - seek($dom, $pos, 0); + seek( $dom, $pos, 0 ); return 1; } - if (!$fieldsNameRead) { + if ( !$fieldsNameRead ) { + # New table, we read the field names $fieldsNameRead = 1; - $fields = [@arrData]; + $fields = [@arrData]; my $non_empty_fields = [ grep { $_ ne '' } @$fields ]; @empty_indexes = indexes { $_ eq '' } @$fields; - $fieldsStr = join(',', @$non_empty_fields); - $dataStr = ''; - map { $dataStr .= '?,';} @$non_empty_fields; + $fieldsStr = join( ',', @$non_empty_fields ); + $dataStr = ''; + map { $dataStr .= '?,'; } @$non_empty_fields; chop($dataStr) if ($dataStr); $updateStr = ''; - map { $updateStr .= $_ . '=?,';} @$non_empty_fields; + map { $updateStr .= $_ . '=?,'; } @$non_empty_fields; chop($updateStr) if ($updateStr); } else { + # Read data - my $j = 0; + my $j = 0; my %dataFields = (); my @values; for my $value (@arrData) { if ( grep { $_ == $j } @empty_indexes ) { + # empty field - } elsif ($frameworktype eq "authority"){ - if ($fields->[$j] eq 'authtypecode' && $value ne $frameworkcode) { - $dataFields{$fields->[$j]} = $frameworkcode; + } elsif ( $frameworktype eq "authority" ) { + if ( $fields->[$j] eq 'authtypecode' && $value ne $frameworkcode ) { + $dataFields{ $fields->[$j] } = $frameworkcode; push @values, $frameworkcode; - } elsif ($fields->[$j] eq 'isurl' && defined $value && $value eq q{}) { - $dataFields{$fields->[$j]} = undef; + } elsif ( $fields->[$j] eq 'isurl' && defined $value && $value eq q{} ) { + $dataFields{ $fields->[$j] } = undef; push @values, undef; } else { - $dataFields{$fields->[$j]} = $value; + $dataFields{ $fields->[$j] } = $value; push @values, $value; } - $j++ + $j++; } else { - if ($fields->[$j] eq 'frameworkcode' && $value ne $frameworkcode) { - $dataFields{$fields->[$j]} = $frameworkcode; + if ( $fields->[$j] eq 'frameworkcode' && $value ne $frameworkcode ) { + $dataFields{ $fields->[$j] } = $frameworkcode; push @values, $frameworkcode; - } elsif ($fields->[$j] eq 'isurl' && defined $value && $value eq q{}) { - $dataFields{$fields->[$j]} = undef; + } elsif ( $fields->[$j] eq 'isurl' && defined $value && $value eq q{} ) { + $dataFields{ $fields->[$j] } = undef; push @values, undef; } else { - $dataFields{$fields->[$j]} = $value; + $dataFields{ $fields->[$j] } = $value; push @values, $value; } - $j++ + $j++; } } - $ok = _processRow_DB($dbh, $table, $fieldsStr, $dataStr, $updateStr, \@values, \%dataFields, $PKArray, \@fieldsPK, $fields2Delete); + $ok = _processRow_DB( + $dbh, $table, $fieldsStr, $dataStr, $updateStr, \@values, \%dataFields, $PKArray, + \@fieldsPK, $fields2Delete + ); } $pos = tell($dom); } @arrData = (); } return $ok; -}#_import_table_csv - +} #_import_table_csv # Import worksheet from the ods content.xml file to the mysql table -sub _import_table_ods -{ - my ($dbh, $table, $frameworkcode, $dom, $PKArray, $fields2Delete, $frameworktype) = @_; +sub _import_table_ods { + my ( $dbh, $table, $frameworkcode, $dom, $PKArray, $fields2Delete, $frameworktype ) = @_; my $xc = XML::LibXML::XPathContext->new($dom); - $xc->registerNs('xmlns:office','urn:oasis:names:tc:opendocument:xmlns:office:1.0'); - $xc->registerNs('xmlns:table','urn:oasis:names:tc:opendocument:xmlns:table:1.0'); - $xc->registerNs('xmlns:text','urn:oasis:names:tc:opendocument:xmlns:text:1.0'); + $xc->registerNs( 'xmlns:office', 'urn:oasis:names:tc:opendocument:xmlns:office:1.0' ); + $xc->registerNs( 'xmlns:table', 'urn:oasis:names:tc:opendocument:xmlns:table:1.0' ); + $xc->registerNs( 'xmlns:text', 'urn:oasis:names:tc:opendocument:xmlns:text:1.0' ); my @nodes; - @nodes = $xc->findnodes('//table:table[@table:name="' . $table . '"]'); - if (@nodes == 1 && $nodes[0]->hasChildNodes()) { + @nodes = $xc->findnodes( '//table:table[@table:name="' . $table . '"]' ); + if ( @nodes == 1 && $nodes[0]->hasChildNodes() ) { my $nodeR = $nodes[0]->firstChild; - return _processRows_Table($dbh, $frameworkcode, $nodeR, $table, $PKArray, 'ods', $fields2Delete, $frameworktype); + return _processRows_Table( + $dbh, $frameworkcode, $nodeR, $table, $PKArray, 'ods', $fields2Delete, + $frameworktype + ); } else { Koha::Logger->get->warn("Error _import_table_ods there's not worksheet for $table"); } return 0; -}#_import_table_ods - +} #_import_table_ods # Import worksheet from the excel-xml file to the mysql table -sub _import_table_excel -{ - my ($dbh, $table, $frameworkcode, $dom, $PKArray, $fields2Delete, $frameworktype) = @_; +sub _import_table_excel { + my ( $dbh, $table, $frameworkcode, $dom, $PKArray, $fields2Delete, $frameworktype ) = @_; my $xc = XML::LibXML::XPathContext->new($dom); - $xc->registerNs('xmlns','urn:schemas-microsoft-com:office:spreadsheet'); - $xc->registerNs('xmlns:ss','urn:schemas-microsoft-com:office:spreadsheet'); - $xc->registerNs('xmlns:x','urn:schemas-microsoft-com:office:excel'); + $xc->registerNs( 'xmlns', 'urn:schemas-microsoft-com:office:spreadsheet' ); + $xc->registerNs( 'xmlns:ss', 'urn:schemas-microsoft-com:office:spreadsheet' ); + $xc->registerNs( 'xmlns:x', 'urn:schemas-microsoft-com:office:excel' ); my @nodes; - @nodes = $xc->findnodes('//ss:Worksheet[@ss:Name="' . $table . '"]'); - if (@nodes > 0) { - for (my $i=0; $i < @nodes; $i++) { - my @nodesT = $nodes[$i]->getElementsByTagNameNS('urn:schemas-microsoft-com:office:spreadsheet', 'Table'); - if (@nodesT == 1 && $nodesT[0]->hasChildNodes()) { + @nodes = $xc->findnodes( '//ss:Worksheet[@ss:Name="' . $table . '"]' ); + if ( @nodes > 0 ) { + for ( my $i = 0 ; $i < @nodes ; $i++ ) { + my @nodesT = $nodes[$i]->getElementsByTagNameNS( 'urn:schemas-microsoft-com:office:spreadsheet', 'Table' ); + if ( @nodesT == 1 && $nodesT[0]->hasChildNodes() ) { my $nodeR = $nodesT[0]->firstChild; - return _processRows_Table($dbh, $frameworkcode, $nodeR, $table, $PKArray, undef, $fields2Delete, $frameworktype); + return _processRows_Table( + $dbh, $frameworkcode, $nodeR, $table, $PKArray, undef, $fields2Delete, + $frameworktype + ); } } } else { Koha::Logger->get->warn("Error _import_table_excel there's not worksheet for $table"); } return 0; -}#_import_table_excel - +} #_import_table_excel # Get the data from a cell on a ods file through the value attribute or the text node -sub _getDataNodeODS -{ +sub _getDataNodeODS { my $node = shift; my $data; my $repeated = 0; - if ($node->nodeType == 1 && $node->nodeName =~ /(?:table:)?table-cell/) { - if ($node->hasAttributeNS('urn:oasis:names:tc:opendocument:xmlns:office:1.0', 'value')) { - $data = $node->getAttributeNS('urn:oasis:names:tc:opendocument:xmlns:office:1.0', 'value'); - } elsif ($node->hasChildNodes()) { - my @nodes2 = $node->getElementsByTagNameNS('urn:oasis:names:tc:opendocument:xmlns:text:1.0', 'p'); - if (@nodes2 == 1 && $nodes2[0]->hasChildNodes()) { + if ( $node->nodeType == 1 && $node->nodeName =~ /(?:table:)?table-cell/ ) { + if ( $node->hasAttributeNS( 'urn:oasis:names:tc:opendocument:xmlns:office:1.0', 'value' ) ) { + $data = $node->getAttributeNS( 'urn:oasis:names:tc:opendocument:xmlns:office:1.0', 'value' ); + } elsif ( $node->hasChildNodes() ) { + my @nodes2 = $node->getElementsByTagNameNS( 'urn:oasis:names:tc:opendocument:xmlns:text:1.0', 'p' ); + if ( @nodes2 == 1 && $nodes2[0]->hasChildNodes() ) { $data = $nodes2[0]->firstChild->nodeValue; } } - if ($node->hasAttributeNS('urn:oasis:names:tc:opendocument:xmlns:table:1.0', 'number-columns-repeated')) { - $repeated = $node->getAttributeNS('urn:oasis:names:tc:opendocument:xmlns:table:1.0', 'number-columns-repeated'); + if ( $node->hasAttributeNS( 'urn:oasis:names:tc:opendocument:xmlns:table:1.0', 'number-columns-repeated' ) ) { + $repeated = + $node->getAttributeNS( 'urn:oasis:names:tc:opendocument:xmlns:table:1.0', 'number-columns-repeated' ); } } - return ($data, $repeated); -}#_getDataNodeODS - + return ( $data, $repeated ); +} #_getDataNodeODS # Get the data from a row of a spreadsheet -sub _getDataFields -{ - my ($frameworkcode, $node, $fields, $format, $frameworktype) = @_; +sub _getDataFields { + my ( $frameworkcode, $node, $fields, $format, $frameworktype ) = @_; - my $dataFields = {}; + my $dataFields = {}; my @dataFieldsA = (); $frameworktype ||= ''; - if ($node && $node->hasChildNodes()) { + if ( $node && $node->hasChildNodes() ) { my $node2 = $node->firstChild; - my ($data, $repeated); - my $i = 0; + my ( $data, $repeated ); + my $i = 0; my $ok = 0; $repeated = 0; while ($node2) { - if ($format && $format eq 'ods') { - ($data, $repeated) = _getDataNodeODS($node2) if ($repeated <= 0); + if ( $format && $format eq 'ods' ) { + ( $data, $repeated ) = _getDataNodeODS($node2) if ( $repeated <= 0 ); $repeated--; $ok = 1; } else { - if ($node2->nodeType == 1 && $node2->nodeName =~ /(?:ss:)?Cell/) { - my @nodes3 = $node2->getElementsByTagNameNS('urn:schemas-microsoft-com:office:spreadsheet', 'Data'); - if (@nodes3 == 1 && $nodes3[0]->hasChildNodes()) { + if ( $node2->nodeType == 1 && $node2->nodeName =~ /(?:ss:)?Cell/ ) { + my @nodes3 = + $node2->getElementsByTagNameNS( 'urn:schemas-microsoft-com:office:spreadsheet', 'Data' ); + if ( @nodes3 == 1 && $nodes3[0]->hasChildNodes() ) { $data = $nodes3[0]->firstChild->nodeValue; - $ok = 1; + $ok = 1; } } } if ($ok) { $data //= ''; - $data = '' if ($data eq '#'); - if ($frameworktype eq "authority") { + $data = '' if ( $data eq '#' ); + if ( $frameworktype eq "authority" ) { if ( $fields->[$i] eq 'authtypecode' ) { $data = $frameworkcode; - } - elsif ( $fields->[$i] eq 'isurl' ) { + } elsif ( $fields->[$i] eq 'isurl' ) { $data = undef if defined $data && $data eq q{}; } } else { if ( $fields->[$i] eq 'frameworkcode' ) { $data = $frameworkcode; - } - elsif ( $fields->[$i] eq 'isurl' ) { + } elsif ( $fields->[$i] eq 'isurl' ) { $data = undef if defined $data && $data eq q{}; } } - $dataFields->{$fields->[$i]} = $data; + $dataFields->{ $fields->[$i] } = $data; push @dataFieldsA, $data; $i++; } - $ok = 0; - $node2 = $node2->nextSibling if ($repeated <= 0); + $ok = 0; + $node2 = $node2->nextSibling if ( $repeated <= 0 ); } } - return ($dataFields, \@dataFieldsA); -}#_getDataFields - + return ( $dataFields, \@dataFieldsA ); +} #_getDataFields # Get the data from the first row to know the column names -sub _getFields -{ - my ($node, $fields, $format) = @_; +sub _getFields { + my ( $node, $fields, $format ) = @_; - if ($node && $node->hasChildNodes()) { + if ( $node && $node->hasChildNodes() ) { my $node2 = $node->firstChild; - my ($data, $repeated); + my ( $data, $repeated ); while ($node2) { - if ($format && $format eq 'ods') { - ($data, $repeated) = _getDataNodeODS($node2); - push @$fields, $data if (defined($data)); + if ( $format && $format eq 'ods' ) { + ( $data, $repeated ) = _getDataNodeODS($node2); + push @$fields, $data if ( defined($data) ); } else { - if ($node2->nodeType == 1 && $node2->nodeName =~ /(?:ss:)?Cell/) { - my @nodes3 = $node2->getElementsByTagNameNS('urn:schemas-microsoft-com:office:spreadsheet', 'Data'); - if (@nodes3 == 1 && $nodes3[0]->hasChildNodes()) { + if ( $node2->nodeType == 1 && $node2->nodeName =~ /(?:ss:)?Cell/ ) { + my @nodes3 = + $node2->getElementsByTagNameNS( 'urn:schemas-microsoft-com:office:spreadsheet', 'Data' ); + if ( @nodes3 == 1 && $nodes3[0]->hasChildNodes() ) { $data = $nodes3[0]->firstChild->nodeValue; push @$fields, $data; } @@ -1193,10 +1237,7 @@ sub _getFields $node2 = $node2->nextSibling; } } -}#_getFields - - - +} #_getFields 1; __END__ diff --git a/C4/InstallAuth.pm b/C4/InstallAuth.pm index fa52cbcfc5..27e612557c 100644 --- a/C4/InstallAuth.pm +++ b/C4/InstallAuth.pm @@ -29,12 +29,13 @@ use C4::Templates; use Koha::Session; -our (@ISA, @EXPORT_OK); +our ( @ISA, @EXPORT_OK ); + BEGIN { - @ISA = qw(Exporter); + @ISA = qw(Exporter); @EXPORT_OK = qw( - checkauth - get_template_and_user + checkauth + get_template_and_user ); } @@ -104,18 +105,18 @@ Templates.pm module. sub get_template_and_user { my $in = shift; my $query = $in->{'query'}; - my $language =_get_template_language($query->cookie('KohaOpacLanguage')); - my $path = C4::Context->config('intrahtdocs'). "/prog/". $language; + my $language = _get_template_language( $query->cookie('KohaOpacLanguage') ); + my $path = C4::Context->config('intrahtdocs') . "/prog/" . $language; - my $tmplbase = $in->{template_name}; - my $filename = "$path/modules/" . $tmplbase; + my $tmplbase = $in->{template_name}; + my $filename = "$path/modules/" . $tmplbase; my $interface = 'intranet'; - my $template = C4::Templates->new( $interface, $filename, $tmplbase, $query); + my $template = C4::Templates->new( $interface, $filename, $tmplbase, $query ); my $request_method = $in->{query}->request_method // q{}; unless ( $request_method eq 'POST' && $in->{query}->param('op') eq 'cud-login' ) { - $in->{query}->param('login_userid', ''); - $in->{query}->param('login_password', '') + $in->{query}->param( 'login_userid', '' ); + $in->{query}->param( 'login_password', '' ); } my ( $user, $cookie, $sessionID, $flags ) = checkauth( @@ -149,13 +150,13 @@ sub get_template_and_user { $template->param( CAN_user_editauthorities => 1 ); $template->param( CAN_user_serials => 1 ); $template->param( CAN_user_reports => 1 ); - $template->param( CAN_user_problem_reports => 1 ); + $template->param( CAN_user_problem_reports => 1 ); $template->param( CAN_user_recalls => 1 ); } my $minPasswordLength = C4::Context->preference('minPasswordLength'); $minPasswordLength = 3 if not $minPasswordLength or $minPasswordLength < 3; - $template->param(minPasswordLength => $minPasswordLength,); + $template->param( minPasswordLength => $minPasswordLength, ); } return ( $template, $borrowernumber, $cookie ); } @@ -232,7 +233,7 @@ has authenticated. sub checkauth { my $query = shift; -# $authnotrequired will be set for scripts which will run without authentication + # $authnotrequired will be set for scripts which will run without authentication my $authnotrequired = shift; my $flagsrequired = shift; my $type = shift; @@ -249,9 +250,9 @@ sub checkauth { my $logout = $query->param('logout.x'); my $sessionID = $query->cookie("CGISESSID"); - my $session = Koha::Session->get_session( { sessionID => $sessionID, storage_method => 'file' } ); + my $session = Koha::Session->get_session( { sessionID => $sessionID, storage_method => 'file' } ); - if ( $session ) { + if ($session) { if ( $session->param('cardnumber') ) { C4::Context->set_userenv( $session->param('number'), @@ -268,7 +269,7 @@ sub checkauth { -name => 'CGISESSID', -value => $session->id, -HttpOnly => 1, - -secure => ( C4::Context->https_enabled() ? 1 : 0 ), + -secure => ( C4::Context->https_enabled() ? 1 : 0 ), -sameSite => 'Lax' ); $loggedin = 1; @@ -276,7 +277,8 @@ sub checkauth { } } - if ($logout || !$session) { + if ( $logout || !$session ) { + # voluntary logout the user C4::Context->unset_userenv(); $session = Koha::Session->get_session( { storage_method => 'file' } ); @@ -290,6 +292,7 @@ sub checkauth { my ( $return, $cardnumber ) = checkpw( $userid, $password ); if ($return) { $loggedin = 1; + # open L, ">>/tmp/sessionlog"; # my $time = localtime( time() ); # printf L "%20s from %16s logged in at %30s.\n", $userid, @@ -299,14 +302,14 @@ sub checkauth { -name => 'CGISESSID', -value => $sessionID, -HttpOnly => 1, - -secure => ( C4::Context->https_enabled() ? 1 : 0 ), + -secure => ( C4::Context->https_enabled() ? 1 : 0 ), -sameSite => 'Lax' ); if ( $return == 2 ) { - #Only superlibrarian should have access to this page. - #Since if it is a user, it is supposed that there is a borrower table - #And thus that data structure is loaded. + #Only superlibrarian should have access to this page. + #Since if it is a user, it is supposed that there is a borrower table + #And thus that data structure is loaded. my $hash = C4::Context->set_userenv( 0, 0, C4::Context->config('user'), C4::Context->config('user'), @@ -322,14 +325,15 @@ sub checkauth { $session->param( 'branch', 'NO_LIBRARY_SET' ); $session->param( 'branchname', 'NO_LIBRARY_SET' ); $session->param( 'flags', 1 ); - $session->param( 'emailaddress', - C4::Context->preference('KohaAdminEmailAddress') ); + $session->param( + 'emailaddress', + C4::Context->preference('KohaAdminEmailAddress') + ); $session->param( 'ip', $session->remote_addr() ); $session->param( 'lasttime', time() ); $userid = C4::Context->config('user'); } - } - else { + } else { if ($userid) { $info{'invalid_username_or_password'} = 1; C4::Context->unset_userenv(); @@ -343,18 +347,17 @@ sub checkauth { # successful login unless ($cookie) { $cookie = $query->cookie( - -name => 'CGISESSID', - -value => '', + -name => 'CGISESSID', + -value => '', -HttpOnly => 1, - -expires => '', - -secure => ( C4::Context->https_enabled() ? 1 : 0 ), + -expires => '', + -secure => ( C4::Context->https_enabled() ? 1 : 0 ), -sameSite => 'Lax' ); } if ($envcookie) { return ( $userid, [ $cookie, $envcookie ], $sessionID, $flags ); - } - else { + } else { return ( $userid, $cookie, $sessionID, $flags ); } } @@ -369,24 +372,25 @@ sub checkauth { } my $path = - C4::Context->config('intrahtdocs') . "/prog/" - . ( $query->param('language') ? $query->param('language') : "en" ); - my $filename = "$path/modules/$template_name"; + C4::Context->config('intrahtdocs') + . "/prog/" + . ( $query->param('language') ? $query->param('language') : "en" ); + my $filename = "$path/modules/$template_name"; my $interface = 'intranet'; - my $template = C4::Templates->new( $interface, $filename, '', $query); + my $template = C4::Templates->new( $interface, $filename, '', $query ); $template->param( INPUTS => \@inputs, ); - $template->param( login => 1 ); + $template->param( login => 1 ); $template->param( loginprompt => 1 ) unless $info{'nopermission'}; - if ($info{'invalid_username_or_password'} && $info{'invalid_username_or_password'} == 1) { - $template->param( 'invalid_username_or_password' => $info{'invalid_username_or_password'}); + if ( $info{'invalid_username_or_password'} && $info{'invalid_username_or_password'} == 1 ) { + $template->param( 'invalid_username_or_password' => $info{'invalid_username_or_password'} ); } - unless ( $sessionID ) { - $session = Koha::Session->get_session( { storage_method => 'file' } ); + unless ($sessionID) { + $session = Koha::Session->get_session( { storage_method => 'file' } ); $sessionID = $session->id; } $template->param( @@ -394,18 +398,18 @@ sub checkauth { sessionID => $sessionID, ); $cookie = $query->cookie( - -name => 'CGISESSID', - -value => $sessionID, + -name => 'CGISESSID', + -value => $sessionID, -HttpOnly => 1, - -expires => '', - -secure => ( C4::Context->https_enabled() ? 1 : 0 ), + -expires => '', + -secure => ( C4::Context->https_enabled() ? 1 : 0 ), -sameSite => 'Lax' ); print $query->header( - -type => 'text/html; charset=utf-8', - -cookie => $cookie - ), - $template->output; + -type => 'text/html; charset=utf-8', + -cookie => $cookie + ), + $template->output; exit; } @@ -414,7 +418,7 @@ sub checkpw { my ( $userid, $password ) = @_; if ( $userid - && $userid eq C4::Context->config('user') + && $userid eq C4::Context->config('user') && "$password" eq C4::Context->config('pass') ) { diff --git a/C4/Installer.pm b/C4/Installer.pm index 4dfebbf7fe..1f9df85aa3 100644 --- a/C4/Installer.pm +++ b/C4/Installer.pm @@ -33,11 +33,13 @@ use Koha::Installer; use Koha::Installer::Output qw ( say_failure ); use vars qw(@ISA @EXPORT); + BEGIN { require Exporter; @ISA = qw( Exporter ); - push @EXPORT, qw( primary_key_exists unique_key_exists foreign_key_exists index_exists column_exists TableExists marc_framework_sql_list TransformToNum CheckVersion NewVersion SetVersion sanitize_zero_date update get_db_entries get_atomic_updates run_atomic_updates has_non_dynamic_row_format ); -}; + push @EXPORT, + qw( primary_key_exists unique_key_exists foreign_key_exists index_exists column_exists TableExists marc_framework_sql_list TransformToNum CheckVersion NewVersion SetVersion sanitize_zero_date update get_db_entries get_atomic_updates run_atomic_updates has_non_dynamic_row_format ); +} =head1 NAME @@ -81,22 +83,32 @@ sub new { $self->{'port'} = C4::Context->config("port"); $self->{'user'} = C4::Context->config("user"); $self->{'password'} = C4::Context->config("pass"); - $self->{'tls'} = C4::Context->config("tls"); - if( $self->{'tls'} && $self->{'tls'} eq 'yes' ) { - $self->{'ca'} = C4::Context->config('ca'); + $self->{'tls'} = C4::Context->config("tls"); + + if ( $self->{'tls'} && $self->{'tls'} eq 'yes' ) { + $self->{'ca'} = C4::Context->config('ca'); $self->{'cert'} = C4::Context->config('cert'); - $self->{'key'} = C4::Context->config('key'); - $self->{'tlsoptions'} = ";mysql_ssl=1;mysql_ssl_client_key=".$self->{key}.";mysql_ssl_client_cert=".$self->{cert}.";mysql_ssl_ca_file=".$self->{ca}; - $self->{'tlscmdline'} = " --ssl-cert ". $self->{cert} . " --ssl-key " . $self->{key} . " --ssl-ca ".$self->{ca}." " + $self->{'key'} = C4::Context->config('key'); + $self->{'tlsoptions'} = + ";mysql_ssl=1;mysql_ssl_client_key=" + . $self->{key} + . ";mysql_ssl_client_cert=" + . $self->{cert} + . ";mysql_ssl_ca_file=" + . $self->{ca}; + $self->{'tlscmdline'} = + " --ssl-cert " . $self->{cert} . " --ssl-key " . $self->{key} . " --ssl-ca " . $self->{ca} . " "; } - $self->{'dbh'} = DBI->connect("DBI:$self->{dbms}:dbname=$self->{dbname};host=$self->{hostname}" . - ( $self->{port} ? ";port=$self->{port}" : "" ). - ( $self->{tlsoptions} ? $self->{tlsoptions} : ""), - $self->{'user'}, $self->{'password'}); - $self->{'language'} = undef; + $self->{'dbh'} = DBI->connect( + "DBI:$self->{dbms}:dbname=$self->{dbname};host=$self->{hostname}" + . ( $self->{port} ? ";port=$self->{port}" : "" ) + . ( $self->{tlsoptions} ? $self->{tlsoptions} : "" ), + $self->{'user'}, $self->{'password'} + ); + $self->{'language'} = undef; $self->{'marcflavour'} = undef; - $self->{'dbh'}->do('set NAMES "utf8"'); - $self->{'dbh'}->{'mysql_enable_utf8'}=1; + $self->{'dbh'}->do('set NAMES "utf8"'); + $self->{'dbh'}->{'mysql_enable_utf8'} = 1; bless $self, $class; return $self; @@ -117,23 +129,26 @@ for language C<$lang> and the 'en' ones are returned. =cut sub marc_framework_sql_list { - my $self = shift; - my $lang = shift; + my $self = shift; + my $lang = shift; my $marcflavour = shift; my $defaulted_to_en = 0; undef $/; - my $dir = C4::Context->config('intranetdir') . "/installer/data/$self->{dbms}/$lang/marcflavour/".lc($marcflavour); + my $dir = + C4::Context->config('intranetdir') . "/installer/data/$self->{dbms}/$lang/marcflavour/" . lc($marcflavour); my $dir_h; - unless (opendir( $dir_h, $dir )) { - if ($lang eq 'en') { + unless ( opendir( $dir_h, $dir ) ) { + if ( $lang eq 'en' ) { warn "cannot open MARC frameworks directory $dir"; } else { + # if no translated MARC framework is available, # default to English - $dir = C4::Context->config('intranetdir') . "/installer/data/$self->{dbms}/en/marcflavour/".lc($marcflavour); - opendir($dir_h, $dir) or warn "cannot open English MARC frameworks directory $dir"; + $dir = + C4::Context->config('intranetdir') . "/installer/data/$self->{dbms}/en/marcflavour/" . lc($marcflavour); + opendir( $dir_h, $dir ) or warn "cannot open English MARC frameworks directory $dir"; $defaulted_to_en = 1; } } @@ -144,7 +159,7 @@ sub marc_framework_sql_list { my $request = $self->{'dbh'}->prepare("SELECT value FROM systempreferences WHERE variable='FrameworksLoaded'"); $request->execute; my ($frameworksloaded) = $request->fetchrow; - $frameworksloaded = '' unless defined $frameworksloaded; # avoid warning + $frameworksloaded = '' unless defined $frameworksloaded; # avoid warning my %frameworksloaded; foreach ( split( /\|/, $frameworksloaded ) ) { $frameworksloaded{$_} = 1; @@ -166,29 +181,29 @@ sub marc_framework_sql_list { } else { open my $fh, "<:encoding(UTF-8)", "$dir/$requirelevel/$name.txt"; my $line = <$fh>; - $line = Encode::encode('UTF-8', $line) unless ( Encode::is_utf8($line) ); + $line = Encode::encode( 'UTF-8', $line ) unless ( Encode::is_utf8($line) ); @lines = split /\n/, $line; } - my $mandatory = ($requirelevel =~ /(mandatory|requi|oblig|necess)/i); + my $mandatory = ( $requirelevel =~ /(mandatory|requi|oblig|necess)/i ); push @frameworklist, - { + { 'fwkname' => $name, 'fwkfile' => "$dir/$requirelevel/$_", 'fwkdescription' => \@lines, 'checked' => ( ( $frameworksloaded{$_} || $mandatory ) ? 1 : 0 ), 'mandatory' => $mandatory, - }; + }; } @listname; my @fwks = - sort { $a->{'fwkname'} cmp $b->{'fwkname'} } @frameworklist; + sort { $a->{'fwkname'} cmp $b->{'fwkname'} } @frameworklist; $cell{"frameworks"} = \@fwks; - $cell{"label"} = ($requirelevel =~ /(mandatory|requi|oblig|necess)/i)?'mandatory':'optional'; + $cell{"label"} = ( $requirelevel =~ /(mandatory|requi|oblig|necess)/i ) ? 'mandatory' : 'optional'; $cell{"code"} = lc($requirelevel); push @fwklist, \%cell; } - return ($defaulted_to_en, \@fwklist); + return ( $defaulted_to_en, \@fwklist ); } =head2 sample_data_sql_list @@ -211,14 +226,15 @@ sub sample_data_sql_list { undef $/; my $dir = C4::Context->config('intranetdir') . "/installer/data/$self->{dbms}/$lang"; my $dir_h; - unless (opendir( $dir_h, $dir )) { - if ($lang eq 'en') { + unless ( opendir( $dir_h, $dir ) ) { + if ( $lang eq 'en' ) { warn "cannot open sample data directory $dir"; } else { + # if no sample data is available, # default to English $dir = C4::Context->config('intranetdir') . "/installer/data/$self->{dbms}/en"; - opendir($dir_h, $dir) or warn "cannot open English sample data directory $dir"; + opendir( $dir_h, $dir ) or warn "cannot open English sample data directory $dir"; $defaulted_to_en = 1; } } @@ -229,7 +245,7 @@ sub sample_data_sql_list { my $request = $self->{'dbh'}->prepare("SELECT value FROM systempreferences WHERE variable='FrameworksLoaded'"); $request->execute; my ($frameworksloaded) = $request->fetchrow; - $frameworksloaded = '' unless defined $frameworksloaded; # avoid warning + $frameworksloaded = '' unless defined $frameworksloaded; # avoid warning my %frameworksloaded; foreach ( split( /\|/, $frameworksloaded ) ) { $frameworksloaded{$_} = 1; @@ -251,28 +267,28 @@ sub sample_data_sql_list { } else { open my $fh, "<:encoding(UTF-8)", "$dir/$requirelevel/$name.txt"; my $line = <$fh>; - $line = Encode::encode('UTF-8', $line) unless ( Encode::is_utf8($line) ); + $line = Encode::encode( 'UTF-8', $line ) unless ( Encode::is_utf8($line) ); @lines = split /\n/, $line; } - my $mandatory = ($requirelevel =~ /(mandatory|requi|oblig|necess)/i); + my $mandatory = ( $requirelevel =~ /(mandatory|requi|oblig|necess)/i ); push @frameworklist, - { + { 'fwkname' => $name, 'fwkfile' => "$dir/$requirelevel/$_", 'fwkdescription' => \@lines, 'checked' => ( ( $frameworksloaded{$_} || $mandatory ) ? 1 : 0 ), 'mandatory' => $mandatory, - }; + }; } @listname; my @fwks = sort { $a->{'fwkname'} cmp $b->{'fwkname'} } @frameworklist; $cell{"frameworks"} = \@fwks; - $cell{"label"} = ($requirelevel =~ /(mandatory|requi|oblig|necess)/i)?'mandatory':'optional'; + $cell{"label"} = ( $requirelevel =~ /(mandatory|requi|oblig|necess)/i ) ? 'mandatory' : 'optional'; $cell{"code"} = lc($requirelevel); push @levellist, \%cell; } - return ($defaulted_to_en, \@levellist); + return ( $defaulted_to_en, \@levellist ); } =head2 load_db_schema @@ -338,10 +354,10 @@ moved to a different method. =cut sub load_sql_in_order { - my $self = shift; - my $langchoice = shift; + my $self = shift; + my $langchoice = shift; my $all_languages = shift; - my @sql_list = @_; + my @sql_list = @_; my $lang; my %hashlevel; @@ -350,15 +366,16 @@ sub load_sql_in_order { my @bb = split /\/|\\/, ($b); $aa[-1] cmp $bb[-1] } @sql_list; - my $request = $self->{'dbh'}->prepare( "SELECT value FROM systempreferences WHERE variable='FrameworksLoaded'" ); + my $request = $self->{'dbh'}->prepare("SELECT value FROM systempreferences WHERE variable='FrameworksLoaded'"); $request->execute; my ($systempreference) = $request->fetchrow; - $systempreference = '' unless defined $systempreference; # avoid warning + $systempreference = '' unless defined $systempreference; # avoid warning my $global_mandatory_dir = C4::Context->config('intranetdir') . "/installer/data/$self->{dbms}/mandatory"; # Make sure some stuffs are loaded first - unshift(@fnames, + unshift( + @fnames, "$global_mandatory_dir/sysprefs.sql", "$global_mandatory_dir/subtag_registry.sql", "$global_mandatory_dir/auth_val_cat.sql", @@ -369,29 +386,30 @@ sub load_sql_in_order { ); push @fnames, "$global_mandatory_dir/userflags.sql", - "$global_mandatory_dir/userpermissions.sql", - "$global_mandatory_dir/audio_alerts.sql", - ; - my $localization_file = C4::Context->config('intranetdir') . - "/installer/data/$self->{dbms}/localization/$langchoice/custom.sql"; + "$global_mandatory_dir/userpermissions.sql", + "$global_mandatory_dir/audio_alerts.sql", + ; + my $localization_file = + C4::Context->config('intranetdir') . "/installer/data/$self->{dbms}/localization/$langchoice/custom.sql"; if ( -f $localization_file ) { push @fnames, $localization_file; } foreach my $file (@fnames) { + # warn $file; undef $/; my $error = $self->load_sql($file); - my @file = split qr(\/|\\), $file; + my @file = split qr(\/|\\), $file; $lang = $file[ scalar(@file) - 3 ] unless ($lang); my $level = ( $file =~ /(localization)/ ) ? $1 : $file[ scalar(@file) - 2 ]; unless ($error) { $systempreference .= "$file[scalar(@file)-1]|" - unless ( index( $systempreference, $file[ scalar(@file) - 1 ] ) >= 0 ); + unless ( index( $systempreference, $file[ scalar(@file) - 1 ] ) >= 0 ); } #Bulding here a hierarchy to display files by level. push @{ $hashlevel{$level} }, - { "fwkname" => $file[ scalar(@file) - 1 ], "error" => $error }; + { "fwkname" => $file[ scalar(@file) - 1 ], "error" => $error }; } #systempreference contains an ending | @@ -408,9 +426,8 @@ sub load_sql_in_order { } } my $updateflag = - $self->{'dbh'}->do( - "UPDATE systempreferences set value=\"$systempreference\" where variable='FrameworksLoaded'" - ); + $self->{'dbh'} + ->do("UPDATE systempreferences set value=\"$systempreference\" where variable='FrameworksLoaded'"); unless ( $updateflag == 1 ) { my $string = @@ -418,7 +435,7 @@ sub load_sql_in_order { my $rq = $self->{'dbh'}->prepare($string); $rq->execute; } - return ($fwk_language, \@list); + return ( $fwk_language, \@list ); } =head2 set_marcflavour_syspref @@ -436,7 +453,7 @@ MARC21 or UNIMARC. =cut sub set_marcflavour_syspref { - my $self = shift; + my $self = shift; my $marcflavour = shift; # we can have some variants of marc flavour, by having different directories, like : unimarc_small and unimarc_full, for small and complete unimarc frameworks. @@ -445,7 +462,7 @@ sub set_marcflavour_syspref { $marc_cleaned = 'UNIMARC' if $marcflavour =~ /unimarc/i; my $request = $self->{'dbh'}->prepare( - "INSERT IGNORE INTO `systempreferences` (variable,value,explanation,options,type) VALUES('marcflavour','$marc_cleaned','Define global MARC flavor (MARC21 or UNIMARC) used for character encoding','MARC21|UNIMARC','Choice');" + "INSERT IGNORE INTO `systempreferences` (variable,value,explanation,options,type) VALUES('marcflavour','$marc_cleaned','Define global MARC flavor (MARC21 or UNIMARC) used for character encoding','MARC21|UNIMARC','Choice');" ); $request->execute; } @@ -463,15 +480,19 @@ sub set_version_syspref { my $self = shift; my $kohaversion = Koha::version(); + # remove the 3 last . to have a Perl number $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/; - if (C4::Context->preference('Version')) { + if ( C4::Context->preference('Version') ) { warn "UPDATE Version"; - my $finish=$self->{'dbh'}->prepare("UPDATE systempreferences SET value=? WHERE variable='Version'"); + my $finish = $self->{'dbh'}->prepare("UPDATE systempreferences SET value=? WHERE variable='Version'"); $finish->execute($kohaversion); } else { warn "INSERT Version"; - my $finish=$self->{'dbh'}->prepare("INSERT into systempreferences (variable,value,explanation) values ('Version',?,'The Koha database version. WARNING: Do not change this value manually, it is maintained by the webinstaller')"); + my $finish = + $self->{'dbh'}->prepare( + "INSERT into systempreferences (variable,value,explanation) values ('Version',?,'The Koha database version. WARNING: Do not change this value manually, it is maintained by the webinstaller')" + ); $finish->execute($kohaversion); } C4::Context->clear_syspref_cache(); @@ -493,9 +514,11 @@ sub set_languages_syspref { return if ( not $language or $language eq 'en' ); warn "UPDATE Languages"; + # intranet my $pref = $self->{'dbh'}->prepare("UPDATE systempreferences SET value=? WHERE variable='StaffInterfaceLanguages'"); $pref->execute("en,$language"); + # opac $pref = $self->{'dbh'}->prepare("UPDATE systempreferences SET value=? WHERE variable='OPACLanguages'"); $pref->execute("en,$language"); @@ -513,22 +536,25 @@ Returns the values required to build an insert statement. =cut sub process_yml_table { - my ($table) = @_; - my $table_name = ( keys %$table )[0]; # table name - my @rows = @{ $table->{$table_name}->{rows} }; # - my @columns = ( sort keys %{$rows[0]} ); # column names - my $fields = join ",", map{sprintf("`%s`", $_)} @columns; # idem, joined + my ($table) = @_; + my $table_name = ( keys %$table )[0]; # table name + my @rows = @{ $table->{$table_name}->{rows} }; # + my @columns = ( sort keys %{ $rows[0] } ); # column names + my $fields = join ",", map { sprintf( "`%s`", $_ ) } @columns; # idem, joined my $query = "INSERT INTO $table_name ( $fields ) VALUES "; - my @multiline = @{ $table->{$table_name}->{'multiline'} }; # to check multiline values; - my $placeholders = '(' . join ( ",", map { "?" } @columns ) . ')'; # '(?,..,?)' string + my @multiline = @{ $table->{$table_name}->{'multiline'} }; # to check multiline values; + my $placeholders = '(' . join( ",", map { "?" } @columns ) . ')'; # '(?,..,?)' string my @values; - foreach my $row ( @rows ) { - push @values, [ map { - my $col = $_; - ( @multiline and grep { $_ eq $col } @multiline ) - ? join "\r\n", @{$row->{$col}} # join multiline values - : $row->{$col}; - } @columns ]; + + foreach my $row (@rows) { + push @values, [ + map { + my $col = $_; + ( @multiline and grep { $_ eq $col } @multiline ) + ? join "\r\n", @{ $row->{$col} } # join multiline values + : $row->{$col}; + } @columns + ]; } return { query => $query, placeholders => $placeholders, values => \@values }; } @@ -546,49 +572,50 @@ error. =cut sub load_sql { - my $self = shift; + my $self = shift; my $filename = shift; my $error; - my $dbh = $self->{ dbh }; + my $dbh = $self->{dbh}; my $dup_stderr; do { local *STDERR; open STDERR, ">>", \$dup_stderr; - if ( $filename =~ /sql$/ ) { # SQL files + if ( $filename =~ /sql$/ ) { # SQL files eval { DBIx::RunSQL->run_sql_file( - dbh => $dbh, - sql => $filename, + dbh => $dbh, + sql => $filename, ); }; - } - else { # YAML files + } else { # YAML files eval { - my $yaml = YAML::XS::LoadFile( $filename ); # Load YAML + my $yaml = YAML::XS::LoadFile($filename); # Load YAML for my $table ( @{ $yaml->{'tables'} } ) { my $query_info = process_yml_table($table); my $query = $query_info->{query}; my $placeholders = $query_info->{placeholders}; my $values = $query_info->{values}; + # Doing only 1 INSERT query for the whole table my @all_rows_values = map { @$_ } @$values; - $query .= join ', ', ( $placeholders ) x scalar @$values; + $query .= join ', ', ($placeholders) x scalar @$values; $dbh->do( $query, undef, @all_rows_values ); } - for my $statement ( @{ $yaml->{'sql_statements'} } ) { # extra SQL statements + for my $statement ( @{ $yaml->{'sql_statements'} } ) { # extra SQL statements $dbh->do($statement); } }; } - if ($@){ + if ($@) { warn "Something went wrong loading file $filename ($@)"; } }; + # errors thrown while loading installer data should be logged - if( $dup_stderr ) { + if ($dup_stderr) { warn "C4::Installer::load_sql returned the following errors while attempting to load $filename:\n"; $error = $dup_stderr; } @@ -609,17 +636,18 @@ returns undef if no match was found. =cut sub get_file_path_from_name { - my $self = shift; + my $self = shift; my $partialname = shift; - my $lang = 'en'; # FIXME: how do I know what language I want? + my $lang = 'en'; # FIXME: how do I know what language I want? + + my ( $defaulted_to_en, $list ) = $self->sample_data_sql_list($lang); - my ($defaulted_to_en, $list) = $self->sample_data_sql_list($lang); # warn( Data::Dumper->Dump( [ $list ], [ 'list' ] ) ); my @found; - foreach my $frameworklist ( @$list ) { - push @found, grep { $_->{'fwkfile'} =~ /$partialname$/ } @{$frameworklist->{'frameworks'}}; + foreach my $frameworklist (@$list) { + push @found, grep { $_->{'fwkfile'} =~ /$partialname$/ } @{ $frameworklist->{'frameworks'} }; } # warn( Data::Dumper->Dump( [ \@found ], [ 'found' ] ) ); @@ -639,7 +667,7 @@ sub primary_key_exists { my $dbh = C4::Context->dbh; my $sql = qq| SHOW INDEX FROM $table_name WHERE key_name='PRIMARY' |; my $exists; - if( $key_name ){ + if ($key_name) { $sql .= 'AND column_name = ? ' if $key_name; ($exists) = $dbh->selectrow_array( $sql, undef, $key_name ); } else { @@ -652,14 +680,14 @@ sub primary_key_exists { sub foreign_key_exists { my ( $table_name, $constraint_name ) = @_; my $dbh = C4::Context->dbh; - my (undef, $infos) = $dbh->selectrow_array(qq|SHOW CREATE TABLE $table_name|); + my ( undef, $infos ) = $dbh->selectrow_array(qq|SHOW CREATE TABLE $table_name|); return $infos =~ m|CONSTRAINT `$constraint_name` FOREIGN KEY|; } sub unique_key_exists { my ( $table_name, $constraint_name ) = @_; my $dbh = C4::Context->dbh; - my (undef, $infos) = $dbh->selectrow_array(qq|SHOW CREATE TABLE $table_name|); + my ( undef, $infos ) = $dbh->selectrow_array(qq|SHOW CREATE TABLE $table_name|); return $infos =~ m|UNIQUE KEY `$constraint_name`|; } @@ -688,14 +716,14 @@ sub column_exists { return $exists; } -sub TableExists { # Could be renamed table_exists for consistency +sub TableExists { # Could be renamed table_exists for consistency my $table = shift; eval { - my $dbh = C4::Context->dbh; - local $dbh->{PrintError} = 0; - local $dbh->{RaiseError} = 1; - $dbh->do(qq{SELECT * FROM $table WHERE 1 = 0 }); - }; + my $dbh = C4::Context->dbh; + local $dbh->{PrintError} = 0; + local $dbh->{RaiseError} = 1; + $dbh->do(qq{SELECT * FROM $table WHERE 1 = 0 }); + }; return 1 unless $@; return 0; } @@ -709,17 +737,17 @@ sub version_from_file { sub get_db_entries { my $db_revs_dir = C4::Context->config('intranetdir') . '/installer/data/mysql/db_revs'; opendir my $dh, $db_revs_dir or die "Cannot open $db_revs_dir dir ($!)"; - my @files = sort grep { m|\.pl$| && ! m|skeleton\.pl$| } readdir $dh; + my @files = sort grep { m|\.pl$| && !m|skeleton\.pl$| } readdir $dh; my @need_update; - for my $file ( @files ) { - my $version = version_from_file( $file ); + for my $file (@files) { + my $version = version_from_file($file); - unless ( $version ) { + unless ($version) { warn "Invalid db_rev found: " . $file; - next + next; } - next unless CheckVersion( $version ); + next unless CheckVersion($version); push @need_update, sprintf( "%s/%s", $db_revs_dir, $file ); } @@ -741,8 +769,7 @@ sub run_db_rev { $db_rev->{up}->( { dbh => $schema->storage->dbh, out => $outfh } ); } ); - } - catch { + } catch { $error = $_; say_failure( $outfh, "ERROR: " . $error ); }; @@ -759,7 +786,7 @@ sub run_db_rev { time => POSIX::strftime( "%H:%M:%S", localtime ), error => $error }; - $db_entry->{output} = generate_output_db_entry($db_entry, $out); + $db_entry->{output} = generate_output_db_entry( $db_entry, $out ); return $db_entry; } @@ -769,24 +796,25 @@ sub update { my $force = $params->{force} || 0; my ( @done, @errors ); - for my $file ( @$files ) { + for my $file (@$files) { my $db_entry = run_db_rev($file); if ( $db_entry->{error} ) { push @errors, $db_entry; - $force ? next : last ; - # We stop the update if an error occurred! + $force ? next : last; + + # We stop the update if an error occurred! } - SetVersion($db_entry->{version}); + SetVersion( $db_entry->{version} ); push @done, $db_entry; } return { success => \@done, error => \@errors }; } sub generate_output_db_entry { - my ( $db_entry ) = @_; + my ($db_entry) = @_; my $description = $db_entry->{description}; my $output = $db_entry->{output}; @@ -794,30 +822,36 @@ sub generate_output_db_entry { my $bug_number = $db_entry->{bug_number}; my $time = $db_entry->{time}; my $exec_output = $db_entry->{exec_output}; - my $done = defined $db_entry->{done} - ? $db_entry->{done} - ? " done" - : " failed" - : ""; # For old versions, we don't know if we succeed or failed + my $done = + defined $db_entry->{done} + ? $db_entry->{done} + ? " done" + : " failed" + : ""; # For old versions, we don't know if we succeed or failed my @output; - if ( $DBversion ) { + if ($DBversion) { if ($bug_number) { - push @output, sprintf('Upgrade to %s %s [%s]: Bug %5s - %s', $DBversion, $done, $time, $bug_number, $description); + push @output, + sprintf( 'Upgrade to %s %s [%s]: Bug %5s - %s', $DBversion, $done, $time, $bug_number, $description ); } else { - push @output, sprintf('Upgrade to %s %s [%s]: %s', $DBversion, $done, $time, $description); + push @output, sprintf( 'Upgrade to %s %s [%s]: %s', $DBversion, $done, $time, $description ); } - } else { # Atomic update + } else { # Atomic update if ($bug_number) { - push @output, sprintf('DEV atomic update %s %s [%s]: Bug %5s - %s', $db_entry->{filepath}, $done, $time, $bug_number, $description); - } else { # Old atomic update syntax - push @output, sprintf('DEV atomic update %s %s [%s]', $db_entry->{filepath}, $done, $time); + push @output, + sprintf( + 'DEV atomic update %s %s [%s]: Bug %5s - %s', $db_entry->{filepath}, $done, $time, + $bug_number, $description + ); + } else { # Old atomic update syntax + push @output, sprintf( 'DEV atomic update %s %s [%s]', $db_entry->{filepath}, $done, $time ); } } if ($exec_output) { - foreach my $line (split /\n/, $exec_output) { + foreach my $line ( split /\n/, $exec_output ) { push @output, sprintf "\t%s", $line; } } @@ -831,24 +865,24 @@ sub get_atomic_updates { } sub run_atomic_updates { - my ( $files ) = @_; + my ($files) = @_; my $update_dir = C4::Context->config('intranetdir') . '/installer/data/mysql/atomicupdate/'; my ( @done, @errors ); - for my $file ( @$files ) { + for my $file (@$files) { my $filepath = $update_dir . $file; my $atomic_update; if ( $file =~ m{\.perl$} ) { - my $code = read_file( $filepath ); - my ( $out, $err ) = ('', ''); + my $code = read_file($filepath); + my ( $out, $err ) = ( '', '' ); { open my $oldout, qw{>&}, "STDOUT"; close STDOUT; - open STDOUT,'>:encoding(utf8)', \$out; - my $DBversion = Koha::version; # We need $DBversion and $dbh for the eval - my $dbh = C4::Context->dbh; - eval $code; ## no critic (StringyEval) + open STDOUT, '>:encoding(utf8)', \$out; + my $DBversion = Koha::version; # We need $DBversion and $dbh for the eval + my $dbh = C4::Context->dbh; + eval $code; ## no critic (StringyEval) $err = $@; warn $err if $err; close STDOUT; @@ -862,11 +896,10 @@ sub run_atomic_updates { time => POSIX::strftime( "%H:%M:%S", localtime ), }; - $atomic_update->{output} = - $out - ? [ split "\n", $out ] - : generate_output_db_entry($atomic_update); # There wad an error, we didn't reach NewVersion) + $out + ? [ split "\n", $out ] + : generate_output_db_entry($atomic_update); # There wad an error, we didn't reach NewVersion) $atomic_update->{error} = $err if $err; } elsif ( $file =~ m{\.pl$} ) { @@ -893,27 +926,31 @@ Drop all foreign keys of the table $table sub DropAllForeignKeys { my ($table) = @_; + # get the table description my $dbh = C4::Context->dbh; my $sth = $dbh->prepare("SHOW CREATE TABLE $table"); $sth->execute; my $vsc_structure = $sth->fetchrow; + # split on CONSTRAINT keyword - my @fks = split /CONSTRAINT /,$vsc_structure; + my @fks = split /CONSTRAINT /, $vsc_structure; + # parse each entry foreach (@fks) { + # isolate what is before FOREIGN KEY, if there is something, it's a foreign key to drop $_ = /(.*) FOREIGN KEY.*/; my $id = $1; if ($id) { + # we have found 1 foreign, drop it $dbh->do("ALTER TABLE $table DROP FOREIGN KEY $id"); - $id=""; + $id = ""; } } } - =head2 TransformToNum Transform the Koha version from a 4 parts string @@ -934,18 +971,21 @@ set the DBversion in the systempreferences =cut sub SetVersion { - return if $_[0]=~ /XXX$/; - #you are testing a patch with a db revision; do not change version - my $kohaversion = TransformToNum($_[0]); - my $dbh = C4::Context->dbh; - if (C4::Context->preference('Version')) { - my $finish=$dbh->prepare("UPDATE systempreferences SET value=? WHERE variable='Version'"); - $finish->execute($kohaversion); + return if $_[0] =~ /XXX$/; + + #you are testing a patch with a db revision; do not change version + my $kohaversion = TransformToNum( $_[0] ); + my $dbh = C4::Context->dbh; + if ( C4::Context->preference('Version') ) { + my $finish = $dbh->prepare("UPDATE systempreferences SET value=? WHERE variable='Version'"); + $finish->execute($kohaversion); } else { - my $finish=$dbh->prepare("INSERT into systempreferences (variable,value,explanation) values ('Version',?,'The Koha database version. WARNING: Do not change this value manually, it is maintained by the webinstaller')"); - $finish->execute($kohaversion); + my $finish = $dbh->prepare( + "INSERT into systempreferences (variable,value,explanation) values ('Version',?,'The Koha database version. WARNING: Do not change this value manually, it is maintained by the webinstaller')" + ); + $finish->execute($kohaversion); } - C4::Context::clear_syspref_cache(); # invalidate cached preferences + C4::Context::clear_syspref_cache(); # invalidate cached preferences } # DEPRECATED Don't use it! @@ -959,18 +999,19 @@ sub NewVersion { if ( ref($descriptions) ) { $description = shift @$descriptions; $report = join( "\n", @{$descriptions} ); - } - else { + } else { $description = $descriptions; } - my $output = generate_output_db_entry( { + my $output = generate_output_db_entry( + { bug_number => $bug_number, description => $description, report => $report, version => $DBversion, time => POSIX::strftime( "%H:%M:%S", localtime ), - }); + } + ); say join "\n", @$output; @@ -995,7 +1036,7 @@ sub CheckVersion { return 1 if ( $proposed_version =~ m/XXX/ ); if ( C4::Context->preference("Version") < $version_number - && $version_number <= TransformToNum( $Koha::VERSION ) ) + && $version_number <= TransformToNum($Koha::VERSION) ) { return 1; } @@ -1008,21 +1049,27 @@ sub sanitize_zero_date { my $dbh = C4::Context->dbh; - my (undef, $datatype) = $dbh->selectrow_array(qq| - SHOW COLUMNS FROM $table_name WHERE Field = ?|, undef, $column_name); + my ( undef, $datatype ) = $dbh->selectrow_array( + qq| + SHOW COLUMNS FROM $table_name WHERE Field = ?|, undef, $column_name + ); if ( $datatype eq 'date' ) { - $dbh->do(qq| + $dbh->do( + qq| UPDATE $table_name SET $column_name = NULL WHERE CAST($column_name AS CHAR(10)) = '0000-00-00'; - |); + | + ); } else { - $dbh->do(qq| + $dbh->do( + qq| UPDATE $table_name SET $column_name = NULL WHERE CAST($column_name AS CHAR(19)) = '0000-00-00 00:00:00'; - |); + | + ); } } @@ -1033,10 +1080,10 @@ Return the number of tables with row_format that is not Dynamic =cut sub has_non_dynamic_row_format { - my ($class) = @_; + my ($class) = @_; my $database = C4::Context->config('database'); - my $count = 0; - if ($database){ + my $count = 0; + if ($database) { my $dbh = C4::Context->dbh; my $sql = q# SELECT count(table_name) @@ -1045,7 +1092,7 @@ sub has_non_dynamic_row_format { table_schema = ? AND row_format != "Dynamic" #; - ( $count ) = $dbh->selectrow_array($sql, undef, $database); + ($count) = $dbh->selectrow_array( $sql, undef, $database ); } return $count; } diff --git a/C4/Installer/PerlModules.pm b/C4/Installer/PerlModules.pm index 5d4a84ecda..c1dea59f02 100644 --- a/C4/Installer/PerlModules.pm +++ b/C4/Installer/PerlModules.pm @@ -8,23 +8,23 @@ use Module::CPANfile; sub new { my $invocant = shift; - my $self = { - missing_pm => [], - upgrade_pm => [], - current_pm => [], + my $self = { + missing_pm => [], + upgrade_pm => [], + current_pm => [], }; my $type = ref($invocant) || $invocant; - bless ($self, $type); + bless( $self, $type ); return $self; } sub prereqs { my $self = shift; - unless (defined $self->{prereqs}) { + unless ( defined $self->{prereqs} ) { my $filename = $INC{'C4/Installer/PerlModules.pm'}; - my $path = dirname(dirname(dirname($filename))); + my $path = dirname( dirname( dirname($filename) ) ); $self->{prereqs} = Module::CPANfile->load("$path/cpanfile")->prereqs; } @@ -35,8 +35,8 @@ sub prereq_pm { my $self = shift; my $prereq_pm = {}; - my $reqs = $self->prereqs->merged_requirements; - foreach my $module ($reqs->required_modules) { + my $reqs = $self->prereqs->merged_requirements; + foreach my $module ( $reqs->required_modules ) { $prereq_pm->{$module} = $reqs->requirements_for_module($module); } @@ -51,10 +51,10 @@ sub versions_info { $self->{'upgrade_pm'} = []; $self->{'current_pm'} = []; - foreach my $phase ($self->prereqs->phases) { - foreach my $type ($self->prereqs->types_in($phase)) { - my $reqs = $self->prereqs->requirements_for($phase, $type); - foreach my $module (sort $reqs->required_modules) { + foreach my $phase ( $self->prereqs->phases ) { + foreach my $type ( $self->prereqs->types_in($phase) ) { + my $reqs = $self->prereqs->requirements_for( $phase, $type ); + foreach my $module ( sort $reqs->required_modules ) { my $module_infos = { cur_ver => 0, required => $type eq 'requires', @@ -67,14 +67,14 @@ sub versions_info { } elsif ( $req->[0] eq '<=' || $req->[0] eq '<' ) { $module_infos->{max_ver} = $req->[1]; } else { - push @{$module_infos->{exc_ver}}, $req->[1]; + push @{ $module_infos->{exc_ver} }, $req->[1]; } } my $attr; { # ignore warnings from noisy modules - local $SIG{__WARN__} = sub {}; + local $SIG{__WARN__} = sub { }; eval "require $module"; } if ($@) { @@ -82,7 +82,7 @@ sub versions_info { } else { my $pkg_version = $module->can("VERSION") ? $module->VERSION : 0; $module_infos->{cur_ver} = $pkg_version; - if ($reqs->accepts_module($module => $pkg_version)) { + if ( $reqs->accepts_module( $module => $pkg_version ) ) { $attr = 'current_pm'; } else { $attr = 'upgrade_pm'; @@ -96,7 +96,7 @@ sub versions_info { } sub get_attr { - return $_[0]->{$_[1]}; + return $_[0]->{ $_[1] }; } 1; diff --git a/C4/Installer/UpgradeBackup.pm b/C4/Installer/UpgradeBackup.pm index 61aa6fb2d9..1c12e8f88d 100644 --- a/C4/Installer/UpgradeBackup.pm +++ b/C4/Installer/UpgradeBackup.pm @@ -19,7 +19,7 @@ package C4::Installer::UpgradeBackup; use Modern::Perl; use File::Compare qw( compare ); -use Cwd qw( cwd ); +use Cwd qw( cwd ); use File::Copy; use File::Find qw( find ); use File::Spec; @@ -27,7 +27,7 @@ use Exporter; use vars qw(@ISA @EXPORT ); -@ISA = ('Exporter'); +@ISA = ('Exporter'); @EXPORT = ('backup_changed_files'); =head1 NAME @@ -42,39 +42,42 @@ creates backups of files updated during an upgrade. =cut sub backup_changed_files { - my $from_to = shift; - my $suffix = shift; - my $verbose = shift; + my $from_to = shift; + my $suffix = shift; + my $verbose = shift; my $inc_uninstall = shift; my $cwd = cwd(); - foreach my $sourceroot (sort keys %$from_to) { + foreach my $sourceroot ( sort keys %$from_to ) { my $targetroot = $from_to->{$sourceroot}; - my $currdir = File::Spec->catdir($cwd, $sourceroot); + my $currdir = File::Spec->catdir( $cwd, $sourceroot ); next unless -d $currdir; chdir $currdir or die "could not change to $currdir: $!"; # expand path - find(sub { - return unless -f $_; - my $filename = $_; + find( + sub { + return unless -f $_; + my $filename = $_; - my $targetdir = File::Spec->catdir($targetroot, $File::Find::dir); - my $targetfile = File::Spec->catfile($targetdir, $filename); - my $sourcedir = File::Spec->catdir($currdir, $File::Find::dir); - my $sourcefile = File::Spec->catfile($sourcedir, $filename); + my $targetdir = File::Spec->catdir( $targetroot, $File::Find::dir ); + my $targetfile = File::Spec->catfile( $targetdir, $filename ); + my $sourcedir = File::Spec->catdir( $currdir, $File::Find::dir ); + my $sourcefile = File::Spec->catfile( $sourcedir, $filename ); - if (-f $targetfile) { - my ($size) = (stat $sourcefile)[7]; - my $backup = $targetfile . $suffix; - unless (-s $targetfile == $size and not compare($sourcefile, $targetfile)) { - print "Backed up $targetfile to $backup\n"; - File::Copy::copy($targetfile, $backup); + if ( -f $targetfile ) { + my ($size) = ( stat $sourcefile )[7]; + my $backup = $targetfile . $suffix; + unless ( -s $targetfile == $size and not compare( $sourcefile, $targetfile ) ) { + print "Backed up $targetfile to $backup\n"; + File::Copy::copy( $targetfile, $backup ); + } } - } - }, "."); + }, + "." + ); } } diff --git a/C4/ItemCirculationAlertPreference.pm b/C4/ItemCirculationAlertPreference.pm index 2526e5c61a..7263575f4d 100644 --- a/C4/ItemCirculationAlertPreference.pm +++ b/C4/ItemCirculationAlertPreference.pm @@ -31,13 +31,10 @@ our $AUTOLOAD; our $valid = sub { my $opts = shift; for (qw(branchcode categorycode item_type notification)) { - exists($opts->{$_}) || croak("'$_' is a required parameter."); + exists( $opts->{$_} ) || croak("'$_' is a required parameter."); } }; - - - =head1 NAME C4::ItemCirculationAlertPreference - manage preferences for sending alerts @@ -93,13 +90,10 @@ object. The database is not affected by this method. =cut sub new { - my ($class, $opts) = @_; + my ( $class, $opts ) = @_; bless $opts => $class; } - - - =head3 C4::ItemCirculationAlertPreference->create(\%opts) This will find or create an item circulation alert preference. You must pass @@ -129,9 +123,9 @@ This can be "CHECKIN" or "CHECKOUT" =cut sub create { - my ($class, $opts) = @_; + my ( $class, $opts ) = @_; $valid->($opts); - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $prefs = $dbh->selectall_arrayref( "SELECT id, branchcode, categorycode, item_type FROM item_circulation_alert_preferences @@ -146,7 +140,7 @@ sub create { $opts->{notification}, ); if (@$prefs) { - return $class->new($prefs->[0]); + return $class->new( $prefs->[0] ); } else { my $success = $dbh->do( "INSERT INTO item_circulation_alert_preferences @@ -159,7 +153,7 @@ sub create { ); if ($success) { my $self = { - id => $dbh->last_insert_id(undef, undef, undef, undef), + id => $dbh->last_insert_id( undef, undef, undef, undef ), branchcode => $opts->{branchcode}, categorycode => $opts->{categorycode}, item_type => $opts->{item_type}, @@ -173,9 +167,6 @@ sub create { } } - - - =head3 C4::ItemCirculationAlertPreference->delete(\%opts) Delete an item circulation alert preference. You can delete by either passing @@ -185,9 +176,9 @@ triplet. =cut sub delete { - my ($class, $opts) = @_; + my ( $class, $opts ) = @_; my $dbh = C4::Context->dbh; - if ($opts->{id}) { + if ( $opts->{id} ) { $dbh->do( "DELETE FROM item_circulation_alert_preferences WHERE id = ?", {}, @@ -195,8 +186,7 @@ sub delete { ); } else { $valid->($opts); - my $sql = - "DELETE FROM item_circulation_alert_preferences + my $sql = "DELETE FROM item_circulation_alert_preferences WHERE branchcode = ? AND categorycode = ? AND item_type = ? @@ -212,9 +202,6 @@ sub delete { } } - - - =head3 C4::ItemCirculationAlertPreference->is_enabled_for(\%opts) Based on the existing preferences in the C @@ -237,7 +224,7 @@ B: =cut sub is_disabled_for { - my ($class, $opts) = @_; + my ( $class, $opts ) = @_; $valid->($opts); my $dbh = C4::Context->dbh; @@ -265,13 +252,10 @@ sub is_disabled_for { } sub is_enabled_for { - my ($class, $opts) = @_; + my ( $class, $opts ) = @_; return not $class->is_disabled_for($opts); } - - - =head3 C4::ItemCirculationAlertPreference->find({ branchcode => $bc, notification => $type }) This method returns all the item circulation alert preferences for a given @@ -287,25 +271,24 @@ B: =cut sub find { - my ($class, $where) = @_; - my $dbh = C4::Context->dbh; + my ( $class, $where ) = @_; + my $dbh = C4::Context->dbh; my $query = qq{ SELECT id, branchcode, categorycode, item_type, notification FROM item_circulation_alert_preferences WHERE branchcode = ? AND notification = ? ORDER BY categorycode, item_type }; - return map { $class->new($_) } @{$dbh->selectall_arrayref( - $query, - { Slice => {} }, - $where->{branchcode}, - $where->{notification}, - )}; + return map { $class->new($_) } @{ + $dbh->selectall_arrayref( + $query, + { Slice => {} }, + $where->{branchcode}, + $where->{notification}, + ) + }; } - - - =head3 C4::ItemCirculationAlertPreference->grid({ branchcode => $c, notification => $type }) Return a 2D arrayref for the grid view in F. @@ -328,21 +311,21 @@ See F to see how this method is used. =cut sub grid { - my ($class, $where) = @_; - my @branch_prefs = $class->find($where); - my @default_prefs = $class->find({ branchcode => '*', notification => $where->{notification} }); - my @cc = Koha::Patron::Categories->search_with_library_limits->as_list; - my @it = Koha::ItemTypes->search->as_list; - my $notification = $where->{notification}; - my %disabled = map { + my ( $class, $where ) = @_; + my @branch_prefs = $class->find($where); + my @default_prefs = $class->find( { branchcode => '*', notification => $where->{notification} } ); + my @cc = Koha::Patron::Categories->search_with_library_limits->as_list; + my @it = Koha::ItemTypes->search->as_list; + my $notification = $where->{notification}; + my %disabled = map { my $key = $_->categorycode . "-" . $_->item_type . "-" . $notification; $key =~ s/\*/_/g; - ($key => 1); + ( $key => 1 ); } @branch_prefs; my %default = map { my $key = $_->categorycode . "-" . $_->item_type . "-" . $notification; $key =~ s/\*/_/g; - ($key => 1); + ( $key => 1 ); } @default_prefs; my @grid; for my $c (@cc) { @@ -353,16 +336,16 @@ sub grid { $key =~ s/\*/_/g; my @classes; my $text = " "; - if ($disabled{$key}) { + if ( $disabled{$key} ) { push @classes, 'disabled'; $text = "Disabled for $where->{branchcode}"; } - if ($default{$key}) { + if ( $default{$key} ) { push @classes, 'default'; $text = "Disabled for all"; } - push @{$row->{items}}, { - class => join(' ', @classes), + push @{ $row->{items} }, { + class => join( ' ', @classes ), id => $key, text => $text, }; @@ -371,9 +354,6 @@ sub grid { return \@grid; } - - - =head2 Object Methods These are read-only accessors for the various attributes of a preference. @@ -402,7 +382,7 @@ sub AUTOLOAD { my $self = shift; my $attr = $AUTOLOAD; $attr =~ s/.*://; - if (exists $self->{$attr}) { + if ( exists $self->{$attr} ) { return $self->{$attr}; } else { return; @@ -411,8 +391,6 @@ sub AUTOLOAD { sub DESTROY { } - - =head1 SEE ALSO L, F diff --git a/C4/Items.pm b/C4/Items.pm index 82882dccf8..c0375939d6 100644 --- a/C4/Items.pm +++ b/C4/Items.pm @@ -20,7 +20,8 @@ package C4::Items; use Modern::Perl; -our (@ISA, @EXPORT_OK); +our ( @ISA, @EXPORT_OK ); + BEGIN { require Exporter; @ISA = qw(Exporter); @@ -44,17 +45,18 @@ BEGIN { ); } -use Carp qw( croak ); +use Carp qw( croak ); use C4::Circulation qw( barcodedecode ); use C4::Context; use C4::Koha; use C4::Biblio qw( GetMarcStructure TransformMarcToKoha ); use MARC::Record; use C4::ClassSource qw( GetClassSort GetClassSources GetClassSource ); -use C4::Log qw( logaction ); +use C4::Log qw( logaction ); use List::MoreUtils qw( any ); use DateTime::Format::MySQL; - # debugging; so please don't remove this + +# debugging; so please don't remove this use Try::Tiny qw( catch try ); use Koha::AuthorisedValues; @@ -119,15 +121,15 @@ location is a special processing ('PROC') or shelving cart =cut sub CartToShelf { - my ( $itemnumber ) = @_; + my ($itemnumber) = @_; - unless ( $itemnumber ) { + unless ($itemnumber) { croak "FAILED CartToShelf() - no itemnumber supplied"; } my $item = Koha::Items->find($itemnumber); if ( $item->location eq 'CART' ) { - $item->location($item->permanent_location)->store({ skip_holds_queue => 1 }); + $item->location( $item->permanent_location )->store( { skip_holds_queue => 1 } ); } } @@ -163,18 +165,18 @@ sub AddItemFromMarc { # parse item hash from MARC my $frameworkcode = C4::Biblio::GetFrameworkCode($biblionumber); - my ( $itemtag, $itemsubfield ) = C4::Biblio::GetMarcFromKohaField( "items.itemnumber" ); + my ( $itemtag, $itemsubfield ) = C4::Biblio::GetMarcFromKohaField("items.itemnumber"); my $localitemmarc = MARC::Record->new; $localitemmarc->append_fields( $source_item_marc->field($itemtag) ); - my $item_values = C4::Biblio::TransformMarcToKoha({ record => $localitemmarc, limit_table => 'items' }); + my $item_values = C4::Biblio::TransformMarcToKoha( { record => $localitemmarc, limit_table => 'items' } ); my $unlinked_item_subfields = _get_unlinked_item_subfields( $localitemmarc, $frameworkcode ); $item_values->{more_subfields_xml} = _get_unlinked_subfields_xml($unlinked_item_subfields); - $item_values->{biblionumber} = $biblionumber; - $item_values->{biblioitemnumber} = $params->{biblioitemnumber}; - $item_values->{cn_source} = delete $item_values->{'items.cn_source'}; # Because of C4::Biblio::_disambiguate - $item_values->{cn_sort} = delete $item_values->{'items.cn_sort'}; # Because of C4::Biblio::_disambiguate - my $item = Koha::Item->new( $item_values )->store({ skip_record_index => $params->{skip_record_index} }); + $item_values->{biblionumber} = $biblionumber; + $item_values->{biblioitemnumber} = $params->{biblioitemnumber}; + $item_values->{cn_source} = delete $item_values->{'items.cn_source'}; # Because of C4::Biblio::_disambiguate + $item_values->{cn_sort} = delete $item_values->{'items.cn_sort'}; # Because of C4::Biblio::_disambiguate + my $item = Koha::Item->new($item_values)->store( { skip_record_index => $params->{skip_record_index} } ); return ( $item->biblionumber, $item->biblioitemnumber, $item->itemnumber ); } @@ -224,51 +226,54 @@ Additional information appropriate to the error condition. =cut sub AddItemBatchFromMarc { - my ($record, $biblionumber, $biblioitemnumber, $frameworkcode) = @_; + my ( $record, $biblionumber, $biblioitemnumber, $frameworkcode ) = @_; my @itemnumbers = (); - my @errors = (); - my $dbh = C4::Context->dbh; + my @errors = (); + my $dbh = C4::Context->dbh; # We modify the record, so lets work on a clone so we don't change the # original. $record = $record->clone(); + # loop through the item tags and start creating items my @bad_item_fields = (); - my ($itemtag, $itemsubfield) = C4::Biblio::GetMarcFromKohaField( "items.itemnumber" ); + my ( $itemtag, $itemsubfield ) = C4::Biblio::GetMarcFromKohaField("items.itemnumber"); my $item_sequence_num = 0; - ITEMFIELD: foreach my $item_field ($record->field($itemtag)) { +ITEMFIELD: foreach my $item_field ( $record->field($itemtag) ) { $item_sequence_num++; + # we take the item field and stick it into a new # MARC record -- this is required so far because (FIXME) # TransformMarcToKoha requires a MARC::Record, not a MARC::Field # and there is no TransformMarcFieldToKoha my $temp_item_marc = MARC::Record->new(); $temp_item_marc->append_fields($item_field); - + # add biblionumber and biblioitemnumber - my $item = TransformMarcToKoha({ record => $temp_item_marc, limit_table => 'items' }); - my $unlinked_item_subfields = _get_unlinked_item_subfields($temp_item_marc, $frameworkcode); + my $item = TransformMarcToKoha( { record => $temp_item_marc, limit_table => 'items' } ); + my $unlinked_item_subfields = _get_unlinked_item_subfields( $temp_item_marc, $frameworkcode ); $item->{'more_subfields_xml'} = _get_unlinked_subfields_xml($unlinked_item_subfields); - $item->{'biblionumber'} = $biblionumber; - $item->{'biblioitemnumber'} = $biblioitemnumber; - $item->{cn_source} = delete $item->{'items.cn_source'}; # Because of C4::Biblio::_disambiguate - $item->{cn_sort} = delete $item->{'items.cn_sort'}; # Because of C4::Biblio::_disambiguate + $item->{'biblionumber'} = $biblionumber; + $item->{'biblioitemnumber'} = $biblioitemnumber; + $item->{cn_source} = delete $item->{'items.cn_source'}; # Because of C4::Biblio::_disambiguate + $item->{cn_sort} = delete $item->{'items.cn_sort'}; # Because of C4::Biblio::_disambiguate # check for duplicate barcode my %item_errors = CheckItemPreSave($item); if (%item_errors) { - push @errors, _repack_item_errors($item_sequence_num, $item, \%item_errors); + push @errors, _repack_item_errors( $item_sequence_num, $item, \%item_errors ); push @bad_item_fields, $item_field; next ITEMFIELD; } my $item_object = Koha::Item->new($item)->store; - push @itemnumbers, $item_object->itemnumber; # FIXME not checking error + push @itemnumbers, $item_object->itemnumber; # FIXME not checking error - logaction("CATALOGUING", "ADD", $item_object->itemnumber, "item") if C4::Context->preference("CataloguingLog"); + logaction( "CATALOGUING", "ADD", $item_object->itemnumber, "item" ) + if C4::Context->preference("CataloguingLog"); - my $new_item_marc = _marc_from_item_hash($item_object->unblessed, $frameworkcode, $unlinked_item_subfields); - $item_field->replace_with($new_item_marc->field($itemtag)); + my $new_item_marc = _marc_from_item_hash( $item_object->unblessed, $frameworkcode, $unlinked_item_subfields ); + $item_field->replace_with( $new_item_marc->field($itemtag) ); } # remove any MARC item fields for rejected items @@ -276,7 +281,7 @@ sub AddItemBatchFromMarc { $record->delete_field($item_field); } - return (\@itemnumbers, \@errors); + return ( \@itemnumbers, \@errors ); } =head2 ModItemFromMarc @@ -298,24 +303,25 @@ sub ModItemFromMarc { my ( $item_marc, $biblionumber, $itemnumber, $params ) = @_; my $frameworkcode = C4::Biblio::GetFrameworkCode($biblionumber); - my ( $itemtag, $itemsubfield ) = C4::Biblio::GetMarcFromKohaField( "items.itemnumber" ); + my ( $itemtag, $itemsubfield ) = C4::Biblio::GetMarcFromKohaField("items.itemnumber"); my $localitemmarc = MARC::Record->new; $localitemmarc->append_fields( $item_marc->field($itemtag) ); my $item_object = Koha::Items->find($itemnumber); - my $item = TransformMarcToKoha({ record => $localitemmarc, limit_table => 'items' }); + my $item = TransformMarcToKoha( { record => $localitemmarc, limit_table => 'items' } ); # When importing items we blank this column, we need to set it to the existing value # to prevent it being blanked by set_or_blank - $item->{onloan} = $item_object->onloan if( $item_object->onloan && !defined $item->{onloan} ); + $item->{onloan} = $item_object->onloan if ( $item_object->onloan && !defined $item->{onloan} ); # When importing and replacing items we should not remove the dateacquired so we should set it # to the existing value $item->{dateaccessioned} = $item_object->dateaccessioned - if ( $item_object->dateaccessioned && !defined $item->{dateaccessioned} ); + if ( $item_object->dateaccessioned && !defined $item->{dateaccessioned} ); - my ( $perm_loc_tag, $perm_loc_subfield ) = C4::Biblio::GetMarcFromKohaField( "items.permanent_location" ); - my $has_permanent_location = defined $perm_loc_tag && defined $item_marc->subfield( $perm_loc_tag, $perm_loc_subfield ); + my ( $perm_loc_tag, $perm_loc_subfield ) = C4::Biblio::GetMarcFromKohaField("items.permanent_location"); + my $has_permanent_location = + defined $perm_loc_tag && defined $item_marc->subfield( $perm_loc_tag, $perm_loc_subfield ); # Retrieving the values for the fields that are not linked my @mapped_fields = Koha::MarcSubfieldStructures->search( @@ -329,21 +335,21 @@ sub ModItemFromMarc { $item->{$c} = $item_object->$c; } - $item->{cn_source} = delete $item->{'items.cn_source'}; # Because of C4::Biblio::_disambiguate - delete $item->{'items.cn_sort'}; # Because of C4::Biblio::_disambiguate - $item->{itemnumber} = $itemnumber; + $item->{cn_source} = delete $item->{'items.cn_source'}; # Because of C4::Biblio::_disambiguate + delete $item->{'items.cn_sort'}; # Because of C4::Biblio::_disambiguate + $item->{itemnumber} = $itemnumber; $item->{biblionumber} = $biblionumber; - my $existing_cn_sort = $item_object->cn_sort; # set_or_blank will reset cn_sort to undef as we are not passing it - # We rely on Koha::Item->store to modify it if itemcallnumber or cn_source is modified + my $existing_cn_sort = $item_object->cn_sort; # set_or_blank will reset cn_sort to undef as we are not passing it + # We rely on Koha::Item->store to modify it if itemcallnumber or cn_source is modified $item_object = $item_object->set_or_blank($item); - $item_object->cn_sort($existing_cn_sort); # Resetting to the existing value + $item_object->cn_sort($existing_cn_sort); # Resetting to the existing value $item_object->make_column_dirty('permanent_location') if $has_permanent_location; my $unlinked_item_subfields = _get_unlinked_item_subfields( $localitemmarc, $frameworkcode ); - $item_object->more_subfields_xml(_get_unlinked_subfields_xml($unlinked_item_subfields)); - $item_object->store({ skip_record_index => $params->{skip_record_index} }); + $item_object->more_subfields_xml( _get_unlinked_subfields_xml($unlinked_item_subfields) ); + $item_object->store( { skip_record_index => $params->{skip_record_index} } ); return $item_object->unblessed; } @@ -441,9 +447,14 @@ sub ModDateLastSeen { my $item = Koha::Items->find($itemnumber); $item->datelastseen(dt_from_string); - my $log = $item->itemlost && !$leave_item_lost ? 1 : 0; # If item was lost, record the change to the item + my $log = $item->itemlost && !$leave_item_lost ? 1 : 0; # If item was lost, record the change to the item $item->itemlost(0) unless $leave_item_lost; - $item->store({ log_action => $log, skip_record_index => $params->{skip_record_index}, skip_holds_queue => $params->{skip_holds_queue} }); + $item->store( + { + log_action => $log, skip_record_index => $params->{skip_record_index}, + skip_holds_queue => $params->{skip_holds_queue} + } + ); } =head2 CheckItemPreSave @@ -509,17 +520,17 @@ sub CheckItemPreSave { } # check for valid home branch - if (exists $item_ref->{'homebranch'} and defined $item_ref->{'homebranch'}) { + if ( exists $item_ref->{'homebranch'} and defined $item_ref->{'homebranch'} ) { my $home_library = Koha::Libraries->find( $item_ref->{homebranch} ); - unless (defined $home_library) { + unless ( defined $home_library ) { $errors{'invalid_homebranch'} = $item_ref->{'homebranch'}; } } # check for valid holding branch - if (exists $item_ref->{'holdingbranch'} and defined $item_ref->{'holdingbranch'}) { + if ( exists $item_ref->{'holdingbranch'} and defined $item_ref->{'holdingbranch'} ) { my $holding_library = Koha::Libraries->find( $item_ref->{holdingbranch} ); - unless (defined $holding_library) { + unless ( defined $holding_library ) { $errors{'invalid_holdingbranch'} = $item_ref->{'holdingbranch'}; } } @@ -568,147 +579,155 @@ $iTotalRecords is the number of rows that would have been returned without the $ =cut sub GetItemsForInventory { - my ( $parameters ) = @_; - my $minlocation = $parameters->{'minlocation'} // ''; - my $maxlocation = $parameters->{'maxlocation'} // ''; - my $class_source = $parameters->{'class_source'} // C4::Context->preference('DefaultClassificationSource'); - my $location = $parameters->{'location'} // ''; - my $itemtype = $parameters->{'itemtype'} // ''; - my $ignoreissued = $parameters->{'ignoreissued'} // ''; - my $datelastseen = $parameters->{'datelastseen'} // ''; - my $branchcode = $parameters->{'branchcode'} // ''; - my $branch = $parameters->{'branch'} // ''; - my $offset = $parameters->{'offset'} // ''; - my $size = $parameters->{'size'} // ''; - my $statushash = $parameters->{'statushash'} // ''; + my ($parameters) = @_; + my $minlocation = $parameters->{'minlocation'} // ''; + my $maxlocation = $parameters->{'maxlocation'} // ''; + my $class_source = $parameters->{'class_source'} // C4::Context->preference('DefaultClassificationSource'); + my $location = $parameters->{'location'} // ''; + my $itemtype = $parameters->{'itemtype'} // ''; + my $ignoreissued = $parameters->{'ignoreissued'} // ''; + my $datelastseen = $parameters->{'datelastseen'} // ''; + my $branchcode = $parameters->{'branchcode'} // ''; + my $branch = $parameters->{'branch'} // ''; + my $offset = $parameters->{'offset'} // ''; + my $size = $parameters->{'size'} // ''; + my $statushash = $parameters->{'statushash'} // ''; my $ignore_waiting_holds = $parameters->{'ignore_waiting_holds'} // ''; - my $itemtypes = $parameters->{'itemtypes'} || []; - my $ccode = $parameters->{'ccode'} // ''; + my $itemtypes = $parameters->{'itemtypes'} || []; + my $ccode = $parameters->{'ccode'} // ''; my $dbh = C4::Context->dbh; my ( @bind_params, @where_strings ); - my $min_cnsort = GetClassSort($class_source,undef,$minlocation); - my $max_cnsort = GetClassSort($class_source,undef,$maxlocation); + my $min_cnsort = GetClassSort( $class_source, undef, $minlocation ); + my $max_cnsort = GetClassSort( $class_source, undef, $maxlocation ); my $select_columns = q{ SELECT DISTINCT(items.itemnumber), barcode, itemcallnumber, title, author, biblio.biblionumber, biblio.frameworkcode, datelastseen, homebranch, location, notforloan, damaged, itemlost, withdrawn, stocknumber, items.cn_sort, ccode }; my $select_count = q{SELECT COUNT(DISTINCT(items.itemnumber))}; - my $query = q{ + my $query = q{ FROM items LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber LEFT JOIN biblioitems on items.biblionumber = biblioitems.biblionumber }; - if ($statushash){ - for my $authvfield (keys %$statushash){ - if ( scalar @{$statushash->{$authvfield}} > 0 ){ - my $joinedvals = join ',', @{$statushash->{$authvfield}}; + if ($statushash) { + for my $authvfield ( keys %$statushash ) { + if ( scalar @{ $statushash->{$authvfield} } > 0 ) { + my $joinedvals = join ',', @{ $statushash->{$authvfield} }; push @where_strings, "$authvfield in (" . $joinedvals . ")"; } } } - if ($ccode){ + if ($ccode) { push @where_strings, 'ccode = ?'; - push @bind_params, $ccode; + push @bind_params, $ccode; } if ($minlocation) { push @where_strings, 'items.cn_sort >= ?'; - push @bind_params, $min_cnsort; + push @bind_params, $min_cnsort; } if ($maxlocation) { push @where_strings, 'items.cn_sort <= ?'; - push @bind_params, $max_cnsort; + push @bind_params, $max_cnsort; } if ($datelastseen) { push @where_strings, '(datelastseen < ? OR datelastseen IS NULL)'; - push @bind_params, $datelastseen; + push @bind_params, $datelastseen; } - if ( $location ) { + if ($location) { push @where_strings, 'items.location = ?'; - push @bind_params, $location; + push @bind_params, $location; } - if ( $branchcode ) { - if($branch eq "homebranch"){ - push @where_strings, 'items.homebranch = ?'; - }else{ + if ($branchcode) { + if ( $branch eq "homebranch" ) { + push @where_strings, 'items.homebranch = ?'; + } else { push @where_strings, 'items.holdingbranch = ?'; } push @bind_params, $branchcode; } - if ( $itemtype ) { + if ($itemtype) { push @where_strings, 'biblioitems.itemtype = ?'; - push @bind_params, $itemtype; + push @bind_params, $itemtype; } - if ( $ignoreissued) { + if ($ignoreissued) { $query .= "LEFT JOIN issues ON items.itemnumber = issues.itemnumber "; push @where_strings, 'issues.date_due IS NULL'; } - if ( $ignore_waiting_holds ) { + if ($ignore_waiting_holds) { $query .= "LEFT JOIN reserves ON items.itemnumber = reserves.itemnumber "; push( @where_strings, q{(reserves.found != 'W' OR reserves.found IS NULL)} ); } - if ( @$itemtypes ) { + if (@$itemtypes) { my $itemtypes_str = join ', ', @$itemtypes; - push @where_strings, "( biblioitems.itemtype IN (" . $itemtypes_str . ") OR items.itype IN (" . $itemtypes_str . ") )"; + push @where_strings, + "( biblioitems.itemtype IN (" . $itemtypes_str . ") OR items.itype IN (" . $itemtypes_str . ") )"; } - if ( @where_strings ) { + if (@where_strings) { $query .= 'WHERE '; $query .= join ' AND ', @where_strings; } my $count_query = $select_count . $query; $query .= ' ORDER BY items.cn_sort, itemcallnumber, title'; - $query .= " LIMIT $offset, $size" if ($offset and $size); + $query .= " LIMIT $offset, $size" if ( $offset and $size ); $query = $select_columns . $query; my $sth = $dbh->prepare($query); - $sth->execute( @bind_params ); + $sth->execute(@bind_params); - my @results = (); - my $tmpresults = $sth->fetchall_arrayref({}); - $sth = $dbh->prepare( $count_query ); - $sth->execute( @bind_params ); + my @results = (); + my $tmpresults = $sth->fetchall_arrayref( {} ); + $sth = $dbh->prepare($count_query); + $sth->execute(@bind_params); my ($iTotalRecords) = $sth->fetchrow_array(); my @avs = Koha::AuthorisedValues->search( - { 'marc_subfield_structures.kohafield' => { '>' => '' }, + { + 'marc_subfield_structures.kohafield' => { '>' => '' }, 'me.authorised_value' => { '>' => '' }, }, - { join => { category => 'marc_subfield_structures' }, - distinct => ['marc_subfield_structures.kohafield, me.category, frameworkcode, me.authorised_value'], - '+select' => [ 'marc_subfield_structures.kohafield', 'marc_subfield_structures.frameworkcode', 'me.authorised_value', 'me.lib' ], - '+as' => [ 'kohafield', 'frameworkcode', 'authorised_value', 'lib' ], + { + join => { category => 'marc_subfield_structures' }, + distinct => ['marc_subfield_structures.kohafield, me.category, frameworkcode, me.authorised_value'], + '+select' => [ + 'marc_subfield_structures.kohafield', 'marc_subfield_structures.frameworkcode', 'me.authorised_value', + 'me.lib' + ], + '+as' => [ 'kohafield', 'frameworkcode', 'authorised_value', 'lib' ], } )->as_list; - my $avmapping = { map { $_->get_column('kohafield') . ',' . $_->get_column('frameworkcode') . ',' . $_->get_column('authorised_value') => $_->get_column('lib') } @avs }; + my $avmapping = { + map { + $_->get_column('kohafield') . ',' + . $_->get_column('frameworkcode') . ',' + . $_->get_column('authorised_value') => $_->get_column('lib') + } @avs + }; foreach my $row (@$tmpresults) { # Auth values - foreach (keys %$row) { - if ( - defined( - $avmapping->{ "items.$_," . $row->{'frameworkcode'} . "," . ( $row->{$_} // q{} ) } - ) - ) { - $row->{$_} = $avmapping->{"items.$_,".$row->{'frameworkcode'}.",".$row->{$_}}; + foreach ( keys %$row ) { + if ( defined( $avmapping->{ "items.$_," . $row->{'frameworkcode'} . "," . ( $row->{$_} // q{} ) } ) ) { + $row->{$_} = $avmapping->{ "items.$_," . $row->{'frameworkcode'} . "," . $row->{$_} }; } } push @results, $row; } - return (\@results, $iTotalRecords); + return ( \@results, $iTotalRecords ); } =head2 get_hostitemnumbers_of @@ -722,15 +741,14 @@ references on array of itemnumbers. =cut - sub get_hostitemnumbers_of { my ($biblionumber) = @_; - if( !C4::Context->preference('EasyAnalyticalRecords') ) { + if ( !C4::Context->preference('EasyAnalyticalRecords') ) { return (); } - my $biblio = Koha::Biblios->find($biblionumber); + my $biblio = Koha::Biblios->find($biblionumber); my $marcrecord = $biblio->metadata->record; return unless $marcrecord; @@ -741,8 +759,7 @@ sub get_hostitemnumbers_of { $tag = '773'; $biblio_s = '0'; $item_s = '9'; - } - elsif ( $marcflavor eq 'UNIMARC' ) { + } elsif ( $marcflavor eq 'UNIMARC' ) { $tag = '461'; $biblio_s = '0'; $item_s = '9'; @@ -750,15 +767,16 @@ sub get_hostitemnumbers_of { foreach my $hostfield ( $marcrecord->field($tag) ) { my $hostbiblionumber = $hostfield->subfield($biblio_s); - next unless $hostbiblionumber; # have tag, don't have $biblio_s subfield + next unless $hostbiblionumber; # have tag, don't have $biblio_s subfield my $linkeditemnumber = $hostfield->subfield($item_s); - if ( ! $linkeditemnumber ) { + if ( !$linkeditemnumber ) { warn "ERROR biblionumber $biblionumber has 773^0, but doesn't have 9"; next; } - my $is_from_biblio = Koha::Items->search({ itemnumber => $linkeditemnumber, biblionumber => $hostbiblionumber }); + my $is_from_biblio = + Koha::Items->search( { itemnumber => $linkeditemnumber, biblionumber => $hostbiblionumber } ); push @returnhostitemnumbers, $linkeditemnumber - if $is_from_biblio; + if $is_from_biblio; } return @returnhostitemnumbers; @@ -805,27 +823,27 @@ sub GetMarcItem { # Tack on 'items.' prefix to column names so that C4::Biblio::TransformKohaToMarc will work. # Also, don't emit a subfield if the underlying field is blank. - return Item2Marc($item->unblessed, $biblionumber); + return Item2Marc( $item->unblessed, $biblionumber ); } + sub Item2Marc { - my ($itemrecord,$biblionumber)=@_; - my $mungeditem = { - map { - defined($itemrecord->{$_}) && $itemrecord->{$_} ne '' ? ("items.$_" => $itemrecord->{$_}) : () - } keys %{ $itemrecord } + my ( $itemrecord, $biblionumber ) = @_; + my $mungeditem = { + map { defined( $itemrecord->{$_} ) && $itemrecord->{$_} ne '' ? ( "items.$_" => $itemrecord->{$_} ) : () } + keys %{$itemrecord} }; - my $framework = C4::Biblio::GetFrameworkCode( $biblionumber ); - my $itemmarc = C4::Biblio::TransformKohaToMarc( $mungeditem, { framework => $framework } ); + my $framework = C4::Biblio::GetFrameworkCode($biblionumber); + my $itemmarc = C4::Biblio::TransformKohaToMarc( $mungeditem, { framework => $framework } ); my ( $itemtag, $itemsubfield ) = C4::Biblio::GetMarcFromKohaField('items.itemnumber'); - my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml($mungeditem->{'items.more_subfields_xml'}); - if (defined $unlinked_item_subfields and $#$unlinked_item_subfields > -1) { - foreach my $field ($itemmarc->field($itemtag)){ + my $unlinked_item_subfields = _parse_unlinked_item_subfields_from_xml( $mungeditem->{'items.more_subfields_xml'} ); + if ( defined $unlinked_item_subfields and $#$unlinked_item_subfields > -1 ) { + foreach my $field ( $itemmarc->field($itemtag) ) { $field->add_subfields(@$unlinked_item_subfields); } } - return $itemmarc; + return $itemmarc; } =head1 PRIVATE FUNCTIONS AND VARIABLES @@ -852,33 +870,40 @@ of the item. =cut sub _marc_from_item_hash { - my $item = shift; + my $item = shift; my $frameworkcode = shift; my $unlinked_item_subfields; if (@_) { $unlinked_item_subfields = shift; } - + # Tack on 'items.' prefix to column names so lookup from MARC frameworks will work # Also, don't emit a subfield if the underlying field is blank. - my $mungeditem = { map { (defined($item->{$_}) and $item->{$_} ne '') ? - (/^items\./ ? ($_ => $item->{$_}) : ("items.$_" => $item->{$_})) - : () } keys %{ $item } }; + my $mungeditem = { + map { + ( defined( $item->{$_} ) and $item->{$_} ne '' ) + ? ( /^items\./ ? ( $_ => $item->{$_} ) : ( "items.$_" => $item->{$_} ) ) + : () + } keys %{$item} + }; my $item_marc = MARC::Record->new(); foreach my $item_field ( keys %{$mungeditem} ) { - my ( $tag, $subfield ) = C4::Biblio::GetMarcFromKohaField( $item_field ); + my ( $tag, $subfield ) = C4::Biblio::GetMarcFromKohaField($item_field); next unless defined $tag and defined $subfield; # skip if not mapped to MARC field - my @values = split(/\s?\|\s?/, $mungeditem->{$item_field}, -1); - foreach my $value (@values){ + my @values = split( /\s?\|\s?/, $mungeditem->{$item_field}, -1 ); + foreach my $value (@values) { if ( my $field = $item_marc->field($tag) ) { - $field->add_subfields( $subfield => $value ); + $field->add_subfields( $subfield => $value ); } else { my $add_subfields = []; - if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) { + if ( defined $unlinked_item_subfields + and ref($unlinked_item_subfields) eq 'ARRAY' + and $#$unlinked_item_subfields > -1 ) + { $add_subfields = $unlinked_item_subfields; - } - $item_marc->add_fields( $tag, " ", " ", $subfield => $value, @$add_subfields ); + } + $item_marc->add_fields( $tag, " ", " ", $subfield => $value, @$add_subfields ); } } } @@ -895,19 +920,19 @@ to a list of errors. sub _repack_item_errors { my $item_sequence_num = shift; - my $item_ref = shift; - my $error_ref = shift; + my $item_ref = shift; + my $error_ref = shift; my @repacked_errors = (); - foreach my $error_code (sort keys %{ $error_ref }) { + foreach my $error_code ( sort keys %{$error_ref} ) { my $repacked_error = {}; - $repacked_error->{'item_sequence'} = $item_sequence_num; - $repacked_error->{'item_barcode'} = exists($item_ref->{'barcode'}) ? $item_ref->{'barcode'} : ''; - $repacked_error->{'error_code'} = $error_code; + $repacked_error->{'item_sequence'} = $item_sequence_num; + $repacked_error->{'item_barcode'} = exists( $item_ref->{'barcode'} ) ? $item_ref->{'barcode'} : ''; + $repacked_error->{'error_code'} = $error_code; $repacked_error->{'error_information'} = $error_ref->{$error_code}; push @repacked_errors, $repacked_error; - } + } return @repacked_errors; } @@ -920,21 +945,22 @@ sub _repack_item_errors { sub _get_unlinked_item_subfields { my $original_item_marc = shift; - my $frameworkcode = shift; + my $frameworkcode = shift; - my $marcstructure = C4::Biblio::GetMarcStructure(1, $frameworkcode, { unsafe => 1 }); + my $marcstructure = C4::Biblio::GetMarcStructure( 1, $frameworkcode, { unsafe => 1 } ); # assume that this record has only one field, and that that # field contains only the item information my $subfields = []; - my @fields = $original_item_marc->fields(); - if ($#fields > -1) { + my @fields = $original_item_marc->fields(); + if ( $#fields > -1 ) { my $field = $fields[0]; - my $tag = $field->tag(); - foreach my $subfield ($field->subfields()) { - if (defined $subfield->[1] and - $subfield->[1] ne '' and - !$marcstructure->{$tag}->{$subfield->[0]}->{'kohafield'}) { + my $tag = $field->tag(); + foreach my $subfield ( $field->subfields() ) { + if ( defined $subfield->[1] + and $subfield->[1] ne '' + and !$marcstructure->{$tag}->{ $subfield->[0] }->{'kohafield'} ) + { push @$subfields, $subfield->[0] => $subfield->[1]; } } @@ -952,12 +978,16 @@ sub _get_unlinked_subfields_xml { my $unlinked_item_subfields = shift; my $xml; - if (defined $unlinked_item_subfields and ref($unlinked_item_subfields) eq 'ARRAY' and $#$unlinked_item_subfields > -1) { + if ( defined $unlinked_item_subfields + and ref($unlinked_item_subfields) eq 'ARRAY' + and $#$unlinked_item_subfields > -1 ) + { my $marc = MARC::Record->new(); + # use of tag 999 is arbitrary, and doesn't need to match the item tag # used in the framework - $marc->append_fields(MARC::Field->new('999', ' ', ' ', @$unlinked_item_subfields)); - $marc->encoding("UTF-8"); + $marc->append_fields( MARC::Field->new( '999', ' ', ' ', @$unlinked_item_subfields ) ); + $marc->encoding("UTF-8"); $xml = $marc->as_xml("USMARC"); } @@ -970,15 +1000,15 @@ sub _get_unlinked_subfields_xml { =cut -sub _parse_unlinked_item_subfields_from_xml { +sub _parse_unlinked_item_subfields_from_xml { my $xml = shift; require C4::Charset; return unless defined $xml and $xml ne ""; - my $marc = MARC::Record->new_from_xml(C4::Charset::StripNonXmlChars($xml),'UTF-8'); + my $marc = MARC::Record->new_from_xml( C4::Charset::StripNonXmlChars($xml), 'UTF-8' ); my $unlinked_subfields = []; - my @fields = $marc->fields(); - if ($#fields > -1) { - foreach my $subfield ($fields[0]->subfields()) { + my @fields = $marc->fields(); + if ( $#fields > -1 ) { + foreach my $subfield ( $fields[0]->subfields() ) { push @$unlinked_subfields, $subfield->[0] => $subfield->[1]; } } @@ -1002,9 +1032,9 @@ sub GetAnalyticsCount { ### ZOOM search here my $query; - $query= "hi=".$itemnumber; - my $searcher = Koha::SearchEngine::Search->new({index => $Koha::SearchEngine::BIBLIOS_INDEX}); - my ($err,$res,$result) = $searcher->simple_search_compat($query,0,10); + $query = "hi=" . $itemnumber; + my $searcher = Koha::SearchEngine::Search->new( { index => $Koha::SearchEngine::BIBLIOS_INDEX } ); + my ( $err, $res, $result ) = $searcher->simple_search_compat( $query, 0, 10 ); return ($result); } @@ -1014,9 +1044,9 @@ sub _SearchItems_build_where_fragment { my $dbh = C4::Context->dbh; my $where_fragment; - if (exists($filter->{conjunction})) { - my (@where_strs, @where_args); - foreach my $f (@{ $filter->{filters} }) { + if ( exists( $filter->{conjunction} ) ) { + my ( @where_strs, @where_args ); + foreach my $f ( @{ $filter->{filters} } ) { my $fragment = _SearchItems_build_where_fragment($f); if ($fragment) { push @where_strs, $fragment->{str}; @@ -1025,9 +1055,9 @@ sub _SearchItems_build_where_fragment { } my $where_str = ''; if (@where_strs) { - $where_str = '(' . join (' ' . $filter->{conjunction} . ' ', @where_strs) . ')'; + $where_str = '(' . join( ' ' . $filter->{conjunction} . ' ', @where_strs ) . ')'; $where_fragment = { - str => $where_str, + str => $where_str, args => \@where_args, }; } @@ -1039,39 +1069,42 @@ sub _SearchItems_build_where_fragment { my @operators = qw(= != > < >= <= is like); push @operators, 'not like'; my $field = $filter->{field} // q{}; - if ( (0 < grep { $_ eq $field } @columns) or (substr($field, 0, 5) eq 'marc:') ) { - my $op = $filter->{operator}; - my $query = $filter->{query}; + if ( ( 0 < grep { $_ eq $field } @columns ) or ( substr( $field, 0, 5 ) eq 'marc:' ) ) { + my $op = $filter->{operator}; + my $query = $filter->{query}; my $ifnull = $filter->{ifnull}; - if (!$op or (0 == grep { $_ eq $op } @operators)) { - $op = '='; # default operator + if ( !$op or ( 0 == grep { $_ eq $op } @operators ) ) { + $op = '='; # default operator } my $column; - if ($field =~ /^marc:(\d{3})(?:\$(\w))?$/) { - my $marcfield = $1; + if ( $field =~ /^marc:(\d{3})(?:\$(\w))?$/ ) { + my $marcfield = $1; my $marcsubfield = $2; - my ($kohafield) = $dbh->selectrow_array(q| + my ($kohafield) = $dbh->selectrow_array( + q| SELECT kohafield FROM marc_subfield_structure WHERE tagfield=? AND tagsubfield=? AND frameworkcode='' - |, undef, $marcfield, $marcsubfield); + |, undef, $marcfield, $marcsubfield + ); if ($kohafield) { $column = $kohafield; } else { + # MARC field is not linked to a DB field so we need to use # ExtractValue on marcxml from biblio_metadata or # items.more_subfields_xml, depending on the MARC field. my $xpath; my $sqlfield; my ($itemfield) = C4::Biblio::GetMarcFromKohaField('items.itemnumber'); - if ($marcfield eq $itemfield) { + if ( $marcfield eq $itemfield ) { $sqlfield = 'more_subfields_xml'; - $xpath = '//record/datafield/subfield[@code="' . $marcsubfield . '"]'; + $xpath = '//record/datafield/subfield[@code="' . $marcsubfield . '"]'; } else { - $sqlfield = 'metadata'; # From biblio_metadata - if ($marcfield < 10) { + $sqlfield = 'metadata'; # From biblio_metadata + if ( $marcfield < 10 ) { $xpath = "//record/controlfield[\@tag=\"$marcfield\"]"; } else { $xpath = "//record/datafield[\@tag=\"$marcfield\"]/subfield[\@code=\"$marcsubfield\"]"; @@ -1079,18 +1112,16 @@ sub _SearchItems_build_where_fragment { } $column = "ExtractValue($sqlfield, '$xpath')"; } - } - elsif ($field eq 'isbn') { + } elsif ( $field eq 'isbn' ) { if ( C4::Context->preference("SearchWithISBNVariations") and $query ) { - my @isbns = C4::Koha::GetVariationsOfISBN( $query ); + my @isbns = C4::Koha::GetVariationsOfISBN($query); $query = []; push @$query, @isbns; } $column = $field; - } - elsif ($field eq 'issn') { + } elsif ( $field eq 'issn' ) { if ( C4::Context->preference("SearchWithISSNVariations") and $query ) { - my @issns = C4::Koha::GetVariationsOfISSN( $query ); + my @issns = C4::Koha::GetVariationsOfISSN($query); $query = []; push @$query, @issns; } @@ -1103,33 +1134,32 @@ sub _SearchItems_build_where_fragment { $column = "COALESCE($column, ?)"; } - if (ref $query eq 'ARRAY') { - if ($op eq 'like') { + if ( ref $query eq 'ARRAY' ) { + if ( $op eq 'like' ) { $where_fragment = { - str => "($column LIKE " . join (" OR $column LIKE ", ('?') x @$query ) . ")", + str => "($column LIKE " . join( " OR $column LIKE ", ('?') x @$query ) . ")", args => $query, }; - } - else { - if ($op eq '=') { + } else { + if ( $op eq '=' ) { $op = 'IN'; - } elsif ($op eq '!=') { + } elsif ( $op eq '!=' ) { $op = 'NOT IN'; } $where_fragment = { - str => "$column $op (" . join (',', ('?') x @$query) . ")", + str => "$column $op (" . join( ',', ('?') x @$query ) . ")", args => $query, }; } } elsif ( $op eq 'is' ) { $where_fragment = { - str => "$column $op $query", + str => "$column $op $query", args => [], }; } else { $where_fragment = { - str => "$column $op ?", - args => [ $query ], + str => "$column $op ?", + args => [$query], }; } @@ -1190,7 +1220,7 @@ $params is a reference to a hash that can contain the following parameters: =cut sub SearchItems { - my ($filter, $params) = @_; + my ( $filter, $params ) = @_; $filter //= {}; $params //= {}; @@ -1198,19 +1228,19 @@ sub SearchItems { return unless ref $params eq 'HASH'; # Default parameters - $params->{rows} ||= 0; - $params->{page} ||= 1; - $params->{sortby} ||= 'itemnumber'; + $params->{rows} ||= 0; + $params->{page} ||= 1; + $params->{sortby} ||= 'itemnumber'; $params->{sortorder} ||= 'ASC'; - my ($where_str, @where_args); + my ( $where_str, @where_args ); my $where_fragment = _SearchItems_build_where_fragment($filter); if ($where_fragment) { - $where_str = $where_fragment->{str}; + $where_str = $where_fragment->{str}; @where_args = @{ $where_fragment->{args} }; } - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $query = q{ SELECT SQL_CALC_FOUND_ROWS items.* FROM items @@ -1220,7 +1250,7 @@ sub SearchItems { LEFT JOIN issues USING (itemnumber) WHERE 1 }; - if (defined $where_str and $where_str ne '') { + if ( defined $where_str and $where_str ne '' ) { $query .= qq{ AND $where_str }; } @@ -1233,34 +1263,32 @@ sub SearchItems { push @columns, Koha::Database->new()->schema()->resultset('Issue')->result_source->columns; if ( $params->{sortby} eq 'availability' ) { - my $sortorder = (uc($params->{sortorder}) eq 'ASC') ? 'ASC' : 'DESC'; + my $sortorder = ( uc( $params->{sortorder} ) eq 'ASC' ) ? 'ASC' : 'DESC'; $query .= qq{ ORDER BY onloan $sortorder }; } else { - my $sortby = (0 < grep {$params->{sortby} eq $_} @columns) - ? $params->{sortby} : 'itemnumber'; + my $sortby = ( 0 < grep { $params->{sortby} eq $_ } @columns ) ? $params->{sortby} : 'itemnumber'; $sortby = 'cn_sort' if $sortby eq 'itemcallnumber'; - my $sortorder = (uc($params->{sortorder}) eq 'ASC') ? 'ASC' : 'DESC'; + my $sortorder = ( uc( $params->{sortorder} ) eq 'ASC' ) ? 'ASC' : 'DESC'; $query .= qq{ ORDER BY $sortby $sortorder }; } my $rows = $params->{rows}; my @limit_args; - if ($rows > 0) { - my $offset = $rows * ($params->{page}-1); + if ( $rows > 0 ) { + my $offset = $rows * ( $params->{page} - 1 ); $query .= qq { LIMIT ?, ? }; push @limit_args, $offset, $rows; } my $sth = $dbh->prepare($query); - my $rv = $sth->execute(@where_args, @limit_args); + my $rv = $sth->execute( @where_args, @limit_args ); return unless ($rv); my ($total_rows) = $dbh->selectrow_array(q{ SELECT FOUND_ROWS() }); - return ($sth->fetchall_arrayref({}), $total_rows); + return ( $sth->fetchall_arrayref( {} ), $total_rows ); } - =head1 OTHER FUNCTIONS =head2 _find_value @@ -1302,7 +1330,6 @@ sub _find_value { return ( $indicator, @result ); } - =head2 PrepareItemrecordDisplay PrepareItemrecordDisplay($bibnum,$itemumber,$defaultvalues,$frameworkcode); @@ -1321,7 +1348,7 @@ sub PrepareItemrecordDisplay { my $dbh = C4::Context->dbh; $frameworkcode = C4::Biblio::GetFrameworkCode($bibnum) if $bibnum; - my ( $itemtagfield, $itemtagsubfield ) = C4::Biblio::GetMarcFromKohaField( "items.itemnumber" ); + my ( $itemtagfield, $itemtagsubfield ) = C4::Biblio::GetMarcFromKohaField("items.itemnumber"); # Note: $tagslib obtained from GetMarcStructure() in 'unsafe' mode is # a shared data structure. No plugin (including custom ones) should change @@ -1343,7 +1370,7 @@ sub PrepareItemrecordDisplay { my @loop_data; my $branch_limit = C4::Context->userenv ? C4::Context->userenv->{"branch"} : ""; - my $query = qq{ + my $query = qq{ SELECT authorised_value,lib FROM authorised_values }; $query .= qq{ @@ -1354,7 +1381,8 @@ sub PrepareItemrecordDisplay { }; $query .= qq{ AND ( branchcode = ? OR branchcode IS NULL )} if $branch_limit; $query .= qq{ ORDER BY lib}; - my $authorised_values_sth = $dbh->prepare( $query ); + my $authorised_values_sth = $dbh->prepare($query); + foreach my $tag ( sort keys %{$tagslib} ) { if ( $tag ne '' ) { @@ -1362,8 +1390,9 @@ sub PrepareItemrecordDisplay { my $cntsubf; foreach my $subfield ( sort { $a->{display_order} <=> $b->{display_order} || $a->{subfield} cmp $b->{subfield} } - grep { ref($_) && %$_ } # Not a subfield (values for "important", "lib", "mandatory", etc.) or empty - values %{ $tagslib->{$tag} } ) + grep { ref($_) && %$_ } # Not a subfield (values for "important", "lib", "mandatory", etc.) or empty + values %{ $tagslib->{$tag} } + ) { next unless ( $subfield->{'tab'} ); next if ( $subfield->{'tab'} ne "10" ); @@ -1372,14 +1401,14 @@ sub PrepareItemrecordDisplay { $subfield_data{subfield} = $subfield->{subfield}; $subfield_data{countsubfield} = $cntsubf++; $subfield_data{kohafield} = $subfield->{kohafield}; - $subfield_data{id} = "tag_".$tag."_subfield_".$subfield->{subfield}."_".int(rand(1000000)); + $subfield_data{id} = "tag_" . $tag . "_subfield_" . $subfield->{subfield} . "_" . int( rand(1000000) ); # $subfield_data{marc_lib}=$tagslib->{$tag}->{$subfield}->{lib}; $subfield_data{marc_lib} = $subfield->{lib}; $subfield_data{mandatory} = $subfield->{mandatory}; $subfield_data{repeatable} = $subfield->{repeatable}; $subfield_data{hidden} = "display:none" - if ( ( $subfield->{hidden} > 4 ) + if ( ( $subfield->{hidden} > 4 ) || ( $subfield->{hidden} < -4 ) ); my ( $x, $defaultvalue ); if ($itemrecord) { @@ -1390,74 +1419,87 @@ sub PrepareItemrecordDisplay { $defaultvalue = q||; } else { $defaultvalue =~ s/"/"/g; + # get today date & replace <>, <>, <
> if provided in the default value - my $today_dt = dt_from_string; - my $year = $today_dt->strftime('%Y'); - my $shortyear = $today_dt->strftime('%y'); - my $month = $today_dt->strftime('%m'); - my $day = $today_dt->strftime('%d'); + my $today_dt = dt_from_string; + my $year = $today_dt->strftime('%Y'); + my $shortyear = $today_dt->strftime('%y'); + my $month = $today_dt->strftime('%m'); + my $day = $today_dt->strftime('%d'); $defaultvalue =~ s/<>/$year/g; $defaultvalue =~ s/<>/$shortyear/g; $defaultvalue =~ s/<>/$month/g; $defaultvalue =~ s/<
>/$day/g; # And <> with surname (?) - my $username = - ( C4::Context->userenv + my $username = ( + C4::Context->userenv ? C4::Context->userenv->{'surname'} - : "superlibrarian" ); + : "superlibrarian" + ); $defaultvalue =~ s/<>/$username/g; } my $maxlength = $subfield->{maxlength}; # search for itemcallnumber if applicable - if ( $subfield->{kohafield} eq 'items.itemcallnumber' - && C4::Context->preference('itemcallnumber') && $itemrecord) { - foreach my $itemcn_pref (split(/,/,C4::Context->preference('itemcallnumber'))){ - my $CNtag = substr( $itemcn_pref, 0, 3 ); + if ( $subfield->{kohafield} eq 'items.itemcallnumber' + && C4::Context->preference('itemcallnumber') + && $itemrecord ) + { + foreach my $itemcn_pref ( split( /,/, C4::Context->preference('itemcallnumber') ) ) { + my $CNtag = substr( $itemcn_pref, 0, 3 ); next unless my $field = $itemrecord->field($CNtag); my $CNsubfields = substr( $itemcn_pref, 3 ); - $CNsubfields = undef if $CNsubfields eq ''; - $defaultvalue = $field->as_string( $CNsubfields, ' '); + $CNsubfields = undef if $CNsubfields eq ''; + $defaultvalue = $field->as_string( $CNsubfields, ' ' ); last if $defaultvalue; } } if ( $subfield->{kohafield} eq 'items.itemcallnumber' && $defaultvalues - && $defaultvalues->{'callnumber'} ) { - if( $itemrecord and $defaultvalues and not $itemrecord->subfield($tag,$subfield->{subfield}) ){ + && $defaultvalues->{'callnumber'} ) + { + if ( $itemrecord and $defaultvalues and not $itemrecord->subfield( $tag, $subfield->{subfield} ) ) { + # if the item record exists, only use default value if the item has no callnumber $defaultvalue = $defaultvalues->{callnumber}; } elsif ( !$itemrecord and $defaultvalues ) { + # if the item record *doesn't* exists, always use the default value $defaultvalue = $defaultvalues->{callnumber}; } } - if ( ( $subfield->{kohafield} eq 'items.holdingbranch' || $subfield->{kohafield} eq 'items.homebranch' ) + if ( ( $subfield->{kohafield} eq 'items.holdingbranch' || $subfield->{kohafield} eq 'items.homebranch' ) && $defaultvalues - && $defaultvalues->{'branchcode'} ) { - if ( $itemrecord and $defaultvalues and not $itemrecord->subfield($tag,$subfield) ) { + && $defaultvalues->{'branchcode'} ) + { + if ( $itemrecord and $defaultvalues and not $itemrecord->subfield( $tag, $subfield ) ) { $defaultvalue = $defaultvalues->{branchcode}; } } if ( ( $subfield->{kohafield} eq 'items.location' ) && $defaultvalues - && $defaultvalues->{'location'} ) { + && $defaultvalues->{'location'} ) + { + + if ( $itemrecord and $defaultvalues and not $itemrecord->subfield( $tag, $subfield->{subfield} ) ) { - if ( $itemrecord and $defaultvalues and not $itemrecord->subfield($tag,$subfield->{subfield}) ) { # if the item record exists, only use default value if the item has no locationr $defaultvalue = $defaultvalues->{location}; } elsif ( !$itemrecord and $defaultvalues ) { + # if the item record *doesn't* exists, always use the default value $defaultvalue = $defaultvalues->{location}; } } if ( ( $subfield->{kohafield} eq 'items.ccode' ) && $defaultvalues - && $defaultvalues->{'ccode'} ) { + && $defaultvalues->{'ccode'} ) + { if ( !$itemrecord and $defaultvalues ) { + # if the item record *doesn't* exists, always use the default value $defaultvalue = $defaultvalues->{ccode}; } @@ -1469,21 +1511,23 @@ sub PrepareItemrecordDisplay { # builds list, depending on authorised value... #---- branch if ( $subfield->{'authorised_value'} eq "branches" ) { - if ( ( C4::Context->preference("IndependentBranches") ) - && !C4::Context->IsSuperLibrarian() ) { - my $sth = $dbh->prepare( "SELECT branchcode,branchname FROM branches WHERE branchcode = ? ORDER BY branchname" ); + if ( ( C4::Context->preference("IndependentBranches") ) + && !C4::Context->IsSuperLibrarian() ) + { + my $sth = $dbh->prepare( + "SELECT branchcode,branchname FROM branches WHERE branchcode = ? ORDER BY branchname"); $sth->execute( C4::Context->userenv->{branch} ); push @authorised_values, "" - unless ( $subfield->{mandatory} ); + unless ( $subfield->{mandatory} ); while ( my ( $branchcode, $branchname ) = $sth->fetchrow_array ) { push @authorised_values, $branchcode; $authorised_lib{$branchcode} = $branchname; } } else { - my $sth = $dbh->prepare( "SELECT branchcode,branchname FROM branches ORDER BY branchname" ); + my $sth = $dbh->prepare("SELECT branchcode,branchname FROM branches ORDER BY branchname"); $sth->execute; push @authorised_values, "" - unless ( $subfield->{mandatory} ); + unless ( $subfield->{mandatory} ); while ( my ( $branchcode, $branchname ) = $sth->fetchrow_array ) { push @authorised_values, $branchcode; $authorised_lib{$branchcode} = $branchname; @@ -1501,9 +1545,9 @@ sub PrepareItemrecordDisplay { push @authorised_values, ""; while ( my $itemtype = $itemtypes->next ) { push @authorised_values, $itemtype->itemtype; - $authorised_lib{$itemtype->itemtype} = $itemtype->translated_description; + $authorised_lib{ $itemtype->itemtype } = $itemtype->translated_description; } - if ($defaultvalues && $defaultvalues->{'itemtype'}) { + if ( $defaultvalues && $defaultvalues->{'itemtype'} ) { $defaultvalue = $defaultvalues->{'itemtype'}; } @@ -1511,12 +1555,13 @@ sub PrepareItemrecordDisplay { } elsif ( $subfield->{authorised_value} eq "cn_source" ) { push @authorised_values, ""; - my $class_sources = GetClassSources(); + my $class_sources = GetClassSources(); my $default_source = $defaultvalue || C4::Context->preference("DefaultClassificationSource"); - foreach my $class_source (sort keys %$class_sources) { - next unless $class_sources->{$class_source}->{'used'} or - ($class_source eq $default_source); + foreach my $class_source ( sort keys %$class_sources ) { + next + unless $class_sources->{$class_source}->{'used'} + or ( $class_source eq $default_source ); push @authorised_values, $class_source; $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'}; } @@ -1542,44 +1587,55 @@ sub PrepareItemrecordDisplay { labels => \%authorised_lib, }; } elsif ( $subfield->{value_builder} ) { - # it is a plugin + + # it is a plugin require Koha::FrameworkPlugin; - my $plugin = Koha::FrameworkPlugin->new({ - name => $subfield->{value_builder}, - item_style => 1, - }); - my $pars = { dbh => $dbh, record => undef, tagslib =>$tagslib, id => $subfield_data{id} }; - $plugin->build( $pars ); + my $plugin = Koha::FrameworkPlugin->new( + { + name => $subfield->{value_builder}, + item_style => 1, + } + ); + my $pars = { dbh => $dbh, record => undef, tagslib => $tagslib, id => $subfield_data{id} }; + $plugin->build($pars); if ( $itemrecord and my $field = $itemrecord->field($tag) ) { - $defaultvalue = $field->subfield($subfield->{subfield}) || q{}; + $defaultvalue = $field->subfield( $subfield->{subfield} ) || q{}; } - if( !$plugin->errstr ) { + if ( !$plugin->errstr ) { + #TODO Move html to template; see report 12176/13397 - my $tab= $plugin->noclick? '-1': ''; - my $class= $plugin->noclick? ' disabled': ''; - my $title= $plugin->noclick? 'No popup': 'Tag editor'; - $subfield_data{marc_value} = qq[...\n].$plugin->javascript; + my $tab = $plugin->noclick ? '-1' : ''; + my $class = $plugin->noclick ? ' disabled' : ''; + my $title = $plugin->noclick ? 'No popup' : 'Tag editor'; + $subfield_data{marc_value} = + qq[...\n] + . $plugin->javascript; } else { warn $plugin->errstr; - $subfield_data{marc_value} = qq(); # supply default input form + $subfield_data{marc_value} = + qq() + ; # supply default input form } - } - elsif ( $tag eq '' ) { # it's an hidden field - $subfield_data{marc_value} = qq(); - } - elsif ( $subfield->{'hidden'} ) { # FIXME: shouldn't input type be "hidden" ? - $subfield_data{marc_value} = qq(); - } - elsif ( length($defaultvalue) > 100 - or (C4::Context->preference("marcflavour") eq "UNIMARC" and - 300 <= $tag && $tag < 400 && $subfield->{subfield} eq 'a' ) - or (C4::Context->preference("marcflavour") eq "MARC21" and - 500 <= $tag && $tag < 600 ) - ) { + } elsif ( $tag eq '' ) { # it's an hidden field + $subfield_data{marc_value} = + qq(); + } elsif ( $subfield->{'hidden'} ) { # FIXME: shouldn't input type be "hidden" ? + $subfield_data{marc_value} = + qq(); + } elsif ( + length($defaultvalue) > 100 + or ( C4::Context->preference("marcflavour") eq "UNIMARC" + and 300 <= $tag && $tag < 400 && $subfield->{subfield} eq 'a' ) + or ( C4::Context->preference("marcflavour") eq "MARC21" + and 500 <= $tag && $tag < 600 ) + ) + { # oversize field (textarea) - $subfield_data{marc_value} = qq(\n"); + $subfield_data{marc_value} = + qq(\n"); } else { - $subfield_data{marc_value} = qq(); + $subfield_data{marc_value} = + qq(); } push( @loop_data, \%subfield_data ); } diff --git a/C4/Koha.pm b/C4/Koha.pm index 1c3e2ceb2d..39e543b71d 100644 --- a/C4/Koha.pm +++ b/C4/Koha.pm @@ -19,7 +19,6 @@ package C4::Koha; # You should have received a copy of the GNU General Public License # along with Koha; if not, see . - use Modern::Perl; use C4::Context; @@ -31,32 +30,33 @@ use Business::ISBN; use Business::ISSN; use autouse 'Data::cselectall_arrayref' => qw(Dumper); -our (@ISA, @EXPORT_OK); +our ( @ISA, @EXPORT_OK ); + BEGIN { require Exporter; @ISA = qw(Exporter); @EXPORT_OK = qw( - GetItemTypesCategorized - getallthemes - getFacets - getImageSets - getnbpages - getitemtypeimagedir - getitemtypeimagesrc - getitemtypeimagelocation - GetAuthorisedValues - GetNormalizedUPC - GetNormalizedISBN - GetNormalizedEAN - GetNormalizedOCLCNumber - xml_escape + GetItemTypesCategorized + getallthemes + getFacets + getImageSets + getnbpages + getitemtypeimagedir + getitemtypeimagesrc + getitemtypeimagelocation + GetAuthorisedValues + GetNormalizedUPC + GetNormalizedISBN + GetNormalizedEAN + GetNormalizedOCLCNumber + xml_escape - GetVariationsOfISBN - GetVariationsOfISBNs - NormalizeISBN - GetVariationsOfISSN - GetVariationsOfISSNs - NormalizeISSN + GetVariationsOfISBN + GetVariationsOfISBNs + NormalizeISBN + GetVariationsOfISSN + GetVariationsOfISSNs + NormalizeISSN ); } @@ -88,7 +88,8 @@ The categories must be part of Authorized Values (ITEMTYPECAT) =cut sub GetItemTypesCategorized { - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; + # Order is important, so that partially hidden (some items are not visible in OPAC) search # categories will be visible. hideinopac=0 must be last. my $query = q| @@ -110,7 +111,7 @@ sub GetItemTypesCategorized { LEFT JOIN authorised_values ON searchcategory = authorised_value WHERE searchcategory > '' and hideinopac=0 |; -return ($dbh->selectall_hashref($query,'itemtype')); + return ( $dbh->selectall_hashref( $query, 'itemtype' ) ); } =head2 getitemtypeimagedir @@ -124,34 +125,34 @@ returns the full path to the appropriate directory containing images. =cut sub getitemtypeimagedir { - my $src = shift || 'opac'; - if ($src eq 'intranet') { - return C4::Context->config('intrahtdocs') . '/' .C4::Context->preference('template') . '/img/itemtypeimg'; - } else { - return C4::Context->config('opachtdocs') . '/' . C4::Context->preference('opacthemes') . '/itemtypeimg'; - } + my $src = shift || 'opac'; + if ( $src eq 'intranet' ) { + return C4::Context->config('intrahtdocs') . '/' . C4::Context->preference('template') . '/img/itemtypeimg'; + } else { + return C4::Context->config('opachtdocs') . '/' . C4::Context->preference('opacthemes') . '/itemtypeimg'; + } } sub getitemtypeimagesrc { - my $src = shift || 'opac'; - if ($src eq 'intranet') { - return '/intranet-tmpl' . '/' . C4::Context->preference('template') . '/img/itemtypeimg'; - } else { - return '/opac-tmpl' . '/' . C4::Context->preference('opacthemes') . '/itemtypeimg'; - } + my $src = shift || 'opac'; + if ( $src eq 'intranet' ) { + return '/intranet-tmpl' . '/' . C4::Context->preference('template') . '/img/itemtypeimg'; + } else { + return '/opac-tmpl' . '/' . C4::Context->preference('opacthemes') . '/itemtypeimg'; + } } sub getitemtypeimagelocation { - my ( $src, $image ) = @_; + my ( $src, $image ) = @_; - return '' if ( !$image ); + return '' if ( !$image ); require URI::Split; - my $scheme = ( URI::Split::uri_split( $image ) )[0]; + my $scheme = ( URI::Split::uri_split($image) )[0]; - return $image if ( $scheme ); + return $image if ($scheme); - return getitemtypeimagesrc( $src ) . '/' . $image; + return getitemtypeimagesrc($src) . '/' . $image; } =head3 _getImagesFromDirectory @@ -174,8 +175,8 @@ sub _getImagesFromDirectory { return unless defined $directoryname; return unless -d $directoryname; - if ( opendir ( my $dh, $directoryname ) ) { - my @images = grep { /\.(gif|png)$/i } readdir( $dh ); + if ( opendir( my $dh, $directoryname ) ) { + my @images = grep { /\.(gif|png)$/i } readdir($dh); closedir $dh; @images = sort(@images); return @images; @@ -204,8 +205,8 @@ sub _getSubdirectoryNames { return unless defined $directoryname; return unless -d $directoryname; - if ( opendir ( my $dh, $directoryname ) ) { - my @directories = grep { -d File::Spec->catfile( $directoryname, $_ ) && ! ( /^\./ ) } readdir( $dh ); + if ( opendir( my $dh, $directoryname ) ) { + my @directories = grep { -d File::Spec->catfile( $directoryname, $_ ) && !(/^\./) } readdir($dh); closedir $dh; return @directories; } else { @@ -234,37 +235,45 @@ each image is represented by a hashref like this: =cut sub getImageSets { - my %params = @_; + my %params = @_; my $checked = $params{'checked'} || ''; - my $paths = { staff => { filesystem => getitemtypeimagedir('intranet'), - url => getitemtypeimagesrc('intranet'), - }, - opac => { filesystem => getitemtypeimagedir('opac'), - url => getitemtypeimagesrc('opac'), - } - }; - - my @imagesets = (); # list of hasrefs of image set data to pass to template - my @subdirectories = _getSubdirectoryNames( $paths->{'staff'}{'filesystem'} ); - foreach my $imagesubdir ( @subdirectories ) { - my @imagelist = (); # hashrefs of image info - my @imagenames = _getImagesFromDirectory( File::Spec->catfile( $paths->{'staff'}{'filesystem'}, $imagesubdir ) ); - my $imagesetactive = 0; - foreach my $thisimage ( @imagenames ) { - push( @imagelist, - { KohaImage => "$imagesubdir/$thisimage", - StaffImageUrl => join( '/', $paths->{'staff'}{'url'}, $imagesubdir, $thisimage ), - OpacImageUrl => join( '/', $paths->{'opac'}{'url'}, $imagesubdir, $thisimage ), - checked => "$imagesubdir/$thisimage" eq $checked ? 1 : 0, - } - ); - $imagesetactive = 1 if "$imagesubdir/$thisimage" eq $checked; + my $paths = { + staff => { + filesystem => getitemtypeimagedir('intranet'), + url => getitemtypeimagesrc('intranet'), + }, + opac => { + filesystem => getitemtypeimagedir('opac'), + url => getitemtypeimagesrc('opac'), } - push @imagesets, { imagesetname => $imagesubdir, - imagesetactive => $imagesetactive, - images => \@imagelist }; - + }; + + my @imagesets = (); # list of hasrefs of image set data to pass to template + my @subdirectories = _getSubdirectoryNames( $paths->{'staff'}{'filesystem'} ); + foreach my $imagesubdir (@subdirectories) { + my @imagelist = (); # hashrefs of image info + my @imagenames = + _getImagesFromDirectory( File::Spec->catfile( $paths->{'staff'}{'filesystem'}, $imagesubdir ) ); + my $imagesetactive = 0; + foreach my $thisimage (@imagenames) { + push( + @imagelist, + { + KohaImage => "$imagesubdir/$thisimage", + StaffImageUrl => join( '/', $paths->{'staff'}{'url'}, $imagesubdir, $thisimage ), + OpacImageUrl => join( '/', $paths->{'opac'}{'url'}, $imagesubdir, $thisimage ), + checked => "$imagesubdir/$thisimage" eq $checked ? 1 : 0, + } + ); + $imagesetactive = 1 if "$imagesubdir/$thisimage" eq $checked; + } + push @imagesets, { + imagesetname => $imagesubdir, + imagesetactive => $imagesetactive, + images => \@imagelist + }; + } return \@imagesets; } @@ -297,8 +306,7 @@ sub getallthemes { my @themes; if ( $type eq 'intranet' ) { $htdocs = C4::Context->config('intrahtdocs'); - } - else { + } else { $htdocs = C4::Context->config('opachtdocs'); } my $dir_h; @@ -319,58 +327,57 @@ sub getFacets { { idx => 'su-to', label => 'Topics', - tags => [ qw/ 600ab 601ab 602a 604at 605a 606ax 610a / ], + tags => [qw/ 600ab 601ab 602a 604at 605a 606ax 610a /], sep => ' - ', }, { idx => 'su-geo', label => 'Places', - tags => [ qw/ 607a / ], + tags => [qw/ 607a /], sep => ' - ', }, { idx => 'au', label => 'Authors', - tags => [ qw/ 700ab 701ab 702ab / ], + tags => [qw/ 700ab 701ab 702ab /], sep => C4::Context->preference("UNIMARCAuthorsFacetsSeparator"), }, { idx => 'se', label => 'Series', - tags => [ qw/ 225a / ], + tags => [qw/ 225a /], sep => ', ', }, { - idx => 'location', + idx => 'location', label => 'Location', - tags => [ qw/ 995e / ], + tags => [qw/ 995e /], }, { - idx => 'ccode', + idx => 'ccode', label => 'Collections', - tags => [ qw / 099t 955h / ], + tags => [qw / 099t 955h /], } - ]; + ]; - unless ( Koha::Libraries->search->count == 1 ) + unless ( Koha::Libraries->search->count == 1 ) { + my $DisplayLibraryFacets = C4::Context->preference('DisplayLibraryFacets'); + if ( $DisplayLibraryFacets eq 'both' + || $DisplayLibraryFacets eq 'holding' ) { - my $DisplayLibraryFacets = C4::Context->preference('DisplayLibraryFacets'); - if ( $DisplayLibraryFacets eq 'both' - || $DisplayLibraryFacets eq 'holding' ) - { - push( - @$facets, - { - idx => 'holdingbranch', - label => 'Holding libraries', - tags => [qw / 995c /], - } - ); - } + push( + @$facets, + { + idx => 'holdingbranch', + label => 'Holding libraries', + tags => [qw / 995c /], + } + ); + } - if ( $DisplayLibraryFacets eq 'both' - || $DisplayLibraryFacets eq 'home' ) - { + if ( $DisplayLibraryFacets eq 'both' + || $DisplayLibraryFacets eq 'home' ) + { push( @$facets, { @@ -379,17 +386,17 @@ sub getFacets { tags => [qw / 995b /], } ); - } } - } - else { + } + } else { $facets = [ { idx => 'su-to', label => 'Topics', - tags => [ qw/ 650a / ], + tags => [qw/ 650a /], sep => '--', }, + # { # idx => 'su-na', # label => 'People and Organizations', @@ -399,64 +406,63 @@ sub getFacets { { idx => 'su-geo', label => 'Places', - tags => [ qw/ 651a / ], + tags => [qw/ 651a /], sep => '--', }, { idx => 'su-ut', label => 'Titles', - tags => [ qw/ 630a / ], + tags => [qw/ 630a /], sep => '--', }, { idx => 'au', label => 'Authors', - tags => [ qw/ 100a 110a 700a / ], + tags => [qw/ 100a 110a 700a /], sep => ', ', }, { idx => 'se', label => 'Series', - tags => [ qw/ 440a 490a / ], + tags => [qw/ 440a 490a /], sep => ', ', }, { idx => 'itype', label => 'Item types', - tags => [ qw/ 952y 942c / ], + tags => [qw/ 952y 942c /], sep => ', ', }, { - idx => 'location', + idx => 'location', label => 'Location', - tags => [ qw / 952c / ], + tags => [qw / 952c /], }, { - idx => 'ccode', + idx => 'ccode', label => 'Collections', - tags => [ qw / 9528 / ], + tags => [qw / 9528 /], } - ]; + ]; - unless ( Koha::Libraries->search->count == 1 ) + unless ( Koha::Libraries->search->count == 1 ) { + my $DisplayLibraryFacets = C4::Context->preference('DisplayLibraryFacets'); + if ( $DisplayLibraryFacets eq 'both' + || $DisplayLibraryFacets eq 'holding' ) { - my $DisplayLibraryFacets = C4::Context->preference('DisplayLibraryFacets'); - if ( $DisplayLibraryFacets eq 'both' - || $DisplayLibraryFacets eq 'holding' ) - { - push( - @$facets, - { - idx => 'holdingbranch', - label => 'Holding libraries', - tags => [qw / 952b /], - } - ); - } + push( + @$facets, + { + idx => 'holdingbranch', + label => 'Holding libraries', + tags => [qw / 952b /], + } + ); + } - if ( $DisplayLibraryFacets eq 'both' - || $DisplayLibraryFacets eq 'home' ) - { + if ( $DisplayLibraryFacets eq 'both' + || $DisplayLibraryFacets eq 'home' ) + { push( @$facets, { @@ -465,8 +471,8 @@ sub getFacets { tags => [qw / 952a /], } ); - } } + } } return $facets; } @@ -484,20 +490,18 @@ C<$opac> If set to a true value, displays OPAC descriptions rather than normal o =cut sub GetAuthorisedValues { - my $category = shift // ''; # optional parameter - my $opac = shift ? 1 : 0; # normalise to be safe + my $category = shift // ''; # optional parameter + my $opac = shift ? 1 : 0; # normalise to be safe # Is this cached already? - my $branch_limit = - C4::Context->userenv ? C4::Context->userenv->{"branch"} : ""; - my $cache_key = - "AuthorisedValues-$category-$opac-$branch_limit"; - my $cache = Koha::Caches->get_instance(); - my $result = $cache->get_from_cache($cache_key); + my $branch_limit = C4::Context->userenv ? C4::Context->userenv->{"branch"} : ""; + my $cache_key = "AuthorisedValues-$category-$opac-$branch_limit"; + my $cache = Koha::Caches->get_instance(); + my $result = $cache->get_from_cache($cache_key); return $result if $result; my @results; - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $query = qq{ SELECT DISTINCT av.* FROM authorised_values av @@ -507,27 +511,30 @@ sub GetAuthorisedValues { } if $branch_limit; my @where_strings; my @where_args; - if($category) { + + if ($category) { push @where_strings, "category = ?"; - push @where_args, $category; + push @where_args, $category; } - if($branch_limit) { + if ($branch_limit) { push @where_strings, "( branchcode = ? OR branchcode IS NULL )"; - push @where_args, $branch_limit; + push @where_args, $branch_limit; } - if(@where_strings > 0) { - $query .= " WHERE " . join(" AND ", @where_strings); + if ( @where_strings > 0 ) { + $query .= " WHERE " . join( " AND ", @where_strings ); } - $query .= ' ORDER BY category, ' . ( - $opac ? 'COALESCE(lib_opac, lib)' - : 'lib, lib_opac' - ); + $query .= ' ORDER BY category, ' + . ( + $opac + ? 'COALESCE(lib_opac, lib)' + : 'lib, lib_opac' + ); my $sth = $dbh->prepare($query); - $sth->execute( @where_args ); - while (my $data=$sth->fetchrow_hashref) { - if ($opac && $data->{lib_opac}) { + $sth->execute(@where_args); + while ( my $data = $sth->fetchrow_hashref ) { + if ( $opac && $data->{lib_opac} ) { $data->{lib} = $data->{lib_opac}; } push @results, $data; @@ -569,9 +576,9 @@ MARC field, replacing any blanks with '#'. =cut sub display_marc_indicators { - my $field = shift; + my $field = shift; my $indicators = ''; - if ($field && $field->tag() >= 10) { + if ( $field && $field->tag() >= 10 ) { $indicators = $field->indicator(1) . $field->indicator(2); $indicators =~ s/ /#/g; } @@ -579,27 +586,26 @@ sub display_marc_indicators { } sub GetNormalizedUPC { - my ($marcrecord,$marcflavour) = @_; + my ( $marcrecord, $marcflavour ) = @_; $marcflavour ||= C4::Context->preference('marcflavour'); return unless $marcrecord; - if ($marcflavour eq 'UNIMARC') { + if ( $marcflavour eq 'UNIMARC' ) { my @fields = $marcrecord->field('072'); foreach my $field (@fields) { - my $upc = _normalize_match_point($field->subfield('a')); + my $upc = _normalize_match_point( $field->subfield('a') ); if ($upc) { return $upc; } } - } - else { # assume marc21 if not unimarc + } else { # assume marc21 if not unimarc my @fields = $marcrecord->field('024'); foreach my $field (@fields) { my $indicator = $field->indicator(1); - my $upc = _normalize_match_point($field->subfield('a')); - if ($upc && $indicator eq '1' ) { + my $upc = _normalize_match_point( $field->subfield('a') ); + if ( $upc && $indicator eq '1' ) { return $upc; } } @@ -609,17 +615,18 @@ sub GetNormalizedUPC { # Normalizes and returns the first valid ISBN found in the record # ISBN13 are converted into ISBN10. This is required to get some book cover images. sub GetNormalizedISBN { - my ($isbn,$marcrecord,$marcflavour) = @_; + my ( $isbn, $marcrecord, $marcflavour ) = @_; if ($isbn) { + # Koha attempts to store multiple ISBNs in biblioitems.isbn, separated by " | " # anything after " | " should be removed, along with the delimiter - ($isbn) = split(/\|/, $isbn ); + ($isbn) = split( /\|/, $isbn ); return _isbn_cleanup($isbn); } return unless $marcrecord; - if ($marcflavour eq 'UNIMARC') { + if ( $marcflavour eq 'UNIMARC' ) { my @fields = $marcrecord->field('010'); foreach my $field (@fields) { my $isbn = $field->subfield('a'); @@ -627,8 +634,7 @@ sub GetNormalizedISBN { return _isbn_cleanup($isbn); } } - } - else { # assume marc21 if not unimarc + } else { # assume marc21 if not unimarc my @fields = $marcrecord->field('020'); foreach my $field (@fields) { $isbn = $field->subfield('a'); @@ -640,25 +646,24 @@ sub GetNormalizedISBN { } sub GetNormalizedEAN { - my ($marcrecord,$marcflavour) = @_; + my ( $marcrecord, $marcflavour ) = @_; return unless $marcrecord; - if ($marcflavour eq 'UNIMARC') { + if ( $marcflavour eq 'UNIMARC' ) { my @fields = $marcrecord->field('073'); foreach my $field (@fields) { - my $ean = _normalize_match_point($field->subfield('a')); - if ( $ean ) { + my $ean = _normalize_match_point( $field->subfield('a') ); + if ($ean) { return $ean; } } - } - else { # assume marc21 if not unimarc + } else { # assume marc21 if not unimarc my @fields = $marcrecord->field('024'); foreach my $field (@fields) { my $indicator = $field->indicator(1); - my $ean = _normalize_match_point($field->subfield('a')); - if ( $ean && $indicator eq '3' ) { + my $ean = _normalize_match_point( $field->subfield('a') ); + if ( $ean && $indicator eq '3' ) { return $ean; } } @@ -666,28 +671,29 @@ sub GetNormalizedEAN { } sub GetNormalizedOCLCNumber { - my ($marcrecord,$marcflavour) = @_; + my ( $marcrecord, $marcflavour ) = @_; return unless $marcrecord; $marcflavour ||= C4::Context->preference('marcflavour'); - if ($marcflavour ne 'UNIMARC' ) { + if ( $marcflavour ne 'UNIMARC' ) { my @fields = $marcrecord->field('035'); foreach my $field (@fields) { my $oclc = $field->subfield('a'); - if ($oclc && $oclc =~ /OCoLC/) { + if ( $oclc && $oclc =~ /OCoLC/ ) { $oclc =~ s/\(OCoLC\)//; return $oclc; } } } else { + # TODO for UNIMARC } } sub _normalize_match_point { my $match_point = shift; - (my $normalized_match_point) = $match_point =~ /([\d-]*[X]*)/; + ( my $normalized_match_point ) = $match_point =~ /([\d-]*[X]*)/; $normalized_match_point =~ s/-//g; return $normalized_match_point; @@ -726,9 +732,9 @@ sub _isbn_cleanup { sub NormalizeISBN { my ($params) = @_; - my $string = $params->{isbn}; - my $strip_hyphens = $params->{strip_hyphens}; - my $format = $params->{format} || q{}; + my $string = $params->{isbn}; + my $strip_hyphens = $params->{strip_hyphens}; + my $format = $params->{format} || q{}; my $return_invalid = $params->{return_invalid}; return unless $string; @@ -738,9 +744,8 @@ sub NormalizeISBN { if ( $isbn && $isbn->is_valid() ) { if ( $format eq 'ISBN-10' ) { - $isbn = $isbn->as_isbn10(); - } - elsif ( $format eq 'ISBN-13' ) { + $isbn = $isbn->as_isbn10(); + } elsif ( $format eq 'ISBN-13' ) { $isbn = $isbn->as_isbn13(); } return unless $isbn; @@ -752,7 +757,7 @@ sub NormalizeISBN { } return $string; - } elsif ( $return_invalid ) { + } elsif ($return_invalid) { return $string; } @@ -778,11 +783,11 @@ sub GetVariationsOfISBN { my @isbns; - push( @isbns, NormalizeISBN({ isbn => $isbn, return_invalid => 1 }) ); - push( @isbns, NormalizeISBN({ isbn => $isbn, format => 'ISBN-10' }) ); - push( @isbns, NormalizeISBN({ isbn => $isbn, format => 'ISBN-13' }) ); - push( @isbns, NormalizeISBN({ isbn => $isbn, format => 'ISBN-10', strip_hyphens => 1 }) ); - push( @isbns, NormalizeISBN({ isbn => $isbn, format => 'ISBN-13', strip_hyphens => 1 }) ); + push( @isbns, NormalizeISBN( { isbn => $isbn, return_invalid => 1 } ) ); + push( @isbns, NormalizeISBN( { isbn => $isbn, format => 'ISBN-10' } ) ); + push( @isbns, NormalizeISBN( { isbn => $isbn, format => 'ISBN-13' } ) ); + push( @isbns, NormalizeISBN( { isbn => $isbn, format => 'ISBN-10', strip_hyphens => 1 } ) ); + push( @isbns, NormalizeISBN( { isbn => $isbn, format => 'ISBN-13', strip_hyphens => 1 } ) ); # Strip out any "empty" strings from the array @isbns = grep { defined($_) && $_ =~ /\S/ } @isbns; @@ -806,7 +811,7 @@ sub GetVariationsOfISBN { sub GetVariationsOfISBNs { my (@isbns) = @_; - @isbns = map { GetVariationsOfISBN( $_ ) } @isbns; + @isbns = map { GetVariationsOfISBN($_) } @isbns; return wantarray ? @isbns : join( " | ", @isbns ); } @@ -829,17 +834,16 @@ sub GetVariationsOfISBNs { sub NormalizeISSN { my ($params) = @_; - my $string = $params->{issn}; - my $strip_hyphen = $params->{strip_hyphen}; + my $string = $params->{issn}; + my $strip_hyphen = $params->{strip_hyphen}; my $issn = Business::ISSN->new($string); - if ( $issn && $issn->is_valid ){ + if ( $issn && $issn->is_valid ) { if ($strip_hyphen) { $string = $issn->_issn; - } - else { + } else { $string = $issn->as_string; } return $string; @@ -860,16 +864,16 @@ sub NormalizeISSN { =cut sub GetVariationsOfISSN { - my ( $issn ) = @_; + my ($issn) = @_; return unless $issn; my @issns; - my $str = NormalizeISSN({ issn => $issn }); - if( $str ) { + my $str = NormalizeISSN( { issn => $issn } ); + if ($str) { push @issns, $str; - push @issns, NormalizeISSN({ issn => $issn, strip_hyphen => 1 }); - } else { + push @issns, NormalizeISSN( { issn => $issn, strip_hyphen => 1 } ); + } else { push @issns, $issn; } @@ -894,7 +898,7 @@ sub GetVariationsOfISSN { sub GetVariationsOfISSNs { my (@issns) = @_; - @issns = map { GetVariationsOfISSN( $_ ) } @issns; + @issns = map { GetVariationsOfISSN($_) } @issns; return wantarray ? @issns : join( " | ", @issns ); } diff --git a/C4/Labels/Batch.pm b/C4/Labels/Batch.pm index 66bcf978d2..e6d603a320 100644 --- a/C4/Labels/Batch.pm +++ b/C4/Labels/Batch.pm @@ -7,7 +7,6 @@ use base qw(C4::Creators::Batch); use autouse 'Data::Dumper' => qw(Dumper); - __PACKAGE__ =~ m/^C4::(.+)::.+$/; my $me = $1; @@ -30,14 +29,13 @@ sub retrieve { } sub delete { - if (ref($_[0])) { - my $self = shift; # check to see if this is a method call + if ( ref( $_[0] ) ) { + my $self = shift; # check to see if this is a method call push @_, "creator", $me; return $self->SUPER::delete(@_); - } - else { + } else { push @_, "creator", $me; - return __PACKAGE__->SUPER::delete(@_); # XXX: is this too hackish? + return __PACKAGE__->SUPER::delete(@_); # XXX: is this too hackish? } } diff --git a/C4/Labels/Label.pm b/C4/Labels/Label.pm index 702f566169..dc77111cf2 100644 --- a/C4/Labels/Label.pm +++ b/C4/Labels/Label.pm @@ -3,7 +3,7 @@ package C4::Labels::Label; use strict; use warnings; -use Text::Wrap qw( wrap ); +use Text::Wrap qw( wrap ); use Algorithm::CheckDigits qw( CheckDigits ); use Text::CSV_XS; use Text::Bidi qw( log2vis ); @@ -20,8 +20,8 @@ use C4::ClassSplitRoutine::Generic; use C4::ClassSplitRoutine::RegEx; sub _check_params { - my $given_params = {}; - my $exit_code = 0; + my $given_params = {}; + my $exit_code = 0; my @valid_label_params = ( 'batch_id', 'item_number', @@ -45,18 +45,17 @@ sub _check_params { 'text_wrap_cols', 'barcode', ); - if (scalar(@_) >1) { + if ( scalar(@_) > 1 ) { $given_params = {@_}; - foreach my $key (keys %{$given_params}) { - if (!(grep m/$key/, @valid_label_params)) { - warn sprintf('Unrecognized parameter type of "%s".', $key); + foreach my $key ( keys %{$given_params} ) { + if ( !( grep m/$key/, @valid_label_params ) ) { + warn sprintf( 'Unrecognized parameter type of "%s".', $key ); $exit_code = 1; } } - } - else { - if (!(grep m/$_/, @valid_label_params)) { - warn sprintf('Unrecognized parameter type of "%s".', $_); + } else { + if ( !( grep m/$_/, @valid_label_params ) ) { + warn sprintf( 'Unrecognized parameter type of "%s".', $_ ); $exit_code = 1; } } @@ -65,8 +64,10 @@ sub _check_params { sub _guide_box { my ( $llx, $lly, $width, $height ) = @_; - return unless ( defined $llx and defined $lly and - defined $width and defined $height ); + return unless ( defined $llx + and defined $lly + and defined $width + and defined $height ); my $obj_stream = "q\n"; # save the graphic state $obj_stream .= "0.5 w\n"; # border line width $obj_stream .= "1.0 0.0 0.0 RG\n"; # border color red @@ -78,57 +79,70 @@ sub _guide_box { } sub _get_label_item { - my $item_number = shift; + my $item_number = shift; my $barcode_only = shift || 0; - my $dbh = C4::Context->dbh; -# FIXME This makes for a very bulky data structure; data from tables w/duplicate col names also gets overwritten. -# Something like this, perhaps, but this also causes problems because we need more fields sometimes. -# SELECT i.barcode, i.itemcallnumber, i.itype, bi.isbn, bi.issn, b.title, b.author - my $sth = $dbh->prepare("SELECT bi.*, i.*, b.*,br.* FROM items AS i, biblioitems AS bi ,biblio AS b, branches AS br WHERE itemnumber=? AND i.biblioitemnumber=bi.biblioitemnumber AND bi.biblionumber=b.biblionumber AND i.homebranch=br.branchcode;"); + my $dbh = C4::Context->dbh; + + # FIXME This makes for a very bulky data structure; data from tables w/duplicate col names also gets overwritten. + # Something like this, perhaps, but this also causes problems because we need more fields sometimes. + # SELECT i.barcode, i.itemcallnumber, i.itype, bi.isbn, bi.issn, b.title, b.author + my $sth = $dbh->prepare( + "SELECT bi.*, i.*, b.*,br.* FROM items AS i, biblioitems AS bi ,biblio AS b, branches AS br WHERE itemnumber=? AND i.biblioitemnumber=bi.biblioitemnumber AND bi.biblionumber=b.biblionumber AND i.homebranch=br.branchcode;" + ); $sth->execute($item_number); - if ($sth->err) { - warn sprintf('Database returned the following error: %s', $sth->errstr); + if ( $sth->err ) { + warn sprintf( 'Database returned the following error: %s', $sth->errstr ); } my $data = $sth->fetchrow_hashref; + # Replaced item's itemtype with the more user-friendly description... my $sth1 = $dbh->prepare("SELECT itemtype,description FROM itemtypes WHERE itemtype = ?"); - $sth1->execute($data->{'itemtype'}); - if ($sth1->err) { - warn sprintf('Database returned the following error: %s', $sth1->errstr); + $sth1->execute( $data->{'itemtype'} ); + if ( $sth1->err ) { + warn sprintf( 'Database returned the following error: %s', $sth1->errstr ); } my $data1 = $sth1->fetchrow_hashref; $data->{'itemtype'} = $data1->{'description'}; - $data->{'itype'} = $data1->{'description'}; + $data->{'itype'} = $data1->{'description'}; + # add *_description fields - if ($data->{'homebranch'} || $data->{'holdingbranch'}){ + if ( $data->{'homebranch'} || $data->{'holdingbranch'} ) { require Koha::Libraries; + # FIXME Is this used?? - $data->{'homebranch_description'} = Koha::Libraries->find($data->{'homebranch'})->branchname if $data->{'homebranch'}; - $data->{'holdingbranch_description'} = Koha::Libraries->find($data->{'holdingbranch'})->branchname if $data->{'holdingbranch'}; + $data->{'homebranch_description'} = Koha::Libraries->find( $data->{'homebranch'} )->branchname + if $data->{'homebranch'}; + $data->{'holdingbranch_description'} = Koha::Libraries->find( $data->{'holdingbranch'} )->branchname + if $data->{'holdingbranch'}; } - $data->{'ccode_description'} = C4::Biblio::GetAuthorisedValueDesc('','', $data->{'ccode'} ,'','','CCODE', 1) if $data->{'ccode'}; - $data->{'location_description'} = C4::Biblio::GetAuthorisedValueDesc('','', $data->{'location'} ,'','','LOC', 1) if $data->{'location'}; - $data->{'permanent_location_description'} = C4::Biblio::GetAuthorisedValueDesc('','', $data->{'permanent_location'} ,'','','LOC', 1) if $data->{'permanent_location'}; + $data->{'ccode_description'} = C4::Biblio::GetAuthorisedValueDesc( '', '', $data->{'ccode'}, '', '', 'CCODE', 1 ) + if $data->{'ccode'}; + $data->{'location_description'} = + C4::Biblio::GetAuthorisedValueDesc( '', '', $data->{'location'}, '', '', 'LOC', 1 ) + if $data->{'location'}; + $data->{'permanent_location_description'} = + C4::Biblio::GetAuthorisedValueDesc( '', '', $data->{'permanent_location'}, '', '', 'LOC', 1 ) + if $data->{'permanent_location'}; $barcode_only ? return $data->{'barcode'} : return $data; } sub _get_text_fields { my $format_string = shift; - my $csv = Text::CSV_XS->new( { allow_whitespace => 1, formula => "empty" } ); - my $status = $csv->parse($format_string); - my @sorted_fields = map {{ 'code' => $_, desc => $_ }} - map { $_ && $_ eq 'callnumber' ? 'itemcallnumber' : $_ } # see bug 5653 - $csv->fields(); + my $csv = Text::CSV_XS->new( { allow_whitespace => 1, formula => "empty" } ); + my $status = $csv->parse($format_string); + my @sorted_fields = map { { 'code' => $_, desc => $_ } } + map { $_ && $_ eq 'callnumber' ? 'itemcallnumber' : $_ } # see bug 5653 + $csv->fields(); my $error = $csv->error_input(); - warn sprintf('Text field sort failed with this error: %s', $error) if $error; + warn sprintf( 'Text field sort failed with this error: %s', $error ) if $error; return \@sorted_fields; } sub _get_barcode_data { my ( $f, $item, $record ) = @_; - my $kohatables = _desc_koha_tables(); - my $datastring = ''; + my $kohatables = _desc_koha_tables(); + my $datastring = ''; my $match_kohatable = join( '|', ( @@ -138,60 +152,56 @@ sub _get_barcode_data { @{ $kohatables->{'branches'} } ) ); - FIELD_LIST: +FIELD_LIST: while ($f) { my $err = ''; $f =~ s/^\s?//; if ( $f =~ /^'(.*)'.*/ ) { + # single quotes indicate a static text string. $datastring .= $1; $f = $'; next FIELD_LIST; - } - elsif ( $f =~ /^($match_kohatable).*/ ) { + } elsif ( $f =~ /^($match_kohatable).*/ ) { my @fields = split ' ', $f; my @data; - for my $field ( @fields ) { - if ($item->{$field}) { + for my $field (@fields) { + if ( $item->{$field} ) { push @data, $item->{$field}; } } $datastring .= join ' ', @data; $f = $'; next FIELD_LIST; - } - elsif ( $f =~ /^([0-9a-z]{3})(\w)(\W?).*?/ ) { - my ($field,$subf,$ws) = ($1,$2,$3); - my ($itemtag, $itemsubfieldcode) = &GetMarcFromKohaField( "items.itemnumber" ); + } elsif ( $f =~ /^([0-9a-z]{3})(\w)(\W?).*?/ ) { + my ( $field, $subf, $ws ) = ( $1, $2, $3 ); + my ( $itemtag, $itemsubfieldcode ) = &GetMarcFromKohaField("items.itemnumber"); my @marcfield = $record->field($field); - if(@marcfield) { - if($field eq $itemtag) { # item-level data, we need to get the right item. - ITEM_FIELDS: + if (@marcfield) { + if ( $field eq $itemtag ) { # item-level data, we need to get the right item. + ITEM_FIELDS: foreach my $itemfield (@marcfield) { if ( $itemfield->subfield($itemsubfieldcode) eq $item->{'itemnumber'} ) { - if ($itemfield->subfield($subf)) { + if ( $itemfield->subfield($subf) ) { $datastring .= $itemfield->subfield($subf) . $ws; - } - else { - warn sprintf("The '%s' field contains no data.", $f); + } else { + warn sprintf( "The '%s' field contains no data.", $f ); } last ITEM_FIELDS; } } - } else { # bib-level data, we'll take the first matching tag/subfield. - if ($marcfield[0]->subfield($subf)) { + } else { # bib-level data, we'll take the first matching tag/subfield. + if ( $marcfield[0]->subfield($subf) ) { $datastring .= $marcfield[0]->subfield($subf) . $ws; - } - else { - warn sprintf("The '%s' field contains no data.", $f); + } else { + warn sprintf( "The '%s' field contains no data.", $f ); } } } $f = $'; next FIELD_LIST; - } - else { - warn sprintf('Failed to parse label format string: %s', $f); + } else { + warn sprintf( 'Failed to parse label format string: %s', $f ); last FIELD_LIST; # Failed to match } } @@ -199,16 +209,16 @@ sub _get_barcode_data { } sub _desc_koha_tables { - my $dbh = C4::Context->dbh(); - my $kohatables; - for my $table ( 'biblio','biblioitems','items','branches' ) { - my $sth = $dbh->column_info(undef,undef,$table,'%'); - while (my $info = $sth->fetchrow_hashref()){ - push @{$kohatables->{$table}} , $info->{'COLUMN_NAME'} ; - } - $sth->finish; - } - return $kohatables; + my $dbh = C4::Context->dbh(); + my $kohatables; + for my $table ( 'biblio', 'biblioitems', 'items', 'branches' ) { + my $sth = $dbh->column_info( undef, undef, $table, '%' ); + while ( my $info = $sth->fetchrow_hashref() ) { + push @{ $kohatables->{$table} }, $info->{'COLUMN_NAME'}; + } + $sth->finish; + } + return $kohatables; } ### This series of functions calculates the position of text and barcode on individual labels @@ -217,9 +227,10 @@ sub _desc_koha_tables { ### NOTE: Each function must be passed seven parameters and return seven even if some are 0 or undef sub _BIB { - my $self = shift; - my $line_spacer = ($self->{'font_size'} * 1); # number of pixels between text rows (This is actually leading: baseline to baseline minus font size. Recommended starting point is 20% of font size.). - my $text_lly = ($self->{'lly'} + ($self->{'height'} - $self->{'top_text_margin'})); + my $self = shift; + my $line_spacer = ( $self->{'font_size'} * 1 ) + ; # number of pixels between text rows (This is actually leading: baseline to baseline minus font size. Recommended starting point is 20% of font size.). + my $text_lly = ( $self->{'lly'} + ( $self->{'height'} - $self->{'top_text_margin'} ) ); return $self->{'llx'}, $text_lly, $line_spacer, 0, 0, 0, 0; } @@ -284,7 +295,7 @@ sub _BARBIB { } sub new { - my ($invocant, %params) = @_; + my ( $invocant, %params ) = @_; my $type = ref($invocant) || $invocant; my $self = { batch_id => $params{'batch_id'}, @@ -310,10 +321,10 @@ sub new { barcode => $params{'barcode'}, }; - if ($self->{'guidebox'}) { - $self->{'guidebox'} = _guide_box($self->{'llx'}, $self->{'lly'}, $self->{'width'}, $self->{'height'}); + if ( $self->{'guidebox'} ) { + $self->{'guidebox'} = _guide_box( $self->{'llx'}, $self->{'lly'}, $self->{'width'}, $self->{'height'} ); } - bless ($self, $type); + bless( $self, $type ); return $self; } @@ -324,40 +335,42 @@ sub get_label_type { sub get_attr { my $self = shift; - if (_check_params(@_) eq 1) { + if ( _check_params(@_) eq 1 ) { return -1; } my ($attr) = @_; - if (exists($self->{$attr})) { + if ( exists( $self->{$attr} ) ) { return $self->{$attr}; - } - else { + } else { return -1; } return; } sub create_label { - my $self = shift; + my $self = shift; my $label_text = ''; - my ($text_llx, $text_lly, $line_spacer, $barcode_llx, $barcode_lly, $barcode_width, $barcode_y_scale_factor); + my ( $text_llx, $text_lly, $line_spacer, $barcode_llx, $barcode_lly, $barcode_width, $barcode_y_scale_factor ); { - my $sub = \&{'_' . $self->{printing_type}}; - ($text_llx, $text_lly, $line_spacer, $barcode_llx, $barcode_lly, $barcode_width, $barcode_y_scale_factor) = $sub->($self); # an obfuscated call to the correct printing type sub + my $sub = \&{ '_' . $self->{printing_type} }; + ( $text_llx, $text_lly, $line_spacer, $barcode_llx, $barcode_lly, $barcode_width, $barcode_y_scale_factor ) = + $sub->($self); # an obfuscated call to the correct printing type sub } - if ($self->{'printing_type'} =~ /BIB/) { - $label_text = draw_label_text( $self, - llx => $text_llx, - lly => $text_lly, - line_spacer => $line_spacer, - ); + if ( $self->{'printing_type'} =~ /BIB/ ) { + $label_text = draw_label_text( + $self, + llx => $text_llx, + lly => $text_lly, + line_spacer => $line_spacer, + ); } - if ($self->{'printing_type'} =~ /BAR/) { - barcode( $self, - llx => $barcode_llx, - lly => $barcode_lly, - width => $barcode_width, - y_scale_factor => $barcode_y_scale_factor, + if ( $self->{'printing_type'} =~ /BAR/ ) { + barcode( + $self, + llx => $barcode_llx, + lly => $barcode_lly, + width => $barcode_width, + y_scale_factor => $barcode_y_scale_factor, ); } return $label_text if $label_text; @@ -365,43 +378,44 @@ sub create_label { } sub draw_label_text { - my ($self, %params) = @_; - my @label_text = (); - my $text_llx = 0; - my $text_lly = $params{'lly'}; - my $font = $self->{'font'}; - my $item = _get_label_item($self->{'item_number'}); - my $label_fields = _get_text_fields($self->{'format_string'}); - my $biblio = Koha::Biblios->find($item->{biblionumber}); - my $record = $biblio->metadata->record; + my ( $self, %params ) = @_; + my @label_text = (); + my $text_llx = 0; + my $text_lly = $params{'lly'}; + my $font = $self->{'font'}; + my $item = _get_label_item( $self->{'item_number'} ); + my $label_fields = _get_text_fields( $self->{'format_string'} ); + my $biblio = Koha::Biblios->find( $item->{biblionumber} ); + my $record = $biblio->metadata->record; + # FIXME - returns all items, so you can't get data from an embedded holdings field. # TODO - add a GetMarcBiblio1item(bibnum,itemnum) or a GetMarcItem(itemnum). - my $cn_source = ($item->{'cn_source'} ? $item->{'cn_source'} : C4::Context->preference('DefaultClassificationSource')); - my $class_source = Koha::ClassSources->find( $cn_source ); + my $cn_source = + ( $item->{'cn_source'} ? $item->{'cn_source'} : C4::Context->preference('DefaultClassificationSource') ); + my $class_source = Koha::ClassSources->find($cn_source); my ( $split_routine, $regexs ); if ($class_source) { my $class_split_rule = Koha::ClassSplitRules->find( $class_source->class_split_rule ); $split_routine = $class_split_rule->split_routine; $regexs = $class_split_rule->regexs; + } else { + $split_routine = $cn_source; } - else { $split_routine = $cn_source } - LABEL_FIELDS: # process data for requested fields on current label +LABEL_FIELDS: # process data for requested fields on current label for my $field (@$label_fields) { - if ($field->{'code'} eq 'itemtype') { + if ( $field->{'code'} eq 'itemtype' ) { $field->{'data'} = C4::Context->preference('item-level_itypes') ? $item->{'itype'} : $item->{'itemtype'}; + } else { + $field->{'data'} = _get_barcode_data( $field->{'code'}, $item, $record ); } - else { - $field->{'data'} = _get_barcode_data($field->{'code'},$item,$record); - } + # Find appropriate font it oblique title selected, except main font is oblique if ( ( $field->{'code'} eq 'title' ) and ( $self->{'oblique_title'} == 1 ) ) { if ( $font =~ /^TB$/ ) { $font .= 'I'; - } - elsif ( $font =~ /^TR$/ ) { + } elsif ( $font =~ /^TR$/ ) { $font = 'TI'; - } - elsif ( $font !~ /^T/ and $font !~ /O$/ ) { + } elsif ( $font !~ /^T/ and $font !~ /O$/ ) { $font .= 'O'; } } @@ -411,74 +425,82 @@ sub draw_label_text { $field_data =~ s/\r//g; } my @label_lines; + # Fields which hold call number data FIXME: ( 060? 090? 092? 099? ) my @callnumber_list = qw(itemcallnumber 050a 050b 082a 952o 995k); - if ((grep {$field->{'code'} =~ m/$_/} @callnumber_list) and ($self->{'printing_type'} ne 'BAR') and ($self->{'callnum_split'})) { # If the field contains the call number, we do some sp - if ($split_routine eq 'LCC' || $split_routine eq 'nlm') { # NLM and LCC should be split the same way + if ( ( grep { $field->{'code'} =~ m/$_/ } @callnumber_list ) + and ( $self->{'printing_type'} ne 'BAR' ) + and ( $self->{'callnum_split'} ) ) + { # If the field contains the call number, we do some sp + if ( $split_routine eq 'LCC' || $split_routine eq 'nlm' ) { # NLM and LCC should be split the same way @label_lines = C4::ClassSplitRoutine::LCC::split_callnumber($field_data); - @label_lines = C4::ClassSplitRoutine::Generic::split_callnumber($field_data) unless @label_lines; # If it was not a true lccn, try it as a custom call number - push (@label_lines, $field_data) unless @label_lines; # If it was not that, send it on unsplit - } elsif ($split_routine eq 'Dewey') { + @label_lines = C4::ClassSplitRoutine::Generic::split_callnumber($field_data) + unless @label_lines; # If it was not a true lccn, try it as a custom call number + push( @label_lines, $field_data ) unless @label_lines; # If it was not that, send it on unsplit + } elsif ( $split_routine eq 'Dewey' ) { @label_lines = C4::ClassSplitRoutine::Dewey::split_callnumber($field_data); @label_lines = C4::ClassSplitRoutine::Generic::split_callnumber($field_data) unless @label_lines; - push (@label_lines, $field_data) unless @label_lines; - } elsif ($split_routine eq 'RegEx' ) { - @label_lines = C4::ClassSplitRoutine::RegEx::split_callnumber($field_data, $regexs); + push( @label_lines, $field_data ) unless @label_lines; + } elsif ( $split_routine eq 'RegEx' ) { + @label_lines = C4::ClassSplitRoutine::RegEx::split_callnumber( $field_data, $regexs ); @label_lines = C4::ClassSplitRoutine::Generic::split_callnumber($field_data) unless @label_lines; - push (@label_lines, $field_data) unless @label_lines; + push( @label_lines, $field_data ) unless @label_lines; } else { - warn sprintf('Call number splitting failed for: %s. Please add this call number to bug #2500 at bugs.koha-community.org', $field_data); + warn sprintf( + 'Call number splitting failed for: %s. Please add this call number to bug #2500 at bugs.koha-community.org', + $field_data + ); push @label_lines, $field_data; } - } - else { + } else { if ($field_data) { - $field_data =~ s/\/$//g; # Here we will strip out all trailing '/' in fields other than the call number... - # Escaping the parens was causing odd output, see bug 13124 - # $field_data =~ s/\(/\\\(/g; # Escape '(' and ')' for the pdf object stream... - # $field_data =~ s/\)/\\\)/g; + $field_data =~ + s/\/$//g; # Here we will strip out all trailing '/' in fields other than the call number... + # Escaping the parens was causing odd output, see bug 13124 + # $field_data =~ s/\(/\\\(/g; # Escape '(' and ')' for the pdf object stream... + # $field_data =~ s/\)/\\\)/g; } - eval{$Text::Wrap::columns = $self->{'text_wrap_cols'};}; - my @line = split(/\n/ ,wrap('', '', $field_data)); + eval { $Text::Wrap::columns = $self->{'text_wrap_cols'}; }; + my @line = split( /\n/, wrap( '', '', $field_data ) ); + # If this is a title field, limit to two lines; all others limit to one... FIXME: this is rather arbitrary - if ($field->{'code'} eq 'title' && scalar(@line) >= 2) { - while (scalar(@line) > 2) { + if ( $field->{'code'} eq 'title' && scalar(@line) >= 2 ) { + while ( scalar(@line) > 2 ) { pop @line; } } else { - while (scalar(@line) > 1) { + while ( scalar(@line) > 1 ) { pop @line; } } - push(@label_lines, @line); + push( @label_lines, @line ); } - LABEL_LINES: # generate lines of label text for current field + LABEL_LINES: # generate lines of label text for current field foreach my $line (@label_lines) { next LABEL_LINES if $line eq ''; - $line = log2vis( $line ); - my $string_width = C4::Creators::PDF->StrWidth($line, $font, $self->{'font_size'}); - if ($self->{'justify'} eq 'R') { - $text_llx = $params{'llx'} + $self->{'width'} - ($self->{'left_text_margin'} + $string_width); + $line = log2vis($line); + my $string_width = C4::Creators::PDF->StrWidth( $line, $font, $self->{'font_size'} ); + if ( $self->{'justify'} eq 'R' ) { + $text_llx = $params{'llx'} + $self->{'width'} - ( $self->{'left_text_margin'} + $string_width ); + } elsif ( $self->{'justify'} eq 'C' ) { + + # some code to try and center each line on the label based on font size and string point width... + my $whitespace = ( $self->{'width'} - ( $string_width + ( 2 * $self->{'left_text_margin'} ) ) ); + $text_llx = ( ( $whitespace / 2 ) + $params{'llx'} + $self->{'left_text_margin'} ); + } else { + $text_llx = ( $params{'llx'} + $self->{'left_text_margin'} ); } - elsif($self->{'justify'} eq 'C') { - # some code to try and center each line on the label based on font size and string point width... - my $whitespace = ($self->{'width'} - ($string_width + (2 * $self->{'left_text_margin'}))); - $text_llx = (($whitespace / 2) + $params{'llx'} + $self->{'left_text_margin'}); - } - else { - $text_llx = ($params{'llx'} + $self->{'left_text_margin'}); - } - push @label_text, { - text_llx => $text_llx, - text_lly => $text_lly, - font => $font, - font_size => $self->{'font_size'}, - line => $line, - }; + push @label_text, { + text_llx => $text_llx, + text_lly => $text_lly, + font => $font, + font_size => $self->{'font_size'}, + line => $line, + }; $text_lly = $text_lly - $params{'line_spacer'}; } - $font = $self->{'font'}; # reset font for next field - } #foreach field + $font = $self->{'font'}; # reset font for next field + } #foreach field return \@label_text; } @@ -487,112 +509,110 @@ sub draw_guide_box { } sub barcode { - my $self = shift; + my $self = shift; my %params = @_; - $params{'barcode_data'} = ($self->{'barcode'} || _get_label_item($self->{'item_number'}, 1)) if !$params{'barcode_data'}; + $params{'barcode_data'} = ( $self->{'barcode'} || _get_label_item( $self->{'item_number'}, 1 ) ) + if !$params{'barcode_data'}; $params{'barcode_type'} = $self->{'barcode_type'} if !$params{'barcode_type'}; my $x_scale_factor = 1; - my $num_of_bars = length($params{'barcode_data'}); + my $num_of_bars = length( $params{'barcode_data'} ); my $tot_bar_length = 0; - my $bar_length = 0; - my $guard_length = 10; - my $hide_text = 'yes'; - if ($params{'barcode_type'} =~ m/CODE39/) { - $bar_length = '17.5'; - $tot_bar_length = ($bar_length * $num_of_bars) + ($guard_length * 2); - $x_scale_factor = ($params{'width'} / $tot_bar_length); - if ($params{'barcode_type'} eq 'CODE39MOD') { - my $c39 = CheckDigits('code_39'); # get modulo43 checksum - $params{'barcode_data'} = $c39->complete($params{'barcode_data'}); - } - elsif ($params{'barcode_type'} eq 'CODE39MOD10') { - my $c39_10 = CheckDigits('siret'); # get modulo43 checksum - $params{'barcode_data'} = $c39_10->complete($params{'barcode_data'}); + my $bar_length = 0; + my $guard_length = 10; + my $hide_text = 'yes'; + + if ( $params{'barcode_type'} =~ m/CODE39/ ) { + $bar_length = '17.5'; + $tot_bar_length = ( $bar_length * $num_of_bars ) + ( $guard_length * 2 ); + $x_scale_factor = ( $params{'width'} / $tot_bar_length ); + if ( $params{'barcode_type'} eq 'CODE39MOD' ) { + my $c39 = CheckDigits('code_39'); # get modulo43 checksum + $params{'barcode_data'} = $c39->complete( $params{'barcode_data'} ); + } elsif ( $params{'barcode_type'} eq 'CODE39MOD10' ) { + my $c39_10 = CheckDigits('siret'); # get modulo43 checksum + $params{'barcode_data'} = $c39_10->complete( $params{'barcode_data'} ); $hide_text = ''; } eval { PDF::Reuse::Barcode::Code39( - x => $params{'llx'}, - y => $params{'lly'}, - value => "*$params{barcode_data}*", - xSize => $x_scale_factor, - ySize => $params{'y_scale_factor'}, - hide_asterisk => 1, - text => $hide_text, - mode => 'graphic', + x => $params{'llx'}, + y => $params{'lly'}, + value => "*$params{barcode_data}*", + xSize => $x_scale_factor, + ySize => $params{'y_scale_factor'}, + hide_asterisk => 1, + text => $hide_text, + mode => 'graphic', ); }; if ($@) { - warn sprintf('Barcode generation failed for item %s with this error: %s', $self->{'item_number'}, $@); + warn sprintf( 'Barcode generation failed for item %s with this error: %s', $self->{'item_number'}, $@ ); } - } - elsif ($params{'barcode_type'} eq 'COOP2OF5') { - $bar_length = '9.43333333333333'; - $tot_bar_length = ($bar_length * $num_of_bars) + ($guard_length * 2); - $x_scale_factor = ($params{'width'} / $tot_bar_length) * 0.9; + } elsif ( $params{'barcode_type'} eq 'COOP2OF5' ) { + $bar_length = '9.43333333333333'; + $tot_bar_length = ( $bar_length * $num_of_bars ) + ( $guard_length * 2 ); + $x_scale_factor = ( $params{'width'} / $tot_bar_length ) * 0.9; eval { PDF::Reuse::Barcode::COOP2of5( - x => $params{'llx'}, - y => $params{'lly'}, - value => $params{barcode_data}, - xSize => $x_scale_factor, - ySize => $params{'y_scale_factor'}, - mode => 'graphic', + x => $params{'llx'}, + y => $params{'lly'}, + value => $params{barcode_data}, + xSize => $x_scale_factor, + ySize => $params{'y_scale_factor'}, + mode => 'graphic', ); }; if ($@) { - warn sprintf('Barcode generation failed for item %s with this error: %s', $self->{'item_number'}, $@); + warn sprintf( 'Barcode generation failed for item %s with this error: %s', $self->{'item_number'}, $@ ); } - } - elsif ( $params{'barcode_type'} eq 'INDUSTRIAL2OF5' ) { - $bar_length = '13.1333333333333'; - $tot_bar_length = ($bar_length * $num_of_bars) + ($guard_length * 2); - $x_scale_factor = ($params{'width'} / $tot_bar_length) * 0.9; + } elsif ( $params{'barcode_type'} eq 'INDUSTRIAL2OF5' ) { + $bar_length = '13.1333333333333'; + $tot_bar_length = ( $bar_length * $num_of_bars ) + ( $guard_length * 2 ); + $x_scale_factor = ( $params{'width'} / $tot_bar_length ) * 0.9; eval { PDF::Reuse::Barcode::Industrial2of5( - x => $params{'llx'}, - y => $params{'lly'}, - value => $params{barcode_data}, - xSize => $x_scale_factor, - ySize => $params{'y_scale_factor'}, - mode => 'graphic', + x => $params{'llx'}, + y => $params{'lly'}, + value => $params{barcode_data}, + xSize => $x_scale_factor, + ySize => $params{'y_scale_factor'}, + mode => 'graphic', ); }; if ($@) { - warn sprintf('Barcode generation failed for item %s with this error: %s', $self->{'item_number'}, $@); + warn sprintf( 'Barcode generation failed for item %s with this error: %s', $self->{'item_number'}, $@ ); } - } - elsif ($params{'barcode_type'} eq 'EAN13') { - $bar_length = 4; # FIXME - $num_of_bars = 13; - $tot_bar_length = ($bar_length * $num_of_bars) + ($guard_length * 2); - $x_scale_factor = ($params{'width'} / $tot_bar_length) * 0.9; + } elsif ( $params{'barcode_type'} eq 'EAN13' ) { + $bar_length = 4; # FIXME + $num_of_bars = 13; + $tot_bar_length = ( $bar_length * $num_of_bars ) + ( $guard_length * 2 ); + $x_scale_factor = ( $params{'width'} / $tot_bar_length ) * 0.9; eval { PDF::Reuse::Barcode::EAN13( - x => $params{'llx'}, - y => $params{'lly'}, - value => sprintf('%013d',$params{barcode_data}), -# xSize => $x_scale_factor, -# ySize => $params{'y_scale_factor'}, - mode => 'graphic', + x => $params{'llx'}, + y => $params{'lly'}, + value => sprintf( '%013d', $params{barcode_data} ), + + # xSize => $x_scale_factor, + # ySize => $params{'y_scale_factor'}, + mode => 'graphic', ); }; if ($@) { - warn sprintf('Barcode generation failed for item %s with this error: %s', $self->{'item_number'}, $@); + warn sprintf( 'Barcode generation failed for item %s with this error: %s', $self->{'item_number'}, $@ ); } - } - else { - warn "unknown barcode_type: $params{barcode_type}"; + } else { + warn "unknown barcode_type: $params{barcode_type}"; } } sub csv_data { - my $self = shift; - my $label_fields = _get_text_fields($self->{'format_string'}); - my $item = _get_label_item($self->{'item_number'}); - my $biblio = Koha::Biblios->find($item->{biblionumber}); - my $bib_record = $biblio->metadata->record; - my @csv_data = (map { _get_barcode_data($_->{'code'},$item,$bib_record) } @$label_fields); + my $self = shift; + my $label_fields = _get_text_fields( $self->{'format_string'} ); + my $item = _get_label_item( $self->{'item_number'} ); + my $biblio = Koha::Biblios->find( $item->{biblionumber} ); + my $bib_record = $biblio->metadata->record; + my @csv_data = ( map { _get_barcode_data( $_->{'code'}, $item, $bib_record ) } @$label_fields ); return \@csv_data; } diff --git a/C4/Labels/Layout.pm b/C4/Labels/Layout.pm index 5cda8f47b7..5611fd3eec 100644 --- a/C4/Labels/Layout.pm +++ b/C4/Labels/Layout.pm @@ -7,7 +7,6 @@ use base qw(C4::Creators::Layout); use autouse 'Data::Dumper' => qw(Dumper); - __PACKAGE__ =~ m/^C4::(.+)::.+$/; my $me = $1; @@ -30,14 +29,13 @@ sub retrieve { } sub delete { - if (ref($_[0])) { - my $self = shift; # check to see if this is a method call + if ( ref( $_[0] ) ) { + my $self = shift; # check to see if this is a method call push @_, "creator", $me; return $self->SUPER::delete(@_); - } - else { + } else { push @_, "creator", $me; - return __PACKAGE__->SUPER::delete(@_); # XXX: is this too hackish? + return __PACKAGE__->SUPER::delete(@_); # XXX: is this too hackish? } } diff --git a/C4/Labels/Profile.pm b/C4/Labels/Profile.pm index b65af631d7..32f256b704 100644 --- a/C4/Labels/Profile.pm +++ b/C4/Labels/Profile.pm @@ -7,7 +7,6 @@ use base qw(C4::Creators::Profile); use autouse 'Data::Dumper' => qw(Dumper); - __PACKAGE__ =~ m/^C4::(.+)::.+$/; my $me = $1; @@ -30,14 +29,13 @@ sub retrieve { } sub delete { - if (ref($_[0])) { - my $self = shift; # check to see if this is a method call + if ( ref( $_[0] ) ) { + my $self = shift; # check to see if this is a method call push @_, "creator", $me; return $self->SUPER::delete(@_); - } - else { + } else { push @_, "creator", $me; - return __PACKAGE__->SUPER::delete(@_); # XXX: is this too hackish? + return __PACKAGE__->SUPER::delete(@_); # XXX: is this too hackish? } } diff --git a/C4/Labels/Template.pm b/C4/Labels/Template.pm index 890c77d1bf..384d626355 100644 --- a/C4/Labels/Template.pm +++ b/C4/Labels/Template.pm @@ -7,7 +7,6 @@ use base qw(C4::Creators::Template); use autouse 'Data::Dumper' => qw(Dumper); - use constant TEMPLATE_TABLE => 'creator_templates'; __PACKAGE__ =~ m/^C4::(.+)::.+$/; diff --git a/C4/Languages.pm b/C4/Languages.pm index cb8567e909..7b1776874d 100644 --- a/C4/Languages.pm +++ b/C4/Languages.pm @@ -18,7 +18,6 @@ package C4::Languages; # You should have received a copy of the GNU General Public License # along with Koha; if not, see . - use strict; use warnings; @@ -30,17 +29,19 @@ use Koha::Caches; use Koha::Cache::Memory::Lite; use Koha::Language; -our (@ISA, @EXPORT_OK); +our ( @ISA, @EXPORT_OK ); + BEGIN { require Exporter; - @ISA = qw(Exporter); + @ISA = qw(Exporter); @EXPORT_OK = qw( getFrameworkLanguages getTranslatedLanguages getLanguages getAllLanguages ); - push @EXPORT_OK, qw(getFrameworkLanguages getTranslatedLanguages getAllLanguages getLanguages get_bidi regex_lang_subtags language_get_description accept_language getlanguage get_rfc4646_from_iso639); + push @EXPORT_OK, + qw(getFrameworkLanguages getTranslatedLanguages getAllLanguages getLanguages get_bidi regex_lang_subtags language_get_description accept_language getlanguage get_rfc4646_from_iso639); } =head1 NAME @@ -71,26 +72,28 @@ Returns a reference to an array of hashes: =cut sub getFrameworkLanguages { + # get a hash with all language codes, names, and locale names my $all_languages = getAllLanguages(); my @languages; - + # find the available directory names - my $dir=C4::Context->config('intranetdir')."/installer/data/"; + my $dir = C4::Context->config('intranetdir') . "/installer/data/"; my $dir_h; - opendir ($dir_h,$dir); - my @listdir= grep { !/^\.|CVS/ && -d "$dir/$_"} readdir($dir_h); + opendir( $dir_h, $dir ); + my @listdir = grep { !/^\.|CVS/ && -d "$dir/$_" } readdir($dir_h); closedir $dir_h; # pull out all data for the dir names that exist for my $dirname (@listdir) { for my $language_set (@$all_languages) { - if ($dirname eq $language_set->{language_code}) { + if ( $dirname eq $language_set->{language_code} ) { push @languages, { - 'language_code'=>$dirname, - 'language_description'=>$language_set->{language_description}, - 'native_descrition'=>$language_set->{language_native_description} } + 'language_code' => $dirname, + 'language_description' => $language_set->{language_description}, + 'native_descrition' => $language_set->{language_native_description} + }; } } } @@ -112,54 +115,52 @@ Returns a reference to an array of hashes: =cut sub getTranslatedLanguages { - my ($interface, $theme, $current_language) = @_; + my ( $interface, $theme, $current_language ) = @_; $interface //= q{}; $theme //= q{}; my @languages; my @enabled_languages; if ($interface) { - if ($interface eq 'intranet') { + if ( $interface eq 'intranet' ) { @enabled_languages = split ",", C4::Context->preference('StaffInterfaceLanguages'); - } elsif ($interface eq 'opac') { + } elsif ( $interface eq 'opac' ) { @enabled_languages = split ",", C4::Context->preference('OPACLanguages'); } } - my $cache = Koha::Caches->get_instance; + my $cache = Koha::Caches->get_instance; my $cache_key = "languages_${interface}_${theme}"; - if ($interface && $interface eq 'opac' ) { + if ( $interface && $interface eq 'opac' ) { my $htdocs = C4::Context->config('opachtdocs'); my $cached = $cache->get_from_cache($cache_key); - if ( $cached ) { + if ($cached) { @languages = @{$cached}; } else { @languages = _get_opac_language_dirs( $htdocs, $theme ); - $cache->set_in_cache($cache_key, \@languages ); + $cache->set_in_cache( $cache_key, \@languages ); } - } - elsif ($interface && $interface eq 'intranet' ) { + } elsif ( $interface && $interface eq 'intranet' ) { my $htdocs = C4::Context->config('intrahtdocs'); my $cached = $cache->get_from_cache($cache_key); - if ( $cached ) { + if ($cached) { @languages = @{$cached}; } else { @languages = _get_intranet_language_dirs( $htdocs, $theme ); - $cache->set_in_cache($cache_key, \@languages ); + $cache->set_in_cache( $cache_key, \@languages ); } - } - else { + } else { my $htdocs = C4::Context->config('intrahtdocs'); - push @languages, _get_intranet_language_dirs( $htdocs ); + push @languages, _get_intranet_language_dirs($htdocs); $htdocs = C4::Context->config('opachtdocs'); - push @languages, _get_opac_language_dirs( $htdocs ); + push @languages, _get_opac_language_dirs($htdocs); my %seen; $seen{$_}++ for @languages; @languages = keys %seen; } - return _build_languages_arrayref(\@languages,$current_language,\@enabled_languages); + return _build_languages_arrayref( \@languages, $current_language, \@enabled_languages ); } =head2 getAllLanguages @@ -196,7 +197,7 @@ Returns a reference to an array of hashes of languages. =cut sub getLanguages { - my $lang = shift; + my $lang = shift; my $isFiltered = shift; my $dbh = C4::Context->dbh; @@ -207,10 +208,10 @@ sub getLanguages { $current_language = regex_lang_subtags($lang)->{'language'}; } - my $language_list = $isFiltered ? C4::Context->preference("AdvancedSearchLanguages") : undef; + my $language_list = $isFiltered ? C4::Context->preference("AdvancedSearchLanguages") : undef; my $language_list_cond = $language_list ? 'AND FIND_IN_SET(language_rfc4646_to_iso639.iso639_2_code, ?)' : ''; - my $sth = $dbh->prepare(" + my $sth = $dbh->prepare( " SELECT language_subtag_registry.*, language_rfc4646_to_iso639.iso639_2_code, @@ -259,16 +260,16 @@ sub getLanguages { AND native_language_descriptions.type = 'language' WHERE language_subtag_registry.type = 'language' - ${language_list_cond}"); + ${language_list_cond}" ); if ($language_list) { - $sth->execute($current_language, join ',' => split(/,|\|/, $language_list)); + $sth->execute( $current_language, join ',' => split( /,|\|/, $language_list ) ); } else { $sth->execute($current_language); } my @languages_list; - while (my $row = $sth->fetchrow_hashref) { + while ( my $row = $sth->fetchrow_hashref ) { push @languages_list, $row; } return \@languages_list; @@ -279,27 +280,24 @@ sub _get_opac_language_dirs { my @languages; if ( $theme and -d "$htdocs/$theme" ) { - (@languages) = _get_language_dirs($htdocs,$theme); - } - else { + (@languages) = _get_language_dirs( $htdocs, $theme ); + } else { for my $theme ( _get_themes('opac') ) { - push @languages, _get_language_dirs($htdocs,$theme); + push @languages, _get_language_dirs( $htdocs, $theme ); } } return @languages; } - sub _get_intranet_language_dirs { my ( $htdocs, $theme ) = @_; my @languages; if ( $theme and -d "$htdocs/$theme" ) { - @languages = _get_language_dirs($htdocs,$theme); - } - else { + @languages = _get_language_dirs( $htdocs, $theme ); + } else { foreach my $theme ( _get_themes('intranet') ) { - push @languages, _get_language_dirs($htdocs,$theme); + push @languages, _get_language_dirs( $htdocs, $theme ); } } return @languages; @@ -320,14 +318,14 @@ sub _get_themes { my @themes; if ( $interface && $interface eq 'intranet' ) { $htdocs = C4::Context->config('intrahtdocs'); - } - else { + } else { $htdocs = C4::Context->config('opachtdocs'); } my $dir_h; opendir $dir_h, "$htdocs"; my @dirlist = readdir $dir_h; foreach my $directory (@dirlist) { + # if there's an en dir, it's a valid theme -d "$htdocs/$directory/en" and push @themes, $directory; } @@ -342,21 +340,21 @@ Internal function, returns an array of directory names, excluding non-language d =cut sub _get_language_dirs { - my ($htdocs,$theme) = @_; + my ( $htdocs, $theme ) = @_; $htdocs //= ''; - $theme //= ''; + $theme //= ''; my @lang_strings; my $dir_h; opendir $dir_h, "$htdocs/$theme"; for my $lang_string ( sort readdir $dir_h ) { - next if $lang_string =~/^\./; + next if $lang_string =~ /^\./; next if $lang_string eq 'all'; - next if $lang_string =~/png$/; - next if $lang_string =~/js$/; - next if $lang_string =~/css$/; - next if $lang_string =~/CVS$/; - next if $lang_string =~/\.txt$/i; #Don't read the readme.txt ! - next if $lang_string =~/img|images|famfam|js|less|lib|sound|pdf/; + next if $lang_string =~ /png$/; + next if $lang_string =~ /js$/; + next if $lang_string =~ /css$/; + next if $lang_string =~ /CVS$/; + next if $lang_string =~ /\.txt$/i; #Don't read the readme.txt ! + next if $lang_string =~ /img|images|famfam|js|less|lib|sound|pdf/; push @lang_strings, $lang_string; } close $dir_h; @@ -372,114 +370,131 @@ FIXME: this could be rewritten and simplified using map =cut sub _build_languages_arrayref { - my ($translated_languages,$current_language,$enabled_languages) = @_; - $current_language //= ''; - my @translated_languages = @$translated_languages; - my @languages_loop; # the final reference to an array of hashrefs - my @enabled_languages = @$enabled_languages; - # how many languages are enabled, if one, take note, some contexts won't need to display it - my $language_groups; - my $track_language_groups; - my $current_language_regex = regex_lang_subtags($current_language); - # Loop through the translated languages - for my $translated_language (@translated_languages) { - # separate the language string into its subtag types - my $language_subtags_hashref = regex_lang_subtags($translated_language); + my ( $translated_languages, $current_language, $enabled_languages ) = @_; + $current_language //= ''; + my @translated_languages = @$translated_languages; + my @languages_loop; # the final reference to an array of hashrefs + my @enabled_languages = @$enabled_languages; - # is this language string 'enabled'? - for my $enabled_language (@enabled_languages) { - #warn "Checking out if $translated_language eq $enabled_language"; - $language_subtags_hashref->{'enabled'} = 1 if $translated_language eq $enabled_language; - } - - # group this language, key by langtag - $language_subtags_hashref->{'sublanguage_current'} = 1 if $translated_language eq $current_language; - $language_subtags_hashref->{'rfc4646_subtag'} = $translated_language; - $language_subtags_hashref->{'native_description'} = language_get_description($language_subtags_hashref->{language},$language_subtags_hashref->{language},'language'); - $language_subtags_hashref->{'script_description'} = language_get_description($language_subtags_hashref->{script},$language_subtags_hashref->{'language'},'script'); - $language_subtags_hashref->{'region_description'} = language_get_description($language_subtags_hashref->{region},$language_subtags_hashref->{'language'},'region'); - $language_subtags_hashref->{'variant_description'} = language_get_description($language_subtags_hashref->{variant},$language_subtags_hashref->{'language'},'variant'); - $track_language_groups->{$language_subtags_hashref->{'language'}}++; - push ( @{ $language_groups->{$language_subtags_hashref->{language}} }, $language_subtags_hashref ); + # how many languages are enabled, if one, take note, some contexts won't need to display it + my $language_groups; + my $track_language_groups; + my $current_language_regex = regex_lang_subtags($current_language); + + # Loop through the translated languages + for my $translated_language (@translated_languages) { + + # separate the language string into its subtag types + my $language_subtags_hashref = regex_lang_subtags($translated_language); + + # is this language string 'enabled'? + for my $enabled_language (@enabled_languages) { + + #warn "Checking out if $translated_language eq $enabled_language"; + $language_subtags_hashref->{'enabled'} = 1 if $translated_language eq $enabled_language; } - # $key is a language subtag like 'en' - my %idx = map { $enabled_languages->[$_] => $_ } reverse 0 .. @$enabled_languages-1; - my @ordered_keys = sort { - my $aa = ''; - my $bb = ''; - my $acount = @{ $language_groups->{$a} }; - my $bcount = @{ $language_groups->{$b} }; - if ( $language_groups->{$a}->[0]->{enabled} ) { - $aa = $language_groups->{$a}->[0]->{rfc4646_subtag}; - } - elsif ( $acount > 1 ) { - for ( my $i = 1 ; $i < $acount ; $i++ ) { - if ( $language_groups->{$a}->[$i]->{enabled} ) { - $aa = $language_groups->{$a}->[$i]->{rfc4646_subtag}; - last; - } + # group this language, key by langtag + $language_subtags_hashref->{'sublanguage_current'} = 1 if $translated_language eq $current_language; + $language_subtags_hashref->{'rfc4646_subtag'} = $translated_language; + $language_subtags_hashref->{'native_description'} = language_get_description( + $language_subtags_hashref->{language}, $language_subtags_hashref->{language}, + 'language' + ); + $language_subtags_hashref->{'script_description'} = language_get_description( + $language_subtags_hashref->{script}, $language_subtags_hashref->{'language'}, + 'script' + ); + $language_subtags_hashref->{'region_description'} = language_get_description( + $language_subtags_hashref->{region}, $language_subtags_hashref->{'language'}, + 'region' + ); + $language_subtags_hashref->{'variant_description'} = language_get_description( + $language_subtags_hashref->{variant}, $language_subtags_hashref->{'language'}, + 'variant' + ); + $track_language_groups->{ $language_subtags_hashref->{'language'} }++; + push( @{ $language_groups->{ $language_subtags_hashref->{language} } }, $language_subtags_hashref ); + } + + # $key is a language subtag like 'en' + + my %idx = map { $enabled_languages->[$_] => $_ } reverse 0 .. @$enabled_languages - 1; + my @ordered_keys = sort { + my $aa = ''; + my $bb = ''; + my $acount = @{ $language_groups->{$a} }; + my $bcount = @{ $language_groups->{$b} }; + if ( $language_groups->{$a}->[0]->{enabled} ) { + $aa = $language_groups->{$a}->[0]->{rfc4646_subtag}; + } elsif ( $acount > 1 ) { + for ( my $i = 1 ; $i < $acount ; $i++ ) { + if ( $language_groups->{$a}->[$i]->{enabled} ) { + $aa = $language_groups->{$a}->[$i]->{rfc4646_subtag}; + last; } } - if ( $language_groups->{$b}->[0]->{enabled} ) { - $bb = $language_groups->{$b}->[0]->{rfc4646_subtag}; - } - elsif ( $bcount > 1 ) { - for ( my $i = 1 ; $i < $bcount ; $i++ ) { - if ( $language_groups->{$b}->[$i]->{enabled} ) { - $bb = $language_groups->{$b}->[$i]->{rfc4646_subtag}; - last; - } + } + if ( $language_groups->{$b}->[0]->{enabled} ) { + $bb = $language_groups->{$b}->[0]->{rfc4646_subtag}; + } elsif ( $bcount > 1 ) { + for ( my $i = 1 ; $i < $bcount ; $i++ ) { + if ( $language_groups->{$b}->[$i]->{enabled} ) { + $bb = $language_groups->{$b}->[$i]->{rfc4646_subtag}; + last; } } - ( exists $idx{$aa} - and exists $idx{$bb} - and ( $idx{$aa} cmp $idx{$bb} ) ) - || ( exists $idx{$aa} and exists $idx{$bb} ) - || exists $idx{$bb} - } keys %$language_groups; - - for my $key ( @ordered_keys ) { - my $value = $language_groups->{$key}; - # is this language group enabled? are any of the languages within it enabled? - my $enabled; - for my $enabled_language (@enabled_languages) { - my $regex_enabled_language = regex_lang_subtags($enabled_language); - $enabled = 1 if $key eq ($regex_enabled_language->{language} // ''); - } - push @languages_loop, { - # this is only use if there is one - rfc4646_subtag => @$value[0]->{rfc4646_subtag}, - native_description => language_get_description($key,$key,'language'), - language => $key, - sublanguages_loop => $value, - plural => $track_language_groups->{$key} >1 ? 1 : 0, - current => ($current_language_regex->{language} // '') eq $key ? 1 : 0, - group_enabled => $enabled, - }; } - return \@languages_loop; + ( exists $idx{$aa} and exists $idx{$bb} and ( $idx{$aa} cmp $idx{$bb} ) ) + || ( exists $idx{$aa} and exists $idx{$bb} ) + || exists $idx{$bb} + } keys %$language_groups; + + for my $key (@ordered_keys) { + my $value = $language_groups->{$key}; + + # is this language group enabled? are any of the languages within it enabled? + my $enabled; + for my $enabled_language (@enabled_languages) { + my $regex_enabled_language = regex_lang_subtags($enabled_language); + $enabled = 1 if $key eq ( $regex_enabled_language->{language} // '' ); + } + push @languages_loop, { + + # this is only use if there is one + rfc4646_subtag => @$value[0]->{rfc4646_subtag}, + native_description => language_get_description( $key, $key, 'language' ), + language => $key, + sublanguages_loop => $value, + plural => $track_language_groups->{$key} > 1 ? 1 : 0, + current => ( $current_language_regex->{language} // '' ) eq $key ? 1 : 0, + group_enabled => $enabled, + }; + } + return \@languages_loop; } sub language_get_description { - my ($script,$lang,$type) = @_; + my ( $script, $lang, $type ) = @_; my $dbh = C4::Context->dbh; my $desc; my $sth = $dbh->prepare("SELECT description FROM language_descriptions WHERE subtag=? AND lang=? AND type=?"); + #warn "QUERY: SELECT description FROM language_descriptions WHERE subtag=$script AND lang=$lang AND type=$type"; - $sth->execute($script,$lang,$type); - while (my $descriptions = $sth->fetchrow_hashref) { + $sth->execute( $script, $lang, $type ); + while ( my $descriptions = $sth->fetchrow_hashref ) { $desc = $descriptions->{'description'}; } unless ($desc) { $sth = $dbh->prepare("SELECT description FROM language_descriptions WHERE subtag=? AND lang=? AND type=?"); - $sth->execute($script,'en',$type); - while (my $descriptions = $sth->fetchrow_hashref) { + $sth->execute( $script, 'en', $type ); + while ( my $descriptions = $sth->fetchrow_hashref ) { $desc = $descriptions->{'description'}; } } return $desc; } + =head2 regex_lang_subtags This internal sub takes a string composed according to RFC 4646 as @@ -500,31 +515,32 @@ sub regex_lang_subtags { # # Note: the tool requires that any real "=" or "#" or ";" in the regex be escaped. - my $alpha = qr/[a-zA-Z]/ ; # ALPHA - my $digit = qr/[0-9]/ ; # DIGIT - my $alphanum = qr/[a-zA-Z0-9]/ ; # ALPHA / DIGIT - my $x = qr/[xX]/ ; # private use singleton - my $singleton = qr/[a-w y-z A-W Y-Z]/ ; # other singleton - my $s = qr/[-]/ ; # separator -- lenient parsers will use [-_] + my $alpha = qr/[a-zA-Z]/; # ALPHA + my $digit = qr/[0-9]/; # DIGIT + my $alphanum = qr/[a-zA-Z0-9]/; # ALPHA / DIGIT + my $x = qr/[xX]/; # private use singleton + my $singleton = qr/[a-w y-z A-W Y-Z]/; # other singleton + my $s = qr/[-]/; # separator -- lenient parsers will use [-_] # Now do the components. The structure is slightly different to allow for capturing the right components. # The notation (?:....) is a non-capturing version of (...): so the "?:" can be deleted if someone doesn't care about capturing. - my $extlang = qr{(?: $s $alpha{3} )}x ; # *3("-" 3ALPHA) - my $language = qr{(?: $alpha{2,3} | $alpha{4,8} )}x ; + my $extlang = qr{(?: $s $alpha{3} )}x; # *3("-" 3ALPHA) + my $language = qr{(?: $alpha{2,3} | $alpha{4,8} )}x; + #my $language = qr{(?: $alpha{2,3}$extlang{0,3} | $alpha{4,8} )}x ; # (2*3ALPHA [ extlang ]) / 4ALPHA / 5*8ALPHA - my $script = qr{(?: $alpha{4} )}x ; # 4ALPHA + my $script = qr{(?: $alpha{4} )}x; # 4ALPHA - my $region = qr{(?: $alpha{2} | $digit{3} )}x ; # 2ALPHA / 3DIGIT + my $region = qr{(?: $alpha{2} | $digit{3} )}x; # 2ALPHA / 3DIGIT - my $variantSub = qr{(?: $digit$alphanum{3} | $alphanum{5,8} )}x ; # *("-" variant), 5*8alphanum / (DIGIT 3alphanum) - my $variant = qr{(?: $variantSub (?: $s$variantSub )* )}x ; # *("-" variant), 5*8alphanum / (DIGIT 3alphanum) + my $variantSub = qr{(?: $digit$alphanum{3} | $alphanum{5,8} )}x; # *("-" variant), 5*8alphanum / (DIGIT 3alphanum) + my $variant = qr{(?: $variantSub (?: $s$variantSub )* )}x; # *("-" variant), 5*8alphanum / (DIGIT 3alphanum) - my $extensionSub = qr{(?: $singleton (?: $s$alphanum{2,8} )+ )}x ; # singleton 1*("-" (2*8alphanum)) - my $extension = qr{(?: $extensionSub (?: $s$extensionSub )* )}x ; # singleton 1*("-" (2*8alphanum)) + my $extensionSub = qr{(?: $singleton (?: $s$alphanum{2,8} )+ )}x; # singleton 1*("-" (2*8alphanum)) + my $extension = qr{(?: $extensionSub (?: $s$extensionSub )* )}x; # singleton 1*("-" (2*8alphanum)) - my $privateuse = qr{(?: $x (?: $s$alphanum{1,8} )+ )}x ; # ("x"/"X") 1*("-" (1*8alphanum)) + my $privateuse = qr{(?: $x (?: $s$alphanum{1,8} )+ )}x; # ("x"/"X") 1*("-" (1*8alphanum)) # Define certain grandfathered codes, since otherwise the regex is pretty useless. # Since these are limited, this is safe even later changes to the registry -- @@ -533,7 +549,7 @@ sub regex_lang_subtags { # http://www.iana.org/assignments/language-subtag-registry # Note that these have to be compared case insensitively, requiring (?i) below. - my $grandfathered = qr{(?: (?i) + my $grandfathered = qr{(?: (?i) en $s GB $s oed | i $s (?: ami | bnn | default | enochian | hak | klingon | lux | mingo | navajo | pwn | tao | tay | tsu ) | sgn $s (?: BE $s fr | BE $s nl | CH $s de) @@ -552,15 +568,17 @@ sub regex_lang_subtags { #my $root = qr{(?: ($language) (?: $s ($script) )? 40% (?: $s ($region) )? 40% (?: $s ($variant) )? 10% (?: $s ($extension) )? 5% (?: $s ($privateuse) )? 5% ) 90% | ($grandfathered) 5% | ($privateuse) 5% }; - $string =~ qr{^ (?:($language)) (?:$s($script))? (?:$s($region))? (?:$s($variant))? (?:$s($extension))? (?:$s($privateuse))? $}xi; # |($grandfathered) | ($privateuse) $}xi; + $string =~ + qr{^ (?:($language)) (?:$s($script))? (?:$s($region))? (?:$s($variant))? (?:$s($extension))? (?:$s($privateuse))? $}xi + ; # |($grandfathered) | ($privateuse) $}xi; my %subtag = ( 'rfc4646_subtag' => $string, - 'language' => $1, - 'script' => $2, - 'region' => $3, - 'variant' => $4, - 'extension' => $5, - 'privateuse' => $6, + 'language' => $1, + 'script' => $2, + 'region' => $3, + 'variant' => $4, + 'extension' => $5, + 'privateuse' => $6, ); return \%subtag; } @@ -568,49 +586,61 @@ sub regex_lang_subtags { # Script Direction Resources: # http://www.w3.org/International/questions/qa-scripts sub get_bidi { - my ($language_script)= @_; + my ($language_script) = @_; my $dbh = C4::Context->dbh; my $bidi; my $sth = $dbh->prepare('SELECT bidi FROM language_script_bidi WHERE rfc4646_subtag=?'); $sth->execute($language_script); - while (my $result = $sth->fetchrow_hashref) { + while ( my $result = $sth->fetchrow_hashref ) { $bidi = $result->{'bidi'}; } return $bidi; -}; +} sub accept_language { + # referenced http://search.cpan.org/src/CGILMORE/I18N-AcceptLanguage-1.04/lib/I18N/AcceptLanguage.pm - my ($clientPreferences,$supportedLanguages) = @_; + my ( $clientPreferences, $supportedLanguages ) = @_; my @languages = (); if ($clientPreferences) { + # There should be no whitespace anways, but a cleanliness/sanity check $clientPreferences =~ s/\s//g; + # Prepare the list of client-acceptable languages - foreach my $tag (split(/,/, $clientPreferences)) { - my ($language, $quality) = split(/\;/, $tag); + foreach my $tag ( split( /,/, $clientPreferences ) ) { + my ( $language, $quality ) = split( /\;/, $tag ); $quality =~ s/^q=//i if $quality; $quality = 1 unless $quality; next if $quality <= 0; + # We want to force the wildcard to be last - $quality = 0 if ($language eq '*'); + $quality = 0 if ( $language eq '*' ); + # Pushing lowercase language here saves processing later - push(@languages, { quality => $quality, - language => $language, - lclanguage => lc($language) }); + push( + @languages, + { + quality => $quality, + language => $language, + lclanguage => lc($language) + } + ); } } else { carp "accept_language(x,y) called with no clientPreferences (x)."; } + # Prepare the list of server-supported languages my %supportedLanguages = (); my %secondaryLanguages = (); foreach my $language (@$supportedLanguages) { + # warn "Language supported: " . $language->{language}; my $subtag = $language->{rfc4646_subtag}; - $supportedLanguages{lc($subtag)} = $subtag; + $supportedLanguages{ lc($subtag) } = $subtag; if ( $subtag =~ /^([^-]+)-?/ ) { - $secondaryLanguages{lc($1)} = $subtag; + $secondaryLanguages{ lc($1) } = $subtag; } } @@ -618,32 +648,38 @@ sub accept_language { @languages = sort { $b->{quality} <=> $a->{quality} } @languages; my $secondaryMatch = ''; foreach my $tag (@languages) { - if (exists($supportedLanguages{$tag->{lclanguage}})) { + if ( exists( $supportedLanguages{ $tag->{lclanguage} } ) ) { + # Client en-us eq server en-us - return $supportedLanguages{$tag->{language}} if exists($supportedLanguages{$tag->{language}}); - return $supportedLanguages{$tag->{lclanguage}}; - } elsif (exists($secondaryLanguages{$tag->{lclanguage}})) { + return $supportedLanguages{ $tag->{language} } if exists( $supportedLanguages{ $tag->{language} } ); + return $supportedLanguages{ $tag->{lclanguage} }; + } elsif ( exists( $secondaryLanguages{ $tag->{lclanguage} } ) ) { + # Client en eq server en-us - return $secondaryLanguages{$tag->{language}} if exists($secondaryLanguages{$tag->{language}}); - return $supportedLanguages{$tag->{lclanguage}}; - } elsif ($tag->{lclanguage} =~ /^([^-]+)-/ && exists($secondaryLanguages{$1}) && $secondaryMatch eq '') { + return $secondaryLanguages{ $tag->{language} } if exists( $secondaryLanguages{ $tag->{language} } ); + return $supportedLanguages{ $tag->{lclanguage} }; + } elsif ( $tag->{lclanguage} =~ /^([^-]+)-/ && exists( $secondaryLanguages{$1} ) && $secondaryMatch eq '' ) { + # Client en-gb eq server en-us $secondaryMatch = $secondaryLanguages{$1}; - } elsif ($tag->{lclanguage} =~ /^([^-]+)-/ && exists($secondaryLanguages{$1}) && $secondaryMatch eq '') { + } elsif ( $tag->{lclanguage} =~ /^([^-]+)-/ && exists( $secondaryLanguages{$1} ) && $secondaryMatch eq '' ) { + # FIXME: We just checked the exact same conditional! # Client en-us eq server en $secondaryMatch = $supportedLanguages{$1}; - } elsif ($tag->{lclanguage} eq '*') { - # * matches every language not already specified. - # It doesn't care which we pick, so let's pick the default, - # if available, then the first in the array. - #return $acceptor->defaultLanguage() if $acceptor->defaultLanguage(); - return $supportedLanguages->[0]; + } elsif ( $tag->{lclanguage} eq '*' ) { + + # * matches every language not already specified. + # It doesn't care which we pick, so let's pick the default, + # if available, then the first in the array. + #return $acceptor->defaultLanguage() if $acceptor->defaultLanguage(); + return $supportedLanguages->[0]; } } + # No primary matches. Secondary? (ie, en-us requested and en supported) return $secondaryMatch if $secondaryMatch; - return; # else, we got nothing. + return; # else, we got nothing. } =head2 getlanguage @@ -675,23 +711,23 @@ sub getlanguage { my ($cgi) = @_; my $memory_cache = Koha::Cache::Memory::Lite->get_instance(); - my $cache_key = "getlanguage"; + my $cache_key = "getlanguage"; unless ( $cgi and $cgi->param('language') ) { my $cached = $memory_cache->get_from_cache($cache_key); return $cached if $cached; } my $interface = C4::Context->interface; - my $theme = ''; + my $theme = ''; my $language; my @languages; - if ($interface eq 'opac' || $interface eq 'intranet') { + if ( $interface eq 'opac' || $interface eq 'intranet' ) { $cgi //= CGI->new; $theme = C4::Context->preference( ( $interface eq 'opac' ) ? 'opacthemes' : 'template' ); - my $preference_to_check = - $interface eq 'intranet' ? 'StaffInterfaceLanguages' : 'OPACLanguages'; + my $preference_to_check = $interface eq 'intranet' ? 'StaffInterfaceLanguages' : 'OPACLanguages'; + # Get the available/valid languages list my $preference_value = C4::Context->preference($preference_to_check); if ($preference_value) { @@ -699,24 +735,26 @@ sub getlanguage { } # Choose language from the URL - my $cgi_param_language = $cgi->param( 'language' ); - if ( defined $cgi_param_language && any { $_ eq $cgi_param_language } @languages) { + my $cgi_param_language = $cgi->param('language'); + if ( defined $cgi_param_language && any { $_ eq $cgi_param_language } @languages ) { $language = $cgi_param_language; } # cookie - if (not $language and my $cgi_cookie_language = $cgi->cookie('KohaOpacLanguage') ) { - ( $language = $cgi_cookie_language ) =~ s/[^a-zA-Z_-]*//; # sanitize cookie + if ( not $language and my $cgi_cookie_language = $cgi->cookie('KohaOpacLanguage') ) { + ( $language = $cgi_cookie_language ) =~ s/[^a-zA-Z_-]*//; # sanitize cookie } } else { - @languages = map { $_->{rfc4646_subtag} } @{ getTranslatedLanguages($interface, $theme) }; - $language = Koha::Language->get_requested_language(); + @languages = map { $_->{rfc4646_subtag} } @{ getTranslatedLanguages( $interface, $theme ) }; + $language = Koha::Language->get_requested_language(); } # HTTP_ACCEPT_LANGUAGE if ( !$language && $ENV{HTTP_ACCEPT_LANGUAGE} ) { - $language = accept_language( $ENV{HTTP_ACCEPT_LANGUAGE}, - getTranslatedLanguages( $interface, $theme ) ); + $language = accept_language( + $ENV{HTTP_ACCEPT_LANGUAGE}, + getTranslatedLanguages( $interface, $theme ) + ); } # Ignore a lang not selected in sysprefs @@ -743,8 +781,9 @@ sub getlanguage { sub get_rfc4646_from_iso639 { my $iso_code = shift; - my $rfc_subtag = Koha::Database->new()->schema->resultset('LanguageRfc4646ToIso639')->find({iso639_2_code=>$iso_code}); - if ( $rfc_subtag ) { + my $rfc_subtag = + Koha::Database->new()->schema->resultset('LanguageRfc4646ToIso639')->find( { iso639_2_code => $iso_code } ); + if ($rfc_subtag) { return $rfc_subtag->rfc4646_subtag; } else { return; diff --git a/C4/Letters.pm b/C4/Letters.pm index 122231b87d..0e17d4c23d 100644 --- a/C4/Letters.pm +++ b/C4/Letters.pm @@ -44,26 +44,27 @@ use Koha::Template::Plugin::KohaDates; use constant SERIALIZED_EMAIL_CONTENT_TYPE => 'message/rfc822'; -our (@ISA, @EXPORT_OK); +our ( @ISA, @EXPORT_OK ); + BEGIN { require Exporter; - @ISA = qw(Exporter); + @ISA = qw(Exporter); @EXPORT_OK = qw( - GetLetters - GetLettersAvailableForALibrary - GetLetterTemplates - DelLetter - GetPreparedLetter - GetWrappedLetter - SendAlerts - GetPrintMessages - GetQueuedMessages - GetMessage - GetMessageTransportTypes + GetLetters + GetLettersAvailableForALibrary + GetLetterTemplates + DelLetter + GetPreparedLetter + GetWrappedLetter + SendAlerts + GetPrintMessages + GetQueuedMessages + GetMessage + GetMessageTransportTypes - EnqueueLetter - SendQueuedMessages - ResendMessage + EnqueueLetter + SendQueuedMessages + ResendMessage ); } @@ -96,23 +97,23 @@ C4::Letters - Give functions for Letters management =cut sub GetLetters { - my ($filters) = @_; - my $module = $filters->{module}; - my $code = $filters->{code}; + my ($filters) = @_; + my $module = $filters->{module}; + my $code = $filters->{code}; my $branchcode = $filters->{branchcode}; - my $dbh = C4::Context->dbh; - my $letters = $dbh->selectall_arrayref( + my $dbh = C4::Context->dbh; + my $letters = $dbh->selectall_arrayref( q| SELECT code, module, name FROM letter WHERE 1 | - . ( $module ? q| AND module = ?| : q|| ) - . ( $code ? q| AND code = ?| : q|| ) - . ( defined $branchcode ? q| AND branchcode = ?| : q|| ) - . q| GROUP BY code, module, name ORDER BY name|, { Slice => {} } - , ( $module ? $module : () ) - , ( $code ? $code : () ) + . ( $module ? q| AND module = ?| : q|| ) + . ( $code ? q| AND code = ?| : q|| ) + . ( defined $branchcode ? q| AND branchcode = ?| : q|| ) + . q| GROUP BY code, module, name ORDER BY name|, { Slice => {} } + , ( $module ? $module : () ) + , ( $code ? $code : () ) , ( defined $branchcode ? $branchcode : () ) ); @@ -134,12 +135,12 @@ sub GetLetters { =cut sub GetLetterTemplates { - my ( $params ) = @_; + my ($params) = @_; - my $module = $params->{module}; - my $code = $params->{code}; + my $module = $params->{module}; + my $code = $params->{code}; my $branchcode = $params->{branchcode} // ''; - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; return Koha::Notice::Templates->search( { module => $module, @@ -183,9 +184,9 @@ sub GetLettersAvailableForALibrary { FROM letter WHERE 1 | - . q| AND branchcode = ''| - . ( $module ? q| AND module = ?| : q|| ) - . q| ORDER BY name|, { Slice => {} } + . q| AND branchcode = ''| + . ( $module ? q| AND module = ?| : q|| ) + . q| ORDER BY name|, { Slice => {} } , ( $module ? $module : () ) ); @@ -197,9 +198,9 @@ sub GetLettersAvailableForALibrary { FROM letter WHERE 1 | - . q| AND branchcode = ?| - . ( $module ? q| AND module = ?| : q|| ) - . q| ORDER BY name|, { Slice => {} } + . q| AND branchcode = ?| + . ( $module ? q| AND module = ?| : q|| ) + . q| ORDER BY name|, { Slice => {} } , $branchcode , ( $module ? $module : () ) ); @@ -210,13 +211,16 @@ sub GetLettersAvailableForALibrary { $letters{ $l->{code} } = $l; } for my $l (@$specific_letters) { + # Overwrite the default letter with the specific one. $letters{ $l->{code} } = $l; } - return [ map { $letters{$_} } - sort { $letters{$a}->{name} cmp $letters{$b}->{name} } - keys %letters ]; + return [ + map { $letters{$_} } + sort { $letters{$a}->{name} cmp $letters{$b}->{name} } + keys %letters + ]; } @@ -244,15 +248,16 @@ sub DelLetter { my $mtt = $params->{mtt}; my $lang = $params->{lang}; my $dbh = C4::Context->dbh; - $dbh->do(q| + $dbh->do( + q| DELETE FROM letter WHERE branchcode = ? AND module = ? AND code = ? | - . ( $mtt ? q| AND message_transport_type = ?| : q|| ) - . ( $lang? q| AND lang = ?| : q|| ) - , undef, $branchcode, $module, $code, ( $mtt ? $mtt : () ), ( $lang ? $lang : () ) ); + . ( $mtt ? q| AND message_transport_type = ?| : q|| ) . ( $lang ? q| AND lang = ?| : q|| ), undef, + $branchcode, $module, $code, ( $mtt ? $mtt : () ), ( $lang ? $lang : () ) + ); } =head2 SendAlerts @@ -287,43 +292,39 @@ sub SendAlerts { # prepare the letter... # search the subscriptionid - my $sth = - $dbh->prepare( - "SELECT subscriptionid FROM serial WHERE serialid=?"); + my $sth = $dbh->prepare("SELECT subscriptionid FROM serial WHERE serialid=?"); $sth->execute($externalid); my ($subscriptionid) = $sth->fetchrow - or warn( "No subscription for '$externalid'" ), - return; + or warn("No subscription for '$externalid'"), + return; # search the biblionumber - $sth = - $dbh->prepare( - "SELECT biblionumber FROM subscription WHERE subscriptionid=?"); + $sth = $dbh->prepare("SELECT biblionumber FROM subscription WHERE subscriptionid=?"); $sth->execute($subscriptionid); my ($biblionumber) = $sth->fetchrow - or warn( "No biblionumber for '$subscriptionid'" ), - return; + or warn("No biblionumber for '$subscriptionid'"), + return; # find the list of subscribers to notify - my $subscription = Koha::Subscriptions->find( $subscriptionid ); - my $subscribers = $subscription->subscribers; + my $subscription = Koha::Subscriptions->find($subscriptionid); + my $subscribers = $subscription->subscribers; while ( my $patron = $subscribers->next ) { my $email = $patron->notice_email_address or next; -# warn "sending issues..."; + # warn "sending issues..."; my $userenv = C4::Context->userenv; my $library = $patron->library; - my $letter = GetPreparedLetter ( - module => 'serial', + my $letter = GetPreparedLetter( + module => 'serial', letter_code => $letter_code, - branchcode => $userenv->{branch}, - tables => { - 'branches' => $library->branchcode, - 'biblio' => $biblionumber, - 'biblioitems' => $biblionumber, - 'borrowers' => $patron->unblessed, + branchcode => $userenv->{branch}, + tables => { + 'branches' => $library->branchcode, + 'biblio' => $biblionumber, + 'biblioitems' => $biblionumber, + 'borrowers' => $patron->unblessed, 'subscription' => $subscriptionid, - 'serial' => $externalid, + 'serial' => $externalid, }, want_librarian => 1, ) or return; @@ -342,15 +343,14 @@ sub SendAlerts { if ( $letter->{is_html} ) { $mail->html_body( _wrap_html( $letter->{content}, "" . $letter->{title} ) ); - } - else { + } else { $mail->text_body( $letter->{content} ); } my $success = try { - $mail->send_or_die({ transport => $library->smtp_server->transport }); - } - catch { + $mail->send_or_die( { transport => $library->smtp_server->transport } ); + } catch { + # We expect ref($_) eq 'Email::Sender::Failure' $error = $_->message; @@ -361,8 +361,7 @@ sub SendAlerts { return { error => $error } unless $success; } - } - elsif ( $type eq 'claimacquisition' or $type eq 'claimissues' or $type eq 'orderacquisition' ) { + } elsif ( $type eq 'claimacquisition' or $type eq 'claimissues' or $type eq 'orderacquisition' ) { # prepare the letter... my $strsth; @@ -371,7 +370,7 @@ sub SendAlerts { my $action; my $basketno; my %loops; - if ( $type eq 'claimacquisition') { + if ( $type eq 'claimacquisition' ) { $strsth = qq{ SELECT aqorders.*,aqbasket.*,biblio.*,biblioitems.* FROM aqorders @@ -381,18 +380,18 @@ sub SendAlerts { WHERE aqorders.ordernumber IN ( }; - if (!@$externalid){ + if ( !@$externalid ) { carp "No order selected"; return { error => "no_order_selected" }; } $strsth .= join( ",", ('?') x @$externalid ) . ")"; - $action = "ACQUISITION CLAIM"; + $action = "ACQUISITION CLAIM"; $sthorders = $dbh->prepare($strsth); - $sthorders->execute( @$externalid ); + $sthorders->execute(@$externalid); $dataorders = $sthorders->fetchall_arrayref( {} ); } - if ($type eq 'claimissues') { + if ( $type eq 'claimissues' ) { $strsth = qq{ SELECT serial.*,subscription.*, biblio.*, biblioitems.*, aqbooksellers.*, aqbooksellers.id AS booksellerid @@ -404,21 +403,21 @@ sub SendAlerts { WHERE serial.serialid IN ( }; - if (!@$externalid){ + if ( !@$externalid ) { carp "No issues selected"; return { error => "no_issues_selected" }; } $strsth .= join( ",", ('?') x @$externalid ) . ")"; - $action = "SERIAL CLAIM"; + $action = "SERIAL CLAIM"; $sthorders = $dbh->prepare($strsth); - $sthorders->execute( @$externalid ); + $sthorders->execute(@$externalid); $dataorders = $sthorders->fetchall_arrayref( {} ); } - if ( $type eq 'orderacquisition') { + if ( $type eq 'orderacquisition' ) { $basketno = $externalid; - $strsth = qq{ + $strsth = qq{ SELECT aqorders.*,aqbasket.*,biblio.*,biblioitems.* FROM aqorders LEFT JOIN aqbasket ON aqbasket.basketno=aqorders.basketno @@ -428,52 +427,50 @@ sub SendAlerts { AND orderstatus IN ('new','ordered') }; - unless ( $basketno ) { + unless ($basketno) { carp "No basketnumber given"; return { error => "no_basketno" }; } - $action = "ACQUISITION ORDER"; + $action = "ACQUISITION ORDER"; $sthorders = $dbh->prepare($strsth); $sthorders->execute($basketno); $dataorders = $sthorders->fetchall_arrayref( {} ); - %loops = ( - aqorders => [ map { $_->{ordernumber} } @$dataorders ] - ); + %loops = ( aqorders => [ map { $_->{ordernumber} } @$dataorders ] ); } my $booksellerid = $dataorders->[0]->{booksellerid}; - my $addressee = $type eq 'claimacquisition' || $type eq 'orderacquisition' ? 'acqprimary' : 'serialsprimary'; + my $addressee = $type eq 'claimacquisition' || $type eq 'orderacquisition' ? 'acqprimary' : 'serialsprimary'; my $sthcontact = - $dbh->prepare("SELECT * FROM aqcontacts WHERE booksellerid=? AND $type=1 ORDER BY $addressee DESC"); - $sthcontact->execute( $booksellerid ); + $dbh->prepare("SELECT * FROM aqcontacts WHERE booksellerid=? AND $type=1 ORDER BY $addressee DESC"); + $sthcontact->execute($booksellerid); my $datacontact = $sthcontact->fetchrow_hashref; my @email; my @cc; - push @email, $datacontact->{email} if ( $datacontact && $datacontact->{email} ); + push @email, $datacontact->{email} if ( $datacontact && $datacontact->{email} ); unless (@email) { warn "Bookseller $booksellerid without emails"; return { error => "no_email" }; } my $addlcontact; - while ($addlcontact = $sthcontact->fetchrow_hashref) { + while ( $addlcontact = $sthcontact->fetchrow_hashref ) { push @cc, $addlcontact->{email} if ( $addlcontact && $addlcontact->{email} ); } my $userenv = C4::Context->userenv; - my $letter = GetPreparedLetter ( - module => $type, + my $letter = GetPreparedLetter( + module => $type, letter_code => $letter_code, - branchcode => $userenv->{branch}, - tables => { + branchcode => $userenv->{branch}, + tables => { 'branches' => $userenv->{branch}, 'aqbooksellers' => $booksellerid, 'aqcontacts' => $datacontact, 'aqbasket' => $basketno, }, - repeat => $dataorders, - loops => \%loops, + repeat => $dataorders, + loops => \%loops, want_librarian => 1, ) or return { error => "no_letter" }; @@ -482,7 +479,7 @@ sub SendAlerts { # ... then send mail my $library = Koha::Libraries->find( $userenv->{branch} ); - my $mail = Koha::Email->create( + my $mail = Koha::Email->create( { to => join( ',', @email ), cc => join( ',', @cc ), @@ -518,15 +515,14 @@ sub SendAlerts { if ( $letter->{is_html} ) { $mail->html_body( _wrap_html( $letter->{content}, "" . $letter->{title} ) ); - } - else { + } else { $mail->text_body( "" . $letter->{content} ); } my $success = try { - $mail->send_or_die({ transport => $library->smtp_server->transport }); - } - catch { + $mail->send_or_die( { transport => $library->smtp_server->transport } ); + } catch { + # We expect ref($_) eq 'Email::Sender::Failure' $error = $_->message; @@ -537,18 +533,13 @@ sub SendAlerts { return { error => $error } unless $success; - my $log_object = $action eq 'ACQUISITION ORDER' ? $externalid : undef; - my $module = $action eq 'ACQUISITION ORDER' ? 'ACQUISITIONS' : 'CLAIMS'; + my $log_object = $action eq 'ACQUISITION ORDER' ? $externalid : undef; + my $module = $action eq 'ACQUISITION ORDER' ? 'ACQUISITIONS' : 'CLAIMS'; logaction( $module, $action, $log_object, - "To=" - . join( ',', @email ) - . " Title=" - . $letter->{title} - . " Content=" - . $letter->{content} + "To=" . join( ',', @email ) . " Title=" . $letter->{title} . " Content=" . $letter->{content} ) if C4::Context->preference("ClaimsLog"); } @@ -591,10 +582,10 @@ sub GetPreparedLetter { my $letter = $params{letter}; my $lang = $params{lang} || 'default'; - unless ( $letter ) { - my $module = $params{module} or croak "No module"; + unless ($letter) { + my $module = $params{module} or croak "No module"; my $letter_code = $params{letter_code} or croak "No letter_code"; - my $branchcode = $params{branchcode} || ''; + my $branchcode = $params{branchcode} || ''; my $mtt = $params{message_transport_type} || 'email'; my $template = Koha::Notice::Templates->find_effective_template( @@ -607,7 +598,7 @@ sub GetPreparedLetter { } ); - unless ( $template ) { + unless ($template) { warn( "No $module $letter_code letter transported by " . $mtt ); return; } @@ -617,15 +608,16 @@ sub GetPreparedLetter { } $lang = $letter->{'lang'}; - my $objects = $params{objects} || {}; - my $tables = $params{tables} || {}; + my $objects = $params{objects} || {}; + my $tables = $params{tables} || {}; my $substitute = $params{substitute} || {}; - my $loops = $params{loops} || {}; # loops is not supported for historical notices syntax - my $repeat = $params{repeat}; + my $loops = $params{loops} || {}; # loops is not supported for historical notices syntax + my $repeat = $params{repeat}; %$tables || %$substitute || $repeat || %$loops || %$objects - or carp( "ERROR: nothing to substitute - all of 'objects', 'tables', 'loops' and 'substitute' are empty" ), - return; + or carp("ERROR: nothing to substitute - all of 'objects', 'tables', 'loops' and 'substitute' are empty"), + return; my $want_librarian = $params{want_librarian}; + if ($want_librarian) { my $userenv = C4::Context->userenv; $objects->{librarian} = Koha::Patrons->find( C4::Context->userenv->{number} ) if ($userenv); @@ -666,21 +658,22 @@ sub GetPreparedLetter { ); if (%$substitute) { - while ( my ($token, $val) = each %$substitute ) { + while ( my ( $token, $val ) = each %$substitute ) { $val //= q{}; if ( $token eq 'items.content' ) { $val =~ s|\n|
|g if $letter->{is_html}; } - $letter->{title} =~ s/<<$token>>/$val/g; + $letter->{title} =~ s/<<$token>>/$val/g; $letter->{content} =~ s/<<$token>>/$val/g; - } + } } my $OPACBaseURL = C4::Context->preference('OPACBaseURL'); $letter->{content} =~ s/<>/$OPACBaseURL/go; if ($want_librarian) { + # parsing librarian name my $userenv = C4::Context->userenv; $letter->{content} =~ s/<>/$userenv->{firstname}/go; @@ -688,10 +681,10 @@ sub GetPreparedLetter { $letter->{content} =~ s/<>/$userenv->{emailaddress}/go; } - my ($repeat_no_enclosing_tags, $repeat_enclosing_tags); + my ( $repeat_no_enclosing_tags, $repeat_enclosing_tags ); if ($repeat) { - if (ref ($repeat) eq 'ARRAY' ) { + if ( ref($repeat) eq 'ARRAY' ) { $repeat_no_enclosing_tags = $repeat; } else { $repeat_enclosing_tags = $repeat; @@ -699,10 +692,10 @@ sub GetPreparedLetter { } if ($repeat_enclosing_tags) { - while ( my ($tag, $tag_tables) = each %$repeat_enclosing_tags ) { + while ( my ( $tag, $tag_tables ) = each %$repeat_enclosing_tags ) { if ( $letter->{content} =~ m!<$tag>(.*)!s ) { my $subcontent = $1; - my @lines = map { + my @lines = map { my %subletter = ( title => '', content => $subcontent ); _substitute_tables( \%subletter, $_ ); $subletter{content}; @@ -718,8 +711,8 @@ sub GetPreparedLetter { if ($repeat_no_enclosing_tags) { if ( $letter->{content} =~ m/[^\n]*<<.*>>[^\n]*/so ) { - my $line = $&; - my $i = 1; + my $line = $&; + my $i = 1; my @lines = map { my $c = $line; $c =~ s/<>/$i/go; @@ -735,7 +728,7 @@ sub GetPreparedLetter { } } - $letter->{content} =~ s/<<\S*>>//go; #remove any stragglers + $letter->{content} =~ s/<<\S*>>//go; #remove any stragglers Koha::Plugins->call( 'transform_prepared_letter', { letter => $letter, params => \%params } ); @@ -744,19 +737,19 @@ sub GetPreparedLetter { sub _substitute_tables { my ( $letter, $tables ) = @_; - while ( my ($table, $param) = each %$tables ) { + while ( my ( $table, $param ) = each %$tables ) { next unless $param; my $ref = ref $param; my $values; - if ($ref && $ref eq 'HASH') { + if ( $ref && $ref eq 'HASH' ) { $values = $param; - } - else { + } else { my $sth = _parseletter_sth($table); unless ($sth) { - warn "_parseletter_sth('$table') failed to return a valid sth. No substitution will be done for that table."; + warn + "_parseletter_sth('$table') failed to return a valid sth. No substitution will be done for that table."; return; } $sth->execute( $ref ? @$param : $param ); @@ -765,7 +758,7 @@ sub _substitute_tables { $sth->finish(); } - _parseletter ( $letter, $table, $values ); + _parseletter( $letter, $table, $values ); } } @@ -776,42 +769,44 @@ sub _parseletter_sth { carp "ERROR: _parseletter_sth() called without argument (table)"; return; } + # NOTE: we used to check whether we had a statement handle cached in # a %handles module-level variable. This was a dumb move and # broke things for the rest of us. prepare_cached is a better # way to cache statement handles anyway. - my $query = - ($table eq 'accountlines' ) ? "SELECT * FROM $table WHERE accountlines_id = ?" : - ($table eq 'biblio' ) ? "SELECT * FROM $table WHERE biblionumber = ?" : - ($table eq 'biblioitems' ) ? "SELECT * FROM $table WHERE biblionumber = ?" : - ($table eq 'tickets' ) ? "SELECT * FROM $table WHERE id = ?" : - ($table eq 'ticket_updates' ) ? "SELECT * FROM $table WHERE id = ?" : - ($table eq 'credits' ) ? "SELECT * FROM accountlines WHERE accountlines_id = ?" : - ($table eq 'debits' ) ? "SELECT * FROM accountlines WHERE accountlines_id = ?" : - ($table eq 'items' ) ? "SELECT * FROM $table WHERE itemnumber = ?" : - ($table eq 'issues' ) ? "SELECT * FROM $table WHERE itemnumber = ?" : - ($table eq 'old_issues' ) ? "SELECT * FROM $table WHERE issue_id = ?" : - ($table eq 'reserves' ) ? "SELECT * FROM $table WHERE borrowernumber = ? and biblionumber = ?" : - ($table eq 'borrowers' ) ? "SELECT * FROM $table WHERE borrowernumber = ?" : - ($table eq 'branches' ) ? "SELECT * FROM $table WHERE branchcode = ?" : - ($table eq 'suggestions' ) ? "SELECT * FROM $table WHERE suggestionid = ?" : - ($table eq 'aqbooksellers') ? "SELECT * FROM $table WHERE id = ?" : - ($table eq 'aqorders' ) ? "SELECT * FROM $table WHERE ordernumber = ?" : - ($table eq 'aqbasket' ) ? "SELECT * FROM $table WHERE basketno = ?" : - ($table eq 'illrequests' ) ? "SELECT * FROM $table WHERE illrequest_id = ?" : - ($table eq 'article_requests') ? "SELECT * FROM $table WHERE id = ?" : - ($table eq 'borrower_modifications') ? "SELECT * FROM $table WHERE verification_token = ?" : - ($table eq 'subscription') ? "SELECT * FROM $table WHERE subscriptionid = ?" : - ($table eq 'serial') ? "SELECT * FROM $table WHERE serialid = ?" : - ($table eq 'problem_reports') ? "SELECT * FROM $table WHERE reportid = ?" : - ($table eq 'additional_contents' || $table eq 'opac_news') ? "SELECT * FROM additional_contents_localizations WHERE id = ?" : - ($table eq 'recalls') ? "SELECT * FROM $table WHERE recall_id = ?" : - undef ; + my $query = + ( $table eq 'accountlines' ) ? "SELECT * FROM $table WHERE accountlines_id = ?" + : ( $table eq 'biblio' ) ? "SELECT * FROM $table WHERE biblionumber = ?" + : ( $table eq 'biblioitems' ) ? "SELECT * FROM $table WHERE biblionumber = ?" + : ( $table eq 'tickets' ) ? "SELECT * FROM $table WHERE id = ?" + : ( $table eq 'ticket_updates' ) ? "SELECT * FROM $table WHERE id = ?" + : ( $table eq 'credits' ) ? "SELECT * FROM accountlines WHERE accountlines_id = ?" + : ( $table eq 'debits' ) ? "SELECT * FROM accountlines WHERE accountlines_id = ?" + : ( $table eq 'items' ) ? "SELECT * FROM $table WHERE itemnumber = ?" + : ( $table eq 'issues' ) ? "SELECT * FROM $table WHERE itemnumber = ?" + : ( $table eq 'old_issues' ) ? "SELECT * FROM $table WHERE issue_id = ?" + : ( $table eq 'reserves' ) ? "SELECT * FROM $table WHERE borrowernumber = ? and biblionumber = ?" + : ( $table eq 'borrowers' ) ? "SELECT * FROM $table WHERE borrowernumber = ?" + : ( $table eq 'branches' ) ? "SELECT * FROM $table WHERE branchcode = ?" + : ( $table eq 'suggestions' ) ? "SELECT * FROM $table WHERE suggestionid = ?" + : ( $table eq 'aqbooksellers' ) ? "SELECT * FROM $table WHERE id = ?" + : ( $table eq 'aqorders' ) ? "SELECT * FROM $table WHERE ordernumber = ?" + : ( $table eq 'aqbasket' ) ? "SELECT * FROM $table WHERE basketno = ?" + : ( $table eq 'illrequests' ) ? "SELECT * FROM $table WHERE illrequest_id = ?" + : ( $table eq 'article_requests' ) ? "SELECT * FROM $table WHERE id = ?" + : ( $table eq 'borrower_modifications' ) ? "SELECT * FROM $table WHERE verification_token = ?" + : ( $table eq 'subscription' ) ? "SELECT * FROM $table WHERE subscriptionid = ?" + : ( $table eq 'serial' ) ? "SELECT * FROM $table WHERE serialid = ?" + : ( $table eq 'problem_reports' ) ? "SELECT * FROM $table WHERE reportid = ?" + : ( $table eq 'additional_contents' || $table eq 'opac_news' ) + ? "SELECT * FROM additional_contents_localizations WHERE id = ?" + : ( $table eq 'recalls' ) ? "SELECT * FROM $table WHERE recall_id = ?" + : undef; unless ($query) { warn "ERROR: No _parseletter_sth query for table '$table'"; - return; # nothing to get + return; # nothing to get } - unless ($sth = C4::Context->dbh->prepare_cached($query)) { + unless ( $sth = C4::Context->dbh->prepare_cached($query) ) { warn "ERROR: Failed to prepare query: '$query'"; return; } @@ -834,86 +829,92 @@ sub _parseletter { # Work on a local copy of $values_in (passed by reference) to avoid side effects # in callers ( by changing / formatting values ) - my $values = $values_in ? { %$values_in } : {}; + my $values = $values_in ? {%$values_in} : {}; # FIXME Dates formatting must be done in notice's templates - if ( $table eq 'borrowers' && $values->{'dateexpiry'} ){ - $values->{'dateexpiry'} = output_pref({ dt => dt_from_string( $values->{'dateexpiry'} ), dateonly => 1 }); + if ( $table eq 'borrowers' && $values->{'dateexpiry'} ) { + $values->{'dateexpiry'} = output_pref( { dt => dt_from_string( $values->{'dateexpiry'} ), dateonly => 1 } ); } if ( $table eq 'reserves' && $values->{'waitingdate'} ) { - $values->{'waitingdate'} = output_pref({ dt => dt_from_string( $values->{'waitingdate'} ), dateonly => 1 }); + $values->{'waitingdate'} = output_pref( { dt => dt_from_string( $values->{'waitingdate'} ), dateonly => 1 } ); } - if ($letter->{content} && $letter->{content} =~ /<>/) { + if ( $letter->{content} && $letter->{content} =~ /<>/ ) { my $todaysdate = output_pref( dt_from_string() ); $letter->{content} =~ s/<>/$todaysdate/go; } - while ( my ($field, $val) = each %$values ) { - $val =~ s/\p{P}$// if $val && $table=~/biblio/; - #BZ 9886: Assuming that we want to eliminate ISBD punctuation here - #Therefore adding the test on biblio. This includes biblioitems, - #but excludes items. Removed unneeded global and lookahead. + while ( my ( $field, $val ) = each %$values ) { + $val =~ s/\p{P}$// if $val && $table =~ /biblio/; - if ( $table=~/^borrowers$/ && $field=~/^streettype$/ ) { - my $av = Koha::AuthorisedValues->search({ category => 'ROADTYPE', authorised_value => $val }); + #BZ 9886: Assuming that we want to eliminate ISBD punctuation here + #Therefore adding the test on biblio. This includes biblioitems, + #but excludes items. Removed unneeded global and lookahead. + + if ( $table =~ /^borrowers$/ && $field =~ /^streettype$/ ) { + my $av = Koha::AuthorisedValues->search( { category => 'ROADTYPE', authorised_value => $val } ); $val = $av->count ? $av->next->lib : ''; } # Dates replacement - my $replacedby = defined ($val) ? $val : ''; + my $replacedby = defined($val) ? $val : ''; if ( $replacedby and not $replacedby =~ m|9999-12-31| and $replacedby =~ m|^\d{4}-\d{2}-\d{2}( \d{2}:\d{2}:\d{2})?$| ) { # If the value is XXXX-YY-ZZ[ AA:BB:CC] we assume it is a date - my $dateonly = defined $1 ? 0 : 1; #$1 refers to the capture group wrapped in parentheses. In this case, that's the hours, minutes, seconds. + my $dateonly = + defined $1 + ? 0 + : 1 + ; #$1 refers to the capture group wrapped in parentheses. In this case, that's the hours, minutes, seconds. my $re_dateonly_filter = qr{ $field( \s* \| \s* dateonly\s*)?>> }xms; - for my $letter_field ( qw( title content ) ) { + for my $letter_field (qw( title content )) { my $filter_string_used = q{}; - if ( $letter->{ $letter_field } =~ $re_dateonly_filter ) { + if ( $letter->{$letter_field} =~ $re_dateonly_filter ) { + # We overwrite $dateonly if the filter exists and we have a time in the datetime $filter_string_used = $1 || q{}; - $dateonly = $1 unless $dateonly; + $dateonly = $1 unless $dateonly; } - my $replacedby_date = eval { - output_pref({ dt => scalar dt_from_string( $replacedby ), dateonly => $dateonly }); - }; + my $replacedby_date = + eval { output_pref( { dt => scalar dt_from_string($replacedby), dateonly => $dateonly } ); }; $replacedby_date //= q{}; - if ( $letter->{ $letter_field } ) { - $letter->{ $letter_field } =~ s/\Q<<$table.$field$filter_string_used>>\E/$replacedby_date/g; - $letter->{ $letter_field } =~ s/\Q<<$field$filter_string_used>>\E/$replacedby_date/g; + if ( $letter->{$letter_field} ) { + $letter->{$letter_field} =~ s/\Q<<$table.$field$filter_string_used>>\E/$replacedby_date/g; + $letter->{$letter_field} =~ s/\Q<<$field$filter_string_used>>\E/$replacedby_date/g; } } } + # Other fields replacement else { - for my $letter_field ( qw( title content ) ) { - if ( $letter->{ $letter_field } ) { - $letter->{ $letter_field } =~ s/<<$table.$field>>/$replacedby/g; - $letter->{ $letter_field } =~ s/<<$field>>/$replacedby/g; + for my $letter_field (qw( title content )) { + if ( $letter->{$letter_field} ) { + $letter->{$letter_field} =~ s/<<$table.$field>>/$replacedby/g; + $letter->{$letter_field} =~ s/<<$field>>/$replacedby/g; } } } } - if ($table eq 'borrowers' && $letter->{content}) { + if ( $table eq 'borrowers' && $letter->{content} ) { my $patron = Koha::Patrons->find( $values->{borrowernumber} ); - if ( $patron ) { + if ($patron) { my $attributes = $patron->extended_attributes; my %attr; while ( my $attribute = $attributes->next ) { my $code = $attribute->code; - my $val = $attribute->description; # FIXME - we always display intranet description here! + my $val = $attribute->description; # FIXME - we always display intranet description here! $val =~ s/\p{P}(?=$)//g if $val; next unless $val gt ''; $attr{$code} ||= []; push @{ $attr{$code} }, $val; } - while ( my ($code, $val_ar) = each %attr ) { + while ( my ( $code, $val_ar ) = each %attr ) { my $replacefield = "<>"; my $replacedby = join ',', @$val_ar; $letter->{content} =~ s/$replacefield/$replacedby/g; @@ -948,11 +949,12 @@ sub EnqueueLetter { my $params = shift or return; return unless exists $params->{'letter'}; -# return unless exists $params->{'borrowernumber'}; + + # return unless exists $params->{'borrowernumber'}; return unless exists $params->{'message_transport_type'}; my $content = $params->{letter}->{content}; - $content =~ s/\s+//g if(defined $content); + $content =~ s/\s+//g if ( defined $content ); if ( not defined $content or $content eq '' ) { Koha::Logger->get->info("Trying to add an empty message to the message queue"); return; @@ -961,7 +963,8 @@ sub EnqueueLetter { # If we have any attachments we should encode then into the body. if ( $params->{'attachments'} ) { $params->{'letter'} = _add_attachments( - { letter => $params->{'letter'}, + { + letter => $params->{'letter'}, attachments => $params->{'attachments'}, } ); @@ -980,7 +983,7 @@ sub EnqueueLetter { subject => $params->{letter}->{title}, content => $params->{letter}->{content}, metadata => $params->{letter}->{metadata} || q{}, - letter_code => $params->{letter}->{code} || q{}, + letter_code => $params->{letter}->{code} || q{}, message_transport_type => $params->{message_transport_type}, status => 'pending', time_queued => dt_from_string(), @@ -1020,16 +1023,18 @@ Returns number of messages sent. sub SendQueuedMessages { my $params = shift; - my $limit = $params->{limit}; - my $where = $params->{where}; + my $limit = $params->{limit}; + my $where = $params->{where}; Koha::Exceptions::BadParameter->throw("Parameter message_id cannot be empty if passed.") if ( exists( $params->{message_id} ) && !$params->{message_id} ); if ( C4::Context->config("enable_plugins") ) { - my @plugins = Koha::Plugins->new->GetPlugins({ - method => 'before_send_messages', - }); + my @plugins = Koha::Plugins->new->GetPlugins( + { + method => 'before_send_messages', + } + ); if (@plugins) { foreach my $plugin (@plugins) { @@ -1045,21 +1050,29 @@ sub SendQueuedMessages { my $smtp_transports = {}; - my $count_messages = 0; - my $unsent_messages = Koha::Notice::Messages->search({ - status => 'pending', - $params->{message_id} ? ( message_id => $params->{message_id} ) : (), - $params->{borrowernumber} ? ( borrowernumber => $params->{borrowernumber} ) : (), - # Check for scalar or array in letter_code and type - ref($params->{letter_code}) && @{$params->{letter_code}} ? ( letter_code => $params->{letter_code} ) : (), - !ref($params->{letter_code}) && $params->{letter_code} ? ( letter_code => $params->{letter_code} ) : (), - ref($params->{type}) && @{$params->{type}} ? ( message_transport_type => $params->{type} ) : (), #TODO Existing inconsistency - !ref($params->{type}) && $params->{type} ? ( message_transport_type => $params->{type} ) : (), #TODO Existing inconsistency - }); + my $count_messages = 0; + my $unsent_messages = Koha::Notice::Messages->search( + { + status => 'pending', + $params->{message_id} ? ( message_id => $params->{message_id} ) : (), + $params->{borrowernumber} ? ( borrowernumber => $params->{borrowernumber} ) : (), + + # Check for scalar or array in letter_code and type + ref( $params->{letter_code} ) + && @{ $params->{letter_code} } ? ( letter_code => $params->{letter_code} ) : (), + !ref( $params->{letter_code} ) && $params->{letter_code} ? ( letter_code => $params->{letter_code} ) : (), + ref( $params->{type} ) + && @{ $params->{type} } + ? ( message_transport_type => $params->{type} ) + : (), #TODO Existing inconsistency + !ref( $params->{type} ) + && $params->{type} ? ( message_transport_type => $params->{type} ) : (), #TODO Existing inconsistency + } + ); $unsent_messages = $unsent_messages->search( \$where ) if $where; - $domain_limits = Koha::Notice::Util->load_domain_limits; # (re)initialize per run - while( ( my $message_object = $unsent_messages->next ) && ( !$limit || $count_messages < $limit ) ) { + $domain_limits = Koha::Notice::Util->load_domain_limits; # (re)initialize per run + while ( ( my $message_object = $unsent_messages->next ) && ( !$limit || $count_messages < $limit ) ) { my $message = $message_object->unblessed; # If this fails the database is unwritable and we won't manage to send a message that continues to be marked 'pending' @@ -1067,45 +1080,55 @@ sub SendQueuedMessages { return unless $message_object->store; # warn Data::Dumper->Dump( [ $message ], [ 'message' ] ); - warn sprintf( 'Processing %s message to patron: %s', - $message->{'message_transport_type'}, - $message->{'borrowernumber'} || 'Admin' ) - if $params->{'verbose'}; + warn sprintf( + 'Processing %s message to patron: %s', + $message->{'message_transport_type'}, + $message->{'borrowernumber'} || 'Admin' + ) if $params->{'verbose'}; + # This is just begging for subclassing - next if ( lc($message->{'message_transport_type'}) eq 'rss' ); + next if ( lc( $message->{'message_transport_type'} ) eq 'rss' ); if ( lc( $message->{'message_transport_type'} ) eq 'email' ) { - my $rv = _send_message_by_email( $message, $params->{'username'}, $params->{'password'}, $params->{'method'}, $smtp_transports ); + my $rv = _send_message_by_email( + $message, $params->{'username'}, $params->{'password'}, $params->{'method'}, + $smtp_transports + ); $count_messages++ if $rv; - } - elsif ( lc( $message->{'message_transport_type'} ) eq 'sms' ) { + } elsif ( lc( $message->{'message_transport_type'} ) eq 'sms' ) { if ( C4::Context->preference('SMSSendDriver') eq 'Email' ) { - my $patron = Koha::Patrons->find( $message->{borrowernumber} ); + my $patron = Koha::Patrons->find( $message->{borrowernumber} ); my $sms_provider = Koha::SMS::Providers->find( $patron->sms_provider_id ); - unless ( $sms_provider ) { - warn sprintf( "Patron %s has no sms provider id set!", $message->{'borrowernumber'} ) if $params->{'verbose'}; + unless ($sms_provider) { + warn sprintf( "Patron %s has no sms provider id set!", $message->{'borrowernumber'} ) + if $params->{'verbose'}; _set_message_status( { message_id => $message->{'message_id'}, status => 'failed' } ); next; } unless ( $patron->smsalertnumber ) { _set_message_status( { message_id => $message->{'message_id'}, status => 'failed' } ); - warn sprintf( "No smsalertnumber found for patron %s!", $message->{'borrowernumber'} ) if $params->{'verbose'}; + warn sprintf( "No smsalertnumber found for patron %s!", $message->{'borrowernumber'} ) + if $params->{'verbose'}; next; } - $message->{to_address} = $patron->smsalertnumber; #Sometime this is set to email - sms should always use smsalertnumber + $message->{to_address} = + $patron->smsalertnumber; #Sometime this is set to email - sms should always use smsalertnumber $message->{to_address} .= '@' . $sms_provider->domain(); # Check for possible from_address override my $from_address = C4::Context->preference('EmailSMSSendDriverFromAddress'); - if ($from_address && $message->{from_address} ne $from_address) { + if ( $from_address && $message->{from_address} ne $from_address ) { $message->{from_address} = $from_address; - _update_message_from_address($message->{'message_id'}, $message->{from_address}); + _update_message_from_address( $message->{'message_id'}, $message->{from_address} ); } - _update_message_to_address($message->{'message_id'}, $message->{to_address}); - my $rv = _send_message_by_email( $message, $params->{'username'}, $params->{'password'}, $params->{'method'} ); + _update_message_to_address( $message->{'message_id'}, $message->{to_address} ); + my $rv = _send_message_by_email( + $message, $params->{'username'}, $params->{'password'}, + $params->{'method'} + ); $count_messages++ if $rv; } else { - my $rv = _send_message_by_sms( $message ); + my $rv = _send_message_by_sms($message); $count_messages++ if $rv; } } @@ -1127,10 +1150,14 @@ sub GetRSSMessages { return unless $params; return unless ref $params; return unless $params->{'borrowernumber'}; - - return _get_unsent_messages( { message_transport_type => 'rss', - limit => $params->{'limit'}, - borrowernumber => $params->{'borrowernumber'}, } ); + + return _get_unsent_messages( + { + message_transport_type => 'rss', + limit => $params->{'limit'}, + borrowernumber => $params->{'borrowernumber'}, + } + ); } =head2 GetPrintMessages @@ -1144,10 +1171,13 @@ person). sub GetPrintMessages { my $params = shift || {}; - - return _get_unsent_messages( { message_transport_type => 'print', - borrowernumber => $params->{'borrowernumber'}, - } ); + + return _get_unsent_messages( + { + message_transport_type => 'print', + borrowernumber => $params->{'borrowernumber'}, + } + ); } =head2 GetQueuedMessages ([$hashref]) @@ -1164,7 +1194,7 @@ Return is an arrayref of hashes, each has represents a message in the message qu sub GetQueuedMessages { my $params = shift; - my $dbh = C4::Context->dbh(); + my $dbh = C4::Context->dbh(); my $statement = << 'ENDSQL'; SELECT message_id, borrowernumber, subject, content, message_transport_type, status, time_queued, updated_on, failure_code, from_address, to_address, cc_address FROM message_queue @@ -1177,7 +1207,7 @@ ENDSQL push @query_params, $params->{'borrowernumber'}; } - if ( @whereclauses ) { + if (@whereclauses) { $statement .= ' WHERE ' . join( 'AND', @whereclauses ); } @@ -1186,9 +1216,9 @@ ENDSQL push @query_params, $params->{'limit'}; } - my $sth = $dbh->prepare( $statement ); - my $result = $sth->execute( @query_params ); - return $sth->fetchall_arrayref({}); + my $sth = $dbh->prepare($statement); + my $result = $sth->execute(@query_params); + return $sth->fetchall_arrayref( {} ); } =head2 GetMessageTransportTypes @@ -1200,12 +1230,12 @@ ENDSQL =cut sub GetMessageTransportTypes { - my $dbh = C4::Context->dbh(); - my $mtts = $dbh->selectcol_arrayref(" + my $dbh = C4::Context->dbh(); + my $mtts = $dbh->selectcol_arrayref( " SELECT message_transport_type FROM message_transport_types ORDER BY message_transport_type - "); + " ); return $mtts; } @@ -1216,14 +1246,16 @@ sub GetMessageTransportTypes { =cut sub GetMessage { - my ( $message_id ) = @_; + my ($message_id) = @_; return unless $message_id; my $dbh = C4::Context->dbh; - return $dbh->selectrow_hashref(q| + return $dbh->selectrow_hashref( + q| SELECT message_id, borrowernumber, subject, content, metadata, letter_code, message_transport_type, status, time_queued, updated_on, to_address, from_address, reply_address, content_type, failure_code FROM message_queue WHERE message_id = ? - |, {}, $message_id ); + |, {}, $message_id + ); } =head2 ResendMessage @@ -1243,18 +1275,22 @@ sub ResendMessage { my $message_id = shift; return unless $message_id; - my $message = GetMessage( $message_id ); + my $message = GetMessage($message_id); return unless $message; my $rv = 0; if ( $message->{status} ne 'pending' ) { - $rv = C4::Letters::_set_message_status({ - message_id => $message_id, - status => 'pending', - }); - $rv = $rv > 0? 1: 0; + $rv = C4::Letters::_set_message_status( + { + message_id => $message_id, + status => 'pending', + } + ); + $rv = $rv > 0 ? 1 : 0; + # Clear destination email address to force address update - _update_message_to_address( $message_id, undef ) if $rv && - $message->{message_transport_type} eq 'email'; + _update_message_to_address( $message_id, undef ) + if $rv + && $message->{message_transport_type} eq 'email'; } return $rv; } @@ -1281,7 +1317,7 @@ sub ResendMessage { sub _add_attachments { my $params = shift; - my $letter = $params->{letter}; + my $letter = $params->{letter}; my $attachments = $params->{attachments}; return $letter unless @$attachments; @@ -1289,12 +1325,11 @@ sub _add_attachments { if ( $letter->{is_html} ) { $message->html_body( _wrap_html( $letter->{content}, $letter->{title} ) ); - } - else { + } else { $message->text_body( $letter->{content} ); } - foreach my $attachment ( @$attachments ) { + foreach my $attachment (@$attachments) { $message->attach( Encode::encode( "UTF-8", $attachment->{content} ), content_type => $attachment->{type} || 'application/octet-stream', @@ -1304,7 +1339,7 @@ sub _add_attachments { } $letter->{'content-type'} = SERIALIZED_EMAIL_CONTENT_TYPE; - $letter->{content} = $message->as_string; + $letter->{content} = $message->as_string; return $letter; @@ -1330,7 +1365,7 @@ sub _add_attachments { sub _get_unsent_messages { my $params = shift; - my $dbh = C4::Context->dbh(); + my $dbh = C4::Context->dbh(); my $statement = qq{ SELECT mq.message_id, mq.borrowernumber, mq.subject, mq.content, mq.message_transport_type, mq.status, mq.time_queued, mq.from_address, mq.reply_address, mq.to_address, mq.content_type, b.branchcode, mq.letter_code, mq.failure_code, mq.letter_id FROM message_queue mq @@ -1345,16 +1380,20 @@ sub _get_unsent_messages { push @query_params, $params->{'borrowernumber'}; } if ( $params->{'letter_code'} ) { - my @letter_codes = ref $params->{'letter_code'} eq "ARRAY" ? @{$params->{'letter_code'}} : $params->{'letter_code'}; - if ( @letter_codes ) { + my @letter_codes = + ref $params->{'letter_code'} eq "ARRAY" ? @{ $params->{'letter_code'} } : $params->{'letter_code'}; + if (@letter_codes) { my $q = join( ",", ("?") x @letter_codes ); $statement .= " AND mq.letter_code IN ( $q ) "; push @query_params, @letter_codes; } } if ( $params->{'message_transport_type'} ) { - my @types = ref $params->{'message_transport_type'} eq "ARRAY" ? @{$params->{'message_transport_type'}} : $params->{'message_transport_type'}; - if ( @types ) { + my @types = + ref $params->{'message_transport_type'} eq "ARRAY" + ? @{ $params->{'message_transport_type'} } + : $params->{'message_transport_type'}; + if (@types) { my $q = join( ",", ("?") x @types ); $statement .= " AND message_transport_type IN ( $q ) "; push @query_params, @types; @@ -1373,21 +1412,22 @@ sub _get_unsent_messages { } } - my $sth = $dbh->prepare( $statement ); - my $result = $sth->execute( @query_params ); - return $sth->fetchall_arrayref({}); + my $sth = $dbh->prepare($statement); + my $result = $sth->execute(@query_params); + return $sth->fetchall_arrayref( {} ); } sub _send_message_by_email { my $message = shift or return; my ( $username, $password, $method, $smtp_transports ) = @_; - my $patron = Koha::Patrons->find( $message->{borrowernumber} ); + my $patron = Koha::Patrons->find( $message->{borrowernumber} ); my $to_address = $message->{'to_address'}; my $cc_address; my @guarantor_address; my $count_guarantor_address; - if (C4::Context->preference('RedirectGuaranteeEmail') && $patron) { + if ( C4::Context->preference('RedirectGuaranteeEmail') && $patron ) { + # Get guarantor addresses my $guarantor_relationships = $patron->guarantor_relationships; my @guarantors = $guarantor_relationships->guarantors->as_list; @@ -1398,7 +1438,7 @@ sub _send_message_by_email { $count_guarantor_address = scalar @guarantor_address; } unless ($to_address) { - if (!$patron) { + if ( !$patron ) { warn "FAIL: No 'to_address' and INVALID borrowernumber ($message->{borrowernumber})"; _set_message_status( { @@ -1412,8 +1452,9 @@ sub _send_message_by_email { if ($patron) { $to_address = $patron->notice_email_address; } - if (!$to_address && !$count_guarantor_address) { - warn "FAIL: No 'to_address', email address or guarantors email address for borrowernumber ($message->{borrowernumber})"; + if ( !$to_address && !$count_guarantor_address ) { + warn + "FAIL: No 'to_address', email address or guarantors email address for borrowernumber ($message->{borrowernumber})"; _set_message_status( { message_id => $message->{'message_id'}, @@ -1430,8 +1471,10 @@ sub _send_message_by_email { $cc_address = join( ',', @guarantor_address ); _update_message_cc_address( $message->{'message_id'}, $cc_address ); + # Skip this message if we exceed domain limits in this run - if( Koha::Notice::Util->exceeds_limit({ to => $to_address, limits => $domain_limits }) ) { + if ( Koha::Notice::Util->exceeds_limit( { to => $to_address, limits => $domain_limits } ) ) { + # Save the to_address if you delay the message so that we dont need to look it up again _update_message_to_address( $message->{'message_id'}, $to_address ) if !$message->{to_address}; @@ -1440,16 +1483,16 @@ sub _send_message_by_email { my $subject = $message->{'subject'}; - my $content = $message->{'content'}; + my $content = $message->{'content'}; my $content_type = $message->{'content_type'} || 'text/plain; charset="UTF-8"'; - my $is_html = $content_type =~ m/html/io; + my $is_html = $content_type =~ m/html/io; - my $branch_email = undef; - my $branch_replyto = undef; + my $branch_email = undef; + my $branch_replyto = undef; my $branch_returnpath = undef; my $library; - $patron //= Koha::Patrons->find( $message->{borrowernumber} ); # we might already found him + $patron //= Koha::Patrons->find( $message->{borrowernumber} ); # we might already found him if ($patron) { $library = $patron->library; $branch_email = $library->from_email_address; @@ -1460,10 +1503,10 @@ sub _send_message_by_email { # NOTE: Patron may not be defined above so branch_email may be undefined still # so we need to fallback to KohaAdminEmailAddress as a last resort. my $from_address = - $message->{'from_address'} - || $branch_email - || C4::Context->preference('KohaAdminEmailAddress'); - if( !$from_address ) { + $message->{'from_address'} + || $branch_email + || C4::Context->preference('KohaAdminEmailAddress'); + if ( !$from_address ) { _set_message_status( { message_id => $message->{'message_id'}, @@ -1472,7 +1515,7 @@ sub _send_message_by_email { } ); return; - }; + } my $email; try { @@ -1515,14 +1558,13 @@ sub _send_message_by_email { $email->text_body($content); } } - } - catch { + } catch { if ( ref($_) eq 'Koha::Exceptions::BadParameter' ) { _set_message_status( { message_id => $message->{'message_id'}, status => 'failed', - failure_code => "INVALID_EMAIL:".$_->parameter + failure_code => "INVALID_EMAIL:" . $_->parameter } ); } else { @@ -1539,14 +1581,13 @@ sub _send_message_by_email { return unless $email; my $smtp_server; - if ( $library ) { + if ($library) { $smtp_server = $library->smtp_server; - } - else { + } else { $smtp_server = Koha::SMTP::Servers->get_default; } - if ( $username ) { + if ($username) { $smtp_server->set( { sasl_username => $username, @@ -1555,11 +1596,11 @@ sub _send_message_by_email { ); } -# if initial message address was empty, coming here means that a to address was found and -# queue should be updated; same if to address was overriden by Koha::Email->create + # if initial message address was empty, coming here means that a to address was found and + # queue should be updated; same if to address was overriden by Koha::Email->create _update_message_to_address( $message->{'message_id'}, $email->email->header('To') ) - if !$message->{to_address} - || $message->{to_address} ne $email->email->header('To'); + if !$message->{to_address} + || $message->{to_address} ne $email->email->header('To'); $smtp_transports->{ $smtp_server->id // 'default' } ||= $smtp_server->transport; my $smtp_transport = $smtp_transports->{ $smtp_server->id // 'default' }; @@ -1569,22 +1610,21 @@ sub _send_message_by_email { || $message->{from_address} ne $email->email->header('From'); try { - $email->send_or_die({ transport => $smtp_transport }); + $email->send_or_die( { transport => $smtp_transport } ); _set_message_status( { - message_id => $message->{'message_id'}, - status => 'sent', + message_id => $message->{'message_id'}, + status => 'sent', failure_code => '' } ); return 1; - } - catch { + } catch { _set_message_status( { - message_id => $message->{'message_id'}, - status => 'failed', + message_id => $message->{'message_id'}, + status => 'failed', failure_code => 'SENDMAIL' } ); @@ -1595,7 +1635,7 @@ sub _send_message_by_email { } sub _wrap_html { - my ($content, $title) = @_; + my ( $content, $title ) = @_; my $css = C4::Context->preference("NoticeCSS") || ''; $css = qq{} if $css; @@ -1616,9 +1656,10 @@ EOS } sub _is_duplicate { - my ( $message ) = @_; - my $dbh = C4::Context->dbh; - my $count = $dbh->selectrow_array(q| + my ($message) = @_; + my $dbh = C4::Context->dbh; + my $count = $dbh->selectrow_array( + q| SELECT COUNT(*) FROM message_queue WHERE message_transport_type = ? @@ -1627,23 +1668,28 @@ sub _is_duplicate { AND CAST(updated_on AS date) = CAST(NOW() AS date) AND status="sent" AND content = ? - |, {}, $message->{message_transport_type}, $message->{borrowernumber}, $message->{letter_code}, $message->{content} ); + |, {}, $message->{message_transport_type}, $message->{borrowernumber}, $message->{letter_code}, $message->{content} + ); return $count; } sub _send_message_by_sms { my $message = shift or return; - my $patron = Koha::Patrons->find( $message->{borrowernumber} ); - _update_message_to_address($message->{message_id}, $patron->smsalertnumber) if $patron; + my $patron = Koha::Patrons->find( $message->{borrowernumber} ); + _update_message_to_address( $message->{message_id}, $patron->smsalertnumber ) if $patron; unless ( $patron and $patron->smsalertnumber ) { - _set_message_status( { message_id => $message->{'message_id'}, - status => 'failed', - failure_code => 'MISSING_SMS' } ); + _set_message_status( + { + message_id => $message->{'message_id'}, + status => 'failed', + failure_code => 'MISSING_SMS' + } + ); return; } - if ( _is_duplicate( $message ) ) { + if ( _is_duplicate($message) ) { _set_message_status( { message_id => $message->{'message_id'}, @@ -1669,8 +1715,7 @@ sub _send_message_by_sms { failure_code => '' } ); - } - else { + } else { _set_message_status( { message_id => $message->{'message_id'}, @@ -1684,41 +1729,43 @@ sub _send_message_by_sms { } sub _update_message_to_address { - my ($id, $to)= @_; + my ( $id, $to ) = @_; my $dbh = C4::Context->dbh(); - $dbh->do('UPDATE message_queue SET to_address=? WHERE message_id=?',undef,($to,$id)); + $dbh->do( 'UPDATE message_queue SET to_address=? WHERE message_id=?', undef, ( $to, $id ) ); } sub _update_message_from_address { - my ($message_id, $from_address) = @_; + my ( $message_id, $from_address ) = @_; my $dbh = C4::Context->dbh(); - $dbh->do('UPDATE message_queue SET from_address = ? WHERE message_id = ?', undef, ($from_address, $message_id)); + $dbh->do( 'UPDATE message_queue SET from_address = ? WHERE message_id = ?', undef, ( $from_address, $message_id ) ); } sub _update_message_cc_address { - my ($message_id, $cc_address) = @_; + my ( $message_id, $cc_address ) = @_; my $dbh = C4::Context->dbh(); - $dbh->do('UPDATE message_queue SET cc_address = ? WHERE message_id = ?', undef, ($cc_address, $message_id)); + $dbh->do( 'UPDATE message_queue SET cc_address = ? WHERE message_id = ?', undef, ( $cc_address, $message_id ) ); } sub _set_message_status { my $params = shift or return; - foreach my $required_parameter ( qw( message_id status ) ) { - return unless exists $params->{ $required_parameter }; + foreach my $required_parameter (qw( message_id status )) { + return unless exists $params->{$required_parameter}; } - my $dbh = C4::Context->dbh(); + my $dbh = C4::Context->dbh(); my $statement = 'UPDATE message_queue SET status= ?, failure_code= ? WHERE message_id = ?'; - my $sth = $dbh->prepare( $statement ); - my $result = $sth->execute( $params->{'status'}, - $params->{'failure_code'} || '', - $params->{'message_id'} ); + my $sth = $dbh->prepare($statement); + my $result = $sth->execute( + $params->{'status'}, + $params->{'failure_code'} || '', + $params->{'message_id'} + ); return $result; } sub _process_tt { - my ( $params ) = @_; + my ($params) = @_; my $content = $params->{content}; my $tables = $params->{tables}; @@ -1726,10 +1773,10 @@ sub _process_tt { my $objects = $params->{objects} || {}; my $substitute = $params->{substitute} || {}; my $lang = $params->{lang} // 'en'; - my ($theme, $availablethemes); + my ( $theme, $availablethemes ); my $htdocs = C4::Context->config('intrahtdocs'); - ($theme, $lang, $availablethemes)= C4::Templates::availablethemes( $htdocs, 'about.tt', 'intranet', $lang); + ( $theme, $lang, $availablethemes ) = C4::Templates::availablethemes( $htdocs, 'about.tt', 'intranet', $lang ); my @includes; foreach (@$availablethemes) { push @includes, "$htdocs/$_/$lang/includes"; @@ -1742,7 +1789,7 @@ sub _process_tt { EVAL_PERL => 1, ABSOLUTE => 1, PLUGIN_BASE => 'Koha::Template::Plugin', - COMPILE_EXT => $use_template_cache ? '.ttc' : '', + COMPILE_EXT => $use_template_cache ? '.ttc' : '', COMPILE_DIR => $use_template_cache ? C4::Context->config('template_cache_dir') : '', INCLUDE_PATH => \@includes, FILTERS => {}, @@ -1750,9 +1797,10 @@ sub _process_tt { } ) or die Template->error(); - my $tt_params = { %{ _get_tt_params( $tables ) }, %{ _get_tt_params( $loops, 'is_a_loop' ) }, %$substitute, %$objects }; + my $tt_params = + { %{ _get_tt_params($tables) }, %{ _get_tt_params( $loops, 'is_a_loop' ) }, %$substitute, %$objects }; - $content = add_tt_filters( $content ); + $content = add_tt_filters($content); $content = qq|[% USE KohaDates %][% USE Remove_MARC_punctuation %]$content|; my $output; @@ -1760,8 +1808,7 @@ sub _process_tt { $schema->txn_begin; my $processed = try { $template->process( \$content, $tt_params, \$output ); - } - finally { + } finally { $schema->txn_rollback; }; croak "ERROR PROCESSING TEMPLATE: " . $template->error() unless $processed; @@ -1770,7 +1817,7 @@ sub _process_tt { } sub _get_tt_params { - my ($tables, $is_a_loop) = @_; + my ( $tables, $is_a_loop ) = @_; my $params; $is_a_loop ||= 0; @@ -1819,16 +1866,16 @@ sub _get_tt_params { pk => 'branchcode', }, credits => { - module => 'Koha::Account::Lines', + module => 'Koha::Account::Lines', singular => 'credit', - plural => 'credits', - pk => 'accountlines_id', + plural => 'credits', + pk => 'accountlines_id', }, debits => { - module => 'Koha::Account::Lines', + module => 'Koha::Account::Lines', singular => 'debit', - plural => 'debits', - pk => 'accountlines_id', + plural => 'debits', + pk => 'accountlines_id', }, items => { module => 'Koha::Items', @@ -1932,19 +1979,20 @@ sub _get_tt_params { foreach my $table ( keys %$tables ) { next unless $config->{$table}; - my $ref = ref( $tables->{$table} ) || q{}; + my $ref = ref( $tables->{$table} ) || q{}; my $module = $config->{$table}->{module}; if ( can_load( modules => { $module => undef } ) ) { my $pk = $config->{$table}->{pk}; my $fk = $config->{$table}->{fk}; - if ( $is_a_loop ) { + if ($is_a_loop) { my $values = $tables->{$table} || []; - unless ( ref( $values ) eq 'ARRAY' ) { + unless ( ref($values) eq 'ARRAY' ) { croak "ERROR processing table $table. Wrong API call."; } my $key = $pk ? $pk : $fk; + # $key does not come from user input my $objects = $module->search( { $key => $values }, @@ -1958,49 +2006,45 @@ sub _get_tt_params { ? ( order_by => \[ sprintf "field(%s, %s)", $key, - join(',', map { $dbh->quote($_) } @$values ) + join( ',', map { $dbh->quote($_) } @$values ) ] ) : () } ); $params->{ $config->{$table}->{plural} } = $objects; - } - elsif ( $ref eq q{} || $ref eq 'HASH' ) { + } elsif ( $ref eq q{} || $ref eq 'HASH' ) { my $id = ref $ref eq 'HASH' ? $tables->{$table}->{$pk} : $tables->{$table}; my $object; - if ( $fk ) { # Using a foreign key for lookup - if ( ref( $fk ) eq 'ARRAY' ) { # Foreign key is multi-column + if ($fk) { # Using a foreign key for lookup + if ( ref($fk) eq 'ARRAY' ) { # Foreign key is multi-column my $search; - foreach my $key ( @$fk ) { + foreach my $key (@$fk) { $search->{$key} = $id->{$key}; } - $object = $module->search( $search )->last(); - } else { # Foreign key is single column + $object = $module->search($search)->last(); + } else { # Foreign key is single column $object = $module->search( { $fk => $id } )->last(); } - } else { # using the table's primary key for lookup + } else { # using the table's primary key for lookup $object = $module->find($id); } $params->{ $config->{$table}->{singular} } = $object; - } - else { # $ref eq 'ARRAY' + } else { # $ref eq 'ARRAY' my $object; if ( @{ $tables->{$table} } == 1 ) { # Param is a single key $object = $module->search( { $pk => $tables->{$table} } )->last(); - } - else { # Params are mutliple foreign keys + } else { # Params are mutliple foreign keys croak "Multiple foreign keys (table $table) should be passed using an hashref"; } $params->{ $config->{$table}->{singular} } = $object; } - } - else { + } else { croak "ERROR LOADING MODULE $module: $Module::Load::Conditional::ERROR"; } } - $params->{today} = output_pref({ dt => dt_from_string, dateformat => 'iso' }); + $params->{today} = output_pref( { dt => dt_from_string, dateformat => 'iso' } ); return $params; } @@ -2016,7 +2060,7 @@ For now we only add the Remove_MARC_punctuation TT filter to biblio and biblioit =cut sub add_tt_filters { - my ( $content ) = @_; + my ($content) = @_; $content =~ s|\[%\s*biblio\.(.*?)\s*%\]|[% biblio.$1 \| \$Remove_MARC_punctuation %]|gxms; $content =~ s|\[%\s*biblioitem\.(.*?)\s*%\]|[% biblioitem.$1 \| \$Remove_MARC_punctuation %]|gxms; return $content; @@ -2037,21 +2081,18 @@ are formatted following the current setup. =cut sub get_item_content { - my ( $params ) = @_; - my $item = $params->{item}; - my $dateonly = $params->{dateonly} || 0; + my ($params) = @_; + my $item = $params->{item}; + my $dateonly = $params->{dateonly} || 0; my $item_content_fields = $params->{item_content_fields} || []; return unless $item; my @item_info = map { $_ =~ /^date|date$/ - ? eval { - output_pref( - { dt => dt_from_string( $item->{$_} ), dateonly => $dateonly } ); - } - : $item->{$_} - || '' + ? eval { output_pref( { dt => dt_from_string( $item->{$_} ), dateonly => $dateonly } ); } + : $item->{$_} + || '' } @$item_content_fields; return join( "\t", @item_info ) . "\n"; } diff --git a/C4/Linker.pm b/C4/Linker.pm index 0648ee3e03..1a1888ce17 100644 --- a/C4/Linker.pm +++ b/C4/Linker.pm @@ -62,20 +62,17 @@ sub new { while ( my ( $key, $value ) = each %$param ) { if ( $key eq 'auth_limit' && $value ) { my $dbh = C4::Context->dbh; - my $sql = - "SELECT authid FROM auth_header WHERE $value ORDER BY authid ASC"; + my $sql = "SELECT authid FROM auth_header WHERE $value ORDER BY authid ASC"; my $sth = $dbh->prepare($sql); $sth->execute(); while ( my ($authid) = $sth->fetchrow_array() ) { push @{ $self->{'auths_to_link'} }, $authid; } - } - elsif ( $key eq 'options' && $value ) { + } elsif ( $key eq 'options' && $value ) { foreach my $opt ( split( /\|/, $value ) ) { $self->{$opt} = 1; } - } - elsif ($value) { + } elsif ($value) { $self->{$key} = $value; } } @@ -96,8 +93,7 @@ sub _handle_auth_limit { my $self = shift; my $authid = shift; - if ( defined $self->{'auths_to_link'} && defined $authid && !grep { $_ == $authid } - @{ $self->{'auths_to_link'} } ) + if ( defined $self->{'auths_to_link'} && defined $authid && !grep { $_ == $authid } @{ $self->{'auths_to_link'} } ) { undef $authid; } diff --git a/C4/Linker/Default.pm b/C4/Linker/Default.pm index 9b3f225bce..63bde4855c 100644 --- a/C4/Linker/Default.pm +++ b/C4/Linker/Default.pm @@ -29,19 +29,18 @@ sub get_link { my $heading = shift; my $behavior = shift || 'default'; my $search_form = $heading->search_form(); - my $auth_type = $heading->auth_type(); + my $auth_type = $heading->auth_type(); my $thesaurus = $heading->{thesaurus} || 'notdefined'; $thesaurus = 'notconsidered' unless C4::Context->preference('LinkerConsiderThesaurus'); my $authid; my $fuzzy = 0; my $match_count; - if ( $self->{'cache'}->{$search_form.$auth_type.$thesaurus}->{'cached'} ) { - $authid = $self->{'cache'}->{$search_form.$auth_type.$thesaurus}->{'authid'}; - $fuzzy = $self->{'cache'}->{$search_form.$auth_type.$thesaurus}->{'fuzzy'}; - $match_count = $self->{'cache'}->{$search_form.$auth_type.$thesaurus}->{'match_count'}; - } - else { + if ( $self->{'cache'}->{ $search_form . $auth_type . $thesaurus }->{'cached'} ) { + $authid = $self->{'cache'}->{ $search_form . $auth_type . $thesaurus }->{'authid'}; + $fuzzy = $self->{'cache'}->{ $search_form . $auth_type . $thesaurus }->{'fuzzy'}; + $match_count = $self->{'cache'}->{ $search_form . $auth_type . $thesaurus }->{'match_count'}; + } else { # look for matching authorities my $authorities = $heading->authorities(1); # $skipmetadata = true @@ -49,12 +48,10 @@ sub get_link { if ( $behavior eq 'default' && $#{$authorities} == 0 ) { $authid = $authorities->[0]->{'authid'}; - } - elsif ( $behavior eq 'first' && $#{$authorities} >= 0 ) { + } elsif ( $behavior eq 'first' && $#{$authorities} >= 0 ) { $authid = $authorities->[0]->{'authid'}; $fuzzy = $#{$authorities} > 0; - } - elsif ( $behavior eq 'last' && $#{$authorities} >= 0 ) { + } elsif ( $behavior eq 'last' && $#{$authorities} >= 0 ) { $authid = $authorities->[ $#{$authorities} ]->{'authid'}; $fuzzy = $#{$authorities} > 0; } @@ -64,23 +61,23 @@ sub get_link { my @subfields = grep { $_->[0] ne '9' } $field->subfields(); if ( scalar @subfields > 1 ) { pop @subfields; - $field = - MARC::Field->new( - $field->tag, - $field->indicator(1), - $field->indicator(2), - map { $_->[0] => $_->[1] } @subfields - ); - ( $authid, $fuzzy ) = - $self->get_link( C4::Heading->new_from_field($field), - $behavior ); + $field = MARC::Field->new( + $field->tag, + $field->indicator(1), + $field->indicator(2), + map { $_->[0] => $_->[1] } @subfields + ); + ( $authid, $fuzzy ) = $self->get_link( + C4::Heading->new_from_field($field), + $behavior + ); } } - $self->{'cache'}->{$search_form.$auth_type.$thesaurus}->{'cached'} = 1; - $self->{'cache'}->{$search_form.$auth_type.$thesaurus}->{'authid'} = $authid; - $self->{'cache'}->{$search_form.$auth_type.$thesaurus}->{'fuzzy'} = $fuzzy; - $self->{'cache'}->{$search_form.$auth_type.$thesaurus}->{'match_count'} = $match_count; + $self->{'cache'}->{ $search_form . $auth_type . $thesaurus }->{'cached'} = 1; + $self->{'cache'}->{ $search_form . $auth_type . $thesaurus }->{'authid'} = $authid; + $self->{'cache'}->{ $search_form . $auth_type . $thesaurus }->{'fuzzy'} = $fuzzy; + $self->{'cache'}->{ $search_form . $auth_type . $thesaurus }->{'match_count'} = $match_count; } return $self->SUPER::_handle_auth_limit($authid), $fuzzy, $match_count; } @@ -90,14 +87,14 @@ sub update_cache { my $heading = shift; my $authid = shift; my $search_form = $heading->search_form(); - my $auth_type = $heading->auth_type(); + my $auth_type = $heading->auth_type(); my $thesaurus = $heading->{thesaurus} || 'notdefined'; $thesaurus = 'notconsidered' unless C4::Context->preference('LinkerConsiderThesaurus'); my $fuzzy = 0; - $self->{'cache'}->{$search_form.$auth_type.$thesaurus}->{'cached'} = 1; - $self->{'cache'}->{$search_form.$auth_type.$thesaurus}->{'authid'} = $authid; - $self->{'cache'}->{$search_form.$auth_type.$thesaurus}->{'fuzzy'} = $fuzzy; + $self->{'cache'}->{ $search_form . $auth_type . $thesaurus }->{'cached'} = 1; + $self->{'cache'}->{ $search_form . $auth_type . $thesaurus }->{'authid'} = $authid; + $self->{'cache'}->{ $search_form . $auth_type . $thesaurus }->{'fuzzy'} = $fuzzy; } sub flip_heading { diff --git a/C4/Linker/FirstMatch.pm b/C4/Linker/FirstMatch.pm index 873395a362..37d12f8d17 100644 --- a/C4/Linker/FirstMatch.pm +++ b/C4/Linker/FirstMatch.pm @@ -41,9 +41,9 @@ sub get_link { } sub update_cache { - my $self = shift; - my $heading = shift; - my $authid = shift; + my $self = shift; + my $heading = shift; + my $authid = shift; $self->{'default_linker'}->update_cache( $heading, $authid ); } diff --git a/C4/Linker/LastMatch.pm b/C4/Linker/LastMatch.pm index 1f873d8c5b..237bea05f8 100644 --- a/C4/Linker/LastMatch.pm +++ b/C4/Linker/LastMatch.pm @@ -41,9 +41,9 @@ sub get_link { } sub update_cache { - my $self = shift; - my $heading = shift; - my $authid = shift; + my $self = shift; + my $heading = shift; + my $authid = shift; $self->{'default_linker'}->update_cache( $heading, $authid ); } diff --git a/C4/MarcModificationTemplates.pm b/C4/MarcModificationTemplates.pm index 13b81ca0b4..9fa267362e 100644 --- a/C4/MarcModificationTemplates.pm +++ b/C4/MarcModificationTemplates.pm @@ -40,24 +40,23 @@ use vars qw(@ISA @EXPORT); BEGIN { @ISA = qw(Exporter); @EXPORT = qw( - GetModificationTemplates - AddModificationTemplate - DelModificationTemplate + GetModificationTemplates + AddModificationTemplate + DelModificationTemplate - GetModificationTemplateAction - GetModificationTemplateActions + GetModificationTemplateAction + GetModificationTemplateActions - AddModificationTemplateAction - ModModificationTemplateAction - DelModificationTemplateAction - MoveModificationTemplateAction + AddModificationTemplateAction + ModModificationTemplateAction + DelModificationTemplateAction + MoveModificationTemplateAction - ModifyRecordsWithTemplate - ModifyRecordWithTemplate + ModifyRecordsWithTemplate + ModifyRecordWithTemplate ); } - =head1 NAME C4::MarcModificationTemplates - Module to manage MARC Modification Templates @@ -81,20 +80,20 @@ files telling Koha what fields to insert data into. =cut sub GetModificationTemplates { - my ( $template_id ) = @_; + my ($template_id) = @_; - my $dbh = C4::Context->dbh; - my $sth = $dbh->prepare("SELECT * FROM marc_modification_templates ORDER BY name"); - $sth->execute(); + my $dbh = C4::Context->dbh; + my $sth = $dbh->prepare("SELECT * FROM marc_modification_templates ORDER BY name"); + $sth->execute(); - my @templates; - while ( my $template = $sth->fetchrow_hashref() ) { - $template->{'selected'} = 1 - if $template_id && $template->{'template_id'} eq $template_id; - push( @templates, $template ); - } + my @templates; + while ( my $template = $sth->fetchrow_hashref() ) { + $template->{'selected'} = 1 + if $template_id && $template->{'template_id'} eq $template_id; + push( @templates, $template ); + } - return @templates; + return @templates; } =head2 @@ -107,45 +106,45 @@ sub GetModificationTemplates { =cut sub AddModificationTemplate { - my ( $template_name, $template_id_copy ) = @_; + my ( $template_name, $template_id_copy ) = @_; - my $dbh = C4::Context->dbh; - my $sth = $dbh->prepare("INSERT INTO marc_modification_templates ( name ) VALUES ( ? )"); - $sth->execute( $template_name ); + my $dbh = C4::Context->dbh; + my $sth = $dbh->prepare("INSERT INTO marc_modification_templates ( name ) VALUES ( ? )"); + $sth->execute($template_name); - $sth = $dbh->prepare("SELECT * FROM marc_modification_templates WHERE name = ?"); - $sth->execute( $template_name ); - my $row = $sth->fetchrow_hashref(); - my $template_id = $row->{'template_id'}; + $sth = $dbh->prepare("SELECT * FROM marc_modification_templates WHERE name = ?"); + $sth->execute($template_name); + my $row = $sth->fetchrow_hashref(); + my $template_id = $row->{'template_id'}; - if ( $template_id_copy ) { - my @actions = GetModificationTemplateActions( $template_id_copy ); - foreach my $action ( @actions ) { - AddModificationTemplateAction( - $template_id, - $action->{'action'}, - $action->{'field_number'}, - $action->{'from_field'}, - $action->{'from_subfield'}, - $action->{'field_value'}, - $action->{'to_field'}, - $action->{'to_subfield'}, - $action->{'to_regex_search'}, - $action->{'to_regex_replace'}, - $action->{'to_regex_modifiers'}, - $action->{'conditional'}, - $action->{'conditional_field'}, - $action->{'conditional_subfield'}, - $action->{'conditional_comparison'}, - $action->{'conditional_value'}, - $action->{'conditional_regex'}, - $action->{'description'}, - ); + if ($template_id_copy) { + my @actions = GetModificationTemplateActions($template_id_copy); + foreach my $action (@actions) { + AddModificationTemplateAction( + $template_id, + $action->{'action'}, + $action->{'field_number'}, + $action->{'from_field'}, + $action->{'from_subfield'}, + $action->{'field_value'}, + $action->{'to_field'}, + $action->{'to_subfield'}, + $action->{'to_regex_search'}, + $action->{'to_regex_replace'}, + $action->{'to_regex_modifiers'}, + $action->{'conditional'}, + $action->{'conditional_field'}, + $action->{'conditional_subfield'}, + $action->{'conditional_comparison'}, + $action->{'conditional_value'}, + $action->{'conditional_regex'}, + $action->{'description'}, + ); + } } - } - return $template_id; + return $template_id; } =head2 @@ -155,11 +154,11 @@ sub AddModificationTemplate { =cut sub DelModificationTemplate { - my ( $template_id ) = @_; + my ($template_id) = @_; - my $dbh = C4::Context->dbh; - my $sth = $dbh->prepare("DELETE FROM marc_modification_templates WHERE template_id = ?"); - $sth->execute( $template_id ); + my $dbh = C4::Context->dbh; + my $sth = $dbh->prepare("DELETE FROM marc_modification_templates WHERE template_id = ?"); + $sth->execute($template_id); } =head2 @@ -169,14 +168,14 @@ sub DelModificationTemplate { =cut sub GetModificationTemplateAction { - my ( $mmta_id ) = @_; + my ($mmta_id) = @_; - my $dbh = C4::Context->dbh; - my $sth = $dbh->prepare("SELECT * FROM marc_modification_template_actions WHERE mmta_id = ?"); - $sth->execute( $mmta_id ); - my $action = $sth->fetchrow_hashref(); + my $dbh = C4::Context->dbh; + my $sth = $dbh->prepare("SELECT * FROM marc_modification_template_actions WHERE mmta_id = ?"); + $sth->execute($mmta_id); + my $action = $sth->fetchrow_hashref(); - return $action; + return $action; } =head2 @@ -186,18 +185,18 @@ sub GetModificationTemplateAction { =cut sub GetModificationTemplateActions { - my ( $template_id ) = @_; + my ($template_id) = @_; - my $dbh = C4::Context->dbh; - my $sth = $dbh->prepare("SELECT * FROM marc_modification_template_actions WHERE template_id = ? ORDER BY ordering"); - $sth->execute( $template_id ); + my $dbh = C4::Context->dbh; + my $sth = $dbh->prepare("SELECT * FROM marc_modification_template_actions WHERE template_id = ? ORDER BY ordering"); + $sth->execute($template_id); - my @actions; - while ( my $action = $sth->fetchrow_hashref() ) { - push( @actions, $action ); - } + my @actions; + while ( my $action = $sth->fetchrow_hashref() ) { + push( @actions, $action ); + } - return @actions; + return @actions; } =head2 @@ -217,38 +216,39 @@ sub GetModificationTemplateActions { =cut sub AddModificationTemplateAction { - my ( - $template_id, - $action, - $field_number, - $from_field, - $from_subfield, - $field_value, - $to_field, - $to_subfield, - $to_regex_search, - $to_regex_replace, - $to_regex_modifiers, - $conditional, - $conditional_field, - $conditional_subfield, - $conditional_comparison, - $conditional_value, - $conditional_regex, - $description - ) = @_; + my ( + $template_id, + $action, + $field_number, + $from_field, + $from_subfield, + $field_value, + $to_field, + $to_subfield, + $to_regex_search, + $to_regex_replace, + $to_regex_modifiers, + $conditional, + $conditional_field, + $conditional_subfield, + $conditional_comparison, + $conditional_value, + $conditional_regex, + $description + ) = @_; - $conditional ||= undef; - $conditional_comparison ||= undef; - $conditional_regex ||= '0'; + $conditional ||= undef; + $conditional_comparison ||= undef; + $conditional_regex ||= '0'; - my $dbh = C4::Context->dbh; - my $sth = $dbh->prepare( 'SELECT MAX(ordering) + 1 AS next_ordering FROM marc_modification_template_actions WHERE template_id = ?' ); - $sth->execute( $template_id ); - my $row = $sth->fetchrow_hashref; - my $ordering = $row->{'next_ordering'} || 1; + my $dbh = C4::Context->dbh; + my $sth = $dbh->prepare( + 'SELECT MAX(ordering) + 1 AS next_ordering FROM marc_modification_template_actions WHERE template_id = ?'); + $sth->execute($template_id); + my $row = $sth->fetchrow_hashref; + my $ordering = $row->{'next_ordering'} || 1; - my $query = " + my $query = " INSERT INTO marc_modification_template_actions ( mmta_id, template_id, @@ -273,29 +273,29 @@ sub AddModificationTemplateAction { ) VALUES ( NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"; - $sth = $dbh->prepare( $query ); + $sth = $dbh->prepare($query); - $sth->execute( - $template_id, - $ordering, - $action, - $field_number, - $from_field, - $from_subfield, - $field_value, - $to_field, - $to_subfield, - $to_regex_search, - $to_regex_replace, - $to_regex_modifiers, - $conditional, - $conditional_field, - $conditional_subfield, - $conditional_comparison, - $conditional_value, - $conditional_regex, - $description - ); + $sth->execute( + $template_id, + $ordering, + $action, + $field_number, + $from_field, + $from_subfield, + $field_value, + $to_field, + $to_subfield, + $to_regex_search, + $to_regex_replace, + $to_regex_modifiers, + $conditional, + $conditional_field, + $conditional_subfield, + $conditional_comparison, + $conditional_value, + $conditional_regex, + $description + ); } =head2 @@ -315,33 +315,33 @@ sub AddModificationTemplateAction { =cut sub ModModificationTemplateAction { - my ( - $mmta_id, - $action, - $field_number, - $from_field, - $from_subfield, - $field_value, - $to_field, - $to_subfield, - $to_regex_search, - $to_regex_replace, - $to_regex_modifiers, - $conditional, - $conditional_field, - $conditional_subfield, - $conditional_comparison, - $conditional_value, - $conditional_regex, - $description - ) = @_; + my ( + $mmta_id, + $action, + $field_number, + $from_field, + $from_subfield, + $field_value, + $to_field, + $to_subfield, + $to_regex_search, + $to_regex_replace, + $to_regex_modifiers, + $conditional, + $conditional_field, + $conditional_subfield, + $conditional_comparison, + $conditional_value, + $conditional_regex, + $description + ) = @_; - my $dbh = C4::Context->dbh; - $conditional ||= undef; - $conditional_comparison ||= undef; - $conditional_regex ||= '0'; + my $dbh = C4::Context->dbh; + $conditional ||= undef; + $conditional_comparison ||= undef; + $conditional_regex ||= '0'; - my $query = " + my $query = " UPDATE marc_modification_template_actions SET action = ?, field_number = ?, @@ -362,31 +362,30 @@ sub ModModificationTemplateAction { description = ? WHERE mmta_id = ?"; - my $sth = $dbh->prepare( $query ); + my $sth = $dbh->prepare($query); - $sth->execute( - $action, - $field_number, - $from_field, - $from_subfield, - $field_value, - $to_field, - $to_subfield, - $to_regex_search, - $to_regex_replace, - $to_regex_modifiers, - $conditional, - $conditional_field, - $conditional_subfield, - $conditional_comparison, - $conditional_value, - $conditional_regex, - $description, - $mmta_id - ); + $sth->execute( + $action, + $field_number, + $from_field, + $from_subfield, + $field_value, + $to_field, + $to_subfield, + $to_regex_search, + $to_regex_replace, + $to_regex_modifiers, + $conditional, + $conditional_field, + $conditional_subfield, + $conditional_comparison, + $conditional_value, + $conditional_regex, + $description, + $mmta_id + ); } - =head2 DelModificationTemplateAction @@ -396,16 +395,17 @@ sub ModModificationTemplateAction { =cut sub DelModificationTemplateAction { - my ( $mmta_id ) = @_; + my ($mmta_id) = @_; - my $action = GetModificationTemplateAction( $mmta_id ); + my $action = GetModificationTemplateAction($mmta_id); - my $dbh = C4::Context->dbh; - my $sth = $dbh->prepare("DELETE FROM marc_modification_template_actions WHERE mmta_id = ?"); - $sth->execute( $mmta_id ); + my $dbh = C4::Context->dbh; + my $sth = $dbh->prepare("DELETE FROM marc_modification_template_actions WHERE mmta_id = ?"); + $sth->execute($mmta_id); - $sth = $dbh->prepare("UPDATE marc_modification_template_actions SET ordering = ordering - 1 WHERE template_id = ? AND ordering > ?"); - $sth->execute( $action->{'template_id'}, $action->{'ordering'} ); + $sth = $dbh->prepare( + "UPDATE marc_modification_template_actions SET ordering = ordering - 1 WHERE template_id = ? AND ordering > ?"); + $sth->execute( $action->{'template_id'}, $action->{'ordering'} ); } =head2 @@ -416,55 +416,62 @@ sub DelModificationTemplateAction { Changes the order for the given action. Options for $where are 'up', 'down', 'top' and 'bottom' =cut + sub MoveModificationTemplateAction { - my ( $mmta_id, $where ) = @_; + my ( $mmta_id, $where ) = @_; - my $action = GetModificationTemplateAction( $mmta_id ); + my $action = GetModificationTemplateAction($mmta_id); - return if ( $action->{'ordering'} eq '1' && ( $where eq 'up' || $where eq 'top' ) ); - return if ( $action->{'ordering'} eq GetModificationTemplateActions( $action->{'template_id'} ) && ( $where eq 'down' || $where eq 'bottom' ) ); + return if ( $action->{'ordering'} eq '1' && ( $where eq 'up' || $where eq 'top' ) ); + return + if ( $action->{'ordering'} eq GetModificationTemplateActions( $action->{'template_id'} ) + && ( $where eq 'down' || $where eq 'bottom' ) ); - my $dbh = C4::Context->dbh; - my ( $sth, $query ); + my $dbh = C4::Context->dbh; + my ( $sth, $query ); - if ( $where eq 'up' || $where eq 'down' ) { + if ( $where eq 'up' || $where eq 'down' ) { - ## For up and down, we just swap the ordering number with the one above or below it. + ## For up and down, we just swap the ordering number with the one above or below it. - ## Change the ordering for the other action - $query = "UPDATE marc_modification_template_actions SET ordering = ? WHERE template_id = ? AND ordering = ?"; + ## Change the ordering for the other action + $query = "UPDATE marc_modification_template_actions SET ordering = ? WHERE template_id = ? AND ordering = ?"; - my $ordering = $action->{'ordering'}; - $ordering-- if ( $where eq 'up' ); - $ordering++ if ( $where eq 'down' ); + my $ordering = $action->{'ordering'}; + $ordering-- if ( $where eq 'up' ); + $ordering++ if ( $where eq 'down' ); - $sth = $dbh->prepare( $query ); - $sth->execute( $action->{'ordering'}, $action->{'template_id'}, $ordering ); + $sth = $dbh->prepare($query); + $sth->execute( $action->{'ordering'}, $action->{'template_id'}, $ordering ); - ## Change the ordering for this action - $query = "UPDATE marc_modification_template_actions SET ordering = ? WHERE mmta_id = ?"; - $sth = $dbh->prepare( $query ); - $sth->execute( $ordering, $action->{'mmta_id'} ); + ## Change the ordering for this action + $query = "UPDATE marc_modification_template_actions SET ordering = ? WHERE mmta_id = ?"; + $sth = $dbh->prepare($query); + $sth->execute( $ordering, $action->{'mmta_id'} ); - } elsif ( $where eq 'top' ) { + } elsif ( $where eq 'top' ) { - $sth = $dbh->prepare('UPDATE marc_modification_template_actions SET ordering = ordering + 1 WHERE template_id = ? AND ordering < ?'); - $sth->execute( $action->{'template_id'}, $action->{'ordering'} ); + $sth = $dbh->prepare( + 'UPDATE marc_modification_template_actions SET ordering = ordering + 1 WHERE template_id = ? AND ordering < ?' + ); + $sth->execute( $action->{'template_id'}, $action->{'ordering'} ); - $sth = $dbh->prepare('UPDATE marc_modification_template_actions SET ordering = 1 WHERE mmta_id = ?'); - $sth->execute( $mmta_id ); + $sth = $dbh->prepare('UPDATE marc_modification_template_actions SET ordering = 1 WHERE mmta_id = ?'); + $sth->execute($mmta_id); - } elsif ( $where eq 'bottom' ) { + } elsif ( $where eq 'bottom' ) { - my $ordering = GetModificationTemplateActions( $action->{'template_id'} ); + my $ordering = GetModificationTemplateActions( $action->{'template_id'} ); - $sth = $dbh->prepare('UPDATE marc_modification_template_actions SET ordering = ordering - 1 WHERE template_id = ? AND ordering > ?'); - $sth->execute( $action->{'template_id'}, $action->{'ordering'} ); + $sth = $dbh->prepare( + 'UPDATE marc_modification_template_actions SET ordering = ordering - 1 WHERE template_id = ? AND ordering > ?' + ); + $sth->execute( $action->{'template_id'}, $action->{'ordering'} ); - $sth = $dbh->prepare('UPDATE marc_modification_template_actions SET ordering = ? WHERE mmta_id = ?'); - $sth->execute( $ordering, $mmta_id ); + $sth = $dbh->prepare('UPDATE marc_modification_template_actions SET ordering = ? WHERE mmta_id = ?'); + $sth->execute( $ordering, $mmta_id ); - } + } } @@ -477,11 +484,11 @@ sub MoveModificationTemplateAction { =cut sub ModifyRecordsWithTemplate { - my ( $template_id, $batch ) = @_; + my ( $template_id, $batch ) = @_; - while ( my $record = $batch->next() ) { - ModifyRecordWithTemplate( $template_id, $record ); - } + while ( my $record = $batch->next() ) { + ModifyRecordWithTemplate( $template_id, $record ); + } } =head2 @@ -497,77 +504,85 @@ sub ModifyRecordWithTemplate { my ( $template_id, $record ) = @_; my $current_date = dt_from_string()->ymd(); - my $branchcode = ''; + my $branchcode = ''; $branchcode = C4::Context->userenv->{branch} if C4::Context->userenv; - my @actions = GetModificationTemplateActions( $template_id ); + my @actions = GetModificationTemplateActions($template_id); - foreach my $a ( @actions ) { - my $action = $a->{'action'}; - my $field_number = $a->{'field_number'} // 1; - my $from_field = $a->{'from_field'}; - my $from_subfield = $a->{'from_subfield'}; - my $field_value = $a->{'field_value'}; - my $to_field = $a->{'to_field'}; - my $to_subfield = $a->{'to_subfield'}; - my $to_regex_search = $a->{'to_regex_search'}; - my $to_regex_replace = $a->{'to_regex_replace'}; - my $to_regex_modifiers = $a->{'to_regex_modifiers'}; - my $conditional = $a->{'conditional'}; - my $conditional_field = $a->{'conditional_field'}; - my $conditional_subfield = $a->{'conditional_subfield'}; + foreach my $a (@actions) { + my $action = $a->{'action'}; + my $field_number = $a->{'field_number'} // 1; + my $from_field = $a->{'from_field'}; + my $from_subfield = $a->{'from_subfield'}; + my $field_value = $a->{'field_value'}; + my $to_field = $a->{'to_field'}; + my $to_subfield = $a->{'to_subfield'}; + my $to_regex_search = $a->{'to_regex_search'}; + my $to_regex_replace = $a->{'to_regex_replace'}; + my $to_regex_modifiers = $a->{'to_regex_modifiers'}; + my $conditional = $a->{'conditional'}; + my $conditional_field = $a->{'conditional_field'}; + my $conditional_subfield = $a->{'conditional_subfield'}; my $conditional_comparison = $a->{'conditional_comparison'}; - my $conditional_value = $a->{'conditional_value'}; - my $conditional_regex = $a->{'conditional_regex'}; + my $conditional_value = $a->{'conditional_value'}; + my $conditional_regex = $a->{'conditional_regex'}; - if ( $field_value ) { + if ($field_value) { $field_value =~ s/__CURRENTDATE__/$current_date/g; $field_value =~ s/__BRANCHCODE__/$branchcode/g; } - my $do = 1; + my $do = 1; my $field_numbers = []; - if ( $conditional ) { + if ($conditional) { if ( $conditional_comparison eq 'exists' ) { - $field_numbers = field_exists({ - record => $record, - field => $conditional_field, + $field_numbers = field_exists( + { + record => $record, + field => $conditional_field, subfield => $conditional_subfield, - }); - $do = $conditional eq 'if' + } + ); + $do = + $conditional eq 'if' ? @$field_numbers : not @$field_numbers; - } - elsif ( $conditional_comparison eq 'not_exists' ) { - $field_numbers = field_exists({ - record => $record, - field => $conditional_field, + } elsif ( $conditional_comparison eq 'not_exists' ) { + $field_numbers = field_exists( + { + record => $record, + field => $conditional_field, subfield => $conditional_subfield - }); - $do = $conditional eq 'if' + } + ); + $do = + $conditional eq 'if' ? not @$field_numbers : @$field_numbers; - } - elsif ( $conditional_comparison eq 'equals' ) { - $field_numbers = field_equals({ - record => $record, - value => $conditional_value, - field => $conditional_field, - subfield => $conditional_subfield, - is_regex => $conditional_regex, - }); - $do = $conditional eq 'if' + } elsif ( $conditional_comparison eq 'equals' ) { + $field_numbers = field_equals( + { + record => $record, + value => $conditional_value, + field => $conditional_field, + subfield => $conditional_subfield, + is_regex => $conditional_regex, + } + ); + $do = + $conditional eq 'if' ? @$field_numbers : not @$field_numbers; - } - elsif ( $conditional_comparison eq 'not_equals' ) { - $field_numbers = field_equals({ - record => $record, - value => $conditional_value, - field => $conditional_field, - subfield => $conditional_subfield, - is_regex => $conditional_regex, - }); + } elsif ( $conditional_comparison eq 'not_equals' ) { + $field_numbers = field_equals( + { + record => $record, + value => $conditional_value, + field => $conditional_field, + subfield => $conditional_subfield, + is_regex => $conditional_regex, + } + ); my $all_fields = [ 1 .. scalar @{ field_exists( @@ -579,20 +594,22 @@ sub ModifyRecordWithTemplate { ) } ]; - $field_numbers = [Koha::MoreUtils::singleton ( @$field_numbers, @$all_fields ) ]; - if ( $from_field == $conditional_field ){ - $do = $conditional eq 'if' + $field_numbers = [ Koha::MoreUtils::singleton( @$field_numbers, @$all_fields ) ]; + if ( $from_field == $conditional_field ) { + $do = + $conditional eq 'if' ? @$field_numbers : not @$field_numbers; } else { - $do = $conditional eq 'if' + $do = + $conditional eq 'if' ? not @$field_numbers : @$field_numbers; } } } - if ( $do ) { + if ($do) { # field_number == 0 if all field need to be updated # or 1 if only the first field need to be updated @@ -600,103 +617,118 @@ sub ModifyRecordWithTemplate { # A condition has been given if ( @$field_numbers > 0 ) { if ( $field_number == 1 ) { + # We want only the first - if ( $from_field == $conditional_field ){ + if ( $from_field == $conditional_field ) { + # want first field matching condition $field_numbers = [ $field_numbers->[0] ]; } else { + # condition doesn't match, so just want first occurrence of from field - $field_numbers = [ 1 ]; + $field_numbers = [1]; } } else { - unless ( $from_field == $conditional_field ){ + unless ( $from_field == $conditional_field ) { + # condition doesn't match from fields so need all occurrences of from fields for action - $field_numbers = field_exists({ - record => $record, - field => $from_field, - subfield => $from_subfield, - }); + $field_numbers = field_exists( + { + record => $record, + field => $from_field, + subfield => $from_subfield, + } + ); } } } + # There was no condition else { if ( $field_number == 1 ) { + # We want to process the first field - $field_numbers = [ 1 ]; + $field_numbers = [1]; } } if ( $action eq 'copy_field' ) { - copy_field({ - record => $record, - from_field => $from_field, - from_subfield => $from_subfield, - to_field => $to_field, - to_subfield => $to_subfield, - regex => { - search => $to_regex_search, - replace => $to_regex_replace, - modifiers => $to_regex_modifiers - }, - field_numbers => $field_numbers, - }); - } - elsif ( $action eq 'copy_and_replace_field' ) { - copy_and_replace_field({ - record => $record, - from_field => $from_field, - from_subfield => $from_subfield, - to_field => $to_field, - to_subfield => $to_subfield, - regex => { - search => $to_regex_search, - replace => $to_regex_replace, - modifiers => $to_regex_modifiers - }, - field_numbers => $field_numbers, - }); - } - elsif ( $action eq 'add_field' ) { - add_field({ - record => $record, - field => $from_field, - subfield => $from_subfield, - values => [ $field_value ], - field_numbers => $field_numbers, - }); - } - elsif ( $action eq 'update_field' ) { - update_field({ - record => $record, - field => $from_field, - subfield => $from_subfield, - values => [ $field_value ], - field_numbers => $field_numbers, - }); - } - elsif ( $action eq 'move_field' ) { - move_field({ - record => $record, - from_field => $from_field, - from_subfield => $from_subfield, - to_field => $to_field, - to_subfield => $to_subfield, - regex => { - search => $to_regex_search, - replace => $to_regex_replace, - modifiers => $to_regex_modifiers - }, - field_numbers => $field_numbers, - }); - } - elsif ( $action eq 'delete_field' ) { - delete_field({ - record => $record, - field => $from_field, - subfield => $from_subfield, - field_numbers => $field_numbers, - }); + copy_field( + { + record => $record, + from_field => $from_field, + from_subfield => $from_subfield, + to_field => $to_field, + to_subfield => $to_subfield, + regex => { + search => $to_regex_search, + replace => $to_regex_replace, + modifiers => $to_regex_modifiers + }, + field_numbers => $field_numbers, + } + ); + } elsif ( $action eq 'copy_and_replace_field' ) { + copy_and_replace_field( + { + record => $record, + from_field => $from_field, + from_subfield => $from_subfield, + to_field => $to_field, + to_subfield => $to_subfield, + regex => { + search => $to_regex_search, + replace => $to_regex_replace, + modifiers => $to_regex_modifiers + }, + field_numbers => $field_numbers, + } + ); + } elsif ( $action eq 'add_field' ) { + add_field( + { + record => $record, + field => $from_field, + subfield => $from_subfield, + values => [$field_value], + field_numbers => $field_numbers, + } + ); + } elsif ( $action eq 'update_field' ) { + update_field( + { + record => $record, + field => $from_field, + subfield => $from_subfield, + values => [$field_value], + field_numbers => $field_numbers, + } + ); + } elsif ( $action eq 'move_field' ) { + move_field( + { + record => $record, + from_field => $from_field, + from_subfield => $from_subfield, + to_field => $to_field, + to_subfield => $to_subfield, + regex => { + search => $to_regex_search, + replace => $to_regex_replace, + modifiers => $to_regex_modifiers + }, + field_numbers => $field_numbers, + } + ); + } elsif ( $action eq 'delete_field' ) { + delete_field( + { + record => $record, + field => $from_field, + subfield => $from_subfield, + field_numbers => $field_numbers, + } + ); } } } diff --git a/C4/Matcher.pm b/C4/Matcher.pm index fbfcc1cb40..2bb6418cb4 100644 --- a/C4/Matcher.pm +++ b/C4/Matcher.pm @@ -19,7 +19,6 @@ package C4::Matcher; use Modern::Perl; - use Koha::SearchEngine; use Koha::SearchEngine::Search; use Koha::SearchEngine::QueryBuilder; @@ -84,13 +83,13 @@ present in the database. Each hashref includes: sub GetMatcherList { my $dbh = C4::Context->dbh; - + my $sth = $dbh->prepare_cached("SELECT matcher_id, code, description FROM marc_matchers ORDER BY matcher_id"); $sth->execute(); my @results = (); - while (my $row = $sth->fetchrow_hashref) { + while ( my $row = $sth->fetchrow_hashref ) { push @results, $row; - } + } return @results; } @@ -106,7 +105,7 @@ sub GetMatcherId { my ($code) = @_; my $dbh = C4::Context->dbh; - my $matcher_id = $dbh->selectrow_array("SELECT matcher_id FROM marc_matchers WHERE code = ?", undef, $code); + my $matcher_id = $dbh->selectrow_array( "SELECT matcher_id FROM marc_matchers WHERE code = ?", undef, $code ); return $matcher_id; } @@ -125,26 +124,26 @@ and defaults to 1000. sub new { my $class = shift; - my $self = {}; + my $self = {}; $self->{'id'} = undef; - if ($#_ > -1) { + if ( $#_ > -1 ) { $self->{'record_type'} = shift; } else { $self->{'record_type'} = 'biblio'; } - if ($#_ > -1) { + if ( $#_ > -1 ) { $self->{'threshold'} = shift; } else { $self->{'threshold'} = 1000; } - $self->{'code'} = ''; + $self->{'code'} = ''; $self->{'description'} = ''; - $self->{'matchpoints'} = []; + $self->{'matchpoints'} = []; $self->{'required_checks'} = []; bless $self, $class; @@ -163,8 +162,8 @@ id does not exist, returns undef. sub fetch { my $class = shift; - my $id = shift; - my $dbh = C4::Context->dbh(); + my $id = shift; + my $dbh = C4::Context->dbh(); my $sth = $dbh->prepare_cached("SELECT * FROM marc_matchers WHERE matcher_id = ?"); $sth->execute($id); @@ -173,30 +172,30 @@ sub fetch { return unless defined $row; my $self = {}; - $self->{'id'} = $row->{'matcher_id'}; + $self->{'id'} = $row->{'matcher_id'}; $self->{'record_type'} = $row->{'record_type'}; - $self->{'code'} = $row->{'code'}; + $self->{'code'} = $row->{'code'}; $self->{'description'} = $row->{'description'}; - $self->{'threshold'} = int($row->{'threshold'}); + $self->{'threshold'} = int( $row->{'threshold'} ); bless $self, $class; # matchpoints $self->{'matchpoints'} = []; $sth = $dbh->prepare_cached("SELECT * FROM matcher_matchpoints WHERE matcher_id = ? ORDER BY matchpoint_id"); - $sth->execute($self->{'id'}); - while (my $row = $sth->fetchrow_hashref) { - my $matchpoint = $self->_fetch_matchpoint($row->{'matchpoint_id'}); + $sth->execute( $self->{'id'} ); + while ( my $row = $sth->fetchrow_hashref ) { + my $matchpoint = $self->_fetch_matchpoint( $row->{'matchpoint_id'} ); push @{ $self->{'matchpoints'} }, $matchpoint; } # required checks $self->{'required_checks'} = []; $sth = $dbh->prepare_cached("SELECT * FROM matchchecks WHERE matcher_id = ? ORDER BY matchcheck_id"); - $sth->execute($self->{'id'}); - while (my $row = $sth->fetchrow_hashref) { - my $source_matchpoint = $self->_fetch_matchpoint($row->{'source_matchpoint_id'}); - my $target_matchpoint = $self->_fetch_matchpoint($row->{'target_matchpoint_id'}); - my $matchcheck = {}; + $sth->execute( $self->{'id'} ); + while ( my $row = $sth->fetchrow_hashref ) { + my $source_matchpoint = $self->_fetch_matchpoint( $row->{'source_matchpoint_id'} ); + my $target_matchpoint = $self->_fetch_matchpoint( $row->{'target_matchpoint_id'} ); + my $matchcheck = {}; $matchcheck->{'source_matchpoint'} = $source_matchpoint; $matchcheck->{'target_matchpoint'} = $target_matchpoint; push @{ $self->{'required_checks'} }, $matchcheck; @@ -206,33 +205,36 @@ sub fetch { } sub _fetch_matchpoint { - my $self = shift; + my $self = shift; my $matchpoint_id = shift; - + my $dbh = C4::Context->dbh; my $sth = $dbh->prepare_cached("SELECT * FROM matchpoints WHERE matchpoint_id = ?"); $sth->execute($matchpoint_id); - my $row = $sth->fetchrow_hashref; + my $row = $sth->fetchrow_hashref; my $matchpoint = {}; $matchpoint->{'index'} = $row->{'search_index'}; - $matchpoint->{'score'} = int($row->{'score'}); + $matchpoint->{'score'} = int( $row->{'score'} ); $sth->finish(); $matchpoint->{'components'} = []; $sth = $dbh->prepare_cached("SELECT * FROM matchpoint_components WHERE matchpoint_id = ? ORDER BY sequence"); $sth->execute($matchpoint_id); - while ($row = $sth->fetchrow_hashref) { + while ( $row = $sth->fetchrow_hashref ) { my $component = {}; - $component->{'tag'} = $row->{'tag'}; - $component->{'subfields'} = { map { $_ => 1 } split(//, $row->{'subfields'}) }; - $component->{'offset'} = int($row->{'offset'}); - $component->{'length'} = int($row->{'length'}); - $component->{'norms'} = []; - my $sth2 = $dbh->prepare_cached("SELECT * + $component->{'tag'} = $row->{'tag'}; + $component->{'subfields'} = { map { $_ => 1 } split( //, $row->{'subfields'} ) }; + $component->{'offset'} = int( $row->{'offset'} ); + $component->{'length'} = int( $row->{'length'} ); + $component->{'norms'} = []; + my $sth2 = $dbh->prepare_cached( + "SELECT * FROM matchpoint_component_norms - WHERE matchpoint_component_id = ? ORDER BY sequence"); - $sth2->execute($row->{'matchpoint_component_id'}); - while (my $row2 = $sth2->fetchrow_hashref) { + WHERE matchpoint_component_id = ? ORDER BY sequence" + ); + $sth2->execute( $row->{'matchpoint_component_id'} ); + + while ( my $row2 = $sth2->fetchrow_hashref ) { push @{ $component->{'norms'} }, $row2->{'norm_routine'}; } push @{ $matchpoint->{'components'} }, $component; @@ -255,11 +257,13 @@ is replaced. sub store { my $self = shift; - if (defined $self->{'id'}) { + if ( defined $self->{'id'} ) { + # update $self->_del_matcher_components(); $self->_update_marc_matchers(); } else { + # create new $self->_new_marc_matchers(); } @@ -272,9 +276,10 @@ sub _del_matcher_components { my $dbh = C4::Context->dbh(); my $sth = $dbh->prepare_cached("DELETE FROM matchpoints WHERE matcher_id = ?"); - $sth->execute($self->{'id'}); + $sth->execute( $self->{'id'} ); $sth = $dbh->prepare_cached("DELETE FROM matchchecks WHERE matcher_id = ?"); - $sth->execute($self->{'id'}); + $sth->execute( $self->{'id'} ); + # foreign key delete cascades take care of deleting relevant rows # from matcher_matchpoints, matchpoint_components, and # matchpoint_component_norms @@ -284,23 +289,30 @@ sub _update_marc_matchers { my $self = shift; my $dbh = C4::Context->dbh(); - my $sth = $dbh->prepare_cached("UPDATE marc_matchers + my $sth = $dbh->prepare_cached( + "UPDATE marc_matchers SET code = ?, description = ?, record_type = ?, threshold = ? - WHERE matcher_id = ?"); - $sth->execute($self->{'code'}, $self->{'description'}, $self->{'record_type'}, $self->{'threshold'}, $self->{'id'}); + WHERE matcher_id = ?" + ); + $sth->execute( + $self->{'code'}, $self->{'description'}, $self->{'record_type'}, $self->{'threshold'}, + $self->{'id'} + ); } sub _new_marc_matchers { my $self = shift; my $dbh = C4::Context->dbh(); - my $sth = $dbh->prepare_cached("INSERT INTO marc_matchers + my $sth = $dbh->prepare_cached( + "INSERT INTO marc_matchers (code, description, record_type, threshold) - VALUES (?, ?, ?, ?)"); - $sth->execute($self->{'code'}, $self->{'description'}, $self->{'record_type'}, $self->{'threshold'}); + VALUES (?, ?, ?, ?)" + ); + $sth->execute( $self->{'code'}, $self->{'description'}, $self->{'record_type'}, $self->{'threshold'} ); $self->{'id'} = $dbh->{'mysql_insertid'}; } @@ -310,61 +322,72 @@ sub _store_matcher_components { my $dbh = C4::Context->dbh(); my $sth; my $matcher_id = $self->{'id'}; - foreach my $matchpoint (@{ $self->{'matchpoints'}}) { + foreach my $matchpoint ( @{ $self->{'matchpoints'} } ) { my $matchpoint_id = $self->_store_matchpoint($matchpoint); - $sth = $dbh->prepare_cached("INSERT INTO matcher_matchpoints (matcher_id, matchpoint_id) - VALUES (?, ?)"); - $sth->execute($matcher_id, $matchpoint_id); + $sth = $dbh->prepare_cached( + "INSERT INTO matcher_matchpoints (matcher_id, matchpoint_id) + VALUES (?, ?)" + ); + $sth->execute( $matcher_id, $matchpoint_id ); } - foreach my $matchcheck (@{ $self->{'required_checks'} }) { - my $source_matchpoint_id = $self->_store_matchpoint($matchcheck->{'source_matchpoint'}); - my $target_matchpoint_id = $self->_store_matchpoint($matchcheck->{'target_matchpoint'}); - $sth = $dbh->prepare_cached("INSERT INTO matchchecks + foreach my $matchcheck ( @{ $self->{'required_checks'} } ) { + my $source_matchpoint_id = $self->_store_matchpoint( $matchcheck->{'source_matchpoint'} ); + my $target_matchpoint_id = $self->_store_matchpoint( $matchcheck->{'target_matchpoint'} ); + $sth = $dbh->prepare_cached( + "INSERT INTO matchchecks (matcher_id, source_matchpoint_id, target_matchpoint_id) - VALUES (?, ?, ?)"); - $sth->execute($matcher_id, $source_matchpoint_id, $target_matchpoint_id); + VALUES (?, ?, ?)" + ); + $sth->execute( $matcher_id, $source_matchpoint_id, $target_matchpoint_id ); } } sub _store_matchpoint { - my $self = shift; + my $self = shift; my $matchpoint = shift; my $dbh = C4::Context->dbh(); my $sth; my $matcher_id = $self->{'id'}; - $sth = $dbh->prepare_cached("INSERT INTO matchpoints (matcher_id, search_index, score) - VALUES (?, ?, ?)"); - $sth->execute($matcher_id, $matchpoint->{'index'}, $matchpoint->{'score'}||0); + $sth = $dbh->prepare_cached( + "INSERT INTO matchpoints (matcher_id, search_index, score) + VALUES (?, ?, ?)" + ); + $sth->execute( $matcher_id, $matchpoint->{'index'}, $matchpoint->{'score'} || 0 ); my $matchpoint_id = $dbh->{'mysql_insertid'}; - my $seqnum = 0; - foreach my $component (@{ $matchpoint->{'components'} }) { + my $seqnum = 0; + + foreach my $component ( @{ $matchpoint->{'components'} } ) { $seqnum++; - $sth = $dbh->prepare_cached("INSERT INTO matchpoint_components + $sth = $dbh->prepare_cached( + "INSERT INTO matchpoint_components (matchpoint_id, sequence, tag, subfields, `offset`, length) - VALUES (?, ?, ?, ?, ?, ?)"); - $sth->bind_param(1, $matchpoint_id); - $sth->bind_param(2, $seqnum); - $sth->bind_param(3, $component->{'tag'}); - $sth->bind_param(4, join "", sort keys %{ $component->{'subfields'} }); - $sth->bind_param(5, $component->{'offset'}||0); - $sth->bind_param(6, $component->{'length'}); + VALUES (?, ?, ?, ?, ?, ?)" + ); + $sth->bind_param( 1, $matchpoint_id ); + $sth->bind_param( 2, $seqnum ); + $sth->bind_param( 3, $component->{'tag'} ); + $sth->bind_param( 4, join "", sort keys %{ $component->{'subfields'} } ); + $sth->bind_param( 5, $component->{'offset'} || 0 ); + $sth->bind_param( 6, $component->{'length'} ); $sth->execute(); my $matchpoint_component_id = $dbh->{'mysql_insertid'}; - my $normseq = 0; - foreach my $norm (@{ $component->{'norms'} }) { + my $normseq = 0; + + foreach my $norm ( @{ $component->{'norms'} } ) { $normseq++; - $sth = $dbh->prepare_cached("INSERT INTO matchpoint_component_norms + $sth = $dbh->prepare_cached( + "INSERT INTO matchpoint_component_norms (matchpoint_component_id, sequence, norm_routine) - VALUES (?, ?, ?)"); - $sth->execute($matchpoint_component_id, $normseq, $norm); + VALUES (?, ?, ?)" + ); + $sth->execute( $matchpoint_component_id, $normseq, $norm ); } } return $matchpoint_id; } - =head2 delete C4::Matcher->delete($id); @@ -375,12 +398,12 @@ from the database. =cut sub delete { - my $class = shift; + my $class = shift; my $matcher_id = shift; my $dbh = C4::Context->dbh; my $sth = $dbh->prepare("DELETE FROM marc_matchers WHERE matcher_id = ?"); - $sth->execute($matcher_id); # relying on cascading deletes to clean up everything + $sth->execute($matcher_id); # relying on cascading deletes to clean up everything } =head2 record_type @@ -478,16 +501,16 @@ normalization subroutine (under C4::Normalize) to be applied to the source string. =cut - + sub add_matchpoint { my $self = shift; - my ($index, $score, $matchcomponents) = @_; + my ( $index, $score, $matchcomponents ) = @_; my $matchpoint = {}; - $matchpoint->{'index'} = $index; - $matchpoint->{'score'} = $score; + $matchpoint->{'index'} = $index; + $matchpoint->{'score'} = $score; $matchpoint->{'components'} = []; - foreach my $input_component (@{ $matchcomponents }) { + foreach my $input_component ( @{$matchcomponents} ) { push @{ $matchpoint->{'components'} }, _parse_match_component($input_component); } push @{ $self->{'matchpoints'} }, $matchpoint; @@ -508,14 +531,18 @@ will receive the assigned score. sub add_simple_matchpoint { my $self = shift; - my ($index, $score, $source_tag, $source_subfields, $source_offset, $source_length, $source_normalizer) = @_; + my ( $index, $score, $source_tag, $source_subfields, $source_offset, $source_length, $source_normalizer ) = @_; - $self->add_matchpoint($index, $score, [ - { tag => $source_tag, subfields => $source_subfields, - offset => $source_offset, 'length' => $source_length, - norms => [ $source_normalizer ] - } - ]); + $self->add_matchpoint( + $index, $score, + [ + { + tag => $source_tag, subfields => $source_subfields, + offset => $source_offset, 'length' => $source_length, + norms => [$source_normalizer] + } + ] + ); } =head2 add_required_check @@ -552,19 +579,19 @@ to the source string. sub add_required_check { my $self = shift; - my ($source_matchpoint, $target_matchpoint) = @_; + my ( $source_matchpoint, $target_matchpoint ) = @_; my $matchcheck = {}; - $matchcheck->{'source_matchpoint'}->{'index'} = ''; - $matchcheck->{'source_matchpoint'}->{'score'} = 0; + $matchcheck->{'source_matchpoint'}->{'index'} = ''; + $matchcheck->{'source_matchpoint'}->{'score'} = 0; $matchcheck->{'source_matchpoint'}->{'components'} = []; - $matchcheck->{'target_matchpoint'}->{'index'} = ''; - $matchcheck->{'target_matchpoint'}->{'score'} = 0; + $matchcheck->{'target_matchpoint'}->{'index'} = ''; + $matchcheck->{'target_matchpoint'}->{'score'} = 0; $matchcheck->{'target_matchpoint'}->{'components'} = []; - foreach my $input_component (@{ $source_matchpoint }) { + foreach my $input_component ( @{$source_matchpoint} ) { push @{ $matchcheck->{'source_matchpoint'}->{'components'} }, _parse_match_component($input_component); } - foreach my $input_component (@{ $target_matchpoint }) { + foreach my $input_component ( @{$target_matchpoint} ) { push @{ $matchcheck->{'target_matchpoint'}->{'components'} }, _parse_match_component($input_component); } push @{ $self->{'required_checks'} }, $matchcheck; @@ -584,14 +611,26 @@ must match for a match to be considered valid. sub add_simple_required_check { my $self = shift; - my ($source_tag, $source_subfields, $source_offset, $source_length, $source_normalizer, - $target_tag, $target_subfields, $target_offset, $target_length, $target_normalizer) = @_; + my ( + $source_tag, $source_subfields, $source_offset, $source_length, $source_normalizer, + $target_tag, $target_subfields, $target_offset, $target_length, $target_normalizer + ) = @_; $self->add_required_check( - [ { tag => $source_tag, subfields => $source_subfields, offset => $source_offset, 'length' => $source_length, - norms => [ $source_normalizer ] } ], - [ { tag => $target_tag, subfields => $target_subfields, offset => $target_offset, 'length' => $target_length, - norms => [ $target_normalizer ] } ] + [ + { + tag => $source_tag, subfields => $source_subfields, offset => $source_offset, + 'length' => $source_length, + norms => [$source_normalizer] + } + ], + [ + { + tag => $target_tag, subfields => $target_subfields, offset => $target_offset, + 'length' => $target_length, + norms => [$target_normalizer] + } + ] ); } @@ -623,7 +662,7 @@ in order of decreasing score, i.e., the best match is first. sub get_matches { my $self = shift; - my ($source_record, $max_matches) = @_; + my ( $source_record, $max_matches ) = @_; my $matches = {}; @@ -633,11 +672,11 @@ sub get_matches { next if scalar(@source_keys) == 0; @source_keys = C4::Koha::GetVariationsOfISBNs(@source_keys) - if ( $matchpoint->{index} =~ /^isbn$/i + if ( $matchpoint->{index} =~ /^isbn$/i && C4::Context->preference('AggressiveMatchOnISBN') ); @source_keys = C4::Koha::GetVariationsOfISSNs(@source_keys) - if ( $matchpoint->{index} =~ /^issn$/i + if ( $matchpoint->{index} =~ /^issn$/i && C4::Context->preference('AggressiveMatchOnISSN') ); # build query @@ -647,35 +686,41 @@ sub get_matches { my $total_hits; if ( $self->{'record_type'} eq 'biblio' ) { - my $phr = ( C4::Context->preference('AggressiveMatchOnISBN') || C4::Context->preference('AggressiveMatchOnISSN') ) ? ',phr' : q{}; - $query = join( " OR ", - map { "$matchpoint->{'index'}$phr=\"$_\"" } @source_keys ); - #NOTE: double-quote the values so you don't get a "Embedded truncation not supported" error when a term has a ? in it. + my $phr = + ( C4::Context->preference('AggressiveMatchOnISBN') || C4::Context->preference('AggressiveMatchOnISSN') ) + ? ',phr' + : q{}; + $query = join( + " OR ", + map { "$matchpoint->{'index'}$phr=\"$_\"" } @source_keys + ); + + #NOTE: double-quote the values so you don't get a "Embedded truncation not supported" error when a term has a ? in it. # Use state variables to avoid recreating the objects every time. # With Elasticsearch this also avoids creating a massive amount of # ES connectors that would eventually run out of file descriptors. - state $searcher = Koha::SearchEngine::Search->new({index => $Koha::SearchEngine::BIBLIOS_INDEX}); + state $searcher = Koha::SearchEngine::Search->new( { index => $Koha::SearchEngine::BIBLIOS_INDEX } ); ( $error, $searchresults, $total_hits ) = - $searcher->simple_search_compat( $query, 0, $max_matches, undef, skip_normalize => 1 ); + $searcher->simple_search_compat( $query, 0, $max_matches, undef, skip_normalize => 1 ); if ( defined $error ) { warn "search failed ($query) $error"; - } - else { + } else { foreach my $matched ( @{$searchresults} ) { my $target_record = C4::Search::new_record_from_zebra( 'biblioserver', $matched ); - my ( $biblionumber_tag, $biblionumber_subfield ) = C4::Biblio::GetMarcFromKohaField( "biblio.biblionumber" ); - my $id = ( $biblionumber_tag > 10 ) ? - $target_record->field($biblionumber_tag)->subfield($biblionumber_subfield) : - $target_record->field($biblionumber_tag)->data(); + my ( $biblionumber_tag, $biblionumber_subfield ) = + C4::Biblio::GetMarcFromKohaField("biblio.biblionumber"); + my $id = + ( $biblionumber_tag > 10 ) + ? $target_record->field($biblionumber_tag)->subfield($biblionumber_subfield) + : $target_record->field($biblionumber_tag)->data(); $matches->{$id}->{score} += $matchpoint->{score}; $matches->{$id}->{record} = $target_record; } } - } - elsif ( $self->{'record_type'} eq 'authority' ) { + } elsif ( $self->{'record_type'} eq 'authority' ) { my @marclist; my @and_or; my @excluding = []; @@ -687,20 +732,22 @@ sub get_matches { push @operator, 'exact'; push @value, $key; } + # Use state variables to avoid recreating the objects every time. # With Elasticsearch this also avoids creating a massive amount of # ES connectors that would eventually run out of file descriptors. - state $builder = Koha::SearchEngine::QueryBuilder->new({index => $Koha::SearchEngine::AUTHORITIES_INDEX}); - state $searcher = Koha::SearchEngine::Search->new({index => $Koha::SearchEngine::AUTHORITIES_INDEX}); + state $builder = + Koha::SearchEngine::QueryBuilder->new( { index => $Koha::SearchEngine::AUTHORITIES_INDEX } ); + state $searcher = Koha::SearchEngine::Search->new( { index => $Koha::SearchEngine::AUTHORITIES_INDEX } ); my $search_query = $builder->build_authorities_query_compat( \@marclist, \@and_or, \@excluding, \@operator, - \@value, undef, 'AuthidAsc' + \@value, undef, 'AuthidAsc' ); my ( $authresults, $total ) = $searcher->search_auth_compat( $search_query, 0, 20 ); foreach my $result (@$authresults) { - my $id = $result->{authid}; - my $target_record = Koha::Authorities->find( $id )->record; + my $id = $result->{authid}; + my $target_record = Koha::Authorities->find($id)->record; $matches->{$id}->{score} += $matchpoint->{'score'}; $matches->{$id}->{record} = $target_record; } @@ -708,17 +755,19 @@ sub get_matches { } # get rid of any that don't meet the threshold - $matches = { map { ($matches->{$_}->{score} >= $self->{'threshold'}) ? ($_ => $matches->{$_}) : () } keys %$matches }; + $matches = + { map { ( $matches->{$_}->{score} >= $self->{'threshold'} ) ? ( $_ => $matches->{$_} ) : () } keys %$matches }; my @results = (); - if ($self->{'record_type'} eq 'biblio') { + if ( $self->{'record_type'} eq 'biblio' ) { require C4::Biblio; + # get rid of any that don't meet the required checks $matches = { map { _passes_required_checks( $source_record, $matches->{$_}->{'record'}, $self->{'required_checks'} ) - ? ( $_ => $matches->{$_} ) - : () + ? ( $_ => $matches->{$_} ) + : () } keys %$matches }; @@ -728,30 +777,28 @@ sub get_matches { score => $matches->{$id}->{score} }; } - } elsif ($self->{'record_type'} eq 'authority') { + } elsif ( $self->{'record_type'} eq 'authority' ) { require C4::AuthoritiesMarc; + # get rid of any that don't meet the required checks $matches = { map { _passes_required_checks( $source_record, $matches->{$_}->{'record'}, $self->{'required_checks'} ) - ? ( $_ => $matches->{$_} ) - : () + ? ( $_ => $matches->{$_} ) + : () } keys %$matches }; - foreach my $id (keys %$matches) { + foreach my $id ( keys %$matches ) { push @results, { record_id => $id, score => $matches->{$id}->{score} }; } } - @results = sort { - $b->{'score'} cmp $a->{'score'} or - $b->{'record_id'} cmp $a->{'record_id'} - } @results; - if (scalar(@results) > $max_matches) { - @results = @results[0..$max_matches-1]; + @results = sort { $b->{'score'} cmp $a->{'score'} or $b->{'record_id'} cmp $a->{'record_id'} } @results; + if ( scalar(@results) > $max_matches ) { + @results = @results[ 0 .. $max_matches - 1 ]; } return @results; } @@ -768,35 +815,35 @@ aid setting up a HTML editing form. sub dump { my $self = shift; - + my $result = {}; - $result->{'matcher_id'} = $self->{'id'}; - $result->{'code'} = $self->{'code'}; + $result->{'matcher_id'} = $self->{'id'}; + $result->{'code'} = $self->{'code'}; $result->{'description'} = $self->{'description'}; $result->{'record_type'} = $self->{'record_type'}; $result->{'matchpoints'} = []; - foreach my $matchpoint (@{ $self->{'matchpoints'} }) { - push @{ $result->{'matchpoints'} }, $matchpoint; + foreach my $matchpoint ( @{ $self->{'matchpoints'} } ) { + push @{ $result->{'matchpoints'} }, $matchpoint; } $result->{'matchchecks'} = []; - foreach my $matchcheck (@{ $self->{'required_checks'} }) { - push @{ $result->{'matchchecks'} }, $matchcheck; + foreach my $matchcheck ( @{ $self->{'required_checks'} } ) { + push @{ $result->{'matchchecks'} }, $matchcheck; } return $result; } sub _passes_required_checks { - my ($source_record, $target_record, $matchchecks) = @_; + my ( $source_record, $target_record, $matchchecks ) = @_; # no checks supplied == automatic pass - return 1 if $#{ $matchchecks } == -1; + return 1 if $#{$matchchecks} == -1; - foreach my $matchcheck (@{ $matchchecks }) { - my $source_key = join "", _get_match_keys($source_record, $matchcheck->{'source_matchpoint'}); - my $target_key = join "", _get_match_keys($target_record, $matchcheck->{'target_matchpoint'}); + foreach my $matchcheck ( @{$matchchecks} ) { + my $source_key = join "", _get_match_keys( $source_record, $matchcheck->{'source_matchpoint'} ); + my $target_key = join "", _get_match_keys( $target_record, $matchcheck->{'target_matchpoint'} ); return 0 unless $source_key eq $target_key; } return 1; @@ -804,8 +851,8 @@ sub _passes_required_checks { sub _get_match_keys { - my $source_record = shift; - my $matchpoint = shift; + my $source_record = shift; + my $matchpoint = shift; my $check_only_first_repeat = @_ ? shift : 0; # If there is more than one component to the matchpoint (e.g., @@ -824,62 +871,56 @@ sub _get_match_keys { # second 003 + second 001 my @keys = (); - for (my $i = 0; $i <= $#{ $matchpoint->{'components'} }; $i++) { + for ( my $i = 0 ; $i <= $#{ $matchpoint->{'components'} } ; $i++ ) { my $component = $matchpoint->{'components'}->[$i]; - my $j = -1; + my $j = -1; my @fields = (); - my $tag = $component->{'tag'}; - if ($tag && $tag eq 'LDR'){ + my $tag = $component->{'tag'}; + if ( $tag && $tag eq 'LDR' ) { $fields[0] = $source_record->leader(); - } - else { + } else { @fields = $source_record->field($tag); } - FIELD: foreach my $field (@fields) { + FIELD: foreach my $field (@fields) { $j++; last FIELD if $j > 0 and $check_only_first_repeat; last FIELD if $i > 0 and $j > $#keys; my $string; - if ( ! ref $field ){ + if ( !ref $field ) { $string = "$field"; - } - elsif ( $field->is_control_field() ) { + } elsif ( $field->is_control_field() ) { $string = $field->data(); - } elsif ( defined $component->{subfields} && keys %{$component->{subfields}} ){ + } elsif ( defined $component->{subfields} && keys %{ $component->{subfields} } ) { $string = $field->as_string( - join('', keys %{ $component->{ subfields } }), ' ' # ' ' as separator + join( '', keys %{ $component->{subfields} } ), ' ' # ' ' as separator ); } else { $string = $field->as_string(); } - if ($component->{'length'}>0) { - $string= substr($string, $component->{'offset'}, $component->{'length'}); - } elsif ($component->{'offset'}) { - $string= substr($string, $component->{'offset'}); + if ( $component->{'length'} > 0 ) { + $string = substr( $string, $component->{'offset'}, $component->{'length'} ); + } elsif ( $component->{'offset'} ) { + $string = substr( $string, $component->{'offset'} ); } my $norms = $component->{'norms'}; - my $key = $string; + my $key = $string; - foreach my $norm ( @{ $norms } ) { + foreach my $norm ( @{$norms} ) { if ( grep { $norm eq $_ } valid_normalization_routines() ) { if ( $norm eq 'remove_spaces' ) { $key = remove_spaces($key); - } - elsif ( $norm eq 'upper_case' ) { + } elsif ( $norm eq 'upper_case' ) { $key = upper_case($key); - } - elsif ( $norm eq 'lower_case' ) { + } elsif ( $norm eq 'lower_case' ) { $key = lower_case($key); - } - elsif ( $norm eq 'legacy_default' ) { + } elsif ( $norm eq 'legacy_default' ) { $key = legacy_default($key); - } - elsif ( $norm eq 'ISBN' ) { + } elsif ( $norm eq 'ISBN' ) { $key = ISBN($key); } } else { @@ -888,7 +929,7 @@ sub _get_match_keys { } } - if ($i == 0) { + if ( $i == 0 ) { push @keys, $key if $key; } else { $keys[$j] .= " $key" if $key; @@ -898,16 +939,15 @@ sub _get_match_keys { return @keys; } - sub _parse_match_component { my $input_component = shift; my $component = {}; - $component->{'tag'} = $input_component->{'tag'}; - $component->{'subfields'} = { map { $_ => 1 } split(//, $input_component->{'subfields'}) }; - $component->{'offset'} = exists($input_component->{'offset'}) ? $input_component->{'offset'} : -1; - $component->{'length'} = $input_component->{'length'} ? $input_component->{'length'} : 0; - $component->{'norms'} = $input_component->{'norms'} ? $input_component->{'norms'} : []; + $component->{'tag'} = $input_component->{'tag'}; + $component->{'subfields'} = { map { $_ => 1 } split( //, $input_component->{'subfields'} ) }; + $component->{'offset'} = exists( $input_component->{'offset'} ) ? $input_component->{'offset'} : -1; + $component->{'length'} = $input_component->{'length'} ? $input_component->{'length'} : 0; + $component->{'norms'} = $input_component->{'norms'} ? $input_component->{'norms'} : []; return $component; } diff --git a/C4/Members.pm b/C4/Members.pm index 82a013db3b..06365485b3 100644 --- a/C4/Members.pm +++ b/C4/Members.pm @@ -19,11 +19,10 @@ package C4::Members; # You should have received a copy of the GNU General Public License # along with Koha; if not, see . - use Modern::Perl; use C4::Context; use Scalar::Util qw( looks_like_number ); -use Date::Calc qw( check_date Date_to_Days ); +use Date::Calc qw( check_date Date_to_Days ); use C4::Overdues qw( checkoverdues ); use C4::Reserves; use C4::Accounts; @@ -37,14 +36,15 @@ use Koha::AdditionalContents; use Koha::Patrons; use Koha::Patron::Categories; -our (@ISA, @EXPORT_OK); +our ( @ISA, @EXPORT_OK ); + BEGIN { require Exporter; - @ISA = qw(Exporter); + @ISA = qw(Exporter); @EXPORT_OK = qw( - GetBorrowersToExpunge + GetBorrowersToExpunge - IssueSlip + IssueSlip ); } @@ -128,26 +128,25 @@ The "message" field that comes from the DB is OK. # DEPRECATED Do not use this subroutine! sub patronflags { my %flags; - my ( $patroninformation) = @_; - my $dbh=C4::Context->dbh; - my $patron = Koha::Patrons->find( $patroninformation->{borrowernumber} ); - my $account = $patron->account; + my ($patroninformation) = @_; + my $dbh = C4::Context->dbh; + my $patron = Koha::Patrons->find( $patroninformation->{borrowernumber} ); + my $account = $patron->account; my $patron_charge_limits = $patron->is_patron_inside_charge_limits(); if ( $patron_charge_limits->{noissuescharge}->{charge} > 0 ) { my %flaginfo; my $noissuescharge = $patron_charge_limits->{noissuescharge}->{limit} || 5; $flaginfo{'message'} = sprintf 'Patron owes %.02f', $patron_charge_limits->{noissuescharge}->{charge}; - $flaginfo{'amount'} = sprintf "%.02f", $patron_charge_limits->{noissuescharge}->{charge}; + $flaginfo{'amount'} = sprintf "%.02f", $patron_charge_limits->{noissuescharge}->{charge}; if ( $patron_charge_limits->{noissuescharge}->{overlimit} && !C4::Context->preference("AllowFineOverride") ) { $flaginfo{'noissues'} = 1; } $flags{'CHARGES'} = \%flaginfo; - } - elsif ( ( my $balance = $account->balance ) < 0 ) { + } elsif ( ( my $balance = $account->balance ) < 0 ) { my %flaginfo; $flaginfo{'message'} = sprintf 'Patron has credit of %.02f', -$balance; - $flaginfo{'amount'} = sprintf "%.02f", $balance; - $flags{'CREDITS'} = \%flaginfo; + $flaginfo{'amount'} = sprintf "%.02f", $balance; + $flags{'CREDITS'} = \%flaginfo; } # Check the debt of this patrons guarantees @@ -156,9 +155,10 @@ sub patronflags { if ( defined $no_issues_charge_guarantees ) { if ( $patron_charge_limits->{NoIssuesChargeGuarantees}->{overlimit} ) { my %flaginfo; - $flaginfo{'message'} = sprintf 'patron guarantees owe %.02f', $patron_charge_limits->{NoIssuesChargeGuarantees}->{charge}; - $flaginfo{'amount'} = $patron_charge_limits->{NoIssuesChargeGuarantees}->{charge}; - $flaginfo{'noissues'} = 1 unless C4::Context->preference("allowfineoverride"); + $flaginfo{'message'} = sprintf 'patron guarantees owe %.02f', + $patron_charge_limits->{NoIssuesChargeGuarantees}->{charge}; + $flaginfo{'amount'} = $patron_charge_limits->{NoIssuesChargeGuarantees}->{charge}; + $flaginfo{'noissues'} = 1 unless C4::Context->preference("allowfineoverride"); $flags{'CHARGES_GUARANTEES'} = \%flaginfo; } } @@ -184,7 +184,7 @@ sub patronflags { $flaginfo{'message'} = $patroninformation->{'debarredcomment'}; $flaginfo{'noissues'} = 1; $flaginfo{'dateend'} = $patroninformation->{'debarred'}; - $flags{'DBARRED'} = \%flaginfo; + $flags{'DBARRED'} = \%flaginfo; } } if ( $patroninformation->{'borrowernotes'} @@ -194,22 +194,19 @@ sub patronflags { $flaginfo{'message'} = $patroninformation->{'borrowernotes'}; $flags{'NOTES'} = \%flaginfo; } - my ( $odues, $itemsoverdue ) = C4::Overdues::checkoverdues($patroninformation->{'borrowernumber'}); + my ( $odues, $itemsoverdue ) = C4::Overdues::checkoverdues( $patroninformation->{'borrowernumber'} ); if ( $odues && $odues > 0 ) { my %flaginfo; $flaginfo{'message'} = "Yes"; $flaginfo{'itemlist'} = $itemsoverdue; - foreach ( sort { $a->{'date_due'} cmp $b->{'date_due'} } - @$itemsoverdue ) - { - $flaginfo{'itemlisttext'} .= - "$_->{'date_due'} $_->{'barcode'} $_->{'title'} \n"; # newline is display layer + foreach ( sort { $a->{'date_due'} cmp $b->{'date_due'} } @$itemsoverdue ) { + $flaginfo{'itemlisttext'} .= "$_->{'date_due'} $_->{'barcode'} $_->{'title'} \n"; # newline is display layer } $flags{'ODUES'} = \%flaginfo; } - my $waiting_holds = $patron->holds->search({ found => 'W' }); - my $nowaiting = $waiting_holds->count; + my $waiting_holds = $patron->holds->search( { found => 'W' } ); + my $nowaiting = $waiting_holds->count; if ( $nowaiting > 0 ) { my %flaginfo; $flaginfo{'message'} = "Reserved items available"; @@ -235,18 +232,22 @@ sub patronflags { sub GetBorrowersToExpunge { - my $params = shift; - my $filterdate = $params->{'not_borrowed_since'}; - my $filterexpiry = $params->{'expired_before'}; - my $filterlastseen = $params->{'last_seen'}; - my $filtercategory = $params->{'category_code'}; - my $filterbranch = $params->{'branchcode'} || - ((C4::Context->preference('IndependentBranches') - && C4::Context->userenv - && !C4::Context->IsSuperLibrarian() - && C4::Context->userenv->{branch}) - ? C4::Context->userenv->{branch} - : ""); + my $params = shift; + my $filterdate = $params->{'not_borrowed_since'}; + my $filterexpiry = $params->{'expired_before'}; + my $filterlastseen = $params->{'last_seen'}; + my $filtercategory = $params->{'category_code'}; + my $filterbranch = $params->{'branchcode'} + || ( + ( + C4::Context->preference('IndependentBranches') + && C4::Context->userenv + && !C4::Context->IsSuperLibrarian() + && C4::Context->userenv->{branch} + ) + ? C4::Context->userenv->{branch} + : "" + ); my $filterpatronlist = $params->{'patron_list_id'}; my $dbh = C4::Context->dbh; @@ -266,7 +267,7 @@ sub GetBorrowersToExpunge { ) as tmp ON borrowers.borrowernumber=tmp.guarantor_id LEFT JOIN old_issues USING (borrowernumber) LEFT JOIN issues USING (borrowernumber)|; - if ( $filterpatronlist ){ + if ($filterpatronlist) { $query .= q| LEFT JOIN patron_list_patrons USING (borrowernumber)|; } $query .= q| WHERE category_type <> 'S' @@ -276,36 +277,36 @@ sub GetBorrowersToExpunge { |; my @query_params; if ( $filterbranch && $filterbranch ne "" ) { - $query.= " AND borrowers.branchcode = ? "; + $query .= " AND borrowers.branchcode = ? "; push( @query_params, $filterbranch ); } - if ( $filterexpiry ) { + if ($filterexpiry) { $query .= " AND dateexpiry < ? "; push( @query_params, $filterexpiry ); } - if ( $filterlastseen ) { + if ($filterlastseen) { $query .= ' AND lastseen < ? '; push @query_params, $filterlastseen; } - if ( $filtercategory ) { - if (ref($filtercategory) ne 'ARRAY' ) { - $filtercategory = [ $filtercategory ]; + if ($filtercategory) { + if ( ref($filtercategory) ne 'ARRAY' ) { + $filtercategory = [$filtercategory]; } - if ( @$filtercategory ) { - $query .= " AND categorycode IN (" . join(',', ('?') x @$filtercategory) . ") "; + if (@$filtercategory) { + $query .= " AND categorycode IN (" . join( ',', ('?') x @$filtercategory ) . ") "; push( @query_params, @$filtercategory ); } } - if ( $filterpatronlist ){ - $query.=" AND patron_list_id = ? "; + if ($filterpatronlist) { + $query .= " AND patron_list_id = ? "; push( @query_params, $filterpatronlist ); } $query .= " GROUP BY borrowers.borrowernumber"; $query .= q| ) xxx WHERE currentissue IS NULL|; - if ( $filterdate ) { - $query.=" AND ( latestissue < ? OR latestissue IS NULL ) "; - push @query_params,$filterdate; + if ($filterdate) { + $query .= " AND ( latestissue < ? OR latestissue IS NULL ) "; + push @query_params, $filterdate; } if ( my $anonymous_patron = C4::Context->preference("AnonymousPatron") ) { @@ -314,10 +315,9 @@ sub GetBorrowersToExpunge { } my $sth = $dbh->prepare($query); - if (scalar(@query_params)>0){ + if ( scalar(@query_params) > 0 ) { $sth->execute(@query_params); - } - else { + } else { $sth->execute; } @@ -377,22 +377,22 @@ sub GetBorrowersToExpunge { =cut sub IssueSlip { - my ($branch, $borrowernumber, $quickslip) = @_; + my ( $branch, $borrowernumber, $quickslip ) = @_; # FIXME Check callers before removing this statement #return unless $borrowernumber; - my $patron = Koha::Patrons->find( $borrowernumber ); + my $patron = Koha::Patrons->find($borrowernumber); return unless $patron; - my $pending_checkouts = $patron->pending_checkouts; # Should be $patron->checkouts->pending? + my $pending_checkouts = $patron->pending_checkouts; # Should be $patron->checkouts->pending? - my ($letter_code, %repeat, %loops); - if ( $quickslip ) { - my $today_start = dt_from_string->set( hour => 0, minute => 0, second => 0 ); - my $today_end = dt_from_string->set( hour => 23, minute => 59, second => 0 ); - $today_start = Koha::Database->new->schema->storage->datetime_parser->format_datetime( $today_start ); - $today_end = Koha::Database->new->schema->storage->datetime_parser->format_datetime( $today_end ); + my ( $letter_code, %repeat, %loops ); + if ($quickslip) { + my $today_start = dt_from_string->set( hour => 0, minute => 0, second => 0 ); + my $today_end = dt_from_string->set( hour => 23, minute => 59, second => 0 ); + $today_start = Koha::Database->new->schema->storage->datetime_parser->format_datetime($today_start); + $today_end = Koha::Database->new->schema->storage->datetime_parser->format_datetime($today_end); $letter_code = 'ISSUEQSLIP'; # issue date or lastreneweddate is today @@ -403,8 +403,7 @@ sub IssueSlip { '>=' => $today_start, '<=' => $today_end, }, - lastreneweddate => - { '>=' => $today_start, '<=' => $today_end, } + lastreneweddate => { '>=' => $today_start, '<=' => $today_end, } } } ); @@ -419,18 +418,19 @@ sub IssueSlip { }; } - %repeat = ( - checkedout => \@checkouts, # Historical syntax + %repeat = ( + checkedout => \@checkouts, # Historical syntax ); %loops = ( - issues => [ map { $_->{issues}{itemnumber} } @checkouts ], # TT syntax + issues => [ map { $_->{issues}{itemnumber} } @checkouts ], # TT syntax ); - } - else { - my $today = Koha::Database->new->schema->storage->datetime_parser->format_datetime( dt_from_string ); + } else { + my $today = Koha::Database->new->schema->storage->datetime_parser->format_datetime(dt_from_string); + # Checkouts due in the future - my $checkouts = $pending_checkouts->search({ date_due => { '>' => $today } }); - my @checkouts; my @overdues; + my $checkouts = $pending_checkouts->search( { date_due => { '>' => $today } } ); + my @checkouts; + my @overdues; while ( my $c = $checkouts->next ) { my $all = $c->unblessed_all_relateds; push @checkouts, { @@ -442,7 +442,7 @@ sub IssueSlip { } # Checkouts due in the past are overdues - my $overdues = $pending_checkouts->search({ date_due => { '<=' => $today } }); + my $overdues = $pending_checkouts->search( { date_due => { '<=' => $today } } ); while ( my $o = $overdues->next ) { my $all = $o->unblessed_all_relateds; push @overdues, { @@ -466,24 +466,24 @@ sub IssueSlip { overdue => \@overdues, ); %loops = ( - issues => [ map { $_->{issues}{itemnumber} } @checkouts ], - overdues => [ map { $_->{issues}{itemnumber} } @overdues ], - opac_news => \@news_ids, + issues => [ map { $_->{issues}{itemnumber} } @checkouts ], + overdues => [ map { $_->{issues}{itemnumber} } @overdues ], + opac_news => \@news_ids, additional_contents => \@news_ids, ); } - return C4::Letters::GetPreparedLetter ( - module => 'circulation', + return C4::Letters::GetPreparedLetter( + module => 'circulation', letter_code => $letter_code, - branchcode => $branch, - lang => $patron->lang, - tables => { - 'branches' => $branch, - 'borrowers' => $borrowernumber, + branchcode => $branch, + lang => $patron->lang, + tables => { + 'branches' => $branch, + 'borrowers' => $borrowernumber, }, repeat => \%repeat, - loops => \%loops, + loops => \%loops, ); } diff --git a/C4/Members/Messaging.pm b/C4/Members/Messaging.pm index e3b93f614b..a92801f108 100644 --- a/C4/Members/Messaging.pm +++ b/C4/Members/Messaging.pm @@ -21,8 +21,6 @@ use strict; use warnings; use C4::Context; - - =head1 NAME C4::Members::Messaging - manage patron messaging preferences @@ -57,7 +55,7 @@ sub GetMessagingPreferences { my $params = shift; return unless exists $params->{message_name}; - return unless exists $params->{borrowernumber} xor exists $params->{categorycode}; # yes, xor + return unless exists $params->{borrowernumber} xor exists $params->{categorycode}; # yes, xor my $sql = <<'END_SQL'; SELECT borrower_message_preferences.*, borrower_message_transport_preferences.message_transport_type, @@ -90,7 +88,7 @@ END_SQL my $sth = C4::Context->dbh->prepare($sql); $sth->execute(@bind_params); my $return; - ROW: while ( my $row = $sth->fetchrow_hashref() ) { +ROW: while ( my $row = $sth->fetchrow_hashref() ) { next ROW unless $row->{'message_attribute_id'}; $return->{'days_in_advance'} = $row->{'days_in_advance'} if defined $row->{'days_in_advance'}; $return->{'wants_digest'} = $row->{'wants_digest'} if defined $row->{'wants_digest'}; @@ -121,21 +119,21 @@ returns nothing useful. sub SetMessagingPreference { my $params = shift; - unless (exists $params->{borrowernumber} xor exists $params->{categorycode}) { # yes, xor + unless ( exists $params->{borrowernumber} xor exists $params->{categorycode} ) { # yes, xor warn "SetMessagingPreference called without exactly one of borrowernumber or categorycode"; return; } - foreach my $required ( qw( message_attribute_id message_transport_types ) ) { - if ( ! exists $params->{ $required } ) { + foreach my $required (qw( message_attribute_id message_transport_types )) { + if ( !exists $params->{$required} ) { warn "SetMessagingPreference called without required parameter: $required"; return; } } - $params->{'days_in_advance'} = undef unless exists ( $params->{'days_in_advance'} ); - $params->{'wants_digest'} = 0 unless exists ( $params->{'wants_digest'} ); + $params->{'days_in_advance'} = undef unless exists( $params->{'days_in_advance'} ); + $params->{'wants_digest'} = 0 unless exists( $params->{'wants_digest'} ); my $dbh = C4::Context->dbh(); - + my $delete_sql = <<'END_SQL'; DELETE FROM borrower_message_preferences WHERE message_attribute_id = ? @@ -148,8 +146,8 @@ END_SQL $delete_sql .= " AND categorycode = ? "; push @bind_params, $params->{categorycode}; } - my $sth = $dbh->prepare( $delete_sql ); - my $deleted = $sth->execute( @bind_params ); + my $sth = $dbh->prepare($delete_sql); + my $deleted = $sth->execute(@bind_params); if ( $params->{'message_transport_types'} ) { my $insert_bmp = <<'END_SQL'; @@ -158,19 +156,23 @@ INSERT INTO borrower_message_preferences VALUES (NULL, ?, ?, ?, ?, ?) END_SQL - + $sth = C4::Context->dbh()->prepare($insert_bmp); + # set up so that we can easily construct the insert SQL - $params->{'borrowernumber'} = undef unless exists ( $params->{'borrowernumber'} ); - $params->{'categorycode'} = undef unless exists ( $params->{'categorycode'} ); - my $success = $sth->execute( $params->{'borrowernumber'}, - $params->{'categorycode'}, - $params->{'message_attribute_id'}, - $params->{'days_in_advance'}, - $params->{'wants_digest'} ); + $params->{'borrowernumber'} = undef unless exists( $params->{'borrowernumber'} ); + $params->{'categorycode'} = undef unless exists( $params->{'categorycode'} ); + my $success = $sth->execute( + $params->{'borrowernumber'}, + $params->{'categorycode'}, + $params->{'message_attribute_id'}, + $params->{'days_in_advance'}, + $params->{'wants_digest'} + ); + # my $borrower_message_preference_id = $dbh->last_insert_id(); my $borrower_message_preference_id = $dbh->{'mysql_insertid'}; - + my $insert_bmtp = <<'END_SQL'; INSERT INTO borrower_message_transport_preferences (borrower_message_preference_id, message_transport_type) @@ -178,11 +180,11 @@ VALUES (?, ?) END_SQL $sth = C4::Context->dbh()->prepare($insert_bmtp); - foreach my $transport ( @{$params->{'message_transport_types'}}) { + foreach my $transport ( @{ $params->{'message_transport_types'} } ) { my $success = $sth->execute( $borrower_message_preference_id, $transport ); } } - return; + return; } =head2 GetMessagingOptions @@ -210,7 +212,7 @@ END_SQL $choices->{ $row->{'message_name'} }->{'message_name'} = $row->{'message_name'}; $choices->{ $row->{'message_name'} }->{'takes_days'} = $row->{'takes_days'}; $choices->{ $row->{'message_name'} }->{'has_digest'} = 1 if $row->{'is_digest'}; - $choices->{ $row->{'message_name'} }->{'transport_' . $row->{'message_transport_type'}} = ' '; + $choices->{ $row->{'message_name'} }->{ 'transport_' . $row->{'message_transport_type'} } = ' '; } my @return = values %$choices; @@ -253,19 +255,24 @@ whatever defaults are defined for the patron category. sub SetMessagingPreferencesFromDefaults { my $params = shift; - foreach my $required ( qw( borrowernumber categorycode ) ) { - unless ( exists $params->{ $required } ) { + foreach my $required (qw( borrowernumber categorycode )) { + unless ( exists $params->{$required} ) { die "SetMessagingPreferencesFromDefaults called without required parameter: $required"; } } my $messaging_options = GetMessagingOptions(); - OPTION: foreach my $option ( @$messaging_options ) { +OPTION: foreach my $option (@$messaging_options) { if ( defined $params->{message_name} && $option->{'message_name'} ne $params->{message_name} ) { next OPTION; } - my $default_pref = GetMessagingPreferences( { categorycode => $params->{categorycode}, - message_name => $option->{'message_name'} } ); + my $default_pref = GetMessagingPreferences( + { + categorycode => $params->{categorycode}, + message_name => $option->{'message_name'} + } + ); + # FIXME - except for setting the borrowernumber, it really ought to be possible # to have the output of GetMessagingPreferences be able to be the input # to SetMessagingPreference @@ -273,7 +280,7 @@ sub SetMessagingPreferencesFromDefaults { $default_pref->{message_attribute_id} = $option->{'message_attribute_id'}; $default_pref->{message_transport_types} = \@message_transport_types; $default_pref->{borrowernumber} = $params->{borrowernumber}; - SetMessagingPreference( $default_pref ); + SetMessagingPreference($default_pref); } } diff --git a/C4/Members/Statistics.pm b/C4/Members/Statistics.pm index 8259dda319..3f6d9b4307 100644 --- a/C4/Members/Statistics.pm +++ b/C4/Members/Statistics.pm @@ -52,16 +52,16 @@ sub get_fields { my $syspref = C4::Context->preference('StatisticsFields'); my $ret; - if ( $syspref ) { + if ($syspref) { my @ret; - my @spfields = split ('\|', $syspref); - my $schema = Koha::Database->new()->schema(); - my @columns = $schema->source('Item')->columns; + my @spfields = split( '\|', $syspref ); + my $schema = Koha::Database->new()->schema(); + my @columns = $schema->source('Item')->columns; - foreach my $fn ( @spfields ) { - push ( @ret, $fn ) if ( grep { $_ eq $fn } @columns ); + foreach my $fn (@spfields) { + push( @ret, $fn ) if ( grep { $_ eq $fn } @columns ); } - $ret = join( '|', @ret); + $ret = join( '|', @ret ); } return $ret || 'location|itype|ccode'; } @@ -73,11 +73,11 @@ sub get_fields { =cut sub construct_query { - my $count = shift; - my $subquery = shift; - my $fields = get_fields(); + my $count = shift; + my $subquery = shift; + my $fields = get_fields(); my @select_fields = split '\|', $fields; - my $query = "SELECT COUNT(*) as count_$count,"; + my $query = "SELECT COUNT(*) as count_$count,"; $query .= join ',', @select_fields; $query .= " " . $subquery; @@ -96,17 +96,17 @@ sub construct_query { sub GetTotalIssuesTodayByBorrower { my ($borrowernumber) = @_; - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $query = construct_query "total_issues_today", "FROM ( SELECT it.* FROM issues i, items it WHERE i.itemnumber = it.itemnumber AND i.borrowernumber = ? AND DATE(i.issuedate) = CAST(now() AS date) UNION SELECT it.* FROM old_issues oi, items it WHERE oi.itemnumber = it.itemnumber AND oi.borrowernumber = ? AND DATE(oi.issuedate) = CAST(now() AS date) - ) tmp"; # alias is required by MySQL + ) tmp"; # alias is required by MySQL my $sth = $dbh->prepare($query); - $sth->execute($borrowernumber, $borrowernumber); + $sth->execute( $borrowernumber, $borrowernumber ); return $sth->fetchall_arrayref( {} ); } @@ -117,9 +117,10 @@ sub GetTotalIssuesTodayByBorrower { sub GetTotalIssuesReturnedTodayByBorrower { my ($borrowernumber) = @_; - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; - my $query = construct_query "total_issues_returned_today", "FROM old_issues i, items it WHERE i.itemnumber = it.itemnumber AND i.borrowernumber = ? AND DATE(i.returndate) = CAST(now() AS date) "; + my $query = construct_query "total_issues_returned_today", + "FROM old_issues i, items it WHERE i.itemnumber = it.itemnumber AND i.borrowernumber = ? AND DATE(i.returndate) = CAST(now() AS date) "; my $sth = $dbh->prepare($query); $sth->execute($borrowernumber); @@ -133,18 +134,18 @@ sub GetTotalIssuesReturnedTodayByBorrower { sub GetPrecedentStateByBorrower { my ($borrowernumber) = @_; - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $query = construct_query "precedent_state", "FROM ( SELECT it.* FROM issues i, items it WHERE i.borrowernumber = ? AND i.itemnumber = it.itemnumber AND DATE(i.issuedate) < CAST(now() AS date) UNION SELECT it.* FROM old_issues oi, items it WHERE oi.borrowernumber = ? AND oi.itemnumber = it.itemnumber AND DATE(oi.issuedate) < CAST(now() AS date) AND DATE(oi.returndate) = CAST(now() AS date) - ) tmp"; # alias is required by MySQL + ) tmp"; # alias is required by MySQL my $sth = $dbh->prepare($query); - $sth->execute($borrowernumber, $borrowernumber); - return $sth->fetchall_arrayref( {}); + $sth->execute( $borrowernumber, $borrowernumber ); + return $sth->fetchall_arrayref( {} ); } 1; diff --git a/C4/Message.pm b/C4/Message.pm index 68205083d5..efcd2f3293 100644 --- a/C4/Message.pm +++ b/C4/Message.pm @@ -18,12 +18,11 @@ package C4::Message; # You should have received a copy of the GNU General Public License # along with Koha; if not, see . - use strict; use warnings; use C4::Context; use C4::Letters qw( GetPreparedLetter EnqueueLetter ); -use YAML::XS qw( Dump ); +use YAML::XS qw( Dump ); use Encode; use Carp qw( carp ); @@ -68,10 +67,8 @@ database. =cut - our $AUTOLOAD; - =head2 Class Methods =head3 C4::Message->new(\%attributes) @@ -82,12 +79,11 @@ This method creates an in-memory version of a message object. # C4::Message->new(\%attributes) -- constructor sub new { - my ($class, $opts) = @_; + my ( $class, $opts ) = @_; $opts ||= {}; bless {%$opts} => $class; } - =head3 C4::Message->find($id) This method searches the message_queue table for a row with the given @@ -97,15 +93,15 @@ C and it'll return a C4::Message object if it finds one. # C4::Message->find($id) -- find a message by its message_id sub find { - my ($class, $id) = @_; - my $dbh = C4::Context->dbh; + my ( $class, $id ) = @_; + my $dbh = C4::Context->dbh; my $msgs = $dbh->selectall_arrayref( qq{SELECT * FROM message_queue WHERE message_id = ?}, { Slice => {} }, $id, ); if (@$msgs) { - return $class->new($msgs->[0]); + return $class->new( $msgs->[0] ); } else { return; } @@ -122,10 +118,11 @@ message before it gets sent out.) # C4::Message->find_last_message($borrower, $letter_code, $transport) # -- get the borrower's most recent pending checkin or checkout notification sub find_last_message { - my ($class, $borrower, $letter_code, $transport) = @_; + my ( $class, $borrower, $letter_code, $transport ) = @_; + # $type is the message_transport_type $transport ||= 'email'; - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $msgs = $dbh->selectall_arrayref( qq{ SELECT * @@ -141,13 +138,12 @@ sub find_last_message { $transport, ); if (@$msgs) { - return $class->new($msgs->[0]); + return $class->new( $msgs->[0] ); } else { return; } } - =head3 C4::Message->enqueue($letter, $patron, $transport) This is a front-end for C that adds metadata to @@ -183,18 +179,13 @@ sub _to_address { my $address; if ( $transport eq 'email' ) { $address = $patron->notice_email_address; - } - elsif ( $transport eq 'sms' ) { + } elsif ( $transport eq 'sms' ) { $address = $patron->smsalertnumber; - } - else { + } else { warn "'$transport' is an unknown message transport."; } if ( not defined $address ) { - warn "An appropriate $transport address " - . "for borrower " - . $patron->userid - . "could not be found."; + warn "An appropriate $transport address " . "for borrower " . $patron->userid . "could not be found."; } return $address; } @@ -202,8 +193,8 @@ sub _to_address { # _metadata($letter) -- return the letter split into head/body/footer sub _metadata { my ($letter) = @_; - if ($letter->{content} =~ /----/) { - my ($header, $body, $footer) = split(/----\r?\n?/, $letter->{content}); + if ( $letter->{content} =~ /----/ ) { + my ( $header, $body, $footer ) = split( /----\r?\n?/, $letter->{content} ); return { header => $header, body => [$body], @@ -212,7 +203,7 @@ sub _metadata { } else { return { header => '', - body => [$letter->{content}], + body => [ $letter->{content} ], footer => '', }; } @@ -252,7 +243,7 @@ sub update { $self->borrowernumber, $self->subject, $self->content, - $self->{metadata}, # we want the raw YAML here + $self->{metadata}, # we want the raw YAML here $self->letter_code, $self->message_transport_type, $self->status, @@ -274,26 +265,26 @@ attribute. (It is stored in YAML format.) # $object->metadata -- this is a YAML serialized column that contains a # structured representation of $object->content sub metadata { - my ($self, $data) = @_; + my ( $self, $data ) = @_; if ($data) { $data->{header} ||= ''; $data->{body} ||= []; $data->{footer} ||= ''; - $self->{metadata} = Encode::decode_utf8(Dump($data)); - $self->content($self->render_metadata); + $self->{metadata} = Encode::decode_utf8( Dump($data) ); + $self->content( $self->render_metadata ); return $data; } else { - return YAML::XS::Load(Encode::encode_utf8($self->{metadata})); + return YAML::XS::Load( Encode::encode_utf8( $self->{metadata} ) ); } } # turn $object->metadata into a string suitable for $object->content sub render_metadata { - my ($self, $format) = @_; + my ( $self, $format ) = @_; $format ||= sub { $_[0] || "" }; my $metadata = $self->metadata; my $body = $metadata->{body}; - my $text = join('', map { $format->($_) } @$body); + my $text = join( '', map { $format->($_) } @$body ); return $metadata->{header} . $text . $metadata->{footer}; } @@ -311,23 +302,23 @@ If passed a string, it'll append the string to the message. # $object->append($letter_or_item) -- add a new item to a message's content sub append { - my ($self, $letter_or_item, $format) = @_; + my ( $self, $letter_or_item, $format ) = @_; my ( $item, $header, $footer ); - if (ref($letter_or_item)) { + if ( ref($letter_or_item) ) { my $letter = $letter_or_item; my $metadata = _metadata($letter); $header = $metadata->{header}; $footer = $metadata->{footer}; - $item = $metadata->{body}->[0]; + $item = $metadata->{body}->[0]; } else { $item = $letter_or_item; } - if (not $self->metadata) { + if ( not $self->metadata ) { carp "Can't append to messages that don't have metadata."; return; } my $metadata = $self->metadata; - push @{$metadata->{body}}, $item; + push @{ $metadata->{body} }, $item; $metadata->{header} = $header; $metadata->{footer} = $footer; $self->metadata($metadata); @@ -387,11 +378,11 @@ sub append { # $object->$method -- treat keys as methods sub AUTOLOAD { - my ($self, @args) = @_; + my ( $self, @args ) = @_; my $attr = $AUTOLOAD; $attr =~ s/.*://; - if (ref($self->{$attr}) eq 'CODE') { - $self->{$attr}->($self, @args); + if ( ref( $self->{$attr} ) eq 'CODE' ) { + $self->{$attr}->( $self, @args ); } else { if (@args) { $self->{$attr} = $args[0]; diff --git a/C4/OAI/Sets.pm b/C4/OAI/Sets.pm index a81183bb32..88e6d45bf1 100644 --- a/C4/OAI/Sets.pm +++ b/C4/OAI/Sets.pm @@ -37,7 +37,7 @@ use vars qw(@ISA @EXPORT); BEGIN { require Exporter; - @ISA = qw(Exporter); + @ISA = qw(Exporter); @EXPORT = qw( GetOAISets GetOAISet GetOAISetBySpec ModOAISet DelOAISet AddOAISet GetOAISetsMappings GetOAISetMappings ModOAISetMappings @@ -68,13 +68,13 @@ The hash references looks like this: =cut sub GetOAISets { - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $query = qq{ SELECT * FROM oai_sets }; my $sth = $dbh->prepare($query); $sth->execute; - my $results = $sth->fetchall_arrayref({}); + my $results = $sth->fetchall_arrayref( {} ); $query = qq{ SELECT description @@ -83,10 +83,10 @@ sub GetOAISets { }; $sth = $dbh->prepare($query); foreach my $set (@$results) { - $sth->execute($set->{'id'}); - my $desc = $sth->fetchall_arrayref({}); + $sth->execute( $set->{'id'} ); + my $desc = $sth->fetchall_arrayref( {} ); foreach (@$desc) { - push @{$set->{'descriptions'}}, $_->{'description'}; + push @{ $set->{'descriptions'} }, $_->{'description'}; } } @@ -108,7 +108,7 @@ sub GetOAISet { return unless $set_id; - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $query = qq{ SELECT * FROM oai_sets @@ -124,10 +124,10 @@ sub GetOAISet { WHERE set_id = ? }; $sth = $dbh->prepare($query); - $sth->execute($set->{'id'}); - my $desc = $sth->fetchall_arrayref({}); + $sth->execute( $set->{'id'} ); + my $desc = $sth->fetchall_arrayref( {} ); foreach (@$desc) { - push @{$set->{'descriptions'}}, $_->{'description'}; + push @{ $set->{'descriptions'} }, $_->{'description'}; } return $set; @@ -146,7 +146,7 @@ sub GetOAISetBySpec { return unless defined $setSpec; - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $query = qq{ SELECT * FROM oai_sets @@ -176,14 +176,14 @@ ModOAISet modify a set in the database. sub ModOAISet { my ($set) = @_; - return unless($set && $set->{'spec'} && $set->{'name'}); + return unless ( $set && $set->{'spec'} && $set->{'name'} ); - if(!defined $set->{'id'}) { + if ( !defined $set->{'id'} ) { warn "Set ID not defined, can't modify the set"; return; } - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $query = qq{ UPDATE oai_sets SET spec = ?, @@ -191,24 +191,24 @@ sub ModOAISet { WHERE id = ? }; my $sth = $dbh->prepare($query); - $sth->execute($set->{'spec'}, $set->{'name'}, $set->{'id'}); + $sth->execute( $set->{'spec'}, $set->{'name'}, $set->{'id'} ); - if($set->{'descriptions'}) { + if ( $set->{'descriptions'} ) { $query = qq{ DELETE FROM oai_sets_descriptions WHERE set_id = ? }; $sth = $dbh->prepare($query); - $sth->execute($set->{'id'}); + $sth->execute( $set->{'id'} ); - if(scalar @{$set->{'descriptions'}} > 0) { + if ( scalar @{ $set->{'descriptions'} } > 0 ) { $query = qq{ INSERT INTO oai_sets_descriptions (set_id, description) VALUES (?,?) }; $sth = $dbh->prepare($query); - foreach (@{ $set->{'descriptions'} }) { - $sth->execute($set->{'id'}, $_) if $_; + foreach ( @{ $set->{'descriptions'} } ) { + $sth->execute( $set->{'id'}, $_ ) if $_; } } } @@ -227,7 +227,7 @@ sub DelOAISet { return unless $set_id; - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $query = qq{ DELETE oai_sets, oai_sets_descriptions, oai_sets_mappings FROM oai_sets @@ -256,25 +256,25 @@ AddOAISet adds a new set and returns its id, or undef if something went wrong. sub AddOAISet { my ($set) = @_; - return unless($set && $set->{'spec'} && $set->{'name'}); + return unless ( $set && $set->{'spec'} && $set->{'name'} ); my $set_id; - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $query = qq{ INSERT INTO oai_sets (spec, name) VALUES (?,?) }; my $sth = $dbh->prepare($query); - if( $sth->execute($set->{'spec'}, $set->{'name'}) ) { - $set_id = $dbh->last_insert_id(undef, undef, 'oai_sets', undef); - if($set->{'descriptions'}) { + if ( $sth->execute( $set->{'spec'}, $set->{'name'} ) ) { + $set_id = $dbh->last_insert_id( undef, undef, 'oai_sets', undef ); + if ( $set->{'descriptions'} ) { $query = qq{ INSERT INTO oai_sets_descriptions (set_id, description) VALUES (?,?) }; $sth = $dbh->prepare($query); - foreach( @{ $set->{'descriptions'} } ) { - $sth->execute($set_id, $_) if $_; + foreach ( @{ $set->{'descriptions'} } ) { + $sth->execute( $set_id, $_ ) if $_; } } } else { @@ -330,7 +330,7 @@ The first hashref keys are the sets IDs, so it looks like this: =cut sub GetOAISetsMappings { - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $query = qq{ SELECT * FROM oai_sets_mappings ORDER BY set_id, rule_order }; @@ -338,14 +338,14 @@ sub GetOAISetsMappings { $sth->execute; my $mappings = {}; - while(my $result = $sth->fetchrow_hashref) { - push @{ $mappings->{$result->{'set_id'}} }, { - marcfield => $result->{'marcfield'}, - marcsubfield => $result->{'marcsubfield'}, - operator => $result->{'operator'}, - marcvalue => $result->{'marcvalue'}, + while ( my $result = $sth->fetchrow_hashref ) { + push @{ $mappings->{ $result->{'set_id'} } }, { + marcfield => $result->{'marcfield'}, + marcsubfield => $result->{'marcsubfield'}, + operator => $result->{'operator'}, + marcvalue => $result->{'marcvalue'}, rule_operator => $result->{'rule_operator'}, - rule_order => $result->{'rule_order'} + rule_order => $result->{'rule_order'} }; } @@ -365,7 +365,7 @@ sub GetOAISetMappings { return unless $set_id; - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $query = qq{ SELECT * FROM oai_sets_mappings @@ -376,14 +376,14 @@ sub GetOAISetMappings { $sth->execute($set_id); my @mappings; - while(my $result = $sth->fetchrow_hashref) { + while ( my $result = $sth->fetchrow_hashref ) { push @mappings, { - marcfield => $result->{'marcfield'}, - marcsubfield => $result->{'marcsubfield'}, - operator => $result->{'operator'}, - marcvalue => $result->{'marcvalue'}, + marcfield => $result->{'marcfield'}, + marcsubfield => $result->{'marcsubfield'}, + operator => $result->{'operator'}, + marcvalue => $result->{'marcvalue'}, rule_operator => $result->{'rule_operator'}, - rule_order => $result->{'rule_order'} + rule_order => $result->{'rule_order'} }; } @@ -408,25 +408,28 @@ ModOAISetMappings modifies mappings of a given set. =cut sub ModOAISetMappings { - my ($set_id, $mappings) = @_; + my ( $set_id, $mappings ) = @_; return unless $set_id; - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $query = qq{ DELETE FROM oai_sets_mappings WHERE set_id = ? }; my $sth = $dbh->prepare($query); $sth->execute($set_id); - if(scalar @$mappings > 0) { + if ( scalar @$mappings > 0 ) { $query = qq{ INSERT INTO oai_sets_mappings (set_id, marcfield, marcsubfield, operator, marcvalue, rule_operator, rule_order) VALUES (?,?,?,?,?,?,?) }; $sth = $dbh->prepare($query); foreach (@$mappings) { - $sth->execute($set_id, $_->{'marcfield'}, $_->{'marcsubfield'}, $_->{'operator'}, $_->{'marcvalue'}, $_->{'rule_operator'}, $_->{'rule_order'}); + $sth->execute( + $set_id, $_->{'marcfield'}, $_->{'marcsubfield'}, $_->{'operator'}, $_->{'marcvalue'}, + $_->{'rule_operator'}, $_->{'rule_order'} + ); } } } @@ -445,7 +448,7 @@ Keys of hash are id, spec and name sub GetOAISetsBiblio { my ($biblionumber) = @_; - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $query = qq{ SELECT oai_sets.* FROM oai_sets @@ -455,7 +458,7 @@ sub GetOAISetsBiblio { my $sth = $dbh->prepare($query); $sth->execute($biblionumber); - return $sth->fetchall_arrayref({}); + return $sth->fetchall_arrayref( {} ); } =head2 DelOAISetsBiblio @@ -471,7 +474,7 @@ sub DelOAISetsBiblio { return unless $biblionumber; - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $query = qq{ DELETE FROM oai_sets_biblios WHERE biblionumber = ? @@ -491,41 +494,41 @@ GetOAISetsMappings =cut sub CalcOAISetsBiblio { - my ($record, $oai_sets_mappings) = @_; + my ( $record, $oai_sets_mappings ) = @_; return unless $record; $oai_sets_mappings ||= GetOAISetsMappings; my @biblio_sets; - foreach my $set_id (keys %$oai_sets_mappings) { + foreach my $set_id ( keys %$oai_sets_mappings ) { my $rules = []; - foreach my $mapping (@{ $oai_sets_mappings->{$set_id} }) { + foreach my $mapping ( @{ $oai_sets_mappings->{$set_id} } ) { next if not $mapping; my $rule_operator = $mapping->{'rule_operator'}; - my $result = _evalRule($record, $mapping); + my $result = _evalRule( $record, $mapping ); # First rule or 'or' rule is always pushed - if (!@$rules || $rule_operator eq 'or') { + if ( !@$rules || $rule_operator eq 'or' ) { push @$rules, [$result]; next; } # 'and' rule is pushed in the last 'or' rule - push @{$rules->[-1]}, $result; + push @{ $rules->[-1] }, $result; } my @evaluated_and; foreach my $ruleset (@$rules) { - if (0 < grep /0/, @{$ruleset}) { + if ( 0 < grep /0/, @{$ruleset} ) { push @evaluated_and, 0; } else { push @evaluated_and, 1; } } - if (grep /1/, @evaluated_and) { + if ( grep /1/, @evaluated_and ) { push @biblio_sets, $set_id; } @@ -535,39 +538,40 @@ sub CalcOAISetsBiblio { # Does the record match a given mapping rule? sub _evalRule { - my $record = shift; + my $record = shift; my $mapping = shift; - my $field = $mapping->{'marcfield'}; + my $field = $mapping->{'marcfield'}; my $subfield = $mapping->{'marcsubfield'}; my $operator = $mapping->{'operator'}; - my $value = $mapping->{'marcvalue'}; + my $value = $mapping->{'marcvalue'}; my @all_subfield_values; + # Get all the fields with the given tag my @fields = $record->field($field); + # Iterate over all the fields - foreach my $field ( @fields ) { + foreach my $field (@fields) { + # Get the values from all the subfields with the given subfield code if ( my @subfield_values = $field->subfield($subfield) ) { push @all_subfield_values, @subfield_values; } } - if ($operator eq 'notequal') { - if(0 == grep { $_ eq $value } @all_subfield_values) { + if ( $operator eq 'notequal' ) { + if ( 0 == grep { $_ eq $value } @all_subfield_values ) { return 1; } - } - else { - if(0 < grep { $_ eq $value } @all_subfield_values) { + } else { + if ( 0 < grep { $_ eq $value } @all_subfield_values ) { return 1; } } return 0; } - =head2 ModOAISetsBiblios my $oai_sets_biblios = { @@ -587,7 +591,7 @@ sub ModOAISetsBiblios { return unless ref($oai_sets_biblios) eq "HASH"; - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $query = qq{ DELETE FROM oai_sets_biblios }; @@ -606,12 +610,12 @@ $record is a MARC::Record. =cut sub UpdateOAISetsBiblio { - my ($biblionumber, $record) = @_; + my ( $biblionumber, $record ) = @_; - return unless($biblionumber and $record); + return unless ( $biblionumber and $record ); $record = $record->clone; - if (C4::Context->preference('OAI-PMH:AutoUpdateSetsEmbedItemData')) { + if ( C4::Context->preference('OAI-PMH:AutoUpdateSetsEmbedItemData') ) { $record = Koha::Biblio::Metadata->record( { record => $record, @@ -649,15 +653,15 @@ sub AddOAISetsBiblios { return unless ref($oai_sets_biblios) eq "HASH"; - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $query = qq{ INSERT INTO oai_sets_biblios (set_id, biblionumber) VALUES (?,?) }; my $sth = $dbh->prepare($query); - foreach my $set_id (keys %$oai_sets_biblios) { - foreach my $biblionumber (@{$oai_sets_biblios->{$set_id}}) { - $sth->execute($set_id, $biblionumber); + foreach my $set_id ( keys %$oai_sets_biblios ) { + foreach my $biblionumber ( @{ $oai_sets_biblios->{$set_id} } ) { + $sth->execute( $set_id, $biblionumber ); } } } diff --git a/C4/Output.pm b/C4/Output.pm index d8ea0bfb52..14892c29b2 100644 --- a/C4/Output.pm +++ b/C4/Output.pm @@ -21,7 +21,6 @@ package C4::Output; # You should have received a copy of the GNU General Public License # along with Koha; if not, see . - # NOTE: I'm pretty sure this module is deprecated in favor of # templates. @@ -35,12 +34,12 @@ use C4::Auth qw( get_template_and_user ); use C4::Context; use C4::Templates; -our (@ISA, @EXPORT_OK); +our ( @ISA, @EXPORT_OK ); BEGIN { require Exporter; - @ISA = qw(Exporter); + @ISA = qw(Exporter); @EXPORT_OK = qw( is_ajax ajax_fail @@ -78,10 +77,10 @@ This function returns HTML, without any language dependency. =cut sub pagination_bar { - my $base_url = (@_ ? shift : return); - my $nb_pages = (@_) ? shift : 1; - my $current_page = (@_) ? shift : undef; # delay default until later - my $startfrom_name = (@_) ? shift : 'page'; + my $base_url = ( @_ ? shift : return ); + my $nb_pages = (@_) ? shift : 1; + my $current_page = (@_) ? shift : undef; # delay default until later + my $startfrom_name = (@_) ? shift : 'page'; my $additional_parameters = shift || {}; $base_url = HTML::Entities::encode($base_url); @@ -92,16 +91,16 @@ sub pagination_bar { # how many pages to show before and after the current page? my $pages_around = 2; - my $delim = qr/\&(?:amp;)?|;/; # "non memory" cluster: no backreference - $base_url =~ s/$delim*\b$startfrom_name=(\d+)//g; # remove previous pagination var - unless (defined $current_page and $current_page > 0 and $current_page <= $nb_pages) { - $current_page = ($1) ? $1 : 1; # pull current page from param in URL, else default to 1 + my $delim = qr/\&(?:amp;)?|;/; # "non memory" cluster: no backreference + $base_url =~ s/$delim*\b$startfrom_name=(\d+)//g; # remove previous pagination var + unless ( defined $current_page and $current_page > 0 and $current_page <= $nb_pages ) { + $current_page = ($1) ? $1 : 1; # pull current page from param in URL, else default to 1 } - $base_url =~ s/($delim)+/$1/g; # compress duplicate delims - $base_url =~ s/$delim;//g; # remove empties - $base_url =~ s/$delim$//; # remove trailing delim + $base_url =~ s/($delim)+/$1/g; # compress duplicate delims + $base_url =~ s/$delim;//g; # remove empties + $base_url =~ s/$delim$//; # remove trailing delim - my $url = $base_url . (($base_url =~ m/$delim/ or $base_url =~ m/\?/) ? '&' : '?' ) . $startfrom_name . '='; + my $url = $base_url . ( ( $base_url =~ m/$delim/ or $base_url =~ m/\?/ ) ? '&' : '?' ) . $startfrom_name . '='; my $url_suffix = ''; while ( my ( $k, $v ) = each %$additional_parameters ) { $url_suffix .= '&' . URI::Escape::uri_escape_utf8($k) . '=' . URI::Escape::uri_escape_utf8($v); @@ -114,17 +113,9 @@ sub pagination_bar { # link to first page? if ( $current_page > 1 ) { $pagination_bar .= - "\n" . ' ' - . '' - . '<<' . ''; - } - else { - $pagination_bar .= - "\n" . ' <<'; + "\n" . ' ' . '' . '<<' . ''; + } else { + $pagination_bar .= "\n" . ' <<'; } # link on previous page ? @@ -132,16 +123,9 @@ sub pagination_bar { my $previous = $current_page - 1; $pagination_bar .= - "\n" . ' ' - . ''; - } - else { - $pagination_bar .= - "\n" . ' <'; + "\n" . ' ' . ''; + } else { + $pagination_bar .= "\n" . ' <'; } my $min_to_display = $current_page - $pages_around; @@ -154,31 +138,25 @@ sub pagination_bar { or $page_number == $nb_pages or ( $page_number >= $min_to_display and $page_number <= $max_to_display ) - ) + ) { if ( defined $last_displayed_page and $last_displayed_page != $page_number - 1 ) { - $pagination_bar .= - "\n" . ' ...'; + $pagination_bar .= "\n" . ' ...'; } if ( $page_number == $current_page ) { + $pagination_bar .= "\n" . ' ' . '' . $page_number . ''; + } else { $pagination_bar .= - "\n" . ' ' - . '' - . $page_number - . ''; - } - else { - $pagination_bar .= - "\n" . ' ' - . '' - . $page_number . ''; + "\n" + . ' ' + . '' + . $page_number . ''; } $last_displayed_page = $page_number; } @@ -188,31 +166,18 @@ sub pagination_bar { if ( $current_page < $nb_pages ) { my $next = $current_page + 1; - $pagination_bar .= "\n" - . ' '; - } - else { $pagination_bar .= - "\n" . ' >'; + "\n" . ' '; + } else { + $pagination_bar .= "\n" . ' >'; } # link to last page? if ( $current_page != $nb_pages ) { - $pagination_bar .= "\n" - . ' ' - . '>>' . ''; - } - else { $pagination_bar .= - "\n" . ' >>'; + "\n" . ' ' . '>>' . ''; + } else { + $pagination_bar .= "\n" . ' >>'; } } @@ -250,10 +215,11 @@ sub output_with_http_headers { 'js' => 'text/javascript', 'json' => 'application/json', 'xml' => 'text/xml', + # NOTE: not using application/atom+xml or application/rss+xml because of # Internet Explorer 6; see bug 2078. - 'rss' => 'text/xml', - 'atom' => 'text/xml', + 'rss' => 'text/xml', + 'atom' => 'text/xml', 'opensearchdescription' => 'application/opensearchdescription+xml', ); @@ -268,18 +234,18 @@ sub output_with_http_headers { 'Cache-Control' => $cache_policy, 'X-Frame-Options' => 'SAMEORIGIN', }; - $options->{expires} = 'now' if $extra_options->{force_no_caching}; + $options->{expires} = 'now' if $extra_options->{force_no_caching}; $options->{'Access-Control-Allow-Origin'} = C4::Context->preference('AccessControlAllowOrigin') if C4::Context->preference('AccessControlAllowOrigin'); $options->{cookie} = $cookie if $cookie; - if ($content_type eq 'html') { # guaranteed to be one of the content_type_map keys, else we'd have died - $options->{'Content-Style-Type' } = 'text/css'; + if ( $content_type eq 'html' ) { # guaranteed to be one of the content_type_map keys, else we'd have died + $options->{'Content-Style-Type'} = 'text/css'; $options->{'Content-Script-Type'} = 'text/javascript'; } -# We can't encode here, that will double encode our templates, and xslt -# We need to fix the encoding as it comes out of the database, or when we pass the variables to templates + # We can't encode here, that will double encode our templates, and xslt + # We need to fix the encoding as it comes out of the database, or when we pass the variables to templates $data =~ s/\&\;amp\; /\&\; /g; print $query->header($options), $data; @@ -290,7 +256,6 @@ sub output_html_with_http_headers { output_with_http_headers( $query, $cookie, $data, 'html', $status, $extra_options ); } - sub output_ajax_with_http_headers { my ( $query, $js ) = @_; print $query->header( @@ -339,27 +304,24 @@ sub output_and_exit_if_error { my $current_patron = $params->{current_patron}; if ( not $current_patron ) { $error = 'unknown_patron'; - } - elsif ( not $logged_in_user->can_see_patron_infos($current_patron) ) - { + } elsif ( not $logged_in_user->can_see_patron_infos($current_patron) ) { $error = 'cannot_see_patron_infos'; } - } - elsif ( $params->{module} eq 'cataloguing' ) { + } elsif ( $params->{module} eq 'cataloguing' ) { + # We are testing the record to avoid additem to fetch the Koha::Biblio # But in the long term we will want to get a biblio in parameter $error = 'unknown_biblio' unless $params->{record}; } - } - elsif ( $params and exists $params->{check} ) { + } elsif ( $params and exists $params->{check} ) { if ( $params->{check} eq 'csrf_token' ) { $error = 'wrong_csrf_token' - unless Koha::Token->new->check_csrf( + unless Koha::Token->new->check_csrf( { session_id => scalar $query->cookie('CGISESSID'), token => scalar $query->param('csrf_token'), } - ); + ); } } output_and_exit( $query, $cookie, $template, $error ) if $error; @@ -378,7 +340,7 @@ sub output_and_exit_if_error { sub output_and_exit { my ( $query, $cookie, $template, $error ) = @_; $template->param( blocking_error => $error ); - output_html_with_http_headers ( $query, $cookie, $template->output ); + output_html_with_http_headers( $query, $cookie, $template->output ); exit; } @@ -393,7 +355,7 @@ sub output_error { } ); my $admin = C4::Context->preference('KohaAdminEmailAddress'); - $template->param ( + $template->param( admin => $admin, errno => $error, ); @@ -401,18 +363,18 @@ sub output_error { } sub parametrized_url { - my $url = shift || ''; # ie page.pl?ln={LANG} - my $vars = shift || {}; # ie { LANG => en } - my $ret = $url; - while ( my ($key,$val) = each %$vars) { + my $url = shift || ''; # ie page.pl?ln={LANG} + my $vars = shift || {}; # ie { LANG => en } + my $ret = $url; + while ( my ( $key, $val ) = each %$vars ) { my $val_url = URI::Escape::uri_escape_utf8( $val // q{} ); $ret =~ s/\{$key\}/$val_url/g; } - $ret =~ s/\{[^\{]*\}//g; # remove remaining vars + $ret =~ s/\{[^\{]*\}//g; # remove remaining vars return $ret; } -END { } # module clean-up code here (global destructor) +END { } # module clean-up code here (global destructor) 1; __END__ diff --git a/C4/Output/JSONStream.pm b/C4/Output/JSONStream.pm index a16143c534..f6c8372a76 100644 --- a/C4/Output/JSONStream.pm +++ b/C4/Output/JSONStream.pm @@ -43,8 +43,8 @@ use JSON qw( to_json ); sub new { my $class = shift; - my $self = { - data => {}, + my $self = { + data => {}, options => {} }; @@ -60,8 +60,8 @@ sub param { die 'param() received odd number of arguments (should be called with param => "value" pairs)'; } - for ( my $i = 0; $i < $#_; $i += 2 ) { - $self->{data}->{$_[$i]} = $_[$i + 1]; + for ( my $i = 0 ; $i < $#_ ; $i += 2 ) { + $self->{data}->{ $_[$i] } = $_[ $i + 1 ]; } } diff --git a/C4/Overdues.pm b/C4/Overdues.pm index 171651cdb3..4d6e50f27a 100644 --- a/C4/Overdues.pm +++ b/C4/Overdues.pm @@ -1,6 +1,5 @@ package C4::Overdues; - # Copyright 2000-2002 Katipo Communications # copyright 2010 BibLibre # @@ -20,12 +19,12 @@ package C4::Overdues; # along with Koha; if not, see . use Modern::Perl; -use Date::Calc qw( Today ); -use Date::Manip qw( UnixDate ); -use List::MoreUtils qw( uniq ); -use POSIX qw( ceil floor ); +use Date::Calc qw( Today ); +use Date::Manip qw( UnixDate ); +use List::MoreUtils qw( uniq ); +use POSIX qw( ceil floor ); use Locale::Currency::Format 1.28 qw( currency_format FMT_SYMBOL ); -use Carp qw( carp ); +use Carp qw( carp ); use C4::Accounts; use C4::Context; @@ -37,24 +36,25 @@ use Koha::Recalls; use Koha::Logger; use Koha::Patrons; -our (@ISA, @EXPORT_OK); +our ( @ISA, @EXPORT_OK ); + BEGIN { require Exporter; @ISA = qw(Exporter); # subs to rename (and maybe merge some...) @EXPORT_OK = qw( - CalcFine - Getoverdues - checkoverdues - UpdateFine - GetFine - GetBranchcodesWithOverdueRules - get_chargeable_units - GetOverduesForBranch - GetOverdueMessageTransportTypes - parse_overdues_letter - GetIssuesIteminfo + CalcFine + Getoverdues + checkoverdues + UpdateFine + GetFine + GetBranchcodesWithOverdueRules + get_chargeable_units + GetOverduesForBranch + GetOverdueMessageTransportTypes + parse_overdues_letter + GetIssuesIteminfo ); } @@ -88,7 +88,7 @@ Koha database. #' sub Getoverdues { my $params = shift; - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $statement; if ( C4::Context->preference('item-level_itypes') ) { $statement = " @@ -119,12 +119,11 @@ LEFT JOIN biblioitems USING (biblioitemnumber) push @bind_parameters, $params->{'maximumdays'}; } $statement .= 'ORDER BY borrowernumber'; - my $sth = $dbh->prepare( $statement ); - $sth->execute( @bind_parameters ); - return $sth->fetchall_arrayref({}); + my $sth = $dbh->prepare($statement); + $sth->execute(@bind_parameters); + return $sth->fetchall_arrayref( {} ); } - =head2 checkoverdues ($count, $overdueitems) = checkoverdues($borrowernumber); @@ -135,7 +134,7 @@ Returns a count and a list of overdueitems for a given borrowernumber sub checkoverdues { my $borrowernumber = shift or return; - my $sth = C4::Context->dbh->prepare( + my $sth = C4::Context->dbh->prepare( "SELECT biblio.*, items.*, issues.*, biblioitems.volume, biblioitems.number, @@ -172,8 +171,8 @@ sub checkoverdues { AND issues.date_due < NOW()" ); $sth->execute($borrowernumber); - my $results = $sth->fetchall_arrayref({}); - return ( scalar(@$results), $results); # returning the count and the results is silly + my $results = $sth->fetchall_arrayref( {} ); + return ( scalar(@$results), $results ); # returning the count and the results is silly } =head2 CalcFine @@ -218,20 +217,21 @@ or "Final Notice". But CalcFine never defined any value. =cut sub CalcFine { - my ( $item, $bortype, $branchcode, $due_dt, $end_date ) = @_; + my ( $item, $bortype, $branchcode, $due_dt, $end_date ) = @_; # Skip calculations if item is not overdue - return ( 0, 0, 0 ) unless (DateTime->compare( $due_dt, $end_date ) == -1); + return ( 0, 0, 0 ) unless ( DateTime->compare( $due_dt, $end_date ) == -1 ); my $start_date = $due_dt->clone(); + # get issuingrules (fines part will be used) - my $itemtype = $item->{itemtype} || $item->{itype}; + my $itemtype = $item->{itemtype} || $item->{itype}; my $issuing_rule = Koha::CirculationRules->get_effective_rules( { categorycode => $bortype, itemtype => $itemtype, branchcode => $branchcode, - rules => [ + rules => [ 'lengthunit', 'firstremind', 'chargeperiod', @@ -246,41 +246,48 @@ sub CalcFine { $itemtype = Koha::ItemTypes->find($itemtype); - return unless $issuing_rule; # If not rule exist, there is no fine + return unless $issuing_rule; # If not rule exist, there is no fine my $fine_unit = $issuing_rule->{lengthunit} || 'days'; - my $chargeable_units = get_chargeable_units($fine_unit, $start_date, $end_date, $branchcode); - my $units_minus_grace = $chargeable_units - ($issuing_rule->{firstremind} || 0); - my $amount = 0; + my $chargeable_units = get_chargeable_units( $fine_unit, $start_date, $end_date, $branchcode ); + my $units_minus_grace = $chargeable_units - ( $issuing_rule->{firstremind} || 0 ); + my $amount = 0; if ( $issuing_rule->{chargeperiod} && ( $units_minus_grace > 0 ) ) { my $units = C4::Context->preference('FinesIncludeGracePeriod') ? $chargeable_units : $units_minus_grace; my $charge_periods = $units / $issuing_rule->{chargeperiod}; + # If chargeperiod_charge_at = 1, we charge a fine at the start of each charge period # if chargeperiod_charge_at = 0, we charge at the end of each charge period - $charge_periods = defined $issuing_rule->{chargeperiod_charge_at} && $issuing_rule->{chargeperiod_charge_at} == 1 ? ceil($charge_periods) : floor($charge_periods); + $charge_periods = defined $issuing_rule->{chargeperiod_charge_at} + && $issuing_rule->{chargeperiod_charge_at} == 1 ? ceil($charge_periods) : floor($charge_periods); # check if item has been recalled. recall should have been marked Overdue by cronjob, so only look at overdue recalls # only charge using recall_overdue_fine if there is an item-level recall for this particular item, OR a biblio-level recall - my @recalls = Koha::Recalls->search({ biblio_id => $item->{biblionumber}, status => 'overdue' })->as_list; + my @recalls = Koha::Recalls->search( { biblio_id => $item->{biblionumber}, status => 'overdue' } )->as_list; my $bib_level_recall = 0; $bib_level_recall = 1 if scalar @recalls > 0; - foreach my $recall ( @recalls ) { - if ( $recall->item_level and $recall->item_id == $item->{itemnumber} and $issuing_rule->{recall_overdue_fine} ) { + foreach my $recall (@recalls) { + if ( $recall->item_level + and $recall->item_id == $item->{itemnumber} + and $issuing_rule->{recall_overdue_fine} ) + { $bib_level_recall = 0; - $amount = $charge_periods * $issuing_rule->{recall_overdue_fine}; + $amount = $charge_periods * $issuing_rule->{recall_overdue_fine}; last; } } if ( $bib_level_recall and $issuing_rule->{recall_overdue_fine} ) { + # biblio-level recall $amount = $charge_periods * $issuing_rule->{recall_overdue_fine}; } - if ( scalar @recalls == 0 && $issuing_rule->{fine}) { + if ( scalar @recalls == 0 && $issuing_rule->{fine} ) { + # no recall, use normal fine amount $amount = $charge_periods * $issuing_rule->{fine}; } - } # else { # a zero (or null) chargeperiod or negative units_minus_grace value means no charge. } + } # else { # a zero (or null) chargeperiod or negative units_minus_grace value means no charge. } $amount = $issuing_rule->{overduefinescap} if $issuing_rule->{overduefinescap} @@ -295,12 +302,14 @@ sub CalcFine { $item->{replacementprice} = $itemtype->defaultreplacecost; } - $amount = $item->{replacementprice} if ( $issuing_rule->{cap_fine_to_replacement_price} && $item->{replacementprice} && $amount > $item->{replacementprice} ); + $amount = $item->{replacementprice} + if ( $issuing_rule->{cap_fine_to_replacement_price} + && $item->{replacementprice} + && $amount > $item->{replacementprice} ); - return ($amount, $units_minus_grace, $chargeable_units); + return ( $amount, $units_minus_grace, $chargeable_units ); } - =head2 get_chargeable_units get_chargeable_units($unit, $start_date_ $end_date, $branchcode); @@ -316,37 +325,35 @@ C<$branchcode> is the branch whose calendar to use for finding holidays. =cut sub get_chargeable_units { - my ($unit, $date_due, $date_returned, $branchcode) = @_; + my ( $unit, $date_due, $date_returned, $branchcode ) = @_; # If the due date is later than the return date return 0 unless ( $date_returned > $date_due ); my $charge_units = 0; my $charge_duration; - if ($unit eq 'hours') { - if(C4::Context->preference('finesCalendar') eq 'noFinesWhenClosed') { + if ( $unit eq 'hours' ) { + if ( C4::Context->preference('finesCalendar') eq 'noFinesWhenClosed' ) { my $calendar = Koha::Calendar->new( branchcode => $branchcode ); $charge_duration = $calendar->hours_between( $date_due, $date_returned ); } else { - $charge_duration = $date_returned->delta_ms( $date_due ); + $charge_duration = $date_returned->delta_ms($date_due); } - if($charge_duration->in_units('hours') == 0 && $charge_duration->in_units('seconds') > 0){ + if ( $charge_duration->in_units('hours') == 0 && $charge_duration->in_units('seconds') > 0 ) { return 1; } return $charge_duration->in_units('hours'); - } - else { # days - if(C4::Context->preference('finesCalendar') eq 'noFinesWhenClosed') { + } else { # days + if ( C4::Context->preference('finesCalendar') eq 'noFinesWhenClosed' ) { my $calendar = Koha::Calendar->new( branchcode => $branchcode ); $charge_duration = $calendar->days_between( $date_due, $date_returned ); } else { - $charge_duration = $date_returned->delta_days( $date_due ); + $charge_duration = $date_returned->delta_days($date_due); } return $charge_duration->in_units('days'); } } - =head2 GetSpecialHolidays &GetSpecialHolidays($date_dues,$itemnumber); @@ -369,9 +376,8 @@ sub GetSpecialHolidays { my $iteminfo = GetIssuesIteminfo($itemnumber); # use sql request to find all date between date_due and today - my $dbh = C4::Context->dbh; - my $query = - qq|SELECT DATE_FORMAT(concat(year,'-',month,'-',day),'%Y-%m-%d') as date + my $dbh = C4::Context->dbh; + my $query = qq|SELECT DATE_FORMAT(concat(year,'-',month,'-',day),'%Y-%m-%d') as date FROM `special_holidays` WHERE DATE_FORMAT(concat(year,'-',month,'-',day),'%Y-%m-%d') >= ? AND DATE_FORMAT(concat(year,'-',month,'-',day),'%Y-%m-%d') <= ? @@ -383,7 +389,7 @@ AND branchcode=? my $dateinsec; my $sth = $dbh->prepare($query); $sth->execute( $date_dues, $today, $iteminfo->{'branchcode'} ) - ; # FIXME: just use NOW() in SQL instead of passing in $today + ; # FIXME: just use NOW() in SQL instead of passing in $today while ( my $special_date = $sth->fetchrow_hashref ) { push( @result_date, $special_date ); @@ -393,8 +399,7 @@ AND branchcode=? for ( my $i = 0 ; $i < scalar(@result_date) ; $i++ ) { $dateinsec = UnixDate( $result_date[$i]->{'date'}, "%o" ); - ( undef, undef, undef, undef, undef, undef, $wday, undef, undef ) = - localtime($dateinsec); + ( undef, undef, undef, undef, undef, undef, $wday, undef, undef ) = localtime($dateinsec); for ( my $j = 0 ; $j < scalar(@result) ; $j++ ) { if ( $wday == ( $result[$j]->{'weekday'} ) ) { $specialdaycount--; @@ -422,8 +427,7 @@ C<$difference> numbers of between day date of the day and date due sub GetRepeatableHolidays { my ( $date_dues, $itemnumber, $difference ) = @_; my $dateinsec = UnixDate( $date_dues, "%o" ); - my ( $sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst ) = - localtime($dateinsec); + my ( $sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst ) = localtime($dateinsec); my @result = GetWdayFromItemnumber($itemnumber); my @dayclosedcount; my $j; @@ -442,7 +446,6 @@ sub GetRepeatableHolidays { return scalar(@dayclosedcount); } - =head2 GetWayFromItemnumber &Getwdayfromitemnumber($itemnumber); @@ -470,7 +473,6 @@ sub GetWdayFromItemnumber { return @result; } - =head2 GetIssuesIteminfo &GetIssuesIteminfo($itemnumber); @@ -494,7 +496,6 @@ sub GetIssuesIteminfo { return $issuesinfo; } - =head2 UpdateFine &UpdateFine( @@ -543,32 +544,36 @@ sub UpdateFine { my $amount = $params->{amount}; my $due = $params->{due} // q{}; - unless ( $issue_id ) { + unless ($issue_id) { carp("No issue_id passed in!"); return; } - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $overdues = Koha::Account::Lines->search( { - borrowernumber => $borrowernumber, - debit_type_code => 'OVERDUE' + borrowernumber => $borrowernumber, + debit_type_code => 'OVERDUE' } ); my $accountline; my $total_amount_other = 0.00; + # Cycle through the fines and # - find line that relates to the requested $itemnum # - accumulate fines for other items # so we can update $itemnum fine taking in account fine caps - while (my $overdue = $overdues->next) { - if ( defined $overdue->checkout && $overdue->checkout->issue_id == $issue_id && $overdue->status eq 'UNRETURNED' ) { + while ( my $overdue = $overdues->next ) { + if ( defined $overdue->checkout + && $overdue->checkout->issue_id == $issue_id + && $overdue->status eq 'UNRETURNED' ) + { if ($accountline) { - Koha::Logger->get->debug("Not a unique accountlines record for issue_id $issue_id"); # FIXME Do we really need to log that? - #FIXME Should we still count this one in total_amount ?? - } - else { + Koha::Logger->get->debug("Not a unique accountlines record for issue_id $issue_id") + ; # FIXME Do we really need to log that? + #FIXME Should we still count this one in total_amount ?? + } else { $accountline = $overdue; } } @@ -581,18 +586,21 @@ sub UpdateFine { if ($accountline) { if ( ( $amount - $accountline->amount ) > $maxIncrease ) { my $new_amount = $accountline->amount + $maxIncrease; - Koha::Logger->get->debug("Reducing fine for item $itemnum borrower $borrowernumber from $amount to $new_amount - MaxFine reached"); + Koha::Logger->get->debug( + "Reducing fine for item $itemnum borrower $borrowernumber from $amount to $new_amount - MaxFine reached" + ); $amount = $new_amount; } - } - elsif ( $amount > $maxIncrease ) { - Koha::Logger->get->debug("Reducing fine for item $itemnum borrower $borrowernumber from $amount to $maxIncrease - MaxFine reached"); + } elsif ( $amount > $maxIncrease ) { + Koha::Logger->get->debug( + "Reducing fine for item $itemnum borrower $borrowernumber from $amount to $maxIncrease - MaxFine reached" + ); $amount = $maxIncrease; } } - if ( $accountline ) { - if ( Koha::Number::Price->new($accountline->amount)->round != Koha::Number::Price->new($amount)->round ) { + if ($accountline) { + if ( Koha::Number::Price->new( $accountline->amount )->round != Koha::Number::Price->new($amount)->round ) { $accountline->adjust( { amount => $amount, @@ -602,22 +610,24 @@ sub UpdateFine { ); } } else { - if ( $amount ) { # Don't add new fines with an amount of 0 - my $patron = Koha::Patrons->find( $borrowernumber ); - my $letter = eval { C4::Letters::GetPreparedLetter( - module => 'circulation', - letter_code => 'OVERDUE_FINE_DESC', - message_transport_type => 'print', - lang => $patron->lang, - tables => { - issues => $itemnum, - borrowers => $borrowernumber, - items => $itemnum, - }, - ) }; - my $desc = $letter ? $letter->{content} : sprintf("Item %s - due %s", $itemnum, output_pref($due) ); + if ($amount) { # Don't add new fines with an amount of 0 + my $patron = Koha::Patrons->find($borrowernumber); + my $letter = eval { + C4::Letters::GetPreparedLetter( + module => 'circulation', + letter_code => 'OVERDUE_FINE_DESC', + message_transport_type => 'print', + lang => $patron->lang, + tables => { + issues => $itemnum, + borrowers => $borrowernumber, + items => $itemnum, + }, + ); + }; + my $desc = $letter ? $letter->{content} : sprintf( "Item %s - due %s", $itemnum, output_pref($due) ); - my $account = Koha::Account->new({ patron_id => $borrowernumber }); + my $account = Koha::Account->new( { patron_id => $borrowernumber } ); $accountline = $account->add_debit( { amount => $amount, @@ -625,7 +635,7 @@ sub UpdateFine { note => undef, user_id => undef, interface => C4::Context->interface, - library_id => undef, #FIXME: Should we grab the checkout or circ-control branch here perhaps? + library_id => undef, #FIXME: Should we grab the checkout or circ-control branch here perhaps? type => 'OVERDUE', item_id => $itemnum, issue_id => $issue_id, @@ -655,15 +665,14 @@ sub GetFine { AND amountoutstanding > 0 AND borrowernumber=?|; my @query_param; push @query_param, $borrowernumber; - if (defined $itemnum ) - { + if ( defined $itemnum ) { $query .= " AND itemnumber=?"; push @query_param, $itemnum; } my $sth = $dbh->prepare($query); - $sth->execute( @query_param ); + $sth->execute(@query_param); my $fine = $sth->fetchrow_hashref(); - if ($fine->{fineamount}) { + if ( $fine->{fineamount} ) { return $fine->{fineamount}; } return 0; @@ -678,16 +687,19 @@ returns a list of branch codes for branches with overdue rules defined. =cut sub GetBranchcodesWithOverdueRules { - my $dbh = C4::Context->dbh; - my $branchcodes = $dbh->selectcol_arrayref(q| + my $dbh = C4::Context->dbh; + my $branchcodes = $dbh->selectcol_arrayref( + q| SELECT DISTINCT(branchcode) FROM overduerules WHERE delay1 IS NOT NULL ORDER BY branchcode - |); + | + ); if ( defined $branchcodes->[0] && $branchcodes->[0] eq '' ) { + # If a default rule exists, all branches should be returned - return Koha::Libraries->search({}, { order_by => 'branchname' })->get_column('branchcode'); + return Koha::Libraries->search( {}, { order_by => 'branchname' } )->get_column('branchcode'); } return @$branchcodes; } @@ -703,10 +715,10 @@ FIXME: This function should be renamed. =cut sub GetOverduesForBranch { - my ( $branch, $location) = @_; - my $itype_link = (C4::Context->preference('item-level_itypes')) ? " items.itype " : " biblioitems.itemtype "; - my $dbh = C4::Context->dbh; - my $select = " + my ( $branch, $location ) = @_; + my $itype_link = ( C4::Context->preference('item-level_itypes') ) ? " items.itype " : " biblioitems.itemtype "; + my $dbh = C4::Context->dbh; + my $select = " SELECT borrowers.cardnumber, borrowers.borrowernumber, @@ -749,10 +761,10 @@ sub GetOverduesForBranch { "; if ($location) { my $q = "$select AND items.location = ? ORDER BY borrowers.surname, borrowers.firstname"; - return @{ $dbh->selectall_arrayref($q, { Slice => {} }, $branch, $location ) }; + return @{ $dbh->selectall_arrayref( $q, { Slice => {} }, $branch, $location ) }; } else { my $q = "$select ORDER BY borrowers.surname, borrowers.firstname"; - return @{ $dbh->selectall_arrayref($q, { Slice => {} }, $branch ) }; + return @{ $dbh->selectall_arrayref( $q, { Slice => {} }, $branch ) }; } } @@ -768,13 +780,13 @@ sub GetOverdueMessageTransportTypes { my ( $branchcode, $categorycode, $letternumber ) = @_; return unless $categorycode and $letternumber; my $dbh = C4::Context->dbh; - my $sth = $dbh->prepare(" + my $sth = $dbh->prepare( " SELECT message_transport_type FROM overduerules odr LEFT JOIN overduerules_transport_types ott USING (overduerules_id) WHERE branchcode = ? AND categorycode = ? AND letternumber = ? - "); + " ); $sth->execute( $branchcode, $categorycode, $letternumber ); my @mtts; while ( my $mtt = $sth->fetchrow ) { @@ -828,31 +840,32 @@ sub parse_overdues_letter { my @item_tables; if ( my $i = $params->{'items'} ) { foreach my $item (@$i) { - my $fine = GetFine($item->{'itemnumber'}, $params->{'borrowernumber'}); - $item->{'fine'} = currency_format($currency_format, "$fine", FMT_SYMBOL); + my $fine = GetFine( $item->{'itemnumber'}, $params->{'borrowernumber'} ); + $item->{'fine'} = currency_format( $currency_format, "$fine", FMT_SYMBOL ); + # if active currency isn't correct ISO code fallback to sprintf - $item->{'fine'} = sprintf('%.2f', $fine) unless $item->{'fine'}; + $item->{'fine'} = sprintf( '%.2f', $fine ) unless $item->{'fine'}; push @item_tables, { - 'biblio' => $item->{'biblionumber'}, + 'biblio' => $item->{'biblionumber'}, 'biblioitems' => $item->{'biblionumber'}, - 'items' => $item, - 'issues' => $item->{'itemnumber'}, + 'items' => $item, + 'issues' => $item->{'itemnumber'}, }; } } - return C4::Letters::GetPreparedLetter ( - module => 'circulation', + return C4::Letters::GetPreparedLetter( + module => 'circulation', letter_code => $params->{'letter_code'}, - branchcode => $params->{'branchcode'}, - lang => $patron->lang, - tables => \%tables, - loops => { + branchcode => $params->{'branchcode'}, + lang => $patron->lang, + tables => \%tables, + loops => { overdues => [ map { $_->{items}->{itemnumber} } @item_tables ], }, - substitute => $substitute, - repeat => { item => \@item_tables }, + substitute => $substitute, + repeat => { item => \@item_tables }, message_transport_type => $params->{message_transport_type}, ); } diff --git a/C4/Patroncards.pm b/C4/Patroncards.pm index 7358b29075..c9f3574b79 100644 --- a/C4/Patroncards.pm +++ b/C4/Patroncards.pm @@ -6,26 +6,26 @@ BEGIN { use vars qw(@EXPORT @ISA); @ISA = qw(Exporter); our @EXPORT = qw(unpack_UTF8 - text_alignment - leading - box - get_borrower_attributes - put_image - get_image - rm_image + text_alignment + leading + box + get_borrower_attributes + put_image + get_image + rm_image ); use C4::Patroncards::Batch; use C4::Patroncards::Layout; use C4::Patroncards::Lib qw( - box - get_borrower_attributes - get_image - leading - put_image - rm_image - text_alignment - unpack_UTF8 -); + box + get_borrower_attributes + get_image + leading + put_image + rm_image + text_alignment + unpack_UTF8 + ); use C4::Patroncards::Patroncard; use C4::Patroncards::Profile; use C4::Patroncards::Template; diff --git a/C4/Patroncards/Batch.pm b/C4/Patroncards/Batch.pm index 8982fce386..30004b737a 100644 --- a/C4/Patroncards/Batch.pm +++ b/C4/Patroncards/Batch.pm @@ -7,7 +7,6 @@ use base qw(C4::Creators::Batch); use autouse 'Data::Dumper' => qw(Dumper); - __PACKAGE__ =~ m/^C4::(.+)::.+$/; my $me = $1; @@ -30,14 +29,13 @@ sub retrieve { } sub delete { - if (ref($_[0])) { - my $self = shift; # check to see if this is a method call + if ( ref( $_[0] ) ) { + my $self = shift; # check to see if this is a method call push @_, "creator", $me; return $self->SUPER::delete(@_); - } - else { + } else { push @_, "creator", $me; - return __PACKAGE__->SUPER::delete(@_); # XXX: is this too hackish? + return __PACKAGE__->SUPER::delete(@_); # XXX: is this too hackish? } } diff --git a/C4/Patroncards/Layout.pm b/C4/Patroncards/Layout.pm index 4c2dc218bc..f8f4d40aaf 100644 --- a/C4/Patroncards/Layout.pm +++ b/C4/Patroncards/Layout.pm @@ -7,7 +7,6 @@ use base qw(C4::Creators::Layout); use autouse 'Data::Dumper' => qw(Dumper); - __PACKAGE__ =~ m/^C4::(.+)::.+$/; my $me = $1; @@ -30,14 +29,13 @@ sub retrieve { } sub delete { - if (ref($_[0])) { - my $self = shift; # check to see if this is a method call + if ( ref( $_[0] ) ) { + my $self = shift; # check to see if this is a method call push @_, "creator", $me; return $self->SUPER::delete(@_); - } - else { + } else { push @_, "creator", $me; - return __PACKAGE__->SUPER::delete(@_); # XXX: is this too hackish? + return __PACKAGE__->SUPER::delete(@_); # XXX: is this too hackish? } } diff --git a/C4/Patroncards/Lib.pm b/C4/Patroncards/Lib.pm index 3f31a4d252..6f0472e17e 100644 --- a/C4/Patroncards/Lib.pm +++ b/C4/Patroncards/Lib.pm @@ -25,57 +25,55 @@ use C4::Context; BEGIN { use base qw(Exporter); our @EXPORT = qw(unpack_UTF8 - text_alignment - leading - box - get_borrower_attributes - put_image - get_image - rm_image + text_alignment + leading + box + get_borrower_attributes + put_image + get_image + rm_image ); } sub unpack_UTF8 { my ($str) = @_; - my @UTF8 = (unpack("U0U*", $str)); - my @HEX = map { sprintf '%2.2x', $_ } @UTF8; + my @UTF8 = ( unpack( "U0U*", $str ) ); + my @HEX = map { sprintf '%2.2x', $_ } @UTF8; return \@HEX; } sub text_alignment { - my ($origin_llx, $text_box_width, $text_llx, $string_width, $line, $alignment) = @_; + my ( $origin_llx, $text_box_width, $text_llx, $string_width, $line, $alignment ) = @_; my $Tw = 0; my $Tx = 0; - if ($alignment eq 'J') { - my $UTF82HEX = unpack_UTF8($line); + if ( $alignment eq 'J' ) { + my $UTF82HEX = unpack_UTF8($line); my $space_count = 0; - grep {$space_count++ if $_ eq '20'} @$UTF82HEX; - $Tw = (($text_box_width - $text_llx) - $string_width) / $space_count; + grep { $space_count++ if $_ eq '20' } @$UTF82HEX; + $Tw = ( ( $text_box_width - $text_llx ) - $string_width ) / $space_count; return $origin_llx, $Tw; - } - elsif ($alignment eq 'C') { - my $center_margin = ($text_box_width / 2) + ($origin_llx - $text_llx); - $Tx = $center_margin - ($string_width / 2); + } elsif ( $alignment eq 'C' ) { + my $center_margin = ( $text_box_width / 2 ) + ( $origin_llx - $text_llx ); + $Tx = $center_margin - ( $string_width / 2 ); return $Tx, $Tw; - } - elsif ($alignment eq 'R') { - $Tx = ($text_box_width - $string_width) + (($origin_llx - $text_llx) / 2); + } elsif ( $alignment eq 'R' ) { + $Tx = ( $text_box_width - $string_width ) + ( ( $origin_llx - $text_llx ) / 2 ); return $Tx, $Tw; - } - elsif ($alignment eq 'L') { + } elsif ( $alignment eq 'L' ) { return $origin_llx, $Tw; - } - else { # if we are not handed an alignment default to left align text... + } else { # if we are not handed an alignment default to left align text... return $origin_llx, $Tw; } } sub leading { - return $_[0] + ($_[0] * 0.20); # recommended starting point for leading is 20% of the font point size (See http://www.bastoky.com/KeyRelations.htm) + return $_[0] + + ( $_[0] * 0.20 ) + ; # recommended starting point for leading is 20% of the font point size (See http://www.bastoky.com/KeyRelations.htm) } sub box { - my ($llx, $lly, $width, $height, $pdf) = @_; + my ( $llx, $lly, $width, $height, $pdf ) = @_; my $obj_stream = "q\n"; # save the graphic state $obj_stream .= "0.5 w\n"; # border line width $obj_stream .= "1.0 0.0 0.0 RG\n"; # border color red @@ -87,30 +85,31 @@ sub box { } sub get_borrower_attributes { - my ($borrower_number, @fields) = @_; + my ( $borrower_number, @fields ) = @_; my $get_branch = 0; - $get_branch = 1 if grep{$_ eq 'branchcode'} @fields; + $get_branch = 1 if grep { $_ eq 'branchcode' } @fields; my $attrib_count = scalar(@fields); - my $query = "SELECT "; - while (scalar(@fields)) { + my $query = "SELECT "; + while ( scalar(@fields) ) { $query .= shift(@fields); $query .= ', ' if scalar(@fields); } $query .= " FROM borrowers WHERE borrowernumber = ?"; my $sth = C4::Context->dbh->prepare($query); -# $sth->{'TraceLevel'} = 3; + + # $sth->{'TraceLevel'} = 3; $sth->execute($borrower_number); - if ($sth->err) { - warn sprintf('Database returned the following error: %s', $sth->errstr); + if ( $sth->err ) { + warn sprintf( 'Database returned the following error: %s', $sth->errstr ); return 1; } my $borrower_attributes = $sth->fetchrow_hashref(); if ($get_branch) { $query = "SELECT branchname FROM branches WHERE branchcode = ?"; - $sth = C4::Context->dbh->prepare($query); - $sth->execute($borrower_attributes->{'branchcode'}); - if ($sth->err) { - warn sprintf('Database returned the following error: %s', $sth->errstr); + $sth = C4::Context->dbh->prepare($query); + $sth->execute( $borrower_attributes->{'branchcode'} ); + if ( $sth->err ) { + warn sprintf( 'Database returned the following error: %s', $sth->errstr ); return 1; } $borrower_attributes->{'branchcode'} = $sth->fetchrow_hashref()->{'branchname'}; @@ -119,62 +118,61 @@ sub get_borrower_attributes { } sub put_image { - my ($image_name, $image_file) = @_; - if (my $image_limit = C4::Context->preference('ImageLimit')) { # enforce quota if set + my ( $image_name, $image_file ) = @_; + if ( my $image_limit = C4::Context->preference('ImageLimit') ) { # enforce quota if set my $query = "SELECT count(*) FROM creator_images;"; - my $sth = C4::Context->dbh->prepare($query); + my $sth = C4::Context->dbh->prepare($query); $sth->execute(); - if ($sth->err) { - warn sprintf('Database returned the following error: %s', $sth->errstr); + if ( $sth->err ) { + warn sprintf( 'Database returned the following error: %s', $sth->errstr ); return 1; } return 202 if $sth->fetchrow_array >= $image_limit; } - my$query = "INSERT INTO creator_images (imagefile, image_name) VALUES (?,?) ON DUPLICATE KEY UPDATE imagefile = ?;"; + my $query = + "INSERT INTO creator_images (imagefile, image_name) VALUES (?,?) ON DUPLICATE KEY UPDATE imagefile = ?;"; my $sth = C4::Context->dbh->prepare($query); - $sth->execute($image_file, $image_name, $image_file); - if ($sth->err) { - warn sprintf('Database returned the following error: %s', $sth->errstr); + $sth->execute( $image_file, $image_name, $image_file ); + if ( $sth->err ) { + warn sprintf( 'Database returned the following error: %s', $sth->errstr ); return 1; } return; } sub get_image { - my ($image_name, $fields) = @_; + my ( $image_name, $fields ) = @_; $fields = '*' unless $fields; my $query = "SELECT $fields FROM creator_images"; $query .= " WHERE image_name = ?" if $image_name; my $sth = C4::Context->dbh->prepare($query); if ($image_name) { $sth->execute($image_name); - } - else { + } else { $sth->execute(); } - if ($sth->err) { - warn sprintf('Database returned the following error: %s', $sth->errstr); + if ( $sth->err ) { + warn sprintf( 'Database returned the following error: %s', $sth->errstr ); return 1; } - return $sth->fetchall_arrayref({}); + return $sth->fetchall_arrayref( {} ); } sub rm_image { my $image_ids = shift; - my $errstr = (); + my $errstr = (); foreach my $image_id (@$image_ids) { my $query = "DELETE FROM creator_images WHERE image_id = ?"; - my $sth = C4::Context->dbh->prepare($query); + my $sth = C4::Context->dbh->prepare($query); $sth->execute($image_id); - if ($sth->err) { - warn sprintf('Database returned the following error: %s', $sth->errstr); - push (@$errstr, $image_id); + if ( $sth->err ) { + warn sprintf( 'Database returned the following error: %s', $sth->errstr ); + push( @$errstr, $image_id ); } } if ($errstr) { return $errstr; - } - else { + } else { return; } } diff --git a/C4/Patroncards/Patroncard.pm b/C4/Patroncards/Patroncard.pm index ee5c73e352..f28f362e6c 100644 --- a/C4/Patroncards/Patroncard.pm +++ b/C4/Patroncards/Patroncard.pm @@ -21,10 +21,11 @@ use strict; use warnings; use autouse 'Data::Dumper' => qw(Dumper); + #use Font::TTFMetrics; -use C4::Creators::Lib qw( get_unit_values ); -use C4::Creators::PDF qw(StrWidth); +use C4::Creators::Lib qw( get_unit_values ); +use C4::Creators::PDF qw(StrWidth); use C4::Patroncards::Lib qw( box get_borrower_attributes @@ -54,35 +55,36 @@ C4::Patroncards::Patroncard =cut sub new { - my ($invocant, %params) = @_; + my ( $invocant, %params ) = @_; my $type = ref($invocant) || $invocant; - my $units = get_unit_values(); + my $units = get_unit_values(); my $unitvalue = 1; - my $unitdesc = ''; - foreach my $un (@$units){ - if ($un->{'type'} eq $params{'layout'}->{'units'}) { + my $unitdesc = ''; + foreach my $un (@$units) { + if ( $un->{'type'} eq $params{'layout'}->{'units'} ) { $unitvalue = $un->{'value'}; - $unitdesc = $un->{'desc'}; + $unitdesc = $un->{'desc'}; } } my $self = { - batch_id => $params{'batch_id'}, + batch_id => $params{'batch_id'}, + #card_number => $params{'card_number'}, - borrower_number => $params{'borrower_number'}, - llx => $params{'llx'}, - lly => $params{'lly'}, - height => $params{'height'}, - width => $params{'width'}, - layout => $params{'layout'}, - unitvalue => $unitvalue, - unitdesc => $unitdesc, - text_wrap_cols => $params{'text_wrap_cols'}, - barcode_height_scale => $params{'layout'}->{'barcode'}[0]->{'height_scale'} || 0.01, - barcode_width_scale => $params{'layout'}->{'barcode'}[0]->{'width_scale'} || 0.8, + borrower_number => $params{'borrower_number'}, + llx => $params{'llx'}, + lly => $params{'lly'}, + height => $params{'height'}, + width => $params{'width'}, + layout => $params{'layout'}, + unitvalue => $unitvalue, + unitdesc => $unitdesc, + text_wrap_cols => $params{'text_wrap_cols'}, + barcode_height_scale => $params{'layout'}->{'barcode'}[0]->{'height_scale'} || 0.01, + barcode_width_scale => $params{'layout'}->{'barcode'}[0]->{'width_scale'} || 0.8, }; - bless ($self, $type); + bless( $self, $type ); return $self; } @@ -96,9 +98,9 @@ sub draw_barcode { # Default values for barcode scaling are set in constructor to work with pre-existing installations my $barcode_height_scale = $self->{'barcode_height_scale'}; my $barcode_width_scale = $self->{'barcode_width_scale'}; - my $llx = $self->{'llx'} || 0; + my $llx = $self->{'llx'} || 0; my $llx_layout = $self->{'layout'}->{'barcode'}->[0]->{'llx'} || 0; - my $lly = $self->{'lly'} || 0; + my $lly = $self->{'lly'} || 0; my $lly_layout = $self->{'layout'}->{'barcode'}->[0]->{'lly'} || 0; _draw_barcode( $self, @@ -117,16 +119,16 @@ sub draw_barcode { =cut sub draw_guide_box { - my ($self, $pdf) = @_; + my ( $self, $pdf ) = @_; warn sprintf('No pdf object passed in.') and return -1 if !$pdf; - my $obj_stream = "q\n"; # save the graphic state - $obj_stream .= "0.5 w\n"; # border line width - $obj_stream .= "1.0 0.0 0.0 RG\n"; # border color red - $obj_stream .= "1.0 1.0 1.0 rg\n"; # fill color white - $obj_stream .= "$self->{'llx'} $self->{'lly'} $self->{'width'} $self->{'height'} re\n"; # a rectangle - $obj_stream .= "B\n"; # fill (and a little more) - $obj_stream .= "Q\n"; # restore the graphic state + my $obj_stream = "q\n"; # save the graphic state + $obj_stream .= "0.5 w\n"; # border line width + $obj_stream .= "1.0 0.0 0.0 RG\n"; # border color red + $obj_stream .= "1.0 1.0 1.0 rg\n"; # fill color white + $obj_stream .= "$self->{'llx'} $self->{'lly'} $self->{'width'} $self->{'height'} re\n"; # a rectangle + $obj_stream .= "B\n"; # fill (and a little more) + $obj_stream .= "Q\n"; # restore the graphic state $pdf->Add($obj_stream); } @@ -139,21 +141,26 @@ Adds a grid to the PDF output ($pdf) to support layout design =cut sub draw_guide_grid { - my ($self, $pdf) = @_; + my ( $self, $pdf ) = @_; warn sprintf('No pdf object passed in.') and return -1 if !$pdf; # Set up the grid in user defined units. # Each 5th and 10th line get separate values - my $obj_stream = "q\n"; # save the graphic state - my $x = $self->{'llx'}; - my $y = $self->{'lly'}; + my $obj_stream = "q\n"; # save the graphic state + my $x = $self->{'llx'}; + my $y = $self->{'lly'}; my $cnt = 0; - for ( $x = $self->{'llx'}/$self->{'unitvalue'}; $x <= ($self->{'llx'} + $self->{'width'})/$self->{'unitvalue'}; $x++) { - my $xx = $x*$self->{'unitvalue'}; + for ( + $x = $self->{'llx'} / $self->{'unitvalue'} ; + $x <= ( $self->{'llx'} + $self->{'width'} ) / $self->{'unitvalue'} ; + $x++ + ) + { + my $xx = $x * $self->{'unitvalue'}; my $yy = $y + $self->{'height'}; - if ( ($cnt % 10) && ! ($cnt % 5) ) { + if ( ( $cnt % 10 ) && !( $cnt % 5 ) ) { $obj_stream .= "0.0 1.0 0.0 RG\n"; $obj_stream .= "0 w\n"; } elsif ( $cnt % 5 ) { @@ -163,7 +170,7 @@ sub draw_guide_grid { $obj_stream .= "0.0 0.0 1.0 RG\n"; $obj_stream .= "0 w\n"; } - $cnt ++; + $cnt++; $obj_stream .= "$xx $y m\n"; $obj_stream .= "$xx $yy l\n"; @@ -171,15 +178,20 @@ sub draw_guide_grid { $obj_stream .= "s\n"; } - $x = $self->{'llx'}; - $y = $self->{'lly'}; + $x = $self->{'llx'}; + $y = $self->{'lly'}; $cnt = 0; - for ( $y = $self->{'lly'}/$self->{'unitvalue'}; $y <= ($self->{'lly'} + $self->{'height'})/$self->{'unitvalue'}; $y++) { + for ( + $y = $self->{'lly'} / $self->{'unitvalue'} ; + $y <= ( $self->{'lly'} + $self->{'height'} ) / $self->{'unitvalue'} ; + $y++ + ) + { my $xx = $x + $self->{'width'}; - my $yy = $y*$self->{'unitvalue'}; + my $yy = $y * $self->{'unitvalue'}; - if ( ($cnt % 10) && ! ($cnt % 5) ) { + if ( ( $cnt % 10 ) && !( $cnt % 5 ) ) { $obj_stream .= "0.0 1.0 0.0 RG\n"; $obj_stream .= "0 w\n"; } elsif ( $cnt % 5 ) { @@ -189,25 +201,29 @@ sub draw_guide_grid { $obj_stream .= "0.0 0.0 1.0 RG\n"; $obj_stream .= "0 w\n"; } - $cnt ++; + $cnt++; $obj_stream .= "$x $yy m\n"; $obj_stream .= "$xx $yy l\n"; $obj_stream .= "s\n"; } - $obj_stream .= "Q\n"; # restore the graphic state + $obj_stream .= "Q\n"; # restore the graphic state $pdf->Add($obj_stream); # Add info about units my $strbottom = "0/0 $self->{'unitdesc'}"; - my $strtop = sprintf('%.2f', $self->{'width'}/$self->{'unitvalue'}) .'/'. sprintf('%.2f', $self->{'height'}/$self->{'unitvalue'}); + my $strtop = sprintf( '%.2f', $self->{'width'} / $self->{'unitvalue'} ) . '/' + . sprintf( '%.2f', $self->{'height'} / $self->{'unitvalue'} ); my $font_size = 6; - $pdf->Font( 'Courier' ); - $pdf->FontSize( $font_size ); + $pdf->Font('Courier'); + $pdf->FontSize($font_size); my $strtop_len = $pdf->StrWidth($strtop) * 1.5; $pdf->Text( $self->{'llx'} + 2, $self->{'lly'} + 2, $strbottom ); - $pdf->Text( $self->{'llx'} + $self->{'width'} - $strtop_len , $self->{'lly'} + $self->{'height'} - $font_size , $strtop ); + $pdf->Text( + $self->{'llx'} + $self->{'width'} - $strtop_len, $self->{'lly'} + $self->{'height'} - $font_size, + $strtop + ); } =head2 draw_text @@ -219,55 +235,57 @@ Draws text to PDF output ($pdf) =cut sub draw_text { - my ($self, $pdf, %params) = @_; + my ( $self, $pdf, %params ) = @_; warn sprintf('No pdf object passed in.') and return -1 if !$pdf; my @card_text = (); - return unless (ref($self->{'layout'}->{'text'}) eq 'ARRAY'); # just in case there is not text + return unless ( ref( $self->{'layout'}->{'text'} ) eq 'ARRAY' ); # just in case there is not text - my $text = [@{$self->{'layout'}->{'text'}}]; # make a copy of the arrayref *not* simply a pointer - while (scalar @$text) { - my $line = shift @$text; + my $text = [ @{ $self->{'layout'}->{'text'} } ]; # make a copy of the arrayref *not* simply a pointer + while ( scalar @$text ) { + my $line = shift @$text; my $parse_line = $line; - my @orig_line = split(/ /,$line); - if ($parse_line =~ m/<[A-Za-z0-9_]+>/) { # test to see if the line has db fields embedded... + my @orig_line = split( / /, $line ); + if ( $parse_line =~ m/<[A-Za-z0-9_]+>/ ) { # test to see if the line has db fields embedded... my @fields = (); - while ($parse_line =~ m/<([A-Za-z0-9_]+)>(.*$)/) { - push (@fields, $1); + while ( $parse_line =~ m/<([A-Za-z0-9_]+)>(.*$)/ ) { + push( @fields, $1 ); $parse_line = $2; } - my $borrower_attributes = get_borrower_attributes($self->{'borrower_number'},@fields); - @orig_line = map { # substitute data for db fields + my $borrower_attributes = get_borrower_attributes( $self->{'borrower_number'}, @fields ); + @orig_line = map { # substitute data for db fields my $l = $_; - if ($l =~ m/<([A-Za-z0-9_]+)>/) { + if ( $l =~ m/<([A-Za-z0-9_]+)>/ ) { my $field = $1; $l =~ s/$l/$borrower_attributes->{$field}/; } $l; } @orig_line; - $line = join(' ',@orig_line); + $line = join( ' ', @orig_line ); } my $text_attribs = shift @$text; - my $llx = $self->{'llx'} || 0; + my $llx = $self->{'llx'} || 0; my $llx_text_attr = $text_attribs->{'llx'} || 0; - my $lly = $self->{'lly'} || 0; + my $lly = $self->{'lly'} || 0; my $lly_text_attr = $text_attribs->{'lly'} || 0; my $origin_llx = $llx + $llx_text_attr * $self->{'unitvalue'}; my $origin_lly = $lly + $lly_text_attr * $self->{'unitvalue'}; - my $Tx = 0; # final text llx - my $Ty = $origin_lly; # final text lly - my $Tw = 0; # final text word spacing. See http://www.adobe.com/devnet/pdf/pdf_reference.html ISO 32000-1 -#FIXME: Move line wrapping code to its own sub if possible - my $trim = ''; + my $Tx = 0; # final text llx + my $Ty = $origin_lly; # final text lly + my $Tw = 0; # final text word spacing. See http://www.adobe.com/devnet/pdf/pdf_reference.html ISO 32000-1 + + #FIXME: Move line wrapping code to its own sub if possible + my $trim = ''; my @lines = (); -#FIXME: Using embedded True Type fonts is a far superior way of handing things as well as being much more unicode friendly. -# However this will take significant work using better than PDF::Reuse to do it. For the time being, I'm leaving -# the basic code here commented out to preserve the basic method of accomplishing this. -chris_n -# -# my $m = Font::TTFMetrics->new("/usr/share/fonts/truetype/msttcorefonts/Times_New_Roman_Bold.ttf"); -# my $units_per_em = $m->get_units_per_em(); -# my $font_units_width = $m->string_width($line); -# my $string_width = ($font_units_width * $text_attribs->{'font_size'}) / $units_per_em; + + #FIXME: Using embedded True Type fonts is a far superior way of handing things as well as being much more unicode friendly. + # However this will take significant work using better than PDF::Reuse to do it. For the time being, I'm leaving + # the basic code here commented out to preserve the basic method of accomplishing this. -chris_n + # + # my $m = Font::TTFMetrics->new("/usr/share/fonts/truetype/msttcorefonts/Times_New_Roman_Bold.ttf"); + # my $units_per_em = $m->get_units_per_em(); + # my $font_units_width = $m->string_width($line); + # my $string_width = ($font_units_width * $text_attribs->{'font_size'}) / $units_per_em; ## Please see file perltidy.ERR my $string_width = C4::Creators::PDF->StrWidth( $line, $text_attribs->{'font'}, $text_attribs->{'font_size'} ); if ( ( $string_width + $llx_text_attr ) > $self->{'width'} ) { @@ -308,11 +326,12 @@ sub draw_text { $text_attribs->{'llx'} * $self->{'unitvalue'}, $string_width, $line, $text_attribs->{'text_alignment'} ); - $line =~ s/^\s+//g; # strip naughty leading spaces - push @lines, {line=> $line, Tx => $Tx, Ty => $Ty, Tw => $Tw}; + $line =~ s/^\s+//g; # strip naughty leading spaces + push @lines, { line => $line, Tx => $Tx, Ty => $Ty, Tw => $Tw }; last WRAP_LINES; } } else { + # We only split lines on spaces - it seems if we push a line too far, it can end # never getting short enough in which case we need to escape and the malformed PDF # will indicate the layout problem @@ -320,31 +339,36 @@ sub draw_text { $cur_line = $line; } } + } else { + ( $Tx, $Tw ) = text_alignment( + $origin_llx, $self->{'width'}, $lly_text_attr * $self->{'unitvalue'}, $string_width, + $line, $text_attribs->{'text_alignment'} + ); + $line =~ s/^\s+//g; # strip naughty leading spaces + push @lines, { line => $line, Tx => $Tx, Ty => $Ty, Tw => $Tw }; } - else { - ($Tx, $Tw) = text_alignment($origin_llx, $self->{'width'}, $lly_text_attr * $self->{'unitvalue'}, $string_width, $line, $text_attribs->{'text_alignment'}); - $line =~ s/^\s+//g; # strip naughty leading spaces - push @lines, {line=> $line, Tx => $Tx, Ty => $Ty, Tw => $Tw}; - } -# Draw boxes around text box areas -# FIXME: This needs to compensate for the point height of decenders. In its current form it is helpful but not really usable. The boxes are also not transparent atm. -# If these things were fixed, it may be desirable to give the user control over whether or not to display these boxes for layout design. + + # Draw boxes around text box areas + # FIXME: This needs to compensate for the point height of decenders. In its current form it is helpful but not really usable. The boxes are also not transparent atm. + # If these things were fixed, it may be desirable to give the user control over whether or not to display these boxes for layout design. if (0) { my $box_height = 0; - my $box_lly = $origin_lly; - if (scalar(@lines) > 1) { - $box_height += scalar(@lines) * ($text_attribs->{'font_size'} * 1.2); - $box_lly -= ($text_attribs->{'font_size'} * 0.2); - } - else { + my $box_lly = $origin_lly; + if ( scalar(@lines) > 1 ) { + $box_height += scalar(@lines) * ( $text_attribs->{'font_size'} * 1.2 ); + $box_lly -= ( $text_attribs->{'font_size'} * 0.2 ); + } else { $box_height += $text_attribs->{'font_size'}; } - box ($origin_llx, $box_lly, $self->{'width'} - ( $text_attribs->{'llx'} * $self->{'unitvalue'} ), $box_height, $pdf); + box( + $origin_llx, $box_lly, $self->{'width'} - ( $text_attribs->{'llx'} * $self->{'unitvalue'} ), + $box_height, $pdf + ); } - $pdf->Font($text_attribs->{'font'}); - $pdf->FontSize($text_attribs->{'font_size'}); + $pdf->Font( $text_attribs->{'font'} ); + $pdf->FontSize( $text_attribs->{'font_size'} ); foreach my $line (@lines) { - $pdf->Text($line->{'Tx'}, $line->{'Ty'}, $line->{'line'}); + $pdf->Text( $line->{'Tx'}, $line->{'Ty'}, $line->{'line'} ); } } } @@ -358,20 +382,26 @@ Draws images to PDF output ($pdf) =cut sub draw_image { - my ($self, $pdf) = @_; + my ( $self, $pdf ) = @_; warn sprintf('No pdf object passed in.') and return -1 if !$pdf; my $images = $self->{'layout'}->{'images'}; - PROCESS_IMAGES: - foreach my $image (keys %$images) { +PROCESS_IMAGES: + foreach my $image ( keys %$images ) { next PROCESS_IMAGES if $images->{$image}->{'data_source'}->[0]->{'image_source'} eq 'none'; my $Tx = $self->{'llx'} + $images->{$image}->{'Tx'} * $self->{'unitvalue'}; my $Ty = $self->{'lly'} + $images->{$image}->{'Ty'} * $self->{'unitvalue'}; warn sprintf('No image passed in.') and next if !$images->{$image}->{'data'}; - my $intName = $pdf->AltJpeg($images->{$image}->{'data'},$images->{$image}->{'Sx'}, $images->{$image}->{'Sy'}, 1, $images->{$image}->{'alt'}->{'data'},$images->{$image}->{'alt'}->{'Sx'}, $images->{$image}->{'alt'}->{'Sy'}, 1); + my $intName = $pdf->AltJpeg( + $images->{$image}->{'data'}, $images->{$image}->{'Sx'}, $images->{$image}->{'Sy'}, 1, + $images->{$image}->{'alt'}->{'data'}, $images->{$image}->{'alt'}->{'Sx'}, + $images->{$image}->{'alt'}->{'Sy'}, 1 + ); my $obj_stream = "q\n"; - $obj_stream .= "$images->{$image}->{'Sx'} $images->{$image}->{'Ox'} $images->{$image}->{'Oy'} $images->{$image}->{'Sy'} $Tx $Ty cm\n"; # see http://www.adobe.com/devnet/pdf/pdf_reference.html sec 8.3.3 of ISO 32000-1 - $obj_stream .= "$images->{$image}->{'scale'} 0 0 $images->{$image}->{'scale'} 0 0 cm\n"; #scale to 20% + $obj_stream .= + "$images->{$image}->{'Sx'} $images->{$image}->{'Ox'} $images->{$image}->{'Oy'} $images->{$image}->{'Sy'} $Tx $Ty cm\n" + ; # see http://www.adobe.com/devnet/pdf/pdf_reference.html sec 8.3.3 of ISO 32000-1 + $obj_stream .= "$images->{$image}->{'scale'} 0 0 $images->{$image}->{'scale'} 0 0 cm\n"; #scale to 20% $obj_stream .= "/$intName Do\n"; $obj_stream .= "Q\n"; $pdf->Add($obj_stream); @@ -386,77 +416,75 @@ Draws a barcode to PDF output ($pdf) =cut -sub _draw_barcode { # this is cut-and-paste from Label.pm because there is no common place for it atm... - my $self = shift; +sub _draw_barcode { # this is cut-and-paste from Label.pm because there is no common place for it atm... + my $self = shift; my %params = @_; my $x_scale_factor = 1; - my $num_of_chars = length($params{'barcode_data'}); + my $num_of_chars = length( $params{'barcode_data'} ); my $tot_bar_length = 0; - my $bar_length = 0; - my $guard_length = 10; - if ($params{'barcode_type'} =~ m/CODE39/) { - $bar_length = '17.5'; - $tot_bar_length = ($bar_length * $num_of_chars) + ($guard_length * 2); # not sure what all is going on here and on the next line; this is old (very) code - $x_scale_factor = ($params{'width'} / $tot_bar_length); - if ($params{'barcode_type'} eq 'CODE39MOD') { - my $c39 = CheckDigits('code_39'); # get modulo 43 checksum - $params{'barcode_data'} = $c39->complete($params{'barcode_data'}); - } - elsif ($params{'barcode_type'} eq 'CODE39MOD10') { - my $c39_10 = CheckDigits('siret'); # get modulo 10 checksum - $params{'barcode_data'} = $c39_10->complete($params{'barcode_data'}); + my $bar_length = 0; + my $guard_length = 10; + if ( $params{'barcode_type'} =~ m/CODE39/ ) { + $bar_length = '17.5'; + $tot_bar_length = ( $bar_length * $num_of_chars ) + + ( $guard_length * 2 ); # not sure what all is going on here and on the next line; this is old (very) code + $x_scale_factor = ( $params{'width'} / $tot_bar_length ); + if ( $params{'barcode_type'} eq 'CODE39MOD' ) { + my $c39 = CheckDigits('code_39'); # get modulo 43 checksum + $params{'barcode_data'} = $c39->complete( $params{'barcode_data'} ); + } elsif ( $params{'barcode_type'} eq 'CODE39MOD10' ) { + my $c39_10 = CheckDigits('siret'); # get modulo 10 checksum + $params{'barcode_data'} = $c39_10->complete( $params{'barcode_data'} ); } eval { PDF::Reuse::Barcode::Code39( - x => $params{'llx'}, - y => $params{'lly'}, - value => "*$params{barcode_data}*", - xSize => $x_scale_factor, - ySize => $params{'y_scale_factor'}, - hide_asterisk => 1, - text => $params{'text'}, - mode => 'graphic', + x => $params{'llx'}, + y => $params{'lly'}, + value => "*$params{barcode_data}*", + xSize => $x_scale_factor, + ySize => $params{'y_scale_factor'}, + hide_asterisk => 1, + text => $params{'text'}, + mode => 'graphic', ); }; if ($@) { - warn sprintf('Barcode generation failed for item %s with this error: %s', $self->{'item_number'}, $@); + warn sprintf( 'Barcode generation failed for item %s with this error: %s', $self->{'item_number'}, $@ ); } - } - elsif ($params{'barcode_type'} eq 'COOP2OF5') { - $bar_length = '9.43333333333333'; - $tot_bar_length = ($bar_length * $num_of_chars) + ($guard_length * 2); - $x_scale_factor = ($params{'width'} / $tot_bar_length) * 0.9; + } elsif ( $params{'barcode_type'} eq 'COOP2OF5' ) { + $bar_length = '9.43333333333333'; + $tot_bar_length = ( $bar_length * $num_of_chars ) + ( $guard_length * 2 ); + $x_scale_factor = ( $params{'width'} / $tot_bar_length ) * 0.9; eval { PDF::Reuse::Barcode::COOP2of5( - x => $params{'llx'}, - y => $params{'lly'}, - value => $params{barcode_data}, - xSize => $x_scale_factor, - ySize => $params{'y_scale_factor'}, - mode => 'graphic', + x => $params{'llx'}, + y => $params{'lly'}, + value => $params{barcode_data}, + xSize => $x_scale_factor, + ySize => $params{'y_scale_factor'}, + mode => 'graphic', ); }; if ($@) { - warn sprintf('Barcode generation failed for item %s with this error: %s', $self->{'item_number'}, $@); + warn sprintf( 'Barcode generation failed for item %s with this error: %s', $self->{'item_number'}, $@ ); } - } - elsif ( $params{'barcode_type'} eq 'INDUSTRIAL2OF5' ) { - $bar_length = '13.1333333333333'; - $tot_bar_length = ($bar_length * $num_of_chars) + ($guard_length * 2); - $x_scale_factor = ($params{'width'} / $tot_bar_length) * 0.9; + } elsif ( $params{'barcode_type'} eq 'INDUSTRIAL2OF5' ) { + $bar_length = '13.1333333333333'; + $tot_bar_length = ( $bar_length * $num_of_chars ) + ( $guard_length * 2 ); + $x_scale_factor = ( $params{'width'} / $tot_bar_length ) * 0.9; eval { PDF::Reuse::Barcode::Industrial2of5( - x => $params{'llx'}, - y => $params{'lly'}, - value => $params{barcode_data}, - xSize => $x_scale_factor, - ySize => $params{'y_scale_factor'}, - mode => 'graphic', + x => $params{'llx'}, + y => $params{'lly'}, + value => $params{barcode_data}, + xSize => $x_scale_factor, + ySize => $params{'y_scale_factor'}, + mode => 'graphic', ); }; if ($@) { - warn sprintf('Barcode generation failed for item %s with this error: %s', $self->{'item_number'}, $@); + warn sprintf( 'Barcode generation failed for item %s with this error: %s', $self->{'item_number'}, $@ ); } } } diff --git a/C4/Patroncards/Profile.pm b/C4/Patroncards/Profile.pm index 36797c0f1c..47368c00be 100644 --- a/C4/Patroncards/Profile.pm +++ b/C4/Patroncards/Profile.pm @@ -7,7 +7,6 @@ use base qw(C4::Creators::Profile); use autouse 'Data::Dumper' => qw(Dumper); - __PACKAGE__ =~ m/^C4::(.+)::.+$/; my $me = $1; @@ -30,14 +29,13 @@ sub retrieve { } sub delete { - if (ref($_[0])) { - my $self = shift; # check to see if this is a method call + if ( ref( $_[0] ) ) { + my $self = shift; # check to see if this is a method call push @_, "creator", $me; return $self->SUPER::delete(@_); - } - else { + } else { push @_, "creator", $me; - return __PACKAGE__->SUPER::delete(@_); # XXX: is this too hackish? + return __PACKAGE__->SUPER::delete(@_); # XXX: is this too hackish? } } diff --git a/C4/Patroncards/Template.pm b/C4/Patroncards/Template.pm index 4bb4543ac7..6560fe2d94 100644 --- a/C4/Patroncards/Template.pm +++ b/C4/Patroncards/Template.pm @@ -7,7 +7,6 @@ use base qw(C4::Creators::Template); use autouse 'Data::Dumper' => qw(Dumper); - use constant TEMPLATE_TABLE => 'creator_templates'; __PACKAGE__ =~ m/^C4::(.+)::.+$/; diff --git a/C4/Record.pm b/C4/Record.pm index 3228a432ed..74ad9defcc 100644 --- a/C4/Record.pm +++ b/C4/Record.pm @@ -22,45 +22,44 @@ package C4::Record; use Modern::Perl; # please specify in which methods a given module is used -use MARC::Record; # marc2marcxml, marcxml2marc, changeEncoding -use MARC::File::XML; # marc2marcxml, marcxml2marc, changeEncoding +use MARC::Record; # marc2marcxml, marcxml2marc, changeEncoding +use MARC::File::XML; # marc2marcxml, marcxml2marc, changeEncoding use Biblio::EndnoteStyle; -use Unicode::Normalize qw( NFC ); # _entity_encode -use C4::Biblio qw( GetFrameworkCode ); -use C4::Koha; #marc2csv +use Unicode::Normalize qw( NFC ); # _entity_encode +use C4::Biblio qw( GetFrameworkCode ); +use C4::Koha; #marc2csv use C4::XSLT; -use YAML::XS; #marcrecords2csv +use YAML::XS; #marcrecords2csv use Encode; use Template; -use Text::CSV::Encoded; #marc2csv +use Text::CSV::Encoded; #marc2csv use Koha::Items; use Koha::SimpleMARC qw( read_field ); use Koha::XSLT::Base; use Koha::CsvProfiles; use Koha::AuthorisedValues; use Koha::TemplateUtils qw( process_tt ); -use Carp qw( carp croak ); +use Carp qw( carp croak ); use vars qw(@ISA @EXPORT); - @ISA = qw(Exporter); # only export API methods @EXPORT = qw( - marc2endnote - marc2marc - marc2marcxml - marcxml2marc - marc2dcxml - marc2modsxml - marc2madsxml - marc2bibtex - marc2csv - marc2cites - marcrecord2csv - changeEncoding + marc2endnote + marc2marc + marc2marcxml + marcxml2marc + marc2dcxml + marc2modsxml + marc2madsxml + marc2bibtex + marc2csv + marc2cites + marcrecord2csv + changeEncoding ); =head1 NAME @@ -82,25 +81,27 @@ Returns an ISO-2709 scalar =cut sub marc2marc { - my ($marc,$to_flavour,$from_flavour,$encoding) = @_; - my $error; - if ($to_flavour && $to_flavour =~ m/marcstd/) { + my ( $marc, $to_flavour, $from_flavour, $encoding ) = @_; + my $error; + if ( $to_flavour && $to_flavour =~ m/marcstd/ ) { my $marc_record_obj; - if ($marc =~ /^MARC::Record/) { # it's already a MARC::Record object + if ( $marc =~ /^MARC::Record/ ) { # it's already a MARC::Record object $marc_record_obj = $marc; - } else { # it's not a MARC::Record object, make it one - eval { $marc_record_obj = MARC::Record->new_from_usmarc($marc) }; # handle exceptions + } else { # it's not a MARC::Record object, make it one + eval { $marc_record_obj = MARC::Record->new_from_usmarc($marc) }; # handle exceptions -# conversion to MARC::Record object failed, populate $error - if ($@) { $error .="\nCreation of MARC::Record object failed: ".$MARC::File::ERROR }; + # conversion to MARC::Record object failed, populate $error + if ($@) { $error .= "\nCreation of MARC::Record object failed: " . $MARC::File::ERROR } } unless ($error) { my @privatefields; - foreach my $field ($marc_record_obj->fields()) { - if ($field->tag() =~ m/9/ && ($field->tag() != '490' || C4::Context->preference("marcflavour") eq 'UNIMARC')) { + foreach my $field ( $marc_record_obj->fields() ) { + if ( $field->tag() =~ m/9/ + && ( $field->tag() != '490' || C4::Context->preference("marcflavour") eq 'UNIMARC' ) ) + { push @privatefields, $field; - } elsif (! ($field->is_control_field())) { - $field->delete_subfield(code => '9') if ($field->subfield('9')); + } elsif ( !( $field->is_control_field() ) ) { + $field->delete_subfield( code => '9' ) if ( $field->subfield('9') ); } } $marc_record_obj->delete_field($_) for @privatefields; @@ -109,7 +110,7 @@ sub marc2marc { } else { $error = "Feature not yet implemented\n"; } - return ($error,$marc); + return ( $error, $marc ); } =head2 marc2marcxml - Convert from ISO-2709 to MARCXML @@ -129,65 +130,71 @@ C<$dont_entity_encode> - a flag that instructs marc2marcxml not to entity encode =cut sub marc2marcxml { - my ($marc,$encoding,$flavour,$dont_entity_encode) = @_; - my $error; # the error string - my $marcxml; # the final MARCXML scalar + my ( $marc, $encoding, $flavour, $dont_entity_encode ) = @_; + my $error; # the error string + my $marcxml; # the final MARCXML scalar - # test if it's already a MARC::Record object, if not, make it one - my $marc_record_obj; - if ($marc =~ /^MARC::Record/) { # it's already a MARC::Record object - $marc_record_obj = $marc; - } else { # it's not a MARC::Record object, make it one - eval { $marc_record_obj = MARC::Record->new_from_usmarc($marc) }; # handle exceptions + # test if it's already a MARC::Record object, if not, make it one + my $marc_record_obj; + if ( $marc =~ /^MARC::Record/ ) { # it's already a MARC::Record object + $marc_record_obj = $marc; + } else { # it's not a MARC::Record object, make it one + eval { $marc_record_obj = MARC::Record->new_from_usmarc($marc) }; # handle exceptions - # conversion to MARC::Record object failed, populate $error - if ($@) { $error .="\nCreation of MARC::Record object failed: ".$MARC::File::ERROR }; - } - # only proceed if no errors so far - unless ($error) { + # conversion to MARC::Record object failed, populate $error + if ($@) { $error .= "\nCreation of MARC::Record object failed: " . $MARC::File::ERROR } + } - # check the record for warnings - my @warnings = $marc_record_obj->warnings(); - if (@warnings) { - warn "\nWarnings encountered while processing ISO-2709 record with title \"".$marc_record_obj->title()."\":\n"; - foreach my $warn (@warnings) { warn "\t".$warn }; - } - unless($encoding) {$encoding = "UTF-8"}; # set default encoding - unless($flavour) {$flavour = C4::Context->preference("marcflavour")}; # set default MARC flavour + # only proceed if no errors so far + unless ($error) { - # attempt to convert the record to MARCXML - eval { $marcxml = $marc_record_obj->as_xml_record($flavour) }; #handle exceptions + # check the record for warnings + my @warnings = $marc_record_obj->warnings(); + if (@warnings) { + warn "\nWarnings encountered while processing ISO-2709 record with title \"" + . $marc_record_obj->title() . "\":\n"; + foreach my $warn (@warnings) { warn "\t" . $warn } + } + unless ($encoding) { $encoding = "UTF-8" } + ; # set default encoding + unless ($flavour) { $flavour = C4::Context->preference("marcflavour") } + ; # set default MARC flavour - # record creation failed, populate $error - if ($@) { - $error .= "Creation of MARCXML failed:".$MARC::File::ERROR; - $error .= "Additional information:\n"; - my @warnings = $@->warnings(); - foreach my $warn (@warnings) { $error.=$warn."\n" }; + # attempt to convert the record to MARCXML + eval { $marcxml = $marc_record_obj->as_xml_record($flavour) }; #handle exceptions - # record creation was successful - } else { + # record creation failed, populate $error + if ($@) { + $error .= "Creation of MARCXML failed:" . $MARC::File::ERROR; + $error .= "Additional information:\n"; + my @warnings = $@->warnings(); + foreach my $warn (@warnings) { $error .= $warn . "\n" } - # check the record for warning flags again (warnings() will be cleared already if there was an error, see above block - @warnings = $marc_record_obj->warnings(); - if (@warnings) { - warn "\nWarnings encountered while processing ISO-2709 record with title \"".$marc_record_obj->title()."\":\n"; - foreach my $warn (@warnings) { warn "\t".$warn }; - } - } + # record creation was successful + } else { - # only proceed if no errors so far - unless ($error) { + # check the record for warning flags again (warnings() will be cleared already if there was an error, see above block + @warnings = $marc_record_obj->warnings(); + if (@warnings) { + warn "\nWarnings encountered while processing ISO-2709 record with title \"" + . $marc_record_obj->title() . "\":\n"; + foreach my $warn (@warnings) { warn "\t" . $warn } + } + } - # entity encode the XML unless instructed not to - unless ($dont_entity_encode) { - my ($marcxml_entity_encoded) = _entity_encode($marcxml); - $marcxml = $marcxml_entity_encoded; - } - } - } - # return result to calling program - return ($error,$marcxml); + # only proceed if no errors so far + unless ($error) { + + # entity encode the XML unless instructed not to + unless ($dont_entity_encode) { + my ($marcxml_entity_encoded) = _entity_encode($marcxml); + $marcxml = $marcxml_entity_encoded; + } + } + } + + # return result to calling program + return ( $error, $marcxml ); } =head2 marcxml2marc - Convert from MARCXML to ISO-2709 @@ -205,21 +212,25 @@ C<$flavour> - MARC21 or UNIMARC =cut sub marcxml2marc { - my ($marcxml,$encoding,$flavour) = @_; - my $error; # the error string - my $marc; # the final ISO-2709 scalar - unless($encoding) {$encoding = "UTF-8"}; # set the default encoding - unless($flavour) {$flavour = C4::Context->preference("marcflavour")}; # set the default MARC flavour + my ( $marcxml, $encoding, $flavour ) = @_; + my $error; # the error string + my $marc; # the final ISO-2709 scalar + unless ($encoding) { $encoding = "UTF-8" } + ; # set the default encoding + unless ($flavour) { $flavour = C4::Context->preference("marcflavour") } + ; # set the default MARC flavour - # attempt to do the conversion - eval { $marc = MARC::Record->new_from_xml($marcxml,$encoding,$flavour) }; # handle exceptions + # attempt to do the conversion + eval { $marc = MARC::Record->new_from_xml( $marcxml, $encoding, $flavour ) }; # handle exceptions - # record creation failed, populate $error - if ($@) {$error .="\nCreation of MARCXML Record failed: ".$@; - $error.=$MARC::File::ERROR if ($MARC::File::ERROR); - }; - # return result to calling program - return ($error,$marc); + # record creation failed, populate $error + if ($@) { + $error .= "\nCreation of MARCXML Record failed: " . $@; + $error .= $MARC::File::ERROR if ($MARC::File::ERROR); + } + + # return result to calling program + return ( $error, $marc ); } =head2 marc2dcxml - Convert from ISO-2709 to Dublin Core @@ -254,45 +265,51 @@ sub marc2dcxml { # set the default path for intranet xslts # differents xslts to process (OAIDC, SRWDC and RDFDC) - my $xsl = C4::Context->config('intrahtdocs') . '/prog/en/xslt/' . - C4::Context->preference('marcflavour') . 'slim2' . uc ( $format ) . '.xsl'; + my $xsl = + C4::Context->config('intrahtdocs') + . '/prog/en/xslt/' + . C4::Context->preference('marcflavour') . 'slim2' + . uc($format) . '.xsl'; if ( defined $marc ) { + # no need to catch errors or warnings marc2marcxml do it instead - $marcxml = C4::Record::marc2marcxml( $marc ); + $marcxml = C4::Record::marc2marcxml($marc); } elsif ( not defined $xml and defined $biblionumber ) { + # get MARCXML biblio directly without item information - $marcxml = C4::Biblio::GetXmlBiblio( $biblionumber ); + $marcxml = C4::Biblio::GetXmlBiblio($biblionumber); } else { $marcxml = $xml; } - eval { $record = MARC::Record->new_from_xml( - $marcxml, - 'UTF-8', - C4::Context->preference('marcflavour') - ); + eval { + $record = MARC::Record->new_from_xml( + $marcxml, + 'UTF-8', + C4::Context->preference('marcflavour') + ); }; # conversion to MARC::Record object failed - if ( $@ ) { + if ($@) { croak "Creation of MARC::Record object failed."; } elsif ( $record->warnings() ) { carp "Warnings encountered while processing ISO-2709 record.\n"; my @warnings = $record->warnings(); foreach my $warn (@warnings) { - carp "\t". $warn; - }; - } elsif ( $record =~ /^MARC::Record/ ) { # if OK makes xslt transformation + carp "\t" . $warn; + } + } elsif ( $record =~ /^MARC::Record/ ) { # if OK makes xslt transformation my $xslt_engine = Koha::XSLT::Base->new; if ( $format =~ /^(dc|oaidc|srwdc|rdfdc)$/i ) { $output = $xslt_engine->transform( $marcxml, $xsl ); } else { - croak "The format argument ($format) not accepted.\n" . - "Please pass a valid format (oaidc, srwdc, or rdfdc)\n"; + croak "The format argument ($format) not accepted.\n" + . "Please pass a valid format (oaidc, srwdc, or rdfdc)\n"; } - my $err = $xslt_engine->err; # error code - if ( $err ) { + my $err = $xslt_engine->err; # error code + if ($err) { croak "Error $err while processing\n"; } else { return $output; @@ -310,7 +327,7 @@ Returns a MODS scalar sub marc2modsxml { my ($marc) = @_; - return _transformWithStylesheet($marc, "/prog/en/xslt/MARC21slim2MODS3-1.xsl"); + return _transformWithStylesheet( $marc, "/prog/en/xslt/MARC21slim2MODS3-1.xsl" ); } =head2 marc2madsxml - Convert from ISO-2709 to MADS @@ -323,7 +340,7 @@ Returns a MADS scalar sub marc2madsxml { my ($marc) = @_; - return _transformWithStylesheet($marc, "/prog/en/xslt/MARC21slim2MADS.xsl"); + return _transformWithStylesheet( $marc, "/prog/en/xslt/MARC21slim2MADS.xsl" ); } =head2 _transformWithStylesheet - Transform a MARC record with a stylesheet @@ -336,16 +353,17 @@ contain the path to a stylesheet under intrahtdocs. =cut sub _transformWithStylesheet { - my ($marc, $stylesheet) = @_; + my ( $marc, $stylesheet ) = @_; + # grab the XML, run it through our stylesheet, push it out to the browser my $xmlrecord = marc2marcxml($marc); - my $xslfile = C4::Context->config('intrahtdocs') . $stylesheet; - return C4::XSLT::engine->transform($xmlrecord, $xslfile); + my $xslfile = C4::Context->config('intrahtdocs') . $stylesheet; + return C4::XSLT::engine->transform( $xmlrecord, $xslfile ); } sub marc2endnote { my ($marc) = @_; - my $marc_rec_obj = MARC::Record->new_from_usmarc($marc); + my $marc_rec_obj = MARC::Record->new_from_usmarc($marc); my ( $abstract, $f260a, $f710a ); my $f260 = $marc_rec_obj->field('260'); if ($f260) { @@ -360,24 +378,24 @@ sub marc2endnote { $abstract = $f500->subfield('a'); } my $fields = { - DB => C4::Context->preference("LibraryName"), - Title => $marc_rec_obj->title(), - Author => $marc_rec_obj->author(), + DB => C4::Context->preference("LibraryName"), + Title => $marc_rec_obj->title(), + Author => $marc_rec_obj->author(), Publisher => $f710a, - City => $f260a, - Year => $marc_rec_obj->publication_date, - Abstract => $abstract, + City => $f260a, + Year => $marc_rec_obj->publication_date, + Abstract => $abstract, }; my $style = Biblio::EndnoteStyle->new(); my $template; - $template.= "DB - DB\n" if C4::Context->preference("LibraryName"); - $template.="T1 - Title\n" if $marc_rec_obj->title(); - $template.="A1 - Author\n" if $marc_rec_obj->author(); - $template.="PB - Publisher\n" if $f710a; - $template.="CY - City\n" if $f260a; - $template.="Y1 - Year\n" if $marc_rec_obj->publication_date; - $template.="AB - Abstract\n" if $abstract; - my ($text, $errmsg) = $style->format($template, $fields); + $template .= "DB - DB\n" if C4::Context->preference("LibraryName"); + $template .= "T1 - Title\n" if $marc_rec_obj->title(); + $template .= "A1 - Author\n" if $marc_rec_obj->author(); + $template .= "PB - Publisher\n" if $f710a; + $template .= "CY - City\n" if $f260a; + $template .= "Y1 - Year\n" if $marc_rec_obj->publication_date; + $template .= "AB - Abstract\n" if $abstract; + my ( $text, $errmsg ) = $style->format( $template, $fields ); return ($text); } @@ -399,25 +417,25 @@ C<$itemnumbers> - a list of itemnumbers to export =cut sub marc2csv { - my ($biblios, $id, $itemnumbers) = @_; + my ( $biblios, $id, $itemnumbers ) = @_; $itemnumbers ||= []; my $output; my $csv = Text::CSV::Encoded->new( { formula => "empty" } ); # Getting yaml file my $configfile = "../tools/csv-profiles/$id.yaml"; - my ($preprocess, $postprocess, $fieldprocessing); - if (-e $configfile){ - ($preprocess,$postprocess, $fieldprocessing) = YAML::XS::LoadFile($configfile); + my ( $preprocess, $postprocess, $fieldprocessing ); + if ( -e $configfile ) { + ( $preprocess, $postprocess, $fieldprocessing ) = YAML::XS::LoadFile($configfile); } # Preprocessing - eval $preprocess if ($preprocess); ## no critic (StringyEval) + eval $preprocess if ($preprocess); ## no critic (StringyEval) my $firstpass = 1; - if ( @$itemnumbers ) { - for my $itemnumber ( @$itemnumbers) { - my $item = Koha::Items->find( $itemnumber ); + if (@$itemnumbers) { + for my $itemnumber (@$itemnumbers) { + my $item = Koha::Items->find($itemnumber); my $biblionumber = $item->biblio->biblionumber; $output .= marcrecord2csv( $biblionumber, $id, $firstpass, $csv, $fieldprocessing, [$itemnumber] ) // ''; $firstpass = 0; @@ -430,7 +448,7 @@ sub marc2csv { } # Postprocessing - eval $postprocess if ($postprocess); ## no critic (StringyEval) + eval $postprocess if ($postprocess); ## no critic (StringyEval) return $output; } @@ -456,7 +474,7 @@ C<$itemnumbers> a list of itemnumbers to export =cut sub marcrecord2csv { - my ($biblionumber, $id, $header, $csv, $fieldprocessing, $itemnumbers) = @_; + my ( $biblionumber, $id, $header, $csv, $fieldprocessing, $itemnumbers ) = @_; my $output; # Getting the record @@ -472,46 +490,48 @@ sub marcrecord2csv { my $profile = Koha::CsvProfiles->find($id); # Getting output encoding - my $encoding = $profile->encoding || 'utf8'; + my $encoding = $profile->encoding || 'utf8'; + # Getting separators my $csvseparator = $profile->csv_separator || ','; my $fieldseparator = $profile->field_separator || '#'; my $subfieldseparator = $profile->subfield_separator || '|'; # TODO: Be more generic (in case we have to handle other protected chars or more separators) - if ($csvseparator eq '\t') { $csvseparator = "\t" } - if ($fieldseparator eq '\t') { $fieldseparator = "\t" } - if ($subfieldseparator eq '\t') { $subfieldseparator = "\t" } - if ($csvseparator eq '\n') { $csvseparator = "\n" } - if ($fieldseparator eq '\n') { $fieldseparator = "\n" } - if ($subfieldseparator eq '\n') { $subfieldseparator = "\n" } + if ( $csvseparator eq '\t' ) { $csvseparator = "\t" } + if ( $fieldseparator eq '\t' ) { $fieldseparator = "\t" } + if ( $subfieldseparator eq '\t' ) { $subfieldseparator = "\t" } + if ( $csvseparator eq '\n' ) { $csvseparator = "\n" } + if ( $fieldseparator eq '\n' ) { $fieldseparator = "\n" } + if ( $subfieldseparator eq '\n' ) { $subfieldseparator = "\n" } - $csv = $csv->encoding_out($encoding) ; + $csv = $csv->encoding_out($encoding); $csv->sep_char($csvseparator); # Getting the marcfields my $marcfieldslist = $profile->content; # Getting the marcfields as an array - my @marcfieldsarray = split('\|', $marcfieldslist); + my @marcfieldsarray = split( '\|', $marcfieldslist ); - # Separating the marcfields from the user-supplied headers + # Separating the marcfields from the user-supplied headers my @csv_structures; foreach (@marcfieldsarray) { - my @result = split('=', $_, 2); - my $content = ( @result == 2 ) + my @result = split( '=', $_, 2 ); + my $content = + ( @result == 2 ) ? $result[1] : $result[0]; my @fields; while ( $content =~ m|(\d{3})\$?(.)?|g ) { - my $fieldtag = $1; + my $fieldtag = $1; my $subfieldtag = $2; push @fields, { fieldtag => $fieldtag, subfieldtag => $subfieldtag }; } - if ( @result == 2) { - push @csv_structures, { header => $result[0], content => $content, fields => \@fields }; + if ( @result == 2 ) { + push @csv_structures, { header => $result[0], content => $content, fields => \@fields }; } else { - push @csv_structures, { content => $content, fields => \@fields } + push @csv_structures, { content => $content, fields => \@fields }; } } @@ -529,33 +549,36 @@ sub marcrecord2csv { $values->{indicator}{2} = $field->indicator(2); for my $subfield ( $field->subfields ) { my $subfieldtag = $subfield->[0]; - my $value = $subfield->[1]; + my $value = $subfield->[1]; push @{ $values->{$subfieldtag} }, $value; } } + # We force the key as an integer (trick for 00X and OXX fields) - push @{ $field_list->{fields}{0+$fieldtag} }, $values; + push @{ $field_list->{fields}{ 0 + $fieldtag } }, $values; } # For each field or subfield foreach my $csv_structure (@csv_structures) { my @field_values; - my $tags = $csv_structure->{fields}; + my $tags = $csv_structure->{fields}; my $content = $csv_structure->{content}; - if ( $header ) { + if ($header) { + # If we have a user-supplied header, we use it if ( exists $csv_structure->{header} ) { push @marcfieldsheaders, $csv_structure->{header}; } else { + # If not, we get the matching tag name from koha my $tag = $tags->[0]; - if (defined $tag->{subfieldtag} ) { - my $query = "SELECT liblibrarian FROM marc_subfield_structure WHERE tagfield=? AND tagsubfield=?"; + if ( defined $tag->{subfieldtag} ) { + my $query = "SELECT liblibrarian FROM marc_subfield_structure WHERE tagfield=? AND tagsubfield=?"; my @results = $dbh->selectrow_array( $query, {}, $tag->{fieldtag}, $tag->{subfieldtag} ); push @marcfieldsheaders, $results[0]; } else { - my $query = "SELECT liblibrarian FROM marc_tag_structure WHERE tagfield=?"; + my $query = "SELECT liblibrarian FROM marc_tag_structure WHERE tagfield=?"; my @results = $dbh->selectrow_array( $query, {}, $tag->{fieldtag} ); push @marcfieldsheaders, $results[0]; } @@ -564,43 +587,53 @@ sub marcrecord2csv { # TT tags exist if ( $content =~ m|\[\%.*\%\]| ) { + # Replace 00X and 0XX with X or XX $content =~ s|fields.00(\d)|fields.$1|g; $content =~ s|fields.0(\d{2})|fields.$1|g; my $tt_output = process_tt( $content, $field_list ); push @csv_rows, $tt_output; } else { - for my $tag ( @$tags ) { + for my $tag (@$tags) { my @fields = $record->field( $tag->{fieldtag} ); + # If it is a subfield my @loop_values; - if (defined $tag->{subfieldtag} ) { + if ( defined $tag->{subfieldtag} ) { my $av_description_mapping = Koha::AuthorisedValues->get_descriptions_by_marc_field( { frameworkcode => $frameworkcode, tagfield => $tag->{fieldtag}, tagsubfield => $tag->{subfieldtag}, } ); + # For each field foreach my $field (@fields) { my @subfields = $field->subfield( $tag->{subfieldtag} ); foreach my $subfield (@subfields) { - push @loop_values, (defined $av_description_mapping->{$subfield}) ? $av_description_mapping->{$subfield} : $subfield; + push @loop_values, + ( defined $av_description_mapping->{$subfield} ) + ? $av_description_mapping->{$subfield} + : $subfield; } } - # Or a field + # Or a field } else { - foreach my $field ( @fields ) { + foreach my $field (@fields) { my $value; # If it is a control field - if ($field->is_control_field) { + if ( $field->is_control_field ) { my $authvalues = Koha::AuthorisedValues->get_descriptions_by_marc_field( { frameworkcode => $frameworkcode, tagfield => $tag->{fieldtag}, } ); - $value = defined $authvalues->{$field->as_string} ? $authvalues->{$field->as_string} : $field->as_string; + $value = + defined $authvalues->{ $field->as_string } + ? $authvalues->{ $field->as_string } + : $field->as_string; } else { + # If it is a field, we gather all subfields, joined by the subfield separator my @subvaluesarray; my @subfields = $field->subfields; @@ -611,27 +644,32 @@ sub marcrecord2csv { tagsubfield => $subfield->[0], } ); - push (@subvaluesarray, defined $authvalues->{$subfield->[1]} ? $authvalues->{$subfield->[1]} : $subfield->[1]); + push( + @subvaluesarray, + defined $authvalues->{ $subfield->[1] } + ? $authvalues->{ $subfield->[1] } + : $subfield->[1] + ); } - $value = join ($subfieldseparator, @subvaluesarray); + $value = join( $subfieldseparator, @subvaluesarray ); } # Field processing - my $marcfield = $tag->{fieldtag}; # This line fixes a retrocompatibility concern - # The "processing" could be based on the $marcfield variable. - eval $fieldprocessing if ($fieldprocessing); ## no critic (StringyEval) + my $marcfield = $tag->{fieldtag}; # This line fixes a retrocompatibility concern + # The "processing" could be based on the $marcfield variable. + eval $fieldprocessing if ($fieldprocessing); ## no critic (StringyEval) push @loop_values, $value; } } push @field_values, { - fieldtag => $tag->{fieldtag}, + fieldtag => $tag->{fieldtag}, subfieldtag => $tag->{subfieldtag}, - values => \@loop_values, + values => \@loop_values, }; } - for my $field_value ( @field_values ) { + for my $field_value (@field_values) { if ( $field_value->{subfieldtag} ) { push @csv_rows, join( $subfieldseparator, @{ $field_value->{values} } ); } else { @@ -641,8 +679,7 @@ sub marcrecord2csv { } } - - if ( $header ) { + if ($header) { $csv->combine(@marcfieldsheaders); $output = $csv->string() . "\n"; } @@ -653,7 +690,6 @@ sub marcrecord2csv { } - =head2 changeEncoding - Change the encoding of a record my ($error, $newrecord) = changeEncoding($record,$format,$flavour,$to_encoding,$from_encoding); @@ -679,34 +715,35 @@ FIXME: shouldn't have to convert to and from xml/marc just to change encoding so =cut sub changeEncoding { - my ($record,$format,$flavour,$to_encoding,$from_encoding) = @_; - my $newrecord; - my $error; - unless($flavour) {$flavour = C4::Context->preference("marcflavour")}; - unless($to_encoding) {$to_encoding = "UTF-8"}; + my ( $record, $format, $flavour, $to_encoding, $from_encoding ) = @_; + my $newrecord; + my $error; + unless ($flavour) { $flavour = C4::Context->preference("marcflavour") } + unless ($to_encoding) { $to_encoding = "UTF-8" } - # ISO-2709 Record (MARC21 or UNIMARC) - if (lc($format) =~ /^marc$/o) { - # if we're converting encoding of an ISO2709 file, we need to roundtrip through XML - # because MARC::Record doesn't directly provide us with an encoding method - # It's definitely less than idea and should be fixed eventually - kados - my $marcxml; # temporary storage of MARCXML scalar - ($error,$marcxml) = marc2marcxml($record,$to_encoding,$flavour); - unless ($error) { - ($error,$newrecord) = marcxml2marc($marcxml,$to_encoding,$flavour); - } + # ISO-2709 Record (MARC21 or UNIMARC) + if ( lc($format) =~ /^marc$/o ) { - # MARCXML Record - } elsif (lc($format) =~ /^marcxml$/o) { # MARCXML Record - my $marc; - ($error,$marc) = marcxml2marc($record,$to_encoding,$flavour); - unless ($error) { - ($error,$newrecord) = marc2marcxml($record,$to_encoding,$flavour); - } - } else { - $error.="Unsupported record format:".$format; - } - return ($error,$newrecord); + # if we're converting encoding of an ISO2709 file, we need to roundtrip through XML + # because MARC::Record doesn't directly provide us with an encoding method + # It's definitely less than idea and should be fixed eventually - kados + my $marcxml; # temporary storage of MARCXML scalar + ( $error, $marcxml ) = marc2marcxml( $record, $to_encoding, $flavour ); + unless ($error) { + ( $error, $newrecord ) = marcxml2marc( $marcxml, $to_encoding, $flavour ); + } + + # MARCXML Record + } elsif ( lc($format) =~ /^marcxml$/o ) { # MARCXML Record + my $marc; + ( $error, $marc ) = marcxml2marc( $record, $to_encoding, $flavour ); + unless ($error) { + ( $error, $newrecord ) = marc2marcxml( $record, $to_encoding, $flavour ); + } + } else { + $error .= "Unsupported record format:" . $format; + } + return ( $error, $newrecord ); } =head2 marc2bibtex - Convert from MARC21 and UNIMARC to BibTex @@ -721,28 +758,28 @@ C<$id> - an id for the BibTex record (might be the biblionumber) =cut - sub marc2bibtex { - my ($record, $id) = @_; + my ( $record, $id ) = @_; my $tex; my $marcflavour = C4::Context->preference("marcflavour"); # Authors my $author; my @texauthors; - my @authorFields = ('100','110','111','700','710','711'); - @authorFields = ('700','701','702','710','711','721') if ( $marcflavour eq "UNIMARC" ); + my @authorFields = ( '100', '110', '111', '700', '710', '711' ); + @authorFields = ( '700', '701', '702', '710', '711', '721' ) if ( $marcflavour eq "UNIMARC" ); + + foreach my $field (@authorFields) { - foreach my $field ( @authorFields ) { # author formatted surname, firstname my $texauthor = ''; if ( $marcflavour eq "UNIMARC" ) { - $texauthor = join ', ', - ( $record->subfield($field,"a"), $record->subfield($field,"b") ); - } else { - $texauthor = $record->subfield($field,"a"); - } - push @texauthors, $texauthor if $texauthor; + $texauthor = join ', ', + ( $record->subfield( $field, "a" ), $record->subfield( $field, "b" ) ); + } else { + $texauthor = $record->subfield( $field, "a" ); + } + push @texauthors, $texauthor if $texauthor; } $author = join ' and ', @texauthors; @@ -758,18 +795,18 @@ sub marc2bibtex { # Mandatory author => $author, - title => $record->subfield("200", "a") || "", - editor => $record->subfield("210", "g") || "", - publisher => $record->subfield("210", "c") || "", - year => $record->subfield("210", "d") || $record->subfield("210", "h") || "", + title => $record->subfield( "200", "a" ) || "", + editor => $record->subfield( "210", "g" ) || "", + publisher => $record->subfield( "210", "c" ) || "", + year => $record->subfield( "210", "d" ) || $record->subfield( "210", "h" ) || "", # Optional - volume => $record->subfield("200", "v") || "", - series => $record->subfield("225", "a") || "", - address => $record->subfield("210", "a") || "", - edition => $record->subfield("205", "a") || "", - note => $record->subfield("300", "a") || "", - url => $record->subfield("856", "u") || "" + volume => $record->subfield( "200", "v" ) || "", + series => $record->subfield( "225", "a" ) || "", + address => $record->subfield( "210", "a" ) || "", + edition => $record->subfield( "205", "a" ) || "", + note => $record->subfield( "300", "a" ) || "", + url => $record->subfield( "856", "u" ) || "" ); } else { @@ -778,18 +815,21 @@ sub marc2bibtex { # Mandatory author => $author, - title => $record->subfield("245", "a") || "", - editor => $record->subfield("260", "f") || "", - publisher => $record->subfield("264", "b") || $record->subfield("260", "b") || "", - year => $record->subfield("264", "c") || $record->subfield("260", "c") || $record->subfield("260", "g") || "", + title => $record->subfield( "245", "a" ) || "", + editor => $record->subfield( "260", "f" ) || "", + publisher => $record->subfield( "264", "b" ) || $record->subfield( "260", "b" ) || "", + year => $record->subfield( "264", "c" ) + || $record->subfield( "260", "c" ) + || $record->subfield( "260", "g" ) + || "", # Optional # unimarc to marc21 specification says not to convert 200$v to marc21 - series => $record->subfield("490", "a") || "", - address => $record->subfield("264", "a") || $record->subfield("260", "a") || "", - edition => $record->subfield("250", "a") || "", - note => $record->subfield("500", "a") || "", - url => $record->subfield("856", "u") || "" + series => $record->subfield( "490", "a" ) || "", + address => $record->subfield( "264", "a" ) || $record->subfield( "260", "a" ) || "", + edition => $record->subfield( "250", "a" ) || "", + note => $record->subfield( "500", "a" ) || "", + url => $record->subfield( "856", "u" ) || "" ); } @@ -797,25 +837,23 @@ sub marc2bibtex { if ( $additional_fields && $additional_fields->{'@'} ) { my ( $f, $sf ) = split( /\$/, $additional_fields->{'@'} ); - my ( $type ) = read_field( { record => $record, field => $f, subfield => $sf, field_numbers => [1] } ); + my ($type) = read_field( { record => $record, field => $f, subfield => $sf, field_numbers => [1] } ); if ($type) { $tex .= '@' . $type . '{'; - } - else { + } else { $tex .= "\@book{"; } - } - else { + } else { $tex .= "\@book{"; } my @elt; - for ( my $i = 0 ; $i < scalar( @bh ) ; $i = $i + 2 ) { - next unless $bh[$i+1]; + for ( my $i = 0 ; $i < scalar(@bh) ; $i = $i + 2 ) { + next unless $bh[ $i + 1 ]; push @elt, qq|\t$bh[$i] = {$bh[$i+1]}|; } - $tex .= join(",\n", $id, @elt); + $tex .= join( ",\n", $id, @elt ); if ($additional_fields) { $tex .= ",\n"; @@ -823,9 +861,9 @@ sub marc2bibtex { next if $bibtex_tag eq '@'; my @fields = - ref( $additional_fields->{$bibtex_tag} ) eq 'ARRAY' - ? @{ $additional_fields->{$bibtex_tag} } - : $additional_fields->{$bibtex_tag}; + ref( $additional_fields->{$bibtex_tag} ) eq 'ARRAY' + ? @{ $additional_fields->{$bibtex_tag} } + : $additional_fields->{$bibtex_tag}; for my $tag (@fields) { my ( $f, $sf ) = split( /\$/, $tag ); @@ -835,8 +873,7 @@ sub marc2bibtex { } } } - } - else { + } else { $tex .= "\n"; } @@ -845,7 +882,6 @@ sub marc2bibtex { return $tex; } - =head2 marc2cites - Convert from MARC21 and UNIMARC to citations my $cites = marc2cites($record); @@ -957,7 +993,6 @@ sub marc2cites { return \%cites; } - =head1 INTERNAL FUNCTIONS =head2 _entity_encode - Entity-encode an array of strings @@ -973,17 +1008,17 @@ Entity-encode an array of strings =cut sub _entity_encode { - my @strings = @_; - my @strings_entity_encoded; - foreach my $string (@strings) { - my $nfc_string = NFC($string); - $nfc_string =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe; - push @strings_entity_encoded, $nfc_string; - } - return @strings_entity_encoded; + my @strings = @_; + my @strings_entity_encoded; + foreach my $string (@strings) { + my $nfc_string = NFC($string); + $nfc_string =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe; + push @strings_entity_encoded, $nfc_string; + } + return @strings_entity_encoded; } -END { } # module clean-up code here (global destructor) +END { } # module clean-up code here (global destructor) 1; __END__ diff --git a/C4/Reports.pm b/C4/Reports.pm index ef1f00417e..fc48fdd6c1 100644 --- a/C4/Reports.pm +++ b/C4/Reports.pm @@ -22,10 +22,11 @@ use CGI qw ( -utf8 ); use C4::Context; -our (@ISA, @EXPORT_OK); +our ( @ISA, @EXPORT_OK ); + BEGIN { require Exporter; - @ISA = qw(Exporter); + @ISA = qw(Exporter); @EXPORT_OK = qw( GetDelimiterChoices ); @@ -52,15 +53,15 @@ This will return a list of all the available delimiters. sub GetDelimiterChoices { my $dbh = C4::Context->dbh; - my $sth = $dbh->prepare(" + my $sth = $dbh->prepare( " SELECT options, value FROM systempreferences WHERE variable = 'CSVDelimiter' - "); + " ); $sth->execute(); - my ($choices, $default) = $sth->fetchrow; + my ( $choices, $default ) = $sth->fetchrow; my @dels = split /\|/, $choices; return { diff --git a/C4/Reports/Guided.pm b/C4/Reports/Guided.pm index 938eacd65b..f5f65d9639 100644 --- a/C4/Reports/Guided.pm +++ b/C4/Reports/Guided.pm @@ -19,13 +19,13 @@ package C4::Reports::Guided; use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use Carp qw( carp croak ); use JSON qw( from_json ); use C4::Context; use C4::Koha qw( GetAuthorisedValues ); -use C4::Log qw( logaction ); +use C4::Log qw( logaction ); use C4::Output; use C4::Templates qw/themelanguage/; use Koha::AuthorisedValues; @@ -39,24 +39,25 @@ use Koha::Reports; use Koha::SharedContent; use Koha::TemplateUtils qw( process_tt ); -our (@ISA, @EXPORT_OK); +our ( @ISA, @EXPORT_OK ); + BEGIN { require Exporter; - @ISA = qw(Exporter); + @ISA = qw(Exporter); @EXPORT_OK = qw( - get_report_types get_report_areas get_report_groups get_columns build_query get_criteria - save_report get_saved_reports execute_query - get_column_type get_distinct_values save_dictionary get_from_dictionary - delete_definition delete_report store_results format_results get_sql get_results - nb_rows update_sql - strip_limit - convert_sql - GetReservedAuthorisedValues - GetParametersFromSQL - IsAuthorisedValueValid - ValidateSQLParameters - nb_rows update_sql - EmailReport + get_report_types get_report_areas get_report_groups get_columns build_query get_criteria + save_report get_saved_reports execute_query + get_column_type get_distinct_values save_dictionary get_from_dictionary + delete_definition delete_report store_results format_results get_sql get_results + nb_rows update_sql + strip_limit + convert_sql + GetReservedAuthorisedValues + GetParametersFromSQL + IsAuthorisedValueValid + ValidateSQLParameters + nb_rows update_sql + EmailReport ); } @@ -82,17 +83,15 @@ This will return a list of all the available report areas sub get_area_name_sql_snippet { my @REPORT_AREA = ( - [CIRC => "Circulation"], - [CAT => "Catalogue"], - [PAT => "Patrons"], - [ACQ => "Acquisition"], - [ACC => "Accounts"], - [SER => "Serials"], + [ CIRC => "Circulation" ], + [ CAT => "Catalogue" ], + [ PAT => "Patrons" ], + [ ACQ => "Acquisition" ], + [ ACC => "Accounts" ], + [ SER => "Serials" ], ); - return "CASE report_area " . - join (" ", map "WHEN '$_->[0]' THEN '$_->[1]'", @REPORT_AREA) . - " END AS areaname"; + return "CASE report_area " . join( " ", map "WHEN '$_->[0]' THEN '$_->[1]'", @REPORT_AREA ) . " END AS areaname"; } sub get_report_areas { @@ -104,12 +103,15 @@ sub get_report_areas { sub get_table_areas { return ( - CIRC => [ 'borrowers', 'statistics', 'items', 'biblioitems' ], - CAT => [ 'items', 'biblioitems', 'biblio' ], - PAT => ['borrowers'], - ACQ => [ 'aqorders', 'biblio', 'items' ], - ACC => [ 'borrowers', 'accountlines' ], - SER => [ 'serial', 'serialitems', 'subscription', 'subscriptionhistory', 'subscriptionroutinglist', 'biblioitems', 'biblio', 'aqbooksellers' ], + CIRC => [ 'borrowers', 'statistics', 'items', 'biblioitems' ], + CAT => [ 'items', 'biblioitems', 'biblio' ], + PAT => ['borrowers'], + ACQ => [ 'aqorders', 'biblio', 'items' ], + ACC => [ 'borrowers', 'accountlines' ], + SER => [ + 'serial', 'serialitems', 'subscription', 'subscriptionhistory', 'subscriptionroutinglist', 'biblioitems', + 'biblio', 'aqbooksellers' + ], ); } @@ -144,24 +146,26 @@ This will return a list of all the available report areas with groups sub get_report_groups { my $dbh = C4::Context->dbh(); - my $groups = GetAuthorisedValues('REPORT_GROUP'); + my $groups = GetAuthorisedValues('REPORT_GROUP'); my $subgroups = GetAuthorisedValues('REPORT_SUBGROUP'); - my %groups_with_subgroups = map { $_->{authorised_value} => { - name => $_->{lib}, - groups => {} - } } @$groups; + my %groups_with_subgroups = map { + $_->{authorised_value} => { + name => $_->{lib}, + groups => {} + } + } @$groups; foreach (@$subgroups) { my $sg = $_->{authorised_value}; - my $g = $_->{lib_opac} - or warn( qq{REPORT_SUBGROUP "$sg" without REPORT_GROUP (lib_opac)} ), - next; + my $g = $_->{lib_opac} + or warn(qq{REPORT_SUBGROUP "$sg" without REPORT_GROUP (lib_opac)}), + next; my $g_sg = $groups_with_subgroups{$g} - or warn( qq{REPORT_SUBGROUP "$sg" with invalid REPORT_GROUP "$g"} ), - next; + or warn(qq{REPORT_SUBGROUP "$sg" with invalid REPORT_GROUP "$g"}), + next; $g_sg->{subgroups}{$sg} = $_->{lib}; } - return \%groups_with_subgroups + return \%groups_with_subgroups; } =head2 get_all_tables @@ -236,61 +240,69 @@ sub build_query { my ( $columns, $criteria, $orderby, $area, $totals, $definition ) = @_; my %keys = ( - CIRC => [ 'statistics.borrowernumber=borrowers.borrowernumber', - 'items.itemnumber = statistics.itemnumber', - 'biblioitems.biblioitemnumber = items.biblioitemnumber' ], - CAT => [ 'items.biblioitemnumber=biblioitems.biblioitemnumber', - 'biblioitems.biblionumber=biblio.biblionumber' ], - PAT => [], - ACQ => [ 'aqorders.biblionumber=biblio.biblionumber', - 'biblio.biblionumber=items.biblionumber' ], - ACC => ['borrowers.borrowernumber=accountlines.borrowernumber'], - SER => [ 'serial.serialid=serialitems.serialid', 'serial.subscriptionid=subscription.subscriptionid', 'serial.subscriptionid=subscriptionhistory.subscriptionid', 'serial.subscriptionid=subscriptionroutinglist.subscriptionid', 'biblioitems.biblionumber=serial.biblionumber', 'biblio.biblionumber=biblioitems.biblionumber', 'subscription.aqbooksellerid=aqbooksellers.id'], + CIRC => [ + 'statistics.borrowernumber=borrowers.borrowernumber', + 'items.itemnumber = statistics.itemnumber', + 'biblioitems.biblioitemnumber = items.biblioitemnumber' + ], + CAT => [ + 'items.biblioitemnumber=biblioitems.biblioitemnumber', + 'biblioitems.biblionumber=biblio.biblionumber' + ], + PAT => [], + ACQ => [ + 'aqorders.biblionumber=biblio.biblionumber', + 'biblio.biblionumber=items.biblionumber' + ], + ACC => ['borrowers.borrowernumber=accountlines.borrowernumber'], + SER => [ + 'serial.serialid=serialitems.serialid', 'serial.subscriptionid=subscription.subscriptionid', + 'serial.subscriptionid=subscriptionhistory.subscriptionid', + 'serial.subscriptionid=subscriptionroutinglist.subscriptionid', + 'biblioitems.biblionumber=serial.biblionumber', 'biblio.biblionumber=biblioitems.biblionumber', + 'subscription.aqbooksellerid=aqbooksellers.id' + ], ); - ### $orderby - my $keys = $keys{$area}; + my $keys = $keys{$area}; my %table_areas = get_table_areas; - my $tables = $table_areas{$area}; + my $tables = $table_areas{$area}; - my $sql = - _build_query( $tables, $columns, $criteria, $keys, $orderby, $totals, $definition ); + my $sql = _build_query( $tables, $columns, $criteria, $keys, $orderby, $totals, $definition ); return ($sql); } sub _build_query { - my ( $tables, $columns, $criteria, $keys, $orderby, $totals, $definition) = @_; + my ( $tables, $columns, $criteria, $keys, $orderby, $totals, $definition ) = @_; ### $orderby # $keys is an array of joining constraints my $dbh = C4::Context->dbh(); my $joinedtables = join( ',', @$tables ); my $joinedcolumns = join( ',', @$columns ); - my $query = - "SELECT $totals $joinedcolumns FROM $tables->[0] "; - for (my $i=1;$i<@$tables;$i++){ - $query .= "LEFT JOIN $tables->[$i] on ($keys->[$i-1]) "; - } + my $query = "SELECT $totals $joinedcolumns FROM $tables->[0] "; + for ( my $i = 1 ; $i < @$tables ; $i++ ) { + $query .= "LEFT JOIN $tables->[$i] on ($keys->[$i-1]) "; + } if ($criteria) { - $criteria =~ s/AND/WHERE/; + $criteria =~ s/AND/WHERE/; $query .= " $criteria"; } - if ($definition){ - my @definitions = split(',',$definition); - my $deftext; - foreach my $def (@definitions){ - my $defin=get_from_dictionary('',$def); - $deftext .=" ".$defin->[0]->{'saved_sql'}; - } - if ($query =~ /WHERE/i){ - $query .= $deftext; - } - else { - $deftext =~ s/AND/WHERE/; - $query .= $deftext; - } - } + if ($definition) { + my @definitions = split( ',', $definition ); + my $deftext; + foreach my $def (@definitions) { + my $defin = get_from_dictionary( '', $def ); + $deftext .= " " . $defin->[0]->{'saved_sql'}; + } + if ( $query =~ /WHERE/i ) { + $query .= $deftext; + } else { + $deftext =~ s/AND/WHERE/; + $query .= $deftext; + } + } if ($totals) { my $groupby; my @totcolumns = split( ',', $totals ); @@ -298,8 +310,7 @@ sub _build_query { if ( $total =~ /\((.*)\)/ ) { if ( $groupby eq '' ) { $groupby = " GROUP BY $1"; - } - else { + } else { $groupby .= ",$1"; } } @@ -319,44 +330,50 @@ Returns an arraref to hashrefs suitable for using in a tmpl_loop. With the crite =cut sub get_criteria { - my ($area,$cgi) = @_; - my $dbh = C4::Context->dbh(); + my ( $area, $cgi ) = @_; + my $dbh = C4::Context->dbh(); # have to do someting here to know if its dropdown, free text, date etc my %criteria = ( - CIRC => [ 'statistics.type', 'borrowers.categorycode', 'statistics.branch', - 'biblioitems.publicationyear|date', 'items.dateaccessioned|date' ], - CAT => [ 'items.itemnumber|textrange', 'items.biblionumber|textrange', - 'items.barcode|textrange', 'biblio.frameworkcode', - 'items.holdingbranch', 'items.homebranch', - 'biblio.datecreated|daterange', 'biblio.timestamp|daterange', - 'items.onloan|daterange', 'items.ccode', - 'items.itemcallnumber|textrange', 'items.itype', 'items.itemlost', - 'items.location' ], - PAT => [ 'borrowers.branchcode', 'borrowers.categorycode' ], - ACQ => ['aqorders.datereceived|date'], - ACC => [ 'borrowers.branchcode', 'borrowers.categorycode' ], - SER => ['subscription.startdate|date', 'subscription.enddate|date', 'subscription.periodicity', 'subscription.callnumber', 'subscription.location', 'subscription.branchcode'], + CIRC => [ + 'statistics.type', 'borrowers.categorycode', 'statistics.branch', + 'biblioitems.publicationyear|date', 'items.dateaccessioned|date' + ], + CAT => [ + 'items.itemnumber|textrange', 'items.biblionumber|textrange', + 'items.barcode|textrange', 'biblio.frameworkcode', + 'items.holdingbranch', 'items.homebranch', + 'biblio.datecreated|daterange', 'biblio.timestamp|daterange', + 'items.onloan|daterange', 'items.ccode', + 'items.itemcallnumber|textrange', 'items.itype', 'items.itemlost', + 'items.location' + ], + PAT => [ 'borrowers.branchcode', 'borrowers.categorycode' ], + ACQ => ['aqorders.datereceived|date'], + ACC => [ 'borrowers.branchcode', 'borrowers.categorycode' ], + SER => [ + 'subscription.startdate|date', 'subscription.enddate|date', 'subscription.periodicity', + 'subscription.callnumber', 'subscription.location', 'subscription.branchcode' + ], ); # Adds itemtypes to criteria, according to the syspref if ( C4::Context->preference('item-level_itypes') ) { unshift @{ $criteria{'CIRC'} }, 'items.itype'; - unshift @{ $criteria{'CAT'} }, 'items.itype'; + unshift @{ $criteria{'CAT'} }, 'items.itype'; } else { unshift @{ $criteria{'CIRC'} }, 'biblioitems.itemtype'; - unshift @{ $criteria{'CAT'} }, 'biblioitems.itemtype'; + unshift @{ $criteria{'CAT'} }, 'biblioitems.itemtype'; } - - my $crit = $criteria{$area}; + my $crit = $criteria{$area}; my $columns = Koha::Database::Columns->columns; my @criteria_array; foreach my $localcrit (@$crit) { my ( $value, $type ) = split( /\|/, $localcrit ); my ( $table, $column ) = split( /\./, $value ); my $description = $columns->{$table}->{$column}; - if ($type eq 'textrange') { + if ( $type eq 'textrange' ) { my %temp; $temp{'name'} = $value; $temp{'from'} = "from_" . $value; @@ -364,15 +381,13 @@ sub get_criteria { $temp{'textrange'} = 1; $temp{'description'} = $description; push @criteria_array, \%temp; - } - elsif ($type eq 'date') { + } elsif ( $type eq 'date' ) { my %temp; $temp{'name'} = $value; $temp{'date'} = 1; $temp{'description'} = $description; push @criteria_array, \%temp; - } - elsif ($type eq 'daterange') { + } elsif ( $type eq 'daterange' ) { my %temp; $temp{'name'} = $value; $temp{'from'} = "from_" . $value; @@ -380,26 +395,26 @@ sub get_criteria { $temp{'daterange'} = 1; $temp{'description'} = $description; push @criteria_array, \%temp; - } - else { - my $query = - "SELECT distinct($column) as availablevalues FROM $table"; - my $sth = $dbh->prepare($query); + } else { + my $query = "SELECT distinct($column) as availablevalues FROM $table"; + my $sth = $dbh->prepare($query); $sth->execute(); my @values; + # push the runtime choosing option my $list; - $list='branches' if $column eq 'branchcode' or $column eq 'holdingbranch' or $column eq 'homebranch'; - $list='categorycode' if $column eq 'categorycode'; - $list='itemtypes' if $column eq 'itype'; - $list='ccode' if $column eq 'ccode'; + $list = 'branches' if $column eq 'branchcode' or $column eq 'holdingbranch' or $column eq 'homebranch'; + $list = 'categorycode' if $column eq 'categorycode'; + $list = 'itemtypes' if $column eq 'itype'; + $list = 'ccode' if $column eq 'ccode'; + # TODO : improve to let the librarian choose the description at runtime push @values, { availablevalues => "<<$column" . ( $list ? "|$list" : '' ) . ">>", display_value => "<<$column" . ( $list ? "|$list" : '' ) . ">>", }; while ( my $row = $sth->fetchrow_hashref() ) { - if ($row->{'availablevalues'} eq '') { $row->{'default'} = 1 } + if ( $row->{'availablevalues'} eq '' ) { $row->{'default'} = 1 } else { $row->{display_value} = _get_display_value( $row->{'availablevalues'}, $column ); } push @values, $row; } @@ -419,12 +434,12 @@ sub nb_rows { my $sql = shift or return; my $derived_name = 'xxx'; + # make sure the derived table name is not already used while ( $sql =~ m/$derived_name/ ) { $derived_name .= 'x'; } - my $dbh = C4::Context->dbh; my $sth; my $n = 0; @@ -434,24 +449,27 @@ sub nb_rows { $dbh->{RaiseError} = 1; $dbh->{PrintError} = 0; eval { - $sth = $dbh->prepare(qq{ + $sth = $dbh->prepare( + qq{ SELECT COUNT(*) FROM ( $sql ) $derived_name - }); + } + ); $sth->execute(); }; $dbh->{RaiseError} = $RaiseError; $dbh->{PrintError} = $PrintError; - if ($@) { # To catch "Duplicate column name" caused by the derived table, or any other syntax error + if ($@) { # To catch "Duplicate column name" caused by the derived table, or any other syntax error eval { $sth = $dbh->prepare($sql); $sth->execute; }; warn $@ if $@; + # Loop through the complete results, fetching 1,000 rows at a time. This # lowers memory requirements but increases execution time. - while (my $rows = $sth->fetchall_arrayref(undef, 1000)) { + while ( my $rows = $sth->fetchall_arrayref( undef, 1000 ) ) { $n += @$rows; } return $n; @@ -471,6 +489,7 @@ sub nb_rows { =cut sub select_2_select_count { + # Modify the query passed in to create a count query... (I think this covers all cases -crn) my ($sql) = strip_limit(shift) or return; $sql =~ s/\bSELECT\W+(?:\w+\W+){1,}?FROM\b|\bSELECT\W\*\WFROM\b/SELECT count(*) FROM /ig; @@ -503,20 +522,20 @@ Notes: sub strip_limit { my ($sql) = @_; - return unless $sql; - return ($sql, 0, undef) unless $sql =~ /\bLIMIT\b/i; + return unless $sql; + return ( $sql, 0, undef ) unless $sql =~ /\bLIMIT\b/i; # Two options: if there's no WHERE clause in the SQL, we simply capture # any LIMIT that's there. If there is a WHERE, we make sure that we only # capture a LIMIT after the last one. This prevents stomping on subqueries. - if ($sql !~ /\bWHERE\b/i) { - (my $res = $sql) =~ s/\bLIMIT\b\s*(\d+)(\s*\,\s*(\d+))?\s*/ /ig; - return ($res, (defined $2 ? $1 : 0), (defined $3 ? $3 : $1)); + if ( $sql !~ /\bWHERE\b/i ) { + ( my $res = $sql ) =~ s/\bLIMIT\b\s*(\d+)(\s*\,\s*(\d+))?\s*/ /ig; + return ( $res, ( defined $2 ? $1 : 0 ), ( defined $3 ? $3 : $1 ) ); } else { my $res = $sql; $res =~ m/.*\bWHERE\b/gsi; $res =~ s/\G(.*)\bLIMIT\b\s*(\d+)(\s*\,\s*(\d+))?\s*/$1 /is; - return ($res, (defined $3 ? $2 : 0), (defined $4 ? $4 : $2)); + return ( $res, ( defined $3 ? $2 : 0 ), ( defined $4 ? $4 : $2 ) ); } } @@ -554,7 +573,7 @@ sub execute_query { my $params = shift; my $sql = $params->{sql}; my $offset = $params->{offset} || 0; - my $limit = $params->{limit} || C4::Context->config('report_results_limit') || 999999; + my $limit = $params->{limit} || C4::Context->config('report_results_limit') || 999999; my $sql_params = defined $params->{sql_params} ? $params->{sql_params} : []; my $report_id = $params->{report_id}; @@ -606,16 +625,19 @@ sub execute_query { $dbh->do( 'UPDATE saved_sql SET last_run = NOW() WHERE id = ?', undef, $report_id ) if $report_id; Koha::Logger->get( { prefix => 0, interface => 'reports', category => 'execute.query' } ) - ->info("Report $report_id : $sql, $offset, $limit") if $report_id; + ->info("Report $report_id : $sql, $offset, $limit") + if $report_id; Koha::Logger->get( { prefix => 0, interface => 'reports', category => 'execute.time.start' } ) - ->info("Report starting: $report_id") if $report_id; + ->info("Report starting: $report_id") + if $report_id; my $sth = $dbh->prepare($sql); eval { $sth->execute( @$sql_params, $offset, $limit ); }; warn $@ if $@; Koha::Logger->get( { prefix => 0, interface => 'reports', category => 'execute.time.end' } ) - ->info("Report finished: $report_id") if $report_id; + ->info("Report finished: $report_id") + if $report_id; return ( $sth, { queryerr => $sth->errstr } ) if ( $sth->err ); @@ -634,25 +656,25 @@ Returns id of the newly created report =cut sub save_report { - my ($fields) = @_; + my ($fields) = @_; my $borrowernumber = $fields->{borrowernumber}; - my $sql = $fields->{sql}; - my $name = $fields->{name}; - my $type = $fields->{type}; - my $notes = $fields->{notes}; - my $area = $fields->{area}; - my $group = $fields->{group}; - my $subgroup = $fields->{subgroup}; - my $cache_expiry = $fields->{cache_expiry}; - my $public = $fields->{public}; + my $sql = $fields->{sql}; + my $name = $fields->{name}; + my $type = $fields->{type}; + my $notes = $fields->{notes}; + my $area = $fields->{area}; + my $group = $fields->{group}; + my $subgroup = $fields->{subgroup}; + my $cache_expiry = $fields->{cache_expiry}; + my $public = $fields->{public}; $sql =~ s/(\s*\;\s*)$//; # removes trailing whitespace and /;/ - my $now = dt_from_string; + my $now = dt_from_string; my $report = Koha::Report->new( { borrowernumber => $borrowernumber, - date_created => $now, # Must be moved to Koha::Report->store - last_modified => $now, # Must be moved to Koha::Report->store + date_created => $now, # Must be moved to Koha::Report->store + last_modified => $now, # Must be moved to Koha::Report->store savedsql => $sql, report_name => $name, report_area => $area, @@ -669,15 +691,15 @@ sub save_report { } sub update_sql { - my $id = shift || croak "No Id given"; - my $fields = shift; - my $sql = $fields->{sql}; - my $name = $fields->{name}; - my $notes = $fields->{notes}; - my $group = $fields->{group}; - my $subgroup = $fields->{subgroup}; + my $id = shift || croak "No Id given"; + my $fields = shift; + my $sql = $fields->{sql}; + my $name = $fields->{name}; + my $notes = $fields->{notes}; + my $group = $fields->{group}; + my $subgroup = $fields->{subgroup}; my $cache_expiry = $fields->{cache_expiry}; - my $public = $fields->{public}; + my $public = $fields->{public}; $sql =~ s/(\s*\;\s*)$// if defined $sql; # removes trailing whitespace and /;/ my $report = Koha::Reports->find($id); @@ -690,8 +712,9 @@ sub update_sql { $report->cache_expiry($cache_expiry) if defined $cache_expiry; $report->public($public); $report->store(); - if( $cache_expiry >= 2592000 ){ - die "Please specify a cache expiry less than 30 days\n"; # That's a bit harsh + + if ( $cache_expiry >= 2592000 ) { + die "Please specify a cache expiry less than 30 days\n"; # That's a bit harsh } return $report; @@ -700,25 +723,29 @@ sub update_sql { sub store_results { my ( $id, $json ) = @_; my $dbh = C4::Context->dbh(); - $dbh->do(q| + $dbh->do( + q| INSERT INTO saved_reports ( report_id, report, date_run ) VALUES ( ?, ?, NOW() ); - |, undef, $id, $json ); + |, undef, $id, $json + ); } sub format_results { - my ( $id ) = @_; + my ($id) = @_; my $dbh = C4::Context->dbh(); - my ( $report_name, $notes, $json, $date_run ) = $dbh->selectrow_array(q| + my ( $report_name, $notes, $json, $date_run ) = $dbh->selectrow_array( + q| SELECT ss.report_name, ss.notes, sr.report, sr.date_run FROM saved_sql ss LEFT JOIN saved_reports sr ON sr.report_id = ss.id WHERE sr.id = ? - |, undef, $id); + |, undef, $id + ); return { report_name => $report_name, - notes => $notes, - results => from_json( $json ), - date_run => $date_run, + notes => $notes, + results => from_json($json), + date_run => $date_run, }; } @@ -727,11 +754,12 @@ sub delete_report { return unless @ids; foreach my $id (@ids) { my $data = Koha::Reports->find($id); - logaction( "REPORTS", "DELETE", $id, $data->report_name." | ".$data->savedsql ) if C4::Context->preference("ReportsLog"); + logaction( "REPORTS", "DELETE", $id, $data->report_name . " | " . $data->savedsql ) + if C4::Context->preference("ReportsLog"); } - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $query = 'DELETE FROM saved_sql WHERE id IN (' . join( ',', ('?') x @ids ) . ')'; - my $sth = $dbh->prepare($query); + my $sth = $dbh->prepare($query); return $sth->execute(@ids); } @@ -749,28 +777,29 @@ EOQ } sub get_saved_reports { -# $filter is either { date => $d, author => $a, keyword => $kw, } -# or $keyword. Optional. + + # $filter is either { date => $d, author => $a, keyword => $kw, } + # or $keyword. Optional. my ($filter) = @_; - $filter = { keyword => $filter } if $filter && !ref( $filter ); - my ($group, $subgroup) = @_; + $filter = { keyword => $filter } if $filter && !ref($filter); + my ( $group, $subgroup ) = @_; my $dbh = C4::Context->dbh(); my $query = get_saved_reports_base_query; - my (@cond,@args); + my ( @cond, @args ); if ($filter) { - if (my $date = $filter->{date}) { + if ( my $date = $filter->{date} ) { push @cond, "DATE(last_modified) = ? OR DATE(last_run) = ?"; push @args, $date, $date; } - if (my $author = $filter->{author}) { + if ( my $author = $filter->{author} ) { $author = "%$author%"; push @cond, "surname LIKE ? OR firstname LIKE ?"; push @args, $author, $author; } - if (my $keyword = $filter->{keyword}) { + if ( my $keyword = $filter->{keyword} ) { push @cond, q| report LIKE ? OR report_name LIKE ? @@ -780,20 +809,21 @@ sub get_saved_reports { |; push @args, "%$keyword%", "%$keyword%", "%$keyword%", "%$keyword%", $keyword; } - if ($filter->{group}) { + if ( $filter->{group} ) { push @cond, "report_group = ?"; push @args, $filter->{group}; } - if ($filter->{subgroup}) { + if ( $filter->{subgroup} ) { push @cond, "report_subgroup = ?"; push @args, $filter->{subgroup}; } } - $query .= " WHERE ".join( " AND ", map "($_)", @cond ) if @cond; - $query .= " GROUP BY s.id, s.borrowernumber, s.date_created, s.last_modified, s.savedsql, s.last_run, s.report_name, s.type, s.notes, s.cache_expiry, s.public, s.report_area, s.report_group, s.report_subgroup, s.mana_id, av_g.lib, av_sg.lib, b.firstname, b.surname"; + $query .= " WHERE " . join( " AND ", map "($_)", @cond ) if @cond; + $query .= + " GROUP BY s.id, s.borrowernumber, s.date_created, s.last_modified, s.savedsql, s.last_run, s.report_name, s.type, s.notes, s.cache_expiry, s.public, s.report_area, s.report_group, s.report_subgroup, s.mana_id, av_g.lib, av_sg.lib, b.firstname, b.surname"; $query .= " ORDER by date_created"; - my $result = $dbh->selectall_arrayref($query, {Slice => {}}, @args); + my $result = $dbh->selectall_arrayref( $query, { Slice => {} }, @args ); return $result; } @@ -806,24 +836,25 @@ This takes a column name of the format table.column and will return what type it =cut sub get_column_type { - my ($tablecolumn) = @_; - my ($table,$column) = split(/\./,$tablecolumn); - my $dbh = C4::Context->dbh(); - my $catalog; - my $schema; + my ($tablecolumn) = @_; + my ( $table, $column ) = split( /\./, $tablecolumn ); + my $dbh = C4::Context->dbh(); + my $catalog; + my $schema; # mysql doesn't support a column selection, set column to % - my $tempcolumn='%'; - my $sth = $dbh->column_info( $catalog, $schema, $table, $tempcolumn ) || die $dbh->errstr; - while (my $info = $sth->fetchrow_hashref()){ - if ($info->{'COLUMN_NAME'} eq $column){ - #column we want - if ($info->{'TYPE_NAME'} eq 'CHAR' || $info->{'TYPE_NAME'} eq 'VARCHAR'){ - $info->{'TYPE_NAME'} = 'distinct'; - } - return $info->{'TYPE_NAME'}; - } - } + my $tempcolumn = '%'; + my $sth = $dbh->column_info( $catalog, $schema, $table, $tempcolumn ) || die $dbh->errstr; + while ( my $info = $sth->fetchrow_hashref() ) { + if ( $info->{'COLUMN_NAME'} eq $column ) { + + #column we want + if ( $info->{'TYPE_NAME'} eq 'CHAR' || $info->{'TYPE_NAME'} eq 'VARCHAR' ) { + $info->{'TYPE_NAME'} = 'distinct'; + } + return $info->{'TYPE_NAME'}; + } + } } =head2 get_distinct_values($column) @@ -834,15 +865,14 @@ with the distinct values of the column =cut sub get_distinct_values { - my ($tablecolumn) = @_; - my ($table,$column) = split(/\./,$tablecolumn); - my $dbh = C4::Context->dbh(); - my $query = - "SELECT distinct($column) as availablevalues FROM $table"; - my $sth = $dbh->prepare($query); - $sth->execute(); - return $sth->fetchall_arrayref({}); -} + my ($tablecolumn) = @_; + my ( $table, $column ) = split( /\./, $tablecolumn ); + my $dbh = C4::Context->dbh(); + my $query = "SELECT distinct($column) as availablevalues FROM $table"; + my $sth = $dbh->prepare($query); + $sth->execute(); + return $sth->fetchall_arrayref( {} ); +} sub save_dictionary { my ( $name, $description, $sql, $area ) = @_; @@ -850,15 +880,15 @@ sub save_dictionary { my $query = "INSERT INTO reports_dictionary (name,description,saved_sql,report_area,date_created,date_modified) VALUES (?,?,?,?,now(),now())"; my $sth = $dbh->prepare($query); - $sth->execute($name,$description,$sql,$area) || return 0; + $sth->execute( $name, $description, $sql, $area ) || return 0; return 1; } sub get_from_dictionary { my ( $area, $id ) = @_; - my $dbh = C4::Context->dbh(); + my $dbh = C4::Context->dbh(); my $area_name_sql_snippet = get_area_name_sql_snippet; - my $query = <dbh(); - my $query = "DELETE FROM reports_dictionary WHERE id = ?"; - my $sth = $dbh->prepare($query); - $sth->execute($id); + my ($id) = @_ or return; + my $dbh = C4::Context->dbh(); + my $query = "DELETE FROM reports_dictionary WHERE id = ?"; + my $sth = $dbh->prepare($query); + $sth->execute($id); } =head2 get_sql($report_id) @@ -899,23 +929,25 @@ Otherwise, it just returns. =cut sub get_sql { - my ($id) = @_ or return; - my $dbh = C4::Context->dbh(); - my $query = "SELECT * FROM saved_sql WHERE id = ?"; - my $sth = $dbh->prepare($query); - $sth->execute($id); - my $data=$sth->fetchrow_hashref(); - return $data->{'savedsql'}; + my ($id) = @_ or return; + my $dbh = C4::Context->dbh(); + my $query = "SELECT * FROM saved_sql WHERE id = ?"; + my $sth = $dbh->prepare($query); + $sth->execute($id); + my $data = $sth->fetchrow_hashref(); + return $data->{'savedsql'}; } sub get_results { - my ( $report_id ) = @_; + my ($report_id) = @_; my $dbh = C4::Context->dbh; - return $dbh->selectall_arrayref(q| + return $dbh->selectall_arrayref( + q| SELECT id, report, date_run FROM saved_reports WHERE report_id = ? - |, { Slice => {} }, $report_id); + |, { Slice => {} }, $report_id + ); } =head2 GetReservedAuthorisedValues @@ -928,21 +960,22 @@ Returns a hash containig all reserved words sub GetReservedAuthorisedValues { my %reserved_authorised_values = - map { $_ => 1 } ( 'date', - 'list', - 'branches', - 'itemtypes', - 'cn_source', - 'categorycode', - 'biblio_framework', - 'cash_registers', - 'debit_types', - 'credit_types' ); + map { $_ => 1 } ( + 'date', + 'list', + 'branches', + 'itemtypes', + 'cn_source', + 'categorycode', + 'biblio_framework', + 'cash_registers', + 'debit_types', + 'credit_types' + ); - return \%reserved_authorised_values; + return \%reserved_authorised_values; } - =head2 IsAuthorisedValueValid my $is_valid_ath_value = IsAuthorisedValueValid($authorised_value) @@ -954,11 +987,12 @@ in the authorised value categories defined in sub IsAuthorisedValueValid { - my $authorised_value = shift; + my $authorised_value = shift; my $reserved_authorised_values = GetReservedAuthorisedValues(); - if ( exists $reserved_authorised_values->{$authorised_value} || - Koha::AuthorisedValues->search({ category => $authorised_value })->count ) { + if ( exists $reserved_authorised_values->{$authorised_value} + || Koha::AuthorisedValues->search( { category => $authorised_value } )->count ) + { return 1; } @@ -975,12 +1009,12 @@ Returns an arrayref of hashes containing the keys name and authval sub GetParametersFromSQL { - my $sql = shift ; - my @split = split(/<<|>>/,$sql); + my $sql = shift; + my @split = split( /<<|>>/, $sql ); my @sql_parameters = (); - for ( my $i = 0; $i < ($#split/2) ; $i++ ) { - my ($name,$authval) = split(/\|/,$split[$i*2+1]); + for ( my $i = 0 ; $i < ( $#split / 2 ) ; $i++ ) { + my ( $name, $authval ) = split( /\|/, $split[ $i * 2 + 1 ] ); $authval =~ s/\:all$|\:in$// if $authval; push @sql_parameters, { 'name' => $name, 'authval' => $authval }; } @@ -999,14 +1033,14 @@ those SQL parameters that do not correspond to valid authorised names sub ValidateSQLParameters { - my $sql = shift; + my $sql = shift; my @problematic_parameters = (); - my $sql_parameters = GetParametersFromSQL($sql); + my $sql_parameters = GetParametersFromSQL($sql); foreach my $sql_parameter (@$sql_parameters) { if ( defined $sql_parameter->{'authval'} ) { - push @problematic_parameters, $sql_parameter unless - IsAuthorisedValueValid($sql_parameter->{'authval'}); + push @problematic_parameters, $sql_parameter + unless IsAuthorisedValueValid( $sql_parameter->{'authval'} ); } } @@ -1024,61 +1058,64 @@ Returns arrayrefs containing prepared letters and errors respectively sub EmailReport { - my $params = shift; - my $report_id = $params->{report_id}; - my $from = $params->{from}; - my $email_col = $params->{email} || 'email'; - my $module = $params->{module}; - my $code = $params->{code}; - my $branch = $params->{branch} || ""; + my $params = shift; + my $report_id = $params->{report_id}; + my $from = $params->{from}; + my $email_col = $params->{email} || 'email'; + my $module = $params->{module}; + my $code = $params->{code}; + my $branch = $params->{branch} || ""; my @errors = (); my @emails = (); - return ( undef, [{ FATAL => "MISSING_PARAMS" }] ) unless ($report_id && $module && $code); + return ( undef, [ { FATAL => "MISSING_PARAMS" } ] ) unless ( $report_id && $module && $code ); - return ( undef, [{ FATAL => "NO_LETTER" }] ) unless - my $letter = Koha::Notice::Templates->find({ - module => $module, - code => $code, - branchcode => $branch, - message_transport_type => 'email', - }); + return ( undef, [ { FATAL => "NO_LETTER" } ] ) + unless my $letter = Koha::Notice::Templates->find( + { + module => $module, + code => $code, + branchcode => $branch, + message_transport_type => 'email', + } + ); $letter = $letter->unblessed; $letter->{'content-type'} = 'text/html; charset="UTF-8"' if $letter->{'is_html'}; - my $report = Koha::Reports->find( $report_id ); - my $sql = $report->savedsql; + my $report = Koha::Reports->find($report_id); + my $sql = $report->savedsql; return ( { FATAL => "NO_REPORT" } ) unless $sql; #don't pass offset or limit, hardcoded limit of 999,999 will be used my ( $sth, $errors ) = execute_query( { sql => $sql, report_id => $report_id } ); - return ( undef, [{ FATAL => "REPORT_FAIL" }] ) if $errors; + return ( undef, [ { FATAL => "REPORT_FAIL" } ] ) if $errors; - my $counter = 1; + my $counter = 1; my $template = $letter->{content}; while ( my $row = $sth->fetchrow_hashref() ) { my $email; my $err_count = scalar @errors; - push ( @errors, { NO_BOR_COL => $counter } ) unless defined $row->{borrowernumber}; - push ( @errors, { NO_EMAIL_COL => $counter } ) unless ( defined $row->{$email_col} ); - push ( @errors, { NO_FROM_COL => $counter } ) unless defined ( $from || $row->{from} ); - push ( @errors, { NO_BOR => $row->{borrowernumber} } ) unless Koha::Patrons->find({borrowernumber=>$row->{borrowernumber}}); + push( @errors, { NO_BOR_COL => $counter } ) unless defined $row->{borrowernumber}; + push( @errors, { NO_EMAIL_COL => $counter } ) unless ( defined $row->{$email_col} ); + push( @errors, { NO_FROM_COL => $counter } ) unless defined( $from || $row->{from} ); + push( @errors, { NO_BOR => $row->{borrowernumber} } ) + unless Koha::Patrons->find( { borrowernumber => $row->{borrowernumber} } ); my $from_address = $from || $row->{from}; - my $to_address = $row->{$email_col}; - push ( @errors, { NOT_PARSE => $counter } ) unless my $content = process_tt( $template, $row ); + my $to_address = $row->{$email_col}; + push( @errors, { NOT_PARSE => $counter } ) unless my $content = process_tt( $template, $row ); $counter++; - next if scalar @errors > $err_count; #If any problems, try next + next if scalar @errors > $err_count; #If any problems, try next $letter->{content} = $content; $email->{borrowernumber} = $row->{borrowernumber}; - $email->{letter} = { %$letter }; + $email->{letter} = {%$letter}; $email->{from_address} = $from_address; $email->{to_address} = $to_address; - push ( @emails, $email ); + push( @emails, $email ); } return ( \@emails, \@errors ); @@ -1088,7 +1125,7 @@ sub EmailReport { sub _get_display_value { my ( $original_value, $column ) = @_; if ( $column eq 'periodicity' ) { - my $dbh = C4::Context->dbh(); + my $dbh = C4::Context->dbh(); my $query = "SELECT description FROM subscription_frequencies WHERE id = ?"; my $sth = $dbh->prepare($query); $sth->execute($original_value); @@ -1097,7 +1134,6 @@ sub _get_display_value { return $original_value; } - =head3 convert_sql my $updated_sql = C4::Reports::Guided::convert_sql( $sql ); @@ -1108,7 +1144,7 @@ biblio_metadata.metadata field instead =cut sub convert_sql { - my ( $sql ) = @_; + my ($sql) = @_; my $updated_sql = $sql; if ( $sql =~ m|biblioitems| and $sql =~ m|marcxml| ) { $updated_sql =~ s|biblioitems|biblio_metadata|g; diff --git a/C4/Reserves.pm b/C4/Reserves.pm index 667020adef..432ae461dc 100644 --- a/C4/Reserves.pm +++ b/C4/Reserves.pm @@ -20,11 +20,10 @@ package C4::Reserves; # You should have received a copy of the GNU General Public License # along with Koha; if not, see . - use Modern::Perl; use C4::Accounts; -use C4::Biblio qw( GetMarcFromKohaField ); +use C4::Biblio qw( GetMarcFromKohaField ); use C4::Circulation qw( CheckIfIssuedToPatron GetAgeRestriction GetBranchItemRule ); use C4::Context; use C4::Items qw( CartToShelf get_hostitemnumbers_of ); @@ -96,48 +95,49 @@ This modules provides somes functions to deal with reservations. =cut -our (@ISA, @EXPORT_OK); +our ( @ISA, @EXPORT_OK ); + BEGIN { require Exporter; - @ISA = qw(Exporter); + @ISA = qw(Exporter); @EXPORT_OK = qw( - AddReserve + AddReserve - GetReserveStatus + GetReserveStatus - ChargeReserveFee - GetReserveFee + ChargeReserveFee + GetReserveFee - ModReserveAffect - ModReserve - ModReserveStatus - ModReserveCancelAll - ModReserveMinusPriority - MoveReserve + ModReserveAffect + ModReserve + ModReserveStatus + ModReserveCancelAll + ModReserveMinusPriority + MoveReserve - CheckReserves - CanBookBeReserved - CanItemBeReserved - CancelExpiredReserves + CheckReserves + CanBookBeReserved + CanItemBeReserved + CancelExpiredReserves - AutoUnsuspendReserves + AutoUnsuspendReserves - IsAvailableForItemLevelRequest - ItemsAnyAvailableAndNotRestricted + IsAvailableForItemLevelRequest + ItemsAnyAvailableAndNotRestricted - AlterPriority - ToggleLowestPriority + AlterPriority + ToggleLowestPriority - ReserveSlip - SuspendAll + ReserveSlip + SuspendAll - CalculatePriority + CalculatePriority - GetMaxPatronHoldsForRecord + GetMaxPatronHoldsForRecord - MergeHolds + MergeHolds - RevertWaitingStatus + RevertWaitingStatus ); } @@ -179,27 +179,27 @@ The following tables are available within the HOLDPLACED_PATRON message: =cut sub AddReserve { - my ($params) = @_; - my $branch = $params->{branchcode}; - my $borrowernumber = $params->{borrowernumber}; - my $biblionumber = $params->{biblionumber}; - my $priority = $params->{priority}; - my $resdate = $params->{reservation_date}; + my ($params) = @_; + my $branch = $params->{branchcode}; + my $borrowernumber = $params->{borrowernumber}; + my $biblionumber = $params->{biblionumber}; + my $priority = $params->{priority}; + my $resdate = $params->{reservation_date}; my $patron_expiration_date = $params->{expiration_date}; - my $notes = $params->{notes}; - my $title = $params->{title}; - my $checkitem = $params->{itemnumber}; - my $found = $params->{found}; - my $itemtype = $params->{itemtype}; - my $non_priority = $params->{non_priority}; - my $item_group_id = $params->{item_group_id}; + my $notes = $params->{notes}; + my $title = $params->{title}; + my $checkitem = $params->{itemnumber}; + my $found = $params->{found}; + my $itemtype = $params->{itemtype}; + my $non_priority = $params->{non_priority}; + my $item_group_id = $params->{item_group_id}; $resdate ||= dt_from_string; # if we have an item selectionned, and the pickup branch is the same as the holdingbranch # of the document, we force the value $priority and $found . if ( $checkitem and not C4::Context->preference('ReservesNeedReturns') ) { - my $item = Koha::Items->find( $checkitem ); # FIXME Prevent bad calls + my $item = Koha::Items->find($checkitem); # FIXME Prevent bad calls if ( # If item is already checked out, it cannot be set waiting @@ -215,15 +215,17 @@ sub AddReserve { && ( $item->damaged && C4::Context->preference('AllowHoldsOnDamagedItems') || !$item->damaged ) # Lastly, if this already has holds, we shouldn't make it waiting for the new hold - && !$item->current_holds->count ) + && !$item->current_holds->count + ) { $priority = 0; - $found = 'W'; + $found = 'W'; } } - if ( C4::Context->preference( 'AllowHoldDateInFuture' ) ) { - # Make room in reserves for this if passed a priority - $priority = _ShiftPriority( $biblionumber, $priority ); + if ( C4::Context->preference('AllowHoldDateInFuture') ) { + + # Make room in reserves for this if passed a priority + $priority = _ShiftPriority( $biblionumber, $priority ); } my $waitingdate; @@ -239,20 +241,20 @@ sub AddReserve { # updates take place here my $hold = Koha::Hold->new( { - borrowernumber => $borrowernumber, - biblionumber => $biblionumber, - item_group_id => $item_group_id, - reservedate => $resdate, - branchcode => $branch, - priority => $priority, - reservenotes => $notes, - itemnumber => $checkitem, - found => $found, - waitingdate => $waitingdate, + borrowernumber => $borrowernumber, + biblionumber => $biblionumber, + item_group_id => $item_group_id, + reservedate => $resdate, + branchcode => $branch, + priority => $priority, + reservenotes => $notes, + itemnumber => $checkitem, + found => $found, + waitingdate => $waitingdate, patron_expiration_date => $patron_expiration_date, - itemtype => $itemtype, - item_level_hold => $checkitem ? 1 : 0, - non_priority => $non_priority ? 1 : 0, + itemtype => $itemtype, + item_level_hold => $checkitem ? 1 : 0, + non_priority => $non_priority ? 1 : 0, } )->store(); $hold->set_waiting() if $found && $found eq 'W'; @@ -271,26 +273,29 @@ sub AddReserve { ChargeReserveFee( $borrowernumber, $reserve_fee, $title ); } - _FixPriority({ biblionumber => $biblionumber}); + _FixPriority( { biblionumber => $biblionumber } ); # Send e-mail to librarian if syspref is active - if(C4::Context->preference("emailLibrarianWhenHoldIsPlaced")){ - my $patron = $hold->patron; + if ( C4::Context->preference("emailLibrarianWhenHoldIsPlaced") ) { + my $patron = $hold->patron; my $library = $patron->library; - if ( my $letter = C4::Letters::GetPreparedLetter ( - module => 'reserves', - letter_code => 'HOLDPLACED', - branchcode => $branch, - lang => $patron->lang, - tables => { - 'branches' => $library->unblessed, - 'borrowers' => $patron->unblessed, - 'biblio' => $biblionumber, - 'biblioitems' => $biblionumber, - 'items' => $checkitem, - 'reserves' => $hold->unblessed, - }, - ) ) { + if ( + my $letter = C4::Letters::GetPreparedLetter( + module => 'reserves', + letter_code => 'HOLDPLACED', + branchcode => $branch, + lang => $patron->lang, + tables => { + 'branches' => $library->unblessed, + 'borrowers' => $patron->unblessed, + 'biblio' => $biblionumber, + 'biblioitems' => $biblionumber, + 'items' => $checkitem, + 'reserves' => $hold->unblessed, + }, + ) + ) + { my $branch_email_address = $library->inbound_email_address; @@ -332,7 +337,7 @@ sub AddReserve { } } - Koha::Plugins->call('after_hold_create', $hold); + Koha::Plugins->call( 'after_hold_create', $hold ); Koha::Plugins->call( 'after_hold_action', { @@ -341,11 +346,8 @@ sub AddReserve { } ); - Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue->new->enqueue( - { - biblio_ids => [ $biblionumber ] - } - ) if C4::Context->preference('RealTimeHoldsQueue'); + Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue->new->enqueue( { biblio_ids => [$biblionumber] } ) + if C4::Context->preference('RealTimeHoldsQueue'); return $reserve_id; } @@ -361,13 +363,14 @@ See CanItemBeReserved() for possible return values. =cut -sub CanBookBeReserved{ - my ($borrowernumber, $biblionumber, $pickup_branchcode, $params) = @_; +sub CanBookBeReserved { + my ( $borrowernumber, $biblionumber, $pickup_branchcode, $params ) = @_; # Check that patron have not checked out this biblio (if AllowHoldsOnPatronsPossessions set) if ( !C4::Context->preference('AllowHoldsOnPatronsPossessions') - && C4::Circulation::CheckIfIssuedToPatron( $borrowernumber, $biblionumber ) ) { - return { status =>'alreadypossession' }; + && C4::Circulation::CheckIfIssuedToPatron( $borrowernumber, $biblionumber ) ) + { + return { status => 'alreadypossession' }; } if ( $params->{itemtype} ) { @@ -392,31 +395,32 @@ sub CanBookBeReserved{ { 'item.itype' => $params->{itemtype} } ] }, - { - join => ['item'] - } + { join => ['item'] } )->count; return { status => '' } - if defined $reservesallowed and $reservesallowed < $count + 1; + if defined $reservesallowed and $reservesallowed < $count + 1; } my $items; + #get items linked via host records my @hostitemnumbers = get_hostitemnumbers_of($biblionumber); - if (@hostitemnumbers){ - $items = Koha::Items->search({ - -or => [ - biblionumber => $biblionumber, - itemnumber => { -in => @hostitemnumbers } - ] - }); + if (@hostitemnumbers) { + $items = Koha::Items->search( + { + -or => [ + biblionumber => $biblionumber, + itemnumber => { -in => @hostitemnumbers } + ] + } + ); } else { - $items = Koha::Items->search({ biblionumber => $biblionumber}); + $items = Koha::Items->search( { biblionumber => $biblionumber } ); } my $canReserve = { status => '' }; - my $patron = Koha::Patrons->find( $borrowernumber ); + my $patron = Koha::Patrons->find($borrowernumber); while ( my $item = $items->next ) { $canReserve = CanItemBeReserved( $patron, $item, $pickup_branchcode, $params ); return { status => 'OK' } if $canReserve->{status} eq 'OK'; @@ -449,8 +453,9 @@ sub CanBookBeReserved{ =cut our $CanItemBeReserved_cache_key; + sub _cache { - my ( $return ) = @_; + my ($return) = @_; my $memory_cache = Koha::Cache::Memory::Lite->get_instance(); $memory_cache->set_in_cache( $CanItemBeReserved_cache_key, $return ); return $return; @@ -460,15 +465,16 @@ sub CanItemBeReserved { my ( $patron, $item, $pickup_branchcode, $params ) = @_; my $memory_cache = Koha::Cache::Memory::Lite->get_instance(); - $CanItemBeReserved_cache_key = sprintf "Hold_CanItemBeReserved:%s:%s:%s", $patron->borrowernumber, $item->itemnumber, $pickup_branchcode || ""; + $CanItemBeReserved_cache_key = sprintf "Hold_CanItemBeReserved:%s:%s:%s", $patron->borrowernumber, + $item->itemnumber, $pickup_branchcode || ""; if ( $params->{get_from_cache} ) { my $cached = $memory_cache->get_from_cache($CanItemBeReserved_cache_key); return $cached if $cached; } my $dbh = C4::Context->dbh; - my $ruleitemtype; # itemtype of the matching issuing rule - my $allowedreserves = 0; # Total number of holds allowed across all records, default to none + my $ruleitemtype; # itemtype of the matching issuing rule + my $allowedreserves = 0; # Total number of holds allowed across all records, default to none # We check item branch if IndependentBranches is ON # and canreservefromotherbranches is OFF @@ -481,30 +487,35 @@ sub CanItemBeReserved { } # If an item is damaged and we don't allow holds on damaged items, we can stop right here - return _cache { status =>'damaged' } - if ( $item->damaged + return _cache { status => 'damaged' } + if ( $item->damaged && !C4::Context->preference('AllowHoldsOnDamagedItems') ); - if( GetMarcFromKohaField('biblioitems.agerestriction') ){ + if ( GetMarcFromKohaField('biblioitems.agerestriction') ) { my $biblio = $item->biblio; + # Check for the age restriction my $ageRestriction = C4::Circulation::GetAgeRestriction( $biblio->biblioitem->agerestriction ); - return _cache { status => 'ageRestricted' } if $ageRestriction && $patron->dateofbirth && $ageRestriction > $patron->get_age(); + return _cache { status => 'ageRestricted' } + if $ageRestriction && $patron->dateofbirth && $ageRestriction > $patron->get_age(); } # Check that the patron doesn't have an item level hold on this item already - return _cache { status =>'itemAlreadyOnHold' } - if ( !$params->{ignore_hold_counts} && Koha::Holds->search( { borrowernumber => $patron->borrowernumber, itemnumber => $item->itemnumber } )->count() ); + return _cache { status => 'itemAlreadyOnHold' } + if ( !$params->{ignore_hold_counts} + && Koha::Holds->search( { borrowernumber => $patron->borrowernumber, itemnumber => $item->itemnumber } ) + ->count() ); # Check that patron have not checked out this biblio (if AllowHoldsOnPatronsPossessions set) if ( !C4::Context->preference('AllowHoldsOnPatronsPossessions') - && C4::Circulation::CheckIfIssuedToPatron( $patron->borrowernumber, $item->biblionumber ) ) { - return _cache { status =>'alreadypossession' }; + && C4::Circulation::CheckIfIssuedToPatron( $patron->borrowernumber, $item->biblionumber ) ) + { + return _cache { status => 'alreadypossession' }; } # check if a recall exists on this item from this borrower return _cache { status => 'recall' } - if $patron->recalls->filter_by_current->search({ item_id => $item->itemnumber })->count; + if $patron->recalls->filter_by_current->search( { item_id => $item->itemnumber } )->count; my $controlbranch = C4::Context->preference('ReservesControlBranch'); @@ -512,40 +523,43 @@ sub CanItemBeReserved { my $branchfield = "reserves.branchcode"; if ( $controlbranch eq "ItemHomeLibrary" ) { - $branchfield = "items.homebranch"; - $reserves_control_branch = $item->homebranch; - } - elsif ( $controlbranch eq "PatronLibrary" ) { - $branchfield = "borrowers.branchcode"; - $reserves_control_branch = $patron->branchcode; + $branchfield = "items.homebranch"; + $reserves_control_branch = $item->homebranch; + } elsif ( $controlbranch eq "PatronLibrary" ) { + $branchfield = "borrowers.branchcode"; + $reserves_control_branch = $patron->branchcode; } # we retrieve rights if ( - my $reservesallowed = Koha::CirculationRules->get_effective_rule({ + my $reservesallowed = Koha::CirculationRules->get_effective_rule( + { itemtype => $item->effective_itemtype, categorycode => $patron->categorycode, branchcode => $reserves_control_branch, rule_name => 'reservesallowed', - }) - ) { - $ruleitemtype = $reservesallowed->itemtype; - $allowedreserves = $reservesallowed->rule_value // 0; #undefined is 0, blank is unlimited - } - else { + } + ) + ) + { + $ruleitemtype = $reservesallowed->itemtype; + $allowedreserves = $reservesallowed->rule_value // 0; #undefined is 0, blank is unlimited + } else { $ruleitemtype = undef; } - my $rights = Koha::CirculationRules->get_effective_rules({ - categorycode => $patron->categorycode, - itemtype => $item->effective_itemtype, - branchcode => $reserves_control_branch, - rules => ['holds_per_record','holds_per_day'] - }); + my $rights = Koha::CirculationRules->get_effective_rules( + { + categorycode => $patron->categorycode, + itemtype => $item->effective_itemtype, + branchcode => $reserves_control_branch, + rules => [ 'holds_per_record', 'holds_per_day' ] + } + ); my $holds_per_record = $rights->{holds_per_record} // 1; my $holds_per_day = $rights->{holds_per_day}; - if ( defined $holds_per_record && $holds_per_record ne '' ){ + if ( defined $holds_per_record && $holds_per_record ne '' ) { if ( $holds_per_record == 0 ) { return _cache { status => "noReservesAllowed" }; } @@ -555,25 +569,29 @@ sub CanItemBeReserved { biblionumber => $item->biblionumber, }; my $holds = Koha::Holds->search($search_params); - return _cache { status => "tooManyHoldsForThisRecord", limit => $holds_per_record } if $holds->count() >= $holds_per_record; + return _cache { status => "tooManyHoldsForThisRecord", limit => $holds_per_record } + if $holds->count() >= $holds_per_record; } } - if (!$params->{ignore_hold_counts} && defined $holds_per_day && $holds_per_day ne '') - { - my $today_holds = Koha::Holds->search({ - borrowernumber => $patron->borrowernumber, - reservedate => dt_from_string->date - }); - return _cache { status => 'tooManyReservesToday', limit => $holds_per_day } if $today_holds->count() >= $holds_per_day; + if ( !$params->{ignore_hold_counts} && defined $holds_per_day && $holds_per_day ne '' ) { + my $today_holds = Koha::Holds->search( + { + borrowernumber => $patron->borrowernumber, + reservedate => dt_from_string->date + } + ); + return _cache { status => 'tooManyReservesToday', limit => $holds_per_day } + if $today_holds->count() >= $holds_per_day; } # we check if it's ok or not - if ( defined $allowedreserves && $allowedreserves ne '' ){ - if( $allowedreserves == 0 ){ + if ( defined $allowedreserves && $allowedreserves ne '' ) { + if ( $allowedreserves == 0 ) { return _cache { status => 'noReservesAllowed' }; } if ( !$params->{ignore_hold_counts} ) { + # we retrieve count my $querycount = q{ SELECT count(*) AS count @@ -593,8 +611,7 @@ sub CanItemBeReserved { AND ( COALESCE( items.itype, biblioitems.itemtype ) = ? OR reserves.itemtype = ? ) }; - } - else { + } else { $querycount .= q{ AND ( biblioitems.itemtype = ? OR reserves.itemtype = ? ) @@ -606,8 +623,7 @@ sub CanItemBeReserved { if ( defined $ruleitemtype ) { $sthcount->execute( $patron->borrowernumber, $reserves_control_branch, $ruleitemtype, $ruleitemtype ); - } - else { + } else { $sthcount->execute( $patron->borrowernumber, $reserves_control_branch ); } @@ -616,7 +632,8 @@ sub CanItemBeReserved { $reservecount = $rowcount->{count}; } - return _cache { status => 'tooManyReserves', limit => $allowedreserves } if $reservecount >= $allowedreserves; + return _cache { status => 'tooManyReserves', limit => $allowedreserves } + if $reservecount >= $allowedreserves; } } @@ -628,18 +645,14 @@ sub CanItemBeReserved { rule_name => 'max_holds', } ); - if (!$params->{ignore_hold_counts} && $rule && defined( $rule->rule_value ) && $rule->rule_value ne '' ) { - my $total_holds_count = Koha::Holds->search( - { - borrowernumber => $patron->borrowernumber - } - )->count(); + if ( !$params->{ignore_hold_counts} && $rule && defined( $rule->rule_value ) && $rule->rule_value ne '' ) { + my $total_holds_count = Koha::Holds->search( { borrowernumber => $patron->borrowernumber } )->count(); - return _cache { status => 'tooManyReserves', limit => $rule->rule_value} if $total_holds_count >= $rule->rule_value; + return _cache { status => 'tooManyReserves', limit => $rule->rule_value } + if $total_holds_count >= $rule->rule_value; } - my $branchitemrule = - C4::Circulation::GetBranchItemRule( $reserves_control_branch, $item->effective_itemtype ); + my $branchitemrule = C4::Circulation::GetBranchItemRule( $reserves_control_branch, $item->effective_itemtype ); if ( $branchitemrule->{holdallowed} eq 'not_allowed' ) { return _cache { status => 'notReservable' }; @@ -651,31 +664,40 @@ sub CanItemBeReserved { return _cache { status => 'cannotReserveFromOtherBranches' }; } - my $item_library = Koha::Libraries->find( {branchcode => $item->homebranch} ); - if ( $branchitemrule->{holdallowed} eq 'from_local_hold_group') { - if($patron->branchcode ne $item->homebranch && !$item_library->validate_hold_sibling( {branchcode => $patron->branchcode} )) { + my $item_library = Koha::Libraries->find( { branchcode => $item->homebranch } ); + if ( $branchitemrule->{holdallowed} eq 'from_local_hold_group' ) { + if ( $patron->branchcode ne $item->homebranch + && !$item_library->validate_hold_sibling( { branchcode => $patron->branchcode } ) ) + { return _cache { status => 'branchNotInHoldGroup' }; } } if ($pickup_branchcode) { - my $destination = Koha::Libraries->find({ - branchcode => $pickup_branchcode, - }); + my $destination = Koha::Libraries->find( + { + branchcode => $pickup_branchcode, + } + ); unless ($destination) { return _cache { status => 'libraryNotFound' }; } - unless ($destination->pickup_location) { + unless ( $destination->pickup_location ) { return _cache { status => 'libraryNotPickupLocation' }; } - unless ($item->can_be_transferred({ to => $destination })) { + unless ( $item->can_be_transferred( { to => $destination } ) ) { return _cache { status => 'cannotBeTransferred' }; } - if ($branchitemrule->{hold_fulfillment_policy} eq 'holdgroup' && !$item_library->validate_hold_sibling( {branchcode => $pickup_branchcode} )) { + if ( $branchitemrule->{hold_fulfillment_policy} eq 'holdgroup' + && !$item_library->validate_hold_sibling( { branchcode => $pickup_branchcode } ) ) + { return _cache { status => 'pickupNotInHoldGroup' }; } - if ($branchitemrule->{hold_fulfillment_policy} eq 'patrongroup' && !Koha::Libraries->find({branchcode => $patron->branchcode})->validate_hold_sibling({branchcode => $pickup_branchcode})) { + if ( $branchitemrule->{hold_fulfillment_policy} eq 'patrongroup' + && !Koha::Libraries->find( { branchcode => $patron->branchcode } ) + ->validate_hold_sibling( { branchcode => $pickup_branchcode } ) ) + { return _cache { status => 'pickupNotInHoldGroup' }; } } @@ -732,21 +754,27 @@ SELECT COUNT(*) FROM reserves WHERE biblionumber=? AND borrowernumber<>? }; my $dbh = C4::Context->dbh; - my ( $fee ) = $dbh->selectrow_array( $borquery, undef, ($borrowernumber) ); + my ($fee) = $dbh->selectrow_array( $borquery, undef, ($borrowernumber) ); $fee += 0; my $hold_fee_mode = C4::Context->preference('HoldFeeMode') || 'not_always'; - if( $fee and $fee > 0 and $hold_fee_mode eq 'not_always' ) { + if ( $fee and $fee > 0 and $hold_fee_mode eq 'not_always' ) { + # This is a reconstruction of the old code: # Compare number of items with items issued, and optionally check holds # If not all items are issued and there are no holds: charge no fee # NOTE: Lost, damaged, not-for-loan, etc. are just ignored here my ( $notissued, $reserved ); - ( $notissued ) = $dbh->selectrow_array( $issue_qry, undef, - ( $biblionumber ) ); - if( $notissued == 0 ) { + ($notissued) = $dbh->selectrow_array( + $issue_qry, undef, + ($biblionumber) + ); + if ( $notissued == 0 ) { + # all items are issued - ( $reserved ) = $dbh->selectrow_array( $holds_qry, undef, - ( $biblionumber, $borrowernumber ) ); + ($reserved) = $dbh->selectrow_array( + $holds_qry, undef, + ( $biblionumber, $borrowernumber ) + ); $fee = 0 if $reserved == 0; } else { $fee = 0; @@ -773,22 +801,22 @@ sub GetReserveStatus { my $dbh = C4::Context->dbh; - my ($sth, $found, $priority); - if ( $itemnumber ) { + my ( $sth, $found, $priority ); + if ($itemnumber) { $sth = $dbh->prepare("SELECT found, priority FROM reserves WHERE itemnumber = ? order by priority LIMIT 1"); $sth->execute($itemnumber); - ($found, $priority) = $sth->fetchrow_array; + ( $found, $priority ) = $sth->fetchrow_array; } - if(defined $found) { - return 'Waiting' if $found eq 'W' and $priority == 0; - return 'Processing' if $found eq 'P'; - return 'Finished' if $found eq 'F'; + if ( defined $found ) { + return 'Waiting' if $found eq 'W' and $priority == 0; + return 'Processing' if $found eq 'P'; + return 'Finished' if $found eq 'F'; } return 'Reserved' if defined $priority && $priority > 0; - return ''; # empty string here will remove need for checking undef, or less log lines + return ''; # empty string here will remove need for checking undef, or less log lines } =head2 CheckReserves @@ -821,9 +849,10 @@ table in the Koha database. sub CheckReserves { my ( $item, $lookahead_days, $ignore_borrowers ) = @_; + # note: we get the itemnumber because we might have started w/ just the barcode. Now we know for sure we have it. - return unless $item; # bail if we got nothing. + return unless $item; # bail if we got nothing. return if ( $item->damaged && !C4::Context->preference('AllowHoldsOnDamagedItems') ); @@ -836,16 +865,15 @@ sub CheckReserves { my $dont_trap = C4::Context->preference('TrapHoldsOnOrder') ? $item->notforloan > 0 : $item->notforloan; if ( !$dont_trap ) { my $item_type = $item->effective_itemtype; - if ( $item_type ) { - return if Koha::ItemTypes->find( $item_type )->notforloan; + if ($item_type) { + return if Koha::ItemTypes->find($item_type)->notforloan; } - } - else { + } else { return; } # Find this item in the reserves - my @reserves = _Findgroupreserve( $item->biblionumber, $item->itemnumber, $lookahead_days, $ignore_borrowers); + my @reserves = _Findgroupreserve( $item->biblionumber, $item->itemnumber, $lookahead_days, $ignore_borrowers ); # $priority and $highest are used to find the most important item # in the list returned by &_Findgroupreserve. (The lower $priority, @@ -853,19 +881,19 @@ sub CheckReserves { # $highest is the most important item we've seen so far. my $highest; - if (scalar @reserves) { - my $LocalHoldsPriority = C4::Context->preference('LocalHoldsPriority'); + if ( scalar @reserves ) { + my $LocalHoldsPriority = C4::Context->preference('LocalHoldsPriority'); my $LocalHoldsPriorityPatronControl = C4::Context->preference('LocalHoldsPriorityPatronControl'); - my $LocalHoldsPriorityItemControl = C4::Context->preference('LocalHoldsPriorityItemControl'); - my $priority = 10000000; + my $LocalHoldsPriorityItemControl = C4::Context->preference('LocalHoldsPriorityItemControl'); + my $priority = 10000000; foreach my $res (@reserves) { - if ($res->{'found'} && $res->{'found'} eq 'W') { - return ( "Waiting", $res, \@reserves ); # Found it, it is waiting - } elsif ($res->{'found'} && $res->{'found'} eq 'P') { - return ( "Processing", $res, \@reserves ); # Found determinated hold, e. g. the transferred one - } elsif ($res->{'found'} && $res->{'found'} eq 'T') { - return ( "Transferred", $res, \@reserves ); # Found determinated hold, e. g. the transferred one + if ( $res->{'found'} && $res->{'found'} eq 'W' ) { + return ( "Waiting", $res, \@reserves ); # Found it, it is waiting + } elsif ( $res->{'found'} && $res->{'found'} eq 'P' ) { + return ( "Processing", $res, \@reserves ); # Found determinated hold, e. g. the transferred one + } elsif ( $res->{'found'} && $res->{'found'} eq 'T' ) { + return ( "Transferred", $res, \@reserves ); # Found determinated hold, e. g. the transferred one } else { my $patron; my $local_hold_match; @@ -873,36 +901,46 @@ sub CheckReserves { if ($LocalHoldsPriority) { $patron = Koha::Patrons->find( $res->{borrowernumber} ); - unless ($item->exclude_from_local_holds_priority || $patron->category->exclude_from_local_holds_priority) { - my $local_holds_priority_item_branchcode = - $item->$LocalHoldsPriorityItemControl; + unless ( $item->exclude_from_local_holds_priority + || $patron->category->exclude_from_local_holds_priority ) + { + my $local_holds_priority_item_branchcode = $item->$LocalHoldsPriorityItemControl; my $local_holds_priority_patron_branchcode = - ( $LocalHoldsPriorityPatronControl eq 'PickupLibrary' ) - ? $res->{branchcode} - : ( $LocalHoldsPriorityPatronControl eq 'HomeLibrary' ) - ? $patron->branchcode - : undef; + ( $LocalHoldsPriorityPatronControl eq 'PickupLibrary' ) ? $res->{branchcode} + : ( $LocalHoldsPriorityPatronControl eq 'HomeLibrary' ) ? $patron->branchcode + : undef; $local_hold_match = - $local_holds_priority_item_branchcode eq - $local_holds_priority_patron_branchcode; + $local_holds_priority_item_branchcode eq $local_holds_priority_patron_branchcode; } } # See if this item is more important than what we've got so far if ( ( $res->{'priority'} && $res->{'priority'} < $priority ) || $local_hold_match ) { - next if $res->{item_group_id} && ( !$item->item_group || $item->item_group->id != $res->{item_group_id} ); + next + if $res->{item_group_id} + && ( !$item->item_group || $item->item_group->id != $res->{item_group_id} ); next if $res->{itemtype} && $res->{itemtype} ne $item->effective_itemtype; $patron //= Koha::Patrons->find( $res->{borrowernumber} ); - my $branch = Koha::Policy::Holds->holds_control_library( $item, $patron ); - my $branchitemrule = C4::Circulation::GetBranchItemRule($branch,$item->effective_itemtype); - next if ($branchitemrule->{'holdallowed'} eq 'not_allowed'); - next if (($branchitemrule->{'holdallowed'} eq 'from_home_library') && ($item->homebranch ne $patron->branchcode)); - my $library = Koha::Libraries->find({branchcode=>$item->homebranch}); - next if (($branchitemrule->{'holdallowed'} eq 'from_local_hold_group') && (!$library->validate_hold_sibling({branchcode => $patron->branchcode}) )); + my $branch = Koha::Policy::Holds->holds_control_library( $item, $patron ); + my $branchitemrule = C4::Circulation::GetBranchItemRule( $branch, $item->effective_itemtype ); + next if ( $branchitemrule->{'holdallowed'} eq 'not_allowed' ); + next + if ( ( $branchitemrule->{'holdallowed'} eq 'from_home_library' ) + && ( $item->homebranch ne $patron->branchcode ) ); + my $library = Koha::Libraries->find( { branchcode => $item->homebranch } ); + next + if ( ( $branchitemrule->{'holdallowed'} eq 'from_local_hold_group' ) + && ( !$library->validate_hold_sibling( { branchcode => $patron->branchcode } ) ) ); my $hold_fulfillment_policy = $branchitemrule->{hold_fulfillment_policy}; - next if ( ($hold_fulfillment_policy eq 'holdgroup') && (!$library->validate_hold_sibling({branchcode => $res->{branchcode}})) ); - next if ( ($hold_fulfillment_policy eq 'homebranch') && ($res->{branchcode} ne $item->$hold_fulfillment_policy) ); - next if ( ($hold_fulfillment_policy eq 'holdingbranch') && ($res->{branchcode} ne $item->$hold_fulfillment_policy) ); + next + if ( ( $hold_fulfillment_policy eq 'holdgroup' ) + && ( !$library->validate_hold_sibling( { branchcode => $res->{branchcode} } ) ) ); + next + if ( ( $hold_fulfillment_policy eq 'homebranch' ) + && ( $res->{branchcode} ne $item->$hold_fulfillment_policy ) ); + next + if ( ( $hold_fulfillment_policy eq 'holdingbranch' ) + && ( $res->{branchcode} ne $item->$hold_fulfillment_policy ) ); next unless $item->can_be_transferred( { to => Koha::Libraries->find( $res->{branchcode} ) } ); $priority = $res->{'priority'}; $highest = $res; @@ -919,7 +957,7 @@ sub CheckReserves { return ( "Reserved", $highest, \@reserves ); } - return ( '' ); + return (''); } =head2 CancelExpiredReserves @@ -932,35 +970,35 @@ Cancels all reserves with an expiration date from before today. sub CancelExpiredReserves { my $cancellation_reason = shift; - my $today = dt_from_string(); - my $cancel_on_holidays = C4::Context->preference('ExpireReservesOnHolidays'); - my $expireWaiting = C4::Context->preference('ExpireReservesMaxPickUpDelay'); + my $today = dt_from_string(); + my $cancel_on_holidays = C4::Context->preference('ExpireReservesOnHolidays'); + my $expireWaiting = C4::Context->preference('ExpireReservesMaxPickUpDelay'); - my $dtf = Koha::Database->new->schema->storage->datetime_parser; + my $dtf = Koha::Database->new->schema->storage->datetime_parser; my $params = { -or => [ - { expirationdate => { '<', $dtf->format_date($today) } }, + { expirationdate => { '<', $dtf->format_date($today) } }, { patron_expiration_date => { '<' => $dtf->format_date($today) } } ] }; - $params->{found} = [ { '!=', 'W' }, undef ] unless $expireWaiting; + $params->{found} = [ { '!=', 'W' }, undef ] unless $expireWaiting; # FIXME To move to Koha::Holds->search_expired (?) - my $holds = Koha::Holds->search( $params ); + my $holds = Koha::Holds->search($params); while ( my $hold = $holds->next ) { my $calendar = Koha::Calendar->new( branchcode => $hold->branchcode ); - next if !$cancel_on_holidays && $calendar->is_holiday( $today ); + next if !$cancel_on_holidays && $calendar->is_holiday($today); my $cancel_params = {}; $cancel_params->{cancellation_reason} = $cancellation_reason if defined($cancellation_reason); - if ( defined($hold->found) && $hold->found eq 'W' ) { + if ( defined( $hold->found ) && $hold->found eq 'W' ) { $cancel_params->{charge_cancel_fee} = 1; } $cancel_params->{autofill} = C4::Context->preference('ExpireReservesAutoFill'); - $hold->cancel( $cancel_params ); + $hold->cancel($cancel_params); } } @@ -1020,27 +1058,28 @@ itemnumber and supplying itemnumber. =cut sub ModReserve { - my ( $params ) = @_; + my ($params) = @_; - my $rank = $params->{'rank'}; - my $reserve_id = $params->{'reserve_id'}; - my $branchcode = $params->{'branchcode'}; - my $itemnumber = $params->{'itemnumber'}; - my $suspend_until = $params->{'suspend_until'}; - my $borrowernumber = $params->{'borrowernumber'}; - my $biblionumber = $params->{'biblionumber'}; + my $rank = $params->{'rank'}; + my $reserve_id = $params->{'reserve_id'}; + my $branchcode = $params->{'branchcode'}; + my $itemnumber = $params->{'itemnumber'}; + my $suspend_until = $params->{'suspend_until'}; + my $borrowernumber = $params->{'borrowernumber'}; + my $biblionumber = $params->{'biblionumber'}; my $cancellation_reason = $params->{'cancellation_reason'}; - my $date = $params->{expirationdate}; + my $date = $params->{expirationdate}; return if defined $rank && $rank eq "n"; return unless ( $reserve_id || ( $borrowernumber && ( $biblionumber || $itemnumber ) ) ); my $hold; - unless ( $reserve_id ) { - my $holds = Koha::Holds->search({ biblionumber => $biblionumber, borrowernumber => $borrowernumber, itemnumber => $itemnumber }); - return unless $holds->count; # FIXME Should raise an exception - $hold = $holds->next; + unless ($reserve_id) { + my $holds = Koha::Holds->search( + { biblionumber => $biblionumber, borrowernumber => $borrowernumber, itemnumber => $itemnumber } ); + return unless $holds->count; # FIXME Should raise an exception + $hold = $holds->next; $reserve_id = $hold->reserve_id; } @@ -1052,17 +1091,15 @@ sub ModReserve { my $original = C4::Context->preference('HoldsLog') ? $hold->unblessed : undef; if ( $rank eq "del" ) { - $hold->cancel({ cancellation_reason => $cancellation_reason }); - } - elsif ($hold->found && $hold->priority eq '0' && $date) { + $hold->cancel( { cancellation_reason => $cancellation_reason } ); + } elsif ( $hold->found && $hold->priority eq '0' && $date ) { # The only column that can be updated for a found hold is the expiration date $hold->expirationdate($date)->store(); logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, $hold, undef, $original ) if C4::Context->preference('HoldsLog'); - } - elsif ($rank =~ /^\d+/ and $rank > 0) { + } elsif ( $rank =~ /^\d+/ and $rank > 0 ) { my $properties = { priority => $rank, branchcode => $branchcode, @@ -1070,19 +1107,20 @@ sub ModReserve { found => undef, waitingdate => undef }; - if (exists $params->{reservedate}) { + if ( exists $params->{reservedate} ) { $properties->{reservedate} = $params->{reservedate} || undef; } - if (exists $params->{expirationdate}) { + if ( exists $params->{expirationdate} ) { $properties->{expirationdate} = $params->{expirationdate} || undef; } $hold->set($properties)->store(); - if ( defined( $suspend_until ) ) { - if ( $suspend_until ) { - $hold->suspend_hold( $suspend_until ); + if ( defined($suspend_until) ) { + if ($suspend_until) { + $hold->suspend_hold($suspend_until); } else { + # If the hold is suspended leave the hold suspended, but convert it to an indefinite hold. # If the hold is not suspended, this does nothing. $hold->set( { suspend_until => undef } )->store(); @@ -1111,18 +1149,21 @@ $newstatus is the new status. sub ModReserveStatus { #first : check if we have a reservation for this item . - my ($itemnumber, $newstatus) = @_; + my ( $itemnumber, $newstatus ) = @_; my $dbh = C4::Context->dbh; - my $query = "UPDATE reserves SET found = ?, waitingdate = NOW() WHERE itemnumber = ? AND found IS NULL AND priority = 0"; + my $query = + "UPDATE reserves SET found = ?, waitingdate = NOW() WHERE itemnumber = ? AND found IS NULL AND priority = 0"; my $sth_set = $dbh->prepare($query); $sth_set->execute( $newstatus, $itemnumber ); my $item = Koha::Items->find($itemnumber); - if ( $item->location && $item->location eq 'CART' + if ( $item->location + && $item->location eq 'CART' && ( !$item->permanent_location || $item->permanent_location ne 'CART' ) - && $newstatus ) { - CartToShelf( $itemnumber ); + && $newstatus ) + { + CartToShelf($itemnumber); } } @@ -1157,10 +1198,13 @@ sub ModReserveAffect { # waiting in order to not send duplicate hold filled notifications my $hold; + # Find hold by id if we have it - $hold = Koha::Holds->find( $reserve_id ) if $reserve_id; + $hold = Koha::Holds->find($reserve_id) if $reserve_id; + # Find item level hold for this item if there is one $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, itemnumber => $itemnumber } )->next(); + # Find record level hold if there is no item level hold $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, biblionumber => $biblionumber } )->next(); @@ -1174,28 +1218,33 @@ sub ModReserveAffect { if ($transferToDo) { $hold->set_transfer(); - } elsif (C4::Context->preference('HoldsNeedProcessingSIP') - && C4::Context->interface eq 'sip' - && !$already_on_shelf) { + } elsif ( C4::Context->preference('HoldsNeedProcessingSIP') + && C4::Context->interface eq 'sip' + && !$already_on_shelf ) + { $hold->set_processing(); } else { $hold->set_waiting($desk_id); _koha_notify_reserve( $hold->reserve_id ) unless $already_on_shelf; + # Complete transfer if one exists my $transfer = $hold->item->get_transfer; $transfer->receive if $transfer; } - _koha_notify_hold_changed( $hold ) if $notify_library; + _koha_notify_hold_changed($hold) if $notify_library; _FixPriority( { biblionumber => $biblionumber } ); my $item = Koha::Items->find($itemnumber); - if ( $item->location && $item->location eq 'CART' - && ( !$item->permanent_location || $item->permanent_location ne 'CART' ) ) { - CartToShelf( $itemnumber ); + if ( $item->location + && $item->location eq 'CART' + && ( !$item->permanent_location || $item->permanent_location ne 'CART' ) ) + { + CartToShelf($itemnumber); } - my $std = $dbh->prepare(q{ + my $std = $dbh->prepare( + q{ DELETE q, t FROM tmp_holdsqueue q INNER JOIN hold_fill_targets t @@ -1205,8 +1254,9 @@ sub ModReserveAffect { AND q.item_level_request = t.item_level_request AND q.holdingbranch = t.source_branchcode WHERE t.reserve_id = ? - }); - $std->execute($hold->reserve_id); + } + ); + $std->execute( $hold->reserve_id ); logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, $hold, undef, $original ) if C4::Context->preference('HoldsLog'); @@ -1229,18 +1279,17 @@ sub ModReserveCancelAll { my $item = Koha::Items->find($itemnumber); #step 1 : cancel the reservation - my $holds = Koha::Holds->search({ itemnumber => $itemnumber, borrowernumber => $borrowernumber }); + my $holds = Koha::Holds->search( { itemnumber => $itemnumber, borrowernumber => $borrowernumber } ); return unless $holds->count; - $holds->next->cancel({ cancellation_reason => $cancellation_reason }); + $holds->next->cancel( { cancellation_reason => $cancellation_reason } ); #step 2 check for other reserves on this item ( undef, $nextreservinfo, undef ) = CheckReserves($item); if ($nextreservinfo) { - if( $item->holdingbranch ne $nextreservinfo->{'branchcode'} ) { + if ( $item->holdingbranch ne $nextreservinfo->{'branchcode'} ) { $messages->{'transfert'} = $nextreservinfo->{'branchcode'}; - } - else { + } else { $messages->{'waiting'} = 1; } } @@ -1268,8 +1317,9 @@ sub ModReserveMinusPriority { "; my $sth_upd = $dbh->prepare($query); $sth_upd->execute( $itemnumber, $reserve_id ); + # second step update all others reserves - _FixPriority({ reserve_id => $reserve_id, rank => '0' }); + _FixPriority( { reserve_id => $reserve_id, rank => '0' } ); } =head2 IsAvailableForItemLevelRequest @@ -1302,26 +1352,28 @@ checks with CanItemBeReserved or CanBookBeReserved. =cut sub IsAvailableForItemLevelRequest { - my $item = shift; - my $patron = shift; - my $pickup_branchcode = shift; + my $item = shift; + my $patron = shift; + my $pickup_branchcode = shift; my $dbh = C4::Context->dbh; + # must check the notforloan setting of the itemtype # FIXME - a lot of places in the code do this # or something similar - need to be # consolidated my $itemtype = $item->effective_itemtype; return 0 - unless defined $itemtype; + unless defined $itemtype; my $notforloan_per_itemtype = Koha::ItemTypes->find($itemtype)->notforloan; - return 0 if - $notforloan_per_itemtype || - $item->itemlost || - $item->notforloan > 0 || # item with negative or zero notforloan value is holdable - $item->withdrawn || - ($item->damaged && !C4::Context->preference('AllowHoldsOnDamagedItems')); + return 0 + if $notforloan_per_itemtype + || $item->itemlost + || $item->notforloan > 0 + || # item with negative or zero notforloan value is holdable + $item->withdrawn + || ( $item->damaged && !C4::Context->preference('AllowHoldsOnDamagedItems') ); if ($pickup_branchcode) { my $destination = Koha::Libraries->find($pickup_branchcode); @@ -1329,10 +1381,11 @@ sub IsAvailableForItemLevelRequest { return 0 unless $destination->pickup_location; return 0 unless $item->can_be_transferred( { to => $destination } ); my $reserves_control_branch = Koha::Policy::Holds->holds_control_library( $item, $patron ); - my $branchitemrule = - C4::Circulation::GetBranchItemRule( $reserves_control_branch, $item->itype ); - my $home_library = Koha::Libraries->find( {branchcode => $item->homebranch} ); - return 0 unless $branchitemrule->{hold_fulfillment_policy} ne 'holdgroup' || $home_library->validate_hold_sibling( {branchcode => $pickup_branchcode} ); + my $branchitemrule = C4::Circulation::GetBranchItemRule( $reserves_control_branch, $item->itype ); + my $home_library = Koha::Libraries->find( { branchcode => $item->homebranch } ); + return 0 + unless $branchitemrule->{hold_fulfillment_policy} ne 'holdgroup' + || $home_library->validate_hold_sibling( { branchcode => $pickup_branchcode } ); } my $on_shelf_holds = Koha::CirculationRules->get_onshelfholds_policy( { item => $item, patron => $patron } ); @@ -1378,22 +1431,22 @@ sub ItemsAnyAvailableAndNotRestricted { foreach my $i (@items) { my $reserves_control_branch = Koha::Policy::Holds->holds_control_library( $i, $param->{patron} ); - my $branchitemrule = - C4::Circulation::GetBranchItemRule( $reserves_control_branch, $i->itype ); - my $item_library = Koha::Libraries->find( { branchcode => $i->homebranch } ); + my $branchitemrule = C4::Circulation::GetBranchItemRule( $reserves_control_branch, $i->itype ); + my $item_library = Koha::Libraries->find( { branchcode => $i->homebranch } ); # we can return (end the loop) when first one found: return 1 unless $i->itemlost - || $i->notforloan # items with non-zero notforloan cannot be checked out + || $i->notforloan # items with non-zero notforloan cannot be checked out || $i->withdrawn || $i->onloan || $i->holds->filter_by_found->count || ( $i->damaged - && ! C4::Context->preference('AllowHoldsOnDamagedItems') ) + && !C4::Context->preference('AllowHoldsOnDamagedItems') ) || Koha::ItemTypes->find( $i->effective_itemtype() )->notforloan || $branchitemrule->{holdallowed} eq 'from_home_library' && $param->{patron}->branchcode ne $i->homebranch - || $branchitemrule->{holdallowed} eq 'from_local_hold_group' && ! $item_library->validate_hold_sibling( { branchcode => $param->{patron}->branchcode } ) + || $branchitemrule->{holdallowed} eq 'from_local_hold_group' + && !$item_library->validate_hold_sibling( { branchcode => $param->{patron}->branchcode } ) || CanItemBeReserved( $param->{patron}, $i )->{status} ne 'OK'; } @@ -1412,31 +1465,30 @@ Input: $where is 'up', 'down', 'top' or 'bottom'. Biblionumber, Date reserve was sub AlterPriority { my ( $where, $reserve_id, $prev_priority, $next_priority, $first_priority, $last_priority ) = @_; - my $hold = Koha::Holds->find( $reserve_id ); + my $hold = Koha::Holds->find($reserve_id); return unless $hold; if ( $hold->cancellationdate ) { - warn "I cannot alter the priority for reserve_id $reserve_id, the reserve has been cancelled (" . $hold->cancellationdate . ')'; + warn "I cannot alter the priority for reserve_id $reserve_id, the reserve has been cancelled (" + . $hold->cancellationdate . ')'; return; } if ( $where eq 'up' ) { - return unless $prev_priority; - _FixPriority({ reserve_id => $reserve_id, rank => $prev_priority }) + return unless $prev_priority; + _FixPriority( { reserve_id => $reserve_id, rank => $prev_priority } ); } elsif ( $where eq 'down' ) { - return unless $next_priority; - _FixPriority({ reserve_id => $reserve_id, rank => $next_priority }) + return unless $next_priority; + _FixPriority( { reserve_id => $reserve_id, rank => $next_priority } ); } elsif ( $where eq 'top' ) { - _FixPriority({ reserve_id => $reserve_id, rank => $first_priority }) + _FixPriority( { reserve_id => $reserve_id, rank => $first_priority } ); } elsif ( $where eq 'bottom' ) { - _FixPriority({ reserve_id => $reserve_id, rank => $last_priority }); + _FixPriority( { reserve_id => $reserve_id, rank => $last_priority } ); } - Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue->new->enqueue( - { - biblio_ids => [ $hold->biblionumber ] - } - ) if C4::Context->preference('RealTimeHoldsQueue'); + Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue->new->enqueue( { biblio_ids => [ $hold->biblionumber ] } ) + if C4::Context->preference('RealTimeHoldsQueue'); + # FIXME Should return the new priority } @@ -1449,14 +1501,14 @@ This function sets the lowestPriority field to true if is false, and false if it =cut sub ToggleLowestPriority { - my ( $reserve_id ) = @_; + my ($reserve_id) = @_; my $dbh = C4::Context->dbh; - my $sth = $dbh->prepare( "UPDATE reserves SET lowestPriority = NOT lowestPriority WHERE reserve_id = ?"); - $sth->execute( $reserve_id ); + my $sth = $dbh->prepare("UPDATE reserves SET lowestPriority = NOT lowestPriority WHERE reserve_id = ?"); + $sth->execute($reserve_id); - _FixPriority({ reserve_id => $reserve_id, rank => '999999' }); + _FixPriority( { reserve_id => $reserve_id, rank => '999999' } ); } =head2 SuspendAll @@ -1481,26 +1533,24 @@ sub SuspendAll { my $borrowernumber = $params{'borrowernumber'} || undef; my $biblionumber = $params{'biblionumber'} || undef; my $suspend_until = $params{'suspend_until'} || undef; - my $suspend = defined( $params{'suspend'} ) ? $params{'suspend'} : 1; + my $suspend = defined( $params{'suspend'} ) ? $params{'suspend'} : 1; return unless ( $borrowernumber || $biblionumber ); my $params; $params->{found} = undef; $params->{borrowernumber} = $borrowernumber if $borrowernumber; - $params->{biblionumber} = $biblionumber if $biblionumber; + $params->{biblionumber} = $biblionumber if $biblionumber; my @holds = Koha::Holds->search($params)->as_list; if ($suspend) { map { $_->suspend_hold($suspend_until) } @holds; - } - else { + } else { map { $_->resume() } @holds; } } - =head2 _FixPriority _FixPriority({ @@ -1537,33 +1587,33 @@ when _FixPriority calls itself. =cut sub _FixPriority { - my ( $params ) = @_; - my $reserve_id = $params->{reserve_id}; - my $rank = $params->{rank} // ''; + my ($params) = @_; + my $reserve_id = $params->{reserve_id}; + my $rank = $params->{rank} // ''; my $ignoreSetLowestRank = $params->{ignoreSetLowestRank}; - my $biblionumber = $params->{biblionumber}; + my $biblionumber = $params->{biblionumber}; my $dbh = C4::Context->dbh; my $hold; - if ( $reserve_id ) { - $hold = Koha::Holds->find( $reserve_id ); - if (!defined $hold){ + if ($reserve_id) { + $hold = Koha::Holds->find($reserve_id); + if ( !defined $hold ) { + # may have already been checked out and hold fulfilled require Koha::Old::Holds; - $hold = Koha::Old::Holds->find( $reserve_id ); + $hold = Koha::Old::Holds->find($reserve_id); } return unless $hold; } - unless ( $biblionumber ) { # FIXME This is a very weird API + unless ($biblionumber) { # FIXME This is a very weird API $biblionumber = $hold->biblionumber; } - if ( $rank eq "del" ) { # FIXME will crash if called without $hold + if ( $rank eq "del" ) { # FIXME will crash if called without $hold $hold->cancel; - } - elsif ( $reserve_id && ( $rank eq "W" || $rank eq "0" ) ) { + } elsif ( $reserve_id && ( $rank eq "W" || $rank eq "0" ) ) { # make sure priority for waiting or in-transit items is 0 my $query = " @@ -1573,7 +1623,7 @@ sub _FixPriority { AND found IN ('W', 'T', 'P') "; my $sth = $dbh->prepare($query); - $sth->execute( $reserve_id ); + $sth->execute($reserve_id); } my @priority; @@ -1586,9 +1636,9 @@ sub _FixPriority { ORDER BY priority ASC "; my $sth = $dbh->prepare($query); - $sth->execute( $biblionumber ); + $sth->execute($biblionumber); while ( my $line = $sth->fetchrow_hashref ) { - push( @priority, $line ); + push( @priority, $line ); } # FIXME This whole sub must be rewritten, especially to highlight what is done when reserve_id is not given @@ -1604,7 +1654,7 @@ sub _FixPriority { # if index exists in array then move it to new position if ( $key > -1 && $rank ne 'del' && $rank > 0 ) { - my $new_rank = $rank - 1; # $new_rank is what you want the new index to be in the array + my $new_rank = $rank - 1; # $new_rank is what you want the new index to be in the array my $moving_item = splice( @priority, $key, 1 ); $new_rank = scalar @priority if $new_rank > scalar @priority; splice( @priority, $new_rank, 0, $moving_item ); @@ -1624,16 +1674,19 @@ sub _FixPriority { ); } - unless ( $ignoreSetLowestRank ) { - $sth = $dbh->prepare( "SELECT reserve_id FROM reserves WHERE lowestPriority = 1 AND biblionumber = ? ORDER BY priority" ); + unless ($ignoreSetLowestRank) { + $sth = $dbh->prepare( + "SELECT reserve_id FROM reserves WHERE lowestPriority = 1 AND biblionumber = ? ORDER BY priority"); $sth->execute($biblionumber); - while ( my $res = $sth->fetchrow_hashref() ) { - _FixPriority({ - reserve_id => $res->{'reserve_id'}, - rank => '999999', - ignoreSetLowestRank => 1 - }); - } + while ( my $res = $sth->fetchrow_hashref() ) { + _FixPriority( + { + reserve_id => $res->{'reserve_id'}, + rank => '999999', + ignoreSetLowestRank => 1 + } + ); + } } } @@ -1660,8 +1713,8 @@ All return values will respect any borrowernumbers passed as arrayref in $ignore =cut sub _Findgroupreserve { - my ( $biblionumber, $itemnumber, $lookahead, $ignore_borrowers) = @_; - my $dbh = C4::Context->dbh; + my ( $biblionumber, $itemnumber, $lookahead, $ignore_borrowers ) = @_; + my $dbh = C4::Context->dbh; # check for targeted match form the holds queue my $hold_target_query = qq{ @@ -1691,11 +1744,11 @@ sub _Findgroupreserve { ORDER BY priority }; my $sth = $dbh->prepare($hold_target_query); - $sth->execute($itemnumber, $lookahead||0); + $sth->execute( $itemnumber, $lookahead || 0 ); my @results; if ( my $data = $sth->fetchrow_hashref ) { push( @results, $data ) - unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ; + unless any { $data->{borrowernumber} eq $_ } @$ignore_borrowers; } return @results if @results; @@ -1723,11 +1776,11 @@ sub _Findgroupreserve { ORDER BY priority }; $sth = $dbh->prepare($query); - $sth->execute( $biblionumber, $itemnumber, $lookahead||0); + $sth->execute( $biblionumber, $itemnumber, $lookahead || 0 ); @results = (); while ( my $data = $sth->fetchrow_hashref ) { push( @results, $data ) - unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ; + unless any { $data->{borrowernumber} eq $_ } @$ignore_borrowers; } return @results; } @@ -1763,39 +1816,42 @@ The following tables are availalbe witin the notice: sub _koha_notify_reserve { my $reserve_id = shift; - my $hold = Koha::Holds->find($reserve_id); + my $hold = Koha::Holds->find($reserve_id); my $borrowernumber = $hold->borrowernumber; - my $patron = Koha::Patrons->find( $borrowernumber ); + my $patron = Koha::Patrons->find($borrowernumber); # Try to get the borrower's email address my $to_address = $patron->notice_email_address; - my $messagingprefs = C4::Members::Messaging::GetMessagingPreferences( { + my $messagingprefs = C4::Members::Messaging::GetMessagingPreferences( + { borrowernumber => $borrowernumber, - message_name => 'Hold_Filled' - } ); + message_name => 'Hold_Filled' + } + ); my $library = Koha::Libraries->find( $hold->branchcode ); my $from_email_address = $library->from_email_address; my $reply_email_address = $library->inbound_email_address; my %letter_params = ( - module => 'reserves', + module => 'reserves', branchcode => $hold->branchcode, - lang => $patron->lang, - tables => { - 'branches' => $library->unblessed, - 'borrowers' => $patron->unblessed, - 'biblio' => $hold->biblionumber, - 'biblioitems' => $hold->biblionumber, - 'reserves' => $hold->unblessed, - 'items' => $hold->itemnumber, + lang => $patron->lang, + tables => { + 'branches' => $library->unblessed, + 'borrowers' => $patron->unblessed, + 'biblio' => $hold->biblionumber, + 'biblioitems' => $hold->biblionumber, + 'reserves' => $hold->unblessed, + 'items' => $hold->itemnumber, }, ); - my $notification_sent = 0; #Keeping track if a Hold_filled message is sent. If no message can be sent, then default to a print message. - my $do_not_lock = ( exists $ENV{_} && $ENV{_} =~ m|prove| ) || $ENV{KOHA_TESTING}; + my $notification_sent = + 0; #Keeping track if a Hold_filled message is sent. If no message can be sent, then default to a print message. + my $do_not_lock = ( exists $ENV{_} && $ENV{_} =~ m|prove| ) || $ENV{KOHA_TESTING}; my $send_notification = sub { my ( $mtt, $letter_code, $wants_digest ) = (@_); return unless defined $letter_code; @@ -1833,19 +1889,23 @@ sub _koha_notify_reserve { }; while ( my ( $mtt, $letter_code ) = each %{ $messagingprefs->{transports} } ) { - next if ( - ( $mtt eq 'email' and not $to_address ) # No email address - or ( $mtt eq 'sms' and not $patron->smsalertnumber ) # No SMS number - or ( $mtt eq 'itiva' and C4::Context->preference('TalkingTechItivaPhoneNotification') ) # Notice is handled by TalkingTech_itiva_outbound.pl - or ( $mtt eq 'phone' and not $patron->phone ) # No phone number to call - ); + next + if ( + ( $mtt eq 'email' and not $to_address ) # No email address + or ( $mtt eq 'sms' and not $patron->smsalertnumber ) # No SMS number + or ( $mtt eq 'itiva' + and C4::Context->preference('TalkingTechItivaPhoneNotification') + ) # Notice is handled by TalkingTech_itiva_outbound.pl + or ( $mtt eq 'phone' and not $patron->phone ) # No phone number to call + ); - &$send_notification($mtt, $letter_code, $messagingprefs->{wants_digest}); + &$send_notification( $mtt, $letter_code, $messagingprefs->{wants_digest} ); $notification_sent++; } + #Making sure that a print notification is sent if no other transport types can be utilized. - if (! $notification_sent) { - &$send_notification('print', 'HOLD'); + if ( !$notification_sent ) { + &$send_notification( 'print', 'HOLD' ); } } @@ -1859,14 +1919,14 @@ sub _koha_notify_reserve { sub _koha_notify_hold_changed { my $hold = shift; - my $patron = $hold->patron; + my $patron = $hold->patron; my $library = $hold->branch; my $letter = C4::Letters::GetPreparedLetter( module => 'reserves', letter_code => 'HOLD_CHANGED', branchcode => $hold->branchcode, - substitute => { today => output_pref( dt_from_string ) }, + substitute => { today => output_pref(dt_from_string) }, tables => { 'branches' => $library->unblessed, 'borrowers' => $patron->unblessed, @@ -1879,9 +1939,8 @@ sub _koha_notify_hold_changed { return unless $letter; - my $email = - C4::Context->preference('ExpireReservesAutoFillEmail') - || $library->inbound_email_address; + my $email = C4::Context->preference('ExpireReservesAutoFillEmail') + || $library->inbound_email_address; C4::Letters::EnqueueLetter( { @@ -1915,13 +1974,14 @@ the sub accounts for that too. sub _ShiftPriority { my ( $biblio, $new_priority ) = @_; - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $query = "SELECT priority FROM reserves WHERE biblionumber = ? AND priority > ? ORDER BY priority ASC LIMIT 1"; - my $sth = $dbh->prepare( $query ); + my $sth = $dbh->prepare($query); $sth->execute( $biblio, $new_priority ); my $min_priority = $sth->fetchrow; + # if no such matches are found, $new_priority remains as original value - $new_priority = $min_priority if ( $min_priority ); + $new_priority = $min_priority if ($min_priority); # Shift the priority up by one; works in conjunction with the next SQL statement $query = "UPDATE reserves @@ -1930,17 +1990,18 @@ sub _ShiftPriority { AND borrowernumber = ? AND reservedate = ? AND found IS NULL"; - my $sth_update = $dbh->prepare( $query ); + my $sth_update = $dbh->prepare($query); # Select all reserves for the biblio with priority greater than $new_priority, and order greatest to least - $query = "SELECT borrowernumber, reservedate FROM reserves WHERE priority >= ? AND biblionumber = ? ORDER BY priority DESC"; - $sth = $dbh->prepare( $query ); + $query = + "SELECT borrowernumber, reservedate FROM reserves WHERE priority >= ? AND biblionumber = ? ORDER BY priority DESC"; + $sth = $dbh->prepare($query); $sth->execute( $new_priority, $biblio ); while ( my $row = $sth->fetchrow_hashref ) { - $sth_update->execute( $biblio, $row->{borrowernumber}, $row->{reservedate} ); + $sth_update->execute( $biblio, $row->{borrowernumber}, $row->{reservedate} ); } - return $new_priority; # so the caller knows what priority they wind up receiving + return $new_priority; # so the caller knows what priority they wind up receiving } =head2 MoveReserve @@ -1957,38 +2018,39 @@ sub MoveReserve { $cancelreserve //= 0; - my $lookahead = C4::Context->preference('ConfirmFutureHolds'); #number of days to look for future holds - my $item = Koha::Items->find($itemnumber); + my $lookahead = C4::Context->preference('ConfirmFutureHolds'); #number of days to look for future holds + my $item = Koha::Items->find($itemnumber); my ( $restype, $res, undef ) = CheckReserves( $item, $lookahead ); return unless $res; my $biblionumber = $res->{biblionumber}; - if ($res->{borrowernumber} == $borrowernumber) { + if ( $res->{borrowernumber} == $borrowernumber ) { my $hold = Koha::Holds->find( $res->{reserve_id} ); - $hold->fill({ item_id => $itemnumber }); - } - else { + $hold->fill( { item_id => $itemnumber } ); + } else { + # warn "Reserved"; # The item is reserved by someone else. # Find this item in the reserves - my $borr_res = Koha::Holds->search({ - borrowernumber => $borrowernumber, - biblionumber => $biblionumber, - },{ - order_by => 'priority' - })->next(); + my $borr_res = Koha::Holds->search( + { + borrowernumber => $borrowernumber, + biblionumber => $biblionumber, + }, + { order_by => 'priority' } + )->next(); + + if ($borr_res) { - if ( $borr_res ) { # The item is reserved by the current patron - $borr_res->fill({ item_id => $itemnumber }); + $borr_res->fill( { item_id => $itemnumber } ); } - if ( $cancelreserve eq 'revert' ) { ## Revert waiting reserve to priority 1 - RevertWaitingStatus({ itemnumber => $itemnumber }); - } - elsif ( $cancelreserve eq 'cancel' || $cancelreserve ) { # cancel reserves on this item + if ( $cancelreserve eq 'revert' ) { ## Revert waiting reserve to priority 1 + RevertWaitingStatus( { itemnumber => $itemnumber } ); + } elsif ( $cancelreserve eq 'cancel' || $cancelreserve ) { # cancel reserves on this item my $hold = Koha::Holds->find( $res->{reserve_id} ); $hold->cancel; } @@ -2005,28 +2067,25 @@ This shifts the holds from C<$from_biblio> to C<$to_biblio> and reorders them by sub MergeHolds { my ( $dbh, $to_biblio, $from_biblio ) = @_; - my $sth = $dbh->prepare( - "SELECT count(*) as reserve_count FROM reserves WHERE biblionumber = ?" - ); + my $sth = $dbh->prepare("SELECT count(*) as reserve_count FROM reserves WHERE biblionumber = ?"); $sth->execute($from_biblio); if ( my $data = $sth->fetchrow_hashref() ) { # holds exist on old record, if not we don't need to do anything - $sth = $dbh->prepare( - "UPDATE reserves SET biblionumber = ? WHERE biblionumber = ?"); + $sth = $dbh->prepare("UPDATE reserves SET biblionumber = ? WHERE biblionumber = ?"); $sth->execute( $to_biblio, $from_biblio ); # Reorder by date # don't reorder those already waiting $sth = $dbh->prepare( -"SELECT * FROM reserves WHERE biblionumber = ? AND (found NOT IN ('W', 'T', 'P') OR found is NULL) ORDER BY reservedate ASC" + "SELECT * FROM reserves WHERE biblionumber = ? AND (found NOT IN ('W', 'T', 'P') OR found is NULL) ORDER BY reservedate ASC" ); my $upd_sth = $dbh->prepare( -"UPDATE reserves SET priority = ? WHERE biblionumber = ? AND borrowernumber = ? + "UPDATE reserves SET priority = ? WHERE biblionumber = ? AND borrowernumber = ? AND reservedate = ? AND (itemnumber = ? or itemnumber is NULL) " ); - $sth->execute( $to_biblio ); + $sth->execute($to_biblio); my $priority = 1; while ( my $reserve = $sth->fetchrow_hashref() ) { $upd_sth->execute( @@ -2054,10 +2113,10 @@ sub MergeHolds { =cut sub RevertWaitingStatus { - my ( $params ) = @_; + my ($params) = @_; my $itemnumber = $params->{'itemnumber'}; - return unless ( $itemnumber ); + return unless ($itemnumber); my $dbh = C4::Context->dbh; @@ -2065,7 +2124,7 @@ sub RevertWaitingStatus { my $hold = Koha::Holds->search( { itemnumber => $itemnumber, - found => { not => undef }, + found => { not => undef }, } )->next; @@ -2073,8 +2132,8 @@ sub RevertWaitingStatus { ## Increment the priority of all other non-waiting ## reserves for this bib record - my $holds = Koha::Holds->search({ biblionumber => $hold->biblionumber, priority => { '>' => 0 } }) - ->update({ priority => \'priority + 1' }, { no_triggers => 1 }); + my $holds = Koha::Holds->search( { biblionumber => $hold->biblionumber, priority => { '>' => 0 } } ) + ->update( { priority => \'priority + 1' }, { no_triggers => 1 } ); ## Fix up the currently waiting reserve $hold->set( @@ -2092,12 +2151,8 @@ sub RevertWaitingStatus { _FixPriority( { biblionumber => $hold->biblionumber } ); - Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue->new->enqueue( - { - biblio_ids => [ $hold->biblionumber ] - } - ) if C4::Context->preference('RealTimeHoldsQueue'); - + Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue->new->enqueue( { biblio_ids => [ $hold->biblionumber ] } ) + if C4::Context->preference('RealTimeHoldsQueue'); return $hold; } @@ -2129,23 +2184,23 @@ available within the slip: =cut sub ReserveSlip { - my ($args) = @_; - my $branchcode = $args->{branchcode}; + my ($args) = @_; + my $branchcode = $args->{branchcode}; my $reserve_id = $args->{reserve_id}; my $itemnumber = $args->{itemnumber}; my $hold = Koha::Holds->find($reserve_id); return unless $hold; - my $patron = $hold->borrower; + my $patron = $hold->borrower; my $reserve = $hold->unblessed; - return C4::Letters::GetPreparedLetter ( - module => 'circulation', + return C4::Letters::GetPreparedLetter( + module => 'circulation', letter_code => 'HOLD_SLIP', - branchcode => $branchcode, - lang => $patron->lang, - tables => { + branchcode => $branchcode, + lang => $patron->lang, + tables => { 'reserves' => $reserve, 'branches' => $reserve->{branchcode}, 'borrowers' => $reserve->{borrowernumber}, @@ -2184,21 +2239,21 @@ sub CalculatePriority { AND priority > 0 AND (found IS NULL OR found = '') }; + #skip found==W or found==T or found==P (waiting, transit or processing holds) - if( $resdate ) { - $sql.= ' AND ( reservedate <= ? )'; - } - else { - $sql.= ' AND ( reservedate < NOW() )'; + if ($resdate) { + $sql .= ' AND ( reservedate <= ? )'; + } else { + $sql .= ' AND ( reservedate < NOW() )'; } my $dbh = C4::Context->dbh(); my @row = $dbh->selectrow_array( $sql, undef, - $resdate ? ($biblionumber, $resdate) : ($biblionumber) + $resdate ? ( $biblionumber, $resdate ) : ($biblionumber) ); - return @row ? $row[0]+1 : 1; + return @row ? $row[0] + 1 : 1; } =head2 GetMaxPatronHoldsForRecord @@ -2217,7 +2272,7 @@ sub GetMaxPatronHoldsForRecord { my ( $borrowernumber, $biblionumber ) = @_; my $patron = Koha::Patrons->find($borrowernumber); - my @items = Koha::Items->search( { biblionumber => $biblionumber } )->as_list; + my @items = Koha::Items->search( { biblionumber => $biblionumber } )->as_list; my $controlbranch = C4::Context->preference('ReservesControlBranch'); @@ -2231,12 +2286,14 @@ sub GetMaxPatronHoldsForRecord { $branchcode = $item->homebranch if ( $controlbranch eq "ItemHomeLibrary" ); - my $rule = Koha::CirculationRules->get_effective_rule({ - categorycode => $categorycode, - itemtype => $itemtype, - branchcode => $branchcode, - rule_name => 'holds_per_record' - }); + my $rule = Koha::CirculationRules->get_effective_rule( + { + categorycode => $categorycode, + itemtype => $itemtype, + branchcode => $branchcode, + rule_name => 'holds_per_record' + } + ); my $holds_per_record = $rule ? $rule->rule_value : 0; $max = $holds_per_record if $holds_per_record > $max; } diff --git a/C4/Ris.pm b/C4/Ris.pm index b03f1eaa70..39703c94f5 100644 --- a/C4/Ris.pm +++ b/C4/Ris.pm @@ -16,7 +16,7 @@ package C4::Ris; ## 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. -## +## ## This program 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 @@ -37,7 +37,6 @@ package C4::Ris; ## comparing UKMARC to MARC21 found at: ## www.bl.uk/services/bibliographic/marcchange.pdf - # Modified 2008 by BibLibre for Koha # Modified 2011 by Catalyst # Modified 2011 by Equinox Software, Inc. @@ -68,16 +67,15 @@ use vars qw(@ISA @EXPORT); use Koha::SimpleMARC qw( read_field ); - @ISA = qw(Exporter); # only export API methods @EXPORT = qw( - marc2ris + marc2ris ); -our $marcprint = 0; # Debug flag; +our $marcprint = 0; # Debug flag; =head1 marc2bibtex - Convert from UNIMARC to RIS @@ -93,13 +91,13 @@ sub marc2ris { my ($record) = @_; my $marcflavour = C4::Context->preference("marcflavour"); - my $intype = lc($marcflavour); + my $intype = lc($marcflavour); # Let's redirect stdout open my $oldout, qw{>&}, "STDOUT"; my $outvar; close STDOUT; - open STDOUT,'>:encoding(utf8)', \$outvar; + open STDOUT, '>:encoding(utf8)', \$outvar; ## First we should check the character encoding. This may be ## MARC-8 or UTF-8. The former is indicated by a blank, the latter @@ -108,8 +106,7 @@ sub marc2ris { if ( $intype eq "marc21" ) { if ( $leader =~ /^.{9}a/ ) { print "---\r\nUTF-8 data\r\n" if $marcprint; - } - else { + } else { print "---\r\nMARC-8 data\r\n" if $marcprint; } } @@ -121,180 +118,187 @@ sub marc2ris { ## start RIS dataset if ( $ris_additional_fields && $ris_additional_fields->{TY} ) { my ( $f, $sf ) = split( /\$/, $ris_additional_fields->{TY} ); - my ( $type ) = read_field( { record => $record, field => $f, subfield => $sf, field_numbers => [1] } ); + my ($type) = read_field( { record => $record, field => $f, subfield => $sf, field_numbers => [1] } ); if ($type) { print "TY - $type\r\n"; - } - else { + } else { &print_typetag($leader); } - } - else { + } else { &print_typetag($leader); } - ## retrieve all author fields and collect them in a list - my @author_fields; + ## retrieve all author fields and collect them in a list + my @author_fields; - if ($intype eq "unimarc") { - ## Fields 700, 701, and 702 can contain author names - @author_fields = ($record->field('700'), $record->field('701'), $record->field('702')); - } - else { ## marc21, ukmarc - ## Field 100 sometimes carries main author - ## Field(s) 700 carry added entries - personal names - @author_fields = ($record->field('100'), $record->field('700')); - } + if ( $intype eq "unimarc" ) { + ## Fields 700, 701, and 702 can contain author names + @author_fields = ( $record->field('700'), $record->field('701'), $record->field('702') ); + } else { ## marc21, ukmarc + ## Field 100 sometimes carries main author + ## Field(s) 700 carry added entries - personal names + @author_fields = ( $record->field('100'), $record->field('700') ); + } - ## loop over all author fields - foreach my $field (@author_fields) { - if (length($field)) { - my $author = &get_author($field); - print "AU - ",$author,"\r\n"; - } - } + ## loop over all author fields + foreach my $field (@author_fields) { + if ( length($field) ) { + my $author = &get_author($field); + print "AU - ", $author, "\r\n"; + } + } - # ToDo: should we specify anonymous as author if we didn't find - # one? or use one of the corporate/meeting names below? + # ToDo: should we specify anonymous as author if we didn't find + # one? or use one of the corporate/meeting names below? - ## add corporate names or meeting names as editors ?? - my @editor_fields; + ## add corporate names or meeting names as editors ?? + my @editor_fields; - if ($intype eq "unimarc") { - ## Fields 710, 711, and 712 can carry corporate names - ## Field(s) 720, 721, 722, 730 have additional candidates - @editor_fields = ($record->field('710'), $record->field('711'), $record->field('712'), $record->field('720'), $record->field('721'), $record->field('722'), $record->field('730')); - } - else { ## marc21, ukmarc - ## Fields 110 and 111 carry the main entries - corporate name and - ## meeting name, respectively - ## Field(s) 710, 711 carry added entries - personal names - @editor_fields = ($record->field('110'), $record->field('111'), $record->field('710'), $record->field('711')); - } + if ( $intype eq "unimarc" ) { + ## Fields 710, 711, and 712 can carry corporate names + ## Field(s) 720, 721, 722, 730 have additional candidates + @editor_fields = ( + $record->field('710'), $record->field('711'), $record->field('712'), $record->field('720'), + $record->field('721'), $record->field('722'), $record->field('730') + ); + } else { ## marc21, ukmarc + ## Fields 110 and 111 carry the main entries - corporate name and + ## meeting name, respectively + ## Field(s) 710, 711 carry added entries - personal names + @editor_fields = ( $record->field('110'), $record->field('111'), $record->field('710'), $record->field('711') ); + } - ## loop over all editor fields - foreach my $field (@editor_fields) { - if (length($field)) { - my $editor = &get_editor($field); - print "ED - ",$editor,"\r\n"; - } - } + ## loop over all editor fields + foreach my $field (@editor_fields) { + if ( length($field) ) { + my $editor = &get_editor($field); + print "ED - ", $editor, "\r\n"; + } + } - ## get info from the title field - if ($intype eq "unimarc") { - &print_title($record->field('200')); - } - else { ## marc21, ukmarc - &print_title($record->field('245')); - } + ## get info from the title field + if ( $intype eq "unimarc" ) { + &print_title( $record->field('200') ); + } else { ## marc21, ukmarc + &print_title( $record->field('245') ); + } - ## series title - if ($intype eq "unimarc") { - &print_stitle($record->field('225')); - } - else { ## marc21, ukmarc - &print_stitle($record->field('490')); - } + ## series title + if ( $intype eq "unimarc" ) { + &print_stitle( $record->field('225') ); + } else { ## marc21, ukmarc + &print_stitle( $record->field('490') ); + } - ## ISBN/ISSN - if ($intype eq "unimarc") { - &print_isbn($record->field('010')); - &print_issn($record->field('011')); - } - elsif ($intype eq "ukmarc") { - &print_isbn($record->field('021')); - ## this is just an assumption - &print_issn($record->field('022')); - } - else { ## assume marc21 - &print_isbn($record->field('020')); - &print_issn($record->field('022')); - } + ## ISBN/ISSN + if ( $intype eq "unimarc" ) { + &print_isbn( $record->field('010') ); + &print_issn( $record->field('011') ); + } elsif ( $intype eq "ukmarc" ) { + &print_isbn( $record->field('021') ); + ## this is just an assumption + &print_issn( $record->field('022') ); + } else { ## assume marc21 + &print_isbn( $record->field('020') ); + &print_issn( $record->field('022') ); + } - if ($intype eq "marc21") { - &print_loc_callno($record->field('050')); - &print_dewey($record->field('082')); - } - ## else: unimarc, ukmarc do not seem to store call numbers? - - ## publication info - if ($intype eq "unimarc") { - &print_pubinfo($record->field('210')); - } - else { ## marc21, ukmarc - if ($record->field('264')) { - &print_pubinfo($record->field('264')); - } - else { - &print_pubinfo($record->field('260')); - } - } + if ( $intype eq "marc21" ) { + &print_loc_callno( $record->field('050') ); + &print_dewey( $record->field('082') ); + } + ## else: unimarc, ukmarc do not seem to store call numbers? - ## 6XX fields contain KW candidates. We add all of them to a + ## publication info + if ( $intype eq "unimarc" ) { + &print_pubinfo( $record->field('210') ); + } else { ## marc21, ukmarc + if ( $record->field('264') ) { + &print_pubinfo( $record->field('264') ); + } else { + &print_pubinfo( $record->field('260') ); + } + } + + ## 6XX fields contain KW candidates. We add all of them to a my @field_list; - if ($intype eq "unimarc") { - @field_list = ('600', '601', '602', '604', '605', '606','607', '608', '610', '615', '620', '660', '661', '670', '675', '676', '680', '686'); - } elsif ($intype eq "ukmarc") { - @field_list = ('600', '610', '611', '630', '650', '651','653', '655', '660', '661', '668', '690', '691', '692', '695'); - } else { ## assume marc21 - @field_list = ('600', '610', '611', '630', '650', '651','653', '654', '655', '656', '657', '658'); + if ( $intype eq "unimarc" ) { + @field_list = ( + '600', '601', '602', '604', '605', '606', '607', '608', '610', '615', '620', '660', '661', '670', '675', + '676', '680', '686' + ); + } elsif ( $intype eq "ukmarc" ) { + @field_list = + ( '600', '610', '611', '630', '650', '651', '653', '655', '660', '661', '668', '690', '691', '692', '695' ); + } else { ## assume marc21 + @field_list = ( '600', '610', '611', '630', '650', '651', '653', '654', '655', '656', '657', '658' ); } my @kwpool; - for my $f ( @field_list ) { + for my $f (@field_list) { my @fields = $record->field($f); - push @kwpool, ( get_keywords("$f",$record->field($f)) ); + push @kwpool, ( get_keywords( "$f", $record->field($f) ) ); } # Remove duplicate @kwpool = uniq @kwpool; - for my $kw ( @kwpool ) { + for my $kw (@kwpool) { print "KW - ", $kw, "\r\n"; } - ## 5XX have various candidates for notes and abstracts. We pool - ## all notes-like stuff in one list. - my @notepool; + ## 5XX have various candidates for notes and abstracts. We pool + ## all notes-like stuff in one list. + my @notepool; - ## these fields have notes candidates - if ($intype eq "unimarc") { - foreach ('300', '301', '302', '303', '304', '305', '306', '307', '308', '310', '311', '312', '313', '314', '315', '316', '317', '318', '320', '321', '322', '323', '324', '325', '326', '327', '328', '332', '333', '336', '337', '345') { - &pool_subx(\@notepool, $_, $record->field($_)); - } - } - elsif ($intype eq "ukmarc") { - foreach ('500', '501', '502', '503', '504', '505', '506', '508', '514', '515', '516', '521', '524', '525', '528', '530', '531', '532', '533', '534', '535', '537', '538', '540', '541', '542', '544', '554', '555', '556', '557', '561', '563', '580', '583', '584', '586') { - &pool_subx(\@notepool, $_, $record->field($_)); + ## these fields have notes candidates + if ( $intype eq "unimarc" ) { + foreach ( + '300', '301', '302', '303', '304', '305', '306', '307', '308', '310', '311', '312', '313', '314', + '315', '316', '317', '318', '320', '321', '322', '323', '324', '325', '326', '327', '328', '332', '333', + '336', '337', '345' + ) + { + &pool_subx( \@notepool, $_, $record->field($_) ); } - } - else { ## assume marc21 - foreach ('500', '501', '502', '504', '505', '506', '507', '508', '510', '511', '513', '514', '515', '516', '518', '521', '522', '524', '525', '526', '530', '533', '534', '535') { - &pool_subx(\@notepool, $_, $record->field($_)); - } - } + } elsif ( $intype eq "ukmarc" ) { + foreach ( + '500', '501', '502', '503', '504', '505', '506', '508', '514', '515', '516', '521', '524', '525', + '528', '530', '531', '532', '533', '534', '535', '537', '538', '540', '541', '542', '544', '554', '555', + '556', '557', '561', '563', '580', '583', '584', '586' + ) + { + &pool_subx( \@notepool, $_, $record->field($_) ); + } + } else { ## assume marc21 + foreach ( + '500', '501', '502', '504', '505', '506', '507', '508', '510', '511', '513', '514', '515', '516', + '518', '521', '522', '524', '525', '526', '530', '533', '534', '535' + ) + { + &pool_subx( \@notepool, $_, $record->field($_) ); + } + } - my $allnotes = join "; ", @notepool; + my $allnotes = join "; ", @notepool; - if (length($allnotes) > 0) { - print "N1 - ", $allnotes, "\r\n"; - } + if ( length($allnotes) > 0 ) { + print "N1 - ", $allnotes, "\r\n"; + } + + ## 320/520 have the abstract + if ( $intype eq "unimarc" ) { + &print_abstract( $record->field('320') ); + } elsif ( $intype eq "ukmarc" ) { + &print_abstract( $record->field('512'), $record->field('513') ); + } else { ## assume marc21 + &print_abstract( $record->field('520') ); + } - ## 320/520 have the abstract - if ($intype eq "unimarc") { - &print_abstract($record->field('320')); - } - elsif ($intype eq "ukmarc") { - &print_abstract($record->field('512'), $record->field('513')); - } - else { ## assume marc21 - &print_abstract($record->field('520')); - } - # 856u has the URI - if ($record->field('856')) { - print_uri($record->field('856')); + if ( $record->field('856') ) { + print_uri( $record->field('856') ); } if ($ris_additional_fields) { @@ -302,9 +306,9 @@ sub marc2ris { next if $ris_tag eq 'TY'; my @fields = - ref( $ris_additional_fields->{$ris_tag} ) eq 'ARRAY' - ? @{ $ris_additional_fields->{$ris_tag} } - : $ris_additional_fields->{$ris_tag}; + ref( $ris_additional_fields->{$ris_tag} ) eq 'ARRAY' + ? @{ $ris_additional_fields->{$ris_tag} } + : $ris_additional_fields->{$ris_tag}; for my $tag (@fields) { my ( $f, $sf ) = split( /\$/, $tag ); @@ -316,96 +320,92 @@ sub marc2ris { } } - ## end RIS dataset - print "ER - \r\n"; + ## end RIS dataset + print "ER - \r\n"; # Let's re-redirect stdout close STDOUT; open STDOUT, ">&", $oldout; - + return $outvar; } - ##******************************************************************** ## print_typetag(): prints the first line of a RIS dataset including ## the preceding newline ## Argument: the leader of a MARC dataset -## Returns: the value at leader position 06 +## Returns: the value at leader position 06 ##******************************************************************** sub print_typetag { - my ($leader)= @_; + my ($leader) = @_; ## the keys of typehash are the allowed values at position 06 ## of the leader of a MARC record, the values are the RIS types ## that might appropriately represent these types. my %ustypehash = ( - "a" => "BOOK", - "c" => "MUSIC", - "d" => "MUSIC", - "e" => "MAP", - "f" => "MAP", - "g" => "ADVS", - "i" => "SOUND", - "j" => "SOUND", - "k" => "ART", - "m" => "DATA", - "o" => "GEN", - "p" => "GEN", - "r" => "ART", - "t" => "MANSCPT", - ); + "a" => "BOOK", + "c" => "MUSIC", + "d" => "MUSIC", + "e" => "MAP", + "f" => "MAP", + "g" => "ADVS", + "i" => "SOUND", + "j" => "SOUND", + "k" => "ART", + "m" => "DATA", + "o" => "GEN", + "p" => "GEN", + "r" => "ART", + "t" => "MANSCPT", + ); my %unitypehash = ( - "a" => "BOOK", - "b" => "MANSCPT", - "c" => "MUSIC", - "d" => "MUSIC", - "e" => "MAP", - "f" => "MAP", - "g" => "ADVS", - "i" => "SOUND", - "j" => "SOUND", - "k" => "ART", - "l" => "ELEC", - "m" => "GEN", - "r" => "ART", - ); + "a" => "BOOK", + "b" => "MANSCPT", + "c" => "MUSIC", + "d" => "MUSIC", + "e" => "MAP", + "f" => "MAP", + "g" => "ADVS", + "i" => "SOUND", + "j" => "SOUND", + "k" => "ART", + "l" => "ELEC", + "m" => "GEN", + "r" => "ART", + ); ## The type of a MARC record is found at position 06 of the leader - my $typeofrecord = defined($leader) && length $leader >=6 ? - substr($leader, 6, 1): undef; + my $typeofrecord = defined($leader) && length $leader >= 6 ? substr( $leader, 6, 1 ) : undef; ## Pos 07 == Bibliographic level - my $biblevel = defined($leader) && length $leader >=7 ? - substr($leader, 7, 1): ''; + my $biblevel = defined($leader) && length $leader >= 7 ? substr( $leader, 7, 1 ) : ''; ## TODO: for books, field 008 positions 24-27 might have a few more ## hints my %typehash; my $marcflavour = C4::Context->preference("marcflavour"); - my $intype = lc($marcflavour); - if ($intype eq "unimarc") { + my $intype = lc($marcflavour); + if ( $intype eq "unimarc" ) { %typehash = %unitypehash; - } - else { + } else { %typehash = %ustypehash; } - if (!defined $typeofrecord || !exists $typehash{$typeofrecord}) { - print "TY - GEN\r\n"; ## most reasonable default - warn ("no type found - assume GEN") if $marcprint; + if ( !defined $typeofrecord || !exists $typehash{$typeofrecord} ) { + print "TY - GEN\r\n"; ## most reasonable default + warn("no type found - assume GEN") if $marcprint; } elsif ( $typeofrecord =~ "a" ) { if ( $biblevel eq 'a' ) { - print "TY - GEN\r\n"; ## monographic component part + print "TY - GEN\r\n"; ## monographic component part } elsif ( $biblevel eq 'b' || $biblevel eq 's' ) { - print "TY - SER\r\n"; ## serial or serial component part + print "TY - SER\r\n"; ## serial or serial component part } elsif ( $biblevel eq 'm' ) { - print "TY - $typehash{$typeofrecord}\r\n"; ## book + print "TY - $typehash{$typeofrecord}\r\n"; ## book } elsif ( $biblevel eq 'c' || $biblevel eq 'd' ) { - print "TY - GEN\r\n"; ## collections, part of collections or made-up collections + print "TY - GEN\r\n"; ## collections, part of collections or made-up collections } elsif ( $biblevel eq 'i' ) { - print "TY - DATA\r\n"; ## updating loose-leafe as Dataset + print "TY - DATA\r\n"; ## updating loose-leafe as Dataset } } else { print "TY - $typehash{$typeofrecord}\r\n"; @@ -427,38 +427,36 @@ sub print_typetag { ## Returns: the normalized authorname ##******************************************************************** sub normalize_author { - my($rawauthora, $rawauthorb, $rawauthorc, $nametype) = @_; + my ( $rawauthora, $rawauthorb, $rawauthorc, $nametype ) = @_; - if ($nametype == 0) { - # ToDo: convert every input to Last[,(F.|First)[ (M.|Middle)[,Suffix]]] - warn("name >>$rawauthora<< in direct order - leave as is") if $marcprint; - return $rawauthora; - } - elsif ($nametype == 1) { - ## start munging subfield a (the real name part) - ## remove spaces after separators - $rawauthora =~ s%([,.]+) *%$1%g; + if ( $nametype == 0 ) { - ## remove trailing separators after spaces - $rawauthora =~ s% *[,;:/]*$%%; + # ToDo: convert every input to Last[,(F.|First)[ (M.|Middle)[,Suffix]]] + warn("name >>$rawauthora<< in direct order - leave as is") if $marcprint; + return $rawauthora; + } elsif ( $nametype == 1 ) { + ## start munging subfield a (the real name part) + ## remove spaces after separators + $rawauthora =~ s%([,.]+) *%$1%g; - ## remove periods after a non-abbreviated name - $rawauthora =~ s%(\w{2,})\.%$1%g; + ## remove trailing separators after spaces + $rawauthora =~ s% *[,;:/]*$%%; - ## start munging subfield b (something like the suffix) - ## remove trailing separators after spaces - $rawauthorb =~ s% *[,;:/]*$%%; + ## remove periods after a non-abbreviated name + $rawauthora =~ s%(\w{2,})\.%$1%g; - ## we currently ignore subfield c until someone complains - if (length($rawauthorb) > 0) { - return join ", ", ($rawauthora, $rawauthorb); - } - else { - return $rawauthora; - } - } - elsif ($nametype == 3) { - return $rawauthora; + ## start munging subfield b (something like the suffix) + ## remove trailing separators after spaces + $rawauthorb =~ s% *[,;:/]*$%%; + + ## we currently ignore subfield c until someone complains + if ( length($rawauthorb) > 0 ) { + return join ", ", ( $rawauthora, $rawauthorb ); + } else { + return $rawauthora; + } + } elsif ( $nametype == 3 ) { + return $rawauthora; } } @@ -474,25 +472,29 @@ sub get_author { ## the sequence of the name parts is encoded either in indicator ## 1 (marc21) or 2 (unimarc) my $marcflavour = C4::Context->preference("marcflavour"); - my $intype = lc($marcflavour); - if ($intype eq "unimarc") { - $indicator = 2; - } - else { ## assume marc21 - $indicator = 1; + my $intype = lc($marcflavour); + if ( $intype eq "unimarc" ) { + $indicator = 2; + } else { ## assume marc21 + $indicator = 1; } - print ":Author(Ind$indicator): ", $authorfield->indicator("$indicator"),"\r\n" if $marcprint; - print ":Author(\$a): ", $authorfield->subfield('a'),"\r\n" if $marcprint; - print ":Author(\$b): ", $authorfield->subfield('b'),"\r\n" if $marcprint; - print ":Author(\$c): ", $authorfield->subfield('c'),"\r\n" if $marcprint; - print ":Author(\$h): ", $authorfield->subfield('h'),"\r\n" if $marcprint; - if ($intype eq "ukmarc") { - my $authorname = $authorfield->subfield('a') . "," . $authorfield->subfield('h'); - normalize_author($authorname, $authorfield->subfield('b'), $authorfield->subfield('c'), $authorfield->indicator("$indicator")); - } - else { - normalize_author($authorfield->subfield('a') // '', $authorfield->subfield('b') // '', $authorfield->subfield('c') // '', $authorfield->indicator("$indicator")); + print ":Author(Ind$indicator): ", $authorfield->indicator("$indicator"), "\r\n" if $marcprint; + print ":Author(\$a): ", $authorfield->subfield('a'), "\r\n" if $marcprint; + print ":Author(\$b): ", $authorfield->subfield('b'), "\r\n" if $marcprint; + print ":Author(\$c): ", $authorfield->subfield('c'), "\r\n" if $marcprint; + print ":Author(\$h): ", $authorfield->subfield('h'), "\r\n" if $marcprint; + if ( $intype eq "ukmarc" ) { + my $authorname = $authorfield->subfield('a') . "," . $authorfield->subfield('h'); + normalize_author( + $authorname, $authorfield->subfield('b'), $authorfield->subfield('c'), + $authorfield->indicator("$indicator") + ); + } else { + normalize_author( + $authorfield->subfield('a') // '', $authorfield->subfield('b') // '', + $authorfield->subfield('c') // '', $authorfield->indicator("$indicator") + ); } } @@ -504,97 +506,95 @@ sub get_author { sub get_editor { my ($editorfield) = @_; - if (!$editorfield) { - return; - } - else { - print "Editor(\$a): ", $editorfield->subfield('a'),"\r\n" if $marcprint; - print "Editor(\$b): ", $editorfield->subfield('b'),"\r\n" if $marcprint; - print "editor(\$c): ", $editorfield->subfield('c'),"\r\n" if $marcprint; - return $editorfield->subfield('a'); + if ( !$editorfield ) { + return; + } else { + print "Editor(\$a): ", $editorfield->subfield('a'), "\r\n" if $marcprint; + print "Editor(\$b): ", $editorfield->subfield('b'), "\r\n" if $marcprint; + print "editor(\$c): ", $editorfield->subfield('c'), "\r\n" if $marcprint; + return $editorfield->subfield('a'); } } ##******************************************************************** ## print_title(): gets info from MARC field 245 ## Arguments: field (245) -## Returns: +## Returns: ##******************************************************************** sub print_title { my ($titlefield) = @_; - if (!$titlefield) { - print "empty title field (245)\r\n" if $marcprint; - warn("empty title field (245)") if $marcprint; - } - else { - print "Title(\$a): ",$titlefield->subfield('a'),"\r\n" if $marcprint; - print "Title(\$b): ",$titlefield->subfield('b'),"\r\n" if $marcprint; - print "Title(\$c): ",$titlefield->subfield('c'),"\r\n" if $marcprint; - - ## The title is usually written in a very odd notation. The title - ## proper ($a) often ends with a space followed by a separator like - ## a slash or a colon. The subtitle ($b) doesn't start with a space - ## so simple concatenation looks odd. We have to conditionally remove - ## the separator and make sure there's a space between title and - ## subtitle + if ( !$titlefield ) { + print "empty title field (245)\r\n" if $marcprint; + warn("empty title field (245)") if $marcprint; + } else { + print "Title(\$a): ", $titlefield->subfield('a'), "\r\n" if $marcprint; + print "Title(\$b): ", $titlefield->subfield('b'), "\r\n" if $marcprint; + print "Title(\$c): ", $titlefield->subfield('c'), "\r\n" if $marcprint; - my $clean_title = $titlefield->subfield('a'); + ## The title is usually written in a very odd notation. The title + ## proper ($a) often ends with a space followed by a separator like + ## a slash or a colon. The subtitle ($b) doesn't start with a space + ## so simple concatenation looks odd. We have to conditionally remove + ## the separator and make sure there's a space between title and + ## subtitle - my $clean_subtitle = $titlefield->subfield('b'); -$clean_subtitle ||= q{}; - $clean_title =~ s% *[/:;.]$%%; - $clean_subtitle =~ s%^ *(.*) *[/:;.]$%$1%; + my $clean_title = $titlefield->subfield('a'); - my $marcflavour = C4::Context->preference("marcflavour"); - my $intype = lc($marcflavour); - if (length($clean_title) > 0 - || (length($clean_subtitle) > 0 && $intype ne "unimarc")) { - print "TI - ", $clean_title; + my $clean_subtitle = $titlefield->subfield('b'); + $clean_subtitle ||= q{}; + $clean_title =~ s% *[/:;.]$%%; + $clean_subtitle =~ s%^ *(.*) *[/:;.]$%$1%; - ## subfield $b is relevant only for marc21/ukmarc - if (length($clean_subtitle) > 0 && $intype ne "unimarc") { - print ": ",$clean_subtitle; - } - print "\r\n"; - } + my $marcflavour = C4::Context->preference("marcflavour"); + my $intype = lc($marcflavour); + if ( length($clean_title) > 0 + || ( length($clean_subtitle) > 0 && $intype ne "unimarc" ) ) + { + print "TI - ", $clean_title; - ## The statement of responsibility is just this: horrors. There is - ## no formal definition how authors, editors and the like should - ## be written and designated. The field is free-form and resistant - ## to all parsing efforts, so this information is lost on me + ## subfield $b is relevant only for marc21/ukmarc + if ( length($clean_subtitle) > 0 && $intype ne "unimarc" ) { + print ": ", $clean_subtitle; + } + print "\r\n"; + } + + ## The statement of responsibility is just this: horrors. There is + ## no formal definition how authors, editors and the like should + ## be written and designated. The field is free-form and resistant + ## to all parsing efforts, so this information is lost on me } return; } ##******************************************************************** ## print_stitle(): prints info from series title field -## Arguments: field -## Returns: +## Arguments: field +## Returns: ##******************************************************************** sub print_stitle { my ($titlefield) = @_; - if (!$titlefield) { - print "empty series title field\r\n" if $marcprint; - } - else { - print "Series title(\$a): ",$titlefield->subfield('a'),"\r\n" if $marcprint; - my $clean_title = $titlefield->subfield('a'); + if ( !$titlefield ) { + print "empty series title field\r\n" if $marcprint; + } else { + print "Series title(\$a): ", $titlefield->subfield('a'), "\r\n" if $marcprint; + my $clean_title = $titlefield->subfield('a'); - $clean_title =~ s% *[/:;.]$%%; + $clean_title =~ s% *[/:;.]$%%; - if (length($clean_title) > 0) { - print "T2 - ", $clean_title,"\r\n"; - } + if ( length($clean_title) > 0 ) { + print "T2 - ", $clean_title, "\r\n"; + } - my $marcflavour = C4::Context->preference("marcflavour"); - my $intype = lc($marcflavour); - if ($intype eq "unimarc") { - print "Series vol(\$v): ",$titlefield->subfield('v'),"\r\n" if $marcprint; - if (length($titlefield->subfield('v')) > 0) { - print "VL - ", $titlefield->subfield('v'),"\r\n"; - } - } + my $marcflavour = C4::Context->preference("marcflavour"); + my $intype = lc($marcflavour); + if ( $intype eq "unimarc" ) { + print "Series vol(\$v): ", $titlefield->subfield('v'), "\r\n" if $marcprint; + if ( length( $titlefield->subfield('v') ) > 0 ) { + print "VL - ", $titlefield->subfield('v'), "\r\n"; + } + } } return; } @@ -604,20 +604,19 @@ sub print_stitle { ## Arguments: field (020) ##******************************************************************** sub print_isbn { - my($isbnfield) = @_; + my ($isbnfield) = @_; - if (!$isbnfield || length ($isbnfield->subfield('a')) == 0) { - print "no isbn found (020\$a)\r\n" if $marcprint; - warn("no isbn found") if $marcprint; - } - else { - if (length ($isbnfield->subfield('a')) < 10) { - print "truncated isbn (020\$a)\r\n" if $marcprint; - warn("truncated isbn") if $marcprint; - } + if ( !$isbnfield || length( $isbnfield->subfield('a') ) == 0 ) { + print "no isbn found (020\$a)\r\n" if $marcprint; + warn("no isbn found") if $marcprint; + } else { + if ( length( $isbnfield->subfield('a') ) < 10 ) { + print "truncated isbn (020\$a)\r\n" if $marcprint; + warn("truncated isbn") if $marcprint; + } - my $isbn = $isbnfield->subfield('a'); - print "SN - ", $isbn, "\r\n"; + my $isbn = $isbnfield->subfield('a'); + print "SN - ", $isbn, "\r\n"; } } @@ -626,32 +625,31 @@ sub print_isbn { ## Arguments: field (022) ##******************************************************************** sub print_issn { - my($issnfield) = @_; + my ($issnfield) = @_; - if (!$issnfield || length ($issnfield->subfield('a')) == 0) { - print "no issn found (022\$a)\r\n" if $marcprint; - warn("no issn found") if $marcprint; - } - else { - if (length ($issnfield->subfield('a')) < 9) { - print "truncated issn (022\$a)\r\n" if $marcprint; - warn("truncated issn") if $marcprint; - } + if ( !$issnfield || length( $issnfield->subfield('a') ) == 0 ) { + print "no issn found (022\$a)\r\n" if $marcprint; + warn("no issn found") if $marcprint; + } else { + if ( length( $issnfield->subfield('a') ) < 9 ) { + print "truncated issn (022\$a)\r\n" if $marcprint; + warn("truncated issn") if $marcprint; + } - my $issn = substr($issnfield->subfield('a'), 0, 9); - print "SN - ", $issn, "\r\n"; + my $issn = substr( $issnfield->subfield('a'), 0, 9 ); + print "SN - ", $issn, "\r\n"; } } ### -# print_uri() prints info from 856 u +# print_uri() prints info from 856 u ### sub print_uri { my @f856s = @_; foreach my $f856 (@f856s) { - if (my $uri = $f856->subfield('u')) { - print "UR - ", $uri, "\r\n"; + if ( my $uri = $f856->subfield('u') ) { + print "UR - ", $uri, "\r\n"; } } } @@ -661,14 +659,13 @@ sub print_uri { ## Arguments: field (050) ##******************************************************************** sub print_loc_callno { - my($callnofield) = @_; + my ($callnofield) = @_; - if (!$callnofield || length ($callnofield->subfield('a')) == 0) { - print "no LOC call number found (050\$a)\r\n" if $marcprint; - warn("no LOC call number found") if $marcprint; - } - else { - print "AV - ", $callnofield->subfield('a'), " ", $callnofield->subfield('b'), "\r\n"; + if ( !$callnofield || length( $callnofield->subfield('a') ) == 0 ) { + print "no LOC call number found (050\$a)\r\n" if $marcprint; + warn("no LOC call number found") if $marcprint; + } else { + print "AV - ", $callnofield->subfield('a'), " ", $callnofield->subfield('b'), "\r\n"; } } @@ -677,14 +674,13 @@ sub print_loc_callno { ## Arguments: field (082) ##******************************************************************** sub print_dewey { - my($deweyfield) = @_; + my ($deweyfield) = @_; - if (!$deweyfield || length ($deweyfield->subfield('a')) == 0) { - print "no Dewey number found (082\$a)\r\n" if $marcprint; - warn("no Dewey number found") if $marcprint; - } - else { - print "U1 - ", $deweyfield->subfield('a'), " ", $deweyfield->subfield('2'), "\r\n"; + if ( !$deweyfield || length( $deweyfield->subfield('a') ) == 0 ) { + print "no Dewey number found (082\$a)\r\n" if $marcprint; + warn("no Dewey number found") if $marcprint; + } else { + print "U1 - ", $deweyfield->subfield('a'), " ", $deweyfield->subfield('2'), "\r\n"; } } @@ -693,118 +689,112 @@ sub print_dewey { ## Arguments: field (260) ##******************************************************************** sub print_pubinfo { - my($pubinfofield) = @_; + my ($pubinfofield) = @_; - if (!$pubinfofield) { - print "no publication information found (260/264)\r\n" if $marcprint; - warn("no publication information found") if $marcprint; - } - else { - ## the following information is available in MARC21: - ## $a place -> CY - ## $b publisher -> PB - ## $c date -> PY - ## the corresponding subfields for UNIMARC: - ## $a place -> CY - ## $c publisher -> PB - ## $d date -> PY + if ( !$pubinfofield ) { + print "no publication information found (260/264)\r\n" if $marcprint; + warn("no publication information found") if $marcprint; + } else { + ## the following information is available in MARC21: + ## $a place -> CY + ## $b publisher -> PB + ## $c date -> PY + ## the corresponding subfields for UNIMARC: + ## $a place -> CY + ## $c publisher -> PB + ## $d date -> PY - ## all of them are repeatable. We pool all places into a - ## comma-separated list in CY. We also pool all publishers - ## into a comma-separated list in PB. We break the rule with - ## the date field because this wouldn't make much sense. In - ## this case, we use the first occurrence for PY, the second - ## for Y2, and ignore the rest + ## all of them are repeatable. We pool all places into a + ## comma-separated list in CY. We also pool all publishers + ## into a comma-separated list in PB. We break the rule with + ## the date field because this wouldn't make much sense. In + ## this case, we use the first occurrence for PY, the second + ## for Y2, and ignore the rest - my @pubsubfields = $pubinfofield->subfields(); - my @cities; - my @publishers; - my $pycounter = 0; + my @pubsubfields = $pubinfofield->subfields(); + my @cities; + my @publishers; + my $pycounter = 0; - my $pubsub_place; - my $pubsub_publisher; - my $pubsub_date; + my $pubsub_place; + my $pubsub_publisher; + my $pubsub_date; - my $marcflavour = C4::Context->preference("marcflavour"); - my $intype = lc($marcflavour); - if ($intype eq "unimarc") { - $pubsub_place = "a"; - $pubsub_publisher = "c"; - $pubsub_date = "d"; - } - else { ## assume marc21 - $pubsub_place = "a"; - $pubsub_publisher = "b"; - $pubsub_date = "c"; - } - - ## loop over all subfield list entries - for my $tuple (@pubsubfields) { - ## each tuple consists of the subfield code and the value - if (@$tuple[0] eq $pubsub_place) { - ## strip any trailing crap - $_ = @$tuple[1]; - s% *[,;:/]$%%; - ## pool all occurrences in a list - push (@cities, $_); - } - elsif (@$tuple[0] eq $pubsub_publisher) { - ## strip any trailing crap - $_ = @$tuple[1]; - s% *[,;:/]$%%; - ## pool all occurrences in a list - push (@publishers, $_); - } - elsif (@$tuple[0] eq $pubsub_date) { - ## the dates are free-form, so we want to extract - ## a four-digit year and leave the rest as - ## "other info" - my $protoyear = @$tuple[1]; - print "Year (260\$c): $protoyear\r\n" if $marcprint; + my $marcflavour = C4::Context->preference("marcflavour"); + my $intype = lc($marcflavour); + if ( $intype eq "unimarc" ) { + $pubsub_place = "a"; + $pubsub_publisher = "c"; + $pubsub_date = "d"; + } else { ## assume marc21 + $pubsub_place = "a"; + $pubsub_publisher = "b"; + $pubsub_date = "c"; + } - ## strip any separator chars at the end - $protoyear =~ s% *[\.;:/]*$%%; + ## loop over all subfield list entries + for my $tuple (@pubsubfields) { + ## each tuple consists of the subfield code and the value + if ( @$tuple[0] eq $pubsub_place ) { + ## strip any trailing crap + $_ = @$tuple[1]; + s% *[,;:/]$%%; + ## pool all occurrences in a list + push( @cities, $_ ); + } elsif ( @$tuple[0] eq $pubsub_publisher ) { + ## strip any trailing crap + $_ = @$tuple[1]; + s% *[,;:/]$%%; + ## pool all occurrences in a list + push( @publishers, $_ ); + } elsif ( @$tuple[0] eq $pubsub_date ) { + ## the dates are free-form, so we want to extract + ## a four-digit year and leave the rest as + ## "other info" + my $protoyear = @$tuple[1]; + print "Year (260\$c): $protoyear\r\n" if $marcprint; - ## isolate a four-digit year. We discard anything - ## preceding the year, but keep everything after - ## the year as other info. - $protoyear =~ s%\D*([0-9\-]{4})(.*)%$1///$2%; + ## strip any separator chars at the end + $protoyear =~ s% *[\.;:/]*$%%; - ## check what we've got. If there is no four-digit - ## year, make it up. If digits are replaced by '-', - ## replace those with 0s + ## isolate a four-digit year. We discard anything + ## preceding the year, but keep everything after + ## the year as other info. + $protoyear =~ s%\D*([0-9\-]{4})(.*)%$1///$2%; - if (index($protoyear, "/") == 4) { - ## have year info - ## replace all '-' in the four-digit year - ## by '0' - substr($protoyear,0,4) =~ s!-!0!g; - } - else { - ## have no year info - print "no four-digit year found, use 0000\r\n" if $marcprint; - $protoyear = "0000///$protoyear"; - warn("no four-digit year found, use 0000") if $marcprint; - } + ## check what we've got. If there is no four-digit + ## year, make it up. If digits are replaced by '-', + ## replace those with 0s - if ($pycounter == 0 && length($protoyear)) { - print "PY - $protoyear\r\n"; - } - elsif ($pycounter == 1 && length($_)) { - print "Y2 - $protoyear\r\n"; - } - ## else: discard - } - ## else: discard - } + if ( index( $protoyear, "/" ) == 4 ) { + ## have year info + ## replace all '-' in the four-digit year + ## by '0' + substr( $protoyear, 0, 4 ) =~ s!-!0!g; + } else { + ## have no year info + print "no four-digit year found, use 0000\r\n" if $marcprint; + $protoyear = "0000///$protoyear"; + warn("no four-digit year found, use 0000") if $marcprint; + } - ## now dump the collected CY and PB lists - if (@cities > 0) { - print "CY - ", join(", ", @cities), "\r\n"; - } - if (@publishers > 0) { - print "PB - ", join(", ", @publishers), "\r\n"; - } + if ( $pycounter == 0 && length($protoyear) ) { + print "PY - $protoyear\r\n"; + } elsif ( $pycounter == 1 && length($_) ) { + print "Y2 - $protoyear\r\n"; + } + ## else: discard + } + ## else: discard + } + + ## now dump the collected CY and PB lists + if ( @cities > 0 ) { + print "CY - ", join( ", ", @cities ), "\r\n"; + } + if ( @publishers > 0 ) { + print "PB - ", join( ", ", @publishers ), "\r\n"; + } } } @@ -813,22 +803,30 @@ sub print_pubinfo { ## Arguments: list of fields (6XX) ##******************************************************************** sub get_keywords { - my($fieldname, @keywords) = @_; + my ( $fieldname, @keywords ) = @_; my @kw; ## a list of all possible subfields - my @subfields = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'x', 'y', 'z', '2', '3', '4'); + my @subfields = ( + 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'x', + 'y', 'z', '2', '3', '4' + ); ## loop over all 6XX fields foreach my $kwfield (@keywords) { - if( defined $kwfield ) { + if ( defined $kwfield ) { ## authornames get special treatment - if ($fieldname eq "600") { - my $val = normalize_author($kwfield->subfield('a'), $kwfield->subfield('b'), $kwfield->subfield('c'), $kwfield->indicator('1')); + if ( $fieldname eq "600" ) { + my $val = normalize_author( + $kwfield->subfield('a'), $kwfield->subfield('b'), $kwfield->subfield('c'), + $kwfield->indicator('1') + ); push @kw, $val; - print "Field $kwfield subfield a:", $kwfield->subfield('a'), "\r\nField $kwfield subfield b:", $kwfield->subfield('b'), "\r\nField $kwfield subfield c:", $kwfield->subfield('c'), "\r\n" if $marcprint; - } - else { + print "Field $kwfield subfield a:", $kwfield->subfield('a'), + "\r\nField $kwfield subfield b:", $kwfield->subfield('b'), + "\r\nField $kwfield subfield c:", $kwfield->subfield('c'), "\r\n" + if $marcprint; + } else { ## retrieve all available subfields my @kwsubfields = $kwfield->subfields(); @@ -837,10 +835,10 @@ sub get_keywords { ## loop over all subfields to check foreach my $subfield (@subfields) { ## [0] contains subfield code - if (@$kwtuple[0] eq $subfield) { + if ( @$kwtuple[0] eq $subfield ) { ## [1] contains value, remove trailing separators @$kwtuple[1] =~ s% *[,;.:/]*$%%; - if (length(@$kwtuple[1]) > 0) { + if ( length( @$kwtuple[1] ) > 0 ) { push @kw, @$kwtuple[1]; print "Field $fieldname subfield $subfield:", @$kwtuple[1], "\r\n" if $marcprint; } @@ -862,89 +860,66 @@ sub get_keywords { ## list of fields (5XX) ##******************************************************************** sub pool_subx { - my($aref, $fieldname, @notefields) = @_; + my ( $aref, $fieldname, @notefields ) = @_; ## we use a list that contains the interesting subfields ## for each field # ToDo: this is apparently correct only for marc21 my @subfields; - if ($fieldname eq "500") { - @subfields = ('a'); - } - elsif ($fieldname eq "501") { - @subfields = ('a'); - } - elsif ($fieldname eq "502") { - @subfields = ('a'); - } - elsif ($fieldname eq "504") { - @subfields = ('a', 'b'); - } - elsif ($fieldname eq "505") { - @subfields = ('a', 'g', 'r', 't', 'u'); - } - elsif ($fieldname eq "506") { - @subfields = ('a', 'b', 'c', 'd', 'e'); - } - elsif ($fieldname eq "507") { - @subfields = ('a', 'b'); - } - elsif ($fieldname eq "508") { - @subfields = ('a'); - } - elsif ($fieldname eq "510") { - @subfields = ('a', 'b', 'c', 'x', '3'); - } - elsif ($fieldname eq "511") { - @subfields = ('a'); - } - elsif ($fieldname eq "513") { - @subfields = ('a', 'b'); - } - elsif ($fieldname eq "514") { - @subfields = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'm', 'u', 'z'); - } - elsif ($fieldname eq "515") { - @subfields = ('a'); - } - elsif ($fieldname eq "516") { - @subfields = ('a'); - } - elsif ($fieldname eq "518") { - @subfields = ('a', '3'); - } - elsif ($fieldname eq "521") { - @subfields = ('a', 'b', '3'); - } - elsif ($fieldname eq "522") { - @subfields = ('a'); - } - elsif ($fieldname eq "524") { - @subfields = ('a', '2', '3'); - } - elsif ($fieldname eq "525") { - @subfields = ('a'); - } - elsif ($fieldname eq "526") { - @subfields = ('a', 'b', 'c', 'd', 'i', 'x', 'z', '5'); - } - elsif ($fieldname eq "530") { - @subfields = ('a', 'b', 'c', 'd', 'u', '3'); - } - elsif ($fieldname eq "533") { - @subfields = ('a', 'b', 'c', 'd', 'e', 'f', 'm', 'n', '3'); - } - elsif ($fieldname eq "534") { - @subfields = ('a', 'b', 'c', 'e', 'f', 'k', 'l', 'm', 'n', 'p', 't', 'x', 'z'); - } - elsif ($fieldname eq "535") { - @subfields = ('a', 'b', 'c', 'd', 'g', '3'); + if ( $fieldname eq "500" ) { + @subfields = ('a'); + } elsif ( $fieldname eq "501" ) { + @subfields = ('a'); + } elsif ( $fieldname eq "502" ) { + @subfields = ('a'); + } elsif ( $fieldname eq "504" ) { + @subfields = ( 'a', 'b' ); + } elsif ( $fieldname eq "505" ) { + @subfields = ( 'a', 'g', 'r', 't', 'u' ); + } elsif ( $fieldname eq "506" ) { + @subfields = ( 'a', 'b', 'c', 'd', 'e' ); + } elsif ( $fieldname eq "507" ) { + @subfields = ( 'a', 'b' ); + } elsif ( $fieldname eq "508" ) { + @subfields = ('a'); + } elsif ( $fieldname eq "510" ) { + @subfields = ( 'a', 'b', 'c', 'x', '3' ); + } elsif ( $fieldname eq "511" ) { + @subfields = ('a'); + } elsif ( $fieldname eq "513" ) { + @subfields = ( 'a', 'b' ); + } elsif ( $fieldname eq "514" ) { + @subfields = ( 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'm', 'u', 'z' ); + } elsif ( $fieldname eq "515" ) { + @subfields = ('a'); + } elsif ( $fieldname eq "516" ) { + @subfields = ('a'); + } elsif ( $fieldname eq "518" ) { + @subfields = ( 'a', '3' ); + } elsif ( $fieldname eq "521" ) { + @subfields = ( 'a', 'b', '3' ); + } elsif ( $fieldname eq "522" ) { + @subfields = ('a'); + } elsif ( $fieldname eq "524" ) { + @subfields = ( 'a', '2', '3' ); + } elsif ( $fieldname eq "525" ) { + @subfields = ('a'); + } elsif ( $fieldname eq "526" ) { + @subfields = ( 'a', 'b', 'c', 'd', 'i', 'x', 'z', '5' ); + } elsif ( $fieldname eq "530" ) { + @subfields = ( 'a', 'b', 'c', 'd', 'u', '3' ); + } elsif ( $fieldname eq "533" ) { + @subfields = ( 'a', 'b', 'c', 'd', 'e', 'f', 'm', 'n', '3' ); + } elsif ( $fieldname eq "534" ) { + @subfields = ( 'a', 'b', 'c', 'e', 'f', 'k', 'l', 'm', 'n', 'p', 't', 'x', 'z' ); + } elsif ( $fieldname eq "535" ) { + @subfields = ( 'a', 'b', 'c', 'd', 'g', '3' ); } ## loop over all notefields foreach my $notefield (@notefields) { - if (defined $notefield) { + if ( defined $notefield ) { ## retrieve all available subfield tuples my @notesubfields = $notefield->subfields(); @@ -953,11 +928,11 @@ sub pool_subx { ## loop over all subfields to check foreach my $subfield (@subfields) { ## [0] contains subfield code - if (@$notetuple[0] eq $subfield) { + if ( @$notetuple[0] eq $subfield ) { ## [1] contains value, remove trailing separators print "field $fieldname subfield $subfield: ", @$notetuple[1], "\r\n" if $marcprint; @$notetuple[1] =~ s% *[,;.:/]*$%%; - if (length(@$notetuple[1]) > 0) { + if ( length( @$notetuple[1] ) > 0 ) { ## add to list push @{$aref}, @$notetuple[1]; } @@ -974,11 +949,12 @@ sub pool_subx { ## Arguments: list of fields (520) ##******************************************************************** sub print_abstract { + # ToDo: take care of repeatable subfields - my(@abfields) = @_; + my (@abfields) = @_; ## we check the following subfields - my @subfields = ('a', 'b'); + my @subfields = ( 'a', 'b' ); ## we generate a list for all useful strings my @abstrings; @@ -1002,8 +978,8 @@ sub print_abstract { my $allabs = join "; ", @abstrings; - if (length($allabs) > 0) { - print "N2 - ", $allabs, "\r\n"; + if ( length($allabs) > 0 ) { + print "N2 - ", $allabs, "\r\n"; } } diff --git a/C4/RotatingCollections.pm b/C4/RotatingCollections.pm index abadf85afe..44ebc02e2f 100644 --- a/C4/RotatingCollections.pm +++ b/C4/RotatingCollections.pm @@ -31,7 +31,6 @@ use Try::Tiny qw( catch try ); use vars qw(@ISA @EXPORT); - =head1 NAME C4::RotatingCollections - Functions for managing rotating collections @@ -44,22 +43,22 @@ BEGIN { require Exporter; @ISA = qw( Exporter ); @EXPORT = qw( - CreateCollection - UpdateCollection - DeleteCollection + CreateCollection + UpdateCollection + DeleteCollection - GetItemsInCollection + GetItemsInCollection - GetCollection - GetCollections + GetCollection + GetCollections - AddItemToCollection - RemoveItemFromCollection - TransferCollection + AddItemToCollection + RemoveItemFromCollection + TransferCollection - GetCollectionItemBranches - isItemInAnyCollection - isItemInThisCollection + GetCollectionItemBranches + isItemInAnyCollection + isItemInThisCollection ); } @@ -82,13 +81,13 @@ Creates a new collection sub CreateCollection { my ( $title, $description ) = @_; - my $schema = Koha::Database->new()->schema(); - my $duplicate_titles = $schema->resultset('Collection')->count({ colTitle => $title }); + my $schema = Koha::Database->new()->schema(); + my $duplicate_titles = $schema->resultset('Collection')->count( { colTitle => $title } ); ## Check for all necessary parameters if ( !$title ) { return ( 0, 1, "NO_TITLE" ); - } elsif ( $duplicate_titles ) { + } elsif ($duplicate_titles) { return ( 0, 2, "DUPLICATE_TITLE" ); } @@ -131,7 +130,8 @@ sub UpdateCollection { my ( $colId, $title, $description ) = @_; my $schema = Koha::Database->new()->schema(); - my $duplicate_titles = $schema->resultset('Collection')->count({ colTitle => $title, -not => { colId => $colId } }); + my $duplicate_titles = + $schema->resultset('Collection')->count( { colTitle => $title, -not => { colId => $colId } } ); ## Check for all necessary parameters if ( !$colId ) { @@ -140,7 +140,7 @@ sub UpdateCollection { if ( !$title ) { return ( 0, 2, "NO_TITLE" ); } - if ( $duplicate_titles ) { + if ($duplicate_titles) { return ( 0, 3, "DUPLICATE_TITLE" ); } @@ -156,7 +156,7 @@ sub UpdateCollection { WHERE colId = ?" ); $sth->execute( $title, $description, $colId ) - or return ( 0, 4, $sth->errstr() ); + or return ( 0, 4, $sth->errstr() ); return 1; @@ -335,20 +335,19 @@ sub AddItemToCollection { if ( isItemInThisCollection( $itemnumber, $colId ) ) { return ( 0, 2, "IN_COLLECTION" ); - } - elsif ( isItemInAnyCollection($itemnumber) ) { + } elsif ( isItemInAnyCollection($itemnumber) ) { return ( 0, 3, "IN_COLLECTION_OTHER" ); } my $dbh = C4::Context->dbh; my $sth; - $sth = $dbh->prepare(" + $sth = $dbh->prepare( " INSERT INTO collections_tracking ( colId, itemnumber ) VALUES ( ?, ? ) - "); + " ); $sth->execute( $colId, $itemnumber ) or return ( 0, 3, $sth->errstr() ); return 1; @@ -417,10 +416,10 @@ sub TransferCollection { ## Check for all necessary parameters if ( !$colId ) { - return ( 0, [{ type => 'error', code => 'NO_ID' }] ); + return ( 0, [ { type => 'error', code => 'NO_ID' } ] ); } if ( !$colBranchcode ) { - return ( 0, [{ type => 'error', code => 'NO_BRANCHCODE' }] ); + return ( 0, [ { type => 'error', code => 'NO_BRANCHCODE' } ] ); } my $dbh = C4::Context->dbh; @@ -433,15 +432,17 @@ sub TransferCollection { WHERE colId = ?" ); $sth->execute( $colBranchcode, $colId ) or return 0; - my $to_library = Koha::Libraries->find( $colBranchcode ); + my $to_library = Koha::Libraries->find($colBranchcode); - $sth = $dbh->prepare(q{ + $sth = $dbh->prepare( + q{ SELECT items.itemnumber, items.barcode FROM collections_tracking LEFT JOIN items ON collections_tracking.itemnumber = items.itemnumber LEFT JOIN issues ON items.itemnumber = issues.itemnumber WHERE issues.borrowernumber IS NULL AND collections_tracking.colId = ? - }); + } + ); $sth->execute($colId) or return 0; my $messages; while ( my $item = $sth->fetchrow_hashref ) { @@ -454,8 +455,7 @@ sub TransferCollection { ignore_limits => 0 } ); # Request transfer - } - catch { + } catch { if ( $_->isa('Koha::Exceptions::Item::Transfer::InQueue') ) { my $exception = $_; my $found_transfer = $_->transfer; @@ -471,14 +471,13 @@ sub TransferCollection { } ); # Queue transfer push @{$messages}, - { + { type => 'alert', code => 'enqueued', item => $item_object, found_transfer => $found_transfer - }; - } - else { + }; + } else { my $transfer = $item_object->request_transfer( { to => $to_library, @@ -493,22 +492,20 @@ sub TransferCollection { # we were at the first stage.. then there won't be a datearrived # to calculate against. See bug 35100 } - } - elsif ( $_->isa('Koha::Exceptions::Item::Transfer::Limit') ) { + } elsif ( $_->isa('Koha::Exceptions::Item::Transfer::Limit') ) { push @{$messages}, - { + { type => 'error', code => 'limits', item => $item_object - }; - } - else { + }; + } else { $_->rethrow(); } }; } - return (1, $messages); + return ( 1, $messages ); } =head2 GetCollectionItemBranches @@ -528,7 +525,7 @@ sub GetCollectionItemBranches { my ( $sth, @results ); $sth = $dbh->prepare( -"SELECT holdingbranch, colBranchcode FROM items, collections, collections_tracking + "SELECT holdingbranch, colBranchcode FROM items, collections, collections_tracking WHERE items.itemnumber = collections_tracking.itemnumber AND collections.colId = collections_tracking.colId AND items.itemnumber = ?" @@ -551,9 +548,8 @@ sub isItemInThisCollection { my $dbh = C4::Context->dbh; - my $sth = $dbh->prepare( -"SELECT COUNT(*) as inCollection FROM collections_tracking WHERE itemnumber = ? AND colId = ?" - ); + my $sth = + $dbh->prepare("SELECT COUNT(*) as inCollection FROM collections_tracking WHERE itemnumber = ? AND colId = ?"); $sth->execute( $itemnumber, $colId ) or return (0); my $row = $sth->fetchrow_hashref; @@ -581,8 +577,7 @@ sub isItemInAnyCollection { $itemnumber = $row->{itemnumber}; if ($itemnumber) { return 1; - } - else { + } else { return 0; } } diff --git a/C4/SIP/ILS.pm b/C4/SIP/ILS.pm index 42da8d2252..751cd5906e 100644 --- a/C4/SIP/ILS.pm +++ b/C4/SIP/ILS.pm @@ -48,10 +48,10 @@ my %supports = ( ); sub new { - my ($class, $institution) = @_; + my ( $class, $institution ) = @_; my $type = ref($class) || $class; my $self = {}; - siplog("LOG_DEBUG", "new ILS '%s'", $institution->{id}); + siplog( "LOG_DEBUG", "new ILS '%s'", $institution->{id} ); $self->{institution} = $institution; return bless $self, $type; } @@ -68,7 +68,7 @@ sub find_item { sub institution { my $self = shift; - return $self->{institution}->{id}; # consider making this return the whole institution + return $self->{institution}->{id}; # consider making this return the whole institution } sub institution_id { @@ -77,46 +77,54 @@ sub institution_id { } sub supports { - my ($self, $op) = @_; - return (exists($supports{$op}) && $supports{$op}); + my ( $self, $op ) = @_; + return ( exists( $supports{$op} ) && $supports{$op} ); } sub check_inst_id { - my ($self, $id, $whence) = @_; - if ($id ne $self->{institution}->{id}) { - siplog("LOG_WARNING", "%s: received institution '%s', expected '%s'", $whence, $id, $self->{institution}->{id}); + my ( $self, $id, $whence ) = @_; + if ( $id ne $self->{institution}->{id} ) { + siplog( + "LOG_WARNING", "%s: received institution '%s', expected '%s'", $whence, $id, + $self->{institution}->{id} + ); + # Just an FYI check, we don't expect the user to change location from that in SIPconfig.xml } } sub to_bool { my $bool = shift; + # If it's defined, and matches a true sort of string, or is # a non-zero number, then it's true. - defined($bool) or return; # false - ($bool =~ /true|y|yes/i) and return 1; # true - return ($bool =~ /^\d+$/ and $bool != 0); # true for non-zero numbers, false otherwise + defined($bool) or return; # false + ( $bool =~ /true|y|yes/i ) and return 1; # true + return ( $bool =~ /^\d+$/ and $bool != 0 ); # true for non-zero numbers, false otherwise } sub checkout_ok { my $self = shift; - return (exists($self->{institution}->{policy}->{checkout}) - && to_bool($self->{institution}->{policy}->{checkout})); + return ( exists( $self->{institution}->{policy}->{checkout} ) + && to_bool( $self->{institution}->{policy}->{checkout} ) ); } + sub checkin_ok { my $self = shift; - return (exists($self->{institution}->{policy}->{checkin}) - && to_bool($self->{institution}->{policy}->{checkin})); + return ( exists( $self->{institution}->{policy}->{checkin} ) + && to_bool( $self->{institution}->{policy}->{checkin} ) ); } + sub status_update_ok { my $self = shift; - return (exists($self->{institution}->{policy}->{status_update}) - && to_bool($self->{institution}->{policy}->{status_update})); + return ( exists( $self->{institution}->{policy}->{status_update} ) + && to_bool( $self->{institution}->{policy}->{status_update} ) ); } + sub offline_ok { my $self = shift; - return (exists($self->{institution}->{policy}->{offline}) - && to_bool($self->{institution}->{policy}->{offline})); + return ( exists( $self->{institution}->{policy}->{offline} ) + && to_bool( $self->{institution}->{policy}->{offline} ) ); } # @@ -131,10 +139,11 @@ sub checkout { my ( $self, $patron_id, $item_id, $sc_renew, $fee_ack, $account, $no_block_due_date ) = @_; my ( $patron, $item, $circ ); my @blocked_item_types; - if (defined $account->{blocked_item_types}) { + if ( defined $account->{blocked_item_types} ) { @blocked_item_types = split /\|/, $account->{blocked_item_types}; } $circ = C4::SIP::ILS::Transaction::Checkout->new(); + # BEGIN TRANSACTION $circ->patron( $patron = C4::SIP::ILS::Patron->new($patron_id) ); $circ->item( $item = C4::SIP::ILS::Item->new($item_id) ); @@ -145,11 +154,10 @@ sub checkout { if ( !$patron ) { $circ->screen_msg("Invalid Patron"); - } - elsif ( !$item ) { + } elsif ( !$item ) { $circ->screen_msg("Invalid Item"); - } - elsif ( $no_block_due_date ) { + } elsif ($no_block_due_date) { + # A no block due date means we need check this item out to the patron # regardless if fines, restrictions or any other things that would # typically prevent a patron from checking out. @@ -167,38 +175,35 @@ sub checkout { "LOG_DEBUG", "ILS::Checkout: patron %s has checked out %s via a no block checkout", $patron_id, join( ', ', map { $_->{barcode} } @{ $patron->{items} } ) ); - } - elsif ( !$patron->charge_ok ) { - if ($patron->debarred) { + } elsif ( !$patron->charge_ok ) { + if ( $patron->debarred ) { $circ->screen_msg("Patron debarred"); - } elsif ($patron->expired) { - $circ->screen_msg("Patron expired on " . output_pref({ dt => dt_from_string( $patron->dateexpiry_iso, 'iso' ), dateonly => 1 })); - } elsif ($patron->fine_blocked) { + } elsif ( $patron->expired ) { + $circ->screen_msg( "Patron expired on " + . output_pref( { dt => dt_from_string( $patron->dateexpiry_iso, 'iso' ), dateonly => 1 } ) ); + } elsif ( $patron->fine_blocked ) { my $message = "Patron has fines"; - if ($account->{show_outstanding_amount}) { - my $patron_account = Koha::Account->new( { patron_id => $patron->{borrowernumber} }); - my $balance = $patron_account->balance; + if ( $account->{show_outstanding_amount} ) { + my $patron_account = Koha::Account->new( { patron_id => $patron->{borrowernumber} } ); + my $balance = $patron_account->balance; if ($balance) { - $message .= (" - You owe " . Koha::Number::Price->new( $balance )->format({ with_symbol => 1}) . "."); + $message .= + ( " - You owe " . Koha::Number::Price->new($balance)->format( { with_symbol => 1 } ) . "." ); } } $circ->screen_msg($message); } else { $circ->screen_msg("Patron blocked"); } - } - elsif ( - $item->{borrowernumber} - && !C4::Context->preference('AllowItemsOnLoanCheckoutSIP') - && !_ci_cardnumber_cmp( $item->{borrowernumber}, $patron->borrowernumber ) - ) + } elsif ( $item->{borrowernumber} + && !C4::Context->preference('AllowItemsOnLoanCheckoutSIP') + && !_ci_cardnumber_cmp( $item->{borrowernumber}, $patron->borrowernumber ) ) { $circ->screen_msg("Item checked out to another patron"); - } - elsif (grep { $_ eq $item->{itemtype} } @blocked_item_types) { + } elsif ( grep { $_ eq $item->{itemtype} } @blocked_item_types ) { $circ->screen_msg("Item type cannot be checked out at this checkout location"); - } - else { + } else { + # No block checkouts were handled earlier so there is no need # to bass the no block due date here. $circ->do_checkout($account); @@ -207,19 +212,18 @@ sub checkout { # If the item is already associated with this patron, then # we're renewing it. $circ->renew_ok( $item->{borrowernumber} - && _ci_cardnumber_cmp( $item->{borrowernumber}, $patron->borrowernumber ) ); + && _ci_cardnumber_cmp( $item->{borrowernumber}, $patron->borrowernumber ) ); - $item->{borrowernumber} = $patron_id; - $item->{due_date} = $circ->{due}; + $item->{borrowernumber} = $patron_id; + $item->{due_date} = $circ->{due}; push( @{ $patron->{items} }, { barcode => $item_id } ); $circ->desensitize( !$item->magnetic_media ); siplog( "LOG_DEBUG", "ILS::Checkout: patron %s has checked out %s", - $patron_id, join( ', ', map{ $_->{barcode} } @{ $patron->{items} } ) + $patron_id, join( ', ', map { $_->{barcode} } @{ $patron->{items} } ) ); - } - else { + } else { siplog( "LOG_ERR", "ILS::Checkout Issue failed" ); } } @@ -230,7 +234,8 @@ sub checkout { } sub _ci_cardnumber_cmp { - my ( $s1, $s2) = @_; + my ( $s1, $s2 ) = @_; + # As the database is case insensitive we need to normalize two strings # before comparing them return ( uc($s1) eq uc($s2) ); @@ -239,16 +244,16 @@ sub _ci_cardnumber_cmp { # wrapper which allows above to be called for testing sub test_cardnumber_compare { - my ($self, $str1, $str2) = @_; - return _ci_cardnumber_cmp($str1, $str2); + my ( $self, $str1, $str2 ) = @_; + return _ci_cardnumber_cmp( $str1, $str2 ); } sub checkin { my ( $self, $item_id, $trans_date, $return_date, $current_loc, $item_props, $cancel, $account ) = @_; - my $checked_in_ok = $account->{checked_in_ok}; - my $cv_triggers_alert = $account->{cv_triggers_alert}; - my $holds_block_checkin = $account->{holds_block_checkin}; + my $checked_in_ok = $account->{checked_in_ok}; + my $cv_triggers_alert = $account->{cv_triggers_alert}; + my $holds_block_checkin = $account->{holds_block_checkin}; my ( $patron, $item, $circ ); @@ -260,34 +265,33 @@ sub checkin { my $data; if ($item) { $data = $circ->do_checkin( $current_loc, $return_date, $account ); - } - else { + } else { $circ->alert(1); $circ->alert_type(99); - $circ->ok( 0 ); + $circ->ok(0); $circ->screen_msg('Invalid Item'); return $circ; } - if ( !$circ->ok && $circ->alert_type && $circ->alert_type == 98 ) { # data corruption + if ( !$circ->ok && $circ->alert_type && $circ->alert_type == 98 ) { # data corruption $circ->screen_msg("Checkin failed: data problem"); siplog( "LOG_WARNING", "Problem with issue_id in issues and old_issues; check the about page" ); } elsif ( $data->{messages}->{ResFound} && !$circ->ok && $holds_block_checkin ) { $circ->screen_msg("Item is on hold, please return to circulation desk"); - siplog ("LOG_DEBUG", "C4::SIP::ILS::Checkin - item on hold"); + siplog( "LOG_DEBUG", "C4::SIP::ILS::Checkin - item on hold" ); } elsif ( $data->{messages}->{withdrawn} && !$circ->ok && C4::Context->preference("BlockReturnOfWithdrawnItems") ) { - $circ->screen_msg("Item withdrawn, return not allowed"); - siplog ("LOG_DEBUG", "C4::SIP::ILS::Checkin - item withdrawn"); + $circ->screen_msg("Item withdrawn, return not allowed"); + siplog( "LOG_DEBUG", "C4::SIP::ILS::Checkin - item withdrawn" ); } elsif ( $data->{messages}->{WasLost} && !$circ->ok && C4::Context->preference("BlockReturnOfLostItems") ) { - $circ->screen_msg("Item lost, return not allowed"); - siplog("LOG_DEBUG", "C4::SIP::ILS::Checkin - item lost"); + $circ->screen_msg("Item lost, return not allowed"); + siplog( "LOG_DEBUG", "C4::SIP::ILS::Checkin - item lost" ); } elsif ( !$item->{borrowernumber} ) { - if ( $checked_in_ok ) { # Mark checkin ok although book not checked out - $circ->ok( 1 ); - siplog("LOG_DEBUG", "C4::SIP::ILS::Checkin - using checked_in_ok"); + if ($checked_in_ok) { # Mark checkin ok although book not checked out + $circ->ok(1); + siplog( "LOG_DEBUG", "C4::SIP::ILS::Checkin - using checked_in_ok" ); } else { $circ->screen_msg("Item not checked out"); - siplog("LOG_DEBUG", "C4::SIP::ILS::Checkin - item not checked out"); + siplog( "LOG_DEBUG", "C4::SIP::ILS::Checkin - item not checked out" ); } } elsif ( $circ->ok ) { $circ->patron( $patron = C4::SIP::ILS::Patron->new( { borrowernumber => $item->{borrowernumber} } ) ); @@ -307,19 +311,22 @@ sub checkin { } # Check for overdue fines to display - if ($account->{show_outstanding_amount}) { + if ( $account->{show_outstanding_amount} ) { my $kohaitem = Koha::Items->find( { barcode => $item_id } ); if ($kohaitem) { my $charges = Koha::Account::Lines->search( { borrowernumber => $patron->{borrowernumber}, amountoutstanding => { '>' => 0 }, - debit_type_code => [ 'OVERDUE' ], + debit_type_code => ['OVERDUE'], itemnumber => $kohaitem->itemnumber }, ); if ($charges) { - $message .= "You owe " . Koha::Number::Price->new( $charges->total_outstanding )->format({ with_symbol => 1}) . " for this item."; + $message .= + "You owe " + . Koha::Number::Price->new( $charges->total_outstanding )->format( { with_symbol => 1 } ) + . " for this item."; } } } @@ -327,6 +334,7 @@ sub checkin { $circ->screen_msg($message); } } else { + # Checkin failed: Wrongbranch or withdrawn? # Bug 10748 with pref BlockReturnOfLostItems adds another case to come # here: returning a lost item when the pref is set. @@ -340,27 +348,31 @@ sub checkin { # If the ILS caches patron information, this lets it free # it up sub end_patron_session { - my ($self, $patron_id) = @_; + my ( $self, $patron_id ) = @_; # success?, screen_msg, print_line - return (1, 'Thank you!', ''); + return ( 1, 'Thank you!', '' ); } sub pay_fee { - my ($self, $patron_id, $patron_pwd, $fee_amt, $fee_type, $pay_type, $fee_id, $trans_id, $currency, $is_writeoff, $disallow_overpayment, $register_id) = @_; + my ( + $self, $patron_id, $patron_pwd, $fee_amt, $fee_type, $pay_type, $fee_id, $trans_id, $currency, $is_writeoff, + $disallow_overpayment, $register_id + ) = @_; my $trans = C4::SIP::ILS::Transaction::FeePayment->new(); $trans->transaction_id($trans_id); my $patron; - $trans->patron($patron = C4::SIP::ILS::Patron->new($patron_id)); - if (!$patron) { + $trans->patron( $patron = C4::SIP::ILS::Patron->new($patron_id) ); + if ( !$patron ) { $trans->screen_msg('Invalid patron barcode.'); - return { - status => $trans - }; + return { status => $trans }; } - my $trans_result = $trans->pay( $patron->{borrowernumber}, $fee_amt, $pay_type, $fee_id, $is_writeoff, $disallow_overpayment, $register_id ); + my $trans_result = $trans->pay( + $patron->{borrowernumber}, $fee_amt, $pay_type, $fee_id, $is_writeoff, $disallow_overpayment, + $register_id + ); my $ok = $trans_result->{ok}; $trans->ok($ok); @@ -372,88 +384,92 @@ sub pay_fee { } sub add_hold { - my ($self, $patron_id, $patron_pwd, $item_id, $title_id, - $expiry_date, $pickup_location, $hold_type, $fee_ack) = @_; - my ($patron, $item); + my ( + $self, $patron_id, $patron_pwd, $item_id, $title_id, + $expiry_date, $pickup_location, $hold_type, $fee_ack + ) = @_; + my ( $patron, $item ); - my $trans = C4::SIP::ILS::Transaction::Hold->new(); + my $trans = C4::SIP::ILS::Transaction::Hold->new(); - $patron = C4::SIP::ILS::Patron->new( $patron_id ); + $patron = C4::SIP::ILS::Patron->new($patron_id); if ( !$patron ) { $trans->screen_msg("Invalid patron barcode."); return $trans; } - unless ($item = C4::SIP::ILS::Item->new($item_id || $title_id)) { - $trans->screen_msg("No such item."); - return $trans; - } + unless ( $item = C4::SIP::ILS::Item->new( $item_id || $title_id ) ) { + $trans->screen_msg("No such item."); + return $trans; + } if ( $patron->holds_blocked_by_excessive_fees() ) { $trans->screen_msg("Excessive fees blocking placement of hold."); } - if ($item->fee and $fee_ack ne 'Y') { - $trans->screen_msg = "Fee required to place hold."; - return $trans; + if ( $item->fee and $fee_ack ne 'Y' ) { + $trans->screen_msg = "Fee required to place hold."; + return $trans; } my $hold = { - item_id => $item->id, - patron_id => $patron->id, - expiration_date => $expiry_date, - pickup_location => $pickup_location, - hold_type => $hold_type, + item_id => $item->id, + patron_id => $patron->id, + expiration_date => $expiry_date, + pickup_location => $pickup_location, + hold_type => $hold_type, }; $trans->ok(1); $trans->patron($patron); $trans->item($item); $trans->pickup_location($pickup_location); - $trans->do_hold; + $trans->do_hold; - push(@{$item->hold_queue}, $hold); - push(@{$patron->{hold_items}}, $hold); + push( @{ $item->hold_queue }, $hold ); + push( @{ $patron->{hold_items} }, $hold ); return $trans; } sub cancel_hold { - my ($self, $patron_id, $patron_pwd, $item_id, $title_id) = @_; - my ($patron, $item, $hold); + my ( $self, $patron_id, $patron_pwd, $item_id, $title_id ) = @_; + my ( $patron, $item, $hold ); - my $trans = C4::SIP::ILS::Transaction::Hold->new(); + my $trans = C4::SIP::ILS::Transaction::Hold->new(); - $patron = C4::SIP::ILS::Patron->new( $patron_id ); - if (!$patron) { - $trans->screen_msg("Invalid patron barcode."); - return $trans; + $patron = C4::SIP::ILS::Patron->new($patron_id); + if ( !$patron ) { + $trans->screen_msg("Invalid patron barcode."); + return $trans; } - unless ($item = C4::SIP::ILS::Item->new($item_id || $title_id)) { - $trans->screen_msg("No such item."); - return $trans; + unless ( $item = C4::SIP::ILS::Item->new( $item_id || $title_id ) ) { + $trans->screen_msg("No such item."); + return $trans; } $trans->patron($patron); $trans->item($item); - $trans->drop_hold; - unless ($trans->ok) { - $trans->screen_msg("Error with transaction drop_hold: " . $trans->screen_msg); - return $trans; - } + $trans->drop_hold; + unless ( $trans->ok ) { + $trans->screen_msg( "Error with transaction drop_hold: " . $trans->screen_msg ); + return $trans; + } + # Remove the hold from the patron's record first - $patron->drop_hold($item_id); # different than the transaction drop! + $patron->drop_hold($item_id); # different than the transaction drop! # Now, remove it from the item record. If it was on the patron # record but not on the item record, we'll treat that as success. - foreach my $i (0 .. scalar @{$item->hold_queue}) { - $hold = $item->hold_queue->[$i]; - if ($item->barcode_is_borrowernumber($patron->id, $hold->{borrowernumber})) { - # found it: delete it. - splice @{$item->hold_queue}, $i, 1; - last; # ?? should we keep going, in case there are multiples - } + foreach my $i ( 0 .. scalar @{ $item->hold_queue } ) { + $hold = $item->hold_queue->[$i]; + if ( $item->barcode_is_borrowernumber( $patron->id, $hold->{borrowernumber} ) ) { + + # found it: delete it. + splice @{ $item->hold_queue }, $i, 1; + last; # ?? should we keep going, in case there are multiples + } } $trans->screen_msg("Hold Cancelled."); @@ -461,40 +477,43 @@ sub cancel_hold { return $trans; } - # The patron and item id's can't be altered, but the # date, location, and type can. sub alter_hold { - my ($self, $patron_id, $patron_pwd, $item_id, $title_id, - $expiry_date, $pickup_location, $hold_type, $fee_ack) = @_; - my ($patron, $item); + my ( + $self, $patron_id, $patron_pwd, $item_id, $title_id, + $expiry_date, $pickup_location, $hold_type, $fee_ack + ) = @_; + my ( $patron, $item ); my $hold; my $trans; $trans = C4::SIP::ILS::Transaction::Hold->new(); # BEGIN TRANSACTION - $patron = C4::SIP::ILS::Patron->new( $patron_id ); + $patron = C4::SIP::ILS::Patron->new($patron_id); unless ($patron) { - $trans->screen_msg("Invalid patron barcode: '$patron_id'."); - return $trans; + $trans->screen_msg("Invalid patron barcode: '$patron_id'."); + return $trans; } - foreach my $i (0 .. scalar @{$patron->{hold_items}}) { - $hold = $patron->{hold_items}[$i]; + foreach my $i ( 0 .. scalar @{ $patron->{hold_items} } ) { + $hold = $patron->{hold_items}[$i]; - if ($hold->{item_id} eq $item_id) { - # Found it. So fix it. - $hold->{expiration_date} = $expiry_date if $expiry_date; - $hold->{pickup_location} = $pickup_location if $pickup_location; - $hold->{hold_type} = $hold_type if $hold_type; - $trans->change_hold(); - # $trans->ok(1); - $trans->screen_msg("Hold updated."); - $trans->patron($patron); - $trans->item(C4::SIP::ILS::Item->new( $hold->{item_id})); - last; - } + if ( $hold->{item_id} eq $item_id ) { + + # Found it. So fix it. + $hold->{expiration_date} = $expiry_date if $expiry_date; + $hold->{pickup_location} = $pickup_location if $pickup_location; + $hold->{hold_type} = $hold_type if $hold_type; + $trans->change_hold(); + + # $trans->ok(1); + $trans->screen_msg("Hold updated."); + $trans->patron($patron); + $trans->item( C4::SIP::ILS::Item->new( $hold->{item_id} ) ); + last; + } } # The same hold structure is linked into both the patron's @@ -502,54 +521,58 @@ sub alter_hold { # for the item, so we don't need to search the hold queue for # the item, since it's already been updated by the patron code. - if (!$trans->ok) { - $trans->screen_msg("No such outstanding hold."); + if ( !$trans->ok ) { + $trans->screen_msg("No such outstanding hold."); } return $trans; } sub renew { - my ($self, $patron_id, $patron_pwd, $item_id, $title_id, - $no_block, $nb_due_date, $third_party, - $item_props, $fee_ack) = @_; - my ($patron, $item); + my ( + $self, $patron_id, $patron_pwd, $item_id, $title_id, + $no_block, $nb_due_date, $third_party, + $item_props, $fee_ack + ) = @_; + my ( $patron, $item ); my $trans; $trans = C4::SIP::ILS::Transaction::Renew->new(); - $trans->patron($patron = C4::SIP::ILS::Patron->new( $patron_id )); - if (!$patron) { - $trans->screen_msg("Invalid patron barcode."); - return $trans; - } elsif (!$patron->renew_ok) { - $trans->screen_msg("Renewals not allowed."); - return $trans; + $trans->patron( $patron = C4::SIP::ILS::Patron->new($patron_id) ); + if ( !$patron ) { + $trans->screen_msg("Invalid patron barcode."); + return $trans; + } elsif ( !$patron->renew_ok ) { + $trans->screen_msg("Renewals not allowed."); + return $trans; } - # Previously: renewing a title, rather than an item (sort of) - # This is gross, but in a real ILS it would be better + # Previously: renewing a title, rather than an item (sort of) + # This is gross, but in a real ILS it would be better # if (defined($title_id)) { - # foreach my $i (@{$patron->{items}}) { - # $item = new ILS::Item $i; - # last if ($title_id eq $item->title_id); - # $item = undef; - # } + # foreach my $i (@{$patron->{items}}) { + # $item = new ILS::Item $i; + # last if ($title_id eq $item->title_id); + # $item = undef; + # } # } else { - my $j = 0; - my $count = scalar @{$patron->{items}}; - foreach my $i (@{$patron->{items}}) { - unless (defined $i->{barcode}) { # FIXME: using data instead of objects may violate the abstraction layer - siplog("LOG_ERR", "No barcode for item %s of %s: $item_id", $j+1, $count); - next; - } - siplog("LOG_DEBUG", "checking item %s of %s: $item_id vs. %s", ++$j, $count, $i->{barcode}); - if ($i->{barcode} eq $item_id) { - # We have it checked out - $item = C4::SIP::ILS::Item->new( $item_id ); - last; - } - } + my $j = 0; + my $count = scalar @{ $patron->{items} }; + foreach my $i ( @{ $patron->{items} } ) { + unless ( defined $i->{barcode} ) { # FIXME: using data instead of objects may violate the abstraction layer + siplog( "LOG_ERR", "No barcode for item %s of %s: $item_id", $j + 1, $count ); + next; + } + siplog( "LOG_DEBUG", "checking item %s of %s: $item_id vs. %s", ++$j, $count, $i->{barcode} ); + if ( $i->{barcode} eq $item_id ) { + + # We have it checked out + $item = C4::SIP::ILS::Item->new($item_id); + last; + } + } + # } $trans->item($item); @@ -557,12 +580,12 @@ sub renew { $trans->fee_ack($fee_ack); } - if (!defined($item)) { - $trans->screen_msg("Item not checked out to " . $patron->name); # not checked out to $patron_id + if ( !defined($item) ) { + $trans->screen_msg( "Item not checked out to " . $patron->name ); # not checked out to $patron_id $trans->ok(0); } else { $trans->do_renew(); - if ($trans->renewal_ok()) { + if ( $trans->renewal_ok() ) { $item->{due_date} = $trans->{due}; $trans->desensitize(0); } @@ -572,8 +595,8 @@ sub renew { } sub renew_all { - my ($self, $patron_id, $patron_pwd, $fee_ack) = @_; - my ($patron, $item_id); + my ( $self, $patron_id, $patron_pwd, $fee_ack ) = @_; + my ( $patron, $item_id ); my $trans; $trans = C4::SIP::ILS::Transaction::RenewAll->new(); @@ -581,22 +604,22 @@ sub renew_all { $trans->fee_ack($fee_ack); } - $trans->patron($patron = C4::SIP::ILS::Patron->new( $patron_id )); - if (defined $patron) { - siplog("LOG_DEBUG", "ILS::renew_all: patron '%s': renew_ok: %s", $patron->name, $patron->renew_ok); + $trans->patron( $patron = C4::SIP::ILS::Patron->new($patron_id) ); + if ( defined $patron ) { + siplog( "LOG_DEBUG", "ILS::renew_all: patron '%s': renew_ok: %s", $patron->name, $patron->renew_ok ); } else { - siplog("LOG_DEBUG", "ILS::renew_all: Invalid patron id: '%s'", $patron_id); + siplog( "LOG_DEBUG", "ILS::renew_all: Invalid patron id: '%s'", $patron_id ); } - if (!$patron) { - $trans->screen_msg("Invalid patron barcode."); - return $trans; - } elsif (!$patron->renew_ok) { - $trans->screen_msg("Renewals not allowed."); - return $trans; + if ( !$patron ) { + $trans->screen_msg("Invalid patron barcode."); + return $trans; + } elsif ( !$patron->renew_ok ) { + $trans->screen_msg("Renewals not allowed."); + return $trans; } - $trans->do_renew_all; + $trans->do_renew_all; $trans->ok(1); return $trans; } diff --git a/C4/SIP/ILS/Item.pm b/C4/SIP/ILS/Item.pm index 89bcd82708..69abf8b524 100644 --- a/C4/SIP/ILS/Item.pm +++ b/C4/SIP/ILS/Item.pm @@ -1,6 +1,6 @@ # # ILS::Item.pm -# +# # A Class for hiding the ILS's concept of the item from OpenSIP # @@ -73,24 +73,24 @@ use Koha::TemplateUtils qw( process_tt ); =cut sub new { - my ($class, $item_id) = @_; + my ( $class, $item_id ) = @_; my $type = ref($class) || $class; - my $item = Koha::Items->find( { barcode => barcodedecode( $item_id ) } ); - unless ( $item ) { - siplog("LOG_DEBUG", "new ILS::Item('%s'): not found", $item_id); + my $item = Koha::Items->find( { barcode => barcodedecode($item_id) } ); + unless ($item) { + siplog( "LOG_DEBUG", "new ILS::Item('%s'): not found", $item_id ); warn "new ILS::Item($item_id) : No item '$item_id'."; return; } my $self = $item->unblessed; - $self->{_object} = $item; - $self->{id} = $item->barcode; # to SIP, the barcode IS the id. - if (C4::Context->preference('UseLocationAsAQInSIP')) { + $self->{_object} = $item; + $self->{id} = $item->barcode; # to SIP, the barcode IS the id. + if ( C4::Context->preference('UseLocationAsAQInSIP') ) { $self->{permanent_location} = $item->permanent_location; } else { $self->{permanent_location} = $item->homebranch; } - $self->{collection_code} = $item->ccode; - $self->{call_number} = $item->itemcallnumber; + $self->{collection_code} = $item->ccode; + $self->{call_number} = $item->itemcallnumber; $self->{'shelving_location'} = $item->location; $self->{'permanent_shelving_location'} = $item->permanent_location; @@ -98,7 +98,7 @@ sub new { my $it = $item->effective_itemtype; $self->{itemtype} = $it; - my $itemtype = Koha::Database->new()->schema()->resultset('Itemtype')->find( $it ); + my $itemtype = Koha::Database->new()->schema()->resultset('Itemtype')->find($it); $self->{sip_media_type} = $itemtype->sip_media_type() if $itemtype; # check if its on issue and if so get the borrower @@ -109,16 +109,28 @@ sub new { $self->{borrowernumber} = $patron->borrowernumber; } my $biblio = Koha::Biblios->find( $self->{biblionumber} ); - my $holds = $biblio->current_holds->unblessed; - $self->{hold_queue} = $holds; - $self->{hold_attached} = [( grep { defined $_->{found} and ( $_->{found} eq 'W' or $_->{found} eq 'P' or $_->{found} eq 'T' ) } @{$self->{hold_queue}} )]; - $self->{pending_queue} = [( grep {(! defined $_->{found}) or ( $_->{found} ne 'W' and $_->{found} ne 'P' and $_->{found} ne 'T' ) } @{$self->{hold_queue}} )]; - $self->{title} = $biblio->title; + my $holds = $biblio->current_holds->unblessed; + $self->{hold_queue} = $holds; + $self->{hold_attached} = [ + ( + grep { defined $_->{found} and ( $_->{found} eq 'W' or $_->{found} eq 'P' or $_->{found} eq 'T' ) } + @{ $self->{hold_queue} } + ) + ]; + $self->{pending_queue} = [ + ( + grep { ( !defined $_->{found} ) or ( $_->{found} ne 'W' and $_->{found} ne 'P' and $_->{found} ne 'T' ) } + @{ $self->{hold_queue} } + ) + ]; + $self->{title} = $biblio->title; $self->{author} = $biblio->author; bless $self, $type; - siplog( "LOG_DEBUG", "new ILS::Item('%s'): found with title '%s'", - $item_id, $self->{title} // '' ); + siplog( + "LOG_DEBUG", "new ILS::Item('%s'): found with title '%s'", + $item_id, $self->{title} // '' + ); return $self; } @@ -127,38 +139,41 @@ sub new { # 1 means read/write my %fields = ( - id => 0, - sip_media_type => 0, - sip_item_properties => 0, - magnetic_media => 0, - permanent_location => 0, - current_location => 0, - print_line => 1, - screen_msg => 1, - itemnumber => 0, - biblionumber => 0, - barcode => 0, - onloan => 0, - collection_code => 0, - shelving_location => 0, - permanent_shelving_location => 0, - call_number => 0, - enumchron => 0, - location => 0, - author => 0, - title => 0, - itemtype => 0, + id => 0, + sip_media_type => 0, + sip_item_properties => 0, + magnetic_media => 0, + permanent_location => 0, + current_location => 0, + print_line => 1, + screen_msg => 1, + itemnumber => 0, + biblionumber => 0, + barcode => 0, + onloan => 0, + collection_code => 0, + shelving_location => 0, + permanent_shelving_location => 0, + call_number => 0, + enumchron => 0, + location => 0, + author => 0, + title => 0, + itemtype => 0, ); sub next_hold { my $self = shift; + # use Data::Dumper; warn "next_hold() hold_attached: " . Dumper($self->{hold_attached}); warn "next_hold() pending_queue: " . $self->{pending_queue}; - foreach (@{$self->hold_attached}) { # If this item was taken from the hold shelf, then that reserve still governs - next unless ($_->{itemnumber} and $_->{itemnumber} == $self->{itemnumber}); + foreach ( @{ $self->hold_attached } ) + { # If this item was taken from the hold shelf, then that reserve still governs + next unless ( $_->{itemnumber} and $_->{itemnumber} == $self->{itemnumber} ); return $_; } - if (scalar @{$self->{pending_queue}}) { # Otherwise, if there is at least one hold, the first (best priority) gets it - return $self->{pending_queue}->[0]; + if ( scalar @{ $self->{pending_queue} } ) + { # Otherwise, if there is at least one hold, the first (best priority) gets it + return $self->{pending_queue}->[0]; } return; } @@ -172,12 +187,13 @@ sub hold_patron_id { if ($id) { $self->{hold}->{borrowernumber} = $id; } - if ($self->{hold} ) { + if ( $self->{hold} ) { return $self->{hold}->{borrowernumber}; } return; } + sub hold_patron_name { my ( $self, $template ) = @_; my $borrowernumber = $self->hold_patron_id() or return q{}; @@ -187,38 +203,38 @@ sub hold_patron_name { return process_tt( $template, { patron => $patron } ); } - my $holder = Koha::Patrons->find( $borrowernumber ); + my $holder = Koha::Patrons->find($borrowernumber); unless ($holder) { - siplog("LOG_ERR", "While checking hold, failed to retrieve the patron with borrowernumber '$borrowernumber'"); + siplog( "LOG_ERR", "While checking hold, failed to retrieve the patron with borrowernumber '$borrowernumber'" ); return q{}; } my $email = $holder->email || ''; my $phone = $holder->phone || ''; - my $extra = ($email and $phone) ? " ($email, $phone)" : # both populated, employ comma - ($email or $phone) ? " ($email$phone)" : # only 1 populated, we don't care which: no comma - "" ; # neither populated, empty string + my $extra = ( $email and $phone ) ? " ($email, $phone)" : # both populated, employ comma + ( $email or $phone ) ? " ($email$phone)" : # only 1 populated, we don't care which: no comma + ""; # neither populated, empty string my $name = $holder->firstname ? $holder->firstname . ' ' : ''; $name .= $holder->surname . $extra; return $name; } sub hold_patron_bcode { - my $self = shift; - my $borrowernumber = (@_ ? shift: $self->hold_patron_id()) or return q{}; - my $holder = Koha::Patrons->find( $borrowernumber ); - if ($holder and $holder->cardnumber ) { + my $self = shift; + my $borrowernumber = ( @_ ? shift : $self->hold_patron_id() ) or return q{}; + my $holder = Koha::Patrons->find($borrowernumber); + if ( $holder and $holder->cardnumber ) { return $holder->cardnumber; } return q(); } sub destination_loc { - my $self = shift; + my $self = shift; my $set_loc = shift; if ($set_loc) { $self->{dest_loc} = $set_loc; } - if ($self->{dest_loc} ) { + if ( $self->{dest_loc} ) { return $self->{dest_loc}; } return q{}; @@ -226,32 +242,32 @@ sub destination_loc { our $AUTOLOAD; -sub DESTROY { } # keeps AUTOLOAD from catching inherent DESTROY calls +sub DESTROY { } # keeps AUTOLOAD from catching inherent DESTROY calls sub AUTOLOAD { - my $self = shift; + my $self = shift; my $class = ref($self) or croak "$self is not an object"; - my $name = $AUTOLOAD; + my $name = $AUTOLOAD; $name =~ s/.*://; - unless (exists $fields{$name}) { - croak "Cannot access '$name' field of class '$class'"; + unless ( exists $fields{$name} ) { + croak "Cannot access '$name' field of class '$class'"; } - if (@_) { + if (@_) { $fields{$name} or croak "Field '$name' of class '$class' is READ ONLY."; - return $self->{$name} = shift; - } else { - return $self->{$name}; - } + return $self->{$name} = shift; + } else { + return $self->{$name}; + } } -sub status_update { # FIXME: this looks unimplemented - my ($self, $props) = @_; +sub status_update { # FIXME: this looks unimplemented + my ( $self, $props ) = @_; my $status = C4::SIP::ILS::Transaction->new(); $self->{sip_item_properties} = $props; - $status->{ok} = 1; + $status->{ok} = 1; return $status; } @@ -294,8 +310,9 @@ sub sip_circulation_status { sub sip_security_marker { my $self = shift; - return '02'; # FIXME? 00-other; 01-None; 02-Tattle-Tape Security Strip (3M); 03-Whisper Tape (3M) + return '02'; # FIXME? 00-other; 01-None; 02-Tattle-Tape Security Strip (3M); 03-Whisper Tape (3M) } + sub sip_fee_type { my $self = shift; return '01'; # FIXME? 01-09 enumerated in spec. We just use O1-other/unknown. @@ -305,41 +322,46 @@ sub fee { my $self = shift; return $self->{fee} || 0; } + sub fee_currency { my $self = shift; return $self->{currency} || 'USD'; } + sub owner { my $self = shift; return $self->{homebranch}; } + sub hold_queue { my $self = shift; - (defined $self->{hold_queue}) or return []; + ( defined $self->{hold_queue} ) or return []; return $self->{hold_queue}; } + sub pending_queue { my $self = shift; - (defined $self->{pending_queue}) or return []; + ( defined $self->{pending_queue} ) or return []; return $self->{pending_queue}; } + sub hold_attached { my $self = shift; - (defined $self->{hold_attached}) or return []; + ( defined $self->{hold_attached} ) or return []; return $self->{hold_attached}; } sub hold_queue_position { - my ($self, $patron_id) = @_; - ($self->{hold_queue}) or return 0; - my $i = 0; - foreach (@{$self->{hold_queue}}) { - $i++; - $_->{patron_id} or next; - if ($self->barcode_is_borrowernumber($patron_id, $_->{borrowernumber})) { - return $i; # maybe should return $_->{priority} - } - } + my ( $self, $patron_id ) = @_; + ( $self->{hold_queue} ) or return 0; + my $i = 0; + foreach ( @{ $self->{hold_queue} } ) { + $i++; + $_->{patron_id} or next; + if ( $self->barcode_is_borrowernumber( $patron_id, $_->{borrowernumber} ) ) { + return $i; # maybe should return $_->{priority} + } + } return 0; } @@ -347,15 +369,17 @@ sub due_date { my $self = shift; return $self->{due_date} || 0; } + sub recall_date { my $self = shift; return $self->{recall_date} || 0; } + sub hold_pickup_date { my $self = shift; - my $hold = Koha::Holds->find({ itemnumber => $self->{itemnumber}, found => 'W' }); - if ( $hold ) { + my $hold = Koha::Holds->find( { itemnumber => $self->{itemnumber}, found => 'W' } ); + if ($hold) { return $hold->expirationdate || 0; } @@ -364,7 +388,7 @@ sub hold_pickup_date { # This is a partial check of "availability". It is not supposed to check everything here. # An item is available for a patron if it is: -# 1) checked out to the same patron +# 1) checked out to the same patron # AND no pending (i.e. non-W) hold queue # OR # 2) not checked out @@ -378,32 +402,34 @@ sub hold_pickup_date { # they should not be able to place a hold on an item they already have. sub available { - my ($self, $for_patron) = @_; - my $count = (defined $self->{pending_queue}) ? scalar @{$self->{pending_queue}} : 0; - my $count2 = (defined $self->{hold_attached} ) ? scalar @{$self->{hold_attached} } : 0; - if (defined($self->{borrowernumber})) { - ($self->{borrowernumber} eq $for_patron) or return 0; - return ($count ? 0 : 1); - } else { # not checked out - ($count2) and return $self->barcode_is_borrowernumber($for_patron, $self->{hold_attached}[0]->{borrowernumber}); - } - return 0; + my ( $self, $for_patron ) = @_; + my $count = ( defined $self->{pending_queue} ) ? scalar @{ $self->{pending_queue} } : 0; + my $count2 = ( defined $self->{hold_attached} ) ? scalar @{ $self->{hold_attached} } : 0; + if ( defined( $self->{borrowernumber} ) ) { + ( $self->{borrowernumber} eq $for_patron ) or return 0; + return ( $count ? 0 : 1 ); + } else { # not checked out + ($count2) + and return $self->barcode_is_borrowernumber( $for_patron, $self->{hold_attached}[0]->{borrowernumber} ); + } + return 0; } sub _barcode_to_borrowernumber { my $known = shift; return unless defined $known; my $patron = Koha::Patrons->find( { cardnumber => $known } ) or return; - return $patron->borrowernumber + return $patron->borrowernumber; } + sub barcode_is_borrowernumber { # because hold_queue only has borrowernumber... - my $self = shift; + my $self = shift; my $barcode = shift; - my $number = shift or return; # can't be zero - return unless defined $barcode; # might be 0 or 000 or 000000 + my $number = shift or return; # can't be zero + return unless defined $barcode; # might be 0 or 000 or 000000 my $converted = _barcode_to_borrowernumber($barcode); return unless $converted; - return ($number == $converted); + return ( $number == $converted ); } =head2 build_additional_item_fields_string @@ -420,12 +446,12 @@ sub build_additional_item_fields_string { if ( $server->{account}->{item_field} ) { my @fields_to_send = - ref $server->{account}->{item_field} eq "ARRAY" - ? @{ $server->{account}->{item_field} } - : ( $server->{account}->{item_field} ); + ref $server->{account}->{item_field} eq "ARRAY" + ? @{ $server->{account}->{item_field} } + : ( $server->{account}->{item_field} ); - foreach my $f ( @fields_to_send ) { - my $code = $f->{code}; + foreach my $f (@fields_to_send) { + my $code = $f->{code}; my $value = $self->{object}->$code; $string .= add_field( $f->{field}, $value ); } @@ -437,11 +463,11 @@ sub build_additional_item_fields_string { ? @{ $server->{account}->{custom_item_field} } : $server->{account}->{custom_item_field}; - foreach my $custom_field ( @custom_fields ) { + foreach my $custom_field (@custom_fields) { my $field = $custom_field->{field}; return q{} unless defined $field; - my $template = $custom_field->{template}; - my $formatted = $self->format( $template ); + my $template = $custom_field->{template}; + my $formatted = $self->format($template); my $substring = maybe_add( $field, $formatted, $server ); $string .= $substring; } @@ -461,7 +487,6 @@ sub build_custom_field_string { my $string = q{}; - return $string; } diff --git a/C4/SIP/ILS/Patron.pm b/C4/SIP/ILS/Patron.pm index 19412ebac1..4e5b39ecf2 100644 --- a/C4/SIP/ILS/Patron.pm +++ b/C4/SIP/ILS/Patron.pm @@ -1,6 +1,6 @@ # # ILS::Patron.pm -# +# # A Class for hiding the ILS's concept of the patron from the OpenSIP # system # @@ -30,7 +30,7 @@ use Koha::Checkouts; use Koha::TemplateUtils qw( process_tt ); use Koha::Patron::Messages; use Koha::DateUtils qw(dt_from_string output_pref); -use Date::Calc qw/Today Date_to_Days/; +use Date::Calc qw/Today Date_to_Days/; our $kp; # koha patron @@ -39,7 +39,7 @@ our $kp; # koha patron =cut sub new { - my ($class, $patron_id) = @_; + my ( $class, $patron_id ) = @_; my $type = ref($class) || $class; my $self; @@ -58,17 +58,17 @@ sub new { } unless ($patron) { - siplog("LOG_DEBUG", "new ILS::Patron(%s): no such patron", $patron_id); + siplog( "LOG_DEBUG", "new ILS::Patron(%s): no such patron", $patron_id ); return; } $kp = $patron->unblessed; - my $pw = $kp->{password}; - my $flags = C4::Members::patronflags( $kp ); - my $debarred = $patron->is_debarred; + my $pw = $kp->{password}; + my $flags = C4::Members::patronflags($kp); + my $debarred = $patron->is_debarred; siplog( "LOG_DEBUG", "Debarred = %s : ", ( $debarred || 'undef' ) ); # Do we need more debug info here? my $expired = 0; if ( $kp->{'dateexpiry'} && C4::Context->preference('NotifyBorrowerDeparture') ) { - my ( $today_year, $today_month, $today_day ) = Today(); + my ( $today_year, $today_month, $today_day ) = Today(); my ( $warning_year, $warning_month, $warning_day ) = split /-/, $kp->{'dateexpiry'}; my $days_to_expiry = Date_to_Days( $warning_year, $warning_month, $warning_day ) - Date_to_Days( $today_year, $today_month, $today_day ); @@ -92,10 +92,10 @@ sub new { } } my %ilspatron; - my $adr = _get_address($kp); - my $dob = $kp->{dateofbirth}; - $dob and $dob =~ s/-//g; # YYYYMMDD - my $dexpiry = $kp->{dateexpiry}; + my $adr = _get_address($kp); + my $dob = $kp->{dateofbirth}; + $dob and $dob =~ s/-//g; # YYYYMMDD + my $dexpiry = $kp->{dateexpiry}; $dexpiry and $dexpiry =~ s/-//g; # YYYYMMDD # Get fines and add fines for guarantees (depends on preference NoIssuesChargeGuarantees) @@ -107,7 +107,7 @@ sub new { $patron_charge_limits->{NoIssuesChargeGuarantorsWithGuarantees}->{limit}; my $noissueschargeguarantees = $patron_charge_limits->{NoIssuesChargeGuarantees}->{limit}; - my $fines_msg = ""; + my $fines_msg = ""; my $fine_blocked = 0; if ( $patron_charge_limits->{noissuescharge}->{overlimit} ) { $fine_blocked = 1; @@ -127,69 +127,70 @@ sub new { # Get currency 3 chars max my $currency = substr Koha::Acquisition::Currencies->get_active->currency, 0, 3; - my $circ_blocked =( C4::Context->preference('OverduesBlockCirc') ne "noblock" && defined $flags->{ODUES}->{itemlist} ) ? 1 : 0; + my $circ_blocked = + ( C4::Context->preference('OverduesBlockCirc') ne "noblock" && defined $flags->{ODUES}->{itemlist} ) ? 1 : 0; { - no warnings; # any of these $kp->{fields} being concat'd could be undef - %ilspatron = ( - name => $kp->{firstname} . " " . $kp->{surname}, - id => $kp->{cardnumber}, # to SIP, the id is the BARCODE, not userid - password => $pw, - ptype => $kp->{categorycode}, # 'A'dult. Whatever. - dateexpiry => $dexpiry, - dateexpiry_iso => $kp->{dateexpiry}, - birthdate => $dob, - birthdate_iso => $kp->{dateofbirth}, - branchcode => $kp->{branchcode}, - library_name => "", # only populated if needed, cached here - borrowernumber => $kp->{borrowernumber}, - address => $adr, - home_phone => $kp->{phone}, - email_addr => $kp->{email}, - charge_ok => ( !$debarred && !$expired && !$fine_blocked && !$circ_blocked), - renew_ok => ( !$debarred && !$expired && !$fine_blocked), - recall_ok => ( !$debarred && !$expired && !$fine_blocked), - hold_ok => ( !$debarred && !$expired && !$fine_blocked), - card_lost => ( $kp->{lost} || $kp->{gonenoaddress} || $flags->{LOST} ), - claims_returned => 0, - fines => $personal_fines_amount, - fees => 0, # currently not distinct from fines - recall_overdue => 0, - items_billed => 0, - screen_msg => 'Greetings from Koha. ' . $kp->{opacnote} . $fines_msg, - print_line => '', - items => [], - hold_items => $flags->{WAITING}->{itemlist}, - overdue_items => $flags->{ODUES}->{itemlist}, - too_many_overdue => $circ_blocked, - fine_items => [], - recall_items => [], - unavail_holds => [], - inet => ( !$debarred && !$expired ), - debarred => $debarred, - expired => $expired, - fine_blocked => $fine_blocked, - fee_limit => $fee_limit, - userid => $kp->{userid}, - currency => $currency, - ); + no warnings; # any of these $kp->{fields} being concat'd could be undef + %ilspatron = ( + name => $kp->{firstname} . " " . $kp->{surname}, + id => $kp->{cardnumber}, # to SIP, the id is the BARCODE, not userid + password => $pw, + ptype => $kp->{categorycode}, # 'A'dult. Whatever. + dateexpiry => $dexpiry, + dateexpiry_iso => $kp->{dateexpiry}, + birthdate => $dob, + birthdate_iso => $kp->{dateofbirth}, + branchcode => $kp->{branchcode}, + library_name => "", # only populated if needed, cached here + borrowernumber => $kp->{borrowernumber}, + address => $adr, + home_phone => $kp->{phone}, + email_addr => $kp->{email}, + charge_ok => ( !$debarred && !$expired && !$fine_blocked && !$circ_blocked ), + renew_ok => ( !$debarred && !$expired && !$fine_blocked ), + recall_ok => ( !$debarred && !$expired && !$fine_blocked ), + hold_ok => ( !$debarred && !$expired && !$fine_blocked ), + card_lost => ( $kp->{lost} || $kp->{gonenoaddress} || $flags->{LOST} ), + claims_returned => 0, + fines => $personal_fines_amount, + fees => 0, # currently not distinct from fines + recall_overdue => 0, + items_billed => 0, + screen_msg => 'Greetings from Koha. ' . $kp->{opacnote} . $fines_msg, + print_line => '', + items => [], + hold_items => $flags->{WAITING}->{itemlist}, + overdue_items => $flags->{ODUES}->{itemlist}, + too_many_overdue => $circ_blocked, + fine_items => [], + recall_items => [], + unavail_holds => [], + inet => ( !$debarred && !$expired ), + debarred => $debarred, + expired => $expired, + fine_blocked => $fine_blocked, + fee_limit => $fee_limit, + userid => $kp->{userid}, + currency => $currency, + ); } if ( $patron->is_debarred and $patron->debarredcomment ) { $ilspatron{screen_msg} .= " -- " . $patron->debarredcomment; } - if ( $circ_blocked ) { + if ($circ_blocked) { $ilspatron{screen_msg} .= " -- " . "Patron has overdues"; } for (qw(EXPIRED CHARGES CREDITS GNA LOST NOTES)) { - ($flags->{$_}) or next; - if ($_ ne 'NOTES' and $flags->{$_}->{message}) { - $ilspatron{screen_msg} .= " -- " . $flags->{$_}->{message}; # show all but internal NOTES + ( $flags->{$_} ) or next; + if ( $_ ne 'NOTES' and $flags->{$_}->{message} ) { + $ilspatron{screen_msg} .= " -- " . $flags->{$_}->{message}; # show all but internal NOTES } - if ($flags->{$_}->{noissues}) { + if ( $flags->{$_}->{noissues} ) { foreach my $toggle (qw(charge_ok renew_ok recall_ok hold_ok inet)) { - $ilspatron{$toggle} = 0; # if we get noissues, disable everything + $ilspatron{$toggle} = 0; # if we get noissues, disable everything } } } @@ -213,7 +214,7 @@ sub new { } # FIXME: populate recall_items - $ilspatron{unavail_holds} = _get_outstanding_holds($kp->{borrowernumber}); + $ilspatron{unavail_holds} = _get_outstanding_holds( $kp->{borrowernumber} ); my $pending_checkouts = $patron->pending_checkouts; my @barcodes; @@ -223,64 +224,65 @@ sub new { $ilspatron{items} = \@barcodes; $self = \%ilspatron; - siplog("LOG_DEBUG", "new ILS::Patron(%s): found patron '%s'", $patron_id,$self->{id}); + siplog( "LOG_DEBUG", "new ILS::Patron(%s): found patron '%s'", $patron_id, $self->{id} ); bless $self, $type; return $self; } - # 0 means read-only # 1 means read/write my %fields = ( - id => 0, - borrowernumber => 0, - name => 0, - address => 0, - email_addr => 0, - home_phone => 0, - birthdate => 0, - birthdate_iso => 0, - dateexpiry => 0, - dateexpiry_iso => 0, - debarred => 0, - fine_blocked => 0, - ptype => 0, - charge_ok => 0, # for patron_status[0] (inverted) - renew_ok => 0, # for patron_status[1] (inverted) - recall_ok => 0, # for patron_status[2] (inverted) - hold_ok => 0, # for patron_status[3] (inverted) - card_lost => 0, # for patron_status[4] - recall_overdue => 0, - currency => 1, - fee_limit => 0, - screen_msg => 1, - print_line => 1, - too_many_charged => 0, # for patron_status[5] - too_many_overdue => 0, # for patron_status[6] - too_many_renewal => 0, # for patron_status[7] - too_many_claim_return => 0, # for patron_status[8] -# excessive_fines => 0, # for patron_status[10] -# excessive_fees => 0, # for patron_status[11] - recall_overdue => 0, # for patron_status[12] - too_many_billed => 0, # for patron_status[13] - inet => 0, # EnvisionWare extension + id => 0, + borrowernumber => 0, + name => 0, + address => 0, + email_addr => 0, + home_phone => 0, + birthdate => 0, + birthdate_iso => 0, + dateexpiry => 0, + dateexpiry_iso => 0, + debarred => 0, + fine_blocked => 0, + ptype => 0, + charge_ok => 0, # for patron_status[0] (inverted) + renew_ok => 0, # for patron_status[1] (inverted) + recall_ok => 0, # for patron_status[2] (inverted) + hold_ok => 0, # for patron_status[3] (inverted) + card_lost => 0, # for patron_status[4] + recall_overdue => 0, + currency => 1, + fee_limit => 0, + screen_msg => 1, + print_line => 1, + too_many_charged => 0, # for patron_status[5] + too_many_overdue => 0, # for patron_status[6] + too_many_renewal => 0, # for patron_status[7] + too_many_claim_return => 0, # for patron_status[8] + + # excessive_fines => 0, # for patron_status[10] + # excessive_fees => 0, # for patron_status[11] + recall_overdue => 0, # for patron_status[12] + too_many_billed => 0, # for patron_status[13] + inet => 0, # EnvisionWare extension ); our $AUTOLOAD; sub DESTROY { + # be cool. needed for AUTOLOAD(?) } sub AUTOLOAD { - my $self = shift; + my $self = shift; my $class = ref($self) or croak "$self is not an object"; - my $name = $AUTOLOAD; + my $name = $AUTOLOAD; $name =~ s/.*://; - unless (exists $fields{$name}) { + unless ( exists $fields{$name} ) { croak "Cannot access '$name' field of class '$class'"; } @@ -320,7 +322,7 @@ sub check_password { return $pwd eq q{} unless $self->{password}; my $ret = 0; - ($ret) = checkpw( $self->{userid}, $pwd, undef, undef, 1 ); # userid, query, type, no_set_userenv + ($ret) = checkpw( $self->{userid}, $pwd, undef, undef, 1 ); # userid, query, type, no_set_userenv return $ret; } @@ -335,9 +337,12 @@ This method checks if number of checkouts of lost items exceeds a threshold (def sub too_many_lost { my ( $self, $server ) = @_; my $too_many_lost = 0; - if( $server && $server->{account} && ( my $lost_block_checkout = $server->{account}->{lost_block_checkout} )) { + if ( $server && $server->{account} && ( my $lost_block_checkout = $server->{account}->{lost_block_checkout} ) ) { my $lost_block_checkout_value = $server->{account}->{lost_block_checkout_value} // 1; - my $lost_checkouts = Koha::Checkouts->search({ borrowernumber => $self->borrowernumber, 'itemlost' => { '>=', $lost_block_checkout_value } }, { join => 'item'} )->count; + my $lost_checkouts = Koha::Checkouts->search( + { borrowernumber => $self->borrowernumber, 'itemlost' => { '>=', $lost_block_checkout_value } }, + { join => 'item' } + )->count; $too_many_lost = $lost_checkouts >= $lost_block_checkout; } return $too_many_lost; @@ -358,7 +363,7 @@ sub fines_amount { sub language { my $self = shift; - return $self->{language} || '000'; # Unspecified + return $self->{language} || '000'; # Unspecified } sub expired { @@ -369,17 +374,17 @@ sub expired { # # remove the hold on item item_id from my hold queue. # return true if I was holding the item, false otherwise. -# +# sub drop_hold { - my ($self, $item_id) = @_; + my ( $self, $item_id ) = @_; return if !$item_id; my $result = 0; foreach (qw(hold_items unavail_holds)) { $self->{$_} or next; - for (my $i = 0; $i < scalar @{$self->{$_}}; $i++) { + for ( my $i = 0 ; $i < scalar @{ $self->{$_} } ; $i++ ) { my $held_item = $self->{$_}[$i]->{barcode} or next; - if ($held_item eq $item_id) { - splice @{$self->{$_}}, $i, 1; + if ( $held_item eq $item_id ) { + splice @{ $self->{$_} }, $i, 1; $result++; } } @@ -393,25 +398,23 @@ sub drop_hold { sub x_items { my $self = shift; my $array_var = shift or return; - my ($start, $end) = @_; + my ( $start, $end ) = @_; my $item_list = []; - if ($self->{$array_var}) { + if ( $self->{$array_var} ) { - if ($start && $start > 1) { + if ( $start && $start > 1 ) { --$start; - } - else { + } else { $start = 0; } - if ( $end && $end < @{$self->{$array_var}} ) { - --$end; - } - else { - $end = @{$self->{$array_var}}; + if ( $end && $end < @{ $self->{$array_var} } ) { + --$end; + } else { + $end = @{ $self->{$array_var} }; --$end; } - @{$item_list} = @{$self->{$array_var}}[ $start .. $end ]; + @{$item_list} = @{ $self->{$array_var} }[ $start .. $end ]; } return $item_list; @@ -421,10 +424,10 @@ sub x_items { # List of outstanding holds placed # sub hold_items { - my $self = shift; - my $item_arr = $self->x_items('hold_items', @_); - foreach my $item (@{$item_arr}) { - my $item_obj = Koha::Items->find($item->{itemnumber}); + my $self = shift; + my $item_arr = $self->x_items( 'hold_items', @_ ); + foreach my $item ( @{$item_arr} ) { + my $item_obj = Koha::Items->find( $item->{itemnumber} ); $item->{barcode} = $item_obj ? $item_obj->barcode : undef; } return $item_arr; @@ -432,12 +435,14 @@ sub hold_items { sub overdue_items { my $self = shift; - return $self->x_items('overdue_items', @_); + return $self->x_items( 'overdue_items', @_ ); } + sub charged_items { my $self = shift; - return $self->x_items('items', @_); + return $self->x_items( 'items', @_ ); } + sub fine_items { require Koha::Database; @@ -448,21 +453,18 @@ sub fine_items { my $end = shift; my $server = shift; - my @fees = - Koha::Database->new()->schema()->resultset('Accountline')->search( + my @fees = Koha::Database->new()->schema()->resultset('Accountline')->search( { borrowernumber => $self->{borrowernumber}, amountoutstanding => { '>' => '0' }, } - ); + ); $start = $start ? $start - 1 : 0; $end = $end ? $end - 1 : scalar @fees - 1; - my $av_field_template = - $server ? $server->{account}->{av_field_template} : undef; - $av_field_template ||= -"[% accountline.description %] [% accountline.amountoutstanding | format('%.2f') %]"; + my $av_field_template = $server ? $server->{account}->{av_field_template} : undef; + $av_field_template ||= "[% accountline.description %] [% accountline.amountoutstanding | format('%.2f') %]"; my @return_values; for ( my $i = $start ; $i <= $end ; $i++ ) { @@ -480,32 +482,37 @@ sub fine_items { sub recall_items { my $self = shift; - return $self->x_items('recall_items', @_); + return $self->x_items( 'recall_items', @_ ); } + sub unavail_holds { my $self = shift; - return $self->x_items('unavail_holds', @_); + return $self->x_items( 'unavail_holds', @_ ); } sub block { - my ($self, $card_retained, $blocked_card_msg) = @_; - foreach my $field ('charge_ok', 'renew_ok', 'recall_ok', 'hold_ok', 'inet') { + my ( $self, $card_retained, $blocked_card_msg ) = @_; + foreach my $field ( 'charge_ok', 'renew_ok', 'recall_ok', 'hold_ok', 'inet' ) { $self->{$field} = 0; } - $self->{screen_msg} = "Block feature not implemented"; # $blocked_card_msg || "Card Blocked. Please contact library staff"; - # TODO: not really affecting patron record + $self->{screen_msg} = + "Block feature not implemented"; # $blocked_card_msg || "Card Blocked. Please contact library staff"; + # TODO: not really affecting patron record return $self; } sub enable { my $self = shift; - foreach my $field ('charge_ok', 'renew_ok', 'recall_ok', 'hold_ok', 'inet') { + foreach my $field ( 'charge_ok', 'renew_ok', 'recall_ok', 'hold_ok', 'inet' ) { $self->{$field} = 1; } - siplog("LOG_DEBUG", "Patron(%s)->enable: charge: %s, renew:%s, recall:%s, hold:%s", - $self->{id}, $self->{charge_ok}, $self->{renew_ok}, - $self->{recall_ok}, $self->{hold_ok}); - $self->{screen_msg} = "Enable feature not implemented."; # "All privileges restored."; # TODO: not really affecting patron record + siplog( + "LOG_DEBUG", "Patron(%s)->enable: charge: %s, renew:%s, recall:%s, hold:%s", + $self->{id}, $self->{charge_ok}, $self->{renew_ok}, + $self->{recall_ok}, $self->{hold_ok} + ); + $self->{screen_msg} = + "Enable feature not implemented."; # "All privileges restored."; # TODO: not really affecting patron record return $self; } @@ -516,23 +523,22 @@ sub inet_privileges { sub excessive_fees { my $self = shift; - return ($self->fee_amount and $self->fee_amount > $self->fee_limit); + return ( $self->fee_amount and $self->fee_amount > $self->fee_limit ); } sub excessive_fines { my $self = shift; - return $self->excessive_fees; # excessive_fines is the same thing as excessive_fees for Koha + return $self->excessive_fees; # excessive_fines is the same thing as excessive_fees for Koha } sub holds_blocked_by_excessive_fees { my $self = shift; - return ( $self->fee_amount - && $self->fee_amount > C4::Context->preference("maxoutstanding") ); + return ( $self->fee_amount && $self->fee_amount > C4::Context->preference("maxoutstanding") ); } - + sub library_name { my $self = shift; - unless ($self->{library_name}) { + unless ( $self->{library_name} ) { my $library = Koha::Libraries->find( $self->{branchcode} ); $self->{library_name} = $library ? $library->branchname : ''; } @@ -556,14 +562,12 @@ sub _get_address { my $patron = shift; my $address = $patron->{streetnumber} || q{}; - for my $field (qw( roaddetails address address2 city state zipcode country)) - { + for my $field (qw( roaddetails address address2 city state zipcode country)) { next unless $patron->{$field}; if ($address) { $address .= q{ }; $address .= $patron->{$field}; - } - else { + } else { $address .= $patron->{$field}; } } @@ -573,15 +577,15 @@ sub _get_address { sub _get_outstanding_holds { my $borrowernumber = shift; - my $patron = Koha::Patrons->find( $borrowernumber ); - my $holds = $patron->holds->search( { -or => [ { found => undef }, { found => { '!=' => 'W' } } ] } ); + my $patron = Koha::Patrons->find($borrowernumber); + my $holds = $patron->holds->search( { -or => [ { found => undef }, { found => { '!=' => 'W' } } ] } ); my @holds; while ( my $hold = $holds->next ) { my $item; - if ($hold->itemnumber) { + if ( $hold->itemnumber ) { $item = $hold->item; - } - else { + } else { + # We need to return a barcode for the biblio so the client # can request the biblio info my $items = $hold->biblio->items; @@ -609,11 +613,11 @@ sub build_patron_attributes_string { my $string = q{}; if ( $server->{account}->{patron_attribute} ) { my @attributes_to_send = - ref $server->{account}->{patron_attribute} eq "ARRAY" - ? @{ $server->{account}->{patron_attribute} } - : ( $server->{account}->{patron_attribute} ); + ref $server->{account}->{patron_attribute} eq "ARRAY" + ? @{ $server->{account}->{patron_attribute} } + : ( $server->{account}->{patron_attribute} ); - foreach my $a ( @attributes_to_send ) { + foreach my $a (@attributes_to_send) { my @attributes = Koha::Patron::Attributes->search( { borrowernumber => $self->{borrowernumber}, @@ -621,7 +625,7 @@ sub build_patron_attributes_string { } )->as_list; - foreach my $attribute ( @attributes ) { + foreach my $attribute (@attributes) { my $value = $attribute->attribute(); $string .= add_field( $a->{field}, $value ); } @@ -631,7 +635,6 @@ sub build_patron_attributes_string { return $string; } - =head2 build_custom_field_string This method builds the part of the sip message for custom patron fields as defined in the sip config @@ -648,8 +651,9 @@ sub build_custom_field_string { ref $server->{account}->{custom_patron_field} eq "ARRAY" ? @{ $server->{account}->{custom_patron_field} } : $server->{account}->{custom_patron_field}; - foreach my $custom_field ( @custom_fields ) { - $string .= maybe_add( $custom_field->{field}, $self->format( $custom_field->{template} ) ) if defined $custom_field->{field}; + foreach my $custom_field (@custom_fields) { + $string .= maybe_add( $custom_field->{field}, $self->format( $custom_field->{template} ) ) + if defined $custom_field->{field}; } } return $string; diff --git a/C4/SIP/ILS/Transaction.pm b/C4/SIP/ILS/Transaction.pm index fade710a04..859f470a30 100644 --- a/C4/SIP/ILS/Transaction.pm +++ b/C4/SIP/ILS/Transaction.pm @@ -12,69 +12,68 @@ use Koha::DateUtils qw( dt_from_string ); use Koha::Checkouts; my %fields = ( - ok => 0, - patron => undef, - item => undef, - desensitize => 0, - alert => '', - transaction_id=> undef, - sip_fee_type => '01', # Other/Unknown - fee_amount => undef, - sip_currency => 'USD', # FIXME: why hardcoded? - screen_msg => '', - print_line => '', - fee_ack => 'N', + ok => 0, + patron => undef, + item => undef, + desensitize => 0, + alert => '', + transaction_id => undef, + sip_fee_type => '01', # Other/Unknown + fee_amount => undef, + sip_currency => 'USD', # FIXME: why hardcoded? + screen_msg => '', + print_line => '', + fee_ack => 'N', ); our $AUTOLOAD; sub new { - my $class = shift; - my $self = { - _permitted => \%fields, - %fields, - }; - return bless $self, $class; + my $class = shift; + my $self = { + _permitted => \%fields, + %fields, + }; + return bless $self, $class; } sub duedatefromissue { - my ($self, $iss, $itemnum) = @_; + my ( $self, $iss, $itemnum ) = @_; my $due_dt; - if (defined $iss ) { + if ( defined $iss ) { $due_dt = dt_from_string( $iss->date_due() ); - } # renew from AddIssue ?? + } # renew from AddIssue ?? else { # need to reread the issue to get due date $iss = Koha::Checkouts->find( { itemnumber => $itemnum } ); - if ($iss && $iss->date_due ) { + if ( $iss && $iss->date_due ) { $due_dt = dt_from_string( $iss->date_due, 'sql' ); } } return $due_dt; } - - sub DESTROY { + # be cool } sub AUTOLOAD { - my $self = shift; + my $self = shift; my $class = ref($self) or croak "$self is not an object"; - my $name = $AUTOLOAD; + my $name = $AUTOLOAD; $name =~ s/.*://; - unless (exists $self->{_permitted}->{$name}) { - croak "Can't access '$name' field of class '$class'"; + unless ( exists $self->{_permitted}->{$name} ) { + croak "Can't access '$name' field of class '$class'"; } - if (@_) { - return $self->{$name} = shift; - } else { - return $self->{$name}; - } + if (@_) { + return $self->{$name} = shift; + } else { + return $self->{$name}; + } } 1; diff --git a/C4/SIP/ILS/Transaction/Checkin.pm b/C4/SIP/ILS/Transaction/Checkin.pm index 0ddbaa8f21..4c7d84a6d9 100644 --- a/C4/SIP/ILS/Transaction/Checkin.pm +++ b/C4/SIP/ILS/Transaction/Checkin.pm @@ -12,21 +12,22 @@ use strict; use C4::SIP::ILS::Transaction; use C4::Circulation qw( AddReturn LostItem ); -use C4::Items qw( ModItemTransfer ); -use C4::Reserves qw( ModReserve ModReserveAffect CheckReserves ); +use C4::Items qw( ModItemTransfer ); +use C4::Reserves qw( ModReserve ModReserveAffect CheckReserves ); use Koha::DateUtils qw( dt_from_string ); use Koha::Items; use parent qw(C4::SIP::ILS::Transaction); my %fields = ( - magnetic => 0, - sort_bin => undef, - collection_code => undef, + magnetic => 0, + sort_bin => undef, + collection_code => undef, + # 3M extensions: call_number => undef, destination_loc => undef, - alert_type => undef, # 00,01,02,03,04 or 99 + alert_type => undef, # 00,01,02,03,04 or 99 hold_patron_id => undef, hold_patron_name => "", hold => undef, @@ -34,44 +35,40 @@ my %fields = ( sub new { my $class = shift; - my $self = $class->SUPER::new(); # start with an ILS::Transaction object + my $self = $class->SUPER::new(); # start with an ILS::Transaction object - foreach (keys %fields) { + foreach ( keys %fields ) { $self->{_permitted}->{$_} = $fields{$_}; # overlaying _permitted } - @{$self}{keys %fields} = values %fields; # copying defaults into object + @{$self}{ keys %fields } = values %fields; # copying defaults into object return bless $self, $class; } sub do_checkin { - my $self = shift; - my $branch = shift; + my $self = shift; + my $branch = shift; my $return_date = shift; - my $account = shift; + my $account = shift; my $checked_in_ok = $account->{checked_in_ok}; my $cv_triggers_alert = $account->{cv_triggers_alert}; my $holds_block_checkin = $account->{holds_block_checkin}; my $holds_get_captured = $account->{holds_get_captured} // 1; - if (!$branch) { + if ( !$branch ) { $branch = 'SIP2'; } my $barcode = $self->{item}->id; - if ( $return_date ) { - $return_date = substr( $return_date, 0, 4 ) - . '-' - . substr( $return_date, 4, 2 ) - . '-' - . substr( $return_date, 6, 2 ) - . q{ } - . substr( $return_date, 12, 2 ) - . ':' - . substr( $return_date, 14, 2 ) - . ':' - . substr( $return_date, 16, 2 ); + if ($return_date) { + $return_date = + substr( $return_date, 0, 4 ) . '-' + . substr( $return_date, 4, 2 ) . '-' + . substr( $return_date, 6, 2 ) . q{ } + . substr( $return_date, 12, 2 ) . ':' + . substr( $return_date, 14, 2 ) . ':' + . substr( $return_date, 16, 2 ); $return_date = dt_from_string($return_date); } @@ -84,24 +81,23 @@ sub do_checkin { && defined($item) && $item->materials ) { - $human_required = 1; + $human_required = 1; $messages->{additional_materials} = 1; } my $reserved; - my $lookahead = C4::Context->preference('ConfirmFutureHolds'); #number of days to look for future holds + my $lookahead = C4::Context->preference('ConfirmFutureHolds'); #number of days to look for future holds my ($resfound) = $item->withdrawn ? q{} : CheckReserves( $item, $lookahead ); - if ( $resfound eq "Reserved") { + if ( $resfound eq "Reserved" ) { $reserved = 1; } my $checkin_blocked_by_holds = $holds_block_checkin && $reserved; - ( $return, $messages, $issue, $borrower ) = - AddReturn( $barcode, $branch, undef, $return_date ) - unless $human_required || $checkin_blocked_by_holds; + ( $return, $messages, $issue, $borrower ) = AddReturn( $barcode, $branch, undef, $return_date ) + unless $human_required || $checkin_blocked_by_holds; - if ( $checked_in_ok ) { + if ($checked_in_ok) { delete $messages->{ItemLocationUpdated}; delete $messages->{NotIssued}; delete $messages->{LocalUse}; @@ -111,43 +107,43 @@ sub do_checkin { # biblionumber, biblioitemnumber, itemnumber # borrowernumber, reservedate, branchcode # cancellationdate, found, reservenotes, priority, timestamp - if ($messages->{additional_materials}) { + if ( $messages->{additional_materials} ) { $self->alert_type('99'); } - if( $messages->{DataCorrupted} ) { + if ( $messages->{DataCorrupted} ) { $self->alert_type('98'); } - if ($messages->{BadBarcode}) { + if ( $messages->{BadBarcode} ) { $self->alert_type('99'); } - if ($messages->{withdrawn}) { + if ( $messages->{withdrawn} ) { $self->alert_type('99'); } - if ($messages->{WasLost}) { + if ( $messages->{WasLost} ) { $self->alert_type('99') if C4::Context->preference("BlockReturnOfLostItems"); } - if ($messages->{Wrongbranch}) { - $self->{item}->destination_loc($messages->{Wrongbranch}->{Rightbranch}); - $self->alert_type('04'); # send to other branch + if ( $messages->{Wrongbranch} ) { + $self->{item}->destination_loc( $messages->{Wrongbranch}->{Rightbranch} ); + $self->alert_type('04'); # send to other branch } - if ($messages->{WrongTransfer}) { - $self->{item}->destination_loc($messages->{WrongTransfer}); - $self->alert_type('04'); # send to other branch + if ( $messages->{WrongTransfer} ) { + $self->{item}->destination_loc( $messages->{WrongTransfer} ); + $self->alert_type('04'); # send to other branch } - if ($messages->{NeedsTransfer}) { - $self->{item}->destination_loc($messages->{NeedsTransfer}); - $self->alert_type('04'); # send to other branch + if ( $messages->{NeedsTransfer} ) { + $self->{item}->destination_loc( $messages->{NeedsTransfer} ); + $self->alert_type('04'); # send to other branch } - if ($messages->{WasTransfered}) { # set into transit so tell unit - $self->{item}->destination_loc($item->homebranch); - $self->alert_type('04'); # send to other branch + if ( $messages->{WasTransfered} ) { # set into transit so tell unit + $self->{item}->destination_loc( $item->homebranch ); + $self->alert_type('04'); # send to other branch } - if ($messages->{ResFound} || $checkin_blocked_by_holds ) { + if ( $messages->{ResFound} || $checkin_blocked_by_holds ) { if ($checkin_blocked_by_holds) { $self->alert_type('99'); $return = 0; - } elsif ($branch eq $messages->{ResFound}->{branchcode}) { - $self->hold($messages->{ResFound}); + } elsif ( $branch eq $messages->{ResFound}->{branchcode} ) { + $self->hold( $messages->{ResFound} ); $self->alert_type('01'); ModReserveAffect( $messages->{ResFound}->{itemnumber}, @@ -156,25 +152,30 @@ sub do_checkin { ) if $holds_get_captured; } else { - $self->hold($messages->{ResFound}); + $self->hold( $messages->{ResFound} ); $self->alert_type('02'); if ($holds_get_captured) { - ModReserveAffect( $item->itemnumber, + ModReserveAffect( + $item->itemnumber, $messages->{ResFound}->{borrowernumber}, - 1, $messages->{ResFound}->{reserve_id} ); - ModItemTransfer( $item->itemnumber, $branch, - $messages->{ResFound}->{branchcode}, 'Reserve', ); + 1, $messages->{ResFound}->{reserve_id} + ); + ModItemTransfer( + $item->itemnumber, $branch, + $messages->{ResFound}->{branchcode}, 'Reserve', + ); } } $self->{item}->hold_patron_id( $messages->{ResFound}->{borrowernumber} ); $self->{item}->destination_loc( $messages->{ResFound}->{branchcode} ); } + # ignoring messages: NotIssued, WasTransfered if ($cv_triggers_alert) { - $self->alert( defined $self->alert_type ); # Overwrites existing alert value, should set to 0 if there is no alert type - } - else { + $self->alert( defined $self->alert_type ) + ; # Overwrites existing alert value, should set to 0 if there is no alert type + } else { $self->alert( !$return || defined $self->alert_type ); } @@ -188,21 +189,21 @@ sub do_checkin { } sub resensitize { - my $self = shift; - unless ($self->{item}) { - warn "resensitize(): no item found in object to resensitize"; - return; - } - return !$self->{item}->magnetic_media; + my $self = shift; + unless ( $self->{item} ) { + warn "resensitize(): no item found in object to resensitize"; + return; + } + return !$self->{item}->magnetic_media; } sub patron_id { - my $self = shift; - unless ($self->{patron}) { - warn "patron_id(): no patron found in object"; - return; - } - return $self->{patron}->id; + my $self = shift; + unless ( $self->{patron} ) { + warn "patron_id(): no patron found in object"; + return; + } + return $self->{patron}->id; } =head1 _get_sort_bin @@ -266,7 +267,7 @@ sub _get_sort_bin { # Iterate over the mapping. The first hit wins. my $rule = 0; - RULE: foreach my $line (@lines) { +RULE: foreach my $line (@lines) { # Skip empty lines and comments next if ( $line =~ /^\s*($|#)/ ); diff --git a/C4/SIP/ILS/Transaction/Checkout.pm b/C4/SIP/ILS/Transaction/Checkout.pm index b27fcbe4ff..b3e9a4d6d7 100644 --- a/C4/SIP/ILS/Transaction/Checkout.pm +++ b/C4/SIP/ILS/Transaction/Checkout.pm @@ -7,7 +7,7 @@ package C4::SIP::ILS::Transaction::Checkout; use warnings; use strict; -use POSIX qw(strftime); +use POSIX qw(strftime); use C4::SIP::Sip qw( siplog ); use Data::Dumper; use CGI qw ( -utf8 ); @@ -24,47 +24,47 @@ use parent qw(C4::SIP::ILS::Transaction); # Most fields are handled by the Transaction superclass my %fields = ( - security_inhibit => 0, - due => undef, - renew_ok => 0, - ); + security_inhibit => 0, + due => undef, + renew_ok => 0, +); sub new { - my $class = shift;; - my $self = $class->SUPER::new(); - foreach my $element (keys %fields) { + my $class = shift; + my $self = $class->SUPER::new(); + foreach my $element ( keys %fields ) { $self->{_permitted}->{$element} = $fields{$element}; } - @{$self}{keys %fields} = values %fields; + @{$self}{ keys %fields } = values %fields; return bless $self, $class; } sub do_checkout { - my $self = shift; - my $account = shift; - my $no_block_due_date = shift; - siplog( 'LOG_DEBUG', "ILS::Transaction::Checkout performing checkout..." ); - my $shelf = $self->{item}->hold_attached; - my $barcode = $self->{item}->id; - my $patron = Koha::Patrons->find( $self->{patron}->{borrowernumber} ); - my $overridden_duedate; # usually passed as undef to AddIssue - my $prevcheckout_block_checkout = $account->{prevcheckout_block_checkout}; - my $allow_additional_materials_checkout = $account->{allow_additional_materials_checkout}; - my ( $issuingimpossible, $needsconfirmation, $messages ) = _can_we_issue( $patron, $barcode, 0 ); + my $self = shift; + my $account = shift; + my $no_block_due_date = shift; + siplog( 'LOG_DEBUG', "ILS::Transaction::Checkout performing checkout..." ); + my $shelf = $self->{item}->hold_attached; + my $barcode = $self->{item}->id; + my $patron = Koha::Patrons->find( $self->{patron}->{borrowernumber} ); + my $overridden_duedate; # usually passed as undef to AddIssue + my $prevcheckout_block_checkout = $account->{prevcheckout_block_checkout}; + my $allow_additional_materials_checkout = $account->{allow_additional_materials_checkout}; + my ( $issuingimpossible, $needsconfirmation, $messages ) = _can_we_issue( $patron, $barcode, 0 ); - if ( $no_block_due_date ) { - my $year = substr($no_block_due_date,0,4); - my $month = substr($no_block_due_date,4,2); - my $day = substr($no_block_due_date,6,2); - my $hour = substr($no_block_due_date,12,2); - my $minute = substr($no_block_due_date,14,2); - my $second = substr($no_block_due_date,16,2); + if ($no_block_due_date) { + my $year = substr( $no_block_due_date, 0, 4 ); + my $month = substr( $no_block_due_date, 4, 2 ); + my $day = substr( $no_block_due_date, 6, 2 ); + my $hour = substr( $no_block_due_date, 12, 2 ); + my $minute = substr( $no_block_due_date, 14, 2 ); + my $second = substr( $no_block_due_date, 16, 2 ); my $iso = "$year-$month-$day $hour:$minute:$second"; $no_block_due_date = dt_from_string( $iso, "iso" ); } - my $noerror=1; # If set to zero we block the issue + my $noerror = 1; # If set to zero we block the issue if ( keys %{$issuingimpossible} ) { foreach ( keys %{$issuingimpossible} ) { @@ -136,28 +136,31 @@ sub do_checkout { } } my $itemnumber = $self->{item}->{itemnumber}; - my ($fee, undef) = GetIssuingCharges($itemnumber, $patron->borrowernumber); + my ( $fee, undef ) = GetIssuingCharges( $itemnumber, $patron->borrowernumber ); if ( $fee > 0 ) { $self->{sip_fee_type} = '06'; - $self->{fee_amount} = sprintf '%.2f', $fee; - if ($self->{fee_ack} eq 'N' ) { + $self->{fee_amount} = sprintf '%.2f', $fee; + if ( $self->{fee_ack} eq 'N' ) { $noerror = 0; } } if ( $noerror == 0 && !$no_block_due_date ) { - $self->ok(0); - return $self; - } + $self->ok(0); + return $self; + } - if ( $no_block_due_date ) { + if ($no_block_due_date) { $overridden_duedate = $no_block_due_date; - ProcessOfflineIssue({ - cardnumber => $patron->cardnumber, - barcode => $barcode, - timestamp => $no_block_due_date, - }); + ProcessOfflineIssue( + { + cardnumber => $patron->cardnumber, + barcode => $barcode, + timestamp => $no_block_due_date, + } + ); } else { + # can issue my $recall_id; foreach ( keys %{$messages} ) { @@ -177,7 +180,7 @@ sub _can_we_issue { my ( $patron, $barcode, $pref ) = @_; my ( $issuingimpossible, $needsconfirmation, $alerts, $messages ) = - CanBookBeIssued( $patron, $barcode, undef, 0, $pref ); + CanBookBeIssued( $patron, $barcode, undef, 0, $pref ); for my $href ( $issuingimpossible, $needsconfirmation ) { # some data is returned using lc keys we only diff --git a/C4/SIP/ILS/Transaction/FeePayment.pm b/C4/SIP/ILS/Transaction/FeePayment.pm index 2e5b3364b5..fc596351a7 100644 --- a/C4/SIP/ILS/Transaction/FeePayment.pm +++ b/C4/SIP/ILS/Transaction/FeePayment.pm @@ -37,7 +37,7 @@ sub new { $self->{_permitted}->{$_} = $fields{$_}; # overlaying _permitted } - @{$self}{ keys %fields } = values %fields; # copying defaults into object + @{$self}{ keys %fields } = values %fields; # copying defaults into object return bless $self, $class; } @@ -70,13 +70,10 @@ sub pay { if ($fee_id) { my $fee = Koha::Account::Lines->find($fee_id); - if ( $fee ) { + if ($fee) { $pay_options->{lines} = [$fee]; - } - else { - return { - ok => 0 - }; + } else { + return { ok => 0 }; } } @@ -85,14 +82,12 @@ sub pay { my $error; try { $pay_response = $account->pay($pay_options); - } - catch { + } catch { $ok = 0; if ( ref($_) =~ /^Koha::Exceptions/ ) { $error = $_->description; - } - else { + } else { $_->rethrow; } }; diff --git a/C4/SIP/ILS/Transaction/Hold.pm b/C4/SIP/ILS/Transaction/Hold.pm index b3dae13860..20a4d0f77a 100644 --- a/C4/SIP/ILS/Transaction/Hold.pm +++ b/C4/SIP/ILS/Transaction/Hold.pm @@ -15,35 +15,35 @@ use Koha::Items; use parent qw(C4::SIP::ILS::Transaction); my %fields = ( - expiration_date => 0, - pickup_location => undef, - constraint_type => undef, + expiration_date => 0, + pickup_location => undef, + constraint_type => undef, ); sub new { - my $class = shift; - my $self = $class->SUPER::new(); - foreach my $element (keys %fields) { - $self->{_permitted}->{$element} = $fields{$element}; - } - @{$self}{keys %fields} = values %fields; - return bless $self, $class; + my $class = shift; + my $self = $class->SUPER::new(); + foreach my $element ( keys %fields ) { + $self->{_permitted}->{$element} = $fields{$element}; + } + @{$self}{ keys %fields } = values %fields; + return bless $self, $class; } sub queue_position { my $self = shift; - return $self->item->hold_queue_position($self->patron->id); + return $self->item->hold_queue_position( $self->patron->id ); } sub do_hold { - my $self = shift; + my $self = shift; my $patron = Koha::Patrons->find( $self->{patron}->borrowernumber ); - unless ( $patron ) { + unless ($patron) { $self->screen_msg('do_hold called with undefined patron'); $self->ok(0); return $self; } - my $item = Koha::Items->find({ barcode => $self->{item}->id }); + my $item = Koha::Items->find( { barcode => $self->{item}->id } ); unless ($item) { $self->screen_msg( 'No biblio record matches barcode "' . $self->{item}->id . '".' ); $self->ok(0); @@ -55,15 +55,15 @@ sub do_hold { $self->ok(0); return $self; } - unless ( $item->can_be_transferred( { to => Koha::Libraries->find( $branch ) } ) ) { + unless ( $item->can_be_transferred( { to => Koha::Libraries->find($branch) } ) ) { $self->screen_msg('Item cannot be transferred.'); $self->ok(0); return $self; } - my $canReserve = CanItemBeReserved($patron, $item, $branch); - if ($canReserve->{status} eq 'OK') { - my $priority = C4::Reserves::CalculatePriority($item->biblionumber); + my $canReserve = CanItemBeReserved( $patron, $item, $branch ); + if ( $canReserve->{status} eq 'OK' ) { + my $priority = C4::Reserves::CalculatePriority( $item->biblionumber ); AddReserve( { priority => $priority, @@ -82,7 +82,7 @@ sub do_hold { } sub drop_hold { - my $self = shift; + my $self = shift; my $patron = Koha::Patrons->find( $self->{patron}->borrowernumber ); unless ($patron) { $self->screen_msg('drop_hold called with undefined patron'); @@ -90,41 +90,42 @@ sub drop_hold { return $self; } - my $item = Koha::Items->find({ barcode => $self->{item}->id }); - my $holds = $item->holds->search({ borrowernumber => $patron->borrowernumber }); + my $item = Koha::Items->find( { barcode => $self->{item}->id } ); + my $holds = $item->holds->search( { borrowernumber => $patron->borrowernumber } ); return $self unless $holds->count; $holds->next->cancel; - $self->ok(1); - return $self; + $self->ok(1); + return $self; } sub change_hold { - my $self = shift; + my $self = shift; my $patron = Koha::Patrons->find( $self->{patron}->borrowernumber ); unless ($patron) { $self->screen_msg('change_hold called with undefined patron'); $self->ok(0); return $self; } - my $item = Koha::Items->find({ barcode => $self->{item}->id }); + my $item = Koha::Items->find( { barcode => $self->{item}->id } ); unless ($item) { - $self->screen_msg('No biblio record matches barcode "' . $self->{item}->id . '".'); - $self->ok(0); - return $self; - } - my $branch = ($self->pickup_location || $self->{patron}->branchcode); - unless ($branch) { - $self->screen_msg('No branch specified (or found w/ patron).'); - $self->ok(0); - return $self; - } - ModReserve({ biblionumber => $item->biblionumber, borrowernumber => $patron->borrowernumber, branchcode => $branch }); + $self->screen_msg( 'No biblio record matches barcode "' . $self->{item}->id . '".' ); + $self->ok(0); + return $self; + } + my $branch = ( $self->pickup_location || $self->{patron}->branchcode ); + unless ($branch) { + $self->screen_msg('No branch specified (or found w/ patron).'); + $self->ok(0); + return $self; + } + ModReserve( + { biblionumber => $item->biblionumber, borrowernumber => $patron->borrowernumber, branchcode => $branch } ); - $self->ok(1); - return $self; + $self->ok(1); + return $self; } 1; diff --git a/C4/SIP/ILS/Transaction/Renew.pm b/C4/SIP/ILS/Transaction/Renew.pm index 939f4abd11..d20148d83b 100644 --- a/C4/SIP/ILS/Transaction/Renew.pm +++ b/C4/SIP/ILS/Transaction/Renew.pm @@ -20,35 +20,35 @@ my %fields = ( sub new { my $class = shift; - my $self = $class->SUPER::new(); + my $self = $class->SUPER::new(); - foreach my $element (keys %fields) { + foreach my $element ( keys %fields ) { $self->{_permitted}->{$element} = $fields{$element}; } - @{$self}{keys %fields} = values %fields; # overkill? + @{$self}{ keys %fields } = values %fields; # overkill? return bless $self, $class; } -sub do_renew_for { - my $self = shift; - my $patron = shift; - my $checkout = Koha::Checkouts->find({ itemnumber => $self->{item}->{itemnumber} }); - my ($renewokay,$renewerror) = CanBookBeRenewed($patron, $checkout); - if ($renewokay) { # ok so far check charges - my ($fee, undef) = GetIssuingCharges($self->{item}->{itemnumber}, $self->{patron}->{borrowernumber}); - if ($fee > 0) { +sub do_renew_for { + my $self = shift; + my $patron = shift; + my $checkout = Koha::Checkouts->find( { itemnumber => $self->{item}->{itemnumber} } ); + my ( $renewokay, $renewerror ) = CanBookBeRenewed( $patron, $checkout ); + if ($renewokay) { # ok so far check charges + my ( $fee, undef ) = GetIssuingCharges( $self->{item}->{itemnumber}, $self->{patron}->{borrowernumber} ); + if ( $fee > 0 ) { $self->{sip_fee_type} = '06'; - $self->{fee_amount} = sprintf '%.2f',$fee; - if ($self->{fee_ack} eq 'N') { + $self->{fee_amount} = sprintf '%.2f', $fee; + if ( $self->{fee_ack} eq 'N' ) { $renewokay = 0; } } } - if ($renewokay){ + if ($renewokay) { my $issue = AddIssue( $patron, $self->{item}->id, undef, 0 ); - $self->{due} = $self->duedatefromissue($issue, $self->{item}->{itemnumber}); + $self->{due} = $self->duedatefromissue( $issue, $self->{item}->{itemnumber} ); $self->renewal_ok(1); } else { $renewerror =~ s/on_reserve/Item unavailable due to outstanding holds/; @@ -66,9 +66,9 @@ sub do_renew_for { sub do_renew { my $self = shift; - siplog('LOG_DEBUG', "ILS::Transaction::Renew performing renewal..."); + siplog( 'LOG_DEBUG', "ILS::Transaction::Renew performing renewal..." ); my $patron = Koha::Patrons->find( $self->{patron}->borrowernumber ); - $patron or return; # FIXME we should log that + $patron or return; # FIXME we should log that return $self->do_renew_for($patron); } diff --git a/C4/SIP/ILS/Transaction/RenewAll.pm b/C4/SIP/ILS/Transaction/RenewAll.pm index ef75ae11ef..2c4dbaf6d8 100644 --- a/C4/SIP/ILS/Transaction/RenewAll.pm +++ b/C4/SIP/ILS/Transaction/RenewAll.pm @@ -32,10 +32,10 @@ sub new { } sub do_renew_all { - my $self = shift; - siplog('LOG_DEBUG', "ILS::Transaction::RenewAll performing renewals..."); + my $self = shift; + siplog( 'LOG_DEBUG', "ILS::Transaction::RenewAll performing renewals..." ); my $patron = Koha::Patrons->find( $self->{patron}->{borrowernumber} ); - my $all_ok = 1; + my $all_ok = 1; $self->{renewed} = []; $self->{unrenewed} = []; foreach my $itemx ( @{ $self->{patron}->{items} } ) { @@ -58,8 +58,7 @@ sub do_renew_all { if ( $self->renewal_ok ) { $item->{due_date} = $self->{due}; push @{ $self->{renewed} }, $item_id; - } - else { + } else { push @{ $self->{unrenewed} }, $item_id; } $self->screen_msg(q{}); # clear indiv message diff --git a/C4/SIP/SIPServer.pm b/C4/SIP/SIPServer.pm index 96c1809fbe..608f664c43 100644 --- a/C4/SIP/SIPServer.pm +++ b/C4/SIP/SIPServer.pm @@ -8,17 +8,17 @@ use FindBin qw($Bin); use lib "$Bin"; use Net::Server::PreFork; use IO::Socket::INET; -use Socket qw(:DEFAULT :crlf TCP_KEEPIDLE TCP_KEEPINTVL IPPROTO_TCP); +use Socket qw(:DEFAULT :crlf TCP_KEEPIDLE TCP_KEEPINTVL IPPROTO_TCP); use Scalar::Util qw(blessed); require UNIVERSAL::require; use C4::Context; -use C4::SIP::Sip qw(siplog); +use C4::SIP::Sip qw(siplog); use C4::SIP::Sip::Constants qw(:all); use C4::SIP::Sip::Configuration; use C4::SIP::Sip::Checksum qw(checksum verify_cksum); -use C4::SIP::Sip::MsgType qw( handle login_core ); -use C4::SIP::Logger qw(set_logger); +use C4::SIP::Sip::MsgType qw( handle login_core ); +use C4::SIP::Logger qw(set_logger); use Koha::Caches; use Koha::Logger; @@ -28,15 +28,14 @@ tie *STDERR, "C4::SIP::Trapper"; use base qw(Net::Server::PreFork); -use constant LOG_SIP => "local6"; # Local alias for the logging facility - +use constant LOG_SIP => "local6"; # Local alias for the logging facility set_logger( Koha::Logger->get( { interface => 'sip' } ) ); # # Main # not really, since package SIPServer # -# FIXME: Is this a module or a script? +# FIXME: Is this a module or a script? # A script with no MAIN namespace? # A module that takes command line args? @@ -57,7 +56,7 @@ my @parms; # # Ports to bind # -foreach my $svc (keys %{$config->{listeners}}) { +foreach my $svc ( keys %{ $config->{listeners} } ) { push @parms, "port=" . $svc; } @@ -70,25 +69,25 @@ foreach my $svc (keys %{$config->{listeners}}) { # # The IDENT is determined by config file 'server-params' arguments - # # Server Management: set parameters for the Net::Server::PreFork # module. The module silently ignores parameters that it doesn't # recognize, and complains about invalid values for parameters # that it does. # -if (defined($config->{'server-params'})) { - while (my ($key, $val) = each %{$config->{'server-params'}}) { +if ( defined( $config->{'server-params'} ) ) { + while ( my ( $key, $val ) = each %{ $config->{'server-params'} } ) { push @parms, $key . '=' . $val; } } + # Add user and group to prevent warn from Net::Server. push @parms, 'user=' . $>; push @parms, 'group=' . $>; # # This is the main event. -__PACKAGE__ ->run(@parms); +__PACKAGE__->run(@parms); # # Server @@ -220,7 +219,7 @@ sub post_accept_hook { sub process_request { my $self = shift; my $service; - my ($sockaddr, $port, $proto); + my ( $sockaddr, $port, $proto ); my $transport; $self->{config} = $config; @@ -228,8 +227,8 @@ sub process_request { # Flushing L1 to make sure the request will be processed using the correct data Koha::Caches->flush_L1_caches(); - $self->{account} = undef; # Clear out the account from the last request, it may be different - $self->{logger} = set_logger( Koha::Logger->get( { interface => 'sip' } ) ); + $self->{account} = undef; # Clear out the account from the last request, it may be different + $self->{logger} = set_logger( Koha::Logger->get( { interface => 'sip' } ) ); # Flush previous MDCs to prevent accidentally leaking incorrect MDC-entries Koha::Logger->clear_mdc(); @@ -238,26 +237,29 @@ sub process_request { # Check if socket connection is IPv6 before resolving address my $family = Socket::sockaddr_family($sockname); - if ($family == AF_INET6) { - ($port, $sockaddr) = sockaddr_in6($sockname); - $sockaddr = Socket::inet_ntop(AF_INET6, $sockaddr); + if ( $family == AF_INET6 ) { + ( $port, $sockaddr ) = sockaddr_in6($sockname); + $sockaddr = Socket::inet_ntop( AF_INET6, $sockaddr ); } else { - ($port, $sockaddr) = sockaddr_in($sockname); - $sockaddr = inet_ntoa($sockaddr); + ( $port, $sockaddr ) = sockaddr_in($sockname); + $sockaddr = inet_ntoa($sockaddr); } $proto = $self->{server}->{client}->NS_proto(); - $self->{service} = $config->find_service($sockaddr, $port, $proto); + $self->{service} = $config->find_service( $sockaddr, $port, $proto ); - if (!defined($self->{service})) { - siplog("LOG_ERR", "process_request: Unknown recognized server connection: %s:%s/%s", $sockaddr, $port, $proto); + if ( !defined( $self->{service} ) ) { + siplog( + "LOG_ERR", "process_request: Unknown recognized server connection: %s:%s/%s", $sockaddr, $port, + $proto + ); die "process_request: Bad server connection"; } - $transport = $transports{$self->{service}->{transport}}; + $transport = $transports{ $self->{service}->{transport} }; - if (!defined($transport)) { - siplog("LOG_WARNING", "Unknown transport '%s', dropping", $service->{transport}); + if ( !defined($transport) ) { + siplog( "LOG_WARNING", "Unknown transport '%s', dropping", $service->{transport} ); return; } else { &$transport($self); @@ -273,29 +275,32 @@ sub raw_transport { my $self = shift; my $input; my $service = $self->{service}; + # If using Net::Server::PreFork you may already have account set from a previous session # Ensure you dont - if ($self->{account}) { + if ( $self->{account} ) { delete $self->{account}; } # Timeout the while loop if we get stuck in it # In practice it should only iterate once but be prepared local $SIG{ALRM} = sub { die 'raw transport Timed Out!' }; - my $timeout = $self->get_timeout({ transport => 1 }); - siplog('LOG_DEBUG', "raw_transport: timeout is $timeout"); + my $timeout = $self->get_timeout( { transport => 1 } ); + siplog( 'LOG_DEBUG', "raw_transport: timeout is $timeout" ); alarm $timeout; - while (!$self->{account}) { + while ( !$self->{account} ) { $input = read_request(); - if (!$input) { + if ( !$input ) { + # EOF on the socket - siplog("LOG_INFO", "raw_transport: shutting down: EOF during login"); + siplog( "LOG_INFO", "raw_transport: shutting down: EOF during login" ); return; } - $input =~ s/[\r\n]+$//sm; # Strip off trailing line terminator(s) + $input =~ s/[\r\n]+$//sm; # Strip off trailing line terminator(s) my $reg = qr/^${\(LOGIN)}/; - last if $input !~ $reg || - C4::SIP::Sip::MsgType::handle($input, $self, LOGIN); + last + if $input !~ $reg + || C4::SIP::Sip::MsgType::handle( $input, $self, LOGIN ); } alarm 0; @@ -303,7 +308,7 @@ sub raw_transport { Koha::Logger->get( { interface => 'sip', - category => $self->{account}->{id}, # Add id to namespace + category => $self->{account}->{id}, # Add id to namespace } ) ); @@ -312,29 +317,31 @@ sub raw_transport { Koha::Logger->put_mdc( "accountid", $self->{account}->{id} ); Koha::Logger->put_mdc( "peeraddr", $self->{server}->{peeraddr} ); - siplog("LOG_DEBUG", "raw_transport: uname/inst: '%s/%s'", + siplog( + "LOG_DEBUG", "raw_transport: uname/inst: '%s/%s'", $self->{account}->{id}, - $self->{account}->{institution}); - if (! $self->{account}->{id}) { - siplog("LOG_ERR","Login failed shutting down"); + $self->{account}->{institution} + ); + if ( !$self->{account}->{id} ) { + siplog( "LOG_ERR", "Login failed shutting down" ); return; } $self->sip_protocol_loop(); - siplog("LOG_INFO", "raw_transport: shutting down"); + siplog( "LOG_INFO", "raw_transport: shutting down" ); return; } sub get_clean_string { my $string = shift; - if (defined $string) { - siplog("LOG_DEBUG", "get_clean_string pre-clean(length %s): %s", length($string), $string); + if ( defined $string ) { + siplog( "LOG_DEBUG", "get_clean_string pre-clean(length %s): %s", length($string), $string ); chomp($string); $string =~ s/^[^A-z0-9]+//; $string =~ s/[^A-z0-9]+$//; - siplog("LOG_DEBUG", "get_clean_string post-clean(length %s): %s", length($string), $string); + siplog( "LOG_DEBUG", "get_clean_string post-clean(length %s): %s", length($string), $string ); } else { - siplog("LOG_INFO", "get_clean_string called on undefined"); + siplog( "LOG_INFO", "get_clean_string called on undefined" ); } return $string; } @@ -343,70 +350,73 @@ sub get_clean_input { local $/ = "\012"; my $in = ; $in = get_clean_string($in); - while (my $extra = ){ - siplog("LOG_ERR", "get_clean_input got extra lines: %s", $extra); + while ( my $extra = ) { + siplog( "LOG_ERR", "get_clean_input got extra lines: %s", $extra ); } return $in; } sub telnet_transport { my $self = shift; - my ($uid, $pwd); + my ( $uid, $pwd ); my $strikes = 3; my $account = undef; my $input; my $config = $self->{config}; - my $timeout = $self->get_timeout({ transport => 1 }); - siplog("LOG_DEBUG", "telnet_transport: timeout is $timeout"); + my $timeout = $self->get_timeout( { transport => 1 } ); + siplog( "LOG_DEBUG", "telnet_transport: timeout is $timeout" ); eval { - local $SIG{ALRM} = sub { die "telnet_transport: Timed Out ($timeout seconds)!\n"; }; - local $| = 1; # Unbuffered output - $/ = "\015"; # Internet Record Separator (lax version) - # Until the terminal has logged in, we don't trust it - # so use a timeout to protect ourselves from hanging. + local $SIG{ALRM} = sub { die "telnet_transport: Timed Out ($timeout seconds)!\n"; }; + local $| = 1; # Unbuffered output + $/ = "\015"; # Internet Record Separator (lax version) + # Until the terminal has logged in, we don't trust it + # so use a timeout to protect ourselves from hanging. - while ($strikes--) { - print "login: "; - alarm $timeout; - # $uid = &get_clean_input; - $uid = ; - print "password: "; - # $pwd = &get_clean_input || ''; - $pwd = ; - alarm 0; + while ( $strikes-- ) { + print "login: "; + alarm $timeout; - siplog("LOG_DEBUG", "telnet_transport 1: uid length %s, pwd length %s", length($uid), length($pwd)); - $uid = get_clean_string ($uid); - $pwd = get_clean_string ($pwd); - siplog("LOG_DEBUG", "telnet_transport 2: uid length %s, pwd length %s", length($uid), length($pwd)); + # $uid = &get_clean_input; + $uid = ; + print "password: "; - if (exists ($config->{accounts}->{$uid}) - && ($pwd eq $config->{accounts}->{$uid}->{password})) { - $account = $config->{accounts}->{$uid}; - if ( C4::SIP::Sip::MsgType::login_core($self,$uid,$pwd) ) { - last; + # $pwd = &get_clean_input || ''; + $pwd = ; + alarm 0; + + siplog( "LOG_DEBUG", "telnet_transport 1: uid length %s, pwd length %s", length($uid), length($pwd) ); + $uid = get_clean_string($uid); + $pwd = get_clean_string($pwd); + siplog( "LOG_DEBUG", "telnet_transport 2: uid length %s, pwd length %s", length($uid), length($pwd) ); + + if ( exists( $config->{accounts}->{$uid} ) + && ( $pwd eq $config->{accounts}->{$uid}->{password} ) ) + { + $account = $config->{accounts}->{$uid}; + if ( C4::SIP::Sip::MsgType::login_core( $self, $uid, $pwd ) ) { + last; + } } + siplog( "LOG_WARNING", "Invalid login attempt: '%s'", ( $uid || '' ) ); + print("Invalid login$CRLF"); } - siplog("LOG_WARNING", "Invalid login attempt: '%s'", ($uid||'')); - print("Invalid login$CRLF"); - } - }; # End of eval + }; # End of eval if ($@) { - siplog("LOG_ERR", "telnet_transport: Login timed out"); + siplog( "LOG_ERR", "telnet_transport: Login timed out" ); die "Telnet Login Timed out"; - } elsif (!defined($account)) { - siplog("LOG_ERR", "telnet_transport: Login Failed"); + } elsif ( !defined($account) ) { + siplog( "LOG_ERR", "telnet_transport: Login Failed" ); die "Login Failure"; } else { print "Login OK. Initiating SIP$CRLF"; } $self->{account} = $account; - siplog("LOG_DEBUG", "telnet_transport: uname/inst: '%s/%s'", $account->{id}, $account->{institution}); + siplog( "LOG_DEBUG", "telnet_transport: uname/inst: '%s/%s'", $account->{id}, $account->{institution} ); $self->sip_protocol_loop(); - siplog("LOG_INFO", "telnet_transport: shutting down"); + siplog( "LOG_INFO", "telnet_transport: shutting down" ); return; } @@ -416,10 +426,10 @@ sub telnet_transport { # telnet transport. From that point on, both the raw and the telnet # processes are the same: sub sip_protocol_loop { - my $self = shift; + my $self = shift; my $service = $self->{service}; my $config = $self->{config}; - my $timeout = $self->get_timeout({ client => 1 }); + my $timeout = $self->get_timeout( { client => 1 } ); # The spec says the first message will be: # SIP v1: SC_STATUS @@ -473,41 +483,41 @@ sub sip_protocol_loop { } sub read_request { - my $raw_length; - local $/ = "\015"; + my $raw_length; + local $/ = "\015"; - # SIP connections might be active for weeks, clear L1 cache on every request - Koha::Caches->flush_L1_caches(); + # SIP connections might be active for weeks, clear L1 cache on every request + Koha::Caches->flush_L1_caches(); # proper SPEC: (octal) \015 = (hex) x0D = (dec) 13 = (ascii) carriage return - my $buffer = ; - if ( defined $buffer ) { - STDIN->flush(); # clear an extra linefeed - chomp $buffer; - $raw_length = length $buffer; - $buffer =~ s/^\s*[^A-z0-9]+//s; -# Every line must start with a "real" character. Not whitespace, control chars, etc. - $buffer =~ s/[^A-z0-9]+$//s; + my $buffer = ; + if ( defined $buffer ) { + STDIN->flush(); # clear an extra linefeed + chomp $buffer; + $raw_length = length $buffer; + $buffer =~ s/^\s*[^A-z0-9]+//s; -# Same for the end. Note this catches the problem some clients have sending empty fields at the end, like ||| - $buffer =~ s/\015?\012//g; # Extra line breaks must die - $buffer =~ s/\015?\012//s; # Extra line breaks must die - $buffer =~ s/\015*\012*$//s; + # Every line must start with a "real" character. Not whitespace, control chars, etc. + $buffer =~ s/[^A-z0-9]+$//s; - # treat as one line to include the extra linebreaks we are trying to remove! - } - else { - siplog( 'LOG_DEBUG', 'EOF returned on read' ); - return; - } - my $len = length $buffer; - if ( $len != $raw_length ) { - my $trim = $raw_length - $len; - siplog( 'LOG_DEBUG', "read_request trimmed $trim character(s) " ); - } + # Same for the end. Note this catches the problem some clients have sending empty fields at the end, like ||| + $buffer =~ s/\015?\012//g; # Extra line breaks must die + $buffer =~ s/\015?\012//s; # Extra line breaks must die + $buffer =~ s/\015*\012*$//s; - siplog( 'LOG_INFO', "INPUT MSG: '$buffer'" ); - return $buffer; + # treat as one line to include the extra linebreaks we are trying to remove! + } else { + siplog( 'LOG_DEBUG', 'EOF returned on read' ); + return; + } + my $len = length $buffer; + if ( $len != $raw_length ) { + my $trim = $raw_length - $len; + siplog( 'LOG_DEBUG', "read_request trimmed $trim character(s) " ); + } + + siplog( 'LOG_INFO', "INPUT MSG: '$buffer'" ); + return $buffer; } # $server->get_timeout({ $type => 1, fallback => $fallback }); @@ -523,25 +533,27 @@ sub read_request { sub get_timeout { my ( $server, $params ) = @_; my $fallback = $params->{fallback} || 30; - my $service = $server->{service} // {}; - my $config = $server->{config} // {}; + my $service = $server->{service} // {}; + my $config = $server->{config} // {}; - if( $params->{transport} || - ( $params->{client} && !exists $service->{client_timeout} )) { + if ( $params->{transport} + || ( $params->{client} && !exists $service->{client_timeout} ) ) + { # We do not allow zero values here. # Note: config/timeout seems to be deprecated. return $service->{timeout} || $config->{timeout} || $fallback; - } elsif( $params->{client} ) { + } elsif ( $params->{client} ) { + # We know that client_timeout exists now. # We do allow zero values here to indicate no timeout. return 0 if $service->{client_timeout} =~ /^0+$|\D/; return $service->{client_timeout}; - } elsif( $params->{policy} ) { + } elsif ( $params->{policy} ) { my $policy = $server->{policy} // {}; - my $rv = sprintf( "%03d", $policy->{timeout} // 0 ); - if( length($rv) != 3 ) { + my $rv = sprintf( "%03d", $policy->{timeout} // 0 ); + if ( length($rv) != 3 ) { siplog( "LOG_ERR", "Policy timeout has wrong size: '%s'", $rv ); return '000'; } diff --git a/C4/SIP/Sip.pm b/C4/SIP/Sip.pm index 667e0c83ac..6858d6437b 100644 --- a/C4/SIP/Sip.pm +++ b/C4/SIP/Sip.pm @@ -8,14 +8,14 @@ use strict; use warnings; use Exporter; use Encode; -use POSIX qw(strftime); +use POSIX qw(strftime); use Socket qw(:crlf); use IO::Handle; use List::Util qw(any); use C4::SIP::Sip::Constants qw(SIP_DATETIME FID_SCREEN_MSG); -use C4::SIP::Sip::Checksum qw(checksum); -use C4::SIP::Logger qw( get_logger ); +use C4::SIP::Sip::Checksum qw(checksum); +use C4::SIP::Logger qw( get_logger ); use base qw(Exporter); @@ -25,14 +25,17 @@ our @EXPORT_OK = qw(y_or_n timestamp add_field maybe_add add_count $last_response siplog); our %EXPORT_TAGS = ( - all => [qw(y_or_n timestamp add_field maybe_add - add_count denied sipbool boolspace write_msg - $error_detection $protocol_version - $field_delimiter $last_response siplog)]); + all => [ + qw(y_or_n timestamp add_field maybe_add + add_count denied sipbool boolspace write_msg + $error_detection $protocol_version + $field_delimiter $last_response siplog) + ] +); -our $error_detection = 0; +our $error_detection = 0; our $protocol_version = 1; -our $field_delimiter = '|'; # Protocol Default +our $field_delimiter = '|'; # Protocol Default # We need to keep a copy of the last message we sent to the SC, # in case there's a transmission error and the SC sends us a @@ -44,13 +47,14 @@ our $last_response = ''; sub timestamp { my $time = $_[0] || time(); - if ( ref $time eq 'DateTime') { + if ( ref $time eq 'DateTime' ) { return $time->strftime(SIP_DATETIME); - } elsif ($time=~m/^(\d{4})\-(\d{2})\-(\d{2})/) { + } elsif ( $time =~ m/^(\d{4})\-(\d{2})\-(\d{2})/ ) { + # passing a db returned date as is + bogus time - return sprintf( '%04d%02d%02d 235900', $1, $2, $3); + return sprintf( '%04d%02d%02d 235900', $1, $2, $3 ); } - return strftime(SIP_DATETIME, localtime($time)); + return strftime( SIP_DATETIME, localtime($time) ); } # @@ -58,26 +62,28 @@ sub timestamp { # return constructed field value # sub add_field { - my ($field_id, $value, $server) = @_; + my ( $field_id, $value, $server ) = @_; return q{} if should_hide( $field_id, $value, $server ); - my ($i, $ent); + my ( $i, $ent ); - if (!defined($value)) { - siplog("LOG_DEBUG", "add_field: Undefined value being added to '%s'", - $field_id); + if ( !defined($value) ) { + siplog( + "LOG_DEBUG", "add_field: Undefined value being added to '%s'", + $field_id + ); $value = ''; } - $value=~s/\r/ /g; # CR terminates a sip message - # Protect against them in sip text fields + $value =~ s/\r/ /g; # CR terminates a sip message + # Protect against them in sip text fields # Replace any occurrences of the field delimiter in the # field value with the HTML character entity - $ent = sprintf("&#%d;", ord($field_delimiter)); + $ent = sprintf( "&#%d;", ord($field_delimiter) ); - while (($i = index($value, $field_delimiter)) != ($[-1)) { - substr($value, $i, 1) = $ent; + while ( ( $i = index( $value, $field_delimiter ) ) != ( $[ - 1 ) ) { + substr( $value, $i, 1 ) = $ent; } return $field_id . $value . $field_delimiter; @@ -89,23 +95,24 @@ sub add_field { # NOTE: if zero is a valid value for your field, don't use maybe_add! # sub maybe_add { - my ($fid, $value, $server) = @_; + my ( $fid, $value, $server ) = @_; return q{} if should_hide( $fid, $value, $server ); - if ( $fid eq FID_SCREEN_MSG && $server->{account}->{screen_msg_regex} && defined($value)) { + if ( $fid eq FID_SCREEN_MSG && $server->{account}->{screen_msg_regex} && defined($value) ) { foreach my $regex ( ref $server->{account}->{screen_msg_regex} eq "ARRAY" ? @{ $server->{account}->{screen_msg_regex} } - : $server->{account}->{screen_msg_regex} ) + : $server->{account}->{screen_msg_regex} + ) { $value =~ s/$regex->{find}/$regex->{replace}/g; } } return ( defined($value) && length($value) ) - ? add_field( $fid, $value ) - : ''; + ? add_field( $fid, $value ) + : ''; } sub should_hide { @@ -132,18 +139,20 @@ sub should_hide { # reason # sub add_count { - my ($label, $count) = @_; + my ( $label, $count ) = @_; # If the field is unsupported, it will be undef, return blanks # as per the spec. - if (!defined($count)) { + if ( !defined($count) ) { return ' ' x 4; } - $count = sprintf("%04d", $count); - if (length($count) != 4) { - siplog("LOG_WARNING", "handle_patron_info: %s wrong size: '%s'", - $label, $count); + $count = sprintf( "%04d", $count ); + if ( length($count) != 4 ) { + siplog( + "LOG_WARNING", "handle_patron_info: %s wrong size: '%s'", + $label, $count + ); $count = ' ' x 4; } return $count; @@ -159,7 +168,7 @@ sub add_count { # sub denied { my $bool = shift; - return boolspace(!$bool); + return boolspace( !$bool ); } sub sipbool { @@ -222,13 +231,13 @@ sub siplog { my ( $level, $mask, @args ) = @_; my $method = - $level eq 'LOG_ERR' ? 'error' - : $level eq 'LOG_DEBUG' ? 'debug' - : $level eq 'LOG_INFO' ? 'info' - : $level eq 'LOG_WARNING' ? 'warn' - : 'error'; + $level eq 'LOG_ERR' ? 'error' + : $level eq 'LOG_DEBUG' ? 'debug' + : $level eq 'LOG_INFO' ? 'info' + : $level eq 'LOG_WARNING' ? 'warn' + : 'error'; - my $message = @args ? sprintf($mask, @args) : $mask; + my $message = @args ? sprintf( $mask, @args ) : $mask; my $logger = C4::SIP::Logger::get_logger(); $logger->$method($message) if $logger; diff --git a/C4/SIP/Sip/Checksum.pm b/C4/SIP/Sip/Checksum.pm index cba51a5c22..4571c42d9b 100644 --- a/C4/SIP/Sip/Checksum.pm +++ b/C4/SIP/Sip/Checksum.pm @@ -4,12 +4,12 @@ use Exporter; use strict; use warnings; -our @ISA = qw(Exporter); +our @ISA = qw(Exporter); our @EXPORT_OK = qw(checksum verify_cksum); sub checksum { my $pkt = shift; - return (-unpack('%16C*', $pkt) & 0xFFFF); + return ( -unpack( '%16C*', $pkt ) & 0xFFFF ); } sub verify_cksum { @@ -17,20 +17,21 @@ sub verify_cksum { my $cksum; my $shortsum; - unless ($pkt =~ /AZ(....)$/) { - warn "verify_cksum: no sum detected"; - return 0; # No checksum at end - } + unless ( $pkt =~ /AZ(....)$/ ) { + warn "verify_cksum: no sum detected"; + return 0; # No checksum at end + } + # return 0 if (substr($pkt, -6, 2) ne "AZ"); # Convert the checksum back to hex and calculate the sum of the # pack without the checksum. - $cksum = hex($1); - $shortsum = unpack("%16C*", substr($pkt, 0, -4)); + $cksum = hex($1); + $shortsum = unpack( "%16C*", substr( $pkt, 0, -4 ) ); - # The checksum is valid if the hex sum, plus the checksum of the + # The checksum is valid if the hex sum, plus the checksum of the # base packet short when truncated to 16 bits. - return (($cksum + $shortsum) & 0xFFFF) == 0; + return ( ( $cksum + $shortsum ) & 0xFFFF ) == 0; } 1; diff --git a/C4/SIP/Sip/Configuration.pm b/C4/SIP/Sip/Configuration.pm index 5c74b124a7..624d48983a 100644 --- a/C4/SIP/Sip/Configuration.pm +++ b/C4/SIP/Sip/Configuration.pm @@ -8,7 +8,7 @@ package C4::SIP::Sip::Configuration; use strict; use warnings; -use XML::Simple qw(:strict); +use XML::Simple qw(:strict); use List::MoreUtils qw(uniq); use C4::SIP::Sip qw(siplog); @@ -49,10 +49,13 @@ sub new { } $cfg->{listeners} = \%listeners; - my @branchcodes = Koha::Libraries->search()->get_column('branchcode'); + my @branchcodes = Koha::Libraries->search()->get_column('branchcode'); my @institutions = uniq( keys %{ $cfg->{institutions} } ); - foreach my $i ( @institutions ) { - siplog("LOG_ERR", "ERROR: Institution $i does does not match a branchcode. This can cause unexpected behavior.") unless grep( /^$i$/, @branchcodes ); + foreach my $i (@institutions) { + siplog( + "LOG_ERR", + "ERROR: Institution $i does does not match a branchcode. This can cause unexpected behavior." + ) unless grep( /^$i$/, @branchcodes ); } return bless $cfg, $class; @@ -73,8 +76,10 @@ sub find_service { my $portstr; foreach my $addr ( '', '*:', "$sockaddr:", "[$sockaddr]:" ) { $portstr = sprintf( "%s%s/%s", $addr, $port, lc $proto ); - siplog( "LOG_DEBUG", - "Configuration::find_service: Trying $portstr" ); + siplog( + "LOG_DEBUG", + "Configuration::find_service: Trying $portstr" + ); last if ( exists( ( $self->{listeners} )->{$portstr} ) ); $portstr .= '/ipv4'; # lc, see ->new last if ( exists( ( $self->{listeners} )->{$portstr} ) ); diff --git a/C4/SIP/Sip/Constants.pm b/C4/SIP/Sip/Constants.pm index fb48c333c6..85875ca650 100644 --- a/C4/SIP/Sip/Constants.pm +++ b/C4/SIP/Sip/Constants.pm @@ -11,91 +11,97 @@ use strict; use warnings; use Exporter; -our (@ISA, @EXPORT_OK, %EXPORT_TAGS); +our ( @ISA, @EXPORT_OK, %EXPORT_TAGS ); BEGIN { @ISA = qw(Exporter); %EXPORT_TAGS = ( - SC_msgs => [qw( - PATRON_STATUS_REQ - CHECKOUT CHECKIN - SC_STATUS REQUEST_ACS_RESEND - LOGIN PATRON_INFO END_PATRON_SESSION - FEE_PAID ITEM_INFORMATION ITEM_STATUS_UPDATE - HOLD RENEW RENEW_ALL - PATRON_ENABLE - BLOCK_PATRON - )], + SC_msgs => [ + qw( + PATRON_STATUS_REQ + CHECKOUT CHECKIN + SC_STATUS REQUEST_ACS_RESEND + LOGIN PATRON_INFO END_PATRON_SESSION + FEE_PAID ITEM_INFORMATION ITEM_STATUS_UPDATE + HOLD RENEW RENEW_ALL + PATRON_ENABLE + BLOCK_PATRON + ) + ], - ACS_msgs => [qw( - PATRON_STATUS_RESP - CHECKOUT_RESP CHECKIN_RESP - ACS_STATUS REQUEST_SC_RESEND - LOGIN_RESP PATRON_INFO_RESP END_SESSION_RESP - FEE_PAID_RESP ITEM_INFO_RESP ITEM_STATUS_UPDATE_RESP - HOLD_RESP RENEW_RESP RENEW_ALL_RESP - PATRON_ENABLE_RESP - )], + ACS_msgs => [ + qw( + PATRON_STATUS_RESP + CHECKOUT_RESP CHECKIN_RESP + ACS_STATUS REQUEST_SC_RESEND + LOGIN_RESP PATRON_INFO_RESP END_SESSION_RESP + FEE_PAID_RESP ITEM_INFO_RESP ITEM_STATUS_UPDATE_RESP + HOLD_RESP RENEW_RESP RENEW_ALL_RESP + PATRON_ENABLE_RESP + ) + ], - SC_status => [qw(SC_STATUS_OK SC_STATUS_PAPER SC_STATUS_SHUTDOWN)], - formats => [qw(SIP_DATETIME)], - constant_msgs => [qw(REQUEST_ACS_RESEND_CKSUM REQUEST_SC_RESEND_CKSUM)], + SC_status => [qw(SC_STATUS_OK SC_STATUS_PAPER SC_STATUS_SHUTDOWN)], + formats => [qw(SIP_DATETIME)], + constant_msgs => [qw(REQUEST_ACS_RESEND_CKSUM REQUEST_SC_RESEND_CKSUM)], - field_ids => [qw( - FID_PATRON_ID FID_ITEM_ID - FID_TERMINAL_PWD FID_PATRON_PWD - FID_PERSONAL_NAME FID_DUE_DATE - FID_SCREEN_MSG FID_PRINT_LINE - FID_TITLE_ID FID_BLOCKED_CARD_MSG - FID_TERMINAL_LOCN FID_INST_ID - FID_CURRENT_LOCN FID_LIBRARY_NAME - FID_PERM_LOCN - FID_HOLD_ITEMS FID_HOLD_ITEMS_LMT - FID_OVERDUE_ITEMS FID_OVERDUE_ITEMS_LMT - FID_CHARGED_ITEMS FID_CHARGED_ITEMS_LMT - FID_FINE_ITEMS FID_SEQNO - FID_CKSUM FID_HOME_ADDR - FID_EMAIL FID_HOME_PHONE - FID_OWNER FID_CURRENCY - FID_CANCEL - FID_TRANSACTION_ID FID_VALID_PATRON - FID_RENEWED_ITEMS - FID_UNRENEWED_ITEMS - FID_FEE_ACK - FID_START_ITEM FID_END_ITEM FID_QUEUE_POS - FID_PICKUP_LOCN FID_FEE_TYPE - FID_RECALL_ITEMS - FID_FEE_AMT FID_FEE_LMT - FID_EXPIRATION - FID_SUPPORTED_MSGS - FID_HOLD_TYPE - FID_UNAVAILABLE_HOLD_ITEMS - FID_HOLD_QUEUE_LEN - FID_FEE_ID FID_ITEM_PROPS - FID_RECALL_DATE FID_SECURITY_INHIBIT - FID_MEDIA_TYPE FID_SORT_BIN - FID_HOLD_PICKUP_DATE - FID_LOGIN_UID FID_LOGIN_PWD - FID_LOCATION_CODE - FID_VALID_PATRON_PWD - FID_PATRON_BIRTHDATE - FID_PATRON_CLASS - FID_INET_PROFILE + field_ids => [ + qw( + FID_PATRON_ID FID_ITEM_ID + FID_TERMINAL_PWD FID_PATRON_PWD + FID_PERSONAL_NAME FID_DUE_DATE + FID_SCREEN_MSG FID_PRINT_LINE + FID_TITLE_ID FID_BLOCKED_CARD_MSG + FID_TERMINAL_LOCN FID_INST_ID + FID_CURRENT_LOCN FID_LIBRARY_NAME + FID_PERM_LOCN + FID_HOLD_ITEMS FID_HOLD_ITEMS_LMT + FID_OVERDUE_ITEMS FID_OVERDUE_ITEMS_LMT + FID_CHARGED_ITEMS FID_CHARGED_ITEMS_LMT + FID_FINE_ITEMS FID_SEQNO + FID_CKSUM FID_HOME_ADDR + FID_EMAIL FID_HOME_PHONE + FID_OWNER FID_CURRENCY + FID_CANCEL + FID_TRANSACTION_ID FID_VALID_PATRON + FID_RENEWED_ITEMS + FID_UNRENEWED_ITEMS + FID_FEE_ACK + FID_START_ITEM FID_END_ITEM FID_QUEUE_POS + FID_PICKUP_LOCN FID_FEE_TYPE + FID_RECALL_ITEMS + FID_FEE_AMT FID_FEE_LMT + FID_EXPIRATION + FID_SUPPORTED_MSGS + FID_HOLD_TYPE + FID_UNAVAILABLE_HOLD_ITEMS + FID_HOLD_QUEUE_LEN + FID_FEE_ID FID_ITEM_PROPS + FID_RECALL_DATE FID_SECURITY_INHIBIT + FID_MEDIA_TYPE FID_SORT_BIN + FID_HOLD_PICKUP_DATE + FID_LOGIN_UID FID_LOGIN_PWD + FID_LOCATION_CODE + FID_VALID_PATRON_PWD + FID_PATRON_BIRTHDATE + FID_PATRON_CLASS + FID_INET_PROFILE - FID_COLLECTION_CODE - FID_CALL_NUMBER - FID_DESTINATION_LOCATION - FID_ALERT_TYPE - FID_HOLD_PATRON_ID - FID_HOLD_PATRON_NAME - )], + FID_COLLECTION_CODE + FID_CALL_NUMBER + FID_DESTINATION_LOCATION + FID_ALERT_TYPE + FID_HOLD_PATRON_ID + FID_HOLD_PATRON_NAME + ) + ], ); # Add the contents of the other ":class" tags to make an ":all" class (deleting duplicates) # This is the textbook example from http://perldoc.perl.org/Exporter.html my %seen; - push @{$EXPORT_TAGS{all}}, grep {!$seen{$_}++} @{$EXPORT_TAGS{$_}} foreach keys %EXPORT_TAGS; + push @{ $EXPORT_TAGS{all} }, grep { !$seen{$_}++ } @{ $EXPORT_TAGS{$_} } foreach keys %EXPORT_TAGS; Exporter::export_ok_tags('all'); # now add :all to @EXPORT_OK } @@ -154,43 +160,47 @@ use constant { # Field Identifiers # use constant { - FID_PATRON_ID => 'AA', - FID_ITEM_ID => 'AB', - FID_TERMINAL_PWD => 'AC', - FID_PATRON_PWD => 'AD', - FID_PERSONAL_NAME => 'AE', - FID_SCREEN_MSG => 'AF', - FID_PRINT_LINE => 'AG', - FID_DUE_DATE => 'AH', + FID_PATRON_ID => 'AA', + FID_ITEM_ID => 'AB', + FID_TERMINAL_PWD => 'AC', + FID_PATRON_PWD => 'AD', + FID_PERSONAL_NAME => 'AE', + FID_SCREEN_MSG => 'AF', + FID_PRINT_LINE => 'AG', + FID_DUE_DATE => 'AH', + # UNUSED AI - FID_TITLE_ID => 'AJ', + FID_TITLE_ID => 'AJ', + # UNUSED AK - FID_BLOCKED_CARD_MSG => 'AL', - FID_LIBRARY_NAME => 'AM', - FID_TERMINAL_LOCN => 'AN', - FID_INST_ID => 'AO', - FID_CURRENT_LOCN => 'AP', - FID_PERM_LOCN => 'AQ', + FID_BLOCKED_CARD_MSG => 'AL', + FID_LIBRARY_NAME => 'AM', + FID_TERMINAL_LOCN => 'AN', + FID_INST_ID => 'AO', + FID_CURRENT_LOCN => 'AP', + FID_PERM_LOCN => 'AQ', + # UNUSED AR - FID_HOLD_ITEMS => 'AS', # SIP 2.0 - FID_OVERDUE_ITEMS => 'AT', # SIP 2.0 - FID_CHARGED_ITEMS => 'AU', # SIP 2.0 - FID_FINE_ITEMS => 'AV', # SIP 2.0 - # UNUSED AW - # UNUSED AX - FID_SEQNO => 'AY', - FID_CKSUM => 'AZ', + FID_HOLD_ITEMS => 'AS', # SIP 2.0 + FID_OVERDUE_ITEMS => 'AT', # SIP 2.0 + FID_CHARGED_ITEMS => 'AU', # SIP 2.0 + FID_FINE_ITEMS => 'AV', # SIP 2.0 + # UNUSED AW + # UNUSED AX + FID_SEQNO => 'AY', + FID_CKSUM => 'AZ', # SIP 2.0 Fields # UNUSED BA # UNUSED BB # UNUSED BC - FID_HOME_ADDR => 'BD', - FID_EMAIL => 'BE', - FID_HOME_PHONE => 'BF', - FID_OWNER => 'BG', - FID_CURRENCY => 'BH', - FID_CANCEL => 'BI', + FID_HOME_ADDR => 'BD', + FID_EMAIL => 'BE', + FID_HOME_PHONE => 'BF', + FID_OWNER => 'BG', + FID_CURRENCY => 'BH', + FID_CANCEL => 'BI', + # UNUSED BJ FID_TRANSACTION_ID => 'BK', FID_VALID_PATRON => 'BL', @@ -212,34 +222,35 @@ use constant { FID_CHARGED_ITEMS_LMT => 'CB', FID_FEE_LMT => 'CC', FID_UNAVAILABLE_HOLD_ITEMS => 'CD', + # UNUSED CE - FID_HOLD_QUEUE_LEN => 'CF', - FID_FEE_ID => 'CG', - FID_ITEM_PROPS => 'CH', - FID_SECURITY_INHIBIT => 'CI', - FID_RECALL_DATE => 'CJ', - FID_MEDIA_TYPE => 'CK', - FID_SORT_BIN => 'CL', - FID_HOLD_PICKUP_DATE => 'CM', - FID_LOGIN_UID => 'CN', - FID_LOGIN_PWD => 'CO', - FID_LOCATION_CODE => 'CP', - FID_VALID_PATRON_PWD => 'CQ', + FID_HOLD_QUEUE_LEN => 'CF', + FID_FEE_ID => 'CG', + FID_ITEM_PROPS => 'CH', + FID_SECURITY_INHIBIT => 'CI', + FID_RECALL_DATE => 'CJ', + FID_MEDIA_TYPE => 'CK', + FID_SORT_BIN => 'CL', + FID_HOLD_PICKUP_DATE => 'CM', + FID_LOGIN_UID => 'CN', + FID_LOGIN_PWD => 'CO', + FID_LOCATION_CODE => 'CP', + FID_VALID_PATRON_PWD => 'CQ', # SIP Extensions used by Envisionware Terminals - FID_PATRON_BIRTHDATE => 'PB', - FID_PATRON_CLASS => 'PC', + FID_PATRON_BIRTHDATE => 'PB', + FID_PATRON_CLASS => 'PC', # SIP Extension for reporting patron internet privileges... application unknown - FID_INET_PROFILE => 'PI', + FID_INET_PROFILE => 'PI', # SIP Extensions by 3M spec: Document Revision 1.20, 02/14/2005 - FID_COLLECTION_CODE => 'CR', - FID_CALL_NUMBER => 'CS', - FID_DESTINATION_LOCATION => 'CT', - FID_ALERT_TYPE => 'CV', - FID_HOLD_PATRON_ID => 'CY', - FID_HOLD_PATRON_NAME => 'DA', + FID_COLLECTION_CODE => 'CR', + FID_CALL_NUMBER => 'CS', + FID_DESTINATION_LOCATION => 'CT', + FID_ALERT_TYPE => 'CV', + FID_HOLD_PATRON_ID => 'CY', + FID_HOLD_PATRON_NAME => 'DA', }; # diff --git a/C4/SIP/Sip/MsgType.pm b/C4/SIP/Sip/MsgType.pm index d5a024298a..23e0682372 100644 --- a/C4/SIP/Sip/MsgType.pm +++ b/C4/SIP/Sip/MsgType.pm @@ -10,14 +10,14 @@ use strict; use warnings; use Exporter; -use C4::SIP::Sip qw(:all); +use C4::SIP::Sip qw(:all); use C4::SIP::Sip::Constants qw(:all); -use C4::SIP::Sip::Checksum qw(verify_cksum); +use C4::SIP::Sip::Checksum qw(verify_cksum); use Data::Dumper; use CGI qw ( -utf8 ); use C4::Context; -use C4::Auth qw(&check_api_auth); +use C4::Auth qw(&check_api_auth); use C4::Items qw(ModDateLastSeen); use Koha::Patrons; @@ -40,10 +40,10 @@ BEGIN { # Predeclare handler subroutines use subs qw(handle_patron_status handle_checkout handle_checkin - handle_block_patron handle_sc_status handle_request_acs_resend - handle_login handle_patron_info handle_end_patron_session - handle_fee_paid handle_item_information handle_item_status_update - handle_patron_enable handle_hold handle_renew handle_renew_all); + handle_block_patron handle_sc_status handle_request_acs_resend + handle_login handle_patron_info handle_end_patron_session + handle_fee_paid handle_item_information handle_item_status_update + handle_patron_enable handle_hold handle_renew handle_renew_all); # # For the most part, Version 2.00 of the protocol just adds new @@ -81,7 +81,10 @@ my %handlers = ( 2 => { template => "A1A1A18A18", template_len => 38, - fields => [ (FID_INST_ID), (FID_PATRON_ID), (FID_ITEM_ID), (FID_TERMINAL_PWD), (FID_ITEM_PROPS), (FID_PATRON_PWD), (FID_FEE_ACK), (FID_CANCEL) ], + fields => [ + (FID_INST_ID), (FID_PATRON_ID), (FID_ITEM_ID), (FID_TERMINAL_PWD), (FID_ITEM_PROPS), + (FID_PATRON_PWD), (FID_FEE_ACK), (FID_CANCEL) + ], }, } }, @@ -97,7 +100,9 @@ my %handlers = ( 2 => { template => "A1A18A18", template_len => 37, - fields => [ (FID_CURRENT_LOCN), (FID_INST_ID), (FID_ITEM_ID), (FID_TERMINAL_PWD), (FID_ITEM_PROPS), (FID_CANCEL) ], + fields => [ + (FID_CURRENT_LOCN), (FID_INST_ID), (FID_ITEM_ID), (FID_TERMINAL_PWD), (FID_ITEM_PROPS), (FID_CANCEL) + ], } } }, @@ -152,7 +157,10 @@ my %handlers = ( 2 => { template => "A3A18A10", template_len => 31, - fields => [ (FID_INST_ID), (FID_PATRON_ID), (FID_TERMINAL_PWD), (FID_PATRON_PWD), (FID_START_ITEM), (FID_END_ITEM) ], + fields => [ + (FID_INST_ID), (FID_PATRON_ID), (FID_TERMINAL_PWD), (FID_PATRON_PWD), (FID_START_ITEM), + (FID_END_ITEM) + ], } } }, @@ -174,7 +182,10 @@ my %handlers = ( 2 => { template => "A18A2A2A3", template_len => 25, - fields => [ (FID_FEE_AMT), (FID_INST_ID), (FID_PATRON_ID), (FID_TERMINAL_PWD), (FID_PATRON_PWD), (FID_FEE_ID), (FID_TRANSACTION_ID) ], + fields => [ + (FID_FEE_AMT), (FID_INST_ID), (FID_PATRON_ID), (FID_TERMINAL_PWD), (FID_PATRON_PWD), (FID_FEE_ID), + (FID_TRANSACTION_ID) + ], } } }, @@ -219,7 +230,8 @@ my %handlers = ( template => "AA18", template_len => 19, fields => [ - (FID_EXPIRATION), (FID_PICKUP_LOCN), (FID_HOLD_TYPE), (FID_INST_ID), (FID_PATRON_ID), (FID_PATRON_PWD), + (FID_EXPIRATION), (FID_PICKUP_LOCN), (FID_HOLD_TYPE), (FID_INST_ID), (FID_PATRON_ID), + (FID_PATRON_PWD), (FID_ITEM_ID), (FID_TITLE_ID), (FID_TERMINAL_PWD), (FID_FEE_ACK) ], } @@ -232,7 +244,10 @@ my %handlers = ( 2 => { template => "A1A1A18A18", template_len => 38, - fields => [ (FID_INST_ID), (FID_PATRON_ID), (FID_PATRON_PWD), (FID_ITEM_ID), (FID_TITLE_ID), (FID_TERMINAL_PWD), (FID_ITEM_PROPS), (FID_FEE_ACK) ], + fields => [ + (FID_INST_ID), (FID_PATRON_ID), (FID_PATRON_PWD), (FID_ITEM_ID), (FID_TITLE_ID), + (FID_TERMINAL_PWD), (FID_ITEM_PROPS), (FID_FEE_ACK) + ], } } }, @@ -260,7 +275,7 @@ foreach my $i ( keys(%handlers) ) { sub new { my ( $class, $msg, $seqno ) = @_; - my $self = {}; + my $self = {}; my $msgtag = substr( $msg, 0, 2 ); if ( $msgtag eq LOGIN ) { @@ -271,14 +286,20 @@ sub new { # it's using the 2.00 login process, so it must support 2.00. $protocol_version = 2; } - siplog( "LOG_DEBUG", "Sip::MsgType::new('%s', '%s...', '%s'): seq.no '%s', protocol %s", $class, substr( $msg, 0, 10 ), $msgtag, $seqno, $protocol_version ); + siplog( + "LOG_DEBUG", "Sip::MsgType::new('%s', '%s...', '%s'): seq.no '%s', protocol %s", $class, + substr( $msg, 0, 10 ), $msgtag, $seqno, $protocol_version + ); # warn "SIP PROTOCOL: $protocol_version"; if ( !exists( $handlers{$msgtag} ) ) { siplog( "LOG_WARNING", "new Sip::MsgType: Skipping message of unknown type '%s' in '%s'", $msgtag, $msg ); return; } elsif ( !exists( $handlers{$msgtag}->{protocol}->{$protocol_version} ) ) { - siplog( "LOG_WARNING", "new Sip::MsgType: Skipping message '%s' unsupported by protocol rev. '%d'", $msgtag, $protocol_version ); + siplog( + "LOG_WARNING", "new Sip::MsgType: Skipping message '%s' unsupported by protocol rev. '%d'", $msgtag, + $protocol_version + ); return; } @@ -310,9 +331,13 @@ sub _initialize { $self->{fields}->{$field} = undef; } - siplog( "LOG_DEBUG", "Sip::MsgType::_initialize('%s', '%s', '%s', '%s', ...)", $self->{name}, $msg, $proto->{template}, $proto->{template_len} ); + siplog( + "LOG_DEBUG", "Sip::MsgType::_initialize('%s', '%s', '%s', '%s', ...)", $self->{name}, $msg, + $proto->{template}, $proto->{template_len} + ); - $self->{fixed_fields} = [ unpack( $proto->{template}, $msg ) ]; # see http://perldoc.perl.org/5.8.8/functions/unpack.html + $self->{fixed_fields} = + [ unpack( $proto->{template}, $msg ) ]; # see http://perldoc.perl.org/5.8.8/functions/unpack.html # Skip over the fixed fields and the split the rest of # the message into fields based on the delimiter and parse them @@ -322,7 +347,10 @@ sub _initialize { if ( !exists( $self->{fields}->{$fn} ) ) { siplog( "LOG_WARNING", "Unsupported field '%s' in %s message '%s'", $fn, $self->{name}, $msg ); } elsif ( defined( $self->{fields}->{$fn} ) ) { - siplog( "LOG_WARNING", "Duplicate field '%s' (previous value '%s') in %s message '%s'", $fn, $self->{fields}->{$fn}, $self->{name}, $msg ); + siplog( + "LOG_WARNING", "Duplicate field '%s' (previous value '%s') in %s message '%s'", $fn, + $self->{fields}->{$fn}, $self->{name}, $msg + ); } else { $self->{fields}->{$fn} = substr( $field, 2 ); } @@ -339,14 +367,14 @@ sub handle { # Set system preference overrides, first global, then account level # Clear overrides from previous message handling first foreach my $key ( keys %ENV ) { - delete $ENV{$key} if index($key, 'OVERRIDE_SYSPREF_') == 0; + delete $ENV{$key} if index( $key, 'OVERRIDE_SYSPREF_' ) == 0; } foreach my $key ( keys %{ $config->{'syspref_overrides'} } ) { $ENV{"OVERRIDE_SYSPREF_$key"} = $config->{'syspref_overrides'}->{$key}; } foreach my $key ( keys %{ $server->{account}->{'syspref_overrides'} } ) { $ENV{"OVERRIDE_SYSPREF_$key"} = - $server->{account}->{'syspref_overrides'}->{$key}; + $server->{account}->{'syspref_overrides'}->{$key}; } # @@ -366,7 +394,7 @@ sub handle { # Special case $error_detection = 1; - $self = C4::SIP::Sip::MsgType->new( (REQUEST_ACS_RESEND), 0 ); + $self = C4::SIP::Sip::MsgType->new( (REQUEST_ACS_RESEND), 0 ); } elsif ( ( length($msg) > 11 ) && ( substr( $msg, -9, 2 ) eq "AY" ) ) { $error_detection = 1; @@ -389,14 +417,15 @@ sub handle { # Warn about this problem, then process the message anyway. siplog( "LOG_WARNING", "Received message without error detection: '%s'", $msg ); $error_detection = 0; - $self = C4::SIP::Sip::MsgType->new( $msg, 0 ); + $self = C4::SIP::Sip::MsgType->new( $msg, 0 ); } else { $self = C4::SIP::Sip::MsgType->new( $msg, 0 ); } if ( ( substr( $msg, 0, 2 ) ne REQUEST_ACS_RESEND ) && $req - && ( substr( $msg, 0, 2 ) ne $req ) ) { + && ( substr( $msg, 0, 2 ) ne $req ) ) + { return substr( $msg, 0, 2 ); } unless ( $self->{handler} ) { @@ -407,7 +436,7 @@ sub handle { } return ( $self->{handler}->( $self, $server ) ); # FIXME # FIXME: Use of uninitialized value in subroutine entry - # Can't use string ("") as a subroutine ref while "strict refs" in use + # Can't use string ("") as a subroutine ref while "strict refs" in use } ## @@ -430,10 +459,10 @@ sub build_patron_status { my ( $patron, $lang, $fields, $server ) = @_; my $patron_pwd = $fields->{ (FID_PATRON_PWD) }; - my $resp = (PATRON_STATUS_RESP); + my $resp = (PATRON_STATUS_RESP); my $password_rc; - if ( $patron ) { + if ($patron) { if ($patron_pwd) { $password_rc = $patron->check_password($patron_pwd); } @@ -441,12 +470,12 @@ sub build_patron_status { $resp .= patron_status_string( $patron, $server ); $resp .= $lang . timestamp(); if ( defined $server->{account}->{ae_field_template} ) { - $resp .= add_field( FID_PERSONAL_NAME, $patron->format( $server->{account}->{ae_field_template}, $server ) ); + $resp .= + add_field( FID_PERSONAL_NAME, $patron->format( $server->{account}->{ae_field_template}, $server ) ); } else { $resp .= add_field( FID_PERSONAL_NAME, $patron->name, $server ); } - # while the patron ID we got from the SC is valid, let's # use the one returned from the ILS, just in case... $resp .= add_field( FID_PATRON_ID, $patron->id, $server ); @@ -456,22 +485,23 @@ sub build_patron_status { # Patron password is a required field. $resp .= add_field( FID_VALID_PATRON_PWD, sipbool($password_rc), $server ); - $resp .= maybe_add( FID_CURRENCY, $patron->currency, $server ); + $resp .= maybe_add( FID_CURRENCY, $patron->currency, $server ); $resp .= maybe_add( FID_FEE_AMT, $patron->fee_amount, $server ); } my $msg = $patron->screen_msg; - $msg .= ' -- '. INVALID_PW if $patron_pwd && !$password_rc; + $msg .= ' -- ' . INVALID_PW if $patron_pwd && !$password_rc; $resp .= maybe_add( FID_SCREEN_MSG, $msg, $server ); $resp .= maybe_add( FID_SCREEN_MSG, $patron->{branchcode}, $server ) - if ( $server->{account}->{send_patron_home_library_in_af} ); + if ( $server->{account}->{send_patron_home_library_in_af} ); $resp .= maybe_add( FID_PRINT_LINE, $patron->print_line, $server ); - $resp .= $patron->build_custom_field_string( $server ); - $resp .= $patron->build_patron_attributes_string( $server ); + $resp .= $patron->build_custom_field_string($server); + $resp .= $patron->build_patron_attributes_string($server); } else { + # Invalid patron (cardnumber) # Report that the user has no privs. @@ -484,7 +514,7 @@ sub build_patron_status { $resp .= add_field( FID_PATRON_ID, $fields->{ (FID_PATRON_ID) }, $server ); ( $protocol_version >= 2 ) - and $resp .= add_field( FID_VALID_PATRON, 'N', $server ); + and $resp .= add_field( FID_VALID_PATRON, 'N', $server ); $resp .= maybe_add( FID_SCREEN_MSG, INVALID_CARD, $server ); } @@ -505,7 +535,7 @@ sub handle_patron_status { $ils->check_inst_id( $fields->{ (FID_INST_ID) }, "handle_patron_status" ); $patron = $ils->find_patron( $fields->{ (FID_PATRON_ID) } ); if ( C4::Context->preference('TrackLastPatronActivityTriggers') && $patron ) { - my $koha_patron = Koha::Patrons->find($patron->{borrowernumber}); + my $koha_patron = Koha::Patrons->find( $patron->{borrowernumber} ); $koha_patron->update_lastseen('connection'); } $resp = build_patron_status( $patron, $lang, $fields, $server ); @@ -528,8 +558,8 @@ sub handle_checkout { $fields = $self->{fields}; $patron_id = $fields->{ (FID_PATRON_ID) }; - Koha::Plugins->call('patron_barcode_transform', \$patron_id ); - $item_id = $fields->{ (FID_ITEM_ID) }; + Koha::Plugins->call( 'patron_barcode_transform', \$patron_id ); + $item_id = $fields->{ (FID_ITEM_ID) }; my $fee_ack = $fields->{ (FID_FEE_ACK) }; if ( $no_block eq 'Y' ) { @@ -575,15 +605,15 @@ sub handle_checkout { $resp .= timestamp; # Now for the variable fields - $resp .= add_field( FID_INST_ID, $inst, $server ); - $resp .= add_field( FID_PATRON_ID, $patron_id, $server ); - $resp .= add_field( FID_ITEM_ID, $item_id, $server ); + $resp .= add_field( FID_INST_ID, $inst, $server ); + $resp .= add_field( FID_PATRON_ID, $patron_id, $server ); + $resp .= add_field( FID_ITEM_ID, $item_id, $server ); $resp .= add_field( FID_TITLE_ID, $item->title_id, $server ); if ( $item->due_date ) { my $due_date = - $account->{format_due_date} - ? output_pref( { str => $item->due_date, as_due_date => 1 } ) - : timestamp( $item->due_date ); + $account->{format_due_date} + ? output_pref( { str => $item->due_date, as_due_date => 1 } ) + : timestamp( $item->due_date ); $resp .= add_field( FID_DUE_DATE, $due_date, $server ); } else { $resp .= add_field( FID_DUE_DATE, q{}, $server ); @@ -596,21 +626,20 @@ sub handle_checkout { if ( $ils->supports('security inhibit') ) { $resp .= add_field( FID_SECURITY_INHIBIT, $status->security_inhibit, $server ); } - $resp .= maybe_add( FID_MEDIA_TYPE, $item->sip_media_type, $server ); + $resp .= maybe_add( FID_MEDIA_TYPE, $item->sip_media_type, $server ); $resp .= maybe_add( FID_ITEM_PROPS, $item->sip_item_properties, $server ); } - } - else { + } else { # Checkout failed # Checkout Response: not ok, no renewal, don't know mag. media, # no desensitize $resp = sprintf( "120NUN%s", timestamp ); - $resp .= add_field( FID_INST_ID, $inst, $server ); + $resp .= add_field( FID_INST_ID, $inst, $server ); $resp .= add_field( FID_PATRON_ID, $patron_id, $server ); - $resp .= add_field( FID_ITEM_ID, $item_id, $server ); + $resp .= add_field( FID_ITEM_ID, $item_id, $server ); # If the item is valid, provide the title, otherwise # leave it blank @@ -631,20 +660,23 @@ sub handle_checkout { if ( $patron && exists( $fields->{FID_PATRON_PWD} ) ) { # Password provided, so we can tell if it was valid or not - $resp .= add_field( FID_VALID_PATRON_PWD, sipbool( $patron->check_password( $fields->{ (FID_PATRON_PWD) } ) ), $server ); + $resp .= add_field( + FID_VALID_PATRON_PWD, + sipbool( $patron->check_password( $fields->{ (FID_PATRON_PWD) } ) ), $server + ); } } } - $resp .= $item->build_additional_item_fields_string( $server ) if $item; + $resp .= $item->build_additional_item_fields_string($server) if $item; if ( $protocol_version >= 2 ) { # Financials : return irrespective of ok status if ( $status->fee_amount ) { $resp .= add_field( FID_FEE_AMT, $status->fee_amount, $server ); - $resp .= maybe_add( FID_CURRENCY, $status->sip_currency, $server ); - $resp .= maybe_add( FID_FEE_TYPE, $status->sip_fee_type, $server ); + $resp .= maybe_add( FID_CURRENCY, $status->sip_currency, $server ); + $resp .= maybe_add( FID_FEE_TYPE, $status->sip_fee_type, $server ); $resp .= maybe_add( FID_TRANSACTION_ID, $status->transaction_id, $server ); } } @@ -678,7 +710,11 @@ sub handle_checkin { if ( $no_block eq 'Y' ) { # Off-line transactions, ick. - siplog( "LOG_WARNING", "received no-block checkin from terminal '%s' - no-block checkin not supported", $account->{id} ); + siplog( + "LOG_WARNING", "received no-block checkin from terminal '%s' - no-block checkin not supported", + $account->{id} + ); + #FIXME We need to write the routine called below #$status = $ils->checkin_no_block( $item_id, $trans_date, $return_date, $item_props, $cancel ); #Until we do, lets just checkin the item @@ -708,7 +744,7 @@ sub handle_checkin { if ($item) { $resp .= add_field( FID_PERM_LOCN, $item->permanent_location, $server ); $resp .= maybe_add( FID_TITLE_ID, $item->title_id, $server ); - $resp .= $item->build_additional_item_fields_string( $server ); + $resp .= $item->build_additional_item_fields_string($server); } else { $resp .= add_field( FID_PERM_LOCN, "", $server ); } @@ -719,12 +755,16 @@ sub handle_checkin { $resp .= add_field( FID_PATRON_ID, $patron->id, $server ); } if ($item) { - $resp .= maybe_add( FID_MEDIA_TYPE, $item->sip_media_type, $server ); - $resp .= maybe_add( FID_ITEM_PROPS, $item->sip_item_properties, $server ); - $resp .= maybe_add( FID_CALL_NUMBER, $item->call_number, $server ); - $resp .= maybe_add( FID_HOLD_PATRON_ID, $item->hold_patron_bcode, $server ); - $resp .= add_field( FID_DESTINATION_LOCATION, $item->destination_loc, $server ) if ( $item->destination_loc || $server->{account}->{ct_always_send} ); - $resp .= maybe_add( FID_HOLD_PATRON_NAME, $item->hold_patron_name( $server->{account}->{da_field_template} ), $server ); + $resp .= maybe_add( FID_MEDIA_TYPE, $item->sip_media_type, $server ); + $resp .= maybe_add( FID_ITEM_PROPS, $item->sip_item_properties, $server ); + $resp .= maybe_add( FID_CALL_NUMBER, $item->call_number, $server ); + $resp .= maybe_add( FID_HOLD_PATRON_ID, $item->hold_patron_bcode, $server ); + $resp .= add_field( FID_DESTINATION_LOCATION, $item->destination_loc, $server ) + if ( $item->destination_loc || $server->{account}->{ct_always_send} ); + $resp .= maybe_add( + FID_HOLD_PATRON_NAME, $item->hold_patron_name( $server->{account}->{da_field_template} ), + $server + ); if ( my $CR = $server->{account}->{cr_item_field} ) { $resp .= maybe_add( FID_COLLECTION_CODE, $item->{$CR}, $server ); @@ -733,7 +773,10 @@ sub handle_checkin { } if ( $status->hold and $status->hold->{branchcode} ne $item->destination_loc ) { - warn 'SIP hold mismatch: $status->hold->{branchcode}=' . $status->hold->{branchcode} . '; $item->destination_loc=' . $item->destination_loc; + warn 'SIP hold mismatch: $status->hold->{branchcode}=' + . $status->hold->{branchcode} + . '; $item->destination_loc=' + . $item->destination_loc; # just me being paranoid. } @@ -758,8 +801,8 @@ sub handle_block_patron { my $account = $server->{account}; my $ils = $server->{ils}; my ( $card_retained, $trans_date ); - my ( $inst_id, $blocked_card_msg, $patron_id, $terminal_pwd ); - my ( $fields, $resp, $patron ); + my ( $inst_id, $blocked_card_msg, $patron_id, $terminal_pwd ); + my ( $fields, $resp, $patron ); ( $card_retained, $trans_date ) = @{ $self->{fixed_fields} }; $fields = $self->{fields}; @@ -768,7 +811,7 @@ sub handle_block_patron { $patron_id = $fields->{ (FID_PATRON_ID) }; $terminal_pwd = $fields->{ (FID_TERMINAL_PWD) }; - Koha::Plugins->call('patron_barcode_transform', \$patron_id ); + Koha::Plugins->call( 'patron_barcode_transform', \$patron_id ); # Terminal passwords are different from account login # passwords, but I have no idea what to do with them. So, @@ -820,9 +863,15 @@ sub handle_sc_status { } if ( $status == SC_STATUS_PAPER ) { - siplog( "LOG_WARNING", "Self-Check unit '%s@%s' out of paper", $self->{account}->{id}, $self->{account}->{institution} ); + siplog( + "LOG_WARNING", "Self-Check unit '%s@%s' out of paper", $self->{account}->{id}, + $self->{account}->{institution} + ); } elsif ( $status == SC_STATUS_SHUTDOWN ) { - siplog( "LOG_WARNING", "Self-Check unit '%s@%s' shutting down", $self->{account}->{id}, $self->{account}->{institution} ); + siplog( + "LOG_WARNING", "Self-Check unit '%s@%s' shutting down", $self->{account}->{id}, + $self->{account}->{institution} + ); } $self->{account}->{print_width} = $print_width; @@ -838,7 +887,8 @@ sub handle_request_acs_resend { # REQUEST_SC_RESEND msg (p. 16) $self->write_msg( REQUEST_SC_RESEND, $server ); } elsif ( ( length($last_response) < 9 ) - || substr( $last_response, -9, 2 ) ne 'AY' ) { + || substr( $last_response, -9, 2 ) ne 'AY' ) + { # When resending a message, we aren't supposed to include # a sequence number, even if the original had one (p. 4). @@ -879,7 +929,10 @@ sub login_core { my $auth_status = api_auth( $uid, $pwd, $inst ); if ( !$auth_status or $auth_status !~ /^ok$/i ) { - siplog( "LOG_WARNING", "api_auth failed for SIP terminal '%s' of '%s': %s", $uid, $inst, ( $auth_status || 'unknown' ) ); + siplog( + "LOG_WARNING", "api_auth failed for SIP terminal '%s' of '%s': %s", $uid, $inst, + ( $auth_status || 'unknown' ) + ); $status = 0; } else { siplog( "LOG_INFO", "Successful login/auth for '%s' of '%s'", $server->{account}->{id}, $inst ); @@ -896,7 +949,10 @@ sub login_core { } $module->use; if ($@) { - siplog( "LOG_ERR", "%s: Loading ILS implementation '%s' for institution '%s' failed", $server->{service}, $module, $inst ); + siplog( + "LOG_ERR", "%s: Loading ILS implementation '%s' for institution '%s' failed", + $server->{service}, $module, $inst + ); die("Failed to load ILS implementation '$module' for $inst"); } @@ -912,7 +968,7 @@ sub login_core { } sub handle_login { - my ( $self, $server ) = @_; + my ( $self, $server ) = @_; my ( $uid_algorithm, $pwd_algorithm ); my ( $uid, $pwd ); my $inst; @@ -926,7 +982,10 @@ sub handle_login { $pwd = $fields->{ (FID_LOGIN_PWD) }; # Terminal PWD, not patron PWD. if ( $uid_algorithm || $pwd_algorithm ) { - siplog( "LOG_ERR", "LOGIN: Unsupported non-zero encryption method(s): uid = $uid_algorithm, pwd = $pwd_algorithm" ); + siplog( + "LOG_ERR", + "LOGIN: Unsupported non-zero encryption method(s): uid = $uid_algorithm, pwd = $pwd_algorithm" + ); $status = 0; } else { $status = login_core( $server, $uid, $pwd ); @@ -994,14 +1053,14 @@ sub handle_patron_info { $start = $fields->{ (FID_START_ITEM) }; $end = $fields->{ (FID_END_ITEM) }; - Koha::Plugins->call('patron_barcode_transform', \$patron_id ); + Koha::Plugins->call( 'patron_barcode_transform', \$patron_id ); $patron = $ils->find_patron($patron_id); $resp = (PATRON_INFO_RESP); if ($patron) { if ( C4::Context->preference('TrackLastPatronActivityTriggers') ) { - my $koha_patron = Koha::Patrons->find($patron->{borrowernumber}); + my $koha_patron = Koha::Patrons->find( $patron->{borrowernumber} ); $koha_patron->update_lastseen('connection'); } $resp .= patron_status_string( $patron, $server ); @@ -1019,9 +1078,10 @@ sub handle_patron_info { # while the patron ID we got from the SC is valid, let's # use the one returned from the ILS, just in case... - $resp .= add_field( FID_PATRON_ID, $patron->id, $server ); + $resp .= add_field( FID_PATRON_ID, $patron->id, $server ); if ( defined $server->{account}->{ae_field_template} ) { - $resp .= add_field( FID_PERSONAL_NAME, $patron->format( $server->{account}->{ae_field_template} ), $server ); + $resp .= + add_field( FID_PERSONAL_NAME, $patron->format( $server->{account}->{ae_field_template} ), $server ); } else { $resp .= add_field( FID_PERSONAL_NAME, $patron->name, $server ); } @@ -1041,10 +1101,10 @@ sub handle_patron_info { } else { $password_rc = $patron->check_password($patron_pwd); } - $resp .= add_field( FID_VALID_PATRON_PWD, sipbool( $password_rc ), $server ); + $resp .= add_field( FID_VALID_PATRON_PWD, sipbool($password_rc), $server ); } - $resp .= maybe_add( FID_CURRENCY, $patron->currency, $server ); + $resp .= maybe_add( FID_CURRENCY, $patron->currency, $server ); $resp .= maybe_add( FID_FEE_AMT, $patron->fee_amount, $server ); $resp .= add_field( FID_FEE_LMT, $patron->fee_limit, $server ); @@ -1057,30 +1117,30 @@ sub handle_patron_info { $resp .= summary_info( $ils, $patron, $summary, $start, $end, $server ); - $resp .= maybe_add( FID_HOME_ADDR, $patron->address, $server ); + $resp .= maybe_add( FID_HOME_ADDR, $patron->address, $server ); $resp .= maybe_add( FID_EMAIL, $patron->email_addr, $server ); $resp .= maybe_add( FID_HOME_PHONE, $patron->home_phone, $server ); # SIP 2.0 extensions used by Envisionware # Other terminals will ignore unrecognized fields (unrecognized field identifiers) $resp .= maybe_add( FID_PATRON_BIRTHDATE, $patron->birthdate, $server ); - $resp .= maybe_add( FID_PATRON_CLASS, $patron->ptype, $server ); + $resp .= maybe_add( FID_PATRON_CLASS, $patron->ptype, $server ); # Custom protocol extension to report patron internet privileges $resp .= maybe_add( FID_INET_PROFILE, $patron->inet_privileges, $server ); my $msg = $patron->screen_msg; - if( defined( $patron_pwd ) && !$password_rc ) { + if ( defined($patron_pwd) && !$password_rc ) { $msg .= ' -- ' . INVALID_PW; } $resp .= maybe_add( FID_SCREEN_MSG, $msg, $server ); if ( $server->{account}->{send_patron_home_library_in_af} ) { - $resp .= maybe_add( FID_SCREEN_MSG, $patron->{branchcode}, $server); + $resp .= maybe_add( FID_SCREEN_MSG, $patron->{branchcode}, $server ); } $resp .= maybe_add( FID_PRINT_LINE, $patron->print_line, $server ); - $resp .= $patron->build_custom_field_string( $server ); - $resp .= $patron->build_patron_attributes_string( $server ); + $resp .= $patron->build_custom_field_string($server); + $resp .= $patron->build_patron_attributes_string($server); } else { # Invalid patron ID: @@ -1092,8 +1152,8 @@ sub handle_patron_info { $resp .= add_field( FID_INST_ID, ( $ils->institution_id || 'SIP2' ), $server ); # patron ID is invalid, but field is required, so just echo it back - $resp .= add_field( FID_PATRON_ID, $fields->{ (FID_PATRON_ID) }, $server ); - $resp .= add_field( FID_PERSONAL_NAME, '', $server ); + $resp .= add_field( FID_PATRON_ID, $fields->{ (FID_PATRON_ID) }, $server ); + $resp .= add_field( FID_PERSONAL_NAME, '', $server ); if ( $protocol_version >= 2 ) { $resp .= add_field( FID_VALID_PATRON, 'N', $server ); @@ -1122,7 +1182,7 @@ sub handle_end_patron_session { $resp .= $status ? 'Y' : 'N'; $resp .= timestamp(); - $resp .= add_field( FID_INST_ID, $server->{ils}->institution, $server ); + $resp .= add_field( FID_INST_ID, $server->{ils}->institution, $server ); $resp .= add_field( FID_PATRON_ID, $fields->{ (FID_PATRON_ID) }, $server ); $resp .= maybe_add( FID_SCREEN_MSG, $screen_msg, $server ); @@ -1156,59 +1216,63 @@ sub handle_fee_paid { $fee_id = $fields->{ (FID_FEE_ID) }; $trans_id = $fields->{ (FID_TRANSACTION_ID) }; - Koha::Plugins->call('patron_barcode_transform', \$patron_id ); + Koha::Plugins->call( 'patron_barcode_transform', \$patron_id ); $ils->check_inst_id( $inst_id, "handle_fee_paid" ); - my $pay_result = $ils->pay_fee( $patron_id, $patron_pwd, $fee_amt, $fee_type, $pay_type, $fee_id, $trans_id, $currency, $is_writeoff, $disallow_overpayment, $register_id ); + my $pay_result = $ils->pay_fee( + $patron_id, $patron_pwd, $fee_amt, $fee_type, $pay_type, $fee_id, $trans_id, $currency, + $is_writeoff, $disallow_overpayment, $register_id + ); $status = $pay_result->{status}; my $pay_response = $pay_result->{pay_response}; my $failmap = { - "no_item" => "No matching item could be found", - "no_checkout" => "Item is not checked out", - "too_soon" => "Cannot yet be renewed", - "too_many" => "Renewed the maximum number of times", - "auto_too_soon" => "Scheduled for automatic renewal and cannot yet be renewed", - "auto_too_late" => "Scheduled for automatic renewal and cannot yet be any more", - "auto_account_expired" => "Scheduled for automatic renewal and cannot be renewed because the patron's account has expired", - "auto_renew" => "Scheduled for automatic renewal", - "auto_too_much_oweing" => "Scheduled for automatic renewal", - "on_reserve" => "On hold for another patron", - "patron_restricted" => "Patron is currently restricted", - "item_denied_renewal" => "Item is not allowed renewal", - "onsite_checkout" => "Item is an onsite checkout", + "no_item" => "No matching item could be found", + "no_checkout" => "Item is not checked out", + "too_soon" => "Cannot yet be renewed", + "too_many" => "Renewed the maximum number of times", + "auto_too_soon" => "Scheduled for automatic renewal and cannot yet be renewed", + "auto_too_late" => "Scheduled for automatic renewal and cannot yet be any more", + "auto_account_expired" => + "Scheduled for automatic renewal and cannot be renewed because the patron's account has expired", + "auto_renew" => "Scheduled for automatic renewal", + "auto_too_much_oweing" => "Scheduled for automatic renewal", + "on_reserve" => "On hold for another patron", + "patron_restricted" => "Patron is currently restricted", + "item_denied_renewal" => "Item is not allowed renewal", + "onsite_checkout" => "Item is an onsite checkout", "item_issued_to_other_patron" => "Item already issued to other borrower" }; my @success = (); - my @fail = (); - foreach my $result( @{$pay_response->{renew_result}} ) { - my $item = Koha::Items->find({ itemnumber => $result->{itemnumber} }); - if ($result->{success}) { + my @fail = (); + foreach my $result ( @{ $pay_response->{renew_result} } ) { + my $item = Koha::Items->find( { itemnumber => $result->{itemnumber} } ); + if ( $result->{success} ) { push @success, '"' . $item->biblio->title . '"'; } else { - push @fail, '"' . $item->biblio->title . '" : ' . $failmap->{$result->{error}}; + push @fail, '"' . $item->biblio->title . '" : ' . $failmap->{ $result->{error} }; } } my $msg = ""; - if (scalar @success > 0) { - $msg.="The following items were renewed: " . join(", ", @success) . ". "; + if ( scalar @success > 0 ) { + $msg .= "The following items were renewed: " . join( ", ", @success ) . ". "; } - if (scalar @fail > 0) { - $msg.="The following items were not renewed: " . join(", ", @fail) . "."; + if ( scalar @fail > 0 ) { + $msg .= "The following items were not renewed: " . join( ", ", @fail ) . "."; } - if (length $msg > 0) { - $status->screen_msg($status->screen_msg . " $msg"); + if ( length $msg > 0 ) { + $status->screen_msg( $status->screen_msg . " $msg" ); } $resp .= ( $status->ok ? 'Y' : 'N' ) . timestamp; - $resp .= add_field( FID_INST_ID, $inst_id, $server ); + $resp .= add_field( FID_INST_ID, $inst_id, $server ); $resp .= add_field( FID_PATRON_ID, $patron_id, $server ); $resp .= maybe_add( FID_TRANSACTION_ID, $status->transaction_id, $server ); - $resp .= maybe_add( FID_SCREEN_MSG, $pay_result->{error}, $server ); - $resp .= maybe_add( FID_SCREEN_MSG, $status->screen_msg, $server ); - $resp .= maybe_add( FID_PRINT_LINE, $status->print_line, $server ); + $resp .= maybe_add( FID_SCREEN_MSG, $pay_result->{error}, $server ); + $resp .= maybe_add( FID_SCREEN_MSG, $status->screen_msg, $server ); + $resp .= maybe_add( FID_PRINT_LINE, $status->print_line, $server ); $self->write_msg( $resp, $server ); @@ -1258,24 +1322,23 @@ sub handle_item_information { $resp .= maybe_add( FID_SCREEN_MSG, "Item is damaged", $server ); } - $resp .= add_field( FID_ITEM_ID, $item->id, $server ); + $resp .= add_field( FID_ITEM_ID, $item->id, $server ); $resp .= add_field( FID_TITLE_ID, $item->title_id, $server ); - $resp .= maybe_add( FID_MEDIA_TYPE, $item->sip_media_type, $server ); - $resp .= maybe_add( FID_PERM_LOCN, $item->permanent_location, $server ); - $resp .= maybe_add( FID_CURRENT_LOCN, $item->current_location, $server ); + $resp .= maybe_add( FID_MEDIA_TYPE, $item->sip_media_type, $server ); + $resp .= maybe_add( FID_PERM_LOCN, $item->permanent_location, $server ); + $resp .= maybe_add( FID_CURRENT_LOCN, $item->current_location, $server ); $resp .= maybe_add( FID_ITEM_PROPS, $item->sip_item_properties, $server ); - if ( my $CR = $server->{account}->{cr_item_field} ) { - $resp .= maybe_add( FID_COLLECTION_CODE, $item->{$CR}, $server ); + $resp .= maybe_add( FID_COLLECTION_CODE, $item->{$CR}, $server ); } else { - $resp .= maybe_add( FID_COLLECTION_CODE, $item->collection_code, $server ); + $resp .= maybe_add( FID_COLLECTION_CODE, $item->collection_code, $server ); } if ( ( $i = $item->fee ) != 0 ) { $resp .= add_field( FID_CURRENCY, $item->fee_currency, $server ); - $resp .= add_field( FID_FEE_AMT, $i, $server ); + $resp .= add_field( FID_FEE_AMT, $i, $server ); } $resp .= maybe_add( FID_OWNER, $item->owner, $server ); @@ -1284,9 +1347,9 @@ sub handle_item_information { } if ( $item->due_date ) { my $due_date = - $account->{format_due_date} - ? output_pref( { str => $item->due_date, as_due_date => 1 } ) - : timestamp( $item->due_date ); + $account->{format_due_date} + ? output_pref( { str => $item->due_date, as_due_date => 1 } ) + : timestamp( $item->due_date ); $resp .= add_field( FID_DUE_DATE, $due_date, $server ); } if ( ( $i = $item->recall_date ) != 0 ) { @@ -1299,8 +1362,8 @@ sub handle_item_information { $resp .= maybe_add( FID_SCREEN_MSG, $item->screen_msg, $server ); $resp .= maybe_add( FID_PRINT_LINE, $item->print_line, $server ); - $resp .= $item->build_additional_item_fields_string( $server ); - $resp .= $item->build_custom_field_string( $server ); + $resp .= $item->build_additional_item_fields_string($server); + $resp .= $item->build_custom_field_string($server); } $self->write_msg( $resp, $server ); @@ -1345,7 +1408,7 @@ sub handle_item_status_update { $resp .= $status->ok ? '1' : '0'; $resp .= timestamp; - $resp .= add_field( FID_ITEM_ID, $item->id, $server ); + $resp .= add_field( FID_ITEM_ID, $item->id, $server ); $resp .= add_field( FID_TITLE_ID, $item->title_id, $server ); $resp .= maybe_add( FID_ITEM_PROPS, $item->sip_item_properties, $server ); } @@ -1370,7 +1433,7 @@ sub handle_patron_enable { $patron_id = $fields->{ (FID_PATRON_ID) }; $patron_pwd = $fields->{ (FID_PATRON_PWD) }; - Koha::Plugins->call('patron_barcode_transform', \$patron_id ); + Koha::Plugins->call( 'patron_barcode_transform', \$patron_id ); siplog( "LOG_DEBUG", "handle_patron_enable: patron_id: '%s', patron_pwd: '%s'", $patron_id, $patron_pwd ); @@ -1381,9 +1444,9 @@ sub handle_patron_enable { # Invalid patron ID $resp .= 'YYYY' . ( ' ' x 10 ) . '000' . timestamp(); $resp .= add_field( FID_PATRON_ID, $patron_id, $server ); - $resp .= add_field( FID_PERSONAL_NAME, '', $server ); - $resp .= add_field( FID_VALID_PATRON, 'N', $server ); - $resp .= add_field( FID_VALID_PATRON_PWD, 'N', $server ); + $resp .= add_field( FID_PERSONAL_NAME, '', $server ); + $resp .= add_field( FID_VALID_PATRON, 'N', $server ); + $resp .= add_field( FID_VALID_PATRON_PWD, 'N', $server ); } else { # valid patron @@ -1395,7 +1458,7 @@ sub handle_patron_enable { $resp .= patron_status_string( $patron, $server ); $resp .= $patron->language . timestamp(); - $resp .= add_field( FID_PATRON_ID, $patron->id, $server ); + $resp .= add_field( FID_PATRON_ID, $patron->id, $server ); $resp .= add_field( FID_PERSONAL_NAME, $patron->format( $server->{account}->{ae_field_template} ), $server ); if ( defined($patron_pwd) ) { $resp .= add_field( FID_VALID_PATRON_PWD, sipbool( $patron->check_password($patron_pwd) ), $server ); @@ -1415,9 +1478,9 @@ sub handle_patron_enable { sub handle_hold { my ( $self, $server ) = @_; my $ils = $server->{ils}; - my ( $hold_mode, $trans_date ); + my ( $hold_mode, $trans_date ); my ( $expiry_date, $pickup_locn, $hold_type, $patron_id, $patron_pwd ); - my ( $item_id, $title_id, $fee_ack ); + my ( $item_id, $title_id, $fee_ack ); my $fields = $self->{fields}; my $status; my $resp = HOLD_RESP; @@ -1427,24 +1490,33 @@ sub handle_hold { $ils->check_inst_id( $fields->{ (FID_INST_ID) }, "handle_hold" ); $patron_id = $fields->{ (FID_PATRON_ID) }; - $expiry_date = $fields->{ (FID_EXPIRATION) } || ''; + $expiry_date = $fields->{ (FID_EXPIRATION) } || ''; $pickup_locn = $fields->{ (FID_PICKUP_LOCN) } || ''; - $hold_type = $fields->{ (FID_HOLD_TYPE) } || '2'; # Any copy of title + $hold_type = $fields->{ (FID_HOLD_TYPE) } || '2'; # Any copy of title $patron_pwd = $fields->{ (FID_PATRON_PWD) }; - $item_id = $fields->{ (FID_ITEM_ID) } || ''; + $item_id = $fields->{ (FID_ITEM_ID) } || ''; $title_id = $fields->{ (FID_TITLE_ID) } || ''; - $fee_ack = $fields->{ (FID_FEE_ACK) } || 'N'; + $fee_ack = $fields->{ (FID_FEE_ACK) } || 'N'; - Koha::Plugins->call('patron_barcode_transform', \$patron_id ); + Koha::Plugins->call( 'patron_barcode_transform', \$patron_id ); if ( $hold_mode eq '+' ) { - $status = $ils->add_hold( $patron_id, $patron_pwd, $item_id, $title_id, $expiry_date, $pickup_locn, $hold_type, $fee_ack ); + $status = $ils->add_hold( + $patron_id, $patron_pwd, $item_id, $title_id, $expiry_date, $pickup_locn, $hold_type, + $fee_ack + ); } elsif ( $hold_mode eq '-' ) { $status = $ils->cancel_hold( $patron_id, $patron_pwd, $item_id, $title_id ); } elsif ( $hold_mode eq '*' ) { - $status = $ils->alter_hold( $patron_id, $patron_pwd, $item_id, $title_id, $expiry_date, $pickup_locn, $hold_type, $fee_ack ); + $status = $ils->alter_hold( + $patron_id, $patron_pwd, $item_id, $title_id, $expiry_date, $pickup_locn, $hold_type, + $fee_ack + ); } else { - siplog( "LOG_WARNING", "handle_hold: Unrecognized hold mode '%s' from terminal '%s'", $hold_mode, $server->{account}->{id} ); + siplog( + "LOG_WARNING", "handle_hold: Unrecognized hold mode '%s' from terminal '%s'", $hold_mode, + $server->{account}->{id} + ); $status = $ils->Transaction::Hold; # new? $status->screen_msg("System error. Please contact library staff."); } @@ -1457,11 +1529,11 @@ sub handle_hold { $resp .= add_field( FID_PATRON_ID, $status->patron->id, $server ); ( $status->expiration_date ) - and $resp .= maybe_add( FID_EXPIRATION, timestamp( $status->expiration_date ), $server ); - $resp .= maybe_add( FID_QUEUE_POS, $status->queue_position, $server ); + and $resp .= maybe_add( FID_EXPIRATION, timestamp( $status->expiration_date ), $server ); + $resp .= maybe_add( FID_QUEUE_POS, $status->queue_position, $server ); $resp .= maybe_add( FID_PICKUP_LOCN, $status->pickup_location, $server ); - $resp .= maybe_add( FID_ITEM_ID, $status->item->id, $server ); - $resp .= maybe_add( FID_TITLE_ID, $status->item->title_id, $server ); + $resp .= maybe_add( FID_ITEM_ID, $status->item->id, $server ); + $resp .= maybe_add( FID_TITLE_ID, $status->item->title_id, $server ); } else { # Not ok. still need required fields @@ -1492,7 +1564,10 @@ sub handle_renew { $ils->check_inst_id( $fields->{ (FID_INST_ID) }, "handle_renew" ); if ( $no_block eq 'Y' ) { - siplog( "LOG_WARNING", "handle_renew: received 'no block' renewal from terminal '%s'", $server->{account}->{id} ); + siplog( + "LOG_WARNING", "handle_renew: received 'no block' renewal from terminal '%s'", + $server->{account}->{id} + ); } $patron_id = $fields->{ (FID_PATRON_ID) }; @@ -1502,9 +1577,12 @@ sub handle_renew { $item_props = $fields->{ (FID_ITEM_PROPS) }; $fee_ack = $fields->{ (FID_FEE_ACK) }; - Koha::Plugins->call('patron_barcode_transform', \$patron_id ); + Koha::Plugins->call( 'patron_barcode_transform', \$patron_id ); - $status = $ils->renew( $patron_id, $patron_pwd, $item_id, $title_id, $no_block, $nb_due_date, $third_party, $item_props, $fee_ack ); + $status = $ils->renew( + $patron_id, $patron_pwd, $item_id, $title_id, $no_block, $nb_due_date, $third_party, $item_props, + $fee_ack + ); $patron = $status->patron; $item = $status->item; @@ -1519,9 +1597,9 @@ sub handle_renew { } $resp .= sipbool( desensitize( { status => $status, patron => $patron, server => $server } ) ); $resp .= timestamp; - $resp .= add_field( FID_PATRON_ID, $patron->id, $server ); - $resp .= add_field( FID_ITEM_ID, $item->id, $server ); - $resp .= add_field( FID_TITLE_ID, $item->title_id, $server ); + $resp .= add_field( FID_PATRON_ID, $patron->id, $server ); + $resp .= add_field( FID_ITEM_ID, $item->id, $server ); + $resp .= add_field( FID_TITLE_ID, $item->title_id, $server ); if ( $item->due_date ) { $resp .= add_field( FID_DUE_DATE, timestamp( $item->due_date ), $server ); } else { @@ -1543,15 +1621,15 @@ sub handle_renew { # information, otherwise echo back the information we received # from the terminal $resp .= add_field( FID_PATRON_ID, $patron ? $patron->id : $patron_id, $server ); - $resp .= add_field( FID_ITEM_ID, $item ? $item->id : $item_id, $server ); - $resp .= add_field( FID_TITLE_ID, $item ? $item->title_id : $title_id, $server ); + $resp .= add_field( FID_ITEM_ID, $item ? $item->id : $item_id, $server ); + $resp .= add_field( FID_TITLE_ID, $item ? $item->title_id : $title_id, $server ); $resp .= add_field( FID_DUE_DATE, '', $server ); } if ( $status->fee_amount ) { $resp .= add_field( FID_FEE_AMT, $status->fee_amount, $server ); - $resp .= maybe_add( FID_CURRENCY, $status->sip_currency, $server ); - $resp .= maybe_add( FID_FEE_TYPE, $status->sip_fee_type, $server ); + $resp .= maybe_add( FID_CURRENCY, $status->sip_currency, $server ); + $resp .= maybe_add( FID_FEE_TYPE, $status->sip_fee_type, $server ); $resp .= maybe_add( FID_TRANSACTION_ID, $status->transaction_id, $server ); } @@ -1585,7 +1663,7 @@ sub handle_renew_all { $terminal_pwd = $fields->{ (FID_TERMINAL_PWD) }; $fee_ack = $fields->{ (FID_FEE_ACK) }; - Koha::Plugins->call('patron_barcode_transform', \$patron_id ); + Koha::Plugins->call( 'patron_barcode_transform', \$patron_id ); $status = $ils->renew_all( $patron_id, $patron_pwd, $fee_ack ); @@ -1648,13 +1726,15 @@ sub send_acs_status { my $msg = ACS_STATUS; ($server) or die "send_acs_status error: no \$server argument received"; - my $account = $server->{account} or die "send_acs_status error: no 'account' in \$server object:\n" . Dumper($server); - my $policy = $server->{policy} or die "send_acs_status error: no 'policy' in \$server object:\n" . Dumper($server); - my $ils = $server->{ils} or die "send_acs_status error: no 'ils' in \$server object:\n" . Dumper($server); - my $sip_username = $server->{sip_username} or die "send_acs_status error: no 'sip_username' in \$server object:\n" . Dumper($server); + my $account = $server->{account} + or die "send_acs_status error: no 'account' in \$server object:\n" . Dumper($server); + my $policy = $server->{policy} or die "send_acs_status error: no 'policy' in \$server object:\n" . Dumper($server); + my $ils = $server->{ils} or die "send_acs_status error: no 'ils' in \$server object:\n" . Dumper($server); + my $sip_username = $server->{sip_username} + or die "send_acs_status error: no 'sip_username' in \$server object:\n" . Dumper($server); my ( $online_status, $checkin_ok, $checkout_ok, $ACS_renewal_policy ); my ( $status_update_ok, $offline_ok, $timeout, $retries ); - my $sip_user = Koha::Patrons->find({ userid => $sip_username }); + my $sip_user = Koha::Patrons->find( { userid => $sip_username } ); die "send_acs_status error: sip_username cannot be found in DB or DB cannot be reached" unless $sip_user; $online_status = 'Y'; @@ -1663,7 +1743,7 @@ sub send_acs_status { $ACS_renewal_policy = sipbool( $policy->{renewal} ); $status_update_ok = sipbool( $ils->status_update_ok ); $offline_ok = sipbool( $ils->offline_ok ); - $timeout = $server->get_timeout({ policy => 1 }); + $timeout = $server->get_timeout( { policy => 1 } ); $retries = sprintf( "%03d", $policy->{retries} ); if ( length($retries) != 3 ) { @@ -1709,7 +1789,8 @@ sub send_acs_status { if ( defined( $account->{print_width} ) && defined($print_line) - && $account->{print_width} < length($print_line) ) { + && $account->{print_width} < length($print_line) ) + { siplog( "LOG_WARNING", "send_acs_status: print line '%s' too long. Truncating", $print_line ); $print_line = substr( $print_line, 0, $account->{print_width} ); } @@ -1744,7 +1825,7 @@ sub patron_status_string { $server->{account}->{overdues_block_checkout} ? boolspace( $patron->too_many_overdue ) : q{ }, boolspace( $patron->too_many_renewal ), boolspace( $patron->too_many_claim_return ), - boolspace( $patron->too_many_lost( $server ) ), + boolspace( $patron->too_many_lost($server) ), boolspace( $patron->excessive_fines ), boolspace( $patron->excessive_fees ), boolspace( $patron->recall_overdue ), @@ -1780,18 +1861,18 @@ sub desensitize { my $server = $params->{server}; my $patron_categories = $server->{account}->{inhouse_patron_categories} // q{}; - my $item_types = $server->{account}->{inhouse_item_types} // q{}; + my $item_types = $server->{account}->{inhouse_item_types} // q{}; # If no patron categories or item types are set for never desensitize, no need to do anything return $desensitize unless $patron_categories || $item_types; - my $patron_category = $patron->ptype(); - my @patron_categories = split( /,/, $patron_categories ); + my $patron_category = $patron->ptype(); + my @patron_categories = split( /,/, $patron_categories ); my $found_patron_category = grep( /^$patron_category$/, @patron_categories ); return 0 if $found_patron_category; - my $item_type = $item->itemtype; - my @item_types = split( /,/, $item_types ); + my $item_type = $item->itemtype; + my @item_types = split( /,/, $item_types ); my $found_item_type = grep( /^$item_type$/, @item_types ); return 0 if $found_item_type; diff --git a/C4/SIP/Trapper.pm b/C4/SIP/Trapper.pm index 658c779188..cfbfd2aff0 100644 --- a/C4/SIP/Trapper.pm +++ b/C4/SIP/Trapper.pm @@ -28,8 +28,7 @@ sub TIEHANDLE { sub PRINT { my $self = shift; $Log::Log4perl::caller_depth += 3; - my $logger = - Koha::Logger->get( { interface => 'sip', category => 'STDERR' } ); + my $logger = Koha::Logger->get( { interface => 'sip', category => 'STDERR' } ); warn @_; $logger->warn(@_); $Log::Log4perl::caller_depth -= 3; @@ -55,6 +54,6 @@ sub OPEN { sub BINMODE { my ( $self, $mode ) = @_; binmode( STDOUT, $mode ); -}; +} 1; diff --git a/C4/SMS.pm b/C4/SMS.pm index eba203154c..54ecf53040 100644 --- a/C4/SMS.pm +++ b/C4/SMS.pm @@ -60,8 +60,6 @@ use warnings; use C4::Context; use File::Spec; - - =head1 METHODS =cut @@ -75,16 +73,18 @@ use File::Spec; =cut sub send_sms { - my $self = shift; - my $params= shift; + my $self = shift; + my $params = shift; + + foreach my $required_parameter (qw( message destination )) { - foreach my $required_parameter ( qw( message destination ) ) { # Should I warn in some way? - return unless defined $params->{ $required_parameter }; + return unless defined $params->{$required_parameter}; } eval { require SMS::Send; }; - if ( $@ ) { + if ($@) { + # we apparently don't have SMS::Send. Return a failure. return; } @@ -93,14 +93,15 @@ sub send_sms { my $driver = exists $params->{'driver'} ? $params->{'driver'} : $self->driver(); return ( undef, 'SMS_SEND_DRIVER_MISSING' ) unless $driver; - my ($sent, $sender); + my ( $sent, $sender ); my $subpath = $driver; $subpath =~ s|::|/|g; # Extract additional SMS::Send arguments from file my $sms_send_config = C4::Context->config('sms_send_config'); - my $conf_file = defined $sms_send_config + my $conf_file = + defined $sms_send_config ? File::Spec->catfile( $sms_send_config, $subpath ) : $subpath; $conf_file .= q{.yaml}; @@ -108,7 +109,7 @@ sub send_sms { my %args = (); if ( -f $conf_file ) { require YAML::XS; - my $conf = YAML::XS::LoadFile( $conf_file ); + my $conf = YAML::XS::LoadFile($conf_file); %args = map { q{_} . $_ => $conf->{$_} } keys %$conf; } @@ -141,6 +142,7 @@ sub send_sms { warn $@; return ( undef, $@ ); } + # warn 'failure' unless $sent; return $sent; } diff --git a/C4/Scheduler.pm b/C4/Scheduler.pm index e2f6d85f65..e0ba896cbd 100644 --- a/C4/Scheduler.pm +++ b/C4/Scheduler.pm @@ -22,7 +22,8 @@ use Modern::Perl; use C4::Context; use Schedule::At; -our (@ISA, @EXPORT_OK); +our ( @ISA, @EXPORT_OK ); + BEGIN { require Exporter; @ISA = qw(Exporter); @@ -51,7 +52,8 @@ This will return all scheduled jobs sub get_jobs { my $jobs = get_at_jobs(); -# add call to get cron jobs here too + + # add call to get cron jobs here too return ($jobs); } @@ -62,8 +64,8 @@ This will return all At scheduled jobs =cut sub get_at_jobs { - my %jobs = Schedule::At::getJobs(); - return (\%jobs); + my %jobs = Schedule::At::getJobs(); + return ( \%jobs ); } =head2 get_at_job($id) @@ -73,8 +75,8 @@ This will return the At job with the given id =cut sub get_at_job { - my ($id)=@_; - my %jobs = Schedule::At::getJobs(JOBID => $id); + my ($id) = @_; + my %jobs = Schedule::At::getJobs( JOBID => $id ); } =head2 add_at_job ($time,$command) @@ -86,12 +88,13 @@ Returns true if the job is added to the queue and false otherwise. =cut sub add_at_job { - my ($time,$command) = @_; - # FIXME - a description of the task to be run + my ( $time, $command ) = @_; + + # FIXME - a description of the task to be run # may be a better tag, since the tag is displayed # in the job list that the administrator sees - e.g., # "run report foo, send to foo@bar.com" - Schedule::At::add(TIME => $time, COMMAND => $command, TAG => $command); + Schedule::At::add( TIME => $time, COMMAND => $command, TAG => $command ); # FIXME - this method of checking whether the job was added # to the queue is less than perfect: @@ -112,8 +115,8 @@ sub add_at_job { # and completed instantly, thus dropping off the queue. my $job_found = 0; eval { - my %jobs = Schedule::At::getJobs(TAG => $command); - $job_found = scalar(keys %jobs) > 0; + my %jobs = Schedule::At::getJobs( TAG => $command ); + $job_found = scalar( keys %jobs ) > 0; }; if ($@) { return 0; @@ -123,8 +126,8 @@ sub add_at_job { } sub remove_at_job { - my ($jobid)=@_; - Schedule::At::remove(JOBID => $jobid); + my ($jobid) = @_; + Schedule::At::remove( JOBID => $jobid ); } 1; diff --git a/C4/Scrubber.pm b/C4/Scrubber.pm index ccfa830585..57abd918ea 100644 --- a/C4/Scrubber.pm +++ b/C4/Scrubber.pm @@ -37,9 +37,8 @@ my %scrubbertypes = ( }, ); - sub new { - shift; # ignore our class we are wrapper + shift; # ignore our class we are wrapper my $type = (@_) ? shift : 'default'; if ( !exists $scrubbertypes{$type} ) { croak "New called with unrecognized type '$type'"; @@ -56,7 +55,6 @@ sub new { return $scrubber; } - 1; __END__ diff --git a/C4/Search.pm b/C4/Search.pm index ca8e79ab0f..6ae9ddcc8d 100644 --- a/C4/Search.pm +++ b/C4/Search.pm @@ -18,15 +18,16 @@ package C4::Search; use Modern::Perl; use C4::Context; use C4::Biblio qw( TransformMarcToKoha GetMarcFromKohaField GetFrameworkCode GetAuthorisedValueDesc GetBiblioData ); -use C4::Koha qw( getFacets GetVariationsOfISBN GetNormalizedUPC GetNormalizedEAN GetNormalizedOCLCNumber GetNormalizedISBN getitemtypeimagelocation ); +use C4::Koha + qw( getFacets GetVariationsOfISBN GetNormalizedUPC GetNormalizedEAN GetNormalizedOCLCNumber GetNormalizedISBN getitemtypeimagelocation ); use Koha::DateUtils; use Koha::Libraries; use Koha::SearchEngine::QueryBuilder; use Lingua::Stem; use XML::Simple; -use C4::XSLT qw( XSLTParse4Display ); +use C4::XSLT qw( XSLTParse4Display ); use C4::Reserves qw( GetReserveStatus ); -use C4::Charset qw( SetUTF8Flag ); +use C4::Charset qw( SetUTF8Flag ); use Koha::AuthorisedValues; use Koha::ItemTypes; use Koha::Libraries; @@ -40,21 +41,22 @@ use Business::ISBN; use MARC::Record; use MARC::Field; -our (@ISA, @EXPORT_OK); +our ( @ISA, @EXPORT_OK ); + BEGIN { require Exporter; - @ISA = qw(Exporter); + @ISA = qw(Exporter); @EXPORT_OK = qw( - FindDuplicate - SimpleSearch - searchResults - getRecords - buildQuery - GetDistinctValues - enabled_staff_search_views - new_record_from_zebra - z3950_search_args - getIndexes + FindDuplicate + SimpleSearch + searchResults + getRecords + buildQuery + GetDistinctValues + enabled_staff_search_views + new_record_from_zebra + z3950_search_args + getIndexes ); } @@ -86,8 +88,8 @@ This function attempts to find duplicate records using a hard-coded, fairly simp sub FindDuplicate { my ($record) = @_; - my $dbh = C4::Context->dbh; - my $result = TransformMarcToKoha({ record => $record }); + my $dbh = C4::Context->dbh; + my $result = TransformMarcToKoha( { record => $record } ); my $sth; my $query; @@ -98,12 +100,11 @@ sub FindDuplicate { $result->{isbn} =~ s/\s+$//; $result->{isbn} =~ s/\|/OR/; $query = "isbn:$result->{isbn}"; - } - else { + } else { - my $titleindex = 'ti,ext'; + my $titleindex = 'ti,ext'; my $authorindex = 'au,ext'; - my $op = 'AND'; + my $op = 'AND'; $result->{title} =~ s /\\//g; $result->{title} =~ s /\"//g; @@ -111,7 +112,7 @@ sub FindDuplicate { $result->{title} =~ s /\)//g; $query = "$titleindex:\"$result->{title}\""; - if ( $result->{author} ) { + if ( $result->{author} ) { $result->{author} =~ s /\\//g; $result->{author} =~ s /\"//g; $result->{author} =~ s /\(//g; @@ -121,17 +122,17 @@ sub FindDuplicate { } } - my $searcher = Koha::SearchEngine::Search->new({index => $Koha::SearchEngine::BIBLIOS_INDEX}); - my ( $error, $searchresults, undef ) = $searcher->simple_search_compat($query,0,50); + my $searcher = Koha::SearchEngine::Search->new( { index => $Koha::SearchEngine::BIBLIOS_INDEX } ); + my ( $error, $searchresults, undef ) = $searcher->simple_search_compat( $query, 0, 50 ); my @results; - if (!defined $error) { - foreach my $possible_duplicate_record (@{$searchresults}) { + if ( !defined $error ) { + foreach my $possible_duplicate_record ( @{$searchresults} ) { my $marcrecord = new_record_from_zebra( 'biblioserver', $possible_duplicate_record ); - my $result = TransformMarcToKoha({ record => $marcrecord }); + my $result = TransformMarcToKoha( { record => $marcrecord } ); # FIXME :: why 2 $biblionumber ? if ($result) { @@ -207,15 +208,16 @@ $template->param(result=>\@results); =cut sub SimpleSearch { - my ( $query, $offset, $max_results, $servers, %options ) = @_; + my ( $query, $offset, $max_results, $servers, %options ) = @_; return ( 'No query entered', undef, undef ) unless $query; + # FIXME hardcoded value. See catalog/search.pl & opac-search.pl too. - my @servers = defined ( $servers ) ? @$servers : ( 'biblioserver' ); + my @servers = defined($servers) ? @$servers : ('biblioserver'); my @zoom_queries; my @tmpresults; my @zconns; - my $results = []; + my $results = []; my $total_hits = 0; # Initialize & Search Zebra @@ -223,27 +225,23 @@ sub SimpleSearch { eval { $zconns[$i] = C4::Context->Zconn( $servers[$i], 1 ); $query =~ s/:/=/g unless $options{skip_normalize}; - $zoom_queries[$i] = ZOOM::Query::CCL2RPN->new( $query, $zconns[$i]); - $tmpresults[$i] = $zconns[$i]->search( $zoom_queries[$i] ); + $zoom_queries[$i] = ZOOM::Query::CCL2RPN->new( $query, $zconns[$i] ); + $tmpresults[$i] = $zconns[$i]->search( $zoom_queries[$i] ); # error handling my $error = - $zconns[$i]->errmsg() . " (" - . $zconns[$i]->errcode() . ") " - . $zconns[$i]->addinfo() . " " - . $zconns[$i]->diagset(); + $zconns[$i]->errmsg() . " (" + . $zconns[$i]->errcode() . ") " + . $zconns[$i]->addinfo() . " " + . $zconns[$i]->diagset(); return ( $error, undef, undef ) if $zconns[$i]->errcode(); }; if ($@) { # caught a ZOOM::Exception - my $error = - $@->message() . " (" - . $@->code() . ") " - . $@->addinfo() . " " - . $@->diagset(); - warn $error." for query: $query"; + my $error = $@->message() . " (" . $@->code() . ") " . $@->addinfo() . " " . $@->diagset(); + warn $error . " for query: $query"; return ( $error, undef, undef ); } } @@ -252,9 +250,9 @@ sub SimpleSearch { \@zconns, \@tmpresults, sub { - my ($i, $size) = @_; + my ( $i, $size ) = @_; my $first_record = defined($offset) ? $offset + 1 : 1; - my $hits = $tmpresults[ $i - 1 ]->size(); + my $hits = $tmpresults[ $i - 1 ]->size(); $total_hits += $hits; my $last_record = $hits; if ( defined $max_results && $offset + $max_results < $hits ) { @@ -263,8 +261,7 @@ sub SimpleSearch { for my $j ( $first_record .. $last_record ) { my $record = eval { - $tmpresults[ $i - 1 ]->record( $j - 1 )->raw() - ; # 0 indexed + $tmpresults[ $i - 1 ]->record( $j - 1 )->raw(); # 0 indexed }; push @{$results}, $record if defined $record; } @@ -296,8 +293,8 @@ See verbose embedded documentation. sub getRecords { my ( - $koha_query, $simple_query, $sort_by_ref, $servers_ref, - $results_per_page, $offset, $branches, $itemtypes, + $koha_query, $simple_query, $sort_by_ref, $servers_ref, + $results_per_page, $offset, $branches, $itemtypes, $query_type, $scan, $opac ) = @_; @@ -324,29 +321,29 @@ sub getRecords { for ( my $i = 0 ; $i < @servers ; $i++ ) { $zconns[$i] = C4::Context->Zconn( $servers[$i], 1 ); -# perform the search, create the results objects -# if this is a local search, use the $koha-query, if it's a federated one, use the federated-query - my $query_to_use = ($servers[$i] =~ /biblioserver/) ? $koha_query : $simple_query; + # perform the search, create the results objects + # if this is a local search, use the $koha-query, if it's a federated one, use the federated-query + my $query_to_use = ( $servers[$i] =~ /biblioserver/ ) ? $koha_query : $simple_query; Koha::Logger->get->debug($simple_query) if $scan; # Check if we've got a query_type defined, if so, use it eval { if ($query_type) { - if ($query_type =~ /^ccl/) { + if ( $query_type =~ /^ccl/ ) { $query_to_use =~ s/\:/\=/g; # change : to = last minute (FIXME) - $results[$i] = $zconns[$i]->search(ZOOM::Query::CCL2RPN->new($query_to_use, $zconns[$i])); - } elsif ($query_type =~ /^cql/) { - $results[$i] = $zconns[$i]->search(ZOOM::Query::CQL->new($query_to_use, $zconns[$i])); - } elsif ($query_type =~ /^pqf/) { - $results[$i] = $zconns[$i]->search(ZOOM::Query::PQF->new($query_to_use, $zconns[$i])); + $results[$i] = $zconns[$i]->search( ZOOM::Query::CCL2RPN->new( $query_to_use, $zconns[$i] ) ); + } elsif ( $query_type =~ /^cql/ ) { + $results[$i] = $zconns[$i]->search( ZOOM::Query::CQL->new( $query_to_use, $zconns[$i] ) ); + } elsif ( $query_type =~ /^pqf/ ) { + $results[$i] = $zconns[$i]->search( ZOOM::Query::PQF->new( $query_to_use, $zconns[$i] ) ); } else { warn "Unknown query_type '$query_type'. Results undetermined."; } } elsif ($scan) { - $results[$i] = $zconns[$i]->scan( ZOOM::Query::CCL2RPN->new($query_to_use, $zconns[$i])); + $results[$i] = $zconns[$i]->scan( ZOOM::Query::CCL2RPN->new( $query_to_use, $zconns[$i] ) ); } else { - $results[$i] = $zconns[$i]->search(ZOOM::Query::CCL2RPN->new($query_to_use, $zconns[$i])); + $results[$i] = $zconns[$i]->search( ZOOM::Query::CCL2RPN->new( $query_to_use, $zconns[$i] ) ); } }; if ($@) { @@ -359,47 +356,33 @@ sub getRecords { foreach my $sort (@sort_by) { if ( $sort eq "author_az" || $sort eq "author_asc" ) { $sort_by .= "1=1003 {'hits'} = $size; - my $times; - if ( $offset + $results_per_page <= $size ) { - $times = $offset + $results_per_page; + # loop through the results + $results_hash->{'hits'} = $size; + my $times; + if ( $offset + $results_per_page <= $size ) { + $times = $offset + $results_per_page; + } else { + $times = $size; + } + + for ( my $j = $offset ; $j < $times ; $j++ ) { + my $record; + + ## Check if it's an index scan + if ($scan) { + my ( $term, $occ ) = $results[ $i - 1 ]->display_term($j); + + # here we create a minimal MARC record and hand it off to the + # template just like a normal result ... perhaps not ideal, but + # it works for now + my $tmprecord = MARC::Record->new(); + $tmprecord->encoding('UTF-8'); + my $tmptitle; + my $tmpauthor; + + # the minimal record in author/title (depending on MARC flavour) + if ( C4::Context->preference("marcflavour") eq "UNIMARC" ) { + $tmptitle = MARC::Field->new( + '200', ' ', ' ', + a => $term, + f => $occ + ); + $tmprecord->append_fields($tmptitle); + } else { + $tmptitle = MARC::Field->new( '245', ' ', ' ', a => $term, ); + $tmpauthor = MARC::Field->new( '100', ' ', ' ', a => $occ, ); + $tmprecord->append_fields($tmptitle); + $tmprecord->append_fields($tmpauthor); + } + $results_hash->{'RECORDS'}[$j] = + $tmprecord->as_usmarc(); } + + # not an index scan else { - $times = $size; + $record = $results[ $i - 1 ]->record($j)->raw(); + + # warn "RECORD $j:".$record; + $results_hash->{'RECORDS'}[$j] = $record; } - for ( my $j = $offset ; $j < $times ; $j++ ) { - my $record; + } + $results_hashref->{ $servers[ $i - 1 ] } = $results_hash; - ## Check if it's an index scan - if ($scan) { - my ( $term, $occ ) = $results[ $i - 1 ]->display_term($j); + # Fill the facets while we're looping, but only for the + # biblioserver and not for a scan + if ( !$scan && $servers[ $i - 1 ] =~ /biblioserver/ ) { + $facets_counter = GetFacets( $results[ $i - 1 ] ); + $facets_info = _get_facets_info($facets); + } - # here we create a minimal MARC record and hand it off to the - # template just like a normal result ... perhaps not ideal, but - # it works for now - my $tmprecord = MARC::Record->new(); - $tmprecord->encoding('UTF-8'); - my $tmptitle; - my $tmpauthor; - - # the minimal record in author/title (depending on MARC flavour) - if ( C4::Context->preference("marcflavour") eq - "UNIMARC" ) - { - $tmptitle = MARC::Field->new( - '200', ' ', ' ', - a => $term, - f => $occ - ); - $tmprecord->append_fields($tmptitle); - } - else { - $tmptitle = - MARC::Field->new( '245', ' ', ' ', a => $term, ); - $tmpauthor = - MARC::Field->new( '100', ' ', ' ', a => $occ, ); - $tmprecord->append_fields($tmptitle); - $tmprecord->append_fields($tmpauthor); - } - $results_hash->{'RECORDS'}[$j] = - $tmprecord->as_usmarc(); - } - - # not an index scan - else { - $record = $results[ $i - 1 ]->record($j)->raw(); - # warn "RECORD $j:".$record; - $results_hash->{'RECORDS'}[$j] = $record; - } - - } - $results_hashref->{ $servers[ $i - 1 ] } = $results_hash; - - # Fill the facets while we're looping, but only for the - # biblioserver and not for a scan - if ( !$scan && $servers[ $i - 1 ] =~ /biblioserver/ ) { - $facets_counter = GetFacets( $results[ $i - 1 ] ); - $facets_info = _get_facets_info( $facets ); - } - - # BUILD FACETS - if ( $servers[ $i - 1 ] =~ /biblioserver/ ) { - for my $link_value ( - sort { $a cmp $b } keys %$facets_counter - ) + # BUILD FACETS + if ( $servers[ $i - 1 ] =~ /biblioserver/ ) { + for my $link_value ( sort { $a cmp $b } keys %$facets_counter ) { + my @this_facets_array; + for my $one_facet ( + sort { $facets_counter->{$link_value}->{$b} <=> $facets_counter->{$link_value}->{$a} } + keys %{ $facets_counter->{$link_value} } + ) { - my @this_facets_array; - for my $one_facet ( - sort { - $facets_counter->{$link_value} - ->{$b} <=> $facets_counter->{$link_value} - ->{$a} - } keys %{ $facets_counter->{$link_value} } - ) - { -# Sanitize the link value : parenthesis, question and exclamation mark will cause errors with CCL - my $facet_link_value = $one_facet; - $facet_link_value =~ s/[()!?¡¿؟]/ /g; + # Sanitize the link value : parenthesis, question and exclamation mark will cause errors with CCL + my $facet_link_value = $one_facet; + $facet_link_value =~ s/[()!?¡¿؟]/ /g; - # fix the length that will display in the label, - my $facet_label_value = $one_facet; - my $facet_max_length = C4::Context->preference( - 'FacetLabelTruncationLength') - || 20; - $facet_label_value = - substr( $one_facet, 0, $facet_max_length ) - . "..." - if length($facet_label_value) > - $facet_max_length; + # fix the length that will display in the label, + my $facet_label_value = $one_facet; + my $facet_max_length = C4::Context->preference('FacetLabelTruncationLength') + || 20; + $facet_label_value = substr( $one_facet, 0, $facet_max_length ) . "..." + if length($facet_label_value) > $facet_max_length; # if it's a branch, label by the name, not the code, - if ( $link_value =~ /branch/ ) { - if ( defined $branches - && ref($branches) eq "HASH" - && defined $branches->{$one_facet} - && ref( $branches->{$one_facet} ) eq - "HASH" ) - { - $facet_label_value = - $branches->{$one_facet} - ->{'branchname'}; - } - else { - $facet_label_value = "*"; - } + if ( $link_value =~ /branch/ ) { + if ( defined $branches + && ref($branches) eq "HASH" + && defined $branches->{$one_facet} + && ref( $branches->{$one_facet} ) eq "HASH" ) + { + $facet_label_value = $branches->{$one_facet}->{'branchname'}; + } else { + $facet_label_value = "*"; } - - # if it's a itemtype, label by the name, not the code, - if ( $link_value =~ /itype/ ) { - if ( defined $itemtypes - && ref($itemtypes) eq "HASH" - && defined $itemtypes->{$one_facet} - && ref( $itemtypes->{$one_facet} ) eq - "HASH" ) - { - $facet_label_value = - $itemtypes->{$one_facet} - ->{translated_description}; - } - } - - # also, if it's a location code, use the name instead of the code - if ( $link_value =~ /location/ ) { - # TODO Retrieve all authorised values at once, instead of 1 query per entry - my $av = Koha::AuthorisedValues->search({ category => 'LOC', authorised_value => $one_facet }); - $facet_label_value = $av->count ? $av->next->opac_description : ''; - } - - # also, if it's a collection code, use the name instead of the code - if ( $link_value =~ /ccode/ ) { - # TODO Retrieve all authorised values at once, instead of 1 query per entry - my $av = Koha::AuthorisedValues->search({ category => 'CCODE', authorised_value => $one_facet }); - $facet_label_value = $av->count ? $av->next->opac_description : ''; - } - - # but we're down with the whole label being in the link's title. - push @this_facets_array, - { - facet_count => - $facets_counter->{$link_value} - ->{$one_facet}, - facet_label_value => $facet_label_value, - facet_title_value => $one_facet, - facet_link_value => $facet_link_value, - type_link_value => $link_value, - } - if ($facet_label_value); } - push @facets_loop, - { - type_link_value => $link_value, - type_id => $link_value . "_id", - "type_label_" - . $facets_info->{$link_value}->{'label_value'} => - 1, - label => $facets_info->{$link_value}->{'label_value'}, - facets => \@this_facets_array, - } - unless ( - ( - $facets_info->{$link_value}->{'label_value'} =~ - /Libraries/ - ) - and ( Koha::Libraries->search->count == 1 ) - ); + # if it's a itemtype, label by the name, not the code, + if ( $link_value =~ /itype/ ) { + if ( defined $itemtypes + && ref($itemtypes) eq "HASH" + && defined $itemtypes->{$one_facet} + && ref( $itemtypes->{$one_facet} ) eq "HASH" ) + { + $facet_label_value = $itemtypes->{$one_facet}->{translated_description}; + } + } + + # also, if it's a location code, use the name instead of the code + if ( $link_value =~ /location/ ) { + + # TODO Retrieve all authorised values at once, instead of 1 query per entry + my $av = + Koha::AuthorisedValues->search( { category => 'LOC', authorised_value => $one_facet } ); + $facet_label_value = $av->count ? $av->next->opac_description : ''; + } + + # also, if it's a collection code, use the name instead of the code + if ( $link_value =~ /ccode/ ) { + + # TODO Retrieve all authorised values at once, instead of 1 query per entry + my $av = Koha::AuthorisedValues->search( + { category => 'CCODE', authorised_value => $one_facet } ); + $facet_label_value = $av->count ? $av->next->opac_description : ''; + } + + # but we're down with the whole label being in the link's title. + push @this_facets_array, + { + facet_count => $facets_counter->{$link_value}->{$one_facet}, + facet_label_value => $facet_label_value, + facet_title_value => $one_facet, + facet_link_value => $facet_link_value, + type_link_value => $link_value, + } + if ($facet_label_value); } + + push @facets_loop, + { + type_link_value => $link_value, + type_id => $link_value . "_id", + "type_label_" . $facets_info->{$link_value}->{'label_value'} => 1, + label => $facets_info->{$link_value}->{'label_value'}, + facets => \@this_facets_array, + } + unless ( ( $facets_info->{$link_value}->{'label_value'} =~ /Libraries/ ) + and ( Koha::Libraries->search->count == 1 ) ); } } - ); + } + ); # This sorts the facets into alphabetical order if (@facets_loop) { foreach my $f (@facets_loop) { - if( C4::Context->preference('FacetOrder') eq 'Alphabetical' ){ + if ( C4::Context->preference('FacetOrder') eq 'Alphabetical' ) { $f->{facets} = - [ sort { uc($a->{facet_label_value}) cmp uc($b->{facet_label_value}) } @{ $f->{facets} } ]; + [ sort { uc( $a->{facet_label_value} ) cmp uc( $b->{facet_label_value} ) } @{ $f->{facets} } ]; } } } @@ -614,10 +570,10 @@ sub GetFacets { my $use_zebra_facets = C4::Context->config('use_zebra_facets') // 0; - if ( $use_zebra_facets ) { - $facets = _get_facets_from_zebra( $rs ); + if ($use_zebra_facets) { + $facets = _get_facets_from_zebra($rs); } else { - $facets = _get_facets_from_records( $rs ); + $facets = _get_facets_from_records($rs); } return $facets; @@ -631,20 +587,20 @@ sub _get_facets_from_records { my $facets_config = getFacets(); my $facets = {}; my $size = $rs->size(); - my $jmax = $size > $facets_maxrecs - ? $facets_maxrecs - : $size; + my $jmax = + $size > $facets_maxrecs + ? $facets_maxrecs + : $size; for ( my $j = 0 ; $j < $jmax ; $j++ ) { - my $marc_record = new_record_from_zebra ( - 'biblioserver', - $rs->record( $j )->raw() + my $marc_record = new_record_from_zebra( + 'biblioserver', + $rs->record($j)->raw() ); - if ( ! defined $marc_record ) { - warn "ERROR DECODING RECORD - $@: " . - $rs->record( $j )->raw(); + if ( !defined $marc_record ) { + warn "ERROR DECODING RECORD - $@: " . $rs->record($j)->raw(); next; } @@ -674,25 +630,27 @@ sub _get_facets_data_from_record { my @used_datas = (); - foreach my $tag ( @{ $facet->{ tags } } ) { + foreach my $tag ( @{ $facet->{tags} } ) { # tag number is the first three digits - my $tag_num = substr( $tag, 0, 3 ); + my $tag_num = substr( $tag, 0, 3 ); + # subfields are the remainder my $subfield_letters = substr( $tag, 3 ); - my @fields = $marc_record->field( $tag_num ); + my @fields = $marc_record->field($tag_num); foreach my $field (@fields) { + # If $field->indicator(1) eq 'z', it means it is a 'see from' # field introduced because of IncludeSeeFromInSearches, so skip it next if $field->indicator(1) eq 'z'; - my $data = $field->as_string( $subfield_letters, $facet->{ sep } ); + my $data = $field->as_string( $subfield_letters, $facet->{sep} ); $data =~ s/\s*(?{ $facet->{ idx } }->{ $data }++; + $facets_counter->{ $facet->{idx} }->{$data}++; } } } @@ -719,21 +677,24 @@ sub _get_facets_from_zebra { my $rs = shift; # save current elementSetName - my $elementSetName = $rs->option( 'elementSetName' ); + my $elementSetName = $rs->option('elementSetName'); my $facets_loop = getFacets(); - my $facets_data = {}; - # loop through defined facets and fill the facets hashref - foreach my $facet ( @$facets_loop ) { + my $facets_data = {}; - my $idx = $facet->{ idx }; - my $sep = $facet->{ sep }; + # loop through defined facets and fill the facets hashref + foreach my $facet (@$facets_loop) { + + my $idx = $facet->{idx}; + my $sep = $facet->{sep}; my $facet_values = _get_facet_from_result_set( $idx, $rs, $sep ); - if ( $facet_values ) { + if ($facet_values) { + # we've actually got a result - $facets_data->{ $idx } = $facet_values; + $facets_data->{$idx} = $facet_values; } } + # set elementSetName to its previous value to avoid side effects $rs->option( elementSetName => $elementSetName ); @@ -768,28 +729,31 @@ sub _get_facet_from_result_set { my $internal_sep = '<*>'; my $facetMaxCount = C4::Context->preference('FacetMaxCount') // 20; - return if ( ! defined $facet_idx || ! defined $rs ); + return if ( !defined $facet_idx || !defined $rs ); + # zebra's facet element, untokenized index my $facet_element = 'zebra::facet::' . $facet_idx . ':0:' . $facetMaxCount; + # configure zebra results for retrieving the desired facet $rs->option( elementSetName => $facet_element ); + # get the facet record from result set - my $facet = $rs->record( 0 )->raw; + my $facet = $rs->record(0)->raw; + # if the facet has no restuls... return if !defined $facet; + # TODO: benchmark DOM vs. SAX performance - my $facet_dom = XML::LibXML->load_xml( - string => ($facet) - ); - my @terms = $facet_dom->getElementsByTagName('term'); - return if ! @terms; + my $facet_dom = XML::LibXML->load_xml( string => ($facet) ); + my @terms = $facet_dom->getElementsByTagName('term'); + return if !@terms; my $facets = {}; - foreach my $term ( @terms ) { + foreach my $term (@terms) { my $facet_value = $term->textContent; $facet_value =~ s/\s*(?{ $facet_value } += $term->getAttribute( 'occur' ); + $facets->{$facet_value} += $term->getAttribute('occur'); } return $facets; @@ -810,8 +774,8 @@ sub _get_facets_info { my $facets_info = {}; - for my $facet ( @$facets ) { - $facets_info->{ $facet->{ idx } }->{ label_value } = $facet->{ label }; + for my $facet (@$facets) { + $facets_info->{ $facet->{idx} }->{label_value} = $facet->{label}; } return $facets_info; @@ -820,24 +784,22 @@ sub _get_facets_info { # TRUNCATION sub _detect_truncation { my ( $operand, $index ) = @_; - my ( @nontruncated, @righttruncated, @lefttruncated, @rightlefttruncated, - @regexpr ); + my ( + @nontruncated, @righttruncated, @lefttruncated, @rightlefttruncated, + @regexpr + ); $operand =~ s/^ //g; my @wordlist = split( /\s/, $operand ); foreach my $word (@wordlist) { if ( $word =~ s/^\*([^\*]+)\*$/$1/ ) { push @rightlefttruncated, $word; - } - elsif ( $word =~ s/^\*([^\*]+)$/$1/ ) { + } elsif ( $word =~ s/^\*([^\*]+)$/$1/ ) { push @lefttruncated, $word; - } - elsif ( $word =~ s/^([^\*]+)\*$/$1/ ) { + } elsif ( $word =~ s/^([^\*]+)\*$/$1/ ) { push @righttruncated, $word; - } - elsif ( index( $word, "*" ) < 0 ) { + } elsif ( index( $word, "*" ) < 0 ) { push @nontruncated, $word; - } - else { + } else { push @regexpr, $word; } } @@ -849,9 +811,9 @@ sub _detect_truncation { # STEMMING sub _build_stemmed_operand { - my ($operand,$lang) = @_; - require Lingua::Stem::Snowball ; - my $stemmed_operand=q{}; + my ( $operand, $lang ) = @_; + require Lingua::Stem::Snowball; + my $stemmed_operand = q{}; # Stemmer needs language return $operand unless $lang; @@ -863,24 +825,27 @@ sub _build_stemmed_operand { # results (e.g., "23 x 29 cm." from the 300$c). Bug 2098. return $operand if $operand =~ /\d/; -# FIXME: the locale should be set based on the user's language and/or search choice + # FIXME: the locale should be set based on the user's language and/or search choice #warn "$lang"; # Make sure we only use the first two letters from the language code - $lang = lc(substr($lang, 0, 2)); + $lang = lc( substr( $lang, 0, 2 ) ); + # The language codes for the two variants of Norwegian will now be "nb" and "nn", # none of which Lingua::Stem::Snowball can use, so we need to "translate" them - if ($lang eq 'nb' || $lang eq 'nn') { - $lang = 'no'; + if ( $lang eq 'nb' || $lang eq 'nn' ) { + $lang = 'no'; } - my $stemmer = Lingua::Stem::Snowball->new( lang => $lang, - encoding => "UTF-8" ); + my $stemmer = Lingua::Stem::Snowball->new( + lang => $lang, + encoding => "UTF-8" + ); my @words = split( / /, $operand ); - my @stems = $stemmer->stem(\@words); + my @stems = $stemmer->stem( \@words ); for my $stem (@stems) { $stemmed_operand .= "$stem"; $stemmed_operand .= "?" - unless ( $stem =~ /(and$|or$|not$)/ ) || ( length($stem) < 3 ); + unless ( $stem =~ /(and$|or$|not$)/ ) || ( length($stem) < 3 ); $stemmed_operand .= " "; } @@ -891,8 +856,8 @@ sub _build_stemmed_operand { # FIELD WEIGHTING sub _build_weighted_query { -# FIELD WEIGHTING - This is largely experimental stuff. What I'm committing works -# pretty well but could work much better if we had a smarter query parser + # FIELD WEIGHTING - This is largely experimental stuff. What I'm committing works + # pretty well but could work much better if we had a smarter query parser my ( $operand, $stemmed_operand, $index ) = @_; my $stemming = C4::Context->preference("QueryStemming") || 0; my $weight_fields = C4::Context->preference("QueryWeightFields") || 0; @@ -903,18 +868,16 @@ sub _build_weighted_query { # Keyword, or, no index specified if ( ( $index eq 'kw' ) || ( !$index ) ) { - $weighted_query .= - "Title-cover,ext,r1=\"$operand\""; # exact title-cover - $weighted_query .= " or ti,ext,r2=\"$operand\""; # exact title + $weighted_query .= "Title-cover,ext,r1=\"$operand\""; # exact title-cover + $weighted_query .= " or ti,ext,r2=\"$operand\""; # exact title $weighted_query .= " or Title-cover,phr,r3=\"$operand\""; # phrase title - $weighted_query .= " or ti,wrdl,r4=\"$operand\""; # words in title - #$weighted_query .= " or any,ext,r4=$operand"; # exact any - #$weighted_query .=" or kw,wrdl,r5=\"$operand\""; # word list any + $weighted_query .= " or ti,wrdl,r4=\"$operand\""; # words in title + #$weighted_query .= " or any,ext,r4=$operand"; # exact any + #$weighted_query .=" or kw,wrdl,r5=\"$operand\""; # word list any $weighted_query .= " or wrdl,fuzzy,r8=\"$operand\"" - if $fuzzy_enabled; # add fuzzy, word list + if $fuzzy_enabled; # add fuzzy, word list $weighted_query .= " or wrdl,right-Truncation,r9=\"$stemmed_operand\"" - if ( $stemming and $stemmed_operand ) - ; # add stemming, right truncation + if ( $stemming and $stemmed_operand ); # add stemming, right truncation $weighted_query .= " or wrdl,r9=\"$operand\""; # embedded sorting: 0 a-z; 1 z-a @@ -946,16 +909,16 @@ sub _build_weighted_query { #TODO: build better cases based on specific search indexes else { $weighted_query .= " $index,ext,r1=\"$operand\""; # exact index - #$weighted_query .= " or (title-sort-az=0 or $index,startswithnt,st-word,r3=$operand #)"; - $weighted_query .= " or $index,phr,r3=\"$operand\""; # phrase index - $weighted_query .= " or $index,wrdl,r6=\"$operand\""; # word list index + #$weighted_query .= " or (title-sort-az=0 or $index,startswithnt,st-word,r3=$operand #)"; + $weighted_query .= " or $index,phr,r3=\"$operand\""; # phrase index + $weighted_query .= " or $index,wrdl,r6=\"$operand\""; # word list index $weighted_query .= " or $index,wrdl,fuzzy,r8=\"$operand\"" - if $fuzzy_enabled; # add fuzzy, word list + if $fuzzy_enabled; # add fuzzy, word list $weighted_query .= " or $index,wrdl,rt,r9=\"$stemmed_operand\"" - if ( $stemming and $stemmed_operand ); # add stemming, right truncation + if ( $stemming and $stemmed_operand ); # add stemming, right truncation } - $weighted_query .= "))"; # close rank specification + $weighted_query .= "))"; # close rank specification return $weighted_query; } @@ -965,225 +928,226 @@ Return an array with available indexes. =cut -sub getIndexes{ +sub getIndexes { my @indexes = ( - # biblio indexes - 'ab', - 'Abstract', - 'acqdate', - 'allrecords', - 'an', - 'Any', - 'at', - 'arl', - 'arp', - 'au', - 'aub', - 'aud', - 'audience', - 'auo', - 'aut', - 'Author', - 'Author-in-order ', - 'Author-personal-bibliography', - 'Authority-Number', - 'authtype', - 'bc', - 'Bib-level', - 'biblionumber', - 'bio', - 'biography', - 'callnum', - 'cfn', - 'Chronological-subdivision', - 'cn-bib-source', - 'cn-bib-sort', - 'cn-class', - 'cn-item', - 'cn-prefix', - 'cn-suffix', - 'cpn', - 'Code-institution', - 'Conference-name', - 'Conference-name-heading', - 'Conference-name-see', - 'Conference-name-seealso', - 'Content-type', - 'Control-number', - 'cnum', - 'Control-number-identifier', - 'cni', - 'copydate', - 'Corporate-name', - 'Corporate-name-heading', - 'Corporate-name-see', - 'Corporate-name-seealso', - 'Country-publication', - 'ctype', - 'curriculum', - 'date-entered-on-file', - 'Date-of-acquisition', - 'Date-of-publication', - 'Date-time-last-modified', - 'Dewey-classification', - 'Dissertation-information', - 'diss', - 'dtlm', - 'EAN', - 'extent', - 'fic', - 'fiction', - 'Form-subdivision', - 'format', - 'Geographic-subdivision', - 'he', - 'Heading', - 'Heading-use-main-or-added-entry', - 'Heading-use-series-added-entry ', - 'Heading-use-subject-added-entry', - 'Host-item', - 'id-other', - 'ident', - 'Identifier-standard', - 'Illustration-code', - 'Index-term-genre', - 'Index-term-uncontrolled', - 'Interest-age-level', - 'Interest-grade-level', - 'ISBN', - 'isbn', - 'ISSN', - 'issn', - 'itemtype', - 'kw', - 'Koha-Auth-Number', - 'l-format', - 'language', - 'language-original', - 'lc-card', - 'LC-card-number', - 'lcn', - 'lex', - 'lexile-number', - 'llength', - 'ln', - 'ln-audio', - 'ln-subtitle', - 'Local-classification', - 'Local-number', - 'Match-heading', - 'Match-heading-see-from', - 'Material-type', - 'mc-itemtype', - 'mc-rtype', - 'mus', - 'Multipart-resource-level', - 'mrl', - 'name', - 'Music-number', - 'Name-geographic', - 'Name-geographic-heading', - 'Name-geographic-see', - 'Name-geographic-seealso', - 'nb', - 'Note', - 'notes', - 'ns', - 'nt', - 'Other-control-number', - 'pb', - 'Personal-name', - 'Personal-name-heading', - 'Personal-name-see', - 'Personal-name-seealso', - 'pl', - 'Place-publication', - 'pn', - 'popularity', - 'pubdate', - 'Publisher', - 'Provider', - 'pv', - 'Reading-grade-level', - 'Record-control-number', - 'rcn', - 'Record-type', - 'rtype', - 'se', - 'See', - 'See-also', - 'sn', - 'Stock-number', - 'su', - 'Subject', - 'Subject-heading-thesaurus', - 'Subject-name-personal', - 'Subject-subdivision', - 'Summary', - 'Suppress', - 'su-geo', - 'su-na', - 'su-to', - 'su-ut', - 'ut', - 'Term-genre-form', - 'Term-genre-form-heading', - 'Term-genre-form-see', - 'Term-genre-form-seealso', - 'ti', - 'Title', - 'Title-cover', - 'Title-series', - 'Title-uniform', - 'Title-uniform-heading', - 'Title-uniform-see', - 'Title-uniform-seealso', - 'totalissues', - 'yr', - # items indexes - 'acqsource', - 'barcode', - 'bc', - 'branch', - 'ccode', - 'classification-source', - 'cn-sort', - 'coded-location-qualifier', - 'copynumber', - 'damaged', - 'datelastborrowed', - 'datelastseen', - 'holdingbranch', - 'homebranch', - 'issues', - 'item', - 'itemnumber', - 'itype', - 'Local-classification', - 'location', - 'lost', - 'materials-specified', - 'mc-ccode', - 'mc-itype', - 'mc-loc', - 'notforloan', - 'Number-local-acquisition', - 'onloan', - 'price', - 'renewals', - 'replacementprice', - 'replacementpricedate', - 'reserves', - 'restricted', - 'stack', - 'stocknumber', - 'inv', - 'uri', - 'withdrawn', + # biblio indexes + 'ab', + 'Abstract', + 'acqdate', + 'allrecords', + 'an', + 'Any', + 'at', + 'arl', + 'arp', + 'au', + 'aub', + 'aud', + 'audience', + 'auo', + 'aut', + 'Author', + 'Author-in-order ', + 'Author-personal-bibliography', + 'Authority-Number', + 'authtype', + 'bc', + 'Bib-level', + 'biblionumber', + 'bio', + 'biography', + 'callnum', + 'cfn', + 'Chronological-subdivision', + 'cn-bib-source', + 'cn-bib-sort', + 'cn-class', + 'cn-item', + 'cn-prefix', + 'cn-suffix', + 'cpn', + 'Code-institution', + 'Conference-name', + 'Conference-name-heading', + 'Conference-name-see', + 'Conference-name-seealso', + 'Content-type', + 'Control-number', + 'cnum', + 'Control-number-identifier', + 'cni', + 'copydate', + 'Corporate-name', + 'Corporate-name-heading', + 'Corporate-name-see', + 'Corporate-name-seealso', + 'Country-publication', + 'ctype', + 'curriculum', + 'date-entered-on-file', + 'Date-of-acquisition', + 'Date-of-publication', + 'Date-time-last-modified', + 'Dewey-classification', + 'Dissertation-information', + 'diss', + 'dtlm', + 'EAN', + 'extent', + 'fic', + 'fiction', + 'Form-subdivision', + 'format', + 'Geographic-subdivision', + 'he', + 'Heading', + 'Heading-use-main-or-added-entry', + 'Heading-use-series-added-entry ', + 'Heading-use-subject-added-entry', + 'Host-item', + 'id-other', + 'ident', + 'Identifier-standard', + 'Illustration-code', + 'Index-term-genre', + 'Index-term-uncontrolled', + 'Interest-age-level', + 'Interest-grade-level', + 'ISBN', + 'isbn', + 'ISSN', + 'issn', + 'itemtype', + 'kw', + 'Koha-Auth-Number', + 'l-format', + 'language', + 'language-original', + 'lc-card', + 'LC-card-number', + 'lcn', + 'lex', + 'lexile-number', + 'llength', + 'ln', + 'ln-audio', + 'ln-subtitle', + 'Local-classification', + 'Local-number', + 'Match-heading', + 'Match-heading-see-from', + 'Material-type', + 'mc-itemtype', + 'mc-rtype', + 'mus', + 'Multipart-resource-level', + 'mrl', + 'name', + 'Music-number', + 'Name-geographic', + 'Name-geographic-heading', + 'Name-geographic-see', + 'Name-geographic-seealso', + 'nb', + 'Note', + 'notes', + 'ns', + 'nt', + 'Other-control-number', + 'pb', + 'Personal-name', + 'Personal-name-heading', + 'Personal-name-see', + 'Personal-name-seealso', + 'pl', + 'Place-publication', + 'pn', + 'popularity', + 'pubdate', + 'Publisher', + 'Provider', + 'pv', + 'Reading-grade-level', + 'Record-control-number', + 'rcn', + 'Record-type', + 'rtype', + 'se', + 'See', + 'See-also', + 'sn', + 'Stock-number', + 'su', + 'Subject', + 'Subject-heading-thesaurus', + 'Subject-name-personal', + 'Subject-subdivision', + 'Summary', + 'Suppress', + 'su-geo', + 'su-na', + 'su-to', + 'su-ut', + 'ut', + 'Term-genre-form', + 'Term-genre-form-heading', + 'Term-genre-form-see', + 'Term-genre-form-seealso', + 'ti', + 'Title', + 'Title-cover', + 'Title-series', + 'Title-uniform', + 'Title-uniform-heading', + 'Title-uniform-see', + 'Title-uniform-seealso', + 'totalissues', + 'yr', - # subject related - ); + # items indexes + 'acqsource', + 'barcode', + 'bc', + 'branch', + 'ccode', + 'classification-source', + 'cn-sort', + 'coded-location-qualifier', + 'copynumber', + 'damaged', + 'datelastborrowed', + 'datelastseen', + 'holdingbranch', + 'homebranch', + 'issues', + 'item', + 'itemnumber', + 'itype', + 'Local-classification', + 'location', + 'lost', + 'materials-specified', + 'mc-ccode', + 'mc-itype', + 'mc-loc', + 'notforloan', + 'Number-local-acquisition', + 'onloan', + 'price', + 'renewals', + 'replacementprice', + 'replacementpricedate', + 'reserves', + 'restricted', + 'stack', + 'stocknumber', + 'inv', + 'uri', + 'withdrawn', + + # subject related + ); return \@indexes; } @@ -1205,7 +1169,7 @@ See verbose embedded documentation. =cut sub buildQuery { - my ( $operators, $operands, $indexes, $limits, $sort_by, $scan, $lang) = @_; + my ( $operators, $operands, $indexes, $limits, $sort_by, $scan, $lang ) = @_; my $query_desc; @@ -1216,10 +1180,10 @@ sub buildQuery { my @limits = $limits ? @$limits : (); my @sort_by = $sort_by ? @$sort_by : (); - my $stemming = C4::Context->preference("QueryStemming") || 0; - my $auto_truncation = C4::Context->preference("QueryAutoTruncate") || 0; - my $weight_fields = C4::Context->preference("QueryWeightFields") || 0; - my $fuzzy_enabled = C4::Context->preference("QueryFuzzy") || 0; + my $stemming = C4::Context->preference("QueryStemming") || 0; + my $auto_truncation = C4::Context->preference("QueryAutoTruncate") || 0; + my $weight_fields = C4::Context->preference("QueryWeightFields") || 0; + my $fuzzy_enabled = C4::Context->preference("QueryFuzzy") || 0; my $query = $operands[0] // ""; my $simple_query = $operands[0]; @@ -1248,12 +1212,12 @@ sub buildQuery { foreach my $this_limit (@limits) { next unless $this_limit; if ( $this_limit =~ /available/ ) { -# + # ## 'available' is defined as (items.onloan is NULL) and (items.itemlost = 0) ## In English: ## all records not indexed in the onloan register (zebra) and all records with a value of lost equal to 0 $availability_limit .= -"( (allrecords,AlwaysMatches='') and (not-onloan-count,st-numeric >= 1) and (lost,st-numeric=0) )"; + "( (allrecords,AlwaysMatches='') and (not-onloan-count,st-numeric >= 1) and (lost,st-numeric=0) )"; $limit_cgi .= "&limit=available"; $limit_desc .= ""; } @@ -1261,28 +1225,28 @@ sub buildQuery { # group_OR_limits, prefixed by mc- # OR every member of the group elsif ( $this_limit =~ /mc/ ) { - my ($k,$v) = split(/:/, $this_limit,2); + my ( $k, $v ) = split( /:/, $this_limit, 2 ); if ( $k !~ /mc-i(tem)?type/ ) { + # in case the mc-ccode value has complicating chars like ()'s inside it we wrap in quotes $this_limit =~ tr/"//d; - $this_limit = $k.':"'.$v.'"'; + $this_limit = $k . ':"' . $v . '"'; } $group_OR_limits{$k} .= " or " if $group_OR_limits{$k}; - $limit_desc .= " or " if $group_OR_limits{$k}; + $limit_desc .= " or " if $group_OR_limits{$k}; $group_OR_limits{$k} .= "$this_limit"; - $limit_cgi .= "&limit=" . uri_escape_utf8($this_limit); - $limit_desc .= " $this_limit"; - } - elsif ( $this_limit =~ '^multibranchlimit:|^branch:' ) { - $limit_cgi .= "&limit=" . uri_escape_utf8($this_limit); - $limit .= " and " if $limit || $query; - my $branchfield = C4::Context->preference('SearchLimitLibrary'); + $limit_cgi .= "&limit=" . uri_escape_utf8($this_limit); + $limit_desc .= " $this_limit"; + } elsif ( $this_limit =~ '^multibranchlimit:|^branch:' ) { + $limit_cgi .= "&limit=" . uri_escape_utf8($this_limit); + $limit .= " and " if $limit || $query; + my $branchfield = C4::Context->preference('SearchLimitLibrary'); my @branchcodes; - if( $this_limit =~ '^multibranchlimit:' ){ + if ( $this_limit =~ '^multibranchlimit:' ) { my ($group_id) = ( $this_limit =~ /^multibranchlimit:(.*)$/ ); - my $search_group = Koha::Library::Groups->find( $group_id ); - @branchcodes = map { $_->branchcode } $search_group->all_libraries; + my $search_group = Koha::Library::Groups->find($group_id); + @branchcodes = map { $_->branchcode } $search_group->all_libraries; @branchcodes = sort { $a cmp $b } @branchcodes; } else { @branchcodes = ( $this_limit =~ /^branch:(.*)$/ ); @@ -1291,42 +1255,42 @@ sub buildQuery { if (@branchcodes) { if ( $branchfield eq "homebranch" ) { $this_limit = sprintf "(%s)", join " or ", map { 'homebranch: ' . $_ } @branchcodes; - } - elsif ( $branchfield eq "holdingbranch" ) { + } elsif ( $branchfield eq "holdingbranch" ) { $this_limit = sprintf "(%s)", join " or ", map { 'holdingbranch: ' . $_ } @branchcodes; - } - else { - $this_limit = sprintf "(%s or %s)", - join( " or ", map { 'homebranch: ' . $_ } @branchcodes ), - join( " or ", map { 'holdingbranch: ' . $_ } @branchcodes ); + } else { + $this_limit = sprintf "(%s or %s)", + join( " or ", map { 'homebranch: ' . $_ } @branchcodes ), + join( " or ", map { 'holdingbranch: ' . $_ } @branchcodes ); } } - $limit .= "$this_limit"; + $limit .= "$this_limit"; $limit_desc .= " $this_limit"; } elsif ( $this_limit =~ '^search_filter:' ) { + # Here we will get the query as a string, append to the limits, and pass through buildQuery # again to clean the terms and handle nested filters - $limit_cgi .= "&limit=" . uri_escape_utf8($this_limit); + $limit_cgi .= "&limit=" . uri_escape_utf8($this_limit); my ($filter_id) = ( $this_limit =~ /^search_filter:(.*)$/ ); - my $search_filter = Koha::SearchFilters->find( $filter_id ); + my $search_filter = Koha::SearchFilters->find($filter_id); next unless $search_filter; - my ($expanded_lim, $query_lim) = $search_filter->expand_filter; + my ( $expanded_lim, $query_lim ) = $search_filter->expand_filter; push @$expanded_lim, $query_lim; - my ( $error, undef, undef, undef, undef, $fixed_limit, undef, undef, undef ) = buildQuery ( undef, undef, undef, $expanded_lim, undef, undef, $lang); - $limit .= " and " if $limit || $query; - $limit .= "$fixed_limit"; + my ( $error, undef, undef, undef, undef, $fixed_limit, undef, undef, undef ) = + buildQuery( undef, undef, undef, $expanded_lim, undef, undef, $lang ); + $limit .= " and " if $limit || $query; + $limit .= "$fixed_limit"; $limit_desc .= " $limit"; } # Regular old limits else { - $limit .= " and " if $limit || $query; + $limit .= " and " if $limit || $query; $limit .= "$this_limit"; $limit_cgi .= "&limit=" . uri_escape_utf8($this_limit); $limit_desc .= " $this_limit"; } } - foreach my $k (keys (%group_OR_limits)) { + foreach my $k ( keys(%group_OR_limits) ) { $limit .= " and " if ( $query || $limit ); $limit .= "($group_OR_limits{$k})"; } @@ -1335,22 +1299,23 @@ sub buildQuery { $limit .= "($availability_limit)"; } -# for handling ccl, cql, pqf queries in diagnostic mode, skip the rest of the steps -# DIAGNOSTIC ONLY!! + # for handling ccl, cql, pqf queries in diagnostic mode, skip the rest of the steps + # DIAGNOSTIC ONLY!! if ( $query =~ /^ccl=/ ) { - my $q=$'; + my $q = $'; + # This is needed otherwise ccl= and &limit won't work together, and # this happens when selecting a subject on the opac-detail page - my $original_q = $q; # without available part + my $original_q = $q; # without available part $q .= $limit if $limit; - return ( undef, $q, $q, "q=ccl=".uri_escape_utf8($q), $original_q, '', '', '', 'ccl' ); + return ( undef, $q, $q, "q=ccl=" . uri_escape_utf8($q), $original_q, '', '', '', 'ccl' ); } if ( $query =~ /^cql=/ ) { - return ( undef, $', $', "q=cql=".uri_escape_utf8($'), $', '', '', '', 'cql' ); + return ( undef, $', $', "q=cql=" . uri_escape_utf8($'), $', '', '', '', 'cql' ); } if ( $query =~ /^pqf=/ ) { $query_desc = $'; - $query_cgi = "q=pqf=".uri_escape_utf8($'); + $query_cgi = "q=pqf=" . uri_escape_utf8($'); return ( undef, $', $', $query_cgi, $query_desc, '', '', '', 'pqf' ); } @@ -1358,40 +1323,38 @@ sub buildQuery { # FIXME: need better handling of some of these variables in this case # Nested queries aren't handled well and this implementation is flawed and causes users to be # unable to search for anything containing () commenting out, will be rewritten for 3.4.0 -# if ( $query =~ /(\(|\))/ ) { -# return ( -# undef, $query, $simple_query, $query_cgi, -# $query, $limit, $limit_cgi, $limit_desc, -# 'ccl' -# ); -# } + # if ( $query =~ /(\(|\))/ ) { + # return ( + # undef, $query, $simple_query, $query_cgi, + # $query, $limit, $limit_cgi, $limit_desc, + # 'ccl' + # ); + # } -# Form-based queries are non-nested and fixed depth, so we can easily modify the incoming -# query operands and indexes and add stemming, truncation, field weighting, etc. -# Once we do so, we'll end up with a value in $query, just like if we had an -# incoming $query from the user + # Form-based queries are non-nested and fixed depth, so we can easily modify the incoming + # query operands and indexes and add stemming, truncation, field weighting, etc. + # Once we do so, we'll end up with a value in $query, just like if we had an + # incoming $query from the user else { - $query = "" - ; # clear it out so we can populate properly with field-weighted, stemmed, etc. query - my $previous_operand - ; # a flag used to keep track if there was a previous query - # if there was, we can apply the current operator - # for every operand + $query = ""; # clear it out so we can populate properly with field-weighted, stemmed, etc. query + my $previous_operand; # a flag used to keep track if there was a previous query + # if there was, we can apply the current operator + # for every operand for ( my $i = 0 ; $i <= @operands ; $i++ ) { # COMBINE OPERANDS, INDEXES AND OPERATORS - if ( ($operands[$i] // '') ne '' ) { - $operands[$i]=~s/^\s+//; + if ( ( $operands[$i] // '' ) ne '' ) { + $operands[$i] =~ s/^\s+//; - # A flag to determine whether or not to add the index to the query + # A flag to determine whether or not to add the index to the query my $indexes_set; -# If the user is sophisticated enough to specify an index, turn off field weighting, and stemming handling + # If the user is sophisticated enough to specify an index, turn off field weighting, and stemming handling if ( $operands[$i] =~ /\w(:|=)/ || $scan ) { - $weight_fields = 0; - $stemming = 0; + $weight_fields = 0; + $stemming = 0; } else { - $operands[$i] =~ s/\?/{?}/g; # need to escape question marks + $operands[$i] =~ s/\?/{?}/g; # need to escape question marks } my $operand = $operands[$i]; my $index = $indexes[$i] || 'kw'; @@ -1405,6 +1368,7 @@ sub buildQuery { # Search ranges: Date of Publication, st-numeric if ( $index =~ /(yr|st-numeric)/ ) { + #weight_fields/relevance search causes errors with date ranges #In the case of YYYY-, it will only return records with a 'yr' of YYYY (not the range) #In the case of YYYY-YYYY, it will return no results @@ -1413,13 +1377,15 @@ sub buildQuery { # Date of Acquisition elsif ( $index =~ /acqdate/ ) { + #stemming and auto_truncation would have zero impact since it already is YYYY-MM-DD format #Weight_fields probably SHOULD be turned OFF, otherwise you'll get records floating to the - #top of the results just because they have lots of item records matching that date. + #top of the results just because they have lots of item records matching that date. #Fuzzy actually only applies during _build_weighted_query, and is reset there anyway, so - #irrelevant here + #irrelevant here $stemming = $auto_truncation = $weight_fields = $fuzzy_enabled = 0; } + # ISBN,ISSN,Standard Number, don't need special treatment elsif ( $index eq 'nb' || $index eq 'ns' || $index eq 'hi' ) { ( @@ -1429,16 +1395,16 @@ sub buildQuery { if ( $index eq 'nb' ) { if ( C4::Context->preference("SearchWithISBNVariations") ) { - my @isbns = C4::Koha::GetVariationsOfISBN( $operand ); + my @isbns = C4::Koha::GetVariationsOfISBN($operand); $operands[$i] = $operand = '(' . join( ' OR ', map { 'nb=' . $_ } @isbns ) . ')'; - $indexes[$i] = $index = 'kw'; + $indexes[$i] = $index = 'kw'; } } if ( $index eq 'ns' ) { if ( C4::Context->preference("SearchWithISSNVariations") ) { - my @issns = C4::Koha::GetVariationsOfISSN( $operand ); + my @issns = C4::Koha::GetVariationsOfISSN($operand); $operands[$i] = $operand = '(' . join( ' OR ', map { 'ns=' . $_ } @issns ) . ')'; - $indexes[$i] = $index = 'kw'; + $indexes[$i] = $index = 'kw'; } } } @@ -1453,49 +1419,48 @@ sub buildQuery { my $index_plus = $index . $struct_attr . ':'; my $index_plus_comma = $index . $struct_attr . ','; - if ($auto_truncation){ - unless ( $index =~ /,(st-|phr|ext)/ ) { - #FIXME only valid with LTR scripts - $operand=join(" ",map{ - (index($_,"*")>0?"$_":"$_*") - }split (/\s+/,$operand)); - } - } + if ($auto_truncation) { + unless ( $index =~ /,(st-|phr|ext)/ ) { + + #FIXME only valid with LTR scripts + $operand = + join( " ", map { ( index( $_, "*" ) > 0 ? "$_" : "$_*" ) } split( /\s+/, $operand ) ); + } + } # Detect Truncation my $truncated_operand = q{}; - my( $nontruncated, $righttruncated, $lefttruncated, + my ( + $nontruncated, $righttruncated, $lefttruncated, $rightlefttruncated, $regexpr ) = _detect_truncation( $operand, $index ); Koha::Logger->get->debug( - "TRUNCATION: NON:>@$nontruncated< RIGHT:>@$righttruncated< LEFT:>@$lefttruncated< RIGHTLEFT:>@$rightlefttruncated< REGEX:>@$regexpr<"); + "TRUNCATION: NON:>@$nontruncated< RIGHT:>@$righttruncated< LEFT:>@$lefttruncated< RIGHTLEFT:>@$rightlefttruncated< REGEX:>@$regexpr<" + ); # Apply Truncation - if ( - scalar(@$righttruncated) + scalar(@$lefttruncated) + - scalar(@$rightlefttruncated) > 0 ) - { + if ( scalar(@$righttruncated) + scalar(@$lefttruncated) + scalar(@$rightlefttruncated) > 0 ) { - # Don't field weight or add the index to the query, we do it here + # Don't field weight or add the index to the query, we do it here $indexes_set = 1; undef $weight_fields; my $previous_truncation_operand; - if (scalar @$nontruncated) { + if ( scalar @$nontruncated ) { $truncated_operand .= "$index_plus @$nontruncated "; $previous_truncation_operand = 1; } - if (scalar @$righttruncated) { + if ( scalar @$righttruncated ) { $truncated_operand .= "and " if $previous_truncation_operand; $truncated_operand .= $index_plus_comma . "rtrn:@$righttruncated "; $previous_truncation_operand = 1; } - if (scalar @$lefttruncated) { + if ( scalar @$lefttruncated ) { $truncated_operand .= "and " if $previous_truncation_operand; $truncated_operand .= $index_plus_comma . "ltrn:@$lefttruncated "; $previous_truncation_operand = 1; } - if (scalar @$rightlefttruncated) { + if ( scalar @$rightlefttruncated ) { $truncated_operand .= "and " if $previous_truncation_operand; $truncated_operand .= $index_plus_comma . "rltrn:@$rightlefttruncated "; $previous_truncation_operand = 1; @@ -1506,8 +1471,8 @@ sub buildQuery { # Handle Stemming my $stemmed_operand = q{}; - $stemmed_operand = _build_stemmed_operand($operand, $lang) - if $stemming; + $stemmed_operand = _build_stemmed_operand( $operand, $lang ) + if $stemming; Koha::Logger->get->debug("STEMMED OPERAND: >$stemmed_operand<"); @@ -1515,8 +1480,8 @@ sub buildQuery { my $weighted_operand = q{}; if ($weight_fields) { $weighted_operand = _build_weighted_query( $operand, $stemmed_operand, $index ); - $operand = $weighted_operand; - $indexes_set = 1; + $operand = $weighted_operand; + $indexes_set = 1; } Koha::Logger->get->debug("FIELD WEIGHTED OPERAND: >$weighted_operand<"); @@ -1528,18 +1493,20 @@ sub buildQuery { #the need for this relevance wrapper. $operand = "(rk=($operand))" unless $weight_fields; - ($query,$query_cgi,$query_desc,$previous_operand) = _build_initial_query({ - query => $query, - query_cgi => $query_cgi, - query_desc => $query_desc, - operator => ($operators[ $i - 1 ]) ? $operators[ $i - 1 ] : '', - parsed_operand => $operand, - original_operand => $operands[$i] // '', - index => $index, - index_plus => $index_plus, - indexes_set => $indexes_set, - previous_operand => $previous_operand, - }); + ( $query, $query_cgi, $query_desc, $previous_operand ) = _build_initial_query( + { + query => $query, + query_cgi => $query_cgi, + query_desc => $query_desc, + operator => ( $operators[ $i - 1 ] ) ? $operators[ $i - 1 ] : '', + parsed_operand => $operand, + original_operand => $operands[$i] // '', + index => $index, + index_plus => $index_plus, + indexes_set => $indexes_set, + previous_operand => $previous_operand, + } + ); } #/if $operands } # /for @@ -1549,7 +1516,7 @@ sub buildQuery { # Normalize the query and limit strings # This is flawed , means we can't search anything with : in it # if user wants to do ccl or cql, start the query with that -# $query =~ s/:/=/g; + # $query =~ s/:/=/g; #NOTE: We use several several different regexps here as you can't have variable length lookback assertions $query =~ s/(?<=(ti|au|pb|su|an|kw|mc|nb|ns)):/=/g; $query =~ s/(?<=(wrdl)):/=/g; @@ -1567,27 +1534,30 @@ sub buildQuery { $limit_cgi //= q{}; $simple_query //= q{}; $limit =~ s/:/=/g; + for ( $query, $query_desc, $limit, $limit_desc ) { s/ +/ /g; # remove extra spaces - s/^ //g; # remove any beginning spaces - s/ $//g; # remove any ending spaces - s/==/=/g; # remove double == from query + s/^ //g; # remove any beginning spaces + s/ $//g; # remove any ending spaces + s/==/=/g; # remove double == from query } - $query_cgi =~ s/^&//; # remove unnecessary & from beginning of the query cgi + $query_cgi =~ s/^&//; # remove unnecessary & from beginning of the query cgi - for ($query_cgi,$simple_query) { + for ( $query_cgi, $simple_query ) { s/"//g; } + # append the limit to the query $query .= " " . $limit; Koha::Logger->get->debug( sprintf "buildQuery returns\nQUERY:%s\nQUERY CGI:%s\nQUERY DESC:%s\nLIMIT:%s\nLIMIT CGI:%s\nLIMIT DESC:%s", - $query, $query_cgi, $query_desc, $limit, $limit_cgi, $limit_desc ); + $query, $query_cgi, $query_desc, $limit, $limit_cgi, $limit_desc + ); return ( - undef, $query, $simple_query, $query_cgi, - $query_desc, $limit, $limit_cgi, $limit_desc, + undef, $query, $simple_query, $query_cgi, + $query_desc, $limit, $limit_cgi, $limit_desc, $query_type ); } @@ -1604,28 +1574,33 @@ sub _build_initial_query { my ($params) = @_; my $operator = ""; - if ($params->{previous_operand}){ + if ( $params->{previous_operand} ) { + #If there is a previous operand, add a supplied operator or the default 'and' - $operator = ($params->{operator}) ? ($params->{operator}) : 'AND'; + $operator = ( $params->{operator} ) ? ( $params->{operator} ) : 'AND'; } #NOTE: indexes_set is typically set when doing truncation or field weighting - my $operand = ($params->{indexes_set}) ? $params->{parsed_operand} : $params->{index_plus}.$params->{parsed_operand}; + my $operand = + ( $params->{indexes_set} ) ? $params->{parsed_operand} : $params->{index_plus} . $params->{parsed_operand}; #e.g. "kw,wrdl:test" #e.g. " and kw,wrdl:test" $params->{query} .= " " . $operator . " " . $operand; - $params->{query_cgi} .= "&op=".uri_escape_utf8($operator) if $operator; - $params->{query_cgi} .= "&idx=".uri_escape_utf8($params->{index}) if $params->{index}; - $params->{query_cgi} .= "&q=".uri_escape_utf8($params->{original_operand}) if ( $params->{original_operand} ne '' ); + $params->{query_cgi} .= "&op=" . uri_escape_utf8($operator) if $operator; + $params->{query_cgi} .= "&idx=" . uri_escape_utf8( $params->{index} ) if $params->{index}; + $params->{query_cgi} .= "&q=" . uri_escape_utf8( $params->{original_operand} ) + if ( $params->{original_operand} ne '' ); #e.g. " and kw,wrdl: test" - $params->{query_desc} .= " " . $operator . " " . ( $params->{index_plus} // q{} ) . " " . ( $params->{original_operand} // q{} ); + $params->{query_desc} .= + " " . $operator . " " . ( $params->{index_plus} // q{} ) . " " . ( $params->{original_operand} // q{} ); - $params->{previous_operand} = 1 unless $params->{previous_operand}; #If there is no previous operand, mark this as one + $params->{previous_operand} = 1 + unless $params->{previous_operand}; #If there is no previous operand, mark this as one - return ($params->{query}, $params->{query_cgi}, $params->{query_desc}, $params->{previous_operand}); + return ( $params->{query}, $params->{query_cgi}, $params->{query_desc}, $params->{previous_operand} ); } =head2 searchResults @@ -1647,28 +1622,36 @@ sub searchResults { require C4::Items; - $search_context->{'interface'} = 'opac' if !$search_context->{'interface'} || $search_context->{'interface'} ne 'intranet'; - my ($is_opac, $hidelostitems); - if ($search_context->{'interface'} eq 'opac') { + $search_context->{'interface'} = 'opac' + if !$search_context->{'interface'} || $search_context->{'interface'} ne 'intranet'; + my ( $is_opac, $hidelostitems ); + if ( $search_context->{'interface'} eq 'opac' ) { $hidelostitems = C4::Context->preference('hidelostitems'); $is_opac = 1; } - my $record_processor = Koha::RecordProcessor->new({ - filters => 'ViewPolicy' - }); + my $record_processor = Koha::RecordProcessor->new( { filters => 'ViewPolicy' } ); #Build branchnames hash - my %branches = map { $_->branchcode => $_->branchname } Koha::Libraries->search({}, { order_by => 'branchname' })->as_list; + my %branches = + map { $_->branchcode => $_->branchname } Koha::Libraries->search( {}, { order_by => 'branchname' } )->as_list; -# FIXME - We build an authorised values hash here, using the default framework -# though it is possible to have different authvals for different fws. + # FIXME - We build an authorised values hash here, using the default framework + # though it is possible to have different authvals for different fws. - my $shelflocations = - { map { $_->{authorised_value} => $_->{lib} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.location' } ) }; + my $shelflocations = { + map { $_->{authorised_value} => $_->{lib} } Koha::AuthorisedValues->get_descriptions_by_koha_field( + { frameworkcode => '', kohafield => 'items.location' } + ) + }; # get notforloan authorised value list (see $shelflocations FIXME) - my $av = Koha::MarcSubfieldStructures->search({ frameworkcode => '', kohafield => 'items.notforloan', authorised_value => [ -and => {'!=' => undef }, {'!=' => ''}] }); + my $av = Koha::MarcSubfieldStructures->search( + { + frameworkcode => '', kohafield => 'items.notforloan', + authorised_value => [ -and => { '!=' => undef }, { '!=' => '' } ] + } + ); my $notforloan_authorised_value = $av->count ? $av->next->authorised_value : undef; #Get itemtype hash @@ -1676,37 +1659,36 @@ sub searchResults { my %itemtypes = map { $_->{itemtype} => $_ } @{ $itemtypes->unblessed }; #search item field code - my ($itemtag, undef) = &GetMarcFromKohaField( "items.itemnumber" ); + my ( $itemtag, undef ) = &GetMarcFromKohaField("items.itemnumber"); ## find column names of items related to MARC my %subfieldstosearch; my @columns = Koha::Database->new()->schema()->resultset('Item')->result_source->columns; - for my $column ( @columns ) { - my ( $tagfield, $tagsubfield ) = - &GetMarcFromKohaField( "items." . $column ); + for my $column (@columns) { + my ( $tagfield, $tagsubfield ) = &GetMarcFromKohaField( "items." . $column ); if ( defined $tagsubfield ) { $subfieldstosearch{$column} = $tagsubfield; } } # handle which records to actually retrieve - my $times; # Times is which record to process up to + my $times; # Times is which record to process up to if ( $hits && $offset + $results_per_page <= $hits ) { $times = $offset + $results_per_page; - } - else { - $times = $hits // 0; # If less hits than results_per_page+offset we go to the end + } else { + $times = $hits // 0; # If less hits than results_per_page+offset we go to the end } my $marcflavour = C4::Context->preference("marcflavour"); + # We get the biblionumber position in MARC - my ($bibliotag,$bibliosubf)=GetMarcFromKohaField( 'biblio.biblionumber' ); + my ( $bibliotag, $bibliosubf ) = GetMarcFromKohaField('biblio.biblionumber'); # set stuff for XSLT processing here once, not later again for every record we retrieved my $userenv = C4::Context->userenv; - my $logged_in_user - = ( defined $userenv and $userenv->{number} ) + my $logged_in_user = + ( defined $userenv and $userenv->{number} ) ? Koha::Patrons->find( $userenv->{number} ) : undef; my $patron_category_hide_lost_items = ($logged_in_user) ? $logged_in_user->category->hidelostitems : 0; @@ -1716,63 +1698,72 @@ sub searchResults { my $marcrecord; if ($scan) { + # For Scan searches we built USMARC data - $marcrecord = MARC::Record->new_from_usmarc( $marcresults->[$i]); + $marcrecord = MARC::Record->new_from_usmarc( $marcresults->[$i] ); } else { + # Normal search, render from Zebra's output $marcrecord = new_record_from_zebra( 'biblioserver', $marcresults->[$i] ); - if ( ! defined $marcrecord ) { + if ( !defined $marcrecord ) { warn "ERROR DECODING RECORD - $@: " . $marcresults->[$i]; next; } } - my $fw = $scan - ? undef - : $bibliotag < 10 - ? GetFrameworkCode($marcrecord->field($bibliotag)->data) - : GetFrameworkCode($marcrecord->subfield($bibliotag,$bibliosubf)); + my $fw = + $scan ? undef + : $bibliotag < 10 ? GetFrameworkCode( $marcrecord->field($bibliotag)->data ) + : GetFrameworkCode( $marcrecord->subfield( $bibliotag, $bibliosubf ) ); SetUTF8Flag($marcrecord); - my $oldbiblio = TransformMarcToKoha({ record => $marcrecord, limit_table => 'no_items' }); + my $oldbiblio = TransformMarcToKoha( { record => $marcrecord, limit_table => 'no_items' } ); $oldbiblio->{result_number} = $i + 1; - $oldbiblio->{normalized_upc} = GetNormalizedUPC( $marcrecord,$marcflavour); - $oldbiblio->{normalized_ean} = GetNormalizedEAN( $marcrecord,$marcflavour); - $oldbiblio->{normalized_oclc} = GetNormalizedOCLCNumber($marcrecord,$marcflavour); - $oldbiblio->{normalized_isbn} = GetNormalizedISBN($oldbiblio->{isbn},$marcrecord,$marcflavour); # Use existing ISBN from record if we got one - $oldbiblio->{content_identifier_exists} = 1 if ($oldbiblio->{normalized_isbn} or $oldbiblio->{normalized_oclc} or $oldbiblio->{normalized_ean} or $oldbiblio->{normalized_upc}); + $oldbiblio->{normalized_upc} = GetNormalizedUPC( $marcrecord, $marcflavour ); + $oldbiblio->{normalized_ean} = GetNormalizedEAN( $marcrecord, $marcflavour ); + $oldbiblio->{normalized_oclc} = GetNormalizedOCLCNumber( $marcrecord, $marcflavour ); + $oldbiblio->{normalized_isbn} = GetNormalizedISBN( $oldbiblio->{isbn}, $marcrecord, $marcflavour ) + ; # Use existing ISBN from record if we got one + $oldbiblio->{content_identifier_exists} = 1 + if ( $oldbiblio->{normalized_isbn} + or $oldbiblio->{normalized_oclc} + or $oldbiblio->{normalized_ean} + or $oldbiblio->{normalized_upc} ); - # edition information, if any + # edition information, if any $oldbiblio->{edition} = $oldbiblio->{editionstatement}; - my $itemtype = $oldbiblio->{itemtype} ? $itemtypes{$oldbiblio->{itemtype}} : undef; + my $itemtype = $oldbiblio->{itemtype} ? $itemtypes{ $oldbiblio->{itemtype} } : undef; + # add imageurl to itemtype if there is one - $oldbiblio->{imageurl} = $itemtype ? getitemtypeimagelocation( $search_context->{'interface'}, $itemtype->{imageurl} ) : q{}; + $oldbiblio->{imageurl} = + $itemtype ? getitemtypeimagelocation( $search_context->{'interface'}, $itemtype->{imageurl} ) : q{}; + # Build summary if there is one (the summary is defined in the itemtypes table) $oldbiblio->{description} = $itemtype ? $itemtype->{translated_description} : q{}; # Pull out the items fields my @fields = $marcrecord->field($itemtag); - $marcrecord->delete_fields( @fields ) unless C4::Context->preference('PassItemMarcToXSLT'); + $marcrecord->delete_fields(@fields) unless C4::Context->preference('PassItemMarcToXSLT'); my $marcflavor = C4::Context->preference("marcflavour"); # adding linked items that belong to host records if ( C4::Context->preference('EasyAnalyticalRecords') ) { my $analyticsfield = '773'; - if ($marcflavor eq 'MARC21') { + if ( $marcflavor eq 'MARC21' ) { $analyticsfield = '773'; - } elsif ($marcflavor eq 'UNIMARC') { + } elsif ( $marcflavor eq 'UNIMARC' ) { $analyticsfield = '461'; } - foreach my $hostfield ( $marcrecord->field($analyticsfield)) { + foreach my $hostfield ( $marcrecord->field($analyticsfield) ) { my $hostbiblionumber = $hostfield->subfield("0"); my $linkeditemnumber = $hostfield->subfield("9"); - if( $hostbiblionumber ) { + if ($hostbiblionumber) { my $linkeditemmarc = C4::Items::GetMarcItem( $hostbiblionumber, $linkeditemnumber ); if ($linkeditemmarc) { my $linkeditemfield = $linkeditemmarc->field($itemtag); @@ -1798,7 +1789,7 @@ sub searchResults { my $onloan_count = 0; my $longoverdue_count = 0; my $other_count = 0; - my $withdrawn_count = 0; + my $withdrawn_count = 0; my $itemlost_count = 0; my $hideatopac_count = 0; my $itembinding_count = 0; @@ -1808,9 +1799,9 @@ sub searchResults { my $notforloan_count = 0; my $item_recalled_count = 0; my $items_count = scalar(@fields); - my $maxitems_pref = C4::Context->preference('maxItemsinSearchResults'); - my $maxitems = $maxitems_pref ? $maxitems_pref - 1 : 1; - my @hiddenitems; # hidden itemnumbers based on OpacHiddenItems syspref + my $maxitems_pref = C4::Context->preference('maxItemsinSearchResults'); + my $maxitems = $maxitems_pref ? $maxitems_pref - 1 : 1; + my @hiddenitems; # hidden itemnumbers based on OpacHiddenItems syspref # loop through every item foreach my $field (@fields) { @@ -1830,9 +1821,10 @@ sub searchResults { # OPAC hidden items if ($is_opac) { + # hidden based on OpacHiddenItems syspref or because lost my $hi = Koha::Items->search( { itemnumber => $item->{itemnumber} } ) - ->filter_by_visible_in_opac({ patron => $search_context->{patron} }); + ->filter_by_visible_in_opac( { patron => $search_context->{patron} } ); unless ( $hi->count ) { push @hiddenitems, $item->{itemnumber}; $hideatopac_count++; @@ -1842,24 +1834,25 @@ sub searchResults { my $hbranch = C4::Context->preference('StaffSearchResultsDisplayBranch'); my $otherbranch = $hbranch eq 'homebranch' ? 'holdingbranch' : 'homebranch'; + # set item's branch name, use HomeOrHoldingBranch syspref first, fall back to the other one - if ($item->{$hbranch}) { - $item->{'branchname'} = $branches{$item->{$hbranch}}; + if ( $item->{$hbranch} ) { + $item->{'branchname'} = $branches{ $item->{$hbranch} }; $item->{'branchcode'} = $item->{$hbranch}; - } - elsif ($item->{$otherbranch}) { # Last resort - $item->{'branchname'} = $branches{$item->{$otherbranch}}; + } elsif ( $item->{$otherbranch} ) { # Last resort + $item->{'branchname'} = $branches{ $item->{$otherbranch} }; $item->{'branchcode'} = $item->{$otherbranch}; } my $prefix = - ( $item->{$hbranch} ? $item->{$hbranch} . '--' : q{} ) - . ( $item->{location} ? $item->{location} : q{} ) - . ( $item->{itype} ? $item->{itype} : q{} ) - . ( $item->{ccode} ? $item->{ccode} : q{} ) - . ( $item->{itemcallnumber} ? $item->{itemcallnumber} : q{} ); -# For each grouping of items (onloan, available, unavailable), we build a key to store relevant info about that item - if ( $item->{onloan} + ( $item->{$hbranch} ? $item->{$hbranch} . '--' : q{} ) + . ( $item->{location} ? $item->{location} : q{} ) + . ( $item->{itype} ? $item->{itype} : q{} ) + . ( $item->{ccode} ? $item->{ccode} : q{} ) + . ( $item->{itemcallnumber} ? $item->{itemcallnumber} : q{} ); + + # For each grouping of items (onloan, available, unavailable), we build a key to store relevant info about that item + if ( $item->{onloan} and $logged_in_user and !( $patron_category_hide_lost_items and $item->{itemlost} ) ) { @@ -1872,9 +1865,12 @@ sub searchResults { $onloan_items->{$key}->{location} = $shelflocations->{ $item->{location} } if $item->{location}; $onloan_items->{$key}->{itemcallnumber} = $item->{itemcallnumber}; $onloan_items->{$key}->{description} = $item->{description}; - $onloan_items->{$key}->{imageurl} = - getitemtypeimagelocation( $search_context->{'interface'}, $itemtypes{ $item->{itype} }->{imageurl} ); - $onloan_items->{$key}->{collectioncode} = GetAuthorisedValueDesc('','',$item->{ccode},'','','CCODE'); + $onloan_items->{$key}->{imageurl} = getitemtypeimagelocation( + $search_context->{'interface'}, + $itemtypes{ $item->{itype} }->{imageurl} + ); + $onloan_items->{$key}->{collectioncode} = + GetAuthorisedValueDesc( '', '', $item->{ccode}, '', '', 'CCODE' ); # if something's checked out and lost, mark it as 'long overdue' if ( $item->{itemlost} ) { @@ -1883,12 +1879,14 @@ sub searchResults { } } - # items not on loan, but still unavailable ( lost, withdrawn, damaged ) + # items not on loan, but still unavailable ( lost, withdrawn, damaged ) else { - my $itemtype = C4::Context->preference("item-level_itypes")? $item->{itype}: $oldbiblio->{itemtype}; - $item->{notforloan} = 1 if !$item->{notforloan} && - $itemtype && $itemtypes{ $itemtype }->{notforloan}; + my $itemtype = C4::Context->preference("item-level_itypes") ? $item->{itype} : $oldbiblio->{itemtype}; + $item->{notforloan} = 1 + if !$item->{notforloan} + && $itemtype + && $itemtypes{$itemtype}->{notforloan}; # item is on order if ( $item->{notforloan} < 0 ) { @@ -1899,7 +1897,7 @@ sub searchResults { # is item in transit? my $transfertwhen = ''; - my ($transfertfrom, $transfertto); + my ( $transfertfrom, $transfertto ); # is item on the reserve shelf? my $reservestatus = ''; @@ -1907,12 +1905,15 @@ sub searchResults { # is item a waiting recall? my $recallstatus = ''; - unless ($item->{withdrawn} - || $item->{itemlost} - || $item->{damaged} - || $item->{notforloan} - || ( C4::Context->preference('MaxSearchResultsItemsPerRecordStatusCheck') - && $items_count > C4::Context->preference('MaxSearchResultsItemsPerRecordStatusCheck') ) ) { + unless ( + $item->{withdrawn} + || $item->{itemlost} + || $item->{damaged} + || $item->{notforloan} + || ( C4::Context->preference('MaxSearchResultsItemsPerRecordStatusCheck') + && $items_count > C4::Context->preference('MaxSearchResultsItemsPerRecordStatusCheck') ) + ) + { # A couple heuristics to limit how many times # we query the database for item transfer information, sacrificing @@ -1926,18 +1927,17 @@ sub searchResults { # the in transit status count as unavailable for search limiting, # should map transit status to record indexed in Zebra. - my $item_object = Koha::Items->find($item->{itemnumber}); - my $transfer = defined($item_object) ? $item_object->get_transfer : undef; - ( $transfertwhen, $transfertfrom, $transfertto ) = - defined($transfer) - ? ( + my $item_object = Koha::Items->find( $item->{itemnumber} ); + my $transfer = defined($item_object) ? $item_object->get_transfer : undef; + ( $transfertwhen, $transfertfrom, $transfertto ) = defined($transfer) + ? ( $transfer->datesent, $transfer->frombranch, $transfer->tobranch - ) - : ( '', '', '' ); + ) + : ( '', '', '' ); $reservestatus = C4::Reserves::GetReserveStatus( $item->{itemnumber} ); if ( C4::Context->preference('UseRecalls') ) { - if ( Koha::Recalls->search({ item_id => $item->{itemnumber}, status => 'waiting' })->count ) { + if ( Koha::Recalls->search( { item_id => $item->{itemnumber}, status => 'waiting' } )->count ) { $recallstatus = 'Waiting'; } } @@ -1950,15 +1950,19 @@ sub searchResults { || $item->{notforloan} || $reservestatus eq 'Waiting' || $recallstatus eq 'Waiting' - || ($transfertwhen && $transfertwhen ne '')) + || ( $transfertwhen && $transfertwhen ne '' ) ) { - $withdrawn_count++ if $item->{withdrawn}; + $withdrawn_count++ if $item->{withdrawn}; $itemlost_count++ if $item->{itemlost}; $itemdamaged_count++ if $item->{damaged}; $item_in_transit_count++ if $transfertwhen && $transfertwhen ne ''; $item_onhold_count++ if $reservestatus eq 'Waiting'; $item_recalled_count++ if $recallstatus eq 'Waiting'; - $item->{status} = ($item->{withdrawn}//q{}) . "-" . ($item->{itemlost}//q{}) . "-" . ($item->{damaged}//q{}) . "-" . ($item->{notforloan}//q{}); + $item->{status} = + ( $item->{withdrawn} // q{} ) . "-" + . ( $item->{itemlost} // q{} ) . "-" + . ( $item->{damaged} // q{} ) . "-" + . ( $item->{notforloan} // q{} ); $other_count++; @@ -1966,17 +1970,24 @@ sub searchResults { foreach (qw(withdrawn itemlost damaged branchname itemcallnumber)) { $other_items->{$key}->{$_} = $item->{$_}; } - $other_items->{$key}->{branchcode} = $item->{branchcode}; - $other_items->{$key}->{intransit} = ( $transfertwhen ne '' ) ? 1 : 0; - $other_items->{$key}->{recalled} = ($recallstatus) ? 1 : 0; - $other_items->{$key}->{onhold} = ($reservestatus) ? 1 : 0; - $other_items->{$key}->{notforloan} = GetAuthorisedValueDesc('','',$item->{notforloan},'','',$notforloan_authorised_value) if $notforloan_authorised_value and $item->{notforloan}; + $other_items->{$key}->{branchcode} = $item->{branchcode}; + $other_items->{$key}->{intransit} = ( $transfertwhen ne '' ) ? 1 : 0; + $other_items->{$key}->{recalled} = ($recallstatus) ? 1 : 0; + $other_items->{$key}->{onhold} = ($reservestatus) ? 1 : 0; + $other_items->{$key}->{notforloan} = + GetAuthorisedValueDesc( '', '', $item->{notforloan}, '', '', $notforloan_authorised_value ) + if $notforloan_authorised_value and $item->{notforloan}; $other_items->{$key}->{count}++ if $item->{$hbranch}; - $other_items->{$key}->{location} = $shelflocations->{ $item->{location} } if $item->{location}; + $other_items->{$key}->{location} = $shelflocations->{ $item->{location} } if $item->{location}; $other_items->{$key}->{description} = $item->{description}; - $other_items->{$key}->{imageurl} = getitemtypeimagelocation( $search_context->{'interface'}, $itemtypes{ $item->{itype}//q{} }->{imageurl} ); - $other_items->{$key}->{collectioncode} = GetAuthorisedValueDesc('','',$item->{ccode},'','','CCODE'); + $other_items->{$key}->{imageurl} = getitemtypeimagelocation( + $search_context->{'interface'}, + $itemtypes{ $item->{itype} // q{} }->{imageurl} + ); + $other_items->{$key}->{collectioncode} = + GetAuthorisedValueDesc( '', '', $item->{ccode}, '', '', 'CCODE' ); } + # item is available else { $available_count++; @@ -1985,39 +1996,49 @@ sub searchResults { $available_items->{$prefix}->{$_} = $item->{$_}; } $available_items->{$prefix}->{branchcode} = $item->{branchcode}; - $available_items->{$prefix}->{location} = $shelflocations->{ $item->{location} } if $item->{location}; - $available_items->{$prefix}->{imageurl} = getitemtypeimagelocation( $search_context->{'interface'}, $itemtypes{ $item->{itype}//q{} }->{imageurl} ); - $available_items->{$prefix}->{collectioncode} = GetAuthorisedValueDesc('','',$item->{ccode},'','','CCODE'); + $available_items->{$prefix}->{location} = $shelflocations->{ $item->{location} } + if $item->{location}; + $available_items->{$prefix}->{imageurl} = getitemtypeimagelocation( + $search_context->{'interface'}, + $itemtypes{ $item->{itype} // q{} }->{imageurl} + ); + $available_items->{$prefix}->{collectioncode} = + GetAuthorisedValueDesc( '', '', $item->{ccode}, '', '', 'CCODE' ); } } } # notforloan, item level and biblioitem level # if all items are hidden, do not show the record - if ( C4::Context->preference('OpacHiddenItemsHidesRecord') && $items_count > 0 && $hideatopac_count == $items_count) { + if ( C4::Context->preference('OpacHiddenItemsHidesRecord') + && $items_count > 0 + && $hideatopac_count == $items_count ) + { next; } my ( $availableitemscount, $onloanitemscount, $otheritemscount ); for my $key ( sort keys %$onloan_items ) { - (++$onloanitemscount > $maxitems) and last; + ( ++$onloanitemscount > $maxitems ) and last; push @onloan_items_loop, $onloan_items->{$key}; } for my $key ( sort keys %$other_items ) { - (++$otheritemscount > $maxitems) and last; + ( ++$otheritemscount > $maxitems ) and last; push @other_items_loop, $other_items->{$key}; } for my $key ( sort keys %$available_items ) { - (++$availableitemscount > $maxitems) and last; - push @available_items_loop, $available_items->{$key} + ( ++$availableitemscount > $maxitems ) and last; + push @available_items_loop, $available_items->{$key}; } # XSLT processing of some stuff # we fetched the sysprefs already before the loop through all retrieved record! - if (!$scan) { - $record_processor->options({ - frameworkcode => $fw, - interface => $search_context->{'interface'} - }); + if ( !$scan ) { + $record_processor->options( + { + frameworkcode => $fw, + interface => $search_context->{'interface'} + } + ); $record_processor->process($marcrecord); @@ -2039,21 +2060,22 @@ sub searchResults { my $biblio_object = Koha::Biblios->find( $oldbiblio->{biblionumber} ); $oldbiblio->{biblio_object} = $biblio_object; - $oldbiblio->{coins} = eval { $biblio_object->get_coins } - if $biblio_object - && C4::Context->preference('COinSinOPACResults') - && $is_opac; + $oldbiblio->{coins} = eval { $biblio_object->get_coins } + if $biblio_object + && C4::Context->preference('COinSinOPACResults') + && $is_opac; my $can_place_holds = 1; + # if biblio level itypes are used and itemtype is notforloan, it can't be reserved either - if (!C4::Context->preference("item-level_itypes")) { - if ($itemtype && $itemtype->{notforloan}) { + if ( !C4::Context->preference("item-level_itypes") ) { + if ( $itemtype && $itemtype->{notforloan} ) { $can_place_holds = 0; } } else { $can_place_holds = $biblio_object->items->filter_by_for_hold()->count if $biblio_object; } - $oldbiblio->{norequests} = 1 unless $can_place_holds; + $oldbiblio->{norequests} = 1 unless $can_place_holds; $oldbiblio->{items_count} = $items_count; $oldbiblio->{available_items_loop} = \@available_items_loop; $oldbiblio->{onloan_items_loop} = \@onloan_items_loop; @@ -2064,7 +2086,7 @@ sub searchResults { $oldbiblio->{onloanplural} = 1 if $onloan_count > 1; $oldbiblio->{othercount} = $other_count; $oldbiblio->{otherplural} = 1 if $other_count > 1; - $oldbiblio->{withdrawncount} = $withdrawn_count; + $oldbiblio->{withdrawncount} = $withdrawn_count; $oldbiblio->{itemlostcount} = $itemlost_count; $oldbiblio->{damagedcount} = $itemdamaged_count; $oldbiblio->{intransitcount} = $item_in_transit_count; @@ -2073,25 +2095,25 @@ sub searchResults { $oldbiblio->{orderedcount} = $ordered_count; $oldbiblio->{notforloancount} = $notforloan_count; - if (C4::Context->preference("AlternateHoldingsField") && $items_count == 0) { - my $fieldspec = C4::Context->preference("AlternateHoldingsField"); - my $subfields = substr $fieldspec, 3; - my $holdingsep = C4::Context->preference("AlternateHoldingsSeparator") || ' '; + if ( C4::Context->preference("AlternateHoldingsField") && $items_count == 0 ) { + my $fieldspec = C4::Context->preference("AlternateHoldingsField"); + my $subfields = substr $fieldspec, 3; + my $holdingsep = C4::Context->preference("AlternateHoldingsSeparator") || ' '; my @alternateholdingsinfo = (); - my @holdingsfields = $marcrecord->field(substr $fieldspec, 0, 3); + my @holdingsfields = $marcrecord->field( substr $fieldspec, 0, 3 ); for my $field (@holdingsfields) { - my %holding = ( holding => '' ); + my %holding = ( holding => '' ); my $havesubfield = 0; - for my $subfield ($field->subfields()) { - if ((index $subfields, $$subfield[0]) >= 0) { - $holding{'holding'} .= $holdingsep if (length $holding{'holding'} > 0); + for my $subfield ( $field->subfields() ) { + if ( ( index $subfields, $$subfield[0] ) >= 0 ) { + $holding{'holding'} .= $holdingsep if ( length $holding{'holding'} > 0 ); $holding{'holding'} .= $$subfield[1]; $havesubfield++; } } if ($havesubfield) { - push(@alternateholdingsinfo, \%holding); + push( @alternateholdingsinfo, \%holding ); } } @@ -2128,13 +2150,13 @@ $template->param ( C4::Search::enabled_staff_search_views ); =cut -sub enabled_staff_search_views -{ - return ( - can_view_MARC => C4::Context->preference('viewMARC'), # 1 if the staff search allows the MARC view - can_view_ISBD => C4::Context->preference('viewISBD'), # 1 if the staff search allows the ISBD view - can_view_labeledMARC => C4::Context->preference('viewLabeledMARC'), # 1 if the staff search allows the Labeled MARC view - ); +sub enabled_staff_search_views { + return ( + can_view_MARC => C4::Context->preference('viewMARC'), # 1 if the staff search allows the MARC view + can_view_ISBD => C4::Context->preference('viewISBD'), # 1 if the staff search allows the ISBD view + can_view_labeledMARC => C4::Context->preference('viewLabeledMARC') + , # 1 if the staff search allows the Labeled MARC view + ); } =head2 z3950_search_args @@ -2183,26 +2205,23 @@ $template->param ( MYLOOP => C4::Search::z3950_search_args($searchscalar) ) sub z3950_search_args { my $bibrec = shift; - my $isbn_string = ref( $bibrec ) ? $bibrec->{title} : $bibrec; - my $isbn = Business::ISBN->new( $isbn_string ); + my $isbn_string = ref($bibrec) ? $bibrec->{title} : $bibrec; + my $isbn = Business::ISBN->new($isbn_string); - if (defined $isbn && $isbn->is_valid) - { + if ( defined $isbn && $isbn->is_valid ) { if ( ref($bibrec) ) { - $bibrec->{isbn} = $isbn_string; + $bibrec->{isbn} = $isbn_string; $bibrec->{title} = undef; } else { $bibrec = { isbn => $isbn_string }; } - } - else { + } else { $bibrec = { title => $bibrec } if !ref $bibrec; } my $array = []; - for my $field (qw/ lccn isbn issn title author dewey subject /) - { + for my $field (qw/ lccn isbn issn title author dewey subject /) { push @$array, { name => $field, value => $bibrec->{$field} } - if defined $bibrec->{$field}; + if defined $bibrec->{$field}; } return $array; } @@ -2214,29 +2233,30 @@ C<$field> is a reference to the fields array =cut sub GetDistinctValues { - my ($fieldname,$string)=@_; + my ( $fieldname, $string ) = @_; + # returns a reference to a hash of references to branches... - if ($fieldname=~/\./){ - my ($table,$column)=split /\./, $fieldname; - my $dbh = C4::Context->dbh; - my $sth = $dbh->prepare("select DISTINCT($column) as value, count(*) as cnt from $table ".($string?" where $column like \"$string%\"":"")."group by value order by $column "); - $sth->execute; - my $elements=$sth->fetchall_arrayref({}); - return $elements; - } - else { - $string||= qq(""); - my @servers=qw; - my (@zconns,@results); + if ( $fieldname =~ /\./ ) { + my ( $table, $column ) = split /\./, $fieldname; + my $dbh = C4::Context->dbh; + my $sth = + $dbh->prepare( "select DISTINCT($column) as value, count(*) as cnt from $table " + . ( $string ? " where $column like \"$string%\"" : "" ) + . "group by value order by $column " ); + $sth->execute; + my $elements = $sth->fetchall_arrayref( {} ); + return $elements; + } else { + $string ||= qq(""); + my @servers = qw; + my ( @zconns, @results ); for ( my $i = 0 ; $i < @servers ; $i++ ) { - $zconns[$i] = C4::Context->Zconn( $servers[$i], 1 ); - $results[$i] = - $zconns[$i]->scan( - ZOOM::Query::CCL2RPN->new( qq"$fieldname $string", $zconns[$i]) - ); - } - # The big moment: asynchronously retrieve results from all servers - my @elements; + $zconns[$i] = C4::Context->Zconn( $servers[$i], 1 ); + $results[$i] = $zconns[$i]->scan( ZOOM::Query::CCL2RPN->new( qq"$fieldname $string", $zconns[$i] ) ); + } + + # The big moment: asynchronously retrieve results from all servers + my @elements; _ZOOM_event_loop( \@zconns, \@results, @@ -2245,13 +2265,13 @@ sub GetDistinctValues { for ( my $j = 0 ; $j < $size ; $j++ ) { my %hashscan; @hashscan{qw(value cnt)} = - $results[ $i - 1 ]->display_term($j); + $results[ $i - 1 ]->display_term($j); push @elements, \%hashscan; } } ); - return \@elements; - } + return \@elements; + } } =head2 _ZOOM_event_loop @@ -2267,14 +2287,14 @@ processing the results, and destroying the resultsets. =cut sub _ZOOM_event_loop { - my ($zconns, $results, $callback) = @_; - while ( ( my $i = ZOOM::event( $zconns ) ) != 0 ) { + my ( $zconns, $results, $callback ) = @_; + while ( ( my $i = ZOOM::event($zconns) ) != 0 ) { my $ev = $zconns->[ $i - 1 ]->last_event(); if ( $ev == ZOOM::Event::ZEND ) { next unless $results->[ $i - 1 ]; my $size = $results->[ $i - 1 ]->size(); if ( $size > 0 ) { - $callback->($i, $size); + $callback->( $i, $size ); } } } @@ -2304,20 +2324,22 @@ sub new_record_from_zebra { my $server = shift; my $raw_data = shift; + # Set the default indexing modes my $search_engine = C4::Context->preference("SearchEngine"); - if ($search_engine eq 'Elasticsearch') { + if ( $search_engine eq 'Elasticsearch' ) { return ref $raw_data eq 'MARC::Record' ? $raw_data : MARC::Record->new_from_xml( $raw_data, 'UTF-8' ); } - my $index_mode = ( $server eq 'biblioserver' ) - ? C4::Context->config('zebra_bib_index_mode') // 'dom' - : C4::Context->config('zebra_auth_index_mode') // 'dom'; + my $index_mode = + ( $server eq 'biblioserver' ) + ? C4::Context->config('zebra_bib_index_mode') // 'dom' + : C4::Context->config('zebra_auth_index_mode') // 'dom'; - my $marc_record = eval { + my $marc_record = eval { if ( $index_mode eq 'dom' ) { MARC::Record->new_from_xml( $raw_data, 'UTF-8' ); } else { - MARC::Record->new_from_usmarc( $raw_data ); + MARC::Record->new_from_usmarc($raw_data); } }; diff --git a/C4/Search/History.pm b/C4/Search/History.pm index c73df9834b..79113df2f1 100644 --- a/C4/Search/History.pm +++ b/C4/Search/History.pm @@ -6,7 +6,7 @@ use C4::Auth qw( get_session ); use C4::Context; use Koha::DateUtils qw( dt_from_string output_pref ); -use JSON qw( decode_json encode_json ); +use JSON qw( decode_json encode_json ); use URI::Escape qw( uri_escape uri_unescape ); sub add { @@ -30,30 +30,33 @@ sub add { ) }; my $sth = $dbh->prepare($query); - $sth->execute( $userid, $sessionid, $query_desc, $query_cgi, $type, - $total, ( $time ? $time : () ) ); + $sth->execute( + $userid, $sessionid, $query_desc, $query_cgi, $type, + $total, ( $time ? $time : () ) + ); } sub add_to_session { - my ($params) = @_; - my $cgi = $params->{cgi}; + my ($params) = @_; + my $cgi = $params->{cgi}; my $query_desc = $params->{query_desc} || "unknown"; - my $query_cgi = $params->{query_cgi} || "unknown"; + my $query_cgi = $params->{query_cgi} || "unknown"; my $total = $params->{total}; - my $type = $params->{type} || 'biblio'; + my $type = $params->{type} || 'biblio'; # To a cookie (the user is not logged in) my $now = dt_from_string; - my $id = $now->year . $now->month . $now->day . $now->hour . $now->minute . $now->second . int(rand(100)); + my $id = $now->year . $now->month . $now->day . $now->hour . $now->minute . $now->second . int( rand(100) ); my @recent_searches = get_from_session( { cgi => $cgi } ); push @recent_searches, { query_desc => $query_desc, query_cgi => $query_cgi, total => "$total", type => $type, + # FIXME We shouldn't store the formatted date - time => output_pref( { dt => $now, dateformat => 'iso', timeformat => '24hr' } ), - id => $id, + time => output_pref( { dt => $now, dateformat => 'iso', timeformat => '24hr' } ), + id => $id, }; shift @recent_searches if ( @recent_searches > 15 ); @@ -69,8 +72,8 @@ sub delete { my $previous = $params->{previous} || 0; my $interval = $params->{interval} || 0; - unless ( ref( $id ) ) { - $id = $id ? [ $id ] : []; + unless ( ref($id) ) { + $id = $id ? [$id] : []; } unless ( $userid or @$id or $interval ) { @@ -93,13 +96,13 @@ sub delete { if ($sessionid) { $query .= - $previous - ? q{ AND sessionid != ?} - : q{ AND sessionid = ?}; + $previous + ? q{ AND sessionid != ?} + : q{ AND sessionid = ?}; } $query .= q{ AND type = ?} - if $type; + if $type; # FIXME DATE_SUB is a Mysql-ism. Postgres uses: datefield - INTERVAL '6 months' $query .= q{ AND time < DATE_SUB( NOW(), INTERVAL ? DAY )} @@ -107,8 +110,8 @@ sub delete { $dbh->do( $query, {}, - ( @$id ? ( @$id ) : () ), - ( $userid ? $userid : () ), + ( @$id ? (@$id) : () ), + ( $userid ? $userid : () ), ( $sessionid ? $sessionid : () ), ( $type ? $type : () ), ( $interval ? $interval : () ), @@ -122,16 +125,16 @@ sub delete_from_cookie { return unless $cookie; - unless ( ref( $id ) ) { - $id = $id ? [ $id ] : []; + unless ( ref($id) ) { + $id = $id ? [$id] : []; } return unless @$id; my @searches; - if ( $cookie ){ - $cookie = uri_unescape( $cookie ); - if (decode_json( $cookie )) { - @searches = @{decode_json( $cookie )} + if ($cookie) { + $cookie = uri_unescape($cookie); + if ( decode_json($cookie) ) { + @searches = @{ decode_json($cookie) }; } } @@ -152,8 +155,8 @@ sub get { my $type = $params->{type}; my $previous = $params->{previous}; - unless ( ref( $id ) ) { - $id = $id ? [ $id ] : []; + unless ( ref($id) ) { + $id = $id ? [$id] : []; } unless ( $userid or @$id ) { @@ -176,19 +179,19 @@ sub get { if ($sessionid) { $query .= - $previous - ? q{ AND sessionid != ?} - : q{ AND sessionid = ?}; + $previous + ? q{ AND sessionid != ?} + : q{ AND sessionid = ?}; } $query .= q{ AND type = ?} - if $type; + if $type; my $dbh = C4::Context->dbh; my $sth = $dbh->prepare($query); $sth->execute( - ( @$id ? ( @$id ) : () ), - ( $userid ? $userid : () ), + ( @$id ? (@$id) : () ), + ( $userid ? $userid : () ), ( $sessionid ? $sessionid : () ), ( $type ? $type : () ) ); @@ -203,7 +206,7 @@ sub get_from_session { my $session = C4::Auth::get_session($sessionID); return () unless $session and $session->param('search_history'); my $obj = - eval { decode_json( uri_unescape( $session->param('search_history') ) ) }; + eval { decode_json( uri_unescape( $session->param('search_history') ) ) }; return () unless defined $obj; return () unless ref $obj eq 'ARRAY'; return @{$obj}; @@ -217,8 +220,10 @@ sub set_to_session { return () unless $sessionID; my $session = C4::Auth::get_session($sessionID); return () unless $session; - $session->param( 'search_history', - uri_escape( encode_json($search_history) ) ); + $session->param( + 'search_history', + uri_escape( encode_json($search_history) ) + ); $session->flush; } diff --git a/C4/Search/PazPar2.pm b/C4/Search/PazPar2.pm index 886cc868ca..a2a0ddbc27 100644 --- a/C4/Search/PazPar2.pm +++ b/C4/Search/PazPar2.pm @@ -40,13 +40,13 @@ C4::Search::PazPar2 - implement client for PazPar2 =cut sub new { - my $class = shift; + my $class = shift; my $endpoint = shift; my $self = {}; $self->{'endpoint'} = $endpoint; - $self->{'session'} = ''; - $self->{'ua'} = LWP::UserAgent->new; + $self->{'session'} = ''; + $self->{'ua'} = LWP::UserAgent->new; bless $self, $class; return $self; @@ -55,12 +55,12 @@ sub new { sub init { my $self = shift; - my $uri = URI->new($self->{'endpoint'}); - $uri->query_param(command => 'init'); + my $uri = URI->new( $self->{'endpoint'} ); + $uri->query_param( command => 'init' ); my $response = $self->{'ua'}->get($uri); - if ($response->is_success) { - my $message = XMLin($response->content); - if ($message->{'status'} eq 'OK') { + if ( $response->is_success ) { + my $message = XMLin( $response->content ); + if ( $message->{'status'} eq 'OK' ) { $self->{'session'} = $message->{'session'}; } } else { @@ -69,15 +69,16 @@ sub init { } sub search { - my $self = shift; + my $self = shift; my $query = shift; - my $uri = URI->new($self->{'endpoint'}); - $uri->query_param(command => 'search'); - $uri->query_param(session => $self->{'session'}); - $uri->query_param(query => $query); + my $uri = URI->new( $self->{'endpoint'} ); + $uri->query_param( command => 'search' ); + $uri->query_param( session => $self->{'session'} ); + $uri->query_param( query => $query ); my $response = $self->{'ua'}->get($uri); - if ($response->is_success) { + if ( $response->is_success ) { + #print $response->content, "\n"; } else { warn $response->status_line; @@ -88,11 +89,11 @@ sub search { sub stat { my $self = shift; - my $uri = URI->new($self->{'endpoint'}); - $uri->query_param(command => 'stat'); - $uri->query_param(session => $self->{'session'}); + my $uri = URI->new( $self->{'endpoint'} ); + $uri->query_param( command => 'stat' ); + $uri->query_param( session => $self->{'session'} ); my $response = $self->{'ua'}->get($uri); - if ($response->is_success) { + if ( $response->is_success ) { return $response->content; } else { warn $response->status_line; @@ -101,41 +102,42 @@ sub stat { } sub show { - my $self = shift; + my $self = shift; my $start = shift; my $count = shift; - my $sort = shift; + my $sort = shift; - my $uri = URI->new($self->{'endpoint'}); - $uri->query_param(command => 'show'); - $uri->query_param(start => $start); - $uri->query_param(num => $count); - $uri->query_param(block => 1); - $uri->query_param(session => $self->{'session'}); - $uri->query_param(sort => $sort); + my $uri = URI->new( $self->{'endpoint'} ); + $uri->query_param( command => 'show' ); + $uri->query_param( start => $start ); + $uri->query_param( num => $count ); + $uri->query_param( block => 1 ); + $uri->query_param( session => $self->{'session'} ); + $uri->query_param( sort => $sort ); my $response = $self->{'ua'}->get($uri); - if ($response->is_success) { + + if ( $response->is_success ) { return $response->content; } else { warn $response->status_line; return; } - + } sub record { - my $self = shift; - my $id = shift; + my $self = shift; + my $id = shift; my $offset = shift; - my $uri = URI->new($self->{'endpoint'}); - $uri->query_param(command => 'record'); - $uri->query_param(id => $id); - $uri->query_param(offset => $offset); - $uri->query_param(binary => 1); - $uri->query_param(session => $self->{'session'}); + my $uri = URI->new( $self->{'endpoint'} ); + $uri->query_param( command => 'record' ); + $uri->query_param( id => $id ); + $uri->query_param( offset => $offset ); + $uri->query_param( binary => 1 ); + $uri->query_param( session => $self->{'session'} ); my $response = $self->{'ua'}->get($uri); - if ($response->is_success) { + if ( $response->is_success ) { return $response->content; } else { warn $response->status_line; @@ -147,12 +149,12 @@ sub termlist { my $self = shift; my $name = shift; - my $uri = URI->new($self->{'endpoint'}); - $uri->query_param(command => 'termlist'); - $uri->query_param(name => $name); - $uri->query_param(session => $self->{'session'}); + my $uri = URI->new( $self->{'endpoint'} ); + $uri->query_param( command => 'termlist' ); + $uri->query_param( name => $name ); + $uri->query_param( session => $self->{'session'} ); my $response = $self->{'ua'}->get($uri); - if ($response->is_success) { + if ( $response->is_success ) { return $response->content; } else { warn $response->status_line; diff --git a/C4/Serials.pm b/C4/Serials.pm index 4421bf35b0..da29ddbe30 100644 --- a/C4/Serials.pm +++ b/C4/Serials.pm @@ -20,7 +20,7 @@ package C4::Serials; use Modern::Perl; -use Carp qw( croak ); +use Carp qw( croak ); use Date::Calc qw( Add_Delta_Days Add_Delta_YM @@ -30,14 +30,14 @@ use Date::Calc qw( Today ); use DateTime; -use POSIX qw( strftime ); +use POSIX qw( strftime ); use Scalar::Util qw( looks_like_number ); use Try::Tiny; -use C4::Auth qw( haspermission ); +use C4::Auth qw( haspermission ); use C4::Biblio qw( GetMarcFromKohaField ModBiblio ); use C4::Context; -use C4::Log qw( logaction ); # logaction +use C4::Log qw( logaction ); # logaction use C4::Serials::Frequency qw( GetSubscriptionFrequency ); use C4::Serials::Numberpattern; use Koha::AdditionalFieldValues; @@ -73,39 +73,40 @@ use constant MISSING_STATUSES => ( MISSING_LOST ); -our (@ISA, @EXPORT_OK); +our ( @ISA, @EXPORT_OK ); + BEGIN { require Exporter; - @ISA = qw(Exporter); + @ISA = qw(Exporter); @EXPORT_OK = qw( - NewSubscription ModSubscription DelSubscription - GetSubscription CountSubscriptionFromBiblionumber GetSubscriptionsFromBiblionumber - SearchSubscriptions - GetFullSubscriptionsFromBiblionumber GetFullSubscription ModSubscriptionHistory - HasSubscriptionStrictlyExpired HasSubscriptionExpired GetExpirationDate abouttoexpire - GetFictiveIssueNumber - GetSubscriptionHistoryFromSubscriptionId + NewSubscription ModSubscription DelSubscription + GetSubscription CountSubscriptionFromBiblionumber GetSubscriptionsFromBiblionumber + SearchSubscriptions + GetFullSubscriptionsFromBiblionumber GetFullSubscription ModSubscriptionHistory + HasSubscriptionStrictlyExpired HasSubscriptionExpired GetExpirationDate abouttoexpire + GetFictiveIssueNumber + GetSubscriptionHistoryFromSubscriptionId - GetNextSeq GetSeq NewIssue GetSerials - GetLatestSerials ModSerialStatus GetNextDate - CloseSubscription ReopenSubscription - subscriptionCurrentlyOnOrder - can_claim_subscription can_edit_subscription can_show_subscription - GetSerials2 - GetSubscriptionLength ReNewSubscription GetLateOrMissingIssues - GetSerialInformation AddItem2Serial - PrepareSerialsData GetNextExpected ModNextExpected - GetSubscriptionIrregularities - GetPreviousSerialid + GetNextSeq GetSeq NewIssue GetSerials + GetLatestSerials ModSerialStatus GetNextDate + CloseSubscription ReopenSubscription + subscriptionCurrentlyOnOrder + can_claim_subscription can_edit_subscription can_show_subscription + GetSerials2 + GetSubscriptionLength ReNewSubscription GetLateOrMissingIssues + GetSerialInformation AddItem2Serial + PrepareSerialsData GetNextExpected ModNextExpected + GetSubscriptionIrregularities + GetPreviousSerialid - GetSuppliersWithLateIssues - getroutinglist delroutingmember addroutingmember - reorder_members - check_routing updateClaim - CountIssues - HasItems + GetSuppliersWithLateIssues + getroutinglist delroutingmember addroutingmember + reorder_members + check_routing updateClaim + CountIssues + HasItems - findSerialsByStatus + findSerialsByStatus ); } @@ -138,9 +139,9 @@ the array is in name order =cut sub GetSuppliersWithLateIssues { - my $dbh = C4::Context->dbh; - my $statuses = join(',', ( LATE, MISSING_STATUSES, CLAIMED ) ); - my $query = qq| + my $dbh = C4::Context->dbh; + my $statuses = join( ',', ( LATE, MISSING_STATUSES, CLAIMED ) ); + my $query = qq| SELECT DISTINCT id, name FROM subscription LEFT JOIN serial ON serial.subscriptionid=subscription.subscriptionid @@ -152,7 +153,7 @@ sub GetSuppliersWithLateIssues { ) AND subscription.closed = 0 ORDER BY name|; - return $dbh->selectall_arrayref($query, { Slice => {} }); + return $dbh->selectall_arrayref( $query, { Slice => {} } ); } =head2 GetSubscriptionHistoryFromSubscriptionId @@ -216,7 +217,8 @@ sub GetSerialInformation { #It is ASSUMED that GetMarcItem ALWAYS WORK... #Maybe GetMarcItem should return values on failure - my $itemprocessed = C4::Items::PrepareItemrecordDisplay( $data->{'biblionumber'}, $itemnum->[0], $data ); + my $itemprocessed = + C4::Items::PrepareItemrecordDisplay( $data->{'biblionumber'}, $itemnum->[0], $data ); $itemprocessed->{'itemnumber'} = $itemnum->[0]; $itemprocessed->{'itemid'} = $itemnum->[0]; $itemprocessed->{'serialid'} = $serialid; @@ -234,8 +236,8 @@ sub GetSerialInformation { } $data->{ "status" . $data->{'serstatus'} } = 1; $data->{'subscriptionexpired'} = HasSubscriptionExpired( $data->{'subscriptionid'} ) && $data->{'status'} == 1; - $data->{'abouttoexpire'} = abouttoexpire( $data->{'subscriptionid'} ); - $data->{cannotedit} = not can_edit_subscription( $data ); + $data->{'abouttoexpire'} = abouttoexpire( $data->{'subscriptionid'} ); + $data->{cannotedit} = not can_edit_subscription($data); return $data; } @@ -250,7 +252,7 @@ returns the number of rows affected sub AddItem2Serial { my ( $serialid, $itemnumber ) = @_; - return unless ($serialid and $itemnumber); + return unless ( $serialid and $itemnumber ); my $dbh = C4::Context->dbh; my $rq = $dbh->prepare("INSERT INTO `serialitems` SET serialid=? , itemnumber=?"); @@ -291,11 +293,10 @@ sub GetSubscription { return unless $subscription; - $subscription->{cannotedit} = not can_edit_subscription( $subscription ); + $subscription->{cannotedit} = not can_edit_subscription($subscription); if ( my $mana_id = $subscription->{mana_id} ) { - my $mana_subscription = Koha::SharedContent::get_entity_by_id( - 'subscription', $mana_id, {usecomments => 1}); + my $mana_subscription = Koha::SharedContent::get_entity_by_id( 'subscription', $mana_id, { usecomments => 1 } ); $subscription->{comments} = $mana_subscription->{data}->{comments}; } @@ -314,8 +315,8 @@ sub GetFullSubscription { return unless ($subscriptionid); - my $dbh = C4::Context->dbh; - my $query = qq| + my $dbh = C4::Context->dbh; + my $query = qq| SELECT serial.serialid, serial.serialseq, serial.planneddate, @@ -341,9 +342,9 @@ sub GetFullSubscription { my $sth = $dbh->prepare($query); $sth->execute($subscriptionid); my $subscriptions = $sth->fetchall_arrayref( {} ); - if (scalar @$subscriptions) { + if ( scalar @$subscriptions ) { my $cannotedit = not can_edit_subscription( $subscriptions->[0] ); - for my $subscription ( @$subscriptions ) { + for my $subscription (@$subscriptions) { $subscription->{cannotedit} = $cannotedit; } } @@ -370,7 +371,7 @@ sub PrepareSerialsData { my $first; my $previousnote = ""; - foreach my $subs (@{$lines}) { + foreach my $subs ( @{$lines} ) { $subs->{ "status" . $subs->{'status'} } = 1; if ( grep { $_ == $subs->{status} } ( EXPECTED, LATE, MISSING_STATUSES, CLAIMED ) ) { $subs->{"checked"} = 1; @@ -415,8 +416,8 @@ sub GetSubscriptionsFromBiblionumber { return unless ($biblionumber); - my $dbh = C4::Context->dbh; - my $query = qq( + my $dbh = C4::Context->dbh; + my $query = qq( SELECT subscription.*, branches.branchname, subscriptionhistory.*, @@ -433,14 +434,14 @@ sub GetSubscriptionsFromBiblionumber { $sth->execute($biblionumber); my @res; while ( my $subs = $sth->fetchrow_hashref ) { - $subs->{opacnote} //= ""; + $subs->{opacnote} //= ""; $subs->{ "periodicity" . $subs->{periodicity} } = 1; $subs->{ "numberpattern" . $subs->{numberpattern} } = 1; $subs->{ "status" . $subs->{'status'} } = 1; $subs->{'abouttoexpire'} = abouttoexpire( $subs->{'subscriptionid'} ); $subs->{'subscriptionexpired'} = HasSubscriptionExpired( $subs->{'subscriptionid'} ); - $subs->{cannotedit} = not can_edit_subscription( $subs ); + $subs->{cannotedit} = not can_edit_subscription($subs); push @res, $subs; } return \@res; @@ -482,9 +483,9 @@ sub GetFullSubscriptionsFromBiblionumber { my $sth = $dbh->prepare($query); $sth->execute($biblionumber); my $subscriptions = $sth->fetchall_arrayref( {} ); - if (scalar @$subscriptions) { + if ( scalar @$subscriptions ) { my $cannotedit = not can_edit_subscription( $subscriptions->[0] ); - for my $subscription ( @$subscriptions ) { + for my $subscription (@$subscriptions) { $subscription->{cannotedit} = $cannotedit; } } @@ -524,16 +525,14 @@ sub SearchSubscriptions { $params //= {}; - my $additional_fields = $args->{additional_fields} // []; + my $additional_fields = $args->{additional_fields} // []; my $matching_record_ids_for_additional_fields = []; - if ( @$additional_fields ) { + if (@$additional_fields) { my @subscriptions = Koha::Subscriptions->filter_by_additional_fields($additional_fields)->as_list; return () unless @subscriptions; - $matching_record_ids_for_additional_fields = [ map { - $_->subscriptionid - } @subscriptions ]; + $matching_record_ids_for_additional_fields = [ map { $_->subscriptionid } @subscriptions ]; } my $query = q| @@ -563,28 +562,28 @@ sub SearchSubscriptions { $query .= q| WHERE 1|; my @where_strs; my @where_args; - if( $args->{biblionumber} ) { + if ( $args->{biblionumber} ) { push @where_strs, "biblio.biblionumber = ?"; push @where_args, $args->{biblionumber}; } - if( $args->{title} ){ + if ( $args->{title} ) { my @words = split / /, $args->{title}; - my (@strs, @args); + my ( @strs, @args ); foreach my $word (@words) { push @strs, "biblio.title LIKE ?"; push @args, "%$word%"; } if (@strs) { - push @where_strs, '(' . join (' AND ', @strs) . ')'; + push @where_strs, '(' . join( ' AND ', @strs ) . ')'; push @where_args, @args; } } - if( $args->{issn} ){ + if ( $args->{issn} ) { push @where_strs, "biblioitems.issn LIKE ?"; push @where_args, "%$args->{issn}%"; } - if( $args->{ean} ){ + if ( $args->{ean} ) { push @where_strs, "biblioitems.ean LIKE ?"; push @where_args, "%$args->{ean}%"; } @@ -592,15 +591,15 @@ sub SearchSubscriptions { push @where_strs, "subscription.callnumber LIKE ?"; push @where_args, "%$args->{callnumber}%"; } - if( $args->{publisher} ){ + if ( $args->{publisher} ) { push @where_strs, "biblioitems.publishercode LIKE ?"; push @where_args, "%$args->{publisher}%"; } - if( $args->{bookseller} ){ + if ( $args->{bookseller} ) { push @where_strs, "aqbooksellers.name LIKE ?"; push @where_args, "%$args->{bookseller}%"; } - if( $args->{branch} ){ + if ( $args->{branch} ) { push @where_strs, "subscription.branchcode = ?"; push @where_args, "$args->{branch}"; } @@ -612,17 +611,15 @@ sub SearchSubscriptions { push @where_strs, "subscription.enddate <= ?"; push @where_args, "$args->{expiration_date}"; } - if( defined $args->{closed} ){ + if ( defined $args->{closed} ) { push @where_strs, "subscription.closed = ?"; push @where_args, "$args->{closed}"; } - if(@where_strs){ - $query .= ' AND ' . join(' AND ', @where_strs); + if (@where_strs) { + $query .= ' AND ' . join( ' AND ', @where_strs ); } - if ( @$additional_fields ) { - $query .= ' AND subscriptionid IN (' - . join( ', ', @$matching_record_ids_for_additional_fields ) - . ')'; + if (@$additional_fields) { + $query .= ' AND subscriptionid IN (' . join( ', ', @$matching_record_ids_for_additional_fields ) . ')'; } $query .= " ORDER BY " . $args->{orderby} if $args->{orderby}; @@ -630,7 +627,7 @@ sub SearchSubscriptions { my $dbh = C4::Context->dbh; my $sth = $dbh->prepare($query); $sth->execute(@where_args); - my $results = $sth->fetchall_arrayref( {} ); + my $results = $sth->fetchall_arrayref( {} ); my $total_results = @{$results}; @@ -638,18 +635,17 @@ sub SearchSubscriptions { $results = [ splice( @{$results}, 0, $params->{results_limit} ) ]; } - for my $subscription ( @$results ) { - $subscription->{cannotedit} = not can_edit_subscription( $subscription ); - $subscription->{cannotdisplay} = not can_show_subscription( $subscription ); + for my $subscription (@$results) { + $subscription->{cannotedit} = not can_edit_subscription($subscription); + $subscription->{cannotdisplay} = not can_show_subscription($subscription); - my $subscription_object = Koha::Subscriptions->find($subscription->{subscriptionid}); + my $subscription_object = Koha::Subscriptions->find( $subscription->{subscriptionid} ); $subscription->{additional_field_values} = $subscription_object->get_additional_field_values_for_template; } return wantarray ? @{$results} : { results => $results, total => $total_results }; } - =head2 GetSerials ($totalissues,@serials) = GetSerials($subscriptionid); @@ -673,7 +669,7 @@ sub GetSerials { $count = 5 unless ($count); my @serials; my $statuses = join( ',', ( ARRIVED, MISSING_STATUSES, NOT_ISSUED ) ); - my $query = "SELECT serialid,serialseq, status, publisheddate, + my $query = "SELECT serialid,serialseq, status, publisheddate, publisheddatetext, planneddate,notes, routingnotes FROM serial WHERE subscriptionid = ? AND status NOT IN ( $statuses ) @@ -682,7 +678,7 @@ sub GetSerials { $sth->execute($subscriptionid); while ( my $line = $sth->fetchrow_hashref ) { - $line->{ "status" . $line->{status} } = 1; # fills a "statusX" value, used for template status select list + $line->{ "status" . $line->{status} } = 1; # fills a "statusX" value, used for template status select list push @serials, $line; } @@ -698,7 +694,7 @@ sub GetSerials { $sth->execute($subscriptionid); while ( ( my $line = $sth->fetchrow_hashref ) && $counter < $count ) { $counter++; - $line->{ "status" . $line->{status} } = 1; # fills a "statusX" value, used for template status select list + $line->{ "status" . $line->{status} } = 1; # fills a "statusX" value, used for template status select list push @serials, $line; } @@ -724,7 +720,7 @@ $statuses is an arrayref of statuses and is mandatory. sub GetSerials2 { my ( $subscription, $statuses ) = @_; - return unless ($subscription and @$statuses); + return unless ( $subscription and @$statuses ); my $dbh = C4::Context->dbh; my $query = q| @@ -733,8 +729,7 @@ sub GetSerials2 { FROM serial WHERE subscriptionid=? | - . q| AND status IN (| . join( ",", ('?') x @$statuses ) . q|)| - . q| + . q| AND status IN (| . join( ",", ('?') x @$statuses ) . q|)| . q| ORDER BY publisheddate,serialid DESC |; my $sth = $dbh->prepare($query); @@ -742,7 +737,7 @@ sub GetSerials2 { my @serials; while ( my $line = $sth->fetchrow_hashref ) { - $line->{ "status" . $line->{status} } = 1; # fills a "statusX" value, used for template status select list + $line->{ "status" . $line->{status} } = 1; # fills a "statusX" value, used for template status select list push @serials, $line; } return @serials; @@ -760,12 +755,12 @@ a ref to an array which contains all of the latest serials stored into a hash. sub GetLatestSerials { my ( $subscriptionid, $limit ) = @_; - return unless ($subscriptionid and $limit); + return unless ( $subscriptionid and $limit ); my $dbh = C4::Context->dbh; my $statuses = join( ',', ( ARRIVED, MISSING_STATUSES ) ); - my $strsth = "SELECT serialid,serialseq, status, planneddate, publisheddate, publisheddatetext, notes + my $strsth = "SELECT serialid,serialseq, status, planneddate, publisheddate, publisheddatetext, notes FROM serial WHERE subscriptionid = ? AND status IN ($statuses) @@ -775,7 +770,7 @@ sub GetLatestSerials { $sth->execute($subscriptionid); my @serials; while ( my $line = $sth->fetchrow_hashref ) { - $line->{ "status" . $line->{status} } = 1; # fills a "statusX" value, used for template status select list + $line->{ "status" . $line->{status} } = 1; # fills a "statusX" value, used for template status select list push @serials, $line; } @@ -794,7 +789,7 @@ the serialid sub GetPreviousSerialid { my ( $subscriptionid, $nth ) = @_; $nth ||= 1; - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $return = undef; # Status 2: Arrived @@ -832,21 +827,23 @@ This function get the next issue for the subscription given on input arg =cut sub GetNextSeq { - my ($subscription, $pattern, $frequency, $planneddate, $count_forward) = @_; + my ( $subscription, $pattern, $frequency, $planneddate, $count_forward ) = @_; - return unless ($subscription and $pattern); + return unless ( $subscription and $pattern ); - my ( $newlastvalue1, $newlastvalue2, $newlastvalue3, - $newinnerloop1, $newinnerloop2, $newinnerloop3 ); + my ( + $newlastvalue1, $newlastvalue2, $newlastvalue3, + $newinnerloop1, $newinnerloop2, $newinnerloop3 + ); my $count = $count_forward || 1; - if ($subscription->{'skip_serialseq'}) { + if ( $subscription->{'skip_serialseq'} ) { my @irreg = split /;/, $subscription->{'irregularity'}; - if(@irreg > 0) { + if ( @irreg > 0 ) { my $irregularities = {}; - $irregularities->{$_} = 1 foreach(@irreg); - my $issueno = GetFictiveIssueNumber($subscription, $planneddate, $frequency) + 1; - while($irregularities->{$issueno}) { + $irregularities->{$_} = 1 foreach (@irreg); + my $issueno = GetFictiveIssueNumber( $subscription, $planneddate, $frequency ) + 1; + while ( $irregularities->{$issueno} ) { $count++; $issueno++; } @@ -854,9 +851,9 @@ sub GetNextSeq { } my $numberingmethod = $pattern->{numberingmethod}; - my $calculated = ""; + my $calculated = ""; if ($numberingmethod) { - $calculated = $numberingmethod; + $calculated = $numberingmethod; my $locale = $subscription->{locale}; $newlastvalue1 = $subscription->{lastvalue1} || 0; $newlastvalue2 = $subscription->{lastvalue2} || 0; @@ -865,51 +862,58 @@ sub GetNextSeq { $newinnerloop2 = $subscription->{innerloop2} || 0; $newinnerloop3 = $subscription->{innerloop3} || 0; my %calc; - foreach(qw/X Y Z/) { - $calc{$_} = 1 if ($numberingmethod =~ /\{$_\}/); + + foreach (qw/X Y Z/) { + $calc{$_} = 1 if ( $numberingmethod =~ /\{$_\}/ ); } - for(my $i = 0; $i < $count; $i++) { - if($calc{'X'}) { + for ( my $i = 0 ; $i < $count ; $i++ ) { + if ( $calc{'X'} ) { + # check if we have to increase the new value. $newinnerloop1 += 1; - if ($newinnerloop1 >= $pattern->{every1}) { - $newinnerloop1 = 0; + if ( $newinnerloop1 >= $pattern->{every1} ) { + $newinnerloop1 = 0; $newlastvalue1 += $pattern->{add1}; } + # reset counter if needed. - $newlastvalue1 = $pattern->{setto1} if ($newlastvalue1 > $pattern->{whenmorethan1}); + $newlastvalue1 = $pattern->{setto1} if ( $newlastvalue1 > $pattern->{whenmorethan1} ); } - if($calc{'Y'}) { + if ( $calc{'Y'} ) { + # check if we have to increase the new value. $newinnerloop2 += 1; - if ($newinnerloop2 >= $pattern->{every2}) { - $newinnerloop2 = 0; + if ( $newinnerloop2 >= $pattern->{every2} ) { + $newinnerloop2 = 0; $newlastvalue2 += $pattern->{add2}; } + # reset counter if needed. - $newlastvalue2 = $pattern->{setto2} if ($newlastvalue2 > $pattern->{whenmorethan2}); + $newlastvalue2 = $pattern->{setto2} if ( $newlastvalue2 > $pattern->{whenmorethan2} ); } - if($calc{'Z'}) { + if ( $calc{'Z'} ) { + # check if we have to increase the new value. $newinnerloop3 += 1; - if ($newinnerloop3 >= $pattern->{every3}) { - $newinnerloop3 = 0; + if ( $newinnerloop3 >= $pattern->{every3} ) { + $newinnerloop3 = 0; $newlastvalue3 += $pattern->{add3}; } + # reset counter if needed. - $newlastvalue3 = $pattern->{setto3} if ($newlastvalue3 > $pattern->{whenmorethan3}); + $newlastvalue3 = $pattern->{setto3} if ( $newlastvalue3 > $pattern->{whenmorethan3} ); } } - if($calc{'X'}) { + if ( $calc{'X'} ) { my $newlastvalue1string = _numeration( $newlastvalue1, $pattern->{numbering1}, $locale ); $calculated =~ s/\{X\}/$newlastvalue1string/g; } - if($calc{'Y'}) { + if ( $calc{'Y'} ) { my $newlastvalue2string = _numeration( $newlastvalue2, $pattern->{numbering2}, $locale ); $calculated =~ s/\{Y\}/$newlastvalue2string/g; } - if($calc{'Z'}) { + if ( $calc{'Z'} ) { my $newlastvalue3string = _numeration( $newlastvalue3, $pattern->{numbering3}, $locale ); $calculated =~ s/\{Z\}/$newlastvalue3string/g; } @@ -923,9 +927,11 @@ sub GetNextSeq { } - return ($calculated, - $newlastvalue1, $newlastvalue2, $newlastvalue3, - $newinnerloop1, $newinnerloop2, $newinnerloop3); + return ( + $calculated, + $newlastvalue1, $newlastvalue2, $newlastvalue3, + $newinnerloop1, $newinnerloop2, $newinnerloop3 + ); } =head2 GetSeq @@ -940,24 +946,27 @@ the sequence in string format =cut sub GetSeq { - my ($subscription, $pattern) = @_; + my ( $subscription, $pattern ) = @_; - return unless ($subscription and $pattern); + return unless ( $subscription and $pattern ); my $locale = $subscription->{locale}; my $calculated = $pattern->{numberingmethod}; my $newlastvalue1 = $subscription->{'lastvalue1'} || 0; - $newlastvalue1 = _numeration($newlastvalue1, $pattern->{numbering1}, $locale) if ($pattern->{numbering1}); # reset counter if needed. + $newlastvalue1 = _numeration( $newlastvalue1, $pattern->{numbering1}, $locale ) + if ( $pattern->{numbering1} ); # reset counter if needed. $calculated =~ s/\{X\}/$newlastvalue1/g; my $newlastvalue2 = $subscription->{'lastvalue2'} || 0; - $newlastvalue2 = _numeration($newlastvalue2, $pattern->{numbering2}, $locale) if ($pattern->{numbering2}); # reset counter if needed. + $newlastvalue2 = _numeration( $newlastvalue2, $pattern->{numbering2}, $locale ) + if ( $pattern->{numbering2} ); # reset counter if needed. $calculated =~ s/\{Y\}/$newlastvalue2/g; my $newlastvalue3 = $subscription->{'lastvalue3'} || 0; - $newlastvalue3 = _numeration($newlastvalue3, $pattern->{numbering3}, $locale) if ($pattern->{numbering3}); # reset counter if needed. + $newlastvalue3 = _numeration( $newlastvalue3, $pattern->{numbering3}, $locale ) + if ( $pattern->{numbering3} ); # reset counter if needed. $calculated =~ s/\{Z\}/$newlastvalue3/g; my $dt = dt_from_string( $subscription->{firstacquidate} ); @@ -996,7 +1005,7 @@ sub GetExpirationDate { return if ( scalar(@date) != 3 || not check_date(@date) ); - my $frequency = C4::Serials::Frequency::GetSubscriptionFrequency($subscription->{periodicity}); + my $frequency = C4::Serials::Frequency::GetSubscriptionFrequency( $subscription->{periodicity} ); if ( $frequency and $frequency->{unit} ) { # If Not Irregular @@ -1013,7 +1022,7 @@ sub GetExpirationDate { } } elsif ( $subscription->{weeklength} ) { if ( $$subscription{startdate} ) { - my @date = split( /-/, $subscription->{startdate} ); + my @date = split( /-/, $subscription->{startdate} ); my @enddate = Add_Delta_Days( $date[0], $date[1], $date[2], $subscription->{weeklength} * 7 ); $enddate = sprintf( "%04d-%02d-%02d", $enddate[0], $enddate[1], $enddate[2] ); } @@ -1040,9 +1049,9 @@ sub CountSubscriptionFromBiblionumber { return unless ($biblionumber); - my $dbh = C4::Context->dbh; - my $query = "SELECT count(*) FROM subscription WHERE biblionumber=?"; - my $sth = $dbh->prepare($query); + my $dbh = C4::Context->dbh; + my $query = "SELECT count(*) FROM subscription WHERE biblionumber=?"; + my $sth = $dbh->prepare($query); $sth->execute($biblionumber); my $subscriptionsnumber = $sth->fetchrow; return $subscriptionsnumber; @@ -1086,8 +1095,10 @@ Note : if we change from "waited" to something else,then we will have to create =cut sub ModSerialStatus { - my ($serialid, $serialseq, $planneddate, $publisheddate, $publisheddatetext, - $status, $notes, $count_forward) = @_; + my ( + $serialid, $serialseq, $planneddate, $publisheddate, $publisheddatetext, + $status, $notes, $count_forward + ) = @_; return unless ($serialid); @@ -1100,7 +1111,7 @@ sub ModSerialStatus { FROM serial, subscription WHERE serial.subscriptionid=subscription.subscriptionid AND serialid=?"; - my $sth = $dbh->prepare($query); + my $sth = $dbh->prepare($query); $sth->execute($serialid); my ( $subscriptionid, $oldstatus, $periodicity, $routingnotes ) = $sth->fetchrow; my $frequency = GetSubscriptionFrequency($periodicity); @@ -1117,8 +1128,10 @@ sub ModSerialStatus { WHERE serialid = ? '; $sth = $dbh->prepare($query); - $sth->execute( $serialseq, $publisheddate, $publisheddatetext, - $planneddate, $status, $notes, $routingnotes, $serialid ); + $sth->execute( + $serialseq, $publisheddate, $publisheddatetext, + $planneddate, $status, $notes, $routingnotes, $serialid + ); $query = "SELECT * FROM subscription WHERE subscriptionid = ?"; $sth = $dbh->prepare($query); $sth->execute($subscriptionid); @@ -1129,17 +1142,18 @@ sub ModSerialStatus { $sth->execute($subscriptionid); my ( $missinglist, $recievedlist ) = $sth->fetchrow; - if ( $status == ARRIVED || ($oldstatus == ARRIVED && $status != ARRIVED) ) { - $recievedlist = _handle_seqno($serialseq, $recievedlist); + if ( $status == ARRIVED || ( $oldstatus == ARRIVED && $status != ARRIVED ) ) { + $recievedlist = _handle_seqno( $serialseq, $recievedlist ); } # in case serial has been previously marked as missing - if (grep /$status/, (EXPECTED, ARRIVED, LATE, CLAIMED)) { - $missinglist = _handle_seqno($serialseq, $missinglist, 'REMOVE'); + if ( grep /$status/, ( EXPECTED, ARRIVED, LATE, CLAIMED ) ) { + $missinglist = _handle_seqno( $serialseq, $missinglist, 'REMOVE' ); } - $missinglist = _handle_seqno($serialseq, $missinglist) if grep { $_ == $status } MISSING_STATUSES; - $missinglist .= "; not issued $serialseq" if $status == NOT_ISSUED and not _handle_seqno($serialseq, $missinglist, 'CHECK'); + $missinglist = _handle_seqno( $serialseq, $missinglist ) if grep { $_ == $status } MISSING_STATUSES; + $missinglist .= "; not issued $serialseq" + if $status == NOT_ISSUED and not _handle_seqno( $serialseq, $missinglist, 'CHECK' ); $query = "UPDATE subscriptionhistory SET recievedlist=?, missinglist=? WHERE subscriptionid=?"; $sth = $dbh->prepare($query); @@ -1150,28 +1164,35 @@ sub ModSerialStatus { } # create new expected entry if needed (ie : was "expected" and has changed) - my $otherIssueExpected = scalar findSerialsByStatus(EXPECTED, $subscriptionid); + my $otherIssueExpected = scalar findSerialsByStatus( EXPECTED, $subscriptionid ); if ( !$otherIssueExpected && $oldstatus == EXPECTED && $status != EXPECTED ) { my $subscription = GetSubscription($subscriptionid); - my $pattern = C4::Serials::Numberpattern::GetSubscriptionNumberpattern($subscription->{numberpattern}); - my $frequency = C4::Serials::Frequency::GetSubscriptionFrequency($subscription->{periodicity}); + my $pattern = C4::Serials::Numberpattern::GetSubscriptionNumberpattern( $subscription->{numberpattern} ); + my $frequency = C4::Serials::Frequency::GetSubscriptionFrequency( $subscription->{periodicity} ); # next issue number my ( $newserialseq, $newlastvalue1, $newlastvalue2, $newlastvalue3, $newinnerloop1, $newinnerloop2, $newinnerloop3 - ) - = GetNextSeq( $subscription, $pattern, $frequency, $publisheddate, $count ); + ) = GetNextSeq( $subscription, $pattern, $frequency, $publisheddate, $count ); # next date (calculated from actual date & frequency parameters) - my $nextpublisheddate = GetNextDate($subscription, $publisheddate, $frequency, 1); - my $nextpubdate = $nextpublisheddate; - $query = "UPDATE subscription SET lastvalue1=?, lastvalue2=?, lastvalue3=?, innerloop1=?, innerloop2=?, innerloop3=? + my $nextpublisheddate = GetNextDate( $subscription, $publisheddate, $frequency, 1 ); + my $nextpubdate = $nextpublisheddate; + $query = + "UPDATE subscription SET lastvalue1=?, lastvalue2=?, lastvalue3=?, innerloop1=?, innerloop2=?, innerloop3=? WHERE subscriptionid = ?"; $sth = $dbh->prepare($query); - $sth->execute( $newlastvalue1, $newlastvalue2, $newlastvalue3, $newinnerloop1, $newinnerloop2, $newinnerloop3, $subscriptionid ); + $sth->execute( + $newlastvalue1, $newlastvalue2, $newlastvalue3, $newinnerloop1, $newinnerloop2, $newinnerloop3, + $subscriptionid + ); my $newnote = C4::Context->preference('PreserveSerialNotes') ? $notes : ""; - NewIssue( $newserialseq, $subscriptionid, $subscription->{'biblionumber'}, 1, $nextpubdate, $nextpubdate, undef, $newnote, $routingnotes ); + NewIssue( + $newserialseq, $subscriptionid, $subscription->{'biblionumber'}, 1, $nextpubdate, $nextpubdate, + undef, $newnote, $routingnotes + ); + # check if an alert must be sent... (= a letter is defined & status became "arrived" if ( $subscription->{letter} && $status == ARRIVED && $oldstatus != ARRIVED ) { require C4::Letters; @@ -1183,18 +1204,19 @@ sub ModSerialStatus { } sub _handle_seqno { -# Adds or removes seqno from list when needed; returns list -# Or checks and returns true when present - my ( $seq, $list, $op ) = @_; # op = ADD | REMOVE | CHECK (default: ADD) + # Adds or removes seqno from list when needed; returns list + # Or checks and returns true when present + + my ( $seq, $list, $op ) = @_; # op = ADD | REMOVE | CHECK (default: ADD) my $seq_r = $seq; - $seq_r =~ s/([()])/\\$1/g; # Adjust disturbing parentheses for regex, maybe extend in future + $seq_r =~ s/([()])/\\$1/g; # Adjust disturbing parentheses for regex, maybe extend in future - if( !$op or $op eq 'ADD' ) { + if ( !$op or $op eq 'ADD' ) { $list .= "; $seq" if $list !~ /(^|;)\s*$seq_r(?=;|$)/; - } elsif( $op eq 'REMOVE' ) { - $list=~ s/(^|;)\s*(not issued )?$seq_r(?=;|$)//g; - } else { # CHECK + } elsif ( $op eq 'REMOVE' ) { + $list =~ s/(^|;)\s*(not issued )?$seq_r(?=;|$)//g; + } else { # CHECK return $list =~ /(^|;)\s*$seq_r(?=;|$)/ ? 1 : q{}; } return $list; @@ -1218,7 +1240,7 @@ $nextexepected = { sub GetNextExpected { my ($subscriptionid) = @_; - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $query = qq{ SELECT * FROM serial @@ -1243,7 +1265,8 @@ sub GetNextExpected { $sth->execute($subscriptionid); $nextissue = $sth->fetchrow_hashref; } - foreach(qw/planneddate publisheddate/) { + foreach (qw/planneddate publisheddate/) { + # or should this default to 1st Jan ??? $nextissue->{$_} //= strftime( '%Y-%m-%d', localtime ); } @@ -1293,7 +1316,7 @@ sub GetSubscriptionIrregularities { return unless $subscriptionid; - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $query = qq{ SELECT irregularity FROM subscription @@ -1303,7 +1326,7 @@ sub GetSubscriptionIrregularities { $sth->execute($subscriptionid); my ($result) = $sth->fetchrow_array; - my @irreg = split /;/, $result; + my @irreg = split /;/, $result; return @irreg; } @@ -1317,63 +1340,64 @@ returns the number of rows affected sub ModSubscription { my ( - $auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $startdate, - $periodicity, $firstacquidate, $irregularity, $numberpattern, $locale, - $numberlength, $weeklength, $monthlength, $lastvalue1, $innerloop1, - $lastvalue2, $innerloop2, $lastvalue3, $innerloop3, $status, - $biblionumber, $callnumber, $notes, $letter, $manualhistory, - $internalnotes, $serialsadditems, $staffdisplaycount, $opacdisplaycount, - $graceperiod, $location, $enddate, $subscriptionid, $skip_serialseq, - $itemtype, $previousitemtype, $mana_id, $ccode, $published_on_template + $auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $startdate, + $periodicity, $firstacquidate, $irregularity, $numberpattern, $locale, + $numberlength, $weeklength, $monthlength, $lastvalue1, $innerloop1, + $lastvalue2, $innerloop2, $lastvalue3, $innerloop3, $status, + $biblionumber, $callnumber, $notes, $letter, $manualhistory, + $internalnotes, $serialsadditems, $staffdisplaycount, $opacdisplaycount, + $graceperiod, $location, $enddate, $subscriptionid, $skip_serialseq, + $itemtype, $previousitemtype, $mana_id, $ccode, $published_on_template ) = @_; my $subscription = Koha::Subscriptions->find($subscriptionid); $subscription->set( { - librarian => $auser, - branchcode => $branchcode, - aqbooksellerid => $aqbooksellerid, - cost => $cost, - aqbudgetid => $aqbudgetid, - biblionumber => $biblionumber, - startdate => $startdate, - periodicity => $periodicity, - numberlength => $numberlength, - weeklength => $weeklength, - monthlength => $monthlength, - lastvalue1 => $lastvalue1, - innerloop1 => $innerloop1, - lastvalue2 => $lastvalue2, - innerloop2 => $innerloop2, - lastvalue3 => $lastvalue3, - innerloop3 => $innerloop3, - status => $status, - notes => $notes, - letter => $letter, - firstacquidate => $firstacquidate, - irregularity => $irregularity, - numberpattern => $numberpattern, - locale => $locale, - callnumber => $callnumber, - manualhistory => $manualhistory, - internalnotes => $internalnotes, - serialsadditems => $serialsadditems, - staffdisplaycount => $staffdisplaycount, - opacdisplaycount => $opacdisplaycount, - graceperiod => $graceperiod, - location => $location, - enddate => $enddate, - skip_serialseq => $skip_serialseq, - itemtype => $itemtype, - previousitemtype => $previousitemtype, - mana_id => $mana_id, - ccode => $ccode, + librarian => $auser, + branchcode => $branchcode, + aqbooksellerid => $aqbooksellerid, + cost => $cost, + aqbudgetid => $aqbudgetid, + biblionumber => $biblionumber, + startdate => $startdate, + periodicity => $periodicity, + numberlength => $numberlength, + weeklength => $weeklength, + monthlength => $monthlength, + lastvalue1 => $lastvalue1, + innerloop1 => $innerloop1, + lastvalue2 => $lastvalue2, + innerloop2 => $innerloop2, + lastvalue3 => $lastvalue3, + innerloop3 => $innerloop3, + status => $status, + notes => $notes, + letter => $letter, + firstacquidate => $firstacquidate, + irregularity => $irregularity, + numberpattern => $numberpattern, + locale => $locale, + callnumber => $callnumber, + manualhistory => $manualhistory, + internalnotes => $internalnotes, + serialsadditems => $serialsadditems, + staffdisplaycount => $staffdisplaycount, + opacdisplaycount => $opacdisplaycount, + graceperiod => $graceperiod, + location => $location, + enddate => $enddate, + skip_serialseq => $skip_serialseq, + itemtype => $itemtype, + previousitemtype => $previousitemtype, + mana_id => $mana_id, + ccode => $ccode, published_on_template => $published_on_template, } )->store; + # FIXME Must be $subscription->serials # FIXME We shouldn't need serial.subscription (instead use serial->subscription->biblionumber) - Koha::Serials->search({ subscriptionid => $subscriptionid })->update({ biblionumber => $biblionumber }); + Koha::Serials->search( { subscriptionid => $subscriptionid } )->update( { biblionumber => $biblionumber } ); logaction( "SERIAL", "MODIFY", $subscriptionid, "" ) if C4::Context->preference("SubscriptionLog"); @@ -1400,57 +1424,57 @@ the id of this new subscription sub NewSubscription { my ( - $auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $biblionumber, - $startdate, $periodicity, $numberlength, $weeklength, $monthlength, - $lastvalue1, $innerloop1, $lastvalue2, $innerloop2, $lastvalue3, - $innerloop3, $status, $notes, $letter, $firstacquidate, $irregularity, - $numberpattern, $locale, $callnumber, $manualhistory, $internalnotes, - $serialsadditems, $staffdisplaycount, $opacdisplaycount, $graceperiod, - $location, $enddate, $skip_serialseq, $itemtype, $previousitemtype, $mana_id, $ccode, - $published_on_template, + $auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $biblionumber, + $startdate, $periodicity, $numberlength, $weeklength, $monthlength, + $lastvalue1, $innerloop1, $lastvalue2, $innerloop2, $lastvalue3, + $innerloop3, $status, $notes, $letter, $firstacquidate, $irregularity, + $numberpattern, $locale, $callnumber, $manualhistory, $internalnotes, + $serialsadditems, $staffdisplaycount, $opacdisplaycount, $graceperiod, + $location, $enddate, $skip_serialseq, $itemtype, $previousitemtype, $mana_id, $ccode, + $published_on_template, ) = @_; my $dbh = C4::Context->dbh; my $subscription = Koha::Subscription->new( { - librarian => $auser, - branchcode => $branchcode, - aqbooksellerid => $aqbooksellerid, - cost => $cost, - aqbudgetid => $aqbudgetid, - biblionumber => $biblionumber, - startdate => $startdate, - periodicity => $periodicity, - numberlength => $numberlength, - weeklength => $weeklength, - monthlength => $monthlength, - lastvalue1 => $lastvalue1, - innerloop1 => $innerloop1, - lastvalue2 => $lastvalue2, - innerloop2 => $innerloop2, - lastvalue3 => $lastvalue3, - innerloop3 => $innerloop3, - status => $status, - notes => $notes, - letter => $letter, - firstacquidate => $firstacquidate, - irregularity => $irregularity, - numberpattern => $numberpattern, - locale => $locale, - callnumber => $callnumber, - manualhistory => $manualhistory, - internalnotes => $internalnotes, - serialsadditems => $serialsadditems, - staffdisplaycount => $staffdisplaycount, - opacdisplaycount => $opacdisplaycount, - graceperiod => $graceperiod, - location => $location, - enddate => $enddate, - skip_serialseq => $skip_serialseq, - itemtype => $itemtype, - previousitemtype => $previousitemtype, - mana_id => $mana_id, - ccode => $ccode, + librarian => $auser, + branchcode => $branchcode, + aqbooksellerid => $aqbooksellerid, + cost => $cost, + aqbudgetid => $aqbudgetid, + biblionumber => $biblionumber, + startdate => $startdate, + periodicity => $periodicity, + numberlength => $numberlength, + weeklength => $weeklength, + monthlength => $monthlength, + lastvalue1 => $lastvalue1, + innerloop1 => $innerloop1, + lastvalue2 => $lastvalue2, + innerloop2 => $innerloop2, + lastvalue3 => $lastvalue3, + innerloop3 => $innerloop3, + status => $status, + notes => $notes, + letter => $letter, + firstacquidate => $firstacquidate, + irregularity => $irregularity, + numberpattern => $numberpattern, + locale => $locale, + callnumber => $callnumber, + manualhistory => $manualhistory, + internalnotes => $internalnotes, + serialsadditems => $serialsadditems, + staffdisplaycount => $staffdisplaycount, + opacdisplaycount => $opacdisplaycount, + graceperiod => $graceperiod, + location => $location, + enddate => $enddate, + skip_serialseq => $skip_serialseq, + itemtype => $itemtype, + previousitemtype => $previousitemtype, + mana_id => $mana_id, + ccode => $ccode, published_on_template => $published_on_template, } )->store; @@ -1459,7 +1483,7 @@ sub NewSubscription { my ( $query, $sth ); unless ($enddate) { $enddate = GetExpirationDate( $subscriptionid, $startdate ); - $query = qq| + $query = qq| UPDATE subscription SET enddate=? WHERE subscriptionid=? @@ -1475,14 +1499,14 @@ sub NewSubscription { VALUES (?,?,?, '', '') ); $sth = $dbh->prepare($query); - $sth->execute( $biblionumber, $subscriptionid, $startdate); + $sth->execute( $biblionumber, $subscriptionid, $startdate ); # reread subscription to get a hash (for calculation of the 1st issue number) - $subscription = GetSubscription($subscriptionid); # We should not do that - my $pattern = C4::Serials::Numberpattern::GetSubscriptionNumberpattern($subscription->{numberpattern}); + $subscription = GetSubscription($subscriptionid); # We should not do that + my $pattern = C4::Serials::Numberpattern::GetSubscriptionNumberpattern( $subscription->{numberpattern} ); # calculate issue number - my $serialseq = GetSeq($subscription, $pattern) || q{}; + my $serialseq = GetSeq( $subscription, $pattern ) || q{}; Koha::Serial->new( { @@ -1501,10 +1525,10 @@ sub NewSubscription { logaction( "SERIAL", "ADD", $subscriptionid, "" ) if C4::Context->preference("SubscriptionLog"); #set serial flag on biblio if not already set. - my $biblio = Koha::Biblios->find( $biblionumber ); + my $biblio = Koha::Biblios->find($biblionumber); if ( $biblio and !$biblio->serial ) { my $record = $biblio->metadata->record; - my ( $tag, $subf ) = GetMarcFromKohaField( 'biblio.serial' ); + my ( $tag, $subf ) = GetMarcFromKohaField('biblio.serial'); if ($tag) { eval { $record->field($tag)->update( $subf => 1 ); }; } @@ -1522,19 +1546,17 @@ This function calculates the subscription length. =cut sub GetSubscriptionLength { - my ($subtype, $length) = @_; + my ( $subtype, $length ) = @_; return unless looks_like_number($length); - return - ( - $subtype eq 'issues' ? $length : 0, - $subtype eq 'weeks' ? $length : 0, - $subtype eq 'months' ? $length : 0, + return ( + $subtype eq 'issues' ? $length : 0, + $subtype eq 'weeks' ? $length : 0, + $subtype eq 'months' ? $length : 0, ); } - =head2 ReNewSubscription ReNewSubscription($params); @@ -1546,7 +1568,7 @@ this function renew a subscription with values given on input args. =cut sub ReNewSubscription { - my ( $params ) = @_; + my ($params) = @_; my $subscriptionid = $params->{subscriptionid}; my $user = $params->{user}; my $startdate = $params->{startdate}; @@ -1582,7 +1604,7 @@ sub ReNewSubscription { )->store; } - $numberlength ||= 0; # Should not we raise an exception instead? + $numberlength ||= 0; # Should not we raise an exception instead? $weeklength ||= 0; # renew subscription @@ -1617,15 +1639,17 @@ returns the serial id =cut sub NewIssue { - my ( $serialseq, $subscriptionid, $biblionumber, $status, $planneddate, - $publisheddate, $publisheddatetext, $notes, $routingnotes ) = @_; + my ( + $serialseq, $subscriptionid, $biblionumber, $status, $planneddate, + $publisheddate, $publisheddatetext, $notes, $routingnotes + ) = @_; ### FIXME biblionumber CAN be provided by subscriptionid. So Do we STILL NEED IT ? return unless ($subscriptionid); my $schema = Koha::Database->new()->schema(); - my $subscription = Koha::Subscriptions->find( $subscriptionid ); + my $subscription = Koha::Subscriptions->find($subscriptionid); if ( my $template = $subscription->published_on_template ) { $publisheddatetext = process_tt( @@ -1668,8 +1692,8 @@ sub NewIssue { my $serialid = $serial->id(); my $subscription_history = Koha::Subscription::Histories->find($subscriptionid); - my $missinglist = $subscription_history->missinglist(); - my $recievedlist = $subscription_history->recievedlist(); + my $missinglist = $subscription_history->missinglist(); + my $recievedlist = $subscription_history->recievedlist(); if ( $status == ARRIVED ) { ### TODO Add a feature that improves recognition and description. @@ -1709,8 +1733,8 @@ sub HasSubscriptionStrictlyExpired { return unless ($subscriptionid); - my $dbh = C4::Context->dbh; - my $subscription = GetSubscription($subscriptionid); + my $dbh = C4::Context->dbh; + my $subscription = GetSubscription($subscriptionid); my $expirationdate = $subscription->{enddate} || GetExpirationDate($subscriptionid); # If the expiration date is set @@ -1753,15 +1777,15 @@ sub HasSubscriptionExpired { return unless ($subscriptionid); - my $dbh = C4::Context->dbh; - my $subscription = GetSubscription($subscriptionid); - my $frequency = C4::Serials::Frequency::GetSubscriptionFrequency($subscription->{periodicity}); + my $dbh = C4::Context->dbh; + my $subscription = GetSubscription($subscriptionid); + my $frequency = C4::Serials::Frequency::GetSubscriptionFrequency( $subscription->{periodicity} ); if ( $frequency and $frequency->{unit} ) { my $expirationdate = $subscription->{enddate} || GetExpirationDate($subscriptionid); - if (!defined $expirationdate) { + if ( !defined $expirationdate ) { $expirationdate = q{}; } - my $query = qq| + my $query = qq| SELECT max(planneddate) FROM serial WHERE subscriptionid=? @@ -1769,17 +1793,29 @@ sub HasSubscriptionExpired { my $sth = $dbh->prepare($query); $sth->execute($subscriptionid); my ($res) = $sth->fetchrow; - if (!$res || $res=~m/^0000/) { + if ( !$res || $res =~ m/^0000/ ) { return 0; } my @res = split( /-/, $res ); my @endofsubscriptiondate = split( /-/, $expirationdate ); - return 2 if ( scalar(@res) != 3 || scalar(@endofsubscriptiondate) != 3 || not check_date(@res) || not check_date(@endofsubscriptiondate) ); + return 2 + if ( scalar(@res) != 3 + || scalar(@endofsubscriptiondate) != 3 + || not check_date(@res) + || not check_date(@endofsubscriptiondate) ); return 1 - if ( ( @endofsubscriptiondate && Delta_Days( $res[0], $res[1], $res[2], $endofsubscriptiondate[0], $endofsubscriptiondate[1], $endofsubscriptiondate[2] ) <= 0 ) - || ( !$res ) ); + if ( + ( + @endofsubscriptiondate && Delta_Days( + $res[0], $res[1], $res[2], $endofsubscriptiondate[0], $endofsubscriptiondate[1], + $endofsubscriptiondate[2] + ) <= 0 + ) + || ( !$res ) + ); return 0; } else { + # Irregular if ( $subscription->{'numberlength'} ) { my $countreceived = countissuesfrom( $subscriptionid, $subscription->{'startdate'} ); @@ -1802,12 +1838,15 @@ this function deletes subscription which has $subscriptionid as id. sub DelSubscription { my ($subscriptionid) = @_; my $dbh = C4::Context->dbh; - $dbh->do("DELETE FROM subscription WHERE subscriptionid=?", undef, $subscriptionid); + $dbh->do( "DELETE FROM subscription WHERE subscriptionid=?", undef, $subscriptionid ); - Koha::AdditionalFieldValues->search({ - 'field.tablename' => 'subscription', - 'me.record_id' => $subscriptionid, - }, { join => 'field' })->delete; + Koha::AdditionalFieldValues->search( + { + 'field.tablename' => 'subscription', + 'me.record_id' => $subscriptionid, + }, + { join => 'field' } + )->delete; logaction( "SERIAL", "DELETE", $subscriptionid, "" ) if C4::Context->preference("SubscriptionLog"); } @@ -1850,7 +1889,10 @@ sub DelIssue { my $serialseq = $dataissue->{'serialseq'}; $data->{'missinglist'} =~ s/\b$serialseq\b//; $data->{'recievedlist'} =~ s/\b$serialseq\b//; - my $strsth = "UPDATE subscriptionhistory SET " . join( ",", map { join( "=", $_, $dbh->quote( $data->{$_} ) ) } keys %$data ) . " WHERE subscriptionid=?"; + my $strsth = + "UPDATE subscriptionhistory SET " + . join( ",", map { join( "=", $_, $dbh->quote( $data->{$_} ) ) } keys %$data ) + . " WHERE subscriptionid=?"; $sth = $dbh->prepare($strsth); $sth->execute( $dataissue->{'subscriptionid'} ); } @@ -1926,11 +1968,11 @@ sub GetLateOrMissingIssues { $sth->execute( EXPECTED, LATE, CLAIMED ); my @issuelist; while ( my $line = $sth->fetchrow_hashref ) { - $line->{"status".$line->{status}} = 1; + $line->{ "status" . $line->{status} } = 1; - my $subscription_object = Koha::Subscriptions->find($line->{subscriptionid}); - $line->{additional_fields} = { map { $_->field->name => $_->value } - $subscription_object->additional_field_values->as_list }; + my $subscription_object = Koha::Subscriptions->find( $line->{subscriptionid} ); + $line->{additional_fields} = + { map { $_->field->name => $_->value } $subscription_object->additional_field_values->as_list }; push @issuelist, $line; } @@ -1951,10 +1993,10 @@ sub updateClaim { my ($serialids) = @_; return unless $serialids; unless ( ref $serialids ) { - $serialids = [ $serialids ]; + $serialids = [$serialids]; } - foreach my $serialid(@$serialids) { + foreach my $serialid (@$serialids) { my $serial = Koha::Serials->find($serialid); C4::Serials::ModSerialStatus( @@ -1969,13 +2011,15 @@ sub updateClaim { } my $dbh = C4::Context->dbh; - return $dbh->do(q| + return $dbh->do( + q| UPDATE serial SET claimdate = NOW(), claims_count = claims_count + 1, status = ? WHERE serialid in (| . join( q|,|, (q|?|) x @$serialids ) . q|)|, - {}, CLAIMED, @$serialids ); + {}, CLAIMED, @$serialids + ); } =head2 check_routing @@ -1992,8 +2036,8 @@ sub check_routing { return unless ($subscriptionid); - my $dbh = C4::Context->dbh; - my $sth = $dbh->prepare( + my $dbh = C4::Context->dbh; + my $sth = $dbh->prepare( "SELECT count(routingid) routingids FROM subscription LEFT JOIN subscriptionroutinglist ON subscription.subscriptionid = subscriptionroutinglist.subscriptionid WHERE subscription.subscriptionid = ? GROUP BY routingid ORDER BY ranking ASC @@ -2049,7 +2093,7 @@ it takes the routingid of the member one wants to re-rank and the rank it is to sub reorder_members { my ( $subscriptionid, $routingid, $rank ) = @_; my $dbh = C4::Context->dbh; - my $sth = $dbh->prepare( "SELECT * FROM subscriptionroutinglist WHERE subscriptionid = ? ORDER BY ranking ASC" ); + my $sth = $dbh->prepare("SELECT * FROM subscriptionroutinglist WHERE subscriptionid = ? ORDER BY ranking ASC"); $sth->execute($subscriptionid); my @result; while ( my $line = $sth->fetchrow_hashref ) { @@ -2068,12 +2112,17 @@ sub reorder_members { # if index exists in array then move it to new position if ( $key > -1 && $rank > 0 ) { - my $new_rank = $rank - 1; # $new_rank is what you want the new index to be in the array + my $new_rank = $rank - 1; # $new_rank is what you want the new index to be in the array my $moving_item = splice( @result, $key, 1 ); splice( @result, $new_rank, 0, $moving_item ); } for ( my $j = 0 ; $j < @result ; $j++ ) { - my $sth = $dbh->prepare( "UPDATE subscriptionroutinglist SET ranking = '" . ( $j + 1 ) . "' WHERE routingid = '" . $result[$j] . "'" ); + my $sth = + $dbh->prepare( "UPDATE subscriptionroutinglist SET ranking = '" + . ( $j + 1 ) + . "' WHERE routingid = '" + . $result[$j] + . "'" ); $sth->execute; } return; @@ -2126,7 +2175,7 @@ sub getroutinglist { WHERE subscription.subscriptionid = ? ORDER BY ranking ASC' ); $sth->execute($subscriptionid); - my $routinglist = $sth->fetchall_arrayref({}); + my $routinglist = $sth->fetchall_arrayref( {} ); return @{$routinglist}; } @@ -2187,16 +2236,16 @@ returns a count of items from serial matching the subscriptionid sub HasItems { my ($subscriptionid) = @_; my $dbh = C4::Context->dbh; - my $query = q| + my $query = q| SELECT COUNT(serialitems.itemnumber) FROM serial LEFT JOIN serialitems USING(serialid) WHERE subscriptionid=? AND serialitems.serialid IS NOT NULL |; - my $sth=$dbh->prepare($query); + my $sth = $dbh->prepare($query); $sth->execute($subscriptionid); - my ($countitems)=$sth->fetchrow_array(); - return $countitems; + my ($countitems) = $sth->fetchrow_array(); + return $countitems; } =head2 abouttoexpire @@ -2214,27 +2263,34 @@ sub abouttoexpire { my ($subscriptionid) = @_; my $dbh = C4::Context->dbh; my $subscription = GetSubscription($subscriptionid); - my $per = $subscription->{'periodicity'}; - my $frequency = C4::Serials::Frequency::GetSubscriptionFrequency($per); - if ($frequency and $frequency->{unit}){ + my $per = $subscription->{'periodicity'}; + my $frequency = C4::Serials::Frequency::GetSubscriptionFrequency($per); + if ( $frequency and $frequency->{unit} ) { my $expirationdate = GetExpirationDate($subscriptionid); - my ($res) = $dbh->selectrow_array('select max(planneddate) from serial where subscriptionid = ?', undef, $subscriptionid); - my $nextdate = GetNextDate($subscription, $res, $frequency); + my ($res) = $dbh->selectrow_array( + 'select max(planneddate) from serial where subscriptionid = ?', undef, + $subscriptionid + ); + my $nextdate = GetNextDate( $subscription, $res, $frequency ); # only compare dates if both dates exist. - if ($nextdate and $expirationdate) { - if(Date::Calc::Delta_Days( - split( /-/, $nextdate ), - split( /-/, $expirationdate ) - ) <= 0) { + if ( $nextdate and $expirationdate ) { + if ( + Date::Calc::Delta_Days( + split( /-/, $nextdate ), + split( /-/, $expirationdate ) + ) <= 0 + ) + { return 1; } } - } elsif ( $subscription->{numberlength} && $subscription->{numberlength}>0) { - return (countissuesfrom($subscriptionid,$subscription->{'startdate'}) >=$subscription->{numberlength}-1); + } elsif ( $subscription->{numberlength} && $subscription->{numberlength} > 0 ) { + return ( + countissuesfrom( $subscriptionid, $subscription->{'startdate'} ) >= $subscription->{numberlength} - 1 ); } return 0; @@ -2261,19 +2317,19 @@ date (in GetNextDate) or the next issue number (in GetNextSeq). =cut sub GetFictiveIssueNumber { - my ($subscription, $publisheddate, $frequency) = @_; + my ( $subscription, $publisheddate, $frequency ) = @_; my $unit = $frequency->{unit} ? lc $frequency->{'unit'} : undef; return if !$unit; my $issueno; - my ( $year, $month, $day ) = split /-/, $publisheddate; + my ( $year, $month, $day ) = split /-/, $publisheddate; my ( $fa_year, $fa_month, $fa_day ) = split /-/, $subscription->{'firstacquidate'}; - my $delta = _delta_units( [$fa_year, $fa_month, $fa_day], [$year, $month, $day], $unit ); + my $delta = _delta_units( [ $fa_year, $fa_month, $fa_day ], [ $year, $month, $day ], $unit ); - if( $frequency->{'unitsperissue'} == 1 ) { + if ( $frequency->{'unitsperissue'} == 1 ) { $issueno = $delta * $frequency->{'issuesperunit'} + $subscription->{'countissuesperunit'}; - } else { # issuesperunit == 1 + } else { # issuesperunit == 1 $issueno = 1 + int( $delta / $frequency->{'unitsperissue'} ); } return $issueno; @@ -2281,11 +2337,12 @@ sub GetFictiveIssueNumber { sub _delta_units { my ( $date1, $date2, $unit ) = @_; + # date1 and date2 are array refs in the form [ yy, mm, dd ] - if( $unit eq 'day' ) { + if ( $unit eq 'day' ) { return Delta_Days( @$date1, @$date2 ); - } elsif( $unit eq 'week' ) { + } elsif ( $unit eq 'week' ) { return int( Delta_Days( @$date1, @$date2 ) / 7 ); } @@ -2293,36 +2350,40 @@ sub _delta_units { # Note that N_Delta_YMD returns 29 days between e.g. 22-2-72 and 22-3-72 # while we expect 1 month. my @delta = N_Delta_YMD( @$date1, @$date2 ); - if( $delta[2] > 27 ) { + if ( $delta[2] > 27 ) { + # Check if we could add a month my @jump = Add_Delta_YM( @$date1, $delta[0], 1 + $delta[1] ); - if( Delta_Days( @jump, @$date2 ) >= 0 ) { + if ( Delta_Days( @jump, @$date2 ) >= 0 ) { $delta[1]++; } } - if( $delta[1] >= 12 ) { + if ( $delta[1] >= 12 ) { $delta[0]++; $delta[1] -= 12; } + # if unit is year, we only return full years return $unit eq 'month' ? $delta[0] * 12 + $delta[1] : $delta[0]; } sub _get_next_date_day { - my ($subscription, $freqdata, $year, $month, $day) = @_; + my ( $subscription, $freqdata, $year, $month, $day ) = @_; - my @newissue; # ( yy, mm, dd ) - # We do not need $delta_days here, since it would be zero where used + my @newissue; # ( yy, mm, dd ) + # We do not need $delta_days here, since it would be zero where used + + if ( $freqdata->{issuesperunit} == 1 ) { - if( $freqdata->{issuesperunit} == 1 ) { # Add full days - @newissue = Add_Delta_Days( - $year, $month, $day, $freqdata->{"unitsperissue"} ); + @newissue = Add_Delta_Days( $year, $month, $day, $freqdata->{"unitsperissue"} ); } elsif ( $subscription->{countissuesperunit} < $freqdata->{issuesperunit} ) { + # Add zero days @newissue = ( $year, $month, $day ); $subscription->{countissuesperunit}++; } else { + # We finished a cycle of issues within a unit. # No subtraction of zero needed, just add one day @newissue = Add_Delta_Days( $year, $month, $day, 1 ); @@ -2332,24 +2393,28 @@ sub _get_next_date_day { } sub _get_next_date_week { - my ($subscription, $freqdata, $year, $month, $day) = @_; + my ( $subscription, $freqdata, $year, $month, $day ) = @_; - my @newissue; # ( yy, mm, dd ) + my @newissue; # ( yy, mm, dd ) my $delta_days = int( 7 / $freqdata->{issuesperunit} ); - if( $freqdata->{issuesperunit} == 1 ) { + if ( $freqdata->{issuesperunit} == 1 ) { + # Add full weeks (of 7 days) - @newissue = Add_Delta_Days( - $year, $month, $day, 7 * $freqdata->{"unitsperissue"} ); + @newissue = Add_Delta_Days( $year, $month, $day, 7 * $freqdata->{"unitsperissue"} ); } elsif ( $subscription->{countissuesperunit} < $freqdata->{issuesperunit} ) { + # Add rounded number of days based on frequency. @newissue = Add_Delta_Days( $year, $month, $day, $delta_days ); $subscription->{countissuesperunit}++; } else { + # We finished a cycle of issues within a unit. # Subtract delta * (issues - 1), add 1 week - @newissue = Add_Delta_Days( $year, $month, $day, - -$delta_days * ($freqdata->{issuesperunit} - 1) ); + @newissue = Add_Delta_Days( + $year, $month, $day, + -$delta_days * ( $freqdata->{issuesperunit} - 1 ) + ); @newissue = Add_Delta_Days( @newissue, 7 ); $subscription->{countissuesperunit} = 1; } @@ -2357,24 +2422,28 @@ sub _get_next_date_week { } sub _get_next_date_month { - my ($subscription, $freqdata, $year, $month, $day) = @_; + my ( $subscription, $freqdata, $year, $month, $day ) = @_; - my @newissue; # ( yy, mm, dd ) + my @newissue; # ( yy, mm, dd ) my $delta_days = int( 30 / $freqdata->{issuesperunit} ); - if( $freqdata->{issuesperunit} == 1 ) { + if ( $freqdata->{issuesperunit} == 1 ) { + # Add full months - @newissue = Add_Delta_YM( - $year, $month, $day, 0, $freqdata->{"unitsperissue"} ); + @newissue = Add_Delta_YM( $year, $month, $day, 0, $freqdata->{"unitsperissue"} ); } elsif ( $subscription->{countissuesperunit} < $freqdata->{issuesperunit} ) { + # Add rounded number of days based on frequency. @newissue = Add_Delta_Days( $year, $month, $day, $delta_days ); $subscription->{countissuesperunit}++; } else { + # We finished a cycle of issues within a unit. # Subtract delta * (issues - 1), add 1 month - @newissue = Add_Delta_Days( $year, $month, $day, - -$delta_days * ($freqdata->{issuesperunit} - 1) ); + @newissue = Add_Delta_Days( + $year, $month, $day, + -$delta_days * ( $freqdata->{issuesperunit} - 1 ) + ); @newissue = Add_Delta_YM( @newissue, 0, 1 ); $subscription->{countissuesperunit} = 1; } @@ -2382,22 +2451,25 @@ sub _get_next_date_month { } sub _get_next_date_year { - my ($subscription, $freqdata, $year, $month, $day) = @_; + my ( $subscription, $freqdata, $year, $month, $day ) = @_; - my @newissue; # ( yy, mm, dd ) + my @newissue; # ( yy, mm, dd ) my $delta_days = int( 365 / $freqdata->{issuesperunit} ); - if( $freqdata->{issuesperunit} == 1 ) { + if ( $freqdata->{issuesperunit} == 1 ) { + # Add full years @newissue = Add_Delta_YM( $year, $month, $day, $freqdata->{"unitsperissue"}, 0 ); } elsif ( $subscription->{countissuesperunit} < $freqdata->{issuesperunit} ) { + # Add rounded number of days based on frequency. @newissue = Add_Delta_Days( $year, $month, $day, $delta_days ); $subscription->{countissuesperunit}++; } else { + # We finished a cycle of issues within a unit. # Subtract delta * (issues - 1), add 1 year - @newissue = Add_Delta_Days( $year, $month, $day, -$delta_days * ($freqdata->{issuesperunit} - 1) ); + @newissue = Add_Delta_Days( $year, $month, $day, -$delta_days * ( $freqdata->{issuesperunit} - 1 ) ); @newissue = Add_Delta_YM( @newissue, 1, 0 ); $subscription->{countissuesperunit} = 1; } @@ -2429,8 +2501,7 @@ sub GetNextDate { return unless $subscription and $publisheddate; - - if ($freqdata->{'unit'}) { + if ( $freqdata->{'unit'} ) { my ( $year, $month, $day ) = split /-/, $publisheddate; # Process an irregularity Hash @@ -2440,7 +2511,7 @@ sub GetNextDate { # (the first issue takes the number 1, the 2nd the number 2 and so on) my %irregularities; if ( $subscription->{irregularity} ) { - my @irreg = split /;/, $subscription->{'irregularity'} ; + my @irreg = split /;/, $subscription->{'irregularity'}; foreach my $irregularity (@irreg) { $irregularities{$irregularity} = 1; } @@ -2448,59 +2519,72 @@ sub GetNextDate { # Get the 'fictive' next issue number # It is used to check if next issue is an irregular issue. - my $issueno = GetFictiveIssueNumber($subscription, $publisheddate, $freqdata) + 1; + my $issueno = GetFictiveIssueNumber( $subscription, $publisheddate, $freqdata ) + 1; # Then get the next date my $unit = lc $freqdata->{'unit'}; - if ($unit eq 'day') { - while ($irregularities{$issueno}) { - ($year, $month, $day) = _get_next_date_day($subscription, - $freqdata, $year, $month, $day); + if ( $unit eq 'day' ) { + while ( $irregularities{$issueno} ) { + ( $year, $month, $day ) = _get_next_date_day( + $subscription, + $freqdata, $year, $month, $day + ); $issueno++; } - ($year, $month, $day) = _get_next_date_day($subscription, $freqdata, - $year, $month, $day); - } - elsif ($unit eq 'week') { - while ($irregularities{$issueno}) { - ($year, $month, $day) = _get_next_date_week($subscription, - $freqdata, $year, $month, $day); + ( $year, $month, $day ) = _get_next_date_day( + $subscription, $freqdata, + $year, $month, $day + ); + } elsif ( $unit eq 'week' ) { + while ( $irregularities{$issueno} ) { + ( $year, $month, $day ) = _get_next_date_week( + $subscription, + $freqdata, $year, $month, $day + ); $issueno++; } - ($year, $month, $day) = _get_next_date_week($subscription, - $freqdata, $year, $month, $day); - } - elsif ($unit eq 'month') { - while ($irregularities{$issueno}) { - ($year, $month, $day) = _get_next_date_month($subscription, - $freqdata, $year, $month, $day); + ( $year, $month, $day ) = _get_next_date_week( + $subscription, + $freqdata, $year, $month, $day + ); + } elsif ( $unit eq 'month' ) { + while ( $irregularities{$issueno} ) { + ( $year, $month, $day ) = _get_next_date_month( + $subscription, + $freqdata, $year, $month, $day + ); $issueno++; } - ($year, $month, $day) = _get_next_date_month($subscription, - $freqdata, $year, $month, $day); - } - elsif ($unit eq 'year') { - while ($irregularities{$issueno}) { - ($year, $month, $day) = _get_next_date_year($subscription, - $freqdata, $year, $month, $day); + ( $year, $month, $day ) = _get_next_date_month( + $subscription, + $freqdata, $year, $month, $day + ); + } elsif ( $unit eq 'year' ) { + while ( $irregularities{$issueno} ) { + ( $year, $month, $day ) = _get_next_date_year( + $subscription, + $freqdata, $year, $month, $day + ); $issueno++; } - ($year, $month, $day) = _get_next_date_year($subscription, - $freqdata, $year, $month, $day); + ( $year, $month, $day ) = _get_next_date_year( + $subscription, + $freqdata, $year, $month, $day + ); } - if ($updatecount){ - my $dbh = C4::Context->dbh; + if ($updatecount) { + my $dbh = C4::Context->dbh; my $query = qq{ UPDATE subscription SET countissuesperunit = ? WHERE subscriptionid = ? }; my $sth = $dbh->prepare($query); - $sth->execute($subscription->{'countissuesperunit'}, $subscription->{'subscriptionid'}); + $sth->execute( $subscription->{'countissuesperunit'}, $subscription->{'subscriptionid'} ); } - return sprintf("%04d-%02d-%02d", $year, $month, $day); + return sprintf( "%04d-%02d-%02d", $year, $month, $day ); } } @@ -2520,40 +2604,43 @@ num_type can take : =cut sub _numeration { - my ($value, $num_type, $locale) = @_; + my ( $value, $num_type, $locale ) = @_; $value ||= 0; $num_type //= ''; $locale ||= 'en'; my $string; if ( $num_type =~ /^dayname$/ or $num_type =~ /^dayabrv$/ ) { + # 1970-11-01 was a Sunday $value = $value % 7; my $dt = DateTime->new( - year => 1970, - month => 11, - day => $value + 1, - locale => $locale, + year => 1970, + month => 11, + day => $value + 1, + locale => $locale, ); - $string = $num_type =~ /^dayname$/ + $string = + $num_type =~ /^dayname$/ ? $dt->strftime("%A") : $dt->strftime("%a"); } elsif ( $num_type =~ /^monthname$/ or $num_type =~ /^monthabrv$/ ) { $value = $value % 12; my $dt = DateTime->new( - year => 1970, - month => $value + 1, - locale => $locale, + year => 1970, + month => $value + 1, + locale => $locale, ); - $string = $num_type =~ /^monthname$/ - ? $dt->format_cldr( "LLLL" ) + $string = + $num_type =~ /^monthname$/ + ? $dt->format_cldr("LLLL") : $dt->strftime("%b"); } elsif ( $num_type =~ /^season$/ ) { - my @seasons= qw( Spring Summer Fall Winter ); - $value = $value % 4; + my @seasons = qw( Spring Summer Fall Winter ); + $value = $value % 4; $string = $seasons[$value]; } elsif ( $num_type =~ /^seasonabrv$/ ) { - my @seasonsabrv= qw( Spr Sum Fal Win ); - $value = $value % 4; + my @seasonsabrv = qw( Spr Sum Fal Win ); + $value = $value % 4; $string = $seasonsabrv[$value]; } else { $string = $value; @@ -2569,23 +2656,27 @@ Close a subscription given a subscriptionid =cut sub CloseSubscription { - my ( $subscriptionid ) = @_; + my ($subscriptionid) = @_; return unless $subscriptionid; my $dbh = C4::Context->dbh; - my $sth = $dbh->prepare( q{ + my $sth = $dbh->prepare( + q{ UPDATE subscription SET closed = 1 WHERE subscriptionid = ? - } ); - $sth->execute( $subscriptionid ); + } + ); + $sth->execute($subscriptionid); # Set status = missing when status = stopped - $sth = $dbh->prepare( q{ + $sth = $dbh->prepare( + q{ UPDATE serial SET status = ? WHERE subscriptionid = ? AND status = ? - } ); + } + ); $sth->execute( STOPPED, $subscriptionid, EXPECTED ); } @@ -2596,23 +2687,27 @@ Reopen a subscription given a subscriptionid =cut sub ReopenSubscription { - my ( $subscriptionid ) = @_; + my ($subscriptionid) = @_; return unless $subscriptionid; my $dbh = C4::Context->dbh; - my $sth = $dbh->prepare( q{ + my $sth = $dbh->prepare( + q{ UPDATE subscription SET closed = 0 WHERE subscriptionid = ? - } ); - $sth->execute( $subscriptionid ); + } + ); + $sth->execute($subscriptionid); # Set status = expected when status = stopped - $sth = $dbh->prepare( q{ + $sth = $dbh->prepare( + q{ UPDATE serial SET status = ? WHERE subscriptionid = ? AND status = ? - } ); + } + ); $sth->execute( EXPECTED, $subscriptionid, STOPPED ); } @@ -2625,15 +2720,15 @@ Return 1 if subscription is currently on order else 0. =cut sub subscriptionCurrentlyOnOrder { - my ( $subscriptionid ) = @_; - my $dbh = C4::Context->dbh; - my $query = qq| + my ($subscriptionid) = @_; + my $dbh = C4::Context->dbh; + my $query = qq| SELECT COUNT(*) FROM aqorders WHERE subscriptionid = ? AND datereceived IS NULL AND datecancellationprinted IS NULL |; - my $sth = $dbh->prepare( $query ); + my $sth = $dbh->prepare($query); $sth->execute($subscriptionid); return $sth->fetchrow_array; } @@ -2685,27 +2780,23 @@ sub _can_do_on_subscription { if ( C4::Context->preference('IndependentBranches') ) { return 1 - if C4::Context->IsSuperLibrarian() - or - C4::Auth::haspermission( $userid, { serials => 'superserials' } ) - or ( - C4::Auth::haspermission( $userid, - { serials => $permission } ) - and ( not defined $subscription->{branchcode} - or $subscription->{branchcode} eq '' - or $subscription->{branchcode} eq - C4::Context->userenv->{'branch'} ) - ); - } - else { + if C4::Context->IsSuperLibrarian() + or C4::Auth::haspermission( $userid, { serials => 'superserials' } ) + or ( + C4::Auth::haspermission( + $userid, + { serials => $permission } + ) + and ( not defined $subscription->{branchcode} + or $subscription->{branchcode} eq '' + or $subscription->{branchcode} eq C4::Context->userenv->{'branch'} ) + ); + } else { return 1 - if C4::Context->IsSuperLibrarian() - or - C4::Auth::haspermission( $userid, { serials => 'superserials' } ) - or C4::Auth::haspermission( - $userid, { serials => $permission } - ), - ; + if C4::Context->IsSuperLibrarian() + or C4::Auth::haspermission( $userid, { serials => 'superserials' } ) + or C4::Auth::haspermission( $userid, { serials => $permission } ), + ; } return 0; } diff --git a/C4/Serials/Frequency.pm b/C4/Serials/Frequency.pm index 9db52c8839..d7a6e2bd93 100644 --- a/C4/Serials/Frequency.pm +++ b/C4/Serials/Frequency.pm @@ -28,17 +28,16 @@ BEGIN { require Exporter; @ISA = qw(Exporter); @EXPORT = qw( - GetSubscriptionFrequencies - GetSubscriptionFrequency - AddSubscriptionFrequency - ModSubscriptionFrequency - DelSubscriptionFrequency + GetSubscriptionFrequencies + GetSubscriptionFrequency + AddSubscriptionFrequency + ModSubscriptionFrequency + DelSubscriptionFrequency - GetSubscriptionsWithFrequency + GetSubscriptionsWithFrequency ); } - =head1 NAME C4::Serials::Frequency - Serials Frequency module @@ -58,7 +57,7 @@ gets frequencies restricted on filters =cut sub GetSubscriptionFrequencies { - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $query = qq{ SELECT * FROM subscription_frequencies @@ -86,7 +85,7 @@ gets frequency where $frequencyid is the identifier sub GetSubscriptionFrequency { my ($frequencyid) = @_; - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $query = qq{ SELECT * FROM subscription_frequencies @@ -133,28 +132,28 @@ Only description is mandatory. sub AddSubscriptionFrequency { my $frequency = shift; - unless(ref($frequency) eq 'HASH' && defined $frequency->{'description'} && $frequency->{'description'} ne '') { + unless ( ref($frequency) eq 'HASH' && defined $frequency->{'description'} && $frequency->{'description'} ne '' ) { return; } my @keys; my @values; foreach (qw/ description unit issuesperunit unitsperissue expectedissuesayear displayorder /) { - if(exists $frequency->{$_}) { - push @keys, $_; + if ( exists $frequency->{$_} ) { + push @keys, $_; push @values, $frequency->{$_}; } } - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $query = "INSERT INTO subscription_frequencies"; - $query .= '(' . join(',', @keys) . ')'; - $query .= ' VALUES (' . ('?,' x (scalar(@keys)-1)) . '?)'; + $query .= '(' . join( ',', @keys ) . ')'; + $query .= ' VALUES (' . ( '?,' x ( scalar(@keys) - 1 ) ) . '?)'; my $sth = $dbh->prepare($query); - my $rv = $sth->execute(@values); + my $rv = $sth->execute(@values); - if(defined $rv) { - return $dbh->last_insert_id(undef, undef, "subscription_frequencies", undef); + if ( defined $rv ) { + return $dbh->last_insert_id( undef, undef, "subscription_frequencies", undef ); } return $rv; @@ -197,34 +196,33 @@ Only id is mandatory. sub ModSubscriptionFrequency { my $frequency = shift; - unless( - ref($frequency) eq 'HASH' - && defined $frequency->{'id'} && $frequency->{'id'} > 0 - && ( - (defined $frequency->{'description'} - && $frequency->{'description'} ne '') - || !defined $frequency->{'description'} - ) - ) { + unless ( + ref($frequency) eq 'HASH' + && defined $frequency->{'id'} + && $frequency->{'id'} > 0 + && ( ( defined $frequency->{'description'} && $frequency->{'description'} ne '' ) + || !defined $frequency->{'description'} ) + ) + { return; } my @keys; my @values; foreach (qw/ description unit issuesperunit unitsperissue expectedissuesayear displayorder /) { - if(exists $frequency->{$_}) { - push @keys, $_; + if ( exists $frequency->{$_} ) { + push @keys, $_; push @values, $frequency->{$_}; } } - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $query = "UPDATE subscription_frequencies"; - $query .= ' SET ' . join(' = ?,', @keys) . ' = ?'; + $query .= ' SET ' . join( ' = ?,', @keys ) . ' = ?'; $query .= ' WHERE id = ?'; my $sth = $dbh->prepare($query); - return $sth->execute(@values, $frequency->{'id'}); + return $sth->execute( @values, $frequency->{'id'} ); } =head2 DelSubscriptionFrequency @@ -242,7 +240,7 @@ Delete a frequency sub DelSubscriptionFrequency { my $frequencyid = shift; - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $query = qq{ DELETE FROM subscription_frequencies WHERE id = ? @@ -264,7 +262,7 @@ sub GetSubscriptionsWithFrequency { return unless $frequencyid; - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $query = qq{ SELECT * FROM subscription @@ -273,8 +271,8 @@ sub GetSubscriptionsWithFrequency { }; my $sth = $dbh->prepare($query); my @results; - if ($sth->execute($frequencyid)) { - @results = @{ $sth->fetchall_arrayref({}) }; + if ( $sth->execute($frequencyid) ) { + @results = @{ $sth->fetchall_arrayref( {} ) }; } return @results; } diff --git a/C4/Serials/Numberpattern.pm b/C4/Serials/Numberpattern.pm index 5c31bc6cf5..8d3c462c5d 100644 --- a/C4/Serials/Numberpattern.pm +++ b/C4/Serials/Numberpattern.pm @@ -40,7 +40,6 @@ BEGIN { ); } - =head1 NAME C4::Serials::Numberpattern - Serials numbering pattern module @@ -55,7 +54,7 @@ this function get all subscription number patterns entered in table =cut sub GetSubscriptionNumberpatterns { - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $query = qq{ SELECT * FROM subscription_numberpatterns @@ -63,7 +62,7 @@ sub GetSubscriptionNumberpatterns { }; my $sth = $dbh->prepare($query); $sth->execute; - my $results = $sth->fetchall_arrayref({}); + my $results = $sth->fetchall_arrayref( {} ); return @$results; } @@ -77,8 +76,8 @@ this function get the data of the subscription numberpatterns which id is $numbe sub GetSubscriptionNumberpattern { my $numberpatternid = shift; - my $dbh = C4::Context->dbh; - my $query = qq( + my $dbh = C4::Context->dbh; + my $query = qq( SELECT * FROM subscription_numberpatterns WHERE id = ? @@ -97,15 +96,15 @@ this function get the data of the subscription numberpatterns which name is $nam =cut sub GetSubscriptionNumberpatternByName { - my $name = shift; - my $dbh = C4::Context->dbh; + my $name = shift; + my $dbh = C4::Context->dbh; my $query = qq( SELECT * FROM subscription_numberpatterns WHERE label = ? ); my $sth = $dbh->prepare($query); - my $rv = $sth->execute($name); + my $rv = $sth->execute($name); return $sth->fetchrow_hashref; } @@ -129,38 +128,40 @@ Add a new numberpattern sub AddSubscriptionNumberpattern { my $numberpattern = shift; - unless( - ref($numberpattern) eq 'HASH' - && defined $numberpattern->{'label'} - && $numberpattern->{'label'} ne '' - && defined $numberpattern->{'numberingmethod'} - && $numberpattern->{'numberingmethod'} ne '' - ) { + unless ( ref($numberpattern) eq 'HASH' + && defined $numberpattern->{'label'} + && $numberpattern->{'label'} ne '' + && defined $numberpattern->{'numberingmethod'} + && $numberpattern->{'numberingmethod'} ne '' ) + { return; } # FIXME label, description and numberingmethod must be mandatory my @keys; my @values; - foreach (qw/ label description numberingmethod displayorder - label1 label2 label3 add1 add2 add3 every1 every2 every3 - setto1 setto2 setto3 whenmorethan1 whenmorethan2 whenmorethan3 - numbering1 numbering2 numbering3 /) { - if(exists $numberpattern->{$_}) { - push @keys, $_; + foreach ( + qw/ label description numberingmethod displayorder + label1 label2 label3 add1 add2 add3 every1 every2 every3 + setto1 setto2 setto3 whenmorethan1 whenmorethan2 whenmorethan3 + numbering1 numbering2 numbering3 / + ) + { + if ( exists $numberpattern->{$_} ) { + push @keys, $_; push @values, $numberpattern->{$_}; } } - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $query = "INSERT INTO subscription_numberpatterns"; - $query .= '(' . join(',', @keys) . ')'; - $query .= ' VALUES (' . ('?,' x (scalar(@keys)-1)) . '?)'; + $query .= '(' . join( ',', @keys ) . ')'; + $query .= ' VALUES (' . ( '?,' x ( scalar(@keys) - 1 ) ) . '?)'; my $sth = $dbh->prepare($query); - my $rv = $sth->execute(@values); + my $rv = $sth->execute(@values); - if(defined $rv) { - return $dbh->last_insert_id(undef, undef, "subscription_numberpatterns", undef); + if ( defined $rv ) { + return $dbh->last_insert_id( undef, undef, "subscription_numberpatterns", undef ); } return $rv; @@ -185,43 +186,41 @@ Modifies a numberpattern sub ModSubscriptionNumberpattern { my $numberpattern = shift; - unless( - ref($numberpattern) eq 'HASH' - && defined $numberpattern->{'id'} - && $numberpattern->{'id'} > 0 - && ( - (defined $numberpattern->{'label'} - && $numberpattern->{'label'} ne '') - || !defined $numberpattern->{'label'} - ) - && ( - (defined $numberpattern->{'numberingmethod'} - && $numberpattern->{'numberingmethod'} ne '') - || !defined $numberpattern->{'numberingmethod'} - ) - ) { + unless ( + ref($numberpattern) eq 'HASH' + && defined $numberpattern->{'id'} + && $numberpattern->{'id'} > 0 + && ( ( defined $numberpattern->{'label'} && $numberpattern->{'label'} ne '' ) + || !defined $numberpattern->{'label'} ) + && ( ( defined $numberpattern->{'numberingmethod'} && $numberpattern->{'numberingmethod'} ne '' ) + || !defined $numberpattern->{'numberingmethod'} ) + ) + { return; } my @keys; my @values; - foreach (qw/ label description numberingmethod displayorder - label1 label2 label3 add1 add2 add3 every1 every2 every3 - setto1 setto2 setto3 whenmorethan1 whenmorethan2 whenmorethan3 - numbering1 numbering2 numbering3 /) { - if(exists $numberpattern->{$_}) { - push @keys, $_; + foreach ( + qw/ label description numberingmethod displayorder + label1 label2 label3 add1 add2 add3 every1 every2 every3 + setto1 setto2 setto3 whenmorethan1 whenmorethan2 whenmorethan3 + numbering1 numbering2 numbering3 / + ) + { + if ( exists $numberpattern->{$_} ) { + push @keys, $_; push @values, $numberpattern->{$_}; } } - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $query = "UPDATE subscription_numberpatterns"; - $query .= ' SET ' . join(' = ?,', @keys) . ' = ?'; + $query .= ' SET ' . join( ' = ?,', @keys ) . ' = ?'; $query .= ' WHERE id = ?'; my $sth = $dbh->prepare($query); - return $sth->execute(@values, $numberpattern->{'id'}); + return $sth->execute( @values, $numberpattern->{'id'} ); } =head2 DelSubscriptionNumberpattern @@ -239,7 +238,7 @@ Delete a number pattern sub DelSubscriptionNumberpattern { my $numberpatternid = shift; - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $query = qq{ DELETE FROM subscription_numberpatterns WHERE id = ? @@ -261,7 +260,7 @@ sub GetSubscriptionsWithNumberpattern { return unless $numberpatternid; - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $query = qq{ SELECT * FROM subscription @@ -270,13 +269,12 @@ sub GetSubscriptionsWithNumberpattern { }; my $sth = $dbh->prepare($query); my @results; - if ($sth->execute($numberpatternid)) { - @results = @{ $sth->fetchall_arrayref({}) }; + if ( $sth->execute($numberpatternid) ) { + @results = @{ $sth->fetchall_arrayref( {} ) }; } return @results; } - 1; __END__ diff --git a/C4/Service.pm b/C4/Service.pm index c50051d6aa..ab33112033 100644 --- a/C4/Service.pm +++ b/C4/Service.pm @@ -41,8 +41,8 @@ This module packages several useful functions for JSON webservices. use strict; use warnings; -use CGI qw ( -utf8 ); -use C4::Auth qw( check_api_auth ); +use CGI qw ( -utf8 ); +use C4::Auth qw( check_api_auth ); use C4::Output qw( output_with_http_headers ); use C4::Output::JSONStream; use JSON; @@ -53,8 +53,8 @@ sub _output { my ( $response, $status ) = @_; binmode STDOUT, ':encoding(UTF-8)'; - if ( $query->param( 'callback' ) ) { - output_with_http_headers $query, $cookie, $query->param( 'callback' ) . '(' . $response->output . ');', 'js'; + if ( $query->param('callback') ) { + output_with_http_headers $query, $cookie, $query->param('callback') . '(' . $response->output . ');', 'js'; } else { output_with_http_headers $query, $cookie, $response->output, 'json', $status; } @@ -84,7 +84,7 @@ sub init { my ( $status, $cookie_, $sessionID ) = check_api_auth( $query, \%needed_flags ); - our $cookie = $cookie_; # I have no desire to offend the Perl scoping gods + our $cookie = $cookie_; # I have no desire to offend the Perl scoping gods $class->return_error( 'auth', $status ) if ( $status ne 'ok' ); @@ -115,8 +115,8 @@ sub return_error { my $response = C4::Output::JSONStream->new; - $response->param( message => $error ) if ( $error ); - $response->param( type => $type, %flags ); + $response->param( message => $error ) if ($error); + $response->param( type => $type, %flags ); _output( $response, '400 Bad Request' ); exit; @@ -149,13 +149,13 @@ sub return_multi { my $response = C4::Output::JSONStream->new; if ( !@$responses ) { - $class->return_success( $response ); + $class->return_success($response); } else { my @responses_formatted; - foreach my $response ( @$responses ) { - if ( ref( $response ) eq 'ARRAY' ) { - my ($type, $error, @error_flags) = @$response; + foreach my $response (@$responses) { + if ( ref($response) eq 'ARRAY' ) { + my ( $type, $error, @error_flags ) = @$response; push @responses_formatted, { is_error => JSON::true, type => $type, message => $error, @error_flags }; } else { @@ -182,7 +182,7 @@ exit with HTTP status 200. sub return_success { my ( $class, $response ) = @_; - _output( $response ); + _output($response); } =head2 require_params @@ -201,9 +201,9 @@ sub require_params { my @values; - for my $param ( @params ) { - $class->return_error( 'params', "Missing '$param'" ) if ( !defined( $query->param( $param ) ) ); - push @values, scalar $query->param( $param ); # will we ever need multi_param here? + for my $param (@params) { + $class->return_error( 'params', "Missing '$param'" ) if ( !defined( $query->param($param) ) ); + push @values, scalar $query->param($param); # will we ever need multi_param here? } return @values; @@ -242,16 +242,16 @@ sub dispatch { my $path_info = $query->path_info || '/'; - ROUTE: foreach my $route ( @_ ) { +ROUTE: foreach my $route (@_) { my ( $path, $params, $handler ) = @$route; - next unless ( my @match = ( ($query->request_method . ' ' . $path_info) =~ m,^$path$, ) ); + next unless ( my @match = ( ( $query->request_method . ' ' . $path_info ) =~ m,^$path$, ) ); - for my $param ( @$params ) { - next ROUTE if ( !defined( $query->param ( $param ) ) ); + for my $param (@$params) { + next ROUTE if ( !defined( $query->param($param) ) ); } - $handler->( @match ); + $handler->(@match); return; } diff --git a/C4/ShelfBrowser.pm b/C4/ShelfBrowser.pm index 5c9159d002..6af35ec324 100644 --- a/C4/ShelfBrowser.pm +++ b/C4/ShelfBrowser.pm @@ -26,12 +26,13 @@ use C4::Koha qw( GetNormalizedUPC GetNormalizedOCLCNumber GetNormalizedISBN GetN use Koha::Biblios; use Koha::Libraries; -our (@ISA, @EXPORT_OK); +our ( @ISA, @EXPORT_OK ); + BEGIN { require Exporter; @ISA = qw(Exporter); @EXPORT_OK = qw( - GetNearbyItems + GetNearbyItems ); } @@ -106,62 +107,68 @@ This will throw an exception if something went wrong. =cut sub GetNearbyItems { - my ( $itemnumber, $num_each_side, $gap) = @_; + my ( $itemnumber, $num_each_side, $gap ) = @_; $num_each_side ||= 3; - $gap ||= 7; # Should be > $num_each_side + $gap ||= 7; # Should be > $num_each_side die "BAD CALL in C4::ShelfBrowser::GetNearbyItems, gap should be > num_each_side" if $gap <= $num_each_side; - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $sth_get_item_details = $dbh->prepare("SELECT cn_sort,homebranch,location,ccode from items where itemnumber=?"); $sth_get_item_details->execute($itemnumber); my $item_details_result = $sth_get_item_details->fetchrow_hashref(); - die "Unable to find item '$itemnumber' for shelf browser" if (!$sth_get_item_details); + die "Unable to find item '$itemnumber' for shelf browser" if ( !$sth_get_item_details ); my $start_cn_sort = $item_details_result->{'cn_sort'}; - my ($start_homebranch, $start_location, $start_ccode); - if (C4::Context->preference('ShelfBrowserUsesHomeBranch') && - defined($item_details_result->{'homebranch'})) { - $start_homebranch->{code} = $item_details_result->{'homebranch'}; - $start_homebranch->{description} = Koha::Libraries->find($item_details_result->{'homebranch'})->branchname; + my ( $start_homebranch, $start_location, $start_ccode ); + if ( C4::Context->preference('ShelfBrowserUsesHomeBranch') + && defined( $item_details_result->{'homebranch'} ) ) + { + $start_homebranch->{code} = $item_details_result->{'homebranch'}; + $start_homebranch->{description} = Koha::Libraries->find( $item_details_result->{'homebranch'} )->branchname; } - if (C4::Context->preference('ShelfBrowserUsesLocation') && - defined($item_details_result->{'location'})) { + if ( C4::Context->preference('ShelfBrowserUsesLocation') + && defined( $item_details_result->{'location'} ) ) + { $start_location->{code} = $item_details_result->{'location'}; - $start_location->{description} = GetAuthorisedValueDesc('','',$item_details_result->{'location'},'','','LOC','opac'); + $start_location->{description} = + GetAuthorisedValueDesc( '', '', $item_details_result->{'location'}, '', '', 'LOC', 'opac' ); } - if (C4::Context->preference('ShelfBrowserUsesCcode') && - defined($item_details_result->{'ccode'})) { + if ( C4::Context->preference('ShelfBrowserUsesCcode') + && defined( $item_details_result->{'ccode'} ) ) + { $start_ccode->{code} = $item_details_result->{'ccode'}; - $start_ccode->{description} = GetAuthorisedValueDesc('', '', $item_details_result->{'ccode'}, '', '', 'CCODE', 'opac'); + $start_ccode->{description} = + GetAuthorisedValueDesc( '', '', $item_details_result->{'ccode'}, '', '', 'CCODE', 'opac' ); } # Build the query for previous and next items - my $prev_query =' + my $prev_query = ' SELECT itemnumber, biblionumber, cn_sort, itemcallnumber FROM items WHERE ((cn_sort = ? AND itemnumber < ?) OR cn_sort < ?) '; - my $next_query =' + my $next_query = ' SELECT itemnumber, biblionumber, cn_sort, itemcallnumber FROM items WHERE ((cn_sort = ? AND itemnumber >= ?) OR cn_sort > ?) '; my @params; my $query_cond; - push @params, ($start_cn_sort, $itemnumber, $start_cn_sort); + push @params, ( $start_cn_sort, $itemnumber, $start_cn_sort ); + if ($start_homebranch) { - $query_cond .= 'AND homebranch = ? '; - push @params, $start_homebranch->{code}; + $query_cond .= 'AND homebranch = ? '; + push @params, $start_homebranch->{code}; } if ($start_location) { - $query_cond .= 'AND location = ? '; - push @params, $start_location->{code}; + $query_cond .= 'AND location = ? '; + push @params, $start_location->{code}; } if ($start_ccode) { - $query_cond .= 'AND ccode = ? '; - push @params, $start_ccode->{code}; + $query_cond .= 'AND ccode = ? '; + push @params, $start_ccode->{code}; } my @prev_items = @{ @@ -187,17 +194,15 @@ sub GetNearbyItems { $next_item = undef if not $next_item - or ( $next_item->{itemnumber} == $items[-1]->{itemnumber} - and ( @prev_items or @next_items <= 1 ) - ); + or ( $next_item->{itemnumber} == $items[-1]->{itemnumber} + and ( @prev_items or @next_items <= 1 ) ); $prev_item = undef if not $prev_item - or ( $prev_item->{itemnumber} == $items[0]->{itemnumber} - and ( @next_items or @prev_items <= 1 ) - ); + or ( $prev_item->{itemnumber} == $items[0]->{itemnumber} + and ( @next_items or @prev_items <= 1 ) ); # populate the items - @items = GetShelfInfo( @items ); + @items = GetShelfInfo(@items); return { items => \@items, @@ -212,10 +217,10 @@ sub GetNearbyItems { # populate an item list with its title and upc, oclc and isbn normalized. # Not really intended to be exported. sub GetShelfInfo { - my @items = @_; + my @items = @_; my $marcflavour = C4::Context->preference("marcflavour"); my @valid_items; - for my $item ( @items ) { + for my $item (@items) { my $biblio = Koha::Biblios->find( $item->{biblionumber} ); next unless defined $biblio; @@ -227,10 +232,10 @@ sub GetShelfInfo { $item->{part_number} = $biblio->part_number; $item->{part_name} = $biblio->part_name; my $this_record = $biblio->metadata->record; - $item->{'browser_normalized_upc'} = GetNormalizedUPC($this_record,$marcflavour); - $item->{'browser_normalized_oclc'} = GetNormalizedOCLCNumber($this_record,$marcflavour); - $item->{'browser_normalized_isbn'} = GetNormalizedISBN(undef,$this_record,$marcflavour); - $item->{'browser_normalized_ean'} = GetNormalizedEAN($this_record,$marcflavour); + $item->{'browser_normalized_upc'} = GetNormalizedUPC( $this_record, $marcflavour ); + $item->{'browser_normalized_oclc'} = GetNormalizedOCLCNumber( $this_record, $marcflavour ); + $item->{'browser_normalized_isbn'} = GetNormalizedISBN( undef, $this_record, $marcflavour ); + $item->{'browser_normalized_ean'} = GetNormalizedEAN( $this_record, $marcflavour ); push @valid_items, $item; } return @valid_items; diff --git a/C4/SocialData.pm b/C4/SocialData.pm index 8a9c123529..899e44cbba 100644 --- a/C4/SocialData.pm +++ b/C4/SocialData.pm @@ -57,10 +57,10 @@ returns: =cut sub get_data { - my ( $isbn ) = @_; - my $dbh = C4::Context->dbh; - my $sth = $dbh->prepare( qq{SELECT * FROM social_data WHERE isbn = ? LIMIT 1} ); - $sth->execute( $isbn ); + my ($isbn) = @_; + my $dbh = C4::Context->dbh; + my $sth = $dbh->prepare(qq{SELECT * FROM social_data WHERE isbn = ? LIMIT 1}); + $sth->execute($isbn); my $results = $sth->fetchrow_hashref; return $results; @@ -79,28 +79,32 @@ data order : isbn ; active ; critics number , critics pro number ; quotations nu =cut sub update_data { - my ( $output_filepath ) = @_; + my ($output_filepath) = @_; my $dbh = C4::Context->dbh; - my $sth = $dbh->prepare( qq{INSERT INTO social_data ( + my $sth = $dbh->prepare( + qq{INSERT INTO social_data ( `isbn`, `num_critics`, `num_critics_pro`, `num_quotations`, `num_videos`, `score_avg`, `num_scores` ) VALUES ( ?, ?, ?, ?, ?, ?, ? ) ON DUPLICATE KEY UPDATE `num_critics`=?, `num_critics_pro`=?, `num_quotations`=?, `num_videos`=?, `score_avg`=?, `num_scores`=? - } ); + } + ); open my $file, '<', $output_filepath or die "File $output_filepath can not be read"; - my $sep = qq{;}; - my $i = 0; + my $sep = qq{;}; + my $i = 0; my $unknown = 0; while ( my $line = <$file> ) { - my ( $isbn, $active, $num_critics, $num_critics_pro, $num_quotations, $num_videos, $score_avg, $num_scores ) = split $sep, $line; + my ( $isbn, $active, $num_critics, $num_critics_pro, $num_quotations, $num_videos, $score_avg, $num_scores ) = + split $sep, $line; next if not $active; eval { - $sth->execute( $isbn, $num_critics, $num_critics_pro, $num_quotations, $num_videos, $score_avg, $num_scores, - $num_critics, $num_critics_pro, $num_quotations, $num_videos, $score_avg, $num_scores + $sth->execute( + $isbn, $num_critics, $num_critics_pro, $num_quotations, $num_videos, $score_avg, $num_scores, + $num_critics, $num_critics_pro, $num_quotations, $num_videos, $score_avg, $num_scores ); }; - if ( $@ ) { + if ($@) { warn "Can't insert $isbn ($@)"; } else { $i++; @@ -118,9 +122,11 @@ Get social data report sub get_report { my $dbh = C4::Context->dbh; - my $sth = $dbh->prepare( qq{ + my $sth = $dbh->prepare( + qq{ SELECT biblionumber, isbn FROM biblioitems - } ); # FIXME We could better join socialdata here than call get_data for each record? + } + ); # FIXME We could better join socialdata here than call get_data for each record? $sth->execute; my %results; while ( my ( $biblionumber, $isbn ) = $sth->fetchrow() ) { @@ -128,15 +134,14 @@ sub get_report { my $original_isbn = $isbn; $isbn =~ s/^\s*(\S*)\s*$/$1/; $isbn = GetNormalizedISBN( $isbn, undef, undef ); - $isbn = Business::ISBN->new( $isbn ); + $isbn = Business::ISBN->new($isbn); next if not $isbn; - eval{ - $isbn = $isbn->as_isbn13->as_string; - }; + eval { $isbn = $isbn->as_isbn13->as_string; }; next if $@; $isbn =~ s/-//g; - my $social_datas = C4::SocialData::get_data( $isbn ); # FIXME Why is data not included in $results ? - if ( $social_datas ) { + my $social_datas = C4::SocialData::get_data($isbn); # FIXME Why is data not included in $results ? + + if ($social_datas) { push @{ $results{with} }, { biblionumber => $biblionumber, isbn => $isbn, original => $original_isbn }; } else { push @{ $results{without} }, { biblionumber => $biblionumber, isbn => $isbn, original => $original_isbn }; diff --git a/C4/Stats.pm b/C4/Stats.pm index e13d30dafb..fcf8eb66f0 100644 --- a/C4/Stats.pm +++ b/C4/Stats.pm @@ -21,12 +21,13 @@ use Modern::Perl; use Koha::Statistics; -our (@ISA, @EXPORT_OK); +our ( @ISA, @EXPORT_OK ); + BEGIN { require Exporter; - @ISA = qw(Exporter); + @ISA = qw(Exporter); @EXPORT_OK = qw( - UpdateStats + UpdateStats ); } diff --git a/C4/TTParser.pm b/C4/TTParser.pm index 269d868a77..9d8900f144 100644 --- a/C4/TTParser.pm +++ b/C4/TTParser.pm @@ -29,50 +29,56 @@ use warnings; #); #tokens found so far (used like a stack) -my ( @tokens ); +my (@tokens); #shiftnext token or undef -sub next_token{ +sub next_token { return shift @tokens; } #unshift token back on @tokens -sub unshift_token{ +sub unshift_token { my $self = shift; unshift @tokens, shift; } #have a peep at next token -sub peep_token{ +sub peep_token { return $tokens[0]; } #wrapper for parse #please use this method INSTEAD of the HTML::Parser->parse_file method (and HTML::Parser->parse) #signature build_tokens( self, filename) -sub build_tokens{ - my ($self, $filename) = @_; +sub build_tokens { + my ( $self, $filename ) = @_; $self->{filename} = $filename; - $self->handler(start => "start", "self, line, tagname, attr, text"); #signature is start( self, linenumber, tagname, hash of attributes, original text ) - $self->handler(text => "text", "self, line, text, is_cdata"); #signature is text( self, linenumber, original text, is_cdata ) - $self->handler(end => "end", "self, line, tag, attr, text"); #signature is end( self, linenumber, tagename, original text ) - $self->handler(declaration => "declaration", "self, line, text, is_cdata"); # declaration - $self->handler(comment => "comment", "self, line, text, is_cdata"); # comments - $self->handler(process => "process", "self, line, text, is_cdata"); # processing statement -# $self->handler(default => "default", "self, line, text, is_cdata"); # anything else - $self->marked_sections(1); #treat anything inside CDATA tags as text, should really make it a C4::TmplTokenType::CDATA - $self->unbroken_text(1); #make contiguous whitespace into a single token (can span multiple lines) - open(my $fh, "<:encoding(utf8)", $filename) || die "Cannot open $filename ($!)"; + $self->handler( start => "start", "self, line, tagname, attr, text" ) + ; #signature is start( self, linenumber, tagname, hash of attributes, original text ) + $self->handler( text => "text", "self, line, text, is_cdata" ) + ; #signature is text( self, linenumber, original text, is_cdata ) + $self->handler( end => "end", "self, line, tag, attr, text" ) + ; #signature is end( self, linenumber, tagename, original text ) + $self->handler( declaration => "declaration", "self, line, text, is_cdata" ); # declaration + $self->handler( comment => "comment", "self, line, text, is_cdata" ); # comments + $self->handler( process => "process", "self, line, text, is_cdata" ); # processing statement + + # $self->handler(default => "default", "self, line, text, is_cdata"); # anything else + $self->marked_sections(1) + ; #treat anything inside CDATA tags as text, should really make it a C4::TmplTokenType::CDATA + $self->unbroken_text(1); #make contiguous whitespace into a single token (can span multiple lines) + open( my $fh, "<:encoding(utf8)", $filename ) || die "Cannot open $filename ($!)"; $self->parse_file($fh); return $self; } #handle parsing of text -sub text{ - my $self = shift; - my $line = shift; - my $work = shift; # original text +sub text { + my $self = shift; + my $line = shift; + my $work = shift; # original text my $is_cdata = shift; + # If there is a split template toolkit tag if ( $work =~ m/^(?:(?!\[%).)*?%\]/s ) { my @strings = ($&); @@ -93,12 +99,17 @@ sub text{ $token ? $token->line_number : $line, $self->{filename} ); } - while($work){ + while ($work) { + # if there is a template_toolkit tag - if( $work =~ m/\[%.*?%\]/ ){ + if ( $work =~ m/\[%.*?%\]/ ) { + #everything before this tag is text (or possibly CDATA), add a text token to tokens if $` - if( $` ){ - my $t = C4::TmplToken->new( $`, ($is_cdata? C4::TmplTokenType::CDATA : C4::TmplTokenType::TEXT), $line, $self->{filename} ); + if ($`) { + my $t = C4::TmplToken->new( + $`, ( $is_cdata ? C4::TmplTokenType::CDATA : C4::TmplTokenType::TEXT ), $line, + $self->{filename} + ); push @tokens, $t; } @@ -109,9 +120,13 @@ sub text{ # put work still to do back into work $work = $' ? $' : 0; } else { + # If there is some left over work, treat it as text token - my $t = C4::TmplToken->new( $work, ($is_cdata? C4::TmplTokenType::CDATA : C4::TmplTokenType::TEXT), $line, $self->{filename} ); - + my $t = C4::TmplToken->new( + $work, ( $is_cdata ? C4::TmplTokenType::CDATA : C4::TmplTokenType::TEXT ), $line, + $self->{filename} + ); + push @tokens, $t; last; } @@ -119,79 +134,92 @@ sub text{ } sub declaration { - my $self = shift; - my $line = shift; - my $work = shift; #original text + my $self = shift; + my $line = shift; + my $work = shift; #original text my $is_cdata = shift; - my $t = C4::TmplToken->new( $work, ($is_cdata? C4::TmplTokenType::CDATA : C4::TmplTokenType::TEXT), $line, $self->{filename} ); - push @tokens, $t; -} + my $t = C4::TmplToken->new( + $work, ( $is_cdata ? C4::TmplTokenType::CDATA : C4::TmplTokenType::TEXT ), $line, + $self->{filename} + ); + push @tokens, $t; +} sub comment { - my $self = shift; - my $line = shift; - my $work = shift; #original text + my $self = shift; + my $line = shift; + my $work = shift; #original text my $is_cdata = shift; - my $t = C4::TmplToken->new( $work, ($is_cdata? C4::TmplTokenType::CDATA : C4::TmplTokenType::TEXT), $line, $self->{filename} ); - push @tokens, $t; -} + my $t = C4::TmplToken->new( + $work, ( $is_cdata ? C4::TmplTokenType::CDATA : C4::TmplTokenType::TEXT ), $line, + $self->{filename} + ); + push @tokens, $t; +} sub process { - my $self = shift; - my $line = shift; - my $work = shift; #original text + my $self = shift; + my $line = shift; + my $work = shift; #original text my $is_cdata = shift; - my $t = C4::TmplToken->new( $work, ($is_cdata? C4::TmplTokenType::CDATA : C4::TmplTokenType::TEXT), $line, $self->{filename} ); + my $t = C4::TmplToken->new( + $work, ( $is_cdata ? C4::TmplTokenType::CDATA : C4::TmplTokenType::TEXT ), $line, + $self->{filename} + ); push @tokens, $t; } sub default { - my $self = shift; - my $line = shift; - my $work = shift; #original text + my $self = shift; + my $line = shift; + my $work = shift; #original text my $is_cdata = shift; - my $t = C4::TmplToken->new( $work, ($is_cdata? C4::TmplTokenType::CDATA : C4::TmplTokenType::TEXT), $line, $self->{filename} ); - push @tokens, $t; -} - + my $t = C4::TmplToken->new( + $work, ( $is_cdata ? C4::TmplTokenType::CDATA : C4::TmplTokenType::TEXT ), $line, + $self->{filename} + ); + push @tokens, $t; +} #handle opening html tags -sub start{ +sub start { my $self = shift; my $line = shift; - my $tag = shift; - my $hash = shift; #hash of attr/value pairs - my $text = shift; #original text - my $t = C4::TmplToken->new( $text, C4::TmplTokenType::TAG, $line, $self->{filename}); + my $tag = shift; + my $hash = shift; #hash of attr/value pairs + my $text = shift; #original text + my $t = C4::TmplToken->new( $text, C4::TmplTokenType::TAG, $line, $self->{filename} ); my %attr; + # tags seem to be uses in an 'interesting' way elsewhere.. - for my $key( %$hash ) { + for my $key (%$hash) { next unless defined $hash->{$key}; - if ($key eq "/"){ - $attr{+lc($key)} = [ $key, $hash->{$key}, $key."=".$hash->{$key}, 1 ]; - } - else { - $attr{+lc($key)} = [ $key, $hash->{$key}, $key."=".$hash->{$key}, 0 ]; - } + if ( $key eq "/" ) { + $attr{ +lc($key) } = [ $key, $hash->{$key}, $key . "=" . $hash->{$key}, 1 ]; + } else { + $attr{ +lc($key) } = [ $key, $hash->{$key}, $key . "=" . $hash->{$key}, 0 ]; + } } $t->set_attributes( \%attr ); push @tokens, $t; } #handle closing html tags -sub end{ +sub end { my $self = shift; my $line = shift; - my $tag = shift; + my $tag = shift; my $hash = shift; my $text = shift; + # what format should this be in? my $t = C4::TmplToken->new( $text, C4::TmplTokenType::TAG, $line, $self->{filename} ); my %attr; + # tags seem to be uses in an 'interesting' way elsewhere.. - for my $key( %$hash ) { + for my $key (%$hash) { next unless defined $hash->{$key}; - $attr{+lc($key)} = [ $key, $hash->{$key}, $key."=".$hash->{$key}, 0 ]; + $attr{ +lc($key) } = [ $key, $hash->{$key}, $key . "=" . $hash->{$key}, 0 ]; } $t->set_attributes( \%attr ); push @tokens, $t; diff --git a/C4/Tags.pm b/C4/Tags.pm index eedd000318..f55fe7f300 100644 --- a/C4/Tags.pm +++ b/C4/Tags.pm @@ -29,37 +29,39 @@ use Koha::Tags; use Koha::Tags::Approvals; use Koha::Tags::Indexes; use constant TAG_FIELDS => qw(tag_id borrowernumber biblionumber term language date_created); -use constant TAG_SELECT => "SELECT " . join(',', TAG_FIELDS) . "\n FROM tags_all\n"; +use constant TAG_SELECT => "SELECT " . join( ',', TAG_FIELDS ) . "\n FROM tags_all\n"; + +our ( @ISA, @EXPORT_OK ); -our (@ISA, @EXPORT_OK); BEGIN { @ISA = qw(Exporter); @EXPORT_OK = qw( - get_tags get_tag_rows - add_tags - add_tag - add_tag_approval - add_tag_index - remove_tag - get_approval_rows - blacklist - whitelist - is_approved - approval_counts - get_count_by_tag_status - get_filters - stratify_tags + get_tags get_tag_rows + add_tags + add_tag + add_tag_approval + add_tag_index + remove_tag + get_approval_rows + blacklist + whitelist + is_approved + approval_counts + get_count_by_tag_status + get_filters + stratify_tags ); my $ext_dict = C4::Context->preference('TagsExternalDictionary'); - if ( $ext_dict && ! check_install( module => 'Lingua::Ispell' ) ) { + + if ( $ext_dict && !check_install( module => 'Lingua::Ispell' ) ) { warn "Ignoring TagsExternalDictionary, because Lingua::Ispell is not installed."; $ext_dict = q{}; } - if ($ext_dict) { - require Lingua::Ispell; + if ($ext_dict) { + require Lingua::Ispell; import Lingua::Ispell qw(spellcheck add_word_lc); $Lingua::Ispell::path = $ext_dict; - } + } } =head1 C4::Tags.pm - Support for user tagging of biblios. @@ -67,32 +69,32 @@ BEGIN { =cut sub get_filters { - my $query = "SELECT * FROM tags_filters "; - my ($sth); - if (@_) { - $sth = C4::Context->dbh->prepare($query . " WHERE filter_id = ? "); - $sth->execute(shift); - } else { - $sth = C4::Context->dbh->prepare($query); - $sth->execute; - } - return $sth->fetchall_arrayref({}); + my $query = "SELECT * FROM tags_filters "; + my ($sth); + if (@_) { + $sth = C4::Context->dbh->prepare( $query . " WHERE filter_id = ? " ); + $sth->execute(shift); + } else { + $sth = C4::Context->dbh->prepare($query); + $sth->execute; + } + return $sth->fetchall_arrayref( {} ); } # (SELECT count(*) FROM tags_all ) as tags_all, # (SELECT count(*) FROM tags_index ) as tags_index, sub approval_counts { - my $query = "SELECT + my $query = "SELECT (SELECT count(*) FROM tags_approval WHERE approved= 1) as approved_count, (SELECT count(*) FROM tags_approval WHERE approved=-1) as rejected_count, (SELECT count(*) FROM tags_approval WHERE approved= 0) as unapproved_count "; - my $sth = C4::Context->dbh->prepare($query); - $sth->execute; - my $result = $sth->fetchrow_hashref(); - $result->{approved_total} = $result->{approved_count} + $result->{rejected_count} + $result->{unapproved_count}; - return $result; + my $sth = C4::Context->dbh->prepare($query); + $sth->execute; + my $result = $sth->fetchrow_hashref(); + $result->{approved_total} = $result->{approved_count} + $result->{rejected_count} + $result->{unapproved_count}; + return $result; } =head2 get_count_by_tag_status @@ -103,198 +105,197 @@ Takes a status and gets a count of tags with that status =cut -sub get_count_by_tag_status { +sub get_count_by_tag_status { my ($status) = @_; - my $dbh = C4::Context->dbh; - my $query = - "SELECT count(*) FROM tags_approval WHERE approved=?"; - my $sth = $dbh->prepare($query); - $sth->execute( $status ); - return $sth->fetchrow; + my $dbh = C4::Context->dbh; + my $query = "SELECT count(*) FROM tags_approval WHERE approved=?"; + my $sth = $dbh->prepare($query); + $sth->execute($status); + return $sth->fetchrow; } sub remove_tag { my $tag_id = shift or return; my $user_id = (@_) ? shift : undef; - my $rows = (defined $user_id) ? - get_tag_rows({tag_id=>$tag_id, borrowernumber=>$user_id}) : - get_tag_rows({tag_id=>$tag_id}) ; - $rows or return 0; - (scalar(@$rows) == 1) or return; # should never happen (duplicate ids) + my $rows = + ( defined $user_id ) + ? get_tag_rows( { tag_id => $tag_id, borrowernumber => $user_id } ) + : get_tag_rows( { tag_id => $tag_id } ); + $rows or return 0; + ( scalar(@$rows) == 1 ) or return; # should never happen (duplicate ids) my $row = shift(@$rows); - ($tag_id == $row->{tag_id}) or return 0; - my $tags = get_tags({term=>$row->{term}, biblionumber=>$row->{biblionumber}}); + ( $tag_id == $row->{tag_id} ) or return 0; + my $tags = get_tags( { term => $row->{term}, biblionumber => $row->{biblionumber} } ); my $index = shift(@$tags); - if ($index->{weight} <= 1) { - Koha::Tags::Indexes->search({ term => $row->{term}, biblionumber => $row->{biblionumber} })->delete; + + if ( $index->{weight} <= 1 ) { + Koha::Tags::Indexes->search( { term => $row->{term}, biblionumber => $row->{biblionumber} } )->delete; } else { - decrement_weight($row->{term},$row->{biblionumber}); + decrement_weight( $row->{term}, $row->{biblionumber} ); } - if ($index->{weight_total} <= 1) { - Koha::Tags::Approvals->search({ term => $row->{term} })->delete; + if ( $index->{weight_total} <= 1 ) { + Koha::Tags::Approvals->search( { term => $row->{term} } )->delete; } else { - decrement_weight_total($row->{term}); + decrement_weight_total( $row->{term} ); } - Koha::Tags->search({ tag_id => $tag_id })->delete; + Koha::Tags->search( { tag_id => $tag_id } )->delete; } sub get_tag_rows { - my $hash = shift || {}; + my $hash = shift || {}; my @ok_fields = TAG_FIELDS; - push @ok_fields, 'limit'; # push the limit! :) - my $wheres; - my $limit = ""; - my @exe_args = (); - foreach my $key (keys %$hash) { - unless (length $key) { - carp "Empty argument key to get_tag_rows: ignoring!"; - next; - } - unless (1 == scalar grep { $_ eq $key } @ok_fields) { + push @ok_fields, 'limit'; # push the limit! :) + my $wheres; + my $limit = ""; + my @exe_args = (); + foreach my $key ( keys %$hash ) { + unless ( length $key ) { + carp "Empty argument key to get_tag_rows: ignoring!"; + next; + } + unless ( 1 == scalar grep { $_ eq $key } @ok_fields ) { carp "get_tag_rows received unrecognized argument key '$key'."; - next; - } - if ($key eq 'limit') { - my $val = $hash->{$key}; - unless ($val =~ /^(\d+,)?\d+$/) { - carp "Non-nuerical limit value '$val' ignored!"; - next; - } - $limit = " LIMIT $val\n"; - } else { - $wheres .= ($wheres) ? " AND $key = ?\n" : " WHERE $key = ?\n"; - push @exe_args, $hash->{$key}; - } - } - my $query = TAG_SELECT . ($wheres||'') . $limit; - my $sth = C4::Context->dbh->prepare($query); - if (@exe_args) { - $sth->execute(@exe_args); - } else { - $sth->execute; - } - return $sth->fetchall_arrayref({}); + next; + } + if ( $key eq 'limit' ) { + my $val = $hash->{$key}; + unless ( $val =~ /^(\d+,)?\d+$/ ) { + carp "Non-nuerical limit value '$val' ignored!"; + next; + } + $limit = " LIMIT $val\n"; + } else { + $wheres .= ($wheres) ? " AND $key = ?\n" : " WHERE $key = ?\n"; + push @exe_args, $hash->{$key}; + } + } + my $query = TAG_SELECT . ( $wheres || '' ) . $limit; + my $sth = C4::Context->dbh->prepare($query); + if (@exe_args) { + $sth->execute(@exe_args); + } else { + $sth->execute; + } + return $sth->fetchall_arrayref( {} ); } -sub get_tags { # i.e., from tags_index - my $hash = shift || {}; - my @ok_fields = qw(term biblionumber weight limit sort approved); - my $wheres; - my $limit = ""; - my $order = ""; - my @exe_args = (); - foreach my $key (keys %$hash) { - unless (length $key) { - carp "Empty argument key to get_tags: ignoring!"; - next; - } - unless (1 == scalar grep { $_ eq $key } @ok_fields) { +sub get_tags { # i.e., from tags_index + my $hash = shift || {}; + my @ok_fields = qw(term biblionumber weight limit sort approved); + my $wheres; + my $limit = ""; + my $order = ""; + my @exe_args = (); + foreach my $key ( keys %$hash ) { + unless ( length $key ) { + carp "Empty argument key to get_tags: ignoring!"; + next; + } + unless ( 1 == scalar grep { $_ eq $key } @ok_fields ) { carp "get_tags received unrecognized argument key '$key'."; - next; - } - if ($key eq 'limit') { - my $val = $hash->{$key}; - unless ($val =~ /^(\d+,)?\d+$/) { - carp "Non-nuerical limit value '$val' ignored!"; - next; - } - $limit = " LIMIT $val\n"; - } elsif ($key eq 'sort') { - foreach my $by (split /\,/, $hash->{$key}) { - unless ( - $by =~ /^([-+])?(term)/ or - $by =~ /^([-+])?(biblionumber)/ or - $by =~ /^([-+])?(weight)/ - ) { - carp "get_tags received illegal sort order '$by'"; - next; - } - if ($order) { - $order .= ", "; - } else { - $order = " ORDER BY "; - } - $order .= $2 . " " . ((!$1) ? '' : $1 eq '-' ? 'DESC' : $1 eq '+' ? 'ASC' : '') . "\n"; - } - - } else { - my $whereval = $hash->{$key}; - my $longkey = ($key eq 'term' ) ? 'tags_index.term' : - ($key eq 'approved') ? 'tags_approval.approved' : $key; - my $op = ($whereval =~ s/^(>=|<=)// or - $whereval =~ s/^(>|=|<)// ) ? $1 : '='; - $wheres .= ($wheres) ? " AND $longkey $op ?\n" : " WHERE $longkey $op ?\n"; - push @exe_args, $whereval; - } - } - my $query = " + next; + } + if ( $key eq 'limit' ) { + my $val = $hash->{$key}; + unless ( $val =~ /^(\d+,)?\d+$/ ) { + carp "Non-nuerical limit value '$val' ignored!"; + next; + } + $limit = " LIMIT $val\n"; + } elsif ( $key eq 'sort' ) { + foreach my $by ( split /\,/, $hash->{$key} ) { + unless ( $by =~ /^([-+])?(term)/ + or $by =~ /^([-+])?(biblionumber)/ + or $by =~ /^([-+])?(weight)/ ) + { + carp "get_tags received illegal sort order '$by'"; + next; + } + if ($order) { + $order .= ", "; + } else { + $order = " ORDER BY "; + } + $order .= $2 . " " . ( ( !$1 ) ? '' : $1 eq '-' ? 'DESC' : $1 eq '+' ? 'ASC' : '' ) . "\n"; + } + + } else { + my $whereval = $hash->{$key}; + my $longkey = + ( $key eq 'term' ) ? 'tags_index.term' + : ( $key eq 'approved' ) ? 'tags_approval.approved' + : $key; + my $op = ( $whereval =~ s/^(>=|<=)// or $whereval =~ s/^(>|=|<)// ) ? $1 : '='; + $wheres .= ($wheres) ? " AND $longkey $op ?\n" : " WHERE $longkey $op ?\n"; + push @exe_args, $whereval; + } + } + my $query = " SELECT tags_index.term as term,biblionumber,weight,weight_total FROM tags_index LEFT JOIN tags_approval ON tags_index.term = tags_approval.term - " . ($wheres||'') . $order . $limit; - my $sth = C4::Context->dbh->prepare($query); - if (@exe_args) { - $sth->execute(@exe_args); - } else { - $sth->execute; - } - return $sth->fetchall_arrayref({}); + " . ( $wheres || '' ) . $order . $limit; + my $sth = C4::Context->dbh->prepare($query); + if (@exe_args) { + $sth->execute(@exe_args); + } else { + $sth->execute; + } + return $sth->fetchall_arrayref( {} ); } -sub get_approval_rows { # i.e., from tags_approval - my $hash = shift || {}; - my @ok_fields = qw(term approved date_approved approved_by weight_total limit sort borrowernumber); - my $wheres; - my $limit = ""; - my $order = ""; - my @exe_args = (); - foreach my $key (keys %$hash) { - unless (length $key) { - carp "Empty argument key to get_approval_rows: ignoring!"; - next; - } - unless (1 == scalar grep { $_ eq $key } @ok_fields) { +sub get_approval_rows { # i.e., from tags_approval + my $hash = shift || {}; + my @ok_fields = qw(term approved date_approved approved_by weight_total limit sort borrowernumber); + my $wheres; + my $limit = ""; + my $order = ""; + my @exe_args = (); + foreach my $key ( keys %$hash ) { + unless ( length $key ) { + carp "Empty argument key to get_approval_rows: ignoring!"; + next; + } + unless ( 1 == scalar grep { $_ eq $key } @ok_fields ) { carp "get_approval_rows received unrecognized argument key '$key'."; - next; - } - if ($key eq 'limit') { - my $val = $hash->{$key}; - unless ($val =~ /^(\d+,)?\d+$/) { - carp "Non-numerical limit value '$val' ignored!"; - next; - } - $limit = " LIMIT $val\n"; - } elsif ($key eq 'sort') { - foreach my $by (split /\,/, $hash->{$key}) { - unless ( - $by =~ /^([-+])?(term)/ or - $by =~ /^([-+])?(biblionumber)/ or - $by =~ /^([-+])?(borrowernumber)/ or - $by =~ /^([-+])?(weight_total)/ or - $by =~ /^([-+])?(approved(_by)?)/ or - $by =~ /^([-+])?(date_approved)/ - ) { - carp "get_approval_rows received illegal sort order '$by'"; - next; - } - if ($order) { - $order .= ", "; - } else { - $order = " ORDER BY " unless $order; - } - $order .= $2 . " " . ((!$1) ? '' : $1 eq '-' ? 'DESC' : $1 eq '+' ? 'ASC' : '') . "\n"; - } - - } else { - my $whereval = $hash->{$key}; - my $op = ($whereval =~ s/^(>=|<=)// or - $whereval =~ s/^(>|=|<)// ) ? $1 : '='; - $wheres .= ($wheres) ? " AND $key $op ?\n" : " WHERE $key $op ?\n"; - push @exe_args, $whereval; - } - } - my $query = " + next; + } + if ( $key eq 'limit' ) { + my $val = $hash->{$key}; + unless ( $val =~ /^(\d+,)?\d+$/ ) { + carp "Non-numerical limit value '$val' ignored!"; + next; + } + $limit = " LIMIT $val\n"; + } elsif ( $key eq 'sort' ) { + foreach my $by ( split /\,/, $hash->{$key} ) { + unless ( $by =~ /^([-+])?(term)/ + or $by =~ /^([-+])?(biblionumber)/ + or $by =~ /^([-+])?(borrowernumber)/ + or $by =~ /^([-+])?(weight_total)/ + or $by =~ /^([-+])?(approved(_by)?)/ + or $by =~ /^([-+])?(date_approved)/ ) + { + carp "get_approval_rows received illegal sort order '$by'"; + next; + } + if ($order) { + $order .= ", "; + } else { + $order = " ORDER BY " unless $order; + } + $order .= $2 . " " . ( ( !$1 ) ? '' : $1 eq '-' ? 'DESC' : $1 eq '+' ? 'ASC' : '' ) . "\n"; + } + + } else { + my $whereval = $hash->{$key}; + my $op = ( $whereval =~ s/^(>=|<=)// or $whereval =~ s/^(>|=|<)// ) ? $1 : '='; + $wheres .= ($wheres) ? " AND $key $op ?\n" : " WHERE $key $op ?\n"; + push @exe_args, $whereval; + } + } + my $query = " SELECT tags_approval.term AS term, tags_approval.approved AS approved, tags_approval.date_approved AS date_approved, @@ -304,208 +305,224 @@ sub get_approval_rows { # i.e., from tags_approval FROM tags_approval LEFT JOIN borrowers ON tags_approval.approved_by = borrowers.borrowernumber "; - $query .= ($wheres||'') . $order . $limit; - my $sth = C4::Context->dbh->prepare($query); - if (@exe_args) { - $sth->execute(@exe_args); - } else { - $sth->execute; - } - return $sth->fetchall_arrayref({}); + $query .= ( $wheres || '' ) . $order . $limit; + my $sth = C4::Context->dbh->prepare($query); + if (@exe_args) { + $sth->execute(@exe_args); + } else { + $sth->execute; + } + return $sth->fetchall_arrayref( {} ); } sub is_approved { - my $term = shift or return; - my $sth = C4::Context->dbh->prepare("SELECT approved FROM tags_approval WHERE term = ?"); - $sth->execute($term); + my $term = shift or return; + my $sth = C4::Context->dbh->prepare("SELECT approved FROM tags_approval WHERE term = ?"); + $sth->execute($term); my $ext_dict = C4::Context->preference('TagsExternalDictionary'); - unless ($sth->rows) { - $ext_dict and return (spellcheck($term) ? 0 : 1); # spellcheck returns empty on OK word - return 0; - } - return $sth->fetchrow; + unless ( $sth->rows ) { + $ext_dict and return ( spellcheck($term) ? 0 : 1 ); # spellcheck returns empty on OK word + return 0; + } + return $sth->fetchrow; } sub get_tag_index { - my $term = shift or return; - my $sth; - if (@_) { - $sth = C4::Context->dbh->prepare("SELECT * FROM tags_index WHERE term = ? AND biblionumber = ?"); - $sth->execute($term,shift); - } else { - $sth = C4::Context->dbh->prepare("SELECT * FROM tags_index WHERE term = ?"); - $sth->execute($term); - } - return $sth->fetchrow_hashref; + my $term = shift or return; + my $sth; + if (@_) { + $sth = C4::Context->dbh->prepare("SELECT * FROM tags_index WHERE term = ? AND biblionumber = ?"); + $sth->execute( $term, shift ); + } else { + $sth = C4::Context->dbh->prepare("SELECT * FROM tags_index WHERE term = ?"); + $sth->execute($term); + } + return $sth->fetchrow_hashref; } sub whitelist { - my $operator = shift; - defined $operator or return; # have to test defined to allow =0 (kohaadmin) + my $operator = shift; + defined $operator or return; # have to test defined to allow =0 (kohaadmin) my $ext_dict = C4::Context->preference('TagsExternalDictionary'); - if ($ext_dict) { - foreach (@_) { - spellcheck($_) or next; - add_word_lc($_); - } - } - foreach (@_) { - my $aref = get_approval_rows({term=>$_}); - if ($aref and scalar @$aref) { - mod_tag_approval($operator,$_,1); - } else { - add_tag_approval($_,$operator); - } - } - return scalar @_; + if ($ext_dict) { + foreach (@_) { + spellcheck($_) or next; + add_word_lc($_); + } + } + foreach (@_) { + my $aref = get_approval_rows( { term => $_ } ); + if ( $aref and scalar @$aref ) { + mod_tag_approval( $operator, $_, 1 ); + } else { + add_tag_approval( $_, $operator ); + } + } + return scalar @_; } + # note: there is no "unwhitelist" operation because there is no remove for Ispell. # The blacklist regexps should operate "in front of" the whitelist, so if you approve # a term mistakenly, you can still reverse it. But there is no going back to "neutral". sub blacklist { - my $operator = shift; - defined $operator or return; # have to test defined to allow =0 (kohaadmin) - foreach (@_) { - my $aref = get_approval_rows({term=>$_}); - if ($aref and scalar @$aref) { - mod_tag_approval($operator,$_,-1); - } else { - add_tag_approval($_,$operator,-1); - } - } - return scalar @_; -} -sub add_filter { - my $operator = shift; - defined $operator or return; # have to test defined to allow =0 (kohaadmin) - my $query = "INSERT INTO tags_blacklist (regexp,y,z) VALUES (?,?,?)"; - # my $sth = C4::Context->dbh->prepare($query); - return scalar @_; -} -sub remove_filter { - my $operator = shift; - defined $operator or return; # have to test defined to allow =0 (kohaadmin) - my $query = "REMOVE FROM tags_blacklist WHERE blacklist_id = ?"; - # my $sth = C4::Context->dbh->prepare($query); - # $sth->execute($term); - return scalar @_; + my $operator = shift; + defined $operator or return; # have to test defined to allow =0 (kohaadmin) + foreach (@_) { + my $aref = get_approval_rows( { term => $_ } ); + if ( $aref and scalar @$aref ) { + mod_tag_approval( $operator, $_, -1 ); + } else { + add_tag_approval( $_, $operator, -1 ); + } + } + return scalar @_; } -sub add_tag_approval { # or disapproval - my $term = shift or return; - my $query = "SELECT * FROM tags_approval WHERE term = ?"; - my $sth = C4::Context->dbh->prepare($query); - $sth->execute($term); - ($sth->rows) and return increment_weight_total($term); - my $operator = shift || 0; - my $approval = (@_ ? shift : 0); # default is unapproved - my @exe_args = ($term); # all 3 queries will use this argument - if ($operator) { - $query = "INSERT INTO tags_approval (term,approved_by,approved,date_approved) VALUES (?,?,?,NOW())"; - push @exe_args, $operator, $approval; - } elsif ($approval) { - $query = "INSERT INTO tags_approval (term,approved,date_approved) VALUES (?,?,NOW())"; - push @exe_args, $approval; - } else { - $query = "INSERT INTO tags_approval (term,date_approved) VALUES (?,NOW())"; - } - $sth = C4::Context->dbh->prepare($query); - $sth->execute(@exe_args); - return $sth->rows; +sub add_filter { + my $operator = shift; + defined $operator or return; # have to test defined to allow =0 (kohaadmin) + my $query = "INSERT INTO tags_blacklist (regexp,y,z) VALUES (?,?,?)"; + + # my $sth = C4::Context->dbh->prepare($query); + return scalar @_; +} + +sub remove_filter { + my $operator = shift; + defined $operator or return; # have to test defined to allow =0 (kohaadmin) + my $query = "REMOVE FROM tags_blacklist WHERE blacklist_id = ?"; + + # my $sth = C4::Context->dbh->prepare($query); + # $sth->execute($term); + return scalar @_; +} + +sub add_tag_approval { # or disapproval + my $term = shift or return; + my $query = "SELECT * FROM tags_approval WHERE term = ?"; + my $sth = C4::Context->dbh->prepare($query); + $sth->execute($term); + ( $sth->rows ) and return increment_weight_total($term); + my $operator = shift || 0; + my $approval = ( @_ ? shift : 0 ); # default is unapproved + my @exe_args = ($term); # all 3 queries will use this argument + + if ($operator) { + $query = "INSERT INTO tags_approval (term,approved_by,approved,date_approved) VALUES (?,?,?,NOW())"; + push @exe_args, $operator, $approval; + } elsif ($approval) { + $query = "INSERT INTO tags_approval (term,approved,date_approved) VALUES (?,?,NOW())"; + push @exe_args, $approval; + } else { + $query = "INSERT INTO tags_approval (term,date_approved) VALUES (?,NOW())"; + } + $sth = C4::Context->dbh->prepare($query); + $sth->execute(@exe_args); + return $sth->rows; } sub mod_tag_approval { - my $operator = shift; - defined $operator or return; # have to test defined to allow =0 (kohaadmin) - my $term = shift or return; - my $approval = (scalar @_ ? shift : 1); # default is to approve - my $query = "UPDATE tags_approval SET approved_by=?, approved=?, date_approved=NOW() WHERE term = ?"; - my $sth = C4::Context->dbh->prepare($query); - $sth->execute($operator,$approval,$term); + my $operator = shift; + defined $operator or return; # have to test defined to allow =0 (kohaadmin) + my $term = shift or return; + my $approval = ( scalar @_ ? shift : 1 ); # default is to approve + my $query = "UPDATE tags_approval SET approved_by=?, approved=?, date_approved=NOW() WHERE term = ?"; + my $sth = C4::Context->dbh->prepare($query); + $sth->execute( $operator, $approval, $term ); } sub add_tag_index { - my $term = shift or return; - my $biblionumber = shift or return; - my $query = "SELECT * FROM tags_index WHERE term = ? AND biblionumber = ?"; - my $sth = C4::Context->dbh->prepare($query); - $sth->execute($term,$biblionumber); - ($sth->rows) and return increment_weight($term,$biblionumber); - $query = "INSERT INTO tags_index (term,biblionumber) VALUES (?,?)"; - $sth = C4::Context->dbh->prepare($query); - $sth->execute($term,$biblionumber); - return $sth->rows; + my $term = shift or return; + my $biblionumber = shift or return; + my $query = "SELECT * FROM tags_index WHERE term = ? AND biblionumber = ?"; + my $sth = C4::Context->dbh->prepare($query); + $sth->execute( $term, $biblionumber ); + ( $sth->rows ) and return increment_weight( $term, $biblionumber ); + $query = "INSERT INTO tags_index (term,biblionumber) VALUES (?,?)"; + $sth = C4::Context->dbh->prepare($query); + $sth->execute( $term, $biblionumber ); + return $sth->rows; } sub increment_weights { - increment_weight(@_); - increment_weight_total(shift); + increment_weight(@_); + increment_weight_total(shift); } + sub decrement_weights { - decrement_weight(@_); - decrement_weight_total(shift); + decrement_weight(@_); + decrement_weight_total(shift); } + sub increment_weight_total { - _set_weight_total('weight_total+1',shift); + _set_weight_total( 'weight_total+1', shift ); } + sub increment_weight { - _set_weight('weight+1',shift,shift); + _set_weight( 'weight+1', shift, shift ); } + sub decrement_weight_total { - _set_weight_total('weight_total-1',shift); + _set_weight_total( 'weight_total-1', shift ); } + sub decrement_weight { - _set_weight('weight-1',shift,shift); + _set_weight( 'weight-1', shift, shift ); } + sub _set_weight_total { - my $sth = C4::Context->dbh->prepare(" + my $sth = C4::Context->dbh->prepare( " UPDATE tags_approval SET weight_total=" . (shift) . " WHERE term=? - "); # note: CANNOT use "?" for weight_total (see the args above). - $sth->execute(shift); # just the term + " ); # note: CANNOT use "?" for weight_total (see the args above). + $sth->execute(shift); # just the term } + sub _set_weight { - my $dbh = C4::Context->dbh; - my $sth = $dbh->prepare(" + my $dbh = C4::Context->dbh; + my $sth = $dbh->prepare( " UPDATE tags_index SET weight=" . (shift) . " WHERE term=? AND biblionumber=? - "); - $sth->execute(@_); + " ); + $sth->execute(@_); } -sub add_tag { # biblionumber,term,[borrowernumber,approvernumber] - my $biblionumber = shift or return; - my $term = shift or return; - my $borrowernumber = (@_) ? shift : 0; # the user, default to kohaadmin - $term =~ s/^\s+//; - $term =~ s/\s+$//; - ($term) or return; # must be more than whitespace - my $rows = get_tag_rows({biblionumber=>$biblionumber, borrowernumber=>$borrowernumber, term=>$term, limit=>1}); - my $query = "INSERT INTO tags_all +sub add_tag { # biblionumber,term,[borrowernumber,approvernumber] + my $biblionumber = shift or return; + my $term = shift or return; + my $borrowernumber = (@_) ? shift : 0; # the user, default to kohaadmin + $term =~ s/^\s+//; + $term =~ s/\s+$//; + ($term) or return; # must be more than whitespace + my $rows = + get_tag_rows( { biblionumber => $biblionumber, borrowernumber => $borrowernumber, term => $term, limit => 1 } ); + my $query = "INSERT INTO tags_all (borrowernumber,biblionumber,term,date_created) VALUES (?,?,?,NOW())"; - if (scalar @$rows) { - return; - } - # add to tags_all regardless of approaval - my $sth = C4::Context->dbh->prepare($query); - $sth->execute($borrowernumber,$biblionumber,$term); - # then - if (scalar @_) { # if arg remains, it is the borrowernumber of the approver: tag is pre-approved. - my $approver = shift; - add_tag_approval($term,$approver,1); - add_tag_index($term,$biblionumber,$approver); - } elsif (is_approved($term) >= 1) { - add_tag_approval($term,0,1); - add_tag_index($term,$biblionumber,1); - } else { - add_tag_approval($term); - add_tag_index($term,$biblionumber); - } + if ( scalar @$rows ) { + return; + } + + # add to tags_all regardless of approaval + my $sth = C4::Context->dbh->prepare($query); + $sth->execute( $borrowernumber, $biblionumber, $term ); + + # then + if ( scalar @_ ) { # if arg remains, it is the borrowernumber of the approver: tag is pre-approved. + my $approver = shift; + add_tag_approval( $term, $approver, 1 ); + add_tag_index( $term, $biblionumber, $approver ); + } elsif ( is_approved($term) >= 1 ) { + add_tag_approval( $term, 0, 1 ); + add_tag_index( $term, $biblionumber, 1 ); + } else { + add_tag_approval($term); + add_tag_index( $term, $biblionumber ); + } } # This takes a set of tags, as returned by C and divides @@ -523,7 +540,7 @@ sub add_tag { # biblionumber,term,[borrowernumber,approvernumber] # value. sub stratify_tags { my ( $strata, $tags ) = @_; - return (0,0) if !@$tags; + return ( 0, 0 ) if !@$tags; my ( $min, $max ); foreach (@$tags) { my $w = $_->{weight_total}; diff --git a/C4/Templates.pm b/C4/Templates.pm index fb7d3e5cb5..70910c0d05 100644 --- a/C4/Templates.pm +++ b/C4/Templates.pm @@ -2,8 +2,8 @@ package C4::Templates; use strict; use warnings; -use Carp qw( carp ); -use CGI qw ( -utf8 ); +use Carp qw( carp ); +use CGI qw ( -utf8 ); use List::MoreUtils qw( uniq ); # Copyright 2009 Chris Cormack and The Koha Dev Team @@ -40,22 +40,19 @@ use Koha::Exceptions; __PACKAGE__->mk_accessors(qw( theme activethemes preferredtheme lang filename htdocs interface vars)); - - sub new { my $class = shift; my $interface = shift; my $filename = shift; my $tmplbase = shift; - my $query = @_? shift: undef; + my $query = @_ ? shift : undef; my $htdocs; if ( $interface ne "intranet" ) { $htdocs = C4::Context->config('opachtdocs'); - } - else { + } else { $htdocs = C4::Context->config('intrahtdocs'); } - my ($theme, $lang, $activethemes)= themelanguage( $htdocs, $tmplbase, $interface, $query); + my ( $theme, $lang, $activethemes ) = themelanguage( $htdocs, $tmplbase, $interface, $query ); my @includes; foreach (@$activethemes) { push @includes, "$htdocs/$_/$lang/includes"; @@ -70,15 +67,16 @@ sub new { # Do not use template cache if script is called from commandline my $use_template_cache = C4::Context->config('template_cache_dir') && defined $ENV{GATEWAY_INTERFACE}; - my $template = Template->new( - { EVAL_PERL => 1, + my $template = Template->new( + { + EVAL_PERL => 1, ABSOLUTE => 1, - PLUGIN_BASE => 'Koha::Template::Plugin', - COMPILE_EXT => $use_template_cache ? '.ttc' : '', - COMPILE_DIR => $use_template_cache ? C4::Context->config('template_cache_dir') : '', + PLUGIN_BASE => 'Koha::Template::Plugin', + COMPILE_EXT => $use_template_cache ? '.ttc' : '', + COMPILE_DIR => $use_template_cache ? C4::Context->config('template_cache_dir') : '', INCLUDE_PATH => \@includes, - FILTERS => {}, - ENCODING => 'UTF-8', + FILTERS => {}, + ENCODING => 'UTF-8', } ) or die Template->error(); my $self = { @@ -89,7 +87,7 @@ sub new { $self->theme($theme); $self->lang($lang); $self->activethemes($activethemes); - $self->preferredtheme($activethemes->[0]); + $self->preferredtheme( $activethemes->[0] ); $self->filename($filename); $self->htdocs($htdocs); $self->interface($interface); @@ -102,27 +100,26 @@ sub output { my $self = shift; my $vars = shift; -# my $file = $self->htdocs . '/' . $self->theme .'/'.$self->lang.'/'.$self->filename; + # my $file = $self->htdocs . '/' . $self->theme .'/'.$self->lang.'/'.$self->filename; my $template = $self->{TEMPLATE}; if ( $self->interface eq 'intranet' ) { $vars->{themelang} = '/intranet-tmpl'; - } - else { + } else { $vars->{themelang} = '/opac-tmpl'; } $vars->{lang} = $self->lang; $vars->{themelang} .= '/' . $self->preferredtheme . '/' . $self->lang; $vars->{interface} = - ( $self->{interface} ne 'intranet' ? '/opac-tmpl' : '/intranet-tmpl' ); - $vars->{theme} = $self->theme; - $vars->{OpacAdditionalStylesheet} = - C4::Context->preference('OpacAdditionalStylesheet'); - $vars->{opaclayoutstylesheet} = - C4::Context->preference('opaclayoutstylesheet'); + ( $self->{interface} ne 'intranet' ? '/opac-tmpl' : '/intranet-tmpl' ); + $vars->{theme} = $self->theme; + $vars->{OpacAdditionalStylesheet} = C4::Context->preference('OpacAdditionalStylesheet'); + $vars->{opaclayoutstylesheet} = C4::Context->preference('opaclayoutstylesheet'); - if(exists $self->{VARS}{lang}) { - warn "Preventing \$template->lang='" . ($self->{vars}{lang}//'-undef-') - . "' to be overwritten by template->{VARS}{lang}='" . ($self->{VARS}{lang}//'-undef-') . "'"; + if ( exists $self->{VARS}{lang} ) { + warn "Preventing \$template->lang='" + . ( $self->{vars}{lang} // '-undef-' ) + . "' to be overwritten by template->{VARS}{lang}='" + . ( $self->{VARS}{lang} // '-undef-' ) . "'"; delete $self->{VARS}{lang}; } @@ -132,7 +129,7 @@ sub output { my $data; binmode( STDOUT, ":encoding(UTF-8)" ); $template->process( $self->filename, $vars, \$data ) - || die "Template process failed: ", $template->error(); + || die "Template process failed: ", $template->error(); return $data; } @@ -143,8 +140,8 @@ sub param { my $key = shift; my $val = shift; if ( ref($val) eq 'ARRAY' && !scalar @$val ) { $val = undef; } - elsif ( ref($val) eq 'HASH' && !scalar %$val ) { $val = undef; } - if ( $key ) { + elsif ( ref($val) eq 'HASH' && !scalar %$val ) { $val = undef; } + if ($key) { $self->{VARS}->{$key} = $val; } else { warn "Problem = a value of $val has been passed to param without key"; @@ -152,7 +149,6 @@ sub param { } } - =head1 NAME C4::Templates - Functions for managing templates @@ -169,15 +165,16 @@ my $path = C4::Context->config('intrahtdocs') . "/prog/en/includes/"; # FIXME - POD sub _get_template_file { - my ($tmplbase, $interface, $query) = @_; + my ( $tmplbase, $interface, $query ) = @_; my $is_intranet = $interface eq 'intranet'; - my $htdocs = C4::Context->config($is_intranet ? 'intrahtdocs' : 'opachtdocs'); - my ($theme, $lang, $availablethemes) = themelanguage($htdocs, $tmplbase, $interface, $query); - $lang //= 'en'; + my $htdocs = C4::Context->config( $is_intranet ? 'intrahtdocs' : 'opachtdocs' ); + my ( $theme, $lang, $availablethemes ) = themelanguage( $htdocs, $tmplbase, $interface, $query ); + $lang //= 'en'; $theme //= ''; $tmplbase = "$htdocs/$theme/$lang/modules/$tmplbase" if $tmplbase !~ /^\//; - # do not prefix an absolute path + + # do not prefix an absolute path return ( $htdocs, $theme, $lang, $tmplbase ); } @@ -194,75 +191,75 @@ sub _get_template_file { =cut sub badtemplatecheck { - my ( $template ) = @_; - if( !$template || $template !~ m/^[a-zA-Z0-9_\-\/]+\.(tt|pref)$/ ) { + my ($template) = @_; + if ( !$template || $template !~ m/^[a-zA-Z0-9_\-\/]+\.(tt|pref)$/ ) { + # This also includes two dots - Koha::Exceptions::NoPermission->throw( 'bad template path' ); + Koha::Exceptions::NoPermission->throw('bad template path'); } else { + # Check allowed dirs - make sure we operate on a copy of the config my $dirs = C4::Context->config("pluginsdir"); if ( !ref($dirs) ) { - $dirs = [ $dirs ]; - } - else { - $dirs = [ @$dirs ]; + $dirs = [$dirs]; + } else { + $dirs = [@$dirs]; } unshift @$dirs, C4::Context->config('opachtdocs'), C4::Context->config('intrahtdocs'); my $found = 0; - foreach my $dir ( @$dirs ) { + foreach my $dir (@$dirs) { $dir .= '/' if $dir !~ m/\/$/; - $found++ if $template =~ m/^$dir/; - last if $found; + $found++ if $template =~ m/^$dir/; + last if $found; } - Koha::Exceptions::NoPermission->throw( 'bad template path' ) if !$found; + Koha::Exceptions::NoPermission->throw('bad template path') if !$found; } } sub gettemplate { my ( $tmplbase, $interface, $query ) = @_; - my ($htdocs, $theme, $lang, $filename) - = _get_template_file($tmplbase, $interface, $query); - badtemplatecheck( $filename ); # single trip for bad templates - my $template = C4::Templates->new($interface, $filename, $tmplbase, $query); + my ( $htdocs, $theme, $lang, $filename ) = _get_template_file( $tmplbase, $interface, $query ); + badtemplatecheck($filename); # single trip for bad templates + my $template = C4::Templates->new( $interface, $filename, $tmplbase, $query ); -# NOTE: Commenting these out rather than deleting them so that those who need -# to know how we previously shimmed these directories will be able to understand. -# my $is_intranet = $interface eq 'intranet'; -# my $themelang = -# ($is_intranet ? '/intranet-tmpl' : '/opac-tmpl') . -# "/$theme/$lang"; -# $template->param( -# themelang => $themelang, -# interface => $is_intranet ? '/intranet-tmpl' : '/opac-tmpl', -# theme => $theme, -# lang => $lang -# ); + # NOTE: Commenting these out rather than deleting them so that those who need + # to know how we previously shimmed these directories will be able to understand. + # my $is_intranet = $interface eq 'intranet'; + # my $themelang = + # ($is_intranet ? '/intranet-tmpl' : '/opac-tmpl') . + # "/$theme/$lang"; + # $template->param( + # themelang => $themelang, + # interface => $is_intranet ? '/intranet-tmpl' : '/opac-tmpl', + # theme => $theme, + # lang => $lang + # ); # Bidirectionality, must be sent even if is the only language my $current_lang = regex_lang_subtags($lang); my $bidi; - $bidi = get_bidi($current_lang->{script}) if $current_lang->{script}; + $bidi = get_bidi( $current_lang->{script} ) if $current_lang->{script}; $template->param( - bidi => $bidi, + bidi => $bidi, ); + # Languages - my $languages_loop = getTranslatedLanguages($interface,$theme,$lang); + my $languages_loop = getTranslatedLanguages( $interface, $theme, $lang ); my $num_languages_enabled = 0; foreach my $lang (@$languages_loop) { - foreach my $sublang (@{ $lang->{'sublanguages_loop'} }) { + foreach my $sublang ( @{ $lang->{'sublanguages_loop'} } ) { $num_languages_enabled++ if $sublang->{enabled}; - } + } } - my $one_language_enabled = ($num_languages_enabled <= 1) ? 1 : 0; # deal with zero enabled langs as well + my $one_language_enabled = ( $num_languages_enabled <= 1 ) ? 1 : 0; # deal with zero enabled langs as well $template->param( - languages_loop => $languages_loop, - one_language_enabled => $one_language_enabled, + languages_loop => $languages_loop, + one_language_enabled => $one_language_enabled, ) unless $one_language_enabled; return $template; } - =head2 themelanguage my ($theme,$lang,\@themes) = themelanguage($htdocs,$tmpl,$interface,query); @@ -278,30 +275,33 @@ the use case where the DB is not populated already when rewriting/fixing. =cut sub themelanguage { - my ($htdocs, $tmpl, $interface, $query) = @_; + my ( $htdocs, $tmpl, $interface, $query ) = @_; # Select a language based on cookie, syspref available languages & browser my $lang = C4::Languages::getlanguage($query); - return availablethemes($htdocs, $tmpl, $interface, $lang); + return availablethemes( $htdocs, $tmpl, $interface, $lang ); } sub availablethemes { - my ($htdocs, $tmpl, $interface, $lang) = @_; + my ( $htdocs, $tmpl, $interface, $lang ) = @_; # Get theme my @themes; - my $theme_syspref = ($interface eq 'intranet') ? 'template' : 'opacthemes'; - my $fallback_syspref = ($interface eq 'intranet') ? 'template' : 'OPACFallback'; + my $theme_syspref = ( $interface eq 'intranet' ) ? 'template' : 'opacthemes'; + my $fallback_syspref = ( $interface eq 'intranet' ) ? 'template' : 'OPACFallback'; + # Yeah, hardcoded, last resort if the DB is not populated - my $hardcoded_theme = ($interface eq 'intranet') ? 'prog' : 'bootstrap'; + my $hardcoded_theme = ( $interface eq 'intranet' ) ? 'prog' : 'bootstrap'; # Configured theme is the first one - push @themes, C4::Context->preference( $theme_syspref ) - if C4::Context->preference( $theme_syspref ); + push @themes, C4::Context->preference($theme_syspref) + if C4::Context->preference($theme_syspref); + # Configured fallback next - push @themes, C4::Context->preference( $fallback_syspref ) - if C4::Context->preference( $fallback_syspref ); + push @themes, C4::Context->preference($fallback_syspref) + if C4::Context->preference($fallback_syspref); + # The hardcoded fallback theme is the last one push @themes, $hardcoded_theme; @@ -312,12 +312,14 @@ sub availablethemes { return ( $theme, $lang, [ uniq(@themes) ] ); } } + # Otherwise return theme/'en', last resort fallback/'en' for my $theme (@themes) { if ( -e "$htdocs/$theme/en/$where/$tmpl" ) { return ( $theme, 'en', [ uniq(@themes) ] ); } } + # tmpl is a full path, so this is a template for a plugin if ( $tmpl =~ /^\// && -e $tmpl ) { return ( $themes[0], $lang, [ uniq(@themes) ] ); @@ -331,7 +333,7 @@ sub setlanguagecookie { # We do not want to set getlanguage in cache, some additional checks are # done in C4::Languages::getlanguage - Koha::Cache::Memory::Lite->get_instance()->clear_from_cache( 'getlanguage' ); + Koha::Cache::Memory::Lite->get_instance()->clear_from_cache('getlanguage'); print $query->redirect( -uri => $uri, @@ -350,12 +352,12 @@ Returns a cookie object containing the calculated language to be used. sub getlanguagecookie { my ( $query, $language ) = @_; my $cookie = $query->cookie( - -name => 'KohaOpacLanguage', - -value => $language, + -name => 'KohaOpacLanguage', + -value => $language, -HttpOnly => 1, - -expires => '+3y', + -expires => '+3y', -sameSite => 'Lax', - -secure => ( C4::Context->https_enabled() ? 1 : 0 ), + -secure => ( C4::Context->https_enabled() ? 1 : 0 ), ); return $cookie; diff --git a/C4/TmplToken.pm b/C4/TmplToken.pm index 045269b80b..9823bb37cb 100644 --- a/C4/TmplToken.pm +++ b/C4/TmplToken.pm @@ -17,7 +17,6 @@ package C4::TmplToken; # You should have received a copy of the GNU General Public License # along with Koha; if not, see . - use strict; use warnings; use C4::TmplTokenType; @@ -32,35 +31,33 @@ This is a class representing a token scanned from an HTML::Template .tmpl file. =cut - - sub new { - my $this = shift; + my $this = shift; my $class = ref($this) || $this; - my $self = {}; + my $self = {}; bless $self, $class; - ($self->{'_string'}, $self->{'_type'}, $self->{'_lc'}, $self->{'_path'}) = @_; + ( $self->{'_string'}, $self->{'_type'}, $self->{'_lc'}, $self->{'_path'} ) = @_; return $self; } sub string { my $this = shift; - return $this->{'_string'} + return $this->{'_string'}; } sub type { my $this = shift; - return $this->{'_type'} + return $this->{'_type'}; } sub pathname { my $this = shift; - return $this->{'_path'} + return $this->{'_path'}; } sub line_number { my $this = shift; - return $this->{'_lc'} + return $this->{'_lc'}; } sub attributes { @@ -70,7 +67,7 @@ sub attributes { sub set_attributes { my $this = shift; - $this->{'_attr'} = ref $_[0] eq 'HASH'? $_[0]: \@_; + $this->{'_attr'} = ref $_[0] eq 'HASH' ? $_[0] : \@_; return $this; } @@ -83,7 +80,7 @@ sub children { # only meaningful for TEXT_PARAMETRIZED tokens sub set_children { my $this = shift; - $this->{'_kids'} = ref $_[0] eq 'ARRAY'? $_[0]: \@_; + $this->{'_kids'} = ref $_[0] eq 'ARRAY' ? $_[0] : \@_; return $this; } @@ -91,16 +88,18 @@ sub set_children { # FIXME: DIRECTIVE is not necessarily TMPL_VAR !! sub parameters_and_fields { my $this = shift; - return map { $_->type == C4::TmplTokenType::DIRECTIVE() ? $_: - ($_->type == C4::TmplTokenType::TAG - && $_->string =~ /^{'_kids'}}; + return map { + $_->type == C4::TmplTokenType::DIRECTIVE() ? $_ + : ( $_->type == C4::TmplTokenType::TAG + && $_->string =~ /^{'_kids'} }; } # only meaningful for TEXT_PARAMETRIZED tokens sub anchors { my $this = shift; - return map { $_->type == C4::TmplTokenType::TAG && $_->string =~ /^{'_kids'}}; + return map { $_->type == C4::TmplTokenType::TAG && $_->string =~ /^{'_kids'} }; } # only meaningful for TEXT_PARAMETRIZED tokens @@ -118,7 +117,7 @@ sub set_form { sub has_js_data { my $this = shift; - return defined $this->{'_js_data'} && ref($this->{'_js_data'}) eq 'ARRAY'; + return defined $this->{'_js_data'} && ref( $this->{'_js_data'} ) eq 'ARRAY'; } sub js_data { diff --git a/C4/TmplTokenType.pm b/C4/TmplTokenType.pm index 91bc40c23c..4b7a16a016 100644 --- a/C4/TmplTokenType.pm +++ b/C4/TmplTokenType.pm @@ -35,51 +35,51 @@ The predefined constants are ############################################################################### - ############################################################################### use vars qw( $_text $_text_parametrized $_cdata $_tag $_decl $_pi $_directive $_comment $_null $_unknown ); -our (@ISA, @EXPORT_OK); +our ( @ISA, @EXPORT_OK ); + BEGIN { require Exporter; - @ISA = qw(Exporter); + @ISA = qw(Exporter); @EXPORT_OK = qw( - TEXT - TEXT_PARAMETRIZED - CDATA - TAG - DECL - PI - DIRECTIVE - COMMENT - UNKNOWN + TEXT + TEXT_PARAMETRIZED + CDATA + TAG + DECL + PI + DIRECTIVE + COMMENT + UNKNOWN ); my $new = sub { - my $this = 'C4::TmplTokenType';#shift; - my $class = ref($this) || $this; - my $self = {}; - bless $self, $class; - ($self->{'id'}, $self->{'name'}, $self->{'desc'}) = @_; - return $self; + my $this = 'C4::TmplTokenType'; #shift; + my $class = ref($this) || $this; + my $self = {}; + bless $self, $class; + ( $self->{'id'}, $self->{'name'}, $self->{'desc'} ) = @_; + return $self; }; - $_text = &$new(0, 'TEXT'); - $_text_parametrized = &$new(8, 'TEXT-PARAMETRIZED'); - $_cdata = &$new(1, 'CDATA'); - $_tag = &$new(2, 'TAG'); - $_decl = &$new(3, 'DECL'); - $_pi = &$new(4, 'PI'); - $_directive = &$new(5, 'DIRECTIVE'); - $_comment = &$new(6, 'COMMENT'); - $_unknown = &$new(7, 'UNKNOWN'); + $_text = &$new( 0, 'TEXT' ); + $_text_parametrized = &$new( 8, 'TEXT-PARAMETRIZED' ); + $_cdata = &$new( 1, 'CDATA' ); + $_tag = &$new( 2, 'TAG' ); + $_decl = &$new( 3, 'DECL' ); + $_pi = &$new( 4, 'PI' ); + $_directive = &$new( 5, 'DIRECTIVE' ); + $_comment = &$new( 6, 'COMMENT' ); + $_unknown = &$new( 7, 'UNKNOWN' ); } sub to_string { my $this = shift; - return $this->{'name'} + return $this->{'name'}; } sub TEXT { $_text } diff --git a/C4/UsageStats.pm b/C4/UsageStats.pm index 8f55c261bd..a8b1b934f2 100644 --- a/C4/UsageStats.pm +++ b/C4/UsageStats.pm @@ -41,35 +41,35 @@ their structure,... sub BuildReport { my $report; my @libraries; - if( C4::Context->preference('UsageStatsLibrariesInfo') ) { + if ( C4::Context->preference('UsageStatsLibrariesInfo') ) { my $libraries = Koha::Libraries->search; while ( my $library = $libraries->next ) { - push @libraries, { name => $library->branchname, url => $library->branchurl, country => $library->branchcountry, geolocation => $library->geolocation, }; + push @libraries, + { + name => $library->branchname, url => $library->branchurl, country => $library->branchcountry, + geolocation => $library->geolocation, + }; } } $report = { installation => { - koha_id => C4::Context->preference('UsageStatsID') || 0, - name => C4::Context->preference('UsageStatsLibraryName') || q||, - url => C4::Context->preference('UsageStatsLibraryUrl') || q||, - type => C4::Context->preference('UsageStatsLibraryType') || q||, - country => C4::Context->preference('UsageStatsCountry') || q||, + koha_id => C4::Context->preference('UsageStatsID') || 0, + name => C4::Context->preference('UsageStatsLibraryName') || q||, + url => C4::Context->preference('UsageStatsLibraryUrl') || q||, + type => C4::Context->preference('UsageStatsLibraryType') || q||, + country => C4::Context->preference('UsageStatsCountry') || q||, geolocation => C4::Context->preference('UsageStatsGeolocation') || q||, }, libraries => \@libraries, }; # Get database volumetry. - foreach ( - qw/biblio items auth_header old_issues old_reserves borrowers aqorders subscription/ - ) - { + foreach (qw/biblio items auth_header old_issues old_reserves borrowers aqorders subscription/) { $report->{volumetry}{$_} = _count($_); } # Get systempreferences. - foreach ( @{ _shared_preferences() } ) - { + foreach ( @{ _shared_preferences() } ) { $report->{systempreferences}{$_} = C4::Context->preference($_); } return $report; @@ -88,11 +88,11 @@ sub ReportToCommunity { my $json = encode_json($data); my $url = "https://hea.koha-community.org/upload.pl"; - my $ua = LWP::UserAgent->new; + my $ua = LWP::UserAgent->new; my $res = $ua->post( $url, 'Content-type' => 'application/json;charset=utf-8', - Content => $json, + Content => $json, ); my $content = decode_json( $res->decoded_content ); if ( $content->{koha_id} ) { diff --git a/C4/Utils/DataTables/TablesSettings.pm b/C4/Utils/DataTables/TablesSettings.pm index 40fe890160..21a1abb2f1 100644 --- a/C4/Utils/DataTables/TablesSettings.pm +++ b/C4/Utils/DataTables/TablesSettings.pm @@ -19,13 +19,13 @@ C4::Utils::DataTables::TablesSettings - Koha DataTables Settings sub get_yaml { my $yml_path = C4::Context->config('intranetdir') . '/admin/columns_settings.yml'; - my $cache = Koha::Caches->get_instance(); - my $yaml = $cache->get_from_cache('TablesSettingsYaml'); + my $cache = Koha::Caches->get_instance(); + my $yaml = $cache->get_from_cache('TablesSettingsYaml'); unless ($yaml) { $yaml = eval { YAML::XS::LoadFile($yml_path) }; warn "ERROR: the yaml file for DT::TablesSettings is not correctly formatted: $@" - if $@; + if $@; $cache->set_in_cache( 'TablesSettingsYaml', $yaml, { expiry => 3600 } ); } @@ -49,7 +49,7 @@ sub get_columns { while ( my $c = $rs->next ) { my $column = first { $c->columnname eq $_->{columnname} } - @{ $list->{modules}{ $c->module }{ $c->page }{ $c->tablename }{ columns } }; + @{ $list->{modules}{ $c->module }{ $c->page }{ $c->tablename }{columns} }; $column->{is_hidden} = $c->is_hidden; $column->{cannot_be_toggled} = $c->cannot_be_toggled; } @@ -104,21 +104,17 @@ sub get_table_settings { my $table_settings = $list->{modules}->{$module}->{$page}->{$tablename}; return { default_display_length => $rs - ? $rs->default_display_length - : $table_settings->{default_display_length}, + ? $rs->default_display_length + : $table_settings->{default_display_length}, default_sort_order => $rs - ? $rs->default_sort_order - : $table_settings->{default_sort_order}, - default_save_state => $rs - ? $rs->default_save_state - : exists $table_settings->{default_save_state} - ? $table_settings->{default_save_state} - : 1, - default_save_state_search => $rs - ? $rs->default_save_state_search - : exists $table_settings->{default_save_state_search} - ? $table_settings->{default_save_state_search} - : 0, + ? $rs->default_sort_order + : $table_settings->{default_sort_order}, + default_save_state => $rs ? $rs->default_save_state + : exists $table_settings->{default_save_state} ? $table_settings->{default_save_state} + : 1, + default_save_state_search => $rs ? $rs->default_save_state_search + : exists $table_settings->{default_save_state_search} ? $table_settings->{default_save_state_search} + : 0, }; } @@ -130,9 +126,9 @@ sub get_modules { while ( my $c = $rs->next ) { my $column = first { $c->columnname eq $_->{columnname} } - @{ $list->{modules}{ $c->module }{ $c->page }{ $c->tablename }{columns} }; - $column->{is_hidden} = $c->is_hidden; - $column->{cannot_be_toggled} = $c->cannot_be_toggled; + @{ $list->{modules}{ $c->module }{ $c->page }{ $c->tablename }{columns} }; + $column->{is_hidden} = $c->is_hidden; + $column->{cannot_be_toggled} = $c->cannot_be_toggled; $column->{cannot_be_modified} = 0 unless exists $column->{cannot_be_modified}; } @@ -152,10 +148,10 @@ sub update_columns { $schema->resultset('ColumnsSetting')->update_or_create( { - module => $c->{module}, - page => $c->{page}, - tablename => $c->{tablename}, - columnname => $c->{columnname}, + module => $c->{module}, + page => $c->{page}, + tablename => $c->{tablename}, + columnname => $c->{columnname}, is_hidden => $c->{is_hidden}, cannot_be_toggled => $c->{cannot_be_toggled}, } diff --git a/C4/Utils/DataTables/VirtualShelves.pm b/C4/Utils/DataTables/VirtualShelves.pm index 2c4c1628e1..4b578e4f70 100644 --- a/C4/Utils/DataTables/VirtualShelves.pm +++ b/C4/Utils/DataTables/VirtualShelves.pm @@ -5,12 +5,12 @@ use C4::Context; use Koha::Virtualshelves; sub search { - my ( $params ) = @_; + my ($params) = @_; my $shelfname = $params->{shelfname}; - my $count = $params->{count}; - my $owner = $params->{owner}; - my $sortby = $params->{sortby}; - my $public = $params->{public} // 1; + my $count = $params->{count}; + my $owner = $params->{owner}; + my $sortby = $params->{sortby}; + my $public = $params->{public} // 1; $public = $public ? 1 : 0; my $order_by = $params->{order_by}; my $start = $params->{start}; @@ -20,7 +20,7 @@ sub search { # to prevent private lists lack my $loggedinuser = C4::Context->userenv->{'number'} || 0; - my ($recordsTotal, $recordsFiltered); + my ( $recordsTotal, $recordsFiltered ); my $dbh = C4::Context->dbh; @@ -43,13 +43,14 @@ sub search { |; my @args; + # private if ( !$public ) { my $join_vs = q| LEFT JOIN virtualshelfshares sh ON sh.shelfnumber = vs.shelfnumber AND sh.borrowernumber = ? |; - $from .= $join_vs; + $from .= $join_vs; $from_total .= $join_vs; push @args, $loggedinuser; @@ -59,19 +60,19 @@ sub search { if ( defined $shelfname and $shelfname ne '' ) { push @where_strs, 'shelfname LIKE ?'; - push @args, "%$shelfname%"; + push @args, "%$shelfname%"; } if ( defined $owner and $owner ne '' ) { push @where_strs, '( bo.firstname LIKE ? OR bo.surname LIKE ? )'; - push @args, "%$owner%", "%$owner%"; -} + push @args, "%$owner%", "%$owner%"; + } if ( defined $sortby and $sortby ne '' ) { push @where_strs, 'sortfield = ?'; - push @args, $sortby; + push @args, $sortby; } push @where_strs, 'public = ?'; - push @args, $public; + push @args, $public; if ( !$public ) { push @where_strs, '(vs.owner = ? OR sh.borrowernumber = ?)'; @@ -79,8 +80,7 @@ sub search { } my $where; - $where = " WHERE " . join (" AND ", @where_strs) if @where_strs; - + $where = " WHERE " . join( " AND ", @where_strs ) if @where_strs; if ($order_by) { $order_by =~ s|shelfnumber|vs.shelfnumber|; @@ -97,8 +97,10 @@ sub search { } my $limit; + # If length == -1, we want to display all shelves if ( $length > -1 ) { + # In order to avoid sql injection $start =~ s/\D//g; $length =~ s/\D//g; @@ -114,34 +116,34 @@ sub search { " ", $select, $from, - ($where ? $where : ""), + ( $where ? $where : "" ), $group_by, - ($order_by ? $order_by : ""), - ($limit ? $limit : "") + ( $order_by ? $order_by : "" ), + ( $limit ? $limit : "" ) ); my $shelves = $dbh->selectall_arrayref( $query, { Slice => {} }, @args ); # Get the recordsFiltered DataTable variable - $query = "SELECT COUNT(vs.shelfnumber) " . $from_total . ($where ? $where : ""); + $query = "SELECT COUNT(vs.shelfnumber) " . $from_total . ( $where ? $where : "" ); ($recordsFiltered) = $dbh->selectrow_array( $query, undef, @args ); # Get the recordsTotal DataTable variable $query = q|SELECT COUNT(vs.shelfnumber)| . $from_total . q| WHERE public = ?|; $query .= q| AND (vs.owner = ? OR sh.borrowernumber = ?)| if !$public; - @args = !$public ? ( $loggedinuser, $public, $loggedinuser, $loggedinuser ) : ( $public ); - ( $recordsTotal ) = $dbh->selectrow_array( $query, undef, @args ); + @args = !$public ? ( $loggedinuser, $public, $loggedinuser, $loggedinuser ) : ($public); + ($recordsTotal) = $dbh->selectrow_array( $query, undef, @args ); - for my $shelf ( @$shelves ) { + for my $shelf (@$shelves) { my $s = Koha::Virtualshelves->find( $shelf->{shelfnumber} ); - $shelf->{can_manage_shelf} = $s->can_be_managed( $loggedinuser ); - $shelf->{can_delete_shelf} = $s->can_be_deleted( $loggedinuser ); - $shelf->{is_shared} = $s->is_shared; + $shelf->{can_manage_shelf} = $s->can_be_managed($loggedinuser); + $shelf->{can_delete_shelf} = $s->can_be_deleted($loggedinuser); + $shelf->{is_shared} = $s->is_shared; } return { - recordsTotal => $recordsTotal, + recordsTotal => $recordsTotal, recordsFiltered => $recordsFiltered, - shelves => $shelves, - } + shelves => $shelves, + }; } 1; diff --git a/C4/XISBN.pm b/C4/XISBN.pm index 67d89ea96c..343616355e 100644 --- a/C4/XISBN.pm +++ b/C4/XISBN.pm @@ -21,9 +21,9 @@ package C4::XISBN; use Modern::Perl; use XML::Simple; -use C4::Biblio qw(TransformMarcToKoha); -use C4::Koha qw( GetNormalizedISBN ); -use C4::Search qw( new_record_from_zebra ); +use C4::Biblio qw(TransformMarcToKoha); +use C4::Koha qw( GetNormalizedISBN ); +use C4::Search qw( new_record_from_zebra ); use C4::External::Syndetics qw( get_syndetics_editions ); use LWP::UserAgent; @@ -31,12 +31,13 @@ use Koha::Biblios; use Koha::SearchEngine; use Koha::SearchEngine::Search; -our (@ISA, @EXPORT_OK); +our ( @ISA, @EXPORT_OK ); + BEGIN { require Exporter; @ISA = qw(Exporter); @EXPORT_OK = qw( - get_xisbns + get_xisbns ); } @@ -52,20 +53,22 @@ This module provides facilities for retrieving ThingISBN and XISBN content in Ko sub _get_biblio_from_xisbn { my $xisbn = shift; - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; - my $searcher = Koha::SearchEngine::Search->new({index => $Koha::SearchEngine::BIBLIOS_INDEX}); + my $searcher = Koha::SearchEngine::Search->new( { index => $Koha::SearchEngine::BIBLIOS_INDEX } ); my ( $errors, $results, $total_hits ) = $searcher->simple_search_compat( "nb=$xisbn", 0, 1 ); return unless ( !$errors && scalar @$results ); - my $record = C4::Search::new_record_from_zebra( 'biblioserver', $results->[0] ); - my $biblionumber = C4::Biblio::TransformMarcToKoha({ - kohafields => ['biblio.biblionumber'], - record => $record - })->{biblionumber}; + my $record = C4::Search::new_record_from_zebra( 'biblioserver', $results->[0] ); + my $biblionumber = C4::Biblio::TransformMarcToKoha( + { + kohafields => ['biblio.biblionumber'], + record => $record + } + )->{biblionumber}; return unless $biblionumber; - my $biblio = Koha::Biblios->find( $biblionumber ); + my $biblio = Koha::Biblios->find($biblionumber); return unless $biblio; my $isbn = $biblio->biblioitem->isbn; $biblio = $biblio->unblessed; @@ -81,57 +84,55 @@ sub _get_biblio_from_xisbn { sub get_xisbns { my ( $isbn, $biblionumber ) = @_; - my ($response,$thing_response,$syndetics_response,$errors); + my ( $response, $thing_response, $syndetics_response, $errors ); + # THINGISBN if ( C4::Context->preference('ThingISBN') ) { - my $url = "http://www.librarything.com/api/thingISBN/".$isbn; - $thing_response = _get_url($url,'thingisbn'); + my $url = "http://www.librarything.com/api/thingISBN/" . $isbn; + $thing_response = _get_url( $url, 'thingisbn' ); } - if ( C4::Context->preference("SyndeticsEnabled") && C4::Context->preference("SyndeticsEditions") ) { - my $syndetics_preresponse = &get_syndetics_editions($isbn); - my @syndetics_response; - for my $response (@$syndetics_preresponse) { - push @syndetics_response, {content => $response->{a}}; - } - $syndetics_response = {isbn => \@syndetics_response}; - } + if ( C4::Context->preference("SyndeticsEnabled") && C4::Context->preference("SyndeticsEditions") ) { + my $syndetics_preresponse = &get_syndetics_editions($isbn); + my @syndetics_response; + for my $response (@$syndetics_preresponse) { + push @syndetics_response, { content => $response->{a} }; + } + $syndetics_response = { isbn => \@syndetics_response }; + } $response->{isbn} = [ @{ $syndetics_response->{isbn} or [] }, @{ $thing_response->{isbn} or [] } ]; my @xisbns; - my $unique_xisbns; # a hashref + my $unique_xisbns; # a hashref # loop through each ISBN and scope to the local collection - for my $response_data( @{ $response->{ isbn } } ) { + for my $response_data ( @{ $response->{isbn} } ) { next if $unique_xisbns->{ $response_data->{content} }; $unique_xisbns->{ $response_data->{content} }++; - my $xbiblio= _get_biblio_from_xisbn($response_data->{content}); + my $xbiblio = _get_biblio_from_xisbn( $response_data->{content} ); next unless $xbiblio; push @xisbns, $xbiblio if $xbiblio && $xbiblio->{biblionumber} ne $biblionumber; } - if ( wantarray ) { - return (\@xisbns, $errors); - } - else { + if (wantarray) { + return ( \@xisbns, $errors ); + } else { return \@xisbns; } } sub _get_url { - my ($url,$service_type) = @_; - my $ua = LWP::UserAgent->new( - timeout => 2 - ); + my ( $url, $service_type ) = @_; + my $ua = LWP::UserAgent->new( timeout => 2 ); my $response = $ua->get($url); - if ($response->is_success) { + if ( $response->is_success ) { warn "WARNING could not retrieve $service_type $url" unless $response; if ($response) { my $xmlsimple = XML::Simple->new(); - my $content = $xmlsimple->XMLin( - $response->content, - ForceArray => [ qw(isbn) ], - ForceContent => 1, + my $content = $xmlsimple->XMLin( + $response->content, + ForceArray => [qw(isbn)], + ForceContent => 1, ); return $content; } diff --git a/C4/XSLT.pm b/C4/XSLT.pm index a2134225d8..6f7d686d6b 100644 --- a/C4/XSLT.pm +++ b/C4/XSLT.pm @@ -24,7 +24,7 @@ package C4::XSLT; use Modern::Perl; use C4::Context; -use C4::Koha qw( xml_escape ); +use C4::Koha qw( xml_escape ); use C4::Biblio qw( GetAuthorisedValueDesc GetFrameworkCode GetMarcStructure ); use Koha::AuthorisedValues; use Koha::ItemTypes; @@ -33,17 +33,18 @@ use Koha::XSLT::Base; use Koha::Libraries; use Koha::Recalls; -my $engine; #XSLT Handler object +my $engine; #XSLT Handler object + +our ( @ISA, @EXPORT_OK ); -our (@ISA, @EXPORT_OK); BEGIN { require Exporter; - @ISA = qw(Exporter); + @ISA = qw(Exporter); @EXPORT_OK = qw( buildKohaItemsNamespace XSLTParse4Display ); - $engine=Koha::XSLT::Base->new( { do_not_return_source => 1 } ); + $engine = Koha::XSLT::Base->new( { do_not_return_source => 1 } ); } =head1 NAME @@ -65,20 +66,20 @@ The helper function _get_best_default_xslt_filename is used in a unit test. =cut sub _get_best_default_xslt_filename { - my ($htdocs, $theme, $lang, $base_xslfile) = @_; + my ( $htdocs, $theme, $lang, $base_xslfile ) = @_; my @candidates = ( - "$htdocs/$theme/$lang/xslt/${base_xslfile}", # exact match - "$htdocs/$theme/en/xslt/${base_xslfile}", # if not, preferred theme in English - "$htdocs/prog/$lang/xslt/${base_xslfile}", # if not, 'prog' theme in preferred language - "$htdocs/prog/en/xslt/${base_xslfile}", # otherwise, prog theme in English; should always - # exist + "$htdocs/$theme/$lang/xslt/${base_xslfile}", # exact match + "$htdocs/$theme/en/xslt/${base_xslfile}", # if not, preferred theme in English + "$htdocs/prog/$lang/xslt/${base_xslfile}", # if not, 'prog' theme in preferred language + "$htdocs/prog/en/xslt/${base_xslfile}", # otherwise, prog theme in English; should always + # exist ); my $xslfilename; foreach my $filename (@candidates) { $xslfilename = $filename; - if (-f $filename) { - last; # we have a winner! + if ( -f $filename ) { + last; # we have a winner! } } return $xslfilename; @@ -118,9 +119,9 @@ sub get_xslt_sysprefs { } sub get_xsl_filename { - my ( $xslsyspref ) = @_; + my ($xslsyspref) = @_; - my $lang = C4::Languages::getlanguage(); + my $lang = C4::Languages::getlanguage(); my $xslfilename = C4::Context->preference($xslsyspref) || "default"; @@ -128,40 +129,36 @@ sub get_xsl_filename { my ( $htdocs, $theme, $xslfile ); - if ($xslsyspref eq "XSLTDetailsDisplay") { + if ( $xslsyspref eq "XSLTDetailsDisplay" ) { $htdocs = C4::Context->config('intrahtdocs'); $theme = C4::Context->preference("template"); - $xslfile = C4::Context->preference('marcflavour') . - "slim2intranetDetail.xsl"; - } elsif ($xslsyspref eq "XSLTResultsDisplay") { + $xslfile = C4::Context->preference('marcflavour') . "slim2intranetDetail.xsl"; + } elsif ( $xslsyspref eq "XSLTResultsDisplay" ) { $htdocs = C4::Context->config('intrahtdocs'); $theme = C4::Context->preference("template"); - $xslfile = C4::Context->preference('marcflavour') . - "slim2intranetResults.xsl"; - } elsif ($xslsyspref eq "OPACXSLTDetailsDisplay") { + $xslfile = C4::Context->preference('marcflavour') . "slim2intranetResults.xsl"; + } elsif ( $xslsyspref eq "OPACXSLTDetailsDisplay" ) { $htdocs = C4::Context->config('opachtdocs'); $theme = C4::Context->preference("opacthemes"); - $xslfile = C4::Context->preference('marcflavour') . - "slim2OPACDetail.xsl"; - } elsif ($xslsyspref eq "OPACXSLTResultsDisplay") { + $xslfile = C4::Context->preference('marcflavour') . "slim2OPACDetail.xsl"; + } elsif ( $xslsyspref eq "OPACXSLTResultsDisplay" ) { $htdocs = C4::Context->config('opachtdocs'); $theme = C4::Context->preference("opacthemes"); - $xslfile = C4::Context->preference('marcflavour') . - "slim2OPACResults.xsl"; - } elsif ($xslsyspref eq 'XSLTListsDisplay') { + $xslfile = C4::Context->preference('marcflavour') . "slim2OPACResults.xsl"; + } elsif ( $xslsyspref eq 'XSLTListsDisplay' ) { + # Lists default to *Results.xslt $htdocs = C4::Context->config('intrahtdocs'); $theme = C4::Context->preference("template"); - $xslfile = C4::Context->preference('marcflavour') . - "slim2intranetResults.xsl"; - } elsif ($xslsyspref eq 'OPACXSLTListsDisplay') { + $xslfile = C4::Context->preference('marcflavour') . "slim2intranetResults.xsl"; + } elsif ( $xslsyspref eq 'OPACXSLTListsDisplay' ) { + # Lists default to *Results.xslt $htdocs = C4::Context->config('opachtdocs'); $theme = C4::Context->preference("opacthemes"); - $xslfile = C4::Context->preference('marcflavour') . - "slim2OPACResults.xsl"; + $xslfile = C4::Context->preference('marcflavour') . "slim2OPACResults.xsl"; } - $xslfilename = _get_best_default_xslt_filename($htdocs, $theme, $lang, $xslfile); + $xslfilename = _get_best_default_xslt_filename( $htdocs, $theme, $lang, $xslfile ); } if ( $xslfilename =~ m/\{langcode\}/ ) { @@ -172,7 +169,7 @@ sub get_xsl_filename { } sub XSLTParse4Display { - my ( $params ) = @_; + my ($params) = @_; my $biblionumber = $params->{biblionumber}; my $record = $params->{record}; @@ -186,12 +183,12 @@ sub XSLTParse4Display { die "Mandatory \$params->{xsl_syspref} was not provided, called with biblionumber $params->{biblionumber}" if not defined $params->{xsl_syspref}; - my $xslfilename = get_xsl_filename( $xslsyspref); + my $xslfilename = get_xsl_filename($xslsyspref); - my $frameworkcode = GetFrameworkCode($biblionumber) || ''; + my $frameworkcode = GetFrameworkCode($biblionumber) || ''; my $record_processor = Koha::RecordProcessor->new( { - filters => [ 'ExpandCodedFields' ], + filters => ['ExpandCodedFields'], options => { interface => $interface, frameworkcode => $frameworkcode @@ -202,24 +199,27 @@ sub XSLTParse4Display { # grab the XML, run it through our stylesheet, push it out to the browser my $itemsxml; - if ( $xslsyspref eq "OPACXSLTDetailsDisplay" || $xslsyspref eq "XSLTDetailsDisplay" || $xslsyspref eq "XSLTResultsDisplay" ) { - $itemsxml = ""; #We don't use XSLT for items display on these pages + if ( $xslsyspref eq "OPACXSLTDetailsDisplay" + || $xslsyspref eq "XSLTDetailsDisplay" + || $xslsyspref eq "XSLTResultsDisplay" ) + { + $itemsxml = ""; #We don't use XSLT for items display on these pages } else { - $itemsxml = buildKohaItemsNamespace($biblionumber, $hidden_items, $items_rs); + $itemsxml = buildKohaItemsNamespace( $biblionumber, $hidden_items, $items_rs ); } - my $xmlrecord = $record->as_xml(C4::Context->preference('marcflavour')); + my $xmlrecord = $record->as_xml( C4::Context->preference('marcflavour') ); $variables ||= {}; my $biblio; - if ( $interface eq 'opac' && C4::Context->preference('OPACShowOpenURL')) { + if ( $interface eq 'opac' && C4::Context->preference('OPACShowOpenURL') ) { my @biblio_itemtypes; $biblio //= Koha::Biblios->find($biblionumber); - if (C4::Context->preference('item-level_itypes')) { + if ( C4::Context->preference('item-level_itypes') ) { @biblio_itemtypes = $biblio->items->get_column("itype"); } else { push @biblio_itemtypes, $biblio->itemtype; } - my @itypes = split( /\s/, C4::Context->preference('OPACOpenURLItemTypes') ); + my @itypes = split( /\s/, C4::Context->preference('OPACOpenURLItemTypes') ); my %original = (); map { $original{$_} = 1 } @biblio_itemtypes; if ( grep { $original{$_} } @itypes ) { @@ -229,7 +229,7 @@ sub XSLTParse4Display { # embed variables my $varxml = "\n"; - while (my ($key, $value) = each %$variables) { + while ( my ( $key, $value ) = each %$variables ) { $value //= q{}; $varxml .= "$value\n"; } @@ -237,7 +237,7 @@ sub XSLTParse4Display { my $sysxml = get_xslt_sysprefs(); $xmlrecord =~ s/\<\/record\>/$itemsxml$sysxml$varxml\<\/record\>/; - if ($fixamps) { # We need to correct the ampersand entities that Zebra outputs + if ($fixamps) { # We need to correct the ampersand entities that Zebra outputs $xmlrecord =~ s/\&amp;/\&/g; $xmlrecord =~ s/\&\;lt\;/\<\;/g; $xmlrecord =~ s/\&\;gt\;/\>\;/g; @@ -248,7 +248,7 @@ sub XSLTParse4Display { #If the xslt should fail, we will return undef (old behavior was #raw MARC) #Note that we did set do_not_return_source at object construction - return $engine->transform($xmlrecord, $xslfilename ); #file or URL + return $engine->transform( $xmlrecord, $xslfilename ); #file or URL } =head2 buildKohaItemsNamespace @@ -267,13 +267,13 @@ Is only used in this module currently. =cut sub buildKohaItemsNamespace { - my ($biblionumber, $hidden_items, $items_rs) = @_; + my ( $biblionumber, $hidden_items, $items_rs ) = @_; $hidden_items ||= []; my $query = {}; $query = { 'me.itemnumber' => { not_in => $hidden_items } } - if $hidden_items; + if $hidden_items; unless ( $items_rs && ref($items_rs) eq 'Koha::Items' ) { $query->{'me.biblionumber'} = $biblionumber; @@ -282,17 +282,27 @@ sub buildKohaItemsNamespace { my $items = $items_rs->search( $query, { prefetch => [ 'branchtransfers', 'reserves' ] } ); - my $shelflocations = - { map { $_->{authorised_value} => $_->{opac_description} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => "", kohafield => 'items.location' } ) }; - my $ccodes = - { map { $_->{authorised_value} => $_->{opac_description} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => "", kohafield => 'items.ccode' } ) }; + my $shelflocations = { + map { $_->{authorised_value} => $_->{opac_description} } + Koha::AuthorisedValues->get_descriptions_by_koha_field( + { frameworkcode => "", kohafield => 'items.location' } + ) + }; + my $ccodes = { + map { $_->{authorised_value} => $_->{opac_description} } + Koha::AuthorisedValues->get_descriptions_by_koha_field( + { frameworkcode => "", kohafield => 'items.ccode' } + ) + }; - my %branches = map { $_->branchcode => $_->branchname } Koha::Libraries->search({}, { order_by => 'branchname' })->as_list; + my %branches = + map { $_->branchcode => $_->branchname } Koha::Libraries->search( {}, { order_by => 'branchname' } )->as_list; my $itemtypes = { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search->unblessed } }; - my $xml = ''; - my %descs = map { $_->{authorised_value} => $_ } Koha::AuthorisedValues->get_descriptions_by_koha_field( { kohafield => 'items.notforloan' } ); - my $ref_status = C4::Context->preference('Reference_NFL_Statuses') // q{}; # fallback to 1|2 removed + my $xml = ''; + my %descs = map { $_->{authorised_value} => $_ } + Koha::AuthorisedValues->get_descriptions_by_koha_field( { kohafield => 'items.notforloan' } ); + my $ref_status = C4::Context->preference('Reference_NFL_Statuses') // q{}; # fallback to 1|2 removed while ( my $item = $items->next ) { my $status; @@ -300,81 +310,82 @@ sub buildKohaItemsNamespace { my $recalls_count; if ( C4::Context->preference('UseRecalls') ) { - $recalls_count = Koha::Recalls->search({ item_id => $item->itemnumber, status => 'waiting' })->count; + $recalls_count = Koha::Recalls->search( { item_id => $item->itemnumber, status => 'waiting' } )->count; } if ($recalls_count) { + # recalls take priority over holds - $status = 'other'; + $status = 'other'; $substatus = 'Recall waiting'; - } - elsif ( $item->has_pending_hold ) { - $status = 'other'; + } elsif ( $item->has_pending_hold ) { + $status = 'other'; $substatus = 'Pending hold'; - } - elsif ( $item->holds->waiting->count ) { - $status = 'other'; + } elsif ( $item->holds->waiting->count ) { + $status = 'other'; $substatus = 'Hold waiting'; - } - elsif ($item->get_transfer) { - $status = 'other'; + } elsif ( $item->get_transfer ) { + $status = 'other'; $substatus = 'In transit'; - } - elsif ( $item->damaged && !C4::Context->preference('AllowHoldsOnDamagedItems') ) { + } elsif ( $item->damaged && !C4::Context->preference('AllowHoldsOnDamagedItems') ) { $status = 'other'; $substatus = 'Damaged'; - } - elsif ($item->itemlost) { - $status = 'other'; + } elsif ( $item->itemlost ) { + $status = 'other'; $substatus = "Lost"; - } - elsif ( $item->withdrawn) { - $status = 'other'; + } elsif ( $item->withdrawn ) { + $status = 'other'; $substatus = "Withdrawn"; - } - elsif ($item->onloan) { - $status = 'other'; + } elsif ( $item->onloan ) { + $status = 'other'; $substatus = "Checked out"; - } - elsif ( $item->notforloan ) { - $status = $item->notforloan =~ /^($ref_status)$/ + } elsif ( $item->notforloan ) { + $status = + $item->notforloan =~ /^($ref_status)$/ ? "reference" : "reallynotforloan"; - $substatus = exists $descs{$item->notforloan} ? $descs{$item->notforloan}->{opac_description} : "Not for loan"; - } - elsif ( exists $itemtypes->{ $item->effective_itemtype } + $substatus = + exists $descs{ $item->notforloan } ? $descs{ $item->notforloan }->{opac_description} : "Not for loan"; + } elsif ( exists $itemtypes->{ $item->effective_itemtype } && $itemtypes->{ $item->effective_itemtype }->{notforloan} && $itemtypes->{ $item->effective_itemtype }->{notforloan} == 1 ) { - $status = "1" =~ /^($ref_status)$/ + $status = + "1" =~ /^($ref_status)$/ ? "reference" : "reallynotforloan"; $substatus = "Not for loan"; - } - else { + } else { $status = "available"; } - my $homebranch = C4::Koha::xml_escape($branches{$item->homebranch}); - my $holdingbranch = C4::Koha::xml_escape($branches{$item->holdingbranch}); - my $resultbranch = C4::Context->preference('OPACResultsLibrary') eq 'homebranch' ? $homebranch : $holdingbranch; - my $location = C4::Koha::xml_escape($item->location && exists $shelflocations->{$item->location} ? $shelflocations->{$item->location} : $item->location); - my $ccode = C4::Koha::xml_escape($item->ccode && exists $ccodes->{$item->ccode} ? $ccodes->{$item->ccode} : $item->ccode); - my $itemcallnumber = C4::Koha::xml_escape($item->itemcallnumber); - my $stocknumber = C4::Koha::xml_escape($item->stocknumber); + my $homebranch = C4::Koha::xml_escape( $branches{ $item->homebranch } ); + my $holdingbranch = C4::Koha::xml_escape( $branches{ $item->holdingbranch } ); + my $resultbranch = C4::Context->preference('OPACResultsLibrary') eq 'homebranch' ? $homebranch : $holdingbranch; + my $location = C4::Koha::xml_escape( + $item->location && exists $shelflocations->{ $item->location } + ? $shelflocations->{ $item->location } + : $item->location + ); + my $ccode = C4::Koha::xml_escape( $item->ccode + && exists $ccodes->{ $item->ccode } ? $ccodes->{ $item->ccode } : $item->ccode ); + my $itemcallnumber = C4::Koha::xml_escape( $item->itemcallnumber ); + my $stocknumber = C4::Koha::xml_escape( $item->stocknumber ); $xml .= - "" - . "$homebranch" - . "$holdingbranch" - . "$resultbranch" - . "$location" - . "$ccode" - . "".( $status // q{} )."" - . "$substatus" - . "$itemcallnumber" - . "$stocknumber" - . ""; + "" + . "$homebranch" + . "$holdingbranch" + . "$resultbranch" + . "$location" + . "$ccode" + . "" + . ( $status // q{} ) + . "" + . "$substatus" + . "$itemcallnumber" + . "$stocknumber" + . ""; } - $xml = "".$xml.""; + $xml = "" . $xml . ""; return $xml; } diff --git a/Koha/Account.pm b/Koha/Account.pm index 41be5dd8c2..bae3645078 100644 --- a/Koha/Account.pm +++ b/Koha/Account.pm @@ -21,11 +21,11 @@ use Modern::Perl; use Carp; use Data::Dumper qw( Dumper ); -use Try::Tiny qw( catch try ); +use Try::Tiny qw( catch try ); use C4::Letters; -use C4::Log qw( logaction ); -use C4::Stats qw( UpdateStats ); +use C4::Log qw( logaction ); +use C4::Stats qw( UpdateStats ); use C4::Overdues qw(GetFine); use C4::Context; @@ -79,7 +79,7 @@ sub pay { my $note = $params->{note} || q{}; my $library_id = $params->{library_id}; my $lines = $params->{lines}; - my $type = $params->{type} || 'PAYMENT'; + my $type = $params->{type} || 'PAYMENT'; my $payment_type = $params->{payment_type} || undef; my $cash_register = $params->{cash_register}; my $item_id = $params->{item_id}; @@ -98,9 +98,9 @@ sub pay { Koha::Exceptions::Account::InvalidPaymentType->throw( error => 'Invalid payment type' ); } } - my $manager_id = $userenv ? $userenv->{number} : undef; - my $interface = $params ? ( $params->{interface} || C4::Context->interface ) : C4::Context->interface; - my $payment = $self->payin_amount( + my $manager_id = $userenv ? $userenv->{number} : undef; + my $interface = $params ? ( $params->{interface} || C4::Context->interface ) : C4::Context->interface; + my $payment = $self->payin_amount( { interface => $interface, type => $type, @@ -119,30 +119,28 @@ sub pay { # NOTE: Pay historically always applied as much credit as it could to all # existing outstanding debits, whether passed specific debits or otherwise. if ( $payment->amountoutstanding ) { - $payment = - $payment->apply( - { debits => [ $self->outstanding_debits->as_list ] } ); + $payment = $payment->apply( { debits => [ $self->outstanding_debits->as_list ] } ); } - my $patron = Koha::Patrons->find( $self->{patron_id} ); - my @account_offsets = $payment->credit_offsets({ type => 'APPLY' })->as_list; + my $patron = Koha::Patrons->find( $self->{patron_id} ); + my @account_offsets = $payment->credit_offsets( { type => 'APPLY' } )->as_list; if ( C4::Context->preference('UseEmailReceipts') ) { if ( my $letter = C4::Letters::GetPreparedLetter( module => 'circulation', letter_code => uc("ACCOUNT_$type"), message_transport_type => 'email', - lang => $patron->lang, - tables => { - borrowers => $self->{patron_id}, - branches => $library_id, + lang => $patron->lang, + tables => { + borrowers => $self->{patron_id}, + branches => $library_id, }, substitute => { - credit => $payment, + credit => $payment, offsets => \@account_offsets, }, - ) - ) + ) + ) { C4::Letters::EnqueueLetter( { @@ -155,7 +153,7 @@ sub pay { } my $renew_outcomes = []; - for my $message ( @{$payment->object_messages} ) { + for my $message ( @{ $payment->object_messages } ) { push @{$renew_outcomes}, $message->payload; } @@ -201,20 +199,18 @@ sub add_credit { my @mandatory = ( 'interface', 'amount' ); for my $param (@mandatory) { unless ( defined( $params->{$param} ) ) { - Koha::Exceptions::MissingParameter->throw( - error => "The $param parameter is mandatory" ); + Koha::Exceptions::MissingParameter->throw( error => "The $param parameter is mandatory" ); } } # amount should always be passed as a positive value my $amount = $params->{amount} * -1; unless ( $amount < 0 ) { - Koha::Exceptions::Account::AmountNotPositive->throw( - error => 'Debit amount passed is not positive' ); + Koha::Exceptions::Account::AmountNotPositive->throw( error => 'Debit amount passed is not positive' ); } my $description = $params->{description} // q{}; - my $note = $params->{note} // q{}; + my $note = $params->{note} // q{}; my $user_id = $params->{user_id}; my $interface = $params->{interface}; my $library_id = $params->{library_id}; @@ -225,17 +221,17 @@ sub add_credit { my $issue_id = $params->{issue_id}; my $old_issue_id; - if ( $issue_id ) { + if ($issue_id) { my $issue = Koha::Checkouts->find($issue_id); - unless ( $issue ) { + unless ($issue) { my $old_issue = Koha::Old::Checkouts->find($issue_id); - $issue_id = undef; + $issue_id = undef; $old_issue_id = $old_issue->id; } } Koha::Exceptions::Account::RegisterRequired->throw() - if ( C4::Context->preference("UseCashRegisters") + if ( C4::Context->preference("UseCashRegisters") && defined($payment_type) && ( $payment_type eq 'CASH' || $payment_type eq 'SIP00' ) && !defined($cash_register) ); @@ -300,7 +296,7 @@ sub add_credit { action => "add_credit", payload => { type => lc($credit_type), - line => $line->get_from_storage, #TODO Seems unneeded + line => $line->get_from_storage, #TODO Seems unneeded } } ); @@ -328,12 +324,10 @@ sub add_credit { } } ); - } - catch { + } catch { if ( ref($_) eq 'Koha::Exceptions::Object::FKConstraint' ) { if ( $_->broken_fk eq 'credit_type_code' ) { - Koha::Exceptions::Account::UnrecognisedType->throw( - error => 'Type of credit not recognised' ); + Koha::Exceptions::Account::UnrecognisedType->throw( error => 'Type of credit not recognised' ); } } $_->rethrow; @@ -377,23 +371,21 @@ sub payin_amount { my @mandatory = ( 'interface', 'amount', 'type' ); for my $param (@mandatory) { unless ( defined( $params->{$param} ) ) { - Koha::Exceptions::MissingParameter->throw( - error => "The $param parameter is mandatory" ); + Koha::Exceptions::MissingParameter->throw( error => "The $param parameter is mandatory" ); } } # Check for mandatory register Koha::Exceptions::Account::RegisterRequired->throw() - if ( C4::Context->preference("UseCashRegisters") + if ( C4::Context->preference("UseCashRegisters") && defined( $params->{payment_type} ) && ( $params->{payment_type} eq 'CASH' || $params->{payment_type} eq 'SIP00' ) - && !defined($params->{cash_register}) ); + && !defined( $params->{cash_register} ) ); # amount should always be passed as a positive value my $amount = $params->{amount}; unless ( $amount > 0 ) { - Koha::Exceptions::Account::AmountNotPositive->throw( - error => 'Payin amount passed is not positive' ); + Koha::Exceptions::Account::AmountNotPositive->throw( error => 'Payin amount passed is not positive' ); } my $credit; @@ -406,22 +398,14 @@ sub payin_amount { # Offset debts passed first if ( exists( $params->{debits} ) ) { - $credit = $credit->apply( - { - debits => $params->{debits} - } - ); + $credit = $credit->apply( { debits => $params->{debits} } ); } # Offset against remaining balance if AutoReconcile if ( C4::Context->preference("AccountAutoReconcile") && $credit->amountoutstanding != 0 ) { - $credit = $credit->apply( - { - debits => [ $self->outstanding_debits->as_list ] - } - ); + $credit = $credit->apply( { debits => [ $self->outstanding_debits->as_list ] } ); } } ); @@ -475,14 +459,13 @@ sub add_debit { my @mandatory = ( 'interface', 'type', 'amount' ); for my $param (@mandatory) { unless ( defined( $params->{$param} ) ) { - Koha::Exceptions::MissingParameter->throw( - error => "The $param parameter is mandatory" ); + Koha::Exceptions::MissingParameter->throw( error => "The $param parameter is mandatory" ); } } # check for cash register if using cash Koha::Exceptions::Account::RegisterRequired->throw() - if ( C4::Context->preference("UseCashRegisters") + if ( C4::Context->preference("UseCashRegisters") && defined( $params->{transaction_type} ) && ( $params->{transaction_type} eq 'CASH' || $params->{payment_type} eq 'SIP00' ) && !defined( $params->{cash_register} ) ); @@ -490,12 +473,11 @@ sub add_debit { # amount should always be a positive value my $amount = $params->{amount}; unless ( $amount > 0 ) { - Koha::Exceptions::Account::AmountNotPositive->throw( - error => 'Debit amount passed is not positive' ); + Koha::Exceptions::Account::AmountNotPositive->throw( error => 'Debit amount passed is not positive' ); } my $description = $params->{description} // q{}; - my $note = $params->{note} // q{}; + my $note = $params->{note} // q{}; my $user_id = $params->{user_id}; my $interface = $params->{interface}; my $library_id = $params->{library_id}; @@ -506,16 +488,15 @@ sub add_debit { my $issue_id = $params->{issue_id}; my $old_issue_id; - if ( $issue_id ) { + if ($issue_id) { my $issue = Koha::Checkouts->find($issue_id); - unless ( $issue ) { + unless ($issue) { my $old_issue = Koha::Old::Checkouts->find($issue_id); - $issue_id = undef; + $issue_id = undef; $old_issue_id = $old_issue->id; } } - my $line; my $schema = Koha::Database->new->schema; try { @@ -587,14 +568,11 @@ sub add_debit { } } ); - } - catch { + } catch { if ( ref($_) eq 'Koha::Exceptions::Object::FKConstraint' ) { if ( $_->broken_fk eq 'debit_type_code' ) { - Koha::Exceptions::Account::UnrecognisedType->throw( - error => 'Type of debit not recognised' ); - } - else { + Koha::Exceptions::Account::UnrecognisedType->throw( error => 'Type of debit not recognised' ); + } else { $_->rethrow; } } @@ -626,41 +604,38 @@ sub payout_amount { my ( $self, $params ) = @_; # Check for mandatory parameters - my @mandatory = - ( 'interface', 'staff_id', 'branch', 'payout_type', 'amount' ); + my @mandatory = ( 'interface', 'staff_id', 'branch', 'payout_type', 'amount' ); for my $param (@mandatory) { unless ( defined( $params->{$param} ) ) { - Koha::Exceptions::MissingParameter->throw( - error => "The $param parameter is mandatory" ); + Koha::Exceptions::MissingParameter->throw( error => "The $param parameter is mandatory" ); } } # Check for mandatory register Koha::Exceptions::Account::RegisterRequired->throw() - if ( C4::Context->preference("UseCashRegisters") + if ( C4::Context->preference("UseCashRegisters") && ( $params->{payout_type} eq 'CASH' || $params->{payout_type} eq 'SIP00' ) - && !defined($params->{cash_register}) ); + && !defined( $params->{cash_register} ) ); # Amount should always be passed as a positive value my $amount = $params->{amount}; unless ( $amount > 0 ) { - Koha::Exceptions::Account::AmountNotPositive->throw( - error => 'Payout amount passed is not positive' ); + Koha::Exceptions::Account::AmountNotPositive->throw( error => 'Payout amount passed is not positive' ); } # Amount should always be less than or equal to outstanding credit my $outstanding = 0; my $outstanding_credits = - exists( $params->{credits} ) - ? $params->{credits} - : $self->outstanding_credits->as_list; + exists( $params->{credits} ) + ? $params->{credits} + : $self->outstanding_credits->as_list; for my $credit ( @{$outstanding_credits} ) { $outstanding += $credit->amountoutstanding; } $outstanding = $outstanding * -1; - Koha::Exceptions::ParameterTooHigh->throw( error => -"Amount to payout ($amount) is higher than amountoutstanding ($outstanding)" - ) unless ( $outstanding >= $amount ); + Koha::Exceptions::ParameterTooHigh->throw( + error => "Amount to payout ($amount) is higher than amountoutstanding ($outstanding)" ) + unless ( $outstanding >= $amount ); my $payout; my $schema = Koha::Database->new->schema; @@ -764,12 +739,11 @@ Charges can be set as exempt from non-issue by editing the debit type in the Deb sub non_issues_charges { my ($self) = @_; - my @blocking_debit_types = Koha::Account::DebitTypes->search({ restricts_checkouts => 1 }, { columns => 'code' })->get_column('code'); + my @blocking_debit_types = + Koha::Account::DebitTypes->search( { restricts_checkouts => 1 }, { columns => 'code' } )->get_column('code'); return $self->lines->search( - { - debit_type_code => { -in => \@blocking_debit_types } - }, + { debit_type_code => { -in => \@blocking_debit_types } }, )->total_outstanding; } @@ -791,7 +765,6 @@ sub lines { ); } - =head3 credits my $credits = $self->credits; @@ -803,11 +776,7 @@ Return all credits for the user sub credits { my ($self) = @_; - return Koha::Account::Credits->search( - { - borrowernumber => $self->{patron_id} - } - ); + return Koha::Account::Credits->search( { borrowernumber => $self->{patron_id} } ); } =head3 debits @@ -823,7 +792,7 @@ sub debits { return Koha::Account::Debits->search( { - borrowernumber => $self->{patron_id}, + borrowernumber => $self->{patron_id}, } ); } @@ -844,8 +813,8 @@ sub reconcile_balance { my $outstanding_debits = $self->outstanding_debits; my $outstanding_credits = $self->outstanding_credits; - while ( $outstanding_debits->total_outstanding > 0 - and my $credit = $outstanding_credits->next ) + while ( $outstanding_debits->total_outstanding > 0 + and my $credit = $outstanding_credits->next ) { # there's both outstanding debits and credits $credit->apply( { debits => [ $outstanding_debits->as_list ] } ); # applying credit, no special offset diff --git a/Koha/Account/Credits.pm b/Koha/Account/Credits.pm index 75ee4497d3..5d3beb9aa6 100644 --- a/Koha/Account/Credits.pm +++ b/Koha/Account/Credits.pm @@ -41,7 +41,7 @@ Returns a list of credit lines. sub search { my ( $self, $where, $attr ) = @_; - my $rs = $self->SUPER::search({ debit_type_code => undef }); + my $rs = $self->SUPER::search( { debit_type_code => undef } ); return $rs->SUPER::search( $where, $attr ); } diff --git a/Koha/Account/Debits.pm b/Koha/Account/Debits.pm index c6a39a1f9e..8bce81934e 100644 --- a/Koha/Account/Debits.pm +++ b/Koha/Account/Debits.pm @@ -41,7 +41,7 @@ Returns a list of debit lines. sub search { my ( $self, $where, $attr ) = @_; - my $rs = $self->SUPER::search({ credit_type_code => undef }); + my $rs = $self->SUPER::search( { credit_type_code => undef } ); return $rs->SUPER::search( $where, $attr ); } diff --git a/Koha/Account/Line.pm b/Koha/Account/Line.pm index a82ad43414..851ebec755 100644 --- a/Koha/Account/Line.pm +++ b/Koha/Account/Line.pm @@ -50,10 +50,10 @@ Return the patron linked to this account line =cut sub patron { - my ( $self ) = @_; + my ($self) = @_; my $rs = $self->_result->patron; return unless $rs; - return Koha::Patron->_new_from_dbic( $rs ); + return Koha::Patron->_new_from_dbic($rs); } =head3 manager @@ -63,10 +63,10 @@ Return the manager linked to this account line =cut sub manager { - my ( $self ) = @_; + my ($self) = @_; my $rs = $self->_result->manager; return unless $rs; - return Koha::Patron->_new_from_dbic( $rs ); + return Koha::Patron->_new_from_dbic($rs); } =head3 item @@ -76,11 +76,11 @@ Return the item linked to this account line if exists =cut sub item { - my ( $self ) = @_; + my ($self) = @_; my $rs = $self->_result->itemnumber; return unless $rs; require Koha::Item; - return Koha::Item->_new_from_dbic( $rs ); + return Koha::Item->_new_from_dbic($rs); } =head3 checkout @@ -111,7 +111,7 @@ Returns a Koha::Library object representing where the accountline was recorded =cut sub library { - my ( $self ) = @_; + my ($self) = @_; my $rs = $self->_result->library; return unless $rs; return Koha::Library->_new_from_dbic($rs); @@ -124,10 +124,10 @@ Return the credit_type linked to this account line =cut sub credit_type { - my ( $self ) = @_; + my ($self) = @_; my $rs = $self->_result->credit_type_code; return unless $rs; - return Koha::Account::CreditType->_new_from_dbic( $rs ); + return Koha::Account::CreditType->_new_from_dbic($rs); } =head3 debit_type @@ -137,10 +137,10 @@ Return the debit_type linked to this account line =cut sub debit_type { - my ( $self ) = @_; + my ($self) = @_; my $rs = $self->_result->debit_type_code; return unless $rs; - return Koha::Account::DebitType->_new_from_dbic( $rs ); + return Koha::Account::DebitType->_new_from_dbic($rs); } =head3 credit_offsets @@ -153,12 +153,10 @@ sub credit_offsets { my ( $self, $cond, $attr ) = @_; unless ( $self->is_credit ) { - Koha::Exceptions::Account::IsNotCredit->throw( - error => 'Account line ' . $self->id . ' is not a credit' - ); + Koha::Exceptions::Account::IsNotCredit->throw( error => 'Account line ' . $self->id . ' is not a credit' ); } - my $rs = $self->_result->search_related( 'account_offsets_credits', $cond, $attr); + my $rs = $self->_result->search_related( 'account_offsets_credits', $cond, $attr ); return unless $rs; return Koha::Account::Offsets->_new_from_dbic($rs); } @@ -173,12 +171,10 @@ sub debit_offsets { my ( $self, $cond, $attr ) = @_; unless ( $self->is_debit ) { - Koha::Exceptions::Account::IsNotDebit->throw( - error => 'Account line ' . $self->id . ' is not a debit' - ); + Koha::Exceptions::Account::IsNotDebit->throw( error => 'Account line ' . $self->id . ' is not a debit' ); } - my $rs = $self->_result->search_related( 'account_offsets_debits', $cond, $attr); + my $rs = $self->_result->search_related( 'account_offsets_debits', $cond, $attr ); return unless $rs; return Koha::Account::Offsets->_new_from_dbic($rs); } @@ -198,15 +194,11 @@ sub credits { my ( $self, $cond, $attr ) = @_; unless ( $self->is_debit ) { - Koha::Exceptions::Account::IsNotDebit->throw( - error => 'Account line ' . $self->id . ' is not a debit' - ); + Koha::Exceptions::Account::IsNotDebit->throw( error => 'Account line ' . $self->id . ' is not a debit' ); } - my $cond_m = { map { "credit.".$_ => $cond->{$_} } keys %{$cond}}; - my $rs = - $self->_result->search_related('account_offsets_debits') - ->search_related( 'credit', $cond_m, $attr ); + my $cond_m = { map { "credit." . $_ => $cond->{$_} } keys %{$cond} }; + my $rs = $self->_result->search_related('account_offsets_debits')->search_related( 'credit', $cond_m, $attr ); return unless $rs; return Koha::Account::Lines->_new_from_dbic($rs); } @@ -226,15 +218,11 @@ sub debits { my ( $self, $cond, $attr ) = @_; unless ( $self->is_credit ) { - Koha::Exceptions::Account::IsNotCredit->throw( - error => 'Account line ' . $self->id . ' is not a credit' - ); + Koha::Exceptions::Account::IsNotCredit->throw( error => 'Account line ' . $self->id . ' is not a credit' ); } - my $cond_m = { map { "debit.".$_ => $cond->{$_} } keys %{$cond}}; - my $rs = - $self->_result->search_related('account_offsets_credits') - ->search_related( 'debit', $cond_m, $attr ); + my $cond_m = { map { "debit." . $_ => $cond->{$_} } keys %{$cond} }; + my $rs = $self->_result->search_related('account_offsets_credits')->search_related( 'debit', $cond_m, $attr ); return unless $rs; return Koha::Account::Lines->_new_from_dbic($rs); } @@ -253,26 +241,23 @@ as 'void' by updating it's status to "VOID". =cut sub void { - my ($self, $params) = @_; + my ( $self, $params ) = @_; # Make sure it is a credit we are voiding unless ( $self->is_credit ) { - Koha::Exceptions::Account::IsNotCredit->throw( - error => 'Account line ' . $self->id . 'is not a credit' ); + Koha::Exceptions::Account::IsNotCredit->throw( error => 'Account line ' . $self->id . 'is not a credit' ); } # Make sure it is not already voided if ( $self->status && $self->status eq 'VOID' ) { - Koha::Exceptions::Account->throw( - error => 'Account line ' . $self->id . 'is already void' ); + Koha::Exceptions::Account->throw( error => 'Account line ' . $self->id . 'is already void' ); } # Check for mandatory parameters - my @mandatory = ( 'interface' ); + my @mandatory = ('interface'); for my $param (@mandatory) { unless ( defined( $params->{$param} ) ) { - Koha::Exceptions::MissingParameter->throw( - error => "The $param parameter is mandatory" ); + Koha::Exceptions::MissingParameter->throw( error => "The $param parameter is mandatory" ); } } @@ -281,17 +266,14 @@ sub void { my @optional = ( 'staff_id', 'branch' ); for my $param (@optional) { unless ( defined( $params->{$param} ) ) { - Koha::Exceptions::MissingParameter->throw( error => -"The $param parameter is mandatory when interface is set to 'intranet'" - ); + Koha::Exceptions::MissingParameter->throw( + error => "The $param parameter is mandatory when interface is set to 'intranet'" ); } } } # Find any applied offsets for the credit so we may reverse them - my @account_offsets = - Koha::Account::Offsets->search( - { credit_id => $self->id, amount => { '<' => 0 } } )->as_list; + my @account_offsets = Koha::Account::Offsets->search( { credit_id => $self->id, amount => { '<' => 0 } } )->as_list; my $void; $self->_result->result_source->schema->txn_do( @@ -321,21 +303,22 @@ sub void { )->store(); # Link void to payment - $self->set({ - amountoutstanding => $self->amount, - status => 'VOID' - })->store(); + $self->set( + { + amountoutstanding => $self->amount, + status => 'VOID' + } + )->store(); $self->apply( { debits => [$void] } ); # Reverse any applied payments foreach my $account_offset (@account_offsets) { - my $fee_paid = - Koha::Account::Lines->find( $account_offset->debit_id ); + my $fee_paid = Koha::Account::Lines->find( $account_offset->debit_id ); next unless $fee_paid; - my $amount_paid = $account_offset->amount * -1; # amount paid is stored as a negative amount - my $new_amount = $fee_paid->amountoutstanding + $amount_paid; + my $amount_paid = $account_offset->amount * -1; # amount paid is stored as a negative amount + my $new_amount = $fee_paid->amountoutstanding + $amount_paid; $fee_paid->amountoutstanding($new_amount); $fee_paid->store(); @@ -355,8 +338,8 @@ sub void { $self->borrowernumber, Dumper( { - action => 'void_payment', - borrowernumber => $self->borrowernumber, + action => 'void_payment', + borrowernumber => $self->borrowernumber, amount => $self->amount, amountoutstanding => $self->amountoutstanding, description => $self->description, @@ -365,8 +348,7 @@ sub void { note => $self->note, itemnumber => $self->itemnumber, manager_id => $self->manager_id, - offsets => - [ map { $_->unblessed } @account_offsets ], + offsets => [ map { $_->unblessed } @account_offsets ], } ) ); @@ -396,32 +378,27 @@ sub cancel { # Make sure it is a charge we are reducing unless ( $self->is_debit ) { - Koha::Exceptions::Account::IsNotDebit->throw( - error => 'Account line ' . $self->id . 'is not a debit' ); + Koha::Exceptions::Account::IsNotDebit->throw( error => 'Account line ' . $self->id . 'is not a debit' ); } if ( $self->debit_type_code eq 'PAYOUT' ) { - Koha::Exceptions::Account::IsNotDebit->throw( - error => 'Account line ' . $self->id . 'is a payout' ); + Koha::Exceptions::Account::IsNotDebit->throw( error => 'Account line ' . $self->id . 'is a payout' ); } # Make sure it is not already cancelled if ( $self->status && $self->status eq 'CANCELLED' ) { - Koha::Exceptions::Account->throw( - error => 'Account line ' . $self->id . 'is already cancelled' ); + Koha::Exceptions::Account->throw( error => 'Account line ' . $self->id . 'is already cancelled' ); } # Make sure it has not be paid yet if ( $self->amount != $self->amountoutstanding ) { - Koha::Exceptions::Account->throw( - error => 'Account line ' . $self->id . 'is already offset' ); + Koha::Exceptions::Account->throw( error => 'Account line ' . $self->id . 'is already offset' ); } # Check for mandatory parameters my @mandatory = ( 'staff_id', 'branch' ); for my $param (@mandatory) { unless ( defined( $params->{$param} ) ) { - Koha::Exceptions::MissingParameter->throw( - error => "The $param parameter is mandatory" ); + Koha::Exceptions::MissingParameter->throw( error => "The $param parameter is mandatory" ); } } @@ -497,24 +474,20 @@ sub reduce { # Make sure it is a charge we are reducing unless ( $self->is_debit ) { - Koha::Exceptions::Account::IsNotDebit->throw( - error => 'Account line ' . $self->id . 'is not a debit' ); + Koha::Exceptions::Account::IsNotDebit->throw( error => 'Account line ' . $self->id . 'is not a debit' ); } if ( $self->debit_type_code eq 'PAYOUT' ) { - Koha::Exceptions::Account::IsNotDebit->throw( - error => 'Account line ' . $self->id . 'is a payout' ); + Koha::Exceptions::Account::IsNotDebit->throw( error => 'Account line ' . $self->id . 'is a payout' ); } if ( $self->debit_type_code eq 'VOID' ) { - Koha::Exceptions::Account::IsNotDebit->throw( - error => 'Account line ' . $self->id . 'is void' ); + Koha::Exceptions::Account::IsNotDebit->throw( error => 'Account line ' . $self->id . 'is void' ); } # Check for mandatory parameters my @mandatory = ( 'interface', 'reduction_type', 'amount' ); for my $param (@mandatory) { unless ( defined( $params->{$param} ) ) { - Koha::Exceptions::MissingParameter->throw( - error => "The $param parameter is mandatory" ); + Koha::Exceptions::MissingParameter->throw( error => "The $param parameter is mandatory" ); } } @@ -523,28 +496,26 @@ sub reduce { my @optional = ( 'staff_id', 'branch' ); for my $param (@optional) { unless ( defined( $params->{$param} ) ) { - Koha::Exceptions::MissingParameter->throw( error => -"The $param parameter is mandatory when interface is set to 'intranet'" - ); + Koha::Exceptions::MissingParameter->throw( + error => "The $param parameter is mandatory when interface is set to 'intranet'" ); } } } # Make sure the reduction isn't more than the original my $original = $self->amount; - Koha::Exceptions::Account::AmountNotPositive->throw( - error => 'Reduce amount passed is not positive' ) - unless ( $params->{amount} > 0 ); - Koha::Exceptions::ParameterTooHigh->throw( error => -"Amount to reduce ($params->{amount}) is higher than original amount ($original)" - ) unless ( $original >= $params->{amount} ); + Koha::Exceptions::Account::AmountNotPositive->throw( error => 'Reduce amount passed is not positive' ) + unless ( $params->{amount} > 0 ); + Koha::Exceptions::ParameterTooHigh->throw( + error => "Amount to reduce ($params->{amount}) is higher than original amount ($original)" ) + unless ( $original >= $params->{amount} ); my $reduced = - $self->credits( { credit_type_code => [ 'DISCOUNT', 'REFUND' ] } )->total; - Koha::Exceptions::ParameterTooHigh->throw( error => -"Combined reduction ($params->{amount} + $reduced) is higher than original amount (" - . abs($original) - . ")" ) - unless ( $original >= ( $params->{amount} + abs($reduced) ) ); + $self->credits( { credit_type_code => [ 'DISCOUNT', 'REFUND' ] } )->total; + Koha::Exceptions::ParameterTooHigh->throw( + error => "Combined reduction ($params->{amount} + $reduced) is higher than original amount (" + . abs($original) + . ")" ) + unless ( $original >= ( $params->{amount} + abs($reduced) ) ); my $status = { 'REFUND' => 'REFUNDED', 'DISCOUNT' => 'DISCOUNTED' }; @@ -581,8 +552,7 @@ sub reduce { $reduction->apply( { debits => [$self] } ); $reduction->status('APPLIED')->store(); - } - else { + } else { # Zero amount offset used to link original 'debit' to # reduction 'credit' @@ -625,20 +595,17 @@ Applies the credit to a given debits array reference. sub apply { my ( $self, $params ) = @_; - my $debits = $params->{debits}; + my $debits = $params->{debits}; unless ( $self->is_credit ) { - Koha::Exceptions::Account::IsNotCredit->throw( - error => 'Account line ' . $self->id . ' is not a credit' - ); + Koha::Exceptions::Account::IsNotCredit->throw( error => 'Account line ' . $self->id . ' is not a credit' ); } my $available_credit = $self->amountoutstanding * -1; unless ( $available_credit > 0 ) { Koha::Exceptions::Account::NoAvailableCredit->throw( - error => 'Outstanding credit is ' . $available_credit . ' and cannot be applied' - ); + error => 'Outstanding credit is ' . $available_credit . ' and cannot be applied' ); } my $schema = Koha::Database->new->schema; @@ -750,34 +717,29 @@ sub payout { # Make sure it is a credit we are paying out unless ( $self->is_credit ) { - Koha::Exceptions::Account::IsNotCredit->throw( - error => 'Account line ' . $self->id . ' is not a credit' ); + Koha::Exceptions::Account::IsNotCredit->throw( error => 'Account line ' . $self->id . ' is not a credit' ); } # Check for mandatory parameters - my @mandatory = - ( 'interface', 'staff_id', 'branch', 'payout_type', 'amount' ); + my @mandatory = ( 'interface', 'staff_id', 'branch', 'payout_type', 'amount' ); for my $param (@mandatory) { unless ( defined( $params->{$param} ) ) { - Koha::Exceptions::MissingParameter->throw( - error => "The $param parameter is mandatory" ); + Koha::Exceptions::MissingParameter->throw( error => "The $param parameter is mandatory" ); } } # Make sure there is outstanding credit to pay out my $outstanding = -1 * $self->amountoutstanding; - my $amount = - $params->{amount} ? $params->{amount} : $outstanding; - Koha::Exceptions::Account::AmountNotPositive->throw( - error => 'Payout amount passed is not positive' ) - unless ( $amount > 0 ); + my $amount = $params->{amount} ? $params->{amount} : $outstanding; + Koha::Exceptions::Account::AmountNotPositive->throw( error => 'Payout amount passed is not positive' ) + unless ( $amount > 0 ); Koha::Exceptions::ParameterTooHigh->throw( error => "Amount to payout ($amount) is higher than amountoutstanding ($outstanding)" ) - unless ($outstanding >= $amount ); + unless ( $outstanding >= $amount ); # Make sure we record the cash register for cash transactions Koha::Exceptions::Account::RegisterRequired->throw() - if ( C4::Context->preference("UseCashRegisters") + if ( C4::Context->preference("UseCashRegisters") && defined( $params->{payout_type} ) && ( $params->{payout_type} eq 'CASH' || $params->{payout_type} eq 'SIP00' ) && !defined( $params->{cash_register} ) ); @@ -845,31 +807,24 @@ or debits and applied, via an offset, to the corresponding debit or credit. sub adjust { my ( $self, $params ) = @_; - my $amount = $params->{amount}; - my $update_type = $params->{type}; - my $interface = $params->{interface}; + my $amount = $params->{amount}; + my $update_type = $params->{type}; + my $interface = $params->{interface}; - unless ( exists($Koha::Account::Line::allowed_update->{$update_type}) ) { - Koha::Exceptions::Account::UnrecognisedType->throw( - error => 'Update type not recognised' - ); + unless ( exists( $Koha::Account::Line::allowed_update->{$update_type} ) ) { + Koha::Exceptions::Account::UnrecognisedType->throw( error => 'Update type not recognised' ); } my $debit_type_code = $self->debit_type_code; my $account_status = $self->status; unless ( ( - exists( - $Koha::Account::Line::allowed_update->{$update_type} - ->{$debit_type_code} - ) - && ( $Koha::Account::Line::allowed_update->{$update_type} - ->{$debit_type_code} eq $account_status ) + exists( $Koha::Account::Line::allowed_update->{$update_type}->{$debit_type_code} ) + && ( $Koha::Account::Line::allowed_update->{$update_type}->{$debit_type_code} eq $account_status ) + ) ) - ) { - Koha::Exceptions::Account::UnrecognisedType->throw( - error => 'Update type not allowed on this debit_type' ); + Koha::Exceptions::Account::UnrecognisedType->throw( error => 'Update type not allowed on this debit_type' ); } my $schema = Koha::Database->new->schema; @@ -887,14 +842,13 @@ sub adjust { # Catch cases that require patron refunds if ( $new_outstanding < 0 ) { - my $account = - Koha::Patrons->find( $self->borrowernumber )->account; - my $credit = $account->add_credit( + my $account = Koha::Patrons->find( $self->borrowernumber )->account; + my $credit = $account->add_credit( { - amount => $new_outstanding * -1, - type => 'OVERPAYMENT', - interface => $interface, - ( $update_type eq 'overdue_update' ? ( item_id => $self->itemnumber ) : ()), + amount => $new_outstanding * -1, + type => 'OVERPAYMENT', + interface => $interface, + ( $update_type eq 'overdue_update' ? ( item_id => $self->itemnumber ) : () ), } ); $new_outstanding = 0; @@ -920,10 +874,11 @@ sub adjust { if ( C4::Context->preference("FinesLog") ) { logaction( - "FINES", 'UPDATE', #undef becomes UPDATE in UpdateFine + "FINES", 'UPDATE', #undef becomes UPDATE in UpdateFine $self->borrowernumber, Dumper( - { action => $update_type, + { + action => $update_type, borrowernumber => $self->borrowernumber, amount => $amount, description => undef, @@ -1000,15 +955,13 @@ sub to_api_mapping { sub is_renewable { my ($self) = @_; - return ( - $self->amountoutstanding == 0 && - $self->debit_type_code && - $self->debit_type_code eq 'OVERDUE' && - $self->status && - $self->status eq 'UNRETURNED' && - $self->item && - $self->patron - ) ? 1 : 0; + return ( $self->amountoutstanding == 0 + && $self->debit_type_code + && $self->debit_type_code eq 'OVERDUE' + && $self->status + && $self->status eq 'UNRETURNED' + && $self->item + && $self->patron ) ? 1 : 0; } =head3 renew_item @@ -1022,7 +975,7 @@ Caller must call is_renewable before. =cut sub renew_item { - my ($self, $params) = @_; + my ( $self, $params ) = @_; my $outcome = {}; @@ -1033,13 +986,12 @@ sub renew_item { # - There is an interface param passed and it's value is 'opac' if ( - !C4::Context->preference('RenewAccruingItemWhenPaid') || - ( - !C4::Context->preference('RenewAccruingItemInOpac') && - $params->{interface} && - $params->{interface} eq 'opac' + !C4::Context->preference('RenewAccruingItemWhenPaid') + || ( !C4::Context->preference('RenewAccruingItemInOpac') + && $params->{interface} + && $params->{interface} eq 'opac' ) ) - ) { + { return; } @@ -1048,9 +1000,9 @@ sub renew_item { $self->patron, $self->item->checkout ); - if ( $can_renew ) { + if ($can_renew) { my $borrowernumber = $self->patron->borrowernumber; - my $due_date = C4::Circulation::AddRenewal( + my $due_date = C4::Circulation::AddRenewal( { borrowernumber => $borrowernumber, itemnumber => $itemnumber, @@ -1082,54 +1034,59 @@ Specific store method to generate credit number before saving sub store { my ($self) = @_; - my $AutoCreditNumber = C4::Context->preference('AutoCreditNumber'); + my $AutoCreditNumber = C4::Context->preference('AutoCreditNumber'); my $credit_number_enabled = $self->is_credit && $self->credit_type->credit_number_enabled; - if ($AutoCreditNumber && $credit_number_enabled && !$self->in_storage) { - if (defined $self->credit_number) { + if ( $AutoCreditNumber && $credit_number_enabled && !$self->in_storage ) { + if ( defined $self->credit_number ) { Koha::Exceptions::Account->throw('AutoCreditNumber is enabled but credit_number is already defined'); } - my $rs = Koha::Database->new->schema->resultset($self->_type); + my $rs = Koha::Database->new->schema->resultset( $self->_type ); - if ($AutoCreditNumber eq 'incremental') { - my $max = $rs->search({ - credit_number => { -regexp => '^[0-9]+$' } - }, { - select => \'CAST(credit_number AS UNSIGNED)', - as => ['credit_number'], - })->get_column('credit_number')->max; + if ( $AutoCreditNumber eq 'incremental' ) { + my $max = $rs->search( + { credit_number => { -regexp => '^[0-9]+$' } }, + { + select => \'CAST(credit_number AS UNSIGNED)', + as => ['credit_number'], + } + )->get_column('credit_number')->max; $max //= 0; - $self->credit_number($max + 1); - } elsif ($AutoCreditNumber eq 'annual') { - my $now = dt_from_string; - my $prefix = sprintf('%d-', $now->year); - my $max = $rs->search({ - -and => [ - credit_number => { -regexp => '[0-9]{4}$' }, - credit_number => { -like => "$prefix%" }, - ], - })->get_column('credit_number')->max; - $max //= $prefix . '0000'; - my $incr = substr($max, length $prefix); - $self->credit_number(sprintf('%s%04d', $prefix, $incr + 1)); - } elsif ($AutoCreditNumber eq 'branchyyyymmincr') { - my $userenv = C4::Context->userenv; - if ($userenv) { - my $branch = $userenv->{branch}; - my $now = dt_from_string; - my $prefix = sprintf('%s%d%02d', $branch, $now->year, $now->month); - my $pattern = $prefix; - $pattern =~ s/([\?%_])/\\$1/g; - my $max = $rs->search({ + $self->credit_number( $max + 1 ); + } elsif ( $AutoCreditNumber eq 'annual' ) { + my $now = dt_from_string; + my $prefix = sprintf( '%d-', $now->year ); + my $max = $rs->search( + { -and => [ credit_number => { -regexp => '[0-9]{4}$' }, - credit_number => { -like => "$pattern%" }, + credit_number => { -like => "$prefix%" }, ], - })->get_column('credit_number')->max; + } + )->get_column('credit_number')->max; + $max //= $prefix . '0000'; + my $incr = substr( $max, length $prefix ); + $self->credit_number( sprintf( '%s%04d', $prefix, $incr + 1 ) ); + } elsif ( $AutoCreditNumber eq 'branchyyyymmincr' ) { + my $userenv = C4::Context->userenv; + if ($userenv) { + my $branch = $userenv->{branch}; + my $now = dt_from_string; + my $prefix = sprintf( '%s%d%02d', $branch, $now->year, $now->month ); + my $pattern = $prefix; + $pattern =~ s/([\?%_])/\\$1/g; + my $max = $rs->search( + { + -and => [ + credit_number => { -regexp => '[0-9]{4}$' }, + credit_number => { -like => "$pattern%" }, + ], + } + )->get_column('credit_number')->max; $max //= $prefix . '0000'; - my $incr = substr($max, length $prefix); - $self->credit_number(sprintf('%s%04d', $prefix, $incr + 1)); + my $incr = substr( $max, length $prefix ); + $self->credit_number( sprintf( '%s%04d', $prefix, $incr + 1 ) ); } } } diff --git a/Koha/Account/Lines.pm b/Koha/Account/Lines.pm index ab8986db2d..0a9d0eea2e 100644 --- a/Koha/Account/Lines.pm +++ b/Koha/Account/Lines.pm @@ -17,7 +17,6 @@ package Koha::Account::Lines; use Modern::Perl; - use Koha::Database; use Koha::Account::Line; @@ -44,18 +43,18 @@ empty it returns 0. sub total_outstanding { my ($self) = @_; - my $me = $self->_resultset()->current_source_alias . "."; + my $me = $self->_resultset()->current_source_alias . "."; my $lines = $self->search( {}, { - select => [ { sum => $me.'amountoutstanding' } ], + select => [ { sum => $me . 'amountoutstanding' } ], as => ['total_amountoutstanding'], } ); return $lines->count - ? $lines->next->get_column('total_amountoutstanding') + 0 - : 0; + ? $lines->next->get_column('total_amountoutstanding') + 0 + : 0; } =head3 total @@ -72,11 +71,11 @@ sub total { my ( $self, $conditions ) = @_; $conditions //= {}; - my $me = $self->_resultset()->current_source_alias . "."; + my $me = $self->_resultset()->current_source_alias . "."; my $lines = $self->search( $conditions, { - select => [ { sum => $me.'amount' } ], + select => [ { sum => $me . 'amount' } ], as => ['total'] } ); @@ -96,15 +95,15 @@ empty it returns 0. sub credits_total { my ( $self, $conditions ) = @_; - my $me = $self->_resultset()->current_source_alias . "."; - my $local_conditions = { $me.'amount' => { '<' => 0 } }; + my $me = $self->_resultset()->current_source_alias . "."; + my $local_conditions = { $me . 'amount' => { '<' => 0 } }; $conditions //= {}; my $merged_conditions = { %{$conditions}, %{$local_conditions} }; my $lines = $self->search( $merged_conditions, { - select => [ { sum => $me.'amount' } ], + select => [ { sum => $me . 'amount' } ], as => ['total'] } ); @@ -124,15 +123,15 @@ empty it returns 0. sub debits_total { my ( $self, $conditions ) = @_; - my $me = $self->_resultset()->current_source_alias . "."; - my $local_conditions = { $me.'amount' => { '>' => 0 } }; + my $me = $self->_resultset()->current_source_alias . "."; + my $local_conditions = { $me . 'amount' => { '>' => 0 } }; $conditions //= {}; my $merged_conditions = { %{$conditions}, %{$local_conditions} }; my $lines = $self->search( $merged_conditions, { - select => [ { sum => $me.'amount' } ], + select => [ { sum => $me . 'amount' } ], as => ['total'] } ); diff --git a/Koha/Account/Offset.pm b/Koha/Account/Offset.pm index 1ff8c11da2..1427fe51ec 100644 --- a/Koha/Account/Offset.pm +++ b/Koha/Account/Offset.pm @@ -17,7 +17,6 @@ package Koha::Account::Offset; use Modern::Perl; - use Koha::Database; use Koha::Account::Lines; @@ -44,10 +43,10 @@ Returns the related accountline that increased the amount owed by the patron. =cut sub debit { - my ( $self ) = @_; + my ($self) = @_; my $debit_rs = $self->_result->debit; return unless $debit_rs; - return Koha::Account::Line->_new_from_dbic( $debit_rs ); + return Koha::Account::Line->_new_from_dbic($debit_rs); } =head3 credit @@ -59,10 +58,10 @@ Returns the related accountline that decreased the amount owed by the patron. =cut sub credit { - my ( $self ) = @_; + my ($self) = @_; my $credit_rs = $self->_result->credit; return unless $credit_rs; - return Koha::Account::Line->_new_from_dbic( $credit_rs ); + return Koha::Account::Line->_new_from_dbic($credit_rs); } =head3 _type diff --git a/Koha/Account/Offsets.pm b/Koha/Account/Offsets.pm index 224cc5ac31..d0b92bc6e4 100644 --- a/Koha/Account/Offsets.pm +++ b/Koha/Account/Offsets.pm @@ -17,7 +17,6 @@ package Koha::Account::Offsets; use Modern::Perl; - use Koha::Database; use Koha::Account::Offset; @@ -56,8 +55,8 @@ sub total { ); return $offsets->count - ? $offsets->next->get_column('total_amount') + 0 - : 0; + ? $offsets->next->get_column('total_amount') + 0 + : 0; } =head3 filter_by_non_reversible @@ -74,8 +73,8 @@ sub filter_by_non_reversible { my $me = $self->_resultset()->current_source_alias; my $where = { - debit_id => { '!=' => undef }, - credit_id => { '!=' => undef }, + debit_id => { '!=' => undef }, + credit_id => { '!=' => undef }, type => 'APPLY', 'credit.credit_type_code' => [ 'WRITEOFF', 'DISCOUNT', 'CANCELLATION' ], 'credit.status' => [ { '!=' => 'VOID' }, undef ], @@ -100,8 +99,8 @@ sub filter_by_reversible { my $me = $self->_resultset()->current_source_alias; my $where = { - debit_id => { '!=' => undef }, - credit_id => { '!=' => undef }, + debit_id => { '!=' => undef }, + credit_id => { '!=' => undef }, type => 'APPLY', 'credit.credit_type_code' => { -not_in => [ 'WRITEOFF', 'DISCOUNT', 'CANCELLATION' ] }, 'credit.status' => [ { '!=' => 'VOID' }, undef ], diff --git a/Koha/Acquisition/Basket.pm b/Koha/Acquisition/Basket.pm index f22673ef9f..b22aa92440 100644 --- a/Koha/Acquisition/Basket.pm +++ b/Koha/Acquisition/Basket.pm @@ -48,7 +48,7 @@ Returns the vendor sub bookseller { my ($self) = @_; my $bookseller_rs = $self->_result->booksellerid; - return Koha::Acquisition::Bookseller->_new_from_dbic( $bookseller_rs ); + return Koha::Acquisition::Bookseller->_new_from_dbic($bookseller_rs); } =head3 creator @@ -61,9 +61,9 @@ Returns the I for the basket creator. sub creator { my ($self) = @_; - my $borrowernumber = $self->authorisedby; # FIXME missing FK here + my $borrowernumber = $self->authorisedby; # FIXME missing FK here return unless $borrowernumber; - return Koha::Patrons->find( $borrowernumber ); + return Koha::Patrons->find($borrowernumber); } =head3 basket_group @@ -77,7 +77,7 @@ sub basket_group { my $basket_group_rs = $self->_result->basket_group; return unless $basket_group_rs; - return Koha::Acquisition::BasketGroup->_new_from_dbic( $basket_group_rs ); + return Koha::Acquisition::BasketGroup->_new_from_dbic($basket_group_rs); } =head3 orders @@ -93,7 +93,7 @@ sub orders { my ($self) = @_; my $orders_rs = $self->_result->orders; - return Koha::Acquisition::Orders->_new_from_dbic( $orders_rs ); + return Koha::Acquisition::Orders->_new_from_dbic($orders_rs); } =head3 edi_order @@ -127,7 +127,7 @@ Returns C for this basket, falling back to C if uns =cut sub effective_create_items { - my ( $self ) = @_; + my ($self) = @_; return $self->create_items || C4::Context->preference('AcqCreateItem'); } @@ -145,9 +145,9 @@ Return implicit undef if the basket is not closed, or the vendor does not have a =cut sub estimated_delivery_date { - my ( $self ) = @_; + my ($self) = @_; return unless $self->closedate and $self->bookseller->deliverytime; - return dt_from_string($self->closedate)->add( days => $self->bookseller->deliverytime); + return dt_from_string( $self->closedate )->add( days => $self->bookseller->deliverytime ); } =head3 late_since_days @@ -161,9 +161,9 @@ Return implicit undef if the basket is not closed. =cut sub late_since_days { - my ( $self ) = @_; + my ($self) = @_; return unless $self->closedate; - return dt_from_string->delta_days(dt_from_string($self->closedate))->delta_days(); + return dt_from_string->delta_days( dt_from_string( $self->closedate ) )->delta_days(); } =head3 authorizer @@ -176,9 +176,10 @@ Returns the patron who authorized/created this basket. sub authorizer { my ($self) = @_; + # FIXME We should use a DBIC rs, but the FK is missing return unless $self->authorisedby; - return scalar Koha::Patrons->find($self->authorisedby); + return scalar Koha::Patrons->find( $self->authorisedby ); } =head3 is_closed @@ -192,7 +193,7 @@ Returns a boolean value representing if the basket is closed. sub is_closed { my ($self) = @_; - return ($self->closedate) ? 1 : 0; + return ( $self->closedate ) ? 1 : 0; } =head3 close @@ -214,20 +215,18 @@ sub close { $self->_result->result_source->schema->txn_do( sub { - my $open_orders = $self->orders->search( - { - orderstatus => { not_in => [ 'complete', 'cancelled' ] } - } - ); + my $open_orders = $self->orders->search( { orderstatus => { not_in => [ 'complete', 'cancelled' ] } } ); + # Mark open orders as ordered - $open_orders->update({ orderstatus => 'ordered' }, { no_triggers => 1 }); + $open_orders->update( { orderstatus => 'ordered' }, { no_triggers => 1 } ); + # set as closed - $self->set({ closedate => \'NOW()' })->store; + $self->set( { closedate => \'NOW()' } )->store; } ); # Log the closure - if (C4::Context->preference("AcquisitionLog")) { + if ( C4::Context->preference("AcquisitionLog") ) { logaction( 'ACQUISITIONS', 'CLOSE_BASKET', @@ -250,12 +249,13 @@ suitable for API output. sub to_api { my ( $self, $params ) = @_; - my $json_basket = $self->SUPER::to_api( $params ); + my $json_basket = $self->SUPER::to_api($params); return unless $json_basket; - $json_basket->{closed} = ( $self->closedate ) - ? Mojo::JSON->true - : Mojo::JSON->false; + $json_basket->{closed} = + ( $self->closedate ) + ? Mojo::JSON->true + : Mojo::JSON->false; return $json_basket; } diff --git a/Koha/Acquisition/Bookseller.pm b/Koha/Acquisition/Bookseller.pm index dd101e713e..0b8a564767 100644 --- a/Koha/Acquisition/Bookseller.pm +++ b/Koha/Acquisition/Bookseller.pm @@ -43,9 +43,9 @@ Returns the list of baskets for the vendor =cut sub baskets { - my ( $self ) = @_; + my ($self) = @_; my $baskets_rs = $self->_result->aqbaskets; - return Koha::Acquisition::Baskets->_new_from_dbic( $baskets_rs ); + return Koha::Acquisition::Baskets->_new_from_dbic($baskets_rs); } =head3 contacts @@ -60,7 +60,7 @@ Returns the list of contacts for the vendor sub contacts { my ($self) = @_; my $contacts_rs = $self->_result->aqcontacts; - return Koha::Acquisition::Bookseller::Contacts->_new_from_dbic( $contacts_rs ); + return Koha::Acquisition::Bookseller::Contacts->_new_from_dbic($contacts_rs); } =head3 subscriptions @@ -87,7 +87,7 @@ sub subscriptions { =cut sub aliases { - my ($self, $aliases) = @_; + my ( $self, $aliases ) = @_; if ($aliases) { my $schema = $self->_result->result_source->schema; @@ -102,7 +102,7 @@ sub aliases { } my $rs = $self->_result->aqbookseller_aliases; - return Koha::Acquisition::Bookseller::Aliases->_new_from_dbic( $rs ); + return Koha::Acquisition::Bookseller::Aliases->_new_from_dbic($rs); } =head3 interfaces @@ -114,7 +114,7 @@ sub aliases { =cut sub interfaces { - my ($self, $interfaces) = @_; + my ( $self, $interfaces ) = @_; if ($interfaces) { my $schema = $self->_result->result_source->schema; @@ -134,7 +134,7 @@ sub interfaces { } my $rs = $self->_result->aqbookseller_interfaces; - return Koha::Acquisition::Bookseller::Interfaces->_new_from_dbic( $rs ); + return Koha::Acquisition::Bookseller::Interfaces->_new_from_dbic($rs); } =head3 issues @@ -158,11 +158,11 @@ on the API. sub to_api_mapping { return { - listprice => 'list_currency', - invoiceprice => 'invoice_currency', - gstreg => 'gst', - listincgst => 'list_includes_gst', - invoiceincgst => 'invoice_includes_gst' + listprice => 'list_currency', + invoiceprice => 'invoice_currency', + gstreg => 'gst', + listincgst => 'list_includes_gst', + invoiceincgst => 'invoice_includes_gst' }; } diff --git a/Koha/Acquisition/Bookseller/Contact.pm b/Koha/Acquisition/Bookseller/Contact.pm index 1b184fb3dd..b4fa888cc2 100644 --- a/Koha/Acquisition/Bookseller/Contact.pm +++ b/Koha/Acquisition/Bookseller/Contact.pm @@ -4,7 +4,6 @@ use Modern::Perl; use base qw( Koha::Object ); - sub _type { return 'Aqcontact'; } diff --git a/Koha/Acquisition/Bookseller/Contacts.pm b/Koha/Acquisition/Bookseller/Contacts.pm index fa066f45af..7ef20da8ff 100644 --- a/Koha/Acquisition/Bookseller/Contacts.pm +++ b/Koha/Acquisition/Bookseller/Contacts.pm @@ -2,7 +2,6 @@ package Koha::Acquisition::Bookseller::Contacts; use Modern::Perl; - use base qw( Koha::Objects ); use Koha::Acquisition::Bookseller::Contact; diff --git a/Koha/Acquisition/Bookseller/Interface.pm b/Koha/Acquisition/Bookseller/Interface.pm index a7a232f454..90195ab6a2 100644 --- a/Koha/Acquisition/Bookseller/Interface.pm +++ b/Koha/Acquisition/Bookseller/Interface.pm @@ -42,7 +42,7 @@ sub store { my ($self) = @_; if ( $self->password ) { - $self->password(Koha::Encryption->new->encrypt_hex($self->password)); + $self->password( Koha::Encryption->new->encrypt_hex( $self->password ) ); } return $self->SUPER::store; @@ -58,7 +58,7 @@ Decrypt the password and return its plain text form. sub plain_text_password { my ($self) = @_; - return Koha::Encryption->new->decrypt_hex($self->password) + return Koha::Encryption->new->decrypt_hex( $self->password ) if $self->password; } diff --git a/Koha/Acquisition/Currencies.pm b/Koha/Acquisition/Currencies.pm index 42f1d2ff20..76969af6c9 100644 --- a/Koha/Acquisition/Currencies.pm +++ b/Koha/Acquisition/Currencies.pm @@ -17,7 +17,6 @@ package Koha::Acquisition::Currencies; use Modern::Perl; - use Koha::Database; use Koha::Acquisition::Currency; @@ -39,7 +38,7 @@ Koha::Acquisition::Currencies - Koha Acquisition Currency Object set class =cut sub get_active { - my ( $self ) = @_; + my ($self) = @_; return $self->SUPER::search( { active => 1 } )->next; } diff --git a/Koha/Acquisition/Currency.pm b/Koha/Acquisition/Currency.pm index bf1daaf165..6b1ebc0adb 100644 --- a/Koha/Acquisition/Currency.pm +++ b/Koha/Acquisition/Currency.pm @@ -17,7 +17,6 @@ package Koha::Acquisition::Currency; use Modern::Perl; - use Koha::Database; use base qw(Koha::Object); @@ -37,20 +36,23 @@ Koha::Acquisition::Currency - Koha Acquisition Currency Object class =cut sub store { - my ( $self ) = @_; + my ($self) = @_; my $result; - $self->_result->result_source->schema->txn_do( sub { - if ( $self->active ) { - # Remove the active flag from all other active currencies - Koha::Acquisition::Currencies->search( - { - currency => { '!=' => $self->currency }, - active => 1, - } - )->update({ active => 0 }); + $self->_result->result_source->schema->txn_do( + sub { + if ( $self->active ) { + + # Remove the active flag from all other active currencies + Koha::Acquisition::Currencies->search( + { + currency => { '!=' => $self->currency }, + active => 1, + } + )->update( { active => 0 } ); + } + $result = $self->SUPER::store; } - $result = $self->SUPER::store; - }); + ); return $result; } diff --git a/Koha/Acquisition/Fund.pm b/Koha/Acquisition/Fund.pm index 3acc8f99ba..2f90f7dc11 100644 --- a/Koha/Acquisition/Fund.pm +++ b/Koha/Acquisition/Fund.pm @@ -40,9 +40,9 @@ associated to the fund. =cut sub budget { - my ( $self ) = @_; + my ($self) = @_; my $budget_rs = $self->_result->budget; - return Koha::Acquisition::Budget->_new_from_dbic( $budget_rs ); + return Koha::Acquisition::Budget->_new_from_dbic($budget_rs); } =head3 to_api diff --git a/Koha/Acquisition/Invoice.pm b/Koha/Acquisition/Invoice.pm index ae1bf38cb1..e7052adbee 100644 --- a/Koha/Acquisition/Invoice.pm +++ b/Koha/Acquisition/Invoice.pm @@ -41,12 +41,13 @@ suitable for API output. sub to_api { my ( $self, $params ) = @_; - my $json_invoice = $self->SUPER::to_api( $params ); + my $json_invoice = $self->SUPER::to_api($params); return unless $json_invoice; - $json_invoice->{closed} = ( $self->closedate ) - ? Mojo::JSON->true - : Mojo::JSON->false; + $json_invoice->{closed} = + ( $self->closedate ) + ? Mojo::JSON->true + : Mojo::JSON->false; return $json_invoice; } diff --git a/Koha/Acquisition/Invoice/Adjustment.pm b/Koha/Acquisition/Invoice/Adjustment.pm index e0f1db3d0f..bc86b190c6 100644 --- a/Koha/Acquisition/Invoice/Adjustment.pm +++ b/Koha/Acquisition/Invoice/Adjustment.pm @@ -17,7 +17,6 @@ package Koha::Acquisition::Invoice::Adjustment; use Modern::Perl; - use Koha::Database; use Koha::Acquisition::Invoices; use Koha::Acquisition::Funds; @@ -43,9 +42,9 @@ Return the invoice for this adjustment =cut sub invoice { - my ( $self ) = @_; + my ($self) = @_; my $invoice_rs = $self->_result->invoiceid; - return Koha::Acquisition::Invoice->_new_from_dbic( $invoice_rs ); + return Koha::Acquisition::Invoice->_new_from_dbic($invoice_rs); } =head3 fund @@ -57,10 +56,10 @@ Return the fund for this adjustment =cut sub fund { - my ( $self ) = @_; + my ($self) = @_; my $fund_rs = $self->_result->budget; return unless $fund_rs; - return Koha::Acquisition::Fund->_new_from_dbic( $fund_rs ); + return Koha::Acquisition::Fund->_new_from_dbic($fund_rs); } =head3 type diff --git a/Koha/Acquisition/Invoice/Adjustments.pm b/Koha/Acquisition/Invoice/Adjustments.pm index f45f12b79e..fc524e6375 100644 --- a/Koha/Acquisition/Invoice/Adjustments.pm +++ b/Koha/Acquisition/Invoice/Adjustments.pm @@ -18,7 +18,6 @@ package Koha::Acquisition::Invoice::Adjustments; use Modern::Perl; use Koha::Acquisition::Invoice::Adjustment; - use Koha::Database; use Koha::Rating; diff --git a/Koha/Acquisition/Order.pm b/Koha/Acquisition/Order.pm index b8399e3524..289e4a3115 100644 --- a/Koha/Acquisition/Order.pm +++ b/Koha/Acquisition/Order.pm @@ -60,7 +60,7 @@ sub new { my @columns = $schema->source('Aqorder')->columns; my $values = - { map { exists $params->{$_} ? ( $_ => $params->{$_} ) : () } @columns }; + { map { exists $params->{$_} ? ( $_ => $params->{$_} ) : () } @columns }; return $self->SUPER::new($values); } @@ -73,33 +73,36 @@ Overloaded I method for backwards compatibility. sub store { my ($self) = @_; - my $schema = Koha::Database->new->schema; + my $schema = Koha::Database->new->schema; + # Override quantity for standing orders $self->quantity(1) if ( $self->basketno && $schema->resultset('Aqbasket')->find( $self->basketno )->is_standing ); # if these parameters are missing, we can't continue for my $key (qw( basketno quantity biblionumber budget_id )) { - next if $key eq 'biblionumber' && ($self->orderstatus // q{}) eq 'cancelled'; # cancelled order might have biblionumber NULL + next + if $key eq 'biblionumber' + && ( $self->orderstatus // q{} ) eq 'cancelled'; # cancelled order might have biblionumber NULL croak "Cannot insert order: Mandatory parameter $key is missing" - unless $self->$key; + unless $self->$key; } - if (not defined $self->{created_by}) { + if ( not defined $self->{created_by} ) { my $userenv = C4::Context->userenv; if ($userenv) { - $self->created_by($userenv->{number}); + $self->created_by( $userenv->{number} ); } } - $self->quantityreceived(0) unless $self->quantityreceived; + $self->quantityreceived(0) unless $self->quantityreceived; $self->entrydate(dt_from_string) unless $self->entrydate; $self->ordernumber(undef) unless $self->ordernumber; - $self = $self->SUPER::store( $self ); + $self = $self->SUPER::store($self); unless ( $self->parent_ordernumber ) { $self->set( { parent_ordernumber => $self->ordernumber } ); - $self = $self->SUPER::store( $self ); + $self = $self->SUPER::store($self); } return $self; @@ -126,7 +129,7 @@ so the caller can take appropriate actions. =cut sub cancel { - my ($self, $params) = @_; + my ( $self, $params ) = @_; my $delete_biblio = $params->{delete_biblio}; my $reason = $params->{reason}; @@ -135,18 +138,18 @@ sub cancel { my $items = $self->items; while ( my $item = $items->next ) { my $deleted = $item->safe_delete; - unless ( $deleted ) { + unless ($deleted) { $self->add_message( { message => 'error_delitem', - payload => { item => $item, reason => @{$deleted->messages}[0]->message } + payload => { item => $item, reason => @{ $deleted->messages }[0]->message } } ); } } # If ordered from a suggestion, revert the suggestion status to ACCEPTED - my $suggestion = Koha::Suggestions->find({ biblionumber => $self->biblionumber, status => "ORDERED" }); + my $suggestion = Koha::Suggestions->find( { biblionumber => $self->biblionumber, status => "ORDERED" } ); if ( $suggestion and $suggestion->id ) { ModSuggestion( { @@ -160,13 +163,9 @@ sub cancel { my $biblio = $self->biblio; if ( $biblio and $delete_biblio ) { - if ( - $biblio->uncancelled_orders->search( - { ordernumber => { '!=' => $self->ordernumber } } - )->count == 0 + if ( $biblio->uncancelled_orders->search( { ordernumber => { '!=' => $self->ordernumber } } )->count == 0 and $biblio->subscriptions->count == 0 - and $biblio->items->count == 0 - ) + and $biblio->items->count == 0 ) { my $error = DelBiblio( $biblio->id ); @@ -176,21 +175,16 @@ sub cancel { payload => { biblio => $biblio, reason => $error } } ) if $error; - $self->biblionumber(undef) unless $error; # constraint cleared biblionumber in db already - } - else { + $self->biblionumber(undef) unless $error; # constraint cleared biblionumber in db already + } else { my $message; - if ( $biblio->uncancelled_orders->search( - { ordernumber => { '!=' => $self->ordernumber } } - )->count > 0 ) { + if ( $biblio->uncancelled_orders->search( { ordernumber => { '!=' => $self->ordernumber } } )->count > 0 ) { $message = 'error_delbiblio_uncancelled_orders'; - } - elsif ( $biblio->subscriptions->count > 0 ) { + } elsif ( $biblio->subscriptions->count > 0 ) { $message = 'error_delbiblio_subscriptions'; - } - else { # $biblio->items->count > 0 + } else { # $biblio->items->count > 0 $message = 'error_delbiblio_items'; } @@ -224,11 +218,11 @@ Link an item to this order. =cut sub add_item { - my ( $self, $itemnumber ) = @_; + my ( $self, $itemnumber ) = @_; my $schema = Koha::Database->new->schema; - my $rs = $schema->resultset('AqordersItem'); - $rs->create({ ordernumber => $self->ordernumber, itemnumber => $itemnumber }); + my $rs = $schema->resultset('AqordersItem'); + $rs->create( { ordernumber => $self->ordernumber, itemnumber => $itemnumber } ); } =head3 basket @@ -241,9 +235,9 @@ to the order. =cut sub basket { - my ( $self ) = @_; + my ($self) = @_; my $basket_rs = $self->_result->basket; - return Koha::Acquisition::Basket->_new_from_dbic( $basket_rs ); + return Koha::Acquisition::Basket->_new_from_dbic($basket_rs); } =head3 fund @@ -256,9 +250,9 @@ associated to the order. =cut sub fund { - my ( $self ) = @_; + my ($self) = @_; my $fund_rs = $self->_result->fund; - return Koha::Acquisition::Fund->_new_from_dbic( $fund_rs ); + return Koha::Acquisition::Fund->_new_from_dbic($fund_rs); } =head3 invoice @@ -273,10 +267,10 @@ It returns B if no linked invoice is found. =cut sub invoice { - my ( $self ) = @_; + my ($self) = @_; my $invoice_rs = $self->_result->invoice; return unless $invoice_rs; - return Koha::Acquisition::Invoice->_new_from_dbic( $invoice_rs ); + return Koha::Acquisition::Invoice->_new_from_dbic($invoice_rs); } =head3 subscription @@ -291,10 +285,10 @@ It returns B if no linked subscription is found. =cut sub subscription { - my ( $self ) = @_; + my ($self) = @_; my $subscription_rs = $self->_result->subscription; return unless $subscription_rs; - return Koha::Subscription->_new_from_dbic( $subscription_rs ); + return Koha::Subscription->_new_from_dbic($subscription_rs); } =head3 current_item_level_holds @@ -317,13 +311,7 @@ sub current_item_level_holds { return Koha::Holds->new->empty; } - return $biblio->current_holds->search( - { - itemnumber => { - -in => \@item_numbers - } - } - ); + return $biblio->current_holds->search( { itemnumber => { -in => \@item_numbers } } ); } =head3 items @@ -335,12 +323,13 @@ Returns the items associated to the order. =cut sub items { - my ( $self ) = @_; + my ($self) = @_; + # aqorders_items is not a join table # There is no FK on items (may have been deleted) - my $items_rs = $self->_result->aqorders_items; - my @itemnumbers = $items_rs->get_column( 'itemnumber' )->all; - return Koha::Items->search({ itemnumber => \@itemnumbers }); + my $items_rs = $self->_result->aqorders_items; + my @itemnumbers = $items_rs->get_column('itemnumber')->all; + return Koha::Items->search( { itemnumber => \@itemnumbers } ); } =head3 biblio @@ -352,10 +341,10 @@ Returns the bibliographic record associated to the order =cut sub biblio { - my ( $self ) = @_; - my $biblio_rs= $self->_result->biblio; + my ($self) = @_; + my $biblio_rs = $self->_result->biblio; return unless $biblio_rs; - return Koha::Biblio->_new_from_dbic( $biblio_rs ); + return Koha::Biblio->_new_from_dbic($biblio_rs); } =head3 claims @@ -367,9 +356,9 @@ Return the claims history for this order =cut sub claims { - my ( $self ) = @_; + my ($self) = @_; my $claims_rs = $self->_result->aqorders_claims; - return Koha::Acquisition::Order::Claims->_new_from_dbic( $claims_rs ); + return Koha::Acquisition::Order::Claims->_new_from_dbic($claims_rs); } =head3 claim @@ -381,8 +370,8 @@ Do claim for this order =cut sub claim { - my ( $self ) = @_; - my $claim_rs = $self->_result->create_related('aqorders_claims', {}); + my ($self) = @_; + my $claim_rs = $self->_result->create_related( 'aqorders_claims', {} ); return Koha::Acquisition::Order::Claim->_new_from_dbic($claim_rs); } @@ -395,7 +384,7 @@ This is the equivalent of $order->claims->count. Keeping it for retrocompatibilt =cut sub claims_count { - my ( $self ) = @_; + my ($self) = @_; return $self->claims->count; } @@ -408,7 +397,7 @@ This is the equivalent of $order->claims->last->claimed_on. Keeping it for retro =cut sub claimed_date { - my ( $self ) = @_; + my ($self) = @_; my $last_claim = $self->claims->last; return unless $last_claim; return $last_claim->claimed_on; @@ -423,10 +412,10 @@ Retrieves patron that created this order. =cut sub creator { - my ( $self ) = @_; + my ($self) = @_; my $creator_rs = $self->_result->creator; return unless $creator_rs; - return Koha::Patron->_new_from_dbic( $creator_rs ); + return Koha::Patron->_new_from_dbic($creator_rs); } =head3 duplicate_to @@ -456,7 +445,7 @@ sub duplicate_to { cancellationreason parent_ordernumber ) - ) + ) { undef $order_info->{$field}; } @@ -469,11 +458,12 @@ sub duplicate_to { my $userenv = C4::Context->userenv; $order_info->{created_by} = $userenv->{number}; - $order_info->{basketno} = $basket->basketno; + $order_info->{basketno} = $basket->basketno; $new_order = Koha::Acquisition::Order->new($order_info)->store; - if ( ! $self->subscriptionid && $self->basket->effective_create_items eq 'ordering') { # Do copy items if not a subscription order AND if items are created on ordering + if ( !$self->subscriptionid && $self->basket->effective_create_items eq 'ordering' ) + { # Do copy items if not a subscription order AND if items are created on ordering my $items = $self->items; while ( my ($item) = $items->next ) { my $item_info = $item->unblessed; @@ -515,45 +505,56 @@ sub populate_with_prices_for_ordering { $discount /= 100 if $discount > 1; if ( $bookseller->listincgst ) { + # The user entered the prices tax included - $self->unitprice($self->unitprice + 0); - $self->unitprice_tax_included($self->unitprice); - $self->rrp_tax_included($self->rrp); + $self->unitprice( $self->unitprice + 0 ); + $self->unitprice_tax_included( $self->unitprice ); + $self->rrp_tax_included( $self->rrp ); # price tax excluded = price tax included / ( 1 + tax rate ) $self->unitprice_tax_excluded( $self->unitprice_tax_included / ( 1 + $self->tax_rate_on_ordering ) ); $self->rrp_tax_excluded( $self->rrp_tax_included / ( 1 + $self->tax_rate_on_ordering ) ); # ecost tax included = rrp tax included ( 1 - discount ) - $self->ecost_tax_included($self->rrp_tax_included * ( 1 - $discount )); + $self->ecost_tax_included( $self->rrp_tax_included * ( 1 - $discount ) ); # ecost tax excluded = rrp tax excluded * ( 1 - discount ) - $self->ecost_tax_excluded($self->rrp_tax_excluded * ( 1 - $discount )); + $self->ecost_tax_excluded( $self->rrp_tax_excluded * ( 1 - $discount ) ); # tax value = quantity * ecost tax excluded * tax rate # we should use the unitprice if included - my $cost_tax_included = $self->unitprice_tax_included == 0 ? $self->ecost_tax_included : $self->unitprice_tax_included; - my $cost_tax_excluded = $self->unitprice_tax_excluded == 0 ? $self->ecost_tax_excluded : $self->unitprice_tax_excluded; - $self->tax_value_on_ordering( ( C4::Acquisition::get_rounded_price($cost_tax_included) - C4::Acquisition::get_rounded_price($cost_tax_excluded) ) * $self->quantity ); + my $cost_tax_included = + $self->unitprice_tax_included == 0 ? $self->ecost_tax_included : $self->unitprice_tax_included; + my $cost_tax_excluded = + $self->unitprice_tax_excluded == 0 ? $self->ecost_tax_excluded : $self->unitprice_tax_excluded; + $self->tax_value_on_ordering( + ( + C4::Acquisition::get_rounded_price($cost_tax_included) - + C4::Acquisition::get_rounded_price($cost_tax_excluded) + ) * $self->quantity + ); } else { + # The user entered the prices tax excluded - $self->unitprice_tax_excluded($self->unitprice); - $self->rrp_tax_excluded($self->rrp); + $self->unitprice_tax_excluded( $self->unitprice ); + $self->rrp_tax_excluded( $self->rrp ); # price tax included = price tax excluded * ( 1 - tax rate ) - $self->unitprice_tax_included($self->unitprice_tax_excluded * ( 1 + $self->tax_rate_on_ordering )); - $self->rrp_tax_included($self->rrp_tax_excluded * ( 1 + $self->tax_rate_on_ordering )); + $self->unitprice_tax_included( $self->unitprice_tax_excluded * ( 1 + $self->tax_rate_on_ordering ) ); + $self->rrp_tax_included( $self->rrp_tax_excluded * ( 1 + $self->tax_rate_on_ordering ) ); # ecost tax excluded = rrp tax excluded * ( 1 - discount ) - $self->ecost_tax_excluded($self->rrp_tax_excluded * ( 1 - $discount )); + $self->ecost_tax_excluded( $self->rrp_tax_excluded * ( 1 - $discount ) ); # ecost tax included = rrp tax excluded * ( 1 + tax rate ) * ( 1 - discount ) = ecost tax excluded * ( 1 + tax rate ) - $self->ecost_tax_included($self->ecost_tax_excluded * ( 1 + $self->tax_rate_on_ordering )); + $self->ecost_tax_included( $self->ecost_tax_excluded * ( 1 + $self->tax_rate_on_ordering ) ); # tax value = quantity * ecost tax included * tax rate # we should use the unitprice if included - my $cost_tax_excluded = $self->unitprice_tax_excluded == 0 ? $self->ecost_tax_excluded : $self->unitprice_tax_excluded; - $self->tax_value_on_ordering($self->quantity * C4::Acquisition::get_rounded_price($cost_tax_excluded) * $self->tax_rate_on_ordering); + my $cost_tax_excluded = + $self->unitprice_tax_excluded == 0 ? $self->ecost_tax_excluded : $self->unitprice_tax_excluded; + $self->tax_value_on_ordering( + $self->quantity * C4::Acquisition::get_rounded_price($cost_tax_excluded) * $self->tax_rate_on_ordering ); } } @@ -584,35 +585,41 @@ sub populate_with_prices_for_receiving { my $discount = $self->discount || 0; $discount /= 100 if $discount > 1; - if ($bookseller->invoiceincgst) { + if ( $bookseller->invoiceincgst ) { + # Trick for unitprice. If the unit price rounded value is the same as the ecost rounded value # we need to keep the exact ecost value - if ( Koha::Number::Price->new( $self->unitprice )->round == Koha::Number::Price->new( $self->ecost_tax_included )->round ) { - $self->unitprice($self->ecost_tax_included); + if ( Koha::Number::Price->new( $self->unitprice )->round == + Koha::Number::Price->new( $self->ecost_tax_included )->round ) + { + $self->unitprice( $self->ecost_tax_included ); } # The user entered the unit price tax included - $self->unitprice_tax_included($self->unitprice); + $self->unitprice_tax_included( $self->unitprice ); # unit price tax excluded = unit price tax included / ( 1 + tax rate ) - $self->unitprice_tax_excluded($self->unitprice_tax_included / ( 1 + $self->tax_rate_on_receiving )); + $self->unitprice_tax_excluded( $self->unitprice_tax_included / ( 1 + $self->tax_rate_on_receiving ) ); } else { + # Trick for unitprice. If the unit price rounded value is the same as the ecost rounded value # we need to keep the exact ecost value - if ( Koha::Number::Price->new($self->unitprice)->round == Koha::Number::Price->new($self->ecost_tax_excluded)->round ) { - $self->unitprice($self->ecost_tax_excluded); + if ( Koha::Number::Price->new( $self->unitprice )->round == + Koha::Number::Price->new( $self->ecost_tax_excluded )->round ) + { + $self->unitprice( $self->ecost_tax_excluded ); } # The user entered the unit price tax excluded - $self->unitprice_tax_excluded($self->unitprice); - + $self->unitprice_tax_excluded( $self->unitprice ); # unit price tax included = unit price tax included * ( 1 + tax rate ) - $self->unitprice_tax_included($self->unitprice_tax_excluded * ( 1 + $self->tax_rate_on_receiving )); + $self->unitprice_tax_included( $self->unitprice_tax_excluded * ( 1 + $self->tax_rate_on_receiving ) ); } # tax value = quantity * unit price tax excluded * tax rate - $self->tax_value_on_receiving($self->quantity * C4::Acquisition::get_rounded_price($self->unitprice_tax_excluded) * $self->tax_rate_on_receiving); + $self->tax_value_on_receiving( $self->quantity * + C4::Acquisition::get_rounded_price( $self->unitprice_tax_excluded ) * $self->tax_rate_on_receiving ); } =head3 to_api_mapping @@ -628,7 +635,7 @@ sub to_api_mapping { biblionumber => 'biblio_id', deleted_biblionumber => 'deleted_biblio_id', budget_id => 'fund_id', - budgetdate => undef, # unused + budgetdate => undef, # unused cancellationreason => 'cancellation_reason', claimed_date => 'last_claim_date', datecancellationprinted => 'cancellation_date', @@ -637,7 +644,7 @@ sub to_api_mapping { entrydate => 'entry_date', freight => 'shipping_cost', invoiceid => 'invoice_id', - line_item_id => undef, # EDIFACT related + line_item_id => undef, # EDIFACT related listprice => 'list_price', order_internalnote => 'internal_note', order_vendornote => 'vendor_note', @@ -651,11 +658,11 @@ sub to_api_mapping { sort2 => 'statistics_2', sort2_authcat => 'statistics_2_authcat', subscriptionid => 'subscription_id', - suppliers_reference_number => undef, # EDIFACT related - suppliers_reference_qualifier => undef, # EDIFACT related - suppliers_report => undef, # EDIFACT related - tax_rate_bak => undef, # unused - tax_value_bak => undef, # unused + suppliers_reference_number => undef, # EDIFACT related + suppliers_reference_qualifier => undef, # EDIFACT related + suppliers_report => undef, # EDIFACT related + tax_rate_bak => undef, # unused + tax_value_bak => undef, # unused uncertainprice => 'uncertain_price', unitprice => 'unit_price', unitprice_tax_excluded => 'unit_price_tax_excluded', diff --git a/Koha/Acquisition/Order/Claim.pm b/Koha/Acquisition/Order/Claim.pm index 902283080d..37d028a83a 100644 --- a/Koha/Acquisition/Order/Claim.pm +++ b/Koha/Acquisition/Order/Claim.pm @@ -17,7 +17,6 @@ package Koha::Acquisition::Order::Claim; use Modern::Perl; - use Koha::Database; use base qw(Koha::Object); diff --git a/Koha/Acquisition/Order/Claims.pm b/Koha/Acquisition/Order/Claims.pm index 3190733652..eef991990e 100644 --- a/Koha/Acquisition/Order/Claims.pm +++ b/Koha/Acquisition/Order/Claims.pm @@ -17,7 +17,6 @@ package Koha::Acquisition::Order::Claims; use Modern::Perl; - use Koha::Database; use Koha::Acquisition::Order::Claim; diff --git a/Koha/Acquisition/Orders.pm b/Koha/Acquisition/Orders.pm index 0911981cd7..c274e4b72a 100644 --- a/Koha/Acquisition/Orders.pm +++ b/Koha/Acquisition/Orders.pm @@ -17,7 +17,6 @@ package Koha::Acquisition::Orders; use Modern::Perl; - use Koha::Database; use Koha::DateUtils qw( dt_from_string ); @@ -60,32 +59,36 @@ $params can be: sub filter_by_lates { my ( $self, $params ) = @_; - my $delay = $params->{delay}; + my $delay = $params->{delay}; my $bookseller_id = $params->{bookseller_id}; + # my $branchcode = $params->{branchcode}; # FIXME do we really need this my $estimated_from = $params->{estimated_from}; - my $estimated_to = $params->{estimated_to}; - my $dtf = Koha::Database->new->schema->storage->datetime_parser; + my $estimated_to = $params->{estimated_to}; + my $dtf = Koha::Database->new->schema->storage->datetime_parser; my @delivery_time_conditions; - my $date_add = "DATE_ADD(basketno.closedate, INTERVAL COALESCE(booksellerid.deliverytime, booksellerid.deliverytime, 0) day)"; + my $date_add = + "DATE_ADD(basketno.closedate, INTERVAL COALESCE(booksellerid.deliverytime, booksellerid.deliverytime, 0) day)"; my @estimated_delivery_time_conditions; if ( defined $estimated_from or defined $estimated_to ) { - push @delivery_time_conditions, \[ "$date_add IS NOT NULL" ]; - push @delivery_time_conditions, \[ "estimated_delivery_date IS NULL" ]; - push @estimated_delivery_time_conditions, \[ "estimated_delivery_date IS NOT NULL" ]; + push @delivery_time_conditions, \["$date_add IS NOT NULL"]; + push @delivery_time_conditions, \["estimated_delivery_date IS NULL"]; + push @estimated_delivery_time_conditions, \["estimated_delivery_date IS NOT NULL"]; } if ( defined $estimated_from ) { push @delivery_time_conditions, \[ "$date_add >= ?", $dtf->format_date($estimated_from) ]; - push @estimated_delivery_time_conditions, \[ "estimated_delivery_date >= ?", $dtf->format_date($estimated_from) ]; + push @estimated_delivery_time_conditions, + \[ "estimated_delivery_date >= ?", $dtf->format_date($estimated_from) ]; } if ( defined $estimated_to ) { - push @delivery_time_conditions, \[ "$date_add <= ?", $dtf->format_date($estimated_to) ]; + push @delivery_time_conditions, \[ "$date_add <= ?", $dtf->format_date($estimated_to) ]; push @estimated_delivery_time_conditions, \[ "estimated_delivery_date <= ?", $dtf->format_date($estimated_to) ]; } if ( defined $estimated_from and not defined $estimated_to ) { push @delivery_time_conditions, \[ "$date_add <= ?", $dtf->format_date(dt_from_string) ]; - push @estimated_delivery_time_conditions, \[ "estimated_delivery_date <= ?", $dtf->format_date(dt_from_string) ]; + push @estimated_delivery_time_conditions, + \[ "estimated_delivery_date <= ?", $dtf->format_date(dt_from_string) ]; } $self->search( @@ -95,18 +98,13 @@ sub filter_by_lates { quantityreceived => { '<' => \'quantity' } ], 'basketno.closedate' => [ - -and => - { '!=' => undef }, + -and => { '!=' => undef }, { defined $delay - ? ( - '<=' => $dtf->format_date( - dt_from_string->subtract( days => $delay ) - ) - ) + ? ( '<=' => $dtf->format_date( dt_from_string->subtract( days => $delay ) ) ) : () } - ], + ], 'datecancellationprinted' => undef, ( $bookseller_id @@ -116,18 +114,19 @@ sub filter_by_lates { # ( $branchcode ? ('borrower.branchcode')) # FIXME branch is not a filter we may not need to implement this - ( ( @delivery_time_conditions and @estimated_delivery_time_conditions ) ? - ( -or => - [ + ( + ( @delivery_time_conditions and @estimated_delivery_time_conditions ) + ? ( + -or => [ -and => \@estimated_delivery_time_conditions, -and => \@delivery_time_conditions ] - ) + ) : () ), ( C4::Context->preference('IndependentBranches') - && !C4::Context->IsSuperLibrarian + && !C4::Context->IsSuperLibrarian ? ( 'borrower.branchcode' => C4::Context->userenv->{branch} ) : () ) @@ -136,11 +135,13 @@ sub filter_by_lates { '+select' => [ \"DATE_ADD(basketno.closedate, INTERVAL COALESCE(booksellerid.deliverytime, booksellerid.deliverytime, 0) day)", ], - '+as' => [qw/ - calculated_estimated_delivery_date - /], - join => { 'basketno' => 'booksellerid' }, - prefetch => {'basketno' => 'booksellerid'}, + '+as' => [ + qw/ + calculated_estimated_delivery_date + / + ], + join => { 'basketno' => 'booksellerid' }, + prefetch => { 'basketno' => 'booksellerid' }, } )->filter_by_active; } @@ -162,8 +163,10 @@ sub filter_by_active { return $self->search( { '-or' => [ - { 'basket.is_standing' => 1, - 'orderstatus' => [ 'new', 'ordered', 'partial' ] }, + { + 'basket.is_standing' => 1, + 'orderstatus' => [ 'new', 'ordered', 'partial' ] + }, { 'orderstatus' => [ 'ordered', 'partial' ] } ], quantityreceived => { '<', \['COALESCE(me.quantity,0)'] }, @@ -199,11 +202,7 @@ Return the orders of the set that have been cancelled. sub filter_by_cancelled { my ($self) = @_; - return $self->search( - { - datecancellationprinted => { '!=' => undef } - } - ); + return $self->search( { datecancellationprinted => { '!=' => undef } } ); } =head3 filter_by_id_including_transfers @@ -222,13 +221,13 @@ so we can find orders that have changed their ordernumber as the result of a tra sub filter_by_id_including_transfers { my ( $self, $params ) = @_; - Koha::Exceptions::MissingParameter->throw( "The ordernumber param is mandatory" ) + Koha::Exceptions::MissingParameter->throw("The ordernumber param is mandatory") unless $params->{ordernumber}; return $self->search( { -or => [ - { 'me.ordernumber' => $params->{ordernumber} }, + { 'me.ordernumber' => $params->{ordernumber} }, { 'aqorders_transfers_ordernumber_to.ordernumber_from' => $params->{ordernumber} } ] }, @@ -277,7 +276,6 @@ sub filter_by_obsolete { return $rs; } - =head3 cancel $orders_rs->cancel( { delete_biblio => 0|1 } ); diff --git a/Koha/AdditionalContents.pm b/Koha/AdditionalContents.pm index f434fba1a0..a16089e524 100644 --- a/Koha/AdditionalContents.pm +++ b/Koha/AdditionalContents.pm @@ -110,23 +110,28 @@ sub search_for_display { sub find_best_match { my ( $self, $params ) = @_; my $library_id = $params->{library_id}; - my $lang = $params->{lang}; + my $lang = $params->{lang}; - my $contents = $self->SUPER::search({ - category => $params->{category}, - location => $params->{location}, - branchcode => [ $library_id, undef ], - }); + my $contents = $self->SUPER::search( + { + category => $params->{category}, + location => $params->{location}, + branchcode => [ $library_id, undef ], + } + ); - my $rs = Koha::AdditionalContentsLocalizations->search({ + my $rs = Koha::AdditionalContentsLocalizations->search( + { additional_content_id => [ $contents->get_column('id') ], - lang => [ $lang, 'default' ], - }); + lang => [ $lang, 'default' ], + } + ); # Pick the best my ( $alt1, $alt2, $alt3 ); - while( my $rec = $rs->next ) { - return $rec if $library_id && $rec->branchcode && $rec->branchcode eq $library_id && $lang && $rec->lang eq $lang; + while ( my $rec = $rs->next ) { + return $rec + if $library_id && $rec->branchcode && $rec->branchcode eq $library_id && $lang && $rec->lang eq $lang; $alt1 = $rec if !$alt1 && $library_id && $rec->branchcode && $rec->branchcode eq $library_id; $alt2 = $rec if !$alt2 && $lang && $rec->lang eq $lang; $alt3 = $rec if !$alt3; diff --git a/Koha/AdditionalField.pm b/Koha/AdditionalField.pm index ec0263697f..160d248322 100644 --- a/Koha/AdditionalField.pm +++ b/Koha/AdditionalField.pm @@ -29,10 +29,10 @@ sub effective_authorised_value_category { my $category = $self->authorised_value_category; unless ($category) { - if ($self->marcfield) { - my ($tag, $subfield) = split /\$/, $self->marcfield; + if ( $self->marcfield ) { + my ( $tag, $subfield ) = split /\$/, $self->marcfield; - my $mss = Koha::MarcSubfieldStructures->find('', $tag, $subfield); + my $mss = Koha::MarcSubfieldStructures->find( '', $tag, $subfield ); if ($mss) { $category = $mss->authorised_value; } diff --git a/Koha/AdditionalFieldValue.pm b/Koha/AdditionalFieldValue.pm index 6af87a9d9d..7f583ed977 100644 --- a/Koha/AdditionalFieldValue.pm +++ b/Koha/AdditionalFieldValue.pm @@ -23,7 +23,7 @@ Return the Koha::AdditionalField object for this AdditionalFieldValue =cut sub field { - my ( $self ) = @_; + my ($self) = @_; return Koha::AdditionalField->_new_from_dbic( $self->_result()->field() ); } diff --git a/Koha/AdditionalFieldValues.pm b/Koha/AdditionalFieldValues.pm index cd0b284ece..b40a7e345e 100644 --- a/Koha/AdditionalFieldValues.pm +++ b/Koha/AdditionalFieldValues.pm @@ -12,7 +12,7 @@ use Koha::AdditionalFieldValue; use base 'Koha::Objects'; -sub _type { 'AdditionalFieldValue' } +sub _type { 'AdditionalFieldValue' } sub object_class { 'Koha::AdditionalFieldValue' } =head1 AUTHOR diff --git a/Koha/AdditionalFields.pm b/Koha/AdditionalFields.pm index 4900ddaa18..dbb16375e2 100644 --- a/Koha/AdditionalFields.pm +++ b/Koha/AdditionalFields.pm @@ -12,7 +12,7 @@ use base 'Koha::Objects'; use Koha::AdditionalField; -sub _type { 'AdditionalField' } +sub _type { 'AdditionalField' } sub object_class { 'Koha::AdditionalField' } =head1 AUTHOR diff --git a/Koha/AdvancedEditorMacro.pm b/Koha/AdvancedEditorMacro.pm index 6627b325de..7006238866 100644 --- a/Koha/AdvancedEditorMacro.pm +++ b/Koha/AdvancedEditorMacro.pm @@ -16,7 +16,6 @@ package Koha::AdvancedEditorMacro; use Modern::Perl; - use Koha::Database; use base qw(Koha::Object); @@ -35,13 +34,12 @@ Koha::AdvancedEditorMacro - Koha Advanced editor macro object class sub to_api_mapping { return { - id => 'macro_id', - macro => 'macro_text', - borrowernumber => 'patron_id', + id => 'macro_id', + macro => 'macro_text', + borrowernumber => 'patron_id', }; } - =head2 Internal methods =head3 _type diff --git a/Koha/AdvancedEditorMacros.pm b/Koha/AdvancedEditorMacros.pm index d890185e4d..36dda12964 100644 --- a/Koha/AdvancedEditorMacros.pm +++ b/Koha/AdvancedEditorMacros.pm @@ -16,7 +16,6 @@ package Koha::AdvancedEditorMacros; use Modern::Perl; - use Koha::Database; use Koha::AdvancedEditorMacro; diff --git a/Koha/ApiKey.pm b/Koha/ApiKey.pm index 28b2c5f42c..3e79c8f479 100644 --- a/Koha/ApiKey.pm +++ b/Koha/ApiKey.pm @@ -19,7 +19,6 @@ package Koha::ApiKey; use Modern::Perl; - use Koha::AuthUtils qw(hash_password); use Koha::Exceptions::Object; @@ -53,12 +52,13 @@ sub store { # only allow 'description' and 'active' to be updated for my $property ( keys %dirty_columns ) { Koha::Exceptions::Object::ReadOnlyProperty->throw( property => $property ) - if $property ne 'description' and $property ne 'active'; + if $property ne 'description' and $property ne 'active'; } } else { $self->{_plain_text_secret} = $self->_generate_unused_uuid('secret'); $self->set( - { secret => Koha::AuthUtils::hash_password( $self->{_plain_text_secret} ), + { + secret => Koha::AuthUtils::hash_password( $self->{_plain_text_secret} ), client_id => $self->_generate_unused_uuid('client_id'), } ); @@ -124,14 +124,15 @@ $column can be 'client_id' or 'secret'. =cut sub _generate_unused_uuid { - my ($self, $column) = @_; + my ( $self, $column ) = @_; my ( $uuid, $uuidstring ); UUID::generate($uuid); UUID::unparse( $uuid, $uuidstring ); - while ( Koha::ApiKeys->search({ $column => $uuidstring })->count > 0 ) { + while ( Koha::ApiKeys->search( { $column => $uuidstring } )->count > 0 ) { + # Make sure $secret is unique UUID::generate($uuid); UUID::unparse( $uuid, $uuidstring ); diff --git a/Koha/ApiKeys.pm b/Koha/ApiKeys.pm index 07cabd3204..28be0fa437 100644 --- a/Koha/ApiKeys.pm +++ b/Koha/ApiKeys.pm @@ -19,7 +19,6 @@ package Koha::ApiKeys; use Modern::Perl; - use Koha::Database; use Koha::ApiKey; diff --git a/Koha/App/Intranet.pm b/Koha/App/Intranet.pm index 5628174fdc..83d2f68efd 100644 --- a/Koha/App/Intranet.pm +++ b/Koha/App/Intranet.pm @@ -27,8 +27,8 @@ use Koha::Cache::Memory::Lite; sub startup { my ($self) = @_; - push @{$self->plugins->namespaces}, 'Koha::App::Plugin'; - push @{$self->static->paths}, $self->home->rel_file('koha-tmpl'); + push @{ $self->plugins->namespaces }, 'Koha::App::Plugin'; + push @{ $self->static->paths }, $self->home->rel_file('koha-tmpl'); # Create route for all CGI scripts, need to be loaded first because of # CGI::Compile @@ -41,12 +41,12 @@ sub startup { $self->plugin('CSRF'); $self->plugin('Language'); - $self->hook(before_dispatch => \&_before_dispatch); - $self->hook(around_action => \&_around_action); + $self->hook( before_dispatch => \&_before_dispatch ); + $self->hook( around_action => \&_around_action ); my $r = $self->routes; - $r->any('/')->to(cb => sub { shift->redirect_to('/cgi-bin/koha/mainpage.pl') }); + $r->any('/')->to( cb => sub { shift->redirect_to('/cgi-bin/koha/mainpage.pl') } ); } sub _before_dispatch { @@ -58,7 +58,7 @@ sub _before_dispatch { $path =~ s/_\d{2}\.\d{7}\.(js|css)/.$1/; # See FIXME above - if ($path =~ m|^/api/v|) { + if ( $path =~ m|^/api/v| ) { $path = '/api' . $path; } @@ -66,7 +66,7 @@ sub _before_dispatch { } sub _around_action { - my ($next, $c, $action, $last) = @_; + my ( $next, $c, $action, $last ) = @_; # Flush memory caches before every request Koha::Caches->flush_L1_caches(); diff --git a/Koha/App/Opac.pm b/Koha/App/Opac.pm index d41a704776..247b38c720 100644 --- a/Koha/App/Opac.pm +++ b/Koha/App/Opac.pm @@ -27,12 +27,12 @@ use Koha::Cache::Memory::Lite; sub startup { my ($self) = @_; - push @{$self->plugins->namespaces}, 'Koha::App::Plugin'; - push @{$self->static->paths}, $self->home->rel_file('koha-tmpl'); + push @{ $self->plugins->namespaces }, 'Koha::App::Plugin'; + push @{ $self->static->paths }, $self->home->rel_file('koha-tmpl'); # Create route for all CGI scripts, need to be loaded first because of # CGI::Compile - $self->plugin('CGIBinKoha', opac => 1); + $self->plugin( 'CGIBinKoha', opac => 1 ); # Create routes for API # FIXME This generates routes like this: /api/api/v1/... @@ -41,12 +41,12 @@ sub startup { $self->plugin('CSRF'); $self->plugin('Language'); - $self->hook(before_dispatch => \&_before_dispatch); - $self->hook(around_action => \&_around_action); + $self->hook( before_dispatch => \&_before_dispatch ); + $self->hook( around_action => \&_around_action ); my $r = $self->routes; - $r->any('/')->to(cb => sub { shift->redirect_to('/cgi-bin/koha/opac-main.pl') }); + $r->any('/')->to( cb => sub { shift->redirect_to('/cgi-bin/koha/opac-main.pl') } ); } sub _before_dispatch { @@ -58,7 +58,7 @@ sub _before_dispatch { $path =~ s/_\d{2}\.\d{7}\.(js|css)/.$1/; # See FIXME above - if ($path =~ m|^/api/v|) { + if ( $path =~ m|^/api/v| ) { $path = '/api' . $path; } @@ -66,7 +66,7 @@ sub _before_dispatch { } sub _around_action { - my ($next, $c, $action, $last) = @_; + my ( $next, $c, $action, $last ) = @_; # Flush memory caches before every request Koha::Caches->flush_L1_caches(); diff --git a/Koha/App/Plugin/CGIBinKoha.pm b/Koha/App/Plugin/CGIBinKoha.pm index 268c45fc7a..6d9fd5cc02 100644 --- a/Koha/App/Plugin/CGIBinKoha.pm +++ b/Koha/App/Plugin/CGIBinKoha.pm @@ -26,7 +26,7 @@ use CGI::Compile; use CGI::Emulate::PSGI; sub register { - my ($self, $app, $conf) = @_; + my ( $self, $app, $conf ) = @_; # CGI::Compile calls CGI::initialize_globals before each request, which resets PARAM_UTF8 to 0 # We need to set it back to the correct value @@ -43,38 +43,40 @@ sub register { my $r = $app->routes; - $r->any('/cgi-bin/koha/*script' => sub { - my ($c) = @_; + $r->any( + '/cgi-bin/koha/*script' => sub { + my ($c) = @_; - my $script = $c->stash('script'); + my $script = $c->stash('script'); - # Special case for installer which can takes a long time - $c->inactivity_timeout(300) if $script eq 'installer/install.pl'; + # Special case for installer which can takes a long time + $c->inactivity_timeout(300) if $script eq 'installer/install.pl'; - # Remove trailing slash, if any (e.g. .../svc/config/systempreferences/) - $script =~ s|/$||; + # Remove trailing slash, if any (e.g. .../svc/config/systempreferences/) + $script =~ s|/$||; - if ($opac) { - $script = "opac/$script"; + if ($opac) { + $script = "opac/$script"; + } + + unless ( -e $c->app->home->rel_file($script) ) { + return $c->reply->not_found; + } + + my $sub = CGI::Compile->compile($script); + my $app = CGI::Emulate::PSGI->handler($sub); + my $response = $app->( $self->_psgi_env($c) ); + + $c->res->code( $response->[0] ); + $c->res->headers->from_hash( { @{ $response->[1] } } ); + $c->res->body( join( '', @{ $response->[2] } ) ); + $c->rendered; } - - unless (-e $c->app->home->rel_file($script)) { - return $c->reply->not_found; - } - - my $sub = CGI::Compile->compile($script); - my $app = CGI::Emulate::PSGI->handler($sub); - my $response = $app->($self->_psgi_env($c)); - - $c->res->code($response->[0]); - $c->res->headers->from_hash({ @{ $response->[1] } }); - $c->res->body(join('', @{$response->[2]})); - $c->rendered; - })->name('cgi'); + )->name('cgi'); } sub _psgi_env { - my ($self, $c) = @_; + my ( $self, $c ) = @_; my $env = $c->req->env; @@ -82,24 +84,24 @@ sub _psgi_env { open my $input, '<', \$body or die "Can't open in-memory scalar: $!"; $env = { %$env, - 'psgi.input' => $input, - 'psgi.errors' => *STDERR, - REQUEST_METHOD => $c->req->method, - QUERY_STRING => $c->req->url->query->to_string, - SERVER_NAME => $c->req->url->to_abs->host, - SERVER_PORT => $c->req->url->to_abs->port, + 'psgi.input' => $input, + 'psgi.errors' => *STDERR, + REQUEST_METHOD => $c->req->method, + QUERY_STRING => $c->req->url->query->to_string, + SERVER_NAME => $c->req->url->to_abs->host, + SERVER_PORT => $c->req->url->to_abs->port, SERVER_PROTOCOL => 'HTTP/1.1', - CONTENT_LENGTH => $c->req->headers->content_length, - CONTENT_TYPE => $c->req->headers->content_type, - REMOTE_ADDR => $c->tx->remote_address, - SCRIPT_NAME => $c->req->url->path->to_string, + CONTENT_LENGTH => $c->req->headers->content_length, + CONTENT_TYPE => $c->req->headers->content_type, + REMOTE_ADDR => $c->tx->remote_address, + SCRIPT_NAME => $c->req->url->path->to_string, }; # Starman sets PATH_INFO to the same value of SCRIPT_NAME, which confuses # CGI and causes the redirect after OPAC login to fail - delete $env->{PATH_INFO} if ($env->{PATH_INFO} && $env->{PATH_INFO} eq $env->{SCRIPT_NAME}); + delete $env->{PATH_INFO} if ( $env->{PATH_INFO} && $env->{PATH_INFO} eq $env->{SCRIPT_NAME} ); - for my $name (@{ $c->req->headers->names }) { + for my $name ( @{ $c->req->headers->names } ) { my $value = $c->req->headers->header($name); $name =~ s/-/_/g; $name = 'HTTP_' . uc($name); diff --git a/Koha/App/Plugin/RESTV1.pm b/Koha/App/Plugin/RESTV1.pm index 883b989cbd..9c98539adf 100644 --- a/Koha/App/Plugin/RESTV1.pm +++ b/Koha/App/Plugin/RESTV1.pm @@ -24,9 +24,9 @@ use Mojo::Base 'Mojolicious::Plugin'; use Koha::REST::V1; sub register { - my ($self, $app) = @_; + my ( $self, $app ) = @_; - $app->routes->any('/api')->partial(1)->to(app => Koha::REST::V1->new); + $app->routes->any('/api')->partial(1)->to( app => Koha::REST::V1->new ); } 1; diff --git a/Koha/ArticleRequest.pm b/Koha/ArticleRequest.pm index 1bfbda3484..5beb5dfeb1 100644 --- a/Koha/ArticleRequest.pm +++ b/Koha/ArticleRequest.pm @@ -52,14 +52,13 @@ Marks the article as requested. Send a notification if appropriate. sub request { my ($self) = @_; - Koha::Exceptions::ArticleRequest::LimitReached->throw( - error => 'Patron cannot request more articles for today' - ) unless $self->borrower->can_request_article; + Koha::Exceptions::ArticleRequest::LimitReached->throw( error => 'Patron cannot request more articles for today' ) + unless $self->borrower->can_request_article; $self->status(Koha::ArticleRequest::Status::Requested); # Handle possible fees - my $debit = $self->borrower->add_article_request_fee_if_needed({ item_id => $self->itemnumber }); + my $debit = $self->borrower->add_article_request_fee_if_needed( { item_id => $self->itemnumber } ); $self->debit_id( $debit->id ) if $debit; @@ -132,38 +131,41 @@ sub cancel { my ( $self, $params ) = @_; my $cancellation_reason = $params->{cancellation_reason}; - my $notes = $params->{notes}; + my $notes = $params->{notes}; $self->status(Koha::ArticleRequest::Status::Canceled); $self->cancellation_reason($cancellation_reason) if $cancellation_reason; - $self->notes($notes) if $notes; + $self->notes($notes) if $notes; $self->store(); $self->notify(); my $debit = $self->debit; - if ( $debit ) { + if ($debit) { + # fees found, refund my $account = $self->borrower->account; my $total_reversible = $debit->debit_offsets->filter_by_reversible->total; - if ( $total_reversible ) { + if ($total_reversible) { $account->add_credit( { - amount => abs $total_reversible, - interface => C4::Context->interface, - type => 'REFUND', + amount => abs $total_reversible, + interface => C4::Context->interface, + type => 'REFUND', } ); } if ( $debit->amountoutstanding ) { - $debit->reduce({ - reduction_type => 'REFUND', - amount => $debit->amountoutstanding, - interface => C4::Context->interface, - })->discard_changes; + $debit->reduce( + { + reduction_type => 'REFUND', + amount => $debit->amountoutstanding, + interface => C4::Context->interface, + } + )->discard_changes; } } @@ -198,7 +200,7 @@ sub debit { my $debit_rs = $self->_result->debit; return unless $debit_rs; - return Koha::Account::Line->_new_from_dbic( $debit_rs ); + return Koha::Account::Line->_new_from_dbic($debit_rs); } =head3 item @@ -289,8 +291,8 @@ sub notify { if ( !defined $reason && $self->cancellation_reason ) { my $av = Koha::AuthorisedValues->search( { - category => 'AR_CANCELLATION', - authorised_value => $self->cancellation_reason + category => 'AR_CANCELLATION', + authorised_value => $self->cancellation_reason } )->next; $reason = $av->lib_opac ? $av->lib_opac : $av->lib if $av; @@ -315,7 +317,7 @@ sub notify { reason => $reason, }, ) - ) + ) { C4::Letters::EnqueueLetter( { diff --git a/Koha/ArticleRequests.pm b/Koha/ArticleRequests.pm index 78b19255ee..48abf17960 100644 --- a/Koha/ArticleRequests.pm +++ b/Koha/ArticleRequests.pm @@ -19,7 +19,6 @@ package Koha::ArticleRequests; use Modern::Perl; - use Koha::Database; use Koha::ArticleRequest::Status; @@ -54,9 +53,10 @@ sub search_limited { my $logged_in_user = Koha::Patrons->find( $userenv->{number} ); @restricted_branchcodes = $logged_in_user->libraries_where_can_see_patrons; } + # TODO This 'borrowernumber' relation name is confusing and needs to be renamed $params->{'borrowernumber.branchcode'} = { -in => \@restricted_branchcodes } if @restricted_branchcodes; - $attributes->{join} = 'borrowernumber'; + $attributes->{join} = 'borrowernumber'; return $self->search( $params, $attributes ); } @@ -122,7 +122,7 @@ sub pending { my ( $self, $branchcode ) = @_; my $params = { status => Koha::ArticleRequest::Status::Pending }; $params->{'me.branchcode'} = $branchcode if $branchcode; - return Koha::ArticleRequests->search_limited( $params ); + return Koha::ArticleRequests->search_limited($params); } =head3 processing @@ -133,7 +133,7 @@ sub processing { my ( $self, $branchcode ) = @_; my $params = { status => Koha::ArticleRequest::Status::Processing }; $params->{'me.branchcode'} = $branchcode if $branchcode; - return Koha::ArticleRequests->search_limited( $params ); + return Koha::ArticleRequests->search_limited($params); } =head3 completed @@ -144,7 +144,7 @@ sub completed { my ( $self, $branchcode ) = @_; my $params = { status => Koha::ArticleRequest::Status::Completed }; $params->{'me.branchcode'} = $branchcode if $branchcode; - return Koha::ArticleRequests->search_limited( $params ); + return Koha::ArticleRequests->search_limited($params); } =head3 canceled @@ -155,7 +155,7 @@ sub canceled { my ( $self, $branchcode ) = @_; my $params = { status => Koha::ArticleRequest::Status::Canceled }; $params->{'me.branchcode'} = $branchcode if $branchcode; - return Koha::ArticleRequests->search_limited( $params ); + return Koha::ArticleRequests->search_limited($params); } =head3 _type diff --git a/Koha/AudioAlert.pm b/Koha/AudioAlert.pm index 6d5cf639e0..3856761f6a 100644 --- a/Koha/AudioAlert.pm +++ b/Koha/AudioAlert.pm @@ -19,7 +19,6 @@ package Koha::AudioAlert; use Modern::Perl; - use Koha::Database; use base qw(Koha::Object); diff --git a/Koha/AudioAlerts.pm b/Koha/AudioAlerts.pm index 8190ee01d1..ba95d2e77c 100644 --- a/Koha/AudioAlerts.pm +++ b/Koha/AudioAlerts.pm @@ -19,7 +19,6 @@ package Koha::AudioAlerts; use Modern::Perl; - use Koha::Database; use Koha::AudioAlert; @@ -95,19 +94,16 @@ sub move { $other->precedence( $alert->precedence() )->store(); $alert->precedence( $alert->precedence() - 1 )->store(); } - } - elsif ( $where eq 'down' ) { + } elsif ( $where eq 'down' ) { unless ( $alert->precedence() == $self->get_last_precedence() ) { my $other = $self->search( { precedence => $alert->precedence() + 1 } )->next; $other->precedence( $alert->precedence() )->store(); $alert->precedence( $alert->precedence() + 1 )->store(); } - } - elsif ( $where eq 'top' ) { + } elsif ( $where eq 'top' ) { $alert->precedence(0)->store(); $self->fix_precedences(); - } - elsif ( $where eq 'bottom' ) { + } elsif ( $where eq 'bottom' ) { $alert->precedence( $self->get_next_precedence() )->store(); $self->fix_precedences(); } diff --git a/Koha/Auth/Client.pm b/Koha/Auth/Client.pm index bd6a515521..ee8e0d23a4 100644 --- a/Koha/Auth/Client.pm +++ b/Koha/Auth/Client.pm @@ -107,6 +107,7 @@ Gets the best suited valid domain configuration for the given provider. =cut sub get_valid_domain_config { + # FIXME: Should be a hashref param my ( $self, $params ) = @_; my $provider = $params->{provider}; @@ -121,9 +122,9 @@ sub get_valid_domain_config { while ( my $domain = $domains->next ) { - my $pattern = '@'; + my $pattern = '@'; my $domain_text = $domain->domain; - unless ( defined $domain_text && $domain_text ne '') { + unless ( defined $domain_text && $domain_text ne '' ) { $response = $domain; next; } @@ -144,7 +145,7 @@ sub get_valid_domain_config { if ( !$perfect_match && @subdomain_matches ) { @subdomain_matches = sort { $b->{match_length} <=> $a->{match_length} } @subdomain_matches - unless scalar @subdomain_matches == 1; + unless scalar @subdomain_matches == 1; $response = $subdomain_matches[0]->{domain}; } elsif ($perfect_match) { $response = $perfect_match; @@ -169,12 +170,13 @@ Checks if provider has a valid domain for user email. If has, returns that domai =cut sub has_valid_domain_config { + # FIXME: Should be a hashref param my ( $self, $params ) = @_; - my $domain = $self->get_valid_domain_config( $params ); + my $domain = $self->get_valid_domain_config($params); Koha::Exceptions::Auth::NoValidDomain->throw( code => 401 ) - unless $domain; + unless $domain; return $domain; } @@ -208,14 +210,14 @@ Get deep nested value in a hash. =cut sub _traverse_hash { - my ($self, $params) = @_; + my ( $self, $params ) = @_; my $base = $params->{base}; my $keys = $params->{keys}; - my ($key, $rest) = ($keys =~ /^([^.]+)(?:\.(.*))?/); + my ( $key, $rest ) = ( $keys =~ /^([^.]+)(?:\.(.*))?/ ); return unless defined $key; my $value = ref $base eq 'HASH' ? $base->{$key} : $base->[$key]; return $value unless $rest; - return $self->_traverse_hash({ base => $value, keys => $rest }); + return $self->_traverse_hash( { base => $value, keys => $rest } ); } 1; diff --git a/Koha/Auth/Client/OAuth.pm b/Koha/Auth/Client/OAuth.pm index fe1fba306d..42d2691f04 100644 --- a/Koha/Auth/Client/OAuth.pm +++ b/Koha/Auth/Client/OAuth.pm @@ -19,7 +19,7 @@ package Koha::Auth::Client::OAuth; use Modern::Perl; -use JSON qw( decode_json ); +use JSON qw( decode_json ); use MIME::Base64 qw{ decode_base64url }; use Koha::Patrons; use Mojo::UserAgent; @@ -58,7 +58,7 @@ sub _get_data_and_patron { my $patron; my $mapped_data; - my $mapping = decode_json( $provider->mapping ); + my $mapping = decode_json( $provider->mapping ); my $matchpoint = $provider->matchpoint; if ( $data->{id_token} ) { @@ -69,7 +69,7 @@ sub _get_data_and_patron { foreach my $key ( keys %$mapping ) { my $pkey = $mapping->{$key}; $mapped_data->{$key} = $claim->{$pkey} - if defined $claim->{$pkey}; + if defined $claim->{$pkey}; } my $value = $mapped_data->{$matchpoint}; @@ -89,15 +89,15 @@ sub _get_data_and_patron { return if $code ne '200'; my $claim = - $tx->res->headers->content_type =~ m!^(application/json|text/javascript)(;\s*charset=\S+)?$! - ? $tx->res->json - : Mojo::Parameters->new( $tx->res->body )->to_hash; + $tx->res->headers->content_type =~ m!^(application/json|text/javascript)(;\s*charset=\S+)?$! + ? $tx->res->json + : Mojo::Parameters->new( $tx->res->body )->to_hash; foreach my $key ( keys %$mapping ) { my $pkey = $mapping->{$key}; my $value = $self->_traverse_hash( { base => $claim, keys => $pkey } ); $mapped_data->{$key} = $value - if defined $value; + if defined $value; } unless ($patron) { diff --git a/Koha/Auth/Identity/Provider.pm b/Koha/Auth/Identity/Provider.pm index d617b2449a..0916a0173f 100644 --- a/Koha/Auth/Identity/Provider.pm +++ b/Koha/Auth/Identity/Provider.pm @@ -63,8 +63,7 @@ sub get_config { return try { return decode_json( Encode::encode_utf8( $self->config ) ); - } - catch { + } catch { Koha::Exceptions::Object::BadValue->throw("Error reading JSON data: $_"); }; } @@ -95,7 +94,7 @@ This method stores the passed config in JSON format. =cut sub set_config { - my ($self, $config) = @_; + my ( $self, $config ) = @_; my @mandatory = $self->mandatory_config_attributes; @@ -128,8 +127,7 @@ sub get_mapping { return try { return decode_json( Encode::encode_utf8( $self->mapping ) ); - } - catch { + } catch { Koha::Exceptions::Object::BadValue->throw("Error reading JSON data: $_"); }; } @@ -143,13 +141,12 @@ This method stores the passed mappings in JSON format. =cut sub set_mapping { - my ($self, $mapping) = @_; + my ( $self, $mapping ) = @_; try { - my $encoded_mapping = encode_json( $mapping ); - $self->mapping( $encoded_mapping ); - } - catch { + my $encoded_mapping = encode_json($mapping); + $self->mapping($encoded_mapping); + } catch { Koha::Exceptions::Object::BadValue->throw("Error serializing data into JSON: $_"); }; @@ -165,12 +162,12 @@ Returns a new instance of the object, with the right class. =cut sub upgrade_class { - my ( $self ) = @_; + my ($self) = @_; my $protocol = $self->protocol; my $class = $self->protocol_to_class_mapping->{$protocol}; - Koha::Exception->throw($protocol . ' is not a valid protocol') + Koha::Exception->throw( $protocol . ' is not a valid protocol' ) unless $class; eval "require $class"; diff --git a/Koha/Auth/Identity/Provider/OAuth.pm b/Koha/Auth/Identity/Provider/OAuth.pm index 45f74a3f75..d297e52480 100644 --- a/Koha/Auth/Identity/Provider/OAuth.pm +++ b/Koha/Auth/Identity/Provider/OAuth.pm @@ -55,10 +55,10 @@ Returns a list of the mandatory config entries for the protocol. sub mandatory_config_attributes { return qw( - key - secret - authorize_url - token_url + key + secret + authorize_url + token_url ); } diff --git a/Koha/Auth/Identity/Provider/OIDC.pm b/Koha/Auth/Identity/Provider/OIDC.pm index 56bacff94e..c686805140 100644 --- a/Koha/Auth/Identity/Provider/OIDC.pm +++ b/Koha/Auth/Identity/Provider/OIDC.pm @@ -55,9 +55,9 @@ Returns a list of the mandatory config entries for the protocol. sub mandatory_config_attributes { return qw( - key - secret - well_known_url + key + secret + well_known_url ); } diff --git a/Koha/Auth/Permissions.pm b/Koha/Auth/Permissions.pm index df9c1a291a..b04d0c2633 100644 --- a/Koha/Auth/Permissions.pm +++ b/Koha/Auth/Permissions.pm @@ -32,38 +32,34 @@ Koha::Auth::Permissions - Class for setting up CAN_user_* permissions =cut sub get_authz_from_flags { - my ($class,$args) = @_; + my ( $class, $args ) = @_; my $flags = $args->{flags}; my $authz; my $all_perms = C4::Auth::get_all_subpermissions(); - if ($flags && $all_perms){ + if ( $flags && $all_perms ) { foreach my $module ( keys %$all_perms ) { - if ( - ( $flags->{superlibrarian} == 1 ) || - ( defined($flags->{$module}) && $flags->{$module} == 1 ) - ) { + if ( ( $flags->{superlibrarian} == 1 ) + || ( defined( $flags->{$module} ) && $flags->{$module} == 1 ) ) + { foreach my $subperm ( keys %{ $all_perms->{$module} } ) { - $authz->{ "CAN_user_${module}_${subperm}" } = 1; + $authz->{"CAN_user_${module}_${subperm}"} = 1; } - } - elsif ( ref( $flags->{$module} ) ){ + } elsif ( ref( $flags->{$module} ) ) { foreach my $subperm ( keys %{ $flags->{$module} } ) { - $authz->{ "CAN_user_${module}_${subperm}" } = 1; + $authz->{"CAN_user_${module}_${subperm}"} = 1; } } } foreach my $module ( keys %$flags ) { - if ( - ( $flags->{superlibrarian} == 1 ) || - ( $flags->{$module} == 1 ) || - ( ref( $flags->{$module} ) ) - ) { - $authz->{ "CAN_user_$module" } = 1; + if ( ( $flags->{superlibrarian} == 1 ) + || ( $flags->{$module} == 1 ) + || ( ref( $flags->{$module} ) ) ) + { + $authz->{"CAN_user_$module"} = 1; } } } return $authz; } - 1; diff --git a/Koha/Auth/TwoFactorAuth.pm b/Koha/Auth/TwoFactorAuth.pm index 5a00d4af10..2700cef160 100644 --- a/Koha/Auth/TwoFactorAuth.pm +++ b/Koha/Auth/TwoFactorAuth.pm @@ -54,10 +54,10 @@ It's based on Auth::GoogleAuth =cut sub new { - my ($class, $params) = @_; + my ( $class, $params ) = @_; my $patron = $params->{patron}; my $secret32 = $params->{secret32}; - my $secret = $params->{secret}; + my $secret = $params->{secret}; # FIXME Raise an exception if the syspref is disabled @@ -65,26 +65,28 @@ sub new { unless $patron && ref($patron) eq 'Koha::Patron'; my $type = 'secret32'; - if( $secret32 ) { + if ($secret32) { Koha::Exceptions::BadParameter->throw("Secret32 should be base32") if $secret32 =~ /[^a-z2-7]/; - } elsif( $secret ) { + } elsif ($secret) { $type = 'secret'; - } elsif( $patron->secret ) { - $secret32 = $patron->decoded_secret; # saved already in base32 + } elsif ( $patron->secret ) { + $secret32 = $patron->decoded_secret; # saved already in base32 } else { Koha::Exceptions::MissingParameter->throw("No secret passed or patron has no secret"); } - my $issuer = Encode::encode_utf8($patron->library->branchname); + my $issuer = Encode::encode_utf8( $patron->library->branchname ); my $key_id = sprintf "%s_%s", - $issuer, ( $patron->email || $patron->userid ); + $issuer, ( $patron->email || $patron->userid ); - return $class->SUPER::new({ - $type => $secret32 || $secret, - issuer => $issuer, - key_id => $key_id, - }); + return $class->SUPER::new( + { + $type => $secret32 || $secret, + issuer => $issuer, + key_id => $key_id, + } + ); } =head3 qr_code @@ -98,13 +100,14 @@ sub new { =cut sub qr_code { - my ( $self ) = @_; + my ($self) = @_; - my $otpauth = $self->SUPER::qr_code( undef, undef, undef, 1); - # no need to pass secret, key and issuer again + my $otpauth = $self->SUPER::qr_code( undef, undef, undef, 1 ); + + # no need to pass secret, key and issuer again my $qrcode = GD::Barcode->new( 'QRcode', $otpauth, { Ecc => 'M', ModuleSize => 4 } ); - my $data = $qrcode->plot->png; - return "data:image/png;base64,". encode_base64( $data, q{} ); # does not contain newlines + my $data = $qrcode->plot->png; + return "data:image/png;base64," . encode_base64( $data, q{} ); # does not contain newlines } =head3 verify diff --git a/Koha/AuthUtils.pm b/Koha/AuthUtils.pm index 1dd8b0a7db..66968e04d1 100644 --- a/Koha/AuthUtils.pm +++ b/Koha/AuthUtils.pm @@ -20,20 +20,21 @@ package Koha::AuthUtils; use Modern::Perl; use Crypt::Eksblowfish::Bcrypt qw( bcrypt en_base64 ); use Encode; -use Fcntl qw( O_RDONLY ); # O_RDONLY is used in generate_salt +use Fcntl qw( O_RDONLY ); # O_RDONLY is used in generate_salt use List::MoreUtils qw( any ); -use String::Random qw( random_string ); +use String::Random qw( random_string ); use Koha::Exceptions::Password; use C4::Context; +our ( @ISA, @EXPORT_OK ); -our (@ISA, @EXPORT_OK); BEGIN { require Exporter; - @ISA = qw(Exporter); + @ISA = qw(Exporter); @EXPORT_OK = qw(hash_password get_script_name is_password_valid); -}; +} + =head1 NAME Koha::AuthUtils - utility routines for authentication @@ -66,16 +67,17 @@ be taken care of. sub hash_password { my $password = shift; $password = Encode::encode( 'UTF-8', $password ) - if Encode::is_utf8($password); + if Encode::is_utf8($password); # Generate a salt if one is not passed my $settings = shift; - unless( defined $settings ){ # if there are no settings, we need to create a salt and append settings - # Set the cost to 8 and append a NULL - $settings = '$2a$08$'.en_base64(generate_salt('weak', 16)); + unless ( defined $settings ) { # if there are no settings, we need to create a salt and append settings + # Set the cost to 8 and append a NULL + $settings = '$2a$08$' . en_base64( generate_salt( 'weak', 16 ) ); } + # Hash it - return bcrypt($password, $settings); + return bcrypt( $password, $settings ); } =head2 generate_salt @@ -100,26 +102,26 @@ C<$length> is a positive integer which specifies the desired length of the retur =cut - # the implementation of generate_salt is loosely based on Crypt::Random::Provider::File sub generate_salt { + # strength is 'strong' or 'weak' # length is number of bytes to read, positive integer - my ($strength, $length) = @_; + my ( $strength, $length ) = @_; my $source; - if( $length < 1 ){ + if ( $length < 1 ) { die "non-positive strength of '$strength' passed to Koha::AuthUtils::generate_salt\n"; } - if( $strength eq "strong" ){ - $source = '/dev/random'; # blocking + if ( $strength eq "strong" ) { + $source = '/dev/random'; # blocking } else { - unless( $strength eq 'weak' ){ + unless ( $strength eq 'weak' ) { warn "unsuppored strength of '$strength' passed to Koha::AuthUtils::generate_salt, defaulting to 'weak'\n"; } - $source = '/dev/urandom'; # non-blocking + $source = '/dev/urandom'; # non-blocking } my $source_fh; @@ -128,16 +130,17 @@ sub generate_salt { # $bytes is the bytes just read # $string is the concatenation of all the bytes read so far - my( $bytes, $string ) = ("", ""); + my ( $bytes, $string ) = ( "", "" ); # keep reading until we have $length bytes in $strength - while( length($string) < $length ){ + while ( length($string) < $length ) { + # return the number of bytes read, 0 (EOF), or -1 (ERROR) my $return = sysread $source_fh, $bytes, $length - length($string); # if no bytes were read, keep reading (if using /dev/random it is possible there was insufficient entropy so this may block) next unless $return; - if( $return == -1 ){ + if ( $return == -1 ) { die "error while reading from $source in Koha::AuthUtils::generate_salt\n"; } @@ -158,18 +161,17 @@ otherwise return $is_valid == 0 and $error will contain the error ('too_short' o =cut sub is_password_valid { - my ($password, $category) = @_; - if(!$category) { + my ( $password, $category ) = @_; + if ( !$category ) { Koha::Exceptions::Password::NoCategoryProvided->throw(); } my $minPasswordLength = $category->effective_min_password_length; $minPasswordLength = 3 if not $minPasswordLength or $minPasswordLength < 3; if ( length($password) < $minPasswordLength ) { return ( 0, 'too_short' ); - } - elsif ( $category->effective_require_strong_password ) { + } elsif ( $category->effective_require_strong_password ) { return ( 0, 'too_weak' ) - if $password !~ m|(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{$minPasswordLength,}|; + if $password !~ m|(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{$minPasswordLength,}|; } return ( 0, 'has_whitespaces' ) if $password =~ m[^\s|\s$]; return ( 1, undef ); @@ -185,7 +187,7 @@ Generate a password according to category's minimum password length and strength sub generate_password { my ($category) = @_; - if(!$category) { + if ( !$category ) { Koha::Exceptions::Password::NoCategoryProvided->throw(); } my $minPasswordLength = $category->effective_min_password_length; @@ -193,13 +195,12 @@ sub generate_password { my ( $password, $is_valid ); do { - $password = random_string('.' x $minPasswordLength ); + $password = random_string( '.' x $minPasswordLength ); ( $is_valid, undef ) = is_password_valid( $password, $category ); } while not $is_valid; return $password; } - =head2 get_script_name This returns the correct script name, for use in redirecting back to the correct page after showing diff --git a/Koha/AuthorisedValue.pm b/Koha/AuthorisedValue.pm index 5669ab6086..7a306bfae5 100644 --- a/Koha/AuthorisedValue.pm +++ b/Koha/AuthorisedValue.pm @@ -55,8 +55,7 @@ sub store { if ( !$self->in_storage ) { $flush = 1; - } - else { + } else { my %updated_columns = $self->_result->get_dirty_columns; if ( exists $updated_columns{lib} @@ -71,7 +70,7 @@ sub store { $self = $self->SUPER::store; if ($flush) { - my $key = "AV_descriptions:".$self->category; + my $key = "AV_descriptions:" . $self->category; $cache->clear_from_cache($key); } @@ -86,7 +85,7 @@ AuthorisedValue specific C to clear relevant caches on delete. sub delete { my $self = shift @_; - my $key = "AV_descriptions:".$self->category; + my $key = "AV_descriptions:" . $self->category; $cache->clear_from_cache($key); $self->SUPER::delete(@_); } diff --git a/Koha/AuthorisedValueCategories.pm b/Koha/AuthorisedValueCategories.pm index 21e4eee49f..cf3fb3fea0 100644 --- a/Koha/AuthorisedValueCategories.pm +++ b/Koha/AuthorisedValueCategories.pm @@ -17,7 +17,6 @@ package Koha::AuthorisedValueCategories; use Modern::Perl; - use Koha::Database; use Koha::Exceptions; diff --git a/Koha/AuthorisedValueCategory.pm b/Koha/AuthorisedValueCategory.pm index 4e715c5c8e..4556dcb689 100644 --- a/Koha/AuthorisedValueCategory.pm +++ b/Koha/AuthorisedValueCategory.pm @@ -17,7 +17,6 @@ package Koha::AuthorisedValueCategory; use Modern::Perl; - use Koha::Database; use Koha::Exceptions; @@ -40,7 +39,7 @@ Returns the authorised values for this authorised value category =cut sub authorised_values { - my ( $self ) = @_; + my ($self) = @_; my $authorised_values_rs = $self->_result->authorised_values; return Koha::AuthorisedValues->_new_from_dbic($authorised_values_rs); diff --git a/Koha/AuthorisedValues.pm b/Koha/AuthorisedValues.pm index 377d1de552..02562e0ddd 100644 --- a/Koha/AuthorisedValues.pm +++ b/Koha/AuthorisedValues.pm @@ -19,7 +19,6 @@ package Koha::AuthorisedValues; use Modern::Perl; - use Koha::Database; use Koha::AuthorisedValue; @@ -47,12 +46,13 @@ sub search_by_marc_field { return unless $tagfield or $tagsubfield; return $self->SUPER::search( - { 'marc_subfield_structures.frameworkcode' => $frameworkcode, + { + 'marc_subfield_structures.frameworkcode' => $frameworkcode, ( defined $tagfield ? ( 'marc_subfield_structures.tagfield' => $tagfield ) : () ), ( defined $tagsubfield ? ( 'marc_subfield_structures.tagsubfield' => $tagsubfield ) : () ), }, { - join => { category => 'marc_subfield_structures' }, + join => { category => 'marc_subfield_structures' }, order_by => [ 'category', 'lib', 'lib_opac' ], } ); @@ -60,18 +60,20 @@ sub search_by_marc_field { sub search_by_koha_field { my ( $self, $params ) = @_; - my $frameworkcode = $params->{frameworkcode} || ''; - my $kohafield = $params->{kohafield}; - my $category = $params->{category}; + my $frameworkcode = $params->{frameworkcode} || ''; + my $kohafield = $params->{kohafield}; + my $category = $params->{category}; return unless $kohafield; return $self->SUPER::search( - { 'marc_subfield_structures.frameworkcode' => $frameworkcode, + { + 'marc_subfield_structures.frameworkcode' => $frameworkcode, 'marc_subfield_structures.kohafield' => $kohafield, - ( defined $category ? ( category_name => $category ) : () ), + ( defined $category ? ( category_name => $category ) : () ), }, - { join => { category => 'marc_subfield_structures' }, + { + join => { category => 'marc_subfield_structures' }, distinct => 1, order_by => [ 'category', 'lib', 'lib_opac' ], } @@ -85,11 +87,13 @@ sub find_by_koha_field { my $authorised_value = $params->{authorised_value}; my $av = $self->SUPER::search( - { 'marc_subfield_structures.frameworkcode' => $frameworkcode, + { + 'marc_subfield_structures.frameworkcode' => $frameworkcode, 'marc_subfield_structures.kohafield' => $kohafield, 'me.authorised_value' => $authorised_value, }, - { join => { category => 'marc_subfield_structures' }, + { + join => { category => 'marc_subfield_structures' }, distinct => 1, } ); @@ -110,7 +114,7 @@ sub get_description_by_koha_field { return $cached if $cached; my $av = $self->find_by_koha_field($params); - if ( ! defined $av ){ + if ( !defined $av ) { $memory_cache->set_in_cache( $cache_key, {} ); return {}; } @@ -122,7 +126,7 @@ sub get_description_by_koha_field { sub get_descriptions_by_koha_field { my ( $self, $params ) = @_; my $frameworkcode = $params->{frameworkcode} || ''; - my $kohafield = $params->{kohafield}; + my $kohafield = $params->{kohafield}; my $memory_cache = Koha::Cache::Memory::Lite->get_instance; my $cache_key = "AV_descriptions:$frameworkcode:$kohafield"; @@ -174,11 +178,11 @@ sub get_descriptions_by_marc_field { } sub categories { - my ( $self ) = @_; + my ($self) = @_; my $rs = $self->_resultset->search( undef, { - select => ['category'], + select => ['category'], distinct => 1, order_by => 'category', }, diff --git a/Koha/Authorities.pm b/Koha/Authorities.pm index 9d29346787..7b1c10db8c 100644 --- a/Koha/Authorities.pm +++ b/Koha/Authorities.pm @@ -19,7 +19,6 @@ package Koha::Authorities; use Modern::Perl; - use Koha::Database; use Koha::Authority; @@ -50,9 +49,9 @@ sub get_usage_count { my ( $class, $params ) = @_; my $authid = $params->{authid} || return; - my $searcher = Koha::SearchEngine::Search->new({ index => $Koha::SearchEngine::BIBLIOS_INDEX }); + my $searcher = Koha::SearchEngine::Search->new( { index => $Koha::SearchEngine::BIBLIOS_INDEX } ); my ( $err, $result, $count ) = $searcher->simple_search_compat( 'an:' . $authid, 0, 0 ); - if( $err ) { + if ($err) { warn "Error: $err from search for " . $authid; return; } @@ -76,18 +75,20 @@ sub linked_biblionumbers { my ( $self, $params ) = @_; my $authid = $params->{authid} || return; - my $searcher = Koha::SearchEngine::Search->new({ index => $Koha::SearchEngine::BIBLIOS_INDEX }); - # if max_results is undefined, we will get all results - my ( $err, $result, $count ) = $searcher->simple_search_compat( 'an:' . $authid, $params->{offset} // 0, $params->{max_results} ); + my $searcher = Koha::SearchEngine::Search->new( { index => $Koha::SearchEngine::BIBLIOS_INDEX } ); - if( $err ) { + # if max_results is undefined, we will get all results + my ( $err, $result, $count ) = + $searcher->simple_search_compat( 'an:' . $authid, $params->{offset} // 0, $params->{max_results} ); + + if ($err) { warn "Error: $err from search for " . $authid; return; } my @biblionumbers; - foreach my $res ( @$result ) { - my $bibno = $searcher->extract_biblionumber( $res ); + foreach my $res (@$result) { + my $bibno = $searcher->extract_biblionumber($res); push @biblionumbers, $bibno if $bibno; } return @biblionumbers; diff --git a/Koha/Authority.pm b/Koha/Authority.pm index 5cfc806b09..65c843408d 100644 --- a/Koha/Authority.pm +++ b/Koha/Authority.pm @@ -43,8 +43,8 @@ Koha::Authority - Koha Authority Object class =cut sub get_usage_count { - my ( $self ) = @_; - return Koha::Authorities->get_usage_count({ authid => $self->authid }); + my ($self) = @_; + return Koha::Authorities->get_usage_count( { authid => $self->authid } ); } =head3 linked_biblionumbers @@ -60,7 +60,7 @@ sub get_usage_count { sub linked_biblionumbers { my ( $self, $params ) = @_; $params->{authid} = $self->authid; - return Koha::Authorities->linked_biblionumbers( $params ); + return Koha::Authorities->linked_biblionumbers($params); } =head3 heading_object @@ -116,29 +116,32 @@ sub heading_object { sub controlled_indicators { my ( $self, $params ) = @_; - my $tag = $params->{biblio_tag} // q{}; + my $tag = $params->{biblio_tag} // q{}; my $record = $params->{record}; - my $flavour = C4::Context->preference('marcflavour') eq 'UNIMARC' + my $flavour = + C4::Context->preference('marcflavour') eq 'UNIMARC' ? 'UNIMARCAUTH' : 'MARC21'; - if( !$record ) { + if ( !$record ) { $record = $self->record; } - if( !$self->{_report_tag} ) { + if ( !$self->{_report_tag} ) { my $authtype = Koha::Authority::Types->find( $self->authtypecode ); - return {} if !$authtype; # very exceptional + return {} if !$authtype; # very exceptional $self->{_report_tag} = $authtype->auth_tag_to_report; } $self->{_ControlledInds} //= Koha::Authority::ControlledIndicators->new; - return $self->{_ControlledInds}->get({ - auth_record => $record, - report_tag => $self->{_report_tag}, - biblio_tag => $tag, - flavour => $flavour, - }); + return $self->{_ControlledInds}->get( + { + auth_record => $record, + report_tag => $self->{_report_tag}, + biblio_tag => $tag, + flavour => $flavour, + } + ); } =head3 get_identifiers_and_information @@ -255,7 +258,6 @@ sub get_identifiers_and_information { return $information; } - =head3 record my $record = $authority->record() @@ -265,7 +267,7 @@ Return the MARC::Record for this authority =cut sub record { - my ( $self ) = @_; + my ($self) = @_; my $flavour = $self->record_schema; return MARC::Record->new_from_xml( $self->marcxml, 'UTF-8', $flavour ); @@ -280,11 +282,11 @@ Returns the record schema (MARC21 or UNIMARCAUTH). =cut sub record_schema { - my ( $self ) = @_; + my ($self) = @_; return C4::Context->preference('marcflavour') eq 'UNIMARC' - ? 'UNIMARCAUTH' - : 'MARC21'; + ? 'UNIMARCAUTH' + : 'MARC21'; } =head3 to_api_mapping diff --git a/Koha/Authority/ControlledIndicators.pm b/Koha/Authority/ControlledIndicators.pm index ae43758360..f1f59f8447 100644 --- a/Koha/Authority/ControlledIndicators.pm +++ b/Koha/Authority/ControlledIndicators.pm @@ -55,9 +55,9 @@ sub new { sub get { my ( $self, $params ) = @_; - my $flavour = $params->{flavour} // q{}; - my $tag = $params->{biblio_tag} // q{}; - my $record = $params->{auth_record}; + my $flavour = $params->{flavour} // q{}; + my $tag = $params->{biblio_tag} // q{}; + my $record = $params->{auth_record}; my $report_tag = $params->{report_tag} // q{}; $flavour = uc($flavour); @@ -66,25 +66,23 @@ sub get { $self->{_parsed} //= _load_pref(); my $result = {}; return $result if !exists $self->{_parsed}->{$flavour}; - my $rule = $self->{_parsed}->{$flavour}->{$tag} // - $self->{_parsed}->{$flavour}->{'*'} // - {}; - my $report_fld = $record ? $record->field( $report_tag ) : undef; + my $rule = $self->{_parsed}->{$flavour}->{$tag} // $self->{_parsed}->{$flavour}->{'*'} // {}; + my $report_fld = $record ? $record->field($report_tag) : undef; foreach my $ind ( 'ind1', 'ind2' ) { - if( exists $rule->{$ind} ) { - if( !$rule->{$ind} ) { - $result->{$ind} = $rule->{$ind}; # undef or empty string - } elsif( $rule->{$ind} eq 'auth1' ) { + if ( exists $rule->{$ind} ) { + if ( !$rule->{$ind} ) { + $result->{$ind} = $rule->{$ind}; # undef or empty string + } elsif ( $rule->{$ind} eq 'auth1' ) { $result->{$ind} = $report_fld->indicator(1) if $report_fld; - } elsif( $rule->{$ind} eq 'auth2' ) { + } elsif ( $rule->{$ind} eq 'auth2' ) { $result->{$ind} = $report_fld->indicator(2) if $report_fld; - } elsif( $rule->{$ind} eq 'thesaurus' ) { - my @info = _thesaurus_info( $record ); + } elsif ( $rule->{$ind} eq 'thesaurus' ) { + my @info = _thesaurus_info($record); $result->{$ind} = $info[0]; $result->{sub2} = $info[1]; } else { - $result->{$ind} = substr( $rule->{$ind}, 0, 1); + $result->{$ind} = substr( $rule->{$ind}, 0, 1 ); } } } @@ -93,24 +91,25 @@ sub get { } sub _load_pref { - my $pref = C4::Context->preference('AuthorityControlledIndicators') // q{}; + my $pref = C4::Context->preference('AuthorityControlledIndicators') // q{}; my @lines = split /\r?\n/, $pref; my $res = {}; foreach my $line (@lines) { $line =~ s/^\s*|\s*$//g; next if $line =~ /^#/; + # line should be of the form: marcflavour,fld,ind1:val,ind2:val my @temp = split /\s*,\s*/, $line; next if @temp < 3; - my $flavour = uc($temp[0]); + my $flavour = uc( $temp[0] ); $flavour = 'UNIMARC' if $flavour eq 'UNIMARCAUTH'; next if $temp[1] !~ /(\d{3}|\*)/; my $tag = $1; - if( $temp[2] =~ /ind1\s*:\s*(.*)/ ) { + if ( $temp[2] =~ /ind1\s*:\s*(.*)/ ) { $res->{$flavour}->{$tag}->{ind1} = $1; } - if( $temp[3] && $temp[3] =~ /ind2\s*:\s*(.*)/ ) { + if ( $temp[3] && $temp[3] =~ /ind2\s*:\s*(.*)/ ) { $res->{$flavour}->{$tag}->{ind2} = $1; } } @@ -118,25 +117,27 @@ sub _load_pref { } sub _thesaurus_info { + # This sub is triggered by the term 'thesaurus' in the controlling pref. # The indicator of some MARC21 fields (like 600 ind2) is controlled by # authority field 008/11 and 040$f. Additionally, it may also control $2. - my ( $record ) = @_; - my $code = $record->field('008') - ? substr($record->field('008')->data, 11, 1) + my ($record) = @_; + my $code = + $record->field('008') + ? substr( $record->field('008')->data, 11, 1 ) : q{}; my %thes_mapping = ( a => 0, b => 1, c => 2, d => 3, k => 5, n => 4, r => 7, s => 7, v => 6, z => 7, '|' => 4 ); - my $ind = $thes_mapping{ $code } // '4'; + my $ind = $thes_mapping{$code} // '4'; # Determine optional subfield $2 my $sub2; - if( $ind eq '7' ) { + if ( $ind eq '7' ) { + # Important now to return a defined value - $sub2 = $code eq 'r' - ? 'aat' - : $code eq 's' - ? 'sears' - : $code eq 'z' # pick from 040$f + $sub2 = + $code eq 'r' ? 'aat' + : $code eq 's' ? 'sears' + : $code eq 'z' # pick from 040$f ? $record->subfield( '040', 'f' ) // q{} : q{}; } diff --git a/Koha/Authority/MergeRequest.pm b/Koha/Authority/MergeRequest.pm index ec12fea95d..8c11e203a6 100644 --- a/Koha/Authority/MergeRequest.pm +++ b/Koha/Authority/MergeRequest.pm @@ -60,13 +60,14 @@ Description sub new { my ( $class, $params ) = @_; my $oldrecord = delete $params->{oldrecord}; - delete $params->{reportxml}; # just making sure it is empty - my $self = $class->SUPER::new( $params ); + delete $params->{reportxml}; # just making sure it is empty + my $self = $class->SUPER::new($params); - if( $self->authid && $oldrecord ) { + if ( $self->authid && $oldrecord ) { my $auth = Koha::Authorities->find( $self->authid ); - my $type = $auth ? Koha::Authority::Types->find($auth->authtypecode) : undef; - $self->reportxml( $self->reporting_tag_xml({ record => $oldrecord, tag => $type->auth_tag_to_report })) if $type; + my $type = $auth ? Koha::Authority::Types->find( $auth->authtypecode ) : undef; + $self->reportxml( $self->reporting_tag_xml( { record => $oldrecord, tag => $type->auth_tag_to_report } ) ) + if $type; } return $self; } @@ -80,7 +81,7 @@ sub new { =cut sub oldmarc { - my ( $self ) = @_; + my ($self) = @_; return if !$self->reportxml; return MARC::Record->new_from_xml( $self->reportxml, 'UTF-8' ); } @@ -100,23 +101,23 @@ sub reporting_tag_xml { return if !$params->{record} || !$params->{tag}; my $newrecord = MARC::Record->new; - $newrecord->encoding( 'UTF-8' ); + $newrecord->encoding('UTF-8'); my $reportfield = $params->{record}->field( $params->{tag} ); return if !$reportfield; # For UNIMARC we need a field 100 that includes the encoding # at position 13 and 14 - if( C4::Context->preference('marcflavour') eq 'UNIMARC' ) { + if ( C4::Context->preference('marcflavour') eq 'UNIMARC' ) { $newrecord->append_fields( - MARC::Field->new( '100', '', '', a => ' 'x13 . '50' ), + MARC::Field->new( '100', '', '', a => ' ' x 13 . '50' ), ); } - $newrecord->append_fields( $reportfield ); + $newrecord->append_fields($reportfield); return $newrecord->as_xml( - C4::Context->preference('marcflavour') eq 'UNIMARC' ? - 'UNIMARCAUTH' : - 'MARC21' + C4::Context->preference('marcflavour') eq 'UNIMARC' + ? 'UNIMARCAUTH' + : 'MARC21' ); } diff --git a/Koha/Authority/MergeRequests.pm b/Koha/Authority/MergeRequests.pm index 481118e0f5..24930ab702 100644 --- a/Koha/Authority/MergeRequests.pm +++ b/Koha/Authority/MergeRequests.pm @@ -60,21 +60,25 @@ sub cron_cleanup { my ( $class_or_self, $params ) = @_; my $reset_hours = $params->{reset_hours} || 1; my $remove_days = $params->{remove_days} || 30; - my $parser = Koha::Database->new->schema->storage->datetime_parser; + my $parser = Koha::Database->new->schema->storage->datetime_parser; my $dt = dt_from_string; $dt->subtract( hours => $reset_hours ); - $class_or_self->search({ - done => 2, - timestamp => { '<' => $parser->format_datetime($dt) }, - })->update({ done => 0 }); + $class_or_self->search( + { + done => 2, + timestamp => { '<' => $parser->format_datetime($dt) }, + } + )->update( { done => 0 } ); $dt = dt_from_string; $dt->subtract( days => $remove_days ); - $class_or_self->search({ - done => 1, - timestamp => { '<' => $parser->format_datetime($dt) }, - })->delete; + $class_or_self->search( + { + done => 1, + timestamp => { '<' => $parser->format_datetime($dt) }, + } + )->delete; } =head3 _type diff --git a/Koha/Authority/Type.pm b/Koha/Authority/Type.pm index 7c6327e86b..7ec7283db5 100644 --- a/Koha/Authority/Type.pm +++ b/Koha/Authority/Type.pm @@ -17,7 +17,6 @@ package Koha::Authority::Type; use Modern::Perl; - use Koha::Database; use base qw(Koha::Object); @@ -33,7 +32,7 @@ Koha::Authority::Type - Koha Authority Type Object class =cut sub auth_tag_structures { - my ( $self ) = @_; + my ($self) = @_; return $self->_result->auth_tag_structures; } diff --git a/Koha/Authority/Types.pm b/Koha/Authority/Types.pm index aa399b4dcc..3ebae36a15 100644 --- a/Koha/Authority/Types.pm +++ b/Koha/Authority/Types.pm @@ -17,7 +17,6 @@ package Koha::Authority::Types; use Modern::Perl; - use Koha::Database; use Koha::Authority::Type; diff --git a/Koha/BackgroundJob.pm b/Koha/BackgroundJob.pm index 4914971dbf..211e2e32f3 100644 --- a/Koha/BackgroundJob.pm +++ b/Koha/BackgroundJob.pm @@ -62,7 +62,7 @@ Connect to the message broker using default guest/guest credential =cut sub connect { - my ( $self ); + my ($self); my $notification_method = C4::Context->preference('JobsNotificationMethod') // 'STOMP'; @@ -72,24 +72,24 @@ sub connect { my $hostname = $ENV{KOHA_STOMP_HOSTNAME} // 'localhost'; my $port = $ENV{KOHA_STOMP_PORT} // '61613'; - my $config = C4::Context->config('message_broker'); + my $config = C4::Context->config('message_broker'); my $credentials = { - login => 'guest', + login => 'guest', passcode => 'guest', }; - if ($config){ - $hostname = $config->{hostname} if $config->{hostname}; - $port = $config->{port} if $config->{port}; - $credentials->{login} = $config->{username} if $config->{username}; + if ($config) { + $hostname = $config->{hostname} if $config->{hostname}; + $port = $config->{port} if $config->{port}; + $credentials->{login} = $config->{username} if $config->{username}; $credentials->{passcode} = $config->{password} if $config->{password}; - $credentials->{host} = $config->{vhost} if $config->{vhost}; + $credentials->{host} = $config->{vhost} if $config->{vhost}; } my $stomp; try { $stomp = Net::Stomp->new( { hostname => $hostname, port => $port } ); - $stomp->connect( $credentials ); + $stomp->connect($credentials); } catch { warn "Cannot connect to broker " . $_; $stomp = undef; @@ -116,13 +116,13 @@ sub enqueue { my $job_size = $params->{job_size}; my $job_args = $params->{job_args}; my $job_context = $params->{job_context} // C4::Context->userenv; - my $job_queue = $params->{job_queue} // 'default'; - my $json = $self->json; + my $job_queue = $params->{job_queue} // 'default'; + my $json = $self->json; - my $borrowernumber = (C4::Context->userenv) ? C4::Context->userenv->{number} : undef; + my $borrowernumber = ( C4::Context->userenv ) ? C4::Context->userenv->{number} : undef; $job_context->{interface} = C4::Context->interface; my $json_context = $json->encode($job_context); - my $json_args = $json->encode($job_args); + my $json_args = $json->encode($job_args); $self->set( { @@ -148,11 +148,11 @@ sub enqueue { # But to do so it needs to be created on the server => much more work when a new Koha instance is created. # Also, here we just want the Koha instance's name, but it's not in the config... # Picking a random id (memcached_namespace) from the config - my $namespace = C4::Context->config('memcached_namespace'); - my $encoded_args = Encode::encode_utf8( $json_args ); # FIXME We should better leave this to Net::Stomp? - my $destination = sprintf( "/queue/%s-%s", $namespace, $job_queue ); + my $namespace = C4::Context->config('memcached_namespace'); + my $encoded_args = Encode::encode_utf8($json_args); # FIXME We should better leave this to Net::Stomp? + my $destination = sprintf( "/queue/%s-%s", $namespace, $job_queue ); $conn->send_with_receipt( { destination => $destination, body => $encoded_args, persistent => 'true' } ) - or Koha::Exceptions::BackgroundJob->throw('Job has not been enqueued'); + or Koha::Exceptions::BackgroundJob->throw('Job has not been enqueued'); } catch { $self->status('failed')->store; if ( ref($_) eq 'Koha::Exceptions::BackgroundJob' ) { @@ -187,7 +187,7 @@ sub process { $args ||= {}; if ( $self->context ) { - my $context = $self->json->decode($self->context); + my $context = $self->json->decode( $self->context ); C4::Context->interface( $context->{interface} ); C4::Context->set_userenv( $context->{number}, $context->{id}, @@ -198,12 +198,11 @@ sub process { $context->{desk_id}, $context->{desk_name}, $context->{register_id}, $context->{register_name} ); - } - else { - Koha::Logger->get->warn("A background job didn't have context defined (" . $self->id . ")"); + } else { + Koha::Logger->get->warn( "A background job didn't have context defined (" . $self->id . ")" ); } - return $derived_class->process( $args ); + return $derived_class->process($args); } =head3 start @@ -285,8 +284,8 @@ done later. =cut sub json { - my ( $self ) = @_; - $self->{_json} //= JSON->new->utf8(0); # TODO Should we allow_nonref ? + my ($self) = @_; + $self->{_json} //= JSON->new->utf8(0); # TODO Should we allow_nonref ? return $self->{_json}; } @@ -333,10 +332,10 @@ Messages let during the processing of the job. =cut sub messages { - my ( $self ) = @_; + my ($self) = @_; my @messages; - my $data_dump = $self->json->decode($self->data); + my $data_dump = $self->json->decode( $self->data ); if ( exists $data_dump->{messages} ) { @messages = @{ $data_dump->{messages} }; } @@ -351,9 +350,9 @@ Report of the job. =cut sub report { - my ( $self ) = @_; + my ($self) = @_; - my $data_dump = $self->json->decode($self->data); + my $data_dump = $self->json->decode( $self->data ); return $data_dump->{report} || {}; } @@ -364,7 +363,7 @@ Build additional variables for the job detail view. =cut sub additional_report { - my ( $self ) = @_; + my ($self) = @_; return {} if ref($self) ne 'Koha::BackgroundJob'; @@ -380,7 +379,7 @@ Cancel a job. =cut sub cancel { - my ( $self ) = @_; + my ($self) = @_; $self->status('cancelled')->store; } @@ -391,12 +390,12 @@ sub cancel { =cut sub _derived_class { - my ( $self ) = @_; + my ($self) = @_; my $job_type = $self->type; my $class = $self->type_to_class_mapping->{$job_type}; - Koha::Exception->throw($job_type . ' is not a valid job_type') + Koha::Exception->throw( $job_type . ' is not a valid job_type' ) unless $class; eval "require $class"; @@ -417,8 +416,8 @@ sub type_to_class_mapping { my $plugins_mapping = ( C4::Context->config("enable_plugins") ) ? $self->plugin_types_to_classes : {}; return ($plugins_mapping) - ? { %{ $self->core_types_to_classes }, %$plugins_mapping } - : $self->core_types_to_classes; + ? { %{ $self->core_types_to_classes }, %$plugins_mapping } + : $self->core_types_to_classes; } =head3 core_types_to_classes @@ -471,10 +470,9 @@ sub plugin_types_to_classes { my $metadata = $plugin->get_metadata; unless ( $metadata->{namespace} ) { - Koha::Logger->get->warn( - q{A plugin includes the 'background_tasks' method, } - . q{but doesn't provide the required 'namespace' } - . qq{method ($plugin->{class})} ); + Koha::Logger->get->warn( q{A plugin includes the 'background_tasks' method, } + . q{but doesn't provide the required 'namespace' } + . qq{method ($plugin->{class})} ); next; } @@ -508,10 +506,10 @@ suitable for API output. sub to_api { my ( $self, $params ) = @_; - my $json = $self->SUPER::to_api( $params ); + my $json = $self->SUPER::to_api($params); - $json->{context} = $self->json->decode($self->context) - if defined $self->context; + $json->{context} = $self->json->decode( $self->context ) + if defined $self->context; $json->{data} = $self->decoded_data; return $json; diff --git a/Koha/BackgroundJob/BatchCancelHold.pm b/Koha/BackgroundJob/BatchCancelHold.pm index d302f972a8..b94adaeee6 100644 --- a/Koha/BackgroundJob/BatchCancelHold.pm +++ b/Koha/BackgroundJob/BatchCancelHold.pm @@ -64,7 +64,7 @@ sub process { total_success => 0, }; my @messages; - HOLD_IDS: for my $hold_id ( sort { $a <=> $b } @hold_ids ) { +HOLD_IDS: for my $hold_id ( sort { $a <=> $b } @hold_ids ) { next unless $hold_id; # Authorities @@ -79,26 +79,25 @@ sub process { if ( $error and $error != $hold or $@ ) { push @messages, - { - type => 'error', - code => 'hold_not_cancelled', - patron_id => defined $patron ? $patron->borrowernumber : '', - biblio_id => defined $biblio ? $biblio->biblionumber : '', - hold_id => $hold_id, - error => defined $hold + { + type => 'error', + code => 'hold_not_cancelled', + patron_id => defined $patron ? $patron->borrowernumber : '', + biblio_id => defined $biblio ? $biblio->biblionumber : '', + hold_id => $hold_id, + error => defined $hold ? ( $@ ? "$@" : 0 ) : 'hold_not_found', - }; - } - else { + }; + } else { push @messages, - { + { type => 'success', code => 'hold_cancelled', patron_id => $patron->borrowernumber, - biblio_id => $biblio->biblionumber, - hold_id => $hold_id, - }; + biblio_id => $biblio->biblionumber, + hold_id => $hold_id, + }; $report->{total_success}++; } $self->step; @@ -106,9 +105,9 @@ sub process { my $data = $self->decoded_data; $data->{messages} = \@messages; - $data->{report} = $report; + $data->{report} = $report; - $self->finish( $data ); + $self->finish($data); } =head3 enqueue @@ -144,9 +143,9 @@ sub additional_report { my ( $self, $args ) = @_; my $messages = $self->messages; - for my $m ( @$messages ) { - $m->{patron} = Koha::Patrons->find($m->{patron_id}); - $m->{biblio} = Koha::Biblios->find($m->{biblio_id}); + for my $m (@$messages) { + $m->{patron} = Koha::Patrons->find( $m->{patron_id} ); + $m->{biblio} = Koha::Biblios->find( $m->{biblio_id} ); } return { report_messages => $messages }; } diff --git a/Koha/BackgroundJob/BatchDeleteAuthority.pm b/Koha/BackgroundJob/BatchDeleteAuthority.pm index 68d668208c..bab15e1645 100644 --- a/Koha/BackgroundJob/BatchDeleteAuthority.pm +++ b/Koha/BackgroundJob/BatchDeleteAuthority.pm @@ -25,7 +25,7 @@ sub process { $self->start; - my $mmtid = $args->{mmtid}; + my $mmtid = $args->{mmtid}; my @record_ids = @{ $args->{record_ids} }; my $report = { @@ -34,7 +34,7 @@ sub process { }; my @messages; my $schema = Koha::Database->new->schema; - RECORD_IDS: for my $record_id ( sort { $a <=> $b } @record_ids ) { +RECORD_IDS: for my $record_id ( sort { $a <=> $b } @record_ids ) { last if $self->get_from_storage->status eq 'cancelled'; @@ -43,23 +43,20 @@ sub process { $schema->storage->txn_begin; my $authid = $record_id; - eval { - C4::AuthoritiesMarc::DelAuthority( - { authid => $authid, skip_record_index => 1 } ); - }; - if ( $@ ) { + eval { C4::AuthoritiesMarc::DelAuthority( { authid => $authid, skip_record_index => 1 } ); }; + if ($@) { push @messages, { - type => 'error', - code => 'authority_not_deleted', + type => 'error', + code => 'authority_not_deleted', authid => $authid, - error => "$@", + error => "$@", }; $schema->storage->txn_rollback; next; } else { push @messages, { - type => 'success', - code => 'authority_deleted', + type => 'success', + code => 'authority_deleted', authid => $authid, }; $report->{total_success}++; @@ -70,34 +67,35 @@ sub process { } my @deleted_authids = - map { $_->{code} eq 'authority_deleted' ? $_->{authid} : () } - @messages; + map { $_->{code} eq 'authority_deleted' ? $_->{authid} : () } @messages; - if ( @deleted_authids ) { - my $indexer = Koha::SearchEngine::Indexer->new({ index => $Koha::SearchEngine::AUTHORITIES_INDEX }); + if (@deleted_authids) { + my $indexer = Koha::SearchEngine::Indexer->new( { index => $Koha::SearchEngine::AUTHORITIES_INDEX } ); $indexer->index_records( \@deleted_authids, "recordDelete", "authorityserver" ); } my $data = $self->decoded_data; $data->{messages} = \@messages; - $data->{report} = $report; + $data->{report} = $report; - $self->finish( $data ); + $self->finish($data); } sub enqueue { - my ( $self, $args) = @_; + my ( $self, $args ) = @_; # TODO Raise exception instead return unless exists $args->{record_ids}; my @record_ids = @{ $args->{record_ids} }; - $self->SUPER::enqueue({ - job_size => scalar @record_ids, - job_args => {record_ids => \@record_ids,}, - job_queue => 'long_tasks', - }); + $self->SUPER::enqueue( + { + job_size => scalar @record_ids, + job_args => { record_ids => \@record_ids, }, + job_queue => 'long_tasks', + } + ); } 1; diff --git a/Koha/BackgroundJob/BatchDeleteBiblio.pm b/Koha/BackgroundJob/BatchDeleteBiblio.pm index 2054a726fe..3bc7f7336e 100644 --- a/Koha/BackgroundJob/BatchDeleteBiblio.pm +++ b/Koha/BackgroundJob/BatchDeleteBiblio.pm @@ -49,7 +49,7 @@ sub process { $self->start; - my $mmtid = $args->{mmtid}; + my $mmtid = $args->{mmtid}; my @record_ids = @{ $args->{record_ids} }; my $report = { @@ -58,7 +58,7 @@ sub process { }; my @messages; my $schema = Koha::Database->new->schema; - RECORD_IDS: for my $record_id ( sort { $a <=> $b } @record_ids ) { +RECORD_IDS: for my $record_id ( sort { $a <=> $b } @record_ids ) { last if $self->get_from_storage->status eq 'cancelled'; @@ -67,15 +67,16 @@ sub process { $schema->storage->txn_begin; my $biblionumber = $record_id; + # First, checking if issues exist. # If yes, nothing to do - my $biblio = Koha::Biblios->find( $biblionumber ); + my $biblio = Koha::Biblios->find($biblionumber); # TODO Replace with $biblio->get_issues->count - if ( C4::Biblio::CountItemsIssued( $biblionumber ) ) { + if ( C4::Biblio::CountItemsIssued($biblionumber) ) { push @messages, { - type => 'warning', - code => 'item_issued', + type => 'warning', + code => 'item_issued', biblionumber => $biblionumber, }; $schema->storage->txn_rollback; @@ -87,16 +88,14 @@ sub process { # Cancel reserves my $holds = $biblio->holds; while ( my $hold = $holds->next ) { - eval{ - $hold->cancel({ skip_holds_queue => 1 }); - }; - if ( $@ ) { + eval { $hold->cancel( { skip_holds_queue => 1 } ); }; + if ($@) { push @messages, { - type => 'error', - code => 'reserve_not_cancelled', + type => 'error', + code => 'reserve_not_cancelled', biblionumber => $biblionumber, - reserve_id => $hold->reserve_id, - error => "$@", + reserve_id => $hold->reserve_id, + error => "$@", }; $schema->storage->txn_rollback; @@ -106,16 +105,16 @@ sub process { } # Delete items - my $items = Koha::Items->search({ biblionumber => $biblionumber }); + my $items = Koha::Items->search( { biblionumber => $biblionumber } ); while ( my $item = $items->next ) { - my $deleted = $item->safe_delete({ skip_record_index => 1, skip_holds_queue => 1 }); - unless ( $deleted ) { + my $deleted = $item->safe_delete( { skip_record_index => 1, skip_holds_queue => 1 } ); + unless ($deleted) { push @messages, { - type => 'error', - code => 'item_not_deleted', + type => 'error', + code => 'item_not_deleted', biblionumber => $biblionumber, - itemnumber => $item->itemnumber, - error => @{$deleted->messages}[0]->message, + itemnumber => $item->itemnumber, + error => @{ $deleted->messages }[0]->message, }; $schema->storage->txn_rollback; @@ -132,15 +131,13 @@ sub process { } # Finally, delete the biblio - my $error = eval { - C4::Biblio::DelBiblio( $biblionumber, { skip_record_index => 1, skip_holds_queue => 1 } ); - }; + my $error = eval { C4::Biblio::DelBiblio( $biblionumber, { skip_record_index => 1, skip_holds_queue => 1 } ); }; if ( $error or $@ ) { push @messages, { - type => 'error', - code => 'biblio_not_deleted', + type => 'error', + code => 'biblio_not_deleted', biblionumber => $biblionumber, - error => ($@ ? $@ : $error), + error => ( $@ ? $@ : $error ), }; $schema->storage->txn_rollback; @@ -149,8 +146,8 @@ sub process { } push @messages, { - type => 'success', - code => 'biblio_deleted', + type => 'success', + code => 'biblio_deleted', biblionumber => $biblionumber, }; $report->{total_success}++; @@ -160,25 +157,21 @@ sub process { } my @deleted_biblionumbers = - map { $_->{code} eq 'biblio_deleted' ? $_->{biblionumber} : () } - @messages; + map { $_->{code} eq 'biblio_deleted' ? $_->{biblionumber} : () } @messages; - if ( @deleted_biblionumbers ) { - my $indexer = Koha::SearchEngine::Indexer->new({ index => $Koha::SearchEngine::BIBLIOS_INDEX }); + if (@deleted_biblionumbers) { + my $indexer = Koha::SearchEngine::Indexer->new( { index => $Koha::SearchEngine::BIBLIOS_INDEX } ); $indexer->index_records( \@deleted_biblionumbers, "recordDelete", "biblioserver" ); - Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue->new->enqueue( - { - biblio_ids => \@deleted_biblionumbers - } - ) if C4::Context->preference('RealTimeHoldsQueue'); + Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue->new->enqueue( { biblio_ids => \@deleted_biblionumbers } ) + if C4::Context->preference('RealTimeHoldsQueue'); } my $data = $self->decoded_data; $data->{messages} = \@messages; - $data->{report} = $report; + $data->{report} = $report; - $self->finish( $data ); + $self->finish($data); } =head3 enqueue @@ -188,18 +181,20 @@ Enqueue the new job =cut sub enqueue { - my ( $self, $args) = @_; + my ( $self, $args ) = @_; # TODO Raise exception instead return unless exists $args->{record_ids}; my @record_ids = @{ $args->{record_ids} }; - $self->SUPER::enqueue({ - job_size => scalar @record_ids, - job_args => {record_ids => \@record_ids,}, - job_queue => 'long_tasks', - }); + $self->SUPER::enqueue( + { + job_size => scalar @record_ids, + job_args => { record_ids => \@record_ids, }, + job_queue => 'long_tasks', + } + ); } 1; diff --git a/Koha/BackgroundJob/BatchDeleteItem.pm b/Koha/BackgroundJob/BatchDeleteItem.pm index 474450e57b..6533d9dc1a 100644 --- a/Koha/BackgroundJob/BatchDeleteItem.pm +++ b/Koha/BackgroundJob/BatchDeleteItem.pm @@ -90,8 +90,10 @@ sub process { }; my @messages; my $schema = Koha::Database->new->schema; - my ( @deleted_itemnumbers, @not_deleted_itemnumbers, - @deleted_biblionumbers ); + my ( + @deleted_itemnumbers, @not_deleted_itemnumbers, + @deleted_biblionumbers + ); try { my $schema = Koha::Database->new->schema; @@ -104,21 +106,21 @@ sub process { my $item = Koha::Items->find($record_id) || next; - my $return = $item->safe_delete({ skip_record_index => 1, skip_holds_queue => 1 }); - unless ( $return ) { + my $return = $item->safe_delete( { skip_record_index => 1, skip_holds_queue => 1 } ); + unless ($return) { # FIXME Do we need to rollback the whole transaction if a deletion failed? push @not_deleted_itemnumbers, $item->itemnumber; push @messages, - { + { type => 'error', code => 'item_not_deleted', itemnumber => $item->itemnumber, biblionumber => $item->biblionumber, barcode => $item->barcode, title => $item->biblio->title, - reason => @{$return->messages}[0]->message, - }; + reason => @{ $return->messages }[0]->message, + }; next; } @@ -133,11 +135,12 @@ sub process { # If there are no items left, delete the biblio my @updated_biblionumbers; for my $biblionumber ( uniq @biblionumbers ) { - my $items_count = - Koha::Biblios->find($biblionumber)->items->count; + my $items_count = Koha::Biblios->find($biblionumber)->items->count; if ( $delete_biblios && $items_count == 0 ) { - my $error = C4::Biblio::DelBiblio( $biblionumber, - { skip_record_index => 1, skip_holds_queue => 1 } ); + my $error = C4::Biblio::DelBiblio( + $biblionumber, + { skip_record_index => 1, skip_holds_queue => 1 } + ); unless ($error) { push @deleted_biblionumbers, $biblionumber; } @@ -147,48 +150,45 @@ sub process { } if (@deleted_biblionumbers) { - my $indexer = Koha::SearchEngine::Indexer->new( - { index => $Koha::SearchEngine::BIBLIOS_INDEX } ); + my $indexer = Koha::SearchEngine::Indexer->new( { index => $Koha::SearchEngine::BIBLIOS_INDEX } ); - $indexer->index_records( \@deleted_biblionumbers, - 'recordDelete', "biblioserver", undef ); + $indexer->index_records( + \@deleted_biblionumbers, + 'recordDelete', "biblioserver", undef + ); Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue->new->enqueue( - { - biblio_ids => \@deleted_biblionumbers - } - ) if C4::Context->preference('RealTimeHoldsQueue'); + { biblio_ids => \@deleted_biblionumbers } ) + if C4::Context->preference('RealTimeHoldsQueue'); } if (@updated_biblionumbers) { - my $indexer = Koha::SearchEngine::Indexer->new( - { index => $Koha::SearchEngine::BIBLIOS_INDEX } ); + my $indexer = Koha::SearchEngine::Indexer->new( { index => $Koha::SearchEngine::BIBLIOS_INDEX } ); - $indexer->index_records( \@updated_biblionumbers, - 'specialUpdate', "biblioserver", undef ); + $indexer->index_records( + \@updated_biblionumbers, + 'specialUpdate', "biblioserver", undef + ); Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue->new->enqueue( - { - biblio_ids => \@updated_biblionumbers - } - ) if C4::Context->preference('RealTimeHoldsQueue'); + { biblio_ids => \@updated_biblionumbers } ) + if C4::Context->preference('RealTimeHoldsQueue'); } } ); - } - catch { + } catch { warn $_; push @messages, - { + { type => 'error', code => 'unknown', error => $_, - }; + }; die "Something terrible has happened!" - if ( $_ =~ /Rollback failed/ ); # Rollback failed + if ( $_ =~ /Rollback failed/ ); # Rollback failed }; $report->{deleted_itemnumbers} = \@deleted_itemnumbers; @@ -197,9 +197,9 @@ sub process { my $data = $self->decoded_data; $data->{messages} = \@messages; - $data->{report} = $report; + $data->{report} = $report; - $self->finish( $data ); + $self->finish($data); } =head3 enqueue @@ -221,7 +221,7 @@ sub enqueue { # TODO Raise exception instead return unless exists $args->{record_ids}; - my @record_ids = @{ $args->{record_ids} }; + my @record_ids = @{ $args->{record_ids} }; my $delete_biblios = $args->{delete_biblios} || 0; $self->SUPER::enqueue( diff --git a/Koha/BackgroundJob/BatchUpdateAuthority.pm b/Koha/BackgroundJob/BatchUpdateAuthority.pm index d161187ebb..ef8d78d42e 100644 --- a/Koha/BackgroundJob/BatchUpdateAuthority.pm +++ b/Koha/BackgroundJob/BatchUpdateAuthority.pm @@ -18,7 +18,7 @@ package Koha::BackgroundJob::BatchUpdateAuthority; use Modern::Perl; use C4::MarcModificationTemplates qw( ModifyRecordWithTemplate ); -use C4::AuthoritiesMarc qw( ModAuthority ); +use C4::AuthoritiesMarc qw( ModAuthority ); use Koha::BackgroundJobs; use Koha::MetadataRecord::Authority; use Koha::SearchEngine; @@ -61,7 +61,7 @@ sub process { $self->start; - my $mmtid = $args->{mmtid}; + my $mmtid = $args->{mmtid}; my @record_ids = @{ $args->{record_ids} }; my $report = { @@ -69,27 +69,28 @@ sub process { total_success => 0, }; my @messages; - RECORD_IDS: for my $record_id ( sort { $a <=> $b } @record_ids ) { +RECORD_IDS: for my $record_id ( sort { $a <=> $b } @record_ids ) { next unless $record_id; + # Authorities my $authid = $record_id; - my $error = eval { - my $authority = Koha::MetadataRecord::Authority->get_from_authid( $authid ); - my $record = $authority->record; + my $error = eval { + my $authority = Koha::MetadataRecord::Authority->get_from_authid($authid); + my $record = $authority->record; ModifyRecordWithTemplate( $mmtid, $record ); ModAuthority( $authid, $record, $authority->authtypecode, { skip_record_index => 1 } ); }; if ( $error and $error != $authid or $@ ) { push @messages, { - type => 'error', - code => 'authority_not_modified', + type => 'error', + code => 'authority_not_modified', authid => $authid, - error => ($@ ? "$@" : 0), + error => ( $@ ? "$@" : 0 ), }; } else { push @messages, { - type => 'success', - code => 'authority_modified', + type => 'success', + code => 'authority_modified', authid => $authid, }; $report->{total_success}++; @@ -97,14 +98,14 @@ sub process { $self->step; } - my $indexer = Koha::SearchEngine::Indexer->new({ index => $Koha::SearchEngine::AUTHORITIES_INDEX }); + my $indexer = Koha::SearchEngine::Indexer->new( { index => $Koha::SearchEngine::AUTHORITIES_INDEX } ); $indexer->index_records( \@record_ids, "specialUpdate", "authorityserver" ); my $data = $self->decoded_data; $data->{messages} = \@messages; $data->{report} = $report; - $self->finish( $data ); + $self->finish($data); } @@ -115,20 +116,22 @@ Enqueue the new job =cut sub enqueue { - my ( $self, $args) = @_; + my ( $self, $args ) = @_; # TODO Raise exception instead return unless exists $args->{mmtid}; return unless exists $args->{record_ids}; - my $mmtid = $args->{mmtid}; + my $mmtid = $args->{mmtid}; my @record_ids = @{ $args->{record_ids} }; - $self->SUPER::enqueue({ - job_size => scalar @record_ids, - job_args => {mmtid => $mmtid, record_ids => \@record_ids,}, - job_queue => 'long_tasks', - }); + $self->SUPER::enqueue( + { + job_size => scalar @record_ids, + job_args => { mmtid => $mmtid, record_ids => \@record_ids, }, + job_queue => 'long_tasks', + } + ); } 1; diff --git a/Koha/BackgroundJob/BatchUpdateBiblio.pm b/Koha/BackgroundJob/BatchUpdateBiblio.pm index 64e429d0b7..af98fe0eb2 100644 --- a/Koha/BackgroundJob/BatchUpdateBiblio.pm +++ b/Koha/BackgroundJob/BatchUpdateBiblio.pm @@ -66,7 +66,7 @@ sub process { $self->start; - my $mmtid = $args->{mmtid}; + my $mmtid = $args->{mmtid}; my @record_ids = @{ $args->{record_ids} }; my $report = { @@ -74,7 +74,7 @@ sub process { total_success => 0, }; my @messages; - RECORD_IDS: for my $biblionumber ( sort { $a <=> $b } @record_ids ) { +RECORD_IDS: for my $biblionumber ( sort { $a <=> $b } @record_ids ) { last if $self->get_from_storage->status eq 'cancelled'; @@ -85,23 +85,28 @@ sub process { my $biblio = Koha::Biblios->find($biblionumber); my $record = $biblio->metadata->record; C4::MarcModificationTemplates::ModifyRecordWithTemplate( $mmtid, $record ); - my $frameworkcode = C4::Biblio::GetFrameworkCode( $biblionumber ); - C4::Biblio::ModBiblio( $record, $biblionumber, $frameworkcode, { - overlay_context => $args->{overlay_context}, - skip_record_index => 1, - }); + my $frameworkcode = C4::Biblio::GetFrameworkCode($biblionumber); + C4::Biblio::ModBiblio( + $record, + $biblionumber, + $frameworkcode, + { + overlay_context => $args->{overlay_context}, + skip_record_index => 1, + } + ); }; - if ( $error and $error != 1 or $@ ) { # ModBiblio returns 1 if everything as gone well + if ( $error and $error != 1 or $@ ) { # ModBiblio returns 1 if everything as gone well push @messages, { - type => 'error', - code => 'biblio_not_modified', + type => 'error', + code => 'biblio_not_modified', biblionumber => $biblionumber, - error => ($@ ? "$@" : $error), + error => ( $@ ? "$@" : $error ), }; } else { push @messages, { - type => 'success', - code => 'biblio_modified', + type => 'success', + code => 'biblio_modified', biblionumber => $biblionumber, }; $report->{total_success}++; @@ -110,14 +115,14 @@ sub process { $self->step; } - my $indexer = Koha::SearchEngine::Indexer->new({ index => $Koha::SearchEngine::BIBLIOS_INDEX }); + my $indexer = Koha::SearchEngine::Indexer->new( { index => $Koha::SearchEngine::BIBLIOS_INDEX } ); $indexer->index_records( \@record_ids, "specialUpdate", "biblioserver" ); my $data = $self->decoded_data; $data->{messages} = \@messages; - $data->{report} = $report; + $data->{report} = $report; - $self->finish( $data ); + $self->finish($data); } =head3 enqueue @@ -127,17 +132,19 @@ Enqueue the new job =cut sub enqueue { - my ( $self, $args) = @_; + my ( $self, $args ) = @_; # TODO Raise exception instead return unless exists $args->{mmtid}; return unless exists $args->{record_ids}; - $self->SUPER::enqueue({ - job_size => scalar @{$args->{record_ids}}, - job_args => $args, - job_queue => 'long_tasks', - }); + $self->SUPER::enqueue( + { + job_size => scalar @{ $args->{record_ids} }, + job_args => $args, + job_queue => 'long_tasks', + } + ); } =head3 additional_report diff --git a/Koha/BackgroundJob/BatchUpdateBiblioHoldsQueue.pm b/Koha/BackgroundJob/BatchUpdateBiblioHoldsQueue.pm index 4c64a61d1a..4a779f4c9c 100644 --- a/Koha/BackgroundJob/BatchUpdateBiblioHoldsQueue.pm +++ b/Koha/BackgroundJob/BatchUpdateBiblioHoldsQueue.pm @@ -22,8 +22,7 @@ use Try::Tiny; use Koha::Biblios; use Koha::Exceptions; -use C4::HoldsQueue - qw(load_branches_to_pull_from TransportCostMatrix update_queue_for_biblio); +use C4::HoldsQueue qw(load_branches_to_pull_from TransportCostMatrix update_queue_for_biblio); use base 'Koha::BackgroundJob'; @@ -69,8 +68,8 @@ sub process { }; my $use_transport_cost_matrix = C4::Context->preference("UseTransportCostMatrix"); - my $transport_cost_matrix = $use_transport_cost_matrix ? TransportCostMatrix() : undef; - my $branches_to_use = load_branches_to_pull_from($use_transport_cost_matrix); + my $transport_cost_matrix = $use_transport_cost_matrix ? TransportCostMatrix() : undef; + my $branches_to_use = load_branches_to_pull_from($use_transport_cost_matrix); my @messages; @@ -88,24 +87,23 @@ sub process { } ); push @messages, - { - type => 'success', - code => 'holds_queue_updated', - biblio_id => $biblio_id, - }; + { + type => 'success', + code => 'holds_queue_updated', + biblio_id => $biblio_id, + }; $report->{total_success}++; $schema->storage->txn_commit; - } - catch { + } catch { push @messages, - { + { type => 'error', code => 'holds_queue_update_error', biblio_id => $biblio_id, error => "$_", - }; + }; $schema->storage->txn_rollback; }; @@ -115,9 +113,9 @@ sub process { my $data = $self->decoded_data; $data->{messages} = \@messages; - $data->{report} = $report; + $data->{report} = $report; - $self->finish( $data ); + $self->finish($data); } =head3 enqueue @@ -131,9 +129,8 @@ sub enqueue { return if !C4::Context->preference('RealTimeHoldsQueue'); #TODO Remove check from callers - Koha::Exceptions::MissingParameter->throw( - "Missing biblio_ids parameter is mandatory") - unless exists $args->{biblio_ids}; + Koha::Exceptions::MissingParameter->throw("Missing biblio_ids parameter is mandatory") + unless exists $args->{biblio_ids}; my @biblio_ids = @{ $args->{biblio_ids} }; diff --git a/Koha/BackgroundJob/BatchUpdateItem.pm b/Koha/BackgroundJob/BatchUpdateItem.pm index 63f6f71d40..1158efd568 100644 --- a/Koha/BackgroundJob/BatchUpdateItem.pm +++ b/Koha/BackgroundJob/BatchUpdateItem.pm @@ -92,22 +92,21 @@ sub process { $self->start; - my @record_ids = @{ $args->{record_ids} }; - my $regex_mod = $args->{regex_mod}; - my $new_values = $args->{new_values}; - my $exclude_from_local_holds_priority = - $args->{exclude_from_local_holds_priority}; - my $mark_items_returned = - $args->{mark_items_returned}; + my @record_ids = @{ $args->{record_ids} }; + my $regex_mod = $args->{regex_mod}; + my $new_values = $args->{new_values}; + my $exclude_from_local_holds_priority = $args->{exclude_from_local_holds_priority}; + my $mark_items_returned = $args->{mark_items_returned}; my $report = { - total_records => scalar @record_ids, - modified_fields => 0, + total_records => scalar @record_ids, + modified_fields => 0, }; try { my ($results) = Koha::Items->search( { itemnumber => \@record_ids } )->batch_update( - { regex_mod => $regex_mod, + { + regex_mod => $regex_mod, new_values => $new_values, exclude_from_local_holds_priority => $exclude_from_local_holds_priority, mark_items_returned => $mark_items_returned, @@ -116,17 +115,16 @@ sub process { ); $report->{modified_itemnumbers} = $results->{modified_itemnumbers}; $report->{modified_fields} = $results->{modified_fields}; - } - catch { + } catch { warn $_; die "Something terrible has happened!" - if ( $_ =~ /Rollback failed/ ); # Rollback failed + if ( $_ =~ /Rollback failed/ ); # Rollback failed }; my $data = $self->decoded_data; $data->{report} = $report; - $self->finish( $data ); + $self->finish($data); } =head3 enqueue @@ -167,9 +165,7 @@ sub additional_report { if ( scalar(@$itemnumbers) > C4::Context->preference('MaxItemsToDisplayForBatchMod') ) { return { too_many_items_display => 1 }; } else { - my $items_table = - Koha::UI::Table::Builder::Items->new( { itemnumbers => $itemnumbers } ) - ->build_table; + my $items_table = Koha::UI::Table::Builder::Items->new( { itemnumbers => $itemnumbers } )->build_table; return { items => $items_table->{items}, diff --git a/Koha/BackgroundJob/CreateEHoldingsFromBiblios.pm b/Koha/BackgroundJob/CreateEHoldingsFromBiblios.pm index 9638c7fcd3..244818c551 100644 --- a/Koha/BackgroundJob/CreateEHoldingsFromBiblios.pm +++ b/Koha/BackgroundJob/CreateEHoldingsFromBiblios.pm @@ -47,11 +47,10 @@ sub job_type { return 'create_eholdings_from_biblios'; } - my $fix_coverage = sub { - my $coverage = shift || q{}; + my $coverage = shift || q{}; my @coverages = split '-', $coverage; - return ($coverages[0], (@coverages > 1 ? $coverages[1] : q{})); + return ( $coverages[0], ( @coverages > 1 ? $coverages[1] : q{} ) ); }; sub _get_unimarc_mapping { @@ -60,32 +59,33 @@ sub _get_unimarc_mapping { my $biblio_id = $biblio->biblionumber; my $publication_title = $biblio->title; my $print_identifier = - $record->subfield( '010', 'a' ) - || $record->subfield( '010', 'z' ) - || $record->subfield( '011', 'a' ) - || $record->subfield( '011', 'y' ); - my $online_identifier = $print_identifier; - my $date_first_issue_online = $record->subfield( '955', 'a' ); - my $date_last_issue_online = $record->subfield( '955', 'k' ); - my $num_first_vol_online = $record->subfield( '955', 'd' ); - my $num_last_vol_online = $record->subfield( '955', 'n' ); - my $num_first_issue_online = $record->subfield( '955', 'e' ); - my $num_last_issue_online = $record->subfield( '955', 'o' ); - my $title_url = $record->subfield( '856', 'u' ); - my $first_author = $biblio->author; - my $embargo_info = $record->subfield( '371', 'a' ); - my $coverage_depth = $title_url ? 'fulltext' : 'print'; - my $notes = $record->subfield( '336', 'a' ); - my $publisher_name = $record->subfield( '214', 'c' ); - my $label_pos67 = substr( $record->leader, 6, 2 ); - my $publication_type = $label_pos67 eq 'am' ? 'monograph' : $label_pos67 eq 'as' ? 'serial' : ''; - my $date_monograph_published_print = $record->subfield( '214', 'd' ) || substr( $record->subfield(100, 'a'), 9, 4 ) || ''; + $record->subfield( '010', 'a' ) + || $record->subfield( '010', 'z' ) + || $record->subfield( '011', 'a' ) + || $record->subfield( '011', 'y' ); + my $online_identifier = $print_identifier; + my $date_first_issue_online = $record->subfield( '955', 'a' ); + my $date_last_issue_online = $record->subfield( '955', 'k' ); + my $num_first_vol_online = $record->subfield( '955', 'd' ); + my $num_last_vol_online = $record->subfield( '955', 'n' ); + my $num_first_issue_online = $record->subfield( '955', 'e' ); + my $num_last_issue_online = $record->subfield( '955', 'o' ); + my $title_url = $record->subfield( '856', 'u' ); + my $first_author = $biblio->author; + my $embargo_info = $record->subfield( '371', 'a' ); + my $coverage_depth = $title_url ? 'fulltext' : 'print'; + my $notes = $record->subfield( '336', 'a' ); + my $publisher_name = $record->subfield( '214', 'c' ); + my $label_pos67 = substr( $record->leader, 6, 2 ); + my $publication_type = $label_pos67 eq 'am' ? 'monograph' : $label_pos67 eq 'as' ? 'serial' : ''; + my $date_monograph_published_print = + $record->subfield( '214', 'd' ) || substr( $record->subfield( 100, 'a' ), 9, 4 ) || ''; my $date_monograph_published_online = $date_monograph_published_print; my $monograph_volume = $record->subfield( '200', 'v' ); my $monograph_edition = $record->subfield( '205', 'a' ); my $first_editor = $publisher_name; - my $parent_publication_title_id = ''; # FIXME ? - my $preceding_publication_title_id = ''; # FIXME ? + my $parent_publication_title_id = ''; # FIXME ? + my $preceding_publication_title_id = ''; # FIXME ? my $access_type = $record->subfield( '856', 'y' ); return { @@ -123,16 +123,16 @@ sub _get_marc21_mapping { my $biblio_id = $biblio->biblionumber; my $publication_title = $biblio->title; my $print_identifier = - $record->subfield( '020', 'a' ) - || $record->subfield( '020', 'z' ) - || $record->subfield( '022', 'a' ) - || $record->subfield( '022', 'y' ); + $record->subfield( '020', 'a' ) + || $record->subfield( '020', 'z' ) + || $record->subfield( '022', 'a' ) + || $record->subfield( '022', 'y' ); my $online_identifier = $print_identifier; my ( $date_first_issue_online, $date_last_issue_online ) = - $fix_coverage->( $record->subfield( '866', 'a' ) ); + $fix_coverage->( $record->subfield( '866', 'a' ) ); my ( $num_first_vol_online, $num_last_vol_online ) = - $fix_coverage->( $record->subfield( '863', 'a' ) ); - my ( $num_first_issue_online, $num_last_issue_online ) = ( '', '' ); # FIXME ? + $fix_coverage->( $record->subfield( '863', 'a' ) ); + my ( $num_first_issue_online, $num_last_issue_online ) = ( '', '' ); # FIXME ? my $title_url = $record->subfield( '856', 'u' ); my $first_author = $biblio->author; my $embargo_info = ''; # FIXME ? @@ -203,18 +203,18 @@ sub process { }; my $package = Koha::ERM::EHoldings::Packages->find($package_id); - unless ( $package ) { + unless ($package) { push @messages, { - type => 'error', - code => 'package_do_not_exist', + type => 'error', + code => 'package_do_not_exist', package_id => $package_id, }; my $data = $self->decoded_data; $data->{messages} = \@messages; - $data->{report} = $report; + $data->{report} = $report; - return $self->finish( $data ); + return $self->finish($data); } my %existing_biblio_ids = map { @@ -222,7 +222,7 @@ sub process { map { $_->biblio_id => $resource->resource_id } $resource->title } $package->resources->as_list; - RECORD_IDS: for my $biblio_id ( sort { $a <=> $b } @record_ids ) { +RECORD_IDS: for my $biblio_id ( sort { $a <=> $b } @record_ids ) { last if $self->get_from_storage->status eq 'cancelled'; @@ -231,38 +231,39 @@ sub process { try { if ( grep { $_ eq $biblio_id } keys %existing_biblio_ids ) { push @messages, - { + { type => 'warning', code => 'biblio_already_exists', biblio_id => $biblio_id, resource_id => $existing_biblio_ids{$biblio_id}, - }; + }; return; } my $biblio = Koha::Biblios->find($biblio_id); - my $eholding_title = C4::Context->preference('marcflavour') eq 'UNIMARC' + my $eholding_title = + C4::Context->preference('marcflavour') eq 'UNIMARC' ? _get_unimarc_mapping($biblio) : _get_marc21_mapping($biblio); $eholding_title = Koha::ERM::EHoldings::Title->new($eholding_title)->store; - Koha::ERM::EHoldings::Resource->new({ title_id => $eholding_title->title_id, package_id => $package_id })->store; + Koha::ERM::EHoldings::Resource->new( { title_id => $eholding_title->title_id, package_id => $package_id } ) + ->store; $report->{total_success}++; } catch { push @messages, { - type => 'error', - code => 'eholding_not_created', + type => 'error', + code => 'eholding_not_created', error => $_, }; }; $self->step; } - my $data = $self->decoded_data; $data->{messages} = \@messages; - $data->{report} = $report; + $data->{report} = $report; - $self->finish( $data ); + $self->finish($data); } =head3 enqueue @@ -272,16 +273,18 @@ Enqueue the new job =cut sub enqueue { - my ( $self, $args) = @_; + my ( $self, $args ) = @_; return unless exists $args->{package_id}; return unless exists $args->{record_ids}; - $self->SUPER::enqueue({ - job_size => scalar @{$args->{record_ids}}, - job_args => $args, - job_queue => 'long_tasks', - }); + $self->SUPER::enqueue( + { + job_size => scalar @{ $args->{record_ids} }, + job_args => $args, + job_queue => 'long_tasks', + } + ); } =head3 additional_report diff --git a/Koha/BackgroundJob/ImportKBARTFile.pm b/Koha/BackgroundJob/ImportKBARTFile.pm index 890a3c926a..eb68fe7a6c 100644 --- a/Koha/BackgroundJob/ImportKBARTFile.pm +++ b/Koha/BackgroundJob/ImportKBARTFile.pm @@ -85,8 +85,8 @@ sub process { if ( scalar( @{$rows} ) == 0 ) { push @messages, { - code => 'no_rows', - type => 'error', + code => 'no_rows', + type => 'error', }; $self->status('failed')->store; } @@ -114,10 +114,10 @@ sub process { my $formatted_title = format_title($new_title); if ( !$formatted_title->{publication_title} ) { push @messages, { - code => 'no_title_found', - type => 'error', - title => '(Unknown)', - title_id => $formatted_title->{external_id} + code => 'no_title_found', + type => 'error', + title => '(Unknown)', + title_id => $formatted_title->{external_id} }; $failed_imports++; } else { @@ -243,7 +243,7 @@ sub read_file { my $lines = $csv->getline_all( $fh, 0 ); close($fh); - unless($csv->eof()) { + unless ( $csv->eof() ) { my ( $cde, $str, $pos ) = $csv->error_diag(); my $error = $cde ? "$cde, $str, $pos" : ""; warn $error if $error; diff --git a/Koha/BackgroundJob/MARCImportCommitBatch.pm b/Koha/BackgroundJob/MARCImportCommitBatch.pm index d2d45b6070..aeec1de935 100644 --- a/Koha/BackgroundJob/MARCImportCommitBatch.pm +++ b/Koha/BackgroundJob/MARCImportCommitBatch.pm @@ -57,41 +57,45 @@ sub process { $self->start; - my $import_batch_id = $args->{import_batch_id}; - my $frameworkcode = $args->{frameworkcode}; + my $import_batch_id = $args->{import_batch_id}; + my $frameworkcode = $args->{frameworkcode}; my $overlay_frameworkcode = $args->{overlay_framework}; my @messages; my $job_progress = 0; - my ( $num_added, $num_updated, $num_items_added, - $num_items_replaced, $num_items_errored, $num_ignored ); + my ( + $num_added, $num_updated, $num_items_added, + $num_items_replaced, $num_items_errored, $num_ignored + ); try { - my $size = Koha::Import::Records->search({ import_batch_id => $import_batch_id })->count; + my $size = Koha::Import::Records->search( { import_batch_id => $import_batch_id } )->count; $self->size($size)->store; - ( $num_added, $num_updated, $num_items_added, - $num_items_replaced, $num_items_errored, $num_ignored ) = - BatchCommitRecords({ - batch_id => $import_batch_id, - framework => $frameworkcode, - overlay_framework => $overlay_frameworkcode, - progress_interval => 50, - progress_callback => - sub { my $job_progress = shift; $self->progress( $job_progress )->store }, - }); + ( + $num_added, $num_updated, $num_items_added, + $num_items_replaced, $num_items_errored, $num_ignored + ) + = BatchCommitRecords( + { + batch_id => $import_batch_id, + framework => $frameworkcode, + overlay_framework => $overlay_frameworkcode, + progress_interval => 50, + progress_callback => sub { my $job_progress = shift; $self->progress($job_progress)->store }, + } + ); my $count = $num_added + $num_updated; - if( $count ) { - $self->set({ progress => $count, size => $count }); - } else { # TODO Refine later - $self->set({ progress => 0, status => 'failed' }); + if ($count) { + $self->set( { progress => $count, size => $count } ); + } else { # TODO Refine later + $self->set( { progress => 0, status => 'failed' } ); } - } - catch { + } catch { warn $_; - Koha::Database->schema->storage->txn_rollback; # TODO BatchCommitRecords started a transaction + Koha::Database->schema->storage->txn_rollback; # TODO BatchCommitRecords started a transaction die "Something terrible has happened!" - if ( $_ =~ /Rollback failed/ ); # Rollback failed - $self->set({ progress => 0, status => 'failed' }); + if ( $_ =~ /Rollback failed/ ); # Rollback failed + $self->set( { progress => 0, status => 'failed' } ); }; my $report = { @@ -117,13 +121,15 @@ Enqueue the new job =cut sub enqueue { - my ( $self, $args) = @_; + my ( $self, $args ) = @_; - $self->SUPER::enqueue({ - job_size => Koha::Import::Records->search({ import_batch_id => $args->{import_batch_id} })->count, - job_args => $args, - job_queue => 'long_tasks', - }); + $self->SUPER::enqueue( + { + job_size => Koha::Import::Records->search( { import_batch_id => $args->{import_batch_id} } )->count, + job_args => $args, + job_queue => 'long_tasks', + } + ); } 1; diff --git a/Koha/BackgroundJob/MARCImportRevertBatch.pm b/Koha/BackgroundJob/MARCImportRevertBatch.pm index b9d7c6e59c..a9115492c2 100644 --- a/Koha/BackgroundJob/MARCImportRevertBatch.pm +++ b/Koha/BackgroundJob/MARCImportRevertBatch.pm @@ -70,20 +70,19 @@ sub process { try { $schema->storage->txn_begin; ( $num_deleted, $num_errors, $num_reverted, $num_items_deleted, $num_ignored ) = - BatchRevertRecords( $import_batch_id ); # TODO BatchRevertRecords still needs a progress_callback + BatchRevertRecords($import_batch_id); # TODO BatchRevertRecords still needs a progress_callback $schema->storage->txn_commit; my $count = $num_deleted + $num_reverted; - if( $count ) { - $self->set({ progress => $count, size => $count }); - } else { # TODO Nothing happened? Refine later - $self->set({ progress => 0, status => 'failed' }); + if ($count) { + $self->set( { progress => $count, size => $count } ); + } else { # TODO Nothing happened? Refine later + $self->set( { progress => 0, status => 'failed' } ); } - } - catch { + } catch { warn $_; $schema->storage->txn_rollback; - $self->set({ progress => 0, status => 'failed' }); + $self->set( { progress => 0, status => 'failed' } ); }; my $report = { @@ -109,13 +108,15 @@ Enqueue the new job =cut sub enqueue { - my ( $self, $args) = @_; + my ( $self, $args ) = @_; - $self->SUPER::enqueue({ - job_size => Koha::Import::Records->search({ import_batch_id => $args->{import_batch_id} })->count, - job_args => $args, - job_queue => 'long_tasks', - }); + $self->SUPER::enqueue( + { + job_size => Koha::Import::Records->search( { import_batch_id => $args->{import_batch_id} } )->count, + job_args => $args, + job_queue => 'long_tasks', + } + ); } 1; diff --git a/Koha/BackgroundJob/StageMARCForImport.pm b/Koha/BackgroundJob/StageMARCForImport.pm index cead144cd5..84dcced798 100644 --- a/Koha/BackgroundJob/StageMARCForImport.pm +++ b/Koha/BackgroundJob/StageMARCForImport.pm @@ -67,7 +67,7 @@ sub process { $self->start; my $import_args = { %$args, job => $self }; - my $result = Koha::ImportBatch->new_from_file($import_args); + my $result = Koha::ImportBatch->new_from_file($import_args); my $data = $self->decoded_data; $data->{messages} = $result->{messages}; @@ -83,14 +83,16 @@ Enqueue the new job =cut sub enqueue { - my ( $self, $args) = @_; + my ( $self, $args ) = @_; # FIXME: no $args validation - $self->SUPER::enqueue({ - job_size => 0, # TODO Unknown for now? - job_args => $args, - job_queue => 'long_tasks', - }); + $self->SUPER::enqueue( + { + job_size => 0, # TODO Unknown for now? + job_args => $args, + job_queue => 'long_tasks', + } + ); } 1; diff --git a/Koha/BackgroundJob/UpdateElasticIndex.pm b/Koha/BackgroundJob/UpdateElasticIndex.pm index 1439482dda..a60d45c205 100644 --- a/Koha/BackgroundJob/UpdateElasticIndex.pm +++ b/Koha/BackgroundJob/UpdateElasticIndex.pm @@ -54,20 +54,23 @@ Enqueue the new job =cut sub enqueue { - my ( $self, $args) = @_; + my ( $self, $args ) = @_; return unless exists $args->{record_server}; return unless exists $args->{record_ids}; my $record_server = $args->{record_server}; - my @record_ids = @{ $args->{record_ids} }; + my @record_ids = @{ $args->{record_ids} }; + # elastic_index queue will be handled by the es_indexer_daemon script - $self->SUPER::enqueue({ - job_size => 1, # Each index is a single job, regardless of the amount of records included - job_args => {record_server => $record_server, record_ids => \@record_ids}, - job_queue => 'elastic_index' - }); + $self->SUPER::enqueue( + { + job_size => 1, # Each index is a single job, regardless of the amount of records included + job_args => { record_server => $record_server, record_ids => \@record_ids }, + job_queue => 'elastic_index' + } + ); } 1; diff --git a/Koha/BackgroundJobs.pm b/Koha/BackgroundJobs.pm index 48afbf68fa..126333f85e 100644 --- a/Koha/BackgroundJobs.pm +++ b/Koha/BackgroundJobs.pm @@ -44,14 +44,13 @@ sub search_limited { my $logged_in_user; my $userenv = C4::Context->userenv; if ( $userenv and $userenv->{number} ) { - $logged_in_user = Koha::Patrons->find( $userenv->{number} ); - $can_manage_background_jobs = $logged_in_user->has_permission( - { parameters => 'manage_background_jobs' } ); + $logged_in_user = Koha::Patrons->find( $userenv->{number} ); + $can_manage_background_jobs = $logged_in_user->has_permission( { parameters => 'manage_background_jobs' } ); } return $self->search( $params, $attributes ) if $can_manage_background_jobs; my $id = $logged_in_user ? $logged_in_user->borrowernumber : undef; - return $self->search({ borrowernumber => $id })->search( $params, $attributes ); + return $self->search( { borrowernumber => $id } )->search( $params, $attributes ); } =head3 filter_by_current @@ -65,11 +64,7 @@ Returns a new resultset, filtering out finished jobs. sub filter_by_current { my ($self) = @_; - return $self->search( - { - status => { not_in => [ 'cancelled', 'failed', 'finished' ] } - } - ); + return $self->search( { status => { not_in => [ 'cancelled', 'failed', 'finished' ] } } ); } =head2 Internal methods diff --git a/Koha/Biblio.pm b/Koha/Biblio.pm index 927d7b898e..030da1a371 100644 --- a/Koha/Biblio.pm +++ b/Koha/Biblio.pm @@ -80,9 +80,9 @@ Overloaded I method to set default values =cut sub store { - my ( $self ) = @_; + my ($self) = @_; - $self->datecreated( dt_from_string ) unless $self->datecreated; + $self->datecreated(dt_from_string) unless $self->datecreated; return $self->SUPER::store; } @@ -96,7 +96,7 @@ Returns a Koha::Biblio::Metadata object =cut sub metadata { - my ( $self ) = @_; + my ($self) = @_; my $metadata = $self->_result->metadata; return Koha::Biblio::Metadata->_new_from_dbic($metadata); @@ -111,7 +111,7 @@ Returns a Marc::Record object =cut sub record { - my ( $self ) = @_; + my ($self) = @_; return $self->metadata->record; } @@ -125,7 +125,7 @@ Returns the record schema (MARC21, USMARC or UNIMARC). =cut sub record_schema { - my ( $self ) = @_; + my ($self) = @_; return $self->metadata->schema // C4::Context->preference("marcflavour"); } @@ -204,7 +204,7 @@ Returns a Koha::Acquisition::Orders object =cut sub orders { - my ( $self ) = @_; + my ($self) = @_; my $orders = $self->_result->orders; return Koha::Acquisition::Orders->_new_from_dbic($orders); @@ -219,7 +219,7 @@ Returns acquisition orders related to this biblio that are not cancelled. =cut sub uncancelled_orders { - my ( $self ) = @_; + my ($self) = @_; return $self->orders->filter_out_cancelled; } @@ -259,9 +259,9 @@ Returns all tickets linked to the biblio =cut sub tickets { - my ( $self ) = @_; + my ($self) = @_; my $rs = $self->_result->tickets; - return Koha::Tickets->_new_from_dbic( $rs ); + return Koha::Tickets->_new_from_dbic($rs); } =head3 ill_requests @@ -273,7 +273,7 @@ Returns a Koha::ILL::Requests object =cut sub ill_requests { - my ( $self ) = @_; + my ($self) = @_; my $ill_requests = $self->_result->ill_requests; return Koha::ILL::Requests->_new_from_dbic($ill_requests); @@ -288,7 +288,7 @@ Returns a Koha::Biblio::ItemGroups object =cut sub item_groups { - my ( $self ) = @_; + my ($self) = @_; my $item_groups = $self->_result->item_groups; return Koha::Biblio::ItemGroups->_new_from_dbic($item_groups); @@ -309,7 +309,7 @@ sub can_article_request { my $rule = $self->article_request_type($borrower); return q{} if $rule eq 'item_only' && !$self->items()->count(); - return 1 if $rule && $rule ne 'no'; + return 1 if $rule && $rule ne 'no'; return q{}; } @@ -427,7 +427,7 @@ to $to_library, otherwise 0. =cut sub can_be_transferred { - my ($self, $params) = @_; + my ( $self, $params ) = @_; my $to = $params->{to}; my $from = $params->{from}; @@ -436,15 +436,16 @@ sub can_be_transferred { my $limittype = C4::Context->preference('BranchTransferLimitsType'); my $items; - foreach my $item_of_bib ($self->items->as_list) { + foreach my $item_of_bib ( $self->items->as_list ) { next unless $item_of_bib->holdingbranch; - next if $from && $from->branchcode ne $item_of_bib->holdingbranch; + next if $from && $from->branchcode ne $item_of_bib->holdingbranch; return 1 if $item_of_bib->holdingbranch eq $to->branchcode; - my $code = $limittype eq 'itemtype' + my $code = + $limittype eq 'itemtype' ? $item_of_bib->effective_itemtype : $item_of_bib->ccode; return 1 unless $code; - $items->{$code}->{$item_of_bib->holdingbranch} = 1; + $items->{$code}->{ $item_of_bib->holdingbranch } = 1; } # At this point we will have a HASHref containing each itemtype/ccode that @@ -454,21 +455,21 @@ sub can_be_transferred { # listed holdingbranches to the given $to library exist. If at least one # holdingbranch for that $limittype does not have a transfer limit to given # $to library, then we know that the transfer is possible. - foreach my $code (keys %{$items}) { - my @holdingbranches = keys %{$items->{$code}}; - return 1 if Koha::Item::Transfer::Limits->search({ - toBranch => $to->branchcode, - fromBranch => { 'in' => \@holdingbranches }, - $limittype => $code - }, { - group_by => [qw/fromBranch/] - })->count == scalar(@holdingbranches) ? 0 : 1; + foreach my $code ( keys %{$items} ) { + my @holdingbranches = keys %{ $items->{$code} }; + return 1 if Koha::Item::Transfer::Limits->search( + { + toBranch => $to->branchcode, + fromBranch => { 'in' => \@holdingbranches }, + $limittype => $code + }, + { group_by => [qw/fromBranch/] } + )->count == scalar(@holdingbranches) ? 0 : 1; } return 0; } - =head3 pickup_locations my $pickup_locations = $biblio->pickup_locations({ patron => $patron }); @@ -502,7 +503,7 @@ sub pickup_locations { $memory_cache->set_in_cache( $cache_key, $item_pickup_locations ); } push @pickup_locations, @{$item_pickup_locations}; - for my $location (@{$item_pickup_locations}) { + for my $location ( @{$item_pickup_locations} ) { push @{ $location_items->{$location} }, $item->itemnumber; } } @@ -541,9 +542,9 @@ sub hidden_in_opac { my @items = $self->items->as_list; - return 0 unless @items; # Do not hide if there is no item + return 0 unless @items; # Do not hide if there is no item - return !(any { !$_->hidden_in_opac({ rules => $rules }) } @items); + return !( any { !$_->hidden_in_opac( { rules => $rules } ) } @items ); } =head3 article_request_type @@ -562,7 +563,7 @@ sub article_request_type { return q{} unless $borrower; - my $rule = $self->article_request_type_for_items( $borrower ); + my $rule = $self->article_request_type_for_items($borrower); return $rule if $rule; # If the record has no items that are requestable, go by the record itemtype @@ -597,7 +598,7 @@ sub article_request_type_for_bib { ); return q{} unless $rule; - return $rule->rule_value || q{} + return $rule->rule_value || q{}; } =head3 article_request_type_for_items @@ -635,7 +636,7 @@ Returns the article requests associated with this biblio =cut sub article_requests { - my ( $self ) = @_; + my ($self) = @_; return Koha::ArticleRequests->_new_from_dbic( scalar $self->_result->article_requests ); } @@ -651,8 +652,10 @@ Returns the current checkouts associated with this biblio sub current_checkouts { my ($self) = @_; - return Koha::Checkouts->search( { "item.biblionumber" => $self->id }, - { join => 'item' } ); + return Koha::Checkouts->search( + { "item.biblionumber" => $self->id }, + { join => 'item' } + ); } =head3 old_checkouts @@ -664,10 +667,12 @@ Returns the past checkouts associated with this biblio =cut sub old_checkouts { - my ( $self ) = @_; + my ($self) = @_; - return Koha::Old::Checkouts->search( { "item.biblionumber" => $self->id }, - { join => 'item' } ); + return Koha::Old::Checkouts->search( + { "item.biblionumber" => $self->id }, + { join => 'item' } + ); } =head3 items @@ -681,17 +686,17 @@ Returns the related Koha::Items object for this biblio =cut sub items { - my ($self,$params) = @_; + my ( $self, $params ) = @_; my $items_rs = $self->_result->items; return Koha::Items->_new_from_dbic($items_rs) unless $params->{host_items} && C4::Context->preference('EasyAnalyticalRecords'); - my @itemnumbers = $items_rs->get_column('itemnumber')->all; + my @itemnumbers = $items_rs->get_column('itemnumber')->all; my $host_itemnumbers = $self->_host_itemnumbers(); - push @itemnumbers, @{ $host_itemnumbers }; - return Koha::Items->search({ "me.itemnumber" => { -in => \@itemnumbers } }); + push @itemnumbers, @{$host_itemnumbers}; + return Koha::Items->search( { "me.itemnumber" => { -in => \@itemnumbers } } ); } =head3 bookable_items @@ -719,7 +724,7 @@ sub host_items { my ($self) = @_; return Koha::Items->new->empty - unless C4::Context->preference('EasyAnalyticalRecords'); + unless C4::Context->preference('EasyAnalyticalRecords'); my $host_itemnumbers = $self->_host_itemnumbers; @@ -737,7 +742,7 @@ Return the itemnumbers for analytical items on this record sub _host_itemnumbers { my ($self) = @_; - my $marcflavour = C4::Context->preference("marcflavour"); + my $marcflavour = C4::Context->preference("marcflavour"); my $analyticfield = '773'; if ( $marcflavour eq 'UNIMARC' ) { $analyticfield = '461'; @@ -750,7 +755,6 @@ sub _host_itemnumbers { return \@itemnumbers; } - =head3 itemtype my $itemtype = $biblio->itemtype(); @@ -760,7 +764,7 @@ Returns the itemtype for this record. =cut sub itemtype { - my ( $self ) = @_; + my ($self) = @_; return $self->biblioitem()->itemtype(); } @@ -807,8 +811,7 @@ It does not include future holds. sub current_holds { my ($self) = @_; my $dtf = Koha::Database->new->schema->storage->datetime_parser; - return $self->holds( - { reservedate => { '<=' => $dtf->format_date(dt_from_string) } } ); + return $self->holds( { reservedate => { '<=' => $dtf->format_date(dt_from_string) } } ); } =head3 biblioitem @@ -850,7 +853,7 @@ sub suggestions { my ($self) = @_; my $suggestions_rs = $self->_result->suggestions; - return Koha::Suggestions->_new_from_dbic( $suggestions_rs ); + return Koha::Suggestions->_new_from_dbic($suggestions_rs); } =head3 get_marc_components @@ -863,20 +866,23 @@ this object (MARC21 773 points to this) =cut sub get_marc_components { - my ($self, $max_results) = @_; + my ( $self, $max_results ) = @_; - return [] if (C4::Context->preference('marcflavour') ne 'MARC21'); + return [] if ( C4::Context->preference('marcflavour') ne 'MARC21' ); my ( $searchstr, $sort ) = $self->get_components_query; my $components; - if (defined($searchstr)) { - my $searcher = Koha::SearchEngine::Search->new({index => $Koha::SearchEngine::BIBLIOS_INDEX}); + if ( defined($searchstr) ) { + my $searcher = Koha::SearchEngine::Search->new( { index => $Koha::SearchEngine::BIBLIOS_INDEX } ); my ( $error, $results, $facets ); eval { - ( $error, $results, $facets ) = $searcher->search_compat( $searchstr, undef, [$sort], ['biblioserver'], $max_results, 0, undef, undef, 'ccl', 0 ); + ( $error, $results, $facets ) = $searcher->search_compat( + $searchstr, undef, [$sort], ['biblioserver'], $max_results, 0, undef, undef, + 'ccl', 0 + ); }; - if( $error || $@ ) { + if ( $error || $@ ) { $error //= q{}; $error .= $@ if $@; warn "Warning from search_compat: '$error'"; @@ -903,12 +909,11 @@ Returns a query which can be used to search for all component parts of MARC21 bi sub get_components_query { my ($self) = @_; - my $builder = Koha::SearchEngine::QueryBuilder->new( - { index => $Koha::SearchEngine::BIBLIOS_INDEX } ); - my $marc = $self->metadata->record; + my $builder = Koha::SearchEngine::QueryBuilder->new( { index => $Koha::SearchEngine::BIBLIOS_INDEX } ); + my $marc = $self->metadata->record; my $component_sort_field = C4::Context->preference('ComponentSortField') // "title"; my $component_sort_order = C4::Context->preference('ComponentSortOrder') // "asc"; - my $sort = $component_sort_field . "_" . $component_sort_order; + my $sort = $component_sort_field . "_" . $component_sort_order; my $searchstr; if ( C4::Context->preference('UseControlNumber') ) { @@ -919,11 +924,12 @@ sub get_components_query { my $pf003 = $marc->field('003') || undef; if ( !defined($pf003) ) { + # search for 773$w='Host001' - $searchstr .= "rcn:\"" . $pf001->data()."\""; - } - else { + $searchstr .= "rcn:\"" . $pf001->data() . "\""; + } else { $searchstr .= "("; + # search for (773$w='Host001' and 003='Host003') or 773$w='(Host003)Host001' $searchstr .= "(rcn:\"" . $pf001->data() . "\" AND cni:\"" . $pf003->data() . "\")"; $searchstr .= " OR rcn:\"" . $pf003->data() . " " . $pf001->data() . "\""; @@ -934,20 +940,19 @@ sub get_components_query { $searchstr .= " AND (bib-level:a OR bib-level:b)"; $searchstr .= ")"; } - } - else { - my $cleaned_title = $marc->subfield('245', "a"); + } else { + my $cleaned_title = $marc->subfield( '245', "a" ); $cleaned_title =~ tr|/||; $cleaned_title = $builder->clean_search_term($cleaned_title); - $searchstr = qq#Host-item:("$cleaned_title")#; + $searchstr = qq#Host-item:("$cleaned_title")#; } - my ($error, $query ,$query_str) = $builder->build_query_compat( undef, [$searchstr], undef, undef, [$sort], 0 ); - if( $error ){ + my ( $error, $query, $query_str ) = $builder->build_query_compat( undef, [$searchstr], undef, undef, [$sort], 0 ); + if ($error) { warn $error; return; } - return ($query, $query_str, $sort); + return ( $query, $query_str, $sort ); } =head3 get_marc_volumes @@ -1089,10 +1094,17 @@ Tells if this bibliographic record has items waiting or in transit. =cut sub has_items_waiting_or_intransit { - my ( $self ) = @_; + my ($self) = @_; - if ( Koha::Holds->search({ biblionumber => $self->id, - found => ['W', 'T'] })->count ) { + if ( + Koha::Holds->search( + { + biblionumber => $self->id, + found => [ 'W', 'T' ] + } + )->count + ) + { return 1; } @@ -1112,7 +1124,7 @@ Returns the COinS (a span) which can be included in a biblio record =cut sub get_coins { - my ( $self ) = @_; + my ($self) = @_; my $record = $self->metadata->record; @@ -1157,22 +1169,22 @@ sub get_coins { $genre = $fmts6->{$pos6} ? $fmts6->{$pos6} : 'book'; if ( $genre eq 'book' ) { - $genre = $fmts7->{$pos7} if $fmts7->{$pos7}; + $genre = $fmts7->{$pos7} if $fmts7->{$pos7}; } ##### We must transform mtx to a valable mtx and document type #### if ( $genre eq 'book' ) { - $mtx = 'book'; - $titletype = 'b'; + $mtx = 'book'; + $titletype = 'b'; } elsif ( $genre eq 'journal' ) { - $mtx = 'journal'; - $titletype = 'j'; + $mtx = 'journal'; + $titletype = 'j'; } elsif ( $genre eq 'journalArticle' ) { - $mtx = 'journal'; - $genre = 'article'; - $titletype = 'a'; + $mtx = 'journal'; + $genre = 'article'; + $titletype = 'a'; } else { - $mtx = 'dc'; + $mtx = 'dc'; } if ( C4::Context->preference("marcflavour") eq "UNIMARC" ) { @@ -1180,7 +1192,7 @@ sub get_coins { # Setting datas $aulast = $record->subfield( '700', 'a' ) || ''; $aufirst = $record->subfield( '700', 'b' ) || ''; - push @authors, "$aufirst $aulast" if ($aufirst or $aulast); + push @authors, "$aufirst $aulast" if ( $aufirst or $aulast ); # others authors if ( $record->field('200') ) { @@ -1189,9 +1201,9 @@ sub get_coins { } } - $title = $record->subfield( '200', 'a' ); - my $subfield_210d = $record->subfield('210', 'd'); - if ($subfield_210d and $subfield_210d =~ /(\d{4})/) { + $title = $record->subfield( '200', 'a' ); + my $subfield_210d = $record->subfield( '210', 'd' ); + if ( $subfield_210d and $subfield_210d =~ /(\d{4})/ ) { $pubyear = $1; } $publisher = $record->subfield( '210', 'c' ) || ''; @@ -1214,14 +1226,14 @@ sub get_coins { } $title = $record->field('245'); $title &&= $title->as_string('ab'); - if ($titletype eq 'a') { + if ( $titletype eq 'a' ) { $pubyear = $record->field('008') || ''; - $pubyear = substr($pubyear->data(), 7, 4) if $pubyear; + $pubyear = substr( $pubyear->data(), 7, 4 ) if $pubyear; $isbn = $record->subfield( '773', 'z' ) || ''; $issn = $record->subfield( '773', 'x' ) || ''; - $hosttitle = $record->subfield( '773', 't' ) || $record->subfield( '773', 'a') || q{}; + $hosttitle = $record->subfield( '773', 't' ) || $record->subfield( '773', 'a' ) || q{}; my @rels = $record->subfield( '773', 'g' ); - $pages = join(', ', @rels); + $pages = join( ', ', @rels ); } else { $pubyear = $record->subfield( '260', 'c' ) || ''; $publisher = $record->subfield( '260', 'b' ) || ''; @@ -1232,15 +1244,15 @@ sub get_coins { } my @params = ( - [ 'ctx_ver', 'Z39.88-2004' ], - [ 'rft_val_fmt', "info:ofi/fmt:kev:mtx:$mtx" ], - [ ($mtx eq 'dc' ? 'rft.type' : 'rft.genre'), $genre ], - [ "rft.${titletype}title", $title ], + [ 'ctx_ver', 'Z39.88-2004' ], + [ 'rft_val_fmt', "info:ofi/fmt:kev:mtx:$mtx" ], + [ ( $mtx eq 'dc' ? 'rft.type' : 'rft.genre' ), $genre ], + [ "rft.${titletype}title", $title ], ); # rft.title is authorized only once, so by checking $titletype # we ensure that rft.title is not already in the list. - if ($hosttitle and $titletype) { + if ( $hosttitle and $titletype ) { push @params, [ 'rft.title', $hosttitle ]; } @@ -1250,19 +1262,21 @@ sub get_coins { ); # If it's a subscription, these informations have no meaning. - if ($genre ne 'journal') { + if ( $genre ne 'journal' ) { push @params, ( - [ 'rft.aulast', $aulast ], + [ 'rft.aulast', $aulast ], [ 'rft.aufirst', $aufirst ], - (map { [ 'rft.au', $_ ] } @authors), - [ 'rft.pub', $publisher ], - [ 'rft.date', $pubyear ], + ( map { [ 'rft.au', $_ ] } @authors ), + [ 'rft.pub', $publisher ], + [ 'rft.date', $pubyear ], [ 'rft.pages', $pages ], ); } - my $coins_value = join( '&', - map { $$_[1] ? $$_[0] . '=' . uri_escape_utf8( $$_[1] ) : () } @params ); + my $coins_value = join( + '&', + map { $$_[1] ? $$_[0] . '=' . uri_escape_utf8( $$_[1] ) : () } @params + ); return $coins_value; } @@ -1276,14 +1290,14 @@ Returns url for OpenURL resolver set in OpenURLResolverURL system preference =cut sub get_openurl { - my ( $self ) = @_; + my ($self) = @_; my $OpenURLResolverURL = C4::Context->preference('OpenURLResolverURL'); if ($OpenURLResolverURL) { my $uri = URI->new($OpenURLResolverURL); - if (not defined $uri->query) { + if ( not defined $uri->query ) { $OpenURLResolverURL .= '?'; } else { $OpenURLResolverURL .= '&'; @@ -1303,12 +1317,12 @@ Return boolean true if this bibbliographic record is continuing resource =cut sub is_serial { - my ( $self ) = @_; + my ($self) = @_; return 1 if $self->serial; my $record = $self->metadata->record; - return 1 if substr($record->leader, 7, 1) eq 's'; + return 1 if substr( $record->leader, 7, 1 ) eq 's'; return 0; } @@ -1323,7 +1337,7 @@ It is built regaring the value of the system preference CustomCoverImagesURL =cut sub custom_cover_image_url { - my ( $self ) = @_; + my ($self) = @_; my $url = C4::Context->preference('CustomCoverImagesURL'); if ( $url =~ m|{isbn}| ) { my $isbn = $self->biblioitem->isbn; @@ -1343,11 +1357,11 @@ sub custom_cover_image_url { my $re = qr|{(?\d{3})(\$(?.))?}|; if ( $url =~ $re ) { - my $field = $+{field}; - my $subfield = $+{subfield}; + my $field = $+{field}; + my $subfield = $+{subfield}; my $marc_record = $self->metadata->record; my $value; - if ( $subfield ) { + if ($subfield) { $value = $marc_record->subfield( $field, $subfield ); } else { my $controlfield = $marc_record->field($field); @@ -1367,7 +1381,7 @@ Return the cover images associated with this biblio. =cut sub cover_images { - my ( $self ) = @_; + my ($self) = @_; my $cover_images_rs = $self->_result->cover_images; return unless $cover_images_rs; @@ -1388,10 +1402,10 @@ sub get_marc_notes { my ( $self, $params ) = @_; my $marcflavour = C4::Context->preference('marcflavour'); - my $opac = $params->{opac} // '0'; - my $interface = $params->{opac} ? 'opac' : 'intranet'; + my $opac = $params->{opac} // '0'; + my $interface = $params->{opac} ? 'opac' : 'intranet'; - my $record = $params->{record} // $self->metadata->record; + my $record = $params->{record} // $self->metadata->record; my $record_processor = Koha::RecordProcessor->new( { filters => [ 'ViewPolicy', 'ExpandCodedFields' ], @@ -1403,7 +1417,8 @@ sub get_marc_notes { ); $record_processor->process($record); - my $scope = $marcflavour eq "UNIMARC"? '3..': '5..'; + my $scope = $marcflavour eq "UNIMARC" ? '3..' : '5..'; + #MARC21 specs indicate some notes should be private if first indicator 0 my %maybe_private = ( 541 => 1, @@ -1414,23 +1429,23 @@ sub get_marc_notes { ); my %hiddenlist = map { $_ => 1 } - split( /,/, C4::Context->preference('NotesToHide')); + split( /,/, C4::Context->preference('NotesToHide') ); my @marcnotes; foreach my $field ( $record->field($scope) ) { my $tag = $field->tag(); - next if $hiddenlist{ $tag }; + next if $hiddenlist{$tag}; next if $opac && $maybe_private{$tag} && !$field->indicator(1); - if( $marcflavour ne 'UNIMARC' && $field->subfield('u') ) { + if ( $marcflavour ne 'UNIMARC' && $field->subfield('u') ) { + # Field 5XX$u always contains URI # Examples: 505u, 506u, 510u, 514u, 520u, 530u, 538u, 540u, 542u, 552u, 555u, 561u, 563u, 583u # We first push the other subfields, then all $u's separately # Leave further actions to the template (see e.g. opac-detail) - my $othersub = - join '', ( 'a' .. 't', 'v' .. 'z', '0' .. '9' ); # excl 'u' + my $othersub = join '', ( 'a' .. 't', 'v' .. 'z', '0' .. '9' ); # excl 'u' push @marcnotes, { marcnote => $field->as_string($othersub) }; foreach my $sub ( $field->subfield('u') ) { - $sub =~ s/^\s+|\s+$//g; # trim + $sub =~ s/^\s+|\s+$//g; # trim push @marcnotes, { marcnote => $sub, tag => $tag }; } } else { @@ -1458,16 +1473,17 @@ sub _get_marc_authors { my $marcflavour = C4::Context->preference('marcflavour'); # tagslib useful only for UNIMARC author responsibilities - my $tagslib = $marcflavour eq "UNIMARC" - ? C4::Biblio::GetMarcStructure( 1, $self->frameworkcode, { unsafe => 1 } ) - : undef; + my $tagslib = + $marcflavour eq "UNIMARC" + ? C4::Biblio::GetMarcStructure( 1, $self->frameworkcode, { unsafe => 1 } ) + : undef; my @marcauthors; foreach my $field ( $self->metadata->record->field($fields_filter) ) { next - if $mintag && $field->tag() < $mintag - || $maxtag && $field->tag() > $maxtag; + if $mintag && $field->tag() < $mintag + || $maxtag && $field->tag() > $maxtag; my @subfields_loop; my @link_loop; @@ -1494,39 +1510,42 @@ sub _get_marc_authors { # don't load unimarc subfields 3, 5 next if ( $marcflavour eq 'UNIMARC' and ( $authors_subfield->[0] =~ /3|5/ ) ); - my $code = $authors_subfield->[0]; - my $value = $authors_subfield->[1]; - my $linkvalue = $value; + my $code = $authors_subfield->[0]; + my $value = $authors_subfield->[1]; + my $linkvalue = $value; $linkvalue =~ s/(\(|\))//g; + # UNIMARC author responsibility if ( $marcflavour eq 'UNIMARC' and $code eq '4' ) { - $value = C4::Biblio::GetAuthorisedValueDesc( $field->tag(), $code, $value, '', $tagslib ); + $value = C4::Biblio::GetAuthorisedValueDesc( $field->tag(), $code, $value, '', $tagslib ); $linkvalue = "($value)"; } + # if no authority link, build a search query unless ($subfield9) { push @link_loop, { limit => 'au', 'link' => $linkvalue, - operator => (scalar @link_loop) ? ' AND ' : undef + operator => ( scalar @link_loop ) ? ' AND ' : undef }; } my @this_link_loop = @link_loop; + # do not display $0 - unless ( $code eq '0') { + unless ( $code eq '0' ) { push @subfields_loop, { tag => $field->tag(), code => $code, value => $value, link_loop => \@this_link_loop, - separator => (scalar @subfields_loop) ? $AuthoritySeparator : '' + separator => ( scalar @subfields_loop ) ? $AuthoritySeparator : '' }; } } push @marcauthors, { MARCAUTHOR_SUBFIELDS_LOOP => \@subfields_loop, - authoritylink => $subfield9, - unimarc3 => $unimarc3 + authoritylink => $subfield9, + unimarc3 => $unimarc3 }; } return \@marcauthors; @@ -1548,20 +1567,20 @@ sub get_marc_contributors { my $marcflavour = C4::Context->preference('marcflavour'); if ( $marcflavour eq "UNIMARC" ) { - $mintag = "700"; - $maxtag = "712"; + $mintag = "700"; + $maxtag = "712"; $fields_filter = '7..'; - } else { # marc21/normarc - $mintag = "700"; - $maxtag = "720"; + } else { # marc21/normarc + $mintag = "700"; + $maxtag = "720"; $fields_filter = '7..'; } return $self->_get_marc_authors( { fields_filter => $fields_filter, - mintag => $mintag, - maxtag => $maxtag + mintag => $mintag, + maxtag => $maxtag } ); } @@ -1584,21 +1603,23 @@ sub get_marc_authors { if ( $marcflavour eq "UNIMARC" ) { $fields_filter = '200'; - } else { # marc21/normarc + } else { # marc21/normarc $fields_filter = '100'; } - my @first_authors = @{$self->_get_marc_authors( - { - fields_filter => $fields_filter, - mintag => $mintag, - maxtag => $maxtag - } - )}; + my @first_authors = @{ + $self->_get_marc_authors( + { + fields_filter => $fields_filter, + mintag => $mintag, + maxtag => $maxtag + } + ) + }; - my @other_authors = @{$self->get_marc_contributors}; + my @other_authors = @{ $self->get_marc_contributors }; - return [@first_authors, @other_authors]; + return [ @first_authors, @other_authors ]; } =head3 normalized_isbn @@ -1611,8 +1632,8 @@ ISBN13 are converted into ISBN10. This is required to get some book cover images =cut sub normalized_isbn { - my ( $self) = @_; - return C4::Koha::GetNormalizedISBN($self->biblioitem->isbn); + my ($self) = @_; + return C4::Koha::GetNormalizedISBN( $self->biblioitem->isbn ); } =head3 public_read_list @@ -1623,11 +1644,11 @@ This method returns the list of publicly readable database fields for both API a sub public_read_list { return [ - 'biblionumber', 'frameworkcode', 'author', - 'title', 'medium', 'subtitle', - 'part_number', 'part_name', 'unititle', - 'notes', 'serial', 'seriestitle', - 'copyrightdate', 'abstract' + 'biblionumber', 'frameworkcode', 'author', + 'title', 'medium', 'subtitle', + 'part_number', 'part_name', 'unititle', + 'notes', 'serial', 'seriestitle', + 'copyrightdate', 'abstract' ]; } @@ -1684,15 +1705,15 @@ on the API. =cut sub to_api { - my ($self, $args) = @_; + my ( $self, $args ) = @_; - my $json_biblio = $self->SUPER::to_api( $args ); + my $json_biblio = $self->SUPER::to_api($args); return unless $json_biblio; $args = defined $args ? {%$args} : {}; delete $args->{embed}; - my $json_biblioitem = $self->biblioitem->to_api( $args ); + my $json_biblioitem = $self->biblioitem->to_api($args); return unless $json_biblioitem; return { %$json_biblio, %$json_biblioitem }; @@ -1707,13 +1728,13 @@ on the API. sub to_api_mapping { return { - biblionumber => 'biblio_id', - frameworkcode => 'framework_id', - unititle => 'uniform_title', - seriestitle => 'series_title', - copyrightdate => 'copyright_date', - datecreated => 'creation_date', - deleted_on => undef, + biblionumber => 'biblio_id', + frameworkcode => 'framework_id', + unititle => 'uniform_title', + seriestitle => 'series_title', + copyrightdate => 'copyright_date', + datecreated => 'creation_date', + deleted_on => undef, }; } @@ -1739,9 +1760,9 @@ sub to_api_mapping { =cut sub get_marc_host { - my ($self, $params) = @_; + my ( $self, $params ) = @_; my $no_items = $params->{no_items}; - return if C4::Context->preference('marcflavour') eq 'UNIMARC'; # TODO + return if C4::Context->preference('marcflavour') eq 'UNIMARC'; # TODO return if $params->{no_items} && $self->items->count > 0; my $record; @@ -1754,32 +1775,36 @@ sub get_marc_host { my $hostfld; foreach my $f ( $record->field('773') ) { my $w = $f->subfield('w') or next; - if( $w =~ /^\($orgcode\)\s*(\d+)/i or $w =~ /^\d+/ ) { + if ( $w =~ /^\($orgcode\)\s*(\d+)/i or $w =~ /^\d+/ ) { $hostfld = $f; last; } } - my $engine = Koha::SearchEngine::Search->new({ index => $Koha::SearchEngine::BIBLIOS_INDEX }); + my $engine = Koha::SearchEngine::Search->new( { index => $Koha::SearchEngine::BIBLIOS_INDEX } ); my $bibno; - if ( !$hostfld and $record->subfield('773','t') ) { + if ( !$hostfld and $record->subfield( '773', 't' ) ) { + # not linked using $w my $unlinkedf = $record->field('773'); my $host; if ( C4::Context->preference("EasyAnalyticalRecords") ) { if ( $unlinkedf->subfield('0') ) { + # use 773$0 host biblionumber $bibno = $unlinkedf->subfield('0'); } elsif ( $unlinkedf->subfield('9') ) { + # use 773$9 host itemnumber my $linkeditemnumber = $unlinkedf->subfield('9'); - $bibno = Koha::Items->find( $linkeditemnumber )->biblionumber; + $bibno = Koha::Items->find($linkeditemnumber)->biblionumber; } } - if ( $bibno ) { + if ($bibno) { my $host = Koha::Biblios->find($bibno) or return; return wantarray ? ( $host, $unlinkedf->subfield('g') ) : $host; } + # just return plaintext and no host record my $hostinfo = join( ", ", $unlinkedf->subfield('a'), $unlinkedf->subfield('t'), $unlinkedf->subfield('g') ); return wantarray ? ( undef, $unlinkedf->subfield('g'), $hostinfo ) : undef; @@ -1788,22 +1813,23 @@ sub get_marc_host { my $rcn = $hostfld->subfield('w'); # Look for control number with/without orgcode - for my $try (1..2) { - my ( $error, $results, $total_hits ) = $engine->simple_search_compat( 'Control-number='.$rcn, 0,1 ); - if( !$error and $total_hits == 1 ) { + for my $try ( 1 .. 2 ) { + my ( $error, $results, $total_hits ) = $engine->simple_search_compat( 'Control-number=' . $rcn, 0, 1 ); + if ( !$error and $total_hits == 1 ) { $bibno = $engine->extract_biblionumber( $results->[0] ); last; } + # Add or remove orgcode for second try - if( $try == 1 && $rcn =~ /\)\s*(\d+)/ ) { - $rcn = $1; # number only - } elsif( $try == 1 && $rcn =~ /^\d+/ ) { + if ( $try == 1 && $rcn =~ /\)\s*(\d+)/ ) { + $rcn = $1; # number only + } elsif ( $try == 1 && $rcn =~ /^\d+/ ) { $rcn = "($orgcode)$rcn"; } else { last; } } - if( $bibno ) { + if ($bibno) { my $host = Koha::Biblios->find($bibno) or return; return wantarray ? ( $host, $hostfld->subfield('g') ) : $host; } @@ -1820,7 +1846,7 @@ Return host only sub get_marc_host_only { my ($self) = @_; - my ( $host ) = $self->get_marc_host; + my ($host) = $self->get_marc_host; return $host; } @@ -2064,7 +2090,7 @@ Return recalls linked to this biblio =cut sub recalls { - my ( $self ) = @_; + my ($self) = @_; return Koha::Recalls->_new_from_dbic( scalar $self->_result->recalls ); } @@ -2088,7 +2114,7 @@ sub can_be_recalled { $branchcode = $patron->branchcode; } - my @all_items = Koha::Items->search({ biblionumber => $self->biblionumber })->as_list; + my @all_items = Koha::Items->search( { biblionumber => $self->biblionumber } )->as_list; # if there are no available items at all, no recall can be placed return 0 if ( scalar @all_items == 0 ); @@ -2097,12 +2123,12 @@ sub can_be_recalled { my @itemnumbers; my @items; my @all_itemnumbers; - foreach my $item ( @all_items ) { + foreach my $item (@all_items) { push( @all_itemnumbers, $item->itemnumber ); - if ( $item->can_be_recalled({ patron => $patron }) ) { - push( @itemtypes, $item->effective_itemtype ); + if ( $item->can_be_recalled( { patron => $patron } ) ) { + push( @itemtypes, $item->effective_itemtype ); push( @itemnumbers, $item->itemnumber ); - push( @items, $item ); + push( @items, $item ); } } @@ -2111,47 +2137,56 @@ sub can_be_recalled { # Check the circulation rule for each relevant itemtype for this biblio my ( @recalls_allowed, @recalls_per_record, @on_shelf_recalls ); - foreach my $itemtype ( @itemtypes ) { - my $rule = Koha::CirculationRules->get_effective_rules({ - branchcode => $branchcode, - categorycode => $patron ? $patron->categorycode : undef, - itemtype => $itemtype, - rules => [ - 'recalls_allowed', - 'recalls_per_record', - 'on_shelf_recalls', - ], - }); - push( @recalls_allowed, $rule->{recalls_allowed} ) if $rule; + foreach my $itemtype (@itemtypes) { + my $rule = Koha::CirculationRules->get_effective_rules( + { + branchcode => $branchcode, + categorycode => $patron ? $patron->categorycode : undef, + itemtype => $itemtype, + rules => [ + 'recalls_allowed', + 'recalls_per_record', + 'on_shelf_recalls', + ], + } + ); + push( @recalls_allowed, $rule->{recalls_allowed} ) if $rule; push( @recalls_per_record, $rule->{recalls_per_record} ) if $rule; - push( @on_shelf_recalls, $rule->{on_shelf_recalls} ) if $rule; + push( @on_shelf_recalls, $rule->{on_shelf_recalls} ) if $rule; } - my $recalls_allowed = (sort {$b <=> $a} @recalls_allowed)[0]; # take highest - my $recalls_per_record = (sort {$b <=> $a} @recalls_per_record)[0]; # take highest + my $recalls_allowed = ( sort { $b <=> $a } @recalls_allowed )[0]; # take highest + my $recalls_per_record = ( sort { $b <=> $a } @recalls_per_record )[0]; # take highest my %on_shelf_recalls_count = (); - foreach my $count ( @on_shelf_recalls ) { + foreach my $count (@on_shelf_recalls) { $on_shelf_recalls_count{$count}++; } - my $on_shelf_recalls = (sort {$on_shelf_recalls_count{$b} <=> $on_shelf_recalls_count{$a}} @on_shelf_recalls)[0]; # take most common + my $on_shelf_recalls = ( sort { $on_shelf_recalls_count{$b} <=> $on_shelf_recalls_count{$a} } @on_shelf_recalls )[0] + ; # take most common # check recalls allowed has been set and is not zero return 0 if ( !defined($recalls_allowed) || $recalls_allowed == 0 ); - if ( $patron ) { + if ($patron) { + # check borrower has not reached open recalls allowed limit return 0 if ( $patron->recalls->filter_by_current->count >= $recalls_allowed ); # check borrower has not reached open recalls allowed per record limit - return 0 if ( $patron->recalls->filter_by_current->search({ biblio_id => $self->biblionumber })->count >= $recalls_per_record ); + return 0 + if ( $patron->recalls->filter_by_current->search( { biblio_id => $self->biblionumber } )->count >= + $recalls_per_record ); # check if any of the items under this biblio are already checked out by this borrower - return 0 if ( Koha::Checkouts->search({ itemnumber => [ @all_itemnumbers ], borrowernumber => $patron->borrowernumber })->count > 0 ); + return 0 + if ( + Koha::Checkouts->search( { itemnumber => [@all_itemnumbers], borrowernumber => $patron->borrowernumber } ) + ->count > 0 ); } # check item availability my $checked_out_count = 0; foreach (@items) { - if ( Koha::Checkouts->search({ itemnumber => $_->itemnumber })->count > 0 ){ $checked_out_count++; } + if ( Koha::Checkouts->search( { itemnumber => $_->itemnumber } )->count > 0 ) { $checked_out_count++; } } # can't recall if on shelf recalls only allowed when all unavailable, but items are still available for checkout @@ -2173,7 +2208,7 @@ Return a Koha::Ratings object representing the ratings of this bibliographic rec =cut sub ratings { - my ( $self ) = @_; + my ($self) = @_; my $rs = $self->_result->ratings; return Koha::Ratings->_new_from_dbic($rs); } diff --git a/Koha/Biblio/ItemGroup.pm b/Koha/Biblio/ItemGroup.pm index 9525a0fe0a..f145dfee5c 100644 --- a/Koha/Biblio/ItemGroup.pm +++ b/Koha/Biblio/ItemGroup.pm @@ -43,12 +43,9 @@ sub store { my ($self) = @_; unless ( $self->in_storage ) { + # new entry - $self->set( - { - created_on => \'NOW()' - } - ); + $self->set( { created_on => \'NOW()' } ); } return $self->SUPER::store(); @@ -70,13 +67,7 @@ sub items { return Koha::Items->new->empty unless @item_ids; - return Koha::Items->search( - { - itemnumber => { - -in => \@item_ids - } - } - ); + return Koha::Items->search( { itemnumber => { -in => \@item_ids } } ); } =head3 add_item @@ -86,15 +77,13 @@ sub items { =cut sub add_item { - my ($self, $params) = @_; + my ( $self, $params ) = @_; my $item_id = $params->{item_id}; - my $item = Koha::Items->find( $item_id ); + my $item = Koha::Items->find($item_id); unless ( $item->biblionumber == $self->biblio_id ) { - Koha::Exceptions::Object::FKConstraint->throw( - broken_fk => 'biblio_id' - ); + Koha::Exceptions::Object::FKConstraint->throw( broken_fk => 'biblio_id' ); } Koha::Biblio::ItemGroup::Item->new( @@ -116,8 +105,8 @@ on the API. sub to_api_mapping { return { - created_on => 'creation_date', - updated_on => 'modification_date' + created_on => 'creation_date', + updated_on => 'modification_date' }; } diff --git a/Koha/Biblio/Metadata.pm b/Koha/Biblio/Metadata.pm index ff14735162..241937625f 100644 --- a/Koha/Biblio/Metadata.pm +++ b/Koha/Biblio/Metadata.pm @@ -20,9 +20,9 @@ use Modern::Perl; use MARC::File::XML; use Scalar::Util qw( blessed ); -use C4::Biblio qw( GetMarcFromKohaField ); +use C4::Biblio qw( GetMarcFromKohaField ); use C4::Charset qw( StripNonXmlChars ); -use C4::Items qw( GetMarcItem ); +use C4::Items qw( GetMarcItem ); use Koha::Database; use Koha::Exceptions::Metadata; @@ -96,11 +96,11 @@ override if necessary. sub record { - my ($self, $params) = @_; + my ( $self, $params ) = @_; - my $record = $params->{record}; + my $record = $params->{record}; my $embed_items = $params->{embed_items}; - my $format = blessed($self) ? $self->format : $params->{format}; + my $format = blessed($self) ? $self->format : $params->{format}; $format ||= 'marcxml'; if ( !$record && !blessed($self) ) { @@ -123,10 +123,8 @@ sub record { decoding_error => $marcxml_error, ); } - } - else { - Koha::Exceptions::Metadata->throw( - 'Koha::Biblio::Metadata->record called on unhandled format: ' . $format ); + } else { + Koha::Exceptions::Metadata->throw( 'Koha::Biblio::Metadata->record called on unhandled format: ' . $format ); } # FIXME: Remove existing items from the MARC record. This should be handled @@ -135,8 +133,8 @@ sub record { my ( $itemtag, $itemsubfield ) = C4::Biblio::GetMarcFromKohaField("items.itemnumber"); $record->delete_field( ( $record->field($itemtag) ) ); - if ( $embed_items ) { - $self->_embed_items({ %$params, format => $format, record => $record }); + if ($embed_items) { + $self->_embed_items( { %$params, format => $format, record => $record } ); } return $record; @@ -223,33 +221,33 @@ sub _embed_items { my $record = $params->{record}; my $format = $params->{format}; my $biblionumber = $params->{biblionumber} || $self->biblionumber; - my $itemnumbers = $params->{itemnumbers} // []; - my $patron = $params->{patron}; - my $opac = $params->{opac}; + my $itemnumbers = $params->{itemnumbers} // []; + my $patron = $params->{patron}; + my $opac = $params->{opac}; if ( $format eq 'marcxml' ) { - my ( $itemtag, $itemsubfield ) = C4::Biblio::GetMarcFromKohaField( "items.itemnumber" ); + my ( $itemtag, $itemsubfield ) = C4::Biblio::GetMarcFromKohaField("items.itemnumber"); my $biblio = Koha::Biblios->find($biblionumber); my $items = $biblio->items; - if ( @$itemnumbers ) { - $items = $items->search({ itemnumber => { -in => $itemnumbers } }); + if (@$itemnumbers) { + $items = $items->search( { itemnumber => { -in => $itemnumbers } } ); } - if ( $opac ) { - $items = $items->filter_by_visible_in_opac({ patron => $patron }); + if ($opac) { + $items = $items->filter_by_visible_in_opac( { patron => $patron } ); } my @itemnumbers = $items->get_column('itemnumber'); my @item_fields; - for my $itemnumber ( @itemnumbers ) { + for my $itemnumber (@itemnumbers) { my $item_marc = C4::Items::GetMarcItem( $biblionumber, $itemnumber ); push @item_fields, $item_marc->field($itemtag); } $record->insert_fields_ordered( reverse @item_fields ); - # insert_fields_ordered with the reverse keeps 952s in right order - } - else { + # insert_fields_ordered with the reverse keeps 952s in right order + + } else { Koha::Exceptions::Metadata->throw( 'Koha::Biblio::Metadata->embed_item called on unhandled format: ' . $format ); } @@ -257,7 +255,6 @@ sub _embed_items { return $record; } - =head3 _type =cut diff --git a/Koha/Biblio/Metadatas.pm b/Koha/Biblio/Metadatas.pm index d31b86501e..24dee9ea2c 100644 --- a/Koha/Biblio/Metadatas.pm +++ b/Koha/Biblio/Metadatas.pm @@ -17,7 +17,6 @@ package Koha::Biblio::Metadatas; use Modern::Perl; - use Koha::Database; use Koha::Biblio::Metadata; diff --git a/Koha/BiblioFramework.pm b/Koha/BiblioFramework.pm index 30367570ba..ffe8845456 100644 --- a/Koha/BiblioFramework.pm +++ b/Koha/BiblioFramework.pm @@ -17,7 +17,6 @@ package Koha::BiblioFramework; use Modern::Perl; - use Koha::Database; use base qw(Koha::Object); diff --git a/Koha/BiblioFrameworks.pm b/Koha/BiblioFrameworks.pm index 7202d2fec5..a66958955e 100644 --- a/Koha/BiblioFrameworks.pm +++ b/Koha/BiblioFrameworks.pm @@ -17,7 +17,6 @@ package Koha::BiblioFrameworks; use Modern::Perl; - use Koha::Database; use Koha::BiblioFramework; diff --git a/Koha/BiblioUtils.pm b/Koha/BiblioUtils.pm index c7e00c4089..fa38faba56 100644 --- a/Koha/BiblioUtils.pm +++ b/Koha/BiblioUtils.pm @@ -34,7 +34,6 @@ use Koha::MetadataIterator; use Koha::Database; use Modern::Perl; - use base qw(Koha::MetadataRecord); __PACKAGE__->mk_accessors(qw( record schema id datatype )); @@ -51,8 +50,8 @@ the biblionumber can be provided too. =cut sub new { - my $class = shift; - my $record = shift; + my $class = shift; + my $record = shift; my $biblionumber = shift; my $self = $class->SUPER::new( @@ -89,10 +88,10 @@ It will return C if the biblio doesn't exist. =cut sub get_from_biblionumber { - my ($class, $bibnum, %options) = @_; + my ( $class, $bibnum, %options ) = @_; - my $marc = $class->get_marc_biblio($bibnum, %options); - return $class->new($marc, $bibnum); + my $marc = $class->get_marc_biblio( $bibnum, %options ); + return $class->new( $marc, $bibnum ); } =head2 get_all_biblios_iterator @@ -120,39 +119,41 @@ records instead of all. =cut sub get_all_biblios_iterator { - my ($class, %options) = @_; + my ( $class, %options ) = @_; my $search_terms = {}; - my ($slice_modulo, $slice_count); - if ($options{slice}) { - $slice_count = $options{slice}->{count}; + my ( $slice_modulo, $slice_count ); + if ( $options{slice} ) { + $slice_count = $options{slice}->{count}; $slice_modulo = $options{slice}->{index}; $search_terms = \[ 'mod(biblionumber, ?) = ?', $slice_count, $slice_modulo ]; } my $search_options = { columns => [qw/ biblionumber /] }; - if ( $options{desc} ){ - $search_options->{order_by} = { -desc => 'biblionumber' }; + if ( $options{desc} ) { + $search_options->{order_by} = { -desc => 'biblionumber' }; } my $database = Koha::Database->new(); my $schema = $database->schema(); - my $rs = Koha::Biblios->search( + my $rs = Koha::Biblios->search( $search_terms, - $search_options ); + $search_options + ); if ( my $sql = $options{where} ) { $rs = $rs->search( \[$sql] ); } my $next_func = sub { + # Warn and skip bad records, otherwise we break the loop while (1) { my $row = $rs->next(); return if !$row; my $next = eval { my $marc = $row->metadata_record( { embed_items => 1 } ); - $class->new($marc, $row->biblionumber); + $class->new( $marc, $row->biblionumber ); }; if ($@) { warn sprintf "Something went wrong reading record for biblio %s: %s\n", $row->biblionumber, $@; @@ -185,7 +186,7 @@ If set to true, item data is embedded in the record. Default is to not do this. =cut sub get_marc_biblio { - my ($class, $bibnum, %options) = @_; + my ( $class, $bibnum, %options ) = @_; my $record = Koha::Biblios->find($bibnum)->metadata_record( { $options{item_data} ? ( embed_items => 1 ) : () } ); return $record; diff --git a/Koha/Biblioitem.pm b/Koha/Biblioitem.pm index b9058ddd54..e17b7080b7 100644 --- a/Koha/Biblioitem.pm +++ b/Koha/Biblioitem.pm @@ -17,7 +17,6 @@ package Koha::Biblioitem; use Modern::Perl; - use Koha::Database; use base qw(Koha::Object); @@ -59,24 +58,24 @@ on the API. sub to_api_mapping { return { - agerestriction => 'age_restriction', - biblionumber => 'biblio_id', - biblioitemnumber => undef, # meaningless - collectionissn => 'collection_issn', - collectiontitle => 'collection_title', - collectionvolume => 'collection_volume', - editionresponsibility => undef, # obsolete, not mapped - editionstatement => 'edition_statement', - illus => 'illustrations', - itemtype => 'item_type', - lccn => 'lc_control_number', - place => 'publication_place', - publicationyear => 'publication_year', - publishercode => 'publisher', - size => 'material_size', - totalissues => 'serial_total_issues', - volumedate => 'volume_date', - volumedesc => 'volume_description', + agerestriction => 'age_restriction', + biblionumber => 'biblio_id', + biblioitemnumber => undef, # meaningless + collectionissn => 'collection_issn', + collectiontitle => 'collection_title', + collectionvolume => 'collection_volume', + editionresponsibility => undef, # obsolete, not mapped + editionstatement => 'edition_statement', + illus => 'illustrations', + itemtype => 'item_type', + lccn => 'lc_control_number', + place => 'publication_place', + publicationyear => 'publication_year', + publishercode => 'publisher', + size => 'material_size', + totalissues => 'serial_total_issues', + volumedate => 'volume_date', + volumedesc => 'volume_description', }; } diff --git a/Koha/Biblioitems.pm b/Koha/Biblioitems.pm index b8d2ba8d56..5f342b3814 100644 --- a/Koha/Biblioitems.pm +++ b/Koha/Biblioitems.pm @@ -17,7 +17,6 @@ package Koha::Biblioitems; use Modern::Perl; - use Koha::Database; use Koha::Biblioitem; diff --git a/Koha/Biblios.pm b/Koha/Biblios.pm index 0cc05aaba8..084e1cb8b5 100644 --- a/Koha/Biblios.pm +++ b/Koha/Biblios.pm @@ -19,7 +19,6 @@ package Koha::Biblios; use Modern::Perl; - use Koha::Database; use Koha::Biblio; @@ -51,22 +50,19 @@ sub pickup_locations { my ( $self, $params ) = @_; Koha::Exceptions::MissingParameter->throw( parameter => 'patron' ) - unless exists $params->{patron}; + unless exists $params->{patron}; my $patron = $params->{patron}; my @pickup_locations; foreach my $biblio ( $self->as_list ) { push @pickup_locations, - $biblio->pickup_locations( { patron => $patron } ) - ->_resultset->get_column('branchcode')->all; + $biblio->pickup_locations( { patron => $patron } )->_resultset->get_column('branchcode')->all; } return Koha::Libraries->search( - { - branchcode => \@pickup_locations - }, - { order_by => ['branchname'] } + { branchcode => \@pickup_locations }, + { order_by => ['branchname'] } ); } @@ -93,7 +89,7 @@ sub api_query_fixer { } else { $query =~ s/${quotes}(age_restriction|cn_class|cn_item|cn_sort|cn_source|cn_suffix|collection_issn|collection_title|collection_volume|ean|edition_statement|illustrations|isbn|issn|item_type|lc_control_number|notes|number|pages|publication_place|publication_year|publisher|material_size|serial_total_issues|url|volume|volume_date|volume_description)${quotes}/${quotes}biblioitem\.$1${quotes}/g; - $query =~ # handle ambiguous 'biblionumber' + $query =~ # handle ambiguous 'biblionumber' s/${quotes}(biblio_id)${quotes}/${quotes}me\.$1${quotes}/g; } diff --git a/Koha/Booking.pm b/Koha/Booking.pm index 8e9c45ad71..ab5a418047 100644 --- a/Koha/Booking.pm +++ b/Koha/Booking.pm @@ -148,6 +148,7 @@ sub store { booking_id => $self->in_storage ? $self->booking_id : undef } ); + # FIXME: We should be able to combine the above two functions into one # Assign item at booking time diff --git a/Koha/Cache.pm b/Koha/Cache.pm index 2186d82743..709b6a5e36 100644 --- a/Koha/Cache.pm +++ b/Koha/Cache.pm @@ -40,7 +40,7 @@ The first, traditional OO interface provides the following functions: use strict; use warnings; -use Carp qw( croak ); +use Carp qw( croak ); use Module::Load::Conditional qw( can_load ); use Sereal::Encoder; use Sereal::Decoder; @@ -51,8 +51,7 @@ use Koha::Config; use base qw(Class::Accessor); -__PACKAGE__->mk_ro_accessors( - qw( cache memcached_cache )); +__PACKAGE__->mk_ro_accessors(qw( cache memcached_cache )); our %L1_cache; our $L1_encoder = Sereal::Encoder->new; @@ -66,14 +65,14 @@ Create a new Koha::Cache object. This is required for all cache-related function sub new { my ( $class, $self, $params ) = @_; - $self->{'default_type'} = - $self->{cache_type} - || $ENV{CACHING_SYSTEM} # DELME What about this? - || 'memcached'; + $self->{'default_type'} = $self->{cache_type} + || $ENV{CACHING_SYSTEM} # DELME What about this? + || 'memcached'; my $subnamespace = $params->{subnamespace} // ''; - $self->{'timeout'} ||= 0; + $self->{'timeout'} ||= 0; + # Should we continue to support MEMCACHED ENV vars? $self->{'namespace'} ||= $ENV{MEMCACHED_NAMESPACE}; my @servers = split /,/, $ENV{MEMCACHED_SERVERS} || ''; @@ -82,21 +81,21 @@ sub new { unless @servers; $self->{namespace} .= ":$subnamespace:"; - if ( $self->{'default_type'} eq 'memcached' + if ( $self->{'default_type'} eq 'memcached' && can_load( modules => { 'Cache::Memcached::Fast::Safe' => undef } ) - && _initialize_memcached($self, @servers) + && _initialize_memcached( $self, @servers ) && defined( $self->{'memcached_cache'} ) ) { $self->{'cache'} = $self->{'memcached_cache'}; } return - bless $self, - $class; + bless $self, + $class; } sub _initialize_memcached { - my ($self, @servers) = @_; + my ( $self, @servers ) = @_; return unless @servers; @@ -112,9 +111,10 @@ sub _initialize_memcached { ); # Ensure we can actually talk to the memcached server - my $ismemcached = $memcached->set('ismemcached','1'); + my $ismemcached = $memcached->set( 'ismemcached', '1' ); unless ($ismemcached) { - warn "\nConnection to the memcached servers '@servers' failed. Are the unix socket permissions set properly? Is the host reachable?\nIf you ignore this warning, you will face performance issues\n"; + warn + "\nConnection to the memcached servers '@servers' failed. Are the unix socket permissions set properly? Is the host reachable?\nIf you ignore this warning, you will face performance issues\n"; return $self; } $self->{'memcached_cache'} = $memcached; @@ -172,34 +172,36 @@ sub set_in_cache { return unless ( $self->{$cache} && ref( $self->{$cache} ) =~ m/^Cache::/ ); my $expiry = $options->{expiry}; $expiry //= $self->{timeout}; - my $set_sub = $self->{ref($self->{$cache}) . "_set"}; + my $set_sub = $self->{ ref( $self->{$cache} ) . "_set" }; + + my $flag = '-CF0'; # 0: scalar, 1: frozen data structure + if ( ref($value) ) { - my $flag = '-CF0'; # 0: scalar, 1: frozen data structure - if (ref($value)) { # Set in L1 cache as a data structure # We only save the frozen form: we do want to save $value in L1 # directly in order to protect it. And thawing now may not be # needed, so improves performance. - $value = $L1_encoder->encode($value); - $L1_cache{$self->{namespace}}{$key}->{frozen} = $value; - $flag = '-CF1'; + $value = $L1_encoder->encode($value); + $L1_cache{ $self->{namespace} }{$key}->{frozen} = $value; + $flag = '-CF1'; } else { + # Set in L1 cache as a scalar; exit if we are caching an undef - $L1_cache{$self->{namespace}}{$key} = $value; + $L1_cache{ $self->{namespace} }{$key} = $value; return if !defined $value; } $value .= $flag; + # We consider an expiry of 0 to be infinite - if ( $expiry ) { + if ($expiry) { return $set_sub - ? $set_sub->( $key, $value, $expiry ) - : $self->{$cache}->set( $key, $value, $expiry ); - } - else { + ? $set_sub->( $key, $value, $expiry ) + : $self->{$cache}->set( $key, $value, $expiry ); + } else { return $set_sub - ? $set_sub->( $key, $value ) - : $self->{$cache}->set( $key, $value ); + ? $set_sub->( $key, $value ) + : $self->{$cache}->set( $key, $value ); } } @@ -235,43 +237,49 @@ sub get_from_cache { my $unsafe = $options->{unsafe} || 0; $key =~ s/[\x00-\x20]/_/g; croak "No key" unless $key; - return unless ( $self->{$cache} && ref( $self->{$cache} ) =~ m/^Cache::/ ); + return unless ( $self->{$cache} && ref( $self->{$cache} ) =~ m/^Cache::/ ); # Return L1 cache value if exists - if ( exists $L1_cache{$self->{namespace}}{$key} ) { - if (ref($L1_cache{$self->{namespace}}{$key})) { + if ( exists $L1_cache{ $self->{namespace} }{$key} ) { + if ( ref( $L1_cache{ $self->{namespace} }{$key} ) ) { if ($unsafe) { + # ONLY use thawed for unsafe calls !!! - $L1_cache{$self->{namespace}}{$key}->{thawed} ||= $L1_decoder->decode($L1_cache{$self->{namespace}}{$key}->{frozen}); - return $L1_cache{$self->{namespace}}{$key}->{thawed}; + $L1_cache{ $self->{namespace} }{$key}->{thawed} ||= + $L1_decoder->decode( $L1_cache{ $self->{namespace} }{$key}->{frozen} ); + return $L1_cache{ $self->{namespace} }{$key}->{thawed}; } else { - return $L1_decoder->decode($L1_cache{$self->{namespace}}{$key}->{frozen}); + return $L1_decoder->decode( $L1_cache{ $self->{namespace} }{$key}->{frozen} ); } } else { + # No need to thaw if it's a scalar - return $L1_cache{$self->{namespace}}{$key}; + return $L1_cache{ $self->{namespace} }{$key}; } } - my $get_sub = $self->{ref($self->{$cache}) . "_get"}; + my $get_sub = $self->{ ref( $self->{$cache} ) . "_get" }; my $L2_value = $get_sub ? $get_sub->($key) : $self->{$cache}->get($key); return if ref($L2_value); - return unless (defined($L2_value) && length($L2_value) >= 4); + return unless ( defined($L2_value) && length($L2_value) >= 4 ); + + my $flag = substr( $L2_value, -4, 4, '' ); + if ( $flag eq '-CF0' ) { - my $flag = substr($L2_value, -4, 4, ''); - if ($flag eq '-CF0') { # it's a scalar - $L1_cache{$self->{namespace}}{$key} = $L2_value; + $L1_cache{ $self->{namespace} }{$key} = $L2_value; return $L2_value; - } elsif ($flag eq '-CF1') { + } elsif ( $flag eq '-CF1' ) { + # it's a frozen data structure my $thawed; eval { $thawed = $L1_decoder->decode($L2_value); }; return if $@; - $L1_cache{$self->{namespace}}{$key}->{frozen} = $L2_value; + $L1_cache{ $self->{namespace} }{$key}->{frozen} = $L2_value; + # ONLY save thawed for unsafe calls !!! - $L1_cache{$self->{namespace}}{$key}->{thawed} = $thawed if $unsafe; + $L1_cache{ $self->{namespace} }{$key}->{thawed} = $thawed if $unsafe; return $thawed; } @@ -292,13 +300,13 @@ sub clear_from_cache { $key =~ s/[\x00-\x20]/_/g; $cache ||= 'cache'; croak "No key" unless $key; - return unless ( $self->{$cache} && ref( $self->{$cache} ) =~ m/^Cache::/ ); + return unless ( $self->{$cache} && ref( $self->{$cache} ) =~ m/^Cache::/ ); # Clear from L1 cache - delete $L1_cache{$self->{namespace}}{$key}; + delete $L1_cache{ $self->{namespace} }{$key}; return $self->{$cache}->delete($key) - if ( ref( $self->{$cache} ) =~ m'^Cache::Memcached' ); + if ( ref( $self->{$cache} ) =~ m'^Cache::Memcached' ); return $self->{$cache}->remove($key); } @@ -318,13 +326,13 @@ sub flush_all { $self->flush_L1_cache(); return $self->{$cache}->flush_all() - if ( ref( $self->{$cache} ) =~ m'^Cache::Memcached' ); + if ( ref( $self->{$cache} ) =~ m'^Cache::Memcached' ); return $self->{$cache}->clear(); } sub flush_L1_cache { - my( $self ) = @_; - delete $L1_cache{$self->{namespace}}; + my ($self) = @_; + delete $L1_cache{ $self->{namespace} }; } =head1 TIED INTERFACE diff --git a/Koha/Cache/Memory/Lite.pm b/Koha/Cache/Memory/Lite.pm index ebdb0431d4..2d7302f89c 100644 --- a/Koha/Cache/Memory/Lite.pm +++ b/Koha/Cache/Memory/Lite.pm @@ -107,7 +107,7 @@ Returns an array of all keys currently in the lite cache. =cut sub all_keys { - my ( $self ) = @_; + my ($self) = @_; return keys %L1_cache; } @@ -120,7 +120,7 @@ Clear the entire lite cache. =cut sub flush { - my ( $self ) = @_; + my ($self) = @_; %L1_cache = (); } diff --git a/Koha/Cache/Object.pm b/Koha/Cache/Object.pm index 4bdd9106b3..079cfb7d1c 100644 --- a/Koha/Cache/Object.pm +++ b/Koha/Cache/Object.pm @@ -56,8 +56,7 @@ use warnings; use base qw(Class::Accessor); __PACKAGE__->mk_ro_accessors( - qw( allowupdate arguments cache cache_type constructor destructor inprocess key lastupdate timeout unset value ) -); + qw( allowupdate arguments cache cache_type constructor destructor inprocess key lastupdate timeout unset value )); # General/SCALAR routines @@ -69,8 +68,10 @@ sub TIESCALAR { if ( defined $self->{'preload'} ) { $self->{'value'} = &{ $self->{'preload'} }( @{ $self->{'arguments'} } ); if ( defined( $self->{'cache'} ) ) { - $self->{'cache'}->set_in_cache( $self->{'key'}, $self->{'value'}, - { expiry => $self->{'timeout'} } ); + $self->{'cache'}->set_in_cache( + $self->{'key'}, $self->{'value'}, + { expiry => $self->{'timeout'} } + ); } $self->{'lastupdate'} = time; } @@ -85,7 +86,7 @@ sub FETCH { if ( !( $self->{'inprocess'} && defined( $self->{'value'} ) ) && $self->{'cache'} ) { - $self->{'value'} = $self->{'cache'}->get_from_cache( $self->{'key'} ); + $self->{'value'} = $self->{'cache'}->get_from_cache( $self->{'key'} ); $self->{'lastupdate'} = $now; } @@ -94,12 +95,15 @@ sub FETCH { || !defined $self->{'lastupdate'} || ( $now - $self->{'lastupdate'} > $self->{'timeout'} ) ) { - $self->{'value'} = - &{ $self->{'constructor'} }( @{ $self->{'arguments'} }, - $self->{'value'}, $index ); + $self->{'value'} = &{ $self->{'constructor'} }( + @{ $self->{'arguments'} }, + $self->{'value'}, $index + ); if ( defined( $self->{'cache'} ) ) { - $self->{'cache'}->set_in_cache( $self->{'key'}, $self->{'value'}, - { expiry => $self->{'timeout'} } ); + $self->{'cache'}->set_in_cache( + $self->{'key'}, $self->{'value'}, + { expiry => $self->{'timeout'} } + ); } $self->{'lastupdate'} = $now; } @@ -115,15 +119,15 @@ sub STORE { if ( $self->{'datatype'} eq 'HASH' && defined($index) ) { $self->{'value'}->{$index} = $value; - } - else { + } else { $self->{'value'} = $value; } if ( defined( $self->{'allowupdate'} ) && $self->{'allowupdate'} && defined( $self->{'cache'} ) ) { - $self->{'cache'}->set_in_cache( $self->{'key'}, $self->{'value'}, + $self->{'cache'}->set_in_cache( + $self->{'key'}, $self->{'value'}, { expiry => $self->{'timeout'} }, ); } @@ -186,7 +190,7 @@ sub SCALAR { my ($self) = @_; $self->FETCH; return scalar %{ $self->{'value'} } - if ( ref( $self->{'value'} ) eq 'HASH' ); + if ( ref( $self->{'value'} ) eq 'HASH' ); return; } diff --git a/Koha/Caches.pm b/Koha/Caches.pm index 89409255a4..1089358bf4 100644 --- a/Koha/Caches.pm +++ b/Koha/Caches.pm @@ -46,9 +46,9 @@ persistent across multiple instances. =cut sub get_instance { - my ($class, $subnamespace) = @_; + my ( $class, $subnamespace ) = @_; $subnamespace //= ''; - $singleton_caches->{$subnamespace} = Koha::Cache->new({}, { subnamespace => $subnamespace } ) + $singleton_caches->{$subnamespace} = Koha::Cache->new( {}, { subnamespace => $subnamespace } ) unless $singleton_caches->{$subnamespace}; return $singleton_caches->{$subnamespace}; } diff --git a/Koha/Calendar.pm b/Koha/Calendar.pm index 645b538700..5223220c86 100644 --- a/Koha/Calendar.pm +++ b/Koha/Calendar.pm @@ -34,28 +34,26 @@ sub new { } sub _init { - my $self = shift; - my $branch = $self->{branchcode}; - my $dbh = C4::Context->dbh(); - my $weekly_closed_days_sth = $dbh->prepare( -'SELECT weekday FROM repeatable_holidays WHERE branchcode = ? AND weekday IS NOT NULL' - ); - $weekly_closed_days_sth->execute( $branch ); + my $self = shift; + my $branch = $self->{branchcode}; + my $dbh = C4::Context->dbh(); + my $weekly_closed_days_sth = + $dbh->prepare('SELECT weekday FROM repeatable_holidays WHERE branchcode = ? AND weekday IS NOT NULL'); + $weekly_closed_days_sth->execute($branch); $self->{weekly_closed_days} = [ 0, 0, 0, 0, 0, 0, 0 ]; while ( my $tuple = $weekly_closed_days_sth->fetchrow_hashref ) { $self->{weekly_closed_days}->[ $tuple->{weekday} ] = 1; } - my $day_month_closed_days_sth = $dbh->prepare( -'SELECT day, month FROM repeatable_holidays WHERE branchcode = ? AND weekday IS NULL' - ); - $day_month_closed_days_sth->execute( $branch ); + my $day_month_closed_days_sth = + $dbh->prepare('SELECT day, month FROM repeatable_holidays WHERE branchcode = ? AND weekday IS NULL'); + $day_month_closed_days_sth->execute($branch); $self->{day_month_closed_days} = {}; while ( my $tuple = $day_month_closed_days_sth->fetchrow_hashref ) { $self->{day_month_closed_days}->{ $tuple->{month} }->{ $tuple->{day} } = - 1; + 1; } - $self->{test} = 0; + $self->{test} = 0; return; } @@ -80,17 +78,12 @@ sub _holidays { # Add holidays for each branch my $holidays_sth = $dbh->prepare( -'SELECT day, month, year, MAX(isexception) FROM special_holidays WHERE branchcode = ? GROUP BY day, month, year' + 'SELECT day, month, year, MAX(isexception) FROM special_holidays WHERE branchcode = ? GROUP BY day, month, year' ); - $holidays_sth->execute($self->{branchcode}); + $holidays_sth->execute( $self->{branchcode} ); - while ( my ( $day, $month, $year, $exception ) = - $holidays_sth->fetchrow ) - { - my $datestring = - sprintf( "%04d", $year ) - . sprintf( "%02d", $month ) - . sprintf( "%02d", $day ); + while ( my ( $day, $month, $year, $exception ) = $holidays_sth->fetchrow ) { + my $datestring = sprintf( "%04d", $year ) . sprintf( "%02d", $month ) . sprintf( "%02d", $day ); $holidays->{$datestring} = $exception ? 0 : 1; } @@ -102,7 +95,6 @@ sub _holidays { sub addDuration { my ( $self, $startdate, $add_duration, $unit ) = @_; - Koha::Exceptions::MissingParameter->throw("Missing mandatory option for Koha:Calendar->addDuration: days_mode") unless exists $self->{days_mode}; @@ -111,16 +103,18 @@ sub addDuration { $add_duration = DateTime::Duration->new( days => $add_duration ); } - $unit ||= 'days'; # default days ? + $unit ||= 'days'; # default days ? my $dt; if ( $unit eq 'hours' ) { + # Fixed for legacy support. Should be set as a branch parameter my $return_by_hour = 10; - $dt = $self->addHours($startdate, $add_duration, $return_by_hour); + $dt = $self->addHours( $startdate, $add_duration, $return_by_hour ); } else { + # days - $dt = $self->addDays($startdate, $add_duration); + $dt = $self->addDays( $startdate, $add_duration ); } return $dt; } @@ -137,13 +131,14 @@ sub addHours { Koha::Exceptions::MissingParameter->throw("Missing mandatory option for Koha:Calendar->addHours: days_mode") unless exists $self->{days_mode}; - if ( $self->{days_mode} ne 'Days' && - $self->is_holiday($base_date) ) { + if ( $self->{days_mode} ne 'Days' + && $self->is_holiday($base_date) ) + { if ( $hours_duration->is_negative() ) { - $base_date = $self->prev_open_days($base_date, 1); + $base_date = $self->prev_open_days( $base_date, 1 ); } else { - $base_date = $self->next_open_days($base_date, 1); + $base_date = $self->next_open_days( $base_date, 1 ); } $base_date->set_hour($return_by_hour); @@ -161,42 +156,44 @@ sub addDays { unless exists $self->{days_mode}; if ( $self->{days_mode} eq 'Calendar' ) { + # use the calendar to skip all days the library is closed # when adding my $days = abs $days_duration->in_units('days'); if ( $days_duration->is_negative() ) { while ($days) { - $base_date = $self->prev_open_days($base_date, 1); + $base_date = $self->prev_open_days( $base_date, 1 ); --$days; } } else { while ($days) { - $base_date = $self->next_open_days($base_date, 1); + $base_date = $self->next_open_days( $base_date, 1 ); --$days; } } - } else { # Days, Datedue or Dayweek - # use straight days, then use calendar to push - # the date to the next open day as appropriate - # if Datedue or Dayweek + } else { # Days, Datedue or Dayweek + # use straight days, then use calendar to push + # the date to the next open day as appropriate + # if Datedue or Dayweek $base_date->add_duration($days_duration); - if ( $self->{days_mode} eq 'Datedue' || - $self->{days_mode} eq 'Dayweek') { + if ( $self->{days_mode} eq 'Datedue' + || $self->{days_mode} eq 'Dayweek' ) + { # Datedue or Dayweek, then use the calendar to push # the date to the next open day if holiday if ( $self->is_holiday($base_date) ) { - my $dow = $base_date->day_of_week; + my $dow = $base_date->day_of_week; my $days = $days_duration->in_units('days'); + # Is it a period based on weeks - my $push_amt = $days % 7 == 0 ? - $self->get_push_amt($base_date) : 1; + my $push_amt = $days % 7 == 0 ? $self->get_push_amt($base_date) : 1; if ( $days_duration->is_negative() ) { - $base_date = $self->prev_open_days($base_date, $push_amt); + $base_date = $self->prev_open_days( $base_date, $push_amt ); } else { - $base_date = $self->next_open_days($base_date, $push_amt); + $base_date = $self->next_open_days( $base_date, $push_amt ); } } } @@ -206,12 +203,13 @@ sub addDays { } sub get_push_amt { - my ( $self, $base_date) = @_; + my ( $self, $base_date ) = @_; Koha::Exceptions::MissingParameter->throw("Missing mandatory option for Koha:Calendar->get_push_amt: days_mode") unless exists $self->{days_mode}; my $dow = $base_date->day_of_week; + # Representation fix # DateTime object dow (1-7) where Monday is 1 # Arrays are 0-based where 0 = Sunday, not 7. @@ -222,8 +220,9 @@ sub get_push_amt { return ( # We're using Dayweek useDaysMode option $self->{days_mode} eq 'Dayweek' && - # It's not a permanently closed day - !$self->{weekly_closed_days}->[$dow] + + # It's not a permanently closed day + !$self->{weekly_closed_days}->[$dow] ) ? 7 : 1; } @@ -231,17 +230,18 @@ sub is_holiday { my ( $self, $dt ) = @_; my $localdt = $dt->clone(); - my $day = $localdt->day; - my $month = $localdt->month; - my $ymd = $localdt->ymd(''); + my $day = $localdt->day; + my $month = $localdt->month; + my $ymd = $localdt->ymd(''); #Change timezone to "floating" before doing any calculations or comparisons $localdt->set_time_zone("floating"); $localdt->truncate( to => 'day' ); - return $self->_holidays->{$ymd} if defined($self->_holidays->{$ymd}); + return $self->_holidays->{$ymd} if defined( $self->_holidays->{$ymd} ); my $dow = $localdt->day_of_week; + # Representation fix # DateTime object dow (1-7) where Monday is 1 # Arrays are 0-based where 0 = Sunday, not 7. @@ -269,11 +269,11 @@ sub next_open_days { my $base_date = $dt->clone(); - $base_date->add(days => $to_add); + $base_date->add( days => $to_add ); my $i = 0; while ( $self->is_holiday($base_date) && $i < OPEN_DAYS_SEARCH_MAX_ITERATIONS ) { my $add_next = $self->get_push_amt($base_date); - $base_date->add(days => $add_next); + $base_date->add( days => $add_next ); ++$i; } @@ -297,14 +297,15 @@ sub prev_open_days { # subtracting, so do the right thing $to_sub = $to_sub > 0 ? 0 - $to_sub : $to_sub; - $base_date->add(days => $to_sub); + $base_date->add( days => $to_sub ); my $i = 0; while ( $self->is_holiday($base_date) && $i < OPEN_DAYS_SEARCH_MAX_ITERATIONS ) { my $sub_next = $self->get_push_amt($base_date); + # Ensure we're subtracting when we need to be $sub_next = $sub_next > 0 ? 0 - $sub_next : $sub_next; - $base_date->add(days => $sub_next); + $base_date->add( days => $sub_next ); ++$i; } @@ -328,8 +329,8 @@ sub days_forward { my $base_dt = $start_dt->clone(); - while ($num_days--) { - $base_dt = $self->next_open_days($base_dt, 1); + while ( $num_days-- ) { + $base_dt = $self->next_open_days( $base_dt, 1 ); } return $base_dt; @@ -342,14 +343,14 @@ sub days_between { # Change time zone for date math and swap if needed $start_dt = $start_dt->clone->set_time_zone('floating'); - $end_dt = $end_dt->clone->set_time_zone('floating'); - if( $start_dt->compare($end_dt) > 0 ) { + $end_dt = $end_dt->clone->set_time_zone('floating'); + if ( $start_dt->compare($end_dt) > 0 ) { ( $start_dt, $end_dt ) = ( $end_dt, $start_dt ); } # start and end should not be closed days my $delta_days = $start_dt->delta_days($end_dt)->delta_days; - while( $start_dt->compare($end_dt) < 1 ) { + while ( $start_dt->compare($end_dt) < 1 ) { $delta_days-- if $self->is_holiday($start_dt); $start_dt->add( days => 1 ); } @@ -357,9 +358,9 @@ sub days_between { } sub hours_between { - my ($self, $start_date, $end_date) = @_; + my ( $self, $start_date, $end_date ) = @_; my $start_dt = $start_date->clone()->set_time_zone('floating'); - my $end_dt = $end_date->clone()->set_time_zone('floating'); + my $end_dt = $end_date->clone()->set_time_zone('floating'); my $duration = $end_dt->delta_ms($start_dt); $start_dt->truncate( to => 'day' ); @@ -370,13 +371,13 @@ sub hours_between { # take into account open/close times then it would be a duration # of library open hours my $skipped_days = 0; - while( $start_dt->compare($end_dt) < 1 ) { + while ( $start_dt->compare($end_dt) < 1 ) { $skipped_days++ if $self->is_holiday($start_dt); $start_dt->add( days => 1 ); } if ($skipped_days) { - $duration->subtract_duration(DateTime::Duration->new( hours => 24 * $skipped_days)); + $duration->subtract_duration( DateTime::Duration->new( hours => 24 * $skipped_days ) ); } return $duration; diff --git a/Koha/Cash/Register.pm b/Koha/Cash/Register.pm index 1f794bfaef..19a1ecf937 100644 --- a/Koha/Cash/Register.pm +++ b/Koha/Cash/Register.pm @@ -17,7 +17,6 @@ package Koha::Cash::Register; use Modern::Perl; - use Koha::Account::Lines; use Koha::Account::Offsets; use Koha::Cash::Register::Actions; @@ -46,7 +45,7 @@ Return the library linked to this cash register sub library { my ($self) = @_; - return Koha::Library->_new_from_dbic($self->_result->branch); + return Koha::Library->_new_from_dbic( $self->_result->branch ); } =head3 cashups @@ -62,9 +61,10 @@ sub cashups { $conditions //= {}; my $merged_conditions = { %{$conditions}, %{$local_conditions} }; - my $rs = - $self->_result->search_related( 'cash_register_actions', - $merged_conditions, $attrs ); + my $rs = $self->_result->search_related( + 'cash_register_actions', + $merged_conditions, $attrs + ); return Koha::Cash::Register::Cashups->_new_from_dbic($rs); } @@ -122,17 +122,18 @@ sub outstanding_accountlines { ); my $local_conditions = - $since->count - ? { 'date' => { '>' => $since->get_column('timestamp')->as_query } } - : {}; + $since->count + ? { 'date' => { '>' => $since->get_column('timestamp')->as_query } } + : {}; my $merged_conditions = - $conditions - ? { %{$conditions}, %{$local_conditions} } - : $local_conditions; + $conditions + ? { %{$conditions}, %{$local_conditions} } + : $local_conditions; - my $rs = - $self->_result->search_related( 'accountlines', $merged_conditions, - $attrs ); + my $rs = $self->_result->search_related( + 'accountlines', $merged_conditions, + $attrs + ); return Koha::Account::Lines->_new_from_dbic($rs); } @@ -149,10 +150,8 @@ sub store { $self->_result->result_source->schema->txn_do( sub { if ( $self->_result->is_column_changed('branch_default') ) { - Koha::Exceptions::Object::ReadOnlyProperty->throw( - property => 'branch_default' ); - } - else { + Koha::Exceptions::Object::ReadOnlyProperty->throw( property => 'branch_default' ); + } else { if ( $self->_result->is_column_changed('branch') && $self->branch_default ) { @@ -176,8 +175,7 @@ sub make_default { $self->_result->result_source->schema->txn_do( sub { - my $registers = - Koha::Cash::Registers->search( { branch => $self->branch } ); + my $registers = Koha::Cash::Registers->search( { branch => $self->branch } ); $registers->update( { branch_default => 0 }, { no_triggers => 1 } ); $self->set( { branch_default => 1 } ); $self->SUPER::store; diff --git a/Koha/Cash/Register/Action.pm b/Koha/Cash/Register/Action.pm index 34118695c4..d3ca24d7c3 100644 --- a/Koha/Cash/Register/Action.pm +++ b/Koha/Cash/Register/Action.pm @@ -17,7 +17,6 @@ package Koha::Cash::Register::Action; use Modern::Perl; - use Koha::Database; use base qw(Koha::Object); diff --git a/Koha/Cash/Register/Actions.pm b/Koha/Cash/Register/Actions.pm index d470b4d437..adf4ad5b6b 100644 --- a/Koha/Cash/Register/Actions.pm +++ b/Koha/Cash/Register/Actions.pm @@ -17,7 +17,6 @@ package Koha::Cash::Register::Actions; use Modern::Perl; - use Koha::Database; use Koha::Cash::Register::Action; diff --git a/Koha/Cash/Register/Cashup.pm b/Koha/Cash/Register/Cashup.pm index 18d6d0c536..b9b0e07afe 100644 --- a/Koha/Cash/Register/Cashup.pm +++ b/Koha/Cash/Register/Cashup.pm @@ -17,7 +17,6 @@ package Koha::Cash::Register::Cashup; use Modern::Perl; - use Koha::Database; use base qw(Koha::Cash::Register::Action); @@ -45,7 +44,7 @@ sub search { unless ( exists $attr->{order_by} ) { $attr->{order_by} = - [ { '-asc' => 'register_id' }, { '-desc' => 'timestamp' } ]; + [ { '-asc' => 'register_id' }, { '-desc' => 'timestamp' } ]; } return $self->SUPER::search( $where, $attr ); @@ -76,14 +75,9 @@ sub summary { my $previous = $prior_cashup->single; my $conditions = - $previous - ? { - 'date' => { - '-between' => - [ $previous->_result->get_column('timestamp'), $self->timestamp ] - } - } - : { 'date' => { '<' => $self->timestamp } }; + $previous + ? { 'date' => { '-between' => [ $previous->_result->get_column('timestamp'), $self->timestamp ] } } + : { 'date' => { '<' => $self->timestamp } }; my $payout_transactions = $self->register->accountlines->search( { %{$conditions}, credit_type_code => undef }, @@ -94,16 +88,12 @@ sub summary { my $income_summary = Koha::Account::Offsets->search( { - 'me.credit_id' => { - '-in' => $income_transactions->_resultset->get_column( - 'accountlines_id')->as_query - }, - 'me.debit_id' => { '!=' => undef } + 'me.credit_id' => { '-in' => $income_transactions->_resultset->get_column('accountlines_id')->as_query }, + 'me.debit_id' => { '!=' => undef } }, { - join => { 'debit' => 'debit_type_code' }, - group_by => - [ 'debit.debit_type_code', 'debit_type_code.description' ], + join => { 'debit' => 'debit_type_code' }, + group_by => [ 'debit.debit_type_code', 'debit_type_code.description' ], 'select' => [ { sum => 'me.amount' }, 'debit.debit_type_code', 'debit_type_code.description' @@ -115,24 +105,16 @@ sub summary { my $payout_summary = Koha::Account::Offsets->search( { - 'me.debit_id' => { - '-in' => $payout_transactions->_resultset->get_column( - 'accountlines_id')->as_query - }, - 'me.credit_id' => { '!=' => undef }, - 'account_offsets_credits.debit_id' => { - '-not_in' => $payout_transactions->_resultset->get_column( - 'accountlines_id')->as_query - } + 'me.debit_id' => { '-in' => $payout_transactions->_resultset->get_column('accountlines_id')->as_query }, + 'me.credit_id' => { '!=' => undef }, + 'account_offsets_credits.debit_id' => + { '-not_in' => $payout_transactions->_resultset->get_column('accountlines_id')->as_query } }, { join => { 'credit' => [ 'credit_type_code', - { - 'account_offsets_credits' => - { 'debit' => 'debit_type_code' } - } + { 'account_offsets_credits' => { 'debit' => 'debit_type_code' } } ] }, group_by => [ @@ -140,7 +122,7 @@ sub summary { 'debit.debit_type_code', 'debit_type_code.description' ], 'select' => [ - { sum => 'me.amount' }, 'credit.credit_type_code', + { sum => 'me.amount' }, 'credit.credit_type_code', 'credit_type_code.description', 'debit.debit_type_code', 'debit_type_code.description' ], @@ -149,10 +131,7 @@ sub summary { 'credit_description', 'debit_type_code', 'debit_description' ], - order_by => { - '-asc' => - [ 'credit_type_code.description', 'debit_type_code.description' ] - }, + order_by => { '-asc' => [ 'credit_type_code.description', 'debit_type_code.description' ] }, } ); @@ -160,19 +139,17 @@ sub summary { { total => $_->get_column('total') * -1, debit_type_code => $_->get_column('debit_type_code'), - debit_type => { description => $_->get_column('debit_description') } + debit_type => { description => $_->get_column('debit_description') } } } $income_summary->as_list; my @payout = map { { total => $_->get_column('total') * -1, credit_type_code => $_->get_column('credit_type_code'), - credit_type => - { description => $_->get_column('credit_description') }, - related_debit => { + credit_type => { description => $_->get_column('credit_description') }, + related_debit => { debit_type_code => $_->get_column('debit_type_code'), - debit_type => - { description => $_->get_column('debit_description') } + debit_type => { description => $_->get_column('debit_description') } } } } $payout_summary->as_list; @@ -182,9 +159,7 @@ sub summary { my $total = ( $income_total + $payout_total ); my $payment_types = Koha::AuthorisedValues->search( - { - category => 'PAYMENT_TYPE' - }, + { category => 'PAYMENT_TYPE' }, { order_by => ['lib'], } @@ -194,7 +169,7 @@ sub summary { for my $type ( $payment_types->as_list ) { my $typed_income = $income_transactions->total( { payment_type => $type->authorised_value } ); my $typed_payout = $payout_transactions->total( { payment_type => $type->authorised_value } ); - my $typed_total = ( $typed_income + $typed_payout ); + my $typed_total = ( $typed_income + $typed_payout ); push @total_grouped, { payment_type => $type->lib, total => $typed_total }; } diff --git a/Koha/Cash/Register/Cashups.pm b/Koha/Cash/Register/Cashups.pm index 58a562c0cb..d768fb260e 100644 --- a/Koha/Cash/Register/Cashups.pm +++ b/Koha/Cash/Register/Cashups.pm @@ -17,7 +17,6 @@ package Koha::Cash::Register::Cashups; use Modern::Perl; - use Koha::Database; use Koha::Cash::Register::Cashup; @@ -44,10 +43,10 @@ sub search { unless ( exists $attr->{order_by} ) { $attr->{order_by} = - [ { '-asc' => 'register_id' }, { '-desc' => 'timestamp' } ]; + [ { '-asc' => 'register_id' }, { '-desc' => 'timestamp' } ]; } - my $rs = $self->SUPER::search({ code => 'CASHUP' }); + my $rs = $self->SUPER::search( { code => 'CASHUP' } ); return $rs->SUPER::search( $where, $attr ); } diff --git a/Koha/Cash/Registers.pm b/Koha/Cash/Registers.pm index 9576492caa..d62296ef43 100644 --- a/Koha/Cash/Registers.pm +++ b/Koha/Cash/Registers.pm @@ -17,7 +17,6 @@ package Koha::Cash::Registers; use Modern::Perl; - use Koha::Database; use Koha::Cash::Register; diff --git a/Koha/Charges/Fees.pm b/Koha/Charges/Fees.pm index a9bbf0fe60..f4779a5e23 100644 --- a/Koha/Charges/Fees.pm +++ b/Koha/Charges/Fees.pm @@ -58,19 +58,18 @@ sub new { unless $params->{to_date}; Carp::confess("Key 'patron' is not a Koha::Patron object!") - unless $params->{patron}->isa('Koha::Patron'); + unless $params->{patron}->isa('Koha::Patron'); Carp::confess("Key 'library' is not a Koha::Library object!") - unless $params->{library}->isa('Koha::Library'); + unless $params->{library}->isa('Koha::Library'); Carp::confess("Key 'item' is not a Koha::Item object!") - unless $params->{item}->isa('Koha::Item'); + unless $params->{item}->isa('Koha::Item'); Carp::confess("Key 'to_date' is not a DateTime object!") - unless $params->{to_date}->isa('DateTime'); + unless $params->{to_date}->isa('DateTime'); if ( $params->{from_date} ) { Carp::croak("Key 'from_date' is not a DateTime object!") - unless $params->{from_date}->isa('DateTime'); - } - else { + unless $params->{from_date}->isa('DateTime'); + } else { $params->{from_date} = dt_from_string(); } @@ -102,9 +101,9 @@ sub accumulate_rentalcharge { my $units = $lengthunit_rule->rule_value; my $rentalcharge_increment = - ( $units eq 'days' ) - ? $itemtype->rentalcharge_daily - : $itemtype->rentalcharge_hourly; + ( $units eq 'days' ) + ? $itemtype->rentalcharge_daily + : $itemtype->rentalcharge_hourly; return 0 unless $rentalcharge_increment && $rentalcharge_increment > 0; @@ -117,18 +116,14 @@ sub accumulate_rentalcharge { $self->from_date->truncate( to => 'minute' ), $self->to_date->truncate( to => 'minute' ) ); - } - else { - $duration = $self->to_date->truncate( to => 'minute' ) - ->delta_ms( $self->from_date->truncate( to => 'minute' ) ); - } - } - else { - if ( $itemtype->rentalcharge_daily_calendar ) { + } else { $duration = - $calendar->days_between( $self->from_date, $self->to_date ); + $self->to_date->truncate( to => 'minute' )->delta_ms( $self->from_date->truncate( to => 'minute' ) ); } - else { + } else { + if ( $itemtype->rentalcharge_daily_calendar ) { + $duration = $calendar->days_between( $self->from_date, $self->to_date ); + } else { $duration = $self->to_date->delta_days( $self->from_date ); } } @@ -147,7 +142,7 @@ sub patron { my ( $self, $patron ) = @_; Carp::carp("Setting 'patron' to something other than a Koha::Patron is not supported!") - if ($patron && !$patron->isa('Koha::Patron')); + if ( $patron && !$patron->isa('Koha::Patron') ); $self->{patron} = $patron if $patron; @@ -164,7 +159,7 @@ sub library { my ( $self, $library ) = @_; Carp::carp("Setting 'library' to something other than a Koha::Library is not supported!") - if ($library && !$library->isa('Koha::Library')); + if ( $library && !$library->isa('Koha::Library') ); $self->{library} = $library if $library; @@ -181,7 +176,7 @@ sub item { my ( $self, $item ) = @_; Carp::carp("Setting 'item' to something other than a Koha::Item is not supported!") - if ($item && !$item->isa('Koha::Item')); + if ( $item && !$item->isa('Koha::Item') ); $self->{item} = $item if $item; @@ -198,7 +193,7 @@ sub to_date { my ( $self, $to_date ) = @_; Carp::carp("Setting 'to_date' to something other than a DateTime is not supported!") - if ($to_date && !$to_date->isa('DateTime')); + if ( $to_date && !$to_date->isa('DateTime') ); $self->{to_date} = $to_date if $to_date; @@ -215,7 +210,7 @@ sub from_date { my ( $self, $from_date ) = @_; Carp::carp("Setting 'from_date' to something other than a DateTime is not supported!") - if ($from_date && !$from_date->isa('DateTime')); + if ( $from_date && !$from_date->isa('DateTime') ); $self->{from_date} = $from_date if $from_date && $from_date->isa('DateTime'); diff --git a/Koha/Charges/Sales.pm b/Koha/Charges/Sales.pm index 20ea3fcb3d..f67ed4c2ac 100644 --- a/Koha/Charges/Sales.pm +++ b/Koha/Charges/Sales.pm @@ -57,16 +57,14 @@ Koha::Charges::Sale - Module for collecting sales in Koha sub new { my ( $class, $params ) = @_; - Koha::Exceptions::MissingParameter->throw( - "Missing mandatory parameter: cash_register") - unless $params->{cash_register}; + Koha::Exceptions::MissingParameter->throw("Missing mandatory parameter: cash_register") + unless $params->{cash_register}; - Koha::Exceptions::MissingParameter->throw( - "Missing mandatory parameter: staff_id") - unless $params->{staff_id}; + Koha::Exceptions::MissingParameter->throw("Missing mandatory parameter: staff_id") + unless $params->{staff_id}; Carp::confess("Key 'cash_register' is not a Koha::Cash::Register object!") - unless $params->{cash_register}->isa('Koha::Cash::Register'); + unless $params->{cash_register}->isa('Koha::Cash::Register'); return bless( $params, $class ); } @@ -83,9 +81,8 @@ sub payment_type { my ( $self, $payment_type ) = @_; if ($payment_type) { - Koha::Exceptions::Account::UnrecognisedType->throw( - error => 'Type of payment not recognised' ) - unless ( exists( $self->_get_valid_payments->{$payment_type} ) ); + Koha::Exceptions::Account::UnrecognisedType->throw( error => 'Type of payment not recognised' ) + unless ( exists( $self->_get_valid_payments->{$payment_type} ) ); $self->{payment_type} = $payment_type; } @@ -106,11 +103,9 @@ sub _get_valid_payments { $self->{valid_payments} //= { map { $_ => 1 } Koha::AuthorisedValues->search_with_library_limits( - { - category => 'PAYMENT_TYPE' - }, + { category => 'PAYMENT_TYPE' }, {}, - $self->{cash_register}->branch # filter by cash_register branch + $self->{cash_register}->branch # filter by cash_register branch )->get_column('authorised_value') }; @@ -127,21 +122,17 @@ sub _get_valid_payments { sub add_item { my ( $self, $item ) = @_; - Koha::Exceptions::MissingParameter->throw( - "Missing mandatory parameter: code") - unless $item->{code}; + Koha::Exceptions::MissingParameter->throw("Missing mandatory parameter: code") + unless $item->{code}; - Koha::Exceptions::Account::UnrecognisedType->throw( - error => 'Type of debit not recognised' ) - unless ( exists( $self->_get_valid_items->{ $item->{code} } ) ); + Koha::Exceptions::Account::UnrecognisedType->throw( error => 'Type of debit not recognised' ) + unless ( exists( $self->_get_valid_items->{ $item->{code} } ) ); - Koha::Exceptions::MissingParameter->throw( - "Missing mandatory parameter: price") - unless $item->{price}; + Koha::Exceptions::MissingParameter->throw("Missing mandatory parameter: price") + unless $item->{price}; - Koha::Exceptions::MissingParameter->throw( - "Missing mandatory parameter: quantity") - unless $item->{quantity}; + Koha::Exceptions::MissingParameter->throw("Missing mandatory parameter: quantity") + unless $item->{quantity}; push @{ $self->{items} }, $item; return $self; @@ -159,9 +150,10 @@ sub _get_valid_items { my $self = shift; $self->{valid_items} //= { - map { $_ => 1 } - Koha::Account::DebitTypes->search_with_library_limits( {}, {}, - $self->{cash_register}->branch )->get_column('code') + map { $_ => 1 } Koha::Account::DebitTypes->search_with_library_limits( + {}, {}, + $self->{cash_register}->branch + )->get_column('code') }; return $self->{valid_items}; @@ -177,21 +169,17 @@ sub purchase { my ( $self, $params ) = @_; if ( $params->{payment_type} ) { - Koha::Exceptions::Account::UnrecognisedType->throw( - error => 'Type of payment not recognised' ) - unless ( - exists( $self->_get_valid_payments->{ $params->{payment_type} } ) ); + Koha::Exceptions::Account::UnrecognisedType->throw( error => 'Type of payment not recognised' ) + unless ( exists( $self->_get_valid_payments->{ $params->{payment_type} } ) ); $self->{payment_type} = $params->{payment_type}; } - Koha::Exceptions::MissingParameter->throw( - "Missing mandatory parameter: payment_type") - unless $self->{payment_type}; + Koha::Exceptions::MissingParameter->throw("Missing mandatory parameter: payment_type") + unless $self->{payment_type}; - Koha::Exceptions::NoChanges->throw( - "Cannot purchase before calling add_item") - unless $self->{items}; + Koha::Exceptions::NoChanges->throw("Cannot purchase before calling add_item") + unless $self->{items}; my $schema = Koha::Database->new->schema; my $dt = dt_from_string(); diff --git a/Koha/Checkout.pm b/Koha/Checkout.pm index d0d460ec3c..31ec7a5d1a 100644 --- a/Koha/Checkout.pm +++ b/Koha/Checkout.pm @@ -59,9 +59,9 @@ sub is_overdue { $dt ||= dt_from_string(); my $is_overdue = - DateTime->compare( dt_from_string( $self->date_due, 'sql' ), $dt ) == -1 - ? 1 - : 0; + DateTime->compare( dt_from_string( $self->date_due, 'sql' ), $dt ) == -1 + ? 1 + : 0; return $is_overdue; } @@ -74,9 +74,9 @@ Return the checked out item =cut sub item { - my ( $self ) = @_; + my ($self) = @_; my $item_rs = $self->_result->item; - return Koha::Item->_new_from_dbic( $item_rs ); + return Koha::Item->_new_from_dbic($item_rs); } =head3 account_lines @@ -88,9 +88,9 @@ Return the checked out account_lines =cut sub account_lines { - my ( $self ) = @_; + my ($self) = @_; my $account_lines_rs = $self->_result->account_lines; - return Koha::Account::Lines->_new_from_dbic( $account_lines_rs ); + return Koha::Account::Lines->_new_from_dbic($account_lines_rs); } =head3 overdue_fines @@ -102,9 +102,9 @@ Return the account lines for just the overdue fines =cut sub overdue_fines { - my ( $self ) = @_; + my ($self) = @_; my $account_lines_rs = $self->_result->account_lines->search( { debit_type_code => 'OVERDUE' } ); - return Koha::Account::Lines->_new_from_dbic( $account_lines_rs ); + return Koha::Account::Lines->_new_from_dbic($account_lines_rs); } =head3 library @@ -116,9 +116,9 @@ Return the library in which the transaction took place =cut sub library { - my ( $self ) = @_; + my ($self) = @_; my $library_rs = $self->_result->library; - return Koha::Library->_new_from_dbic( $library_rs ); + return Koha::Library->_new_from_dbic($library_rs); } =head3 patron @@ -130,9 +130,9 @@ Return the patron for who the checkout has been done =cut sub patron { - my ( $self ) = @_; + my ($self) = @_; my $patron_rs = $self->_result->patron; - return Koha::Patron->_new_from_dbic( $patron_rs ); + return Koha::Patron->_new_from_dbic($patron_rs); } =head3 issuer @@ -144,10 +144,10 @@ Return the patron by whom the checkout was done =cut sub issuer { - my ( $self ) = @_; + my ($self) = @_; my $issuer_rs = $self->_result->issuer; return unless $issuer_rs; - return Koha::Patron->_new_from_dbic( $issuer_rs ); + return Koha::Patron->_new_from_dbic($issuer_rs); } =head3 renewals @@ -159,10 +159,10 @@ Return a Koha::Checkouts::Renewals set attached to this checkout =cut sub renewals { - my ( $self ) = @_; + my ($self) = @_; my $renewals_rs = $self->_result->renewals; return unless $renewals_rs; - return Koha::Checkouts::Renewals->_new_from_dbic( $renewals_rs ); + return Koha::Checkouts::Renewals->_new_from_dbic($renewals_rs); } =head3 attempt_auto_renew @@ -278,15 +278,17 @@ sub claim_returned { my $ClaimReturnedChargeFee = C4::Context->preference('ClaimReturnedChargeFee'); $charge_lost_fee = - $ClaimReturnedChargeFee eq 'charge' ? 1 - : $ClaimReturnedChargeFee eq 'no_charge' ? 0 - : $charge_lost_fee; # $ClaimReturnedChargeFee eq 'ask' + $ClaimReturnedChargeFee eq 'charge' ? 1 + : $ClaimReturnedChargeFee eq 'no_charge' ? 0 + : $charge_lost_fee; # $ClaimReturnedChargeFee eq 'ask' - if ( $charge_lost_fee ) { + if ($charge_lost_fee) { C4::Circulation::LostItem( $self->itemnumber, 'claim_returned' ); - } - elsif ( C4::Context->preference( 'MarkLostItemsAsReturned' ) =~ m/claim_returned/ ) { - C4::Circulation::MarkIssueReturned( $self->borrowernumber, $self->itemnumber, undef, $self->patron->privacy ); + } elsif ( C4::Context->preference('MarkLostItemsAsReturned') =~ m/claim_returned/ ) { + C4::Circulation::MarkIssueReturned( + $self->borrowernumber, $self->itemnumber, undef, + $self->patron->privacy + ); } if ($refund_lost_fee) { @@ -296,14 +298,13 @@ sub claim_returned { return $claim; } ); - } - catch { + } catch { if ( $_->isa('Koha::Exception') ) { $_->rethrow(); - } - else { + } else { + # ? - Koha::Exception->throw( "Unhandled exception" ); + Koha::Exception->throw("Unhandled exception"); } }; } diff --git a/Koha/Checkouts.pm b/Koha/Checkouts.pm index 377b817ca8..b4ee3f8cf6 100644 --- a/Koha/Checkouts.pm +++ b/Koha/Checkouts.pm @@ -19,7 +19,6 @@ package Koha::Checkouts; use Modern::Perl; - use C4::Context; use C4::Circulation qw( AddReturn ); use Koha::Checkout; @@ -28,7 +27,6 @@ use Koha::DateUtils qw( dt_from_string ); use base qw(Koha::Objects); - =head1 NAME Koha::Checkouts - Koha Checkout object set class @@ -109,7 +107,6 @@ sub automatic_checkin { } } - =head3 type =cut diff --git a/Koha/Checkouts/Renewal.pm b/Koha/Checkouts/Renewal.pm index b90072a028..b562a07015 100644 --- a/Koha/Checkouts/Renewal.pm +++ b/Koha/Checkouts/Renewal.pm @@ -46,7 +46,7 @@ exceptions as needed. =cut sub store { - my ( $self ) = @_; + my ($self) = @_; unless ( ( !$self->checkout_id && $self->in_storage ) || Koha::Checkouts->find( $self->checkout_id ) @@ -90,10 +90,10 @@ sub old_checkout { =cut sub renewer { - my ( $self ) = @_; + my ($self) = @_; my $renewer = $self->_result->renewer; - return Koha::Patron->_new_from_dbic( $renewer ) if $renewer; + return Koha::Patron->_new_from_dbic($renewer) if $renewer; } =head2 Internal methods diff --git a/Koha/Checkouts/Renewals.pm b/Koha/Checkouts/Renewals.pm index 5ec654fa8e..f60e0faa43 100644 --- a/Koha/Checkouts/Renewals.pm +++ b/Koha/Checkouts/Renewals.pm @@ -19,7 +19,6 @@ package Koha::Checkouts::Renewals; use Modern::Perl; - use Koha::Database; use Koha::Checkouts::Renewal; diff --git a/Koha/Checkouts/ReturnClaim.pm b/Koha/Checkouts/ReturnClaim.pm index d2ac4ba32b..2ca5cac6c8 100644 --- a/Koha/Checkouts/ReturnClaim.pm +++ b/Koha/Checkouts/ReturnClaim.pm @@ -47,14 +47,15 @@ exceptions as needed. =cut sub store { - my ( $self ) = @_; + my ($self) = @_; unless ( $self->in_storage || $self->created_by ) { Koha::Exceptions::Checkouts::ReturnClaims::NoCreatedBy->throw(); } # if issue_id is not found in issues or old_issues, set to null - $self->issue_id(undef) unless ( !$self->issue_id + $self->issue_id(undef) + unless ( !$self->issue_id || Koha::Checkouts->find( $self->issue_id ) || Koha::Old::Checkouts->find( $self->issue_id ) ); @@ -90,10 +91,10 @@ sub old_checkout { =cut sub patron { - my ( $self ) = @_; + my ($self) = @_; my $borrower = $self->_result->borrowernumber; - return Koha::Patron->_new_from_dbic( $borrower ) if $borrower; + return Koha::Patron->_new_from_dbic($borrower) if $borrower; } =head3 item @@ -105,9 +106,9 @@ Return the return claim item =cut sub item { - my ( $self ) = @_; + my ($self) = @_; my $item_rs = $self->_result->item; - return Koha::Item->_new_from_dbic( $item_rs ); + return Koha::Item->_new_from_dbic($item_rs); } =head3 resolve @@ -138,7 +139,8 @@ sub resolve { $self->_result->result_source->schema->txn_do( sub { $self->set( - { resolution => $params->{resolution}, + { + resolution => $params->{resolution}, resolved_by => $params->{resolved_by}, resolved_on => $params->{resolved_on} // \'NOW()', updated_by => $params->{resolved_by} diff --git a/Koha/Checkouts/ReturnClaims.pm b/Koha/Checkouts/ReturnClaims.pm index 1174cdd1a2..3a659a8428 100644 --- a/Koha/Checkouts/ReturnClaims.pm +++ b/Koha/Checkouts/ReturnClaims.pm @@ -19,7 +19,6 @@ package Koha::Checkouts::ReturnClaims; use Modern::Perl; - use Koha::Database; use Koha::Checkouts::ReturnClaim; @@ -45,7 +44,7 @@ sub unresolved { my $results = $self->_resultset()->search_rs( { resolved_on => undef } ); - return Koha::Checkouts::ReturnClaims->_new_from_dbic( $results ); + return Koha::Checkouts::ReturnClaims->_new_from_dbic($results); } =head3 resolved @@ -57,7 +56,7 @@ sub resolved { my $results = $self->_resultset()->search_rs( { resolved_on => { '!=' => undef } } ); - return Koha::Checkouts::ReturnClaims->_new_from_dbic( $results ); + return Koha::Checkouts::ReturnClaims->_new_from_dbic($results); } =head3 _type diff --git a/Koha/CirculationRule.pm b/Koha/CirculationRule.pm index 29edbe2c42..d45b0850b0 100644 --- a/Koha/CirculationRule.pm +++ b/Koha/CirculationRule.pm @@ -75,12 +75,12 @@ Clone a circulation rule to another branch =cut sub clone { - my ($self, $to_branch) = @_; + my ( $self, $to_branch ) = @_; my $cloned_rule = $self->unblessed; $cloned_rule->{branchcode} = $to_branch; delete $cloned_rule->{id}; - return Koha::CirculationRule->new( $cloned_rule )->store; + return Koha::CirculationRule->new($cloned_rule)->store; } =head3 _type diff --git a/Koha/CirculationRules.pm b/Koha/CirculationRules.pm index d43ba4f34d..7eda2d3c90 100644 --- a/Koha/CirculationRules.pm +++ b/Koha/CirculationRules.pm @@ -51,10 +51,10 @@ Any attempt to set a rule with a nonsensical scope (for instance, setting the C< our $RULE_KINDS = { lostreturn => { - scope => [ 'branchcode' ], + scope => ['branchcode'], }, processingreturn => { - scope => [ 'branchcode' ], + scope => ['branchcode'], }, patron_maxissueqty => { scope => [ 'branchcode', 'categorycode' ], @@ -67,15 +67,15 @@ our $RULE_KINDS = { }, holdallowed => { - scope => [ 'branchcode', 'itemtype' ], + scope => [ 'branchcode', 'itemtype' ], can_be_blank => 0, }, hold_fulfillment_policy => { - scope => [ 'branchcode', 'itemtype' ], + scope => [ 'branchcode', 'itemtype' ], can_be_blank => 0, }, returnbranch => { - scope => [ 'branchcode', 'itemtype' ], + scope => [ 'branchcode', 'itemtype' ], can_be_blank => 0, }, @@ -83,7 +83,7 @@ our $RULE_KINDS = { scope => [ 'branchcode', 'categorycode', 'itemtype' ], }, article_request_fee => { - scope => [ 'branchcode', 'categorycode' ], + scope => [ 'branchcode', 'categorycode' ], is_monetary => 1, }, open_article_requests_limit => { @@ -97,7 +97,7 @@ our $RULE_KINDS = { scope => [ 'branchcode', 'categorycode', 'itemtype' ], }, expire_reserves_charge => { - scope => [ 'branchcode', 'categorycode', 'itemtype' ], + scope => [ 'branchcode', 'categorycode', 'itemtype' ], can_be_blank => 0, }, chargeperiod => { @@ -183,7 +183,7 @@ our $RULE_KINDS = { scope => [ 'branchcode', 'categorycode', 'itemtype' ], }, rentaldiscount => { - scope => [ 'branchcode', 'categorycode', 'itemtype' ], + scope => [ 'branchcode', 'categorycode', 'itemtype' ], can_be_blank => 0, }, reservesallowed => { @@ -192,7 +192,7 @@ our $RULE_KINDS = { suspension_chargeperiod => { scope => [ 'branchcode', 'categorycode', 'itemtype' ], }, - note => { # This is not really a rule. Maybe we will want to separate this later. + note => { # This is not really a rule. Maybe we will want to separate this later. scope => [ 'branchcode', 'categorycode', 'itemtype' ], }, decreaseloanholds => { @@ -211,7 +211,7 @@ our $RULE_KINDS = { scope => [ 'branchcode', 'categorycode', 'itemtype' ], }, recall_overdue_fine => { - scope => [ 'branchcode', 'categorycode', 'itemtype' ], + scope => [ 'branchcode', 'categorycode', 'itemtype' ], is_monetary => 1, }, recall_shelf_time => { @@ -226,6 +226,7 @@ our $RULE_KINDS = { bookings_trail_period => { scope => [ 'branchcode', 'itemtype' ], }, + # Not included (deprecated?): # * accountsent # * reservecharge @@ -264,29 +265,27 @@ sub get_effective_rule { my $itemtype = $params->{itemtype}; my $branchcode = $params->{branchcode}; - Koha::Exceptions::MissingParameter->throw( - "Required parameter 'rule_name' missing") - unless $rule_name; + Koha::Exceptions::MissingParameter->throw("Required parameter 'rule_name' missing") + unless $rule_name; for my $v ( $branchcode, $categorycode, $itemtype ) { $v = undef if $v and $v eq '*'; } - my $order_by = $params->{order_by} - // { -desc => [ 'branchcode', 'categorycode', 'itemtype' ] }; + my $order_by = $params->{order_by} // { -desc => [ 'branchcode', 'categorycode', 'itemtype' ] }; my $search_params; $search_params->{rule_name} = $rule_name; $search_params->{categorycode} = defined $categorycode ? [ $categorycode, undef ] : undef; - $search_params->{itemtype} = defined $itemtype ? [ $itemtype, undef ] : undef; + $search_params->{itemtype} = defined $itemtype ? [ $itemtype, undef ] : undef; $search_params->{branchcode} = defined $branchcode ? [ $branchcode, undef ] : undef; my $rule = $self->search( $search_params, { order_by => $order_by, - rows => 1, + rows => 1, } )->single; @@ -320,15 +319,15 @@ sub get_effective_rule_value { my $branchcode = $params->{branchcode}; my $memory_cache = Koha::Cache::Memory::Lite->get_instance; - my $cache_key = sprintf "CircRules:%s:%s:%s:%s", $rule_name // q{}, - $categorycode // q{}, $branchcode // q{}, $itemtype // q{}; + my $cache_key = sprintf "CircRules:%s:%s:%s:%s", $rule_name // q{}, + $categorycode // q{}, $branchcode // q{}, $itemtype // q{}; - my $cached = $memory_cache->get_from_cache($cache_key); + my $cached = $memory_cache->get_from_cache($cache_key); return $cached if $cached; my $rule = $self->get_effective_rule($params); - my $value= $rule ? $rule->rule_value : undef; + my $value = $rule ? $rule->rule_value : undef; $memory_cache->set_in_cache( $cache_key, $value ); return $value; } @@ -369,19 +368,17 @@ sub get_effective_rules { sub set_rule { my ( $self, $params ) = @_; - for my $mandatory_parameter (qw( rule_name rule_value ) ) { - Koha::Exceptions::MissingParameter->throw( - "Required parameter '$mandatory_parameter' missing") - unless exists $params->{$mandatory_parameter}; + for my $mandatory_parameter (qw( rule_name rule_value )) { + Koha::Exceptions::MissingParameter->throw("Required parameter '$mandatory_parameter' missing") + unless exists $params->{$mandatory_parameter}; } my $kind_info = $RULE_KINDS->{ $params->{rule_name} }; - Koha::Exceptions::MissingParameter->throw( - "set_rule given unknown rule '$params->{rule_name}'!") + Koha::Exceptions::MissingParameter->throw("set_rule given unknown rule '$params->{rule_name}'!") unless defined $kind_info; # Enforce scope; a rule should be set for its defined scope, no more, no less. - foreach my $scope_level ( qw( branchcode categorycode itemtype ) ) { + foreach my $scope_level (qw( branchcode categorycode itemtype )) { if ( grep /$scope_level/, @{ $kind_info->{scope} } ) { croak "set_rule needs '$scope_level' to set '$params->{rule_name}'!" unless exists $params->{$scope_level}; @@ -418,12 +415,10 @@ sub set_rule { if ( defined $rule_value ) { $rule->rule_value($rule_value); $rule->update(); - } - else { + } else { $rule->delete(); } - } - else { + } else { if ( defined $rule_value ) { $rule = Koha::CirculationRule->new( { @@ -454,18 +449,18 @@ sub set_rules { my ( $self, $params ) = @_; my %set_params; - $set_params{branchcode} = $params->{branchcode} if exists $params->{branchcode}; + $set_params{branchcode} = $params->{branchcode} if exists $params->{branchcode}; $set_params{categorycode} = $params->{categorycode} if exists $params->{categorycode}; - $set_params{itemtype} = $params->{itemtype} if exists $params->{itemtype}; - my $rules = $params->{rules}; + $set_params{itemtype} = $params->{itemtype} if exists $params->{itemtype}; + my $rules = $params->{rules}; my $rule_objects = []; while ( my ( $rule_name, $rule_value ) = each %$rules ) { my $rule_object = Koha::CirculationRules->set_rule( { %set_params, - rule_name => $rule_name, - rule_value => $rule_value, + rule_name => $rule_name, + rule_value => $rule_value, } ); push( @$rule_objects, $rule_object ); @@ -481,9 +476,9 @@ Delete a set of circulation rules, needed for cleaning up when deleting issuingr =cut sub delete { - my ( $self ) = @_; + my ($self) = @_; - while ( my $rule = $self->next ){ + while ( my $rule = $self->next ) { $rule->delete; } } @@ -497,7 +492,7 @@ Clone a set of circulation rules to another branch sub clone { my ( $self, $to_branch ) = @_; - while ( my $rule = $self->next ){ + while ( my $rule = $self->next ) { $rule->clone($to_branch); } } @@ -528,12 +523,12 @@ sub get_return_branch_policy { my $pref = C4::Context->preference('CircControlReturnsBranch'); my $branchcode = - $pref eq 'ItemHomeLibrary' ? $item->homebranch - : $pref eq 'ItemHoldingLibrary' ? $item->holdingbranch - : $pref eq 'CheckInLibrary' ? C4::Context->userenv - ? C4::Context->userenv->{branch} - : $item->homebranch - : $item->homebranch; + $pref eq 'ItemHomeLibrary' ? $item->homebranch + : $pref eq 'ItemHoldingLibrary' ? $item->holdingbranch + : $pref eq 'CheckInLibrary' ? C4::Context->userenv + ? C4::Context->userenv->{branch} + : $item->homebranch + : $item->homebranch; my $itemtype = $item->effective_itemtype; @@ -548,7 +543,6 @@ sub get_return_branch_policy { return $rule ? $rule->rule_value : 'homebranch'; } - =head3 get_opacitemholds_policy my $can_place_a_hold_at_item_level = Koha::CirculationRules->get_opacitemholds_policy( { patron => $patron, item => $item } ); @@ -587,10 +581,10 @@ sub get_opacitemholds_policy { sub get_onshelfholds_policy { my ( $class, $params ) = @_; - my $item = $params->{item}; + my $item = $params->{item}; my $itemtype = $item->effective_itemtype; - my $patron = $params->{patron}; - my $rule = Koha::CirculationRules->get_effective_rule( + my $patron = $params->{patron}; + my $rule = Koha::CirculationRules->get_effective_rule( { categorycode => ( $patron ? $patron->categorycode : undef ), itemtype => $itemtype, @@ -639,25 +633,25 @@ processing return return values are: sub get_lostreturn_policy { my ( $class, $params ) = @_; - my $item = $params->{item}; + my $item = $params->{item}; - my $behaviour = C4::Context->preference( 'RefundLostOnReturnControl' ) // 'CheckinLibrary'; + my $behaviour = C4::Context->preference('RefundLostOnReturnControl') // 'CheckinLibrary'; my $behaviour_mapping = { CheckinLibrary => $params->{'return_branch'} // $item->homebranch, ItemHomeBranch => $item->homebranch, ItemHoldingBranch => $item->holdingbranch }; - my $branch = $behaviour_mapping->{ $behaviour }; + my $branch = $behaviour_mapping->{$behaviour}; my $rules = Koha::CirculationRules->get_effective_rules( { branchcode => $branch, - rules => ['lostreturn','processingreturn'] + rules => [ 'lostreturn', 'processingreturn' ] } ); - $rules->{lostreturn} //= 'refund'; + $rules->{lostreturn} //= 'refund'; $rules->{processingreturn} //= 'refund'; return $rules; } @@ -676,11 +670,13 @@ sub article_requestable_rules { my $category = $params->{categorycode}; return if !C4::Context->preference('ArticleRequests'); - return $class->search({ - $category ? ( categorycode => [ $category, undef ] ) : (), - rule_name => 'article_requests', - rule_value => { '!=' => 'no' }, - }); + return $class->search( + { + $category ? ( categorycode => [ $category, undef ] ) : (), + rule_name => 'article_requests', + rule_value => { '!=' => 'no' }, + } + ); } =head3 guess_article_requestable_itemtypes @@ -704,25 +700,27 @@ sub article_requestable_rules { sub guess_article_requestable_itemtypes { my ( $class, $params ) = @_; my $category = $params->{categorycode}; - return {} if !C4::Context->preference('ArticleRequests'); + return {} if !C4::Context->preference('ArticleRequests'); return { '*' => 1 } if C4::Context->preference('ArticleRequestsLinkControl') eq 'always'; - my $cache = Koha::Caches->get_instance; + my $cache = Koha::Caches->get_instance; my $last_article_requestable_guesses = $cache->get_from_cache(GUESSED_ITEMTYPES_KEY); - my $key = $category || '*'; + my $key = $category || '*'; return $last_article_requestable_guesses->{$key} if $last_article_requestable_guesses && exists $last_article_requestable_guesses->{$key}; - my $res = {}; - my $rules = $class->article_requestable_rules({ - $category ? ( categorycode => $category ) : (), - }); + my $res = {}; + my $rules = $class->article_requestable_rules( + { + $category ? ( categorycode => $category ) : (), + } + ); return $res if !$rules; foreach my $rule ( $rules->as_list ) { $res->{ $rule->itemtype // '*' } = 1; } $last_article_requestable_guesses->{$key} = $res; - $cache->set_in_cache(GUESSED_ITEMTYPES_KEY, $last_article_requestable_guesses); + $cache->set_in_cache( GUESSED_ITEMTYPES_KEY, $last_article_requestable_guesses ); return $res; } @@ -736,9 +734,9 @@ If not defined (or empty string), the value of the system preference useDaysMode sub get_effective_daysmode { my ( $class, $params ) = @_; - my $categorycode = $params->{categorycode}; - my $itemtype = $params->{itemtype}; - my $branchcode = $params->{branchcode}; + my $categorycode = $params->{categorycode}; + my $itemtype = $params->{itemtype}; + my $branchcode = $params->{branchcode}; my $daysmode_rule = $class->get_effective_rule( { @@ -749,10 +747,9 @@ sub get_effective_daysmode { } ); - return ( defined($daysmode_rule) - and $daysmode_rule->rule_value ne '' ) - ? $daysmode_rule->rule_value - : C4::Context->preference('useDaysMode'); + return ( defined($daysmode_rule) and $daysmode_rule->rule_value ne '' ) + ? $daysmode_rule->rule_value + : C4::Context->preference('useDaysMode'); } @@ -781,7 +778,9 @@ sub get_effective_expire_reserves_charge { # return the rule value (incl. 0) if rule found so there's an object in the variable, # or return default value from sysprefs when rule wasn't found and there's undef - return $expire_reserves_charge_rule ? $expire_reserves_charge_rule->rule_value : C4::Context->preference("ExpireReservesMaxPickUpDelayCharge"); + return $expire_reserves_charge_rule + ? $expire_reserves_charge_rule->rule_value + : C4::Context->preference("ExpireReservesMaxPickUpDelayCharge"); } diff --git a/Koha/Cities.pm b/Koha/Cities.pm index eabe4909f3..ea47b86572 100644 --- a/Koha/Cities.pm +++ b/Koha/Cities.pm @@ -17,7 +17,6 @@ package Koha::Cities; use Modern::Perl; - use Koha::Database; use Koha::City; diff --git a/Koha/City.pm b/Koha/City.pm index e95f081644..f61d70ef90 100644 --- a/Koha/City.pm +++ b/Koha/City.pm @@ -17,7 +17,6 @@ package Koha::City; use Modern::Perl; - use Koha::Database; use base qw(Koha::Object); diff --git a/Koha/ClassSortRule.pm b/Koha/ClassSortRule.pm index 73f181e573..f34a5e4edd 100644 --- a/Koha/ClassSortRule.pm +++ b/Koha/ClassSortRule.pm @@ -17,7 +17,6 @@ package Koha::ClassSortRule; use Modern::Perl; - use Koha::Database; use base qw(Koha::Object); diff --git a/Koha/ClassSortRules.pm b/Koha/ClassSortRules.pm index 1a59b0b6a8..7aa9a8ee5c 100644 --- a/Koha/ClassSortRules.pm +++ b/Koha/ClassSortRules.pm @@ -17,7 +17,6 @@ package Koha::ClassSortRules; use Modern::Perl; - use Koha::Database; use Koha::ClassSortRule; diff --git a/Koha/ClassSource.pm b/Koha/ClassSource.pm index f6994a1763..61252b921a 100644 --- a/Koha/ClassSource.pm +++ b/Koha/ClassSource.pm @@ -45,8 +45,7 @@ sub store { if ( !$self->in_storage ) { $flush = 1; - } - else { + } else { my $self_from_storage = $self->get_from_storage; $flush = 1 if ( $self_from_storage->description ne $self->description ); } diff --git a/Koha/ClassSources.pm b/Koha/ClassSources.pm index 7a56ab8b3c..a4f0312b7e 100644 --- a/Koha/ClassSources.pm +++ b/Koha/ClassSources.pm @@ -17,7 +17,6 @@ package Koha::ClassSources; use Modern::Perl; - use Koha::Database; use Koha::ClassSource; diff --git a/Koha/ClassSplitRule.pm b/Koha/ClassSplitRule.pm index 28937fc59d..451bd8af57 100644 --- a/Koha/ClassSplitRule.pm +++ b/Koha/ClassSplitRule.pm @@ -41,10 +41,10 @@ It should be an arrayref that will be serialized in JSON before stored in DB. =cut sub new { - my ($class, $attributes) = @_; + my ( $class, $attributes ) = @_; if ( exists $attributes->{regexs} ) { - $attributes->{split_regex} = to_json($attributes->{regexs}); + $attributes->{split_regex} = to_json( $attributes->{regexs} ); delete $attributes->{regexs}; } return $class->SUPER::new($attributes); @@ -63,8 +63,8 @@ Getter or setter for split_regex sub regexs { my ( $self, $regexs ) = @_; return $regexs - ? $self->split_regex( to_json($regexs) ) - : from_json( $self->split_regex || '[]' ); + ? $self->split_regex( to_json($regexs) ) + : from_json( $self->split_regex || '[]' ); } =head3 type diff --git a/Koha/Club.pm b/Koha/Club.pm index b752301d79..799531cc1c 100644 --- a/Koha/Club.pm +++ b/Koha/Club.pm @@ -19,7 +19,6 @@ package Koha::Club; use Modern::Perl; - use Koha::Database; use Koha::Club::Templates; diff --git a/Koha/Club/Enrollment.pm b/Koha/Club/Enrollment.pm index e9e434bc17..7a54061c94 100644 --- a/Koha/Club/Enrollment.pm +++ b/Koha/Club/Enrollment.pm @@ -19,7 +19,6 @@ package Koha::Club::Enrollment; use Modern::Perl; - use Koha::Database; use Koha::Clubs; use Koha::Patrons; @@ -47,7 +46,7 @@ for statistical purposes. =cut sub cancel { - my ( $self ) = @_; + my ($self) = @_; $self->_result()->update( { date_canceled => \'NOW()' } ); @@ -59,7 +58,7 @@ sub cancel { =cut sub club { - my ( $self ) = @_; + my ($self) = @_; return Koha::Clubs->find( $self->club_id() ); } @@ -68,7 +67,7 @@ sub club { =cut sub patron { - my ( $self ) = @_; + my ($self) = @_; return Koha::Patrons->find( $self->borrowernumber() ); } @@ -79,13 +78,13 @@ Determines if enrollment is canceled =cut sub is_canceled { - my ( $self ) = @_; + my ($self) = @_; return 0 unless $self->date_canceled; - my $today = dt_from_string; + my $today = dt_from_string; my $date_canceled = dt_from_string( $self->date_canceled ); - return DateTime->compare($date_canceled, $today) < 1; + return DateTime->compare( $date_canceled, $today ) < 1; } =head3 type diff --git a/Koha/Club/Enrollment/Field.pm b/Koha/Club/Enrollment/Field.pm index 54ffaff031..383811cf1e 100644 --- a/Koha/Club/Enrollment/Field.pm +++ b/Koha/Club/Enrollment/Field.pm @@ -19,7 +19,6 @@ package Koha::Club::Enrollment::Field; use Modern::Perl; - use Koha::Database; use base qw(Koha::Object); diff --git a/Koha/Club/Enrollment/Fields.pm b/Koha/Club/Enrollment/Fields.pm index 590c265161..706e36128a 100644 --- a/Koha/Club/Enrollment/Fields.pm +++ b/Koha/Club/Enrollment/Fields.pm @@ -19,7 +19,6 @@ package Koha::Club::Enrollment::Fields; use Modern::Perl; - use Koha::Database; use Koha::Club::Enrollment::Field; diff --git a/Koha/Club/Enrollments.pm b/Koha/Club/Enrollments.pm index 8e7327b323..bf4bff3743 100644 --- a/Koha/Club/Enrollments.pm +++ b/Koha/Club/Enrollments.pm @@ -19,7 +19,6 @@ package Koha::Club::Enrollments; use Modern::Perl; - use Koha::Database; use Koha::Club::Enrollment; diff --git a/Koha/Club/Field.pm b/Koha/Club/Field.pm index 956ee7ae45..ea4c6e0845 100644 --- a/Koha/Club/Field.pm +++ b/Koha/Club/Field.pm @@ -19,7 +19,6 @@ package Koha::Club::Field; use Modern::Perl; - use Koha::Database; use Koha::Club::Template::Fields; @@ -43,7 +42,7 @@ Represents the value set at creation time for a Koha::Club::Template::Field =cut sub club_template_field { - my ( $self ) = @_; + my ($self) = @_; return Koha::Club::Template::Fields->find( $self->club_template_field_id ); } diff --git a/Koha/Club/Fields.pm b/Koha/Club/Fields.pm index 7a2837b1a0..94d130e539 100644 --- a/Koha/Club/Fields.pm +++ b/Koha/Club/Fields.pm @@ -19,7 +19,6 @@ package Koha::Club::Fields; use Modern::Perl; - use Koha::Database; use Koha::Club::Field; diff --git a/Koha/Club/Hold.pm b/Koha/Club/Hold.pm index 18390559c7..181a78b6ae 100644 --- a/Koha/Club/Hold.pm +++ b/Koha/Club/Hold.pm @@ -19,7 +19,6 @@ package Koha::Club::Hold; use Modern::Perl; - use Koha::Database; use Koha::Club::Template::Fields; @@ -53,25 +52,24 @@ Class (static) method that returns a new Koha::Club::Hold instance =cut sub add { - my ( $params ) = @_; + my ($params) = @_; my $itemnumber = $params->{item_id}; # check for mandatory params my @mandatory = ( 'biblio_id', 'club_id' ); for my $param (@mandatory) { unless ( defined( $params->{$param} ) ) { - Koha::Exceptions::MissingParameter->throw( - error => "The $param parameter is mandatory" ); + Koha::Exceptions::MissingParameter->throw( error => "The $param parameter is mandatory" ); } } - my $club = Koha::Clubs->find($params->{club_id}); + my $club = Koha::Clubs->find( $params->{club_id} ); my @enrollments = $club->club_enrollments->as_list; Koha::Exceptions::ClubHold::NoPatrons->throw() unless scalar @enrollments; - my $biblio = Koha::Biblios->find($params->{biblio_id}); + my $biblio = Koha::Biblios->find( $params->{biblio_id} ); my $club_params = { club_id => $params->{club_id}, @@ -90,35 +88,42 @@ sub add { my $can_place_hold; my $patron = Koha::Patrons->find($patron_id); - my $item = $itemnumber ? Koha::Items->find( $itemnumber ) : undef; - if($params->{default_patron_home}) { + my $item = $itemnumber ? Koha::Items->find($itemnumber) : undef; + if ( $params->{default_patron_home} ) { my $patron_home = $patron->branchcode; - $can_place_hold = $itemnumber + $can_place_hold = + $itemnumber ? C4::Reserves::CanItemBeReserved( $patron, $item, $patron_home ) : C4::Reserves::CanBookBeReserved( $patron_id, $params->{biblio_id}, $patron_home ); $pickup_id = $patron_home if $can_place_hold->{status} eq 'OK'; unless ( $can_place_hold->{status} eq 'OK' ) { - warn "Patron(".$patron_id.") Hold cannot be placed with patron's homebranch ($patron_home). Reason: " . $can_place_hold->{status}; + warn "Patron(" + . $patron_id + . ") Hold cannot be placed with patron's homebranch ($patron_home). Reason: " + . $can_place_hold->{status}; } } unless ( defined $can_place_hold && $can_place_hold->{status} eq 'OK' ) { - $can_place_hold = $itemnumber + $can_place_hold = + $itemnumber ? C4::Reserves::CanItemBeReserved( $patron, $item, $pickup_id ) : C4::Reserves::CanBookBeReserved( $patron_id, $params->{biblio_id}, $pickup_id ); } unless ( $can_place_hold->{status} eq 'OK' ) { - warn "Patron(".$patron_id.") Hold cannot be placed. Reason: " . $can_place_hold->{status}; - Koha::Club::Hold::PatronHold->new({ - patron_id => $patron_id, - club_hold_id => $club_hold->id, - error_code => $can_place_hold->{status} - })->store(); + warn "Patron(" . $patron_id . ") Hold cannot be placed. Reason: " . $can_place_hold->{status}; + Koha::Club::Hold::PatronHold->new( + { + patron_id => $patron_id, + club_hold_id => $club_hold->id, + error_code => $can_place_hold->{status} + } + )->store(); next; } - my $priority = C4::Reserves::CalculatePriority($params->{biblio_id}); + my $priority = C4::Reserves::CalculatePriority( $params->{biblio_id} ); my $hold_id = C4::Reserves::AddReserve( { @@ -130,23 +135,27 @@ sub add { notes => $params->{notes}, title => $biblio->title, itemnumber => $params->{item_id}, - found => undef, # TODO: Why not? + found => undef, # TODO: Why not? itemtype => $params->{item_type}, } ); if ($hold_id) { - Koha::Club::Hold::PatronHold->new({ - patron_id => $patron_id, - club_hold_id => $club_hold->id, - hold_id => $hold_id - })->store(); + Koha::Club::Hold::PatronHold->new( + { + patron_id => $patron_id, + club_hold_id => $club_hold->id, + hold_id => $hold_id + } + )->store(); } else { - warn "Could not create hold for Patron(".$patron_id.")"; - Koha::Club::Hold::PatronHold->new({ - patron_id => $patron_id, - club_hold_id => $club_hold->id, - error_message => "Could not create hold for Patron(".$patron_id.")" - })->store(); + warn "Could not create hold for Patron(" . $patron_id . ")"; + Koha::Club::Hold::PatronHold->new( + { + patron_id => $patron_id, + club_hold_id => $club_hold->id, + error_message => "Could not create hold for Patron(" . $patron_id . ")" + } + )->store(); } } @@ -154,7 +163,6 @@ sub add { } - =head3 to_api_mapping This method returns the mapping for representing a Koha::Club::Hold object @@ -163,9 +171,7 @@ on the API. =cut sub to_api_mapping { - return { - id => 'club_hold_id' - }; + return { id => 'club_hold_id' }; } =head2 Internal methods diff --git a/Koha/Club/Hold/PatronHold.pm b/Koha/Club/Hold/PatronHold.pm index b24b33fc2e..296fb32fc3 100644 --- a/Koha/Club/Hold/PatronHold.pm +++ b/Koha/Club/Hold/PatronHold.pm @@ -19,7 +19,6 @@ package Koha::Club::Hold::PatronHold; use Modern::Perl; - use Koha::Database; use Koha::Club::Template::Fields; diff --git a/Koha/Club/Hold/PatronHolds.pm b/Koha/Club/Hold/PatronHolds.pm index 76fffcbdcc..95be549814 100644 --- a/Koha/Club/Hold/PatronHolds.pm +++ b/Koha/Club/Hold/PatronHolds.pm @@ -19,7 +19,6 @@ package Koha::Club::Hold::PatronHolds; use Modern::Perl; - use Koha::Database; use Koha::Club::Field; diff --git a/Koha/Club/Holds.pm b/Koha/Club/Holds.pm index 8a8a20334c..bd46320710 100644 --- a/Koha/Club/Holds.pm +++ b/Koha/Club/Holds.pm @@ -19,7 +19,6 @@ package Koha::Club::Holds; use Modern::Perl; - use Koha::Database; use Koha::Club::Field; diff --git a/Koha/Club/Template.pm b/Koha/Club/Template.pm index 57d87f9536..23333e6e01 100644 --- a/Koha/Club/Template.pm +++ b/Koha/Club/Template.pm @@ -19,7 +19,6 @@ package Koha::Club::Template; use Modern::Perl; - use Koha::Database; use Koha::Club::Template::Fields; diff --git a/Koha/Club/Template/EnrollmentField.pm b/Koha/Club/Template/EnrollmentField.pm index ba1fdb0b1d..fd3d19250a 100644 --- a/Koha/Club/Template/EnrollmentField.pm +++ b/Koha/Club/Template/EnrollmentField.pm @@ -19,7 +19,6 @@ package Koha::Club::Template::EnrollmentField; use Modern::Perl; - use Koha::Database; use base qw(Koha::Object); diff --git a/Koha/Club/Template/EnrollmentFields.pm b/Koha/Club/Template/EnrollmentFields.pm index 4b383f5a97..8087c5e114 100644 --- a/Koha/Club/Template/EnrollmentFields.pm +++ b/Koha/Club/Template/EnrollmentFields.pm @@ -19,7 +19,6 @@ package Koha::Club::Template::EnrollmentFields; use Modern::Perl; - use Koha::Database; use Koha::Club::Template::EnrollmentField; diff --git a/Koha/Club/Template/Field.pm b/Koha/Club/Template/Field.pm index ab5cb809b1..144c4e5845 100644 --- a/Koha/Club/Template/Field.pm +++ b/Koha/Club/Template/Field.pm @@ -19,7 +19,6 @@ package Koha::Club::Template::Field; use Modern::Perl; - use Koha::Database; use base qw(Koha::Object); diff --git a/Koha/Club/Template/Fields.pm b/Koha/Club/Template/Fields.pm index bf9fd9bd54..103ce0921d 100644 --- a/Koha/Club/Template/Fields.pm +++ b/Koha/Club/Template/Fields.pm @@ -19,7 +19,6 @@ package Koha::Club::Template::Fields; use Modern::Perl; - use Koha::Database; use Koha::Club::Template::Field; diff --git a/Koha/Club/Templates.pm b/Koha/Club/Templates.pm index b365ade79b..8197f212c8 100644 --- a/Koha/Club/Templates.pm +++ b/Koha/Club/Templates.pm @@ -19,7 +19,6 @@ package Koha::Club::Templates; use Modern::Perl; - use Koha::Database; use Koha::Club::Template; diff --git a/Koha/Clubs.pm b/Koha/Clubs.pm index 2f60648959..85e7ee5a80 100644 --- a/Koha/Clubs.pm +++ b/Koha/Clubs.pm @@ -19,7 +19,6 @@ package Koha::Clubs; use Modern::Perl; - use Koha::Database; use Koha::DateUtils qw( dt_from_string ); diff --git a/Koha/CodeList/Unimarc/MediumOfPerformance.pm b/Koha/CodeList/Unimarc/MediumOfPerformance.pm index 99e200040b..d8cf8c666d 100644 --- a/Koha/CodeList/Unimarc/MediumOfPerformance.pm +++ b/Koha/CodeList/Unimarc/MediumOfPerformance.pm @@ -430,44 +430,44 @@ sub other_performers { sub tessitura { return { - 'a' => N__p('tessitura', 'sopranino'), - 'b' => N__p('tessitura', 'soprano'), - 'c' => N__p('tessitura', 'alto'), - 'd' => N__p('tessitura', 'tenor'), - 'e' => N__p('tessitura', 'baritone'), - 'f' => N__p('tessitura', 'bass'), - 'g' => N__p('tessitura', 'contrabass'), - 'h' => N__p('tessitura', 'sub-contrabass'), - 'i' => N__p('tessitura', 'sopracute'), - 'j' => N__p('tessitura', 'high'), - 'k' => N__p('tessitura', 'medium'), - 'l' => N__p('tessitura', 'low'), - 'm' => N__p('tessitura', 'prepared'), + 'a' => N__p( 'tessitura', 'sopranino' ), + 'b' => N__p( 'tessitura', 'soprano' ), + 'c' => N__p( 'tessitura', 'alto' ), + 'd' => N__p( 'tessitura', 'tenor' ), + 'e' => N__p( 'tessitura', 'baritone' ), + 'f' => N__p( 'tessitura', 'bass' ), + 'g' => N__p( 'tessitura', 'contrabass' ), + 'h' => N__p( 'tessitura', 'sub-contrabass' ), + 'i' => N__p( 'tessitura', 'sopracute' ), + 'j' => N__p( 'tessitura', 'high' ), + 'k' => N__p( 'tessitura', 'medium' ), + 'l' => N__p( 'tessitura', 'low' ), + 'm' => N__p( 'tessitura', 'prepared' ), }; } sub number_of_hands_or_keys { return { - '1' => N__p('music', 'one hand'), - '2' => N__p('music', 'two players on one instrument'), - '3' => N__p('music', 'three hands'), - '4' => N__p('music', 'four hands'), - '6' => N__p('music', 'six hands'), - '8' => N__p('music', 'eight hands'), - 'a' => N__p('music', 'A'), - 'b' => N__p('music', 'B flat'), - 'c' => N__p('music', 'C'), - 'd' => N__p('music', 'D'), - 'e' => N__p('music', 'E'), - 'f' => N__p('music', 'F'), - 'g' => N__p('music', 'G'), - 'h' => N__p('music', 'B'), - 'i' => N__p('music', 'E flat'), - 'j' => N__p('music', 'A flat'), - 'k' => N__p('music', 'D flat'), - 'l' => N__p('music', 'F sharp'), - 'n' => N__p('music', 'Instrument played in non standard way'), - 's' => N__p('music', 'non standard string number'), + '1' => N__p( 'music', 'one hand' ), + '2' => N__p( 'music', 'two players on one instrument' ), + '3' => N__p( 'music', 'three hands' ), + '4' => N__p( 'music', 'four hands' ), + '6' => N__p( 'music', 'six hands' ), + '8' => N__p( 'music', 'eight hands' ), + 'a' => N__p( 'music', 'A' ), + 'b' => N__p( 'music', 'B flat' ), + 'c' => N__p( 'music', 'C' ), + 'd' => N__p( 'music', 'D' ), + 'e' => N__p( 'music', 'E' ), + 'f' => N__p( 'music', 'F' ), + 'g' => N__p( 'music', 'G' ), + 'h' => N__p( 'music', 'B' ), + 'i' => N__p( 'music', 'E flat' ), + 'j' => N__p( 'music', 'A flat' ), + 'k' => N__p( 'music', 'D flat' ), + 'l' => N__p( 'music', 'F sharp' ), + 'n' => N__p( 'music', 'Instrument played in non standard way' ), + 's' => N__p( 'music', 'non standard string number' ), }; } diff --git a/Koha/Config.pm b/Koha/Config.pm index f3308c76a7..99133f105b 100644 --- a/Koha/Config.pm +++ b/Koha/Config.pm @@ -71,11 +71,11 @@ file will be read only the first time. our %configs; sub get_instance { - my ($class, $file) = @_; + my ( $class, $file ) = @_; $file //= $class->guess_koha_conf; - unless (exists $configs{$file}) { + unless ( exists $configs{$file} ) { $configs{$file} = $class->read_from_file($file); } @@ -100,14 +100,15 @@ sub read_from_file { my $config = {}; eval { - my $dom = XML::LibXML->load_xml(location => $file); - foreach my $childNode ($dom->documentElement->nonBlankChildNodes) { - $class->_read_from_dom_node($childNode, $config); + my $dom = XML::LibXML->load_xml( location => $file ); + foreach my $childNode ( $dom->documentElement->nonBlankChildNodes ) { + $class->_read_from_dom_node( $childNode, $config ); } }; if ($@) { - die "\nError reading file $file.\nTry running this again as the koha instance user (or use the koha-shell command in debian)\n\n"; + die + "\nError reading file $file.\nTry running this again as the koha instance user (or use the koha-shell command in debian)\n\n"; } return bless $config, $class; @@ -148,6 +149,7 @@ sub guess_koha_conf { if ( exists $ENV{"KOHA_CONF"} and $ENV{'KOHA_CONF'} and -s $ENV{"KOHA_CONF"} ) { $conf_fname = $ENV{"KOHA_CONF"}; } elsif ( $INSTALLED_CONFIG_FNAME !~ /__KOHA_CONF_DIR/ and -s $INSTALLED_CONFIG_FNAME ) { + # NOTE: be careful -- don't change __KOHA_CONF_DIR in the above # regex to anything else -- don't want installer to rewrite it $conf_fname = $INSTALLED_CONFIG_FNAME; @@ -174,12 +176,12 @@ If not given, C<$section> defaults to 'config'. =cut sub get { - my ($self, $key, $section) = @_; + my ( $self, $key, $section ) = @_; $section //= 'config'; my $value; - if (exists $self->{$section} and exists $self->{$section}->{$key}) { + if ( exists $self->{$section} and exists $self->{$section}->{$key} ) { $value = $self->{$section}->{$key}; } @@ -201,7 +203,7 @@ sub timezone { my $timezone = $self->get('timezone') || $ENV{TZ}; if ($timezone) { require DateTime::TimeZone; - if ( !DateTime::TimeZone->is_valid_name( $timezone ) ) { + if ( !DateTime::TimeZone->is_valid_name($timezone) ) { warn "Invalid timezone in koha-conf.xml ($timezone)"; $timezone = 'local'; } @@ -212,48 +214,50 @@ sub timezone { return $timezone; } - sub _read_from_dom_node { - my ($class, $node, $config) = @_; + my ( $class, $node, $config ) = @_; - if ($node->nodeType == XML_TEXT_NODE) { + if ( $node->nodeType == XML_TEXT_NODE ) { $config->{content} = $node->textContent; - } elsif ($node->nodeType == XML_ELEMENT_NODE) { + } elsif ( $node->nodeType == XML_ELEMENT_NODE ) { my $subconfig = {}; - foreach my $attribute ($node->attributes) { - my $key = $attribute->nodeName; + foreach my $attribute ( $node->attributes ) { + my $key = $attribute->nodeName; my $value = $attribute->value; $subconfig->{$key} = $value; } - foreach my $childNode ($node->nonBlankChildNodes) { - $class->_read_from_dom_node($childNode, $subconfig); + foreach my $childNode ( $node->nonBlankChildNodes ) { + $class->_read_from_dom_node( $childNode, $subconfig ); } my $key = $node->nodeName; - if ($node->hasAttribute('id')) { + if ( $node->hasAttribute('id') ) { my $id = $node->getAttribute('id'); $config->{$key} //= {}; $config->{$key}->{$id} = $subconfig; delete $subconfig->{id}; } else { my @keys = keys %$subconfig; - if (!$node->hasAttributes() && 1 == scalar @keys && $keys[0] eq 'content') { + if ( !$node->hasAttributes() && 1 == scalar @keys && $keys[0] eq 'content' ) { + # An element with no attributes and no child elements becomes its text content $subconfig = $subconfig->{content}; - } elsif (0 == scalar @keys) { + } elsif ( 0 == scalar @keys ) { + # An empty element becomes an empty string $subconfig = ''; } - if (exists $config->{$key}) { - unless (ref $config->{$key} eq 'ARRAY') { - $config->{$key} = [$config->{$key}]; + if ( exists $config->{$key} ) { + unless ( ref $config->{$key} eq 'ARRAY' ) { + $config->{$key} = [ $config->{$key} ]; } push @{ $config->{$key} }, $subconfig; } else { - if (grep { $_ eq $key } (qw(listen server serverinfo))) { + if ( grep { $_ eq $key } (qw(listen server serverinfo)) ) { + # , and are always arrays $config->{$key} = [$subconfig]; } else { diff --git a/Koha/Config/SysPref.pm b/Koha/Config/SysPref.pm index be04b3d504..a59329d8e0 100644 --- a/Koha/Config/SysPref.pm +++ b/Koha/Config/SysPref.pm @@ -19,7 +19,6 @@ package Koha::Config::SysPref; use Modern::Perl; - use Koha::Database; use C4::Log; @@ -36,7 +35,6 @@ Koha::Config::SysPref - Koha System Preference Object class =cut - =head3 store =cut diff --git a/Koha/Config/SysPrefs.pm b/Koha/Config/SysPrefs.pm index 8b08d71a32..9b043f8da7 100644 --- a/Koha/Config/SysPrefs.pm +++ b/Koha/Config/SysPrefs.pm @@ -19,7 +19,6 @@ package Koha::Config::SysPrefs; use Modern::Perl; - use Koha::Database; use Koha::Config::SysPref; diff --git a/Koha/CookieManager.pm b/Koha/CookieManager.pm index 07795ee4d8..3b655fa12c 100644 --- a/Koha/CookieManager.pm +++ b/Koha/CookieManager.pm @@ -19,6 +19,7 @@ package Koha::CookieManager; use Modern::Perl; use CGI::Cookie; + # use Data::Dumper qw( Dumper ); # use List::MoreUtils qw( uniq ); @@ -63,11 +64,11 @@ etc. And could serve to register all our cookies in a central location. sub new { my ( $class, $params ) = @_; - my $self = bless $params//{}, $class; - my $denied = C4::Context->config(DENY_LIST_VAR) || []; # expecting scalar or arrayref - $denied = [ $denied ] if ref($denied) eq q{}; + my $self = bless $params // {}, $class; + my $denied = C4::Context->config(DENY_LIST_VAR) || []; # expecting scalar or arrayref + $denied = [$denied] if ref($denied) eq q{}; $self->{_remove_unless} = { map { $_ => 1 } @$denied }; - $self->{_secure} = C4::Context->https_enabled; + $self->{_secure} = C4::Context->https_enabled; return $self; } @@ -89,43 +90,45 @@ sub clear_unless { my ( $self, @cookies ) = @_; my @rv; my $seen = {}; - foreach my $c ( @cookies ) { + foreach my $c (@cookies) { my $name; my $type = ref($c); - if( $type eq 'CGI::Cookie' ) { + if ( $type eq 'CGI::Cookie' ) { $name = $c->name; - } elsif( $type ) { # not expected: ignore + } elsif ($type) { # not expected: ignore next; } else { $name = $c; } next if !$name; - if( $self->_should_be_cleared($name) ) { + if ( $self->_should_be_cleared($name) ) { next if $seen->{$name}; push @rv, CGI::Cookie->new( + # -expires explicitly omitted to create shortlived 'session' cookie # -HttpOnly explicitly set to 0: not really needed here for the # cleared httponly cookies, while the js cookies should be 0 -name => $name, -value => q{}, -HttpOnly => 0, $self->{_secure} ? ( -secure => 1 ) : (), ); - $seen->{$name} = 1; # prevent duplicates - } elsif( $type eq 'CGI::Cookie' ) { # keep the last occurrence + $seen->{$name} = 1; # prevent duplicates + } elsif ( $type eq 'CGI::Cookie' ) { # keep the last occurrence @rv = @{ $self->replace_in_list( \@rv, $c ) }; } } return \@rv; } -sub _should_be_cleared { # when it is not on the deny list in koha-conf +sub _should_be_cleared { # when it is not on the deny list in koha-conf my ( $self, $name ) = @_; - return if $self->{_remove_unless}->{$name}; # exact match + return if $self->{_remove_unless}->{$name}; # exact match # Now try the entries as regex - foreach my $k ( keys %{$self->{_remove_unless}} ) { + foreach my $k ( keys %{ $self->{_remove_unless} } ) { my $reg = $self->{_remove_unless}->{$k}; + # The entry in koha-conf should match the complete string # So adding a ^ and $ return if $name =~ qr/^${k}$/; @@ -151,7 +154,7 @@ sub replace_in_list { my $name = ref($cookie) eq 'CGI::Cookie' ? $cookie->name : q{}; my @result; - foreach my $c ( @$list ) { + foreach my $c (@$list) { next if ref($c) ne 'CGI::Cookie'; push @result, $c if !$name or $c->name ne $name; } diff --git a/Koha/Course/Instructor.pm b/Koha/Course/Instructor.pm index e6c4db9739..4b6f8a262d 100644 --- a/Koha/Course/Instructor.pm +++ b/Koha/Course/Instructor.pm @@ -17,7 +17,6 @@ package Koha::Course::Instructor; use Modern::Perl; - use base qw(Koha::Object); =head1 NAME diff --git a/Koha/Course/Instructors.pm b/Koha/Course/Instructors.pm index f69dd48ca0..82a0191b34 100644 --- a/Koha/Course/Instructors.pm +++ b/Koha/Course/Instructors.pm @@ -17,7 +17,6 @@ package Koha::Course::Instructors; use Modern::Perl; - use Koha::Course::Instructor; use base qw(Koha::Objects); diff --git a/Koha/Course/Item.pm b/Koha/Course/Item.pm index d55382c7a2..d13be0ba55 100644 --- a/Koha/Course/Item.pm +++ b/Koha/Course/Item.pm @@ -17,7 +17,6 @@ package Koha::Course::Item; use Modern::Perl; - use base qw(Koha::Object); use Koha::Course::Reserves; @@ -35,7 +34,7 @@ Koha::Course::Item - Koha Course Item Object class =cut sub is_enabled { - my ( $self ) = @_; + my ($self) = @_; return $self->enabled eq 'yes'; } @@ -48,7 +47,7 @@ sub course_reserves { my ($self) = @_; my $rs = $self->_result->course_reserves; - return Koha::Course::Reserves->_new_from_dbic( $rs ); + return Koha::Course::Reserves->_new_from_dbic($rs); } =head3 item @@ -59,7 +58,7 @@ sub item { my ($self) = @_; my $rs = $self->_result->itemnumber; - return Koha::Item->_new_from_dbic( $rs ); + return Koha::Item->_new_from_dbic($rs); } =head2 Internal methods diff --git a/Koha/Course/Items.pm b/Koha/Course/Items.pm index 9076540c7a..f563998515 100644 --- a/Koha/Course/Items.pm +++ b/Koha/Course/Items.pm @@ -17,7 +17,6 @@ package Koha::Course::Items; use Modern::Perl; - use Koha::Course::Item; use base qw(Koha::Objects); diff --git a/Koha/Course/Reserves.pm b/Koha/Course/Reserves.pm index e96cee6316..b824a78da2 100644 --- a/Koha/Course/Reserves.pm +++ b/Koha/Course/Reserves.pm @@ -17,7 +17,6 @@ package Koha::Course::Reserves; use Modern::Perl; - use Koha::Course::Reserve; use base qw(Koha::Objects); diff --git a/Koha/Courses.pm b/Koha/Courses.pm index df2a74163e..6a3f396daa 100644 --- a/Koha/Courses.pm +++ b/Koha/Courses.pm @@ -17,7 +17,6 @@ package Koha::Courses; use Modern::Perl; - use Koha::Course; use base qw(Koha::Objects); diff --git a/Koha/CoverImage.pm b/Koha/CoverImage.pm index e5467bedeb..8a67fa1d92 100644 --- a/Koha/CoverImage.pm +++ b/Koha/CoverImage.pm @@ -55,16 +55,15 @@ sub new { my $src_image = delete $params->{src_image}; - if ( $src_image ) { - ; # GD autodetects three basic image formats: PNG, JPEG, XPM; we will convert all to PNG which is lossless... + if ($src_image) { + ; # GD autodetects three basic image formats: PNG, JPEG, XPM; we will convert all to PNG which is lossless... # Check the pixel size of the image we are about to import... - my $thumbnail = $class->_scale_image( $src_image, 140, 200 ) - ; # MAX pixel dims are 140 X 200 for thumbnail... - my $fullsize = $class->_scale_image( $src_image, 600, 800 ) - ; # MAX pixel dims are 600 X 800 for full-size image... + my $thumbnail = $class->_scale_image( $src_image, 140, 200 ); # MAX pixel dims are 140 X 200 for thumbnail... + my $fullsize = + $class->_scale_image( $src_image, 600, 800 ); # MAX pixel dims are 600 X 800 for full-size image... - $params->{mimetype} = 'image/png'; + $params->{mimetype} = 'image/png'; $params->{imagefile} = $fullsize->png(); $params->{thumbnail} = $thumbnail->png(); } @@ -77,31 +76,26 @@ sub _scale_image { my ( $width, $height ) = $image->getBounds(); if ( $width > $maxwidth || $height > $maxheight ) { - my $percent_reduce; # Percent we will reduce the image dimensions by... + my $percent_reduce; # Percent we will reduce the image dimensions by... if ( $width > $maxwidth ) { $percent_reduce = - sprintf( "%.5f", ( $maxwidth / $width ) ) - ; # If the width is oversize, scale based on width overage... - } - else { - $percent_reduce = - sprintf( "%.5f", ( $maxheight / $height ) ) - ; # otherwise scale based on height overage. + sprintf( "%.5f", ( $maxwidth / $width ) ); # If the width is oversize, scale based on width overage... + } else { + $percent_reduce = sprintf( "%.5f", ( $maxheight / $height ) ); # otherwise scale based on height overage. } my $width_reduce = sprintf( "%.0f", ( $width * $percent_reduce ) ); my $height_reduce = sprintf( "%.0f", ( $height * $percent_reduce ) ); - my $newimage = GD::Image->new( $width_reduce, $height_reduce, 1 ) - ; #'1' creates true color image... - $newimage->copyResampled( $image, 0, 0, 0, 0, $width_reduce, - $height_reduce, $width, $height ); + my $newimage = GD::Image->new( $width_reduce, $height_reduce, 1 ); #'1' creates true color image... + $newimage->copyResampled( + $image, 0, 0, 0, 0, $width_reduce, + $height_reduce, $width, $height + ); return $newimage; - } - else { + } else { return $image; } } - =head2 Internal methods =head3 _type diff --git a/Koha/CoverImages.pm b/Koha/CoverImages.pm index bf807b0813..10dfa59ee3 100644 --- a/Koha/CoverImages.pm +++ b/Koha/CoverImages.pm @@ -17,7 +17,6 @@ package Koha::CoverImages; use Modern::Perl; - use Koha::Database; use Koha::CoverImage; @@ -42,10 +41,10 @@ Its mimetype is image/gif. =cut sub no_image { - my $no_image = pack( "H*", - '47494638396101000100800000FFFFFF' - . '00000021F90401000000002C00000000' - . '010001000002024401003B' ); + my $no_image = pack( + "H*", + '47494638396101000100800000FFFFFF' . '00000021F90401000000002C00000000' . '010001000002024401003B' + ); return Koha::CoverImage->new( { mimetype => 'image/gif', diff --git a/Koha/CsvProfile.pm b/Koha/CsvProfile.pm index c0d4d6a57c..187a03b015 100644 --- a/Koha/CsvProfile.pm +++ b/Koha/CsvProfile.pm @@ -17,7 +17,6 @@ package Koha::CsvProfile; use Modern::Perl; - use Koha::Database; use base qw(Koha::Object); diff --git a/Koha/CsvProfiles.pm b/Koha/CsvProfiles.pm index 1ea493a447..8af2ae4b1c 100644 --- a/Koha/CsvProfiles.pm +++ b/Koha/CsvProfiles.pm @@ -17,7 +17,6 @@ package Koha::CsvProfiles; use Modern::Perl; - use Koha::Database; use Koha::CsvProfile; diff --git a/Koha/CurbsidePickup.pm b/Koha/CurbsidePickup.pm index 06526961a1..6c75a8525b 100644 --- a/Koha/CurbsidePickup.pm +++ b/Koha/CurbsidePickup.pm @@ -23,9 +23,9 @@ use Koha::Database; use base qw(Koha::Object); -use C4::Circulation qw( CanBookBeIssued AddIssue ); +use C4::Circulation qw( CanBookBeIssued AddIssue ); use C4::Members::Messaging qw( GetMessagingPreferences ); -use C4::Letters qw( GetPreparedLetter EnqueueLetter ); +use C4::Letters qw( GetPreparedLetter EnqueueLetter ); use Koha::Calendar; use Koha::DateUtils qw( dt_from_string ); use Koha::Patron; @@ -51,27 +51,27 @@ sub new { my ( $self, $params ) = @_; my $policy = - Koha::CurbsidePickupPolicies->find( { branchcode => $params->{branchcode} } ); + Koha::CurbsidePickupPolicies->find( { branchcode => $params->{branchcode} } ); Koha::Exceptions::CurbsidePickup::NotEnabled->throw - unless $policy && $policy->enabled; + unless $policy && $policy->enabled; my $calendar = Koha::Calendar->new( branchcode => $params->{branchcode} ); Koha::Exceptions::CurbsidePickup::LibraryIsClosed->throw - if $calendar->is_holiday( $params->{scheduled_pickup_datetime} ); + if $calendar->is_holiday( $params->{scheduled_pickup_datetime} ); if ( $policy->enable_waiting_holds_only ) { my $patron = Koha::Patrons->find( $params->{borrowernumber} ); my $waiting_holds = $patron->holds->waiting->search( { branchcode => $params->{branchcode} } ); Koha::Exceptions::CurbsidePickup::NoWaitingHolds->throw - unless $waiting_holds->count; + unless $waiting_holds->count; } my $existing_curbside_pickups = Koha::CurbsidePickups->search( { - branchcode => $params->{branchcode}, - borrowernumber => $params->{borrowernumber}, - delivered_datetime => undef, + branchcode => $params->{branchcode}, + borrowernumber => $params->{borrowernumber}, + delivered_datetime => undef, } )->filter_by_scheduled_today; Koha::Exceptions::CurbsidePickup::TooManyPickups->throw( @@ -79,16 +79,14 @@ sub new { borrowernumber => $params->{borrowernumber} ) if $existing_curbside_pickups->count; - my $is_valid = - $policy->is_valid_pickup_datetime( $params->{scheduled_pickup_datetime} ); + my $is_valid = $policy->is_valid_pickup_datetime( $params->{scheduled_pickup_datetime} ); unless ($is_valid) { my $error = @{ $is_valid->messages }[0]->message; Koha::Exceptions::CurbsidePickup::NoMatchingSlots->throw - if $error eq 'no_matching_slots'; + if $error eq 'no_matching_slots'; Koha::Exceptions::CurbsidePickup::NoMorePickupsAvailable->throw - if $error eq 'no_more_available'; - Koha::Exceptions->throw( - "Error message must raise the appropriate exception"); + if $error eq 'no_more_available'; + Koha::Exceptions->throw("Error message must raise the appropriate exception"); } return $self->SUPER::new($params); @@ -104,25 +102,30 @@ Letter 'NEW_CURBSIDE_PICKUP will be used', and depending on 'Hold_Filled' config =cut sub notify_new_pickup { - my ( $self ) = @_; + my ($self) = @_; my $patron = $self->patron; my $library = $self->library; - $patron->queue_notice({ letter_params => { - module => 'reserves', - letter_code => 'NEW_CURBSIDE_PICKUP', - borrowernumber => $patron->borrowernumber, - branchcode => $self->branchcode, - tables => { - 'branches' => $library->unblessed, - 'borrowers' => $patron->unblessed, - }, - substitute => { - curbside_pickup => $self, + $patron->queue_notice( + { + letter_params => { + module => 'reserves', + letter_code => 'NEW_CURBSIDE_PICKUP', + borrowernumber => $patron->borrowernumber, + branchcode => $self->branchcode, + tables => { + 'branches' => $library->unblessed, + 'borrowers' => $patron->unblessed, + }, + substitute => { + curbside_pickup => $self, + } + }, + message_name => 'Hold_Filled' } - }, message_name => 'Hold_Filled' }); + ); } =head3 checkouts @@ -132,9 +135,9 @@ Return the checkouts linked to this pickup =cut sub checkouts { - my ( $self ) = @_; + my ($self) = @_; - my @pi = Koha::CurbsidePickupIssues->search({ curbside_pickup_id => $self->id })->as_list; + my @pi = Koha::CurbsidePickupIssues->search( { curbside_pickup_id => $self->id } )->as_list; my @checkouts = map { $_->checkout } @pi; @checkouts = grep { defined $_ } @checkouts; @@ -149,10 +152,10 @@ Return the patron linked to this pickup =cut sub patron { - my ( $self ) = @_; + my ($self) = @_; my $rs = $self->_result->borrowernumber; return unless $rs; - return Koha::Patron->_new_from_dbic( $rs ); + return Koha::Patron->_new_from_dbic($rs); } =head3 staged_by_staff @@ -162,10 +165,10 @@ Return the staff member that staged this pickup =cut sub staged_by_staff { - my ( $self ) = @_; + my ($self) = @_; my $rs = $self->_result->staged_by; return unless $rs; - return Koha::Patron->_new_from_dbic( $rs ); + return Koha::Patron->_new_from_dbic($rs); } =head3 library @@ -175,10 +178,10 @@ Return the branch associated with this pickup =cut sub library { - my ( $self ) = @_; + my ($self) = @_; my $rs = $self->_result->branchcode; return unless $rs; - return Koha::Library->_new_from_dbic( $rs ); + return Koha::Library->_new_from_dbic($rs); } =head3 mark_as_staged @@ -188,7 +191,7 @@ Mark the pickup as staged =cut sub mark_as_staged { - my ( $self ) = @_; + my ($self) = @_; my $staged_by = C4::Context->userenv ? C4::Context->userenv->{number} : undef; $self->set( { @@ -206,7 +209,7 @@ Mark the pickup as unstaged =cut sub mark_as_unstaged { - my ( $self ) = @_; + my ($self) = @_; $self->set( { @@ -224,7 +227,7 @@ Set the arrival time of the patron =cut sub mark_patron_has_arrived { - my ( $self ) = @_; + my ($self) = @_; $self->set( { arrival_datetime => dt_from_string(), @@ -239,18 +242,17 @@ Mark the pickup as delivered. The waiting holds will be filled. =cut sub mark_as_delivered { - my ( $self ) = @_; - my $patron = $self->patron; - my $holds = $patron->holds; + my ($self) = @_; + my $patron = $self->patron; + my $holds = $patron->holds; my $branchcode = C4::Context->userenv ? C4::Context->userenv->{branch} : undef; foreach my $hold ( $holds->as_list ) { if ( $hold->is_waiting && $branchcode && $hold->branchcode eq $branchcode ) { my ( $issuingimpossible, $needsconfirmation ) = - C4::Circulation::CanBookBeIssued( $patron, $hold->item->barcode ); + C4::Circulation::CanBookBeIssued( $patron, $hold->item->barcode ); unless ( keys %$issuingimpossible ) { - my $issue = - C4::Circulation::AddIssue( $patron, $hold->item->barcode ); + my $issue = C4::Circulation::AddIssue( $patron, $hold->item->barcode ); if ($issue) { Koha::CurbsidePickupIssue->new( { @@ -259,9 +261,13 @@ sub mark_as_delivered { reserve_id => $hold->id, } )->store(); - } - else { - Koha::Exceptions->throw(sprintf("Cannot checkout hold %s for patron %s: %s", $patron->id, $hold->id, join(", ", keys %$issuingimpossible))); + } else { + Koha::Exceptions->throw( + sprintf( + "Cannot checkout hold %s for patron %s: %s", $patron->id, $hold->id, + join( ", ", keys %$issuingimpossible ) + ) + ); } } } @@ -286,10 +292,10 @@ Return the status of the pickup, can be 'to-be-staged', 'staged-and-ready', 'pat sub status { my ($self) = @_; return - !defined $self->staged_datetime ? 'to-be-staged' - : !defined $self->arrival_datetime ? 'staged-and-ready' - : !defined $self->delivered_datetime ? 'patron-is-outside' - : 'delivered'; + !defined $self->staged_datetime ? 'to-be-staged' + : !defined $self->arrival_datetime ? 'staged-and-ready' + : !defined $self->delivered_datetime ? 'patron-is-outside' + : 'delivered'; } =head2 Internal methods diff --git a/Koha/CurbsidePickupIssue.pm b/Koha/CurbsidePickupIssue.pm index 1821063bc5..d0d05a36c0 100644 --- a/Koha/CurbsidePickupIssue.pm +++ b/Koha/CurbsidePickupIssue.pm @@ -39,7 +39,7 @@ Return the checkout object =cut sub checkout { - my ( $self ) = @_; + my ($self) = @_; return Koha::Checkouts->find( $self->issue_id ); } diff --git a/Koha/CurbsidePickupPolicy.pm b/Koha/CurbsidePickupPolicy.pm index 8408b5f0c2..af9b2a2553 100644 --- a/Koha/CurbsidePickupPolicy.pm +++ b/Koha/CurbsidePickupPolicy.pm @@ -41,10 +41,10 @@ Return the branch associated with this policy =cut sub library { - my ( $self ) = @_; + my ($self) = @_; my $rs = $self->_result->branchcode; return unless $rs; - return Koha::Library->_new_from_dbic( $rs ); + return Koha::Library->_new_from_dbic($rs); } =head3 opening_slots @@ -56,10 +56,10 @@ Return the list of opening slots (Koha::CurbsidePickupOpeningSlots object) =cut sub opening_slots { - my ( $self ) = @_; + my ($self) = @_; my $rs = $self->_result->curbside_pickup_opening_slots; return unless $rs; - return Koha::CurbsidePickupOpeningSlots->_new_from_dbic( $rs ); + return Koha::CurbsidePickupOpeningSlots->_new_from_dbic($rs); } =head3 add_opening_slot @@ -96,32 +96,29 @@ sub add_opening_slot { sub is_valid_pickup_datetime { my ( $self, $datetime ) = @_; - my $opening_slots = - $self->opening_slots->search( { day => $datetime->dow % 7 } ); + my $opening_slots = $self->opening_slots->search( { day => $datetime->dow % 7 } ); my $matching_slot; while ( my $opening_slot = $opening_slots->next ) { - my $start = $datetime->clone->set_hour( $opening_slot->start_hour ) - ->set_minute( $opening_slot->start_minute ); - my $end = $datetime->clone->set_hour( $opening_slot->end_hour ) - ->set_minute( $opening_slot->end_minute ); + my $start = $datetime->clone->set_hour( $opening_slot->start_hour )->set_minute( $opening_slot->start_minute ); + my $end = $datetime->clone->set_hour( $opening_slot->end_hour )->set_minute( $opening_slot->end_minute ); my $keep_going = 1; my $slot_start = $start->clone; - my $slot_end = $slot_start->clone->add(minutes => $self->pickup_interval); - while ($slot_end <= $end) { + my $slot_end = $slot_start->clone->add( minutes => $self->pickup_interval ); + while ( $slot_end <= $end ) { if ( $slot_start == $datetime ) { $matching_slot = $slot_start; last; } - $slot_start->add( minutes => $self->pickup_interval); - $slot_end->add( minutes => $self->pickup_interval); + $slot_start->add( minutes => $self->pickup_interval ); + $slot_end->add( minutes => $self->pickup_interval ); } } - return Koha::Result::Boolean->new(0) - ->add_message( { message => 'no_matching_slots' } ) - unless $matching_slot; + return Koha::Result::Boolean->new(0)->add_message( { message => 'no_matching_slots' } ) + unless $matching_slot; + + my $dtf = Koha::Database->new->schema->storage->datetime_parser; - my $dtf = Koha::Database->new->schema->storage->datetime_parser; # Check too many users for this slot my $existing_pickups = Koha::CurbsidePickups->search( { @@ -130,9 +127,8 @@ sub is_valid_pickup_datetime { } ); - return Koha::Result::Boolean->new(0) - ->add_message( { message => 'no_more_available' } ) - if $existing_pickups->count >= $self->patrons_per_interval; + return Koha::Result::Boolean->new(0)->add_message( { message => 'no_more_available' } ) + if $existing_pickups->count >= $self->patrons_per_interval; return 1; } diff --git a/Koha/CurbsidePickups.pm b/Koha/CurbsidePickups.pm index 97eaa8faef..5bbee128a3 100644 --- a/Koha/CurbsidePickups.pm +++ b/Koha/CurbsidePickups.pm @@ -55,8 +55,7 @@ Filter by pickups that have been staged and are ready sub filter_by_staged_and_ready { my ($self) = @_; - return $self->search( - { staged_datetime => { -not => undef }, arrival_datetime => undef } ); + return $self->search( { staged_datetime => { -not => undef }, arrival_datetime => undef } ); } =head3 filter_by_patron_outside @@ -67,9 +66,7 @@ Filter by pickups with patrons waiting outside sub filter_by_patron_outside { my ($self) = @_; - return $self->search( - { arrival_datetime => { -not => undef }, delivered_datetime => undef } - ); + return $self->search( { arrival_datetime => { -not => undef }, delivered_datetime => undef } ); } =head3 filter_by_delivered @@ -88,9 +85,10 @@ sub filter_by_delivered { Filter by pickups that are scheduled today =cut + sub filter_by_scheduled_today { my ($self) = @_; - my $dtf = Koha::Database->new->schema->storage->datetime_parser; + my $dtf = Koha::Database->new->schema->storage->datetime_parser; return $self->search( { scheduled_pickup_datetime => { '>' => $dtf->format_date(dt_from_string) } } ); } diff --git a/Koha/Database.pm b/Koha/Database.pm index bae5d7633a..40d526790a 100644 --- a/Koha/Database.pm +++ b/Koha/Database.pm @@ -58,41 +58,42 @@ sub new { bless {}, shift } sub dbh { my $config = Koha::Config->get_instance; - my $driver = db_scheme2dbi($config->get('db_scheme')); - my $user = $config->get("user"), - my $pass = $config->get("pass"), - my $dsn = generate_dsn($config); + my $driver = db_scheme2dbi( $config->get('db_scheme') ); + my $user = $config->get("user"), + my $pass = $config->get("pass"), + my $dsn = generate_dsn($config); my $attr = { RaiseError => 1, PrintError => 1, }; - if ($driver eq 'mysql') { + if ( $driver eq 'mysql' ) { $attr->{mysql_enable_utf8} = 1; } - my $dbh = DBI->connect($dsn, $user, $pass, $attr); + my $dbh = DBI->connect( $dsn, $user, $pass, $attr ); if ($dbh) { my @queries; my $tz = $config->timezone; $tz = '' if $tz eq 'local'; - if ($driver eq 'mysql') { + if ( $driver eq 'mysql' ) { push @queries, "SET NAMES 'utf8mb4'"; push @queries, qq{SET time_zone = "$tz"} if $tz; if ( $config->get('strict_sql_modes') || ( exists $ENV{_} && $ENV{_} =~ m|prove| ) - || $ENV{KOHA_TESTING} - ) { + || $ENV{KOHA_TESTING} ) + { push @queries, q{ SET sql_mode = 'ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION' }; } else { - push @queries, q{SET sql_mode = 'IGNORE_SPACE,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION'} + push @queries, + q{SET sql_mode = 'IGNORE_SPACE,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION'}; } - } elsif ($driver eq 'Pg') { + } elsif ( $driver eq 'Pg' ) { push @queries, qq{SET TIME ZONE = "$tz"} if $tz; push @queries, q{set client_encoding = 'UTF8'}; } @@ -105,7 +106,6 @@ sub dbh { return $dbh; } - # _new_schema # Internal helper function (not a method!). This creates a new # database connection from the data given in the current context, and @@ -114,11 +114,13 @@ sub _new_schema { require Koha::Schema; - my $schema = Koha::Schema->connect({ - dbh_maker => \&Koha::Database::dbh, - quote_names => 1, - auto_savepoint => 1, - }); + my $schema = Koha::Schema->connect( + { + dbh_maker => \&Koha::Database::dbh, + quote_names => 1, + auto_savepoint => 1, + } + ); my $dbh = $schema->storage->dbh; eval { @@ -126,13 +128,14 @@ sub _new_schema { if ( $ENV{KOHA_DB_DO_NOT_RAISE_OR_PRINT_ERROR} ) { $dbh->{HandleError} = sub { return 1 }; } - $dbh->do(q| + $dbh->do( + q| SELECT * FROM systempreferences WHERE 1 = 0 | ); $dbh->{HandleError} = $HandleError; }; - if ( $@ ) { + if ($@) { $dbh->{HandleError} = sub { warn $_[0]; return 1 }; } @@ -155,7 +158,7 @@ times. =cut sub schema { - my ($class, $params) = @_; + my ( $class, $params ) = @_; unless ( $params->{new} ) { return $database->{schema} if defined $database->{schema}; diff --git a/Koha/Database/Auditor.pm b/Koha/Database/Auditor.pm index cd78db36e6..8b56bb1076 100644 --- a/Koha/Database/Auditor.pm +++ b/Koha/Database/Auditor.pm @@ -78,15 +78,15 @@ sub run { )->compute_differences->produce_diff_sql; my $diff_found = 1; - my $message = __( + my $message = __( "These commands are only suggestions. They are not a replacement for the database update scripts run during installations and updates.\nReview the database, the atomic update files and the table definitions in kohastructure.sql before running any of the commands below:" ); my $title = __("Warning!"); if ( $diff =~ /No differences found/ ) { $diff_found = 0; - $message = __("The installed database schema is correct."); - $title = __("All is well"); + $message = __("The installed database schema is correct."); + $title = __("All is well"); } return { diff --git a/Koha/Database/Commenter.pm b/Koha/Database/Commenter.pm index 7987b668b9..68f4e44a53 100644 --- a/Koha/Database/Commenter.pm +++ b/Koha/Database/Commenter.pm @@ -23,7 +23,7 @@ use File::Slurp qw(read_file); use C4::Context; use Koha::Exceptions; -use constant KOHA_STRUCTURE => 'installer/data/mysql/kohastructure.sql'; +use constant KOHA_STRUCTURE => 'installer/data/mysql/kohastructure.sql'; use constant DBI_HANDLE_CLASS => 'DBI::db'; =head1 NAME @@ -69,12 +69,12 @@ Koha::Database::Commenter - Manage column comments in database =cut sub new { - my ( $class, $params ) = @_; # params: database, dbh, schema_file + my ( $class, $params ) = @_; # params: database, dbh, schema_file my $self = bless $params // {}, $class; Koha::Exceptions::MissingParameter->throw( parameter => 'dbh' ) unless $self->{dbh}; - Koha::Exceptions::WrongParameter->throw( name => 'dbh', type => ref($self->{dbh}) ) - unless ref($self->{dbh}) eq DBI_HANDLE_CLASS; + Koha::Exceptions::WrongParameter->throw( name => 'dbh', type => ref( $self->{dbh} ) ) + unless ref( $self->{dbh} ) eq DBI_HANDLE_CLASS; $self->{database} //= ( $self->{dbh}->selectrow_array('SELECT DATABASE()') )[0]; $self->_find_schema; @@ -94,12 +94,12 @@ sub new { =cut sub clear { - my ( $self, $params, $messages ) = @_; # dry_run, table + my ( $self, $params, $messages ) = @_; # dry_run, table my $cols = $self->_fetch_stored_comments($params); - foreach my $col ( @$cols ) { + foreach my $col (@$cols) { next if !$col->{column_comment}; next if $params->{table} && $col->{table_name} ne $params->{table}; - $self->_change_column( $col->{table_name}, $col->{column_name}, undef, $params, $messages ); # undef clears + $self->_change_column( $col->{table_name}, $col->{column_name}, undef, $params, $messages ); # undef clears } } @@ -115,12 +115,12 @@ sub clear { =cut sub reset_to_schema { - my ( $self, $params, $messages ) = @_; # dry_run, table + my ( $self, $params, $messages ) = @_; # dry_run, table $self->clear( $params, $messages ); my $schema_comments = $self->_fetch_schema_comments; foreach my $table ( sort keys %$schema_comments ) { next if $params->{table} && $table ne $params->{table}; - foreach my $col ( sort keys %{$schema_comments->{$table}} ) { + foreach my $col ( sort keys %{ $schema_comments->{$table} } ) { $self->_change_column( $table, $col, $schema_comments->{$table}->{$col}, $params, $messages ); } } @@ -140,10 +140,10 @@ sub reset_to_schema { =cut sub renumber { - my ( $self, $params, $messages ) = @_; # dry_run, table + my ( $self, $params, $messages ) = @_; # dry_run, table my $cols = $self->_fetch_stored_comments($params); - my $i = 0; - foreach my $col ( @$cols ) { + my $i = 0; + foreach my $col (@$cols) { next if $params->{table} && $col->{table_name} ne $params->{table}; $i++; $self->_change_column( $col->{table_name}, $col->{column_name}, "Column_$i", $params, $messages ); @@ -157,14 +157,14 @@ sub renumber { =cut sub _find_schema { - my $self = shift; + my $self = shift; my $rootdir = C4::Context->config('intranetdir'); - if( $self->{schema_file} ) { - warn "File ". $self->{schema_file}. " not found!\n" if !-e $self->{schema_file}; - } elsif( -e "$rootdir/". KOHA_STRUCTURE ) { - $self->{schema_file} = "$rootdir/". KOHA_STRUCTURE; - } elsif( -e "$rootdir/intranet/cgi-bin/". KOHA_STRUCTURE ) { - $self->{schema_file} = "$rootdir/intranet/cgi-bin/". KOHA_STRUCTURE; + if ( $self->{schema_file} ) { + warn "File " . $self->{schema_file} . " not found!\n" if !-e $self->{schema_file}; + } elsif ( -e "$rootdir/" . KOHA_STRUCTURE ) { + $self->{schema_file} = "$rootdir/" . KOHA_STRUCTURE; + } elsif ( -e "$rootdir/intranet/cgi-bin/" . KOHA_STRUCTURE ) { + $self->{schema_file} = "$rootdir/intranet/cgi-bin/" . KOHA_STRUCTURE; } } @@ -173,22 +173,23 @@ sub _find_schema { =cut sub _fetch_schema_comments { -# Wish we had a DBIC function for this, showing comments too ;) Now using kohastructure as source of truth. - my ( $self ) = @_; + + # Wish we had a DBIC function for this, showing comments too ;) Now using kohastructure as source of truth. + my ($self) = @_; my $file = $self->{schema_file}; Koha::Exceptions::FileNotFound->throw( filename => $file ) unless $file && -e $file; - return $self->{schema_info} if keys %{$self->{schema_info}}; + return $self->{schema_info} if keys %{ $self->{schema_info} }; - my @schema_lines = read_file( $file ); - my $info = {}; + my @schema_lines = read_file($file); + my $info = {}; my $current_table = q{}; - foreach my $line ( @schema_lines ) { - if( $line =~ /^CREATE TABLE\s*(?:IF NOT EXISTS)?\s*`?(\w+)`?/ ) { + foreach my $line (@schema_lines) { + if ( $line =~ /^CREATE TABLE\s*(?:IF NOT EXISTS)?\s*`?(\w+)`?/ ) { $current_table = $1; - } elsif( $current_table && $line =~ /^\s+`?(\w+)`?.*COMMENT ['"](.+)['"][,)]?$/ ) { + } elsif ( $current_table && $line =~ /^\s+`?(\w+)`?.*COMMENT ['"](.+)['"][,)]?$/ ) { my ( $col, $comment ) = ( $1, $2 ); - $comment =~ s/''/'/g; # we call quote later on + $comment =~ s/''/'/g; # we call quote later on $info->{$current_table}->{$col} = $comment; } } @@ -200,13 +201,14 @@ sub _fetch_schema_comments { =cut sub _fetch_stored_comments { - my ( $self, $params ) = @_; # params: table + my ( $self, $params ) = @_; # params: table my $sql = q| SELECT table_name AS `table_name`, column_name AS `column_name`, column_comment AS `column_comment` FROM information_schema.columns WHERE table_schema=? AND table_name=? ORDER BY table_name, column_name|; -# The AS `table_name` etc. is needed for MySQL8 which returns uppercase columns in information_schema + + # The AS `table_name` etc. is needed for MySQL8 which returns uppercase columns in information_schema $sql =~ s/AND table_name=\?// unless $params->{table}; return $self->{dbh}->selectall_arrayref( $sql, { Slice => {} }, $self->{database}, $params->{table} || () ); } @@ -216,54 +218,56 @@ ORDER BY table_name, column_name|; =cut sub _change_column { -# NOTE: We do not want to use DBIx schema here, but we use stored structure, -# since we only want to change comment not actual table structure. - my ( $self, $table_name, $column_name, $comment, $params, $messages ) = @_; # params: dry_run + + # NOTE: We do not want to use DBIx schema here, but we use stored structure, + # since we only want to change comment not actual table structure. + my ( $self, $table_name, $column_name, $comment, $params, $messages ) = @_; # params: dry_run $params //= {}; - my $dbh = $self->{dbh}; - my $info = $self->_columns_info( $table_name )->{$column_name}; + my $dbh = $self->{dbh}; + my $info = $self->_columns_info($table_name)->{$column_name}; # datatype; nullable, collation my $rv = qq|ALTER TABLE $self->{database}.$table_name MODIFY COLUMN `$column_name` $info->{Type} |; - $rv .= 'NOT NULL ' if $info->{Null} eq 'NO'; + $rv .= 'NOT NULL ' if $info->{Null} eq 'NO'; $rv .= "COLLATE $info->{Collation} " if $info->{Collation}; # Default - needs a bit of tweaking - if( !defined $info->{Default} && $info->{Null} eq 'NO' ) { + if ( !defined $info->{Default} && $info->{Null} eq 'NO' ) { + # Do not provide a default - } elsif( $info->{Type} =~ /char|text|enum/i ) { - if( !defined $info->{Default} ) { + } elsif ( $info->{Type} =~ /char|text|enum/i ) { + if ( !defined $info->{Default} ) { $rv .= "DEFAULT NULL "; - } else { #includes: $info->{Default} eq '' || $info->{Default} eq '0' - $rv .= "DEFAULT ". $dbh->quote($info->{Default}). " "; + } else { #includes: $info->{Default} eq '' || $info->{Default} eq '0' + $rv .= "DEFAULT " . $dbh->quote( $info->{Default} ) . " "; } - } elsif( !$info->{Default} && $info->{Type} =~ /timestamp/ ) { # Peculiar correction for nullable timestamps + } elsif ( !$info->{Default} && $info->{Type} =~ /timestamp/ ) { # Peculiar correction for nullable timestamps $rv .= 'NULL DEFAULT NULL ' if $info->{Null} eq 'YES'; } else { - $rv .= "DEFAULT ". ( $info->{Default} // 'NULL' ). " "; + $rv .= "DEFAULT " . ( $info->{Default} // 'NULL' ) . " "; } # Extra (like autoincrement) - $info->{Extra} =~ s/DEFAULT_GENERATED//; # need to remove it for mysql8 timestamps - $rv .= $info->{Extra}. ' ' if $info->{Extra}; + $info->{Extra} =~ s/DEFAULT_GENERATED//; # need to remove it for mysql8 timestamps + $rv .= $info->{Extra} . ' ' if $info->{Extra}; # Comment if passed; not passing means clearing actually. - if( $comment ) { - $comment = $dbh->quote($comment) unless $comment =~ /\\'/; # Prevent quoting twice - $rv .= "COMMENT ". $comment; + if ($comment) { + $comment = $dbh->quote($comment) unless $comment =~ /\\'/; # Prevent quoting twice + $rv .= "COMMENT " . $comment; } - $rv =~ s/\s+$//; # remove trailing spaces + $rv =~ s/\s+$//; # remove trailing spaces # Dry run - if( $params->{dry_run} ) { + if ( $params->{dry_run} ) { push @$messages, "$rv;" if $messages; return; } # Deploy eval { $dbh->do($rv) }; - if( $@ ) { + if ($@) { warn "Failure for $table_name:$column_name"; push @$messages, "-- FAILED: $rv;" if $messages; } else { @@ -273,7 +277,7 @@ sub _change_column { sub _columns_info { my ( $self, $table ) = @_; - return $self->{dbh}->selectall_hashref( 'SHOW FULL COLUMNS FROM '. $self->{database}. '.'. $table, 'Field' ); + return $self->{dbh}->selectall_hashref( 'SHOW FULL COLUMNS FROM ' . $self->{database} . '.' . $table, 'Field' ); } 1; diff --git a/Koha/DateUtils.pm b/Koha/DateUtils.pm index 6679843c0b..ce484ee962 100644 --- a/Koha/DateUtils.pm +++ b/Koha/DateUtils.pm @@ -23,6 +23,7 @@ use Koha::Exceptions; use Koha::DateTime::Format::RFC3339; use vars qw(@ISA @EXPORT_OK); + BEGIN { require Exporter; @ISA = qw(Exporter); @@ -62,7 +63,7 @@ sub dt_from_string { return if $date_string and $date_string =~ m|^0000-0|; my $do_fallback = defined($date_format) ? 0 : 1; - my $server_tz = C4::Context->tz; + my $server_tz = C4::Context->tz; $tz = C4::Context->tz unless $tz; return DateTime->now( time_zone => $tz ) unless $date_string; @@ -73,7 +74,7 @@ sub dt_from_string { return $date_string->clone(); } - if ($date_format eq 'rfc3339') { + if ( $date_format eq 'rfc3339' ) { return Koha::DateTime::Format::RFC3339->parse_datetime($date_string); } @@ -89,6 +90,7 @@ sub dt_from_string { |xms; if ( $date_format eq 'metric' ) { + # metric format is "dd/mm/yyyy[ hh:mm:ss]" $regex = qr| (?\d{2}) @@ -97,8 +99,8 @@ sub dt_from_string { / (?\d{4}) |xms; - } - elsif ( $date_format eq 'dmydot' ) { + } elsif ( $date_format eq 'dmydot' ) { + # dmydot format is "dd.mm.yyyy[ hh:mm:ss]" $regex = qr| (?\d{2}) @@ -107,8 +109,8 @@ sub dt_from_string { . (?\d{4}) |xms; - } - elsif ( $date_format eq 'us' ) { + } elsif ( $date_format eq 'us' ) { + # us format is "mm/dd/yyyy[ hh:mm:ss]" $regex = qr| (?\d{2}) @@ -117,12 +119,11 @@ sub dt_from_string { / (?\d{4}) |xms; - } - elsif ( $date_format eq 'iso' or $date_format eq 'sql' ) { + } elsif ( $date_format eq 'iso' or $date_format eq 'sql' ) { + # iso or sql format are yyyy-dd-mm[ hh:mm:ss]" $regex = $fallback_re; - } - else { + } else { die "Invalid dateformat parameter ($date_format)"; } @@ -147,11 +148,11 @@ sub dt_from_string { )? )? }xms; - $regex .= $time_re; + $regex .= $time_re; $fallback_re .= $time_re; # Ensure we only accept date strings and not other characters. - $regex = '^' . $regex . '$'; + $regex = '^' . $regex . '$'; $fallback_re = '^' . $fallback_re . '$'; my %dt_params; @@ -170,6 +171,7 @@ sub dt_from_string { $tz = DateTime::TimeZone->new( name => 'UTC' ); } if ( $+{offset} ) { + # If offset given, set inbound timezone using it. $tz = DateTime::TimeZone->new( name => $+{offset} . $+{hours} . ( $+{minutes} || '00' ) ); } @@ -183,8 +185,7 @@ sub dt_from_string { second => $+{second}, ); $ampm = $+{ampm}; - } - else { + } else { die "The given date ($date_string) does not match the date format ($date_format)"; } @@ -192,35 +193,36 @@ sub dt_from_string { $dt_params{day} = '01' if $dt_params{day} eq '00'; # Set default hh:mm:ss to 00:00:00 - my $date_only = ( !defined( $dt_params{hour} ) - && !defined( $dt_params{minute} ) - && !defined( $dt_params{second} ) ); + my $date_only = + ( !defined( $dt_params{hour} ) && !defined( $dt_params{minute} ) && !defined( $dt_params{second} ) ); $dt_params{hour} = 00 unless defined $dt_params{hour}; $dt_params{minute} = 00 unless defined $dt_params{minute}; $dt_params{second} = 00 unless defined $dt_params{second}; - if ( $ampm ) { + if ($ampm) { if ( $ampm eq 'AM' ) { $dt_params{hour} = 00 if $dt_params{hour} == 12; - } elsif ( $dt_params{hour} != 12 ) { # PM + } elsif ( $dt_params{hour} != 12 ) { # PM $dt_params{hour} += 12; $dt_params{hour} = 00 if $dt_params{hour} == 24; } } my $floating = 0; - my $dt = eval { + my $dt = eval { DateTime->new( %dt_params, + # No TZ for dates 'infinite' => see bug 13242 ( $dt_params{year} < 9999 ? ( time_zone => $tz ) : () ), ); }; if ($@) { - $tz = DateTime::TimeZone->new( name => 'floating' ); + $tz = DateTime::TimeZone->new( name => 'floating' ); $floating = 1; - $dt = DateTime->new( + $dt = DateTime->new( %dt_params, + # No TZ for dates 'infinite' => see bug 13242 ( $dt_params{year} < 9999 ? ( time_zone => $tz ) : () ), ); @@ -253,75 +255,77 @@ sub output_pref { my $params = shift; my ( $dt, $str, $force_pref, $force_time, $dateonly, $as_due_date ); if ( ref $params eq 'HASH' ) { - $dt = $params->{dt}; - $str = $params->{str}; - $force_pref = $params->{dateformat}; # if testing we want to override Context - $force_time = $params->{timeformat}; - $dateonly = $params->{dateonly} || 0; # if you don't want the hours and minutes - $as_due_date = $params->{as_due_date} || 0; # don't display the hours and minutes if eq to 23:59 or 11:59 (depending the TimeFormat value) + $dt = $params->{dt}; + $str = $params->{str}; + $force_pref = $params->{dateformat}; # if testing we want to override Context + $force_time = $params->{timeformat}; + $dateonly = $params->{dateonly} || 0; # if you don't want the hours and minutes + $as_due_date = $params->{as_due_date} + || 0; # don't display the hours and minutes if eq to 23:59 or 11:59 (depending the TimeFormat value) } else { $dt = $params; } - Koha::Exceptions::WrongParameter->throw( 'output_pref should not be called with both dt and str parameter' ) if $dt and $str; + Koha::Exceptions::WrongParameter->throw('output_pref should not be called with both dt and str parameter') + if $dt and $str; - if ( $str ) { + if ($str) { local $@; - $dt = eval { dt_from_string( $str ) }; - Koha::Exceptions::WrongParameter->throw("Invalid date '$str' passed to output_pref" ) if $@; + $dt = eval { dt_from_string($str) }; + Koha::Exceptions::WrongParameter->throw("Invalid date '$str' passed to output_pref") if $@; } - return if !defined $dt; # NULL date - Koha::Exceptions::WrongParameter->throw( "output_pref is called with '$dt' (ref ". ( ref($dt) ? ref($dt):'SCALAR')."), not a DateTime object") if ref($dt) ne 'DateTime'; + return if !defined $dt; # NULL date + Koha::Exceptions::WrongParameter->throw( + "output_pref is called with '$dt' (ref " . ( ref($dt) ? ref($dt) : 'SCALAR' ) . "), not a DateTime object" ) + if ref($dt) ne 'DateTime'; # FIXME: see bug 13242 => no TZ for dates 'infinite' if ( $dt->ymd !~ /^9999/ ) { - my $tz = $dateonly ? DateTime::TimeZone->new(name => 'floating') : C4::Context->tz; - eval { $dt->set_time_zone( $tz ); } + my $tz = $dateonly ? DateTime::TimeZone->new( name => 'floating' ) : C4::Context->tz; + eval { $dt->set_time_zone($tz); } } - my $pref = - defined $force_pref ? $force_pref : C4::Context->preference('dateformat'); + my $pref = defined $force_pref ? $force_pref : C4::Context->preference('dateformat'); my $time_format = $force_time || C4::Context->preference('TimeFormat') || q{}; - my $time = ( $time_format eq '12hr' ) ? '%I:%M %p' : '%H:%M'; + my $time = ( $time_format eq '12hr' ) ? '%I:%M %p' : '%H:%M'; my $date; if ( $pref =~ m/^iso/ ) { - $date = $dateonly - ? $dt->strftime("%Y-%m-%d") - : $dt->strftime("%Y-%m-%d $time"); - } - elsif ( $pref =~ m/^rfc3339/ ) { - if (!$dateonly) { + $date = + $dateonly + ? $dt->strftime("%Y-%m-%d") + : $dt->strftime("%Y-%m-%d $time"); + } elsif ( $pref =~ m/^rfc3339/ ) { + if ( !$dateonly ) { $date = Koha::DateTime::Format::RFC3339->format_datetime($dt); - } - else { + } else { $date = $dt->strftime("%Y-%m-%d"); } - } - elsif ( $pref =~ m/^metric/ ) { - $date = $dateonly - ? $dt->strftime("%d/%m/%Y") - : $dt->strftime("%d/%m/%Y $time"); - } - elsif ( $pref =~ m/^dmydot/ ) { - $date = $dateonly - ? $dt->strftime("%d.%m.%Y") - : $dt->strftime("%d.%m.%Y $time"); + } elsif ( $pref =~ m/^metric/ ) { + $date = + $dateonly + ? $dt->strftime("%d/%m/%Y") + : $dt->strftime("%d/%m/%Y $time"); + } elsif ( $pref =~ m/^dmydot/ ) { + $date = + $dateonly + ? $dt->strftime("%d.%m.%Y") + : $dt->strftime("%d.%m.%Y $time"); + + } elsif ( $pref =~ m/^us/ ) { + $date = + $dateonly + ? $dt->strftime("%m/%d/%Y") + : $dt->strftime("%m/%d/%Y $time"); + } else { + $date = + $dateonly + ? $dt->strftime("%Y-%m-%d") + : $dt->strftime("%Y-%m-%d $time"); } - elsif ( $pref =~ m/^us/ ) { - $date = $dateonly - ? $dt->strftime("%m/%d/%Y") - : $dt->strftime("%m/%d/%Y $time"); - } - else { - $date = $dateonly - ? $dt->strftime("%Y-%m-%d") - : $dt->strftime("%Y-%m-%d $time"); - } - - if ( $as_due_date ) { + if ($as_due_date) { $time_format eq '12hr' ? $date =~ s| 11:59 PM$|| : $date =~ s| 23:59$||; @@ -349,12 +353,14 @@ sub format_sqldatetime { my $dt = dt_from_string( $str, 'sql' ); return q{} unless $dt; $dt->truncate( to => 'minute' ); - return output_pref({ - dt => $dt, - dateformat => $force_pref, - timeformat => $force_time, - dateonly => $dateonly - }); + return output_pref( + { + dt => $dt, + dateformat => $force_pref, + timeformat => $force_time, + dateonly => $dateonly + } + ); } return q{}; } diff --git a/Koha/Desk.pm b/Koha/Desk.pm index 56e627551c..e1ba9affa4 100644 --- a/Koha/Desk.pm +++ b/Koha/Desk.pm @@ -18,7 +18,6 @@ package Koha::Desk; use Modern::Perl; - use Koha::Database; use base qw(Koha::Object); diff --git a/Koha/Desks.pm b/Koha/Desks.pm index 20fb541c66..bf88cb423c 100644 --- a/Koha/Desks.pm +++ b/Koha/Desks.pm @@ -16,10 +16,8 @@ package Koha::Desks; # You should have received a copy of the GNU General Public License # along with Koha; if not, see . - use Modern::Perl; - use Koha::Database; use Koha::Desk; diff --git a/Koha/EDI.pm b/Koha/EDI.pm index 09b3d6f74f..b27b049362 100644 --- a/Koha/EDI.pm +++ b/Koha/EDI.pm @@ -21,7 +21,7 @@ use strict; use warnings; use base qw(Exporter); use utf8; -use Carp qw( carp ); +use Carp qw( carp ); use English qw{ -no_match_vars }; use Business::ISBN; use DateTime; @@ -30,7 +30,7 @@ use Koha::Database; use Koha::DateUtils qw( dt_from_string ); use C4::Acquisition qw( ModOrder NewBasket ); use C4::Suggestions qw( ModSuggestion ); -use C4::Biblio qw( +use C4::Biblio qw( AddBiblio GetFrameworkCode GetMarcFromKohaField @@ -38,10 +38,10 @@ use C4::Biblio qw( ); use Koha::Edifact::Order; use Koha::Edifact; -use C4::Log qw( logaction ); +use C4::Log qw( logaction ); use Text::Unidecode qw( unidecode ); use Koha::Logger; -use Koha::Plugins; # Adds plugin dirs to @INC +use Koha::Plugins; # Adds plugin dirs to @INC use Koha::Plugins::Handler; use Koha::Acquisition::Baskets; use Koha::Acquisition::Booksellers; @@ -49,18 +49,19 @@ use Koha::Util::FrameworkPlugin qw( biblio_008 ); our $VERSION = 1.1; -our (@ISA, @EXPORT_OK); +our ( @ISA, @EXPORT_OK ); + BEGIN { require Exporter; - @ISA = qw(Exporter); + @ISA = qw(Exporter); @EXPORT_OK = qw( - process_quote - process_invoice - process_ordrsp - create_edi_order - get_edifact_ean + process_quote + process_invoice + process_ordrsp + create_edi_order + get_edifact_ean ); -}; +} sub create_edi_order { my $parameters = shift; @@ -97,8 +98,7 @@ sub create_edi_order { if ($branchcode) { $ean_search_keys->{branchcode} = $branchcode; } - my $ean_obj = - $schema->resultset('EdifactEan')->search($ean_search_keys)->single; + my $ean_obj = $schema->resultset('EdifactEan')->search($ean_search_keys)->single; # If no branch specific each can be found, look for a default ean unless ($ean_obj) { @@ -112,7 +112,7 @@ sub create_edi_order { my $dbh = C4::Context->dbh; my $arr_ref = $dbh->selectcol_arrayref( -'select id from edifact_messages where basketno = ? and message_type = \'QUOTE\'', + 'select id from edifact_messages where basketno = ? and message_type = \'QUOTE\'', {}, $basketno ); my $response = @{$arr_ref} ? 1 : 0; @@ -135,8 +135,7 @@ sub create_edi_order { } } ); - } - else { + } else { $edifact = Koha::Edifact::Order->new($edifact_order_params); } @@ -146,8 +145,8 @@ sub create_edi_order { # ingest result if ($order_file) { - my $m = unidecode($order_file); # remove diacritics and non-latin chars - if ($noingest) { # allows scripts to produce test files + my $m = unidecode($order_file); # remove diacritics and non-latin chars + if ($noingest) { # allows scripts to produce test files return $m; } my $order = { @@ -175,8 +174,7 @@ sub process_ordrsp { my $schema = Koha::Database->new()->schema(); my $logger = Koha::Logger->get( { interface => 'edi' } ); my $vendor_acct; - my $edi = - Koha::Edifact->new( { transmission => $response_message->raw_msg, } ); + my $edi = Koha::Edifact->new( { transmission => $response_message->raw_msg, } ); my $messages = $edi->message_array(); if ( @{$messages} ) { @@ -185,7 +183,7 @@ sub process_ordrsp { foreach my $line ( @{$lines} ) { my $ordernumber = $line->ordernumber(); - # action cancelled:change_requested:no_action:accepted:not_found:recorded + # action cancelled:change_requested:no_action:accepted:not_found:recorded my $action = $line->action_notification(); if ( $action eq 'cancelled' ) { my $reason = $line->coded_orderline_text(); @@ -197,8 +195,7 @@ sub process_ordrsp { datecancellationprinted => dt_from_string()->ymd(), } ); - } - else { # record order as due with possible further info + } else { # record order as due with possible further info my $report = $line->coded_orderline_text(); my $date_avail = $line->availability_date(); @@ -233,8 +230,9 @@ sub process_invoice { my $plugin_class = $invoice_message->edi_acct()->plugin(); # Plugin has its own invoice processor, only run it and not the standard invoice processor below - if ( $plugin_class ) { - eval "require $plugin_class"; # Import the class, eval is needed because requiring a string doesn't work like requiring a bareword + if ($plugin_class) { + eval "require $plugin_class" + ; # Import the class, eval is needed because requiring a string doesn't work like requiring a bareword my $plugin = $plugin_class->new(); if ( $plugin->can('edifact_process_invoice') ) { Koha::Plugins::Handler->run( @@ -251,21 +249,21 @@ sub process_invoice { } my $edi_plugin; - if ( $plugin_class ) { + if ($plugin_class) { $edi_plugin = Koha::Plugins::Handler->run( { class => $plugin_class, method => 'edifact', params => { invoice_message => $invoice_message, - transmission => $invoice_message->raw_msg, + transmission => $invoice_message->raw_msg, } } ); } - my $edi = $edi_plugin || - Koha::Edifact->new( { transmission => $invoice_message->raw_msg, } ); + my $edi = $edi_plugin + || Koha::Edifact->new( { transmission => $invoice_message->raw_msg, } ); my $messages = $edi->message_array(); @@ -290,7 +288,8 @@ sub process_invoice { )->single; } if ( !$vendor_acct ) { - carp "Cannot find vendor with ean $vendor_ean for invoice $invoicenumber in ".$invoice_message->filename; + carp "Cannot find vendor with ean $vendor_ean for invoice $invoicenumber in " + . $invoice_message->filename; next; } $invoice_message->edi_acct( $vendor_acct->id ); @@ -441,7 +440,7 @@ sub _get_invoiced_price { sub receipt_items { my ( $schema, $inv_line, $ordernumber, $quantity ) = @_; - my $logger = Koha::Logger->get( { interface => 'edi' } ); + my $logger = Koha::Logger->get( { interface => 'edi' } ); # itemnumber is not a foreign key ??? makes this a bit cumbersome my @item_links = $schema->resultset('AqordersItem')->search( @@ -454,8 +453,7 @@ sub receipt_items { my $item = $schema->resultset('Item')->find( $ilink->itemnumber ); if ( !$item ) { my $i = $ilink->itemnumber; - $logger->warn( - "Cannot find aqorder item for $i :Order:$ordernumber"); + $logger->warn("Cannot find aqorder item for $i :Order:$ordernumber"); next; } my $b = $item->get_column('homebranch'); @@ -471,7 +469,7 @@ sub receipt_items { my $itemfield; if ( C4::Context->preference('AcqCreateItem') eq 'ordering' ) { @affects = split q{\|}, - C4::Context->preference("AcqItemSetSubfieldsWhenReceived"); + C4::Context->preference("AcqItemSetSubfieldsWhenReceived"); if (@affects) { my $order = Koha::Acquisition::Orders->find($ordernumber); $biblionumber = $order->biblionumber; @@ -483,7 +481,7 @@ sub receipt_items { my $gir_occurrence = 0; while ( $gir_occurrence < $quantity ) { my $branch = $inv_line->girfield( 'branch', $gir_occurrence ); - my $item = shift @{ $branch_map{$branch} }; + my $item = shift @{ $branch_map{$branch} }; if ($item) { my $barcode = $inv_line->girfield( 'barcode', $gir_occurrence ); if ( $barcode && !$item->barcode ) { @@ -494,8 +492,7 @@ sub receipt_items { ); if ( $rs->count > 0 ) { $logger->warn("Barcode $barcode is a duplicate"); - } - else { + } else { $logger->trace("Adding barcode $barcode"); $item->barcode($barcode); @@ -515,8 +512,7 @@ sub receipt_items { } $item->update; - } - else { + } else { $logger->warn("Unmatched item at branch:$branch"); } ++$gir_occurrence; @@ -529,14 +525,13 @@ sub transfer_items { my ( $schema, $inv_line, $order_from, $order_to, $quantity ) = @_; # Transfer x items from the orig order to a completed partial order - my $gocc = 0; + my $gocc = 0; my %mapped_by_branch; while ( $gocc < $quantity ) { my $branch = $inv_line->girfield( 'branch', $gocc ); if ( !exists $mapped_by_branch{$branch} ) { $mapped_by_branch{$branch} = 1; - } - else { + } else { $mapped_by_branch{$branch}++; } ++$gocc; @@ -562,10 +557,9 @@ sub transfer_items { $ilink->update; --$quantity; --$mapped_by_branch{$i_branch}; - $logger->warn("Transferred item " . $item->itemnumber); - } - else { - $logger->warn("Skipped item " . $item->itemnumber); + $logger->warn( "Transferred item " . $item->itemnumber ); + } else { + $logger->warn( "Skipped item " . $item->itemnumber ); } if ( $quantity < 1 ) { last; @@ -593,9 +587,10 @@ sub process_quote { if ( @{$messages} && $quote->vendor_id ) { foreach my $msg ( @{$messages} ) { ++$message_count; - my $basketno = - NewBasket( $quote->vendor_id, 0, $quote->filename, q{}, - q{} . q{} ); + my $basketno = NewBasket( + $quote->vendor_id, 0, $quote->filename, q{}, + q{} . q{} + ); push @added_baskets, $basketno; if ( $message_count > 1 ) { my $m_filename = $quote->filename; @@ -612,8 +607,7 @@ sub process_quote { filename => $m_filename, } ); - } - else { + } else { $quote->basketno($basketno); } $logger->trace("Created basket :$basketno"); @@ -649,20 +643,20 @@ sub process_quote { } ); Koha::Acquisition::Baskets->find($b)->close; + # Log the approval - if (C4::Context->preference("AcquisitionLog")) { - my $approved = Koha::Acquisition::Baskets->find( $b ); + if ( C4::Context->preference("AcquisitionLog") ) { + my $approved = Koha::Acquisition::Baskets->find($b); logaction( 'ACQUISITIONS', 'APPROVE_BASKET', $b, - to_json($approved->unblessed) + to_json( $approved->unblessed ) ); } } } - return; } @@ -674,8 +668,8 @@ sub quote_item { # $basketno is the return from AddBasket in the calling routine # So this call should not fail unless that has - my $basket = Koha::Acquisition::Baskets->find( $basketno ); - unless ( $basket ) { + my $basket = Koha::Acquisition::Baskets->find($basketno); + unless ($basket) { $logger->error('Skipping order creation no valid basketno'); return; } @@ -689,10 +683,9 @@ sub quote_item { $bib_record = _handle_008_field($bib_record); ( $bib->{biblionumber}, $bib->{biblioitemnumber} ) = - AddBiblio( $bib_record, q{} ); + AddBiblio( $bib_record, q{} ); $logger->trace("New biblio added $bib->{biblionumber}"); - } - else { + } else { $logger->trace("Match found: $bib->{biblionumber}"); } @@ -704,14 +697,14 @@ sub quote_item { $order_quantity ||= 1; # quantity not necessarily present if ( $gir_count > 1 ) { if ( $gir_count != $order_quantity ) { - $logger->error( - "Order for $order_quantity items, $gir_count segments present"); + $logger->error("Order for $order_quantity items, $gir_count segments present"); } $order_quantity = 1; # attempts to create an orderline for each gir } - my $price = $item->price_info; + my $price = $item->price_info; + # Howells do not send an info price but do have a gross price - if (!$price) { + if ( !$price ) { $price = $item->price_gross; } my $vendor = Koha::Acquisition::Booksellers->find( $quote->vendor_id ); @@ -746,10 +739,8 @@ sub quote_item { if ( $item->reference() ) { $order_hash->{suppliers_reference_number} = $item->reference; $order_hash->{suppliers_reference_qualifier} = 'QLI'; - } - elsif ( $item->orderline_reference_number() ) { - $order_hash->{suppliers_reference_number} = - $item->orderline_reference_number; + } elsif ( $item->orderline_reference_number() ) { + $order_hash->{suppliers_reference_number} = $item->orderline_reference_number; $order_hash->{suppliers_reference_qualifier} = 'SLI'; } if ( $item->item_number_id ) { # suppliers ean @@ -787,8 +778,7 @@ sub quote_item { carp 'Skipping line with no budget info'; $logger->trace('girfield skipped for invalid budget'); $skip++; - } - else { + } else { carp 'Skipping line with no budget info'; $logger->trace('orderline skipped for invalid budget'); return; @@ -820,9 +810,9 @@ sub quote_item { my $created = 0; while ( $created < $order_quantity ) { - $item_hash->{biblionumber} = $bib->{biblionumber}; + $item_hash->{biblionumber} = $bib->{biblionumber}; $item_hash->{biblioitemnumber} = $bib->{biblioitemnumber}; - my $kitem = Koha::Item->new( $item_hash )->store; + my $kitem = Koha::Item->new($item_hash)->store; my $itemnumber = $kitem->itemnumber; $logger->trace("Added item:$itemnumber"); $schema->resultset('AqordersItem')->create( @@ -855,15 +845,15 @@ sub quote_item { while ( $occurrence < $item->quantity ) { # check budget code - $budget = _get_budget( $schema, - $item->girfield( 'fund_allocation', $occurrence ) ); + $budget = _get_budget( + $schema, + $item->girfield( 'fund_allocation', $occurrence ) + ); if ( !$budget ) { - my $bad_budget = - $item->girfield( 'fund_allocation', $occurrence ); + my $bad_budget = $item->girfield( 'fund_allocation', $occurrence ); carp 'Skipping line with no budget info'; - $logger->trace( - "girfield skipped for invalid budget:$bad_budget"); + $logger->trace("girfield skipped for invalid budget:$bad_budget"); ++$occurrence; ## lets look at the next one not this one again next; } @@ -876,9 +866,8 @@ sub quote_item { $order_hash->{budget_id} = $budget->budget_id; - my $new_order = - $schema->resultset('Aqorder')->create($order_hash); - my $o = $new_order->ordernumber(); + my $new_order = $schema->resultset('Aqorder')->create($order_hash); + my $o = $new_order->ordernumber(); $logger->trace("Order created :$o"); # should be done by database settings @@ -896,15 +885,12 @@ sub quote_item { $item_hash = _create_item_from_quote( $item, $quote ); } my $new_item = { - itype => - $item->girfield( 'stock_category', $occurrence ), - itemcallnumber => - $item->girfield( 'shelfmark', $occurrence ) - || $item->girfield( 'classification', $occurrence ) - || title_level_class($item), - holdingbranch => - $item->girfield( 'branch', $occurrence ), - homebranch => $item->girfield( 'branch', $occurrence ), + itype => $item->girfield( 'stock_category', $occurrence ), + itemcallnumber => $item->girfield( 'shelfmark', $occurrence ) + || $item->girfield( 'classification', $occurrence ) + || title_level_class($item), + holdingbranch => $item->girfield( 'branch', $occurrence ), + homebranch => $item->girfield( 'branch', $occurrence ), }; my $lsq_field = C4::Context->preference('EdifactLSQ'); @@ -917,20 +903,18 @@ sub quote_item { $item_hash->{$lsq_field} = $new_item->{$lsq_field}; } if ( $new_item->{itemcallnumber} ) { - $item_hash->{itemcallnumber} = - $new_item->{itemcallnumber}; + $item_hash->{itemcallnumber} = $new_item->{itemcallnumber}; } if ( $new_item->{holdingbranch} ) { - $item_hash->{holdingbranch} = - $new_item->{holdingbranch}; + $item_hash->{holdingbranch} = $new_item->{holdingbranch}; } if ( $new_item->{homebranch} ) { $item_hash->{homebranch} = $new_item->{homebranch}; } - $item_hash->{biblionumber} = $bib->{biblionumber}; + $item_hash->{biblionumber} = $bib->{biblionumber}; $item_hash->{biblioitemnumber} = $bib->{biblioitemnumber}; - my $kitem = Koha::Item->new( $item_hash )->store; + my $kitem = Koha::Item->new($item_hash)->store; my $itemnumber = $kitem->itemnumber; $logger->trace("New item $itemnumber added"); $schema->resultset('AqordersItem')->create( @@ -940,19 +924,17 @@ sub quote_item { } ); - my $lrp = - $item->girfield( 'library_rotation_plan', $occurrence ); + my $lrp = $item->girfield( 'library_rotation_plan', $occurrence ); if ($lrp) { - my $rota = - Koha::StockRotationRotas->find( { title => $lrp }, - { key => 'stockrotationrotas_title' } ); + my $rota = Koha::StockRotationRotas->find( + { title => $lrp }, + { key => 'stockrotationrotas_title' } + ); if ($rota) { $rota->add_item($itemnumber); $logger->trace("Item added to rota $rota->id"); - } - else { - $logger->error( - "No rota found matching $lrp in orderline"); + } else { + $logger->error("No rota found matching $lrp in orderline"); } } } @@ -962,11 +944,7 @@ sub quote_item { # increment quantity in orderline for EXISTING budget in $budgets else { - my $row = $schema->resultset('Aqorder')->find( - { - ordernumber => $ordernumber{ $budget->budget_id } - } - ); + my $row = $schema->resultset('Aqorder')->find( { ordernumber => $ordernumber{ $budget->budget_id } } ); if ($row) { my $qty = $row->quantity; $qty++; @@ -986,21 +964,18 @@ sub quote_item { cn_source => 'ddc', price => $price, replacementprice => $price, - itype => - $item->girfield( 'stock_category', $occurrence ), - itemcallnumber => - $item->girfield( 'shelfmark', $occurrence ) - || $item->girfield( 'classification', $occurrence ) - || $item_hash->{itemcallnumber}, - holdingbranch => - $item->girfield( 'branch', $occurrence ), - homebranch => $item->girfield( 'branch', $occurrence ), + itype => $item->girfield( 'stock_category', $occurrence ), + itemcallnumber => $item->girfield( 'shelfmark', $occurrence ) + || $item->girfield( 'classification', $occurrence ) + || $item_hash->{itemcallnumber}, + holdingbranch => $item->girfield( 'branch', $occurrence ), + homebranch => $item->girfield( 'branch', $occurrence ), }; my $lsq_field = C4::Context->preference('EdifactLSQ'); - $new_item->{$lsq_field} = $item->girfield( 'sequence_code', $occurrence ); - $new_item->{biblionumber} = $bib->{biblionumber}; + $new_item->{$lsq_field} = $item->girfield( 'sequence_code', $occurrence ); + $new_item->{biblionumber} = $bib->{biblionumber}; $new_item->{biblioitemnumber} = $bib->{biblioitemnumber}; - my $kitem = Koha::Item->new( $new_item )->store; + my $kitem = Koha::Item->new($new_item)->store; my $itemnumber = $kitem->itemnumber; $logger->trace("New item $itemnumber added"); $schema->resultset('AqordersItem')->create( @@ -1010,19 +985,17 @@ sub quote_item { } ); - my $lrp = - $item->girfield( 'library_rotation_plan', $occurrence ); + my $lrp = $item->girfield( 'library_rotation_plan', $occurrence ); if ($lrp) { - my $rota = - Koha::StockRotationRotas->find( { title => $lrp }, - { key => 'stockrotationrotas_title' } ); + my $rota = Koha::StockRotationRotas->find( + { title => $lrp }, + { key => 'stockrotationrotas_title' } + ); if ($rota) { $rota->add_item($itemnumber); $logger->trace("Item added to rota $rota->id"); - } - else { - $logger->error( - "No rota found matching $lrp in orderline"); + } else { + $logger->error("No rota found matching $lrp in orderline"); } } } @@ -1047,10 +1020,10 @@ sub get_edifact_ean { # We should not need to have a routine to do this here sub _discounted_price { my ( $discount, $price, $discounted_price ) = @_; - if (defined $discounted_price) { + if ( defined $discounted_price ) { return $discounted_price; } - if (!$price) { + if ( !$price ) { return 0; } return $price - ( ( $discount * $price ) / 100 ); @@ -1064,24 +1037,23 @@ sub _check_for_existing_bib { $search_isbn =~ s/\s*$/%/xms; my $dbh = C4::Context->dbh; my $sth = $dbh->prepare( -'select biblionumber, biblioitemnumber from biblioitems where isbn like ?', + 'select biblionumber, biblioitemnumber from biblioitems where isbn like ?', ); my $tuple_arr = - $dbh->selectall_arrayref( $sth, { Slice => {} }, $search_isbn ); + $dbh->selectall_arrayref( $sth, { Slice => {} }, $search_isbn ); + if ( @{$tuple_arr} ) { return $tuple_arr->[0]; - } - elsif ( length($isbn) == 13 && $isbn !~ /^97[89]/ ) { + } elsif ( length($isbn) == 13 && $isbn !~ /^97[89]/ ) { my $tarr = $dbh->selectall_arrayref( -'select biblionumber, biblioitemnumber from biblioitems where ean = ?', + 'select biblionumber, biblioitemnumber from biblioitems where ean = ?', { Slice => {} }, $isbn ); if ( @{$tarr} ) { return $tarr->[0]; } - } - else { + } else { undef $search_isbn; $isbn =~ s/\-//xmsg; if ( $isbn =~ m/(\d{13})/xms ) { @@ -1090,8 +1062,7 @@ sub _check_for_existing_bib { $search_isbn = $b_isbn->as_isbn10->as_string( [] ); } - } - elsif ( $isbn =~ m/(\d{9}[xX]|\d{10})/xms ) { + } elsif ( $isbn =~ m/(\d{9}[xX]|\d{10})/xms ) { my $b_isbn = Business::ISBN->new($1); if ( $b_isbn && $b_isbn->is_valid ) { $search_isbn = $b_isbn->as_isbn13->as_string( [] ); @@ -1101,7 +1072,7 @@ sub _check_for_existing_bib { if ($search_isbn) { $search_isbn = "%$search_isbn%"; $tuple_arr = - $dbh->selectall_arrayref( $sth, { Slice => {} }, $search_isbn ); + $dbh->selectall_arrayref( $sth, { Slice => {} }, $search_isbn ); if ( @{$tuple_arr} ) { return $tuple_arr->[0]; } @@ -1123,9 +1094,8 @@ sub _get_budget { # db does not ensure budget code is unque return $schema->resultset('Aqbudget')->single( { - budget_code => $budget_code, - budget_period_id => - { -in => $period_rs->get_column('budget_period_id')->as_query }, + budget_code => $budget_code, + budget_period_id => { -in => $period_rs->get_column('budget_period_id')->as_query }, } ); } @@ -1137,15 +1107,14 @@ sub title_level_class { my $default_scheme = C4::Context->preference('DefaultClassificationSource'); if ( $default_scheme eq 'ddc' ) { $class = $item->dewey_class(); - } - elsif ( $default_scheme eq 'lcc' ) { + } elsif ( $default_scheme eq 'lcc' ) { $class = $item->lc_class(); } if ( !$class ) { $class = - $item->girfield('shelfmark') - || $item->girfield('classification') - || q{}; + $item->girfield('shelfmark') + || $item->girfield('classification') + || q{}; } return $class; } @@ -1155,10 +1124,9 @@ sub _create_bib_from_quote { #TBD we should flag this for updating from an external source #As biblio (&biblioitems) has no candidates flag in order my ( $item, $quote ) = @_; - my $itemid = $item->item_number_id; - my $defalt_classification_source = - C4::Context->preference('DefaultClassificationSource'); - my $bib_hash = { + my $itemid = $item->item_number_id; + my $defalt_classification_source = C4::Context->preference('DefaultClassificationSource'); + my $bib_hash = { 'biblioitems.cn_source' => $defalt_classification_source, 'items.cn_source' => $defalt_classification_source, 'items.notforloan' => -1, @@ -1166,9 +1134,8 @@ sub _create_bib_from_quote { }; $bib_hash->{'biblio.seriestitle'} = $item->series; - $bib_hash->{'biblioitems.publishercode'} = $item->publisher; - $bib_hash->{'biblioitems.publicationyear'} = - $bib_hash->{'biblio.copyrightdate'} = $item->publication_date; + $bib_hash->{'biblioitems.publishercode'} = $item->publisher; + $bib_hash->{'biblioitems.publicationyear'} = $bib_hash->{'biblio.copyrightdate'} = $item->publication_date; $bib_hash->{'biblio.title'} = $item->title; $bib_hash->{'biblio.author'} = $item->author; @@ -1194,9 +1161,8 @@ sub _create_bib_from_quote { sub _create_item_from_quote { my ( $item, $quote ) = @_; - my $defalt_classification_source = - C4::Context->preference('DefaultClassificationSource'); - my $item_hash = { + my $defalt_classification_source = C4::Context->preference('DefaultClassificationSource'); + my $item_hash = { cn_source => $defalt_classification_source, notforloan => -1, cn_sort => q{}, @@ -1205,14 +1171,14 @@ sub _create_item_from_quote { $item_hash->{price} = $item_hash->{replacementprice} = $item->price; $item_hash->{itype} = $item->girfield('stock_category'); my $lsq_field = C4::Context->preference('EdifactLSQ'); - $item_hash->{$lsq_field} = $item->girfield('sequence_code'); + $item_hash->{$lsq_field} = $item->girfield('sequence_code'); my $note = {}; $item_hash->{itemcallnumber} = - $item->girfield('shelfmark') - || $item->girfield('classification') - || title_level_class($item); + $item->girfield('shelfmark') + || $item->girfield('classification') + || title_level_class($item); my $branch = $item->girfield('branch'); $item_hash->{holdingbranch} = $item_hash->{homebranch} = $branch; diff --git a/Koha/ERM/Agreement.pm b/Koha/ERM/Agreement.pm index 785c5e30c7..ae2ab94e4b 100644 --- a/Koha/ERM/Agreement.pm +++ b/Koha/ERM/Agreement.pm @@ -53,7 +53,7 @@ Returns the periods for this agreement sub periods { my ( $self, $periods ) = @_; - if ( $periods ) { + if ($periods) { my $schema = $self->_result->result_source->schema; $schema->txn_do( sub { @@ -79,7 +79,7 @@ Returns the user roles for this agreement sub user_roles { my ( $self, $user_roles ) = @_; - if ( $user_roles ) { + if ($user_roles) { my $schema = $self->_result->result_source->schema; $schema->txn_do( sub { @@ -104,11 +104,10 @@ Returns the agreement_licenses for this agreement sub agreement_licenses { my ( $self, $agreement_licenses ) = @_; - if ( $agreement_licenses ) { + if ($agreement_licenses) { my $controlling = grep { $_->{status} eq 'controlling' } @$agreement_licenses; if ( $controlling > 1 ) { - Koha::Exceptions::DuplicateObject->throw( - "Only one controlling license can exist for a given agreement"); + Koha::Exceptions::DuplicateObject->throw("Only one controlling license can exist for a given agreement"); } my $schema = $self->_result->result_source->schema; @@ -135,19 +134,20 @@ Returns the agreement relationships of this agreement sub agreement_relationships { my ( $self, $relationships ) = @_; - if ( $relationships ) { + if ($relationships) { my $schema = $self->_result->result_source->schema; + # FIXME naming - is "back link" ok? my $back_links = { - 'supersedes' => 'is-superseded-by', - 'is-superseded-by' => 'supersedes', + 'supersedes' => 'is-superseded-by', + 'is-superseded-by' => 'supersedes', 'provides_post-cancellation_access_for' => 'has-post-cancellation-access-in', 'has-post-cancellation-access-in' => 'provides_post-cancellation_access_for', 'tracks_demand-driven_acquisitions_for' => 'has-demand-driven-acquisitions-in', 'has-demand-driven-acquisitions-in' => 'tracks_demand-driven_acquisitions_for', - 'has_backfile_in' => 'has_frontfile_in', - 'has_frontfile_in' => 'has_backfile_in', - 'related_to' => 'related_to', + 'has_backfile_in' => 'has_frontfile_in', + 'has_frontfile_in' => 'has_backfile_in', + 'related_to' => 'related_to', }; $schema->txn_do( sub { @@ -157,10 +157,10 @@ sub agreement_relationships { for my $relationship (@$relationships) { $self->_result->add_to_erm_agreement_relationships_agreements($relationship); my $back_link = { - agreement_id => $relationship->{related_agreement_id}, + agreement_id => $relationship->{related_agreement_id}, related_agreement_id => $self->agreement_id, - relationship => $back_links->{$relationship->{relationship}}, - notes => $relationship->{notes}, # FIXME Is it correct, do we keep the note here? + relationship => $back_links->{ $relationship->{relationship} }, + notes => $relationship->{notes}, # FIXME Is it correct, do we keep the note here? }; $self->_result->add_to_erm_agreement_relationships_related_agreements($back_link); } @@ -179,7 +179,7 @@ Returns the reverse relationship =cut sub agreement_back_relationships { - my ( $self ) = @_; + my ($self) = @_; my $rs = $self->_result->erm_agreement_relationships_related_agreements; return Koha::ERM::Agreement::Relationships->_new_from_dbic($rs); } @@ -199,7 +199,7 @@ Returns or updates the documents for this agreement sub documents { my ( $self, $documents ) = @_; if ($documents) { - $self->documents->replace_with($documents, $self); + $self->documents->replace_with( $documents, $self ); } my $documents_rs = $self->_result->erm_documents; return Koha::ERM::Documents->_new_from_dbic($documents_rs); @@ -212,7 +212,7 @@ Return the local packages for this agreement (and the other ones that have an en =cut sub agreement_packages { - my ( $self ) = @_; + my ($self) = @_; my $packages_agreements_rs = $self->_result->erm_eholdings_packages_agreements; return Koha::ERM::EHoldings::Package::Agreements->_new_from_dbic($packages_agreements_rs); } @@ -224,7 +224,7 @@ Return the vendor for this agreement =cut sub vendor { - my ( $self ) = @_; + my ($self) = @_; my $vendor_rs = $self->_result->vendor; return unless $vendor_rs; return Koha::Acquisition::Bookseller->_new_from_dbic($vendor_rs); diff --git a/Koha/ERM/Agreement/License.pm b/Koha/ERM/Agreement/License.pm index 35ae9c3a3f..7c1a95f722 100644 --- a/Koha/ERM/Agreement/License.pm +++ b/Koha/ERM/Agreement/License.pm @@ -41,7 +41,7 @@ Return the license =cut sub license { - my ( $self ) = @_; + my ($self) = @_; my $license_rs = $self->_result->license; return Koha::ERM::License->_new_from_dbic($license_rs); } @@ -53,7 +53,7 @@ Return the agreement =cut sub agreement { - my ( $self ) = @_; + my ($self) = @_; my $agreement_rs = $self->_result->agreement; return Koha::ERM::Agreement->_new_from_dbic($agreement_rs); } diff --git a/Koha/ERM/Agreement/Licenses.pm b/Koha/ERM/Agreement/Licenses.pm index 61d9e4c14d..e7e0160db7 100644 --- a/Koha/ERM/Agreement/Licenses.pm +++ b/Koha/ERM/Agreement/Licenses.pm @@ -17,7 +17,6 @@ package Koha::ERM::Agreement::Licenses; use Modern::Perl; - use Koha::Database; use Koha::ERM::Agreement::License; diff --git a/Koha/ERM/Agreement/Periods.pm b/Koha/ERM/Agreement/Periods.pm index eb35b9a739..5062d83f38 100644 --- a/Koha/ERM/Agreement/Periods.pm +++ b/Koha/ERM/Agreement/Periods.pm @@ -17,7 +17,6 @@ package Koha::ERM::Agreement::Periods; use Modern::Perl; - use Koha::Database; use Koha::ERM::Agreement::Period; diff --git a/Koha/ERM/Agreement/Relationship.pm b/Koha/ERM/Agreement/Relationship.pm index 0186ec70f5..f2851798c1 100644 --- a/Koha/ERM/Agreement/Relationship.pm +++ b/Koha/ERM/Agreement/Relationship.pm @@ -40,7 +40,7 @@ Return the agreement of this relationship =cut sub agreement { - my ( $self ) = @_; + my ($self) = @_; my $agreement_rs = $self->_result->agreement; return Koha::ERM::Agreement->_new_from_dbic($agreement_rs); } @@ -52,7 +52,7 @@ Return the agreement linked to this relationship =cut sub related_agreement { - my ( $self ) = @_; + my ($self) = @_; my $agreement_rs = $self->_result->related_agreement; return Koha::ERM::Agreement->_new_from_dbic($agreement_rs); } diff --git a/Koha/ERM/Agreement/Relationships.pm b/Koha/ERM/Agreement/Relationships.pm index 501eba44d0..7d4309b603 100644 --- a/Koha/ERM/Agreement/Relationships.pm +++ b/Koha/ERM/Agreement/Relationships.pm @@ -17,7 +17,6 @@ package Koha::ERM::Agreement::Relationships; use Modern::Perl; - use Koha::Database; use Koha::ERM::Agreement::Relationship; diff --git a/Koha/ERM/Agreements.pm b/Koha/ERM/Agreements.pm index 9c786ca107..2a81307781 100644 --- a/Koha/ERM/Agreements.pm +++ b/Koha/ERM/Agreements.pm @@ -41,19 +41,19 @@ Koha::ERM::Agreements- Koha ErmAgreement Object set class =cut sub filter_by_expired { - my ($self, $max_expiration_date) = @_; + my ( $self, $max_expiration_date ) = @_; $max_expiration_date = - $max_expiration_date - ? dt_from_string( $max_expiration_date, 'iso' ) - : dt_from_string; + $max_expiration_date + ? dt_from_string( $max_expiration_date, 'iso' ) + : dt_from_string; my $periods = Koha::ERM::Agreement::Periods->search( { agreement_id => [ $self->get_column('agreement_id') ] }, { select => [ 'agreement_id', - \do {"CASE WHEN MAX(me.ended_on IS NULL) = 0 THEN max(me.ended_on) END"} + \do { "CASE WHEN MAX(me.ended_on IS NULL) = 0 THEN max(me.ended_on) END" } ], as => [ 'agreement_id', 'max_ended_on' ], group_by => ['agreement_id'], @@ -62,6 +62,7 @@ sub filter_by_expired { my @expired_agreement_ids; while ( my $p = $periods->next ) { + # FIXME Can this be moved in the HAVING clause of the previous query? my $max_ended_on = $p->get_column('max_ended_on'); next unless $max_ended_on; diff --git a/Koha/ERM/Documents.pm b/Koha/ERM/Documents.pm index 36c507cf43..1492facabc 100644 --- a/Koha/ERM/Documents.pm +++ b/Koha/ERM/Documents.pm @@ -49,6 +49,7 @@ sub replace_with { sub { my $existing_documents = $obj->documents; my $max_allowed_packet = C4::Context->dbh->selectrow_array(q{SELECT @@max_allowed_packet}); + # FIXME Here we are not deleting all the documents before recreating them, like we do for other related resources. # As we do not want the content of the documents to transit over the network we need to use the document_id (and allow it in the API spec) # to distinguish from each other @@ -57,34 +58,33 @@ sub replace_with { $obj->documents->search( { @$document_ids_after_update - ? ( - document_id => { - '-not_in' => $document_ids_after_update - } - ) + ? ( document_id => { '-not_in' => $document_ids_after_update } ) : () } )->delete; for my $document (@$documents) { - my $file_content = defined($document->{file_content}) ? decode_base64( $document->{file_content} ) : ""; + my $file_content = + defined( $document->{file_content} ) ? decode_base64( $document->{file_content} ) : ""; my $mt = MIME::Types->new(); + # Throw exception if uploaded file exceeds server limit - Koha::Exceptions::PayloadTooLarge->throw("File size exceeds limit defined by server") if length($file_content) > $max_allowed_packet; + Koha::Exceptions::PayloadTooLarge->throw("File size exceeds limit defined by server") + if length($file_content) > $max_allowed_packet; if ( $document->{document_id} ) { + # The document already exists in DB - $existing_documents->find( $document->{document_id} ) - ->set( + $existing_documents->find( $document->{document_id} )->set( { #Check if existing document had its file changed length $file_content ? ( - file_content => $file_content, - file_type => $mt->mimeTypeOf( $document->{file_name} ), - file_name => $document->{file_name}, - uploaded_on => dt_from_string, - ) + file_content => $file_content, + file_type => $mt->mimeTypeOf( $document->{file_name} ), + file_name => $document->{file_name}, + uploaded_on => dt_from_string, + ) : (), file_description => $document->{file_description}, physical_location => $document->{physical_location}, @@ -92,13 +92,13 @@ sub replace_with { notes => $document->{notes}, } )->store; - } - else { + } else { + # Creating a whole new document $document->{file_type} = $mt->mimeTypeOf( $document->{file_name} ); $document->{uploaded_on} //= dt_from_string; $document->{file_content} = $file_content; - $obj->_result->add_to_erm_documents( $document); + $obj->_result->add_to_erm_documents($document); } } } diff --git a/Koha/ERM/EHoldings/Package.pm b/Koha/ERM/EHoldings/Package.pm index 06c3c3a2a6..3e028cea41 100644 --- a/Koha/ERM/EHoldings/Package.pm +++ b/Koha/ERM/EHoldings/Package.pm @@ -42,7 +42,7 @@ Returns the package agreements link for this package sub package_agreements { my ( $self, $package_agreements ) = @_; - if ( $package_agreements ) { + if ($package_agreements) { my $schema = $self->_result->result_source->schema; $schema->txn_do( sub { @@ -66,7 +66,7 @@ Returns the resources from this package =cut sub resources { - my ( $self ) = @_; + my ($self) = @_; my $rs = $self->_result->erm_eholdings_resources; return Koha::ERM::EHoldings::Resources->_new_from_dbic($rs); } @@ -78,7 +78,7 @@ Returns the vendor =cut sub vendor { - my ( $self ) = @_; + my ($self) = @_; my $rs = $self->_result->vendor; return unless $rs; return Koha::Acquisition::Bookseller->_new_from_dbic($rs); diff --git a/Koha/ERM/EHoldings/Package/Agreement.pm b/Koha/ERM/EHoldings/Package/Agreement.pm index 0df41b435a..52eca7249c 100644 --- a/Koha/ERM/EHoldings/Package/Agreement.pm +++ b/Koha/ERM/EHoldings/Package/Agreement.pm @@ -41,7 +41,7 @@ Return the agreement linked to this package agreement =cut sub agreement { - my ( $self ) = @_; + my ($self) = @_; my $agreement_rs = $self->_result->agreement; return Koha::ERM::Agreement->_new_from_dbic($agreement_rs); } @@ -53,7 +53,7 @@ Return the package linked to this package package =cut sub package { - my ( $self ) = @_; + my ($self) = @_; my $package_rs = $self->_result->package; return Koha::ERM::EHoldings::Package->_new_from_dbic($package_rs); } diff --git a/Koha/ERM/EHoldings/Packages.pm b/Koha/ERM/EHoldings/Packages.pm index 021f1b1aec..79ace6cd28 100644 --- a/Koha/ERM/EHoldings/Packages.pm +++ b/Koha/ERM/EHoldings/Packages.pm @@ -17,7 +17,6 @@ package Koha::ERM::EHoldings::Packages; use Modern::Perl; - use Koha::Database; use Koha::ERM::EHoldings::Package; diff --git a/Koha/ERM/EHoldings/Resource.pm b/Koha/ERM/EHoldings/Resource.pm index b9e3bb4a6f..020d8ac0ca 100644 --- a/Koha/ERM/EHoldings/Resource.pm +++ b/Koha/ERM/EHoldings/Resource.pm @@ -45,7 +45,7 @@ Return the package for this resource =cut sub package { - my ( $self ) = @_; + my ($self) = @_; my $package_rs = $self->_result->package; return Koha::ERM::EHoldings::Package->_new_from_dbic($package_rs); } @@ -57,7 +57,7 @@ Return the title for this resource =cut sub title { - my ( $self ) = @_; + my ($self) = @_; my $title_rs = $self->_result->title; return Koha::ERM::EHoldings::Title->_new_from_dbic($title_rs); } @@ -69,13 +69,12 @@ Return the vendor for this resource =cut sub vendor { - my ( $self ) = @_; + my ($self) = @_; my $vendor_rs = $self->_result->vendor; return unless $vendor_rs; return Koha::Acquisition::Bookseller->_new_from_dbic($vendor_rs); } - =head2 Internal methods =head3 _type diff --git a/Koha/ERM/EHoldings/Titles.pm b/Koha/ERM/EHoldings/Titles.pm index 756067568a..d50332f516 100644 --- a/Koha/ERM/EHoldings/Titles.pm +++ b/Koha/ERM/EHoldings/Titles.pm @@ -17,7 +17,6 @@ package Koha::ERM::EHoldings::Titles; use Modern::Perl; - use Koha::Database; use Koha::ERM::EHoldings::Title; diff --git a/Koha/ERM/EUsage/CounterLog.pm b/Koha/ERM/EUsage/CounterLog.pm index 1dd7c5aa01..f31e0d3a04 100644 --- a/Koha/ERM/EUsage/CounterLog.pm +++ b/Koha/ERM/EUsage/CounterLog.pm @@ -57,7 +57,6 @@ sub patron { return Koha::Patron->_new_from_dbic($patrons_rs); } - =head2 Internal methods =head3 _type diff --git a/Koha/ERM/EUsage/SushiCounter.pm b/Koha/ERM/EUsage/SushiCounter.pm index 10bde4ea21..5476320643 100644 --- a/Koha/ERM/EUsage/SushiCounter.pm +++ b/Koha/ERM/EUsage/SushiCounter.pm @@ -110,10 +110,10 @@ sub _COUNTER_report_header { my $end_date = $self->_get_SUSHI_Name_Value( $header->{Report_Filters}, "End_Date" ); return ( - [ Report_Name => $header->{Report_Name} || "" ], - [ Report_ID => $header->{Report_ID} || "" ], - [ Release => $header->{Release} || "" ], - [ Institution_Name => $header->{Institution_Name} || "" ], + [ Report_Name => $header->{Report_Name} || "" ], + [ Report_ID => $header->{Report_ID} || "" ], + [ Release => $header->{Release} || "" ], + [ Institution_Name => $header->{Institution_Name} || "" ], [ Institution_ID => join( "; ", map( $_->{Type} . ":" . $_->{Value}, @{ $header->{Institution_ID} } ) ) || "" ], [ Metric_Types => join( "; ", split( /\|/, $metric_types_string[0] ) ) || "" ], [ Report_Filters => join( "; ", map( $_->{Name} . ":" . $_->{Value}, @{ $header->{Report_Filters} } ) ) || "" ], @@ -127,7 +127,7 @@ sub _COUNTER_report_header { || "" ], [ Reporting_Period => "Begin_Date=" . $begin_date . "; End_Date=" . $end_date ], - [ Created => $header->{Created} || "" ], + [ Created => $header->{Created} || "" ], [ Created_By => $header->{Created_By} || "" ], [""] #empty 13th line (COUNTER 5) ); @@ -269,7 +269,7 @@ sub _COUNTER_platform_report_row { return ( [ $platform_row->{Platform} || "", $metric_type, - $total_usage, @{$monthly_usages} + $total_usage, @{$monthly_usages} ] ); } @@ -715,7 +715,7 @@ sub get_report_type_specific_fields { "TR_J3" => ['Access_Type'], "TR_J4" => ['YOP'], "IR_A1" => [ - 'Authors', 'Publication_Date', 'Article_Version', 'Print_ISSN', 'Online_ISSN', 'Parent_Title', + 'Authors', 'Publication_Date', 'Article_Version', 'Print_ISSN', 'Online_ISSN', 'Parent_Title', 'Parent_Authors', 'Parent_Article_Version', 'Parent_DOI', 'Parent_Proprietary_ID', 'Parent_Print_ISSN', 'Parent_Online_ISSN', 'Parent_URI', 'Access_Type' ], diff --git a/Koha/ERM/License.pm b/Koha/ERM/License.pm index d690fe24ab..e6bb7b9ae1 100644 --- a/Koha/ERM/License.pm +++ b/Koha/ERM/License.pm @@ -44,7 +44,7 @@ Returns the user roles for this license sub user_roles { my ( $self, $user_roles ) = @_; - if ( $user_roles ) { + if ($user_roles) { my $schema = $self->_result->result_source->schema; $schema->txn_do( sub { @@ -69,7 +69,7 @@ Returns or updates the documents for this license sub documents { my ( $self, $documents ) = @_; if ($documents) { - $self->documents->replace_with($documents, $self); + $self->documents->replace_with( $documents, $self ); } my $documents_rs = $self->_result->erm_documents; return Koha::ERM::Documents->_new_from_dbic($documents_rs); @@ -82,7 +82,7 @@ Return the vendor for this license =cut sub vendor { - my ( $self ) = @_; + my ($self) = @_; my $vendor_rs = $self->_result->vendor; return unless $vendor_rs; return Koha::Acquisition::Bookseller->_new_from_dbic($vendor_rs); diff --git a/Koha/ERM/Licenses.pm b/Koha/ERM/Licenses.pm index abece2c679..ef8d45ab51 100644 --- a/Koha/ERM/Licenses.pm +++ b/Koha/ERM/Licenses.pm @@ -17,7 +17,6 @@ package Koha::ERM::Licenses; use Modern::Perl; - use Koha::Database; use Koha::ERM::License; diff --git a/Koha/ERM/Providers/EBSCO.pm b/Koha/ERM/Providers/EBSCO.pm index 5e3aa377ef..edaa61f6f8 100644 --- a/Koha/ERM/Providers/EBSCO.pm +++ b/Koha/ERM/Providers/EBSCO.pm @@ -4,7 +4,7 @@ use Modern::Perl; use HTTP::Request; use LWP::UserAgent; -use JSON qw( from_json decode_json encode_json ); +use JSON qw( from_json decode_json encode_json ); use List::Util qw( first ); use Koha::Exceptions; @@ -13,13 +13,14 @@ use Koha::ERM::EHoldings::Packages; sub new { my $class = shift; - my $self = {}; + my $self = {}; return bless $self, $class; } sub config { return { - custid => C4::Context->preference('ERMProviderEbscoCustomerID') || C4::Context->config('ERMProviderEbscoCustomerID'), + custid => C4::Context->preference('ERMProviderEbscoCustomerID') + || C4::Context->config('ERMProviderEbscoCustomerID'), api_key => C4::Context->preference('ERMProviderEbscoApiKey') || C4::Context->config('ERMProviderEbscoApiKey'), }; } @@ -29,6 +30,7 @@ sub build_title { my $title = { title_id => $result->{titleId}, publication_title => $result->{titleName}, + # date_first_issue_online => ?, # num_first_vol_online => ?, # num_first_issue_online => ?, @@ -39,8 +41,9 @@ sub build_title { # embargo_info => ?, # coverage_depth => ?, # notes => ?, - publisher_name => $result->{publisherName}, + publisher_name => $result->{publisherName}, publication_type => $result->{pubType}, + # date_monograph_published_print => ?, # date_monograph_published_online => ?, # monograph_volume => ?, @@ -53,7 +56,7 @@ sub build_title { if ( $result->{contributorsList} ) { my @contributors = @{ $result->{contributorsList} }; my $first_author = first { $_->{type} eq 'author' || $_->{type} eq 'Author' } @contributors; - if ( $first_author ) { + if ($first_author) { $title->{first_author} = $first_author->{contributor}; } } @@ -62,8 +65,7 @@ sub build_title { # FIXME $identifier->{type} : 0 for ISSN and 1 for ISBN if ( $identifier->{subtype} == 1 ) { $title->{print_identifier} = $identifier->{id}; - } - elsif ( $identifier->{subtype} == 2 ) { + } elsif ( $identifier->{subtype} == 2 ) { $title->{online_identifier} = $identifier->{id}; } } @@ -89,15 +91,16 @@ sub build_vendor { sub build_package { my ( $self, $result ) = @_; - my $local_package = $self->get_local_package( - $result->{vendorId} . '-' . $result->{packageId} ); - my $package = { - package_id => $result->{vendorId} . '-' . $result->{packageId}, - ( $local_package + my $local_package = $self->get_local_package( $result->{vendorId} . '-' . $result->{packageId} ); + my $package = { + package_id => $result->{vendorId} . '-' . $result->{packageId}, + ( + $local_package ? ( koha_internal_id => $local_package->package_id ) - : () ), + : () + ), name => $result->{packageName}, - content_type => $result->{contentType}, # This does not exist in /vendors/1/packages/2/titles/3 + content_type => $result->{contentType}, # This does not exist in /vendors/1/packages/2/titles/3 created_on => undef, is_selected => $result->{isSelected}, package_type => $result->{packageType}, @@ -109,9 +112,7 @@ sub build_package { sub build_resource { my ( $self, $result ) = @_; my $resource = { - resource_id => $result->{vendorId} . '-' - . $result->{packageId} . '-' - . $result->{titleId}, + resource_id => $result->{vendorId} . '-' . $result->{packageId} . '-' . $result->{titleId}, package_id => $result->{vendorId} . '-' . $result->{packageId}, title_id => $result->{titleId}, is_selected => $result->{isSelected}, @@ -137,8 +138,7 @@ sub build_additional_params { sub get_local_package { my ( $self, $package_id ) = @_; - return Koha::ERM::EHoldings::Packages->find( - { provider => 'ebsco', external_id => $package_id } ); + return Koha::ERM::EHoldings::Packages->find( { provider => 'ebsco', external_id => $package_id } ); } sub embed { @@ -150,36 +150,29 @@ sub embed { foreach my $embed_req ( split /\s*,\s*/, $embed_header ) { if ( $embed_req eq 'vendor.name' ) { $object->{vendor} = { name => $info->{vendorName}, }; - } - elsif ( $embed_req eq 'vendor' ) { + } elsif ( $embed_req eq 'vendor' ) { $object->{vendor} = $self->build_vendor($info); - } - elsif ( $embed_req eq 'title' ) { + } elsif ( $embed_req eq 'title' ) { $object->{title} = $self->build_title($info); - } - elsif ( $embed_req eq 'resources+count' ) { + } elsif ( $embed_req eq 'resources+count' ) { $object->{resources_count} = $info->{titleCount}; - } - elsif ( $embed_req eq 'package' ) { + } elsif ( $embed_req eq 'package' ) { $object->{package} = $self->build_package($info); - } - elsif ( $embed_req eq 'package.name' ) { + } elsif ( $embed_req eq 'package.name' ) { $object->{package} = { name => $info->{packageName}, }; - } - elsif ( $embed_req eq 'package_agreements.agreement' ) { + } elsif ( $embed_req eq 'package_agreements.agreement' ) { + # How to deal with 'package_agreements.agreement'? $object->{package_agreements} = []; - my $package_id = $info->{vendorId} . '-' . $info->{packageId}; + my $package_id = $info->{vendorId} . '-' . $info->{packageId}; my $local_package = $self->get_local_package($package_id); - if ( $local_package ) { - for my $package_agreement ( - @{ $local_package->package_agreements->as_list } ) - { + if ($local_package) { + for my $package_agreement ( @{ $local_package->package_agreements->as_list } ) { push @{ $object->{package_agreements} }, - { + { %{ $package_agreement->unblessed }, agreement => $package_agreement->agreement->unblessed, - }; + }; } } } @@ -191,18 +184,17 @@ sub embed { if (@embed_resources) { for my $r ( @{ $info->{customerResourcesList} } ) { my $resource = {}; - for my $embed_req ( @embed_resources ) { + for my $embed_req (@embed_resources) { if ( $embed_req eq 'resources' ) { $resource = $self->build_resource($r); - } - elsif ( $embed_req eq 'resources.package' ) { - unless ( %$resource ) { + } elsif ( $embed_req eq 'resources.package' ) { + unless (%$resource) { $resource = $self->build_resource($r); } $resource->{package} = $self->build_package($r); } } - push @{$object->{resources}}, $resource; + push @{ $object->{resources} }, $resource; } } return $object; @@ -210,8 +202,7 @@ sub embed { sub build_query_pagination { my ( $self, $params ) = @_; - my $per_page = $params->{_per_page} - // C4::Context->preference('RESTdefaultPageSize') // 20; + my $per_page = $params->{_per_page} // C4::Context->preference('RESTdefaultPageSize') // 20; if ( $per_page == -1 || $per_page > 100 ) { $per_page = 100; } my $page = $params->{_page} || 1; @@ -225,17 +216,13 @@ sub build_query { while ( my ( $attr, $value ) = each %$params ) { if ( $attr eq 'name' ) { $url .= '&search=' . $value; - } - elsif ( $attr eq 'content_type' ) { + } elsif ( $attr eq 'content_type' ) { $url .= '&contenttype=' . $value; - } - elsif ( $attr eq 'selection_type' ) { + } elsif ( $attr eq 'selection_type' ) { $url .= '&selection=' . $value; - } - elsif ( $attr eq 'publication_title' ) { + } elsif ( $attr eq 'publication_title' ) { $url .= '&search=' . $value; - } - elsif ( $attr eq 'publication_type' ) { + } elsif ( $attr eq 'publication_type' ) { $url .= '&resourcetype=' . $value; } } @@ -245,17 +232,17 @@ sub build_query { sub request { my ( $self, $method, $url, $params, $payload ) = @_; - $url = $self->build_query($url, $params) if $params; + $url = $self->build_query( $url, $params ) if $params; - my $config = $self->config; + my $config = $self->config; my $base_url = 'https://api.ebsco.io/rm/rmaccounts/' . $config->{custid}; - my $request = HTTP::Request->new( + my $request = HTTP::Request->new( $method => $base_url . $url, undef, ( $payload ? encode_json($payload) : undef ) ); - $request->header( 'x-api-key' => $config->{api_key} ); + $request->header( 'x-api-key' => $config->{api_key} ); $request->header( 'content-type' => 'application/json; charset=UTF-8' ); - my $ua = LWP::UserAgent->new; + my $ua = LWP::UserAgent->new; my $response = $ua->simple_request($request); if ( $response->code >= 400 ) { my $result = decode_json( $response->decoded_content ); @@ -264,8 +251,7 @@ sub request { for my $r (@$result) { $message .= $r->{message}; } - } - else { + } else { $message = $result->{message} || $result->{Message} || q{}; if ( $result->{errors} ) { for my $e ( @{ $result->{errors} } ) { @@ -280,10 +266,10 @@ sub request { Koha::Exceptions::Authorization::Unauthorized->throw($message); } else { die sprintf "ERROR requesting EBSCO API\n%s\ncode %s: %s\n", $url, $response->code, - $message; + $message; } - } elsif ( $response->code == 204 ) { # No content - return + } elsif ( $response->code == 204 ) { # No content + return; } return decode_json( $response->decoded_content ); diff --git a/Koha/ERM/UserRole.pm b/Koha/ERM/UserRole.pm index d0e6a72cec..08ead1b026 100644 --- a/Koha/ERM/UserRole.pm +++ b/Koha/ERM/UserRole.pm @@ -40,7 +40,7 @@ Return the patron linked to this user role =cut sub patron { - my ( $self ) = @_; + my ($self) = @_; my $patron_rs = $self->_result->user; return Koha::Patron->_new_from_dbic($patron_rs); } diff --git a/Koha/ERM/UserRoles.pm b/Koha/ERM/UserRoles.pm index d4153dbec4..480134fc0c 100644 --- a/Koha/ERM/UserRoles.pm +++ b/Koha/ERM/UserRoles.pm @@ -17,7 +17,6 @@ package Koha::ERM::UserRoles; use Modern::Perl; - use Koha::Database; use Koha::ERM::UserRole; diff --git a/Koha/Edifact.pm b/Koha/Edifact.pm index b3b3bf473e..d472201c46 100644 --- a/Koha/Edifact.pm +++ b/Koha/Edifact.pm @@ -20,7 +20,7 @@ package Koha::Edifact; use strict; use warnings; use File::Slurp qw( read_file ); -use Carp qw( carp croak ); +use Carp qw( carp croak ); use Koha::Edifact::Segment; use Koha::Edifact::Message; @@ -40,13 +40,11 @@ sub new { if ( $param_hashref->{filename} ) { if ( $param_hashref->{transmission} ) { - carp -"Cannot instantiate $class : both filename and transmission passed"; + carp "Cannot instantiate $class : both filename and transmission passed"; return; } $transmission = read_file( $param_hashref->{filename} ); - } - else { + } else { $transmission = $param_hashref->{transmission}; } $self->{transmission} = _init($transmission); @@ -78,8 +76,7 @@ sub interchange_trailer { my $trailer = $self->{transmission}->[-1]; if ( $field eq 'interchange_control_count' ) { return $trailer->elem(0); - } - elsif ( $field eq 'interchange_control_reference' ) { + } elsif ( $field eq 'interchange_control_reference' ) { return $trailer->elem(1); } carp "Trailer field $field not recognized"; @@ -107,15 +104,13 @@ sub next_segment { if ( $seg->tag eq 'UNH' ) { $self->{msg_type} = $seg->elem( 1, 0 ); - } - elsif ( $seg->tag eq 'LIN' ) { + } elsif ( $seg->tag eq 'LIN' ) { $self->{msg_type} = 'detail'; } if ( $seg->tag ne 'UNZ' ) { $self->{data_iterator}++; - } - else { + } else { $self->{data_iterator} = undef; } return $seg; @@ -146,8 +141,7 @@ sub _init { } return; - } - else { + } else { my $s = substr $msg, 10; croak "File does not start with a Service string advice :$s"; } @@ -165,15 +159,13 @@ sub message_array { if ( $seg->tag eq 'UNH' ) { $in_msg = 1; push @{$msg}, $seg; - } - elsif ( $seg->tag eq 'UNT' ) { + } elsif ( $seg->tag eq 'UNT' ) { $in_msg = 0; if ( @{$msg} ) { push @{$msg_arr}, Koha::Edifact::Message->new($msg); $msg = []; } - } - elsif ($in_msg) { + } elsif ($in_msg) { push @{$msg}, $seg; } } diff --git a/Koha/Edifact/Line.pm b/Koha/Edifact/Line.pm index 379ef13605..9d2c823737 100644 --- a/Koha/Edifact/Line.pm +++ b/Koha/Edifact/Line.pm @@ -54,34 +54,29 @@ sub _parse_lines { foreach my $s ( @{$aref} ) { if ( $s->tag eq 'PIA' ) { push @{ $d->{additional_product_ids} }, - { + { function_code => $s->elem(0), item_number => $s->elem( 1, 0 ), number_type => $s->elem( 1, 1 ), - }; - } - elsif ( $s->tag eq 'IMD' ) { + }; + } elsif ( $s->tag eq 'IMD' ) { push @item_description, $s; - } - elsif ( $s->tag eq 'QTY' ) { + } elsif ( $s->tag eq 'QTY' ) { if ( $s->elem( 0, 0 ) eq '47' ) { $d->{quantity_invoiced} = $s->elem( 0, 1 ); } $d->{quantity} = $s->elem( 0, 1 ); - } - elsif ( $s->tag eq 'DTM' ) { + } elsif ( $s->tag eq 'DTM' ) { if ( $s->elem( 0, 0 ) eq '44' ) { $d->{availability_date} = $s->elem( 0, 1 ); } - } - elsif ( $s->tag eq 'GIR' ) { + } elsif ( $s->tag eq 'GIR' ) { # we may get a Gir for each copy if QTY > 1 if ( !$d->{GIR} ) { $d->{GIR} = []; push @{ $d->{GIR} }, extract_gir($s); - } - else { + } else { my $gir = extract_gir($s); if ( $gir->{copy} ) { # may have to merge foreach my $g ( @{ $d->{GIR} } ) { @@ -100,23 +95,19 @@ sub _parse_lines { } } } - } - elsif ( $s->tag eq 'FTX' ) { + } elsif ( $s->tag eq 'FTX' ) { my $type = $s->elem(0); my $ctype = 'coded_free_text'; if ( $type eq 'LNO' ) { # Ingrams Oasis Internal Notes field $type = 'internal_notes'; $ctype = 'coded_internal_note'; - } - elsif ( $type eq 'LIN' ) { + } elsif ( $type eq 'LIN' ) { $type = 'orderline_free_text'; $ctype = 'coded_orderline_text'; - } - elsif ( $type eq 'SUB' ) { + } elsif ( $type eq 'SUB' ) { $type = 'coded_substitute_text'; - } - else { + } else { $type = 'free_text'; } @@ -127,35 +118,28 @@ sub _parse_lines { } my $ftx = $s->elem(3); - if ( ref $ftx eq 'ARRAY' ) { # it comes in 70 character components + if ( ref $ftx eq 'ARRAY' ) { # it comes in 70 character components $ftx = join q{ }, @{$ftx}; } - if ( exists $d->{$type} ) { # we can only catenate repeats + if ( exists $d->{$type} ) { # we can only catenate repeats $d->{$type} .= q{ }; $d->{$type} .= $ftx; - } - else { + } else { $d->{$type} = $ftx; } - } - elsif ( $s->tag eq 'MOA' ) { + } elsif ( $s->tag eq 'MOA' ) { $d->{monetary_amount} = $s->elem( 0, 1 ); - } - elsif ( $s->tag eq 'PRI' ) { + } elsif ( $s->tag eq 'PRI' ) { $d->{price} = $s->elem( 0, 1 ); - } - elsif ( $s->tag eq 'RFF' ) { + } elsif ( $s->tag eq 'RFF' ) { my $qualifier = $s->elem( 0, 0 ); - if ( $qualifier eq 'QLI' ) { # Suppliers unique quotation reference + if ( $qualifier eq 'QLI' ) { # Suppliers unique quotation reference $d->{reference} = $s->elem( 0, 1 ); - } - elsif ( $qualifier eq 'LI' ) { # Buyer's unique orderline number + } elsif ( $qualifier eq 'LI' ) { # Buyer's unique orderline number $d->{ordernumber} = $s->elem( 0, 1 ); - } - elsif ( $qualifier eq 'SLI' ) - { # Suppliers unique order line reference number + } elsif ( $qualifier eq 'SLI' ) { # Suppliers unique order line reference number $d->{orderline_reference_number} = $s->elem( 0, 1 ); } } @@ -170,7 +154,7 @@ sub _format_item_description { my @imd = @_; my $bibrec = {}; - # IMD : +Type code 'L' + characteristic code 3 char + Description in comp 3 & 4 + # IMD : +Type code 'L' + characteristic code 3 char + Description in comp 3 & 4 foreach my $imd (@imd) { my $type_code = $imd->elem(0); my $ccode = $imd->elem(1); @@ -179,15 +163,13 @@ sub _format_item_description { $desc .= $imd->elem( 2, 4 ); } if ( $type_code ne 'L' ) { - carp - "Only handles text item descriptions at present: code=$type_code"; + carp "Only handles text item descriptions at present: code=$type_code"; next; } if ( exists $bibrec->{$ccode} ) { $bibrec->{$ccode} .= q{ }; $bibrec->{$ccode} .= $desc; - } - else { + } else { $bibrec->{$ccode} = $desc; } } @@ -232,7 +214,7 @@ sub marc_record { push @fields, $f; } @spec = qw( 180 a 181 b 182 c 183 e); - $f = new_field( $b, [ 300, q{ }, q{ } ], @spec ); + $f = new_field( $b, [ 300, q{ }, q{ } ], @spec ); if ($f) { push @fields, $f; } @@ -307,17 +289,14 @@ sub corpcon { $tag = ( $level * 100 ) + 11; if ( $level == 1 ) { @spec = qw( 030 a 031 e 032 n 033 c 034 d); - } - else { + } else { @spec = qw( 040 a 041 e 042 n 043 c 044 d); } - } - else { + } else { $tag = ( $level * 100 ) + 10; if ( $level == 1 ) { @spec = qw( 030 a 031 b); - } - else { + } else { @spec = qw( 040 a 041 b); } } @@ -439,8 +418,7 @@ sub coded_orderline_text { my $txt; if ( $table eq '8B' || $table eq '7B' ) { $txt = translate_8B($code); - } - elsif ( $table eq '12B' ) { + } elsif ( $table eq '12B' ) { $txt = translate_12B($code); } if ( !$txt || $txt eq 'no match' ) { @@ -504,8 +482,7 @@ sub translate_8B { if ( exists $code_list_8B{$code} ) { return $code_list_8B{$code}; - } - else { + } else { return 'no match'; } } @@ -516,11 +493,9 @@ sub translate_12B { my %code_list_12B = ( 100 => 'Order line accepted', 101 => 'Price query: orderline will be held awaiting customer response', - 102 => - 'Discount query: order line will be held awaiting customer response', + 102 => 'Discount query: order line will be held awaiting customer response', 103 => 'Minimum order value not reached: order line will be held', - 104 => -'Firm order required: order line will be held awaiting customer response', + 104 => 'Firm order required: order line will be held awaiting customer response', 110 => 'Order line accepted, substitute product will be supplied', 200 => 'Order line not accepted', 201 => 'Price query: order line not accepted', @@ -528,8 +503,7 @@ sub translate_12B { 203 => 'Minimum order value not reached: order line not accepted', 205 => 'Order line not accepted: quoted promotion is invalid', 206 => 'Order line not accepted: quoted promotion has ended', - 207 => - 'Order line not accepted: customer ineligible for quoted promotion', + 207 => 'Order line not accepted: customer ineligible for quoted promotion', 210 => 'Order line not accepted: substitute product is offered', 220 => 'Oustanding order line cancelled: reason unspecified', 221 => 'Oustanding order line cancelled: past order expiry date', @@ -548,8 +522,7 @@ sub translate_12B { 408 => 'Our supplier sent imperfect item(s), re-ordered', 409 => 'Our supplier cannot trace order, re-ordered', 410 => 'Ordered item(s) being processed by bookseller', - 411 => -'Ordered item(s) being processed by bookseller, awaiting customer action', + 411 => 'Ordered item(s) being processed by bookseller, awaiting customer action', 412 => 'Order line held awaiting customer instruction', 500 => 'Order line on hold - contact customer service', 800 => 'Order line already despatched', @@ -562,8 +535,7 @@ sub translate_12B { if ( exists $code_list_12B{$code} ) { return $code_list_12B{$code}; - } - else { + } else { return 'no match'; } } @@ -649,8 +621,7 @@ sub girfield { } $occ ||= 0; return $self->{GIR}->[$occ]->{$field}; - } - else { + } else { return; } } @@ -662,8 +633,7 @@ sub number_of_girs { my $qty = @{ $self->{GIR} }; return $qty; - } - else { + } else { return 0; } } @@ -697,16 +667,15 @@ sub extract_gir { RIC => 'reader_interest_category', ); - my $set_qualifier = $s->elem( 0, 0 ); # copy number - my $gir_element = { copy => $set_qualifier, }; - my $element = 1; + my $set_qualifier = $s->elem( 0, 0 ); # copy number + my $gir_element = { copy => $set_qualifier, }; + my $element = 1; while ( my $e = $s->elem($element) ) { ++$element; if ( exists $qmap{ $e->[1] } ) { my $qualifier = $qmap{ $e->[1] }; $gir_element->{$qualifier} = $e->[0]; - } - else { + } else { carp "Unrecognized GIR code : $e->[1] for $e->[0]"; } @@ -724,8 +693,10 @@ sub moa_amt { } return; } + sub moa_multiple_amt { my ( $self, $qualifier ) = @_; + # return a repeatable MOA field my $amt = 0; my $found = 0; @@ -768,6 +739,7 @@ sub amt_lineitem { my $self = shift; return $self->moa_amt('203'); } + sub amt_taxoncharge { my $self = shift; return $self->moa_multiple_amt('124'); @@ -775,14 +747,16 @@ sub amt_taxoncharge { sub pri_price { my ( $self, $price_qualifier ) = @_; - # In practice qualifier is AAE in the quote and AAA & AAB in invoices - # but the following are defined - # AAA calculation price net (unit price excl tax but incl any allowances or charges) - # AAB calculation price gross (unit price excl all taxes, allowances and charges ) - # AAE information price (incl tax but excl allowances or charges ) - # AAF information price (including all taxes, allowances or charges) + + # In practice qualifier is AAE in the quote and AAA & AAB in invoices + # but the following are defined + # AAA calculation price net (unit price excl tax but incl any allowances or charges) + # AAB calculation price gross (unit price excl all taxes, allowances and charges ) + # AAE information price (incl tax but excl allowances or charges ) + # AAF information price (including all taxes, allowances or charges) foreach my $s ( @{ $self->{segs} } ) { if ( $s->tag eq 'PRI' && $s->elem( 0, 0 ) eq $price_qualifier ) { + # in practice not all 3 fields may be present # so use a temp variable to avoid runtime warnings my $p = { @@ -846,20 +820,21 @@ sub tax { sub tax_rate { my $self = shift; - my $tr = {}; + my $tr = {}; foreach my $s ( @{ $self->{segs} } ) { if ( $s->tag eq 'TAX' && $s->elem( 0, 0 ) == 7 ) { - $tr->{type} = $s->elem( 1, 0 ); # VAT, GST or IMP - $tr->{rate} = $s->elem( 4, 3 ); # percentage - # category values may be: - # E = exempt from tax - # G = export item, tax not charged - # H = higher rate - # L = lower rate - # S = standard rate - # Z = zero-rated + $tr->{type} = $s->elem( 1, 0 ); # VAT, GST or IMP + $tr->{rate} = $s->elem( 4, 3 ); # percentage + # category values may be: + # E = exempt from tax + # G = export item, tax not charged + # H = higher rate + # L = lower rate + # S = standard rate + # Z = zero-rated $tr->{category} = $s->elem( 5, 0 ); - if (!defined $tr->{rate} && $tr->{category} eq 'Z') { + + if ( !defined $tr->{rate} && $tr->{category} eq 'Z' ) { $tr->{rate} = 0; } return $tr; diff --git a/Koha/Edifact/Message.pm b/Koha/Edifact/Message.pm index 96eb680d2e..5c096ded41 100644 --- a/Koha/Edifact/Message.pm +++ b/Koha/Edifact/Message.pm @@ -56,8 +56,7 @@ sub function { my $msg_function = $self->{bgm}->elem(2); if ( $msg_function == 9 ) { return 'original'; - } - elsif ( $msg_function == 7 ) { + } elsif ( $msg_function == 7 ) { return 'retransmission'; } return; @@ -188,8 +187,7 @@ sub lineitems { my $self = shift; if ( $self->{quotation_lines} ) { return $self->{quotation_lines}; - } - else { + } else { my $items = []; my $item_arr = []; foreach my $seg ( @{ $self->{datasegs} } ) { @@ -200,14 +198,12 @@ sub lineitems { } $item_arr = [$seg]; next; - } - elsif ( $tag =~ m/^(UNS|CNT|UNT)$/sxm ) { + } elsif ( $tag =~ m/^(UNS|CNT|UNT)$/sxm ) { if ( @{$item_arr} ) { push @{$items}, Koha::Edifact::Line->new($item_arr); } last; - } - else { + } else { if ( @{$item_arr} ) { push @{$item_arr}, $seg; } diff --git a/Koha/Edifact/Order.pm b/Koha/Edifact/Order.pm index e43da925d5..d21de7cc69 100644 --- a/Koha/Edifact/Order.pm +++ b/Koha/Edifact/Order.pm @@ -26,7 +26,7 @@ use DateTime; use Readonly qw( Readonly ); use Koha::Database; use Koha::DateUtils qw( dt_from_string ); -use C4::Budgets qw( GetBudget ); +use C4::Budgets qw( GetBudget ); use Koha::Acquisition::Orders; @@ -50,7 +50,7 @@ sub new { $self->{is_response} = $parameter_hashref->{is_response}; # convenient alias - $self->{basket} = $self->{orderlines}->[0]->basketno; + $self->{basket} = $self->{orderlines}->[0]->basketno; $self->{message_date} = dt_from_string(); } @@ -60,13 +60,11 @@ sub new { return; } if ( !$self->{recipient} ) { - carp 'No vendor passed to order creation: basket = ' - . $self->{basket}->basketno; + carp 'No vendor passed to order creation: basket = ' . $self->{basket}->basketno; return; } if ( !$self->{sender} ) { - carp 'No sender ean passed to order creation: basket = ' - . $self->{basket}->basketno; + carp 'No sender ean passed to order creation: basket = ' . $self->{basket}->basketno; return; } @@ -105,7 +103,7 @@ sub encode { $self->{transmission} .= $self->trailing_service_segments(); # Guard against CR LF etc being added in data from DB - $self->{transmission}=~s/[\r\n\t]//g; + $self->{transmission} =~ s/[\r\n\t]//g; return $self->{transmission}; } @@ -132,13 +130,16 @@ sub interchange_header { my $self = shift; # syntax identifier - my $hdr = - 'UNB+UNOC:3'; # controlling agency character set syntax version number - # Interchange Sender - $hdr .= _interchange_sr_identifier( $self->{sender}->ean, - $self->{sender}->id_code_qualifier ); # interchange sender - $hdr .= _interchange_sr_identifier( $self->{recipient}->san, - $self->{recipient}->id_code_qualifier ); # interchange Recipient + my $hdr = 'UNB+UNOC:3'; # controlling agency character set syntax version number + # Interchange Sender + $hdr .= _interchange_sr_identifier( + $self->{sender}->ean, + $self->{sender}->id_code_qualifier + ); # interchange sender + $hdr .= _interchange_sr_identifier( + $self->{recipient}->san, + $self->{recipient}->id_code_qualifier + ); # interchange Recipient $hdr .= $separator; @@ -149,14 +150,14 @@ sub interchange_header { $hdr .= $separator; # Recipents reference password not usually used in edifact - $hdr .= q{+ORDERS}; # application reference + $hdr .= q{+ORDERS}; # application reference -#Edifact does not usually include the following -# $hdr .= $separator; # Processing priority not usually used in edifact -# $hdr .= $separator; # Acknowledgewment request : not usually used in edifact -# $hdr .= q{+EANCOM} # Communications agreement id -# $hdr .= q{+1} # Test indicator -# + #Edifact does not usually include the following + # $hdr .= $separator; # Processing priority not usually used in edifact + # $hdr .= $separator; # Acknowledgewment request : not usually used in edifact + # $hdr .= q{+EANCOM} # Communications agreement id + # $hdr .= q{+1} # Test indicator + # $hdr .= $seg_terminator; return $hdr; } @@ -194,9 +195,8 @@ sub message_trailer { $self->add_seg("CNT+2:$num_orderlines$seg_terminator"); # UNT Message Trailer - my $segments_in_message = - 1 + @{ $self->{segs} }; # count incl UNH & UNT (!!this one) - my $reference = $self->message_reference('current'); + my $segments_in_message = 1 + @{ $self->{segs} }; # count incl UNH & UNT (!!this one) + my $reference = $self->message_reference('current'); $self->add_seg("UNT+$segments_in_message+$reference$seg_terminator"); return; } @@ -216,8 +216,7 @@ sub interchange_control_reference { my $self = shift; if ( $self->{interchange_control_reference} ) { return sprintf '%014d', $self->{interchange_control_reference}; - } - else { + } else { carp 'calling for ref of unencoded order'; return 'NONE ASSIGNED'; } @@ -261,28 +260,28 @@ sub order_msg_header { # UNH see message_header # BGM push @header, - beginning_of_message( + beginning_of_message( $self->{basket}->basketno, $self->{recipient}->standard, $self->{is_response} - ); + ); # DTM push @header, message_date_segment( $self->{message_date} ); # NAD-RFF buyer supplier ids push @header, - name_and_address( + name_and_address( 'BUYER', $self->{sender}->ean, $self->{sender}->id_code_qualifier - ); + ); push @header, - name_and_address( + name_and_address( 'SUPPLIER', $self->{recipient}->san, $self->{recipient}->id_code_qualifier - ); + ); # repeat for for other relevant parties @@ -339,15 +338,13 @@ sub order_line { my $basket = Koha::Acquisition::Orders->find( $orderline->ordernumber )->basket; my $schema = $self->{schema}; - if ( !$orderline->biblionumber ) - { # cannot generate an orderline without a bib record + if ( !$orderline->biblionumber ) { # cannot generate an orderline without a bib record return; } my $biblionumber = $orderline->biblionumber->biblionumber; - my @biblioitems = $schema->resultset('Biblioitem') - ->search( { biblionumber => $biblionumber, } ); - my $biblioitem = $biblioitems[0]; # makes the assumption there is 1 only - # or else all have same details + my @biblioitems = $schema->resultset('Biblioitem')->search( { biblionumber => $biblionumber, } ); + my $biblioitem = $biblioitems[0]; # makes the assumption there is 1 only + # or else all have same details my $id_string = $orderline->line_item_id; @@ -389,8 +386,7 @@ sub order_line { }; } } - } - else { + } else { my $item_hash = { itype => $biblioitem->itemtype, itemcallnumber => $biblioitem->cn_class, @@ -403,18 +399,18 @@ sub order_line { push @items, $item_hash; } } - my $budget = GetBudget( $orderline->budget_id ); + my $budget = GetBudget( $orderline->budget_id ); my $ol_fields = { budget_code => $budget->{budget_code}, }; my $item_fields = []; for my $item (@items) { push @{$item_fields}, - { + { branchcode => $item->{branchcode}, itype => $item->{itype}, $lsq_field => $item->{$lsq_field}, itemcallnumber => $item->{itemcallnumber}, - }; + }; } $self->add_seg( gir_segments( @@ -437,6 +433,7 @@ sub order_line { $ftx .= $seg_terminator; $self->add_seg($ftx); } + # Encode notes here # PRI-CUX-DTM unit price on which order is placed : optional # Coutts read this as 0.00 if not present @@ -453,7 +450,7 @@ sub order_line { # RFF : suppliers unique quotation reference number if ( $orderline->suppliers_reference_number ) { $rff = join q{}, 'RFF+', $orderline->suppliers_reference_qualifier, - ':', $orderline->suppliers_reference_number, $seg_terminator; + ':', $orderline->suppliers_reference_number, $seg_terminator; $self->add_seg($rff); } @@ -523,8 +520,7 @@ sub imd_segment { foreach my $c (@chunks) { if ($odd) { push @segs, "$seg_prefix$c"; - } - else { + } else { $segs[-1] .= ":$c$seg_terminator"; } $odd = !$odd; @@ -544,40 +540,40 @@ sub gir_segments { my $budget_code = $orderfields->{budget_code}; my @segments; my $sequence_no = 1; - my $lsq_field = C4::Context->preference('EdifactLSQ'); + my $lsq_field = C4::Context->preference('EdifactLSQ'); foreach my $item (@onorderitems) { my $elements_added = 0; my @gir_elements; if ($budget_code) { push @gir_elements, - { identity_number => 'LFN', data => $budget_code }; + { identity_number => 'LFN', data => $budget_code }; } if ( $item->{branchcode} ) { push @gir_elements, - { identity_number => 'LLO', data => $item->{branchcode} }; + { identity_number => 'LLO', data => $item->{branchcode} }; } if ( $item->{itype} ) { push @gir_elements, - { identity_number => 'LST', data => $item->{itype} }; + { identity_number => 'LST', data => $item->{itype} }; } if ( $item->{$lsq_field} ) { push @gir_elements, - { identity_number => 'LSQ', data => $item->{$lsq_field} }; + { identity_number => 'LSQ', data => $item->{$lsq_field} }; } if ( $item->{itemcallnumber} ) { push @gir_elements, - { identity_number => 'LSM', data => $item->{itemcallnumber} }; + { identity_number => 'LSM', data => $item->{itemcallnumber} }; } # itemcallnumber -> shelfmark if ( $orderfields->{servicing_instruction} ) { push @gir_elements, - { + { identity_number => 'LVT', data => $orderfields->{servicing_instruction} - }; + }; } - my $e_cnt = 0; # count number of elements so we dont exceed 5 per segment + my $e_cnt = 0; # count number of elements so we dont exceed 5 per segment my $copy_no = sprintf 'GIR+%03d', $sequence_no; my $seg = $copy_no; foreach my $e (@gir_elements) { @@ -586,7 +582,7 @@ sub gir_segments { $seg = $copy_no; } $seg .= - add_gir_identity_number( $e->{identity_number}, $e->{data} ); + add_gir_identity_number( $e->{identity_number}, $e->{data} ); ++$e_cnt; } @@ -620,8 +616,7 @@ sub lin_segment { if ($item_number_id) { $item_number_id = "++${item_number_id}:EN"; - } - else { + } else { $item_number_id = q||; } @@ -634,8 +629,7 @@ sub additional_product_id { if ( $isbn_field =~ m/(\d{13})/ ) { $product_id = $1; $product_code = 'EN'; - } - elsif ( $isbn_field =~ m/(\d{9}[Xx\d])/ ) { + } elsif ( $isbn_field =~ m/(\d{9}[Xx\d])/ ) { $product_id = $1; $product_code = 'IB'; } diff --git a/Koha/Edifact/Segment.pm b/Koha/Edifact/Segment.pm index 8a29e57c18..563b3e7222 100644 --- a/Koha/Edifact/Segment.pm +++ b/Koha/Edifact/Segment.pm @@ -48,15 +48,13 @@ sub elem { if ( $component_number < @{$e} ) { return $e->[$component_number]; } - } - elsif ( $component_number == 0 ) { + } elsif ( $component_number == 0 ) { # a string could be an element with a single component return $e; } return; - } - else { + } else { return $e; } } @@ -77,8 +75,7 @@ sub as_string { $string .= q|+|; if ( ref $e eq 'ARRAY' ) { $string .= join q{:}, @{$e}; - } - else { + } else { $string .= $e; } } @@ -90,7 +87,7 @@ sub as_string { sub _parse_seg { my $s = shift; my $e = { - tag => substr( $s, 0, 3 ), + tag => substr( $s, 0, 3 ), elem_arr => _get_elements( substr( $s, 3 ) ), }; return $e; @@ -111,7 +108,7 @@ sub _get_elements { sub _components { my $element = shift; - my @c = split /(?schema(); my $acct = $schema->resultset('VendorEdiAccount')->find($account_id); my $self = { - account => $acct, - schema => $schema, - working_dir => C4::Context::temporary_directory, #temporary work directory + account => $acct, + schema => $schema, + working_dir => C4::Context::temporary_directory, #temporary work directory transfer_date => dt_from_string(), }; @@ -66,11 +66,9 @@ sub download_messages { if ( $self->{account}->transport eq 'SFTP' ) { @retrieved_files = $self->sftp_download(); - } - elsif ( $self->{account}->transport eq 'FILE' ) { + } elsif ( $self->{account}->transport eq 'FILE' ) { @retrieved_files = $self->file_download(); - } - else { # assume FTP + } else { # assume FTP @retrieved_files = $self->ftp_download(); } return @retrieved_files; @@ -81,11 +79,9 @@ sub upload_messages { if (@messages) { if ( $self->{account}->transport eq 'SFTP' ) { $self->sftp_upload(@messages); - } - elsif ( $self->{account}->transport eq 'FILE' ) { + } elsif ( $self->{account}->transport eq 'FILE' ) { $self->file_upload(@messages); - } - else { # assume FTP + } else { # assume FTP $self->ftp_upload(@messages); } } @@ -98,8 +94,8 @@ sub file_download { my $file_ext = _get_file_ext( $self->{message_type} ); - my $dir = $self->{account}->download_directory; # makes code more readable - # C = ready to retrieve E = Edifact + my $dir = $self->{account}->download_directory; # makes code more readable + # C = ready to retrieve E = Edifact my $msg_hash = $self->message_hash(); if ( opendir my $dh, $dir ) { my @file_list = readdir $dh; @@ -108,8 +104,7 @@ sub file_download { if ( $filename =~ m/[.]$file_ext$/ ) { if ( copy( "$dir/$filename", $self->{working_dir} ) ) { - } - else { + } else { carp "copy of $filename failed"; next; } @@ -120,8 +115,7 @@ sub file_download { } } $self->ingest( $msg_hash, @downloaded_files ); - } - else { + } else { carp "Cannot open $dir"; return; } @@ -140,28 +134,36 @@ sub sftp_download { my $sftp = Net::SFTP::Foreign->new( host => $self->{account}->host, user => $self->{account}->username, - password => Koha::Encryption->new->decrypt_hex($self->{account}->password), + password => Koha::Encryption->new->decrypt_hex( $self->{account}->password ), port => $port, timeout => 10, ); if ( $sftp->error ) { - return $self->_abort_download( undef, - 'Unable to connect to remote host: ' . $sftp->error ); + return $self->_abort_download( + undef, + 'Unable to connect to remote host: ' . $sftp->error + ); } $sftp->setcwd( $self->{account}->download_directory ) - or return $self->_abort_download( $sftp, - "Cannot change remote dir: " . $sftp->error ); + or return $self->_abort_download( + $sftp, + "Cannot change remote dir: " . $sftp->error + ); my $file_list = $sftp->ls() - or return $self->_abort_download( $sftp, - "cannot get file list from server: " . $sftp->error ); + or return $self->_abort_download( + $sftp, + "cannot get file list from server: " . $sftp->error + ); foreach my $file ( @{$file_list} ) { my $filename = $file->{filename}; if ( $filename =~ m/[.]$file_ext$/ ) { $sftp->get( $filename, "$self->{working_dir}/$filename" ); if ( $sftp->error ) { - $self->_abort_download( $sftp, - "Error retrieving $filename: " . $sftp->error ); + $self->_abort_download( + $sftp, + "Error retrieving $filename: " . $sftp->error + ); last; } push @downloaded_files, $filename; @@ -171,8 +173,10 @@ sub sftp_download { #$sftp->atomic_rename( $filename, $processed_name ); my $ret = $sftp->rename( $filename, $processed_name ); if ( !$ret ) { - $self->_abort_download( $sftp, - "Error renaming $filename: " . $sftp->error ); + $self->_abort_download( + $sftp, + "Error renaming $filename: " . $sftp->error + ); last; } @@ -189,16 +193,14 @@ sub ingest { foreach my $f (@downloaded_files) { # Check file has not been downloaded already - my $existing_file = $self->{schema}->resultset('EdifactMessage') - ->find( { filename => $f, } ); + my $existing_file = $self->{schema}->resultset('EdifactMessage')->find( { filename => $f, } ); if ($existing_file) { carp "skipping ingest of $f : filename exists"; next; } $msg_hash->{filename} = $f; - my $file_content = - read_file( "$self->{working_dir}/$f", binmode => ':raw' ); + my $file_content = read_file( "$self->{working_dir}/$f", binmode => ':raw' ); if ( !defined $file_content ) { carp "Unable to read download file $f"; next; @@ -230,22 +232,25 @@ sub ftp_download { undef, "Cannot connect to $self->{account}->host: $EVAL_ERROR" ); - $ftp->login( $self->{account}->username, Koha::Encryption->new->decrypt_hex($self->{account}->password) ) - or return $self->_abort_download( $ftp, "Cannot login: $ftp->message()" ); + $ftp->login( $self->{account}->username, Koha::Encryption->new->decrypt_hex( $self->{account}->password ) ) + or return $self->_abort_download( $ftp, "Cannot login: $ftp->message()" ); $ftp->cwd( $self->{account}->download_directory ) - or return $self->_abort_download( $ftp, - "Cannot change remote dir : $ftp->message()" ); + or return $self->_abort_download( + $ftp, + "Cannot change remote dir : $ftp->message()" + ); my $file_list = $ftp->ls() - or - return $self->_abort_download( $ftp, 'cannot get file list from server' ); + or return $self->_abort_download( $ftp, 'cannot get file list from server' ); foreach my $filename ( @{$file_list} ) { if ( $filename =~ m/[.]$file_ext$/ ) { if ( !$ftp->get( $filename, "$self->{working_dir}/$filename" ) ) { - $self->_abort_download( $ftp, - "Error retrieving $filename: $ftp->message" ); + $self->_abort_download( + $ftp, + "Error retrieving $filename: $ftp->message" + ); last; } @@ -275,11 +280,13 @@ sub ftp_upload { undef, "Cannot connect to $self->{account}->host: $EVAL_ERROR" ); - $ftp->login( $self->{account}->username, Koha::Encryption->new->decrypt_hex($self->{account}->password) ) - or return $self->_abort_download( $ftp, "Cannot login: $ftp->message()" ); + $ftp->login( $self->{account}->username, Koha::Encryption->new->decrypt_hex( $self->{account}->password ) ) + or return $self->_abort_download( $ftp, "Cannot login: $ftp->message()" ); $ftp->cwd( $self->{account}->upload_directory ) - or return $self->_abort_download( $ftp, - "Cannot change remote dir : $ftp->message()" ); + or return $self->_abort_download( + $ftp, + "Cannot change remote dir : $ftp->message()" + ); foreach my $m (@messages) { my $content = $m->raw_msg; if ($content) { @@ -289,8 +296,8 @@ sub ftp_upload { $m->transfer_date( $self->{transfer_date} ); $m->status('sent'); $m->update; - } - else { + } else { + # error in transfer } @@ -307,14 +314,16 @@ sub sftp_upload { my $sftp = Net::SFTP::Foreign->new( host => $self->{account}->host, user => $self->{account}->username, - password => Koha::Encryption->new->decrypt_hex($self->{account}->password), + password => Koha::Encryption->new->decrypt_hex( $self->{account}->password ), port => $port, timeout => 10, ); $sftp->die_on_error("Cannot ssh to $self->{account}->host"); $sftp->setcwd( $self->{account}->upload_directory ) - or return $self->_abort_download( $sftp, - "Cannot change remote dir : " . $sftp->error ); + or return $self->_abort_download( + $sftp, + "Cannot change remote dir : " . $sftp->error + ); foreach my $m (@messages) { my $content = $m->raw_msg; if ($content) { @@ -324,8 +333,8 @@ sub sftp_upload { $m->transfer_date( $self->{transfer_date} ); $m->status('sent'); $m->update; - } - else { + } else { + # error in transfer } @@ -351,15 +360,13 @@ sub file_upload { $m->transfer_date( $self->{transfer_date} ); $m->status('sent'); $m->update; - } - else { + } else { carp "Could not transfer $m->filename : $ERRNO"; next; } } } - } - else { + } else { carp "Upload directory $dir does not exist"; } return; diff --git a/Koha/Email.pm b/Koha/Email.pm index c95cda0108..280077b4fb 100644 --- a/Koha/Email.pm +++ b/Koha/Email.pm @@ -23,7 +23,7 @@ use Modern::Perl; use Email::Address; use Email::MessageID; use Email::MIME; -use List::Util qw( pairs ); +use List::Util qw( pairs ); use Scalar::Util qw( blessed ); use Koha::Exceptions; @@ -59,7 +59,7 @@ sub new_from_string { unless $email_string; my $self = $class->SUPER::new(); - my $mime = Email::MIME->new( $email_string ); + my $mime = Email::MIME->new($email_string); $self->{email} = $mime; return $self; @@ -113,8 +113,7 @@ sub create { if ( C4::Context->preference('SendAllEmailsTo') ) { $args->{to} = C4::Context->preference('SendAllEmailsTo'); - } - else { + } else { $args->{to} = $params->{to}; } @@ -141,11 +140,11 @@ sub create { foreach my $address ( keys %{$addresses} ) { Koha::Exceptions::BadParameter->throw( - error => "Invalid '$address' parameter: " . $addresses->{$address}, + error => "Invalid '$address' parameter: " . $addresses->{$address}, parameter => $address - ) - if $addresses->{$address} - and !Koha::Email->is_valid( $addresses->{$address} ); + ) + if $addresses->{$address} + and !Koha::Email->is_valid( $addresses->{$address} ); } $args->{cc} = $addresses->{cc} @@ -154,6 +153,7 @@ sub create { if $addresses->{bcc}; my $email; + # FIXME: This is ugly, but aids backportability # TODO: Remove this and move address and default headers handling # to separate subs to be (re)used @@ -165,9 +165,8 @@ sub create { $email->bcc( $args->{bcc} ) if $args->{bcc}; $email->reply_to( $args->{reply_to} ) if $args->{reply_to}; $email->subject( $args->{subject} ) if $args->{subject}; - } - else { - $email = $self->SUPER::new( $args ); + } else { + $email = $self->SUPER::new($args); } $email->header( 'Reply-To', $addresses->{reply_to} ) @@ -184,8 +183,7 @@ sub create { if ( $params->{text_body} ) { $email->text_body( $params->{text_body}, %{ $params->{body_params} } ); - } - elsif ( $params->{html_body} ) { + } elsif ( $params->{html_body} ) { $email->html_body( $params->{html_body}, %{ $params->{body_params} } ); } @@ -218,8 +216,8 @@ sub send_or_die { my @headers = $self->email->header_str_pairs; foreach my $pair ( pairs @headers ) { my ( $header, $value ) = @$pair; - push @recipients, split (', ', $value) - if grep { $_ eq $header } ('To', 'Cc', 'Bcc'); + push @recipients, split( ', ', $value ) + if grep { $_ eq $header } ( 'To', 'Cc', 'Bcc' ); } # Remove the Bcc header @@ -231,7 +229,7 @@ sub send_or_die { unless ( $args->{from} ) { # don't do it if passed an explicit 'from' param $args->{from} = $self->email->header_str('Sender'); - $self->email->header_str_set('Sender'); # remove Sender header + $self->email->header_str_set('Sender'); # remove Sender header } $self->SUPER::send_or_die($args); diff --git a/Koha/Encryption.pm b/Koha/Encryption.pm index faa7dbb3f8..b18f75a9d4 100644 --- a/Koha/Encryption.pm +++ b/Koha/Encryption.pm @@ -53,9 +53,9 @@ It's based on Crypt::CBC =cut sub new { - my ( $class ) = @_; + my ($class) = @_; my $encryption_key = C4::Context->config('encryption_key'); - if ( !$encryption_key || $encryption_key eq '__ENCRYPTION_KEY__') { + if ( !$encryption_key || $encryption_key eq '__ENCRYPTION_KEY__' ) { Koha::Exceptions::MissingParameter->throw( q{No encryption_key in koha-conf.xml. Please generate a key. We recommend one of at least 32 bytes. (You might use 'pwgen 32' to do so.)} ); diff --git a/Koha/Exception.pm b/Koha/Exception.pm index c420777cd2..f890ddada8 100644 --- a/Koha/Exception.pm +++ b/Koha/Exception.pm @@ -20,9 +20,7 @@ package Koha::Exception; use Modern::Perl; use Exception::Class ( - 'Koha::Exception' => { - description => "Something went wrong!" - }, + 'Koha::Exception' => { description => "Something went wrong!" }, ); sub full_message { @@ -30,7 +28,7 @@ sub full_message { # If a message was passed manually, use it return sprintf "Exception '%s' thrown '%s'\n", ref($self), $self->message - if $self->message; + if $self->message; my $field_hash = $self->field_hash; @@ -39,12 +37,12 @@ sub full_message { foreach my $key ( sort keys %$field_hash ) { push @fields, $key . " => " . $field_hash->{$key} - if defined $field_hash->{$key}; + if defined $field_hash->{$key}; } return - sprintf "Exception '%s' thrown '%s'" . ( @fields ? " with %s" : "" ) . "\n", - ref($self), $description, ( @fields ? join ', ', @fields : () ); + sprintf "Exception '%s' thrown '%s'" . ( @fields ? " with %s" : "" ) . "\n", + ref($self), $description, ( @fields ? join ', ', @fields : () ); } =head1 NAME diff --git a/Koha/Exceptions.pm b/Koha/Exceptions.pm index 0d5a1ac1ed..5166e7fb65 100644 --- a/Koha/Exceptions.pm +++ b/Koha/Exceptions.pm @@ -7,16 +7,16 @@ use Koha::Exception; use Exception::Class ( 'Koha::Exceptions::BadParameter' => { - isa => 'Koha::Exception', + isa => 'Koha::Exception', description => 'A bad parameter was given', - fields => ['parameter'], + fields => ['parameter'], }, 'Koha::Exceptions::DuplicateObject' => { - isa => 'Koha::Exception', + isa => 'Koha::Exception', description => 'Same object already exists', }, 'Koha::Exceptions::FileNotFound' => { - isa => 'Koha::Exception', + isa => 'Koha::Exception', description => 'File not found', fields => ['filename'], }, @@ -26,57 +26,57 @@ use Exception::Class ( fields => ['invalid_status'], }, 'Koha::Exceptions::ObjectNotFound' => { - isa => 'Koha::Exception', + isa => 'Koha::Exception', description => 'The required object doesn\'t exist', }, 'Koha::Exceptions::PayloadTooLarge' => { - isa => 'Koha::Exception', + isa => 'Koha::Exception', description => 'Request entity is larger than limits defined by server', }, 'Koha::Exceptions::ObjectNotCreated' => { - isa => 'Koha::Exception', + isa => 'Koha::Exception', description => 'The object have not been created', }, 'Koha::Exceptions::CannotDeleteDefault' => { - isa => 'Koha::Exception', + isa => 'Koha::Exception', description => 'The default value cannot be deleted' }, 'Koha::Exceptions::CannotDeleteSystem' => { - isa => 'Koha::Exception', + isa => 'Koha::Exception', description => 'The system value cannot be deleted' }, 'Koha::Exceptions::MissingParameter' => { - isa => 'Koha::Exception', + isa => 'Koha::Exception', description => 'A required parameter is missing', - fields => ['parameter'], + fields => ['parameter'], }, 'Koha::Exceptions::TooManyParameters' => { - isa => 'Koha::Exception', + isa => 'Koha::Exception', description => 'Too many parameters given', }, 'Koha::Exceptions::ParameterTooHigh' => { - isa => 'Koha::Exception', + isa => 'Koha::Exception', description => 'A passed parameter value is too high' }, 'Koha::Exceptions::NoChanges' => { - isa => 'Koha::Exception', + isa => 'Koha::Exception', description => 'No changes were made', }, 'Koha::Exceptions::WrongParameter' => { - isa => 'Koha::Exception', + isa => 'Koha::Exception', description => 'Parameter has wrong value or type', - fields => ['name', 'value', 'type'], + fields => [ 'name', 'value', 'type' ], }, 'Koha::Exceptions::NoPermission' => { - isa => 'Koha::Exception', + isa => 'Koha::Exception', description => 'You do not have permission for this action', }, 'Koha::Exceptions::CannotAddLibraryLimit' => { - isa => 'Koha::Exception', + isa => 'Koha::Exception', description => 'General problem adding a library limit' }, 'Koha::Exceptions::UnderMaintenance' => { - isa => 'Koha::Exception', + isa => 'Koha::Exception', description => 'Koha is under maintenance.' }, 'Koha::Exceptions::NoInteger' => { diff --git a/Koha/Exceptions/Authentication.pm b/Koha/Exceptions/Authentication.pm index 6bd83f48a0..155236729b 100644 --- a/Koha/Exceptions/Authentication.pm +++ b/Koha/Exceptions/Authentication.pm @@ -10,11 +10,11 @@ use Exception::Class ( isa => 'Koha::Exception', }, 'Koha::Exceptions::Authentication::Required' => { - isa => 'Koha::Exceptions::Authentication', + isa => 'Koha::Exceptions::Authentication', description => 'Authentication required' }, 'Koha::Exceptions::Authentication::SessionExpired' => { - isa => 'Koha::Exceptions::Authentication', + isa => 'Koha::Exceptions::Authentication', description => 'Session has been expired', }, diff --git a/Koha/Exceptions/Authorization.pm b/Koha/Exceptions/Authorization.pm index fde34bc178..f8332f6ea9 100644 --- a/Koha/Exceptions/Authorization.pm +++ b/Koha/Exceptions/Authorization.pm @@ -10,9 +10,9 @@ use Exception::Class ( isa => 'Koha::Exception', }, 'Koha::Exceptions::Authorization::Unauthorized' => { - isa => 'Koha::Exceptions::Authorization', + isa => 'Koha::Exceptions::Authorization', description => 'Unauthorized', - fields => ['required_permissions'] + fields => ['required_permissions'] }, ); diff --git a/Koha/Exceptions/BackgroundJob.pm b/Koha/Exceptions/BackgroundJob.pm index 65da5a3014..80c6ebc844 100644 --- a/Koha/Exceptions/BackgroundJob.pm +++ b/Koha/Exceptions/BackgroundJob.pm @@ -27,7 +27,7 @@ use Exception::Class ( 'Koha::Exceptions::BackgroundJob::InconsistentStatus' => { isa => 'Koha::Exceptions::BackgroundJob', description => 'Status change requested but an invalid status found', - fields => ['current_status', 'expected_status'] + fields => [ 'current_status', 'expected_status' ] }, 'Koha::Exceptions::BackgroundJob::StepOutOfBounds' => { isa => 'Koha::Exceptions::BackgroundJob', diff --git a/Koha/Exceptions/Checkouts/ReturnClaims.pm b/Koha/Exceptions/Checkouts/ReturnClaims.pm index d4d35b1711..213dfad5e5 100644 --- a/Koha/Exceptions/Checkouts/ReturnClaims.pm +++ b/Koha/Exceptions/Checkouts/ReturnClaims.pm @@ -21,7 +21,7 @@ use Koha::Exception; use Exception::Class ( 'Koha::Exceptions::Checkouts::ReturnClaims' => { - isa => 'Koha::Exception', + isa => 'Koha::Exception', }, 'Koha::Exceptions::Checkouts::ReturnClaims::NoCreatedBy' => { isa => 'Koha::Exceptions::Checkouts::ReturnClaims', diff --git a/Koha/Exceptions/ClubHold.pm b/Koha/Exceptions/ClubHold.pm index a7f0c2498c..927b007868 100644 --- a/Koha/Exceptions/ClubHold.pm +++ b/Koha/Exceptions/ClubHold.pm @@ -9,7 +9,7 @@ use Exception::Class ( isa => 'Koha::Exception', }, 'Koha::Exceptions::ClubHold::NoPatrons' => { - isa => 'Koha::Exceptions::ClubHold', + isa => 'Koha::Exceptions::ClubHold', description => "Cannot place a hold on a club without patrons.", }, ); diff --git a/Koha/Exceptions/Config.pm b/Koha/Exceptions/Config.pm index 06a85f4b64..c1cf2207f5 100644 --- a/Koha/Exceptions/Config.pm +++ b/Koha/Exceptions/Config.pm @@ -10,7 +10,7 @@ use Exception::Class ( isa => 'Koha::Exception', }, 'Koha::Exceptions::Config::MissingEntry' => { - isa => 'Koha::Exceptions::Config', + isa => 'Koha::Exceptions::Config', description => 'The required entry is missing in the configuration file' } ); diff --git a/Koha/Exceptions/Hold.pm b/Koha/Exceptions/Hold.pm index 38577b4126..fe06eb5c15 100644 --- a/Koha/Exceptions/Hold.pm +++ b/Koha/Exceptions/Hold.pm @@ -30,7 +30,7 @@ use Exception::Class ( 'Koha::Exceptions::Hold::CannotSuspendFound' => { isa => 'Koha::Exceptions::Hold', description => "Found holds cannot be suspended", - fields => ['status'] + fields => ['status'] }, 'Koha::Exceptions::Hold::InvalidPickupLocation' => { isa => 'Koha::Exceptions::Hold', @@ -47,9 +47,9 @@ sub full_message { my $msg = $self->message; - unless ( $msg) { + unless ($msg) { if ( $self->isa('Koha::Exceptions::Hold::CannotSuspendFound') ) { - $msg = sprintf("Found hold cannot be suspended. Status=%s", $self->status ); + $msg = sprintf( "Found hold cannot be suspended. Status=%s", $self->status ); } } diff --git a/Koha/Exceptions/Ill.pm b/Koha/Exceptions/Ill.pm index 34e3c62223..ebd17d876a 100644 --- a/Koha/Exceptions/Ill.pm +++ b/Koha/Exceptions/Ill.pm @@ -25,15 +25,15 @@ use Exception::Class ( isa => 'Koha::Exception', }, 'Koha::Exceptions::Ill::InvalidBackendId' => { - isa => 'Koha::Exceptions::Ill', + isa => 'Koha::Exceptions::Ill', description => "Invalid backend name required", }, 'Koha::Exceptions::Ill::NoTargetEmail' => { - isa => 'Koha::Exceptions::Ill', + isa => 'Koha::Exceptions::Ill', description => "ILL partner library has no email address configured", }, 'Koha::Exceptions::Ill::NoLibraryEmail' => { - isa => 'Koha::Exceptions::Ill', + isa => 'Koha::Exceptions::Ill', description => "Invalid backend name required", } ); diff --git a/Koha/Exceptions/Library.pm b/Koha/Exceptions/Library.pm index 9009254773..de679dd8fe 100644 --- a/Koha/Exceptions/Library.pm +++ b/Koha/Exceptions/Library.pm @@ -11,7 +11,7 @@ use Exception::Class ( }, 'Koha::Exceptions::Library::NotFound' => { - isa => 'Koha::Exceptions::Library::Exception', + isa => 'Koha::Exceptions::Library::Exception', description => 'Library not found', }, ); diff --git a/Koha/Exceptions/MarcOverlayRule.pm b/Koha/Exceptions/MarcOverlayRule.pm index 3b69916e4c..d2e44970af 100644 --- a/Koha/Exceptions/MarcOverlayRule.pm +++ b/Koha/Exceptions/MarcOverlayRule.pm @@ -25,11 +25,11 @@ use Exception::Class ( isa => 'Koha::Exception', }, 'Koha::Exceptions::MarcOverlayRule::InvalidTagRegExp' => { - isa => 'Koha::Exceptions::MarcOverlayRule', + isa => 'Koha::Exceptions::MarcOverlayRule', description => 'Invalid regular expression for tag' }, 'Koha::Exceptions::MarcOverlayRule::InvalidControlFieldActions' => { - isa => 'Koha::Exceptions::MarcOverlayRule', + isa => 'Koha::Exceptions::MarcOverlayRule', description => 'Invalid control field actions' } ); diff --git a/Koha/Exceptions/Metadata.pm b/Koha/Exceptions/Metadata.pm index 5cc494013b..40f335ffce 100644 --- a/Koha/Exceptions/Metadata.pm +++ b/Koha/Exceptions/Metadata.pm @@ -25,9 +25,9 @@ use Exception::Class ( isa => 'Koha::Exception', }, 'Koha::Exceptions::Metadata::Invalid' => { - isa => 'Koha::Exceptions::Metadata', + isa => 'Koha::Exceptions::Metadata', description => 'Invalid data', - fields => ['id', 'biblionumber', 'format', 'schema', 'decoding_error'] + fields => [ 'id', 'biblionumber', 'format', 'schema', 'decoding_error' ] } ); @@ -38,8 +38,10 @@ sub full_message { unless ($msg) { if ( $self->isa('Koha::Exceptions::Metadata::Invalid') ) { - $msg = sprintf( "Invalid data, cannot decode metadata object (biblio_metadata.id=%s, biblionumber=%s, format=%s, schema=%s, decoding_error='%s')", - $self->id, $self->biblionumber, $self->format, $self->schema, $self->decoding_error ); + $msg = sprintf( + "Invalid data, cannot decode metadata object (biblio_metadata.id=%s, biblionumber=%s, format=%s, schema=%s, decoding_error='%s')", + $self->id, $self->biblionumber, $self->format, $self->schema, $self->decoding_error + ); } } diff --git a/Koha/Exceptions/Object.pm b/Koha/Exceptions/Object.pm index 4181675826..d27e746b96 100644 --- a/Koha/Exceptions/Object.pm +++ b/Koha/Exceptions/Object.pm @@ -21,17 +21,17 @@ use Koha::Exception; use Exception::Class ( 'Koha::Exceptions::Object' => { - isa => 'Koha::Exception', + isa => 'Koha::Exception', }, 'Koha::Exceptions::Object::DuplicateID' => { isa => 'Koha::Exceptions::Object', description => "Duplicate ID passed", - fields => ['duplicate_id'] + fields => ['duplicate_id'] }, 'Koha::Exceptions::Object::FKConstraint' => { isa => 'Koha::Exceptions::Object', description => "Foreign key constraint broken", - fields => ['broken_fk', 'value'], + fields => [ 'broken_fk', 'value' ], }, 'Koha::Exceptions::Object::FKConstraintDeletion' => { isa => 'Koha::Exceptions::Object', @@ -39,31 +39,31 @@ use Exception::Class ( fields => [ 'column', 'fk', 'table', 'constraint' ], }, 'Koha::Exceptions::Object::MethodNotFound' => { - isa => 'Koha::Exceptions::Object', + isa => 'Koha::Exceptions::Object', description => "Invalid method", }, 'Koha::Exceptions::Object::PropertyNotFound' => { - isa => 'Koha::Exceptions::Object', + isa => 'Koha::Exceptions::Object', description => "Invalid property", }, 'Koha::Exceptions::Object::ReadOnlyProperty' => { - isa => 'Koha::Exceptions::Object', + isa => 'Koha::Exceptions::Object', description => "Change of readonly property attempted", - fields => [ 'property' ], + fields => ['property'], }, 'Koha::Exceptions::Object::MethodNotCoveredByTests' => { - isa => 'Koha::Exceptions::Object', + isa => 'Koha::Exceptions::Object', description => "Method not covered by tests", }, 'Koha::Exceptions::Object::BadValue' => { isa => 'Koha::Exceptions::Object', description => 'Invalid data passed', - fields => ['type', 'property', 'value'], + fields => [ 'type', 'property', 'value' ], }, 'Koha::Exceptions::Object::NotInstantiated' => { isa => 'Koha::Exceptions::Object', description => 'Tried to access a method on an uninstantiated object', - fields => ['class','method'] + fields => [ 'class', 'method' ] }, 'Koha::Exceptions::Object::NotInStorage' => { isa => 'Koha::Exceptions::Object', @@ -76,18 +76,19 @@ sub full_message { my $msg = $self->message; - unless ( $msg) { + unless ($msg) { if ( $self->isa('Koha::Exceptions::Object::FKConstraint') ) { - $msg = sprintf("Invalid parameter passed, %s=%s does not exist", $self->broken_fk, $self->value ); - } - elsif ( $self->isa('Koha::Exceptions::Object::BadValue') ) { - $msg = sprintf("Invalid value passed, %s=%s expected type is %s", $self->property, $self->value, $self->type ); - } - elsif ( $self->isa('Koha::Exceptions::Object::ReadOnlyProperty') ) { - $msg = sprintf("Invalid attempt to change readonly property: %s", $self->property ); - } - elsif ( $self->isa('Koha::Exceptions::Object::NotInstantiated') ) { - $msg = sprintf("Tried to access the '%s' method, but %s is not instantiated", $self->method, $self->class ); + $msg = sprintf( "Invalid parameter passed, %s=%s does not exist", $self->broken_fk, $self->value ); + } elsif ( $self->isa('Koha::Exceptions::Object::BadValue') ) { + $msg = sprintf( + "Invalid value passed, %s=%s expected type is %s", $self->property, $self->value, + $self->type + ); + } elsif ( $self->isa('Koha::Exceptions::Object::ReadOnlyProperty') ) { + $msg = sprintf( "Invalid attempt to change readonly property: %s", $self->property ); + } elsif ( $self->isa('Koha::Exceptions::Object::NotInstantiated') ) { + $msg = + sprintf( "Tried to access the '%s' method, but %s is not instantiated", $self->method, $self->class ); } } diff --git a/Koha/Exceptions/Password.pm b/Koha/Exceptions/Password.pm index 803e8a7243..b3d323f404 100644 --- a/Koha/Exceptions/Password.pm +++ b/Koha/Exceptions/Password.pm @@ -25,28 +25,28 @@ use Exception::Class ( isa => 'Koha::Exception', }, 'Koha::Exceptions::Password::Invalid' => { - isa => 'Koha::Exceptions::Password', + isa => 'Koha::Exceptions::Password', description => 'Invalid password' }, 'Koha::Exceptions::Password::TooShort' => { - isa => 'Koha::Exceptions::Password', + isa => 'Koha::Exceptions::Password', description => 'Password is too short', - fields => ['length','min_length'] + fields => [ 'length', 'min_length' ] }, 'Koha::Exceptions::Password::TooWeak' => { - isa => 'Koha::Exceptions::Password', + isa => 'Koha::Exceptions::Password', description => 'Password is too weak' }, 'Koha::Exceptions::Password::WhitespaceCharacters' => { - isa => 'Koha::Exceptions::Password', + isa => 'Koha::Exceptions::Password', description => 'Password contains leading/trailing whitespace character(s)' }, 'Koha::Exceptions::Password::Plugin' => { - isa => 'Koha::Exceptions::Password', + isa => 'Koha::Exceptions::Password', description => 'The password was rejected by a plugin' }, 'Koha::Exceptions::Password::NoCategoryProvided' => { - isa => 'Koha::Exceptions::Password', + isa => 'Koha::Exceptions::Password', description => 'You must provide a patron\'s category to validate password\'s strength and length' } ); @@ -56,9 +56,9 @@ sub full_message { my $msg = $self->message; - unless ( $msg) { + unless ($msg) { if ( $self->isa('Koha::Exceptions::Password::TooShort') ) { - $msg = sprintf("Password length (%s) is shorter than required (%s)", $self->length, $self->min_length ); + $msg = sprintf( "Password length (%s) is shorter than required (%s)", $self->length, $self->min_length ); } } diff --git a/Koha/Exceptions/Patron.pm b/Koha/Exceptions/Patron.pm index bc52bd8a1e..f775e99cd1 100644 --- a/Koha/Exceptions/Patron.pm +++ b/Koha/Exceptions/Patron.pm @@ -30,7 +30,7 @@ use Exception::Class ( 'Koha::Exceptions::Patron::InvalidUserid' => { isa => 'Koha::Exceptions::Patron', description => 'Field userid is not valid (probably not unique)', - fields => [ 'userid' ], + fields => ['userid'], }, 'Koha::Exceptions::Patron::MissingMandatoryExtendedAttribute' => { isa => 'Koha::Exceptions::Patron', @@ -38,7 +38,7 @@ use Exception::Class ( fields => ['type'] }, 'Koha::Exceptions::Patron::NotFound' => { - isa => 'Koha::Exceptions::Patron', + isa => 'Koha::Exceptions::Patron', description => "Patron not found" }, ); @@ -48,9 +48,9 @@ sub full_message { my $msg = $self->message; - unless ( $msg) { + unless ($msg) { if ( $self->isa('Koha::Exceptions::Patron::MissingMandatoryExtendedAttribute') ) { - $msg = sprintf("Missing mandatory extended attribute (type=%s)", $self->type ); + $msg = sprintf( "Missing mandatory extended attribute (type=%s)", $self->type ); } } diff --git a/Koha/Exceptions/Patron/Attribute/Type.pm b/Koha/Exceptions/Patron/Attribute/Type.pm index 2cb29f26b8..9decc8cfc5 100644 --- a/Koha/Exceptions/Patron/Attribute/Type.pm +++ b/Koha/Exceptions/Patron/Attribute/Type.pm @@ -10,9 +10,9 @@ use Exception::Class ( isa => 'Koha::Exception', }, 'Koha::Exceptions::Patron::Attribute::Type::CannotChangeProperty' => { - isa => 'Koha::Exceptions::Patron::Attribute::Type', + isa => 'Koha::Exceptions::Patron::Attribute::Type', description => "Cannot change property", - fields => ['property'], + fields => ['property'], }, ); @@ -21,9 +21,12 @@ sub full_message { my $msg = $self->message; - unless ( $msg) { + unless ($msg) { if ( $self->isa('Koha::Exceptions::Patron::Attribute::Type::CannotChangeProperty') ) { - $msg = sprintf("The property '%s' cannot be changed, some patron attributes are using it that way.", $self->property ); + $msg = sprintf( + "The property '%s' cannot be changed, some patron attributes are using it that way.", + $self->property + ); } } diff --git a/Koha/Exceptions/Patron/Category.pm b/Koha/Exceptions/Patron/Category.pm index 3eac4d2ba2..b1517884a3 100644 --- a/Koha/Exceptions/Patron/Category.pm +++ b/Koha/Exceptions/Patron/Category.pm @@ -18,11 +18,9 @@ package Koha::Exceptions::Patron::Category; use Modern::Perl; use Exception::Class ( - 'Koha::Exceptions::Patron::Category' => { - description => "Something went wrong!" - }, + 'Koha::Exceptions::Patron::Category' => { description => "Something went wrong!" }, 'Koha::Exceptions::Patron::Category::NotFound' => { - isa => 'Koha::Exceptions::Patron::Category', + isa => 'Koha::Exceptions::Patron::Category', description => "Patron category not found" }, ); diff --git a/Koha/Exceptions/Patron/MessagePreference.pm b/Koha/Exceptions/Patron/MessagePreference.pm index 02509c2222..9601721d35 100644 --- a/Koha/Exceptions/Patron/MessagePreference.pm +++ b/Koha/Exceptions/Patron/MessagePreference.pm @@ -19,58 +19,57 @@ use Modern::Perl; use Exception::Class ( - 'Koha::Exceptions::Patron::MessagePreference' => { - description => 'Something went wrong' - }, + 'Koha::Exceptions::Patron::MessagePreference' => { description => 'Something went wrong' }, 'Koha::Exceptions::Patron::MessagePreference::AttributeNotFound' => { - isa => 'Koha::Exceptions::Patron::MessagePreference', + isa => 'Koha::Exceptions::Patron::MessagePreference', description => "Message attribute not found", - fields => ['message_attribute_id'] + fields => ['message_attribute_id'] }, 'Koha::Exceptions::Patron::MessagePreference::DaysInAdvanceOutOfRange' => { - isa => 'Koha::Exceptions::Patron::MessagePreference', + isa => 'Koha::Exceptions::Patron::MessagePreference', description => "Days in advance is out of range", - fields => ['min','max', 'message_name'] + fields => [ 'min', 'max', 'message_name' ] }, 'Koha::Exceptions::Patron::MessagePreference::DaysInAdvanceNotAvailable' => { - isa => 'Koha::Exceptions::Patron::MessagePreference', + isa => 'Koha::Exceptions::Patron::MessagePreference', description => "Days in advance cannot be selected for this preference", - fields => ['message_name'] + fields => ['message_name'] }, 'Koha::Exceptions::Patron::MessagePreference::DigestNotAvailable' => { - isa => 'Koha::Exceptions::Patron::MessagePreference', + isa => 'Koha::Exceptions::Patron::MessagePreference', description => "Digest is not available for this message type", - fields => ['message_name'] + fields => ['message_name'] }, 'Koha::Exceptions::Patron::MessagePreference::DigestRequired' => { - isa => 'Koha::Exceptions::Patron::MessagePreference', + isa => 'Koha::Exceptions::Patron::MessagePreference', description => "Digest must be selected for this message type", - fields => ['message_name'] + fields => ['message_name'] }, 'Koha::Exceptions::Patron::MessagePreference::EmailAddressRequired' => { - isa => 'Koha::Exceptions::Patron::MessagePreference', + isa => 'Koha::Exceptions::Patron::MessagePreference', description => "Patron has no email address, cannot use email transport type.", - fields => ['message_name', 'borrowernumber' ] + fields => [ 'message_name', 'borrowernumber' ] }, 'Koha::Exceptions::Patron::MessagePreference::NoTransportType' => { - isa => 'Koha::Exceptions::Patron::MessagePreference', + isa => 'Koha::Exceptions::Patron::MessagePreference', description => "Transport type not available for this message.", - fields => ['message_name', 'transport_type'] + fields => [ 'message_name', 'transport_type' ] }, 'Koha::Exceptions::Patron::MessagePreference::PhoneNumberRequired' => { - isa => 'Koha::Exceptions::Patron::MessagePreference', + isa => 'Koha::Exceptions::Patron::MessagePreference', description => "Patron has no phone number, cannot use phone transport type.", - fields => ['message_name', 'borrowernumber' ] + fields => [ 'message_name', 'borrowernumber' ] }, 'Koha::Exceptions::Patron::MessagePreference::SMSNumberRequired' => { - isa => 'Koha::Exceptions::Patron::MessagePreference', + isa => 'Koha::Exceptions::Patron::MessagePreference', description => "Patron has no SMS number, cannot use sms transport type.", - fields => ['message_name', 'borrowernumber' ] + fields => [ 'message_name', 'borrowernumber' ] }, 'Koha::Exceptions::Patron::MessagePreference::TalkingTechItivaPhoneNotificationRequired' => { - isa => 'Koha::Exceptions::Patron::MessagePreference', - description => "System preference TalkingTechItivaPhoneNotification is disabled, cannot use itiva transport type.", - fields => ['message_name', 'borrowernumber' ] + isa => 'Koha::Exceptions::Patron::MessagePreference', + description => + "System preference TalkingTechItivaPhoneNotification is disabled, cannot use itiva transport type.", + fields => [ 'message_name', 'borrowernumber' ] }, ); diff --git a/Koha/Exceptions/Patron/MessagePreference/Transport.pm b/Koha/Exceptions/Patron/MessagePreference/Transport.pm index 7f6b61ef5a..3118640543 100644 --- a/Koha/Exceptions/Patron/MessagePreference/Transport.pm +++ b/Koha/Exceptions/Patron/MessagePreference/Transport.pm @@ -19,13 +19,11 @@ use Modern::Perl; use Exception::Class ( - 'Koha::Exceptions::Patron::MessagePreference::Transport' => { - description => 'Something went wrong' - }, + 'Koha::Exceptions::Patron::MessagePreference::Transport' => { description => 'Something went wrong' }, 'Koha::Exceptions::Patron::MessagePreference::Transport::TypeNotFound' => { - isa => 'Koha::Exceptions::Patron::MessagePreference::Transport', + isa => 'Koha::Exceptions::Patron::MessagePreference::Transport', description => "Transport type does not exist.", - fields => ['transport_type'] + fields => ['transport_type'] }, ); diff --git a/Koha/Exceptions/Patron/Modification.pm b/Koha/Exceptions/Patron/Modification.pm index 9dc9064ddb..3539fa15f5 100644 --- a/Koha/Exceptions/Patron/Modification.pm +++ b/Koha/Exceptions/Patron/Modification.pm @@ -10,11 +10,11 @@ use Exception::Class ( isa => 'Koha::Exception', }, 'Koha::Exceptions::Patron::Modification::DuplicateVerificationToken' => { - isa => 'Koha::Exceptions::Patron::Modification', + isa => 'Koha::Exceptions::Patron::Modification', description => "The verification token given already exists" }, 'Koha::Exceptions::Patron::Modification::InvalidData' => { - isa => 'Koha::Exceptions::Patron::Modification', + isa => 'Koha::Exceptions::Patron::Modification', description => "Some passed data is invalid" } ); diff --git a/Koha/Exceptions/Plugin.pm b/Koha/Exceptions/Plugin.pm index 2dd7e9b3b4..585e89cbbd 100644 --- a/Koha/Exceptions/Plugin.pm +++ b/Koha/Exceptions/Plugin.pm @@ -21,7 +21,7 @@ use Koha::Exception; use Exception::Class ( 'Koha::Exceptions::Plugin' => { - isa => 'Koha::Exception', + isa => 'Koha::Exception', }, 'Koha::Exceptions::Plugin::ForbiddenAction' => { isa => 'Koha::Exceptions::Plugin', @@ -30,7 +30,7 @@ use Exception::Class ( 'Koha::Exceptions::Plugin::MissingMethod' => { isa => 'Koha::Exceptions::Plugin', description => 'Required method is missing', - fields => ['plugin_name','method'] + fields => [ 'plugin_name', 'method' ] }, 'Koha::Exceptions::Plugin::InstallDied' => { isa => 'Koha::Exceptions::Plugin', @@ -49,15 +49,16 @@ sub full_message { my $msg = $self->message; - unless ( $msg) { + unless ($msg) { if ( $self->isa('Koha::Exceptions::Plugin::MissingMethod') ) { - $msg = sprintf("Cannot use plugin (%s) because the it doesn't implement the '%s' method which is required.", $self->plugin_name, $self->method ); - } - elsif ( $self->isa('Koha::Exceptions::Plugin::InstallDied') ) { - $msg = sprintf("Calling 'install' died for plugin %s", $self->plugin_class); - } - elsif ( $self->isa('Koha::Exceptions::Plugin::UpgradeDied') ) { - $msg = sprintf("Calling 'upgrade' died for plugin %s", $self->plugin_class); + $msg = sprintf( + "Cannot use plugin (%s) because the it doesn't implement the '%s' method which is required.", + $self->plugin_name, $self->method + ); + } elsif ( $self->isa('Koha::Exceptions::Plugin::InstallDied') ) { + $msg = sprintf( "Calling 'install' died for plugin %s", $self->plugin_class ); + } elsif ( $self->isa('Koha::Exceptions::Plugin::UpgradeDied') ) { + $msg = sprintf( "Calling 'upgrade' died for plugin %s", $self->plugin_class ); } } diff --git a/Koha/Exceptions/SysPref.pm b/Koha/Exceptions/SysPref.pm index 2ba89b8bee..a8ffb107e1 100644 --- a/Koha/Exceptions/SysPref.pm +++ b/Koha/Exceptions/SysPref.pm @@ -26,7 +26,7 @@ use Exception::Class ( 'Koha::Exceptions::SysPref::NotSet' => { isa => 'Koha::Exceptions::SysPref', description => 'Required syspref is not set', - fields => ['syspref'] + fields => ['syspref'] } ); diff --git a/Koha/Exceptions/Token.pm b/Koha/Exceptions/Token.pm index 92701ebae8..3c2d2fe9ab 100644 --- a/Koha/Exceptions/Token.pm +++ b/Koha/Exceptions/Token.pm @@ -24,11 +24,11 @@ use Exception::Class ( isa => 'Koha::Exception', }, 'Koha::Exceptions::Token::BadPattern' => { - isa => 'Koha::Exceptions::Token', + isa => 'Koha::Exceptions::Token', description => 'Bad pattern for random token generation' }, 'Koha::Exceptions::Token::WrongCSRFToken' => { - isa => 'Koha::Exceptions::Token', + isa => 'Koha::Exceptions::Token', description => 'Invalid CSRF Token' }, diff --git a/Koha/Exceptions/TransferLimit.pm b/Koha/Exceptions/TransferLimit.pm index 0b1e518f6e..a580ff1d81 100644 --- a/Koha/Exceptions/TransferLimit.pm +++ b/Koha/Exceptions/TransferLimit.pm @@ -26,7 +26,7 @@ use Exception::Class ( }, 'Koha::Exceptions::TransferLimit::Duplicate' => { - isa => 'Koha::Exceptions::TransferLimit::Exception', + isa => 'Koha::Exceptions::TransferLimit::Exception', description => 'A transfer limit with the given parameters already exists!', }, ); diff --git a/Koha/Exceptions/Virtualshelf.pm b/Koha/Exceptions/Virtualshelf.pm index c3d32133fb..a56fcdfa80 100644 --- a/Koha/Exceptions/Virtualshelf.pm +++ b/Koha/Exceptions/Virtualshelf.pm @@ -25,23 +25,23 @@ use Exception::Class ( isa => 'Koha::Exception', }, 'Koha::Exceptions::Virtualshelf::DuplicateObject' => { - isa => 'Koha::Exceptions::Virtualshelf', + isa => 'Koha::Exceptions::Virtualshelf', description => "Duplicate shelf object", }, 'Koha::Exceptions::Virtualshelf::InvalidInviteKey' => { - isa => 'Koha::Exceptions::Virtualshelf', + isa => 'Koha::Exceptions::Virtualshelf', description => 'Invalid key on accepting the share', }, 'Koha::Exceptions::Virtualshelf::InvalidKeyOnSharing' => { - isa => 'Koha::Exceptions::Virtualshelf', - description=> 'Invalid key on sharing a shelf', + isa => 'Koha::Exceptions::Virtualshelf', + description => 'Invalid key on sharing a shelf', }, 'Koha::Exceptions::Virtualshelf::ShareHasExpired' => { - isa => 'Koha::Exceptions::Virtualshelf', - description=> 'Cannot share this shelf, the share has expired', + isa => 'Koha::Exceptions::Virtualshelf', + description => 'Cannot share this shelf, the share has expired', }, 'Koha::Exceptions::Virtualshelf::UseDbAdminAccount' => { - isa => 'Koha::Exceptions::Virtualshelf', + isa => 'Koha::Exceptions::Virtualshelf', description => "Invalid use of database administrator account", } ); diff --git a/Koha/Exceptions/XSLT.pm b/Koha/Exceptions/XSLT.pm index c0addeef65..9b5cb20001 100644 --- a/Koha/Exceptions/XSLT.pm +++ b/Koha/Exceptions/XSLT.pm @@ -24,11 +24,11 @@ use Exception::Class ( isa => 'Koha::Exception', }, 'Koha::Exceptions::XSLT::MissingFilename' => { - isa => 'Koha::Exceptions::XSLT', + isa => 'Koha::Exceptions::XSLT', description => 'File name required', }, 'Koha::Exceptions::XSLT::FetchFailed' => { - isa => 'Koha::Exceptions::XSLT', + isa => 'Koha::Exceptions::XSLT', description => 'Fetching xslt file failed', }, ); diff --git a/Koha/Exporter/Record.pm b/Koha/Exporter/Record.pm index dd9d22293c..4d818e1614 100644 --- a/Koha/Exporter/Record.pm +++ b/Koha/Exporter/Record.pm @@ -27,10 +27,10 @@ sub _get_record_for_export { } elsif ( $record_type eq 'bibs' ) { $record = _get_biblio_for_export( { %$params, biblionumber => $record_id } ); } else { - Koha::Logger->get->warn( "Record_type $record_type not supported." ); + Koha::Logger->get->warn("Record_type $record_type not supported."); } if ( !$record ) { - Koha::Logger->get->warn( "Record $record_id could not be exported." ); + Koha::Logger->get->warn("Record $record_id could not be exported."); return; } @@ -51,32 +51,30 @@ sub _get_record_for_export { }, ); if ($conditions) { - foreach my $condition (@{$conditions}) { - my ($field_tag, $subfield, $operator, $match_value) = @{$condition}; - my @fields = $record->field($field_tag); + foreach my $condition ( @{$conditions} ) { + my ( $field_tag, $subfield, $operator, $match_value ) = @{$condition}; + my @fields = $record->field($field_tag); my $no_target = 0; - if (!@fields) { + if ( !@fields ) { $no_target = 1; - } - else { - if ($operator eq '?') { + } else { + if ( $operator eq '?' ) { return unless any { $subfield ? $_->subfield($subfield) : $_->data() } @fields; - } elsif ($operator eq '!?') { + } elsif ( $operator eq '!?' ) { return if any { $subfield ? $_->subfield($subfield) : $_->data() } @fields; } else { my $op; - if (exists $operators{$operator}) { + if ( exists $operators{$operator} ) { $op = $operators{$operator}; } else { die("Invalid operator: $op"); } - my @target_values = map { $subfield ? $_->subfield($subfield) : ($_->data()) } @fields; - if (!@target_values) { + my @target_values = map { $subfield ? $_->subfield($subfield) : ( $_->data() ) } @fields; + if ( !@target_values ) { $no_target = 1; - } - else { - return unless all { $op->($_, $match_value) } @target_values; + } else { + return unless all { $op->( $_, $match_value ) } @target_values; } } } @@ -108,8 +106,8 @@ sub _get_record_for_export { } sub _get_authority_for_export { - my ($params) = @_; - my $authid = $params->{authid} || return; + my ($params) = @_; + my $authid = $params->{authid} || return; my $authority = Koha::MetadataRecord::Authority->get_from_authid($authid); return unless $authority; return $authority->record; @@ -139,12 +137,12 @@ sub _get_biblio_for_export { record => $record, embed_items => 1, biblionumber => $biblionumber, - itemnumbers => $itemnumbers, + itemnumbers => $itemnumbers, } ); - if ($only_export_items_for_branches && @$only_export_items_for_branches) { + if ( $only_export_items_for_branches && @$only_export_items_for_branches ) { my %export_items_for_branches = map { $_ => 1 } @$only_export_items_for_branches; - my ( $homebranchfield, $homebranchsubfield ) = GetMarcFromKohaField( 'items.homebranch' ); + my ( $homebranchfield, $homebranchsubfield ) = GetMarcFromKohaField('items.homebranch'); for my $itemfield ( $record->field($homebranchfield) ) { my $homebranch = $itemfield->subfield($homebranchsubfield); @@ -169,14 +167,14 @@ sub export { my $csv_profile_id = $params->{csv_profile_id}; my $output_filepath = $params->{output_filepath}; - if( !$record_type ) { - Koha::Logger->get->warn( "No record_type given." ); + if ( !$record_type ) { + Koha::Logger->get->warn("No record_type given."); return; } return unless @$record_ids; my $fh; - if ( $output_filepath ) { + if ($output_filepath) { open $fh, '>', $output_filepath or die "Cannot open file $output_filepath ($!)"; select $fh; binmode $fh, ':encoding(UTF-8)' unless $format eq 'csv'; @@ -190,17 +188,17 @@ sub export { next unless $record; my $errorcount_on_decode = eval { scalar( MARC::File::USMARC->decode( $record->as_usmarc )->warnings() ) }; if ( $errorcount_on_decode or $@ ) { - my $msg = "Record $record_id could not be exported. " . - ( $@ // '' ); + my $msg = "Record $record_id could not be exported. " . ( $@ // '' ); chomp $msg; - Koha::Logger->get->info( $msg ); + Koha::Logger->get->info($msg); next; } print $record->as_usmarc(); } } elsif ( $format eq 'xml' ) { my $marcflavour = C4::Context->preference("marcflavour"); - MARC::File::XML->default_record_format( ( $marcflavour eq 'UNIMARC' && $record_type eq 'auths' ) ? 'UNIMARCAUTH' : $marcflavour ); + MARC::File::XML->default_record_format( + ( $marcflavour eq 'UNIMARC' && $record_type eq 'auths' ) ? 'UNIMARCAUTH' : $marcflavour ); print MARC::File::XML::header(); print "\n"; @@ -214,7 +212,7 @@ sub export { print "\n"; } elsif ( $format eq 'csv' ) { die 'There is no valid csv profile defined for this export' - unless Koha::CsvProfiles->find( $csv_profile_id ); + unless Koha::CsvProfiles->find($csv_profile_id); print marc2csv( $record_ids, $csv_profile_id, $itemnumbers ); } diff --git a/Koha/ExternalContent.pm b/Koha/ExternalContent.pm index be5174d32e..46cae690a0 100644 --- a/Koha/ExternalContent.pm +++ b/Koha/ExternalContent.pm @@ -49,12 +49,12 @@ common methods for getting Koha patron. =cut sub agent_string { - return 'Koha/'.Koha::version(); + return 'Koha/' . Koha::version(); } sub new { - my $class = shift; - my $params = shift || {}; + my $class = shift; + my $params = shift || {}; $params->{logger} = Koha::Logger->get(); @@ -62,37 +62,37 @@ sub new { } sub _koha_session { - my $self = shift; + my $self = shift; my $session_id = $self->koha_session_id or return; return C4::Auth::get_session($session_id); } sub get_from_koha_session { - my $self = shift; - my $key = shift or croak "No key"; + my $self = shift; + my $key = shift or croak "No key"; my $session = $self->_koha_session or return; return $session->param($key); } sub set_in_koha_session { - my $self = shift; - my $key = shift or croak "No key"; - my $value = shift; + my $self = shift; + my $key = shift or croak "No key"; + my $value = shift; my $session = $self->_koha_session or croak "No Koha session"; - return $session->param($key, $value); + return $session->param( $key, $value ); } sub koha_patron { my $self = shift; - if (my $patron = $self->_koha_patron_accessor) { + if ( my $patron = $self->_koha_patron_accessor ) { return $patron; } my $id = $self->get_from_koha_session('number') - or return; + or return; my $patron = Koha::Patrons->find($id) - or die "Invalid patron number in session"; + or die "Invalid patron number in session"; return $self->_koha_patron_accessor($patron); } diff --git a/Koha/ExternalContent/OverDrive.pm b/Koha/ExternalContent/OverDrive.pm index bf355a2d4a..bc956a71c8 100644 --- a/Koha/ExternalContent/OverDrive.pm +++ b/Koha/ExternalContent/OverDrive.pm @@ -53,22 +53,24 @@ sub new { $params->{koha_session_id} or croak "No koha_session_id"; my $self = $class->SUPER::new($params); - unless ($params->{client}) { - my $client_key = C4::Context->preference('OverDriveClientKey') - or croak("OverDriveClientKey pref not set"); - my $client_secret = C4::Context->preference('OverDriveClientSecret') - or croak("OverDriveClientSecret pref not set"); - my $library_id = C4::Context->preference('OverDriveLibraryID') - or croak("OverDriveLibraryID pref not set"); - my ($token, $token_type) = $self->get_token_from_koha_session(); - $self->client( WebService::ILS::OverDrive::Patron->new( - client_id => $client_key, - client_secret => $client_secret, - library_id => $library_id, - access_token => $token, - access_token_type => $token_type, - user_agent_params => { agent => $class->agent_string } - ) ); + unless ( $params->{client} ) { + my $client_key = C4::Context->preference('OverDriveClientKey') + or croak("OverDriveClientKey pref not set"); + my $client_secret = C4::Context->preference('OverDriveClientSecret') + or croak("OverDriveClientSecret pref not set"); + my $library_id = C4::Context->preference('OverDriveLibraryID') + or croak("OverDriveLibraryID pref not set"); + my ( $token, $token_type ) = $self->get_token_from_koha_session(); + $self->client( + WebService::ILS::OverDrive::Patron->new( + client_id => $client_key, + client_secret => $client_secret, + library_id => $library_id, + access_token => $token, + access_token_type => $token_type, + user_agent_params => { agent => $class->agent_string } + ) + ); } return $self; @@ -111,10 +113,10 @@ Methods with slightly moded interfaces: =cut sub auth_url { - my $self = shift; + my $self = shift; my $page_url = shift or croak "Page url not provided"; - my ($return_url, $page) = $self->_return_url($page_url); + my ( $return_url, $page ) = $self->_return_url($page_url); $self->set_return_page_in_koha_session($page); return $self->client->auth_url($return_url); } @@ -126,17 +128,17 @@ sub auth_url { =cut sub auth_by_code { - my $self = shift; - my $code = shift or croak "OverDrive auth code not provided"; + my $self = shift; + my $code = shift or croak "OverDrive auth code not provided"; my $base_url = shift or croak "App base url not provided"; - my ($access_token, $access_token_type, $auth_token) - = $self->client->auth_by_code($code, $self->_return_url($base_url)); + my ( $access_token, $access_token_type, $auth_token ) = + $self->client->auth_by_code( $code, $self->_return_url($base_url) ); $access_token or die "Invalid OverDrive code returned"; - $self->set_token_in_koha_session($access_token, $access_token_type); + $self->set_token_in_koha_session( $access_token, $access_token_type ); - if (my $koha_patron = $self->koha_patron) { - $koha_patron->set({overdrive_auth_token => $auth_token})->store; + if ( my $koha_patron = $self->koha_patron ) { + $koha_patron->set( { overdrive_auth_token => $auth_token } )->store; } return $self->get_return_page_from_koha_session; } @@ -149,42 +151,45 @@ sub auth_by_code { =cut sub auth_by_userid { - my $self = shift; - my $userid = shift or croak "No user provided"; + my $self = shift; + my $userid = shift or croak "No user provided"; my $password = shift; - croak "No password provided" unless ($password || !C4::Context->preference("OverDrivePasswordRequired")); - my $website_id = shift or croak "OverDrive Library ID not provided"; + croak "No password provided" unless ( $password || !C4::Context->preference("OverDrivePasswordRequired") ); + my $website_id = shift or croak "OverDrive Library ID not provided"; my $authorization_name = shift or croak "OverDrive Authname not provided"; - my ($access_token, $access_token_type, $auth_token) - = $self->client->auth_by_user_id($userid, $password, $website_id, $authorization_name); + my ( $access_token, $access_token_type, $auth_token ) = + $self->client->auth_by_user_id( $userid, $password, $website_id, $authorization_name ); $access_token or die "Invalid OverDrive code returned"; - $self->set_token_in_koha_session($access_token, $access_token_type); + $self->set_token_in_koha_session( $access_token, $access_token_type ); - $self->koha_patron->set({overdrive_auth_token => $auth_token})->store; + $self->koha_patron->set( { overdrive_auth_token => $auth_token } )->store; return $self->get_return_page_from_koha_session; } use constant AUTH_RETURN_HANDLER => "/cgi-bin/koha/external/overdrive/auth.pl"; + sub _return_url { - my $self = shift; + my $self = shift; my $page_url = shift or croak "Page url not provided"; - my ($base_url, $page) = ($page_url =~ m!^(https?://[^/]+)(.*)!); - my $return_url = $base_url.AUTH_RETURN_HANDLER; + my ( $base_url, $page ) = ( $page_url =~ m!^(https?://[^/]+)(.*)! ); + my $return_url = $base_url . AUTH_RETURN_HANDLER; - return wantarray ? ($return_url, $page) : $return_url; + return wantarray ? ( $return_url, $page ) : $return_url; } use constant RETURN_PAGE_SESSION_KEY => "overdrive.return_page"; + sub get_return_page_from_koha_session { - my $self = shift; + my $self = shift; my $return_page = $self->get_from_koha_session(RETURN_PAGE_SESSION_KEY) || ""; $self->logger->debug("get_return_page_from_koha_session: $return_page"); return $return_page; } + sub set_return_page_in_koha_session { - my $self = shift; + my $self = shift; my $return_page = shift || ""; $self->logger->debug("set_return_page_in_koha_session: $return_page"); return $self->set_in_koha_session( RETURN_PAGE_SESSION_KEY, $return_page ); @@ -192,21 +197,23 @@ sub set_return_page_in_koha_session { use constant ACCESS_TOKEN_SESSION_KEY => "overdrive.access_token"; my $ACCESS_TOKEN_DELIMITER = ":"; + sub get_token_from_koha_session { my $self = shift; - my ($token, $token_type) - = split $ACCESS_TOKEN_DELIMITER, $self->get_from_koha_session(ACCESS_TOKEN_SESSION_KEY) || ""; - $self->logger->debug("get_token_from_koha_session: ".($token || "(none)")); - return ($token, $token_type); + my ( $token, $token_type ) = split $ACCESS_TOKEN_DELIMITER, + $self->get_from_koha_session(ACCESS_TOKEN_SESSION_KEY) || ""; + $self->logger->debug( "get_token_from_koha_session: " . ( $token || "(none)" ) ); + return ( $token, $token_type ); } + sub set_token_in_koha_session { - my $self = shift; - my $token = shift || ""; + my $self = shift; + my $token = shift || ""; my $token_type = shift || ""; $self->logger->debug("set_token_in_koha_session: $token $token_type"); return $self->set_in_koha_session( ACCESS_TOKEN_SESSION_KEY, - join($ACCESS_TOKEN_DELIMITER, $token, $token_type) + join( $ACCESS_TOKEN_DELIMITER, $token, $token_type ) ); } @@ -219,16 +226,16 @@ sub set_token_in_koha_session { =cut sub checkout_download_url { - my $self = shift; + my $self = shift; my $item_id = shift or croak "Item ID not specified"; my $ua = LWP::UserAgent->new; $ua->max_redirect(0); - $ua->agent( 'Koha/'.Koha::version() ); + $ua->agent( 'Koha/' . Koha::version() ); my $response = $ua->get( - "https://patron.api.overdrive.com/v1/patrons/me/checkouts/".$item_id."/formats/downloadredirect", - 'Authorization' => "Bearer ".$self->client->access_token, - ); + "https://patron.api.overdrive.com/v1/patrons/me/checkouts/" . $item_id . "/formats/downloadredirect", + 'Authorization' => "Bearer " . $self->client->access_token, + ); my $redirect = { redirect => $response->{_headers}->{location} }; return $redirect; @@ -244,7 +251,7 @@ sub checkout_download_url { sub is_logged_in { my $self = shift; - my ($token, $token_type) = $self->get_token_from_koha_session(); + my ( $token, $token_type ) = $self->get_token_from_koha_session(); $token ||= $self->auth_by_saved_token; return $token; } @@ -254,11 +261,10 @@ sub auth_by_saved_token { my $koha_patron = $self->koha_patron or return; - if (my $auth_token = $koha_patron->overdrive_auth_token) { - my ($access_token, $access_token_type, $new_auth_token) - = $self->client->make_access_token_request(); - $self->set_token_in_koha_session($access_token, $access_token_type); - $koha_patron->set({overdrive_auth_token => $new_auth_token})->store; + if ( my $auth_token = $koha_patron->overdrive_auth_token ) { + my ( $access_token, $access_token_type, $new_auth_token ) = $self->client->make_access_token_request(); + $self->set_token_in_koha_session( $access_token, $access_token_type ); + $koha_patron->set( { overdrive_auth_token => $new_auth_token } )->store; return $access_token; } @@ -274,16 +280,17 @@ sub auth_by_saved_token { sub forget { my $self = shift; - $self->set_token_in_koha_session("", ""); - if (my $koha_patron = $self->koha_patron) { - $koha_patron->set({overdrive_auth_token => undef})->store; + $self->set_token_in_koha_session( "", "" ); + if ( my $koha_patron = $self->koha_patron ) { + $koha_patron->set( { overdrive_auth_token => undef } )->store; } } use vars qw{$AUTOLOAD}; + sub AUTOLOAD { my $self = shift; - (my $method = $AUTOLOAD) =~ s/.*:://; + ( my $method = $AUTOLOAD ) =~ s/.*:://; my $od = $self->client; local $@; my $ret = eval { $od->$method(@_) }; diff --git a/Koha/Filter/MARC/EmbedItemsAvailability.pm b/Koha/Filter/MARC/EmbedItemsAvailability.pm index 2e8a6c0e84..e5486edcf7 100644 --- a/Koha/Filter/MARC/EmbedItemsAvailability.pm +++ b/Koha/Filter/MARC/EmbedItemsAvailability.pm @@ -48,19 +48,19 @@ Embed not on loan items count into the specified record(s) and return the result =cut sub filter { - my $self = shift; + my $self = shift; my $record = shift; my $newrecord; return unless defined $record; - if (ref $record eq 'ARRAY') { + if ( ref $record eq 'ARRAY' ) { my @recarray; foreach my $thisrec (@$record) { push @recarray, _processrecord($thisrec); } $newrecord = \@recarray; - } elsif (ref $record eq 'MARC::Record') { + } elsif ( ref $record eq 'MARC::Record' ) { $newrecord = _processrecord($record); } @@ -71,23 +71,27 @@ sub _processrecord { my $record = shift; - my ($biblionumber_field, $biblionumber_subfield) = GetMarcFromKohaField( "biblio.biblionumber" ); - my $biblionumber = ( $biblionumber_field > 9 ) - ? $record->field($biblionumber_field)->subfield($biblionumber_subfield) - : $record->field($biblionumber_field)->data(); + my ( $biblionumber_field, $biblionumber_subfield ) = GetMarcFromKohaField("biblio.biblionumber"); + my $biblionumber = + ( $biblionumber_field > 9 ) + ? $record->field($biblionumber_field)->subfield($biblionumber_subfield) + : $record->field($biblionumber_field)->data(); - my $not_onloan_items = Koha::Items->search({ - biblionumber => $biblionumber, - onloan => undef, - })->count; + my $not_onloan_items = Koha::Items->search( + { + biblionumber => $biblionumber, + onloan => undef, + } + )->count; # check for field 999 my $destination_field = $record->field('999'); - if (defined $destination_field) { + if ( defined $destination_field ) { + # we have a field, add what we need $destination_field->update( x => $not_onloan_items ); - } - else { + } else { + # no field, create one $destination_field = MARC::Field->new( '999', '', '', x => $not_onloan_items ); $record->append_fields($destination_field); diff --git a/Koha/Filter/MARC/EmbedSeeFromHeadings.pm b/Koha/Filter/MARC/EmbedSeeFromHeadings.pm index 4933b88745..2dac9aeb03 100644 --- a/Koha/Filter/MARC/EmbedSeeFromHeadings.pm +++ b/Koha/Filter/MARC/EmbedSeeFromHeadings.pm @@ -48,20 +48,21 @@ In order to differentiate added headings from actual headings, a 'z' is put in the first indicator. =cut + sub filter { - my $self = shift; + my $self = shift; my $record = shift; my $newrecord; return unless defined $record; - if (ref $record eq 'ARRAY') { + if ( ref $record eq 'ARRAY' ) { my @recarray; foreach my $thisrec (@$record) { push @recarray, $self->_processrecord($thisrec); } $newrecord = \@recarray; - } elsif (ref $record eq 'MARC::Record') { + } elsif ( ref $record eq 'MARC::Record' ) { $newrecord = $self->_processrecord($record); } @@ -69,9 +70,9 @@ sub filter { } sub _processrecord { - my ($self, $record) = @_; + my ( $self, $record ) = @_; - $record->append_fields($self->fields($record)); + $record->append_fields( $self->fields($record) ); return $record; } @@ -85,6 +86,7 @@ Used during Elasticsearch indexing to give special treatment to these field (i.e include in facets, sorting, or suggestion fields) =cut + sub fields { my ( $self, $record ) = @_; diff --git a/Koha/Filter/MARC/ExpandCodedFields.pm b/Koha/Filter/MARC/ExpandCodedFields.pm index 909d908e01..3c0d7b0cce 100644 --- a/Koha/Filter/MARC/ExpandCodedFields.pm +++ b/Koha/Filter/MARC/ExpandCodedFields.pm @@ -86,10 +86,10 @@ sub filter { if ( !( $tag eq '942' && $subfield->[0] eq 'n' ) || $marcflavour eq 'UNIMARC' ) { - $value = - GetAuthorisedValueDesc( $tag, $letter, $value, '', - $coded_fields, undef, $opac ) - if $coded_fields->{$tag}->{$letter}; + $value = GetAuthorisedValueDesc( + $tag, $letter, $value, '', + $coded_fields, undef, $opac + ) if $coded_fields->{$tag}->{$letter}; } push( @new_subfields, $letter, $value ); } @@ -115,16 +115,16 @@ sub _getCodedFields { return $cached if $cached; my $coded_fields = {}; - my @fields = Koha::MarcSubfieldStructures->search( - { - frameworkcode => $frameworkcode, - authorised_value => { '>' => '' } - }, - { - columns => [ 'tagfield', 'tagsubfield', 'authorised_value' ], - order_by => [ 'tagfield', 'tagsubfield' ] - } - )->as_list; + my @fields = Koha::MarcSubfieldStructures->search( + { + frameworkcode => $frameworkcode, + authorised_value => { '>' => '' } + }, + { + columns => [ 'tagfield', 'tagsubfield', 'authorised_value' ], + order_by => [ 'tagfield', 'tagsubfield' ] + } + )->as_list; for my $field (@fields) { $coded_fields->{ $field->tagfield }->{ $field->tagsubfield }->{'authorised_value'} = $field->authorised_value; } diff --git a/Koha/Filter/MARC/Null.pm b/Koha/Filter/MARC/Null.pm index d504fe41da..8aa94327f6 100644 --- a/Koha/Filter/MARC/Null.pm +++ b/Koha/Filter/MARC/Null.pm @@ -45,8 +45,9 @@ our $NAME = 'Null'; Return the original record. =cut + sub filter { - my $self = shift; + my $self = shift; my $record = shift; return $record; diff --git a/Koha/Filter/MARC/ViewPolicy.pm b/Koha/Filter/MARC/ViewPolicy.pm index 0523b1bc51..389046497e 100644 --- a/Koha/Filter/MARC/ViewPolicy.pm +++ b/Koha/Filter/MARC/ViewPolicy.pm @@ -72,18 +72,17 @@ sub filter { if ( ref($precord) eq 'ARRAY' ) { @records = @{$precord}; - } - else { + } else { push @records, $precord; } - my $params = $self->params; - my $interface = $params->{options}->{interface} // 'opac'; + my $params = $self->params; + my $interface = $params->{options}->{interface} // 'opac'; my $frameworkcode = $params->{options}->{frameworkcode} // q{}; foreach my $current_record (@records) { - my $result = $current_record; - my $hide = _should_hide_on_interface(); + my $result = $current_record; + my $hide = _should_hide_on_interface(); my $marcsubfieldstructure = C4::Biblio::GetMarcStructure( 0, $frameworkcode, { unsafe => 1 } ); @@ -124,7 +123,7 @@ sub _filter_field { # visibility is a "level" (-9 to +9), default to 0 # -8 is flagged, and 9/-9 are not implemented. my $visibility = - $marcsubfieldstructure->{$tag}->{$subtag}->{hidden}; + $marcsubfieldstructure->{$tag}->{$subtag}->{hidden}; $visibility //= 0; if ( $hide->{$interface}->{$visibility} ) { @@ -132,8 +131,7 @@ sub _filter_field { # this detects that case to delete the field. if ( scalar $field->subfields() <= 1 ) { $result->delete_fields($field); - } - else { + } else { $field->delete_subfield( code => $subtag ); } } @@ -253,8 +251,7 @@ sub should_hide_marc { my $shouldhide = $hide->{$interface}->{$hidden}; if ($shouldhide) { $shouldhidemarc{$field} = 1; - } - elsif ( !exists $shouldhidemarc{$field} ) { + } elsif ( !exists $shouldhidemarc{$field} ) { $shouldhidemarc{$field} = 0; } } diff --git a/Koha/FrameworkPlugin.pm b/Koha/FrameworkPlugin.pm index dab6c4f471..842e660233 100644 --- a/Koha/FrameworkPlugin.pm +++ b/Koha/FrameworkPlugin.pm @@ -117,9 +117,11 @@ use base qw(Class::Accessor); use C4::Context; -__PACKAGE__->mk_ro_accessors( qw| - name path errstr javascript noclick -|); +__PACKAGE__->mk_ro_accessors( + qw| + name path errstr javascript noclick + | +); =head2 new @@ -135,19 +137,18 @@ __PACKAGE__->mk_ro_accessors( qw| sub new { my ( $class, $params ) = @_; my $self = $class->SUPER::new(); - if( ref($params) eq 'HASH' ) { - foreach( 'name', 'path', 'item_style' ) { + if ( ref($params) eq 'HASH' ) { + foreach ( 'name', 'path', 'item_style' ) { $self->{$_} = $params->{$_}; } - } - elsif( !ref($params) && $params ) { # use it as plugin name + } elsif ( !ref($params) && $params ) { # use it as plugin name $self->{name} = $params; - if( $params =~ /^(.*)\/([^\/]+)$/ ) { + if ( $params =~ /^(.*)\/([^\/]+)$/ ) { $self->{name} = $2; $self->{path} = $1; } } - $self->_error( 'Plugin needs a name' ) if !$self->{name}; + $self->_error('Plugin needs a name') if !$self->{name}; return $self; } @@ -169,12 +170,12 @@ sub new { sub build { my ( $self, $params ) = @_; - return if $self->{errstr}; - return 1 if exists $self->{html}; # no rebuild + return if $self->{errstr}; + return 1 if exists $self->{html}; # no rebuild $self->_load if !$self->{_loaded}; - return if $self->{errstr}; # load had error - return $self->_generate_js( $params ); + return if $self->{errstr}; # load had error + return $self->_generate_js($params); } =head2 launch @@ -191,81 +192,85 @@ sub launch { return if $self->{errstr}; $self->_load if !$self->{_loaded}; - return if $self->{errstr}; # load had error - return 1 if !exists $self->{launcher}; #just ignore this request - if( defined( &{$self->{launcher}} ) ) { - my $arg= $self->{oldschool}? $params->{cgi}: $params; - return &{$self->{launcher}}( $arg ); + return if $self->{errstr}; # load had error + return 1 if !exists $self->{launcher}; #just ignore this request + if ( defined( &{ $self->{launcher} } ) ) { + my $arg = $self->{oldschool} ? $params->{cgi} : $params; + return &{ $self->{launcher} }($arg); } - return $self->_error( 'No launcher sub defined' ); + return $self->_error('No launcher sub defined'); } # ************** INTERNAL ROUTINES ******************************************** sub _error { my ( $self, $info ) = @_; - $self->{errstr} = 'ERROR: Plugin '. ( $self->{name}//'' ). ': '. $info; - return; #always return false + $self->{errstr} = 'ERROR: Plugin ' . ( $self->{name} // '' ) . ': ' . $info; + return; #always return false } sub _load { - my ( $self ) = @_; + my ($self) = @_; my ( $rv, $file ); - return $self->_error( 'Plugin needs a name' ) if !$self->{name}; #2chk + return $self->_error('Plugin needs a name') if !$self->{name}; #2chk $self->{path} //= _valuebuilderpath(); + #NOTE: Resolve symlinks and relative path components if present, #so the base will compare correctly lower down my $abs_base_path = Cwd::abs_path( $self->{path} ); - $file= $self->{path}. '/'. $self->{name}; + $file = $self->{path} . '/' . $self->{name}; + #NOTE: Resolve relative path components to prevent loading files outside the base path my $abs_file_path = Cwd::abs_path($file); if ( $abs_file_path !~ /^\Q$abs_base_path\E/ ) { warn "Attempt to load $file ($abs_file_path) in framework plugin!"; return $self->_error('File not found'); } - return $self->_error( 'File not found' ) if !-e $file; + return $self->_error('File not found') if !-e $file; # undefine oldschool subroutines before defining them again undef &plugin_parameters; undef &plugin_javascript; undef &plugin; - $rv = do( $file ); - return $self->_error( $@ ) if $@; + $rv = do($file); + return $self->_error($@) if $@; - my $type = ref( $rv ); - if( $type eq 'HASH' ) { # new style + my $type = ref($rv); + if ( $type eq 'HASH' ) { # new style $self->{oldschool} = 0; - if( exists $rv->{builder} && ref($rv->{builder}) eq 'CODE' ) { + if ( exists $rv->{builder} && ref( $rv->{builder} ) eq 'CODE' ) { $self->{builder} = $rv->{builder}; - } elsif( exists $rv->{builder} ) { - return $self->_error( 'Builder sub is no coderef' ); + } elsif ( exists $rv->{builder} ) { + return $self->_error('Builder sub is no coderef'); } - if( exists $rv->{launcher} && ref($rv->{launcher}) eq 'CODE' ) { + if ( exists $rv->{launcher} && ref( $rv->{launcher} ) eq 'CODE' ) { $self->{launcher} = $rv->{launcher}; - } elsif( exists $rv->{launcher} ) { - return $self->_error( 'Launcher sub is no coderef' ); + } elsif ( exists $rv->{launcher} ) { + return $self->_error('Launcher sub is no coderef'); } - } else { # old school + } else { # old school $self->{oldschool} = 1; - if( defined(&plugin_javascript) ) { + if ( defined(&plugin_javascript) ) { $self->{builder} = \&plugin_javascript; } - if( defined(&plugin) ) { + if ( defined(&plugin) ) { $self->{launcher} = \&plugin; } } - if( !$self->{builder} && !$self->{launcher} ) { - return $self->_error( 'Plugin does not contain builder nor launcher' ); + if ( !$self->{builder} && !$self->{launcher} ) { + return $self->_error('Plugin does not contain builder nor launcher'); } - $self->{_loaded} = $self->{oldschool}? 0: 1; - # old style needs reload due to possible sub redefinition + $self->{_loaded} = $self->{oldschool} ? 0 : 1; + + # old style needs reload due to possible sub redefinition return 1; } sub _valuebuilderpath { return C4::Context->config('intranetdir') . "/cataloguing/value_builder"; + #Formerly, intranetdir/cgi-bin was tested first. #But the intranetdir from koha-conf already includes cgi-bin for #package installs, single and standard installs. @@ -276,28 +281,32 @@ sub _generate_js { my $sub = $self->{builder}; return 1 if !$sub; - #it is safe to assume here that we do have a launcher - #we assume that it is launched in an unorthodox fashion - #just useless to build, but no problem - if( !defined(&$sub) ) { # 2chk: if there is something, it should be code - return $self->_error( 'Builder sub not defined' ); + #it is safe to assume here that we do have a launcher + #we assume that it is launched in an unorthodox fashion + #just useless to build, but no problem + + if ( !defined(&$sub) ) { # 2chk: if there is something, it should be code + return $self->_error('Builder sub not defined'); } - my @params = $self->{oldschool}//0 ? - ( $params->{dbh}, $params->{record}, $params->{tagslib}, - $params->{id} ): - ( $params ); - my @rv = &$sub( @params ); + my @params = $self->{oldschool} // 0 + ? ( + $params->{dbh}, $params->{record}, $params->{tagslib}, + $params->{id} + ) + : ($params); + my @rv = &$sub(@params); return $self->_error( 'Builder sub failed: ' . $@ ) if $@; - my $arg= $self->{oldschool}? pop @rv: shift @rv; - #oldschool returns functionname and script; we only use the latter - if( $arg && $arg=~/^\s*\'; + return $self->_tag( 'script', $attributes ) . ''; } =head2 css @@ -108,11 +108,11 @@ sub css { return; } - $attributes->{rel} = 'stylesheet'; + $attributes->{rel} = 'stylesheet'; $attributes->{type} = 'text/css'; $attributes->{href} = $url; - return $self->_tag('link', $attributes); + return $self->_tag( 'link', $attributes ); } =head2 url @@ -126,14 +126,14 @@ Returns the URL for the given file sub url { my ( $self, $filename ) = @_; - my $stash = $self->{_CONTEXT}->stash(); + my $stash = $self->{_CONTEXT}->stash(); my $interface = $stash->get('interface'); - my $theme = $stash->get('theme'); + my $theme = $stash->get('theme'); my $configkey = $interface =~ /opac/ ? 'opachtdocs' : 'intrahtdocs'; - my $root = C4::Context->config($configkey); + my $root = C4::Context->config($configkey); - my ($basename, $dirname, $suffix) = fileparse($filename, qr/\.[^.]*/); + my ( $basename, $dirname, $suffix ) = fileparse( $filename, qr/\.[^.]*/ ); my $type = substr $suffix, 1; my @dirs = ( @@ -144,9 +144,9 @@ sub url { my $version = Koha::version; $version =~ s/([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)/$1.$2$3$4/; foreach my $dir (@dirs) { - my $abspath = File::Spec->catfile($root, $dir, $filename); - if (-e $abspath) { - return File::Spec->catfile($interface, $dir, $dirname, "${basename}_${version}${suffix}"); + my $abspath = File::Spec->catfile( $root, $dir, $filename ); + if ( -e $abspath ) { + return File::Spec->catfile( $interface, $dir, $dirname, "${basename}_${version}${suffix}" ); } } } @@ -159,11 +159,11 @@ This shouldn't be used directly. =cut sub _tag { - my ($self, $name, $attributes) = @_; + my ( $self, $name, $attributes ) = @_; my @attributes_strs; if ($attributes) { - while (my ($key, $value) = each %$attributes) { + while ( my ( $key, $value ) = each %$attributes ) { push @attributes_strs, qq{$key="$value"}; } } diff --git a/Koha/Template/Plugin/AudioAlerts.pm b/Koha/Template/Plugin/AudioAlerts.pm index a666f20766..4c5dfcaa51 100644 --- a/Koha/Template/Plugin/AudioAlerts.pm +++ b/Koha/Template/Plugin/AudioAlerts.pm @@ -27,7 +27,7 @@ use C4::Context; use Koha; sub AudioAlerts { - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $audio_alerts = $dbh->selectall_arrayref( 'SELECT * FROM audio_alerts ORDER BY precedence', { Slice => {} } ); return encode_json($audio_alerts); } diff --git a/Koha/Template/Plugin/AuthClient.pm b/Koha/Template/Plugin/AuthClient.pm index 5646371bfa..4a014d6376 100644 --- a/Koha/Template/Plugin/AuthClient.pm +++ b/Koha/Template/Plugin/AuthClient.pm @@ -47,10 +47,11 @@ sub get_providers { my ( $self, $interface ) = @_; $interface = 'staff' - if $interface eq 'intranet'; + if $interface eq 'intranet'; - my $providers = Koha::Auth::Identity::Providers->search( { "domains.allow_$interface" => 1 }, { prefetch => 'domains' } ); - my $base_url = ( $interface eq 'staff' ) ? "/api/v1/oauth/login" : "/api/v1/public/oauth/login"; + my $providers = + Koha::Auth::Identity::Providers->search( { "domains.allow_$interface" => 1 }, { prefetch => 'domains' } ); + my $base_url = ( $interface eq 'staff' ) ? "/api/v1/oauth/login" : "/api/v1/public/oauth/login"; my @urls; @@ -60,11 +61,12 @@ sub get_providers { if ( $provider->protocol eq 'OIDC' || $provider->protocol eq 'OAuth' ) { push @urls, - { code => $code, + { + code => $code, description => $provider->description, icon_url => $provider->icon_url, url => "$base_url/$code/$interface", - }; + }; } } return \@urls; diff --git a/Koha/Template/Plugin/AuthorisedValues.pm b/Koha/Template/Plugin/AuthorisedValues.pm index 4e74c1bbad..2e72aaffe7 100644 --- a/Koha/Template/Plugin/AuthorisedValues.pm +++ b/Koha/Template/Plugin/AuthorisedValues.pm @@ -26,12 +26,13 @@ use Koha::AuthorisedValues; sub GetByCode { my ( $self, $category, $code, $opac ) = @_; - my $av = Koha::AuthorisedValues->search({ category => $category, authorised_value => $code }); - return $av->count - ? $opac - ? $av->next->opac_description - : $av->next->lib - : $code; + my $av = Koha::AuthorisedValues->search( { category => $category, authorised_value => $code } ); + return + $av->count + ? $opac + ? $av->next->opac_description + : $av->next->lib + : $code; } sub Get { @@ -55,7 +56,7 @@ sub GetAuthValueDropbox { sub GetCategories { my ( $self, $params ) = @_; - my $selected = $params->{selected}; + my $selected = $params->{selected}; my @categories = Koha::AuthorisedValues->new->categories; return [ map { @@ -69,8 +70,7 @@ sub GetCategories { sub GetDescriptionsByKohaField { my ( $self, $params ) = @_; - return [ Koha::AuthorisedValues->get_descriptions_by_koha_field( - { kohafield => $params->{kohafield} } ) ]; + return [ Koha::AuthorisedValues->get_descriptions_by_koha_field( { kohafield => $params->{kohafield} } ) ]; } sub GetDescriptionByKohaField { @@ -85,8 +85,8 @@ sub GetDescriptionByKohaField { my $description = $av->{lib} || $params->{authorised_value} || ''; return $params->{opac} - ? $av->{opac_description} || $description - : $description; + ? $av->{opac_description} || $description + : $description; } 1; diff --git a/Koha/Template/Plugin/Biblio.pm b/Koha/Template/Plugin/Biblio.pm index b16bb3e138..4455b25b41 100644 --- a/Koha/Template/Plugin/Biblio.pm +++ b/Koha/Template/Plugin/Biblio.pm @@ -41,7 +41,7 @@ sub HoldsCount { sub RecallsCount { my ( $self, $biblionumber ) = @_; - my $recalls = Koha::Recalls->search({ biblio_id => $biblionumber, completed => 0 }); + my $recalls = Koha::Recalls->search( { biblio_id => $biblionumber, completed => 0 } ); return $recalls->count; } diff --git a/Koha/Template/Plugin/Branches.pm b/Koha/Template/Plugin/Branches.pm index 72870b8b69..164bc8162b 100644 --- a/Koha/Template/Plugin/Branches.pm +++ b/Koha/Template/Plugin/Branches.pm @@ -60,7 +60,7 @@ sub GetLoggedInBranchname { sub GetURL { my ( $self, $branchcode ) = @_; - unless (exists $self->{libraries}->{$branchcode} ){ + unless ( exists $self->{libraries}->{$branchcode} ) { my $l = Koha::Libraries->find($branchcode); $self->{libraries}->{$branchcode} = $l if $l; } @@ -119,7 +119,7 @@ sub all { } sub InIndependentBranchesMode { - my ( $self ) = @_; + my ($self) = @_; return ( not C4::Context->preference("IndependentBranches") or C4::Context::IsSuperLibrarian ); } @@ -140,27 +140,25 @@ sub pickup_locations { if ($item) { $item = Koha::Items->find($item) - unless ref($item) eq 'Koha::Item'; + unless ref($item) eq 'Koha::Item'; @libraries = $item->pickup_locations( { patron => $patron } )->as_list - if defined $item; + if defined $item; } elsif ($biblio) { $biblio = Koha::Biblios->find($biblio) - unless ref($biblio) eq 'Koha::Biblio'; + unless ref($biblio) eq 'Koha::Biblio'; @libraries = $biblio->pickup_locations( { patron => $patron } )->as_list - if defined $biblio; + if defined $biblio; } } else { @libraries = Koha::Libraries->search( { pickup_location => 1 }, { order_by => ['branchname'] } )->as_list - unless @libraries; + unless @libraries; } @libraries = map { $_->unblessed } @libraries; for my $l (@libraries) { if ( defined $selected and $l->{branchcode} eq $selected - or not defined $selected - and C4::Context->userenv - and $l->{branchcode} eq C4::Context->userenv->{branch} ) + or not defined $selected and C4::Context->userenv and $l->{branchcode} eq C4::Context->userenv->{branch} ) { $l->{selected} = 1; } diff --git a/Koha/Template/Plugin/Categories.pm b/Koha/Template/Plugin/Categories.pm index 4d425d6f9e..af7f832094 100644 --- a/Koha/Template/Plugin/Categories.pm +++ b/Koha/Template/Plugin/Categories.pm @@ -25,18 +25,18 @@ use Koha::Patron::Categories; sub all { my ( $self, $params ) = @_; - return Koha::Patron::Categories->search($params, { order_by => [ 'description' ] } ); + return Koha::Patron::Categories->search( $params, { order_by => ['description'] } ); } sub limited { my ( $self, $params ) = @_; - return Koha::Patron::Categories->search_with_library_limits($params, { order_by => [ 'description' ] } ); + return Koha::Patron::Categories->search_with_library_limits( $params, { order_by => ['description'] } ); } sub GetName { my ( $self, $categorycode ) = @_; - return Koha::Patron::Categories->find( $categorycode )->description; + return Koha::Patron::Categories->find($categorycode)->description; } sub can_any_reset_password { diff --git a/Koha/Template/Plugin/CirculationRules.pm b/Koha/Template/Plugin/CirculationRules.pm index 5e00e45638..e791519372 100644 --- a/Koha/Template/Plugin/CirculationRules.pm +++ b/Koha/Template/Plugin/CirculationRules.pm @@ -44,7 +44,7 @@ sub Get { $branchcode = undef if $branchcode eq q{} or $branchcode eq q{*}; $categorycode = undef if $categorycode eq q{} or $categorycode eq q{*}; - $itemtype = undef if $itemtype eq q{} or $itemtype eq q{*}; + $itemtype = undef if $itemtype eq q{} or $itemtype eq q{*}; my $rule = Koha::CirculationRules->get_effective_rule( { @@ -71,7 +71,7 @@ the rule object. =cut sub Search { - my ( $self, $branchcode, $categorycode, $itemtype, $rule_name, $params) = @_; + my ( $self, $branchcode, $categorycode, $itemtype, $rule_name, $params ) = @_; $branchcode = undef if $branchcode eq q{} or $branchcode eq q{*}; $categorycode = undef if $categorycode eq q{} or $categorycode eq q{*}; @@ -86,7 +86,7 @@ sub Search { } )->next; - return $rule if $params->{want_rule}; + return $rule if $params->{want_rule}; return $rule->rule_value if $rule; } @@ -110,7 +110,8 @@ unseen_remaining - The total number of unseen renewals that can still be made sub Renewals { my ( $self, $borrowernumber, $itemnumber ) = @_; - my ( $count, $allowed, $remaining, $unseen_count, $unseen_allowed, $unseen_remaining ) = GetRenewCount( $borrowernumber, $itemnumber ); + my ( $count, $allowed, $remaining, $unseen_count, $unseen_allowed, $unseen_remaining ) = + GetRenewCount( $borrowernumber, $itemnumber ); return { count => $count, diff --git a/Koha/Template/Plugin/ClassSources.pm b/Koha/Template/Plugin/ClassSources.pm index 81063e7acd..406d53c408 100644 --- a/Koha/Template/Plugin/ClassSources.pm +++ b/Koha/Template/Plugin/ClassSources.pm @@ -38,16 +38,16 @@ Return the list of class sources =cut sub all { - my ($self, $params) = @_; + my ( $self, $params ) = @_; my $selected = $params->{selected}; my $default_source = C4::Context->preference("DefaultClassificationSource"); my @class_sources = grep { - $_->used - or ( $selected and $_->cn_source eq $selected ) - or ( $default_source and $_->cn_source eq $default_source ) + $_->used + or ( $selected and $_->cn_source eq $selected ) + or ( $default_source and $_->cn_source eq $default_source ) } Koha::ClassSources->search->as_list; return @class_sources; diff --git a/Koha/Template/Plugin/Desks.pm b/Koha/Template/Plugin/Desks.pm index 0bc374c7f1..29c57c100c 100644 --- a/Koha/Template/Plugin/Desks.pm +++ b/Koha/Template/Plugin/Desks.pm @@ -48,8 +48,8 @@ sub GetLoggedInDeskId { my ($self) = @_; return C4::Context->userenv - ? C4::Context->userenv->{'desk_id'} - : ''; + ? C4::Context->userenv->{'desk_id'} + : ''; } =head3 GetLoggedInDeskName @@ -64,8 +64,8 @@ sub GetLoggedInDeskName { my ($self) = @_; return C4::Context->userenv - ? C4::Context->userenv->{'desk_name'} - : ''; + ? C4::Context->userenv->{'desk_name'} + : ''; } =head3 ListForLibrary @@ -78,8 +78,7 @@ returns all desks existing at the current library sub ListForLibrary { my ($self) = @_; - my $branch_limit = - C4::Context->userenv ? C4::Context->userenv->{"branch"} : ""; + my $branch_limit = C4::Context->userenv ? C4::Context->userenv->{"branch"} : ""; return Koha::Desks->search( { branchcode => $branch_limit }, { order_by => { '-asc' => 'desk_name' } } @@ -94,10 +93,9 @@ returns all desks existing at all libraries =cut - sub all { - my ( $self ) = @_; + my ($self) = @_; return Koha::Desks->search(); } diff --git a/Koha/Template/Plugin/Frameworks.pm b/Koha/Template/Plugin/Frameworks.pm index 01305455be..3700e323f3 100644 --- a/Koha/Template/Plugin/Frameworks.pm +++ b/Koha/Template/Plugin/Frameworks.pm @@ -44,7 +44,6 @@ is not found =cut - sub GetName { my ( $self, $frameworkcode ) = @_; return q{} unless defined $frameworkcode; diff --git a/Koha/Template/Plugin/HtmlId.pm b/Koha/Template/Plugin/HtmlId.pm index 5ca9912aa5..b04442e3f2 100644 --- a/Koha/Template/Plugin/HtmlId.pm +++ b/Koha/Template/Plugin/HtmlId.pm @@ -36,7 +36,7 @@ It will replace characters that are not valid for HTML IDs with an underscore (_ sub filter { my ( $self, $text ) = @_; - return $text =~ s/[^a-zA-Z0-9-]+/_/gr + return $text =~ s/[^a-zA-Z0-9-]+/_/gr; } 1; diff --git a/Koha/Template/Plugin/HtmlTags.pm b/Koha/Template/Plugin/HtmlTags.pm index 301e21f81d..258531f3ae 100644 --- a/Koha/Template/Plugin/HtmlTags.pm +++ b/Koha/Template/Plugin/HtmlTags.pm @@ -26,7 +26,7 @@ our $DYNAMIC = 1; sub filter { my ( $self, $text, $args, $config ) = @_; - return "" unless $text; + return "" unless $text; return $text unless $config->{tag}; $config->{attributes} //= ''; diff --git a/Koha/Template/Plugin/I18N.pm b/Koha/Template/Plugin/I18N.pm index 43e2ef3c07..9ba622ebcf 100644 --- a/Koha/Template/Plugin/I18N.pm +++ b/Koha/Template/Plugin/I18N.pm @@ -63,7 +63,7 @@ there are no variables and not pluralisations to consider. =cut sub t { - my ($self, $msgid) = @_; + my ( $self, $msgid ) = @_; return __($msgid); } @@ -77,8 +77,8 @@ includes a variable =cut sub tx { - my ($self, $msgid, $vars) = @_; - return __x($msgid, %$vars); + my ( $self, $msgid, $vars ) = @_; + return __x( $msgid, %$vars ); } =head2 tn @@ -91,8 +91,8 @@ singular and plural forms =cut sub tn { - my ($self, $msgid, $msgid_plural, $count) = @_; - return __n($msgid, $msgid_plural, $count); + my ( $self, $msgid, $msgid_plural, $count ) = @_; + return __n( $msgid, $msgid_plural, $count ); } =head2 tnx @@ -105,8 +105,8 @@ that needs singular and plural forms and includes a variable =cut sub tnx { - my ($self, $msgid, $msgid_plural, $count, $vars) = @_; - return __nx($msgid, $msgid_plural, $count, %$vars); + my ( $self, $msgid, $msgid_plural, $count, $vars ) = @_; + return __nx( $msgid, $msgid_plural, $count, %$vars ); } =head2 txn @@ -116,8 +116,8 @@ Alias of tnx =cut sub txn { - my ($self, $msgid, $msgid_plural, $count, $vars) = @_; - return __xn($msgid, $msgid_plural, $count, %$vars); + my ( $self, $msgid, $msgid_plural, $count, $vars ) = @_; + return __xn( $msgid, $msgid_plural, $count, %$vars ); } =head2 tp @@ -135,8 +135,8 @@ can understand the context correctly. =cut sub tp { - my ($self, $msgctxt, $msgid) = @_; - return __p($msgctxt, $msgid); + my ( $self, $msgctxt, $msgid ) = @_; + return __p( $msgctxt, $msgid ); } =head2 tpx @@ -149,8 +149,8 @@ that needs both a contextual hint and includes a variable. =cut sub tpx { - my ($self, $msgctxt, $msgid, $vars) = @_; - return __px($msgctxt, $msgid, %$vars); + my ( $self, $msgctxt, $msgid, $vars ) = @_; + return __px( $msgctxt, $msgid, %$vars ); } =head2 tnp @@ -164,8 +164,8 @@ forms. =cut sub tnp { - my ($self, $msgctxt, $msgid, $msgid_plural, $count) = @_; - return __np($msgctxt, $msgid, $msgid_plural, $count); + my ( $self, $msgctxt, $msgid, $msgid_plural, $count ) = @_; + return __np( $msgctxt, $msgid, $msgid_plural, $count ); } =head2 tnpx @@ -179,8 +179,8 @@ and also includes variables. =cut sub tnpx { - my ($self, $msgctxt, $msgid, $msgid_plural, $count, $vars) = @_; - return __npx($msgctxt, $msgid, $msgid_plural, $count, %$vars); + my ( $self, $msgctxt, $msgid, $msgid_plural, $count, $vars ) = @_; + return __npx( $msgctxt, $msgid, $msgid_plural, $count, %$vars ); } 1; diff --git a/Koha/Template/Plugin/ItemTypes.pm b/Koha/Template/Plugin/ItemTypes.pm index d2184f8fa7..dd4b7c4951 100644 --- a/Koha/Template/Plugin/ItemTypes.pm +++ b/Koha/Template/Plugin/ItemTypes.pm @@ -30,12 +30,13 @@ sub GetDescription { return q{} unless defined $itemtypecode; my $memory_cache = Koha::Cache::Memory::Lite->get_instance; - my $cache_key = $want_parent ? "Itemtype_parent_description:".$itemtypecode : "Itemtype_description:" . $itemtypecode; + my $cache_key = + $want_parent ? "Itemtype_parent_description:" . $itemtypecode : "Itemtype_description:" . $itemtypecode; - my $cached = $memory_cache->get_from_cache($cache_key); + my $cached = $memory_cache->get_from_cache($cache_key); return $cached if $cached; - my $itemtype = Koha::ItemTypes->find( $itemtypecode ); + my $itemtype = Koha::ItemTypes->find($itemtypecode); unless ($itemtype) { $memory_cache->set_in_cache( $cache_key, q{} ); return q{}; @@ -44,7 +45,10 @@ sub GetDescription { my $parent; $parent = $itemtype->parent if $want_parent; - my $description = $parent ? $parent->translated_description . "->" . $itemtype->translated_description : $itemtype->translated_description; + my $description = + $parent + ? $parent->translated_description . "->" . $itemtype->translated_description + : $itemtype->translated_description; $memory_cache->set_in_cache( $cache_key, $description ); return $description; diff --git a/Koha/Template/Plugin/JSConsents.pm b/Koha/Template/Plugin/JSConsents.pm index 174a36a02e..983d40f798 100644 --- a/Koha/Template/Plugin/JSConsents.pm +++ b/Koha/Template/Plugin/JSConsents.pm @@ -18,10 +18,10 @@ package Koha::Template::Plugin::JSConsents; use Modern::Perl; use Template::Plugin; -use base qw( Template::Plugin ); +use base qw( Template::Plugin ); use MIME::Base64 qw{ decode_base64 }; -use JSON qw{ decode_json }; -use Encode qw{ encode_utf8 }; +use JSON qw{ decode_json }; +use Encode qw{ encode_utf8 }; use C4::Context; diff --git a/Koha/Template/Plugin/Koha.pm b/Koha/Template/Plugin/Koha.pm index 0b69249779..7b836afd54 100644 --- a/Koha/Template/Plugin/Koha.pm +++ b/Koha/Template/Plugin/Koha.pm @@ -65,10 +65,9 @@ sub new { }, $class; } - sub Preference { my ( $self, $pref ) = @_; - return C4::Context->preference( $pref ); + return C4::Context->preference($pref); } =head3 CSVDelimiter diff --git a/Koha/Template/Plugin/KohaDates.pm b/Koha/Template/Plugin/KohaDates.pm index e3f39c2eb2..3803d89730 100644 --- a/Koha/Template/Plugin/KohaDates.pm +++ b/Koha/Template/Plugin/KohaDates.pm @@ -32,21 +32,22 @@ sub filter { $config->{with_hours} //= 0; my $dt = dt_from_string( $text, 'iso' ); - $dt->add( %$_ ) for _parse_config_for_durations($config); # Allow date add/subtract; see _parse_config_for_durations + $dt->add(%$_) for _parse_config_for_durations($config); # Allow date add/subtract; see _parse_config_for_durations - return $config->{as_due_date} ? - output_pref({ dt => $dt, as_due_date => 1, dateformat => $config->{dateformat} }) : - output_pref({ dt => $dt, dateonly => !$config->{with_hours}, dateformat => $config->{dateformat} }); + return $config->{as_due_date} + ? output_pref( { dt => $dt, as_due_date => 1, dateformat => $config->{dateformat} } ) + : output_pref( { dt => $dt, dateonly => !$config->{with_hours}, dateformat => $config->{dateformat} } ); } sub _parse_config_for_durations { -# Supports passing things like add_years => 1 or subtract_years => 1 -# Same for months, weeks, days, hours, minutes or seconds -# Returns a list of hashrefs like { years => 1 }, { days => -1 } that can be passed to dt->add + + # Supports passing things like add_years => 1 or subtract_years => 1 + # Same for months, weeks, days, hours, minutes or seconds + # Returns a list of hashrefs like { years => 1 }, { days => -1 } that can be passed to dt->add my $config = shift; my @results; foreach my $entry ( keys %$config ) { - if( $entry =~ /^(add|subtract)_(years|months|weeks|days|hours|minutes|seconds)$/ ) { + if ( $entry =~ /^(add|subtract)_(years|months|weeks|days|hours|minutes|seconds)$/ ) { push @results, { $2 => ( $1 eq 'add' ? 1 : -1 ) * $config->{$entry} }; } } @@ -55,12 +56,12 @@ sub _parse_config_for_durations { sub datetime_from_string { my ( $self, @params ) = @_; - return dt_from_string( @params ); + return dt_from_string(@params); } sub output_preference { my ( $self, @params ) = @_; - return output_pref( @params ); + return output_pref(@params); } sub tz { diff --git a/Koha/Template/Plugin/KohaPlugins.pm b/Koha/Template/Plugin/KohaPlugins.pm index 9b2adb7d72..63bbc2c6ff 100644 --- a/Koha/Template/Plugin/KohaPlugins.pm +++ b/Koha/Template/Plugin/KohaPlugins.pm @@ -62,12 +62,11 @@ sub get_plugins_opac_head { ); my @data = (); - foreach my $plugin (@plugins){ + foreach my $plugin (@plugins) { try { my $datum = $plugin->opac_head || q{}; - push(@data,$datum); - } - catch { + push( @data, $datum ); + } catch { warn "Error calling 'opac_head' on the " . $plugin->{class} . "plugin ($_)"; }; } @@ -98,12 +97,11 @@ sub get_plugins_opac_js { ); my @data = (); - foreach my $plugin (@plugins){ + foreach my $plugin (@plugins) { try { my $datum = $plugin->opac_js || q{}; - push(@data,$datum); - } - catch { + push( @data, $datum ); + } catch { warn "Error calling 'opac_js' on the " . $plugin->{class} . "plugin ($_)"; }; } @@ -134,12 +132,11 @@ sub get_plugins_intranet_head { ); my @data = (); - foreach my $plugin (@plugins){ + foreach my $plugin (@plugins) { try { my $datum = $plugin->intranet_head || q{}; - push(@data,$datum); - } - catch { + push( @data, $datum ); + } catch { warn "Error calling 'intranet_head' on the " . $plugin->{class} . "plugin ($_)"; }; } @@ -170,12 +167,11 @@ sub get_plugins_intranet_js { ); my @data = (); - foreach my $plugin (@plugins){ + foreach my $plugin (@plugins) { try { my $datum = $plugin->intranet_js || q{}; - push(@data,$datum); - } - catch { + push( @data, $datum ); + } catch { warn "Error calling 'intranet_js' on the " . $plugin->{class} . "plugin ($_)"; }; } @@ -214,15 +210,16 @@ sub get_plugins_intranet_catalog_biblio_tab { try { my @newtabs = $plugin->intranet_catalog_biblio_tab($params); foreach my $newtab (@newtabs) { + # Add a unique HTML id - my $html_id = 'tab-'. $plugin->{class} . '-' . $newtab->title; + my $html_id = 'tab-' . $plugin->{class} . '-' . $newtab->title; + # Using characters except ASCII letters, digits, '_', '-' and '.' may cause compatibility problems $html_id =~ s/[^0-9A-Za-z]+/-/g; $newtab->id($html_id); } push @$tabs, @newtabs; - } - catch { + } catch { warn "Error calling 'intranet_catalog_biblio_tab' on the " . $plugin->{class} . "plugin ($_)"; }; } diff --git a/Koha/Template/Plugin/Languages.pm b/Koha/Template/Plugin/Languages.pm index 65534e5071..503c8b2877 100644 --- a/Koha/Template/Plugin/Languages.pm +++ b/Koha/Template/Plugin/Languages.pm @@ -26,9 +26,9 @@ use C4::Languages; sub GetByISOCode { my ( $self, $lang, $code ) = @_; - $lang = substr($lang,0,2); #Get db code from Koha lang value - my $rfc = C4::Languages::get_rfc4646_from_iso639( $code ); - my $description = C4::Languages::language_get_description($rfc,$lang,'language'); + $lang = substr( $lang, 0, 2 ); #Get db code from Koha lang value + my $rfc = C4::Languages::get_rfc4646_from_iso639($code); + my $description = C4::Languages::language_get_description( $rfc, $lang, 'language' ); return $description; } diff --git a/Koha/Template/Plugin/NoticeTemplates.pm b/Koha/Template/Plugin/NoticeTemplates.pm index 894e3080fc..7e5395febe 100644 --- a/Koha/Template/Plugin/NoticeTemplates.pm +++ b/Koha/Template/Plugin/NoticeTemplates.pm @@ -59,4 +59,5 @@ In a template, you can get notice templates by module with Alex Arnaud =cut + 1; diff --git a/Koha/Template/Plugin/Price.pm b/Koha/Template/Plugin/Price.pm index ec1fe71d27..2577504e79 100644 --- a/Koha/Template/Plugin/Price.pm +++ b/Koha/Template/Plugin/Price.pm @@ -30,8 +30,8 @@ sub filter { $value ||= 0; $config->{on_editing} //= 0; return $config->{on_editing} - ? Koha::Number::Price->new( $value )->format_for_editing - : Koha::Number::Price->new( $value )->format( $config ); + ? Koha::Number::Price->new($value)->format_for_editing + : Koha::Number::Price->new($value)->format($config); } 1; diff --git a/Koha/Template/Plugin/Registers.pm b/Koha/Template/Plugin/Registers.pm index cb5fab8b61..da88a69aec 100644 --- a/Koha/Template/Plugin/Registers.pm +++ b/Koha/Template/Plugin/Registers.pm @@ -53,9 +53,9 @@ Return the register_id for the register attached to the current session. sub session_register_id { my ($self) = @_; - return C4::Context->userenv ? - C4::Context->userenv->{'register_id'} : - ''; + return C4::Context->userenv + ? C4::Context->userenv->{'register_id'} + : ''; } =head2 session_register_name @@ -68,8 +68,8 @@ sub session_register_name { my ($self) = @_; return C4::Context->userenv - ? C4::Context->userenv->{'register_name'} - : ''; + ? C4::Context->userenv->{'register_name'} + : ''; } =head2 all @@ -87,19 +87,18 @@ sub all { return unless C4::Context->preference('UseCashRegisters'); my $filters = $params->{filters} // {}; - my $where = { archived => 0 }; + my $where = { archived => 0 }; $where->{branch} = C4::Context->userenv->{'branch'} - if ( $filters->{current_branch} && C4::Context->userenv ); + if ( $filters->{current_branch} && C4::Context->userenv ); my $registers = Koha::Cash::Registers->search($where)->unblessed(); my $selected = $params->{selected}; for my $register ( @{$registers} ) { if ( defined($selected) ) { $register->{selected} = ( $register->{id} == $selected ) ? 1 : 0; - } - else { - $register->{selected} = ( defined( $self->session_register_id ) - && $register->{id} eq $self->session_register_id ) ? 1 : 0; + } else { + $register->{selected} = + ( defined( $self->session_register_id ) && $register->{id} eq $self->session_register_id ) ? 1 : 0; } } diff --git a/Koha/Template/Plugin/TablesSettings.pm b/Koha/Template/Plugin/TablesSettings.pm index bed439b6e7..3cf0222ea3 100644 --- a/Koha/Template/Plugin/TablesSettings.pm +++ b/Koha/Template/Plugin/TablesSettings.pm @@ -75,8 +75,8 @@ it may contain confidential information and should be fully hidden rather than j sub is_hidden { my ( $self, $module, $page, $table, $column_name ) = @_; my $columns = C4::Utils::DataTables::TablesSettings::get_columns( $module, $page, $table ); - foreach my $keys(@$columns){ - if($keys->{'columnname'} eq $column_name){ + foreach my $keys (@$columns) { + if ( $keys->{'columnname'} eq $column_name ) { return $keys->{'is_hidden'}; } } @@ -98,7 +98,7 @@ sub GetTableSettings { $format //= q{}; my $settings = C4::Utils::DataTables::TablesSettings::get_table_settings( $module, $page, $table ); - my $columns = C4::Utils::DataTables::TablesSettings::get_columns( $module, $page, $table ); + my $columns = C4::Utils::DataTables::TablesSettings::get_columns( $module, $page, $table ); $settings = { %$settings, @@ -110,7 +110,7 @@ sub GetTableSettings { return $format eq 'json' ? to_json( $settings || {} ) - : $settings + : $settings; } 1; diff --git a/Koha/Template/Plugin/To.pm b/Koha/Template/Plugin/To.pm index dccd8e6cfe..747c653cc1 100644 --- a/Koha/Template/Plugin/To.pm +++ b/Koha/Template/Plugin/To.pm @@ -30,8 +30,8 @@ sub json { my $json = JSON->new->allow_nonref(1); $json = $json->encode($value); - $json =~ s/^"|"$//g; # Remove quotes around the strings - $json =~ s/\\r/\\\\r/g; # Convert newlines to escaped newline characters + $json =~ s/^"|"$//g; # Remove quotes around the strings + $json =~ s/\\r/\\\\r/g; # Convert newlines to escaped newline characters $json =~ s/\\n/\\\\n/g; return $json; } diff --git a/Koha/Token.pm b/Koha/Token.pm index 4a806b0e37..95213d0037 100644 --- a/Koha/Token.pm +++ b/Koha/Token.pm @@ -60,9 +60,9 @@ use Koha::Exceptions::Token; use Koha::Session; use base qw(Class::Accessor); -use constant HMAC_SHA1_LENGTH => 20; -use constant CSRF_EXPIRY_HOURS => 8; # 8 hours instead of 7 days.. -use constant DEFA_SESSION_ID => 0; +use constant HMAC_SHA1_LENGTH => 20; +use constant CSRF_EXPIRY_HOURS => 8; # 8 hours instead of 7 days.. +use constant DEFA_SESSION_ID => 0; use constant DEFA_SESSION_USERID => 'anonymous'; =head1 METHODS @@ -74,7 +74,7 @@ use constant DEFA_SESSION_USERID => 'anonymous'; =cut sub new { - my ( $class ) = @_; + my ($class) = @_; return $class->SUPER::new(); } @@ -108,12 +108,12 @@ sub new { sub generate { my ( $self, $params ) = @_; - if( $params->{type} && $params->{type} eq 'CSRF' ) { - $self->{lasttoken} = _gen_csrf( $params ); - } elsif( $params->{type} && $params->{type} eq 'JWT' ) { - $self->{lasttoken} = _gen_jwt( $params ); + if ( $params->{type} && $params->{type} eq 'CSRF' ) { + $self->{lasttoken} = _gen_csrf($params); + } elsif ( $params->{type} && $params->{type} eq 'JWT' ) { + $self->{lasttoken} = _gen_jwt($params); } else { - $self->{lasttoken} = _gen_rand( $params ); + $self->{lasttoken} = _gen_rand($params); } return $self->{lasttoken}; } @@ -129,8 +129,8 @@ sub generate { sub generate_csrf { my ( $self, $params ) = @_; return if !$params->{session_id}; - $params = _add_default_csrf_params( $params ); - return $self->generate({ %$params, type => 'CSRF' }); + $params = _add_default_csrf_params($params); + return $self->generate( { %$params, type => 'CSRF' } ); } =head2 generate_jwt @@ -144,8 +144,8 @@ sub generate_csrf { sub generate_jwt { my ( $self, $params ) = @_; return if !$params->{id}; - $params = _add_default_jwt_params( $params ); - return $self->generate({ %$params, type => 'JWT' }); + $params = _add_default_jwt_params($params); + return $self->generate( { %$params, type => 'JWT' } ); } =head2 check @@ -161,11 +161,10 @@ sub generate_jwt { sub check { my ( $self, $params ) = @_; - if( $params->{type} && $params->{type} eq 'CSRF' ) { - return _chk_csrf( $params ); - } - elsif( $params->{type} && $params->{type} eq 'JWT' ) { - return _chk_jwt( $params ); + if ( $params->{type} && $params->{type} eq 'CSRF' ) { + return _chk_csrf($params); + } elsif ( $params->{type} && $params->{type} eq 'JWT' ) { + return _chk_jwt($params); } return; } @@ -181,13 +180,14 @@ sub check { sub check_csrf { my ( $self, $params ) = @_; return if !$params->{session_id}; - $params = _add_default_csrf_params( $params ); - my $c = $self->check({ %$params, type => 'CSRF' }); + $params = _add_default_csrf_params($params); + my $c = $self->check( { %$params, type => 'CSRF' } ); + + unless ($c) { - unless ( $c ) { # If the check failed we need to test with the "anonymous" in case the token was generating without the user being logged in yet. $params->{id} = DEFA_SESSION_USERID . '_' . $params->{session_id}; - $c = $self->check({ %$params, type => 'CSRF' }); + $c = $self->check( { %$params, type => 'CSRF' } ); } return $c; @@ -203,8 +203,8 @@ sub check_csrf { sub check_jwt { my ( $self, $params ) = @_; - $params = _add_default_jwt_params( $params ); - return $self->check({ %$params, type => 'JWT' }); + $params = _add_default_jwt_params($params); + return $self->check( { %$params, type => 'JWT' } ); } =head2 decode_jwt @@ -214,16 +214,17 @@ sub check_jwt { Will return the value of the id stored in the token. =cut + sub decode_jwt { my ( $self, $params ) = @_; - $params = _add_default_jwt_params( $params ); - return _decode_jwt( $params ); + $params = _add_default_jwt_params($params); + return _decode_jwt($params); } # --- Internal routines --- sub _add_default_csrf_params { - my ( $params ) = @_; + my ($params) = @_; $params->{session_id} //= DEFA_SESSION_ID; my $id; @@ -240,24 +241,24 @@ sub _add_default_csrf_params { my $pw = C4::Context->config('pass'); $params->{secret} //= md5_base64( Encode::encode( 'UTF-8', $pw ) ), - return $params; + return $params; } sub _gen_csrf { -# Since WWW::CSRF::generate_csrf_token does not use the NonBlocking -# parameter of Bytes::Random::Secure, we are passing random bytes from -# a non blocking source to WWW::CSRF via its Random parameter. + # Since WWW::CSRF::generate_csrf_token does not use the NonBlocking + # parameter of Bytes::Random::Secure, we are passing random bytes from + # a non blocking source to WWW::CSRF via its Random parameter. - my ( $params ) = @_; + my ($params) = @_; return if !$params->{id} || !$params->{secret}; - my $randomizer = Bytes::Random::Secure->new( NonBlocking => 1 ); - # this is most fundamental: do not use /dev/random since it is - # blocking, but use /dev/urandom ! - my $random = $randomizer->bytes( HMAC_SHA1_LENGTH ); - my $token = WWW::CSRF::generate_csrf_token( + + # this is most fundamental: do not use /dev/random since it is + # blocking, but use /dev/urandom ! + my $random = $randomizer->bytes(HMAC_SHA1_LENGTH); + my $token = WWW::CSRF::generate_csrf_token( $params->{id}, $params->{secret}, { Random => $random }, ); @@ -265,7 +266,7 @@ sub _gen_csrf { } sub _chk_csrf { - my ( $params ) = @_; + my ($params) = @_; return if !$params->{id} || !$params->{secret} || !$params->{token}; my $csrf_status = WWW::CSRF::check_csrf_token( @@ -278,28 +279,26 @@ sub _chk_csrf { } sub _gen_rand { - my ( $params ) = @_; + my ($params) = @_; my $length = $params->{length} || 1; $length = 1 unless $length > 0; - my $pattern = $params->{pattern} // '.{'.$length.'}'; # pattern overrides length parameter + my $pattern = $params->{pattern} // '.{' . $length . '}'; # pattern overrides length parameter my $token; - eval { - $token = String::Random::random_regex( $pattern ); - }; + eval { $token = String::Random::random_regex($pattern); }; Koha::Exceptions::Token::BadPattern->throw($@) if $@; return $token; } sub _add_default_jwt_params { - my ( $params ) = @_; + my ($params) = @_; my $pw = C4::Context->config('pass'); $params->{secret} //= md5_base64( Encode::encode( 'UTF-8', $pw ) ), - return $params; + return $params; } sub _gen_jwt { - my ( $params ) = @_; + my ($params) = @_; return if !$params->{id} || !$params->{secret}; return Mojo::JWT->new( @@ -309,19 +308,19 @@ sub _gen_jwt { } sub _chk_jwt { - my ( $params ) = @_; + my ($params) = @_; return if !$params->{id} || !$params->{secret} || !$params->{token}; - my $claims = Mojo::JWT->new(secret => $params->{secret})->decode($params->{token}); + my $claims = Mojo::JWT->new( secret => $params->{secret} )->decode( $params->{token} ); return 1 if exists $claims->{id} && $claims->{id} eq $params->{id}; } sub _decode_jwt { - my ( $params ) = @_; + my ($params) = @_; return if !$params->{token} || !$params->{secret}; - my $claims = Mojo::JWT->new(secret => $params->{secret})->decode($params->{token}); + my $claims = Mojo::JWT->new( secret => $params->{secret} )->decode( $params->{token} ); return $claims->{id}; } diff --git a/Koha/TrackedLink.pm b/Koha/TrackedLink.pm index 7c7eeb871e..d3fba18a78 100644 --- a/Koha/TrackedLink.pm +++ b/Koha/TrackedLink.pm @@ -17,7 +17,6 @@ package Koha::TrackedLink; use Modern::Perl; - use Koha::Database; use base qw(Koha::Object); diff --git a/Koha/TrackedLinks.pm b/Koha/TrackedLinks.pm index 20ea4a90b2..bbf61b33ba 100644 --- a/Koha/TrackedLinks.pm +++ b/Koha/TrackedLinks.pm @@ -17,7 +17,6 @@ package Koha::TrackedLinks; use Modern::Perl; - use Koha::Database; use Koha::TrackedLink; diff --git a/Koha/UI/Form/Builder/Biblio.pm b/Koha/UI/Form/Builder/Biblio.pm index 13ecc67ff6..ffd0397653 100644 --- a/Koha/UI/Form/Builder/Biblio.pm +++ b/Koha/UI/Form/Builder/Biblio.pm @@ -46,7 +46,6 @@ Helper to build a form to add or edit a new biblio =cut - sub new { my ( $class, $params ) = @_; @@ -69,21 +68,21 @@ sub new { =cut sub generate_subfield_form { - my ($self, $params) = @_; + my ( $self, $params ) = @_; - my $tag = $params->{tag}; - my $subfield = $params->{subfield}; - my $value = $params->{value} // ''; - my $index_tag = $params->{index_tag}; - my $rec = $params->{record}; - my $hostitemnumber = $params->{hostitemnumber}; - my $op = $params->{op} // ''; + my $tag = $params->{tag}; + my $subfield = $params->{subfield}; + my $value = $params->{value} // ''; + my $index_tag = $params->{index_tag}; + my $rec = $params->{record}; + my $hostitemnumber = $params->{hostitemnumber}; + my $op = $params->{op} // ''; my $changed_framework = $params->{changed_framework}; - my $breedingid = $params->{breedingid}; - my $tagslib = $params->{tagslib}; - my $mandatory_z3950 = $params->{mandatory_z3950} // {}; + my $breedingid = $params->{breedingid}; + my $tagslib = $params->{tagslib}; + my $mandatory_z3950 = $params->{mandatory_z3950} // {}; - my $index_subfield = $self->create_key(); # create a specific key for each subfield + my $index_subfield = $self->create_key(); # create a specific key for each subfield # Apply optional framework default value when it is a new record, # or when editing as new (duplicating a record), @@ -92,27 +91,30 @@ sub generate_subfield_form { # based on the ApplyFrameworkDefaults setting. # Substitute date parts, user name my $applydefaults = C4::Context->preference('ApplyFrameworkDefaults'); - if ( $value eq '' && ( - ( $applydefaults =~ /new/ && !$self->{biblionumber} ) || - ( $applydefaults =~ /duplicate/ && $op eq 'duplicate' ) || - ( $applydefaults =~ /changed/ && $changed_framework ) || - ( $applydefaults =~ /imported/ && $breedingid ) - ) ) { + if ( + $value eq '' + && ( ( $applydefaults =~ /new/ && !$self->{biblionumber} ) + || ( $applydefaults =~ /duplicate/ && $op eq 'duplicate' ) + || ( $applydefaults =~ /changed/ && $changed_framework ) + || ( $applydefaults =~ /imported/ && $breedingid ) ) + ) + { $value = $tagslib->{$tag}->{$subfield}->{defaultvalue} // q{}; # get today date & replace <>, <>, <>, <
> if provided in the default value - my $today_dt = dt_from_string; - my $year = $today_dt->strftime('%Y'); + my $today_dt = dt_from_string; + my $year = $today_dt->strftime('%Y'); my $shortyear = $today_dt->strftime('%y'); - my $month = $today_dt->strftime('%m'); - my $day = $today_dt->strftime('%d'); + my $month = $today_dt->strftime('%m'); + my $day = $today_dt->strftime('%d'); $value =~ s/<>/$year/g; $value =~ s/<>/$shortyear/g; $value =~ s/<>/$month/g; $value =~ s/<
>/$day/g; + # And <> with surname (?) - my $username=(C4::Context->userenv?C4::Context->userenv->{'surname'}:"superlibrarian"); - $value=~s/<>/$username/g; + my $username = ( C4::Context->userenv ? C4::Context->userenv->{'surname'} : "superlibrarian" ); + $value =~ s/<>/$username/g; } my $dbh = C4::Context->dbh; @@ -123,58 +125,61 @@ sub generate_subfield_form { $id_subfield = "00" if $id_subfield eq "@"; my %subfield_data = ( - tag => $tag, - subfield => $id_subfield, - marc_lib => $tagslib->{$tag}->{$subfield}->{lib}, - tag_mandatory => $tagslib->{$tag}->{mandatory}, - mandatory => $tagslib->{$tag}->{$subfield}->{mandatory}, - important => $tagslib->{$tag}->{$subfield}->{important}, - repeatable => $tagslib->{$tag}->{$subfield}->{repeatable}, - kohafield => $tagslib->{$tag}->{$subfield}->{kohafield}, - index => $index_tag, - id => "tag_".$tag."_subfield_".$id_subfield."_".$index_tag."_".$index_subfield, - value => $value, - maxlength => $tagslib->{$tag}->{$subfield}->{maxlength}, - random => $self->create_key(), + tag => $tag, + subfield => $id_subfield, + marc_lib => $tagslib->{$tag}->{$subfield}->{lib}, + tag_mandatory => $tagslib->{$tag}->{mandatory}, + mandatory => $tagslib->{$tag}->{$subfield}->{mandatory}, + important => $tagslib->{$tag}->{$subfield}->{important}, + repeatable => $tagslib->{$tag}->{$subfield}->{repeatable}, + kohafield => $tagslib->{$tag}->{$subfield}->{kohafield}, + index => $index_tag, + id => "tag_" . $tag . "_subfield_" . $id_subfield . "_" . $index_tag . "_" . $index_subfield, + value => $value, + maxlength => $tagslib->{$tag}->{$subfield}->{maxlength}, + random => $self->create_key(), ); - if (exists $mandatory_z3950->{$tag.$subfield}){ - $subfield_data{z3950_mandatory} = $mandatory_z3950->{$tag.$subfield}; + if ( exists $mandatory_z3950->{ $tag . $subfield } ) { + $subfield_data{z3950_mandatory} = $mandatory_z3950->{ $tag . $subfield }; } + # Subfield is hidden depending of hidden and mandatory flag, and is always # shown if it contains anything or if its field is mandatory or important. my $tdef = $tagslib->{$tag}; $subfield_data{visibility} = "display:none;" - if $tdef->{$subfield}->{hidden} % 2 == 1 && - $value eq '' && - !$tdef->{$subfield}->{mandatory} && - !$tdef->{mandatory} && - !$tdef->{$subfield}->{important} && - !$tdef->{important}; - # expand all subfields of 773 if there is a host item provided in the input - $subfield_data{visibility} = '' if ($tag eq '773' and $hostitemnumber); + if $tdef->{$subfield}->{hidden} % 2 == 1 + && $value eq '' + && !$tdef->{$subfield}->{mandatory} + && !$tdef->{mandatory} + && !$tdef->{$subfield}->{important} + && !$tdef->{important}; + # expand all subfields of 773 if there is a host item provided in the input + $subfield_data{visibility} = '' if ( $tag eq '773' and $hostitemnumber ); # it's an authorised field if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) { $subfield_data{marc_value} = $self->build_authorized_values_list( { - tag => $tag, - subfield => $subfield, - value => $value, - index_tag => $index_tag, + tag => $tag, + subfield => $subfield, + value => $value, + index_tag => $index_tag, index_subfield => $index_subfield, - tagslib => $tagslib, + tagslib => $tagslib, } ); } + # it's a subfield $9 linking to an authority record - see bug 2206 and 28022 - elsif ($subfield eq "9" and - exists($tagslib->{$tag}->{'a'}->{authtypecode}) and - defined($tagslib->{$tag}->{'a'}->{authtypecode}) and - $tagslib->{$tag}->{'a'}->{authtypecode} ne '' and - $tagslib->{$tag}->{'a'}->{hidden} > -4 and - $tagslib->{$tag}->{'a'}->{hidden} < 5) { + elsif ( $subfield eq "9" + and exists( $tagslib->{$tag}->{'a'}->{authtypecode} ) + and defined( $tagslib->{$tag}->{'a'}->{authtypecode} ) + and $tagslib->{$tag}->{'a'}->{authtypecode} ne '' + and $tagslib->{$tag}->{'a'}->{hidden} > -4 + and $tagslib->{$tag}->{'a'}->{hidden} < 5 ) + { $subfield_data{marc_value} = { type => 'text', id => $subfield_data{id}, @@ -185,9 +190,9 @@ sub generate_subfield_form { readonly => 1, }; - # it's a thesaurus / authority field - } - elsif ( $tagslib->{$tag}->{$subfield}->{authtypecode} ) { + # it's a thesaurus / authority field + } elsif ( $tagslib->{$tag}->{$subfield}->{authtypecode} ) { + # when authorities auto-creation is allowed, do not set readonly my $is_readonly = C4::Context->preference('RequireChoosingExistingAuthority'); @@ -202,29 +207,34 @@ sub generate_subfield_form { authtype => $tagslib->{$tag}->{$subfield}->{authtypecode}, }; - # it's a plugin field + # it's a plugin field } elsif ( $tagslib->{$tag}->{$subfield}->{'value_builder'} ) { require Koha::FrameworkPlugin; - my $plugin = Koha::FrameworkPlugin->new( { - name => $tagslib->{$tag}->{$subfield}->{'value_builder'}, - }); - my $pars= { dbh => $dbh, record => $rec, tagslib => $tagslib, - id => $subfield_data{id} }; - $plugin->build( $pars ); - if( !$plugin->errstr ) { + my $plugin = Koha::FrameworkPlugin->new( + { + name => $tagslib->{$tag}->{$subfield}->{'value_builder'}, + } + ); + my $pars = { + dbh => $dbh, record => $rec, tagslib => $tagslib, + id => $subfield_data{id} + }; + $plugin->build($pars); + if ( !$plugin->errstr ) { $subfield_data{marc_value} = { - type => 'text_complex', - id => $subfield_data{id}, - name => $subfield_data{id}, - value => $value, - size => 67, - maxlength => $subfield_data{maxlength}, - javascript => $plugin->javascript, - plugin => $plugin->name, - noclick => $plugin->noclick, + type => 'text_complex', + id => $subfield_data{id}, + name => $subfield_data{id}, + value => $value, + size => 67, + maxlength => $subfield_data{maxlength}, + javascript => $plugin->javascript, + plugin => $plugin->name, + noclick => $plugin->noclick, }; } else { warn $plugin->errstr; + # supply default input form $subfield_data{marc_value} = { type => 'text', @@ -237,7 +247,7 @@ sub generate_subfield_form { }; } - # it's an hidden field + # it's an hidden field } elsif ( $tag eq '' ) { $subfield_data{marc_value} = { type => 'hidden', @@ -248,28 +258,25 @@ sub generate_subfield_form { maxlength => $subfield_data{maxlength}, }; - } - else { + } else { + # it's a standard field if ( length($value) > 100 - or - ( C4::Context->preference("marcflavour") eq "UNIMARC" && $tag >= 300 + or ( C4::Context->preference("marcflavour") eq "UNIMARC" && $tag >= 300 and $tag < 400 && $subfield eq 'a' ) or ( $tag >= 500 - and $tag < 600 - && C4::Context->preference("marcflavour") eq "MARC21" ) - ) + and $tag < 600 && C4::Context->preference("marcflavour") eq "MARC21" ) + ) { $subfield_data{marc_value} = { - type => 'textarea', - id => $subfield_data{id}, - name => $subfield_data{id}, - value => $value, + type => 'textarea', + id => $subfield_data{id}, + name => $subfield_data{id}, + value => $value, }; - } - else { + } else { $subfield_data{marc_value} = { type => 'text', id => $subfield_data{id}, @@ -294,14 +301,14 @@ sub generate_subfield_form { =cut sub build_authorized_values_list { - my ($self, $params) = @_; + my ( $self, $params ) = @_; - my $tag = $params->{tag}; - my $subfield = $params->{subfield}; - my $value = $params->{value}; - my $index_tag = $params->{index_tag}; + my $tag = $params->{tag}; + my $subfield = $params->{subfield}; + my $value = $params->{value}; + my $index_tag = $params->{index_tag}; my $index_subfield = $params->{index_subfield}; - my $tagslib = $params->{tagslib}; + my $tagslib = $params->{tagslib}; my @authorised_values; my %authorised_lib; @@ -311,42 +318,40 @@ sub build_authorized_values_list { #---- branch my $category = $tagslib->{$tag}->{$subfield}->{authorised_value}; if ( $category eq "branches" ) { - my $libraries = Koha::Libraries->search_filtered({}, {order_by => ['branchname']}); + my $libraries = Koha::Libraries->search_filtered( {}, { order_by => ['branchname'] } ); while ( my $l = $libraries->next ) { push @authorised_values, $l->branchcode; - $authorised_lib{$l->branchcode} = $l->branchname; + $authorised_lib{ $l->branchcode } = $l->branchname; } - } - elsif ( $category eq "itemtypes" ) { + } elsif ( $category eq "itemtypes" ) { push @authorised_values, ""; my $itemtype; my $itemtypes = Koha::ItemTypes->search_with_localization; while ( $itemtype = $itemtypes->next ) { push @authorised_values, $itemtype->itemtype; - $authorised_lib{$itemtype->itemtype} = $itemtype->translated_description; + $authorised_lib{ $itemtype->itemtype } = $itemtype->translated_description; } $value = $itemtype unless ($value); - } - elsif ( $category eq "cn_source" ) { + } elsif ( $category eq "cn_source" ) { push @authorised_values, ""; my $class_sources = GetClassSources(); my $default_source = C4::Context->preference("DefaultClassificationSource"); - foreach my $class_source (sort {fc($a) cmp fc($b)} keys %$class_sources) { - next unless $class_sources->{$class_source}->{'used'} or - ($value and $class_source eq $value) or - ($class_source eq $default_source); + foreach my $class_source ( sort { fc($a) cmp fc($b) } keys %$class_sources ) { + next + unless $class_sources->{$class_source}->{'used'} + or ( $value and $class_source eq $value ) + or ( $class_source eq $default_source ); push @authorised_values, $class_source; $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'}; } $value = $default_source unless $value; - } - else { + } else { my $branch_limit = C4::Context->userenv ? C4::Context->userenv->{branch} : ''; - my $query = 'SELECT authorised_value, lib FROM authorised_values'; + my $query = 'SELECT authorised_value, lib FROM authorised_values'; $query .= ' LEFT JOIN authorised_values_branches ON ( id = av_id )' if $branch_limit; $query .= ' WHERE category = ?'; $query .= ' AND ( branchcode = ? OR branchcode IS NULL )' if $branch_limit; @@ -370,13 +375,13 @@ sub build_authorized_values_list { $id_subfield = "00" if $id_subfield eq "@"; return { - type => 'select', - id => "tag_".$tag."_subfield_".$id_subfield."_".$index_tag."_".$index_subfield, - name => "tag_".$tag."_subfield_".$id_subfield."_".$index_tag."_".$index_subfield, - default => $value, - values => \@authorised_values, - labels => \%authorised_lib, - ( ( grep { $_ eq $category } ( qw(branches itemtypes cn_source) ) ) ? () : ( category => $category ) ), + type => 'select', + id => "tag_" . $tag . "_subfield_" . $id_subfield . "_" . $index_tag . "_" . $index_subfield, + name => "tag_" . $tag . "_subfield_" . $id_subfield . "_" . $index_tag . "_" . $index_subfield, + default => $value, + values => \@authorised_values, + labels => \%authorised_lib, + ( ( grep { $_ eq $category } (qw(branches itemtypes cn_source)) ) ? () : ( category => $category ) ), }; } @@ -388,7 +393,7 @@ sub build_authorized_values_list { =cut sub create_key { - return int(rand(1000000)); + return int( rand(1000000) ); } 1; diff --git a/Koha/UI/Form/Builder/Item.pm b/Koha/UI/Form/Builder/Item.pm index cbc52522c3..9ec651e186 100644 --- a/Koha/UI/Form/Builder/Item.pm +++ b/Koha/UI/Form/Builder/Item.pm @@ -16,13 +16,13 @@ package Koha::UI::Form::Builder::Item; # along with Koha; if not, see . use Modern::Perl; -use feature qw(fc); +use feature qw(fc); use List::Util qw( any ); use MARC::Record; use C4::Context; -use C4::Biblio qw( GetFrameworkCode GetMarcStructure IsMarcStructureInternal ); -use C4::Koha qw( GetAuthorisedValues ); +use C4::Biblio qw( GetFrameworkCode GetMarcStructure IsMarcStructureInternal ); +use C4::Koha qw( GetAuthorisedValues ); use C4::ClassSource qw( GetClassSources ); use Koha::Biblios; @@ -56,13 +56,12 @@ For edition, an hashref representing the item to edit item must be passed. =cut - sub new { my ( $class, $params ) = @_; my $self; $self->{biblionumber} = $params->{biblionumber}; - $self->{item} = $params->{item}; + $self->{item} = $params->{item}; bless $self, $class; return $self; @@ -76,18 +75,18 @@ Generate subfield's info for given tag, subfieldtag, etc. sub generate_subfield_form { - my ($self, $params) = @_; - my $tag = $params->{tag}; - my $subfieldtag = $params->{subfieldtag}; - my $value = $params->{value}; - my $tagslib = $params->{tagslib}; - my $libraries = $params->{libraries}; - my $marc_record = $params->{marc_record}; - my $restricted_edition = $params->{restricted_editition}; + my ( $self, $params ) = @_; + my $tag = $params->{tag}; + my $subfieldtag = $params->{subfieldtag}; + my $value = $params->{value}; + my $tagslib = $params->{tagslib}; + my $libraries = $params->{libraries}; + my $marc_record = $params->{marc_record}; + my $restricted_edition = $params->{restricted_editition}; my $prefill_with_default_values = $params->{prefill_with_default_values}; - my $branch_limit = $params->{branch_limit}; - my $default_branches_empty = $params->{default_branches_empty}; - my $readonly = $params->{readonly}; + my $branch_limit = $params->{branch_limit}; + my $default_branches_empty = $params->{default_branches_empty}; + my $readonly = $params->{readonly}; my $item = $self->{item}; my $subfield = $tagslib->{$tag}{$subfieldtag}; @@ -101,32 +100,25 @@ sub generate_subfield_form { my $index_subfield = int( rand(1000000) ); if ( $subfieldtag eq '@' ) { $subfield_data{id} = "tag_" . $tag . "_subfield_00_" . $index_subfield; - } - else { - $subfield_data{id} = - "tag_" . $tag . "_subfield_" . $subfieldtag . "_" . $index_subfield; + } else { + $subfield_data{id} = "tag_" . $tag . "_subfield_" . $subfieldtag . "_" . $index_subfield; } - $subfield_data{tag} = $tag; - $subfield_data{subfield} = $subfieldtag; - $subfield_data{marc_lib} = - "{lib} . "\">" - . $subfield->{lib} - . ""; + $subfield_data{tag} = $tag; + $subfield_data{subfield} = $subfieldtag; + $subfield_data{marc_lib} = "{lib} . "\">" . $subfield->{lib} . ""; $subfield_data{mandatory} = $subfield->{mandatory}; $subfield_data{important} = $subfield->{important}; $subfield_data{repeatable} = $subfield->{repeatable}; $subfield_data{maxlength} = $subfield->{maxlength}; $subfield_data{display_order} = $subfield->{display_order}; - $subfield_data{kohafield} = - $subfield->{kohafield} || 'items.more_subfields_xml'; + $subfield_data{kohafield} = $subfield->{kohafield} || 'items.more_subfields_xml'; if ( $prefill_with_default_values && ( !defined($value) || $value eq '' ) ) { - $value = $subfield->{defaultvalue} if !$item->{itemnumber}; # apply defaultvalue only to new items + $value = $subfield->{defaultvalue} if !$item->{itemnumber}; # apply defaultvalue only to new items if ($value) { -# get today date & replace <>, <>, <>, <
> if provided in the default value + # get today date & replace <>, <>, <>, <
> if provided in the default value my $today_dt = dt_from_string; my $year = $today_dt->strftime('%Y'); my $shortyear = $today_dt->strftime('%y'); @@ -152,23 +144,19 @@ sub generate_subfield_form { defined $subfield->{kohafield} ? $columns->{ $subfield->{kohafield} =~ s|^items\.||r }->{data_type} : undef; $subfield_data{visibility} = "display:none;" - if ( ( $subfield->{hidden} > 4 ) || ( $subfield->{hidden} <= -4 ) ); + if ( ( $subfield->{hidden} > 4 ) || ( $subfield->{hidden} <= -4 ) ); my $pref_itemcallnumber = C4::Context->preference('itemcallnumber'); - if ( $prefill_with_default_values + if ( $prefill_with_default_values && !$value && $subfield->{kohafield} && $subfield->{kohafield} eq 'items.itemcallnumber' && $pref_itemcallnumber && $marc_record ) { - foreach - my $pref_itemcallnumber_part ( split( /,/, $pref_itemcallnumber ) ) - { - my $CNtag = - substr( $pref_itemcallnumber_part, 0, 3 ); # 3-digit tag number - my $CNsubfields = - substr( $pref_itemcallnumber_part, 3 ); # Any and all subfields + foreach my $pref_itemcallnumber_part ( split( /,/, $pref_itemcallnumber ) ) { + my $CNtag = substr( $pref_itemcallnumber_part, 0, 3 ); # 3-digit tag number + my $CNsubfields = substr( $pref_itemcallnumber_part, 3 ); # Any and all subfields $CNsubfields = undef if $CNsubfields eq ''; my $temp2 = $marc_record->field($CNtag); @@ -184,9 +172,8 @@ sub generate_subfield_form { # builds list, depending on authorised value... if ( $subfield->{authorised_value} eq "LOST" ) { - my $ClaimReturnedLostValue = - C4::Context->preference('ClaimReturnedLostValue'); - my $claim = Koha::Checkouts::ReturnClaims->find( + my $ClaimReturnedLostValue = C4::Context->preference('ClaimReturnedLostValue'); + my $claim = Koha::Checkouts::ReturnClaims->find( { itemnumber => $item->{itemnumber}, resolution => undef, @@ -204,36 +191,30 @@ sub generate_subfield_form { push @authorised_values, $r->{authorised_value}; $authorised_lib{ $r->{authorised_value} } = $r->{lib}; } - } - elsif ( $subfield->{authorised_value} eq "branches" ) { + } elsif ( $subfield->{authorised_value} eq "branches" ) { push @authorised_values, "" if $default_branches_empty; foreach my $thisbranch (@$libraries) { push @authorised_values, $thisbranch->{branchcode}; $authorised_lib{ $thisbranch->{branchcode} } = - $thisbranch->{branchname}; + $thisbranch->{branchname}; $value = $thisbranch->{branchcode} - if $thisbranch->{selected} && !$value; + if $thisbranch->{selected} && !$value; } - } - elsif ( $subfield->{authorised_value} eq "itemtypes" ) { + } elsif ( $subfield->{authorised_value} eq "itemtypes" ) { push @authorised_values, ""; my $itemtypes; if ($branch_limit) { - $itemtypes = Koha::ItemTypes->search_with_localization( - { branchcode => $branch_limit } ); - } - else { + $itemtypes = Koha::ItemTypes->search_with_localization( { branchcode => $branch_limit } ); + } else { $itemtypes = Koha::ItemTypes->search_with_localization; } while ( my $itemtype = $itemtypes->next ) { push @authorised_values, $itemtype->itemtype; - $authorised_lib{ $itemtype->itemtype } = - $itemtype->translated_description; + $authorised_lib{ $itemtype->itemtype } = $itemtype->translated_description; } - if (!$value && $biblionumber) { - my $itype_sth = $dbh->prepare( - "SELECT itemtype FROM biblioitems WHERE biblionumber = ?"); + if ( !$value && $biblionumber ) { + my $itype_sth = $dbh->prepare("SELECT itemtype FROM biblioitems WHERE biblionumber = ?"); $itype_sth->execute($biblionumber); my ($biblio_itemtype) = $itype_sth->fetchrow_array; @@ -244,13 +225,11 @@ sub generate_subfield_form { } #---- class_sources - } - elsif ( $subfield->{authorised_value} eq "cn_source" ) { + } elsif ( $subfield->{authorised_value} eq "cn_source" ) { push @authorised_values, ""; - my $class_sources = GetClassSources(); - my $default_source = - C4::Context->preference("DefaultClassificationSource"); + my $class_sources = GetClassSources(); + my $default_source = C4::Context->preference("DefaultClassificationSource"); foreach my $class_source ( sort { fc($a) cmp fc($b) } keys %$class_sources ) { next @@ -264,8 +243,7 @@ sub generate_subfield_form { $value = $default_source if !$value && $prefill_with_default_values; #---- "true" authorised value - } - else { + } else { push @authorised_values, qq{}; my $av = GetAuthorisedValues( $subfield->{authorised_value} ); for my $r (@$av) { @@ -281,29 +259,22 @@ sub generate_subfield_form { maxlength => $subfield_data{maxlength}, value => $value, ( - ( - grep { $_ eq $subfield->{authorised_value} } - (qw(branches itemtypes cn_source)) - ) ? () : ( category => $subfield->{authorised_value} ) + ( grep { $_ eq $subfield->{authorised_value} } (qw(branches itemtypes cn_source)) ) + ? () + : ( category => $subfield->{authorised_value} ) ), }; - } - else { + } else { $subfield_data{marc_value} = { - type => 'select', - id => "tag_" - . $tag - . "_subfield_" - . $subfieldtag . "_" - . $index_subfield, + type => 'select', + id => "tag_" . $tag . "_subfield_" . $subfieldtag . "_" . $index_subfield, values => \@authorised_values, labels => \%authorised_lib, default => $value, ( - ( - grep { $_ eq $subfield->{authorised_value} } - (qw(branches itemtypes cn_source)) - ) ? () : ( category => $subfield->{authorised_value} ) + ( grep { $_ eq $subfield->{authorised_value} } (qw(branches itemtypes cn_source)) ) + ? () + : ( category => $subfield->{authorised_value} ) ), }; } @@ -318,21 +289,20 @@ sub generate_subfield_form { value => $value, authtypecode => $subfield->{authtypecode}, }; - } - elsif ( defined $subfield_data{data_type} && $subfield_data{data_type} eq 'date' ) { + } elsif ( defined $subfield_data{data_type} && $subfield_data{data_type} eq 'date' ) { $subfield_data{marc_value} = { - type => 'date_field', - id => $subfield_data{id}, + type => 'date_field', + id => $subfield_data{id}, value => $value, - } - } - elsif ( defined $subfield_data{data_type} && $subfield_data{data_type} eq 'datetime' ) { + }; + } elsif ( defined $subfield_data{data_type} && $subfield_data{data_type} eq 'datetime' ) { $subfield_data{marc_value} = { - type => 'datetime_field', - id => $subfield_data{id}, + type => 'datetime_field', + id => $subfield_data{id}, value => $value, - } + }; } + # it's a plugin field elsif ( $subfield->{value_builder} ) { # plugin require Koha::FrameworkPlugin; @@ -344,7 +314,7 @@ sub generate_subfield_form { ); my $pars = { dbh => $dbh, - record => $marc_record, #Note: could be undefined + record => $marc_record, #Note: could be undefined tagslib => $tagslib, id => $subfield_data{id}, }; @@ -360,8 +330,7 @@ sub generate_subfield_form { nopopup => $plugin->noclick, javascript => $plugin->javascript, }; - } - else { + } else { warn $plugin->errstr; $subfield_data{marc_value} = { type => 'text', @@ -370,31 +339,27 @@ sub generate_subfield_form { value => $value, }; # supply default input form } - } - elsif ( $tag eq '' ) { # it's an hidden field + } elsif ( $tag eq '' ) { # it's an hidden field $subfield_data{marc_value} = { type => 'hidden', id => $subfield_data{id}, maxlength => $subfield_data{maxlength}, value => $value, }; - } - elsif ( $subfield->{'hidden'} ) - { # FIXME: shouldn't input type be "hidden" ? + } elsif ( $subfield->{'hidden'} ) { # FIXME: shouldn't input type be "hidden" ? $subfield_data{marc_value} = { type => 'text', id => $subfield_data{id}, maxlength => $subfield_data{maxlength}, value => $value, }; - } - elsif ( + } elsif ( ( $value and length($value) > 100 ) or ( C4::Context->preference("marcflavour") eq "UNIMARC" and 300 <= $tag && $tag < 400 && $subfieldtag eq 'a' ) or ( C4::Context->preference("marcflavour") eq "MARC21" and 500 <= $tag && $tag < 600 ) - ) + ) { # oversize field (textarea) $subfield_data{marc_value} = { @@ -402,8 +367,8 @@ sub generate_subfield_form { id => $subfield_data{id}, value => $value, }; - } - else { + } else { + # it's a standard field $subfield_data{marc_value} = { type => 'text', @@ -499,34 +464,35 @@ When duplicating an item we do not want to retrieve the subfields that are hidde sub edit_form { my ( $self, $params ) = @_; - my $branchcode = $params->{branchcode}; - my $restricted_edition = $params->{restricted_editition}; - my $subfields_to_prefill = $params->{subfields_to_prefill} || []; - my $subfields_to_allow = $params->{subfields_to_allow} || []; + my $branchcode = $params->{branchcode}; + my $restricted_edition = $params->{restricted_editition}; + my $subfields_to_prefill = $params->{subfields_to_prefill} || []; + my $subfields_to_allow = $params->{subfields_to_allow} || []; my $ignore_not_allowed_subfields = $params->{ignore_not_allowed_subfields}; - my $kohafields_to_ignore = $params->{kohafields_to_ignore} || []; - my $prefill_with_default_values = $params->{prefill_with_default_values}; - my $branch_limit = $params->{branch_limit}; - my $default_branches_empty = $params->{default_branches_empty}; - my $ignore_invisible_subfields = $params->{ignore_invisible_subfields} || 0; + my $kohafields_to_ignore = $params->{kohafields_to_ignore} || []; + my $prefill_with_default_values = $params->{prefill_with_default_values}; + my $branch_limit = $params->{branch_limit}; + my $default_branches_empty = $params->{default_branches_empty}; + my $ignore_invisible_subfields = $params->{ignore_invisible_subfields} || 0; my $libraries = - Koha::Libraries->search( {}, { order_by => ['branchname'] } )->unblessed; + Koha::Libraries->search( {}, { order_by => ['branchname'] } )->unblessed; for my $library (@$libraries) { $library->{selected} = 1 if $branchcode && $library->{branchcode} eq $branchcode; } my $item = $self->{item}; my $marc_more_subfields = $item->{more_subfields_xml} - ? + ? + # FIXME Use Maybe MARC::Record::new_from_xml if encoding issues on subfield (??) MARC::Record->new_from_xml( $item->{more_subfields_xml}, 'UTF-8' ) - : undef; + : undef; - my $biblionumber = $self->{biblionumber}; - my $biblio = Koha::Biblios->find($biblionumber); - my $frameworkcode = $biblio ? GetFrameworkCode($biblionumber) : q{}; - my $marc_record = $biblio ? $biblio->metadata->record : undef; + my $biblionumber = $self->{biblionumber}; + my $biblio = Koha::Biblios->find($biblionumber); + my $frameworkcode = $biblio ? GetFrameworkCode($biblionumber) : q{}; + my $marc_record = $biblio ? $biblio->metadata->record : undef; my @subfields; my $tagslib = GetMarcStructure( 1, $frameworkcode ); foreach my $tag ( keys %{$tagslib} ) { @@ -538,21 +504,18 @@ sub edit_form { next if IsMarcStructureInternal($subfield); next if $subfield->{tab} ne "10"; next - if grep { $subfield->{kohafield} && $subfield->{kohafield} eq $_ } - @$kohafields_to_ignore; + if grep { $subfield->{kohafield} && $subfield->{kohafield} eq $_ } @$kohafields_to_ignore; next - if $ignore_invisible_subfields - && ( $subfield->{hidden} > 4 || $subfield->{hidden} <= -4 ); + if $ignore_invisible_subfields + && ( $subfield->{hidden} > 4 || $subfield->{hidden} <= -4 ); my $readonly; - if ( - @$subfields_to_allow && !grep { - sprintf( "%s\$%s", $subfield->{tagfield}, $subfield->{tagsubfield} ) eq $_ - } @$subfields_to_allow - ) + if ( @$subfields_to_allow + && !grep { sprintf( "%s\$%s", $subfield->{tagfield}, $subfield->{tagsubfield} ) eq $_ } + @$subfields_to_allow ) { - next if $ignore_not_allowed_subfields; + next if $ignore_not_allowed_subfields; $readonly = 1 if $restricted_edition; } @@ -560,11 +523,8 @@ sub edit_form { my $subfield_data; - if ( - !@$subfields_to_prefill - || ( @$subfields_to_prefill && grep { $_ eq $subfieldtag } - @$subfields_to_prefill ) - ) + if ( !@$subfields_to_prefill + || ( @$subfields_to_prefill && grep { $_ eq $subfieldtag } @$subfields_to_prefill ) ) { my $kohafield = $subfield->{kohafield}; if ($kohafield) { @@ -572,12 +532,12 @@ sub edit_form { # This is a mapped field ( my $attribute = $kohafield ) =~ s|^items\.||; push @values, $subfield->{repeatable} - ? split '\s\|\s', $item->{$attribute} - : $item->{$attribute} - if defined $item->{$attribute}; - } - else { - # Not mapped, picked the values from more_subfields_xml's MARC + ? split '\s\|\s', $item->{$attribute} + : $item->{$attribute} + if defined $item->{$attribute}; + } else { + + # Not mapped, picked the values from more_subfields_xml's MARC if ($marc_more_subfields) { for my $f ( $marc_more_subfields->fields($tag) ) { push @values, $f->subfield($subfieldtag); @@ -591,17 +551,17 @@ sub edit_form { for my $value (@values) { my $subfield_data = $self->generate_subfield_form( { - tag => $tag, - subfieldtag => $subfieldtag, - value => $value, - tagslib => $tagslib, - libraries => $libraries, - marc_record => $marc_record, #Note: could be undefined - restricted_edition => $restricted_edition, + tag => $tag, + subfieldtag => $subfieldtag, + value => $value, + tagslib => $tagslib, + libraries => $libraries, + marc_record => $marc_record, #Note: could be undefined + restricted_edition => $restricted_edition, prefill_with_default_values => $prefill_with_default_values, - branch_limit => $branch_limit, - default_branches_empty => $default_branches_empty, - readonly => $readonly + branch_limit => $branch_limit, + default_branches_empty => $default_branches_empty, + readonly => $readonly } ); push @subfields, $subfield_data; @@ -609,10 +569,7 @@ sub edit_form { } } - @subfields = sort { - $a->{display_order} <=> $b->{display_order} - || $a->{subfield} cmp $b->{subfield} - } @subfields; + @subfields = sort { $a->{display_order} <=> $b->{display_order} || $a->{subfield} cmp $b->{subfield} } @subfields; return \@subfields; diff --git a/Koha/UI/Table/Builder/Items.pm b/Koha/UI/Table/Builder/Items.pm index b3e4181e29..901879d8c8 100644 --- a/Koha/UI/Table/Builder/Items.pm +++ b/Koha/UI/Table/Builder/Items.pm @@ -17,7 +17,7 @@ package Koha::UI::Table::Builder::Items; use Modern::Perl; use List::MoreUtils qw( uniq ); -use C4::Biblio qw( GetMarcStructure GetMarcFromKohaField IsMarcStructureInternal ); +use C4::Biblio qw( GetMarcStructure GetMarcFromKohaField IsMarcStructureInternal ); use Koha::Items; =head1 NAME @@ -74,7 +74,7 @@ sub build_table { my $patron = $params->{patron}; - my %itemnumbers_to_idx = map { $self->{itemnumbers}->[$_] => $_ } 0..$#{$self->{itemnumbers}}; + my %itemnumbers_to_idx = map { $self->{itemnumbers}->[$_] => $_ } 0 .. $#{ $self->{itemnumbers} }; my $items = Koha::Items->search( { itemnumber => $self->{itemnumbers} } ); @@ -83,13 +83,13 @@ sub build_table { my $item_info = $item->columns_to_str; $item_info = { %$item_info, - index => $itemnumbers_to_idx{$item->itemnumber}, + index => $itemnumbers_to_idx{ $item->itemnumber }, biblio => $item->biblio, safe_to_delete => $item->safe_to_delete, holds => $item->biblio->holds->count, item_holds => $item->holds->count, - is_checked_out => $item->checkout ? 1 : 0, - nomod => $patron ? !$patron->can_edit_items_from($item->homebranch) : 0, + is_checked_out => $item->checkout ? 1 : 0, + nomod => $patron ? !$patron->can_edit_items_from( $item->homebranch ) : 0, }; push @items, $item_info; } @@ -116,15 +116,14 @@ sub _build_headers { my $item = $_; map { defined $item->{$_} - && !ref( $item->{$_} ) # biblio and safe_to_delete are objects - && $item->{$_} ne "" - ? $_ - : () - } keys %$item + && !ref( $item->{$_} ) # biblio and safe_to_delete are objects + && $item->{$_} ne "" + ? $_ + : () + } keys %$item } @$items; - my ( $itemtag, $itemsubfield ) = - C4::Biblio::GetMarcFromKohaField("items.itemnumber"); + my ( $itemtag, $itemsubfield ) = C4::Biblio::GetMarcFromKohaField("items.itemnumber"); my $tagslib = C4::Biblio::GetMarcStructure(1); my $subfieldcode_attribute_mappings; for my $subfield_code ( keys %{ $tagslib->{$itemtag} } ) { @@ -137,8 +136,7 @@ sub _build_headers { my $attribute; if ( $subfield->{kohafield} ) { ( $attribute = $subfield->{kohafield} ) =~ s|^items\.||; - } - else { + } else { $attribute = $subfield_code; # It's in more_subfields_xml } next unless grep { $attribute eq $_ } @witness_attributes; diff --git a/Koha/UploadedFile.pm b/Koha/UploadedFile.pm index 13ec2eaadb..f5906b9cf9 100644 --- a/Koha/UploadedFile.pm +++ b/Koha/UploadedFile.pm @@ -77,12 +77,11 @@ sub delete { my $retval = $self->SUPER::delete; return $retval if $params->{keep_file}; - if( ! -e $file ) { + if ( !-e $file ) { if ( $self->permanent ) { - warn "Removing record for $name within category ". - $self->uploadcategorycode. ", but file was missing."; + warn "Removing record for $name within category " . $self->uploadcategorycode . ", but file was missing."; } - } elsif( ! unlink($file) ) { + } elsif ( !unlink($file) ) { warn "Problem while deleting: $file"; } return $retval; @@ -95,13 +94,13 @@ Returns the fully qualified path name for an uploaded file. =cut sub full_path { - my ( $self ) = @_; + my ($self) = @_; my $path = File::Spec->catfile( - $self->permanent - ? $self->permanent_directory - : C4::Context->temporary_directory, + $self->permanent + ? $self->permanent_directory + : C4::Context->temporary_directory, $self->dir, - $self->hashvalue. '_'. $self->filename, + $self->hashvalue . '_' . $self->filename, ); return $path; } @@ -113,7 +112,7 @@ Returns a file handle for an uploaded file. =cut sub file_handle { - my ( $self ) = @_; + my ($self) = @_; $self->{_file_handle} = IO::File->new( $self->full_path, "r" ); return if !$self->{_file_handle}; $self->{_file_handle}->binmode; @@ -129,11 +128,11 @@ Will be extended by report 14282 =cut sub httpheaders { - my ( $self ) = @_; - if( $self->filename =~ /\.pdf$/ ) { + my ($self) = @_; + if ( $self->filename =~ /\.pdf$/ ) { return ( - '-type' => 'application/pdf', - 'Content-Disposition' => 'inline; filename="'.$self->filename.'"', + '-type' => 'application/pdf', + 'Content-Disposition' => 'inline; filename="' . $self->filename . '"', ); } else { return ( @@ -152,7 +151,7 @@ Returns root directory for permanent storage =cut sub permanent_directory { - my ( $class ) = @_; + my ($class) = @_; return C4::Context->config('upload_path'); } diff --git a/Koha/UploadedFiles.pm b/Koha/UploadedFiles.pm index c453c6f977..1104e2625c 100644 --- a/Koha/UploadedFiles.pm +++ b/Koha/UploadedFiles.pm @@ -68,14 +68,14 @@ as the number of files. sub delete { my ( $self, $params ) = @_; - $self = Koha::UploadedFiles->new if !ref($self); # handle class call - # We use the individual delete on each resultset record + $self = Koha::UploadedFiles->new if !ref($self); # handle class call + # We use the individual delete on each resultset record my $rv = 0; - while( my $row = $self->next ) { - my $deleted = eval { $row->delete( $params ) }; + while ( my $row = $self->next ) { + my $deleted = eval { $row->delete($params) }; $rv++ if $deleted && !$@; } - return $rv==0 ? "0E0" : $rv; + return $rv == 0 ? "0E0" : $rv; } =head3 delete_temporary @@ -91,18 +91,20 @@ Return value: see delete. sub delete_temporary { my ( $self, $params ) = @_; my $days = C4::Context->preference('UploadPurgeTemporaryFilesDays'); - if( exists $params->{override_pref} ) { + if ( exists $params->{override_pref} ) { $days = $params->{override_pref}; - } elsif( !defined($days) || $days eq '' ) { # allow 0, not NULL or "" + } elsif ( !defined($days) || $days eq '' ) { # allow 0, not NULL or "" return "0E0"; } my $dt = dt_from_string(); $dt->subtract( days => $days ); my $parser = Koha::Database->new->schema->storage->datetime_parser; - return $self->search({ - permanent => [ undef, 0 ], - dtcreated => { '<' => $parser->format_datetime($dt) }, - })->delete; + return $self->search( + { + permanent => [ undef, 0 ], + dtcreated => { '<' => $parser->format_datetime($dt) }, + } + )->delete; } =head3 delete_missing @@ -123,22 +125,23 @@ as delete does. sub delete_missing { my ( $self, $params ) = @_; - $self = Koha::UploadedFiles->new if !ref($self); # handle class call + $self = Koha::UploadedFiles->new if !ref($self); # handle class call my $rv = 0; - while( my $row = $self->next ) { + while ( my $row = $self->next ) { my $file = $row->full_path; next if -e $file; - if( $params->{keep_record} ) { + if ( $params->{keep_record} ) { $rv++; next; } + # We are passing keep_file since we already know that the file # is missing and we do not want to see the warning # Apply the same logic as in delete for the return value - my $deleted = eval { $row->delete({ keep_file => 1 }) }; + my $deleted = eval { $row->delete( { keep_file => 1 } ) }; $rv++ if $deleted && !$@; } - return $rv==0 ? "0E0" : $rv; + return $rv == 0 ? "0E0" : $rv; } =head3 search_term @@ -152,15 +155,17 @@ Is only a wrapper around Koha::Objects search. Has similar return value. sub search_term { my ( $self, $params ) = @_; - my $term = $params->{term} // ''; + my $term = $params->{term} // ''; my %public = (); - if( !$params->{include_private} ) { + if ( !$params->{include_private} ) { %public = ( public => 1 ); } return $self->search( - [ { filename => { like => '%'.$term.'%' }, %public }, - { hashvalue => { like => '%'.$params->{term}.'%' }, %public } ], - { order_by => { -asc => 'id' }}, + [ + { filename => { like => '%' . $term . '%' }, %public }, + { hashvalue => { like => '%' . $params->{term} . '%' }, %public } + ], + { order_by => { -asc => 'id' } }, ); } @@ -173,9 +178,9 @@ getCategories returns a list of upload category codes and names =cut sub getCategories { - my ( $class ) = @_; + my ($class) = @_; my $cats = C4::Koha::GetAuthorisedValues('UPLOAD'); - [ map {{ code => $_->{authorised_value}, name => $_->{lib} }} @$cats ]; + [ map { { code => $_->{authorised_value}, name => $_->{lib} } } @$cats ]; } =head3 _type diff --git a/Koha/Uploader.pm b/Koha/Uploader.pm index 39aee036b9..99329dfa27 100644 --- a/Koha/Uploader.pm +++ b/Koha/Uploader.pm @@ -66,7 +66,7 @@ use constant ERR_ROOT => 'UPLERR_NO_ROOT_DIR'; use constant ERR_TEMP => 'UPLERR_NO_TEMP_DIR'; use Modern::Perl; -use CGI; # no utf8 flag, since it may interfere with binary uploads +use CGI; # no utf8 flag, since it may interfere with binary uploads use Digest::MD5; use Encode; use IO::File; @@ -79,7 +79,7 @@ use C4::Koha; use Koha::UploadedFile; use Koha::UploadedFiles; -__PACKAGE__->mk_ro_accessors( qw|| ); +__PACKAGE__->mk_ro_accessors(qw||); =head1 INSTANCE METHODS @@ -95,7 +95,7 @@ __PACKAGE__->mk_ro_accessors( qw|| ); sub new { my ( $class, $params ) = @_; my $self = $class->SUPER::new(); - $self->_init( $params ); + $self->_init($params); return $self; } @@ -106,14 +106,14 @@ sub new { =cut sub cgi { - my ( $self ) = @_; + my ($self) = @_; # Next call handles the actual upload via CGI hook. # The third parameter (0) below means: no CGI temporary storage. # Cancelling an upload will make CGI abort the script; no problem, # the file(s) without db entry will be removed later. my $query = CGI::->new( sub { $self->_hook(@_); }, {}, 0 ); - if( $query ) { + if ($query) { $self->_done; return $query; } @@ -126,7 +126,7 @@ sub cgi { =cut sub count { - my ( $self ) = @_; + my ($self) = @_; return scalar grep { !exists $self->{files}->{$_}->{errcode} } keys %{ $self->{files} }; } @@ -137,11 +137,11 @@ sub count { =cut sub result { - my ( $self ) = @_; - my @a = map { $self->{files}->{$_}->{id} } + my ($self) = @_; + my @a = map { $self->{files}->{$_}->{id} } grep { !exists $self->{files}->{$_}->{errcode} } keys %{ $self->{files} }; - return @a? ( join ',', @a ): undef; + return @a ? ( join ',', @a ) : undef; } =head2 err @@ -152,11 +152,11 @@ sub result { =cut sub err { - my ( $self ) = @_; + my ($self) = @_; my $err; foreach my $f ( keys %{ $self->{files} } ) { my $e = $self->{files}->{$f}->{errcode}; - $err->{ $f }->{code} = $e if $e; + $err->{$f}->{code} = $e if $e; } return $err; } @@ -170,15 +170,15 @@ sub err { =cut sub allows_add_by { - my ( $class, $userid ) = @_; # do not confuse with borrowernumber + my ( $class, $userid ) = @_; # do not confuse with borrowernumber my $flags = [ - { tools => 'upload_general_files' }, - { circulate => 'circulate_remaining_permissions' }, - { tools => 'stage_marc_import' }, - { tools => 'upload_local_cover_images' }, + { tools => 'upload_general_files' }, + { circulate => 'circulate_remaining_permissions' }, + { tools => 'stage_marc_import' }, + { tools => 'upload_local_cover_images' }, ]; require C4::Auth; - foreach( @$flags ) { + foreach (@$flags) { return 1 if C4::Auth::haspermission( $userid, $_ ); } return; @@ -192,26 +192,26 @@ sub _init { my ( $self, $params ) = @_; $self->{rootdir} = Koha::UploadedFile->permanent_directory; - $self->{tmpdir} = C4::Context::temporary_directory; + $self->{tmpdir} = C4::Context::temporary_directory; - $params->{tmp} = $params->{temp} if !exists $params->{tmp}; - $self->{temporary} = $params->{tmp}? 1: 0; #default false - if( $params->{tmp} ) { - my $db = C4::Context->config('database'); + $params->{tmp} = $params->{temp} if !exists $params->{tmp}; + $self->{temporary} = $params->{tmp} ? 1 : 0; #default false + if ( $params->{tmp} ) { + my $db = C4::Context->config('database'); $self->{category} = KOHA_UPLOAD; $self->{category} =~ s/koha/$db/; } else { $self->{category} = $params->{category} || KOHA_UPLOAD; } - $self->{files} = {}; - $self->{uid} = C4::Context->userenv->{number} if C4::Context->userenv; - $self->{public} = $params->{public}? 1: undef; + $self->{files} = {}; + $self->{uid} = C4::Context->userenv->{number} if C4::Context->userenv; + $self->{public} = $params->{public} ? 1 : undef; } sub _fh { my ( $self, $filename ) = @_; - if( $self->{files}->{$filename} ) { + if ( $self->{files}->{$filename} ) { return $self->{files}->{$filename}->{fh}; } } @@ -219,33 +219,39 @@ sub _fh { sub _create_file { my ( $self, $filename ) = @_; my $fh; - if( $self->{files}->{$filename} && - $self->{files}->{$filename}->{errcode} ) { + if ( $self->{files}->{$filename} + && $self->{files}->{$filename}->{errcode} ) + { #skip - } elsif( !$self->{temporary} && !$self->{rootdir} ) { - $self->{files}->{$filename}->{errcode} = ERR_ROOT; #no rootdir - } elsif( $self->{temporary} && !$self->{tmpdir} ) { - $self->{files}->{$filename}->{errcode} = ERR_TEMP; #no tempdir + } elsif ( !$self->{temporary} && !$self->{rootdir} ) { + $self->{files}->{$filename}->{errcode} = ERR_ROOT; #no rootdir + } elsif ( $self->{temporary} && !$self->{tmpdir} ) { + $self->{files}->{$filename}->{errcode} = ERR_TEMP; #no tempdir } else { - my $dir = $self->_dir; + my $dir = $self->_dir; my $hashval = $self->{files}->{$filename}->{hash}; - my $fn = $hashval. '_'. $filename; + my $fn = $hashval . '_' . $filename; # if the file exists and it is registered, then set error # if it exists, but is not in the database, we will overwrite - if( -e "$dir/$fn" && - Koha::UploadedFiles->search({ - hashvalue => $hashval, - uploadcategorycode => $self->{category}, - })->count ) { + if ( + -e "$dir/$fn" + && Koha::UploadedFiles->search( + { + hashvalue => $hashval, + uploadcategorycode => $self->{category}, + } + )->count + ) + { $self->{files}->{$filename}->{errcode} = ERR_EXISTS; return; } - $fh = IO::File->new( "$dir/$fn", "w"); - if( $fh ) { + $fh = IO::File->new( "$dir/$fn", "w" ); + if ($fh) { $fh->binmode; - $self->{files}->{$filename}->{fh}= $fh; + $self->{files}->{$filename}->{fh} = $fh; } else { $self->{files}->{$filename}->{errcode} = ERR_PERMS; } @@ -254,28 +260,28 @@ sub _create_file { } sub _dir { - my ( $self ) = @_; - my $dir = $self->{temporary}? $self->{tmpdir}: $self->{rootdir}; - $dir.= '/'. $self->{category}; + my ($self) = @_; + my $dir = $self->{temporary} ? $self->{tmpdir} : $self->{rootdir}; + $dir .= '/' . $self->{category}; mkdir $dir if !-d $dir; return $dir; } sub _hook { my ( $self, $filename, $buffer, $bytes_read, $data ) = @_; - $filename= Encode::decode_utf8( $filename ); # UTF8 chars in filename + $filename = Encode::decode_utf8($filename); # UTF8 chars in filename $filename =~ s/[^A-Za-z0-9\-\.]//g; $self->_compute( $filename, $buffer ); - my $fh = $self->_fh( $filename ) // $self->_create_file( $filename ); + my $fh = $self->_fh($filename) // $self->_create_file($filename); print $fh $buffer if $fh; } sub _done { - my ( $self ) = @_; + my ($self) = @_; $self->{done} = 1; foreach my $f ( keys %{ $self->{files} } ) { my $fh = $self->_fh($f); - $self->_register( $f, $fh? tell( $fh ): undef ) + $self->_register( $f, $fh ? tell($fh) : undef ) if !$self->{files}->{$f}->{errcode}; $fh->close if $fh; } @@ -283,30 +289,37 @@ sub _done { sub _register { my ( $self, $filename, $size ) = @_; - my $rec = Koha::UploadedFile->new({ - hashvalue => $self->{files}->{$filename}->{hash}, - filename => $filename, - dir => $self->{category}, - filesize => $size, - owner => $self->{uid}, - uploadcategorycode => $self->{category}, - public => $self->{public}, - permanent => $self->{temporary}? 0: 1, - })->store; + my $rec = Koha::UploadedFile->new( + { + hashvalue => $self->{files}->{$filename}->{hash}, + filename => $filename, + dir => $self->{category}, + filesize => $size, + owner => $self->{uid}, + uploadcategorycode => $self->{category}, + public => $self->{public}, + permanent => $self->{temporary} ? 0 : 1, + } + )->store; $self->{files}->{$filename}->{id} = $rec->id if $rec; } sub _compute { -# Computes hash value when sub hook feeds the first block -# For temporary files, the id is made unique with time + + # Computes hash value when sub hook feeds the first block + # For temporary files, the id is made unique with time my ( $self, $name, $block ) = @_; - if( !$self->{files}->{$name}->{hash} ) { - my $str = $name. ( $self->{uid} // '0' ). - ( $self->{temporary}? Time::HiRes::time(): '' ). - $self->{category}. substr( $block, 0, BYTES_DIGEST ); + if ( !$self->{files}->{$name}->{hash} ) { + my $str = + $name + . ( $self->{uid} // '0' ) + . ( $self->{temporary} ? Time::HiRes::time() : '' ) + . $self->{category} + . substr( $block, 0, BYTES_DIGEST ); + # since Digest cannot handle wide chars, we need to encode here # there could be a wide char in the filename or the category - my $h = Digest::MD5::md5_hex( Encode::encode_utf8( $str ) ); + my $h = Digest::MD5::md5_hex( Encode::encode_utf8($str) ); $self->{files}->{$name}->{hash} = $h; } } diff --git a/Koha/Util/FrameworkPlugin.pm b/Koha/Util/FrameworkPlugin.pm index bc2c8dabd5..14d6193e52 100644 --- a/Koha/Util/FrameworkPlugin.pm +++ b/Koha/Util/FrameworkPlugin.pm @@ -25,9 +25,10 @@ use Modern::Perl; use constant DEFAULT_008_POS_6_39 => 'b |||||||| |||| 00| 0 eng d'; our ( @ISA, @EXPORT_OK ); + BEGIN { require Exporter; - @ISA = qw( Exporter ); + @ISA = qw( Exporter ); @EXPORT_OK = qw( wrapper date_entered biblio_008 ); } @@ -45,11 +46,11 @@ Koha::Util::FrameworkPlugin - utility class with routines for framework plugins =cut sub wrapper { - my ( $str ) = @_; - return "space" if $str eq " "; + my ($str) = @_; + return "space" if $str eq " "; return "dblspace" if $str eq " "; - return "pipe" if $str eq "|"; - return "dblpipe" if $str eq "||"; + return "pipe" if $str eq "|"; + return "dblpipe" if $str eq "||"; return $str; } @@ -60,11 +61,12 @@ sub wrapper { =cut sub date_entered { + # find today's date - my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time); - $year +=1900; - $mon +=1; - return substr($year,2,2).sprintf ("%0.2d", $mon).sprintf ("%0.2d",$mday); + my ( $sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst ) = localtime(time); + $year += 1900; + $mon += 1; + return substr( $year, 2, 2 ) . sprintf( "%0.2d", $mon ) . sprintf( "%0.2d", $mday ); } =head2 biblio_008 @@ -76,11 +78,11 @@ sub date_entered { sub biblio_008 { my $result = date_entered() . DEFAULT_008_POS_6_39; - if( C4::Context->preference('DefaultCountryField008') ) { + if ( C4::Context->preference('DefaultCountryField008') ) { substr( $result, 15, 3 ) = pack( "A3", C4::Context->preference('DefaultCountryField008') ); } - if( C4::Context->preference('DefaultLanguageField008') ) { - substr( $result, 35, 3 ) = pack( "A3", C4::Context->preference('DefaultLanguageField008' ) ); + if ( C4::Context->preference('DefaultLanguageField008') ) { + substr( $result, 35, 3 ) = pack( "A3", C4::Context->preference('DefaultLanguageField008') ); } return $result; } diff --git a/Koha/Util/MARC.pm b/Koha/Util/MARC.pm index d3963e6e58..307c7f24f0 100644 --- a/Koha/Util/MARC.pm +++ b/Koha/Util/MARC.pm @@ -19,7 +19,7 @@ package Koha::Util::MARC; use Modern::Perl; -use constant OCLC_REGEX => qr/OCoLC/i; # made it case insensitive, includes the various oclc suffixes too +use constant OCLC_REGEX => qr/OCoLC/i; # made it case insensitive, includes the various oclc suffixes too =head1 NAME @@ -48,7 +48,7 @@ sub createMergeHash { !defined($tagslib) || ( defined( $tagslib->{$fieldtag} ) && $tagslib->{$fieldtag}->{'@'}->{'tab'} >= 0 ) - ) + ) { push @array, { tag => $fieldtag, @@ -56,8 +56,7 @@ sub createMergeHash { value => $field->data(), }; } - } - else { + } else { my @subfields = $field->subfields(); my @subfield_array; foreach my $subfield (@subfields) { @@ -67,7 +66,7 @@ sub createMergeHash { && defined $tagslib->{$fieldtag}->{ @$subfield[0] } && defined $tagslib->{$fieldtag}->{ @$subfield[0] }->{'tab'} && $tagslib->{$fieldtag}->{ @$subfield[0] }->{'tab'} >= 0 ) - ) + ) { push @subfield_array, { subtag => @$subfield[0], @@ -85,15 +84,15 @@ sub createMergeHash { && ( $tagslib->{$fieldtag}->{'tab'} ? $tagslib->{$fieldtag}->{'tab'} : 0 ) >= 0 ) ) && @subfield_array - ) + ) { push @array, { - tag => $fieldtag, - key => _createKey(), - indicator1 => $field->indicator(1), - indicator2 => $field->indicator(2), - subfield => [@subfield_array], - }; + tag => $fieldtag, + key => _createKey(), + indicator1 => $field->indicator(1), + indicator2 => $field->indicator(2), + subfield => [@subfield_array], + }; } } @@ -108,7 +107,7 @@ Create a random value to set it into the input name =cut sub _createKey { - return int(rand(1000000)); + return int( rand(1000000) ); } =head2 getAuthorityAuthorizedHeading @@ -127,8 +126,7 @@ sub getAuthorityAuthorizedHeading { foreach my $field ( $record->field('2..') ) { return $field->as_string('abcdefghijlmnopqrstuvwxyz'); } - } - else { + } else { foreach my $field ( $record->field('1..') ) { my $tag = $field->tag(); next if "152" eq $tag; @@ -138,41 +136,29 @@ sub getAuthorityAuthorizedHeading { # 9XX if ( $tag eq '100' ) { return $field->as_string('abcdefghjklmnopqrstvxyz68'); - } - elsif ( $tag eq '110' ) { + } elsif ( $tag eq '110' ) { return $field->as_string('abcdefghklmnoprstvxyz68'); - } - elsif ( $tag eq '111' ) { + } elsif ( $tag eq '111' ) { return $field->as_string('acdefghklnpqstvxyz68'); - } - elsif ( $tag eq '130' ) { + } elsif ( $tag eq '130' ) { return $field->as_string('adfghklmnoprstvxyz68'); - } - elsif ( $tag eq '148' ) { + } elsif ( $tag eq '148' ) { return $field->as_string('abvxyz68'); - } - elsif ( $tag eq '150' ) { + } elsif ( $tag eq '150' ) { return $field->as_string('abvxyz68'); - } - elsif ( $tag eq '151' ) { + } elsif ( $tag eq '151' ) { return $field->as_string('avxyz68'); - } - elsif ( $tag eq '155' ) { + } elsif ( $tag eq '155' ) { return $field->as_string('abvxyz68'); - } - elsif ( $tag eq '180' ) { + } elsif ( $tag eq '180' ) { return $field->as_string('vxyz68'); - } - elsif ( $tag eq '181' ) { + } elsif ( $tag eq '181' ) { return $field->as_string('vxyz68'); - } - elsif ( $tag eq '182' ) { + } elsif ( $tag eq '182' ) { return $field->as_string('vxyz68'); - } - elsif ( $tag eq '185' ) { + } elsif ( $tag eq '185' ) { return $field->as_string('vxyz68'); - } - else { + } else { return $field->as_string(); } } @@ -208,20 +194,22 @@ the value =cut sub set_marc_field { - my ($record, $marcField, $value) = @_; + my ( $record, $marcField, $value ) = @_; if ($marcField) { - my ($fieldTag, $subfieldCode) = split /\$/, $marcField; - if( !$subfieldCode ) { + my ( $fieldTag, $subfieldCode ) = split /\$/, $marcField; + if ( !$subfieldCode ) { warn "set_marc_field: Invalid marcField format: $marcField\n"; return; } my $field = $record->field($fieldTag); if ($field) { - $field->update($subfieldCode => $value); + $field->update( $subfieldCode => $value ); } else { - $field = MARC::Field->new($fieldTag, ' ', ' ', - $subfieldCode => $value); + $field = MARC::Field->new( + $fieldTag, ' ', ' ', + $subfieldCode => $value + ); $record->append_fields($field); } } @@ -239,15 +227,15 @@ sub set_marc_field { =cut sub find_marc_info { - my ( $params ) = @_; - my $record = $params->{record} or return; - my $field = $params->{field} or return; + my ($params) = @_; + my $record = $params->{record} or return; + my $field = $params->{field} or return; my $subfield = $params->{subfield}; - my $match = $params->{match}; + my $match = $params->{match}; my @rv; foreach my $f ( $record->field($field) ) { - if( $f->is_control_field ) { + if ( $f->is_control_field ) { push @rv, $f->data if !$match || $f->data =~ /$match/; last if @rv && !wantarray; } else { @@ -257,7 +245,7 @@ sub find_marc_info { } } } - return @rv if wantarray; + return @rv if wantarray; return $rv[0] if @rv; } @@ -286,10 +274,14 @@ sub strip_orgcode { sub oclc_number { my $record = shift; - return strip_orgcode( scalar find_marc_info({ - # Note: Field 035 same for MARC21 and UNIMARC - record => $record, field => '035', subfield => 'a', match => OCLC_REGEX, - })); + return strip_orgcode( + scalar find_marc_info( + { + # Note: Field 035 same for MARC21 and UNIMARC + record => $record, field => '035', subfield => 'a', match => OCLC_REGEX, + } + ) + ); } 1; diff --git a/Koha/Util/Navigation.pm b/Koha/Util/Navigation.pm index 75bde71fa1..a3d2942439 100644 --- a/Koha/Util/Navigation.pm +++ b/Koha/Util/Navigation.pm @@ -49,27 +49,27 @@ Utility class sub local_referer { my ( $cgi, $params ) = @_; - my $referer = $cgi->referer; + my $referer = $cgi->referer; my $fallback = $params->{fallback} // '/'; - my $staff = $params->{staff}; # no staff means OPAC + my $staff = $params->{staff}; # no staff means OPAC return $fallback if !$referer; - my $base = C4::Context->preference($staff ? 'staffClientBaseURL' : 'OPACBaseURL'); + my $base = C4::Context->preference( $staff ? 'staffClientBaseURL' : 'OPACBaseURL' ); my $rv; # Try ..BaseURL first, otherwise use CGI::url - if( $base ) { - if( $referer =~ m|^\Q$base\E|i && - $referer =~ /\/cgi-bin\/koha\// ) + if ($base) { + if ( $referer =~ m|^\Q$base\E|i + && $referer =~ /\/cgi-bin\/koha\// ) { $rv = substr( $referer, length($base) ); $rv =~ s/^\///; - $rv = '/'.$rv; + $rv = '/' . $rv; } } else { my $cgibase = $cgi->url( -base => 1 ); $cgibase =~ s/^https?://; - if( $referer =~ /$cgibase(\/cgi-bin\/koha\/.*)$/ ) { + if ( $referer =~ /$cgibase(\/cgi-bin\/koha\/.*)$/ ) { $rv = $1; } } diff --git a/Koha/Util/Normalize.pm b/Koha/Util/Normalize.pm index f05999de07..1c6c4ff198 100644 --- a/Koha/Util/Normalize.pm +++ b/Koha/Util/Normalize.pm @@ -22,11 +22,11 @@ use Modern::Perl; use parent qw( Exporter ); our @EXPORT = qw( - legacy_default - remove_spaces - upper_case - lower_case - ISBN + legacy_default + remove_spaces + upper_case + lower_case + ISBN ); =head1 NAME @@ -42,8 +42,8 @@ Default normalization function =cut sub legacy_default { - my ( $string ) = @_; - return if !defined( $string ); + my ($string) = @_; + return if !defined($string); $string = uc $string; @@ -62,8 +62,8 @@ Normalization function removing spaces =cut sub remove_spaces { - my ( $string ) = @_; - return if !defined( $string ); + my ($string) = @_; + return if !defined($string); $string =~ s/\s+//g; @@ -77,8 +77,8 @@ Normalization function converting characters into upper-case =cut sub upper_case { - my ( $string ) = @_; - return if !defined( $string ); + my ($string) = @_; + return if !defined($string); $string = uc $string; @@ -92,8 +92,8 @@ Normalization function converting characters into lower-case =cut sub lower_case { - my ( $string ) = @_; - return if !defined( $string ); + my ($string) = @_; + return if !defined($string); $string = lc $string; @@ -108,15 +108,17 @@ If string is not a valid ISBN we pass it through unaltered =cut sub ISBN { - my ( $string ) = @_; - return if !defined( $string ); + my ($string) = @_; + return if !defined($string); - my $isbn = C4::Koha::NormalizeISBN({ - isbn => $string, - format => 'ISBN-13', - strip_hyphens => 1, - return_invalid => 1, - }); + my $isbn = C4::Koha::NormalizeISBN( + { + isbn => $string, + format => 'ISBN-13', + strip_hyphens => 1, + return_invalid => 1, + } + ); return $isbn; } diff --git a/Koha/Util/OpenDocument.pm b/Koha/Util/OpenDocument.pm index f86c44452d..bde909fb5d 100644 --- a/Koha/Util/OpenDocument.pm +++ b/Koha/Util/OpenDocument.pm @@ -19,13 +19,13 @@ package Koha::Util::OpenDocument; use Modern::Perl; -use File::Basename qw( dirname ); +use File::Basename qw( dirname ); use OpenOffice::OODoc qw( odfDocument odfWorkingDirectory ); use parent qw( Exporter ); our @EXPORT = qw( - generate_ods + generate_ods ); =head1 NAME @@ -42,7 +42,6 @@ Arguments are file path and content as an arrayref of lines containing arrayrefs =cut - sub generate_ods { my ( $filepath, $content ) = @_; @@ -53,7 +52,7 @@ sub generate_ods { my $nb_rows = scalar @input_rows; my $nb_cols; if ($nb_rows) { - $nb_cols= scalar @{ $input_rows[0] }; + $nb_cols = scalar @{ $input_rows[0] }; } # Create document @@ -62,9 +61,10 @@ sub generate_ods { my $odf_doc = odfDocument( file => $filepath, create => 'spreadsheet' ); if ($nb_rows) { + # Prepare sheet my $odf_sheet = $odf_doc->expandTable( 0, $nb_rows + 1, $nb_cols ); - my @odf_rows = $odf_doc->getTableRows($odf_sheet); + my @odf_rows = $odf_doc->getTableRows($odf_sheet); # Writing for ( my $i = 0 ; $i < $nb_rows ; $i++ ) { diff --git a/Koha/Util/StockRotation.pm b/Koha/Util/StockRotation.pm index b26e63972e..9d56f4505d 100644 --- a/Koha/Util/StockRotation.pm +++ b/Koha/Util/StockRotation.pm @@ -26,10 +26,11 @@ use Koha::StockRotationItems; use Koha::Database; our ( @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS ); + BEGIN { require Exporter; - @ISA = qw( Exporter ); - @EXPORT = qw( ); + @ISA = qw( Exporter ); + @EXPORT = qw( ); @EXPORT_OK = qw( get_branches get_stages @@ -77,11 +78,11 @@ sub get_stages { my @out = (); - if ($rota->stockrotationstages->count > 0) { + if ( $rota->stockrotationstages->count > 0 ) { push @out, $rota->first_stage->unblessed; - push @out, @{$rota->first_stage->siblings->unblessed}; + push @out, @{ $rota->first_stage->siblings->unblessed }; } @@ -118,7 +119,7 @@ sub toggle_indemand { sub move_to_next_stage { - my ($item_id, $stage_id) = shift; + my ( $item_id, $stage_id ) = shift; # Get the item object my $item = Koha::StockRotationItems->find( @@ -140,7 +141,7 @@ sub move_to_next_stage { sub remove_from_stage { - my ($item_id, $stage_id) = @_; + my ( $item_id, $stage_id ) = @_; # Get the item object and delete it Koha::StockRotationItems->find( @@ -160,21 +161,18 @@ sub remove_from_stage { sub get_barcodes_status { - my ($rota_id, $barcodes, $status) = @_; + my ( $rota_id, $barcodes, $status ) = @_; # Get the items associated with these barcodes my $items = Koha::Items->search( - { - barcode => { '-in' => $barcodes } - }, - { - prefetch => 'stockrotationitem' - } + { barcode => { '-in' => $barcodes } }, + { prefetch => 'stockrotationitem' } ); + # Get an array of barcodes that were found # Assign each barcode's status my @found = (); - while (my $item = $items->next) { + while ( my $item = $items->next ) { push @found, $item->barcode if $item->barcode; @@ -185,22 +183,22 @@ sub get_barcodes_status { if ($on_rota) { # Check if it's on this rota - if ($on_rota->stage->rota->rota_id == $rota_id) { + if ( $on_rota->stage->rota->rota_id == $rota_id ) { # It's on this rota - push @{$status->{on_this}}, $item; + push @{ $status->{on_this} }, $item; } else { # It's on another rota - push @{$status->{on_other}}, $item; + push @{ $status->{on_other} }, $item; } } else { # Item is not on a rota - push @{$status->{ok}}, $item; + push @{ $status->{ok} }, $item; } @@ -208,10 +206,8 @@ sub get_barcodes_status { # Create an array of barcodes supplied in the file that # were not found in the catalogue - my %found_in_cat = map{ $_ => 1 } @found; - push @{$status->{not_found}}, grep( - !defined $found_in_cat{$_}, @{$barcodes} - ); + my %found_in_cat = map { $_ => 1 } @found; + push @{ $status->{not_found} }, grep( !defined $found_in_cat{$_}, @{$barcodes} ); } @@ -223,9 +219,9 @@ sub get_barcodes_status { sub add_items_to_rota { - my ($rota_id, $items) = @_; + my ( $rota_id, $items ) = @_; - foreach my $item(@{$items}) { + foreach my $item ( @{$items} ) { $item->add_to_rota($rota_id); diff --git a/Koha/Virtualshelfcontent.pm b/Koha/Virtualshelfcontent.pm index 0a7eb5b5ff..6b9ddbac95 100644 --- a/Koha/Virtualshelfcontent.pm +++ b/Koha/Virtualshelfcontent.pm @@ -17,7 +17,6 @@ package Koha::Virtualshelfcontent; use Modern::Perl; - use Koha::Database; use Koha::Exceptions; diff --git a/Koha/Virtualshelfcontents.pm b/Koha/Virtualshelfcontents.pm index 23776f395e..edc68a83f2 100644 --- a/Koha/Virtualshelfcontents.pm +++ b/Koha/Virtualshelfcontents.pm @@ -17,7 +17,6 @@ package Koha::Virtualshelfcontents; use Modern::Perl; - use Koha::Database; use Koha::Virtualshelf; diff --git a/Koha/Virtualshelfshare.pm b/Koha/Virtualshelfshare.pm index 48681b81ea..11ec90df29 100644 --- a/Koha/Virtualshelfshare.pm +++ b/Koha/Virtualshelfshare.pm @@ -27,7 +27,7 @@ use Koha::Patron; use base qw(Koha::Object); -use constant SHARE_INVITATION_EXPIRY_DAYS => 14; #two weeks to accept +use constant SHARE_INVITATION_EXPIRY_DAYS => 14; #two weeks to accept =head1 NAME @@ -54,8 +54,9 @@ sub accept { # If this borrower already has a share, there is no need to accept twice # We solve this by 'pretending' to reaccept, but delete instead - my $search = Koha::Virtualshelfshares->search({ shelfnumber => $self->shelfnumber, borrowernumber => $borrowernumber, invitekey => undef }); - if( $search->count ) { + my $search = Koha::Virtualshelfshares->search( + { shelfnumber => $self->shelfnumber, borrowernumber => $borrowernumber, invitekey => undef } ); + if ( $search->count ) { $self->delete; return $search->next; } else { @@ -72,13 +73,14 @@ sub accept { =cut sub has_expired { - my ($self) = @_; + my ($self) = @_; my $dt_sharedate = dt_from_string( $self->sharedate, 'sql' ); my $today = dt_from_string; my $expiration_delay = DateTime::Duration->new( days => SHARE_INVITATION_EXPIRY_DAYS ); - my $has_expired = DateTime->compare( $today, $dt_sharedate->add_duration($expiration_delay) ); + my $has_expired = DateTime->compare( $today, $dt_sharedate->add_duration($expiration_delay) ); + # Note: has_expired = 0 if the share expires today - return $has_expired == 1 ? 1 : 0 + return $has_expired == 1 ? 1 : 0; } =head3 sharee @@ -89,8 +91,8 @@ sub has_expired { sub sharee { my $self = shift; - my $rs = $self->_result->borrowernumber; - return Koha::Patron->_new_from_dbic( $rs ); + my $rs = $self->_result->borrowernumber; + return Koha::Patron->_new_from_dbic($rs); } =head3 _type diff --git a/Koha/Virtualshelfshares.pm b/Koha/Virtualshelfshares.pm index de709ff49c..628696fb88 100644 --- a/Koha/Virtualshelfshares.pm +++ b/Koha/Virtualshelfshares.pm @@ -17,7 +17,6 @@ package Koha::Virtualshelfshares; use Modern::Perl; - use Koha::Database; use Koha::Virtualshelf; diff --git a/Koha/Virtualshelves.pm b/Koha/Virtualshelves.pm index 58653130a4..9d60c517b2 100644 --- a/Koha/Virtualshelves.pm +++ b/Koha/Virtualshelves.pm @@ -23,7 +23,6 @@ use Koha::Exceptions; use Koha::Patrons; use Koha::Virtualshelf; - use base qw(Koha::Objects); =head1 NAME @@ -52,10 +51,10 @@ sub disown_or_delete { my $new_owner; $new_owner = C4::Context->preference('ListOwnerDesignated') - if C4::Context->preference('ListOwnerDesignated') - and Koha::Patrons->find( C4::Context->preference('ListOwnerDesignated') ); + if C4::Context->preference('ListOwnerDesignated') + and Koha::Patrons->find( C4::Context->preference('ListOwnerDesignated') ); - if( !$new_owner && C4::Context->userenv ) { + if ( !$new_owner && C4::Context->userenv ) { $new_owner = C4::Context->userenv->{number}; } @@ -81,20 +80,20 @@ sub disown_or_delete { sub get_private_shelves { my ( $self, $params ) = @_; - my $page = $params->{page}; - my $rows = $params->{rows}; + my $page = $params->{page}; + my $rows = $params->{rows}; my $borrowernumber = $params->{borrowernumber} || 0; $self->search( { public => 0, - -or => { + -or => { 'virtualshelfshares.borrowernumber' => $borrowernumber, - 'me.owner' => $borrowernumber, + 'me.owner' => $borrowernumber, } }, { - join => [ 'virtualshelfshares' ], + join => ['virtualshelfshares'], distinct => 'shelfnumber', order_by => 'shelfname', ( ( $page and $rows ) ? ( page => $page, rows => $rows ) : () ), @@ -130,25 +129,24 @@ sub get_public_shelves { sub get_some_shelves { my ( $self, $params ) = @_; my $borrowernumber = $params->{borrowernumber} || 0; - my $public = $params->{public} || 0; - my $add_allowed = $params->{add_allowed}; + my $public = $params->{public} || 0; + my $add_allowed = $params->{add_allowed}; my @conditions; my $patron; - my $staffuser = 0; + my $staffuser = 0; my $permitteduser = 0; if ( $borrowernumber != 0 ) { - $patron = Koha::Patrons->find( $borrowernumber ); - $staffuser = $patron->can_patron_change_staff_only_lists; + $patron = Koha::Patrons->find($borrowernumber); + $staffuser = $patron->can_patron_change_staff_only_lists; $permitteduser = $patron->can_patron_change_permitted_staff_lists; } - if ( $add_allowed ) { - if ( $permitteduser ) { + if ($add_allowed) { + if ($permitteduser) { push @conditions, { - -or => - [ + -or => [ { - "me.owner" => $borrowernumber, + "me.owner" => $borrowernumber, "me.allow_change_from_owner" => 1, }, "me.allow_change_from_others" => 1, @@ -156,24 +154,22 @@ sub get_some_shelves { "me.allow_change_from_permitted_staff" => 1 ] }; - } elsif ( $staffuser ) { + } elsif ($staffuser) { push @conditions, { - -or => - [ + -or => [ { - "me.owner" => $borrowernumber, + "me.owner" => $borrowernumber, "me.allow_change_from_owner" => 1, }, - "me.allow_change_from_others" => 1, - "me.allow_change_from_staff" => 1 + "me.allow_change_from_others" => 1, + "me.allow_change_from_staff" => 1 ] }; } else { push @conditions, { - -or => - [ + -or => [ { - "me.owner" => $borrowernumber, + "me.owner" => $borrowernumber, "me.allow_change_from_owner" => 1, }, "me.allow_change_from_others" => 1, @@ -183,10 +179,9 @@ sub get_some_shelves { } if ( !$public ) { push @conditions, { - -or => - { + -or => { "virtualshelfshares.borrowernumber" => $borrowernumber, - "me.owner" => $borrowernumber, + "me.owner" => $borrowernumber, } }; } @@ -197,7 +192,7 @@ sub get_some_shelves { ( @conditions ? ( -and => \@conditions ) : () ), }, { - join => [ 'virtualshelfshares' ], + join => ['virtualshelfshares'], distinct => 'shelfnumber', order_by => { -desc => 'lastmodified' }, } @@ -216,11 +211,11 @@ sub get_shelves_containing_record { my @conditions = ( 'virtualshelfcontents.biblionumber' => $biblionumber ); if ($borrowernumber) { push @conditions, - { - -or => [ + { + -or => [ { public => 0, - -or => { + -or => { 'me.owner' => $borrowernumber, -or => { 'virtualshelfshares.borrowernumber' => $borrowernumber, @@ -229,15 +224,13 @@ sub get_shelves_containing_record { }, { public => 1 }, ] - }; + }; } else { push @conditions, { public => 1 }; } return Koha::Virtualshelves->search( - { - -and => \@conditions - }, + { -and => \@conditions }, { join => [ 'virtualshelfcontents', 'virtualshelfshares' ], distinct => 'shelfnumber', @@ -277,7 +270,6 @@ sub filter_by_readable { return $self->search( { '-or' => { public => 1, owner => $params->{patron_id} } } ); } - =head2 Internal methods =head3 _type diff --git a/Koha/XSLT/Base.pm b/Koha/XSLT/Base.pm index cdadee741d..f973934fe5 100644 --- a/Koha/XSLT/Base.pm +++ b/Koha/XSLT/Base.pm @@ -128,13 +128,13 @@ use base qw(Class::Accessor); __PACKAGE__->mk_ro_accessors(qw( err )); __PACKAGE__->mk_accessors(qw( do_not_return_source print_warns )); -use constant XSLTH_ERR_1 => 'XSLTH_ERR_NO_FILE'; -use constant XSLTH_ERR_2 => 'XSLTH_ERR_FILE_NOT_FOUND'; -use constant XSLTH_ERR_3 => 'XSLTH_ERR_LOADING'; -use constant XSLTH_ERR_4 => 'XSLTH_ERR_PARSING_CODE'; -use constant XSLTH_ERR_5 => 'XSLTH_ERR_PARSING_DATA'; -use constant XSLTH_ERR_6 => 'XSLTH_ERR_TRANSFORMING'; -use constant XSLTH_ERR_7 => 'XSLTH_NO_STRING_PASSED'; +use constant XSLTH_ERR_1 => 'XSLTH_ERR_NO_FILE'; +use constant XSLTH_ERR_2 => 'XSLTH_ERR_FILE_NOT_FOUND'; +use constant XSLTH_ERR_3 => 'XSLTH_ERR_LOADING'; +use constant XSLTH_ERR_4 => 'XSLTH_ERR_PARSING_CODE'; +use constant XSLTH_ERR_5 => 'XSLTH_ERR_PARSING_DATA'; +use constant XSLTH_ERR_6 => 'XSLTH_ERR_TRANSFORMING'; +use constant XSLTH_ERR_7 => 'XSLTH_NO_STRING_PASSED'; =head2 new @@ -143,7 +143,7 @@ use constant XSLTH_ERR_7 => 'XSLTH_NO_STRING_PASSED'; =cut sub new { - my ($class, $params) = @_; + my ( $class, $params ) = @_; my $self = $class->SUPER::new($params); $self->{_security} = Koha::XSLT::Security->new; $self->{_security}->register_callbacks; @@ -180,12 +180,12 @@ sub transform { # new style: $hashref my ( $xml, $filename, $xsltcode, $format ); my $parameters = {}; - if( ref $_[0] eq 'HASH' ) { - $xml = $_[0]->{xml}; - $xsltcode = $_[0]->{code}; - $filename = $_[0]->{file} if !$xsltcode; #xsltcode gets priority + if ( ref $_[0] eq 'HASH' ) { + $xml = $_[0]->{xml}; + $xsltcode = $_[0]->{code}; + $filename = $_[0]->{file} if !$xsltcode; #xsltcode gets priority $parameters = $_[0]->{parameters} if ref $_[0]->{parameters} eq 'HASH'; - $format = $_[0]->{format} || 'chars'; + $format = $_[0]->{format} || 'chars'; } else { ( $xml, $filename, $format ) = @_; $format ||= 'chars'; @@ -194,21 +194,20 @@ sub transform { #Initialized yet? if ( !$self->{xslt_hash} ) { $self->_init; - } - else { - $self->_set_error; #clear last error + } else { + $self->_set_error; #clear last error } my $retval = $self->{do_not_return_source} ? undef : $xml; #check if no string passed if ( !defined $xml ) { - $self->_set_error( XSLTH_ERR_7 ); - return; #always undef + $self->_set_error(XSLTH_ERR_7); + return; #always undef } #load stylesheet - my $key = $self->_load( $filename, $xsltcode ); - my $stsh = $key? $self->{xslt_hash}->{$key}: undef; + my $key = $self->_load( $filename, $xsltcode ); + my $stsh = $key ? $self->{xslt_hash}->{$key} : undef; return $retval if $self->{err}; #parse input and transform @@ -220,6 +219,7 @@ sub transform { return $retval; } my $result = eval { + #$parameters is an optional hashref that contains #key-value pairs to be sent to the XSLT. #Numbers may be bare but strings must be double quoted @@ -228,12 +228,10 @@ sub transform { #NOTE: Parameters are not cached. They are provided for #each different transform. - my $transformed = $stsh->transform($source, %$parameters); - $format eq 'bytes' - ? $stsh->output_as_bytes( $transformed ) - : $format eq 'xmldoc' - ? $transformed - : $stsh->output_as_chars( $transformed ); # default: chars + my $transformed = $stsh->transform( $source, %$parameters ); + $format eq 'bytes' ? $stsh->output_as_bytes($transformed) + : $format eq 'xmldoc' ? $transformed + : $stsh->output_as_chars($transformed); # default: chars }; if ($@) { $self->_set_error( XSLTH_ERR_6, $@ ); @@ -265,8 +263,7 @@ sub refresh { my $rv; if ($file) { $rv = delete $self->{xslt_hash}->{$file} ? 1 : 0; - } - else { + } else { $rv = scalar keys %{ $self->{xslt_hash} }; $self->{xslt_hash} = {}; } @@ -282,10 +279,10 @@ sub _init { my $self = shift; $self->_set_error; - $self->{xslt_hash} = {}; - $self->{print_warns} = 1 unless exists $self->{print_warns}; + $self->{xslt_hash} = {}; + $self->{print_warns} = 1 unless exists $self->{print_warns}; $self->{do_not_return_source} = 0 - unless exists $self->{do_not_return_source}; + unless exists $self->{do_not_return_source}; #by default we return source on a failing transformation #but it could be passed at construction time already @@ -298,41 +295,39 @@ sub _init { sub _load { my ( $self, $filename, $code ) = @_; my ( $digest, $codelen, $salt, $rv ); - $salt = 'AZ'; #just a constant actually + $salt = 'AZ'; #just a constant actually #If no file or code passed, use the last file again if ( !$filename && !$code ) { my $last = $self->{last_xsltfile}; if ( !$last || !exists $self->{xslt_hash}->{$last} ) { - $self->_set_error( XSLTH_ERR_1 ); + $self->_set_error(XSLTH_ERR_1); return; } return $last; } #check if it is loaded already - if( $code ) { - $codelen = length( $code ); - $digest = eval { crypt($code, $salt) }; - if( $digest && exists $self->{xslt_hash}->{$digest.$codelen} ) { - return $digest.$codelen; + if ($code) { + $codelen = length($code); + $digest = eval { crypt( $code, $salt ) }; + if ( $digest && exists $self->{xslt_hash}->{ $digest . $codelen } ) { + return $digest . $codelen; } - } elsif( $filename && exists $self->{xslt_hash}->{$filename} ) { - return $filename; + } elsif ( $filename && exists $self->{xslt_hash}->{$filename} ) { + return $filename; } #Check file existence (skipping URLs) - if( $filename && $filename !~ /^https?:\/\// && !-e $filename ) { - $self->_set_error( XSLTH_ERR_2 ); + if ( $filename && $filename !~ /^https?:\/\// && !-e $filename ) { + $self->_set_error(XSLTH_ERR_2); return; } #load sheet my $parser = XML::LibXML->new; $self->{_security}->set_parser_options($parser); - my $style_doc = eval { - $parser->load_xml( $self->_load_xml_args($filename, $code) ) - }; + my $style_doc = eval { $parser->load_xml( $self->_load_xml_args( $filename, $code ) ) }; if ($@) { $self->_set_error( XSLTH_ERR_3, $@ ); return; @@ -342,7 +337,7 @@ sub _load { my $xslt = XML::LibXSLT->new; $self->{_security}->set_callbacks($xslt); - $rv = $code? $digest.$codelen: $filename; + $rv = $code ? $digest . $codelen : $filename; $self->{xslt_hash}->{$rv} = eval { $xslt->parse_stylesheet($style_doc) }; if ($@) { $self->_set_error( XSLTH_ERR_4, $@ ); @@ -355,8 +350,9 @@ sub _load { sub _load_xml_args { my ( $self, $filename, $code ) = @_; return Koha::XSLT::HTTPS->load($filename) if $filename && $filename =~ /^https/i; - # Workaround for current problems with https location in libxml2/libxslt - # Returns response like { string => SOME_CODE } + + # Workaround for current problems with https location in libxml2/libxslt + # Returns response like { string => SOME_CODE } return $code ? { string => $code } : { location => $filename }; } @@ -366,8 +362,8 @@ sub _load_xml_args { sub _set_error { my ( $self, $errcode, $warn ) = @_; - $self->{err} = $errcode; #set or clear error - warn 'XSLT::Base: '. $warn if $warn && $self->{print_warns}; + $self->{err} = $errcode; #set or clear error + warn 'XSLT::Base: ' . $warn if $warn && $self->{print_warns}; } =head1 AUTHOR diff --git a/Koha/XSLT/HTTPS.pm b/Koha/XSLT/HTTPS.pm index 834afa02a9..1eb05e6550 100644 --- a/Koha/XSLT/HTTPS.pm +++ b/Koha/XSLT/HTTPS.pm @@ -54,12 +54,13 @@ sub load { my ( $class, $filename ) = @_; Koha::Exceptions::XSLT::MissingFilename->throw if !$filename; - return { location => $filename } if $filename !~ /^https:\/\//; + return { location => $filename } if $filename !~ /^https:\/\//; - my $ua = LWP::UserAgent->new( ssl_opts => { verify_hostname => 0 } ); - my $resp = $ua->get( $filename ); - if( $resp->is_success ) { + my $ua = LWP::UserAgent->new( ssl_opts => { verify_hostname => 0 } ); + my $resp = $ua->get($filename); + if ( $resp->is_success ) { my $contents = $resp->decoded_content; + # $contents = $self->_resolve_includes( $contents ); return { string => $contents }; } @@ -67,8 +68,10 @@ sub load { } sub _resolve_includes { -# We could parse the code for includes/imports, fetch them and change refs + + # We could parse the code for includes/imports, fetch them and change refs my ( $self, $code ) = @_; + # TODO Extend it return $code; } diff --git a/Koha/XSLT/Security.pm b/Koha/XSLT/Security.pm index 09b5b58e08..76822402ce 100644 --- a/Koha/XSLT/Security.pm +++ b/Koha/XSLT/Security.pm @@ -56,15 +56,15 @@ sub new { $self->{_options} = {}; my $conf = C4::Context->config('koha_xslt_security'); - if( $conf && ref($conf) eq 'HASH' ) { + if ( $conf && ref($conf) eq 'HASH' ) { $self->{_options} = $conf; } my $security = eval { XML::LibXSLT::Security->new }; - if( $security ) { + if ($security) { $self->{_security_obj} = $security; } else { - warn "No XML::LibXSLT::Security object: $@"; #TODO Move to about ? + warn "No XML::LibXSLT::Security object: $@"; #TODO Move to about ? } return bless $self, $class; @@ -82,35 +82,47 @@ sub register_callbacks { my $security = $self->{_security_obj}; return if !$security; - $security->register_callback( read_file => sub { - warn "read_file called in XML::LibXSLT"; - #i.e. when using the exsl:document() element or document() function (to read a XML file) - my ($tctxt,$value) = @_; - return 0; - }); - $security->register_callback( write_file => sub { - warn "write_file called in XML::LibXSLT"; - #i.e. when using the exsl:document element (or document() function?) (to write an output file of many possible types) - #e.g. - # - # breached! - # - my ($tctxt,$value) = @_; - return 0; - }); - $security->register_callback( read_net => sub { - warn "read_net called in XML::LibXSLT"; - #i.e. when using the document() function (to read XML from the network) - #e.g. - my ($tctxt,$value) = @_; - return 0; - }); - $security->register_callback( write_net => sub { - warn "write_net called in XML::LibXSLT"; - #NOTE: it's unknown how one would invoke this, but covering our bases anyway - my ($tctxt,$value) = @_; - return 0; - }); + $security->register_callback( + read_file => sub { + warn "read_file called in XML::LibXSLT"; + + #i.e. when using the exsl:document() element or document() function (to read a XML file) + my ( $tctxt, $value ) = @_; + return 0; + } + ); + $security->register_callback( + write_file => sub { + warn "write_file called in XML::LibXSLT"; + + #i.e. when using the exsl:document element (or document() function?) (to write an output file of many possible types) + #e.g. + # + # breached! + # + my ( $tctxt, $value ) = @_; + return 0; + } + ); + $security->register_callback( + read_net => sub { + warn "read_net called in XML::LibXSLT"; + + #i.e. when using the document() function (to read XML from the network) + #e.g. + my ( $tctxt, $value ) = @_; + return 0; + } + ); + $security->register_callback( + write_net => sub { + warn "write_net called in XML::LibXSLT"; + + #NOTE: it's unknown how one would invoke this, but covering our bases anyway + my ( $tctxt, $value ) = @_; + return 0; + } + ); } =head2 set_callbacks @@ -123,11 +135,11 @@ sub register_callbacks { =cut sub set_callbacks { - my ($self, $xslt) = @_; + my ( $self, $xslt ) = @_; my $security = $self->{_security_obj}; return if !$security; - $xslt->security_callbacks( $security ); + $xslt->security_callbacks($security); } =head2 set_parser_options @@ -140,22 +152,24 @@ sub set_callbacks { =cut sub set_parser_options { - my ($self, $parser) = @_; + my ( $self, $parser ) = @_; my $conf = $self->{_options}; - if( $conf->{expand_entities_unsafe} ) { # NOT recommended - _set_option($parser, 'expand_entities', 1); + if ( $conf->{expand_entities_unsafe} ) { # NOT recommended + _set_option( $parser, 'expand_entities', 1 ); } else { + # If not explicitly set, we should disable expanding for security - _set_option($parser, 'expand_entities', 0); + _set_option( $parser, 'expand_entities', 0 ); } } sub _set_option { - my ($parser, $option_name, $value) = @_; - if( $parser->option_exists($option_name) ) { - $parser->set_option($option_name, $value); + my ( $parser, $option_name, $value ) = @_; + if ( $parser->option_exists($option_name) ) { + $parser->set_option( $option_name, $value ); } + #TODO Should we warn if it does not exist? } diff --git a/Koha/Z3950Responder.pm b/Koha/Z3950Responder.pm index 3e1f1d22cd..327aeb46d5 100644 --- a/Koha/Z3950Responder.pm +++ b/Koha/Z3950Responder.pm @@ -20,7 +20,7 @@ package Koha::Z3950Responder; use Modern::Perl; use C4::Biblio qw( GetMarcFromKohaField ); -use C4::Koha qw( GetAuthorisedValues ); +use C4::Koha qw( GetAuthorisedValues ); use Koha::Caches; @@ -65,36 +65,38 @@ service. Uses a Session class for the actual functionality. sub new { my ( $class, $config ) = @_; - my ($item_tag, $itemnumber_subfield) = GetMarcFromKohaField( "items.itemnumber" ); + my ( $item_tag, $itemnumber_subfield ) = GetMarcFromKohaField("items.itemnumber"); # We hardcode the strings for English so SOMETHING will work if the authorized value doesn't exist. my $status_strings = { - AVAILABLE => 'Available', - CHECKED_OUT => 'Checked Out', - LOST => 'Lost', + AVAILABLE => 'Available', + CHECKED_OUT => 'Checked Out', + LOST => 'Lost', NOT_FOR_LOAN => 'Not for Loan', - DAMAGED => 'Damaged', - WITHDRAWN => 'Withdrawn', - IN_TRANSIT => 'In Transit', - ON_HOLD => 'On Hold', + DAMAGED => 'Damaged', + WITHDRAWN => 'Withdrawn', + IN_TRANSIT => 'In Transit', + ON_HOLD => 'On Hold', }; - foreach my $val ( @{ GetAuthorisedValues( 'Z3950_STATUS' ) } ) { + foreach my $val ( @{ GetAuthorisedValues('Z3950_STATUS') } ) { $status_strings->{ $val->{authorised_value} } = $val->{lib}; } my $self = { %$config, - item_tag => $item_tag, + item_tag => $item_tag, itemnumber_subfield => $itemnumber_subfield, - status_strings => $status_strings, + status_strings => $status_strings, }; # If requested, turn on debugging. if ( $self->{debug} ) { + # Turn on single-process mode. unshift @{ $self->{yaz_options} }, '-S'; } else { + # Turn off Yaz's built-in logging apart from fatal errors (can be turned back on if desired). unshift @{ $self->{yaz_options} }, '-v', 'none,fatal'; } @@ -109,10 +111,10 @@ sub new { $self->{num_to_prefetch} //= 20; $self->{server} = Net::Z3950::SimpleServer->new( - INIT => sub { $self->init_handler(@_) }, + INIT => sub { $self->init_handler(@_) }, SEARCH => sub { $self->search_handler(@_) }, - FETCH => sub { $self->fetch_handler(@_) }, - CLOSE => sub { $self->close_handler(@_) }, + FETCH => sub { $self->fetch_handler(@_) }, + CLOSE => sub { $self->close_handler(@_) }, ); return bless( $self, $class ); @@ -128,9 +130,9 @@ fatal error occurs. =cut sub start { - my ( $self ) = @_; + my ($self) = @_; - $self->{server}->launch_server( 'Koha::Z3950Responder', @{ $self->{yaz_options} } ) + $self->{server}->launch_server( 'Koha::Z3950Responder', @{ $self->{yaz_options} } ); } =head2 CALLBACKS @@ -146,29 +148,34 @@ Callback that is called when a new connection is initialized =cut sub init_handler { + # Called when the client first connects. my ( $self, $args ) = @_; # This holds all of the per-connection state. my $session; - if (C4::Context->preference('SearchEngine') eq 'Zebra') { + if ( C4::Context->preference('SearchEngine') eq 'Zebra' ) { use Koha::Z3950Responder::ZebraSession; - $session = Koha::Z3950Responder::ZebraSession->new({ - server => $self, - peer => $args->{PEER_NAME}, - }); + $session = Koha::Z3950Responder::ZebraSession->new( + { + server => $self, + peer => $args->{PEER_NAME}, + } + ); } else { use Koha::Z3950Responder::GenericSession; - $session = Koha::Z3950Responder::GenericSession->new({ - server => $self, - peer => $args->{PEER_NAME} - }); + $session = Koha::Z3950Responder::GenericSession->new( + { + server => $self, + peer => $args->{PEER_NAME} + } + ); } $args->{HANDLE} = $session; $args->{IMP_NAME} = "Koha"; - $args->{IMP_VER} = Koha::version; + $args->{IMP_VER} = Koha::version; } =head3 search_handler @@ -181,6 +188,7 @@ sub search_handler { my ( $self, $args ) = @_; my $SearchEngine = C4::Context->preference('SearchEngine'); + # Flushing L1 to make sure the search will be processed using the correct data Koha::Caches->flush_L1_caches(); $self->init_handler($args) @@ -198,7 +206,7 @@ Callback that is called when records are requested sub fetch_handler { my ( $self, $args ) = @_; - $args->{HANDLE}->fetch_handler( $args ); + $args->{HANDLE}->fetch_handler($args); } =head3 close_handler @@ -210,7 +218,7 @@ Callback that is called when a session is terminated sub close_handler { my ( $self, $args ) = @_; - $args->{HANDLE}->close_handler( $args ); + $args->{HANDLE}->close_handler($args); } 1; diff --git a/Koha/Z3950Responder/GenericSession.pm b/Koha/Z3950Responder/GenericSession.pm index a4552dfe5d..66747734f7 100644 --- a/Koha/Z3950Responder/GenericSession.pm +++ b/Koha/Z3950Responder/GenericSession.pm @@ -48,36 +48,36 @@ Perform a search using C's QueryBuilder and Search. sub start_search { my ( $self, $args, $num_to_prefetch ) = @_; - if (!defined $self->{'attribute_mappings'}) { + if ( !defined $self->{'attribute_mappings'} ) { require YAML::XS; - $self->{'attribute_mappings'} = YAML::XS::LoadFile($self->{server}->{config_dir} . 'attribute_mappings.yaml'); + $self->{'attribute_mappings'} = YAML::XS::LoadFile( $self->{server}->{config_dir} . 'attribute_mappings.yaml' ); } my $database = $args->{DATABASES}->[0]; - my $builder = Koha::SearchEngine::QueryBuilder->new({ index => $database }); - my $searcher = Koha::SearchEngine::Search->new({ index => $database }); + my $builder = Koha::SearchEngine::QueryBuilder->new( { index => $database } ); + my $searcher = Koha::SearchEngine::Search->new( { index => $database } ); my $built_query; - my $query = $args->{RPN}->{'query'}->to_koha($self->{'attribute_mappings'}->{$database}); + my $query = $args->{RPN}->{'query'}->to_koha( $self->{'attribute_mappings'}->{$database} ); $self->log_debug(" parsed search: $query"); my @operands = $query; - (undef, $built_query) = $builder->build_query_compat( undef, \@operands, undef, undef, undef, 0); + ( undef, $built_query ) = $builder->build_query_compat( undef, \@operands, undef, undef, undef, 0 ); - my ($error, $marcresults, $hits ) = $searcher->simple_search_compat($built_query, 0, $num_to_prefetch); - if (defined $error) { - $self->set_error($args, $self->ERR_SEARCH_FAILED, 'Search failed'); + my ( $error, $marcresults, $hits ) = $searcher->simple_search_compat( $built_query, 0, $num_to_prefetch ); + if ( defined $error ) { + $self->set_error( $args, $self->ERR_SEARCH_FAILED, 'Search failed' ); return; } my $resultset = { - query => $built_query, - database => $database, - cached_offset => 0, + query => $built_query, + database => $database, + cached_offset => 0, cached_results => $marcresults, - hits => $hits + hits => $hits }; - return ($resultset, $hits); + return ( $resultset, $hits ); } =head3 fetch_record @@ -93,19 +93,20 @@ sub fetch_record { # Fetch more records if necessary my $offset = $args->{OFFSET} - 1; - if ($offset < $resultset->{cached_offset} || $offset >= $resultset->{cached_offset} + $num_to_prefetch) { + if ( $offset < $resultset->{cached_offset} || $offset >= $resultset->{cached_offset} + $num_to_prefetch ) { $self->log_debug(" fetch uncached, fetching $num_to_prefetch records starting at $offset"); - my $searcher = Koha::SearchEngine::Search->new({ index => $resultset->{'database'} }); - my ($error, $marcresults, $num_hits ) = $searcher->simple_search_compat($resultset->{'query'}, $offset, $num_to_prefetch); - if (defined $error) { - $self->set_error($args, $self->ERR_TEMPORARY_ERROR, 'Fetch failed'); + my $searcher = Koha::SearchEngine::Search->new( { index => $resultset->{'database'} } ); + my ( $error, $marcresults, $num_hits ) = + $searcher->simple_search_compat( $resultset->{'query'}, $offset, $num_to_prefetch ); + if ( defined $error ) { + $self->set_error( $args, $self->ERR_TEMPORARY_ERROR, 'Fetch failed' ); return; } - $resultset->{cached_offset} = $offset; + $resultset->{cached_offset} = $offset; $resultset->{cached_results} = $marcresults; } - return $resultset->{cached_results}[$offset - $resultset->{cached_offset}]; + return $resultset->{cached_results}[ $offset - $resultset->{cached_offset} ]; } 1; diff --git a/Koha/Z3950Responder/RPN.pm b/Koha/Z3950Responder/RPN.pm index 71860ce460..b97208a181 100644 --- a/Koha/Z3950Responder/RPN.pm +++ b/Koha/Z3950Responder/RPN.pm @@ -38,27 +38,27 @@ C. =cut sub to_koha { - my ($self, $mappings) = @_; + my ( $self, $mappings ) = @_; - my $attrs = $self->{'attributes'}; + my $attrs = $self->{'attributes'}; my $fields = $mappings->{use}{default}; - my $split = 0; + my $split = 0; my $prefix = ''; my $suffix = ''; - my $term = $self->{'term'}; + my $term = $self->{'term'}; utf8::decode($term); if ($attrs) { foreach my $attr (@$attrs) { - if ($attr->{'attributeType'} == 1) { # use + if ( $attr->{'attributeType'} == 1 ) { # use my $use = $attr->{'attributeValue'}; $fields = $mappings->{use}{$use} if defined $mappings->{use}{$use}; - } elsif ($attr->{'attributeType'} == 4) { # structure - $split = 1 if ($attr->{'attributeValue'} == 2); - } elsif ($attr->{'attributeType'} == 5) { # truncation + } elsif ( $attr->{'attributeType'} == 4 ) { # structure + $split = 1 if ( $attr->{'attributeValue'} == 2 ); + } elsif ( $attr->{'attributeType'} == 5 ) { # truncation my $truncation = $attr->{'attributeValue'}; - $prefix = '*' if ($truncation == 2 || $truncation == 3); - $suffix = '*' if ($truncation == 1 || $truncation == 3); + $prefix = '*' if ( $truncation == 2 || $truncation == 3 ); + $suffix = '*' if ( $truncation == 1 || $truncation == 3 ); } } } @@ -67,62 +67,62 @@ sub to_koha { if ($split) { my @terms; - foreach my $word (split(/\s/, $term)) { + foreach my $word ( split( /\s/, $term ) ) { $word =~ s/^[\,\.;:\\\/\"\'\-\=]+//g; $word =~ s/[\,\.;:\\\/\"\'\-\=]+$//g; - next if (!$word); + next if ( !$word ); $word = $self->escape($word); my @words; - if( $fields ) { - foreach my $field (@{$fields}) { - push(@words, "$field:($prefix$word$suffix)"); + if ($fields) { + foreach my $field ( @{$fields} ) { + push( @words, "$field:($prefix$word$suffix)" ); } } else { - push(@words, "($prefix$word$suffix)"); + push( @words, "($prefix$word$suffix)" ); } - push (@terms, join(' OR ', @words)); + push( @terms, join( ' OR ', @words ) ); } - return '(' . join(' AND ', @terms) . ')'; + return '(' . join( ' AND ', @terms ) . ')'; } my @terms; $term = $self->escape($term); return "($prefix$term$suffix)" unless $fields; - foreach my $field (@{$fields}) { - push(@terms, "$field:($prefix$term$suffix)"); + foreach my $field ( @{$fields} ) { + push( @terms, "$field:($prefix$term$suffix)" ); } - return '(' . join(' OR ', @terms) . ')'; + return '(' . join( ' OR ', @terms ) . ')'; } sub escape { - my ($self, $term) = @_; + my ( $self, $term ) = @_; $term =~ s/([()])/\\$1/g; return $term; } package Net::Z3950::RPN::And; -sub to_koha { - my ($self, $mappings) = @_; - return '(' . $self->[0]->to_koha($mappings) . ' AND ' . - $self->[1]->to_koha($mappings) . ')'; +sub to_koha { + my ( $self, $mappings ) = @_; + + return '(' . $self->[0]->to_koha($mappings) . ' AND ' . $self->[1]->to_koha($mappings) . ')'; } package Net::Z3950::RPN::Or; -sub to_koha { - my ($self, $mappings) = @_; - return '(' . $self->[0]->to_koha($mappings) . ' OR ' . - $self->[1]->to_koha($mappings) . ')'; +sub to_koha { + my ( $self, $mappings ) = @_; + + return '(' . $self->[0]->to_koha($mappings) . ' OR ' . $self->[1]->to_koha($mappings) . ')'; } package Net::Z3950::RPN::AndNot; -sub to_koha { - my ($self, $mappings) = @_; - return '(' . $self->[0]->to_koha($mappings) . ' NOT ' . - $self->[1]->to_koha($mappings) . ')'; +sub to_koha { + my ( $self, $mappings ) = @_; + + return '(' . $self->[0]->to_koha($mappings) . ' NOT ' . $self->[1]->to_koha($mappings) . ')'; } 1; diff --git a/Koha/Z3950Responder/Session.pm b/Koha/Z3950Responder/Session.pm index 8cefe1e1d5..433fc83fc4 100644 --- a/Koha/Z3950Responder/Session.pm +++ b/Koha/Z3950Responder/Session.pm @@ -50,18 +50,18 @@ OIDs and diagnostic codes used in Z39.50 use constant { UNIMARC_OID => '1.2.840.10003.5.1', - USMARC_OID => '1.2.840.10003.5.10', + USMARC_OID => '1.2.840.10003.5.10', MARCXML_OID => '1.2.840.10003.5.109.10' }; use constant { - ERR_TEMPORARY_ERROR => 2, + ERR_TEMPORARY_ERROR => 2, ERR_PRESENT_OUT_OF_RANGE => 13, - ERR_RECORD_TOO_LARGE => 16, - ERR_NO_SUCH_RESULTSET => 30, - ERR_SEARCH_FAILED => 125, - ERR_SYNTAX_UNSUPPORTED => 239, - ERR_DB_DOES_NOT_EXIST => 235, + ERR_RECORD_TOO_LARGE => 16, + ERR_NO_SUCH_RESULTSET => 30, + ERR_SEARCH_FAILED => 125, + ERR_SYNTAX_UNSUPPORTED => 239, + ERR_DB_DOES_NOT_EXIST => 235, }; =head1 FUNCTIONS @@ -82,11 +82,14 @@ Instantiate a Session sub new { my ( $class, $args ) = @_; - my $self = bless( { - %$args, - logger => Koha::Logger->get({ interface => 'z3950' }), - resultsets => {}, - }, $class ); + my $self = bless( + { + %$args, + logger => Koha::Logger->get( { interface => 'z3950' } ), + resultsets => {}, + }, + $class + ); if ( $self->{server}->{debug} ) { $self->{logger}->debug_to_screen(); @@ -118,7 +121,7 @@ sub search_handler { my $query = $args->{QUERY}; $self->log_info("received search for '$query', (RS $args->{SETNAME})"); - my ($resultset, $hits) = $self->start_search( $args, $self->{server}->{num_to_prefetch} ); + my ( $resultset, $hits ) = $self->start_search( $args, $self->{server}->{num_to_prefetch} ); return unless $resultset; $args->{HITS} = $hits; @@ -140,11 +143,12 @@ sub fetch_handler { my $server = $self->{server}; - my $form_oid = $args->{REQ_FORM} // ''; - my $composition = $args->{COMP} // ''; + my $form_oid = $args->{REQ_FORM} // ''; + my $composition = $args->{COMP} // ''; $self->log_debug(" form OID '$form_oid', composition '$composition'"); my $resultset = $self->{resultsets}->{ $args->{SETNAME} }; + # The offset comes across 1-indexed. my $offset = $args->{OFFSET} - 1; @@ -165,16 +169,21 @@ sub fetch_handler { my $tag = $server->{item_tag}; foreach my $field ( $record->field($tag) ) { - $self->add_item_status( $field ); + $self->add_item_status($field); } } if ( $form_oid eq $self->MARCXML_OID && $composition eq 'marcxml' ) { $args->{RECORD} = $record->as_xml_record(); - } elsif ( ( $form_oid eq $self->USMARC_OID || $form_oid eq $self->UNIMARC_OID ) && ( !$composition || $composition eq 'F' ) ) { + } elsif ( ( $form_oid eq $self->USMARC_OID || $form_oid eq $self->UNIMARC_OID ) + && ( !$composition || $composition eq 'F' ) ) + { $args->{RECORD} = $record->as_usmarc(); } else { - $self->set_error( $args, $self->ERR_SYNTAX_UNSUPPORTED, "Unsupported syntax/composition $form_oid/$composition" ); + $self->set_error( + $args, $self->ERR_SYNTAX_UNSUPPORTED, + "Unsupported syntax/composition $form_oid/$composition" + ); return; } } @@ -214,12 +223,12 @@ Check that the fetch request parameters are within bounds of the result set. sub check_fetch { my ( $self, $resultset, $args, $offset, $num_records ) = @_; - if ( !defined( $resultset ) ) { + if ( !defined($resultset) ) { $self->set_error( $args, ERR_NO_SUCH_RESULTSET, 'No such resultset' ); return 0; } - if ( $offset < 0 || $offset + $num_records > $resultset->{hits} ) { + if ( $offset < 0 || $offset + $num_records > $resultset->{hits} ) { $self->set_error( $args, ERR_PRESENT_OUT_OF_RANGE, 'Present request out of range' ); return 0; } @@ -253,25 +262,25 @@ sub add_item_status { my $server = $self->{server}; my $itemnumber_subfield = $server->{itemnumber_subfield}; - my $add_subfield = $server->{add_item_status_subfield}; - my $status_strings = $server->{status_strings}; + my $add_subfield = $server->{add_item_status_subfield}; + my $status_strings = $server->{status_strings}; my $itemnumber = $field->subfield($itemnumber_subfield); next unless $itemnumber; - my $item = Koha::Items->find( $itemnumber ); + my $item = Koha::Items->find($itemnumber); return unless $item; my $statuses = $item->z3950_status($status_strings); if ( $server->{add_status_multi_subfield} ) { - $field->add_subfields( map { ( $add_subfield, $_ ) } ( @$statuses ? @$statuses : $status_strings->{AVAILABLE} ) ); + $field->add_subfields( map { ( $add_subfield, $_ ) } + ( @$statuses ? @$statuses : $status_strings->{AVAILABLE} ) ); } else { $field->add_subfields( $add_subfield, @$statuses ? join( ', ', @$statuses ) : $status_strings->{AVAILABLE} ); } } - =head3 log_debug $self->log_debug('Message'); diff --git a/Koha/Z3950Responder/ZebraSession.pm b/Koha/Z3950Responder/ZebraSession.pm index 302472ba69..516afb6278 100644 --- a/Koha/Z3950Responder/ZebraSession.pm +++ b/Koha/Z3950Responder/ZebraSession.pm @@ -53,9 +53,10 @@ sub start_search { eval { $connection = C4::Context->Zconn( + # We're depending on the caller to have done some validation. $database eq 'biblios' ? 'biblioserver' : 'authorityserver', - 0 # No, no async, doesn't really help much for single-server searching + 0 # No, no async, doesn't really help much for single-server searching ); $results = $connection->search_pqf( $args->{QUERY} ); @@ -74,13 +75,13 @@ sub start_search { $connection = undef; } - my $hits = $results ? $results->size() : -1; + my $hits = $results ? $results->size() : -1; my $resultset = { - database => $database, + database => $database, connection => $connection, - results => $results, - query => $args->{QUERY}, - hits => $hits + results => $results, + query => $args->{QUERY}, + hits => $hits }; return ( $resultset, $hits ); @@ -100,7 +101,7 @@ sub fetch_record { my $record; eval { - if ( !$resultset->{results}->record_immediate( $index ) ) { + if ( !$resultset->{results}->record_immediate($index) ) { my $start = $num_to_prefetch ? int( $index / $num_to_prefetch ) * $num_to_prefetch : $index; if ( $start + $num_to_prefetch >= $resultset->{results}->size() ) { @@ -112,7 +113,7 @@ sub fetch_record { $resultset->{results}->records( $start, $num_to_prefetch, 0 ); } - $record = $resultset->{results}->record_immediate( $index )->raw(); + $record = $resultset->{results}->record_immediate($index)->raw(); }; if ($@) { die $@ if ( ref($@) ne 'ZOOM::Exception' ); @@ -149,13 +150,11 @@ sub _set_error_from_zoom { my ( $self, $args, $exception ) = @_; $self->set_error( $args, $self->ERR_TEMPORARY_ERROR, 'Cannot connect to upstream server' ); - $self->log_error( - "Zebra upstream error: " . - $exception->message() . " (" . - $exception->code() . ") " . - ( $exception->addinfo() // '' ) . " " . - $exception->diagset() - ); + $self->log_error( "Zebra upstream error: " + . $exception->message() . " (" + . $exception->code() . ") " + . ( $exception->addinfo() // '' ) . " " + . $exception->diagset() ); } 1; diff --git a/Koha/Z3950Server.pm b/Koha/Z3950Server.pm index 21dc0224fa..96762a598e 100644 --- a/Koha/Z3950Server.pm +++ b/Koha/Z3950Server.pm @@ -17,7 +17,6 @@ package Koha::Z3950Server; use Modern::Perl; - use Koha::Database; use base qw(Koha::Object); diff --git a/Koha/Z3950Servers.pm b/Koha/Z3950Servers.pm index 96bf35245f..6a63090d33 100644 --- a/Koha/Z3950Servers.pm +++ b/Koha/Z3950Servers.pm @@ -17,7 +17,6 @@ package Koha::Z3950Servers; use Modern::Perl; - use Koha::Database; use Koha::Z3950Server; diff --git a/Koha/pdfformat/layout2pages.pm b/Koha/pdfformat/layout2pages.pm index 365273d8cb..0e869a0f36 100644 --- a/Koha/pdfformat/layout2pages.pm +++ b/Koha/pdfformat/layout2pages.pm @@ -30,13 +30,12 @@ use Koha::DateUtils qw( dt_from_string output_pref ); use Koha::Libraries; BEGIN { - use Exporter (); - our (@ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS); - @ISA = qw(Exporter); - @EXPORT = qw(printpdf); + use Exporter (); + our ( @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS ); + @ISA = qw(Exporter); + @EXPORT = qw(printpdf); } - #be careful, all the sizes (height, width, etc...) are in mm, not PostScript points (the default measurment of PDF::API2). #The constants exported transform that into PostScript points (/mm for milimeter, /in for inch, pt is postscript point, and as so is there only to show what is happening. use constant mm => 25.4 / 72; @@ -44,54 +43,65 @@ use constant in => 1 / 72; use constant pt => 1; use PDF::API2; + #A4 paper specs -my ($height, $width) = (297, 210); +my ( $height, $width ) = ( 297, 210 ); use PDF::Table; sub printorders { - my ($pdf, $basketgroup, $baskets, $orders) = @_; - + my ( $pdf, $basketgroup, $baskets, $orders ) = @_; + my $cur_format = C4::Context->preference("CurrencyFormat"); - $pdf->mediabox($height/mm, $width/mm); + $pdf->mediabox( $height / mm, $width / mm ); my $page = $pdf->page(); - + my $pdftable = PDF::Table->new(); - + my $abaskets; my $arrbasket; - my @keys = ('Basket (no.)', 'Document', 'Qty', 'RRP tax inc.', 'Discount', 'Tax', 'Total tax exc.', 'Total tax inc.'); + my @keys = + ( 'Basket (no.)', 'Document', 'Qty', 'RRP tax inc.', 'Discount', 'Tax', 'Total tax exc.', 'Total tax inc.' ); for my $bkey (@keys) { - push(@$arrbasket, $bkey); + push( @$arrbasket, $bkey ); } - push(@$abaskets, $arrbasket); + push( @$abaskets, $arrbasket ); my $titleinfo; - for my $basket (@$baskets){ - for my $line (@{$orders->{$basket->{basketno}}}) { + for my $basket (@$baskets) { + for my $line ( @{ $orders->{ $basket->{basketno} } } ) { $arrbasket = undef; $titleinfo = ""; if ( C4::Context->preference("marcflavour") eq 'UNIMARC' ) { - $titleinfo = $line->{title} . " / " . $line->{author} . - ( $line->{isbn} ? " ISBN: " . $line->{isbn} : '' ) . - ( $line->{en} ? " EN: " . $line->{en} : '' ) . - ( $line->{itemtype} ? ", " . $line->{itemtype} : '' ) . - ( $line->{edition} ? ", " . $line->{edition} : '' ) . - ( $line->{publishercode} ? ' published by '. $line->{publishercode} : '') . - ( $line->{publicationyear} ? ', '. $line->{publicationyear} : ''); + $titleinfo = + $line->{title} . " / " + . $line->{author} + . ( $line->{isbn} ? " ISBN: " . $line->{isbn} : '' ) + . ( $line->{en} ? " EN: " . $line->{en} : '' ) + . ( $line->{itemtype} ? ", " . $line->{itemtype} : '' ) + . ( $line->{edition} ? ", " . $line->{edition} : '' ) + . ( $line->{publishercode} ? ' published by ' . $line->{publishercode} : '' ) + . ( $line->{publicationyear} ? ', ' . $line->{publicationyear} : '' ); + } else { # MARC21 + $titleinfo = + $line->{title} . " " + . $line->{author} + . ( $line->{isbn} ? " ISBN: " . $line->{isbn} : '' ) + . ( $line->{en} ? " EN: " . $line->{en} : '' ) + . ( $line->{itemtype} ? " " . $line->{itemtype} : '' ) + . ( $line->{edition} ? ", " . $line->{edition} : '' ) + . ( $line->{publishercode} ? ' published by ' . $line->{publishercode} : '' ) + . ( $line->{copyrightdate} ? ' ' . $line->{copyrightdate} : '' ); } - else { # MARC21 - $titleinfo = $line->{title} . " " . $line->{author} . - ( $line->{isbn} ? " ISBN: " . $line->{isbn} : '' ) . - ( $line->{en} ? " EN: " . $line->{en} : '' ) . - ( $line->{itemtype} ? " " . $line->{itemtype} : '' ) . - ( $line->{edition} ? ", " . $line->{edition} : '' ) . - ( $line->{publishercode} ? ' published by '. $line->{publishercode} : '') . - ( $line->{copyrightdate} ? ' '. $line->{copyrightdate} : ''); - } - push( @$arrbasket, + push( + @$arrbasket, $basket->{basketno}, - $titleinfo. ($line->{order_vendornote} ? "\n----------------\nNote for vendor : " . $line->{order_vendornote} : '' ), + $titleinfo + . ( + $line->{order_vendornote} + ? "\n----------------\nNote for vendor : " . $line->{order_vendornote} + : '' + ), $line->{quantity}, Koha::Number::Price->new( $line->{rrp_tax_included} )->format, Koha::Number::Price->new( $line->{discount} )->format . '%', @@ -99,31 +109,32 @@ sub printorders { Koha::Number::Price->new( $line->{total_tax_excluded} )->format, Koha::Number::Price->new( $line->{total_tax_included} )->format, ); - push(@$abaskets, $arrbasket); + push( @$abaskets, $arrbasket ); } } - - $pdftable->table($pdf, $page, $abaskets, - x => 10/mm, - w => ($width - 20)/mm, - start_y => 285/mm, - next_y => 285/mm, - start_h => 260/mm, - next_h => 260/mm, - padding => 5, - padding_right => 5, - background_color_odd => "lightgray", - font => $pdf->corefont("Times", -encoding => "utf8"), - font_size => 3/mm, - header_props => { - font => $pdf->corefont("Times", -encoding => "utf8"), - font_size => 10, - bg_color => 'gray', - repeat => 1, + + $pdftable->table( + $pdf, $page, $abaskets, + x => 10 / mm, + w => ( $width - 20 ) / mm, + start_y => 285 / mm, + next_y => 285 / mm, + start_h => 260 / mm, + next_h => 260 / mm, + padding => 5, + padding_right => 5, + background_color_odd => "lightgray", + font => $pdf->corefont( "Times", -encoding => "utf8" ), + font_size => 3 / mm, + header_props => { + font => $pdf->corefont( "Times", -encoding => "utf8" ), + font_size => 10, + bg_color => 'gray', + repeat => 1, }, column_props => [ - { justify => 'left' }, - { min_w => 90/mm }, + { justify => 'left' }, + { min_w => 90 / mm }, { justify => 'right' }, { justify => 'right' }, { justify => 'right' }, @@ -132,88 +143,90 @@ sub printorders { { justify => 'right' }, ], ); - - $pdf->mediabox($width/mm, $height/mm); + + $pdf->mediabox( $width / mm, $height / mm ); } sub printhead { - my ($pdf, $basketgroup, $bookseller) = @_; + my ( $pdf, $basketgroup, $bookseller ) = @_; # get library name - my $libraryname = C4::Context->preference("LibraryName"); - my $billing_library = Koha::Libraries->find( $basketgroup->{billingplace} ); - my $delivery_library = Koha::Libraries->find( $basketgroup->{deliveryplace} ); + my $libraryname = C4::Context->preference("LibraryName"); + my $billing_library = Koha::Libraries->find( $basketgroup->{billingplace} ); + my $delivery_library = Koha::Libraries->find( $basketgroup->{deliveryplace} ); my $freedeliveryplace = $basketgroup->{freedeliveryplace}; + # get the subject my $subject; # open 1st page (with the header) my $page = $pdf->openpage(1); - + # create a text my $text = $page->text; - + # print the libraryname in the header - $text->font( $pdf->corefont("Times", -encoding => "utf8"), 6/mm ); - $text->translate(30/mm, ($height-28.5)/mm); + $text->font( $pdf->corefont( "Times", -encoding => "utf8" ), 6 / mm ); + $text->translate( 30 / mm, ( $height - 28.5 ) / mm ); $text->text($libraryname); # print order info, on the default PDF - $text->font( $pdf->corefont("Times", -encoding => "utf8"), 8/mm ); - $text->translate(100/mm, ($height-5-48)/mm); - $text->text($basketgroup->{'id'}); - + $text->font( $pdf->corefont( "Times", -encoding => "utf8" ), 8 / mm ); + $text->translate( 100 / mm, ( $height - 5 - 48 ) / mm ); + $text->text( $basketgroup->{'id'} ); + # print the date - my $today = output_pref({ dt => dt_from_string, dateonly => 1 }); - $text->translate(130/mm, ($height-5-48)/mm); + my $today = output_pref( { dt => dt_from_string, dateonly => 1 } ); + $text->translate( 130 / mm, ( $height - 5 - 48 ) / mm ); $text->text($today); - - $text->font( $pdf->corefont("Times", -encoding => "utf8"), 4/mm ); - + + $text->font( $pdf->corefont( "Times", -encoding => "utf8" ), 4 / mm ); + # print billing infos - $text->translate(100/mm, ($height-86)/mm); + $text->translate( 100 / mm, ( $height - 86 ) / mm ); $text->text($libraryname); - $text->translate(100/mm, ($height-97)/mm); - $text->text($billing_library->branchname); - $text->translate(100/mm, ($height-108.5)/mm); - $text->text($billing_library->branchphone); - $text->translate(100/mm, ($height-115.5)/mm); - $text->text($billing_library->branchfax); - $text->translate(100/mm, ($height-122.5)/mm); - $text->text($billing_library->branchaddress1); - $text->translate(100/mm, ($height-127.5)/mm); - $text->text($billing_library->branchaddress2); - $text->translate(100/mm, ($height-132.5)/mm); - $text->text($billing_library->branchaddress3); - $text->translate(100/mm, ($height-137.5)/mm); - $text->text(join(' ', $billing_library->branchzip, $billing_library->branchcity, $billing_library->branchcountry)); - $text->translate(100/mm, ($height-147.5)/mm); - $text->text($billing_library->branchemail); - + $text->translate( 100 / mm, ( $height - 97 ) / mm ); + $text->text( $billing_library->branchname ); + $text->translate( 100 / mm, ( $height - 108.5 ) / mm ); + $text->text( $billing_library->branchphone ); + $text->translate( 100 / mm, ( $height - 115.5 ) / mm ); + $text->text( $billing_library->branchfax ); + $text->translate( 100 / mm, ( $height - 122.5 ) / mm ); + $text->text( $billing_library->branchaddress1 ); + $text->translate( 100 / mm, ( $height - 127.5 ) / mm ); + $text->text( $billing_library->branchaddress2 ); + $text->translate( 100 / mm, ( $height - 132.5 ) / mm ); + $text->text( $billing_library->branchaddress3 ); + $text->translate( 100 / mm, ( $height - 137.5 ) / mm ); + $text->text( + join( ' ', $billing_library->branchzip, $billing_library->branchcity, $billing_library->branchcountry ) ); + $text->translate( 100 / mm, ( $height - 147.5 ) / mm ); + $text->text( $billing_library->branchemail ); + # print subject - $text->translate(100/mm, ($height-145.5)/mm); + $text->translate( 100 / mm, ( $height - 145.5 ) / mm ); $text->text($subject); - + # print bookseller infos - $text->translate(100/mm, ($height-180)/mm); - $text->text($bookseller->name); - $text->translate(100/mm, ($height-185)/mm); - $text->text($bookseller->postal); - $text->translate(100/mm, ($height-190)/mm); - $text->text($bookseller->address1); - $text->translate(100/mm, ($height-195)/mm); - $text->text($bookseller->address2); - $text->translate(100/mm, ($height-200)/mm); - $text->text($bookseller->address3); - $text->translate(100/mm, ($height-205)/mm); - $text->text($bookseller->accountnumber); - + $text->translate( 100 / mm, ( $height - 180 ) / mm ); + $text->text( $bookseller->name ); + $text->translate( 100 / mm, ( $height - 185 ) / mm ); + $text->text( $bookseller->postal ); + $text->translate( 100 / mm, ( $height - 190 ) / mm ); + $text->text( $bookseller->address1 ); + $text->translate( 100 / mm, ( $height - 195 ) / mm ); + $text->text( $bookseller->address2 ); + $text->translate( 100 / mm, ( $height - 200 ) / mm ); + $text->text( $bookseller->address3 ); + $text->translate( 100 / mm, ( $height - 205 ) / mm ); + $text->text( $bookseller->accountnumber ); + # print delivery infos - $text->font( $pdf->corefont("Times-Bold", -encoding => "utf8"), 4/mm ); - $text->translate(50/mm, ($height-237)/mm); + $text->font( $pdf->corefont( "Times-Bold", -encoding => "utf8" ), 4 / mm ); + $text->translate( 50 / mm, ( $height - 237 ) / mm ); if ($freedeliveryplace) { my $start = 242; - my @fdp = split('\n', $freedeliveryplace); + my @fdp = split( '\n', $freedeliveryplace ); foreach (@fdp) { $text->text($_); $text->translate( 50 / mm, ( $height - $start ) / mm ); @@ -226,35 +239,44 @@ sub printhead { $text->translate( 50 / mm, ( $height - 247 ) / mm ); $text->text( $delivery_library->branchaddress3 ); $text->translate( 50 / mm, ( $height - 252 ) / mm ); - $text->text( join( ' ', $delivery_library->branchzip, $delivery_library->branchcity, $delivery_library->branchcountry ) ); + $text->text( + join( ' ', $delivery_library->branchzip, $delivery_library->branchcity, $delivery_library->branchcountry ) + ); } - $text->translate(50/mm, ($height-262)/mm); - $text->text($basketgroup->{deliverycomment}); + $text->translate( 50 / mm, ( $height - 262 ) / mm ); + $text->text( $basketgroup->{deliverycomment} ); } sub printfooters { my $pdf = shift; - for ( 1..$pdf->pages ) { + for ( 1 .. $pdf->pages ) { my $page = $pdf->openpage($_); my $text = $page->text; - $text->font( $pdf->corefont("Times", -encoding => "utf8"), 3/mm ); - $text->translate(10/mm, 10/mm); - $text->text("Page $_ / ".$pdf->pages); + $text->font( $pdf->corefont( "Times", -encoding => "utf8" ), 3 / mm ); + $text->translate( 10 / mm, 10 / mm ); + $text->text( "Page $_ / " . $pdf->pages ); } } sub printpdf { - my ($basketgroup, $bookseller, $baskets, $orders, $GST) = @_; + my ( $basketgroup, $bookseller, $baskets, $orders, $GST ) = @_; + # open the default PDF that will be used for base (1st page already filled) - my $pdf_template = C4::Context->config('intrahtdocs') . '/' . C4::Context->preference('template') . '/pdf/layout2pages.pdf'; + my $pdf_template = + C4::Context->config('intrahtdocs') . '/' . C4::Context->preference('template') . '/pdf/layout2pages.pdf'; my $pdf = PDF::API2->open($pdf_template); - $pdf->pageLabel( 0, { - -style => 'roman', - } ); # start with roman numbering - # fill the 1st page (basketgroup information) - printhead($pdf, $basketgroup, $bookseller); + $pdf->pageLabel( + 0, + { + -style => 'roman', + } + ); # start with roman numbering + # fill the 1st page (basketgroup information) + printhead( $pdf, $basketgroup, $bookseller ); + # fill other pages (orders) - printorders($pdf, $basketgroup, $baskets, $orders); + printorders( $pdf, $basketgroup, $baskets, $orders ); + # print something on each page (usually the footer, but you could also put a header printfooters($pdf); return $pdf->stringify; diff --git a/Koha/pdfformat/layout2pagesde.pm b/Koha/pdfformat/layout2pagesde.pm index bdd4c2760e..66fd1db5b6 100644 --- a/Koha/pdfformat/layout2pagesde.pm +++ b/Koha/pdfformat/layout2pagesde.pm @@ -28,14 +28,14 @@ use Koha::Number::Price; use Koha::DateUtils qw( dt_from_string output_pref ); use Koha::Libraries; -our (@ISA, @EXPORT_OK); +our ( @ISA, @EXPORT_OK ); + BEGIN { require Exporter; - @ISA = qw(Exporter); + @ISA = qw(Exporter); @EXPORT_OK = qw(printpdf); } - #be careful, all the sizes (height, width, etc...) are in mm, not PostScript points (the default measurment of PDF::API2). #The constants exported transform that into PostScript points (/mm for milimeter, /in for inch, pt is postscript point, and as so is there only to show what is happening. use constant mm => 25.4 / 72; @@ -43,54 +43,67 @@ use constant in => 1 / 72; use constant pt => 1; use PDF::API2; + #A4 paper specs -my ($height, $width) = (297, 210); +my ( $height, $width ) = ( 297, 210 ); use PDF::Table; sub printorders { - my ($pdf, $basketgroup, $baskets, $orders) = @_; - + my ( $pdf, $basketgroup, $baskets, $orders ) = @_; + my $cur_format = C4::Context->preference("CurrencyFormat"); - $pdf->mediabox($height/mm, $width/mm); + $pdf->mediabox( $height / mm, $width / mm ); my $page = $pdf->page(); - + my $pdftable = PDF::Table->new(); - + my $abaskets; my $arrbasket; - my @keys = ('Bestellung', 'Titel', 'Anz.', 'Preis inkl. MWSt.', 'Rabatt', 'MWSt.', 'Gesamt, exkl. MWSt.', 'Gesamt inkl. MWSt.'); + my @keys = ( + 'Bestellung', 'Titel', 'Anz.', 'Preis inkl. MWSt.', 'Rabatt', 'MWSt.', 'Gesamt, exkl. MWSt.', + 'Gesamt inkl. MWSt.' + ); for my $bkey (@keys) { - push(@$arrbasket, $bkey); + push( @$arrbasket, $bkey ); } - push(@$abaskets, $arrbasket); + push( @$abaskets, $arrbasket ); my $titleinfo; - for my $basket (@$baskets){ - for my $line (@{$orders->{$basket->{basketno}}}) { + for my $basket (@$baskets) { + for my $line ( @{ $orders->{ $basket->{basketno} } } ) { $arrbasket = undef; $titleinfo = ""; if ( C4::Context->preference("marcflavour") eq 'UNIMARC' ) { - $titleinfo = $line->{title} . " / " . $line->{author} . - ( $line->{isbn} ? " ISBN: " . $line->{isbn} : '' ) . - ( $line->{en} ? " EN: " . $line->{en} : '' ) . - ( $line->{itemtype} ? ", " . $line->{itemtype} : '' ) . - ( $line->{edition} ? ", " . $line->{edition} : '' ) . - ( $line->{publishercode} ? ' Verlag: '. $line->{publishercode} : '') . - ( $line->{publicationyear} ? ', '. $line->{publicationyear} : ''); + $titleinfo = + $line->{title} . " / " + . $line->{author} + . ( $line->{isbn} ? " ISBN: " . $line->{isbn} : '' ) + . ( $line->{en} ? " EN: " . $line->{en} : '' ) + . ( $line->{itemtype} ? ", " . $line->{itemtype} : '' ) + . ( $line->{edition} ? ", " . $line->{edition} : '' ) + . ( $line->{publishercode} ? ' Verlag: ' . $line->{publishercode} : '' ) + . ( $line->{publicationyear} ? ', ' . $line->{publicationyear} : '' ); + } else { # MARC21 + $titleinfo = + $line->{title} . " " + . $line->{author} + . ( $line->{isbn} ? " ISBN: " . $line->{isbn} : '' ) + . ( $line->{en} ? " EN: " . $line->{en} : '' ) + . ( $line->{itemtype} ? " " . $line->{itemtype} : '' ) + . ( $line->{edition} ? ", " . $line->{edition} : '' ) + . ( $line->{publishercode} ? ' Verlag: ' . $line->{publishercode} : '' ) + . ( $line->{copyrightdate} ? ' ' . $line->{copyrightdate} : '' ); } - else { # MARC21 - $titleinfo = $line->{title} . " " . $line->{author} . - ( $line->{isbn} ? " ISBN: " . $line->{isbn} : '' ) . - ( $line->{en} ? " EN: " . $line->{en} : '' ) . - ( $line->{itemtype} ? " " . $line->{itemtype} : '' ) . - ( $line->{edition} ? ", " . $line->{edition} : '' ) . - ( $line->{publishercode} ? ' Verlag: '. $line->{publishercode} : '') . - ( $line->{copyrightdate} ? ' '. $line->{copyrightdate} : ''); - } - push( @$arrbasket, + push( + @$arrbasket, $basket->{basketno}, - $titleinfo. ($line->{order_vendornote} ? "\n----------------\nLieferantennotiz : ". $line->{order_vendornote} : '' ), + $titleinfo + . ( + $line->{order_vendornote} + ? "\n----------------\nLieferantennotiz : " . $line->{order_vendornote} + : '' + ), $line->{quantity}, Koha::Number::Price->new( $line->{rrp_tax_included} )->format, Koha::Number::Price->new( $line->{discount} )->format . '%', @@ -98,31 +111,32 @@ sub printorders { Koha::Number::Price->new( $line->{total_tax_excluded} )->format, Koha::Number::Price->new( $line->{total_tax_included} )->format, ); - push(@$abaskets, $arrbasket); + push( @$abaskets, $arrbasket ); } } - - $pdftable->table($pdf, $page, $abaskets, - x => 10/mm, - w => ($width - 20)/mm, - start_y => 285/mm, - next_y => 285/mm, - start_h => 260/mm, - next_h => 260/mm, - padding => 5, - padding_right => 5, - background_color_odd => "lightgray", - font => $pdf->corefont("Times", -encoding => "utf8"), - font_size => 3/mm, - header_props => { - font => $pdf->corefont("Times", -encoding => "utf8"), - font_size => 10, - bg_color => 'gray', - repeat => 1, + + $pdftable->table( + $pdf, $page, $abaskets, + x => 10 / mm, + w => ( $width - 20 ) / mm, + start_y => 285 / mm, + next_y => 285 / mm, + start_h => 260 / mm, + next_h => 260 / mm, + padding => 5, + padding_right => 5, + background_color_odd => "lightgray", + font => $pdf->corefont( "Times", -encoding => "utf8" ), + font_size => 3 / mm, + header_props => { + font => $pdf->corefont( "Times", -encoding => "utf8" ), + font_size => 10, + bg_color => 'gray', + repeat => 1, }, column_props => [ - { justify => 'left' }, - { min_w => 90/mm }, + { justify => 'left' }, + { min_w => 90 / mm }, { justify => 'right' }, { justify => 'right' }, { justify => 'right' }, @@ -131,88 +145,90 @@ sub printorders { { justify => 'right' }, ], ); - - $pdf->mediabox($width/mm, $height/mm); + + $pdf->mediabox( $width / mm, $height / mm ); } sub printhead { - my ($pdf, $basketgroup, $bookseller) = @_; + my ( $pdf, $basketgroup, $bookseller ) = @_; # get library name - my $libraryname = C4::Context->preference("LibraryName"); - my $billing_library = Koha::Libraries->find( $basketgroup->{billingplace} ); - my $delivery_library = Koha::Libraries->find( $basketgroup->{deliveryplace} ); + my $libraryname = C4::Context->preference("LibraryName"); + my $billing_library = Koha::Libraries->find( $basketgroup->{billingplace} ); + my $delivery_library = Koha::Libraries->find( $basketgroup->{deliveryplace} ); my $freedeliveryplace = $basketgroup->{freedeliveryplace}; + # get the subject my $subject; # open 1st page (with the header) my $page = $pdf->openpage(1); - + # create a text my $text = $page->text; - + # print the libraryname in the header - $text->font( $pdf->corefont("Times", -encoding => "utf8"), 6/mm ); - $text->translate(30/mm, ($height-28.5)/mm); + $text->font( $pdf->corefont( "Times", -encoding => "utf8" ), 6 / mm ); + $text->translate( 30 / mm, ( $height - 28.5 ) / mm ); $text->text($libraryname); # print order info, on the default PDF - $text->font( $pdf->corefont("Times", -encoding => "utf8"), 8/mm ); - $text->translate(100/mm, ($height-5-48)/mm); - $text->text($basketgroup->{'id'}); - + $text->font( $pdf->corefont( "Times", -encoding => "utf8" ), 8 / mm ); + $text->translate( 100 / mm, ( $height - 5 - 48 ) / mm ); + $text->text( $basketgroup->{'id'} ); + # print the date - my $today = output_pref({ dt => dt_from_string, dateonly => 1 }); - $text->translate(130/mm, ($height-5-48)/mm); + my $today = output_pref( { dt => dt_from_string, dateonly => 1 } ); + $text->translate( 130 / mm, ( $height - 5 - 48 ) / mm ); $text->text($today); - - $text->font( $pdf->corefont("Times", -encoding => "utf8"), 4/mm ); - + + $text->font( $pdf->corefont( "Times", -encoding => "utf8" ), 4 / mm ); + # print billing infos - $text->translate(100/mm, ($height-86)/mm); + $text->translate( 100 / mm, ( $height - 86 ) / mm ); $text->text($libraryname); - $text->translate(100/mm, ($height-97)/mm); - $text->text($billing_library->branchname); - $text->translate(100/mm, ($height-108.5)/mm); - $text->text($billing_library->branchphone); - $text->translate(100/mm, ($height-115.5)/mm); - $text->text($billing_library->branchfax); - $text->translate(100/mm, ($height-122.5)/mm); - $text->text($billing_library->branchaddress1); - $text->translate(100/mm, ($height-127.5)/mm); - $text->text($billing_library->branchaddress2); - $text->translate(100/mm, ($height-132.5)/mm); - $text->text($billing_library->branchaddress3); - $text->translate(100/mm, ($height-137.5)/mm); - $text->text(join(' ', $billing_library->branchzip, $billing_library->branchcity, $billing_library->branchcountry)); - $text->translate(100/mm, ($height-147.5)/mm); - $text->text($billing_library->branchemail); - + $text->translate( 100 / mm, ( $height - 97 ) / mm ); + $text->text( $billing_library->branchname ); + $text->translate( 100 / mm, ( $height - 108.5 ) / mm ); + $text->text( $billing_library->branchphone ); + $text->translate( 100 / mm, ( $height - 115.5 ) / mm ); + $text->text( $billing_library->branchfax ); + $text->translate( 100 / mm, ( $height - 122.5 ) / mm ); + $text->text( $billing_library->branchaddress1 ); + $text->translate( 100 / mm, ( $height - 127.5 ) / mm ); + $text->text( $billing_library->branchaddress2 ); + $text->translate( 100 / mm, ( $height - 132.5 ) / mm ); + $text->text( $billing_library->branchaddress3 ); + $text->translate( 100 / mm, ( $height - 137.5 ) / mm ); + $text->text( + join( ' ', $billing_library->branchzip, $billing_library->branchcity, $billing_library->branchcountry ) ); + $text->translate( 100 / mm, ( $height - 147.5 ) / mm ); + $text->text( $billing_library->branchemail ); + # print subject - $text->translate(100/mm, ($height-145.5)/mm); + $text->translate( 100 / mm, ( $height - 145.5 ) / mm ); $text->text($subject); - + # print bookseller infos - $text->translate(100/mm, ($height-180)/mm); - $text->text($bookseller->name); - $text->translate(100/mm, ($height-185)/mm); - $text->text($bookseller->postal); - $text->translate(100/mm, ($height-190)/mm); - $text->text($bookseller->address1); - $text->translate(100/mm, ($height-195)/mm); - $text->text($bookseller->address2); - $text->translate(100/mm, ($height-200)/mm); - $text->text($bookseller->address3); - $text->translate(100/mm, ($height-205)/mm); - $text->text($bookseller->accountnumber); - + $text->translate( 100 / mm, ( $height - 180 ) / mm ); + $text->text( $bookseller->name ); + $text->translate( 100 / mm, ( $height - 185 ) / mm ); + $text->text( $bookseller->postal ); + $text->translate( 100 / mm, ( $height - 190 ) / mm ); + $text->text( $bookseller->address1 ); + $text->translate( 100 / mm, ( $height - 195 ) / mm ); + $text->text( $bookseller->address2 ); + $text->translate( 100 / mm, ( $height - 200 ) / mm ); + $text->text( $bookseller->address3 ); + $text->translate( 100 / mm, ( $height - 205 ) / mm ); + $text->text( $bookseller->accountnumber ); + # print delivery infos - $text->font( $pdf->corefont("Times-Bold", -encoding => "utf8"), 4/mm ); - $text->translate(50/mm, ($height-237)/mm); + $text->font( $pdf->corefont( "Times-Bold", -encoding => "utf8" ), 4 / mm ); + $text->translate( 50 / mm, ( $height - 237 ) / mm ); if ($freedeliveryplace) { my $start = 242; - my @fdp = split('\n', $freedeliveryplace); + my @fdp = split( '\n', $freedeliveryplace ); foreach (@fdp) { $text->text($_); $text->translate( 50 / mm, ( $height - $start ) / mm ); @@ -225,35 +241,44 @@ sub printhead { $text->translate( 50 / mm, ( $height - 247 ) / mm ); $text->text( $delivery_library->branchaddress3 ); $text->translate( 50 / mm, ( $height - 252 ) / mm ); - $text->text( join( ' ', $delivery_library->branchzip, $delivery_library->branchcity, $delivery_library->branchcountry ) ); + $text->text( + join( ' ', $delivery_library->branchzip, $delivery_library->branchcity, $delivery_library->branchcountry ) + ); } - $text->translate(50/mm, ($height-262)/mm); - $text->text($basketgroup->{deliverycomment}); + $text->translate( 50 / mm, ( $height - 262 ) / mm ); + $text->text( $basketgroup->{deliverycomment} ); } sub printfooters { my $pdf = shift; - for ( 1..$pdf->pages ) { + for ( 1 .. $pdf->pages ) { my $page = $pdf->openpage($_); my $text = $page->text; - $text->font( $pdf->corefont("Times", -encoding => "utf8"), 3/mm ); - $text->translate(10/mm, 10/mm); - $text->text("Seite $_ / ".$pdf->pages); + $text->font( $pdf->corefont( "Times", -encoding => "utf8" ), 3 / mm ); + $text->translate( 10 / mm, 10 / mm ); + $text->text( "Seite $_ / " . $pdf->pages ); } } sub printpdf { - my ($basketgroup, $bookseller, $baskets, $orders, $GST) = @_; + my ( $basketgroup, $bookseller, $baskets, $orders, $GST ) = @_; + # open the default PDF that will be used for base (1st page already filled) - my $pdf_template = C4::Context->config('intrahtdocs') . '/' . C4::Context->preference('template') . '/pdf/layout2pagesde.pdf'; + my $pdf_template = + C4::Context->config('intrahtdocs') . '/' . C4::Context->preference('template') . '/pdf/layout2pagesde.pdf'; my $pdf = PDF::API2->open($pdf_template); - $pdf->pageLabel( 0, { - -style => 'roman', - } ); # start with roman numbering - # fill the 1st page (basketgroup information) - printhead($pdf, $basketgroup, $bookseller); + $pdf->pageLabel( + 0, + { + -style => 'roman', + } + ); # start with roman numbering + # fill the 1st page (basketgroup information) + printhead( $pdf, $basketgroup, $bookseller ); + # fill other pages (orders) - printorders($pdf, $basketgroup, $baskets, $orders); + printorders( $pdf, $basketgroup, $baskets, $orders ); + # print something on each page (usually the footer, but you could also put a header printfooters($pdf); return $pdf->stringify; diff --git a/Koha/pdfformat/layout3pages.pm b/Koha/pdfformat/layout3pages.pm index 0213c17673..f90bd45e29 100644 --- a/Koha/pdfformat/layout3pages.pm +++ b/Koha/pdfformat/layout3pages.pm @@ -21,7 +21,7 @@ package Koha::pdfformat::layout3pages; # along with Koha; if not, see . #you can use any PDF::API2 module, all you need to do is return the stringifyed pdf object from the printpdf sub. -use vars qw(@ISA @EXPORT); +use vars qw(@ISA @EXPORT); use List::MoreUtils qw( uniq ); use Modern::Perl; use utf8; @@ -32,13 +32,12 @@ use Koha::DateUtils qw( dt_from_string output_pref ); use Koha::Libraries; BEGIN { - use Exporter (); - our (@ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS); - @ISA = qw(Exporter); - @EXPORT = qw(printpdf); + use Exporter (); + our ( @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS ); + @ISA = qw(Exporter); + @EXPORT = qw(printpdf); } - #be careful, all the sizes (height, width, etc...) are in mm, not PostScript points (the default measurment of PDF::API2). #The constants exported transform that into PostScript points (/mm for milimeter, /in for inch, pt is postscript point, and as so is there only to show what is happening. use constant mm => 25.4 / 72; @@ -46,384 +45,432 @@ use constant in => 1 / 72; use constant pt => 1; use PDF::API2; + #A4 paper specs -my ($height, $width) = (297, 210); +my ( $height, $width ) = ( 297, 210 ); use PDF::Table; sub printorders { - my ($pdf, $basketgroup, $baskets, $orders) = @_; - + my ( $pdf, $basketgroup, $baskets, $orders ) = @_; + my $cur_format = C4::Context->preference("CurrencyFormat"); - $pdf->mediabox($height/mm, $width/mm); + $pdf->mediabox( $height / mm, $width / mm ); my $number = 3; - for my $basket (@$baskets){ - my $page = $pdf->page(); - my $billing_library = Koha::Libraries->find( $basket->{billingplace} ); + for my $basket (@$baskets) { + my $page = $pdf->page(); + my $billing_library = Koha::Libraries->find( $basket->{billingplace} ); my $delivery_library = Koha::Libraries->find( $basket->{deliveryplace} ); # print basket header (box) my $box = $page->gfx; - $box->rectxy(($width - 10)/mm, ($height - 5)/mm, 10/mm, ($height - 25)/mm); + $box->rectxy( ( $width - 10 ) / mm, ( $height - 5 ) / mm, 10 / mm, ( $height - 25 ) / mm ); $box->stroke; -# $box->restore(); - + + # $box->restore(); + # create a text my $text = $page->text; + # add basketgroup number - $text->font( $pdf->corefont("Times", -encoding => "utf8"), 6/mm ); - $text->translate(20/mm, ($height-15)/mm); - $text->text("Order no. ".$basketgroup->{'id'}.". Basket no. ".$basket->{basketno}.". ".$basket->{booksellernote}); - $text->translate(20/mm, ($height-20)/mm); - $text->font( $pdf->corefont("Times", -encoding => "utf8"), 4/mm ); + $text->font( $pdf->corefont( "Times", -encoding => "utf8" ), 6 / mm ); + $text->translate( 20 / mm, ( $height - 15 ) / mm ); + $text->text( "Order no. " + . $basketgroup->{'id'} + . ". Basket no. " + . $basket->{basketno} . ". " + . $basket->{booksellernote} ); + $text->translate( 20 / mm, ( $height - 20 ) / mm ); + $text->font( $pdf->corefont( "Times", -encoding => "utf8" ), 4 / mm ); $text->text( ( $billing_library ? "Billing at " . $billing_library->branchname : "" ) - . ( $billing_library and $delivery_library ? " and " : "" ) - . ( $delivery_library ? "delivery at " . $delivery_library->branchname : "" ) - ); + . ( $billing_library and $delivery_library ? " and " : "" ) + . ( $delivery_library ? "delivery at " . $delivery_library->branchname : "" ) ); my $pdftable = PDF::Table->new(); my $abaskets; my $arrbasket; - my @keys = ('Document', 'Qty', 'RRP tax exc.', 'RRP tax inc.', 'Discount', 'Discount price', 'Tax rate', 'Total tax exc.', 'Total tax inc.'); + my @keys = ( + 'Document', 'Qty', 'RRP tax exc.', 'RRP tax inc.', 'Discount', 'Discount price', 'Tax rate', + 'Total tax exc.', 'Total tax inc.' + ); for my $bkey (@keys) { - push(@$arrbasket, $bkey); + push( @$arrbasket, $bkey ); } - push(@$abaskets, $arrbasket); + push( @$abaskets, $arrbasket ); my $titleinfo; - foreach my $line (@{$orders->{$basket->{basketno}}}) { + foreach my $line ( @{ $orders->{ $basket->{basketno} } } ) { $arrbasket = undef; $titleinfo = ""; if ( C4::Context->preference("marcflavour") eq 'UNIMARC' ) { - $titleinfo = $line->{title} . " / " . $line->{author} . - ( $line->{isbn} ? " ISBN: " . $line->{isbn} : '' ) . - ( $line->{en} ? " EN: " . $line->{en} : '' ) . - ( $line->{itemtype} ? ", " . $line->{itemtype} : '' ) . - ( $line->{edition} ? ", " . $line->{edition} : '' ) . - ( $line->{publishercode} ? ' published by '. $line->{publishercode} : '') . - ( $line->{publicationyear} ? ', '. $line->{publicationyear} : ''); + $titleinfo = + $line->{title} . " / " + . $line->{author} + . ( $line->{isbn} ? " ISBN: " . $line->{isbn} : '' ) + . ( $line->{en} ? " EN: " . $line->{en} : '' ) + . ( $line->{itemtype} ? ", " . $line->{itemtype} : '' ) + . ( $line->{edition} ? ", " . $line->{edition} : '' ) + . ( $line->{publishercode} ? ' published by ' . $line->{publishercode} : '' ) + . ( $line->{publicationyear} ? ', ' . $line->{publicationyear} : '' ); + } else { # MARC21 + $titleinfo = + $line->{title} . " " + . $line->{author} + . ( $line->{isbn} ? " ISBN: " . $line->{isbn} : '' ) + . ( $line->{en} ? " EN: " . $line->{en} : '' ) + . ( $line->{itemtype} ? " " . $line->{itemtype} : '' ) + . ( $line->{edition} ? ", " . $line->{edition} : '' ) + . ( $line->{publishercode} ? ' published by ' . $line->{publishercode} : '' ) + . ( $line->{copyrightdate} ? ' ' . $line->{copyrightdate} : '' ); } - else { # MARC21 - $titleinfo = $line->{title} . " " . $line->{author} . - ( $line->{isbn} ? " ISBN: " . $line->{isbn} : '' ) . - ( $line->{en} ? " EN: " . $line->{en} : '' ) . - ( $line->{itemtype} ? " " . $line->{itemtype} : '' ) . - ( $line->{edition} ? ", " . $line->{edition} : '' ) . - ( $line->{publishercode} ? ' published by '. $line->{publishercode} : '') . - ( $line->{copyrightdate} ? ' '. $line->{copyrightdate} : ''); - } - push( @$arrbasket, - $titleinfo. ($line->{order_vendornote} ? "\n----------------\nNote for vendor : " . $line->{order_vendornote} : '' ), + push( + @$arrbasket, + $titleinfo + . ( + $line->{order_vendornote} + ? "\n----------------\nNote for vendor : " . $line->{order_vendornote} + : '' + ), $line->{quantity}, Koha::Number::Price->new( $line->{rrp_tax_excluded} )->format, Koha::Number::Price->new( $line->{rrp_tax_included} )->format, Koha::Number::Price->new( $line->{discount} )->format . '%', - Koha::Number::Price->new( $line->{rrp_tax_excluded} - $line->{ecost_tax_excluded})->format, + Koha::Number::Price->new( $line->{rrp_tax_excluded} - $line->{ecost_tax_excluded} )->format, Koha::Number::Price->new( $line->{tax_rate} * 100 )->format . '%', Koha::Number::Price->new( $line->{total_tax_excluded} )->format, Koha::Number::Price->new( $line->{total_tax_included} )->format, ); - push(@$abaskets, $arrbasket); + push( @$abaskets, $arrbasket ); } - $pdftable->table($pdf, $page, $abaskets, - x => 10/mm, - w => ($width - 20)/mm, - start_y => 270/mm, - next_y => 285/mm, - start_h => 250/mm, - next_h => 250/mm, - padding => 5, - padding_right => 5, - background_color_odd => "lightgray", - font => $pdf->corefont("Times", -encoding => "utf8"), - font_size => 3/mm, - header_props => { - font => $pdf->corefont("Times", -encoding => "utf8"), - font_size => 9, - bg_color => 'gray', - repeat => 1, - }, - column_props => [ - { - min_w => 85/mm, # Minimum column width. - }, - { - justify => 'right', # One of left|right , - }, - { - justify => 'right', # One of left|right , - }, - { - justify => 'right', # One of left|right , - }, - { - justify => 'right', # One of left|right , - }, - { - justify => 'right', # One of left|right , - }, - { - justify => 'right', # One of left|right , - }, - { - justify => 'right', # One of left|right , - }, - { - justify => 'right', # One of left|right , - }, - ], - ); + $pdftable->table( + $pdf, $page, $abaskets, + x => 10 / mm, + w => ( $width - 20 ) / mm, + start_y => 270 / mm, + next_y => 285 / mm, + start_h => 250 / mm, + next_h => 250 / mm, + padding => 5, + padding_right => 5, + background_color_odd => "lightgray", + font => $pdf->corefont( "Times", -encoding => "utf8" ), + font_size => 3 / mm, + header_props => { + font => $pdf->corefont( "Times", -encoding => "utf8" ), + font_size => 9, + bg_color => 'gray', + repeat => 1, + }, + column_props => [ + { + min_w => 85 / mm, # Minimum column width. + }, + { + justify => 'right', # One of left|right , + }, + { + justify => 'right', # One of left|right , + }, + { + justify => 'right', # One of left|right , + }, + { + justify => 'right', # One of left|right , + }, + { + justify => 'right', # One of left|right , + }, + { + justify => 'right', # One of left|right , + }, + { + justify => 'right', # One of left|right , + }, + { + justify => 'right', # One of left|right , + }, + ], + ); } - $pdf->mediabox($width/mm, $height/mm); + $pdf->mediabox( $width / mm, $height / mm ); } sub printbaskets { - my ($pdf, $basketgroup, $hbaskets, $bookseller, $GSTrate, $orders) = @_; - + my ( $pdf, $basketgroup, $hbaskets, $bookseller, $GSTrate, $orders ) = @_; + # get library name my $libraryname = C4::Context->preference("LibraryName"); - + my $cur_format = C4::Context->preference("CurrencyFormat"); - $pdf->mediabox($width/mm, $height/mm); + $pdf->mediabox( $width / mm, $height / mm ); my $page = $pdf->openpage(2); + # create a text my $text = $page->text; - + # add basketgroup number - $text->font( $pdf->corefont("Times", -encoding => "utf8"), 6/mm ); - $text->translate(($width-40)/mm, ($height-53)/mm); - $text->text("".$basketgroup->{'id'}); + $text->font( $pdf->corefont( "Times", -encoding => "utf8" ), 6 / mm ); + $text->translate( ( $width - 40 ) / mm, ( $height - 53 ) / mm ); + $text->text( "" . $basketgroup->{'id'} ); + # print the libraryname in the header - $text->font( $pdf->corefont("Times", -encoding => "utf8"), 6/mm ); - $text->translate(30/mm, ($height-28.5)/mm); + $text->font( $pdf->corefont( "Times", -encoding => "utf8" ), 6 / mm ); + $text->translate( 30 / mm, ( $height - 28.5 ) / mm ); $text->text($libraryname); my $pdftable = PDF::Table->new(); my $abaskets; my $arrbasket; + # header of the table - my @keys = ('Lot', 'Basket (No.)','Total RRP tax exc.', 'Total RRP tax inc.', 'Tax rate', 'Tax', 'Total discount', 'Total tax exc.', 'Total tax inc.'); + my @keys = ( + 'Lot', 'Basket (No.)', 'Total RRP tax exc.', 'Total RRP tax inc.', 'Tax rate', 'Tax', 'Total discount', + 'Total tax exc.', 'Total tax inc.' + ); for my $bkey (@keys) { - push(@$arrbasket, $bkey); + push( @$arrbasket, $bkey ); } - my ($grandtotal_rrp_tax_included, $grandtotal_rrp_tax_excluded, $grandtotal_tax_included, $grandtotal_tax_excluded, $grandtotaltax_value, $grandtotaldiscount); + my ( + $grandtotal_rrp_tax_included, $grandtotal_rrp_tax_excluded, $grandtotal_tax_included, + $grandtotal_tax_excluded, $grandtotaltax_value, $grandtotaldiscount + ); + # calculate each basket total - push(@$abaskets, $arrbasket); + push( @$abaskets, $arrbasket ); for my $basket (@$hbaskets) { my @gst; $arrbasket = undef; - my ($total_rrp_tax_excluded, $total_rrp_tax_included, $total_tax_excluded, $total_tax_included, $totaltax_value, $totaldiscount); - my $ords = $orders->{$basket->{basketno}}; + my ( + $total_rrp_tax_excluded, $total_rrp_tax_included, $total_tax_excluded, $total_tax_included, + $totaltax_value, $totaldiscount + ); + my $ords = $orders->{ $basket->{basketno} }; my $ordlength = @$ords; foreach my $ord (@$ords) { $total_tax_excluded += $ord->{total_tax_excluded}; $total_tax_included += $ord->{total_tax_included}; - $totaltax_value += $ord->{tax_value}; - $totaldiscount += (get_rounded_price($ord->{rrp_tax_excluded}) - get_rounded_price($ord->{ecost_tax_excluded}) ) * $ord->{quantity}; - $total_rrp_tax_excluded += get_rounded_price($ord->{rrp_tax_excluded}) * $ord->{quantity}; - $total_rrp_tax_included += get_rounded_price($ord->{rrp_tax_included}) * $ord->{quantity}; + $totaltax_value += $ord->{tax_value}; + $totaldiscount += + ( get_rounded_price( $ord->{rrp_tax_excluded} ) - get_rounded_price( $ord->{ecost_tax_excluded} ) ) * + $ord->{quantity}; + $total_rrp_tax_excluded += get_rounded_price( $ord->{rrp_tax_excluded} ) * $ord->{quantity}; + $total_rrp_tax_included += get_rounded_price( $ord->{rrp_tax_included} ) * $ord->{quantity}; push @gst, $ord->{tax_rate}; } @gst = uniq map { $_ * 100 } @gst; $grandtotal_rrp_tax_excluded += $total_rrp_tax_excluded; $grandtotal_rrp_tax_included += $total_rrp_tax_included; - $grandtotal_tax_included += $total_tax_included; - $grandtotal_tax_excluded += $total_tax_excluded; - $grandtotaltax_value += $totaltax_value; - $grandtotaldiscount += $totaldiscount; + $grandtotal_tax_included += $total_tax_included; + $grandtotal_tax_excluded += $total_tax_excluded; + $grandtotaltax_value += $totaltax_value; + $grandtotaldiscount += $totaldiscount; my @gst_string = - map { Koha::Number::Price->new($_)->format . '%' } @gst; - push(@$arrbasket, + map { Koha::Number::Price->new($_)->format . '%' } @gst; + push( + @$arrbasket, $basket->{contractname}, $basket->{basketname} . ' (No. ' . $basket->{basketno} . ')', - Koha::Number::Price->new( $total_rrp_tax_excluded )->format, - Koha::Number::Price->new( $total_rrp_tax_included )->format, + Koha::Number::Price->new($total_rrp_tax_excluded)->format, + Koha::Number::Price->new($total_rrp_tax_included)->format, "@gst_string", - Koha::Number::Price->new( $totaltax_value )->format, - Koha::Number::Price->new( $totaldiscount )->format, - Koha::Number::Price->new( $total_tax_excluded )->format, - Koha::Number::Price->new( $total_tax_included )->format, + Koha::Number::Price->new($totaltax_value)->format, + Koha::Number::Price->new($totaldiscount)->format, + Koha::Number::Price->new($total_tax_excluded)->format, + Koha::Number::Price->new($total_tax_included)->format, ); - push(@$abaskets, $arrbasket); + push( @$abaskets, $arrbasket ); } + # now, push total undef $arrbasket; push @$arrbasket, - '', - 'Total', - Koha::Number::Price->new( $grandtotal_rrp_tax_excluded )->format, - Koha::Number::Price->new( $grandtotal_rrp_tax_included )->format, - '', - Koha::Number::Price->new( $grandtotaltax_value )->format, - Koha::Number::Price->new( $grandtotaldiscount )->format, - Koha::Number::Price->new( $grandtotal_tax_excluded )->format, - Koha::Number::Price->new( $grandtotal_tax_included )->format; - push @$abaskets,$arrbasket; + '', + 'Total', + Koha::Number::Price->new($grandtotal_rrp_tax_excluded)->format, + Koha::Number::Price->new($grandtotal_rrp_tax_included)->format, + '', + Koha::Number::Price->new($grandtotaltax_value)->format, + Koha::Number::Price->new($grandtotaldiscount)->format, + Koha::Number::Price->new($grandtotal_tax_excluded)->format, + Koha::Number::Price->new($grandtotal_tax_included)->format; + push @$abaskets, $arrbasket; + # height is width and width is height in this function, as the pdf is in landscape mode for the Tables. - $pdftable->table($pdf, $page, $abaskets, - x => 5/mm, - w => ($width - 10)/mm, - start_y => 230/mm, - next_y => 230/mm, - start_h => 230/mm, - next_h => 230/mm, - font => $pdf->corefont("Times", -encoding => "utf8"), - font_size => 3/mm, - padding => 5, - padding_right => 10, - background_color_odd => "lightgray", - header_props => { - bg_color => 'gray', - repeat => 1, - }, - column_props => [ - { - }, - { - }, - { - justify => 'right', - }, - { - justify => 'right', - }, - { - justify => 'right', - }, - { - justify => 'right', - }, - { - justify => 'right', - }, - ], + $pdftable->table( + $pdf, $page, $abaskets, + x => 5 / mm, + w => ( $width - 10 ) / mm, + start_y => 230 / mm, + next_y => 230 / mm, + start_h => 230 / mm, + next_h => 230 / mm, + font => $pdf->corefont( "Times", -encoding => "utf8" ), + font_size => 3 / mm, + padding => 5, + padding_right => 10, + background_color_odd => "lightgray", + header_props => { + bg_color => 'gray', + repeat => 1, + }, + column_props => [ + {}, + {}, + { + justify => 'right', + }, + { + justify => 'right', + }, + { + justify => 'right', + }, + { + justify => 'right', + }, + { + justify => 'right', + }, + ], ); - $pdf->mediabox($height/mm, $width/mm); + $pdf->mediabox( $height / mm, $width / mm ); } sub printhead { - my ($pdf, $basketgroup, $bookseller) = @_; + my ( $pdf, $basketgroup, $bookseller ) = @_; # get library name - my $libraryname = C4::Context->preference("LibraryName"); - my $billing_library = Koha::Libraries->find( $basketgroup->{billingplace} ); - my $delivery_library = Koha::Libraries->find( $basketgroup->{deliveryplace} ); + my $libraryname = C4::Context->preference("LibraryName"); + my $billing_library = Koha::Libraries->find( $basketgroup->{billingplace} ); + my $delivery_library = Koha::Libraries->find( $basketgroup->{deliveryplace} ); my $freedeliveryplace = $basketgroup->{freedeliveryplace}; + # get the subject my $subject; # open 1st page (with the header) my $page = $pdf->openpage(1); - + # create a text my $text = $page->text; - + # print the libraryname in the header - $text->font( $pdf->corefont("Times", -encoding => "utf8"), 6/mm ); - $text->translate(30/mm, ($height-28.5)/mm); + $text->font( $pdf->corefont( "Times", -encoding => "utf8" ), 6 / mm ); + $text->translate( 30 / mm, ( $height - 28.5 ) / mm ); $text->text($libraryname); # print order info, on the default PDF - $text->font( $pdf->corefont("Times", -encoding => "utf8"), 8/mm ); - $text->translate(100/mm, ($height-5-48)/mm); - $text->text($basketgroup->{'id'}); - + $text->font( $pdf->corefont( "Times", -encoding => "utf8" ), 8 / mm ); + $text->translate( 100 / mm, ( $height - 5 - 48 ) / mm ); + $text->text( $basketgroup->{'id'} ); + # print the date - my $today = output_pref({ dt => dt_from_string, dateonly => 1 }); - $text->translate(130/mm, ($height-5-48)/mm); + my $today = output_pref( { dt => dt_from_string, dateonly => 1 } ); + $text->translate( 130 / mm, ( $height - 5 - 48 ) / mm ); $text->text($today); - - $text->font( $pdf->corefont("Times", -encoding => "utf8"), 4/mm ); - + + $text->font( $pdf->corefont( "Times", -encoding => "utf8" ), 4 / mm ); + # print billing infos - $text->translate(100/mm, ($height-86)/mm); + $text->translate( 100 / mm, ( $height - 86 ) / mm ); $text->text($libraryname); - $text->translate(100/mm, ($height-97)/mm); - $text->text($billing_library->branchname); - $text->translate(100/mm, ($height-108.5)/mm); - $text->text($billing_library->branchphone); - $text->translate(100/mm, ($height-115.5)/mm); - $text->text($billing_library->branchfax); - $text->translate(100/mm, ($height-122.5)/mm); - $text->text($billing_library->branchaddress1); - $text->translate(100/mm, ($height-127.5)/mm); - $text->text($billing_library->branchaddress2); - $text->translate(100/mm, ($height-132.5)/mm); - $text->text($billing_library->branchaddress3); - $text->translate(100/mm, ($height-137.5)/mm); - $text->text(join(' ', $billing_library->branchzip, $billing_library->branchcity, $billing_library->branchcountry)); - $text->translate(100/mm, ($height-147.5)/mm); - $text->text($billing_library->branchemail); - + $text->translate( 100 / mm, ( $height - 97 ) / mm ); + $text->text( $billing_library->branchname ); + $text->translate( 100 / mm, ( $height - 108.5 ) / mm ); + $text->text( $billing_library->branchphone ); + $text->translate( 100 / mm, ( $height - 115.5 ) / mm ); + $text->text( $billing_library->branchfax ); + $text->translate( 100 / mm, ( $height - 122.5 ) / mm ); + $text->text( $billing_library->branchaddress1 ); + $text->translate( 100 / mm, ( $height - 127.5 ) / mm ); + $text->text( $billing_library->branchaddress2 ); + $text->translate( 100 / mm, ( $height - 132.5 ) / mm ); + $text->text( $billing_library->branchaddress3 ); + $text->translate( 100 / mm, ( $height - 137.5 ) / mm ); + $text->text( + join( ' ', $billing_library->branchzip, $billing_library->branchcity, $billing_library->branchcountry ) ); + $text->translate( 100 / mm, ( $height - 147.5 ) / mm ); + $text->text( $billing_library->branchemail ); + # print subject - $text->translate(100/mm, ($height-145.5)/mm); + $text->translate( 100 / mm, ( $height - 145.5 ) / mm ); $text->text($subject); - + # print bookseller infos - $text->translate(100/mm, ($height-180)/mm); - $text->text($bookseller->name); - $text->translate(100/mm, ($height-185)/mm); - $text->text($bookseller->postal); - $text->translate(100/mm, ($height-190)/mm); - $text->text($bookseller->address1); - $text->translate(100/mm, ($height-195)/mm); - $text->text($bookseller->address2); - $text->translate(100/mm, ($height-200)/mm); - $text->text($bookseller->address3); - $text->translate(100/mm, ($height-205)/mm); - $text->text($bookseller->accountnumber); - + $text->translate( 100 / mm, ( $height - 180 ) / mm ); + $text->text( $bookseller->name ); + $text->translate( 100 / mm, ( $height - 185 ) / mm ); + $text->text( $bookseller->postal ); + $text->translate( 100 / mm, ( $height - 190 ) / mm ); + $text->text( $bookseller->address1 ); + $text->translate( 100 / mm, ( $height - 195 ) / mm ); + $text->text( $bookseller->address2 ); + $text->translate( 100 / mm, ( $height - 200 ) / mm ); + $text->text( $bookseller->address3 ); + $text->translate( 100 / mm, ( $height - 205 ) / mm ); + $text->text( $bookseller->accountnumber ); + # print delivery infos - $text->font( $pdf->corefont("Times-Bold", -encoding => "utf8"), 4/mm ); - $text->translate(50/mm, ($height-237)/mm); + $text->font( $pdf->corefont( "Times-Bold", -encoding => "utf8" ), 4 / mm ); + $text->translate( 50 / mm, ( $height - 237 ) / mm ); if ($freedeliveryplace) { my $start = 242; - my @fdp = split('\n', $freedeliveryplace); + my @fdp = split( '\n', $freedeliveryplace ); foreach (@fdp) { $text->text($_); $text->translate( 50 / mm, ( $height - $start ) / mm ); $start += 5; } } else { - $text->text($delivery_library->branchaddress1); - $text->translate(50/mm, ($height-242)/mm); - $text->text($delivery_library->branchaddress2); - $text->translate(50/mm, ($height-247)/mm); - $text->text($delivery_library->branchaddress3); - $text->translate(50/mm, ($height-252)/mm); - $text->text(join(' ', $delivery_library->branchzip, $delivery_library->branchcity, $delivery_library->branchcountry)); + $text->text( $delivery_library->branchaddress1 ); + $text->translate( 50 / mm, ( $height - 242 ) / mm ); + $text->text( $delivery_library->branchaddress2 ); + $text->translate( 50 / mm, ( $height - 247 ) / mm ); + $text->text( $delivery_library->branchaddress3 ); + $text->translate( 50 / mm, ( $height - 252 ) / mm ); + $text->text( + join( ' ', $delivery_library->branchzip, $delivery_library->branchcity, $delivery_library->branchcountry ) + ); } - $text->translate(50/mm, ($height-262)/mm); - $text->text($basketgroup->{deliverycomment}); + $text->translate( 50 / mm, ( $height - 262 ) / mm ); + $text->text( $basketgroup->{deliverycomment} ); } sub printfooters { - my ($pdf) = @_; - for (my $i=1;$i <= $pdf->pages;$i++) { + my ($pdf) = @_; + for ( my $i = 1 ; $i <= $pdf->pages ; $i++ ) { my $page = $pdf->openpage($i); my $text = $page->text; - $text->font( $pdf->corefont("Times", -encoding => "utf8"), 3/mm ); - $text->translate(10/mm, 10/mm); - $text->text("Page $i / ".$pdf->pages); - } + $text->font( $pdf->corefont( "Times", -encoding => "utf8" ), 3 / mm ); + $text->translate( 10 / mm, 10 / mm ); + $text->text( "Page $i / " . $pdf->pages ); + } } sub printpdf { - my ($basketgroup, $bookseller, $baskets, $orders, $GST) = @_; + my ( $basketgroup, $bookseller, $baskets, $orders, $GST ) = @_; + # open the default PDF that will be used for base (1st page already filled) - my $pdf_template = C4::Context->config('intrahtdocs') . '/' . C4::Context->preference('template') . '/pdf/layout3pages.pdf'; + my $pdf_template = + C4::Context->config('intrahtdocs') . '/' . C4::Context->preference('template') . '/pdf/layout3pages.pdf'; my $pdf = PDF::API2->open($pdf_template); - $pdf->pageLabel( 0, { - -style => 'roman', - } ); # start with roman numbering - # fill the 1st page (basketgroup information) - printhead($pdf, $basketgroup, $bookseller); + $pdf->pageLabel( + 0, + { + -style => 'roman', + } + ); # start with roman numbering + # fill the 1st page (basketgroup information) + printhead( $pdf, $basketgroup, $bookseller ); + # fill the 2nd page (orders summary) - printbaskets($pdf, $basketgroup, $baskets, $bookseller, $GST, $orders); + printbaskets( $pdf, $basketgroup, $baskets, $bookseller, $GST, $orders ); + # fill other pages (orders) - printorders($pdf, $basketgroup, $baskets, $orders); + printorders( $pdf, $basketgroup, $baskets, $orders ); + # print something on each page (usually the footer, but you could also put a header printfooters($pdf); return $pdf->stringify; diff --git a/Koha/pdfformat/layout3pagesfr.pm b/Koha/pdfformat/layout3pagesfr.pm index 21f3f0270d..f95d518a01 100644 --- a/Koha/pdfformat/layout3pagesfr.pm +++ b/Koha/pdfformat/layout3pagesfr.pm @@ -33,13 +33,12 @@ use Koha::DateUtils qw( dt_from_string output_pref ); use Koha::Libraries; BEGIN { - use Exporter (); - our (@ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS); - @ISA = qw(Exporter); - @EXPORT = qw(printpdf); + use Exporter (); + our ( @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS ); + @ISA = qw(Exporter); + @EXPORT = qw(printpdf); } - #be careful, all the sizes (height, width, etc...) are in mm, not PostScript points (the default measurment of PDF::API2). #The constants exported transform that into PostScript points (/mm for milimeter, /in for inch, pt is postscript point, and as so is there only to show what is happening. use constant mm => 25.4 / 72; @@ -47,182 +46,208 @@ use constant in => 1 / 72; use constant pt => 1; use PDF::API2; + #A4 paper specs -my ($height, $width) = (297, 210); +my ( $height, $width ) = ( 297, 210 ); use PDF::Table; sub printorders { - my ($pdf, $basketgroup, $baskets, $orders) = @_; + my ( $pdf, $basketgroup, $baskets, $orders ) = @_; my $cur_format = C4::Context->preference("CurrencyFormat"); - $pdf->mediabox($height/mm, $width/mm); + $pdf->mediabox( $height / mm, $width / mm ); my $number = 3; - for my $basket (@$baskets){ - my $page = $pdf->page(); - my $billing_library = Koha::Libraries->find( $basket->{billingplace} ); + for my $basket (@$baskets) { + my $page = $pdf->page(); + my $billing_library = Koha::Libraries->find( $basket->{billingplace} ); my $delivery_library = Koha::Libraries->find( $basket->{deliveryplace} ); # print basket header (box) my $box = $page->gfx; - $box->rectxy(($width - 10)/mm, ($height - 5)/mm, 10/mm, ($height - 25)/mm); + $box->rectxy( ( $width - 10 ) / mm, ( $height - 5 ) / mm, 10 / mm, ( $height - 25 ) / mm ); $box->stroke; -# $box->restore(); + + # $box->restore(); # create a text my $text = $page->text; + # add basketgroup number - $text->font( $pdf->corefont("Times", -encoding => "utf8"), 6/mm ); - $text->translate(20/mm, ($height-15)/mm); - $text->text("Commande N°".$basketgroup->{'id'}.". Panier N° ".$basket->{basketno}.". ".$basket->{booksellernote}); - $text->translate(20/mm, ($height-20)/mm); - $text->font( $pdf->corefont("Times", -encoding => "utf8"), 4/mm ); + $text->font( $pdf->corefont( "Times", -encoding => "utf8" ), 6 / mm ); + $text->translate( 20 / mm, ( $height - 15 ) / mm ); + $text->text( "Commande N°" + . $basketgroup->{'id'} + . ". Panier N° " + . $basket->{basketno} . ". " + . $basket->{booksellernote} ); + $text->translate( 20 / mm, ( $height - 20 ) / mm ); + $text->font( $pdf->corefont( "Times", -encoding => "utf8" ), 4 / mm ); $text->text( ( $billing_library ? "Facturation à " . $billing_library->branchname : "" ) - . ( $billing_library and $delivery_library ? " et " : "" ) - . ( $delivery_library ? "livraison à " . $delivery_library->branchname : "" ) - ); + . ( $billing_library and $delivery_library ? " et " : "" ) + . ( $delivery_library ? "livraison à " . $delivery_library->branchname : "" ) ); my $pdftable = PDF::Table->new(); my $abaskets; my $arrbasket; - my @keys = ('Document', 'Qté', 'Prix', 'Prix net', '% Remise', 'Remise', 'Taux TVA', 'Total HT', 'Total TTC'); + my @keys = ( 'Document', 'Qté', 'Prix', 'Prix net', '% Remise', 'Remise', 'Taux TVA', 'Total HT', 'Total TTC' ); for my $bkey (@keys) { - push(@$arrbasket, $bkey); + push( @$arrbasket, $bkey ); } - push(@$abaskets, $arrbasket); + push( @$abaskets, $arrbasket ); my $titleinfo; - foreach my $line (@{$orders->{$basket->{basketno}}}) { + foreach my $line ( @{ $orders->{ $basket->{basketno} } } ) { $arrbasket = undef; $titleinfo = ""; if ( C4::Context->preference("marcflavour") eq 'UNIMARC' ) { - $titleinfo = $line->{title} . " / " . $line->{author} . - ( $line->{isbn} ? " ISBN : " . $line->{isbn} : '' ) . - ( $line->{en} ? " EN : " . $line->{en} : '' ) . - ( $line->{itemtype} ? ", " . $line->{itemtype} : '' ) . - ( $line->{edition} ? ", " . $line->{edition} : '' ) . - ( $line->{publishercode} ? ' publié par '. $line->{publishercode} : '') . - ( $line->{publicationyear} ? ', '. $line->{publicationyear} : ''); - } - else { # MARC21 - $titleinfo = $line->{title} . " " . $line->{author} . - ( $line->{isbn} ? " ISBN : " . $line->{isbn} : '' ) . - ( $line->{en} ? " EN : " . $line->{en} : '' ) . - ( $line->{itemtype} ? " " . $line->{itemtype} : '' ) . - ( $line->{edition} ? ", " . $line->{edition} : '' ) . - ( $line->{publishercode} ? ' publié par '. $line->{publishercode} : '') . - ( $line->{copyrightdate} ? ' '. $line->{copyrightdate} : ''); + $titleinfo = + $line->{title} . " / " + . $line->{author} + . ( $line->{isbn} ? " ISBN : " . $line->{isbn} : '' ) + . ( $line->{en} ? " EN : " . $line->{en} : '' ) + . ( $line->{itemtype} ? ", " . $line->{itemtype} : '' ) + . ( $line->{edition} ? ", " . $line->{edition} : '' ) + . ( $line->{publishercode} ? ' publié par ' . $line->{publishercode} : '' ) + . ( $line->{publicationyear} ? ', ' . $line->{publicationyear} : '' ); + } else { # MARC21 + $titleinfo = + $line->{title} . " " + . $line->{author} + . ( $line->{isbn} ? " ISBN : " . $line->{isbn} : '' ) + . ( $line->{en} ? " EN : " . $line->{en} : '' ) + . ( $line->{itemtype} ? " " . $line->{itemtype} : '' ) + . ( $line->{edition} ? ", " . $line->{edition} : '' ) + . ( $line->{publishercode} ? ' publié par ' . $line->{publishercode} : '' ) + . ( $line->{copyrightdate} ? ' ' . $line->{copyrightdate} : '' ); } - push( @$arrbasket, - $titleinfo. ($line->{order_vendornote} ? "\n----------------\nNote pour le fournisseur : ". $line->{order_vendornote} : '' ), + push( + @$arrbasket, + $titleinfo + . ( + $line->{order_vendornote} + ? "\n----------------\nNote pour le fournisseur : " . $line->{order_vendornote} + : '' + ), $line->{quantity}, - Koha::Number::Price->new( $line->{rrp_tax_excluded})->format, - Koha::Number::Price->new( $line->{rrp_tax_included})->format, - Koha::Number::Price->new( $line->{discount})->format.'%', - Koha::Number::Price->new( $line->{rrp_tax_excluded} - $line->{ecost_tax_excluded})->format, - Koha::Number::Price->new( $line->{tax_rate} * 100)->format.'%', - Koha::Number::Price->new( $line->{total_tax_excluded})->format, - Koha::Number::Price->new( $line->{total_tax_included})->format, + Koha::Number::Price->new( $line->{rrp_tax_excluded} )->format, + Koha::Number::Price->new( $line->{rrp_tax_included} )->format, + Koha::Number::Price->new( $line->{discount} )->format . '%', + Koha::Number::Price->new( $line->{rrp_tax_excluded} - $line->{ecost_tax_excluded} )->format, + Koha::Number::Price->new( $line->{tax_rate} * 100 )->format . '%', + Koha::Number::Price->new( $line->{total_tax_excluded} )->format, + Koha::Number::Price->new( $line->{total_tax_included} )->format, ); - push(@$abaskets, $arrbasket); + push( @$abaskets, $arrbasket ); } - $pdftable->table($pdf, $page, $abaskets, - x => 10/mm, - w => ($width - 20)/mm, - start_y => 270/mm, - next_y => 285/mm, - start_h => 250/mm, - next_h => 250/mm, - padding => 5, - padding_right => 5, - background_color_odd => "lightgray", - font => $pdf->corefont("Times", -encoding => "utf8"), - font_size => 3/mm, - header_props => { - font => $pdf->corefont("Times", -encoding => "utf8"), - font_size => 9, - bg_color => 'gray', - repeat => 1, - }, - column_props => [ - { - min_w => 85/mm, # Minimum column width. - }, - { - justify => 'right', # One of left|right , - }, - { - justify => 'right', # One of left|right , - }, - { - justify => 'right', # One of left|right , - }, - { - justify => 'right', # One of left|right , - }, - { - justify => 'right', # One of left|right , - }, - { - justify => 'right', # One of left|right , - }, - { - justify => 'right', # One of left|right , - }, - { - justify => 'right', # One of left|right , - }, - ], - ); + $pdftable->table( + $pdf, $page, $abaskets, + x => 10 / mm, + w => ( $width - 20 ) / mm, + start_y => 270 / mm, + next_y => 285 / mm, + start_h => 250 / mm, + next_h => 250 / mm, + padding => 5, + padding_right => 5, + background_color_odd => "lightgray", + font => $pdf->corefont( "Times", -encoding => "utf8" ), + font_size => 3 / mm, + header_props => { + font => $pdf->corefont( "Times", -encoding => "utf8" ), + font_size => 9, + bg_color => 'gray', + repeat => 1, + }, + column_props => [ + { + min_w => 85 / mm, # Minimum column width. + }, + { + justify => 'right', # One of left|right , + }, + { + justify => 'right', # One of left|right , + }, + { + justify => 'right', # One of left|right , + }, + { + justify => 'right', # One of left|right , + }, + { + justify => 'right', # One of left|right , + }, + { + justify => 'right', # One of left|right , + }, + { + justify => 'right', # One of left|right , + }, + { + justify => 'right', # One of left|right , + }, + ], + ); } - $pdf->mediabox($width/mm, $height/mm); + $pdf->mediabox( $width / mm, $height / mm ); } sub printbaskets { - my ($pdf, $basketgroup, $hbaskets, $bookseller, $GSTrate, $orders) = @_; + my ( $pdf, $basketgroup, $hbaskets, $bookseller, $GSTrate, $orders ) = @_; # get library name my $libraryname = C4::Context->preference("LibraryName"); my $cur_format = C4::Context->preference("CurrencyFormat"); - $pdf->mediabox($width/mm, $height/mm); + $pdf->mediabox( $width / mm, $height / mm ); my $page = $pdf->openpage(2); + # create a text my $text = $page->text; # add basketgroup number - $text->font( $pdf->corefont("Times", -encoding => "utf8"), 6/mm ); - $text->translate(($width-40)/mm, ($height-53)/mm); - $text->text("".$basketgroup->{'id'}); + $text->font( $pdf->corefont( "Times", -encoding => "utf8" ), 6 / mm ); + $text->translate( ( $width - 40 ) / mm, ( $height - 53 ) / mm ); + $text->text( "" . $basketgroup->{'id'} ); + # print the libraryname in the header - $text->font( $pdf->corefont("Times", -encoding => "utf8"), 6/mm ); - $text->translate(30/mm, ($height-28.5)/mm); + $text->font( $pdf->corefont( "Times", -encoding => "utf8" ), 6 / mm ); + $text->translate( 30 / mm, ( $height - 28.5 ) / mm ); $text->text($libraryname); my $pdftable = PDF::Table->new(); my $abaskets; my $arrbasket; + # header of the table - my @keys = ('Lot', 'Panier', 'Prix', 'Prix net', 'Taux TVA', 'TVA', 'Remise', 'Total HT', 'Total TTC'); + my @keys = ( 'Lot', 'Panier', 'Prix', 'Prix net', 'Taux TVA', 'TVA', 'Remise', 'Total HT', 'Total TTC' ); for my $bkey (@keys) { - push(@$arrbasket, $bkey); + push( @$arrbasket, $bkey ); } - my ($grandtotal_rrp_tax_included, $grandtotal_rrp_tax_excluded, $grandtotal_tax_included, $grandtotal_tax_excluded, $grandtotaltax_value, $grandtotaldiscount); + my ( + $grandtotal_rrp_tax_included, $grandtotal_rrp_tax_excluded, $grandtotal_tax_included, + $grandtotal_tax_excluded, $grandtotaltax_value, $grandtotaldiscount + ); + # calculate each basket total - push(@$abaskets, $arrbasket); + push( @$abaskets, $arrbasket ); for my $basket (@$hbaskets) { my @gst; $arrbasket = undef; - my ($total_rrp_tax_excluded, $total_rrp_tax_included, $total_tax_excluded, $total_tax_included, $totaltax_value, $totaldiscount); - my $ords = $orders->{$basket->{basketno}}; + my ( + $total_rrp_tax_excluded, $total_rrp_tax_included, $total_tax_excluded, $total_tax_included, + $totaltax_value, $totaldiscount + ); + my $ords = $orders->{ $basket->{basketno} }; my $ordlength = @$ords; foreach my $ord (@$ords) { - $total_tax_excluded += $ord->{total_tax_excluded}; - $total_tax_included += $ord->{total_tax_included}; - $totaltax_value += $ord->{tax_value}; - $totaldiscount += ($ord->{rrp_tax_excluded} - $ord->{ecost_tax_excluded} ) * $ord->{quantity}; + $total_tax_excluded += $ord->{total_tax_excluded}; + $total_tax_included += $ord->{total_tax_included}; + $totaltax_value += $ord->{tax_value}; + $totaldiscount += ( $ord->{rrp_tax_excluded} - $ord->{ecost_tax_excluded} ) * $ord->{quantity}; $total_rrp_tax_excluded += $ord->{rrp_tax_excluded} * $ord->{quantity}; $total_rrp_tax_included += $ord->{rrp_tax_included} * $ord->{quantity}; push @gst, $ord->{tax_rate}; @@ -230,89 +255,92 @@ sub printbaskets { @gst = uniq map { $_ * 100 } @gst; $grandtotal_rrp_tax_excluded += $total_rrp_tax_excluded; $grandtotal_rrp_tax_included += $total_rrp_tax_included; - $grandtotal_tax_included += $total_tax_included; - $grandtotal_tax_excluded += $total_tax_excluded; - $grandtotaltax_value += $totaltax_value; - $grandtotaldiscount += $totaldiscount; + $grandtotal_tax_included += $total_tax_included; + $grandtotal_tax_excluded += $total_tax_excluded; + $grandtotaltax_value += $totaltax_value; + $grandtotaldiscount += $totaldiscount; my @gst_string = - map { Koha::Number::Price->new($_)->format . '%' } @gst; - push(@$arrbasket, + map { Koha::Number::Price->new($_)->format . '%' } @gst; + push( + @$arrbasket, $basket->{contractname}, $basket->{basketname} . ' (No. ' . $basket->{basketno} . ')', - Koha::Number::Price->new( $total_rrp_tax_excluded )->format, - Koha::Number::Price->new( $total_rrp_tax_included )->format, + Koha::Number::Price->new($total_rrp_tax_excluded)->format, + Koha::Number::Price->new($total_rrp_tax_included)->format, "@gst_string", - Koha::Number::Price->new( $totaltax_value )->format, - Koha::Number::Price->new( $totaldiscount )->format, - Koha::Number::Price->new( $total_tax_excluded )->format, - Koha::Number::Price->new( $total_tax_included )->format, + Koha::Number::Price->new($totaltax_value)->format, + Koha::Number::Price->new($totaldiscount)->format, + Koha::Number::Price->new($total_tax_excluded)->format, + Koha::Number::Price->new($total_tax_included)->format, ); - push(@$abaskets, $arrbasket); + push( @$abaskets, $arrbasket ); } + # now, push total undef $arrbasket; push @$arrbasket, - '', - 'Total', - Koha::Number::Price->new( $grandtotal_rrp_tax_excluded )->format, - Koha::Number::Price->new( $grandtotal_rrp_tax_included )->format, - '', - Koha::Number::Price->new( $grandtotaltax_value )->format, - Koha::Number::Price->new( $grandtotaldiscount )->format, - Koha::Number::Price->new( $grandtotal_tax_excluded )->format, - Koha::Number::Price->new( $grandtotal_tax_included )->format; - push @$abaskets,$arrbasket; + '', + 'Total', + Koha::Number::Price->new($grandtotal_rrp_tax_excluded)->format, + Koha::Number::Price->new($grandtotal_rrp_tax_included)->format, + '', + Koha::Number::Price->new($grandtotaltax_value)->format, + Koha::Number::Price->new($grandtotaldiscount)->format, + Koha::Number::Price->new($grandtotal_tax_excluded)->format, + Koha::Number::Price->new($grandtotal_tax_included)->format; + push @$abaskets, $arrbasket; + # height is width and width is height in this function, as the pdf is in landscape mode for the Tables. - $pdftable->table($pdf, $page, $abaskets, - x => 5/mm, - w => ($width - 10)/mm, - start_y => 230/mm, - next_y => 230/mm, - start_h => 230/mm, - next_h => 230/mm, - font => $pdf->corefont("Times", -encoding => "utf8"), - font_size => 3/mm, - padding => 5, - padding_right => 10, - background_color_odd => "lightgray", - header_props => { - bg_color => 'gray', - repeat => 1, - }, - column_props => [ - { - }, - { - }, - { - justify => 'right', - }, - { - justify => 'right', - }, - { - justify => 'right', - }, - { - justify => 'right', - }, - { - justify => 'right', - }, - ], + $pdftable->table( + $pdf, $page, $abaskets, + x => 5 / mm, + w => ( $width - 10 ) / mm, + start_y => 230 / mm, + next_y => 230 / mm, + start_h => 230 / mm, + next_h => 230 / mm, + font => $pdf->corefont( "Times", -encoding => "utf8" ), + font_size => 3 / mm, + padding => 5, + padding_right => 10, + background_color_odd => "lightgray", + header_props => { + bg_color => 'gray', + repeat => 1, + }, + column_props => [ + {}, + {}, + { + justify => 'right', + }, + { + justify => 'right', + }, + { + justify => 'right', + }, + { + justify => 'right', + }, + { + justify => 'right', + }, + ], ); - $pdf->mediabox($height/mm, $width/mm); + $pdf->mediabox( $height / mm, $width / mm ); } sub printhead { - my ($pdf, $basketgroup, $bookseller) = @_; + my ( $pdf, $basketgroup, $bookseller ) = @_; # get library name - my $libraryname = C4::Context->preference("LibraryName"); - my $billing_library = Koha::Libraries->find( $basketgroup->{billingplace} ); - my $delivery_library = Koha::Libraries->find( $basketgroup->{deliveryplace} ); + my $libraryname = C4::Context->preference("LibraryName"); + my $billing_library = Koha::Libraries->find( $basketgroup->{billingplace} ); + my $delivery_library = Koha::Libraries->find( $basketgroup->{deliveryplace} ); my $freedeliveryplace = $basketgroup->{freedeliveryplace}; + # get the subject my $subject; @@ -323,109 +351,120 @@ sub printhead { my $text = $page->text; # print the libraryname in the header - $text->font( $pdf->corefont("Times", -encoding => "utf8"), 6/mm ); - $text->translate(30/mm, ($height-28.5)/mm); + $text->font( $pdf->corefont( "Times", -encoding => "utf8" ), 6 / mm ); + $text->translate( 30 / mm, ( $height - 28.5 ) / mm ); $text->text($libraryname); # print order info, on the default PDF - $text->font( $pdf->corefont("Times", -encoding => "utf8"), 8/mm ); - $text->translate(100/mm, ($height-5-48)/mm); - $text->text($basketgroup->{'id'}); + $text->font( $pdf->corefont( "Times", -encoding => "utf8" ), 8 / mm ); + $text->translate( 100 / mm, ( $height - 5 - 48 ) / mm ); + $text->text( $basketgroup->{'id'} ); # print the date - my $today = output_pref({ dt => dt_from_string, dateonly => 1 }); - $text->translate(130/mm, ($height-5-48)/mm); + my $today = output_pref( { dt => dt_from_string, dateonly => 1 } ); + $text->translate( 130 / mm, ( $height - 5 - 48 ) / mm ); $text->text($today); - $text->font( $pdf->corefont("Times", -encoding => "utf8"), 4/mm ); + $text->font( $pdf->corefont( "Times", -encoding => "utf8" ), 4 / mm ); # print billing infos - $text->translate(100/mm, ($height-86)/mm); + $text->translate( 100 / mm, ( $height - 86 ) / mm ); $text->text($libraryname); - $text->translate(100/mm, ($height-97)/mm); - $text->text($billing_library->branchname); - $text->translate(100/mm, ($height-108.5)/mm); - $text->text($billing_library->branchphone); - $text->translate(100/mm, ($height-115.5)/mm); - $text->text($billing_library->branchfax); - $text->translate(100/mm, ($height-122.5)/mm); - $text->text($billing_library->branchaddress1); - $text->translate(100/mm, ($height-127.5)/mm); - $text->text($billing_library->branchaddress2); - $text->translate(100/mm, ($height-132.5)/mm); - $text->text($billing_library->branchaddress3); - $text->translate(100/mm, ($height-137.5)/mm); - $text->text(join(' ', $billing_library->branchzip, $billing_library->branchcity, $billing_library->branchcountry)); - $text->translate(100/mm, ($height-147.5)/mm); - $text->text($billing_library->branchemail); + $text->translate( 100 / mm, ( $height - 97 ) / mm ); + $text->text( $billing_library->branchname ); + $text->translate( 100 / mm, ( $height - 108.5 ) / mm ); + $text->text( $billing_library->branchphone ); + $text->translate( 100 / mm, ( $height - 115.5 ) / mm ); + $text->text( $billing_library->branchfax ); + $text->translate( 100 / mm, ( $height - 122.5 ) / mm ); + $text->text( $billing_library->branchaddress1 ); + $text->translate( 100 / mm, ( $height - 127.5 ) / mm ); + $text->text( $billing_library->branchaddress2 ); + $text->translate( 100 / mm, ( $height - 132.5 ) / mm ); + $text->text( $billing_library->branchaddress3 ); + $text->translate( 100 / mm, ( $height - 137.5 ) / mm ); + $text->text( + join( ' ', $billing_library->branchzip, $billing_library->branchcity, $billing_library->branchcountry ) ); + $text->translate( 100 / mm, ( $height - 147.5 ) / mm ); + $text->text( $billing_library->branchemail ); # print subject - $text->translate(100/mm, ($height-145.5)/mm); + $text->translate( 100 / mm, ( $height - 145.5 ) / mm ); $text->text($subject); # print bookseller infos - $text->translate(100/mm, ($height-180)/mm); - $text->text($bookseller->name); - $text->translate(100/mm, ($height-185)/mm); - $text->text($bookseller->postal); - $text->translate(100/mm, ($height-190)/mm); - $text->text($bookseller->address1); - $text->translate(100/mm, ($height-195)/mm); - $text->text($bookseller->address2); - $text->translate(100/mm, ($height-200)/mm); - $text->text($bookseller->address3); - $text->translate(100/mm, ($height-205)/mm); - $text->text($bookseller->accountnumber); + $text->translate( 100 / mm, ( $height - 180 ) / mm ); + $text->text( $bookseller->name ); + $text->translate( 100 / mm, ( $height - 185 ) / mm ); + $text->text( $bookseller->postal ); + $text->translate( 100 / mm, ( $height - 190 ) / mm ); + $text->text( $bookseller->address1 ); + $text->translate( 100 / mm, ( $height - 195 ) / mm ); + $text->text( $bookseller->address2 ); + $text->translate( 100 / mm, ( $height - 200 ) / mm ); + $text->text( $bookseller->address3 ); + $text->translate( 100 / mm, ( $height - 205 ) / mm ); + $text->text( $bookseller->accountnumber ); # print delivery infos - $text->font( $pdf->corefont("Times-Bold", -encoding => "utf8"), 4/mm ); - $text->translate(50/mm, ($height-237)/mm); + $text->font( $pdf->corefont( "Times-Bold", -encoding => "utf8" ), 4 / mm ); + $text->translate( 50 / mm, ( $height - 237 ) / mm ); if ($freedeliveryplace) { my $start = 242; - my @fdp = split('\n', $freedeliveryplace); + my @fdp = split( '\n', $freedeliveryplace ); foreach (@fdp) { $text->text($_); $text->translate( 50 / mm, ( $height - $start ) / mm ); $start += 5; } } else { - $text->text($delivery_library->branchaddress1); - $text->translate(50/mm, ($height-242)/mm); - $text->text($delivery_library->branchaddress2); - $text->translate(50/mm, ($height-247)/mm); - $text->text($delivery_library->branchaddress3); - $text->translate(50/mm, ($height-252)/mm); - $text->text(join(' ', $delivery_library->branchzip, $delivery_library->branchcity, $delivery_library->branchcountry)); + $text->text( $delivery_library->branchaddress1 ); + $text->translate( 50 / mm, ( $height - 242 ) / mm ); + $text->text( $delivery_library->branchaddress2 ); + $text->translate( 50 / mm, ( $height - 247 ) / mm ); + $text->text( $delivery_library->branchaddress3 ); + $text->translate( 50 / mm, ( $height - 252 ) / mm ); + $text->text( + join( ' ', $delivery_library->branchzip, $delivery_library->branchcity, $delivery_library->branchcountry ) + ); } - $text->translate(50/mm, ($height-262)/mm); - $text->text($basketgroup->{deliverycomment}); + $text->translate( 50 / mm, ( $height - 262 ) / mm ); + $text->text( $basketgroup->{deliverycomment} ); } sub printfooters { - my ($pdf) = @_; - for (my $i=1;$i <= $pdf->pages;$i++) { + my ($pdf) = @_; + for ( my $i = 1 ; $i <= $pdf->pages ; $i++ ) { my $page = $pdf->openpage($i); my $text = $page->text; - $text->font( $pdf->corefont("Times", -encoding => "utf8"), 3/mm ); - $text->translate(10/mm, 10/mm); - $text->text("Page $i / ".$pdf->pages); - } + $text->font( $pdf->corefont( "Times", -encoding => "utf8" ), 3 / mm ); + $text->translate( 10 / mm, 10 / mm ); + $text->text( "Page $i / " . $pdf->pages ); + } } sub printpdf { - my ($basketgroup, $bookseller, $baskets, $orders, $GST) = @_; + my ( $basketgroup, $bookseller, $baskets, $orders, $GST ) = @_; + # open the default PDF that will be used for base (1st page already filled) - my $pdf_template = C4::Context->config('intrahtdocs') . '/' . C4::Context->preference('template') . '/pdf/layout3pagesfr.pdf'; + my $pdf_template = + C4::Context->config('intrahtdocs') . '/' . C4::Context->preference('template') . '/pdf/layout3pagesfr.pdf'; my $pdf = PDF::API2->open($pdf_template); - $pdf->pageLabel( 0, { - -style => 'roman', - } ); # start with roman numbering - # fill the 1st page (basketgroup information) - printhead($pdf, $basketgroup, $bookseller); + $pdf->pageLabel( + 0, + { + -style => 'roman', + } + ); # start with roman numbering + # fill the 1st page (basketgroup information) + printhead( $pdf, $basketgroup, $bookseller ); + # fill the 2nd page (orders summary) - printbaskets($pdf, $basketgroup, $baskets, $bookseller, $GST, $orders); + printbaskets( $pdf, $basketgroup, $baskets, $bookseller, $GST, $orders ); + # fill other pages (orders) - printorders($pdf, $basketgroup, $baskets, $orders); + printorders( $pdf, $basketgroup, $baskets, $orders ); + # print something on each page (usually the footer, but you could also put a header printfooters($pdf); return $pdf->stringify; diff --git a/about.pl b/about.pl index afb58e9555..39e04930cf 100755 --- a/about.pl +++ b/about.pl @@ -24,18 +24,18 @@ use Modern::Perl; use CGI qw ( -utf8 ); use DateTime::TimeZone; -use File::Slurp qw( read_file ); -use IPC::Cmd qw(can_run); -use List::MoreUtils qw( any ); +use File::Slurp qw( read_file ); +use IPC::Cmd qw(can_run); +use List::MoreUtils qw( any ); use Module::Load::Conditional qw( can_load ); -use Config qw( %Config ); +use Config qw( %Config ); use Search::Elasticsearch; use Try::Tiny qw( catch try ); use YAML::XS; use Encode; use C4::Output qw( output_html_with_http_headers ); -use C4::Auth qw( get_template_and_user get_user_subpermissions ); +use C4::Auth qw( get_template_and_user get_user_subpermissions ); use C4::Context; use C4::Installer; use C4::Installer::PerlModules; @@ -60,15 +60,15 @@ use Koha::Filter::MARC::ViewPolicy; use C4::Members::Statistics; -my $query = CGI->new; +my $query = CGI->new; my $params = $query->Vars(); my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "about.tt", - query => $query, - type => "intranet", - flagsrequired => { catalogue => 1 }, + template_name => "about.tt", + query => $query, + type => "intranet", + flagsrequired => { catalogue => 1 }, } ); @@ -92,20 +92,21 @@ my %versions = C4::Context::get_versions(); if ( $tab eq 'about' ) { - my $config_timezone = C4::Context->config('timezone') // ''; - my $config_invalid = !DateTime::TimeZone->is_valid_name( $config_timezone ); - my $env_timezone = $ENV{TZ} // ''; - my $env_invalid = !DateTime::TimeZone->is_valid_name( $env_timezone ); + my $config_timezone = C4::Context->config('timezone') // ''; + my $config_invalid = !DateTime::TimeZone->is_valid_name($config_timezone); + my $env_timezone = $ENV{TZ} // ''; + my $env_invalid = !DateTime::TimeZone->is_valid_name($env_timezone); my $actual_bad_tz_fallback = 0; - if ( $config_timezone ne '' && - $config_invalid ) { + if ( $config_timezone ne '' + && $config_invalid ) + { # Bad config $actual_bad_tz_fallback = 1; - } - elsif ( $config_timezone eq '' && - $env_timezone ne '' && - $env_invalid ) { + } elsif ( $config_timezone eq '' + && $env_timezone ne '' + && $env_invalid ) + { # No config, but bad ENV{TZ} $actual_bad_tz_fallback = 1; } @@ -119,31 +120,30 @@ if ( $tab eq 'about' ) { environment_invalid => $env_invalid }; - { # Logger checks + { # Logger checks my $log4perl_config = C4::Context->config("log4perl_conf"); my @log4perl_errors; - if ( ! $log4perl_config ) { - push @log4perl_errors, 'missing_config_entry' - } - else { + if ( !$log4perl_config ) { + push @log4perl_errors, 'missing_config_entry'; + } else { my @lines = read_file($log4perl_config) or push @log4perl_errors, 'cannot_read_config_file'; - for my $line ( @lines ) { + for my $line (@lines) { next unless $line =~ m|log4perl.appender.\w+.filename=(.*)|; push @log4perl_errors, 'logfile_not_writable' unless -w $1; } } - eval {Koha::Logger->get}; + eval { Koha::Logger->get }; push @log4perl_errors, 'cannot_init_module' and warn $@ if $@; $template->param( log4perl_errors => @log4perl_errors ); } $template->param( - time_zone => $time_zone, - current_date_and_time => output_pref({ dt => dt_from_string(), dateformat => 'iso' }) + time_zone => $time_zone, + current_date_and_time => output_pref( { dt => dt_from_string(), dateformat => 'iso' } ) ); my $perl_path = $^X; - if ($^O ne 'VMS') { + if ( $^O ne 'VMS' ) { $perl_path .= $Config{_exe} unless $perl_path =~ m/$Config{_exe}$/i; } @@ -153,21 +153,22 @@ if ( $tab eq 'about' ) { if ( C4::Context->psgi_env ) { $template->param( is_psgi => 1, - psgi_server => ($ENV{ PLACK_ENV }) ? "Plack ($ENV{PLACK_ENV})" : - ($ENV{ MOD_PERL }) ? "mod_perl ($ENV{MOD_PERL})" : - 'Unknown' + psgi_server => ( $ENV{PLACK_ENV} ) ? "Plack ($ENV{PLACK_ENV})" + : ( $ENV{MOD_PERL} ) ? "mod_perl ($ENV{MOD_PERL})" + : 'Unknown' ); } # Memcached configuration - my $memcached_servers = $ENV{MEMCACHED_SERVERS} || C4::Context->config('memcached_servers'); + my $memcached_servers = $ENV{MEMCACHED_SERVERS} || C4::Context->config('memcached_servers'); my $memcached_namespace = $ENV{MEMCACHED_NAMESPACE} || C4::Context->config('memcached_namespace') // 'koha'; - my $cache = Koha::Caches->get_instance; - my $effective_caching_method = ref($cache->cache); + my $cache = Koha::Caches->get_instance; + my $effective_caching_method = ref( $cache->cache ); + # Memcached may have been running when plack has been initialized but could have been stopped since # FIXME What are the consequences of that?? - my $is_memcached_still_active = $cache->set_in_cache('test_for_about_page', "just a simple value"); + my $is_memcached_still_active = $cache->set_in_cache( 'test_for_about_page', "just a simple value" ); my $where_is_memcached_config = 'nowhere'; if ( $ENV{MEMCACHED_SERVERS} and C4::Context->config('memcached_servers') ) { @@ -182,25 +183,25 @@ if ( $tab eq 'about' ) { elasticsearch_check($template); $template->param( - effective_caching_method => $effective_caching_method, - memcached_servers => $memcached_servers, - memcached_namespace => $memcached_namespace, + effective_caching_method => $effective_caching_method, + memcached_servers => $memcached_servers, + memcached_namespace => $memcached_namespace, is_memcached_still_active => $is_memcached_still_active, where_is_memcached_config => $where_is_memcached_config, - perlPath => $perl_path, - zebraVersion => $zebraVersion, - kohaVersion => $versions{'kohaVersion'}, - osVersion => $versions{'osVersion'}, - perlVersion => $versions{'perlVersion'}, - perlIncPath => [ map { perlinc => $_ }, @INC ], - mysqlVersion => $versions{'mysqlVersion'}, - apacheVersion => $versions{'apacheVersion'}, - memcached_running => Koha::Caches->get_instance->memcached_cache, + perlPath => $perl_path, + zebraVersion => $zebraVersion, + kohaVersion => $versions{'kohaVersion'}, + osVersion => $versions{'osVersion'}, + perlVersion => $versions{'perlVersion'}, + perlIncPath => [ map { perlinc => $_ }, @INC ], + mysqlVersion => $versions{'mysqlVersion'}, + apacheVersion => $versions{'apacheVersion'}, + memcached_running => Koha::Caches->get_instance->memcached_cache, ); } -if($tab eq 'sysinfo') { +if ( $tab eq 'sysinfo' ) { # Additional system information for warnings @@ -211,33 +212,31 @@ if($tab eq 'sysinfo') { unless ( $prefStatisticsFields eq C4::Members::Statistics->get_fields() ); } - my $prefAutoCreateAuthorities = C4::Context->preference('AutoCreateAuthorities'); + my $prefAutoCreateAuthorities = C4::Context->preference('AutoCreateAuthorities'); my $prefRequireChoosingExistingAuthority = C4::Context->preference('RequireChoosingExistingAuthority'); - my $warnPrefRequireChoosingExistingAuthority = ( !$prefAutoCreateAuthorities && ( !$prefRequireChoosingExistingAuthority) ); + my $warnPrefRequireChoosingExistingAuthority = + ( !$prefAutoCreateAuthorities && ( !$prefRequireChoosingExistingAuthority ) ); - my $prefEasyAnalyticalRecords = C4::Context->preference('EasyAnalyticalRecords'); - my $prefUseControlNumber = C4::Context->preference('UseControlNumber'); - my $warnPrefEasyAnalyticalRecords = ( $prefEasyAnalyticalRecords && $prefUseControlNumber ); + my $prefEasyAnalyticalRecords = C4::Context->preference('EasyAnalyticalRecords'); + my $prefUseControlNumber = C4::Context->preference('UseControlNumber'); + my $warnPrefEasyAnalyticalRecords = ( $prefEasyAnalyticalRecords && $prefUseControlNumber ); - my $AnonymousPatron = C4::Context->preference('AnonymousPatron'); - my $warnPrefAnonymousPatronOPACPrivacy = ( - C4::Context->preference('OPACPrivacy') - and not $AnonymousPatron - ); - my $warnPrefAnonymousPatronAnonSuggestions = ( - C4::Context->preference('AnonSuggestions') - and not $AnonymousPatron - ); + my $AnonymousPatron = C4::Context->preference('AnonymousPatron'); + my $warnPrefAnonymousPatronOPACPrivacy = ( C4::Context->preference('OPACPrivacy') and not $AnonymousPatron ); + my $warnPrefAnonymousPatronAnonSuggestions = + ( C4::Context->preference('AnonSuggestions') and not $AnonymousPatron ); - my $anonymous_patron = Koha::Patrons->find( $AnonymousPatron ); - my $warnPrefAnonymousPatronAnonSuggestions_PatronDoesNotExist = ( $AnonymousPatron && C4::Context->preference('AnonSuggestions') && not $anonymous_patron ); + my $anonymous_patron = Koha::Patrons->find($AnonymousPatron); + my $warnPrefAnonymousPatronAnonSuggestions_PatronDoesNotExist = + ( $AnonymousPatron && C4::Context->preference('AnonSuggestions') && not $anonymous_patron ); - my $warnPrefAnonymousPatronOPACPrivacy_PatronDoesNotExist = ( not $anonymous_patron and Koha::Patrons->search({ privacy => 2 })->count ); + my $warnPrefAnonymousPatronOPACPrivacy_PatronDoesNotExist = + ( not $anonymous_patron and Koha::Patrons->search( { privacy => 2 } )->count ); - my $warnPrefKohaAdminEmailAddress = !Koha::Email->is_valid(C4::Context->preference('KohaAdminEmailAddress')); + my $warnPrefKohaAdminEmailAddress = !Koha::Email->is_valid( C4::Context->preference('KohaAdminEmailAddress') ); - my $c = Koha::Items->filter_by_visible_in_opac->count; - my @warnings = C4::Context->dbh->selectrow_array('SHOW WARNINGS'); + my $c = Koha::Items->filter_by_visible_in_opac->count; + my @warnings = C4::Context->dbh->selectrow_array('SHOW WARNINGS'); my $warnPrefOpacHiddenItems = $warnings[2]; my $invalid_yesno = Koha::Config::SysPrefs->search( @@ -248,11 +247,11 @@ if($tab eq 'sysinfo') { ); $template->param( invalid_yesno => $invalid_yesno ); - my $errZebraConnection = C4::Context->Zconn("biblioserver",0)->errcode(); + my $errZebraConnection = C4::Context->Zconn( "biblioserver", 0 )->errcode(); - my $warnIsRootUser = (! $loggedinuser); + my $warnIsRootUser = ( !$loggedinuser ); - my $warnNoActiveCurrency = (! defined Koha::Acquisition::Currencies->get_active); + my $warnNoActiveCurrency = ( !defined Koha::Acquisition::Currencies->get_active ); my @xml_config_warnings; @@ -269,58 +268,47 @@ if($tab eq 'sysinfo') { } my $authorityserver = C4::Context->zebraconfig('authorityserver'); - if( ( C4::Context->config('zebra_auth_index_mode') - and C4::Context->config('zebra_auth_index_mode') eq 'dom' ) + if ( ( C4::Context->config('zebra_auth_index_mode') and C4::Context->config('zebra_auth_index_mode') eq 'dom' ) && ( $authorityserver->{config} !~ /zebra-authorities-dom.cfg/ ) ) { - push @xml_config_warnings, { - error => 'zebra_auth_index_mode_mismatch_warn' - }; + push @xml_config_warnings, { error => 'zebra_auth_index_mode_mismatch_warn' }; } - if ( ! defined C4::Context->config('log4perl_conf') ) { - push @xml_config_warnings, { - error => 'log4perl_entry_missing' - } + if ( !defined C4::Context->config('log4perl_conf') ) { + push @xml_config_warnings, { error => 'log4perl_entry_missing' }; } - if ( ! defined C4::Context->config('lockdir') ) { - push @xml_config_warnings, { - error => 'lockdir_entry_missing' - } - } - else { + if ( !defined C4::Context->config('lockdir') ) { + push @xml_config_warnings, { error => 'lockdir_entry_missing' }; + } else { unless ( -w C4::Context->config('lockdir') ) { push @xml_config_warnings, { error => 'lockdir_not_writable', lockdir => C4::Context->config('lockdir') - } + }; } } - if ( ! defined C4::Context->config('upload_path') ) { + if ( !defined C4::Context->config('upload_path') ) { if ( Koha::Config::SysPrefs->find('OPACBaseURL')->value ) { + # OPACBaseURL seems to be set - push @xml_config_warnings, { - error => 'uploadpath_entry_missing' - } + push @xml_config_warnings, { error => 'uploadpath_entry_missing' }; } else { - push @xml_config_warnings, { - error => 'uploadpath_and_opacbaseurl_entry_missing' - } + push @xml_config_warnings, { error => 'uploadpath_and_opacbaseurl_entry_missing' }; } } - if ( ! C4::Context->config('tmp_path') ) { + if ( !C4::Context->config('tmp_path') ) { my $temporary_directory = C4::Context::temporary_directory; push @xml_config_warnings, { error => 'tmp_path_missing', effective_tmp_dir => $temporary_directory, - } + }; } my $encryption_key = C4::Context->config('encryption_key'); - if ( !$encryption_key || $encryption_key eq '__ENCRYPTION_KEY__') { + if ( !$encryption_key || $encryption_key eq '__ENCRYPTION_KEY__' ) { push @xml_config_warnings, { error => 'encryption_key_missing' }; } @@ -337,10 +325,9 @@ if($tab eq 'sysinfo') { if ( C4::Context->preference('ILLModule') ) { my $warnILLConfiguration = 0; my $ill_config_from_file = C4::Context->config("interlibrary_loans"); - my $ill_config = Koha::ILL::Request::Config->new; + my $ill_config = Koha::ILL::Request::Config->new; - my $available_ill_backends = - ( scalar @{ $ill_config->available_backends } > 0 ); + my $available_ill_backends = ( scalar @{ $ill_config->available_backends } > 0 ); # Check backends if ( !$available_ill_backends ) { @@ -365,13 +352,14 @@ if($tab eq 'sysinfo') { } if ( !C4::Context->preference('ILLPartnerCode') ) { + # partner code not defined $template->param( ill_partner_code_not_defined => 1 ); $warnILLConfiguration = 1; } - if ( !$ill_config_from_file->{branch} ) { + # branch not defined $template->param( ill_branch_not_defined => 1 ); $warnILLConfiguration = 1; @@ -394,35 +382,37 @@ if($tab eq 'sysinfo') { XSLTResultsDisplay ); my @warnXSLT; - for my $p ( @xslt_prefs ) { - my $xsl_filename = C4::XSLT::get_xsl_filename( $p ); + + for my $p (@xslt_prefs) { + my $xsl_filename = C4::XSLT::get_xsl_filename($p); next if -e $xsl_filename; push @warnXSLT, - { + { syspref => $p, value => C4::Context->preference("$p"), filename => $xsl_filename - }; + }; } $template->param( warnXSLT => \@warnXSLT ) if @warnXSLT; } - elasticsearch_check( $template ); + elasticsearch_check($template); if ( C4::Context->preference('RESTOAuth2ClientCredentials') ) { + # Do we have the required deps? - unless ( can_load( modules => { 'Net::OAuth2::AuthorizationServer' => undef }) ) { + unless ( can_load( modules => { 'Net::OAuth2::AuthorizationServer' => undef } ) ) { $template->param( oauth2_missing_deps => 1 ); } } # Sco Patron should not contain any other perms than circulate => self_checkout - if ( C4::Context->preference('WebBasedSelfCheck') - and C4::Context->preference('AutoSelfCheckAllowed') - ) { - my $userid = C4::Context->preference('AutoSelfCheckID'); - my $all_permissions = C4::Auth::get_user_subpermissions( $userid ); + if ( C4::Context->preference('WebBasedSelfCheck') + and C4::Context->preference('AutoSelfCheckAllowed') ) + { + my $userid = C4::Context->preference('AutoSelfCheckID'); + my $all_permissions = C4::Auth::get_user_subpermissions($userid); my ( $has_self_checkout_perm, $has_other_permissions ); while ( my ( $module, $permissions ) = each %$all_permissions ) { if ( $module eq 'self_check' ) { @@ -438,14 +428,14 @@ if($tab eq 'sysinfo') { } } $template->param( - AutoSelfCheckPatronDoesNotHaveSelfCheckPerm => not ( $has_self_checkout_perm ), - AutoSelfCheckPatronHasTooManyPerm => $has_other_permissions, + AutoSelfCheckPatronDoesNotHaveSelfCheckPerm => not($has_self_checkout_perm), + AutoSelfCheckPatronHasTooManyPerm => $has_other_permissions, ); } if ( C4::Context->preference('PatronSelfRegistration') ) { $template->param( warnPrefPatronSelfRegistrationDefaultCategory => 1 ) - unless Koha::Patron::Categories->find(C4::Context->preference('PatronSelfRegistrationDefaultCategory')); + unless Koha::Patron::Categories->find( C4::Context->preference('PatronSelfRegistrationDefaultCategory') ); } # Test YAML system preferences @@ -464,8 +454,8 @@ if($tab eq 'sysinfo') { ); my @bad_yaml_prefs; foreach my $syspref (@yaml_prefs) { - my $yaml = C4::Context->preference( $syspref ); - if ( $yaml ) { + my $yaml = C4::Context->preference($syspref); + if ($yaml) { eval { YAML::XS::Load( Encode::encode_utf8("$yaml\n\n") ); }; if ($@) { push @bad_yaml_prefs, $syspref; @@ -475,7 +465,7 @@ if($tab eq 'sysinfo') { $template->param( 'bad_yaml_prefs' => \@bad_yaml_prefs ) if @bad_yaml_prefs; { - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $patrons = $dbh->selectall_arrayref( q|select b.borrowernumber from borrowers b join deletedborrowers db on b.borrowernumber=db.borrowernumber|, { Slice => {} } @@ -516,7 +506,8 @@ if($tab eq 'sysinfo') { # Circ rule warnings { my $dbh = C4::Context->dbh; - my $units = Koha::CirculationRules->search({ rule_name => 'lengthunit', rule_value => { -not_in => ['days', 'hours'] } }); + my $units = Koha::CirculationRules->search( + { rule_name => 'lengthunit', rule_value => { -not_in => [ 'days', 'hours' ] } } ); if ( $units->count ) { $template->param( @@ -528,27 +519,31 @@ if($tab eq 'sysinfo') { # Guarantor relationships warnings { - my $dbh = C4::Context->dbh; - my ($bad_relationships_count) = $dbh->selectall_arrayref(q{ + my $dbh = C4::Context->dbh; + my ($bad_relationships_count) = $dbh->selectall_arrayref( + q{ SELECT COUNT(*) FROM ( SELECT relationship FROM borrower_relationships WHERE relationship='_bad_data' UNION ALL SELECT relationship FROM borrowers WHERE relationship='_bad_data') a - }); + } + ); $bad_relationships_count = $bad_relationships_count->[0]->[0]; - my $existing_relationships = $dbh->selectall_arrayref(q{ + my $existing_relationships = $dbh->selectall_arrayref( + q{ SELECT DISTINCT(relationship) FROM ( SELECT relationship FROM borrower_relationships WHERE relationship IS NOT NULL UNION ALL SELECT relationship FROM borrowers WHERE relationship IS NOT NULL) a - }); + } + ); my %valid_relationships = map { $_ => 1 } split( /,|\|/, C4::Context->preference('borrowerRelationship') ); - $valid_relationships{ _bad_data } = 1; # we handle this case in another way + $valid_relationships{_bad_data} = 1; # we handle this case in another way my $wrong_relationships = [ grep { !$valid_relationships{ $_->[0] } } @{$existing_relationships} ]; if ( @$wrong_relationships or $bad_relationships_count ) { @@ -557,10 +552,8 @@ if($tab eq 'sysinfo') { warnRelationships => 1, ); - if ( $wrong_relationships ) { - $template->param( - wrong_relationships => $wrong_relationships - ); + if ($wrong_relationships) { + $template->param( wrong_relationships => $wrong_relationships ); } if ($bad_relationships_count) { $template->param( @@ -573,16 +566,16 @@ if($tab eq 'sysinfo') { { # Test 'bcrypt_settings' config for Pseudonymization $template->param( config_bcrypt_settings_no_set => 1 ) - if C4::Context->preference('Pseudonymization') - and not C4::Context->config('bcrypt_settings'); + if C4::Context->preference('Pseudonymization') + and not C4::Context->config('bcrypt_settings'); } { my @frameworkcodes = Koha::BiblioFrameworks->search->get_column('frameworkcode'); my @hidden_biblionumbers; - push @frameworkcodes, ""; # it's not in the biblio_frameworks table! + push @frameworkcodes, ""; # it's not in the biblio_frameworks table! my $no_FA_framework = 1; - for my $frameworkcode ( @frameworkcodes ) { + for my $frameworkcode (@frameworkcodes) { $no_FA_framework = 0 if $frameworkcode eq 'FA'; my $shouldhidemarc_opac = Koha::Filter::MARC::ViewPolicy->should_hide_marc( { @@ -591,7 +584,7 @@ if($tab eq 'sysinfo') { } ); push @hidden_biblionumbers, { frameworkcode => $frameworkcode, interface => 'opac' } - if $shouldhidemarc_opac->{biblionumber}; + if $shouldhidemarc_opac->{biblionumber}; my $shouldhidemarc_intranet = Koha::Filter::MARC::ViewPolicy->should_hide_marc( { @@ -600,10 +593,10 @@ if($tab eq 'sysinfo') { } ); push @hidden_biblionumbers, { frameworkcode => $frameworkcode, interface => 'intranet' } - if $shouldhidemarc_intranet->{biblionumber}; + if $shouldhidemarc_intranet->{biblionumber}; } $template->param( warnHiddenBiblionumbers => \@hidden_biblionumbers ); - $template->param( warnFastCataloging => $no_FA_framework ); + $template->param( warnFastCataloging => $no_FA_framework ); } message_broker_check($template); @@ -614,22 +607,23 @@ if($tab eq 'sysinfo') { } $template->param( - prefRequireChoosingExistingAuthority => $prefRequireChoosingExistingAuthority, - prefAutoCreateAuthorities => $prefAutoCreateAuthorities, - warnPrefRequireChoosingExistingAuthority => $warnPrefRequireChoosingExistingAuthority, - warnPrefEasyAnalyticalRecords => $warnPrefEasyAnalyticalRecords, - warnPrefAnonymousPatronOPACPrivacy => $warnPrefAnonymousPatronOPACPrivacy, - warnPrefAnonymousPatronAnonSuggestions => $warnPrefAnonymousPatronAnonSuggestions, - warnPrefAnonymousPatronOPACPrivacy_PatronDoesNotExist => $warnPrefAnonymousPatronOPACPrivacy_PatronDoesNotExist, - warnPrefAnonymousPatronAnonSuggestions_PatronDoesNotExist => $warnPrefAnonymousPatronAnonSuggestions_PatronDoesNotExist, + prefRequireChoosingExistingAuthority => $prefRequireChoosingExistingAuthority, + prefAutoCreateAuthorities => $prefAutoCreateAuthorities, + warnPrefRequireChoosingExistingAuthority => $warnPrefRequireChoosingExistingAuthority, + warnPrefEasyAnalyticalRecords => $warnPrefEasyAnalyticalRecords, + warnPrefAnonymousPatronOPACPrivacy => $warnPrefAnonymousPatronOPACPrivacy, + warnPrefAnonymousPatronAnonSuggestions => $warnPrefAnonymousPatronAnonSuggestions, + warnPrefAnonymousPatronOPACPrivacy_PatronDoesNotExist => $warnPrefAnonymousPatronOPACPrivacy_PatronDoesNotExist, + warnPrefAnonymousPatronAnonSuggestions_PatronDoesNotExist => + $warnPrefAnonymousPatronAnonSuggestions_PatronDoesNotExist, warnPrefKohaAdminEmailAddress => $warnPrefKohaAdminEmailAddress, - warnPrefOpacHiddenItems => $warnPrefOpacHiddenItems, - errZebraConnection => $errZebraConnection, - warnIsRootUser => $warnIsRootUser, - warnNoActiveCurrency => $warnNoActiveCurrency, - warnNoTemplateCaching => ( C4::Context->config('template_cache_dir') ? 0 : 1 ), - xml_config_warnings => \@xml_config_warnings, - warnStatisticsFieldsError => $warnStatisticsFieldsError, + warnPrefOpacHiddenItems => $warnPrefOpacHiddenItems, + errZebraConnection => $errZebraConnection, + warnIsRootUser => $warnIsRootUser, + warnNoActiveCurrency => $warnNoActiveCurrency, + warnNoTemplateCaching => ( C4::Context->config('template_cache_dir') ? 0 : 1 ), + xml_config_warnings => \@xml_config_warnings, + warnStatisticsFieldsError => $warnStatisticsFieldsError, ); } @@ -642,19 +636,19 @@ if ( $tab eq 'perl' ) { my @pm_types = qw(missing_pm upgrade_pm current_pm); - foreach my $pm_type(@pm_types) { + foreach my $pm_type (@pm_types) { my $modules = $perl_modules->get_attr($pm_type); foreach (@$modules) { - my ($module, $stats) = each %$_; + my ( $module, $stats ) = each %$_; push( @components, { - name => $module, - version => $stats->{'cur_ver'}, - missing => ($pm_type eq 'missing_pm' ? 1 : 0), - upgrade => ($pm_type eq 'upgrade_pm' ? 1 : 0), - current => ($pm_type eq 'current_pm' ? 1 : 0), - require => $stats->{'required'}, + name => $module, + version => $stats->{'cur_ver'}, + missing => ( $pm_type eq 'missing_pm' ? 1 : 0 ), + upgrade => ( $pm_type eq 'upgrade_pm' ? 1 : 0 ), + current => ( $pm_type eq 'current_pm' ? 1 : 0 ), + require => $stats->{'required'}, reqversion => $stats->{'min_ver'}, maxversion => $stats->{'max_ver'}, excversion => $stats->{'exc_ver'} @@ -663,24 +657,27 @@ if ( $tab eq 'perl' ) { } } - @components = sort {$a->{'name'} cmp $b->{'name'}} @components; + @components = sort { $a->{'name'} cmp $b->{'name'} } @components; - my $counter=0; - my $row = []; - my $table = []; + my $counter = 0; + my $row = []; + my $table = []; foreach (@components) { - push (@$row, $_); - unless (++$counter % 4) { - push (@$table, {row => $row}); + push( @$row, $_ ); + unless ( ++$counter % 4 ) { + push( @$table, { row => $row } ); $row = []; } } + # Processing the last line (if there are any modules left) - if (scalar(@$row) > 0) { + if ( scalar(@$row) > 0 ) { + # Extending $row to the table size $$row[3] = ''; + # Pushing the last line - push (@$table, {row => $row}); + push( @$table, { row => $row } ); } ## ## $table @@ -695,30 +692,30 @@ if ( $tab eq 'team' ) { ## Release teams my $teams = - -e "$docdir" . "/teams.yaml" - ? YAML::XS::LoadFile( "$docdir" . "/teams.yaml" ) - : {}; - my $dev_team = (sort {$b <=> $a} (keys %{$teams->{team}}))[0]; - my $short_version = substr($versions{'kohaVersion'},0,5); - my $minor = substr($versions{'kohaVersion'},3,2); + -e "$docdir" . "/teams.yaml" + ? YAML::XS::LoadFile( "$docdir" . "/teams.yaml" ) + : {}; + my $dev_team = ( sort { $b <=> $a } ( keys %{ $teams->{team} } ) )[0]; + my $short_version = substr( $versions{'kohaVersion'}, 0, 5 ); + my $minor = substr( $versions{'kohaVersion'}, 3, 2 ); my $development_version = ( $minor eq '05' || $minor eq '11' ) ? 0 : 1; my $codename; - $template->param( short_version => $short_version ); + $template->param( short_version => $short_version ); $template->param( development_version => $development_version ); ## Contributors my $contributors = - -e "$docdir" . "/contributors.yaml" - ? YAML::XS::LoadFile( "$docdir" . "/contributors.yaml" ) - : {}; + -e "$docdir" . "/contributors.yaml" + ? YAML::XS::LoadFile( "$docdir" . "/contributors.yaml" ) + : {}; delete $contributors->{_others_}; - for my $version ( sort { $a <=> $b } keys %{$teams->{team}} ) { + for my $version ( sort { $a <=> $b } keys %{ $teams->{team} } ) { for my $role ( keys %{ $teams->{team}->{$version} } ) { - my $detail = $teams->{team}->{$version}->{$role}; + my $detail = $teams->{team}->{$version}->{$role}; my $normalized_role = "$role"; $normalized_role =~ s/s$//; - if ( ref( $detail ) eq 'ARRAY' ) { - for my $contributor ( @{ $detail } ) { + if ( ref($detail) eq 'ARRAY' ) { + for my $contributor ( @{$detail} ) { my $localized_role = $normalized_role; if ( my $subversion = $contributor->{version} ) { @@ -729,25 +726,25 @@ if ( $tab eq 'team' ) { } my $name = $contributor->{name}; + # Add role to contributors push @{ $contributors->{$name}->{roles}->{$localized_role} }, - $version; + $version; + # Add openhub to teams if ( exists( $contributors->{$name}->{openhub} ) ) { $contributor->{openhub} = $contributors->{$name}->{openhub}; } } - } - elsif ( $role eq 'release_date' ) { - $teams->{team}->{$version}->{$role} = DateTime->from_epoch( epoch => $teams->{team}->{$version}->{$role} ); - } - elsif ( $role eq 'codename' ) { + } elsif ( $role eq 'release_date' ) { + $teams->{team}->{$version}->{$role} = + DateTime->from_epoch( epoch => $teams->{team}->{$version}->{$role} ); + } elsif ( $role eq 'codename' ) { if ( $version == $short_version ) { $codename = $detail; } next; - } - else { + } else { if ( my $subversion = $detail->{version} ) { $normalized_role .= ':' . $subversion; } @@ -756,36 +753,36 @@ if ( $tab eq 'team' ) { } my $name = $detail->{name}; + # Add role to contributors push @{ $contributors->{$name}->{roles}->{$normalized_role} }, - $version; + $version; + # Add openhub to teams if ( exists( $contributors->{$name}->{openhub} ) ) { $detail->{openhub} = - $contributors->{$name}->{openhub}; + $contributors->{$name}->{openhub}; } } } } ## Create last name ordered array of people from contributors - my @people = map { - { name => $_, ( $contributors->{$_} ? %{ $contributors->{$_} } : () ) } - } sort { - my ($alast) = $a =~ /(\S+)$/; - my ($blast) = $b =~ /(\S+)$/; - my $cmp = lc($alast||"") cmp lc($blast||""); - return $cmp if $cmp; + my @people = map { { name => $_, ( $contributors->{$_} ? %{ $contributors->{$_} } : () ) } } sort { + my ($alast) = $a =~ /(\S+)$/; + my ($blast) = $b =~ /(\S+)$/; + my $cmp = lc( $alast || "" ) cmp lc( $blast || "" ); + return $cmp if $cmp; - my ($a2last) = $a =~ /(\S+)\s\S+$/; - my ($b2last) = $b =~ /(\S+)\s\S+$/; - lc($a2last||"") cmp lc($b2last||""); + my ($a2last) = $a =~ /(\S+)\s\S+$/; + my ($b2last) = $b =~ /(\S+)\s\S+$/; + lc( $a2last || "" ) cmp lc( $b2last || "" ); } keys %$contributors; - $template->param( kohaCodename => $codename); - $template->param( contributors => \@people ); + $template->param( kohaCodename => $codename ); + $template->param( contributors => \@people ); $template->param( maintenance_team => $teams->{team}->{$dev_team} ); - $template->param( release_team => $teams->{team}->{$short_version} ); + $template->param( release_team => $teams->{team}->{$short_version} ); } if ( $tab eq 'history' ) { @@ -801,12 +798,12 @@ if ( $tab eq 'history' ) { my @lines = <$file>; close($file); - shift @lines; #remove header row + shift @lines; #remove header row foreach (@lines) { my ( $epoch, $date, $desc, $tag ) = split(/\t/); - if(!$desc && $date=~ /(?<=\d{4})\s+/) { - ($date, $desc)= ($`, $'); + if ( !$desc && $date =~ /(?<=\d{4})\s+/ ) { + ( $date, $desc ) = ( $`, $' ); } push( @rows2, @@ -818,9 +815,10 @@ if ( $tab eq 'history' ) { } my $table2 = []; + #foreach my $row2 (@rows2) { - foreach (@rows2) { - push (@$row2, $_); + foreach (@rows2) { + push( @$row2, $_ ); push( @$table2, { row2 => $row2 } ); $row2 = []; } @@ -914,22 +912,20 @@ sub message_broker_check { { # BackgroundJob - test connection to message broker my $conn = Koha::BackgroundJob->connect; - if (! $conn) { - if (C4::Context->preference('JobsNotificationMethod') eq 'STOMP' ) { + if ( !$conn ) { + if ( C4::Context->preference('JobsNotificationMethod') eq 'STOMP' ) { $template->param( warnConnectBroker => 'Error connecting' ); } else { - $template->param( - warnConnectBroker => C4::Context->preference('JobsNotificationMethod') - ); + $template->param( warnConnectBroker => C4::Context->preference('JobsNotificationMethod') ); } } } - } +} if ( $tab eq 'database' ) { use Koha::Database::Auditor; my $db_auditor = Koha::Database::Auditor->new(); - my $db_audit = $db_auditor->run; + my $db_audit = $db_auditor->run; $template->param( db_audit => $db_audit ); } output_html_with_http_headers $query, $cookie, $template->output; diff --git a/acqui/addorderiso2709.pl b/acqui/addorderiso2709.pl index 7f0f160bc2..a1533ec338 100755 --- a/acqui/addorderiso2709.pl +++ b/acqui/addorderiso2709.pl @@ -97,7 +97,7 @@ if ( $op eq "" ) { #display batches my $batches_list = Koha::MarcOrder->import_batches_list(); $template->param( - batch_list => $batches_list->{list}, + batch_list => $batches_list->{list}, num_results => $batches_list->{num_results} ); # @@ -116,7 +116,7 @@ if ( $op eq "" ) { bookseller => $bookseller, "allmatch" => $allmatch, ); - my $biblios_list = Koha::MarcOrder->import_biblios_list( $cgiparams->{'import_batch_id'} ); + my $biblios_list = Koha::MarcOrder->import_biblios_list( $cgiparams->{'import_batch_id'} ); my $overlay_action = $biblios_list->{overlay_action}; my $nomatch_action = $biblios_list->{nomatch_action}; my $item_action = $biblios_list->{item_action}; @@ -168,13 +168,15 @@ if ( $op eq "" ) { $template->param( items => \@itemloop ); } -# -# 3rd step = import the records -# + # + # 3rd step = import the records + # } elsif ( $op eq 'cud-import_records' ) { -#import selected lines - $template->param('basketno' => $cgiparams->{'basketno'}); -# Budget_id is mandatory for adding an order, we just add a default, the user needs to modify this aftewards + + #import selected lines + $template->param( 'basketno' => $cgiparams->{'basketno'} ); + + # Budget_id is mandatory for adding an order, we just add a default, the user needs to modify this aftewards my $budgets = GetBudgets(); if ( scalar @$budgets == 0 ) { die "No budgets defined, can't continue"; @@ -228,34 +230,32 @@ if ( $op eq "" ) { my $all_currency = $cgiparams->{'all_currency'}; my $client_item_fields = { - quantity => scalar(@homebranches), - homebranches => \@homebranches, - holdingbranches => \@holdingbranches, - itypes => \@itypes, - nonpublic_notes => \@nonpublic_notes, - public_notes => \@public_notes, - locs => \@locs, - ccodes => \@ccodes, - notforloans => \@notforloans, - uris => \@uris, - copynos => \@copynos, - budget_codes => \@budget_codes, - itemprices => \@itemprices, - replacementprices => \@replacementprices, - itemcallnumbers => \@itemcallnumbers, + quantity => scalar(@homebranches), + homebranches => \@homebranches, + holdingbranches => \@holdingbranches, + itypes => \@itypes, + nonpublic_notes => \@nonpublic_notes, + public_notes => \@public_notes, + locs => \@locs, + ccodes => \@ccodes, + notforloans => \@notforloans, + uris => \@uris, + copynos => \@copynos, + budget_codes => \@budget_codes, + itemprices => \@itemprices, + replacementprices => \@replacementprices, + itemcallnumbers => \@itemcallnumbers, coded_location_qualifiers => \@coded_location_qualifiers, - barcodes => \@barcodes, - enumchrons => \@enumchrons, - tags => \@tags, - subfields => \@subfields, - field_values => \@field_values, - serials => \@serials, - c_quantity => - $input->param( 'quantity_' . $import_record->import_record_id ) + barcodes => \@barcodes, + enumchrons => \@enumchrons, + tags => \@tags, + subfields => \@subfields, + field_values => \@field_values, + serials => \@serials, + c_quantity => $input->param( 'quantity_' . $import_record->import_record_id ) || GetMarcQuantity( $marcrecord, C4::Context->preference('marcflavour') ) || 1, - c_budget_id => - $input->param( 'budget_id_' . $import_record->import_record_id ) + c_budget_id => $input->param( 'budget_id_' . $import_record->import_record_id ) || $input->param('all_budget_id') || $budget_id, c_discount => $input->param( 'discount_' . $import_record->import_record_id ), diff --git a/acqui/ajax-getauthvaluedropbox.pl b/acqui/ajax-getauthvaluedropbox.pl index 6d7034b823..172ae47fa2 100755 --- a/acqui/ajax-getauthvaluedropbox.pl +++ b/acqui/ajax-getauthvaluedropbox.pl @@ -47,25 +47,25 @@ Default value for the dropbox. use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Charset qw( NormalizeString ); -use C4::Auth qw( check_api_auth ); +use C4::Auth qw( check_api_auth ); use Koha::AuthorisedValues; my $query = CGI->new(); binmode STDOUT, ':encoding(UTF-8)'; -my ($status, $cookie, $sessionID) = check_api_auth($query, { catalogue => '*'} ); -unless ($status eq "ok") { - print $query->header(-type => 'text/plain', -status => '403 Forbidden'); +my ( $status, $cookie, $sessionID ) = check_api_auth( $query, { catalogue => '*' } ); +unless ( $status eq "ok" ) { + print $query->header( -type => 'text/plain', -status => '403 Forbidden' ); print ''; exit 0; } -my $input = CGI->new; -my $name = $input->param('name'); +my $input = CGI->new; +my $name = $input->param('name'); my $category = $input->param('category'); -my $default = $input->param('default'); +my $default = $input->param('default'); $default = C4::Charset::NormalizeString($default); my $branch_limit = C4::Context->userenv ? C4::Context->userenv->{"branch"} : ""; @@ -89,5 +89,5 @@ while ( my $av = $avs->next ) { $html .= qq||; binmode STDOUT, ':encoding(UTF-8)'; -print $input->header(-type => 'text/plain', -charset => 'UTF-8'); +print $input->header( -type => 'text/plain', -charset => 'UTF-8' ); print $html; diff --git a/acqui/basket.pl b/acqui/basket.pl index ac988877c0..ab19470483 100755 --- a/acqui/basket.pl +++ b/acqui/basket.pl @@ -21,12 +21,13 @@ # along with Koha; if not, see . use Modern::Perl; -use C4::Auth qw( get_template_and_user haspermission ); +use C4::Auth qw( get_template_and_user haspermission ); use C4::Output qw( output_html_with_http_headers output_and_exit ); -use CGI qw ( -utf8 ); -use C4::Acquisition qw( GetBasket CanUserManageBasket GetBasketAsCSV NewBasket NewBasketgroup ModBasket ReopenBasket ModBasketUsers GetBasketgroup GetBasketgroups GetBasketUsers GetOrders GetOrder get_rounded_price ); -use C4::Budgets qw( GetBudgetHierarchy GetBudget CanUserUseBudget ); -use C4::Contract qw( GetContract ); +use CGI qw ( -utf8 ); +use C4::Acquisition + qw( GetBasket CanUserManageBasket GetBasketAsCSV NewBasket NewBasketgroup ModBasket ReopenBasket ModBasketUsers GetBasketgroup GetBasketgroups GetBasketUsers GetOrders GetOrder get_rounded_price ); +use C4::Budgets qw( GetBudgetHierarchy GetBudget CanUserUseBudget ); +use C4::Contract qw( GetContract ); use C4::Suggestions qw( GetSuggestion GetSuggestionInfoFromBiblionumber GetSuggestionInfo ); use Koha::Biblios; use Koha::Acquisition::Baskets; @@ -34,7 +35,7 @@ use Koha::Acquisition::Booksellers; use Koha::Acquisition::Orders; use Koha::Libraries; use C4::Letters qw( SendAlerts ); -use Date::Calc qw( Add_Delta_Days ); +use Date::Calc qw( Add_Delta_Days ); use Koha::Database; use Koha::EDI qw( create_edi_order ); use Koha::CsvProfiles; @@ -75,25 +76,24 @@ our $query = CGI->new; our $basketno = $query->param('basketno'); our $ean = $query->param('ean'); our $booksellerid = $query->param('booksellerid'); -my $duplinbatch = $query->param('duplinbatch'); +my $duplinbatch = $query->param('duplinbatch'); our ( $template, $loggedinuser, $cookie, $userflags ) = get_template_and_user( { - template_name => "acqui/basket.tt", - query => $query, - type => "intranet", - flagsrequired => { acquisition => 'order_manage' }, + template_name => "acqui/basket.tt", + query => $query, + type => "intranet", + flagsrequired => { acquisition => 'order_manage' }, } ); -my $logged_in_patron = Koha::Patrons->find( $loggedinuser ); +my $logged_in_patron = Koha::Patrons->find($loggedinuser); our $basket = GetBasket($basketno); $booksellerid = $basket->{booksellerid} unless $booksellerid; -my $bookseller = Koha::Acquisition::Booksellers->find( $booksellerid ); -my $schema = Koha::Database->new()->schema(); -my $rs = $schema->resultset('VendorEdiAccount')->search( - { vendor_id => $booksellerid, } ); +my $bookseller = Koha::Acquisition::Booksellers->find($booksellerid); +my $schema = Koha::Database->new()->schema(); +my $rs = $schema->resultset('VendorEdiAccount')->search( { vendor_id => $booksellerid, } ); my $ediaccount = ( $rs->count > 0 ); $template->param( ediaccount => $ediaccount ); if ($ediaccount) { @@ -106,13 +106,13 @@ if ($ediaccount) { $template->param( eans => \@eans ); } -unless (CanUserManageBasket($loggedinuser, $basket, $userflags)) { +unless ( CanUserManageBasket( $loggedinuser, $basket, $userflags ) ) { $template->param( cannot_manage_basket => 1, - basketno => $basketno, - basketname => $basket->{basketname}, - booksellerid => $booksellerid, - booksellername => $bookseller->name, + basketno => $basketno, + basketname => $basket->{basketname}, + booksellerid => $booksellerid, + booksellername => $bookseller->name, ); output_html_with_http_headers $query, $cookie, $template->output; exit; @@ -124,8 +124,8 @@ unless (CanUserManageBasket($loggedinuser, $basket, $userflags)) { # warn "=>".$basket->{booksellerid}; my $op = $query->param('op') // 'list'; -our $confirm_pref= C4::Context->preference("BasketConfirmations") || '1'; -$template->param( skip_confirm_reopen => 1) if $confirm_pref eq '2'; +our $confirm_pref = C4::Context->preference("BasketConfirmations") || '1'; +$template->param( skip_confirm_reopen => 1 ) if $confirm_pref eq '2'; my @messages; @@ -147,7 +147,7 @@ if ( $op eq 'cud-delete-order' ) { } elsif ( $op eq 'cud-delete' ) { output_and_exit( $query, $cookie, $template, 'insufficient_permission' ) - unless $logged_in_patron->has_permission( { acquisition => 'delete_baskets' } ); + unless $logged_in_patron->has_permission( { acquisition => 'delete_baskets' } ); my $basketno = $query->param('basketno'); my $delbiblio = $query->param('delbiblio'); @@ -158,8 +158,9 @@ if ( $op eq 'cud-delete-order' ) { my @cannotdelbiblios; while ( my $order = $orders->next ) { + # cancel the order - $order->cancel({ delete_biblio => $delbiblio }); + $order->cancel( { delete_biblio => $delbiblio } ); my @messages = @{ $order->object_messages }; if ( scalar @messages > 0 ) { @@ -168,7 +169,7 @@ if ( $op eq 'cud-delete-order' ) { push @cannotdelbiblios, { biblionumber => $biblio->id, - title => $biblio->title // '', + title => $biblio->title // '', author => $biblio->author // '', countbiblio => $biblio->uncancelled_orders->count, itemcount => $biblio->items->count, @@ -183,24 +184,23 @@ if ( $op eq 'cud-delete-order' ) { $basket_obj->delete; $template->param( delete_confirmed => 1, - booksellername => $bookseller->name, - booksellerid => $booksellerid, + booksellername => $bookseller->name, + booksellerid => $booksellerid, ); } elsif ( !$bookseller ) { $template->param( NO_BOOKSELLER => 1 ); -} elsif ($op eq 'export') { +} elsif ( $op eq 'export' ) { print $query->header( -type => 'text/csv', -attachment => 'basket' . $basket->{'basketno'} . '.csv', ); my $csv_profile_id = $query->param('csv_profile'); - print GetBasketAsCSV( scalar $query->param('basketno'), $query, $csv_profile_id ); # if no csv_profile_id passed, using default rows + print GetBasketAsCSV( scalar $query->param('basketno'), $query, $csv_profile_id ) + ; # if no csv_profile_id passed, using default rows exit; -} elsif ($op eq 'cud-email') { - my $err = eval { - SendAlerts( 'orderacquisition', scalar $query->param('basketno'), 'ACQORDER' ); - }; - if ( $@ ) { +} elsif ( $op eq 'cud-email' ) { + my $err = eval { SendAlerts( 'orderacquisition', scalar $query->param('basketno'), 'ACQORDER' ); }; + if ($@) { push @messages, { type => 'error', code => $@ }; } elsif ( ref $err and exists $err->{error} ) { push @messages, { type => 'error', code => $err->{error} }; @@ -209,7 +209,7 @@ if ( $op eq 'cud-delete-order' ) { } $op = 'list'; -} elsif ($op eq 'cud-close') { +} elsif ( $op eq 'cud-close' ) { my $confirm = $query->param('confirm') || $confirm_pref eq '2'; if ($confirm) { @@ -219,87 +219,98 @@ if ( $op eq 'cud-delete-order' ) { Koha::Acquisition::Baskets->find($basketno)->close; # if requested, create basket group, close it and attach the basket - if ($query->param('createbasketgroup')) { + if ( $query->param('createbasketgroup') ) { my $branchcode; - if(C4::Context->userenv and C4::Context->userenv->{'branch'}) { + if ( C4::Context->userenv and C4::Context->userenv->{'branch'} ) { $branchcode = C4::Context->userenv->{'branch'}; } - my $basketgroupid = NewBasketgroup( { name => $basket->{basketname}, - booksellerid => $booksellerid, - deliveryplace => $branchcode, - billingplace => $branchcode, - closed => 1, - }); - ModBasket( { basketno => $basketno, - basketgroupid => $basketgroupid } ); - print $query->redirect('/cgi-bin/koha/acqui/basketgroup.pl?booksellerid='.$booksellerid.'&closed=1'); + my $basketgroupid = NewBasketgroup( + { + name => $basket->{basketname}, + booksellerid => $booksellerid, + deliveryplace => $branchcode, + billingplace => $branchcode, + closed => 1, + } + ); + ModBasket( + { + basketno => $basketno, + basketgroupid => $basketgroupid + } + ); + print $query->redirect( '/cgi-bin/koha/acqui/basketgroup.pl?booksellerid=' . $booksellerid . '&closed=1' ); } else { - print $query->redirect('/cgi-bin/koha/acqui/booksellers.pl?booksellerid=' . $booksellerid); + print $query->redirect( '/cgi-bin/koha/acqui/booksellers.pl?booksellerid=' . $booksellerid ); } exit; } else { - $template->param( - confirm_close => "1", - booksellerid => $booksellerid, - booksellername => $bookseller->name, - basketno => $basket->{'basketno'}, - basketname => $basket->{'basketname'}, - basketgroupname => $basket->{'basketname'}, - ); + $template->param( + confirm_close => "1", + booksellerid => $booksellerid, + booksellername => $bookseller->name, + basketno => $basket->{'basketno'}, + basketname => $basket->{'basketname'}, + basketgroupname => $basket->{'basketname'}, + ); } -} elsif ($op eq 'cud-reopen') { - ReopenBasket(scalar $query->param('basketno')); - print $query->redirect('/cgi-bin/koha/acqui/basket.pl?basketno='.$basket->{'basketno'}) -} -elsif ( $op eq 'cud-ediorder' ) { +} elsif ( $op eq 'cud-reopen' ) { + ReopenBasket( scalar $query->param('basketno') ); + print $query->redirect( '/cgi-bin/koha/acqui/basket.pl?basketno=' . $basket->{'basketno'} ); +} elsif ( $op eq 'cud-ediorder' ) { $template->param( booksellername => $bookseller->name ); - edi_close_and_order() + edi_close_and_order(); } elsif ( $op eq 'cud-mod_users' ) { my $basketusers_ids = $query->param('users_ids'); - my @basketusers = split( /:/, $basketusers_ids ); - ModBasketUsers($basketno, @basketusers); + my @basketusers = split( /:/, $basketusers_ids ); + ModBasketUsers( $basketno, @basketusers ); print $query->redirect("/cgi-bin/koha/acqui/basket.pl?basketno=$basketno"); exit; } elsif ( $op eq 'cud-mod_branch' ) { my $branch = $query->param('branch'); - $branch = undef if(defined $branch and $branch eq ''); - ModBasket({ - basketno => $basket->{basketno}, - branch => $branch - }); + $branch = undef if ( defined $branch and $branch eq '' ); + ModBasket( + { + basketno => $basket->{basketno}, + branch => $branch + } + ); print $query->redirect("/cgi-bin/koha/acqui/basket.pl?basketno=$basketno"); exit; } if ( $op eq 'list' ) { my @branches_loop; + # get librarian branch... if ( C4::Context->preference("IndependentBranches") ) { my $userenv = C4::Context->userenv; unless ( C4::Context->IsSuperLibrarian() ) { - my $validtest = ( $basket->{creationdate} eq '' ) - || ( $userenv->{branch} eq $basket->{branch} ) - || ( $userenv->{branch} eq '' ) - || ( $basket->{branch} eq '' ); + my $validtest = + ( $basket->{creationdate} eq '' ) + || ( $userenv->{branch} eq $basket->{branch} ) + || ( $userenv->{branch} eq '' ) + || ( $basket->{branch} eq '' ); unless ($validtest) { print $query->redirect("../mainpage.pl"); exit 0; } } - if (!defined $basket->{branch} or $basket->{branch} eq $userenv->{branch}) { + if ( !defined $basket->{branch} or $basket->{branch} eq $userenv->{branch} ) { push @branches_loop, { branchcode => $userenv->{branch}, branchname => $userenv->{branchname}, - selected => 1, + selected => 1, }; } } else { + # get branches my $branches = Koha::Libraries->search( {}, { order_by => ['branchname'] } )->unblessed; foreach my $branch (@$branches) { my $selected = 0; - if (defined $basket->{branch}) { + if ( defined $basket->{branch} ) { $selected = 1 if $branch->{branchcode} eq $basket->{branch}; } else { $selected = 1 if $branch->{branchcode} eq C4::Context->userenv->{branch}; @@ -307,18 +318,18 @@ if ( $op eq 'list' ) { push @branches_loop, { branchcode => $branch->{branchcode}, branchname => $branch->{branchname}, - selected => $selected + selected => $selected }; } } -#if the basket is closed,and the user has the permission to edit basketgroups, display a list of basketgroups - my ($basketgroup, $basketgroups); + #if the basket is closed,and the user has the permission to edit basketgroups, display a list of basketgroups + my ( $basketgroup, $basketgroups ); my $patron = Koha::Patrons->find($loggedinuser); - if ($basket->{closedate} && haspermission($patron->userid, { acquisition => 'group_manage'} )) { - $basketgroups = GetBasketgroups($basket->{booksellerid}); + if ( $basket->{closedate} && haspermission( $patron->userid, { acquisition => 'group_manage' } ) ) { + $basketgroups = GetBasketgroups( $basket->{booksellerid} ); for my $bg ( @{$basketgroups} ) { - if ($basket->{basketgroupid} && $basket->{basketgroupid} == $bg->{id}){ + if ( $basket->{basketgroupid} && $basket->{basketgroupid} == $bg->{id} ) { $bg->{default} = 1; $basketgroup = $bg; } @@ -327,9 +338,9 @@ if ( $op eq 'list' ) { # if the basket is closed, calculate estimated delivery date my $estimateddeliverydate; - if( $basket->{closedate} ) { - my ($year, $month, $day) = ($basket->{closedate} =~ /(\d+)-(\d+)-(\d+)/); - ($year, $month, $day) = Add_Delta_Days($year, $month, $day, $bookseller->deliverytime); + if ( $basket->{closedate} ) { + my ( $year, $month, $day ) = ( $basket->{closedate} =~ /(\d+)-(\d+)-(\d+)/ ); + ( $year, $month, $day ) = Add_Delta_Days( $year, $month, $day, $bookseller->deliverytime ); $estimateddeliverydate = sprintf( "%04d-%02d-%02d", $year, $month, $day ); } @@ -340,120 +351,120 @@ if ( $op eq 'list' ) { my @basketusers_ids = GetBasketUsers($basketno); my @basketusers; foreach my $basketuser_id (@basketusers_ids) { + # FIXME Could be improved with a search -in - my $basket_patron = Koha::Patrons->find( $basketuser_id ); + my $basket_patron = Koha::Patrons->find($basketuser_id); push @basketusers, $basket_patron if $basket_patron; } my $active_currency = Koha::Acquisition::Currencies->get_active; - my @orders = GetOrders( $basketno ); + my @orders = GetOrders($basketno); my @books_loop; my @book_foot_loop; my %foot; - my $total_quantity = 0; + my $total_quantity = 0; my $total_tax_excluded = 0; my $total_tax_included = 0; - my $total_tax_value = 0; + my $total_tax_value = 0; for my $order (@orders) { - my $line = get_order_infos( $order, $bookseller); + my $line = get_order_infos( $order, $bookseller ); if ( $line->{uncertainprice} ) { $template->param( uncertainprices => 1 ); } - $line->{tax_rate} = $line->{tax_rate_on_ordering} // 0; + $line->{tax_rate} = $line->{tax_rate_on_ordering} // 0; $line->{tax_value} = $line->{tax_value_on_ordering} // 0; push @books_loop, $line; - $foot{$$line{tax_rate}}{tax_rate} = $$line{tax_rate}; - $foot{$$line{tax_rate}}{tax_value} += get_rounded_price($$line{tax_value}); - $total_tax_value += $$line{tax_value}; - $foot{$$line{tax_rate}}{quantity} += get_rounded_price($$line{quantity}); - $total_quantity += $$line{quantity}; - $foot{$$line{tax_rate}}{total_tax_excluded} += $$line{total_tax_excluded}; - $total_tax_excluded += $$line{total_tax_excluded}; - $foot{$$line{tax_rate}}{total_tax_included} += $$line{total_tax_included}; - $total_tax_included += $$line{total_tax_included}; + $foot{ $$line{tax_rate} }{tax_rate} = $$line{tax_rate}; + $foot{ $$line{tax_rate} }{tax_value} += get_rounded_price( $$line{tax_value} ); + $total_tax_value += $$line{tax_value}; + $foot{ $$line{tax_rate} }{quantity} += get_rounded_price( $$line{quantity} ); + $total_quantity += $$line{quantity}; + $foot{ $$line{tax_rate} }{total_tax_excluded} += $$line{total_tax_excluded}; + $total_tax_excluded += $$line{total_tax_excluded}; + $foot{ $$line{tax_rate} }{total_tax_included} += $$line{total_tax_included}; + $total_tax_included += $$line{total_tax_included}; } - push @book_foot_loop, map {$_} values %foot; + push @book_foot_loop, map { $_ } values %foot; # Get cancelled orders - my @cancelledorders = GetOrders($basketno, { cancelled => 1 }); + my @cancelledorders = GetOrders( $basketno, { cancelled => 1 } ); my @cancelledorders_loop; for my $order (@cancelledorders) { - my $line = get_order_infos( $order, $bookseller); + my $line = get_order_infos( $order, $bookseller ); push @cancelledorders_loop, $line; } - my $contract = GetContract({ - contractnumber => $basket->{contractnumber} - }); + my $contract = GetContract( { contractnumber => $basket->{contractnumber} } ); - if ($basket->{basketgroupid}){ - $basketgroup = GetBasketgroup($basket->{basketgroupid}); + if ( $basket->{basketgroupid} ) { + $basketgroup = GetBasketgroup( $basket->{basketgroupid} ); } - my $budgets = GetBudgetHierarchy; + my $budgets = GetBudgetHierarchy; my $has_budgets = 0; - foreach my $r (@{$budgets}) { - next unless (CanUserUseBudget($loggedinuser, $r, $userflags)); + foreach my $r ( @{$budgets} ) { + next unless ( CanUserUseBudget( $loggedinuser, $r, $userflags ) ); $has_budgets = 1; last; } my $basket_obj = Koha::Acquisition::Baskets->find($basketno); - my $edi_order = $basket_obj->edi_order; + my $edi_order = $basket_obj->edi_order; $template->param( - basketno => $basketno, - basket => $basket, - basketname => $basket->{'basketname'}, - basketbranchcode => $basket->{branch}, - basketnote => $basket->{note}, - basketbooksellernote => $basket->{booksellernote}, - basketcontractno => $basket->{contractnumber}, - basketcontractname => $contract->{contractname}, - branches_loop => \@branches_loop, - creationdate => $basket->{creationdate}, - edi_order => $edi_order, - authorisedby => $basket->{authorisedby}, - authorisedbyname => $basket->{authorisedbyname}, - users_ids => join(':', @basketusers_ids), - users => \@basketusers, - closedate => $basket->{closedate}, - estimateddeliverydate=> $estimateddeliverydate, - is_standing => $basket->{is_standing}, - deliveryplace => $basket->{deliveryplace}, - billingplace => $basket->{billingplace}, - active => $bookseller->active, - booksellerid => $bookseller->id, - booksellername => $bookseller->name, - books_loop => \@books_loop, - book_foot_loop => \@book_foot_loop, - cancelledorders_loop => \@cancelledorders_loop, - total_quantity => $total_quantity, - total_tax_excluded => $total_tax_excluded, - total_tax_included => $total_tax_included, - total_tax_value => $total_tax_value, - currency => $active_currency->currency, - listincgst => $bookseller->listincgst, - basketgroups => $basketgroups, - basketgroup => $basketgroup, - grouped => $basket->{basketgroupid}, + basketno => $basketno, + basket => $basket, + basketname => $basket->{'basketname'}, + basketbranchcode => $basket->{branch}, + basketnote => $basket->{note}, + basketbooksellernote => $basket->{booksellernote}, + basketcontractno => $basket->{contractnumber}, + basketcontractname => $contract->{contractname}, + branches_loop => \@branches_loop, + creationdate => $basket->{creationdate}, + edi_order => $edi_order, + authorisedby => $basket->{authorisedby}, + authorisedbyname => $basket->{authorisedbyname}, + users_ids => join( ':', @basketusers_ids ), + users => \@basketusers, + closedate => $basket->{closedate}, + estimateddeliverydate => $estimateddeliverydate, + is_standing => $basket->{is_standing}, + deliveryplace => $basket->{deliveryplace}, + billingplace => $basket->{billingplace}, + active => $bookseller->active, + booksellerid => $bookseller->id, + booksellername => $bookseller->name, + books_loop => \@books_loop, + book_foot_loop => \@book_foot_loop, + cancelledorders_loop => \@cancelledorders_loop, + total_quantity => $total_quantity, + total_tax_excluded => $total_tax_excluded, + total_tax_included => $total_tax_included, + total_tax_value => $total_tax_value, + currency => $active_currency->currency, + listincgst => $bookseller->listincgst, + basketgroups => $basketgroups, + basketgroup => $basketgroup, + grouped => $basket->{basketgroupid}, + # The double negatives and booleans here mean: # "A basket cannot be closed if there are no orders in it or it's a standing order basket." # # (The template has another implicit restriction that the order cannot be closed if there # are any orders with uncertain prices.) - unclosable => @orders || @cancelledorders ? $basket->{is_standing} : 1, - has_budgets => $has_budgets, - duplinbatch => $duplinbatch, - csv_profiles => Koha::CsvProfiles->search({ type => 'sql', used_for => 'export_basket' }), + unclosable => @orders || @cancelledorders ? $basket->{is_standing} : 1, + has_budgets => $has_budgets, + duplinbatch => $duplinbatch, + csv_profiles => Koha::CsvProfiles->search( { type => 'sql', used_for => 'export_basket' } ), available_additional_fields => Koha::AdditionalFields->search( { tablename => 'aqbasket' } ), - additional_field_values => + additional_field_values => Koha::Acquisition::Baskets->find($basketno)->get_additional_field_values_for_template, ); } @@ -462,16 +473,17 @@ $template->param( messages => \@messages ); output_html_with_http_headers $query, $cookie, $template->output; sub get_order_infos { - my $order = shift; + my $order = shift; my $bookseller = shift; - my $qty = $order->{'quantity'} || 0; + my $qty = $order->{'quantity'} || 0; if ( !defined $order->{quantityreceived} ) { $order->{quantityreceived} = 0; } - my $budget = GetBudget($order->{budget_id}); - my $basket = GetBasket($order->{basketno}); + my $budget = GetBudget( $order->{budget_id} ); + my $basket = GetBasket( $order->{basketno} ); + + my %line = %{$order}; - my %line = %{ $order }; # Don't show unreceived standing orders as received $line{order_received} = ( $qty == $order->{'quantityreceived'} && ( $basket->{is_standing} ? $qty : 1 ) ); $line{basketno} = $basketno; @@ -486,8 +498,8 @@ sub get_order_infos { my $cost_tax_excluded = $line{unitprice_tax_excluded} || $line{ecost_tax_excluded}; $line{total_tax_included} = get_rounded_price($cost_tax_included) * $line{quantity}; $line{total_tax_excluded} = get_rounded_price($cost_tax_excluded) * $line{quantity}; - $line{tax_value} = $line{tax_value_on_ordering}; - $line{tax_rate} = $line{tax_rate_on_ordering}; + $line{tax_value} = $line{tax_value_on_ordering}; + $line{tax_rate} = $line{tax_rate_on_ordering}; if ( $line{'title'} ) { my $volume = $order->{'volume'}; @@ -497,19 +509,21 @@ sub get_order_infos { } my $biblionumber = $order->{'biblionumber'}; - if ( $biblionumber ) { # The biblio still exists - my $biblio = Koha::Biblios->find( $biblionumber ); + if ($biblionumber) { # The biblio still exists + my $biblio = Koha::Biblios->find($biblionumber); my $countbiblio = $biblio->uncancelled_orders->count; my $ordernumber = $order->{'ordernumber'}; my $cnt_subscriptions = $biblio->subscriptions->count; my $itemcount = $biblio->items->count; my $holds_count = $biblio->holds->count; - my $order = Koha::Acquisition::Orders->find($ordernumber); # FIXME We should certainly do that at the beginning of this sub + my $order = Koha::Acquisition::Orders->find($ordernumber) + ; # FIXME We should certainly do that at the beginning of this sub my $items = $order->items; my $invoice = $order->invoice; - my $itemholds = $biblio->holds->search({ itemnumber => { -in => [ $items->get_column('itemnumber') ] } })->count; + my $itemholds = + $biblio->holds->search( { itemnumber => { -in => [ $items->get_column('itemnumber') ] } } )->count; # if the biblio is not in other orders and if there is no items elsewhere and no subscriptions and no holds we can then show the link "Delete order and Biblio" see bug 5680 $line{can_del_bib} = 1 @@ -530,7 +544,7 @@ sub get_order_infos { $line{deleted_biblio} = Koha::Old::Biblios->find( $order->{deleted_biblionumber} ); } - my $suggestion = GetSuggestionInfoFromBiblionumber($line{biblionumber}); + my $suggestion = GetSuggestionInfoFromBiblionumber( $line{biblionumber} ); $line{suggestionid} = $$suggestion{suggestionid}; $line{surnamesuggestedby} = $$suggestion{surnamesuggestedby}; $line{firstnamesuggestedby} = $$suggestion{firstnamesuggestedby}; @@ -538,15 +552,15 @@ sub get_order_infos { $line{estimated_delivery_date} = $order->{estimated_delivery_date}; foreach my $key (qw(transferred_from transferred_to)) { - if ($line{$key}) { - my $order = GetOrder($line{$key}); - my $basket = GetBasket($order->{basketno}); + if ( $line{$key} ) { + my $order = GetOrder( $line{$key} ); + my $basket = GetBasket( $order->{basketno} ); my $bookseller = Koha::Acquisition::Booksellers->find( $basket->{booksellerid} ); $line{$key} = { - order => $order, - basket => $basket, + order => $order, + basket => $basket, bookseller => $bookseller, - timestamp => $line{$key . '_timestamp'}, + timestamp => $line{ $key . '_timestamp' }, }; } } @@ -559,12 +573,13 @@ sub edi_close_and_order { if ($confirm) { my $edi_params = { basketno => $basketno, - ean => $ean, + ean => $ean, }; if ( $basket->{branch} ) { $edi_params->{branchcode} = $basket->{branch}; } if ( create_edi_order($edi_params) ) { + #$template->param( edifile => 1 ); } Koha::Acquisition::Baskets->find($basketno)->close; @@ -588,22 +603,16 @@ sub edi_close_and_order { ); ModBasket( { - basketno => $basketno, - basketgroupid => $basketgroupid + basketno => $basketno, + basketgroupid => $basketgroupid } ); - print $query->redirect( -"/cgi-bin/koha/acqui/basketgroup.pl?booksellerid=$booksellerid&closed=1" - ); - } - else { - print $query->redirect( - "/cgi-bin/koha/acqui/booksellers.pl?booksellerid=$booksellerid" - ); + print $query->redirect("/cgi-bin/koha/acqui/basketgroup.pl?booksellerid=$booksellerid&closed=1"); + } else { + print $query->redirect("/cgi-bin/koha/acqui/booksellers.pl?booksellerid=$booksellerid"); } exit; - } - else { + } else { $template->param( edi_confirm => 1, booksellerid => $booksellerid, diff --git a/acqui/basketgroup.pl b/acqui/basketgroup.pl index e785bfd545..3055033797 100755 --- a/acqui/basketgroup.pl +++ b/acqui/basketgroup.pl @@ -21,7 +21,6 @@ # You should have received a copy of the GNU General Public License # along with Koha; if not, see . - =head1 NAME basketgroup.pl @@ -46,12 +45,13 @@ The bookseller who we want to display the baskets (and basketgroups) of. use Modern::Perl; use Carp qw( croak ); -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use File::Spec; -use C4::Acquisition qw( GetOrders GetOrder get_rounded_price GetBasket GetBasketgroup GetBasketsByBasketgroup GetBasketgroups GetBasketsByBookseller ModBasket CloseBasketgroup GetBasketGroupAsCSV DelBasketgroup ReOpenBasketgroup ModBasketgroup NewBasket NewBasketgroup ); +use C4::Acquisition + qw( GetOrders GetOrder get_rounded_price GetBasket GetBasketgroup GetBasketsByBasketgroup GetBasketgroups GetBasketsByBookseller ModBasket CloseBasketgroup GetBasketGroupAsCSV DelBasketgroup ReOpenBasketgroup ModBasketgroup NewBasket NewBasketgroup ); use Koha::Database; use Koha::EDI qw( get_edifact_ean create_edi_order ); @@ -60,26 +60,29 @@ use Koha::Acquisition::Booksellers; use Koha::ItemTypes; use Koha::Patrons; -our $input=CGI->new; +our $input = CGI->new; -our ($template, $loggedinuser, $cookie) - = get_template_and_user({template_name => "acqui/basketgroup.tt", - query => $input, - type => "intranet", - flagsrequired => {acquisition => 'group_manage'}, - }); +our ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "acqui/basketgroup.tt", + query => $input, + type => "intranet", + flagsrequired => { acquisition => 'group_manage' }, + } +); sub BasketTotal { - my $basketno = shift; + my $basketno = shift; my $bookseller = shift; - my $total = 0; - my @orders = GetOrders($basketno); - for my $order (@orders){ + my $total = 0; + my @orders = GetOrders($basketno); + for my $order (@orders) { + # FIXME The following is wrong if ( $bookseller->listincgst ) { - $total = $total + ( get_rounded_price($order->{ecost_tax_included}) * $order->{quantity} ); + $total = $total + ( get_rounded_price( $order->{ecost_tax_included} ) * $order->{quantity} ); } else { - $total = $total + ( get_rounded_price($order->{ecost_tax_excluded}) * $order->{quantity} ); + $total = $total + ( get_rounded_price( $order->{ecost_tax_excluded} ) * $order->{quantity} ); } } return $total; @@ -88,90 +91,90 @@ sub BasketTotal { #displays all basketgroups and all closed baskets (in their respective groups) sub displaybasketgroups { my $basketgroups = shift; - my $bookseller = shift; - my $baskets = shift; - if (scalar @$basketgroups != 0) { - foreach my $basketgroup (@$basketgroups){ - my $i = 0; + my $bookseller = shift; + my $baskets = shift; + if ( scalar @$basketgroups != 0 ) { + foreach my $basketgroup (@$basketgroups) { + my $i = 0; my $basketsqty = 0; - while($i < scalar(@$baskets)){ + while ( $i < scalar(@$baskets) ) { my $basket = @$baskets[$i]; - if($basket->{'basketgroupid'} && $basket->{'basketgroupid'} == $basketgroup->{'id'}){ - $basket->{total} = BasketTotal($basket->{basketno}, $bookseller); - push(@{$basketgroup->{'baskets'}}, $basket); - splice(@$baskets, $i, 1); + if ( $basket->{'basketgroupid'} && $basket->{'basketgroupid'} == $basketgroup->{'id'} ) { + $basket->{total} = BasketTotal( $basket->{basketno}, $bookseller ); + push( @{ $basketgroup->{'baskets'} }, $basket ); + splice( @$baskets, $i, 1 ); ++$basketsqty; --$i; } ++$i; } - $basketgroup -> {'basketsqty'} = $basketsqty; + $basketgroup->{'basketsqty'} = $basketsqty; } - $template->param(basketgroups => $basketgroups); + $template->param( basketgroups => $basketgroups ); } - for(my $i=0; $i < scalar @$baskets; ++$i) { - if( ! @$baskets[$i]->{'closedate'} ) { - splice(@$baskets, $i, 1); + for ( my $i = 0 ; $i < scalar @$baskets ; ++$i ) { + if ( !@$baskets[$i]->{'closedate'} ) { + splice( @$baskets, $i, 1 ); --$i; - }else{ - @$baskets[$i]->{total} = BasketTotal(@$baskets[$i]->{basketno}, $bookseller); + } else { + @$baskets[$i]->{total} = BasketTotal( @$baskets[$i]->{basketno}, $bookseller ); } } - $template->param(baskets => $baskets); - $template->param( booksellername => $bookseller->name); + $template->param( baskets => $baskets ); + $template->param( booksellername => $bookseller->name ); } -sub printbasketgrouppdf{ +sub printbasketgrouppdf { my ($basketgroupid) = @_; my $pdfformat = C4::Context->preference("OrderPdfFormat"); - my @valid_pdfformats = qw(pdfformat::layout3pages pdfformat::layout2pages pdfformat::layout3pagesfr pdfformat::layout2pagesde pdfformat::layout1page); - if (grep {$_ eq $pdfformat} @valid_pdfformats) { + my @valid_pdfformats = + qw(pdfformat::layout3pages pdfformat::layout2pages pdfformat::layout3pagesfr pdfformat::layout2pagesde pdfformat::layout1page); + if ( grep { $_ eq $pdfformat } @valid_pdfformats ) { $pdfformat = "Koha::$pdfformat"; - my $pdfformat_filepath = File::Spec->catfile(split /::/, $pdfformat) . '.pm'; + my $pdfformat_filepath = File::Spec->catfile( split /::/, $pdfformat ) . '.pm'; require $pdfformat_filepath; import $pdfformat qw(printpdf); - } - else { + } else { print $input->header; - print $input->start_html; # FIXME Should do a nicer page + print $input->start_html; # FIXME Should do a nicer page print "

Invalid PDF Format set

"; print "Please go to the systempreferences and set a valid pdfformat"; exit; } my $basketgroup = GetBasketgroup($basketgroupid); - my $bookseller = Koha::Acquisition::Booksellers->find( $basketgroup->{booksellerid} ); - my $baskets = GetBasketsByBasketgroup($basketgroupid); + my $bookseller = Koha::Acquisition::Booksellers->find( $basketgroup->{booksellerid} ); + my $baskets = GetBasketsByBasketgroup($basketgroupid); my %orders; for my $basket (@$baskets) { my @ba_orders; - my @ords = &GetOrders($basket->{basketno}); + my @ords = &GetOrders( $basket->{basketno} ); for my $ord (@ords) { - next unless ( $ord->{biblionumber} or $ord->{quantity}> 0 ); + next unless ( $ord->{biblionumber} or $ord->{quantity} > 0 ); eval { require C4::Biblio; import C4::Biblio; }; - if ($@){ + if ($@) { croak $@; } eval { require C4::Koha; import C4::Koha; }; - if ($@){ + if ($@) { croak $@; } - $ord->{tax_value} = $ord->{tax_value_on_ordering}; - $ord->{tax_rate} = $ord->{tax_rate_on_ordering}; - $ord->{total_tax_included} = get_rounded_price($ord->{ecost_tax_included}) * $ord->{quantity}; - $ord->{total_tax_excluded} = get_rounded_price($ord->{ecost_tax_excluded}) * $ord->{quantity}; + $ord->{tax_value} = $ord->{tax_value_on_ordering}; + $ord->{tax_rate} = $ord->{tax_rate_on_ordering}; + $ord->{total_tax_included} = get_rounded_price( $ord->{ecost_tax_included} ) * $ord->{quantity}; + $ord->{total_tax_excluded} = get_rounded_price( $ord->{ecost_tax_excluded} ) * $ord->{quantity}; - my $biblioitem = Koha::Biblioitems->search({ biblionumber => $ord->{biblionumber} })->next; + my $biblioitem = Koha::Biblioitems->search( { biblionumber => $ord->{biblionumber} } )->next; #FIXME DELETE ME # 0 1 2 3 4 5 6 7 8 9 @@ -181,34 +184,38 @@ sub printbasketgrouppdf{ my $en; my $edition; $ord->{marcxml} = C4::Biblio::GetXmlBiblio( $ord->{biblionumber} ); - my $marcrecord=eval{MARC::Record::new_from_xml( $ord->{marcxml},'UTF-8' )}; - if ($marcrecord){ + my $marcrecord = eval { MARC::Record::new_from_xml( $ord->{marcxml}, 'UTF-8' ) }; + if ($marcrecord) { if ( C4::Context->preference("marcflavour") eq 'UNIMARC' ) { - $en = $marcrecord->subfield( '345', "b" ); + $en = $marcrecord->subfield( '345', "b" ); $edition = $marcrecord->subfield( '205', 'a' ); } elsif ( C4::Context->preference("marcflavour") eq 'MARC21' ) { - $en = $marcrecord->subfield( '037', "a" ); + $en = $marcrecord->subfield( '037', "a" ); $edition = $marcrecord->subfield( '250', 'a' ); } } - my $itemtype = ( $ord->{itemtype} and $biblioitem->itemtype ) + my $itemtype = + ( $ord->{itemtype} and $biblioitem->itemtype ) ? Koha::ItemTypes->find( $biblioitem->itemtype ) : undef; $ord->{itemtype} = $itemtype ? $itemtype->description : undef; - $ord->{en} = $en ? $en : undef; + $ord->{en} = $en ? $en : undef; $ord->{edition} = $edition ? $edition : undef; - push(@ba_orders, $ord); + push( @ba_orders, $ord ); } - $orders{$basket->{basketno}} = \@ba_orders; + $orders{ $basket->{basketno} } = \@ba_orders; } print $input->header( -type => 'application/pdf', -attachment => ( $basketgroup->{name} || $basketgroupid ) . '.pdf' ); - my $pdf = printpdf($basketgroup, $bookseller, $baskets, \%orders, $bookseller->tax_rate // C4::Context->preference("TaxRates")) || die "pdf generation failed"; + my $pdf = printpdf( + $basketgroup, $bookseller, $baskets, \%orders, + $bookseller->tax_rate // C4::Context->preference("TaxRates") + ) || die "pdf generation failed"; print $pdf; } @@ -218,20 +225,20 @@ sub generate_edifact_orders { my $baskets = GetBasketsByBasketgroup($basketgroupid); my $ean = get_edifact_ean(); - if($ean) { + if ($ean) { for my $basket ( @{$baskets} ) { create_edi_order( { ean => $ean, basketno => $basket->{basketno}, } ); } } else { my $booksellerid = $input->param('booksellerid') || 0; - print $input->redirect('/cgi-bin/koha/acqui/basketgroup.pl?booksellerid=' . - $booksellerid . - '&message=No%20EDIFACT%20Setup'); + print $input->redirect( + '/cgi-bin/koha/acqui/basketgroup.pl?booksellerid=' . $booksellerid . '&message=No%20EDIFACT%20Setup' ); } return; } my $op = $input->param('op') || 'display'; + # possible values of $op : # - add : adds a new basketgroup, or edit an open basketgroup, or display a closed basketgroup # - mod_basket : modify an individual basket of the basketgroup @@ -244,118 +251,131 @@ my $op = $input->param('op') || 'display'; # - attachbasket : save a modified basketgroup, or creates a new basketgroup when a basket is closed. called from basket page # - display : display the list of all basketgroups for a vendor my $booksellerid = $input->param('booksellerid'); -$template->param(booksellerid => $booksellerid); -my $bookseller = Koha::Acquisition::Booksellers->find( $booksellerid ); +$template->param( booksellerid => $booksellerid ); +my $bookseller = Koha::Acquisition::Booksellers->find($booksellerid); my $schema = Koha::Database->new()->schema(); -my $rs = $schema->resultset('VendorEdiAccount')->search( - { vendor_id => $booksellerid, } ); -$template->param( ediaccount => ($rs->count > 0)); +my $rs = $schema->resultset('VendorEdiAccount')->search( { vendor_id => $booksellerid, } ); +$template->param( ediaccount => ( $rs->count > 0 ) ); if ( $op eq "add_form" ) { -# -# if no param('basketgroupid') is not defined, adds a new basketgroup -# else, edit (if it is open) or display (if it is close) the basketgroup basketgroupid -# the template will know if basketgroup must be displayed or edited, depending on the value of closed key -# - my $bookseller = Koha::Acquisition::Booksellers->find( $booksellerid ); + # + # if no param('basketgroupid') is not defined, adds a new basketgroup + # else, edit (if it is open) or display (if it is close) the basketgroup basketgroupid + # the template will know if basketgroup must be displayed or edited, depending on the value of closed key + # + my $bookseller = Koha::Acquisition::Booksellers->find($booksellerid); my $basketgroupid = $input->param('basketgroupid'); my $billingplace; my $deliveryplace; my $freedeliveryplace; - if ( $basketgroupid ) { + if ($basketgroupid) { + # Get the selected baskets in the basketgroup to display them my $selecteds = GetBasketsByBasketgroup($basketgroupid); - foreach my $basket(@{$selecteds}){ - $basket->{total} = BasketTotal($basket->{basketno}, $bookseller); + foreach my $basket ( @{$selecteds} ) { + $basket->{total} = BasketTotal( $basket->{basketno}, $bookseller ); } - $template->param(basketgroupid => $basketgroupid, - selectedbaskets => $selecteds); + $template->param( + basketgroupid => $basketgroupid, + selectedbaskets => $selecteds + ); # Get general informations about the basket group to prefill the form my $basketgroup = GetBasketgroup($basketgroupid); $template->param( - name => $basketgroup->{name}, - deliverycomment => $basketgroup->{deliverycomment}, + name => $basketgroup->{name}, + deliverycomment => $basketgroup->{deliverycomment}, freedeliveryplace => $basketgroup->{freedeliveryplace}, ); - $billingplace = $basketgroup->{billingplace}; - $deliveryplace = $basketgroup->{deliveryplace}; + $billingplace = $basketgroup->{billingplace}; + $deliveryplace = $basketgroup->{deliveryplace}; $freedeliveryplace = $basketgroup->{freedeliveryplace}; - $template->param( closedbg => ($basketgroup ->{'closed'}) ? 1 : 0); + $template->param( closedbg => ( $basketgroup->{'closed'} ) ? 1 : 0 ); } else { + # When creating a new basket group preselect billing and delivery place based on logged-in user - my $patron = Koha::Patrons->find( $loggedinuser ); + my $patron = Koha::Patrons->find($loggedinuser); $billingplace = $patron->branchcode; $deliveryplace = $patron->branchcode; - $template->param( closedbg => 0); + $template->param( closedbg => 0 ); } - $template->param( billingplace => $billingplace ); + $template->param( billingplace => $billingplace ); $template->param( deliveryplace => $deliveryplace ); - $template->param( booksellerid => $booksellerid ); + $template->param( booksellerid => $booksellerid ); # the template will display a unique basketgroup - $template->param(grouping => 1); + $template->param( grouping => 1 ); my $basketgroups = &GetBasketgroups($booksellerid); - my $baskets = &GetBasketsByBookseller($booksellerid); - displaybasketgroups($basketgroups, $bookseller, $baskets); -} elsif ($op eq 'cud-mod_basket') { -# -# edit an individual basket contained in this basketgroup -# - my $basketno=$input->param('basketno'); - my $basketgroupid=$input->param('basketgroupid'); - ModBasket( { basketno => $basketno, - basketgroupid => $basketgroupid } ); - print $input->redirect("basket.pl?basketno=" . $basketno); -} elsif ( $op eq 'closeandprint') { -# -# close an open basketgroup and generates a pdf -# + my $baskets = &GetBasketsByBookseller($booksellerid); + displaybasketgroups( $basketgroups, $bookseller, $baskets ); +} elsif ( $op eq 'cud-mod_basket' ) { + # + # edit an individual basket contained in this basketgroup + # + my $basketno = $input->param('basketno'); + my $basketgroupid = $input->param('basketgroupid'); + ModBasket( + { + basketno => $basketno, + basketgroupid => $basketgroupid + } + ); + print $input->redirect( "basket.pl?basketno=" . $basketno ); +} elsif ( $op eq 'closeandprint' ) { + # + # close an open basketgroup and generates a pdf + # my $basketgroupid = $input->param('basketgroupid'); CloseBasketgroup($basketgroupid); printbasketgrouppdf($basketgroupid); exit; -}elsif ($op eq 'print'){ -# -# print a closed basketgroup -# +} elsif ( $op eq 'print' ) { + # + # print a closed basketgroup + # my $basketgroupid = $input->param('basketgroupid'); printbasketgrouppdf($basketgroupid); exit; -}elsif ( $op eq "export" ) { -# -# export a closed basketgroup in csv -# +} elsif ( $op eq "export" ) { + # + # export a closed basketgroup in csv + # my $basketgroupid = $input->param('basketgroupid'); - my $basketgroup = GetBasketgroup($basketgroupid); + my $basketgroup = GetBasketgroup($basketgroupid); print $input->header( -type => 'text/csv', -attachment => ( $basketgroup->{name} || $basketgroupid ) . '.csv' ); print GetBasketGroupAsCSV( $basketgroupid, $input ); exit; -}elsif( $op eq "cud-delete"){ -# -# delete an closed basketgroup -# +} elsif ( $op eq "cud-delete" ) { + # + # delete an closed basketgroup + # my $basketgroupid = $input->param('basketgroupid'); DelBasketgroup($basketgroupid); - print $input->redirect('/cgi-bin/koha/acqui/basketgroup.pl?booksellerid=' . $booksellerid.'&listclosed=1'); -}elsif ( $op eq 'cud-reopen'){ -# -# reopen a closed basketgroup -# - my $basketgroupid = $input->param('basketgroupid'); - my $booksellerid = $input->param('booksellerid'); + print $input->redirect( '/cgi-bin/koha/acqui/basketgroup.pl?booksellerid=' . $booksellerid . '&listclosed=1' ); +} elsif ( $op eq 'cud-reopen' ) { + # + # reopen a closed basketgroup + # + my $basketgroupid = $input->param('basketgroupid'); + my $booksellerid = $input->param('booksellerid'); ReOpenBasketgroup($basketgroupid); - my $redirectpath = ((defined $input->param('mode'))&& ($input->param('mode') eq 'singlebg')) ?'/cgi-bin/koha/acqui/basketgroup.pl?op=add&basketgroupid='.$basketgroupid.'&booksellerid='.$booksellerid : '/cgi-bin/koha/acqui/basketgroup.pl?booksellerid=' .$booksellerid.'&listclosed=1'; + my $redirectpath = + ( ( defined $input->param('mode') ) && ( $input->param('mode') eq 'singlebg' ) ) + ? '/cgi-bin/koha/acqui/basketgroup.pl?op=add&basketgroupid=' + . $basketgroupid + . '&booksellerid=' + . $booksellerid + : '/cgi-bin/koha/acqui/basketgroup.pl?booksellerid=' . $booksellerid . '&listclosed=1'; print $input->redirect($redirectpath); -} elsif ( $op eq 'cud-attachbasket') { -# -# save a modified basketgroup, or creates a new basketgroup when a basket is closed. called from basket page -# +} elsif ( $op eq 'cud-attachbasket' ) { + # + # save a modified basketgroup, or creates a new basketgroup when a basket is closed. called from basket page + # # Getting parameters my $basketgroup = {}; my @baskets = $input->multi_param('basket'); @@ -367,24 +387,28 @@ if ( $op eq "add_form" ) { my $freedeliveryplace = $input->param('freedeliveryplace'); my $deliverycomment = $input->param('deliverycomment'); my $closedbg = $input->param('closedbg') ? 1 : 0; + if ($basketgroupid) { - # If we have a basketgroupid we edit the basketgroup + + # If we have a basketgroupid we edit the basketgroup $basketgroup = { - name => $basketgroupname, - id => $basketgroupid, - basketlist => \@baskets, - billingplace => $billingplace, - deliveryplace => $deliveryplace, - freedeliveryplace => $freedeliveryplace, - deliverycomment => $deliverycomment, - closed => $closedbg, + name => $basketgroupname, + id => $basketgroupid, + basketlist => \@baskets, + billingplace => $billingplace, + deliveryplace => $deliveryplace, + freedeliveryplace => $freedeliveryplace, + deliverycomment => $deliverycomment, + closed => $closedbg, }; ModBasketgroup($basketgroup); - if($closedbg){ -# FIXME + if ($closedbg) { + + # FIXME } - }else{ - # we create a new basketgroup (with a closed basket) + } else { + + # we create a new basketgroup (with a closed basket) $basketgroup = { name => $basketgroupname, booksellerid => $booksellerid, @@ -397,31 +421,40 @@ if ( $op eq "add_form" ) { }; $basketgroupid = NewBasketgroup($basketgroup); } - my $redirectpath = ((defined $input->param('mode')) && ($input->param('mode') eq 'singlebg')) ?'/cgi-bin/koha/acqui/basketgroup.pl?op=add&basketgroupid='.$basketgroupid.'&booksellerid='.$booksellerid : '/cgi-bin/koha/acqui/basketgroup.pl?booksellerid=' . $booksellerid; - $redirectpath .= "&listclosed=1" if $closedbg ; - print $input->redirect($redirectpath ); - -} elsif ( $op eq 'cud-ediprint') { + my $redirectpath = + ( ( defined $input->param('mode') ) && ( $input->param('mode') eq 'singlebg' ) ) + ? '/cgi-bin/koha/acqui/basketgroup.pl?op=add&basketgroupid=' + . $basketgroupid + . '&booksellerid=' + . $booksellerid + : '/cgi-bin/koha/acqui/basketgroup.pl?booksellerid=' . $booksellerid; + $redirectpath .= "&listclosed=1" if $closedbg; + print $input->redirect($redirectpath); + +} elsif ( $op eq 'cud-ediprint' ) { my $basketgroupid = $input->param('basketgroupid'); - if ($template->param( 'ediaccount' )) { - generate_edifact_orders( $basketgroupid ); + if ( $template->param('ediaccount') ) { + generate_edifact_orders($basketgroupid); exit; } else { - $template->param('NoEDIMessage' => 1); + $template->param( 'NoEDIMessage' => 1 ); my $basketgroups = &GetBasketgroups($booksellerid); - my $bookseller = Koha::Acquisition::Booksellers->find( $booksellerid ); - my $baskets = &GetBasketsByBookseller($booksellerid); + my $bookseller = Koha::Acquisition::Booksellers->find($booksellerid); + my $baskets = &GetBasketsByBookseller($booksellerid); - displaybasketgroups($basketgroups, $bookseller, $baskets); + displaybasketgroups( $basketgroups, $bookseller, $baskets ); } -}else{ -# no param : display the list of all basketgroups for a given vendor - my $basketgroups = &GetBasketgroups($booksellerid); - my $bookseller = Koha::Acquisition::Booksellers->find( $booksellerid ); - my $baskets = &GetBasketsByBookseller($booksellerid); +} else { - displaybasketgroups($basketgroups, $bookseller, $baskets); + # no param : display the list of all basketgroups for a given vendor + my $basketgroups = &GetBasketgroups($booksellerid); + my $bookseller = Koha::Acquisition::Booksellers->find($booksellerid); + my $baskets = &GetBasketsByBookseller($booksellerid); + + displaybasketgroups( $basketgroups, $bookseller, $baskets ); } -$template->param(listclosed => ((defined $input->param('listclosed')) && ($input->param('listclosed') eq '1'))? 1:0 ); +$template->param( + listclosed => ( ( defined $input->param('listclosed') ) && ( $input->param('listclosed') eq '1' ) ) ? 1 : 0 ); + #prolly won't use all these, maybe just use print, the rest can be done inside validate output_html_with_http_headers $input, $cookie, $template->output; diff --git a/acqui/basketheader.pl b/acqui/basketheader.pl index c45376103f..4ab854258d 100755 --- a/acqui/basketheader.pl +++ b/acqui/basketheader.pl @@ -48,10 +48,10 @@ If it exists, C<$basketno> is the basket we edit use Modern::Perl; use CGI qw ( -utf8 ); use C4::Context; -use C4::Auth qw( get_template_and_user ); -use C4::Output qw( output_html_with_http_headers ); +use C4::Auth qw( get_template_and_user ); +use C4::Output qw( output_html_with_http_headers ); use C4::Acquisition qw( GetBasket ModBasket ModBasketHeader NewBasket ); -use C4::Contract qw( GetContracts GetContract ); +use C4::Contract qw( GetContracts GetContract ); use Koha::Acquisition::Booksellers; use Koha::Acquisition::Baskets; @@ -60,34 +60,37 @@ use Koha::AdditionalFields; my $input = CGI->new; my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "acqui/basketheader.tt", - query => $input, - type => "intranet", - flagsrequired => { acquisition => 'order_manage' }, + template_name => "acqui/basketheader.tt", + query => $input, + type => "intranet", + flagsrequired => { acquisition => 'order_manage' }, } ); #parameters: my $booksellerid = $input->param('booksellerid'); -my $basketno = $input->param('basketno'); +my $basketno = $input->param('basketno'); my $basket; -my $op = $input->param('op'); +my $op = $input->param('op'); my $is_an_edit = $input->param('is_an_edit'); $template->param( available_additional_fields => Koha::AdditionalFields->search( { tablename => 'aqbasket' } ) ); if ( $op eq 'add_form' ) { my @contractloop; - if ( $basketno ) { - #this is an edit + if ($basketno) { + + #this is an edit $basket = GetBasket($basketno); - if (! $booksellerid) { - $booksellerid=$basket->{'booksellerid'}; + if ( !$booksellerid ) { + $booksellerid = $basket->{'booksellerid'}; } - my $contracts = GetContracts({ - booksellerid => $booksellerid, - activeonly => 1, - }); + my $contracts = GetContracts( + { + booksellerid => $booksellerid, + activeonly => 1, + } + ); @contractloop = @$contracts; for (@contractloop) { @@ -95,46 +98,53 @@ if ( $op eq 'add_form' ) { $_->{'selected'} = 1; } } - $template->param( is_an_edit => 1); + $template->param( is_an_edit => 1 ); $template->param( additional_field_values => Koha::Acquisition::Baskets->find($basketno)->get_additional_field_values_for_template ); } else { - #new basket + + #new basket my $basket; - my $contracts = GetContracts({ - booksellerid => $booksellerid, - activeonly => 1, - }); - push(@contractloop, @$contracts); + my $contracts = GetContracts( + { + booksellerid => $booksellerid, + activeonly => 1, + } + ); + push( @contractloop, @$contracts ); } - my $bookseller = Koha::Acquisition::Booksellers->find( $booksellerid ); - my $count = scalar @contractloop; - if ( $count > 0) { - $template->param(contractloop => \@contractloop, - basketcontractnumber => $basket->{'contractnumber'}); + my $bookseller = Koha::Acquisition::Booksellers->find($booksellerid); + my $count = scalar @contractloop; + if ( $count > 0 ) { + $template->param( + contractloop => \@contractloop, + basketcontractnumber => $basket->{'contractnumber'} + ); } - $template->param( add_form => 1, - basketname => $basket->{'basketname'}, - basketnote => $basket->{'note'}, - basketbooksellernote => $basket->{'booksellernote'}, - booksellername => $bookseller->name, - booksellerid => $booksellerid, - basketno => $basketno, - is_standing => $basket->{is_standing}, - create_items => $basket->{create_items}, + $template->param( + add_form => 1, + basketname => $basket->{'basketname'}, + basketnote => $basket->{'note'}, + basketbooksellernote => $basket->{'booksellernote'}, + booksellername => $bookseller->name, + booksellerid => $booksellerid, + basketno => $basketno, + is_standing => $basket->{is_standing}, + create_items => $basket->{create_items}, ); - my $billingplace = $basket->{'billingplace'} || C4::Context->userenv->{"branch"}; + my $billingplace = $basket->{'billingplace'} || C4::Context->userenv->{"branch"}; my $deliveryplace = $basket->{'deliveryplace'} || C4::Context->userenv->{"branch"}; - $template->param( billingplace => $billingplace ); + $template->param( billingplace => $billingplace ); $template->param( deliveryplace => $deliveryplace ); -#End Edit + #End Edit } elsif ( $op eq 'cud-add_validate' ) { -#we are confirming the changes, save the basket - if ( $is_an_edit ) { + + #we are confirming the changes, save the basket + if ($is_an_edit) { ModBasketHeader( $basketno, scalar $input->param('basketname'), @@ -147,7 +157,7 @@ if ( $op eq 'add_form' ) { scalar $input->param('is_standing') ? 1 : undef, scalar $input->param('create_items') ); - } else { #New basket + } else { #New basket $basketno = NewBasket( scalar $input->param('basketbooksellerid'), $loggedinuser, @@ -164,9 +174,9 @@ if ( $op eq 'add_form' ) { my @additional_fields = Koha::Acquisition::Baskets->find($basketno)->prepare_cgi_additional_field_values( $input, 'aqbasket' ); - Koha::Acquisition::Baskets->find($basketno)->set_additional_fields(\@additional_fields); + Koha::Acquisition::Baskets->find($basketno)->set_additional_fields( \@additional_fields ); - print $input->redirect('basket.pl?basketno='.$basketno); + print $input->redirect( 'basket.pl?basketno=' . $basketno ); exit 0; } output_html_with_http_headers $input, $cookie, $template->output; diff --git a/acqui/booksellers.pl b/acqui/booksellers.pl index beaf0e7b0b..fed8060a72 100755 --- a/acqui/booksellers.pl +++ b/acqui/booksellers.pl @@ -52,10 +52,10 @@ The id of the supplier whose baskets we will display =cut use Modern::Perl; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Budgets qw( GetBudgetHierarchy GetBudget CanUserUseBudget ); -use C4::Output qw( output_html_with_http_headers ); -use CGI qw ( -utf8 ); +use C4::Output qw( output_html_with_http_headers ); +use CGI qw ( -utf8 ); use C4::Acquisition qw( GetBasket GetBasketsInfosByBookseller CanUserManageBasket GetBasketgroup ); use C4::Context; @@ -65,25 +65,26 @@ use Koha::Patrons; my $query = CGI->new; my ( $template, $loggedinuser, $cookie, $userflags ) = get_template_and_user( - { template_name => 'acqui/booksellers.tt', - query => $query, - type => 'intranet', - flagsrequired => { acquisition => '*' }, + { + template_name => 'acqui/booksellers.tt', + query => $query, + type => 'intranet', + flagsrequired => { acquisition => '*' }, } ); #parameters -my $supplier = $query->param('supplier'); +my $supplier = $query->param('supplier'); my $booksellerid = $query->param('booksellerid'); -my $allbaskets= $query->param('allbaskets')||0; +my $allbaskets = $query->param('allbaskets') || 0; my @suppliers; if ($booksellerid) { - push @suppliers, Koha::Acquisition::Booksellers->find( $booksellerid ); + push @suppliers, Koha::Acquisition::Booksellers->find($booksellerid); } else { @suppliers = Koha::Acquisition::Booksellers->search( [ - { name => { -like => "%$supplier%" } }, + { name => { -like => "%$supplier%" } }, { 'aqbookseller_aliases.alias' => { -like => "%$supplier%" } }, ], { @@ -97,30 +98,32 @@ if ($booksellerid) { my $supplier_count = @suppliers; if ( $supplier_count == 1 ) { $template->param( - supplier_name => $suppliers[0]->name, - booksellerid => $suppliers[0]->id, - basketcount => $suppliers[0]->baskets->count, + supplier_name => $suppliers[0]->name, + booksellerid => $suppliers[0]->id, + basketcount => $suppliers[0]->baskets->count, subscriptionscount => $suppliers[0]->subscriptions->count, - active => $suppliers[0]->active, + active => $suppliers[0]->active, ); } my $uid; + # FIXME This script should only be accessed by a valid logged in patron if ($loggedinuser) { + # FIXME Should not be needed, logged in patron should be cached - $uid = Koha::Patrons->find( $loggedinuser )->userid; + $uid = Koha::Patrons->find($loggedinuser)->userid; } -my $userenv = C4::Context::userenv; +my $userenv = C4::Context::userenv; my $viewbaskets = C4::Context->preference('AcqViewBaskets'); my $userbranch = $userenv->{branch}; -my $budgets = GetBudgetHierarchy; +my $budgets = GetBudgetHierarchy; my $has_budgets = 0; -foreach my $r (@{$budgets}) { - next unless (CanUserUseBudget($loggedinuser, $r, $userflags)); +foreach my $r ( @{$budgets} ) { + next unless ( CanUserUseBudget( $loggedinuser, $r, $userflags ) ); $has_budgets = 1; last; @@ -135,40 +138,41 @@ for my $vendor (@suppliers) { my $loop_basket = []; for my $basket ( @{$baskets} ) { - if (CanUserManageBasket($loggedinuser, $basket, $userflags)) { + if ( CanUserManageBasket( $loggedinuser, $basket, $userflags ) ) { my $patron = Koha::Patrons->find( $basket->{authorisedby} ); foreach (qw(total_items total_biblios expected_items)) { $basket->{$_} ||= 0; } - if ( $patron ) { + if ($patron) { $basket->{authorisedby} = $patron; } - if ($basket->{basketgroupid}) { - my $basketgroup = C4::Acquisition::GetBasketgroup($basket->{basketgroupid}); + if ( $basket->{basketgroupid} ) { + my $basketgroup = C4::Acquisition::GetBasketgroup( $basket->{basketgroupid} ); if ($basketgroup) { $basket->{basketgroup} = $basketgroup; } } - push @{$loop_basket}, $basket; + push @{$loop_basket}, $basket; } } push @{$loop_suppliers}, - { loop_basket => $loop_basket, - booksellerid => $vendor->id, - name => $vendor->name, - active => $vendor->active, - vendor_type => $vendor->type, - basketcount => $vendor->baskets->count, + { + loop_basket => $loop_basket, + booksellerid => $vendor->id, + name => $vendor->name, + active => $vendor->active, + vendor_type => $vendor->type, + basketcount => $vendor->baskets->count, subscriptioncount => $vendor->subscriptions->count, - }; + }; } $template->param( loop_suppliers => $loop_suppliers, supplier => ( $booksellerid || $supplier ), count => $supplier_count, - has_budgets => $has_budgets, + has_budgets => $has_budgets, ); $template->{VARS}->{'allbaskets'} = $allbaskets; diff --git a/acqui/cancelorder.pl b/acqui/cancelorder.pl index 8174270228..be4dbb3b7d 100755 --- a/acqui/cancelorder.pl +++ b/acqui/cancelorder.pl @@ -32,18 +32,20 @@ and add possibility to indicate a reason for cancellation use Modern::Perl; use CGI; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); -use C4::Log qw(logaction); +use C4::Log qw(logaction); use Koha::Acquisition::Baskets; my $input = CGI->new; -my ($template, $loggedinuser, $cookie, $flags) = get_template_and_user( { - template_name => 'acqui/cancelorder.tt', - query => $input, - type => 'intranet', - flagsrequired => { 'acquisition' => 'order_manage' }, -} ); +my ( $template, $loggedinuser, $cookie, $flags ) = get_template_and_user( + { + template_name => 'acqui/cancelorder.tt', + query => $input, + type => 'intranet', + flagsrequired => { 'acquisition' => 'order_manage' }, + } +); my $op = $input->param('op') || q{}; my $ordernumber = $input->param('ordernumber'); @@ -54,17 +56,17 @@ my $basket = Koha::Acquisition::Baskets->find( { basketno => $basketno }, my $referrer = $input->param('referrer') || $input->referer; my $delete_biblio = $input->param('del_biblio') ? 1 : 0; -if( $op eq "cud-confirmcancel" ) { +if ( $op eq "cud-confirmcancel" ) { my $reason = $input->param('reason'); my @messages; - if( !$order ) { - push @messages, Koha::Object::Message->new({ message => 'error_order_not_found', type => 'error' }); + if ( !$order ) { + push @messages, Koha::Object::Message->new( { message => 'error_order_not_found', type => 'error' } ); $template->param( error_order_not_found => 1 ); - } elsif( $order->datecancellationprinted ) { - push @messages, Koha::Object::Message->new({ message => 'error_order_already_cancelled', type => 'error' }); + } elsif ( $order->datecancellationprinted ) { + push @messages, Koha::Object::Message->new( { message => 'error_order_already_cancelled', type => 'error' } ); $template->param( error_order_already_cancelled => 1 ); } else { - $order->cancel({ reason => $reason, delete_biblio => $delete_biblio }); + $order->cancel( { reason => $reason, delete_biblio => $delete_biblio } ); @messages = @{ $order->object_messages }; } @@ -74,21 +76,22 @@ if( $op eq "cud-confirmcancel" ) { $template->param( error_delbiblio => 1 ) if $messages[0]->message eq 'error_delbiblio'; } else { + # Log the cancellation of the order - if (C4::Context->preference("AcquisitionLog")) { - logaction('ACQUISITIONS', 'CANCEL_ORDER', $ordernumber); + if ( C4::Context->preference("AcquisitionLog") ) { + logaction( 'ACQUISITIONS', 'CANCEL_ORDER', $ordernumber ); } - $template->param(success_cancelorder => 1); + $template->param( success_cancelorder => 1 ); } - $template->param(confirmcancel => 1); + $template->param( confirmcancel => 1 ); } $template->param( - ordernumber => $ordernumber, + ordernumber => $ordernumber, biblionumber => $biblionumber, - basket => $basket, - referrer => $referrer, - del_biblio => $delete_biblio, + basket => $basket, + referrer => $referrer, + del_biblio => $delete_biblio, ); output_html_with_http_headers $input, $cookie, $template->output; diff --git a/acqui/check_budget_total.pl b/acqui/check_budget_total.pl index 46379fa005..81583c0e4b 100755 --- a/acqui/check_budget_total.pl +++ b/acqui/check_budget_total.pl @@ -20,8 +20,8 @@ use Modern::Perl; use CGI qw ( -utf8 ); use C4::Context; -use C4::Output qw( output_html_with_http_headers ); -use C4::Auth qw( get_template_and_user ); +use C4::Output qw( output_html_with_http_headers ); +use C4::Auth qw( get_template_and_user ); use C4::Budgets qw( GetBudget ); =head1 DESCRIPTION @@ -30,19 +30,21 @@ fetches the budget amount fron the DB =cut -my $input = CGI->new; +my $input = CGI->new; my $budget_id = $input->param('budget_id'); -my $total = $input->param('total'); +my $total = $input->param('total'); my ( $template, $loggedinuser, $cookie ) = get_template_and_user( - { template_name => "acqui/ajax.tt", - query => $input, - type => "intranet", -} ); + { + template_name => "acqui/ajax.tt", + query => $input, + type => "intranet", + } +); my $budget = GetBudget($budget_id); -$template->param( return => $budget->{'budget_amount'} ); +$template->param( return => $budget->{'budget_amount'} ); output_html_with_http_headers $input, $cookie, $template->output; 1; diff --git a/acqui/check_uniqueness.pl b/acqui/check_uniqueness.pl index aece6aac55..66c8e7f7f2 100755 --- a/acqui/check_uniqueness.pl +++ b/acqui/check_uniqueness.pl @@ -31,10 +31,10 @@ use Modern::Perl; -use CGI qw ( -utf8 ); -use JSON qw( to_json ); +use CGI qw ( -utf8 ); +use JSON qw( to_json ); use C4::Output qw( output_with_http_headers ); -use C4::Items qw( SearchItems ); +use C4::Items qw( SearchItems ); use C4::Auth qw( check_cookie_auth ); my $input = CGI->new; @@ -50,11 +50,11 @@ my @value = $input->multi_param('value[]'); my $r = {}; my $i = 0; -for ( my $i=0; $i<@field; $i++ ) { - my ($items) = C4::Items::SearchItems({ field => $field[$i], query => $value[$i]}); +for ( my $i = 0 ; $i < @field ; $i++ ) { + my ($items) = C4::Items::SearchItems( { field => $field[$i], query => $value[$i] } ); - if ( @$items ) { - push @{ $r->{$field[$i]} }, $value[$i]; + if (@$items) { + push @{ $r->{ $field[$i] } }, $value[$i]; } } diff --git a/acqui/duplicate_orders.pl b/acqui/duplicate_orders.pl index 05b6b28628..3b065153aa 100755 --- a/acqui/duplicate_orders.pl +++ b/acqui/duplicate_orders.pl @@ -21,10 +21,10 @@ use Modern::Perl; use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); -use C4::Output qw( output_and_exit output_html_with_http_headers ); +use C4::Auth qw( get_template_and_user ); +use C4::Output qw( output_and_exit output_html_with_http_headers ); use C4::Acquisition qw( GetHistory ); -use C4::Budgets qw( GetBudgetHierarchy GetBudget CanUserUseBudget GetBudgetPeriods GetBudgetPeriod ); +use C4::Budgets qw( GetBudgetHierarchy GetBudget CanUserUseBudget GetBudgetPeriods GetBudgetPeriod ); use Koha::Acquisition::Baskets; use Koha::Acquisition::Currencies; use Koha::Acquisition::Orders; @@ -36,17 +36,17 @@ my $op = $input->param('op') || 'search'; # search, select, batch_edit my ( $template, $loggedinuser, $cookie, $userflags ) = get_template_and_user( { - template_name => "acqui/duplicate_orders.tt", - query => $input, - type => "intranet", - flagsrequired => { acquisition => 'order_manage' }, + template_name => "acqui/duplicate_orders.tt", + query => $input, + type => "intranet", + flagsrequired => { acquisition => 'order_manage' }, } ); my $basket = Koha::Acquisition::Baskets->find($basketno); output_and_exit( $input, $cookie, $template, 'unknown_basket' ) - unless $basket; + unless $basket; my $vendor = $basket->bookseller; my $patron = Koha::Patrons->find($loggedinuser)->unblessed; @@ -64,22 +64,23 @@ my $filters = { orderstatus => scalar $input->param('orderstatus'), ordernumber => scalar $input->param('ordernumber'), search_children_too => scalar $input->param('search_children_too'), - created_by => [$input->multi_param('created_by')] + created_by => [ $input->multi_param('created_by') ] }; my $from_placed_on = - eval { dt_from_string( scalar $input->param('from') ) } || dt_from_string; + eval { dt_from_string( scalar $input->param('from') ) } || dt_from_string; my $to_placed_on = - eval { dt_from_string( scalar $input->param('to') ) } || dt_from_string; + eval { dt_from_string( scalar $input->param('to') ) } || dt_from_string; unless ( $input->param('from') ) { + # Fill the form with year-1 $from_placed_on->set_time_zone('floating')->subtract( years => 1 ); } $filters->{from_placed_on} = $from_placed_on; $filters->{to_placed_on} = $to_placed_on; - my ( @result_order_loop, @selected_order_loop ); +my ( @result_order_loop, @selected_order_loop ); my @ordernumbers = split ',', scalar $input->param('ordernumbers') || ''; if ( $op eq 'select' ) { @@ -90,15 +91,14 @@ if ( $op eq 'select' ) { @result_order_loop = map { my $order = $_; - ( grep {$_ eq $order->{ordernumber}} @ordernumbers ) ? () : $order + ( grep { $_ eq $order->{ordernumber} } @ordernumbers ) ? () : $order } @{ C4::Acquisition::GetHistory(%$filters) }; @selected_order_loop = - scalar @ordernumbers - ? @{ C4::Acquisition::GetHistory( ordernumbers => \@ordernumbers ) } - : (); -} -elsif ( $op eq 'cud-batch_edit' ) { + scalar @ordernumbers + ? @{ C4::Acquisition::GetHistory( ordernumbers => \@ordernumbers ) } + : (); +} elsif ( $op eq 'cud-batch_edit' ) { @ordernumbers = $input->multi_param('ordernumber'); # build budget list @@ -106,33 +106,30 @@ elsif ( $op eq 'cud-batch_edit' ) { my $budgets_hierarchy = GetBudgetHierarchy; foreach my $r ( @{$budgets_hierarchy} ) { next - unless ( C4::Budgets::CanUserUseBudget( $patron, $r, $userflags ) ); + unless ( C4::Budgets::CanUserUseBudget( $patron, $r, $userflags ) ); push @{$budget_loop}, - { + { b_id => $r->{budget_id}, b_txt => $r->{budget_name}, b_code => $r->{budget_code}, b_sort1_authcat => $r->{'sort1_authcat'}, b_sort2_authcat => $r->{'sort2_authcat'}, b_active => $r->{budget_period_active}, - }; + }; } @{$budget_loop} = - sort { uc( $a->{b_txt} ) cmp uc( $b->{b_txt} ) } @{$budget_loop}; + sort { uc( $a->{b_txt} ) cmp uc( $b->{b_txt} ) } @{$budget_loop}; $template->param( currencies => Koha::Acquisition::Currencies->search, budget_loop => $budget_loop, ); -} -elsif ( $op eq 'cud-do_duplicate' ) { +} elsif ( $op eq 'cud-do_duplicate' ) { my @fields_to_copy = $input->multi_param('copy_existing_value'); my $default_values; - for my $field ( - qw(currency budget_id order_internalnote order_vendornote sort1 sort2 )) - { + for my $field (qw(currency budget_id order_internalnote order_vendornote sort1 sort2 )) { next if grep { $_ eq $field } @fields_to_copy; $default_values->{$field} = $input->param("all_$field"); } @@ -142,13 +139,11 @@ elsif ( $op eq 'cud-do_duplicate' ) { for my $ordernumber (@ordernumbers) { my $original_order = Koha::Acquisition::Orders->find($ordernumber); next unless $original_order; - my $new_order = - $original_order->duplicate_to( $basket, $default_values ); + my $new_order = $original_order->duplicate_to( $basket, $default_values ); push @new_ordernumbers, $new_order->ordernumber; } - my $new_orders = - C4::Acquisition::GetHistory( ordernumbers => \@new_ordernumbers ); + my $new_orders = C4::Acquisition::GetHistory( ordernumbers => \@new_ordernumbers ); $template->param( new_orders => $new_orders ); $op = 'duplication_done'; } @@ -159,7 +154,7 @@ for my $bp ( @{$budgetperiods} ) { my $hierarchy = C4::Budgets::GetBudgetHierarchy( $$bp{budget_period_id} ); for my $budget ( @{$hierarchy} ) { $$budget{budget_display_name} = - sprintf( "%s", ">" x $$budget{depth} . $$budget{budget_name} ); + sprintf( "%s", ">" x $$budget{depth} . $$budget{budget_name} ); } $$bp{hierarchy} = $hierarchy; } diff --git a/acqui/edifactmsgs.pl b/acqui/edifactmsgs.pl index 47a1316eb5..aae5404dbd 100755 --- a/acqui/edifactmsgs.pl +++ b/acqui/edifactmsgs.pl @@ -20,7 +20,7 @@ use Modern::Perl; use CGI; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use Koha::Database; use Koha::EDI qw( process_invoice ); @@ -28,10 +28,10 @@ use Koha::EDI qw( process_invoice ); my $q = CGI->new; my ( $template, $loggedinuser, $cookie, $userflags ) = get_template_and_user( { - template_name => 'acqui/edifactmsgs.tt', - query => $q, - type => 'intranet', - flagsrequired => { acquisition => 'edi_manage' }, + template_name => 'acqui/edifactmsgs.tt', + query => $q, + type => 'intranet', + flagsrequired => { acquisition => 'edi_manage' }, } ); @@ -45,7 +45,7 @@ if ( $cmd && $cmd eq 'cud-delete' ) { } if ( $cmd && $cmd eq 'import' ) { - my $id = $q->param('message_id'); + my $id = $q->param('message_id'); my $invoice = $schema->resultset('EdifactMessage')->find($id); process_invoice($invoice); } diff --git a/acqui/edimsg.pl b/acqui/edimsg.pl index 05340d4481..8a49359e31 100755 --- a/acqui/edimsg.pl +++ b/acqui/edimsg.pl @@ -21,16 +21,16 @@ use Modern::Perl; use CGI; use Koha::Database; use C4::Koha; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); my $q = CGI->new; my ( $template, $loggedinuser, $cookie, $userflags ) = get_template_and_user( { - template_name => 'acqui/edimsg.tt', - query => $q, - type => 'intranet', - flagsrequired => { acquisition => 'edi_manage' }, + template_name => 'acqui/edimsg.tt', + query => $q, + type => 'intranet', + flagsrequired => { acquisition => 'edi_manage' }, } ); my $msg_id = $q->param('id'); @@ -42,8 +42,7 @@ if ($msg) { my @segments = segmentize($transmission); $template->param( segments => \@segments ); -} -else { +} else { $template->param( no_message => 1 ); } diff --git a/acqui/finishreceive.pl b/acqui/finishreceive.pl index 8419ac30be..4116ad3b49 100755 --- a/acqui/finishreceive.pl +++ b/acqui/finishreceive.pl @@ -21,15 +21,15 @@ # along with Koha; if not, see . use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Auth qw( checkauth ); -use JSON qw( encode_json ); +use JSON qw( encode_json ); use C4::Output; use C4::Context; use C4::Acquisition qw( GetInvoice GetOrder ModReceiveOrder ); -use C4::Biblio qw( GetFrameworkCode GetMarcFromKohaField TransformHtmlToXml ); -use C4::Items qw( GetMarcItem ModItemFromMarc AddItemFromMarc ); -use C4::Log qw(logaction); +use C4::Biblio qw( GetFrameworkCode GetMarcFromKohaField TransformHtmlToXml ); +use C4::Items qw( GetMarcItem ModItemFromMarc AddItemFromMarc ); +use C4::Log qw(logaction); use C4::Search; use Koha::Number::Price; @@ -45,56 +45,56 @@ if ( $input->request_method ne "POST" ) { my $flagsrequired = { acquisition => 'order_receive' }; -checkauth($input, 0, $flagsrequired, 'intranet'); +checkauth( $input, 0, $flagsrequired, 'intranet' ); -my $user = $input->remote_user; -my $biblionumber = $input->param('biblionumber'); -my $ordernumber = $input->param('ordernumber'); -my $origquantityrec = $input->param('origquantityrec'); -my $quantityrec = $input->param('quantityrec'); -my $quantity = $input->param('quantity'); -my $unitprice = $input->param('unitprice'); -my $replacementprice = $input->param('replacementprice'); -my $datereceived = $input->param('datereceived'); +my $user = $input->remote_user; +my $biblionumber = $input->param('biblionumber'); +my $ordernumber = $input->param('ordernumber'); +my $origquantityrec = $input->param('origquantityrec'); +my $quantityrec = $input->param('quantityrec'); +my $quantity = $input->param('quantity'); +my $unitprice = $input->param('unitprice'); +my $replacementprice = $input->param('replacementprice'); +my $datereceived = $input->param('datereceived'); my $invoice_unitprice = $input->param('invoice_unitprice'); -my $invoice_currency = $input->param('invoice_currency'); -my $invoiceid = $input->param('invoiceid'); -my $invoice = GetInvoice($invoiceid); -my $invoiceno = $invoice->{invoicenumber}; -my $booksellerid = $input->param('booksellerid'); -my $cnt = 0; -my $bookfund = $input->param("bookfund"); -my $suggestion_id = $input->param("suggestionid"); -my $order = GetOrder($ordernumber); -my $new_ordernumber = $ordernumber; +my $invoice_currency = $input->param('invoice_currency'); +my $invoiceid = $input->param('invoiceid'); +my $invoice = GetInvoice($invoiceid); +my $invoiceno = $invoice->{invoicenumber}; +my $booksellerid = $input->param('booksellerid'); +my $cnt = 0; +my $bookfund = $input->param("bookfund"); +my $suggestion_id = $input->param("suggestionid"); +my $order = GetOrder($ordernumber); +my $new_ordernumber = $ordernumber; #bug18723 regression fix -if (C4::Context->preference("CurrencyFormat") eq 'FR') { - if (rindex($unitprice, '.') ge 0) { - substr($unitprice, rindex($unitprice, '.'), 1, ','); +if ( C4::Context->preference("CurrencyFormat") eq 'FR' ) { + if ( rindex( $unitprice, '.' ) ge 0 ) { + substr( $unitprice, rindex( $unitprice, '.' ), 1, ',' ); } - if (rindex($replacementprice,'.') ge 0) { - substr($replacementprice, rindex($replacementprice, '.'), 1, ','); + if ( rindex( $replacementprice, '.' ) ge 0 ) { + substr( $replacementprice, rindex( $replacementprice, '.' ), 1, ',' ); } } -$unitprice = Koha::Number::Price->new( $unitprice )->unformat(); -$replacementprice = Koha::Number::Price->new( $replacementprice )->unformat(); -my $order_obj = Koha::Acquisition::Orders->find( $ordernumber ); -my $basket = $order_obj->basket; +$unitprice = Koha::Number::Price->new($unitprice)->unformat(); +$replacementprice = Koha::Number::Price->new($replacementprice)->unformat(); +my $order_obj = Koha::Acquisition::Orders->find($ordernumber); +my $basket = $order_obj->basket; #need old receivedate if we update the order, parcel.pl only shows the right parcel this way FIXME -if ($quantityrec > $origquantityrec ) { +if ( $quantityrec > $origquantityrec ) { my @received_items = (); - if ($basket->effective_create_items eq 'ordering') { + if ( $basket->effective_create_items eq 'ordering' ) { @received_items = $input->multi_param('items_to_receive[]'); my @affects = split q{\|}, C4::Context->preference("AcqItemSetSubfieldsWhenReceived"); - if ( @affects ) { + if (@affects) { my $frameworkcode = GetFrameworkCode($biblionumber); - my ( $itemfield ) = GetMarcFromKohaField( 'items.itemnumber' ); - for my $in ( @received_items ) { + my ($itemfield) = GetMarcFromKohaField('items.itemnumber'); + for my $in (@received_items) { my $item = C4::Items::GetMarcItem( $biblionumber, $in ); - for my $affect ( @affects ) { + for my $affect (@affects) { my ( $sf, $v ) = split q{=}, $affect, 2; foreach ( $item->field($itemfield) ) { $_->update( $sf => $v ); @@ -116,7 +116,7 @@ if ($quantityrec > $origquantityrec ) { ? ( invoice_unitprice => $invoice_unitprice, invoice_currency => $invoice_currency, - ) + ) : ( invoice_unitprice => undef, invoice_currency => undef, @@ -130,8 +130,9 @@ if ($quantityrec > $origquantityrec ) { # save the quantity received. if ( $quantityrec > 0 ) { if ( $order_obj->subscriptionid ) { + # Quantity can only be modified if linked to a subscription - $order_obj->quantity($quantity); # quantityrec will be deduced from this value in ModReceiveOrder + $order_obj->quantity($quantity); # quantityrec will be deduced from this value in ModReceiveOrder } ( $datereceived, $new_ordernumber ) = ModReceiveOrder( { @@ -148,56 +149,61 @@ if ($quantityrec > $origquantityrec ) { } # now, add items if applicable - if ($basket->effective_create_items eq 'receiving') { + if ( $basket->effective_create_items eq 'receiving' ) { my @tags = $input->multi_param('tag[]'); my @subfields = $input->multi_param('subfield[]'); my @field_values = $input->multi_param('field_value[]'); my @serials = $input->multi_param('serial[]'); my @itemid = $input->multi_param('itemid[]'); + #Rebuilding ALL the data for items into a hash # parting them on $itemid. my %itemhash; my $countdistinct; - my $range=scalar(@itemid); - for (my $i=0; $i<$range; $i++){ - unless ($itemhash{$itemid[$i]}){ - $countdistinct++; + my $range = scalar(@itemid); + for ( my $i = 0 ; $i < $range ; $i++ ) { + unless ( $itemhash{ $itemid[$i] } ) { + $countdistinct++; } - push @{$itemhash{$itemid[$i]}->{'tags'}},$tags[$i]; - push @{$itemhash{$itemid[$i]}->{'subfields'}},$subfields[$i]; - push @{$itemhash{$itemid[$i]}->{'field_values'}},$field_values[$i]; + push @{ $itemhash{ $itemid[$i] }->{'tags'} }, $tags[$i]; + push @{ $itemhash{ $itemid[$i] }->{'subfields'} }, $subfields[$i]; + push @{ $itemhash{ $itemid[$i] }->{'field_values'} }, $field_values[$i]; } - my $new_order = Koha::Acquisition::Orders->find( $new_ordernumber ); - foreach my $item (keys %itemhash){ - my $xml = TransformHtmlToXml( $itemhash{$item}->{'tags'}, - $itemhash{$item}->{'subfields'}, - $itemhash{$item}->{'field_values'}, - undef, - undef, - 'ITEM' ); - my $record=MARC::Record::new_from_xml($xml, 'UTF-8'); - my (undef,$bibitemnum,$itemnumber) = AddItemFromMarc($record,$biblionumber); - $new_order->add_item( $itemnumber ); + my $new_order = Koha::Acquisition::Orders->find($new_ordernumber); + foreach my $item ( keys %itemhash ) { + my $xml = TransformHtmlToXml( + $itemhash{$item}->{'tags'}, + $itemhash{$item}->{'subfields'}, + $itemhash{$item}->{'field_values'}, + undef, + undef, + 'ITEM' + ); + my $record = MARC::Record::new_from_xml( $xml, 'UTF-8' ); + my ( undef, $bibitemnum, $itemnumber ) = AddItemFromMarc( $record, $biblionumber ); + $new_order->add_item($itemnumber); } } } -my $new_order_object = Koha::Acquisition::Orders->find( $new_ordernumber ); # FIXME we should not need to refetch it -my $items = $new_order_object->items; -while ( my $item = $items->next ) { - $item->update({ - booksellerid => $booksellerid, - dateaccessioned => $datereceived, - datelastseen => $datereceived, - price => $unitprice, - replacementprice => $replacementprice, - replacementpricedate => $datereceived, - }); +my $new_order_object = Koha::Acquisition::Orders->find($new_ordernumber); # FIXME we should not need to refetch it +my $items = $new_order_object->items; +while ( my $item = $items->next ) { + $item->update( + { + booksellerid => $booksellerid, + dateaccessioned => $datereceived, + datelastseen => $datereceived, + price => $unitprice, + replacementprice => $replacementprice, + replacementpricedate => $datereceived, + } + ); } if ($suggestion_id) { - my $reason = $input->param("reason") || ''; + my $reason = $input->param("reason") || ''; my $other_reason = $input->param("other_reason"); $reason = $other_reason if $reason eq 'other'; my $suggestion = Koha::Suggestions->find($suggestion_id); @@ -205,7 +211,7 @@ if ($suggestion_id) { } # Log the receipt -if (C4::Context->preference("AcquisitionLog")) { +if ( C4::Context->preference("AcquisitionLog") ) { my $infos = { quantityrec => $quantityrec, bookfund => $bookfund || 'unchanged', @@ -217,7 +223,7 @@ if (C4::Context->preference("AcquisitionLog")) { ? ( invoice_unitprice => $invoice_unitprice, invoice_currency => $invoice_currency, - ) + ) : () ), }; diff --git a/acqui/histsearch.pl b/acqui/histsearch.pl index 571cbeb132..41e187c6ed 100755 --- a/acqui/histsearch.pl +++ b/acqui/histsearch.pl @@ -50,23 +50,23 @@ to filter on ended date. =cut use Modern::Perl; -use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); -use C4::Output qw( output_html_with_http_headers ); +use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); +use C4::Output qw( output_html_with_http_headers ); use C4::Acquisition qw( GetHistory ); use Koha::AdditionalFields; use Koha::DateUtils qw( dt_from_string ); -my $input = CGI->new; -my $do_search = $input->param('do_search') || 0; +my $input = CGI->new; +my $do_search = $input->param('do_search') || 0; my $dbh = C4::Context->dbh; my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "acqui/histsearch.tt", - query => $input, - type => "intranet", - flagsrequired => { acquisition => '*' }, + template_name => "acqui/histsearch.tt", + query => $input, + type => "intranet", + flagsrequired => { acquisition => '*' }, } ); @@ -93,8 +93,9 @@ my $filters = { }; my $from_placed_on = eval { dt_from_string( scalar $input->param('from') ) } || dt_from_string; -my $to_placed_on = eval { dt_from_string( scalar $input->param('to') ) } || dt_from_string; +my $to_placed_on = eval { dt_from_string( scalar $input->param('to') ) } || dt_from_string; unless ( $input->param('from') ) { + # Fill the form with year-1 $from_placed_on->set_time_zone('floating')->subtract( years => 1 ); } @@ -104,10 +105,10 @@ my $additional_fields = Koha::AdditionalFields->search( { tablename => 'aqbasket $template->param( available_additional_fields => $additional_fields ); my @additional_field_filters; while ( my $additional_field = $additional_fields->next ) { - my $value = $input->param('additional_field_' . $additional_field->id); - if (defined $value and $value ne '') { + my $value = $input->param( 'additional_field_' . $additional_field->id ); + if ( defined $value and $value ne '' ) { push @additional_field_filters, { - id => $additional_field->id, + id => $additional_field->id, value => $value, }; } @@ -120,17 +121,18 @@ if ( $filters->{orderstatus} eq "any" ) { } my $order_loop; + # If we're supplied any value then we do a search. Otherwise we don't. if ($do_search) { $order_loop = GetHistory(%$filters); } my $budgetperiods = C4::Budgets::GetBudgetPeriods; -my $bp_loop = $budgetperiods; +my $bp_loop = $budgetperiods; for my $bp ( @{$budgetperiods} ) { my $hierarchy = C4::Budgets::GetBudgetHierarchy( $$bp{budget_period_id}, undef, undef, 1 ); for my $budget ( @{$hierarchy} ) { - $$budget{budget_display_name} = sprintf("%s", ">" x $$budget{depth} . $$budget{budget_name}); + $$budget{budget_display_name} = sprintf( "%s", ">" x $$budget{depth} . $$budget{budget_name} ); } $$bp{hierarchy} = $hierarchy; } diff --git a/acqui/invoice-files.pl b/acqui/invoice-files.pl index a026a00a5d..cf93fc924e 100755 --- a/acqui/invoice-files.pl +++ b/acqui/invoice-files.pl @@ -30,23 +30,23 @@ Manage files associated with invoice use Modern::Perl; use CGI; -use C4::Auth qw( get_template_and_user ); -use C4::Output qw( output_html_with_http_headers ); +use C4::Auth qw( get_template_and_user ); +use C4::Output qw( output_html_with_http_headers ); use C4::Acquisition qw( GetInvoice GetInvoiceDetails ); use Koha::Misc::Files; my $input = CGI->new; my ( $template, $loggedinuser, $cookie, $flags ) = get_template_and_user( { - template_name => 'acqui/invoice-files.tt', - query => $input, - type => 'intranet', - flagsrequired => { 'acquisition' => '*' }, + template_name => 'acqui/invoice-files.tt', + query => $input, + type => 'intranet', + flagsrequired => { 'acquisition' => '*' }, } ); my $invoiceid = $input->param('invoiceid') // ''; -my $op = $input->param('op') // ''; +my $op = $input->param('op') // ''; my %errors; my $mf = Koha::Misc::Files->new( tabletag => 'aqinvoices', recordid => $invoiceid ); @@ -54,15 +54,15 @@ defined($mf) || do { $op = 'none'; $errors{'invalid_parameter'} = 1; }; if ( $op eq 'download' ) { my $file_id = $input->param('file_id'); - my $file = $mf->GetFile( id => $file_id ); + my $file = $mf->GetFile( id => $file_id ); my $fname = $file->{'file_name'}; my $ftype = $file->{'file_type'}; - if ($input->param('view') && ($ftype =~ m|^image/|i || $fname =~ /\.pdf/i)) { - $fname =~ /\.pdf/i && do { $ftype='application/pdf'; }; + if ( $input->param('view') && ( $ftype =~ m|^image/|i || $fname =~ /\.pdf/i ) ) { + $fname =~ /\.pdf/i && do { $ftype = 'application/pdf'; }; print $input->header( - -type => $ftype, - -charset => 'utf-8' + -type => $ftype, + -charset => 'utf-8' ); } else { print $input->header( @@ -72,15 +72,14 @@ if ( $op eq 'download' ) { ); } print $file->{'file_content'}; -} -else { +} else { my $details = GetInvoiceDetails($invoiceid); $template->param( - invoiceid => $details->{'invoiceid'}, - invoicenumber => $details->{'invoicenumber'}, - suppliername => $details->{'suppliername'}, - booksellerid => $details->{'booksellerid'}, - datereceived => $details->{'datereceived'}, + invoiceid => $details->{'invoiceid'}, + invoicenumber => $details->{'invoicenumber'}, + suppliername => $details->{'suppliername'}, + booksellerid => $details->{'booksellerid'}, + datereceived => $details->{'datereceived'}, ); if ( $op eq 'cud-upload' ) { @@ -93,18 +92,17 @@ else { $errors{'empty_upload'} = 1 if ( -z $uploaded_file ); unless (%errors) { my $file_content = do { local $/; <$uploaded_file>; }; - if ($mimetype =~ /^application\/(force-download|unknown)$/i && $filename =~ /\.pdf$/i) { + if ( $mimetype =~ /^application\/(force-download|unknown)$/i && $filename =~ /\.pdf$/i ) { $mimetype = 'application/pdf'; } $mf->AddFile( - name => $filename, - type => $mimetype, - content => $file_content, + name => $filename, + type => $mimetype, + content => $file_content, description => scalar $input->param('description') ); } - } - else { + } else { $errors{'no_file'} = 1; } } elsif ( $op eq 'cud-delete' ) { @@ -112,7 +110,7 @@ else { } $template->param( - files => (defined($mf)? $mf->GetFilesInfo(): undef), + files => ( defined($mf) ? $mf->GetFilesInfo() : undef ), errors => \%errors ); output_html_with_http_headers $input, $cookie, $template->output; diff --git a/acqui/invoice.pl b/acqui/invoice.pl index 3b5a647b8b..29216d5a22 100755 --- a/acqui/invoice.pl +++ b/acqui/invoice.pl @@ -28,13 +28,14 @@ Invoice details use Modern::Perl; -use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_and_exit output_html_with_http_headers ); -use C4::Acquisition qw( CloseInvoice ReopenInvoice ModInvoice MergeInvoices DelInvoice GetInvoice GetInvoiceDetails get_rounded_price ); +use C4::Acquisition + qw( CloseInvoice ReopenInvoice ModInvoice MergeInvoices DelInvoice GetInvoice GetInvoiceDetails get_rounded_price ); use C4::Budgets qw( GetBudgetHierarchy GetBudget CanUserUseBudget ); -use JSON qw( encode_json ); -use C4::Log qw(logaction); +use JSON qw( encode_json ); +use C4::Log qw(logaction); use Koha::Acquisition::Booksellers; use Koha::Acquisition::Currencies qw( get_active ); @@ -47,35 +48,34 @@ use Koha::Acquisition::Invoices; my $input = CGI->new; my ( $template, $loggedinuser, $cookie, $flags ) = get_template_and_user( { - template_name => 'acqui/invoice.tt', - query => $input, - type => 'intranet', - flagsrequired => { 'acquisition' => '*' }, + template_name => 'acqui/invoice.tt', + query => $input, + type => 'intranet', + flagsrequired => { 'acquisition' => '*' }, } ); -my $logged_in_patron = Koha::Patrons->find( $loggedinuser ); -my $invoiceid = $input->param('invoiceid'); -my $op = $input->param('op'); +my $logged_in_patron = Koha::Patrons->find($loggedinuser); +my $invoiceid = $input->param('invoiceid'); +my $op = $input->param('op'); output_and_exit( $input, $cookie, $template, 'insufficient_permission' ) - if $op - && ! $logged_in_patron->has_permission( { acquisition => 'edit_invoices' } ) - && ! $logged_in_patron->has_permission( { acquisition => 'reopen_closed_invoices' } ) - && ! $logged_in_patron->has_permission( { acquisition => 'merge_invoices' } ) - && ! $logged_in_patron->has_permission( { acquisition => 'delete_invoices' } ); + if $op + && !$logged_in_patron->has_permission( { acquisition => 'edit_invoices' } ) + && !$logged_in_patron->has_permission( { acquisition => 'reopen_closed_invoices' } ) + && !$logged_in_patron->has_permission( { acquisition => 'merge_invoices' } ) + && !$logged_in_patron->has_permission( { acquisition => 'delete_invoices' } ); my $invoice_files; if ( C4::Context->preference('AcqEnableFiles') ) { - $invoice_files = Koha::Misc::Files->new( - tabletag => 'aqinvoices', recordid => $invoiceid ); + $invoice_files = Koha::Misc::Files->new( tabletag => 'aqinvoices', recordid => $invoiceid ); } if ( $op && $op eq 'cud-close' ) { output_and_exit( $input, $cookie, $template, 'insufficient_permission' ) unless $logged_in_patron->has_permission( { acquisition => 'edit_invoices' } ); my @invoiceid = split( ',', scalar $input->param('invoiceid') ); - foreach my $invoiceid ( @invoiceid ) { + foreach my $invoiceid (@invoiceid) { CloseInvoice($invoiceid); } my $referer = $input->param('referer'); @@ -83,12 +83,11 @@ if ( $op && $op eq 'cud-close' ) { print $input->redirect($referer); exit 0; } -} -elsif ( $op && $op eq 'cud-reopen' ) { +} elsif ( $op && $op eq 'cud-reopen' ) { output_and_exit( $input, $cookie, $template, 'insufficient_permission' ) unless $logged_in_patron->has_permission( { acquisition => 'reopen_closed_invoices' } ); my @invoiceid = split( ',', scalar $input->param('invoiceid') ); - foreach my $invoiceid ( @invoiceid ) { + foreach my $invoiceid (@invoiceid) { ReopenInvoice($invoiceid); } my $referer = $input->param('referer'); @@ -96,8 +95,7 @@ elsif ( $op && $op eq 'cud-reopen' ) { print $input->redirect($referer); exit 0; } -} -elsif ( $op && $op eq 'cud-mod' ) { +} elsif ( $op && $op eq 'cud-mod' ) { my $shipmentcost = $input->param('shipmentcost'); my $shipment_budget_id = $input->param('shipment_budget_id'); my $invoicenumber = $input->param('invoicenumber'); @@ -109,32 +107,31 @@ elsif ( $op && $op eq 'cud-mod' ) { shipmentcost => $shipmentcost, shipmentcost_budgetid => $shipment_budget_id ); - if ($input->param('reopen')) { + if ( $input->param('reopen') ) { ReopenInvoice($invoiceid) if $logged_in_patron->has_permission( { acquisition => 'reopen_closed_invoices' } ); - } elsif ($input->param('close')) { + } elsif ( $input->param('close') ) { output_and_exit( $input, $cookie, $template, 'insufficient_permission' ) unless $logged_in_patron->has_permission( { acquisition => 'edit_invoices' } ); CloseInvoice($invoiceid); - } elsif ($input->param('merge')) { + } elsif ( $input->param('merge') ) { output_and_exit( $input, $cookie, $template, 'insufficient_permission' ) unless $logged_in_patron->has_permission( { acquisition => 'merge_invoices' } ); my @sources = $input->multi_param('merge'); - MergeInvoices($invoiceid, \@sources); + MergeInvoices( $invoiceid, \@sources ); defined($invoice_files) && $invoice_files->MergeFileRecIds(@sources); } my @additional_fields = Koha::Acquisition::Invoices->find($invoiceid)->prepare_cgi_additional_field_values( $input, 'aqinvoices' ); - Koha::Acquisition::Invoices->find($invoiceid)->set_additional_fields(\@additional_fields); + Koha::Acquisition::Invoices->find($invoiceid)->set_additional_fields( \@additional_fields ); $template->param( modified => 1 ); -} -elsif ( $op && $op eq 'cud-delete' ) { +} elsif ( $op && $op eq 'cud-delete' ) { output_and_exit( $input, $cookie, $template, 'insufficient_permission' ) unless $logged_in_patron->has_permission( { acquisition => 'delete_invoices' } ); @@ -146,16 +143,15 @@ elsif ( $op && $op eq 'cud-delete' ) { print $input->redirect($referer); exit 0; } -} -elsif ( $op && $op eq 'cud-del_adj' ) { +} elsif ( $op && $op eq 'cud-del_adj' ) { output_and_exit( $input, $cookie, $template, 'insufficient_permission' ) unless $logged_in_patron->has_permission( { acquisition => 'edit_invoices' } ); - my $adjustment_id = $input->param('adjustment_id'); - my $del_adj = Koha::Acquisition::Invoice::Adjustments->find( $adjustment_id ); + my $adjustment_id = $input->param('adjustment_id'); + my $del_adj = Koha::Acquisition::Invoice::Adjustments->find($adjustment_id); if ($del_adj) { - if (C4::Context->preference("AcquisitionLog")) { + if ( C4::Context->preference("AcquisitionLog") ) { my $infos = { invoiceid => $del_adj->invoiceid, budget_id => $del_adj->budget_id, @@ -172,36 +168,36 @@ elsif ( $op && $op eq 'cud-del_adj' ) { } $del_adj->delete(); } -} -elsif ( $op && $op eq 'cud-mod_adj' ) { +} elsif ( $op && $op eq 'cud-mod_adj' ) { output_and_exit( $input, $cookie, $template, 'insufficient_permission' ) unless $logged_in_patron->has_permission( { acquisition => 'edit_invoices' } ); - my @adjustment_id = $input->multi_param('adjustment_id'); - my @adjustment = $input->multi_param('adjustment'); - my @reason = $input->multi_param('reason'); - my @note = $input->multi_param('note'); - my @budget_id = $input->multi_param('budget_id'); - my @encumber_open = $input->multi_param('encumber_open'); - my %e_open = map { $_ => 1 } @encumber_open; + my @adjustment_id = $input->multi_param('adjustment_id'); + my @adjustment = $input->multi_param('adjustment'); + my @reason = $input->multi_param('reason'); + my @note = $input->multi_param('note'); + my @budget_id = $input->multi_param('budget_id'); + my @encumber_open = $input->multi_param('encumber_open'); + my %e_open = map { $_ => 1 } @encumber_open; - my @keys = ('adjustment', 'reason', 'budget_id', 'encumber_open'); - for( my $i=0; $i < scalar @adjustment; $i++ ){ - if( $adjustment_id[$i] eq 'new' ){ + my @keys = ( 'adjustment', 'reason', 'budget_id', 'encumber_open' ); + for ( my $i = 0 ; $i < scalar @adjustment ; $i++ ) { + if ( $adjustment_id[$i] eq 'new' ) { next unless ( $adjustment[$i] || $reason[$i] ); my $adj = { - invoiceid => $invoiceid, - adjustment => $adjustment[$i], - reason => $reason[$i], - note => $note[$i], - budget_id => $budget_id[$i] || undef, + invoiceid => $invoiceid, + adjustment => $adjustment[$i], + reason => $reason[$i], + note => $note[$i], + budget_id => $budget_id[$i] || undef, encumber_open => defined $e_open{ $adjustment_id[$i] } ? 1 : 0, }; my $new_adj = Koha::Acquisition::Invoice::Adjustment->new($adj); $new_adj->store(); + # Log this addition - if (C4::Context->preference("AcquisitionLog")) { + if ( C4::Context->preference("AcquisitionLog") ) { logaction( 'ACQUISITIONS', 'CREATE_INVOICE_ADJUSTMENT', @@ -209,17 +205,21 @@ elsif ( $op && $op eq 'cud-mod_adj' ) { encode_json($adj) ); } - } - else { + } else { my $old_adj = Koha::Acquisition::Invoice::Adjustments->find( $adjustment_id[$i] ); - unless ( $old_adj->adjustment == $adjustment[$i] && $old_adj->reason eq $reason[$i] && $old_adj->budget_id == $budget_id[$i] && $old_adj->encumber_open == $e_open{$adjustment_id[$i]} && $old_adj->note eq $note[$i] ){ + unless ( $old_adj->adjustment == $adjustment[$i] + && $old_adj->reason eq $reason[$i] + && $old_adj->budget_id == $budget_id[$i] + && $old_adj->encumber_open == $e_open{ $adjustment_id[$i] } + && $old_adj->note eq $note[$i] ) + { # Log this modification - if (C4::Context->preference("AcquisitionLog")) { + if ( C4::Context->preference("AcquisitionLog") ) { my $infos = { adjustment => $adjustment[$i], reason => $reason[$i], budget_id => $budget_id[$i], - encumber_open => $e_open{$adjustment_id[$i]}, + encumber_open => $e_open{ $adjustment_id[$i] }, adjustment_old => $old_adj->adjustment, reason_old => $old_adj->reason, budget_id_old => $old_adj->budget_id, @@ -237,7 +237,7 @@ elsif ( $op && $op eq 'cud-mod_adj' ) { $old_adj->reason( $reason[$i] ); $old_adj->note( $note[$i] ); $old_adj->budget_id( $budget_id[$i] || undef ); - $old_adj->encumber_open( $e_open{$adjustment_id[$i]} ? 1 : 0 ); + $old_adj->encumber_open( $e_open{ $adjustment_id[$i] } ? 1 : 0 ); $old_adj->update(); } } @@ -245,43 +245,44 @@ elsif ( $op && $op eq 'cud-mod_adj' ) { } my $active_currency = Koha::Acquisition::Currencies->get_active, -my $details = GetInvoiceDetails($invoiceid); -my $bookseller = Koha::Acquisition::Booksellers->find( $details->{booksellerid} ); + my $details = GetInvoiceDetails($invoiceid); +my $bookseller = Koha::Acquisition::Booksellers->find( $details->{booksellerid} ); my @orders_loop = (); -my $orders = $details->{'orders'}; +my $orders = $details->{'orders'}; my @foot_loop; my %foot; -my $shipmentcost = $details->{shipmentcost} || 0; -my $total_quantity = 0; +my $shipmentcost = $details->{shipmentcost} || 0; +my $total_quantity = 0; my $total_tax_excluded = 0; my $total_tax_included = 0; -my $total_tax_value = 0; +my $total_tax_value = 0; my $has_invoice_unitprice; -foreach my $order (@$orders) { - my $line = get_infos( $order, $bookseller); - $line->{total_tax_excluded} = get_rounded_price($line->{unitprice_tax_excluded}) * $line->{quantity}; - $line->{total_tax_included} = get_rounded_price($line->{unitprice_tax_included}) * $line->{quantity}; +foreach my $order (@$orders) { + my $line = get_infos( $order, $bookseller ); + + $line->{total_tax_excluded} = get_rounded_price( $line->{unitprice_tax_excluded} ) * $line->{quantity}; + $line->{total_tax_included} = get_rounded_price( $line->{unitprice_tax_included} ) * $line->{quantity}; $line->{tax_value} = $line->{tax_value_on_receiving}; - $line->{tax_rate} = $line->{tax_rate_on_receiving}; + $line->{tax_rate} = $line->{tax_rate_on_receiving}; - $foot{$$line{tax_rate}}{tax_rate} = $$line{tax_rate}; - $foot{$$line{tax_rate}}{tax_value} += get_rounded_price($$line{tax_value}); - $total_tax_value += $$line{tax_value}; - $foot{$$line{tax_rate}}{quantity} += $$line{quantity}; - $total_quantity += $$line{quantity}; - $foot{$$line{tax_rate}}{total_tax_excluded} += get_rounded_price($$line{total_tax_excluded}); - $total_tax_excluded += get_rounded_price($$line{total_tax_excluded}); - $foot{$$line{tax_rate}}{total_tax_included} += get_rounded_price($$line{total_tax_included}); - $total_tax_included += get_rounded_price($$line{total_tax_included}); + $foot{ $$line{tax_rate} }{tax_rate} = $$line{tax_rate}; + $foot{ $$line{tax_rate} }{tax_value} += get_rounded_price( $$line{tax_value} ); + $total_tax_value += $$line{tax_value}; + $foot{ $$line{tax_rate} }{quantity} += $$line{quantity}; + $total_quantity += $$line{quantity}; + $foot{ $$line{tax_rate} }{total_tax_excluded} += get_rounded_price( $$line{total_tax_excluded} ); + $total_tax_excluded += get_rounded_price( $$line{total_tax_excluded} ); + $foot{ $$line{tax_rate} }{total_tax_included} += get_rounded_price( $$line{total_tax_included} ); + $total_tax_included += get_rounded_price( $$line{total_tax_included} ); $line->{orderline} = $line->{parent_ordernumber}; $has_invoice_unitprice = 1 if $line->{invoice_currency} ne $active_currency->currency; push @orders_loop, $line; } -push @foot_loop, map {$_} values %foot; +push @foot_loop, map { $_ } values %foot; my $shipmentcost_budgetid = $details->{shipmentcost_budgetid}; @@ -294,26 +295,26 @@ foreach my $r ( @{$budgets} ) { my $selected = $shipmentcost_budgetid ? $r->{budget_id} eq $shipmentcost_budgetid : 0; push @{$budget_loop}, - { - b_id => $r->{budget_id}, - b_txt => $r->{budget_name}, - b_active => $r->{budget_period_active}, - selected => $selected, + { + b_id => $r->{budget_id}, + b_txt => $r->{budget_name}, + b_active => $r->{budget_period_active}, + selected => $selected, b_sort1_authcat => $r->{'sort1_authcat'}, b_sort2_authcat => $r->{'sort2_authcat'}, - }; + }; } @{$budget_loop} = - sort { uc( $a->{b_txt} ) cmp uc( $b->{b_txt} ) } @{$budget_loop}; + sort { uc( $a->{b_txt} ) cmp uc( $b->{b_txt} ) } @{$budget_loop}; -my $adjustments = Koha::Acquisition::Invoice::Adjustments->search({ invoiceid => $details->{'invoiceid'} }); -if ( $adjustments ) { $template->param( adjustments => $adjustments ); } +my $adjustments = Koha::Acquisition::Invoice::Adjustments->search( { invoiceid => $details->{'invoiceid'} } ); +if ($adjustments) { $template->param( adjustments => $adjustments ); } my $invoice = Koha::Acquisition::Invoices->find($invoiceid); $template->param( available_additional_fields => Koha::AdditionalFields->search( { tablename => 'aqinvoices' } ), - additional_field_values => $invoice->get_additional_field_values_for_template, + additional_field_values => $invoice->get_additional_field_values_for_template, ); $template->param( @@ -337,25 +338,25 @@ $template->param( invoiceincgst => $bookseller->invoiceincgst, currency => $active_currency, budgets => $budget_loop, - budget => GetBudget( $shipmentcost_budgetid ), + budget => GetBudget($shipmentcost_budgetid), has_invoice_unitprice => $has_invoice_unitprice, ); -defined( $invoice_files ) && $template->param( files => $invoice_files->GetFilesInfo() ); +defined($invoice_files) && $template->param( files => $invoice_files->GetFilesInfo() ); # FIXME # Fonction dupplicated from basket.pl # Code must to be exported. Where ?? sub get_infos { - my $order = shift; + my $order = shift; my $bookseller = shift; - my $qty = $order->{'quantity'} || 0; + my $qty = $order->{'quantity'} || 0; if ( !defined $order->{quantityreceived} ) { $order->{quantityreceived} = 0; } my $budget = GetBudget( $order->{'budget_id'} ); - my %line = %{ $order }; + my %line = %{$order}; $line{order_received} = ( $qty == $order->{'quantityreceived'} ); $line{budget_name} = $budget->{budget_name}; diff --git a/acqui/invoices.pl b/acqui/invoices.pl index 309060efff..7e04b24ae0 100755 --- a/acqui/invoices.pl +++ b/acqui/invoices.pl @@ -28,12 +28,12 @@ Search for invoices use Modern::Perl; -use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use C4::Acquisition qw( GetInvoices GetInvoice ); -use C4::Budgets qw( GetBudget GetBudgets CanUserUseBudget ); +use C4::Budgets qw( GetBudget GetBudgets CanUserUseBudget ); use Koha::DateUtils qw( dt_from_string ); use Koha::Acquisition::Booksellers; use Koha::AdditionalFields; @@ -41,10 +41,10 @@ use Koha::AdditionalFields; my $input = CGI->new; my ( $template, $loggedinuser, $cookie, $flags ) = get_template_and_user( { - template_name => 'acqui/invoices.tt', - query => $input, - type => 'intranet', - flagsrequired => { 'acquisition' => '*' }, + template_name => 'acqui/invoices.tt', + query => $input, + type => 'intranet', + flagsrequired => { 'acquisition' => '*' }, } ); @@ -64,7 +64,8 @@ my $message_id = $input->param('message_id'); my $op = $input->param('op'); my @additional_fields = Koha::AdditionalFields->search( - { tablename => 'aqinvoices', + { + tablename => 'aqinvoices', searchable => 1 } )->as_list; @@ -73,9 +74,10 @@ for my $field (@additional_fields) { my $value = $input->param( 'additional_field_' . $field->id ); if ( defined $value and $value ne '' ) { push @additional_field_filters, - { id => $field->id, + { + id => $field->id, value => $value, - }; + }; } } @@ -114,12 +116,12 @@ foreach my $budget (@$budgets) { push @budgets_loop, $budget if CanUserUseBudget( $loggedinuser, $budget, $flags ); } -my (@openedinvoices, @closedinvoices); +my ( @openedinvoices, @closedinvoices ); for my $sub ( @{$invoices} ) { unless ( $sub->{closedate} ) { - push @openedinvoices, $sub + push @openedinvoices, $sub; } else { - push @closedinvoices, $sub + push @closedinvoices, $sub; } } diff --git a/acqui/lateorders-export.pl b/acqui/lateorders-export.pl index 207c879e31..0898b01033 100755 --- a/acqui/lateorders-export.pl +++ b/acqui/lateorders-export.pl @@ -19,50 +19,51 @@ use Modern::Perl; use CGI qw ( -utf8 ); use Encode; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Acquisition qw( GetOrder ); use C4::Output; use C4::Context; my $input = CGI->new; -my ($template, $loggedinuser, $cookie) = get_template_and_user({ - template_name => "acqui/csv/lateorders.tt", - query => $input, - type => "intranet", - flagsrequired => {acquisition => 'order_receive'}, -}); +my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "acqui/csv/lateorders.tt", + query => $input, + type => "intranet", + flagsrequired => { acquisition => 'order_receive' }, + } +); my @ordernumbers = $input->multi_param('ordernumber'); my $csv_profile_id = $input->param('csv_profile'); -unless ( $csv_profile_id ) { +unless ($csv_profile_id) { my @orders; - for my $ordernumber ( @ordernumbers ) { - my $order = GetOrder $ordernumber; + for my $ordernumber (@ordernumbers) { + my $order = GetOrder $ordernumber; my $order_object = Koha::Acquisition::Orders->find($ordernumber); - my $claims = $order_object->claims; + my $claims = $order_object->claims; push @orders, { - orderdate => $order->{orderdate}, - latesince => $order->{latesince}, - estimateddeliverydate => $order->{estimated_delivery_date} || $order->{calculateddeliverydate}, - supplier => $order->{supplier}, - supplierid => $order->{supplierid}, - title => $order->{title}, - author => $order->{author}, - publisher => $order->{publisher}, - unitpricesupplier => $order->{unitpricesupplier}, - quantity_to_receive => $order->{quantity_to_receive}, - subtotal => $order->{subtotal}, - budget => $order->{budget}, - basketname => $order->{basketname}, - basketno => $order->{basketno}, - claims_count => $claims->count, - claimed_date => $claims->count ? $claims->last->claimed_on : undef, - internalnote => $order->{order_internalnote}, - vendornote => $order->{order_vendornote}, - isbn => $order->{isbn}, - } - ; + orderdate => $order->{orderdate}, + latesince => $order->{latesince}, + estimateddeliverydate => $order->{estimated_delivery_date} || $order->{calculateddeliverydate}, + supplier => $order->{supplier}, + supplierid => $order->{supplierid}, + title => $order->{title}, + author => $order->{author}, + publisher => $order->{publisher}, + unitpricesupplier => $order->{unitpricesupplier}, + quantity_to_receive => $order->{quantity_to_receive}, + subtotal => $order->{subtotal}, + budget => $order->{budget}, + basketname => $order->{basketname}, + basketno => $order->{basketno}, + claims_count => $claims->count, + claimed_date => $claims->count ? $claims->last->claimed_on : undef, + internalnote => $order->{order_internalnote}, + vendornote => $order->{order_vendornote}, + isbn => $order->{isbn}, + }; } # We want to export using the default profile, using the template acqui/csv/lateorders.tt @@ -77,12 +78,14 @@ unless ( $csv_profile_id ) { exit; } else { my $csv_profile = Koha::CsvProfiles->find($csv_profile_id); - my $content = '[% SET separator = "'.$csv_profile->csv_separator.'" ~%]' . $csv_profile->content; + my $content = '[% SET separator = "' . $csv_profile->csv_separator . '" ~%]' . $csv_profile->content; - my $csv = C4::Letters::_process_tt({ - content => $content, - loops => { aqorders => \@ordernumbers }, - }); + my $csv = C4::Letters::_process_tt( + { + content => $content, + loops => { aqorders => \@ordernumbers }, + } + ); print $input->header( -type => 'text/csv', diff --git a/acqui/lateorders.pl b/acqui/lateorders.pl index 479fe47fa5..eb43a93de1 100755 --- a/acqui/lateorders.pl +++ b/acqui/lateorders.pl @@ -1,6 +1,5 @@ #!/usr/bin/perl - # Copyright 2005 Biblibre # This file is part of Koha. # @@ -44,22 +43,22 @@ To know on which branch this script have to display late order. =cut use Modern::Perl; -use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use C4::Context; -use C4::Letters qw( SendAlerts GetLetters ); +use C4::Letters qw( SendAlerts GetLetters ); use Koha::DateUtils qw( dt_from_string ); use Koha::Acquisition::Orders; use Koha::CsvProfiles; my $input = CGI->new; -my ($template, $loggedinuser, $cookie) = get_template_and_user( +my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "acqui/lateorders.tt", - query => $input, - type => "intranet", - flagsrequired => { acquisition => 'order_receive' }, + template_name => "acqui/lateorders.tt", + query => $input, + type => "intranet", + flagsrequired => { acquisition => 'order_receive' }, } ); @@ -72,19 +71,19 @@ my $estimateddeliverydateto = $input->param('estimateddeliverydateto'); # Get the "date to" param. If it is not defined and $delay is not defined too, it is the today's date. $estimateddeliverydateto ||= - ( not defined $delay and not defined $estimateddeliverydatefrom ) - ? dt_from_string() - : undef; + ( not defined $delay and not defined $estimateddeliverydatefrom ) + ? dt_from_string() + : undef; -my $branch = $input->param('branch'); -my $op = $input->param('op'); +my $branch = $input->param('branch'); +my $op = $input->param('op'); my @errors = (); if ( $delay and not $delay =~ /^\d{1,3}$/ ) { - push @errors, {delay_digits => 1, bad_delay => $delay}; + push @errors, { delay_digits => 1, bad_delay => $delay }; } -if ($op and $op eq "cud-send_alert"){ +if ( $op and $op eq "cud-send_alert" ) { my @ordernums = $input->multi_param("ordernumber"); my $err; eval { @@ -96,10 +95,10 @@ if ($op and $op eq "cud-send_alert"){ if ( ref $err and exists $err->{error} and $err->{error} eq "no_email" ) { $template->{VARS}->{'error_claim'} = "no_email"; - } elsif ( ref $err and exists $err->{error} and $err->{error} eq "no_order_selected"){ + } elsif ( ref $err and exists $err->{error} and $err->{error} eq "no_order_selected" ) { $template->{VARS}->{'error_claim'} = "no_order_selected"; } elsif ( $@ or ref $err and exists $err->{error} ) { - $template->param(error_claim => $@ || $err->{error}); + $template->param( error_claim => $@ || $err->{error} ); } else { $template->{VARS}->{'info_claim'} = 1; } @@ -107,15 +106,15 @@ if ($op and $op eq "cud-send_alert"){ my @lateorders = Koha::Acquisition::Orders->filter_by_lates( { - delay => $delay, + delay => $delay, ( $estimateddeliverydatefrom - ? ( estimated_from => dt_from_string($estimateddeliverydatefrom, 'iso') ) + ? ( estimated_from => dt_from_string( $estimateddeliverydatefrom, 'iso' ) ) : () ), ( $estimateddeliverydateto - ? ( estimated_to => dt_from_string($estimateddeliverydateto, 'iso') ) + ? ( estimated_to => dt_from_string( $estimateddeliverydateto, 'iso' ) ) : () ) }, @@ -123,26 +122,24 @@ my @lateorders = Koha::Acquisition::Orders->filter_by_lates( my $booksellers = Koha::Acquisition::Booksellers->search( { - id => { - -in => [ map { $_->basket->booksellerid } @lateorders ] - }, + id => { -in => [ map { $_->basket->booksellerid } @lateorders ] }, } ); @lateorders = grep { $_->basket->booksellerid eq $booksellerid } @lateorders if $booksellerid; -my $letters = GetLetters({ module => "claimacquisition" }); +my $letters = GetLetters( { module => "claimacquisition" } ); -$template->param(ERROR_LOOP => \@errors) if (@errors); +$template->param( ERROR_LOOP => \@errors ) if (@errors); $template->param( - lateorders => \@lateorders, - booksellers => $booksellers, - bookseller_filter => ( $booksellerid ? $booksellers->find($booksellerid) : undef), - delay => $delay, - letters => $letters, + lateorders => \@lateorders, + booksellers => $booksellers, + bookseller_filter => ( $booksellerid ? $booksellers->find($booksellerid) : undef ), + delay => $delay, + letters => $letters, estimateddeliverydatefrom => $estimateddeliverydatefrom, estimateddeliverydateto => $estimateddeliverydateto, - intranetcolorstylesheet => C4::Context->preference("intranetcolorstylesheet"), - csv_profiles => Koha::CsvProfiles->search({ type => 'sql', used_for => 'late_orders' }), + intranetcolorstylesheet => C4::Context->preference("intranetcolorstylesheet"), + csv_profiles => Koha::CsvProfiles->search( { type => 'sql', used_for => 'late_orders' } ), ); output_html_with_http_headers $input, $cookie, $template->output; diff --git a/acqui/moddeliverydate.pl b/acqui/moddeliverydate.pl index f90cfb552e..55f80c08ec 100755 --- a/acqui/moddeliverydate.pl +++ b/acqui/moddeliverydate.pl @@ -30,53 +30,52 @@ its basket is closed. use Modern::Perl; -use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); -use C4::Output qw( output_html_with_http_headers ); +use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); +use C4::Output qw( output_html_with_http_headers ); use C4::Acquisition qw( GetOrder GetBasket ModOrder ); use Koha::Acquisition::Booksellers; use Koha::DateUtils qw( dt_from_string ); my $input = CGI->new; -my ($template, $loggedinuser, $cookie, $flags) = get_template_and_user( { - template_name => 'acqui/moddeliverydate.tt', - query => $input, - type => 'intranet', - flagsrequired => { 'acquisition' => 'order_manage' }, -} ); +my ( $template, $loggedinuser, $cookie, $flags ) = get_template_and_user( + { + template_name => 'acqui/moddeliverydate.tt', + query => $input, + type => 'intranet', + flagsrequired => { 'acquisition' => 'order_manage' }, + } +); -my $op = $input->param('op'); +my $op = $input->param('op'); my $ordernumber = $input->param('ordernumber'); -my $referrer = $input->param('referrer') || $input->referer(); -my $order = GetOrder($ordernumber); -my $basket = GetBasket($order->{basketno}); -my $bookseller = Koha::Acquisition::Booksellers->find( $basket->{booksellerid} ); +my $referrer = $input->param('referrer') || $input->referer(); +my $order = GetOrder($ordernumber); +my $basket = GetBasket( $order->{basketno} ); +my $bookseller = Koha::Acquisition::Booksellers->find( $basket->{booksellerid} ); -if($op and $op eq 'cud-save') { +if ( $op and $op eq 'cud-save' ) { my $estimated_delivery_date = $input->param('estimated_delivery_date'); - $order->{'estimated_delivery_date'} = $estimated_delivery_date ? dt_from_string( $estimated_delivery_date ) : undef; + $order->{'estimated_delivery_date'} = $estimated_delivery_date ? dt_from_string($estimated_delivery_date) : undef; ModOrder($order); print $input->redirect($referrer); exit; } else { - $template->param( - estimated_delivery_date => $order->{'estimated_delivery_date'} - ); + $template->param( estimated_delivery_date => $order->{'estimated_delivery_date'} ); } -if($op) { - $template->param($op => 1); +if ($op) { + $template->param( $op => 1 ); } $template->param( - basketname => $basket->{'basketname'}, - basketno => $order->{basketno}, - booksellerid => $bookseller->id, - booksellername => $bookseller->name, - ordernumber => $ordernumber, - referrer => $referrer, + basketname => $basket->{'basketname'}, + basketno => $order->{basketno}, + booksellerid => $bookseller->id, + booksellername => $bookseller->name, + ordernumber => $ordernumber, + referrer => $referrer, ); - output_html_with_http_headers $input, $cookie, $template->output; diff --git a/acqui/modordernotes.pl b/acqui/modordernotes.pl index eabfa123f1..0c6ead9044 100755 --- a/acqui/modordernotes.pl +++ b/acqui/modordernotes.pl @@ -28,33 +28,34 @@ Modify just notes when basket is closed. use Modern::Perl; -use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); -use C4::Output qw( output_html_with_http_headers ); +use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); +use C4::Output qw( output_html_with_http_headers ); use C4::Acquisition qw( GetOrder GetBasket ModOrder ); use Koha::Acquisition::Booksellers; my $input = CGI->new; -my ($template, $loggedinuser, $cookie, $flags) = get_template_and_user( { - template_name => 'acqui/modordernotes.tt', - query => $input, - type => 'intranet', - flagsrequired => { 'acquisition' => '*' }, -} ); +my ( $template, $loggedinuser, $cookie, $flags ) = get_template_and_user( + { + template_name => 'acqui/modordernotes.tt', + query => $input, + type => 'intranet', + flagsrequired => { 'acquisition' => '*' }, + } +); -my $op = $input->param('op'); +my $op = $input->param('op'); my $ordernumber = $input->param('ordernumber'); -my $referrer = $input->param('referrer') || $input->referer(); -my $type = $input->param('type'); -my $order = GetOrder($ordernumber); -my $basket = GetBasket($order->{basketno}); -my $bookseller = Koha::Acquisition::Booksellers->find( $basket->{booksellerid} ); +my $referrer = $input->param('referrer') || $input->referer(); +my $type = $input->param('type'); +my $order = GetOrder($ordernumber); +my $basket = GetBasket( $order->{basketno} ); +my $bookseller = Koha::Acquisition::Booksellers->find( $basket->{booksellerid} ); - -if($op and $op eq 'cud-save') { +if ( $op and $op eq 'cud-save' ) { my $ordernotes = $input->param('ordernotes'); - if ($type eq "vendor") { + if ( $type eq "vendor" ) { $order->{'order_vendornote'} = $ordernotes; } else { $order->{'order_internalnote'} = $ordernotes; @@ -63,26 +64,25 @@ if($op and $op eq 'cud-save') { print $input->redirect($referrer); exit; } else { - if ($type eq "vendor") { - $template->param(ordernotes => $order->{'order_vendornote'}); + if ( $type eq "vendor" ) { + $template->param( ordernotes => $order->{'order_vendornote'} ); } else { - $template->param(ordernotes => $order->{'order_internalnote'}); + $template->param( ordernotes => $order->{'order_internalnote'} ); } } -if($op) { - $template->param($op => 1); +if ($op) { + $template->param( $op => 1 ); } $template->param( - basketname => $basket->{'basketname'}, - basketno => $order->{basketno}, - booksellerid => $bookseller->id, - booksellername => $bookseller->name, - ordernumber => $ordernumber, - referrer => $referrer, - type => $type, + basketname => $basket->{'basketname'}, + basketno => $order->{basketno}, + booksellerid => $bookseller->id, + booksellername => $bookseller->name, + ordernumber => $ordernumber, + referrer => $referrer, + type => $type, ); - output_html_with_http_headers $input, $cookie, $template->output; diff --git a/acqui/neworderempty.pl b/acqui/neworderempty.pl index 3937ef89c5..4228db940f 100755 --- a/acqui/neworderempty.pl +++ b/acqui/neworderempty.pl @@ -20,7 +20,6 @@ # You should have received a copy of the GNU General Public License # along with Koha; if not, see . - =head1 NAME neworderempty.pl @@ -68,13 +67,13 @@ use Modern::Perl; use CGI qw ( -utf8 ); use C4::Context; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Budgets qw( GetBudget GetBudgetHierarchy CanUserUseBudget ); use C4::Acquisition qw( GetOrder GetBasket FillWithDefaultValues GetOrderUsers ); -use C4::Contract qw( GetContract ); +use C4::Contract qw( GetContract ); use C4::Suggestions qw( GetSuggestion GetSuggestionInfo ); -use C4::Biblio qw( +use C4::Biblio qw( AddBiblio GetBiblioData GetMarcFromKohaField @@ -126,16 +125,16 @@ my $op = $input->param('op') || q{}; our ( $template, $loggedinuser, $cookie, $userflags ) = get_template_and_user( { - template_name => "acqui/neworderempty.tt", - query => $input, - type => "intranet", - flagsrequired => { acquisition => 'order_manage' }, + template_name => "acqui/neworderempty.tt", + query => $input, + type => "intranet", + flagsrequired => { acquisition => 'order_manage' }, } ); our $marcflavour = C4::Context->preference('marcflavour'); -if(!$basketno) { +if ( !$basketno ) { my $order = GetOrder($ordernumber); $basketno = $order->{'basketno'}; } @@ -146,8 +145,8 @@ $booksellerid = $basket->{booksellerid} unless $booksellerid; my $bookseller = Koha::Acquisition::Booksellers->find($booksellerid); $data = GetOrder($ordernumber) if $ordernumber; -output_and_exit( $input, $cookie, $template, 'unknown_basket') unless $basketobj; -output_and_exit( $input, $cookie, $template, 'unknown_vendor') unless $bookseller; +output_and_exit( $input, $cookie, $template, 'unknown_basket' ) unless $basketobj; +output_and_exit( $input, $cookie, $template, 'unknown_vendor' ) unless $bookseller; $template->param( ordernumber => $ordernumber, @@ -159,52 +158,54 @@ $template->param( output_and_exit( $input, $cookie, $template, 'order_cannot_be_edited' ) if $ordernumber and ( $basketobj->closedate || $data->{orderstatus} eq "complete" ); -my $contract = GetContract({ - contractnumber => $basket->{contractnumber} -}); +my $contract = GetContract( { contractnumber => $basket->{contractnumber} } ); -my $listprice=0; # the price, that can be in MARC record if we have one -if ( $ordernumber eq '' and defined $breedingid ){ -#we want to import from the breeding reservoir (from a z3950 search) - my ($marcrecord, $encoding) = MARCfindbreeding($breedingid); +my $listprice = 0; # the price, that can be in MARC record if we have one +if ( $ordernumber eq '' and defined $breedingid ) { + + #we want to import from the breeding reservoir (from a z3950 search) + my ( $marcrecord, $encoding ) = MARCfindbreeding($breedingid); die("Could not find the selected record in the reservoir, bailing") unless $marcrecord; # Remove all the items (952) from the imported record - foreach my $item ($marcrecord->field('952')) { + foreach my $item ( $marcrecord->field('952') ) { $marcrecord->delete_field($item); } my $duplicatetitle; -#look for duplicates - ($biblionumber,$duplicatetitle) = FindDuplicate($marcrecord); - if($biblionumber && $op ne 'cud-use_external_source') { + + #look for duplicates + ( $biblionumber, $duplicatetitle ) = FindDuplicate($marcrecord); + if ( $biblionumber && $op ne 'cud-use_external_source' ) { + #if duplicate record found and user did not decide yet, first warn user #and let them choose between using a new record or an existing record Load_Duplicate($duplicatetitle); exit; } + #from this point: add a new record - C4::Acquisition::FillWithDefaultValues($marcrecord, {only_mandatory => 1}); + C4::Acquisition::FillWithDefaultValues( $marcrecord, { only_mandatory => 1 } ); my $bibitemnum; ( $biblionumber, $bibitemnum ) = AddBiblio( $marcrecord, $frameworkcode ); + # get the price if there is one. - $listprice = GetMarcPrice($marcrecord, $marcflavour); + $listprice = GetMarcPrice( $marcrecord, $marcflavour ); SetImportRecordStatus( $breedingid, 'imported' ); SetMatchedBiblionumber( $breedingid, $biblionumber ); } - - my ( @order_user_ids, @order_users, @catalog_details ); -our $tagslib = GetMarcStructure(1, 'ACQ', { unsafe => 1 } ); -my ( $itemnumber_tag, $itemnumber_subtag ) = GetMarcFromKohaField( 'items.itemnumber' ); +our $tagslib = GetMarcStructure( 1, 'ACQ', { unsafe => 1 } ); +my ( $itemnumber_tag, $itemnumber_subtag ) = GetMarcFromKohaField('items.itemnumber'); if ( not $ordernumber ) { # create order $new = 'yes'; - if ( $biblionumber ) { + if ($biblionumber) { $data = GetBiblioData($biblionumber); } + # get suggestion fields if applicable. If it's a subscription renewal, then the biblio already exists # otherwise, retrieve suggestion information. elsif ($suggestionid) { @@ -219,52 +220,46 @@ if ( not $ordernumber ) { # create order foreach my $tag ( sort keys %{$tagslib} ) { next if $tag eq ''; next if $tag eq $itemnumber_tag; # skip items fields - my $index_tag = int(rand(1000000)); + my $index_tag = int( rand(1000000) ); foreach my $subfield ( sort keys %{ $tagslib->{$tag} } ) { my $mss = $tagslib->{$tag}{$subfield}; next if IsMarcStructureInternal($mss); next if $mss->{tab} == -1; my $value = $mss->{defaultvalue}; - if ($suggestionid and $mss->{kohafield}) { + if ( $suggestionid and $mss->{kohafield} ) { + # Reading suggestion info if ordering from a suggestion if ( $mss->{kohafield} eq 'biblio.title' ) { $value = $data->{title}; - } - elsif ( $mss->{kohafield} eq 'biblio.author' ) { + } elsif ( $mss->{kohafield} eq 'biblio.author' ) { $value = $data->{author}; - } - elsif ( $mss->{kohafield} eq 'biblioitems.publishercode' ) { + } elsif ( $mss->{kohafield} eq 'biblioitems.publishercode' ) { $value = $data->{publishercode}; - } - elsif ( $mss->{kohafield} eq 'biblioitems.editionstatement' ) { + } elsif ( $mss->{kohafield} eq 'biblioitems.editionstatement' ) { $value = $data->{editionstatement}; - } - elsif ( $mss->{kohafield} eq 'biblioitems.publicationyear' ) { + } elsif ( $mss->{kohafield} eq 'biblioitems.publicationyear' ) { $value = $data->{publicationyear}; - } - elsif ( $mss->{kohafield} eq 'biblioitems.isbn' ) { + } elsif ( $mss->{kohafield} eq 'biblioitems.isbn' ) { $value = $data->{isbn}; - } - elsif ( $mss->{kohafield} eq 'biblio.seriestitle' ) { + } elsif ( $mss->{kohafield} eq 'biblio.seriestitle' ) { $value = $data->{seriestitle}; } } push @catalog_details, $biblio_form_builder->generate_subfield_form( { - tag => $tag, - subfield => $subfield, - value => $value, + tag => $tag, + subfield => $subfield, + value => $value, index_tag => $index_tag, - tagslib => $tagslib, + tagslib => $tagslib, } ); } } } -} -else { #modify order +} else { #modify order $budget_id = $data->{'budget_id'}; $template->param( @@ -276,8 +271,9 @@ else { #modify order @order_user_ids = GetOrderUsers($ordernumber); foreach my $order_user_id (@order_user_ids) { + # FIXME Could be improved with search -in - my $order_patron = Koha::Patrons->find( $order_user_id ); + my $order_patron = Koha::Patrons->find($order_user_id); push @order_users, $order_patron if $order_patron; } } @@ -288,8 +284,8 @@ $biblionumber = $data->{biblionumber}; # - no ordernumber, no biblionumber: from a suggestion, from a new order if ( not $ordernumber or $biblionumber ) { if ( C4::Context->preference('UseACQFrameworkForBiblioRecords') ) { - my $biblio = Koha::Biblios->find($biblionumber); - my $record = $biblio ? $biblio->metadata->record : undef; + my $biblio = Koha::Biblios->find($biblionumber); + my $record = $biblio ? $biblio->metadata->record : undef; my $biblio_form_builder = Koha::UI::Form::Builder::Biblio->new( { biblionumber => $biblionumber, @@ -297,24 +293,25 @@ if ( not $ordernumber or $biblionumber ) { ); foreach my $tag ( sort keys %{$tagslib} ) { next if $tag eq ''; - next if $tag eq $itemnumber_tag; # skip items fields - my @fields = $biblionumber ? $record->field($tag) : (); - my $index_tag = int(rand(1000000)); + next if $tag eq $itemnumber_tag; # skip items fields + my @fields = $biblionumber ? $record->field($tag) : (); + my $index_tag = int( rand(1000000) ); foreach my $subfield ( sort keys %{ $tagslib->{$tag} } ) { my $mss = $tagslib->{$tag}{$subfield}; next if IsMarcStructureInternal($mss); next if $mss->{tab} == -1; + # We only need to display the values - my $value = join '; ', map { $tag < 10 ? $_->data : $_->subfield( $subfield ) } @fields; - if ( $value ) { + my $value = join '; ', map { $tag < 10 ? $_->data : $_->subfield($subfield) } @fields; + if ($value) { push @catalog_details, $biblio_form_builder->generate_subfield_form( { - tag => $tag, - subfield => $subfield, - value => $value, + tag => $tag, + subfield => $subfield, + value => $value, index_tag => $index_tag, - record => $record, - tagslib => $tagslib, + record => $record, + tagslib => $tagslib, } ); } @@ -331,30 +328,31 @@ $suggestion = GetSuggestionInfo($suggestionid) if $suggestionid; my $active_currency = Koha::Acquisition::Currencies->get_active; # build bookfund list -my $patron = Koha::Patrons->find( $loggedinuser )->unblessed; +my $patron = Koha::Patrons->find($loggedinuser)->unblessed; + +my $budget = GetBudget($budget_id); -my $budget = GetBudget($budget_id); # build budget list my $budget_loop = []; -my $budgets = GetBudgetHierarchy; -foreach my $r (@{$budgets}) { - next unless (CanUserUseBudget($patron, $r, $userflags)); +my $budgets = GetBudgetHierarchy; +foreach my $r ( @{$budgets} ) { + next unless ( CanUserUseBudget( $patron, $r, $userflags ) ); push @{$budget_loop}, { - b_id => $r->{budget_id}, - b_txt => $r->{budget_name}, + b_id => $r->{budget_id}, + b_txt => $r->{budget_name}, b_sort1_authcat => $r->{'sort1_authcat'}, b_sort2_authcat => $r->{'sort2_authcat'}, - b_active => $r->{budget_period_active}, - b_sel => ( $r->{budget_id} == $budget_id ) ? 1 : 0, - b_level => $r->{budget_level}, + b_active => $r->{budget_period_active}, + b_sel => ( $r->{budget_id} == $budget_id ) ? 1 : 0, + b_level => $r->{budget_level}, }; } - $template->param( sort1 => $data->{'sort1'} ); $template->param( sort2 => $data->{'sort2'} ); if ( $basketobj->effective_create_items eq 'ordering' ) { + # Check if ACQ framework exists my $marc = GetMarcStructure( 1, 'ACQ', { unsafe => 1 } ); unless ($marc) { @@ -369,33 +367,31 @@ if ( $basketobj->effective_create_items eq 'ordering' ) { my @itemtypes = Koha::ItemTypes->search( {}, { order_by => { -asc => "description" } } )->as_list; if ( defined $from_subscriptionid ) { + # Get the last received order for this subscription my $lastOrderReceived = Koha::Acquisition::Orders->search( { subscriptionid => $from_subscriptionid, datereceived => { '!=' => undef } }, - { - order_by => - [ { -desc => 'datereceived' }, { -desc => 'ordernumber' } ] - } + { order_by => [ { -desc => 'datereceived' }, { -desc => 'ordernumber' } ] } ); if ( $lastOrderReceived->count ) { - $lastOrderReceived = $lastOrderReceived->next->unblessed; # FIXME We should send the object to the template + $lastOrderReceived = $lastOrderReceived->next->unblessed; # FIXME We should send the object to the template $budget_id = $lastOrderReceived->{budgetid}; $data->{listprice} = $lastOrderReceived->{listprice}; $data->{uncertainprice} = $lastOrderReceived->{uncertainprice}; - $data->{tax_rate} = $lastOrderReceived->{tax_rate_on_ordering}; - $data->{discount} = $lastOrderReceived->{discount}; - $data->{rrp} = $lastOrderReceived->{rrp}; - $data->{replacementprice} = $lastOrderReceived->{replacementprice}; - $data->{ecost} = $lastOrderReceived->{ecost}; - $data->{quantity} = $lastOrderReceived->{quantity}; - $data->{unitprice} = $lastOrderReceived->{unitprice}; + $data->{tax_rate} = $lastOrderReceived->{tax_rate_on_ordering}; + $data->{discount} = $lastOrderReceived->{discount}; + $data->{rrp} = $lastOrderReceived->{rrp}; + $data->{replacementprice} = $lastOrderReceived->{replacementprice}; + $data->{ecost} = $lastOrderReceived->{ecost}; + $data->{quantity} = $lastOrderReceived->{quantity}; + $data->{unitprice} = $lastOrderReceived->{unitprice}; $data->{order_internalnote} = $lastOrderReceived->{order_internalnote}; $data->{order_vendornote} = $lastOrderReceived->{order_vendornote}; - $data->{sort1} = $lastOrderReceived->{sort1}; - $data->{sort2} = $lastOrderReceived->{sort2}; + $data->{sort1} = $lastOrderReceived->{sort1}; + $data->{sort2} = $lastOrderReceived->{sort2}; $basket = GetBasket( $input->param('basketno') ); } @@ -408,46 +404,44 @@ if ( defined $from_subscriptionid ) { } # Find the items.barcode subfield for barcode validations -my (undef, $barcode_subfield) = GetMarcFromKohaField( 'items.barcode' ); - +my ( undef, $barcode_subfield ) = GetMarcFromKohaField('items.barcode'); # get option values for TaxRates syspref -my @gst_values = map { - option => $_ + 0.0 -}, split( '\|', C4::Context->preference("TaxRates") ); +my @gst_values = map { option => $_ + 0.0 }, split( '\|', C4::Context->preference("TaxRates") ); -my $quantity = $input->param('rr_quantity_to_order') ? - $input->param('rr_quantity_to_order') : - $data->{'quantity'}; +my $quantity = + $input->param('rr_quantity_to_order') + ? $input->param('rr_quantity_to_order') + : $data->{'quantity'}; $quantity //= 0; # Get additional fields my $record; -my @additional_fields = Koha::AdditionalFields->search({ tablename => 'aqorders' })->as_list; +my @additional_fields = Koha::AdditionalFields->search( { tablename => 'aqorders' } )->as_list; my $additional_field_values; my $items; if ($ordernumber) { my $order = Koha::Acquisition::Orders->find($ordernumber); $additional_field_values = $order->get_additional_field_values_for_template; - $items = $order->items; -} elsif ( $biblionumber ) { + $items = $order->items; +} elsif ($biblionumber) { my %additional_field_values; foreach my $af (@additional_fields) { my @marc_field_values; - if ($af->marcfield) { + if ( $af->marcfield ) { $record //= Koha::Biblios->find($biblionumber)->metadata->record; - my ($field, $subfield) = split /\$/, $af->marcfield; + my ( $field, $subfield ) = split /\$/, $af->marcfield; push @marc_field_values, $record->subfield( $field, $subfield ) if $record->subfield( $field, $subfield ); $additional_field_values{ $af->id } = \@marc_field_values; } } - $additional_field_values = \%additional_field_values + $additional_field_values = \%additional_field_values; } $template->param( - additional_fields => \@additional_fields, + additional_fields => \@additional_fields, additional_field_values => $additional_field_values, - items => $items, + items => $items, ); # fill template @@ -520,7 +514,6 @@ $template->param( output_html_with_http_headers $input, $cookie, $template->output; - =head2 MARCfindbreeding $record = MARCfindbreeding($breedingid); @@ -533,12 +526,13 @@ Returns as second parameter the character encoding. =cut sub MARCfindbreeding { - my ( $id ) = @_; - my ($marc, $encoding) = GetImportRecordMarc($id); + my ($id) = @_; + my ( $marc, $encoding ) = GetImportRecordMarc($id); + # remove the - in isbn, koha store isbn without any - if ($marc) { my $record = MARC::Record->new_from_usmarc($marc); - my ($isbnfield,$isbnsubfield) = GetMarcFromKohaField( 'biblioitems.isbn' ); + my ( $isbnfield, $isbnsubfield ) = GetMarcFromKohaField('biblioitems.isbn'); if ( $record->field($isbnfield) ) { foreach my $field ( $record->field($isbnfield) ) { foreach my $subfield ( $field->subfield($isbnsubfield) ) { @@ -548,10 +542,11 @@ sub MARCfindbreeding { } } } + # fix the unimarc 100 coded field (with unicode information) - if ($marcflavour eq 'UNIMARC' && $record->subfield(100,'a')) { - my $f100a=$record->subfield(100,'a'); - my $f100 = $record->field(100); + if ( $marcflavour eq 'UNIMARC' && $record->subfield( 100, 'a' ) ) { + my $f100a = $record->subfield( 100, 'a' ); + my $f100 = $record->field(100); my $f100temp = $f100->as_string; $record->delete_field($f100); if ( length($f100temp) > 28 ) { @@ -561,19 +556,18 @@ sub MARCfindbreeding { $record->insert_fields_ordered($f100); } } - - if ( !defined(ref($record)) ) { + + if ( !defined( ref($record) ) ) { return -1; - } - else { + } else { + # normalize author : probably UNIMARC specific... if ( C4::Context->preference("z3950NormalizeAuthor") and C4::Context->preference("z3950AuthorAuthFields") ) { - my ( $tag, $subfield ) = GetMarcFromKohaField( "biblio.author" ); + my ( $tag, $subfield ) = GetMarcFromKohaField("biblio.author"); - my $auth_fields = - C4::Context->preference("z3950AuthorAuthFields"); + my $auth_fields = C4::Context->preference("z3950AuthorAuthFields"); my @auth_fields = split /,/, $auth_fields; my $field; @@ -583,15 +577,13 @@ sub MARCfindbreeding { my $subfieldcode = shift @$tmpfield; my $subfieldvalue = shift @$tmpfield; if ($field) { - $field->add_subfields( - "$subfieldcode" => $subfieldvalue ) - if ( $subfieldcode ne $subfield ); - } - else { - $field = - MARC::Field->new( $tag, "", "", - $subfieldcode => $subfieldvalue ) - if ( $subfieldcode ne $subfield ); + $field->add_subfields( "$subfieldcode" => $subfieldvalue ) + if ( $subfieldcode ne $subfield ); + } else { + $field = MARC::Field->new( + $tag, "", "", + $subfieldcode => $subfieldvalue + ) if ( $subfieldcode ne $subfield ); } } } @@ -604,14 +596,9 @@ sub MARCfindbreeding { my $number = $record->field($fieldtag)->subfield('d'); if ($title) { $field->add_subfields( - "$subfield" => ucfirst($title) . " " - . ucfirst($firstname) . " " - . $number ); - } - else { - $field->add_subfields( - "$subfield" => ucfirst($firstname) . ", " - . ucfirst($lastname) ); + "$subfield" => ucfirst($title) . " " . ucfirst($firstname) . " " . $number ); + } else { + $field->add_subfields( "$subfield" => ucfirst($firstname) . ", " . ucfirst($lastname) ); } } $record->insert_fields_ordered($field); @@ -623,24 +610,24 @@ sub MARCfindbreeding { } sub Load_Duplicate { - my ($duplicatetitle)= @_; - ($template, $loggedinuser, $cookie) = get_template_and_user( - { - template_name => "acqui/neworderempty_duplicate.tt", - query => $input, - type => "intranet", - flagsrequired => { acquisition => 'order_manage' }, - } - ); + my ($duplicatetitle) = @_; + ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "acqui/neworderempty_duplicate.tt", + query => $input, + type => "intranet", + flagsrequired => { acquisition => 'order_manage' }, + } + ); - $template->param( - biblionumber => $biblionumber, - basketno => $basketno, - booksellerid => $basket->{'booksellerid'}, - breedingid => $breedingid, - duplicatetitle => $duplicatetitle, - (uc(C4::Context->preference("marcflavour"))) => 1 - ); + $template->param( + biblionumber => $biblionumber, + basketno => $basketno, + booksellerid => $basket->{'booksellerid'}, + breedingid => $breedingid, + duplicatetitle => $duplicatetitle, + ( uc( C4::Context->preference("marcflavour") ) ) => 1 + ); - output_html_with_http_headers $input, $cookie, $template->output; + output_html_with_http_headers $input, $cookie, $template->output; } diff --git a/acqui/newordersubscription.pl b/acqui/newordersubscription.pl index e8d776598b..a74a92eb85 100755 --- a/acqui/newordersubscription.pl +++ b/acqui/newordersubscription.pl @@ -18,11 +18,11 @@ # along with Koha; if not, see . use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Acquisition qw( GetBasket ); -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Context; -use C4::Output qw( output_html_with_http_headers ); +use C4::Output qw( output_html_with_http_headers ); use C4::Serials qw( SearchSubscriptions subscriptionCurrentlyOnOrder check_routing ); use Koha::Acquisition::Booksellers; @@ -42,27 +42,30 @@ my $basketno = $query->param('basketno'); my $booksellerid = $query->param('booksellerid'); my ( $template, $loggedinuser, $cookie, $flags ) = get_template_and_user( - { template_name => "acqui/newordersubscription.tt", - query => $query, - type => "intranet", - flagsrequired => { acquisition => 'order_manage' }, + { + template_name => "acqui/newordersubscription.tt", + query => $query, + type => "intranet", + flagsrequired => { acquisition => 'order_manage' }, } ); my $basket = GetBasket($basketno); $booksellerid = $basket->{booksellerid} unless $booksellerid; -my $bookseller = Koha::Acquisition::Booksellers->find( $booksellerid ); +my $bookseller = Koha::Acquisition::Booksellers->find($booksellerid); my @subscriptions; if ($searched) { - @subscriptions = SearchSubscriptions({ - title => $title, - issn => $ISSN, - ean => $EAN, - publisher => $publisher, - bookseller => $supplier, - branch => $branch - }); + @subscriptions = SearchSubscriptions( + { + title => $title, + issn => $ISSN, + ean => $EAN, + publisher => $publisher, + bookseller => $supplier, + branch => $branch + } + ); } foreach my $sub (@subscriptions) { diff --git a/acqui/newordersuggestion.pl b/acqui/newordersuggestion.pl index 9d35ec48de..e41381f4f4 100755 --- a/acqui/newordersuggestion.pl +++ b/acqui/newordersuggestion.pl @@ -90,9 +90,9 @@ can be equal to use Modern::Perl; -use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); -use C4::Output qw( output_html_with_http_headers ); +use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); +use C4::Output qw( output_html_with_http_headers ); use C4::Suggestions qw( ConnectSuggestionAndBiblio ); use C4::Budgets; @@ -103,24 +103,24 @@ my $input = CGI->new; # getting the CGI params my $basketno = $input->param('basketno'); -my $booksellerid = $input->param('booksellerid'); +my $booksellerid = $input->param('booksellerid'); my $author = $input->param('author'); my $title = $input->param('title'); my $publishercode = $input->param('publishercode'); my $op = $input->param('op'); my $suggestionid = $input->param('suggestionid'); my $duplicateNumber = $input->param('duplicateNumber'); -my $uncertainprice = $input->param('uncertainprice'); +my $uncertainprice = $input->param('uncertainprice'); $op = 'else' unless $op; my $dbh = C4::Context->dbh; my ( $template, $borrowernumber, $cookie ) = get_template_and_user( { - template_name => "acqui/newordersuggestion.tt", - type => "intranet", - query => $input, - flagsrequired => { acquisition => 'order_manage' }, + template_name => "acqui/newordersuggestion.tt", + type => "intranet", + query => $input, + flagsrequired => { acquisition => 'order_manage' }, } ); @@ -128,23 +128,25 @@ if ( $op eq 'connectDuplicate' ) { ConnectSuggestionAndBiblio( $suggestionid, $duplicateNumber ); } -my $suggestions = [ Koha::Suggestions->search_limited( - { - ( $author ? ( author => $author ) : () ), - ( $title ? ( title => $title ) : () ), - ( $publishercode ? ( publishercode => $publishercode ) : () ), - STATUS => 'ACCEPTED' - }, - { prefetch => ['managedby', 'suggestedby'] }, -)->as_list ]; +my $suggestions = [ + Koha::Suggestions->search_limited( + { + ( $author ? ( author => $author ) : () ), + ( $title ? ( title => $title ) : () ), + ( $publishercode ? ( publishercode => $publishercode ) : () ), + STATUS => 'ACCEPTED' + }, + { prefetch => [ 'managedby', 'suggestedby' ] }, + )->as_list +]; -my $vendor = Koha::Acquisition::Booksellers->find( $booksellerid ); +my $vendor = Koha::Acquisition::Booksellers->find($booksellerid); $template->param( - suggestions => $suggestions, - basketno => $basketno, - booksellerid => $booksellerid, - name => $vendor->name, - "op_$op" => 1, + suggestions => $suggestions, + basketno => $basketno, + booksellerid => $booksellerid, + name => $vendor->name, + "op_$op" => 1, ); output_html_with_http_headers $input, $cookie, $template->output; diff --git a/acqui/ordered.pl b/acqui/ordered.pl index 1d07220550..fd36464094 100755 --- a/acqui/ordered.pl +++ b/acqui/ordered.pl @@ -29,23 +29,23 @@ this script is to show orders ordered but not yet received use C4::Context; use Modern::Perl; -use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use Koha::Acquisition::Invoice::Adjustments; use C4::Acquisition qw( get_rounded_price ); -my $dbh = C4::Context->dbh; -my $input = CGI->new; -my $fund_id = $input->param('fund'); +my $dbh = C4::Context->dbh; +my $input = CGI->new; +my $fund_id = $input->param('fund'); my $fund_code = $input->param('fund_code'); my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "acqui/ordered.tt", - query => $input, - type => "intranet", - flagsrequired => { acquisition => '*' }, + template_name => "acqui/ordered.tt", + query => $input, + type => "intranet", + flagsrequired => { acquisition => '*' }, } ); @@ -93,7 +93,7 @@ my @ordered; my $total = 0; while ( my $data = $sth->fetchrow_hashref ) { - $data->{'itemtypes'} = [split('\|', $data->{itypes})]; + $data->{'itemtypes'} = [ split( '\|', $data->{itypes} ) ]; my $left = $data->{'tleft'}; if ( !$left || $left eq '' ) { $left = $data->{'quantity'}; @@ -101,23 +101,26 @@ while ( my $data = $sth->fetchrow_hashref ) { if ( $left && $left > 0 ) { my $subtotal = $left * get_rounded_price( $data->{$ecost_field} ); $data->{subtotal} = sprintf( "%.2f", $subtotal ); - $data->{'left'} = $left; + $data->{'left'} = $left; push @ordered, $data; $total += $subtotal; } } -my $adjustments = Koha::Acquisition::Invoice::Adjustments->search({budget_id => $fund_id, closedate => undef, encumber_open => 1 }, { prefetch => 'invoiceid' } ); -while ( my $adj = $adjustments->next ){ +my $adjustments = Koha::Acquisition::Invoice::Adjustments->search( + { budget_id => $fund_id, closedate => undef, encumber_open => 1 }, + { prefetch => 'invoiceid' } +); +while ( my $adj = $adjustments->next ) { $total += $adj->adjustment; } $total = sprintf( "%.2f", $total ); -$template->{VARS}->{'fund'} = $fund_id; -$template->{VARS}->{'ordered'} = \@ordered; -$template->{VARS}->{'total'} = $total; -$template->{VARS}->{'fund_code'} = $fund_code; +$template->{VARS}->{'fund'} = $fund_id; +$template->{VARS}->{'ordered'} = \@ordered; +$template->{VARS}->{'total'} = $total; +$template->{VARS}->{'fund_code'} = $fund_code; $template->{VARS}->{'adjustments'} = $adjustments; $sth->finish; diff --git a/acqui/orderreceive.pl b/acqui/orderreceive.pl index 0282020a7b..06564c730a 100755 --- a/acqui/orderreceive.pl +++ b/acqui/orderreceive.pl @@ -1,6 +1,5 @@ #!/usr/bin/perl - #script to receive orders #written by chris@katipo.co.nz 24/2/2000 @@ -63,11 +62,11 @@ use Modern::Perl; use CGI qw ( -utf8 ); use C4::Context; use C4::Acquisition qw( GetInvoice ); -use C4::Auth qw( get_template_and_user ); -use C4::Output qw( output_html_with_http_headers ); -use C4::Budgets qw( GetBudget GetBudgetPeriods GetBudgetPeriod GetBudgetHierarchy CanUserUseBudget ); +use C4::Auth qw( get_template_and_user ); +use C4::Output qw( output_html_with_http_headers ); +use C4::Budgets qw( GetBudget GetBudgetPeriods GetBudgetPeriod GetBudgetHierarchy CanUserUseBudget ); use C4::Members; -use C4::Biblio qw( GetMarcStructure ); +use C4::Biblio qw( GetMarcStructure ); use C4::Suggestions qw( GetSuggestion GetSuggestionInfoFromBiblionumber GetSuggestionInfo ); use Koha::Acquisition::Booksellers; @@ -77,25 +76,25 @@ use Koha::DateUtils qw( dt_from_string ); use Koha::ItemTypes; use Koha::Patrons; -my $input = CGI->new; +my $input = CGI->new; -my $dbh = C4::Context->dbh; -my $invoiceid = $input->param('invoiceid'); -my $invoice = GetInvoice($invoiceid); -my $booksellerid = $invoice->{booksellerid}; -my $freight = $invoice->{shipmentcost}; -my $ordernumber = $input->param('ordernumber'); +my $dbh = C4::Context->dbh; +my $invoiceid = $input->param('invoiceid'); +my $invoice = GetInvoice($invoiceid); +my $booksellerid = $invoice->{booksellerid}; +my $freight = $invoice->{shipmentcost}; +my $ordernumber = $input->param('ordernumber'); my $multiple_orders = $input->param('multiple_orders'); -my $bookseller = Koha::Acquisition::Booksellers->find( $booksellerid ); -my $order = Koha::Acquisition::Orders->find( $ordernumber ); +my $bookseller = Koha::Acquisition::Booksellers->find($booksellerid); +my $order = Koha::Acquisition::Orders->find($ordernumber); my ( $template, $loggedinuser, $cookie, $userflags ) = get_template_and_user( { - template_name => "acqui/orderreceive.tt", - query => $input, - type => "intranet", - flagsrequired => {acquisition => 'order_receive'}, + template_name => "acqui/orderreceive.tt", + query => $input, + type => "intranet", + flagsrequired => { acquisition => 'order_receive' }, } ); @@ -154,19 +153,17 @@ if ($multiple_orders) { $template->param( multiple_orders => $multiple_orders ); } -my $currencies = Koha::Acquisition::Currencies->search; +my $currencies = Koha::Acquisition::Currencies->search; my $active_currency = $currencies->get_active; # Check if ACQ framework exists my $acq_fw = GetMarcStructure( 1, 'ACQ', { unsafe => 1 } ); -unless($acq_fw) { - $template->param('NoACQframework' => 1); +unless ($acq_fw) { + $template->param( 'NoACQframework' => 1 ); } # get option values for TaxRates syspref -my @gst_values = map { - option => $_ + 0.0 -}, split( '\|', C4::Context->preference("TaxRates") ); +my @gst_values = map { option => $_ + 0.0 }, split( '\|', C4::Context->preference("TaxRates") ); $template->param( freight => $freight, @@ -181,29 +178,29 @@ $template->param( UniqueItemFields => C4::Context->preference('UniqueItemFields'), ); -my $patron = Koha::Patrons->find( $loggedinuser )->unblessed; +my $patron = Koha::Patrons->find($loggedinuser)->unblessed; my %budget_loops; my $budgets = GetBudgetHierarchy( undef, undef, undef, 1 ); -foreach my $budget (@{$budgets}) { - next unless (CanUserUseBudget($patron, $budget, $userflags)); - unless ( defined $budget_loops{$budget->{budget_period_id}} ){ - $budget_loops{$budget->{budget_period_id}}->{description} = $budget->{budget_period_description}; - $budget_loops{$budget->{budget_period_id}}->{active} = $budget->{budget_period_active}; - $budget_loops{$budget->{budget_period_id}}->{funds} = []; +foreach my $budget ( @{$budgets} ) { + next unless ( CanUserUseBudget( $patron, $budget, $userflags ) ); + unless ( defined $budget_loops{ $budget->{budget_period_id} } ) { + $budget_loops{ $budget->{budget_period_id} }->{description} = $budget->{budget_period_description}; + $budget_loops{ $budget->{budget_period_id} }->{active} = $budget->{budget_period_active}; + $budget_loops{ $budget->{budget_period_id} }->{funds} = []; } - push @{$budget_loops{$budget->{budget_period_id}}->{funds}}, { - b_id => $budget->{budget_id}, - b_txt => $budget->{budget_name}, + push @{ $budget_loops{ $budget->{budget_period_id} }->{funds} }, { + b_id => $budget->{budget_id}, + b_txt => $budget->{budget_name}, b_sort1_authcat => $budget->{'sort1_authcat'}, b_sort2_authcat => $budget->{'sort2_authcat'}, - b_active => $budget->{budget_period_active}, - b_level => $budget->{budget_level}, + b_active => $budget->{budget_period_active}, + b_level => $budget->{budget_level}, }; } $template->{'VARS'}->{'budget_loops'} = \%budget_loops; my $op = $input->param('op'); -if ($op and $op eq 'cud-edit'){ - $template->param(edit => 1); +if ( $op and $op eq 'cud-edit' ) { + $template->param( edit => 1 ); } output_html_with_http_headers $input, $cookie, $template->output; diff --git a/acqui/parcel.pl b/acqui/parcel.pl index 7fd16c76d2..01e4e9ce86 100755 --- a/acqui/parcel.pl +++ b/acqui/parcel.pl @@ -2,7 +2,6 @@ #script to receive orders - # Copyright 2000-2002 Katipo Communications # Copyright 2008-2009 BibLibre SARL # @@ -56,11 +55,11 @@ To filter the results list on this given date. use Modern::Perl; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Acquisition qw( CancelReceipt GetInvoice GetInvoiceDetails get_rounded_price ); -use C4::Budgets qw( GetBudget GetBudgetByOrderNumber GetBudgetName ); -use CGI qw ( -utf8 ); -use C4::Output qw( output_html_with_http_headers ); +use C4::Budgets qw( GetBudget GetBudgetByOrderNumber GetBudgetName ); +use CGI qw ( -utf8 ); +use C4::Output qw( output_html_with_http_headers ); use C4::Suggestions qw( GetSuggestion GetSuggestionInfoFromBiblionumber GetSuggestionInfo ); use Koha::Acquisition::Baskets; @@ -68,25 +67,26 @@ use Koha::Acquisition::Bookseller; use Koha::Acquisition::Orders; use Koha::Biblios; - my $input = CGI->new; -my ($template, $loggedinuser, $cookie) - = get_template_and_user({template_name => "acqui/parcel.tt", - query => $input, - type => "intranet", - flagsrequired => {acquisition => 'order_receive'}, -}); +my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "acqui/parcel.tt", + query => $input, + type => "intranet", + flagsrequired => { acquisition => 'order_receive' }, + } +); my $op = $input->param('op') // ''; # process cancellation first so that list of # orders to display is calculated after -if ($op eq 'cud-cancelreceipt') { - my $ordernumber = $input->param('ordernumber'); +if ( $op eq 'cud-cancelreceipt' ) { + my $ordernumber = $input->param('ordernumber'); my $parent_ordernumber = CancelReceipt($ordernumber); - unless($parent_ordernumber) { - $template->param(error_cancelling_receipt => 1); + unless ($parent_ordernumber) { + $template->param( error_cancelling_receipt => 1 ); } } @@ -94,7 +94,7 @@ my $invoiceid = $input->param('invoiceid'); my $invoice; $invoice = GetInvoiceDetails($invoiceid) if $invoiceid; -unless( $invoiceid and $invoice->{invoiceid} ) { +unless ( $invoiceid and $invoice->{invoiceid} ) { $template->param( error_invoice_not_known => 1, no_orders_to_display => 1 @@ -104,7 +104,7 @@ unless( $invoiceid and $invoice->{invoiceid} ) { } my $booksellerid = $invoice->{booksellerid}; -my $bookseller = Koha::Acquisition::Booksellers->find( $booksellerid ); +my $bookseller = Koha::Acquisition::Booksellers->find($booksellerid); my @orders = @{ $invoice->{orders} }; my $countlines = scalar @orders; @@ -115,50 +115,48 @@ my $total_tax_excluded = 0; my $total_tax_included = 0; my $subtotal_for_funds; -for my $order ( @orders ) { +for my $order (@orders) { $order->{'unitprice'} += 0; - my $order_object = Koha::Acquisition::Orders->find($order->{ordernumber}); + my $order_object = Koha::Acquisition::Orders->find( $order->{ordernumber} ); if ( $bookseller->invoiceincgst ) { $order->{ecost} = $order->{ecost_tax_included}; $order->{unitprice} = $order->{unitprice_tax_included}; - } - else { + } else { $order->{ecost} = $order->{ecost_tax_excluded}; $order->{unitprice} = $order->{unitprice_tax_excluded}; } - $order->{total} = get_rounded_price($order->{unitprice}) * $order->{quantity}; + $order->{total} = get_rounded_price( $order->{unitprice} ) * $order->{quantity}; - my %line = %{ $order }; + my %line = %{$order}; $line{invoice} = $invoice->{invoicenumber}; my @itemnumbers = $order_object->items->get_column('itemnumber'); - my $biblio = Koha::Biblios->find( $line{biblionumber} ); + my $biblio = Koha::Biblios->find( $line{biblionumber} ); $line{total_holds} = $biblio ? $biblio->holds->count : 0; - $line{item_holds} = $biblio ? $biblio->current_holds->search( + $line{item_holds} = $biblio + ? $biblio->current_holds->search( { itemnumber => { -in => \@itemnumbers }, } - )->count : 0; + )->count + : 0; $line{budget} = GetBudgetByOrderNumber( $line{ordernumber} ); - $line{tax_value} = $line{tax_value_on_receiving}; - $line{tax_rate} = $line{tax_rate_on_receiving}; - $foot{$line{tax_rate}}{tax_rate} = $line{tax_rate}; - $foot{$line{tax_rate}}{tax_value} += $line{tax_value}; - $total_tax_excluded += get_rounded_price($line{unitprice_tax_excluded}) * $line{quantity}; - $total_tax_included += get_rounded_price($line{unitprice_tax_included}) * $line{quantity}; + $line{tax_value} = $line{tax_value_on_receiving}; + $line{tax_rate} = $line{tax_rate_on_receiving}; + $foot{ $line{tax_rate} }{tax_rate} = $line{tax_rate}; + $foot{ $line{tax_rate} }{tax_value} += $line{tax_value}; + $total_tax_excluded += get_rounded_price( $line{unitprice_tax_excluded} ) * $line{quantity}; + $total_tax_included += get_rounded_price( $line{unitprice_tax_included} ) * $line{quantity}; - my $suggestion = GetSuggestionInfoFromBiblionumber($line{biblionumber}); + my $suggestion = GetSuggestionInfoFromBiblionumber( $line{biblionumber} ); $line{suggestionid} = $suggestion->{suggestionid}; $line{surnamesuggestedby} = $suggestion->{surnamesuggestedby}; $line{firstnamesuggestedby} = $suggestion->{firstnamesuggestedby}; if ( $line{parent_ordernumber} != $line{ordernumber} ) { - if ( grep { $_->{ordernumber} == $line{parent_ordernumber} } - @orders - ) - { + if ( grep { $_->{ordernumber} == $line{parent_ordernumber} } @orders ) { $line{cannot_cancel} = 1; } } @@ -166,7 +164,7 @@ for my $order ( @orders ) { my $budget_name = GetBudgetName( $line{budget_id} ); $line{budget_name} = $budget_name; - $subtotal_for_funds->{ $line{budget_name} }{ecost} += get_rounded_price($order->{ecost}) * $order->{quantity}; + $subtotal_for_funds->{ $line{budget_name} }{ecost} += get_rounded_price( $order->{ecost} ) * $order->{quantity}; $subtotal_for_funds->{ $line{budget_name} }{unitprice} += $order->{total}; push @loop_received, \%line; @@ -174,17 +172,17 @@ for my $order ( @orders ) { push @book_foot_loop, map { $_ } values %foot; $template->param( - invoiceid => $invoice->{invoiceid}, - invoice => $invoice->{invoicenumber}, - invoiceclosedate => $invoice->{closedate}, - shipmentdate => $invoice->{shipmentdate}, - name => $bookseller->name, - booksellerid => $bookseller->id, - loop_received => \@loop_received, - book_foot_loop => \@book_foot_loop, - (uc(C4::Context->preference("marcflavour"))) => 1, - total_tax_excluded => $total_tax_excluded, - total_tax_included => $total_tax_included, - subtotal_for_funds => $subtotal_for_funds, + invoiceid => $invoice->{invoiceid}, + invoice => $invoice->{invoicenumber}, + invoiceclosedate => $invoice->{closedate}, + shipmentdate => $invoice->{shipmentdate}, + name => $bookseller->name, + booksellerid => $bookseller->id, + loop_received => \@loop_received, + book_foot_loop => \@book_foot_loop, + ( uc( C4::Context->preference("marcflavour") ) ) => 1, + total_tax_excluded => $total_tax_excluded, + total_tax_included => $total_tax_included, + subtotal_for_funds => $subtotal_for_funds, ); output_html_with_http_headers $input, $cookie, $template->output; diff --git a/acqui/parcels.pl b/acqui/parcels.pl index fa7c617320..ee3e3d6a06 100755 --- a/acqui/parcels.pl +++ b/acqui/parcels.pl @@ -1,9 +1,7 @@ #!/usr/bin/perl - #script to show display basket of orders - # Copyright 2000-2002 Katipo Communications # Copyright 2008-2009 BibLibre SARL # @@ -67,12 +65,12 @@ To know how many results have to be display / page. =cut use Modern::Perl; -use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use C4::Acquisition qw( GetInvoices GetInvoice AddInvoice ); -use C4::Budgets qw( GetBudgetHierarchy GetBudget CanUserUseBudget ); +use C4::Budgets qw( GetBudgetHierarchy GetBudget CanUserUseBudget ); use Koha::Acquisition::Booksellers; use Koha::Acquisition::Invoices; @@ -80,7 +78,7 @@ use Koha::AdditionalFields; use Koha::DateUtils qw( dt_from_string ); my $input = CGI->new; -my $booksellerid = $input->param('booksellerid'); +my $booksellerid = $input->param('booksellerid'); my $order = $input->param('orderby') || 'shipmentdate desc'; my $startfrom = $input->param('startfrom'); my $code = $input->param('filter'); @@ -92,17 +90,18 @@ my $op = $input->param('op'); $resultsperpage ||= 20; our ( $template, $loggedinuser, $cookie, $flags ) = get_template_and_user( - { template_name => 'acqui/parcels.tt', - query => $input, - type => 'intranet', - flagsrequired => { acquisition => 'order_receive' }, + { + template_name => 'acqui/parcels.tt', + query => $input, + type => 'intranet', + flagsrequired => { acquisition => 'order_receive' }, } ); -my $invoicenumber = $input->param('invoice'); -my $shipmentcost = $input->param('shipmentcost'); +my $invoicenumber = $input->param('invoice'); +my $shipmentcost = $input->param('shipmentcost'); my $shipmentcost_budgetid = $input->param('shipmentcost_budgetid'); -my $shipmentdate = $input->param('shipmentdate'); +my $shipmentdate = $input->param('shipmentdate'); if ( $op and $op eq 'cud-new' ) { if ( C4::Context->preference('AcqWarnOnDuplicateInvoice') ) { @@ -111,51 +110,50 @@ if ( $op and $op eq 'cud-new' ) { invoicenumber => $invoicenumber, ); if ( scalar @invoices > 0 ) { - $template->{'VARS'}->{'duplicate_invoices'} = \@invoices; - $template->{'VARS'}->{'invoicenumber'} = $invoicenumber; - $template->{'VARS'}->{'shipmentdate'} = $shipmentdate; - $template->{'VARS'}->{'shipmentcost'} = $shipmentcost; - $template->{'VARS'}->{'shipmentcost_budgetid'} = - $shipmentcost_budgetid; + $template->{'VARS'}->{'duplicate_invoices'} = \@invoices; + $template->{'VARS'}->{'invoicenumber'} = $invoicenumber; + $template->{'VARS'}->{'shipmentdate'} = $shipmentdate; + $template->{'VARS'}->{'shipmentcost'} = $shipmentcost; + $template->{'VARS'}->{'shipmentcost_budgetid'} = $shipmentcost_budgetid; } } $op = 'cud-confirm' unless $template->{'VARS'}->{'duplicate_invoices'}; } -if ($op and $op eq 'cud-confirm') { +if ( $op and $op eq 'cud-confirm' ) { my $invoiceid = AddInvoice( - invoicenumber => $invoicenumber, - booksellerid => $booksellerid, - shipmentdate => $shipmentdate, - shipmentcost => $shipmentcost, + invoicenumber => $invoicenumber, + booksellerid => $booksellerid, + shipmentdate => $shipmentdate, + shipmentcost => $shipmentcost, shipmentcost_budgetid => $shipmentcost_budgetid, ); - if (defined $invoiceid) { + if ( defined $invoiceid ) { my @additional_fields = Koha::Acquisition::Invoices->find($invoiceid)->prepare_cgi_additional_field_values( $input, 'aqinvoices' ); if (@additional_fields) { - my $invoice = Koha::Acquisition::Invoices->find( $invoiceid ); - $invoice->set_additional_fields(\@additional_fields); + my $invoice = Koha::Acquisition::Invoices->find($invoiceid); + $invoice->set_additional_fields( \@additional_fields ); } + # Successful 'Add' print $input->redirect("/cgi-bin/koha/acqui/parcel.pl?invoiceid=$invoiceid"); exit 0; } else { - $template->param(error_failed_to_create_invoice => 1); + $template->param( error_failed_to_create_invoice => 1 ); } } $template->param( - available_additional_fields => [ Koha::AdditionalFields->search({ tablename => 'aqinvoices' })->as_list ] -); + available_additional_fields => [ Koha::AdditionalFields->search( { tablename => 'aqinvoices' } )->as_list ] ); -my $bookseller = Koha::Acquisition::Booksellers->find( $booksellerid ); +my $bookseller = Koha::Acquisition::Booksellers->find($booksellerid); my @parcels = GetInvoices( supplierid => $booksellerid, invoicenumber => $code, ( $datefrom ? ( shipmentdatefrom => $datefrom ) : () ), - ( $dateto ? ( shipmentdateto => $dateto ) : () ), + ( $dateto ? ( shipmentdateto => $dateto ) : () ), order_by => $order, ( $include_closed ? () : ( closedate => undef ) ), ); @@ -183,12 +181,13 @@ if ( $count_parcels > $resultsperpage ) { my $loopres = []; my $next_page_start = $startfrom + $resultsperpage; -my $last_row = ( $next_page_start < $count_parcels ) ? $next_page_start - 1 : $count_parcels - 1; -for my $i ( $startfrom .. $last_row) { +my $last_row = ( $next_page_start < $count_parcels ) ? $next_page_start - 1 : $count_parcels - 1; +for my $i ( $startfrom .. $last_row ) { my $p = $parcels[$i]; push @{$loopres}, - { number => $i + 1, + { + number => $i + 1, invoiceid => $p->{invoiceid}, code => $p->{invoicenumber}, nullcode => $p->{invoicenumber} eq 'NULL', @@ -196,9 +195,9 @@ for my $i ( $startfrom .. $last_row) { raw_datereceived => $p->{shipmentdate}, datereceived => $p->{shipmentdate}, bibcount => $p->{receivedbiblios} || 0, - reccount => $p->{receiveditems} || 0, - itemcount => $p->{itemsexpected} || 0, - }; + reccount => $p->{receiveditems} || 0, + itemcount => $p->{itemsexpected} || 0, + }; } if ($count_parcels) { $template->param( searchresults => $loopres, count => $count_parcels ); @@ -206,32 +205,31 @@ if ($count_parcels) { # build budget list my $budget_loop = []; -my $budgets = GetBudgetHierarchy; -foreach my $r (@{$budgets}) { - next unless (CanUserUseBudget($loggedinuser, $r, $flags)); +my $budgets = GetBudgetHierarchy; +foreach my $r ( @{$budgets} ) { + next unless ( CanUserUseBudget( $loggedinuser, $r, $flags ) ); push @{$budget_loop}, { - b_id => $r->{budget_id}, - b_txt => $r->{budget_name}, + b_id => $r->{budget_id}, + b_txt => $r->{budget_name}, b_active => $r->{budget_period_active}, }; } @{$budget_loop} = - sort { uc( $a->{b_txt}) cmp uc( $b->{b_txt}) } @{$budget_loop}; - + sort { uc( $a->{b_txt} ) cmp uc( $b->{b_txt} ) } @{$budget_loop}; $template->param( - orderby => $order, - filter => $code, - datefrom => $datefrom, - dateto => $dateto, - resultsperpage => $resultsperpage, - filter_include_closed => $include_closed, - name => $bookseller->name, - shipmentdate_today => dt_from_string, - booksellerid => $booksellerid, - GST => C4::Context->preference('TaxRates'), - budgets => $budget_loop, + orderby => $order, + filter => $code, + datefrom => $datefrom, + dateto => $dateto, + resultsperpage => $resultsperpage, + filter_include_closed => $include_closed, + name => $bookseller->name, + shipmentdate_today => dt_from_string, + booksellerid => $booksellerid, + GST => C4::Context->preference('TaxRates'), + budgets => $budget_loop, ); output_html_with_http_headers $input, $cookie, $template->output; @@ -256,23 +254,24 @@ sub set_page_navigation { } # set up page indexes for at max 15 pages - my $max_idx = ( $pages < 15 ) ? $pages : 15; + my $max_idx = ( $pages < 15 ) ? $pages : 15; my $current_page = ( $startfrom / $resultsperpage ) - 1; for my $idx ( 1 .. $max_idx ) { push @{$numbers}, - { number => $idx, + { + number => $idx, startfrom => ( $idx - 1 ) * $resultsperpage, highlight => ( $idx == $current_page ), - }; + }; } } $template->param( - numbers => $numbers, - displaynext => $displaynext, - displayprev => $displayprev, + numbers => $numbers, + displaynext => $displaynext, + displayprev => $displayprev, nextstartfrom => ( ( $next_row < $total_rows ) ? $next_row : $total_rows ), - prevstartfrom => ( ( $prev_row > 0 ) ? $prev_row : 0 ) + prevstartfrom => ( ( $prev_row > 0 ) ? $prev_row : 0 ) ); return; } diff --git a/acqui/showorder.pl b/acqui/showorder.pl index da7cce55b1..e110161660 100755 --- a/acqui/showorder.pl +++ b/acqui/showorder.pl @@ -18,26 +18,28 @@ use Modern::Perl; use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use Koha::Acquisition::Orders; use Koha::Patrons; my $cgi = CGI->new; -my ( $template, $loggedinuser, $cookie ) = get_template_and_user({ - template_name => "acqui/showorder.tt", - query => $cgi, - type => "intranet", - flagsrequired => { acquisition => '*' }, -}); +my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "acqui/showorder.tt", + query => $cgi, + type => "intranet", + flagsrequired => { acquisition => '*' }, + } +); my $ordernumber = $cgi->param('ordernumber'); -my $order = Koha::Acquisition::Orders->find($ordernumber); -my $creator = Koha::Patrons->find($order->created_by); +my $order = Koha::Acquisition::Orders->find($ordernumber); +my $creator = Koha::Patrons->find( $order->created_by ); $template->param( - order => $order, + order => $order, creator => $creator, ); diff --git a/acqui/spent.pl b/acqui/spent.pl index acd84676ee..8ca58ad758 100755 --- a/acqui/spent.pl +++ b/acqui/spent.pl @@ -30,24 +30,24 @@ this script is designed to show the spent amount in budgets =cut use C4::Context; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Acquisition qw( get_rounded_price ); use Koha::Acquisition::Invoice::Adjustments; -my $dbh = C4::Context->dbh; -my $input = CGI->new; -my $bookfund = $input->param('fund'); +my $dbh = C4::Context->dbh; +my $input = CGI->new; +my $bookfund = $input->param('fund'); my $fund_code = $input->param('fund_code'); my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "acqui/spent.tt", - query => $input, - type => "intranet", - flagsrequired => { acquisition => '*' }, + template_name => "acqui/spent.tt", + query => $input, + type => "intranet", + flagsrequired => { acquisition => '*' }, } ); @@ -106,10 +106,10 @@ my $subtotal = 0; my @spent; while ( my $data = $sth->fetchrow_hashref ) { my $recv = $data->{'quantityreceived'}; - $data->{'itemtypes'} = [split('\|', $data->{itypes})]; + $data->{'itemtypes'} = [ split( '\|', $data->{itypes} ) ]; if ( $recv > 0 ) { - my $rowtotal = $recv * get_rounded_price($data->{$unitprice_field}); - $data->{'rowtotal'} = sprintf( "%.2f", $rowtotal ); + my $rowtotal = $recv * get_rounded_price( $data->{$unitprice_field} ); + $data->{'rowtotal'} = sprintf( "%.2f", $rowtotal ); $data->{'unitprice_tax_included'} = sprintf( "%.2f", $data->{$unitprice_field} ); $subtotal += $rowtotal; push @spent, $data; @@ -126,31 +126,34 @@ $query = qq{ $sth = $dbh->prepare($query); $sth->execute($bookfund); my @shipmentcosts; -while (my $data = $sth->fetchrow_hashref) { +while ( my $data = $sth->fetchrow_hashref ) { push @shipmentcosts, { - shipmentcost => sprintf("%.2f", $data->{shipmentcost}), - invoiceid => $data->{invoiceid}, + shipmentcost => sprintf( "%.2f", $data->{shipmentcost} ), + invoiceid => $data->{invoiceid}, invoicenumber => $data->{invoicenumber} }; $total += $data->{shipmentcost}; } $sth->finish; -my $adjustments = Koha::Acquisition::Invoice::Adjustments->search({budget_id => $bookfund, closedate => { '!=' => undef } }, { prefetch => 'invoiceid' }, ); -while ( my $adj = $adjustments->next ){ +my $adjustments = Koha::Acquisition::Invoice::Adjustments->search( + { budget_id => $bookfund, closedate => { '!=' => undef } }, + { prefetch => 'invoiceid' }, +); +while ( my $adj = $adjustments->next ) { $total += $adj->adjustment; } $total = sprintf( "%.2f", $total ); $template->param( - fund => $bookfund, - spent => \@spent, - subtotal => $subtotal, + fund => $bookfund, + spent => \@spent, + subtotal => $subtotal, shipmentcosts => \@shipmentcosts, - adjustments => $adjustments, - total => $total, - fund_code => $fund_code + adjustments => $adjustments, + total => $total, + fund_code => $fund_code ); output_html_with_http_headers $input, $cookie, $template->output; diff --git a/acqui/supplier.pl b/acqui/supplier.pl index 2de890d08f..285a40f13e 100755 --- a/acqui/supplier.pl +++ b/acqui/supplier.pl @@ -41,10 +41,10 @@ To know the bookseller this script has to display details. =cut use Modern::Perl; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Contract qw( GetContracts GetContract ); -use C4::Output qw( output_html_with_http_headers ); -use CGI qw ( -utf8 ); +use C4::Output qw( output_html_with_http_headers ); +use CGI qw ( -utf8 ); use C4::Budgets; @@ -52,24 +52,25 @@ use Koha::Acquisition::Bookseller::Contacts; use Koha::Acquisition::Booksellers; use Koha::Acquisition::Currencies; -my $query = CGI->new; -my $op = $query->param('op') || 'display'; +my $query = CGI->new; +my $op = $query->param('op') || 'display'; my ( $template, $loggedinuser, $cookie ) = get_template_and_user( - { template_name => 'acqui/supplier.tt', - query => $query, - type => 'intranet', - flagsrequired => { acquisition => '*' }, + { + template_name => 'acqui/supplier.tt', + query => $query, + type => 'intranet', + flagsrequired => { acquisition => '*' }, } ); -my $booksellerid = $query->param('booksellerid'); +my $booksellerid = $query->param('booksellerid'); my $supplier; if ($booksellerid) { - $supplier = Koha::Acquisition::Booksellers->find( $booksellerid ); + $supplier = Koha::Acquisition::Booksellers->find($booksellerid); my $supplier_hashref = $supplier->unblessed; foreach ( keys %{$supplier_hashref} ) { $template->{'VARS'}->{$_} = $supplier->$_; } - $template->{VARS}->{contacts} = $supplier->contacts if $supplier->contacts->count; + $template->{VARS}->{contacts} = $supplier->contacts if $supplier->contacts->count; $template->{'VARS'}->{'booksellerid'} = $booksellerid; } @@ -79,19 +80,20 @@ if ( $op eq 'display' ) { my $contracts = GetContracts( { booksellerid => $booksellerid } ); $template->param( - active => $supplier->active, - tax_rate => $supplier->tax_rate + 0.0, - invoiceprice => $supplier->invoiceprice, - listprice => $supplier->listprice, - basketcount => $supplier->baskets->count, + active => $supplier->active, + tax_rate => $supplier->tax_rate + 0.0, + invoiceprice => $supplier->invoiceprice, + listprice => $supplier->listprice, + basketcount => $supplier->baskets->count, subscriptioncount => $supplier->subscriptions->count, - vendor => $supplier, - contracts => $contracts, + vendor => $supplier, + contracts => $contracts, ); } elsif ( $op eq 'cud-delete' ) { + # no further message needed for the user # the DELETE button only appears in the template if basketcount == 0 AND subscriptioncount == 0 - if ( $supplier->baskets->count == 0 && $supplier->subscriptions->count == 0) { + if ( $supplier->baskets->count == 0 && $supplier->subscriptions->count == 0 ) { Koha::Acquisition::Booksellers->find($booksellerid)->delete; } print $query->redirect('/cgi-bin/koha/acqui/acqui-home.pl'); @@ -99,18 +101,17 @@ if ( $op eq 'display' ) { } else { # get option values from TaxRates syspref - my @gst_values = map { - option => $_ + 0.0 - }, split( '\|', C4::Context->preference("TaxRates") ); + my @gst_values = map { option => $_ + 0.0 }, split( '\|', C4::Context->preference("TaxRates") ); $template->param( + # set active ON by default for supplier add (id empty for add) active => $supplier ? $supplier->active : 1, tax_rate => $supplier ? $supplier->tax_rate + 0.0 : 0, - vendor => $supplier, - gst_values => \@gst_values, - currencies => Koha::Acquisition::Currencies->search, - enter => 1, + vendor => $supplier, + gst_values => \@gst_values, + currencies => Koha::Acquisition::Currencies->search, + enter => 1, ); } diff --git a/acqui/transferorder.pl b/acqui/transferorder.pl index 69597f4e7e..50edf2b5ec 100755 --- a/acqui/transferorder.pl +++ b/acqui/transferorder.pl @@ -22,7 +22,7 @@ use Modern::Perl; use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use C4::Context; use C4::Acquisition qw( GetOrder GetBasket TransferOrder GetBasketsByBookseller SearchOrders ); @@ -30,62 +30,65 @@ use Koha::Acquisition::Booksellers; my $input = CGI->new; my ( $template, $loggedinuser, $cookie ) = get_template_and_user( - { template_name => "acqui/transferorder.tt", - query => $input, - type => "intranet", - flagsrequired => { acquisition => 'order_manage' }, + { + template_name => "acqui/transferorder.tt", + query => $input, + type => "intranet", + flagsrequired => { acquisition => 'order_manage' }, } ); my $dbh = C4::Context->dbh; -my $bookselleridfrom = $input->param('bookselleridfrom'); -my $ordernumber = $input->param('ordernumber'); -my $bookselleridto = $input->param('bookselleridto'); -my $basketno = $input->param('basketno'); -my $op = $input->param('op'); -my $query = $input->param('query'); +my $bookselleridfrom = $input->param('bookselleridfrom'); +my $ordernumber = $input->param('ordernumber'); +my $bookselleridto = $input->param('bookselleridto'); +my $basketno = $input->param('basketno'); +my $op = $input->param('op'); +my $query = $input->param('query'); -my $order = GetOrder($ordernumber); +my $order = GetOrder($ordernumber); my $basketfromname = ''; -if($order) { - my $basket = GetBasket($order->{basketno}); - $basketfromname = $basket->{basketname}; +if ($order) { + my $basket = GetBasket( $order->{basketno} ); + $basketfromname = $basket->{basketname}; $bookselleridfrom = $basket->{booksellerid} if $basket; } -my $booksellerfrom = Koha::Acquisition::Booksellers->find( $bookselleridfrom ); +my $booksellerfrom = Koha::Acquisition::Booksellers->find($bookselleridfrom); my $booksellerfromname; -if($booksellerfrom){ +if ($booksellerfrom) { $booksellerfromname = $booksellerfrom->name; } -my $booksellerto = Koha::Acquisition::Booksellers->find( $bookselleridto ); +my $booksellerto = Koha::Acquisition::Booksellers->find($bookselleridto); my $booksellertoname; -if($booksellerto){ +if ($booksellerto) { $booksellertoname = $booksellerto->name; } +if ( $basketno && $ordernumber ) { -if( $basketno && $ordernumber) { # Transfer order and exit - my $order = GetOrder( $ordernumber ); - my $basket = GetBasket($order->{basketno}); - my $booksellerfrom = Koha::Acquisition::Booksellers->find( $basket->{booksellerid} ); + my $order = GetOrder($ordernumber); + my $basket = GetBasket( $order->{basketno} ); + my $booksellerfrom = Koha::Acquisition::Booksellers->find( $basket->{booksellerid} ); my $bookselleridfrom = $booksellerfrom->id; - TransferOrder($ordernumber, $basketno); + TransferOrder( $ordernumber, $basketno ); + + $template->param( transferred => 1 ); +} elsif ( $bookselleridto && $ordernumber ) { - $template->param(transferred => 1) -} elsif ( $bookselleridto && $ordernumber) { # Show open baskets for this bookseller - my $order = GetOrder( $ordernumber ); - my $basketfrom = GetBasket( $order->{basketno} ); + my $order = GetOrder($ordernumber); + my $basketfrom = GetBasket( $order->{basketno} ); my $booksellerfrom = Koha::Acquisition::Booksellers->find( $basketfrom->{booksellerid} ); $booksellerfromname = $booksellerfrom->name; - my $baskets = GetBasketsByBookseller( $bookselleridto ); + my $baskets = GetBasketsByBookseller($bookselleridto); my $basketscount = scalar @$baskets; - my @basketsloop = (); - for( my $i = 0 ; $i < $basketscount ; $i++ ){ + my @basketsloop = (); + + for ( my $i = 0 ; $i < $basketscount ; $i++ ) { my %line; %line = %{ $baskets->[$i] }; my $createdby = Koha::Patrons->find( $line{authorisedby} ); @@ -93,50 +96,55 @@ if( $basketno && $ordernumber) { push @basketsloop, \%line unless $line{closedate}; } $template->param( - show_baskets => 1, + show_baskets => 1, query => $query, - basketsloop => \@basketsloop, + basketsloop => \@basketsloop, basketfromname => $basketfrom->{basketname}, ); -} elsif ( $bookselleridfrom && !defined $ordernumber) { +} elsif ( $bookselleridfrom && !defined $ordernumber ) { + # Show pending orders - my $pendingorders = SearchOrders({ - booksellerid => $bookselleridfrom, - pending => 1, - }); + my $pendingorders = SearchOrders( + { + booksellerid => $bookselleridfrom, + pending => 1, + } + ); my $orderscount = scalar @$pendingorders; - my @ordersloop = (); - for( my $i = 0 ; $i < $orderscount ; $i++ ){ + my @ordersloop = (); + for ( my $i = 0 ; $i < $orderscount ; $i++ ) { my %line; %line = %{ $pendingorders->[$i] }; push @ordersloop, \%line; } $template->param( - ordersloop => \@ordersloop, + ordersloop => \@ordersloop, ); } else { + # Search for booksellers to transfer from/to $op = '' unless $op; - if( $op eq "do_search" ) { + if ( $op eq "do_search" ) { my $booksellers = Koha::Acquisition::Booksellers->search( - { name => { -like => "%$query%" } }, - { order_by => { -asc => 'name' } } ); + { name => { -like => "%$query%" } }, + { order_by => { -asc => 'name' } } + ); $template->param( - query => $query, - do_search => 1, + query => $query, + do_search => 1, booksellers => $booksellers, ); } } $template->param( - bookselleridfrom => $bookselleridfrom, - booksellerfromname => $booksellerfromname, - bookselleridto => $bookselleridto, - booksellertoname => $booksellertoname, - ordernumber => $ordernumber, - basketno => $basketno, - basketfromname => $basketfromname, + bookselleridfrom => $bookselleridfrom, + booksellerfromname => $booksellerfromname, + bookselleridto => $bookselleridto, + booksellertoname => $booksellertoname, + ordernumber => $ordernumber, + basketno => $basketno, + basketfromname => $basketfromname, ); output_html_with_http_headers $input, $cookie, $template->output; diff --git a/acqui/uncertainprice.pl b/acqui/uncertainprice.pl index f03dea0562..1aa6cc206e 100755 --- a/acqui/uncertainprice.pl +++ b/acqui/uncertainprice.pl @@ -21,7 +21,6 @@ # You should have received a copy of the GNU General Public License # along with Koha; if not, see . - =head1 NAME uncertainprice.pl @@ -42,75 +41,81 @@ The bookseller who we want to display the orders of. =cut - use Modern::Perl; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Acquisition qw( SearchOrders GetOrder ModOrder ); use Koha::Acquisition::Booksellers; use Koha::Acquisition::Baskets; -my $input=CGI->new; +my $input = CGI->new; -my ($template, $loggedinuser, $cookie) - = get_template_and_user({template_name => "acqui/uncertainprice.tt", - query => $input, - type => "intranet", - flagsrequired => { acquisition => 'order_manage' }, - }); +my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "acqui/uncertainprice.tt", + query => $input, + type => "intranet", + flagsrequired => { acquisition => 'order_manage' }, + } +); my $booksellerid = $input->param('booksellerid'); my $basketno = $input->param('basketno'); -my $op = $input->param('op'); -my $owner = $input->param('owner') || 0 ; # flag to see only "my" orders, or everyone orders -my $bookseller = Koha::Acquisition::Booksellers->find( $booksellerid ); +my $op = $input->param('op'); +my $owner = $input->param('owner') || 0; # flag to see only "my" orders, or everyone orders +my $bookseller = Koha::Acquisition::Booksellers->find($booksellerid); $template->param( basket => Koha::Acquisition::Baskets->find($basketno) ); #show all orders that have uncertain price for the bookseller -my $pendingorders = SearchOrders({ - booksellerid => $booksellerid, - owner => $owner, - basketno => $basketno, - pending => 1, -}); +my $pendingorders = SearchOrders( + { + booksellerid => $booksellerid, + owner => $owner, + basketno => $basketno, + pending => 1, + } +); my @orders = grep { $_->{'uncertainprice'} } @$pendingorders; if ( $op eq 'cud-validate' ) { - $template->param( validate => 1); + $template->param( validate => 1 ); my $count = scalar(@orders); - for (my $i=0; $i < $count; $i++) { - my $order = pop(@orders); + for ( my $i = 0 ; $i < $count ; $i++ ) { + my $order = pop(@orders); my $ordernumber = $order->{ordernumber}; - next unless ($input->param('qty'.$ordernumber)); - my $order_as_from_db=GetOrder($order->{ordernumber}); - $order->{'listprice'} = $input->param('price'.$ordernumber); - $order->{'ecost'}= $input->param('price'.$ordernumber) - (($input->param('price'.$ordernumber) /100) * $bookseller->discount); - $order->{'rrp'} = $input->param('price'.$ordernumber); - $order->{'quantity'}=$input->param('qty'.$ordernumber); - $order->{'uncertainprice'}=$input->param('uncertainprice'.$ordernumber); + next unless ( $input->param( 'qty' . $ordernumber ) ); + my $order_as_from_db = GetOrder( $order->{ordernumber} ); + $order->{'listprice'} = $input->param( 'price' . $ordernumber ); + $order->{'ecost'} = $input->param( 'price' . $ordernumber ) - + ( ( $input->param( 'price' . $ordernumber ) / 100 ) * $bookseller->discount ); + $order->{'rrp'} = $input->param( 'price' . $ordernumber ); + $order->{'quantity'} = $input->param( 'qty' . $ordernumber ); + $order->{'uncertainprice'} = $input->param( 'uncertainprice' . $ordernumber ); ModOrder($order); } } -$template->param( uncertainpriceorders => \@orders, - booksellername => "".$bookseller->name, - booksellerid => $bookseller->id, - booksellerpostal =>$bookseller->postal, - bookselleraddress1 => $bookseller->address1, - bookselleraddress2 => $bookseller->address2, - bookselleraddress3 => $bookseller->address3, - bookselleraddress4 => $bookseller->address4, - booksellerphone =>$bookseller->phone, - booksellernotes => $bookseller->notes, - basketcount => $bookseller->baskets->count, - subscriptioncount => $bookseller->subscriptions->count, - active => $bookseller->active, - owner => $owner, - scriptname => "/cgi-bin/koha/acqui/uncertainprice.pl"); +$template->param( + uncertainpriceorders => \@orders, + booksellername => "" . $bookseller->name, + booksellerid => $bookseller->id, + booksellerpostal => $bookseller->postal, + bookselleraddress1 => $bookseller->address1, + bookselleraddress2 => $bookseller->address2, + bookselleraddress3 => $bookseller->address3, + bookselleraddress4 => $bookseller->address4, + booksellerphone => $bookseller->phone, + booksellernotes => $bookseller->notes, + basketcount => $bookseller->baskets->count, + subscriptioncount => $bookseller->subscriptions->count, + active => $bookseller->active, + owner => $owner, + scriptname => "/cgi-bin/koha/acqui/uncertainprice.pl" +); $template->{'VARS'}->{'contacts'} = $bookseller->contacts; output_html_with_http_headers $input, $cookie, $template->output; diff --git a/acqui/vendor_issues.pl b/acqui/vendor_issues.pl index bae905b17d..935c4cd021 100755 --- a/acqui/vendor_issues.pl +++ b/acqui/vendor_issues.pl @@ -21,7 +21,7 @@ use Modern::Perl; use CGI qw ( -utf8 ); use Try::Tiny; use C4::Context; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use Koha::Acquisition::Booksellers; diff --git a/acqui/z3950_search.pl b/acqui/z3950_search.pl index 6913adecee..a3403f726d 100755 --- a/acqui/z3950_search.pl +++ b/acqui/z3950_search.pl @@ -22,7 +22,7 @@ use Modern::Perl; use CGI qw/-utf8/; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use C4::Context; use C4::Breeding qw( Z3950Search ); @@ -31,7 +31,7 @@ use Koha::Acquisition::Booksellers; use Koha::BiblioFrameworks; my $input = CGI->new; -my $biblionumber = $input->param('biblionumber')||0; +my $biblionumber = $input->param('biblionumber') || 0; my $frameworkcode = $input->param('frameworkcode') || q{}; my $title = $input->param('title'); my $author = $input->param('author'); @@ -45,87 +45,88 @@ my $stdid = $input->param('stdid'); my $dewey = $input->param('dewey'); my $controlnumber = $input->param('controlnumber'); my $publicationyear = $input->param('publicationyear'); -my $op = $input->param('op')||''; +my $op = $input->param('op') || ''; my $booksellerid = $input->param('booksellerid'); my $basketno = $input->param('basketno'); my $page = $input->param('current_page') || 1; -$page = $input->param('goto_page') if $input->param('changepage_goto'); +$page = $input->param('goto_page') if $input->param('changepage_goto'); # get framework list -my $frameworks = Koha::BiblioFrameworks->search({}, { order_by => ['frameworktext'] }); +my $frameworks = Koha::BiblioFrameworks->search( {}, { order_by => ['frameworktext'] } ); -my $vendor = Koha::Acquisition::Booksellers->find( $booksellerid ); +my $vendor = Koha::Acquisition::Booksellers->find($booksellerid); my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "acqui/z3950_search.tt", - query => $input, - type => "intranet", - flagsrequired => { acquisition => 'order_manage' }, + template_name => "acqui/z3950_search.tt", + query => $input, + type => "intranet", + flagsrequired => { acquisition => 'order_manage' }, } ); $template->param( - frameworkcode => $frameworkcode, - frameworks => $frameworks, - booksellerid => $booksellerid, - basketno => $basketno, - name => $vendor->name, - isbn => $isbn, - issn => $issn, - lccn => $lccn, - lccall => $lccall, - title => $title, - author => $author, - controlnumber=> $controlnumber, - biblionumber => $biblionumber, - dewey => $dewey, - subject => $subject, - srchany => $srchany, - stdid => $stdid, - publicationyear => $publicationyear, + frameworkcode => $frameworkcode, + frameworks => $frameworks, + booksellerid => $booksellerid, + basketno => $basketno, + name => $vendor->name, + isbn => $isbn, + issn => $issn, + lccn => $lccn, + lccall => $lccall, + title => $title, + author => $author, + controlnumber => $controlnumber, + biblionumber => $biblionumber, + dewey => $dewey, + subject => $subject, + srchany => $srchany, + stdid => $stdid, + publicationyear => $publicationyear, ); if ( $op ne "cud-do_search" ) { my $schema = Koha::Database->new()->schema(); - my $rs = $schema->resultset('Z3950server')->search( + my $rs = $schema->resultset('Z3950server')->search( { recordtype => 'biblio', - servertype => ['zed', 'sru'], + servertype => [ 'zed', 'sru' ], }, - { result_class => 'DBIx::Class::ResultClass::HashRefInflator', - order_by => ['rank', 'servername'], + { + result_class => 'DBIx::Class::ResultClass::HashRefInflator', + order_by => [ 'rank', 'servername' ], }, ); $template->param( - serverloop => [ $rs->all ], - opsearch => "cud-search", + serverloop => [ $rs->all ], + opsearch => "cud-search", ); output_html_with_http_headers $input, $cookie, $template->output; exit; } my @id = $input->multi_param('id'); -if (@id==0) { +if ( @id == 0 ) { $template->param( emptyserverlist => 1 ); output_html_with_http_headers $input, $cookie, $template->output; exit; } -my $pars= { - biblionumber => $biblionumber, - page => $page, - id => \@id, - isbn => $isbn, - issn => $issn, - title => $title, - author => $author, - dewey => $dewey, - subject => $subject, - lccall => $lccall, - controlnumber => $controlnumber, - stdid => $stdid, - srchany => $srchany, - publicationyear => $publicationyear, +my $pars = { + biblionumber => $biblionumber, + page => $page, + id => \@id, + isbn => $isbn, + issn => $issn, + title => $title, + author => $author, + dewey => $dewey, + subject => $subject, + lccall => $lccall, + controlnumber => $controlnumber, + stdid => $stdid, + srchany => $srchany, + publicationyear => $publicationyear, }; -Z3950Search($pars, $template); +Z3950Search( $pars, $template ); output_html_with_http_headers $input, $cookie, $template->output; diff --git a/admin/additional-fields.pl b/admin/additional-fields.pl index 11bf70814c..1e09d3c6da 100755 --- a/admin/additional-fields.pl +++ b/admin/additional-fields.pl @@ -18,7 +18,7 @@ use Modern::Perl; use CGI; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use Koha::AdditionalFields; @@ -28,19 +28,19 @@ my %flagsrequired; $flagsrequired{parameters} = 'manage_additional_fields'; my $tablename = $input->param('tablename'); -my $op = $input->param('op') // ( $tablename ? 'list' : 'list_tables' ); +my $op = $input->param('op') // ( $tablename ? 'list' : 'list_tables' ); -if( $op ne 'list_tables' ){ - $flagsrequired{acquisition} = 'order_manage' if $tablename eq 'aqbasket'; - $flagsrequired{serials} = 'edit_subscription' if $tablename eq 'subscription'; +if ( $op ne 'list_tables' ) { + $flagsrequired{acquisition} = 'order_manage' if $tablename eq 'aqbasket'; + $flagsrequired{serials} = 'edit_subscription' if $tablename eq 'subscription'; } my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "admin/additional-fields.tt", - query => $input, - type => "intranet", - flagsrequired => \%flagsrequired, + template_name => "admin/additional-fields.tt", + query => $input, + type => "intranet", + flagsrequired => \%flagsrequired, } ); @@ -48,12 +48,12 @@ my $field_id = $input->param('field_id'); my @messages; if ( $op eq 'cud-add' ) { - my $name = $input->param('name') // q{}; + my $name = $input->param('name') // q{}; my $authorised_value_category = $input->param('authorised_value_category'); - my $marcfield = $input->param('marcfield') // q{}; - my $marcfield_mode = $input->param('marcfield_mode') // 'get'; - my $searchable = $input->param('searchable') ? 1 : 0; - my $repeatable = $input->param('repeatable') ? 1 : 0; + my $marcfield = $input->param('marcfield') // q{}; + my $marcfield_mode = $input->param('marcfield_mode') // 'get'; + my $searchable = $input->param('searchable') ? 1 : 0; + my $repeatable = $input->param('repeatable') ? 1 : 0; if ( $field_id and $name ) { my $updated = 0; my $set_fields = { @@ -71,10 +71,10 @@ if ( $op eq 'cud-add' ) { $updated = $af->store ? 1 : 0; }; push @messages, { - code => 'cud-update', + code => 'cud-update', number => $updated, }; - } elsif ( $name ) { + } elsif ($name) { my $inserted = 0; my $set_fields = { tablename => $tablename, @@ -91,12 +91,12 @@ if ( $op eq 'cud-add' ) { $inserted = $af->store ? 1 : 0; }; push @messages, { - code => 'cud-insert', + code => 'cud-insert', number => $inserted, }; } else { push @messages, { - code => 'cud-insert', + code => 'cud-insert', number => 0, }; } @@ -110,7 +110,7 @@ if ( $op eq 'cud-delete' ) { $deleted = $af->delete; }; push @messages, { - code => 'cud-delete', + code => 'cud-delete', number => $deleted, }; $op = 'list'; @@ -118,7 +118,7 @@ if ( $op eq 'cud-delete' ) { if ( $op eq 'add_form' ) { my $field; - if ( $field_id ) { + if ($field_id) { $field = Koha::AdditionalFields->find($field_id); } @@ -135,9 +135,9 @@ if ( $op eq 'list' ) { } $template->param( - op => $op, + op => $op, tablename => $tablename, - messages => \@messages, + messages => \@messages, ); -output_html_with_http_headers $input, $cookie, $template->output; \ No newline at end of file +output_html_with_http_headers $input, $cookie, $template->output; diff --git a/admin/admin-home.pl b/admin/admin-home.pl index 40e3e4e2af..b649bf4f5b 100755 --- a/admin/admin-home.pl +++ b/admin/admin-home.pl @@ -17,8 +17,8 @@ use Modern::Perl; -use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use Koha::Plugins; diff --git a/admin/adveditorshortcuts.pl b/admin/adveditorshortcuts.pl index 8ca9969a90..23cd1b40cf 100755 --- a/admin/adveditorshortcuts.pl +++ b/admin/adveditorshortcuts.pl @@ -38,17 +38,18 @@ use Modern::Perl; use C4::Auth qw( get_template_and_user ); use C4::Context; use C4::Output qw( output_html_with_http_headers ); -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use Koha::KeyboardShortcuts; -my $input = CGI->new; -my $op = $input->param('op') || 'list'; +my $input = CGI->new; +my $op = $input->param('op') || 'list'; my ( $template, $loggedinuser, $cookie ) = get_template_and_user( - { template_name => "admin/adveditorshortcuts.tt", - query => $input, - type => "intranet", - flagsrequired => { parameters => 'manage_keyboard_shortcuts' }, + { + template_name => "admin/adveditorshortcuts.tt", + query => $input, + type => "intranet", + flagsrequired => { parameters => 'manage_keyboard_shortcuts' }, } ); @@ -60,15 +61,14 @@ if ( $op eq 'cud-save' ) { my %updated_shortcuts; @updated_shortcuts{@shortcut_names} = @shortcut_keys; - while ( my $shortcut = $shortcuts->next() ){ - $shortcut->shortcut_keys( $updated_shortcuts{$shortcut->shortcut_name} ); + while ( my $shortcut = $shortcuts->next() ) { + $shortcut->shortcut_keys( $updated_shortcuts{ $shortcut->shortcut_name } ); $shortcut->store(); } } - $template->param( - shortcuts => $shortcuts, + shortcuts => $shortcuts, ); output_html_with_http_headers $input, $cookie, $template->output; diff --git a/admin/aqbudgetperiods.pl b/admin/aqbudgetperiods.pl index c66969a21c..ebb017676c 100755 --- a/admin/aqbudgetperiods.pl +++ b/admin/aqbudgetperiods.pl @@ -46,52 +46,55 @@ script to administer the budget periods table use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use JSON qw( encode_json ); use Koha::Database; use C4::Koha; use C4::Context; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use C4::Acquisition; -use C4::Budgets qw( GetBudgetPeriod GetBudgetHierarchy GetBudgetPeriods ModBudgetPeriod AddBudgetPeriod GetBudgets DelBudgetPeriod CloneBudgetPeriod MoveOrders ); +use C4::Budgets + qw( GetBudgetPeriod GetBudgetHierarchy GetBudgetPeriods ModBudgetPeriod AddBudgetPeriod GetBudgets DelBudgetPeriod CloneBudgetPeriod MoveOrders ); use C4::Log qw(logaction); use Koha::Acquisition::Currencies; my $dbh = C4::Context->dbh; -my $input = CGI->new; +my $input = CGI->new; + +my $searchfield = $input->param('searchfield') // ''; +my $budget_period_id = $input->param('budget_period_id'); +my $op = $input->param('op') || "else"; -my $searchfield = $input->param('searchfield') // ''; -my $budget_period_id = $input->param('budget_period_id'); -my $op = $input->param('op')||"else"; #my $sort1_authcat = $input->param('sort1_authcat'); #my $sort2_authcat = $input->param('sort2_authcat'); # get only the columns of aqbudgetperiods in budget_period_hashref my @columns = Koha::Database->new()->schema->source('Aqbudgetperiod')->columns; -my $budget_period_hashref = { map { join(' ',@columns) =~ /$_/ ? ( $_ => scalar $input->param($_) ) : () } keys( %{$input->Vars()} ) } ; +my $budget_period_hashref = + { map { join( ' ', @columns ) =~ /$_/ ? ( $_ => scalar $input->param($_) ) : () } keys( %{ $input->Vars() } ) }; $budget_period_hashref->{budget_period_startdate} = $input->param('budget_period_startdate'); $budget_period_hashref->{budget_period_enddate} = $input->param('budget_period_enddate'); $searchfield =~ s/\,//g; -my ($template, $borrowernumber, $cookie, $staff_flags ) = get_template_and_user( +my ( $template, $borrowernumber, $cookie, $staff_flags ) = get_template_and_user( { - template_name => "admin/aqbudgetperiods.tt", - query => $input, - type => "intranet", - flagsrequired => { acquisition => 'period_manage' }, + template_name => "admin/aqbudgetperiods.tt", + query => $input, + type => "intranet", + flagsrequired => { acquisition => 'period_manage' }, } ); - # This is used in incbudgets-active-currency.inc my $active_currency = Koha::Acquisition::Currencies->get_active; -if ( $active_currency ) { - $template->param( symbol => $active_currency->symbol, - currency => $active_currency->currency - ); +if ($active_currency) { + $template->param( + symbol => $active_currency->symbol, + currency => $active_currency->currency + ); } # ADD OR MODIFY A BUDGET PERIOD - BUILD SCREEN @@ -100,27 +103,27 @@ if ( $op eq 'add_form' ) { ## get information about the budget period that must be modified if ($budget_period_id) { # MOD - my $budgetperiod_hash=GetBudgetPeriod($budget_period_id); + my $budgetperiod_hash = GetBudgetPeriod($budget_period_id); + # get dropboxes - $template->param( - %$budgetperiod_hash - ); - } # IF-MOD -} + $template->param(%$budgetperiod_hash); + } # IF-MOD -elsif ( $op eq 'cud-add_validate' ) { +} elsif ( $op eq 'cud-add_validate' ) { ## add or modify a budget period (confirmation) ## update budget period data if ( $budget_period_id ne '' ) { + # Grab the previous values so we can log them - my $budgetperiod_old=GetBudgetPeriod($budget_period_id); - $$budget_period_hashref{$_}||=0 for qw(budget_period_active budget_period_locked); - my $status=ModBudgetPeriod($budget_period_hashref); + my $budgetperiod_old = GetBudgetPeriod($budget_period_id); + $$budget_period_hashref{$_} ||= 0 for qw(budget_period_active budget_period_locked); + my $status = ModBudgetPeriod($budget_period_hashref); + # Log the budget modification - if (C4::Context->preference("AcquisitionLog")) { - my $diff = 0 - ($budgetperiod_old->{budget_period_total} - $budget_period_hashref->{budget_period_total}); + if ( C4::Context->preference("AcquisitionLog") ) { + my $diff = 0 - ( $budgetperiod_old->{budget_period_total} - $budget_period_hashref->{budget_period_total} ); my $infos = { budget_period_startdate => $input->param('budget_period_startdate'), budget_period_enddate => $input->param('budget_period_enddate'), @@ -137,17 +140,16 @@ elsif ( $op eq 'cud-add_validate' ) { encode_json($infos) ); } + } else { # ELSE ITS AN ADD + my $budget_period_id = AddBudgetPeriod($budget_period_hashref); } - else { # ELSE ITS AN ADD - my $budget_period_id=AddBudgetPeriod($budget_period_hashref); - } - $op='else'; + $op = 'else'; } #-------------------------------------------------- elsif ( $op eq 'delete_confirm' ) { ## delete a budget period (preparation) - my $funds = GetBudgets({ budget_period_id => $budget_period_id }); + my $funds = GetBudgets( { budget_period_id => $budget_period_id } ); my $fund_count = scalar @$funds; if ( $fund_count > 0 ) { $template->param( funds_exist => 1 ); @@ -155,76 +157,70 @@ elsif ( $op eq 'delete_confirm' ) { #$total = number of records linked to the record that must be deleted my $total = 0; - my $data = GetBudgetPeriod( $budget_period_id); - $template->param( - %$data - ); -} + my $data = GetBudgetPeriod($budget_period_id); + $template->param(%$data); -elsif ( $op eq 'cud-delete_confirmed' ) { +} elsif ( $op eq 'cud-delete_confirmed' ) { ## confirm no funds have been added to budget - my $funds = GetBudgets({ budget_period_id => $budget_period_id }); + my $funds = GetBudgets( { budget_period_id => $budget_period_id } ); my $fund_count = scalar @$funds; if ( $fund_count > 0 ) { $template->param( failed_delete_funds_exist => 1 ); } else { ## delete the budget period record - my $data = GetBudgetPeriod( $budget_period_id); + my $data = GetBudgetPeriod($budget_period_id); DelBudgetPeriod($budget_period_id); } - $op='else'; + $op = 'else'; } # display the form for duplicating -elsif ( $op eq 'duplicate_form'){ +elsif ( $op eq 'duplicate_form' ) { my $budgetperiod = GetBudgetPeriod($budget_period_id); $template->param( - 'duplicate_form' => '1', + 'duplicate_form' => '1', 'budget_period_id' => $budget_period_id, - 'budgetperiod' => $budgetperiod, + 'budgetperiod' => $budgetperiod, ); } # handle the actual duplication -elsif ( $op eq 'cud-duplicate_budget' ){ - die "please specify a budget period id\n" if( !defined $budget_period_id || $budget_period_id eq '' ); +elsif ( $op eq 'cud-duplicate_budget' ) { + die "please specify a budget period id\n" if ( !defined $budget_period_id || $budget_period_id eq '' ); - my $budget_period_startdate = $input->param('budget_period_startdate'); - my $budget_period_enddate = $input->param('budget_period_enddate'); - my $budget_period_description = $input->param('budget_period_description'); - my $amount_change_percentage = $input->param('amount_change_percentage'); - my $amount_change_round_increment = $input->param('amount_change_round_increment'); + my $budget_period_startdate = $input->param('budget_period_startdate'); + my $budget_period_enddate = $input->param('budget_period_enddate'); + my $budget_period_description = $input->param('budget_period_description'); + my $amount_change_percentage = $input->param('amount_change_percentage'); + my $amount_change_round_increment = $input->param('amount_change_round_increment'); my $mark_original_budget_as_inactive = $input->param('mark_original_budget_as_inactive'); - my $reset_all_budgets = $input->param('reset_all_budgets'); + my $reset_all_budgets = $input->param('reset_all_budgets'); my $new_budget_period_id = CloneBudgetPeriod( { - budget_period_id => $budget_period_id, - budget_period_startdate => $budget_period_startdate, - budget_period_enddate => $budget_period_enddate, - budget_period_description => $budget_period_description, - amount_change_percentage => $amount_change_percentage, - amount_change_round_increment => $amount_change_round_increment, + budget_period_id => $budget_period_id, + budget_period_startdate => $budget_period_startdate, + budget_period_enddate => $budget_period_enddate, + budget_period_description => $budget_period_description, + amount_change_percentage => $amount_change_percentage, + amount_change_round_increment => $amount_change_round_increment, mark_original_budget_as_inactive => $mark_original_budget_as_inactive, - reset_all_budgets => $reset_all_budgets, + reset_all_budgets => $reset_all_budgets, } ); # display the list of budgets $op = 'else'; -} -elsif ( $op eq 'close_form' ) { +} elsif ( $op eq 'close_form' ) { my $budget_period = GetBudgetPeriod($budget_period_id); - my $active_budget_periods = - GetBudgetPeriods( { budget_period_active => 1 } ); + my $active_budget_periods = GetBudgetPeriods( { budget_period_active => 1 } ); # Remove the budget period from the list $active_budget_periods = - [ map { ( $_->{budget_period_id} == $budget_period_id ) ? () : $_ } - @$active_budget_periods ]; + [ map { ( $_->{budget_period_id} == $budget_period_id ) ? () : $_ } @$active_budget_periods ]; my $budgets_to_move = GetBudgetHierarchy($budget_period_id); @@ -243,17 +239,15 @@ elsif ( $op eq 'close_form' ) { } $template->param( - close_form => 1, - budget_period_id => $budget_period_id, - budget_period_description => - $budget_period->{budget_period_description}, + close_form => 1, + budget_period_id => $budget_period_id, + budget_period_description => $budget_period->{budget_period_description}, budget_periods => $active_budget_periods, budgets_to_move => $budgets_to_move, number_of_unreceived_orders => $number_of_unreceived_orders, ); -} -elsif ( $op eq 'cud-close_confirmed' ) { +} elsif ( $op eq 'cud-close_confirmed' ) { my $to_budget_period_id = $input->param('to_budget_period_id'); my $move_remaining_unspent = $input->param('move_remaining_unspent'); my $report = MoveOrders( @@ -267,12 +261,12 @@ elsif ( $op eq 'cud-close_confirmed' ) { my $from_budget_period = GetBudgetPeriod($budget_period_id); my $to_budget_period = GetBudgetPeriod($to_budget_period_id); $template->param( - closed => 1, - budget_period_id => $from_budget_period->{budget_period_id}, + closed => 1, + budget_period_id => $from_budget_period->{budget_period_id}, budget_period_description => $from_budget_period->{budget_period_description}, - from_budget_period => $from_budget_period, - to_budget_period => $to_budget_period, - report => $report, + from_budget_period => $from_budget_period, + to_budget_period => $to_budget_period, + report => $report, ); } @@ -280,12 +274,13 @@ elsif ( $op eq 'cud-close_confirmed' ) { # ------------------------------------------------------------------- # display the list of budget periods -my $activepage = $input->param('apage') || 1; +my $activepage = $input->param('apage') || 1; my $inactivepage = $input->param('ipage') || 1; + # Get active budget periods my $results = GetBudgetPeriods( { budget_period_active => 1 }, - { -asc => 'budget_period_description' }, + { -asc => 'budget_period_description' }, ); my @period_active_loop; @@ -293,7 +288,7 @@ my @period_active_loop; foreach my $result ( @{$results} ) { my $budgetperiod = $result; $budgetperiod->{budget_active} = 1; - my $funds = GetBudgets({ budget_period_id => $budgetperiod->{budget_period_id} }); + my $funds = GetBudgets( { budget_period_id => $budgetperiod->{budget_period_id} } ); $budgetperiod->{count} = scalar @$funds; push( @period_active_loop, $budgetperiod ); } @@ -301,24 +296,24 @@ foreach my $result ( @{$results} ) { # Get inactive budget periods $results = GetBudgetPeriods( { budget_period_active => 0 }, - { -desc => 'budget_period_enddate' }, + { -desc => 'budget_period_enddate' }, ); my @period_inactive_loop; foreach my $result ( @{$results} ) { my $budgetperiod = $result; $budgetperiod->{budget_active} = 1; - my $funds = GetBudgets({ budget_period_id => $budgetperiod->{budget_period_id} }); + my $funds = GetBudgets( { budget_period_id => $budgetperiod->{budget_period_id} } ); $budgetperiod->{count} = scalar @$funds; push( @period_inactive_loop, $budgetperiod ); } my $tab = $input->param('tab') ? $input->param('tab') - 1 : 0; $template->param( - period_active_loop => \@period_active_loop, - period_inactive_loop => \@period_inactive_loop, - tab => $tab, + period_active_loop => \@period_active_loop, + period_inactive_loop => \@period_inactive_loop, + tab => $tab, ); -$template->param($op=>1); +$template->param( $op => 1 ); output_html_with_http_headers $input, $cookie, $template->output; diff --git a/admin/aqbudgets.pl b/admin/aqbudgets.pl index 6a1df616fc..f6901a352d 100755 --- a/admin/aqbudgets.pl +++ b/admin/aqbudgets.pl @@ -24,7 +24,7 @@ use Modern::Perl; use CGI qw ( -utf8 ); use Koha::Database; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Budgets qw( AddBudget BudgetHasChildren @@ -46,21 +46,23 @@ use Koha::Acquisition::Currencies; use Koha::Patrons; my $input = CGI->new; -my $dbh = C4::Context->dbh; +my $dbh = C4::Context->dbh; -my ($template, $borrowernumber, $cookie, $staffflags ) = get_template_and_user( - { template_name => "admin/aqbudgets.tt", - query => $input, - type => "intranet", - flagsrequired => { acquisition => 'budget_manage' }, +my ( $template, $borrowernumber, $cookie, $staffflags ) = get_template_and_user( + { + template_name => "admin/aqbudgets.tt", + query => $input, + type => "intranet", + flagsrequired => { acquisition => 'budget_manage' }, } ); my $active_currency = Koha::Acquisition::Currencies->get_active; -if ( $active_currency ) { - $template->param( symbol => $active_currency->symbol, - currency => $active_currency->currency - ); +if ($active_currency) { + $template->param( + symbol => $active_currency->symbol, + currency => $active_currency->currency + ); } my $op = $input->param('op') || 'list'; @@ -69,54 +71,54 @@ my $op = $input->param('op') || 'list'; my $show_mine = $input->param('show_mine') // 0; # IF USER DOESN'T HAVE PERM FOR AN 'ADD', THEN REDIRECT TO THE DEFAULT VIEW... -if (not defined $template->{VARS}->{'CAN_user_acquisition_budget_add_del'} - and $op eq 'add_form') +if ( not defined $template->{VARS}->{'CAN_user_acquisition_budget_add_del'} + and $op eq 'add_form' ) { $op = 'list'; } # get only the columns of aqbudgets in budget_hash my @columns = Koha::Database->new()->schema->source('Aqbudget')->columns; -my $budget_hash = { map { join(' ',@columns) =~ /$_/ ? ( $_ => scalar $input->param($_) ) : () } keys( %{$input->Vars()}) } ; - -my $budget_id = $input->param('budget_id'); -my $budget_period_id = $input->param('budget_period_id'); -my $budget_permission = $input->param('budget_permission'); -my $budget_users_ids = $input->param('budget_users_ids'); -my $filter_budgetbranch = $input->param('filter_budgetbranch') // ''; -my $filter_budgetname = $input->param('filter_budgetname'); +my $budget_hash = + { map { join( ' ', @columns ) =~ /$_/ ? ( $_ => scalar $input->param($_) ) : () } keys( %{ $input->Vars() } ) }; +my $budget_id = $input->param('budget_id'); +my $budget_period_id = $input->param('budget_period_id'); +my $budget_permission = $input->param('budget_permission'); +my $budget_users_ids = $input->param('budget_users_ids'); +my $filter_budgetbranch = $input->param('filter_budgetbranch') // ''; +my $filter_budgetname = $input->param('filter_budgetname'); # ' ------- get periods stuff ------------------' # IF PERIODID IS DEFINED, GET THE PERIOD - ELSE JUST GET THE ACTIVE PERIOD BY DEFAULT my $period; -if ( $budget_period_id ) { - $period = GetBudgetPeriod( $budget_period_id ); +if ($budget_period_id) { + $period = GetBudgetPeriod($budget_period_id); } # ------- get periods stuff ------------------ $template->param( - show_mine => $show_mine, - op => $op, + show_mine => $show_mine, + op => $op, selected_branchcode => $filter_budgetbranch, ); my $budget; -$template->param(auth_cats_loop => GetBudgetAuthCats( $budget_period_id )) +$template->param( auth_cats_loop => GetBudgetAuthCats($budget_period_id) ) if $budget_period_id; # Used to create form to add or modify a record -if ($op eq 'add_form') { +if ( $op eq 'add_form' ) { #### ------------------- ADD_FORM ------------------------- # if no buget_id is passed then its an add # pass the period_id to build the dropbox - because we only want to show budgets from this period my $dropbox_disabled; - if (defined $budget_id ) { ### MOD + if ( defined $budget_id ) { ### MOD $budget = GetBudget($budget_id); - if (!CanUserModifyBudget($borrowernumber, $budget, $staffflags)) { - $template->param(error_not_authorised_to_modify => 1); + if ( !CanUserModifyBudget( $borrowernumber, $budget, $staffflags ) ) { + $template->param( error_not_authorised_to_modify => 1 ); output_html_with_http_headers $input, $cookie, $template->output; exit; } @@ -129,18 +131,19 @@ if ($op eq 'add_form') { # build budget hierarchy my %labels; my @values; - my $hier = GetBudgetHierarchy($$period{budget_period_id}); + my $hier = GetBudgetHierarchy( $$period{budget_period_id} ); foreach my $r (@$hier) { $labels{"$r->{budget_id}"} = $r->{budget_code}; push @values, $r->{budget_id}; } push @values, ''; + # if no buget_id is passed then its an add my $budget_parent; my $budget_parent_id; - if ($budget){ - $budget_parent_id = $budget->{'budget_parent_id'} ; - }else{ + if ($budget) { + $budget_parent_id = $budget->{'budget_parent_id'}; + } else { $budget_parent_id = $input->param('budget_parent_id'); } $budget_parent = GetBudget($budget_parent_id); @@ -151,24 +154,24 @@ if ($op eq 'add_form') { sort2_auth => $budget->{sort2_authcat}, ); - if($budget->{'budget_permission'}){ - my $budget_permission = "budget_perm_".$budget->{'budget_permission'}; - $template->param($budget_permission => 1); + if ( $budget->{'budget_permission'} ) { + my $budget_permission = "budget_perm_" . $budget->{'budget_permission'}; + $template->param( $budget_permission => 1 ); } if ($budget) { - my @budgetusers = GetBudgetUsers($budget->{budget_id}); + my @budgetusers = GetBudgetUsers( $budget->{budget_id} ); my @budgetusers_loop; foreach my $borrowernumber (@budgetusers) { - my $patron = Koha::Patrons->find( $borrowernumber ); + my $patron = Koha::Patrons->find($borrowernumber); push @budgetusers_loop, { - firstname => $patron->firstname, # FIXME Should pass the patron object - surname => $patron->surname, + firstname => $patron->firstname, # FIXME Should pass the patron object + surname => $patron->surname, borrowernumber => $borrowernumber }; } $template->param( - budget_users => \@budgetusers_loop, + budget_users => \@budgetusers_loop, budget_users_ids => join ':', @budgetusers ); } @@ -176,16 +179,17 @@ if ($op eq 'add_form') { # if no buget_id is passed then its an add $template->param( budget_has_children => BudgetHasChildren( $budget->{budget_id} ), - budget_parent_id => $budget_parent->{'budget_id'}, - budget_parent_name => $budget_parent->{'budget_name'}, - %$period, - %$budget, + budget_parent_id => $budget_parent->{'budget_id'}, + budget_parent_name => $budget_parent->{'budget_name'}, + %$period, + %$budget, ); - # END $OP eq ADD_FORM -#---------------------- DEFAULT DISPLAY BELOW --------------------- -# called by default form, used to confirm deletion of data in DB -} elsif ($op eq 'delete_confirm') { + # END $OP eq ADD_FORM + #---------------------- DEFAULT DISPLAY BELOW --------------------- + + # called by default form, used to confirm deletion of data in DB +} elsif ( $op eq 'delete_confirm' ) { my $budget = GetBudget($budget_id); $template->param( @@ -194,36 +198,41 @@ if ($op eq 'add_form') { budget_name => $budget->{'budget_name'}, budget_amount => $budget->{'budget_amount'}, ); - # END $OP eq DELETE_CONFIRM -# called by delete_confirm, used to effectively confirm deletion of data in DB + + # END $OP eq DELETE_CONFIRM + # called by delete_confirm, used to effectively confirm deletion of data in DB } elsif ( $op eq 'cud-delete_confirmed' ) { - if ( BudgetHasChildren( $budget_id ) ) { + if ( BudgetHasChildren($budget_id) ) { + # We should never be here, the interface does not provide this action. die("Delete a fund with children is not possible"); } my $rc = DelBudget($budget_id); $op = 'list'; -} elsif( $op eq 'cud-add_validate' ) { +} elsif ( $op eq 'cud-add_validate' ) { my @budgetusersid; - if (defined $budget_users_ids){ - @budgetusersid = split(':', $budget_users_ids); + if ( defined $budget_users_ids ) { + @budgetusersid = split( ':', $budget_users_ids ); } my $budget_modified = 0; - if (defined $budget_id) { - if (CanUserModifyBudget($borrowernumber, $budget_hash->{budget_id}, - $staffflags) - ) { - ModBudget( $budget_hash ); - ModBudgetUsers($budget_hash->{budget_id}, @budgetusersid); + if ( defined $budget_id ) { + if ( + CanUserModifyBudget( + $borrowernumber, $budget_hash->{budget_id}, + $staffflags + ) + ) + { + ModBudget($budget_hash); + ModBudgetUsers( $budget_hash->{budget_id}, @budgetusersid ); $budget_modified = 1; - } - else { - $template->param(error_not_authorised_to_modify => 1); + } else { + $template->param( error_not_authorised_to_modify => 1 ); } } else { - $budget_hash->{budget_id} = AddBudget( $budget_hash ); - ModBudgetUsers($budget_hash->{budget_id}, @budgetusersid); + $budget_hash->{budget_id} = AddBudget($budget_hash); + ModBudgetUsers( $budget_hash->{budget_id}, @budgetusersid ); $budget_modified = 1; } @@ -240,63 +249,64 @@ if ( $op eq 'list' ) { %$period, ); - my @budgets = @{ - GetBudgetHierarchy( $$period{budget_period_id}, undef, ( $show_mine ? $borrowernumber : 0 )) - }; + my @budgets = @{ GetBudgetHierarchy( $$period{budget_period_id}, undef, ( $show_mine ? $borrowernumber : 0 ) ) }; my $period_total = 0; - my ($period_alloc_total, $spent_total, $ordered_total, $available_total) = (0,0,0,0); + my ( $period_alloc_total, $spent_total, $ordered_total, $available_total ) = ( 0, 0, 0, 0 ); - #This Looks WEIRD to me : should budgets be filtered in such a way ppl who donot own it would not see the amount spent on the budget by others ? + #This Looks WEIRD to me : should budgets be filtered in such a way ppl who donot own it would not see the amount spent on the budget by others ? my @budgets_to_display; foreach my $budget (@budgets) { + # PERMISSIONS - next unless CanUserUseBudget($borrowernumber, $budget, $staffflags); - unless(CanUserModifyBudget($borrowernumber, $budget, $staffflags)) { + next unless CanUserUseBudget( $borrowernumber, $budget, $staffflags ); + unless ( CanUserModifyBudget( $borrowernumber, $budget, $staffflags ) ) { $budget->{'budget_lock'} = 1; } # if a budget search doesn't match, next if ($filter_budgetname) { next - unless $budget->{budget_code} =~ m/$filter_budgetname/i - || $budget->{budget_name} =~ m/$filter_budgetname/i; + unless $budget->{budget_code} =~ m/$filter_budgetname/i + || $budget->{budget_name} =~ m/$filter_budgetname/i; } - if ($filter_budgetbranch ) { - next unless $budget->{budget_branchcode} eq $filter_budgetbranch; + if ($filter_budgetbranch) { + next unless $budget->{budget_branchcode} eq $filter_budgetbranch; } ## TOTALS - $budget->{'budget_remaining'} = $budget->{'budget_amount'} - $budget->{'budget_spent'} - $budget->{budget_ordered}; + $budget->{'budget_remaining'} = + $budget->{'budget_amount'} - $budget->{'budget_spent'} - $budget->{budget_ordered}; $budget->{'total_remaining'} = $budget->{'budget_amount'} - $budget->{'total_spent'} - $budget->{total_ordered}; + # adds to total - only if budget is a 'top-level' budget unless ( defined $budget->{budget_parent_id} ) { $period_alloc_total += $budget->{'budget_amount'}; - $spent_total += $budget->{total_spent}; - $ordered_total += $budget->{total_ordered}; - $available_total += $budget->{total_remaining}; + $spent_total += $budget->{total_spent}; + $ordered_total += $budget->{total_ordered}; + $available_total += $budget->{total_remaining}; } -# if amount == 0 don't display... + # if amount == 0 don't display... delete $budget->{'budget_unalloc_sublevel'} - if (!defined $budget->{'budget_unalloc_sublevel'} - or $budget->{'budget_unalloc_sublevel'} == 0); + if ( !defined $budget->{'budget_unalloc_sublevel'} + or $budget->{'budget_unalloc_sublevel'} == 0 ); # Value of budget_spent equals 0 instead of undefined value - $budget->{budget_spent} = 0 unless defined($budget->{budget_spent}); - $budget->{budget_ordered} = 0 unless defined($budget->{budget_ordered}); + $budget->{budget_spent} = 0 unless defined( $budget->{budget_spent} ); + $budget->{budget_ordered} = 0 unless defined( $budget->{budget_ordered} ); #Make a list of parents of the bugdet my @budget_hierarchy; - push @budget_hierarchy, { element_name => $budget->{"budget_name"}, element_id => $budget->{"budget_id"} }; + push @budget_hierarchy, { element_name => $budget->{"budget_name"}, element_id => $budget->{"budget_id"} }; my $parent_id = $budget->{"budget_parent_id"}; while ($parent_id) { my $parent = GetBudget($parent_id); push @budget_hierarchy, { element_name => $parent->{"budget_name"}, element_id => $parent->{"budget_id"} }; $parent_id = $parent->{"budget_parent_id"}; } - push @budget_hierarchy, { element_name => $period->{"budget_period_description"} }; + push @budget_hierarchy, { element_name => $period->{"budget_period_description"} }; @budget_hierarchy = reverse(@budget_hierarchy); $budget->{budget_hierarchy} = \@budget_hierarchy; @@ -310,17 +320,17 @@ if ( $op eq 'list' ) { my $periods = GetBudgetPeriods(); $template->param( - op => 'list', - budgets => \@budgets_to_display, - periods => $periods, - budget_period_total => $budget_period_total, - period_alloc_total => $period_alloc_total, - spent_total => $spent_total, - ordered_total => $ordered_total, - available_total => $available_total, - filter_budgetname => $filter_budgetname, + op => 'list', + budgets => \@budgets_to_display, + periods => $periods, + budget_period_total => $budget_period_total, + period_alloc_total => $period_alloc_total, + spent_total => $spent_total, + ordered_total => $ordered_total, + available_total => $available_total, + filter_budgetname => $filter_budgetname, ); -} #---- END list +} #---- END list output_html_with_http_headers $input, $cookie, $template->output; diff --git a/admin/aqcontract.pl b/admin/aqcontract.pl index edb71f583a..5f1975a68f 100755 --- a/admin/aqcontract.pl +++ b/admin/aqcontract.pl @@ -23,8 +23,8 @@ use Modern::Perl; use CGI qw ( -utf8 ); use C4::Context; -use C4::Auth qw( get_template_and_user ); -use C4::Output qw( output_html_with_http_headers ); +use C4::Auth qw( get_template_and_user ); +use C4::Output qw( output_html_with_http_headers ); use C4::Contract qw( AddContract DelContract @@ -41,34 +41,33 @@ my $contractnumber = $input->param('contractnumber'); my $booksellerid = $input->param('booksellerid'); my $op = $input->param('op') || 'list'; -my $bookseller = Koha::Acquisition::Booksellers->find( $booksellerid ); +my $bookseller = Koha::Acquisition::Booksellers->find($booksellerid); my ( $template, $loggedinuser, $cookie ) = get_template_and_user( - { template_name => "admin/aqcontract.tt", - query => $input, - type => "intranet", - flagsrequired => { acquisition => 'contracts_manage' }, + { + template_name => "admin/aqcontract.tt", + query => $input, + type => "intranet", + flagsrequired => { acquisition => 'contracts_manage' }, } ); $template->param( - contractnumber => $contractnumber, - booksellerid => $booksellerid, - booksellername => $bookseller->name, - basketcount => $bookseller->baskets->count, - active => $bookseller->active, - subscriptioncount => $bookseller->subscriptions->count, + contractnumber => $contractnumber, + booksellerid => $booksellerid, + booksellername => $bookseller->name, + basketcount => $bookseller->baskets->count, + active => $bookseller->active, + subscriptioncount => $bookseller->subscriptions->count, ); #ADD_FORM: called if $op is 'add_form'. Used to create form to add or modify a record if ( $op eq 'add_form' ) { $template->param( add_form => 1 ); - # if contractnumber exists, it's a modify action, so read values to modify... + # if contractnumber exists, it's a modify action, so read values to modify... if ($contractnumber) { - my $contract = GetContract({ - contractnumber => $contractnumber - }); + my $contract = GetContract( { contractnumber => $contractnumber } ); $template->param( contractnumber => $contract->{contractnumber}, @@ -79,16 +78,17 @@ if ( $op eq 'add_form' ) { ); } else { $template->param( - contractnumber => undef, - contractname => undef, - contractdescription => undef, - contractstartdate => undef, - contractenddate => undef, + contractnumber => undef, + contractname => undef, + contractdescription => undef, + contractstartdate => undef, + contractenddate => undef, ); } # END $OP eq ADD_FORM } + #ADD_VALIDATE: called by add_form, used to insert/modify data in DB elsif ( $op eq 'cud-add_validate' ) { ## Please see file perltidy.ERR @@ -96,30 +96,34 @@ elsif ( $op eq 'cud-add_validate' ) { my $is_a_modif = $input->param("is_a_modif"); my $contractstart_dt = $input->param('contractstartdate'); - my $contractend_dt = $input->param('contractenddate'); + my $contractend_dt = $input->param('contractenddate'); unless ( $contractstart_dt and $contractend_dt ) { my $today = dt_from_string; $contractstart_dt ||= $today; $contractend_dt ||= $today; } - if ( $is_a_modif ) { - ModContract({ - contractstartdate => $contractstart_dt, - contractenddate => $contractend_dt, - contractname => scalar $input->param('contractname'), - contractdescription => scalar $input->param('contractdescription'), - booksellerid => scalar $input->param('booksellerid'), - contractnumber => scalar $input->param('contractnumber'), - }); + if ($is_a_modif) { + ModContract( + { + contractstartdate => $contractstart_dt, + contractenddate => $contractend_dt, + contractname => scalar $input->param('contractname'), + contractdescription => scalar $input->param('contractdescription'), + booksellerid => scalar $input->param('booksellerid'), + contractnumber => scalar $input->param('contractnumber'), + } + ); } else { - AddContract({ - contractname => scalar $input->param('contractname'), - contractdescription => scalar $input->param('contractdescription'), - booksellerid => scalar $input->param('booksellerid'), - contractstartdate => scalar $input->param('contractstartdate'), - contractenddate => scalar $input->param('contractenddate'), - }); + AddContract( + { + contractname => scalar $input->param('contractname'), + contractdescription => scalar $input->param('contractdescription'), + booksellerid => scalar $input->param('booksellerid'), + contractstartdate => scalar $input->param('contractstartdate'), + contractenddate => scalar $input->param('contractenddate'), + } + ); } print $input->redirect("/cgi-bin/koha/acqui/supplier.pl?booksellerid=$booksellerid"); @@ -127,6 +131,7 @@ elsif ( $op eq 'cud-add_validate' ) { # END $OP eq ADD_VALIDATE } + #DELETE_CONFIRM: called by default form, used to confirm deletion of data in DB elsif ( $op eq 'delete_confirm' ) { $template->param( delete_confirm => 1 ); @@ -143,11 +148,12 @@ elsif ( $op eq 'delete_confirm' ) { # END $OP eq DELETE_CONFIRM } + #DELETE_CONFIRMED: called by delete_confirm, used to effectively confirm deletion of data in DB elsif ( $op eq 'cud-delete_confirmed' ) { my $deleted = DelContract( { contractnumber => $contractnumber } ); - if ( $deleted ) { + if ($deleted) { print $input->redirect("/cgi-bin/koha/acqui/supplier.pl?booksellerid=$booksellerid"); exit; } else { @@ -157,14 +163,15 @@ elsif ( $op eq 'cud-delete_confirmed' ) { # END $OP eq LIST } + # DEFAULT: Builds a list of contracts and displays them if ( $op eq 'list' ) { - $template->param(else => 1); + $template->param( else => 1 ); # get contracts - my @contracts = @{GetContracts( { booksellerid => $booksellerid } )}; + my @contracts = @{ GetContracts( { booksellerid => $booksellerid } ) }; - $template->param(loop => \@contracts); + $template->param( loop => \@contracts ); #---- END $OP eq DEFAULT } diff --git a/admin/aqplan.pl b/admin/aqplan.pl index b9b4121500..c155b7d088 100755 --- a/admin/aqplan.pl +++ b/admin/aqplan.pl @@ -21,8 +21,8 @@ # This software is placed under the gnu General Public License, v2 (http://www.gnu.org/licenses/gpl.html) use Modern::Perl; -use CGI qw ( -utf8 ); -use Date::Calc qw( Delta_YMD ); +use CGI qw ( -utf8 ); +use Date::Calc qw( Delta_YMD ); use Date::Manip qw( DateCalc UnixDate ); use Text::CSV_XS; @@ -39,7 +39,7 @@ use C4::Budgets qw( ); use C4::Context; use C4::Output qw( output_html_with_http_headers ); -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use Koha::Acquisition::Currencies; our $input = CGI->new; @@ -48,37 +48,37 @@ our $input = CGI->new; my $dbh = C4::Context->dbh; my ( $template, $borrowernumber, $cookie, $staff_flags ) = get_template_and_user( - { template_name => "admin/aqplan.tt", - query => $input, - type => "intranet", - flagsrequired => { acquisition => 'planning_manage' }, + { + template_name => "admin/aqplan.tt", + query => $input, + type => "intranet", + flagsrequired => { acquisition => 'planning_manage' }, } ); my $budget_period_id = $input->param('budget_period_id'); + # ' ------- get periods stuff ------------------' # IF PERIOD_ID IS DEFINED, GET THE PERIOD - ELSE GET THE ACTIVE PERIOD BY DEFAULT -my $period = GetBudgetPeriod($budget_period_id); -my $count = GetPeriodsCount(); +my $period = GetBudgetPeriod($budget_period_id); +my $count = GetPeriodsCount(); my $active_currency = Koha::Acquisition::Currencies->get_active; -if ( $active_currency ) { - $template->param( symbol => $active_currency->symbol, - currency => $active_currency->currency, - ); +if ($active_currency) { + $template->param( + symbol => $active_currency->symbol, + currency => $active_currency->currency, + ); } $template->param( period_button_only => 1 ) if $count == 0; - - # authcats_loop populates the YUI planning button -my $auth_cats_loop = GetBudgetAuthCats($budget_period_id); -$budget_period_id = $period->{'budget_period_id'}; +my $auth_cats_loop = GetBudgetAuthCats($budget_period_id); +$budget_period_id = $period->{'budget_period_id'}; my $budget_period_startdate = $period->{'budget_period_startdate'}; my $budget_period_enddate = $period->{'budget_period_enddate'}; my $budget_period_locked = $period->{'budget_period_locked'}; my $budget_period_description = $period->{'budget_period_description'}; - $template->param( budget_period_id => $budget_period_id, budget_period_locked => $budget_period_locked, @@ -88,7 +88,6 @@ $template->param( # ------- get periods stuff ------------------ - my $borrower_branchcode = my $branch_code = C4::Context->userenv->{'branch'}; my $authcat = $input->param('authcat'); @@ -96,18 +95,18 @@ my $show_active = $input->param('show_active') // 0; my $show_actual = $input->param('show_actual'); my $show_percent = $input->param('show_percent'); my $output = $input->param("output") // q{}; -our $basename = $input->param("basename"); -our $del = C4::Context->csv_delimiter(scalar $input->param("sep")); +our $basename = $input->param("basename"); +our $del = C4::Context->csv_delimiter( scalar $input->param("sep") ); -my $show_mine = $input->param('show_mine') ; +my $show_mine = $input->param('show_mine'); -my @hide_cols = $input->multi_param('hide_cols'); +my @hide_cols = $input->multi_param('hide_cols'); -if ( $budget_period_locked == 1 && not defined $show_actual ) { - $show_actual = 1; +if ( $budget_period_locked == 1 && not defined $show_actual ) { + $show_actual = 1; } -$authcat = 'Asort1' if not defined $authcat; # defaults to Asort if no authcat given +$authcat = 'Asort1' if not defined $authcat; # defaults to Asort if no authcat given my $budget_id = $input->param('budget_id'); my $op = $input->param("op") // q{}; @@ -130,24 +129,28 @@ push( @category_list, $_ ) foreach @$auth_cats_loop; #reorder the list @category_list = sort { $a cmp $b } @category_list; -$template->param( authcat_dropbox => { - values => \@category_list, +$template->param( + authcat_dropbox => { + values => \@category_list, default => $authcat, - }); + } +); my @budgets = @$budgets_ref; my @authvals; my %labels; my @names = $input->multi_param(); + # ------------------------------------------------------------ if ( $op eq 'cud-save' ) { + #get budgets my ( @buds, @auth_values ); foreach my $n (@names) { next if $n =~ m/^[^0-9]/; my @moo = split( ',', $n ); - push @buds, $moo[0]; + push @buds, $moo[0]; push @auth_values, $moo[1]; } @@ -163,10 +166,11 @@ if ( $op eq 'cud-save' ) { my %cell_hash; foreach my $authvalue (@auth_values) { + # get actual stats my $cell_name = "$budget,$authvalue"; my $estimated_amount = $input->param("$cell_name"); - my %cell_hash = ( + my %cell_hash = ( estimated_amount => $estimated_amount, authvalue => $authvalue, authcat => $authcat, @@ -184,15 +188,15 @@ if ( $op eq 'cud-save' ) { my $plan = \@budget_lines; ModBudgetPlan( $plan, $budget_period_id, $authcat ); -HideCols($authcat, @hide_cols); - + HideCols( $authcat, @hide_cols ); } + # ------------------------------------------------------------ if ( $authcat =~ m/^Asort/ ) { - my $query = qq{ SELECT * FROM authorised_values WHERE category=? order by lib }; + my $query = qq{ SELECT * FROM authorised_values WHERE category=? order by lib }; my $sth = $dbh->prepare($query); - $sth->execute($authcat ); + $sth->execute($authcat); if ( $sth->rows > 0 ) { for ( my $i = 0 ; $i < $sth->rows ; $i++ ) { my $results = $sth->fetchrow_hashref; @@ -202,8 +206,7 @@ if ( $authcat =~ m/^Asort/ ) { } $sth->finish; @authvals = sort { $a <=> $b } @authvals; -} -elsif ( $authcat eq 'MONTHS' && $budget_period_startdate && $budget_period_enddate ) { +} elsif ( $authcat eq 'MONTHS' && $budget_period_startdate && $budget_period_enddate ) { # build months my @start_date = UnixDate( $budget_period_startdate, ( '%Y', '%m', '%d' ) ); @@ -224,12 +227,11 @@ elsif ( $authcat eq 'MONTHS' && $budget_period_startdate && $budget_period_endda foreach my $vv (@authvals) { $labels{$vv} = $vv; } -} -elsif ( $authcat eq 'ITEMTYPES' ) { +} elsif ( $authcat eq 'ITEMTYPES' ) { my $query = qq| SELECT itemtype, description FROM itemtypes |; my $sth = $dbh->prepare($query); - $sth->execute( ); + $sth->execute(); if ( $sth->rows > 0 ) { for ( my $i = 0 ; $i < $sth->rows ; $i++ ) { @@ -269,15 +271,15 @@ elsif ( $authcat eq 'ITEMTYPES' ) { } my @authvals_row; -my $i=1; +my $i = 1; foreach my $val (@authvals) { my %auth_hash; - $auth_hash{val} = $labels{$val}; - $auth_hash{code} = $val; - $auth_hash{colnum} = $i++; + $auth_hash{val} = $labels{$val}; + $auth_hash{code} = $val; + $auth_hash{colnum} = $i++; # display lookup - $auth_hash{display} = GetCols( $authcat, $auth_hash{code}); + $auth_hash{display} = GetCols( $authcat, $auth_hash{code} ); push( @authvals_row, \%auth_hash ); } @@ -287,25 +289,23 @@ my ( @buds, @auth_values ); foreach my $n (@names) { next if $n =~ m/^[^0-9]/; $n =~ m/(\d*),(.*)/; - push @buds, $1; + push @buds, $1; push @auth_values, $2; } - # ------------------------------------------------------------ # DEFAULT DISPLAY BEGINS -my $CGIextChoice = ( 'CSV' ); # FIXME translation +my $CGIextChoice = ('CSV'); # FIXME translation my $CGIsepChoice = ( C4::Context->csv_delimiter ); my ( @budget_lines, %cell_hash ); - foreach my $budget (@budgets) { my $budget_lock; - unless (CanUserUseBudget($borrowernumber, $budget, $staff_flags)) { - $budget_lock = 1 + unless ( CanUserUseBudget( $borrowernumber, $budget, $staff_flags ) ) { + $budget_lock = 1; } # check budget permission @@ -319,15 +319,16 @@ foreach my $budget (@budgets) { # allow hard-coded itemtype and branch planning unless ( $authcat eq 'ITEMTYPES' - or $authcat eq 'BRANCHES' - or $authcat eq 'MONTHS' ) { + or $authcat eq 'BRANCHES' + or $authcat eq 'MONTHS' ) + { # but skip budgets that don't match the current auth-category next if ( $budget->{'sort1_authcat'} ne $authcat && $budget->{'sort2_authcat'} ne $authcat ); } - my %budget_line; # each row of the table + my %budget_line; # each row of the table my @cells_line; my $actual_spent; my $estimated_spent; @@ -347,7 +348,7 @@ foreach my $budget (@budgets) { ); my ( $actual, $estimated, $display ) = GetBudgetsPlanCell( \%cell, $period, $budget ); - $cell{actual_amount} = sprintf( "%.2f", $actual // 0 ); + $cell{actual_amount} = sprintf( "%.2f", $actual // 0 ); $cell{estimated_amount} = sprintf( "%.2f", $estimated // 0 ); $cell{display} = $authvals_row[$i]{display}; $cell{colnum} = $i; @@ -355,7 +356,6 @@ foreach my $budget (@budgets) { $actual_spent += $cell{actual_amount}; $estimated_spent += $cell{estimated_amount}; - push( @cells_line, \%cell ); $i++; } @@ -364,18 +364,16 @@ foreach my $budget (@budgets) { my $budget_est_remain = $budget->{budget_amount} - $estimated_spent; %budget_line = ( - lines => \@cells_line, - budget_name => $budget->{budget_name}, - budget_amount => $budget->{budget_amount}, - budget_alloc => $budget->{budget_alloc}, - budget_act_remain => sprintf( "%.2f", $budget_act_remain ), - budget_est_remain => sprintf( "%.2f", $budget_est_remain ), - budget_id => $budget->{budget_id}, - budget_lock => $budget_lock, + lines => \@cells_line, + budget_name => $budget->{budget_name}, + budget_amount => $budget->{budget_amount}, + budget_alloc => $budget->{budget_alloc}, + budget_act_remain => sprintf( "%.2f", $budget_act_remain ), + budget_est_remain => sprintf( "%.2f", $budget_est_remain ), + budget_id => $budget->{budget_id}, + budget_lock => $budget_lock, ); - - $budget_line{est_negative} = '1' if $budget_est_remain < 0; $budget_line{est_positive} = '1' if $budget_est_remain > 0; $budget_line{act_negative} = '1' if $budget_act_remain < 0; @@ -388,7 +386,7 @@ foreach my $budget (@budgets) { } if ( $output eq "file" ) { - _print_to_csv(\@authvals_row, \@budget_lines); + _print_to_csv( \@authvals_row, \@budget_lines ); exit(); } @@ -406,8 +404,8 @@ $template->param( CGIextChoice => $CGIextChoice, CGIsepChoice => $CGIsepChoice, - authvals => \@authvals_row, - hide_cols_loop => \@hide_cols, + authvals => \@authvals_row, + hide_cols_loop => \@hide_cols, ); output_html_with_http_headers $input, $cookie, $template->output; @@ -442,7 +440,7 @@ sub _print_to_csv { foreach my $row (@$results) { my @col = ( $row->{'budget_name'}, $row->{'budget_amount'} ); - my $l = $row->{'lines'}; + my $l = $row->{'lines'}; foreach my $line (@$l) { push @col, $line->{'estimated_amount'}; } diff --git a/admin/audio_alerts.pl b/admin/audio_alerts.pl index 01d3f4d4ce..017c55497d 100755 --- a/admin/audio_alerts.pl +++ b/admin/audio_alerts.pl @@ -20,7 +20,7 @@ use Modern::Perl; use CGI; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use Koha::AudioAlert; use Koha::AudioAlerts; diff --git a/admin/auth_subfields_structure.pl b/admin/auth_subfields_structure.pl index df8d10a211..a8402d0d36 100755 --- a/admin/auth_subfields_structure.pl +++ b/admin/auth_subfields_structure.pl @@ -19,8 +19,8 @@ use Modern::Perl; use C4::Output qw( output_html_with_http_headers ); -use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); use C4::Context; use Koha::Authority::Types; @@ -35,11 +35,12 @@ my $tagsubfield = $input->param('tagsubfield'); my $authtypecode = $input->param('authtypecode'); my $op = $input->param('op') || ''; -my ($template, $borrowernumber, $cookie) = get_template_and_user( - { template_name => "admin/auth_subfields_structure.tt", - query => $input, - type => "intranet", - flagsrequired => { parameters => 'manage_marc_frameworks' }, +my ( $template, $borrowernumber, $cookie ) = get_template_and_user( + { + template_name => "admin/auth_subfields_structure.tt", + query => $input, + type => "intranet", + flagsrequired => { parameters => 'manage_marc_frameworks' }, } ); my $pagesize = 30; @@ -47,45 +48,48 @@ $tagfield =~ s/\,//g; if ($op) { $template->param( - tagfield =>$tagfield, - authtypecode => $authtypecode, - $op => 1); # we show only the TMPL_VAR names $op + tagfield => $tagfield, + authtypecode => $authtypecode, + $op => 1 + ); # we show only the TMPL_VAR names $op } else { $template->param( - tagfield =>$tagfield, - authtypecode => $authtypecode, - else => 1); # we show only the TMPL_VAR names $op + tagfield => $tagfield, + authtypecode => $authtypecode, + else => 1 + ); # we show only the TMPL_VAR names $op } my $dbh = C4::Context->dbh; ################## ADD_FORM ################################## # called by default. Used to create form to add or modify a record -if ($op eq 'add_form') { - # builds kohafield tables - my @kohafields; - push @kohafields, ""; - my $sth2=$dbh->prepare("SHOW COLUMNS from auth_header"); - $sth2->execute; - while ((my $field) = $sth2->fetchrow_array) { - push @kohafields, "auth_header.".$field; - } - - # build authorised value category list - my @authorised_value_categories = Koha::AuthorisedValues->new->categories; - unshift @authorised_value_categories, ''; - push @authorised_value_categories, 'branches'; - push @authorised_value_categories, 'itemtypes'; +if ( $op eq 'add_form' ) { - # build thesaurus categories list - my @authtypes = uniq( "", map { $_->authtypecode } Koha::Authority::Types->search->as_list ); + # builds kohafield tables + my @kohafields; + push @kohafields, ""; + my $sth2 = $dbh->prepare("SHOW COLUMNS from auth_header"); + $sth2->execute; + while ( ( my $field ) = $sth2->fetchrow_array ) { + push @kohafields, "auth_header." . $field; + } - # build value_builder list - my @value_builder=(''); + # build authorised value category list + my @authorised_value_categories = Koha::AuthorisedValues->new->categories; + unshift @authorised_value_categories, ''; + push @authorised_value_categories, 'branches'; + push @authorised_value_categories, 'itemtypes'; - # read value_builder directory. - # 2 cases here : on CVS install, $cgidir does not need a /cgi-bin - # on a standard install, /cgi-bin need to be added. - # test one, then the other + # build thesaurus categories list + my @authtypes = uniq( "", map { $_->authtypecode } Koha::Authority::Types->search->as_list ); + + # build value_builder list + my @value_builder = (''); + + # read value_builder directory. + # 2 cases here : on CVS install, $cgidir does not need a /cgi-bin + # on a standard install, /cgi-bin need to be added. + # test one, then the other my $cgidir = C4::Context->config('intranetdir') . "/cgi-bin"; my $dir_h; unless ( opendir( $dir_h, "$cgidir/cataloguing/value_builder" ) ) { @@ -94,7 +98,8 @@ if ($op eq 'add_form') { } while ( my $line = readdir($dir_h) ) { if ( $line =~ /\.pl$/ - && $line !~ /EXAMPLE\.pl$/ ) { # documentation purposes + && $line !~ /EXAMPLE\.pl$/ ) + { # documentation purposes push( @value_builder, $line ); } } @@ -102,9 +107,12 @@ if ($op eq 'add_form') { closedir $dir_h; my @loop_data; - my $asses = Koha::Authority::Subfields->search({ tagfield => $tagfield, authtypecode => $authtypecode}, {order_by => 'display_order'})->unblessed; + my $asses = Koha::Authority::Subfields->search( + { tagfield => $tagfield, authtypecode => $authtypecode }, + { order_by => 'display_order' } + )->unblessed; my $i; - for my $ass ( @$asses ) { + for my $ass (@$asses) { my %row_data = %$ass; $row_data{kohafields} = \@kohafields; $row_data{authorised_values} = \@authorised_value_categories; @@ -115,69 +123,72 @@ if ($op eq 'add_form') { } # Add a new row for the "New" tab - my %row_data; # get a fresh hash for the row data + my %row_data; # get a fresh hash for the row data $row_data{'new_subfield'} = 1; - $row_data{tab} = -1; # ignore - $row_data{ohidden} = 0; # show all - $row_data{tagsubfield} = ""; - $row_data{liblibrarian} = ""; - $row_data{libopac} = ""; - $row_data{seealso} = ""; - $row_data{hidden} = "000"; - $row_data{repeatable} = 0; - $row_data{mandatory} = 0; - $row_data{isurl} = 0; - $row_data{kohafields} = \@kohafields, - $row_data{authorised_values} = \@authorised_value_categories; + $row_data{tab} = -1; # ignore + $row_data{ohidden} = 0; # show all + $row_data{tagsubfield} = ""; + $row_data{liblibrarian} = ""; + $row_data{libopac} = ""; + $row_data{seealso} = ""; + $row_data{hidden} = "000"; + $row_data{repeatable} = 0; + $row_data{mandatory} = 0; + $row_data{isurl} = 0; + $row_data{kohafields} = \@kohafields, + $row_data{authorised_values} = \@authorised_value_categories; $row_data{frameworkcodes} = \@authtypes; $row_data{value_builders} = \@value_builder; - $row_data{row} = $i; + $row_data{row} = $i; push( @loop_data, \%row_data ); - $template->param('use_heading_flags_p' => 1); - $template->param('heading_edit_subfields_p' => 1); - $template->param(action => "Edit subfields", - tagfield => $tagfield, - tagsubfield => $tagsubfield, - loop => \@loop_data, - more_tag => $tagfield); + $template->param( 'use_heading_flags_p' => 1 ); + $template->param( 'heading_edit_subfields_p' => 1 ); + $template->param( + action => "Edit subfields", + tagfield => $tagfield, + tagsubfield => $tagsubfield, + loop => \@loop_data, + more_tag => $tagfield + ); - # END $OP eq ADD_FORM + # END $OP eq ADD_FORM ################## ADD_VALIDATE ################################## -# called by add_form, used to insert/modify data in DB -} elsif ($op eq 'cud-add_validate') { - $template->param(tagfield => "$input->param('tagfield')"); - my @tagsubfield = $input->multi_param('tagsubfield'); - my @liblibrarian = $input->multi_param('liblibrarian'); - my @libopac = $input->multi_param('libopac'); - my @kohafield = ''.$input->param('kohafield'); - my @tab = $input->multi_param('tab'); - my @seealso = $input->multi_param('seealso'); - my @ohidden = $input->multi_param('ohidden'); + # called by add_form, used to insert/modify data in DB +} elsif ( $op eq 'cud-add_validate' ) { + $template->param( tagfield => "$input->param('tagfield')" ); + my @tagsubfield = $input->multi_param('tagsubfield'); + my @liblibrarian = $input->multi_param('liblibrarian'); + my @libopac = $input->multi_param('libopac'); + my @kohafield = '' . $input->param('kohafield'); + my @tab = $input->multi_param('tab'); + my @seealso = $input->multi_param('seealso'); + my @ohidden = $input->multi_param('ohidden'); my @authorised_value_categories = $input->multi_param('authorised_value'); - my $authtypecode = $input->param('authtypecode'); - my @frameworkcodes = $input->multi_param('frameworkcode'); - my @value_builder =$input->multi_param('value_builder'); - my @defaultvalue = $input->multi_param('defaultvalue'); + my $authtypecode = $input->param('authtypecode'); + my @frameworkcodes = $input->multi_param('frameworkcode'); + my @value_builder = $input->multi_param('value_builder'); + my @defaultvalue = $input->multi_param('defaultvalue'); my $display_order; - for (my $i=0; $i<= $#tagsubfield ; $i++) { - my $tagfield =$input->param('tagfield'); - my $tagsubfield =$tagsubfield[$i]; - $tagsubfield="@" unless $tagsubfield ne ''; - my $liblibrarian =$liblibrarian[$i]; - my $libopac =$libopac[$i]; - my $repeatable =$input->param("repeatable$i")?1:0; - my $mandatory =$input->param("mandatory$i")?1:0; - my $kohafield =$kohafield[$i]; - my $tab =$tab[$i]; - my $seealso =$seealso[$i]; + for ( my $i = 0 ; $i <= $#tagsubfield ; $i++ ) { + my $tagfield = $input->param('tagfield'); + my $tagsubfield = $tagsubfield[$i]; + $tagsubfield = "@" unless $tagsubfield ne ''; + my $liblibrarian = $liblibrarian[$i]; + my $libopac = $libopac[$i]; + my $repeatable = $input->param("repeatable$i") ? 1 : 0; + my $mandatory = $input->param("mandatory$i") ? 1 : 0; + my $kohafield = $kohafield[$i]; + my $tab = $tab[$i]; + my $seealso = $seealso[$i]; my $authorised_value = $authorised_value_categories[$i]; - my $frameworkcode =$frameworkcodes[$i]; - my $value_builder=$value_builder[$i]; - my $defaultvalue = $defaultvalue[$i]; - my $hidden = $ohidden[$i]; #collate from 3 hiddens; - my $isurl = $input->param("isurl$i")?1:0; + my $frameworkcode = $frameworkcodes[$i]; + my $value_builder = $value_builder[$i]; + my $defaultvalue = $defaultvalue[$i]; + my $hidden = $ohidden[$i]; #collate from 3 hiddens; + my $isurl = $input->param("isurl$i") ? 1 : 0; + if ($liblibrarian) { my $ass = Koha::Authority::Subfields->find( { @@ -205,8 +216,7 @@ if ($op eq 'add_form') { if ($ass) { $ass->update($attributes); - } - else { + } else { Koha::Authority::Subfield->new( { authtypecode => $authtypecode, @@ -218,27 +228,26 @@ if ($op eq 'add_form') { } $display_order->{$tagfield}++; } - } - print $input->redirect("/cgi-bin/koha/admin/auth_subfields_structure.pl?tagfield=$tagfield&authtypecode=$authtypecode"); + } + print $input->redirect( + "/cgi-bin/koha/admin/auth_subfields_structure.pl?tagfield=$tagfield&authtypecode=$authtypecode"); exit; - # END $OP eq ADD_VALIDATE + # END $OP eq ADD_VALIDATE ################## DELETE_CONFIRM ################################## -# called by default form, used to confirm deletion of data in DB -} -elsif ( $op eq 'delete_confirm' ) { - my $ass = Koha::Authority::Subfields->find( - { - authtypecode => $authtypecode, - tagfield => $tagfield, - tagsubfield => $tagsubfield - } - ); - $template->param( - ass => $ass, - ); -} -elsif ( $op eq 'cud-delete_confirmed' ) { + # called by default form, used to confirm deletion of data in DB +} elsif ( $op eq 'delete_confirm' ) { + my $ass = Koha::Authority::Subfields->find( + { + authtypecode => $authtypecode, + tagfield => $tagfield, + tagsubfield => $tagsubfield + } + ); + $template->param( + ass => $ass, + ); +} elsif ( $op eq 'cud-delete_confirmed' ) { Koha::Authority::Subfields->find( { authtypecode => $authtypecode, @@ -246,23 +255,23 @@ elsif ( $op eq 'cud-delete_confirmed' ) { tagsubfield => $tagsubfield } )->delete; - print $input->redirect("/cgi-bin/koha/admin/auth_subfields_structure.pl?tagfield=$tagfield&authtypecode=$authtypecode"); + print $input->redirect( + "/cgi-bin/koha/admin/auth_subfields_structure.pl?tagfield=$tagfield&authtypecode=$authtypecode"); exit; -} -else { # DEFAULT +} else { # DEFAULT my $ass = Koha::Authority::Subfields->search( { - tagfield => { -like => "$tagfield%" }, - authtypecode => $authtypecode, + tagfield => { -like => "$tagfield%" }, + authtypecode => $authtypecode, }, { order_by => [ 'tagfield', 'display_order' ] } )->unblessed; $template->param( loop => $ass ); $template->param( - edit_tagfield => $tagfield, - edit_authtypecode => $authtypecode, + edit_tagfield => $tagfield, + edit_authtypecode => $authtypecode, ); -} #---- END $OP eq DEFAULT +} #---- END $OP eq DEFAULT output_html_with_http_headers $input, $cookie, $template->output; diff --git a/admin/auth_tag_structure.pl b/admin/auth_tag_structure.pl index b4d8b58fa0..4ae2be4269 100755 --- a/admin/auth_tag_structure.pl +++ b/admin/auth_tag_structure.pl @@ -1,6 +1,5 @@ #!/usr/bin/perl - # Copyright 2000-2002 Katipo Communications # # This file is part of Koha. @@ -19,7 +18,7 @@ # along with Koha; if not, see . use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Auth qw( get_template_and_user ); use C4::Context; use C4::Output qw( output_html_with_http_headers ); @@ -28,91 +27,102 @@ use C4::Context; use Koha::Authority::Types; # retrieve parameters -my $input = CGI->new; -my $authtypecode = $input->param('authtypecode') || ''; # set to select framework -my $existingauthtypecode = $input->param('existingauthtypecode') || ''; # set when we have to create a new framework (in authtype) by copying an old one (in existingauthtype) +my $input = CGI->new; +my $authtypecode = $input->param('authtypecode') || ''; # set to select framework +my $existingauthtypecode = $input->param('existingauthtypecode') + || ''; # set when we have to create a new framework (in authtype) by copying an old one (in existingauthtype) my $searchfield = $input->param('searchfield') || 0; my $offset = $input->param('offset'); $offset = 0 if not defined $offset or $offset < 0; -my $op = $input->param('op') || ''; +my $op = $input->param('op') || ''; $searchfield =~ s/\,//g; - my $dbh = C4::Context->dbh; # open template -my ($template, $loggedinuser, $cookie) - = get_template_and_user({template_name => "admin/auth_tag_structure.tt", - query => $input, - type => "intranet", - flagsrequired => {parameters => 'manage_marc_frameworks'}, - }); +my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "admin/auth_tag_structure.tt", + query => $input, + type => "intranet", + flagsrequired => { parameters => 'manage_marc_frameworks' }, + } +); my $authority_types = Koha::Authority::Types->search( {}, { order_by => ['authtypecode'] } ); my $sth; + # check that authtype framework is defined in auth_tag_structure if we are on a default action -if (!$op or $op eq 'cud-authtype_create_confirm') { - $sth=$dbh->prepare("select count(*) from auth_tag_structure where authtypecode=?"); +if ( !$op or $op eq 'cud-authtype_create_confirm' ) { + $sth = $dbh->prepare("select count(*) from auth_tag_structure where authtypecode=?"); $sth->execute($authtypecode); my ($authtypeexist) = $sth->fetchrow; if ($authtypeexist) { } else { + # if authtype does not exists, then OP must be changed to "create authtype" if we are not on the way to create it # (op = authtyp_create_confirm) - if ($op eq "cud-authtype_create_confirm") { - duplicate_auth_framework($authtypecode, $existingauthtypecode); + if ( $op eq "cud-authtype_create_confirm" ) { + duplicate_auth_framework( $authtypecode, $existingauthtypecode ); } else { $op = "authtype_create"; } } } -$template->param(authority_types => $authority_types ); -if ($op && $op ne 'cud-authtype_create_confirm') { - $template->param($op => 1); +$template->param( authority_types => $authority_types ); +if ( $op && $op ne 'cud-authtype_create_confirm' ) { + $template->param( $op => 1 ); } else { - $template->param(else => 1); + $template->param( else => 1 ); } - + ################## ADD_FORM ################################## # called by default. Used to create form to add or modify a record -if ($op eq 'add_form') { +if ( $op eq 'add_form' ) { + #---- if primkey exists, it's a modify action, so read values to modify... my $data; if ($searchfield) { - $sth=$dbh->prepare("select tagfield,liblibrarian,libopac,repeatable,mandatory,authorised_value from auth_tag_structure where tagfield=? and authtypecode=?"); - $sth->execute($searchfield,$authtypecode); - $data=$sth->fetchrow_hashref; + $sth = $dbh->prepare( + "select tagfield,liblibrarian,libopac,repeatable,mandatory,authorised_value from auth_tag_structure where tagfield=? and authtypecode=?" + ); + $sth->execute( $searchfield, $authtypecode ); + $data = $sth->fetchrow_hashref; } if ($searchfield) { - $template->param('searchfield' => $searchfield); - $template->param('heading_modify_tag_p' => 1); + $template->param( 'searchfield' => $searchfield ); + $template->param( 'heading_modify_tag_p' => 1 ); } else { - $template->param('heading_add_tag_p' => 1); + $template->param( 'heading_add_tag_p' => 1 ); } - $template->param('use_heading_flags_p' => 1); - $template->param(liblibrarian => $data->{'liblibrarian'}, - libopac => $data->{'libopac'}, - repeatable => "".$data->{'repeatable'}, - mandatory => "".$data->{'mandatory'}, - authorised_value => $data->{authorised_value}, - authtypecode => $authtypecode, - ); - # END $OP eq ADD_FORM + $template->param( 'use_heading_flags_p' => 1 ); + $template->param( + liblibrarian => $data->{'liblibrarian'}, + libopac => $data->{'libopac'}, + repeatable => "" . $data->{'repeatable'}, + mandatory => "" . $data->{'mandatory'}, + authorised_value => $data->{authorised_value}, + authtypecode => $authtypecode, + ); + + # END $OP eq ADD_FORM ################## ADD_VALIDATE ################################## -# called by add_form, used to insert/modify data in DB -} elsif ($op eq 'cud-add_validate') { + # called by add_form, used to insert/modify data in DB +} elsif ( $op eq 'cud-add_validate' ) { my $tagfield = $input->param('tagfield'); my $liblibrarian = $input->param('liblibrarian'); my $libopac = $input->param('libopac'); my $repeatable = $input->param('repeatable') ? 1 : 0; my $mandatory = $input->param('mandatory') ? 1 : 0; my $authorised_value = $input->param('authorised_value'); - if ($input->param('modif')) { - $sth=$dbh->prepare("UPDATE auth_tag_structure SET tagfield=?, liblibrarian=?, libopac=?, repeatable=?, mandatory=?, authorised_value=? WHERE authtypecode=? AND tagfield=?"); + if ( $input->param('modif') ) { + $sth = $dbh->prepare( + "UPDATE auth_tag_structure SET tagfield=?, liblibrarian=?, libopac=?, repeatable=?, mandatory=?, authorised_value=? WHERE authtypecode=? AND tagfield=?" + ); $sth->execute( $tagfield, $liblibrarian, @@ -124,7 +134,9 @@ if ($op eq 'add_form') { $tagfield, ); } else { - $sth=$dbh->prepare("INSERT INTO auth_tag_structure (tagfield,liblibrarian,libopac,repeatable,mandatory,authorised_value,authtypecode) VALUES (?,?,?,?,?,?,?)"); + $sth = $dbh->prepare( + "INSERT INTO auth_tag_structure (tagfield,liblibrarian,libopac,repeatable,mandatory,authorised_value,authtypecode) VALUES (?,?,?,?,?,?,?)" + ); $sth->execute( $tagfield, $liblibrarian, @@ -133,119 +145,164 @@ if ($op eq 'add_form') { $mandatory, $authorised_value, $authtypecode - ); + ); } - print $input->redirect("/cgi-bin/koha/admin/auth_tag_structure.pl?searchfield=$tagfield&authtypecode=$authtypecode"); + print $input->redirect( + "/cgi-bin/koha/admin/auth_tag_structure.pl?searchfield=$tagfield&authtypecode=$authtypecode"); exit; - # END $OP eq ADD_VALIDATE + + # END $OP eq ADD_VALIDATE ################## DELETE_CONFIRM ################################## -# called by default form, used to confirm deletion of data in DB -} elsif ($op eq 'delete_confirm') { - $sth=$dbh->prepare("select tagfield,liblibrarian,libopac,repeatable,mandatory,authorised_value from auth_tag_structure where tagfield=?"); + # called by default form, used to confirm deletion of data in DB +} elsif ( $op eq 'delete_confirm' ) { + $sth = $dbh->prepare( + "select tagfield,liblibrarian,libopac,repeatable,mandatory,authorised_value from auth_tag_structure where tagfield=?" + ); $sth->execute($searchfield); - my $data=$sth->fetchrow_hashref; - $template->param(liblibrarian => $data->{'liblibrarian'}, - searchfield => $searchfield, - authtypecode => $authtypecode, - ); - # END $OP eq DELETE_CONFIRM + my $data = $sth->fetchrow_hashref; + $template->param( + liblibrarian => $data->{'liblibrarian'}, + searchfield => $searchfield, + authtypecode => $authtypecode, + ); + + # END $OP eq DELETE_CONFIRM ################## DELETE_CONFIRMED ################################## -# called by delete_confirm, used to effectively confirm deletion of data in DB -} elsif ($op eq 'cud-delete_confirmed') { - $dbh->do(q|delete from auth_tag_structure where tagfield=? and authtypecode=?|, undef, $searchfield, $authtypecode); - $dbh->do(q|delete from auth_subfield_structure where tagfield=? and authtypecode=?|, undef, $searchfield, $authtypecode); - print $input->redirect("/cgi-bin/koha/admin/auth_tag_structure.pl?searchfield=$searchfield&authtypecode=$authtypecode"); + # called by delete_confirm, used to effectively confirm deletion of data in DB +} elsif ( $op eq 'cud-delete_confirmed' ) { + $dbh->do( + q|delete from auth_tag_structure where tagfield=? and authtypecode=?|, undef, $searchfield, + $authtypecode + ); + $dbh->do( + q|delete from auth_subfield_structure where tagfield=? and authtypecode=?|, undef, $searchfield, + $authtypecode + ); + print $input->redirect( + "/cgi-bin/koha/admin/auth_tag_structure.pl?searchfield=$searchfield&authtypecode=$authtypecode"); exit; - # END $OP eq DELETE_CONFIRMED + + # END $OP eq DELETE_CONFIRMED ################## ITEMTYPE_CREATE ################################## -# called automatically if an unexisting authtypecode is selected -} elsif ($op eq 'authtype_create') { - $sth = $dbh->prepare("select count(*),auth_tag_structure.authtypecode,authtypetext from auth_tag_structure,auth_types where auth_types.authtypecode=auth_tag_structure.authtypecode group by auth_tag_structure.authtypecode"); + # called automatically if an unexisting authtypecode is selected +} elsif ( $op eq 'authtype_create' ) { + $sth = $dbh->prepare( + "select count(*),auth_tag_structure.authtypecode,authtypetext from auth_tag_structure,auth_types where auth_types.authtypecode=auth_tag_structure.authtypecode group by auth_tag_structure.authtypecode" + ); $sth->execute; my @existingauthtypeloop; - while (my ($tot,$thisauthtype,$authtypetext) = $sth->fetchrow) { - if ($tot>0) { - my %line = ( value => $thisauthtype, - authtypetext => $authtypetext, - ); - push @existingauthtypeloop,\%line; + while ( my ( $tot, $thisauthtype, $authtypetext ) = $sth->fetchrow ) { + if ( $tot > 0 ) { + my %line = ( + value => $thisauthtype, + authtypetext => $authtypetext, + ); + push @existingauthtypeloop, \%line; } } - @existingauthtypeloop = sort { lc($a->{authtypetext}) cmp lc($b->{authtypetext}) }@existingauthtypeloop; - $template->param(existingauthtypeloop => \@existingauthtypeloop, - authtypecode => $authtypecode, - ); + @existingauthtypeloop = sort { lc( $a->{authtypetext} ) cmp lc( $b->{authtypetext} ) } @existingauthtypeloop; + $template->param( + existingauthtypeloop => \@existingauthtypeloop, + authtypecode => $authtypecode, + ); ################## DEFAULT ################################## -} else { # DEFAULT - # here, $op can be unset or set to "cud-authtype_create_confirm". -# warn "authtype : $authtypecode"; - if ($searchfield ne '') { - $template->param(searchfield => $searchfield); +} else { # DEFAULT + # here, $op can be unset or set to "cud-authtype_create_confirm". + + # warn "authtype : $authtypecode"; + if ( $searchfield ne '' ) { + $template->param( searchfield => $searchfield ); } - my ($count,$results)=StringSearch($searchfield,$authtypecode); + my ( $count, $results ) = StringSearch( $searchfield, $authtypecode ); my @loop_data = (); for ( my $i = $offset ; $i < $count ; $i++ ) { - my %row_data; # get a fresh hash for the row data + my %row_data; # get a fresh hash for the row data $row_data{tagfield} = $results->[$i]{'tagfield'}; $row_data{liblibrarian} = $results->[$i]{'liblibrarian'}; $row_data{repeatable} = $results->[$i]{'repeatable'}; $row_data{mandatory} = $results->[$i]{'mandatory'}; $row_data{authorised_value} = $results->[$i]{'authorised_value'}; - push(@loop_data, \%row_data); + push( @loop_data, \%row_data ); } - $template->param(loop => \@loop_data, - authtypecode => $authtypecode, + $template->param( + loop => \@loop_data, + authtypecode => $authtypecode, ); - if ($offset>0) { - $template->param(isprevpage => $offset, - searchfield => $searchfield, - ); + if ( $offset > 0 ) { + $template->param( + isprevpage => $offset, + searchfield => $searchfield, + ); } if ( $offset < $count ) { $template->param( - searchfield => $searchfield, + searchfield => $searchfield, ); } -} #---- END $OP eq DEFAULT +} #---- END $OP eq DEFAULT output_html_with_http_headers $input, $cookie, $template->output; # # the sub used for searches # -sub StringSearch { - my ($searchstring,$authtypecode)=@_; +sub StringSearch { + my ( $searchstring, $authtypecode ) = @_; my $dbh = C4::Context->dbh; - $searchstring=~ s/\'/\\\'/g; - my @data=split(' ',$searchstring); - my $sth=$dbh->prepare("Select tagfield,liblibrarian,libopac,repeatable,mandatory,authorised_value from auth_tag_structure where (tagfield >= ? and authtypecode=?) order by tagfield"); - $sth->execute($data[0], $authtypecode); + $searchstring =~ s/\'/\\\'/g; + my @data = split( ' ', $searchstring ); + my $sth = $dbh->prepare( + "Select tagfield,liblibrarian,libopac,repeatable,mandatory,authorised_value from auth_tag_structure where (tagfield >= ? and authtypecode=?) order by tagfield" + ); + $sth->execute( $data[0], $authtypecode ); my @results; - while (my $data=$sth->fetchrow_hashref){ - push(@results,$data); + while ( my $data = $sth->fetchrow_hashref ) { + push( @results, $data ); } - return (scalar(@results),\@results); + return ( scalar(@results), \@results ); } # # the sub used to duplicate a framework from an existing one in MARC parameters tables. # sub duplicate_auth_framework { - my ($newauthtype,$oldauthtype) = @_; -# warn "TO $newauthtype FROM $oldauthtype"; + my ( $newauthtype, $oldauthtype ) = @_; + + # warn "TO $newauthtype FROM $oldauthtype"; my $dbh = C4::Context->dbh; - my $sth = $dbh->prepare("select tagfield,liblibrarian,libopac,repeatable,mandatory,authorised_value from auth_tag_structure where authtypecode=?"); + my $sth = $dbh->prepare( + "select tagfield,liblibrarian,libopac,repeatable,mandatory,authorised_value from auth_tag_structure where authtypecode=?" + ); $sth->execute($oldauthtype); - my $sth_insert = $dbh->prepare("insert into auth_tag_structure (tagfield, liblibrarian, libopac, repeatable, mandatory, authorised_value, authtypecode) values (?,?,?,?,?,?,?)"); - while ( my ($tagfield,$liblibrarian,$libopac,$repeatable,$mandatory,$authorised_value) = $sth->fetchrow) { - $sth_insert->execute($tagfield,$liblibrarian,$libopac,$repeatable,$mandatory,$authorised_value,$newauthtype); + my $sth_insert = $dbh->prepare( + "insert into auth_tag_structure (tagfield, liblibrarian, libopac, repeatable, mandatory, authorised_value, authtypecode) values (?,?,?,?,?,?,?)" + ); + while ( my ( $tagfield, $liblibrarian, $libopac, $repeatable, $mandatory, $authorised_value ) = $sth->fetchrow ) { + $sth_insert->execute( + $tagfield, $liblibrarian, $libopac, $repeatable, $mandatory, $authorised_value, + $newauthtype + ); } - $sth = $dbh->prepare("select tagfield,tagsubfield,liblibrarian,libopac,repeatable,mandatory,kohafield,tab,authorised_value,value_builder,seealso,hidden from auth_subfield_structure where authtypecode=?"); + $sth = $dbh->prepare( + "select tagfield,tagsubfield,liblibrarian,libopac,repeatable,mandatory,kohafield,tab,authorised_value,value_builder,seealso,hidden from auth_subfield_structure where authtypecode=?" + ); $sth->execute($oldauthtype); - $sth_insert = $dbh->prepare("insert into auth_subfield_structure (authtypecode,tagfield,tagsubfield,liblibrarian,libopac,repeatable,mandatory,kohafield,tab,authorised_value,value_builder,seealso,hidden) values (?,?,?,?,?,?,?,?,?,?,?,?,?)"); - while ( my ( $tagfield, $tagsubfield, $liblibrarian, $libopac, $repeatable, $mandatory, $kohafield,$tab, $authorised_value, $thesaurus_category, $seealso,$hidden) = $sth->fetchrow) { - $sth_insert->execute($newauthtype, $tagfield, $tagsubfield, $liblibrarian, $libopac, $repeatable, $mandatory,$kohafield, $tab, $authorised_value, $thesaurus_category, $seealso,$hidden); + $sth_insert = $dbh->prepare( + "insert into auth_subfield_structure (authtypecode,tagfield,tagsubfield,liblibrarian,libopac,repeatable,mandatory,kohafield,tab,authorised_value,value_builder,seealso,hidden) values (?,?,?,?,?,?,?,?,?,?,?,?,?)" + ); + while ( + my ( + $tagfield, $tagsubfield, $liblibrarian, $libopac, $repeatable, $mandatory, $kohafield, $tab, + $authorised_value, $thesaurus_category, $seealso, $hidden + ) + = $sth->fetchrow + ) + { + $sth_insert->execute( + $newauthtype, $tagfield, $tagsubfield, $liblibrarian, $libopac, $repeatable, $mandatory, + $kohafield, $tab, $authorised_value, $thesaurus_category, $seealso, $hidden + ); } } diff --git a/admin/authorised_values.pl b/admin/authorised_values.pl index 9513ce7eda..4210945b98 100755 --- a/admin/authorised_values.pl +++ b/admin/authorised_values.pl @@ -19,19 +19,19 @@ use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use List::MoreUtils qw( any ); use C4::Auth qw( get_template_and_user ); use C4::Context; -use C4::Koha qw( getitemtypeimagelocation ); +use C4::Koha qw( getitemtypeimagelocation ); use C4::Output qw( output_html_with_http_headers ); use Koha::AuthorisedValues; use Koha::AuthorisedValueCategories; use Koha::Libraries; -my $input = CGI->new; +my $input = CGI->new; my $id = $input->param('id'); my $op = $input->param('op') || 'list'; my $searchfield = $input->param('searchfield'); @@ -39,19 +39,21 @@ $searchfield = '' unless defined $searchfield; $searchfield =~ s/\,//g; my @messages; -our ($template, $borrowernumber, $cookie)= get_template_and_user({ - template_name => "admin/authorised_values.tt", - flagsrequired => {parameters => 'manage_auth_values'}, - query => $input, - type => "intranet", -}); +our ( $template, $borrowernumber, $cookie ) = get_template_and_user( + { + template_name => "admin/authorised_values.tt", + flagsrequired => { parameters => 'manage_auth_values' }, + query => $input, + type => "intranet", + } +); ################## ADD_FORM ################################## # called by default. Used to create form to add or modify a record if ( $op eq 'add_form' or $op eq 'edit_form' ) { my ( @selected_branches, $category, $category_name, $av ); if ($id) { - $av = Koha::AuthorisedValues->new->find( $id ); + $av = Koha::AuthorisedValues->new->find($id); @selected_branches = $av->library_limits ? $av->library_limits->as_list : (); } else { $category_name = $input->param('category'); @@ -64,23 +66,23 @@ if ( $op eq 'add_form' or $op eq 'edit_form' ) { push @branches_loop, { branchcode => $branch->branchcode, branchname => $branch->branchname, - selected => any {$_->branchcode eq $branch->branchcode} @selected_branches, + selected => any { $_->branchcode eq $branch->branchcode } @selected_branches, }; } - if ($id) { - $template->param(action_modify => 1); - } elsif ( ! $category_name ) { - $template->param(action_add_category => 1); - } else { - $template->param(action_add_value => 1); - } + if ($id) { + $template->param( action_modify => 1 ); + } elsif ( !$category_name ) { + $template->param( action_add_category => 1 ); + } else { + $template->param( action_add_value => 1 ); + } - if ( $av ) { + if ($av) { $template->param( category_name => $av->category, - av => $av, - imagesets => C4::Koha::getImageSets( checked => $av->imageurl ), + av => $av, + imagesets => C4::Koha::getImageSets( checked => $av->imageurl ), ); } else { $template->param( @@ -90,51 +92,49 @@ if ( $op eq 'add_form' or $op eq 'edit_form' ) { ); } $template->param( - branches_loop => \@branches_loop, - num_pattern => Koha::AuthorisedValue::NUM_PATTERN_JS(), + branches_loop => \@branches_loop, + num_pattern => Koha::AuthorisedValue::NUM_PATTERN_JS(), ); -} elsif ($op eq 'cud-add') { +} elsif ( $op eq 'cud-add' ) { my $new_authorised_value = $input->param('authorised_value'); - my $new_category = $input->param('category'); - my $image = $input->param( 'image' ) || ''; + my $new_category = $input->param('category'); + my $image = $input->param('image') || ''; my $imageurl = - $image eq 'removeImage' ? '' - : ( + $image eq 'removeImage' ? '' + : ( $image eq 'remoteImage' ? $input->param('remoteImage') : $image - ); + ); my $duplicate_entry = 0; my @branches = grep { $_ ne q{} } $input->multi_param('branches'); if ( $new_category eq 'branches' or $new_category eq 'itemtypes' or $new_category eq 'cn_source' ) { - push @messages, {type => 'error', code => 'invalid_category_name' }; - } - elsif ( $id ) { # Update - my $av = Koha::AuthorisedValues->new->find( $id ); + push @messages, { type => 'error', code => 'invalid_category_name' }; + } elsif ($id) { # Update + my $av = Koha::AuthorisedValues->new->find($id); - $av->lib( scalar $input->param('lib') || undef ); + $av->lib( scalar $input->param('lib') || undef ); $av->lib_opac( scalar $input->param('lib_opac') || undef ); - $av->category( $new_category ); - $av->authorised_value( $new_authorised_value ); - $av->imageurl( $imageurl ); - eval{ + $av->category($new_category); + $av->authorised_value($new_authorised_value); + $av->imageurl($imageurl); + eval { $av->store; $av->replace_library_limits( \@branches ); }; - if ( $@ ) { - push @messages, {type => 'error', code => 'error_on_update' }; + if ($@) { + push @messages, { type => 'error', code => 'error_on_update' }; } else { push @messages, { type => 'message', code => 'success_on_update' }; } - } - else { # Insert + } else { # Insert eval { my $av = Koha::AuthorisedValue->new( { category => $new_category, authorised_value => $new_authorised_value, - lib => scalar $input->param('lib') || undef, + lib => scalar $input->param('lib') || undef, lib_opac => scalar $input->param('lib_opac') || undef, imageurl => $imageurl, } @@ -143,16 +143,16 @@ if ( $op eq 'add_form' or $op eq 'edit_form' ) { $av->store; }; - if ( $@ ) { - push @messages, {type => 'error', code => 'error_on_insert' }; + if ($@) { + push @messages, { type => 'error', code => 'error_on_insert' }; } else { push @messages, { type => 'message', code => 'success_on_insert' }; } } - $op = 'list'; + $op = 'list'; $searchfield = $new_category; -} elsif ($op eq 'cud-add_category' ) { +} elsif ( $op eq 'cud-add_category' ) { my $new_category = $input->param('category'); my $is_integer_only = $input->param('is_integer_only') ? 1 : 0; @@ -162,24 +162,23 @@ if ( $op eq 'add_form' or $op eq 'edit_form' ) { } ); - if ( $already_exists ) { + if ($already_exists) { if ( $new_category eq 'branches' or $new_category eq 'itemtypes' or $new_category eq 'cn_source' ) { - push @messages, {type => 'error', code => 'invalid_category_name' }; + push @messages, { type => 'error', code => 'invalid_category_name' }; } else { - push @messages, {type => 'error', code => 'cat_already_exists' }; + push @messages, { type => 'error', code => 'cat_already_exists' }; } - } - else { # Insert - my $av = Koha::AuthorisedValueCategory->new( { - category_name => $new_category, is_integer_only => $is_integer_only, - } ); + } else { # Insert + my $av = Koha::AuthorisedValueCategory->new( + { + category_name => $new_category, is_integer_only => $is_integer_only, + } + ); - eval { - $av->store; - }; + eval { $av->store; }; - if ( $@ ) { - push @messages, {type => 'error', code => 'error_on_insert_cat' }; + if ($@) { + push @messages, { type => 'error', code => 'error_on_insert_cat' }; } else { push @messages, { type => 'message', code => 'success_on_insert_cat' }; $searchfield = $new_category; @@ -195,26 +194,26 @@ if ( $op eq 'add_form' or $op eq 'edit_form' ) { if ($category) { $category->is_integer_only($is_integer_only)->store; } else { - push @messages, {type => 'error', code => 'error_on_edit_cat' }; + push @messages, { type => 'error', code => 'error_on_edit_cat' }; } $op = 'list'; -} elsif ($op eq 'cud-delete') { - my $av = Koha::AuthorisedValues->new->find( $id ); - my $deleted = eval {$av->delete}; +} elsif ( $op eq 'cud-delete' ) { + my $av = Koha::AuthorisedValues->new->find($id); + my $deleted = eval { $av->delete }; if ( $@ or not $deleted ) { - push @messages, {type => 'error', code => 'error_on_delete' }; + push @messages, { type => 'error', code => 'error_on_delete' }; } else { push @messages, { type => 'message', code => 'success_on_delete' }; } $op = 'list'; -} elsif ($op eq 'cud-delete_category') { +} elsif ( $op eq 'cud-delete_category' ) { my $category_name = $input->param('category_name'); - my $avc = Koha::AuthorisedValueCategories->find( $category_name ); - my $deleted = eval {$avc->delete}; + my $avc = Koha::AuthorisedValueCategories->find($category_name); + my $deleted = eval { $avc->delete }; if ( $@ or not $deleted ) { - push @messages, {type => 'error', code => 'error_on_delete_category' }; + push @messages, { type => 'error', code => 'error_on_delete_category' }; } else { push @messages, { type => 'message', code => 'success_on_delete_category' }; } @@ -223,45 +222,45 @@ if ( $op eq 'add_form' or $op eq 'edit_form' ) { } $template->param( - op => $op, + op => $op, searchfield => $searchfield, - messages => \@messages, + messages => \@messages, ); if ( $op eq 'list' ) { + # build categories list my $category_rs = Koha::AuthorisedValueCategories->search( - { - category_name => - { -not_in => [ '', 'branches', 'itemtypes', 'cn_source' ] } - }, - { order_by => ['category_name'] } + { category_name => { -not_in => [ '', 'branches', 'itemtypes', 'cn_source' ] } }, + { order_by => ['category_name'] } ); my @category_names = $category_rs->get_column('category_name'); $searchfield ||= ""; my @avs_by_category = Koha::AuthorisedValues->new->search( { category => $searchfield } )->as_list; - my @loop_data = (); + my @loop_data = (); my $category = $category_rs->find($searchfield); my $is_integer_only = $category && $category->is_integer_only; + # builds value list - for my $av ( @avs_by_category ) { - my %row_data; # get a fresh hash for the row data - $row_data{category} = $av->category; - $row_data{authorised_value} = $av->authorised_value; - $row_data{lib} = $av->lib; - $row_data{lib_opac} = $av->lib_opac; - $row_data{image} = getitemtypeimagelocation( 'intranet', $av->imageurl ); - $row_data{branches} = $av->library_limits ? $av->library_limits->as_list : []; - $row_data{id} = $av->id; - $row_data{is_integer_only} = $is_integer_only; - push(@loop_data, \%row_data); + for my $av (@avs_by_category) { + my %row_data; # get a fresh hash for the row data + $row_data{category} = $av->category; + $row_data{authorised_value} = $av->authorised_value; + $row_data{lib} = $av->lib; + $row_data{lib_opac} = $av->lib_opac; + $row_data{image} = getitemtypeimagelocation( 'intranet', $av->imageurl ); + $row_data{branches} = $av->library_limits ? $av->library_limits->as_list : []; + $row_data{id} = $av->id; + $row_data{is_integer_only} = $is_integer_only; + push( @loop_data, \%row_data ); } $template->param( loop => \@loop_data, - category => Koha::AuthorisedValueCategories->find($searchfield), # TODO Move this up and add a Koha::AVC->authorised_values method to replace call for avs_by_category + category => Koha::AuthorisedValueCategories->find($searchfield) + , # TODO Move this up and add a Koha::AVC->authorised_values method to replace call for avs_by_category category_names => \@category_names, ); diff --git a/admin/authtypes.pl b/admin/authtypes.pl index 13f573b300..151c1000e8 100755 --- a/admin/authtypes.pl +++ b/admin/authtypes.pl @@ -22,7 +22,7 @@ use Modern::Perl; use CGI qw ( -utf8 ); use C4::Context; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use Koha::Authorities; @@ -33,16 +33,17 @@ my $authtypecode = $input->param('authtypecode'); my $op = $input->param('op') || 'list'; my @messages; my ( $template, $borrowernumber, $cookie ) = get_template_and_user( - { template_name => "admin/authtypes.tt", - query => $input, - type => "intranet", - flagsrequired => { parameters => 'manage_marc_frameworks' }, + { + template_name => "admin/authtypes.tt", + query => $input, + type => "intranet", + flagsrequired => { parameters => 'manage_marc_frameworks' }, } ); if ( $op eq 'add_form' ) { my $authority_type; - if (defined $authtypecode) { + if ( defined $authtypecode ) { $authority_type = Koha::Authority::Types->find($authtypecode); } @@ -67,7 +68,8 @@ if ( $op eq 'add_form' ) { } } else { my $authority_type = Koha::Authority::Type->new( - { authtypecode => $authtypecode, + { + authtypecode => $authtypecode, authtypetext => $authtypetext, auth_tag_to_report => $auth_tag_to_report, summary => $summary, @@ -83,7 +85,7 @@ if ( $op eq 'add_form' ) { $op = 'list'; } elsif ( $op eq 'delete_confirm' ) { - my $authority_type = Koha::Authority::Types->find($authtypecode); + my $authority_type = Koha::Authority::Types->find($authtypecode); my $authorities_using_it = Koha::Authorities->search( { authtypecode => $authtypecode } )->count; $template->param( authority_type => $authority_type, @@ -93,7 +95,7 @@ if ( $op eq 'add_form' ) { my $authorities_using_it = Koha::Authorities->search( { authtypecode => $authtypecode } )->count; if ( $authorities_using_it == 0 ) { my $authority_type = Koha::Authority::Types->find($authtypecode); - my $deleted = eval { $authority_type->delete; }; + my $deleted = eval { $authority_type->delete; }; if ( $@ or not $deleted ) { push @messages, { type => 'error', code => 'error_on_delete' }; diff --git a/admin/background_jobs.pl b/admin/background_jobs.pl index 6eb4b066c6..dd4f56963a 100755 --- a/admin/background_jobs.pl +++ b/admin/background_jobs.pl @@ -20,28 +20,27 @@ use CGI qw ( -utf8 ); use C4::Context; use Koha::DateUtils qw( dt_from_string ); -use C4::Auth qw( get_template_and_user ); -use C4::Output qw( output_html_with_http_headers ); +use C4::Auth qw( get_template_and_user ); +use C4::Output qw( output_html_with_http_headers ); use Koha::BackgroundJobs; use Koha::Virtualshelves; -my $input = CGI->new; -my $op = $input->param('op') || 'list'; +my $input = CGI->new; +my $op = $input->param('op') || 'list'; my @messages; my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "admin/background_jobs.tt", - query => $input, - type => "intranet", - flagsrequired => { catalogue => 1 }, + template_name => "admin/background_jobs.tt", + query => $input, + type => "intranet", + flagsrequired => { catalogue => 1 }, } ); -my $logged_in_user = Koha::Patrons->find($loggedinuser); -my $can_manage_background_jobs = - $logged_in_user->has_permission( { parameters => 'manage_background_jobs' } ); +my $logged_in_user = Koha::Patrons->find($loggedinuser); +my $can_manage_background_jobs = $logged_in_user->has_permission( { parameters => 'manage_background_jobs' } ); if ( $op eq 'view' ) { my $id = $input->param('id'); @@ -50,12 +49,11 @@ if ( $op eq 'view' ) { && !$can_manage_background_jobs ) { push @messages, { code => 'cannot_view_job' }; - } - else { + } else { $template->param( job => $job, ); if ( $job->status ne 'new' ) { my $report = $job->additional_report() || {}; - $template->param( %$report ); + $template->param(%$report); } } } else { @@ -64,14 +62,13 @@ if ( $op eq 'view' ) { } if ( $op eq 'cud-cancel' ) { - my $id = $input->param('id'); + my $id = $input->param('id'); my $job = Koha::BackgroundJobs->find($id); if ( $can_manage_background_jobs || $job->borrowernumber eq $logged_in_user->borrowernumber ) { $job->cancel; - } - else { + } else { push @messages, { code => 'cannot_cancel_job' }; } $op = 'list'; diff --git a/admin/biblio_framework.pl b/admin/biblio_framework.pl index a6f0e10050..29b13d60d9 100755 --- a/admin/biblio_framework.pl +++ b/admin/biblio_framework.pl @@ -21,7 +21,7 @@ use Modern::Perl; use CGI qw ( -utf8 ); use C4::Context; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use Koha::Biblios; use Koha::BiblioFramework; @@ -30,15 +30,16 @@ use Koha::Caches; my $input = CGI->new; my $frameworkcode = $input->param('frameworkcode') || q||; -my $op = $input->param('op') || q|list|; +my $op = $input->param('op') || q|list|; my $cache = Koha::Caches->get_instance(); my @messages; my ( $template, $borrowernumber, $cookie ) = get_template_and_user( - { template_name => "admin/biblio_framework.tt", - query => $input, - type => "intranet", - flagsrequired => { parameters => 'manage_marc_frameworks' }, + { + template_name => "admin/biblio_framework.tt", + query => $input, + type => "intranet", + flagsrequired => { parameters => 'manage_marc_frameworks' }, } ); @@ -65,7 +66,8 @@ if ( $op eq 'add_form' ) { } } else { my $framework = Koha::BiblioFramework->new( - { frameworkcode => $frameworkcode, + { + frameworkcode => $frameworkcode, frameworktext => $frameworktext, } ); @@ -83,7 +85,7 @@ if ( $op eq 'add_form' ) { $op = 'list'; } elsif ( $op eq 'delete_confirm' ) { my $framework = Koha::BiblioFrameworks->find($frameworkcode); - my $count = Koha::Biblios->search( { frameworkcode => $frameworkcode, } )->count; + my $count = Koha::Biblios->search( { frameworkcode => $frameworkcode, } )->count; $template->param( framework => $framework, @@ -91,7 +93,7 @@ if ( $op eq 'add_form' ) { ); } elsif ( $op eq 'cud-delete_confirmed' ) { my $framework = Koha::BiblioFrameworks->find($frameworkcode); - my $deleted = eval { $framework->delete; }; + my $deleted = eval { $framework->delete; }; if ( $@ or not $deleted ) { push @messages, { type => 'error', code => 'error_on_delete' }; diff --git a/admin/branch_transfer_limits.pl b/admin/branch_transfer_limits.pl index 3b45a68867..403d38b710 100755 --- a/admin/branch_transfer_limits.pl +++ b/admin/branch_transfer_limits.pl @@ -20,31 +20,30 @@ use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Auth qw( get_template_and_user ); use C4::Context; -use C4::Output qw( output_html_with_http_headers ); +use C4::Output qw( output_html_with_http_headers ); use C4::Circulation qw( DeleteBranchTransferLimits CreateBranchTransferLimit IsBranchTransferAllowed ); my $input = CGI->new; -my $op = $input->param('op') || q{}; +my $op = $input->param('op') || q{}; -my ($template, $loggedinuser, $cookie) - = get_template_and_user({template_name => "admin/branch_transfer_limits.tt", - query => $input, - type => "intranet", - flagsrequired => {parameters => 'manage_transfers'}, - }); +my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "admin/branch_transfer_limits.tt", + query => $input, + type => "intranet", + flagsrequired => { parameters => 'manage_transfers' }, + } +); my $dbh = C4::Context->dbh; my $branchcode; -if((!defined($input->param('branchcode'))) & C4::Context::mybranch() ne '') -{ +if ( ( !defined( $input->param('branchcode') ) ) & C4::Context::mybranch() ne '' ) { $branchcode = C4::Context::mybranch(); -} -else -{ - $branchcode = $input->param('branchcode'); +} else { + $branchcode = $input->param('branchcode'); } # Set the template language for the correct limit type using $limitType @@ -54,7 +53,7 @@ my @codes; my @branchcodes; if ( $limitType eq 'ccode' ) { - @codes = Koha::AuthorisedValues->search({ category => 'CCODE' })->get_column('authorised_value'); + @codes = Koha::AuthorisedValues->search( { category => 'CCODE' } )->get_column('authorised_value'); } elsif ( $limitType eq 'itemtype' ) { @codes = Koha::ItemTypes->search->get_column('itemtype'); } @@ -64,53 +63,51 @@ if ( $limitType eq 'ccode' ) { if ( $input->param('updateLimits') && $op eq 'cud-update' ) { DeleteBranchTransferLimits($branchcode); - - foreach my $code ( @codes ) { - foreach my $toBranch ( @branchcodes ) { - my $isSet = not $input->param( $code . "_" . $toBranch); - if ( $isSet ) { - CreateBranchTransferLimit( $toBranch, $branchcode, $code ); - } - } - } + foreach my $code (@codes) { + foreach my $toBranch (@branchcodes) { + my $isSet = not $input->param( $code . "_" . $toBranch ); + if ($isSet) { + CreateBranchTransferLimit( $toBranch, $branchcode, $code ); + } + } + } } ## Build branchcode loop my @branchcode_loop; -foreach my $branchcode ( @branchcodes ) { - my %row_data; - $row_data{ branchcode } = $branchcode; - push ( @branchcode_loop, \%row_data ); +foreach my $branchcode (@branchcodes) { + my %row_data; + $row_data{branchcode} = $branchcode; + push( @branchcode_loop, \%row_data ); } my $branchcount = scalar(@branchcode_loop); ## Build the default data my @codes_loop; -foreach my $code ( @codes ) { - my @to_branch_loop; - my %row_data; - $row_data{ code } = $code; - $row_data{ to_branch_loop } = \@to_branch_loop; - foreach my $toBranch ( @branchcodes ) { - my %row_data; - my $isChecked = IsBranchTransferAllowed( $toBranch, $branchcode, $code ); - $row_data{ code } = $code; - $row_data{ toBranch } = $toBranch; - $row_data{ isChecked } = $isChecked; - push( @to_branch_loop, \%row_data ); - } +foreach my $code (@codes) { + my @to_branch_loop; + my %row_data; + $row_data{code} = $code; + $row_data{to_branch_loop} = \@to_branch_loop; + foreach my $toBranch (@branchcodes) { + my %row_data; + my $isChecked = IsBranchTransferAllowed( $toBranch, $branchcode, $code ); + $row_data{code} = $code; + $row_data{toBranch} = $toBranch; + $row_data{isChecked} = $isChecked; + push( @to_branch_loop, \%row_data ); + } - push( @codes_loop, \%row_data ); + push( @codes_loop, \%row_data ); } - $template->param( - branchcount => $branchcount, - codes_loop => \@codes_loop, - branchcode_loop => \@branchcode_loop, - branchcode => $branchcode, - limitType => $limitType, - ); + branchcount => $branchcount, + codes_loop => \@codes_loop, + branchcode_loop => \@branchcode_loop, + branchcode => $branchcode, + limitType => $limitType, +); output_html_with_http_headers $input, $cookie, $template->output; diff --git a/admin/branches.pl b/admin/branches.pl index b6d705cd18..bcfead37f6 100755 --- a/admin/branches.pl +++ b/admin/branches.pl @@ -20,7 +20,7 @@ use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use Try::Tiny qw( catch try ); use C4::Auth qw( get_template_and_user ); @@ -42,10 +42,11 @@ my $op = $input->param('op') || 'list'; my @messages; my ( $template, $borrowernumber, $cookie ) = get_template_and_user( - { template_name => "admin/branches.tt", - query => $input, - type => "intranet", - flagsrequired => { parameters => 'manage_libraries' }, + { + template_name => "admin/branches.tt", + query => $input, + type => "intranet", + flagsrequired => { parameters => 'manage_libraries' }, } ); @@ -57,40 +58,41 @@ if ( $op eq 'add_form' ) { } elsif ( $branchcode && $op eq 'view' ) { my $library = Koha::Libraries->find($branchcode); $template->param( - library => $library, + library => $library, ); } elsif ( $op eq 'cud-add_validate' ) { my @fields = qw( - branchname - branchaddress1 - branchaddress2 - branchaddress3 - branchzip - branchcity - branchstate - branchcountry - branchphone - branchfax - branchemail - branchillemail - branchreplyto - branchreturnpath - branchurl - issuing - branchip - branchnotes - marcorgcode - pickup_location - public - opacuserjs - opacusercss + branchname + branchaddress1 + branchaddress2 + branchaddress3 + branchzip + branchcity + branchstate + branchcountry + branchphone + branchfax + branchemail + branchillemail + branchreplyto + branchreturnpath + branchurl + issuing + branchip + branchnotes + marcorgcode + pickup_location + public + opacuserjs + opacusercss ); my $is_a_modif = $input->param('is_a_modif'); if ($is_a_modif) { my $library = Koha::Libraries->find($branchcode); for my $field (@fields) { - if( $field =~ /^(pickup_location|public)$/ ) { + if ( $field =~ /^(pickup_location|public)$/ ) { + # Don't fallback to undef/NULL, default is 1 in DB $library->$field( scalar $input->param($field) ); } else { @@ -149,8 +151,7 @@ if ( $op eq 'add_form' ) { push @messages, { type => 'message', code => 'success_on_update' }; } ); - } - catch { + } catch { push @messages, { type => 'alert', code => 'error_on_update' }; }; } else { @@ -160,9 +161,9 @@ if ( $op eq 'add_form' ) { branchcode => $branchcode, ( map { - /^(pickup_location|public)$/ # Don't fallback to undef for those fields - ? ( $_ => scalar $input->param($_) ) - : ( $_ => scalar $input->param($_) || undef ) + /^(pickup_location|public)$/ # Don't fallback to undef for those fields + ? ( $_ => scalar $input->param($_) ) + : ( $_ => scalar $input->param($_) || undef ) } @fields ) } @@ -211,16 +212,16 @@ if ( $op eq 'add_form' ) { push @messages, { type => 'message', code => 'success_on_insert' }; } ); - } - catch { + } catch { push @messages, { type => 'alert', code => 'error_on_insert' }; }; } $op = 'list'; } elsif ( $op eq 'delete_confirm' ) { - my $library = Koha::Libraries->find($branchcode); + my $library = Koha::Libraries->find($branchcode); my $items_count = Koha::Items->search( - { -or => { + { + -or => { holdingbranch => $branchcode, homebranch => $branchcode }, @@ -230,13 +231,14 @@ if ( $op eq 'add_form' ) { if ( $items_count or $patrons_count ) { push @messages, - { type => 'alert', + { + type => 'alert', code => 'cannot_delete_library', data => { items_count => $items_count, patrons_count => $patrons_count, }, - }; + }; $op = 'list'; } else { $template->param( diff --git a/admin/cash_registers.pl b/admin/cash_registers.pl index 94eebbd5a0..ecc32da8fb 100755 --- a/admin/cash_registers.pl +++ b/admin/cash_registers.pl @@ -33,10 +33,10 @@ use Koha::Cash::Registers; my $cgi = CGI->new(); my ( $template, $borrowernumber, $cookie ) = get_template_and_user( { - template_name => 'admin/cash_registers.tt', - query => $cgi, - type => 'intranet', - flagsrequired => { parameters => 'manage_cash_registers' }, + template_name => 'admin/cash_registers.tt', + query => $cgi, + type => 'intranet', + flagsrequired => { parameters => 'manage_cash_registers' }, } ); @@ -50,13 +50,12 @@ if ( $op eq 'add_form' ) { $template->param( cash_register => $cash_register ); } my $libraries = - Koha::Libraries->search( {}, { order_by => ['branchcode'] }, ); + Koha::Libraries->search( {}, { order_by => ['branchcode'] }, ); $template->param( branch_list => $libraries, add_form => 1 ); -} -elsif ( $op eq 'cud-add_validate' ) { +} elsif ( $op eq 'cud-add_validate' ) { my $name = $cgi->param('name'); $name ||= q{}; my $description = $cgi->param('description'); @@ -75,12 +74,10 @@ elsif ( $op eq 'cud-add_validate' ) { } )->store; push @messages, { code => 'success_on_update', type => 'message' }; - } - catch { + } catch { push @messages, { code => 'error_on_update', type => 'alert' }; } - } - else { + } else { try { my $cash_register = Koha::Cash::Register->new( { @@ -91,74 +88,65 @@ elsif ( $op eq 'cud-add_validate' ) { } )->store; push @messages, { code => 'success_on_insert', type => 'message' }; - } - catch { + } catch { push @messages, { code => 'error_on_insert', type => 'alert' }; } } $op = 'list'; -} -elsif ( $op eq 'cud-archive' ) { +} elsif ( $op eq 'cud-archive' ) { if ($registerid) { try { my $cash_register = Koha::Cash::Registers->find($registerid); $cash_register->archived(1)->store(); push @messages, { code => 'success_on_archive', type => 'message' }; - } - catch { + } catch { push @messages, { code => 'error_on_archive', type => 'alert' }; } } $op = 'list'; -} -elsif ( $op eq 'cud-unarchive' ) { +} elsif ( $op eq 'cud-unarchive' ) { if ($registerid) { try { my $cash_register = Koha::Cash::Registers->find($registerid); $cash_register->archived(0)->store(); push @messages, { code => 'success_on_restore', type => 'message' }; - } - catch { + } catch { push @messages, { code => 'error_on_restore', type => 'alert' }; } } $op = 'list'; -} -elsif ( $op eq 'cud-make_default' ) { +} elsif ( $op eq 'cud-make_default' ) { if ($registerid) { try { my $cash_register = Koha::Cash::Registers->find($registerid); $cash_register->make_default; push @messages, { code => 'success_on_default', type => 'message' }; - } - catch { + } catch { push @messages, { code => 'error_on_default', type => 'alert' }; } } $op = 'list'; -} -elsif ( $op eq 'cud-drop_default' ) { +} elsif ( $op eq 'cud-drop_default' ) { if ($registerid) { try { my $cash_register = Koha::Cash::Registers->find($registerid); $cash_register->drop_default; push @messages, { code => 'success_on_default', type => 'message' }; - } - catch { + } catch { push @messages, { code => 'error_on_default', type => 'alert' }; } } $op = 'list'; } - if ( $op eq 'list' ) { - my $cash_registers = - Koha::Cash::Registers->search( {}, - { prefetch => 'branch', order_by => { -asc => [qw/branch name/] } } ); + my $cash_registers = Koha::Cash::Registers->search( + {}, + { prefetch => 'branch', order_by => { -asc => [qw/branch name/] } } + ); $template->param( cash_registers => $cash_registers, ); } diff --git a/admin/categories.pl b/admin/categories.pl index ce1bd85d28..6093583888 100755 --- a/admin/categories.pl +++ b/admin/categories.pl @@ -22,7 +22,7 @@ use Modern::Perl; use CGI qw ( -utf8 ); use C4::Context; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use C4::Form::MessagingPreferences; use Koha::Patrons; @@ -30,18 +30,18 @@ use Koha::Database; use Koha::Patron::Categories; use Koha::Libraries; -my $input = CGI->new; -my $searchfield = $input->param('description') // q||; -my $categorycode = $input->param('categorycode'); -my $op = $input->param('op') // 'list'; +my $input = CGI->new; +my $searchfield = $input->param('description') // q||; +my $categorycode = $input->param('categorycode'); +my $op = $input->param('op') // 'list'; my @messages; my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "admin/categories.tt", - query => $input, - type => "intranet", - flagsrequired => { parameters => 'manage_patron_categories' }, + template_name => "admin/categories.tt", + query => $input, + type => "intranet", + flagsrequired => { parameters => 'manage_patron_categories' }, } ); @@ -54,8 +54,7 @@ if ( $op eq 'add_form' ) { if ( C4::Context->preference('EnhancedMessagingPreferences') ) { C4::Form::MessagingPreferences::set_form_values( { categorycode => $categorycode }, $template ); } -} -elsif ( $op eq 'cud-add_validate' ) { +} elsif ( $op eq 'cud-add_validate' ) { my $categorycode = $input->param('categorycode'); my $description = $input->param('description'); my $enrolmentperiod = $input->param('enrolmentperiod'); @@ -77,12 +76,12 @@ elsif ( $op eq 'cud-add_validate' ) { my $exclude_from_local_holds_priority = $input->param('exclude_from_local_holds_priority'); my $min_password_length = $input->param('min_password_length'); my $require_strong_password = $input->param('require_strong_password'); - my $noissuescharge = $input->param('noissuescharge') || undef; - my $noissueschargeguarantees = $input->param('noissueschargeguarantees') || undef; + my $noissuescharge = $input->param('noissuescharge') || undef; + my $noissueschargeguarantees = $input->param('noissueschargeguarantees') || undef; my $noissueschargeguarantorswithguarantees = $input->param('noissueschargeguarantorswithguarantees') || undef; - my @branches = grep { $_ ne q{} } $input->multi_param('branches'); - my $can_be_guarantee = $input->param('can_be_guarantee'); + my @branches = grep { $_ ne q{} } $input->multi_param('branches'); + my $can_be_guarantee = $input->param('can_be_guarantee'); my $force_password_reset_when_set_by_staff = $input->param('force_password_reset_when_set_by_staff'); $reset_password = undef if $reset_password eq -1; @@ -182,29 +181,25 @@ elsif ( $op eq 'cud-add_validate' ) { $searchfield = q||; $op = 'list'; -} -elsif ( $op eq 'delete_confirm' ) { +} elsif ( $op eq 'delete_confirm' ) { - my $count = Koha::Patrons->search({ - categorycode => $categorycode - })->count; + my $count = Koha::Patrons->search( { categorycode => $categorycode } )->count; my $category = Koha::Patron::Categories->find($categorycode); $template->param( - category => $category, + category => $category, patrons_in_category => $count, ); -} -elsif ( $op eq 'cud-delete_confirmed' ) { +} elsif ( $op eq 'cud-delete_confirmed' ) { my $categorycode = uc( $input->param('categorycode') ); - my $category = Koha::Patron::Categories->find( $categorycode ); - my $deleted = eval { $category->delete; }; + my $category = Koha::Patron::Categories->find($categorycode); + my $deleted = eval { $category->delete; }; if ( $@ or not $deleted ) { - push @messages, {type => 'error', code => 'error_on_delete' }; + push @messages, { type => 'error', code => 'error_on_delete' }; } else { push @messages, { type => 'message', code => 'success_on_delete' }; } @@ -214,24 +209,20 @@ elsif ( $op eq 'cud-delete_confirmed' ) { if ( $op eq 'list' ) { my $categories = Koha::Patron::Categories->search( - { - description => { -like => "$searchfield%" } - }, - { - order_by => ['category_type', 'description', 'categorycode' ] - } + { description => { -like => "$searchfield%" } }, + { order_by => [ 'category_type', 'description', 'categorycode' ] } ); $template->param( categories => $categories, - ) + ); } $template->param( categorycode => $categorycode, searchfield => $searchfield, messages => \@messages, - op => $op, + op => $op, ); output_html_with_http_headers $input, $cookie, $template->output; diff --git a/admin/check_budget_parent.pl b/admin/check_budget_parent.pl index 2274679f3b..4e2edb8ed0 100755 --- a/admin/check_budget_parent.pl +++ b/admin/check_budget_parent.pl @@ -20,8 +20,8 @@ use Modern::Perl; use CGI qw ( -utf8 ); use C4::Context; -use C4::Output qw( output_html_with_http_headers ); -use C4::Auth qw( get_template_and_user ); +use C4::Output qw( output_html_with_http_headers ); +use C4::Auth qw( get_template_and_user ); use C4::Budgets qw( CheckBudgetParent GetBudget ); =head1 DESCRIPTION @@ -37,9 +37,10 @@ my $budget_id = $input->param('budget_id'); my $new_parent_id = $input->param('new_parent'); my ( $template, $loggedinuser, $cookie ) = get_template_and_user( - { template_name => "acqui/ajax.tt", - query => $input, - type => "intranet", + { + template_name => "acqui/ajax.tt", + query => $input, + type => "intranet", } ); diff --git a/admin/check_parent_total.pl b/admin/check_parent_total.pl index 95a38328c2..94770eca5c 100755 --- a/admin/check_parent_total.pl +++ b/admin/check_parent_total.pl @@ -20,8 +20,8 @@ use Modern::Perl; use CGI qw ( -utf8 ); use C4::Context; -use C4::Output qw( output_html_with_http_headers ); -use C4::Auth qw( get_template_and_user ); +use C4::Output qw( output_html_with_http_headers ); +use C4::Auth qw( get_template_and_user ); use C4::Budgets qw( GetBudget GetBudgetPeriod ); =head1 DESCRIPTION @@ -33,7 +33,7 @@ to determine whether the new parent budget (or period) has enough unallocated fu =cut -my $dbh = C4::Context->dbh; +my $dbh = C4::Context->dbh; my $input = CGI->new; my $total = $input->param('total'); @@ -43,29 +43,31 @@ my $period_id = $input->param('period_id'); my $returncode; my ( $template, $loggedinuser, $cookie ) = get_template_and_user( - { template_name => "acqui/ajax.tt", - query => $input, - type => "intranet", + { + template_name => "acqui/ajax.tt", + query => $input, + type => "intranet", } ); -my ($period, $parent , $budget); +my ( $period, $parent, $budget ); $period = GetBudgetPeriod($period_id) if $period_id; $parent = GetBudget($parent_id) if defined $parent_id; $budget = GetBudget($budget_id) if defined $budget_id; # CHECK THE PARENT BUDGET FOR ENOUGHT AMOUNT UNALLOCATED, IF NOT THEN RETURN 1 -my ($sub_unalloc , $period_sum, $budget_period_unalloc); +my ( $sub_unalloc, $period_sum, $budget_period_unalloc ); if ($parent) { my $query = " SELECT SUM(budget_amount) as sum FROM aqbudgets where budget_parent_id = ? "; my @sql_params; - my $sth = $dbh->prepare($query); + my $sth = $dbh->prepare($query); $sth->execute( $parent->{'budget_id'} ); my $sum = $sth->fetchrow_hashref; $sth->finish; $sub_unalloc = $parent->{'budget_amount'} - $sum->{sum}; -# TRICKY.. , IF THE PARENT IS THE CURRENT PARENT - THEN SUBTRACT CURRENT BUDGET FROM TOTAL - $sub_unalloc += $budget->{'budget_amount'} if ( $budget->{'budget_parent_id'} == $parent_id ) ; + + # TRICKY.. , IF THE PARENT IS THE CURRENT PARENT - THEN SUBTRACT CURRENT BUDGET FROM TOTAL + $sub_unalloc += $budget->{'budget_amount'} if ( $budget->{'budget_parent_id'} == $parent_id ); } # ELSE , IF NO PARENT PASSED, THEN CHECK UNALLOCATED FOR PERIOD, IF NOT THEN RETURN 2 @@ -74,16 +76,17 @@ else { FROM aqbudgets WHERE budget_period_id = ? and budget_parent_id IS NULL |; my @sql_params; push @sql_params, $period_id; - if ($budget_id){ - $query.=qq| and budget_id <> ? |; - push @sql_params,$budget_id; + if ($budget_id) { + $query .= qq| and budget_id <> ? |; + push @sql_params, $budget_id; } my $sth = $dbh->prepare($query); $sth->execute(@sql_params); $period_sum = $sth->fetchrow_hashref; $sth->finish; - $budget_period_unalloc = $period->{'budget_period_total'} - $period_sum->{'sum'} if $period->{'budget_period_total'}; + $budget_period_unalloc = $period->{'budget_period_total'} - $period_sum->{'sum'} + if $period->{'budget_period_total'}; } # FIXME - we really need a better way to do this consistently @@ -94,8 +97,8 @@ $total = sprintf( "%.2f", $total ); $sub_unalloc = sprintf( "%.2f", $sub_unalloc ); $budget_period_unalloc = sprintf( "%.2f", $budget_period_unalloc ); -if ( $parent_id) { - if ( ($total > $sub_unalloc ) && $sub_unalloc ) { +if ($parent_id) { + if ( ( $total > $sub_unalloc ) && $sub_unalloc ) { $returncode = 1; } } elsif ( ( $total > $budget_period_unalloc ) && $budget_period_unalloc ) { @@ -105,6 +108,5 @@ if ( $parent_id) { $returncode = 0; } - output_html_with_http_headers $input, $cookie, $returncode; 1; diff --git a/admin/checkmarc.pl b/admin/checkmarc.pl index 3dcda21432..0558d5cfd3 100755 --- a/admin/checkmarc.pl +++ b/admin/checkmarc.pl @@ -1,6 +1,5 @@ #!/usr/bin/perl - # Copyright 2000-2002 Katipo Communications # # This file is part of Koha. @@ -20,152 +19,162 @@ use Modern::Perl; use C4::Output qw( output_html_with_http_headers ); -use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); use C4::Context; - my $input = CGI->new; -my ($template, $borrowernumber, $cookie) - = get_template_and_user({template_name => "admin/checkmarc.tt", - query => $input, - type => "intranet", - flagsrequired => { parameters => 'manage_marc_frameworks' }, - }); +my ( $template, $borrowernumber, $cookie ) = get_template_and_user( + { + template_name => "admin/checkmarc.tt", + query => $input, + type => "intranet", + flagsrequired => { parameters => 'manage_marc_frameworks' }, + } +); -my $dbh = C4::Context->dbh; +my $dbh = C4::Context->dbh; my $total = 0; + # checks itemnum field my $sth = $dbh->prepare("select tab from marc_subfield_structure where kohafield=\"items.itemnumber\""); $sth->execute; -while (my ($res) = $sth->fetchrow) { - if ($res==-1) { - $template->param(itemnum => 0); +while ( my ($res) = $sth->fetchrow ) { + if ( $res == -1 ) { + $template->param( itemnum => 0 ); } else { - $template->param(itemnum => 1); - $total++; + $template->param( itemnum => 1 ); + $total++; last; } } # checks biblio.biblionumber and biblioitem.biblioitemnumber (same tag and tab=-1) -$sth = $dbh->prepare("select tagfield,tab,frameworkcode from marc_subfield_structure where kohafield=\"biblio.biblionumber\""); +$sth = $dbh->prepare( + "select tagfield,tab,frameworkcode from marc_subfield_structure where kohafield=\"biblio.biblionumber\""); $sth->execute; -my $first = 1; +my $first = 1; my $bibliotag = ''; -while (my ($res,$tab,$frameworkcode) = $sth->fetchrow) { +while ( my ( $res, $tab, $frameworkcode ) = $sth->fetchrow ) { if ($first) { $bibliotag = $res; - $first = 0; + $first = 0; } else { - if ($bibliotag != $res) { - $template->param(biblionumber => 1); - $total++; + if ( $bibliotag != $res ) { + $template->param( biblionumber => 1 ); + $total++; last; } } - my $sth2 = $dbh->prepare("SELECT tagfield,tab + my $sth2 = $dbh->prepare( + "SELECT tagfield,tab FROM marc_subfield_structure WHERE kohafield=\"biblioitems.biblioitemnumber\" - AND frameworkcode = ? "); + AND frameworkcode = ? " + ); $sth2->execute($frameworkcode); - my ($res2,$tab2) = $sth2->fetchrow; - if ($res && $res2 && $tab==-1 && $tab2==-1) { - $template->param(biblionumber => 0); + my ( $res2, $tab2 ) = $sth2->fetchrow; + if ( $res && $res2 && $tab == -1 && $tab2 == -1 ) { + $template->param( biblionumber => 0 ); } else { - $template->param(biblionumber => 1); - $total++; + $template->param( biblionumber => 1 ); + $total++; last; } } # checks all item fields are in the same tag and in tab 10 -$sth = $dbh->prepare("select tagfield,tab,kohafield from marc_subfield_structure where kohafield like \"items.%\" and tab >=0"); +$sth = $dbh->prepare( + "select tagfield,tab,kohafield from marc_subfield_structure where kohafield like \"items.%\" and tab >=0"); $sth->execute; my $field; my $res; my $res2; my $tab; -($res,$res2,$field) = $sth->fetchrow; +( $res, $res2, $field ) = $sth->fetchrow; my $tagfield = $res; $tab = $res2; -my $subtotal=0; +my $subtotal = 0; + #warn "TAGF : $tagfield"; -while (($res,$res2,$field) = $sth->fetchrow) { - # (ignore itemnumber, that must be in -1 tab) - if (($res ne $tagfield) or ($res2 ne $tab)) { - $subtotal++; - } +while ( ( $res, $res2, $field ) = $sth->fetchrow ) { + + # (ignore itemnumber, that must be in -1 tab) + if ( ( $res ne $tagfield ) or ( $res2 ne $tab ) ) { + $subtotal++; + } } $sth = $dbh->prepare("select kohafield from marc_subfield_structure where tagfield=?"); $sth->execute($tagfield); -while (($res2) = $sth->fetchrow) { - if (!$res2 || $res2 =~ /^items/) { - } else { - $subtotal++; - } +while ( ($res2) = $sth->fetchrow ) { + if ( !$res2 || $res2 =~ /^items/ ) { + } else { + $subtotal++; + } } -if ($subtotal == 0) { - $template->param(itemfields => 0); +if ( $subtotal == 0 ) { + $template->param( itemfields => 0 ); } else { - $template->param(itemfields => 1); - $total++; + $template->param( itemfields => 1 ); + $total++; } $sth = $dbh->prepare("select distinct tagfield from marc_subfield_structure where tab = 10"); $sth->execute; my $totaltags = 0; -my $list = ""; -while (($res2) = $sth->fetchrow) { - $totaltags++; - $list.=$res2.","; +my $list = ""; +while ( ($res2) = $sth->fetchrow ) { + $totaltags++; + $list .= $res2 . ","; } -if ($totaltags > 1) { - $template->param(itemtags => $list); - $total++; +if ( $totaltags > 1 ) { + $template->param( itemtags => $list ); + $total++; } else { - $template->param(itemtags => 0); + $template->param( itemtags => 0 ); } - # checks biblioitems.itemtype must be mapped and use authorised_value=itemtype -$sth = $dbh->prepare("select tagfield,tab,authorised_value from marc_subfield_structure where kohafield = \"biblioitems.itemtype\""); +$sth = $dbh->prepare( + "select tagfield,tab,authorised_value from marc_subfield_structure where kohafield = \"biblioitems.itemtype\""); $sth->execute; -while (($res,$res2,$field) = $sth->fetchrow) { - if ($res && $res2>=0 && $field eq "itemtypes") { - $template->param(itemtype => 0); +while ( ( $res, $res2, $field ) = $sth->fetchrow ) { + if ( $res && $res2 >= 0 && $field eq "itemtypes" ) { + $template->param( itemtype => 0 ); } else { - $template->param(itemtype => 1); - $total++; + $template->param( itemtype => 1 ); + $total++; last; } } # checks items.homebranch must be mapped and use authorised_value=branches -$sth = $dbh->prepare("select tagfield,tab,authorised_value from marc_subfield_structure where kohafield = \"items.homebranch\""); +$sth = $dbh->prepare( + "select tagfield,tab,authorised_value from marc_subfield_structure where kohafield = \"items.homebranch\""); $sth->execute; -while (($res,$res2,$field) = $sth->fetchrow) { - if ($res && $res2 eq 10 && $field eq "branches") { - $template->param(branch => 0); +while ( ( $res, $res2, $field ) = $sth->fetchrow ) { + if ( $res && $res2 eq 10 && $field eq "branches" ) { + $template->param( branch => 0 ); } else { - $template->param(branch => 1); - $total++; + $template->param( branch => 1 ); + $total++; last; } } # checks items.homebranch must be mapped and use authorised_value=branches -$sth = $dbh->prepare("select tagfield,tab,authorised_value from marc_subfield_structure where kohafield = \"items.holdingbranch\""); +$sth = $dbh->prepare( + "select tagfield,tab,authorised_value from marc_subfield_structure where kohafield = \"items.holdingbranch\""); $sth->execute; -while (($res,$res2,$field) = $sth->fetchrow) { - if ($res && $res2 eq 10 && $field eq "branches") { - $template->param(holdingbranch => 0); +while ( ( $res, $res2, $field ) = $sth->fetchrow ) { + if ( $res && $res2 eq 10 && $field eq "branches" ) { + $template->param( holdingbranch => 0 ); } else { - $template->param(holdingbranch => 1); - $total++; - last; #MR + $template->param( holdingbranch => 1 ); + $total++; + last; #MR } } @@ -174,88 +183,93 @@ $sth = $dbh->prepare("select count(*) from itemtypes"); $sth->execute; ($res) = $sth->fetchrow; if ($res) { - $template->param(itemtypes_empty =>0); + $template->param( itemtypes_empty => 0 ); } else { - $template->param(itemtypes_empty =>1); - $total++; + $template->param( itemtypes_empty => 1 ); + $total++; } - $sth = $dbh->prepare("select count(*) from branches"); $sth->execute; ($res) = $sth->fetchrow; if ($res) { - $template->param(branches_empty =>0); + $template->param( branches_empty => 0 ); } else { - $template->param(branches_empty =>1); - $total++; + $template->param( branches_empty => 1 ); + $total++; } $sth = $dbh->prepare("select count(*) from marc_subfield_structure where frameworkcode is NULL"); $sth->execute; ($res) = $sth->fetchrow; if ($res) { - $template->param(frameworknull =>1); - $total++; + $template->param( frameworknull => 1 ); + $total++; } $sth = $dbh->prepare("select count(*) from marc_tag_structure where frameworkcode is NULL"); $sth->execute; ($res) = $sth->fetchrow; if ($res) { - $template->param(frameworknull =>1); - $total++; + $template->param( frameworknull => 1 ); + $total++; } # verify that all of a field's subfields (except the ones explicitly ignored) # are in the same tab -$sth = $dbh->prepare("SELECT tagfield, frameworkcode, frameworktext, GROUP_CONCAT(DISTINCT tab) AS tabs +$sth = $dbh->prepare( + "SELECT tagfield, frameworkcode, frameworktext, GROUP_CONCAT(DISTINCT tab) AS tabs FROM marc_subfield_structure LEFT JOIN biblio_framework USING (frameworkcode) WHERE tab != -1 GROUP BY tagfield, frameworkcode, frameworktext - HAVING COUNT(DISTINCT tab) > 1"); + HAVING COUNT(DISTINCT tab) > 1" +); $sth->execute; -my $inconsistent_tabs = $sth->fetchall_arrayref({}); -if (scalar(@$inconsistent_tabs) > 0) { +my $inconsistent_tabs = $sth->fetchall_arrayref( {} ); +if ( scalar(@$inconsistent_tabs) > 0 ) { $total++; - $template->param(inconsistent_tabs => 1); - $template->param(tab_info => $inconsistent_tabs); + $template->param( inconsistent_tabs => 1 ); + $template->param( tab_info => $inconsistent_tabs ); } -# verify that authtypecodes used in the framework +# verify that authtypecodes used in the framework # are defined in auth_types -$sth = $dbh->prepare("SELECT frameworkcode, frameworktext, tagfield, tagsubfield, authtypecode +$sth = $dbh->prepare( + "SELECT frameworkcode, frameworktext, tagfield, tagsubfield, authtypecode FROM marc_subfield_structure LEFT JOIN biblio_framework USING (frameworkcode) WHERE authtypecode IS NOT NULL AND authtypecode <> '' AND tab > '-1' AND authtypecode NOT IN (SELECT authtypecode FROM auth_types) - ORDER BY frameworkcode, tagfield, tagsubfield"); + ORDER BY frameworkcode, tagfield, tagsubfield" +); $sth->execute; -my $invalid_authtypecodes = $sth->fetchall_arrayref({}); -if (scalar(@$invalid_authtypecodes) > 0) { +my $invalid_authtypecodes = $sth->fetchall_arrayref( {} ); +if ( scalar(@$invalid_authtypecodes) > 0 ) { $total++; - $template->param(invalid_authtypecodes => 1); - $template->param(authtypecode_info => $invalid_authtypecodes); + $template->param( invalid_authtypecodes => 1 ); + $template->param( authtypecode_info => $invalid_authtypecodes ); } # checks items.permanent_location is not mapped -$sth = $dbh->prepare("SELECT frameworkcode, frameworktext, tagfield, tagsubfield +$sth = $dbh->prepare( + "SELECT frameworkcode, frameworktext, tagfield, tagsubfield FROM marc_subfield_structure LEFT JOIN biblio_framework USING (frameworkcode) WHERE kohafield='permanent_location' OR - kohafield='items.permanent_location'"); + kohafield='items.permanent_location'" +); $sth->execute; -my $permanent_location_mapped = $sth->fetchall_arrayref({}); -if (scalar(@$permanent_location_mapped) > 0) { +my $permanent_location_mapped = $sth->fetchall_arrayref( {} ); +if ( scalar(@$permanent_location_mapped) > 0 ) { $total++; - $template->param(permanent_location_mapped => 1); - $template->param(mapped_permanent_location => $permanent_location_mapped); + $template->param( permanent_location_mapped => 1 ); + $template->param( mapped_permanent_location => $permanent_location_mapped ); } - -$template->param(total => $total, - ); +$template->param( + total => $total, +); output_html_with_http_headers $input, $cookie, $template->output; diff --git a/admin/cities.pl b/admin/cities.pl index 8373b9be20..320efa136a 100755 --- a/admin/cities.pl +++ b/admin/cities.pl @@ -21,22 +21,23 @@ use Modern::Perl; use CGI qw ( -utf8 ); use C4::Context; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use Koha::Cities; -my $input = CGI->new; +my $input = CGI->new; my $city_name_filter = $input->param('city_name_filter') // q||; -my $cityid = $input->param('cityid'); -my $op = $input->param('op') || 'list'; +my $cityid = $input->param('cityid'); +my $op = $input->param('op') || 'list'; my @messages; my ( $template, $loggedinuser, $cookie ) = get_template_and_user( - { template_name => "admin/cities.tt", - query => $input, - type => "intranet", - flagsrequired => { parameters => 'manage_cities' }, + { + template_name => "admin/cities.tt", + query => $input, + type => "intranet", + flagsrequired => { parameters => 'manage_cities' }, } ); @@ -68,7 +69,8 @@ if ( $op eq 'add_form' ) { } } else { my $city = Koha::City->new( - { city_name => $city_name, + { + city_name => $city_name, city_state => $city_state, city_zipcode => $city_zipcode, city_country => $city_country, @@ -87,7 +89,7 @@ if ( $op eq 'add_form' ) { my $city = Koha::Cities->find($cityid); $template->param( city => $city, ); } elsif ( $op eq 'cud-delete_confirmed' ) { - my $city = Koha::Cities->find($cityid); + my $city = Koha::Cities->find($cityid); my $deleted = eval { $city->delete; }; if ( $@ or not $deleted ) { @@ -103,10 +105,10 @@ if ( $op eq 'list' ) { } $template->param( - cityid => $cityid, + cityid => $cityid, city_name_filter => $city_name_filter, - messages => \@messages, - op => $op, + messages => \@messages, + op => $op, ); output_html_with_http_headers $input, $cookie, $template->output; diff --git a/admin/classsources.pl b/admin/classsources.pl index 3a35860964..46d9475091 100755 --- a/admin/classsources.pl +++ b/admin/classsources.pl @@ -20,11 +20,11 @@ # use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Auth qw( get_template_and_user ); use C4::Context; -use C4::Output qw( output_html_with_http_headers ); -use C4::ClassSortRoutine qw( GetSortRoutineNames ); +use C4::Output qw( output_html_with_http_headers ); +use C4::ClassSortRoutine qw( GetSortRoutineNames ); use C4::ClassSplitRoutine qw( GetSplitRoutineNames ); use Koha::ClassSources; use Koha::ClassSortRules; @@ -43,25 +43,23 @@ my $used = $input->param('used'); my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "admin/classsources.tt", - query => $input, - type => "intranet", - flagsrequired => { parameters => 'manage_classifications' }, + template_name => "admin/classsources.tt", + query => $input, + type => "intranet", + flagsrequired => { parameters => 'manage_classifications' }, } ); my @messages; if ( $op eq "add_source" ) { - my $class_source = - $cn_source ? Koha::ClassSources->find($cn_source) : undef; + my $class_source = $cn_source ? Koha::ClassSources->find($cn_source) : undef; $template->param( class_source => $class_source, sort_rules => Koha::ClassSortRules->search, split_rules => Koha::ClassSplitRules->search, ); -} -elsif ( $op eq "cud-add_source_validate" ) { +} elsif ( $op eq "cud-add_source_validate" ) { my $class_source = Koha::ClassSources->find($cn_source); if ($class_source) { $class_source->set( @@ -75,15 +73,13 @@ elsif ( $op eq "cud-add_source_validate" ) { eval { $class_source->store; }; if ($@) { push @messages, - { type => 'error', code => 'error_on_update_source' }; - } - else { + { type => 'error', code => 'error_on_update_source' }; + } else { push @messages, - { type => 'message', code => 'success_on_update_source' }; + { type => 'message', code => 'success_on_update_source' }; } - } - else { + } else { $class_source = Koha::ClassSource->new( { cn_source => $cn_source, @@ -96,54 +92,45 @@ elsif ( $op eq "cud-add_source_validate" ) { eval { $class_source->store; }; if ($@) { push @messages, - { type => 'error', code => 'error_on_insert_source' }; - } - else { + { type => 'error', code => 'error_on_insert_source' }; + } else { push @messages, - { type => 'message', code => 'success_on_insert_source' }; + { type => 'message', code => 'success_on_insert_source' }; } } $op = 'list'; -} -elsif ( $op eq "cud-delete_source_confirmed" ) { +} elsif ( $op eq "cud-delete_source_confirmed" ) { my $class_source = Koha::ClassSources->find($cn_source); - my $deleted = eval { $class_source->delete }; + my $deleted = eval { $class_source->delete }; if ( $@ or not $deleted ) { push @messages, { type => 'error', code => 'error_on_delete_source' }; - } - else { + } else { push @messages, - { type => 'message', code => 'success_on_delete_source' }; + { type => 'message', code => 'success_on_delete_source' }; } $op = 'list'; -} -elsif ( $op eq "add_sort_rule" ) { - my $sort_rule = - $class_sort_rule ? Koha::ClassSortRules->find($class_sort_rule) : undef; +} elsif ( $op eq "add_sort_rule" ) { + my $sort_rule = $class_sort_rule ? Koha::ClassSortRules->find($class_sort_rule) : undef; $template->param( sort_rule => $sort_rule, sort_routines => get_class_sort_routines(), ); -} -elsif ( $op eq "cud-add_sort_rule_validate" ) { +} elsif ( $op eq "cud-add_sort_rule_validate" ) { my $sort_rule = Koha::ClassSortRules->find($class_sort_rule); if ($sort_rule) { - $sort_rule->set( - { description => $description, sort_routine => $sort_routine } ); + $sort_rule->set( { description => $description, sort_routine => $sort_routine } ); eval { $sort_rule->store; }; if ($@) { push @messages, - { type => 'error', code => 'error_on_update_sort_rule' }; - } - else { + { type => 'error', code => 'error_on_update_sort_rule' }; + } else { push @messages, - { type => 'message', code => 'success_on_update_sort_rule' }; + { type => 'message', code => 'success_on_update_sort_rule' }; } - } - else { + } else { $sort_rule = Koha::ClassSortRule->new( { class_sort_rule => $class_sort_rule, @@ -154,42 +141,37 @@ elsif ( $op eq "cud-add_sort_rule_validate" ) { eval { $sort_rule->store; }; if ($@) { push @messages, - { type => 'error', code => 'error_on_insert_sort_rule' }; - } - else { + { type => 'error', code => 'error_on_insert_sort_rule' }; + } else { push @messages, - { type => 'message', code => 'success_on_insert_sort_rule' }; + { type => 'message', code => 'success_on_insert_sort_rule' }; } } $op = 'list'; -} -elsif ( $op eq "cud-delete_sort_rule" ) { +} elsif ( $op eq "cud-delete_sort_rule" ) { my $sort_rule = Koha::ClassSortRules->find($class_sort_rule); - my $deleted = eval { $sort_rule->delete }; + my $deleted = eval { $sort_rule->delete }; if ( $@ or not $deleted ) { push @messages, - { type => 'error', code => 'error_on_delete_sort_rule' }; - } - else { + { type => 'error', code => 'error_on_delete_sort_rule' }; + } else { push @messages, - { type => 'message', code => 'success_on_delete_sort_rule' }; + { type => 'message', code => 'success_on_delete_sort_rule' }; } $op = 'list'; -} -elsif ( $op eq "add_split_rule" ) { +} elsif ( $op eq "add_split_rule" ) { my $split_rule = - $class_split_rule - ? Koha::ClassSplitRules->find($class_split_rule) - : undef; + $class_split_rule + ? Koha::ClassSplitRules->find($class_split_rule) + : undef; $template->param( split_rule => $split_rule, split_routines => get_class_split_routines(), ); -} -elsif ( $op eq "cud-add_split_rule_validate" ) { +} elsif ( $op eq "cud-add_split_rule_validate" ) { my $split_rule = Koha::ClassSplitRules->find($class_split_rule); - @split_regex = grep {!/^$/} @split_regex; # Remove empty + @split_regex = grep { !/^$/ } @split_regex; # Remove empty if ($split_rule) { $split_rule->set( { @@ -198,21 +180,19 @@ elsif ( $op eq "cud-add_split_rule_validate" ) { } ); eval { - $split_rule->regexs(\@split_regex) + $split_rule->regexs( \@split_regex ) if $split_routine eq 'RegEx'; $split_rule->store; }; if ($@) { push @messages, - { type => 'error', code => 'error_on_update_split_rule' }; - } - else { + { type => 'error', code => 'error_on_update_split_rule' }; + } else { push @messages, - { type => 'message', code => 'success_on_update_split_rule' }; + { type => 'message', code => 'success_on_update_split_rule' }; } - } - else { + } else { $split_rule = Koha::ClassSplitRule->new( { class_split_rule => $class_split_rule, @@ -225,25 +205,22 @@ elsif ( $op eq "cud-add_split_rule_validate" ) { if ($@) { warn $@; push @messages, - { type => 'error', code => 'error_on_insert_split_rule' }; - } - else { + { type => 'error', code => 'error_on_insert_split_rule' }; + } else { push @messages, - { type => 'message', code => 'success_on_insert_split_rule' }; + { type => 'message', code => 'success_on_insert_split_rule' }; } } $op = 'list'; -} -elsif ( $op eq "cud-delete_split_rule" ) { +} elsif ( $op eq "cud-delete_split_rule" ) { my $split_rule = Koha::ClassSplitRules->find($class_split_rule); - my $deleted = eval { $split_rule->delete }; + my $deleted = eval { $split_rule->delete }; if ( $@ or not $deleted ) { push @messages, - { type => 'error', code => 'error_on_delete_split_rule' }; - } - else { + { type => 'error', code => 'error_on_delete_split_rule' }; + } else { push @messages, - { type => 'message', code => 'success_on_delete_split_rule' }; + { type => 'message', code => 'success_on_delete_split_rule' }; } $op = 'list'; } diff --git a/admin/clone-rules.pl b/admin/clone-rules.pl index 12d90bceeb..5e612c9e16 100755 --- a/admin/clone-rules.pl +++ b/admin/clone-rules.pl @@ -1,6 +1,6 @@ #!/usr/bin/perl # vim: et ts=4 sw=4 -# Copyright BibLibre +# Copyright BibLibre # # This file is part of Koha. # @@ -17,9 +17,8 @@ # You should have received a copy of the GNU General Public License # along with Koha; if not, see . - # This script clones issuing rules from a library to another -# parameters : +# parameters : # - frombranch : the branch we want to clone issuing rules from # - tobranch : the branch we want to clone issuing rules to # @@ -29,35 +28,37 @@ use Modern::Perl; use CGI qw ( -utf8 ); use C4::Context; use C4::Output qw( output_html_with_http_headers ); -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use Koha::CirculationRules; my $input = CGI->new; -my ($template, $loggedinuser, $cookie) - = get_template_and_user({template_name => "admin/clone-rules.tt", - query => $input, - type => "intranet", - flagsrequired => {parameters => 'manage_circ_rules'}, - }); +my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "admin/clone-rules.tt", + query => $input, + type => "intranet", + flagsrequired => { parameters => 'manage_circ_rules' }, + } +); my $op = $input->param("op") || q{}; my $frombranch = $input->param("frombranch"); my $tobranch = $input->param("tobranch"); -$template->param(frombranch => $frombranch) if ($frombranch); -$template->param(tobranch => $tobranch) if ($tobranch); +$template->param( frombranch => $frombranch ) if ($frombranch); +$template->param( tobranch => $tobranch ) if ($tobranch); -if ($op eq 'cud-clone' && $frombranch && $tobranch && $frombranch ne $tobranch) { +if ( $op eq 'cud-clone' && $frombranch && $tobranch && $frombranch ne $tobranch ) { $frombranch = ( $frombranch ne '*' ? $frombranch : undef ); - $tobranch = ( $tobranch ne '*' ? $tobranch : undef ); + $tobranch = ( $tobranch ne '*' ? $tobranch : undef ); - Koha::CirculationRules->search({branchcode => $tobranch})->delete; + Koha::CirculationRules->search( { branchcode => $tobranch } )->delete; - my $rules = Koha::CirculationRules->search({ branchcode => $frombranch }); + my $rules = Koha::CirculationRules->search( { branchcode => $frombranch } ); $rules->clone($tobranch); } else { - $template->param(error => 1); + $template->param( error => 1 ); } output_html_with_http_headers $input, $cookie, $template->output; diff --git a/admin/columns_settings.pl b/admin/columns_settings.pl index 0bca8d11f3..5554362175 100755 --- a/admin/columns_settings.pl +++ b/admin/columns_settings.pl @@ -4,39 +4,38 @@ use Modern::Perl; use CGI; use C4::Auth qw( get_template_and_user ); use C4::Context; -use C4::Output qw( output_html_with_http_headers ); +use C4::Output qw( output_html_with_http_headers ); use C4::Utils::DataTables::TablesSettings qw( get_modules ); my $input = CGI->new; my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "admin/columns_settings.tt", - query => $input, - type => "intranet", - flagsrequired => { parameters => 'manage_column_config' }, + template_name => "admin/columns_settings.tt", + query => $input, + type => "intranet", + flagsrequired => { parameters => 'manage_column_config' }, } ); my $op = $input->param('op') // 'list'; if ( $op eq 'cud-save' ) { - my $module = $input->param('module'); + my $module = $input->param('module'); my @columnids = $input->multi_param("columnid"); my @columns; for my $columnid (@columnids) { next unless $columnid =~ m{^([^\|]*)\|([^\|]*)\|(.*)$}; - my $is_hidden = $input->param( $columnid . '_hidden' ) // 0; - my $cannot_be_toggled = - $input->param( $columnid . '_cannot_be_toggled' ) // 0; + my $is_hidden = $input->param( $columnid . '_hidden' ) // 0; + my $cannot_be_toggled = $input->param( $columnid . '_cannot_be_toggled' ) // 0; push @columns, - { + { module => $module, page => $1, tablename => $2, columnname => $3, is_hidden => $is_hidden, cannot_be_toggled => $cannot_be_toggled, - }; + }; } C4::Utils::DataTables::TablesSettings::update_columns( @@ -58,8 +57,7 @@ if ( $op eq 'cud-save' ) { $default_save_state //= 0; $default_save_state_search //= 0; - if ( defined $default_display_length || defined $default_sort_order || defined $default_save_state ) - { + if ( defined $default_display_length || defined $default_sort_order || defined $default_save_state ) { C4::Utils::DataTables::TablesSettings::update_table_settings( { module => $module, diff --git a/admin/credit_types.pl b/admin/credit_types.pl index d4b26d6dd0..a0eb1bfb6f 100755 --- a/admin/credit_types.pl +++ b/admin/credit_types.pl @@ -18,11 +18,11 @@ # along with Koha; if not, see . use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use Try::Tiny qw( catch try ); use C4::Context; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use Koha::Account::CreditType; @@ -35,10 +35,10 @@ my @messages; my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "admin/credit_types.tt", - query => $input, - type => "intranet", - flagsrequired => { parameters => 'manage_accounts' }, + template_name => "admin/credit_types.tt", + query => $input, + type => "intranet", + flagsrequired => { parameters => 'manage_accounts' }, } ); @@ -49,39 +49,37 @@ if ($code) { if ( $op eq 'add_form' ) { - my $selected_branches = - $credit_type ? $credit_type->get_library_limits : undef; + my $selected_branches = $credit_type ? $credit_type->get_library_limits : undef; my $branches = - Koha::Libraries->search( {}, { order_by => ['branchname'] } )->unblessed; + Koha::Libraries->search( {}, { order_by => ['branchname'] } )->unblessed; my @branches_loop; foreach my $branch (@$branches) { my $selected = - ( $selected_branches - && grep { $_->branchcode eq $branch->{branchcode} } - @{ $selected_branches->as_list } ) ? 1 : 0; + ( $selected_branches && grep { $_->branchcode eq $branch->{branchcode} } @{ $selected_branches->as_list } ) + ? 1 + : 0; push @branches_loop, - { + { branchcode => $branch->{branchcode}, branchname => $branch->{branchname}, selected => $selected, - }; + }; } $template->param( - credit_type => $credit_type, + credit_type => $credit_type, branches_loop => \@branches_loop ); -} -elsif ( $op eq 'cud-add_validate' ) { +} elsif ( $op eq 'cud-add_validate' ) { my $description = $input->param('description'); my $can_be_added_manually = $input->param('can_be_added_manually') || 0; my $credit_number_enabled = $input->param('credit_number_enabled') || 0; - my @branches = grep { $_ ne q{} } $input->multi_param('branches'); + my @branches = grep { $_ ne q{} } $input->multi_param('branches'); if ( not defined $credit_type ) { $credit_type = Koha::Account::CreditType->new( { code => $code } ); } - unless ($credit_type->is_system) { + unless ( $credit_type->is_system ) { $credit_type->description($description); $credit_type->can_be_added_manually($can_be_added_manually); } @@ -89,33 +87,28 @@ elsif ( $op eq 'cud-add_validate' ) { try { $credit_type->store; - unless ($credit_type->is_system) { + unless ( $credit_type->is_system ) { $credit_type->replace_library_limits( \@branches ); } push @messages, { type => 'message', code => 'success_on_saving' }; - } - catch { + } catch { push @messages, { type => 'error', code => 'error_on_saving' }; }; $op = 'list'; -} -elsif ( $op eq 'cud-archive' ) { +} elsif ( $op eq 'cud-archive' ) { try { $credit_type->archived(1)->store(); push @messages, { code => 'success_on_archive', type => 'message' }; - } - catch { + } catch { push @messages, { code => 'error_on_archive', type => 'alert' }; }; $op = 'list'; -} -elsif ( $op eq 'cud-unarchive' ) { +} elsif ( $op eq 'cud-unarchive' ) { try { $credit_type->archived(0)->store(); push @messages, { code => 'success_on_restore', type => 'message' }; - } - catch { + } catch { push @messages, { code => 'error_on_restore', type => 'alert' }; }; $op = 'list'; diff --git a/admin/curbside_pickup.pl b/admin/curbside_pickup.pl index b5abb0e1ec..c7264674ac 100755 --- a/admin/curbside_pickup.pl +++ b/admin/curbside_pickup.pl @@ -18,14 +18,14 @@ use Modern::Perl; use CGI qw ( -utf8 ); use C4::Context; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use Koha::CurbsidePickupPolicies; use Koha::Libraries; -my $input = CGI->new; -my $op = $input->param('op') || 'list'; +my $input = CGI->new; +my $op = $input->param('op') || 'list'; my @messages; my ( $template, $loggedinuser, $cookie ) = get_template_and_user( @@ -43,21 +43,20 @@ if ( $op eq 'cud-save' ) { my $branchcode = $library->branchcode; my $params = { - branchcode => $branchcode, - enabled => scalar $input->param("enable-$branchcode") || 0, + branchcode => $branchcode, + enabled => scalar $input->param("enable-$branchcode") || 0, enable_waiting_holds_only => scalar $input->param("enable-waiting-holds-only-$branchcode") || 0, - pickup_interval => scalar $input->param("interval-$branchcode"), - patrons_per_interval => scalar $input->param("max-per-interval-$branchcode"), - patron_scheduled_pickup => scalar $input->param("patron-scheduled-$branchcode") || 0, + pickup_interval => scalar $input->param("interval-$branchcode"), + patrons_per_interval => scalar $input->param("max-per-interval-$branchcode"), + patron_scheduled_pickup => scalar $input->param("patron-scheduled-$branchcode") || 0, }; - my $policy = - Koha::CurbsidePickupPolicies->find_or_create( { branchcode => $branchcode } ); + my $policy = Koha::CurbsidePickupPolicies->find_or_create( { branchcode => $branchcode } ); $policy->update($params); $policy->opening_slots->delete; - my @pickup_slots = $input->multi_param("pickup-slot-" . $branchcode); - for my $pickup_slot ( @pickup_slots ) { + my @pickup_slots = $input->multi_param( "pickup-slot-" . $branchcode ); + for my $pickup_slot (@pickup_slots) { $policy->add_opening_slot($pickup_slot); } } @@ -66,10 +65,7 @@ if ( $op eq 'cud-save' ) { if ( $op eq 'list' ) { $template->param( - policies => { - map { $_->branchcode => $_ } - Koha::CurbsidePickupPolicies->search->as_list - }, + policies => { map { $_->branchcode => $_ } Koha::CurbsidePickupPolicies->search->as_list }, libraries => $libraries, ); } diff --git a/admin/currency.pl b/admin/currency.pl index 2ca7d620e4..2a8904d8d4 100755 --- a/admin/currency.pl +++ b/admin/currency.pl @@ -20,7 +20,7 @@ # along with Koha; if not, see . use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Auth qw( get_template_and_user ); use C4::Context; use C4::Output qw( output_html_with_http_headers ); @@ -36,10 +36,11 @@ my $op = $input->param('op') || 'list'; my @messages; our ( $template, $loggedinuser, $cookie ) = get_template_and_user( - { template_name => 'admin/currency.tt', - query => $input, - type => 'intranet', - flagsrequired => { acquisition => 'currencies_manage' }, + { + template_name => 'admin/currency.tt', + query => $input, + type => 'intranet', + flagsrequired => { acquisition => 'currencies_manage' }, } ); @@ -51,14 +52,14 @@ if ( $op eq 'add_form' ) { $template->param( currency => $currency, ); } elsif ( $op eq 'cud-add_validate' ) { - my $currency_code = $input->param('currency_code'); - my $symbol = $input->param('symbol'); - my $isocode = $input->param('isocode'); - my $rate = $input->param('rate'); - my $active = $input->param('active'); + my $currency_code = $input->param('currency_code'); + my $symbol = $input->param('symbol'); + my $isocode = $input->param('isocode'); + my $rate = $input->param('rate'); + my $active = $input->param('active'); my $p_sep_by_space = $input->param('p_sep_by_space'); - my $p_cs_precedes = $input->param('p_cs_precedes') // 0; - my $is_a_modif = $input->param('is_a_modif'); + my $p_cs_precedes = $input->param('p_cs_precedes') // 0; + my $is_a_modif = $input->param('is_a_modif'); if ($is_a_modif) { my $currency = Koha::Acquisition::Currencies->find($currency_code); @@ -69,6 +70,7 @@ if ( $op eq 'add_form' ) { $currency->p_sep_by_space($p_sep_by_space); $currency->p_cs_precedes($p_cs_precedes); eval { $currency->store; }; + if ($@) { push @messages, { type => 'error', code => 'error_on_update' }; } else { @@ -98,16 +100,17 @@ if ( $op eq 'add_form' ) { } elsif ( $op eq 'delete_confirm' ) { my $currency = Koha::Acquisition::Currencies->find($currency_code); - my $nb_of_orders = Koha::Acquisition::Orders->search( { currency => $currency->currency } )->count; - my $nb_of_vendors = Koha::Acquisition::Booksellers->search( { -or => { listprice => $currency->currency, invoiceprice => $currency->currency } })->count; + my $nb_of_orders = Koha::Acquisition::Orders->search( { currency => $currency->currency } )->count; + my $nb_of_vendors = Koha::Acquisition::Booksellers->search( + { -or => { listprice => $currency->currency, invoiceprice => $currency->currency } } )->count; $template->param( - currency => $currency, - nb_of_orders => $nb_of_orders, + currency => $currency, + nb_of_orders => $nb_of_orders, nb_of_vendors => $nb_of_vendors, ); } elsif ( $op eq 'cud-delete_confirmed' ) { my $currency = Koha::Acquisition::Currencies->find($currency_code); - my $deleted = eval { $currency->delete; }; + my $deleted = eval { $currency->delete; }; if ( $@ or not $deleted ) { push @messages, { type => 'error', code => 'error_on_delete' }; diff --git a/admin/debit_types.pl b/admin/debit_types.pl index 597afcbf57..9425f5cab8 100755 --- a/admin/debit_types.pl +++ b/admin/debit_types.pl @@ -18,11 +18,11 @@ # along with Koha; if not, see . use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use Try::Tiny qw( catch try ); use C4::Context; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use Koha::Account::DebitType; @@ -35,10 +35,10 @@ my @messages; my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "admin/debit_types.tt", - query => $input, - type => "intranet", - flagsrequired => { parameters => 'manage_accounts' }, + template_name => "admin/debit_types.tt", + query => $input, + type => "intranet", + flagsrequired => { parameters => 'manage_accounts' }, } ); @@ -49,36 +49,34 @@ if ($code) { if ( $op eq 'add_form' ) { - my $selected_branches = - $debit_type ? $debit_type->get_library_limits : undef; + my $selected_branches = $debit_type ? $debit_type->get_library_limits : undef; my $branches = - Koha::Libraries->search( {}, { order_by => ['branchname'] } )->unblessed; + Koha::Libraries->search( {}, { order_by => ['branchname'] } )->unblessed; my @branches_loop; foreach my $branch (@$branches) { my $selected = - ( $selected_branches - && grep { $_->branchcode eq $branch->{branchcode} } - @{ $selected_branches->as_list } ) ? 1 : 0; + ( $selected_branches && grep { $_->branchcode eq $branch->{branchcode} } @{ $selected_branches->as_list } ) + ? 1 + : 0; push @branches_loop, - { + { branchcode => $branch->{branchcode}, branchname => $branch->{branchname}, selected => $selected, - }; + }; } $template->param( debit_type => $debit_type, branches_loop => \@branches_loop ); -} -elsif ( $op eq 'cud-add_validate' ) { - my $description = $input->param('description'); - my $can_be_invoiced = $input->param('can_be_invoiced') || 0; - my $can_be_sold = $input->param('can_be_sold') || 0; - my $default_amount = $input->param('default_amount') || undef; +} elsif ( $op eq 'cud-add_validate' ) { + my $description = $input->param('description'); + my $can_be_invoiced = $input->param('can_be_invoiced') || 0; + my $can_be_sold = $input->param('can_be_sold') || 0; + my $default_amount = $input->param('default_amount') || undef; my $restricts_checkouts = $input->param('restricts_checkouts') || 0; - my @branches = grep { $_ ne q{} } $input->multi_param('branches'); + my @branches = grep { $_ ne q{} } $input->multi_param('branches'); if ( not defined $debit_type ) { $debit_type = Koha::Account::DebitType->new( { code => $code } ); @@ -93,29 +91,24 @@ elsif ( $op eq 'cud-add_validate' ) { $debit_type->store; $debit_type->replace_library_limits( \@branches ); push @messages, { type => 'message', code => 'success_on_saving' }; - } - catch { + } catch { push @messages, { type => 'error', code => 'error_on_saving' }; }; $op = 'list'; -} -elsif ( $op eq 'cud-archive' ) { +} elsif ( $op eq 'cud-archive' ) { try { $debit_type->archived(1)->store(); push @messages, { code => 'success_on_archive', type => 'message' }; - } - catch { + } catch { push @messages, { code => 'error_on_archive', type => 'alert' }; }; $op = 'list'; -} -elsif ( $op eq 'cud-unarchive' ) { +} elsif ( $op eq 'cud-unarchive' ) { try { $debit_type->archived(0)->store(); push @messages, { code => 'success_on_restore', type => 'message' }; - } - catch { + } catch { push @messages, { code => 'error_on_restore', type => 'alert' }; }; $op = 'list'; diff --git a/admin/desks.pl b/admin/desks.pl index c688cf1753..6ecb23c7cd 100755 --- a/admin/desks.pl +++ b/admin/desks.pl @@ -17,23 +17,23 @@ # You should have received a copy of the GNU General Public License # along with Koha; if not, see . - use Modern::Perl; use CGI qw ( -utf8 ); use C4::Context; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use Koha::Desks; my $input = CGI->new; my $searchfield = $input->param('desk_name') // q||; -my $desk_id = $input->param('desk_id') || ''; -my $op = $input->param('op') || 'list'; +my $desk_id = $input->param('desk_id') || ''; +my $op = $input->param('op') || 'list'; my @messages; my ( $template, $loggedinuser, $cookie ) = get_template_and_user( - { template_name => "admin/desks.tt", + { + template_name => "admin/desks.tt", query => $input, type => "intranet", authnotrequired => 0, @@ -51,11 +51,11 @@ if ( $op eq 'add_form' ) { $template->param( desk => $desk, ); } elsif ( $op eq 'cud-add_validate' ) { - my $desk_id = $input->param('desk_id'); - my $desk_name = $input->param('desk_name'); - my $branchcode = $input->param('branchcode'); + my $desk_id = $input->param('desk_id'); + my $desk_name = $input->param('desk_name'); + my $branchcode = $input->param('branchcode'); - if (Koha::Desks->find($desk_id)) { + if ( Koha::Desks->find($desk_id) ) { my $desk = Koha::Desks->find($desk_id); $desk->desk_name($desk_name); $desk->branchcode($branchcode); @@ -68,9 +68,9 @@ if ( $op eq 'add_form' ) { } else { my $desk = Koha::Desk->new( { - desk_id => $desk_id, - desk_name => $desk_name, - branchcode => $branchcode, + desk_id => $desk_id, + desk_name => $desk_name, + branchcode => $branchcode, } ); eval { $desk->store; }; @@ -86,7 +86,7 @@ if ( $op eq 'add_form' ) { my $desk = Koha::Desks->find($desk_id); $template->param( desk => $desk, ); } elsif ( $op eq 'cud-delete_confirmed' ) { - my $desk = Koha::Desks->find($desk_id); + my $desk = Koha::Desks->find($desk_id); my $deleted = eval { $desk->delete; }; if ( $@ or not $deleted ) { @@ -97,13 +97,13 @@ if ( $op eq 'add_form' ) { $op = 'list'; } -if ( $op eq 'list' || ! $op) { +if ( $op eq 'list' || !$op ) { my $desks = Koha::Desks->search( { desk_name => { -like => "%$searchfield%" } } ); $template->param( desks => $desks, ); } $template->param( - desk_id => $desk_id, + desk_id => $desk_id, searchfield => $searchfield, messages => \@messages, op => $op, diff --git a/admin/didyoumean.pl b/admin/didyoumean.pl index b584c5b299..a90321d006 100755 --- a/admin/didyoumean.pl +++ b/admin/didyoumean.pl @@ -3,27 +3,29 @@ use Modern::Perl; use CGI qw ( -utf8 ); use C4::Context; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use Koha::SuggestionEngine; use Module::Load::Conditional qw( can_load ); -use JSON qw( from_json ); +use JSON qw( from_json ); my $input = CGI->new; -my ($template, $loggedinuser, $cookie) - = get_template_and_user({template_name => "admin/didyoumean.tt", - query => $input, - type => "intranet", - flagsrequired => {parameters => 'manage_didyoumean'}, - }); +my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "admin/didyoumean.tt", + query => $input, + type => "intranet", + flagsrequired => { parameters => 'manage_didyoumean' }, + } +); -my $opacplugins = from_json(C4::Context->preference('OPACdidyoumean') || '[]'); +my $opacplugins = from_json( C4::Context->preference('OPACdidyoumean') || '[]' ); my @pluginlist = Koha::SuggestionEngine::AvailablePlugins(); foreach my $plugin (@pluginlist) { next if $plugin eq 'Koha::SuggestionEngine::Plugin::Null'; - next unless (can_load( modules => { "$plugin" => undef } )); + next unless ( can_load( modules => { "$plugin" => undef } ) ); push @$opacplugins, { name => $plugin->NAME } unless grep { $_->{name} eq $plugin->NAME } @$opacplugins; } $template->{VARS}->{OPACpluginlist} = $opacplugins; diff --git a/admin/edi_accounts.pl b/admin/edi_accounts.pl index 4d7ae364f5..c5dda416d8 100755 --- a/admin/edi_accounts.pl +++ b/admin/edi_accounts.pl @@ -21,21 +21,21 @@ use Modern::Perl; use CGI; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use Koha::Database; use Koha::Encryption; use Koha::Plugins; -our $input = CGI->new(); +our $input = CGI->new(); our $schema = Koha::Database->new()->schema(); our ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => 'admin/edi_accounts.tt', - query => $input, - type => 'intranet', - flagsrequired => { acquisition => 'edi_manage' }, + template_name => 'admin/edi_accounts.tt', + query => $input, + type => 'intranet', + flagsrequired => { acquisition => 'edi_manage' }, } ); @@ -50,28 +50,28 @@ if ( $op eq 'acct_form' ) { my @vendors = $schema->resultset('Aqbookseller')->search( undef, { - columns => [ 'name', 'id' ], + columns => [ 'name', 'id' ], order_by => { -asc => 'name' } } ); $template->param( vendors => \@vendors ); if ( C4::Context->config("enable_plugins") ) { - my @plugins = Koha::Plugins->new()->GetPlugins({ - method => 'edifact', - }); + my @plugins = Koha::Plugins->new()->GetPlugins( + { + method => 'edifact', + } + ); $template->param( plugins => \@plugins ); } -} -elsif ( $op eq 'delete_confirm' ) { +} elsif ( $op eq 'delete_confirm' ) { show_account($crypt); $template->param( delete_confirm => 1 ); -} -else { +} else { if ( $op eq 'cud-save' ) { # validate & display - my $id = $input->param('id'); + my $id = $input->param('id'); my $password = scalar $input->param('password'); $password = $crypt->encrypt_hex($password); my $fields = { @@ -87,11 +87,11 @@ else { san => scalar $input->param('san'), standard => scalar $input->param('standard'), transport => scalar $input->param('transport'), - quotes_enabled => $input->param('quotes_enabled') ? 1 : 0, - invoices_enabled => $input->param('invoices_enabled') ? 1 : 0, - orders_enabled => $input->param('orders_enabled') ? 1 : 0, + quotes_enabled => $input->param('quotes_enabled') ? 1 : 0, + invoices_enabled => $input->param('invoices_enabled') ? 1 : 0, + orders_enabled => $input->param('orders_enabled') ? 1 : 0, responses_enabled => $input->param('responses_enabled') ? 1 : 0, - auto_orders => $input->param('auto_orders') ? 1 : 0, + auto_orders => $input->param('auto_orders') ? 1 : 0, id_code_qualifier => scalar $input->param('id_code_qualifier'), plugin => scalar $input->param('plugin'), }; @@ -102,15 +102,12 @@ else { id => $id, } )->update_all($fields); - } - else { # new record + } else { # new record $schema->resultset('VendorEdiAccount')->create($fields); } - } - elsif ( $op eq 'cud-delete_confirmed' ) { + } elsif ( $op eq 'cud-delete_confirmed' ) { - $schema->resultset('VendorEdiAccount') - ->search( { id => scalar $input->param('id'), } )->delete_all; + $schema->resultset('VendorEdiAccount')->search( { id => scalar $input->param('id'), } )->delete_all; } # we do a default dispaly after deletes and saves @@ -162,11 +159,11 @@ sub get_account { } sub show_account { - my $crypt = shift; + my $crypt = shift; my $acct_id = $input->param('id'); if ($acct_id) { my $acct = $schema->resultset('VendorEdiAccount')->find($acct_id); - $acct->password( $crypt->decrypt_hex($acct->password) ); + $acct->password( $crypt->decrypt_hex( $acct->password ) ); if ($acct) { $template->param( account => $acct ); } diff --git a/admin/edi_ean_accounts.pl b/admin/edi_ean_accounts.pl index 12d9589006..ece6d7fa02 100755 --- a/admin/edi_ean_accounts.pl +++ b/admin/edi_ean_accounts.pl @@ -19,7 +19,7 @@ use Modern::Perl; use CGI; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use Koha::Database; @@ -27,10 +27,10 @@ my $input = CGI->new(); my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => 'admin/edi_ean_accounts.tt', - query => $input, - type => 'intranet', - flagsrequired => { acquisition => 'edi_manage' }, + template_name => 'admin/edi_ean_accounts.tt', + query => $input, + type => 'intranet', + flagsrequired => { acquisition => 'edi_manage' }, } ); @@ -53,15 +53,13 @@ if ( $op eq 'ean_form' ) { branches => \@branches, ean => $e, ); -} -elsif ( $op eq 'delete_confirm' ) { +} elsif ( $op eq 'delete_confirm' ) { my $e = $schema->resultset('EdifactEan')->find($id); $template->param( delete_confirm => 1, ean => $e, ); -} -else { +} else { if ( $op eq 'cud-save' ) { my $change = $id; if ($change) { @@ -73,8 +71,7 @@ else { id_code_qualifier => scalar $input->param('id_code_qualifier'), } ); - } - else { + } else { my $new_ean = $schema->resultset('EdifactEan')->new( { branchcode => scalar $input->param('branchcode') || undef, @@ -85,8 +82,7 @@ else { ); $new_ean->insert(); } - } - elsif ( $op eq 'cud-delete_confirmed' ) { + } elsif ( $op eq 'cud-delete_confirmed' ) { my $e = $schema->resultset('EdifactEan')->find($id); $e->delete if $e; } diff --git a/admin/identity_providers.pl b/admin/identity_providers.pl index 74416f6aa7..ef71aaee86 100755 --- a/admin/identity_providers.pl +++ b/admin/identity_providers.pl @@ -19,19 +19,19 @@ use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use Scalar::Util qw( blessed ); -use Try::Tiny qw( catch try ); +use Try::Tiny qw( catch try ); -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use Koha::Database; use Koha::Auth::Identity::Providers; -my $input = CGI->new; -my $op = $input->param('op') || 'list'; -my $domain_ops = $input->param('domain_ops'); +my $input = CGI->new; +my $op = $input->param('op') || 'list'; +my $domain_ops = $input->param('domain_ops'); my $identity_provider_id = $input->param('identity_provider_id'); my $identity_provider; @@ -41,10 +41,11 @@ $identity_provider = Koha::Auth::Identity::Providers->find($identity_provider_id my $template_name = $domain_ops ? 'admin/identity_provider_domains.tt' : 'admin/identity_providers.tt'; my ( $template, $borrowernumber, $cookie ) = get_template_and_user( - { template_name => $template_name, - query => $input, - type => "intranet", - flagsrequired => { parameters => 'manage_identity_providers' }, + { + template_name => $template_name, + query => $input, + type => "intranet", + flagsrequired => { parameters => 'manage_identity_providers' }, } ); @@ -60,9 +61,10 @@ if ( !$domain_ops && $op eq 'cud-add' ) { my $mapping = $input->param('mapping'); my $matchpoint = $input->param('matchpoint'); my $protocol = $input->param('protocol'); + # Domain configuration params - my $allow_opac = $input->param('allow_opac') // 0; - my $allow_staff = $input->param('allow_staff') // 0; + my $allow_opac = $input->param('allow_opac') // 0; + my $allow_staff = $input->param('allow_staff') // 0; my $auto_register = $input->param('auto_register') // 0; my $default_category_id = $input->param('default_category_id'); my $default_library_id = $input->param('default_library_id'); @@ -73,7 +75,8 @@ if ( !$domain_ops && $op eq 'cud-add' ) { Koha::Database->new->schema->txn_do( sub { my $provider = Koha::Auth::Identity::Provider->new( - { code => $code, + { + code => $code, config => $config, description => $description, icon_url => $icon_url, @@ -84,7 +87,8 @@ if ( !$domain_ops && $op eq 'cud-add' ) { )->store; Koha::Auth::Identity::Provider::Domain->new( - { identity_provider_id => $provider->identity_provider_id, + { + identity_provider_id => $provider->identity_provider_id, allow_opac => $allow_opac, allow_staff => $allow_staff, auto_register => $auto_register, @@ -98,103 +102,91 @@ if ( !$domain_ops && $op eq 'cud-add' ) { push @messages, { type => 'message', code => 'success_on_insert' }; } ); - } - catch { + } catch { if ( blessed $_ and $_->isa('Koha::Exceptions::Object::DuplicateID') ) { push @messages, - { + { type => 'alert', code => 'error_on_insert', reason => 'duplicate_id' - }; + }; } }; # list servers after adding $op = 'list'; -} -elsif ( $domain_ops && $op eq 'cud-add' ) { +} elsif ( $domain_ops && $op eq 'cud-add' ) { - my $allow_opac = $input->param('allow_opac'); - my $allow_staff = $input->param('allow_staff'); - my $identity_provider_id = $input->param('identity_provider_id'); - my $auto_register = $input->param('auto_register'); - my $default_category_id = $input->param('default_category_id') || undef; - my $default_library_id = $input->param('default_library_id') || undef; - my $domain = $input->param('domain'); - my $update_on_auth = $input->param('update_on_auth'); + my $allow_opac = $input->param('allow_opac'); + my $allow_staff = $input->param('allow_staff'); + my $identity_provider_id = $input->param('identity_provider_id'); + my $auto_register = $input->param('auto_register'); + my $default_category_id = $input->param('default_category_id') || undef; + my $default_library_id = $input->param('default_library_id') || undef; + my $domain = $input->param('domain'); + my $update_on_auth = $input->param('update_on_auth'); try { Koha::Auth::Identity::Provider::Domain->new( { - allow_opac => $allow_opac, - allow_staff => $allow_staff, - identity_provider_id => $identity_provider_id, - auto_register => $auto_register, - default_category_id => $default_category_id, - default_library_id => $default_library_id, - domain => $domain, - update_on_auth => $update_on_auth, + allow_opac => $allow_opac, + allow_staff => $allow_staff, + identity_provider_id => $identity_provider_id, + auto_register => $auto_register, + default_category_id => $default_category_id, + default_library_id => $default_library_id, + domain => $domain, + update_on_auth => $update_on_auth, } )->store; push @messages, { type => 'message', code => 'success_on_insert' }; - } - catch { + } catch { if ( blessed $_ and $_->isa('Koha::Exceptions::Object::DuplicateID') ) { push @messages, - { + { type => 'alert', code => 'error_on_insert', reason => 'duplicate_id' - }; + }; } }; # list servers after adding $op = 'list'; -} -elsif ( !$domain_ops && $op eq 'edit_form' ) { +} elsif ( !$domain_ops && $op eq 'edit_form' ) { - if ( $identity_provider ) { - $template->param( - identity_provider => $identity_provider - ); - } - else { + if ($identity_provider) { + $template->param( identity_provider => $identity_provider ); + } else { push @messages, { - type => 'alert', - code => 'error_on_edit', - reason => 'invalid_id' + type => 'alert', + code => 'error_on_edit', + reason => 'invalid_id' }; } -} -elsif ( $domain_ops && $op eq 'edit_form' ) { +} elsif ( $domain_ops && $op eq 'edit_form' ) { my $identity_provider_domain_id = $input->param('identity_provider_domain_id'); my $identity_provider_domain; $identity_provider_domain = Koha::Auth::Identity::Provider::Domains->find($identity_provider_domain_id) unless !$identity_provider_domain_id; - if ( $identity_provider_domain ) { - $template->param( - identity_provider_domain => $identity_provider_domain - ); - } - else { + if ($identity_provider_domain) { + $template->param( identity_provider_domain => $identity_provider_domain ); + } else { push @messages, { - type => 'alert', - code => 'error_on_edit', - reason => 'invalid_id' + type => 'alert', + code => 'error_on_edit', + reason => 'invalid_id' }; } -} -elsif ( !$domain_ops && $op eq 'cud-edit_save' ) { +} elsif ( !$domain_ops && $op eq 'cud-edit_save' ) { - if ( $identity_provider ) { + if ($identity_provider) { my $code = $input->param('code'); my $config = $input->param('config'); @@ -207,7 +199,8 @@ elsif ( !$domain_ops && $op eq 'cud-edit_save' ) { try { $identity_provider->set( - { code => $code, + { + code => $code, config => $config, description => $description, icon_url => $icon_url, @@ -218,32 +211,29 @@ elsif ( !$domain_ops && $op eq 'cud-edit_save' ) { )->store; push @messages, - { + { type => 'message', code => 'success_on_update' - }; - } - catch { + }; + } catch { push @messages, - { - type => 'alert', - code => 'error_on_update' - }; + { + type => 'alert', + code => 'error_on_update' + }; }; # list servers after adding $op = 'list'; - } - else { + } else { push @messages, { - type => 'alert', - code => 'error_on_update', - reason => 'invalid_id' + type => 'alert', + code => 'error_on_update', + reason => 'invalid_id' }; } -} -elsif ( $domain_ops && $op eq 'cud-edit_save' ) { +} elsif ( $domain_ops && $op eq 'cud-edit_save' ) { my $identity_provider_domain_id = $input->param('identity_provider_domain_id'); my $identity_provider_domain; @@ -251,60 +241,58 @@ elsif ( $domain_ops && $op eq 'cud-edit_save' ) { $identity_provider_domain = Koha::Auth::Identity::Provider::Domains->find($identity_provider_domain_id) unless !$identity_provider_domain_id; - if ( $identity_provider_domain ) { + if ($identity_provider_domain) { - my $identity_provider_id = $input->param('identity_provider_id'); - my $domain = $input->param('domain'); - my $auto_register = $input->param('auto_register'); - my $update_on_auth = $input->param('update_on_auth'); - my $default_library_id = $input->param('default_library_id') || undef; - my $default_category_id = $input->param('default_category_id') || undef; - my $allow_opac = $input->param('allow_opac'); - my $allow_staff = $input->param('allow_staff'); + my $identity_provider_id = $input->param('identity_provider_id'); + my $domain = $input->param('domain'); + my $auto_register = $input->param('auto_register'); + my $update_on_auth = $input->param('update_on_auth'); + my $default_library_id = $input->param('default_library_id') || undef; + my $default_category_id = $input->param('default_category_id') || undef; + my $allow_opac = $input->param('allow_opac'); + my $allow_staff = $input->param('allow_staff'); try { $identity_provider_domain->set( { - identity_provider_id => $identity_provider_id, - domain => $domain, - auto_register => $auto_register, - update_on_auth => $update_on_auth, - default_library_id => $default_library_id, - default_category_id => $default_category_id, - allow_opac => $allow_opac, - allow_staff => $allow_staff, + identity_provider_id => $identity_provider_id, + domain => $domain, + auto_register => $auto_register, + update_on_auth => $update_on_auth, + default_library_id => $default_library_id, + default_category_id => $default_category_id, + allow_opac => $allow_opac, + allow_staff => $allow_staff, } )->store; push @messages, - { + { type => 'message', code => 'success_on_update' - }; - } - catch { + }; + } catch { push @messages, - { - type => 'alert', - code => 'error_on_update' - }; + { + type => 'alert', + code => 'error_on_update' + }; }; # list servers after adding $op = 'list'; - } - else { + } else { push @messages, { - type => 'alert', - code => 'error_on_update', - reason => 'invalid_id' + type => 'alert', + code => 'error_on_update', + reason => 'invalid_id' }; } } -if ( $domain_ops ) { +if ($domain_ops) { $template->param( identity_provider_code => $identity_provider->code, identity_provider_id => $identity_provider_id, diff --git a/admin/import_export_authtype.pl b/admin/import_export_authtype.pl index bc1d2ec432..0b88442fe6 100755 --- a/admin/import_export_authtype.pl +++ b/admin/import_export_authtype.pl @@ -21,13 +21,13 @@ use Modern::Perl; use CGI qw ( -utf8 ); use CGI::Cookie; use C4::Context; -use C4::Auth qw/check_cookie_auth/; +use C4::Auth qw/check_cookie_auth/; use C4::ImportExportFramework qw( ExportFramework ImportFramework createODS ); my %cookies = CGI::Cookie->fetch(); -my ($auth_status, $sessionID); -if (exists $cookies{'CGISESSID'}) { - ($auth_status, $sessionID) = check_cookie_auth( +my ( $auth_status, $sessionID ); +if ( exists $cookies{'CGISESSID'} ) { + ( $auth_status, $sessionID ) = check_cookie_auth( $cookies{'CGISESSID'}->value, { parameters => 'parameters_remaining_permissions' }, ); @@ -35,8 +35,8 @@ if (exists $cookies{'CGISESSID'}) { my $input = CGI->new; -unless ($auth_status eq 'ok') { - print $input->header(-type => 'text/plain', -status => '403 Forbidden'); +unless ( $auth_status eq 'ok' ) { + print $input->header( -type => 'text/plain', -status => '403 Forbidden' ); exit 0; } @@ -46,57 +46,66 @@ my $op = $input->param('op') || 'export'; ## Exporting if ( $op eq 'export' ) { # GET operation for downloading my $strXml = ''; - my $format = $input->param('type_export_' . $authtypecode); - if ($authtypecode eq 'default') { + my $format = $input->param( 'type_export_' . $authtypecode ); + if ( $authtypecode eq 'default' ) { $format = $input->param('type_export_'); - ExportFramework('', \$strXml, $format, 'authority'); + ExportFramework( '', \$strXml, $format, 'authority' ); } else { - ExportFramework($authtypecode, \$strXml, $format, 'authority'); + ExportFramework( $authtypecode, \$strXml, $format, 'authority' ); } - if ($format eq 'csv') { + if ( $format eq 'csv' ) { + # CSV file # Correctly set the encoding to output plain text in UTF-8 - binmode(STDOUT,':encoding(UTF-8)'); - print $input->header(-type => 'application/vnd.ms-excel', -attachment => 'export_' . $authtypecode . '.csv'); + binmode( STDOUT, ':encoding(UTF-8)' ); + print $input->header( -type => 'application/vnd.ms-excel', -attachment => 'export_' . $authtypecode . '.csv' ); print $strXml; } else { + # ODS file my $strODS = ''; - createODS($strXml, 'en', \$strODS); - print $input->header(-type => 'application/vnd.oasis.opendocument.spreadsheet', -attachment => 'export_' . $authtypecode . '.ods'); + createODS( $strXml, 'en', \$strODS ); + print $input->header( + -type => 'application/vnd.oasis.opendocument.spreadsheet', + -attachment => 'export_' . $authtypecode . '.ods' + ); print $strODS; } } elsif ( $op eq 'cud-import' ) { # POST for importing - my $ok = -1; + my $ok = -1; my $fieldname = 'file_import_' . $authtypecode; - if ($authtypecode eq 'default'){ + if ( $authtypecode eq 'default' ) { $fieldname = 'file_import_'; } my $filename = $input->param($fieldname); + # upload the input file - if ($filename && $filename =~ /\.(csv|ods)$/i) { + if ( $filename && $filename =~ /\.(csv|ods)$/i ) { my $extension = $1; - my $uploadFd = $input->upload($fieldname); - if ($uploadFd && !$input->cgi_error) { - my $tmpfilename = $input->tmpFileName(scalar $input->param($fieldname)); - $filename = $tmpfilename . '.' . $extension; # rename the tmp file with the extension - if ($authtypecode eq 'default') { - $ok = ImportFramework($filename, '', 1, 'authority') if (rename($tmpfilename, $filename)); + my $uploadFd = $input->upload($fieldname); + if ( $uploadFd && !$input->cgi_error ) { + my $tmpfilename = $input->tmpFileName( scalar $input->param($fieldname) ); + $filename = $tmpfilename . '.' . $extension; # rename the tmp file with the extension + if ( $authtypecode eq 'default' ) { + $ok = ImportFramework( $filename, '', 1, 'authority' ) if ( rename( $tmpfilename, $filename ) ); } else { - $ok = ImportFramework($filename, $authtypecode, 1, 'authority') if (rename($tmpfilename, $filename)); + $ok = ImportFramework( $filename, $authtypecode, 1, 'authority' ) + if ( rename( $tmpfilename, $filename ) ); } } } - if ($ok >= 0) { # If everything went ok go to the authority type marc structure - if ($authtypecode eq 'default'){ - print $input->redirect( -location => '/cgi-bin/koha/admin/auth_tag_structure.pl?authtypecode='); + if ( $ok >= 0 ) { # If everything went ok go to the authority type marc structure + if ( $authtypecode eq 'default' ) { + print $input->redirect( -location => '/cgi-bin/koha/admin/auth_tag_structure.pl?authtypecode=' ); } else { - print $input->redirect( -location => '/cgi-bin/koha/admin/auth_tag_structure.pl?authtypecode=' . $authtypecode); + print $input->redirect( + -location => '/cgi-bin/koha/admin/auth_tag_structure.pl?authtypecode=' . $authtypecode ); } } else { + # If something failed go to the list of authority types and show message - print $input->redirect( -location => '/cgi-bin/koha/admin/authtypes.pl?error_import_export=' . $authtypecode); + print $input->redirect( -location => '/cgi-bin/koha/admin/authtypes.pl?error_import_export=' . $authtypecode ); } } diff --git a/admin/import_export_framework.pl b/admin/import_export_framework.pl index 159ff08f59..363a5217b9 100755 --- a/admin/import_export_framework.pl +++ b/admin/import_export_framework.pl @@ -21,13 +21,13 @@ use Modern::Perl; use CGI qw ( -utf8 ); use CGI::Cookie; use C4::Context; -use C4::Auth qw( check_cookie_auth ); +use C4::Auth qw( check_cookie_auth ); use C4::ImportExportFramework qw( createODS ExportFramework ImportFramework ); my %cookies = CGI::Cookie->fetch(); my ($auth_status); -if (exists $cookies{'CGISESSID'}) { - ($auth_status, undef) = check_cookie_auth( +if ( exists $cookies{'CGISESSID'} ) { + ( $auth_status, undef ) = check_cookie_auth( $cookies{'CGISESSID'}->value, { parameters => 'manage_marc_frameworks' }, ); @@ -35,57 +35,66 @@ if (exists $cookies{'CGISESSID'}) { my $input = CGI->new; -unless ($auth_status eq 'ok') { - print $input->header(-type => 'text/plain', -status => '403 Forbidden'); +unless ( $auth_status eq 'ok' ) { + print $input->header( -type => 'text/plain', -status => '403 Forbidden' ); exit 0; } my $frameworkcode = $input->param('frameworkcode') || 'default'; -my $op = $input->param('op') || 'export'; +my $op = $input->param('op') || 'export'; ## Exporting -if ($op eq 'export') { +if ( $op eq 'export' ) { my $strXml = ''; - my $format = $input->param('type_export_' . $frameworkcode); - if ($frameworkcode eq 'default') { - ExportFramework('', \$strXml, $format, 'biblio'); + my $format = $input->param( 'type_export_' . $frameworkcode ); + if ( $frameworkcode eq 'default' ) { + ExportFramework( '', \$strXml, $format, 'biblio' ); } else { - ExportFramework($frameworkcode, \$strXml, $format, 'biblio'); + ExportFramework( $frameworkcode, \$strXml, $format, 'biblio' ); } - if ($format eq 'csv') { + if ( $format eq 'csv' ) { + # CSV file # Correctly set the encoding to output plain text in UTF-8 - binmode(STDOUT,':encoding(UTF-8)'); - print $input->header(-type => 'application/vnd.ms-excel', -attachment => 'export_' . $frameworkcode . '.csv'); + binmode( STDOUT, ':encoding(UTF-8)' ); + print $input->header( -type => 'application/vnd.ms-excel', -attachment => 'export_' . $frameworkcode . '.csv' ); print $strXml; } else { + # ODS file my $strODS = ''; - createODS($strXml, 'en', \$strODS); - print $input->header(-type => 'application/vnd.oasis.opendocument.spreadsheet', -attachment => 'export_' . $frameworkcode . '.ods'); + createODS( $strXml, 'en', \$strODS ); + print $input->header( + -type => 'application/vnd.oasis.opendocument.spreadsheet', + -attachment => 'export_' . $frameworkcode . '.ods' + ); print $strODS; } ## Importing -} elsif ($op eq 'cud-import') { - my $ok = -1; +} elsif ( $op eq 'cud-import' ) { + my $ok = -1; my $fieldname = 'file_import_' . $frameworkcode; - my $filename = $input->param($fieldname); + my $filename = $input->param($fieldname); + # upload the input file - if ($filename && $filename =~ /\.(csv|ods)$/i) { + if ( $filename && $filename =~ /\.(csv|ods)$/i ) { my $extension = $1; - my $uploadFd = $input->upload($fieldname); - if ($uploadFd && !$input->cgi_error) { - my $tmpfilename = $input->tmpFileName(scalar $input->param($fieldname)); - $filename = $tmpfilename . '.' . $extension; # rename the tmp file with the extension - $ok = ImportFramework($filename, $frameworkcode, 1, 'biblio') if (rename($tmpfilename, $filename)); + my $uploadFd = $input->upload($fieldname); + if ( $uploadFd && !$input->cgi_error ) { + my $tmpfilename = $input->tmpFileName( scalar $input->param($fieldname) ); + $filename = $tmpfilename . '.' . $extension; # rename the tmp file with the extension + $ok = ImportFramework( $filename, $frameworkcode, 1, 'biblio' ) if ( rename( $tmpfilename, $filename ) ); } } - if ($ok >= 0) { # If everything went ok go to the framework marc structure - print $input->redirect( -location => '/cgi-bin/koha/admin/marctagstructure.pl?frameworkcode=' . $frameworkcode); + if ( $ok >= 0 ) { # If everything went ok go to the framework marc structure + print $input->redirect( + -location => '/cgi-bin/koha/admin/marctagstructure.pl?frameworkcode=' . $frameworkcode ); } else { + # If something failed go to the list of frameworks and show message - print $input->redirect( -location => '/cgi-bin/koha/admin/biblio_framework.pl?error_import_export=' . $frameworkcode); + print $input->redirect( + -location => '/cgi-bin/koha/admin/biblio_framework.pl?error_import_export=' . $frameworkcode ); } } diff --git a/admin/item_circulation_alerts.pl b/admin/item_circulation_alerts.pl index 997b33c3fd..6f39674aca 100755 --- a/admin/item_circulation_alerts.pl +++ b/admin/item_circulation_alerts.pl @@ -17,8 +17,9 @@ use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use JSON qw( encode_json ); + #use Data::Dump 'pp'; use C4::Auth qw( get_template_and_user ); @@ -36,19 +37,19 @@ our $preferences = 'C4::ItemCirculationAlertPreference'; sub show { my ($input) = @_; my $dbh = C4::Context->dbh; - my ($template, $user, $cookie) = get_template_and_user( + my ( $template, $user, $cookie ) = get_template_and_user( { - template_name => "admin/item_circulation_alerts.tt", - query => $input, - type => "intranet", - flagsrequired => { parameters => 'manage_item_circ_alerts' }, - debug => defined($input->param('debug')), + template_name => "admin/item_circulation_alerts.tt", + query => $input, + type => "intranet", + flagsrequired => { parameters => 'manage_item_circ_alerts' }, + debug => defined( $input->param('debug') ), } ); - my $branch = $input->param('branch') || '*'; - my $grid_checkout = $preferences->grid({ branchcode => $branch, notification => 'CHECKOUT' }); - my $grid_checkin = $preferences->grid({ branchcode => $branch, notification => 'CHECKIN' }); + my $branch = $input->param('branch') || '*'; + my $grid_checkout = $preferences->grid( { branchcode => $branch, notification => 'CHECKOUT' } ); + my $grid_checkin = $preferences->grid( { branchcode => $branch, notification => 'CHECKIN' } ); $template->param( branch => $branch, @@ -63,9 +64,9 @@ sub show { # toggle a preference via ajax sub toggle { my ($input) = @_; - my $id = $input->param('id'); - my $branch = $input->param('branch'); - my ($category, $item_type, $notification) = split('-', $id); + my $id = $input->param('id'); + my $branch = $input->param('branch'); + my ( $category, $item_type, $notification ) = split( '-', $id ); $category =~ s/_/*/; $item_type =~ s/_/*/; @@ -76,19 +77,21 @@ sub toggle { notification => $notification, }; - my $restrictions = $preferences; # all the same thing... - my $notifications = $preferences; # - if ($notifications->is_enabled_for($settings)) { + my $restrictions = $preferences; # all the same thing... + my $notifications = $preferences; # + if ( $notifications->is_enabled_for($settings) ) { + # toggle by adding a restriction $restrictions->create($settings); } else { + # toggle by removing the restriction $restrictions->delete($settings); } my $response = { success => 1 }; my @reasons = $notifications->is_disabled_for($settings); - if (@reasons == 0) { + if ( @reasons == 0 ) { $response->{classes} = ''; } else { my $default_exists = grep { $_->{branchcode} eq '*' } @reasons; @@ -96,7 +99,7 @@ sub toggle { my @classes; push @classes, 'default' if $default_exists; push @classes, 'disabled' if $non_default_also; - $response->{classes} = join(' ', @classes); + $response->{classes} = join( ' ', @classes ); } print $input->header; print encode_json($response); @@ -108,14 +111,15 @@ sub dispatch { show => \&show, 'cud-toggle' => \&toggle, ); - my $input = CGI->new; - my $op = $input->param('op') || 'show'; + my $input = CGI->new; + my $op = $input->param('op') || 'show'; - if (not exists $handler{$op}) { + if ( not exists $handler{$op} ) { my $status = 400; - print $input->header(-status => $status); + print $input->header( -status => $status ); print $input->div( $input->h1($status), + # FIXME This is not translatable $input->p("op parameter is not supported (must be 'show' or 'toggle').") ); @@ -128,7 +132,6 @@ sub dispatch { dispatch if $ENV{REQUEST_URI}; 1; - =head1 NAME admin/item_circulation_alerts.pl - per-branch configuration for messaging diff --git a/admin/items_search_field.pl b/admin/items_search_field.pl index caaefe6a28..262ae91f37 100755 --- a/admin/items_search_field.pl +++ b/admin/items_search_field.pl @@ -19,26 +19,28 @@ use Modern::Perl; use CGI; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use Koha::Item::Search::Field qw(GetItemSearchField AddItemSearchField ModItemSearchField); my $cgi = CGI->new; -my ($template, $borrowernumber, $cookie) = get_template_and_user({ - template_name => 'admin/items_search_field.tt', - query => $cgi, - type => 'intranet', - flagsrequired => { parameters => 'manage_item_search_fields' }, -}); +my ( $template, $borrowernumber, $cookie ) = get_template_and_user( + { + template_name => 'admin/items_search_field.tt', + query => $cgi, + type => 'intranet', + flagsrequired => { parameters => 'manage_item_search_fields' }, + } +); -my $op = $cgi->param('op') || ''; +my $op = $cgi->param('op') || ''; my $name = $cgi->param('name'); -if ($op eq 'cud-mod') { - my %vars = $cgi->Vars; - my $field = { name => $name }; +if ( $op eq 'cud-mod' ) { + my %vars = $cgi->Vars; + my $field = { name => $name }; my @params = qw(label tagfield tagsubfield authorised_values_category); @$field{@params} = @vars{@params}; if ( $field->{authorised_values_category} eq '' ) { @@ -46,7 +48,7 @@ if ($op eq 'cud-mod') { } $field = ModItemSearchField($field); my $updated = ($field) ? 1 : 0; - print $cgi->redirect('/cgi-bin/koha/admin/items_search_fields.pl?updated=' . $updated); + print $cgi->redirect( '/cgi-bin/koha/admin/items_search_fields.pl?updated=' . $updated ); exit; } elsif ( $op eq 'cud-add' ) { my %vars = $cgi->Vars; diff --git a/admin/items_search_fields.pl b/admin/items_search_fields.pl index 1cfc051d9b..63334ded71 100755 --- a/admin/items_search_fields.pl +++ b/admin/items_search_fields.pl @@ -19,37 +19,39 @@ use Modern::Perl; use CGI; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use Koha::Item::Search::Field qw(GetItemSearchFields DelItemSearchField); my $cgi = CGI->new; -my ($template, $borrowernumber, $cookie) = get_template_and_user({ - template_name => 'admin/items_search_fields.tt', - query => $cgi, - type => 'intranet', - flagsrequired => { parameters => 'manage_item_search_fields' }, -}); +my ( $template, $borrowernumber, $cookie ) = get_template_and_user( + { + template_name => 'admin/items_search_fields.tt', + query => $cgi, + type => 'intranet', + flagsrequired => { parameters => 'manage_item_search_fields' }, + } +); my $op = $cgi->param('op') || ''; -if ($op eq 'cud-del') { +if ( $op eq 'cud-del' ) { my $name = $cgi->param('name'); - my $rv = DelItemSearchField($name); + my $rv = DelItemSearchField($name); if ($rv) { - $template->param(field_deleted => 1); + $template->param( field_deleted => 1 ); } else { - $template->param(field_not_deleted => 1); + $template->param( field_not_deleted => 1 ); } } else { my $updated = $cgi->param('updated'); - if (defined $updated) { + if ( defined $updated ) { if ($updated) { - $template->param(field_updated => 1); + $template->param( field_updated => 1 ); } else { - $template->param(field_not_updated => 1); + $template->param( field_not_updated => 1 ); } } } diff --git a/admin/koha2marclinks.pl b/admin/koha2marclinks.pl index 98a7a533cc..3f2b201857 100755 --- a/admin/koha2marclinks.pl +++ b/admin/koha2marclinks.pl @@ -22,7 +22,7 @@ use Modern::Perl; use CGI qw ( -utf8 ); use Koha::Database; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use Koha::BiblioFrameworks; use Koha::Caches; @@ -31,66 +31,71 @@ use Koha::MarcSubfieldStructures; my $input = CGI->new; my $op = $input->param('op') // q{}; -my ( $template, $borrowernumber, $cookie ) = get_template_and_user ( +my ( $template, $borrowernumber, $cookie ) = get_template_and_user( { - template_name => "admin/koha2marclinks.tt", - query => $input, - type => "intranet", - flagsrequired => { parameters => 'manage_marc_frameworks' }, + template_name => "admin/koha2marclinks.tt", + query => $input, + type => "intranet", + flagsrequired => { parameters => 'manage_marc_frameworks' }, } ); my $schema = Koha::Database->new->schema; -my $cache = Koha::Caches->get_instance(); +my $cache = Koha::Caches->get_instance(); # Update data before showing the form my $no_upd; -if( $input->param('add_field') && $op eq 'cud-save' ) { +if ( $input->param('add_field') && $op eq 'cud-save' ) { + # add a mapping to all frameworks - my ($kohafield, $tag, $sub) = split /,/, $input->param('add_field'), 3; - my $rs = Koha::MarcSubfieldStructures->search({ tagfield => $tag, tagsubfield => $sub }); - if( $rs->count ) { - $rs->update({ kohafield => $kohafield }); + my ( $kohafield, $tag, $sub ) = split /,/, $input->param('add_field'), 3; + my $rs = Koha::MarcSubfieldStructures->search( { tagfield => $tag, tagsubfield => $sub } ); + if ( $rs->count ) { + $rs->update( { kohafield => $kohafield } ); } else { $template->param( error_add => 1, error_info => "$tag, $sub" ); } -} elsif( $input->param('remove_field') && $op eq 'cud-save' ) { +} elsif ( $input->param('remove_field') && $op eq 'cud-save' ) { + # remove a mapping from all frameworks - my ($tag, $sub) = split /,/, $input->param('remove_field'), 2; - Koha::MarcSubfieldStructures->search({ tagfield => $tag, tagsubfield => $sub })->update({ kohafield => undef }); + my ( $tag, $sub ) = split /,/, $input->param('remove_field'), 2; + Koha::MarcSubfieldStructures->search( { tagfield => $tag, tagsubfield => $sub } )->update( { kohafield => undef } ); } else { $no_upd = 1; } # Clear the cache when needed -unless( $no_upd ) { +unless ($no_upd) { $cache->clear_from_cache("MarcSubfieldStructure-"); } # Build/Show the form my $dbix_map = { + # Koha to MARC mappings are found in only three tables - biblio => 'Biblio', + biblio => 'Biblio', biblioitems => 'Biblioitem', - items => 'Item', + items => 'Item', }; my @cols; foreach my $tbl ( sort keys %{$dbix_map} ) { push @cols, map { "$tbl.$_" } $schema->source( $dbix_map->{$tbl} )->columns; } -my $kohafields = Koha::MarcSubfieldStructures->search({ - frameworkcode => q{}, - kohafield => { '>', '' }, -}); +my $kohafields = Koha::MarcSubfieldStructures->search( + { + frameworkcode => q{}, + kohafield => { '>', '' }, + } +); my @loop_data; -foreach my $col ( @cols ) { +foreach my $col (@cols) { my $found; my $readonly = $col =~ /\.(biblio|biblioitem|item)number$/; - foreach my $row ( $kohafields->search({ kohafield => $col })->as_list ) { + foreach my $row ( $kohafields->search( { kohafield => $col } )->as_list ) { $found = 1; push @loop_data, { kohafield => $col, @@ -101,13 +106,13 @@ foreach my $col ( @cols ) { }; } push @loop_data, { - kohafield => $col, - readonly => $readonly, + kohafield => $col, + readonly => $readonly, } if !$found; } $template->param( - loop => \@loop_data, + loop => \@loop_data, ); output_html_with_http_headers $input, $cookie, $template->output; diff --git a/admin/library_groups.pl b/admin/library_groups.pl index 84dc309c66..80021876d5 100755 --- a/admin/library_groups.pl +++ b/admin/library_groups.pl @@ -20,7 +20,7 @@ use Modern::Perl; use CGI qw ( -utf8 ); use C4::Context; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use Koha::Libraries; @@ -31,10 +31,10 @@ my $cgi = CGI->new; my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "admin/library_groups.tt", - query => $cgi, - type => "intranet", - flagsrequired => { parameters => 'manage_libraries' }, + template_name => "admin/library_groups.tt", + query => $cgi, + type => "intranet", + flagsrequired => { parameters => 'manage_libraries' }, } ); @@ -42,10 +42,10 @@ my $op = $cgi->param('op') || q{}; my @messages; if ( $op eq 'cud-add' ) { - my $parent_id = $cgi->param('parent_id') || undef; - my $title = $cgi->param('title') || undef; - my $description = $cgi->param('description') || undef; - my $branchcode = $cgi->param('branchcode') || undef; + my $parent_id = $cgi->param('parent_id') || undef; + my $title = $cgi->param('title') || undef; + my $description = $cgi->param('description') || undef; + my $branchcode = $cgi->param('branchcode') || undef; my $ft_hide_patron_info = $cgi->param('ft_hide_patron_info') || 0; my $ft_limit_item_editing = $cgi->param('ft_limit_item_editing') || 0; my $ft_search_groups_opac = $cgi->param('ft_search_groups_opac') || 0; @@ -55,8 +55,7 @@ if ( $op eq 'cud-add' ) { if ( !$branchcode && Koha::Library::Groups->search( { title => $title } )->count() ) { $template->param( error_duplicate_title => $title ); - } - else { + } else { my $group = eval { Koha::Library::Group->new( { @@ -75,16 +74,14 @@ if ( $op eq 'cud-add' ) { }; if ($@) { push @messages, { type => 'warning', code => 'error_on_insert' }; - } - else { + } else { $template->param( added => $group ); } } -} -elsif ( $op eq 'cud-edit' ) { - my $id = $cgi->param('id') || undef; - my $title = $cgi->param('title') || undef; - my $description = $cgi->param('description') || undef; +} elsif ( $op eq 'cud-edit' ) { + my $id = $cgi->param('id') || undef; + my $title = $cgi->param('title') || undef; + my $description = $cgi->param('description') || undef; my $ft_hide_patron_info = $cgi->param('ft_hide_patron_info') || 0; my $ft_limit_item_editing = $cgi->param('ft_limit_item_editing') || 0; my $ft_search_groups_opac = $cgi->param('ft_search_groups_opac') || 0; @@ -110,8 +107,7 @@ elsif ( $op eq 'cud-edit' ) { $template->param( edited => $group ); } -} -elsif ( $op eq 'cud-delete' ) { +} elsif ( $op eq 'cud-delete' ) { my $id = $cgi->param('id'); my $group = Koha::Library::Groups->find($id); diff --git a/admin/localization.pl b/admin/localization.pl index 58205d8df7..e263c1ef7d 100755 --- a/admin/localization.pl +++ b/admin/localization.pl @@ -15,10 +15,9 @@ # You should have received a copy of the GNU General Public License # along with Koha; if not, see . - use Modern::Perl; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use Koha::Localization; @@ -29,10 +28,11 @@ use CGI qw( -utf8 ); my $query = CGI->new; my ( $template, $borrowernumber, $cookie ) = get_template_and_user( - { template_name => "admin/localization.tt", - flagsrequired => { parameters => 'manage_itemtypes' }, - query => $query, - type => "intranet", + { + template_name => "admin/localization.tt", + flagsrequired => { parameters => 'manage_itemtypes' }, + query => $query, + type => "intranet", } ); @@ -42,12 +42,13 @@ my $rs = Koha::Localizations->search( { entity => $entity, code => $code } ) my @translations; while ( my $s = $rs->next ) { push @translations, - { id => $s->localization_id, + { + id => $s->localization_id, entity => $s->entity, code => $s->code, lang => $s->lang, translation => $s->translation, - }; + }; } my $translated_languages = C4::Languages::getTranslatedLanguages( 'intranet', C4::Context->preference('template') ); diff --git a/admin/marc-overlay-rules.pl b/admin/marc-overlay-rules.pl index fc4c849e95..e7bf62d1e0 100755 --- a/admin/marc-overlay-rules.pl +++ b/admin/marc-overlay-rules.pl @@ -21,14 +21,14 @@ use CGI qw ( -utf8 ); use Try::Tiny; use C4::Context; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use C4::ImportBatch; use Koha::MarcOverlayRules; use Koha::Patron::Categories; -my $input = CGI->new; -my $op = $input->param('op') || ''; +my $input = CGI->new; +my $op = $input->param('op') || ''; my $errors = []; my $rule_from_cgi = sub { @@ -52,12 +52,12 @@ my $rule_from_cgi = sub { return \%rule; }; -my ($template, $loggedinuser, $cookie) = get_template_and_user( +my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "admin/marc-overlay-rules.tt", - query => $input, - type => "intranet", - flagsrequired => { parameters => 'manage_marc_overlay_rules' }, + template_name => "admin/marc-overlay-rules.tt", + query => $input, + type => "intranet", + flagsrequired => { parameters => 'manage_marc_overlay_rules' }, } ); @@ -66,63 +66,63 @@ my $get_rules = sub { }; my $rules = $get_rules->(); -if ($op eq 'cud-remove') { +if ( $op eq 'cud-remove' ) { my @remove_ids = $input->multi_param('batchremove'); push @remove_ids, scalar $input->param('id') if $input->param('id'); - Koha::MarcOverlayRules->search({ id => { in => \@remove_ids } })->delete(); + Koha::MarcOverlayRules->search( { id => { in => \@remove_ids } } )->delete(); + # Update $rules after deletion $rules = $get_rules->(); -} -elsif ($op eq 'edit') { +} elsif ( $op eq 'edit' ) { $template->param( edit => 1 ); my $id = $input->param('id'); - for my $rule(@{$rules}) { - if ($rule->{id} == $id) { + for my $rule ( @{$rules} ) { + if ( $rule->{id} == $id ) { $rule->{'edit'} = 1; last; } } -} -elsif ($op eq 'cud-edit' || $op eq 'cud-add') { +} elsif ( $op eq 'cud-edit' || $op eq 'cud-add' ) { my $rule_data = $rule_from_cgi->($input); - if (!@{$errors}) { + if ( !@{$errors} ) { try { Koha::MarcOverlayRules->validate($rule_data); - } - catch { + } catch { die $_ unless blessed $_ && $_->can('rethrow'); - if ($_->isa('Koha::Exceptions::MarcOverlayRule::InvalidTagRegExp')) { + if ( $_->isa('Koha::Exceptions::MarcOverlayRule::InvalidTagRegExp') ) { push @{$errors}, { type => 'error', code => 'invalid_tag_regexp', - tag => $rule_data->{tag}, + tag => $rule_data->{tag}, }; - } - elsif ($_->isa('Koha::Exceptions::MarcOverlayRule::InvalidControlFieldActions')) { + } elsif ( $_->isa('Koha::Exceptions::MarcOverlayRule::InvalidControlFieldActions') ) { push @{$errors}, { type => 'error', code => 'invalid_control_field_actions', - tag => $rule_data->{tag}, + tag => $rule_data->{tag}, }; - } - else { + } else { $_->rethrow; } }; - if (!@{$errors}) { + if ( !@{$errors} ) { my $rule = Koha::MarcOverlayRules->find_or_create($rule_data); + # Need to call set and store here in case we have an update $rule->set($rule_data); $rule->store(); } + # Update $rules after edit/add $rules = $get_rules->(); } } -my $categories = Koha::Patron::Categories->search_with_library_limits( {}, - { order_by => ['description'], columns => [ 'categorycode', 'description' ] } )->unblessed; +my $categories = Koha::Patron::Categories->search_with_library_limits( + {}, + { order_by => ['description'], columns => [ 'categorycode', 'description' ] } +)->unblessed; $template->param( rules => $rules, diff --git a/admin/marc_subfields_structure.pl b/admin/marc_subfields_structure.pl index 2b6e9fb03a..d150ea5c00 100755 --- a/admin/marc_subfields_structure.pl +++ b/admin/marc_subfields_structure.pl @@ -18,10 +18,10 @@ # along with Koha; if not, see . use Modern::Perl; -use Encode qw( encode_utf8 ); +use Encode qw( encode_utf8 ); use C4::Output qw( output_html_with_http_headers ); -use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); use C4::Context; use Koha::Authority::Types; @@ -41,18 +41,18 @@ $offset = 0 if not defined $offset or $offset < 0; my ( $template, $borrowernumber, $cookie ) = get_template_and_user( { - template_name => "admin/marc_subfields_structure.tt", - query => $input, - type => "intranet", - flagsrequired => { parameters => 'manage_marc_frameworks' }, + template_name => "admin/marc_subfields_structure.tt", + query => $input, + type => "intranet", + flagsrequired => { parameters => 'manage_marc_frameworks' }, } ); my $cache = Koha::Caches->get_instance(); -my $op = $input->param('op') || ""; +my $op = $input->param('op') || ""; $tagfield =~ s/\,//g; -my $framework = Koha::BiblioFrameworks->search({ frameworkcode => $frameworkcode })->next; +my $framework = Koha::BiblioFrameworks->search( { frameworkcode => $frameworkcode } )->next; if ($op) { $template->param( @@ -61,8 +61,7 @@ if ($op) { framework => $framework, $op => 1 ); # we show only the TMPL_VAR names $op -} -else { +} else { $template->param( tagfield => $tagfield, frameworkcode => $frameworkcode, @@ -74,7 +73,7 @@ else { ################## ADD_FORM ################################## # called by default. Used to create form to add or modify a record if ( $op eq 'add_form' ) { - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; # builds kohafield tables my @kohafields; @@ -98,7 +97,7 @@ if ( $op eq 'add_form' ) { # build authorised value list $sth2->finish; - my @authorised_values= Koha::AuthorisedValueCategories->search->get_column('category_name'); + my @authorised_values = Koha::AuthorisedValueCategories->search->get_column('category_name'); # build thesaurus categories list my @authtypes = uniq( "", map { $_->authtypecode } Koha::Authority::Types->search->as_list ); @@ -115,15 +114,16 @@ if ( $op eq 'add_form' ) { unless ( opendir( $dir_h, "$cgidir/cataloguing/value_builder" ) ) { $cgidir = C4::Context->config('intranetdir'); opendir( $dir_h, "$cgidir/cataloguing/value_builder" ) - || die "can't opendir $cgidir/value_builder: $!"; + || die "can't opendir $cgidir/value_builder: $!"; } while ( my $line = readdir($dir_h) ) { - if ( $line =~ /\.pl$/ && - $line !~ /EXAMPLE\.pl$/ ) { # documentation purposes + if ( $line =~ /\.pl$/ + && $line !~ /EXAMPLE\.pl$/ ) + { # documentation purposes push( @value_builder, $line ); } } - @value_builder= sort {$a cmp $b} @value_builder; + @value_builder = sort { $a cmp $b } @value_builder; closedir $dir_h; # build values list @@ -133,7 +133,7 @@ if ( $op eq 'add_form' ) { )->unblessed; my @loop_data = (); my $i = 0; - for my $m ( @$mss ) { + for my $m (@$mss) { my %row_data = %$m; # get a fresh hash for the row data $row_data{subfieldcode} = $m->{tagsubfield}; $row_data{urisubfieldcode} = $row_data{subfieldcode} eq '%' ? 'pct' : $row_data{subfieldcode}; @@ -147,24 +147,24 @@ if ( $op eq 'add_form' ) { and $m->{kohafield} eq 'biblio.biblionumber' ) { my $hidden_opac = Koha::Filter::MARC::ViewPolicy->should_hide_marc( - { - frameworkcode => $frameworkcode, - interface => "opac", - } - )->{biblionumber}; + { + frameworkcode => $frameworkcode, + interface => "opac", + } + )->{biblionumber}; my $hidden_intranet = Koha::Filter::MARC::ViewPolicy->should_hide_marc( - { - frameworkcode => $frameworkcode, - interface => "intranet", - } - )->{biblionumber}; + { + frameworkcode => $frameworkcode, + interface => "intranet", + } + )->{biblionumber}; if ( $hidden_opac or $hidden_intranet ) { + # We should allow editing for fixing it $row_data{hidden_protected} = 0; - } - else { + } else { $row_data{hidden_protected} = 1; } } @@ -174,7 +174,7 @@ if ( $op eq 'add_form' ) { } # Add a new row for the "New" tab - my %row_data; # get a fresh hash for the row data + my %row_data; # get a fresh hash for the row data $row_data{'new_subfield'} = 1; $row_data{'subfieldcode'} = ''; $row_data{'maxlength'} = 9999; @@ -199,17 +199,16 @@ if ( $op eq 'add_form' ) { $template->param( 'use_heading_flags_p' => 1 ); $template->param( 'heading_edit_subfields_p' => 1 ); $template->param( - tagfield => $tagfield, + tagfield => $tagfield, tagsubfield => $tagsubfield, - loop => \@loop_data, - more_tag => $tagfield + loop => \@loop_data, + more_tag => $tagfield ); # END $OP eq ADD_FORM ################## ADD_VALIDATE ################################## # called by add_form, used to insert/modify data in DB -} -elsif ( $op eq 'cud-add_validate' ) { +} elsif ( $op eq 'cud-add_validate' ) { my $dbh = C4::Context->dbh; $template->param( tagfield => "$input->param('tagfield')" ); my $tagfield = $input->param('tagfield'); @@ -217,28 +216,29 @@ elsif ( $op eq 'cud-add_validate' ) { my @tab_ids = $input->multi_param('tab_id'); my $display_order; - for my $tagsubfield ( @tagsubfield ) { + for my $tagsubfield (@tagsubfield) { $tagsubfield = "@" unless $tagsubfield ne ''; - my $id = shift @tab_ids; + my $id = shift @tab_ids; my $liblibrarian = $input->param("liblibrarian_$id"); my $libopac = $input->param("libopac_$id"); my $repeatable = $input->param("repeatable_$id") ? 1 : 0; - my $mandatory = $input->param("mandatory_$id") ? 1 : 0; - my $important = $input->param("important_$id") ? 1 : 0; + my $mandatory = $input->param("mandatory_$id") ? 1 : 0; + my $important = $input->param("important_$id") ? 1 : 0; my $kohafield = $input->param("kohafield_$id"); my $tab = $input->param("tab_$id"); my $seealso = $input->param("seealso_$id"); my $authorised_value = $input->param("authorised_value_$id"); my $authtypecode = $input->param("authtypecode_$id"); my $value_builder = $input->param("value_builder_$id"); - my $hidden = $input->param("hidden_$id"); - my $isurl = $input->param("isurl_$id") ? 1 : 0; - my $link = $input->param("link_$id"); - my $defaultvalue = $input->param("defaultvalue_$id"); - my $maxlength = $input->param("maxlength_$id") || 9999; + my $hidden = $input->param("hidden_$id"); + my $isurl = $input->param("isurl_$id") ? 1 : 0; + my $link = $input->param("link_$id"); + my $defaultvalue = $input->param("defaultvalue_$id"); + my $maxlength = $input->param("maxlength_$id") || 9999; - if (defined($liblibrarian) && $liblibrarian ne "") { - my $mss = Koha::MarcSubfieldStructures->find({tagfield => $tagfield, tagsubfield => $tagsubfield, frameworkcode => $frameworkcode }); + if ( defined($liblibrarian) && $liblibrarian ne "" ) { + my $mss = Koha::MarcSubfieldStructures->find( + { tagfield => $tagfield, tagsubfield => $tagsubfield, frameworkcode => $frameworkcode } ); if ($mss) { $mss->update( { @@ -262,9 +262,10 @@ elsif ( $op eq 'cud-add_validate' ) { } ); } else { - if( $frameworkcode ne q{} ) { + if ( $frameworkcode ne q{} ) { + # BZ 19096: Overwrite kohafield from Default when adding a new record - my $rec = Koha::MarcSubfieldStructures->find( q{}, $tagfield, $tagsubfield ); + my $rec = Koha::MarcSubfieldStructures->find( q{}, $tagfield, $tagsubfield ); $kohafield = $rec->kohafield if $rec; } Koha::MarcSubfieldStructure->new( @@ -300,14 +301,14 @@ elsif ( $op eq 'cud-add_validate' ) { $cache->clear_from_cache("MarcSubfieldStructure-$frameworkcode"); $cache->clear_from_cache("MarcCodedFields-$frameworkcode"); - print $input->redirect("/cgi-bin/koha/admin/marc_subfields_structure.pl?tagfield=$tagfield&frameworkcode=$frameworkcode"); + print $input->redirect( + "/cgi-bin/koha/admin/marc_subfields_structure.pl?tagfield=$tagfield&frameworkcode=$frameworkcode"); exit; # END $OP eq ADD_VALIDATE ################## DELETE_CONFIRM ################################## # called by default form, used to confirm deletion of data in DB -} -elsif ( $op eq 'delete_confirm' ) { +} elsif ( $op eq 'delete_confirm' ) { my $mss = Koha::MarcSubfieldStructures->find( { tagfield => $tagfield, @@ -321,9 +322,8 @@ elsif ( $op eq 'delete_confirm' ) { # END $OP eq DELETE_CONFIRM ################## DELETE_CONFIRMED ################################## - # called by delete_confirm, used to effectively confirm deletion of data in DB -} -elsif ( $op eq 'cud-delete_confirmed' ) { + # called by delete_confirm, used to effectively confirm deletion of data in DB +} elsif ( $op eq 'cud-delete_confirmed' ) { Koha::MarcSubfieldStructures->find( { tagfield => $tagfield, @@ -336,13 +336,13 @@ elsif ( $op eq 'cud-delete_confirmed' ) { $cache->clear_from_cache("MarcStructure-1-$frameworkcode"); $cache->clear_from_cache("MarcSubfieldStructure-$frameworkcode"); $cache->clear_from_cache("MarcCodedFields-$frameworkcode"); - print $input->redirect("/cgi-bin/koha/admin/marc_subfields_structure.pl?tagfield=$tagfield&frameworkcode=$frameworkcode"); + print $input->redirect( + "/cgi-bin/koha/admin/marc_subfields_structure.pl?tagfield=$tagfield&frameworkcode=$frameworkcode"); exit; # END $OP eq DELETE_CONFIRMED ################## DEFAULT ################################## -} -else { # DEFAULT +} else { # DEFAULT my $mss = Koha::MarcSubfieldStructures->search( { tagfield => { -like => "$tagfield%" }, diff --git a/admin/marctagstructure.pl b/admin/marctagstructure.pl index 06239bfda7..d59e8aa2e8 100755 --- a/admin/marctagstructure.pl +++ b/admin/marctagstructure.pl @@ -1,6 +1,5 @@ #!/usr/bin/perl - # Copyright 2000-2002 Katipo Communications # # This file is part of Koha. @@ -19,7 +18,7 @@ # along with Koha; if not, see . use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Auth qw( get_template_and_user ); use C4::Context; use C4::Output qw( output_html_with_http_headers ); @@ -31,108 +30,116 @@ use Koha::BiblioFrameworks; use Koha::Database; # retrieve parameters -my $input = CGI->new; -my $frameworkcode = $input->param('frameworkcode') || ''; # set to select framework +my $input = CGI->new; +my $frameworkcode = $input->param('frameworkcode') || ''; # set to select framework my $existingframeworkcode = $input->param('existingframeworkcode') || ''; -my $searchfield = $input->param('searchfield') || 0; -$searchfield=~ s/\,//g; +my $searchfield = $input->param('searchfield') || 0; +$searchfield =~ s/\,//g; my $offset = $input->param('offset') || 0; my $op = $input->param('op') || ''; my $dspchoice = $input->cookie("marctagstructure_selectdisplay") // $input->param('select_display'); -my $pagesize = 20; +my $pagesize = 20; -my $dbh = C4::Context->dbh; +my $dbh = C4::Context->dbh; my $cache = Koha::Caches->get_instance(); # open template -my ($template, $loggedinuser, $cookie) - = get_template_and_user({template_name => "admin/marctagstructure.tt", - query => $input, - type => "intranet", - flagsrequired => { parameters => 'manage_marc_frameworks' }, - }); +my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "admin/marctagstructure.tt", + query => $input, + type => "intranet", + flagsrequired => { parameters => 'manage_marc_frameworks' }, + } +); -my $frameworks = Koha::BiblioFrameworks->search({}, { order_by => ['frameworktext'] }); +my $frameworks = Koha::BiblioFrameworks->search( {}, { order_by => ['frameworktext'] } ); # check that framework is defined in marc_tag_structure -my $sth=$dbh->prepare("select count(*) from marc_tag_structure where frameworkcode=?"); +my $sth = $dbh->prepare("select count(*) from marc_tag_structure where frameworkcode=?"); $sth->execute($frameworkcode); my ($frameworkexist) = $sth->fetchrow; unless ($frameworkexist) { - # if frameworkcode does not exists, then OP must be changed to "create framework" if we are not on the way to create it - # (op = itemtyp_create_confirm) - if ($op eq "cud-framework_create_confirm") { - duplicate_framework($frameworkcode, $existingframeworkcode); - $op = ""; # unset $op to go back to framework list - } else { - $op = "framework_create"; - } + + # if frameworkcode does not exists, then OP must be changed to "create framework" if we are not on the way to create it + # (op = itemtyp_create_confirm) + if ( $op eq "cud-framework_create_confirm" ) { + duplicate_framework( $frameworkcode, $existingframeworkcode ); + $op = ""; # unset $op to go back to framework list + } else { + $op = "framework_create"; + } } -my $framework = $frameworks->search({ frameworkcode => $frameworkcode })->next; +my $framework = $frameworks->search( { frameworkcode => $frameworkcode } )->next; $template->param( - frameworks => $frameworks, - framework => $framework, + frameworks => $frameworks, + framework => $framework, ( $op || 'else' ) => 1, ); - ################## ADD_FORM ################################## # called by default. Used to create form to add or modify a record -if ($op eq 'add_form') { - #---- if primkey exists, it's a modify action, so read values to modify... - my $data; - if ($searchfield) { - $sth=$dbh->prepare("select tagfield,liblibrarian,libopac,repeatable,mandatory,important,authorised_value,ind1_defaultvalue,ind2_defaultvalue from marc_tag_structure where tagfield=? and frameworkcode=?"); - $sth->execute($searchfield,$frameworkcode); - $data=$sth->fetchrow_hashref; - } +if ( $op eq 'add_form' ) { - if ($searchfield) { - $template->param(searchfield => $searchfield); - $template->param('heading_modify_tag_p' => 1); - } else { - $template->param('heading_add_tag_p' => 1); - } - $template->param('use_heading_flags_p' => 1); - $template->param(liblibrarian => $data->{'liblibrarian'}, - libopac => $data->{'libopac'}, - repeatable => $data->{'repeatable'}, - mandatory => $data->{'mandatory'}, - important => $data->{'important'}, - authorised_value => $data->{authorised_value}, - ind1_defaultvalue => $data->{'ind1_defaultvalue'}, - ind2_defaultvalue => $data->{'ind2_defaultvalue'} - ); # FIXME: move checkboxes to presentation layer - # END $OP eq ADD_FORM + #---- if primkey exists, it's a modify action, so read values to modify... + my $data; + if ($searchfield) { + $sth = $dbh->prepare( + "select tagfield,liblibrarian,libopac,repeatable,mandatory,important,authorised_value,ind1_defaultvalue,ind2_defaultvalue from marc_tag_structure where tagfield=? and frameworkcode=?" + ); + $sth->execute( $searchfield, $frameworkcode ); + $data = $sth->fetchrow_hashref; + } + + if ($searchfield) { + $template->param( searchfield => $searchfield ); + $template->param( 'heading_modify_tag_p' => 1 ); + } else { + $template->param( 'heading_add_tag_p' => 1 ); + } + $template->param( 'use_heading_flags_p' => 1 ); + $template->param( + liblibrarian => $data->{'liblibrarian'}, + libopac => $data->{'libopac'}, + repeatable => $data->{'repeatable'}, + mandatory => $data->{'mandatory'}, + important => $data->{'important'}, + authorised_value => $data->{authorised_value}, + ind1_defaultvalue => $data->{'ind1_defaultvalue'}, + ind2_defaultvalue => $data->{'ind2_defaultvalue'} + ); # FIXME: move checkboxes to presentation layer + # END $OP eq ADD_FORM ################## ADD_VALIDATE ################################## -# called by add_form, used to insert/modify data in DB -} elsif ($op eq 'cud-add_validate') { - my $tagfield = $input->param('tagfield'); - my $liblibrarian = $input->param('liblibrarian'); - my $libopac = $input->param('libopac'); - my $repeatable = $input->param('repeatable') ? 1 : 0; - my $mandatory = $input->param('mandatory') ? 1 : 0; - my $important = $input->param('important') ? 1 : 0; - my $authorised_value = $input->param('authorised_value'); + # called by add_form, used to insert/modify data in DB +} elsif ( $op eq 'cud-add_validate' ) { + my $tagfield = $input->param('tagfield'); + my $liblibrarian = $input->param('liblibrarian'); + my $libopac = $input->param('libopac'); + my $repeatable = $input->param('repeatable') ? 1 : 0; + my $mandatory = $input->param('mandatory') ? 1 : 0; + my $important = $input->param('important') ? 1 : 0; + my $authorised_value = $input->param('authorised_value'); my $ind1_defaultvalue = $input->param('ind1_defaultvalue'); my $ind2_defaultvalue = $input->param('ind2_defaultvalue'); my $error; - if ($input->param('modif')) { + + if ( $input->param('modif') ) { $sth = $dbh->prepare( - "UPDATE marc_tag_structure SET liblibrarian=? ,libopac=? ,repeatable=? ,mandatory=? ,important=? ,authorised_value=?, ind1_defaultvalue=?, ind2_defaultvalue=? WHERE frameworkcode=? AND tagfield=?" + "UPDATE marc_tag_structure SET liblibrarian=? ,libopac=? ,repeatable=? ,mandatory=? ,important=? ,authorised_value=?, ind1_defaultvalue=?, ind2_defaultvalue=? WHERE frameworkcode=? AND tagfield=?" ); - $sth->execute( $liblibrarian, - $libopac, - $repeatable, - $mandatory, - $important, - $authorised_value, - $ind1_defaultvalue, - $ind2_defaultvalue, - $frameworkcode, - $tagfield + $sth->execute( + $liblibrarian, + $libopac, + $repeatable, + $mandatory, + $important, + $authorised_value, + $ind1_defaultvalue, + $ind2_defaultvalue, + $frameworkcode, + $tagfield ); } else { my $schema = Koha::Database->new()->schema(); @@ -170,25 +177,29 @@ if ($op eq 'add_form') { } print $input->redirect($redirect_url); exit; - # END $OP eq ADD_VALIDATE + + # END $OP eq ADD_VALIDATE ################## DELETE_CONFIRM ################################## -# called by default form, used to confirm deletion of data in DB -} elsif ($op eq 'delete_confirm') { - $sth=$dbh->prepare("select tagfield,liblibrarian,libopac,repeatable,mandatory,authorised_value,ind1_defaultvalue,ind2_defaultvalue from marc_tag_structure where tagfield=? and frameworkcode=?"); - $sth->execute($searchfield, $frameworkcode); - my $data = $sth->fetchrow_hashref; - $template->param( - liblibrarian => $data->{'liblibrarian'}, - searchfield => $searchfield + # called by default form, used to confirm deletion of data in DB +} elsif ( $op eq 'delete_confirm' ) { + $sth = $dbh->prepare( + "select tagfield,liblibrarian,libopac,repeatable,mandatory,authorised_value,ind1_defaultvalue,ind2_defaultvalue from marc_tag_structure where tagfield=? and frameworkcode=?" ); - # END $OP eq DELETE_CONFIRM + $sth->execute( $searchfield, $frameworkcode ); + my $data = $sth->fetchrow_hashref; + $template->param( + liblibrarian => $data->{'liblibrarian'}, + searchfield => $searchfield + ); + + # END $OP eq DELETE_CONFIRM ################## DELETE_CONFIRMED ################################## -# called by delete_confirm, used to effectively confirm deletion of data in DB -} elsif ($op eq 'cud-delete_confirmed') { + # called by delete_confirm, used to effectively confirm deletion of data in DB +} elsif ( $op eq 'cud-delete_confirmed' ) { my $sth1 = $dbh->prepare("DELETE FROM marc_tag_structure WHERE tagfield=? AND frameworkcode=?"); my $sth2 = $dbh->prepare("DELETE FROM marc_subfield_structure WHERE tagfield=? AND frameworkcode=?"); - $sth1->execute($searchfield, $frameworkcode); - $sth2->execute($searchfield, $frameworkcode); + $sth1->execute( $searchfield, $frameworkcode ); + $sth2->execute( $searchfield, $frameworkcode ); $cache->clear_from_cache("MarcStructure-0-$frameworkcode"); $cache->clear_from_cache("MarcStructure-1-$frameworkcode"); $cache->clear_from_cache("MarcSubfieldStructure-$frameworkcode"); @@ -196,39 +207,40 @@ if ($op eq 'add_form') { print $input->redirect( "/cgi-bin/koha/admin/marctagstructure.pl?searchfield=$searchfield&frameworkcode=$frameworkcode"); exit; - # END $OP eq DELETE_CONFIRMED + + # END $OP eq DELETE_CONFIRMED ################## ITEMTYPE_CREATE ################################## -# called automatically if an unexisting frameworkis selected -} elsif ($op eq 'framework_create') { + # called automatically if an unexisting frameworkis selected +} elsif ( $op eq 'framework_create' ) { my $frameworks = Koha::BiblioFrameworks->search( + { 'marc_tag_structure.frameworkcode' => { '!=' => undef } }, { - 'marc_tag_structure.frameworkcode' => { '!=' => undef } - }, - { - join => 'marc_tag_structure', + join => 'marc_tag_structure', distinct => 1 } ); $template->param( existing_frameworks => $frameworks ); ################## DEFAULT ################################## -} else { # DEFAULT +} else { # DEFAULT my $error_code = $input->param('error'); - if ($error_code){ - if ($error_code eq 'duplicate_tagfield'){ - $template->param('blocking_error' => $error_code); + if ($error_code) { + if ( $error_code eq 'duplicate_tagfield' ) { + $template->param( 'blocking_error' => $error_code ); } } - # here, $op can be unset or set to "cud-framework_create_confirm". - if ($searchfield ne '') { - $template->param(searchfield => $searchfield); + + # here, $op can be unset or set to "cud-framework_create_confirm". + if ( $searchfield ne '' ) { + $template->param( searchfield => $searchfield ); } - my $cnt=0; - if ($dspchoice) { - #here, user only wants used tags/subfields displayed - $searchfield=~ s/\'/\\\'/g; - my @data=split(' ',$searchfield); - my $sth=$dbh->prepare(" + my $cnt = 0; + if ($dspchoice) { + + #here, user only wants used tags/subfields displayed + $searchfield =~ s/\'/\\\'/g; + my @data = split( ' ', $searchfield ); + my $sth = $dbh->prepare( " SELECT marc_tag_structure.tagfield AS mts_tagfield, marc_tag_structure.liblibrarian as mts_liblibrarian, marc_tag_structure.libopac as mts_libopac, @@ -240,120 +252,140 @@ if ($op eq 'add_form') { marc_tag_structure.ind1_defaultvalue as mts_ind2_defaultvalue, marc_subfield_structure.* FROM marc_tag_structure - LEFT JOIN marc_subfield_structure ON (marc_tag_structure.tagfield=marc_subfield_structure.tagfield AND marc_tag_structure.frameworkcode=marc_subfield_structure.frameworkcode) WHERE (marc_tag_structure.tagfield >= ? and marc_tag_structure.frameworkcode=?) AND marc_subfield_structure.tab>=0 ORDER BY marc_tag_structure.tagfield,marc_subfield_structure.tagsubfield"); - #could be ordoned by tab - $sth->execute($data[0], $frameworkcode); - my @results = (); - while (my $data=$sth->fetchrow_hashref){ - push(@results,$data); - $cnt++; - } - - my @loop_data = (); - my $j=1; - my $i=$offset; + LEFT JOIN marc_subfield_structure ON (marc_tag_structure.tagfield=marc_subfield_structure.tagfield AND marc_tag_structure.frameworkcode=marc_subfield_structure.frameworkcode) WHERE (marc_tag_structure.tagfield >= ? and marc_tag_structure.frameworkcode=?) AND marc_subfield_structure.tab>=0 ORDER BY marc_tag_structure.tagfield,marc_subfield_structure.tagsubfield" + ); + + #could be ordoned by tab + $sth->execute( $data[0], $frameworkcode ); + my @results = (); + while ( my $data = $sth->fetchrow_hashref ) { + push( @results, $data ); + $cnt++; + } + + my @loop_data = (); + my $j = 1; + my $i = $offset; while ( $i < $cnt ) { - my %row_data; # get a fresh hash for the row data - $row_data{tagfield} = $results[$i]->{'mts_tagfield'}; - $row_data{liblibrarian} = $results[$i]->{'mts_liblibrarian'}; - $row_data{repeatable} = $results[$i]->{'mts_repeatable'}; - $row_data{mandatory} = $results[$i]->{'mts_mandatory'}; - $row_data{important} = $results[$i]->{'mts_important'}; - $row_data{authorised_value} = $results[$i]->{'mts_authorised_value'}; + my %row_data; # get a fresh hash for the row data + $row_data{tagfield} = $results[$i]->{'mts_tagfield'}; + $row_data{liblibrarian} = $results[$i]->{'mts_liblibrarian'}; + $row_data{repeatable} = $results[$i]->{'mts_repeatable'}; + $row_data{mandatory} = $results[$i]->{'mts_mandatory'}; + $row_data{important} = $results[$i]->{'mts_important'}; + $row_data{authorised_value} = $results[$i]->{'mts_authorised_value'}; $row_data{ind1_defaultvalue} = $results[$i]->{'mts_ind1_defaultvalue'}; $row_data{ind2_defaultvalue} = $results[$i]->{'mts_ind2_defaultvalue'}; - $j=$i; - my @internal_loop = (); - while ( ( $j < $cnt ) and ( $results[$i]->{'tagfield'} == $results[$j]->{'tagfield'} ) ) { - my %subfield_data; - $subfield_data{tagsubfield} = $results[$j]->{'tagsubfield'}; - $subfield_data{liblibrarian} = $results[$j]->{'liblibrarian'}; - $subfield_data{kohafield} = $results[$j]->{'kohafield'}; - $subfield_data{repeatable} = $results[$j]->{'repeatable'}; - $subfield_data{mandatory} = $results[$j]->{'mandatory'}; + $j = $i; + my @internal_loop = (); + + while ( ( $j < $cnt ) and ( $results[$i]->{'tagfield'} == $results[$j]->{'tagfield'} ) ) { + my %subfield_data; + $subfield_data{tagsubfield} = $results[$j]->{'tagsubfield'}; + $subfield_data{liblibrarian} = $results[$j]->{'liblibrarian'}; + $subfield_data{kohafield} = $results[$j]->{'kohafield'}; + $subfield_data{repeatable} = $results[$j]->{'repeatable'}; + $subfield_data{mandatory} = $results[$j]->{'mandatory'}; $subfield_data{important} = $results[$j]->{'important'}; - $subfield_data{tab} = $results[$j]->{'tab'}; - $subfield_data{seealso} = $results[$j]->{'seealso'}; - $subfield_data{authorised_value} = $results[$j]->{'authorised_value'}; - $subfield_data{authtypecode} = $results[$j]->{'authtypecode'}; - $subfield_data{value_builder} = $results[$j]->{'value_builder'}; -# warn "tagfield : ".$results[$j]->{'tagfield'}." tagsubfield :".$results[$j]->{'tagsubfield'}; - push @internal_loop,\%subfield_data; - $j++; - } - $row_data{'subfields'}=\@internal_loop; - push(@loop_data, \%row_data); - $i=$j; - } - $template->param(select_display => "True", - loop => \@loop_data); - } else { + $subfield_data{tab} = $results[$j]->{'tab'}; + $subfield_data{seealso} = $results[$j]->{'seealso'}; + $subfield_data{authorised_value} = $results[$j]->{'authorised_value'}; + $subfield_data{authtypecode} = $results[$j]->{'authtypecode'}; + $subfield_data{value_builder} = $results[$j]->{'value_builder'}; + + # warn "tagfield : ".$results[$j]->{'tagfield'}." tagsubfield :".$results[$j]->{'tagsubfield'}; + push @internal_loop, \%subfield_data; + $j++; + } + $row_data{'subfields'} = \@internal_loop; + push( @loop_data, \%row_data ); + $i = $j; + } + $template->param( + select_display => "True", + loop => \@loop_data + ); + } else { + # Hidden feature: If search was field$subfield, redirect to the subfield edit form my ( $tagfield, $tagsubfield ) = split /\$/, $searchfield; - if ( $tagsubfield ) { - print $input->redirect('/cgi-bin/koha/admin/marc_subfields_structure.pl?op=add_form&tagfield='.$tagfield.'&frameworkcode='.$frameworkcode.'#sub'.$tagsubfield.'field'); + if ($tagsubfield) { + print $input->redirect( '/cgi-bin/koha/admin/marc_subfields_structure.pl?op=add_form&tagfield=' + . $tagfield + . '&frameworkcode=' + . $frameworkcode . '#sub' + . $tagsubfield + . 'field' ); exit; } - #here, normal old style : display every tags - my ($count,$results)=StringSearch($searchfield,$frameworkcode); - $cnt = $count; - my @loop_data = (); + + #here, normal old style : display every tags + my ( $count, $results ) = StringSearch( $searchfield, $frameworkcode ); + $cnt = $count; + my @loop_data = (); for ( my $i = $offset ; $i < $count ; $i++ ) { - my %row_data; # get a fresh hash for the row data - $row_data{tagfield} = $results->[$i]{'tagfield'}; - $row_data{liblibrarian} = $results->[$i]{'liblibrarian'}; - $row_data{repeatable} = $results->[$i]{'repeatable'}; - $row_data{mandatory} = $results->[$i]{'mandatory'}; - $row_data{important} = $results->[$i]{'important'}; - $row_data{authorised_value} = $results->[$i]{'authorised_value'}; + my %row_data; # get a fresh hash for the row data + $row_data{tagfield} = $results->[$i]{'tagfield'}; + $row_data{liblibrarian} = $results->[$i]{'liblibrarian'}; + $row_data{repeatable} = $results->[$i]{'repeatable'}; + $row_data{mandatory} = $results->[$i]{'mandatory'}; + $row_data{important} = $results->[$i]{'important'}; + $row_data{authorised_value} = $results->[$i]{'authorised_value'}; $row_data{ind1_defaultvalue} = $results->[$i]{'ind1_defaultvalue'}; $row_data{ind2_defaultvalue} = $results->[$i]{'ind2_defaultvalue'}; - push(@loop_data, \%row_data); - } - $template->param(loop => \@loop_data); - } - if ($offset>0) { - $template->param(isprevpage => $offset, - prevpage=> $offset-$pagesize, - searchfield => $searchfield, - ); - } - if ($offset+$pagesize<$cnt) { - $template->param(nextpage =>$offset+$pagesize, - searchfield => $searchfield, - ); - } -} #---- END $OP eq DEFAULT + push( @loop_data, \%row_data ); + } + $template->param( loop => \@loop_data ); + } + if ( $offset > 0 ) { + $template->param( + isprevpage => $offset, + prevpage => $offset - $pagesize, + searchfield => $searchfield, + ); + } + if ( $offset + $pagesize < $cnt ) { + $template->param( + nextpage => $offset + $pagesize, + searchfield => $searchfield, + ); + } +} #---- END $OP eq DEFAULT output_html_with_http_headers $input, $cookie, $template->output; # # the sub used for searches # -sub StringSearch { - my ($searchstring,$frameworkcode)=@_; - my $sth = C4::Context->dbh->prepare(" +sub StringSearch { + my ( $searchstring, $frameworkcode ) = @_; + my $sth = C4::Context->dbh->prepare( " SELECT tagfield,liblibrarian,libopac,repeatable,mandatory,important,authorised_value,ind1_defaultvalue,ind2_defaultvalue FROM marc_tag_structure WHERE (tagfield >= ? and frameworkcode=?) ORDER BY tagfield - "); - $sth->execute($searchstring, $frameworkcode); - my $results = $sth->fetchall_arrayref({}); - return (scalar(@$results), $results); + " ); + $sth->execute( $searchstring, $frameworkcode ); + my $results = $sth->fetchall_arrayref( {} ); + return ( scalar(@$results), $results ); } # # the sub used to duplicate a framework from an existing one in MARC parameters tables. # sub duplicate_framework { - my ($newframeworkcode,$oldframeworkcode) = @_; + my ( $newframeworkcode, $oldframeworkcode ) = @_; my $dbh = C4::Context->dbh; - $dbh->do(q|INSERT INTO marc_tag_structure (tagfield, liblibrarian, libopac, repeatable, mandatory, important, authorised_value, ind1_defaultvalue, ind2_defaultvalue, frameworkcode) - SELECT tagfield,liblibrarian,libopac,repeatable,mandatory,important,authorised_value, ind1_defaultvalue, ind2_defaultvalue, ? from marc_tag_structure where frameworkcode=?|, undef, $newframeworkcode, $oldframeworkcode ); + $dbh->do( + q|INSERT INTO marc_tag_structure (tagfield, liblibrarian, libopac, repeatable, mandatory, important, authorised_value, ind1_defaultvalue, ind2_defaultvalue, frameworkcode) + SELECT tagfield,liblibrarian,libopac,repeatable,mandatory,important,authorised_value, ind1_defaultvalue, ind2_defaultvalue, ? from marc_tag_structure where frameworkcode=?|, + undef, $newframeworkcode, $oldframeworkcode + ); - $dbh->do(q|INSERT INTO marc_subfield_structure (frameworkcode,tagfield,tagsubfield,liblibrarian,libopac,repeatable,mandatory,important,kohafield,tab,authorised_value,authtypecode,value_builder,isurl,seealso,hidden,link,defaultvalue,maxlength) + $dbh->do( + q|INSERT INTO marc_subfield_structure (frameworkcode,tagfield,tagsubfield,liblibrarian,libopac,repeatable,mandatory,important,kohafield,tab,authorised_value,authtypecode,value_builder,isurl,seealso,hidden,link,defaultvalue,maxlength) SELECT ?,tagfield,tagsubfield,liblibrarian,libopac,repeatable,mandatory,important,kohafield,tab,authorised_value,authtypecode,value_builder,isurl,seealso,hidden,link,defaultvalue,maxlength from marc_subfield_structure where frameworkcode=? - |, undef, $newframeworkcode, $oldframeworkcode ); + |, undef, $newframeworkcode, $oldframeworkcode + ); } diff --git a/admin/matching-rules.pl b/admin/matching-rules.pl index ba807e05db..85782e614d 100755 --- a/admin/matching-rules.pl +++ b/admin/matching-rules.pl @@ -20,22 +20,23 @@ use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Auth qw( get_template_and_user ); use C4::Context; -use C4::Output qw( output_html_with_http_headers ); +use C4::Output qw( output_html_with_http_headers ); use C4::Matcher qw/valid_normalization_routines/; our $input = CGI->new; my $op = $input->param('op') || ''; - -my ($template, $loggedinuser, $cookie) - = get_template_and_user({template_name => "admin/matching-rules.tt", - query => $input, - type => "intranet", - flagsrequired => { parameters => 'manage_matching_rules' }, - }); +my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "admin/matching-rules.tt", + query => $input, + type => "intranet", + flagsrequired => { parameters => 'manage_matching_rules' }, + } +); my $matcher_id = $input->param("matcher_id"); @@ -46,20 +47,20 @@ unshift @valid_norms, 'none'; $template->param( valid_norms => \@valid_norms ); my $display_list = 0; -if ($op eq "edit_matching_rule") { - edit_matching_rule_form($template, $matcher_id); -} elsif ($op eq "cud-edit_matching_rule_confirmed") { - add_update_matching_rule($template, $matcher_id); +if ( $op eq "edit_matching_rule" ) { + edit_matching_rule_form( $template, $matcher_id ); +} elsif ( $op eq "cud-edit_matching_rule_confirmed" ) { + add_update_matching_rule( $template, $matcher_id ); $display_list = 1; -} elsif ($op eq "add_matching_rule") { +} elsif ( $op eq "add_matching_rule" ) { add_matching_rule_form($template); -} elsif ($op eq "cud-add_matching_rule_confirmed") { - add_update_matching_rule($template, $matcher_id); +} elsif ( $op eq "cud-add_matching_rule_confirmed" ) { + add_update_matching_rule( $template, $matcher_id ); $display_list = 1; -} elsif ($op eq "delete_matching_rule") { - delete_matching_rule_form($template, $matcher_id); -} elsif ($op eq "cud-delete_matching_rule_confirmed") { - delete_matching_rule($template, $matcher_id); +} elsif ( $op eq "delete_matching_rule" ) { + delete_matching_rule_form( $template, $matcher_id ); +} elsif ( $op eq "cud-delete_matching_rule_confirmed" ) { + delete_matching_rule( $template, $matcher_id ); $display_list = 1; } else { $display_list = 1; @@ -78,193 +79,204 @@ sub add_matching_rule_form { $template->param( matching_rule_form => 1, - confirm_op => 'cud-add_matching_rule_confirmed', - max_matchpoint => 1, - max_matchcheck => 1 + confirm_op => 'cud-add_matching_rule_confirmed', + max_matchpoint => 1, + max_matchcheck => 1 ); } sub add_update_matching_rule { - my $template = shift; - my $matcher_id = shift; + my $template = shift; + my $matcher_id = shift; my $record_type = $input->param('record_type') || 'biblio'; # do parsing - my $matcher = C4::Matcher->new($record_type, 1000); - $matcher->code(scalar $input->param('code')); - $matcher->description(scalar $input->param('description')); - $matcher->threshold(scalar $input->param('threshold')); + my $matcher = C4::Matcher->new( $record_type, 1000 ); + $matcher->code( scalar $input->param('code') ); + $matcher->description( scalar $input->param('description') ); + $matcher->threshold( scalar $input->param('threshold') ); # matchpoints - my @mp_nums = sort map { /^mp_(\d+)_search_index/ ? int($1): () } $input->multi_param; + my @mp_nums = sort map { /^mp_(\d+)_search_index/ ? int($1) : () } $input->multi_param; foreach my $mp_num (@mp_nums) { my $index = $input->param("mp_${mp_num}_search_index"); my $score = $input->param("mp_${mp_num}_score"); + # components my $components = []; - my @comp_nums = sort map { /^mp_${mp_num}_c_(\d+)_tag/ ? int($1): () } $input->multi_param; + my @comp_nums = sort map { /^mp_${mp_num}_c_(\d+)_tag/ ? int($1) : () } $input->multi_param; foreach my $comp_num (@comp_nums) { my $component = {}; - $component->{'tag'} = $input->param("mp_${mp_num}_c_${comp_num}_tag"); + $component->{'tag'} = $input->param("mp_${mp_num}_c_${comp_num}_tag"); $component->{'subfields'} = $input->param("mp_${mp_num}_c_${comp_num}_subfields"); - $component->{'offset'} = $input->param("mp_${mp_num}_c_${comp_num}_offset"); - $component->{'length'} = $input->param("mp_${mp_num}_c_${comp_num}_length"); + $component->{'offset'} = $input->param("mp_${mp_num}_c_${comp_num}_offset"); + $component->{'length'} = $input->param("mp_${mp_num}_c_${comp_num}_length"); + # norms $component->{'norms'} = []; - my @norm_nums = sort map { /^mp_${mp_num}_c_${comp_num}_n_(\d+)_norm/ ? int($1): () } $input->multi_param; + my @norm_nums = sort map { /^mp_${mp_num}_c_${comp_num}_n_(\d+)_norm/ ? int($1) : () } $input->multi_param; foreach my $norm_num (@norm_nums) { push @{ $component->{'norms'} }, $input->multi_param("mp_${mp_num}_c_${comp_num}_n_${norm_num}_norm"); } push @$components, $component; } - $matcher->add_matchpoint($index, $score, $components); + $matcher->add_matchpoint( $index, $score, $components ); } # match checks - my @mc_nums = sort map { /^mc_(\d+)_id/ ? int($1): () } $input->multi_param; + my @mc_nums = sort map { /^mc_(\d+)_id/ ? int($1) : () } $input->multi_param; foreach my $mc_num (@mc_nums) { + # source components my $src_components = []; - my @src_comp_nums = sort map { /^mc_${mc_num}_src_c_(\d+)_tag/ ? int($1): () } $input->multi_param; + my @src_comp_nums = sort map { /^mc_${mc_num}_src_c_(\d+)_tag/ ? int($1) : () } $input->multi_param; foreach my $comp_num (@src_comp_nums) { my $component = {}; - $component->{'tag'} = $input->param("mc_${mc_num}_src_c_${comp_num}_tag"); + $component->{'tag'} = $input->param("mc_${mc_num}_src_c_${comp_num}_tag"); $component->{'subfields'} = $input->param("mc_${mc_num}_src_c_${comp_num}_subfields"); - $component->{'offset'} = $input->param("mc_${mc_num}_src_c_${comp_num}_offset"); - $component->{'length'} = $input->param("mc_${mc_num}_src_c_${comp_num}_length"); + $component->{'offset'} = $input->param("mc_${mc_num}_src_c_${comp_num}_offset"); + $component->{'length'} = $input->param("mc_${mc_num}_src_c_${comp_num}_length"); + # norms $component->{'norms'} = []; - my @norm_nums = sort map { /^mc_${mc_num}_src_c_${comp_num}_n_(\d+)_norm/ ? int($1): () } $input->multi_param; + my @norm_nums = + sort map { /^mc_${mc_num}_src_c_${comp_num}_n_(\d+)_norm/ ? int($1) : () } $input->multi_param; foreach my $norm_num (@norm_nums) { - push @{ $component->{'norms'} }, $input->multi_param("mc_${mc_num}_src_c_${comp_num}_n_${norm_num}_norm"); + push @{ $component->{'norms'} }, + $input->multi_param("mc_${mc_num}_src_c_${comp_num}_n_${norm_num}_norm"); } push @$src_components, $component; } + # target components my $tgt_components = []; - my @tgt_comp_nums = sort map { /^mc_${mc_num}_tgt_c_(\d+)_tag/ ? int($1): () } $input->multi_param; + my @tgt_comp_nums = sort map { /^mc_${mc_num}_tgt_c_(\d+)_tag/ ? int($1) : () } $input->multi_param; foreach my $comp_num (@tgt_comp_nums) { my $component = {}; - $component->{'tag'} = $input->param("mc_${mc_num}_tgt_c_${comp_num}_tag"); + $component->{'tag'} = $input->param("mc_${mc_num}_tgt_c_${comp_num}_tag"); $component->{'subfields'} = $input->param("mc_${mc_num}_tgt_c_${comp_num}_subfields"); - $component->{'offset'} = $input->param("mc_${mc_num}_tgt_c_${comp_num}_offset"); - $component->{'length'} = $input->param("mc_${mc_num}_tgt_c_${comp_num}_length"); + $component->{'offset'} = $input->param("mc_${mc_num}_tgt_c_${comp_num}_offset"); + $component->{'length'} = $input->param("mc_${mc_num}_tgt_c_${comp_num}_length"); + # norms $component->{'norms'} = []; - my @norm_nums = sort map { /^mc_${mc_num}_tgt_c_${comp_num}_n_(\d+)_norm/ ? int($1): () } $input->multi_param; + my @norm_nums = + sort map { /^mc_${mc_num}_tgt_c_${comp_num}_n_(\d+)_norm/ ? int($1) : () } $input->multi_param; foreach my $norm_num (@norm_nums) { - push @{ $component->{'norms'} }, $input->multi_param("mc_${mc_num}_tgt_c_${comp_num}_n_${norm_num}_norm"); + push @{ $component->{'norms'} }, + $input->multi_param("mc_${mc_num}_tgt_c_${comp_num}_n_${norm_num}_norm"); } push @$tgt_components, $component; } - $matcher->add_required_check($src_components, $tgt_components); + $matcher->add_required_check( $src_components, $tgt_components ); } - - if (defined $matcher_id and $matcher_id =~ /^\d+/) { + + if ( defined $matcher_id and $matcher_id =~ /^\d+/ ) { $matcher->_id($matcher_id); - $template->param(edited_matching_rule => $matcher->code()); + $template->param( edited_matching_rule => $matcher->code() ); } else { - $template->param(added_matching_rule => $matcher->code()); + $template->param( added_matching_rule => $matcher->code() ); } $matcher_id = $matcher->store(); } sub delete_matching_rule_form { - my $template = shift; + my $template = shift; my $matcher_id = shift; my $matcher = C4::Matcher->fetch($matcher_id); $template->param( delete_matching_rule_form => 1, - confirm_op => "cud-delete_matching_rule_confirmed", - matcher_id => $matcher_id, - code => $matcher->code(), - description => $matcher->description(), + confirm_op => "cud-delete_matching_rule_confirmed", + matcher_id => $matcher_id, + code => $matcher->code(), + description => $matcher->description(), ); } sub delete_matching_rule { - my $template = shift; + my $template = shift; my $matcher_id = shift; my $matcher = C4::Matcher->fetch($matcher_id); - $template->param(deleted_matching_rule => $matcher->code(), - ); + $template->param( + deleted_matching_rule => $matcher->code(), + ); C4::Matcher->delete($matcher_id); } sub edit_matching_rule_form { - my $template = shift; + my $template = shift; my $matcher_id = shift; my $matcher = C4::Matcher->fetch($matcher_id); - $template->{VARS}->{'matcher_id'} = $matcher_id; - $template->{VARS}->{'code'} = $matcher->code(); + $template->{VARS}->{'matcher_id'} = $matcher_id; + $template->{VARS}->{'code'} = $matcher->code(); $template->{VARS}->{'description'} = $matcher->description(); - $template->{VARS}->{'threshold'} = $matcher->threshold(); + $template->{VARS}->{'threshold'} = $matcher->threshold(); $template->{VARS}->{'record_type'} = $matcher->record_type(); my $matcher_info = $matcher->dump(); - my @matchpoints = (); - my $mp_num = 0; - foreach my $matchpoint (@{ $matcher_info->{'matchpoints'} }) { + my @matchpoints = (); + my $mp_num = 0; + foreach my $matchpoint ( @{ $matcher_info->{'matchpoints'} } ) { $mp_num++; - my @components = _parse_components($matchpoint->{'components'}); - push @matchpoints, { - mp_num => $mp_num, - index => $matchpoint->{'index'}, - score => $matchpoint->{'score'}, + my @components = _parse_components( $matchpoint->{'components'} ); + push @matchpoints, { + mp_num => $mp_num, + index => $matchpoint->{'index'}, + score => $matchpoint->{'score'}, components => \@components - }; + }; } - $template->param(matchpoints => \@matchpoints); + $template->param( matchpoints => \@matchpoints ); - my $mc_num = 0; + my $mc_num = 0; my @matchchecks = (); - foreach my $matchcheck (@{ $matcher_info->{'matchchecks'} }) { + foreach my $matchcheck ( @{ $matcher_info->{'matchchecks'} } ) { $mc_num++; - my @src_components = _parse_components($matchcheck->{'source_matchpoint'}->{'components'}); - my @tgt_components = _parse_components($matchcheck->{'target_matchpoint'}->{'components'}); + my @src_components = _parse_components( $matchcheck->{'source_matchpoint'}->{'components'} ); + my @tgt_components = _parse_components( $matchcheck->{'target_matchpoint'}->{'components'} ); push @matchchecks, { - mc_num => $mc_num, + mc_num => $mc_num, src_components => \@src_components, tgt_components => \@tgt_components }; } - $template->param(matchchecks => \@matchchecks); + $template->param( matchchecks => \@matchchecks ); $template->param( matching_rule_form => 1, edit_matching_rule => 1, - confirm_op => 'cud-edit_matching_rule_confirmed', - max_matchpoint => $mp_num, - max_matchcheck => $mc_num + confirm_op => 'cud-edit_matching_rule_confirmed', + max_matchpoint => $mp_num, + max_matchcheck => $mc_num ); } sub _parse_components { my $components_ref = shift; - my @components = (); + my @components = (); my $comp_num = 0; - foreach my $component (@{ $components_ref }) { + foreach my $component ( @{$components_ref} ) { $comp_num++; my $norm_num = 0; my @norms; - foreach my $norm (@{ $component->{'norms'} }) { + foreach my $norm ( @{ $component->{'norms'} } ) { $norm_num++; push @norms, { norm_num => $norm_num, norm => $norm }; } push @components, { - comp_num => $comp_num, - tag => $component->{'tag'}, - subfields => join("", sort keys %{ $component->{'subfields'} }), - offset => $component->{'offset'}, - 'length' => $component->{'length'}, - norms => \@norms + comp_num => $comp_num, + tag => $component->{'tag'}, + subfields => join( "", sort keys %{ $component->{'subfields'} } ), + offset => $component->{'offset'}, + 'length' => $component->{'length'}, + norms => \@norms }; } @@ -273,8 +285,8 @@ sub _parse_components { sub matching_rule_list { my $template = shift; - + my @matching_rules = C4::Matcher::GetMatcherList(); - $template->param(available_matching_rules => \@matching_rules); - $template->param(display_list => 1); + $template->param( available_matching_rules => \@matching_rules ); + $template->param( display_list => 1 ); } diff --git a/admin/oai_set_mappings.pl b/admin/oai_set_mappings.pl index cdd9bb3f61..1ff3efe22e 100755 --- a/admin/oai_set_mappings.pl +++ b/admin/oai_set_mappings.pl @@ -32,35 +32,36 @@ the OR operator will be applied. use Modern::Perl; -use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); -use C4::Output qw( output_html_with_http_headers ); +use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); +use C4::Output qw( output_html_with_http_headers ); use C4::OAI::Sets qw( GetOAISet GetOAISetMappings ModOAISetMappings ); - my $input = CGI->new; -my ($template, $loggedinuser, $cookie, $flags) = get_template_and_user( { - template_name => 'admin/oai_set_mappings.tt', - query => $input, - type => 'intranet', - flagsrequired => { 'parameters' => 'manage_oai_sets' }, -} ); +my ( $template, $loggedinuser, $cookie, $flags ) = get_template_and_user( + { + template_name => 'admin/oai_set_mappings.tt', + query => $input, + type => 'intranet', + flagsrequired => { 'parameters' => 'manage_oai_sets' }, + } +); my $id = $input->param('id'); my $op = $input->param('op'); -if($op && $op eq "cud-save") { - my @marcfields = $input->multi_param('marcfield'); +if ( $op && $op eq "cud-save" ) { + my @marcfields = $input->multi_param('marcfield'); my @marcsubfields = $input->multi_param('marcsubfield'); - my @operators = $input->multi_param('operator'); - my @marcvalues = $input->multi_param('marcvalue'); + my @operators = $input->multi_param('operator'); + my @marcvalues = $input->multi_param('marcvalue'); my @ruleoperators = $input->multi_param('rule_operator'); - my @ruleorders = $input->multi_param('rule_order'); + my @ruleorders = $input->multi_param('rule_order'); my @mappings; my $i = 0; - while($i < @marcfields and $i < @marcsubfields and $i < @marcvalues) { - if($marcfields[$i] ne '' and $marcsubfields[$i] ne '' ) { + while ( $i < @marcfields and $i < @marcsubfields and $i < @marcvalues ) { + if ( $marcfields[$i] ne '' and $marcsubfields[$i] ne '' ) { push @mappings, { marcfield => $marcfields[$i], marcsubfield => $marcsubfields[$i], @@ -73,17 +74,17 @@ if($op && $op eq "cud-save") { $i++; } $mappings[0]{'rule_operator'} = undef if (@mappings); - ModOAISetMappings($id, \@mappings); - $template->param(mappings_saved => 1); + ModOAISetMappings( $id, \@mappings ); + $template->param( mappings_saved => 1 ); } -my $set = GetOAISet($id); +my $set = GetOAISet($id); my $mappings = GetOAISetMappings($id); $template->param( - id => $id, - setName => $set->{'name'}, - setSpec => $set->{'spec'}, + id => $id, + setName => $set->{'name'}, + setSpec => $set->{'spec'}, mappings => $mappings, ); diff --git a/admin/oai_sets.pl b/admin/oai_sets.pl index 6e69eac652..4fab217336 100755 --- a/admin/oai_sets.pl +++ b/admin/oai_sets.pl @@ -28,67 +28,72 @@ Admin page to describe OAI SETs use Modern::Perl; -use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); -use C4::Output qw( output_html_with_http_headers ); +use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); +use C4::Output qw( output_html_with_http_headers ); use C4::OAI::Sets qw( AddOAISet DelOAISet GetOAISet GetOAISets ModOAISet ); - my $input = CGI->new; -my ($template, $loggedinuser, $cookie, $flags) = get_template_and_user( { - template_name => 'admin/oai_sets.tt', - query => $input, - type => 'intranet', - flagsrequired => { 'parameters' => 'manage_oai_sets' }, -} ); +my ( $template, $loggedinuser, $cookie, $flags ) = get_template_and_user( + { + template_name => 'admin/oai_sets.tt', + query => $input, + type => 'intranet', + flagsrequired => { 'parameters' => 'manage_oai_sets' }, + } +); my $op = $input->param('op'); -if($op && $op eq "new") { +if ( $op && $op eq "new" ) { $template->param( op_new => 1 ); -} elsif($op && $op eq "cud-savenew") { - my $spec = $input->param('spec'); - my $name = $input->param('name'); +} elsif ( $op && $op eq "cud-savenew" ) { + my $spec = $input->param('spec'); + my $name = $input->param('name'); my @descriptions = $input->multi_param('description'); - AddOAISet({ - spec => $spec, - name => $name, - descriptions => \@descriptions - }); -} elsif($op && $op eq "mod") { - my $id = $input->param('id'); + AddOAISet( + { + spec => $spec, + name => $name, + descriptions => \@descriptions + } + ); +} elsif ( $op && $op eq "mod" ) { + my $id = $input->param('id'); my $set = GetOAISet($id); $template->param( - op_mod => 1, - id => $set->{'id'}, - spec => $set->{'spec'}, - name => $set->{'name'}, - descriptions => [ map { {description => $_} } @{ $set->{'descriptions'} } ], + op_mod => 1, + id => $set->{'id'}, + spec => $set->{'spec'}, + name => $set->{'name'}, + descriptions => [ map { { description => $_ } } @{ $set->{'descriptions'} } ], ); -} elsif($op && $op eq "cud-savemod") { - my $id = $input->param('id'); - my $spec = $input->param('spec'); - my $name = $input->param('name'); +} elsif ( $op && $op eq "cud-savemod" ) { + my $id = $input->param('id'); + my $spec = $input->param('spec'); + my $name = $input->param('name'); my @descriptions = $input->multi_param('description'); - ModOAISet({ - id => $id, - spec => $spec, - name => $name, - descriptions => \@descriptions - }); -} elsif($op && $op eq "cud-del") { + ModOAISet( + { + id => $id, + spec => $spec, + name => $name, + descriptions => \@descriptions + } + ); +} elsif ( $op && $op eq "cud-del" ) { my $id = $input->param('id'); DelOAISet($id); } my $OAISets = GetOAISets; my @sets_loop; -foreach(@$OAISets) { +foreach (@$OAISets) { push @sets_loop, { - id => $_->{'id'}, - spec => $_->{'spec'}, - name => $_->{'name'}, - descriptions => [ map { {description => $_} } @{ $_->{'descriptions'} } ] + id => $_->{'id'}, + spec => $_->{'spec'}, + name => $_->{'name'}, + descriptions => [ map { { description => $_ } } @{ $_->{'descriptions'} } ] }; } diff --git a/admin/overdrive.pl b/admin/overdrive.pl index 27e2c175cb..f290efd836 100755 --- a/admin/overdrive.pl +++ b/admin/overdrive.pl @@ -18,7 +18,7 @@ # along with Koha; if not, see . use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Auth qw( get_template_and_user ); use C4::Context; use C4::Output qw( output_html_with_http_headers ); @@ -26,40 +26,43 @@ use C4::Output qw( output_html_with_http_headers ); use Koha::Libraries; use Koha::Library::OverDriveInfos; -my $input = CGI->new; -my @branchcodes = $input->multi_param('branchcode'); -my @authnames = $input->multi_param('authname'); -my $op = $input->param('op'); +my $input = CGI->new; +my @branchcodes = $input->multi_param('branchcode'); +my @authnames = $input->multi_param('authname'); +my $op = $input->param('op'); our ( $template, $loggedinuser, $cookie ) = get_template_and_user( - { template_name => 'admin/overdrive.tt', - query => $input, - type => 'intranet', - flagsrequired => { parameters => 'parameters_remaining_permissions' }, + { + template_name => 'admin/overdrive.tt', + query => $input, + type => 'intranet', + flagsrequired => { parameters => 'parameters_remaining_permissions' }, } ); if ( $op && $op eq 'cud-update' ) { my %od_info; - @od_info{ @branchcodes } = @authnames; - while( my($branchcode,$authname) = each %od_info){ + @od_info{@branchcodes} = @authnames; + while ( my ( $branchcode, $authname ) = each %od_info ) { my $cur_info = Koha::Library::OverDriveInfos->find($branchcode); - if( $cur_info ) { + if ($cur_info) { $cur_info->authname($authname)->store; } else { - Koha::Library::OverDriveInfo->new({ - branchcode => $branchcode, - authname => $authname, - })->store; + Koha::Library::OverDriveInfo->new( + { + branchcode => $branchcode, + authname => $authname, + } + )->store; } } } my @branches = Koha::Libraries->search->as_list; my @branch_od_info; -foreach my $branch ( @branches ){ - my $od_info = Koha::Library::OverDriveInfos->find($branch->branchcode); - if( $od_info ){ +foreach my $branch (@branches) { + my $od_info = Koha::Library::OverDriveInfos->find( $branch->branchcode ); + if ($od_info) { push @branch_od_info, { branchcode => $od_info->branchcode, authname => $od_info->authname }; } else { push @branch_od_info, { branchcode => $branch->branchcode, authname => "" }; diff --git a/admin/patron-attr-types.pl b/admin/patron-attr-types.pl index 401522b604..9b771b1ae3 100755 --- a/admin/patron-attr-types.pl +++ b/admin/patron-attr-types.pl @@ -21,7 +21,7 @@ use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use List::MoreUtils qw( uniq ); use C4::Auth qw( get_template_and_user ); @@ -36,11 +36,11 @@ use Koha::Patron::Categories; our $input = CGI->new; my $op = $input->param('op') || ''; - my ( $template, $loggedinuser, $cookie ) = get_template_and_user( - { template_name => "admin/patron-attr-types.tt", - query => $input, - type => "intranet", + { + template_name => "admin/patron-attr-types.tt", + query => $input, + type => "intranet", flagsrequired => { parameters => 'manage_patron_attributes' } } ); @@ -48,26 +48,26 @@ my ( $template, $loggedinuser, $cookie ) = get_template_and_user( my $code = $input->param("code"); my $display_list = 0; -if ($op eq "edit_attribute_type") { - edit_attribute_type_form($template, $code); -} elsif ($op eq "cud-edit_attribute_type_confirmed") { - $display_list = add_update_attribute_type('edit', $template, $code); -} elsif ($op eq "add_attribute_type") { +if ( $op eq "edit_attribute_type" ) { + edit_attribute_type_form( $template, $code ); +} elsif ( $op eq "cud-edit_attribute_type_confirmed" ) { + $display_list = add_update_attribute_type( 'edit', $template, $code ); +} elsif ( $op eq "add_attribute_type" ) { add_attribute_type_form($template); -} elsif ($op eq "cud-add_attribute_type_confirmed") { - $display_list = add_update_attribute_type('add', $template, $code); -} elsif ($op eq "delete_attribute_type") { - $display_list = delete_attribute_type_form($template, $code); -} elsif ($op eq "cud-delete_attribute_type_confirmed") { - delete_attribute_type($template, $code); +} elsif ( $op eq "cud-add_attribute_type_confirmed" ) { + $display_list = add_update_attribute_type( 'add', $template, $code ); +} elsif ( $op eq "delete_attribute_type" ) { + $display_list = delete_attribute_type_form( $template, $code ); +} elsif ( $op eq "cud-delete_attribute_type_confirmed" ) { + delete_attribute_type( $template, $code ); $display_list = 1; } else { $display_list = 1; } if ($display_list) { - unless (C4::Context->preference('ExtendedPatronAttributes')) { - $template->param(WARNING_extended_attributes_off => 1); + unless ( C4::Context->preference('ExtendedPatronAttributes') ) { + $template->param( WARNING_extended_attributes_off => 1 ); } patron_attribute_type_list($template); } @@ -79,24 +79,24 @@ exit 0; sub add_attribute_type_form { my $template = shift; - my $patron_categories = Koha::Patron::Categories->search_with_library_limits({}, {order_by => ['description']}); + my $patron_categories = Koha::Patron::Categories->search_with_library_limits( {}, { order_by => ['description'] } ); $template->param( attribute_type_form => 1, - confirm_op => 'cud-add_attribute_type_confirmed', - categories => $patron_categories, + confirm_op => 'cud-add_attribute_type_confirmed', + categories => $patron_categories, ); } sub error_add_attribute_type_form { my $template = shift; - $template->param(description => scalar $input->param('description')); + $template->param( description => scalar $input->param('description') ); $template->param( category_code => scalar $input->param('category_code') ); - $template->param( class => scalar $input->param('class') ); + $template->param( class => scalar $input->param('class') ); $template->param( - attribute_type_form => 1, - confirm_op => 'cud-add_attribute_type_confirmed', + attribute_type_form => 1, + confirm_op => 'cud-add_attribute_type_confirmed', authorised_value_category => scalar $input->param('authorised_value_category'), ); } @@ -107,15 +107,15 @@ sub add_update_attribute_type { my $code = shift; my $description = $input->param('description'); - my $repeatable = $input->param('repeatable') ? 1 : 0; - my $unique_id = $input->param('unique_id') ? 1 : 0; - my $is_date = $input->param('is_date') ? 1 : 0; - my $opac_display = $input->param('opac_display') ? 1 : 0; - my $opac_editable = $input->param('opac_editable') ? 1 : 0; - my $staff_searchable = $input->param('staff_searchable') ? 1 : 0; - my $searched_by_default = $input->param('searched_by_default') ? 1 : 0; + my $repeatable = $input->param('repeatable') ? 1 : 0; + my $unique_id = $input->param('unique_id') ? 1 : 0; + my $is_date = $input->param('is_date') ? 1 : 0; + my $opac_display = $input->param('opac_display') ? 1 : 0; + my $opac_editable = $input->param('opac_editable') ? 1 : 0; + my $staff_searchable = $input->param('staff_searchable') ? 1 : 0; + my $searched_by_default = $input->param('searched_by_default') ? 1 : 0; my $keep_for_pseudonymization = $input->param('keep_for_pseudonymization') ? 1 : 0; - my $mandatory = $input->param('mandatory') ? 1 : 0; + my $mandatory = $input->param('mandatory') ? 1 : 0; my $authorised_value_category = $input->param('authorised_value_category'); my $display_checkout = $input->param('display_checkout') ? 1 : 0; my $category_code = $input->param('category_code') || undef; @@ -124,8 +124,7 @@ sub add_update_attribute_type { my $attr_type = Koha::Patron::Attribute::Types->find($code); if ( $op eq 'edit' ) { $attr_type->description($description); - } - else { + } else { if ($attr_type) { # Already exists $template->param( duplicate_code_error => $code ); @@ -160,13 +159,12 @@ sub add_update_attribute_type { } )->store; - my @branches = grep { ! /^\s*$/ } $input->multi_param('branches'); + my @branches = grep { !/^\s*$/ } $input->multi_param('branches'); $attr_type->library_limits( \@branches ); if ( $op eq 'edit' ) { $template->param( edited_attribute_type => $attr_type->code() ); - } - else { + } else { $template->param( added_attribute_type => $attr_type->code() ); } @@ -175,19 +173,19 @@ sub add_update_attribute_type { sub delete_attribute_type_form { my $template = shift; - my $code = shift; + my $code = shift; - my $attr_type = Koha::Patron::Attribute::Types->find($code); + my $attr_type = Koha::Patron::Attribute::Types->find($code); my $display_list = 0; - if (defined($attr_type)) { + if ( defined($attr_type) ) { $template->param( delete_attribute_type_form => 1, - confirm_op => "cud-delete_attribute_type_confirmed", - code => $code, - description => $attr_type->description(), + confirm_op => "cud-delete_attribute_type_confirmed", + code => $code, + description => $attr_type->description(), ); } else { - $template->param(ERROR_delete_not_found => $code); + $template->param( ERROR_delete_not_found => $code ); $display_list = 1; } return $display_list; @@ -195,54 +193,56 @@ sub delete_attribute_type_form { sub delete_attribute_type { my $template = shift; - my $code = shift; + my $code = shift; my $attr_type = Koha::Patron::Attribute::Types->find($code); - if (defined($attr_type)) { + if ( defined($attr_type) ) { + # TODO Check must be done for previous step as well if ( my $num_patrons = Koha::Patrons->filter_by_attribute_type($code)->count ) { - $template->param(ERROR_delete_in_use => $code); - $template->param(ERROR_num_patrons => $num_patrons ); + $template->param( ERROR_delete_in_use => $code ); + $template->param( ERROR_num_patrons => $num_patrons ); } else { $attr_type->delete(); - $template->param(deleted_attribute_type => $code); + $template->param( deleted_attribute_type => $code ); } } else { + # FIXME Really needed? - $template->param(ERROR_delete_not_found => $code); + $template->param( ERROR_delete_not_found => $code ); } } sub edit_attribute_type_form { my $template = shift; - my $code = shift; + my $code = shift; my $attr_type = Koha::Patron::Attribute::Types->find($code); - my $patron_categories = Koha::Patron::Categories->search({}, {order_by => ['description']}); + my $patron_categories = Koha::Patron::Categories->search( {}, { order_by => ['description'] } ); my $can_be_set_to_nonrepeatable = 1; if ( $attr_type->repeatable == 1 ) { $attr_type->repeatable(0); - eval {$attr_type->check_repeatables}; + eval { $attr_type->check_repeatables }; $can_be_set_to_nonrepeatable = 0 if $@; $attr_type->repeatable(1); } my $can_be_set_to_unique = 1; if ( $attr_type->unique_id == 0 ) { $attr_type->unique_id(1); - eval {$attr_type->check_unique_ids}; + eval { $attr_type->check_unique_ids }; $can_be_set_to_unique = 0 if $@; $attr_type->unique_id(0); } $template->param( - attribute_type => $attr_type, - attribute_type_form => 1, - edit_attribute_type => 1, + attribute_type => $attr_type, + attribute_type_form => 1, + edit_attribute_type => 1, can_be_set_to_nonrepeatable => $can_be_set_to_nonrepeatable, - can_be_set_to_unique => $can_be_set_to_unique, - confirm_op => 'cud-edit_attribute_type_confirmed', - categories => $patron_categories, + can_be_set_to_unique => $can_be_set_to_unique, + confirm_op => 'cud-edit_attribute_type_confirmed', + categories => $patron_categories, ); } @@ -256,6 +256,7 @@ sub patron_attribute_type_list { @classes = sort @classes; my @attributes_loop; + # FIXME This is not efficient and should be improved for my $class (@classes) { my @items; @@ -263,7 +264,7 @@ sub patron_attribute_type_list { next if $attr->class ne $class; push @items, $attr; } - my $av = Koha::AuthorisedValues->search({ category => 'PA_CLASS', authorised_value => $class }); + my $av = Koha::AuthorisedValues->search( { category => 'PA_CLASS', authorised_value => $class } ); my $lib = $av->count ? $av->next->lib : $class; push @attributes_loop, { class => $class, @@ -271,6 +272,6 @@ sub patron_attribute_type_list { lib => $lib, }; } - $template->param(available_attribute_types => \@attributes_loop); - $template->param(display_list => 1); + $template->param( available_attribute_types => \@attributes_loop ); + $template->param( display_list => 1 ); } diff --git a/admin/preferences.pl b/admin/preferences.pl index e3688874d7..a98867646b 100755 --- a/admin/preferences.pl +++ b/admin/preferences.pl @@ -19,13 +19,13 @@ use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Auth qw( get_template_and_user ); use C4::Context; -use C4::Koha qw( getallthemes ); -use C4::Languages qw( getTranslatedLanguages ); +use C4::Koha qw( getallthemes ); +use C4::Languages qw( getTranslatedLanguages ); use C4::ClassSource qw( GetClassSources GetClassSource ); -use C4::Output qw( output_html_with_http_headers output_and_exit_if_error ); +use C4::Output qw( output_html_with_http_headers output_and_exit_if_error ); use C4::Templates; use Koha::Acquisition::Currencies; use Koha::Database::Columns; @@ -45,18 +45,19 @@ sub GetTab { $local_currency = $active_currency->currency; } $tab_template->param( - local_currency => $local_currency, # currency code is used, because we do not know how a given currency is formatted. + local_currency => + $local_currency, # currency code is used, because we do not know how a given currency is formatted. ); - return YAML::XS::Load( Encode::encode_utf8($tab_template->output())); + return YAML::XS::Load( Encode::encode_utf8( $tab_template->output() ) ); } sub _get_chunk { my ( $value, %options ) = @_; - my $name = $options{'pref'}; + my $name = $options{'pref'}; my $chunk = { name => $name, value => $value, type => $options{'type'} || 'input', class => $options{'class'} }; - if( $options{'syntax'} ){ + if ( $options{'syntax'} ) { $chunk->{'syntax'} = $options{'syntax'}; } if ( $options{'type'} ) { @@ -64,7 +65,7 @@ sub _get_chunk { $chunk->{'source'} = $options{'source'}; $chunk->{'exclusions'} = $options{'exclusions'} // ""; $chunk->{'inclusions'} = $options{'inclusions'} // ""; - $chunk->{'required'} = $options{'required'} // ""; + $chunk->{'required'} = $options{'required'} // ""; $chunk->{'type'} = 'modalselect'; } elsif ( $options{'type'} eq 'modaljs' ) { $chunk->{'type'} = 'modaljs'; @@ -85,32 +86,36 @@ sub _get_chunk { my $theme; my $interface; if ( $options{'type'} eq 'opac-languages' ) { + # this is the OPAC $interface = 'opac'; $theme = C4::Context->preference('opacthemes'); } else { + # this is the staff interface $interface = 'intranet'; $theme = C4::Context->preference('template'); } $chunk->{'languages'} = getTranslatedLanguages( $interface, $theme ); - $chunk->{'type'} = 'languages'; - } elsif ( $options{ 'choices' } ) { + $chunk->{'type'} = 'languages'; + } elsif ( $options{'choices'} ) { my $add_blank; - if ( $options{'choices'} && ref( $options{ 'choices' } ) eq '' ) { + if ( $options{'choices'} && ref( $options{'choices'} ) eq '' ) { if ( $options{'choices'} eq 'class-sources' ) { my $sources = GetClassSources(); $options{'choices'} = { map { $_ => $sources->{$_}->{'description'} } keys %$sources }; } elsif ( $options{'choices'} eq 'opac-templates' ) { - $options{'choices'} = { map { $_ => $_ } getallthemes( 'opac' ) } + $options{'choices'} = { map { $_ => $_ } getallthemes('opac') }; } elsif ( $options{'choices'} eq 'staff-templates' ) { - $options{'choices'} = { map { $_ => $_ } getallthemes( 'intranet' ) } + $options{'choices'} = { map { $_ => $_ } getallthemes('intranet') }; } elsif ( $options{choices} eq 'patron-categories' ) { - $options{choices} = { map { $_->categorycode => $_->description } Koha::Patron::Categories->search->as_list }; + $options{choices} = + { map { $_->categorycode => $_->description } Koha::Patron::Categories->search->as_list }; $add_blank = 1; - } elsif ( $options{'choices'} eq 'authval' ){ - if( $options{'source'} ){ - $options{'choices'} = { map { $_->authorised_value => $_->lib } Koha::AuthorisedValues->search( { category => $options{'source'} } )->as_list }; + } elsif ( $options{'choices'} eq 'authval' ) { + if ( $options{'source'} ) { + $options{'choices'} = { map { $_->authorised_value => $_->lib } + Koha::AuthorisedValues->search( { category => $options{'source'} } )->as_list }; $add_blank = 1; } } else { @@ -126,17 +131,15 @@ sub _get_chunk { @values = split /,/, $value if defined($value); $chunk->{'CHOICES'} = [ sort { $a->{'text'} cmp $b->{'text'} } - map { + map { my $c = $_; { text => $options{'choices'}->{$c}, value => $c, - selected => ( - grep { $_ eq $c || ( $c eq '' && ($value eq '0' || !$value ) ) } @values - ) ? 1 : 0, + selected => ( grep { $_ eq $c || ( $c eq '' && ( $value eq '0' || !$value ) ) } @values ) ? 1 : 0, } - } - keys %{ $options{'choices'} } + } + keys %{ $options{'choices'} } ]; # Add a first blank value if needed @@ -147,39 +150,37 @@ sub _get_chunk { } elsif ( $options{'multiple'} ) { my @values; - @values = split /,/, $value if defined($value); + @values = split /,/, $value if defined($value); $chunk->{type} = 'multiple'; $chunk->{CHOICES} = [ sort { $a->{'text'} cmp $b->{'text'} } - map { + map { my $option_value = $_; { text => $options{multiple}->{$option_value}, value => $option_value, - selected => (grep { $_ eq $option_value } @values) ? 1 : 0, + selected => ( grep { $_ eq $option_value } @values ) ? 1 : 0, } - } - keys %{ $options{multiple} } + } + keys %{ $options{multiple} } ]; } elsif ( $options{'multiple_sortable'} ) { my @values; - @values = split /,/, $value if defined($value); - $chunk->{type} = 'multiple_sortable'; + @values = split /,/, $value if defined($value); + $chunk->{type} = 'multiple_sortable'; my @options = sort keys %{ $options{multiple_sortable} }; $chunk->{CHOICES} = [ - map { + map { my $option_value = $_; { text => $options{multiple_sortable}->{$option_value}, value => $option_value, - selected => (grep { $_ eq $option_value } @values) ? 1 : 0, + selected => ( grep { $_ eq $option_value } @values ) ? 1 : 0, } - } - uniq(@values, @options) + } uniq( @values, @options ) ]; } - $chunk->{ 'type_' . $chunk->{'type'} } = 1; return $chunk; @@ -189,36 +190,41 @@ sub TransformPrefsToHTML { my ( $data, $searchfield ) = @_; my @lines; - my $dbh = C4::Context->dbh; - my $title = ( keys( %$data ) )[0]; - my $tab = $data->{ $title }; - $tab = { '' => $tab } if ( ref( $tab ) eq 'ARRAY' ); + my $dbh = C4::Context->dbh; + my $title = ( keys(%$data) )[0]; + my $tab = $data->{$title}; + $tab = { '' => $tab } if ( ref($tab) eq 'ARRAY' ); my @override_syspref_names; - if ( exists($ENV{OVERRIDE_SYSPREF_NAMES}) && - defined($ENV{OVERRIDE_SYSPREF_NAMES}) - ) { + if ( exists( $ENV{OVERRIDE_SYSPREF_NAMES} ) + && defined( $ENV{OVERRIDE_SYSPREF_NAMES} ) ) + { @override_syspref_names = split /,/, $ENV{OVERRIDE_SYSPREF_NAMES}; } foreach my $group ( sort keys %$tab ) { - if ( $group ) { + if ($group) { push @lines, { is_group_title => 1, title => $group }; } - foreach my $line ( @{ $tab->{ $group } } ) { + foreach my $line ( @{ $tab->{$group} } ) { my @chunks; my @names; my @warnings; - foreach my $piece ( @$line ) { - if ( ref ( $piece ) eq 'HASH' ) { + foreach my $piece (@$line) { + if ( ref($piece) eq 'HASH' ) { my $name = $piece->{'pref'}; - if ( $name ) { - my $row = $dbh->selectrow_hashref( "SELECT value, type FROM systempreferences WHERE variable = ?", {}, $name ); + if ($name) { + my $row = $dbh->selectrow_hashref( + "SELECT value, type FROM systempreferences WHERE variable = ?", + {}, $name + ); my $value; - if ( ( !defined( $row ) || ( !defined( $row->{'value'} ) && $row->{'type'} ne 'YesNo' ) ) && defined( $piece->{'default'} ) ) { + if ( ( !defined($row) || ( !defined( $row->{'value'} ) && $row->{'type'} ne 'YesNo' ) ) + && defined( $piece->{'default'} ) ) + { $value = $piece->{'default'}; } else { $value = $row->{'value'}; @@ -228,14 +234,14 @@ sub TransformPrefsToHTML { # No highlighting of inputs yet, but would be useful $chunk->{'highlighted'} = 1 if ( $searchfield && $name =~ /^$searchfield$/i ); - if ( $name eq 'Pseudonymization' && ! C4::Context->config('bcrypt_settings')) { + if ( $name eq 'Pseudonymization' && !C4::Context->config('bcrypt_settings') ) { push @warnings, 'bcrypt_config_not_set'; - $chunk->{disabled} = 1 unless $value; # Let disable if enabled + $chunk->{disabled} = 1 unless $value; # Let disable if enabled } push @chunks, $chunk; my $name_entry = { name => $name }; - if ( $searchfield ) { + if ($searchfield) { if ( $name =~ /^$searchfield$/i ) { $name_entry->{'jumped'} = 1; } elsif ( $name =~ /$searchfield/i ) { @@ -249,7 +255,7 @@ sub TransformPrefsToHTML { push @chunks, $piece; } } else { - if ( $piece ) { + if ($piece) { my $version = Koha::version(); my ( $major, $minor, $maintenance, $development ) = split( '\.', $version ); if ( $minor % 2 ) { @@ -271,12 +277,13 @@ sub TransformPrefsToHTML { sub _get_pref_files { my ( $input, $open_files ) = @_; - my ( $htdocs, $theme, $lang, undef ) = C4::Templates::_get_template_file( 'admin/preferences/admin.pref', 'intranet', $input ); + my ( $htdocs, $theme, $lang, undef ) = + C4::Templates::_get_template_file( 'admin/preferences/admin.pref', 'intranet', $input ); my %results; - foreach my $file ( glob( "$htdocs/$theme/$lang/modules/admin/preferences/*.pref" ) ) { - my ( $tab ) = ( $file =~ /([a-z0-9_-]+)\.pref$/ ); + foreach my $file ( glob("$htdocs/$theme/$lang/modules/admin/preferences/*.pref") ) { + my ($tab) = ( $file =~ /([a-z0-9_-]+)\.pref$/ ); $results{$tab} = $open_files ? IO::File->new( $file, 'r' ) : ''; } @@ -288,16 +295,17 @@ sub SearchPrefs { my ( $input, $searchfield ) = @_; my @tabs; - my %tab_files = _get_pref_files( $input ); + my %tab_files = _get_pref_files($input); our @terms = split( /\s+/, $searchfield ); foreach my $tab_name ( sort keys %tab_files ) { + # FIXME Hum? # Force list context to remove 'uninitialized value in goto' warn coming from YAML::Syck; note that the other GetTab call is in list context too. The actual cause however is the null value for the pref OpacRenewalBranch in opac.pref my ($data) = GetTab( $input, $tab_name ); - my $title = ( keys( %$data ) )[0]; - my $tab = $data->{ $title }; - $tab = { '' => $tab } if ( ref( $tab ) eq 'ARRAY' ); + my $title = ( keys(%$data) )[0]; + my $tab = $data->{$title}; + $tab = { '' => $tab } if ( ref($tab) eq 'ARRAY' ); my $matched_groups; @@ -309,32 +317,34 @@ sub SearchPrefs { my @new_contents; - foreach my $line ( @$contents ) { + foreach my $line (@$contents) { my $matched; - foreach my $piece ( @$line ) { - if ( ref( $piece ) eq 'HASH' ) { - if ( !$piece->{'pref'} ){ + foreach my $piece (@$line) { + if ( ref($piece) eq 'HASH' ) { + if ( !$piece->{'pref'} ) { next; } - if ( matches( $piece->{'pref'}, \@terms) ) { + if ( matches( $piece->{'pref'}, \@terms ) ) { $matched = 1; - } elsif ( ref( $piece->{'choices'} ) eq 'HASH' && grep( { $_ && matches( $_, \@terms ) } values( %{ $piece->{'choices'} } ) ) ) { + } elsif ( ref( $piece->{'choices'} ) eq 'HASH' + && grep( { $_ && matches( $_, \@terms ) } values( %{ $piece->{'choices'} } ) ) ) + { $matched = 1; } } elsif ( matches( $piece, \@terms ) ) { $matched = 1; } - last if ( $matched ); + last if ($matched); } - push @new_contents, $line if ( $matched ); + push @new_contents, $line if ($matched); } - $matched_groups->{$group_title} = \@new_contents if ( @new_contents ); + $matched_groups->{$group_title} = \@new_contents if (@new_contents); } - if ( $matched_groups ) { + if ($matched_groups) { my ( $title, $LINES ) = TransformPrefsToHTML( { $title => $matched_groups }, $searchfield ); push @tabs, { tab => $tab, tab_title => $title, LINES => $LINES, tab_id => $tab_name }; @@ -346,14 +356,12 @@ sub SearchPrefs { sub matches { my ( $text, $terms ) = @_; - if ( $text ) { - return !grep( - { - my $re = eval{qr|$_|i}; + if ($text) { + return !grep( { + my $re = eval { qr|$_|i }; $re = qr|\Q$_\E| if $@; $text !~ m|$re|; - } @$terms - ) + } @$terms ); } } @@ -361,28 +369,29 @@ my $dbh = C4::Context->dbh; our $input = CGI->new; my ( $template, $borrowernumber, $cookie ) = get_template_and_user( - { template_name => "admin/preferences.tt", - query => $input, - type => "intranet", - flagsrequired => { parameters => 'manage_sysprefs' }, + { + template_name => "admin/preferences.tt", + query => $input, + type => "intranet", + flagsrequired => { parameters => 'manage_sysprefs' }, } ); -my $op = $input->param( 'op' ) || ''; -my $tab = $input->param( 'tab' ); -$tab ||= 'accounting'; # Ideally this should be "local-use" but preferences.pl - # does not presently support local use preferences +my $op = $input->param('op') || ''; +my $tab = $input->param('tab'); +$tab ||= 'accounting'; # Ideally this should be "local-use" but preferences.pl + # does not presently support local use preferences my $highlighted; if ( $op eq 'cud-save' ) { - output_and_exit_if_error($input, $cookie, $template, { check => 'csrf_token' }); + output_and_exit_if_error( $input, $cookie, $template, { check => 'csrf_token' } ); foreach my $param ( $input->param() ) { - my ( $pref ) = ( $param =~ /pref_(.*)/ ); + my ($pref) = ( $param =~ /pref_(.*)/ ); - next if ( !defined( $pref ) ); + next if ( !defined($pref) ); - my $value = join( ',', $input->param( $param ) ); + my $value = join( ',', $input->param($param) ); C4::Context->set_preference( $pref, $value ); } @@ -394,7 +403,7 @@ if ( $op eq 'cud-save' ) { my @TABS; if ( $op eq 'search' ) { - my $searchfield = $input->param( 'searchfield' ); + my $searchfield = $input->param('searchfield'); $searchfield =~ s/\p{IsC}//g; $searchfield =~ s/\s+/ /; @@ -405,14 +414,12 @@ if ( $op eq 'search' ) { @TABS = SearchPrefs( $input, $searchfield ); - foreach my $tabh ( @TABS ) { - $template->param( - $tabh->{'tab'} => 1 - ); + foreach my $tabh (@TABS) { + $template->param( $tabh->{'tab'} => 1 ); } - if ( @TABS ) { - $tab = ''; # No need to load a particular tab, as we found results + if (@TABS) { + $tab = ''; # No need to load a particular tab, as we found results $template->param( search_jumped => 1 ) if ( $TABS[0]->{'search_jumped'} ); } else { $template->param( @@ -421,18 +428,18 @@ if ( $op eq 'search' ) { } } -if ( $tab ) { +if ($tab) { my ( $tab_title, $LINES ) = TransformPrefsToHTML( GetTab( $input, $tab ), $highlighted ); push @TABS, { tab_title => $tab_title, LINES => $LINES, tab_id => $tab }; $template->param( $tab => 1, - tab => $tab, + tab => $tab, ); } $template->param( - TABS => \@TABS, + TABS => \@TABS, db_columns => Koha::Database::Columns->columns, ); diff --git a/admin/restrictions.pl b/admin/restrictions.pl index bfeb82c1f1..c1eea67307 100755 --- a/admin/restrictions.pl +++ b/admin/restrictions.pl @@ -19,37 +19,34 @@ use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use Try::Tiny qw( try catch ); -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use Koha::Patron::Restriction::Types; -my $input = CGI->new; -my $op = $input->param('op') // 'list'; -my $code = uc $input->param('code'); +my $input = CGI->new; +my $op = $input->param('op') // 'list'; +my $code = uc $input->param('code'); my @messages = (); my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "admin/restrictions.tt", - query => $input, - type => "intranet", - flagsrequired => { parameters => 'manage_patron_restrictions' }, - debug => 1, + template_name => "admin/restrictions.tt", + query => $input, + type => "intranet", + flagsrequired => { parameters => 'manage_patron_restrictions' }, + debug => 1, } ); -if ( $op eq 'add_form') { +if ( $op eq 'add_form' ) { + # Get all existing restrictions, so we can do client-side validation - $template->param( - existing => scalar Koha::Patron::Restriction::Types->search() - ); + $template->param( existing => scalar Koha::Patron::Restriction::Types->search() ); if ($code) { - $template->param( - restriction => scalar Koha::Patron::Restriction::Types->find($code) - ); + $template->param( restriction => scalar Koha::Patron::Restriction::Types->find($code) ); } } elsif ( $op eq 'cud-add_validate' ) { @@ -59,6 +56,7 @@ if ( $op eq 'add_form') { my $is_a_modif = $input->param("is_a_modif"); if ($is_a_modif) { + # Check whether another restriction already has this display text my $dupe = Koha::Patron::Restriction::Types->search( { @@ -67,9 +65,7 @@ if ( $op eq 'add_form') { } ); if ( $dupe->count ) { - push @messages, { - type => 'error', code => 'duplicate_display_text' - }; + push @messages, { type => 'error', code => 'duplicate_display_text' }; } else { my $restriction = Koha::Patron::Restriction::Types->find($code); $restriction->display_text($display_text); @@ -79,12 +75,11 @@ if ( $op eq 'add_form') { push @messages, { type => 'message', code => 'update_success' }; } } else { + # Check whether another restriction already has this code my $dupe = Koha::Patron::Restriction::Types->find($code); if ($dupe) { - push @messages, { - type => 'error', code => 'duplicate_code' - }; + push @messages, { type => 'error', code => 'duplicate_code' }; } else { my $restriction = Koha::Patron::Restriction::Type->new( { @@ -104,20 +99,16 @@ if ( $op eq 'add_form') { $restriction->make_default; $op = 'list'; } elsif ( $op eq 'delete_confirm' ) { - $template->param( - restriction => scalar Koha::Patron::Restriction::Types->find($code) - ); + $template->param( restriction => scalar Koha::Patron::Restriction::Types->find($code) ); } elsif ( $op eq 'cud-delete_confirmed' ) { try { Koha::Patron::Restriction::Types->find($code)->delete; push @messages, { type => 'message', code => 'delete_success' }; - } - catch { + } catch { if ( blessed $_ ) { if ( $_->isa('Koha::Exceptions::CannotDeleteDefault') ) { push @messages, { type => 'error', code => 'delete_default' }; - } - elsif ( $_->isa('Koha::Exceptions::CannotDeleteSystem') ) { + } elsif ( $_->isa('Koha::Exceptions::CannotDeleteSystem') ) { push @messages, { type => 'error', code => 'delete_system' }; } } @@ -134,7 +125,7 @@ if ( $op eq 'list' ) { my $restrictions = Koha::Patron::Restriction::Types->search(); $template->param( restrictions => $restrictions, - ) + ); } output_html_with_http_headers $input, $cookie, $template->output; diff --git a/admin/search_filters.pl b/admin/search_filters.pl index d49ca621fc..4d79466637 100755 --- a/admin/search_filters.pl +++ b/admin/search_filters.pl @@ -20,7 +20,7 @@ use Modern::Perl; use CGI; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use Koha::SearchFilters; @@ -29,21 +29,23 @@ use Try::Tiny qw( catch try); my $cgi = CGI->new; -my ($template, $borrowernumber, $cookie) = get_template_and_user({ - template_name => 'admin/search_filters.tt', - query => $cgi, - type => 'intranet', - flagsrequired => { parameters => 'manage_search_filters' }, -}); +my ( $template, $borrowernumber, $cookie ) = get_template_and_user( + { + template_name => 'admin/search_filters.tt', + query => $cgi, + type => 'intranet', + flagsrequired => { parameters => 'manage_search_filters' }, + } +); my $op = $cgi->param('op') || ''; -if ($op eq 'cud-del') { +if ( $op eq 'cud-del' ) { my $id = $cgi->param('id'); my $sf = Koha::SearchFilters->find($id); - $template->param(filter_not_found => 1) unless $sf; + $template->param( filter_not_found => 1 ) unless $sf; if ($sf) { - try{ + try { $sf->delete(); $template->param( filter_deleted => $sf->name ); } catch { diff --git a/admin/searchengine/elasticsearch/mappings.pl b/admin/searchengine/elasticsearch/mappings.pl index fe54c40479..64d151ef3f 100755 --- a/admin/searchengine/elasticsearch/mappings.pl +++ b/admin/searchengine/elasticsearch/mappings.pl @@ -18,9 +18,9 @@ use Modern::Perl; use CGI; use Scalar::Util qw( looks_like_number ); -use List::Util qw( first ); -use C4::Output qw( output_html_with_http_headers ); -use C4::Auth qw( get_template_and_user ); +use List::Util qw( first ); +use C4::Output qw( output_html_with_http_headers ); +use C4::Auth qw( get_template_and_user ); use C4::Log; use Koha::SearchEngine::Elasticsearch; @@ -30,57 +30,56 @@ use Koha::SearchFields; use Koha::Caches; use Koha::AuthorisedValues; -use Try::Tiny qw( catch try ); +use Try::Tiny qw( catch try ); use Module::Load::Conditional qw( can_load ); - my $input = CGI->new; my ( $template, $borrowernumber, $cookie ) = get_template_and_user( { - template_name => 'admin/searchengine/elasticsearch/mappings.tt', - query => $input, - type => 'intranet', - flagsrequired => { parameters => 'manage_search_engine_config' }, + template_name => 'admin/searchengine/elasticsearch/mappings.tt', + query => $input, + type => 'intranet', + flagsrequired => { parameters => 'manage_search_engine_config' }, } ); unless ( can_load( modules => { 'Koha::SearchEngine::Elasticsearch::Indexer' => undef } ) ) { - output_and_exit( $input, $cookie, $template, 'missing_es_modules'); + output_and_exit( $input, $cookie, $template, 'missing_es_modules' ); } - my $index = $input->param('index') || 'biblios'; my $op = $input->param('op') || 'list'; my ( @messages, @errors ); push @messages, { type => 'message', code => 'elasticsearch_disabled' } - if ( C4::Context->preference('SearchEngine') ne 'Elasticsearch' ); + if ( C4::Context->preference('SearchEngine') ne 'Elasticsearch' ); my $database = Koha::Database->new(); my $schema = $database->schema; my $marc_type = lc C4::Context->preference('marcflavour'); -my @index_names = ($Koha::SearchEngine::Elasticsearch::BIBLIOS_INDEX, $Koha::SearchEngine::Elasticsearch::AUTHORITIES_INDEX); +my @index_names = + ( $Koha::SearchEngine::Elasticsearch::BIBLIOS_INDEX, $Koha::SearchEngine::Elasticsearch::AUTHORITIES_INDEX ); my $update_mappings = sub { for my $index_name (@index_names) { - my $indexer = Koha::SearchEngine::Elasticsearch::Indexer->new({ index => $index_name }); + my $indexer = Koha::SearchEngine::Elasticsearch::Indexer->new( { index => $index_name } ); try { $indexer->update_mappings(); } catch { my $conf = $indexer->get_elasticsearch_params(); push @errors, { - type => 'error', - code => 'error_on_update_es_mappings', + type => 'error', + code => 'error_on_update_es_mappings', message => $_[0], - index => $conf->{index_name}, + index => $conf->{index_name}, }; }; } }; my $search_fields_aliases = {}; -while ( my ( $key, $value ) = each(%{Koha::SearchEngine::Elasticsearch::QueryBuilder->get_index_field_convert}) ) { +while ( my ( $key, $value ) = each( %{ Koha::SearchEngine::Elasticsearch::QueryBuilder->get_index_field_convert } ) ) { my $field_aliases = $search_fields_aliases->{$value}; $field_aliases = [] unless $field_aliases; push @$field_aliases, $key; @@ -205,33 +204,30 @@ if ( $op eq 'cud-edit' ) { $update_mappings->(); } -} -elsif( $op eq 'cud-reset_confirmed' ) { +} elsif ( $op eq 'cud-reset_confirmed' ) { Koha::SearchEngine::Elasticsearch->reset_elasticsearch_mappings; push @messages, { type => 'message', code => 'success_on_reset' }; C4::Log::logaction( 'SEARCHENGINE', 'RESET_MAPPINGS', undef, q{} ); -} -elsif( $op eq 'reset_confirm' ) { +} elsif ( $op eq 'reset_confirm' ) { $template->param( reset_confirm => 1 ); } my @indexes; for my $index_name (@index_names) { - my $indexer = Koha::SearchEngine::Elasticsearch::Indexer->new({ index => $index_name }); - if (!$indexer->is_index_status_ok) { + my $indexer = Koha::SearchEngine::Elasticsearch::Indexer->new( { index => $index_name } ); + if ( !$indexer->is_index_status_ok ) { my $conf = $indexer->get_elasticsearch_params(); - if ($indexer->is_index_status_reindex_required) { + if ( $indexer->is_index_status_reindex_required ) { push @errors, { - type => 'error', - code => 'reindex_required', + type => 'error', + code => 'reindex_required', index => $conf->{index_name}, }; - } - elsif($indexer->is_index_status_recreate_required) { + } elsif ( $indexer->is_index_status_recreate_required ) { push @errors, { - type => 'error', - code => 'recreate_required', + type => 'error', + code => 'recreate_required', index => $conf->{index_name}, }; } @@ -273,17 +269,17 @@ for my $index_name (@index_names) { while ( my $s = $search_fields->next ) { my $name = $s->name; push @mappings, { - search_field_name => $name, - search_field_label => $s->label, - search_field_type => $s->type, - search_field_mandatory => $s->mandatory, - marc_field => $s->get_column('marc_field'), - sort => $s->get_column('sort') // 'undef', # To avoid warnings "Use of uninitialized value in lc" - suggestible => $s->get_column('suggestible'), - search => $s->get_column('search'), - filter => $s->get_column('filter'), - facet => $s->get_column('facet'), - is_facetable => ( grep { $_ eq $name } @facetable_field_names ) ? 1 : 0, + search_field_name => $name, + search_field_label => $s->label, + search_field_type => $s->type, + search_field_mandatory => $s->mandatory, + marc_field => $s->get_column('marc_field'), + sort => $s->get_column('sort') // 'undef', # To avoid warnings "Use of uninitialized value in lc" + suggestible => $s->get_column('suggestible'), + search => $s->get_column('search'), + filter => $s->get_column('filter'), + facet => $s->get_column('facet'), + is_facetable => ( grep { $_ eq $name } @facetable_field_names ) ? 1 : 0, }; } @@ -295,8 +291,8 @@ my @all_search_fields; while ( my $search_field = $search_fields->next ) { my $search_field_unblessed = $search_field->unblessed; $search_field_unblessed->{mapped_biblios} = 1 if $search_field->is_mapped_biblios; - $search_field_unblessed->{is_mapped} = $search_field->is_mapped; - $search_field_unblessed->{aliases} = $search_fields_aliases->{$search_field_unblessed->{name}}; + $search_field_unblessed->{is_mapped} = $search_field->is_mapped; + $search_field_unblessed->{aliases} = $search_fields_aliases->{ $search_field_unblessed->{name} }; push @all_search_fields, $search_field_unblessed; } diff --git a/admin/share_content.pl b/admin/share_content.pl index e1f927ae38..fb08342efa 100755 --- a/admin/share_content.pl +++ b/admin/share_content.pl @@ -17,11 +17,11 @@ use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use JSON qw( to_json ); use HTTP::Request; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use Koha::SharedContent; @@ -29,48 +29,53 @@ use Koha::SharedContent; my $query = CGI->new; my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "admin/share_content.tt", - query => $query, - type => "intranet", - flagsrequired => { parameters => 'manage_mana' }, + template_name => "admin/share_content.tt", + query => $query, + type => "intranet", + flagsrequired => { parameters => 'manage_mana' }, } ); -my $op = $query->param('op') || q{}; +my $op = $query->param('op') || q{}; my $mana_base = C4::Context->config('mana_config') || ''; + # Check the mana server actually exists at the other end my $bad_url; if ($mana_base) { my $request = HTTP::Request->new( GET => $mana_base ); - my $result = Koha::SharedContent::process_request($request); - $bad_url = 1 unless (exists($result->{version})); + my $result = Koha::SharedContent::process_request($request); + $bad_url = 1 unless ( exists( $result->{version} ) ); } if ( $op eq 'cud-save' ) { my $auto_share = $query->param('autosharewithmana') || q{}; - my $mana = $query->param('mana'); + my $mana = $query->param('mana'); - C4::Context->set_preference('Mana', $mana); + C4::Context->set_preference( 'Mana', $mana ); if ( $auto_share ne '' ) { - C4::Context->set_preference('AutoShareWithMana', 'subscription'); + C4::Context->set_preference( 'AutoShareWithMana', 'subscription' ); } else { - C4::Context->set_preference('AutoShareWithMana', ''); + C4::Context->set_preference( 'AutoShareWithMana', '' ); } } if ( $op eq 'cud-reset' ) { - C4::Context->set_preference('ManaToken', ''); + C4::Context->set_preference( 'ManaToken', '' ); } if ( $op eq 'cud-send' && not $bad_url ) { - my $name = $query->param('name'); + my $name = $query->param('name'); my $email = $query->param('email'); - my $content = to_json({name => $name, - email => $email}); + my $content = to_json( + { + name => $name, + email => $email + } + ); - my $url = "$mana_base/getsecuritytoken"; + my $url = "$mana_base/getsecuritytoken"; my $request = HTTP::Request->new( POST => $url ); $request->content($content); my $result = Koha::SharedContent::process_request($request); @@ -78,14 +83,13 @@ if ( $op eq 'cud-send' && not $bad_url ) { $template->param( result => $result ); if ( $result->{code} eq '201' && $result->{token} ) { - C4::Context->set_preference('ManaToken', $result->{token}); + C4::Context->set_preference( 'ManaToken', $result->{token} ); } } - $template->param( - mana_url => $mana_base, - bad_url => $bad_url, + mana_url => $mana_base, + bad_url => $bad_url, ); output_html_with_http_headers $query, $cookie, $template->output; diff --git a/admin/smart-rules.pl b/admin/smart-rules.pl index c5244636c1..f0f358ccb1 100755 --- a/admin/smart-rules.pl +++ b/admin/smart-rules.pl @@ -21,7 +21,7 @@ use Modern::Perl; use CGI qw ( -utf8 ); use C4::Context; use C4::Output qw( output_html_with_http_headers ); -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use Koha::Exception; use Koha::Database; use Koha::Logger; @@ -32,42 +32,44 @@ use Koha::Caches; use Koha::Patrons; my $input = CGI->new; -my $dbh = C4::Context->dbh; +my $dbh = C4::Context->dbh; # my $flagsrequired; # $flagsrequired->{circulation}=1; -my ($template, $loggedinuser, $cookie) - = get_template_and_user({template_name => "admin/smart-rules.tt", - query => $input, - type => "intranet", - flagsrequired => {parameters => 'manage_circ_rules'}, - }); +my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "admin/smart-rules.tt", + query => $input, + type => "intranet", + flagsrequired => { parameters => 'manage_circ_rules' }, + } +); -my $type=$input->param('type'); +my $type = $input->param('type'); my $branch = $input->param('branch'); -unless ( $branch ) { +unless ($branch) { if ( C4::Context->preference('DefaultToLoggedInLibraryCircRules') ) { $branch = Koha::Libraries->search->count() == 1 ? undef : C4::Context::mybranch(); - } - else { + } else { $branch = C4::Context::only_my_library() ? ( C4::Context::mybranch() || '*' ) : '*'; } } -my $logged_in_patron = Koha::Patrons->find( $loggedinuser ); +my $logged_in_patron = Koha::Patrons->find($loggedinuser); -my $can_edit_from_any_library = $logged_in_patron->has_permission( {parameters => 'manage_circ_rules_from_any_libraries' } ); +my $can_edit_from_any_library = + $logged_in_patron->has_permission( { parameters => 'manage_circ_rules_from_any_libraries' } ); $template->param( restricted_to_own_library => not $can_edit_from_any_library ); $branch = C4::Context::mybranch() unless $can_edit_from_any_library; -my $op = $input->param('op') || q{}; +my $op = $input->param('op') || q{}; my $language = C4::Languages::getlanguage(); my $cache = Koha::Caches->get_instance; -$cache->clear_from_cache( Koha::CirculationRules::GUESSED_ITEMTYPES_KEY ); +$cache->clear_from_cache(Koha::CirculationRules::GUESSED_ITEMTYPES_KEY); -if ($op eq 'cud-delete') { +if ( $op eq 'cud-delete' ) { my $itemtype = $input->param('itemtype'); my $categorycode = $input->param('categorycode'); @@ -121,19 +123,18 @@ if ($op eq 'cud-delete') { } } ); -} -elsif ($op eq 'cud-delete-branch-cat') { - my $categorycode = $input->param('categorycode'); - if ($branch eq "*") { - if ($categorycode eq "*") { +} elsif ( $op eq 'cud-delete-branch-cat' ) { + my $categorycode = $input->param('categorycode'); + if ( $branch eq "*" ) { + if ( $categorycode eq "*" ) { Koha::CirculationRules->set_rules( { branchcode => undef, categorycode => undef, rules => { - max_holds => undef, - patron_maxissueqty => undef, - patron_maxonsiteissueqty => undef, + max_holds => undef, + patron_maxissueqty => undef, + patron_maxonsiteissueqty => undef, } } ); @@ -163,7 +164,7 @@ elsif ($op eq 'cud-delete-branch-cat') { } ); } - } elsif ($categorycode eq "*") { + } elsif ( $categorycode eq "*" ) { Koha::CirculationRules->set_rules( { branchcode => $branch, @@ -194,18 +195,17 @@ elsif ($op eq 'cud-delete-branch-cat') { categorycode => $categorycode, branchcode => $branch, rules => { - max_holds => undef, + max_holds => undef, patron_maxissueqty => undef, patron_maxonsiteissueqty => undef, } } ); } -} -elsif ($op eq 'cud-delete-branch-item') { - my $itemtype = $input->param('itemtype'); - if ($branch eq "*") { - if ($itemtype eq "*") { +} elsif ( $op eq 'cud-delete-branch-item' ) { + my $itemtype = $input->param('itemtype'); + if ( $branch eq "*" ) { + if ( $itemtype eq "*" ) { Koha::CirculationRules->set_rules( { branchcode => undef, @@ -234,7 +234,7 @@ elsif ($op eq 'cud-delete-branch-item') { } ); } - } elsif ($itemtype eq "*") { + } elsif ( $itemtype eq "*" ) { Koha::CirculationRules->set_rules( { branchcode => $branch, @@ -264,6 +264,7 @@ elsif ($op eq 'cud-delete-branch-item') { ); } } + # save the values entered elsif ( $op eq 'cud-add' ) { my $br = $branch; # branch @@ -286,7 +287,7 @@ elsif ( $op eq 'cud-add' ) { my $renewalperiod = $input->param('renewalperiod'); my $norenewalbefore = $input->param('norenewalbefore'); $norenewalbefore = q{} if $norenewalbefore =~ /^\s*$/; - my $noautorenewalbefore = $input->param('noautorenewalbefore'); + my $noautorenewalbefore = $input->param('noautorenewalbefore'); my $auto_renew = $input->param('auto_renew') eq 'yes' ? 1 : 0; my $no_auto_renewal_after = $input->param('no_auto_renewal_after'); $no_auto_renewal_after = q{} if $no_auto_renewal_after =~ /^\s*$/; @@ -370,8 +371,7 @@ elsif ( $op eq 'cud-add' ) { } ); -} -elsif ($op eq "cud-set-branch-defaults") { +} elsif ( $op eq "cud-set-branch-defaults" ) { my $categorycode = $input->param('categorycode'); my $patron_maxissueqty = strip_non_numeric( scalar $input->param('patron_maxissueqty') ); my $patron_maxonsiteissueqty = $input->param('patron_maxonsiteissueqty'); @@ -383,7 +383,7 @@ elsif ($op eq "cud-set-branch-defaults") { my $returnbranch = $input->param('returnbranch'); my $max_holds = strip_non_numeric( scalar $input->param('max_holds') ); - if ($branch eq "*") { + if ( $branch eq "*" ) { Koha::CirculationRules->set_rules( { itemtype => undef, @@ -402,8 +402,8 @@ elsif ($op eq "cud-set-branch-defaults") { categorycode => undef, branchcode => undef, rules => { - patron_maxissueqty => $patron_maxissueqty, - patron_maxonsiteissueqty => $patron_maxonsiteissueqty, + patron_maxissueqty => $patron_maxissueqty, + patron_maxonsiteissueqty => $patron_maxonsiteissueqty, } } ); @@ -426,8 +426,8 @@ elsif ($op eq "cud-set-branch-defaults") { categorycode => undef, branchcode => $branch, rules => { - patron_maxissueqty => $patron_maxissueqty, - patron_maxonsiteissueqty => $patron_maxonsiteissueqty, + patron_maxissueqty => $patron_maxissueqty, + patron_maxonsiteissueqty => $patron_maxonsiteissueqty, } } ); @@ -440,23 +440,22 @@ elsif ($op eq "cud-set-branch-defaults") { rule_value => $max_holds, } ); -} -elsif ($op eq "cud-add-branch-cat") { - my $categorycode = $input->param('categorycode'); - my $patron_maxissueqty = strip_non_numeric( scalar $input->param('patron_maxissueqty') ); +} elsif ( $op eq "cud-add-branch-cat" ) { + my $categorycode = $input->param('categorycode'); + my $patron_maxissueqty = strip_non_numeric( scalar $input->param('patron_maxissueqty') ); my $patron_maxonsiteissueqty = $input->param('patron_maxonsiteissueqty'); $patron_maxonsiteissueqty = strip_non_numeric($patron_maxonsiteissueqty); my $max_holds = $input->param('max_holds'); $max_holds = strip_non_numeric($max_holds); - if ($branch eq "*") { - if ($categorycode eq "*") { + if ( $branch eq "*" ) { + if ( $categorycode eq "*" ) { Koha::CirculationRules->set_rules( { categorycode => undef, branchcode => undef, rules => { - max_holds => $max_holds, + max_holds => $max_holds, patron_maxissueqty => $patron_maxissueqty, patron_maxonsiteissueqty => $patron_maxonsiteissueqty, } @@ -468,20 +467,20 @@ elsif ($op eq "cud-add-branch-cat") { categorycode => $categorycode, branchcode => undef, rules => { - max_holds => $max_holds, + max_holds => $max_holds, patron_maxissueqty => $patron_maxissueqty, patron_maxonsiteissueqty => $patron_maxonsiteissueqty, } } ); } - } elsif ($categorycode eq "*") { + } elsif ( $categorycode eq "*" ) { Koha::CirculationRules->set_rules( { categorycode => undef, branchcode => $branch, rules => { - max_holds => $max_holds, + max_holds => $max_holds, patron_maxissueqty => $patron_maxissueqty, patron_maxonsiteissueqty => $patron_maxonsiteissueqty, } @@ -493,33 +492,34 @@ elsif ($op eq "cud-add-branch-cat") { categorycode => $categorycode, branchcode => $branch, rules => { - max_holds => $max_holds, + max_holds => $max_holds, patron_maxissueqty => $patron_maxissueqty, patron_maxonsiteissueqty => $patron_maxonsiteissueqty, } } ); } -} -elsif ( $op eq "cud-add-open-article-requests-limit" ) { +} elsif ( $op eq "cud-add-open-article-requests-limit" ) { my $categorycode = $input->param('categorycode'); my $open_article_requests_limit = strip_non_numeric( scalar $input->param('open_article_requests_limit') ); Koha::Exception->throw("No value passed for article request limit") - if not defined $open_article_requests_limit # There is a JS check for that - || $open_article_requests_limit eq q{}; + if not defined $open_article_requests_limit # There is a JS check for that + || $open_article_requests_limit eq q{}; if ( $branch eq "*" ) { if ( $categorycode eq "*" ) { Koha::CirculationRules->set_rules( - { categorycode => undef, + { + categorycode => undef, branchcode => undef, rules => { open_article_requests_limit => $open_article_requests_limit, } } ); } else { Koha::CirculationRules->set_rules( - { categorycode => $categorycode, + { + categorycode => $categorycode, branchcode => undef, rules => { open_article_requests_limit => $open_article_requests_limit, } } @@ -527,14 +527,16 @@ elsif ( $op eq "cud-add-open-article-requests-limit" ) { } } elsif ( $categorycode eq "*" ) { Koha::CirculationRules->set_rules( - { categorycode => undef, + { + categorycode => undef, branchcode => $branch, rules => { open_article_requests_limit => $open_article_requests_limit, } } ); } else { Koha::CirculationRules->set_rules( - { categorycode => $categorycode, + { + categorycode => $categorycode, branchcode => $branch, rules => { open_article_requests_limit => $open_article_requests_limit, } } @@ -545,14 +547,16 @@ elsif ( $op eq "cud-add-open-article-requests-limit" ) { if ( $branch eq "*" ) { if ( $categorycode eq "*" ) { Koha::CirculationRules->set_rules( - { branchcode => undef, + { + branchcode => undef, categorycode => undef, rules => { open_article_requests_limit => undef, } } ); } else { Koha::CirculationRules->set_rules( - { categorycode => $categorycode, + { + categorycode => $categorycode, branchcode => undef, rules => { open_article_requests_limit => undef, } } @@ -560,48 +564,50 @@ elsif ( $op eq "cud-add-open-article-requests-limit" ) { } } elsif ( $categorycode eq "*" ) { Koha::CirculationRules->set_rules( - { branchcode => $branch, + { + branchcode => $branch, categorycode => undef, rules => { open_article_requests_limit => undef, } } ); } else { Koha::CirculationRules->set_rules( - { categorycode => $categorycode, + { + categorycode => $categorycode, branchcode => $branch, rules => { open_article_requests_limit => undef, } } ); } -} -elsif ( $op eq "cud-set-article-request-fee" ) { +} elsif ( $op eq "cud-set-article-request-fee" ) { my $category = $input->param('article_request_fee_category'); my $fee = strip_non_numeric( scalar $input->param('article_request_fee') ); Koha::Exception->throw("No value passed for article request fee") - if not defined $fee # There is a JS check for that - || $fee eq q{}; + if not defined $fee # There is a JS check for that + || $fee eq q{}; Koha::CirculationRules->set_rules( - { categorycode => ( $category eq '*' ) ? undef : $category, - branchcode => ( $branch eq '*' ) ? undef : $branch, + { + categorycode => ( $category eq '*' ) ? undef : $category, + branchcode => ( $branch eq '*' ) ? undef : $branch, rules => { article_request_fee => $fee }, } ); } elsif ( $op eq 'cud-del-article-request-fee' ) { - my $category = $input->param('categorycode'); + my $category = $input->param('categorycode'); Koha::CirculationRules->set_rules( - { categorycode => ( $category eq '*' ) ? undef : $category, - branchcode => ( $branch eq '*' ) ? undef : $branch, + { + categorycode => ( $category eq '*' ) ? undef : $category, + branchcode => ( $branch eq '*' ) ? undef : $branch, rules => { article_request_fee => undef }, } ); -} -elsif ($op eq "cud-add-branch-item") { +} elsif ( $op eq "cud-add-branch-item" ) { my $itemtype = $input->param('itemtype'); my $holdallowed = $input->param('holdallowed'); my $hold_fulfillment_policy = $input->param('hold_fulfillment_policy'); @@ -609,8 +615,8 @@ elsif ($op eq "cud-add-branch-item") { my $bookings_trail_period = $input->param('bookings_trail_period'); my $returnbranch = $input->param('returnbranch'); - if ($branch eq "*") { - if ($itemtype eq "*") { + if ( $branch eq "*" ) { + if ( $itemtype eq "*" ) { Koha::CirculationRules->set_rules( { itemtype => undef, @@ -639,20 +645,20 @@ elsif ($op eq "cud-add-branch-item") { } ); } - } elsif ($itemtype eq "*") { - Koha::CirculationRules->set_rules( - { - itemtype => undef, - branchcode => $branch, - rules => { - holdallowed => $holdallowed, - hold_fulfillment_policy => $hold_fulfillment_policy, - bookings_lead_period => $bookings_lead_period, - bookings_trail_period => $bookings_trail_period, - returnbranch => $returnbranch, - } + } elsif ( $itemtype eq "*" ) { + Koha::CirculationRules->set_rules( + { + itemtype => undef, + branchcode => $branch, + rules => { + holdallowed => $holdallowed, + hold_fulfillment_policy => $hold_fulfillment_policy, + bookings_lead_period => $bookings_lead_period, + bookings_trail_period => $bookings_trail_period, + returnbranch => $returnbranch, } - ); + } + ); } else { Koha::CirculationRules->set_rules( { @@ -668,30 +674,26 @@ elsif ($op eq "cud-add-branch-item") { } ); } -} -elsif ( $op eq 'cud-mod-refund-lost-item-fee-rule' ) { +} elsif ( $op eq 'cud-mod-refund-lost-item-fee-rule' ) { my $lostreturn = $input->param('lostreturn'); if ( $lostreturn eq '*' ) { if ( $branch ne '*' ) { + # only do something for $lostreturn eq '*' if branch-specific Koha::CirculationRules->set_rules( { - branchcode => $branch, - rules => { - lostreturn => undef - } + branchcode => $branch, + rules => { lostreturn => undef } } ); } } else { Koha::CirculationRules->set_rules( { - branchcode => $branch, - rules => { - lostreturn => $lostreturn - } + branchcode => $branch, + rules => { lostreturn => $lostreturn } } ); } @@ -700,23 +702,20 @@ elsif ( $op eq 'cud-mod-refund-lost-item-fee-rule' ) { if ( $processingreturn eq '*' ) { if ( $branch ne '*' ) { + # only do something for $processingreturn eq '*' if branch-specific Koha::CirculationRules->set_rules( { - branchcode => $branch, - rules => { - processingreturn => undef - } + branchcode => $branch, + rules => { processingreturn => undef } } ); } } else { Koha::CirculationRules->set_rules( { - branchcode => $branch, - rules => { - processingreturn => $processingreturn - } + branchcode => $branch, + rules => { processingreturn => $processingreturn } } ); } @@ -724,18 +723,20 @@ elsif ( $op eq 'cud-mod-refund-lost-item-fee-rule' ) { my $category = $input->param('waiting_hold_cancellation_category'); my $itemtype = $input->param('waiting_hold_cancellation_itemtype'); - my $policy = strip_non_numeric( scalar $input->param('waiting_hold_cancellation_policy') ) - ? 1 - : 0; + my $policy = + strip_non_numeric( scalar $input->param('waiting_hold_cancellation_policy') ) + ? 1 + : 0; Koha::Exception->throw("No value passed for waiting holds cancellation policy") - if not defined $policy # There is a JS check for that - || $policy eq ''; + if not defined $policy # There is a JS check for that + || $policy eq ''; Koha::CirculationRules->set_rules( - { categorycode => ( $category eq '*' ) ? undef : $category, + { + categorycode => ( $category eq '*' ) ? undef : $category, itemtype => ( $itemtype eq '*' ) ? undef : $itemtype, - branchcode => ( $branch eq '*' ) ? undef : $branch, + branchcode => ( $branch eq '*' ) ? undef : $branch, rules => { waiting_hold_cancellation => $policy }, } ); @@ -746,27 +747,29 @@ elsif ( $op eq 'cud-mod-refund-lost-item-fee-rule' ) { my $itemtype = $input->param('itemtype'); Koha::CirculationRules->set_rules( - { categorycode => ( $category eq '*' ) ? undef : $category, + { + categorycode => ( $category eq '*' ) ? undef : $category, itemtype => ( $itemtype eq '*' ) ? undef : $itemtype, - branchcode => ( $branch eq '*' ) ? undef : $branch, + branchcode => ( $branch eq '*' ) ? undef : $branch, rules => { waiting_hold_cancellation => undef }, } ); } - -my $refundLostItemFeeRule = Koha::CirculationRules->find({ branchcode => ($branch eq '*') ? undef : $branch, rule_name => 'lostreturn' }); -my $defaultLostItemFeeRule = Koha::CirculationRules->find({ branchcode => undef, rule_name => 'lostreturn' }); -my $refundProcessingFeeRule = Koha::CirculationRules->find({ branchcode => ($branch eq '*') ? undef : $branch, rule_name => 'processingreturn' }); -my $defaultProcessingFeeRule = Koha::CirculationRules->find({ branchcode => undef, rule_name => 'processingreturn' }); +my $refundLostItemFeeRule = + Koha::CirculationRules->find( { branchcode => ( $branch eq '*' ) ? undef : $branch, rule_name => 'lostreturn' } ); +my $defaultLostItemFeeRule = Koha::CirculationRules->find( { branchcode => undef, rule_name => 'lostreturn' } ); +my $refundProcessingFeeRule = Koha::CirculationRules->find( + { branchcode => ( $branch eq '*' ) ? undef : $branch, rule_name => 'processingreturn' } ); +my $defaultProcessingFeeRule = Koha::CirculationRules->find( { branchcode => undef, rule_name => 'processingreturn' } ); $template->param( - refundLostItemFeeRule => $refundLostItemFeeRule, - defaultRefundRule => $defaultLostItemFeeRule ? $defaultLostItemFeeRule->rule_value : 'cud-refund', - refundProcessingFeeRule => $refundProcessingFeeRule, + refundLostItemFeeRule => $refundLostItemFeeRule, + defaultRefundRule => $defaultLostItemFeeRule ? $defaultLostItemFeeRule->rule_value : 'cud-refund', + refundProcessingFeeRule => $refundProcessingFeeRule, defaultProcessingRefundRule => $defaultProcessingFeeRule ? $defaultProcessingFeeRule->rule_value : 'cud-refund', ); -my $patron_categories = Koha::Patron::Categories->search({}, { order_by => ['description'] }); +my $patron_categories = Koha::Patron::Categories->search( {}, { order_by => ['description'] } ); my $itemtypes = Koha::ItemTypes->search_with_localization; @@ -779,7 +782,7 @@ my @used_itemtypes = Koha::CirculationRules->search( { branchcode => $humanbranch }, { columns => ['itemtype'], distinct => 1, } ) ->get_column('itemtype'); -my $all_rules = Koha::CirculationRules->search({ branchcode => $humanbranch }); +my $all_rules = Koha::CirculationRules->search( { branchcode => $humanbranch } ); my $definedbranch = $all_rules->count ? 1 : 0; my $rules = {}; @@ -788,7 +791,7 @@ while ( my $r = $all_rules->next ) { $rules->{ $r->{categorycode} // q{} }->{ $r->{itemtype} // q{} }->{ $r->{rule_name} } = $r->{rule_value}; } -$template->param(show_branch_cat_rule_form => 1); +$template->param( show_branch_cat_rule_form => 1 ); $template->param( used_categorycodes => \@used_categorycodes, @@ -807,16 +810,16 @@ exit 0; # sort by patron category, then item type, putting # default entries at the bottom sub by_category_and_itemtype { - unless (by_category($a, $b)) { - return by_itemtype($a, $b); + unless ( by_category( $a, $b ) ) { + return by_itemtype( $a, $b ); } } sub by_category { - my ($a, $b) = @_; - if ($a->{'default_humancategorycode'}) { - return ($b->{'default_humancategorycode'} ? 0 : 1); - } elsif ($b->{'default_humancategorycode'}) { + my ( $a, $b ) = @_; + if ( $a->{'default_humancategorycode'} ) { + return ( $b->{'default_humancategorycode'} ? 0 : 1 ); + } elsif ( $b->{'default_humancategorycode'} ) { return -1; } else { return $a->{'humancategorycode'} cmp $b->{'humancategorycode'}; @@ -824,10 +827,10 @@ sub by_category { } sub by_itemtype { - my ($a, $b) = @_; - if ($a->{default_translated_description}) { - return ($b->{'default_translated_description'} ? 0 : 1); - } elsif ($b->{'default_translated_description'}) { + my ( $a, $b ) = @_; + if ( $a->{default_translated_description} ) { + return ( $b->{'default_translated_description'} ? 0 : 1 ); + } elsif ( $b->{'default_translated_description'} ) { return -1; } else { return lc $a->{'translated_description'} cmp lc $b->{'translated_description'}; diff --git a/admin/sms_providers.pl b/admin/sms_providers.pl index 859712af46..86e3a6b425 100755 --- a/admin/sms_providers.pl +++ b/admin/sms_providers.pl @@ -22,7 +22,7 @@ use Modern::Perl; use CGI; use C4::Context; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use Koha::SMS::Provider; @@ -32,10 +32,10 @@ my $cgi = CGI->new; my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "admin/sms_providers.tt", - query => $cgi, - type => "intranet", - flagsrequired => { parameters => 'manage_sms_providers' }, + template_name => "admin/sms_providers.tt", + query => $cgi, + type => "intranet", + flagsrequired => { parameters => 'manage_sms_providers' }, } ); @@ -49,15 +49,12 @@ if ( $op eq 'cud-add_update' ) { if ($id) { my $provider = Koha::SMS::Providers->find($id); $provider->set( { name => $name, domain => $domain } )->store() - if $provider; - } - else { - Koha::SMS::Provider->new( { name => $name, domain => $domain } ) - ->store(); + if $provider; + } else { + Koha::SMS::Provider->new( { name => $name, domain => $domain } )->store(); } } -} -elsif ( $op eq 'cud-delete' ) { +} elsif ( $op eq 'cud-delete' ) { my $provider = Koha::SMS::Providers->find($id); $provider->delete() if $provider; } diff --git a/admin/smtp_servers.pl b/admin/smtp_servers.pl index 1171477fab..01702fd891 100755 --- a/admin/smtp_servers.pl +++ b/admin/smtp_servers.pl @@ -19,11 +19,11 @@ use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use Scalar::Util qw( blessed ); -use Try::Tiny qw( catch try ); +use Try::Tiny qw( catch try ); -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use Koha::Libraries; @@ -33,10 +33,11 @@ my $input = CGI->new; my $op = $input->param('op') || 'list'; my ( $template, $borrowernumber, $cookie ) = get_template_and_user( - { template_name => "admin/smtp_servers.tt", - query => $input, - type => "intranet", - flagsrequired => { parameters => 'manage_smtp_servers' }, + { + template_name => "admin/smtp_servers.tt", + query => $input, + type => "intranet", + flagsrequired => { parameters => 'manage_smtp_servers' }, } ); @@ -48,13 +49,13 @@ if ( $op eq 'cud-add' ) { my $name = $input->param('smtp_name'); my $host = $input->param('smtp_host'); - my $port = $input->param('smtp_port') || 25; + my $port = $input->param('smtp_port') || 25; my $timeout = $input->param('smtp_timeout') || 120; my $ssl_mode = $input->param('smtp_ssl_mode'); my $user_name = $input->param('smtp_user_name') || undef; - my $password = $input->param('smtp_password') || undef; + my $password = $input->param('smtp_password') || undef; my $debug = ( scalar $input->param('smtp_debug_mode') ) ? 1 : 0; - my $is_default = ( scalar $input->param('smtp_default') ) ? 1 : 0; + my $is_default = ( scalar $input->param('smtp_default') ) ? 1 : 0; try { @@ -73,44 +74,40 @@ if ( $op eq 'cud-add' ) { )->store; push @messages, { type => 'message', code => 'success_on_insert' }; - } - catch { + } catch { if ( blessed $_ and $_->isa('Koha::Exceptions::Object::DuplicateID') ) { push @messages, - { + { type => 'alert', code => 'error_on_insert', reason => 'duplicate_id' - }; + }; } }; # list servers after adding $op = 'list'; -} -elsif ( $op eq 'edit_form' ) { +} elsif ( $op eq 'edit_form' ) { my $smtp_server_id = $input->param('smtp_server_id'); my $smtp_server; $smtp_server = Koha::SMTP::Servers->find($smtp_server_id) unless !$smtp_server_id; - if ( $smtp_server ) { + if ($smtp_server) { $template->param( - smtp_server => $smtp_server, + smtp_server => $smtp_server, default_config => $smtp_servers->get_default, ); - } - else { + } else { push @messages, { - type => 'alert', - code => 'error_on_edit', - reason => 'invalid_id' + type => 'alert', + code => 'error_on_edit', + reason => 'invalid_id' }; } -} -elsif ( $op eq 'cud-edit_save' ) { +} elsif ( $op eq 'cud-edit_save' ) { my $smtp_server_id = $input->param('smtp_server_id'); my $smtp_server; @@ -118,23 +115,23 @@ elsif ( $op eq 'cud-edit_save' ) { $smtp_server = Koha::SMTP::Servers->find($smtp_server_id) unless !$smtp_server_id; - if ( $smtp_server ) { + if ($smtp_server) { my $name = $input->param('smtp_name'); my $host = $input->param('smtp_host'); - my $port = $input->param('smtp_port') || 25; + my $port = $input->param('smtp_port') || 25; my $timeout = $input->param('smtp_timeout') || 120; my $ssl_mode = $input->param('smtp_ssl_mode'); my $user_name = $input->param('smtp_user_name') || undef; - my $password = $input->param('smtp_password') || undef; + my $password = $input->param('smtp_password') || undef; my $debug = ( scalar $input->param('smtp_debug_mode') ) ? 1 : 0; - my $is_default = ( scalar $input->param('smtp_default') ) ? 1 : 0; + my $is_default = ( scalar $input->param('smtp_default') ) ? 1 : 0; try { - $smtp_server->password( $password ) + $smtp_server->password($password) if defined $password and $password ne '****' - or not defined $password; + or not defined $password; $smtp_server->set( { @@ -150,28 +147,26 @@ elsif ( $op eq 'cud-edit_save' ) { )->store; push @messages, - { + { type => 'message', code => 'success_on_update' - }; - } - catch { + }; + } catch { push @messages, - { - type => 'alert', - code => 'error_on_update' - }; + { + type => 'alert', + code => 'error_on_update' + }; }; # list servers after adding $op = 'list'; - } - else { + } else { push @messages, { - type => 'alert', - code => 'error_on_update', - reason => 'invalid_id' + type => 'alert', + code => 'error_on_update', + reason => 'invalid_id' }; } } diff --git a/admin/sru_modmapping.pl b/admin/sru_modmapping.pl index 67023772e3..a355757596 100755 --- a/admin/sru_modmapping.pl +++ b/admin/sru_modmapping.pl @@ -19,27 +19,29 @@ use Modern::Perl; use CGI; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); # Initialize CGI, template -my $input = CGI->new; -my $mapstr = $input->param('mapping')//''; -my $type = $input->param('type')//''; -my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => $type eq "authority" ? "admin/sru_modmapping_auth.tt" : "admin/sru_modmapping.tt", - query => $input, - type => "intranet", - flagsrequired => { parameters => 'manage_search_targets' }, -}); +my $input = CGI->new; +my $mapstr = $input->param('mapping') // ''; +my $type = $input->param('type') // ''; +my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => $type eq "authority" ? "admin/sru_modmapping_auth.tt" : "admin/sru_modmapping.tt", + query => $input, + type => "intranet", + flagsrequired => { parameters => 'manage_search_targets' }, + } +); # Main code: convert mapping string to hash structure and show template my %map; foreach my $singlemap ( split ',', $mapstr ) { my @temp = split '=', $singlemap, 2; - $map{ $temp[0] } = $temp[1] if @temp>1; + $map{ $temp[0] } = $temp[1] if @temp > 1; } $template->param( mapping => \%map ); output_html_with_http_headers $input, $cookie, $template->output; diff --git a/admin/systempreferences.pl b/admin/systempreferences.pl index 049bf79743..eadda9030a 100755 --- a/admin/systempreferences.pl +++ b/admin/systempreferences.pl @@ -42,49 +42,49 @@ ALSO : use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use MIME::Base64 qw( encode_base64 ); -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Context; -use C4::Koha qw( getallthemes ); -use C4::Languages qw( getTranslatedLanguages ); +use C4::Koha qw( getallthemes ); +use C4::Languages qw( getTranslatedLanguages ); use C4::ClassSource qw( GetClassSources GetClassSource ); -use C4::Output qw( output_html_with_http_headers output_and_exit_if_error ); +use C4::Output qw( output_html_with_http_headers output_and_exit_if_error ); use YAML::XS; -my %tabsysprefs; #we do no longer need to keep track of a tab per pref (yaml) +my %tabsysprefs; #we do no longer need to keep track of a tab per pref (yaml) sub StringSearch { my ( $searchstring, $tab ) = @_; - return (0,[]) if $tab ne 'local_use'; + return ( 0, [] ) if $tab ne 'local_use'; my $dbh = C4::Context->dbh; $searchstring =~ s/\'/\\\'/g; - my @data = split( ' ', $searchstring ); + my @data = split( ' ', $searchstring ); my $count = @data; my @results; my $cnt = 0; my $sth; my $strsth = "Select variable,value,explanation,type,options from systempreferences where variable in ("; - my $first = 1; + my $first = 1; my @sql_bind; for my $name ( get_local_prefs() ) { - $strsth .= ',' unless $first; - $strsth .= "?"; - push(@sql_bind,$name); - $first = 0; + $strsth .= ',' unless $first; + $strsth .= "?"; + push( @sql_bind, $name ); + $first = 0; } $strsth .= ") order by variable"; $sth = $dbh->prepare($strsth); $sth->execute(@sql_bind); while ( my $data = $sth->fetchrow_hashref ) { - unless (defined $data->{value}) { $data->{value} = "";} - $data->{shortvalue} = $data->{value}; - $data->{shortvalue} = substr( $data->{value}, 0, 60 ) . "..." if length( $data->{value} ) > 60; - push( @results, $data ); - $cnt++; + unless ( defined $data->{value} ) { $data->{value} = ""; } + $data->{shortvalue} = $data->{value}; + $data->{shortvalue} = substr( $data->{value}, 0, 60 ) . "..." if length( $data->{value} ) > 60; + push( @results, $data ); + $cnt++; } return ( $cnt, \@results ); @@ -106,7 +106,7 @@ sub GetPrefParams { $params->{'prefoptions'} = $data->{'options'}; if ( not defined( $data->{'type'} ) ) { - $params->{'type_free'} = 1; + $params->{'type_free'} = 1; $params->{'fieldlength'} = ( defined( $data->{'options'} ) and $data->{'options'} and $data->{'options'} > 0 ); } elsif ( $data->{'type'} eq 'cud-Upload' ) { $params->{'type_upload'} = 1; @@ -122,7 +122,10 @@ sub GetPrefParams { } } elsif ( $data->{'type'} eq 'Integer' || $data->{'type'} eq 'Float' ) { $params->{'type_free'} = 1; - $params->{'fieldlength'} = ( defined( $data->{'options'} ) and $data->{'options'} and $data->{'options'} > 0 ) ? $data->{'options'} : 10; + $params->{'fieldlength'} = + ( defined( $data->{'options'} ) and $data->{'options'} and $data->{'options'} > 0 ) + ? $data->{'options'} + : 10; } elsif ( $data->{'type'} eq 'Textarea' ) { $params->{'type_textarea'} = 1; $data->{options} =~ /(.*)\|(.*)/; @@ -192,7 +195,10 @@ sub GetPrefParams { $params->{'type_langselector'} = 1; } else { $params->{'type_free'} = 1; - $params->{'fieldlength'} = ( defined( $data->{'options'} ) and $data->{'options'} and $data->{'options'} > 0 ) ? $data->{'options'} : 30; + $params->{'fieldlength'} = + ( defined( $data->{'options'} ) and $data->{'options'} and $data->{'options'} > 0 ) + ? $data->{'options'} + : 30; } if ( $params->{'type_choice'} || $params->{'type_free'} || $params->{'type_yesno'} ) { @@ -212,14 +218,15 @@ my $offset = $input->param('offset') || 0; my $script_name = "/cgi-bin/koha/admin/systempreferences.pl"; my ( $template, $borrowernumber, $cookie ) = get_template_and_user( - { template_name => "admin/systempreferences.tt", - query => $input, - type => "intranet", - flagsrequired => { parameters => 'manage_sysprefs' }, + { + template_name => "admin/systempreferences.tt", + query => $input, + type => "intranet", + flagsrequired => { parameters => 'manage_sysprefs' }, } ); my $pagesize = 100; -my $op = $input->param('op') || ''; +my $op = $input->param('op') || ''; $searchfield =~ s/\,//g; if ($op) { @@ -229,7 +236,7 @@ if ($op) { } if ( $op eq 'update_and_reedit' ) { - output_and_exit_if_error($input, $cookie, $template, { check => 'csrf_token' }); + output_and_exit_if_error( $input, $cookie, $template, { check => 'csrf_token' } ); foreach ( $input->param ) { } my $value = ''; @@ -262,7 +269,7 @@ if ( $op eq 'update_and_reedit' ) { } } my $variable = $input->param('variable'); - C4::Context->set_preference($variable, $value); + C4::Context->set_preference( $variable, $value ); } ################## ADD_FORM ################################## @@ -274,7 +281,8 @@ if ( $op eq 'add_form' ) { my $data; if ($searchfield) { my $dbh = C4::Context->dbh; - my $sth = $dbh->prepare("select variable,value,explanation,type,options from systempreferences where variable=?"); + my $sth = + $dbh->prepare("select variable,value,explanation,type,options from systempreferences where variable=?"); $sth->execute($searchfield); $data = $sth->fetchrow_hashref; $template->param( modify => 1 ); @@ -285,13 +293,14 @@ if ( $op eq 'add_form' ) { $data->{'lang'} = $template->param('lang'); my $prefparams = GetPrefParams($data); - $template->param( %$prefparams ); + $template->param(%$prefparams); $template->param( searchfield => $searchfield ); ################## ADD_VALIDATE ################################## # called by add_form, used to insert/modify data in DB } elsif ( $op eq 'cud-add_validate' ) { - output_and_exit_if_error($input, $cookie, $template, { check => 'csrf_token' }); + output_and_exit_if_error( $input, $cookie, $template, { check => 'csrf_token' } ); + # to handle multiple values my $value; @@ -338,9 +347,10 @@ if ( $op eq 'add_form' ) { ################## DELETE_CONFIRMED ################################## # called by delete_confirm, used to effectively confirm deletion of data in DB } elsif ( $op eq 'cud-delete_confirmed' ) { - output_and_exit_if_error($input, $cookie, $template, { check => 'csrf_token' }); + output_and_exit_if_error( $input, $cookie, $template, { check => 'csrf_token' } ); C4::Context->delete_preference($searchfield); $template->param( delete_confirmed => 1 ); + # END $OP eq DELETE_CONFIRMED ################## DEFAULT ################################## } else { # DEFAULT @@ -352,7 +362,7 @@ if ( $op eq 'add_form' ) { for ( my $i = $offset ; $i < ( $offset + $pagesize < $count ? $offset + $pagesize : $count ) ; $i++ ) { my $row_data = $results->[$i]; $row_data->{'lang'} = $template->param('lang'); - $row_data = GetPrefParams($row_data); # get a fresh hash for the row data + $row_data = GetPrefParams($row_data); # get a fresh hash for the row data $row_data->{edit} = "$script_name?op=add_form&searchfield=" . $results->[$i]{'variable'}; $row_data->{delete} = "$script_name?op=delete_confirm&searchfield=" . $results->[$i]{'variable'}; push( @loop_data, $row_data ); @@ -370,24 +380,23 @@ if ( $op eq 'add_form' ) { } #---- END $OP eq DEFAULT output_html_with_http_headers $input, $cookie, $template->output; - # Return an array containing all preferences defined in current Koha instance # .pref files. sub get_prefs_from_files { - my $path_pref_en = C4::Context->config('intrahtdocs') . - '/prog/en/modules/admin/preferences'; + my $path_pref_en = C4::Context->config('intrahtdocs') . '/prog/en/modules/admin/preferences'; + # Get all .pref file names - opendir ( my $fh, $path_pref_en ); + opendir( my $fh, $path_pref_en ); my @pref_files = grep { /.pref$/ } readdir($fh); close $fh; - my @names = (); + my @names = (); my $append = sub { my $prefs = shift; - for my $pref ( @$prefs ) { - for my $element ( @$pref ) { - if ( ref( $element) eq 'HASH' ) { + for my $pref (@$prefs) { + for my $element (@$pref) { + if ( ref($element) eq 'HASH' ) { my $name = $element->{pref}; next unless $name; push @names, $name; @@ -397,7 +406,7 @@ sub get_prefs_from_files { } }; for my $file (@pref_files) { - my $pref = YAML::XS::LoadFile( "$path_pref_en/$file" ); + my $pref = YAML::XS::LoadFile("$path_pref_en/$file"); for my $tab ( keys %$pref ) { my $content = $pref->{$tab}; if ( ref($content) eq 'ARRAY' ) { @@ -413,7 +422,6 @@ sub get_prefs_from_files { return @names; } - # Return an array containg all preferences defined in DB sub get_prefs_from_db { @@ -421,24 +429,23 @@ sub get_prefs_from_db { my $sth = $dbh->prepare("SELECT variable FROM systempreferences"); $sth->execute; my @names = (); - while ( (my $name) = $sth->fetchrow_array ) { + while ( ( my $name ) = $sth->fetchrow_array ) { push @names, $name if $name; } return @names; } - # Return an array containing all local preferences: those which are defined in # DB and not defined in Koha .pref files. sub get_local_prefs { my @prefs_file = get_prefs_from_files(); - my @prefs_db = get_prefs_from_db(); + my @prefs_db = get_prefs_from_db(); my %prefs_file = map { lc $_ => 1 } @prefs_file; - my @names = (); + my @names = (); foreach my $name (@prefs_db) { - push @names, $name unless $prefs_file{lc $name}; + push @names, $name unless $prefs_file{ lc $name }; } return @names; diff --git a/admin/transfer_limits.pl b/admin/transfer_limits.pl index dfa7f6309c..0729b4e3ec 100755 --- a/admin/transfer_limits.pl +++ b/admin/transfer_limits.pl @@ -19,8 +19,8 @@ use Modern::Perl; -use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); my $input = CGI->new; diff --git a/admin/transport-cost-matrix.pl b/admin/transport-cost-matrix.pl index 1930e45a26..e56155eb84 100755 --- a/admin/transport-cost-matrix.pl +++ b/admin/transport-cost-matrix.pl @@ -20,50 +20,52 @@ use Modern::Perl; use CGI qw ( -utf8 ); use C4::Context; -use C4::Output qw( output_html_with_http_headers ); -use C4::Auth qw( get_template_and_user ); +use C4::Output qw( output_html_with_http_headers ); +use C4::Auth qw( get_template_and_user ); use C4::HoldsQueue qw( TransportCostMatrix UpdateTransportCostMatrix ); use Koha::Libraries; - my $input = CGI->new; -my ($template, $loggedinuser, $cookie) - = get_template_and_user({template_name => "admin/transport-cost-matrix.tt", - query => $input, - type => "intranet", - flagsrequired => { parameters => 'manage_transfers' }, - }); +my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "admin/transport-cost-matrix.tt", + query => $input, + type => "intranet", + flagsrequired => { parameters => 'manage_transfers' }, + } +); my $use_transport_cost_matrix = C4::Context->preference("UseTransportCostMatrix"); my $update = ( $input->param('op') // '' ) eq 'cud-set-cost-matrix'; -my ($cost_matrix, $have_matrix); +my ( $cost_matrix, $have_matrix ); unless ($update) { $cost_matrix = TransportCostMatrix(); $have_matrix = keys %$cost_matrix if $cost_matrix; } -my @branchloop = map { code => $_->branchcode, name => $_->branchname }, Koha::Libraries->search({}, { order_by => 'branchname' })->as_list; -my (@branchfromloop, @errors); -foreach my $branchfrom ( @branchloop ) { +my @branchloop = map { code => $_->branchcode, name => $_->branchname }, + Koha::Libraries->search( {}, { order_by => 'branchname' } )->as_list; +my ( @branchfromloop, @errors ); +foreach my $branchfrom (@branchloop) { my $fromcode = $branchfrom->{code}; my %from_row = ( code => $fromcode, name => $branchfrom->{name} ); - foreach my $branchto ( @branchloop ) { + foreach my $branchto (@branchloop) { my $tocode = $branchto->{code}; my %from_to_input_def = ( code => $tocode, name => $branchto->{name} ); push @{ $from_row{branchtoloop} }, \%from_to_input_def; - if ($fromcode eq $tocode) { + if ( $fromcode eq $tocode ) { $from_to_input_def{skip} = 1; next; } - (my $from_to = "${fromcode}_${tocode}") =~ s/\W//go; - $from_to_input_def{id} = $from_to; + ( my $from_to = "${fromcode}_${tocode}" ) =~ s/\W//go; + $from_to_input_def{id} = $from_to; my $input_name = "cost_$from_to"; my $disable_name = "disable_$from_to"; @@ -71,48 +73,50 @@ foreach my $branchfrom ( @branchloop ) { my $value = $from_to_input_def{value} = $input->param($input_name); if ( $input->param($disable_name) ) { $from_to_input_def{disabled} = 1; - } - else { + } else { push @errors, "$from_row{name} -> $from_to_input_def{name}" - unless $value =~ /\d/o && $value >= 0.0; + unless $value =~ /\d/o && $value >= 0.0; } - } - else { + } else { if ($have_matrix) { if ( my $cell = $cost_matrix->{$tocode}{$fromcode} ) { - $from_to_input_def{value} = $cell->{cost}; + $from_to_input_def{value} = $cell->{cost}; $from_to_input_def{disabled} = 1 if $cell->{disable_transfer}; } else { + # matrix has been previously initialized, but a branch referenced here was created afterward. $from_to_input_def{disabled} = 1; } } else { + # First time initializing the matrix $from_to_input_def{disabled} = 1; } } } -# die Dumper(\%from_row); + # die Dumper(\%from_row); push @branchfromloop, \%from_row; } -if ($update && !@errors) { +if ( $update && !@errors ) { my @update_recs = map { my $from = $_->{code}; - map { frombranch => $from, tobranch => $_->{code}, cost => $_->{value}, disable_transfer => $_->{disabled} || 0 }, - grep { $_->{code} ne $from } - @{ $_->{branchtoloop} }; + map { + frombranch => $from, tobranch => $_->{code}, cost => $_->{value}, disable_transfer => $_->{disabled} + || 0 + }, + grep { $_->{code} ne $from } @{ $_->{branchtoloop} }; } @branchfromloop; - UpdateTransportCostMatrix(\@update_recs); + UpdateTransportCostMatrix( \@update_recs ); } $template->param( - branchloop => \@branchloop, - branchfromloop => \@branchfromloop, + branchloop => \@branchloop, + branchfromloop => \@branchfromloop, WARNING_transport_cost_matrix_off => !$use_transport_cost_matrix, - errors => \@errors, + errors => \@errors, ); output_html_with_http_headers $input, $cookie, $template->output; diff --git a/admin/usage_statistics.pl b/admin/usage_statistics.pl index 5288d6327d..afac8ae99a 100755 --- a/admin/usage_statistics.pl +++ b/admin/usage_statistics.pl @@ -17,50 +17,51 @@ use Modern::Perl; -use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); -use C4::Output qw( output_html_with_http_headers ); +use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); +use C4::Output qw( output_html_with_http_headers ); use Koha::DateUtils qw( output_pref ); use Koha::Libraries; my $query = CGI->new; my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "admin/usage_statistics.tt", - query => $query, - type => "intranet", - flagsrequired => { parameters => 'manage_usage_stats' }, + template_name => "admin/usage_statistics.tt", + query => $query, + type => "intranet", + flagsrequired => { parameters => 'manage_usage_stats' }, } ); my $op = $query->param('op') || q||; if ( $op eq 'cud-update' ) { - my $UsageStats = $query->param('UsageStats'); - my $UsageStatsCountry = $query->param('UsageStatsCountry'); - my $UsageStatsLibraryName = $query->param('UsageStatsLibraryName'); - my $UsageStatsLibraryType = $query->param('UsageStatsLibraryType'); - my $UsageStatsLibraryUrl = $query->param('UsageStatsLibraryUrl'); + my $UsageStats = $query->param('UsageStats'); + my $UsageStatsCountry = $query->param('UsageStatsCountry'); + my $UsageStatsLibraryName = $query->param('UsageStatsLibraryName'); + my $UsageStatsLibraryType = $query->param('UsageStatsLibraryType'); + my $UsageStatsLibraryUrl = $query->param('UsageStatsLibraryUrl'); my $UsageStatsLibrariesInfo = $query->param('UsageStatsLibrariesInfo'); - my $UsageStatsGeolocation = $query->param('UsageStatsGeolocation'); - C4::Context->set_preference('UsageStats', $UsageStats); - C4::Context->set_preference('UsageStatsCountry', $UsageStatsCountry); - C4::Context->set_preference('UsageStatsLibraryName', $UsageStatsLibraryName); - C4::Context->set_preference('UsageStatsLibraryType', $UsageStatsLibraryType); - C4::Context->set_preference('UsageStatsLibraryUrl', $UsageStatsLibraryUrl); - C4::Context->set_preference('UsageStatsLibrariesInfo', $UsageStatsLibrariesInfo); - C4::Context->set_preference('UsageStatsGeolocation', $UsageStatsGeolocation); + my $UsageStatsGeolocation = $query->param('UsageStatsGeolocation'); + C4::Context->set_preference( 'UsageStats', $UsageStats ); + C4::Context->set_preference( 'UsageStatsCountry', $UsageStatsCountry ); + C4::Context->set_preference( 'UsageStatsLibraryName', $UsageStatsLibraryName ); + C4::Context->set_preference( 'UsageStatsLibraryType', $UsageStatsLibraryType ); + C4::Context->set_preference( 'UsageStatsLibraryUrl', $UsageStatsLibraryUrl ); + C4::Context->set_preference( 'UsageStatsLibrariesInfo', $UsageStatsLibrariesInfo ); + C4::Context->set_preference( 'UsageStatsGeolocation', $UsageStatsGeolocation ); my $libraries = Koha::Libraries->search; + while ( my $library = $libraries->next ) { - if ( my $latlng = $query->param('geolocation_' . $library->branchcode) ) { - $library->geolocation( $latlng )->store; + if ( my $latlng = $query->param( 'geolocation_' . $library->branchcode ) ) { + $library->geolocation($latlng)->store; } } } if ( C4::Context->preference('UsageStatsLastUpdateTime') ) { - my $dt = DateTime->from_epoch( epoch => C4::Context->preference('UsageStatsLastUpdateTime')); - $template->param(UsageStatsLastUpdateTime => output_pref($dt) ); + my $dt = DateTime->from_epoch( epoch => C4::Context->preference('UsageStatsLastUpdateTime') ); + $template->param( UsageStatsLastUpdateTime => output_pref($dt) ); } my $libraries = Koha::Libraries->search; diff --git a/admin/z3950servers.pl b/admin/z3950servers.pl index 710a4ae2b4..1968f87457 100755 --- a/admin/z3950servers.pl +++ b/admin/z3950servers.pl @@ -18,7 +18,6 @@ # You should have received a copy of the GNU General Public License # along with Koha; if not, see . - # This script is used to maintain the Z3950 servers table. # Parameter $op is operation: list, new, edit, add_validated, delete_confirmed. # add_validated saves a validated record and goes to list view. @@ -27,34 +26,36 @@ use Modern::Perl; use CGI qw ( -utf8 ); use C4::Context; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use Koha::Database; use Koha::Z3950Servers; # Initialize CGI, template, database -my $input = CGI->new; -my $op = $input->param('op') || 'list'; -my $id = $input->param('id') || 0; -my $type = $input->param('type') || ''; +my $input = CGI->new; +my $op = $input->param('op') || 'list'; +my $id = $input->param('id') || 0; +my $type = $input->param('type') || ''; my $searchfield = ''; -my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "admin/z3950servers.tt", - query => $input, - type => "intranet", - flagsrequired => { parameters => 'manage_search_targets' }, -}); +my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "admin/z3950servers.tt", + query => $input, + type => "intranet", + flagsrequired => { parameters => 'manage_search_targets' }, + } +); my $schema = Koha::Database->new()->schema(); # Main code # First process a confirmed delete, or save a validated record -if( $op eq 'cud-delete_confirmed' && $id ) { +if ( $op eq 'cud-delete_confirmed' && $id ) { my $server = Koha::Z3950Servers->find($id); - if ( $server ) { + if ($server) { $server->delete; $template->param( msg_deleted => 1, msg_add => $server->servername ); } else { @@ -62,24 +63,25 @@ if( $op eq 'cud-delete_confirmed' && $id ) { } $id = 0; } elsif ( $op eq 'cud-add_validated' ) { - my @fields=qw/host port db userid password rank syntax encoding timeout + my @fields = qw/host port db userid password rank syntax encoding timeout recordtype checked servername servertype sru_options sru_fields attributes add_xslt/; my $formdata = _form_data_hashref( $input, \@fields ); - if( $id ) { + if ($id) { my $server = Koha::Z3950Servers->find($id); - if ( $server ) { - $server->set( $formdata )->store; + if ($server) { + $server->set($formdata)->store; $template->param( msg_updated => 1, msg_add => $formdata->{servername} ); } else { $template->param( msg_notfound => 1, msg_add => $id ); } $id = 0; } else { - Koha::Z3950Server->new( $formdata )->store; + Koha::Z3950Server->new($formdata)->store; $template->param( msg_added => 1, msg_add => $formdata->{servername} ); } -} elsif ($op eq 'search') { +} elsif ( $op eq 'search' ) { + #use searchfield only in remaining operations $searchfield = $input->param('searchfield') || ''; } @@ -89,20 +91,24 @@ if( $op eq 'cud-delete_confirmed' && $id ) { my $data = []; if ( $op eq 'add' || $op eq 'edit' ) { $data = ServerSearch( $schema, $id, $searchfield ) if $searchfield || $id; - delete $data->[0]->{id} if @$data && $op eq 'add'; #cloning record - $template->param( add_form => 1, server => @$data? $data->[0]: undef, - op => $op, type => $op eq 'add'? lc $type: '' ); + delete $data->[0]->{id} if @$data && $op eq 'add'; #cloning record + $template->param( + add_form => 1, server => @$data ? $data->[0] : undef, + op => $op, type => $op eq 'add' ? lc $type : '' + ); } else { $data = ServerSearch( $schema, $id, $searchfield ); - $template->param( loop => \@$data, searchfield => $searchfield, id => $id, - op => 'list' ); + $template->param( + loop => \@$data, searchfield => $searchfield, id => $id, + op => 'list' + ); } output_html_with_http_headers $input, $cookie, $template->output; # End of main code -sub ServerSearch { #find server(s) by id or name - my ( $schema, $id, $searchstring )= @_; +sub ServerSearch { #find server(s) by id or name + my ( $schema, $id, $searchstring ) = @_; return Koha::Z3950Servers->search( $id ? { id => $id } : { servername => { like => $searchstring . '%' } }, @@ -111,5 +117,5 @@ sub ServerSearch { #find server(s) by id or name sub _form_data_hashref { my ( $input, $fieldref ) = @_; - return { map { ( $_ => scalar $input->param($_)//'' ) } @$fieldref }; + return { map { ( $_ => scalar $input->param($_) // '' ) } @$fieldref }; } diff --git a/authorities/auth_finder.pl b/authorities/auth_finder.pl index 1603fbbc31..f31fb80714 100755 --- a/authorities/auth_finder.pl +++ b/authorities/auth_finder.pl @@ -19,9 +19,9 @@ use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Output qw( output_html_with_http_headers ); -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Context; use C4::Languages; use Koha::SearchEngine::Search; @@ -32,11 +32,11 @@ use Koha::Authorities; use Koha::XSLT::Base; my $query = CGI->new; -my $op = $query->param('op') || ''; +my $op = $query->param('op') || ''; my $authtypecode = $query->param('authtypecode') || ''; -my $index = $query->param('index') || ''; -my $tagid = $query->param('tagid') || ''; -my $source = $query->param('source') || ''; +my $index = $query->param('index') || ''; +my $tagid = $query->param('tagid') || ''; +my $source = $query->param('source') || ''; my $relationship = $query->param('relationship') || ''; my ( $template, $loggedinuser, $cookie ) = get_template_and_user( @@ -44,9 +44,9 @@ my ( $template, $loggedinuser, $cookie ) = get_template_and_user( template_name => ( $op eq 'do_search' ) ? 'authorities/searchresultlist-auth.tt' : 'authorities/auth_finder.tt', - query => $query, - type => 'intranet', - flagsrequired => { catalogue => 1 }, + query => $query, + type => 'intranet', + flagsrequired => { catalogue => 1 }, } ); @@ -68,19 +68,18 @@ if ( $op eq "do_search" ) { my $startfrom = $query->param('startfrom') || 0; my $resultsperpage = $query->param('resultsperpage') || 20; - my $builder = Koha::SearchEngine::QueryBuilder->new( - { index => $Koha::SearchEngine::AUTHORITIES_INDEX } ); - my $searcher = Koha::SearchEngine::Search->new( - { index => $Koha::SearchEngine::AUTHORITIES_INDEX } ); + my $builder = Koha::SearchEngine::QueryBuilder->new( { index => $Koha::SearchEngine::AUTHORITIES_INDEX } ); + my $searcher = Koha::SearchEngine::Search->new( { index => $Koha::SearchEngine::AUTHORITIES_INDEX } ); my $search_query = $builder->build_authorities_query_compat( - \@marclist, \@and_or, \@excluding, \@operator, - \@value, $authtypecode, $orderby + \@marclist, \@and_or, \@excluding, \@operator, + \@value, $authtypecode, $orderby ); $template->param( search_query => $search_query ) if C4::Context->preference('DumpSearchQueryTemplate'); my $offset = $startfrom * $resultsperpage; - my ( $results, $total ) = - $searcher->search_auth_compat( $search_query, $offset, - $resultsperpage ); + my ( $results, $total ) = $searcher->search_auth_compat( + $search_query, $offset, + $resultsperpage + ); # multi page display gestion my $displaynext = 0; @@ -91,7 +90,7 @@ if ( $op eq "do_search" ) { my @field_data = (); -# get marclist again, as the previous one has been modified by catalogsearch (mainentry replaced by field name) + # get marclist again, as the previous one has been modified by catalogsearch (mainentry replaced by field name) my @marclist_ini = $query->multi_param('marclist'); for ( my $i = 0 ; $i <= $#marclist ; $i++ ) { push @field_data, { term => "marclist", val => $marclist_ini[$i] }; @@ -101,13 +100,13 @@ if ( $op eq "do_search" ) { } push @field_data, - { term => "value_mainstr", val => scalar $query->param('value_mainstr') || "" }; + { term => "value_mainstr", val => scalar $query->param('value_mainstr') || "" }; push @field_data, - { term => "value_main", val => scalar $query->param('value_main') || "" }; + { term => "value_main", val => scalar $query->param('value_main') || "" }; push @field_data, - { term => "value_match", val => scalar $query->param('value_match') || "" }; + { term => "value_match", val => scalar $query->param('value_match') || "" }; push @field_data, - { term => "value_any", val => scalar $query->param('value_any') || "" }; + { term => "value_any", val => scalar $query->param('value_any') || "" }; my @numbers = (); if ( $total > $resultsperpage ) { @@ -116,12 +115,12 @@ if ( $op eq "do_search" ) { my $highlight = 0; ( $startfrom == ( $i - 1 ) ) && ( $highlight = 1 ); push @numbers, - { + { number => $i, highlight => $highlight, searchdata => \@field_data, startfrom => ( $i - 1 ) - }; + }; } } } @@ -130,8 +129,7 @@ if ( $op eq "do_search" ) { my $to; if ( $total < ( ( $startfrom + 1 ) * $resultsperpage ) ) { $to = $total; - } - else { + } else { $to = ( ( $startfrom + 1 ) * $resultsperpage ); } @@ -177,8 +175,7 @@ if ( $op eq "do_search" ) { operator_match => ( @operator > 2 && $operator[2] ) ? $operator[2] : '', operator_any => ( @operator > 3 && $operator[3] ) ? $operator[3] : '', ); -} -else { +} else { # special case for UNIMARC field 210c builder my $resultstring = $query->param('result') || ''; @@ -186,17 +183,17 @@ else { } $template->param( - op => $op, - value_mainstr => scalar $query->param('value_mainstr') || '', - value_main => scalar $query->param('value_main') || '', - value_any => scalar $query->param('value_any') || '', - value_match => scalar $query->param('value_match') || '', - tagid => $tagid, - index => $index, - authority_types => $authority_types, - authtypecode => $authtypecode, - source => $source, - relationship => $relationship, + op => $op, + value_mainstr => scalar $query->param('value_mainstr') || '', + value_main => scalar $query->param('value_main') || '', + value_any => scalar $query->param('value_any') || '', + value_match => scalar $query->param('value_match') || '', + tagid => $tagid, + index => $index, + authority_types => $authority_types, + authtypecode => $authtypecode, + source => $source, + relationship => $relationship, ); # Print the page diff --git a/authorities/authorities-home.pl b/authorities/authorities-home.pl index b9a381a702..a3f2a1ec52 100755 --- a/authorities/authorities-home.pl +++ b/authorities/authorities-home.pl @@ -19,13 +19,13 @@ use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use URI::Escape qw( uri_escape_utf8 ); -use POSIX qw( ceil ); +use POSIX qw( ceil ); use C4::Context; -use C4::Auth qw( get_template_and_user ); -use C4::Output qw( output_and_exit pagination_bar output_html_with_http_headers ); +use C4::Auth qw( get_template_and_user ); +use C4::Output qw( output_and_exit pagination_bar output_html_with_http_headers ); use C4::AuthoritiesMarc qw( DelAuthority ); use C4::Search::History; use C4::Languages; @@ -36,8 +36,8 @@ use Koha::SearchEngine::QueryBuilder; use Koha::XSLT::Base; use Koha::Z3950Servers; -my $query = CGI->new; -my $dbh = C4::Context->dbh; +my $query = CGI->new; +my $dbh = C4::Context->dbh; my $op = $query->param('op') || ''; my $authtypecode = $query->param('authtypecode') || ''; my $authid = $query->param('authid') || ''; @@ -50,22 +50,23 @@ my $pending_deletion_authid; if ( $op eq "cud-delete" ) { ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "authorities/authorities-home.tt", - query => $query, - type => 'intranet', - flagsrequired => { catalogue => 1 }, + template_name => "authorities/authorities-home.tt", + query => $query, + type => 'intranet', + flagsrequired => { catalogue => 1 }, } ); - DelAuthority({ authid => $authid }); + DelAuthority( { authid => $authid } ); + # FIXME No error handling here, DelAuthority needs adjustments $pending_deletion_authid = $authid; if ( $query->param('operator') ) { + # query contains search params so perform search $op = "do_search"; - } - else { + } else { $op = ''; } } @@ -79,14 +80,14 @@ if ( $op eq "do_search" ) { my $startfrom = $query->param('startfrom') || 1; my $resultsperpage = $query->param('resultsperpage') || 20; - my $offset = ( $startfrom - 1 ) * $resultsperpage + 1; + my $offset = ( $startfrom - 1 ) * $resultsperpage + 1; ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "authorities/searchresultlist.tt", - query => $query, - type => 'intranet', - flagsrequired => { catalogue => 1 }, + template_name => "authorities/searchresultlist.tt", + query => $query, + type => 'intranet', + flagsrequired => { catalogue => 1 }, } ); @@ -94,8 +95,8 @@ if ( $op eq "do_search" ) { my $searcher = Koha::SearchEngine::Search->new( { index => $Koha::SearchEngine::AUTHORITIES_INDEX } ); my $search_query = $builder->build_authorities_query_compat( - [$marclist], [$and_or], [$excluding], [$operator], - [$value], $authtypecode, $orderby + [$marclist], [$and_or], [$excluding], [$operator], + [$value], $authtypecode, $orderby ); my ( $results, $total ); eval { ( $results, $total ) = $searcher->search_auth_compat( $search_query, $offset, $resultsperpage ); }; @@ -108,21 +109,23 @@ if ( $op eq "do_search" ) { $template->param( search_query => $search_query ) if C4::Context->preference('DumpSearchQueryTemplate'); # search history - if (C4::Context->preference('EnableSearchHistory')) { - if ( $startfrom == 1) { - my $path_info = $query->url(-path_info=>1); - my $query_cgi_history = $query->url(-query=>1); + if ( C4::Context->preference('EnableSearchHistory') ) { + if ( $startfrom == 1 ) { + my $path_info = $query->url( -path_info => 1 ); + my $query_cgi_history = $query->url( -query => 1 ); $query_cgi_history =~ s/^$path_info\?//; $query_cgi_history =~ s/;/&/g; - C4::Search::History::add({ - userid => $loggedinuser, - sessionid => $query->cookie("CGISESSID"), - query_desc => $value, - query_cgi => $query_cgi_history, - total => $total, - type => "authority", - }); + C4::Search::History::add( + { + userid => $loggedinuser, + sessionid => $query->cookie("CGISESSID"), + query_desc => $value, + query_cgi => $query_cgi_history, + total => $total, + type => "authority", + } + ); } } @@ -144,17 +147,18 @@ if ( $op eq "do_search" ) { # construction of the url of each page my $value_url = uri_escape_utf8($value); - my $base_url = "authorities-home.pl?" - ."marclist=$marclist" - ."&and_or=$and_or" - ."&excluding=$excluding" - ."&operator=$operator" - ."&value=$value_url" - ."&resultsperpage=$resultsperpage" - ."&type=intranet" - ."&op=do_search" - ."&authtypecode=$authtypecode" - ."&orderby=$orderby"; + my $base_url = + "authorities-home.pl?" + . "marclist=$marclist" + . "&and_or=$and_or" + . "&excluding=$excluding" + . "&operator=$operator" + . "&value=$value_url" + . "&resultsperpage=$resultsperpage" + . "&type=intranet" + . "&op=do_search" + . "&authtypecode=$authtypecode" + . "&orderby=$orderby"; my $from = ( $startfrom - 1 ) * $resultsperpage + 1; my $to; @@ -164,26 +168,25 @@ if ( $op eq "do_search" ) { if ( $total < $startfrom * $resultsperpage ) { $to = $total; - } - else { + } else { $to = $startfrom * $resultsperpage; } my $AuthorityXSLTResultsDisplay = C4::Context->preference('AuthorityXSLTResultsDisplay'); - if ($results && $AuthorityXSLTResultsDisplay) { + if ( $results && $AuthorityXSLTResultsDisplay ) { my $lang = C4::Languages::getlanguage(); foreach my $result (@$results) { - my $authority = Koha::Authorities->find($result->{authid}); + my $authority = Koha::Authorities->find( $result->{authid} ); next unless $authority; my $authtypecode = $authority->authtypecode; - my $xsl = $AuthorityXSLTResultsDisplay; + my $xsl = $AuthorityXSLTResultsDisplay; $xsl =~ s/\{langcode\}/$lang/g; $xsl =~ s/\{authtypecode\}/$authtypecode/g; my $xslt_engine = Koha::XSLT::Base->new; - my $output = $xslt_engine->transform({ xml => $authority->marcxml, file => $xsl }); - if ($xslt_engine->err) { + my $output = $xslt_engine->transform( { xml => $authority->marcxml, file => $xsl } ); + if ( $xslt_engine->err ) { warn "XSL transformation failed ($xsl): " . $xslt_engine->err; next; } @@ -192,14 +195,14 @@ if ( $op eq "do_search" ) { } } - if( $pending_deletion_authid && $results ) { + if ( $pending_deletion_authid && $results ) { $results = [ grep { $_->{authid} != $pending_deletion_authid } @$results ]; } $template->param( result => $results ) if $results; my $max_result_window = $searcher->max_result_window; - my $hits_to_paginate = ($max_result_window && $max_result_window < $total) ? $max_result_window : $total; + my $hits_to_paginate = ( $max_result_window && $max_result_window < $total ) ? $max_result_window : $total; $template->param( pagination_bar => pagination_bar( @@ -217,10 +220,10 @@ if ( $op eq "do_search" ) { if ( $op eq '' ) { ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "authorities/authorities-home.tt", - query => $query, - type => 'intranet', - flagsrequired => { catalogue => 1 }, + template_name => "authorities/authorities-home.tt", + query => $query, + type => 'intranet', + flagsrequired => { catalogue => 1 }, } ); @@ -229,14 +232,14 @@ if ( $op eq '' ) { my $servers = Koha::Z3950Servers->search( { recordtype => 'authority', - servertype => ['zed', 'sru'], + servertype => [ 'zed', 'sru' ], }, ); $template->param( - servers => $servers, + servers => $servers, authority_types => $authority_types, - op => $op, + op => $op, ); $template->{VARS}->{marcflavour} = C4::Context->preference("marcflavour"); diff --git a/authorities/authorities.pl b/authorities/authorities.pl index 2133008f4f..74c22d54f6 100755 --- a/authorities/authorities.pl +++ b/authorities/authorities.pl @@ -1,6 +1,5 @@ #!/usr/bin/perl - # Copyright 2000-2002 Katipo Communications # # This file is part of Koha. @@ -20,11 +19,12 @@ use Modern::Perl; -use CGI qw ( -utf8 ); -use POSIX qw( strftime ); -use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); +use POSIX qw( strftime ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); -use C4::AuthoritiesMarc qw( AddAuthority ModAuthority GetAuthority GetTagsLabels GetAuthMARCFromKohaField FindDuplicateAuthority ); +use C4::AuthoritiesMarc + qw( AddAuthority ModAuthority GetAuthority GetTagsLabels GetAuthMARCFromKohaField FindDuplicateAuthority ); use C4::Context; use Date::Calc qw( Today ); use MARC::File::USMARC; @@ -37,7 +37,7 @@ use vars qw( $tagslib); use vars qw( $authorised_values_sth); use vars qw( $is_a_modif ); -our($authorised_values_sth,$is_a_modif,$usedTagsLib,$mandatory_z3950); +our ( $authorised_values_sth, $is_a_modif, $usedTagsLib, $mandatory_z3950 ); =head1 FUNCTIONS @@ -50,7 +50,7 @@ builds list, depending on authorised value... =cut sub build_authorized_values_list { - my ( $tag, $subfield, $value, $dbh, $authorised_values_sth,$index_tag,$index_subfield ) = @_; + my ( $tag, $subfield, $value, $dbh, $authorised_values_sth, $index_tag, $index_subfield ) = @_; my @authorised_values; my %authorised_lib; @@ -59,24 +59,20 @@ sub build_authorized_values_list { push @authorised_values, q{} unless $tagslib->{$tag}->{$subfield}->{mandatory} && $value; if ( $category eq "branches" ) { - my $sth = $dbh->prepare( "select branchcode,branchname from branches order by branchname" ); + my $sth = $dbh->prepare("select branchcode,branchname from branches order by branchname"); $sth->execute; while ( my ( $branchcode, $branchname ) = $sth->fetchrow_array ) { push @authorised_values, $branchcode; $authorised_lib{$branchcode} = $branchname; } - } - elsif ( $category eq "itemtypes" ) { + } elsif ( $category eq "itemtypes" ) { my $itemtypes = Koha::ItemTypes->search_with_localization; while ( my $itemtype = $itemtypes->next ) { push @authorised_values, $itemtype->itemtype; - $authorised_lib{$itemtype->itemtype} = $itemtype->translated_description; + $authorised_lib{ $itemtype->itemtype } = $itemtype->translated_description; } - } - else { # "true" authorised value - $authorised_values_sth->execute( - $tagslib->{$tag}->{$subfield}->{authorised_value} - ); + } else { # "true" authorised value + $authorised_values_sth->execute( $tagslib->{$tag}->{$subfield}->{authorised_value} ); while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) { push @authorised_values, $value; $authorised_lib{$value} = $lib; @@ -84,13 +80,13 @@ sub build_authorized_values_list { } return { - type => 'select', - id => "tag_".$tag."_subfield_".$subfield."_".$index_tag."_".$index_subfield, - name => "tag_".$tag."_subfield_".$subfield."_".$index_tag."_".$index_subfield, - values => \@authorised_values, - labels => \%authorised_lib, - default => $value, - ( ( grep { $_ eq $category } ( qw(branches itemtypes cn_source) ) ) ? () : ( category => $category ) ), + type => 'select', + id => "tag_" . $tag . "_subfield_" . $subfield . "_" . $index_tag . "_" . $index_subfield, + name => "tag_" . $tag . "_subfield_" . $subfield . "_" . $index_tag . "_" . $index_subfield, + values => \@authorised_values, + labels => \%authorised_lib, + default => $value, + ( ( grep { $_ eq $category } (qw(branches itemtypes cn_source)) ) ? () : ( category => $category ) ), }; } @@ -103,13 +99,13 @@ builds the entry for a subfield. sub create_input { my ( $tag, $subfield, $value, $index_tag, $rec, $authorised_values_sth, $cgi ) = @_; - my $index_subfield = CreateKey(); # create a specific key for each subfield + my $index_subfield = CreateKey(); # create a specific key for each subfield # determine maximum length; 9999 bytes per ISO 2709 except for leader and MARC21 008 my $max_length = 9999; - if ($tag eq '000') { + if ( $tag eq '000' ) { $max_length = 24; - } elsif ($tag eq '008' and C4::Context->preference('marcflavour') eq 'MARC21') { + } elsif ( $tag eq '008' and C4::Context->preference('marcflavour') eq 'MARC21' ) { $max_length = 40; } @@ -118,13 +114,15 @@ sub create_input { # based on the ApplyFrameworkDefaults setting. # Substitute date parts, user name my $applydefaults = C4::Context->preference('ApplyFrameworkDefaults'); - if ( $value eq '' && ( - ( $applydefaults =~ /new/ && !$cgi->param('authid') ) || - ( $applydefaults =~ /duplicate/ && $cgi->param('op') eq 'duplicate' ) || - ( $applydefaults =~ /imported/ && $cgi->param('breedingid') ) - ) ) { + if ( + $value eq '' + && ( ( $applydefaults =~ /new/ && !$cgi->param('authid') ) + || ( $applydefaults =~ /duplicate/ && $cgi->param('op') eq 'duplicate' ) + || ( $applydefaults =~ /imported/ && $cgi->param('breedingid') ) ) + ) + { $value = $tagslib->{$tag}->{$subfield}->{defaultvalue}; - if (!defined $value) { + if ( !defined $value ) { $value = q{}; } @@ -144,37 +142,36 @@ sub create_input { $id_subfield = "00" if $id_subfield eq "@"; my %subfield_data = ( - tag => $tag, - subfield => $id_subfield, - marc_lib => $tagslib->{$tag}->{$subfield}->{lib}, - tag_mandatory => $tagslib->{$tag}->{mandatory}, - mandatory => $tagslib->{$tag}->{$subfield}->{mandatory}, - repeatable => $tagslib->{$tag}->{$subfield}->{repeatable}, - kohafield => $tagslib->{$tag}->{$subfield}->{kohafield}, - index => $index_tag, - id => "tag_".$tag."_subfield_".$id_subfield."_".$index_tag."_".$index_subfield, - value => $value, - random => CreateKey(), + tag => $tag, + subfield => $id_subfield, + marc_lib => $tagslib->{$tag}->{$subfield}->{lib}, + tag_mandatory => $tagslib->{$tag}->{mandatory}, + mandatory => $tagslib->{$tag}->{$subfield}->{mandatory}, + repeatable => $tagslib->{$tag}->{$subfield}->{repeatable}, + kohafield => $tagslib->{$tag}->{$subfield}->{kohafield}, + index => $index_tag, + id => "tag_" . $tag . "_subfield_" . $id_subfield . "_" . $index_tag . "_" . $index_subfield, + value => $value, + random => CreateKey(), ); - if(exists $mandatory_z3950->{$tag.$subfield}){ - $subfield_data{z3950_mandatory} = $mandatory_z3950->{$tag.$subfield}; + if ( exists $mandatory_z3950->{ $tag . $subfield } ) { + $subfield_data{z3950_mandatory} = $mandatory_z3950->{ $tag . $subfield }; } - + $subfield_data{visibility} = "display:none;" - if( $tagslib->{$tag}->{$subfield}->{hidden} and $value ne '' - or ($value eq '' and !$tagslib->{$tag}->{$subfield}->{mandatory}) - ); - + if ( $tagslib->{$tag}->{$subfield}->{hidden} and $value ne '' + or ( $value eq '' and !$tagslib->{$tag}->{$subfield}->{mandatory} ) ); + # it's an authorised field if ( $tagslib->{$tag}->{$subfield}->{authorised_value} ) { - $subfield_data{marc_value} = - build_authorized_values_list( $tag, $subfield, $value, $dbh, - $authorised_values_sth,$index_tag,$index_subfield ); + $subfield_data{marc_value} = build_authorized_values_list( + $tag, $subfield, $value, $dbh, + $authorised_values_sth, $index_tag, $index_subfield + ); - # it's a thesaurus / authority field - } - elsif ( $tagslib->{$tag}->{$subfield}->{authtypecode} ) { + # it's a thesaurus / authority field + } elsif ( $tagslib->{$tag}->{$subfield}->{authtypecode} ) { $subfield_data{marc_value} = { type => 'text1', id => $subfield_data{id}, @@ -182,26 +179,29 @@ sub create_input { value => $value, authtypecode => $tagslib->{$tag}->{$subfield}->{authtypecode}, }; - } - elsif ( $tagslib->{$tag}->{$subfield}->{'value_builder'} ) { # plugin + } elsif ( $tagslib->{$tag}->{$subfield}->{'value_builder'} ) { # plugin require Koha::FrameworkPlugin; - my $plugin = Koha::FrameworkPlugin->new({ - name => $tagslib->{$tag}->{$subfield}->{'value_builder'}, - }); - my $pars= { dbh => $dbh, record => $rec, tagslib =>$tagslib, - id => $subfield_data{id} }; - $plugin->build( $pars ); - if( !$plugin->errstr ) { + my $plugin = Koha::FrameworkPlugin->new( + { + name => $tagslib->{$tag}->{$subfield}->{'value_builder'}, + } + ); + my $pars = { + dbh => $dbh, record => $rec, tagslib => $tagslib, + id => $subfield_data{id} + }; + $plugin->build($pars); + if ( !$plugin->errstr ) { $subfield_data{marc_value} = { type => 'text2', - id => $subfield_data{id}, - name => $subfield_data{id}, - value => $value, - maxlength => $max_length, + id => $subfield_data{id}, + name => $subfield_data{id}, + value => $value, + maxlength => $max_length, javascript => $plugin->javascript, noclick => $plugin->noclick, }; - } else { # warn and supply default field + } else { # warn and supply default field warn $plugin->errstr; $subfield_data{marc_value} = { type => 'text', @@ -212,6 +212,7 @@ sub create_input { }; } } + # it's an hidden field elsif ( $tag eq '' ) { $subfield_data{marc_value} = { @@ -220,11 +221,10 @@ sub create_input { name => $subfield_data{id}, value => $value, maxlength => $max_length, - } - } - elsif ( $tagslib->{$tag}->{$subfield}->{'hidden'} ) { + }; + } elsif ( $tagslib->{$tag}->{$subfield}->{'hidden'} ) { $subfield_data{marc_value} = { - type => 'text', + type => 'text', id => $subfield_data{id}, name => $subfield_data{id}, value => $value, @@ -232,30 +232,26 @@ sub create_input { }; # it's a standard field - } - else { + } else { if ( length($value) > 100 - or - ( C4::Context->preference("marcflavour") eq "UNIMARC" && $tag >= 300 + or ( C4::Context->preference("marcflavour") eq "UNIMARC" && $tag >= 300 and $tag < 400 && $subfield eq 'a' ) or ( $tag >= 600 - and $tag < 700 - && C4::Context->preference("marcflavour") eq "MARC21" ) - ) + and $tag < 700 && C4::Context->preference("marcflavour") eq "MARC21" ) + ) { $subfield_data{marc_value} = { - type => 'textarea', + type => 'textarea', id => $subfield_data{id}, name => $subfield_data{id}, value => $value, maxlength => $max_length, }; - } - else { + } else { $subfield_data{marc_value} = { - type => 'text', + type => 'text', id => $subfield_data{id}, name => $subfield_data{id}, value => $value, @@ -264,8 +260,9 @@ sub create_input { } } - if ($cgi->param('tagreport') && $subfield_data{tag} == $cgi->param('tagreport')) { - $subfield_data{marc_value}{value} = $cgi->param('tag'. $cgi->param('tagbiblio') . 'subfield' . $subfield_data{subfield}); + if ( $cgi->param('tagreport') && $subfield_data{tag} == $cgi->param('tagreport') ) { + $subfield_data{marc_value}{value} = + $cgi->param( 'tag' . $cgi->param('tagbiblio') . 'subfield' . $subfield_data{subfield} ); } $subfield_data{'index_subfield'} = $index_subfield; return \%subfield_data; @@ -293,7 +290,7 @@ Create a random value to set it into the input name =cut sub CreateKey { - return int(rand(1000000)); + return int( rand(1000000) ); } =item GetMandatoryFieldZ3950 @@ -305,7 +302,7 @@ sub CreateKey { sub GetMandatoryFieldZ3950 { my $authtypecode = shift; - if ( C4::Context->preference('marcflavour') eq 'MARC21' ){ + if ( C4::Context->preference('marcflavour') eq 'MARC21' ) { return { '100a' => 'authorpersonal', '110a' => 'authorcorp', @@ -313,10 +310,10 @@ sub GetMandatoryFieldZ3950 { '130a' => 'uniformtitle', '150a' => 'subject', }; - }else{ + } else { return { '200a' => 'authorpersonal', - '210a' => 'authorcorp', #210 in UNIMARC is used for both corporation and meeting + '210a' => 'authorcorp', #210 in UNIMARC is used for both corporation and meeting '230a' => 'uniformtitle', }; } @@ -334,27 +331,28 @@ sub build_tabs { FROM authorised_values WHERE category=? ORDER BY lib" ); - + # in this array, we will push all the 10 tabs # to avoid having 10 tabs in the template : they will all be in the same BIG_LOOP my @BIG_LOOP; my %seen; - my @tab_data; # all tags to display - - foreach my $used ( keys %$tagslib ){ - push @tab_data,$used if not $seen{$used}; + my @tab_data; # all tags to display + + foreach my $used ( keys %$tagslib ) { + push @tab_data, $used if not $seen{$used}; $seen{$used}++; } - - my $max_num_tab=9; + + my $max_num_tab = 9; + # loop through each tab 0 through 9 for ( my $tabloop = 0 ; $tabloop <= $max_num_tab ; $tabloop++ ) { - my @loop_data = (); #innerloop in the template. - my $i = 0; - foreach my $tag (sort @tab_data) { + my @loop_data = (); #innerloop in the template. + my $i = 0; + foreach my $tag ( sort @tab_data ) { $i++; - next if ! $tag; - my ($indicator1, $indicator2); + next if !$tag; + my ( $indicator1, $indicator2 ); my $index_tag = CreateKey; # if MARC::Record is not empty =>use it as master loop, then add missing subfields that should be in the tab. @@ -362,22 +360,21 @@ sub build_tabs { if ( $record && ( $record->field($tag) || $tag eq '000' ) ) { my @fields; if ( $tag ne '000' ) { - @fields = $record->field($tag); - } - else { - push @fields, $record->leader(); # if tag == 000 + @fields = $record->field($tag); + } else { + push @fields, $record->leader(); # if tag == 000 } + # loop through each field foreach my $field (@fields) { - + my @subfields_data; if ( $tag < 10 ) { my ( $value, $subfield ); if ( $tag ne '000' ) { $value = $field->data(); $subfield = "@"; - } - else { + } else { $value = $field; $subfield = '@'; } @@ -387,11 +384,10 @@ sub build_tabs { @subfields_data, &create_input( $tag, $subfield, $value, $index_tag, $record, - $authorised_values_sth,$input + $authorised_values_sth, $input ) ); - } - else { + } else { my @subfields = $field->subfields(); foreach my $subfieldcount ( 0 .. $#subfields ) { my $subfield = $subfields[$subfieldcount][0]; @@ -402,16 +398,15 @@ sub build_tabs { push( @subfields_data, &create_input( - $tag, $subfield, $value, $index_tag, - $record, $authorised_values_sth,$input + $tag, $subfield, $value, $index_tag, + $record, $authorised_values_sth, $input ) ); } } # now, loop again to add parameter subfield that are not in the MARC::Record - foreach my $subfield ( sort( keys %{ $tagslib->{$tag} } ) ) - { + foreach my $subfield ( sort( keys %{ $tagslib->{$tag} } ) ) { next if ( length $subfield != 1 ); next if ( $tagslib->{$tag}->{$subfield}->{tab} ne $tabloop ); next if ( $tag < 10 ); @@ -421,41 +416,42 @@ sub build_tabs { @subfields_data, &create_input( $tag, $subfield, '', $index_tag, $record, - $authorised_values_sth,$input + $authorised_values_sth, $input ) ); } if ( $#subfields_data >= 0 ) { + # build the tag entry. - # note that the random() field is mandatory. Otherwise, on repeated fields, you'll + # note that the random() field is mandatory. Otherwise, on repeated fields, you'll # have twice the same "name" value, and cgi->param() will return only one, making # all subfields to be merged in a single field. my %tag_data = ( tag => $tag, index => $index_tag, tag_lib => $tagslib->{$tag}->{lib}, - repeatable => $tagslib->{$tag}->{repeatable}, - mandatory => $tagslib->{$tag}->{mandatory}, + repeatable => $tagslib->{$tag}->{repeatable}, + mandatory => $tagslib->{$tag}->{mandatory}, subfield_loop => \@subfields_data, - fixedfield => ($tag < 10)?(1):(0), + fixedfield => ( $tag < 10 ) ? (1) : (0), random => CreateKey, ); - if ($tag >= 10){ # no indicator for theses tag - $tag_data{indicator1} = format_indicator($field->indicator(1)), - $tag_data{indicator2} = format_indicator($field->indicator(2)), + if ( $tag >= 10 ) { # no indicator for theses tag + $tag_data{indicator1} = format_indicator( $field->indicator(1) ), + $tag_data{indicator2} = format_indicator( $field->indicator(2) ),; } push( @loop_data, \%tag_data ); } - } # foreach $field end + } # foreach $field end - # if breeding is empty - } - else { + # if breeding is empty + } else { my @subfields_data; foreach my $subfield ( sort { $a->{display_order} <=> $b->{display_order} || $a->{subfield} cmp $b->{subfield} } grep { ref($_) && %$_ } # Not a subfield (values for "important", "lib", "mandatory", etc.) or empty - values %{ $tagslib->{$tag} } ) + values %{ $tagslib->{$tag} } + ) { next if $subfield->{hidden} && $subfield->{subfield} ne '9'; next if ( $subfield->{tab} ne $tabloop ); @@ -463,7 +459,7 @@ sub build_tabs { @subfields_data, &create_input( $tag, $subfield->{subfield}, '', $index_tag, $record, - $authorised_values_sth,$input + $authorised_values_sth, $input ) ); } @@ -473,15 +469,15 @@ sub build_tabs { index => $index_tag, tag_lib => $tagslib->{$tag}->{lib}, repeatable => $tagslib->{$tag}->{repeatable}, - mandatory => $tagslib->{$tag}->{mandatory}, + mandatory => $tagslib->{$tag}->{mandatory}, indicator1 => $indicator1, indicator2 => $indicator2, subfield_loop => \@subfields_data, tagfirstsubfield => $subfields_data[0], - fixedfield => ($tag < 10)?(1):(0) + fixedfield => ( $tag < 10 ) ? (1) : (0) ); - - push @loop_data, \%tag_data ; + + push @loop_data, \%tag_data; } } } @@ -495,33 +491,33 @@ sub build_tabs { $template->param( BIG_LOOP => \@BIG_LOOP ); } - sub build_hidden_data { + # build hidden data => # we store everything, even if we show only requested subfields. - my @loop_data =(); - my $i=0; - foreach my $tag (keys %{$tagslib}) { + my @loop_data = (); + my $i = 0; + foreach my $tag ( keys %{$tagslib} ) { my $previous_tag = ''; # loop through each subfield - foreach my $subfield (keys %{$tagslib->{$tag}}) { - next if ($subfield eq 'lib'); - next if ($subfield eq 'tab'); - next if ($subfield eq 'mandatory'); - next if ($subfield eq 'repeatable'); - next if ($tagslib->{$tag}->{$subfield}->{'tab'} ne "-1"); + foreach my $subfield ( keys %{ $tagslib->{$tag} } ) { + next if ( $subfield eq 'lib' ); + next if ( $subfield eq 'tab' ); + next if ( $subfield eq 'mandatory' ); + next if ( $subfield eq 'repeatable' ); + next if ( $tagslib->{$tag}->{$subfield}->{'tab'} ne "-1" ); my %subfield_data; - $subfield_data{marc_lib}=$tagslib->{$tag}->{$subfield}->{lib}; - $subfield_data{marc_mandatory}=$tagslib->{$tag}->{$subfield}->{mandatory}; - $subfield_data{marc_repeatable}=$tagslib->{$tag}->{$subfield}->{repeatable}; - $subfield_data{marc_value} = { + $subfield_data{marc_lib} = $tagslib->{$tag}->{$subfield}->{lib}; + $subfield_data{marc_mandatory} = $tagslib->{$tag}->{$subfield}->{mandatory}; + $subfield_data{marc_repeatable} = $tagslib->{$tag}->{$subfield}->{repeatable}; + $subfield_data{marc_value} = { type => 'hidden_simple', name => 'field_value[]', }; - push(@loop_data, \%subfield_data); - $i++ + push( @loop_data, \%subfield_data ); + $i++; } } } @@ -530,48 +526,49 @@ sub build_hidden_data { =cut - -# ======================== -# MAIN +# ======================== +# MAIN #========================= -my $input = CGI->new; -my $z3950 = $input->param('z3950'); -my $error = $input->param('error'); +my $input = CGI->new; +my $z3950 = $input->param('z3950'); +my $error = $input->param('error'); my $authid = $input->param('authid') =~ s/\D//gr ; # if authid exists, it's a modif, not a new authority. We remove from authid all non-digit characters just in case the CGI parameter contains weird characters like spaces -my $op = $input->param('op'); -my $myindex = $input->param('index'); -my $linkid=$input->param('linkid'); +my $op = $input->param('op'); +my $myindex = $input->param('index'); +my $linkid = $input->param('linkid'); my $authtypecode = $input->param('authtypecode'); -my $breedingid = $input->param('breedingid'); +my $breedingid = $input->param('breedingid'); my $changed_authtype; if ( $op eq 'cud-change-framework' ) { - $op = $input->param('original_op'); + $op = $input->param('original_op'); $changed_authtype = 1; } -my $dbh = C4::Context->dbh; +my $dbh = C4::Context->dbh; my $authobj = Koha::Authorities->find($authid); if ( $authid && !$authobj ) { print $input->redirect("/cgi-bin/koha/errors/404.pl"); # escape early exit; } -if(!$authtypecode) { +if ( !$authtypecode ) { $authtypecode = $authid ? $authobj->authtypecode : ''; } my $count = $authobj ? $authobj->get_usage_count : 0; -my ($template, $loggedinuser, $cookie) - = get_template_and_user({template_name => "authorities/authorities.tt", - query => $input, - type => "intranet", - flagsrequired => {editauthorities => 1}, - }); +my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "authorities/authorities.tt", + query => $input, + type => "intranet", + flagsrequired => { editauthorities => 1 }, + } +); $template->param( index => $myindex, authtypecode => $authtypecode, breedingid => $breedingid, count => $count ); -$tagslib = GetTagsLabels(1,$authtypecode); +$tagslib = GetTagsLabels( 1, $authtypecode ); $mandatory_z3950 = GetMandatoryFieldZ3950($authtypecode); my $record; @@ -584,37 +581,42 @@ if ($breedingid) { $record = GetAuthority($authid); } -my ($oldauthnumtagfield,$oldauthnumtagsubfield); -my ($oldauthtypetagfield,$oldauthtypetagsubfield); -$is_a_modif=0; +my ( $oldauthnumtagfield, $oldauthnumtagsubfield ); +my ( $oldauthtypetagfield, $oldauthtypetagsubfield ); +$is_a_modif = 0; if ($authid) { - $is_a_modif=1; - ($oldauthnumtagfield,$oldauthnumtagsubfield) = GetAuthMARCFromKohaField("auth_header.authid",$authtypecode); - ($oldauthtypetagfield,$oldauthtypetagsubfield) = GetAuthMARCFromKohaField("auth_header.authtypecode",$authtypecode); + $is_a_modif = 1; + ( $oldauthnumtagfield, $oldauthnumtagsubfield ) = GetAuthMARCFromKohaField( "auth_header.authid", $authtypecode ); + ( $oldauthtypetagfield, $oldauthtypetagsubfield ) = + GetAuthMARCFromKohaField( "auth_header.authtypecode", $authtypecode ); } $op ||= q{}; -#------------------------------------------------------------------------------------------------------------------------------ -if ($op eq "cud-add") { -#------------------------------------------------------------------------------------------------------------------------------ - # rebuild - my @tags = $input->multi_param('tag'); - my @subfields = $input->multi_param('subfield'); - my @values = $input->multi_param('field_value'); - # build indicator hash. - my @ind_tag = $input->multi_param('ind_tag'); - my @indicator = $input->multi_param('indicator'); - my $record = TransformHtmlToMarc($input, 0); - my ($duplicateauthid,$duplicateauthvalue); +#------------------------------------------------------------------------------------------------------------------------------ +if ( $op eq "cud-add" ) { + + #------------------------------------------------------------------------------------------------------------------------------ + # rebuild + my @tags = $input->multi_param('tag'); + my @subfields = $input->multi_param('subfield'); + my @values = $input->multi_param('field_value'); + + # build indicator hash. + my @ind_tag = $input->multi_param('ind_tag'); + my @indicator = $input->multi_param('indicator'); + my $record = TransformHtmlToMarc( $input, 0 ); + + my ( $duplicateauthid, $duplicateauthvalue ); ( $duplicateauthid, $duplicateauthvalue ) = FindDuplicateAuthority( $record, $authtypecode ) unless $is_a_modif; my $confirm_not_duplicate = $input->param('confirm_not_duplicate'); + # it is not a duplicate (determined either by Koha itself or by user checking it's not a duplicate) - if (!$duplicateauthid or $confirm_not_duplicate) { - if ($is_a_modif ) { - ModAuthority($authid,$record,$authtypecode); + if ( !$duplicateauthid or $confirm_not_duplicate ) { + if ($is_a_modif) { + ModAuthority( $authid, $record, $authtypecode ); } else { - ($authid) = AddAuthority($record,$authid,$authtypecode); + ($authid) = AddAuthority( $record, $authid, $authtypecode ); } if ($myindex) { print $input->redirect("blinddetail-biblio-search.pl?authid=$authid&index=$myindex"); @@ -623,13 +625,15 @@ if ($op eq "cud-add") { } exit; } else { - # it may be a duplicate, warn the user and do nothing - build_tabs($template, $record, $dbh, $input); + + # it may be a duplicate, warn the user and do nothing + build_tabs( $template, $record, $dbh, $input ); build_hidden_data; - $template->param(authid =>$authid, - duplicateauthid => $duplicateauthid, - duplicateauthvalue => $duplicateauthvalue->{'authorized'}->[0]->{'heading'}, - ); + $template->param( + authid => $authid, + duplicateauthid => $duplicateauthid, + duplicateauthvalue => $duplicateauthvalue->{'authorized'}->[0]->{'heading'}, + ); } } else { if ( $op eq "duplicate" ) { @@ -647,7 +651,7 @@ if ($op eq "cud-add") { } } - if ( $changed_authtype ) { + if ($changed_authtype) { $record = TransformHtmlToMarc( $input, 0 ); } diff --git a/authorities/blinddetail-biblio-search.pl b/authorities/blinddetail-biblio-search.pl index bf8af6d0ae..e4c3eb4ceb 100755 --- a/authorities/blinddetail-biblio-search.pl +++ b/authorities/blinddetail-biblio-search.pl @@ -38,11 +38,11 @@ parameters tables. use Modern::Perl; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::AuthoritiesMarc qw( GetAuthority ); use C4::Context; use C4::Output qw( output_html_with_http_headers ); -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use Koha::Authorities; use Koha::Authority::Types; @@ -59,10 +59,10 @@ my $relationship = $query->param('relationship'); # open template my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "authorities/blinddetail-biblio-search.tt", - query => $query, - type => "intranet", - flagsrequired => { editcatalogue => 'edit_catalogue' }, + template_name => "authorities/blinddetail-biblio-search.tt", + query => $query, + type => "intranet", + flagsrequired => { editcatalogue => 'edit_catalogue' }, } ); @@ -72,29 +72,29 @@ $tag_number =~ s/^tag_(\d*)_.*$/$1/; # fill arrays my @subfield_loop; -my ($indicator1, $indicator2); +my ( $indicator1, $indicator2 ); if ($authid) { - my $auth = Koha::Authorities->find( $authid ); + my $auth = Koha::Authorities->find($authid); my $authtypecode = $auth ? $auth->authtypecode : q{}; - my $auth_type = Koha::Authority::Types->find($authtypecode); - my $record = GetAuthority($authid); - my @fields = $record->field( $auth_type->auth_tag_to_report ); - my $repet = ($query->param('repet') || 1) - 1; - my $field = $fields[$repet]; + my $auth_type = Koha::Authority::Types->find($authtypecode); + my $record = GetAuthority($authid); + my @fields = $record->field( $auth_type->auth_tag_to_report ); + my $repet = ( $query->param('repet') || 1 ) - 1; + my $field = $fields[$repet]; # Get all values for each distinct subfield and add to subfield loop my %done_subfields; for ( $field->subfields ) { - next if $_->[0] eq '9'; # $9 will be set with authid value + next if $_->[0] eq '9'; # $9 will be set with authid value my $letter = $_->[0]; $letter ||= '@'; next if defined $done_subfields{$letter}; my @values = $field->subfield($letter); - push @subfield_loop, {marc_subfield => $letter, marc_values => \@values }; + push @subfield_loop, { marc_subfield => $letter, marc_values => \@values }; $done_subfields{$letter} = 1; } - push( @subfield_loop, { marc_subfield => 'w', marc_values => $relationship } ) if ( $relationship ); + push( @subfield_loop, { marc_subfield => 'w', marc_values => $relationship } ) if ($relationship); # Copy the ISNI number over (should one exist) to subfield $o when linking # authorities with authorities in UNIMARC instances. This only applies to @@ -119,32 +119,30 @@ if ($authid) { push( @subfield_loop, { marc_subfield => 'o', marc_values => $isninumber } ) if defined $isninumber; } - my $controlled_ind = $auth->controlled_indicators({ record => $record, biblio_tag => $tag_number }); + my $controlled_ind = $auth->controlled_indicators( { record => $record, biblio_tag => $tag_number } ); $indicator1 = $controlled_ind->{ind1}; $indicator2 = $controlled_ind->{ind2}; - if( defined $controlled_ind->{sub2} ) { + if ( defined $controlled_ind->{sub2} ) { my $v = $controlled_ind->{sub2}; - push @subfield_loop, { marc_subfield => '2', marc_values => [ $v ] }; + push @subfield_loop, { marc_subfield => '2', marc_values => [$v] }; } } else { + # authid is empty => the user want to empty the entry. $template->param( "clear" => 1 ); } - - $template->param( - authid => $authid ? $authid : "", - index => $index, - tagid => $tagid, - update_ind1 => defined($indicator1), - indicator1 => $indicator1, - update_ind2 => defined($indicator2), - indicator2 => $indicator2, - SUBFIELD_LOOP => \@subfield_loop, - tag_number => $tag_number, - rancor => $index =~ /rancor$/, + authid => $authid ? $authid : "", + index => $index, + tagid => $tagid, + update_ind1 => defined($indicator1), + indicator1 => $indicator1, + update_ind2 => defined($indicator2), + indicator2 => $indicator2, + SUBFIELD_LOOP => \@subfield_loop, + tag_number => $tag_number, + rancor => $index =~ /rancor$/, ); - output_html_with_http_headers $query, $cookie, $template->output; diff --git a/authorities/detail-biblio-search.pl b/authorities/detail-biblio-search.pl index 2e8ea40e9a..e2868a70e2 100755 --- a/authorities/detail-biblio-search.pl +++ b/authorities/detail-biblio-search.pl @@ -38,82 +38,89 @@ parameters tables. use Modern::Perl; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::AuthoritiesMarc qw( GetAuthority GetTagsLabels ); use C4::Context; use C4::Output qw( output_html_with_http_headers ); -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); + # use C4::Biblio; # use C4::Catalogue; use Koha::Authorities; use Koha::Authority::Types; -my $query=CGI->new; +my $query = CGI->new; -my $dbh=C4::Context->dbh; +my $dbh = C4::Context->dbh; -my $authid = $query->param('authid'); -my $index = $query->param('index'); +my $authid = $query->param('authid'); +my $index = $query->param('index'); my $authtypecode = Koha::Authorities->find($authid)->authtypecode; -my $tagslib = GetTagsLabels(1,$authtypecode); +my $tagslib = GetTagsLabels( 1, $authtypecode ); + +my $record = GetAuthority($authid); -my $record =GetAuthority($authid); # open template -my ($template, $loggedinuser, $cookie) = get_template_and_user( +my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "authorities/detail-biblio-search.tt", - query => $query, - type => "intranet", - flagsrequired => { catalogue => 1 }, + template_name => "authorities/detail-biblio-search.tt", + query => $query, + type => "intranet", + flagsrequired => { catalogue => 1 }, } ); # fill arrays -my @loop_data =(); +my @loop_data = (); + # loop through each tab 0 through 9 # for (my $tabloop = 0; $tabloop<=10;$tabloop++) { # loop through each tag my @fields = $record->fields(); - foreach my $field (@fields) { - my @subfields_data; - # if tag <10, there's no subfield, use the "@" trick - if ($field->tag()<10) { -# next if ($tagslib->{$field->tag()}->{'@'}->{tab} ne $tabloop); - next if ($tagslib->{$field->tag()}->{'@'}->{hidden}); - my %subfield_data; - $subfield_data{marc_lib}=$tagslib->{$field->tag()}->{'@'}->{lib}; - $subfield_data{marc_value}=$field->data(); - $subfield_data{marc_subfield}='@'; - $subfield_data{marc_tag}=$field->tag(); - push(@subfields_data, \%subfield_data); - } else { - my @subf=$field->subfields; - # loop through each subfield - for my $i (0..$#subf) { - $subf[$i][0] = "@" unless defined $subf[$i][0]; -# next if ($tagslib->{$field->tag()}->{$subf[$i][0]}->{tab} ne $tabloop); - next if ($tagslib->{$field->tag()}->{$subf[$i][0]}->{hidden}); - my %subfield_data; - $subfield_data{marc_lib}=$tagslib->{$field->tag()}->{$subf[$i][0]}->{lib}; - if ($tagslib->{$field->tag()}->{$subf[$i][0]}->{isurl}) { - $subfield_data{marc_value}="$subf[$i][1]"; - } else { - $subfield_data{marc_value}=$subf[$i][1]; - } - $subfield_data{marc_subfield}=$subf[$i][0]; - $subfield_data{marc_tag}=$field->tag(); - push(@subfields_data, \%subfield_data); - } - } - if ($#subfields_data>=0) { - my %tag_data; - $tag_data{tag}=$field->tag().' -'. $tagslib->{$field->tag()}->{lib}; - $tag_data{subfield} = \@subfields_data; - push (@loop_data, \%tag_data); - } - } - $template->param("0XX" =>\@loop_data); +foreach my $field (@fields) { + my @subfields_data; + + # if tag <10, there's no subfield, use the "@" trick + if ( $field->tag() < 10 ) { + + # next if ($tagslib->{$field->tag()}->{'@'}->{tab} ne $tabloop); + next if ( $tagslib->{ $field->tag() }->{'@'}->{hidden} ); + my %subfield_data; + $subfield_data{marc_lib} = $tagslib->{ $field->tag() }->{'@'}->{lib}; + $subfield_data{marc_value} = $field->data(); + $subfield_data{marc_subfield} = '@'; + $subfield_data{marc_tag} = $field->tag(); + push( @subfields_data, \%subfield_data ); + } else { + my @subf = $field->subfields; + + # loop through each subfield + for my $i ( 0 .. $#subf ) { + $subf[$i][0] = "@" unless defined $subf[$i][0]; + + # next if ($tagslib->{$field->tag()}->{$subf[$i][0]}->{tab} ne $tabloop); + next if ( $tagslib->{ $field->tag() }->{ $subf[$i][0] }->{hidden} ); + my %subfield_data; + $subfield_data{marc_lib} = $tagslib->{ $field->tag() }->{ $subf[$i][0] }->{lib}; + if ( $tagslib->{ $field->tag() }->{ $subf[$i][0] }->{isurl} ) { + $subfield_data{marc_value} = "$subf[$i][1]"; + } else { + $subfield_data{marc_value} = $subf[$i][1]; + } + $subfield_data{marc_subfield} = $subf[$i][0]; + $subfield_data{marc_tag} = $field->tag(); + push( @subfields_data, \%subfield_data ); + } + } + if ( $#subfields_data >= 0 ) { + my %tag_data; + $tag_data{tag} = $field->tag() . ' -' . $tagslib->{ $field->tag() }->{lib}; + $tag_data{subfield} = \@subfields_data; + push( @loop_data, \%tag_data ); + } +} +$template->param( "0XX" => \@loop_data ); my $authority_types = Koha::Authority::Types->search( {}, { order_by => ['authtypetext'] } ); diff --git a/authorities/detail.pl b/authorities/detail.pl index 83f42dfdfb..dbe42f1bc4 100755 --- a/authorities/detail.pl +++ b/authorities/detail.pl @@ -40,7 +40,7 @@ use Modern::Perl; use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::AuthoritiesMarc qw( GetAuthority GenerateHierarchy GetTagsLabels ); use C4::Context; use C4::Koha; @@ -56,7 +56,7 @@ use Koha::Z3950Servers; our ($tagslib); sub build_tabs { - my ( $template, $record, $dbh, $encoding,$input ) = @_; + my ( $template, $record, $dbh, $encoding, $input ) = @_; # fill arrays my @loop_data = (); @@ -66,21 +66,22 @@ sub build_tabs { # to avoid having 10 tabs in the template : they will all be in the same BIG_LOOP my @BIG_LOOP; my %seen; - my @tab_data; # all tags to display - - foreach my $used ( keys %$tagslib ){ - push @tab_data,$used if not $seen{$used}; + my @tab_data; # all tags to display + + foreach my $used ( keys %$tagslib ) { + push @tab_data, $used if not $seen{$used}; $seen{$used}++; } - - my $max_num_tab=9; + + my $max_num_tab = 9; + # loop through each tab 0 through 9 for ( my $tabloop = 0 ; $tabloop <= $max_num_tab ; $tabloop++ ) { - my @loop_data = (); #innerloop in the template. - my $i = 0; - foreach my $tag (sort @tab_data) { + my @loop_data = (); #innerloop in the template. + my $i = 0; + foreach my $tag ( sort @tab_data ) { $i++; - next if ! $tag; + next if !$tag; # if MARC::Record is not empty =>use it as master loop, then add missing subfields that should be in the tab. # if MARC::Record is empty => use tab as master loop. @@ -88,121 +89,119 @@ sub build_tabs { my @fields; if ( $tag ne '000' ) { @fields = $record->field($tag); + } else { + push @fields, MARC::Field->new( '000', $record->leader() ); # if tag == 000 } - else { - push @fields, MARC::Field->new('000', $record->leader()); # if tag == 000 - } + # loop through each field foreach my $field (@fields) { my @subfields_data; - if ($field->tag()<10) { + if ( $field->tag() < 10 ) { next - if ( - $tagslib->{ $field->tag() }->{ '@' }->{tab} - ne $tabloop ); - next if ($tagslib->{$field->tag()}->{'@'}->{hidden}); - my %subfield_data; - $subfield_data{marc_lib}=$tagslib->{$field->tag()}->{'@'}->{lib}; - $subfield_data{marc_value}=$field->data(); - $subfield_data{marc_subfield}='@'; - $subfield_data{marc_tag}=$field->tag(); - push(@subfields_data, \%subfield_data); - } else { - my @subf=$field->subfields; - # loop through each subfield - for my $i (0..$#subf) { - $subf[$i][0] = "@" unless defined $subf[$i][0]; - next - if ( - $tagslib->{ $field->tag() }->{ $subf[$i][0] }->{tab} - ne $tabloop ); - next - if ( $tagslib->{ $field->tag() }->{ $subf[$i][0] } - ->{hidden} ); + if ( $tagslib->{ $field->tag() }->{'@'}->{tab} ne $tabloop ); + next if ( $tagslib->{ $field->tag() }->{'@'}->{hidden} ); my %subfield_data; - $subfield_data{marc_lib}=$tagslib->{$field->tag()}->{$subf[$i][0]}->{lib}; - if ($tagslib->{$field->tag()}->{$subf[$i][0]}->{isurl}) { - $subfield_data{marc_value} = $subf[$i][1]; - $subfield_data{is_url} = 1; - } else { - $subfield_data{marc_value}=$subf[$i][1]; - } - $subfield_data{short_desc} = substr( - $tagslib->{ $field->tag() }->{ $subf[$i][0] }->{lib}, - 0, 20 - ); - $subfield_data{long_desc} = - $tagslib->{ $field->tag() }->{ $subf[$i][0] }->{lib}; - $subfield_data{marc_subfield}=$subf[$i][0]; - $subfield_data{marc_tag}=$field->tag(); - push(@subfields_data, \%subfield_data); - } - } - if ($#subfields_data>=0) { - my %tag_data; - $tag_data{tag_number} = $tag; - $tag_data{tag_desc} = $tagslib->{$field->tag()}->{lib}; - $tag_data{subfield} = \@subfields_data; - my $indicators = C4::Koha::display_marc_indicators($field); - if ( $indicators ) { - $tag_data{ind1} = substr $indicators, 0, 1; - $tag_data{ind2} = substr $indicators, 1, 1; - } + $subfield_data{marc_lib} = $tagslib->{ $field->tag() }->{'@'}->{lib}; + $subfield_data{marc_value} = $field->data(); + $subfield_data{marc_subfield} = '@'; + $subfield_data{marc_tag} = $field->tag(); + push( @subfields_data, \%subfield_data ); + } else { + my @subf = $field->subfields; - push (@loop_data, \%tag_data); + # loop through each subfield + for my $i ( 0 .. $#subf ) { + $subf[$i][0] = "@" unless defined $subf[$i][0]; + next + if ( $tagslib->{ $field->tag() }->{ $subf[$i][0] }->{tab} ne $tabloop ); + next + if ( $tagslib->{ $field->tag() }->{ $subf[$i][0] }->{hidden} ); + my %subfield_data; + $subfield_data{marc_lib} = $tagslib->{ $field->tag() }->{ $subf[$i][0] }->{lib}; + if ( $tagslib->{ $field->tag() }->{ $subf[$i][0] }->{isurl} ) { + $subfield_data{marc_value} = $subf[$i][1]; + $subfield_data{is_url} = 1; + } else { + $subfield_data{marc_value} = $subf[$i][1]; + } + $subfield_data{short_desc} = substr( + $tagslib->{ $field->tag() }->{ $subf[$i][0] }->{lib}, + 0, 20 + ); + $subfield_data{long_desc} = + $tagslib->{ $field->tag() }->{ $subf[$i][0] }->{lib}; + $subfield_data{marc_subfield} = $subf[$i][0]; + $subfield_data{marc_tag} = $field->tag(); + push( @subfields_data, \%subfield_data ); + } } - } - } - } - if ( $#loop_data >= 0 ) { - push @BIG_LOOP, { - number => $tabloop, - innerloop => \@loop_data, - }; + if ( $#subfields_data >= 0 ) { + my %tag_data; + $tag_data{tag_number} = $tag; + $tag_data{tag_desc} = $tagslib->{ $field->tag() }->{lib}; + $tag_data{subfield} = \@subfields_data; + my $indicators = C4::Koha::display_marc_indicators($field); + if ($indicators) { + $tag_data{ind1} = substr $indicators, 0, 1; + $tag_data{ind2} = substr $indicators, 1, 1; + } + + push( @loop_data, \%tag_data ); + } + } } } - $template->param( singletab => (scalar(@BIG_LOOP)==1), BIG_LOOP => \@BIG_LOOP ); + if ( $#loop_data >= 0 ) { + push @BIG_LOOP, { + number => $tabloop, + innerloop => \@loop_data, + }; + } + } + $template->param( singletab => ( scalar(@BIG_LOOP) == 1 ), BIG_LOOP => \@BIG_LOOP ); } +# +my $query = CGI->new; -# -my $query=CGI->new; - -my $dbh=C4::Context->dbh; +my $dbh = C4::Context->dbh; # open template -my ($template, $loggedinuser, $cookie) = get_template_and_user( +my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "authorities/detail.tt", - query => $query, - type => "intranet", - flagsrequired => { catalogue => 1 }, + template_name => "authorities/detail.tt", + query => $query, + type => "intranet", + flagsrequired => { catalogue => 1 }, } ); my $authid = $query->param('authid'); -my $authobj = Koha::Authorities->find($authid); +my $authobj = Koha::Authorities->find($authid); my $authtypecode = $authobj ? $authobj->authtypecode : q{}; -$tagslib = GetTagsLabels(1,$authtypecode); +$tagslib = GetTagsLabels( 1, $authtypecode ); # Build list of authtypes for showing them -my $authority_types = Koha::Authority::Types->search({}, { order_by => ['authtypetext']}); +my $authority_types = Koha::Authority::Types->search( {}, { order_by => ['authtypetext'] } ); -my $record=GetAuthority($authid); +my $record = GetAuthority($authid); + +if ( not defined $record ) { -if (not defined $record) { # authid invalid - $template->param ( errauthid => $authid, - unknownauthid => 1, - authority_types => $authority_types, ); + $template->param( + errauthid => $authid, + unknownauthid => 1, + authority_types => $authority_types, + ); output_html_with_http_headers $query, $cookie, $template->output; exit; } -if (C4::Context->preference("AuthDisplayHierarchy")){ +if ( C4::Context->preference("AuthDisplayHierarchy") ) { $template->{VARS}->{'displayhierarchy'} = C4::Context->preference("AuthDisplayHierarchy"); - $template->{VARS}->{'loophierarchies'} = GenerateHierarchy($authid); + $template->{VARS}->{'loophierarchies'} = GenerateHierarchy($authid); } my $count = $authobj ? $authobj->get_usage_count : 0; @@ -211,34 +210,34 @@ my $count = $authobj ? $authobj->get_usage_count : 0; my $sth = $dbh->prepare("select distinct tagfield from marc_subfield_structure where authtypecode=?"); $sth->execute($authtypecode); my $biblio_fields; -while (my ($tagfield) = $sth->fetchrow) { - $biblio_fields.= $tagfield."9,"; +while ( my ($tagfield) = $sth->fetchrow ) { + $biblio_fields .= $tagfield . "9,"; } chop $biblio_fields if $biblio_fields; my $AuthorityXSLTDetailsDisplay = C4::Context->preference('AuthorityXSLTDetailsDisplay'); -if ( $AuthorityXSLTDetailsDisplay ) { - my $xsl = $AuthorityXSLTDetailsDisplay; +if ($AuthorityXSLTDetailsDisplay) { + my $xsl = $AuthorityXSLTDetailsDisplay; my $lang = C4::Languages::getlanguage(); $xsl =~ s/\{langcode\}/$lang/g; $xsl =~ s/\{authtypecode\}/$authtypecode/g; my $xslt_engine = Koha::XSLT::Base->new; - my $output = $xslt_engine->transform({ xml => $authobj->marcxml, file => $xsl }); - if ($xslt_engine->err) { + my $output = $xslt_engine->transform( { xml => $authobj->marcxml, file => $xsl } ); + if ( $xslt_engine->err ) { warn "XSL transformation failed ($xsl): " . $xslt_engine->err; next; } $template->param( html => $output ); } else { - build_tabs ($template, $record, $dbh,"",$query); + build_tabs( $template, $record, $dbh, "", $query ); } my $servers = Koha::Z3950Servers->search( { recordtype => 'authority', - servertype => ['zed', 'sru'], + servertype => [ 'zed', 'sru' ], }, ); @@ -247,10 +246,10 @@ $template->param( authid => $authid, count => $count, biblio_fields => $biblio_fields, - authtypetext => $type ? $type->authtypetext: "", + authtypetext => $type ? $type->authtypetext : "", authtypecode => $authtypecode, authority_types => $authority_types, - servers => $servers, + servers => $servers, ); $template->{VARS}->{marcflavour} = C4::Context->preference("marcflavour"); diff --git a/authorities/export.pl b/authorities/export.pl index 0703da840b..089ee90bf3 100755 --- a/authorities/export.pl +++ b/authorities/export.pl @@ -5,15 +5,15 @@ use C4::Record; use C4::Auth qw( get_template_and_user ); use C4::Output; use C4::AuthoritiesMarc qw( GetAuthority ); -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); my $query = CGI->new; my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "tools/export.tt", - query => $query, - type => "intranet", - flagsrequired => { catalogue => 1 }, + template_name => "tools/export.tt", + query => $query, + type => "intranet", + flagsrequired => { catalogue => 1 }, } ); @@ -27,16 +27,16 @@ if ( $op eq "export" ) { my $marc = GetAuthority($authid); if ( $format =~ /marcxml/ ) { - $marc = marc2marcxml($marc, 'UTF-8', C4::Context->preference("marcflavour") eq 'UNIMARC' ? 'UNIMARCAUTH' : 'MARC21' ); - } - elsif ($format=~ /mads/) { + $marc = marc2marcxml( + $marc, 'UTF-8', + C4::Context->preference("marcflavour") eq 'UNIMARC' ? 'UNIMARCAUTH' : 'MARC21' + ); + } elsif ( $format =~ /mads/ ) { $marc = marc2madsxml($marc); - } - elsif ( $format =~ /marc8/ ) { + } elsif ( $format =~ /marc8/ ) { $marc = changeEncoding( $marc, "MARC", "MARC21", "MARC-8" ); $marc = $marc->as_usmarc(); - } - elsif ( $format =~ /utf8/ ) { + } elsif ( $format =~ /utf8/ ) { C4::Charset::SetUTF8Flag( $marc, 1 ); $marc = $marc->as_usmarc(); } diff --git a/authorities/merge.pl b/authorities/merge.pl index d3208a8fa2..3204b5c93a 100755 --- a/authorities/merge.pl +++ b/authorities/merge.pl @@ -18,11 +18,11 @@ # along with Koha; if not, see . use Modern::Perl; -use CGI qw ( -utf8 ); -use C4::Output qw( output_html_with_http_headers ); -use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); +use C4::Output qw( output_html_with_http_headers ); +use C4::Auth qw( get_template_and_user ); use C4::AuthoritiesMarc qw( GetAuthority ModAuthority DelAuthority GetTagsLabels merge ); -use C4::Biblio qw( TransformHtmlToMarc ); +use C4::Biblio qw( TransformHtmlToMarc ); use Koha::Authority::MergeRequests; use Koha::Authority::Types; @@ -36,40 +36,40 @@ my @errors; my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "authorities/merge.tt", - query => $input, - type => "intranet", - flagsrequired => { editauthorities => 1 }, + template_name => "authorities/merge.tt", + query => $input, + type => "intranet", + flagsrequired => { editauthorities => 1 }, } ); #------------------------ # Merging #------------------------ -if ($op eq 'cud-merge') { +if ( $op eq 'cud-merge' ) { # Creating a new record from the html code - my $record = TransformHtmlToMarc($input, 0); - my $recordid1 = $input->param('recordid1') // q{}; - my $recordid2 = $input->param('recordid2') // q{}; - my $typecode = $input->param('frameworkcode'); + my $record = TransformHtmlToMarc( $input, 0 ); + my $recordid1 = $input->param('recordid1') // q{}; + my $recordid2 = $input->param('recordid2') // q{}; + my $typecode = $input->param('frameworkcode'); # Some error checking - if( $recordid1 eq $recordid2 ) { + if ( $recordid1 eq $recordid2 ) { push @errors, { code => 'DESTRUCTIVE_MERGE' }; - } elsif( !$typecode || !Koha::Authority::Types->find($typecode) ) { + } elsif ( !$typecode || !Koha::Authority::Types->find($typecode) ) { push @errors, { code => 'WRONG_FRAMEWORK' }; - } elsif( scalar $record->fields == 0 ) { + } elsif ( scalar $record->fields == 0 ) { push @errors, { code => 'EMPTY_MARC' }; } - if( @errors ) { + if (@errors) { $template->param( errors => \@errors ); output_html_with_http_headers $input, $cookie, $template->output; exit; } # Rewriting the leader - if( my $authrec = GetAuthority($recordid1) ) { + if ( my $authrec = GetAuthority($recordid1) ) { $record->leader( $authrec->leader() ); } @@ -78,44 +78,42 @@ if ($op eq 'cud-merge') { ModAuthority( $recordid1, $record, $typecode ); # Now merge for biblios attached to $recordid2 - my $MARCfrom = GetAuthority( $recordid2 ); - merge({ mergefrom => $recordid2, MARCfrom => $MARCfrom, mergeto => $recordid1, MARCto => $record }); + my $MARCfrom = GetAuthority($recordid2); + merge( { mergefrom => $recordid2, MARCfrom => $MARCfrom, mergeto => $recordid1, MARCto => $record } ); # Delete the other record. No need to merge. - DelAuthority({ authid => $recordid2, skip_merge => 1 }); + DelAuthority( { authid => $recordid2, skip_merge => 1 } ); # Parameters $template->param( - result => 1, + result => 1, recordid1 => $recordid1 ); #------------------------- # Show records to merge #------------------------- -} -else { +} else { my $mergereference = $input->param('mergereference'); $template->{'VARS'}->{'mergereference'} = $mergereference; if ( scalar(@authid) != 2 ) { push @errors, { code => "WRONG_COUNT", value => scalar(@authid) }; - } elsif( $authid[0] eq $authid[1] ) { + } elsif ( $authid[0] eq $authid[1] ) { push @errors, { code => 'DESTRUCTIVE_MERGE' }; } else { - my $recordObj1 = Koha::MetadataRecord::Authority->get_from_authid($authid[0]); - if (!$recordObj1) { + my $recordObj1 = Koha::MetadataRecord::Authority->get_from_authid( $authid[0] ); + if ( !$recordObj1 ) { push @errors, { code => "MISSING_RECORD", value => $authid[0] }; } - my $recordObj2; - if (defined $mergereference && $mergereference eq 'breeding') { - $recordObj2 = Koha::MetadataRecord::Authority->get_from_breeding($authid[1]); + if ( defined $mergereference && $mergereference eq 'breeding' ) { + $recordObj2 = Koha::MetadataRecord::Authority->get_from_breeding( $authid[1] ); } else { - $recordObj2 = Koha::MetadataRecord::Authority->get_from_authid($authid[1]); + $recordObj2 = Koha::MetadataRecord::Authority->get_from_authid( $authid[1] ); } - if (!$recordObj2) { + if ( !$recordObj2 ) { push @errors, { code => "MISSING_RECORD", value => $authid[1] }; } @@ -127,16 +125,15 @@ else { exit; } - if ($mergereference ) { + if ($mergereference) { my $framework; if ( $recordObj1->authtypecode ne $recordObj2->authtypecode && $mergereference ne 'breeding' ) { $framework = $input->param('frameworkcode'); - } - else { + } else { $framework = $recordObj1->authtypecode; } - if ($mergereference eq 'breeding') { + if ( $mergereference eq 'breeding' ) { $mergereference = $authid[0]; } @@ -150,10 +147,11 @@ else { #Setting $notreference my $notreference = $authid[1]; - if($mergereference == $notreference){ + if ( $mergereference == $notreference ) { $notreference = $authid[0]; + #Swap so $recordObj1 is always the correct merge reference - ($recordObj1, $recordObj2) = ($recordObj2, $recordObj1); + ( $recordObj1, $recordObj2 ) = ( $recordObj2, $recordObj1 ); } # Getting frameworktext @@ -190,19 +188,21 @@ else { frameworktext => $frameworktextdestination->authtypetext, multipleauthtypes => ( $recordObj1->authtypecode ne $recordObj2->authtypecode ) ? 1 : 0, ); - } - else { + } else { # Ask the user to choose which record will be the kept $template->param( choosereference => 1, - recordid1 => $authid[0], - recordid2 => $authid[1], + recordid1 => $authid[0], + recordid2 => $authid[1], title1 => $recordObj1->authorized_heading, title2 => $recordObj2->authorized_heading, ); if ( $recordObj1->authtypecode ne $recordObj2->authtypecode ) { - my $authority_types = Koha::Authority::Types->search( { authtypecode => { '!=' => '' } }, { order_by => ['authtypetext'] } ); + my $authority_types = Koha::Authority::Types->search( + { authtypecode => { '!=' => '' } }, + { order_by => ['authtypetext'] } + ); my $frameworktext1 = Koha::Authority::Types->find( $recordObj1->authtypecode ); my $frameworktext2 = Koha::Authority::Types->find( $recordObj2->authtypecode ); $template->param( diff --git a/authorities/merge_ajax.pl b/authorities/merge_ajax.pl index b4e489be5e..a2a76378e4 100755 --- a/authorities/merge_ajax.pl +++ b/authorities/merge_ajax.pl @@ -3,22 +3,22 @@ use Modern::Perl; use CGI qw ( -utf8 ); -use CGI::Cookie; # need to check cookies before CGI parses the POST request +use CGI::Cookie; # need to check cookies before CGI parses the POST request use JSON qw( encode_json ); use C4::Context; -use C4::Auth qw( check_cookie_auth ); +use C4::Auth qw( check_cookie_auth ); use C4::AuthoritiesMarc qw( GetTagsLabels ); -my %cookies = CGI::Cookie->fetch; -my ($auth_status) = check_cookie_auth($cookies{'CGISESSID'}->value, { editcatalogue => 'edit_catalogue' }); -my $reply = CGI->new; -if ($auth_status ne "ok") { - print $reply->header(-type => 'text/html'); +my %cookies = CGI::Cookie->fetch; +my ($auth_status) = check_cookie_auth( $cookies{'CGISESSID'}->value, { editcatalogue => 'edit_catalogue' } ); +my $reply = CGI->new; +if ( $auth_status ne "ok" ) { + print $reply->header( -type => 'text/html' ); exit 0; } my $framework = $reply->param('frameworkcode'); -my $tagslib = GetTagsLabels(1, $framework); -print $reply->header(-type => 'text/html'); +my $tagslib = GetTagsLabels( 1, $framework ); +print $reply->header( -type => 'text/html' ); print encode_json $tagslib; diff --git a/authorities/ysearch.pl b/authorities/ysearch.pl index 3a58fe9758..d2a4ec2289 100755 --- a/authorities/ysearch.pl +++ b/authorities/ysearch.pl @@ -33,67 +33,64 @@ use JSON qw( to_json ); use C4::Context; use C4::Charset qw( nsb_clean ); -use C4::Auth qw( check_cookie_auth ); -use C4::Output qw( output_with_http_headers ); +use C4::Auth qw( check_cookie_auth ); +use C4::Output qw( output_with_http_headers ); use Koha::SearchEngine::Search; use Koha::SearchEngine::QueryBuilder; my $query = CGI->new; -my ( $auth_status) = check_cookie_auth( $query->cookie('CGISESSID'), { catalogue => 1 } ); +my ($auth_status) = check_cookie_auth( $query->cookie('CGISESSID'), { catalogue => 1 } ); if ( $auth_status ne "ok" ) { + # send empty response my $reply = CGI->new(""); - print $reply->header(-type => 'text/html'); + print $reply->header( -type => 'text/html' ); exit 0; } - my @value = $query->multi_param('term'); - my $searchtype = $query->param('querytype'); - my @marclist = ($searchtype); - my $authtypecode = $query->param('authtypecode'); - my @and_or = $query->multi_param('and_or'); - my @excluding = $query->multi_param('excluding'); - my @operator = $query->multi_param('operator'); - my $orderby = $query->param('orderby'); +my @value = $query->multi_param('term'); +my $searchtype = $query->param('querytype'); +my @marclist = ($searchtype); +my $authtypecode = $query->param('authtypecode'); +my @and_or = $query->multi_param('and_or'); +my @excluding = $query->multi_param('excluding'); +my @operator = $query->multi_param('operator'); +my $orderby = $query->param('orderby'); - my $resultsperpage = 50; - my $startfrom = 0; +my $resultsperpage = 50; +my $startfrom = 0; - my $builder = Koha::SearchEngine::QueryBuilder->new( - { index => $Koha::SearchEngine::AUTHORITIES_INDEX } ); - my $searcher = Koha::SearchEngine::Search->new( - { index => $Koha::SearchEngine::AUTHORITIES_INDEX } ); - my $search_query = $builder->build_authorities_query_compat( - \@marclist, \@and_or, \@excluding, \@operator, - \@value, $authtypecode, $orderby +my $builder = Koha::SearchEngine::QueryBuilder->new( { index => $Koha::SearchEngine::AUTHORITIES_INDEX } ); +my $searcher = Koha::SearchEngine::Search->new( { index => $Koha::SearchEngine::AUTHORITIES_INDEX } ); +my $search_query = $builder->build_authorities_query_compat( + \@marclist, \@and_or, \@excluding, \@operator, + \@value, $authtypecode, $orderby +); +my $offset = $startfrom * $resultsperpage; +my ( $results, $total ) = $searcher->search_auth_compat( + $search_query, $offset, + $resultsperpage +); + +my %used_summaries; # hash to avoid duplicates +my @summaries; +foreach my $result (@$results) { + my $authorized = $result->{'summary'}->{'authorized'}; + my $summary = join( + ' ', + map { ( $searchtype eq 'mainmainentry' ) ? $_->{'hemain'} : $_->{'heading'} } @$authorized ); - my $offset = $startfrom * $resultsperpage; - my ( $results, $total ) = - $searcher->search_auth_compat( $search_query, $offset, - $resultsperpage ); + $summary =~ s/^\s+//; + $summary =~ s/\s+$//; + $summary = nsb_clean($summary); - my %used_summaries; # hash to avoid duplicates - my @summaries; - foreach my $result (@$results) { - my $authorized = $result->{'summary'}->{'authorized'}; - my $summary = join( - ' ', - map { - ( $searchtype eq 'mainmainentry' ) - ? $_->{'hemain'} - : $_->{'heading'} - } @$authorized - ); - $summary =~ s/^\s+//; - $summary =~ s/\s+$//; - $summary = nsb_clean($summary); - # test if already added ignoring case - unless ( exists $used_summaries{ lc($summary) } ) { - push @summaries, { 'summary' => $summary }; - $used_summaries{ lc($summary) } = 1; - } + # test if already added ignoring case + unless ( exists $used_summaries{ lc($summary) } ) { + push @summaries, { 'summary' => $summary }; + $used_summaries{ lc($summary) } = 1; } +} -output_with_http_headers $query, undef, to_json(\@summaries, { utf8 => 1 }), 'json'; +output_with_http_headers $query, undef, to_json( \@summaries, { utf8 => 1 } ), 'json'; diff --git a/basket/basket.pl b/basket/basket.pl index 4220f0a629..d8c633aa95 100755 --- a/basket/basket.pl +++ b/basket/basket.pl @@ -15,7 +15,6 @@ # You should have received a copy of the GNU General Public License # along with Koha; if not, see . - use Modern::Perl; use CGI qw ( -utf8 ); use C4::Koha; @@ -24,7 +23,7 @@ use C4::Biblio qw( GetMarcSubjects GetMarcUrls ); -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use Koha::AuthorisedValues; @@ -33,54 +32,53 @@ use Koha::CsvProfiles; my $query = CGI->new; -my ( $template, $borrowernumber, $cookie ) = get_template_and_user ( +my ( $template, $borrowernumber, $cookie ) = get_template_and_user( { - template_name => "basket/basket.tt", - query => $query, - type => "intranet", - flagsrequired => { catalogue => 1 }, + template_name => "basket/basket.tt", + query => $query, + type => "intranet", + flagsrequired => { catalogue => 1 }, } ); -my $bib_list = $query->param('bib_list'); -my $verbose = $query->param('verbose'); +my $bib_list = $query->param('bib_list'); +my $verbose = $query->param('verbose'); -if ($verbose) { $template->param( verbose => 1 ); } +if ($verbose) { $template->param( verbose => 1 ); } my @bibs = split( /\//, $bib_list ); my @results; -my $num = 1; +my $num = 1; my $marcflavour = C4::Context->preference('marcflavour'); -if (C4::Context->preference('TagsEnabled')) { - $template->param(TagsEnabled => 1); - foreach (qw(TagsShowOnList TagsInputOnList)) { - C4::Context->preference($_) and $template->param($_ => 1); - } +if ( C4::Context->preference('TagsEnabled') ) { + $template->param( TagsEnabled => 1 ); + foreach (qw(TagsShowOnList TagsInputOnList)) { + C4::Context->preference($_) and $template->param( $_ => 1 ); + } } - -foreach my $biblionumber ( @bibs ) { +foreach my $biblionumber (@bibs) { $template->param( biblionumber => $biblionumber ); - my $biblio = Koha::Biblios->find( $biblionumber ) or next; - my $dat = { %{$biblio->unblessed}, %{$biblio->biblioitem->unblessed} }; + my $biblio = Koha::Biblios->find($biblionumber) or next; + my $dat = { %{ $biblio->unblessed }, %{ $biblio->biblioitem->unblessed } }; my $record = $biblio->metadata->record; my $marcnotesarray = $biblio->get_marc_notes; my $marcauthorsarray = $biblio->get_marc_contributors; my $marcsubjctsarray = GetMarcSubjects( $record, $marcflavour ); - my $marcseriesarray = GetMarcSeries ($record,$marcflavour); - my $marcurlsarray = GetMarcUrls ($record,$marcflavour); + my $marcseriesarray = GetMarcSeries( $record, $marcflavour ); + my $marcurlsarray = GetMarcUrls( $record, $marcflavour ); my $hasauthors = 0; - if($dat->{'author'} || @$marcauthorsarray) { - $hasauthors = 1; + if ( $dat->{'author'} || @$marcauthorsarray ) { + $hasauthors = 1; } # COinS format FIXME: for books Only - my $fmt = substr $record->leader(), 6,2; + my $fmt = substr $record->leader(), 6, 2; my $fmts; - $fmts->{'am'} = 'book'; + $fmts->{'am'} = 'book'; $dat->{ocoins_format} = $fmts->{$fmt}; if ( $num % 2 == 1 ) { @@ -89,17 +87,17 @@ foreach my $biblionumber ( @bibs ) { $num++; $dat->{biblionumber} = $biblionumber; - $dat->{ITEM_RESULTS} = $biblio->items->search_ordered; - $dat->{MARCNOTES} = $marcnotesarray; - $dat->{MARCSUBJCTS} = $marcsubjctsarray; - $dat->{MARCAUTHORS} = $marcauthorsarray; - $dat->{MARCSERIES} = $marcseriesarray; - $dat->{MARCURLS} = $marcurlsarray; - $dat->{HASAUTHORS} = $hasauthors; + $dat->{ITEM_RESULTS} = $biblio->items->search_ordered; + $dat->{MARCNOTES} = $marcnotesarray; + $dat->{MARCSUBJCTS} = $marcsubjctsarray; + $dat->{MARCAUTHORS} = $marcauthorsarray; + $dat->{MARCSERIES} = $marcseriesarray; + $dat->{MARCURLS} = $marcurlsarray; + $dat->{HASAUTHORS} = $hasauthors; my ( $host, $relatedparts, $hostinfo ) = $biblio->get_marc_host; $dat->{HOSTITEMENTRIES} = $host; - $dat->{RELATEDPARTS} = $relatedparts; - $dat->{HOSTINFO} = $hostinfo; + $dat->{RELATEDPARTS} = $relatedparts; + $dat->{HOSTINFO} = $hostinfo; push( @results, $dat ); } @@ -110,8 +108,8 @@ my $resultsarray = \@results; $template->param( BIBLIO_RESULTS => $resultsarray, - csv_profiles => Koha::CsvProfiles->search({ type => 'marc', used_for => 'export_records' }), - bib_list => $bib_list, + csv_profiles => Koha::CsvProfiles->search( { type => 'marc', used_for => 'export_records' } ), + bib_list => $bib_list, ); output_html_with_http_headers $query, $cookie, $template->output; diff --git a/basket/downloadcart.pl b/basket/downloadcart.pl index 484b6741e7..94a6df8363 100755 --- a/basket/downloadcart.pl +++ b/basket/downloadcart.pl @@ -19,10 +19,10 @@ use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use Encode qw( encode ); -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use C4::Record; use C4::Ris qw( marc2ris ); @@ -33,32 +33,32 @@ use Koha::Biblios; use utf8; my $query = CGI->new; -my ( $template, $borrowernumber, $cookie ) = get_template_and_user ( +my ( $template, $borrowernumber, $cookie ) = get_template_and_user( { - template_name => "basket/downloadcart.tt", - query => $query, - type => "intranet", - flagsrequired => { catalogue => 1 }, + template_name => "basket/downloadcart.tt", + query => $query, + type => "intranet", + flagsrequired => { catalogue => 1 }, } ); my $bib_list = $query->param('bib_list'); -my $format = $query->param('format'); -my $dbh = C4::Context->dbh; +my $format = $query->param('format'); +my $dbh = C4::Context->dbh; -if ($bib_list && $format) { +if ( $bib_list && $format ) { my @bibs = split( /\//, $bib_list ); - my $marcflavour = C4::Context->preference('marcflavour'); + my $marcflavour = C4::Context->preference('marcflavour'); my $output; - # CSV - if ($format =~ /^\d+$/) { + # CSV + if ( $format =~ /^\d+$/ ) { - $output = marc2csv(\@bibs, $format); - - # Other formats + $output = marc2csv( \@bibs, $format ); + + # Other formats } else { foreach my $biblionumber (@bibs) { @@ -67,31 +67,31 @@ if ($bib_list && $format) { my $record = $biblio->metadata_record( { embed_items => 1 } ); next unless $record; - if ($format eq 'iso2709') { + if ( $format eq 'iso2709' ) { + #NOTE: If we don't explicitly UTF-8 encode the output, #the browser will guess the encoding, and it won't always choose UTF-8. - $output .= encode("UTF-8", $record->as_usmarc()) // q{}; - } - elsif ($format eq 'ris') { + $output .= encode( "UTF-8", $record->as_usmarc() ) // q{}; + } elsif ( $format eq 'ris' ) { $output .= marc2ris($record); - } - elsif ($format eq 'bibtex') { - $output .= marc2bibtex($record, $biblionumber); + } elsif ( $format eq 'bibtex' ) { + $output .= marc2bibtex( $record, $biblionumber ); } } } # If it was a CSV export we change the format after the export so the file extension is fine - $format = "csv" if ($format =~ m/^\d+$/); + $format = "csv" if ( $format =~ m/^\d+$/ ); print $query->header( - -type => 'application/octet-stream', - -'Content-Transfer-Encoding' => 'binary', - -attachment=>"cart.$format"); + -type => 'application/octet-stream', + -'Content-Transfer-Encoding' => 'binary', + -attachment => "cart.$format" + ); print $output; -} else { - $template->param(csv_profiles => Koha::CsvProfiles->search({ type => 'marc', used_for => 'export_records' })); - $template->param(bib_list => $bib_list); +} else { + $template->param( csv_profiles => Koha::CsvProfiles->search( { type => 'marc', used_for => 'export_records' } ) ); + $template->param( bib_list => $bib_list ); output_html_with_http_headers $query, $cookie, $template->output; } diff --git a/basket/sendbasket.pl b/basket/sendbasket.pl index d0c06c342f..ad8fd87e22 100755 --- a/basket/sendbasket.pl +++ b/basket/sendbasket.pl @@ -19,13 +19,13 @@ use Modern::Perl; use CGI qw ( -utf8 ); use Encode; -use Carp qw( carp ); +use Carp qw( carp ); use Try::Tiny qw( catch try ); use C4::Biblio qw( - GetMarcSubjects + GetMarcSubjects ); -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_and_exit output_html_with_http_headers ); use C4::Templates; use Koha::Biblios; @@ -42,7 +42,7 @@ my ( $template, $borrowernumber, $cookie ) = get_template_and_user( } ); -my $op = $query->param('op') || q{}; +my $op = $query->param('op') || q{}; my $bib_list = $query->param('bib_list') || ''; my $email_add = $query->param('email_add'); @@ -66,12 +66,10 @@ if ( $op eq "cud-send" && $email_add ) { if ( !defined $iso2709 ) { carp "Error sending mail: empty basket"; $template->param( error => 1 ); - } - elsif ( !defined $user_email or $user_email eq '' ) { + } elsif ( !defined $user_email or $user_email eq '' ) { carp "Error sending mail: sender's email address is invalid"; $template->param( error => 1 ); - } - else { + } else { my %loops = ( biblio => \@bibs, ); my %substitute = ( comment => $comment, ); @@ -110,8 +108,7 @@ if ( $op eq "cud-send" && $email_add ) { } $template->param( email_add => $email_add ); output_html_with_http_headers $query, $cookie, $template->output; -} -else { +} else { $template->param( bib_list => $bib_list, url => "/cgi-bin/koha/basket/sendbasket.pl", diff --git a/bookings/list.pl b/bookings/list.pl index 6333287e04..40c7ac4228 100755 --- a/bookings/list.pl +++ b/bookings/list.pl @@ -22,7 +22,7 @@ use Modern::Perl; use CGI qw ( -utf8 ); use C4::Output qw( output_html_with_http_headers ); -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); my $input = CGI->new; my ( $template, $borrowernumber, $cookie, $flags ) = get_template_and_user( diff --git a/catalogue/ISBDdetail.pl b/catalogue/ISBDdetail.pl index fd47a7e84c..5267b2a9e2 100755 --- a/catalogue/ISBDdetail.pl +++ b/catalogue/ISBDdetail.pl @@ -38,20 +38,19 @@ use Modern::Perl; use HTML::Entities; use C4::Auth qw( get_template_and_user ); use C4::Context; -use C4::Output qw( output_html_with_http_headers ); -use CGI qw ( -utf8 ); -use C4::Biblio qw( GetBiblioData GetISBDView ); +use C4::Output qw( output_html_with_http_headers ); +use CGI qw ( -utf8 ); +use C4::Biblio qw( GetBiblioData GetISBDView ); use C4::Serials qw( CountSubscriptionFromBiblionumber GetSubscription GetSubscriptionsFromBiblionumber ); -use C4::Search qw( z3950_search_args enabled_staff_search_views ); +use C4::Search qw( z3950_search_args enabled_staff_search_views ); use Koha::Biblios; use Koha::Patrons; use Koha::RecordProcessor; use Koha::Virtualshelves; - my $query = CGI->new; -my $dbh = C4::Context->dbh; +my $dbh = C4::Context->dbh; my $biblionumber = $query->param('biblionumber'); $biblionumber = HTML::Entities::encode($biblionumber); @@ -62,11 +61,11 @@ my ( $template, $loggedinuser, $cookie ) = get_template_and_user( template_name => "catalogue/ISBDdetail.tt", query => $query, type => "intranet", - flagsrequired => { catalogue => 1 }, + flagsrequired => { catalogue => 1 }, } ); -my $biblio = Koha::Biblios->find( $biblionumber ); +my $biblio = Koha::Biblios->find($biblionumber); unless ( $biblionumber && $biblio ) { # biblionumber invalid -> report and exit @@ -78,8 +77,7 @@ unless ( $biblionumber && $biblio ) { exit; } -my $record = - $biblio->metadata_record( { embed_items => 1, interface => 'intranet' } ); +my $record = $biblio->metadata_record( { embed_items => 1, interface => 'intranet' } ); if ( not defined $record ) { # biblionumber invalid -> report and exit @@ -91,15 +89,16 @@ if ( not defined $record ) { exit; } - my $framework = $biblio->frameworkcode; -my $res = GetISBDView({ - 'record' => $record, - 'template' => 'intranet', - 'framework' => $framework, -}); +my $res = GetISBDView( + { + 'record' => $record, + 'template' => 'intranet', + 'framework' => $framework, + } +); -if($query->cookie("holdfor")){ +if ( $query->cookie("holdfor") ) { my $holdfor_patron = Koha::Patrons->find( $query->cookie("holdfor") ); $template->param( holdfor => $query->cookie("holdfor"), @@ -107,7 +106,7 @@ if($query->cookie("holdfor")){ ); } -if( $query->cookie("searchToOrder") ){ +if ( $query->cookie("searchToOrder") ) { my ( $basketno, $vendorid ) = split( /\//, $query->cookie("searchToOrder") ); $template->param( searchtoorder_basketno => $basketno, @@ -117,9 +116,9 @@ if( $query->cookie("searchToOrder") ){ # count of item linked with biblio my $itemcount = $biblio->items->count; -$template->param( count => $itemcount); +$template->param( count => $itemcount ); my $subscriptionsnumber = CountSubscriptionFromBiblionumber($biblionumber); - + if ($subscriptionsnumber) { my $subscriptions = GetSubscriptionsFromBiblionumber($biblionumber); my $subscriptiontitle = $subscriptions->[0]{'bibliotitle'}; @@ -132,10 +131,10 @@ if ($subscriptionsnumber) { # get biblionumbers stored in the cart my @cart_list; -if($query->cookie("intranet_bib_list")){ +if ( $query->cookie("intranet_bib_list") ) { my $cart_list = $query->cookie("intranet_bib_list"); - @cart_list = split(/\//, $cart_list); - if ( grep {$_ eq $biblionumber} @cart_list) { + @cart_list = split( /\//, $cart_list ); + if ( grep { $_ eq $biblionumber } @cart_list ) { $template->param( incart => 1 ); } } @@ -155,21 +154,20 @@ my $some_public_shelves = Koha::Virtualshelves->get_some_shelves( } ); - $template->param( add_to_some_private_shelves => $some_private_shelves, add_to_some_public_shelves => $some_public_shelves, ); -$template->param ( +$template->param( ISBD => $res, biblionumber => $biblionumber, isbdview => 1, - z3950_search_params => C4::Search::z3950_search_args(GetBiblioData($biblionumber)), - ocoins => $biblio->get_coins, + z3950_search_params => C4::Search::z3950_search_args( GetBiblioData($biblionumber) ), + ocoins => $biblio->get_coins, C4::Search::enabled_staff_search_views, - searchid => scalar $query->param('searchid'), - biblio => $biblio, + searchid => scalar $query->param('searchid'), + biblio => $biblio, ); my $holds = $biblio->holds; diff --git a/catalogue/MARCdetail.pl b/catalogue/MARCdetail.pl index 0560fce965..bb599382b0 100755 --- a/catalogue/MARCdetail.pl +++ b/catalogue/MARCdetail.pl @@ -59,7 +59,7 @@ use C4::Biblio qw( GetMarcStructure ); use C4::Serials qw( CountSubscriptionFromBiblionumber GetSubscription GetSubscriptionsFromBiblionumber ); -use C4::Search qw( z3950_search_args enabled_staff_search_views ); +use C4::Search qw( z3950_search_args enabled_staff_search_views ); use Koha::Biblios; use Koha::BiblioFrameworks; @@ -73,24 +73,22 @@ my $query = CGI->new; my $dbh = C4::Context->dbh; my $biblionumber = $query->param('biblionumber'); $biblionumber = HTML::Entities::encode($biblionumber); -my $frameworkcode = $query->param('frameworkcode') // GetFrameworkCode( $biblionumber ); -my $popup = - $query->param('popup') - ; # if set to 1, then don't insert links, it's just to show the biblio +my $frameworkcode = $query->param('frameworkcode') // GetFrameworkCode($biblionumber); +my $popup = $query->param('popup'); # if set to 1, then don't insert links, it's just to show the biblio my $subscriptionid = $query->param('subscriptionid'); # open template my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "catalogue/MARCdetail.tt", - query => $query, - type => "intranet", - flagsrequired => { catalogue => 1 }, + template_name => "catalogue/MARCdetail.tt", + query => $query, + type => "intranet", + flagsrequired => { catalogue => 1 }, } ); -my $biblio_object = Koha::Biblios->find( $biblionumber ); # FIXME Should replace $biblio -my $record = $biblio_object ? $biblio_object->metadata_record( { embed_items => 1 } ) : undef; +my $biblio_object = Koha::Biblios->find($biblionumber); # FIXME Should replace $biblio +my $record = $biblio_object ? $biblio_object->metadata_record( { embed_items => 1 } ) : undef; if ( !$record ) { @@ -103,11 +101,10 @@ if ( !$record ) { exit; } +my $tagslib = &GetMarcStructure( 1, $frameworkcode ); +my $biblio = GetBiblioData($biblionumber); -my $tagslib = &GetMarcStructure(1,$frameworkcode); -my $biblio = GetBiblioData($biblionumber); - -if($query->cookie("holdfor")){ +if ( $query->cookie("holdfor") ) { my $holdfor_patron = Koha::Patrons->find( $query->cookie("holdfor") ); $template->param( holdfor => $query->cookie("holdfor"), @@ -115,7 +112,7 @@ if($query->cookie("holdfor")){ ); } -if( $query->cookie("searchToOrder") ){ +if ( $query->cookie("searchToOrder") ) { my ( $basketno, $vendorid ) = split( /\//, $query->cookie("searchToOrder") ); $template->param( searchtoorder_basketno => $basketno, @@ -127,14 +124,17 @@ $template->param( ocoins => $biblio_object->get_coins ); #count of item linked my $itemcount = $biblio_object->items->count; -$template->param( count => $itemcount, - bibliotitle => $biblio->{title}, ); +$template->param( + count => $itemcount, + bibliotitle => $biblio->{title}, +); my $frameworks = Koha::BiblioFrameworks->search( {}, { order_by => ['frameworktext'] } ); $template->param( frameworks => $frameworks, frameworkcode => $frameworkcode, ); + # fill arrays my @loop_data = (); @@ -156,7 +156,7 @@ for ( my $tabloop = 0 ; $tabloop <= 10 ; $tabloop++ ) { $subfield_data{marc_tag} = '000'; push( @subfields_data, \%subfield_data ); my %tag_data; - $tag_data{tag} = '000'; + $tag_data{tag} = '000'; $tag_data{tag_desc} = $tagslib->{'000'}->{lib}; my @tmp = @subfields_data; $tag_data{subfield} = \@tmp; @@ -169,57 +169,49 @@ for ( my $tabloop = 0 ; $tabloop <= 10 ; $tabloop++ ) { # if tag <10, there's no subfield, use the "@" trick if ( $fields[$x_i]->tag() < 10 ) { next - if ( - $tagslib->{ $fields[$x_i]->tag() }->{'@'}->{tab} ne $tabloop ); - next if ( $tagslib->{ $fields[$x_i]->tag() }->{'@'}->{hidden} =~ /-7|-4|-3|-2|2|3|5|8/); + if ( $tagslib->{ $fields[$x_i]->tag() }->{'@'}->{tab} ne $tabloop ); + next if ( $tagslib->{ $fields[$x_i]->tag() }->{'@'}->{hidden} =~ /-7|-4|-3|-2|2|3|5|8/ ); my %subfield_data; $subfield_data{marc_lib} = - $tagslib->{ $fields[$x_i]->tag() }->{'@'}->{lib}; + $tagslib->{ $fields[$x_i]->tag() }->{'@'}->{lib}; $subfield_data{marc_value} = $fields[$x_i]->data(); $subfield_data{marc_subfield} = '@'; $subfield_data{marc_tag} = $fields[$x_i]->tag(); push( @subfields_data, \%subfield_data ); - } - else { + } else { my @subf = $fields[$x_i]->subfields; # loop through each subfield for my $i ( 0 .. $#subf ) { $subf[$i][0] = "@" unless defined $subf[$i][0]; - next if ( $tagslib->{ $fields[$x_i]->tag() }->{ $subf[$i][0] }->{tab} // q{} ) ne $tabloop; # Note: defaulting to '0' changes behavior! next - if ( $tagslib->{ $fields[$x_i]->tag() }->{ $subf[$i][0] } - ->{hidden} =~ /-7|-4|-3|-2|2|3|5|8/); + if ( $tagslib->{ $fields[$x_i]->tag() }->{ $subf[$i][0] }->{tab} // q{} ) ne + $tabloop; # Note: defaulting to '0' changes behavior! + next + if ( $tagslib->{ $fields[$x_i]->tag() }->{ $subf[$i][0] }->{hidden} =~ /-7|-4|-3|-2|2|3|5|8/ ); my %subfield_data; $subfield_data{short_desc} = $tagslib->{ $fields[$x_i]->tag() }->{ $subf[$i][0] }->{lib}; $subfield_data{long_desc} = - $tagslib->{ $fields[$x_i]->tag() }->{ $subf[$i][0] }->{lib}; + $tagslib->{ $fields[$x_i]->tag() }->{ $subf[$i][0] }->{lib}; $subfield_data{link} = - $tagslib->{ $fields[$x_i]->tag() }->{ $subf[$i][0] }->{link}; + $tagslib->{ $fields[$x_i]->tag() }->{ $subf[$i][0] }->{link}; -# warn "tag : ".$tagslib->{$fields[$x_i]->tag()}." subfield :".$tagslib->{$fields[$x_i]->tag()}->{$subf[$i][0]}."lien koha? : "$subfield_data{link}; - if ( $tagslib->{ $fields[$x_i]->tag() }->{ $subf[$i][0] } - ->{isurl} ) - { + # warn "tag : ".$tagslib->{$fields[$x_i]->tag()}." subfield :".$tagslib->{$fields[$x_i]->tag()}->{$subf[$i][0]}."lien koha? : "$subfield_data{link}; + if ( $tagslib->{ $fields[$x_i]->tag() }->{ $subf[$i][0] }->{isurl} ) { $subfield_data{marc_value} = $subf[$i][1]; - $subfield_data{is_url} = 1; - } - elsif ( $tagslib->{ $fields[$x_i]->tag() }->{ $subf[$i][0] } - ->{kohafield} eq "biblioitems.isbn" ) - { + $subfield_data{is_url} = 1; + } elsif ( $tagslib->{ $fields[$x_i]->tag() }->{ $subf[$i][0] }->{kohafield} eq "biblioitems.isbn" ) { -# warn " tag : ".$tagslib->{$fields[$x_i]->tag()}." subfield :".$tagslib->{$fields[$x_i]->tag()}->{$subf[$i][0]}. "ISBN : ".$subf[$i][1]."PosttraitementISBN :".DisplayISBN($subf[$i][1]); + # warn " tag : ".$tagslib->{$fields[$x_i]->tag()}." subfield :".$tagslib->{$fields[$x_i]->tag()}->{$subf[$i][0]}. "ISBN : ".$subf[$i][1]."PosttraitementISBN :".DisplayISBN($subf[$i][1]); $subfield_data{marc_value} = $subf[$i][1]; - } - else { - if ( $tagslib->{ $fields[$x_i]->tag() }->{ $subf[$i][0] } - ->{authtypecode} ) - { + } else { + if ( $tagslib->{ $fields[$x_i]->tag() }->{ $subf[$i][0] }->{authtypecode} ) { $subfield_data{authority} = $fields[$x_i]->subfield(9); } - $subfield_data{marc_value} = - GetAuthorisedValueDesc( $fields[$x_i]->tag(), - $subf[$i][0], $subf[$i][1], '', $tagslib) || $subf[$i][1]; + $subfield_data{marc_value} = GetAuthorisedValueDesc( + $fields[$x_i]->tag(), + $subf[$i][0], $subf[$i][1], '', $tagslib + ) || $subf[$i][1]; } $subfield_data{marc_subfield} = $subf[$i][0]; @@ -228,22 +220,23 @@ for ( my $tabloop = 0 ; $tabloop <= 10 ; $tabloop++ ) { } } if ( $#subfields_data == 0 ) { - $subfields_data[0]->{marc_lib} = ''; -# $subfields_data[0]->{marc_subfield} = ''; + $subfields_data[0]->{marc_lib} = ''; + + # $subfields_data[0]->{marc_subfield} = ''; } - if ( $#subfields_data >= 0) { + if ( $#subfields_data >= 0 ) { my %tag_data; - if ( $fields[$x_i]->tag() eq $fields[ $x_i - 1 ]->tag() && (C4::Context->preference('LabelMARCView') eq 'economical')) { + if ( $fields[$x_i]->tag() eq $fields[ $x_i - 1 ]->tag() + && ( C4::Context->preference('LabelMARCView') eq 'economical' ) ) + { $tag_data{tag} = ""; - } - else { + } else { if ( C4::Context->preference('hide_marc') ) { $tag_data{tag} = $tagslib->{ $fields[$x_i]->tag() }->{lib}; - } - else { - $tag_data{tag} = $fields[$x_i]->tag(); - $tag_data{tag_ind} = C4::Koha::display_marc_indicators($fields[$x_i]); - $tag_data{tag_desc} = $tagslib->{ $fields[$x_i]->tag() }->{lib}; + } else { + $tag_data{tag} = $fields[$x_i]->tag(); + $tag_data{tag_ind} = C4::Koha::display_marc_indicators( $fields[$x_i] ); + $tag_data{tag_desc} = $tagslib->{ $fields[$x_i]->tag() }->{lib}; } } my @tmp = @subfields_data; @@ -261,8 +254,7 @@ for ( my $tabloop = 0 ; $tabloop <= 10 ; $tabloop++ ) { # warning : we may have differents number of columns in each row. Thus, we first build a hash, complete it if necessary # then construct template. my @fields = $record->fields(); -my %witness - ; #---- stores the list of subfields used at least once, with the "meaning" of the code +my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code my @item_subfield_codes; my @item_loop; @@ -274,49 +266,51 @@ foreach my $field (@fields) { # loop through each subfield for my $i ( 0 .. $#subf ) { next if ( $tagslib->{ $field->tag() }->{ $subf[$i][0] }->{tab} ne 10 ); - next if ( $tagslib->{ $field->tag() }->{ $subf[$i][0] }->{hidden} =~ /-7|-4|-3|-2|2|3|5|8/); + next if ( $tagslib->{ $field->tag() }->{ $subf[$i][0] }->{hidden} =~ /-7|-4|-3|-2|2|3|5|8/ ); push @item_subfield_codes, $subf[$i][0]; $witness{ $subf[$i][0] } = - $tagslib->{ $field->tag() }->{ $subf[$i][0] }->{lib}; + $tagslib->{ $field->tag() }->{ $subf[$i][0] }->{lib}; # Allow repeatables (BZ 13574) - if( $item->{$subf[$i][0]}) { - $item->{$subf[$i][0]} .= ' | '; + if ( $item->{ $subf[$i][0] } ) { + $item->{ $subf[$i][0] } .= ' | '; } else { - $item->{$subf[$i][0]} = q{}; + $item->{ $subf[$i][0] } = q{}; } - if( $tagslib->{$field->tag()}->{$subf[$i][0]}->{isurl} ) { - $item->{$subf[$i][0]} .= "$subf[$i][1]"; + if ( $tagslib->{ $field->tag() }->{ $subf[$i][0] }->{isurl} ) { + $item->{ $subf[$i][0] } .= "$subf[$i][1]"; } else { - $item->{ $subf[$i][0] } .= GetAuthorisedValueDesc( $field->tag(), $subf[$i][0], $subf[$i][1], '', $tagslib) || $subf[$i][1]; + $item->{ $subf[$i][0] } .= + GetAuthorisedValueDesc( $field->tag(), $subf[$i][0], $subf[$i][1], '', $tagslib ) || $subf[$i][1]; } my $kohafield = $tagslib->{ $field->tag() }->{ $subf[$i][0] }->{kohafield}; $item->{ $subf[$i][0] } = output_pref( { str => $item->{ $subf[$i][0] }, dateonly => 1 } ) - if grep { $kohafield eq $_ } - qw( items.dateaccessioned items.onloan items.datelastseen items.datelastborrowed items.replacementpricedate ); + if grep { $kohafield eq $_ } + qw( items.dateaccessioned items.onloan items.datelastseen items.datelastborrowed items.replacementpricedate ); } push @item_loop, $item if $item; } -my ($holdingbrtagf,$holdingbrtagsubf) = &GetMarcFromKohaField( "items.holdingbranch" ); -@item_loop = sort {$a->{$holdingbrtagsubf} cmp $b->{$holdingbrtagsubf}} @item_loop; +my ( $holdingbrtagf, $holdingbrtagsubf ) = &GetMarcFromKohaField("items.holdingbranch"); +@item_loop = sort { $a->{$holdingbrtagsubf} cmp $b->{$holdingbrtagsubf} } @item_loop; @item_subfield_codes = uniq @item_subfield_codes; + # fill item info my @item_header_loop; -for my $subfield_code ( @item_subfield_codes ) { +for my $subfield_code (@item_subfield_codes) { push @item_header_loop, $witness{$subfield_code}; - for my $item_data ( @item_loop ) { - $item_data->{$subfield_code} ||= " " + for my $item_data (@item_loop) { + $item_data->{$subfield_code} ||= " "; } } my $subscriptionscount = CountSubscriptionFromBiblionumber($biblionumber); if ($subscriptionscount) { - my $subscriptions = GetSubscriptionsFromBiblionumber($biblionumber); + my $subscriptions = GetSubscriptionsFromBiblionumber($biblionumber); my $subscriptiontitle = $subscriptions->[0]{'bibliotitle'}; $template->param( subscriptiontitle => $subscriptiontitle, @@ -327,10 +321,10 @@ if ($subscriptionscount) { # get biblionumbers stored in the cart my @cart_list; -if($query->cookie("intranet_bib_list")){ +if ( $query->cookie("intranet_bib_list") ) { my $cart_list = $query->cookie("intranet_bib_list"); - @cart_list = split(/\//, $cart_list); - if ( grep {$_ eq $biblionumber} @cart_list) { + @cart_list = split( /\//, $cart_list ); + if ( grep { $_ eq $biblionumber } @cart_list ) { $template->param( incart => 1 ); } } @@ -350,24 +344,23 @@ my $some_public_shelves = Koha::Virtualshelves->get_some_shelves( } ); - $template->param( add_to_some_private_shelves => $some_private_shelves, add_to_some_public_shelves => $some_public_shelves, ); -$template->param ( - item_loop => \@item_loop, - item_header_loop => \@item_header_loop, - item_subfield_codes => \@item_subfield_codes, - biblionumber => $biblionumber, - popup => $popup, - hide_marc => C4::Context->preference('hide_marc'), - marcview => 1, - z3950_search_params => C4::Search::z3950_search_args($biblio), - C4::Search::enabled_staff_search_views, - searchid => scalar $query->param('searchid'), - biblio => $biblio_object, +$template->param( + item_loop => \@item_loop, + item_header_loop => \@item_header_loop, + item_subfield_codes => \@item_subfield_codes, + biblionumber => $biblionumber, + popup => $popup, + hide_marc => C4::Context->preference('hide_marc'), + marcview => 1, + z3950_search_params => C4::Search::z3950_search_args($biblio), + C4::Search::enabled_staff_search_views, + searchid => scalar $query->param('searchid'), + biblio => $biblio_object, loggedinuser => $loggedinuser, ); diff --git a/catalogue/detail.pl b/catalogue/detail.pl index ec802ec049..d7d13b2f1d 100755 --- a/catalogue/detail.pl +++ b/catalogue/detail.pl @@ -15,7 +15,6 @@ # You should have received a copy of the GNU General Public License # along with Koha; if not, see . - use Modern::Perl; use CGI qw ( -utf8 ); @@ -31,17 +30,17 @@ use C4::Koha qw( GetNormalizedUPC ); use C4::Serials qw( CountSubscriptionFromBiblionumber SearchSubscriptions GetLatestSerials ); -use C4::Output qw( output_html_with_http_headers ); -use C4::Biblio qw( GetBiblioData GetFrameworkCode ); -use C4::Items qw( GetAnalyticsCount ); +use C4::Output qw( output_html_with_http_headers ); +use C4::Biblio qw( GetBiblioData GetFrameworkCode ); +use C4::Items qw( GetAnalyticsCount ); use C4::Reserves; -use C4::Serials qw( CountSubscriptionFromBiblionumber SearchSubscriptions GetLatestSerials ); -use C4::XISBN qw( get_xisbns ); +use C4::Serials qw( CountSubscriptionFromBiblionumber SearchSubscriptions GetLatestSerials ); +use C4::XISBN qw( get_xisbns ); use C4::External::Amazon qw( get_amazon_tld ); -use C4::Search qw( z3950_search_args enabled_staff_search_views new_record_from_zebra ); -use C4::Tags qw( get_tags ); -use C4::XSLT qw( XSLTParse4Display ); -use Koha::DateUtils qw( format_sqldatetime ); +use C4::Search qw( z3950_search_args enabled_staff_search_views new_record_from_zebra ); +use C4::Tags qw( get_tags ); +use C4::XSLT qw( XSLTParse4Display ); +use Koha::DateUtils qw( format_sqldatetime ); use C4::HTML5Media; use C4::CourseReserves qw( GetItemCourseReservesInfo ); use Koha::AuthorisedValues; @@ -68,19 +67,19 @@ my $analyze = $query->param('analyze'); my ( $template, $borrowernumber, $cookie, $flags ) = get_template_and_user( { - template_name => 'catalogue/detail.tt', - query => $query, - type => "intranet", - flagsrequired => { catalogue => 1 }, + template_name => 'catalogue/detail.tt', + query => $query, + type => "intranet", + flagsrequired => { catalogue => 1 }, } ); # Determine if we should be offering any enhancement plugin buttons if ( C4::Context->config('enable_plugins') ) { + # Only pass plugins that can offer a toolbar button - my @plugins = Koha::Plugins->new()->GetPlugins({ - method => 'intranet_catalog_biblio_enhancements_toolbar_button' - }); + my @plugins = + Koha::Plugins->new()->GetPlugins( { method => 'intranet_catalog_biblio_enhancements_toolbar_button' } ); $template->param( plugins => \@plugins, ); @@ -89,30 +88,35 @@ if ( C4::Context->config('enable_plugins') ) { my $activetab = $query->param('activetab'); my $biblionumber = $query->param('biblionumber'); $biblionumber = HTML::Entities::encode($biblionumber); -my $biblio = Koha::Biblios->find( $biblionumber ); +my $biblio = Koha::Biblios->find($biblionumber); $template->param( biblio => $biblio, activetab => $activetab, ); -unless ( $biblio ) { +unless ($biblio) { + # biblionumber invalid -> report and exit - $template->param( blocking_error => 'unknown_biblionumber', - biblionumber => $biblionumber ); + $template->param( + blocking_error => 'unknown_biblionumber', + biblionumber => $biblionumber + ); output_html_with_http_headers $query, $cookie, $template->output; exit; } -my $marc_record = eval { $biblio->metadata->record }; +my $marc_record = eval { $biblio->metadata->record }; my $invalid_marc_record = $@ || !$marc_record; if ($invalid_marc_record) { $template->param( decoding_error => $@ ); my $marc_xml = C4::Charset::StripNonXmlChars( $biblio->metadata->metadata ); $marc_record = eval { - MARC::Record::new_from_xml( $marc_xml, 'UTF-8', - C4::Context->preference('marcflavour') ); + MARC::Record::new_from_xml( + $marc_xml, 'UTF-8', + C4::Context->preference('marcflavour') + ); }; } @@ -126,22 +130,20 @@ if ( $op eq 'set_item_group' ) { if ($item_group_item) { $item_group_item->item_group_id($item_group_id); - } - else { + } else { $item_group_item = Koha::Biblio::ItemGroup::Item->new( { - item_id => $item_id, - item_group_id => $item_group_id, + item_id => $item_id, + item_group_id => $item_group_id, } ); } $item_group_item->store(); } -} -elsif ( $op eq 'unset_item_group' ) { - my $item_group_id = $query->param('item_group_id'); - my @itemnumbers = $query->multi_param('itemnumber'); +} elsif ( $op eq 'unset_item_group' ) { + my $item_group_id = $query->param('item_group_id'); + my @itemnumbers = $query->multi_param('itemnumber'); foreach my $item_id (@itemnumbers) { my $item_group_item = Koha::Biblio::ItemGroup::Items->find( { item_id => $item_id } ); @@ -149,9 +151,9 @@ elsif ( $op eq 'unset_item_group' ) { } } -if($query->cookie("holdfor")){ +if ( $query->cookie("holdfor") ) { my $holdfor_patron = Koha::Patrons->find( $query->cookie("holdfor") ); - if ( $holdfor_patron ) { + if ($holdfor_patron) { $template->param( holdfor => $query->cookie("holdfor"), holdfor_patron => $holdfor_patron, @@ -159,7 +161,7 @@ if($query->cookie("holdfor")){ } } -if($query->cookie("searchToOrder")){ +if ( $query->cookie("searchToOrder") ) { my ( $basketno, $vendorid ) = split( /\//, $query->cookie("searchToOrder") ); $template->param( searchtoorder_basketno => $basketno, @@ -178,42 +180,42 @@ $template->param( ocoins => !$invalid_marc_record ? $biblio->get_coins : undef ) # some useful variables for enhanced content; # in each case, we're grabbing the first value we find in # the record and normalizing it -my $upc = GetNormalizedUPC($marc_record,$marcflavour); -my $ean = GetNormalizedEAN($marc_record,$marcflavour); -my $oclc = GetNormalizedOCLCNumber($marc_record,$marcflavour); -my $isbn = GetNormalizedISBN(undef,$marc_record,$marcflavour); +my $upc = GetNormalizedUPC( $marc_record, $marcflavour ); +my $ean = GetNormalizedEAN( $marc_record, $marcflavour ); +my $oclc = GetNormalizedOCLCNumber( $marc_record, $marcflavour ); +my $isbn = GetNormalizedISBN( undef, $marc_record, $marcflavour ); my $content_identifier_exists; if ( $isbn or $ean or $oclc or $upc ) { $content_identifier_exists = 1; } $template->param( - normalized_upc => $upc, - normalized_ean => $ean, - normalized_oclc => $oclc, - normalized_isbn => $isbn, - content_identifier_exists => $content_identifier_exists, + normalized_upc => $upc, + normalized_ean => $ean, + normalized_oclc => $oclc, + normalized_isbn => $isbn, + content_identifier_exists => $content_identifier_exists, ); -my $itemtypes = { map { $_->itemtype => $_ } @{ Koha::ItemTypes->search_with_localization->as_list } }; -my $patron = Koha::Patrons->find( $borrowernumber ); +my $itemtypes = { map { $_->itemtype => $_ } @{ Koha::ItemTypes->search_with_localization->as_list } }; +my $patron = Koha::Patrons->find($borrowernumber); my $include_lost_items = !$patron->category->hidelostitems || $showallitems; -my $items_params = { +my $items_params = { ( $invalid_marc_record ? () : ( host_items => 1 ) ), }; -my $all_items = $biblio->items($items_params); -my $items_to_display = $all_items->search({ $include_lost_items ? () : ( itemlost => 0 ) }); +my $all_items = $biblio->items($items_params); +my $items_to_display = $all_items->search( { $include_lost_items ? () : ( itemlost => 0 ) } ); my $dat = &GetBiblioData($biblionumber); #is biblio a collection and are bundles enabled my $leader = $marc_record->leader(); -$dat->{bundlesEnabled} = ( ( substr( $leader, 7, 1 ) eq 'c' ) - && C4::Context->preference('BundleNotLoanValue') ) ? 1 : 0; +$dat->{bundlesEnabled} = + ( ( substr( $leader, 7, 1 ) eq 'c' ) && C4::Context->preference('BundleNotLoanValue') ) ? 1 : 0; #coping with subscriptions my $subscriptionsnumber = CountSubscriptionFromBiblionumber($biblionumber); -my @subscriptions = SearchSubscriptions({ biblionumber => $biblionumber, orderby => 'title' }); +my @subscriptions = SearchSubscriptions( { biblionumber => $biblionumber, orderby => 'title' } ); my @subs; foreach my $subscription (@subscriptions) { @@ -228,12 +230,13 @@ foreach my $subscription (@subscriptions) { $cell{callnumber} = $subscription->{callnumber}; $cell{location} = $subscription->{location}; $cell{closed} = $subscription->{closed}; + #get the three latest serials. - $serials_to_display = $subscription->{staffdisplaycount}; - $serials_to_display = C4::Context->preference('StaffSerialIssueDisplayCount') unless $serials_to_display; + $serials_to_display = $subscription->{staffdisplaycount}; + $serials_to_display = C4::Context->preference('StaffSerialIssueDisplayCount') unless $serials_to_display; $cell{staffdisplaycount} = $serials_to_display; $cell{latestserials} = - GetLatestSerials( $subscription->{subscriptionid}, $serials_to_display ); + GetLatestSerials( $subscription->{subscriptionid}, $serials_to_display ); push @subs, \%cell; } @@ -241,32 +244,37 @@ foreach my $subscription (@subscriptions) { my $showcomp = C4::Context->preference('ShowComponentRecords'); my $show_analytics; if ( $showcomp eq 'both' || $showcomp eq 'staff' ) { - if ( my $components = !$invalid_marc_record ? $biblio->get_marc_components(C4::Context->preference('MaxComponentRecords')) : undef ) { - $show_analytics = 1 if @{$components}; # just show link when having results - $template->param( analytics_error => 1 ) if grep { $_->message eq 'component_search' } @{$biblio->object_messages}; + if ( my $components = + !$invalid_marc_record ? $biblio->get_marc_components( C4::Context->preference('MaxComponentRecords') ) : undef ) + { + $show_analytics = 1 if @{$components}; # just show link when having results + $template->param( analytics_error => 1 ) + if grep { $_->message eq 'component_search' } @{ $biblio->object_messages }; my $parts; for my $part ( @{$components} ) { $part = C4::Search::new_record_from_zebra( 'biblioserver', $part ); - my $id = Koha::SearchEngine::Search::extract_biblionumber( $part ); + my $id = Koha::SearchEngine::Search::extract_biblionumber($part); push @{$parts}, - XSLTParse4Display( + XSLTParse4Display( { biblionumber => $id, record => $part, xsl_syspref => "XSLTResultsDisplay", fix_amps => 1, } - ); + ); } $template->param( ComponentParts => $parts ); my ( $comp_query, $comp_query_str, $comp_sort ) = $biblio->get_components_query; my $cpq = $comp_query_str . "&sort_by=" . $comp_sort; $template->param( ComponentPartsQuery => $cpq ); } -} else { # check if we should show analytics anyway - $show_analytics = 1 if !$invalid_marc_record && @{$biblio->get_marc_components(1)}; # count matters here, results does not - $template->param( analytics_error => 1 ) if grep { $_->message eq 'component_search' } @{$biblio->object_messages}; +} else { # check if we should show analytics anyway + $show_analytics = 1 + if !$invalid_marc_record && @{ $biblio->get_marc_components(1) }; # count matters here, results does not + $template->param( analytics_error => 1 ) + if grep { $_->message eq 'component_search' } @{ $biblio->object_messages }; } # Display volumes link @@ -279,13 +287,15 @@ my $xslt_variables = { }; $template->param( XSLTDetailsDisplay => '1', - XSLTBloc => XSLTParse4Display({ - biblionumber => $biblionumber, - record => $marc_record, - xsl_syspref => "XSLTDetailsDisplay", - fix_amps => 1, - xslt_variables => $xslt_variables, - }), + XSLTBloc => XSLTParse4Display( + { + biblionumber => $biblionumber, + record => $marc_record, + xsl_syspref => "XSLTDetailsDisplay", + fix_amps => 1, + xslt_variables => $xslt_variables, + } + ), ); # Get acquisition details @@ -293,7 +303,7 @@ if ( C4::Context->preference('AcquisitionDetails') ) { my $orders = Koha::Acquisition::Orders->search( { biblionumber => $biblionumber }, { - join => 'basketno', + join => 'basketno', order_by => 'basketno.booksellerid' } ); # GetHistory sorted by aqbooksellerid, but does it make sense? @@ -310,11 +320,9 @@ if ( C4::Context->preference('suggestion') ) { biblionumber => $biblionumber, archived => 0, }, - { - order_by => { -desc => 'suggesteddate' } - } + { order_by => { -desc => 'suggesteddate' } } ); - my $nb_archived_suggestions = Koha::Suggestions->search({ biblionumber => $biblionumber, archived => 1 })->count; + my $nb_archived_suggestions = Koha::Suggestions->search( { biblionumber => $biblionumber, archived => 1 } )->count; $template->param( suggestions => $suggestions, nb_archived_suggestions => $nb_archived_suggestions ); } @@ -324,13 +332,14 @@ if ( defined $dat->{'itemtype'} ) { if ( C4::Context->preference('SeparateHoldings') ) { my $SeparateHoldingsBranch = C4::Context->preference('SeparateHoldingsBranch') || 'homebranch'; - my $other_holdings_count = $items_to_display->search({ $SeparateHoldingsBranch => { '!=' => C4::Context->userenv->{branch} } })->count; + my $other_holdings_count = + $items_to_display->search( { $SeparateHoldingsBranch => { '!=' => C4::Context->userenv->{branch} } } )->count; $template->param( other_holdings_count => $other_holdings_count ); } $template->param( - count => $all_items->count, # FIXME 'count' is used in catalog-strings.inc - # But it's not a meaningful variable, we should rename it there - all_items_count => $all_items->count, + count => $all_items->count, # FIXME 'count' is used in catalog-strings.inc + # But it's not a meaningful variable, we should rename it there + all_items_count => $all_items->count, items_to_display_count => $items_to_display->count, ); @@ -349,43 +358,42 @@ my $some_public_shelves = Koha::Virtualshelves->get_some_shelves( } ); - $template->param( add_to_some_private_shelves => $some_private_shelves, add_to_some_public_shelves => $some_public_shelves, ); $template->param( - MARCNOTES => !$invalid_marc_record ? $biblio->get_marc_notes() : undef, - z3950_search_params => C4::Search::z3950_search_args($dat), + MARCNOTES => !$invalid_marc_record ? $biblio->get_marc_notes() : undef, + z3950_search_params => C4::Search::z3950_search_args($dat), C4::Search::enabled_staff_search_views, ); -if (C4::Context->preference("AlternateHoldingsField") && $items_to_display->count == 0) { - my $fieldspec = C4::Context->preference("AlternateHoldingsField"); - my $subfields = substr $fieldspec, 3; - my $holdingsep = C4::Context->preference("AlternateHoldingsSeparator") || ' '; +if ( C4::Context->preference("AlternateHoldingsField") && $items_to_display->count == 0 ) { + my $fieldspec = C4::Context->preference("AlternateHoldingsField"); + my $subfields = substr $fieldspec, 3; + my $holdingsep = C4::Context->preference("AlternateHoldingsSeparator") || ' '; my @alternateholdingsinfo = (); - my @holdingsfields = $marc_record->field(substr $fieldspec, 0, 3); + my @holdingsfields = $marc_record->field( substr $fieldspec, 0, 3 ); for my $field (@holdingsfields) { - my %holding = ( holding => '' ); + my %holding = ( holding => '' ); my $havesubfield = 0; - for my $subfield ($field->subfields()) { - if ((index $subfields, $$subfield[0]) >= 0) { - $holding{'holding'} .= $holdingsep if (length $holding{'holding'} > 0); + for my $subfield ( $field->subfields() ) { + if ( ( index $subfields, $$subfield[0] ) >= 0 ) { + $holding{'holding'} .= $holdingsep if ( length $holding{'holding'} > 0 ); $holding{'holding'} .= $$subfield[1]; $havesubfield++; } } if ($havesubfield) { - push(@alternateholdingsinfo, \%holding); + push( @alternateholdingsinfo, \%holding ); } } $template->param( - ALTERNATEHOLDINGS => \@alternateholdingsinfo, - ); + ALTERNATEHOLDINGS => \@alternateholdingsinfo, + ); } if ( C4::Context->preference('OPACComments') ) { @@ -426,23 +434,23 @@ foreach ( keys %{$dat} ) { # does not work: my %views_enabled = map { $_ => 1 } $template->query(loop => 'EnableViews'); # method query not found?!?! -$template->param( AmazonTld => get_amazon_tld() ) if ( C4::Context->preference("AmazonCoverImages")); +$template->param( AmazonTld => get_amazon_tld() ) if ( C4::Context->preference("AmazonCoverImages") ); $template->param( - biblionumber => $biblionumber, - ($analyze? 'analyze':'detailview') =>1, - subscriptions => \@subs, - subscriptionsnumber => $subscriptionsnumber, - subscriptiontitle => $dat->{title}, - searchid => scalar $query->param('searchid'), + biblionumber => $biblionumber, + ( $analyze ? 'analyze' : 'detailview' ) => 1, + subscriptions => \@subs, + subscriptionsnumber => $subscriptionsnumber, + subscriptiontitle => $dat->{title}, + searchid => scalar $query->param('searchid'), ); # Lists -if (C4::Context->preference("virtualshelves") ) { +if ( C4::Context->preference("virtualshelves") ) { my $shelves = Koha::Virtualshelves->search( { biblionumber => $biblionumber, - public => 1, + public => 1, }, { join => 'virtualshelfcontents', @@ -452,38 +460,41 @@ if (C4::Context->preference("virtualshelves") ) { } # XISBN Stuff -if (C4::Context->preference("FRBRizeEditions")==1) { - eval { - $template->param( - XISBNS => scalar get_xisbns($isbn, $biblionumber) - ); - }; +if ( C4::Context->preference("FRBRizeEditions") == 1 ) { + eval { $template->param( XISBNS => scalar get_xisbns( $isbn, $biblionumber ) ); }; if ($@) { warn "XISBN Failed $@"; } } if ( C4::Context->preference("LocalCoverImages") == 1 ) { my $images = $biblio->cover_images; $template->param( - localimages => $biblio->cover_images->search( - {}, { order_by => [ \"COALESCE(itemnumber, 0, 1)", 'timestamp' ] } - ), + localimages => + $biblio->cover_images->search( {}, { order_by => [ \"COALESCE(itemnumber, 0, 1)", 'timestamp' ] } ), ); } # HTML5 Media -if ( (C4::Context->preference("HTML5MediaEnabled") eq 'both') or (C4::Context->preference("HTML5MediaEnabled") eq 'staff') ) { - $template->param( C4::HTML5Media->gethtml5media($marc_record)); +if ( ( C4::Context->preference("HTML5MediaEnabled") eq 'both' ) + or ( C4::Context->preference("HTML5MediaEnabled") eq 'staff' ) ) +{ + $template->param( C4::HTML5Media->gethtml5media($marc_record) ); } # Displaying tags my $tag_quantity; -if (C4::Context->preference('TagsEnabled') and $tag_quantity = C4::Context->preference('TagsShowOnDetail')) { +if ( C4::Context->preference('TagsEnabled') and $tag_quantity = C4::Context->preference('TagsShowOnDetail') ) { $template->param( - TagsEnabled => 1, + TagsEnabled => 1, TagsShowOnDetail => $tag_quantity ); - $template->param(TagLoop => get_tags({biblionumber=>$biblionumber, approved=>1, - 'sort'=>'-weight', limit=>$tag_quantity})); + $template->param( + TagLoop => get_tags( + { + biblionumber => $biblionumber, approved => 1, + 'sort' => '-weight', limit => $tag_quantity + } + ) + ); } #we only need to pass the number of holds to the template @@ -492,18 +503,18 @@ $template->param( holdcount => $holds->count ); # Check if there are any ILL requests connected to the biblio my $illrequests = - C4::Context->preference('ILLModule') - ? Koha::ILL::Requests->search( { biblio_id => $biblionumber } ) - : []; + C4::Context->preference('ILLModule') + ? Koha::ILL::Requests->search( { biblio_id => $biblionumber } ) + : []; $template->param( illrequests => $illrequests ); # get biblionumbers stored in the cart my @cart_list; -if($query->cookie("intranet_bib_list")){ +if ( $query->cookie("intranet_bib_list") ) { my $cart_list = $query->cookie("intranet_bib_list"); - @cart_list = split(/\//, $cart_list); - if ( grep {$_ eq $biblionumber} @cart_list) { + @cart_list = split( /\//, $cart_list ); + if ( grep { $_ eq $biblionumber } @cart_list ) { $template->param( incart => 1 ); } } @@ -514,17 +525,14 @@ if ( C4::Context->preference('UseCourseReserves') ) { } my @libraries = $patron->libraries_where_can_edit_items; -$template->param(can_edit_items_from => \@libraries); +$template->param( can_edit_items_from => \@libraries ); -my @itemtypes = Koha::ItemTypes->search->as_list; -my %item_type_image_locations = map { - $_->itemtype => $_->image_location('intranet') -} @itemtypes; -$template->param(item_type_image_locations => \%item_type_image_locations); +my @itemtypes = Koha::ItemTypes->search->as_list; +my %item_type_image_locations = map { $_->itemtype => $_->image_location('intranet') } @itemtypes; +$template->param( item_type_image_locations => \%item_type_image_locations ); +$template->param( found1 => scalar $query->param('found1') ); -$template->param(found1 => scalar $query->param('found1') ); - -$template->param(biblio => $biblio); +$template->param( biblio => $biblio ); output_html_with_http_headers $query, $cookie, $template->output; diff --git a/catalogue/export.pl b/catalogue/export.pl index b9fea04dfc..cd81ec3b53 100755 --- a/catalogue/export.pl +++ b/catalogue/export.pl @@ -4,86 +4,79 @@ use Modern::Perl; use C4::Record; use C4::Auth qw( get_template_and_user ); use C4::Output; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Ris qw( marc2ris ); - - my $query = CGI->new; -my ( $template, $loggedinuser, $cookie ) = get_template_and_user({ - template_name => "tools/export.tt", - query => $query, - type => "intranet", - flagsrequired => { catalogue => 1 }, - }); +my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "tools/export.tt", + query => $query, + type => "intranet", + flagsrequired => { catalogue => 1 }, + } +); -my $op=$query->param("op"); -my $format=$query->param("format"); -my $error = ''; -if ($op eq "export") { +my $op = $query->param("op"); +my $format = $query->param("format"); +my $error = ''; +if ( $op eq "export" ) { my $biblionumber = $query->param("bib"); - if ($biblionumber){ - my $file_id = $biblionumber; - my $file_pre = "bib-"; + if ($biblionumber) { + my $file_id = $biblionumber; + my $file_pre = "bib-"; - my $biblio = Koha::Biblios->find($biblionumber); - my $marc = $biblio->metadata_record( { embed_items => 1 } ); + my $biblio = Koha::Biblios->find($biblionumber); + my $marc = $biblio->metadata_record( { embed_items => 1 } ); - my $metadata_extractor = $biblio->metadata_extractor; + my $metadata_extractor = $biblio->metadata_extractor; - if ( C4::Context->preference('DefaultSaveRecordFileID') eq 'controlnumber' ) { - my $control_num = $metadata_extractor->get_control_number(); - if ($control_num) { - $file_id = $control_num; - $file_pre = "record-"; - } + if ( C4::Context->preference('DefaultSaveRecordFileID') eq 'controlnumber' ) { + my $control_num = $metadata_extractor->get_control_number(); + if ($control_num) { + $file_id = $control_num; + $file_pre = "record-"; } - - if ($format =~ /endnote/) { - $marc = marc2endnote($marc); - $format = 'endnote'; - } - elsif ($format =~ /marcxml/) { - $marc = marc2marcxml($marc); - $format = "marcxml"; - } - elsif ($format=~ /mods/) { - $marc = marc2modsxml($marc); - $format = "mods"; - } - elsif ($format =~ /ris/) { - $marc = marc2ris($marc); - $format = "ris"; - } - elsif ($format =~ /bibtex/) { - $marc = marc2bibtex($marc); - $format = "bibtex"; - } - elsif ($format =~ /dc$/) { - $marc = marc2dcxml(undef, undef, $biblionumber, $format); - $format = "dublin-core.xml"; - } - elsif ($format =~ /marc8/) { - $marc = changeEncoding($marc,"MARC","MARC21","MARC-8"); - $marc = $marc->as_usmarc(); - $format = "marc8"; - } - elsif ($format =~ /utf8/) { - C4::Charset::SetUTF8Flag($marc, 1); - $marc = $marc->as_usmarc(); - $format = "utf8"; - } - elsif ($format =~ /marcstd/) { - C4::Charset::SetUTF8Flag($marc,1); - ($error, $marc) = marc2marc($marc, 'marcstd', C4::Context->preference('marcflavour')); - $format = "marcstd"; - } - if ( $format =~ /utf8/ or $format =~ /marcstd/ ) { - binmode STDOUT, ':encoding(UTF-8)'; - } - print $query->header( - -type => 'application/octet-stream', - -attachment=>"$file_pre$file_id.$format"); - print $marc; } + + if ( $format =~ /endnote/ ) { + $marc = marc2endnote($marc); + $format = 'endnote'; + } elsif ( $format =~ /marcxml/ ) { + $marc = marc2marcxml($marc); + $format = "marcxml"; + } elsif ( $format =~ /mods/ ) { + $marc = marc2modsxml($marc); + $format = "mods"; + } elsif ( $format =~ /ris/ ) { + $marc = marc2ris($marc); + $format = "ris"; + } elsif ( $format =~ /bibtex/ ) { + $marc = marc2bibtex($marc); + $format = "bibtex"; + } elsif ( $format =~ /dc$/ ) { + $marc = marc2dcxml( undef, undef, $biblionumber, $format ); + $format = "dublin-core.xml"; + } elsif ( $format =~ /marc8/ ) { + $marc = changeEncoding( $marc, "MARC", "MARC21", "MARC-8" ); + $marc = $marc->as_usmarc(); + $format = "marc8"; + } elsif ( $format =~ /utf8/ ) { + C4::Charset::SetUTF8Flag( $marc, 1 ); + $marc = $marc->as_usmarc(); + $format = "utf8"; + } elsif ( $format =~ /marcstd/ ) { + C4::Charset::SetUTF8Flag( $marc, 1 ); + ( $error, $marc ) = marc2marc( $marc, 'marcstd', C4::Context->preference('marcflavour') ); + $format = "marcstd"; + } + if ( $format =~ /utf8/ or $format =~ /marcstd/ ) { + binmode STDOUT, ':encoding(UTF-8)'; + } + print $query->header( + -type => 'application/octet-stream', + -attachment => "$file_pre$file_id.$format" + ); + print $marc; + } } diff --git a/catalogue/getitem-ajax.pl b/catalogue/getitem-ajax.pl index 9dad680e0c..d09b4bec30 100755 --- a/catalogue/getitem-ajax.pl +++ b/catalogue/getitem-ajax.pl @@ -18,10 +18,10 @@ # along with Koha; if not, see . use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use JSON qw( to_json ); -use C4::Auth qw( check_api_auth ); +use C4::Auth qw( check_api_auth ); use C4::Biblio qw( GetMarcStructure ); use C4::Output qw( output_with_http_headers ); use Koha::Libraries; @@ -33,49 +33,55 @@ use Koha::ItemTypes; my $cgi = CGI->new; my ( $status, $cookie, $sessionID ) = C4::Auth::check_api_auth( $cgi, { acquisition => 'order_receive' } ); -unless ($status eq "ok") { - print $cgi->header(-type => 'application/json', -status => '403 Forbidden'); - print to_json({ auth_status => $status }); +unless ( $status eq "ok" ) { + print $cgi->header( -type => 'application/json', -status => '403 Forbidden' ); + print to_json( { auth_status => $status } ); exit 0; } -my $item = {}; +my $item = {}; my $itemnumber = $cgi->param('itemnumber'); my $item_unblessed = {}; -if($itemnumber) { - my $acq_fw = GetMarcStructure(1, 'ACQ'); - my $fw = ($acq_fw) ? 'ACQ' : ''; - $item = Koha::Items->find($itemnumber); +if ($itemnumber) { + my $acq_fw = GetMarcStructure( 1, 'ACQ' ); + my $fw = ($acq_fw) ? 'ACQ' : ''; + $item = Koha::Items->find($itemnumber); $item_unblessed = $item->unblessed; # FIXME Not needed, call home_branch and holding_branch in the templates instead - if($item->homebranch) { # This test should not be needed, homebranch and holdingbranch are mandatory + if ( $item->homebranch ) { # This test should not be needed, homebranch and holdingbranch are mandatory $item_unblessed->{homebranchname} = $item->home_branch->branchname; } - if($item->holdingbranch) { + if ( $item->holdingbranch ) { $item_unblessed->{holdingbranchname} = $item->holding_branch->branchname; } my $descriptions; - $descriptions = Koha::AuthorisedValues->get_description_by_koha_field({ frameworkcode => $fw, kohafield => 'items.notforloan', authorised_value => $item->notforloan }); + $descriptions = Koha::AuthorisedValues->get_description_by_koha_field( + { frameworkcode => $fw, kohafield => 'items.notforloan', authorised_value => $item->notforloan } ); $item_unblessed->{notforloan} = $descriptions->{lib} // ''; - $descriptions = Koha::AuthorisedValues->get_description_by_koha_field({ frameworkcode => $fw, kohafield => 'items.restricted', authorised_value => $item->restricted }); + $descriptions = Koha::AuthorisedValues->get_description_by_koha_field( + { frameworkcode => $fw, kohafield => 'items.restricted', authorised_value => $item->restricted } ); $item_unblessed->{restricted} = $descriptions->{lib} // ''; - $descriptions = Koha::AuthorisedValues->get_description_by_koha_field({ frameworkcode => $fw, kohafield => 'items.location', authorised_value => $item->location }); + $descriptions = Koha::AuthorisedValues->get_description_by_koha_field( + { frameworkcode => $fw, kohafield => 'items.location', authorised_value => $item->location } ); $item_unblessed->{location} = $descriptions->{lib} // ''; - $descriptions = Koha::AuthorisedValues->get_description_by_koha_field({ frameworkcode => $fw, kohafield => 'items.ccode', authorised_value => $item->ccode }); + $descriptions = Koha::AuthorisedValues->get_description_by_koha_field( + { frameworkcode => $fw, kohafield => 'items.ccode', authorised_value => $item->ccode } ); $item_unblessed->{collection} = $descriptions->{lib} // ''; - $descriptions = Koha::AuthorisedValues->get_description_by_koha_field({ frameworkcode => $fw, kohafield => 'items.materials', authorised_value => $item->materials }); + $descriptions = Koha::AuthorisedValues->get_description_by_koha_field( + { frameworkcode => $fw, kohafield => 'items.materials', authorised_value => $item->materials } ); $item_unblessed->{materials} = $descriptions->{lib} // ''; my $itemtype = Koha::ItemTypes->find( $item->effective_itemtype ); + # We should not do that here, but call ->itemtype->description when needed instea - $item_unblessed->{itemtype} = $itemtype->description; # FIXME Should not it be translated_description? + $item_unblessed->{itemtype} = $itemtype->description; # FIXME Should not it be translated_description? } my $json_text = to_json( $item_unblessed, { utf8 => 1 } ); diff --git a/catalogue/image.pl b/catalogue/image.pl index af950a6534..4b13425e2e 100755 --- a/catalogue/image.pl +++ b/catalogue/image.pl @@ -65,19 +65,18 @@ imagenumber, a random image is selected. =cut -my ( $image ); +my ($image); if ( C4::Context->preference("LocalCoverImages") ) { - my $imagenumber = $input->param('imagenumber'); + my $imagenumber = $input->param('imagenumber'); my $biblionumber = $input->param('biblionumber'); if ( defined $imagenumber ) { $imagenumber = $input->param('imagenumber'); - $image = Koha::CoverImages->find($imagenumber); + $image = Koha::CoverImages->find($imagenumber); unless ($image) { print $input->redirect("/cgi-bin/koha/errors/404.pl"); exit; } - } - elsif ( defined $biblionumber ) { + } elsif ( defined $biblionumber ) { my $biblio = Koha::Biblios->find($biblionumber); unless ($biblio) { print $input->redirect("/cgi-bin/koha/errors/404.pl"); @@ -93,14 +92,14 @@ if ( C4::Context->preference("LocalCoverImages") ) { $image ||= Koha::CoverImages->no_image; my $image_data = - $input->param('thumbnail') - ? $image->thumbnail - : $image->imagefile; + $input->param('thumbnail') + ? $image->thumbnail + : $image->imagefile; print $input->header( - -type => $image->mimetype, - -expires => '+30m', - -Content_Length => length($image_data) + -type => $image->mimetype, + -expires => '+30m', + -Content_Length => length($image_data) ), $image_data; =head1 AUTHOR diff --git a/catalogue/imageviewer.pl b/catalogue/imageviewer.pl index fc65a1ac07..cde3442c8e 100755 --- a/catalogue/imageviewer.pl +++ b/catalogue/imageviewer.pl @@ -19,8 +19,8 @@ use Modern::Perl; -use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use C4::Search qw( enabled_staff_search_views ); @@ -31,18 +31,19 @@ use Koha::Patrons; my $query = CGI->new; my ( $template, $borrowernumber, $cookie ) = get_template_and_user( { - template_name => "catalogue/imageviewer.tt", - query => $query, - type => "intranet", - flagsrequired => { catalogue => 1 }, + template_name => "catalogue/imageviewer.tt", + query => $query, + type => "intranet", + flagsrequired => { catalogue => 1 }, } ); -my $itemnumber = $query->param('itemnumber'); -my $biblionumber = $query->param('biblionumber') || $query->param('bib') || Koha::Items->find($itemnumber)->biblionumber; +my $itemnumber = $query->param('itemnumber'); +my $biblionumber = + $query->param('biblionumber') || $query->param('bib') || Koha::Items->find($itemnumber)->biblionumber; my $imagenumber = $query->param('imagenumber'); -my $biblio = Koha::Biblios->find( $biblionumber ); -my $itemcount = $biblio ? $biblio->items->count : 0; +my $biblio = Koha::Biblios->find($biblionumber); +my $itemcount = $biblio ? $biblio->items->count : 0; if ( $query->cookie("holdfor") ) { my $holdfor_patron = Koha::Patrons->find( $query->cookie("holdfor") ); @@ -52,7 +53,7 @@ if ( $query->cookie("holdfor") ) { ); } -if( $query->cookie("searchToOrder") ){ +if ( $query->cookie("searchToOrder") ) { my ( $basketno, $vendorid ) = split( /\//, $query->cookie("searchToOrder") ); $template->param( searchtoorder_basketno => $basketno, @@ -62,7 +63,7 @@ if( $query->cookie("searchToOrder") ){ if ( C4::Context->preference("LocalCoverImages") ) { my $images; - if ( $itemnumber ) { + if ($itemnumber) { my $item = Koha::Items->find($itemnumber); $images = $item->cover_images->as_list; } else { @@ -75,13 +76,13 @@ if ( C4::Context->preference("LocalCoverImages") ) { imagenumber => ( $imagenumber || ( @$images ? $images->[0]->imagenumber : undef ) ), ); } -$template->{VARS}->{'count'} = $itemcount; +$template->{VARS}->{'count'} = $itemcount; $template->param(C4::Search::enabled_staff_search_views); $template->{VARS}->{'biblio'} = $biblio; $template->param( biblionumber => $biblionumber, - itemnumber => $itemnumber, + itemnumber => $itemnumber, ); my $hold_count = $biblio ? $biblio->holds->count : 0; diff --git a/catalogue/issuehistory.pl b/catalogue/issuehistory.pl index 4f361367bf..0a8ddbc802 100755 --- a/catalogue/issuehistory.pl +++ b/catalogue/issuehistory.pl @@ -15,14 +15,13 @@ # You should have received a copy of the GNU General Public License # along with Koha; if not, see . - use Modern::Perl; -use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); -use C4::Search qw( enabled_staff_search_views ); +use C4::Search qw( enabled_staff_search_views ); use C4::Serials qw( CountSubscriptionFromBiblionumber ); use Koha::Checkouts; use Koha::Old::Checkouts; @@ -32,10 +31,10 @@ use Koha::Biblios; my $query = CGI->new; my ( $template, $borrowernumber, $cookie ) = get_template_and_user( { - template_name => "catalogue/issuehistory.tt", - query => $query, - type => "intranet", - flagsrequired => { catalogue => 1 }, + template_name => "catalogue/issuehistory.tt", + query => $query, + type => "intranet", + flagsrequired => { catalogue => 1 }, } ); @@ -44,25 +43,25 @@ my $biblionumber = $query->param('biblionumber'); my @checkouts = Koha::Checkouts->search( { biblionumber => $biblionumber }, { - join => 'item', - order_by => 'timestamp', + join => 'item', + order_by => 'timestamp', } )->as_list; my @old_checkouts = Koha::Old::Checkouts->search( { biblionumber => $biblionumber }, { - join => 'item', - order_by => 'timestamp', + join => 'item', + order_by => 'timestamp', } )->as_list; -my $biblio = Koha::Biblios->find( $biblionumber ); +my $biblio = Koha::Biblios->find($biblionumber); $template->param( - checkouts => [ @checkouts, @old_checkouts ], - biblio => $biblio, - issuehistoryview => 1, - C4::Search::enabled_staff_search_views, + checkouts => [ @checkouts, @old_checkouts ], + biblio => $biblio, + issuehistoryview => 1, + C4::Search::enabled_staff_search_views, subscriptionsnumber => CountSubscriptionFromBiblionumber($biblionumber), ); diff --git a/catalogue/item-export.pl b/catalogue/item-export.pl index 52f6b84a4c..31823d4bbe 100755 --- a/catalogue/item-export.pl +++ b/catalogue/item-export.pl @@ -26,23 +26,27 @@ use C4::Output; my $cgi = CGI->new; -my ($template, $borrowernumber, $cookie) = get_template_and_user({ - template_name => 'catalogue/itemsearch_csv.tt', - query => $cgi, - type => 'intranet', - flagsrequired => { catalogue => 1 }, -}); +my ( $template, $borrowernumber, $cookie ) = get_template_and_user( + { + template_name => 'catalogue/itemsearch_csv.tt', + query => $cgi, + type => 'intranet', + flagsrequired => { catalogue => 1 }, + } +); my @itemnumbers = $cgi->multi_param('itemnumber'); -my $format = $cgi->param('format') // 'csv'; +my $format = $cgi->param('format') // 'csv'; -my $items = Koha::Items->search({ itemnumber => { -in => \@itemnumbers } }); +my $items = Koha::Items->search( { itemnumber => { -in => \@itemnumbers } } ); -if ($format eq 'barcodes') { - print $cgi->header({ - type => 'text/plain', - attachment => 'barcodes.txt', - }); +if ( $format eq 'barcodes' ) { + print $cgi->header( + { + type => 'text/plain', + attachment => 'barcodes.txt', + } + ); while ( my $item = $items->next ) { print $item->barcode . "\n"; @@ -54,10 +58,12 @@ $template->param( results => $items, ); -print $cgi->header({ - type => 'text/csv', - attachment => 'items.csv', -}); +print $cgi->header( + { + type => 'text/csv', + attachment => 'items.csv', + } +); for my $line ( split '\n', $template->output ) { print "$line\n" unless $line =~ m|^\s*$|; } diff --git a/catalogue/itemsearch.pl b/catalogue/itemsearch.pl index 40b42adeb7..bb69f32c5c 100755 --- a/catalogue/itemsearch.pl +++ b/catalogue/itemsearch.pl @@ -21,11 +21,11 @@ use CGI; use JSON qw( to_json from_json ); -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Circulation qw( barcodedecode ); -use C4::Output qw( output_with_http_headers output_html_with_http_headers ); -use C4::Items qw( SearchItems ); -use C4::Koha qw( GetAuthorisedValues ); +use C4::Output qw( output_with_http_headers output_html_with_http_headers ); +use C4::Items qw( SearchItems ); +use C4::Koha qw( GetAuthorisedValues ); use Koha::AuthorisedValues; use Koha::Biblios; @@ -35,7 +35,7 @@ use Koha::Libraries; my $cgi = CGI->new; -my $format = $cgi->param('format'); +my $format = $cgi->param('format'); my $template_name = 'catalogue/itemsearch.tt'; if ( defined $format and $format eq 'json' ) { @@ -100,18 +100,30 @@ if ( defined $format and $format eq 'json' ) { die "Unsupported format $format"; } -my ($template, $borrowernumber, $cookie) = get_template_and_user({ - template_name => $template_name, - query => $cgi, - type => 'intranet', - flagsrequired => { catalogue => 1 }, -}); +my ( $template, $borrowernumber, $cookie ) = get_template_and_user( + { + template_name => $template_name, + query => $cgi, + type => 'intranet', + flagsrequired => { catalogue => 1 }, + } +); -my $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => '', kohafield => 'items.itemlost', authorised_value => [ -and => {'!=' => undef }, {'!=' => ''}] }); -my $itemlost_values = $mss->count ? GetAuthorisedValues($mss->next->authorised_value) : []; +my $mss = Koha::MarcSubfieldStructures->search( + { + frameworkcode => '', kohafield => 'items.itemlost', + authorised_value => [ -and => { '!=' => undef }, { '!=' => '' } ] + } +); +my $itemlost_values = $mss->count ? GetAuthorisedValues( $mss->next->authorised_value ) : []; -$mss = Koha::MarcSubfieldStructures->search({ frameworkcode => '', kohafield => 'items.withdrawn', authorised_value => [ -and => {'!=' => undef }, {'!=' => ''}] }); -my $withdrawn_values = $mss->count ? GetAuthorisedValues($mss->next->authorised_value) : []; +$mss = Koha::MarcSubfieldStructures->search( + { + frameworkcode => '', kohafield => 'items.withdrawn', + authorised_value => [ -and => { '!=' => undef }, { '!=' => '' } ] + } +); +my $withdrawn_values = $mss->count ? GetAuthorisedValues( $mss->next->authorised_value ) : []; $mss = Koha::MarcSubfieldStructures->search( { @@ -125,12 +137,13 @@ if ( Koha::MarcSubfieldStructures->search( { frameworkcode => '', kohafield => ' $template->param( has_new_status => 1 ); } -if ( defined $format and $format ne 'shareable') { +if ( defined $format and $format ne 'shareable' ) { + # Parameters given, it's a search my $filter = { conjunction => 'AND', - filters => [], + filters => [], }; foreach my $p ( @@ -163,29 +176,30 @@ if ( defined $format and $format ne 'shareable') { my @op = $param_names{'op[]'} ? $cgi->multi_param('op[]') : $cgi->multi_param('op'); my $f; - for (my $i = 0; $i < @fields; $i++) { + for ( my $i = 0 ; $i < @fields ; $i++ ) { my $field = $fields[$i]; - my $q = shift @q; - my $op = shift @op; - if (defined $q and $q ne '') { - if (C4::Context->preference("marcflavour") ne "UNIMARC" && $field eq 'publicationyear') { + my $q = shift @q; + my $op = shift @op; + if ( defined $q and $q ne '' ) { + if ( C4::Context->preference("marcflavour") ne "UNIMARC" && $field eq 'publicationyear' ) { $field = 'copyrightdate'; } - if ($i == 0) { + if ( $i == 0 ) { $f = { - field => $field, - query => $q, + field => $field, + query => $q, operator => $op, }; } else { my $c = shift @c; $f = { conjunction => $c, - filters => [ - $f, { - field => $field, - query => $q, + filters => [ + $f, + { + field => $field, + query => $q, operator => $op, } ], @@ -218,7 +232,7 @@ if ( defined $format and $format ne 'shareable') { foreach my $p (qw( onloan )) { my $v = $cgi->param($p) // ''; my $f = { - field => $p, + field => $p, operator => "is", }; if ( $v eq 'IS NOT NULL' ) { @@ -229,39 +243,41 @@ if ( defined $format and $format ne 'shareable') { push @{ $filter->{filters} }, $f unless ( $v eq "" ); } - if (my $itemcallnumber_from = scalar $cgi->param('itemcallnumber_from')) { + if ( my $itemcallnumber_from = scalar $cgi->param('itemcallnumber_from') ) { push @{ $filter->{filters} }, { - field => 'itemcallnumber', - query => $itemcallnumber_from, + field => 'itemcallnumber', + query => $itemcallnumber_from, operator => '>=', }; } - if (my $itemcallnumber_to = scalar $cgi->param('itemcallnumber_to')) { + if ( my $itemcallnumber_to = scalar $cgi->param('itemcallnumber_to') ) { push @{ $filter->{filters} }, { - field => 'itemcallnumber', - query => $itemcallnumber_to, + field => 'itemcallnumber', + query => $itemcallnumber_to, operator => '<=', }; } my $sortby = $cgi->param('sortby') || 'itemnumber'; - if (C4::Context->preference("marcflavour") ne "UNIMARC" && $sortby eq 'publicationyear') { + if ( C4::Context->preference("marcflavour") ne "UNIMARC" && $sortby eq 'publicationyear' ) { $sortby = 'copyrightdate'; } my $search_params = { - rows => scalar $cgi->param('rows') // 20, - page => scalar $cgi->param('page') || 1, - sortby => $sortby, + rows => scalar $cgi->param('rows') // 20, + page => scalar $cgi->param('page') || 1, + sortby => $sortby, sortorder => scalar $cgi->param('sortorder') || 'asc', }; - my ($results, $total_rows) = SearchItems($filter, $search_params); + my ( $results, $total_rows ) = SearchItems( $filter, $search_params ); - if ($format eq 'barcodes') { - print $cgi->header({ - type => 'text/plain', - attachment => 'barcodes.txt', - }); + if ( $format eq 'barcodes' ) { + print $cgi->header( + { + type => 'text/plain', + attachment => 'barcodes.txt', + } + ); foreach my $item (@$results) { print $item->{barcode} . "\n"; @@ -272,9 +288,9 @@ if ( defined $format and $format ne 'shareable') { if ($results) { foreach my $item (@$results) { my $biblio = Koha::Biblios->find( $item->{biblionumber} ); - $item->{biblio} = $biblio; + $item->{biblio} = $biblio; $item->{biblioitem} = $biblio->biblioitem->unblessed; - my $checkout = Koha::Checkouts->find({ itemnumber => $item->{itemnumber} }); + my $checkout = Koha::Checkouts->find( { itemnumber => $item->{itemnumber} } ); $item->{checkout} = $checkout; } } @@ -284,20 +300,22 @@ if ( defined $format and $format ne 'shareable') { search_params => $search_params, results => $results, total_rows => $total_rows, - user => Koha::Patrons->find( $borrowernumber ), + user => Koha::Patrons->find($borrowernumber), ); - if ($format eq 'csv') { - print $cgi->header({ - type => 'text/csv', - attachment => 'items.csv', - }); + if ( $format eq 'csv' ) { + print $cgi->header( + { + type => 'text/csv', + attachment => 'items.csv', + } + ); for my $line ( split '\n', $template->output ) { print "$line\n" unless $line =~ m|^\s*$|; } - } elsif ($format eq 'json') { - $template->param(draw => scalar $cgi->param('draw')); + } elsif ( $format eq 'json' ) { + $template->param( draw => scalar $cgi->param('draw') ); output_with_http_headers $cgi, $cookie, $template->output, 'json'; } @@ -306,13 +324,15 @@ if ( defined $format and $format ne 'shareable') { # Display the search form -my @branches = map { value => $_->branchcode, label => $_->branchname }, Koha::Libraries->search( {}, { order_by => 'branchname' } )->as_list; -my @itemtypes = map { value => $_->itemtype, label => $_->translated_description }, Koha::ItemTypes->search_with_localization->as_list; +my @branches = map { value => $_->branchcode, label => $_->branchname }, + Koha::Libraries->search( {}, { order_by => 'branchname' } )->as_list; +my @itemtypes = map { value => $_->itemtype, label => $_->translated_description }, + Koha::ItemTypes->search_with_localization->as_list; -my @ccodes = Koha::AuthorisedValues->get_descriptions_by_koha_field({ kohafield => 'items.ccode' }); +my @ccodes = Koha::AuthorisedValues->get_descriptions_by_koha_field( { kohafield => 'items.ccode' } ); foreach my $ccode (@ccodes) { $ccode->{value} = $ccode->{authorised_value}, - $ccode->{label} = $ccode->{lib}, + $ccode->{label} = $ccode->{lib},; } my @itemlosts; @@ -343,21 +363,21 @@ my @items_search_fields = GetItemSearchFields(); my $authorised_values = {}; foreach my $field (@items_search_fields) { - if (my $category = ($field->{authorised_values_category})) { + if ( my $category = ( $field->{authorised_values_category} ) ) { $authorised_values->{$category} = GetAuthorisedValues($category); } } $template->param( - branches => \@branches, - itemtypes => \@itemtypes, - ccodes => \@ccodes, - itemlosts => \@itemlosts, - withdrawns => \@withdrawns, - damageds => \@damageds, - items_search_fields => \@items_search_fields, + branches => \@branches, + itemtypes => \@itemtypes, + ccodes => \@ccodes, + itemlosts => \@itemlosts, + withdrawns => \@withdrawns, + damageds => \@damageds, + items_search_fields => \@items_search_fields, authorised_values_json => to_json($authorised_values), - query => $cgi, + query => $cgi, ); output_html_with_http_headers $cgi, $cookie, $template->output; diff --git a/catalogue/labeledMARCdetail.pl b/catalogue/labeledMARCdetail.pl index a338172773..51e1e9a97c 100755 --- a/catalogue/labeledMARCdetail.pl +++ b/catalogue/labeledMARCdetail.pl @@ -18,7 +18,7 @@ # along with Koha; if not, see . use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use HTML::Entities; use C4::Auth qw( get_template_and_user ); use C4::Context; @@ -28,7 +28,7 @@ use C4::Biblio qw( GetFrameworkCode GetMarcStructure ); -use C4::Search qw( z3950_search_args enabled_staff_search_views ); +use C4::Search qw( z3950_search_args enabled_staff_search_views ); use C4::Serials qw( CountSubscriptionFromBiblionumber ); use Koha::Biblios; @@ -40,22 +40,20 @@ my $query = CGI->new; my $dbh = C4::Context->dbh; my $biblionumber = $query->param('biblionumber'); $biblionumber = HTML::Entities::encode($biblionumber); -my $frameworkcode = $query->param('frameworkcode') // GetFrameworkCode( $biblionumber ); -my $popup = - $query->param('popup') - ; # if set to 1, then don't insert links, it's just to show the biblio +my $frameworkcode = $query->param('frameworkcode') // GetFrameworkCode($biblionumber); +my $popup = $query->param('popup'); # if set to 1, then don't insert links, it's just to show the biblio # open template my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "catalogue/labeledMARCdetail.tt", - query => $query, - type => "intranet", - flagsrequired => { catalogue => 1 }, + template_name => "catalogue/labeledMARCdetail.tt", + query => $query, + type => "intranet", + flagsrequired => { catalogue => 1 }, } ); -my $biblio_object = Koha::Biblios->find( $biblionumber ); # FIXME Should replace $biblio +my $biblio_object = Koha::Biblios->find($biblionumber); # FIXME Should replace $biblio unless ($biblio_object) { # biblionumber invalid -> report and exit @@ -67,11 +65,11 @@ unless ($biblio_object) { exit; } -my $record = $biblio_object->metadata->record; -my $tagslib = GetMarcStructure(1,$frameworkcode); -my $biblio = GetBiblioData($biblionumber); +my $record = $biblio_object->metadata->record; +my $tagslib = GetMarcStructure( 1, $frameworkcode ); +my $biblio = GetBiblioData($biblionumber); -if($query->cookie("holdfor")){ +if ( $query->cookie("holdfor") ) { my $holdfor_patron = Koha::Patrons->find( $query->cookie("holdfor") ); $template->param( holdfor => $query->cookie("holdfor"), @@ -79,7 +77,7 @@ if($query->cookie("holdfor")){ ); } -if( $query->cookie("searchToOrder") ){ +if ( $query->cookie("searchToOrder") ) { my ( $basketno, $vendorid ) = split( /\//, $query->cookie("searchToOrder") ); $template->param( searchtoorder_basketno => $basketno, @@ -89,10 +87,12 @@ if( $query->cookie("searchToOrder") ){ #count of item linked my $itemcount = $biblio_object->items->count; -$template->param( count => $itemcount, - bibliotitle => $biblio->{title}, ); +$template->param( + count => $itemcount, + bibliotitle => $biblio->{title}, +); -my $frameworks = Koha::BiblioFrameworks->search({}, { order_by => ['frameworktext'] }); +my $frameworks = Koha::BiblioFrameworks->search( {}, { order_by => ['frameworktext'] } ); $template->param( frameworks => $frameworks, frameworkcode => $frameworkcode, @@ -100,35 +100,32 @@ $template->param( my @marc_data; my $prevlabel = ''; -for my $field ($record->fields) -{ - my $tag = $field->tag; - next if ! exists $tagslib->{$tag}->{lib}; - my $label = $tagslib->{$tag}->{lib}; - if ($label eq $prevlabel) - { - $label = ''; - } - else - { - $prevlabel = $label; - } - my $value = $tag < 10 - ? $field->data - : join ' ', map { $_->[1] } $field->subfields; - push @marc_data, { - label => $label, - value => $value, - }; +for my $field ( $record->fields ) { + my $tag = $field->tag; + next if !exists $tagslib->{$tag}->{lib}; + my $label = $tagslib->{$tag}->{lib}; + if ( $label eq $prevlabel ) { + $label = ''; + } else { + $prevlabel = $label; + } + my $value = + $tag < 10 + ? $field->data + : join ' ', map { $_->[1] } $field->subfields; + push @marc_data, { + label => $label, + value => $value, + }; } # get biblionumbers stored in the cart my @cart_list; -if($query->cookie("intranet_bib_list")){ +if ( $query->cookie("intranet_bib_list") ) { my $cart_list = $query->cookie("intranet_bib_list"); - @cart_list = split(/\//, $cart_list); - if ( grep {$_ eq $biblionumber} @cart_list) { + @cart_list = split( /\//, $cart_list ); + if ( grep { $_ eq $biblionumber } @cart_list ) { $template->param( incart => 1 ); } } @@ -148,24 +145,23 @@ my $some_public_shelves = Koha::Virtualshelves->get_some_shelves( } ); - $template->param( add_to_some_private_shelves => $some_private_shelves, add_to_some_public_shelves => $some_public_shelves, ); -$template->param ( - marc_data => \@marc_data, - biblionumber => $biblionumber, - popup => $popup, - labeledmarcview => 1, - z3950_search_params => C4::Search::z3950_search_args($biblio), - C4::Search::enabled_staff_search_views, +$template->param( + marc_data => \@marc_data, + biblionumber => $biblionumber, + popup => $popup, + labeledmarcview => 1, + z3950_search_params => C4::Search::z3950_search_args($biblio), + C4::Search::enabled_staff_search_views, subscriptionsnumber => CountSubscriptionFromBiblionumber($biblionumber), searchid => scalar $query->param('searchid'), ); -$biblio = Koha::Biblios->find( $biblionumber ); +$biblio = Koha::Biblios->find($biblionumber); my $holds = $biblio->holds; $template->param( biblio => $biblio, holdcount => $holds->count ); diff --git a/catalogue/moredetail.pl b/catalogue/moredetail.pl index 10a1d4fe0f..3e848377bc 100755 --- a/catalogue/moredetail.pl +++ b/catalogue/moredetail.pl @@ -18,17 +18,16 @@ # You should have received a copy of the GNU General Public License # along with Koha; if not, see . - use Modern::Perl; use C4::Koha qw( GetAuthorisedValues ); -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use HTML::Entities; -use C4::Biblio qw( GetBiblioData GetFrameworkCode ); +use C4::Biblio qw( GetBiblioData GetFrameworkCode ); use C4::Acquisition qw( GetOrderFromItemnumber GetBasket GetInvoice ); -use C4::Output qw( output_and_exit output_html_with_http_headers ); -use C4::Auth qw( get_template_and_user ); -use C4::Serials qw( CountSubscriptionFromBiblionumber ); -use C4::Search qw( enabled_staff_search_views z3950_search_args ); +use C4::Output qw( output_and_exit output_html_with_http_headers ); +use C4::Auth qw( get_template_and_user ); +use C4::Serials qw( CountSubscriptionFromBiblionumber ); +use C4::Search qw( enabled_staff_search_views z3950_search_args ); use Koha::Acquisition::Booksellers; use Koha::AuthorisedValues; @@ -36,22 +35,21 @@ use Koha::Biblios; use Koha::Items; use Koha::Patrons; -my $query=CGI->new; +my $query = CGI->new; -my ($template, $loggedinuser, $cookie) = get_template_and_user( +my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => 'catalogue/moredetail.tt', - query => $query, - type => "intranet", - flagsrequired => { catalogue => 1 }, + template_name => 'catalogue/moredetail.tt', + query => $query, + type => "intranet", + flagsrequired => { catalogue => 1 }, } ); $template->param( - updated_exclude_from_local_holds_priority => scalar($query->param('updated_exclude_from_local_holds_priority')) -); + updated_exclude_from_local_holds_priority => scalar( $query->param('updated_exclude_from_local_holds_priority') ) ); -if($query->cookie("holdfor")){ +if ( $query->cookie("holdfor") ) { my $holdfor_patron = Koha::Patrons->find( $query->cookie("holdfor") ); $template->param( holdfor => $query->cookie("holdfor"), @@ -59,7 +57,7 @@ if($query->cookie("holdfor")){ ); } -if( $query->cookie("searchToOrder") ){ +if ( $query->cookie("searchToOrder") ) { my ( $basketno, $vendorid ) = split( /\//, $query->cookie("searchToOrder") ); $template->param( searchtoorder_basketno => $basketno, @@ -70,21 +68,21 @@ if( $query->cookie("searchToOrder") ){ # get variables my $biblionumber; my $itemnumber; -if( $query->param('itemnumber') && !$query->param('biblionumber') ){ +if ( $query->param('itemnumber') && !$query->param('biblionumber') ) { $itemnumber = $query->param('itemnumber'); - my $item = Koha::Items->find( $itemnumber ); + my $item = Koha::Items->find($itemnumber); $biblionumber = $item->biblionumber; } else { $biblionumber = $query->param('biblionumber'); } $biblionumber = HTML::Entities::encode($biblionumber); -my $title=$query->param('title'); -my $bi=$query->param('bi'); -$bi = $biblionumber unless $bi; +my $title = $query->param('title'); +my $bi = $query->param('bi'); +$bi = $biblionumber unless $bi; $itemnumber = $query->param('itemnumber'); -my $data = &GetBiblioData($biblionumber); -my $dewey = $data->{'dewey'}; +my $data = &GetBiblioData($biblionumber); +my $dewey = $data->{'dewey'}; my $showallitems = $query->param('showallitems'); #coping with subscriptions @@ -101,22 +99,22 @@ my $subscriptionsnumber = CountSubscriptionFromBiblionumber($biblionumber); # $dewey=~ s/\.$//; # $data->{'dewey'}=$dewey; -my $biblio = Koha::Biblios->find( $biblionumber ); +my $biblio = Koha::Biblios->find($biblionumber); my $record = $biblio ? $biblio->metadata->record : undef; -output_and_exit( $query, $cookie, $template, 'unknown_biblio') +output_and_exit( $query, $cookie, $template, 'unknown_biblio' ) unless $biblio && $record; -my $fw = GetFrameworkCode($biblionumber); +my $fw = GetFrameworkCode($biblionumber); my $all_items = $biblio->items->search_ordered; my @items; -my $patron = Koha::Patrons->find( $loggedinuser ); +my $patron = Koha::Patrons->find($loggedinuser); while ( my $item = $all_items->next ) { push @items, $item - unless $item->itemlost - && $patron->category->hidelostitems - && !$showallitems; + unless $item->itemlost + && $patron->category->hidelostitems + && !$showallitems; } my $hostrecords; @@ -126,68 +124,73 @@ if ( $hostitems->count ) { push @items, $hostitems->as_list; } -my $totalcount = $all_items->count; -my $showncount = scalar @items; +my $totalcount = $all_items->count; +my $showncount = scalar @items; my $hiddencount = $totalcount - $showncount; -$data->{'count'}=$totalcount; -$data->{'showncount'}=$showncount; -$data->{'hiddencount'}=$hiddencount; # can be zero +$data->{'count'} = $totalcount; +$data->{'showncount'} = $showncount; +$data->{'hiddencount'} = $hiddencount; # can be zero my $ccodes = - { map { $_->{authorised_value} => $_->{lib} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => $fw, kohafield => 'items.ccode' } ) }; -my $copynumbers = - { map { $_->{authorised_value} => $_->{lib} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => $fw, kohafield => 'items.copynumber' } ) }; + { map { $_->{authorised_value} => $_->{lib} } + Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => $fw, kohafield => 'items.ccode' } ) + }; +my $copynumbers = { + map { $_->{authorised_value} => $_->{lib} } Koha::AuthorisedValues->get_descriptions_by_koha_field( + { frameworkcode => $fw, kohafield => 'items.copynumber' } + ) +}; my $itemtypes = { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search_with_localization->unblessed } }; $data->{'itemtypename'} = $itemtypes->{ $data->{'itemtype'} }->{'translated_description'} - if $data->{itemtype} && exists $itemtypes->{ $data->{itemtype} }; + if $data->{itemtype} && exists $itemtypes->{ $data->{itemtype} }; foreach ( keys %{$data} ) { $template->param( "$_" => defined $data->{$_} ? $data->{$_} : '' ); } if ($itemnumber) { - @items = (grep {$_->itemnumber == $itemnumber} @items); + @items = ( grep { $_->itemnumber == $itemnumber } @items ); } my @item_data; -foreach my $item (@items){ +foreach my $item (@items) { my $item_info = $item->unblessed; $item_info->{object} = $item; - $item_info->{itype} = $itemtypes->{ $item->itype }->{'translated_description'} if exists $itemtypes->{ $item->itype }; - $item_info->{effective_itemtype} = $itemtypes->{$item->effective_itemtype}; - $item_info->{'ccode'} = $ccodes->{ $item->ccode } if $ccodes && $item->ccode && exists $ccodes->{ $item->ccode }; + $item_info->{itype} = $itemtypes->{ $item->itype }->{'translated_description'} + if exists $itemtypes->{ $item->itype }; + $item_info->{effective_itemtype} = $itemtypes->{ $item->effective_itemtype }; + $item_info->{'ccode'} = $ccodes->{ $item->ccode } if $ccodes && $item->ccode && exists $ccodes->{ $item->ccode }; if ( defined $item->copynumber ) { $item_info->{'displaycopy'} = 1; if ( defined $copynumbers->{ $item_info->{'copynumber'} } ) { - $item_info->{'copyvol'} = $copynumbers->{ $item_info->{'copynumber'} } - } - else { + $item_info->{'copyvol'} = $copynumbers->{ $item_info->{'copynumber'} }; + } else { $item_info->{'copyvol'} = $item_info->{'copynumber'}; } } # item has a host number if its biblio number does not match the current bib - if ($item->biblionumber ne $biblionumber){ + if ( $item->biblionumber ne $biblionumber ) { $item_info->{hostbiblionumber} = $item->biblionumber; - $item_info->{hosttitle} = $item->biblio->title; + $item_info->{hosttitle} = $item->biblio->title; } # FIXME The acquisition code below could be improved using methods from Koha:: objects - my $order = GetOrderFromItemnumber( $item->itemnumber ); - $item_info->{'basketno'} = $order->{'basketno'}; - $item_info->{'orderdate'} = $order->{'entrydate'}; - if ($item_info->{'basketno'}){ - my $basket = GetBasket($item_info->{'basketno'}); + my $order = GetOrderFromItemnumber( $item->itemnumber ); + $item_info->{'basketno'} = $order->{'basketno'}; + $item_info->{'orderdate'} = $order->{'entrydate'}; + if ( $item_info->{'basketno'} ) { + my $basket = GetBasket( $item_info->{'basketno'} ); my $bookseller = Koha::Acquisition::Booksellers->find( $basket->{booksellerid} ); $item_info->{'vendor'} = $bookseller->name; } - $item_info->{'invoiceid'} = $order->{'invoiceid'}; - if($item_info->{invoiceid}) { - my $invoice = GetInvoice($item_info->{invoiceid}); + $item_info->{'invoiceid'} = $order->{'invoiceid'}; + if ( $item_info->{invoiceid} ) { + my $invoice = GetInvoice( $item_info->{invoiceid} ); $item_info->{invoicenumber} = $invoice->{invoicenumber} if $invoice; } - $item_info->{'datereceived'} = $order->{'datereceived'}; + $item_info->{'datereceived'} = $order->{'datereceived'}; if ( $item->notforloan || $item->itemtype->notforloan @@ -216,15 +219,14 @@ foreach my $item (@items){ if ( my $accountline = $accountlines->next ) { my $payment_offsets = $accountline->debit_offsets( { - credit_id => { '!=' => undef }, # it is not the debit itself - 'credit.credit_type_code' => - { '!=' => [ 'Writeoff', 'Forgiven' ] }, + credit_id => { '!=' => undef }, # it is not the debit itself + 'credit.credit_type_code' => { '!=' => [ 'Writeoff', 'Forgiven' ] }, }, { join => 'credit', order_by => { '-desc' => 'created_on' } } ); - if ($payment_offsets->count) { - my $patron = $accountline->patron; + if ( $payment_offsets->count ) { + my $patron = $accountline->patron; my $payment_offset = $payment_offsets->next; $item_info->{paidfor} = { patron => $patron, created_on => $payment_offset->created_on }; } @@ -234,11 +236,12 @@ foreach my $item (@items){ $item_info->{has_return_claim} = 1 if $return_claim; } - if (C4::Context->preference("IndependentBranches")) { + if ( C4::Context->preference("IndependentBranches") ) { + #verifying rights my $userenv = C4::Context->userenv(); - unless (C4::Context->IsSuperLibrarian() or ($userenv->{'branch'} eq $item->homebranch)) { - $item_info->{'nomod'}=1; + unless ( C4::Context->IsSuperLibrarian() or ( $userenv->{'branch'} eq $item->homebranch ) ) { + $item_info->{'nomod'} = 1; } } @@ -255,32 +258,48 @@ foreach my $item (@items){ push @item_data, $item_info; } -my $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => $fw, kohafield => 'items.itemlost', authorised_value => [ -and => {'!=' => undef }, {'!=' => ''}] }); +my $mss = Koha::MarcSubfieldStructures->search( + { + frameworkcode => $fw, kohafield => 'items.itemlost', + authorised_value => [ -and => { '!=' => undef }, { '!=' => '' } ] + } +); if ( $mss->count ) { $template->param( itemlostloop => GetAuthorisedValues( $mss->next->authorised_value ) ); } -$mss = Koha::MarcSubfieldStructures->search({ frameworkcode => $fw, kohafield => 'items.damaged', authorised_value => [ -and => {'!=' => undef }, {'!=' => ''}] }); +$mss = Koha::MarcSubfieldStructures->search( + { + frameworkcode => $fw, kohafield => 'items.damaged', + authorised_value => [ -and => { '!=' => undef }, { '!=' => '' } ] + } +); if ( $mss->count ) { $template->param( itemdamagedloop => GetAuthorisedValues( $mss->next->authorised_value ) ); } -$mss = Koha::MarcSubfieldStructures->search({ frameworkcode => $fw, kohafield => 'items.withdrawn', authorised_value => [ -and => {'!=' => undef }, {'!=' => ''}] }); +$mss = Koha::MarcSubfieldStructures->search( + { + frameworkcode => $fw, kohafield => 'items.withdrawn', + authorised_value => [ -and => { '!=' => undef }, { '!=' => '' } ] + } +); if ( $mss->count ) { - $template->param( itemwithdrawnloop => GetAuthorisedValues( $mss->next->authorised_value) ); + $template->param( itemwithdrawnloop => GetAuthorisedValues( $mss->next->authorised_value ) ); } -$template->param(count => $data->{'count'}, - subscriptionsnumber => $subscriptionsnumber, +$template->param( + count => $data->{'count'}, + subscriptionsnumber => $subscriptionsnumber, subscriptiontitle => $data->{title}, - C4::Search::enabled_staff_search_views, + C4::Search::enabled_staff_search_views, ); # get biblionumbers stored in the cart my @cart_list; -if($query->cookie("intranet_bib_list")){ +if ( $query->cookie("intranet_bib_list") ) { my $cart_list = $query->cookie("intranet_bib_list"); - @cart_list = split(/\//, $cart_list); - if ( grep {$_ eq $biblionumber} @cart_list) { + @cart_list = split( /\//, $cart_list ); + if ( grep { $_ eq $biblionumber } @cart_list ) { $template->param( incart => 1 ); } } @@ -300,7 +319,6 @@ my $some_public_shelves = Koha::Virtualshelves->get_some_shelves( } ); - $template->param( add_to_some_private_shelves => $some_private_shelves, add_to_some_public_shelves => $some_public_shelves, @@ -313,10 +331,10 @@ $template->param( biblionumber => $biblionumber, biblioitemnumber => $bi, itemnumber => $itemnumber, - z3950_search_params => C4::Search::z3950_search_args(GetBiblioData($biblionumber)), + z3950_search_params => C4::Search::z3950_search_args( GetBiblioData($biblionumber) ), biblio => $biblio, ); -$template->param(ONLY_ONE => 1) if ( $itemnumber && $showncount != @items ); +$template->param( ONLY_ONE => 1 ) if ( $itemnumber && $showncount != @items ); $template->{'VARS'}->{'searchid'} = $query->param('searchid'); my $holds = $biblio->holds; diff --git a/catalogue/search-history.pl b/catalogue/search-history.pl index a97fbe839f..eda6679c80 100755 --- a/catalogue/search-history.pl +++ b/catalogue/search-history.pl @@ -27,20 +27,23 @@ use C4::Output qw( output_html_with_http_headers ); my $cgi = CGI->new; -my ($template, $loggedinuser, $cookie) = get_template_and_user({ - template_name => 'catalogue/search-history.tt', - query => $cgi, - type => "intranet", - flagsrequired => {catalogue => 1}, -}); +my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => 'catalogue/search-history.tt', + query => $cgi, + type => "intranet", + flagsrequired => { catalogue => 1 }, + } +); -my $type = $cgi->param('type'); -my $op = $cgi->param('op') || q{list}; +my $type = $cgi->param('type'); +my $op = $cgi->param('op') || q{list}; my $previous = $cgi->param('previous'); # Deleting search history if ( $op eq 'cud-delete' ) { - my $sessionid = defined $previous + my $sessionid = + defined $previous ? $cgi->cookie("CGISESSID") : q{}; C4::Search::History::delete( @@ -49,48 +52,43 @@ if ( $op eq 'cud-delete' ) { id => [ $cgi->param('id') ], } ); + # Redirecting to this same url so the user won't see the search history link in the header print $cgi->redirect('/cgi-bin/koha/catalogue/search-history.pl'); -# Showing search history + # Showing search history } else { - my $current_searches = C4::Search::History::get({ - userid => $loggedinuser, - sessionid => $cgi->cookie("CGISESSID") - }); - my @current_biblio_searches = map { - $_->{type} eq 'biblio' ? $_ : () - } @$current_searches; + my $current_searches = C4::Search::History::get( + { + userid => $loggedinuser, + sessionid => $cgi->cookie("CGISESSID") + } + ); + my @current_biblio_searches = map { $_->{type} eq 'biblio' ? $_ : () } @$current_searches; - my @current_authority_searches = map { - $_->{type} eq 'authority' ? $_ : () - } @$current_searches; + my @current_authority_searches = map { $_->{type} eq 'authority' ? $_ : () } @$current_searches; - my $previous_searches = C4::Search::History::get({ - userid => $loggedinuser, - sessionid => $cgi->cookie("CGISESSID"), - previous => 1 - }); + my $previous_searches = C4::Search::History::get( + { + userid => $loggedinuser, + sessionid => $cgi->cookie("CGISESSID"), + previous => 1 + } + ); - my @previous_biblio_searches = map { - $_->{type} eq 'biblio' ? $_ : () - } @$previous_searches; + my @previous_biblio_searches = map { $_->{type} eq 'biblio' ? $_ : () } @$previous_searches; - my @previous_authority_searches = map { - $_->{type} eq 'authority' ? $_ : () - } @$previous_searches; + my @previous_authority_searches = map { $_->{type} eq 'authority' ? $_ : () } @$previous_searches; $template->param( - current_biblio_searches => \@current_biblio_searches, - current_authority_searches => \@current_authority_searches, - previous_biblio_searches => \@previous_biblio_searches, + current_biblio_searches => \@current_biblio_searches, + current_authority_searches => \@current_authority_searches, + previous_biblio_searches => \@previous_biblio_searches, previous_authority_searches => \@previous_authority_searches, ); } - -$template->param( -); +$template->param(); output_html_with_http_headers $cgi, $cookie, $template->output; diff --git a/catalogue/search.pl b/catalogue/search.pl index c2afba0422..b64f0551b0 100755 --- a/catalogue/search.pl +++ b/catalogue/search.pl @@ -135,17 +135,17 @@ Not yet completed... use Modern::Perl; ## STEP 1. Load things that are used in both search page and -# results page and decide which template to load, operations +# results page and decide which template to load, operations # to perform, etc. ## load Koha modules use C4::Context; -use C4::Output qw( output_html_with_http_headers pagination_bar ); +use C4::Output qw( output_html_with_http_headers pagination_bar ); use C4::Circulation qw( barcodedecode ); -use C4::Auth qw( get_template_and_user ); -use C4::Search qw( searchResults enabled_staff_search_views z3950_search_args new_record_from_zebra ); -use C4::Languages qw( getlanguage getLanguages ); -use C4::Koha qw( getitemtypeimagelocation GetAuthorisedValues ); +use C4::Auth qw( get_template_and_user ); +use C4::Search qw( searchResults enabled_staff_search_views z3950_search_args new_record_from_zebra ); +use C4::Languages qw( getlanguage getLanguages ); +use C4::Koha qw( getitemtypeimagelocation GetAuthorisedValues ); use URI::Escape; use POSIX qw(ceil floor); @@ -162,6 +162,7 @@ use URI::Escape; use JSON qw( decode_json encode_json ); my $DisplayMultiPlaceHold = C4::Context->preference("DisplayMultiPlaceHold"); + # create a new CGI object # FIXME: no_undef_params needs to be tested use CGI qw('-no_undef_params' -utf8 ); @@ -170,40 +171,42 @@ my $cgi = CGI->new; # decide which template to use my $template_name; my $template_type; + # limits are used to limit to results to a pre-defined category such as branch or language -my @limits = map uri_unescape($_), $cgi->multi_param("limit"); -my @nolimits = map uri_unescape($_), $cgi->multi_param('nolimit'); +my @limits = map uri_unescape($_), $cgi->multi_param("limit"); +my @nolimits = map uri_unescape($_), $cgi->multi_param('nolimit'); my %is_nolimit = map { $_ => 1 } @nolimits; @limits = grep { not $is_nolimit{$_} } @limits; -if ( - !$cgi->param('edit_search') && !$cgi->param('edit_filter') && - ( (@limits>=1) || (defined $cgi->param("q") && $cgi->param("q") ne "" ) || ($cgi->param('limit-yr')) ) - ) { +if ( !$cgi->param('edit_search') + && !$cgi->param('edit_filter') + && ( ( @limits >= 1 ) || ( defined $cgi->param("q") && $cgi->param("q") ne "" ) || ( $cgi->param('limit-yr') ) ) ) +{ $template_name = 'catalogue/results.tt'; $template_type = 'results'; -} -else { +} else { $template_name = 'catalogue/advsearch.tt'; $template_type = 'advsearch'; } + # load the template -my ($template, $borrowernumber, $cookie) = get_template_and_user({ - template_name => $template_name, - query => $cgi, - type => "intranet", - flagsrequired => { catalogue => 1 }, +my ( $template, $borrowernumber, $cookie ) = get_template_and_user( + { + template_name => $template_name, + query => $cgi, + type => "intranet", + flagsrequired => { catalogue => 1 }, } ); my $lang = C4::Languages::getlanguage($cgi); -if (C4::Context->preference("marcflavour") eq "UNIMARC" ) { - $template->param('UNIMARC' => 1); +if ( C4::Context->preference("marcflavour") eq "UNIMARC" ) { + $template->param( 'UNIMARC' => 1 ); } -if($cgi->cookie("holdfor")){ +if ( $cgi->cookie("holdfor") ) { my $holdfor_patron = Koha::Patrons->find( $cgi->cookie("holdfor") ); - if ( $holdfor_patron ) { # may have been deleted in the meanwhile + if ($holdfor_patron) { # may have been deleted in the meanwhile $template->param( holdfor => $cgi->cookie("holdfor"), holdfor_patron => $holdfor_patron, @@ -211,17 +214,17 @@ if($cgi->cookie("holdfor")){ } } -if($cgi->cookie("holdforclub")){ +if ( $cgi->cookie("holdforclub") ) { my $holdfor_club = Koha::Clubs->find( $cgi->cookie("holdforclub") ); - if ( $holdfor_club ) { # May have been deleted in the meanwhile + if ($holdfor_club) { # May have been deleted in the meanwhile $template->param( - holdforclub => $cgi->cookie("holdforclub"), + holdforclub => $cgi->cookie("holdforclub"), holdforclub_name => $holdfor_club->name, ); } } -if($cgi->cookie("searchToOrder")){ +if ( $cgi->cookie("searchToOrder") ) { my ( $basketno, $vendorid ) = split( /\//, $cgi->cookie("searchToOrder") ); $template->param( searchtoorder_basketno => $basketno, @@ -232,29 +235,28 @@ if($cgi->cookie("searchToOrder")){ # get biblionumbers stored in the cart my @cart_list; -if($cgi->cookie("intranet_bib_list")){ +if ( $cgi->cookie("intranet_bib_list") ) { my $cart_list = $cgi->cookie("intranet_bib_list"); - @cart_list = split(/\//, $cart_list); + @cart_list = split( /\//, $cart_list ); } -my @search_groups = - Koha::Library::Groups->get_search_groups( { interface => 'staff' } )->as_list; +my @search_groups = Koha::Library::Groups->get_search_groups( { interface => 'staff' } )->as_list; my $branch_limit = ''; -my $limit_param = $cgi->param('limit'); +my $limit_param = $cgi->param('limit'); if ( $limit_param and $limit_param =~ /^branch:([\w-]+)/ ) { $branch_limit = $1; } $template->param( - search_groups => \@search_groups, - branch_limit => $branch_limit + search_groups => \@search_groups, + branch_limit => $branch_limit ); # load the Type stuff -my $types = C4::Context->preference("AdvancedSearchTypes") || "itemtypes"; +my $types = C4::Context->preference("AdvancedSearchTypes") || "itemtypes"; my $advancedsearchesloop = prepare_adv_search_types($types); -$template->param(advancedsearchesloop => $advancedsearchesloop); +$template->param( advancedsearchesloop => $advancedsearchesloop ); $template->param( searchid => scalar $cgi->param('searchid'), ); @@ -267,18 +269,19 @@ if ( $template_type eq 'advsearch' ) { my @operators; my @indexes; my $expanded = $cgi->param('expanded_options'); - if( $cgi->param('edit_search') ){ - @operands = $cgi->multi_param('q'); + if ( $cgi->param('edit_search') ) { + @operands = $cgi->multi_param('q'); @operators = $cgi->multi_param('op'); @indexes = $cgi->multi_param('idx'); $template->param( sort => scalar $cgi->param('sort_by'), ); + # determine what to display next to the search boxes - } elsif ( $cgi->param('edit_filter') ){ + } elsif ( $cgi->param('edit_filter') ) { my $search_filter = Koha::SearchFilters->find( $cgi->param('edit_filter') ); - if( $search_filter ){ - my $query = decode_json( $search_filter->query ); + if ($search_filter) { + my $query = decode_json( $search_filter->query ); my $limits = decode_json( $search_filter->limits ); @operands = @{ $query->{operands} }; @indexes = @{ $query->{indexes} }; @@ -290,7 +293,7 @@ if ( $template_type eq 'advsearch' ) { } } - while( scalar @operands < 3 ){ + while ( scalar @operands < 3 ) { push @operands, ""; } $template->param( operands => \@operands ); @@ -298,19 +301,19 @@ if ( $template_type eq 'advsearch' ) { $template->param( indexes => \@indexes ); my %limit_hash; - foreach my $limit (@limits){ - if ( $limit eq 'available' ){ + foreach my $limit (@limits) { + if ( $limit eq 'available' ) { $template->param( limit_available => 1 ); } else { - my ($index,$value) = split(':',$limit); + my ( $index, $value ) = split( ':', $limit ); $value =~ s/"//g; - if ( $index =~ /mc-/ ){ - $limit_hash{$index . "_" . $value} = 1; + if ( $index =~ /mc-/ ) { + $limit_hash{ $index . "_" . $value } = 1; } else { - push @{$limit_hash{$index}}, $value; + push @{ $limit_hash{$index} }, $value; } } - }; + } $template->param( limits => \%limit_hash ); $expanded = 1 if scalar @operators || scalar @limits; @@ -320,7 +323,7 @@ if ( $template_type eq 'advsearch' ) { $template->param( sort_by => $default_sort_by ); } - $template->param(uc(C4::Context->preference("marcflavour")) =>1 ); + $template->param( uc( C4::Context->preference("marcflavour") ) => 1 ); if ( $template_type && $template_type eq 'advsearch' ) { @@ -337,7 +340,7 @@ if ( $template_type eq 'advsearch' ) { $template->param( expanded_options => $expanded ); } - $template->param(virtualshelves => C4::Context->preference("virtualshelves")); + $template->param( virtualshelves => C4::Context->preference("virtualshelves") ); output_html_with_http_headers $cgi, $cookie, $template->output; exit; @@ -350,6 +353,7 @@ if ( $template_type eq 'advsearch' ) { # * we can edit the values by changing the key # * multivalued CGI parameters are returned as a packaged string separated by "\0" (null) my $params = $cgi->Vars; + # Params that can have more than one value # sort by is used to sort the query # in theory can have more than one but generally there's just one @@ -357,24 +361,24 @@ my @sort_by; @sort_by = $cgi->multi_param('sort_by'); $sort_by[0] = $default_sort_by unless $sort_by[0]; foreach my $sort (@sort_by) { - $template->param($sort => 1) if $sort; + $template->param( $sort => 1 ) if $sort; } -$template->param('sort_by' => $sort_by[0]); +$template->param( 'sort_by' => $sort_by[0] ); # operators include boolean and proximity operators and are used # to evaluate multiple operands my @operators = map uri_unescape($_), $cgi->multi_param('op'); # indexes are query qualifiers, like 'title', 'author', etc. They -# can be single or multiple parameters separated by comma: kw,right-Truncation +# can be single or multiple parameters separated by comma: kw,right-Truncation my @indexes = map uri_unescape($_), $cgi->multi_param('idx'); # if a simple index (only one) display the index used in the top search box -if ($indexes[0] && (!$indexes[1] || $params->{'scan'})) { - my $idx = "ms_".$indexes[0]; - $idx =~ s/\,/comma/g; # template toolkit doesn't like variables with a , in it - $idx =~ s/-/dash/g; # template toolkit doesn't like variables with a dash in it - $template->param(header_pulldown => $idx); +if ( $indexes[0] && ( !$indexes[1] || $params->{'scan'} ) ) { + my $idx = "ms_" . $indexes[0]; + $idx =~ s/\,/comma/g; # template toolkit doesn't like variables with a , in it + $idx =~ s/-/dash/g; # template toolkit doesn't like variables with a dash in it + $template->param( header_pulldown => $idx ); } # an operand can be a single term, a phrase, or a complete ccl query @@ -382,30 +386,31 @@ my @operands = map uri_unescape($_), $cgi->multi_param('q'); # if a simple search, display the value in the search box my $basic_search = 0; -if ($operands[0] && !$operands[1]) { +if ( $operands[0] && !$operands[1] ) { my $ms_query = $operands[0]; $ms_query =~ s/ #\S+//; - $template->param(ms_value => $ms_query); - $basic_search=1; + $template->param( ms_value => $ms_query ); + $basic_search = 1; } my $available; -foreach my $limit(@limits) { - if ($limit =~/available/) { +foreach my $limit (@limits) { + if ( $limit =~ /available/ ) { $available = 1; } } -$template->param(available => $available); +$template->param( available => $available ); # append year limits if they exist my $limit_yr; my $limit_yr_value; -if ($params->{'limit-yr'}) { - if ($params->{'limit-yr'} =~ /\d{4}/) { - $limit_yr = "yr,st-numeric:$params->{'limit-yr'}"; +if ( $params->{'limit-yr'} ) { + if ( $params->{'limit-yr'} =~ /\d{4}/ ) { + $limit_yr = "yr,st-numeric:$params->{'limit-yr'}"; $limit_yr_value = $params->{'limit-yr'}; } - push @limits,$limit_yr; + push @limits, $limit_yr; + #FIXME: Should return a error to the user, incorect date format specified } @@ -417,47 +422,44 @@ my $indexes2z3950 = { callnum => 'dewey', su => 'subject', 'su,phr' => 'subject', ti => 'title', 'ti,phr' => 'title', se => 'title' }; -for (my $ii = 0; $ii < @operands; ++$ii) -{ - my $name = $indexes2z3950->{$indexes[$ii] || 'kw'}; - if (defined $name && defined $operands[$ii]) - { +for ( my $ii = 0 ; $ii < @operands ; ++$ii ) { + my $name = $indexes2z3950->{ $indexes[$ii] || 'kw' }; + if ( defined $name && defined $operands[$ii] ) { $z3950par ||= {}; $z3950par->{$name} = $operands[$ii] if !exists $z3950par->{$name}; } } - # Params that can only have one value -my $scan = $params->{'scan'}; -my $count = C4::Context->preference('numSearchResults') || 20; -my $results_per_page = $params->{'count'} || $count; -my $offset = $params->{'offset'} || 0; -my $whole_record = $params->{'whole_record'} || 0; -my $weight_search = $params->{'advsearch'} ? $params->{'weight_search'} || 0 : 1; +my $scan = $params->{'scan'}; +my $count = C4::Context->preference('numSearchResults') || 20; +my $results_per_page = $params->{'count'} || $count; +my $offset = $params->{'offset'} || 0; +my $whole_record = $params->{'whole_record'} || 0; +my $weight_search = $params->{'advsearch'} ? $params->{'weight_search'} || 0 : 1; $offset = 0 if $offset < 0; # Define some global variables -my ( $error,$query,$simple_query,$query_cgi,$query_desc,$limit,$limit_cgi,$limit_desc,$query_type); +my ( $error, $query, $simple_query, $query_cgi, $query_desc, $limit, $limit_cgi, $limit_desc, $query_type ); -my $builder = Koha::SearchEngine::QueryBuilder->new( - { index => $Koha::SearchEngine::BIBLIOS_INDEX } ); -my $searcher = Koha::SearchEngine::Search->new( - { index => $Koha::SearchEngine::BIBLIOS_INDEX } ); +my $builder = Koha::SearchEngine::QueryBuilder->new( { index => $Koha::SearchEngine::BIBLIOS_INDEX } ); +my $searcher = Koha::SearchEngine::Search->new( { index => $Koha::SearchEngine::BIBLIOS_INDEX } ); # If index indicates the value is a barcode, we need to preprocess it before searching -for ( my $i = 0; $i < @operands; $i++ ) { - $operands[$i] = barcodedecode($operands[$i]) if (defined($indexes[$i]) && $indexes[$i] eq 'bc'); +for ( my $i = 0 ; $i < @operands ; $i++ ) { + $operands[$i] = barcodedecode( $operands[$i] ) if ( defined( $indexes[$i] ) && $indexes[$i] eq 'bc' ); } ## I. BUILD THE QUERY ( - $error, $query, $simple_query, $query_cgi, - $query_desc, $limit, $limit_cgi, $limit_desc, + $error, $query, $simple_query, $query_cgi, + $query_desc, $limit, $limit_cgi, $limit_desc, $query_type - ) - = $builder->build_query_compat( \@operators, \@operands, \@indexes, \@limits, - \@sort_by, $scan, $lang, { weighted_fields => $weight_search, whole_record => $whole_record }); + ) + = $builder->build_query_compat( + \@operators, \@operands, \@indexes, \@limits, + \@sort_by, $scan, $lang, { weighted_fields => $weight_search, whole_record => $whole_record } + ); $template->param( search_query => $query ) if C4::Context->preference('DumpSearchQueryTemplate'); @@ -467,226 +469,245 @@ my $scan_index_to_use; my $scan_search_term_to_use; if ($query_cgi) { - for my $this_cgi ( split('&', $query_cgi) ) { + for my $this_cgi ( split( '&', $query_cgi ) ) { next unless $this_cgi; $this_cgi =~ m/(.*?)=(.*)/; - my $input_name = $1; + my $input_name = $1; my $input_value = $2; - push @query_inputs, { input_name => $input_name, input_value => Encode::decode_utf8( uri_unescape( $input_value ) ) }; - if ($input_name eq 'idx') { + push @query_inputs, + { input_name => $input_name, input_value => Encode::decode_utf8( uri_unescape($input_value) ) }; + if ( $input_name eq 'idx' ) { + # The form contains multiple fields, so take the first value as the scan index $scan_index_to_use = $input_value unless $scan_index_to_use; } - if (!defined $scan_search_term_to_use && $input_name eq 'q') { - $scan_search_term_to_use = Encode::decode_utf8( uri_unescape( $input_value )); + if ( !defined $scan_search_term_to_use && $input_name eq 'q' ) { + $scan_search_term_to_use = Encode::decode_utf8( uri_unescape($input_value) ); } } } -$template->param ( QUERY_INPUTS => \@query_inputs, - scan_index_to_use => $scan_index_to_use, - scan_search_term_to_use => $scan_search_term_to_use ); +$template->param( + QUERY_INPUTS => \@query_inputs, + scan_index_to_use => $scan_index_to_use, + scan_search_term_to_use => $scan_search_term_to_use +); ## parse the limit_cgi string and put it into a form suitable for s my @limit_inputs; my %active_filters; if ($limit_cgi) { - for my $this_cgi ( split('&', $limit_cgi) ) { + for my $this_cgi ( split( '&', $limit_cgi ) ) { next unless $this_cgi; + # handle special case limit-yr - if ($this_cgi =~ /yr,st-numeric/) { + if ( $this_cgi =~ /yr,st-numeric/ ) { push @limit_inputs, { input_name => 'limit-yr', input_value => $limit_yr_value }; next; } $this_cgi =~ m/(.*=)(.*)/; - my $input_name = $1; + my $input_name = $1; my $input_value = $2; $input_name =~ s/=$//; - push @limit_inputs, { input_name => $input_name, input_value => Encode::decode_utf8( uri_unescape($input_value) ) }; - if( $input_value =~ /search_filter/ ){ + push @limit_inputs, + { input_name => $input_name, input_value => Encode::decode_utf8( uri_unescape($input_value) ) }; + if ( $input_value =~ /search_filter/ ) { my ($filter_id) = ( uri_unescape($input_value) =~ /^search_filter:(.*)$/ ); $active_filters{$filter_id} = 1; } } } -$template->param ( LIMIT_INPUTS => \@limit_inputs ); +$template->param( LIMIT_INPUTS => \@limit_inputs ); ## II. DO THE SEARCH AND GET THE RESULTS -my $total = 0; # the total results for the whole set -my $facets; # this object stores the faceted results that display on the left-hand of the results page +my $total = 0; # the total results for the whole set +my $facets; # this object stores the faceted results that display on the left-hand of the results page my $results_hashref; my $server = 'biblioserver'; eval { my $itemtypes = { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search_with_localization->unblessed } }; ( $error, $results_hashref, $facets ) = $searcher->search_compat( - $query, $simple_query, \@sort_by, [$server], - $results_per_page, $offset, undef, $itemtypes, + $query, $simple_query, \@sort_by, [$server], + $results_per_page, $offset, undef, $itemtypes, $query_type, $scan ); }; -if ($@ || $error) { +if ( $@ || $error ) { my $query_error = q{}; $query_error .= $error if $error; - $query_error .= $@ if $@; - $template->param(query_error => $query_error); + $query_error .= $@ if $@; + $template->param( query_error => $query_error ); output_html_with_http_headers $cgi, $cookie, $template->output; exit; } - my $hits = $results_hashref->{$server}->{"hits"} // 0; - if ( $hits == 0 && $basic_search ){ - $operands[0] = '"'.$operands[0].'"'; #quote it - ## I. BUILD THE QUERY - ( - $error, $query, $simple_query, $query_cgi, - $query_desc, $limit, $limit_cgi, $limit_desc, - $query_type - ) - = $builder->build_query_compat( \@operators, \@operands, \@indexes, \@limits, - \@sort_by, $scan, $lang, { weighted_fields => $weight_search, whole_record => $whole_record }); - my $quoted_results_hashref; - eval { - my $itemtypes = { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search_with_localization->unblessed } }; - ( $error, $quoted_results_hashref, $facets ) = $searcher->search_compat( - $query, $simple_query, \@sort_by, [$server], - $results_per_page, $offset, undef, $itemtypes, - $query_type, $scan - ); - }; - my $quoted_hits = $quoted_results_hashref->{$server}->{"hits"} // 0; - if ( $quoted_hits ){ - $results_hashref->{$server} = $quoted_results_hashref->{$server}; - $hits = $quoted_hits; +my $hits = $results_hashref->{$server}->{"hits"} // 0; +if ( $hits == 0 && $basic_search ) { + $operands[0] = '"' . $operands[0] . '"'; #quote it + ## I. BUILD THE QUERY + ( + $error, $query, $simple_query, $query_cgi, + $query_desc, $limit, $limit_cgi, $limit_desc, + $query_type + ) + = $builder->build_query_compat( + \@operators, \@operands, \@indexes, \@limits, + \@sort_by, $scan, $lang, { weighted_fields => $weight_search, whole_record => $whole_record } + ); + my $quoted_results_hashref; + eval { + my $itemtypes = { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search_with_localization->unblessed } }; + ( $error, $quoted_results_hashref, $facets ) = $searcher->search_compat( + $query, $simple_query, \@sort_by, [$server], + $results_per_page, $offset, undef, $itemtypes, + $query_type, $scan + ); + }; + my $quoted_hits = $quoted_results_hashref->{$server}->{"hits"} // 0; + if ($quoted_hits) { + $results_hashref->{$server} = $quoted_results_hashref->{$server}; + $hits = $quoted_hits; + } +} +my @newresults = searchResults( + { 'interface' => 'intranet' }, $query_desc, $hits, $results_per_page, $offset, $scan, + $results_hashref->{$server}->{"RECORDS"} +); +$total = $total + $hits; + +# Search history +if ( C4::Context->preference('EnableSearchHistory') ) { + unless ($offset) { + my $path_info = $cgi->url( -path_info => 1 ); + my $query_cgi_history = $cgi->url( -query => 1 ); + $query_cgi_history =~ s/^$path_info\?//; + $query_cgi_history =~ s/;/&/g; + my $query_desc_history = $query_desc; + $query_desc_history .= ", $limit_desc" + if $limit_desc; + + C4::Search::History::add( + { + userid => $borrowernumber, + sessionid => $cgi->cookie("CGISESSID"), + query_desc => $query_desc_history, + query_cgi => $query_cgi_history, + total => $total, + type => "biblio", } - } - my @newresults = searchResults({ 'interface' => 'intranet' }, $query_desc, $hits, $results_per_page, $offset, $scan, - $results_hashref->{$server}->{"RECORDS"}); - $total = $total + $hits; + ); + } + $template->param( EnableSearchHistory => 1 ); +} - # Search history - if (C4::Context->preference('EnableSearchHistory')) { - unless ( $offset ) { - my $path_info = $cgi->url(-path_info=>1); - my $query_cgi_history = $cgi->url(-query=>1); - $query_cgi_history =~ s/^$path_info\?//; - $query_cgi_history =~ s/;/&/g; - my $query_desc_history = $query_desc; - $query_desc_history .= ", $limit_desc" - if $limit_desc; +## If there's just one result, redirect to the detail page unless doing an index scan +if ( $total == 1 && !$scan && C4::Context->preference('RedirectToSoleResult') ) { + my $biblionumber = $newresults[0]->{biblionumber}; + my $defaultview = C4::Context->preference('IntranetBiblioDefaultView'); + my $views = {C4::Search::enabled_staff_search_views}; + if ( $defaultview eq 'isbd' && $views->{can_view_ISBD} ) { + print $cgi->redirect("/cgi-bin/koha/catalogue/ISBDdetail.pl?biblionumber=$biblionumber&found1=1"); + } elsif ( $defaultview eq 'marc' && $views->{can_view_MARC} ) { + print $cgi->redirect("/cgi-bin/koha/catalogue/MARCdetail.pl?biblionumber=$biblionumber&found1=1"); + } elsif ( $defaultview eq 'labeled_marc' && $views->{can_view_labeledMARC} ) { + print $cgi->redirect("/cgi-bin/koha/catalogue/labeledMARCdetail.pl?biblionumber=$biblionumber&found1=1"); + } else { + print $cgi->redirect("/cgi-bin/koha/catalogue/detail.pl?biblionumber=$biblionumber&found1=1"); + } + exit; +} - C4::Search::History::add({ - userid => $borrowernumber, - sessionid => $cgi->cookie("CGISESSID"), - query_desc => $query_desc_history, - query_cgi => $query_cgi_history, - total => $total, - type => "biblio", - }); - } - $template->param( EnableSearchHistory => 1 ); - } - - ## If there's just one result, redirect to the detail page unless doing an index scan - if ( $total == 1 && !$scan && C4::Context->preference('RedirectToSoleResult') ) { - my $biblionumber = $newresults[0]->{biblionumber}; - my $defaultview = C4::Context->preference('IntranetBiblioDefaultView'); - my $views = {C4::Search::enabled_staff_search_views}; - if ( $defaultview eq 'isbd' && $views->{can_view_ISBD} ) { - print $cgi->redirect("/cgi-bin/koha/catalogue/ISBDdetail.pl?biblionumber=$biblionumber&found1=1"); - } elsif ( $defaultview eq 'marc' && $views->{can_view_MARC} ) { - print $cgi->redirect("/cgi-bin/koha/catalogue/MARCdetail.pl?biblionumber=$biblionumber&found1=1"); - } elsif ( $defaultview eq 'labeled_marc' && $views->{can_view_labeledMARC} ) { - print $cgi->redirect( - "/cgi-bin/koha/catalogue/labeledMARCdetail.pl?biblionumber=$biblionumber&found1=1"); - } else { - print $cgi->redirect("/cgi-bin/koha/catalogue/detail.pl?biblionumber=$biblionumber&found1=1"); - } - exit; - } - - # set up parameters if user wishes to re-run the search - # as a Z39.50 search - $template->param (z3950_search_params => C4::Search::z3950_search_args($z3950par || $query_desc)); - $template->param(limit_cgi => $limit_cgi); - $template->param(query_cgi => $query_cgi); - $template->param(query_json => encode_json({ +# set up parameters if user wishes to re-run the search +# as a Z39.50 search +$template->param( z3950_search_params => C4::Search::z3950_search_args( $z3950par || $query_desc ) ); +$template->param( limit_cgi => $limit_cgi ); +$template->param( query_cgi => $query_cgi ); +$template->param( + query_json => encode_json( + { operators => \@operators, - operands => \@operands, - indexes => \@indexes - })); - $template->param(limit_json => encode_json({ - limits => \@limits - })); - $template->param(query_desc => $query_desc); - $template->param(limit_desc => $limit_desc); - $template->param(offset => $offset); - $template->param(offset => $offset); + operands => \@operands, + indexes => \@indexes + } + ) +); +$template->param( limit_json => encode_json( { limits => \@limits } ) ); +$template->param( query_desc => $query_desc ); +$template->param( limit_desc => $limit_desc ); +$template->param( offset => $offset ); +$template->param( offset => $offset ); +if ($hits) { + $template->param( total => $hits ); + if ($limit_cgi) { + my $limit_cgi_not_availablity = $limit_cgi; + $limit_cgi_not_availablity =~ s/&limit=available//g; + $template->param( limit_cgi_not_availablity => $limit_cgi_not_availablity ); + } + $template->param( DisplayMultiPlaceHold => $DisplayMultiPlaceHold ); + if ( $query_desc || $limit_desc ) { + $template->param( searchdesc => 1 ); + } + $template->param( results_per_page => $results_per_page ); - if ($hits) { - $template->param(total => $hits); - if ($limit_cgi) { - my $limit_cgi_not_availablity = $limit_cgi; - $limit_cgi_not_availablity =~ s/&limit=available//g; - $template->param(limit_cgi_not_availablity => $limit_cgi_not_availablity); - } - $template->param(DisplayMultiPlaceHold => $DisplayMultiPlaceHold); - if ($query_desc || $limit_desc) { - $template->param(searchdesc => 1); - } - $template->param(results_per_page => $results_per_page); - # must define a value for size if not present in DB - # in order to avoid problems generated by the default size value in TT - foreach my $line (@newresults) { - if ( not exists $line->{'size'} ) { $line->{'size'} = "" } - # while we're checking each line, see if item is in the cart - if ( grep {$_ eq $line->{'biblionumber'}} @cart_list) { - $line->{'incart'} = 1; - } + # must define a value for size if not present in DB + # in order to avoid problems generated by the default size value in TT + foreach my $line (@newresults) { + if ( not exists $line->{'size'} ) { $line->{'size'} = "" } - if ( C4::Context->preference('LocalCoverImages') ) { - $line->{has_local_cover_image} = - $line->{biblio_object} ? $line->{biblio_object}->cover_images->count : 0; - } - } - my( $page_numbers, $hits_to_paginate, $pages, $current_page_number, $previous_page_offset, $next_page_offset, $last_page_offset ) = - Koha::SearchEngine::Search->pagination_bar( - { - hits => $hits, - max_result_window => $searcher->max_result_window, - results_per_page => $results_per_page, - offset => $offset, - sort_by => \@sort_by - } - ); - $template->param( hits_to_paginate => $hits_to_paginate ); - $template->param(SEARCH_RESULTS => \@newresults); - # FIXME: no previous_page_offset when pages < 2 - $template->param( PAGE_NUMBERS => $page_numbers, - last_page_offset => $last_page_offset, - previous_page_offset => $previous_page_offset) unless $pages < 2; - $template->param( next_page_offset => $next_page_offset) unless $pages eq $current_page_number; + # while we're checking each line, see if item is in the cart + if ( grep { $_ eq $line->{'biblionumber'} } @cart_list ) { + $line->{'incart'} = 1; } - - # no hits - else { - $template->param(searchdesc => 1,query_desc => $query_desc,limit_desc => $limit_desc); + if ( C4::Context->preference('LocalCoverImages') ) { + $line->{has_local_cover_image} = + $line->{biblio_object} ? $line->{biblio_object}->cover_images->count : 0; } + } + my ( + $page_numbers, $hits_to_paginate, $pages, $current_page_number, $previous_page_offset, $next_page_offset, + $last_page_offset + ) + = Koha::SearchEngine::Search->pagination_bar( + { + hits => $hits, + max_result_window => $searcher->max_result_window, + results_per_page => $results_per_page, + offset => $offset, + sort_by => \@sort_by + } + ); + $template->param( hits_to_paginate => $hits_to_paginate ); + $template->param( SEARCH_RESULTS => \@newresults ); + + # FIXME: no previous_page_offset when pages < 2 + $template->param( + PAGE_NUMBERS => $page_numbers, + last_page_offset => $last_page_offset, + previous_page_offset => $previous_page_offset + ) unless $pages < 2; + $template->param( next_page_offset => $next_page_offset ) unless $pages eq $current_page_number; +} + +# no hits +else { + $template->param( searchdesc => 1, query_desc => $query_desc, limit_desc => $limit_desc ); +} my $gotonumber = $cgi->param('gotoNumber'); if ( $gotonumber && ( $gotonumber eq 'last' || $gotonumber eq 'first' ) ) { $template->{'VARS'}->{'gotoNumber'} = $gotonumber; } -$template->{'VARS'}->{'gotoPage'} = 'detail.pl'; +$template->{'VARS'}->{'gotoPage'} = 'detail.pl'; my $gotopage = $cgi->param('gotoPage'); $template->{'VARS'}->{'gotoPage'} = $gotopage - if $gotopage && $gotopage =~ m/^(ISBD|labeledMARC|MARC|more)?detail.pl$/; + if $gotopage && $gotopage =~ m/^(ISBD|labeledMARC|MARC|more)?detail.pl$/; -for my $facet ( @$facets ) { +for my $facet (@$facets) { for my $entry ( @{ $facet->{facets} } ) { my $index = $entry->{type_link_value}; my $value = $entry->{facet_link_value}; @@ -694,24 +715,24 @@ for my $facet ( @$facets ) { } } - $template->param( - search_filters => Koha::SearchFilters->search({ staff_client => 1 }, { order_by => "name" }), + search_filters => Koha::SearchFilters->search( { staff_client => 1 }, { order_by => "name" } ), active_filters => \%active_filters, ) if C4::Context->preference('SavedSearchFilters'); $template->param( - #classlist => $classlist, - total => $total, - opacfacets => 1, - facets_loop => $facets, - displayFacetCount=> C4::Context->preference('displayFacetCount')||0, - scan => $scan, - search_error => $error, + + #classlist => $classlist, + total => $total, + opacfacets => 1, + facets_loop => $facets, + displayFacetCount => C4::Context->preference('displayFacetCount') || 0, + scan => $scan, + search_error => $error, ); -if ($query_desc || $limit_desc) { - $template->param(searchdesc => 1); +if ( $query_desc || $limit_desc ) { + $template->param( searchdesc => 1 ); } # VI. BUILD THE TEMPLATE @@ -731,7 +752,6 @@ my $some_public_shelves = Koha::Virtualshelves->get_some_shelves( } ); - $template->param( add_to_some_private_shelves => $some_private_shelves, add_to_some_public_shelves => $some_public_shelves, @@ -739,7 +759,6 @@ $template->param( output_html_with_http_headers $cgi, $cookie, $template->output; - =head2 prepare_adv_search_types my $type = C4::Context->preference("AdvancedSearchTypes") || "itemtypes"; @@ -760,9 +779,8 @@ sub prepare_adv_search_types { my @advanced_search_types = split( /\|/, $types ); # the index parameter is different for item-level itemtypes - my $itype_or_itemtype = - ( C4::Context->preference("item-level_itypes") ) ? 'itype' : 'itemtype'; - my $itemtypes = { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search_with_localization->unblessed } }; + my $itype_or_itemtype = ( C4::Context->preference("item-level_itypes") ) ? 'itype' : 'itemtype'; + my $itemtypes = { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search_with_localization->unblessed } }; my ( $cnt, @result ); foreach my $advanced_srch_type (@advanced_search_types) { @@ -770,23 +788,19 @@ sub prepare_adv_search_types { $advanced_srch_type =~ s/\s*$//; if ( $advanced_srch_type eq 'itemtypes' ) { - # itemtype is a special case, since it's not defined in authorized values + # itemtype is a special case, since it's not defined in authorized values my @itypesloop; foreach my $thisitemtype ( - sort { - $itemtypes->{$a}->{'translated_description'} - cmp $itemtypes->{$b}->{'translated_description'} - } keys %$itemtypes - ) + sort { $itemtypes->{$a}->{'translated_description'} cmp $itemtypes->{$b}->{'translated_description'} } + keys %$itemtypes + ) { my %row = ( number => $cnt++, ccl => "$itype_or_itemtype,phr", code => $thisitemtype, description => $itemtypes->{$thisitemtype}->{'translated_description'}, - imageurl => getitemtypeimagelocation( - 'intranet', $itemtypes->{$thisitemtype}->{'imageurl'} - ), + imageurl => getitemtypeimagelocation( 'intranet', $itemtypes->{$thisitemtype}->{'imageurl'} ), ); push @itypesloop, \%row; } @@ -795,8 +809,8 @@ sub prepare_adv_search_types { code_loop => \@itypesloop ); push @result, \%search_code; - } - else { + } else { + # covers all the other cases: non-itemtype authorized values my $advsearchtypes = GetAuthorisedValues($advanced_srch_type); my @authvalueloop; @@ -806,9 +820,7 @@ sub prepare_adv_search_types { ccl => $advanced_srch_type, code => $thisitemtype->{authorised_value}, description => $thisitemtype->{'lib'}, - imageurl => getitemtypeimagelocation( - 'intranet', $thisitemtype->{'imageurl'} - ), + imageurl => getitemtypeimagelocation( 'intranet', $thisitemtype->{'imageurl'} ), ); push @authvalueloop, \%row; } diff --git a/catalogue/showelastic.pl b/catalogue/showelastic.pl index 0b19704c5b..37aab66682 100755 --- a/catalogue/showelastic.pl +++ b/catalogue/showelastic.pl @@ -19,7 +19,6 @@ # You should have received a copy of the GNU General Public License # along with Koha; if not, see . - use Modern::Perl; # standard or CPAN modules used @@ -32,44 +31,45 @@ use Try::Tiny; # Koha modules used use C4::Context; use C4::Output qw( output_html_with_http_headers ); -use C4::Auth qw(get_template_and_user); +use C4::Auth qw(get_template_and_user); use C4::Biblio; use C4::ImportBatch; -use C4::XSLT ; +use C4::XSLT; use Koha::SearchEngine::Elasticsearch; use LWP::Simple qw/get/; -my $input= CGI->new; +my $input = CGI->new; my ( $template, $loggedinuser, $cookie ) = get_template_and_user( - { - template_name => "catalogue/showelastic.tt", - query => $input, - type => "intranet", - flagsrequired => { catalogue => 1 }, - debug => 1, - } + { + template_name => "catalogue/showelastic.tt", + query => $input, + type => "intranet", + flagsrequired => { catalogue => 1 }, + debug => 1, + } ); my $biblionumber = $input->param('id'); -my $es = Koha::SearchEngine::Elasticsearch->new({index=>'biblios'}); +my $es = Koha::SearchEngine::Elasticsearch->new( { index => 'biblios' } ); my $es_record; my @es_fields; try { - $es_record = $es->get_elasticsearch()->get({ - index => $es->index_name, - id => $biblionumber, - }); -} -catch{ + $es_record = $es->get_elasticsearch()->get( + { + index => $es->index_name, + id => $biblionumber, + } + ); +} catch { warn $_; print $input->redirect("/cgi-bin/koha/errors/404.pl"); }; -for my $field (sort keys %{$es_record} ){ +for my $field ( sort keys %{$es_record} ) { push @es_fields, { $field, $es_record->{$field} }; -}; +} $template->param( esrecord => to_json( \@es_fields ) ); output_html_with_http_headers $input, $cookie, $template->output; diff --git a/catalogue/showmarc.pl b/catalogue/showmarc.pl index 74bb20d4cc..a180681b26 100755 --- a/catalogue/showmarc.pl +++ b/catalogue/showmarc.pl @@ -29,67 +29,64 @@ use Encode; # Koha modules used use C4::Context; use C4::Output qw( output_html_with_http_headers ); -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Biblio qw( GetXmlBiblio ); use C4::XSLT; use Koha::Biblios; use Koha::Import::Records; -my $input= CGI->new; +my $input = CGI->new; my ( $template, $loggedinuser, $cookie ) = get_template_and_user( - { - template_name => "catalogue/showmarc.tt", - query => $input, - type => "intranet", - flagsrequired => { catalogue => 1 }, - } + { + template_name => "catalogue/showmarc.tt", + query => $input, + type => "intranet", + flagsrequired => { catalogue => 1 }, + } ); -my $biblionumber= $input->param('id'); -my $importid= $input->param('importid'); -my $view= $input->param('viewas')||''; +my $biblionumber = $input->param('id'); +my $importid = $input->param('importid'); +my $view = $input->param('viewas') || ''; my $marcflavour = C4::Context->preference('marcflavour'); my $record; my $record_type = 'biblio'; -my $format = $marcflavour eq 'UNIMARC' ? 'UNIMARC' : 'USMARC'; +my $format = $marcflavour eq 'UNIMARC' ? 'UNIMARC' : 'USMARC'; if ($importid) { my $import_record = Koha::Import::Records->find($importid); if ($import_record) { - if ($marcflavour eq 'UNIMARC' && $import_record->record_type eq 'auth') { + if ( $marcflavour eq 'UNIMARC' && $import_record->record_type eq 'auth' ) { $format = 'UNIMARCAUTH'; } $record = $import_record->get_marc_record(); } -} -else { +} else { my $biblio = Koha::Biblios->find($biblionumber); $record = $biblio->metadata->record; } -if(!ref $record) { +if ( !ref $record ) { print $input->redirect("/cgi-bin/koha/errors/404.pl"); exit; } -if($view eq 'card' || $view eq 'html') { - my $xml = $importid ? $record->as_xml($format): GetXmlBiblio($biblionumber); +if ( $view eq 'card' || $view eq 'html' ) { + my $xml = $importid ? $record->as_xml($format) : GetXmlBiblio($biblionumber); my $xsl; - if ( $view eq 'card' ){ + if ( $view eq 'card' ) { $xsl = $marcflavour eq 'UNIMARC' ? 'UNIMARC_compact.xsl' : 'compact.xsl'; - } - else { + } else { $xsl = 'plainMARC.xsl'; } my $htdocs = C4::Context->config('intrahtdocs'); - my ($theme, $lang) = C4::Templates::themelanguage($htdocs, $xsl, 'intranet', $input); + my ( $theme, $lang ) = C4::Templates::themelanguage( $htdocs, $xsl, 'intranet', $input ); $xsl = "$htdocs/$theme/$lang/xslt/$xsl"; - print $input->header(-charset => 'UTF-8'), - Encode::encode_utf8(C4::XSLT::engine->transform($xml, $xsl)); -} -else { + print $input->header( -charset => 'UTF-8' ), + Encode::encode_utf8( C4::XSLT::engine->transform( $xml, $xsl ) ); +} else { $template->param( MARC_FORMATTED => $record->as_formatted ); output_html_with_http_headers $input, $cookie, $template->output; } diff --git a/catalogue/stockrotation.pl b/catalogue/stockrotation.pl index 71d68c4206..f9bc43e490 100755 --- a/catalogue/stockrotation.pl +++ b/catalogue/stockrotation.pl @@ -27,9 +27,9 @@ use Modern::Perl; use CGI; -use C4::Auth qw( get_template_and_user ); -use C4::Output qw( output_html_with_http_headers ); -use C4::Search qw( enabled_staff_search_views ); +use C4::Auth qw( get_template_and_user ); +use C4::Output qw( output_html_with_http_headers ); +use C4::Search qw( enabled_staff_search_views ); use C4::Serials qw( CountSubscriptionFromBiblionumber ); use Koha::Biblio; @@ -40,7 +40,8 @@ use Koha::Util::StockRotation qw( get_stages get_branches toggle_indemand remove my $input = CGI->new; -unless (C4::Context->preference('StockRotation')) { +unless ( C4::Context->preference('StockRotation') ) { + # redirect to Intranet home if self-check is not enabled print $input->redirect("/cgi-bin/koha/mainpage.pl"); exit; @@ -52,19 +53,19 @@ my $op = $params{op}; my $biblionumber = $input->param('biblionumber'); -my ($template, $loggedinuser, $cookie) = get_template_and_user( +my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => 'catalogue/stockrotation.tt', - query => $input, - type => 'intranet', - flagsrequired => { - catalogue => 1, + template_name => 'catalogue/stockrotation.tt', + query => $input, + type => 'intranet', + flagsrequired => { + catalogue => 1, stockrotation => 'manage_rota_items', }, } ); -if (!defined $op) { +if ( !defined $op ) { # List all items along with their associated rotas my $biblio = Koha::Biblios->find($biblionumber); @@ -73,9 +74,7 @@ if (!defined $op) { # Get only rotas with stages my $rotas = Koha::StockRotationRotas->search( - { - 'stockrotationstages.stage_id' => { '!=', undef } - }, + { 'stockrotationstages.stage_id' => { '!=', undef } }, { join => 'stockrotationstages', collapse => 1, @@ -86,16 +85,14 @@ if (!defined $op) { # Construct a model to pass to the view my @item_data = (); - while (my $item = $items->next) { + while ( my $item = $items->next ) { - my $item_hashref = { - bib_item => $item - }; + my $item_hashref = { bib_item => $item }; my $stockrotationitem = $item->stockrotationitem; # If this item is on a rota - if ($stockrotationitem != 0) { + if ( $stockrotationitem != 0 ) { # This item's rota my $rota = $stockrotationitem->stage->rota; @@ -116,56 +113,56 @@ if (!defined $op) { } $template->param( - no_op_set => 1, - rotas => $rotas, - items => \@item_data, - branches => get_branches(), - biblio => $biblio, - biblionumber => $biblio->biblionumber, - stockrotationview => 1, + no_op_set => 1, + rotas => $rotas, + items => \@item_data, + branches => get_branches(), + biblio => $biblio, + biblionumber => $biblio->biblionumber, + stockrotationview => 1, subscriptionsnumber => CountSubscriptionFromBiblionumber($biblionumber), C4::Search::enabled_staff_search_views ); -} elsif ($op eq "cud-toggle_in_demand") { +} elsif ( $op eq "cud-toggle_in_demand" ) { # Toggle in demand - toggle_indemand($params{item_id}, $params{stage_id}); + toggle_indemand( $params{item_id}, $params{stage_id} ); # Return to items list print $input->redirect("?biblionumber=$biblionumber"); -} elsif ($op eq "cud-remove_item_from_stage") { +} elsif ( $op eq "cud-remove_item_from_stage" ) { # Remove from the stage - remove_from_stage($params{item_id}, $params{stage_id}); + remove_from_stage( $params{item_id}, $params{stage_id} ); # Return to items list print $input->redirect("?biblionumber=$biblionumber"); -} elsif ($op eq "cud-move_to_next_stage") { +} elsif ( $op eq "cud-move_to_next_stage" ) { - move_to_next_stage($params{item_id}, $params{stage_id}); + move_to_next_stage( $params{item_id}, $params{stage_id} ); # Return to items list - print $input->redirect("?biblionumber=" . $params{biblionumber}); + print $input->redirect( "?biblionumber=" . $params{biblionumber} ); -} elsif ($op eq "cud-add_item_to_rota") { +} elsif ( $op eq "cud-add_item_to_rota" ) { - my $item = Koha::Items->find($params{item_id}); + my $item = Koha::Items->find( $params{item_id} ); - $item->add_to_rota($params{rota_id}); + $item->add_to_rota( $params{rota_id} ); - print $input->redirect("?biblionumber=" . $params{biblionumber}); + print $input->redirect( "?biblionumber=" . $params{biblionumber} ); -} elsif ($op eq "confirm_remove_from_rota") { +} elsif ( $op eq "confirm_remove_from_rota" ) { $template->param( - op => $params{op}, - stage_id => $params{stage_id}, - item_id => $params{item_id}, - biblionumber => $params{biblionumber}, - stockrotationview => 1, + op => $params{op}, + stage_id => $params{stage_id}, + item_id => $params{item_id}, + biblionumber => $params{biblionumber}, + stockrotationview => 1, subscriptionsnumber => CountSubscriptionFromBiblionumber($biblionumber), C4::Search::enabled_staff_search_views ); diff --git a/catalogue/updateitem.pl b/catalogue/updateitem.pl index cb92efbb16..350f4b14e4 100755 --- a/catalogue/updateitem.pl +++ b/catalogue/updateitem.pl @@ -18,39 +18,39 @@ # You should have received a copy of the GNU General Public License # along with Koha; if not, see . use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Auth qw( checkauth ); use C4::Context; use C4::Output; use C4::Circulation qw( LostItem ); use C4::Reserves; -my $cgi= CGI->new; +my $cgi = CGI->new; -checkauth($cgi, 0, {circulate => 'circulate_remaining_permissions'}, 'intranet'); +checkauth( $cgi, 0, { circulate => 'circulate_remaining_permissions' }, 'intranet' ); -my $op = $cgi->param('op') || ""; -my $biblionumber=$cgi->param('biblionumber'); -my $itemnumber=$cgi->param('itemnumber'); -my $biblioitemnumber=$cgi->param('biblioitemnumber'); -my $itemlost=$cgi->param('itemlost'); -my $itemnotes=$cgi->param('itemnotes'); -my $itemnotes_nonpublic=$cgi->param('itemnotes_nonpublic'); -my $withdrawn=$cgi->param('withdrawn'); -my $damaged=$cgi->param('damaged'); +my $op = $cgi->param('op') || ""; +my $biblionumber = $cgi->param('biblionumber'); +my $itemnumber = $cgi->param('itemnumber'); +my $biblioitemnumber = $cgi->param('biblioitemnumber'); +my $itemlost = $cgi->param('itemlost'); +my $itemnotes = $cgi->param('itemnotes'); +my $itemnotes_nonpublic = $cgi->param('itemnotes_nonpublic'); +my $withdrawn = $cgi->param('withdrawn'); +my $damaged = $cgi->param('damaged'); my $exclude_from_local_holds_priority = $cgi->param('exclude_from_local_holds_priority'); -my $bookable = $cgi->param('bookable') // q{}; +my $bookable = $cgi->param('bookable') // q{}; -my $confirm=$cgi->param('confirm'); -my $dbh = C4::Context->dbh; +my $confirm = $cgi->param('confirm'); +my $dbh = C4::Context->dbh; # get the rest of this item's information -my $item = Koha::Items->find($itemnumber); +my $item = Koha::Items->find($itemnumber); my $item_data_hashref = $item->unblessed; # make sure item statuses are set to 0 if empty or NULL -for ($damaged,$itemlost,$withdrawn) { - if (!$_ or $_ eq "") { +for ( $damaged, $itemlost, $withdrawn ) { + if ( !$_ or $_ eq "" ) { $_ = 0; } } @@ -59,36 +59,41 @@ my $messages = q{}; # modify MARC item if input differs from items table. if ( $op eq "cud-set_non_public_note" ) { - checkauth($cgi, 0, {editcatalogue => 'edit_items'}, 'intranet'); - if ((not defined $item_data_hashref->{'itemnotes_nonpublic'}) or $itemnotes_nonpublic ne $item_data_hashref->{'itemnotes_nonpublic'}) { + checkauth( $cgi, 0, { editcatalogue => 'edit_items' }, 'intranet' ); + if ( ( not defined $item_data_hashref->{'itemnotes_nonpublic'} ) + or $itemnotes_nonpublic ne $item_data_hashref->{'itemnotes_nonpublic'} ) + { $item->itemnotes_nonpublic($itemnotes_nonpublic); } -} -elsif ( $op eq "cud-set_public_note" ) { # i.e., itemnotes parameter passed from form - checkauth($cgi, 0, {editcatalogue => 'edit_items'}, 'intranet'); - if ((not defined $item_data_hashref->{'itemnotes'}) or $itemnotes ne $item_data_hashref->{'itemnotes'}) { +} elsif ( $op eq "cud-set_public_note" ) { # i.e., itemnotes parameter passed from form + checkauth( $cgi, 0, { editcatalogue => 'edit_items' }, 'intranet' ); + if ( ( not defined $item_data_hashref->{'itemnotes'} ) or $itemnotes ne $item_data_hashref->{'itemnotes'} ) { $item->itemnotes($itemnotes); } -} elsif ( $op eq "cud-set_lost" && $itemlost ne $item_data_hashref->{'itemlost'}) { +} elsif ( $op eq "cud-set_lost" && $itemlost ne $item_data_hashref->{'itemlost'} ) { $item->itemlost($itemlost); -} elsif ( $op eq "cud-set_withdrawn" && $withdrawn ne $item_data_hashref->{'withdrawn'}) { +} elsif ( $op eq "cud-set_withdrawn" && $withdrawn ne $item_data_hashref->{'withdrawn'} ) { $item->withdrawn($withdrawn); -} elsif ( $op eq "cud-set_exclude_priority" && $exclude_from_local_holds_priority ne $item_data_hashref->{'exclude_from_local_holds_priority'}) { +} elsif ( $op eq "cud-set_exclude_priority" + && $exclude_from_local_holds_priority ne $item_data_hashref->{'exclude_from_local_holds_priority'} ) +{ $item->exclude_from_local_holds_priority($exclude_from_local_holds_priority); $messages = "updated_exclude_from_local_holds_priority=$exclude_from_local_holds_priority&"; } elsif ( $op eq "cud-set_bookable" && $bookable ne $item_data_hashref->{'bookable'} ) { undef $bookable if $bookable eq q{}; $item->bookable($bookable); -} elsif ( $op eq "cud-set_damaged" && $damaged ne $item_data_hashref->{'damaged'}) { +} elsif ( $op eq "cud-set_damaged" && $damaged ne $item_data_hashref->{'damaged'} ) { $item->damaged($damaged); } else { + #nothings changed, so do nothing. print $cgi->redirect("moredetail.pl?biblionumber=$biblionumber&itemnumber=$itemnumber#item$itemnumber"); - exit; + exit; } $item->store; -LostItem($itemnumber, 'moredetail') if $op eq "cud-set_lost"; +LostItem( $itemnumber, 'moredetail' ) if $op eq "cud-set_lost"; -print $cgi->redirect("moredetail.pl?" . $messages . "biblionumber=$biblionumber&itemnumber=$itemnumber#item$itemnumber"); +print $cgi->redirect( + "moredetail.pl?" . $messages . "biblionumber=$biblionumber&itemnumber=$itemnumber#item$itemnumber" ); diff --git a/cataloguing/addbiblio.pl b/cataloguing/addbiblio.pl index 985bede9a8..b4c3f677c1 100755 --- a/cataloguing/addbiblio.pl +++ b/cataloguing/addbiblio.pl @@ -1,6 +1,5 @@ #!/usr/bin/perl - # Copyright 2000-2002 Katipo Communications # Copyright 2004-2010 BibLibre # @@ -25,7 +24,7 @@ use POSIX qw( strftime ); use Try::Tiny qw(catch try); use C4::Output qw( output_html_with_http_headers ); -use C4::Auth qw( get_template_and_user haspermission ); +use C4::Auth qw( get_template_and_user haspermission ); use C4::Biblio qw( AddBiblio DelBiblio @@ -40,12 +39,12 @@ use C4::Biblio qw( ApplyMarcOverlayRules ); use C4::Search qw( FindDuplicate enabled_staff_search_views ); -use C4::Auth qw( get_template_and_user haspermission ); +use C4::Auth qw( get_template_and_user haspermission ); use C4::Context; use MARC::Record; use C4::ClassSource qw( GetClassSources ); use C4::ImportBatch qw( GetImportRecordMarc ); -use C4::Charset qw( SetMarcUnicodeFlag ); +use C4::Charset qw( SetMarcUnicodeFlag ); use Koha::BiblioFrameworks; use Koha::DateUtils qw( dt_from_string ); @@ -82,16 +81,17 @@ Returns as second parameter the character encoding. =cut sub MARCfindbreeding { - my ( $id ) = @_; - my ($marc, $encoding) = GetImportRecordMarc($id); + my ($id) = @_; + my ( $marc, $encoding ) = GetImportRecordMarc($id); + # remove the - in isbn, koha store isbn without any - if ($marc) { my $record = MARC::Record->new_from_usmarc($marc); - if(C4::Context->preference('autoControlNumber') eq 'biblionumber'){ + if ( C4::Context->preference('autoControlNumber') eq 'biblionumber' ) { my @control_num = $record->field('001'); $record->delete_fields(@control_num); } - my ($isbnfield,$isbnsubfield) = GetMarcFromKohaField( 'biblioitems.isbn' ); + my ( $isbnfield, $isbnsubfield ) = GetMarcFromKohaField('biblioitems.isbn'); if ( $record->field($isbnfield) ) { foreach my $field ( $record->field($isbnfield) ) { foreach my $subfield ( $field->subfield($isbnsubfield) ) { @@ -101,10 +101,11 @@ sub MARCfindbreeding { } } } + # fix the unimarc 100 coded field (with unicode information) - if (C4::Context->preference('marcflavour') eq 'UNIMARC' && $record->subfield(100,'a')) { - my $f100a=$record->subfield(100,'a'); - my $f100 = $record->field(100); + if ( C4::Context->preference('marcflavour') eq 'UNIMARC' && $record->subfield( 100, 'a' ) ) { + my $f100a = $record->subfield( 100, 'a' ); + my $f100 = $record->field(100); my $f100temp = $f100->as_string; $record->delete_field($f100); if ( length($f100temp) > 28 ) { @@ -114,20 +115,19 @@ sub MARCfindbreeding { $record->insert_fields_ordered($f100); } } - - if ( !defined(ref($record)) ) { + + if ( !defined( ref($record) ) ) { return -1; - } - else { + } else { + # normalize author : UNIMARC specific... if ( C4::Context->preference("z3950NormalizeAuthor") and C4::Context->preference("z3950AuthorAuthFields") and C4::Context->preference("marcflavour") eq 'UNIMARC' ) { - my ( $tag, $subfield ) = GetMarcFromKohaField( "biblio.author" ); + my ( $tag, $subfield ) = GetMarcFromKohaField("biblio.author"); - my $auth_fields = - C4::Context->preference("z3950AuthorAuthFields"); + my $auth_fields = C4::Context->preference("z3950AuthorAuthFields"); my @auth_fields = split /,/, $auth_fields; my $field; @@ -137,15 +137,13 @@ sub MARCfindbreeding { my $subfieldcode = shift @$tmpfield; my $subfieldvalue = shift @$tmpfield; if ($field) { - $field->add_subfields( - "$subfieldcode" => $subfieldvalue ) - if ( $subfieldcode ne $subfield ); - } - else { - $field = - MARC::Field->new( $tag, "", "", - $subfieldcode => $subfieldvalue ) - if ( $subfieldcode ne $subfield ); + $field->add_subfields( "$subfieldcode" => $subfieldvalue ) + if ( $subfieldcode ne $subfield ); + } else { + $field = MARC::Field->new( + $tag, "", "", + $subfieldcode => $subfieldvalue + ) if ( $subfieldcode ne $subfield ); } } } @@ -158,14 +156,9 @@ sub MARCfindbreeding { my $number = $record->field($fieldtag)->subfield('d'); if ($title) { $field->add_subfields( - "$subfield" => ucfirst($title) . " " - . ucfirst($firstname) . " " - . $number ); - } - else { - $field->add_subfields( - "$subfield" => ucfirst($firstname) . ", " - . ucfirst($lastname) ); + "$subfield" => ucfirst($title) . " " . ucfirst($firstname) . " " . $number ); + } else { + $field->add_subfields( "$subfield" => ucfirst($firstname) . ", " . ucfirst($lastname) ); } } $record->insert_fields_ordered($field); @@ -183,7 +176,7 @@ sub MARCfindbreeding { =cut sub CreateKey { - return int(rand(1000000)); + return int( rand(1000000) ); } =head2 GetMandatoryFieldZ3950 @@ -195,18 +188,18 @@ sub CreateKey { sub GetMandatoryFieldZ3950 { my $frameworkcode = shift; - my @isbn = GetMarcFromKohaField( 'biblioitems.isbn' ); - my @title = GetMarcFromKohaField( 'biblio.title' ); - my @author = GetMarcFromKohaField( 'biblio.author' ); - my @issn = GetMarcFromKohaField( 'biblioitems.issn' ); - my @lccn = GetMarcFromKohaField( 'biblioitems.lccn' ); - + my @isbn = GetMarcFromKohaField('biblioitems.isbn'); + my @title = GetMarcFromKohaField('biblio.title'); + my @author = GetMarcFromKohaField('biblio.author'); + my @issn = GetMarcFromKohaField('biblioitems.issn'); + my @lccn = GetMarcFromKohaField('biblioitems.lccn'); + return { - $isbn[0].$isbn[1] => 'isbn', - $title[0].$title[1] => 'title', - $author[0].$author[1] => 'author', - $issn[0].$issn[1] => 'issn', - $lccn[0].$lccn[1] => 'lccn', + $isbn[0] . $isbn[1] => 'isbn', + $title[0] . $title[1] => 'title', + $author[0] . $author[1] => 'author', + $issn[0] . $issn[1] => 'issn', + $lccn[0] . $lccn[1] => 'lccn', }; } @@ -226,33 +219,33 @@ sub format_indicator { } sub build_tabs { - my ( $template, $record, $dbh, $encoding,$input ) = @_; + my ( $template, $record, $dbh, $encoding, $input ) = @_; # fill arrays my @loop_data = (); my $tag; my $branch_limit = C4::Context->userenv ? C4::Context->userenv->{"branch"} : ""; - my $query = "SELECT authorised_value, lib + my $query = "SELECT authorised_value, lib FROM authorised_values"; $query .= qq{ LEFT JOIN authorised_values_branches ON ( id = av_id )} if $branch_limit; $query .= " WHERE category = ?"; $query .= " AND ( branchcode = ? OR branchcode IS NULL )" if $branch_limit; $query .= " GROUP BY authorised_value,lib ORDER BY lib, lib_opac"; - my $authorised_values_sth = $dbh->prepare( $query ); + my $authorised_values_sth = $dbh->prepare($query); # in this array, we will push all the 10 tabs # to avoid having 10 tabs in the template : they will all be in the same BIG_LOOP my @BIG_LOOP; my %seen; - my @tab_data; # all tags to display + my @tab_data; # all tags to display - my $max_num_tab=-1; - my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField( "items.itemnumber" ); - foreach my $used ( @$usedTagsLib ){ + my $max_num_tab = -1; + my ( $itemtag, $itemsubfield ) = GetMarcFromKohaField("items.itemnumber"); + foreach my $used (@$usedTagsLib) { - push @tab_data,$used->{tagfield} if not $seen{$used->{tagfield}}; - $seen{$used->{tagfield}}++; + push @tab_data, $used->{tagfield} if not $seen{ $used->{tagfield} }; + $seen{ $used->{tagfield} }++; if ( $used->{tab} > -1 && $used->{tab} >= $max_num_tab @@ -261,7 +254,7 @@ sub build_tabs { $max_num_tab = $used->{tab}; } } - if($max_num_tab >= 9){ + if ( $max_num_tab >= 9 ) { $max_num_tab = 9; } @@ -273,42 +266,40 @@ sub build_tabs { # loop through each tab 0 through 9 for ( my $tabloop = 0 ; $tabloop <= $max_num_tab ; $tabloop++ ) { - my @loop_data = (); #innerloop in the template. - my $i = 0; - foreach my $tag (sort @tab_data) { + my @loop_data = (); #innerloop in the template. + my $i = 0; + foreach my $tag ( sort @tab_data ) { $i++; - next if ! $tag; - my ($indicator1, $indicator2); + next if !$tag; + my ( $indicator1, $indicator2 ); my $index_tag = CreateKey; # if MARC::Record is not empty =>use it as master loop, then add missing subfields that should be in the tab. # if MARC::Record is empty => use tab as master loop. if ( $record ne -1 && ( $record->field($tag) || $tag eq '000' ) ) { my @fields; - if ( $tag ne '000' ) { + if ( $tag ne '000' ) { @fields = $record->field($tag); - } - else { - push @fields, $record->leader(); # if tag == 000 - } - # loop through each field + } else { + push @fields, $record->leader(); # if tag == 000 + } + + # loop through each field foreach my $field (@fields) { - + my @subfields_data; if ( $tag < 10 ) { my ( $value, $subfield ); if ( $tag ne '000' ) { $value = $field->data(); $subfield = "@"; - } - else { + } else { $value = $field; $subfield = '@'; } next if ( $tagslib->{$tag}->{$subfield}->{tab} ne $tabloop ); next - if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq - 'biblio.biblionumber' ); + if ( $tagslib->{$tag}->{$subfield}->{kohafield} eq 'biblio.biblionumber' ); push( @subfields_data, $biblio_form_builder->generate_subfield_form( @@ -327,14 +318,15 @@ sub build_tabs { } ) ); - } - else { + } else { my @subfields = $field->subfields(); foreach my $subfieldcount ( 0 .. $#subfields ) { my $subfield = $subfields[$subfieldcount][0]; my $value = $subfields[$subfieldcount][1]; next if ( length $subfield != 1 ); - next if ( !defined $tagslib->{$tag}->{$subfield} || $tagslib->{$tag}->{$subfield}->{tab} ne $tabloop ); + next + if ( !defined $tagslib->{$tag}->{$subfield} + || $tagslib->{$tag}->{$subfield}->{tab} ne $tabloop ); push( @subfields_data, $biblio_form_builder->generate_subfield_form( @@ -357,24 +349,21 @@ sub build_tabs { } # now, loop again to add parameter subfield that are not in the MARC::Record - foreach my $subfield ( sort( keys %{ $tagslib->{$tag} } ) ) - { + foreach my $subfield ( sort( keys %{ $tagslib->{$tag} } ) ) { next if ( length $subfield != 1 ); next if ( $tagslib->{$tag}->{$subfield}->{tab} ne $tabloop ); next if ( $tag < 10 ); next - if ( ( $tagslib->{$tag}->{$subfield}->{hidden} <= -4 ) + if ( ( $tagslib->{$tag}->{$subfield}->{hidden} <= -4 ) or ( $tagslib->{$tag}->{$subfield}->{hidden} >= 5 ) ) - and not ( $subfield eq "9" and - exists($tagslib->{$tag}->{'a'}->{authtypecode}) and - defined($tagslib->{$tag}->{'a'}->{authtypecode}) and - $tagslib->{$tag}->{'a'}->{authtypecode} ne "" and - $tagslib->{$tag}->{'a'}->{hidden} > -4 and - $tagslib->{$tag}->{'a'}->{hidden} < 5 - ) - ; #check for visibility flag - # if subfield is $9 in a field whose $a is authority-controlled, - # always include in the form regardless of the hidden setting - bug 2206 and 28022 + and not( $subfield eq "9" + and exists( $tagslib->{$tag}->{'a'}->{authtypecode} ) + and defined( $tagslib->{$tag}->{'a'}->{authtypecode} ) + and $tagslib->{$tag}->{'a'}->{authtypecode} ne "" + and $tagslib->{$tag}->{'a'}->{hidden} > -4 + and $tagslib->{$tag}->{'a'}->{hidden} < 5 ); #check for visibility flag + # if subfield is $9 in a field whose $a is authority-controlled, + # always include in the form regardless of the hidden setting - bug 2206 and 28022 next if ( defined( $field->subfield($subfield) ) ); push( @subfields_data, @@ -396,88 +385,89 @@ sub build_tabs { ); } if ( $#subfields_data >= 0 ) { + # build the tag entry. - # note that the random() field is mandatory. Otherwise, on repeated fields, you'll + # note that the random() field is mandatory. Otherwise, on repeated fields, you'll # have twice the same "name" value, and cgi->param() will return only one, making # all subfields to be merged in a single field. my %tag_data = ( tag => $tag, index => $index_tag, tag_lib => $tagslib->{$tag}->{lib}, - repeatable => $tagslib->{$tag}->{repeatable}, - mandatory => $tagslib->{$tag}->{mandatory}, - important => $tagslib->{$tag}->{important}, + repeatable => $tagslib->{$tag}->{repeatable}, + mandatory => $tagslib->{$tag}->{mandatory}, + important => $tagslib->{$tag}->{important}, subfield_loop => \@subfields_data, - fixedfield => $tag < 10?1:0, + fixedfield => $tag < 10 ? 1 : 0, random => CreateKey, ); - if ($tag >= 10){ # no indicator for 00x tags - $tag_data{indicator1} = format_indicator($field->indicator(1)), - $tag_data{indicator2} = format_indicator($field->indicator(2)), + if ( $tag >= 10 ) { # no indicator for 00x tags + $tag_data{indicator1} = format_indicator( $field->indicator(1) ), + $tag_data{indicator2} = format_indicator( $field->indicator(2) ),; } push( @loop_data, \%tag_data ); } - } # foreach $field end + } # foreach $field end - # if breeding is empty - } - else { + # if breeding is empty + } else { my @subfields_data; foreach my $subfield ( sort { $a->{display_order} <=> $b->{display_order} || $a->{subfield} cmp $b->{subfield} } grep { ref($_) && %$_ } # Not a subfield (values for "important", "lib", "mandatory", etc.) or empty - values %{ $tagslib->{$tag} } ) + values %{ $tagslib->{$tag} } + ) { next - if ( ( $subfield->{hidden} <= -4 ) + if ( ( $subfield->{hidden} <= -4 ) or ( $subfield->{hidden} >= 5 ) ) - and not ( $subfield->{subfield} eq "9" and - exists($tagslib->{$tag}->{'a'}->{authtypecode}) and - defined($tagslib->{$tag}->{'a'}->{authtypecode}) and - $tagslib->{$tag}->{'a'}->{authtypecode} ne "" and - $tagslib->{$tag}->{'a'}->{hidden} > -4 and - $tagslib->{$tag}->{'a'}->{hidden} < 5 - ) - ; #check for visibility flag - # if subfield is $9 in a field whose $a is authority-controlled, - # always include in the form regardless of the hidden setting - bug 2206 and 28022 + and not( $subfield->{subfield} eq "9" + and exists( $tagslib->{$tag}->{'a'}->{authtypecode} ) + and defined( $tagslib->{$tag}->{'a'}->{authtypecode} ) + and $tagslib->{$tag}->{'a'}->{authtypecode} ne "" + and $tagslib->{$tag}->{'a'}->{hidden} > -4 + and $tagslib->{$tag}->{'a'}->{hidden} < 5 ); #check for visibility flag + # if subfield is $9 in a field whose $a is authority-controlled, + # always include in the form regardless of the hidden setting - bug 2206 and 28022 next - if ( $subfield->{tab} ne $tabloop ); - push( - @subfields_data, - $biblio_form_builder->generate_subfield_form( - { - tag => $tag, - subfield => $subfield->{subfield}, - value => '', - index_tag => $index_tag, - record => $record, - hostitemnumber => scalar $input->param('hostitemnumber'), - op => $op, - changed_framework => $changed_framework, - breedingid => scalar $input->param('breedingid'), - tagslib => $tagslib, - mandatory_z3950 => $mandatory_z3950, - } - ) - ); + if ( $subfield->{tab} ne $tabloop ); + push( + @subfields_data, + $biblio_form_builder->generate_subfield_form( + { + tag => $tag, + subfield => $subfield->{subfield}, + value => '', + index_tag => $index_tag, + record => $record, + hostitemnumber => scalar $input->param('hostitemnumber'), + op => $op, + changed_framework => $changed_framework, + breedingid => scalar $input->param('breedingid'), + tagslib => $tagslib, + mandatory_z3950 => $mandatory_z3950, + } + ) + ); } if ( $#subfields_data >= 0 ) { my %tag_data = ( - tag => $tag, - index => $index_tag, - tag_lib => $tagslib->{$tag}->{lib}, - repeatable => $tagslib->{$tag}->{repeatable}, - mandatory => $tagslib->{$tag}->{mandatory}, - important => $tagslib->{$tag}->{important}, - indicator1 => ( $indicator1 || $tagslib->{$tag}->{ind1_defaultvalue} ), #if not set, try to load the default value - indicator2 => ( $indicator2 || $tagslib->{$tag}->{ind2_defaultvalue} ), #use short-circuit operator for efficiency + tag => $tag, + index => $index_tag, + tag_lib => $tagslib->{$tag}->{lib}, + repeatable => $tagslib->{$tag}->{repeatable}, + mandatory => $tagslib->{$tag}->{mandatory}, + important => $tagslib->{$tag}->{important}, + indicator1 => ( $indicator1 || $tagslib->{$tag}->{ind1_defaultvalue} ) + , #if not set, try to load the default value + indicator2 => ( $indicator2 || $tagslib->{$tag}->{ind2_defaultvalue} ) + , #use short-circuit operator for efficiency subfield_loop => \@subfields_data, tagfirstsubfield => $subfields_data[0], - fixedfield => $tag < 10?1:0, + fixedfield => $tag < 10 ? 1 : 0, ); - - push @loop_data, \%tag_data ; + + push @loop_data, \%tag_data; } } } @@ -495,19 +485,20 @@ sub build_tabs { # ======================== # MAIN #========================= -my $input = CGI->new; -my $error = $input->param('error'); -my $biblionumber = $input->param('biblionumber'); # if biblionumber exists, it's a modif, not a new biblio. -my $parentbiblio = $input->param('parentbiblionumber'); -my $breedingid = $input->param('breedingid'); -my $z3950 = $input->param('z3950'); -my $mode = $input->param('mode') // q{}; -my $frameworkcode = $input->param('frameworkcode'); -my $redirect = $input->param('redirect'); -my $searchid = $input->param('searchid') // ""; -my $dbh = C4::Context->dbh; +my $input = CGI->new; +my $error = $input->param('error'); +my $biblionumber = $input->param('biblionumber'); # if biblionumber exists, it's a modif, not a new biblio. +my $parentbiblio = $input->param('parentbiblionumber'); +my $breedingid = $input->param('breedingid'); +my $z3950 = $input->param('z3950'); +my $mode = $input->param('mode') // q{}; +my $frameworkcode = $input->param('frameworkcode'); +my $redirect = $input->param('redirect'); +my $searchid = $input->param('searchid') // ""; +my $dbh = C4::Context->dbh; my $hostbiblionumber = $input->param('hostbiblionumber'); -my $hostitemnumber = $input->param('hostitemnumber'); +my $hostitemnumber = $input->param('hostitemnumber'); + # fast cataloguing datas in transit my $fa_circborrowernumber = $input->param('circborrowernumber'); my $fa_barcode = $input->param('barcode'); @@ -517,7 +508,7 @@ my $fa_duedatespec = $input->param('duedatespec'); $op = $input->param('op') // q{}; $frameworkcode = &GetFrameworkCode($biblionumber) - if ( $biblionumber and not( defined $frameworkcode) and $op ne 'cud-addbiblio' ); + if ( $biblionumber and not( defined $frameworkcode ) and $op ne 'cud-addbiblio' ); my $userflags = $frameworkcode eq 'FA' @@ -526,10 +517,10 @@ my $userflags = my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "cataloguing/addbiblio.tt", - query => $input, - type => "intranet", - flagsrequired => { editcatalogue => $userflags }, + template_name => "cataloguing/addbiblio.tt", + query => $input, + type => "intranet", + flagsrequired => { editcatalogue => $userflags }, } ); @@ -543,7 +534,7 @@ $is_a_modif = 0; $changed_framework = 0; if ( $op eq 'cud-change-framework' ) { - $op = $input->param('original_op'); + $op = $input->param('original_op'); $changed_framework = 1; } @@ -567,7 +558,8 @@ if ($biblionumber) { } } -if ($frameworkcode eq 'FA'){ +if ( $frameworkcode eq 'FA' ) { + # We need to grab and set some variables in the template for use on the additems screen $template->param( 'circborrowernumber' => $fa_circborrowernumber, @@ -576,19 +568,21 @@ if ($frameworkcode eq 'FA'){ 'stickyduedate' => $fa_stickyduedate, 'duedatespec' => $fa_duedatespec, ); -} elsif ( $op ne "cud-delete" && - C4::Context->preference('EnableAdvancedCatalogingEditor') && - C4::Auth::haspermission(C4::Context->userenv->{id},{'editcatalogue'=>'advanced_editor'}) && - $input->cookie( 'catalogue_editor_' . $loggedinuser ) eq 'advanced' && - !$breedingid ) { +} elsif ( $op ne "cud-delete" + && C4::Context->preference('EnableAdvancedCatalogingEditor') + && C4::Auth::haspermission( C4::Context->userenv->{id}, { 'editcatalogue' => 'advanced_editor' } ) + && $input->cookie( 'catalogue_editor_' . $loggedinuser ) eq 'advanced' + && !$breedingid ) +{ # Only use the advanced editor for non-fast-cataloging. # breedingid is not handled because those would only come off a Z39.50 # search initiated by the basic editor. - print $input->redirect( '/cgi-bin/koha/cataloguing/editor.pl' . ( $biblionumber ? ( ($op eq 'duplicate'?'#duplicate/':'#catalog/') . $biblionumber ) : '' ) ); + print $input->redirect( '/cgi-bin/koha/cataloguing/editor.pl' + . ( $biblionumber ? ( ( $op eq 'duplicate' ? '#duplicate/' : '#catalog/' ) . $biblionumber ) : '' ) ); exit; } -my $frameworks = Koha::BiblioFrameworks->search({}, { order_by => ['frameworktext'] }); +my $frameworks = Koha::BiblioFrameworks->search( {}, { order_by => ['frameworktext'] } ); $template->param( frameworks => $frameworks, breedingid => $breedingid, @@ -597,11 +591,11 @@ $template->param( my $record = -1; my $encoding = ""; my ( - $biblionumbertagfield, - $biblionumbertagsubfield, - $biblioitemnumtagfield, - $biblioitemnumtagsubfield, - $biblioitemnumber + $biblionumbertagfield, + $biblionumbertagsubfield, + $biblioitemnumtagfield, + $biblioitemnumtagsubfield, + $biblioitemnumber ); if ( $biblio && !$breedingid ) { @@ -614,10 +608,12 @@ if ( $biblio && !$breedingid ) { } } if ($breedingid) { - ( $record, $encoding ) = MARCfindbreeding( $breedingid ) ; + ( $record, $encoding ) = MARCfindbreeding($breedingid); } -if ( $record && $op eq 'duplicate' && - C4::Context->preference('autoControlNumber') eq 'biblionumber' ){ +if ( $record + && $op eq 'duplicate' + && C4::Context->preference('autoControlNumber') eq 'biblionumber' ) +{ my @control_num = $record->field('001'); $record->delete_fields(@control_num); } @@ -634,13 +630,13 @@ if ( $record && $op eq 'duplicate' ) { $record->field('100')->update( a => $s100a ); } } + #populate hostfield if hostbiblionumber is available if ($hostbiblionumber) { my $marcflavour = C4::Context->preference("marcflavour"); $record = MARC::Record->new(); $record->leader(''); - my $field = - PrepHostMarcField( $hostbiblionumber, $hostitemnumber, $marcflavour ); + my $field = PrepHostMarcField( $hostbiblionumber, $hostitemnumber, $marcflavour ); $record->append_fields($field); } @@ -648,8 +644,8 @@ if ($hostbiblionumber) { if ($parentbiblio) { my $marcflavour = C4::Context->preference('marcflavour'); $record = MARC::Record->new(); - SetMarcUnicodeFlag($record, $marcflavour); - my $hostfield = prepare_host_field($parentbiblio,$marcflavour); + SetMarcUnicodeFlag( $record, $marcflavour ); + my $hostfield = prepare_host_field( $parentbiblio, $marcflavour ); if ($hostfield) { $record->append_fields($hostfield); } @@ -657,28 +653,26 @@ if ($parentbiblio) { if ($biblionumber) { $is_a_modif = 1; - my $title = C4::Context->preference('marcflavour') eq "UNIMARC" ? $record->subfield('200', 'a') : $record->title; + my $title = C4::Context->preference('marcflavour') eq "UNIMARC" ? $record->subfield( '200', 'a' ) : $record->title; $template->param( title => $title ); # if it's a modif, retrieve bibli and biblioitem numbers for the future modification of old-DB. - ( $biblionumbertagfield, $biblionumbertagsubfield ) = - &GetMarcFromKohaField( "biblio.biblionumber" ); - ( $biblioitemnumtagfield, $biblioitemnumtagsubfield ) = - &GetMarcFromKohaField( "biblioitems.biblioitemnumber" ); + ( $biblionumbertagfield, $biblionumbertagsubfield ) = &GetMarcFromKohaField("biblio.biblionumber"); + ( $biblioitemnumtagfield, $biblioitemnumtagsubfield ) = &GetMarcFromKohaField("biblioitems.biblioitemnumber"); # search biblioitems value - my $sth = $dbh->prepare("select biblioitemnumber from biblioitems where biblionumber=?"); + my $sth = $dbh->prepare("select biblioitemnumber from biblioitems where biblionumber=?"); $sth->execute($biblionumber); ($biblioitemnumber) = $sth->fetchrow; - if (C4::Context->preference('MARCOverlayRules')) { + if ( C4::Context->preference('MARCOverlayRules') ) { $record = ApplyMarcOverlayRules( { biblionumber => $biblionumber, record => $record, - overlay_context => { - source => $z3950 ? 'z3950' : 'intranet', - categorycode => $logged_in_patron->categorycode, - userid => $logged_in_patron->userid, + overlay_context => { + source => $z3950 ? 'z3950' : 'intranet', + categorycode => $logged_in_patron->categorycode, + userid => $logged_in_patron->userid, } } ); @@ -687,23 +681,27 @@ if ($biblionumber) { #------------------------------------------------------------------------------------- if ( $op eq "cud-addbiblio" ) { -#------------------------------------------------------------------------------------- + + #------------------------------------------------------------------------------------- $template->param( biblionumberdata => $biblionumber, ); + # getting html input my @params = $input->multi_param(); $record = TransformHtmlToMarc( $input, 1 ); + # check for a duplicate my ( $duplicatebiblionumber, $duplicatetitle ); if ( !$is_a_modif ) { ( $duplicatebiblionumber, $duplicatetitle ) = FindDuplicate($record); } my $confirm_not_duplicate = $input->param('confirm_not_duplicate'); + # it is not a duplicate (determined either by Koha itself or by user checking it's not a duplicate) if ( !$duplicatebiblionumber or $confirm_not_duplicate ) { my $oldbibitemnum; - if ( $is_a_modif ) { + if ($is_a_modif) { ModBiblio( $record, $biblionumber, @@ -716,81 +714,93 @@ if ( $op eq "cud-addbiblio" ) { } } ); - } - else { + } else { ( $biblionumber, $oldbibitemnum ) = AddBiblio( $record, $frameworkcode ); } - if ($redirect eq "items" || ($mode ne "popup" && !$is_a_modif && $redirect ne "view" && $redirect ne "just_save")){ - if ($frameworkcode eq 'FA'){ - print $input->redirect( - '/cgi-bin/koha/cataloguing/additem.pl?' - .'biblionumber='.$biblionumber - .'&frameworkcode='.$frameworkcode - .'&circborrowernumber='.$fa_circborrowernumber - .'&branch='.$fa_branch - .'&barcode='.uri_escape_utf8($fa_barcode) - .'&stickyduedate='.$fa_stickyduedate - .'&duedatespec='.$fa_duedatespec - ); - exit; - } - else { - print $input->redirect( - "/cgi-bin/koha/cataloguing/additem.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode&searchid=$searchid" - ); - exit; - } - } - elsif(($is_a_modif || $redirect eq "view") && $redirect ne "just_save"){ - my $defaultview = C4::Context->preference('IntranetBiblioDefaultView'); - my $views = { C4::Search::enabled_staff_search_views }; - if ($defaultview eq 'isbd' && $views->{can_view_ISBD}) { - print $input->redirect("/cgi-bin/koha/catalogue/ISBDdetail.pl?biblionumber=$biblionumber&searchid=$searchid"); - } elsif ($defaultview eq 'marc' && $views->{can_view_MARC}) { - print $input->redirect("/cgi-bin/koha/catalogue/MARCdetail.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode&searchid=$searchid"); - } elsif ($defaultview eq 'labeled_marc' && $views->{can_view_labeledMARC}) { - print $input->redirect("/cgi-bin/koha/catalogue/labeledMARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid"); + if ( $redirect eq "items" + || ( $mode ne "popup" && !$is_a_modif && $redirect ne "view" && $redirect ne "just_save" ) ) + { + if ( $frameworkcode eq 'FA' ) { + print $input->redirect( '/cgi-bin/koha/cataloguing/additem.pl?' + . 'biblionumber=' + . $biblionumber + . '&frameworkcode=' + . $frameworkcode + . '&circborrowernumber=' + . $fa_circborrowernumber + . '&branch=' + . $fa_branch + . '&barcode=' + . uri_escape_utf8($fa_barcode) + . '&stickyduedate=' + . $fa_stickyduedate + . '&duedatespec=' + . $fa_duedatespec ); + exit; } else { - print $input->redirect("/cgi-bin/koha/catalogue/detail.pl?biblionumber=$biblionumber&searchid=$searchid"); + print $input->redirect( + "/cgi-bin/koha/cataloguing/additem.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode&searchid=$searchid" + ); + exit; + } + } elsif ( ( $is_a_modif || $redirect eq "view" ) && $redirect ne "just_save" ) { + my $defaultview = C4::Context->preference('IntranetBiblioDefaultView'); + my $views = {C4::Search::enabled_staff_search_views}; + if ( $defaultview eq 'isbd' && $views->{can_view_ISBD} ) { + print $input->redirect( + "/cgi-bin/koha/catalogue/ISBDdetail.pl?biblionumber=$biblionumber&searchid=$searchid"); + } elsif ( $defaultview eq 'marc' && $views->{can_view_MARC} ) { + print $input->redirect( + "/cgi-bin/koha/catalogue/MARCdetail.pl?biblionumber=$biblionumber&frameworkcode=$frameworkcode&searchid=$searchid" + ); + } elsif ( $defaultview eq 'labeled_marc' && $views->{can_view_labeledMARC} ) { + print $input->redirect( + "/cgi-bin/koha/catalogue/labeledMARCdetail.pl?biblionumber=$biblionumber&searchid=$searchid"); + } else { + print $input->redirect( + "/cgi-bin/koha/catalogue/detail.pl?biblionumber=$biblionumber&searchid=$searchid"); } exit; - } - elsif ($redirect eq "just_save"){ - my $tab = $input->param('current_tab'); - print $input->redirect("/cgi-bin/koha/cataloguing/addbiblio.pl?biblionumber=$biblionumber&framework=$frameworkcode&tab=$tab&searchid=$searchid"); - } - else { - $template->param( - biblionumber => $biblionumber, - done =>1, - popup =>1 - ); - if ( $record ne '-1' ) { - my $title = C4::Context->preference('marcflavour') eq "UNIMARC" ? $record->subfield('200', 'a') : $record->title; - $template->param( title => $title ); - } - $template->param( - popup => $mode, - itemtype => $frameworkcode, - ); - output_html_with_http_headers $input, $cookie, $template->output; - exit; + } elsif ( $redirect eq "just_save" ) { + my $tab = $input->param('current_tab'); + print $input->redirect( + "/cgi-bin/koha/cataloguing/addbiblio.pl?biblionumber=$biblionumber&framework=$frameworkcode&tab=$tab&searchid=$searchid" + ); + } else { + $template->param( + biblionumber => $biblionumber, + done => 1, + popup => 1 + ); + if ( $record ne '-1' ) { + my $title = + C4::Context->preference('marcflavour') eq "UNIMARC" + ? $record->subfield( '200', 'a' ) + : $record->title; + $template->param( title => $title ); + } + $template->param( + popup => $mode, + itemtype => $frameworkcode, + ); + output_html_with_http_headers $input, $cookie, $template->output; + exit; } } else { - # it may be a duplicate, warn the user and do nothing - build_tabs ($template, $record, $dbh,$encoding,$input); + + # it may be a duplicate, warn the user and do nothing + build_tabs( $template, $record, $dbh, $encoding, $input ); $template->param( - biblionumber => $biblionumber, - biblioitemnumber => $biblioitemnumber, - duplicatebiblionumber => $duplicatebiblionumber, - duplicatebibid => $duplicatebiblionumber, - duplicatetitle => $duplicatetitle, + biblionumber => $biblionumber, + biblioitemnumber => $biblioitemnumber, + duplicatebiblionumber => $duplicatebiblionumber, + duplicatebibid => $duplicatebiblionumber, + duplicatetitle => $duplicatetitle, ); } -} - -elsif ( $op eq "cud-delete" ) { + +} elsif ( $op eq "cud-delete" ) { # Cancel attached order lines first before deleting biblio ! my $error; @@ -806,19 +816,22 @@ elsif ( $op eq "cud-delete" ) { }; if ($error) { + #FIXME This should be handled in template alert warn "ERROR when DELETING BIBLIO $biblionumber : $error"; - print "Content-Type: text/html\n\n

ERROR when DELETING BIBLIO $biblionumber : $error

"; + print + "Content-Type: text/html\n\n

ERROR when DELETING BIBLIO $biblionumber : $error

"; exit; } - print $input->redirect('/cgi-bin/koha/catalogue/search.pl' . ($searchid ? "?searchid=$searchid" : "")); + print $input->redirect( '/cgi-bin/koha/catalogue/search.pl' . ( $searchid ? "?searchid=$searchid" : "" ) ); exit; - + } else { - #---------------------------------------------------------------------------- - # If we're in a duplication case, we have to set to "" the biblionumber - # as we'll save the biblio as a new one. + + #---------------------------------------------------------------------------- + # If we're in a duplication case, we have to set to "" the biblionumber + # as we'll save the biblio as a new one. $template->param( biblionumberdata => $biblionumber, op => $op, @@ -828,42 +841,42 @@ elsif ( $op eq "cud-delete" ) { $biblionumber = ""; } - if($changed_framework){ + if ($changed_framework) { $record = TransformHtmlToMarc( $input, 1 ); - } - elsif( $record ne -1 ) { -#FIXME: it's kind of silly to go from MARC::Record to MARC::File::XML and then back again just to fix the encoding + } elsif ( $record ne -1 ) { + + #FIXME: it's kind of silly to go from MARC::Record to MARC::File::XML and then back again just to fix the encoding eval { my $uxml = $record->as_xml; MARC::Record::default_record_format("UNIMARC") - if ( C4::Context->preference("marcflavour") eq "UNIMARC" ); + if ( C4::Context->preference("marcflavour") eq "UNIMARC" ); my $urecord = MARC::Record::new_from_xml( $uxml, 'UTF-8' ); $record = $urecord; }; } - build_tabs( $template, $record, $dbh, $encoding,$input ); + build_tabs( $template, $record, $dbh, $encoding, $input ); $template->param( biblionumber => $biblionumber, - biblionumbertagfield => $biblionumbertagfield, - biblionumbertagsubfield => $biblionumbertagsubfield, + biblionumbertagfield => $biblionumbertagfield, + biblionumbertagsubfield => $biblionumbertagsubfield, biblioitemnumtagfield => $biblioitemnumtagfield, biblioitemnumtagsubfield => $biblioitemnumtagsubfield, biblioitemnumber => $biblioitemnumber, - hostbiblionumber => $hostbiblionumber, - hostitemnumber => $hostitemnumber + hostbiblionumber => $hostbiblionumber, + hostitemnumber => $hostitemnumber ); } if ( $record ne '-1' ) { - my $title = C4::Context->preference('marcflavour') eq "UNIMARC" ? $record->subfield('200', 'a') : $record->title; + my $title = C4::Context->preference('marcflavour') eq "UNIMARC" ? $record->subfield( '200', 'a' ) : $record->title; $template->param( title => $title ); } $template->param( - popup => $mode, - frameworkcode => $frameworkcode, - itemtype => $frameworkcode, + popup => $mode, + frameworkcode => $frameworkcode, + itemtype => $frameworkcode, borrowernumber => $loggedinuser, - tab => scalar $input->param('tab') + tab => scalar $input->param('tab') ); $template->{'VARS'}->{'searchid'} = $searchid; diff --git a/cataloguing/addbooks.pl b/cataloguing/addbooks.pl index 2206c5e143..398192e17a 100755 --- a/cataloguing/addbooks.pl +++ b/cataloguing/addbooks.pl @@ -1,6 +1,5 @@ #!/usr/bin/perl - # Copyright 2000-2002 Katipo Communications # # This file is part of Koha. @@ -26,11 +25,11 @@ use Modern::Perl; -use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); use C4::Breeding qw( BreedingSearch ); -use C4::Output qw( output_html_with_http_headers pagination_bar ); -use C4::Koha qw( getnbpages ); +use C4::Output qw( output_html_with_http_headers pagination_bar ); +use C4::Koha qw( getnbpages ); use C4::Languages; use C4::Search qw( searchResults z3950_search_args ); @@ -41,20 +40,19 @@ use Koha::Z3950Servers; my $input = CGI->new; -my $success = $input->param('biblioitem'); -my $query = $input->param('q'); -my @value = $input->multi_param('value'); -my $page = $input->param('page') || 1; +my $success = $input->param('biblioitem'); +my $query = $input->param('q'); +my @value = $input->multi_param('value'); +my $page = $input->param('page') || 1; my $results_per_page = 20; -my $lang = C4::Languages::getlanguage($input); - +my $lang = C4::Languages::getlanguage($input); my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "cataloguing/addbooks.tt", - query => $input, - type => "intranet", - flagsrequired => { editcatalogue => '*' }, + template_name => "cataloguing/addbooks.tt", + query => $input, + type => "intranet", + flagsrequired => { editcatalogue => '*' }, } ); @@ -66,17 +64,16 @@ if ($query) { my $builtquery; my $query_cgi; - my $builder = Koha::SearchEngine::QueryBuilder->new( - { index => $Koha::SearchEngine::BIBLIOS_INDEX } ); - my $searcher = Koha::SearchEngine::Search->new( - { index => $Koha::SearchEngine::BIBLIOS_INDEX } ); + my $builder = Koha::SearchEngine::QueryBuilder->new( { index => $Koha::SearchEngine::BIBLIOS_INDEX } ); + my $searcher = Koha::SearchEngine::Search->new( { index => $Koha::SearchEngine::BIBLIOS_INDEX } ); ( undef, $builtquery, undef, $query_cgi, undef, undef, undef, undef, undef, undef ) = - $builder->build_query_compat( undef, \@operands, undef, undef, undef, 0, $lang, { weighted_fields => 1 }); + $builder->build_query_compat( undef, \@operands, undef, undef, undef, 0, $lang, { weighted_fields => 1 } ); $template->param( search_query => $builtquery ) if C4::Context->preference('DumpSearchQueryTemplate'); # find results - my ( $error, $marcresults, $total_hits ) = $searcher->simple_search_compat($builtquery, $results_per_page * ($page - 1), $results_per_page); + my ( $error, $marcresults, $total_hits ) = + $searcher->simple_search_compat( $builtquery, $results_per_page * ( $page - 1 ), $results_per_page ); if ( defined $error ) { $template->param( error => $error ); @@ -88,7 +85,8 @@ if ($query) { # format output # SimpleSearch() give the results per page we want, so 0 offet here my $total = @{$marcresults}; - my @newresults = searchResults( {'interface' => 'intranet'}, $query, $total, $results_per_page, 0, 0, $marcresults ); + my @newresults = + searchResults( { 'interface' => 'intranet' }, $query, $total, $results_per_page, 0, 0, $marcresults ); foreach my $line (@newresults) { if ( not exists $line->{'size'} ) { $line->{'size'} = "" } } @@ -96,7 +94,10 @@ if ($query) { total => $total_hits, query => $query, resultsloop => \@newresults, - pagination_bar => pagination_bar( "/cgi-bin/koha/cataloguing/addbooks.pl?$query_cgi&", getnbpages( $total_hits, $results_per_page ), $page, 'page' ), + pagination_bar => pagination_bar( + "/cgi-bin/koha/cataloguing/addbooks.pl?$query_cgi&", getnbpages( $total_hits, $results_per_page ), $page, + 'page' + ), ); } @@ -105,7 +106,7 @@ if ($query) { my $countbr = 0; my @resultsbr; if ($query) { - ( $countbr, @resultsbr ) = BreedingSearch( $query ); + ( $countbr, @resultsbr ) = BreedingSearch($query); } my $breeding_loop = []; for my $resultsbr (@resultsbr) { @@ -122,16 +123,16 @@ for my $resultsbr (@resultsbr) { my $servers = Koha::Z3950Servers->search( { recordtype => 'biblio', - servertype => ['zed','sru'], + servertype => [ 'zed', 'sru' ], } ); -my $frameworks = Koha::BiblioFrameworks->search({}, { order_by => ['frameworktext'] }); +my $frameworks = Koha::BiblioFrameworks->search( {}, { order_by => ['frameworktext'] } ); $template->param( - servers => $servers, - frameworks => $frameworks, - breeding_count => $countbr, - breeding_loop => $breeding_loop, + servers => $servers, + frameworks => $frameworks, + breeding_count => $countbr, + breeding_loop => $breeding_loop, z3950_search_params => C4::Search::z3950_search_args($query), ); diff --git a/cataloguing/cataloging-home.pl b/cataloguing/cataloging-home.pl index d8e76d23cc..987ddc0955 100755 --- a/cataloguing/cataloging-home.pl +++ b/cataloguing/cataloging-home.pl @@ -17,8 +17,8 @@ # use Modern::Perl; -use CGI qw ( -utf8 ); -use C4::Auth qw( get_cataloguing_page_permissions get_template_and_user ); +use CGI qw ( -utf8 ); +use C4::Auth qw( get_cataloguing_page_permissions get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use C4::Context; @@ -38,16 +38,16 @@ my ( $template, $loggedinuser, $cookie, $flags ) = get_template_and_user( my $servers = Koha::Z3950Servers->search( { recordtype => 'biblio', - servertype => ['zed','sru'], + servertype => [ 'zed', 'sru' ], } ); -my $frameworks = Koha::BiblioFrameworks->search({}, { order_by => ['frameworktext'] }); -$template->param( fast_cataloging => 1 ) if $frameworks->find({ frameworkcode => 'FA' }); +my $frameworks = Koha::BiblioFrameworks->search( {}, { order_by => ['frameworktext'] } ); +$template->param( fast_cataloging => 1 ) if $frameworks->find( { frameworkcode => 'FA' } ); $template->param( - servers => $servers, - frameworks => $frameworks + servers => $servers, + frameworks => $frameworks ); output_html_with_http_headers $query, $cookie, $template->output; diff --git a/cataloguing/concerns.pl b/cataloguing/concerns.pl index 6434983965..6fb4e6971a 100755 --- a/cataloguing/concerns.pl +++ b/cataloguing/concerns.pl @@ -19,16 +19,16 @@ use Modern::Perl; use CGI qw ( -utf8 ); use C4::Context; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); my $query = CGI->new; my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "cataloguing/concerns.tt", - query => $query, - type => "intranet", - flagsrequired => { editcatalogue => 'edit_catalogue' }, + template_name => "cataloguing/concerns.tt", + query => $query, + type => "intranet", + flagsrequired => { editcatalogue => 'edit_catalogue' }, } ); diff --git a/cataloguing/editor.pl b/cataloguing/editor.pl index 3e09b3b09d..f3057011a1 100755 --- a/cataloguing/editor.pl +++ b/cataloguing/editor.pl @@ -35,10 +35,10 @@ my $input = CGI->new; my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => 'cataloguing/editor.tt', - query => $input, - type => 'intranet', - flagsrequired => { + template_name => 'cataloguing/editor.tt', + query => $input, + type => 'intranet', + flagsrequired => { editcatalogue => { 'edit_catalogue' => 1, 'advanced_editor' => 1 @@ -55,30 +55,35 @@ $template->param( ); # Available import batches -$template->{VARS}->{editable_batches} = [ $schema->resultset('ImportBatch')->search( - { - batch_type => [ 'batch', 'webservice' ], - import_status => 'staged', - }, - { result_class => 'DBIx::Class::ResultClass::HashRefInflator' }, -) ]; +$template->{VARS}->{editable_batches} = [ + $schema->resultset('ImportBatch')->search( + { + batch_type => [ 'batch', 'webservice' ], + import_status => 'staged', + }, + { result_class => 'DBIx::Class::ResultClass::HashRefInflator' }, + ) +]; # Needed information for cataloging plugins -$template->{VARS}->{DefaultLanguageField008} = pack( 'A3', C4::Context->preference('DefaultLanguageField008') || 'eng' ); +$template->{VARS}->{DefaultLanguageField008} = + pack( 'A3', C4::Context->preference('DefaultLanguageField008') || 'eng' ); $template->{VARS}->{DefaultCountryField008} = pack( 'A3', C4::Context->preference('DefaultCountryField008') || '|||' ); -my $authtags = Koha::MarcSubfieldStructures->search({ authtypecode => { '!=' => '' }, 'frameworkcode' => '' }); +my $authtags = Koha::MarcSubfieldStructures->search( { authtypecode => { '!=' => '' }, 'frameworkcode' => '' } ); $template->{VARS}->{authtags} = $authtags; -my $frameworks = Koha::BiblioFrameworks->search({}, { order_by => ['frameworktext'] }); +my $frameworks = Koha::BiblioFrameworks->search( {}, { order_by => ['frameworktext'] } ); $template->{VARS}->{frameworks} = $frameworks; # Z39.50 servers my $dbh = C4::Context->dbh; -$template->{VARS}->{z3950_servers} = $dbh->selectall_arrayref( q{ +$template->{VARS}->{z3950_servers} = $dbh->selectall_arrayref( + q{ SELECT * FROM z3950servers WHERE recordtype != 'authority' AND servertype = 'zed' ORDER BY `rank`,servername -}, { Slice => {} } ); +}, { Slice => {} } +); output_html_with_http_headers $input, $cookie, $template->output; diff --git a/cataloguing/linkitem.pl b/cataloguing/linkitem.pl index 7497ec1ba7..d7bf9497d9 100755 --- a/cataloguing/linkitem.pl +++ b/cataloguing/linkitem.pl @@ -21,39 +21,38 @@ use Modern::Perl; -use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use C4::Biblio qw( ModBiblio PrepHostMarcField ); use C4::Context; use Koha::Biblios; - my $query = CGI->new; -my ($template, $loggedinuser, $cookie) = get_template_and_user( +my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "cataloguing/linkitem.tt", - query => $query, - type => "intranet", - flagsrequired => { editcatalogue => 'edit_catalogue' }, + template_name => "cataloguing/linkitem.tt", + query => $query, + type => "intranet", + flagsrequired => { editcatalogue => 'edit_catalogue' }, } ); my $biblionumber = $query->param('biblionumber'); my $barcode = $query->param('barcode'); my $op = $query->param('op') || q{}; -my $biblio = Koha::Biblios->find($biblionumber); -my $record = $biblio->metadata->record; -my $marcflavour = C4::Context->preference("marcflavour"); -$marcflavour ||="MARC21"; -if ($marcflavour eq 'MARC21') { - $template->param(bibliotitle => $record->subfield('245','a')); -} elsif ($marcflavour eq 'UNIMARC') { - $template->param(bibliotitle => $record->subfield('200','a')); +my $biblio = Koha::Biblios->find($biblionumber); +my $record = $biblio->metadata->record; +my $marcflavour = C4::Context->preference("marcflavour"); +$marcflavour ||= "MARC21"; +if ( $marcflavour eq 'MARC21' ) { + $template->param( bibliotitle => $record->subfield( '245', 'a' ) ); +} elsif ( $marcflavour eq 'UNIMARC' ) { + $template->param( bibliotitle => $record->subfield( '200', 'a' ) ); } -$template->param(biblionumber => $biblionumber); +$template->param( biblionumber => $biblionumber ); if ( $op eq 'cud-linkitem' && $barcode && $biblionumber ) { @@ -66,8 +65,7 @@ if ( $op eq 'cud-linkitem' && $barcode && $biblionumber ) { my $modresult = ModBiblio( $record, $biblionumber, '' ); if ($modresult) { $template->param( success => 1 ); - } - else { + } else { $template->param( error => 1, errornomodbiblio => 1 @@ -76,8 +74,7 @@ if ( $op eq 'cud-linkitem' && $barcode && $biblionumber ) { $template->param( hostitemnumber => $item->itemnumber, ); - } - else { + } else { $template->param( error => 1, errornohostitemnumber => 1, @@ -85,15 +82,13 @@ if ( $op eq 'cud-linkitem' && $barcode && $biblionumber ) { } $template->param( - barcode => $barcode, + barcode => $barcode, ); -} -else { +} else { $template->param( missingparameter => 1 ); if ( !$barcode ) { $template->param( missingbarcode => 1 ); } if ( !$biblionumber ) { $template->param( missingbiblionumber => 1 ); } } - output_html_with_http_headers $query, $cookie, $template->output; diff --git a/cataloguing/merge.pl b/cataloguing/merge.pl index 9fe7bc4f8b..1eaaf4a3e7 100755 --- a/cataloguing/merge.pl +++ b/cataloguing/merge.pl @@ -22,7 +22,7 @@ use Modern::Perl; use CGI qw ( -utf8 ); use C4::Output qw( output_html_with_http_headers ); -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Biblio qw( DelBiblio GetBiblioData @@ -32,8 +32,8 @@ use C4::Biblio qw( ModBiblio TransformHtmlToMarc ); -use C4::Serials qw( CountSubscriptionFromBiblionumber ); -use C4::Reserves qw( MergeHolds ); +use C4::Serials qw( CountSubscriptionFromBiblionumber ); +use C4::Reserves qw( MergeHolds ); use C4::Acquisition qw( ModOrder GetOrdersByBiblionumber ); use Koha::BiblioFrameworks; @@ -44,26 +44,27 @@ use Koha::MetadataRecord; my $input = CGI->new; my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "cataloguing/merge.tt", - query => $input, - type => "intranet", - flagsrequired => { editcatalogue => 'edit_catalogue' }, + template_name => "cataloguing/merge.tt", + query => $input, + type => "intranet", + flagsrequired => { editcatalogue => 'edit_catalogue' }, } ); my @biblionumbers = $input->multi_param('biblionumber'); -my $op = $input->param('op') || q{}; +my $op = $input->param('op') || q{}; my @errors; + #------------------------ # Merging #------------------------ -if ($op eq 'cud-merge') { +if ( $op eq 'cud-merge' ) { my $dbh = C4::Context->dbh; # Creating a new record from the html code - my $record = TransformHtmlToMarc( $input, 1 ); + my $record = TransformHtmlToMarc( $input, 1 ); my $ref_biblionumber = $input->param('ref_biblionumber'); @biblionumbers = grep { $_ != $ref_biblionumber } @biblionumbers; @@ -72,54 +73,56 @@ if ($op eq 'cud-merge') { my $report_fields_str = $input->param('report_fields'); $report_fields_str ||= C4::Context->preference('MergeReportFields'); my @report_fields; - foreach my $field_str (split /,/, $report_fields_str) { - if ($field_str =~ /(\d{3})([0-9a-z]*)/) { - my ($field, $subfields) = ($1, $2); + foreach my $field_str ( split /,/, $report_fields_str ) { + if ( $field_str =~ /(\d{3})([0-9a-z]*)/ ) { + my ( $field, $subfields ) = ( $1, $2 ); push @report_fields, { - tag => $field, + tag => $field, subfields => [ split //, $subfields ] - } + }; } } # Rewriting the leader my $biblio = Koha::Biblios->find($ref_biblionumber); - $record->leader($biblio->metadata->record->leader()); + $record->leader( $biblio->metadata->record->leader() ); + #Take new framework code my $frameworkcode = $input->param('frameworkcode'); # Modifying the reference record - ModBiblio($record, $ref_biblionumber, $frameworkcode); + ModBiblio( $record, $ref_biblionumber, $frameworkcode ); my $report_header = {}; - foreach my $biblionumber ($ref_biblionumber, @biblionumbers) { + foreach my $biblionumber ( $ref_biblionumber, @biblionumbers ) { + # build report - my $biblio = Koha::Biblios->find($biblionumber); - my $marcrecord = $biblio->metadata->record; + my $biblio = Koha::Biblios->find($biblionumber); + my $marcrecord = $biblio->metadata->record; my %report_record = ( biblionumber => $biblionumber, - fields => {}, + fields => {}, ); foreach my $field (@report_fields) { - my @marcfields = $marcrecord->field($field->{tag}); + my @marcfields = $marcrecord->field( $field->{tag} ); foreach my $marcfield (@marcfields) { my $tag = $marcfield->tag(); - if (scalar @{$field->{subfields}}) { - foreach my $subfield (@{$field->{subfields}}) { + if ( scalar @{ $field->{subfields} } ) { + foreach my $subfield ( @{ $field->{subfields} } ) { my @values = $marcfield->subfield($subfield); $report_header->{ $tag . $subfield } = 1; - push @{ $report_record{fields}->{$tag . $subfield} }, @values; + push @{ $report_record{fields}->{ $tag . $subfield } }, @values; } - } elsif ($field->{tag} gt '009') { + } elsif ( $field->{tag} gt '009' ) { my @marcsubfields = $marcfield->subfields(); foreach my $marcsubfield (@marcsubfields) { - my ($code, $value) = @$marcsubfield; + my ( $code, $value ) = @$marcsubfield; $report_header->{ $tag . $code } = 1; push @{ $report_record{fields}->{ $tag . $code } }, $value; } } else { $report_header->{ $tag . '@' } = 1; - push @{ $report_record{fields}->{ $tag .'@' } }, $marcfield->data(); + push @{ $report_record{fields}->{ $tag . '@' } }, $marcfield->data(); } } } @@ -143,9 +146,9 @@ if ($op eq 'cud-merge') { ref_biblionumber => scalar $input->param('ref_biblionumber') ); -#------------------------- -# Show records to merge -#------------------------- + #------------------------- + # Show records to merge + #------------------------- } else { my $ref_biblionumber = $input->param('ref_biblionumber'); @@ -154,26 +157,26 @@ if ($op eq 'cud-merge') { $framework //= GetFrameworkCode($ref_biblionumber); # Getting MARC Structure - my $tagslib = GetMarcStructure(1, $framework); + my $tagslib = GetMarcStructure( 1, $framework ); - my $marcflavour = lc(C4::Context->preference('marcflavour')); + my $marcflavour = lc( C4::Context->preference('marcflavour') ); # Creating a loop for display my @records; foreach my $biblionumber (@biblionumbers) { - my $biblio = Koha::Biblios->find($biblionumber); - my $marcrecord = $biblio->metadata->record; + my $biblio = Koha::Biblios->find($biblionumber); + my $marcrecord = $biblio->metadata->record; my $frameworkcode = GetFrameworkCode($biblionumber); - my $recordObj = Koha::MetadataRecord->new({'record' => $marcrecord, schema => $marcflavour}); - my $record = { - recordid => $biblionumber, - record => $marcrecord, + my $recordObj = Koha::MetadataRecord->new( { 'record' => $marcrecord, schema => $marcflavour } ); + my $record = { + recordid => $biblionumber, + record => $marcrecord, frameworkcode => $frameworkcode, - display => $recordObj->createMergeHash($tagslib), + display => $recordObj->createMergeHash($tagslib), }; - if ($ref_biblionumber and $ref_biblionumber == $biblionumber) { + if ( $ref_biblionumber and $ref_biblionumber == $biblionumber ) { $record->{reference} = 1; - $template->param(ref_record => $record); + $template->param( ref_record => $record ); unshift @records, $record; } else { push @records, $record; @@ -184,38 +187,40 @@ if ($op eq 'cud-merge') { # Parameters $template->param( - ref_biblionumber => $ref_biblionumber, - records => \@records, - ref_record => $records[0], - framework => $framework, - biblionumbertag => $biblionumbertag, + ref_biblionumber => $ref_biblionumber, + records => \@records, + ref_record => $records[0], + framework => $framework, + biblionumbertag => $biblionumbertag, MergeReportFields => C4::Context->preference('MergeReportFields'), ); } else { my @records; foreach my $biblionumber (@biblionumbers) { my $frameworkcode = GetFrameworkCode($biblionumber); - my $record = { - biblionumber => $biblionumber, - data => GetBiblioData($biblionumber), + my $record = { + biblionumber => $biblionumber, + data => GetBiblioData($biblionumber), frameworkcode => $frameworkcode, }; push @records, $record; } + # Ask the user to choose which record will be the kept $template->param( choosereference => 1, - records => \@records, + records => \@records, ); - my $frameworks = Koha::BiblioFrameworks->search({}, { order_by => ['frameworktext'] }); + my $frameworks = Koha::BiblioFrameworks->search( {}, { order_by => ['frameworktext'] } ); $template->param( frameworks => $frameworks ); } } if (@errors) { + # Errors - $template->param( errors => \@errors ); + $template->param( errors => \@errors ); } output_html_with_http_headers $input, $cookie, $template->output; diff --git a/cataloguing/merge_ajax.pl b/cataloguing/merge_ajax.pl index ca4543690e..8d497bb82e 100755 --- a/cataloguing/merge_ajax.pl +++ b/cataloguing/merge_ajax.pl @@ -3,24 +3,24 @@ use Modern::Perl; use CGI qw ( -utf8 ); -use CGI::Cookie; # need to check cookies before CGI parses the POST request +use CGI::Cookie; # need to check cookies before CGI parses the POST request use JSON qw( encode_json ); use C4::Context; use C4::Biblio qw( GetMarcStructure ); -use C4::Auth qw( check_cookie_auth ); +use C4::Auth qw( check_cookie_auth ); my %cookies = CGI::Cookie->fetch; -my ( $auth_status ) = check_cookie_auth( +my ($auth_status) = check_cookie_auth( $cookies{'CGISESSID'}->value, { editcatalogue => 'edit_catalogue' }, ); my $reply = CGI->new; -if ($auth_status ne "ok") { - print $reply->header(-type => 'text/html'); +if ( $auth_status ne "ok" ) { + print $reply->header( -type => 'text/html' ); exit 0; -} +} my $framework = $reply->param('frameworkcode'); -my $tagslib = GetMarcStructure(1, $framework); -print $reply->header(-type => 'text/html'); +my $tagslib = GetMarcStructure( 1, $framework ); +print $reply->header( -type => 'text/html' ); print encode_json $tagslib; diff --git a/cataloguing/moveitem.pl b/cataloguing/moveitem.pl index 8fda82d4b8..66a4489415 100755 --- a/cataloguing/moveitem.pl +++ b/cataloguing/moveitem.pl @@ -21,34 +21,36 @@ use Modern::Perl; -use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); use C4::Circulation qw( barcodedecode ); -use C4::Output qw( output_html_with_http_headers ); +use C4::Output qw( output_html_with_http_headers ); use Koha::Biblios; use Koha::Items; my $query = CGI->new; -my ($template, $loggedinuser, $cookie) = get_template_and_user( +my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "cataloguing/moveitem.tt", - query => $query, - type => "intranet", - flagsrequired => { editcatalogue => 'edit_items' }, + template_name => "cataloguing/moveitem.tt", + query => $query, + type => "intranet", + flagsrequired => { editcatalogue => 'edit_items' }, } ); my $op = $query->param('op') || q{}; + # The biblio to move the item to my $biblionumber = $query->param('biblionumber'); -# The barcode of the item to move -my $barcode = barcodedecode($query->param('barcode')); -my $biblio = Koha::Biblios->find( $biblionumber ); -$template->param(biblio => $biblio); -$template->param(biblionumber => $biblionumber); +# The barcode of the item to move +my $barcode = barcodedecode( $query->param('barcode') ); + +my $biblio = Koha::Biblios->find($biblionumber); +$template->param( biblio => $biblio ); +$template->param( biblionumber => $biblionumber ); # If we already have the barcode of the item to move and the biblionumber to move the item to if ( $op eq 'cud-moveitem' && $barcode && $biblionumber ) { @@ -60,24 +62,22 @@ if ( $op eq 'cud-moveitem' && $barcode && $biblionumber ) { $itemnumber = $item->itemnumber; my $frombiblionumber = $item->biblionumber; - my $to_biblio = Koha::Biblios->find($biblionumber); + my $to_biblio = Koha::Biblios->find($biblionumber); my $moveresult = $item->move_to_biblio($to_biblio); if ($moveresult) { $template->param( - success => 1, + success => 1, from_biblio => Koha::Biblios->find($frombiblionumber), ); - } - else { + } else { $template->param( error => 1, errornonewitem => 1 ); } - } - else { + } else { $template->param( error => 1, errornoitem => 1 @@ -88,8 +88,7 @@ if ( $op eq 'cud-moveitem' && $barcode && $biblionumber ) { itemnumber => $itemnumber, ); -} -else { +} else { $template->param( missingparameter => 1 ); if ( !$barcode ) { $template->param( missingbarcode => 1 ); } if ( !$biblionumber ) { $template->param( missingbiblionumber => 1 ); } diff --git a/cataloguing/plugin_launcher.pl b/cataloguing/plugin_launcher.pl index b31ca52c89..b0891e6afb 100755 --- a/cataloguing/plugin_launcher.pl +++ b/cataloguing/plugin_launcher.pl @@ -18,7 +18,7 @@ # along with Koha; if not, see . use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Auth qw( check_cookie_auth ); use Koha::FrameworkPlugin; @@ -31,7 +31,9 @@ if ( $auth_status ne "ok" ) { exit 0; } -my $plugin= Koha::FrameworkPlugin->new( { - name => scalar $input->param("plugin_name"), -}); -$plugin->launch({ cgi => $input }); +my $plugin = Koha::FrameworkPlugin->new( + { + name => scalar $input->param("plugin_name"), + } +); +$plugin->launch( { cgi => $input } ); diff --git a/cataloguing/value_builder/EXAMPLE.pl b/cataloguing/value_builder/EXAMPLE.pl index 691e69f8e2..713bfa41df 100755 --- a/cataloguing/value_builder/EXAMPLE.pl +++ b/cataloguing/value_builder/EXAMPLE.pl @@ -19,7 +19,7 @@ use Modern::Perl; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); # Example of framework plugin new style. @@ -57,9 +57,9 @@ use C4::Output qw( output_html_with_http_headers ); # event.data.id. This makes a difference when the field is cloned or has # been created dynamically (as in additem.js). -my $builder= sub { +my $builder = sub { my $params = shift; - my $id = $params->{id}; + my $id = $params->{id}; return qq| |; }; + # NOTE: Did you see the last semicolon? This was just an assignment! # We continue now with the example launcher. @@ -112,17 +113,19 @@ function Click$id(event) { # When you look at the template EXAMPLE.tt, you can see that the javascript # code there puts a new value back into the input field (referenced by index). -my $launcher= sub { +my $launcher = sub { my $params = shift; - my $cgi = $params->{cgi}; - my ( $template, $loggedinuser, $cookie ) = get_template_and_user({ - template_name => "cataloguing/value_builder/EXAMPLE.tt", - query => $cgi, - type => "intranet", - flagsrequired => {editcatalogue => '*'}, - }); + my $cgi = $params->{cgi}; + my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "cataloguing/value_builder/EXAMPLE.tt", + query => $cgi, + type => "intranet", + flagsrequired => { editcatalogue => '*' }, + } + ); $template->param( - index => scalar $cgi->param('index'), + index => scalar $cgi->param('index'), result => scalar $cgi->param('result'), ); output_html_with_http_headers $cgi, $cookie, $template->output; diff --git a/cataloguing/value_builder/barcode.pl b/cataloguing/value_builder/barcode.pl index 2b408badce..85cb350164 100755 --- a/cataloguing/value_builder/barcode.pl +++ b/cataloguing/value_builder/barcode.pl @@ -24,12 +24,12 @@ use Modern::Perl; use C4::Context; use C4::Barcodes::ValueBuilder; -use C4::Biblio qw( GetMarcFromKohaField ); +use C4::Biblio qw( GetMarcFromKohaField ); use Koha::DateUtils qw( dt_from_string ); use Algorithm::CheckDigits qw( CheckDigits ); -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Auth qw( check_cookie_auth ); my $input = CGI->new; my ($auth_status) = @@ -40,50 +40,49 @@ if ( $auth_status ne "ok" ) { } my $builder = sub { - my ( $params ) = @_; + my ($params) = @_; my $function_name = $params->{id}; my %args; - # find today's date - ($args{year}, $args{mon}, $args{day}) = split('-', dt_from_string()->ymd()); - ($args{tag},$args{subfield}) = GetMarcFromKohaField( "items.barcode" ); + # find today's date + ( $args{year}, $args{mon}, $args{day} ) = split( '-', dt_from_string()->ymd() ); + ( $args{tag}, $args{subfield} ) = GetMarcFromKohaField("items.barcode"); - my $nextnum; + my $nextnum; my $scr; - my $autoBarcodeType = C4::Context->preference("autoBarcode"); - if ((not $autoBarcodeType) or $autoBarcodeType eq 'OFF') { + my $autoBarcodeType = C4::Context->preference("autoBarcode"); + if ( ( not $autoBarcodeType ) or $autoBarcodeType eq 'OFF' ) { + # don't return a value unless we have the appropriate syspref set return q||; } - if ($autoBarcodeType eq 'annual') { - ($nextnum, $scr) = C4::Barcodes::ValueBuilder::annual::get_barcode(\%args); - } - elsif ($autoBarcodeType eq 'incremental') { - ($nextnum, $scr) = C4::Barcodes::ValueBuilder::incremental::get_barcode(\%args); - } - elsif ($autoBarcodeType eq 'hbyymmincr') { # Generates a barcode where hb = home branch Code, yymm = year/month catalogued, incr = incremental number, reset yearly -fbcit - ($nextnum, $scr) = C4::Barcodes::ValueBuilder::hbyymmincr::get_barcode(\%args); - } - elsif ($autoBarcodeType eq 'EAN13') { + if ( $autoBarcodeType eq 'annual' ) { + ( $nextnum, $scr ) = C4::Barcodes::ValueBuilder::annual::get_barcode( \%args ); + } elsif ( $autoBarcodeType eq 'incremental' ) { + ( $nextnum, $scr ) = C4::Barcodes::ValueBuilder::incremental::get_barcode( \%args ); + } elsif ( $autoBarcodeType eq 'hbyymmincr' ) + { # Generates a barcode where hb = home branch Code, yymm = year/month catalogued, incr = incremental number, reset yearly -fbcit + ( $nextnum, $scr ) = C4::Barcodes::ValueBuilder::hbyymmincr::get_barcode( \%args ); + } elsif ( $autoBarcodeType eq 'EAN13' ) { + # not the best, two catalogers could add the same barcode easily this way :/ my $query = "select max(abs(barcode)) from items"; - my $dbh = $params->{dbh}; - my $sth = $dbh->prepare($query); + my $dbh = $params->{dbh}; + my $sth = $dbh->prepare($query); $sth->execute(); - while (my ($last)= $sth->fetchrow_array) { + while ( my ($last) = $sth->fetchrow_array ) { $nextnum = $last; } my $ean = CheckDigits('ean'); if ( $ean->is_valid($nextnum) ) { - my $next = $ean->basenumber( $nextnum ) + 1; - $nextnum = $ean->complete( $next ); - $nextnum = '0' x ( 13 - length($nextnum) ) . $nextnum; # pad zeros + my $next = $ean->basenumber($nextnum) + 1; + $nextnum = $ean->complete($next); + $nextnum = '0' x ( 13 - length($nextnum) ) . $nextnum; # pad zeros } else { warn "ERROR: invalid EAN-13 $nextnum, using increment"; $nextnum++; } - } - else { + } else { warn "ERROR: unknown autoBarcode: $autoBarcodeType"; } @@ -108,7 +107,7 @@ if (\$('#' + id).val() == '' || force) { }; END_OF_JS - my $js = < if(typeof autobarcodetype == 'undefined') { var autobarcodetype = "$autoBarcodeType"; diff --git a/cataloguing/value_builder/barcode_manual.pl b/cataloguing/value_builder/barcode_manual.pl index 67891789e3..f68597550b 100755 --- a/cataloguing/value_builder/barcode_manual.pl +++ b/cataloguing/value_builder/barcode_manual.pl @@ -24,10 +24,10 @@ use Modern::Perl; use C4::Context; use C4::Barcodes::ValueBuilder; -use C4::Biblio qw( GetMarcFromKohaField ); +use C4::Biblio qw( GetMarcFromKohaField ); use Koha::DateUtils qw( dt_from_string ); -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Auth qw( check_cookie_auth ); my $input = CGI->new; my ($auth_status) = @@ -38,42 +38,42 @@ if ( $auth_status ne "ok" ) { } my $builder = sub { - my ( $params ) = @_; + my ($params) = @_; my $function_name = $params->{id}; my %args; my $dbh = $params->{dbh}; $args{dbh} = $dbh; -# find today's date - ($args{year}, $args{mon}, $args{day}) = split('-', dt_from_string()->ymd()); - ($args{tag},$args{subfield}) = GetMarcFromKohaField( "items.barcode" ); + # find today's date + ( $args{year}, $args{mon}, $args{day} ) = split( '-', dt_from_string()->ymd() ); + ( $args{tag}, $args{subfield} ) = GetMarcFromKohaField("items.barcode"); my $nextnum; my $scr; my $autoBarcodeType = C4::Context->preference("autoBarcode"); - if ((not $autoBarcodeType) or $autoBarcodeType eq 'OFF') { -# don't return a value unless we have the appropriate syspref set + if ( ( not $autoBarcodeType ) or $autoBarcodeType eq 'OFF' ) { + + # don't return a value unless we have the appropriate syspref set return q||; } - if ($autoBarcodeType eq 'annual') { - ($nextnum, $scr) = C4::Barcodes::ValueBuilder::annual::get_barcode(\%args); - } - elsif ($autoBarcodeType eq 'incremental') { - ($nextnum, $scr) = C4::Barcodes::ValueBuilder::incremental::get_barcode(\%args); - } - elsif ($autoBarcodeType eq 'hbyymmincr') { # Generates a barcode where hb = home branch Code, yymm = year/month catalogued, incr = incremental number, reset yearly -fbcit - ($nextnum, $scr) = C4::Barcodes::ValueBuilder::hbyymmincr::get_barcode(\%args); + if ( $autoBarcodeType eq 'annual' ) { + ( $nextnum, $scr ) = C4::Barcodes::ValueBuilder::annual::get_barcode( \%args ); + } elsif ( $autoBarcodeType eq 'incremental' ) { + ( $nextnum, $scr ) = C4::Barcodes::ValueBuilder::incremental::get_barcode( \%args ); + } elsif ( $autoBarcodeType eq 'hbyymmincr' ) + { # Generates a barcode where hb = home branch Code, yymm = year/month catalogued, incr = incremental number, reset yearly -fbcit + ( $nextnum, $scr ) = C4::Barcodes::ValueBuilder::hbyymmincr::get_barcode( \%args ); } -# default js body (if not filled by hbyymmincr) + # default js body (if not filled by hbyymmincr) $scr or $scr = < function Click$function_name(event) { diff --git a/cataloguing/value_builder/callnumber-KU.pl b/cataloguing/value_builder/callnumber-KU.pl index d6327a5306..3ae80df1a3 100755 --- a/cataloguing/value_builder/callnumber-KU.pl +++ b/cataloguing/value_builder/callnumber-KU.pl @@ -43,8 +43,8 @@ CCC QW - returns first unused number CCC QWxx starting with CCC QW01 =cut my $builder = sub { - my ( $params ) = @_; - my $res=" + my ($params) = @_; + my $res = " "; - return ($field_number,$res); + return ( $field_number, $res ); } sub plugin { my ($input) = @_; my $isbn = $input->param('isbn'); - my ($template, $loggedinuser, $cookie) - = get_template_and_user({template_name => "cataloguing/value_builder/ajax.tt", - query => $input, - type => "intranet", - flagsrequired => {editcatalogue => '*'}, - }); - + my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "cataloguing/value_builder/ajax.tt", + query => $input, + type => "intranet", + flagsrequired => { editcatalogue => '*' }, + } + ); my $dbh = C4::Context->dbh; my $len = 0; - my $sth = $dbh->prepare('SELECT publishercode FROM biblioitems WHERE REPLACE(isbn, "-", "") LIKE ? OR isbn LIKE ? LIMIT 1'); - + my $sth = $dbh->prepare( + 'SELECT publishercode FROM biblioitems WHERE REPLACE(isbn, "-", "") LIKE ? OR isbn LIKE ? LIMIT 1'); + $isbn =~ s/-//g; - if (length ($isbn) == 13){ - $isbn = substr($isbn, 3, length($isbn)-3); + if ( length($isbn) == 13 ) { + $isbn = substr( $isbn, 3, length($isbn) - 3 ); } - - if(length($isbn) <= 10){ + + if ( length($isbn) <= 10 ) { $len = 5; - if ( substr( $isbn, 0, 1 ) <= 7 ){ + if ( substr( $isbn, 0, 1 ) <= 7 ) { $len = 1; - }elsif ( substr( $isbn, 0, 2 ) <= 94 ){ + } elsif ( substr( $isbn, 0, 2 ) <= 94 ) { $len = 2; - }elsif ( substr( $isbn, 0, 3 ) <= 995 ){ + } elsif ( substr( $isbn, 0, 3 ) <= 995 ) { $len = 3; - }elsif ( substr( $isbn, 0, 4 ) <= 9989 ){ - $len = 4 ; + } elsif ( substr( $isbn, 0, 4 ) <= 9989 ) { + $len = 4; } - my $x = substr( $isbn, $len ); + my $x = substr( $isbn, $len ); my $seg2 = ""; - - if ( substr( $x, 0, 2 ) <= 19 ) { + + if ( substr( $x, 0, 2 ) <= 19 ) { $seg2 = substr( $x, 0, 2 ); - } - elsif ( substr( $x, 0, 3 ) <= 699 ) { + } elsif ( substr( $x, 0, 3 ) <= 699 ) { $seg2 = substr( $x, 0, 3 ); - } - elsif ( substr( $x, 0, 4 ) <= 8399 ) { + } elsif ( substr( $x, 0, 4 ) <= 8399 ) { $seg2 = substr( $x, 0, 4 ); - } - elsif ( substr( $x, 0, 5 ) <= 89999 ) { + } elsif ( substr( $x, 0, 5 ) <= 89999 ) { $seg2 = substr( $x, 0, 5 ); - } - elsif ( substr( $x, 0, 6 ) <= 9499999 ) { + } elsif ( substr( $x, 0, 6 ) <= 9499999 ) { $seg2 = substr( $x, 0, 6 ); - } - else { + } else { $seg2 = substr( $x, 0, 7 ); } - while($len--){ - $seg2 = "_".$seg2; + while ( $len-- ) { + $seg2 = "_" . $seg2; } - - $len = 10 -length($seg2); - - while($len--){ + + $len = 10 - length($seg2); + + while ( $len-- ) { $seg2 .= "_"; } - $sth->execute($seg2, "978$seg2"); + $sth->execute( $seg2, "978$seg2" ); } - - if( (my $publishercode) = $sth->fetchrow ) - { - $template->param(return => $publishercode); + + if ( ( my $publishercode ) = $sth->fetchrow ) { + $template->param( return => $publishercode ); } output_html_with_http_headers $input, $cookie, $template->output; } diff --git a/cataloguing/value_builder/unimarc_field_100.pl b/cataloguing/value_builder/unimarc_field_100.pl index b3725ba6c6..009dfff532 100755 --- a/cataloguing/value_builder/unimarc_field_100.pl +++ b/cataloguing/value_builder/unimarc_field_100.pl @@ -1,6 +1,5 @@ #!/usr/bin/perl - # Copyright 2000-2002 Katipo Communications # # This file is part of Koha. @@ -23,15 +22,14 @@ use Modern::Perl; use Date::Calc; use Koha::Util::FrameworkPlugin qw(wrapper); -use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); use C4::Context; use C4::Output qw( output_html_with_http_headers ); - sub plugin_javascript { my ( $dbh, $record, $tagslib, $field_number ) = @_; - my $res = " + my $res = " "; - return ($field_number,$res); + return ( $field_number, $res ); } - sub plugin { my ($input) = @_; - my $index= $input->param('index'); - my $result= $input->param('result'); - + my $index = $input->param('index'); + my $result = $input->param('result'); my $dbh = C4::Context->dbh; - my ($template, $loggedinuser, $cookie) - = get_template_and_user({template_name => "cataloguing/value_builder/unimarc_field_105.tt", - query => $input, - type => "intranet", - flagsrequired => {editcatalogue => '*'}, - }); - my $f1 = substr($result,0,1); $f1 = wrapper( $f1 ) if $f1; - my $f2 = substr($result,1,1); $f2 = wrapper( $f2 ) if $f2; - my $f3 = substr($result,2,1); $f3 = wrapper( $f3 ) if $f3; - my $f4 = substr($result,3,1); $f4 = wrapper( $f4 ) if $f4; + my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "cataloguing/value_builder/unimarc_field_105.tt", + query => $input, + type => "intranet", + flagsrequired => { editcatalogue => '*' }, + } + ); + my $f1 = substr( $result, 0, 1 ); + $f1 = wrapper($f1) if $f1; + my $f2 = substr( $result, 1, 1 ); + $f2 = wrapper($f2) if $f2; + my $f3 = substr( $result, 2, 1 ); + $f3 = wrapper($f3) if $f3; + my $f4 = substr( $result, 3, 1 ); + $f4 = wrapper($f4) if $f4; - my $f5 = substr($result,4,1); $f5 = wrapper( $f5 ) if $f5; - my $f6 = substr($result,5,1); $f6 = wrapper( $f6 ) if $f6; - my $f7 = substr($result,6,1); $f7 = wrapper( $f7 ) if $f7; - my $f8 = substr($result,7,1); $f8 = wrapper( $f8 ) if $f8; + my $f5 = substr( $result, 4, 1 ); + $f5 = wrapper($f5) if $f5; + my $f6 = substr( $result, 5, 1 ); + $f6 = wrapper($f6) if $f6; + my $f7 = substr( $result, 6, 1 ); + $f7 = wrapper($f7) if $f7; + my $f8 = substr( $result, 7, 1 ); + $f8 = wrapper($f8) if $f8; - my $f9 = substr($result,8,1); $f9 = wrapper( $f9 ) if $f9; - my $f10 = substr($result,9,1); $f10 = wrapper( $f10 ) if $f10; - my $f11 = substr($result,10,1); $f11 = wrapper( $f11 ) if $f11; - my $f12 = substr($result,11,1); $f12 = wrapper( $f12 ) if $f12; - my $f13 = substr($result,12,1); $f13 = wrapper( $f13 ) if $f13; + my $f9 = substr( $result, 8, 1 ); + $f9 = wrapper($f9) if $f9; + my $f10 = substr( $result, 9, 1 ); + $f10 = wrapper($f10) if $f10; + my $f11 = substr( $result, 10, 1 ); + $f11 = wrapper($f11) if $f11; + my $f12 = substr( $result, 11, 1 ); + $f12 = wrapper($f12) if $f12; + my $f13 = substr( $result, 12, 1 ); + $f13 = wrapper($f13) if $f13; - $template->param(index => $index, - "f1$f1" => 1, - "f2$f2" => 1, - "f3$f3" => 1, - "f4$f4" => 1, - "f5$f5" => 1, - "f6$f6" => 1, - "f7$f7" => 1, - "f8$f8" => 1, - "f9$f9" => 1, - "f10$f10" => 1, - "f11$f11" => 1, - "f12$f12" => 1, - "f13$f13" => 1 - ); - output_html_with_http_headers $input, $cookie, $template->output; + $template->param( + index => $index, + "f1$f1" => 1, + "f2$f2" => 1, + "f3$f3" => 1, + "f4$f4" => 1, + "f5$f5" => 1, + "f6$f6" => 1, + "f7$f7" => 1, + "f8$f8" => 1, + "f9$f9" => 1, + "f10$f10" => 1, + "f11$f11" => 1, + "f12$f12" => 1, + "f13$f13" => 1 + ); + output_html_with_http_headers $input, $cookie, $template->output; } diff --git a/cataloguing/value_builder/unimarc_field_106.pl b/cataloguing/value_builder/unimarc_field_106.pl index c1c092a43d..7e0571855e 100755 --- a/cataloguing/value_builder/unimarc_field_106.pl +++ b/cataloguing/value_builder/unimarc_field_106.pl @@ -1,6 +1,5 @@ #!/usr/bin/perl - # Copyright 2000-2002 Katipo Communications # # This file is part of Koha. @@ -21,16 +20,16 @@ use Modern::Perl; use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Context; use C4::Search; use C4::Output qw( output_html_with_http_headers ); sub plugin_javascript { -my ($dbh,$record,$tagslib,$field_number) = @_; -my $function_name= "106".(int(rand(100000))+1); -my $res=" + my ( $dbh, $record, $tagslib, $field_number ) = @_; + my $function_name = "106" . ( int( rand(100000) ) + 1 ); + my $res = " "; -return ($field_number,$res); + return ( $field_number, $res ); } -sub plugin { -my ($input) = @_; - my $index= $input->param('index'); - my $result= $input->param('result') || q{}; - my $dbh = C4::Context->dbh; -my ($template, $loggedinuser, $cookie) - = get_template_and_user({template_name => "cataloguing/value_builder/unimarc_field_106.tt", - query => $input, - type => "intranet", - flagsrequired => {editcatalogue => '*'}, - }); - my $f1 = substr($result,0,1); - $template->param(index => $index, - "f1$f1" => $f1 - ); - output_html_with_http_headers $input, $cookie, $template->output; +sub plugin { + my ($input) = @_; + my $index = $input->param('index'); + my $result = $input->param('result') || q{}; + + my $dbh = C4::Context->dbh; + my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "cataloguing/value_builder/unimarc_field_106.tt", + query => $input, + type => "intranet", + flagsrequired => { editcatalogue => '*' }, + } + ); + my $f1 = substr( $result, 0, 1 ); + $template->param( + index => $index, + "f1$f1" => $f1 + ); + output_html_with_http_headers $input, $cookie, $template->output; } diff --git a/cataloguing/value_builder/unimarc_field_110.pl b/cataloguing/value_builder/unimarc_field_110.pl index 8b0743f785..9fbfe2bfac 100755 --- a/cataloguing/value_builder/unimarc_field_110.pl +++ b/cataloguing/value_builder/unimarc_field_110.pl @@ -1,6 +1,5 @@ #!/usr/bin/perl - # Copyright 2000-2002 Katipo Communications # # This file is part of Koha. @@ -19,19 +18,20 @@ # along with Koha; if not, see . use strict; + #use warnings; FIXME - Bug 2505 use Koha::Util::FrameworkPlugin qw(wrapper); -use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); use C4::Context; use C4::Search; use C4::Output qw( output_html_with_http_headers ); sub plugin_javascript { - my ($dbh,$record,$tagslib,$field_number) = @_; - my $res=" + my ( $dbh, $record, $tagslib, $field_number ) = @_; + my $res = " "; - return ($field_number,$res); + return ( $field_number, $res ); } - sub plugin { -my ($input) = @_; - my $index= $input->param('index'); - my $result= $input->param('result'); + my ($input) = @_; + my $index = $input->param('index'); + my $result = $input->param('result'); - my $dbh = C4::Context->dbh; -my ($template, $loggedinuser, $cookie) - = get_template_and_user({template_name => "cataloguing/value_builder/unimarc_field_110.tt", - query => $input, - type => "intranet", - flagsrequired => {editcatalogue => '*'}, - }); - my $f1 = substr($result,0,1); $f1 = wrapper( $f1 ) if $f1; - my $f2 = substr($result,1,1); $f2 = wrapper( $f2 ) if $f2; - my $f3 = substr($result,2,1); $f3 = wrapper( $f3 ) if $f3; - my $f4 = substr($result,3,1); $f4 = wrapper( $f4 ) if $f4; - my $f5 = substr($result,4,3); - my $f6 = substr($result,7,1); $f6 = wrapper( $f6 ) if $f6; - my $f7 = substr($result,8,1); $f7 = wrapper( $f7 ) if $f7; - my $f8 = substr($result,9,1); $f8 = wrapper( $f8 ) if $f8; - my $f9 = substr($result,10,1); $f9 = wrapper( $f9 ) if $f9; + my $dbh = C4::Context->dbh; + my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "cataloguing/value_builder/unimarc_field_110.tt", + query => $input, + type => "intranet", + flagsrequired => { editcatalogue => '*' }, + } + ); + my $f1 = substr( $result, 0, 1 ); + $f1 = wrapper($f1) if $f1; + my $f2 = substr( $result, 1, 1 ); + $f2 = wrapper($f2) if $f2; + my $f3 = substr( $result, 2, 1 ); + $f3 = wrapper($f3) if $f3; + my $f4 = substr( $result, 3, 1 ); + $f4 = wrapper($f4) if $f4; + my $f5 = substr( $result, 4, 3 ); + my $f6 = substr( $result, 7, 1 ); + $f6 = wrapper($f6) if $f6; + my $f7 = substr( $result, 8, 1 ); + $f7 = wrapper($f7) if $f7; + my $f8 = substr( $result, 9, 1 ); + $f8 = wrapper($f8) if $f8; + my $f9 = substr( $result, 10, 1 ); + $f9 = wrapper($f9) if $f9; - $template->param(index => $index, - "f1$f1" => 1, - "f2$f2" => 1, - "f3$f3" => 1, - "f4$f4" => 1, - f5 => $f5, - "f6$f6" => 1, - "f7$f7" => 1, - "f8$f8" => 1, - "f9$f9" => 1 - ); - output_html_with_http_headers $input, $cookie, $template->output; + $template->param( + index => $index, + "f1$f1" => 1, + "f2$f2" => 1, + "f3$f3" => 1, + "f4$f4" => 1, + f5 => $f5, + "f6$f6" => 1, + "f7$f7" => 1, + "f8$f8" => 1, + "f9$f9" => 1 + ); + output_html_with_http_headers $input, $cookie, $template->output; } diff --git a/cataloguing/value_builder/unimarc_field_115a.pl b/cataloguing/value_builder/unimarc_field_115a.pl index 75b74f68e0..a379cf5851 100755 --- a/cataloguing/value_builder/unimarc_field_115a.pl +++ b/cataloguing/value_builder/unimarc_field_115a.pl @@ -1,6 +1,5 @@ #!/usr/bin/perl - # Copyright 2000-2002 Katipo Communications # # This file is part of Koha. @@ -21,8 +20,8 @@ use Modern::Perl; use Koha::Util::FrameworkPlugin qw(wrapper); -use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); use C4::Context; use C4::Search; @@ -51,7 +50,6 @@ sub plugin_javascript { return ( $field_number, $res ); } - sub plugin { my ($input) = @_; my $index = $input->param('index'); @@ -60,31 +58,47 @@ sub plugin { my $dbh = C4::Context->dbh; my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => - "cataloguing/value_builder/unimarc_field_115a.tt", - query => $input, - type => "intranet", - flagsrequired => { editcatalogue => '*' }, + template_name => "cataloguing/value_builder/unimarc_field_115a.tt", + query => $input, + type => "intranet", + flagsrequired => { editcatalogue => '*' }, } ); - my $f1 = substr( $result, 0, 1 ); $f1 = wrapper( $f1 ) if $f1; - my $f2 = substr( $result, 1, 3 ); - my $f3 = substr( $result, 4, 1 ); $f3 = wrapper( $f3 ) if $f3; - my $f4 = substr( $result, 5, 1 ); $f4 = wrapper( $f4 ) if $f4; - my $f5 = substr( $result, 6, 1 ); $f5 = wrapper( $f5 ) if $f5; - my $f6 = substr( $result, 7, 1 ); $f6 = wrapper( $f6 ) if $f6; - my $f7 = substr( $result, 8, 1 ); $f7 = wrapper( $f7 ) if $f7; - my $f8 = substr( $result, 9, 1 ); $f8 = wrapper( $f8 ) if $f8; - my $f9 = substr( $result, 10, 1 ); $f9 = wrapper( $f9 ) if $f9; - my $f10 = substr( $result, 11, 1 ); $f10 = wrapper( $f10 ) if $f10; - my $f11 = substr( $result, 12, 1 ); $f11 = wrapper( $f11 ) if $f11; - my $f12 = substr( $result, 13, 1 ); $f12 = wrapper( $f12 ) if $f12; - my $f13 = substr( $result, 14, 1 ); $f13 = wrapper( $f13 ) if $f13; - my $f14 = substr( $result, 15, 1 ); $f14 = wrapper( $f14 ) if $f14; - my $f15 = substr( $result, 16, 1 ); $f15 = wrapper( $f15 ) if $f15; - my $f16 = substr( $result, 17, 1 ); $f16 = wrapper( $f16 ) if $f16; - my $f17 = substr( $result, 18, 1 ); $f17 = wrapper( $f17 ) if $f17; - my $f18 = substr( $result, 19, 1 ); $f18 = wrapper( $f18 ) if $f18; + my $f1 = substr( $result, 0, 1 ); + $f1 = wrapper($f1) if $f1; + my $f2 = substr( $result, 1, 3 ); + my $f3 = substr( $result, 4, 1 ); + $f3 = wrapper($f3) if $f3; + my $f4 = substr( $result, 5, 1 ); + $f4 = wrapper($f4) if $f4; + my $f5 = substr( $result, 6, 1 ); + $f5 = wrapper($f5) if $f5; + my $f6 = substr( $result, 7, 1 ); + $f6 = wrapper($f6) if $f6; + my $f7 = substr( $result, 8, 1 ); + $f7 = wrapper($f7) if $f7; + my $f8 = substr( $result, 9, 1 ); + $f8 = wrapper($f8) if $f8; + my $f9 = substr( $result, 10, 1 ); + $f9 = wrapper($f9) if $f9; + my $f10 = substr( $result, 11, 1 ); + $f10 = wrapper($f10) if $f10; + my $f11 = substr( $result, 12, 1 ); + $f11 = wrapper($f11) if $f11; + my $f12 = substr( $result, 13, 1 ); + $f12 = wrapper($f12) if $f12; + my $f13 = substr( $result, 14, 1 ); + $f13 = wrapper($f13) if $f13; + my $f14 = substr( $result, 15, 1 ); + $f14 = wrapper($f14) if $f14; + my $f15 = substr( $result, 16, 1 ); + $f15 = wrapper($f15) if $f15; + my $f16 = substr( $result, 17, 1 ); + $f16 = wrapper($f16) if $f16; + my $f17 = substr( $result, 18, 1 ); + $f17 = wrapper($f17) if $f17; + my $f18 = substr( $result, 19, 1 ); + $f18 = wrapper($f18) if $f18; $template->param( index => $index, diff --git a/cataloguing/value_builder/unimarc_field_115b.pl b/cataloguing/value_builder/unimarc_field_115b.pl index af01dd763d..8e98694122 100755 --- a/cataloguing/value_builder/unimarc_field_115b.pl +++ b/cataloguing/value_builder/unimarc_field_115b.pl @@ -1,6 +1,5 @@ #!/usr/bin/perl - # Copyright 2000-2002 Katipo Communications # # This file is part of Koha. @@ -21,8 +20,8 @@ use Modern::Perl; use Koha::Util::FrameworkPlugin qw(wrapper); -use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); use C4::Context; use C4::Search; @@ -44,7 +43,6 @@ function Clic$field_number(ev) { return ( $field_number, $res ); } - sub plugin { my ($input) = @_; my $index = $input->param('index'); @@ -53,22 +51,30 @@ sub plugin { my $dbh = C4::Context->dbh; my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => - "cataloguing/value_builder/unimarc_field_115b.tt", - query => $input, - type => "intranet", - flagsrequired => { editcatalogue => '*' }, + template_name => "cataloguing/value_builder/unimarc_field_115b.tt", + query => $input, + type => "intranet", + flagsrequired => { editcatalogue => '*' }, } ); - my $f1 = substr( $result, 0, 1 ); $f1 = wrapper( $f1 ) if $f1; - my $f2 = substr( $result, 1, 1 ); $f2 = wrapper( $f2 ) if $f2; - my $f3 = substr( $result, 2, 1 ); $f3 = wrapper( $f3 ) if $f3; - my $f4 = substr( $result, 3, 1 ); $f4 = wrapper( $f4 ) if $f4; - my $f5 = substr( $result, 4, 1 ); $f5 = wrapper( $f5 ) if $f5; - my $f6 = substr( $result, 5, 1 ); $f6 = wrapper( $f6 ) if $f6; - my $f7 = substr( $result, 6, 1 ); $f7 = wrapper( $f7 ) if $f7; - my $f8 = substr( $result, 7, 1 ); $f8 = wrapper( $f8 ) if $f8; - my $f9 = substr( $result, 8, 1 ); $f9 = wrapper( $f9 ) if $f9; + my $f1 = substr( $result, 0, 1 ); + $f1 = wrapper($f1) if $f1; + my $f2 = substr( $result, 1, 1 ); + $f2 = wrapper($f2) if $f2; + my $f3 = substr( $result, 2, 1 ); + $f3 = wrapper($f3) if $f3; + my $f4 = substr( $result, 3, 1 ); + $f4 = wrapper($f4) if $f4; + my $f5 = substr( $result, 4, 1 ); + $f5 = wrapper($f5) if $f5; + my $f6 = substr( $result, 5, 1 ); + $f6 = wrapper($f6) if $f6; + my $f7 = substr( $result, 6, 1 ); + $f7 = wrapper($f7) if $f7; + my $f8 = substr( $result, 7, 1 ); + $f8 = wrapper($f8) if $f8; + my $f9 = substr( $result, 8, 1 ); + $f9 = wrapper($f9) if $f9; my $f10 = substr( $result, 9, 4 ); my $f11 = substr( $result, 13, 2 ); diff --git a/cataloguing/value_builder/unimarc_field_116.pl b/cataloguing/value_builder/unimarc_field_116.pl index a5ca0f6117..89efccddd6 100755 --- a/cataloguing/value_builder/unimarc_field_116.pl +++ b/cataloguing/value_builder/unimarc_field_116.pl @@ -1,6 +1,5 @@ #!/usr/bin/perl - # Copyright 2000-2002 Katipo Communications # # This file is part of Koha. @@ -21,8 +20,8 @@ use Modern::Perl; use Koha::Util::FrameworkPlugin qw(wrapper); -use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); use C4::Context; use C4::Search; @@ -44,7 +43,6 @@ function Clic$field_number(event) { return ( $field_number, $res ); } - sub plugin { my ($input) = @_; my $index = $input->param('index'); @@ -56,23 +54,34 @@ sub plugin { template_name => "cataloguing/value_builder/unimarc_field_116.tt", query => $input, type => "intranet", - flagsrequired => { editcatalogue => '*' }, + flagsrequired => { editcatalogue => '*' }, } ); - my $f1 = substr( $result, 0, 1 ); $f1 = wrapper( $f1 ) if $f1; - my $f2 = substr( $result, 1, 1 ); $f2 = wrapper( $f2 ) if $f2; - my $f3 = substr( $result, 2, 1 ); $f3 = wrapper( $f3 ) if $f3; - my $f4 = substr( $result, 3, 1 ); $f4 = wrapper( $f4 ) if $f4; + my $f1 = substr( $result, 0, 1 ); + $f1 = wrapper($f1) if $f1; + my $f2 = substr( $result, 1, 1 ); + $f2 = wrapper($f2) if $f2; + my $f3 = substr( $result, 2, 1 ); + $f3 = wrapper($f3) if $f3; + my $f4 = substr( $result, 3, 1 ); + $f4 = wrapper($f4) if $f4; - my $f5 = substr( $result, 4, 2 ); $f5 = wrapper( $f5 ) if $f5; - my $f6 = substr( $result, 6, 2 ); $f6 = wrapper( $f6 ) if $f6; - my $f7 = substr( $result, 8, 2 ); $f7 = wrapper( $f7 ) if $f7; + my $f5 = substr( $result, 4, 2 ); + $f5 = wrapper($f5) if $f5; + my $f6 = substr( $result, 6, 2 ); + $f6 = wrapper($f6) if $f6; + my $f7 = substr( $result, 8, 2 ); + $f7 = wrapper($f7) if $f7; - my $f8 = substr( $result, 10, 2 ); $f8 = wrapper( $f8 ) if $f8; - my $f9 = substr( $result, 12, 2 ); $f9 = wrapper( $f9 ) if $f9; - my $f10 = substr( $result, 14, 2 ); $f10 = wrapper( $f10 ) if $f10; + my $f8 = substr( $result, 10, 2 ); + $f8 = wrapper($f8) if $f8; + my $f9 = substr( $result, 12, 2 ); + $f9 = wrapper($f9) if $f9; + my $f10 = substr( $result, 14, 2 ); + $f10 = wrapper($f10) if $f10; - my $f11 = substr( $result, 16, 2 ); $f11 = wrapper( $f11 ) if $f11; + my $f11 = substr( $result, 16, 2 ); + $f11 = wrapper($f11) if $f11; $template->param( index => $index, diff --git a/cataloguing/value_builder/unimarc_field_117.pl b/cataloguing/value_builder/unimarc_field_117.pl index 250f9a0602..d70fa0f673 100755 --- a/cataloguing/value_builder/unimarc_field_117.pl +++ b/cataloguing/value_builder/unimarc_field_117.pl @@ -1,6 +1,5 @@ #!/usr/bin/perl - # Copyright 2000-2002 Katipo Communications # # This file is part of Koha. @@ -21,16 +20,16 @@ use Modern::Perl; use Koha::Util::FrameworkPlugin qw(wrapper); -use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); use C4::Context; use C4::Search; use C4::Output qw( output_html_with_http_headers ); sub plugin_javascript { -my ($dbh,$record,$tagslib,$field_number) = @_; -my $res=" + my ( $dbh, $record, $tagslib, $field_number ) = @_; + my $res = " "; -return ($field_number,$res); + return ( $field_number, $res ); } - sub plugin { -my ($input) = @_; - my $index= $input->param('index'); - my $result= $input->param('result'); + my ($input) = @_; + my $index = $input->param('index'); + my $result = $input->param('result'); - my $dbh = C4::Context->dbh; -my ($template, $loggedinuser, $cookie) - = get_template_and_user({template_name => "cataloguing/value_builder/unimarc_field_117.tt", - query => $input, - type => "intranet", - flagsrequired => {editcatalogue => '*'}, - }); - my $f1 = substr($result,0,2); $f1 = wrapper( $f1 ) if $f1; - my $f2 = substr($result,2,2); $f2 = wrapper( $f2 ) if $f2; - my $f3 = substr($result,4,2); $f3 = wrapper( $f3 ) if $f3; - my $f4 = substr($result,6,2); $f4 = wrapper( $f4 ) if $f4; + my $dbh = C4::Context->dbh; + my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "cataloguing/value_builder/unimarc_field_117.tt", + query => $input, + type => "intranet", + flagsrequired => { editcatalogue => '*' }, + } + ); + my $f1 = substr( $result, 0, 2 ); + $f1 = wrapper($f1) if $f1; + my $f2 = substr( $result, 2, 2 ); + $f2 = wrapper($f2) if $f2; + my $f3 = substr( $result, 4, 2 ); + $f3 = wrapper($f3) if $f3; + my $f4 = substr( $result, 6, 2 ); + $f4 = wrapper($f4) if $f4; - my $f5 = substr($result,8,1); $f5 = wrapper( $f5 ) if $f5; + my $f5 = substr( $result, 8, 1 ); + $f5 = wrapper($f5) if $f5; - $template->param(index => $index, - "f1$f1" => 1, - "f2$f2" => 1, - "f3$f3" => 1, - "f4$f4" => 1, - "f5$f5" => 1 - ); - output_html_with_http_headers $input, $cookie, $template->output; + $template->param( + index => $index, + "f1$f1" => 1, + "f2$f2" => 1, + "f3$f3" => 1, + "f4$f4" => 1, + "f5$f5" => 1 + ); + output_html_with_http_headers $input, $cookie, $template->output; } diff --git a/cataloguing/value_builder/unimarc_field_120.pl b/cataloguing/value_builder/unimarc_field_120.pl index 7e13a724c5..7e5df16826 100755 --- a/cataloguing/value_builder/unimarc_field_120.pl +++ b/cataloguing/value_builder/unimarc_field_120.pl @@ -1,6 +1,5 @@ #!/usr/bin/perl - # Copyright 2000-2002 Katipo Communications # # This file is part of Koha. @@ -19,20 +18,21 @@ # along with Koha; if not, see . use strict; + #use warnings; FIXME - Bug 2505 use Koha::Util::FrameworkPlugin qw(wrapper); -use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); use C4::Context; use C4::Search; use C4::Output qw( output_html_with_http_headers ); sub plugin_javascript { -my ($dbh,$record,$tagslib,$field_number) = @_; -my $function_name=$field_number; -my $res=" + my ( $dbh, $record, $tagslib, $field_number ) = @_; + my $function_name = $field_number; + my $res = " "; -return ($function_name,$res); + return ( $function_name, $res ); } - sub plugin { -my ($input) = @_; - my $index= $input->param('index'); - my $result= $input->param('result'); + my ($input) = @_; + my $index = $input->param('index'); + my $result = $input->param('result'); + my $dbh = C4::Context->dbh; - my $dbh = C4::Context->dbh; - -my ($template, $loggedinuser, $cookie) - = get_template_and_user({template_name => "cataloguing/value_builder/unimarc_field_120.tt", - query => $input, - type => "intranet", - flagsrequired => {editcatalogue => '*'}, - }); - my $f1 = substr($result,0,1); - my $f2 = substr($result,1,1); - my $f3 = substr($result,2,1); - my $f4 = substr($result,3,1); $f4 = wrapper( $f4 ) if $f4; - my $f5 = substr($result,4,1); $f5 = wrapper( $f5 ) if $f5; - my $f6 = substr($result,5,1); $f6 = wrapper( $f6 ) if $f6; - my $f7 = substr($result,6,1); $f7 = wrapper( $f7 ) if $f7; - my $f8 = substr($result,7,2); - my $f9 = substr($result,9,2); $f9 = wrapper( $f9 ) if $f9; - my $f10 = substr($result,11,2); $f10 = wrapper( $f10 ) if $f10; - $template->param(index => $index, - "f1$f1" => 1, - "f2$f2" => 1, - "f3$f3" => 1, - "f4$f4" => 1, - "f5$f5" => 1, - "f6$f6" => 1, - "f7$f7" => 1, - "f8$f8" => 1, - "f9$f9" => 1, - "f10$f10" => 1); - output_html_with_http_headers $input, $cookie, $template->output; + my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "cataloguing/value_builder/unimarc_field_120.tt", + query => $input, + type => "intranet", + flagsrequired => { editcatalogue => '*' }, + } + ); + my $f1 = substr( $result, 0, 1 ); + my $f2 = substr( $result, 1, 1 ); + my $f3 = substr( $result, 2, 1 ); + my $f4 = substr( $result, 3, 1 ); + $f4 = wrapper($f4) if $f4; + my $f5 = substr( $result, 4, 1 ); + $f5 = wrapper($f5) if $f5; + my $f6 = substr( $result, 5, 1 ); + $f6 = wrapper($f6) if $f6; + my $f7 = substr( $result, 6, 1 ); + $f7 = wrapper($f7) if $f7; + my $f8 = substr( $result, 7, 2 ); + my $f9 = substr( $result, 9, 2 ); + $f9 = wrapper($f9) if $f9; + my $f10 = substr( $result, 11, 2 ); + $f10 = wrapper($f10) if $f10; + $template->param( + index => $index, + "f1$f1" => 1, + "f2$f2" => 1, + "f3$f3" => 1, + "f4$f4" => 1, + "f5$f5" => 1, + "f6$f6" => 1, + "f7$f7" => 1, + "f8$f8" => 1, + "f9$f9" => 1, + "f10$f10" => 1 + ); + output_html_with_http_headers $input, $cookie, $template->output; } diff --git a/cataloguing/value_builder/unimarc_field_121a.pl b/cataloguing/value_builder/unimarc_field_121a.pl index b5d2d040f9..e5d53e28fb 100755 --- a/cataloguing/value_builder/unimarc_field_121a.pl +++ b/cataloguing/value_builder/unimarc_field_121a.pl @@ -1,6 +1,5 @@ #!/usr/bin/perl - # Copyright 2000-2002 Katipo Communications # # This file is part of Koha. @@ -21,17 +20,17 @@ use Modern::Perl; use Koha::Util::FrameworkPlugin qw(wrapper); -use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); use C4::Context; use C4::Search; use C4::Output qw( output_html_with_http_headers ); sub plugin_javascript { -my ($dbh,$record,$tagslib,$field_number) = @_; -my $function_name= $field_number; -my $res=" + my ( $dbh, $record, $tagslib, $field_number ) = @_; + my $function_name = $field_number; + my $res = " "; -return ($function_name,$res); + return ( $function_name, $res ); } - sub plugin { -my ($input) = @_; - my $index= $input->param('index'); - my $result= $input->param('result'); + my ($input) = @_; + my $index = $input->param('index'); + my $result = $input->param('result'); + my $dbh = C4::Context->dbh; - my $dbh = C4::Context->dbh; - -my ($template, $loggedinuser, $cookie) - = get_template_and_user({template_name => "cataloguing/value_builder/unimarc_field_121a.tt", - query => $input, - type => "intranet", - flagsrequired => {editcatalogue => '*'}, - }); - my $f1 = substr($result,0,1); - my $f2 = substr($result,1,1); $f2 = wrapper( $f2 ) if $f2; - my $f3 = substr($result,2,1); $f3 = wrapper( $f3 ) if $f3; - my $f4 = substr($result,3,2); - my $f5 = substr($result,5,1); - my $f6 = substr($result,6,1); - my $f7 = substr($result,7,1); - my $f8 = substr($result,8,1); - $template->param(index => $index, - "f1$f1" => 1, - "f2$f2" => 1, - "f3$f3" => 1, - "f4$f4" => 1, - "f5$f5" => 1, - "f6$f6" => 1, - "f7$f7" => 1, - "f8$f8" => $f8); - output_html_with_http_headers $input, $cookie, $template->output; + my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "cataloguing/value_builder/unimarc_field_121a.tt", + query => $input, + type => "intranet", + flagsrequired => { editcatalogue => '*' }, + } + ); + my $f1 = substr( $result, 0, 1 ); + my $f2 = substr( $result, 1, 1 ); + $f2 = wrapper($f2) if $f2; + my $f3 = substr( $result, 2, 1 ); + $f3 = wrapper($f3) if $f3; + my $f4 = substr( $result, 3, 2 ); + my $f5 = substr( $result, 5, 1 ); + my $f6 = substr( $result, 6, 1 ); + my $f7 = substr( $result, 7, 1 ); + my $f8 = substr( $result, 8, 1 ); + $template->param( + index => $index, + "f1$f1" => 1, + "f2$f2" => 1, + "f3$f3" => 1, + "f4$f4" => 1, + "f5$f5" => 1, + "f6$f6" => 1, + "f7$f7" => 1, + "f8$f8" => $f8 + ); + output_html_with_http_headers $input, $cookie, $template->output; } diff --git a/cataloguing/value_builder/unimarc_field_121b.pl b/cataloguing/value_builder/unimarc_field_121b.pl index 265b8f40d9..945888ab24 100755 --- a/cataloguing/value_builder/unimarc_field_121b.pl +++ b/cataloguing/value_builder/unimarc_field_121b.pl @@ -1,6 +1,5 @@ #!/usr/bin/perl - # Copyright 2000-2002 Katipo Communications # # This file is part of Koha. @@ -20,16 +19,16 @@ use Modern::Perl; use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Context; use C4::Search; use C4::Output qw( output_html_with_http_headers ); sub plugin_javascript { -my ($dbh,$record,$tagslib,$field_number) = @_; -my $function_name= $field_number; -my $res=" + my ( $dbh, $record, $tagslib, $field_number ) = @_; + my $function_name = $field_number; + my $res = " "; -return ($function_name,$res); + return ( $function_name, $res ); } + sub plugin { -my ($input) = @_; - my $index= $input->param('index'); - my $result= $input->param('result'); + my ($input) = @_; + my $index = $input->param('index'); + my $result = $input->param('result'); + my $dbh = C4::Context->dbh; - my $dbh = C4::Context->dbh; - -my ($template, $loggedinuser, $cookie) - = get_template_and_user({template_name => "cataloguing/value_builder/unimarc_field_121b.tt", - query => $input, - type => "intranet", - flagsrequired => {editcatalogue => '*'}, - }); - my $f1 = substr($result,0,1); - my $f2 = substr($result,1,1); - my $f3 = substr($result,2,2); - my $f4 = substr($result,4,1); - my $f5 = substr($result,5,1); - my $f6 = substr($result,6,1); - my $f7 = substr($result,7,1); - $template->param(index => $index, - "f1$f1" => 1, - "f2$f2" => 1, - f3 => $f3, - "f4$f4" => 1, - "f5$f5" => 1, - "f6$f6" => 1, - "f7$f7" => 1); - output_html_with_http_headers $input, $cookie, $template->output; + my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "cataloguing/value_builder/unimarc_field_121b.tt", + query => $input, + type => "intranet", + flagsrequired => { editcatalogue => '*' }, + } + ); + my $f1 = substr( $result, 0, 1 ); + my $f2 = substr( $result, 1, 1 ); + my $f3 = substr( $result, 2, 2 ); + my $f4 = substr( $result, 4, 1 ); + my $f5 = substr( $result, 5, 1 ); + my $f6 = substr( $result, 6, 1 ); + my $f7 = substr( $result, 7, 1 ); + $template->param( + index => $index, + "f1$f1" => 1, + "f2$f2" => 1, + f3 => $f3, + "f4$f4" => 1, + "f5$f5" => 1, + "f6$f6" => 1, + "f7$f7" => 1 + ); + output_html_with_http_headers $input, $cookie, $template->output; } diff --git a/cataloguing/value_builder/unimarc_field_122.pl b/cataloguing/value_builder/unimarc_field_122.pl index 7aecbf2cb5..14c14c58ed 100755 --- a/cataloguing/value_builder/unimarc_field_122.pl +++ b/cataloguing/value_builder/unimarc_field_122.pl @@ -1,6 +1,5 @@ #!/usr/bin/perl - # Copyright 2000-2002 Katipo Communications # # This file is part of Koha. @@ -20,16 +19,16 @@ use Modern::Perl; use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Context; use C4::Search; use C4::Output qw( output_html_with_http_headers ); sub plugin_javascript { -my ($dbh,$record,$tagslib,$field_number) = @_; -my $function_name= $field_number; -my $res=" + my ( $dbh, $record, $tagslib, $field_number ) = @_; + my $function_name = $field_number; + my $res = " "; -return ($function_name,$res); + return ( $function_name, $res ); } + sub plugin { -my ($input) = @_; - my $index= $input->param('index'); - my $result= $input->param('result'); + my ($input) = @_; + my $index = $input->param('index'); + my $result = $input->param('result'); + my $dbh = C4::Context->dbh; - my $dbh = C4::Context->dbh; - -my ($template, $loggedinuser, $cookie) - = get_template_and_user({template_name => "cataloguing/value_builder/unimarc_field_122.tt", - query => $input, - type => "intranet", - flagsrequired => {editcatalogue => '*'}, - }); - my $f1 = substr($result,0,1); - my $f2 = substr($result,1,4); - my $f3 = substr($result,5,2); - my $f4 = substr($result,7,2); - my $f5 = substr($result,9,2); - $template->param(index => $index, - "f1$f1" => 1, - f2 => $f2, - f3 => $f3, - f4 => $f4, - f5 => $f5); - output_html_with_http_headers $input, $cookie, $template->output; + my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "cataloguing/value_builder/unimarc_field_122.tt", + query => $input, + type => "intranet", + flagsrequired => { editcatalogue => '*' }, + } + ); + my $f1 = substr( $result, 0, 1 ); + my $f2 = substr( $result, 1, 4 ); + my $f3 = substr( $result, 5, 2 ); + my $f4 = substr( $result, 7, 2 ); + my $f5 = substr( $result, 9, 2 ); + $template->param( + index => $index, + "f1$f1" => 1, + f2 => $f2, + f3 => $f3, + f4 => $f4, + f5 => $f5 + ); + output_html_with_http_headers $input, $cookie, $template->output; } diff --git a/cataloguing/value_builder/unimarc_field_123a.pl b/cataloguing/value_builder/unimarc_field_123a.pl index 25c5c30d8d..a81971a161 100755 --- a/cataloguing/value_builder/unimarc_field_123a.pl +++ b/cataloguing/value_builder/unimarc_field_123a.pl @@ -1,6 +1,5 @@ #!/usr/bin/perl - # Copyright 2000-2002 Katipo Communications # # This file is part of Koha. @@ -20,16 +19,16 @@ use Modern::Perl; use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Context; use C4::Search; use C4::Output qw( output_html_with_http_headers ); sub plugin_javascript { -my ($dbh,$record,$tagslib,$field_number) = @_; -my $function_name= $field_number; -my $res=" + my ( $dbh, $record, $tagslib, $field_number ) = @_; + my $function_name = $field_number; + my $res = " "; -return ($function_name,$res); + return ( $function_name, $res ); } + sub plugin { -my ($input) = @_; - my $index= $input->param('index'); - my $result= $input->param('result'); + my ($input) = @_; + my $index = $input->param('index'); + my $result = $input->param('result'); + my $dbh = C4::Context->dbh; - my $dbh = C4::Context->dbh; - -my ($template, $loggedinuser, $cookie) - = get_template_and_user({template_name => "cataloguing/value_builder/unimarc_field_123a.tt", - query => $input, - type => "intranet", - flagsrequired => {editcatalogue => '*'}, - }); - my $f1 = substr($result,0,1); - $template->param(index => $index, - "f1$f1" => $f1); - output_html_with_http_headers $input, $cookie, $template->output; + my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "cataloguing/value_builder/unimarc_field_123a.tt", + query => $input, + type => "intranet", + flagsrequired => { editcatalogue => '*' }, + } + ); + my $f1 = substr( $result, 0, 1 ); + $template->param( + index => $index, + "f1$f1" => $f1 + ); + output_html_with_http_headers $input, $cookie, $template->output; } diff --git a/cataloguing/value_builder/unimarc_field_123defg.pl b/cataloguing/value_builder/unimarc_field_123defg.pl index 2630fcc783..1cd3d5559c 100755 --- a/cataloguing/value_builder/unimarc_field_123defg.pl +++ b/cataloguing/value_builder/unimarc_field_123defg.pl @@ -1,6 +1,5 @@ #!/usr/bin/perl - # Copyright 2000-2002 Katipo Communications # # This file is part of Koha. @@ -21,16 +20,16 @@ use Modern::Perl; use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Context; use C4::Search; use C4::Output qw( output_html_with_http_headers ); sub plugin_javascript { -my ($dbh,$record,$tagslib,$field_number) = @_; -my $function_name= $field_number; -my $res=" + my ( $dbh, $record, $tagslib, $field_number ) = @_; + my $function_name = $field_number; + my $res = " "; -return ($function_name,$res); + return ( $function_name, $res ); } + sub plugin { -my ($input) = @_; - my $index= $input->param('index'); - my $result= $input->param('result'); + my ($input) = @_; + my $index = $input->param('index'); + my $result = $input->param('result'); + my $dbh = C4::Context->dbh; - my $dbh = C4::Context->dbh; - -my ($template, $loggedinuser, $cookie) - = get_template_and_user({template_name => "cataloguing/value_builder/unimarc_field_123defg.tt", - query => $input, - type => "intranet", - flagsrequired => {editcatalogue => '*'}, - }); - my $f1 = substr($result,0,1); - my $f2 = substr($result,1,3); - my $f3 = substr($result,4,2); - my $f4 = substr($result,6,2); - $template->param(index => $index, - "f1$f1" => 1, - f2 => $f2, - f3 => $f3, - f4 => $f4); - output_html_with_http_headers $input, $cookie, $template->output; + my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "cataloguing/value_builder/unimarc_field_123defg.tt", + query => $input, + type => "intranet", + flagsrequired => { editcatalogue => '*' }, + } + ); + my $f1 = substr( $result, 0, 1 ); + my $f2 = substr( $result, 1, 3 ); + my $f3 = substr( $result, 4, 2 ); + my $f4 = substr( $result, 6, 2 ); + $template->param( + index => $index, + "f1$f1" => 1, + f2 => $f2, + f3 => $f3, + f4 => $f4 + ); + output_html_with_http_headers $input, $cookie, $template->output; } diff --git a/cataloguing/value_builder/unimarc_field_123i.pl b/cataloguing/value_builder/unimarc_field_123i.pl index a41d8d78f4..99a10e59b5 100755 --- a/cataloguing/value_builder/unimarc_field_123i.pl +++ b/cataloguing/value_builder/unimarc_field_123i.pl @@ -1,6 +1,5 @@ #!/usr/bin/perl - # Copyright 2000-2002 Katipo Communications # # This file is part of Koha. @@ -21,16 +20,16 @@ use Modern::Perl; use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Context; use C4::Search; use C4::Output qw( output_html_with_http_headers ); sub plugin_javascript { -my ($dbh,$record,$tagslib,$field_number) = @_; -my $function_name= $field_number; -my $res=" + my ( $dbh, $record, $tagslib, $field_number ) = @_; + my $function_name = $field_number; + my $res = " "; -return ($function_name,$res); + return ( $function_name, $res ); } + sub plugin { -my ($input) = @_; - my $index= $input->param('index'); - my $result= $input->param('result'); + my ($input) = @_; + my $index = $input->param('index'); + my $result = $input->param('result'); + my $dbh = C4::Context->dbh; - my $dbh = C4::Context->dbh; - -my ($template, $loggedinuser, $cookie) - = get_template_and_user({template_name => "cataloguing/value_builder/unimarc_field_123i_j.tt", - query => $input, - type => "intranet", - flagsrequired => {editcatalogue => '*'}, - }); - my $f1 = substr($result,0,1); - my $f2 = substr($result,1,3); - my $f3 = substr($result,4,2); - my $f4 = substr($result,6,2); - $template->param(index => $index, - "f1".($f1 eq '-'?'s':'n') => 1, - f2 => $f2, - f3 => $f3, - f4 => $f4); - output_html_with_http_headers $input, $cookie, $template->output; + my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "cataloguing/value_builder/unimarc_field_123i_j.tt", + query => $input, + type => "intranet", + flagsrequired => { editcatalogue => '*' }, + } + ); + my $f1 = substr( $result, 0, 1 ); + my $f2 = substr( $result, 1, 3 ); + my $f3 = substr( $result, 4, 2 ); + my $f4 = substr( $result, 6, 2 ); + $template->param( + index => $index, + "f1" . ( $f1 eq '-' ? 's' : 'n' ) => 1, + f2 => $f2, + f3 => $f3, + f4 => $f4 + ); + output_html_with_http_headers $input, $cookie, $template->output; } diff --git a/cataloguing/value_builder/unimarc_field_123j.pl b/cataloguing/value_builder/unimarc_field_123j.pl index 074a05ca85..47fe72d683 100755 --- a/cataloguing/value_builder/unimarc_field_123j.pl +++ b/cataloguing/value_builder/unimarc_field_123j.pl @@ -1,6 +1,5 @@ #!/usr/bin/perl - # Copyright 2000-2002 Katipo Communications # # This file is part of Koha. @@ -21,16 +20,16 @@ use Modern::Perl; use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Context; use C4::Search; use C4::Output qw( output_html_with_http_headers ); sub plugin_javascript { -my ($dbh,$record,$tagslib,$field_number) = @_; -my $function_name= $field_number; -my $res=" + my ( $dbh, $record, $tagslib, $field_number ) = @_; + my $function_name = $field_number; + my $res = " "; - return ($function_name,$res); + return ( $function_name, $res ); } sub plugin { - my ($input) = @_; - my $index= $input->param('index'); - my $result= $input->param('result'); + my ($input) = @_; + my $index = $input->param('index'); + my $result = $input->param('result'); + my $dbh = C4::Context->dbh; - my $dbh = C4::Context->dbh; - - my ($template, $loggedinuser, $cookie) - = get_template_and_user( - { + my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { template_name => "cataloguing/value_builder/unimarc_field_123i_j.tt", - query => $input, - type => "intranet", - flagsrequired => {editcatalogue => '*'}, - } - ); - my $f1 = substr($result,0,1); - my $f2 = substr($result,1,3); - my $f3 = substr($result,4,2); - my $f4 = substr($result,6,2); - $template->param(index => $index, - "f1".($f1 eq '-'?'s':'n') => 1, - f2 => $f2, - f3 => $f3, - f4 => $f4); - output_html_with_http_headers $input, $cookie, $template->output; + query => $input, + type => "intranet", + flagsrequired => { editcatalogue => '*' }, + } + ); + my $f1 = substr( $result, 0, 1 ); + my $f2 = substr( $result, 1, 3 ); + my $f3 = substr( $result, 4, 2 ); + my $f4 = substr( $result, 6, 2 ); + $template->param( + index => $index, + "f1" . ( $f1 eq '-' ? 's' : 'n' ) => 1, + f2 => $f2, + f3 => $f3, + f4 => $f4 + ); + output_html_with_http_headers $input, $cookie, $template->output; } diff --git a/cataloguing/value_builder/unimarc_field_124.pl b/cataloguing/value_builder/unimarc_field_124.pl index 426f1436eb..fd9d7a4cb5 100755 --- a/cataloguing/value_builder/unimarc_field_124.pl +++ b/cataloguing/value_builder/unimarc_field_124.pl @@ -1,6 +1,5 @@ #!/usr/bin/perl - # Copyright 2000-2002 Katipo Communications # # This file is part of Koha. @@ -21,16 +20,16 @@ use Modern::Perl; use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Context; use C4::Search; use C4::Output qw( output_html_with_http_headers ); sub plugin_javascript { -my ($dbh,$record,$tagslib,$field_number) = @_; -my $function_name= $field_number; -my $res=" + my ( $dbh, $record, $tagslib, $field_number ) = @_; + my $function_name = $field_number; + my $res = " "; -return ($function_name,$res); + return ( $function_name, $res ); } + sub plugin { -my ($input) = @_; - my $index= $input->param('index'); - my $result= $input->param('result'); + my ($input) = @_; + my $index = $input->param('index'); + my $result = $input->param('result'); + my $dbh = C4::Context->dbh; - my $dbh = C4::Context->dbh; - -my ($template, $loggedinuser, $cookie) - = get_template_and_user({template_name => "cataloguing/value_builder/unimarc_field_100.tt", - query => $input, - type => "intranet", - flagsrequired => {editcatalogue => '*'}, - }); - my $f1 = substr($result,0,8); - my $f2 = substr($result,8,1); - my $f3 = substr($result,9,4); - my $f4 = substr($result,13,4); - $template->param(index => $index, - f1 => $f1, - f3 => $f3, - "f2$f2" => 1, - f4 => $f4); - output_html_with_http_headers $input, $cookie, $template->output; + my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "cataloguing/value_builder/unimarc_field_100.tt", + query => $input, + type => "intranet", + flagsrequired => { editcatalogue => '*' }, + } + ); + my $f1 = substr( $result, 0, 8 ); + my $f2 = substr( $result, 8, 1 ); + my $f3 = substr( $result, 9, 4 ); + my $f4 = substr( $result, 13, 4 ); + $template->param( + index => $index, + f1 => $f1, + f3 => $f3, + "f2$f2" => 1, + f4 => $f4 + ); + output_html_with_http_headers $input, $cookie, $template->output; } diff --git a/cataloguing/value_builder/unimarc_field_124a.pl b/cataloguing/value_builder/unimarc_field_124a.pl index f0173e02f8..169e7daaee 100755 --- a/cataloguing/value_builder/unimarc_field_124a.pl +++ b/cataloguing/value_builder/unimarc_field_124a.pl @@ -1,6 +1,5 @@ #!/usr/bin/perl - # Copyright 2000-2002 Katipo Communications # # This file is part of Koha. @@ -21,16 +20,16 @@ use Modern::Perl; use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Context; use C4::Search; use C4::Output qw( output_html_with_http_headers ); sub plugin_javascript { -my ($dbh,$record,$tagslib,$field_number) = @_; -my $function_name= $field_number; -my $res=" + my ( $dbh, $record, $tagslib, $field_number ) = @_; + my $function_name = $field_number; + my $res = " "; -return ($function_name,$res); + return ( $function_name, $res ); } + sub plugin { -my ($input) = @_; - my $index= $input->param('index'); - my $result= $input->param('result'); + my ($input) = @_; + my $index = $input->param('index'); + my $result = $input->param('result'); + my $dbh = C4::Context->dbh; - my $dbh = C4::Context->dbh; - - my ($template, $loggedinuser, $cookie) = get_template_and_user( + my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "cataloguing/value_builder/unimarc_field_124a.tt", - query => $input, - type => "intranet", - flagsrequired => { editcatalogue => '*' }, + template_name => "cataloguing/value_builder/unimarc_field_124a.tt", + query => $input, + type => "intranet", + flagsrequired => { editcatalogue => '*' }, } ); - my $f1 = substr($result,0,1); - $template->param(index => $index, - "f1$f1" => 1); - output_html_with_http_headers $input, $cookie, $template->output; + my $f1 = substr( $result, 0, 1 ); + $template->param( + index => $index, + "f1$f1" => 1 + ); + output_html_with_http_headers $input, $cookie, $template->output; } diff --git a/cataloguing/value_builder/unimarc_field_124b.pl b/cataloguing/value_builder/unimarc_field_124b.pl index cdd5771bd1..722ba52c8d 100755 --- a/cataloguing/value_builder/unimarc_field_124b.pl +++ b/cataloguing/value_builder/unimarc_field_124b.pl @@ -1,6 +1,5 @@ #!/usr/bin/perl - # Copyright 2000-2002 Katipo Communications # # This file is part of Koha. @@ -21,16 +20,16 @@ use Modern::Perl; use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Context; use C4::Search; use C4::Output qw( output_html_with_http_headers ); sub plugin_javascript { -my ($dbh,$record,$tagslib,$field_number) = @_; -my $function_name= $field_number; -my $res=" + my ( $dbh, $record, $tagslib, $field_number ) = @_; + my $function_name = $field_number; + my $res = " "; -return ($function_name,$res); + return ( $function_name, $res ); } + sub plugin { -my ($input) = @_; - my $index= $input->param('index'); - my $result= $input->param('result'); + my ($input) = @_; + my $index = $input->param('index'); + my $result = $input->param('result'); + my $dbh = C4::Context->dbh; - my $dbh = C4::Context->dbh; - -my ($template, $loggedinuser, $cookie) - = get_template_and_user({template_name => "cataloguing/value_builder/unimarc_field_124b.tt", - query => $input, - type => "intranet", - flagsrequired => {editcatalogue => '*'}, - }); - my $f1 = substr($result,0,1); - $template->param(index => $index, - "f1$f1" => 1); - output_html_with_http_headers $input, $cookie, $template->output; + my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "cataloguing/value_builder/unimarc_field_124b.tt", + query => $input, + type => "intranet", + flagsrequired => { editcatalogue => '*' }, + } + ); + my $f1 = substr( $result, 0, 1 ); + $template->param( + index => $index, + "f1$f1" => 1 + ); + output_html_with_http_headers $input, $cookie, $template->output; } diff --git a/cataloguing/value_builder/unimarc_field_124c.pl b/cataloguing/value_builder/unimarc_field_124c.pl index 571b6b62ca..4c1756ac0d 100755 --- a/cataloguing/value_builder/unimarc_field_124c.pl +++ b/cataloguing/value_builder/unimarc_field_124c.pl @@ -1,6 +1,5 @@ #!/usr/bin/perl - # Copyright 2000-2002 Katipo Communications # # This file is part of Koha. @@ -21,16 +20,16 @@ use Modern::Perl; use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Context; use C4::Search; use C4::Output qw( output_html_with_http_headers ); sub plugin_javascript { -my ($dbh,$record,$tagslib,$field_number) = @_; -my $function_name= $field_number; -my $res=" + my ( $dbh, $record, $tagslib, $field_number ) = @_; + my $function_name = $field_number; + my $res = " "; -return ($function_name,$res); + return ( $function_name, $res ); } + sub plugin { -my ($input) = @_; - my $index= $input->param('index'); - my $result= $input->param('result'); + my ($input) = @_; + my $index = $input->param('index'); + my $result = $input->param('result'); + my $dbh = C4::Context->dbh; - my $dbh = C4::Context->dbh; - -my ($template, $loggedinuser, $cookie) - = get_template_and_user({template_name => "cataloguing/value_builder/unimarc_field_124c.tt", - query => $input, - type => "intranet", - flagsrequired => {editcatalogue => '*'}, - }); - my $f1 = substr($result,0,1); - $template->param(index => $index, - "f1$f1" => 1); - output_html_with_http_headers $input, $cookie, $template->output; + my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "cataloguing/value_builder/unimarc_field_124c.tt", + query => $input, + type => "intranet", + flagsrequired => { editcatalogue => '*' }, + } + ); + my $f1 = substr( $result, 0, 1 ); + $template->param( + index => $index, + "f1$f1" => 1 + ); + output_html_with_http_headers $input, $cookie, $template->output; } diff --git a/cataloguing/value_builder/unimarc_field_124d.pl b/cataloguing/value_builder/unimarc_field_124d.pl index 720d65aa1b..72603bcd9d 100755 --- a/cataloguing/value_builder/unimarc_field_124d.pl +++ b/cataloguing/value_builder/unimarc_field_124d.pl @@ -1,6 +1,5 @@ #!/usr/bin/perl - # Copyright 2000-2002 Katipo Communications # # This file is part of Koha. @@ -21,16 +20,16 @@ use Modern::Perl; use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Context; use C4::Search; use C4::Output qw( output_html_with_http_headers ); sub plugin_javascript { -my ($dbh,$record,$tagslib,$field_number) = @_; -my $function_name= $field_number; -my $res=" + my ( $dbh, $record, $tagslib, $field_number ) = @_; + my $function_name = $field_number; + my $res = " "; -return ($function_name,$res); + return ( $function_name, $res ); } + sub plugin { -my ($input) = @_; - my $index= $input->param('index'); - my $result= $input->param('result'); + my ($input) = @_; + my $index = $input->param('index'); + my $result = $input->param('result'); + my $dbh = C4::Context->dbh; - my $dbh = C4::Context->dbh; - -my ($template, $loggedinuser, $cookie) - = get_template_and_user({template_name => "cataloguing/value_builder/unimarc_field_124d.tt", - query => $input, - type => "intranet", - flagsrequired => {editcatalogue => '*'}, - }); - my $f1 = substr($result,0,1); - $template->param(index => $index, - "f1$f1" => 1); - output_html_with_http_headers $input, $cookie, $template->output; + my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "cataloguing/value_builder/unimarc_field_124d.tt", + query => $input, + type => "intranet", + flagsrequired => { editcatalogue => '*' }, + } + ); + my $f1 = substr( $result, 0, 1 ); + $template->param( + index => $index, + "f1$f1" => 1 + ); + output_html_with_http_headers $input, $cookie, $template->output; } diff --git a/cataloguing/value_builder/unimarc_field_124e.pl b/cataloguing/value_builder/unimarc_field_124e.pl index 65a3b736b9..b2474993ab 100755 --- a/cataloguing/value_builder/unimarc_field_124e.pl +++ b/cataloguing/value_builder/unimarc_field_124e.pl @@ -1,6 +1,5 @@ #!/usr/bin/perl - # Copyright 2000-2002 Katipo Communications # # This file is part of Koha. @@ -21,16 +20,16 @@ use Modern::Perl; use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Context; use C4::Search; use C4::Output qw( output_html_with_http_headers ); sub plugin_javascript { -my ($dbh,$record,$tagslib,$field_number) = @_; -my $function_name= $field_number; -my $res=" + my ( $dbh, $record, $tagslib, $field_number ) = @_; + my $function_name = $field_number; + my $res = " "; -return ($function_name,$res); + return ( $function_name, $res ); } + sub plugin { -my ($input) = @_; - my $index= $input->param('index'); - my $result= $input->param('result'); + my ($input) = @_; + my $index = $input->param('index'); + my $result = $input->param('result'); + my $dbh = C4::Context->dbh; - my $dbh = C4::Context->dbh; - -my ($template, $loggedinuser, $cookie) - = get_template_and_user({template_name => "cataloguing/value_builder/unimarc_field_124e.tt", - query => $input, - type => "intranet", - flagsrequired => {editcatalogue => '*'}, - }); - my $f1 = substr($result,0,1); - $template->param(index => $index, - "f1$f1" => 1); - output_html_with_http_headers $input, $cookie, $template->output; + my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "cataloguing/value_builder/unimarc_field_124e.tt", + query => $input, + type => "intranet", + flagsrequired => { editcatalogue => '*' }, + } + ); + my $f1 = substr( $result, 0, 1 ); + $template->param( + index => $index, + "f1$f1" => 1 + ); + output_html_with_http_headers $input, $cookie, $template->output; } diff --git a/cataloguing/value_builder/unimarc_field_124f.pl b/cataloguing/value_builder/unimarc_field_124f.pl index 695b0b51af..96a7889ffd 100755 --- a/cataloguing/value_builder/unimarc_field_124f.pl +++ b/cataloguing/value_builder/unimarc_field_124f.pl @@ -1,6 +1,5 @@ #!/usr/bin/perl - # Copyright 2000-2002 Katipo Communications # # This file is part of Koha. @@ -21,16 +20,16 @@ use Modern::Perl; use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Context; use C4::Search; use C4::Output qw( output_html_with_http_headers ); sub plugin_javascript { -my ($dbh,$record,$tagslib,$field_number) = @_; -my $function_name= $field_number; -my $res=" + my ( $dbh, $record, $tagslib, $field_number ) = @_; + my $function_name = $field_number; + my $res = " "; -return ($function_name,$res); + return ( $function_name, $res ); } + sub plugin { -my ($input) = @_; - my $index= $input->param('index'); - my $result= $input->param('result'); + my ($input) = @_; + my $index = $input->param('index'); + my $result = $input->param('result'); + my $dbh = C4::Context->dbh; - my $dbh = C4::Context->dbh; - -my ($template, $loggedinuser, $cookie) - = get_template_and_user({template_name => "cataloguing/value_builder/unimarc_field_124f.tt", - query => $input, - type => "intranet", - flagsrequired => {editcatalogue => '*'}, - }); - my $f1 = substr($result,0,2); - $template->param(index => $index, - "f1$f1" => 1); - output_html_with_http_headers $input, $cookie, $template->output; + my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "cataloguing/value_builder/unimarc_field_124f.tt", + query => $input, + type => "intranet", + flagsrequired => { editcatalogue => '*' }, + } + ); + my $f1 = substr( $result, 0, 2 ); + $template->param( + index => $index, + "f1$f1" => 1 + ); + output_html_with_http_headers $input, $cookie, $template->output; } diff --git a/cataloguing/value_builder/unimarc_field_124g.pl b/cataloguing/value_builder/unimarc_field_124g.pl index a1fa48d853..34e87c44ae 100755 --- a/cataloguing/value_builder/unimarc_field_124g.pl +++ b/cataloguing/value_builder/unimarc_field_124g.pl @@ -1,6 +1,5 @@ #!/usr/bin/perl - # Copyright 2000-2002 Katipo Communications # # This file is part of Koha. @@ -21,16 +20,16 @@ use Modern::Perl; use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Context; use C4::Search; use C4::Output qw( output_html_with_http_headers ); sub plugin_javascript { -my ($dbh,$record,$tagslib,$field_number) = @_; -my $function_name= $field_number; -my $res=" + my ( $dbh, $record, $tagslib, $field_number ) = @_; + my $function_name = $field_number; + my $res = " "; -return ($function_name,$res); + return ( $function_name, $res ); } + sub plugin { -my ($input) = @_; - my $index= $input->param('index'); - my $result= $input->param('result'); + my ($input) = @_; + my $index = $input->param('index'); + my $result = $input->param('result'); + my $dbh = C4::Context->dbh; - my $dbh = C4::Context->dbh; - -my ($template, $loggedinuser, $cookie) - = get_template_and_user({template_name => "cataloguing/value_builder/unimarc_field_124g.tt", - query => $input, - type => "intranet", - flagsrequired => {editcatalogue => '*'}, - }); - my $f1 = substr($result,0,2); - $template->param(index => $index, - "f1$f1" => 1); - output_html_with_http_headers $input, $cookie, $template->output; + my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "cataloguing/value_builder/unimarc_field_124g.tt", + query => $input, + type => "intranet", + flagsrequired => { editcatalogue => '*' }, + } + ); + my $f1 = substr( $result, 0, 2 ); + $template->param( + index => $index, + "f1$f1" => 1 + ); + output_html_with_http_headers $input, $cookie, $template->output; } diff --git a/cataloguing/value_builder/unimarc_field_125.pl b/cataloguing/value_builder/unimarc_field_125.pl index 3235293500..673179a3db 100755 --- a/cataloguing/value_builder/unimarc_field_125.pl +++ b/cataloguing/value_builder/unimarc_field_125.pl @@ -1,6 +1,5 @@ #!/usr/bin/perl - # Copyright 2000-2002 Katipo Communications # # This file is part of Koha. @@ -21,7 +20,7 @@ use Modern::Perl; use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Context; use C4::Search; @@ -34,9 +33,9 @@ plugin_parameters : other parameters added when the plugin is called by the dopo =cut sub plugin_javascript { -my ($dbh,$record,$tagslib,$field_number) = @_; -my $function_name= $field_number; -my $res=" + my ( $dbh, $record, $tagslib, $field_number ) = @_; + my $function_name = $field_number; + my $res = " "; -return ($function_name,$res); + return ( $function_name, $res ); } + sub plugin { -my ($input) = @_; - my $index= $input->param('index'); - my $result= $input->param('result'); + my ($input) = @_; + my $index = $input->param('index'); + my $result = $input->param('result'); + my $dbh = C4::Context->dbh; - my $dbh = C4::Context->dbh; - -my ($template, $loggedinuser, $cookie) - = get_template_and_user({template_name => "cataloguing/value_builder/unimarc_field_100.tt", - query => $input, - type => "intranet", - flagsrequired => {editcatalogue => '*'}, - }); - my $f1 = substr($result,0,8); - my $f2 = substr($result,8,1); - my $f3 = substr($result,9,4); - my $f4 = substr($result,13,4); - $template->param(index => $index, - f1 => $f1, - f3 => $f3, - "f2$f2" => 1, - f4 => $f4); - output_html_with_http_headers $input, $cookie, $template->output; + my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "cataloguing/value_builder/unimarc_field_100.tt", + query => $input, + type => "intranet", + flagsrequired => { editcatalogue => '*' }, + } + ); + my $f1 = substr( $result, 0, 8 ); + my $f2 = substr( $result, 8, 1 ); + my $f3 = substr( $result, 9, 4 ); + my $f4 = substr( $result, 13, 4 ); + $template->param( + index => $index, + f1 => $f1, + f3 => $f3, + "f2$f2" => 1, + f4 => $f4 + ); + output_html_with_http_headers $input, $cookie, $template->output; } diff --git a/cataloguing/value_builder/unimarc_field_125a.pl b/cataloguing/value_builder/unimarc_field_125a.pl index 2adf950453..8dc53c8103 100755 --- a/cataloguing/value_builder/unimarc_field_125a.pl +++ b/cataloguing/value_builder/unimarc_field_125a.pl @@ -1,6 +1,5 @@ #!/usr/bin/perl - # Copyright 2000-2002 Katipo Communications # # This file is part of Koha. @@ -21,16 +20,16 @@ use Modern::Perl; use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Context; use C4::Search; use C4::Output qw( output_html_with_http_headers ); sub plugin_javascript { -my ($dbh,$record,$tagslib,$field_number) = @_; -my $function_name= $field_number; -my $res=" + my ( $dbh, $record, $tagslib, $field_number ) = @_; + my $function_name = $field_number; + my $res = " "; -return ($function_name,$res); + return ( $function_name, $res ); } + sub plugin { -my ($input) = @_; - my $index= $input->param('index'); - my $result= $input->param('result'); + my ($input) = @_; + my $index = $input->param('index'); + my $result = $input->param('result'); + my $dbh = C4::Context->dbh; - my $dbh = C4::Context->dbh; - -my ($template, $loggedinuser, $cookie) - = get_template_and_user({template_name => "cataloguing/value_builder/unimarc_field_125a.tt", - query => $input, - type => "intranet", - flagsrequired => {editcatalogue => '*'}, - }); - my $f1 = substr($result,0,1); - my $f2 = substr($result,1,1); - $template->param(index => $index, - "f1$f1" => 1,"f2$f2" => 1); - output_html_with_http_headers $input, $cookie, $template->output; + my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "cataloguing/value_builder/unimarc_field_125a.tt", + query => $input, + type => "intranet", + flagsrequired => { editcatalogue => '*' }, + } + ); + my $f1 = substr( $result, 0, 1 ); + my $f2 = substr( $result, 1, 1 ); + $template->param( + index => $index, + "f1$f1" => 1, "f2$f2" => 1 + ); + output_html_with_http_headers $input, $cookie, $template->output; } diff --git a/cataloguing/value_builder/unimarc_field_125b.pl b/cataloguing/value_builder/unimarc_field_125b.pl index da271bcb33..9604bfe87f 100755 --- a/cataloguing/value_builder/unimarc_field_125b.pl +++ b/cataloguing/value_builder/unimarc_field_125b.pl @@ -1,6 +1,5 @@ #!/usr/bin/perl - # Copyright 2000-2002 Katipo Communications # # This file is part of Koha. @@ -21,17 +20,17 @@ use Modern::Perl; use Koha::Util::FrameworkPlugin qw(wrapper); -use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); use C4::Context; use C4::Search; use C4::Output qw( output_html_with_http_headers ); sub plugin_javascript { -my ($dbh,$record,$tagslib,$field_number) = @_; -my $function_name= $field_number; -my $res=" + my ( $dbh, $record, $tagslib, $field_number ) = @_; + my $function_name = $field_number; + my $res = " "; -return ($function_name,$res); + return ( $function_name, $res ); } - sub plugin { -my ($input) = @_; - my $index= $input->param('index'); - my $result= $input->param('result'); + my ($input) = @_; + my $index = $input->param('index'); + my $result = $input->param('result'); + my $dbh = C4::Context->dbh; - my $dbh = C4::Context->dbh; - -my ($template, $loggedinuser, $cookie) - = get_template_and_user({template_name => "cataloguing/value_builder/unimarc_field_125b.tt", - query => $input, - type => "intranet", - flagsrequired => {editcatalogue => '*'}, - }); - my $f1 = substr($result,0,1); $f1 = wrapper( $f1 ) if $f1; - $template->param(index => $index, - "f1$f1" => 1); - output_html_with_http_headers $input, $cookie, $template->output; + my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "cataloguing/value_builder/unimarc_field_125b.tt", + query => $input, + type => "intranet", + flagsrequired => { editcatalogue => '*' }, + } + ); + my $f1 = substr( $result, 0, 1 ); + $f1 = wrapper($f1) if $f1; + $template->param( + index => $index, + "f1$f1" => 1 + ); + output_html_with_http_headers $input, $cookie, $template->output; } diff --git a/cataloguing/value_builder/unimarc_field_126.pl b/cataloguing/value_builder/unimarc_field_126.pl index 426f1436eb..fd9d7a4cb5 100755 --- a/cataloguing/value_builder/unimarc_field_126.pl +++ b/cataloguing/value_builder/unimarc_field_126.pl @@ -1,6 +1,5 @@ #!/usr/bin/perl - # Copyright 2000-2002 Katipo Communications # # This file is part of Koha. @@ -21,16 +20,16 @@ use Modern::Perl; use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Context; use C4::Search; use C4::Output qw( output_html_with_http_headers ); sub plugin_javascript { -my ($dbh,$record,$tagslib,$field_number) = @_; -my $function_name= $field_number; -my $res=" + my ( $dbh, $record, $tagslib, $field_number ) = @_; + my $function_name = $field_number; + my $res = " "; -return ($function_name,$res); + return ( $function_name, $res ); } + sub plugin { -my ($input) = @_; - my $index= $input->param('index'); - my $result= $input->param('result'); + my ($input) = @_; + my $index = $input->param('index'); + my $result = $input->param('result'); + my $dbh = C4::Context->dbh; - my $dbh = C4::Context->dbh; - -my ($template, $loggedinuser, $cookie) - = get_template_and_user({template_name => "cataloguing/value_builder/unimarc_field_100.tt", - query => $input, - type => "intranet", - flagsrequired => {editcatalogue => '*'}, - }); - my $f1 = substr($result,0,8); - my $f2 = substr($result,8,1); - my $f3 = substr($result,9,4); - my $f4 = substr($result,13,4); - $template->param(index => $index, - f1 => $f1, - f3 => $f3, - "f2$f2" => 1, - f4 => $f4); - output_html_with_http_headers $input, $cookie, $template->output; + my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "cataloguing/value_builder/unimarc_field_100.tt", + query => $input, + type => "intranet", + flagsrequired => { editcatalogue => '*' }, + } + ); + my $f1 = substr( $result, 0, 8 ); + my $f2 = substr( $result, 8, 1 ); + my $f3 = substr( $result, 9, 4 ); + my $f4 = substr( $result, 13, 4 ); + $template->param( + index => $index, + f1 => $f1, + f3 => $f3, + "f2$f2" => 1, + f4 => $f4 + ); + output_html_with_http_headers $input, $cookie, $template->output; } diff --git a/cataloguing/value_builder/unimarc_field_126a.pl b/cataloguing/value_builder/unimarc_field_126a.pl index 6f50585462..f923c75da5 100755 --- a/cataloguing/value_builder/unimarc_field_126a.pl +++ b/cataloguing/value_builder/unimarc_field_126a.pl @@ -1,6 +1,5 @@ #!/usr/bin/perl - # Copyright 2000-2002 Katipo Communications # # This file is part of Koha. @@ -21,17 +20,17 @@ use Modern::Perl; use Koha::Util::FrameworkPlugin qw(wrapper); -use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); use C4::Context; use C4::Search; use C4::Output qw( output_html_with_http_headers ); sub plugin_javascript { -my ($dbh,$record,$tagslib,$field_number) = @_; -my $function_name= $field_number; -my $res=" + my ( $dbh, $record, $tagslib, $field_number ) = @_; + my $function_name = $field_number; + my $res = " "; -return ($function_name,$res); + return ( $function_name, $res ); } - sub plugin { -my ($input) = @_; - my $index= $input->param('index'); - my $result= $input->param('result'); + my ($input) = @_; + my $index = $input->param('index'); + my $result = $input->param('result'); + my $dbh = C4::Context->dbh; - my $dbh = C4::Context->dbh; - -my ($template, $loggedinuser, $cookie) - = get_template_and_user({template_name => "cataloguing/value_builder/unimarc_field_126a.tt", - query => $input, - type => "intranet", - flagsrequired => {editcatalogue => '*'}, - }); - my $f1 = substr($result,0,1); - my $f2 = substr($result,1,1); - my $f3 = substr($result,2,1); - my $f4 = substr($result,3,1); - my $f5 = substr($result,4,1); - my $f6 = substr($result,5,1); - my $f7 = substr($result,6,1); - my $f8 = substr($result,7,1); $f8 = wrapper( $f8 ) if $f8; - my $f9 = substr($result,8,1); $f9 = wrapper( $f9 ) if $f9; - my $f10 = substr($result,9,1); $f10 = wrapper( $f10 ) if $f10; - my $f11 = substr($result,10,1); $f11 = wrapper( $f11 ) if $f11; - my $f12 = substr($result,11,1); $f12 = wrapper( $f12 ) if $f12; - my $f13 = substr($result,12,1); $f13 = wrapper( $f13 ) if $f13; - my $f14 = substr($result,13,1); - my $f15 = substr($result,14,1); - $template->param(index => $index, - "f1$f1" => 1, - "f2$f2" => 1, - "f3$f3" => 1, - "f4$f4" => 1, - "f5$f5" => 1, - "f6$f6" => 1, - "f7$f7" => 1, - "f8$f8" => 1, - "f9$f9" => 1, - "f10$f10" => 1, - "f11$f11" => 1, - "f12$f12" => 1, - "f13$f13" => 1, - "f14$f14" => 1, - "f15$f15" => 1 -); - output_html_with_http_headers $input, $cookie, $template->output; + my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "cataloguing/value_builder/unimarc_field_126a.tt", + query => $input, + type => "intranet", + flagsrequired => { editcatalogue => '*' }, + } + ); + my $f1 = substr( $result, 0, 1 ); + my $f2 = substr( $result, 1, 1 ); + my $f3 = substr( $result, 2, 1 ); + my $f4 = substr( $result, 3, 1 ); + my $f5 = substr( $result, 4, 1 ); + my $f6 = substr( $result, 5, 1 ); + my $f7 = substr( $result, 6, 1 ); + my $f8 = substr( $result, 7, 1 ); + $f8 = wrapper($f8) if $f8; + my $f9 = substr( $result, 8, 1 ); + $f9 = wrapper($f9) if $f9; + my $f10 = substr( $result, 9, 1 ); + $f10 = wrapper($f10) if $f10; + my $f11 = substr( $result, 10, 1 ); + $f11 = wrapper($f11) if $f11; + my $f12 = substr( $result, 11, 1 ); + $f12 = wrapper($f12) if $f12; + my $f13 = substr( $result, 12, 1 ); + $f13 = wrapper($f13) if $f13; + my $f14 = substr( $result, 13, 1 ); + my $f15 = substr( $result, 14, 1 ); + $template->param( + index => $index, + "f1$f1" => 1, + "f2$f2" => 1, + "f3$f3" => 1, + "f4$f4" => 1, + "f5$f5" => 1, + "f6$f6" => 1, + "f7$f7" => 1, + "f8$f8" => 1, + "f9$f9" => 1, + "f10$f10" => 1, + "f11$f11" => 1, + "f12$f12" => 1, + "f13$f13" => 1, + "f14$f14" => 1, + "f15$f15" => 1 + ); + output_html_with_http_headers $input, $cookie, $template->output; } diff --git a/cataloguing/value_builder/unimarc_field_126b.pl b/cataloguing/value_builder/unimarc_field_126b.pl index 1dbc6779ee..d82fea12d9 100755 --- a/cataloguing/value_builder/unimarc_field_126b.pl +++ b/cataloguing/value_builder/unimarc_field_126b.pl @@ -1,6 +1,5 @@ #!/usr/bin/perl - # Copyright 2000-2002 Katipo Communications # # This file is part of Koha. @@ -21,16 +20,16 @@ use Modern::Perl; use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Context; use C4::Search; use C4::Output qw( output_html_with_http_headers ); sub plugin_javascript { -my ($dbh,$record,$tagslib,$field_number) = @_; -my $function_name= $field_number; -my $res=" + my ( $dbh, $record, $tagslib, $field_number ) = @_; + my $function_name = $field_number; + my $res = " "; -return ($function_name,$res); + return ( $function_name, $res ); } + sub plugin { -my ($input) = @_; - my $index= $input->param('index'); - my $result= $input->param('result'); + my ($input) = @_; + my $index = $input->param('index'); + my $result = $input->param('result'); + my $dbh = C4::Context->dbh; - my $dbh = C4::Context->dbh; - -my ($template, $loggedinuser, $cookie) - = get_template_and_user({template_name => "cataloguing/value_builder/unimarc_field_126b.tt", - query => $input, - type => "intranet", - flagsrequired => {editcatalogue => '*'}, - }); - my $f1 = substr($result,0,1); - my $f2 = substr($result,1,1); - my $f3 = substr($result,2,1); - $template->param(index => $index, - "f1$f1" => 1, - "f2$f2" => 1, - "f3$f3" => 1 -); - output_html_with_http_headers $input, $cookie, $template->output; + my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "cataloguing/value_builder/unimarc_field_126b.tt", + query => $input, + type => "intranet", + flagsrequired => { editcatalogue => '*' }, + } + ); + my $f1 = substr( $result, 0, 1 ); + my $f2 = substr( $result, 1, 1 ); + my $f3 = substr( $result, 2, 1 ); + $template->param( + index => $index, + "f1$f1" => 1, + "f2$f2" => 1, + "f3$f3" => 1 + ); + output_html_with_http_headers $input, $cookie, $template->output; } diff --git a/cataloguing/value_builder/unimarc_field_127.pl b/cataloguing/value_builder/unimarc_field_127.pl index 43cc3ac5d8..e6b145550b 100755 --- a/cataloguing/value_builder/unimarc_field_127.pl +++ b/cataloguing/value_builder/unimarc_field_127.pl @@ -1,6 +1,5 @@ #!/usr/bin/perl - # Copyright 2000-2002 Katipo Communications # # This file is part of Koha. @@ -21,16 +20,16 @@ use Modern::Perl; use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Context; use C4::Search; use C4::Output qw( output_html_with_http_headers ); sub plugin_javascript { -my ($dbh,$record,$tagslib,$field_number) = @_; -my $function_name= $field_number; -my $res=" + my ( $dbh, $record, $tagslib, $field_number ) = @_; + my $function_name = $field_number; + my $res = " "; -return ($function_name,$res); + return ( $function_name, $res ); } + sub plugin { -my ($input) = @_; - my $index= $input->param('index'); - my $result= $input->param('result'); + my ($input) = @_; + my $index = $input->param('index'); + my $result = $input->param('result'); + my $dbh = C4::Context->dbh; - my $dbh = C4::Context->dbh; - -my ($template, $loggedinuser, $cookie) - = get_template_and_user({template_name => "cataloguing/value_builder/unimarc_field_127.tt", - query => $input, - type => "intranet", - flagsrequired => {editcatalogue => '*'}, - }); - my $f1 = substr($result,0,2); - my $f2 = substr($result,2,2); - my $f3 = substr($result,4,2); - $template->param(index => $index, - "f1" => $f1, - f2 => $f2, - f3 => $f3); - output_html_with_http_headers $input, $cookie, $template->output; + my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "cataloguing/value_builder/unimarc_field_127.tt", + query => $input, + type => "intranet", + flagsrequired => { editcatalogue => '*' }, + } + ); + my $f1 = substr( $result, 0, 2 ); + my $f2 = substr( $result, 2, 2 ); + my $f3 = substr( $result, 4, 2 ); + $template->param( + index => $index, + "f1" => $f1, + f2 => $f2, + f3 => $f3 + ); + output_html_with_http_headers $input, $cookie, $template->output; } diff --git a/cataloguing/value_builder/unimarc_field_128a.pl b/cataloguing/value_builder/unimarc_field_128a.pl index e825f7c8bc..4572b0e121 100755 --- a/cataloguing/value_builder/unimarc_field_128a.pl +++ b/cataloguing/value_builder/unimarc_field_128a.pl @@ -1,6 +1,5 @@ #!/usr/bin/perl - # Copyright 2000-2002 Katipo Communications # # This file is part of Koha. @@ -21,16 +20,16 @@ use Modern::Perl; use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Context; use C4::Search; use C4::Output qw( output_html_with_http_headers ); sub plugin_javascript { -my ($dbh,$record,$tagslib,$field_number) = @_; -my $function_name= $field_number; -my $res=" + my ( $dbh, $record, $tagslib, $field_number ) = @_; + my $function_name = $field_number; + my $res = " "; -return ($function_name,$res); + return ( $function_name, $res ); } + sub plugin { -my ($input) = @_; - my $index= $input->param('index'); - my $result= $input->param('result'); + my ($input) = @_; + my $index = $input->param('index'); + my $result = $input->param('result'); + my $dbh = C4::Context->dbh; - my $dbh = C4::Context->dbh; - -my ($template, $loggedinuser, $cookie) - = get_template_and_user({template_name => "cataloguing/value_builder/unimarc_field_128a.tt", - query => $input, - type => "intranet", - flagsrequired => {editcatalogue => '*'}, - }); - my $f1 = substr($result,0,2); - $template->param(index => $index, - "f1$f1" => 1); - output_html_with_http_headers $input, $cookie, $template->output; + my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "cataloguing/value_builder/unimarc_field_128a.tt", + query => $input, + type => "intranet", + flagsrequired => { editcatalogue => '*' }, + } + ); + my $f1 = substr( $result, 0, 2 ); + $template->param( + index => $index, + "f1$f1" => 1 + ); + output_html_with_http_headers $input, $cookie, $template->output; } diff --git a/cataloguing/value_builder/unimarc_field_128b.pl b/cataloguing/value_builder/unimarc_field_128b.pl index ee9f267398..6b397cf272 100755 --- a/cataloguing/value_builder/unimarc_field_128b.pl +++ b/cataloguing/value_builder/unimarc_field_128b.pl @@ -1,6 +1,5 @@ #!/usr/bin/perl - # Copyright 2000-2002 Katipo Communications # # This file is part of Koha. @@ -21,17 +20,17 @@ use Modern::Perl; use Koha::Util::FrameworkPlugin qw(wrapper); -use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); use C4::Context; use C4::Search; use C4::Output qw( output_html_with_http_headers ); sub plugin_javascript { -my ($dbh,$record,$tagslib,$field_number) = @_; -my $function_name= $field_number; -my $res=" + my ( $dbh, $record, $tagslib, $field_number ) = @_; + my $function_name = $field_number; + my $res = " "; -return ($function_name,$res); + return ( $function_name, $res ); } - sub plugin { -my ($input) = @_; - my $index= $input->param('index'); - my $result= $input->param('result'); + my ($input) = @_; + my $index = $input->param('index'); + my $result = $input->param('result'); + my $dbh = C4::Context->dbh; - my $dbh = C4::Context->dbh; - -my ($template, $loggedinuser, $cookie) - = get_template_and_user({template_name => "cataloguing/value_builder/unimarc_field_128b.tt", - query => $input, - type => "intranet", - flagsrequired => {editcatalogue => '*'}, - }); - my $f1 = substr($result,0,2); $f1 = wrapper( $f1 ) if $f1; - $template->param(index => $index, - "f1$f1" => 1); - output_html_with_http_headers $input, $cookie, $template->output; + my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "cataloguing/value_builder/unimarc_field_128b.tt", + query => $input, + type => "intranet", + flagsrequired => { editcatalogue => '*' }, + } + ); + my $f1 = substr( $result, 0, 2 ); + $f1 = wrapper($f1) if $f1; + $template->param( + index => $index, + "f1$f1" => 1 + ); + output_html_with_http_headers $input, $cookie, $template->output; } diff --git a/cataloguing/value_builder/unimarc_field_128c.pl b/cataloguing/value_builder/unimarc_field_128c.pl index e8c4cad791..a34286e699 100755 --- a/cataloguing/value_builder/unimarc_field_128c.pl +++ b/cataloguing/value_builder/unimarc_field_128c.pl @@ -1,6 +1,5 @@ #!/usr/bin/perl - # Copyright 2000-2002 Katipo Communications # # This file is part of Koha. @@ -21,16 +20,16 @@ use Modern::Perl; use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Context; use C4::Search; use C4::Output qw( output_html_with_http_headers ); sub plugin_javascript { -my ($dbh,$record,$tagslib,$field_number) = @_; -my $function_name= $field_number; -my $res=" + my ( $dbh, $record, $tagslib, $field_number ) = @_; + my $function_name = $field_number; + my $res = " "; -return ($function_name,$res); + return ( $function_name, $res ); } + sub plugin { -my ($input) = @_; - my $index= $input->param('index'); - my $result= $input->param('result'); + my ($input) = @_; + my $index = $input->param('index'); + my $result = $input->param('result'); + my $dbh = C4::Context->dbh; - my $dbh = C4::Context->dbh; - -my ($template, $loggedinuser, $cookie) - = get_template_and_user({template_name => "cataloguing/value_builder/unimarc_field_128c.tt", - query => $input, - type => "intranet", - flagsrequired => {editcatalogue => '*'}, - }); - my $f1 = substr($result,0,2); - $template->param(index => $index, - "f1$f1" => 1); - output_html_with_http_headers $input, $cookie, $template->output; + my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "cataloguing/value_builder/unimarc_field_128c.tt", + query => $input, + type => "intranet", + flagsrequired => { editcatalogue => '*' }, + } + ); + my $f1 = substr( $result, 0, 2 ); + $template->param( + index => $index, + "f1$f1" => 1 + ); + output_html_with_http_headers $input, $cookie, $template->output; } diff --git a/cataloguing/value_builder/unimarc_field_130.pl b/cataloguing/value_builder/unimarc_field_130.pl index 278136c1b6..db983ea443 100755 --- a/cataloguing/value_builder/unimarc_field_130.pl +++ b/cataloguing/value_builder/unimarc_field_130.pl @@ -1,6 +1,5 @@ #!/usr/bin/perl - # Copyright 2000-2002 Katipo Communications # # This file is part of Koha. @@ -19,20 +18,21 @@ # along with Koha; if not, see . use strict; + #use warnings; FIXME - Bug 2505 use Koha::Util::FrameworkPlugin qw(wrapper); -use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); use C4::Context; use C4::Search; use C4::Output qw( output_html_with_http_headers ); sub plugin_javascript { -my ($dbh,$record,$tagslib,$field_number) = @_; -my $function_name= $field_number; -my $res=" + my ( $dbh, $record, $tagslib, $field_number ) = @_; + my $function_name = $field_number; + my $res = " "; -return ($function_name,$res); + return ( $function_name, $res ); } - sub plugin { -my ($input) = @_; - my $index= $input->param('index'); - my $result= $input->param('result'); + my ($input) = @_; + my $index = $input->param('index'); + my $result = $input->param('result'); + my $dbh = C4::Context->dbh; - my $dbh = C4::Context->dbh; + my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "cataloguing/value_builder/unimarc_field_130.tt", + query => $input, + type => "intranet", + flagsrequired => { editcatalogue => '*' }, + } + ); + my $f1 = substr( $result, 0, 1 ); + my $f2 = substr( $result, 1, 1 ); + my $f3 = substr( $result, 2, 1 ); + $f3 = wrapper($f3) if $f3; + my $f4 = substr( $result, 3, 1 ); + my $f5 = substr( $result, 4, 3 ); + my $f6 = substr( $result, 7, 1 ); + my $f7 = substr( $result, 8, 1 ); + my $f8 = substr( $result, 9, 1 ); + my $f9 = substr( $result, 10, 1 ); -my ($template, $loggedinuser, $cookie) - = get_template_and_user({template_name => "cataloguing/value_builder/unimarc_field_130.tt", - query => $input, - type => "intranet", - flagsrequired => {editcatalogue => '*'}, - }); - my $f1 = substr($result,0,1); - my $f2 = substr($result,1,1); - my $f3 = substr($result,2,1); $f3 = wrapper( $f3 ) if $f3; - my $f4 = substr($result,3,1); - my $f5 = substr($result,4,3); - my $f6 = substr($result,7,1); - my $f7 = substr($result,8,1); - my $f8 = substr($result,9,1); - my $f9 = substr($result,10,1); + $template->param( + index => $index, + "f1$f1" => 1, + "f2$f2" => 1, + "f3$f3" => 1, + "f4$f4" => 1, + "f5" => $f5, + "f6$f6" => 1, + "f7$f7" => 1, + "f8$f8" => 1, + "f9$f9" => 1 - $template->param(index => $index, - "f1$f1" => 1, - "f2$f2" => 1, - "f3$f3" => 1, - "f4$f4" => 1, - "f5" => $f5, - "f6$f6" => 1, - "f7$f7" => 1, - "f8$f8" => 1, - "f9$f9" => 1 - -); - output_html_with_http_headers $input, $cookie, $template->output; + ); + output_html_with_http_headers $input, $cookie, $template->output; } diff --git a/cataloguing/value_builder/unimarc_field_135a.pl b/cataloguing/value_builder/unimarc_field_135a.pl index f965eedd5d..c3e63092c8 100755 --- a/cataloguing/value_builder/unimarc_field_135a.pl +++ b/cataloguing/value_builder/unimarc_field_135a.pl @@ -1,6 +1,5 @@ #!/usr/bin/perl - # Copyright 2000-2002 Katipo Communications # # This file is part of Koha. @@ -21,17 +20,17 @@ use Modern::Perl; use Koha::Util::FrameworkPlugin qw(wrapper); -use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); use C4::Context; use C4::Search; use C4::Output qw( output_html_with_http_headers ); sub plugin_javascript { -my ($dbh,$record,$tagslib,$field_number) = @_; -my $function_name= $field_number; -my $res=" + my ( $dbh, $record, $tagslib, $field_number ) = @_; + my $function_name = $field_number; + my $res = " "; -return ($function_name,$res); + return ( $function_name, $res ); } - sub plugin { -my ($input) = @_; - my $index= $input->param('index'); - my $result= $input->param('result'); + my ($input) = @_; + my $index = $input->param('index'); + my $result = $input->param('result'); + my $dbh = C4::Context->dbh; - my $dbh = C4::Context->dbh; + my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "cataloguing/value_builder/unimarc_field_135a.tt", + query => $input, + type => "intranet", + flagsrequired => { editcatalogue => '*' }, + } + ); + my $f1 = substr( $result, 0, 1 ); + $f1 = wrapper($f1) if $f1; + my $f2 = substr( $result, 1, 1 ); + my $f3 = substr( $result, 2, 1 ); + my $f4 = substr( $result, 3, 1 ); + my $f5 = substr( $result, 4, 3 ); + my $f6 = substr( $result, 7, 1 ); + my $f7 = substr( $result, 8, 1 ); + my $f8 = substr( $result, 9, 1 ); + my $f9 = substr( $result, 10, 1 ); -my ($template, $loggedinuser, $cookie) - = get_template_and_user({template_name => "cataloguing/value_builder/unimarc_field_135a.tt", - query => $input, - type => "intranet", - flagsrequired => {editcatalogue => '*'}, - }); - my $f1 = substr($result,0,1); $f1 = wrapper( $f1 ) if $f1; - my $f2 = substr($result,1,1); - my $f3 = substr($result,2,1); - my $f4 = substr($result,3,1); - my $f5 = substr($result,4,3); - my $f6 = substr($result,7,1); - my $f7 = substr($result,8,1); - my $f8 = substr($result,9,1); - my $f9 = substr($result,10,1); + $template->param( + index => $index, + "f1$f1" => 1, + "f2$f2" => 1, + "f3$f3" => 1, + "f4$f4" => 1, + "f5" => $f5, + "f6$f6" => 1, + "f7$f7" => 1, + "f8$f8" => 1, + "f9$f9" => 1 - $template->param(index => $index, - "f1$f1" => 1, - "f2$f2" => 1, - "f3$f3" => 1, - "f4$f4" => 1, - "f5" => $f5, - "f6$f6" => 1, - "f7$f7" => 1, - "f8$f8" => 1, - "f9$f9" => 1 - -); - output_html_with_http_headers $input, $cookie, $template->output; + ); + output_html_with_http_headers $input, $cookie, $template->output; } diff --git a/cataloguing/value_builder/unimarc_field_140.pl b/cataloguing/value_builder/unimarc_field_140.pl index dc7a34d6e1..37512ea789 100755 --- a/cataloguing/value_builder/unimarc_field_140.pl +++ b/cataloguing/value_builder/unimarc_field_140.pl @@ -1,6 +1,5 @@ #!/usr/bin/perl - # Copyright 2000-2002 Katipo Communications # # This file is part of Koha. @@ -19,20 +18,21 @@ # along with Koha; if not, see . use strict; + #use warnings; FIXME - Bug 2505 use Koha::Util::FrameworkPlugin qw(wrapper); -use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); use C4::Context; use C4::Search; use C4::Output qw( output_html_with_http_headers ); sub plugin_javascript { -my ($dbh,$record,$tagslib,$field_number) = @_; -my $function_name= $field_number; -my $res=" + my ( $dbh, $record, $tagslib, $field_number ) = @_; + my $function_name = $field_number; + my $res = " "; -return ($function_name,$res); + return ( $function_name, $res ); } - sub plugin { -my ($input) = @_; - my $index= $input->param('index'); - my $result= $input->param('result'); + my ($input) = @_; + my $index = $input->param('index'); + my $result = $input->param('result'); + my $dbh = C4::Context->dbh; - my $dbh = C4::Context->dbh; + my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "cataloguing/value_builder/unimarc_field_140.tt", + query => $input, + type => "intranet", + flagsrequired => { editcatalogue => '*' }, + } + ); + my $f1 = substr( $result, 0, 1 ); + $f1 = wrapper($f1) if $f1; + my $f2 = substr( $result, 1, 1 ); + $f2 = wrapper($f2) if $f2; + my $f3 = substr( $result, 2, 1 ); + $f3 = wrapper($f3) if $f3; + my $f4 = substr( $result, 3, 1 ); + $f4 = wrapper($f4) if $f4; + my $f5 = substr( $result, 4, 1 ); + $f5 = wrapper($f5) if $f5; + my $f6 = substr( $result, 5, 1 ); + $f6 = wrapper($f6) if $f6; + my $f7 = substr( $result, 6, 1 ); + $f7 = wrapper($f7) if $f7; + my $f8 = substr( $result, 7, 1 ); + $f8 = wrapper($f8) if $f8; + my $f9 = substr( $result, 8, 1 ); + $f9 = wrapper($f9) if $f9; + my $f10 = substr( $result, 9, 2 ); + $f10 = wrapper($f10) if $f10; + my $f11 = substr( $result, 11, 2 ); + $f11 = wrapper($f11) if $f11; + my $f12 = substr( $result, 13, 2 ); + $f12 = wrapper($f12) if $f12; + my $f13 = substr( $result, 15, 2 ); + $f13 = wrapper($f13) if $f13; + my $f14 = substr( $result, 17, 2 ); + $f14 = wrapper($f14) if $f14; + my $f15 = substr( $result, 19, 1 ); + $f15 = wrapper($f15) if $f15; + my $f16 = substr( $result, 20, 1 ); + $f16 = wrapper($f16) if $f16; + my $f17 = substr( $result, 21, 1 ); + $f17 = wrapper($f17) if $f17; + my $f18 = substr( $result, 22, 1 ); + my $f19 = substr( $result, 23, 1 ); + my $f20 = substr( $result, 24, 1 ); + my $f21 = substr( $result, 25, 1 ); -my ($template, $loggedinuser, $cookie) - = get_template_and_user({template_name => "cataloguing/value_builder/unimarc_field_140.tt", - query => $input, - type => "intranet", - flagsrequired => {editcatalogue => '*'}, - }); - my $f1 = substr($result,0,1); $f1 = wrapper( $f1 ) if $f1; - my $f2 = substr($result,1,1); $f2 = wrapper( $f2 ) if $f2; - my $f3 = substr($result,2,1); $f3 = wrapper( $f3 ) if $f3; - my $f4 = substr($result,3,1); $f4 = wrapper( $f4 ) if $f4; - my $f5 = substr($result,4,1); $f5 = wrapper( $f5 ) if $f5; - my $f6 = substr($result,5,1); $f6 = wrapper( $f6 ) if $f6; - my $f7 = substr($result,6,1); $f7 = wrapper( $f7 ) if $f7; - my $f8 = substr($result,7,1); $f8 = wrapper( $f8 ) if $f8; - my $f9 = substr($result,8,1); $f9 = wrapper( $f9 ) if $f9; - my $f10 = substr($result,9,2); $f10 = wrapper( $f10 ) if $f10; - my $f11 = substr($result,11,2); $f11 = wrapper( $f11 ) if $f11; - my $f12 = substr($result,13,2); $f12 = wrapper( $f12 ) if $f12; - my $f13 = substr($result,15,2); $f13 = wrapper( $f13 ) if $f13; - my $f14 = substr($result,17,2); $f14 = wrapper( $f14 ) if $f14; - my $f15 = substr($result,19,1); $f15 = wrapper( $f15 ) if $f15; - my $f16 = substr($result,20,1); $f16 = wrapper( $f16 ) if $f16; - my $f17 = substr($result,21,1); $f17 = wrapper( $f17 ) if $f17; - my $f18 = substr($result,22,1); - my $f19 = substr($result,23,1); - my $f20 = substr($result,24,1); - my $f21 = substr($result,25 ,1); - - - $template->param(index => $index, - "f1$f1" => 1, - "f2$f2" => 1, - "f3$f3" => 1, - "f4$f4" => 1, - "f5$f5" => 1, - "f6$f6" => 1, - "f7$f7" => 1, - "f8$f8" => 1, - "f9$f9" => 1, - "f10$f10" => 1, - "f11$f11" => 1, - "f12$f12" => 1, - "f13$f13" => 1, - "f14$f14" => 1, - "f15$f15" => 1, - "f16$f16" => 1, - "f17$f17" => 1, - "f18$f18" => 1, - "f19$f19" => 1, - "f20$f20" => 1, - "f21$f21" => 1 -); - output_html_with_http_headers $input, $cookie, $template->output; + $template->param( + index => $index, + "f1$f1" => 1, + "f2$f2" => 1, + "f3$f3" => 1, + "f4$f4" => 1, + "f5$f5" => 1, + "f6$f6" => 1, + "f7$f7" => 1, + "f8$f8" => 1, + "f9$f9" => 1, + "f10$f10" => 1, + "f11$f11" => 1, + "f12$f12" => 1, + "f13$f13" => 1, + "f14$f14" => 1, + "f15$f15" => 1, + "f16$f16" => 1, + "f17$f17" => 1, + "f18$f18" => 1, + "f19$f19" => 1, + "f20$f20" => 1, + "f21$f21" => 1 + ); + output_html_with_http_headers $input, $cookie, $template->output; } diff --git a/cataloguing/value_builder/unimarc_field_141.pl b/cataloguing/value_builder/unimarc_field_141.pl index e6415017f6..0f8ad08d6c 100755 --- a/cataloguing/value_builder/unimarc_field_141.pl +++ b/cataloguing/value_builder/unimarc_field_141.pl @@ -1,6 +1,5 @@ #!/usr/bin/perl - # Copyright 2000-2002 Katipo Communications # # This file is part of Koha. @@ -21,16 +20,16 @@ use Modern::Perl; use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Context; use C4::Search; use C4::Output qw( output_html_with_http_headers ); sub plugin_javascript { -my ($dbh,$record,$tagslib,$field_number) = @_; -my $function_name= $field_number; -my $res=" + my ( $dbh, $record, $tagslib, $field_number ) = @_; + my $function_name = $field_number; + my $res = " "; -return ($function_name,$res); + return ( $function_name, $res ); } + sub plugin { -my ($input) = @_; - my $index= $input->param('index'); - my $result= $input->param('result'); + my ($input) = @_; + my $index = $input->param('index'); + my $result = $input->param('result'); + my $dbh = C4::Context->dbh; - my $dbh = C4::Context->dbh; + my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "cataloguing/value_builder/unimarc_field_141.tt", + query => $input, + type => "intranet", + flagsrequired => { editcatalogue => '*' }, + } + ); + my $f1 = substr( $result, 0, 1 ); + my $f2 = substr( $result, 1, 1 ); + my $f3 = substr( $result, 2, 1 ); + my $f4 = substr( $result, 3, 1 ); + my $f5 = substr( $result, 4, 1 ); + my $f6 = substr( $result, 5, 1 ); + my $f7 = substr( $result, 6, 1 ); + my $f8 = substr( $result, 7, 1 ); -my ($template, $loggedinuser, $cookie) - = get_template_and_user({template_name => "cataloguing/value_builder/unimarc_field_141.tt", - query => $input, - type => "intranet", - flagsrequired => {editcatalogue => '*'}, - }); - my $f1 = substr($result,0,1); - my $f2 = substr($result,1,1); - my $f3 = substr($result,2,1); - my $f4 = substr($result,3,1); - my $f5 = substr($result,4,1); - my $f6 = substr($result,5,1); - my $f7 = substr($result,6,1); - my $f8 = substr($result,7,1); - - $template->param(index => $index, - "f1$f1" => 1, - "f2$f2" => 1, - "f3$f3" => 1, - "f4$f4" => 1, - "f5$f5" => 1, - "f6$f6" => 1, - "f7$f7" => 1, - "f8$f8" => 1 -); - output_html_with_http_headers $input, $cookie, $template->output; + $template->param( + index => $index, + "f1$f1" => 1, + "f2$f2" => 1, + "f3$f3" => 1, + "f4$f4" => 1, + "f5$f5" => 1, + "f6$f6" => 1, + "f7$f7" => 1, + "f8$f8" => 1 + ); + output_html_with_http_headers $input, $cookie, $template->output; } diff --git a/cataloguing/value_builder/unimarc_field_146a.pl b/cataloguing/value_builder/unimarc_field_146a.pl index 6d7de2cf7f..0723f7f093 100755 --- a/cataloguing/value_builder/unimarc_field_146a.pl +++ b/cataloguing/value_builder/unimarc_field_146a.pl @@ -17,14 +17,14 @@ use Modern::Perl; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use Koha::I18N; my $builder = sub { my $params = shift; - my $id = $params->{id}; + my $id = $params->{id}; return qq| |; }; -my $launcher= sub { +my $launcher = sub { my $params = shift; - my $cgi = $params->{cgi}; - my ( $template, $loggedinuser, $cookie ) = get_template_and_user({ - template_name => "cataloguing/value_builder/unimarc_field_181-2.tt", - query => $cgi, - type => "intranet", - flagsrequired => {editcatalogue => '*'}, - }); + my $cgi = $params->{cgi}; + my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "cataloguing/value_builder/unimarc_field_181-2.tt", + query => $cgi, + type => "intranet", + flagsrequired => { editcatalogue => '*' }, + } + ); $template->param( - index => scalar $cgi->param('index'), + index => scalar $cgi->param('index'), result => scalar $cgi->param('result'), - cgi => $cgi, + cgi => $cgi, ); output_html_with_http_headers $cgi, $cookie, $template->output; }; diff --git a/cataloguing/value_builder/unimarc_field_181a.pl b/cataloguing/value_builder/unimarc_field_181a.pl index a29691a95e..7b471be890 100755 --- a/cataloguing/value_builder/unimarc_field_181a.pl +++ b/cataloguing/value_builder/unimarc_field_181a.pl @@ -22,14 +22,14 @@ use Modern::Perl; use Date::Calc; use Koha::Util::FrameworkPlugin qw(wrapper); -use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); use C4::Context; use C4::Output qw( output_html_with_http_headers ); -my $builder= sub { +my $builder = sub { my $params = shift; - my $id = $params->{id}; + my $id = $params->{id}; return qq| |; }; -my $launcher= sub { +my $launcher = sub { my $params = shift; - my $cgi = $params->{cgi}; - my ( $template, $loggedinuser, $cookie ) = get_template_and_user({ - template_name => "cataloguing/value_builder/unimarc_field_181a.tt", - query => $cgi, - type => "intranet", - flagsrequired => {editcatalogue => '*'}, - }); + my $cgi = $params->{cgi}; + my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "cataloguing/value_builder/unimarc_field_181a.tt", + query => $cgi, + type => "intranet", + flagsrequired => { editcatalogue => '*' }, + } + ); my $results = scalar $cgi->param('result'); $template->param( - index => scalar $cgi->param('index'), + index => scalar $cgi->param('index'), result => $results, ); # Return the result of the position in the string, ex: abcde = 1=a, 2=b, 3=c... - my @x = split(//, $results); + my @x = split( //, $results ); my $i = 1; for my $fresult (@x) { - $template->param("f$i" => $fresult); + $template->param( "f$i" => $fresult ); ++$i; } output_html_with_http_headers $cgi, $cookie, $template->output; diff --git a/cataloguing/value_builder/unimarc_field_181b.pl b/cataloguing/value_builder/unimarc_field_181b.pl index d7dd4701e7..7ef00330a8 100755 --- a/cataloguing/value_builder/unimarc_field_181b.pl +++ b/cataloguing/value_builder/unimarc_field_181b.pl @@ -22,15 +22,15 @@ use Modern::Perl; use Date::Calc; use Koha::Util::FrameworkPlugin qw(wrapper); -use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); use C4::Context; use C4::Output qw( output_html_with_http_headers ); use Data::Dumper; -my $builder= sub { +my $builder = sub { my $params = shift; - my $id = $params->{id}; + my $id = $params->{id}; return qq| |; }; -my $launcher= sub { +my $launcher = sub { my $params = shift; - my $cgi = $params->{cgi}; - my ( $template, $loggedinuser, $cookie ) = get_template_and_user({ - template_name => "cataloguing/value_builder/unimarc_field_181b.tt", - query => $cgi, - type => "intranet", - flagsrequired => {editcatalogue => '*'}, - }); + my $cgi = $params->{cgi}; + my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "cataloguing/value_builder/unimarc_field_181b.tt", + query => $cgi, + type => "intranet", + flagsrequired => { editcatalogue => '*' }, + } + ); my $results = scalar $cgi->param('result'); $template->param( - index => scalar $cgi->param('index'), + index => scalar $cgi->param('index'), result => $results, ); # Return the result of the position in the string, ex: abcde = 1=a, 2=b, 3=c... - my @x = split(//, $results); + my @x = split( //, $results ); my $i = 1; for my $fresult (@x) { - $template->param("f$i" => $fresult); + $template->param( "f$i" => $fresult ); ++$i; } diff --git a/cataloguing/value_builder/unimarc_field_181c.pl b/cataloguing/value_builder/unimarc_field_181c.pl index 49ac57d97a..6414bcbb3e 100755 --- a/cataloguing/value_builder/unimarc_field_181c.pl +++ b/cataloguing/value_builder/unimarc_field_181c.pl @@ -22,15 +22,14 @@ use Modern::Perl; use Date::Calc; use Koha::Util::FrameworkPlugin qw(wrapper); -use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); use C4::Context; use C4::Output qw( output_html_with_http_headers ); - -my $builder= sub { +my $builder = sub { my $params = shift; - my $id = $params->{id}; + my $id = $params->{id}; return qq| |; }; -my $launcher= sub { +my $launcher = sub { my $params = shift; - my $cgi = $params->{cgi}; - my ( $template, $loggedinuser, $cookie ) = get_template_and_user({ - template_name => "cataloguing/value_builder/unimarc_field_181c.tt", - query => $cgi, - type => "intranet", - flagsrequired => {editcatalogue => '*'}, - }); + my $cgi = $params->{cgi}; + my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "cataloguing/value_builder/unimarc_field_181c.tt", + query => $cgi, + type => "intranet", + flagsrequired => { editcatalogue => '*' }, + } + ); my $results = scalar $cgi->param('result'); my $input_a = substr $results, 0, 3; $template->param( - index => scalar $cgi->param('index'), + index => scalar $cgi->param('index'), result => $results, - f1 => $input_a, + f1 => $input_a, ); output_html_with_http_headers $cgi, $cookie, $template->output; diff --git a/cataloguing/value_builder/unimarc_field_182-2.pl b/cataloguing/value_builder/unimarc_field_182-2.pl index c5f98c87ad..d2a3ccb9be 100755 --- a/cataloguing/value_builder/unimarc_field_182-2.pl +++ b/cataloguing/value_builder/unimarc_field_182-2.pl @@ -1,6 +1,5 @@ #!/usr/bin/perl - # This file is part of Koha. # # Koha is free software; you can redistribute it and/or modify it @@ -21,14 +20,14 @@ use Modern::Perl; use Date::Calc; use Koha::Util::FrameworkPlugin qw(wrapper); -use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); use C4::Context; use C4::Output qw( output_html_with_http_headers ); -my $builder= sub { +my $builder = sub { my $params = shift; - my $id = $params->{id}; + my $id = $params->{id}; return qq| |; }; -my $launcher= sub { +my $launcher = sub { my $params = shift; - my $cgi = $params->{cgi}; - my ( $template, $loggedinuser, $cookie ) = get_template_and_user({ - template_name => "cataloguing/value_builder/unimarc_field_182-2.tt", - query => $cgi, - type => "intranet", - flagsrequired => {editcatalogue => '*'}, - }); + my $cgi = $params->{cgi}; + my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "cataloguing/value_builder/unimarc_field_182-2.tt", + query => $cgi, + type => "intranet", + flagsrequired => { editcatalogue => '*' }, + } + ); $template->param( - index => scalar $cgi->param('index'), + index => scalar $cgi->param('index'), result => scalar $cgi->param('result'), ); output_html_with_http_headers $cgi, $cookie, $template->output; diff --git a/cataloguing/value_builder/unimarc_field_182a.pl b/cataloguing/value_builder/unimarc_field_182a.pl index 7460903f5f..ad138dab2f 100755 --- a/cataloguing/value_builder/unimarc_field_182a.pl +++ b/cataloguing/value_builder/unimarc_field_182a.pl @@ -22,14 +22,14 @@ use Modern::Perl; use Date::Calc; use Koha::Util::FrameworkPlugin qw(wrapper); -use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); use C4::Context; use C4::Output qw( output_html_with_http_headers ); -my $builder= sub { +my $builder = sub { my $params = shift; - my $id = $params->{id}; + my $id = $params->{id}; return qq| |; }; -my $launcher= sub { +my $launcher = sub { my $params = shift; - my $cgi = $params->{cgi}; - my ( $template, $loggedinuser, $cookie ) = get_template_and_user({ - template_name => "cataloguing/value_builder/unimarc_field_182a.tt", - query => $cgi, - type => "intranet", - flagsrequired => {editcatalogue => '*'}, - }); + my $cgi = $params->{cgi}; + my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "cataloguing/value_builder/unimarc_field_182a.tt", + query => $cgi, + type => "intranet", + flagsrequired => { editcatalogue => '*' }, + } + ); my $results = scalar $cgi->param('result'); $template->param( - index => scalar $cgi->param('index'), + index => scalar $cgi->param('index'), result => $results, ); # Return the result of the position in the string, ex: abcde = 1=a, 2=b, 3=c... - my @x = split(//, $results); + my @x = split( //, $results ); my $i = 1; for my $fresult (@x) { - $template->param("f$i" => $fresult); + $template->param( "f$i" => $fresult ); ++$i; } output_html_with_http_headers $cgi, $cookie, $template->output; diff --git a/cataloguing/value_builder/unimarc_field_182c.pl b/cataloguing/value_builder/unimarc_field_182c.pl index 1a8891d010..aba11fcf7c 100755 --- a/cataloguing/value_builder/unimarc_field_182c.pl +++ b/cataloguing/value_builder/unimarc_field_182c.pl @@ -22,14 +22,14 @@ use Modern::Perl; use Date::Calc; use Koha::Util::FrameworkPlugin qw(wrapper); -use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); use C4::Context; use C4::Output qw( output_html_with_http_headers ); -my $builder= sub { +my $builder = sub { my $params = shift; - my $id = $params->{id}; + my $id = $params->{id}; return qq| |; }; -my $launcher= sub { +my $launcher = sub { my $params = shift; - my $cgi = $params->{cgi}; - my ( $template, $loggedinuser, $cookie ) = get_template_and_user({ - template_name => "cataloguing/value_builder/unimarc_field_182c.tt", - query => $cgi, - type => "intranet", - flagsrequired => {editcatalogue => '*'}, - }); + my $cgi = $params->{cgi}; + my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "cataloguing/value_builder/unimarc_field_182c.tt", + query => $cgi, + type => "intranet", + flagsrequired => { editcatalogue => '*' }, + } + ); my $results = scalar $cgi->param('result'); my $input_a = substr $results, 0, 3; $template->param( - index => scalar $cgi->param('index'), + index => scalar $cgi->param('index'), result => $results, - f1 => $input_a, + f1 => $input_a, ); output_html_with_http_headers $cgi, $cookie, $template->output; diff --git a/cataloguing/value_builder/unimarc_field_183-2.pl b/cataloguing/value_builder/unimarc_field_183-2.pl index c717bb39e5..019c0a068a 100755 --- a/cataloguing/value_builder/unimarc_field_183-2.pl +++ b/cataloguing/value_builder/unimarc_field_183-2.pl @@ -22,14 +22,14 @@ use Modern::Perl; use Date::Calc; use Koha::Util::FrameworkPlugin qw(wrapper); -use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); use C4::Context; use C4::Output qw( output_html_with_http_headers ); -my $builder= sub { +my $builder = sub { my $params = shift; - my $id = $params->{id}; + my $id = $params->{id}; return qq| |; }; -my $launcher= sub { +my $launcher = sub { my $params = shift; - my $cgi = $params->{cgi}; - my ( $template, $loggedinuser, $cookie ) = get_template_and_user({ - template_name => "cataloguing/value_builder/unimarc_field_183-2.tt", - query => $cgi, - type => "intranet", - flagsrequired => {editcatalogue => '*'}, - }); + my $cgi = $params->{cgi}; + my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "cataloguing/value_builder/unimarc_field_183-2.tt", + query => $cgi, + type => "intranet", + flagsrequired => { editcatalogue => '*' }, + } + ); $template->param( - index => scalar $cgi->param('index'), + index => scalar $cgi->param('index'), result => scalar $cgi->param('result'), ); output_html_with_http_headers $cgi, $cookie, $template->output; diff --git a/cataloguing/value_builder/unimarc_field_183a.pl b/cataloguing/value_builder/unimarc_field_183a.pl index de45b96bf0..8adcbe8450 100755 --- a/cataloguing/value_builder/unimarc_field_183a.pl +++ b/cataloguing/value_builder/unimarc_field_183a.pl @@ -22,14 +22,14 @@ use Modern::Perl; use Date::Calc; use Koha::Util::FrameworkPlugin qw(wrapper); -use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); use C4::Context; use C4::Output qw( output_html_with_http_headers ); -my $builder= sub { +my $builder = sub { my $params = shift; - my $id = $params->{id}; + my $id = $params->{id}; return qq| |; }; -my $launcher= sub { +my $launcher = sub { my $params = shift; - my $cgi = $params->{cgi}; - my ( $template, $loggedinuser, $cookie ) = get_template_and_user({ - template_name => "cataloguing/value_builder/unimarc_field_183a.tt", - query => $cgi, - type => "intranet", - flagsrequired => {editcatalogue => '*'}, - }); + my $cgi = $params->{cgi}; + my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "cataloguing/value_builder/unimarc_field_183a.tt", + query => $cgi, + type => "intranet", + flagsrequired => { editcatalogue => '*' }, + } + ); my $results = scalar $cgi->param('result'); $template->param( - index => scalar $cgi->param('index'), + index => scalar $cgi->param('index'), result => $results, ); diff --git a/cataloguing/value_builder/unimarc_field_210c.pl b/cataloguing/value_builder/unimarc_field_210c.pl index 8e7b837baf..fe32ccd5aa 100755 --- a/cataloguing/value_builder/unimarc_field_210c.pl +++ b/cataloguing/value_builder/unimarc_field_210c.pl @@ -1,6 +1,5 @@ #!/usr/bin/perl - # Copyright 2000-2002 Katipo Communications # # This file is part of Koha. @@ -23,25 +22,25 @@ use C4::Auth qw( get_template_and_user ); use C4::Auth qw( get_template_and_user ); use C4::Context; use C4::Output qw( pagination_bar output_html_with_http_headers ); -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Search; -use C4::Koha qw( getnbpages ); +use C4::Koha qw( getnbpages ); use C4::AuthoritiesMarc qw( GetAuthority SearchAuthorities ); ###TODO To rewrite in order to use SearchAuthorities sub plugin_javascript { -my ($dbh,$record,$tagslib,$field_number) = @_; -my $function_name= $field_number; -#---- build editors list. -#---- the editor list is built from the "EDITORS" thesaurus -#---- this thesaurus category must be filled as follow : -#---- 200$a for isbn -#---- 200$b for editor -#---- 200$c (repeated) for collections + my ( $dbh, $record, $tagslib, $field_number ) = @_; + my $function_name = $field_number; + #---- build editors list. + #---- the editor list is built from the "EDITORS" thesaurus + #---- this thesaurus category must be filled as follow : + #---- 200$a for isbn + #---- 200$b for editor + #---- 200$c (repeated) for collections -my $res = " + my $res = " "; -return ($function_name,$res); + return ( $function_name, $res ); } sub plugin { -my ($input) = @_; - my $query=CGI->new; - my $op = $query->param('op'); + my ($input) = @_; + my $query = CGI->new; + my $op = $query->param('op'); my $authtypecode = $query->param('authtypecode'); - my $index = $query->param('index'); - my $category = $query->param('category'); + my $index = $query->param('index'); + my $category = $query->param('category'); my $resultstring = $query->param('result'); - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; - my $startfrom = $query->param('startfrom') // 1; # Page number starting at 1 - my ($template, $loggedinuser, $cookie); - my $resultsperpage = $query->param('resultsperpage') // 20; # TODO hardcoded - my $offset = ( $startfrom - 1 ) * $resultsperpage; + my $startfrom = $query->param('startfrom') // 1; # Page number starting at 1 + my ( $template, $loggedinuser, $cookie ); + my $resultsperpage = $query->param('resultsperpage') // 20; # TODO hardcoded + my $offset = ( $startfrom - 1 ) * $resultsperpage; - if ($op eq "do_search") { - my @marclist = $query->multi_param('marclist'); - my @and_or = $query->multi_param('and_or'); + if ( $op eq "do_search" ) { + my @marclist = $query->multi_param('marclist'); + my @and_or = $query->multi_param('and_or'); my @excluding = $query->multi_param('excluding'); - my @operator = $query->multi_param('operator'); - my @value = $query->multi_param('value'); + my @operator = $query->multi_param('operator'); + my @value = $query->multi_param('value'); my $orderby = $query->param('orderby'); # builds tag and subfield arrays my @tags; - my ($results,$total) = SearchAuthorities( \@tags,\@and_or, - \@excluding, \@operator, \@value, - $offset, $resultsperpage,$authtypecode, $orderby); + my ( $results, $total ) = SearchAuthorities( + \@tags, \@and_or, + \@excluding, \@operator, \@value, + $offset, $resultsperpage, $authtypecode, $orderby + ); - # Getting the $b if it exists - for (@$results) { - my $authority = GetAuthority($_->{authid}); - if ($authority->field('200') and $authority->subfield('200','b')) { - $_->{to_report} = $authority->subfield('200','b'); - } - } + # Getting the $b if it exists + for (@$results) { + my $authority = GetAuthority( $_->{authid} ); + if ( $authority->field('200') and $authority->subfield( '200', 'b' ) ) { + $_->{to_report} = $authority->subfield( '200', 'b' ); + } + } - ($template, $loggedinuser, $cookie) - = get_template_and_user({template_name => "cataloguing/value_builder/unimarc_field_210c.tt", - query => $query, - type => 'intranet', - flagsrequired => {editcatalogue => '*'}, - }); + ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "cataloguing/value_builder/unimarc_field_210c.tt", + query => $query, + type => 'intranet', + flagsrequired => { editcatalogue => '*' }, + } + ); # Results displayed in current page my $from = $offset + 1; - my $to = ( $offset + $resultsperpage > $total ) ? $total : $offset + $resultsperpage; + my $to = ( $offset + $resultsperpage > $total ) ? $total : $offset + $resultsperpage; - my $link="../cataloguing/plugin_launcher.pl?plugin_name=unimarc_field_210c.pl&authtypecode=EDITORS&".join("&",map {"value=".$_} @value)."&op=do_search&type=intranet&index=$index"; + my $link = + "../cataloguing/plugin_launcher.pl?plugin_name=unimarc_field_210c.pl&authtypecode=EDITORS&" + . join( "&", map { "value=" . $_ } @value ) + . "&op=do_search&type=intranet&index=$index"; - $template->param(result => $results) if $results; - $template->param('index' => scalar $query->param('index')); + $template->param( result => $results ) if $results; + $template->param( 'index' => scalar $query->param('index') ); $template->param( - total=>$total, - from=>$from, - to=>$to, - authtypecode =>$authtypecode, - resultstring =>$value[0], - pagination_bar => pagination_bar( - $link, - getnbpages($total, $resultsperpage), - $startfrom, - 'startfrom' - ), - ); + total => $total, + from => $from, + to => $to, + authtypecode => $authtypecode, + resultstring => $value[0], + pagination_bar => pagination_bar( + $link, + getnbpages( $total, $resultsperpage ), + $startfrom, + 'startfrom' + ), + ); } else { - ($template, $loggedinuser, $cookie) - = get_template_and_user({template_name => "cataloguing/value_builder/unimarc_field_210c.tt", - query => $query, - type => 'intranet', - flagsrequired => {editcatalogue => '*'}, - }); + ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "cataloguing/value_builder/unimarc_field_210c.tt", + query => $query, + type => 'intranet', + flagsrequired => { editcatalogue => '*' }, + } + ); - $template->param(index => $index, - resultstring => $resultstring - ); + $template->param( + index => $index, + resultstring => $resultstring + ); } - $template->param(category => $category); + $template->param( category => $category ); # Print the page output_html_with_http_headers $query, $cookie, $template->output; diff --git a/cataloguing/value_builder/unimarc_field_210c_bis.pl b/cataloguing/value_builder/unimarc_field_210c_bis.pl index 0e72a8668d..d920cedea5 100755 --- a/cataloguing/value_builder/unimarc_field_210c_bis.pl +++ b/cataloguing/value_builder/unimarc_field_210c_bis.pl @@ -41,10 +41,10 @@ It need : use Modern::Perl; use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Context; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); sub plugin_javascript { @@ -65,22 +65,23 @@ sub plugin_javascript { } sub plugin { - my ($input) = @_; - my $index = $input->param('index'); - my $result = $input->param('result'); - my $editor_found = $input->param('editor_found'); + my ($input) = @_; + my $index = $input->param('index'); + my $result = $input->param('result'); + my $editor_found = $input->param('editor_found'); my $AuthoritySeparator = C4::Context->preference("AuthoritySeparator"); my ( $template, $loggedinuser, $cookie ) = get_template_and_user( - { template_name => "cataloguing/value_builder/unimarc_field_210c_bis.tt", - query => $input, - type => "intranet", - flagsrequired => { editcatalogue => '*' }, + { + template_name => "cataloguing/value_builder/unimarc_field_210c_bis.tt", + query => $input, + type => "intranet", + flagsrequired => { editcatalogue => '*' }, } ); - $template->param( - index => $index, + $template->param( + index => $index, ); output_html_with_http_headers $input, $cookie, $template->output; } diff --git a/cataloguing/value_builder/unimarc_field_225a.pl b/cataloguing/value_builder/unimarc_field_225a.pl index d882e403a6..e701297403 100755 --- a/cataloguing/value_builder/unimarc_field_225a.pl +++ b/cataloguing/value_builder/unimarc_field_225a.pl @@ -1,6 +1,5 @@ #!/usr/bin/perl - # Copyright 2000-2002 Katipo Communications # # This file is part of Koha. @@ -40,13 +39,14 @@ It need : =cut use strict; + #use warnings; FIXME - Bug 2505 use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Context; -use C4::Auth qw( get_template_and_user ); -use C4::Output qw( output_html_with_http_headers ); +use C4::Auth qw( get_template_and_user ); +use C4::Output qw( output_html_with_http_headers ); use C4::AuthoritiesMarc qw( SearchAuthorities GetAuthority ); =head1 DESCRIPTION @@ -58,7 +58,7 @@ plugin_parameters : other parameters added when the plugin is called by the dopo sub plugin_javascript { my ( $dbh, $record, $tagslib, $field_number ) = @_; my $function_name = $field_number; - my $res = " + my $res = " |; }; -my $launcher= sub { +my $launcher = sub { my $params = shift; - my $cgi = $params->{cgi}; - my ( $template, $loggedinuser, $cookie ) = get_template_and_user({ - template_name => "cataloguing/value_builder/unimarc_field_283-2.tt", - query => $cgi, - type => "intranet", - flagsrequired => {editcatalogue => '*'}, - }); + my $cgi = $params->{cgi}; + my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "cataloguing/value_builder/unimarc_field_283-2.tt", + query => $cgi, + type => "intranet", + flagsrequired => { editcatalogue => '*' }, + } + ); $template->param( - index => scalar $cgi->param('index'), + index => scalar $cgi->param('index'), result => scalar $cgi->param('result'), ); output_html_with_http_headers $cgi, $cookie, $template->output; diff --git a/cataloguing/value_builder/unimarc_field_283a.pl b/cataloguing/value_builder/unimarc_field_283a.pl index 91741a17d4..75bbb8c010 100755 --- a/cataloguing/value_builder/unimarc_field_283a.pl +++ b/cataloguing/value_builder/unimarc_field_283a.pl @@ -22,14 +22,14 @@ use Modern::Perl; use Date::Calc; use Koha::Util::FrameworkPlugin qw(wrapper); -use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); use C4::Context; use C4::Output qw( output_html_with_http_headers ); -my $builder= sub { +my $builder = sub { my $params = shift; - my $id = $params->{id}; + my $id = $params->{id}; return qq| |; }; -my $launcher= sub { +my $launcher = sub { my $params = shift; - my $cgi = $params->{cgi}; - my ( $template, $loggedinuser, $cookie ) = get_template_and_user({ - template_name => "cataloguing/value_builder/unimarc_field_283a.tt", - query => $cgi, - type => "intranet", - flagsrequired => {editcatalogue => '*'}, - }); + my $cgi = $params->{cgi}; + my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "cataloguing/value_builder/unimarc_field_283a.tt", + query => $cgi, + type => "intranet", + flagsrequired => { editcatalogue => '*' }, + } + ); my $results = scalar $cgi->param('result'); my $input_a = substr $results, 0; $template->param( - index => scalar $cgi->param('index'), + index => scalar $cgi->param('index'), result => $results, - f1 => $input_a, + f1 => $input_a, ); output_html_with_http_headers $cgi, $cookie, $template->output; }; diff --git a/cataloguing/value_builder/unimarc_field_325h.pl b/cataloguing/value_builder/unimarc_field_325h.pl index e2d4a33f7a..6c7637913c 100755 --- a/cataloguing/value_builder/unimarc_field_325h.pl +++ b/cataloguing/value_builder/unimarc_field_325h.pl @@ -17,8 +17,6 @@ # You should have received a copy of the GNU General Public License # along with Koha; if not, see . - - ######### ATTENTION c'est le contenu du fichier unimarc_field_181-2.tt %] ############# use Modern::Perl; @@ -26,14 +24,14 @@ use Modern::Perl; use Date::Calc; use Koha::Util::FrameworkPlugin qw(wrapper); -use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); use C4::Context; use C4::Output qw( output_html_with_http_headers ); -my $builder= sub { +my $builder = sub { my $params = shift; - my $id = $params->{id}; + my $id = $params->{id}; return qq| |; }; -my $launcher= sub { +my $launcher = sub { my $params = shift; - my $cgi = $params->{cgi}; - my ( $template, $loggedinuser, $cookie ) = get_template_and_user({ - template_name => "cataloguing/value_builder/unimarc_field_325h.tt", - query => $cgi, - type => "intranet", - flagsrequired => {editcatalogue => '*'}, - }); + my $cgi = $params->{cgi}; + my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "cataloguing/value_builder/unimarc_field_325h.tt", + query => $cgi, + type => "intranet", + flagsrequired => { editcatalogue => '*' }, + } + ); my $results = scalar $cgi->param('result'); my $input_a = substr $results, 0, 1; $template->param( - index => scalar $cgi->param('index'), + index => scalar $cgi->param('index'), result => $results, - f0 => $input_a, + f0 => $input_a, ); output_html_with_http_headers $cgi, $cookie, $template->output; }; @@ -69,4 +69,4 @@ my $launcher= sub { # Return the hashref with the builder and launcher to FrameworkPlugin object. # NOTE: If you do not need a popup but only use e.g. Focus, Blur etc. for a # particular plugin, you only need to define and return the builder. -return { builder => $builder, launcher => $launcher }; \ No newline at end of file +return { builder => $builder, launcher => $launcher }; diff --git a/cataloguing/value_builder/unimarc_field_325j.pl b/cataloguing/value_builder/unimarc_field_325j.pl index 9a97833b8c..2aea8eca9b 100755 --- a/cataloguing/value_builder/unimarc_field_325j.pl +++ b/cataloguing/value_builder/unimarc_field_325j.pl @@ -17,8 +17,6 @@ # You should have received a copy of the GNU General Public License # along with Koha; if not, see . - - ######### ATTENTION c'est le contenu du fichier unimarc_field_181-2.tt %] ############# use Modern::Perl; @@ -26,14 +24,14 @@ use Modern::Perl; use Date::Calc; use Koha::Util::FrameworkPlugin qw(wrapper); -use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); use C4::Context; use C4::Output qw( output_html_with_http_headers ); -my $builder= sub { +my $builder = sub { my $params = shift; - my $id = $params->{id}; + my $id = $params->{id}; return qq| |; }; -my $launcher= sub { +my $launcher = sub { my $params = shift; - my $cgi = $params->{cgi}; - my ( $template, $loggedinuser, $cookie ) = get_template_and_user({ - template_name => "cataloguing/value_builder/unimarc_field_325j.tt", - query => $cgi, - type => "intranet", - flagsrequired => {editcatalogue => '*'}, - }); + my $cgi = $params->{cgi}; + my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "cataloguing/value_builder/unimarc_field_325j.tt", + query => $cgi, + type => "intranet", + flagsrequired => { editcatalogue => '*' }, + } + ); my $results = scalar $cgi->param('result'); $template->param( - index => scalar $cgi->param('index'), + index => scalar $cgi->param('index'), result => $results, ); - # Return the result of the position in the string, ex: abcde = 1=a, 2=b, 3=c... - my @x = split(//, $results); + # Return the result of the position in the string, ex: abcde = 1=a, 2=b, 3=c... + my @x = split( //, $results ); my $i = 0; for my $fresult (@x) { - $template->param("f$i" => $fresult); + $template->param( "f$i" => $fresult ); ++$i; } output_html_with_http_headers $cgi, $cookie, $template->output; @@ -75,4 +75,4 @@ my $launcher= sub { # Return the hashref with the builder and launcher to FrameworkPlugin object. # NOTE: If you do not need a popup but only use e.g. Focus, Blur etc. for a # particular plugin, you only need to define and return the builder. -return { builder => $builder, launcher => $launcher }; \ No newline at end of file +return { builder => $builder, launcher => $launcher }; diff --git a/cataloguing/value_builder/unimarc_field_4XX.pl b/cataloguing/value_builder/unimarc_field_4XX.pl index 5130d26d90..9462daff5e 100755 --- a/cataloguing/value_builder/unimarc_field_4XX.pl +++ b/cataloguing/value_builder/unimarc_field_4XX.pl @@ -17,15 +17,15 @@ # You should have received a copy of the GNU General Public License # along with Koha; if not, see . - use strict; + #use warnings; FIXME - Bug 2505 -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Output qw( output_html_with_http_headers ); use C4::Context; use C4::Search qw( new_record_from_zebra ); -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use C4::Biblio qw( TransformMarcToKoha ); @@ -79,17 +79,16 @@ sub plugin { if ( $op eq "fillinput" ) { my $biblionumber = $query->param('biblionumber'); - my $index = $query->param('index'); + my $index = $query->param('index'); my $marcrecord; # open template ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => - "cataloguing/value_builder/unimarc_field_4XX.tt", - query => $query, - type => "intranet", - flagsrequired => { editcatalogue => '*' }, + template_name => "cataloguing/value_builder/unimarc_field_4XX.tt", + query => $query, + type => "intranet", + flagsrequired => { editcatalogue => '*' }, } ); @@ -100,131 +99,119 @@ sub plugin { my $subfield_value_9 = $biblionumber; my $subfield_value_0; $subfield_value_0 = $marcrecord->field('001')->data - if $marcrecord->field('001'); + if $marcrecord->field('001'); my $subfield_value_a; if ( $marcrecord->field('700') ) { $subfield_value_a = $marcrecord->field('700')->subfield("a"); $subfield_value_a .= ", " . $marcrecord->subfield( '700', "b" ) - if $marcrecord->subfield( '700', 'b' ); + if $marcrecord->subfield( '700', 'b' ); $subfield_value_a .= " " . $marcrecord->subfield( '700', "d" ) - if $marcrecord->subfield( '700', 'd' ); - $subfield_value_a .= - " (" . $marcrecord->subfield( '700', 'c' ) - if $marcrecord->subfield( '700', 'c' ); - $subfield_value_a .= " ; " - if $marcrecord->subfield( '700', 'c' ) - and $marcrecord->subfield( '700', 'f' ); + if $marcrecord->subfield( '700', 'd' ); + $subfield_value_a .= " (" . $marcrecord->subfield( '700', 'c' ) + if $marcrecord->subfield( '700', 'c' ); + $subfield_value_a .= " ; " + if $marcrecord->subfield( '700', 'c' ) + and $marcrecord->subfield( '700', 'f' ); $subfield_value_a .= " (" - if ( $marcrecord->subfield( '700', 'f' ) + if ( $marcrecord->subfield( '700', 'f' ) and not( $marcrecord->subfield( '700', 'c' ) ) ); $subfield_value_a .= $marcrecord->subfield( '700', 'f' ) - if ( $marcrecord->subfield( '700', 'f' ) ); + if ( $marcrecord->subfield( '700', 'f' ) ); $subfield_value_a .= ")" - if ( $marcrecord->subfield( '700', 'f' ) + if ( $marcrecord->subfield( '700', 'f' ) or $marcrecord->subfield( '700', 'c' ) ); - } - elsif ( $marcrecord->field('702') ) { + } elsif ( $marcrecord->field('702') ) { $subfield_value_a = $marcrecord->subfield( '702', 'a' ); $subfield_value_a .= ", " . $marcrecord->subfield( '702', 'b' ) - if $marcrecord->subfield( '702', 'b' ); + if $marcrecord->subfield( '702', 'b' ); $subfield_value_a .= " " . $marcrecord->subfield( '702', 'd' ) - if $marcrecord->subfield( '702', 'd' ); - $subfield_value_a .= - " (" . $marcrecord->subfield( '702', 'c' ) - if $marcrecord->subfield( '702', 'c' ); - $subfield_value_a .= " ; " - if $marcrecord->subfield( '702', 'c' ) - and $marcrecord->subfield( '702', 'f' ); + if $marcrecord->subfield( '702', 'd' ); + $subfield_value_a .= " (" . $marcrecord->subfield( '702', 'c' ) + if $marcrecord->subfield( '702', 'c' ); + $subfield_value_a .= " ; " + if $marcrecord->subfield( '702', 'c' ) + and $marcrecord->subfield( '702', 'f' ); $subfield_value_a .= " (" - if $marcrecord->subfield( '702', 'f' ) - and not $marcrecord->subfield( '702', 'c' ); + if $marcrecord->subfield( '702', 'f' ) + and not $marcrecord->subfield( '702', 'c' ); $subfield_value_a .= $marcrecord->subfield( '702', 'f' ) - if $marcrecord->subfield( '702', 'f' ); + if $marcrecord->subfield( '702', 'f' ); $subfield_value_a .= ")" - if $marcrecord->subfield( '702', 'f' ) - or $marcrecord->subfield( '702', 'c' ); - } - elsif ( $marcrecord->field('710') ) { + if $marcrecord->subfield( '702', 'f' ) + or $marcrecord->subfield( '702', 'c' ); + } elsif ( $marcrecord->field('710') ) { $subfield_value_a = $marcrecord->subfield( '710', 'd' ) . " " - if $marcrecord->subfield( '710', 'd' ); + if $marcrecord->subfield( '710', 'd' ); $subfield_value_a .= $marcrecord->subfield( '710', 'a' ) - if $marcrecord->subfield( '710', 'a' ); + if $marcrecord->subfield( '710', 'a' ); $subfield_value_a .= ", " . $marcrecord->subfield( '710', 'b' ) - if $marcrecord->subfield('710'); - $subfield_value_a .= - " (" . $marcrecord->subfield( '710', 'f' ) . " - " - if $marcrecord->subfield( '710', 'f' ); + if $marcrecord->subfield('710'); + $subfield_value_a .= " (" . $marcrecord->subfield( '710', 'f' ) . " - " + if $marcrecord->subfield( '710', 'f' ); $subfield_value_a .= " (" - if $marcrecord->subfield( '710', 'e' ) - and not $marcrecord->subfield( '710', 'f' ); + if $marcrecord->subfield( '710', 'e' ) + and not $marcrecord->subfield( '710', 'f' ); $subfield_value_a .= $marcrecord->subfield( '710', 'e' ) - if $marcrecord->subfield( '710', 'e' ); + if $marcrecord->subfield( '710', 'e' ); $subfield_value_a .= ")" - if $marcrecord->subfield( '710', 'e' ) - or $marcrecord->subfield( '710', 'f' ); - } - elsif ( $marcrecord->field('701') ) { + if $marcrecord->subfield( '710', 'e' ) + or $marcrecord->subfield( '710', 'f' ); + } elsif ( $marcrecord->field('701') ) { $subfield_value_a = $marcrecord->subfield( '701', 'a' ); $subfield_value_a .= ", " . $marcrecord->subfield( '701', 'b' ) - if $marcrecord->subfield( '701', 'b' ); + if $marcrecord->subfield( '701', 'b' ); $subfield_value_a .= " " . $marcrecord->subfield( '701', 'd', ) - if $marcrecord->subfield( '701', 'd' ); - $subfield_value_a .= - " (" . $marcrecord->subfield( '701', 'c' ) . " - " - if $marcrecord->subfield( '701', 'c' ); + if $marcrecord->subfield( '701', 'd' ); + $subfield_value_a .= " (" . $marcrecord->subfield( '701', 'c' ) . " - " + if $marcrecord->subfield( '701', 'c' ); $subfield_value_a .= " (" - if $marcrecord->subfield( '701', 'f' ) - and not( $marcrecord->subfield( '701', 'c' ) ); + if $marcrecord->subfield( '701', 'f' ) + and not( $marcrecord->subfield( '701', 'c' ) ); $subfield_value_a .= $marcrecord->subfield( '701', 'f' ) - if $marcrecord->subfield( '701', 'f' ); + if $marcrecord->subfield( '701', 'f' ); $subfield_value_a .= ")" - if $marcrecord->subfield( '701', 'f' ) - or $marcrecord->subfield( '701', 'c' ); - } - elsif ( $marcrecord->field('712') ) { + if $marcrecord->subfield( '701', 'f' ) + or $marcrecord->subfield( '701', 'c' ); + } elsif ( $marcrecord->field('712') ) { $subfield_value_a = $marcrecord->subfield( '712', 'd' ) . " " - if $marcrecord->subfield( '712', 'd' ); + if $marcrecord->subfield( '712', 'd' ); $subfield_value_a .= $marcrecord->subfield( '712', 'a' ) - if $marcrecord->subfield( '712', 'a' ); + if $marcrecord->subfield( '712', 'a' ); $subfield_value_a .= ", " . $marcrecord->subfield( '712', 'b' ) - if $marcrecord->subfield( '712', 'b' ); - $subfield_value_a .= - " (" . $marcrecord->subfield( '712', 'f' ) . " - " - if $marcrecord->subfield( '712', 'f' ); + if $marcrecord->subfield( '712', 'b' ); + $subfield_value_a .= " (" . $marcrecord->subfield( '712', 'f' ) . " - " + if $marcrecord->subfield( '712', 'f' ); $subfield_value_a .= " (" - if $marcrecord->subfield( '712', "e" ) - and not $marcrecord->subfield( '712', 'f' ); + if $marcrecord->subfield( '712', "e" ) + and not $marcrecord->subfield( '712', 'f' ); $subfield_value_a .= $marcrecord->subfield( '712', 'e' ) - if $marcrecord->subfield( '712', 'e' ); + if $marcrecord->subfield( '712', 'e' ); $subfield_value_a .= ")" - if $marcrecord->subfield( '712', 'e' ) - or $marcrecord->subfield( '712', 'f' ); - } - elsif ( $marcrecord->field('200') ) { + if $marcrecord->subfield( '712', 'e' ) + or $marcrecord->subfield( '712', 'f' ); + } elsif ( $marcrecord->field('200') ) { $subfield_value_a = $marcrecord->subfield( '200', 'f' ); } - my $subfield_value_c; - my $subfield_value_d; - my $subfield_value_e; + my $subfield_value_c; + my $subfield_value_d; + my $subfield_value_e; $subfield_value_c = $marcrecord->field('210')->subfield("a") - if ( $marcrecord->field('210') ); + if ( $marcrecord->field('210') ); $subfield_value_d = $marcrecord->field('210')->subfield("d") - if ( $marcrecord->field('210') ); - $subfield_value_e = $marcrecord->field('205')->subfield("a") - if ( $marcrecord->field('205') ); + if ( $marcrecord->field('210') ); + $subfield_value_e = $marcrecord->field('205')->subfield("a") + if ( $marcrecord->field('205') ); my $subfield_value_h; if ( ( $marcrecord->field('200') ) && ( $marcrecord->field('200')->subfield("h") ) ) { $subfield_value_h = $marcrecord->field('200')->subfield("h"); - } - elsif (( $marcrecord->field('225') ) + } elsif ( ( $marcrecord->field('225') ) && ( $marcrecord->field('225')->subfield("h") ) ) { $subfield_value_h = $marcrecord->field('225')->subfield("h"); - } - elsif (( $marcrecord->field('500') ) + } elsif ( ( $marcrecord->field('500') ) && ( $marcrecord->field('500')->subfield("h") ) ) { $subfield_value_h = $marcrecord->field('500')->subfield("h"); @@ -235,13 +222,11 @@ sub plugin { && ( $marcrecord->field('200')->subfield("i") ) ) { $subfield_value_i = $marcrecord->field('200')->subfield("i"); - } - elsif (( $marcrecord->field('225') ) + } elsif ( ( $marcrecord->field('225') ) && ( $marcrecord->field('225')->subfield("i") ) ) { $subfield_value_i = $marcrecord->field('225')->subfield("i"); - } - elsif (( $marcrecord->field('500') ) + } elsif ( ( $marcrecord->field('500') ) && ( $marcrecord->field('500')->subfield("i") ) ) { $subfield_value_i = $marcrecord->field('500')->subfield("i"); @@ -260,21 +245,19 @@ sub plugin { if ( $marcrecord->field('200') ); my $subfield_value_p; - $subfield_value_p = $marcrecord->field('215')->subfield("a") - if ( $marcrecord->field('215') ); + $subfield_value_p = $marcrecord->field('215')->subfield("a") + if ( $marcrecord->field('215') ); my $subfield_value_t; if ( ( $marcrecord->field('200') ) && ( $marcrecord->field('200')->subfield("a") ) ) { $subfield_value_t = $marcrecord->field('200')->subfield("a"); - } - elsif (( $marcrecord->field('225') ) + } elsif ( ( $marcrecord->field('225') ) && ( $marcrecord->field('225')->subfield("a") ) ) { $subfield_value_t = $marcrecord->field('225')->subfield("a"); - } - elsif (( $marcrecord->field('500') ) + } elsif ( ( $marcrecord->field('500') ) && ( $marcrecord->field('500')->subfield("a") ) ) { $subfield_value_t = $marcrecord->field('500')->subfield("a"); @@ -290,8 +273,7 @@ sub plugin { && ( $marcrecord->field('225')->subfield("v") ) ) { $subfield_value_v = $marcrecord->field('225')->subfield("v"); - } - elsif (( $marcrecord->field('200') ) + } elsif ( ( $marcrecord->field('200') ) && ( $marcrecord->field('200')->subfield("h") ) ) { $subfield_value_v = $marcrecord->field('200')->subfield("h"); @@ -300,14 +282,16 @@ sub plugin { if ( $marcrecord->field('011') and not( ( $marcrecord->field('011')->subfield("y") ) - or ( $marcrecord->field('011')->subfield("z") ) ) ) { - $subfield_value_x = $marcrecord->field('011')->subfield("a"); + or ( $marcrecord->field('011')->subfield("z") ) ) + ) + { + $subfield_value_x = $marcrecord->field('011')->subfield("a"); } my $subfield_value_y; - if ( $marcrecord->field('013') ) { - $subfield_value_y = $marcrecord->field('013')->subfield("a"); + if ( $marcrecord->field('013') ) { + $subfield_value_y = $marcrecord->field('013')->subfield("a"); } - if ( $marcrecord->field('010') ) { + if ( $marcrecord->field('010') ) { $subfield_value_y = $marcrecord->field('010')->subfield("a"); } $template->param( @@ -333,18 +317,19 @@ sub plugin { subfield_value_y => "$subfield_value_y", ); ############################################################### - } - elsif ( $op eq "do_search" ) { + } elsif ( $op eq "do_search" ) { my $search = $query->param('search'); my $itype = $query->param('itype'); my $startfrom = $query->param('startfrom'); my $resultsperpage = $query->param('resultsperpage') || 20; my $orderby; my $op = 'AND'; - $search = 'kw:'.$search." $op mc-itemtype:".$itype if $itype; - my $searcher = Koha::SearchEngine::Search->new({index => $Koha::SearchEngine::BIBLIOS_INDEX}); - my ( $errors, $results, $total_hits ) = $searcher->simple_search_compat($search, $startfrom * $resultsperpage, $resultsperpage ); - if (defined $errors ) { + $search = 'kw:' . $search . " $op mc-itemtype:" . $itype if $itype; + my $searcher = Koha::SearchEngine::Search->new( { index => $Koha::SearchEngine::BIBLIOS_INDEX } ); + my ( $errors, $results, $total_hits ) = + $searcher->simple_search_compat( $search, $startfrom * $resultsperpage, $resultsperpage ); + + if ( defined $errors ) { $results = []; } my $total = @{$results}; @@ -353,10 +338,9 @@ sub plugin { ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => - "cataloguing/value_builder/unimarc_field_4XX.tt", - query => $query, - type => 'intranet', + template_name => "cataloguing/value_builder/unimarc_field_4XX.tt", + query => $query, + type => 'intranet', } ); @@ -364,31 +348,25 @@ sub plugin { my $displaynext = 0; my $displayprev = $startfrom; - if( ( $total_hits - ( ( $startfrom + 1 ) * ($resultsperpage) ) ) > 0 ) { + if ( ( $total_hits - ( ( $startfrom + 1 ) * ($resultsperpage) ) ) > 0 ) { $displaynext = 1; } my @arrayresults; my @field_data = ($search); - for ( - my $i = 0 ; - $i < $total && $i < $resultsperpage ; - $i++ - ) - { + for ( my $i = 0 ; $i < $total && $i < $resultsperpage ; $i++ ) { my $record = C4::Search::new_record_from_zebra( 'biblioserver', $results->[$i] ); next unless $record; - my $rechash = TransformMarcToKoha({ record => $record }); + my $rechash = TransformMarcToKoha( { record => $record } ); if ( my $f = $record->field('200') ) { $rechash->{fulltitle} = - join(', ', map { $_->[1] } grep { $_->[0] =~ /[aehi]/ } $f->subfields() ); - } - else { + join( ', ', map { $_->[1] } grep { $_->[0] =~ /[aehi]/ } $f->subfields() ); + } else { $rechash->{fulltitle} = $rechash->{title}; } my $pos; my $countitems; if ( $rechash->{itemnumber} ) { - $countitems=1; + $countitems = 1; } while ( index( $rechash->{itemnumber}, '|', $pos ) > 0 ) { $countitems += 1; @@ -399,22 +377,21 @@ sub plugin { my @itemcallnumbers = split /\|/, $rechash->{itemcallnumber}; my $CN; for ( my $i = 0 ; $i < @holdingbranches ; $i++ ) { - $CN .= - $holdingbranches[$i] . " ( " . $itemcallnumbers[$i] . " ) |"; + $CN .= $holdingbranches[$i] . " ( " . $itemcallnumbers[$i] . " ) |"; } $CN =~ s/ \|$//; $rechash->{CN} = $CN; push @arrayresults, $rechash; - } + } - # for(my $i = 0 ; $i <= $#marclist ; $i++) - # { - # push @field_data, { term => "marclist", val=>$marclist[$i] }; - # push @field_data, { term => "and_or", val=>$and_or[$i] }; - # push @field_data, { term => "excluding", val=>$excluding[$i] }; - # push @field_data, { term => "operator", val=>$operator[$i] }; - # push @field_data, { term => "value", val=>$value[$i] }; - # } + # for(my $i = 0 ; $i <= $#marclist ; $i++) + # { + # push @field_data, { term => "marclist", val=>$marclist[$i] }; + # push @field_data, { term => "and_or", val=>$and_or[$i] }; + # push @field_data, { term => "excluding", val=>$excluding[$i] }; + # push @field_data, { term => "operator", val=>$operator[$i] }; + # push @field_data, { term => "value", val=>$value[$i] }; + # } my @numbers = (); @@ -424,12 +401,12 @@ sub plugin { my $highlight = 0; ( $startfrom == ( $i - 1 ) ) && ( $highlight = 1 ); push @numbers, - { + { number => $i, highlight => $highlight, searchdata => \@field_data, startfrom => ( $i - 1 ) - }; + }; } } } @@ -439,21 +416,22 @@ sub plugin { if ( $total_hits < $from + $resultsperpage ) { $to = $total_hits; - }else{ - $to = $from + $resultsperpage ; + } else { + $to = $from + $resultsperpage; } -# my $link="/cgi-bin/koha/cataloguing/value_builder/unimarc4XX.pl?op=do_search&q=$search_desc&resultsperpage=$resultsperpage&startfrom=$startfrom&search=$search"; -# foreach my $sort (@sort_by){ -# $link.="&sort_by=".$sort."&"; -# } -# $template->param( -# pagination_bar => pagination_bar( -# $link, -# getnbpages($hits, $results_per_page), -# $page, -# 'page' -# ), -# ); + + # my $link="/cgi-bin/koha/cataloguing/value_builder/unimarc4XX.pl?op=do_search&q=$search_desc&resultsperpage=$resultsperpage&startfrom=$startfrom&search=$search"; + # foreach my $sort (@sort_by){ + # $link.="&sort_by=".$sort."&"; + # } + # $template->param( + # pagination_bar => pagination_bar( + # $link, + # getnbpages($hits, $results_per_page), + # $page, + # 'page' + # ), + # ); $template->param( result => \@arrayresults, index => scalar $query->param('index') . "", @@ -473,23 +451,21 @@ sub plugin { Search => 0 ); - } - else { + } else { ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => - "cataloguing/value_builder/unimarc_field_4XX.tt", - query => $query, - type => "intranet", + template_name => "cataloguing/value_builder/unimarc_field_4XX.tt", + query => $query, + type => "intranet", } ); my @itemtypes = Koha::ItemTypes->search->as_list; $template->param( #classlist => $classlist, - itypeloop => \@itemtypes, - index => scalar $query->param('index'), - Search => 1, + itypeloop => \@itemtypes, + index => scalar $query->param('index'), + Search => 1, ); } output_html_with_http_headers $query, $cookie, $template->output; diff --git a/cataloguing/value_builder/unimarc_field_686a.pl b/cataloguing/value_builder/unimarc_field_686a.pl index 7841f75f8a..384a711826 100755 --- a/cataloguing/value_builder/unimarc_field_686a.pl +++ b/cataloguing/value_builder/unimarc_field_686a.pl @@ -20,16 +20,16 @@ use Modern::Perl; use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Context; use C4::Search; use C4::Output qw( output_html_with_http_headers ); sub plugin_javascript { -my ($dbh,$record,$tagslib,$field_number) = @_; -my $function_name= $field_number; -my $res = " + my ( $dbh, $record, $tagslib, $field_number ) = @_; + my $function_name = $field_number; + my $res = " "; -return ($function_name,$res); + return ( $function_name, $res ); } sub plugin { -my ($input) = @_; - my $index= $input->param('index'); - my $index2= $input->param('index2'); - $index2=-1 unless($index2); - my $result= $input->param('result'); + my ($input) = @_; + my $index = $input->param('index'); + my $index2 = $input->param('index2'); + $index2 = -1 unless ($index2); + my $result = $input->param('result'); - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; - my ($template, $loggedinuser, $cookie) = get_template_and_user( + my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "cataloguing/value_builder/unimarc_field_686a.tt", - query => $input, - type => "intranet", - flagsrequired => { editcatalogue => '*' }, + template_name => "cataloguing/value_builder/unimarc_field_686a.tt", + query => $input, + type => "intranet", + flagsrequired => { editcatalogue => '*' }, } ); - $template->param(index => $index, - index2 => $index2, - authtypecode => 'CLASSCD', - ); - output_html_with_http_headers $input, $cookie, $template->output; + $template->param( + index => $index, + index2 => $index2, + authtypecode => 'CLASSCD', + ); + output_html_with_http_headers $input, $cookie, $template->output; } diff --git a/cataloguing/value_builder/unimarc_leader.pl b/cataloguing/value_builder/unimarc_leader.pl index 0bcbb04ebb..fdce409a3b 100755 --- a/cataloguing/value_builder/unimarc_leader.pl +++ b/cataloguing/value_builder/unimarc_leader.pl @@ -1,6 +1,5 @@ #!/usr/bin/perl - # Copyright 2000-2002 Katipo Communications # # This file is part of Koha. @@ -21,8 +20,8 @@ use Modern::Perl; use Koha::Util::FrameworkPlugin qw(wrapper); -use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); use C4::Context; use C4::Search; @@ -52,7 +51,6 @@ function Clic$function_name(event) { return ( $function_name, $res ); } - sub plugin { my ($input) = @_; my $index = $input->param('index'); @@ -61,20 +59,26 @@ sub plugin { my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "cataloguing/value_builder/unimarc_leader.tt", - query => $input, - type => "intranet", - flagsrequired => { editcatalogue => '*' }, + template_name => "cataloguing/value_builder/unimarc_leader.tt", + query => $input, + type => "intranet", + flagsrequired => { editcatalogue => '*' }, } ); $result = " nam 3 " unless $result; - my $f5 = substr( $result, 5, 1 ); $f5 = wrapper( $f5 ) if $f5; - my $f6 = substr( $result, 6, 1 ); $f6 = wrapper( $f6 ) if $f6; - my $f7 = substr( $result, 7, 1 ); $f7 = wrapper( $f7 ) if $f7; - my $f8 = substr( $result, 8, 1 ); $f8 = wrapper( $f8 ) if $f8; + my $f5 = substr( $result, 5, 1 ); + $f5 = wrapper($f5) if $f5; + my $f6 = substr( $result, 6, 1 ); + $f6 = wrapper($f6) if $f6; + my $f7 = substr( $result, 7, 1 ); + $f7 = wrapper($f7) if $f7; + my $f8 = substr( $result, 8, 1 ); + $f8 = wrapper($f8) if $f8; my $f9 = substr( $result, 9, 1 ); - my $f17 = substr( $result, 17, 1 ); $f17 = wrapper( $f17 ) if $f17; - my $f18 = substr( $result, 18, 1 ); $f18 = wrapper( $f18 ) if $f18; + my $f17 = substr( $result, 17, 1 ); + $f17 = wrapper($f17) if $f17; + my $f18 = substr( $result, 18, 1 ); + $f18 = wrapper($f18) if $f18; my $f19 = substr( $result, 19, 1 ); $template->param( diff --git a/cataloguing/value_builder/unimarc_leader_authorities.pl b/cataloguing/value_builder/unimarc_leader_authorities.pl index 11b0a0b4db..31131e8b24 100755 --- a/cataloguing/value_builder/unimarc_leader_authorities.pl +++ b/cataloguing/value_builder/unimarc_leader_authorities.pl @@ -20,15 +20,14 @@ use Modern::Perl; use Koha::Util::FrameworkPlugin qw(wrapper); -use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); use C4::Context; use C4::Output qw( output_html_with_http_headers ); - sub plugin_javascript { my ( $dbh, $record, $tagslib, $field_number ) = @_; - my $res = " + my $res = " diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/av-build-dropbox.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/av-build-dropbox.inc index 065fae3f18..a02c5b7e95 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/av-build-dropbox.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/av-build-dropbox.inc @@ -12,21 +12,21 @@ [% DEFAULT class = '' size = 20 %] [% IF avs.count %] - + [% ELSE %] - [% IF no_id %] - - [% ELSE %] - - [% END %] + [% IF no_id %] + + [% ELSE %] + + [% END %] [% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/background_jobs/batch_authority_record_deletion.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/background_jobs/batch_authority_record_deletion.inc index 3abbc98282..43d68d3978 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/background_jobs/batch_authority_record_deletion.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/background_jobs/batch_authority_record_deletion.inc @@ -2,17 +2,11 @@ [% SET report = job.report %] [% IF report %] [% IF report.total_records == report.total_success %] -
- All records have been deleted successfully! -
+
All records have been deleted successfully!
[% ELSIF report.total_success == 0 %] -
- No record has been deleted. An error occurred. -
+
No record has been deleted. An error occurred.
[% ELSE %] -
- [% report.total_success | html %] / [% report.total_records | html %] records have been deleted successfully but some errors occurred. -
+
[% report.total_success | html %] / [% report.total_records | html %] records have been deleted successfully but some errors occurred.
[% END %] [% END %] [% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/background_jobs/batch_authority_record_modification.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/background_jobs/batch_authority_record_modification.inc index 34f04adff0..bcb873b603 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/background_jobs/batch_authority_record_modification.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/background_jobs/batch_authority_record_modification.inc @@ -3,9 +3,7 @@ [% SET report = job.report %] [% IF report %] [% IF report.total_records == report.total_success %] -
- All records have successfully been modified! New batch record modification -
+
All records have successfully been modified! New batch record modification
[% ELSE %]
[% report.total_success | html %] / [% report.total_records | html %] records have successfully been modified. Some errors occurred. @@ -30,7 +28,7 @@ [% SWITCH m.code %] [% CASE 'authority_not_modified' %] Authority record [% authority_link | $raw | $KohaSpan %] has not been modified. An error occurred on modifying it - [% IF m.error %] ([% m.error | html %])[% END %]. + [% IF m.error %]([% m.error | html %])[% END %]. [% CASE 'authority_modified' %] Authority record [% authority_link | $raw | $KohaSpan %] has successfully been modified. [% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/background_jobs/batch_biblio_record_deletion.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/background_jobs/batch_biblio_record_deletion.inc index 2aa40e019e..3c8eb728dd 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/background_jobs/batch_biblio_record_deletion.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/background_jobs/batch_biblio_record_deletion.inc @@ -2,17 +2,11 @@ [% SET report = job.report %] [% IF report %] [% IF report.total_records == report.total_success %] -
- All records have been deleted successfully! -
+
All records have been deleted successfully!
[% ELSIF report.total_success == 0 %] -
- No record has been deleted. An error occurred. -
+
No record has been deleted. An error occurred.
[% ELSE %] -
- [% report.total_success | html %] / [% report.total_records | html %] records have been deleted successfully but some errors occurred. -
+
[% report.total_success | html %] / [% report.total_records | html %] records have been deleted successfully but some errors occurred.
[% END %] [% END %] [% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/background_jobs/batch_biblio_record_modification.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/background_jobs/batch_biblio_record_modification.inc index b932aa05c7..b99adbc505 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/background_jobs/batch_biblio_record_modification.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/background_jobs/batch_biblio_record_modification.inc @@ -41,7 +41,7 @@ [% SWITCH m.code %] [% CASE 'biblio_not_modified' %] Bibliographic record [% biblio_link | $raw %] has not been modified. An error occurred on modifying it. - [% IF m.error %] ([% m.error | html %])[% END %]. + [% IF m.error %]([% m.error | html %])[% END %]. [% CASE 'biblio_modified' %] Bibliographic record [% biblio_link | $raw %] has successfully been modified. [% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/background_jobs/batch_hold_cancel.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/background_jobs/batch_hold_cancel.inc index 91e8efe6c3..e42d32581e 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/background_jobs/batch_hold_cancel.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/background_jobs/batch_hold_cancel.inc @@ -3,9 +3,7 @@ [% SET report = job.report %] [% IF report %] [% IF report.total_holds == report.total_success %] -
- All holds have successfully been cancelled! -
+
All holds have successfully been cancelled!
[% ELSE %]
[% report.total_success | html %] / [% report.total_holds | html %] holds have successfully been modified. Some errors occurred. @@ -13,7 +11,6 @@
[% END %] [% END %] - [% END %] [% BLOCK detail %] @@ -29,13 +26,17 @@ [% SWITCH m.code %] [% CASE 'hold_not_cancelled' %] [% IF m.biblio && m.patron %] - Hold on [% m.biblio.title | html %] for [% INCLUDE 'patron-title.inc' patron=m.patron %] has not been cancelled. + Hold on [% m.biblio.title | html %] for + [% INCLUDE 'patron-title.inc' patron=m.patron %] has not been cancelled. [% END %] An error occurred on cancelling. [% SWITCH m.error %] [% CASE 'hold_not_found' %] No hold with id [% m.hold_id | html %] found. - [% CASE %]Unknown error '[% m.error | html %]'. + [% CASE %] + Unknown error '[% m.error | html %]'. [% END %] [% CASE 'hold_cancelled' %] [% biblio_link = BLOCK %][% m.biblio.title | html %][% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/background_jobs/batch_item_record_deletion.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/background_jobs/batch_item_record_deletion.inc index 0f6909fcc2..d549de90b2 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/background_jobs/batch_item_record_deletion.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/background_jobs/batch_item_record_deletion.inc @@ -15,7 +15,7 @@ [% IF report.not_deleted_itemnumbers.size %]
- [% report.not_deleted_itemnumbers.size | html %] item(s) could not be deleted: [% FOREACH not_deleted_itemnumber IN report.not_deleted_itemnumbers %][% not_deleted_itemnumber | html %] [% END %] + [% report.not_deleted_itemnumbers.size | html %] item(s) could not be deleted: [% FOREACH not_deleted_itemnumber IN report.not_deleted_itemnumbers %][% not_deleted_itemnumber | html %][% END %]
[% END %] @@ -39,18 +39,25 @@ [% END %] [% SWITCH m.code %] - [% CASE 'item_not_deleted' %] - [% item_link = BLOCK %][% m.barcode | html %][% END %] - Item with barcode [% item_link | $raw | $KohaSpan%] cannot be deleted: - [% SWITCH m.reason %] - [% CASE "book_on_loan" %]Item is checked out - [% CASE "not_same_branch" %]Item does not belong to your library - [% CASE "book_reserved" %]Item has a waiting hold - [% CASE "linked_analytics" %]Item has linked analytics - [% CASE "last_item_for_hold" %]Last item for bibliographic record with biblio-level hold on it - [% CASE %]Unknown reason '[% m.reason | html %]' - [% END %] - [% CASE %]Unknown message '[% m.code | html %]' + [% CASE 'item_not_deleted' %] + [% item_link = BLOCK %][% m.barcode | html %][% END %] + Item with barcode [% item_link | $raw | $KohaSpan %] cannot be deleted: + [% SWITCH m.reason %] + [% CASE "book_on_loan" %] + Item is checked out + [% CASE "not_same_branch" %] + Item does not belong to your library + [% CASE "book_reserved" %] + Item has a waiting hold + [% CASE "linked_analytics" %] + Item has linked analytics + [% CASE "last_item_for_hold" %] + Last item for bibliographic record with biblio-level hold on it + [% CASE %] + Unknown reason '[% m.reason | html %]' + [% END %] + [% CASE %] + Unknown message '[% m.code | html %]' [% END %]
[% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/background_jobs/batch_item_record_modification.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/background_jobs/batch_item_record_modification.inc index f7efb32573..916af8b819 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/background_jobs/batch_item_record_modification.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/background_jobs/batch_item_record_modification.inc @@ -28,7 +28,8 @@ [% END %] [% SWITCH m.code %] - [% CASE %]Unknown message '[% m.code | html %]' + [% CASE %] + Unknown message '[% m.code | html %]' [% END %] [% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/background_jobs/create_eholdings_from_biblios.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/background_jobs/create_eholdings_from_biblios.inc index 140b80cea5..1dc75634b6 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/background_jobs/create_eholdings_from_biblios.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/background_jobs/create_eholdings_from_biblios.inc @@ -2,17 +2,11 @@ [% SET report = job.report %] [% IF report && job.status != 'started' && job.status != 'new' %] [% IF report.total_records == report.total_success %] -
- All eHolding titles have been created successfully! -
+
All eHolding titles have been created successfully!
[% ELSIF report.total_success == 0 %] -
- No eHolding titles have been created. An error occurred. -
+
No eHolding titles have been created. An error occurred.
[% ELSE %] -
- [% report.total_success | html %] / [% report.total_records | html %] eHolding titles have been created successfully but some errors occurred. -
+
[% report.total_success | html %] / [% report.total_records | html %] eHolding titles have been created successfully but some errors occurred.
[% END %] [% END %] [% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/background_jobs/erm_sushi_harvester.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/background_jobs/erm_sushi_harvester.inc index 140f95145c..6592937aaf 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/background_jobs/erm_sushi_harvester.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/background_jobs/erm_sushi_harvester.inc @@ -20,15 +20,15 @@ [% job.progress | html %] - [% IF report.report_type.match( '^PR' ) %] - Platforms added - [% ELSIF report.report_type.match( '^DR' ) %] - Databases added - [% ELSIF report.report_type.match( '^IR' ) %] - Items added - [% ELSIF report.report_type.match( '^TR' ) %] - Titles added - [% END %] + [% IF report.report_type.match( '^PR' ) %] + Platforms added + [% ELSIF report.report_type.match( '^DR' ) %] + Databases added + [% ELSIF report.report_type.match( '^IR' ) %] + Items added + [% ELSIF report.report_type.match( '^TR' ) %] + Titles added + [% END %] [% report.us_report_info.added_usage_objects | html %] @@ -85,30 +85,30 @@ [% END %] [% SWITCH m.code %] - [% CASE 'object_already_exists' %] - [% m.title | html %] already exists in this data provider and was not created. New usage statistics were verified anyway - [% CASE 'object_added' %] - [% m.title | html %] successfully added - [% CASE 'object_could_not_be_added' %] - [% m.title | html %] could not be processed - please check the logs - [% CASE 'payload_too_large' %] - COUNTER report file size exceeds limit defined by the database. Limit is [% m.message | html %] MB.
- Please increase this limit or harvest a shorter period. - [% CASE 'no_items' %] - SUSHI response returned no items.
- Please try a different harvest period. - [% CASE %] - SUSHI returned: [% m.message | html %] [% m.code | html %] + [% CASE 'object_already_exists' %] + [% m.title | html %] already exists in this data provider and was not created. New usage statistics were verified anyway + [% CASE 'object_added' %] + [% m.title | html %] successfully added + [% CASE 'object_could_not_be_added' %] + [% m.title | html %] could not be processed - please check the logs + [% CASE 'payload_too_large' %] + COUNTER report file size exceeds limit defined by the database. Limit is [% m.message | html %] MB.
+ Please increase this limit or harvest a shorter period. + [% CASE 'no_items' %] + SUSHI response returned no items.
+ Please try a different harvest period. + [% CASE %] + SUSHI returned: [% m.message | html %] [% m.code | html %] [% END %] [% END %] [% END %] - [% Asset.js("js/job_progress.js") | $raw %] +[% Asset.js("js/job_progress.js") | $raw %] [% BLOCK js %] [% INCLUDE 'str/job_progress.inc' job_id=job.id %] [% INCLUDE 'str/erm_sushi_harvester.inc' %] - + [% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/background_jobs/import_from_kbart_file.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/background_jobs/import_from_kbart_file.inc index 5dce516f49..a4ac5d7451 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/background_jobs/import_from_kbart_file.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/background_jobs/import_from_kbart_file.inc @@ -68,11 +68,10 @@ [% END %] [% END %] - [% BLOCK js %] [% INCLUDE 'str/job_progress.inc' job_id=job.id %] [% INCLUDE 'str/import_from_kbart_file.inc' %] - + [% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/background_jobs/pseudonymize_statistic.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/background_jobs/pseudonymize_statistic.inc index c94fb633e6..ea848cfe6f 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/background_jobs/pseudonymize_statistic.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/background_jobs/pseudonymize_statistic.inc @@ -1,24 +1,16 @@ [% USE KohaSpan %] [% BLOCK report %] [% IF job.status == 'finished' %] -
- Statistic has been pseudonymized. -
+
Statistic has been pseudonymized.
[% ELSIF job.status == 'cancelled' %] -
- Pseudonymization has been cancelled. -
+
Pseudonymization has been cancelled.
[% ELSE %] -
- Pseudonymization is pending. -
+
Pseudonymization is pending.
[% END %] [% END %] [% BLOCK detail %] -
- Pseudonymization. -
+
Pseudonymization.
[% END %] [% BLOCK js %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/background_jobs/stage_marc_for_import.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/background_jobs/stage_marc_for_import.inc index 5361e69df1..f3d8831221 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/background_jobs/stage_marc_for_import.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/background_jobs/stage_marc_for_import.inc @@ -15,12 +15,11 @@

Processing authority records

[% END %]
    -
  • [% report.total | html %] records in file
  • +
  • [% report.total | html %] records in file
  • [% report.import_errors | html %] records not staged because of MARC error
  • [% report.staged | html %] records staged
  • [% IF ( report.checked_matches ) %] -
  • [% report.matched | html %] records with at least one match in catalog per matching rule - "[% report.matcher_code | html %]"
  • +
  • [% report.matched | html %] records with at least one match in catalog per matching rule "[% report.matcher_code | html %]"
  • [% ELSE %] [% IF ( report.matcher_failed ) %]
  • Record matching failed -- unable to retrieve selected matching rule.
  • @@ -39,9 +38,11 @@ View batch

    [% IF report.basket_id && report.vendor_id %] -

    - Add staged files to basket -

    +

    + Add staged files to basket +

    [% END %] [% END %] [% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/background_jobs/update_elastic_index.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/background_jobs/update_elastic_index.inc index 586449db3f..8b14439e45 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/background_jobs/update_elastic_index.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/background_jobs/update_elastic_index.inc @@ -4,13 +4,9 @@ [% BLOCK report %] [% IF job.status == 'finished' %] [% IF report %] -
    - [% report.record_ids.size | html %] records have successfully been reindexed. -
    +
    [% report.record_ids.size | html %] records have successfully been reindexed.
    [% ELSE %] -
    - Job data could not be read, see the logs for details -
    +
    Job data could not be read, see the logs for details
    [% END %] [% ELSIF job.status == 'cancelled' %] The job has been cancelled before it finished. @@ -36,13 +32,12 @@ [% IF report %]

    Record IDs:

    [% END %] [% END %] - [% BLOCK js %] [% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/background_jobs/update_holds_queue_for_biblios.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/background_jobs/update_holds_queue_for_biblios.inc index 66f00a44ed..9337193666 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/background_jobs/update_holds_queue_for_biblios.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/background_jobs/update_holds_queue_for_biblios.inc @@ -3,9 +3,7 @@ [% SET report = job.report %] [% IF report %] [% IF report.total_biblios == report.total_success %] -
    - Holds queue successfully updated. -
    +
    Holds queue successfully updated.
    [% ELSE %]
    Holds queue for [% report.total_success | html %] / [% report.total_biblios | html %] has been successfully updated. Some errors occurred. @@ -13,7 +11,6 @@
    [% END %] [% END %] - [% END %] [% BLOCK detail %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/biblio-title-head.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/biblio-title-head.inc index 19561f1158..ec185129af 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/biblio-title-head.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/biblio-title-head.inc @@ -5,7 +5,8 @@ [%~ END ~%] [%~ biblio.medium | html ~%] [%~ SET subtitles = biblio.subtitle.split(' \| ') ~%] -[%~ FOREACH subtitle IN subtitles ~%][%~ IF Koha.Preference('marcflavour')=='UNIMARC' ~%],[%~ END ~%] +[%~ FOREACH subtitle IN subtitles ~%] + [%~ IF Koha.Preference('marcflavour')=='UNIMARC' ~%],[%~ END ~%] [%~ subtitle | html ~%] [%~ END ~%] [%~ part_numbers = biblio.part_number.split(' \\| ') ~%] diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/biblio-title.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/biblio-title.inc index 6e90032b3c..48f17e2fef 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/biblio-title.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/biblio-title.inc @@ -6,30 +6,31 @@ [%- PROCESS 'show-biblio-title' -%] [%- END -%] [%- BLOCK 'show-biblio-title' -%] -[%- IF !biblio -%] - No bibliographic record -[%- ELSIF !biblio.title -%] - No title -[%- ELSE -%] - [% biblio.title | html | $To %] -[%- END -%] -[%- IF ( biblio.medium ) -%] - [%- biblio.medium | html | $To -%] -[%- END -%] -[%- SET subtitles = biblio.subtitle.split(' \\| ') -%] -[%- FOREACH subtitle IN subtitles -%][%- IF Koha.Preference('marcflavour')=='UNIMARC' -%],[%- END -%] - [%- subtitle | html | $To -%] -[%- END -%] -[%- part_numbers = biblio.part_number.split(' \\| ') -%] -[%- part_names = biblio.part_name.split(' \\| ') -%] -[%- i = 0 -%] -[%- WHILE ( part_numbers.$i.defined || part_names.$i.defined ) -%] - [%- IF ( part_numbers.$i.defined ) -%] - [%- part_numbers.$i | html | $To -%] + [%- IF !biblio -%] + No bibliographic record + [%- ELSIF !biblio.title -%] + No title + [%- ELSE -%] + [% biblio.title | html | $To %] [%- END -%] - [%- IF ( part_names.$i.defined ) -%] - [%- part_names.$i | html | $To -%] + [%- IF ( biblio.medium ) -%] + [%- biblio.medium | html | $To -%] + [%- END -%] + [%- SET subtitles = biblio.subtitle.split(' \\| ') -%] + [%- FOREACH subtitle IN subtitles -%] + [%- IF Koha.Preference('marcflavour')=='UNIMARC' -%],[%- END -%] + [%- subtitle | html | $To -%] + [%- END -%] + [%- part_numbers = biblio.part_number.split(' \\| ') -%] + [%- part_names = biblio.part_name.split(' \\| ') -%] + [%- i = 0 -%] + [%- WHILE ( part_numbers.$i.defined || part_names.$i.defined ) -%] + [%- IF ( part_numbers.$i.defined ) -%] + [%- part_numbers.$i | html | $To -%] + [%- END -%] + [%- IF ( part_names.$i.defined ) -%] + [%- part_names.$i | html | $To -%] + [%- END -%] + [%- i = i + 1 -%] [%- END -%] - [%- i = i + 1 -%] -[%- END -%] [%- END -%] diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/biblio-view-menu.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/biblio-view-menu.inc index a454119b58..5f11926d36 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/biblio-view-menu.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/biblio-view-menu.inc @@ -5,81 +5,83 @@ diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/blocked-fines.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/blocked-fines.inc index 42cbfb6cd7..4868e3cbb4 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/blocked-fines.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/blocked-fines.inc @@ -5,11 +5,11 @@ Charges: Patron has outstanding charges of [% NoIssuesCharge | $Price %]. [% IF !Koha.Preference('AllowFineOverride') && NoIssuesCharge.limit && NoIssuesCharge.overlimit %] - Checkouts are BLOCKED because fine balance is OVER THE LIMIT. + Checkouts are BLOCKED because fine balance is OVER THE LIMIT. [% END %] [% IF CAN_user_updatecharges_remaining_permissions %] - Make payment - Pay all charges + Make payment + Pay all charges [% END %] [% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/blocking_errors.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/blocking_errors.inc index cc0fe60b15..d616a64c83 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/blocking_errors.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/blocking_errors.inc @@ -2,7 +2,8 @@ [% SWITCH blocking_error %] [% CASE 'unknown_patron' %]
    Patron not found. Return to search
    - [% CASE 'cannot_see_patron_infos' %]This account cannot view requested patron information. + [% CASE 'cannot_see_patron_infos' %] + This account cannot view requested patron information. [% CASE 'unknown_biblio' %]
    Bibliographic record not found.
    [% CASE 'unknown_biblionumber' %] @@ -34,5 +35,6 @@ [% END %] [% INCLUDE 'intranet-bottom.inc' %] - [% STOP %] [%# Will stop gracefully without processing any more of the template document.%] + [% STOP %] + [%# Will stop gracefully without processing any more of the template document.%] [% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/branch-selector.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/branch-selector.inc index 61f58aa1c9..19ad580dc5 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/branch-selector.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/branch-selector.inc @@ -1,22 +1,24 @@ [%# To select all include with selectall = 1 %]
    -

    Select all | Clear all

    +

    Select all | Clear all

    [% SET branches_for_loop = branches.hash(1).keys.nsort %][%# Do not modify the original variable 'branches' %] [% WHILE branches_for_loop.size > 0 %] -
    - [% FOREACH i IN branches_for_loop.splice(0, 4) %] - [% i = i - 1%] - [% SET branch = branches.$i %] -
    - [% IF branch.selected || (selectall == 1) %] - - [% ELSE %] - - [% END %] +
    + [% FOREACH i IN branches_for_loop.splice(0, 4) %] + [% i = i - 1 %] + [% SET branch = branches.$i %] +
    + [% IF branch.selected || (selectall == 1) %] + + [% ELSE %] + + [% END %] - + +
    + [% END %]
    - [% END %] -
    [% END %]
    diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/budget_planning.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/budget_planning.inc index 48160ebb20..2ab0e6690d 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/budget_planning.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/budget_planning.inc @@ -1,9 +1,13 @@ [% PROCESS 'i18n.inc' %] [% BLOCK planning %] -[% SWITCH plan %] -[% CASE 'MONTHS' %][% tpx("Budget planning", "Planning for '{fund}' by months", { fund = budget_period_description }) | html %] -[% CASE 'ITEMTYPES' %][% tpx("Budget planning", "Planning for '{fund}' by item types", { fund = budget_period_description }) | html %] -[% CASE 'BRANCHES' %][% tpx("Budget planning", "Planning for '{fund}' by library", { fund = budget_period_description }) | html %] -[% CASE %][% tpx("Budget planning", "Planning for '{fund}' by {type}", { fund = budget_period_description, type = type }) | html %] -[% END %] + [% SWITCH plan %] + [% CASE 'MONTHS' %] + [% tpx("Budget planning", "Planning for '{fund}' by months", { fund = budget_period_description }) | html %] + [% CASE 'ITEMTYPES' %] + [% tpx("Budget planning", "Planning for '{fund}' by item types", { fund = budget_period_description }) | html %] + [% CASE 'BRANCHES' %] + [% tpx("Budget planning", "Planning for '{fund}' by library", { fund = budget_period_description }) | html %] + [% CASE %] + [% tpx("Budget planning", "Planning for '{fund}' by {type}", { fund = budget_period_description, type = type }) | html %] + [% END %] [% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/budgets-admin-search.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/budgets-admin-search.inc index 6546694e42..1ac84c1437 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/budgets-admin-search.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/budgets-admin-search.inc @@ -30,7 +30,7 @@ [% IF branchloo.selected %] [% ELSE %] - + [% END %] [% END %] @@ -44,7 +44,6 @@ [% IF ( CAN_user_catalogue ) %] [% INCLUDE 'catalogue-search-box.inc' %] [% END %] - [% END # /tab_panels %] [% WRAPPER tabs_nav %] [% WRAPPER tab_item tabname= "budgets_search" bt_active= 1 %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/budgets-admin-toolbar.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/budgets-admin-toolbar.inc index 5b18a6e84d..8479b8cf94 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/budgets-admin-toolbar.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/budgets-admin-toolbar.inc @@ -2,66 +2,68 @@ [% IF ( budget_period_id ) %]
    - +
    -
    - [% ELSE %] - + [% END %] -
    diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/calendar.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/calendar.inc index e56932f88f..681e8cc401 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/calendar.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/calendar.inc @@ -3,287 +3,287 @@ [% USE raw %] [% FILTER collapse %] - - -[% Asset.js("js/calendar.js") | $raw %] -[% Asset.js("lib/flatpickr/flatpickr.min.js") | $raw %] -[% Asset.js("lib/flatpickr/shortcut-buttons-flatpickr.min.js") | $raw %] -[% Asset.js("lib/maskito/maskito.core.js") | $raw %] -[% Asset.js("lib/maskito/maskito.kit.js") | $raw %] - + + [% Asset.js("js/calendar.js") | $raw %] + [% Asset.js("lib/flatpickr/flatpickr.min.js") | $raw %] + [% Asset.js("lib/flatpickr/shortcut-buttons-flatpickr.min.js") | $raw %] + [% Asset.js("lib/maskito/maskito.core.js") | $raw %] + [% Asset.js("lib/maskito/maskito.kit.js") | $raw %] + + [% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/cat-menu.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/cat-menu.inc index 90cbd56bf2..fb932fec26 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/cat-menu.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/cat-menu.inc @@ -1,133 +1,131 @@ [% USE Koha %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/cat-toolbar.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/cat-toolbar.inc index d847c33899..2b033e40f6 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/cat-toolbar.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/cat-toolbar.inc @@ -6,185 +6,191 @@ [%# biblionumber: FIXME what about using biblio.id? %]
    - -[% IF ( CAN_user_editcatalogue_edit_catalogue || CAN_user_editcatalogue_edit_items || CAN_user_serials_create_subscription || Koha.Preference('CatalogConcerns') ) %] -
    - - -
    -[% END %] - -[% IF ( CAN_user_editcatalogue_edit_catalogue || CAN_user_editcatalogue_edit_items || CAN_user_tools_items_batchmod || CAN_user_tools_items_batchdel ) or ( frameworkcode == 'FA' and CAN_user_editcatalogue_fast_cataloging ) %] -
    - - +
    + [% END %] [% IF (Koha.Preference("intranetbookbag")) %] @@ -207,9 +213,7 @@ [% IF Koha.Preference('virtualshelves') %]
    - +
    [% END # /IF virtualshelves %] - + -[% IF ( CAN_user_reserveforothers ) %] - [% SET items = biblio.items %] - [% IF Context.Scalar(Context.Scalar(items, "filter_by_for_hold"), "count") %] - [% IF ( holdfor ) %] - - [% ELSE %] - + [% IF ( CAN_user_reserveforothers ) %] + [% SET items = biblio.items %] + [% IF Context.Scalar(Context.Scalar(items, "filter_by_for_hold"), "count") %] + [% IF ( holdfor ) %] + + [% ELSE %] + + [% END %] [% END %] [% END %] -[% END %] -[% IF ( CAN_user_circulate_manage_bookings && biblio.items.filter_by_bookable.count ) %] -
    -[% END %] - -[% IF Koha.Preference('ArticleRequests') %] - -[% END %] - -[% IF ( CAN_user_acquisition_order_manage ) %] - [% IF ( searchtoorder_basketno && searchtoorder_vendorid ) %] - + [% IF ( CAN_user_circulate_manage_bookings && biblio.items.filter_by_bookable.count ) %] +
    [% END %] -[% END %] -[% FOREACH p IN plugins %] - [% p.intranet_catalog_biblio_enhancements_toolbar_button | $raw %] -[% END %] + [% IF Koha.Preference('ArticleRequests') %] + + [% END %] + [% IF ( CAN_user_acquisition_order_manage ) %] + [% IF ( searchtoorder_basketno && searchtoorder_vendorid ) %] + + [% END %] + [% END %] + + [% FOREACH p IN plugins %] + [% p.intranet_catalog_biblio_enhancements_toolbar_button | $raw %] + [% END %]
    - - @@ -38,10 +38,16 @@ Charge Fine Price - Renew

    select all | none

    - Check in

    select all | none

    + Renew

    select all | none

    + Check in

    select all | none

    Return claims - Export

    select all | none

    + Export

    select all | none

    [% INCLUDE 'checkouts-table-footer.inc' %] @@ -88,8 +94,9 @@ [% END %] [% END %] - - + + + diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/circ-menu.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/circ-menu.inc index 592d2b2704..982428466d 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/circ-menu.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/circ-menu.inc @@ -26,9 +26,9 @@ [% IF Koha.Preference('showLastPatron') %] - - - + + + [% END %]
    @@ -39,7 +39,9 @@ [% IF ( CAN_user_tools_batch_upload_patron_images ) %] [% END %] @@ -48,12 +50,15 @@ [% IF ( CAN_user_tools_batch_upload_patron_images ) %] [% END %] [% END # /IF patron.image %] -
    + + [% END # /IF patronimages %]
      @@ -79,7 +84,7 @@ [% END %] [% END %] - [% END # /IF phones %] + [% END # /IF phones %] [% IF ( patron.email ) %]
    • No date of birth stored.
    • [% END %] - [% END # /IF HidePersonalPatronDetailOnCirculation %] [% IF Koha.Preference('ExtendedPatronAttributes') %] [% FOREACH extendedattribute IN patron.extended_attributes %] - [% IF ( extendedattribute.type.display_checkout ) %] [%# FIXME We should filter in the line above %] + [% IF ( extendedattribute.type.display_checkout ) %] + [%# FIXME We should filter in the line above %] [% IF ( extendedattribute.attribute.defined ) %]
    • [% extendedattribute.type.description | html %]: @@ -127,21 +132,16 @@ [% ELSE %] [% extendedattribute.description | html %] [% END %] -
    • + + [% END %] [% END # /IF display_checkout %] [% END # /FOREACH extendedattribute %] [% END # /IF ExtendedPatronAttributes %] -
    • - Category: [% patron.category.description | html %] ([% patron.categorycode | html %]) -
    • -
    • - Home library: [% Branches.GetName( patron.branchcode ) | html %] -
    • -
    • - Borrowernumber: [% patron.borrowernumber | html %] -
    • +
    • Category: [% patron.category.description | html %] ([% patron.categorycode | html %])
    • +
    • Home library: [% Branches.GetName( patron.branchcode ) | html %]
    • +
    • Borrowernumber: [% patron.borrowernumber | html %]
    • Updated on [% patron.updated_on | $KohaDates with_hours => 1 %]
    • @@ -152,10 +152,12 @@ [% END %] [% END %] -
    +
+ - + + + + + + [% IF ( patron.image ) %]
@@ -300,10 +307,13 @@ -
-
+ + + + [% END %] - + +
Take patron photo
@@ -320,13 +330,14 @@
-
+ +
@@ -335,8 +346,10 @@ - - + + + + + + [% ELSE %]

The patron must have a card number before a patron photo can be uploaded.

[% END # /IF patron.cardnumber %] - + + - - - + + + + + + [% END # /IF patronimages %] - [% END # /IF patron.borrowernumber %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/circ-nav.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/circ-nav.inc index 86ca5d18ce..d2b9d245f7 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/circ-nav.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/circ-nav.inc @@ -4,132 +4,131 @@ diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/circ-search.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/circ-search.inc index 844cdfd43d..8a965b37c1 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/circ-search.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/circ-search.inc @@ -12,7 +12,6 @@ [% IF ( CAN_user_catalogue ) %] [% INCLUDE 'catalogue-search-box.inc' %] [% END %] - [% END # /tab_panels %] [% WRAPPER tabs_nav %] [% IF ( CAN_user_circulate_circulate_remaining_permissions ) %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/cities-admin-search.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/cities-admin-search.inc index 42aa472a98..babbdd2242 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/cities-admin-search.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/cities-admin-search.inc @@ -24,7 +24,6 @@ [% IF ( CAN_user_catalogue ) %] [% INCLUDE 'catalogue-search-box.inc' %] [% END %] - [% END # /tab_panels %] [% WRAPPER tabs_nav %] [% WRAPPER tab_item tabname= "city_search" bt_active= 1 %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/clubs-table.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/clubs-table.inc index 46fa2b3d4f..4dfef37c03 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/clubs-table.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/clubs-table.inc @@ -72,46 +72,32 @@ [% c.date_end | $KohaDates %] [% END %] - - [% c.club_enrollments.count | html %] - + [% c.club_enrollments.count | html %] [% UNLESS destination == 'holds' %]
- - Actions - + Actions @@ -121,4 +107,5 @@ [% END %] - + + diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/columns_settings.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/columns_settings.inc index 7015e5f0fd..0ff7305c5a 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/columns_settings.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/columns_settings.inc @@ -2,350 +2,349 @@ [% USE Koha %] [% USE TablesSettings %] - diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/contracts-admin-search.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/contracts-admin-search.inc index 839da940c4..cfe82e3ab8 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/contracts-admin-search.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/contracts-admin-search.inc @@ -11,7 +11,7 @@
- +
diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/country-list.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/country-list.inc index 404a1d25e2..4c2f01424d 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/country-list.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/country-list.inc @@ -1,198 +1,31 @@ [%~ country_strings = BLOCK ~%] [%~ t("Afghanistan") | html ~%], - [%~ t("Albania") | html ~%], - [%~ t("Algeria") | html ~%], - [%~ t("Andorra") | html ~%], - [%~ t("Angola") | html ~%], - [%~ t("Antigua & Deps") | html ~%], - [%~ t("Argentina") | html ~%], - [%~ t("Armenia") | html ~%], - [%~ t("Australia") | html ~%], - [%~ t("Austria") | html ~%], - [%~ t("Azerbaijan") | html ~%], - [%~ t("Bahamas") | html ~%], - [%~ t("Bahrain") | html ~%], - [%~ t("Bangladesh") | html ~%], - [%~ t("Barbados") | html ~%], - [%~ t("Belarus") | html ~%], - [%~ t("Belgium") | html ~%], - [%~ t("Belize") | html ~%], - [%~ t("Benin") | html ~%], - [%~ t("Bhutan") | html ~%], - [%~ t("Bolivia") | html ~%], - [%~ t("Bosnia Herz.") | html ~%], - [%~ t("Botswana") | html ~%], - [%~ t("Brazil") | html ~%], - [%~ t("Brunei") | html ~%], - [%~ t("Bulgaria") | html ~%], - [%~ t("Burkina") | html ~%], - [%~ t("Burundi") | html ~%], - [%~ t("Cambodia") | html ~%], - [%~ t("Cameroon") | html ~%], - [%~ t("Canada") | html ~%], - [%~ t("Cape Verde") | html ~%], - [%~ t("Centr. Afr. Rep") | html ~%], - [%~ t("Chad") | html ~%], - [%~ t("Chile") | html ~%], - [%~ t("China") | html ~%], - [%~ t("Colombia") | html ~%], - [%~ t("Comoros") | html ~%], - [%~ t("Congo") | html ~%], - [%~ t("Costa Rica") | html ~%], - [%~ t("Croatia") | html ~%], - [%~ t("Cuba") | html ~%], - [%~ t("Cyprus") | html ~%], - [%~ t("Czech Republic") | html ~%], - [%~ t("Denmark") | html ~%], - [%~ t("Djibouti") | html ~%], - [%~ t("Dominica") | html ~%], - [%~ t("Dominican Rep.") | html ~%], - [%~ t("East Timor") | html ~%], - [%~ t("Ecuador") | html ~%], - [%~ t("Egypt") | html ~%], - [%~ t("El Salvador") | html ~%], - [%~ t("Equator. Guinea") | html ~%], - [%~ t("Eritrea") | html ~%], - [%~ t("Estonia") | html ~%], - [%~ t("Ethiopia") | html ~%], - [%~ t("Fiji") | html ~%], - [%~ t("Finland") | html ~%], - [%~ t("France") | html ~%], - [%~ t("Gabon") | html ~%], - [%~ t("Gambia") | html ~%], - [%~ t("Georgia") | html ~%], - [%~ t("Germany") | html ~%], - [%~ t("Ghana") | html ~%], - [%~ t("Greece") | html ~%], - [%~ t("Grenada") | html ~%], - [%~ t("Guatemala") | html ~%], - [%~ t("Guinea") | html ~%], - [%~ t("Guinea-Bissau") | html ~%], - [%~ t("Guyana") | html ~%], - [%~ t("Haiti") | html ~%], - [%~ t("Honduras") | html ~%], - [%~ t("Hungary") | html ~%], - [%~ t("Iceland") | html ~%], - [%~ t("India") | html ~%], - [%~ t("Indonesia") | html ~%], - [%~ t("Iran") | html ~%], - [%~ t("Iraq") | html ~%], - [%~ t("Ireland") | html ~%], - [%~ t("Israel") | html ~%], - [%~ t("Italy") | html ~%], - [%~ t("Ivory Coast") | html ~%], - [%~ t("Jamaica") | html ~%], - [%~ t("Japan") | html ~%], - [%~ t("Jordan") | html ~%], - [%~ t("Kazakhstan") | html ~%], - [%~ t("Kenya") | html ~%], - [%~ t("Kiribati") | html ~%], - [%~ t("Korea North") | html ~%], - [%~ t("Korea South") | html ~%], - [%~ t("Kosovo") | html ~%], - [%~ t("Kuwait") | html ~%], - [%~ t("Kyrgyzstan") | html ~%], - [%~ t("Laos") | html ~%], - [%~ t("Latvia") | html ~%], - [%~ t("Lebanon") | html ~%], - [%~ t("Lesotho") | html ~%], - [%~ t("Liberia") | html ~%], - [%~ t("Libya") | html ~%], - [%~ t("Liechtenstein") | html ~%], - [%~ t("Lithuania") | html ~%], - [%~ t("Luxembourg") | html ~%], - [%~ t("Macedonia") | html ~%], - [%~ t("Madagascar") | html ~%], - [%~ t("Malawi") | html ~%], - [%~ t("Malaysia") | html ~%], - [%~ t("Maldives") | html ~%], - [%~ t("Mali") | html ~%], - [%~ t("Malta") | html ~%], - [%~ t("Marshall Isl.") | html ~%], - [%~ t("Mauritania") | html ~%], - [%~ t("Mauritius") | html ~%], - [%~ t("Mexico") | html ~%], - [%~ t("Micronesia") | html ~%], - [%~ t("Moldova") | html ~%], - [%~ t("Monaco") | html ~%], - [%~ t("Mongolia") | html ~%], - [%~ t("Montenegro") | html ~%], - [%~ t("Morocco") | html ~%], - [%~ t("Mozambique") | html ~%], - [%~ t("Myanmar") | html ~%], - [%~ t("Namibia") | html ~%], - [%~ t("Nauru") | html ~%], - [%~ t("Nepal") | html ~%], - [%~ t("Netherlands") | html ~%], - [%~ t("New Zealand") | html ~%], - [%~ t("Nicaragua") | html ~%], - [%~ t("Niger") | html ~%], - [%~ t("Nigeria") | html ~%], - [%~ t("Norway") | html ~%], - [%~ t("Oman") | html ~%], - [%~ t("Pakistan") | html ~%], - [%~ t("Palau") | html ~%], - [%~ t("Panama") | html ~%], - [%~ t("Papua N. Guinea") | html ~%], - [%~ t("Paraguay") | html ~%], - [%~ t("Peru") | html ~%], - [%~ t("Philippines") | html ~%], - [%~ t("Poland") | html ~%], - [%~ t("Portugal") | html ~%], - [%~ t("Qatar") | html ~%], - [%~ t("Romania") | html ~%], - [%~ t("Russian Fed.") | html ~%], - [%~ t("Rwanda") | html ~%], - [%~ t("St Kitts & Nev.") | html ~%], - [%~ t("St Lucia") | html ~%], - [%~ t("Saint Vincent") | html ~%], - [%~ t("Samoa") | html ~%], - [%~ t("San Marino") | html ~%], - [%~ t("Sao Tome") | html ~%], - [%~ t("Saudi Arabia") | html ~%], - [%~ t("Senegal") | html ~%], - [%~ t("Serbia") | html ~%], - [%~ t("Seychelles") | html ~%], - [%~ t("Sierra Leone") | html ~%], - [%~ t("Singapore") | html ~%], - [%~ t("Slovakia") | html ~%], - [%~ t("Slovenia") | html ~%], - [%~ t("Solomon Islands") | html ~%], - [%~ t("Somalia") | html ~%], - [%~ t("South Africa") | html ~%], - [%~ t("Spain") | html ~%], - [%~ t("Sri Lanka") | html ~%], - [%~ t("Sudan") | html ~%], - [%~ t("Suriname") | html ~%], - [%~ t("Swaziland") | html ~%], - [%~ t("Sweden") | html ~%], - [%~ t("Switzerland") | html ~%], - [%~ t("Syria") | html ~%], - [%~ t("Taiwan") | html ~%], - [%~ t("Tajikistan") | html ~%], - [%~ t("Tanzania") | html ~%], - [%~ t("Thailand") | html ~%], - [%~ t("Togo") | html ~%], - [%~ t("Tonga") | html ~%], - [%~ t("Trinidad & Tob.") | html ~%], - [%~ t("Tunisia") | html ~%], - [%~ t("Turkey") | html ~%], - [%~ t("Turkmenistan") | html ~%], - [%~ t("Tuvalu") | html ~%], - [%~ t("Uganda") | html ~%], - [%~ t("Ukraine") | html ~%], - [%~ t("UAE") | html ~%], - [%~ t("United Kingdom") | html ~%], - [%~ t("USA") | html ~%], - [%~ t("Uruguay") | html ~%], - [%~ t("Uzbekistan") | html ~%], - [%~ t("Vanuatu") | html ~%], - [%~ t("Vatican City") | html ~%], - [%~ t("Venezuela") | html ~%], - [%~ t("Vietnam") | html ~%], - [%~ t("Yemen") | html ~%], - [%~ t("Zambia") | html ~%], - [%~ t("Zimbabwe") | html ~%] + [%~ t("Albania") | html ~%], [%~ t("Algeria") | html ~%], [%~ t("Andorra") | html ~%], [%~ t("Angola") | html ~%], [%~ t("Antigua & Deps") | html ~%], [%~ t("Argentina") | html ~%], [%~ t("Armenia") | html ~%], + [%~ t("Australia") | html ~%], [%~ t("Austria") | html ~%], [%~ t("Azerbaijan") | html ~%], [%~ t("Bahamas") | html ~%], [%~ t("Bahrain") | html ~%], [%~ t("Bangladesh") | html ~%], [%~ t("Barbados") | html ~%], + [%~ t("Belarus") | html ~%], [%~ t("Belgium") | html ~%], [%~ t("Belize") | html ~%], [%~ t("Benin") | html ~%], [%~ t("Bhutan") | html ~%], [%~ t("Bolivia") | html ~%], [%~ t("Bosnia Herz.") | html ~%], [%~ t("Botswana") | html ~%], + [%~ t("Brazil") | html ~%], [%~ t("Brunei") | html ~%], [%~ t("Bulgaria") | html ~%], [%~ t("Burkina") | html ~%], [%~ t("Burundi") | html ~%], [%~ t("Cambodia") | html ~%], [%~ t("Cameroon") | html ~%], [%~ t("Canada") | html ~%], + [%~ t("Cape Verde") | html ~%], [%~ t("Centr. Afr. Rep") | html ~%], [%~ t("Chad") | html ~%], [%~ t("Chile") | html ~%], [%~ t("China") | html ~%], [%~ t("Colombia") | html ~%], [%~ t("Comoros") | html ~%], [%~ t("Congo") | html ~%], + [%~ t("Costa Rica") | html ~%], [%~ t("Croatia") | html ~%], [%~ t("Cuba") | html ~%], [%~ t("Cyprus") | html ~%], [%~ t("Czech Republic") | html ~%], [%~ t("Denmark") | html ~%], [%~ t("Djibouti") | html ~%], + [%~ t("Dominica") | html ~%], [%~ t("Dominican Rep.") | html ~%], [%~ t("East Timor") | html ~%], [%~ t("Ecuador") | html ~%], [%~ t("Egypt") | html ~%], [%~ t("El Salvador") | html ~%], [%~ t("Equator. Guinea") | html ~%], + [%~ t("Eritrea") | html ~%], [%~ t("Estonia") | html ~%], [%~ t("Ethiopia") | html ~%], [%~ t("Fiji") | html ~%], [%~ t("Finland") | html ~%], [%~ t("France") | html ~%], [%~ t("Gabon") | html ~%], [%~ t("Gambia") | html ~%], + [%~ t("Georgia") | html ~%], [%~ t("Germany") | html ~%], [%~ t("Ghana") | html ~%], [%~ t("Greece") | html ~%], [%~ t("Grenada") | html ~%], [%~ t("Guatemala") | html ~%], [%~ t("Guinea") | html ~%], [%~ t("Guinea-Bissau") | html ~%], + [%~ t("Guyana") | html ~%], [%~ t("Haiti") | html ~%], [%~ t("Honduras") | html ~%], [%~ t("Hungary") | html ~%], [%~ t("Iceland") | html ~%], [%~ t("India") | html ~%], [%~ t("Indonesia") | html ~%], [%~ t("Iran") | html ~%], + [%~ t("Iraq") | html ~%], [%~ t("Ireland") | html ~%], [%~ t("Israel") | html ~%], [%~ t("Italy") | html ~%], [%~ t("Ivory Coast") | html ~%], [%~ t("Jamaica") | html ~%], [%~ t("Japan") | html ~%], [%~ t("Jordan") | html ~%], + [%~ t("Kazakhstan") | html ~%], [%~ t("Kenya") | html ~%], [%~ t("Kiribati") | html ~%], [%~ t("Korea North") | html ~%], [%~ t("Korea South") | html ~%], [%~ t("Kosovo") | html ~%], [%~ t("Kuwait") | html ~%], + [%~ t("Kyrgyzstan") | html ~%], [%~ t("Laos") | html ~%], [%~ t("Latvia") | html ~%], [%~ t("Lebanon") | html ~%], [%~ t("Lesotho") | html ~%], [%~ t("Liberia") | html ~%], [%~ t("Libya") | html ~%], [%~ t("Liechtenstein") | html ~%], + [%~ t("Lithuania") | html ~%], [%~ t("Luxembourg") | html ~%], [%~ t("Macedonia") | html ~%], [%~ t("Madagascar") | html ~%], [%~ t("Malawi") | html ~%], [%~ t("Malaysia") | html ~%], [%~ t("Maldives") | html ~%], + [%~ t("Mali") | html ~%], [%~ t("Malta") | html ~%], [%~ t("Marshall Isl.") | html ~%], [%~ t("Mauritania") | html ~%], [%~ t("Mauritius") | html ~%], [%~ t("Mexico") | html ~%], [%~ t("Micronesia") | html ~%], + [%~ t("Moldova") | html ~%], [%~ t("Monaco") | html ~%], [%~ t("Mongolia") | html ~%], [%~ t("Montenegro") | html ~%], [%~ t("Morocco") | html ~%], [%~ t("Mozambique") | html ~%], [%~ t("Myanmar") | html ~%], + [%~ t("Namibia") | html ~%], [%~ t("Nauru") | html ~%], [%~ t("Nepal") | html ~%], [%~ t("Netherlands") | html ~%], [%~ t("New Zealand") | html ~%], [%~ t("Nicaragua") | html ~%], [%~ t("Niger") | html ~%], [%~ t("Nigeria") | html ~%], + [%~ t("Norway") | html ~%], [%~ t("Oman") | html ~%], [%~ t("Pakistan") | html ~%], [%~ t("Palau") | html ~%], [%~ t("Panama") | html ~%], [%~ t("Papua N. Guinea") | html ~%], [%~ t("Paraguay") | html ~%], [%~ t("Peru") | html ~%], + [%~ t("Philippines") | html ~%], [%~ t("Poland") | html ~%], [%~ t("Portugal") | html ~%], [%~ t("Qatar") | html ~%], [%~ t("Romania") | html ~%], [%~ t("Russian Fed.") | html ~%], [%~ t("Rwanda") | html ~%], + [%~ t("St Kitts & Nev.") | html ~%], [%~ t("St Lucia") | html ~%], [%~ t("Saint Vincent") | html ~%], [%~ t("Samoa") | html ~%], [%~ t("San Marino") | html ~%], [%~ t("Sao Tome") | html ~%], [%~ t("Saudi Arabia") | html ~%], + [%~ t("Senegal") | html ~%], [%~ t("Serbia") | html ~%], [%~ t("Seychelles") | html ~%], [%~ t("Sierra Leone") | html ~%], [%~ t("Singapore") | html ~%], [%~ t("Slovakia") | html ~%], [%~ t("Slovenia") | html ~%], + [%~ t("Solomon Islands") | html ~%], [%~ t("Somalia") | html ~%], [%~ t("South Africa") | html ~%], [%~ t("Spain") | html ~%], [%~ t("Sri Lanka") | html ~%], [%~ t("Sudan") | html ~%], [%~ t("Suriname") | html ~%], + [%~ t("Swaziland") | html ~%], [%~ t("Sweden") | html ~%], [%~ t("Switzerland") | html ~%], [%~ t("Syria") | html ~%], [%~ t("Taiwan") | html ~%], [%~ t("Tajikistan") | html ~%], [%~ t("Tanzania") | html ~%], + [%~ t("Thailand") | html ~%], [%~ t("Togo") | html ~%], [%~ t("Tonga") | html ~%], [%~ t("Trinidad & Tob.") | html ~%], [%~ t("Tunisia") | html ~%], [%~ t("Turkey") | html ~%], [%~ t("Turkmenistan") | html ~%], + [%~ t("Tuvalu") | html ~%], [%~ t("Uganda") | html ~%], [%~ t("Ukraine") | html ~%], [%~ t("UAE") | html ~%], [%~ t("United Kingdom") | html ~%], [%~ t("USA") | html ~%], [%~ t("Uruguay") | html ~%], [%~ t("Uzbekistan") | html ~%], + [%~ t("Vanuatu") | html ~%], [%~ t("Vatican City") | html ~%], [%~ t("Venezuela") | html ~%], [%~ t("Vietnam") | html ~%], [%~ t("Yemen") | html ~%], [%~ t("Zambia") | html ~%], [%~ t("Zimbabwe") | html ~%] [%~ END ~%] diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/currencies-admin-search.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/currencies-admin-search.inc index 55642a78ea..64338daa2c 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/currencies-admin-search.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/currencies-admin-search.inc @@ -24,7 +24,6 @@ [% IF ( CAN_user_catalogue ) %] [% INCLUDE 'catalogue-search-box.inc' %] [% END %] - [% END # /tab_panels %] [% WRAPPER tabs_nav %] [% WRAPPER tab_item tabname= "currency_search" bt_active= 1 %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/delimiter_text.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/delimiter_text.inc index 0d4eabaa24..cb1c486f6e 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/delimiter_text.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/delimiter_text.inc @@ -1,8 +1,14 @@ [% SWITCH Koha.Preference('CSVDelimiter') %] - [% CASE '#' %]Pound (#) separated text (.csv) - [% CASE ',' %]Comma separated text (.csv) - [% CASE '/' %]Slash separated text (.csv) - [% CASE ';' %]Semicolon separated text (.csv) - [% CASE '\\' %]Backslash separated text (.csv) - [% CASE 'tabulation' %]Tab separated text (.csv) +[% CASE '#' %] + Pound (#) separated text (.csv) +[% CASE ',' %] + Comma separated text (.csv) +[% CASE '/' %] + Slash separated text (.csv) +[% CASE ';' %] + Semicolon separated text (.csv) +[% CASE '\\' %] + Backslash separated text (.csv) +[% CASE 'tabulation' %] + Tab separated text (.csv) [% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/desks-admin-search.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/desks-admin-search.inc index a58dc24016..e24d5e832c 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/desks-admin-search.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/desks-admin-search.inc @@ -24,23 +24,23 @@ [% IF ( CAN_user_catalogue ) %] [% INCLUDE 'catalogue-search-box.inc' %] [% END %] - [% END # /tab_panels %] [% WRAPPER tabs_nav %] [% END # /tabs_nav %] [% END # /WRAPPER tabs %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/doc-head-close.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/doc-head-close.inc index c1066e9012..adf5a61694 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/doc-head-close.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/doc-head-close.inc @@ -6,11 +6,15 @@ [% PROCESS 'html_helpers.inc' %] - + [% IF logged_in_user %][% END %] [%# Prevent XFS attacks -%] [% UNLESS popup %] - + [% END %] @@ -28,19 +32,17 @@ [% INCLUDE intranetstylesheet.inc %] [% IF ( bidi ) %][% Asset.css("css/right-to-left.css") | $raw %][% END %] - - [% IF lang && lang != 'en' %] [% Asset.js(lang _ '/js/locale_data.js') | $raw %] [% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/doc-head-open.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/doc-head-open.inc index 18b3fe39c1..6a3ab19fb3 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/doc-head-open.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/doc-head-open.inc @@ -31,5 +31,7 @@ [% END %] -[% IF ( bidi ) %][% ELSE %][% END %] +[% IF ( bidi ) %][% ELSE %][% END %] + + diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/facets.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/facets.inc index 608c4518a3..61846cf124 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/facets.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/facets.inc @@ -29,25 +29,26 @@
  • Availability [% IF ( related ) %] -
  • - (related searches: [% FOREACH relate IN related %][% relate.related_search | html %][% END %]) -
  • +
  • (related searches: [% FOREACH relate IN related %][% relate.related_search | html %][% END %])
  • [% END %] - + + [% FOREACH facets_loo IN facets_loop %] [% IF facets_loo.facets.size > 0 %] @@ -129,6 +130,7 @@ [% END # /IF facets_loo.facets.size %] [% END # /FOREACH facets_loo %] - + + [% END # /IF ( facets_loop ) %] [% END # /IF ( opacfacets ) %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/filter-orders.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/filter-orders.inc index 6b52ff3410..c64837336f 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/filter-orders.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/filter-orders.inc @@ -26,14 +26,15 @@
  • - [% IF Koha.Preference('marcflavour') == 'UNIMARC' %] -
  • - [% END %] + [% IF Koha.Preference('marcflavour') == 'UNIMARC' %] +
  • + [% END %]
  • -
  • +
  • @@ -53,10 +54,10 @@
  • - [% INCLUDE 'additional-fields-entry.inc' available=available_additional_fields values=additional_field_filters wrap_fieldset=0 search_form=1 %] + [% INCLUDE 'additional-fields-entry.inc' available=available_additional_fields values=additional_field_filters wrap_fieldset=0 search_form=1 %]
  • - - + +
  • @@ -125,21 +126,23 @@ [% FOREACH bp_loo IN bp_loop %] - [% FOREACH h_loo IN bp_loo.hierarchy %] - - [% END %] + [% FOREACH h_loo IN bp_loo.hierarchy %] + + [% END %] [% END %] -
  • +
  • [% INCLUDE 'date-format.inc' %]
  • -
  • +
  • [% INCLUDE 'date-format.inc' %]
  • diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/format_price.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/format_price.inc index 6790bc8d59..d58325a311 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/format_price.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/format_price.inc @@ -43,6 +43,5 @@ value = value.replace(thousands_sep, '').replace(decimal_point, '.').replace(new RegExp('[^\\d.]', 'g'), ''); return Number(value).toFixed(decimal_digits); } - diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/guided-reports-view.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/guided-reports-view.inc index a04f416812..c92bee77c0 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/guided-reports-view.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/guided-reports-view.inc @@ -1,24 +1,23 @@ [% USE Koha %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/header.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/header.inc index 66b8467b8e..15e1f17ce5 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/header.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/header.inc @@ -9,18 +9,28 @@ [% END %] [% content | $raw %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/holds_table.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/holds_table.inc index 1a5c1aaad4..c2d717a9fe 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/holds_table.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/holds_table.inc @@ -8,7 +8,7 @@ - + [% IF ( CAN_user_reserveforothers_modify_holds_priority ) %] @@ -38,18 +38,18 @@ [% FOREACH hold IN holds %] - [%- IF !hold.found && first_priority == 0 -%] - [%- first_priority = hold.priority -%] - [%- found_holds = loop.index() -%] - [%- END -%] - [%- IF Koha.Preference('HoldsSplitQueueNumbering') == 'actual' -%] - [%- this_priority = hold.priority -%] - [%- ELSE -%] - [%- this_priority = loop.count() - found_holds -%] - [%- END -%] + [%- IF !hold.found && first_priority == 0 -%] + [%- first_priority = hold.priority -%] + [%- found_holds = loop.index() -%] + [%- END -%] + [%- IF Koha.Preference('HoldsSplitQueueNumbering') == 'actual' -%] + [%- this_priority = hold.priority -%] + [%- ELSE -%] + [%- this_priority = loop.count() - found_holds -%] + [%- END -%] [% SET tr_class = hold.suspend ? 'suspend' : '' %] - + [%- IF ( CAN_user_reserveforothers_modify_holds_priority ) -%] - [%- UNLESS hold.found -%] + [%- UNLESS hold.found -%] [%- SET prev_priority = loop.prev.priority -%] [%- SET next_priority = loop.next.priority -%] - [%- ELSE -%] - - [%- END -%] + [%- ELSE -%] + + [%- END -%] [%- END -%] - + @@ -182,12 +228,14 @@ [%- ELSE -%] - + @@ -214,25 +262,41 @@ [%- END -%] [%- END -%] [%- IF hold.non_priority -%] -
    Non priority hold +
    Non priority hold [%- END -%] [%- IF ( CAN_user_reserveforothers_modify_holds_priority ) -%] - [%- UNLESS hold.found -%] + [%- UNLESS hold.found -%] - [%- ELSE -%] - - [%- END -%] + [%- ELSE -%] + + [%- END -%] [%- END -%] [% IF ( hold.intransit || hold.atdestination ) %] - + [% ELSE %] [% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/html-customization-help.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/html-customization-help.inc index 5b420abd76..bc0bfabe7c 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/html-customization-help.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/html-customization-help.inc @@ -1,20 +1,12 @@ -
    - This content will be shown to an OPAC user before they can place an article request. -
    +
    This content will be shown to an OPAC user before they can place an article request.
    -
    - Include this content on the form shown in the OPAC when the user submits a catalog concern report. -
    +
    Include this content on the form shown in the OPAC when the user submits a catalog concern report.
    -
    - Prefill the OPAC catalog concern form with this content as a template for the user's submission. -
    +
    Prefill the OPAC catalog concern form with this content as a template for the user's submission.
    -
    - Include this content in the cookie consent footer which is displayed in the OPAC when the CookieConsent system preference is enabled. -
    +
    Include this content in the cookie consent footer which is displayed in the OPAC when the CookieConsent system preference is enabled.
    -
    +
    Include this content in the popup message which is displayed in the OPAC when the CookieConsent system preference is enabled and the user clicks the "Your cookies" menu item in the header.
    @@ -22,118 +14,62 @@ Adding content to this region will enable the copyright clearance stage in request creation. The content will appear on the OPAC during the process of placing an ILL request.
    -
    - Include this content in its own section on the main page of the staff interface -
    +
    Include this content in its own section on the main page of the staff interface
    -
    - Include this content in the footer of all pages in the OPAC. -
    +
    Include this content in the footer of all pages in the OPAC.
    -
    - Replace the search box at the top of OPAC pages with this content. -
    +
    Replace the search box at the top of OPAC pages with this content.
    -
    - Include this content in the header of all pages in the OPAC. -
    +
    Include this content in the header of all pages in the OPAC.
    -
    - Include this content on the library information page in the OPAC. -
    +
    Include this content on the library information page in the OPAC.
    -
    - Show this content on the OPAC login form when a patron is not logged in. -
    +
    Show this content on the OPAC login form when a patron is not logged in.
    -
    - Show this content on the OPAC when the OpacMaintenance system preference is enabled. -
    +
    Show this content on the OPAC when the OpacMaintenance system preference is enabled.
    -
    - Show this content in its own column on the main page of the OPAC. -
    +
    Show this content in its own column on the main page of the OPAC.
    -
    - Add additional elements to the navigation bar below the simple search form. -
    +
    Add additional elements to the navigation bar below the simple search form.
    -
    - Note to display on the patron summary page. This note only appears if the patron is logged in. -
    +
    Note to display on the patron summary page. This note only appears if the patron is logged in.
    -
    - Show this content on the left hand column of the main page and patron account on the OPAC (generally navigation links). -
    +
    Show this content on the left hand column of the main page and patron account on the OPAC (generally navigation links).
    -
    - Show this content on the left hand column of the main page and patron account on the OPAC, after OpacNav, and before patron account links if available. -
    +
    Show this content on the left hand column of the main page and patron account on the OPAC, after OpacNav, and before patron account links if available.
    -
    - Show this content in the right hand column of the main page under the main login form. -
    +
    Show this content in the right hand column of the main page under the main login form.
    -
    - Show this content under the facets in OPAC search results. -
    +
    Show this content under the facets in OPAC search results.
    -
    - Show this content at the top of the purchase suggestion form in the OPAC. -
    +
    Show this content at the top of the purchase suggestion form in the OPAC.
    Display the following message on the redirect page for suppressed bibliographic records. Depends on the system preferences OpacSuppression and OpacSuppressionRedirect.
    -
    - Show the following content on the patron self-registration confirmation page. -
    +
    Show the following content on the patron self-registration confirmation page.
    -
    - Include the following note on all routing list slips. -
    +
    Include the following note on all routing list slips.
    -
    - Show this content on the web-based self checkout screen. -
    +
    Show this content on the web-based self checkout screen.
    -
    - Show this content on the Help page of the web-based self checkout system. -
    +
    Show this content on the Help page of the web-based self checkout system.
    -
    - Show this content on the self check-in screen. -
    +
    Show this content on the self check-in screen.
    -
    - Show this content on the acquisitions home page in the staff interface. -
    +
    Show this content on the acquisitions home page in the staff interface.
    -
    - Show this content on the authorities home page in the staff interface. -
    +
    Show this content on the authorities home page in the staff interface.
    -
    - Show this content on the cataloging home page in the staff interface. -
    +
    Show this content on the cataloging home page in the staff interface.
    -
    - Show this content on the lists home page in the staff interface. -
    +
    Show this content on the lists home page in the staff interface.
    -
    - Show this content on the staff interface login page. -
    +
    Show this content on the staff interface login page.
    -
    - Show this content on the patrons home page in the staff interface. -
    +
    Show this content on the patrons home page in the staff interface.
    -
    - Show this content on the point of sale home page in the staff interface. -
    +
    Show this content on the point of sale home page in the staff interface.
    -
    - Show this content on the serials home page in the staff interface. -
    +
    Show this content on the serials home page in the staff interface.
    diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/html_helpers.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/html_helpers.inc index 929a420c35..aa92f7bb61 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/html_helpers.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/html_helpers.inc @@ -4,7 +4,7 @@ [% ELSE %] - [% END%] + [% END %] [% END %] [% END %] @@ -12,11 +12,11 @@ [% FOREACH d IN desks %] [% IF d.branchcode == branch %] - [% IF selected == d.desk_id || ( selected == '' && loop.first ) %] - - [% ELSE %] - - [% END %] + [% IF selected == d.desk_id || ( selected == '' && loop.first ) %] + + [% ELSE %] + + [% END %] [% ELSE %] [% END %] @@ -27,12 +27,12 @@ [% FOREACH r IN registers %] [% IF r.branch == Branches.GetLoggedInBranchcode %] [% IF r.selected %] - + [% ELSE %] - - [% END%] + + [% END %] [% ELSE %] - + [% END %] [% END %] [% END %] @@ -60,13 +60,9 @@ [% BLOCK options_for_item_types %] [% FOREACH itemtype IN itemtypes %] [% IF itemtype.itemtype == selected_itemtype %] - + [% ELSE %] - + [% END %] [% END %] [% END %] @@ -98,12 +94,12 @@ [% IF ( subfield.mandatory ) %] [% ELSE %] - + [% END %] [% SET mv = subfield.marc_value %] [% IF ( mv.type == 'hidden' ) %] - + [% ELSIF ( mv.type == 'select' ) %] [% SET select_readonly = '' %] [% SET select_disabled = '' %] @@ -115,77 +111,119 @@ [% SET select_class = 'input_marceditor select2 ' _ kohafield %] [% END %] - + [% SET matched = 0 %] + [% FOREACH aval IN mv.values %] + [% IF aval == mv.default %] + [% SET matched = 1 %] + + [% ELSE %] + [% IF subfield.IS_LOST_AV && Koha.Preference("ClaimReturnedLostValue") && aval == Koha.Preference("ClaimReturnedLostValue") %] + + [% ELSIF subfield.IS_LOST_AV && Koha.Preference("BundleLostValue") && aval == Koha.Preference("BundleLostValue") %] + + [% ELSE %] + + [% END %] [% END %] [% END %] - [% END %] - [% UNLESS matched || ( ( kohafield == 'items.damaged' || kohafield == 'items.itemlost' || kohafield == 'items.withdrawn' || kohafield == 'items.notforloan' ) && mv.default == '0' ) %] - [%# If the current value is not in the authorised list and is not a field where 0 means unset #%] + [% UNLESS matched || ( ( kohafield == 'items.damaged' || kohafield == 'items.itemlost' || kohafield == 'items.withdrawn' || kohafield == 'items.notforloan' ) && mv.default == '0' ) %] + [%# If the current value is not in the authorised list and is not a field where 0 means unset #%] - [% END %] - + [% END %] + [% UNLESS matched || ( ( kohafield == 'items.damaged' || kohafield == 'items.itemlost' || kohafield == 'items.withdrawn' || kohafield == 'items.notforloan' ) && mv.default == '0' ) %] - + [% END %] [% ELSIF ( mv.type == 'text_auth' ) %] [% IF mv.readonly %] - + [% ELSE %] [% SET dopop = "Dopop('/cgi-bin/koha/authorities/auth_finder.pl?authtypecode=\"${mv.authtypecode}\"&index=${mv.id}','${mv.id}')" %] - ... + ... [% END %] [% ELSIF ( mv.type == 'text_plugin' ) %] [% IF mv.readonly %] - + [% ELSE %] [% IF ( mv.nopopup ) %] ... - [% ELSE %] + [% ELSE %] ... [% END %] - [% UNLESS no_plugin %][%# FIXME - from batchMod-edit, jQuery is included at the end of the template and cataloguing plugins are not working in this situation %] + [% UNLESS no_plugin %] + [%# FIXME - from batchMod-edit, jQuery is included at the end of the template and cataloguing plugins are not working in this situation %] [%- mv.javascript | $raw -%] [% END %] [% END %] [% ELSIF ( mv.type == 'text' ) %] [% IF mv.readonly %] - + [% ELSE %] [% END %] [% ELSIF ( mv.type == 'textarea' ) %] [% IF mv.readonly %] - + [% ELSE %] - + [% END %] [% ELSIF ( mv.type == 'date_field' ) %] - + [% ELSIF ( mv.type == 'datetime_field' ) %] - + [% END %] [% IF subfield.kohafield == 'items.more_subfields_xml' %] [% END %] - + [%# We should not need that but all item forms are not rewritten yet %] - + @@ -199,19 +237,27 @@ [% IF add_delete_checkbox %] [% UNLESS ( subfield.mandatory ) %] - + [% ELSE %] Required [% END %] [% ELSE %] - [% IF ( subfield.mandatory ) %] Required - [% ELSIF ( subfield.important ) %] Important + [% IF ( subfield.mandatory ) %] + Required + [% ELSIF ( subfield.important ) %] + Important [% END %] [% END %] [% IF add_regex %] [% IF (mv.type == 'text' || mv.type == 'text_plugin' || mv.type == 'textarea' ) %] - RegEx + RegEx [% END %] [% END %] @@ -222,7 +268,6 @@ [% END %] - [% END %] @@ -230,146 +275,147 @@ [% END %] [% BLOCK items_table_batchmod %] -
    - [% IF display_columns_selection %][%# Needs js/pages/batchMod.js %] - [% IF checkboxes_edit OR checkboxes_delete %] -
    - Select all | Clear all | Clear on loan +
    + [% IF display_columns_selection %] + [%# Needs js/pages/batchMod.js %] + [% IF checkboxes_edit OR checkboxes_delete %] + + [% END %] + +
    +

    + Show/hide columns: + + + + + + + + + + [% FOREACH header IN item_header_loop %] + + + + + [% END %] +

    +
    [% END %] - -
    - -

    - Show/hide columns: - - - - - - - - - - [% FOREACH header IN item_header_loop %] - - - - - [% END %] -

    -
    - [% END %] - [% SET date_fields = [ 'dateaccessioned', 'onloan', 'datelastseen', 'datelastborrowed', 'replacementpricedate' ] %] -
    PriorityChange priority
    @@ -57,68 +57,118 @@ [% IF ( CAN_user_reserveforothers_modify_holds_priority ) %] [% IF Koha.Preference('HoldsSplitQueue') == "nothing" && !hold.found %] [% ELSE %] - + [% END %] [% ELSE %] - + [% hold.priority | html %] [% END %] - + - + - + - + - [% INCLUDE 'patron-title.inc' patron=hold.patron hide_patron_infos_if_needed=1 %] - [% INCLUDE 'patron-title.inc' patron=hold.patron hide_patron_infos_if_needed=1 %] [% hold.notes | html | html_line_break %] [% IF Koha.Preference('AllowHoldDateInFuture') %] @@ -134,7 +184,7 @@ [%- IF ( hold.found ) -%] [%- IF ( hold.atdestination ) -%] - Item waiting at [% hold.wbrname | html %][% IF hold.desk_name %], [% hold.desk_name | html %],[% END %] since [% hold.waiting_date | $KohaDates %] + Item waiting at [% hold.wbrname | html %][% IF hold.desk_name %], [% hold.desk_name | html %],[% END %] since [% hold.waiting_date | $KohaDates %] [%- ELSIF (hold.intransit) -%] Item being transferred to [% hold.wbrname | html %] [%- ELSIF (hold.inprocessing) -%] @@ -146,15 +196,11 @@ [%- IF Koha.Preference('IndependentBranches') && Branches.all().size == 1 -%] [% Branches.GetName(hold.branchcode) | html %] [%- ELSE -%] - - + [%- END -%] [%- END -%] [% IF ( hold.lowestPriority ) %] - + [% ELSE %] - + [% END %] @@ -253,19 +317,45 @@ [% END %] [% IF Koha.Preference('AutoResumeSuspendedHolds') %] - - + + [%- ELSE -%] - + [%- END -%] [%- END -%] [%- END # IF SuspendHoldsIntranet -%] [%- IF ( hold.found ) -%] - [% IF hold.intransit %]Revert transit status[% ELSE %]Revert waiting status[% END %] + [% IF hold.intransit %]Revert transit status[% ELSE %]Revert waiting status[% END %] [%- END -%]
    - - - - [% IF checkboxes_edit OR checkboxes_delete %] - - [% END %] - - - [% FOREACH item_header IN headers %] - [% IF item_header.column_name %] - - [% ELSE %] - - [% END %] - [% END %] - - - - [% FOREACH item IN items %] - [% SET can_be_edited = !item.nomod && !( Koha.Preference('IndependentBranches') && ! logged_in_user && item.homebranch != Branches.GetLoggedInBranchname() ) %] - + [% SET date_fields = [ 'dateaccessioned', 'onloan', 'datelastseen', 'datelastborrowed', 'replacementpricedate' ] %] +
    TitleHolds - [% item_header.header_value | html %] - - [% item_header.header_value | html %] -
    + - - [% IF checkboxes_edit %] - [% UNLESS can_be_edited%] - - [% ELSE %] - - [% END %] - [% ELSIF checkboxes_delete %] - [% UNLESS can_be_edited %] - - [% ELSE %] - [% IF item.safe_to_delete %] - - [% ELSE %] - [% SET messages = item.safe_to_delete.messages %] - [% FOR m IN messages %] - [% SWITCH m.message %] - [% CASE "book_on_loan" %][% SET cannot_delete_reason = t("Item is checked out") %] - [% CASE "not_same_branch" %][% SET cannot_delete_reason = t("Item does not belong to your library") %] - [% CASE "book_reserved" %][% SET cannot_delete_reason = t("Item has a waiting hold") %] - [% CASE "linked_analytics" %][% SET cannot_delete_reason = t("Item has linked analytics") %] - [% CASE "last_item_for_hold" %][% SET cannot_delete_reason = t("Last item for bibliographic record with biblio-level hold on it") %] - [% CASE %][% SET cannot_delete_reason = t("Unknown reason") _ '(' _ m.message _ ')' %] - [% END %] - [% END %] - - - [% END %] - - [% END %] + + [% IF checkboxes_edit OR checkboxes_delete %] + [% END %] - - + + [% FOREACH item_header IN headers %] + [% IF item_header.column_name %] + [% ELSE %] - [% IF item.holds %] - [% SET a_title = tx("Holds on this record: {total_holds}", { total_holds=item.holds }) %] - [% ELSE %] - [% SET a_title = t("No holds on this record") %] - [% END %] - [% END # /IF item.holds %] - - [% IF item.holds %] - [% item.item_holds | html %]/[% item.holds | html %] - [% ELSE %] - [% item.holds | html %] - [% END %] - - - [% FOREACH header IN headers %] - [% SET attribute = header.attribute %] - [% IF header.attribute AND date_fields.grep('^' _ attribute _ '$').size %] - - [% ELSE %] - + [% END %] [% END %] - [% END # /FOREACH items %] - -
    [% item.index + 1 | html %] - - - - - - - - - - - [% IF item.holds %] - [% IF item.item_holds %] - [% SET a_title = tx("Holds on this item: {item_holds} / Total holds on this record: {total_holds}", { item_holds=item.item_holds, total_holds=item.holds }) %] - [% ELSE %] - [% SET a_title = tx("No holds on this item / Total holds on this record: {total_holds}", { total_holds=item.holds }) %] - [% END %] + TitleHolds [% item_header.header_value | html %] [% item.$attribute | $KohaDates %][% item.$attribute | html %] [% item_header.header_value | html %]
    - + + + [% FOREACH item IN items %] + [% SET can_be_edited = !item.nomod && !( Koha.Preference('IndependentBranches') && ! logged_in_user && item.homebranch != Branches.GetLoggedInBranchname() ) %] + + + [% item.index + 1 | html %] + [% IF checkboxes_edit %] + [% UNLESS can_be_edited %] + + + + [% ELSE %] + + + + [% END %] + [% ELSIF checkboxes_delete %] + [% UNLESS can_be_edited %] + + + + [% ELSE %] + [% IF item.safe_to_delete %] + + [% ELSE %] + [% SET messages = item.safe_to_delete.messages %] + [% FOR m IN messages %] + [% SWITCH m.message %] + [% CASE "book_on_loan" %] + [% SET cannot_delete_reason = t("Item is checked out") %] + [% CASE "not_same_branch" %] + [% SET cannot_delete_reason = t("Item does not belong to your library") %] + [% CASE "book_reserved" %] + [% SET cannot_delete_reason = t("Item has a waiting hold") %] + [% CASE "linked_analytics" %] + [% SET cannot_delete_reason = t("Item has linked analytics") %] + [% CASE "last_item_for_hold" %] + [% SET cannot_delete_reason = t("Last item for bibliographic record with biblio-level hold on it") %] + [% CASE %] + [% SET cannot_delete_reason = t("Unknown reason") _ '(' _ m.message _ ')' %] + [% END %] + [% END %] + + + + + [% END %] + [% END %] + [% END %] + + + + + [% IF item.holds %] + [% IF item.item_holds %] + [% SET a_title = tx("Holds on this item: {item_holds} / Total holds on this record: {total_holds}", { item_holds=item.item_holds, total_holds=item.holds }) %] + [% ELSE %] + [% SET a_title = tx("No holds on this item / Total holds on this record: {total_holds}", { total_holds=item.holds }) %] + [% END %] + [% ELSE %] + [% IF item.holds %] + [% SET a_title = tx("Holds on this record: {total_holds}", { total_holds=item.holds }) %] + [% ELSE %] + [% SET a_title = t("No holds on this record") %] + [% END %] + [% END # /IF item.holds %] + + [% IF item.holds %] + [% item.item_holds | html %]/[% item.holds | html %] + [% ELSE %] + [% item.holds | html %] + [% END %] + + + [% FOREACH header IN headers %] + [% SET attribute = header.attribute %] + [% IF header.attribute AND date_fields.grep('^' _ attribute _ '$').size %] + [% item.$attribute | $KohaDates %] + [% ELSE %] + [% item.$attribute | html %] + [% END %] + [% END %] + + [% END # /FOREACH items %] + + + + [% END %] [%# BOOTSTRAP TAB WRAPPER USAGE %] @@ -388,13 +434,9 @@ [% BLOCK tabs %] [% IF ( id ) %] -
    - [% content | $raw %] -
    +
    [% content | $raw %]
    [% ELSE %] -
    - [% content | $raw %] -
    +
    [% content | $raw %]
    [% END %] [% END %] @@ -406,46 +448,53 @@ [% BLOCK tab_item %] [% END %] - [% BLOCK tab_panels %] -
    - [% content | $raw %] -
    +
    [% content | $raw %]
    [% END %] [% BLOCK tab_panel %] [% IF ( bt_active ) %] -
    - [% content| $raw %] -
    +
    [% content| $raw %]
    [% ELSE %] -
    - [% content| $raw %] -
    +
    [% content| $raw %]
    [% END %] [% END %] @@ -497,14 +546,10 @@ [% BLOCK breadcrumb_item %] [% IF ( bc_active ) %] [% ELSE %] - + [% END %] [% END %] @@ -520,33 +565,39 @@ [%# [ END ] %] [% BLOCK accordion %] -
    - [% content | $raw %] -
    +
    [% content | $raw %]
    [% END %] [% BLOCK accordion_item %] -
    - [% content | $raw %] -
    +
    [% content | $raw %]
    [% END %] [% BLOCK accordion_heading %] + + [% END %] [% BLOCK accordion_panel %]
    -
    - [% content | $raw %] -
    -
    +
    [% content | $raw %]
    + + + [% END %] [% BLOCK acquisitions_filter_form %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/html_helpers/tables/items/catalogue_detail.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/html_helpers/tables/items/catalogue_detail.inc index c4cff843c0..9e175e03a5 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/html_helpers/tables/items/catalogue_detail.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/html_helpers/tables/items/catalogue_detail.inc @@ -10,39 +10,39 @@ - - [% IF Koha.Preference('LocalCoverImages') %] - - [% END %] - [% IF ( item_level_itypes ) %][% END %] - - - - [% IF Koha.Preference('EnableItemGroups') %] - - [% END %] - - - - - - - - - - - - - - - - - - [% IF Koha.Preference('EasyAnalyticalRecords') %][% END %] - [% IF ( analyze ) %][% END %] - [% IF Koha.Preference('UseCourseReserves') %][% END %] - [% IF ( SpineLabelShowPrintOnBibDetails ) %][% END %] - [% IF ( CAN_user_editcatalogue_edit_items ) %][% END %] + + [% IF Koha.Preference('LocalCoverImages') %] + + [% END %] + [% IF ( item_level_itypes ) %][% END %] + + + + [% IF Koha.Preference('EnableItemGroups') %] + + [% END %] + + + + + + + + + + + + + + + + + + [% IF Koha.Preference('EasyAnalyticalRecords') %][% END %] + [% IF ( analyze ) %][% END %] + [% IF Koha.Preference('UseCourseReserves') %][% END %] + [% IF ( SpineLabelShowPrintOnBibDetails ) %][% END %] + [% IF ( CAN_user_editcatalogue_edit_items ) %][% END %]
    Cover imageItem typeCurrent libraryHome libraryCollectionItem groupCall numberSerial enumeration / chronologyStatusLast seenCheckoutsRenewalsLocal usesDate accessionedDate last borrowedSource of acquisitionBarcodeURLCopy numberInventory numberMaterials specifiedPublic notesNon-public notesHost recordsUsed inCourse reservesSpine label Cover imageItem typeCurrent libraryHome libraryCollectionItem groupCall numberSerial enumeration / chronologyStatusLast seenCheckoutsRenewalsLocal usesDate accessionedDate last borrowedSource of acquisitionBarcodeURLCopy numberInventory numberMaterials specifiedPublic notesNon-public notesHost recordsUsed inCourse reservesSpine label 
    @@ -56,846 +56,844 @@ - | Actions: - [% IF CAN_user_tools_items_batchdel %] -
    - [% INCLUDE 'csrf-token.inc' %] - - - - - -
    - [% END %] - [% IF CAN_user_tools_items_batchmod %] -
    - [% INCLUDE 'csrf-token.inc' %] - - - - -
    - [% END %] - [% IF CAN_user_editcatalogue_manage_item_groups && biblio.item_groups.count %] - Add/move to item group - Remove from item group - [% END %] + | Actions: + [% IF CAN_user_tools_items_batchdel %] +
    + [% INCLUDE 'csrf-token.inc' %] + + + + + +
    + [% END %] + [% IF CAN_user_tools_items_batchmod %] +
    + [% INCLUDE 'csrf-token.inc' %] + + + + +
    + [% END %] + [% IF CAN_user_editcatalogue_manage_item_groups && biblio.item_groups.count %] + Add/move to item group + Remove from item group + [% END %]
    [% PROCESS build_table tab => tab %] [% END %][%# end of block items_table %] - [% BLOCK build_items_table_js %] - + function safe_link(uri,link_text) { + let node = document.createElement('a'); + let url_str = '#'; + try { + const safe_url = new URL(uri); + url_str = safe_url.href; + } catch (e) { + //console.error('Invalid URL:', e); + } + node.setAttribute('href',url_str); + node.textContent = link_text; + return node; + } + [% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/ill-availability-table.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/ill-availability-table.inc index e609b6b287..cbeb794681 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/ill-availability-table.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/ill-availability-table.inc @@ -10,7 +10,6 @@ Date - - + diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/ill-batch-modal-strings.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/ill-batch-modal-strings.inc index cd98fd09bf..3440c78c32 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/ill-batch-modal-strings.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/ill-batch-modal-strings.inc @@ -22,17 +22,17 @@ var ill_batch_metadata_less = _("Less"); var ill_batch_available_via = _("Available via"); var ill_batch_metadata = { - 'doi': _("DOI"), - 'pmid': _("PubMed ID"), - 'issn': _("ISSN"), - 'title': _("Title"), - 'year': _("Year"), - 'issue': _("Issue"), - 'pages': _("Pages"), - 'publisher': _("Publisher"), - 'article_title': _("Article title"), - 'article_author': _("Article author"), - 'volume': _("Volume") + doi: _("DOI"), + pmid: _("PubMed ID"), + issn: _("ISSN"), + title: _("Title"), + year: _("Year"), + issue: _("Issue"), + pages: _("Pages"), + publisher: _("Publisher"), + article_title: _("Article title"), + article_author: _("Article author"), + volume: _("Volume"), }; diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/ill-batch-modal.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/ill-batch-modal.inc index 0f9aaa8ed8..c0178996c6 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/ill-batch-modal.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/ill-batch-modal.inc @@ -15,8 +15,7 @@
    1. - +
    2. @@ -56,13 +55,9 @@ @@ -74,13 +69,12 @@ [% IF Koha.Preference('ILLCheckAvailability') %] - + [% END %] - - +
    3. - +
    4. - +
    5. @@ -55,4 +54,5 @@ - + + diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/ill-list-table.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/ill-list-table.inc index 19f992abdb..5d96eb6537 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/ill-list-table.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/ill-list-table.inc @@ -9,14 +9,14 @@ Request ID Batch - Author - Title + Author + Title Article title - Issue - Volume - Year - Pages - Request type + Issue + Volume + Year + Pages + Request type Order ID Patron Bibliographic record ID @@ -36,6 +36,5 @@ - - + diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/ill-request-log.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/ill-request-log.inc index 965792be3d..2dfd337ce2 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/ill-request-log.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/ill-request-log.inc @@ -11,4 +11,4 @@ - [% action_label | html %]: [% content | $raw %]

      -[% END %] \ No newline at end of file +[% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/ill-toolbar.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/ill-toolbar.inc index ffbbe3f5c6..d6a909527f 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/ill-toolbar.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/ill-toolbar.inc @@ -2,52 +2,40 @@ [% IF Koha.Preference('ILLModule') && CAN_user_ill %]
      [% IF backends_available %] - [% IF backends.size > 1 %] - - [% ELSE %] - - New ILL request - - [% END %] + [% IF backends.size > 1 %] + + [% ELSE %] + New ILL request + [% END %] [% ELSE %] - - New ILL request - + New ILL request [% END %] [% IF query_type == 'illlist' %] - - Refresh - + Refresh [% ELSE %] - - List requests - + List requests [% END %] [% IF have_batch.size > 0 && metadata_enrichment_services %] -
      - [% END %]
      [% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/installer-doc-head-close.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/installer-doc-head-close.inc index af316a59ee..bf1f8b6d7f 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/installer-doc-head-close.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/installer-doc-head-close.inc @@ -7,11 +7,15 @@ [% Asset.css("lib/fontawesome/css/solid.min.css") | $raw %] [% Asset.css("css/installer.css") | $raw %] [% IF lang && lang != 'en' %] [% Asset.js(lang _ '/js/locale_data.js') | $raw %] [% END %] [% Asset.js('js/Gettext.js') | $raw %] [% Asset.js('js/i18n.js') | $raw %] - + diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/installer-intranet-bottom.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/installer-intranet-bottom.inc index ed0f64f49d..382f64ef5b 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/installer-intranet-bottom.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/installer-intranet-bottom.inc @@ -1,27 +1,27 @@ [% USE raw %] [% USE Asset %] - [% Asset.js("lib/jquery/jquery-3.6.0.min.js") | $raw %] - [% Asset.js("lib/jquery/jquery-migrate-3.3.2.min.js") | $raw %] - [% Asset.js("lib/jquery/jquery-ui-1.13.2.min.js") | $raw %] - [% Asset.js("lib/bootstrap/bootstrap.bundle.min.js") | $raw %] - [% Asset.js("lib/jquery/plugins/jquery.validate.min.js") | $raw %] - - - - [% INCLUDE 'calendar.inc' %] - [% jsinclude | $raw # Parse the page template's JavaScript block if necessary %] - +[% Asset.js("lib/jquery/jquery-3.6.0.min.js") | $raw %] +[% Asset.js("lib/jquery/jquery-migrate-3.3.2.min.js") | $raw %] +[% Asset.js("lib/jquery/jquery-ui-1.13.2.min.js") | $raw %] +[% Asset.js("lib/bootstrap/bootstrap.bundle.min.js") | $raw %] +[% Asset.js("lib/jquery/plugins/jquery.validate.min.js") | $raw %] + + + +[% INCLUDE 'calendar.inc' %] +[% jsinclude | $raw # Parse the page template's JavaScript block if necessary %] + diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/installer-strings.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/installer-strings.inc index 43ea0ea906..0b5537b88e 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/installer-strings.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/installer-strings.inc @@ -1,9 +1,9 @@ diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/intranet-bottom.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/intranet-bottom.inc index 2174732dd3..d267032d37 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/intranet-bottom.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/intranet-bottom.inc @@ -42,13 +42,17 @@ [% IF ( sublanguages_loo.sublanguage_current ) %]
    6. - [% sublanguages_loo.native_description | html %] [% sublanguages_loo.script_description | html %] [% sublanguages_loo.region_description | html %] [% sublanguages_loo.variant_description | html %] ([% sublanguages_loo.rfc4646_subtag | html %]) + [% sublanguages_loo.native_description | html %] [% sublanguages_loo.script_description | html %] [% sublanguages_loo.region_description | html %] + [% sublanguages_loo.variant_description | html %] + ([% sublanguages_loo.rfc4646_subtag | html %])
    7. [% ELSE %]
    8. - [% sublanguages_loo.native_description | html %] [% sublanguages_loo.script_description | html %] [% sublanguages_loo.region_description | html %] [% sublanguages_loo.variant_description | html %] ([% sublanguages_loo.rfc4646_subtag | html %]) + [% sublanguages_loo.native_description | html %] [% sublanguages_loo.script_description | html %] [% sublanguages_loo.region_description | html %] + [% sublanguages_loo.variant_description | html %] + ([% sublanguages_loo.rfc4646_subtag | html %])
    9. [% END %] @@ -83,10 +87,14 @@ [% END # /IF ( languages_loo.plural ) %] [% END # /IF ( languages_loo.group_enabled ) %] [% END # /FOREACH languages_loo %] - - - - + + + + + + + + [% END # /UNLESS ( one_language_enabled ) %] [% END # /IF ( ( languages_loop )... %] @@ -110,7 +118,8 @@ - + + - - + + + + + + [% END %] [% IF Koha.Preference( 'CookieConsent' ) && JSConsents.all('staffConsent').size %] [% consents = JSConsents.all('staffConsent') %] [% FOREACH consent IN consents %] - + [% END %] [% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/item-status.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/item-status.inc index 4c01dbd3d3..a087410a8f 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/item-status.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/item-status.inc @@ -29,8 +29,7 @@ [% transfer = item.get_transfer %] [% IF ( transfer.in_transit ) %] [% SET itemavailable = 0 %] - In transit from [% Branches.GetName( transfer.frombranch ) | html %] - to [% Branches.GetName( transfer.tobranch ) | html %] since [% transfer.datesent | $KohaDates %] + In transit from [% Branches.GetName( transfer.frombranch ) | html %] to [% Branches.GetName( transfer.tobranch ) | html %] since [% transfer.datesent | $KohaDates %] [% END %] [% IF ( item.withdrawn ) %] @@ -70,15 +69,15 @@ [% hold = item.holds.next %] [% IF hold %] - [% IF hold.waitingdate %] - [% SET itemavailable = 0 %] - Waiting at [% Branches.GetName(hold.get_column('branchcode')) | html %] since [% hold.waitingdate | $KohaDates %]. - [% ELSE %] - Item-level hold (placed [% hold.reservedate | $KohaDates %]) for delivery at [% Branches.GetName(hold.get_column('branchcode')) | html %]. - [% END %] - [% IF Koha.Preference('canreservefromotherbranches') %] - Hold for: [% INCLUDE 'patron-title.inc' patron=hold.borrower hide_patron_infos_if_needed=1 %] - [% END %] + [% IF hold.waitingdate %] + [% SET itemavailable = 0 %] + Waiting at [% Branches.GetName(hold.get_column('branchcode')) | html %] since [% hold.waitingdate | $KohaDates %]. + [% ELSE %] + Item-level hold (placed [% hold.reservedate | $KohaDates %]) for delivery at [% Branches.GetName(hold.get_column('branchcode')) | html %]. + [% END %] + [% IF Koha.Preference('canreservefromotherbranches') %] + Hold for: [% INCLUDE 'patron-title.inc' patron=hold.borrower hide_patron_infos_if_needed=1 %] + [% END %] [% END %] [% IF ( itemavailable ) %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/job_progress.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/job_progress.inc index 7241ce8348..ff6da4847b 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/job_progress.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/job_progress.inc @@ -1,4 +1,3 @@
      -
      -
      +
      diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/js-biblio-format.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/js-biblio-format.inc index 9d31b778c3..8a5dfee946 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/js-biblio-format.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/js-biblio-format.inc @@ -1,5 +1,6 @@ + - [% END %] @@ -34,7 +34,7 @@ [% IF ( IntranetUserJS ) %] [% END %] @@ -67,7 +67,6 @@ }); [% END %] - [% IF ( PatronAutoComplete ) %] [% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/keyboard_shortcuts.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/keyboard_shortcuts.inc index 38b5abb24a..010966be02 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/keyboard_shortcuts.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/keyboard_shortcuts.inc @@ -1,20 +1,36 @@ [%- BLOCK keyboard_shortcut_descriptions -%] [% SWITCH shortcut_name %] - [%- CASE 'insert_copyright' -%]Insert copyright symbol (©) - [%- CASE 'insert_copyright_sound' -%]Insert copyright symbol (℗) (sound recordings) - [%- CASE 'insert_delimiter' -%]Insert delimiter (‡) - [%- CASE 'subfield_help' -%]Get help on current subfield - [%- CASE 'link_authorities' -%]Link field to authorities - [%- CASE 'delete_field' -%]Delete current field and copy to 'clipboard' - [%- CASE 'delete_subfield' -%]Delete current subfield and copy to 'clipboard' - [%- CASE 'new_line' -%]New field on next line - [%- CASE 'line_break' -%]Insert line break - [%- CASE 'next_position' -%]Move to next position - [%- CASE 'prev_position' -%]Move to previous position - [%- CASE 'toggle_keyboard' -%]Toggle Keyboard - [%- CASE 'copy_line' -%]Copy current field - [%- CASE 'copy_subfield' -%]Copy current subfield - [%- CASE 'paste_line' -%]Paste selection from 'clipboard' - [%- CASE 'insert_line' -%]Copy current field on next line + [%- CASE 'insert_copyright' -%] + Insert copyright symbol (©) + [%- CASE 'insert_copyright_sound' -%] + Insert copyright symbol (℗) (sound recordings) + [%- CASE 'insert_delimiter' -%] + Insert delimiter (‡) + [%- CASE 'subfield_help' -%] + Get help on current subfield + [%- CASE 'link_authorities' -%] + Link field to authorities + [%- CASE 'delete_field' -%] + Delete current field and copy to 'clipboard' + [%- CASE 'delete_subfield' -%] + Delete current subfield and copy to 'clipboard' + [%- CASE 'new_line' -%] + New field on next line + [%- CASE 'line_break' -%] + Insert line break + [%- CASE 'next_position' -%] + Move to next position + [%- CASE 'prev_position' -%] + Move to previous position + [%- CASE 'toggle_keyboard' -%] + Toggle Keyboard + [%- CASE 'copy_line' -%] + Copy current field + [%- CASE 'copy_subfield' -%] + Copy current subfield + [%- CASE 'paste_line' -%] + Paste selection from 'clipboard' + [%- CASE 'insert_line' -%] + Copy current field on next line [%- END -%] [%- END -%] diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/langmenu-staff-top.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/langmenu-staff-top.inc index e515163ea6..7209b6d714 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/langmenu-staff-top.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/langmenu-staff-top.inc @@ -1,39 +1,52 @@ - [% IF ( ( ! one_language_enabled ) && ( languages_loop ) && ( Koha.Preference('StaffLangSelectorMode') == 'both' || Koha.Preference('StaffLangSelectorMode') == 'top') ) %] + [% END # / IF languages_loo.current %] + [% END # / IF ( languages_loo.plural ) %] + [% END # / IF ( languages_loo.group_enabled ) %] + [% END # / FOREACH languages_loo IN languages_loop %] + + + + [% END # / IF opaclanguagedisplay %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/last-borrower.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/last-borrower.inc index eea5014803..6a41899356 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/last-borrower.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/last-borrower.inc @@ -1,5 +1,6 @@ +
      @@ -8,7 +9,7 @@ Toggle dropdown
      diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/letters-search.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/letters-search.inc index 37ac4b494d..9d2cde2669 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/letters-search.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/letters-search.inc @@ -11,7 +11,7 @@
      - +
      diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/main-container.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/main-container.inc index e23c227aa7..e2c4f6fdb8 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/main-container.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/main-container.inc @@ -15,24 +15,42 @@ diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/mana/mana-comment-status.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/mana/mana-comment-status.inc index 0340d0738c..11b344aa49 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/mana/mana-comment-status.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/mana/mana-comment-status.inc @@ -1,9 +1,5 @@ - - + + diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/mana/mana-report-search-result.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/mana/mana-report-search-result.inc index 497156e5ed..a7493afad2 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/mana/mana-report-search-result.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/mana/mana-report-search-result.inc @@ -6,11 +6,12 @@ [% USE raw %] [% PROCESS 'i18n.inc' %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Mana Knowledge Base reports search") | html %] › - [% t("Reports") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Mana Knowledge Base reports search") | html %] + › [% t("Reports") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] [% Asset.css("css/reports.css") | $raw %] @@ -22,8 +23,7 @@ @@ -35,7 +35,6 @@
      [% IF statuscode == "200" AND reports %] - @@ -63,46 +62,45 @@ [% SET tr_class = '' %] [% END %] - - - - - - - - [% UNLESS search_only %] - [% END %] - + + + + + + + [% UNLESS search_only %] + + [% END %] + [% END %] [% END %] @@ -117,15 +115,16 @@ [% END %] - - + +
      - -
      - + + + + + -[% INCLUDE 'intranet-bottom.inc' %] + [% INCLUDE 'intranet-bottom.inc' %] + diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/mana/mana-share-report.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/mana/mana-share-report.inc index b304b423ce..9c1f939f22 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/mana/mana-share-report.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/mana/mana-share-report.inc @@ -13,9 +13,7 @@

      Your report is already linked with a Mana report. Share it if you have made modifications, otherwise it will do nothing.

      [% END %] - +
      • Id:
      • @@ -26,7 +24,7 @@
      • Notes:
      • [% IF (languages_loop) %]
      • - + [% END %]
      -
      - + + + + - - - - + + + + + + + + diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/mana/mana-subscription-search-result.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/mana/mana-subscription-search-result.inc index 76fb704b14..5c71d30f09 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/mana/mana-subscription-search-result.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/mana/mana-subscription-search-result.inc @@ -19,7 +19,7 @@ [% UNLESS search_only %] - + [% END %] @@ -28,18 +28,22 @@ [% UNLESS subscription.cannotdisplay %] [% SET tr_class = '' %] [% SET tr_warning = '' %] - [% IF subscription.nbofcomment > highWarned %] + [% IF subscription.nbofcomment > highWarned %] [% SET tr_class = 'high-warned-row' %] [% SET tr_warning = highWarned %] - [% ELSIF subscription.nbofcomment > warned %] + [% ELSIF subscription.nbofcomment > warned %] [% SET tr_class = 'warned-row' %] [% SET tr_warning = warned %] - [% ELSIF subscription.nbofcomment > lowWarned %] + [% ELSIF subscription.nbofcomment > lowWarned %] [% SET tr_class = 'highlighted-row' %] [% SET tr_warning = lowWarned %] [% END %] - - + + @@ -49,22 +53,25 @@ [% UNLESS search_only %]
      - - [% IF ( report.report_name ) %] - [% report.report_name | html %] - [% END %] - - [% IF report.notes.length > 200 %] -
      - [% report.notes.substr(0,200) | html %]... Show more -
      -
      - [% report.notes | html %] - Show less -
      - [% ELSE %] - [% report.notes | html %] - [% END %] -
      [% report.type | html %] - [% IF ( report.nbofusers ) %] - [% report.nbofusers | html %] - [% END %] - - [% report.lastimport | $KohaDates %] - - [% FOREACH comment IN report.comments %] - [% comment.message | html %] ([% comment.nb | html %])
      - [% END %] -
      - + + [% IF ( report.report_name ) %] + [% report.report_name | html %] + [% END %]
      + [% IF report.notes.length > 200 %] +
      + [% report.notes.substr(0,200) | html %]... Show more +
      +
      + [% report.notes | html %] + Show less +
      + [% ELSE %] + [% report.notes | html %] + [% END %] +
      [% report.type | html %] + [% IF ( report.nbofusers ) %] + [% report.nbofusers | html %] + [% END %] + [% report.lastimport | $KohaDates %] + [% FOREACH comment IN report.comments %] + [% comment.message | html %] + ([% comment.nb | html %])
      + [% END %] +
      + +
      Last import Comments ActionsActions
      [% IF ( subscription.issn ) %][% subscription.issn | html %][% END %] [% subscription.title | html %] [% IF ( subscription.publishercode ) %][% subscription.publishercode | html %][% END %][% subscription.lastimport | $KohaDates %] [% FOREACH comment IN subscription.comments %] - [% comment.message | html %] ([% comment.nb | html %])
      + [% comment.message | html %] + ([% comment.nb | html %])
      [% END %]
      - + diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/member-alt-address-style.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/member-alt-address-style.inc index 06267577af..05d955c590 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/member-alt-address-style.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/member-alt-address-style.inc @@ -83,9 +83,9 @@ [% BLOCK 'alt-address-style_B_address' %] [% UNLESS noB_address %]
    10. - + - [% IF ( mandatoryB_address ) %]Required[% END %] + [% IF ( mandatoryB_address ) %]Required[% END %]
    11. [% END %] [% END %] @@ -115,7 +115,7 @@
    12. - [% IF ( mandatoryB_zipcode ) %]Required[% END %] + [% IF ( mandatoryB_zipcode ) %]Required[% END %]
    13. [% END %] [% END %] @@ -133,9 +133,7 @@ [% IF c.city_name == patron.B_city && c.city_state == patron.B_state && c.city_zipcode == patron.B_zipcode %] [% option_selected = 1 %] [% END %] - + [% END %] or enter @@ -181,9 +179,9 @@
    14. [% IF ( NoUpdateEmail ) %] - + [% ELSE %] - + [% END %] [% IF ( mandatoryB_email ) %]Required[% END %]
    15. diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/member-alt-contact-style.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/member-alt-contact-style.inc index 3fe7290dea..9f3d3b2eba 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/member-alt-contact-style.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/member-alt-contact-style.inc @@ -114,9 +114,7 @@ [% IF c.city_name == patron.altcontactaddress3 && c.city_state == patron.altcontactstate && c.city_zipcode == patron.altcontactzipcode %] [% option_selected = 1 %] [% END %] - + [% END %] or enter diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/member-display-address-style.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/member-display-address-style.inc index 1e527a1836..7f29640ceb 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/member-display-address-style.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/member-display-address-style.inc @@ -17,16 +17,22 @@ [%~ IF patron.streettype ~%] [%~ SET roadtype_desc = AuthorisedValues.GetByCode('ROADTYPE', patron.streettype) ~%] [%~ END ~%] -
    16. [%~ if (patron.streetnumber) | html ~%][%~ patron.streetnumber |html ~%][%~ end | html %] [% patron.address | html %] [% IF roadtype_desc ~%][%~ roadtype_desc |html %] [% END ~%][%~ end | html ~%]
    17. +
    18. [%~ if (patron.streetnumber) | html ~%][%~ patron.streetnumber |html ~%][%~ end | html %] [% patron.address | html %] [% IF roadtype_desc ~%] + [%~ roadtype_desc |html %] + [% END ~%][%~ end | html ~%]
    19. [%~ END ~%] [%~ IF ( patron.address2 ) ~%] -
    20. [%~ patron.address2 |html ~%]
    21. +
    22. [%~ patron.address2 |html ~%]
    23. [%~ END ~%] [%~ END ~%] [%~ IF ( patron.city || patron.zipcode || patron.state || patron.country ) ~%]
    24. - [%~ patron.city |html ~%][%~ IF ( patron.state ) %][%~ IF ( patron.city ) ~%], [% END ~%][% patron.state |html ~%][%~ END ~%] - [%~ IF ( patron.zipcode ) %][%~ " " _ patron.zipcode |html ~%][% END %][%~ IF ( patron.country ) %][%~ IF ( patron.zipcode || patron.state || patron.city ) ~%], [% END ~%][% patron.country |html ~%][%~ END ~%] + [%~ patron.city |html ~%][%~ IF ( patron.state ) %][%~ IF ( patron.city ) ~%],[% END ~%][% patron.state |html ~%][%~ END ~%] + [%~ IF ( patron.zipcode ) %][%~ " " _ patron.zipcode |html ~%][% END %][%~ IF ( patron.country ) %][%~ IF ( patron.zipcode || patron.state || patron.city ) ~%] + , + [% END ~%][% patron.country |html ~%][%~ END ~%]
    25. [%~ END ~%] [%~ END ~%] @@ -38,7 +44,11 @@ [%~ IF patron.streettype ~%] [%~ SET roadtype_desc = AuthorisedValues.GetByCode('ROADTYPE', patron.streettype) ~%] [%~ END ~%] -
    26. [%~ patron.address | html ~%][%~IF roadtype_desc %] [% roadtype_desc | html ~%][%~ END ~%][%~ IF patron.streetnumber %] [% patron.streetnumber | html ~%][%~ END ~%]
    27. +
    28. [%~ patron.address | html ~%][%~ IF roadtype_desc %][% roadtype_desc | html ~%][%~ END ~%][%~ IF patron.streetnumber %] + [% patron.streetnumber | html ~%] + [%~ END ~%]
    29. [%~ END ~%] [%~ IF ( patron.address2 ) ~%]
    30. [%~ patron.address2 | html ~%]
    31. @@ -46,7 +56,9 @@ [%~ END ~%] [%~ IF ( patron.city || patron.zipcode || patron.state || patron.country ) ~%]
    32. - [%~ IF ( patron.zipcode ) ~%][%~ patron.zipcode | html %] [% END ~%][%~ patron.city | html ~%][%~ IF ( patron.state ) ~%][% line_break | $raw %][%~ patron.state | html ~%][%~ END ~%] + [%~ IF ( patron.zipcode ) ~%][%~ patron.zipcode | html %][% END ~%][%~ patron.city | html ~%][%~ IF ( patron.state ) ~%] + [% line_break | $raw %][%~ patron.state | html ~%] + [%~ END ~%] [%~ IF ( patron.country ) ~%][% line_break | $raw %][%~ patron.country | html ~%][%~ END ~%]
    33. [%~ END ~%] @@ -59,8 +71,9 @@ [%~ IF patron.streettype ~%] [%~ SET roadtype_desc = AuthorisedValues.GetByCode('ROADTYPE', patron.streettype) ~%] [%~ END ~%] -
    34. [%~ IF patron.streetnumber ~%][%~ patron.streetnumber | html %] [% END ~%] - [%~IF roadtype_desc ~%][%~ roadtype_desc | html %] [% END ~%] +
    35. [%~ IF patron.streetnumber ~%][%~ patron.streetnumber | html %][% END ~%] + [%~ IF roadtype_desc ~%][%~ roadtype_desc | html %][% END ~%] [%~ patron.address | html ~%]
    36. [%~ END ~%] @@ -70,7 +83,9 @@ [%~ END ~%] [%~ IF ( patron.city || patron.zipcode || patron.state || patron.country ) ~%]
    37. - [%~ IF ( patron.zipcode ) ~%][%~ patron.zipcode | html %] [% END ~%][%~ patron.city | html ~%][%~ IF ( patron.state ) ~%][% line_break | $raw %][%~ patron.state | html ~%][%~ END ~%] + [%~ IF ( patron.zipcode ) ~%][%~ patron.zipcode | html %][% END ~%][%~ patron.city | html ~%][%~ IF ( patron.state ) ~%] + [% line_break | $raw %][%~ patron.state | html ~%] + [%~ END ~%] [%~ IF ( patron.country ) ~%][% line_break | $raw %][%~ patron.country | html ~%][%~ END ~%]
    38. [%~ END ~%] diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/member-display-alt-address-style.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/member-display-alt-address-style.inc index 0e9bb0d154..ef50c7aa34 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/member-display-alt-address-style.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/member-display-alt-address-style.inc @@ -14,7 +14,7 @@ [% IF patron.B_streettype %] [% SET roadtype_desc = AuthorisedValues.GetByCode('ROADTYPE', patron.B_streettype) %] [% END %] -
    39. [% if (patron.B_streetnumber) | html %][% patron.B_streetnumber | html %][% end | html %] [% patron.B_address | html %] [% IF roadtype_desc %][% roadtype_desc | html %] [% END %][% end | html %]
    40. +
    41. [% if (patron.B_streetnumber) | html %][% patron.B_streetnumber | html %][% end | html %] [% patron.B_address | html %] [% IF roadtype_desc %][% roadtype_desc | html %][% END %][% end | html %]
    42. [% END %] [% IF ( patron.B_address2 ) %]
    43. [% patron.B_address2 | html %]
    44. @@ -22,8 +22,8 @@ [% END %] [% IF ( patron.B_city || patron.B_state || patron.B_country || patron.B_zipcode ) %]
    45. - [% patron.B_city | html %][% IF ( patron.B_state ) %][% IF ( patron.B_city ) %], [% END %][%~ patron.B_state | html ~%][%~ END ~%] - [% IF ( patron.B_zipcode ) %][%~ " " _ patron.B_zipcode |html ~%][% END %][% IF ( patron.B_country ) %][% IF ( patron.B_zipcode || patron.B_state || patron.B_city ) %], [% END %][% patron.B_country | html %][% END %] + [% patron.B_city | html %][% IF ( patron.B_state ) %][% IF ( patron.B_city ) %],[% END %][%~ patron.B_state | html ~%][%~ END ~%] + [% IF ( patron.B_zipcode ) %][%~ " " _ patron.B_zipcode |html ~%][% END %][% IF ( patron.B_country ) %][% IF ( patron.B_zipcode || patron.B_state || patron.B_city ) %],[% END %][% patron.B_country | html %][% END %]
    46. [% END %] [% END %] @@ -35,7 +35,7 @@ [% IF patron.B_streettype %] [% SET roadtype_desc = AuthorisedValues.GetByCode('ROADTYPE', patron.B_streettype) %] [% END %] -
    47. [% patron.B_address | html %][%IF roadtype_desc %] [% roadtype_desc | html %][% END %][% IF patron.B_streetnumber %] [% patron.B_streetnumber | html %][% END %]
    48. +
    49. [% patron.B_address | html %][% IF roadtype_desc %][% roadtype_desc | html %][% END %][% IF patron.B_streetnumber %][% patron.B_streetnumber | html %][% END %]
    50. [% END %] [% IF ( patron.B_address2 ) %]
    51. [% patron.B_address2 | html %]
    52. @@ -43,7 +43,7 @@ [% END %] [% IF ( patron.B_city || patron.B_state || patron.B_country || patron.B_zipcode ) %]
    53. - [%IF ( patron.B_zipcode ) %][% patron.B_zipcode | html %] [% END %][% patron.B_city | html %][% IF ( patron.B_state ) %]
      [% patron.B_state | html %][% END %] + [% IF ( patron.B_zipcode ) %][% patron.B_zipcode | html %][% END %][% patron.B_city | html %][% IF ( patron.B_state ) %]
      [% patron.B_state | html %][% END %] [% IF ( patron.B_country ) %]
      [% patron.B_country | html %][% END %]
    54. [% END %] @@ -56,8 +56,9 @@ [% IF patron.B_streettype %] [% SET roadtype_desc = AuthorisedValues.GetByCode('ROADTYPE', patron.B_streettype) %] [% END %] -
    55. [% IF patron.B_streetnumber %][% patron.B_streetnumber | html %][% END %] - [%IF roadtype_desc %][% roadtype_desc | html %] [% END %] +
    56. [% IF patron.B_streetnumber %][% patron.B_streetnumber | html %][% END %] + [% IF roadtype_desc %][% roadtype_desc | html %][% END %] [% patron.B_address | html %]
    57. [% END %] @@ -67,7 +68,7 @@ [% END %] [% IF ( patron.B_city || patron.B_state || patron.B_country || patron.B_zipcode ) %]
    58. - [%IF ( patron.B_zipcode ) %][% patron.B_zipcode | html %] [% END %] + [% IF ( patron.B_zipcode ) %][% patron.B_zipcode | html %][% END %] [% patron.B_city | html %] [% IF ( patron.B_state ) %]
      [% patron.B_state | html %][% END %] [% IF ( patron.B_country ) %]
      [% patron.B_country | html %][% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/member-main-address-style.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/member-main-address-style.inc index 56d6fb4930..b27ec15ca4 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/member-main-address-style.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/member-main-address-style.inc @@ -76,7 +76,7 @@
    59. - [% IF ( mandatoryaddress ) %]Required[% END %] + [% IF ( mandatoryaddress ) %]Required[% END %]
    60. [% END %] [% END %] @@ -106,7 +106,7 @@
    61. - [% IF ( mandatoryzipcode ) %]Required[% END %] + [% IF ( mandatoryzipcode ) %]Required[% END %]
    62. [% END %] [% END %] @@ -124,9 +124,7 @@ [% IF c.city_name == patron.city && c.city_state == patron.state && c.city_zipcode == patron.zipcode %] [% option_selected = 1 %] [% END %] - + [% END %] or enter diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/member-search-box.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/member-search-box.inc index 4f5eb2a5a3..43ece02570 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/member-search-box.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/member-search-box.inc @@ -15,9 +15,9 @@
      [% IF ( Koha.Preference('RetainPatronsSearchTerms') ) %] - + [% ELSE %] - + [% END %] @@ -26,19 +26,17 @@
      -
      - [% INCLUDE patron_fields_dropdown search_box=1 %] -
      +
      [% INCLUDE patron_fields_dropdown search_box=1 %]
      diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/members-patron-selections.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/members-patron-selections.inc index dfa54fab5f..76b308e0a5 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/members-patron-selections.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/members-patron-selections.inc @@ -1,6 +1,5 @@ - - + diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/members-toolbar.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/members-toolbar.inc index 1c8c1847d2..61e96355da 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/members-toolbar.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/members-toolbar.inc @@ -7,49 +7,56 @@ [% USE scalar %]
      [% IF CAN_user_borrowers_edit_borrowers %] - Edit + Edit [% END %] - [% SET guarantee_categories = Categories.limited( can_be_guarantee => 1 ).unblessed %] + [% SET guarantee_categories = Categories.limited( can_be_guarantee => 1 ).unblessed %] [% IF CAN_user_borrowers_edit_borrowers %] [% IF patron.is_adult AND Koha.Preference("borrowerRelationship") %] [% IF guarantee_categories.size > 1 %]
      - +
      [% ELSE %] Add guarantee [% END %] - Change password - Duplicate + Change password + Duplicate [% END %] [% END %] [% IF CAN_user_circulate_circulate_remaining_permissions %] -
      - +
      + -
      +
      [% END %] [% IF ( CAN_user_reserveforothers ) %] @@ -66,7 +73,7 @@ [% IF CAN_user_borrowers_edit_borrowers %]
      - +
      [% END %] [% BLOCK mergesource %] @@ -66,12 +66,12 @@ [% END %] [% END # /WRAPPER tab_panels %] [% END # /WRAPPER tabs %] - [% END %] [% BLOCK mergetarget %]

      Destination record ([% authtypetext | html %])

        -
        +
        + [% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/messaging-preference-form.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/messaging-preference-form.inc index 5c54356e77..0f6eeca4fe 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/messaging-preference-form.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/messaging-preference-form.inc @@ -3,242 +3,324 @@ - +
        - - - [% IF Koha.Preference('SMSSendDriver') %][% END %] - [% IF Koha.Preference('TalkingTechItivaPhoneNotification') || Koha.Preference('PhoneNotification') %][% END %] - - - - + + + [% IF Koha.Preference('SMSSendDriver') %][% END %] + [% IF Koha.Preference('TalkingTechItivaPhoneNotification') || Koha.Preference('PhoneNotification') %][% END %] + + + + - [% FOREACH messaging_preference IN messaging_preferences %] - [% NEXT IF !Koha.Preference( 'ILLModule' ) && messaging_preference.message_name.match('^Ill_') %] - [% NEXT IF !Koha.Preference('MembershipExpiryDaysNotice') && messaging_preference.Patron_Expiry %] - [% NEXT IF messaging_preference.Auto_Renewals && Koha.Preference('AutoRenewalNotices') != 'preferences' %] - [% NEXT IF !Koha.Preference('UseRecalls') && messaging_preference.message_name.match('^Recall_') %] - - - [% IF ( messaging_preference.takes_days ) %] - - [% ELSE %] - - [% END %] + [% FOREACH messaging_preference IN messaging_preferences %] + [% NEXT IF !Koha.Preference( 'ILLModule' ) && messaging_preference.message_name.match('^Ill_') %] + [% NEXT IF !Koha.Preference('MembershipExpiryDaysNotice') && messaging_preference.Patron_Expiry %] + [% NEXT IF messaging_preference.Auto_Renewals && Koha.Preference('AutoRenewalNotices') != 'preferences' %] + [% NEXT IF !Koha.Preference('UseRecalls') && messaging_preference.message_name.match('^Recall_') %] + + + [% IF ( messaging_preference.takes_days ) %] + + [% ELSE %] + + [% END %] - [% IF Koha.Preference('SMSSendDriver') %] - [% IF ( messaging_preference.transport_sms ) %] - - [% ELSE %] - + [% IF Koha.Preference('SMSSendDriver') %] + [% IF ( messaging_preference.transport_sms ) %] + + [% ELSE %] + + [% END %] + [% END %] + + [% IF Koha.Preference('TalkingTechItivaPhoneNotification') %] + [% IF ( messaging_preference.transport_itiva ) %] + + [% ELSE %] + + [% END %] + [% ELSIF Koha.Preference('PhoneNotification') %] + [% IF ( messaging_preference.transport_phone ) %] + + [% ELSE %] + + [% END %] + [% END %] + + [% IF ( messaging_preference.transport_email ) %] + + [% ELSE %] + + [% END %] + + [% IF ( messaging_preference.has_digest ) %] + + [% ELSE %] + + [% END %] + + + [% END %] - [% END %] - - [% IF Koha.Preference('TalkingTechItivaPhoneNotification') %] - [% IF ( messaging_preference.transport_itiva ) %] - - [% ELSE %] - - [% END %] - [% ELSIF Koha.Preference('PhoneNotification') %] - [% IF ( messaging_preference.transport_phone ) %] - - [% ELSE %] - - [% END %] - [% END %] - - [% IF ( messaging_preference.transport_email ) %] - - [% ELSE %] - - [% END %] - - [% IF ( messaging_preference.has_digest ) %] - - [% ELSE %] - - [% END %] - - - - - [% END %] -
        Days in advanceSMSPhoneEmailDigests only
        Days in advanceSMSPhoneEmailDigests only +
        [% IF ( messaging_preference.Item_Due ) %]Item due - [% ELSIF ( messaging_preference.Advance_Notice ) %]Advance notice - [% ELSIF ( messaging_preference.Hold_Filled ) %]Hold filled - [% ELSIF ( messaging_preference.Hold_Reminder ) %]Hold reminder - [% ELSIF ( messaging_preference.Item_Check_in ) %]Item check-in - [% ELSIF ( messaging_preference.Item_Checkout ) %] - [% IF Koha.Preference( 'RenewalSendNotice' ) %] - Item checkout and renewal - [% ELSE %] - Item checkout - [% END %] - [% ELSIF ( messaging_preference.Patron_Expiry ) %]Patron account expiry - [% ELSIF ( messaging_preference.Ill_ready ) %]Interlibrary loan ready - [% ELSIF ( messaging_preference.Ill_unavailable ) %]Interlibrary loan unavailable - [% ELSIF ( messaging_preference.Ill_update ) %]Interlibrary loan updated - [% ELSIF ( messaging_preference.Auto_Renewals ) %]Auto renewal - [% ELSIF ( messaging_preference.Recall_Waiting ) %]Recall awaiting pickup - [% ELSIF ( messaging_preference.Recall_Requested ) %]Return recalled item - [% ELSE %]Unknown - [% END %] - - - -
        [% IF ( messaging_preference.Item_Due ) %] + Item due + [% ELSIF ( messaging_preference.Advance_Notice ) %] + Advance notice + [% ELSIF ( messaging_preference.Hold_Filled ) %] + Hold filled + [% ELSIF ( messaging_preference.Hold_Reminder ) %] + Hold reminder + [% ELSIF ( messaging_preference.Item_Check_in ) %] + Item check-in + [% ELSIF ( messaging_preference.Item_Checkout ) %] + [% IF Koha.Preference( 'RenewalSendNotice' ) %] + Item checkout and renewal + [% ELSE %] + Item checkout + [% END %] + [% ELSIF ( messaging_preference.Patron_Expiry ) %] + Patron account expiry + [% ELSIF ( messaging_preference.Ill_ready ) %] + Interlibrary loan ready + [% ELSIF ( messaging_preference.Ill_unavailable ) %] + Interlibrary loan unavailable + [% ELSIF ( messaging_preference.Ill_update ) %] + Interlibrary loan updated + [% ELSIF ( messaging_preference.Auto_Renewals ) %] + Auto renewal + [% ELSIF ( messaging_preference.Recall_Waiting ) %] + Recall awaiting pickup + [% ELSIF ( messaging_preference.Recall_Requested ) %] + Return recalled item + [% ELSE %] + Unknown + [% END %] + + + - - [% IF ( messaging_form_inactive ) %] - [% IF ( messaging_preference.transports_sms ) %] - - [% ELSE %] - - [% END %] - [% ELSE %] - [% IF ( messaging_preference.transports_sms ) %] - - [% ELSE %] - - [% END %] - [% END %] - - + [% IF ( messaging_form_inactive ) %] + [% IF ( messaging_preference.transports_sms ) %] + + [% ELSE %] + + [% END %] + [% ELSE %] + [% IF ( messaging_preference.transports_sms ) %] + + [% ELSE %] + + [% END %] + [% END %] + - + [% IF ( messaging_form_inactive ) %] + [% IF ( messaging_preference.transports_itiva ) %] + + [% ELSE %] + + [% END %] + [% ELSE %] + [% IF ( messaging_preference.transports_itiva ) %] + + [% ELSE %] + + [% END %] + [% END %] + - + [% IF ( messaging_form_inactive ) %] + [% IF ( messaging_preference.transports_phone ) %] + + [% ELSE %] + + [% END %] + [% ELSE %] + [% IF ( messaging_preference.transports_phone ) %] + + [% ELSE %] + + [% END %] + [% END %] + - + [% IF ( messaging_form_inactive ) %] + [% IF ( messaging_preference.transports_email ) %] + + [% ELSE %] + + [% END %] + [% ELSE %] + [% IF ( messaging_preference.transports_email ) %] + + [% ELSE %] + + [% END %] + [% END %] + - + [% IF ( messaging_form_inactive ) %] + [% IF ( messaging_preference.digest ) %] + + [% ELSE %] + + [% END %] + [% ELSE %] + [% IF ( messaging_preference.digest ) %] + + [% ELSE %] + + [% END %] + [% END %] + -
        - [% IF ( messaging_form_inactive ) %] - [% IF ( messaging_preference.transports_itiva ) %] - - [% ELSE %] - - [% END %] - [% ELSE %] - [% IF ( messaging_preference.transports_itiva ) %] - - [% ELSE %] - - [% END %] - [% END %] - - - [% IF ( messaging_form_inactive ) %] - [% IF ( messaging_preference.transports_phone ) %] - - [% ELSE %] - - [% END %] - [% ELSE %] - [% IF ( messaging_preference.transports_phone ) %] - - [% ELSE %] - - [% END %] - [% END %] - - - [% IF ( messaging_form_inactive ) %] - [% IF ( messaging_preference.transports_email ) %] - - [% ELSE %] - - [% END %] - [% ELSE %] - [% IF ( messaging_preference.transports_email ) %] - - [% ELSE %] - - [% END %] - [% END %] - - - [% IF ( messaging_form_inactive ) %] - [% IF ( messaging_preference.digest ) %] - - [% ELSE %] - - [% END %] - [% ELSE %] - [% IF ( messaging_preference.digest ) %] - - [% ELSE %] - - [% END %] - [% END %] - -
        +
        diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/modal-claims.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/modal-claims.inc index 8cfd36e6df..73f1f4625d 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/modal-claims.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/modal-claims.inc @@ -10,28 +10,27 @@
      - + + - - - + + + + + + + + diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/modals/bundle_contents.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/modals/bundle_contents.inc index 35d8010151..3d05f8dbf7 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/modals/bundle_contents.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/modals/bundle_contents.inc @@ -15,21 +15,25 @@ - [% FOREACH bundle_item IN bundle_items %] - - [% bundle_item.barcode | html %] - [% INCLUDE 'biblio-title.inc' biblio=bundle_item.biblio %] - - [% END %] + [% FOREACH bundle_item IN bundle_items %] + + [% bundle_item.barcode | html %] + [% INCLUDE 'biblio-title.inc' biblio=bundle_item.biblio %] + + [% END %] - - + - + + - - - + + + + + + + + diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/modals/cancel_booking.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/modals/cancel_booking.inc index f5c2a8a102..dedae631ef 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/modals/cancel_booking.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/modals/cancel_booking.inc @@ -10,7 +10,7 @@ - - + + + + - - + + + + + + - + + diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/modals/cashup_summary.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/modals/cashup_summary.inc index 0d51aff4a8..960dc05156 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/modals/cashup_summary.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/modals/cashup_summary.inc @@ -18,16 +18,19 @@ Total - - - - + + - + + - - - + + + + + + + + diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/modals/cataloguing_create_av.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/modals/cataloguing_create_av.inc index 30b6e68291..10dad1e6ca 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/modals/cataloguing_create_av.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/modals/cataloguing_create_av.inc @@ -38,6 +38,9 @@ - - - + + + + + + diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/modals/checkout_renewals.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/modals/checkout_renewals.inc index b02ebca9b2..b3f2bd8b0d 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/modals/checkout_renewals.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/modals/checkout_renewals.inc @@ -5,15 +5,21 @@ + + + + - - - + + + + + + + + diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/modals/display_ticket.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/modals/display_ticket.inc index 3388fc7ac6..a19da9d41d 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/modals/display_ticket.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/modals/display_ticket.inc @@ -12,60 +12,65 @@ + + - - - + + + + + + + + diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/modals/edit_authority_preview.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/modals/edit_authority_preview.inc index ae2264052f..7eec6746d4 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/modals/edit_authority_preview.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/modals/edit_authority_preview.inc @@ -9,6 +9,9 @@ - - - + + + + + + diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/modals/place_booking.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/modals/place_booking.inc index e15df51bc3..217c69460d 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/modals/place_booking.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/modals/place_booking.inc @@ -11,17 +11,17 @@ + + - - + + + + + + - + + diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/modals/resolve_return_claim.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/modals/resolve_return_claim.inc index 53973a9242..5d6a6b87f6 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/modals/resolve_return_claim.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/modals/resolve_return_claim.inc @@ -1,42 +1,41 @@ [% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/oai-admin-search.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/oai-admin-search.inc index 1da8c440cc..57b54d88bc 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/oai-admin-search.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/oai-admin-search.inc @@ -21,12 +21,13 @@ [% END %] [% IF ( CAN_user_catalogue ) %] [% INCLUDE 'catalogue-search-box.inc' %] - [% END %] - - + [% END %] - + diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/onboarding_messages.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/onboarding_messages.inc index 2ea4550554..0e40489a72 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/onboarding_messages.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/onboarding_messages.inc @@ -1,37 +1,38 @@ [% FOR m IN messages %] [% SWITCH m.code %] - [% CASE 'success_on_insert_library' %] -
      Library created!
      - [% CASE 'error_on_insert_library' %] -
      Library already exists and cannot be modified!
      - [% CASE 'success_on_insert_category' %] -
      Patron category created!
      - [% CASE 'error_on_insert_category' %] -
      Patron category already exists and cannot be modified!
      - [% CASE 'success_on_insert_patron' %] -
      Administrator account created!
      - [% CASE 'error_on_insert_patron' %] -
      The patron was not created! The card number or username already exists.
      - [% CASE 'ERROR_cardnumber_already_exists' %] -
      Card number already in use.
      - [% CASE 'ERROR_cardnumber_length' %] -
      Card number length is incorrect.
      - [% CASE 'ERROR_password_mismatch' %] -
      Passwords do not match.
      - [% CASE 'success_on_insert_itemtype' %] -
      New item type created!
      - [% CASE 'error_on_insert_itemtype' %] -
      Item type already exists!
      - [% CASE 'success_on_insert_circ_rule' %] -
      Circulation rule created!
      - [% CASE 'error_on_insert_circ_rule' %] -
      Circulation rule not created!
      - [% CASE 'ERROR_password_too_short' %] -
      The patron has not been created the entered password was too short
      - [% CASE 'ERROR_password_too_weak' %] -
      The patron has not been created the entered password was too weak, must contain at least one uppercase, and lower case letter and one number
      - [% CASE 'ERROR_password_has_whitespaces' %] -
      The patron has not been created the entered password contained whitespaces
      - [% CASE %][% message | html %] + [% CASE 'success_on_insert_library' %] +
      Library created!
      + [% CASE 'error_on_insert_library' %] +
      Library already exists and cannot be modified!
      + [% CASE 'success_on_insert_category' %] +
      Patron category created!
      + [% CASE 'error_on_insert_category' %] +
      Patron category already exists and cannot be modified!
      + [% CASE 'success_on_insert_patron' %] +
      Administrator account created!
      + [% CASE 'error_on_insert_patron' %] +
      The patron was not created! The card number or username already exists.
      + [% CASE 'ERROR_cardnumber_already_exists' %] +
      Card number already in use.
      + [% CASE 'ERROR_cardnumber_length' %] +
      Card number length is incorrect.
      + [% CASE 'ERROR_password_mismatch' %] +
      Passwords do not match.
      + [% CASE 'success_on_insert_itemtype' %] +
      New item type created!
      + [% CASE 'error_on_insert_itemtype' %] +
      Item type already exists!
      + [% CASE 'success_on_insert_circ_rule' %] +
      Circulation rule created!
      + [% CASE 'error_on_insert_circ_rule' %] +
      Circulation rule not created!
      + [% CASE 'ERROR_password_too_short' %] +
      The patron has not been created the entered password was too short
      + [% CASE 'ERROR_password_too_weak' %] +
      The patron has not been created the entered password was too weak, must contain at least one uppercase, and lower case letter and one number
      + [% CASE 'ERROR_password_has_whitespaces' %] +
      The patron has not been created the entered password contained whitespaces
      + [% CASE %] + [% message | html %] [% END %] [% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/page-numbers.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/page-numbers.inc index 81467a295c..bfea1f0ea6 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/page-numbers.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/page-numbers.inc @@ -7,11 +7,19 @@ [% END %] [% IF ( previous_page_offset.defined ) %]
    63. - First + First
    64. - Previous + Previous
    65. [% END %] [% FOREACH PAGE_NUMBER IN PAGE_NUMBERS %] @@ -21,18 +29,31 @@ [% ELSE %]
    66. - [% PAGE_NUMBER.pg | html %] + [% PAGE_NUMBER.pg | html %]
    67. [% END %] [% END %] [% IF ( next_page_offset ) %]
    68. - Next + Next
    69. - Last + Last
    70. [% END %] - + + [% END %][% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/patron-age.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/patron-age.inc index 153d9bac41..787a311ab2 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/patron-age.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/patron-age.inc @@ -6,7 +6,7 @@ [%- SET age = (patron.get_age != undef) ? patron.get_age : patron.age -%] [%- IF age >= 0 %] [%- patron.dateofbirth | $KohaDates -%] - [% I18N.tnx('({age} year)', '({age} years)', age, { age => age }) | html %] + [% I18N.tnx('({age} year)', '({age} years)', age, { age => age }) | html %] [%- END -%] - [%- END -%] + [%- END -%] [%- END -%] diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/patron-article-requests.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/patron-article-requests.inc index c9bd475954..d0072549e2 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/patron-article-requests.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/patron-article-requests.inc @@ -30,52 +30,34 @@ [% ar.item.enumchron | html %] [% ar.biblio.author | html %] - [% IF ar.itemnumber %] (only [% ar.item.barcode | html %])[% END %] + [% IF ar.itemnumber %](only [% ar.item.barcode | html %])[% END %] - - [% ar.created_on | $KohaDates %] - + [% ar.created_on | $KohaDates %] - - [% ar.title | html %] - + [% ar.title | html %] - - [% ar.author | html %] - + [% ar.author | html %] - - [% ar.volume | html %] - + [% ar.volume | html %] - - [% ar.issue | html %] - + [% ar.issue | html %] - - [% ar.date | html %] - + [% ar.date | html %] - - [% IF ar.toc_request %]Yes[% END %] - + [% IF ar.toc_request %]Yes[% END %] - - [% ar.pages | html %] - + [% ar.pages | html %] - - [% ar.chapters | html %] - + [% ar.chapters | html %] - - [% ar.patron_notes | html %] - + [% ar.patron_notes | html %] - [% IF ar.format == 'PHOTOCOPY' %]Copy - [% ELSIF ar.format == 'SCAN' %]Scan + [% IF ar.format == 'PHOTOCOPY' %] + Copy + [% ELSIF ar.format == 'SCAN' %] + Scan [% END %] @@ -91,13 +73,11 @@ [% END %] - - [% ar.branch.branchname | html %] - + [% ar.branch.branchname | html %] [% END %] - [% ELSE %] - Patron has no current article requests. - [% END %] +[% ELSE %] + Patron has no current article requests. +[% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/patron-detail-tabs.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/patron-detail-tabs.inc index 68f5e54630..60947807a7 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/patron-detail-tabs.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/patron-detail-tabs.inc @@ -70,7 +70,8 @@ [% END %] [% SET enrollments = patron.get_club_enrollments %] - [% SET enrollable = patron.get_enrollable_clubs(0) %] + [% SET enrollable = patron.get_enrollable_clubs(0) %] + [% IF CAN_user_clubs && ( enrollable.count || enrollments.count ) %] [% WRAPPER tab_item tabname= "clubs" %] Clubs ([% enrollments.count | html %]/[% enrollable.count | html %]) @@ -84,7 +85,6 @@ [% END %] [% END # /WRAPPER tabs_nav %] - [% WRAPPER tab_panels %] [% WRAPPER tab_panel tabname="checkouts" bt_active= 1 %] [% INCLUDE "checkouts-table.inc" %] @@ -192,7 +192,7 @@ [% IF Koha.Preference('AutoResumeSuspendedHolds') %] - + Specify date on which to resume [% INCLUDE 'date-format.inc' %]: [% END %] @@ -209,7 +209,6 @@ [% END # IF SuspendHoldsIntranet %] - [% ELSE %]

      Patron has nothing on hold.

      [% END %] @@ -249,7 +248,6 @@ [% INCLUDE 'patron-article-requests.inc' %] [% END %] [% END # /tab_panel# %] - [% END # /WRAPPER tab_panels %] [% END # /WRAPPER tabs %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/patron-restrictions-tab.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/patron-restrictions-tab.inc index efb6676e31..1cca1bad70 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/patron-restrictions-tab.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/patron-restrictions-tab.inc @@ -8,21 +8,19 @@ - - - - - [% IF CAN_user_borrowers_edit_borrowers && CAN_user_circulate_manage_restrictions %] - - [% END %] + + + + + [% IF CAN_user_borrowers_edit_borrowers && CAN_user_circulate_manage_restrictions %] + + [% END %] [% FOREACH restriction IN patron.restrictions %] - +
      TypeCommentExpirationCreated TypeCommentExpirationCreated 
      - [% PROCESS restriction_type_description restriction_type=restriction.type %] - [% PROCESS restriction_type_description restriction_type=restriction.type %] [% IF restriction.comment.search('OVERDUES_PROCESS') %] Restriction added by overdues process [% restriction.comment.remove('OVERDUES_PROCESS ') | $raw %] @@ -56,7 +54,9 @@
      [% END %] [% IF CAN_user_borrowers_edit_borrowers && CAN_user_circulate_manage_restrictions %] -

      Add manual restriction

      +

      Add manual restriction

      [% INCLUDE 'csrf-token.inc' %] @@ -65,20 +65,20 @@ Add manual restriction
        [% IF Koha.Preference('PatronRestrictionTypes') %] -
      1. - - + [% FOREACH restriction_type IN restriction_types %] + [% IF !restriction_type.is_system %] + [% IF restriction_type.is_default %] + + [% ELSE %] + + [% END %] [% END %] [% END %] - [% END %] - -
      2. + + [% END %]
      3. @@ -86,7 +86,7 @@
      -
      Cancel
      +
      Cancel
      [% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/patron-search-box.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/patron-search-box.inc index f0c9cb674e..67af8e73db 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/patron-search-box.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/patron-search-box.inc @@ -7,7 +7,7 @@
      - + [% IF ( stickyduedate ) %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/includes/patron-search.inc b/koha-tmpl/intranet-tmpl/prog/en/includes/patron-search.inc index f0f6156332..ba17bf990f 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/includes/patron-search.inc +++ b/koha-tmpl/intranet-tmpl/prog/en/includes/patron-search.inc @@ -12,7 +12,7 @@ [% SET av_bsort2 = AuthorisedValues.Get('Bsort2') %] [%# Display a simple form %] -[% BLOCK patron_search_filters_simple %] +[% BLOCK patron_search_filters_simple %]
      Enter patron card number or partial name:
      @@ -83,21 +83,19 @@ [% CASE 'sort2' %]
    71. - [% PROCESS 'av-build-dropbox.inc' no_id => 1, name="sort2_filter", category="Bsort2", empty=1, size = 20 %] + [% PROCESS 'av-build-dropbox.inc' no_id => 1, name="sort2_filter", category="Bsort2", empty=1, size = 20 %]
    72. [% CASE 'search_field' %] -
    73. - [% INCLUDE patron_fields_dropdown %] -
    74. +
    75. [% INCLUDE patron_fields_dropdown %]
    76. [% CASE 'search_type' %]
    77. @@ -140,8 +138,7 @@ [% END %]
      - Browse by last name: - [% SET alphabet = Koha.Preference('alphabet').split(' ') %] + Browse by last name: [% SET alphabet = Koha.Preference('alphabet').split(' ') %] [% UNLESS alphabet.size %] [% alphabet = ['A' .. 'Z'] %] [% END %] @@ -153,7 +150,6 @@

      Patrons found for:

      - -
    78. Release maintainers: +
    79. Release maintainers:
        [% FOREACH m IN maintenance_team.maintainer %] -
      • [% m.version | html %] - [% INCLUDE person p=m %]
      • +
      • [% m.version | html %] - [% INCLUDE person p=m %]
      • [% IF maintenance_team.maintainer_assistants %] - [% FOREACH ma IN maintenance_team.maintainer_assistants %] - [% IF ma.version == ( m.version ) %] -
        • Assistant: [% INCLUDE person p=ma %]
        + [% FOREACH ma IN maintenance_team.maintainer_assistants %] + [% IF ma.version == ( m.version ) %] +
        • Assistant: [% INCLUDE person p=ma %]
        + [% END %] [% END %] [% END %] - [% END %] [% IF maintenance_team.maintainer_mentors %] - [% FOREACH mm IN maintenance_team.maintainer_mentors %] - [% IF m.version == ( mm.version ) %] -
        • Mentor: [% INCLUDE person p=mm %]
        + [% FOREACH mm IN maintenance_team.maintainer_mentors %] + [% IF m.version == ( mm.version ) %] +
        • Mentor: [% INCLUDE person p=mm %]
        + [% END %] [% END %] [% END %] - [% END %] [% END %]
    80. @@ -893,9 +869,7 @@
      [% ELSE %] -
      - Could not read the teams.yaml file. Please make sure <docdir> is correctly defined in koha-conf.xml. -
      +
      Could not read the teams.yaml file. Please make sure <docdir> is correctly defined in koha-conf.xml.
      [% END # /maintenance_team %]

      Koha development team

      @@ -906,11 +880,9 @@ [% END %] [% ELSE %] -
      - Could not read the contributors.yaml file. Please make sure <docdir> is correctly defined in koha-conf.xml. -
      +
      Could not read the contributors.yaml file. Please make sure <docdir> is correctly defined in koha-conf.xml.
      [% END # /IF contributors.size %] -
      +

      Contributing companies and institutions

        @@ -1034,244 +1006,168 @@ [% WRAPPER tab_panel tabname= "licenses" bt_active = 1 %]

        Koha

        - This program 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 3 of the License, or (at your option) any later version. + This program 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 3 of the License, or (at your option) any later version.

        Bootstrap

        -

        - Bootstrap, Glyphicons Free: MIT License -

        +

        Bootstrap, Glyphicons Free: MIT License

        Bootstrap Icons

        -

        - Bootstrap Icons: MIT License -

        +

        Bootstrap Icons: MIT License

        Bridge Material Type Icon Set

        -

        - Bridge Material Type Icons Project: Creative Commons Attribution-ShareAlike 2.5 License -

        +

        Bridge Material Type Icons Project: Creative Commons Attribution-ShareAlike 2.5 License

        bwip-js

        -

        - bwip-js v4.4.0: MIT License -

        +

        bwip-js v4.4.0: MIT License

        Chocolat.js

        -

        - Chocolat.js v1.1.2: GNU General Public License v3.0 -

        +

        Chocolat.js v1.1.2: GNU General Public License v3.0

        CodeMirror

        -

        - CodeMirror v5.40.2: MIT License -

        +

        CodeMirror v5.40.2: MIT License

        C3.js

        -

        - C3.js D3-based reusable chart library v0.4.11: MIT Licence -

        +

        C3.js D3-based reusable chart library v0.4.11: MIT Licence

        CSSLint

        -

        - CSSLint v0.9.8: License -

        +

        CSSLint v0.9.8: License

        D3

        -

        - D3 JavaScript library for visualizing data v3.5.17: ISC Licence -

        +

        D3 JavaScript library for visualizing data v3.5.17: ISC Licence

        DataTables

        -

        - DataTables v.1.10.18: MIT Licence -

        +

        DataTables v.1.10.18: MIT Licence

        Day.js

        -

        - Day.js v1.11.2: MIT License -

        +

        Day.js v1.11.2: MIT License

        Enquire.js

        -

        - Enquire.js v2.1.6: MIT License -

        +

        Enquire.js v2.1.6: MIT License

        Maskito

        -

        - Maskito All Maskito packages are covered by Apache 2.0 -

        +

        Maskito All Maskito packages are covered by Apache 2.0

        FamFamFam icons

        -

        - FamFamFam Silk icons: Creative Commons Attribution 2.5 License -

        +

        FamFamFam Silk icons: Creative Commons Attribution 2.5 License

        FileSaver.js

        -

        - FileSaver.js v2.0.4: MIT License -

        +

        FileSaver.js v2.0.4: MIT License

        Flatpicker

        -

        - Flatpickr v4.6.9: MIT License -

        +

        Flatpickr v4.6.9: MIT License

        Font Awesome

        - Font Awesome v6.3.0: Creative Commons Attribution 4.0 International License, SIL Open Font License Version 1.1, MIT License + Font Awesome v6.3.0: + Creative Commons Attribution 4.0 International License, SIL Open Font License Version 1.1, MIT License

        Font Face Observer

        -

        - Font Face Observer JavaScript library v2.3.0: BSD 2-Clause "Simplified" License -

        +

        Font Face Observer JavaScript library v2.3.0: BSD 2-Clause "Simplified" License

        GreyBox

        - GreyBox JavaScript Library v5.54: GNU Lesser General Public License, version 2.1 + GreyBox JavaScript Library v5.54: + GNU Lesser General Public License, version 2.1

        Highlight

        -

        - Highlight jQuery Plugin v5.0: MIT License -

        +

        Highlight jQuery Plugin v5.0: MIT License

        HTMLHint

        -

        - HTMLHint v0.9.12: MIT License -

        +

        HTMLHint v0.9.12: MIT License

        Humanized Messages

        -

        - Humanized Messages v1.0: Apache License, Version 2.0 -

        +

        Humanized Messages v1.0: Apache License, Version 2.0

        JavaScript Cookie

        -

        - JavaScript Cookie v3.0.1: MIT License -

        +

        JavaScript Cookie v3.0.1: MIT License

        JavaScript Diff Algorithm

        -

        - JavaScript Diff Algorithm: MIT License -

        +

        JavaScript Diff Algorithm: MIT License

        jQuery, jQuery Migrate, and jQuery UI

        - jQuery v3.6.0, jQuery Migrate, jQuery UI v1.13.2: MIT License + jQuery v3.6.0, jQuery Migrate, jQuery UI v1.13.2: + MIT License

        jQuery Bar Rating Plugin

        -

        - jQuery Bar Rating plugin v1.2.2: MIT License -

        +

        jQuery Bar Rating plugin v1.2.2: MIT License

        jQuery Emojiarea Plugin

        -

        - Emojiarea plugin for jQuery: Apache License, Version 2.0 -

        +

        Emojiarea plugin for jQuery: Apache License, Version 2.0

        jQuery insertAtCaret Plugin

        -

        - jQuery insertAtCaret Plugin v1.0 by the phpMyAdmin development team: GNU General Public License -

        +

        jQuery insertAtCaret Plugin v1.0 by the phpMyAdmin development team: GNU General Public License

        jQuery jsTree Plugin

        -

        - jQuery jsTree Plugin v3.3.12: MIT License -

        +

        jQuery jsTree Plugin v3.3.12: MIT License

        jQuery Multiple Select Plugin

        -

        - jQuery Multiple Select plugin v1.6.0: MIT License -

        +

        jQuery Multiple Select plugin v1.6.0: MIT License

        jQuery Treetable Plugin

        - jQuery Treetable Plugin 3.1.0: GNU General Public License v2.0, MIT License + jQuery Treetable Plugin 3.1.0: GNU General Public License v2.0, + MIT License

        jQuery Validation Plugin

        -

        - jQuery Validation Plugin v1.19.3: MIT License -

        +

        jQuery Validation Plugin v1.19.3: MIT License

        JS-YAML

        -

        - JS-YAML v3.13.1: MIT License -

        +

        JS-YAML v3.13.1: MIT License

        JSHint

        -

        - JSHint v2.9.7: MIT License -

        +

        JSHint v2.9.7: MIT License

        JSZip

        -

        - JSZip JavaScript library v3.1.3: MIT License, GNU General Public License v3.0 -

        +

        JSZip JavaScript library v3.1.3: MIT License, GNU General Public License v3.0

        kjua

        -

        - kjua JavaScript library v0.6.0: MIT License -

        +

        kjua JavaScript library v0.6.0: MIT License

        Leaflet

        -

        - Leaflet JavaScript library v1.9.4: BSD License -

        +

        Leaflet JavaScript library v1.9.4: BSD License

        Noto fonts

        -

        - Noto: SIL Open Font License Version 1.1 -

        +

        Noto: SIL Open Font License Version 1.1

        OAI XSLT stylesheet

        -

        - Adapted from the DSpace project: BSD License -

        +

        Adapted from the DSpace project: BSD License

        OpenAPI 2.0 schema

        - JSON Schema for Swagger 2.0 API: Apache License, Version 2.0, OpenAPI Initiative (OAI) + JSON Schema for Swagger 2.0 API: + Apache License, Version 2.0, OpenAPI Initiative (OAI)

        OpenJS Keyboard Shortcuts Library

        -

        - OpenJS keyboard shortcuts library: BSD License -

        +

        OpenJS keyboard shortcuts library: BSD License

        RequireJS

        -

        - RequireJS JavaScript file and module loader v2.1.8: BSD License or MIT License -

        +

        RequireJS JavaScript file and module loader v2.1.8: BSD License or MIT License

        Select2

        -

        - Select2 library v4.0.13: Apache License, Version 2.0 or GNU General Public License v2.0 -

        +

        Select2 library v4.0.13: Apache License, Version 2.0 or GNU General Public License v2.0

        Sortable

        -

        - Sortable JavaScript Library v1.15.0: MIT Licence -

        +

        Sortable JavaScript Library v1.15.0: MIT Licence

        TinyMCE WYSIWYG Editor

        -

        - TinyMCE WYSIWYG editor v5.9.2: GNU Lesser General Public License v2.1 -

        +

        TinyMCE WYSIWYG editor v5.9.2: GNU Lesser General Public License v2.1

        Verovio

        - Verovio: GNU General Public License v3.0, GNU Lesser General Public License v3.0 + Verovio: GNU General Public License v3.0, + GNU Lesser General Public License v3.0

        Virtual Keyboard

        -

        - Virtual Keyboard v1.30.1: MIT Licence -

        - +

        Virtual Keyboard v1.30.1: MIT Licence

        [% END # tab=licenses %] [% END %] @@ -1279,8 +1175,10 @@ [% WRAPPER tab_panel tabname= "translations" bt_active = 1 %]

        Translation

          -
        • العربية (Arabic) Version 3.2 to 3.4, 3.16 & 3.18 by KnowledgeWare Technologies; Versions 3.6 to 3.14 by Arabic Koha support team: Karam Qubsi, Kouider Bounama, Sham Bajaa, Ghofran Alshami, Chrestian Aboud, Fatema Salem and Duaa Bazzazi. -
        • አማርኛ (Amharic) Getway II Ethiopia Co. (Yohannes Mulugeta (Team Leader), Tegene Assefa, Abiyot Bayou)
        • +
        • العربية (Arabic) Version 3.2 to 3.4, 3.16 & 3.18 by KnowledgeWare Technologies; Versions 3.6 to 3.14 by Arabic Koha support team: Karam Qubsi, Kouider Bounama, Sham Bajaa, Ghofran Alshami, Chrestian Aboud, Fatema Salem and + Duaa Bazzazi.
        • አማርኛ (Amharic) Getway II Ethiopia Co. (Yohannes Mulugeta (Team Leader), Tegene Assefa, Abiyot Bayou)
        • Armenian Tigran Zargaryan
        • Български (Bulgarian) Radoslav Kolev
        • euskara (Basque) Fernando Berrizbeitia, the librarians of Eima Katalogoa, Tabakalera International Contemporary Culture Centre, and Nere Erkiaga
        • @@ -1296,7 +1194,10 @@
        • Français (French) Kohala, Pascale Nalon (ENSMP), and many more
        • Galego (Galician) Ignacio Javier
        • Deutsch (German) Friedrich zur Hellen, Robert Hillig, Katrin Fischer, Beda Szukics, Mirko Tietgen and Marc Véron
        • -
        • ελληνικά (Greek, Modern [1453- ]) Koha Hellenic Users' Group (Georgia Katsarou, Dimitris Antonakis, Eugenios Papadopoulos), Theodoros Theodoropoulos, Panoraia Gaitanou and Kiriaki Roditi
        • +
        • ελληνικά (Greek, Modern [1453- ]) Koha Hellenic Users' Group (Georgia Katsarou, Dimitris Antonakis, Eugenios Papadopoulos), Theodoros Theodoropoulos, Panoraia Gaitanou and Kiriaki + Roditi
        • עברית (Hebrew)
        • हिन्दी (Hindi)
        • Magyar (Hungarian)Agnes Imecs
        • @@ -1335,8 +1236,8 @@ - - + + [% FOREACH tabl IN table2 %] @@ -1349,9 +1250,7 @@ [% END %]
          DateDescriptionDateDescription
          [% ELSE %] -
          - Could not read the history.txt file. Please make sure <docdir> is correctly defined in koha-conf.xml. -
          +
          Could not read the history.txt file. Please make sure <docdir> is correctly defined in koha-conf.xml.
          [% END %] [% END %] [% END %] @@ -1359,18 +1258,11 @@ [% BLOCK dedications_panel %] [% WRAPPER tab_panel tabname= "dedications" bt_active = 1 %]

          22.11

          +

          The Koha Community would like to dedicate the release of Koha 22.11 to Rosalie Blake.

          - The Koha Community would like to dedicate the release of Koha 22.11 to Rosalie Blake. -

          -

          - Rosalie was the Head Librarian at Horowhenua Library Trust when Koha was started and without her Koha - would not exist. She was an inspiring leader and innovator and took the risk of her career entrusting - Chris, Joanne, Rachel and Simon to deliver the original project that became the international sensation - we all know and love. -

          -

          - She was also a practicing Justice of the Peace, a stalwart of the Levin Pottery Club and much loved - mother of Simon and Jeremy, and grandmother of Ben, Toby, Anna, Charlotte and Billy. + Rosalie was the Head Librarian at Horowhenua Library Trust when Koha was started and without her Koha would not exist. She was an inspiring leader and innovator and took the risk of her career entrusting Chris, Joanne, Rachel + and Simon to deliver the original project that became the international sensation we all know and love.

          +

          She was also a practicing Justice of the Peace, a stalwart of the Levin Pottery Club and much loved mother of Simon and Jeremy, and grandmother of Ben, Toby, Anna, Charlotte and Billy.

          [% END # tab=dedications %] [% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/acqui/acqui-home.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/acqui/acqui-home.tt index e7c385bd48..76ac361d9b 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/acqui/acqui-home.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/acqui/acqui-home.tt @@ -8,10 +8,12 @@ [% SET footerjs = 1 %] [% PROCESS 'i18n.inc' %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Acquisitions") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Acquisitions") | html %] + › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] [% Asset.css("lib/jquery/plugins/treetable/stylesheets/jquery.treetable.css") | $raw %] @@ -31,174 +33,173 @@ [% WRAPPER 'main-container.inc' aside='acquisitions-menu' %] -[% INCLUDE 'acquisitions-toolbar.inc' %] + [% INCLUDE 'acquisitions-toolbar.inc' %] -

          Acquisitions

          +

          Acquisitions

          [% INCLUDE 'budgets-active-currency.inc' hide = 'yes' %] [% UNLESS ( loop_budget ) %] [% IF ( CAN_user_acquisition_period_manage ) %] - + [% ELSE %] -
          Your administrator must define a budget in Administration
          +
          Your administrator must define a budget in Administration
          [% END %] [% END %] -
          -
          -
          -
          - Search vendors -
          -

          - -

          -
          -
          -
          -
          - -[% IF ( CAN_user_suggestions_suggestions_manage && ( suggestions_count || all_pendingsuggestions ) ) %] -
          -
          -
          - Pending suggestions -

          - Manage suggestions: - - [% Branches.GetLoggedInBranchname | html %]: [% suggestions_count | html %] - - [% IF (all_pendingsuggestions > 0) %] - / - - All libraries: [% all_pendingsuggestions | html %] - - [% END %] -

          -
          -
          -
          -[% END %] - -
          - -[% PROCESS acquisitions_filter_form context => "main" %] - -[% IF ( loop_budget ) %] - -
          -

          All available funds

          - -
          -
          - - Expand all | - Collapse all | - Hide inactive budgets | - Show inactive budgets | - - +
          +
          +
          +
          + Search vendors +
          +

          + +

          +
          +
          +
          - - - - - - - - - - - - - - - - - - - - - - - - - - - - [% FOREACH loop_budge IN loop_budget %] - - - - - - - - - - - - - [% END %] - -
          ActiveBudget period descriptionFund codeFund nameOwnerLibraryAmountOrderedSpentTotal available
          Total
          [% loop_budge.budget_period_active | html %]Budget [% loop_budge.budget_period_description | html %] [id=[% loop_budge.budget_period_id | html %]][% UNLESS loop_budge.budget_period_active %] (inactive)[% END %] - [% IF ( CAN_user_acquisition_budget_manage ) %] - [% loop_budge.budget_code | html %] - [% ELSE %] - [% loop_budge.budget_code | html %] - [% END %] - [% loop_budge.budget_name | html %][% IF ( loop_budge.budget_owner ) %] - [% loop_budge.budget_owner.surname | html %], [% loop_budge.budget_owner.firstname | html %] - [% ELSE %] -   - [% END %] - [% Branches.GetName( loop_budge.budget_branchcode ) | html %] - [% loop_budge.budget_amount | $Price %] - - [% IF loop_budge.children.size %] - - ([% loop_budge.budget_ordered | $Price %]) - - [% loop_budge.total_ordered | $Price %] - [% ELSE %] - - [% loop_budge.budget_ordered | $Price %] + [% IF ( CAN_user_suggestions_suggestions_manage && ( suggestions_count || all_pendingsuggestions ) ) %] + - [% IF loop_budge.children.size %] - - ([% loop_budge.budget_spent | $Price %]) - - [% loop_budge.total_spent | $Price %] - [% ELSE %] - - [% loop_budge.budget_spent | $Price %] - +

          + + + + [% END %] + + + [% PROCESS acquisitions_filter_form context => "main" %] + + [% IF ( loop_budget ) %] +
          +

          All available funds

          + +
          +
          + + Expand all | Collapse all | Hide inactive budgets | Show inactive budgets | +
          - [% IF loop_budge.children.size %] - ([% loop_budge.budget_avail | $Price %]) - [% loop_budge.total_avail | $Price %] - [% ELSE %] - [% loop_budge.budget_avail | $Price %] - [% END %] -
          -
          -
          -[% END %] + + +
          + + + + + + + + + + + + + + + + + + + + + + + + + + + + [% FOREACH loop_budge IN loop_budget %] + + + + + + + + + + + + + [% END %] + +
          ActiveBudget period descriptionFund codeFund nameOwnerLibraryAmountOrderedSpentTotal available
          Total
          [% loop_budge.budget_period_active | html %]Budget [% loop_budge.budget_period_description | html %] [id=[% loop_budge.budget_period_id | html %]][% UNLESS loop_budge.budget_period_active %](inactive)[% END %] + [% IF ( CAN_user_acquisition_budget_manage ) %] + [% loop_budge.budget_code | html %] + [% ELSE %] + [% loop_budge.budget_code | html %] + [% END %] + [% loop_budge.budget_name | html %][% IF ( loop_budge.budget_owner ) %] + [% loop_budge.budget_owner.surname | html %], [% loop_budge.budget_owner.firstname | html %] + [% ELSE %] +   + [% END %] + [% Branches.GetName( loop_budge.budget_branchcode ) | html %] + [% loop_budge.budget_amount | $Price %] + + [% IF loop_budge.children.size %] + + ([% loop_budge.budget_ordered | $Price %]) + + [% loop_budge.total_ordered | $Price %] + [% ELSE %] + + [% loop_budge.budget_ordered | $Price %] + + [% END %] + + [% IF loop_budge.children.size %] + + ([% loop_budge.budget_spent | $Price %]) + + [% loop_budge.total_spent | $Price %] + [% ELSE %] + + [% loop_budge.budget_spent | $Price %] + + [% END %] + + [% IF loop_budge.children.size %] + ([% loop_budge.budget_avail | $Price %]) + [% loop_budge.total_avail | $Price %] + [% ELSE %] + [% loop_budge.budget_avail | $Price %] + [% END %] +
          + [% END %] [%- SET StaffAcquisitionsHome = AdditionalContents.get( location => "StaffAcquisitionsHome", lang => lang, library => Branches.GetLoggedInBranchcode ) -%] [%- FOREACH block IN StaffAcquisitionsHome.content -%] -
          - [%- block.content | $raw -%] -
          +
          [%- block.content | $raw -%]
          [%- END -%] - [% END %] [% MACRO jsinclude BLOCK %] [% INCLUDE 'calendar.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/acqui/addorder.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/acqui/addorder.tt index 20e28e953f..b1e9ae5238 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/acqui/addorder.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/acqui/addorder.tt @@ -1,45 +1,47 @@ [% USE raw %] [% PROCESS 'i18n.inc' %] [% INCLUDE "doc-head-open.inc" %] -[% FILTER collapse %] - [% t("Add order") | html %] › - [% t("Acquisition") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Add order") | html %] + › [% t("Acquisition") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE "doc-head-close.inc" %] [% INCLUDE "header.inc" %] -
          - [% IF (not_enough_budget) %] +
          + [% IF (not_enough_budget) %]
          - + [% INCLUDE 'csrf-token.inc' %] - [% FOREACH var IN vars_loop %] - [% FOREACH val IN var.values %] - + [% FOREACH var IN vars_loop %] + [% FOREACH val IN var.values %] + + [% END %] [% END %] - [% END %] - - -
          - [% IF (budget_exceeded) %] -

          Warning! Order total amount exceeds allowed budget.

          - [% END %] - [% IF (encumbrance_exceeded) %] -

          Warning! You will exceed [% encumbrance | html %]% of your fund.

          - [% END %] - [% IF (expenditure_exceeded) %] -

          Warning! You will exceed maximum limit ([% expenditure | html %][% IF (currency) %] [% currency | html %][% END %]) for your fund.

          - [% END %] -

          Do you want to confirm this order?

          - - -
          + + +
          + [% IF (budget_exceeded) %] +

          Warning! Order total amount exceeds allowed budget.

          + [% END %] + [% IF (encumbrance_exceeded) %] +

          Warning! You will exceed [% encumbrance | html %]% of your fund.

          + [% END %] + [% IF (expenditure_exceeded) %] +

          Warning! You will exceed maximum limit ([% expenditure | html %][% IF (currency) %][% currency | html %][% END %]) for your fund.

          + [% END %] +

          Do you want to confirm this order?

          + + +
          - [% END %] -
          + [% END %] +
          + [% INCLUDE "intranet-bottom.inc" %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/acqui/addorderiso2709.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/acqui/addorderiso2709.tt index ad94eada7e..96a0ae9d82 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/acqui/addorderiso2709.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/acqui/addorderiso2709.tt @@ -6,21 +6,21 @@ [% USE Price %] [% PROCESS 'i18n.inc' %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% IF ( batch_details ) %] - [% tx('Batch {batch_id}', { batch_id = import_batch_id } ) | html %] - [% ELSE %] - [% t("Batch list") | html %] - [% END %] › - [% t("Order staged MARC records") | html %] › - [% t("Acquisitions") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% IF ( batch_details ) %] + [% tx('Batch {batch_id}', { batch_id = import_batch_id } ) | html %] + [% ELSE %] + [% t("Batch list") | html %] + [% END %] + › [% t("Order staged MARC records") | html %] › [% t("Acquisitions") | html %] › [% t("Koha") | html %] + [% END %] [% FILTER collapse %] @@ -62,542 +62,653 @@ [% INCLUDE 'acquisitions-search.inc' %] [% END %] - [% WRAPPER 'sub-header.inc' %] - [% WRAPPER breadcrumbs %] - [% WRAPPER breadcrumb_item %] - Acquisitions - [% END %] - [% WRAPPER breadcrumb_item %] - [% booksellername | html %] - [% END %] - [% WRAPPER breadcrumb_item %] - Basket [% basketno | html %] - [% END %] - [% WRAPPER breadcrumb_item bc_active= 1 %] - Add orders from MARC file - [% END %] - [% END #/ WRAPPER breadcrumbs %] - [% END #/ WRAPPER sub-header.inc %] +[% WRAPPER 'sub-header.inc' %] + [% WRAPPER breadcrumbs %] + [% WRAPPER breadcrumb_item %] + Acquisitions + [% END %] + [% WRAPPER breadcrumb_item %] + [% booksellername | html %] + [% END %] + [% WRAPPER breadcrumb_item %] + Basket [% basketno | html %] + [% END %] + [% WRAPPER breadcrumb_item bc_active= 1 %] + Add orders from MARC file + [% END %] + [% END #/ WRAPPER breadcrumbs %] +[% END #/ WRAPPER sub-header.inc %] -
          -
          -
          - [% IF ( allmatch ) %] -
          -

          No records imported

          - No records have been imported because they all match existing records in your catalog.
          You'll have to treat them individually. -
          - [% END %] +
          +
          +
          + [% IF ( allmatch ) %] +
          +

          No records imported

          + No records have been imported because they all match existing records in your catalog.
          You'll have to treat them individually. +
          + [% END %] - [% IF ( batch_details ) %] -

          - Add orders from [% comments | html %] - ([% file_name | html %] staged on [% upload_timestamp | $KohaDates with_hours => 1 %]) -

          -
          - [% INCLUDE 'csrf-token.inc' %] - [% WRAPPER tabs id= "tabs" %] - [% WRAPPER tabs_nav %] - [% WRAPPER tab_item tabname= "records_to_import" bt_active= 1 %] Select to import [% END %] - [% IF items %] - [% WRAPPER tab_item tabname= "items_info" %] Item information [% END %] - [% END %] - [% WRAPPER tab_item tabname= "accounting_details" %] Default accounting details [% END %] + [% IF ( batch_details ) %] +

          Add orders from [% comments | html %] ([% file_name | html %] staged on [% upload_timestamp | $KohaDates with_hours => 1 %])

          + + [% INCLUDE 'csrf-token.inc' %] + [% WRAPPER tabs id= "tabs" %] + [% WRAPPER tabs_nav %] + [% WRAPPER tab_item tabname= "records_to_import" bt_active= 1 %]Select to import[% END %] + [% IF items %] + [% WRAPPER tab_item tabname= "items_info" %]Item information[% END %] [% END %] + [% WRAPPER tab_item tabname= "accounting_details" %]Default accounting details[% END %] + [% END %] - [% WRAPPER tab_panels %] - [% WRAPPER tab_panel tabname= "records_to_import" bt_active= 1 %] -
          -
          - Select all - | - Clear all - | - - - - - | - - - - -
          -
          + [% WRAPPER tab_panels %] + [% WRAPPER tab_panel tabname= "records_to_import" bt_active= 1 %] +
          +
          + Select all + | + Clear all + | + + + + + | + + + + +
          +
          + - - - - - + + + + + - - - [% FOREACH biblio IN import_biblio_list %] - - - + + [% END # /FOREACH biblio %] + +
          - - - - - MARC - Card - New order + + + [% FOREACH biblio IN import_biblio_list %] + + + - - [% END # /FOREACH biblio %] - -
          + + +
          - - - [% END # /#records_to_import %] - - [% IF ( items ) %] - [% WRAPPER tab_panel tabname= "items_info" %] -

          Item information

          -

          Import all the checked items in the basket with the following parameters:

          - -
          - Item - [% IF ( NoACQframework ) %] -
          No ACQ framework, using default. You should create a framework with code ACQ, the items framework would be used
          - [% END %] -
          - [% FOREACH item IN items %] -
          -
          -
            - [% FOREACH iteminformatio IN item.iteminformation %] -
          1. -
            - [% IF (iteminformatio.mandatory) %] - + [% IF ( biblio.match_biblionumber ) %] + Matches biblio [% biblio.match_biblionumber | uri %] (score = [% biblio.match_score | html %]): + [% biblio.match_citation | html %] + [% END %] + +
          2. +
          3. + + + Required +
          4. +
          5. + + +
          6. +
          7. + + +
          8. +
          9. + + + % +
            If empty, discount rate from vendor will be used
            +
          10. +
          11. + [% IF ( close ) %] + + [% Budget_name | html %] + [% ELSE %] + + - [% FOREACH value IN iteminformatio.marc_value.values %] - [% IF ( value == iteminformatio.marc_value.default ) %] - + [% END %] + + + [% END %] +
          12. +
          13. + + +
          14. +
          15. + + +
          16. +
          + [% IF ( biblio.iteminfos.size ) %] +
          + [% IF biblio.item_error %]Item records could not be processed because the number of item fields was uneven.[% END %] + [% FOREACH item IN biblio.iteminfos %] +
          + Item record [% item.item_id | html %] +
            +
          1. + + - [% ELSE %] - [% iteminformatio.marc_value | $raw %] - [% END %] - - - - - - [% IF ( iteminformatio.mandatory ) %] - Required - [% END %] -
          - - [% END %] - -
          -
          - [% END #/FOREACH item %] -
          -
          - [% END # /#items_info %] - [% END # /IF items %] + + +
        • + + +
        • +
        • + + +
        • + +
        • + + +
        • +
        • + + +
        • +
        • + + +
        • + +
        • + + +
        • + +
        • + + +
        • +
        • + + +
        • +
        • + + +
        • +
        • + + + Required +
        • +
        • + + +
        • +
        • + + +
        • +
        • + + +
        • +
        • + + +
        • +
        • + + +
        • +
        • + + +
        • + + + [% END # /FOREACH item %] + + + [% END %] + + +
          + + + + + [% END # /#records_to_import %] + + [% IF ( items ) %] + [% WRAPPER tab_panel tabname= "items_info" %] +

          Item information

          +

          Import all the checked items in the basket with the following parameters:

          - [% WRAPPER tab_panel tabname= "accounting_details" %] -

          Import all the checked items in the basket with the following accounting details (used only if no information is filled for the item):

          - Accounting details -
            -
          1. - - -
          2. - [% IF ( close ) %] -
          3. - Fund: - [% Budget_name | html %] -
          4. - [% ELSE %] -
          5. - - -
          6. -
          7. - - - - -
          8. - [% END #/IF close %] -
          9. - - -
          10. -
          11. - - -
          12. -
          13. -
            The 2 following fields are available for your own usage. They can be useful for statistical purposes
            -
          14. -
          15. - - -
          16. -
          17. - - -
          18. -
          -
          - [% END # /#accounting_details %] - [% END #/WRAPPER tab_panels %] - [% END # /WRAPPER tabs %] -
          - Cancel -
          -
          - [% ELSE # IF ( batch_details ) %] -

          Choose the file to add to the basket

          + Item + [% IF ( NoACQframework ) %] +
          No ACQ framework, using default. You should create a framework with code ACQ, the items framework would be used
          + [% END %] +
          + [% FOREACH item IN items %] +
          +
          +
            + [% FOREACH iteminformatio IN item.iteminformation %] +
          1. +
            + [% IF (iteminformatio.mandatory) %] + + [% ELSE %] + + [% END %] -
            - - + [% IF ( iteminformatio.marc_value.type == 'select' ) %] + + [% ELSE %] + [% iteminformatio.marc_value | $raw %] + [% END %] + + + + + + [% IF ( iteminformatio.mandatory ) %] + Required + [% END %] + + + [% END %] + + + + [% END #/FOREACH item %] + + + + [% END # /#items_info %] + [% END # /IF items %] + + [% WRAPPER tab_panel tabname= "accounting_details" %] +

            Import all the checked items in the basket with the following accounting details (used only if no information is filled for the item):

            +
            + Accounting details +
              +
            1. + + +
            2. + [% IF ( close ) %] +
            3. + Fund: + [% Budget_name | html %] +
            4. + [% ELSE %] +
            5. + + +
            6. +
            7. + + + + +
            8. + [% END #/IF close %] +
            9. + + +
            10. +
            11. + + +
            12. +
            13. +
              The 2 following fields are available for your own usage. They can be useful for statistical purposes
              +
            14. +
            15. + + +
            16. +
            17. + + +
            18. +
            +
            + + [% END # /#accounting_details %] + [% END #/WRAPPER tab_panels %] + [% END # /WRAPPER tabs %] +
            Cancel
            + + + [% ELSE # IF ( batch_details ) %] +

            Choose the file to add to the basket

            + +
            +
            + + + + + + + + + + + + [% FOREACH batch_lis IN batch_list %] - - - - - - + + + + + + - - - [% FOREACH batch_lis IN batch_list %] - - - - - - - - - [% END # /FOREACH batch_lis %] - -
            File nameCommentsStatusStaged# Bibliographic records 
            File nameCommentsStatusStaged# Bibliographic records [% batch_lis.file_name | html %][% batch_lis.comments | html %] + [% IF ( batch_lis.import_status == 'cleaned' ) %] + Cleaned + [% ELSIF ( batch_lis.import_status == 'imported' ) %] + Imported + [% ELSIF ( batch_lis.import_status == 'importing' ) %] + Importing + [% ELSIF ( batch_lis.import_status == 'reverted' ) %] + Reverted + [% ELSIF ( batch_lis.import_status == 'reverting' ) %] + Reverting + [% ELSIF ( batch_lis.import_status == 'staged' ) %] + Staged + [% ELSE %] + [% batch_lis.import_status | html %] + [% END %] + [% batch_lis.staged_date | $KohaDates with_hours => 1 %] [% batch_lis.num_records | html %] + Add orders +
            [% batch_lis.file_name | html %][% batch_lis.comments | html %] - [% IF ( batch_lis.import_status == 'cleaned' ) %] - Cleaned - [% ELSIF ( batch_lis.import_status == 'imported' ) %] - Imported - [% ELSIF ( batch_lis.import_status == 'importing' ) %] - Importing - [% ELSIF ( batch_lis.import_status == 'reverted' ) %] - Reverted - [% ELSIF ( batch_lis.import_status == 'reverting' ) %] - Reverting - [% ELSIF ( batch_lis.import_status == 'staged' ) %] - Staged - [% ELSE %] - [% batch_lis.import_status | html %] - [% END %] - - [% batch_lis.staged_date | $KohaDates with_hours => 1 %] - [% batch_lis.num_records | html %] - Add orders -
            -
            - [% END # /IF ( batch_details ) %] -
            [%# /div.col-sm-6 %] -
          [%# /div.row %] -
          + [% END # /FOREACH batch_lis %] + + + +
          + + [% END # /IF ( batch_details ) %] +
          + [%# /div.col-sm-6 %] +
          + [%# /div.row %] +
          + [% INCLUDE 'intranet-bottom.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/acqui/basket.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/acqui/basket.tt index 1bf782f28c..9ed74d2792 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/acqui/basket.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/acqui/basket.tt @@ -26,14 +26,17 @@ [% USE TablesSettings %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% tx("Basket {basketname} ({basketnumber}) for {vendor}", { basketname = basketname, basketnumber = basketno, vendor = booksellername }) | html %] › - [% t("Acquisitions") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% tx("Basket {basketname} ({basketnumber}) for {vendor}", { basketname = basketname, basketnumber = basketno, vendor = booksellername }) | html %] + › [% t("Acquisitions") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -71,939 +74,1022 @@ [% IF booksellerid %][% asides.unshift('vendor-menu') %][% END %] [% WRAPPER 'main-container.inc' asides=asides %] - [% IF (cannot_manage_basket) %] -
          You are not authorised to manage this basket.
          - [% ELSE %] + [% IF (cannot_manage_basket) %] +
          You are not authorised to manage this basket.
          + [% ELSE %] - [% IF !confirm_close && !edi_confirm %] - [% UNLESS ( selectbasketg ) %] - [% UNLESS ( closedate ) %] - [% UNLESS ( delete_confirmed ) %] -
          - [% IF active %] - - [% END %] - - [% IF CAN_user_acquisition_delete_baskets %] - - [% END %] - [% IF ( unclosable ) %] - [% ELSIF ( uncertainprices ) %] - - - [% ELSE %] -
          -
          - [% INCLUDE 'csrf-token.inc' %] - - - - -
          -
          - [% END %] + [% IF !confirm_close && !edi_confirm %] + [% UNLESS ( selectbasketg ) %] + [% UNLESS ( closedate ) %] + [% UNLESS ( delete_confirmed ) %] +
          + [% IF active %] + + [% END %] + + [% IF CAN_user_acquisition_delete_baskets %] + + [% END %] + [% IF ( unclosable ) %] - [% PROCESS csv_export %] - - [% IF Koha.Preference('EDIFACT') && ediaccount %] - [% UNLESS eans.size %] -
          - -
          - [% ELSE %] -
          - [% IF eans.size == 1 %] - Create EDIFACT order - [% ELSE %] - - - [% END %] -
          - [% END %] - [% END %] - - [% IF ( active && books_loop ) %] -
          -
          - [% INCLUDE 'csrf-token.inc' %] - - - -
          -
          - [% END %] -
          - [% END # / UNLESS ( delete_confirmed ) %] - - - - - [% ELSE # UNLESS ( closedate ) %] -
          - [% IF grouped %] - - [% ELSE %] -
          -
          - [% INCLUDE 'csrf-token.inc' %] - - - -
          -
          - - [% PROCESS csv_export %] - [% END %] + [% ELSIF ( uncertainprices ) %] + + - [% END # /UNLESS ( closedate ) %] - [% END # /UNLESS ( selectbasketg ) %] - - [% IF ( NO_BOOKSELLER ) %] -

          Vendor not found

          - [% ELSE %] - [% IF ( delete_confirmed ) %] -
          -

          Basket deleted

          + [% ELSE %] +
          +
          + [% INCLUDE 'csrf-token.inc' %] + + + + +
          - [% IF (cannotdelbiblios) %] -
          -

          Warning:

          -

          The following records could not be deleted:

          -
            - [% FOREACH cannotdelbiblio IN cannotdelbiblios %] -
          • - [% cannotdelbiblio.title | html %] by [% cannotdelbiblio.author | html %]: -
              - [% IF (cannotdelbiblio.itemcount) %]
            • [% cannotdelbiblio.itemcount | html %] item(s) attached.
            • [% END %] - [% IF (cannotdelbiblio.subscriptions) %]
            • [% cannotdelbiblio.subscriptions | html %] subscription(s) attached.
            • [% END %] - [% IF (cannotdelbiblio.countbiblio) %]
            • [% cannotdelbiblio.countbiblio | html %] order(s) attached.
            • [% END %] - [% IF (cannotdelbiblio.othererror) %]
            • Unknown error.
            • [% END %] -
            -
          • - [% END %] -
          + [% END %] + + [% PROCESS csv_export %] + + [% IF Koha.Preference('EDIFACT') && ediaccount %] + [% UNLESS eans.size %] +
          +
          - Go back to vendor page [% ELSE %] - Show baskets for vendor [% booksellername | html %] Show all active baskets - [% END # /IF (cannotdelbiblios) %] - [% ELSE # IF ( delete_confirmed ) %] - - [% FOR m IN messages %] -
          - [% SWITCH m.code %] - [% CASE 'no_email' %] - This vendor has no contact selected for sending orders to or is missing an e-mail address. - [% CASE 'no_basketno' %] - No basket given. - [% CASE 'no_letter' %] - There is no notice template with code ACQORDER defined. - [% CASE 'email_sent' %] - Order e-mail was sent to the vendor. - [% CASE %] - ERROR! - [% m.code | html %] +
          + [% IF eans.size == 1 %] + Create EDIFACT order + [% ELSE %] + + [% END %]
          - [% END # /FOR m %] + [% END %] + [% END %] -

          [% UNLESS ( basketno ) %]New [% END %]Basket [% basketname | html %] ([% basketno | html %]) for [% booksellername | html %]

          + [% IF ( active && books_loop ) %] +
          +
          + [% INCLUDE 'csrf-token.inc' %] + + + +
          +
          + [% END %] +
          + + [% END # / UNLESS ( delete_confirmed ) %] - [% IF ( basketno ) %] -
          -
          -
          -

          General information

          -
            - [% IF ( basketnote ) %] -
          1. Internal note: [% basketnote | html %]
          2. - [% END %] - [% IF ( basketbooksellernote ) %] -
          3. Vendor note: [% basketbooksellernote | html %]
          4. - [% END %] - [% IF ( basketcontractno ) %] -
          5. Contract name: [% basketcontractname | html %]
          6. - [% END %] - [% IF deliveryplace %] -
          7. Delivery place: [% Branches.GetName( deliveryplace ) | html %]
          8. - [% END %] - [% IF billingplace %] -
          9. Billing place: [% Branches.GetName( billingplace ) | html %]
          10. - [% END %] - [% IF ( authorisedbyname ) %] -
          11. [% tp('basket created by', 'Created by:') | html %] [% authorisedbyname | html %]
          12. - [% END %] - - [% IF ( creationdate ) %] -
          13. Opened on: [% creationdate | $KohaDates %]
          14. - [% END %] - [% IF ( closedate ) %] -
          15. Closed on: [% closedate | $KohaDates %]
          16. - [% END %] - - [% IF ( ediaccount ) %] - [%- BLOCK edi_status -%] - [%- SWITCH edi_order.status -%] - [%- CASE 'pending' -%]Pending - [%- CASE 'sent' -%]Sent - [%- CASE 'processed' -%]Processed - [%- END -%] - [%- END -%] - [% IF ( edi_order ) %] -
          17. EDI status: [%- PROCESS edi_status edi_order=edi_order -%] ([% edi_order.transfer_date | $KohaDates %])
          18. - [% ELSE %] -
          19. EDI status: Not ordered
          20. - [% END %] - [% END %] - [% IF ( estimateddeliverydate ) %] -
          21. Estimated delivery date: [% estimateddeliverydate | $KohaDates %]
          22. - [% END %] -
          23. Orders are standing: [% IF is_standing %]Yes[% ELSE %]No[% END %]
          24. - - [% IF basket.create_items %] -
          25. - Create items when: - [% SWITCH basket.create_items %] - [% CASE 'receiving' %]Receiving items - [% CASE 'cataloguing' %]Cataloguing items - [% CASE %]Placing orders - [% END %] -
          26. - [% END %] - - [% INCLUDE 'additional-fields-display.inc' available=available_additional_fields values=additional_field_values %] - -
          -
          -
          - -
          -
          -

          Settings

          - -
            -
          1. -
            - [% INCLUDE 'csrf-token.inc' %] - [% tp('Acquisitions basket managed by user', 'Managed by:') | html %] -
            -
              - [% FOREACH user IN users %] -
            • - [% user.firstname | html %] [% user.surname | html %] - Delete user -
            • - [% END %] -
            • - Add user -
            • - -
            -
            - - - -
            - -
          2. -
          3. - Managing library: - [% IF basketbranchcode %] - [% Branches.GetName( basketbranchcode ) | html %] - Change library - [% ELSE %] - No library - Set library - [% END %] -
          4. - [% IF branches_loop.size %] - - [% END # /IF branches_loop.size %] - -
          - - [% IF ( closedate ) %] -
            -
          1. - Basket group: - [% IF basketgroup.id and not basketgroup.name %] - [% SET basketgroup.name = "Basket group no. " _ basketgroup.id %] - [% END %] - - [% IF basketgroup.closed %] - [% IF ( CAN_user_acquisition_group_manage ) %] - [% basketgroup.name | html %] (closed) - [% ELSE %] - [% basketgroup.name | html %] (closed) - [% END %] - [% ELSIF ( ! CAN_user_acquisition_group_manage ) %] - [%- IF basketgroup.id -%] - [% basketgroup.name | html %] - [%- ELSE -%] - No group - [%- END -%] - [% ELSE %] - [% IF ( CAN_user_acquisition_group_manage ) %] - [% IF ( basketgroup.id ) %] - - [% basketgroup.name | html %] - - Change basket group - [% ELSE %] - No group - Set basket group - [% END %] - [% END %] - [% END %] -
          2. - [% IF ( CAN_user_acquisition_group_manage ) %] - - [% END # /IF ( CAN_user_acquisition_group_manage ) %] - [% IF basketgroup.deliveryplace %] -
          3. - Basket group delivery placename: [% Branches.GetName( basketgroup.deliveryplace ) | html %] -
          4. - [% END %] - [% IF basketgroup.billingplace %] -
          5. - Basket group billing place: [% Branches.GetName( basketgroup.billingplace ) | html %] -
          6. - [% END %] -
          - [% END # /IF closeddate %] -
          -
          -
          - [% END # /IF ( basketno ) %] - - [% IF ( duplinbatch ) %] -
          -

          Duplicate warning

          -

          Some records have not been automatically added because they match an existing record in your catalog: Display them

          + + + + + [% ELSE # UNLESS ( closedate ) %] +
          + [% IF grouped %] + + [% ELSE %] +
          +
          + [% INCLUDE 'csrf-token.inc' %] + + + +
          +
          - [% END # /IF ( delete_confirmed ) %] - [% END # /IF ( NO_BOOKSELLER ) %] - [% ELSE %] - - [% END #/IF !confirm_close && !edi_confirm %] + [% PROCESS csv_export %] + [% END %] +
          + [% END # /UNLESS ( closedate ) %] + [% END # /UNLESS ( selectbasketg ) %] - [% IF ( confirm_close ) %] -
          - -
          - [% INCLUDE 'csrf-token.inc' %] -

          Are you sure you want to close basket [% basketname | html %]?

          - [% IF ( CAN_user_acquisition_group_manage ) %] -

          - - -

          + [% IF ( NO_BOOKSELLER ) %] +

          Vendor not found

          + [% ELSE %] + [% IF ( delete_confirmed ) %] +
          +

          Basket deleted

          +
          + [% IF (cannotdelbiblios) %] +
          +

          Warning:

          +

          The following records could not be deleted:

          +
            + [% FOREACH cannotdelbiblio IN cannotdelbiblios %] +
          • + [% cannotdelbiblio.title | html %] by [% cannotdelbiblio.author | html %]: +
              + [% IF (cannotdelbiblio.itemcount) %]
            • [% cannotdelbiblio.itemcount | html %] item(s) attached.
            • [% END %] + [% IF (cannotdelbiblio.subscriptions) %]
            • [% cannotdelbiblio.subscriptions | html %] subscription(s) attached.
            • [% END %] + [% IF (cannotdelbiblio.countbiblio) %]
            • [% cannotdelbiblio.countbiblio | html %] order(s) attached.
            • [% END %] + [% IF (cannotdelbiblio.othererror) %]
            • Unknown error.
            • [% END %] +
            +
          • [% END %] - - - - - - - -
            +
          +
          + Go back to vendor page + [% ELSE %] + Show baskets for vendor [% booksellername | html %] + Show all active baskets + [% END # /IF (cannotdelbiblios) %] + [% ELSE # IF ( delete_confirmed ) %] + + [% FOR m IN messages %] +
          + [% SWITCH m.code %] + [% CASE 'no_email' %] + This vendor has no contact selected for sending orders to or is missing an e-mail address. + [% CASE 'no_basketno' %] + No basket given. + [% CASE 'no_letter' %] + There is no notice template with code ACQORDER defined. + [% CASE 'email_sent' %] + Order e-mail was sent to the vendor. + [% CASE %] + ERROR! - [% m.code | html %] + [% END %] +
          + [% END # /FOR m %] + +

          [% UNLESS ( basketno ) %]New[% END %]Basket [% basketname | html %] ([% basketno | html %]) for [% booksellername | html %]

          + + [% IF ( basketno ) %] +
          +
          +
          +

          General information

          +
            + [% IF ( basketnote ) %] +
          1. Internal note: [% basketnote | html %]
          2. + [% END %] + [% IF ( basketbooksellernote ) %] +
          3. Vendor note: [% basketbooksellernote | html %]
          4. + [% END %] + [% IF ( basketcontractno ) %] +
          5. Contract name: + [% basketcontractname | html %]
          6. + [% END %] + [% IF deliveryplace %] +
          7. Delivery place: [% Branches.GetName( deliveryplace ) | html %]
          8. + [% END %] + [% IF billingplace %] +
          9. Billing place: [% Branches.GetName( billingplace ) | html %]
          10. + [% END %] + [% IF ( authorisedbyname ) %] +
          11. [% tp('basket created by', 'Created by:') | html %] [% authorisedbyname | html %]
          12. + [% END %] + + [% IF ( creationdate ) %] +
          13. Opened on: [% creationdate | $KohaDates %]
          14. + [% END %] + [% IF ( closedate ) %] +
          15. Closed on: [% closedate | $KohaDates %]
          16. + [% END %] + + [% IF ( ediaccount ) %] + [%- BLOCK edi_status -%] + [%- SWITCH edi_order.status -%] + + [%- CASE 'pending' -%] + Pending + [%- CASE 'sent' -%] + Sent + [%- CASE 'processed' -%] + Processed + [%- END -%] + [%- END -%] + [% IF ( edi_order ) %] +
          17. EDI status: [%- PROCESS edi_status edi_order=edi_order -%] ([% edi_order.transfer_date | $KohaDates %])
          18. + [% ELSE %] +
          19. EDI status: Not ordered
          20. + [% END %] + [% END %] + [% IF ( estimateddeliverydate ) %] +
          21. Estimated delivery date: [% estimateddeliverydate | $KohaDates %]
          22. + [% END %] +
          23. Orders are standing: [% IF is_standing %]Yes[% ELSE %]No[% END %]
          24. + + [% IF basket.create_items %] +
          25. + Create items when: + [% SWITCH basket.create_items %] + [% CASE 'receiving' %] + Receiving items + [% CASE 'cataloguing' %] + Cataloguing items + [% CASE %] + Placing orders + [% END %] +
          26. + [% END %] + + [% INCLUDE 'additional-fields-display.inc' available=available_additional_fields values=additional_field_values %] +
          +
          + +
          + + +
          +
          +

          Settings

          + +
            +
          1. + + [% INCLUDE 'csrf-token.inc' %] + [% tp('Acquisitions basket managed by user', 'Managed by:') | html %] +
            +
              + [% FOREACH user IN users %] +
            • + [% user.firstname | html %] [% user.surname | html %] + Delete user +
            • + [% END %] +
            • + Add user +
            • + +
            +
            + + + + +
          2. + +
          3. + Managing library: + [% IF basketbranchcode %] + [% Branches.GetName( basketbranchcode ) | html %] + Change library + [% ELSE %] + No library + Set library + [% END %] +
          4. + + [% IF branches_loop.size %] + + + [% END # /IF branches_loop.size %] +
          + + [% IF ( closedate ) %] +
            +
          1. + Basket group: + [% IF basketgroup.id and not basketgroup.name %] + [% SET basketgroup.name = "Basket group no. " _ basketgroup.id %] + [% END %] + + [% IF basketgroup.closed %] + [% IF ( CAN_user_acquisition_group_manage ) %] + [% basketgroup.name | html %] (closed) + [% ELSE %] + [% basketgroup.name | html %] (closed) + [% END %] + [% ELSIF ( ! CAN_user_acquisition_group_manage ) %] + [%- IF basketgroup.id -%] + [% basketgroup.name | html %] + [%- ELSE -%] + No group + [%- END -%] + [% ELSE %] + [% IF ( CAN_user_acquisition_group_manage ) %] + [% IF ( basketgroup.id ) %] + + [% basketgroup.name | html %] + + Change basket group + [% ELSE %] + No group + Set basket group + [% END %] + [% END %] + [% END %] +
          2. + [% IF ( CAN_user_acquisition_group_manage ) %] + + [% END # /IF ( CAN_user_acquisition_group_manage ) %] + [% IF basketgroup.deliveryplace %] +
          3. Basket group delivery placename: [% Branches.GetName( basketgroup.deliveryplace ) | html %]
          4. + [% END %] + [% IF basketgroup.billingplace %] +
          5. Basket group billing place: [% Branches.GetName( basketgroup.billingplace ) | html %]
          6. + [% END %] +
          + [% END # /IF closeddate %] +
          + +
          + +
          + + [% END # /IF ( basketno ) %] + + [% IF ( duplinbatch ) %] +
          +

          Duplicate warning

          +

          Some records have not been automatically added because they match an existing record in your catalog: Display them

          +
          + [% END %] + + [% IF ( books_loop ) %] +
          +

          Orders

          + + + + + + + + + + + + + + + + + + + + + + + [% IF Koha.Preference('EDIFACT') && ediaccount %] + + [% END %] + + [% IF ( active && !closedate ) %] + + [% END %] + [% IF !closedate || Koha.Preference('CancelOrdersInClosedBaskets') %] + + [% END %] + + + + [% FOREACH foot_loo IN book_foot_loop %] + + + + + + + + + + + + + + + + + + + + + [% IF Koha.Preference('EDIFACT') && ediaccount %] + + [% END %] + + [% IF ( active && !closedate ) %] + + [% END %] + [% IF !closedate || Koha.Preference('CancelOrdersInClosedBaskets') %] + + [% END %] + + [% END %] + + + + + + + + + + + + + + + + + + + + + [% IF Koha.Preference('EDIFACT') && ediaccount %] + + [% END %] + + [% IF ( active && !closedate ) %] + + [% END %] + [% IF !closedate || Koha.Preference('CancelOrdersInClosedBaskets') %] + + [% END %] + + + + [% FOREACH books_loo IN books_loop %] + [% IF ( books_loo.order_received ) %] + [% SET tr_class = "disabled" %] + [% END %] + + + + [% SET zero_regex = "^0{1,}\.?0{1,}[^1-9]" %] [%# 0 or 0.0 or 0.00 or 00 or 00.0 or 00.00 or 0.000 ... %] + [%# FIXME: use of a regexp is not ideal; bugs 9410 and 10929 suggest better way of handling this %] + + + + + + + + + + + + + + + + + + + [% IF Koha.Preference('EDIFACT') && ediaccount %] + + [% END %] + + [% IF ( active && !closedate ) %] + + [% END %] + [% IF ( !closedate || Koha.Preference('CancelOrdersInClosedBaskets') ) %] + + [% END %] + + [% END %] + +
          No.[% tp('noun', 'Order') | html %]RRP tax exc.Actual cost tax exc.Budgeted cost tax exc.RRP tax inc.Actual cost tax inc.Budgeted cost tax inc.Replacement priceQty.Total tax exc. ([% currency | html %])Total tax inc. ([% currency | html %])GST %GSTFundEstimated delivery dateStatistic 1Statistic 2InvoiceSupplier reportPlace holdModifyCancel order
          Total (GST [% foot_loo.tax_rate * 100 | html %])       [% foot_loo.quantity | html %][% foot_loo.total_tax_excluded | $Price %][% foot_loo.total_tax_included | $Price %] [% foot_loo.tax_value | $Price %]         
          Total ([% currency | html %])       [% total_quantity | html %][% total_tax_excluded | $Price %][% total_tax_included | $Price %] [% total_tax_value | $Price %]         
          [% books_loo.ordernumber | html %] +

          + [% IF ( books_loo.order_received ) %](received)[% END %] + [% IF books_loo.title %] + [% INCLUDE 'biblio-title.inc' biblio=books_loo link = 1 %] + [% IF books_loo.author %]by [% books_loo.author | html %][% END %] + [% ELSIF books_loo.deleted_biblio %] + [% INCLUDE 'biblio-title.inc' biblio=books_loo.deleted_biblio %] +
          (Deleted bibliographic record) + [% ELSE %] + Deleted bibliographic record, can't find title
          + [%- END %] +
          + [%- IF ( books_loo.isbn ) %]- [% books_loo.isbn | html %][% END -%] + [%- IF ( books_loo.issn ) %]- [% books_loo.issn | html %][% END -%] + [%- IF ( books_loo.publishercode ) %], [% books_loo.publishercode | html %][% END -%] + [%- IF ( books_loo.publicationyear ) %] + , [% books_loo.publicationyear | html -%] + [%- ELSIF ( books_loo.copyrightdate ) %] + [% books_loo.copyrightdate | html %] + [% END -%] + [%- IF ( books_loo.editionstatement ) %], [% books_loo.editionstatement | html %][% END -%] + [%- IF ( books_loo.suggestionid ) %] +
          + Suggested by: [% books_loo.surnamesuggestedby | html %][% IF ( books_loo.firstnamesuggestedby ) %], [% books_loo.firstnamesuggestedby | html %][% END %] (suggestion #[% books_loo.suggestionid | html %]) + [% END %] +

          + [% IF ( books_loo.order_internalnote ) %] +

          Internal note: [% books_loo.order_internalnote | html %] + Edit internal note

          + [% ELSE %] + Add internal note + [% END %] + [% IF ( books_loo.order_vendornote ) %] +

          Vendor note: [% books_loo.order_vendornote | html %] + Edit vendor note

          + [% ELSE %] + Add vendor note + [% END %] + [% IF (books_loo.transferred_from) %] + [% basket = books_loo.transferred_from.basket %] + [% bookseller = books_loo.transferred_from.bookseller %] + [% timestamp = books_loo.transferred_from.timestamp %] +

          + Transferred from basket: + [% basket.basketname | html %] + ([% bookseller.name | html %]) on + [% timestamp | $KohaDates %] +

          + [% END %] + [% SET claims = books_loo.order_object.claims %] + [% IF claims.count %] +

          This order has been claimed [% claims.count | html %] times. On [% FOR c IN claims %][% c.claimed_on | $KohaDates %][% UNLESS loop.last %],[% END %][% END %]

          + [% END %] +
          + [% books_loo.rrp_tax_excluded | $Price %] [% IF ( books_loo.uncertainprice ) %](Uncertain)[% END %] + [% books_loo.unitprice_tax_excluded | $Price %] [% books_loo.ecost_tax_excluded | $Price %] [% books_loo.rrp_tax_included | $Price %] [% books_loo.unitprice_tax_included | $Price %] [% books_loo.ecost_tax_included | $Price %] [% books_loo.replacementprice | $Price %] [% books_loo.quantity | html %] [% books_loo.total_tax_excluded | $Price %] [% books_loo.total_tax_included | $Price %] [% books_loo.tax_rate * 100 | html %] [% books_loo.tax_value | $Price %] [% books_loo.budget_name | html %] + [% books_loo.estimated_delivery_date | $KohaDates %] + [% IF CAN_user_acquisition_order_manage %] + + Edit + [% END %] + [% AuthorisedValues.GetByCode( books_loo.sort1_authcat, books_loo.sort1 ) | html %][% AuthorisedValues.GetByCode( books_loo.sort2_authcat, books_loo.sort2 ) | html %] + [% IF CAN_user_acquisition_edit_invoices %] + [% books_loo.invoice_object.invoicenumber | html %] + [% ELSE %] + [% books_loo.invoice_object.invoicenumber | html %] + [% END %] + [% books_loo.suppliers_report | html %] + [% IF ( books_loo.biblionumber && CAN_user_reserveforothers_place_holds ) %] + Place hold + [% END %] + + [% UNLESS (books_loo.order_received) %] + Modify +
          + Transfer + [% END %] +
          + [% IF ( books_loo.orderstatus != "complete") %] + [% IF ( books_loo.left_holds_on_order ) %] + Can't cancel order
          + [% ELSE %] + Cancel order
          + [% END %] + [% IF ( books_loo.can_del_bib ) %] + Cancel order and delete catalog record
          + [% ELSE %] + Can't cancel order and delete catalog record
          + [% END %] + [% IF ( books_loo.left_item ) %] + [% books_loo.items | html %] item(s) left
          + [% END %] + [% IF ( books_loo.left_biblio ) %] + [% books_loo.biblios | html %] order(s) left
          + [% END %] + [% IF ( books_loo.left_subscription ) %] + [% books_loo.subscriptions | html %] subscription(s) left
          + [% END %] + [% IF ( books_loo.left_holds ) %] + [% books_loo.holds | html %] hold(s) left + [% END %] + [% END %] +
          + + [% IF ( listincgst ) %]** Vendor's listings already include tax.[% END %] +
          + + [% END # / IF ( books_loop ) %] + + [% IF (cancelledorders_loop) %] +
          +

          Cancelled orders

          + + + + + + + + + + + + + + + + + + + + + [% FOREACH order IN cancelledorders_loop %] + + + + + + + + + + + + + + + + + [% END # /FOREACH order %] + +
          No.[% tp('noun', 'Order') | html %]RRP tax exc.ecost tax exc.RRP tax inc.ecost tax inc.Replacement priceQty.Total tax exc. ([% currency | html %])Total tax inc. ([% currency | html %])GST %GSTFundDelete order
          [% order.ordernumber | html %] +

          + [% IF ( order.order_received ) %](received)[% END %] + [% IF (order.title) %] + [% order.title | html %][% IF order.author %]by [% order.author | html %][% END %] + [% ELSIF order.deleted_biblio %] + [% INCLUDE 'biblio-title.inc' biblio=order.deleted_biblio %] +
          (Deleted bibliographic record) + [% ELSE %] + Deleted bibliographic record, can't find title + [% END %] +
          + [% IF ( order.order_internalnote ) %][% order.order_internalnote | html %][% END %] + [% IF ( order.isbn ) %]- [% order.isbn | html %][% END %] + [% IF ( order.issn ) %]- [% order.issn | html %][% END %] + [% IF ( order.publishercode ) %], [% order.publishercode | html %][% END %] + [% IF ( order.publicationyear ) %] + , [% order.publicationyear | html %] + [% ELSIF ( order.copyrightdate ) %] + [% order.copyrightdate | html %] + [% END %] + [% IF ( books_loo.editionstatement ) %], [% books_loo.editionstatement | html %][% END %] + [% IF ( order.cancellationreason ) %] +
          + Cancellation reason: [% AuthorisedValues.GetByCode( 'ORDER_CANCELLATION_REASON', order.cancellationreason ) | html %] + [% END %] +

          + [% IF order.transferred_to %] + [% basket = order.transferred_to.basket %] + [% bookseller = order.transferred_to.bookseller %] + [% timestamp = order.transferred_to.timestamp %] +

          Transferred to basket: + [% basket.basketname | html %] + ([% bookseller.name | html %]) on + [% timestamp | $KohaDates %] +

          + [% END %] +
          + [% order.rrp_tax_excluded | $Price %] + [% IF ( order.uncertain ) %] + (Uncertain) + [% END %] + [% order.ecost_tax_excluded | $Price %][% order.rrp_tax_included | $Price %][% order.ecost_tax_included | $Price %][% order.replacementprice | $Price %][% order.quantity | html %][% order.total_tax_excluded | $Price %][% order.total_tax_included | $Price %][% order.tax_rate * 100 | html %][% order.tax_value | $Price %][% order.budget_name | html %] [% UNLESS closedate %]Delete[% END %]
          + +
          + [% INCLUDE 'csrf-token.inc' %] + + -
          - [% END # /IF ( confirm_close ) %] + + [% END # /IF (cancelledorders_loop) %] +
          - [% IF edi_confirm %] -
          -
          - [% INCLUDE 'csrf-token.inc' %] -

          Are you sure you want to generate an EDIFACT order and close basket [% basketname | html %]?

          - [% IF CAN_user_acquisition_group_manage %] -

          - - -

          - [% END %] - - - - - - - -
          -
          - - -
          -
          - [% END # /IF edi_confirm %] - [% END # /IF (cannot_manage_basket) %] + [% UNLESS ( closedate ) %] + + + [% END # /UNLESS ( closedate ) %] + [% END # /IF ( delete_confirmed ) %] + [% END # /IF ( NO_BOOKSELLER ) %] + [% ELSE %] + + [% END #/IF !confirm_close && !edi_confirm %] + + [% IF ( confirm_close ) %] +
          +
          + [% INCLUDE 'csrf-token.inc' %] +

          Are you sure you want to close basket [% basketname | html %]?

          + [% IF ( CAN_user_acquisition_group_manage ) %] +

          + + +

          + [% END %] + + + + + + +
          +
          + + +
          +
          + [% END # /IF ( confirm_close ) %] + + [% IF edi_confirm %] +
          +
          + [% INCLUDE 'csrf-token.inc' %] +

          Are you sure you want to generate an EDIFACT order and close basket [% basketname | html %]?

          + [% IF CAN_user_acquisition_group_manage %] +

          + + +

          + [% END %] + + + + + + + +
          +
          + + +
          +
          + + [% END # /IF edi_confirm %] + [% END # /IF (cannot_manage_basket) %] [% END %] - - + + + - - + + + [% MACRO jsinclude BLOCK %] [% Asset.js("js/acquisitions-menu.js") | $raw %] @@ -1099,7 +1185,6 @@ }); }); - [% UNLESS ( closedate ) %] - [% INCLUDE 'select2.inc' %] [% SET columns = ['cardnumber','name','category','branch','action'] %] [% SET filter = 'baskets_managers' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/acqui/basketgroup.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/acqui/basketgroup.tt index 13f598f899..ae0fa3423f 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/acqui/basketgroup.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/acqui/basketgroup.tt @@ -6,10 +6,12 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% tx("Basket grouping for '{vendor}'", { vendor = booksellername }) %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% tx("Basket grouping for '{vendor}'", { vendor = booksellername }) %] + › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -47,304 +49,349 @@ [% SET asides = ['acquisitions-menu'] %] [% IF booksellerid %][% asides.unshift('vendor-menu') %][% END %] [% WRAPPER 'main-container.inc' asides=asides %] - [% IF ( grouping ) %] - [% IF (closedbg) %] - - [% END %] - [% IF (name && closedbg) %] -

          Basket group [% name | html %] ([% basketgroupid | html %]) for [% booksellername | html %]

          - [% ELSIF (name) %] -

          Edit basket group [% name | html %] ([% basketgroupid | html %]) for [% booksellername | html %]

          - [% ELSE %] -

          Add basket group for [% booksellername | html %]

          - [% END %] -
          - [% UNLESS (closedbg) %] -
          -
          -
          -

          Ungrouped baskets

          -
          - - - - - - - - - - [% IF ( baskets ) %] - [% FOREACH basket IN baskets %] - - - - - - [% END %] - [% END %] - -
          BasketTotal
          - - [% IF ( basket.basketname ) %] - [% basket.basketname | html %] - [% ELSE %] - No name, basketnumber: [% basket.basketno | html %] - [% END %] - - - [% basket.total | $Price %] - - - - Add to group - -
          -
          -
          -
          -
          - [% END %] - [% IF ( closedbg ) %] - [% SET div_class="col" %] - [% ELSE %] - [% SET div_class="col-sm-6 order-sm-1" %] - [% END %] -
          -
          - [% INCLUDE 'csrf-token.inc' %] -
          - [% UNLESS (closedbg) %] -
            -
          1. - - -
          2. -
          3. - - -
          4. -
          5. - - -
          6. -
          -

          or

          -
            -
          1. - - -
          2. -
          3. - - -
          4. -
          - [% ELSE %] - -
            -
          1. - Delivery place: - [% IF (freedeliveryplace) %] - [% freedeliveryplace | html %] - - [% ELSE %] - [% Branches.GetName( deliveryplace ) | html %] - - [% END %] -
          2. -
          - [% END %] -

          Baskets in this group:

          - - - - - - - - - - [% FOREACH selectedbasket IN selectedbaskets %] - - - - - - [% END %] - -
          BasketTotal
          - - [% IF ( selectedbasket.basketname ) %] - [% selectedbasket.basketname | html %] - [% ELSE %] - No name, basketnumber: [% selectedbasket.basketno | html %] - [% END %] - - - [% selectedbasket.total | $Price %] - - - [% IF ( closedbg ) %] - [% ELSE %] - - Remove - - [% END %] -
          - [% UNLESS (closedbg) %] -
            -
          1. -
          - [% ELSE %] - - [% END %] -
          - - [% UNLESS (closedbg) %] -
          - [% IF ( basketgroupid ) %] - - [% END %] - - Cancel -
          - [% END %] -
          -
          -
          - [% ELSE %] - -

          Basket grouping for [% booksellername | html %]

          - [% IF (NoEDIMessage && Koha.Preference('EDIFACT')) %]
          No EDIFACT configuration for [% booksellername | html %]
          [% END %] - - [% WRAPPER tabs id= "basket_groups" %] - [% WRAPPER tabs_nav %] - [% WRAPPER tab_item tabname= "opened" bt_active= 1 %] Open [% END %] - [% WRAPPER tab_item tabname= "closed" %] Closed [% END %] - [% END %] - [% WRAPPER tab_panels %] - [% WRAPPER tab_panel tabname="opened" bt_active= 1 %] - - - - - - - - - - - - - [% FOREACH basketgroup IN basketgroups %] - [% UNLESS ( basketgroup.closed ) %] - - - - - - - - - [% END %] - [% END %] - -
          NameNumberBilling placeDelivery placeNumber of basketsAction
          - [% IF ( basketgroup.name ) %] - [% basketgroup.name | html %] - [% ELSE %] - Basket group no. [% basketgroup.id | html %] - [% END %] - [% basketgroup.id | html %][% Branches.GetName( basketgroup.billingplace ) | html %][% IF (basketgroup.freedeliveryplace) %]Free delivery place[% ELSE %][% Branches.GetName( basketgroup.deliveryplace ) | html %][% END %][% basketgroup.basketsqty | html %] - -
          - - - - -
          - [% UNLESS basketgroup.basketsqty %] -
          - - - - - [% INCLUDE 'csrf-token.inc' %] -
          - [% END %] -
          - [% END #/opened %] - - [% WRAPPER tab_panel tabname="closed" %] - - - - - - - - - - - - - [% FOREACH basketgroup IN basketgroups %] - [% IF ( basketgroup.closed ) %] - - - - - - - - - [% END %] - [% END %] - -
          NameNumberBilling placeDelivery placeNumber of basketsAction
          - [% IF ( basketgroup.name ) %] - [% basketgroup.name | html %] - [% ELSE %] - Basket group no. [% basketgroup.id | html %] - [% END %] - [% basketgroup.id | html %][% Branches.GetName( basketgroup.billingplace ) | html %][% IF (basketgroup.freedeliveryplace) %]Free delivery place[% ELSE %][% Branches.GetName( basketgroup.deliveryplace ) | html %][% END %][% basketgroup.basketsqty | html %] -
          -
          - [% INCLUDE 'csrf-token.inc' %] -
          -
          -
          - [% IF Koha.Preference('EDIFACT') %] - [% IF (ediaccount) %] -
          - [% INCLUDE 'csrf-token.inc' %] -
          - [% ELSE %] -
          No EDIFACT configuration for [% booksellername | html %]
          - [% END %] - [% END %] -
          - [% END #/closed %] - [% END # /WRAPPER tab_panels %] - [% END # /#basket_groups %] + [% IF ( grouping ) %] + [% IF (closedbg) %] + + [% END %] + [% IF (name && closedbg) %] +

          Basket group [% name | html %] ([% basketgroupid | html %]) for [% booksellername | html %]

          + [% ELSIF (name) %] +

          Edit basket group [% name | html %] ([% basketgroupid | html %]) for [% booksellername | html %]

          + [% ELSE %] +

          Add basket group for [% booksellername | html %]

          + [% END %] +
          + [% UNLESS (closedbg) %] +
          +
          +
          +

          Ungrouped baskets

          +
          + + + + + + + + + + [% IF ( baskets ) %] + [% FOREACH basket IN baskets %] + + + + + + [% END %] + [% END %] + +
          BasketTotal
          + + [% IF ( basket.basketname ) %] + [% basket.basketname | html %] + [% ELSE %] + No name, basketnumber: [% basket.basketno | html %] + [% END %] + + + [% basket.total | $Price %] + + + Add to group +
          +
          +
          + [% END %] + [% IF ( closedbg ) %] + [% SET div_class="col" %] + [% ELSE %] + [% SET div_class="col-sm-6 order-sm-1" %] + [% END %] +
          +
          + [% INCLUDE 'csrf-token.inc' %] +
          + [% UNLESS (closedbg) %] +
            +
          1. + + +
          2. +
          3. + + +
          4. +
          5. + + +
          6. +
          +

          or

          +
            +
          1. + + +
          2. +
          3. + + +
          4. +
          + [% ELSE %] + +
            +
          1. + Delivery place: + [% IF (freedeliveryplace) %] + [% freedeliveryplace | html %] + + [% ELSE %] + [% Branches.GetName( deliveryplace ) | html %] + + [% END %] +
          2. +
          + [% END %] +

          Baskets in this group:

          + + + + + + + + + + [% FOREACH selectedbasket IN selectedbaskets %] + + + + + + [% END %] + +
          BasketTotal
          + + [% IF ( selectedbasket.basketname ) %] + [% selectedbasket.basketname | html %] + [% ELSE %] + No name, basketnumber: [% selectedbasket.basketno | html %] + [% END %] + + + [% selectedbasket.total | $Price %] + + + [% IF ( closedbg ) %] + [% ELSE %] + + Remove + + [% END %] +
          + [% UNLESS (closedbg) %] +
            +
          1. +
          + [% ELSE %] + + [% END %] +
          + + [% UNLESS (closedbg) %] +
          + [% IF ( basketgroupid ) %] + + [% END %] + + Cancel +
          + [% END %] +
          +
          + +
          + + [% ELSE %] + +

          Basket grouping for [% booksellername | html %]

          + [% IF (NoEDIMessage && Koha.Preference('EDIFACT')) %]
          No EDIFACT configuration for [% booksellername | html %]
          [% END %] + + [% WRAPPER tabs id= "basket_groups" %] + [% WRAPPER tabs_nav %] + [% WRAPPER tab_item tabname= "opened" bt_active= 1 %]Open[% END %] + [% WRAPPER tab_item tabname= "closed" %]Closed[% END %] + [% END %] + [% WRAPPER tab_panels %] + [% WRAPPER tab_panel tabname="opened" bt_active= 1 %] + + + + + + + + + + + + + [% FOREACH basketgroup IN basketgroups %] + [% UNLESS ( basketgroup.closed ) %] + + + + + + + + + [% END %] + [% END %] + +
          NameNumberBilling placeDelivery placeNumber of basketsAction
          + [% IF ( basketgroup.name ) %] + [% basketgroup.name | html %] + [% ELSE %] + Basket group no. [% basketgroup.id | html %] + [% END %] + [% basketgroup.id | html %][% Branches.GetName( basketgroup.billingplace ) | html %][% IF (basketgroup.freedeliveryplace) %]Free delivery place[% ELSE %][% Branches.GetName( basketgroup.deliveryplace ) | html %][% END %][% basketgroup.basketsqty | html %] + +
          + + + + +
          + [% UNLESS basketgroup.basketsqty %] +
          + + + + + [% INCLUDE 'csrf-token.inc' %] +
          + [% END %] +
          + [% END #/opened %] + + [% WRAPPER tab_panel tabname="closed" %] + + + + + + + + + + + + + [% FOREACH basketgroup IN basketgroups %] + [% IF ( basketgroup.closed ) %] + + + + + + + + + [% END %] + [% END %] + +
          NameNumberBilling placeDelivery placeNumber of basketsAction
          + [% IF ( basketgroup.name ) %] + [% basketgroup.name | html %] + [% ELSE %] + Basket group no. [% basketgroup.id | html %] + [% END %] + [% basketgroup.id | html %][% Branches.GetName( basketgroup.billingplace ) | html %][% IF (basketgroup.freedeliveryplace) %]Free delivery place[% ELSE %][% Branches.GetName( basketgroup.deliveryplace ) | html %][% END %][% basketgroup.basketsqty | html %] +
          +
          + [% INCLUDE 'csrf-token.inc' %] +
          +
          +
          + [% IF Koha.Preference('EDIFACT') %] + [% IF (ediaccount) %] +
          + [% INCLUDE 'csrf-token.inc' %] +
          + [% ELSE %] +
          No EDIFACT configuration for [% booksellername | html %]
          + [% END %] + [% END %] +
          + [% END #/closed %] + [% END # /WRAPPER tab_panels %] + [% END # /#basket_groups %] + [% END %] [% END %] [% MACRO jsinclude BLOCK %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/acqui/basketheader.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/acqui/basketheader.tt index 90d966277b..5bbf5da8e3 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/acqui/basketheader.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/acqui/basketheader.tt @@ -5,17 +5,18 @@ [% SET footerjs = 1 %] [% PROCESS 'i18n.inc' %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% IF ( add_form ) %] - [% IF ( basketno ) %] - [% tx("Edit basket '{basketname}'", { basketname = basketname }) | html %] - [% ELSE %] - [% tx("Add basket to {vendor}", { vendor = booksellername }) | html %] +<title + >[% FILTER collapse %] + [% IF ( add_form ) %] + [% IF ( basketno ) %] + [% tx("Edit basket '{basketname}'", { basketname = basketname }) | html %] + [% ELSE %] + [% tx("Add basket to {vendor}", { vendor = booksellername }) | html %] + [% END %] [% END %] - [% END %] › - [% t("Acquisitions") | html %] › - [% t("Koha") | html %] -[% END %] + › [% t("Acquisitions") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -34,11 +35,11 @@ [% END %] [% IF ( add_form ) %] [% IF ( basketno ) %] - [% WRAPPER breadcrumb_item bc_active= 1%] + [% WRAPPER breadcrumb_item bc_active= 1 %] Edit basket '[% basketname | html %]' [% END %] [% ELSE %] - [% WRAPPER breadcrumb_item bc_active= 1%] + [% WRAPPER breadcrumb_item bc_active= 1 %] Add a basket to [% booksellername | html %] [% END %] [% END %] @@ -51,109 +52,114 @@ [% IF ( add_form ) %] [% IF ( basketno ) %]

          Edit basket [% basketname | html %]

          - [% ELSE %]

          Add a basket to [% booksellername | html %]

          + [% ELSE %] +

          Add a basket to [% booksellername | html %]

          [% END %] -
          - [% INCLUDE 'csrf-token.inc' %] - -
          -
            - [% IF ( basketno ) %] + + [% INCLUDE 'csrf-token.inc' %] + +
            +
              + [% IF ( basketno ) %] +
            1. + + +
            2. + [% END %]
            3. - - + + + Required
            4. - [% END %] -
            5. - - - Required -
            6. -
            7. - - -
            8. -
            9. - - -
            10. -
            11. - - -
            12. -
            13. - - -
            14. -
            15. - - -
            16. - [% IF ( contractloop ) %] -
            17. - + + [% PROCESS options_for_libraries libraries => Branches.all( selected => billingplace ) %]
            18. - [% END %] -
            19. - - [% IF is_standing %] - - [% ELSE %] - +
            20. + + +
            21. +
            22. + + +
            23. +
            24. + + +
            25. +
            26. + + +
            27. + [% IF ( contractloop ) %] +
            28. + +
            29. [% END %] -
              Standing orders do not close when received.
              - - [% IF basketno %] - - [% ELSE %] -
            30. - - + [% ELSE %] + [% END %] - - - - -
            31. - [% END %] -
            -
            +
            Standing orders do not close when received.
            + + [% IF basketno %] + + [% ELSE %] +
          1. + + +
          2. + [% END %] +
          +
          - [% IF available_additional_fields.count %] - [% INCLUDE 'additional-fields-entry.inc' available=available_additional_fields values=additional_field_values %] - [% END %] - -
          - - - [% IF ( basketno ) %] - Cancel - [% ELSE %] - Cancel + [% IF available_additional_fields.count %] + [% INCLUDE 'additional-fields-entry.inc' available=available_additional_fields values=additional_field_values %] [% END %] -
          -
          + +
          + + + [% IF ( basketno ) %] + Cancel + [% ELSE %] + Cancel + [% END %] +
          + [% END %] [% END %] @@ -162,53 +168,49 @@ [% Asset.js("js/acq.js") | $raw %] [% Asset.js("js/additional-fields-entry.js") | $raw %] [% INCLUDE 'select2.inc' %] - + + $("#basketbooksellerid").kohaSelect({ + width: "50%", + allowClear: false, + ajax: { + url: "/api/v1/acquisitions/vendors", + delay: 300, // wait 300 milliseconds before triggering the request + cache: true, + dataType: "json", + data: function (params) { + var search_term = params.term === undefined ? "" : params.term; + var query = { + q: JSON.stringify({ name: { "-like": "%" + search_term + "%" } }), + _order_by: "name", + _page: params.page, + }; + + return query; + }, + processResults: function (data) { + var results = []; + data.results.forEach(function (vendor) { + results.push({ + id: vendor.id, + text: vendor.name.escapeHtml(), + }); + }); + return { results: results, pagination: { more: data.pagination.more } }; + }, + }, + templateResult: display_vendor, + templateSelection: display_vendor, + }); + }); + [% END %] [% INCLUDE 'intranet-bottom.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/acqui/booksellers.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/acqui/booksellers.tt index 60d9d3e5a3..5cb331c2a4 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/acqui/booksellers.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/acqui/booksellers.tt @@ -7,15 +7,17 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% tx("Search for vendor {vendor}", { vendor = supplier }) | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% tx("Search for vendor {vendor}", { vendor = supplier }) | html %] + › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -39,44 +41,45 @@ [% IF booksellerid %][% asides.unshift('vendor-menu') %][% END %] [% WRAPPER 'main-container.inc' asides=asides %] -[% INCLUDE 'acquisitions-toolbar.inc' %] -[% UNLESS ( count == 1 ) %] - [% UNLESS count %] -

          Your vendor search returned no results.

          - [% ELSIF ( supplier.length < 1 ) %] -

          Vendor search: [% count | html %] results found

          - [% ELSE %] -

          Vendor search: [% count | html %] results found for '[% supplier | html %]'

          - [% END %] -[% END %] -[% IF ( loop_suppliers.size ) %] - [% UNLESS (count == 1) %] -

          Choose a vendor in the list to jump directly to the right place. - -

          - [% IF ( allbaskets ) %] - Show active baskets only + [% INCLUDE 'acquisitions-toolbar.inc' %] + [% UNLESS ( count == 1 ) %] + [% UNLESS count %] +

          Your vendor search returned no results.

          + [% ELSIF ( supplier.length < 1 ) %] +

          Vendor search: [% count | html %] results found

          [% ELSE %] - Show all baskets +

          Vendor search: [% count | html %] results found for '[% supplier | html %]'

          [% END %] [% END %] - [% UNLESS booksellerid %] - | Show active vendors onlyShow all vendors - [% END %] -
          - [% FOREACH supplier IN loop_suppliers %] - [% UNLESS supplier.active %] - [% SET div_class="inactive" %] + [% IF ( loop_suppliers.size ) %] + [% UNLESS (count == 1) %] +

          Choose a vendor in the list to jump directly to the right place. + +

          + [% IF ( allbaskets ) %] + Show active baskets only + [% ELSE %] + Show all baskets [% END %] -
          - [% IF ( supplier.active ) %] - [% SET h2_class="inactive" %] + [% END %] + [% UNLESS booksellerid %] + | Show active vendors onlyShow all vendors + [% END %] +
          + [% FOREACH supplier IN loop_suppliers %] + [% UNLESS supplier.active %] + [% SET div_class="inactive" %] [% END %] -

          +
          + [% IF ( supplier.active ) %] + [% SET h2_class="inactive" %] + [% END %] +

          [% IF (supplier.name) %] [% supplier.name | html %] @@ -85,162 +88,173 @@ [% END %] [% IF (supplier.vendor_type) %]([% AuthorisedValues.GetByCode( 'VENDOR_TYPE', supplier.vendor_type ) | html %])[% END %] - [% IF ( !supplier.active ) %](inactive)[% END %] -

          - - [% IF ( count > 1 ) %] - [% supplier.basketcount | html %] [% tn('basket', 'baskets', supplier.basketcount) | $raw %], + [% IF ( !supplier.active ) %](inactive)[% END %] +

          + + [% IF ( count > 1 ) %] + [% supplier.basketcount | html %] [% tn('basket', 'baskets', supplier.basketcount) | $raw %], + [% ELSE %] + [% supplier.basketcount | html %] + [% tn('basket', 'baskets', supplier.basketcount) | $raw %], + [% END %] + [% IF supplier.subscriptioncount > 0 %] + + [% supplier.subscriptioncount | html %] [% tn('subscription', 'subscriptions', supplier.subscriptioncount) | $raw %] + + [% ELSE %] + [% supplier.subscriptioncount | html %] + [% tn('subscription', 'subscriptions', supplier.subscriptioncount) | $raw %] + [% END %] + + [% IF ( count == 1 ) %] + [% IF ( supplier.basketcount > 0 ) %] +
          + [% IF ( allbaskets ) %] + Show active baskets only + [% ELSE %] + Show all baskets + [% END %] +
          + [% END %] [% ELSE %] - [% supplier.basketcount | html %] [% tn('basket', 'baskets', supplier.basketcount) | $raw %], + [% INCLUDE "acquisitions-toolbar.inc" booksellerid=supplier.booksellerid active=supplier.active basketcount=supplier.loop_basket.size basketcount=supplier.basketcount subscriptioncount=supplier.subscriptioncount %] [% END %] - [% IF supplier.subscriptioncount > 0 %] - - [% supplier.subscriptioncount | html %] [% tn('subscription', 'subscriptions', supplier.subscriptioncount) | $raw %] - - [% ELSE %] - [% supplier.subscriptioncount | html %] [% tn('subscription', 'subscriptions', supplier.subscriptioncount) | $raw %] - [% END %] - - [% IF ( count == 1 ) %] - [% IF ( supplier.basketcount > 0 ) %] -
          - [% IF ( allbaskets ) %] - Show active baskets only - [% ELSE %] - Show all baskets - [% END %] -
          - [% END %] - [% ELSE %] - [% INCLUDE "acquisitions-toolbar.inc" booksellerid=supplier.booksellerid active=supplier.active basketcount=supplier.loop_basket.size basketcount=supplier.basketcount subscriptioncount=supplier.subscriptioncount %] - [% END %] -
          - [% IF ( supplier.loop_basket.size ) %] - - - - - - - - - - - - - - - - - - [% FOREACH basket IN supplier.loop_basket %] - [% IF ( basket.uncertainprices ) %] - [% SET tr_class="problem" %] - [% END %] - - - - - - - - - - - - +
          + [% IF ( supplier.loop_basket.size ) %] +
          No.NameItem countBibliographic record countItems expected[% tp('basket created by', 'Created by') | html %]DateBasket groupInternal noteClosedActions
          [% basket.basketno | html %][% basket.basketname | html %] - [% basket.total_items | html %] - [% IF basket.total_items_cancelled %] - ([% basket.total_items_cancelled | html %] cancelled) - [% END %] - - [% basket.total_biblios | html %] - [% IF basket.total_biblios_cancelled %] - ([% basket.total_biblios_cancelled | html %] cancelled) - [% END %] - [% basket.expected_items | html %] - [% IF basket.authorisedby %] - [% basket.authorisedby.firstname | html %] - [% basket.authorisedby.surname | html %] - [% END %] - [% basket.creationdate | $KohaDates %] - [% IF basket.basketgroup %] - [% basketgroup = basket.basketgroup %] - [% IF basketgroup.closed %] - [% basketgroup.name | html %] (closed) - [% ELSE %] - [% basketgroup.name | html %] - [% END %] - [% END %] - - [% basket.note | html %] - - [% basket.closedate | $KohaDates %] - - [% IF not basket.closedate and supplier.active %] - [% IF basket.uncertainprices OR ( basket.total_items && !basket.is_standing ) %] -
          - [%# There should be no space between these two buttons, it would render badly %] - Add to basket - - -
          - [% ELSE %] - Add to basket - [% END %] - - - [% END %] -
          + + + + + + + + + + + + + - [% END %][%# FOREACH basket IN supplier.loop_basket %] - -
          No.NameItem countBibliographic record countItems expected[% tp('basket created by', 'Created by') | html %]DateBasket groupInternal noteClosedActions
          - - [% ELSE %] -

          - No pending baskets. - [% IF ( supplier.basketcount > 0 && count > 1 ) %] - View all baskets. - [% END %] -

          - - [% END %][%# IF ( supplier.loop_basket.size ) %] + + + [% FOREACH basket IN supplier.loop_basket %] + [% IF ( basket.uncertainprices ) %] + [% SET tr_class="problem" %] + [% END %] + + [% basket.basketno | html %] + [% basket.basketname | html %] + + [% basket.total_items | html %] + [% IF basket.total_items_cancelled %] + ([% basket.total_items_cancelled | html %] cancelled) + [% END %] + + + [% basket.total_biblios | html %] + [% IF basket.total_biblios_cancelled %] + ([% basket.total_biblios_cancelled | html %] cancelled) + [% END %] + + [% basket.expected_items | html %] + + [% IF basket.authorisedby %] + [% basket.authorisedby.firstname | html %] + [% basket.authorisedby.surname | html %] + [% END %] + + [% basket.creationdate | $KohaDates %] + + [% IF basket.basketgroup %] + [% basketgroup = basket.basketgroup %] + [% IF basketgroup.closed %] + [% basketgroup.name | html %] (closed) + [% ELSE %] + [% basketgroup.name | html %] + [% END %] + [% END %] + + [% basket.note | html %] + [% basket.closedate | $KohaDates %] + + [% IF not basket.closedate and supplier.active %] + [% IF basket.uncertainprices OR ( basket.total_items && !basket.is_standing ) %] +
          + [%# There should be no space between these two buttons, it would render badly %] + Add to basket + + +
          + [% ELSE %] + Add to basket + [% END %] + + + [% END %] + + + [% END %][%# FOREACH basket IN supplier.loop_basket %] + + + [% ELSE %] +

          + No pending baskets. + [% IF ( supplier.basketcount > 0 && count > 1 ) %] + View all baskets. + [% END %] +

          + [% END %][%# IF ( supplier.loop_basket.size ) %] +
          -
          - [% END %][%# FOREACH supplier IN loop_suppliers %] -
          -[% END %][%# IF ( loop_suppliers.size ) %] - + [% END %][%# FOREACH supplier IN loop_suppliers %] +
          + [% END %][%# IF ( loop_suppliers.size ) %] [% END %] [% MACRO jsinclude BLOCK %] @@ -248,36 +262,36 @@ [% INCLUDE 'datatables.inc' %] [% Asset.js("js/acq.js") | $raw %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/acqui/invoice.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/acqui/invoice.tt index ed7f20a19b..80c36d5c7c 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/acqui/invoice.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/acqui/invoice.tt @@ -7,19 +7,20 @@ [% USE AuthorisedValues %] [% PROCESS 'i18n.inc' %] [% BLOCK fund_dropdown %] - -
          -
          +
          + +
          + +
          + +
          +
          -
          +
          + [% MACRO jsinclude BLOCK %] [% Asset.js("js/acquisitions-menu.js") | $raw %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/acqui/invoices.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/acqui/invoices.tt index 10b906bd3e..bb62e0d764 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/acqui/invoices.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/acqui/invoices.tt @@ -7,11 +7,12 @@ [% SET footerjs = 1 %] [% PROCESS 'i18n.inc' %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Invoices") | html %] › - [% t("Acquisitions") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Invoices") | html %] + › [% t("Acquisitions") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -46,11 +47,12 @@ [% ELSE %] [% SET tab = 'opened' %] [% END %] - - -

          Select all | Clear all

          + + +

          Select all | + Clear all

          @@ -70,19 +72,23 @@ [% FOREACH invoice IN invoices %] - + [% IF CAN_user_acquisition_merge_invoices %] [% END %] - - + + [% END # /FOREACH invoice %] -
          [% invoice.is_linked_to_subscriptions | html %] [% invoice.invoicenumber | html %] [% invoice.suppliername | html %] - [% invoice.shipmentdate | $KohaDates %] - - [% invoice.billingdate | $KohaDates %] - [% invoice.shipmentdate | $KohaDates %] [% invoice.billingdate | $KohaDates %] [% invoice.receivedbiblios | html %] [% invoice.receiveditems | html %] @@ -93,42 +99,92 @@ [% END %] -
          - - Actions - + Actions -
          + +
          + + [% IF CAN_user_acquisition_merge_invoices %] [% IF tab == 'closed' %] Merge selected invoices - Reopen selected invoices - [% ELSE %] + Reopen selected invoices + [% ELSE %] Merge selected invoices - Close selected invoices + Close selected invoices [% END # /IF tab == 'closed' %] [% END # /IF CAN_user_acquisition_merge_invoices %] [% END # /BLOCK invoices_table %] @@ -181,12 +237,10 @@ Shipment cost - - + -
        • @@ -219,21 +273,23 @@
        • -
        • - Status: -
        • +
        • Status:
        • - - -
          + + + + + + [% ELSE # IF invoices %]

          Sorry, but there are no results for your search.

          -
          Search was: +
          Search was:
            [% IF ( invoicenumber ) %]
          • Invoice number: [% invoicenumber | html %]
          • @@ -253,10 +309,7 @@ [% ELSE %] [% IF shipmentdateto %] -
          • - Shipment date: - All until [% shipmentdateto | $KohaDates %] -
          • +
          • Shipment date: All until [% shipmentdateto | $KohaDates %]
          • [% END %] [% END %] [% IF billingdatefrom %] @@ -271,10 +324,7 @@ [% ELSE %] [% IF billingdateto %] -
          • - Billing date: - All until [% billingdateto | $KohaDates %] -
          • +
          • Billing date: All until [% billingdateto | $KohaDates %]
          • [% END %] [% END %] [% IF ( isbneanissn ) %] @@ -302,7 +352,8 @@

            Use the search form on the left to find invoices.

            [% END %] -
          +
          +
          -
          - - + + + + + + [% MACRO jsinclude BLOCK %] [% Asset.js("js/acquisitions-menu.js") | $raw %] @@ -426,146 +480,169 @@ [% INCLUDE 'select2.inc' %] [% INCLUDE 'js-date-format.inc' %] [% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/acqui/lateorders.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/acqui/lateorders.tt index 154eb08418..e26799d977 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/acqui/lateorders.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/acqui/lateorders.tt @@ -8,11 +8,12 @@ [% SET footerjs = 1 %] [% PROCESS 'i18n.inc' %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Late orders") | html %] › - [% t("Acquisitions") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Late orders") | html %] + › [% t("Acquisitions") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -38,246 +39,286 @@
          [% INCLUDE 'messages.inc' %] -

          [% IF bookseller_filter %][% bookseller_filter.name | html %] : [% END %]Late orders

          -
          - -[% IF error_claim %] - [% IF ( error_claim == "no_email" ) %] -
          This vendor has no email
          - [% ELSIF ( error_claim == "no_order_selected" ) %] -
          No order selected
          - [% ELSE %] -
          [% error_claim | html %]
          - [% END %] -[% END %] -[% IF info_claim %] -
          Email has been sent.
          -[% END %] -[% IF lateorders.size %] -
          - [% INCLUDE 'csrf-token.inc' %] - - - - [% IF ( letters ) %] -

          -

          - [% END %] - [% SET total = 0 %] - [% SET total_quantity = 0 %] - [% IF bookseller_filter %] -

          Check all Uncheck all

          - [% END %] - - - - - - - - - - - - - - - - - - - - - - - - - - [% FOREACH lateorder IN lateorders %] - - - - - [% IF lateorder.get_column('estimated_delivery_date') %] - [% SET estimated_delivery_date = lateorder.get_column('estimated_delivery_date') %] - [% ELSIF lateorder.get_column('calculated_estimated_delivery_date') %] - [% SET estimated_delivery_date = lateorder.get_column('calculated_estimated_delivery_date') %] - [% END %] - - - - - - - - - - - - - - - - - - [% END %] - - - - - - - - - -
          Order lineOrder dateEstimated delivery dateVendorInformationQuantityTotal costBasketBasket dateBasket groupLibraryBudgetFundClaims countClaimed dateInternal noteVendor noteISBN
          - - - [% lateorder.ordernumber | $raw %] - - [% lateorder.basket.closedate | $KohaDates %] ([% lateorder.basket.late_since_days | html %] days) - -

          - [% estimated_delivery_date | $KohaDates %] - [% IF CAN_user_acquisition_order_manage %] - - Edit - - [% END %] -

          -
          - [% lateorder.basket.bookseller.name | html %] - ([% lateorder.basket.bookseller.id | html %]) - - [% INCLUDE 'biblio-title.inc' biblio=lateorder.biblio link=1 %] - [% IF ( lateorder.biblio.author ) %]
          Author: [% lateorder.biblio.author | html %][% END %] - [% IF ( lateorder.biblio.biblioitem.publishercode ) %] -
          Published by: [% lateorder.biblio.biblioitem.publishercode | html %] - [% IF ( lateorder.biblio.biblioitem.publicationyear ) %] - in [% lateorder.biblio.biblioitem.publicationyear | html %] +

          [% IF bookseller_filter %][% bookseller_filter.name | html %] :[% END %]Late orders

          +
          + [% IF error_claim %] + [% IF ( error_claim == "no_email" ) %] +
          This vendor has no email
          + [% ELSIF ( error_claim == "no_order_selected" ) %] +
          No order selected
          + [% ELSE %] +
          [% error_claim | html %]
          [% END %] - [% END %] -
          - [% lateorder.quantity | html %] - [% SET total_quantity = total_quantity + lateorder.quantity %] - - [% SET subtotal = (lateorder.quantity - lateorder.quantityreceived) * lateorder.rrp %] - [% SET total = total + subtotal %] - [% lateorder.rrp | html %]x[% lateorder.quantity - lateorder.quantityreceived | html %] = [% subtotal | $Price %] - - [% IF ( CAN_user_acquisition_order_manage ) %] - [% lateorder.basket.basketname | html %] ([% lateorder.basketno | html %]) - [% ELSE %] - [% lateorder.basket.basketname | html %] ([% lateorder.basketno | html %]) - [% END %] - [% lateorder.basket.creationdate | $KohaDates %] - [% IF ( lateorder.basket.basketgroupid ) %] - [% IF ( CAN_user_acquisition_group_manage ) %] - [% lateorder.basket.basket_group.name | html %] ([% lateorder.basket.basketgroupid | html %]) - [% ELSE %] - [% lateorder.basket.basket_group.name | html %] ([% lateorder.basket.basketgroupid | html %]) [% END %] - [% END %] - [% Branches.GetName( lateorder.basket.authorizer.branchcode ) | html %] - [% lateorder.fund.budget.budget_period_description | html %][% lateorder.fund.budget_name | html %][% lateorder.claims.count | html %] - [% FOR claim IN lateorder.claims %] - [% claim.claimed_on | $KohaDates %] - [% UNLESS loop.last %]
          [% END %] - [% END %] -
          - [% IF lateorder.order_internalnote %] -

          - [% lateorder.order_internalnote | html %] - - Edit internal note - -

          - [% ELSE %] - - Add internal note - - [% END %] -
          - [% IF lateorder.order_vendornote %] -

          - [% lateorder.order_vendornote | html %] - - Edit vendor note - -

          - [% ELSE %] - - Add vendor note - - [% END %] -
          [% lateorder.biblio.biblioitem.isbn | $raw %]
          Total[% total_quantity | html %][% total | $Price %] 
          + [% IF info_claim %] +
          Email has been sent.
          + [% END %] + [% IF lateorders.size %] + + [% INCLUDE 'csrf-token.inc' %] + + + + [% IF ( letters ) %] +

          +

          + [% END %] + [% SET total = 0 %] + [% SET total_quantity = 0 %] + [% IF bookseller_filter %] +

          Check all Uncheck all

          + [% END %] + + + + + + + + + + + + + + + + + + + + + + + + + + [% FOREACH lateorder IN lateorders %] + + + + + [% IF lateorder.get_column('estimated_delivery_date') %] + [% SET estimated_delivery_date = lateorder.get_column('estimated_delivery_date') %] + [% ELSIF lateorder.get_column('calculated_estimated_delivery_date') %] + [% SET estimated_delivery_date = lateorder.get_column('calculated_estimated_delivery_date') %] + [% END %] + + + + + + + + + + + + + + + + + + [% END %] + + + + + + + + + +
          Order lineOrder dateEstimated delivery dateVendorInformationQuantityTotal costBasketBasket dateBasket groupLibraryBudgetFundClaims countClaimed dateInternal noteVendor noteISBN
          + + [% lateorder.ordernumber | $raw %] [% lateorder.basket.closedate | $KohaDates %] ([% lateorder.basket.late_since_days | html %] days) +

          + [% estimated_delivery_date | $KohaDates %] + [% IF CAN_user_acquisition_order_manage %] + + Edit + + [% END %] +

          +
          [% lateorder.basket.bookseller.name | html %] ([% lateorder.basket.bookseller.id | html %]) + [% INCLUDE 'biblio-title.inc' biblio=lateorder.biblio link=1 %] + [% IF ( lateorder.biblio.author ) %]
          Author: [% lateorder.biblio.author | html %][% END %] + [% IF ( lateorder.biblio.biblioitem.publishercode ) %] +
          Published by: [% lateorder.biblio.biblioitem.publishercode | html %] + [% IF ( lateorder.biblio.biblioitem.publicationyear ) %] + in [% lateorder.biblio.biblioitem.publicationyear | html %] + [% END %] + [% END %] +
          + [% lateorder.quantity | html %] + [% SET total_quantity = total_quantity + lateorder.quantity %] + + [% SET subtotal = (lateorder.quantity - lateorder.quantityreceived) * lateorder.rrp %] + [% SET total = total + subtotal %] + [% lateorder.rrp | html %]x[% lateorder.quantity - lateorder.quantityreceived | html %] + = [% subtotal | $Price %] + + [% IF ( CAN_user_acquisition_order_manage ) %] + [% lateorder.basket.basketname | html %] ([% lateorder.basketno | html %]) + [% ELSE %] + [% lateorder.basket.basketname | html %] + ([% lateorder.basketno | html %]) + [% END %] + [% lateorder.basket.creationdate | $KohaDates %] + [% IF ( lateorder.basket.basketgroupid ) %] + [% IF ( CAN_user_acquisition_group_manage ) %] + [% lateorder.basket.basket_group.name | html %] ([% lateorder.basket.basketgroupid | html %]) + [% ELSE %] + [% lateorder.basket.basket_group.name | html %] + ([% lateorder.basket.basketgroupid | html %]) + [% END %] + [% END %] + [% Branches.GetName( lateorder.basket.authorizer.branchcode ) | html %] [% lateorder.fund.budget.budget_period_description | html %][% lateorder.fund.budget_name | html %][% lateorder.claims.count | html %] + [% FOR claim IN lateorder.claims %] + [% claim.claimed_on | $KohaDates %] + [% UNLESS loop.last %]
          [% END %] + [% END %] +
          + [% IF lateorder.order_internalnote %] +

          + [% lateorder.order_internalnote | html %] + + Edit internal note + +

          + [% ELSE %] + + Add internal note + + [% END %] +
          + [% IF lateorder.order_vendornote %] +

          + [% lateorder.order_vendornote | html %] + + Edit vendor note + +

          + [% ELSE %] + + Add vendor note + + [% END %] +
          [% lateorder.biblio.biblioitem.isbn | $raw %]
          Total[% total_quantity | html %][% total | $Price %] 
          -
          -
          - Export as CSV - - +
          +
          + Export as CSV + + +
          + + +
          + + [% ELSE %] +

          There are no late orders.

          + [% END %] +
          + +
          + - - - -[% ELSE %]

          There are no late orders.

          -[% END %] - - - +
          + +
          + + - + - + + + + + + @@ -315,15 +356,15 @@ - + +
          [% INCLUDE 'date-format.inc' %]
          + + + + diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/acqui/moddeliverydate.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/acqui/moddeliverydate.tt index 2f1355fa7e..45cbc2b45a 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/acqui/moddeliverydate.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/acqui/moddeliverydate.tt @@ -4,11 +4,12 @@ [% SET footerjs = 1 %] [% PROCESS 'i18n.inc' %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Change estimated delivery date") | html %] › - [% t("Acquisitions") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Change estimated delivery date") | html %] + › [% t("Acquisitions") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -33,24 +34,22 @@ [% END #/ WRAPPER sub-header.inc %] [% WRAPPER 'main-container.inc' %] - -

          Change estimated delivery date

          -
          - [% INCLUDE 'csrf-token.inc' %] +

          Change estimated delivery date

          + + [% INCLUDE 'csrf-token.inc' %]
          - - -
          [% INCLUDE 'date-format.inc' %]
          + + +
          [% INCLUDE 'date-format.inc' %]
          - - Cancel + + Cancel
          -
          - + [% END %] [% MACRO jsinclude BLOCK %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/acqui/modordernotes.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/acqui/modordernotes.tt index 033ce324fc..7daf6c1daf 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/acqui/modordernotes.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/acqui/modordernotes.tt @@ -2,15 +2,16 @@ [% USE Koha %] [% PROCESS 'i18n.inc' %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% IF (type == "vendor") %] - [% t("Change order vendor note") | html %] - [% ELSE %] - [% t("Change order internal note") | html %] - [% END %] › - [% t("Acquisition") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% IF (type == "vendor") %] + [% t("Change order vendor note") | html %] + [% ELSE %] + [% t("Change order internal note") | html %] + [% END %] + › [% t("Acquisition") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -40,27 +41,26 @@ [% WRAPPER 'main-container.inc' %] - [% IF (type == "vendor") %] -

          Change order vendor note (order no. [% ordernumber | html %])

          - [% ELSE %] -

          Change order internal note (order no. [% ordernumber | html %])

          - [% END %] -
          - [% INCLUDE 'csrf-token.inc' %] + [% IF (type == "vendor") %] +

          Change order vendor note (order no. [% ordernumber | html %])

          + [% ELSE %] +

          Change order internal note (order no. [% ordernumber | html %])

          + [% END %] + + [% INCLUDE 'csrf-token.inc' %]
          - - + +
          - - Cancel + + Cancel
          -
          - + [% END %] [% INCLUDE 'intranet-bottom.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/acqui/neworderempty.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/acqui/neworderempty.tt index ec30fb663e..f08f0d77ed 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/acqui/neworderempty.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/acqui/neworderempty.tt @@ -9,16 +9,16 @@ [% PROCESS 'i18n.inc' %] [% PROCESS 'patron-search.inc' %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% IF ( ordernumber ) %] - [% tx("Modify order details (line #{ordernumber})", { ordernumber = ordernumber }) | html %] - [% ELSE %] - [% t("New order") | html %] - [% END %] › - [% tx("Basket {basketnumber}", { basketnumber = basketno }) | html %] › - [% t("Acquisitions") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% IF ( ordernumber ) %] + [% tx("Modify order details (line #{ordernumber})", { ordernumber = ordernumber }) | html %] + [% ELSE %] + [% t("New order") | html %] + [% END %] + › [% tx("Basket {basketnumber}", { basketnumber = basketno }) | html %] › [% t("Acquisitions") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] [% FILTER collapse %] [% END %] - [% Asset.js("js/acquisitions-menu.js") | $raw %] - [% Asset.js("js/acq.js") | $raw %] - [% Asset.js("js/additem.js") | $raw %] - [% Asset.js("js/cataloging.js") | $raw %] - [% Asset.js("js/additional-fields-entry.js") | $raw %] - [% INCLUDE 'calendar.inc' %] - [% INCLUDE 'select2.inc' %] - + return -1; + } + function del_user(borrowernumber) { + $("#user_"+borrowernumber).remove(); + var ids = $("#users_ids").val().split(':'); + ids.splice(ids.indexOf(borrowernumber.toString()), 1); + $("#users_ids").val(ids.join(':')); + } + [% Asset.css("css/addbiblio.css") | $raw %] @@ -260,529 +259,526 @@ [% END #/ WRAPPER sub-header.inc %] [% WRAPPER 'main-container.inc' aside='acquisitions-menu' %] +

          + [% IF ( ordernumber ) %] + Modify order line + [% ELSE %] + New order + [% END %] +

          -

          - [% IF ( ordernumber ) %] - Modify order line - [% ELSE %] - New order + + + [% IF ( basketno ) %] +
          +
          + Basket details +
            + [% IF ( basketnote ) %]
          1. Internal note: [% basketnote | html %]
          2. [% END %] + [% IF ( basketbooksellernote ) %]
          3. Vendor note: [% basketbooksellernote | html %]
          4. [% END %] + [% IF ( basketcontractno ) %] +
          5. Contract number: [% basketcontractno | html %]
          6. +
          7. Contract name: [% basketcontractname | html %]
          8. + [% END %] + [% IF ( authorisedbyname ) %]
          9. [% tp('Acquisitions basket managed by user', 'Managed by:') | html %] [% authorisedbyname | html %]
          10. [% END %] + [% IF ( creationdate ) %]
          11. Open on: [% creationdate | $KohaDates %]
          12. [% END %] + [% IF ( closedate ) %] +
            + [% INCLUDE 'csrf-token.inc' %] +
          13. Closed on: [% closedate | $KohaDates %]
          14. + [% IF ( basketgroups ) %] +
          15. Basketgroup: + + + + +
          16. +
            + [% END %] +
            + [% END %] +
          +
          +
          [% END %] -

          - +
          + [% INCLUDE 'csrf-token.inc' %] -[% IF ( basketno ) %] -
          -
          - Basket details -
            - [% IF ( basketnote ) %]
          1. Internal note: [% basketnote | html %]
          2. [% END %] - [% IF ( basketbooksellernote ) %]
          3. Vendor note: [% basketbooksellernote | html %]
          4. [% END %] - [% IF ( basketcontractno ) %] -
          5. Contract number: [% basketcontractno | html %]
          6. -
          7. Contract name: [% basketcontractname | html %]
          8. - [% END %] - [% IF ( authorisedbyname ) %]
          9. [% tp('Acquisitions basket managed by user', 'Managed by:') | html %] [% authorisedbyname | html %]
          10. [% END %] - [% IF ( creationdate ) %]
          11. Open on: [% creationdate | $KohaDates %]
          12. [% END %] - [% IF ( closedate ) %] - - [% INCLUDE 'csrf-token.inc' %] -
          13. Closed on: [% closedate | $KohaDates %]
          14. - [% IF ( basketgroups ) %] -
          15. Basketgroup: - - - -
          16. -
            - [% END %] - - [% END %] -
          -
          -
          -[% END %] - -
          - [% INCLUDE 'csrf-token.inc' %] - -
          - Patrons -
            -
          1. - To notify on receiving: -
            -
              - [% FOREACH user IN users %] -
            • - [% user.firstname | html %] [% user.surname | html %] - [Delete user] -
            • - [% END %] -
            - - Add user -
            -
          2. -
          -
          - -
          - - Catalog details - [% IF ( biblionumber ) %] - Edit record - [% END %] - - [% UNLESS ( existing ) %] - - [% END %] - - - - - - - - - - [% FOREACH c IN currencies %] - - [% END %] - - [% IF NOT Koha.Preference('UseACQFrameworkForBiblioRecords') OR NoACQframework %] -
          1. - [% IF ( biblionumber ) %] - Title: - [% title | html %] - [% ELSE %] - - - Required - [% END %] -
          2. -
          3. - [% IF ( biblionumber ) %] - Author: - [% author | html %] - [% ELSE %] - - - [% END %] -
          4. -
          5. - [% IF ( biblionumber ) %] - Publisher: - [% publishercode | html %] - [% ELSE %] - - - [% END %] -
          6. -
          7. - [% IF ( biblionumber ) %] - Edition: - [% editionstatement | html %] - - [% ELSE %] - - - [% END %] -
          8. -
          9. - [% IF ( biblionumber ) %] - Publication year: - [% publicationyear | html %] - [% ELSE %] - - - [% END %] -
          10. -
          11. - [% IF ( biblionumber ) %] - ISBN: - [% isbn | html %] - [% ELSE %] - - - [% END %] -
          12. - [% IF (UNIMARC) %] -
          13. - [% IF ( biblionumber ) %] - EAN: - [% ean | html %] - [% ELSE %] - - - [% END %] -
          14. - [% END %] -
          15. - [% IF ( biblionumber ) %] - Series: - [% seriestitle | html %] - [% ELSE %] - - - [% END %] -
          16. - [% UNLESS ( biblionumber ) %] - [% IF ( itemtypeloop ) %] +
            + Patrons +
            1. - Item type: - + Add user + +
            2. +
            +
            + +
            + + Catalog details + [% IF ( biblionumber ) %] + Edit record + [% END %] + + [% UNLESS ( existing ) %] + + [% END %] + + + + + + + + + + [% FOREACH c IN currencies %] + + [% END %] + + [% IF NOT Koha.Preference('UseACQFrameworkForBiblioRecords') OR NoACQframework %] +
            1. + [% IF ( biblionumber ) %] + Title: + [% title | html %] + [% ELSE %] + + + Required + [% END %] +
            2. +
            3. + [% IF ( biblionumber ) %] + Author: + [% author | html %] + [% ELSE %] + + + [% END %] +
            4. +
            5. + [% IF ( biblionumber ) %] + Publisher: + [% publishercode | html %] + [% ELSE %] + + + [% END %] +
            6. +
            7. + [% IF ( biblionumber ) %] + Edition: + [% editionstatement | html %] + [% ELSE %] + + + [% END %] +
            8. +
            9. + [% IF ( biblionumber ) %] + Publication year: + [% publicationyear | html %] + [% ELSE %] + + + [% END %] +
            10. +
            11. + [% IF ( biblionumber ) %] + ISBN: + [% isbn | html %] + [% ELSE %] + + + [% END %] +
            12. + [% IF (UNIMARC) %] +
            13. + [% IF ( biblionumber ) %] + EAN: + [% ean | html %] + [% ELSE %] + + + [% END %] +
            14. [% END %] +
            15. + [% IF ( biblionumber ) %] + Series: + [% seriestitle | html %] + [% ELSE %] + + + [% END %] +
            16. + [% UNLESS ( biblionumber ) %] + [% IF ( itemtypeloop ) %] +
            17. + Item type: + +
            18. + [% END %] + [% END %] +
            + [% ELSE %] + + [% IF biblionumber %] +
              + [% FOREACH field IN catalog_details %] +
            1. + + [% field.value | html %] +
            2. + [% END %] +
            + [% ELSE %] +
              + [% FOREACH field IN catalog_details %] +
            1. [% PROCESS display_subfield field=field %]
            2. + [% END %] +
            + [% END %] + [% END %] +
            + + [% IF ( suggestionid ) %] +
            + Suggestion +
              +
            1. + Suggested by: + [% surnamesuggestedby | html %][% IF ( firstnamesuggestedby ) %], [% firstnamesuggestedby | html %][% END %] (suggestion #[% suggestionid | html %]) +
            2. +
            +
            + [% END %] + + [% UNLESS subscriptionid || basket.is_standing %] + [%# it is a suggestion, we have not items %] + [% IF (AcqCreateItemOrdering) %] +
            +

            Items list

            +
            + + + + + + + + + + + + + + + + + + + + + [% FOREACH item IN items %] + + + + + + + + + + + + + + + + + [% END %] + +
            ActionsBarcodeHome libraryHolding libraryNot for loanRestrictedLocationCall numberCopy numberInventory numberCollectionItem typeMaterialsNotes
             [% item.barcode | html %][% Branches.GetName(item.homebranch) | html %][% Branches.GetName(item.holdingbranch) | html %][% AuthorisedValues.GetDescriptionByKohaField( kohafield => 'items.notforloan', authorised_value => item.notforloan ) | html %][% AuthorisedValues.GetDescriptionByKohaField( kohafield => 'items.restricted', authorised_value => item.restricted ) | html %][% AuthorisedValues.GetDescriptionByKohaField( kohafield => 'items.location', authorised_value => item.location ) | html %][% item.itemcallnumber | html %][% item.copynumber | html %][% item.stocknumber | html %][% AuthorisedValues.GetDescriptionByKohaField( kohafield => 'items.ccode', authorised_value => item.ccode ) | html %][% ItemTypes.GetDescription( item.itype ) | html %][% item.materials | html %][% item.itemnotes | html %]
            +
            +
            + +
            + Item + [% IF ( NoACQframework ) %] +
            No ACQ framework, using default. You should create a framework with code ACQ, the items framework would be used
            + [% END %] + + [% UNLESS Koha.Preference('autoBarcode') == 'OFF' %] +
            The autoBarcode system preference is set to [% Koha.Preference('autoBarcode') | html %] and items with blank barcodes will have barcodes generated upon save to database
            + [% END %] + +
            +
            + [% END %][%# | html UNLESS subscriptionid %] + [% END %][%# IF (AcqCreateItemOrdering) %] +
            + Accounting details +
              +
            1. + + [% IF subscriptionid %] + + [% ELSIF AcqCreateItemOrdering %] + [% IF basket.is_standing %] + + [% ELSE %] + + [% IF quantitysugg %] + (suggested: [% quantitysugg | html %]) + [% END %] + [% END %] + [% ELSE %] + [% IF basket.is_standing %] + + [% ELSE %] + + [% IF quantitysugg %] + (suggested: [% quantitysugg | html %]) + [% END %] + [% END %] + [% END %] + Required + + + + [% IF subscription %] +
              +
              + Frequency: [% subscription.frequency.description | html %] | [% IF subscription.numberlength %]Number of issues: [% subscription.numberlength | html %][% END %] + [% IF subscription.weeklength %]Number of weeks: [% subscription.weeklength | html %][% END %] + [% IF subscription.monthlength %]Number of months: [% subscription.monthlength | html %][% END %] +
              + [% END %] +
            2. +
            3. + + [% active_count = 0 %] + [% IF !ordernumber %] + [% FOREACH budget_loo IN budget_loop %] + [% active_count= active_count + budget_loo.b_active %] + [% END %] + [% END %] + + Required + + +
            4. +
            5. + +
            6. - [% END %] - [% END %] -
            - [% ELSE %] - - [% IF biblionumber %] -
              - [% FOREACH field IN catalog_details %] -
            1. - - [% field.value | html %] -
            2. - [% END %] -
            - [% ELSE %] -
              - [% FOREACH field IN catalog_details %] -
            1. - [% PROCESS display_subfield field=field %] -
            2. - [% END %] -
            - [% END %] - [% END %] -
            - - [% IF ( suggestionid ) %] -
            - Suggestion -
              -
            1. - Suggested by: - [% surnamesuggestedby | html %][% IF ( firstnamesuggestedby ) %], [% firstnamesuggestedby | html %][% END %] (suggestion #[% suggestionid | html %]) -
            2. -
            -
            - [% END %] - - [% UNLESS subscriptionid || basket.is_standing %][%# it is a suggestion, we have not items %] - [% IF (AcqCreateItemOrdering) %] - -
            -

            Items list

            -
            - - - - - - - - - - - - - - - - - - - - - [% FOREACH item IN items %] - - - - - - - - - - - - - - - - - [% END %] - -
            ActionsBarcodeHome libraryHolding libraryNot for loanRestrictedLocationCall numberCopy numberInventory numberCollectionItem typeMaterialsNotes
             [% item.barcode | html %][% Branches.GetName(item.homebranch) | html %][% Branches.GetName(item.holdingbranch) | html %][% AuthorisedValues.GetDescriptionByKohaField( kohafield => 'items.notforloan', authorised_value => item.notforloan ) | html %][% AuthorisedValues.GetDescriptionByKohaField( kohafield => 'items.restricted', authorised_value => item.restricted ) | html %][% AuthorisedValues.GetDescriptionByKohaField( kohafield => 'items.location', authorised_value => item.location ) | html %][% item.itemcallnumber | html %][% item.copynumber | html %][% item.stocknumber | html %][% AuthorisedValues.GetDescriptionByKohaField( kohafield => 'items.ccode', authorised_value => item.ccode ) | html %][% ItemTypes.GetDescription( item.itype ) | html %][% item.materials | html %][% item.itemnotes | html %]
            -
            -
            - -
            - Item - [% IF ( NoACQframework ) %] -
            No ACQ framework, using default. You should create a framework with code ACQ, the items framework would be used
            - [% END %] - - [% UNLESS Koha.Preference('autoBarcode') == 'OFF' %] -
            The autoBarcode system preference is set to [% Koha.Preference('autoBarcode') | html %] and items with blank barcodes will have barcodes generated upon save to database
            - [% END %] - -
            - -
            - [% END %][%# | html UNLESS subscriptionid %] - [% END %][%# IF (AcqCreateItemOrdering) %] -
            - Accounting details -
              -
            1. - - [% IF subscriptionid %] - - [% ELSIF AcqCreateItemOrdering %] - [% IF basket.is_standing %] - - [% ELSE %] - - [% IF quantitysugg %] - (suggested: [% quantitysugg | html %]) - [% END %] - [% END %] - [% ELSE %] - [% IF basket.is_standing %] - - [% ELSE %] - - [% IF quantitysugg %] - (suggested: [% quantitysugg | html %]) - [% END %] - [% END %] - [% END %] - Required - - - - [% IF subscription %] -
              -
              - Frequency: [% subscription.frequency.description | html %] | - [% IF subscription.numberlength %]Number of issues: [% subscription.numberlength | html %][% END %] - [% IF subscription.weeklength %]Number of weeks: [% subscription.weeklength | html %][% END %] - [% IF subscription.monthlength %]Number of months: [% subscription.monthlength | html %][% END %] -
              - [% END %] -
            2. -
            3. - - [% active_count = 0 %] - [% IF !ordernumber %] - [% FOREACH budget_loo IN budget_loop %] - [% active_count= active_count + budget_loo.b_active %] - [% END %] - [% END %] - - Required - - -
            4. -
            5. - - -
            6. -
            7. - +
            8. + [% IF (listincgst == 1) %](tax inclusive)[% ELSE %](tax exclusive)[% END %] -
            9. -
            10. +
            11. +
            12. [% IF ( uncertainprice ) %] - + [% ELSE %] - - [% END %] -
            13. -
            14. - [% IF ( gst_values ) %] - - [% END %] +
            15. +
            16. + [% IF ( gst_values ) %] + + + + [% IF !gst_found %]Tax rate not defined in system preference TaxRates![% END %] + [% ELSE %] + [% END %] - +
            17. +
            18. + + [% IF ( ordernumber ) %] + % + [% ELSE %] + % + [% END %] +
            19. +
            20. + + (adjusted for [% cur_active | html %], + [% IF (listincgst == 1) %]tax inclusive[% ELSE %]tax exclusive[% END %]) +
            21. +
            22. + + +
            23. +
            24. + + [% IF (listincgst == 1) %](tax inclusive)[% ELSE %](tax exclusive)[% END %] +
            25. +
            26. + + (budgeted cost * quantity) +
            27. +
            28. + + + [% IF (invoiceincgst == 1) %](tax inc.)[% ELSE %](tax exc.)[% END %] +
            29. +
            30. + + +
            31. +
            32. + + +
            33. +
            34. + + +
              [% INCLUDE 'date-format.inc' %]
              +
            35. +
            36. +
              The 2 following fields are available for your own usage. They can be useful for statistical purposes
              +
            37. +
            38. + + +
            39. +
            40. + + +
            41. +
            +
            - [% IF !gst_found %]Tax rate not defined in system preference TaxRates![% END %] - [% ELSE %] - - [% END %] - -
          17. - - [% IF ( ordernumber ) %] - % - [% ELSE %] - % - [% END %] -
          18. -
          19. - - (adjusted for [% cur_active | html %], [% IF (listincgst == 1) %]tax inclusive[% ELSE %]tax exclusive[% END %]) -
          20. -
          21. - - -
          22. -
          23. - - [% IF (listincgst == 1) %](tax inclusive)[% ELSE %](tax exclusive)[% END %] -
          24. -
          25. - - (budgeted cost * quantity) -
          26. -
          27. - - - [% IF (invoiceincgst == 1) %](tax inc.)[% ELSE %](tax exc.)[% END %] -
          28. -
          29. - - -
          30. -
          31. - - -
          32. -
          33. - - -
            [% INCLUDE 'date-format.inc' %]
            -
          34. -
          35. -
            The 2 following fields are available for your own usage. They can be useful for statistical purposes
            -
          36. -
          37. - - -
          38. -
          39. - - -
          40. -
          -
          - -[% IF additional_fields.size %] - [% INCLUDE 'additional-fields-entry.inc' available = additional_fields values = additional_field_values %] -[% END %] - -
          - - - - [% IF (suggestionid) %] - Cancel - [% ELSE %] - [% IF subscriptionid %] - Cancel - [% ELSE %] - Cancel - [% END %] + [% IF additional_fields.size %] + [% INCLUDE 'additional-fields-entry.inc' available = additional_fields values = additional_field_values %] [% END %] -
          -
          - +
          + + + + [% IF (suggestionid) %] + Cancel + [% ELSE %] + [% IF subscriptionid %] + Cancel + [% ELSE %] + Cancel + [% END %] + [% END %] +
          + - + [% MACRO jsinclude BLOCK %] [% Asset.js("js/acq.js") | $raw %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/audio_alerts.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/audio_alerts.tt index 35a5e0b454..8c0c99e107 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/audio_alerts.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/audio_alerts.tt @@ -4,11 +4,12 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Audio alerts") | html %] › - [% t("Administration") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Audio alerts") | html %] + › [% t("Administration") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -29,154 +30,155 @@ [% END #/ WRAPPER sub-header.inc %] [% WRAPPER 'main-container.inc' aside='admin-menu' %] + - +
          + [% INCLUDE 'csrf-token.inc' %] +

          New alertEdit alert

          +
          + Audio alert details + +
            +
          1. + + + Required +
          2. +
          3. + + + + Required +
          4. +
          5. + + +
          6. +
          +
          +
          + + + Cancel +
          +
          +

          Audio alerts

          + [% IF !( Koha.Preference('AudioAlerts') ) %] +
          +

          Audio alerts are disabled

          + [% IF ( CAN_user_parameters_manage_sysprefs ) %] +

          Please enable system preference AudioAlerts to activate sounds.

          + [% ELSE %] +

          The system preference AudioAlerts must be enabled to activate sounds.

          + [% END %] +
          + [% END %] +
          + + + + + + + + + + + - - [% INCLUDE 'csrf-token.inc' %] -

          New alertEdit alert

          -
          - Audio alert details - -
            -
          1. - - - Required -
          2. -
          3. - - - - Required -
          4. -
          5. - - -
          6. -
          -
          -
          - - - Cancel -
          - + + [% FOREACH a IN audio_alerts %] + + + + + + + + [% END %] -
          -
           PrecedenceChange orderSelectorSound 
          [% a.precedence | html %] +
          + [% INCLUDE 'csrf-token.inc' %] + + + + +
          -

          Audio alerts

          - [%IF !( Koha.Preference('AudioAlerts') ) %] -
          -

          Audio alerts are disabled

          - [% IF ( CAN_user_parameters_manage_sysprefs ) %] -

          Please enable system preference AudioAlerts to activate sounds.

          - [% ELSE %] -

          The system preference AudioAlerts must be enabled to activate sounds.

          - [% END %] -
          +
          + [% INCLUDE 'csrf-token.inc' %] + + + + +
          + +
          + [% INCLUDE 'csrf-token.inc' %] + + + + +
          + +
          + [% INCLUDE 'csrf-token.inc' %] + + + + +
          +
          [% a.selector | html %][% a.sound | html %] + Edit
          - - - - - - - - - - - - - [% FOREACH a IN audio_alerts %] - - - - - - - - - [% END %] - -
           PrecedenceChange orderSelectorSound 
          [% a.precedence | html %] -
          - [% INCLUDE 'csrf-token.inc' %] - - - - -
          - -
          - [% INCLUDE 'csrf-token.inc' %] - - - - -
          - -
          - [% INCLUDE 'csrf-token.inc' %] - - - - -
          - -
          - [% INCLUDE 'csrf-token.inc' %] - - - - -
          -
          [% a.selector | html %][% a.sound | html %] - Edit
          -
          - -
          - [% INCLUDE 'csrf-token.inc' %] - [% FOREACH a IN audio_alerts %] - - [% END %] -
          - - -
          -
          + + + + +
          + [% INCLUDE 'csrf-token.inc' %] + [% FOREACH a IN audio_alerts %] + + [% END %] +
          + + +
          +
          [% END %] [% MACRO jsinclude BLOCK %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/auth_subfields_structure.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/auth_subfields_structure.tt index 987aa0433d..ab4e6ea47a 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/auth_subfields_structure.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/auth_subfields_structure.tt @@ -4,28 +4,31 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% IF ( add_form ) %] - [% t("Edit subfields constraints") | html %] › - [% END %] +<title + >[% FILTER collapse %] + [% IF ( add_form ) %] + [% t("Edit subfields constraints") | html %] + › + [% END %] - [% IF ( delete_confirm ) %] - [% tx("Confirm deletion of subfield '{subfield}'", {subfield = ass.tagsubfield }) | html %] › - [% END %] + [% IF ( delete_confirm ) %] + [% tx("Confirm deletion of subfield '{subfield}'", {subfield = ass.tagsubfield }) | html %] + › + [% END %] - [% IF ( add_form || delete_confirm || else ) %] - [% tx("Tag {tag}", { tag = tagfield}) | html %] › - [% END %] + [% IF ( add_form || delete_confirm || else ) %] + [% tx("Tag {tag}", { tag = tagfield}) | html %] + › + [% END %] - [% IF ( authtypecode ) %] - [% tx("'{authtypecode}' framework", { authtypecode = authtypecode }) | html %] - [% ELSE %] - [% t("Default framework") | html %] - [% END %] › - [% t("Authority types") | html %] › - [% t("Administration") | html %] › - [% t("Koha") | html %] -[% END %] + [% IF ( authtypecode ) %] + [% tx("'{authtypecode}' framework", { authtypecode = authtypecode }) | html %] + [% ELSE %] + [% t("Default framework") | html %] + [% END %] + › [% t("Authority types") | html %] › [% t("Administration") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -46,7 +49,7 @@ [% IF ( authtypecode ) %] [% WRAPPER breadcrumb_item %] - [% tx("'{authtypecode}' framework", { authtypecode = authtypecode }) | html %] + [% tx("'{authtypecode}' framework", { authtypecode = authtypecode }) | html %] [% END %] [% ELSE %] [% WRAPPER breadcrumb_item %] @@ -88,309 +91,344 @@ [% WRAPPER 'main-container.inc' aside='admin-menu' %] -[% IF ( add_form ) %] - -

          [% IF ( use_heading_flags_p ) %] - [% IF ( heading_edit_subfields_p ) %]Edit MARC subfields constraints for field [% tagfield | html %] authority [% authtypecode | html %][% END %] - [% ELSE %][% action | html %][% END %]

          -
          You can drag and drop the subfield tabs to change the order.
          -
          - [% INCLUDE 'csrf-token.inc' %] - - - -
          Cancel
          - - [% BLOCK outputsubfield %][% FILTER collapse %] - [% SWITCH ( subfieldanchor ) %] - [% CASE "@" %] - AT - [% CASE "%" %] - % - [% CASE %] - [% subfieldanchor | html %] - [% END %] - [% END %][% END %] - - [% WRAPPER tabs id= "subfieldtabs" %] - [% WRAPPER tabs_nav %] - [% FOREACH loo IN loop %] - [% outputsubfield = PROCESS outputsubfield subfieldanchor = loo.tagsubfield %] - [% WRAPPER tab_item tabname= outputsubfield id= "tab_subfield_${outputsubfield}" %] - [% IF ( loo.new_subfield ) %] - New - [% ELSE %] - [% loo.tagsubfield | html %] - [% END # IF loo.new_subfield%] - [% END # WRAPPER tab_item %] - [% END # FOREACH loo %] - [% END # /WRAPPER tabs_nav %] - - [% WRAPPER tab_panels %] - [% FOREACH loo IN loop %] - [% outputsubfield = PROCESS outputsubfield subfieldanchor = loo.tagsubfield %] - [% WRAPPER tab_panel tabname=outputsubfield %] -
            - - [% IF ( loo.new_subfield ) %] -
          1. - - -
          2. - [% ELSE %] -
          3. - -
          4. - [% END %] -
          5. - - [% IF loo.repeatable %] - - [% ELSE %] - - [% END %] -
          6. -
          7. - - [% IF loo.mandatory %] - - [% ELSE %] - - [% END %] -
          8. -
          9. -
          10. -
          11. - -
            Ignore means that the subfield does not display in the record editor and that its value, if any, is deleted from the record
            -
          12. -
          13. -
            - Display -
              -
            1. - -
            2. -
            -
            -
          14. -
          15. -
            - Advanced constraints: -
              -
            1. - - [% IF loo.isurl %] - - [% ELSE %] - - [% END %] - If checked, it means that the subfield is a URL and can be clicked. -
            2. -
            3. - - -
            4. -
            -
            -
          16. -
          17. -
            Help input -
              -
            1. - - -
            2. -
            3. - - -
            4. -
            5. - - -
            6. -
            7. - - -
            8. -
            -
            -
          18. -

          - [% END # /WRAPPER tab_panel %] - [% END # /FOREACH loo %] - [% END # /WRAPPER tab_panels %] - [% END # /WRAPPER tabs %] -
          -[% END %] - -[% IF ( delete_confirm ) %] - -
          -

          Confirm deletion of subfield '[% ass.tagsubfield | html %]'?

          -
          + [% IF ( add_form ) %] +

          [% IF ( use_heading_flags_p ) %] + [% IF ( heading_edit_subfields_p ) %]Edit MARC subfields constraints for field [% tagfield | html %] authority [% authtypecode | html %][% END %] + [% ELSE %] + [% action | html %] + [% END %]

          +
          You can drag and drop the subfield tabs to change the order.
          + [% INCLUDE 'csrf-token.inc' %] - - - - -
          Subfield: [% ass.tagsubfield | html %]
          Description: [% ass.liblibrarian | html_entity %]
          - - - - + + + +
          + Cancel
          + + [% BLOCK outputsubfield %][% FILTER collapse %] + [% SWITCH ( subfieldanchor ) %] + [% CASE "@" %] + AT + [% CASE "%" %] + % + [% CASE %] + [% subfieldanchor | html %] + [% END %] + [% END %][% END %] + + [% WRAPPER tabs id= "subfieldtabs" %] + [% WRAPPER tabs_nav %] + [% FOREACH loo IN loop %] + [% outputsubfield = PROCESS outputsubfield subfieldanchor = loo.tagsubfield %] + [% WRAPPER tab_item tabname= outputsubfield id= "tab_subfield_${outputsubfield}" %] + [% IF ( loo.new_subfield ) %] + New + [% ELSE %] + [% loo.tagsubfield | html %] + [% END # IF loo.new_subfield %] + [% END # WRAPPER tab_item %] + [% END # FOREACH loo %] + [% END # /WRAPPER tabs_nav %] + + [% WRAPPER tab_panels %] + [% FOREACH loo IN loop %] + [% outputsubfield = PROCESS outputsubfield subfieldanchor = loo.tagsubfield %] + [% WRAPPER tab_panel tabname=outputsubfield %] +
            + [% IF ( loo.new_subfield ) %] +
          1. + + +
          2. + [% ELSE %] +
          3. + +
          4. + [% END %] +
          5. + + [% IF loo.repeatable %] + + [% ELSE %] + + [% END %] +
          6. +
          7. + + [% IF loo.mandatory %] + + [% ELSE %] + + [% END %] +
          8. +
          9. +
          10. +
          11. + +
            Ignore means that the subfield does not display in the record editor and that its value, if any, is deleted from the record
            +
          12. +
          13. +
            + Display +
              +
            1. + +
            2. +
            +
            +
          14. +
          15. +
            + Advanced constraints: +
              +
            1. + + [% IF loo.isurl %] + + [% ELSE %] + + [% END %] + If checked, it means that the subfield is a URL and can be clicked. +
            2. +
            3. + + +
            4. +
            +
            +
          16. +
          17. +
            Help input +
              +
            1. + + +
            2. +
            3. + + +
            4. +
            5. + + +
            6. +
            7. + + +
            8. +
            +
            +
          18. +

          + [% END # /WRAPPER tab_panel %] + [% END # /FOREACH loo %] + [% END # /WRAPPER tab_panels %] + [% END # /WRAPPER tabs %]
          - -
          - - - - -
          -
          -[% END %] - -[% IF ( else ) %] -

          Authority MARC subfield structure admin for [% tagfield | html %] (authority: [% authtypecode | html %])

          -

          This screen shows the subfields associated with the selected tag. You can edit subfields or add a new one by clicking on edit.

          -

          The column 'Koha field' shows that the subfield is linked with a Koha field.

          - -
          - - - - - - - - - - - [% FOREACH loo IN loop %] - - - - - - [% END %] - -
          SubfieldDescriptionConstraints 
          - [% loo.tagsubfield | html %] - - [% IF loo.tab == -1 %] - [% loo.liblibrarian | html_entity %] - [% ELSE %] - [% loo.liblibrarian | html_entity %] - [% END %] - - [% IF loo.subfield_ignored == -1 %] - subfield ignored - [% ELSE %] - Tab:[% loo.tab | html %], - [% IF ( loo.kohafield ) %] | Koha field: [% loo.kohafield | html %], [% END %] - [% IF ( loo.repeatable ) %]Repeatable, [% ELSE %]Not repeatable, - [% END %] - [% IF ( loo.mandatory ) %]Mandatory, [% ELSE %]Not mandatory, - [% END %] - [% IF ( loo.hidden ) %]hidden, - [% END %] - [% IF ( loo.isurl ) %]is a URL, - [% END %] - [% IF ( loo.authorised_value ) %] | Auth value:[% loo.authorised_value | html %], - [% END %] - [% IF ( loo.frameworkcode ) %] | Authority:[% loo.frameworkcode | html %], - [% END %] - [% IF ( loo.value_builder ) %] | Plugin:[% loo.value_builder | html %],[% END %] - [% END %] - - Edit - Delete -
          -
          -
          -
          - - - - Cancel
          -
          + [% IF ( delete_confirm ) %] +
          +

          Confirm deletion of subfield '[% ass.tagsubfield | html %]'?

          +
          + [% INCLUDE 'csrf-token.inc' %] + + + + +
          Subfield: [% ass.tagsubfield | html %]
          Description: [% ass.liblibrarian | html_entity %]
          + + + + +
          -[% END %] +
          + + + + +
          +
          + [% END %] + [% IF ( else ) %] +

          Authority MARC subfield structure admin for [% tagfield | html %] (authority: [% authtypecode | html %])

          +

          This screen shows the subfields associated with the selected tag. You can edit subfields or add a new one by clicking on edit.

          +

          The column 'Koha field' shows that the subfield is linked with a Koha field.

          + +
          + + + + + + + + + + + [% FOREACH loo IN loop %] + + + + + + + [% END %] + +
          SubfieldDescriptionConstraints 
          + [% loo.tagsubfield | html %] + + [% IF loo.tab == -1 %] + [% loo.liblibrarian | html_entity %] + [% ELSE %] + [% loo.liblibrarian | html_entity %] + [% END %] + + [% IF loo.subfield_ignored == -1 %] + subfield ignored + [% ELSE %] + Tab:[% loo.tab | html %], [% IF ( loo.kohafield ) %]| Koha field: [% loo.kohafield | html %],[% END %] + [% IF ( loo.repeatable ) %] + Repeatable, + [% ELSE %] + Not repeatable, + [% END %] + [% IF ( loo.mandatory ) %] + Mandatory, + [% ELSE %] + Not mandatory, + [% END %] + [% IF ( loo.hidden ) %] + hidden, + [% END %] + [% IF ( loo.isurl ) %] + is a URL, + [% END %] + [% IF ( loo.authorised_value ) %] + | Auth value:[% loo.authorised_value | html %], + [% END %] + [% IF ( loo.frameworkcode ) %] + | Authority:[% loo.frameworkcode | html %], + [% END %] + [% IF ( loo.value_builder ) %]| Plugin:[% loo.value_builder | html %],[% END %] + [% END %] + + Edit + Delete +
          +
          + + +
          +
          + + + + Cancel
          +
          + [% END %] [% END %] [% MACRO jsinclude BLOCK %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/auth_tag_structure.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/auth_tag_structure.tt index 814bd22a80..b2fa0dcaa3 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/auth_tag_structure.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/auth_tag_structure.tt @@ -5,27 +5,30 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% IF ( add_form ) %] - [% IF ( heading_modify_tag_p ) %] - [% tx("Modify tag '{searchfield}'", { searchfield = searchfield }) | html %] › +<title + >[% FILTER collapse %] + [% IF ( add_form ) %] + [% IF ( heading_modify_tag_p ) %] + [% tx("Modify tag '{searchfield}'", { searchfield = searchfield }) | html %] + › + [% END %] + [% IF ( heading_add_tag_p ) %] + [% t("New tag") | html %] + › + [% END %] [% END %] - [% IF ( heading_add_tag_p ) %] - [% t("New tag") | html %] › + [% IF ( delete_confirm ) %] + [% tx("Confirm deletion of tag '{searchfield}'", { searchfield = searchfield }) | html %] + › [% END %] - [% END %] - [% IF ( delete_confirm ) %] - [% tx("Confirm deletion of tag '{searchfield}'", { searchfield = searchfield }) | html %] › - [% END %] - [% IF ( authtypecode ) %] - [% tx("'{authtypecode}' framework", { authtypecode = authtypecode }) | html %] - [% ELSE %] - [% t("Default framework") | html %] - [% END %] › - [% t("Authority types") | html %] › - [% t("Administration") | html %] › - [% t("Koha") | html %] -[% END %] + [% IF ( authtypecode ) %] + [% tx("'{authtypecode}' framework", { authtypecode = authtypecode }) | html %] + [% ELSE %] + [% t("Default framework") | html %] + [% END %] + › [% t("Authority types") | html %] › [% t("Administration") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -69,13 +72,11 @@ New tag [% END %] [% END %] - [% ELSE %] [% WRAPPER breadcrumb_item bc_active= 1 %] [% action | html %] [% END %] [% END %] - [% ELSE %] [% IF ( delete_confirm ) %] [% WRAPPER breadcrumb_item bc_active= 1 %] @@ -91,7 +92,6 @@ Default framework [% END %] [% END %] - [% END %] [% END %] [% END #/ WRAPPER breadcrumbs %] @@ -99,199 +99,202 @@ [% WRAPPER 'main-container.inc' aside='admin-menu' %] - [% IF ( else ) %] - - [% END %] - -

          - [% IF ( authtypecode ) %] - [% tx("Authority MARC framework for '{authtypecode}'", { authtypecode = authtypecode }) | html %] - [% ELSE %] - [% t("Default authority MARC framework") | html %] + [% IF ( else ) %] + [% END %] -

          - -[% IF ( add_form ) %] - -

          - [% IF ( heading_modify_tag_p ) %] - [% tx("Modify tag '{searchfield}'", { searchfield = searchfield }) | html %] +

          + [% IF ( authtypecode ) %] + [% tx("Authority MARC framework for '{authtypecode}'", { authtypecode = authtypecode }) | html %] + [% ELSE %] + [% t("Default authority MARC framework") | html %] [% END %] - [% IF ( heading_add_tag_p ) %] - New tag - [% END %] -

          -
          - [% INCLUDE 'csrf-token.inc' %] - - [% IF ( heading_modify_tag_p ) %][% END %] - -
          -
            - [% IF ( heading_modify_tag_p ) %] -
          1. - Tag: - - [% searchfield | html %] -
          2. - [% ELSE %] -
          3. - - Required -
          4. - [% END %] + -
          5. -
          6. -
          7. - [% IF ( repeatable ) %] - - [% ELSE %] - + [% IF ( add_form ) %] +

            + [% IF ( heading_modify_tag_p ) %] + [% tx("Modify tag '{searchfield}'", { searchfield = searchfield }) | html %] [% END %] -

          8. -
          9. - [% IF ( mandatory ) %] - - [% ELSE %] - + [% IF ( heading_add_tag_p ) %] + New tag [% END %] -
          10. -
          11. - -
            If you select a value here, the indicators will be limited to the authorized value list
            -
          12. -
          -
          -
          - - Cancel -
          -
          -[% END %] + +
          + [% INCLUDE 'csrf-token.inc' %] + + [% IF ( heading_modify_tag_p ) %][% END %] + +
          +
            + [% IF ( heading_modify_tag_p ) %] +
          1. + Tag: + + [% searchfield | html %] +
          2. + [% ELSE %] +
          3. + + Required +
          4. + [% END %] +
          5. +
          6. +
          7. + [% IF ( repeatable ) %] + + [% ELSE %] + + [% END %] +
          8. +
          9. + [% IF ( mandatory ) %] + + [% ELSE %] + + [% END %] +
          10. +
          11. + +
            If you select a value here, the indicators will be limited to the authorized value list
            +
          12. +
          +
          +
          + + Cancel +
          +
          + [% END %] -[% IF ( delete_confirm ) %] -
          -

          [% tx("Confirm deletion of tag '{searchfield}'", { searchfield = searchfield }) | html %]

          + [% IF ( delete_confirm ) %] +
          +

          [% tx("Confirm deletion of tag '{searchfield}'", { searchfield = searchfield }) | html %]

          +
          + [% INCLUDE 'csrf-token.inc' %] + + +
          Tag: [% searchfield | html %] [% liblibrarian | html %]
          + + + + +
          +
          + +
          +
          + [% END %] + + [% IF ( authtype_create ) %]
          [% INCLUDE 'csrf-token.inc' %] - - -
          Tag: [% searchfield | html %] [% liblibrarian | html %]
          - + - - -
          -
          - -
          -
          -[% END %] - -[% IF ( authtype_create ) %] - -
          - [% INCLUDE 'csrf-token.inc' %] - - - Create authority framework for [% authtypecode | html %] using - - -
          -[% END %] - - -[% IF ( else ) %] - -
          -
          - - - - + [% FOREACH existingauthtypeloo IN existingauthtypeloop %] + [% IF existingauthtypeloo.value == "" %] + + [% ELSE %] + + [% END %] [% END %] - [% END %] - - -
          -
          + + + + [% END %] -
          -
          + [% IF ( else ) %] +
          +
          + + + + + +
          +
          -
          - - - - - - - - - - - - - [% FOREACH loo IN loop %] - - - - - - - - - [% END %] - -
          TagTag descriptionRepeatableMandatoryAuthorized
          value
           
          [% loo.tagfield | html %][% loo.liblibrarian | html %][% IF ( loo.repeatable ) %]Yes[% ELSE %]No[% END %][% IF ( loo.mandatory ) %]Yes[% ELSE %]No[% END %][% loo.authorised_value | html %] - -
          -
          -[% END %] +
          +
          + + + + + + + + + + + + + [% FOREACH loo IN loop %] + + + + + + + + + [% END %] + +
          TagTag descriptionRepeatableMandatoryAuthorized
          value
           
          [% loo.tagfield | html %][% loo.liblibrarian | html %][% IF ( loo.repeatable ) %]Yes[% ELSE %]No[% END %][% IF ( loo.mandatory ) %]Yes[% ELSE %]No[% END %][% loo.authorised_value | html %] + +
          +
          + + [% END %] [% END %] [% MACRO jsinclude BLOCK %] [% INCLUDE 'datatables.inc' %] [% Asset.js("js/admin-menu.js") | $raw %] [% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/authorised_values.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/authorised_values.tt index 5755c08ed4..98966b8f28 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/authorised_values.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/authorised_values.tt @@ -4,36 +4,41 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% IF op == 'add_form' %] - [% IF ( action_modify || action_add_value ) %] - [% IF ( action_modify ) %] - [% t("Modify authorized value") | html %] › +<title + >[% FILTER collapse %] + [% IF op == 'add_form' %] + [% IF ( action_modify || action_add_value ) %] + [% IF ( action_modify ) %] + [% t("Modify authorized value") | html %] + › + [% END %] + [% IF ( action_add_value ) %] + [% t("New authorized value") | html %] + › + [% END %] + [% tx("Authorized values for category {category_name}", { category_name = category_name }) | html %] + › [% END %] - [% IF ( action_add_value ) %] - [% t("New authorized value") | html %] › + [% IF ( action_add_category ) %] + [% t("New category") | html %] + › [% END %] - [% tx("Authorized values for category {category_name}", { category_name = category_name }) | html %] › - [% END %] - [% IF ( action_add_category ) %] - [% t("New category") | html %] › - [% END %] + [% ELSIF ( loop || searchfield ) %] + [% tx("Authorized values for category {category_name}", { category_name = category.category_name }) | html %] + › + [% END # /IF op == 'add_form' %] - [% ELSIF ( loop || searchfield ) %] - [% tx("Authorized values for category {category_name}", { category_name = category.category_name }) | html %] › - [% END # /IF op == 'add_form' %] - - [% t("Authorized values") | html %] › - [% t("Administration") | html %] › - [% t("Koha") | html %] -[% END %] + [% t("Authorized values") | html %] + › [% t("Administration") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] [% FILTER collapse %] [% END %] @@ -99,7 +104,6 @@ New category [% END %] [% END %] - [% ELSIF ( loop || searchfield ) %] [% WRAPPER breadcrumb_item bc_active= 1 %] Authorized values for category [% category.category_name | html %] @@ -109,282 +113,291 @@ [% END #/ WRAPPER sub-header.inc %] [% WRAPPER 'main-container.inc' aside='admin-menu' %] - [% IF op == 'add_form' OR op == 'edit_form' %] -

          - [% IF ( action_modify ) %]Modify authorized value[% END %] - [% IF ( action_add_value ) %]New authorized value[% END %] - [% IF ( action_add_category ) %]New category[% END %] - [% IF ( op == 'edit_form' ) %]Edit category[% END %] -

          + [% IF op == 'add_form' OR op == 'edit_form' %] +

          + [% IF ( action_modify ) %]Modify authorized value[% END %] + [% IF ( action_add_value ) %]New authorized value[% END %] + [% IF ( action_add_category ) %]New category[% END %] + [% IF ( op == 'edit_form' ) %]Edit category[% END %] +

          - [% IF ( action_modify ) %] -
          - NOTE: If you change an authorized value code, existing records using it won't be updated. Changes to value descriptions will show immediately. -
          - [% END %] + [% IF ( action_modify ) %] +
          + NOTE: If you change an authorized value code, existing records using it won't be updated. Changes to value descriptions will show immediately. +
          + [% END %] -
          - [% INCLUDE 'csrf-token.inc' %] -
          - [% IF action_add_category %] -
            -
          1. - - - Required - -
          2. -
          3. - -
          4. -
          - [% ELSIF op == 'edit_form' %] -
            -
          1. - - -
          2. -
          3. - [% IF category.is_integer_only %] - - [% ELSE %] - - [% END %] -
          4. -
          - - - + + [% INCLUDE 'csrf-token.inc' %] +
          + [% IF action_add_category %] +
            +
          1. + + + Required + +
          2. +
          3. +
          + [% ELSIF op == 'edit_form' %] +
            +
          1. + + +
          2. +
          3. + [% IF category.is_integer_only %] + [% ELSE %] -
              -
            1. - Category - - [% category_name | html %] -
            2. -
            3. - - [% IF ( action_modify ) %] - - [% END %] - [% IF ( av && av.is_integer_only ) || category.is_integer_only %] - - [% ELSE %] - - [% END %] -
            4. -
            5. - - -
            6. -
            7. - - -
            8. -
            9. - + [% END %] +
            10. +
            + + + + [% ELSE %] +
              +
            1. + Category + + [% category_name | html %] +
            2. +
            3. + + [% IF ( action_modify ) %] + + [% END %] + [% IF ( av && av.is_integer_only ) || category.is_integer_only %] + + [% ELSE %] + + [% END %] +
            4. +
            5. + + +
            6. +
            7. + + +
            8. +
            9. + +
              Select 'All libraries' if this authorized value must be displayed all the time. Otherwise select libraries you want to associate with this value.
              +
            10. +
            + + [% INCLUDE 'admin-icon-selection.inc' context = "authval" %] + [% END # /IF action_add_category %] +
          + +
          + + + Cancel +
          + + [% END # /IF op == 'add_form' %] + + [% IF op == 'list' %] + + + [% IF ( searchfield ) %] +

          Authorized values for category [% category.category_name | html %]

          + [% PROCESS category_descriptions code_category = category.category_name %] + [% ELSE %] +

          Authorized values

          + [% END %] + + [% IF ( searchfield ) %] +
          + NOTE: If you change an authorized value code, existing records using it won't be updated. Changes to value descriptions will show immediately. +
          + [% END %] + + [% FOR m IN messages %] +
          + [% SWITCH m.code %] + [% CASE 'error_on_update' %] + An error occurred when updating this authorized value. Perhaps the value already exists. + [% CASE 'error_on_insert' %] + An error occurred when inserting this authorized value. Perhaps the value or the category already exists. + [% CASE 'error_on_edit_cat' %] + An error occurred when updating this authorized value category. + [% CASE 'error_on_insert_cat' %] + An error occurred when inserting this authorized value category. Perhaps the category name already exists. + [% CASE 'error_on_delete' %] + An error occurred when deleting this authorized value. Check the logs for details. + [% CASE 'error_on_delete_category' %] + An error occurred when deleting this authorized value category. Check the logs for details. + [% CASE 'success_on_update' %] + Authorized value updated successfully. + [% CASE 'success_on_insert' %] + Authorized value added successfully. + [% CASE 'success_on_insert_cat' %] + Authorized value category added successfully. + [% CASE 'success_on_delete' %] + Authorized value deleted successfully. + [% CASE 'success_on_delete_category' %] + Authorized value category deleted successfully. + [% CASE 'cat_already_exists' %] + This authorized value category already exists. + [% CASE 'invalid_category_name' %] + The authorized value category 'branches', 'itemtypes' and 'cn_source' are used internally by Koha and are not valid. + [% CASE %] + [% m.code | html %] + [% END %] +
          + [% END # /FOR m IN messages %] + +
          + [% IF ( searchfield ) %] +
          +

          + + +

          +
          + + + [% IF loop %] + + + + + + + + + + + + + [% FOREACH loo IN loop %] + + + + + + + + + [% END # /FOREACH loop %] + +
          Authorized valueDescriptionDescription (OPAC)IconLibrary limitationsActions
          [% loo.authorised_value | html %][% loo.lib | html %][% loo.lib_opac | html %] [% IF ( loo.image ) %][% ELSE %] [% END %] + [% IF loo.branches.size > 0 %] + [% branches_str = "" %] + [% FOREACH branch IN loo.branches %] + [%- IF loop.first -%] + [% branches_str = branch.branchname _ " (" _ branch.branchcode _ ")" %] [% ELSE %] - + [% branches_str = branches_str _ "\n" _ branch.branchname _ " (" _ branch.branchcode _ ")" %] [% END %] [% END %] - -
          Select 'All libraries' if this authorized value must be displayed all the time. Otherwise select libraries you want to associate with this value.
          - - - - [% INCLUDE 'admin-icon-selection.inc' context = "authval" %] - - [% END # /IF action_add_category %] - - -
          - - - Cancel -
          - - [% END # /IF op == 'add_form' %] - - [% IF op == 'list' %] -
          - New category - [% IF ( searchfield ) %] - Edit category - New authorized value for [% category.category_name | html %] + + [% IF loo.branches.size > 1 %] + [% loo.branches.size | html %] library limitations + [% ELSE %] + [% loo.branches.size | html %] library limitation + [% END %] + + [% ELSE %] + No limitation + [% END # /IF loo.branches.size > 0 %] +
          + Edit +
          + [% INCLUDE 'csrf-token.inc' %] + + + + +
          +
          + + [% ELSE %] +
          +

          There are no authorized values defined for [% category.category_name | html %]

          +
          + + + +
          + [% UNLESS category.is_system %] +
          + [% INCLUDE 'csrf-token.inc' %] + + + +
          [% END %]
          - - [% IF ( searchfield ) %] -

          Authorized values for category [% category.category_name | html %]

          - [% PROCESS category_descriptions code_category = category.category_name %] - [% ELSE %] -

          Authorized values

          - [% END %] - - [% IF ( searchfield ) %] -
          - NOTE: If you change an authorized value code, existing records using it won't be updated. Changes to value descriptions will show immediately. -
          - [% END %] - - [% FOR m IN messages %] -
          - [% SWITCH m.code %] - [% CASE 'error_on_update' %] - An error occurred when updating this authorized value. Perhaps the value already exists. - [% CASE 'error_on_insert' %] - An error occurred when inserting this authorized value. Perhaps the value or the category already exists. - [% CASE 'error_on_edit_cat' %] - An error occurred when updating this authorized value category. - [% CASE 'error_on_insert_cat' %] - An error occurred when inserting this authorized value category. Perhaps the category name already exists. - [% CASE 'error_on_delete' %] - An error occurred when deleting this authorized value. Check the logs for details. - [% CASE 'error_on_delete_category' %] - An error occurred when deleting this authorized value category. Check the logs for details. - [% CASE 'success_on_update' %] - Authorized value updated successfully. - [% CASE 'success_on_insert' %] - Authorized value added successfully. - [% CASE 'success_on_insert_cat' %] - Authorized value category added successfully. - [% CASE 'success_on_delete' %] - Authorized value deleted successfully. - [% CASE 'success_on_delete_category' %] - Authorized value category deleted successfully. - [% CASE 'cat_already_exists' %] - This authorized value category already exists. - [% CASE 'invalid_category_name' %] - The authorized value category 'branches', 'itemtypes' and 'cn_source' are used internally by Koha and are not valid. - [% CASE %] - [% m.code | html %] - [% END %] -
          - [% END # /FOR m IN messages %] - -
          - [% IF ( searchfield ) %] - -
          -

          - - -

          -
          - - [% IF loop %] - - - - - - - - - - - - - [% FOREACH loo IN loop %] - - - - - - - - - [% END # /FOREACH loop %] - -
          Authorized valueDescriptionDescription (OPAC)IconLibrary limitationsActions
          [% loo.authorised_value | html %][% loo.lib | html %][% loo.lib_opac | html %] - [% IF ( loo.image ) %][% ELSE %] [% END %] - [% IF loo.branches.size > 0 %] - [% branches_str = "" %] - [% FOREACH branch IN loo.branches %] - [%- IF loop.first -%] - [% branches_str = branch.branchname _ " (" _ branch.branchcode _ ")" %] - [% ELSE %] - [% branches_str = branches_str _ "\n" _ branch.branchname _ " (" _ branch.branchcode _ ")" %] - [% END %] - [% END %] - - [% IF loo.branches.size > 1 %] - [% loo.branches.size | html %] library limitations - [% ELSE %] - [% loo.branches.size | html %] library limitation - [% END %] - [% ELSE %] - No limitation - [% END # /IF loo.branches.size > 0 %] - - Edit -
          - [% INCLUDE 'csrf-token.inc' %] - - - - -
          -
          - [% ELSE %] -
          -

          There are no authorized values defined for [% category.category_name | html %]

          -
          - - - -
          - [% UNLESS category.is_system %] -
          - [% INCLUDE 'csrf-token.inc' %] - - - -
          - [% END %] -
          - [% END # /IF loop %] - - [% ELSE # category was selected %] - - - - - - - - - - [% FOR c IN category_names %] - - - - - - [% END # /FOR c %] - -
          CategoryDescription 
          [% c | html %] - [% PROCESS category_descriptions code_category = c %] - - Add -
          - [% END # /IF ( searchfield )%] -
          - - [% END # /IF op == 'list' %] - + [% END # /IF loop %] + [% ELSE # category was selected %] + + + + + + + + + + [% FOR c IN category_names %] + + + + + + [% END # /FOR c %] + +
          CategoryDescription 
          [% c | html %] [% PROCESS category_descriptions code_category = c %] + Add +
          + + [% END # /IF ( searchfield ) %] +
          + [% END # /IF op == 'list' %] [% END %] [% MACRO jsinclude BLOCK %] @@ -392,37 +405,36 @@ [% INCLUDE 'datatables.inc' %] [% INCLUDE 'columns_settings.inc' %] [% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/branches.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/branches.tt index cd1b47cdcf..6ae5d2dd09 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/branches.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/branches.tt @@ -9,20 +9,23 @@ [% INCLUDE 'doc-head-open.inc' %] [% IF library %][% SET OpacLibraryInfo = library.opac_info( lang => lang ) %][% END %] -[% FILTER collapse %] - [% IF op == 'add_form' %] - [% IF library %] - [% tx("Modify library '{library}'", { library = library.branchcode }) | html %] - [% ELSE %] - [% t("New library") | html %] - [% END %] › - [% ELSIF op == 'delete_confirm' %] - [% tx("Confirm deletion of library '{library}'", { library = library.branchcode }) | html %] › - [% END %] - [% t("Libraries") | html %] › - [% t("Administration") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% IF op == 'add_form' %] + [% IF library %] + [% tx("Modify library '{library}'", { library = library.branchcode }) | html %] + [% ELSE %] + [% t("New library") | html %] + [% END %] + › + [% ELSIF op == 'delete_confirm' %] + [% tx("Confirm deletion of library '{library}'", { library = library.branchcode }) | html %] + › + [% END %] + [% t("Libraries") | html %] + › [% t("Administration") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] [% Asset.css("lib/codemirror/codemirror.min.css") | $raw %] [% Asset.css("lib/codemirror/lint.min.css") | $raw %] @@ -35,7 +38,7 @@ [% WRAPPER 'sub-header.inc' %] [% WRAPPER breadcrumbs %] - [% WRAPPER breadcrumb_item %] + [% WRAPPER breadcrumb_item %] Administration [% END %] @@ -49,573 +52,579 @@ [% END %] [% END %] - [% IF op == 'add_form' %] + [% IF op == 'add_form' %] [% IF library %] [% WRAPPER breadcrumb_item bc_active= 1 %] [% tx("Modify library '{library}'", { library = library.branchcode }) | html %] [% END %] [% ELSE %] - [% WRAPPER breadcrumb_item bc_active= 1 %] + [% WRAPPER breadcrumb_item bc_active= 1 %] New library [% END %] [% END %] - [% ELSIF op == 'delete_confirm' %] [% WRAPPER breadcrumb_item bc_active= 1 %] [% tx("Confirm deletion of library '{library}'", { library = library.branchcode }) | html %] [% END %] - [% ELSIF op == 'view' %] [% WRAPPER breadcrumb_item bc_active= 1 %] [% library.branchname | html %] [% END %] - [% END %] [% END #/ WRAPPER breadcrumbs %] [% END #/ WRAPPER sub-header.inc %] [% WRAPPER 'main-container.inc' aside='admin-menu' %] -[% FOREACH m IN messages %] -
          - [% SWITCH m.code %] - [% CASE 'error_on_update' %] - An error occurred when updating this library. Perhaps it already exists. - [% CASE 'error_on_insert' %] - An error occurred when adding this library. The branchcode might already exist. - [% CASE 'error_on_delete' %] - An error occurred when deleting this library. Check the logs for details. - [% CASE 'success_on_update' %] - Library updated successfully. - [% CASE 'success_on_insert' %] - Library added successfully. - [% CASE 'success_on_delete' %] - Library deleted successfully. - [% CASE 'cannot_delete_library' %] - This library cannot be deleted. Patrons or items are still using it - [% IF m.data.patrons_count and m.data.items_count %] - ([% m.data.patrons_count | html %] patrons and [% m.data.items_count | html %] items). - [% ELSIF m.data.patrons_count %] - ([% m.data.patrons_count | html %] patrons). - [% ELSIF m.data.items_count %] - ([% m.data.items_count | html %] items). + [% FOREACH m IN messages %] +
          + [% SWITCH m.code %] + [% CASE 'error_on_update' %] + An error occurred when updating this library. Perhaps it already exists. + [% CASE 'error_on_insert' %] + An error occurred when adding this library. The branchcode might already exist. + [% CASE 'error_on_delete' %] + An error occurred when deleting this library. Check the logs for details. + [% CASE 'success_on_update' %] + Library updated successfully. + [% CASE 'success_on_insert' %] + Library added successfully. + [% CASE 'success_on_delete' %] + Library deleted successfully. + [% CASE 'cannot_delete_library' %] + This library cannot be deleted. Patrons or items are still using it + [% IF m.data.patrons_count and m.data.items_count %] + ([% m.data.patrons_count | html %] patrons and [% m.data.items_count | html %] items). + [% ELSIF m.data.patrons_count %] + ([% m.data.patrons_count | html %] patrons). + [% ELSIF m.data.items_count %] + ([% m.data.items_count | html %] items). + [% END %] + [% CASE %] + [% m.code | html %] [% END %] - [% CASE %] - [% m.code | html %] - [% END %] -
          -[% END %] +
          + [% END %] -[% IF op == 'list' || op == 'view' %] -
          - New library - [% IF op == 'view' && library %] - Edit library - [% END %] -
          -[% END %] + [% IF op == 'list' || op == 'view' %] +
          + New library + [% IF op == 'view' && library %] + Edit library + [% END %] +
          + [% END %] -[% IF op == 'add_form' %] -

          - [% IF library %] - [% tx("Modify library '{library}'", { library = library.branchcode }) | html %] - [% ELSE %] - New library - [% END %] -

          -
          - [% INCLUDE 'csrf-token.inc' %] -
          - + [% IF op == 'add_form' %] +

          [% IF library %] - + [% tx("Modify library '{library}'", { library = library.branchcode }) | html %] + [% ELSE %] + New library [% END %] -
            -
          1. - [% IF library %] - Library code: - - [% library.branchcode | html %] - [% ELSE %] - - - Required - [% END %] -
          2. -
          3. - - [% IF library %] - - [% ELSE %] - - [% END %] - Required -
          4. -
          -

          - [% IF categories %] -
          Group(s): + + + [% INCLUDE 'csrf-token.inc' %] +
          + + [% IF library %] + + [% END %]
            - [% FOREACH category IN categories %] -
          1. - - [% IF category and selected_categorycodes.grep(category.categorycode).size %] - - [% ELSE %] - - [% END %] -
            [% category.codedescription | html %]
            -
          2. - [% END %] +
          3. + [% IF library %] + Library code: + + [% library.branchcode | html %] + [% ELSE %] + + + Required + [% END %] +
          4. +
          5. + + [% IF library %] + + [% ELSE %] + + [% END %] + Required +
          - [% END %] -
          -
            -
          1. -
          2. -
          3. -
          4. -
          5. -
          6. -
          7. -
          8. -
          9. -
          10. - [% IF (Koha.Preference('ILLModule')) %] -
          11. - - -
            - [% IF ( CAN_user_parameters_manage_sysprefs ) %] - [% pref_ILLDefaultStaffEmail_link = BLOCK %]ILLDefaultStaffEmail[% END %] - Default: [% pref_ILLDefaultStaffEmail_link | $raw | $KohaSpan %] system preference - [% ELSE %] - Default: ILLDefaultStaffEmail system preference - [% END %] -
            -
          12. - [% END %] -
          13. - - -
            - [% IF ( CAN_user_parameters_manage_sysprefs ) %] - [% pref_ReplyToDefault_link = BLOCK %]ReplyToDefault[% END %] - Default: [% pref_ReplyToDefault_link | $raw | $KohaSpan %] system preference - [% ELSE %] - Default: ReplyToDefault system preference - [% END %] -
            -
          14. -
          15. - - -
            - [% IF ( CAN_user_parameters_manage_sysprefs ) %] - [% pref_ReturnpathDefault_link = BLOCK %]ReturnpathDefault[% END %] - Default: [% pref_ReturnpathDefault_link | $raw | $KohaSpan %] system preference - [% ELSE %] - Default: ReturnpathDefault system preference - [% END %] -
            -
          16. -
          17. - -
          18. -
          19. -
          20. - [% IF OpacLibraryInfo %] -
            [% OpacLibraryInfo.content | $raw %]
            - - [% ELSE %] - Add HTML content - [% END %] -
          21. -
          22. - - -
            Enter as a single IP address, or a subnet such as 192.168.1.*
            -
          23. -
          24. - - -
            - [% IF ( CAN_user_parameters_manage_sysprefs ) %] - [% pref_MARCOrgCode_link = BLOCK %]MARCOrgCode[% END %] - Default: [% pref_MARCOrgCode_link | $raw | $KohaSpan %] system preference. - [% ELSE %] - Default: MARCOrgCode system preference. - [% END %] - Obtain a library code from the Library of Congress. -
            -
          25. -
          26. -
          27. - -
          28. -
          29. - -
            Set to 'Yes' to show this library as a search option and on the libraries page in the OPAC.
            -
          30. -
          31. - - - - - - - - - - - [% SET CalendarFirstDayOfWeek = Koha.Preference("CalendarFirstDayOfWeek") %] - [% IF library.library_hours.count > 0 # Existing hours %] - [% SET library_hours = library.library_hours.as_list %] - - [% FOR i IN [0..6] %] - [% SET d = ( CalendarFirstDayOfWeek + i ) % 7 %] - [% SET hr = library_hours.$d %] - - - - - + [% IF categories %] +
            Group(s): +
              + [% FOREACH category IN categories %] +
            1. + + [% IF category and selected_categorycodes.grep(category.categorycode).size %] + + [% ELSE %] + [% END %] - [% ELSE # New hours %] - [% FOR i IN [0..6] %] - [% SET d = ( CalendarFirstDayOfWeek + i ) % 7 %] -
            - - - - - [% END %] - [% END %] - -
            DayOpen timeClose time
            - [% PROCESS dayname day=d %] - - - [% IF hr.open_time %] - - [% ELSE %] - - [% END %] - - [% IF hr.close_time %] - - [% ELSE %] - - [% END %] -
            - [% PROCESS dayname day=d %] - - - - - -
            -
          32. -
          33. - -
            - Edit - - -
            -
          34. -
          35. - -
            - Edit - - -
            -
          36. -
          -
          -
          - - Cancel -
          - -[% END %] - -[% BLOCK dayname %] - [% IF day == 0 %] - Sunday - [% ELSIF day == 1 %] - Monday - [% ELSIF day == 2 %] - Tuesday - [% ELSIF day == 3 %] - Wednesday - [% ELSIF day == 4 %] - Thursday - [% ELSIF day == 5 %] - Friday - [% ELSE %] - Saturday - [% END %] -[% END %] - -[% IF op == 'delete_confirm' and not ( items_count or patrons_count )%] -
          -
          - [% INCLUDE 'csrf-token.inc' %] -

          Are you sure you want to delete [% library.branchname | html %] ([% library.branchcode | html %])?

          - - - - -
          -
          - -
          -
          -[% END %] - -[% IF op == 'list' %] -

          Libraries

          - [% IF libraries_count > 0 %] -
          - - - - - - - - - - - - - - - -
          NameCodeAddressMARC organization codeIPPickup locationPublicSMTP serverLibrary hoursActions
          -
          - [% ELSE %] -
          There are no libraries defined. Start defining libraries.
          - [% END %] -[% END %] - -[% IF op == 'view' && library %] -

          [% library.branchname | html %]

          -
          -
          -
          +
          [% category.codedescription | html %]
          + + [% END %] + +
          + [% END %] +
            -
          1. - Library code: - [% library.branchcode | html %] -
          2. -
          3. - Name: - [% library.branchname | html %] -
          4. -
          5. - Category: - [% category.categoryname | html %] -
          6. -
          7. - Address line 1: - [% library.branchaddress1 | html %] -
          8. -
          9. - Address line 2: - [% library.branchaddress2 | html %] -
          10. -
          11. - Address line 3: - [% library.branchaddress3 | html %] -
          12. -
          13. - City: - [% library.branchcity | html %] -
          14. -
          15. - State: - [% library.branchstate | html %] -
          16. -
          17. - ZIP/Postal code: - [% library.branchzip | html %] -
          18. -
          19. - Country: - [% library.branchcountry | html %] -
          20. -
          21. - Phone: - [% library.branchphone | html %] -
          22. -
          23. - Fax: - [% library.branchfax | html %] -
          24. -
          - - -
          -
          -
            -
          1. - Email: - [% IF ( library.branchemail ) %] - [% library.branchemail | html %] - [% END %] -
          2. -
          3. - ILL staff email: - [% IF ( library.branchillemail ) %] - [% library.branchillemail | html %] - [% END %] -
          4. -
          5. - Reply-To: - [% IF ( library.branchreplyto ) %] - [% library.branchreplyto | html %] - [% END %] -
          6. -
          7. - Return-Path: - [% library.branchreturnpath | html %] -
          8. - [% IF ( library.smtp_server.id ) %] +
          9. +
          10. +
          11. +
          12. +
          13. +
          14. +
          15. +
          16. +
          17. +
          18. + [% IF (Koha.Preference('ILLModule')) %]
          19. - SMTP server: - [% IF ( CAN_user_parameters_manage_smtp_servers ) %] - [% library.smtp_server.name | html %] - [% ELSE %] - [% library.smtp_server.name | html %] - [% END %] + + +
            + [% IF ( CAN_user_parameters_manage_sysprefs ) %] + [% pref_ILLDefaultStaffEmail_link = BLOCK %]ILLDefaultStaffEmail[% END %] + Default: [% pref_ILLDefaultStaffEmail_link | $raw | $KohaSpan %] system preference + [% ELSE %] + Default: ILLDefaultStaffEmail system preference + [% END %] +
          20. [% END %]
          21. - URL: - [% IF ( library.branchurl ) %] - [% library.branchurl | html %] - [% END %] + + +
            + [% IF ( CAN_user_parameters_manage_sysprefs ) %] + [% pref_ReplyToDefault_link = BLOCK %]ReplyToDefault[% END %] + Default: [% pref_ReplyToDefault_link | $raw | $KohaSpan %] system preference + [% ELSE %] + Default: ReplyToDefault system preference + [% END %] +
          22. - IP: - [% library.branchip | html %] + + +
            + [% IF ( CAN_user_parameters_manage_sysprefs ) %] + [% pref_ReturnpathDefault_link = BLOCK %]ReturnpathDefault[% END %] + Default: [% pref_ReturnpathDefault_link | $raw | $KohaSpan %] system preference + [% ELSE %] + Default: ReturnpathDefault system preference + [% END %] +
          23. -
          24. - MARC organization code: - [% library.marcorgcode | html %] -
          25. -
          26. - Notes: - [% library.branchnotes | html %] -
          27. -
          28. - Pickup location: - [% IF ( library.pickup_location ) %] - Yes - [% ELSE %] - No - [% END %] -
          29. -
          30. - Public: - [% IF ( library.public ) %] - Yes - [% ELSE %] - No - [% END %] -
          31. -
          32. - Library hours: - [% SET CalendarFirstDayOfWeek = Koha.Preference("CalendarFirstDayOfWeek") %] - [% SET set_hours = 0 %] - [% IF library.library_hours.count > 0 %] - [% FOR i IN [0..6] %] - [% IF library.library_hours.as_list.$i.open_time != null || library.library_hours.as_list.$i.close_time != null %] - [% set_hours = 1 %] +
          33. + +
          34. +
          35. +
          36. + [% IF OpacLibraryInfo %] + +
            [% OpacLibraryInfo.content | $raw %]
            + [% ELSE %] - Library hours not set + Add HTML content [% END %]
          37. +
          38. + + +
            Enter as a single IP address, or a subnet such as 192.168.1.*
            +
          39. +
          40. + + +
            + [% IF ( CAN_user_parameters_manage_sysprefs ) %] + [% pref_MARCOrgCode_link = BLOCK %]MARCOrgCode[% END %] + Default: [% pref_MARCOrgCode_link | $raw | $KohaSpan %] system preference. + [% ELSE %] + Default: MARCOrgCode system preference. + [% END %] + Obtain a library code from the Library of Congress. +
            +
          41. +
          42. +
          43. + +
          44. +
          45. + +
            Set to 'Yes' to show this library as a search option and on the libraries page in the OPAC.
            +
          46. +
          47. + + + + + + + + + + + [% SET CalendarFirstDayOfWeek = Koha.Preference("CalendarFirstDayOfWeek") %] + [% IF library.library_hours.count > 0 # Existing hours %] + [% SET library_hours = library.library_hours.as_list %] + + [% FOR i IN [0..6] %] + [% SET d = ( CalendarFirstDayOfWeek + i ) % 7 %] + [% SET hr = library_hours.$d %] + + + + + + [% END %] + [% ELSE # New hours %] + [% FOR i IN [0..6] %] + [% SET d = ( CalendarFirstDayOfWeek + i ) % 7 %] + + + + + + [% END %] + [% END %] + +
            DayOpen timeClose time
            + [% PROCESS dayname day=d %] + + + [% IF hr.open_time %] + + [% ELSE %] + + [% END %] + + [% IF hr.close_time %] + + [% ELSE %] + + [% END %] +
            + [% PROCESS dayname day=d %] + + + + + +
            +
          48. +
          49. + +
            + Edit + + +
            +
          50. +
          51. + +
            + Edit + + +
            +
          -
          -
          - - [% IF OpacLibraryInfo %] -
          -
          -

          OPAC information

          -
          [% OpacLibraryInfo.content | $raw %]
          -
          +
          +
          + + Cancel +
          + + [% END %] + + [% BLOCK dayname %] + [% IF day == 0 %] + Sunday + [% ELSIF day == 1 %] + Monday + [% ELSIF day == 2 %] + Tuesday + [% ELSIF day == 3 %] + Wednesday + [% ELSIF day == 4 %] + Thursday + [% ELSIF day == 5 %] + Friday + [% ELSE %] + Saturday + [% END %] + [% END %] + + [% IF op == 'delete_confirm' and not ( items_count or patrons_count ) %] +
          +
          + [% INCLUDE 'csrf-token.inc' %] +

          Are you sure you want to delete [% library.branchname | html %] ([% library.branchcode | html %])?

          + + + + +
          +
          + +
          [% END %] -[% ELSIF op == 'view' %] -
          This library does not exist.
          -[% END %] + [% IF op == 'list' %] +

          Libraries

          + [% IF libraries_count > 0 %] +
          + + + + + + + + + + + + + + + +
          NameCodeAddressMARC organization codeIPPickup locationPublicSMTP serverLibrary hoursActions
          +
          + [% ELSE %] +
          There are no libraries defined. Start defining libraries.
          + [% END %] + [% END %] + + [% IF op == 'view' && library %] +

          [% library.branchname | html %]

          +
          +
          +
          +
            +
          1. + Library code: + [% library.branchcode | html %] +
          2. +
          3. + Name: + [% library.branchname | html %] +
          4. +
          5. + Category: + [% category.categoryname | html %] +
          6. +
          7. + Address line 1: + [% library.branchaddress1 | html %] +
          8. +
          9. + Address line 2: + [% library.branchaddress2 | html %] +
          10. +
          11. + Address line 3: + [% library.branchaddress3 | html %] +
          12. +
          13. + City: + [% library.branchcity | html %] +
          14. +
          15. + State: + [% library.branchstate | html %] +
          16. +
          17. + ZIP/Postal code: + [% library.branchzip | html %] +
          18. +
          19. + Country: + [% library.branchcountry | html %] +
          20. +
          21. + Phone: + [% library.branchphone | html %] +
          22. +
          23. + Fax: + [% library.branchfax | html %] +
          24. +
          +
          +
          +
          +
          +
            +
          1. + Email: + [% IF ( library.branchemail ) %] + [% library.branchemail | html %] + [% END %] +
          2. +
          3. + ILL staff email: + [% IF ( library.branchillemail ) %] + [% library.branchillemail | html %] + [% END %] +
          4. +
          5. + Reply-To: + [% IF ( library.branchreplyto ) %] + [% library.branchreplyto | html %] + [% END %] +
          6. +
          7. + Return-Path: + [% library.branchreturnpath | html %] +
          8. + [% IF ( library.smtp_server.id ) %] +
          9. + SMTP server: + [% IF ( CAN_user_parameters_manage_smtp_servers ) %] + [% library.smtp_server.name | html %] + [% ELSE %] + [% library.smtp_server.name | html %] + [% END %] +
          10. + [% END %] +
          11. + URL: + [% IF ( library.branchurl ) %] + [% library.branchurl | html %] + [% END %] +
          12. +
          13. + IP: + [% library.branchip | html %] +
          14. +
          15. + MARC organization code: + [% library.marcorgcode | html %] +
          16. +
          17. + Notes: + [% library.branchnotes | html %] +
          18. +
          19. + Pickup location: + [% IF ( library.pickup_location ) %] + Yes + [% ELSE %] + No + [% END %] +
          20. +
          21. + Public: + [% IF ( library.public ) %] + Yes + [% ELSE %] + No + [% END %] +
          22. +
          23. + Library hours: + [% SET CalendarFirstDayOfWeek = Koha.Preference("CalendarFirstDayOfWeek") %] + [% SET set_hours = 0 %] + [% IF library.library_hours.count > 0 %] + [% FOR i IN [0..6] %] + [% IF library.library_hours.as_list.$i.open_time != null || library.library_hours.as_list.$i.close_time != null %] + [% set_hours = 1 %] + [% END %] + [% END %] + [% END %] + [% IF set_hours > 0 # Existing library %] + [% SET library_hours = library.library_hours.as_list %] + + + + + + + + + + [% FOR i IN [0..6] %] + [% SET d = ( CalendarFirstDayOfWeek + i) % 7 %] + [% SET hr = library_hours.$d %] + + + + + + [% END %] + +
            DayOpen timeClose time
            + [% PROCESS dayname day=d %] + + [% IF hr.open_time != null %][% hr.open_time | $KohaTimes %][% END %] + + [% IF hr.close_time != null %][% hr.close_time | $KohaTimes %][% END %] +
            + [% ELSE %] + Library hours not set + [% END %] +
          24. +
          +
          + +
          + +
          + + [% IF OpacLibraryInfo %] + +
          +
          +

          OPAC information

          +
          [% OpacLibraryInfo.content | $raw %]
          +
          +
          + [% END %] + [% ELSIF op == 'view' %] +
          This library does not exist.
          + [% END %] [% END %] [% MACRO jsinclude BLOCK %] @@ -640,7 +649,7 @@ [% Asset.css("lib/codemirror/codemirror.css") | $raw %] + @@ -57,7 +64,7 @@ [% IF op == 'add_form' %] [% IF ( categorycode ) %] [% WRAPPER breadcrumb_item bc_active= 1 %] - [% tx("Modify category '{categorycode}'", { categorycode = categorycode }) | html %] + [% tx("Modify category '{categorycode}'", { categorycode = categorycode }) | html %] [% END %] [% ELSE %] [% WRAPPER breadcrumb_item bc_active= 1 %] @@ -88,348 +95,95 @@ [% WRAPPER 'main-container.inc' aside='admin-menu' %] -[% FOR m IN messages %] -
          - [% SWITCH m.code %] - [% CASE 'error_on_update' %] - An error occurred when updating this patron category. Perhaps it already exists. - [% CASE 'error_on_insert' %] - An error occurred when inserting this patron category. The patron category might already exist. - [% CASE 'error_on_delete' %] - An error occurred when deleting this patron category. Check the logs for details. - [% CASE 'success_on_update' %] - Patron category updated successfully. - [% CASE 'success_on_insert' %] - Patron category inserted successfully. - [% CASE 'success_on_delete' %] - Patron category deleted successfully. - [% CASE 'already_exists' %] - This patron category already exists. - [% CASE %] - [% m.code | html %] - [% END %] -
          -[% END %] + [% FOR m IN messages %] +
          + [% SWITCH m.code %] + [% CASE 'error_on_update' %] + An error occurred when updating this patron category. Perhaps it already exists. + [% CASE 'error_on_insert' %] + An error occurred when inserting this patron category. The patron category might already exist. + [% CASE 'error_on_delete' %] + An error occurred when deleting this patron category. Check the logs for details. + [% CASE 'success_on_update' %] + Patron category updated successfully. + [% CASE 'success_on_insert' %] + Patron category inserted successfully. + [% CASE 'success_on_delete' %] + Patron category deleted successfully. + [% CASE 'already_exists' %] + This patron category already exists. + [% CASE %] + [% m.code | html %] + [% END %] +
          + [% END %] -[% IF op == 'add_form' %] -
          - [% INCLUDE 'csrf-token.inc' %] - - - [% IF category %] -

          [% tx("Modify category '{categorycode}'", { categorycode = categorycode }) | html %]

          - [% ELSE %] -

          New category

          - [% END %] -
          -
            - [% IF category %] + [% IF op == 'add_form' %] + + [% INCLUDE 'csrf-token.inc' %] + + + [% IF category %] +

            [% tx("Modify category '{categorycode}'", { categorycode = categorycode }) | html %]

            + [% ELSE %] +

            New category

            + [% END %] +
            +
              + [% IF category %] +
            1. Category code: [% categorycode | html %]
            2. + [% ELSE %] +
            3. + + + Required +
            4. + [% END %]
            5. - Category code: [% categorycode | html %] - -
            6. - [% ELSE %] -
            7. - - + + Required
            8. - [% END %] -
            9. - - - Required -
            10. -
            11. - Enrollment period: -
              - Choose one -
                -
              1. - - [% IF category.enrolmentperiod %] - months - [% ELSE %] - months - [% END %] -
              2. -
              3. - - -
              4. -
              -
              -
            12. -
            13. - - days -
            14. -
            15. - - years -
            16. -
            17. - - years -
            18. -
            19. - - -
            20. -
            21. - - -
            22. -
            23. - - -
            24. -
            25. - - -
            26. -
            27. - - - Required -
            28. -
            29. - - -
            30. -
            31. - -
              Select All libraries if this category type must to be displayed all the time. Otherwise select libraries you want to associate with this value. -
              -
            32. -
            33. - - -
            34. -
            35. - - -
            36. -
            37. - - -
              Leave blank to use system default ([% Koha.Preference('minPasswordLength') | html %])
              -
            38. -
            39. - - -
            40. -
            41. - - -
              - Choose whether staff created patrons of this category be forced into resetting their password after their first OPAC login. -
              -
            42. -
            43. - - [%- SET pref_BlockExpiredPatronOpacActions_link = 'BlockExpiredPatronOpacActions' -%] -
              Choose which OPAC actions, if any, should be blocked for expired patrons in this category. Alternatively, you can use the system preference [%- pref_BlockExpiredPatronOpacActions_link | $raw | $KohaSpan -%] instead.
              -
            44. - [% IF ( Koha.Preference('CheckPrevCheckout') == 'softyes' || Koha.Preference('CheckPrevCheckout') == 'softno' ) %] -
            45. - -
              - Choose whether patrons of this category by default are reminded if they try to borrow an item they borrowed before. -
              -
            46. - [% END %] - [% IF ( Koha.Preference('ILLModule') ) %]
            47. - - months + [% ELSE %] + months + [% END %] +
            48. +
            49. + + +
            50. +
            +
            + +
          1. + + days +
          2. +
          3. + + years +
          4. +
          5. + + years +
          6. +
          7. + + +
          8. +
          9. + + -
            - Choose whether patrons of this category can create new interlibrary loan requests. -
          10. - [% END %] -
          11. - - -
            Controls how long a patrons checkout history is kept for new patrons of this category. "Never" anonymizes checkouts on return, and "Forever" keeps a patron's checkout history indefinitely. When set to "Default", the amount of history kept is controlled by the cronjob batch_anonymise.pl which should be set up by your system administrator.
            -
          12. -
          13. - - -
            If Yes, holds placed by patrons of this category will not be given priority.
            -
          14. -
          15. - - - [%- SET pref_noissuescharge_link = 'noissuescharge' -%] -
            If set, this will override the global value set in the [%- pref_noissuescharge_link | $raw | $KohaSpan -%] preference.
            -
          16. -
          17. - - - [%- SET pref_NoIssuesChargeGuarantees_link = 'NoIssuesChargeGuarantees' -%] -
            If set, this will override the global value set in the [%- pref_NoIssuesChargeGuarantees_link | $raw | $KohaSpan -%] preference.
            -
          18. -
          19. - - - [%- SET pref_NoIssuesChargeGuarantorsWithGuarantees_link = 'NoIssuesChargeGuarantees' -%] -
            If set, this will override the global value set in the [%- pref_NoIssuesChargeGuarantorsWithGuarantees_link | $raw | $KohaSpan -%] preference.
            -
          20. -
          -
          - - [% IF ( EnhancedMessagingPreferences ) %] -
          - Default messaging preferences for this patron category - [% INCLUDE 'messaging-preference-form.inc' %] -
          - [% END %] -
          - - Cancel -
          -
          -[% END %] - -[% IF op == 'delete_confirm' %] -

          - [% IF patrons_in_category > 0 %] - [% tx("Cannot delete category '{categorycode}'", { categorycode = categorycode }) | html %] - [% ELSE %] - [% tx("Confirm deletion of category '{categorycode}'", { categorycode = categorycode }) | html %] - [% END %] -

          - - [% IF patrons_in_category > 0 %] -
          - This category is used [% patrons_in_category | html %] times. Deletion not possible -
          - [% END %] - -
          - - - - - - - - - - - - - - - [% IF ( Koha.Preference('CheckPrevCheckout') == 'softyes' || Koha.Preference('CheckPrevCheckout') == 'softno' ) %] - - - - - [% END %] - - [% IF ( Koha.Preference('ILLModule') ) %] - - - - - [% END %] - - - - - -
          Category code: [% category.categorycode | html %]
          Description: [% category.description | html %]
          Enrollment period: - [% IF category.enrolmentperiod %] - [% category.enrolmentperiod | html %] months - [% ELSE %] - until [% category.enrolmentperioddate | $KohaDates %] - [% END %] -
          Password expiration: [% category.password_expiry_days | html %] days
          Age required: [% category.dateofbirthrequired | html %] years
          Upperage limit: [% category.upperagelimit | html %] years
          Enrollment fee: [% category.enrolmentfee | $Price %]
          Receives overdue notices: [% IF category. overduenoticerequired %]Yes[% ELSE %]No[% END %]
          Lost items in staff interface:[% IF category.hidelostitems %]Hidden by default[% ELSE %]Shown[% END %]
          Hold fee: [% category.reservefee | $Price %]
          Check previous checkouts: - [% SWITCH category.checkprevcheckout %] - [% CASE 'yes' %] - Yes - [% CASE 'no' %] - No - [% CASE 'inherit' %] - Inherit - [% END %] -
          Can be guarantee:[% IF category.can_be_guarantee %]Yes[% ELSE %]No[% END %]
          Can place ILL in OPAC: [% IF category.can_place_ill_in_opac %]Yes[% ELSE %]No[% END %]
          Can be guarantee[% IF category.can_be_guarantee %]Yes[% ELSE %]No[% END %]
          Default privacy: - [% SWITCH category.default_privacy %] - [% CASE 'default' %] - Default - [% CASE 'never' %] - Never - [% CASE 'forever' %] - Forever - [% END %] -
          -
          - -
          - [% INCLUDE 'csrf-token.inc' %] -
          - [% IF patrons_in_category > 0 %] - - [% ELSE %] - - - - Cancel - [% END %] -
          -
          -[% END %] - -[% IF op == 'list' %] - - - -

          Patron categories

          -
          - [% IF searchfield %] - You searched for [% searchfield | html %] - [% END %] - [% IF categories %] - - - - - - - - - - - - - - - [% IF ( EnhancedMessagingPreferences ) %] - - [% END %] - +
        • + + +
        • +
        • + + +
        • +
        • + + + Required +
        • +
        • + + +
        • +
        • + +
          Select All libraries if this category type must to be displayed all the time. Otherwise select libraries you want to associate with this value.
          +
        • +
        • + + +
        • +
        • + + +
        • +
        • + + +
          Leave blank to use system default ([% Koha.Preference('minPasswordLength') | html %])
          +
        • +
        • + + +
        • +
        • + + +
          Choose whether staff created patrons of this category be forced into resetting their password after their first OPAC login.
          +
        • +
        • + + [%- SET pref_BlockExpiredPatronOpacActions_link = 'BlockExpiredPatronOpacActions' -%] +
          Choose which OPAC actions, if any, should be blocked for expired patrons in this category. Alternatively, you can use the system preference [%- pref_BlockExpiredPatronOpacActions_link | $raw | $KohaSpan -%] + instead.
          +
        • [% IF ( Koha.Preference('CheckPrevCheckout') == 'softyes' || Koha.Preference('CheckPrevCheckout') == 'softno' ) %] - +
        • + +
          Choose whether patrons of this category by default are reminded if they try to borrow an item they borrowed before.
          +
        • [% END %] [% IF ( Koha.Preference('ILLModule') ) %] - - [% END %] - - - - - - - - - - - [% FOREACH category IN categories %] - - - - - - [% IF (category.password_expiry_days) %] - - [% ELSE %] - - [% END %] - [% IF (category.dateofbirthrequired) %] - - [% ELSE %] - - [% END %] - [% IF (category.upperagelimit) %] - - [% ELSE %] - - [% END %] - [% IF (category.enrolmentfee > 0) %] - - [% ELSE %] - - [% END %] - - - [% IF (category.reservefee > 0) %] - - [% ELSE %] - - [% END %] - [% IF Koha.Preference('EnhancedMessagingPreferences') %] - - [% END %] - - [% IF ( Koha.Preference('CheckPrevCheckout') == 'softyes' || Koha.Preference('CheckPrevCheckout') == 'softno' ) %] - - [% END %] - [% IF ( Koha.Preference('ILLModule') ) %] - - [% END %] - - - - [% IF (category.noissuescharge) %] - + +
          If Yes, holds placed by patrons of this category will not be given priority.
          + +
        • + + + [%- SET pref_noissuescharge_link = 'noissuescharge' -%] +
          If set, this will override the global value set in the [%- pref_noissuescharge_link | $raw | $KohaSpan -%] preference.
          +
        • +
        • + + + [%- SET pref_NoIssuesChargeGuarantees_link = 'NoIssuesChargeGuarantees' -%] +
          If set, this will override the global value set in the [%- pref_NoIssuesChargeGuarantees_link | $raw | $KohaSpan -%] preference.
          +
        • +
        • + + + [%- SET pref_NoIssuesChargeGuarantorsWithGuarantees_link = 'NoIssuesChargeGuarantees' -%] +
          If set, this will override the global value set in the [%- pref_NoIssuesChargeGuarantorsWithGuarantees_link | $raw | $KohaSpan -%] preference.
          +
        • + + + + [% IF ( EnhancedMessagingPreferences ) %] +
          + Default messaging preferences for this patron category + [% INCLUDE 'messaging-preference-form.inc' %] +
          + [% END %] +
          + + Cancel +
          + + [% END %] + + [% IF op == 'delete_confirm' %] +

          + [% IF patrons_in_category > 0 %] + [% tx("Cannot delete category '{categorycode}'", { categorycode = categorycode }) | html %] + [% ELSE %] + [% tx("Confirm deletion of category '{categorycode}'", { categorycode = categorycode }) | html %] + [% END %] +

          + + [% IF patrons_in_category > 0 %] +
          This category is used [% patrons_in_category | html %] times. Deletion not possible
          + [% END %] + +
          +
          CodeCategory nameTypeEnrollment periodPassword expirationAge requiredUpper age limitEnrollment feeOverdueLost itemsHold feeMessagingLibrary limitationsCheck previous checkout?Can place ILL in OPAC?Can be guaranteeDefault privacyExclude from local holds priorityCheckout charge limitGuarantees checkout charge limitGuarantors with guarantees checkout charge limitActions
          [% category.categorycode | html %] - [% category.description | html %] - - [% SWITCH category.category_type %] - [% CASE 'A' %]Adult - [% CASE 'C' %]Child - [% CASE 'P' %]Prof. - [% CASE 'I' %]Org. - [% CASE 'S' %]Staff - [% CASE 'X' %]Statistical - [% END %] - - [% IF ( category.enrolmentperiod ) %] - [% category.enrolmentperiod | html %] months - [% ELSE %] - until [% category.enrolmentperioddate | $KohaDates %] - [% END %] - [% category.password_expiry_days | html %] days-[% category.dateofbirthrequired | html %] years-[% category.upperagelimit | html %] years-[% category.enrolmentfee | $Price %]-[% IF ( category.overduenoticerequired ) %]Yes[% ELSE %]No[% END %][% IF ( category.hidelostitems ) %]Hidden[% ELSE %]Shown[% END %][% category.reservefee | $Price %]- - [% SET default_messaging = category.default_messaging %] - [% IF default_messaging.size %] - [% FOREACH prefs IN default_messaging %] - [% NEXT IF !Koha.Preference( 'ILLModule' ) && prefs.message_name.match('^Ill_') %] - [% FOREACH transport IN prefs.transports %] - [% IF ( transport.transport ) %] - [% IF ( prefs.Item_Due ) %]Item due - [% ELSIF ( prefs.Advance_Notice ) %]Advance notice - [% ELSIF ( prefs.Hold_Filled ) %]Hold filled - [% ELSIF ( prefs.Item_Check_in ) %]Item check-in - [% ELSIF ( prefs.Item_Checkout ) %]Item checkout - [% ELSIF ( prefs.Ill_ready ) %]Interlibrary loan ready - [% ELSIF ( prefs.Ill_unavailable ) %]Interlibrary loan unavailable - [% ELSIF ( prefs.Ill_update ) %]Interlibrary loan updated - [% ELSIF ( prefs.Auto_Renewals ) %]Auto renewal - [% ELSIF ( prefs.Hold_Reminder ) %]Hold reminder - [% ELSIF ( prefs.Patron_Expiry ) %]Patron account expiry - [% ELSE %]Unknown - [% END %]: - [% transport.transport | html %]
          - [% ELSE %]None
          [% END %] - [% END %] - [% END %] +
        • + +
        • - [% SET library_limits = category.library_limits %] - [% IF library_limits.count > 0 %] - [% library_str = "" %] - [% FOREACH library IN library_limits %] - [%- IF loop.first -%] - [% library_str = library.branchname _ " (" _ library.branchcode _ ")" %] - [% ELSE %] - [% library_str = library_str _ "\n" _ library.branchname _ " (" _ library.branchcode _ ")" %] - [% END %] - [% END %] - - [% IF library_limits.count > 1 %] - [% library_limits.count | html %] library limitations - [% ELSE %] - [% library_limits.count | html %] library limitation - [% END %] - [% ELSE %] - No limitation - [% END %] - - [% SWITCH category.checkprevcheckout %] - [% CASE 'yes' %] - Yes - [% CASE 'no' %] - No - [% CASE 'inherit' %] - Inherit - [% END %] - [% IF category.can_place_ill_in_opac %] Yes [% ELSE %] No [% END %][% IF category.can_be_guarantee %] Yes [% ELSE %] No [% END %] - [% SWITCH category.default_privacy %] - [% CASE 'default' %] - Default - [% CASE 'never' %] - Never + +
          Choose whether patrons of this category can create new interlibrary loan requests.
          + + [% END %] +
        • + +
        • + +
          Controls how long a patrons checkout history is kept for new patrons of this category. "Never" anonymizes checkouts on return, and "Forever" keeps a patron's checkout history indefinitely. When set to "Default", + the amount of history kept is controlled by the cronjob batch_anonymise.pl which should be set up by your system administrator.
          + +
        • + +
        • [% category.noissuescharge | $Price %]
          + + + + + until [% category.enrolmentperioddate | $KohaDates %] [% END %] - [% IF (category.noissueschargeguarantees) %] - - [% ELSE %] - - [% END %] - [% IF (category.noissueschargeguarantorswithguarantees) %] - - [% ELSE %] - - [% END %] - + + + + + + + + + + [% IF ( Koha.Preference('CheckPrevCheckout') == 'softyes' || Koha.Preference('CheckPrevCheckout') == 'softno' ) %] + + + [% END %] - -
          Category code: [% category.categorycode | html %]
          Description: [% category.description | html %]
          Enrollment period: + [% IF category.enrolmentperiod %] + [% category.enrolmentperiod | html %] + months [% ELSE %] - [% 0.00 | $Price %][% category.noissueschargeguarantees | $Price %][% 0.00 | $Price %][% category.noissueschargeguarantorswithguarantees | $Price %][% 0.00 | $Price %] - Edit - Delete +
          Password expiration: [% category.password_expiry_days | html %] days
          Age required: [% category.dateofbirthrequired | html %] years
          Upperage limit: [% category.upperagelimit | html %] years
          Enrollment fee: [% category.enrolmentfee | $Price %]
          Receives overdue notices: [% IF category. overduenoticerequired %]Yes[% ELSE %]No[% END %]
          Lost items in staff interface:[% IF category.hidelostitems %]Hidden by default[% ELSE %]Shown[% END %]
          Hold fee: [% category.reservefee | $Price %]
          Check previous checkouts: + [% SWITCH category.checkprevcheckout %] + [% CASE 'yes' %] + Yes + [% CASE 'no' %] + No + [% CASE 'inherit' %] + Inherit + [% END %]
          - [% ELSE %] -
          No categories have been defined. Create a new category.
          - [% END %] -
          -[% END %] + Can be guarantee:[% IF category.can_be_guarantee %]Yes[% ELSE %]No[% END %] + [% IF ( Koha.Preference('ILLModule') ) %] + + Can place ILL in OPAC: + [% IF category.can_place_ill_in_opac %]Yes[% ELSE %]No[% END %] + + [% END %] + Can be guarantee[% IF category.can_be_guarantee %]Yes[% ELSE %]No[% END %] + + Default privacy: + + [% SWITCH category.default_privacy %] + [% CASE 'default' %] + Default + [% CASE 'never' %] + Never + [% CASE 'forever' %] + Forever + [% END %] + + + + + +
          + [% INCLUDE 'csrf-token.inc' %] +
          + [% IF patrons_in_category > 0 %] + + [% ELSE %] + + + + Cancel + [% END %] +
          +
          + [% END %] + + [% IF op == 'list' %] + + +

          Patron categories

          +
          + [% IF searchfield %] + You searched for [% searchfield | html %] + [% END %] + [% IF categories %] + + + + + + + + + + + + + + + [% IF ( EnhancedMessagingPreferences ) %] + + [% END %] + + [% IF ( Koha.Preference('CheckPrevCheckout') == 'softyes' || Koha.Preference('CheckPrevCheckout') == 'softno' ) %] + + [% END %] + [% IF ( Koha.Preference('ILLModule') ) %] + + [% END %] + + + + + + + + + + + [% FOREACH category IN categories %] + + + + + + [% IF (category.password_expiry_days) %] + + [% ELSE %] + + [% END %] + [% IF (category.dateofbirthrequired) %] + + [% ELSE %] + + [% END %] + [% IF (category.upperagelimit) %] + + [% ELSE %] + + [% END %] + [% IF (category.enrolmentfee > 0) %] + + [% ELSE %] + + [% END %] + + + [% IF (category.reservefee > 0) %] + + [% ELSE %] + + [% END %] + [% IF Koha.Preference('EnhancedMessagingPreferences') %] + + [% END %] + + [% IF ( Koha.Preference('CheckPrevCheckout') == 'softyes' || Koha.Preference('CheckPrevCheckout') == 'softno' ) %] + + [% END %] + [% IF ( Koha.Preference('ILLModule') ) %] + + [% END %] + + + + [% IF (category.noissuescharge) %] + + [% ELSE %] + + [% END %] + [% IF (category.noissueschargeguarantees) %] + + [% ELSE %] + + [% END %] + [% IF (category.noissueschargeguarantorswithguarantees) %] + + [% ELSE %] + + [% END %] + + + [% END %] + +
          CodeCategory nameTypeEnrollment periodPassword expirationAge requiredUpper age limitEnrollment feeOverdueLost itemsHold feeMessagingLibrary limitationsCheck previous checkout?Can place ILL in OPAC?Can be guaranteeDefault privacyExclude from local holds priorityCheckout charge limitGuarantees checkout charge limitGuarantors with guarantees checkout charge limitActions
          [% category.categorycode | html %] + [% category.description | html %] + + [% SWITCH category.category_type %] + [% CASE 'A' %] + Adult + [% CASE 'C' %] + Child + [% CASE 'P' %] + Prof. + [% CASE 'I' %] + Org. + [% CASE 'S' %] + Staff + [% CASE 'X' %] + Statistical + [% END %] + + [% IF ( category.enrolmentperiod ) %] + [% category.enrolmentperiod | html %] + months + [% ELSE %] + until [% category.enrolmentperioddate | $KohaDates %] + [% END %] + [% category.password_expiry_days | html %] days-[% category.dateofbirthrequired | html %] years-[% category.upperagelimit | html %] years-[% category.enrolmentfee | $Price %]-[% IF ( category.overduenoticerequired ) %]Yes[% ELSE %]No[% END %][% IF ( category.hidelostitems ) %]Hidden[% ELSE %]Shown[% END %][% category.reservefee | $Price %]- + [% SET default_messaging = category.default_messaging %] + [% IF default_messaging.size %] + [% FOREACH prefs IN default_messaging %] + [% NEXT IF !Koha.Preference( 'ILLModule' ) && prefs.message_name.match('^Ill_') %] + [% FOREACH transport IN prefs.transports %] + [% IF ( transport.transport ) %] + [% IF ( prefs.Item_Due ) %] + Item due + [% ELSIF ( prefs.Advance_Notice ) %] + Advance notice + [% ELSIF ( prefs.Hold_Filled ) %] + Hold filled + [% ELSIF ( prefs.Item_Check_in ) %] + Item check-in + [% ELSIF ( prefs.Item_Checkout ) %] + Item checkout + [% ELSIF ( prefs.Ill_ready ) %] + Interlibrary loan ready + [% ELSIF ( prefs.Ill_unavailable ) %] + Interlibrary loan unavailable + [% ELSIF ( prefs.Ill_update ) %] + Interlibrary loan updated + [% ELSIF ( prefs.Auto_Renewals ) %] + Auto renewal + [% ELSIF ( prefs.Hold_Reminder ) %] + Hold reminder + [% ELSIF ( prefs.Patron_Expiry ) %] + Patron account expiry + [% ELSE %] + Unknown + [% END %]: + [% transport.transport | html %]
          + [% ELSE %] + None
          + [% END %] + [% END %] + [% END %] + [% ELSE %] + None + [% END %] +
          + [% SET library_limits = category.library_limits %] + [% IF library_limits.count > 0 %] + [% library_str = "" %] + [% FOREACH library IN library_limits %] + [%- IF loop.first -%] + [% library_str = library.branchname _ " (" _ library.branchcode _ ")" %] + [% ELSE %] + [% library_str = library_str _ "\n" _ library.branchname _ " (" _ library.branchcode _ ")" %] + [% END %] + [% END %] + + [% IF library_limits.count > 1 %] + [% library_limits.count | html %] library limitations + [% ELSE %] + [% library_limits.count | html %] library limitation + [% END %] + + [% ELSE %] + No limitation + [% END %] + + [% SWITCH category.checkprevcheckout %] + [% CASE 'yes' %] + Yes + [% CASE 'no' %] + No + [% CASE 'inherit' %] + Inherit + [% END %] + [% IF category.can_place_ill_in_opac %]Yes[% ELSE %]No[% END %][% IF category.can_be_guarantee %]Yes[% ELSE %]No[% END %] + [% SWITCH category.default_privacy %] + [% CASE 'default' %] + Default + [% CASE 'never' %] + Never + [% CASE 'forever' %] + Forever + [% END %] + + [% IF category.exclude_from_local_holds_priority %] + Yes + [% ELSE %] + No + [% END %] + [% category.noissuescharge | $Price %][% 0.00 | $Price %][% category.noissueschargeguarantees | $Price %][% 0.00 | $Price %][% category.noissueschargeguarantorswithguarantees | $Price %][% 0.00 | $Price %] + Edit + Delete +
          + [% ELSE %] +
          No categories have been defined. Create a new category.
          + [% END %] +
          + [% END %] [% END %] [% MACRO jsinclude BLOCK %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/checkmarc.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/checkmarc.tt index e40a9d234b..bebbabcfc7 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/checkmarc.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/checkmarc.tt @@ -4,11 +4,12 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("MARC bibliographic framework test") | html %] › - [% t("Administration") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("MARC bibliographic framework test") | html %] + › [% t("Administration") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -28,271 +29,291 @@ [% END #/ WRAPPER sub-header.inc %] [% WRAPPER 'main-container.inc' aside='admin-menu' %] +

          MARC bibliographic framework test

          -

          MARC bibliographic framework test

          + [% IF ( total ) %] +
          +

          Configuration errors found

          + You have [% total | html %] error(s) in your MARC configuration. Please fix them before using Koha +
          + [% ELSE %] +

          Configuration okay

          You don't have errors in your MARC configuration
          + [% END %] -[% IF ( total ) %] -
          -

          Configuration errors found

          - You have [% total | html %] error(s) in your MARC configuration. Please fix them before using Koha +
          + + + + + + + [% IF ( itemnum ) %] + + + + + [% ELSE %] + + + + + [% END %] + + [% IF ( itemfields ) %] + + + + + [% ELSE %] + + + + + [% END %] + + [% IF ( itemtags ) %] + + + + + [% ELSE %] + + + + + [% END %] + + [% IF ( itemtype ) %] + + + + + [% ELSE %] + + + + + [% END %] + + [% IF ( branch ) %] + + + + + [% ELSE %] + + + + + [% END %] + + [% IF ( holdingbranch ) %] + + + + + [% ELSE %] + + + + + [% END %] + + [% IF ( itemtypes_empty ) %] + + + + + [% ELSE %] + + + + + [% END %] + + [% IF ( branches_empty ) %] + + + + + [% ELSE %] + + + + + [% END %] + + [% IF ( biblionumber ) %] + + + + + [% ELSE %] + + + + + [% END %] + + [% IF ( frameworknull ) %] + + + + + [% ELSE %] + + + + + [% END %] + + [% IF ( inconsistent_tabs ) %] + + + + + [% ELSE %] + + + + + [% END %] + + [% IF ( invalid_authtypecodes ) %] + + + + + [% ELSE %] + + + + + [% END %] + + [% IF ( permanent_location_mapped ) %] + + + + + [% ELSE %] + + + + + [% END %] + + + [% IF ( total ) %] + + + + + [% END %] +
          TestResult
          itemnumber
          • The field itemnumber MUST be mapped
          • +
          • The corresponding subfield MUST be in with -1 (ignore) tab
          OKitemnumber : the field itemnumber is mapped to a field in tab -1
          item fieldsALL items fields MUST :
          +
          • be mapped to the same tag,
          • +
          • and they must all be in the 10 (items) tab
          OKAll item fields are in the same tag and in item tab
          Item tagThere is more than 1 MARC tag related to items tab (10) : [% itemtags | html %]
          OKOnly 1 MARC tag mapped to items
          itemtype NOT mappedthe biblioitems.itemtype field MUST :
          +
          • be mapped to a MARC subfield,
          • +
          • the corresponding subfield MUST have "Authorized value" set to "itemtype"
          OKbiblioitems.itemtype defined
          homebranch NOT mappedthe items.homebranch field MUST :
          +
          • be mapped to a MARC subfield,
          • +
          • the corresponding subfield MUST have "Authorized value" set to "branches"
          OKhomebranch defined
          holdingbranch NOT mappedthe items.holdingbranch field MUST :
          +
          • be mapped to a MARC subfield,
          • +
          • the corresponding subfield MUST have "Authorized value" set to "branches"
          OKholdingbranch defined
          item type not definedat least 1 item type must be defined
          OKat least 1 item type defined
          library not definedat least 1 library must be defined
          OKat least 1 library defined
          biblio and biblionumberThe biblio.biblionumber and biblioitems.biblioitemnumber fields be mapped to a MARC subfield,
          OKbiblionumber and biblioitemnumber mapped correctly
          framework valuesthere is a null value in a frameworkcode. Check the following tables
          +
        • select * from marc_subfield_structure where frameworkcode is NULL
        • +
        • select * from marc_tag_structure where frameworkcode is NULL
        • +
          OKno NULL value in frameworkcode
          subfields not in same tabsNot all subfields for the following tags are in the same tab (or marked 'ignored'). + + + + + + + + [% FOREACH tab_inf IN tab_info %] + + + [% IF ( tab_inf.frameworkcode ) %] + + [% ELSE %] + + [% END %] + + + + [% END %] +
          CodeDescriptionTagTabs in use
          [% tab_inf.frameworkcode | html %][% tab_inf.frameworktext | html %]Default framework[% tab_inf.tagfield | html %][% tab_inf.tabs | html %]
          +
          OKall subfields for each tag are in the same tab (or ignored)
          invalid authority typesNot all authority types referred to by the frameworks are defined. + + + + + + + + + [% FOREACH authtypecode_inf IN authtypecode_info %] + + + [% IF ( authtypecode_inf.frameworkcode ) %] + + [% ELSE %] + + [% END %] + + + + + [% END %] +
          Framework codeFramework descriptionTagSubfieldInvalid authority type
          [% authtypecode_inf.frameworkcode | html %][% authtypecode_inf.frameworktext | html %]Default framework[% authtypecode_inf.tagfield | html %][% authtypecode_inf.tagsubfield | html %][% authtypecode_inf.authtypecode | html %]
          +
          OKall authority types used in the frameworks are defined
          items.permanent_location mappedThe following mappings exist for items.permanent_location, and they shouldn't. + + + + + + + + [% FOREACH mapped_perm_loc IN mapped_permanent_location %] + + + [% IF ( mapped_perm_loc.frameworkcode ) %] + + [% ELSE %] + + [% END %] + + + + [% END %] +
          Framework codeFramework descriptionTagSubfield
          [% mapped_perm_loc.frameworkcode | html %][% mapped_perm_loc.frameworktext | html %]Default framework[% mapped_perm_loc.tagfield | html %][% mapped_perm_loc.tagsubfield | html %]
          +
          OKitems.permanent_location is not mapped on the frameworks
          TOTALYou have [% total | html %] error(s) in your MARC configuration. Please fix them before using Koha
          -[% ELSE %] -
          -

          Configuration okay

          You don't have errors in your MARC configuration -
          -[% END %] - -
          - - - - - - -[% IF ( itemnum ) %] - - - - -[% ELSE %] - - - - -[% END %] - -[% IF ( itemfields ) %] - - - - -[% ELSE %] - - - - -[% END %] - - [% IF ( itemtags ) %] - - - - - [% ELSE %] - - - - - [% END %] - -[% IF ( itemtype ) %] - - - - -[% ELSE %] - - - - -[% END %] - -[% IF ( branch ) %] - - - - -[% ELSE %] - - - - -[% END %] - -[% IF ( holdingbranch ) %] - - - - -[% ELSE %] - - - - -[% END %] - -[% IF ( itemtypes_empty ) %] - - - - -[% ELSE %] - - - - -[% END %] - -[% IF ( branches_empty ) %] - - - - -[% ELSE %] - - - - -[% END %] - -[% IF ( biblionumber ) %] - - - - -[% ELSE %] - - - - -[% END %] - - [% IF ( frameworknull ) %] - - - - - [% ELSE %] - - - - - [% END %] - - [% IF ( inconsistent_tabs ) %] - - - - - [% ELSE %] - - - - - [% END %] - - [% IF ( invalid_authtypecodes ) %] - - - - - [% ELSE %] - - - - - [% END %] - - [% IF ( permanent_location_mapped ) %] - - - - - [% ELSE %] - - - - - [% END %] - - -[% IF ( total ) %] - - - - -[% END %] - -
          TestResult
          itemnumber
          • The field itemnumber MUST be mapped
          • -
          • The corresponding subfield MUST be in with -1 (ignore) tab
          OKitemnumber : the field itemnumber is mapped to a field in tab -1
          item fieldsALL items fields MUST :
          -
          • be mapped to the same tag,
          • -
          • and they must all be in the 10 (items) tab
          OKAll item fields are in the same tag and in item tab
          Item tagThere is more than 1 MARC tag related to items tab (10) : [% itemtags | html %]
          OKOnly 1 MARC tag mapped to items
          itemtype NOT mappedthe biblioitems.itemtype field MUST :
          -
          • be mapped to a MARC subfield,
          • -
          • the corresponding subfield MUST have "Authorized value" set to "itemtype"
          OKbiblioitems.itemtype defined
          homebranch NOT mappedthe items.homebranch field MUST :
          -
          • be mapped to a MARC subfield,
          • -
          • the corresponding subfield MUST have "Authorized value" set to "branches"
          OKhomebranch defined
          holdingbranch NOT mappedthe items.holdingbranch field MUST :
          -
          • be mapped to a MARC subfield,
          • -
          • the corresponding subfield MUST have "Authorized value" set to "branches"
          OKholdingbranch defined
          item type not definedat least 1 item type must be defined
          OKat least 1 item type defined
          library not definedat least 1 library must be defined
          OKat least 1 library defined
          biblio and biblionumberThe biblio.biblionumber and biblioitems.biblioitemnumber fields be mapped to a MARC subfield,
          OKbiblionumber and biblioitemnumber mapped correctly
          framework valuesthere is a null value in a frameworkcode. Check the following tables
          -
        • select * from marc_subfield_structure where frameworkcode is NULL
        • -
        • select * from marc_tag_structure where frameworkcode is NULL
        • -
          OKno NULL value in frameworkcode
          subfields not in same tabsNot all subfields for the following tags are in the same tab (or marked 'ignored'). - - - - - - - - [% FOREACH tab_inf IN tab_info %] - - - [% IF ( tab_inf.frameworkcode ) %] - - [% ELSE %] - - [% END %] - - - - [% END %] -
          CodeDescriptionTagTabs in use
          [% tab_inf.frameworkcode | html %][% tab_inf.frameworktext | html %]Default framework[% tab_inf.tagfield | html %][% tab_inf.tabs | html %]
          -
          OKall subfields for each tag are in the same tab (or ignored)
          invalid authority typesNot all authority types referred to by the frameworks are defined. - - - - - - - - - [% FOREACH authtypecode_inf IN authtypecode_info %] - - - [% IF ( authtypecode_inf.frameworkcode ) %] - - [% ELSE %] - - [% END %] - - - - - [% END %] -
          Framework codeFramework descriptionTagSubfieldInvalid authority type
          [% authtypecode_inf.frameworkcode | html %][% authtypecode_inf.frameworktext | html %]Default framework[% authtypecode_inf.tagfield | html %][% authtypecode_inf.tagsubfield | html %][% authtypecode_inf.authtypecode | html %]
          -
          OKall authority types used in the frameworks are defined
          items.permanent_location mappedThe following mappings exist for items.permanent_location, and they shouldn't. - - - - - - - - [% FOREACH mapped_perm_loc IN mapped_permanent_location %] - - - [% IF ( mapped_perm_loc.frameworkcode ) %] - - [% ELSE %] - - [% END %] - - - - [% END %] -
          Framework codeFramework descriptionTagSubfield
          [% mapped_perm_loc.frameworkcode | html %][% mapped_perm_loc.frameworktext | html %]Default framework[% mapped_perm_loc.tagfield | html %][% mapped_perm_loc.tagsubfield | html %]
          -
          OKitems.permanent_location is not mapped on the frameworks
          TOTALYou have [% total | html %] error(s) in your MARC configuration. Please fix them before using Koha
          -
          - + [% END %] [% MACRO jsinclude BLOCK %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/cities.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/cities.tt index 26151ffddb..0601578490 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/cities.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/cities.tt @@ -5,22 +5,25 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% IF op =='add_form' %] - [% IF city.cityid %] - [% tx("Modify city '{city}'", { city = city.city_name }) | html %] +<title + >[% FILTER collapse %] + [% IF op =='add_form' %] + [% IF city.cityid %] + [% tx("Modify city '{city}'", { city = city.city_name }) | html %] + [% ELSE %] + [% t("New city") | html %] + [% END %] + › [% ELSE %] - [% t("New city") | html %] - [% END %] › - [% ELSE %] - [% IF op == 'delete_confirm' %] - [% tx("Confirm deletion of city '{city}'", { city = city.city_name }) | html %] › + [% IF op == 'delete_confirm' %] + [% tx("Confirm deletion of city '{city}'", { city = city.city_name }) | html %] + › + [% END %] [% END %] - [% END %] - [% t("Cities") | html %] › - [% t("Administration") | html %] › - [% t("Koha") | html %] -[% END %] + [% t("Cities") | html %] + › [% t("Administration") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -46,7 +49,6 @@ New city [% END %] [% END %] - [% ELSIF op == 'delete_confirm' %] [% WRAPPER breadcrumb_item %] Cities @@ -54,154 +56,149 @@ [% WRAPPER breadcrumb_item bc_active = 1 %] [% tx("Confirm deletion of city '{city}'", { city = city.city_name }) | html %] [% END %] - [% ELSE %] [% WRAPPER breadcrumb_item bc_active = 1 %] Cities [% END %] [% END #/IF op = add_form %] - [% END #/ WRAPPER breadcrumbs %] [% END #/ WRAPPER sub-header.inc %] [% WRAPPER 'main-container.inc' aside='admin-menu' %] -[% FOR m IN messages %] -
          - [% SWITCH m.code %] - [% CASE 'error_on_update' %] - An error occurred when updating this city. Perhaps it already exists. - [% CASE 'error_on_insert' %] - An error occurred when adding this city. The city ID might already exist. - [% CASE 'error_on_delete' %] - An error occurred when deleting this city. Check the logs for details. - [% CASE 'success_on_update' %] - City updated successfully. - [% CASE 'success_on_insert' %] - City added successfully. - [% CASE 'success_on_delete' %] - City deleted successfully. - [% CASE 'already_exists' %] - This city already exists. - [% CASE %] - [% m.code | html %] - [% END %] -
          -[% END %] - -[% IF op == 'add_form' %] - [% IF city %] -

          - [% tx("Modify city '{city}'", { city = city.city_name }) | html %] -

          - [% ELSE %] -

          New city

          - [% END %] - -
          - [% INCLUDE 'csrf-token.inc' %] - - - -
          -
            - [% IF city %] -
          1. City ID: [% city.cityid | html %]
          2. - [% END %] -
          3. - - Required -
          4. -
          5. - - -
          6. -
          7. - - Required -
          8. -
          9. - - -
          10. -
          -
          - -
          - - Cancel -
          -
          -[% END %] - -[% IF op == 'delete_confirm' %] -
          -

          - [% tx("Confirm deletion of city '{city}'", { city = city.city_name }) | html %] -

          - - - - - - - - - - - - - - - - -
          City id[% city.cityid | html %]
          City[% city.city_name | html %]
          State[% city.city_state | html %]
          ZIP/Postal code[% city.city_zipcode | html %]
          Country[% city.city_country | html %]
          -
          - [% INCLUDE 'csrf-token.inc' %] - - - -
          -
          - -
          -
          -[% END %] - -[% IF op == 'list' %] - - - -

          Cities

          - [% IF city_name_filter %] - Searching: [% city_name_filter | html %] - [% END %] - - [% IF cities_count > 0 %] -
          -
          - - - - - - - - - - - -
          City IDCityStateZIP/Postal codeCountryActions
          -
          - [% ELSE %] -
          - There are no cities defined. Create a new city. + [% FOR m IN messages %] +
          + [% SWITCH m.code %] + [% CASE 'error_on_update' %] + An error occurred when updating this city. Perhaps it already exists. + [% CASE 'error_on_insert' %] + An error occurred when adding this city. The city ID might already exist. + [% CASE 'error_on_delete' %] + An error occurred when deleting this city. Check the logs for details. + [% CASE 'success_on_update' %] + City updated successfully. + [% CASE 'success_on_insert' %] + City added successfully. + [% CASE 'success_on_delete' %] + City deleted successfully. + [% CASE 'already_exists' %] + This city already exists. + [% CASE %] + [% m.code | html %] + [% END %]
          [% END %] -[% END %] + [% IF op == 'add_form' %] + [% IF city %] +

          [% tx("Modify city '{city}'", { city = city.city_name }) | html %]

          + [% ELSE %] +

          New city

          + [% END %] + +
          + [% INCLUDE 'csrf-token.inc' %] + + + +
          +
            + [% IF city %] +
          1. City ID: [% city.cityid | html %]
          2. + [% END %] +
          3. + + Required +
          4. +
          5. + + +
          6. +
          7. + + Required +
          8. +
          9. + + +
          10. +
          +
          + +
          + + Cancel +
          +
          + [% END %] + + [% IF op == 'delete_confirm' %] +
          +

          [% tx("Confirm deletion of city '{city}'", { city = city.city_name }) | html %]

          + + + + + + + + + + + + + + + + +
          City id[% city.cityid | html %]
          City[% city.city_name | html %]
          State[% city.city_state | html %]
          ZIP/Postal code[% city.city_zipcode | html %]
          Country[% city.city_country | html %]
          +
          + [% INCLUDE 'csrf-token.inc' %] + + + +
          +
          + +
          +
          + [% END %] + + [% IF op == 'list' %] + + +

          Cities

          + [% IF city_name_filter %] + Searching: [% city_name_filter | html %] + [% END %] + + [% IF cities_count > 0 %] +
          +
          + + + + + + + + + + + +
          City IDCityStateZIP/Postal codeCountryActions
          + [% ELSE %] +
          There are no cities defined. Create a new city.
          + [% END %] + [% END %] [% END %] [% MACRO jsinclude BLOCK %] @@ -209,7 +206,6 @@ [% INCLUDE 'datatables.inc' %] [% INCLUDE 'columns_settings.inc' %] [% END %] [% INCLUDE 'intranet-bottom.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/clone-rules.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/clone-rules.tt index b0fc615dfc..da139141be 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/clone-rules.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/clone-rules.tt @@ -5,12 +5,12 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Clone circulation and fine rules") | html %] › - [% t("Circulation and fine rules") | html %] › - [% t("Administration") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Clone circulation and fine rules") | html %] + › [% t("Circulation and fine rules") | html %] › [% t("Administration") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -33,18 +33,17 @@ [% END #/ WRAPPER sub-header.inc %] [% WRAPPER 'main-container.inc' aside='admin-menu' %] +

          Cloning circulation and fine rules [% IF frombranch == "*" %]from standard rules[% ELSIF frombranch %]from "[% Branches.GetName( frombranch ) | html %]"[% END %] + [% IF tobranch %]to "[% Branches.GetName( tobranch ) | html %]"[% END %] +

          -

          Cloning circulation and fine rules - [% IF frombranch == "*" %] from standard rules[% ELSIF frombranch %] from "[% Branches.GetName( frombranch ) | html %]"[% END %] - [% IF tobranch %] to "[% Branches.GetName( tobranch ) | html %]"[% END %] -

          - - [% IF ( error ) %] -
          Cloning of circulation and fine rules failed!
          - [% ELSE %] -

          The rules have been cloned.

          - [% END %] - Return to circulation and fine rules + [% IF ( error ) %] +
          Cloning of circulation and fine rules failed!
          + [% ELSE %] +

          The rules have been cloned.

          + [% END %] + Return to circulation and fine rules [% END %] [% MACRO jsinclude BLOCK %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/columns_settings.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/columns_settings.tt index 512e448355..9260d32d6d 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/columns_settings.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/columns_settings.tt @@ -35,9 +35,14 @@
          [% IF pagename == 'additem' AND tablename == 'itemst' %] -
          Changes made below will only apply to item subfields that are mapped to the 'items' table. Go to Koha to MARC mapping
          +
          Changes made below will only apply to item subfields that are mapped to the 'items' table. Go to Koha to MARC mapping
          [% ELSIF pagename == 'detail' AND ( tablename == 'holdings_table' || tablename == 'otherholdings_table' ) %] -
          Please note that if a field is not used on the first page of items in the holdings table, it will be automatically hidden from display and can be made visible on demand. You can still use the column configuration to permanently hide columns from the holdings table.
          +
          Please note that if a field is not used on the first page of items in the holdings table, it will be automatically hidden from display and can be made visible on demand. You can still use the column + configuration to permanently hide columns from the holdings table.
          [% END %]
          @@ -172,7 +177,6 @@ [%- END -%]

          [% END %] - [% END %]
          @@ -190,11 +194,12 @@ [% END %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Table settings") | html %] › - [% t("Administration") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Table settings") | html %] + › [% t("Administration") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -42,141 +43,137 @@ [% WRAPPER 'main-container.inc' aside='admin-menu' %] -[% FOR m IN messages %] -
          - [% SWITCH m.code %] - [% CASE %] - [% m.code | html %] - [% END %] -
          -[% END %] - -[% IF op == 'list' %] - -

          Curbside pickup configuration

          - - [% UNLESS Koha.Preference('CurbsidePickup') %] - [% SET pref_CurbsidePickup_link = 'CurbsidePickup' %] -
          The [% pref_CurbsidePickup_link | $raw | $KohaSpan %] preference is not enabled, do not forget to enable it to turn the feature on.
          + [% FOR m IN messages %] +
          + [% SWITCH m.code %] + [% CASE %] + [% m.code | html %] + [% END %] +
          [% END %] -
          - [% INCLUDE 'csrf-token.inc' %] - [% WRAPPER tabs id= "curbside_pickup_tabs" %] - [% WRAPPER tabs_nav %] - [% FOREACH l IN libraries %] - [% IF loop.first %] - [% SET bt_active = 1 %] - [% ELSE %] - [% SET bt_active = 0 %] + + [% IF op == 'list' %] +

          Curbside pickup configuration

          + + [% UNLESS Koha.Preference('CurbsidePickup') %] + [% SET pref_CurbsidePickup_link = 'CurbsidePickup' %] +
          The [% pref_CurbsidePickup_link | $raw | $KohaSpan %] preference is not enabled, do not forget to enable it to turn the feature on.
          + [% END %] + + [% INCLUDE 'csrf-token.inc' %] + [% WRAPPER tabs id= "curbside_pickup_tabs" %] + [% WRAPPER tabs_nav %] + [% FOREACH l IN libraries %] + [% IF loop.first %] + [% SET bt_active = 1 %] + [% ELSE %] + [% SET bt_active = 0 %] + [% END %] + [% WRAPPER tab_item tabname= "conf-${l.branchcode}" bt_active= bt_active %][% l.branchname | html %][% END %] [% END %] - [% WRAPPER tab_item tabname= "conf-${l.branchcode}" bt_active= bt_active %] [% l.branchname | html %] [% END %] - [% END %] - [% END # /WRAPPER tabs_nav %] + [% END # /WRAPPER tabs_nav %] - [% WRAPPER tab_panels %] - [% FOREACH l IN libraries %] - [% SET branchcode = l.branchcode %] - [% IF loop.first %] - [% SET bt_active = 1 %] - [% ELSE %] - [% SET bt_active = 0 %] - [% END %] - [% WRAPPER tab_panel tabname= "conf-${l.branchcode}" bt_active= bt_active %] -
          -
            -
          1. - - [% IF policies.$branchcode.enabled %] - - [% ELSE %] - - [% END %] - Enable curbside pickup. -
          2. + [% WRAPPER tab_panels %] + [% FOREACH l IN libraries %] + [% SET branchcode = l.branchcode %] + [% IF loop.first %] + [% SET bt_active = 1 %] + [% ELSE %] + [% SET bt_active = 0 %] + [% END %] + [% WRAPPER tab_panel tabname= "conf-${l.branchcode}" bt_active= bt_active %] +
            +
              +
            1. + + [% IF policies.$branchcode.enabled %] + + [% ELSE %] + + [% END %] + Enable curbside pickup. +
            2. -
            3. - - - Number of minutes each curbside pickup interaction will take. -
            4. +
            5. + + + Number of minutes each curbside pickup interaction will take. +
            6. -
            7. - - - Maximum number of simultaneous pickups per interval. -
            8. +
            9. + + + Maximum number of simultaneous pickups per interval. +
            10. -
            11. - - [% IF policies.$branchcode.patron_scheduled_pickup %] - - [% ELSE %] - - [% END %] - Enable patrons to schedule their own curbside pickups. -
            12. +
            13. + + [% IF policies.$branchcode.patron_scheduled_pickup %] + + [% ELSE %] + + [% END %] + Enable patrons to schedule their own curbside pickups. +
            14. -
            15. - - [% IF policies.$branchcode.enable_waiting_holds_only %] - - [% ELSE %] - - [% END %] - Enable only if the patron has waiting holds. -
            16. -
            -
            +
          3. + + [% IF policies.$branchcode.enable_waiting_holds_only %] + + [% ELSE %] + + [% END %] + Enable only if the patron has waiting holds. +
          4. +
          +
          -
          - Curbside pickup hours +
          + Curbside pickup hours - Times should be in 24-hour format (00:00 to 23:59). + Times should be in 24-hour format (00:00 to 23:59). -
            +
              -
                -
              1. - - [% days = { "0" = t("Sunday"), "1" = t("Monday"), "2" = t("Tuesday"), "3" = t("Wednesday"), "4" = t("Thursday"), "5" = t("Friday"), "6" = t("Saturday") } %] - [% SET CalendarFirstDayOfWeek = Koha.Preference("CalendarFirstDayOfWeek") %] -
                - +
                  +
                1. + + [% days = { "0" = t("Sunday"), "1" = t("Monday"), "2" = t("Tuesday"), "3" = t("Wednesday"), "4" = t("Thursday"), "5" = t("Friday"), "6" = t("Saturday") } %] + [% SET CalendarFirstDayOfWeek = Koha.Preference("CalendarFirstDayOfWeek") %] +
                  + - From - to + From to + - - -
                  -
                2. + + +
                +
              2. +
              +
              + [% END # /tab_panel %] + [% END #FOREACH l %] + [% END # /WRAPPER tab_panels %] + [% END # /WRAPPER tabs %] - -
              - [% END # /tab_panel %] - [% END #FOREACH l %] - [% END # /WRAPPER tab_panels %] - [% END # /WRAPPER tabs %] - - - -
              - -
              -
              -[% END %] + +
              + +
              + + [% END %] [% END %] [% MACRO jsinclude BLOCK %] [% Asset.js("js/admin-menu.js") | $raw %] [% END %] [% INCLUDE 'intranet-bottom.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/debit_types.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/debit_types.tt index 873be38179..1666160f11 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/debit_types.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/debit_types.tt @@ -7,18 +7,20 @@ [% SET footerjs = 1 %] [% PROCESS 'accounts.inc' %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% IF op =='add_form' %] - [% IF debit_type.code %] - [% tx("Modify debit type '{debit_type}'", { debit_type = debit_type.code }) | html %] - [% ELSE %] - [% t("New debit type") | html %] - [% END %] › - [% END %] - [% t("Debit types") | html %] › - [% t("Administration") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% IF op =='add_form' %] + [% IF debit_type.code %] + [% tx("Modify debit type '{debit_type}'", { debit_type = debit_type.code }) | html %] + [% ELSE %] + [% t("New debit type") | html %] + [% END %] + › + [% END %] + [% t("Debit types") | html %] + › [% t("Administration") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -44,7 +46,6 @@ New debit type [% END %] [% END %] - [% ELSE %] [% WRAPPER breadcrumb_item bc_active= 1 %] Debit types @@ -55,235 +56,239 @@ [% WRAPPER 'main-container.inc' aside='admin-menu' %] - [% FOREACH m IN messages %] -
              - [% SWITCH m.code %] - [% CASE 'success_on_saving' %] - Debit type saved successfully. - [% CASE 'error_on_saving' %] - An error occurred when saving this debit type. Check the logs for details. - [% CASE 'success_on_archive' %] - Debit type archived successfully. - [% CASE 'success_on_restore' %] - Debit type restored successfully. - [% CASE %] - [% m.code | html %] - [% END %] -
              - [% END %] + [% FOREACH m IN messages %] +
              + [% SWITCH m.code %] + [% CASE 'success_on_saving' %] + Debit type saved successfully. + [% CASE 'error_on_saving' %] + An error occurred when saving this debit type. Check the logs for details. + [% CASE 'success_on_archive' %] + Debit type archived successfully. + [% CASE 'success_on_restore' %] + Debit type restored successfully. + [% CASE %] + [% m.code | html %] + [% END %] +
              + [% END %] - [% IF op == 'add_form' %] - [% IF debit_type %] -

              [% tx("Modify debit type '{debit_type}'", { debit_type = debit_type.code }) | html %]

              - [% ELSE %] -

              New debit type

              - [% END %] + [% IF op == 'add_form' %] + [% IF debit_type %] +

              [% tx("Modify debit type '{debit_type}'", { debit_type = debit_type.code }) | html %]

              + [% ELSE %] +

              New debit type

              + [% END %] -
              - [% INCLUDE 'csrf-token.inc' %] - -
              -
                -
              1. - - [% IF debit_type %] - [% debit_type.code | html %] - - [% ELSE %] - Required. Maximum length is 64 letters + + [% INCLUDE 'csrf-token.inc' %] + +
                +
                  +
                1. + + [% IF debit_type %] + [% debit_type.code | html %] + + [% ELSE %] + Required. Maximum length is 64 letters + [% END %] +
                2. +
                3. + + +
                4. +
                5. + + [% IF debit_type && debit_type.is_system %] + [%- PROCESS debit_type_description debit_type = debit_type -%] + [% ELSE %] + Required + [% END %] +
                6. +
                7. + + [% IF debit_type.can_be_invoiced %] + + [% ELSE %] + + [% END %] +
                8. +
                9. + + [% IF debit_type.can_be_sold %] + + [% ELSE %] + + [% END %] +
                10. +
                11. + + [% IF debit_type.restricts_checkouts %] + + [% ELSE %] + + [% END %] +
                12. +
                13. + + +
                  Select 'All libraries' if this debit type should be available at all libraries. Otherwise select libraries you want to associate debit type with.
                  +
                14. +
                +
                + +
                + + Cancel +
                +
              2. + [% END %] + + [% IF op == 'list' %] + + +

                Debit types

                + [% IF debit_types.count %] +
                + + + + + + + + + + + + + + [% FOREACH debit_type IN debit_types %] + + + + + + + + + + + + [% END %] + +
                ArchivedSystemCodeDescriptionDefault amountAvailable forLibrary limitationsBlocks checkouts?Actions
                [% debit_type.archived | html %][% debit_type.is_system | html %][% debit_type.code | html %][%- PROCESS debit_type_description debit_type = debit_type -%][% debit_type.default_amount | $Price %][% IF debit_type.can_be_invoiced && debit_type.can_be_sold %] + Invoicing, Sale + [% ELSIF debit_type.can_be_invoiced %] + Invoicing + [% ELSIF debit_type.can_be_sold %] + Sale [% END %] - -
              3. - - -
              4. -
              5. - - [% IF debit_type && debit_type.is_system %] - [%- PROCESS debit_type_description debit_type = debit_type -%] +
              6. + [% IF debit_type.library_limits.count > 0 %] + [% library_limits_str = "" %] + [% FOREACH library IN debit_type.library_limits %] + [%- IF loop.first -%] + [% library_limits_str = library.branchname _ " (" _ library.branchcode _ ")" %] + [% ELSE %] + [% library_limits_str = library_limits_str _ "\n" _ library.branchname _ " (" _ library.branchcode _ ")" %] + [% END %] + [% END %] + + [% IF debit_type.library_limits.count > 1 %] + [% debit_type.library_limits.count | html %] library limitations + [% ELSE %] + [% debit_type.library_limits.count | html %] library limitation + [% END %] + [% ELSE %] - Required + No limitation [% END %] - -
              7. - - [% IF debit_type.can_be_invoiced %] - - [% ELSE %] - - [% END %] -
              8. -
              9. - - [% IF debit_type.can_be_sold %] - - [% ELSE %] - - [% END %] -
              10. -
              11. - +
              12. [% IF debit_type.restricts_checkouts %] - + Yes [% ELSE %] - + No [% END %] - -
              13. - -
              14. + [% IF !debit_type.archived %] + Edit + [% IF !debit_type.is_system %] +
                + [% INCLUDE 'csrf-token.inc' %] + + + +
                [% END %] - [% END %] - -
                Select 'All libraries' if this debit type should be available at all libraries. Otherwise select libraries you want to associate debit type with.
                - - - - -
                - - Cancel -
                - - [% END %] - - [% IF op == 'list' %] - - -

                Debit types

                - [% IF debit_types.count %] -
                - - - - - - - - - - - - - - [% FOREACH debit_type IN debit_types %] - - - - - - - - - - - + [% ELSIF debit_type.archived %] + + [% INCLUDE 'csrf-token.inc' %] + + + + [% END %] - -
                ArchivedSystemCodeDescriptionDefault amountAvailable forLibrary limitationsBlocks checkouts?Actions
                [% debit_type.archived | html %][% debit_type.is_system | html %][% debit_type.code | html %][%- PROCESS debit_type_description debit_type = debit_type -%][% debit_type.default_amount | $Price %][% IF debit_type.can_be_invoiced && debit_type.can_be_sold %] - Invoicing, Sale - [% ELSIF debit_type.can_be_invoiced %] - Invoicing - [% ELSIF debit_type.can_be_sold %] - Sale - [% END %] - - [% IF debit_type.library_limits.count > 0 %] - [% library_limits_str = "" %] - [% FOREACH library IN debit_type.library_limits %] - [%- IF loop.first -%] - [% library_limits_str = library.branchname _ " (" _ library.branchcode _ ")" %] - [% ELSE %] - [% library_limits_str = library_limits_str _ "\n" _ library.branchname _ " (" _ library.branchcode _ ")" %] - [% END %] - [% END %] - - [% IF debit_type.library_limits.count > 1 %] - [% debit_type.library_limits.count | html %] library limitations - [% ELSE %] - [% debit_type.library_limits.count | html %] library limitation - [% END %] - [% ELSE %] - No limitation - [% END %] - - [% IF debit_type.restricts_checkouts %] - Yes - [% ELSE %] - No - [% END %] - - [% IF !debit_type.archived %] - Edit - [% IF !debit_type.is_system %] -
                - [% INCLUDE 'csrf-token.inc' %] - - - -
                - [% END %] - [% ELSIF debit_type.archived %] -
                - [% INCLUDE 'csrf-token.inc' %] - - - -
                - [% END %] -
                -
                - [% ELSE %] -
                - There are no account debit types defined. Create new debit type -
                - [% END %] - [% END %] +
                + [% ELSE %] +
                There are no account debit types defined. Create new debit type
                + [% END %] + [% END %] [% END %] [% MACRO jsinclude BLOCK %] [% Asset.js("js/admin-menu.js") | $raw %] [% INCLUDE 'datatables.inc' %] - [% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/desks.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/desks.tt index 09693f7bf6..b8df5080e7 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/desks.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/desks.tt @@ -5,22 +5,25 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% IF op =='add_form' %] - [% IF desk.desk_id %] - [% t("Modify desk") | html %] +<title + >[% FILTER collapse %] + [% IF op =='add_form' %] + [% IF desk.desk_id %] + [% t("Modify desk") | html %] + [% ELSE %] + [% t("New desk") | html %] + [% END %] + › [% ELSE %] - [% t("New desk") | html %] - [% END %] › - [% ELSE %] - [% IF op == 'delete_confirm' %] - [% t("Confirm deletion of desk") | html %] › + [% IF op == 'delete_confirm' %] + [% t("Confirm deletion of desk") | html %] + › + [% END %] [% END %] - [% END %] - [% t("Desks") | html %] › - [% t("Administration") | html %] › - [% t("Koha") | html %] -[% END %] + [% t("Desks") | html %] + › [% t("Administration") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -53,161 +56,158 @@ New desk [% END %] [% END %] - [% ELSIF op == 'delete_confirm' %] [% WRAPPER breadcrumb_item bc_active = 1 %] Confirm deletion of desk [% END %] - [% END %] [% END #/ WRAPPER breadcrumbs %] [% END #/ WRAPPER sub-header.inc %] [% WRAPPER 'main-container.inc' aside='admin-menu' %] -[% FOR m IN messages %] -
                - [% SWITCH m.code %] - [% CASE 'error_on_update' %] - An error occurred when updating this desk. Perhaps it already exists. - [% CASE 'error_on_insert' %] - An error occurred when adding this desk. The desk ID might already exist. - [% CASE 'error_on_delete' %] - An error occurred when deleting this desk. Check the logs for details. - [% CASE 'success_on_update' %] - Desk updated successfully. - [% CASE 'success_on_insert' %] - Desk added successfully. - [% CASE 'success_on_delete' %] - Desk deleted successfully. - [% CASE 'already_exists' %] - This desk already exists. - [% CASE %] - [% m.code | html %] - [% END %] -
                -[% END %] - -[% IF op == 'add_form' %] - [% IF desk %] -

                Modify a desk

                - [% ELSE %] -

                New desk

                - [% END %] - -
                - [% INCLUDE 'csrf-token.inc' %] - - - -
                -
                  - [% IF desk %] -
                1. Desk ID: [% desk.desk_id | html %]
                2. - [% END %] -
                3. - - Required -
                4. -
                5. - - -
                6. - -
                -
                - -
                - - Cancel -
                -
                -[% END %] - -[% IF op == 'delete_confirm' %] -
                -

                Delete desk "[% desk.desk_name | html %]"?

                - - - - - - - - - - -
                Desk ID[% desk.desk_id | html %]
                Desk[% desk.desk_name | html %]
                Library[% Branches.GetName( desk.branchcode ) | html %]
                -
                - [% INCLUDE 'csrf-token.inc' %] - - - -
                -
                - -
                -
                -[% END %] - -[% IF op == 'list' %] - - - -

                Desks

                - [% IF searchfield %] - Searching: [% searchfield | html %] - [% END %] - - [% IF desks.count %] -
                - - - - - - - - - - - [% FOREACH desk IN desks %] - - - - - - - [% END %] - -
                Desk IDDeskLibraryAction
                [% desk.desk_id | html %][% desk.desk_name | html %][% Branches.GetName( desk.branchcode ) | html %] - Edit - Delete -
                -
                - [% ELSE %] -
                - There are no desks defined. Create a new desk. + [% FOR m IN messages %] +
                + [% SWITCH m.code %] + [% CASE 'error_on_update' %] + An error occurred when updating this desk. Perhaps it already exists. + [% CASE 'error_on_insert' %] + An error occurred when adding this desk. The desk ID might already exist. + [% CASE 'error_on_delete' %] + An error occurred when deleting this desk. Check the logs for details. + [% CASE 'success_on_update' %] + Desk updated successfully. + [% CASE 'success_on_insert' %] + Desk added successfully. + [% CASE 'success_on_delete' %] + Desk deleted successfully. + [% CASE 'already_exists' %] + This desk already exists. + [% CASE %] + [% m.code | html %] + [% END %]
                [% END %] -[% END %] + [% IF op == 'add_form' %] + [% IF desk %] +

                Modify a desk

                + [% ELSE %] +

                New desk

                + [% END %] + +
                + [% INCLUDE 'csrf-token.inc' %] + + + +
                +
                  + [% IF desk %] +
                1. Desk ID: [% desk.desk_id | html %]
                2. + [% END %] +
                3. + + Required +
                4. +
                5. + + +
                6. +
                +
                + +
                + + Cancel +
                +
                + [% END %] + + [% IF op == 'delete_confirm' %] +
                +

                Delete desk "[% desk.desk_name | html %]"?

                + + + + + + + + + + +
                Desk ID[% desk.desk_id | html %]
                Desk[% desk.desk_name | html %]
                Library[% Branches.GetName( desk.branchcode ) | html %]
                +
                + [% INCLUDE 'csrf-token.inc' %] + + + +
                +
                + +
                +
                + [% END %] + + [% IF op == 'list' %] + + +

                Desks

                + [% IF searchfield %] + Searching: [% searchfield | html %] + [% END %] + + [% IF desks.count %] +
                + + + + + + + + + + + [% FOREACH desk IN desks %] + + + + + + + [% END %] + +
                Desk IDDeskLibraryAction
                [% desk.desk_id | html %][% desk.desk_name | html %][% Branches.GetName( desk.branchcode ) | html %] + Edit + Delete +
                +
                + + [% ELSE %] +
                There are no desks defined. Create a new desk.
                + [% END %] + [% END %] [% END %] [% MACRO jsinclude BLOCK %] @@ -215,9 +215,9 @@ [% INCLUDE 'datatables.inc' %] [% INCLUDE 'columns_settings.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/didyoumean.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/didyoumean.tt index 59922e6a80..ac557f41f3 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/didyoumean.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/didyoumean.tt @@ -4,32 +4,38 @@ [% USE Koha %] [% SET footerjs = 1 %] [% BLOCK pluginlist %] -
                -[% FOREACH plugin IN plugins %] -
                -
                - [% IF plugin.enabled %][% ELSE %][% END %] -
                -
                - [% SWITCH plugin.name %] - [% CASE 'AuthorityFile' %] - Suggest authorities which are relevant to the term the user searched for. - [% CASE 'ExplodedTerms' %] - Suggest that patrons expand their searches to include broader/narrower/related terms. - [% CASE 'LibrisSpellcheck' %] - Use the LIBRIS spellcheck API. +
                + [% FOREACH plugin IN plugins %] +
                +
                + [% IF plugin.enabled %] + + [% ELSE %] + + [% END %] +
                +
                + [% SWITCH plugin.name %] + [% CASE 'AuthorityFile' %] + Suggest authorities which are relevant to the term the user searched for. + [% CASE 'ExplodedTerms' %] + Suggest that patrons expand their searches to include broader/narrower/related terms. + [% CASE 'LibrisSpellcheck' %] + Use the LIBRIS spellcheck API. + [% END %] +
                +
                [% END %] -
                [% END %] -
                -[% END %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Did you mean?") | html %] › - [% t("Administration") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Did you mean?") | html %] + › [% t("Administration") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -42,91 +48,79 @@ [% WRAPPER breadcrumbs %] [% WRAPPER breadcrumb_item %] Administration - [% END %] + [% END %] [% WRAPPER breadcrumb_item bc_active= 1 %] Did you mean? - [% END %] + [% END %] [% END #/ WRAPPER breadcrumbs %] [% END #/ WRAPPER sub-header.inc %] [% WRAPPER 'main-container.inc' aside='admin-menu' %] - -

                Did you mean?

                - -
                - Please put the 'Did you mean?' plugins in order by significance, from - most significant to least significant, and check the box to enable those - plugins that you want to use. -
                -
                -
                - OPAC - [% PROCESS pluginlist plugins=OPACpluginlist type='opac' %] -
                -
                - - Cancel -
                -
                - +

                Did you mean?

                + +
                Please put the 'Did you mean?' plugins in order by significance, from most significant to least significant, and check the box to enable those plugins that you want to use.
                +
                +
                + OPAC + [% PROCESS pluginlist plugins=OPACpluginlist type='opac' %] +
                +
                + + Cancel +
                +
                [% END %] [% MACRO jsinclude BLOCK %] [% Asset.js("js/admin-menu.js") | $raw %] [% Asset.js( "lib/sortable/Sortable.min.js" ) | $raw %] [% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/edi_accounts.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/edi_accounts.tt index faff2f77ab..daa7abfefb 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/edi_accounts.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/edi_accounts.tt @@ -4,21 +4,23 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% IF acct_form %] - [% IF account %] - [% tx("Modify account '{edi_account}' for vendor '{vendor}'", { edi_account = account.description, vendor = account.vendor.name }) %] - [% ELSE %] - [% t("New account") | html %] - [% END %] › - [% END %] - [% IF delete_confirm %] - [% tx("Confirm deletion of account '{edi_account}' for vendor '{vendor}'", { edi_account = account.description, vendor = account.vendor.name }) %] - [% END %] - [% t("EDI accounts") | html %] › - [% t("Administration") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% IF acct_form %] + [% IF account %] + [% tx("Modify account '{edi_account}' for vendor '{vendor}'", { edi_account = account.description, vendor = account.vendor.name }) %] + [% ELSE %] + [% t("New account") | html %] + [% END %] + › + [% END %] + [% IF delete_confirm %] + [% tx("Confirm deletion of account '{edi_account}' for vendor '{vendor}'", { edi_account = account.description, vendor = account.vendor.name }) %] + [% END %] + [% t("EDI accounts") | html %] + › [% t("Administration") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -52,7 +54,6 @@ New account [% END %] [% END %] - [% ELSIF delete_confirm %] [% WRAPPER breadcrumb_item bc_active= 1 %] [% tx("Confirm deletion of account '{edi_account}' for vendor '{vendor}'", { edi_account = account.description, vendor = account.vendor.name }) %] @@ -63,331 +64,315 @@ [% WRAPPER 'main-container.inc' aside='admin-menu' %] -[% UNLESS Koha.Preference('EDIFACT') %] -
                - EDIFACT is currently disabled -
                -[% END %] - -[% IF display %] - -[% END %] - -[% IF acct_form %] -
                - [% INCLUDE 'csrf-token.inc' %] - - [% IF account %] - - [% END %] -

                - [% IF account %] - [% tx("Modify account '{edi_account}' for vendor '{vendor}'", { edi_account = account.description, vendor = account.vendor.name }) %] - [% ELSE %] - New account - [% END %] -

                -
                - Account details - -
                  -
                1. - - -
                2. - [% IF plugins %] -
                3. - - -
                4. - [% ELSE %] - - [% END %] -
                5. - - -
                6. -
                7. - [% transport_types = [ 'FTP', 'SFTP', 'FILE' ] %] - - -
                8. -
                9. - - -
                10. -
                11. - - -
                12. -
                13. - - -
                14. -
                15. - - -
                  The upload port will default to 22 if not set.
                  -
                16. -
                17. - - -
                  The download port will default to 22 if not set.
                  -
                18. -
                19. - - -
                  The download directory specifies the directory on the ftp site from which quotes and invoices are downloaded.
                  -
                20. -
                21. - - -
                  The upload directory specifies the directory on the ftp site to which orders are uploaded.
                  -
                22. -
                23. - - -
                24. -
                25. - - -
                26. -
                27. - - -
                28. -
                29. - - [% IF account.quotes_enabled %] - - [% ELSE %] - - [% END %] -
                30. -
                31. - -[% IF account.orders_enabled %] - -[% ELSE %] - -[% END %] -
                32. -
                33. - -[% IF account.invoices_enabled %] - -[% ELSE %] - -[% END %] -
                34. -
                35. - -[% IF account.responses_enabled %] - -[% ELSE %] - -[% END %] -
                36. -
                37. - -[% IF account.auto_orders %] - -[% ELSE %] - -[% END %] -
                  - With automatic ordering quotes generate orders without staff intervention. -
                  -
                38. -
                -
                - -
                - - Cancel -
                -
                - -[% END %] -[% IF delete_confirm %] -
                -

                Confirm deletion of account?

                - - - - - - - - - - - - - -
                Vendor[% account.vendor.name | html %]
                Description[% account.description | html %]
                SAN[% account.san | html %]
                -
                - [% INCLUDE 'csrf-token.inc' %] - -
                - - - -
                -
                - -
                -
                -[% END %] -[% IF display %] -[% IF ( ediaccounts ) %] -

                EDI accounts

                -
                - - - - - - - - - - - - - - - - - - - - - - - - [% FOREACH account IN ediaccounts %] - - - - - - - - - - - - - - - - [% IF account.quotes_enabled %] - - [% ELSE %] - - [% END %] - [% IF account.orders_enabled %] - - [% ELSE %] - - [% END %] - [% IF account.invoices_enabled %] - - [% ELSE %] - - [% END %] - [% IF account.responses_enabled %] - - [% ELSE %] - - [% END %] - [% IF account.auto_orders %] - - [% ELSE %] - - [% END %] - - + [% UNLESS Koha.Preference('EDIFACT') %] +
                EDIFACT is currently disabled
                [% END %] -
                IDVendorDescriptionTransportRemote hostUsernamePasswordUpload portDownload portDownload directoryUpload directoryQualifierSANStandard[% tp('EDIFACT message QUOTE', 'Quotes') | html %]OrdersInvoicesResponsesAuto orderingActions
                [% account.id | html %][% account.vendor.name | html %][% account.description | html %][% account.transport | html %][% account.host | html %][% account.username | html %][% IF account.password %]*****[% END %][% account.upload_port | html %][% account.download_port | html %][% account.download_directory | html %][% account.upload_directory | html %] - [% FOREACH qualifier IN code_qualifiers %] - [% IF qualifier.code == account.id_code_qualifier %] - [% qualifier.description | html %] - [% END %] - [% END %] - ([% account.id_code_qualifier | html %]) - [% account.san | html %][% IF account.standard == 'BIC' %]BiC[% ELSE %]EDItEUR[% END %]YesNoYesNoYesNoYesNoYesNo - Edit Delete -
                -
                - [% ELSE %] -
                - There are no EDI accounts. + + [% IF display %] + [% END %] -[% END %] + [% IF acct_form %] +
                + [% INCLUDE 'csrf-token.inc' %] + + [% IF account %] + + [% END %] +

                + [% IF account %] + [% tx("Modify account '{edi_account}' for vendor '{vendor}'", { edi_account = account.description, vendor = account.vendor.name }) %] + [% ELSE %] + New account + [% END %] +

                +
                + Account details + +
                  +
                1. + + +
                2. + [% IF plugins %] +
                3. + + +
                4. + [% ELSE %] + + [% END %] +
                5. + + +
                6. +
                7. + [% transport_types = [ 'FTP', 'SFTP', 'FILE' ] %] + + +
                8. +
                9. + + +
                10. +
                11. + + +
                12. +
                13. + + +
                14. +
                15. + + +
                  The upload port will default to 22 if not set.
                  +
                16. +
                17. + + +
                  The download port will default to 22 if not set.
                  +
                18. +
                19. + + +
                  The download directory specifies the directory on the ftp site from which quotes and invoices are downloaded.
                  +
                20. +
                21. + + +
                  The upload directory specifies the directory on the ftp site to which orders are uploaded.
                  +
                22. +
                23. + + +
                24. +
                25. + + +
                26. +
                27. + + +
                28. +
                29. + + [% IF account.quotes_enabled %] + + [% ELSE %] + + [% END %] +
                30. +
                31. + + [% IF account.orders_enabled %] + + [% ELSE %] + + [% END %] +
                32. +
                33. + + [% IF account.invoices_enabled %] + + [% ELSE %] + + [% END %] +
                34. +
                35. + + [% IF account.responses_enabled %] + + [% ELSE %] + + [% END %] +
                36. +
                37. + + [% IF account.auto_orders %] + + [% ELSE %] + + [% END %] +
                  With automatic ordering quotes generate orders without staff intervention.
                  +
                38. +
                +
                + +
                + + Cancel +
                +
                + [% END %] + [% IF delete_confirm %] +
                +

                Confirm deletion of account?

                + + + + + + + + + + + + + +
                Vendor[% account.vendor.name | html %]
                Description[% account.description | html %]
                SAN[% account.san | html %]
                +
                + [% INCLUDE 'csrf-token.inc' %] +
                + + + +
                +
                + +
                +
                + [% END %] + [% IF display %] + [% IF ( ediaccounts ) %] +

                EDI accounts

                +
                + + + + + + + + + + + + + + + + + + + + + + + + [% FOREACH account IN ediaccounts %] + + + + + + + + + + + + + + + + [% IF account.quotes_enabled %] + + [% ELSE %] + + [% END %] + [% IF account.orders_enabled %] + + [% ELSE %] + + [% END %] + [% IF account.invoices_enabled %] + + [% ELSE %] + + [% END %] + [% IF account.responses_enabled %] + + [% ELSE %] + + [% END %] + [% IF account.auto_orders %] + + [% ELSE %] + + [% END %] + + + [% END %] +
                IDVendorDescriptionTransportRemote hostUsernamePasswordUpload portDownload portDownload directoryUpload directoryQualifierSANStandard[% tp('EDIFACT message QUOTE', 'Quotes') | html %]OrdersInvoicesResponsesAuto orderingActions
                [% account.id | html %][% account.vendor.name | html %][% account.description | html %][% account.transport | html %][% account.host | html %][% account.username | html %][% IF account.password %]*****[% END %][% account.upload_port | html %][% account.download_port | html %][% account.download_directory | html %][% account.upload_directory | html %] + [% FOREACH qualifier IN code_qualifiers %] + [% IF qualifier.code == account.id_code_qualifier %] + [% qualifier.description | html %] + [% END %] + [% END %] + ([% account.id_code_qualifier | html %]) + [% account.san | html %][% IF account.standard == 'BIC' %]BiC[% ELSE %]EDItEUR[% END %]YesNoYesNoYesNoYesNoYesNo + Edit + Delete +
                +
                + + [% ELSE %] +
                There are no EDI accounts.
                + [% END %] + [% END %] [% END %] [% MACRO jsinclude BLOCK %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/edi_ean_accounts.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/edi_ean_accounts.tt index ef7b36ef78..5afe109868 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/edi_ean_accounts.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/edi_ean_accounts.tt @@ -4,25 +4,28 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% IF ean_form %] - [% IF ean %] - [% tx("Modify library EAN '{ean}'", { ean = ean.description }) %] - [% ELSE %] - [% t("New library EAN") | html %] - [% END %] › - [% END %] - [% IF delete_confirm %] - [% IF ( ean.branch.branchname ) %] - [% tx("Confirm deletion of EAN '{ean}' for '{library}'?", { ean = ean.description, library = ean.branch.branchname }) %] - [% ELSE %] - [% tx("Confirm deletion of EAN '{ean}'?", { ean = ean.description }) %] - [% END %] › - [% END %] - [% t("Library EANs") | html %] › - [% t("Administration") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% IF ean_form %] + [% IF ean %] + [% tx("Modify library EAN '{ean}'", { ean = ean.description }) %] + [% ELSE %] + [% t("New library EAN") | html %] + [% END %] + › + [% END %] + [% IF delete_confirm %] + [% IF ( ean.branch.branchname ) %] + [% tx("Confirm deletion of EAN '{ean}' for '{library}'?", { ean = ean.description, library = ean.branch.branchname }) %] + [% ELSE %] + [% tx("Confirm deletion of EAN '{ean}'?", { ean = ean.description }) %] + [% END %] + › + [% END %] + [% t("Library EANs") | html %] + › [% t("Administration") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -40,28 +43,26 @@ [% WRAPPER breadcrumb_item %] Library EANs [% END %] - [% WRAPPER breadcrumb_item bc_active= 1%] + [% WRAPPER breadcrumb_item bc_active= 1 %] [% IF ean %] [% tx("Modify library EAN '{ean}'", { ean = ean.description }) %] [% ELSE %] New library EAN [% END %] [% END %] - [% ELSIF delete_confirm %] [% WRAPPER breadcrumb_item %] Library EANs [% END %] - [% WRAPPER breadcrumb_item bc_active= 1%] + [% WRAPPER breadcrumb_item bc_active= 1 %] [% IF ( ean.branch.branchname ) %] [% tx("Confirm deletion of EAN '{ean}' for '{library}'?", { ean = ean.description, library = ean.branch.branchname }) %] [% ELSE %] [% tx("Confirm deletion of EAN '{ean}'?", { ean = ean.description }) %] [% END %] [% END %] - [% ELSE %] - [% WRAPPER breadcrumb_item bc_active= 1%] + [% WRAPPER breadcrumb_item bc_active= 1 %] Library EANs [% END %] [% END %] @@ -70,148 +71,143 @@ [% WRAPPER 'main-container.inc' aside='admin-menu' %] -[% IF display %] - -[% END %] + [% IF display %] + + [% END %] -[% IF ean_form %] -
                - [% INCLUDE 'csrf-token.inc' %] - - [% IF ean %] - - - [% END %] + [% IF ean_form %] + + [% INCLUDE 'csrf-token.inc' %] + + [% IF ean %] + + + [% END %] -

                - [% IF ean %] - [% tx("Modify library EAN '{ean}'", { ean = ean.description }) %] - [% ELSE %] - New EAN - [% END %] -

                - -
                - EAN details - -
                  -
                1. - - -
                2. -
                3. - - -
                4. -
                5. - - -
                6. -
                7. - - -
                8. -
                -
                - -
                - - Cancel -
                -
                -[% END %] - -[% IF delete_confirm %] -
                -

                - [% IF ( ean.branch.branchname ) %] - [% tx("Confirm deletion of EAN '{ean}' for '{library}'?", { ean = ean.description, library = ean.branch.branchname }) %] - [% ELSE %] - [% tx("Confirm deletion of EAN '{ean}'?", { ean = ean.description }) %] - [% END %] -

                - -
                - [% INCLUDE 'csrf-token.inc' %] - - - -
                -
                - -
                -
                -[% END %] - -[% IF display %] -

                Library EANs

                -[% IF ( eans ) %] -
                - - - - - - - - - [% FOREACH ean IN eans %] - - [% IF ean.branch %] - +

                + [% IF ean %] + [% tx("Modify library EAN '{ean}'", { ean = ean.description }) %] [% ELSE %] -

                + New EAN [% END %] - - - - - - [% END %] -
                LibraryDescriptionEANQualifierActions
                [% ean.branch.branchname | html %]All libraries[% ean.description | html %][% ean.ean | html %] - [% FOREACH qualifier IN code_qualifiers %] - [% IF qualifier.code == ean.id_code_qualifier %] - [% qualifier.description | html %] ([% qualifier.code | html %]) - [% END %] - [% END %] - - Edit - Delete -
                -
                -[% ELSE %] -
                - There are no library EANs. -
                -[% END %] -[% END %] + +
                + EAN details + +
                  +
                1. + + +
                2. +
                3. + + +
                4. +
                5. + + +
                6. +
                7. + + +
                8. +
                +
                + +
                + + Cancel +
                + + [% END %] + + [% IF delete_confirm %] +
                +

                + [% IF ( ean.branch.branchname ) %] + [% tx("Confirm deletion of EAN '{ean}' for '{library}'?", { ean = ean.description, library = ean.branch.branchname }) %] + [% ELSE %] + [% tx("Confirm deletion of EAN '{ean}'?", { ean = ean.description }) %] + [% END %] +

                + +
                + [% INCLUDE 'csrf-token.inc' %] + + + +
                +
                + +
                +
                + [% END %] + + [% IF display %] +

                Library EANs

                + [% IF ( eans ) %] +
                + + + + + + + + + [% FOREACH ean IN eans %] + + [% IF ean.branch %] + + [% ELSE %] + + [% END %] + + + + + + [% END %] +
                LibraryDescriptionEANQualifierActions
                [% ean.branch.branchname | html %]All libraries[% ean.description | html %][% ean.ean | html %] + [% FOREACH qualifier IN code_qualifiers %] + [% IF qualifier.code == ean.id_code_qualifier %] + [% qualifier.description | html %] + ([% qualifier.code | html %]) + [% END %] + [% END %] + + Edit + Delete +
                +
                + + [% ELSE %] +
                There are no library EANs.
                + [% END %] + [% END %] [% END %] [% MACRO jsinclude BLOCK %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/identity_provider_domains.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/identity_provider_domains.tt index dd6f85166b..b38d542948 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/identity_provider_domains.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/identity_provider_domains.tt @@ -6,17 +6,19 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% IF op == 'add_form' %] - [% t("New identity provider domain") | html %] › - [% ELSIF op == 'edit_form' %] - [% tx("Modify identity provider domain '{domain}'", {domain = identity_provider_domain.domain}) | html %] › - [% END %] - [% tx("Identity provider domains for '{identity_provider_code}'", {identity_provider_code = identity_provider_code}) | html %] › - [% t("Identity providers") | html %] › - [% t("Administration") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% IF op == 'add_form' %] + [% t("New identity provider domain") | html %] + › + [% ELSIF op == 'edit_form' %] + [% tx("Modify identity provider domain '{domain}'", {domain = identity_provider_domain.domain}) | html %] + › + [% END %] + [% tx("Identity provider domains for '{identity_provider_code}'", {identity_provider_code = identity_provider_code}) | html %] + › [% t("Identity providers") | html %] › [% t("Administration") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -36,20 +38,22 @@ [% IF op == 'add_form' %] [% WRAPPER breadcrumb_item %] - [% tx("Domains for '{identity_provider_code}'", {identity_provider_code = identity_provider_code}) | html %] + [% tx("Domains for '{identity_provider_code}'", {identity_provider_code = identity_provider_code}) | html %] [% END %] [% WRAPPER breadcrumb_item bc_active= 1 %] New identity provider domain [% END %] - [% ELSIF op == 'edit_form' %] [% WRAPPER breadcrumb_item %] - [% tx("Domains for '{identity_provider_code}'", {identity_provider_code = identity_provider_code}) | html %] + [% tx("Domains for '{identity_provider_code}'", {identity_provider_code = identity_provider_code}) | html %] [% END %] [% WRAPPER breadcrumb_item bc_active= 1 %] [% tx("Modify identity provider domain '{domain}'", {domain = identity_provider_domain.domain}) | html %] [% END %] - [% ELSE %] [% WRAPPER breadcrumb_item bc_active= 1 %] [% tx("Domains for '{identity_provider_code}'", {identity_provider_code = identity_provider_code}) | html %] @@ -60,28 +64,28 @@ [% WRAPPER 'main-container.inc' aside='admin-menu' %] -[% FOREACH m IN messages %] -
                - [% SWITCH m.code %] - [% CASE 'error_on_update' %] - An error occurred trying to open the identity provider domain for editing. The passed ID is invalid. - [% CASE 'error_on_insert' %] - An error occurred when adding a new identity provider domain. Check the logs for details. - [% CASE 'success_on_update' %] - Identity provider domain updated successfully. - [% CASE 'success_on_insert' %] - Identity provider domain added successfully. - [% CASE %] - [% m.code | html %] - [% END %] -
                -[% END %] + [% FOREACH m IN messages %] +
                + [% SWITCH m.code %] + [% CASE 'error_on_update' %] + An error occurred trying to open the identity provider domain for editing. The passed ID is invalid. + [% CASE 'error_on_insert' %] + An error occurred when adding a new identity provider domain. Check the logs for details. + [% CASE 'success_on_update' %] + Identity provider domain updated successfully. + [% CASE 'success_on_insert' %] + Identity provider domain added successfully. + [% CASE %] + [% m.code | html %] + [% END %] +
                + [% END %] - + -[% IF op == 'add_form' %] -

                [% tx("New identity provider domain for '{identity_provider_code}'", {identity_provider_code = identity_provider_code}) | html %]

                + [% IF op == 'add_form' %] +

                [% tx("New identity provider domain for '{identity_provider_code}'", {identity_provider_code = identity_provider_code}) | html %]

                [% INCLUDE 'csrf-token.inc' %] @@ -93,7 +97,9 @@
              15. -
                Email domain to match this rule.
                +
                Email domain to match this rule.
              + [% END %] -[% END %] - -[% IF op == 'edit_form' %] -

              [% tx("Modify identity provider domain '{domain}'", {domain = identity_provider_domain.domain}) | html %]

              + [% IF op == 'edit_form' %] +

              [% tx("Modify identity provider domain '{domain}'", {domain = identity_provider_domain.domain}) | html %]

              [% INCLUDE 'csrf-token.inc' %] @@ -175,8 +180,10 @@
              1. - -
                Email domain to match this rule.
                + +
                Email domain to match this rule.
              2. user data on login
              3. users to auto register on login
              4. @@ -236,26 +243,26 @@
              5. OPAC users of this domain to login with this identity provider
              6. staff users of this domain to login with this identity provider
              7. @@ -266,52 +273,54 @@ Cancel
              + [% END %] -[% END %] + [% IF op == 'list' %] + -[% IF op == 'list' %] +

              [% tx("Identity provider domains for '{identity_provider_code}'", {identity_provider_code = identity_provider_code}) | html %]

              +
              + + + + + + + + + + + + + +
              DomainUpdate on loginAuto registerDefault libraryDefault categoryAllow OPACAllow staffActions
              +
              + [% END %] -
              - New identity provider domain + - -

              [% tx("Identity provider domains for '{identity_provider_code}'", {identity_provider_code = identity_provider_code}) | html %]

              -
              - - - - - - - - - - - - - -
              DomainUpdate on loginAuto registerDefault libraryDefault categoryAllow OPACAllow staffActions
              -
              -[% END %] - - - + [% END %] [% MACRO jsinclude BLOCK %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/identity_providers.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/identity_providers.tt index 86e893ffec..fad61c278f 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/identity_providers.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/identity_providers.tt @@ -6,16 +6,19 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% IF op == 'add_form' %] - [% t("New identity provider") | html %] › - [% ELSIF op == 'edit_form' %] - [% tx("Modify identity provider '{id_provider}'", {id_provider = identity_provider.code}) | html %] › - [% END %] - [% t("Identity providers") | html %] › - [% t("Administration") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% IF op == 'add_form' %] + [% t("New identity provider") | html %] + › + [% ELSIF op == 'edit_form' %] + [% tx("Modify identity provider '{id_provider}'", {id_provider = identity_provider.code}) | html %] + › + [% END %] + [% t("Identity providers") | html %] + › [% t("Administration") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -36,7 +39,6 @@ [% WRAPPER breadcrumb_item bc_active= 1 %] New identity provider [% END %] - [% ELSIF op == 'edit_form' %] [% WRAPPER breadcrumb_item %] Identity providers @@ -44,7 +46,6 @@ [% WRAPPER breadcrumb_item bc_active= 1 %] [% tx("Modify identity provider '{id_provider}'", {id_provider = identity_provider.code}) | html %] [% END %] - [% ELSE %] [% WRAPPER breadcrumb_item bc_active= 1 %] Identity providers @@ -55,29 +56,29 @@ [% WRAPPER 'main-container.inc' aside='admin-menu' %] -[% FOREACH m IN messages %] -
              - [% SWITCH m.code %] - [% CASE 'error_on_update' %] - An error occurred trying to open the identity provider for editing. The passed ID is invalid. - [% CASE 'error_on_insert' %] - An error occurred when adding a new identity provider. Check the logs for details. - [% CASE 'success_on_update' %] - Identity provider updated successfully. - [% CASE 'success_on_insert' %] -
              Identity provider added successfully.
              -
              You will need to restart Koha for the provider to work.
              - [% CASE %] - [% m.code | html %] - [% END %] -
              -[% END %] + [% FOREACH m IN messages %] +
              + [% SWITCH m.code %] + [% CASE 'error_on_update' %] + An error occurred trying to open the identity provider for editing. The passed ID is invalid. + [% CASE 'error_on_insert' %] + An error occurred when adding a new identity provider. Check the logs for details. + [% CASE 'success_on_update' %] + Identity provider updated successfully. + [% CASE 'success_on_insert' %] +
              Identity provider added successfully.
              +
              You will need to restart Koha for the provider to work.
              + [% CASE %] + [% m.code | html %] + [% END %] +
              + [% END %] - + -[% IF op == 'add_form' %] -

              New identity provider

              + [% IF op == 'add_form' %] +

              New identity provider

              [% INCLUDE 'csrf-token.inc' %] @@ -119,7 +120,9 @@ Required -
              Provider's main configuration.
              +
              Provider's main configuration.
              +
              + +
              + +
              + [% MACRO jsinclude BLOCK %] [% INCLUDE 'datatables.inc' %] [% END %] [% INCLUDE 'intranet-bottom.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/marc_order_accounts.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/marc_order_accounts.tt index 5b8fd6c94e..99174f9cfb 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/marc_order_accounts.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/marc_order_accounts.tt @@ -4,9 +4,7 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] - -MARC order accounts - + MARC order accounts [% INCLUDE 'doc-head-close.inc' %] @@ -38,295 +36,291 @@ MARC order accounts [% WRAPPER 'main-container.inc' aside='admin-menu' %] - [% IF display %] - - [% IF ( accounts ) %] -

              MARC ordering accounts

              -
              - - - - - - - - - - [% FOREACH account IN accounts %] - - - - - - - - - [% END %] -
              IDVendorBudgetDescriptionDownload directoryActions
              [% account.id | html %][% account.vendor.name | html %][% account.budget.budget_name | html %][% account.description | html %][% account.download_directory | html %] - Edit - Delete -
              -
              - [% ELSE %] -
              - There are no MARC order accounts. -
              + [% IF display %] + + [% IF ( accounts ) %] +

              MARC ordering accounts

              +
              + + + + + + + + + + [% FOREACH account IN accounts %] + + + + + + + + [% END %] - [% END %] - [% IF acct_form %] -

              - [% IF account %] - Modify account +

              IDVendorBudgetDescriptionDownload directoryActions
              [% account.id | html %][% account.vendor.name | html %][% account.budget.budget_name | html %][% account.description | html %][% account.download_directory | html %] + Edit + Delete +
              +
              + [% ELSE %] +
              There are no MARC order accounts.
              + [% END %] + [% END %] + [% IF acct_form %] +

              + [% IF account %] + Modify account + [% ELSE %] + New account + [% END %] +

              +
              + [% INCLUDE 'csrf-token.inc' %] + + [% IF account %] + + [% END %] +
              + Account details +
                +
              1. + + +
              2. +
              3. + + +
                This fund will be used as the fallback value if the MARC records do not contain a mapped value for a fund code.
                +
              4. +
              5. + + +
              6. +
              7. + + +
                The download directory specifies the directory in your Koha installation that should be searched for new files.
                +
              8. +
              9. + + +
                (Optional): If you have files from multiple vendors in the same file directory, the match field is the field in the MARC record that will be checked to see if the file should be processed by this account.
                +
                The format for this field is the same as MARCFieldsToOrder - the field and the subfield separated by a dollar sign e.g. 245$a
                +
              10. +
              11. + + +
                (Optional): This is the value that will be checked against the match field to see if the file matches this account. If it does it will be processed by this account, if not it will be skipped.
                +
              12. +
              +
              +
              + File import settings +
                +
              1. + + +
              2. +
              3. + + +
              4. +
              +
              +
              + Record matching settings +
                +
              1. + + +
              2. +
              3. + + [% INCLUDE 'tools-overlay-action.inc' class_name='select2' %] +
              4. +
              5. + + [% INCLUDE 'tools-nomatch-action.inc' class_name='select2' %] +
              6. +
              +
              +
              + Check for embedded item record data? +
                +
              1. + [% IF ( account.parse_items == 1 || !account ) %] + [% ELSE %] - New account + [% END %] - - - [% INCLUDE 'csrf-token.inc' %] - - [% IF account %] - + +
              2. +
              3. + [% IF ( account.parse_items == 0 ) %] + + [% ELSE %] + [% END %] -
                - Account details -
                  -
                1. - - -
                2. -
                3. - - -
                  This fund will be used as the fallback value if the MARC records do not contain a mapped value for a fund code.
                  -
                4. -
                5. - - -
                6. -
                7. - - -
                  The download directory specifies the directory in your Koha installation that should be searched for new files.
                  -
                8. -
                9. - - -
                  (Optional): If you have files from multiple vendors in the same file directory, the match field is the field in the MARC record that will be checked to see if the file should be processed by this account.
                  -
                  The format for this field is the same as MARCFieldsToOrder - the field and the subfield separated by a dollar sign e.g. 245$a
                  -
                10. -
                11. - - -
                  (Optional): This is the value that will be checked against the match field to see if the file matches this account. If it does it will be processed by this account, if not it will be skipped.
                  -
                12. -
                -
                -
                - File import settings -
                  -
                1. - - -
                2. -
                3. - - -
                4. -
                -
                -
                - Record matching settings -
                  -
                1. - - -
                2. -
                3. - - [% INCLUDE 'tools-overlay-action.inc' class_name='select2' %] -
                4. -
                5. - - [% INCLUDE 'tools-nomatch-action.inc' class_name='select2' %] -
                6. -
                -
                -
                - Check for embedded item record data? -
                  -
                1. - [% IF ( account.parse_items == 1 || !account ) %] - - [% ELSE %] - - [% END %] - -
                2. -
                3. - [% IF ( account.parse_items == 0 ) %] - - [% ELSE %] - - [% END %] - -
                4. -
                -
                  -
                1. - - [% INCLUDE 'tools-item-action.inc' class_name='select2' %] -
                2. -
                -
                + +
              4. +
              +
                +
              1. + + [% INCLUDE 'tools-item-action.inc' class_name='select2' %] +
              2. +
              +
              -
              - - Cancel -
              -
              - [% END %] - [% IF delete_acct %] -
              -

              Delete this account?

              - - - - - - - - - -
              VendorDescription
              [% account.vendor.name | html %][% account.description | html %]
              -
              - [% INCLUDE 'csrf-token.inc' %] - - - -
              -
              - -
              -
              - [% END %] +
              + + Cancel +
              + + [% END %] + [% IF delete_acct %] +
              +

              Delete this account?

              + + + + + + + + + +
              VendorDescription
              [% account.vendor.name | html %][% account.description | html %]
              +
              + [% INCLUDE 'csrf-token.inc' %] + + + +
              +
              + +
              +
              + [% END %] [% END %] [% MACRO jsinclude BLOCK %] [% Asset.js("js/admin-menu.js") | $raw %] [% INCLUDE 'select2.inc' %] - + + $("#vendor_id").kohaSelect({ + width: "10%", + allowClear: false, + ajax: { + url: "/api/v1/acquisitions/vendors", + delay: 300, // wait 300 milliseconds before triggering the request + cache: true, + dataType: "json", + data: function (params) { + var search_term = params.term === undefined ? "" : params.term; + var query = { + q: JSON.stringify({ name: { "-like": "%" + search_term + "%" } }), + _order_by: "name", + _page: params.page, + }; + + return query; + }, + processResults: function (data) { + var results = []; + data.results.forEach(function (vendor) { + results.push({ + id: vendor.id, + text: vendor.name.escapeHtml(), + }); + }); + return { results: results, pagination: { more: data.pagination.more } }; + }, + }, + templateResult: display_vendor, + templateSelection: display_vendor, + }); + }); + [% END %] [% INCLUDE 'intranet-bottom.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/marc_subfields_structure.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/marc_subfields_structure.tt index c6f9c7edd2..a14cc5fc2d 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/marc_subfields_structure.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/marc_subfields_structure.tt @@ -4,416 +4,444 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% IF ( add_form ) %] - [% t("Edit subfield constraints") | html %] › - [% END %] +<title + >[% FILTER collapse %] + [% IF ( add_form ) %] + [% t("Edit subfield constraints") | html %] + › + [% END %] - [% IF ( delete_confirm ) %] - [% tx("Confirm deletion of subfield '{subfield}'", {subfield = mss.tagsubfield }) | html %] › - [% END %] + [% IF ( delete_confirm ) %] + [% tx("Confirm deletion of subfield '{subfield}'", {subfield = mss.tagsubfield }) | html %] + › + [% END %] - [% IF ( add_form || delete_confirm || else ) %] - [% tx("Tag {tag}", { tag = tagfield}) | html %] › - [% END %] + [% IF ( add_form || delete_confirm || else ) %] + [% tx("Tag {tag}", { tag = tagfield}) | html %] + › + [% END %] - [% IF ( frameworkcode ) %] - [% framework.frameworktext | html %] ([% framework.frameworkcode | html %]) - [% ELSE %] - [% t("Default framework") | html %] - [% END %] › - - [% t("MARC bibliographic frameworks") | html %] › - - [% t("Administration") | html %] › - - [% t("Koha") | html %] -[% END %] + [% IF ( frameworkcode ) %] + [% framework.frameworktext | html %] + ([% framework.frameworkcode | html %]) + [% ELSE %] + [% t("Default framework") | html %] + [% END %] + › [% t("MARC bibliographic frameworks") | html %] › [% t("Administration") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] - + - [% WRAPPER 'header.inc' %] +[% WRAPPER 'header.inc' %] [% INCLUDE 'prefs-admin-search.inc' %] [% END %] - [% WRAPPER 'sub-header.inc' %] - [% WRAPPER breadcrumbs %] +[% WRAPPER 'sub-header.inc' %] + [% WRAPPER breadcrumbs %] + [% WRAPPER breadcrumb_item %] + Administration + [% END %] + [% WRAPPER breadcrumb_item %] + MARC bibliographic frameworks + [% END %] + [% WRAPPER breadcrumb_item %] + + [% IF ( frameworkcode ) %] + [% framework.frameworktext | html %] + ([% framework.frameworkcode | html %]) + [% ELSE %] + Default framework + [% END %] + + [% END %] + + [% IF ( add_form ) %] [% WRAPPER breadcrumb_item %] - Administration + [% tx("Tag {tag}", { tag = tagfield}) | html %] [% END %] + [% WRAPPER breadcrumb_item bc_active= 1 %] + Edit subfield constraints + [% END %] + [% END %] + + [% IF ( delete_confirm ) %] [% WRAPPER breadcrumb_item %] - MARC bibliographic frameworks + [% tx("Tag {tag}", { tag = tagfield}) | html %] [% END %] - [% WRAPPER breadcrumb_item %] - - [% IF ( frameworkcode ) %] - [% framework.frameworktext | html %] ([% framework.frameworkcode | html %]) - [% ELSE %] - Default framework - [% END %] - + [% WRAPPER breadcrumb_item bc_active= 1 %] + [% tx("Confirm deletion of subfield '{subfield}'?", {subfield = mss.tagsubfield }) | html %] [% END %] + [% END %] - [% IF ( add_form ) %] - [% WRAPPER breadcrumb_item %] - [% tx("Tag {tag}", { tag = tagfield}) | html %] - [% END %] - [% WRAPPER breadcrumb_item bc_active= 1 %] - Edit subfield constraints - [% END %] + [% IF ( else ) %] + [% WRAPPER breadcrumb_item bc_active= 1 %] + [% tx("Tag {tag} subfield structure", { tag = tagfield}) | html %] [% END %] + [% END %] + [% END #/ WRAPPER breadcrumbs %] +[% END #/ WRAPPER sub-header.inc %] - [% IF ( delete_confirm ) %] - [% WRAPPER breadcrumb_item %] - [% tx("Tag {tag}", { tag = tagfield}) | html %] +[% WRAPPER 'main-container.inc' aside='admin-menu' %] + + [% IF ( add_form ) %] +

              [% tx("Tag {tag} subfield constraints", { tag = tagfield}) | html %]

              +
              You can drag and drop the subfield tabs to change the order.
              + +
              + [% INCLUDE 'csrf-token.inc' %] + + + + + [% BLOCK outputsubfield %][% FILTER collapse %] + [% SWITCH ( subfieldanchor ) %] + [% CASE "@" %] + AT + [% CASE "%" %] + % + [% CASE %] + [% subfieldanchor | html %] [% END %] - [% WRAPPER breadcrumb_item bc_active= 1 %] - [% tx("Confirm deletion of subfield '{subfield}'?", {subfield = mss.tagsubfield }) | html %] - [% END %] - [% END %] + [% END %][% END %] - [% IF ( else ) %] - [% WRAPPER breadcrumb_item bc_active= 1 %] - [% tx("Tag {tag} subfield structure", { tag = tagfield}) | html %] - [% END %] - [% END %] - [% END #/ WRAPPER breadcrumbs %] - [% END #/ WRAPPER sub-header.inc %] + [% WRAPPER tabs id= "subfieldtabs" %] + [% WRAPPER tabs_nav %] + [% FOREACH loo IN loop %] + [% outputsubfield = PROCESS outputsubfield subfieldanchor = loo.subfieldcode %] + [% WRAPPER tab_item tabname= outputsubfield id= "tab_subfield_${outputsubfield}" %] + [% IF ( loo.new_subfield ) %] + New + [% ELSE %] + [% loo.subfieldcode | html %] + [% END # IF loo.new_subfield %] + [% END # WRAPPER tab_item %] + [% END # FOREACH loo %] + [% END # /WRAPPER tabs_nav %] - [% WRAPPER 'main-container.inc' aside='admin-menu' %] - - [% IF ( add_form ) %] -

              - [% tx("Tag {tag} subfield constraints", { tag = tagfield}) | html %] -

              -
              You can drag and drop the subfield tabs to change the order.
              - - - [% INCLUDE 'csrf-token.inc' %] - - - - - [% BLOCK outputsubfield %][% FILTER collapse %] - [% SWITCH ( subfieldanchor ) %] - [% CASE "@" %] - AT - [% CASE "%" %] - % - [% CASE %] - [% subfieldanchor | html %] - [% END %] - [% END %][% END %] - - [% WRAPPER tabs id= "subfieldtabs" %] - [% WRAPPER tabs_nav %] - [% FOREACH loo IN loop %] - [% outputsubfield = PROCESS outputsubfield subfieldanchor = loo.subfieldcode %] - [% WRAPPER tab_item tabname= outputsubfield id= "tab_subfield_${outputsubfield}" %] - [% IF ( loo.new_subfield ) %] - New - [% ELSE %] + [% WRAPPER tab_panels %] + [% FOREACH loo IN loop %] + [% outputsubfield = PROCESS outputsubfield subfieldanchor = loo.subfieldcode %] + [% WRAPPER tab_panel tabname=outputsubfield %] + +
              +
              + Basic constraints +
                + [% IF ( loo.subfieldcode == 0 || loo.subfieldcode ) %] +
              1. + Subfield code: [% loo.subfieldcode | html %] - [% END # IF loo.new_subfield%] - [% END # WRAPPER tab_item %] - [% END # FOREACH loo %] - [% END # /WRAPPER tabs_nav %] + +
              2. + [% ELSE %] +
              3. + + +
              4. + [% END %] +
              5. + + +
              6. +
              7. + + +
              8. +
              9. + + [% IF loo.repeatable %] + + [% ELSE %] + + [% END %] +
              10. +
              11. + + [% IF loo.mandatory %] + + [% ELSE %] + + [% END %] +
              12. +
              13. + + [% IF loo.important %] + + [% ELSE %] + + [% END %] +
              14. +
              15. + +
                Ignore means that the subfield does not display in the record editor and that its value, if any, is deleted from the record
                +
              16. +
              +
              + +
              + - [% WRAPPER tab_panels %] - [% FOREACH loo IN loop %] - [% outputsubfield = PROCESS outputsubfield subfieldanchor = loo.subfieldcode %] - [% WRAPPER tab_panel tabname=outputsubfield %] - -
              -
              - Basic constraints -
                - [% IF ( loo.subfieldcode == 0 || loo.subfieldcode ) %] -
              1. - Subfield code: - [% loo.subfieldcode | html %] - -
              2. - [% ELSE %] -
              3. - - -
              4. - [% END %] -
              5. - - -
              6. -
              7. - - -
              8. -
              9. - - [% IF loo.repeatable %] - - [% ELSE %] - - [% END %] -
              10. -
              11. - - [% IF loo.mandatory %] - - [% ELSE %] - - [% END %] -
              12. -
              13. - - [% IF loo.important %] - - [% ELSE %] - - [% END %] -
              14. -
              15. - -
                Ignore means that the subfield does not display in the record editor and that its value, if any, is deleted from the record
                -
              16. -
              -
              -
              +
              +
              + Advanced constraints +
                +
              1. + + +
              2. +
              3. + + +
              4. +
              5. + [% IF loo.hidden_protected %] + + [% ELSE %] + + [% END %] + + + + + + + + + + + +
              6. +
              7. + + [% IF loo.isurl %] + + [% ELSE %] + + [% END %] + If checked, it means that the subfield is a URL and can be clicked +
              8. +
              9. + + +
                An index name, e.g. title or Local-Number
                +
              10. +
              11. + + + [% loo.kohafield | html %] + + +
                Edit in 'Koha to MARC mapping'
                +
              12. +
              +
              + +
              + -
              -
              - Advanced constraints -
                -
              1. - - -
              2. -
              3. - - -
              4. -
              5. - [% IF loo.hidden_protected %] - - [% ELSE %] - - [% END %] - - - - - - - - - - - -
              6. -
              7. - - [% IF loo.isurl %] - - [% ELSE %] - - [% END %] - If checked, it means that the subfield is a URL and can be clicked -
              8. -
              9. - - -
                An index name, e.g. title or Local-Number
                -
              10. -
              11. - - - [% loo.kohafield | html %] - - -
                Edit in 'Koha to MARC mapping'
                -
              12. -
              -
              -
              - -
              -
              - Other options (choose one) -
                -
              1. - - -
              2. -
              3. - - -
              4. -
              5. - - -
              6. -
              -
              -
              - [% END # /WRAPPER tab_panel %] - [% END # /FOREACH loo %] - [% END # /WRAPPER tab_panels %] - [% END # /WRAPPER tabs %] - -
              - Cancel -
              -
              - [% END # /IF ( add_form ) %] - - [% IF ( delete_confirm ) %] -
              -

              [% tx("Confirm deletion of subfield '{subfield}'?", {subfield = mss.tagsubfield }) | html %]

              -

              Subfield: [% mss.tagsubfield | html %]

              -

              Description: [% mss.liblibrarian | html_entity %]

              - -
              - [% INCLUDE 'csrf-token.inc' %] - - - - -
              - - -
              - - - -
              -
              - [% END # /IF ( delete_confirm ) %] - - [% IF ( else ) %] - [% IF ( frameworkcode ) %] -

              [% tx("Tag {tag} subfield structure (framework {frameworkcode})", { tag = tagfield, frameworkcode = frameworkcode }) | html %]

              - [% ELSE %] -

              [% tx("Tag {tag} subfield structure (default framework)", { tag = tagfield}) | html %]

              - [% END %] - -

              This screen shows the subfields associated with the selected tag. You can edit subfields or add a new one by clicking on edit.

              -

              The column 'Koha field' shows that the subfield is linked with a Koha field.

              - -
              - - - - - - - - - - - [% FOREACH loo IN loop %] - - - - - - - [% END %] - -
              SubfieldTextConstraintsActions
              [% loo.tagsubfield | html %] - [% IF loo.tab == -1 %] - [% loo.liblibrarian | html_entity %] - [% ELSE %] - [% loo.liblibrarian | html_entity %] +
              +
              + Other options (choose one) +
                +
              1. + +
              - [% IF loo.tab == -1 %] - subfield ignored - [% ELSE %] - Tab:[% loo.tab | html %], - [% IF ( loo.kohafield ) %] | Koha field: [% loo.kohafield | html %], [% END %] - [% IF ( loo.repeatable ) %]Repeatable, [% ELSE %]Not repeatable,[% END %] - [% IF ( loo.mandatory ) %]Mandatory, [% ELSE %]Not mandatory,[% END %] - [% IF ( loo.important ) %]Important, [% ELSE %]Not important,[% END %] - [% IF ( loo.seealso ) %] | See also: [% loo.seealso | html %],[% END %] - [% IF ( loo.hidden ) %]hidden,[% END %] - [% IF ( loo.isurl ) %]is a URL,[% END %] - [% IF ( loo.authorised_value ) %] | Auth value:[% loo.authorised_value | html %],[% END %] - [% IF ( loo.authtypecode ) %] | Authority:[% loo.authtypecode | html %],[% END %] - [% IF ( loo.value_builder ) %] | Plugin:[% loo.value_builder | html %],[% END %] - [% IF ( loo.link ) %] | Link:[% loo.link | html %],[% END %] + + +
            1. + +
            2. - Edit - Delete -
              -
              + + +
            3. + + +
            4. + +
              + + + + [% END # /WRAPPER tab_panel %] + [% END # /FOREACH loo %] + [% END # /WRAPPER tab_panels %] + [% END # /WRAPPER tabs %] -
              -
              - - - - Cancel -
              -
              +
              + + Cancel +
              + + [% END # /IF ( add_form ) %] - [% END # /IF else %] + [% IF ( delete_confirm ) %] +
              +

              [% tx("Confirm deletion of subfield '{subfield}'?", {subfield = mss.tagsubfield }) | html %]

              +

              Subfield: [% mss.tagsubfield | html %]

              +

              Description: [% mss.liblibrarian | html_entity %]

              - [% END %] +
              + [% INCLUDE 'csrf-token.inc' %] + + + + +
              - [% MACRO jsinclude BLOCK %] - [% INCLUDE 'datatables.inc' %] - [% Asset.js( "lib/sortable/Sortable.min.js" ) | $raw %] - [% Asset.js("js/admin-menu.js") | $raw %] - - [% Asset.js("js/marc_subfields_structure.js") | $raw %] - [% END %] +
              + + + +
              +
              + + [% END # /IF ( delete_confirm ) %] - [% INCLUDE 'intranet-bottom.inc' %] + [% IF ( else ) %] + [% IF ( frameworkcode ) %] +

              [% tx("Tag {tag} subfield structure (framework {frameworkcode})", { tag = tagfield, frameworkcode = frameworkcode }) | html %]

              + [% ELSE %] +

              [% tx("Tag {tag} subfield structure (default framework)", { tag = tagfield}) | html %]

              + [% END %] + +

              This screen shows the subfields associated with the selected tag. You can edit subfields or add a new one by clicking on edit.

              +

              The column 'Koha field' shows that the subfield is linked with a Koha field.

              + +
              + + + + + + + + + + + [% FOREACH loo IN loop %] + + + + + + + [% END %] + +
              SubfieldTextConstraintsActions
              [% loo.tagsubfield | html %] + [% IF loo.tab == -1 %] + [% loo.liblibrarian | html_entity %] + [% ELSE %] + [% loo.liblibrarian | html_entity %] + [% END %] + + [% IF loo.tab == -1 %] + subfield ignored + [% ELSE %] + Tab:[% loo.tab | html %], [% IF ( loo.kohafield ) %]| Koha field: [% loo.kohafield | html %],[% END %] + [% IF ( loo.repeatable ) %]Repeatable,[% ELSE %]Not repeatable,[% END %] + [% IF ( loo.mandatory ) %]Mandatory,[% ELSE %]Not mandatory,[% END %] + [% IF ( loo.important ) %]Important,[% ELSE %]Not important,[% END %] + [% IF ( loo.seealso ) %]| See also: [% loo.seealso | html %],[% END %] + [% IF ( loo.hidden ) %]hidden,[% END %] + [% IF ( loo.isurl ) %]is a URL,[% END %] + [% IF ( loo.authorised_value ) %]| Auth value:[% loo.authorised_value | html %],[% END %] + [% IF ( loo.authtypecode ) %]| Authority:[% loo.authtypecode | html %],[% END %] + [% IF ( loo.value_builder ) %]| Plugin:[% loo.value_builder | html %],[% END %] + [% IF ( loo.link ) %]| Link:[% loo.link | html %],[% END %] + [% END %] + + Edit + Delete +
              +
              + +
              +
              + + + + Cancel +
              +
              + [% END # /IF else %] +[% END %] + +[% MACRO jsinclude BLOCK %] + [% INCLUDE 'datatables.inc' %] + [% Asset.js( "lib/sortable/Sortable.min.js" ) | $raw %] + [% Asset.js("js/admin-menu.js") | $raw %] + + [% Asset.js("js/marc_subfields_structure.js") | $raw %] +[% END %] + +[% INCLUDE 'intranet-bottom.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/marctagstructure.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/marctagstructure.tt index a65318d6e1..fc1f3e8505 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/marctagstructure.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/marctagstructure.tt @@ -5,26 +5,31 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% IF ( add_form ) %] - [% IF heading_add_tag_p %] - [% tx("New tag {searchfield}", { searchfield = searchfield }) | html %] +<title + >[% FILTER collapse %] + [% IF ( add_form ) %] + [% IF heading_add_tag_p %] + [% tx("New tag {searchfield}", { searchfield = searchfield }) | html %] + [% ELSE %] + [% tx("Modify tag {searchfield}", { searchfield = searchfield }) | html %] + [% END %] + › + [% END %] + [% IF ( delete_confirm ) %] + [% tx("Confirm deletion of tag {searchfield}", { searchfield = searchfield }) | html %] + › + [% END %] + [% IF framework %] + [% framework.frameworktext | html %] + ([% framework.frameworkcode | html %]) › [% ELSE %] - [% tx("Modify tag {searchfield}", { searchfield = searchfield }) | html %] - [% END %] › - [% END %] - [% IF ( delete_confirm ) %] - [% tx("Confirm deletion of tag {searchfield}", { searchfield = searchfield }) | html %] › - [% END %] - [% IF framework %] - [% framework.frameworktext | html %] ([% framework.frameworkcode | html %]) › - [% ELSE %] - [% t("Default framework") | html %] › - [% END %] - [% t("MARC bibliographic frameworks") | html %] › - [% t("Administration") | html %] › - [% t("Koha") | html %] -[% END %] + [% t("Default framework") | html %] + › + [% END %] + [% t("MARC bibliographic frameworks") | html %] + › [% t("Administration") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -49,26 +54,24 @@ [% framework.frameworktext | html %] ([% framework.frameworkcode | html %]) [% ELSE %] Default MARC bibliographic framework - [% END%] + [% END %] [% END %] - [% WRAPPER breadcrumb_item bc_active= 1%] + [% WRAPPER breadcrumb_item bc_active= 1 %] [% IF heading_add_tag_p %] [% tx("New tag {searchfield}", { searchfield = searchfield }) | html %] [% ELSE %] [% tx("Modify tag {searchfield}", { searchfield = searchfield }) | html %] [% END %] [% END %] - [% ELSIF ( else ) %] - [% WRAPPER breadcrumb_item bc_active= 1%] + [% WRAPPER breadcrumb_item bc_active= 1 %] [% IF framework %] [% framework.frameworktext | html %] ([% framework.frameworkcode | html %]) [% ELSE %] Default framework [% END %] [% END %] - [% ELSIF ( delete_confirm ) %] [% WRAPPER breadcrumb_item %] @@ -79,7 +82,7 @@ [% END %] [% END %] - [% WRAPPER breadcrumb_item bc_active= 1%] + [% WRAPPER breadcrumb_item bc_active= 1 %] [% tx("Confirm deletion of tag {searchfield}", { searchfield = searchfield }) | html %] [% END %] [% END %] @@ -88,226 +91,249 @@ [% WRAPPER 'main-container.inc' aside='admin-menu' %] -[% IF ( else ) %] -[% END %] + [% IF ( else ) %] + + [% END %] -[% IF framework %] -

              - [% tx("MARC bibliographic framework '{framework}' ({frameworkcode})", { framework = framework.frameworktext, frameworkcode = framework.frameworkcode }) | html %] -

              -[% ELSE %] -

              Default MARC bibliographic framework

              -[% END %] + [% IF framework %] +

              [% tx("MARC bibliographic framework '{framework}' ({frameworkcode})", { framework = framework.frameworktext, frameworkcode = framework.frameworkcode }) | html %]

              + [% ELSE %] +

              Default MARC bibliographic framework

              + [% END %] -[% IF ( add_form ) %] + [% IF ( add_form ) %] +
              + [% INCLUDE 'csrf-token.inc' %] - - [% INCLUDE 'csrf-token.inc' %] +
              + + [% IF heading_add_tag_p %] + New tag + [% ELSE %] + [% tx("Modify tag {searchfield}", { searchfield = searchfield }) | html %] + + [% END %] + + + +
                +
              1. + [% IF ( heading_modify_tag_p ) %] + + Tag: + [% searchfield | html %] + [% ELSE %] + + + Required + [% END %] +
              2. +
              3. +
              4. +
              5. + [% IF ( repeatable ) %] + + [% ELSE %] + + [% END %] +
              6. +
              7. + [% IF ( mandatory ) %] + + [% ELSE %] + + [% END %] +
              8. +
              9. + [% IF ( important ) %] + + [% ELSE %] + + [% END %] +
              10. +
              11. + +
              12. +
              13. + +
              14. +
              15. + + (if you select a value here, the indicators will be limited to the authorized value list)
              16. +
              +
              + + Cancel +
              +
              + [% END %] -
              - - [% IF heading_add_tag_p %] - New tag - [% ELSE %] - [% tx("Modify tag {searchfield}", { searchfield = searchfield }) | html %] - - [% END %] - - - -
                -
              1. - [% IF ( heading_modify_tag_p ) %] - - Tag: - [% searchfield | html %] - [% ELSE %] - - - Required - [% END %] -
              2. -
              3. -
              4. -
              5. - [% IF ( repeatable ) %] - - [% ELSE %] - - [% END %] -
              6. -
              7. - [% IF ( mandatory ) %] - - [% ELSE %] - - [% END %] -
              8. -
              9. - [% IF ( important ) %] - - [% ELSE %] - - [% END %] -
              10. -
              11. - -
              12. -
              13. - -
              14. -
              15. - - (if you select a value here, the indicators will be limited to the authorized value list)
              16. -
              -
              - - Cancel -
              - -[% END %] + [% IF ( delete_confirm ) %] +
              +

              [% tx("Confirm deletion of tag {searchfield}?", { searchfield = searchfield }) | html %]

              +

              Tag: [% searchfield | html %]

              +

              Description: [% liblibrarian | html %]

              +
              + [% INCLUDE 'csrf-token.inc' %] + + + + +
              +
              + +
              +
              + [% END %] - -[% IF ( delete_confirm ) %] -
              -

              [% tx("Confirm deletion of tag {searchfield}?", { searchfield = searchfield }) | html %]

              -

              Tag: [% searchfield | html %]

              -

              Description: [% liblibrarian | html %]

              + [% IF ( framework_create ) %]
              [% INCLUDE 'csrf-token.inc' %] - - + - -
              -
              - -
              -
              -[% END %] - -[% IF ( framework_create ) %] - -
              - [% INCLUDE 'csrf-token.inc' %] - - - Create framework for [% framework.frameworkcode | html %] ([% framework.frameworktext | html %]) using - - -
              -[% END %] - - -[% IF ( else ) %] -
              -
              - - - - - + + [% FOREACH fw IN existing_frameworks %] + [% END %] - [% END %] - - -

              - [% IF ( select_display ) %] - - [% ELSE %] - - [% END %]

              -
              -
              - -
              - - - - - - - - - - - - - - - - [% FOREACH loo IN loop %] - - - - - - - - - - - + + + [% END %] - -
              TagTag descriptionRepeatableMandatoryImportantAuth valueIndicator 1Indicator 2 
              [% loo.tagfield | html %] - [% loo.liblibrarian | html %] - [% IF ( select_display ) %] - [% FOREACH subfield IN loo.subfields %] -

              - Tab:[% subfield.tab | html %] | $[% subfield.tagsubfield | html %] - [% subfield.liblibrarian | html %] [% IF ( subfield.kohafield ) %][% subfield.kohafield | html %][% END %][% IF ( subfield.repeatable ) %], repeatable[% END %][% IF ( subfield.mandatory ) %], Mandatory[% END %][% IF ( subfield.seealso ) %], See [% subfield.seealso | html %][% END %][% IF ( subfield.authorised_value ) %], [% subfield.authorised_value | html %][% END %][% IF ( subfield.authtypecode ) %], [% subfield.authtypecode | html %][% END %][% IF ( subfield.value_builder ) %], [% subfield.value_builder | html %][% END %] -

              - [% END %] - [% END %] -
              [% IF ( loo.repeatable ) %]Yes[% ELSE %]No[% END %][% IF ( loo.mandatory ) %]Yes[% ELSE %]No[% END %][% IF ( loo.important ) %]Yes[% ELSE %]No[% END %][% loo.authorised_value | html %][% loo.ind1_defaultvalue | html %][% loo.ind2_defaultvalue | html %] - -
              -
              -[% END %] + [% IF ( else ) %] +
              +
              + + + + + + +

              + [% IF ( select_display ) %] + + [% ELSE %] + + [% END %]

              +
              +
              + +
              + + + + + + + + + + + + + + + + [% FOREACH loo IN loop %] + + + + + + + + + + + + [% END %] + +
              TagTag descriptionRepeatableMandatoryImportantAuth valueIndicator 1Indicator 2 
              [% loo.tagfield | html %] + [% loo.liblibrarian | html %] + [% IF ( select_display ) %] + [% FOREACH subfield IN loo.subfields %] +

              + Tab:[% subfield.tab | html %] | $[% subfield.tagsubfield | html %] + [% subfield.liblibrarian | html %] + [% IF ( subfield.kohafield ) %][% subfield.kohafield | html %][% END %][% IF ( subfield.repeatable ) %], repeatable[% END %][% IF ( subfield.mandatory ) %] + , Mandatory + [% END %][% IF ( subfield.seealso ) %], See [% subfield.seealso | html %][% END %][% IF ( subfield.authorised_value ) %], [% subfield.authorised_value | html %][% END %][% IF ( subfield.authtypecode ) %] + , [% subfield.authtypecode | html %] + [% END %][% IF ( subfield.value_builder ) %], [% subfield.value_builder | html %][% END %] +

              + [% END %] + [% END %] +
              [% IF ( loo.repeatable ) %]Yes[% ELSE %]No[% END %][% IF ( loo.mandatory ) %]Yes[% ELSE %]No[% END %][% IF ( loo.important ) %]Yes[% ELSE %]No[% END %][% loo.authorised_value | html %][% loo.ind1_defaultvalue | html %][% loo.ind2_defaultvalue | html %] + +
              +
              + + [% END %] [% END %] [% MACRO jsinclude BLOCK %] [% INCLUDE 'datatables.inc' %] [% Asset.js("js/admin-menu.js") | $raw %] [% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/oai_sets.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/oai_sets.tt index 558fde1309..40de112318 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/oai_sets.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/oai_sets.tt @@ -4,16 +4,19 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% IF ( op_new ) %] - [% t("New OAI set") | html %] › - [% ELSIF ( op_mod ) %] - [% tx("Modify OAI set '{oai_set}'", { oai_set = spec }) | html %] › - [% END %] - [% t("OAI sets") | html %] › - [% t("Administration") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% IF ( op_new ) %] + [% t("New OAI set") | html %] + › + [% ELSIF ( op_mod ) %] + [% tx("Modify OAI set '{oai_set}'", { oai_set = spec }) | html %] + › + [% END %] + [% t("OAI sets") | html %] + › [% t("Administration") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -38,12 +41,10 @@ [% WRAPPER breadcrumb_item bc_active= 1 %] New OAI set [% END %] - [% ELSIF ( op_mod ) %] [% WRAPPER breadcrumb_item bc_active= 1 %] [% tx("Modify OAI set '{oai_set}'", { oai_set = spec }) | html %] [% END %] - [% ELSE %] [% WRAPPER breadcrumb_item bc_active= 1 %] OAI sets @@ -54,50 +55,48 @@ [% WRAPPER 'main-container.inc' aside='admin-menu' %] - [% IF ( op_new || op_mod ) %] -
              - [% INCLUDE 'csrf-token.inc' %] + [% IF ( op_new || op_mod ) %] + + [% INCLUDE 'csrf-token.inc' %] [% IF ( op_new ) %]

              New OAI set

              [% ELSIF ( op_mod ) %]

              [% tx("Modify OAI set '{oai_set}'", { oai_set = spec }) | html %]

              - - + + [% END %] -
              -
                -
              1. - - [% IF ( spec == "" ) %] - - [% ELSE %] - - [% END %] - Required -
              2. -
              3. - - - Required -
              4. - [% FOREACH desc IN descriptions %] -
              5. - - - Remove -
              6. +
                +
                  +
                1. + + [% IF ( spec == "" ) %] + + [% ELSE %] + [% END %] -
                2.   Add description
                3. - -
                -
                -
                - Cancel -
                - - [% ELSE %] - + Required + +
              7. + + + Required +
              8. + [% FOREACH desc IN descriptions %] +
              9. + + + Remove +
              10. + [% END %] +
              11.   Add description
              12. +
              +
              +
              Cancel
              + + [% ELSE %] @@ -131,15 +130,20 @@ [% END %] - + [% END %] @@ -150,12 +154,12 @@ - + + [% ELSE %]

              There are no sets defined.

              [% END %] - [% END %] - + [% END %] [% END %] [% MACRO jsinclude BLOCK %] @@ -163,38 +167,41 @@ [% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/overdrive.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/overdrive.tt index 0e44ac19c8..16c3148e5a 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/overdrive.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/overdrive.tt @@ -6,11 +6,12 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("OverDrive library authnames") | html %] › - [% t("Administration") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("OverDrive library authnames") | html %] + › [% t("Administration") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -32,53 +33,51 @@ [% END #/ WRAPPER sub-header.inc %] [% WRAPPER 'main-container.inc' aside='admin-menu' %] +

              OverDrive library authnames

              -

              OverDrive library authnames

              - -
              - [% INCLUDE 'csrf-token.inc' %] - -
              - - - - - - - - - [% FOREACH b IN branches %] - - - - - [% END %] - -
              LibraryAuthname
              - [% Branches.GetName( b.branchcode ) | html %] - - - -
              -
              -
              - -
              -
              - +
              + [% INCLUDE 'csrf-token.inc' %] + +
              + + + + + + + + + [% FOREACH b IN branches %] + + + + + [% END %] + +
              LibraryAuthname
              + [% Branches.GetName( b.branchcode ) | html %] + + + +
              +
              +
              + +
              +
              [% END %] [% MACRO jsinclude BLOCK %] [% Asset.js("js/admin-menu.js") | $raw %] [% INCLUDE 'datatables.inc' %] [% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/patron-attr-types.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/patron-attr-types.tt index b44cf12ac4..2b916c2691 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/patron-attr-types.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/patron-attr-types.tt @@ -7,21 +7,25 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% IF ( attribute_type_form ) %] - [% IF ( edit_attribute_type ) %] - [% tx("Modify patron attribute type '{code}'", { code = attribute_type.code }) | html %] › - [% ELSE %] - [% t("New patron attribute type") | html %] › +<title + >[% FILTER collapse %] + [% IF ( attribute_type_form ) %] + [% IF ( edit_attribute_type ) %] + [% tx("Modify patron attribute type '{code}'", { code = attribute_type.code }) | html %] + › + [% ELSE %] + [% t("New patron attribute type") | html %] + › + [% END %] [% END %] - [% END %] - [% IF ( delete_attribute_type_form ) %] - [% tx("Confirm deletion of patron attribute type '{code}'", { code = code }) | html %] › - [% END %] - [% t("Patron attribute types") | html %] › - [% t("Administration") | html %] › - [% t("Koha") | html %] -[% END %] + [% IF ( delete_attribute_type_form ) %] + [% tx("Confirm deletion of patron attribute type '{code}'", { code = code }) | html %] + › + [% END %] + [% t("Patron attribute types") | html %] + › [% t("Administration") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -50,12 +54,10 @@ New patron attribute type [% END %] [% END %] - [% ELSIF ( delete_attribute_type_form ) %] [% WRAPPER breadcrumb_item bc_active= 1 %] [% tx("Confirm deletion of patron attribute type '{code}'", { code = code }) | html %] [% END %] - [% ELSE %] [% WRAPPER breadcrumb_item bc_active= 1 %] Patron attribute types @@ -66,380 +68,389 @@ [% WRAPPER 'main-container.inc' aside='admin-menu' %] -[% IF ( WARNING_extended_attributes_off ) %] -
              Because the 'ExtendedPatronAttributes` system preference is currently not enabled, extended patron attributes cannot be given to patron records.
              Go to the ExtendedPatronAttributes system preference if you wish to enable this feature.
              -[% END %] + [% IF ( WARNING_extended_attributes_off ) %] +
              Because the 'ExtendedPatronAttributes` system preference is currently not enabled, extended patron attributes cannot be given to patron records.
              Go to the + ExtendedPatronAttributes system preference if you wish to enable this feature.
              + [% END %] -[% IF ( attribute_type_form ) %] - [% IF ( edit_attribute_type ) %] -

              [% tx("Modify patron attribute type '{code}'", { code = attribute_type.code }) | html %]

              - [% ELSE %] -

              New patron attribute type

              - [% END %] -[% IF ( duplicate_code_error ) %] -
              Could not add patron attribute type "[% duplicate_code_error | html %]" - — one with that code already exists. -
              -[% END %] -
              - [% INCLUDE 'csrf-token.inc' %] - -
              -
                -
              1. - [% IF attribute_type %] - Patron attribute type code: - - [% attribute_type.code |html %] - [% ELSE %] - - - Required - [% END %] -
              2. -
              3. - - Required -
              4. - -
              5. - - [% IF attribute_type %] - [% IF attribute_type.repeatable AND NOT can_be_set_to_nonrepeatable %] - - - [% ELSIF attribute_type.repeatable %] - - [% ELSE %] - - [% END %] - [% ELSE %] - - [% END %] - Check to let a patron record have multiple values of this attribute. -
              6. - -
              7. - - [% IF attribute_type %] - [% IF attribute_type.unique_id %] - - [% ELSIF can_be_set_to_unique %] - - [% ELSE %] - - - [% END %] - [% ELSE %] - - [% END %] - If checked, attribute will be a unique identifier. If a value is given to a patron record, the same value - cannot be given to a different record. -
              8. -
              9. - [% IF attribute_type AND attribute_type.is_date %] - - [% ELSE %] - - [% END %] - If checked, the attribute will be a date. Date attributes can be repeatable, but cannot be linked to an authorized value category. -
              10. -
              11. - [% IF attribute_type AND attribute_type.opac_display %] - - [% ELSE %] - - [% END %] - Check to display this attribute on a patron's details page in the OPAC. -
              12. -
              13. - [% IF attribute_type AND attribute_type.opac_editable %] - - [% ELSE %] - - [% END %] - Check to allow patrons to edit this attribute from their details page in the OPAC. (Requires above) -
              14. -
              15. - [% IF attribute_type AND attribute_type.staff_searchable %] - - [% ELSE %] - - [% END %] - - Check to make this attribute searchable in staff patron searches. If - checked, this attribute will appear in patron search dropdowns. - -
              16. -
              17. - [% IF attribute_type AND attribute_type.searched_by_default %] - - [% ELSE %] - - [% END %] - - If checked, this field will be included in 'Standard' patron searches. Requires - field to be marked as searchable above - -
              18. -
              19. - [% IF attribute_type AND attribute_type.mandatory %] - - [% ELSE %] - - [% END %] - Check to make this attribute mandatory when creating or editing a patron. -
              20. -
              21. - [% IF attribute_type AND attribute_type.display_checkout %] - - [% ELSE %] - - [% END %] - Check to show this attribute in the brief information panel in the patron's record (staff interface). -
              22. - - [% IF Koha.Preference('Pseudonymization') %] -
              23. - - [% IF attribute_type AND attribute_type.keep_for_pseudonymization %] - - [% ELSE %] - - [% END %] - Check to make this attribute copied to the patron's pseudonymized attributes. -
              24. + [% IF ( attribute_type_form ) %] + [% IF ( edit_attribute_type ) %] +

                [% tx("Modify patron attribute type '{code}'", { code = attribute_type.code }) | html %]

                + [% ELSE %] +

                New patron attribute type

                [% END %] - -
              25. - -
                If one is selected, the patron record input page will only allow values to be chosen from the authorized value list. However, an authorized value list is not enforced during batch patron import.
                -
              26. -
              27. - -
                Select "All libraries" if this attribute type should always be displayed. Otherwise select libraries you want to associate with this value. -
                -
              28. -
              29. - - -
                Choose one to limit this attribute to one patron type. Please leave blank if you want these attributes to be available for all types of patrons.
                -
              30. -
              31. - - [% PROCESS 'av-build-dropbox.inc' name="class", category="PA_CLASS" default=attribute_type.class empty=1 %] -
                - [% IF ( CAN_user_parameters_manage_auth_values ) %] - Group attributes types with a block title (based on authorized values category 'PA_CLASS') - [% ELSE %] - Group attributes types with a block title (based on authorized values category 'PA_CLASS') - [% END %] -
                -
              32. -
              -
              -
              - - Cancel -
              -
              -[% END %] - -[% IF ( delete_attribute_type_form ) %] -
              -

              - [% tx("Confirm deletion of patron attribute type '{code}' ({description})?", { code = code, description = description }) | html %] -

              -
              + [% IF ( duplicate_code_error ) %] +
              Could not add patron attribute type "[% duplicate_code_error | html %]" — one with that code already exists.
              + [% END %] + [% INCLUDE 'csrf-token.inc' %] - - -
              -
              - -
              -
              -[% END %] - -[% IF ( display_list ) %] - - - -

              Patron attribute types

              -[% IF ( added_attribute_type ) %] -
              Added patron attribute type "[% added_attribute_type | html %]"
              -[% END %] -[% IF ( edited_attribute_type ) %] -
              Modified patron attribute type "[% edited_attribute_type | html %]"
              -[% END %] -[% IF ( deleted_attribute_type ) %] -
              Deleted patron attribute type "[% deleted_attribute_type | html %]"
              -[% END %] -[% IF ( ERROR_delete_in_use ) %] -
              Could not delete patron attribute type "[% ERROR_delete_in_use | html %]" - — it is in use by [% ERROR_num_patrons | html %] patron records
              -[% END %] -[% IF ( ERROR_delete_not_found ) %] -
              Could not delete patron attribute type "[% ERROR_delete_not_found | html %]" - — it was already absent from the database.
              -[% END %] -[% IF ( available_attribute_types ) %] - [% FOREACH attribute IN available_attribute_types %] -
              - [% IF attribute.class %] -

              [% attribute.lib | html %]

              - [% ELSE %] -

              Unclassified types

              - [% END %] - - - - - - - - - - - - - - [% FOREACH item IN attribute.items %] - - - - - - - - - + +
            5. + +
              If one is selected, the patron record input page will only allow values to be chosen from the authorized value list. However, an authorized value list is not enforced during batch patron import.
              +
            6. +
            7. + +
              Select "All libraries" if this attribute type should always be displayed. Otherwise select libraries you want to associate with this value.
              +
            8. +
            9. + + +
              Choose one to limit this attribute to one patron type. Please leave blank if you want these attributes to be available for all types of patrons.
              +
            10. +
            11. + + [% PROCESS 'av-build-dropbox.inc' name="class", category="PA_CLASS" default=attribute_type.class empty=1 %] +
              + [% IF ( CAN_user_parameters_manage_auth_values ) %] + Group attributes types with a block title (based on authorized values category 'PA_CLASS') + [% ELSE %] + Group attributes types with a block title (based on authorized values category 'PA_CLASS') + [% END %] +
              +
            12. + + +
              + + Cancel +
              + + [% END %] + + [% IF ( delete_attribute_type_form ) %] +
              +

              [% tx("Confirm deletion of patron attribute type '{code}' ({description})?", { code = code, description = description }) | html %]

              +
              + [% INCLUDE 'csrf-token.inc' %] + + + + +
              + + +
              + [% END %] + + [% IF ( display_list ) %] + + +

              Patron attribute types

              + [% IF ( added_attribute_type ) %] +
              Added patron attribute type "[% added_attribute_type | html %]"
              + [% END %] + [% IF ( edited_attribute_type ) %] +
              Modified patron attribute type "[% edited_attribute_type | html %]"
              + [% END %] + [% IF ( deleted_attribute_type ) %] +
              Deleted patron attribute type "[% deleted_attribute_type | html %]"
              + [% END %] + [% IF ( ERROR_delete_in_use ) %] +
              Could not delete patron attribute type "[% ERROR_delete_in_use | html %]" — it is in use by [% ERROR_num_patrons | html %] patron records
              + [% END %] + [% IF ( ERROR_delete_not_found ) %] +
              Could not delete patron attribute type "[% ERROR_delete_not_found | html %]" — it was already absent from the database.
              + [% END %] + [% IF ( available_attribute_types ) %] + [% FOREACH attribute IN available_attribute_types %] +
              + [% IF attribute.class %] +

              [% attribute.lib | html %]

              + [% ELSE %] +

              Unclassified types

              + [% END %] +
              CodeDescriptionLibrary limitationAuthorized value categoryMandatorySearchingActions
              [% item.code | html %][% item.description | html %] - [% SET libraries = item.library_limits %] - [% IF ( libraries && libraries.count > 0 ) %] - [% branches_str = "" %] - [% FOREACH branch IN libraries %] - [% branches_str = branches_str _ " " _ branch.branchname _ "(" _ branch.branchcode _ ")" %] - [% END %] - - [% IF libraries.count > 1 %] - [% libraries.count | html %] library limitations - [% ELSE %] - [% libraries.count | html %] library limitation - [% END %] - - [% ELSE %] - No limitation - [% END %] - - [% IF ( CAN_user_parameters_manage_auth_values ) %] - [% item.authorised_value_category | html %] - [% ELSE %] - [% item.authorised_value_category | html %] - [% END %] - - [% IF ( item.mandatory ) -%] - Yes - [% ELSE -%] - No - [% END %] - - [% IF ( item.staff_searchable ) %] - [% IF( item.searched_by_default ) %] - Searched by default +
              +
                +
              1. + [% IF attribute_type %] + Patron attribute type code: + + [% attribute_type.code |html %] [% ELSE %] - Searchable + + + Required [% END %] - [% ELSE %] - Not searchable +
              2. +
              3. + + Required +
              4. + +
              5. + + [% IF attribute_type %] + [% IF attribute_type.repeatable AND NOT can_be_set_to_nonrepeatable %] + + + [% ELSIF attribute_type.repeatable %] + + [% ELSE %] + + [% END %] + [% ELSE %] + + [% END %] + Check to let a patron record have multiple values of this attribute. +
              6. + +
              7. + + [% IF attribute_type %] + [% IF attribute_type.unique_id %] + + [% ELSIF can_be_set_to_unique %] + + [% ELSE %] + + + [% END %] + [% ELSE %] + + [% END %] + If checked, attribute will be a unique identifier. If a value is given to a patron record, the same value cannot be given to a different record. +
              8. +
              9. + [% IF attribute_type AND attribute_type.is_date %] + + [% ELSE %] + + [% END %] + If checked, the attribute will be a date. Date attributes can be repeatable, but cannot be linked to an authorized value category. +
              10. +
              11. + [% IF attribute_type AND attribute_type.opac_display %] + + [% ELSE %] + + [% END %] + Check to display this attribute on a patron's details page in the OPAC. +
              12. +
              13. + [% IF attribute_type AND attribute_type.opac_editable %] + + [% ELSE %] + + [% END %] + Check to allow patrons to edit this attribute from their details page in the OPAC. (Requires above) +
              14. +
              15. + [% IF attribute_type AND attribute_type.staff_searchable %] + + [% ELSE %] + + [% END %] + Check to make this attribute searchable in staff patron searches. If checked, this attribute will appear in patron search dropdowns. +
              16. +
              17. + [% IF attribute_type AND attribute_type.searched_by_default %] + + [% ELSE %] + + [% END %] + If checked, this field will be included in 'Standard' patron searches. Requires field to be marked as searchable above +
              18. +
              19. + [% IF attribute_type AND attribute_type.mandatory %] + + [% ELSE %] + + [% END %] + Check to make this attribute mandatory when creating or editing a patron. +
              20. +
              21. + [% IF attribute_type AND attribute_type.display_checkout %] + + [% ELSE %] + + [% END %] + Check to show this attribute in the brief information panel in the patron's record (staff interface). +
              22. + + [% IF Koha.Preference('Pseudonymization') %] +
              23. + + [% IF attribute_type AND attribute_type.keep_for_pseudonymization %] + + [% ELSE %] + + [% END %] + Check to make this attribute copied to the patron's pseudonymized attributes. +
              24. [% END %] -
              - Edit - Delete -
              + + + + + + + + + + + + + [% FOREACH item IN attribute.items %] + + + + + + + + + + [% END %] + +
              CodeDescriptionLibrary limitationAuthorized value categoryMandatorySearchingActions
              [% item.code | html %][% item.description | html %] + [% SET libraries = item.library_limits %] + [% IF ( libraries && libraries.count > 0 ) %] + [% branches_str = "" %] + [% FOREACH branch IN libraries %] + [% branches_str = branches_str _ " " _ branch.branchname _ "(" _ branch.branchcode _ ")" %] + [% END %] + + [% IF libraries.count > 1 %] + [% libraries.count | html %] library limitations + [% ELSE %] + [% libraries.count | html %] library limitation + [% END %] + + [% ELSE %] + No limitation + [% END %] + + [% IF ( CAN_user_parameters_manage_auth_values ) %] + [% item.authorised_value_category | html %] + [% ELSE %] + [% item.authorised_value_category | html %] + [% END %] + + [% IF ( item.mandatory ) -%] + Yes + [% ELSE -%] + No + [% END %] + + [% IF ( item.staff_searchable ) %] + [% IF( item.searched_by_default ) %] + Searched by default + [% ELSE %] + Searchable + [% END %] + [% ELSE %] + Not searchable + [% END %] + + Edit + Delete +
              [% END %] - - - - [% END %] -[% ELSE %] -

              There are no saved patron attribute types.

              -[% END %] - -
              [% pagination_bar | $raw %]
              - -[% END %] + [% ELSE %] +

              There are no saved patron attribute types.

              + [% END %] +
              [% pagination_bar | $raw %]
              + [% END %] [% END %] [% MACRO jsinclude BLOCK %] [% Asset.js("js/admin-menu.js") | $raw %] [% INCLUDE 'datatables.inc' %] [% INCLUDE 'columns_settings.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/preferences.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/preferences.tt index 113e4174e1..94a49d2a12 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/preferences.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/preferences.tt @@ -6,11 +6,12 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("System preferences") | html %] › - [% t("Administration") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("System preferences") | html %] + › [% t("Administration") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] [% Asset.css("lib/jquery/plugins/multiple-select/multiple-select.min.css") | $raw %] [% Asset.css("css/preferences.css") | $raw %] @@ -37,24 +38,20 @@ [% WRAPPER 'main-container.inc' aside='prefs-menu' %] [% IF ( jump_not_found ) %] -
              - Could not find a system preference named [% jumpfield | html %]. -
              +
              Could not find a system preference named [% jumpfield | html %].
              [% END %] [% IF ( search_not_found ) %] -
              - No system preferences matched your search for: [% searchfield | html %] -
              -

              System preferences

              +
              No system preferences matched your search for: [% searchfield | html %]
              +

              System preferences

              [% ELSIF searchfield %] -

              System preferences matching: [% searchfield | html %]

              +

              System preferences matching: [% searchfield | html %]

              [% ELSE %] -

              System preferences

              +

              System preferences

              [% END %] [% FOREACH TAB IN TABS %] -
              -

              [% TAB.tab_title | html %] preferences

              - +
              +

              [% TAB.tab_title | html %] preferences

              +
              [% INCLUDE 'csrf-token.inc' %] [% UNLESS ( searchfield ) %]
              [% END %] @@ -236,9 +233,8 @@
              Cancel
              -
              +
              [% END %] - [% END %] @@ -283,7 +279,6 @@ [% Asset.js( "lib/codemirror/css-lint.min.js" ) | $raw %] [% Asset.js( "lib/codemirror/yaml-lint.min.js" ) | $raw %] [% Asset.js( "lib/sortable/Sortable.min.js" ) | $raw %] - [% Asset.js("lib/jquery/plugins/humanmsg.js") | $raw %] [% Asset.js("js/ajax.js") | $raw %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/record_sources.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/record_sources.tt index 8b1b0f206a..21a1cc3dfc 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/record_sources.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/record_sources.tt @@ -7,11 +7,12 @@ [% SET footerjs = 1 %] [% PROCESS 'i18n.inc' %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Record sources") | html %] › - [% t("Administration") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Record sources") | html %] + › [% t("Administration") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -23,14 +24,14 @@
              [% MACRO jsinclude BLOCK %] - [% INCLUDE 'calendar.inc' %] + [% INCLUDE 'calendar.inc' %] + [% INCLUDE 'datatables.inc' %] [% INCLUDE 'columns_settings.inc' %] [% INCLUDE 'js-patron-format.inc' %] [% INCLUDE 'js-date-format.inc' %] [% Asset.js("js/vue/dist/admin/record_sources.js") | $raw %] - [% END %] [% INCLUDE 'intranet-bottom.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/restrictions.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/restrictions.tt index 8c1927d033..42cc8b0a9b 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/restrictions.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/restrictions.tt @@ -4,21 +4,25 @@ [% PROCESS 'restriction-types.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% IF op == 'add_form' %] - [% IF ( restriction ) %] - [% t("Modify restriction type") | html %] '[% PROCESS restriction_type_description restriction_type=restriction %]' › - [% ELSE %] - [% t("New restriction type") | html %] › +<title + >[% FILTER collapse %] + [% IF op == 'add_form' %] + [% IF ( restriction ) %] + [% t("Modify restriction type") | html %] + '[% PROCESS restriction_type_description restriction_type=restriction %]' › + [% ELSE %] + [% t("New restriction type") | html %] + › + [% END %] [% END %] - [% END %] - [% IF op == 'delete_confirm' %] - [% t("Confirm deletion of restriction type") | html %] '[% PROCESS restriction_type_description restriction_type=restriction %]' › - [% END %] - [% t("Patron restriction types") | html %] › - [% t("Administration") | html %] › - [% t("Koha") | html %] -[% END %] + [% IF op == 'delete_confirm' %] + [% t("Confirm deletion of restriction type") | html %] + '[% PROCESS restriction_type_description restriction_type=restriction %]' › + [% END %] + [% t("Patron restriction types") | html %] + › [% t("Administration") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -65,180 +69,168 @@ [% WRAPPER 'main-container.inc' aside='admin-menu' %] -[% FOR m IN messages %] -
              - [% SWITCH m.code %] - [% CASE 'add_success' %] - Restriction type added. - [% CASE 'update_success' %] - Restriction type updated. - [% CASE 'duplicate_display_text' %] - Another restriction type already has this label. - [% CASE 'duplicate_code' %] - Another restriction type already has this code. - [% CASE 'delete_success' %] - Restriction type deleted. - [% CASE 'delete_default' %] - Cannot delete the default restriction type. - [% CASE 'delete_system' %] - Cannot delete a system restriction type. - [% CASE %] - [% m.code | html %] - [% END %] -
              -[% END %] - -[% IF op == 'add_form' %] -
              - [% INCLUDE 'csrf-token.inc' %] - - - [% IF restriction %] -

              Modify restriction type '[% PROCESS restriction_type_description restriction_type=restriction %]'

              - - [% ELSE %] -

              New restriction type

              - [% END %] -
              -
                - [% IF restriction %] -
              1. - Code: [% restriction.code | html %] - -
              2. -
              3. - - - Required -
              4. -
              5. - - -
              6. -
              7. - - -
              8. - [% ELSE %] -
              9. - - - Required -
              10. -
              11. - - - Required -
              12. -
              13. - - -
              14. -
              15. - - -
              16. - [% END %] -
              -
              - -
              - - Cancel -
              -
              -[% END %] - -[% IF op == 'delete_confirm' %] -
              -

              Confirm restriction type deletion

              -

              Are you sure you want to delete '[% PROCESS restriction_type_description restriction_type=restriction %]'?

              -
              - [% INCLUDE 'csrf-token.inc' %] - - - -
              -
              - -
              -
              -[% END %] - -[% IF op == 'list' %] - - - -

              Patron restriction types

              - - [% IF restrictions %] -
              - - - - - - - - - - - - - [% FOREACH restriction IN restrictions %] - - - - - - - - - [% END %] - -
              CodeLabelDefaultLift after payment?Fee limitActions
              - [% restriction.code | html %] - - [% PROCESS restriction_type_description restriction_type=restriction %] - - [% IF restriction.is_default %]Yes[% END %] - - [% IF restriction.lift_after_payment %]Yes[% END %] - - [% IF restriction.fee_limit %][% restriction.fee_limit | html %][% END %] - - Edit - [% IF !restriction.is_system && !restriction.is_default %] - Delete - [% END %] - [% IF !restriction.is_system && !restriction.is_default %] -
              - [% INCLUDE 'csrf-token.inc' %] - - - -
              - [% END %] -
              -
              - [% ELSE %] -
              No restriction types have been defined. Create a new restriction type.
              + [% FOR m IN messages %] +
              + [% SWITCH m.code %] + [% CASE 'add_success' %] + Restriction type added. + [% CASE 'update_success' %] + Restriction type updated. + [% CASE 'duplicate_display_text' %] + Another restriction type already has this label. + [% CASE 'duplicate_code' %] + Another restriction type already has this code. + [% CASE 'delete_success' %] + Restriction type deleted. + [% CASE 'delete_default' %] + Cannot delete the default restriction type. + [% CASE 'delete_system' %] + Cannot delete a system restriction type. + [% CASE %] + [% m.code | html %] + [% END %] +
              [% END %] -[% END %] + [% IF op == 'add_form' %] +
              + [% INCLUDE 'csrf-token.inc' %] + + + [% IF restriction %] +

              Modify restriction type '[% PROCESS restriction_type_description restriction_type=restriction %]'

              + + [% ELSE %] +

              New restriction type

              + [% END %] +
              +
                + [% IF restriction %] +
              1. + Code: [% restriction.code | html %] + +
              2. +
              3. + + + Required +
              4. +
              5. + + +
              6. +
              7. + + +
              8. + [% ELSE %] +
              9. + + + Required +
              10. +
              11. + + + Required +
              12. +
              13. + + +
              14. +
              15. + + +
              16. + [% END %] +
              +
              + +
              + + Cancel +
              +
              + [% END %] + + [% IF op == 'delete_confirm' %] +
              +

              Confirm restriction type deletion

              +

              Are you sure you want to delete '[% PROCESS restriction_type_description restriction_type=restriction %]'?

              +
              + [% INCLUDE 'csrf-token.inc' %] + + + +
              +
              + +
              +
              + [% END %] + + [% IF op == 'list' %] + + +

              Patron restriction types

              + + [% IF restrictions %] +
              + + + + + + + + + + + + + [% FOREACH restriction IN restrictions %] + + + + + + + + + [% END %] + +
              CodeLabelDefaultLift after payment?Fee limitActions
              [% restriction.code | html %] [% PROCESS restriction_type_description restriction_type=restriction %] [% IF restriction.is_default %]Yes[% END %] [% IF restriction.lift_after_payment %]Yes[% END %] [% IF restriction.fee_limit %][% restriction.fee_limit | html %][% END %] + Edit + [% IF !restriction.is_system && !restriction.is_default %] + Delete + [% END %] + [% IF !restriction.is_system && !restriction.is_default %] +
              + [% INCLUDE 'csrf-token.inc' %] + + + +
              + [% END %] +
              + [% ELSE %] +
              No restriction types have been defined. Create a new restriction type.
              + [% END %] + [% END %] [% END %] [% MACRO jsinclude BLOCK %] @@ -263,7 +255,6 @@ $("#fee_limit").prop("required",false).nextAll().remove(); } }); - [% Asset.js("js/restrictiontypes.js") | $raw %] [% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/search_filters.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/search_filters.tt index 896530a048..f822751a8f 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/search_filters.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/search_filters.tt @@ -5,17 +5,18 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] - [% FILTER collapse %] - [% t("Search filters") | html %] › - [% t("Administration") | html %] › - [% t("Koha") | html %] -[% END %] - [% INCLUDE 'doc-head-close.inc' %] +[% FILTER collapse %] + [% t("Search filters") | html %] + › [% t("Administration") | html %] › [% t("Koha") | html %] + [% END %] +[% INCLUDE 'doc-head-close.inc' %] - [% INCLUDE 'header.inc' %] - [% INCLUDE 'prefs-admin-search.inc' %] +[% INCLUDE 'header.inc' %] +[% INCLUDE 'prefs-admin-search.inc' %] [% WRAPPER 'sub-header.inc' %] [% WRAPPER breadcrumbs %] @@ -30,187 +31,181 @@ [% WRAPPER 'main-container.inc' aside='admin-menu' %] - [% IF filters_count %] -
              -

              Search filters

              - - - - - - - - - - - - - -
              IdNameQueryLimitsOPACStaff interface 
              -
              - [% ELSE %] -
              - There are no search filters defined. -
              - [% END %] + [% IF filters_count %] +
              +

              Search filters

              + + + + + + + + + + + + +
              IdNameQueryLimitsOPACStaff interface 
              +
              + [% ELSE %] +
              There are no search filters defined.
              + [% END %] [% END %] -
            diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/sru_modmapping.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/sru_modmapping.tt index 5df30c3d6e..10ba5b9cfc 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/sru_modmapping.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/sru_modmapping.tt @@ -3,19 +3,18 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("SRU search field mapping for bibliographic records") | html %] › - [% t("Z39.50/SRU servers") | html %] › - [% t("Administration") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("SRU search field mapping for bibliographic records") | html %] + › [% t("Z39.50/SRU servers") | html %] › [% t("Administration") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %]
            -
            [% INCLUDE 'messages.inc' %]

            SRU search field mapping for bibliographic records

            @@ -84,17 +83,17 @@
            -
            - + + [% MACRO jsinclude BLOCK %] [% Asset.js("js/admin-menu.js") | $raw %] [% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/sru_modmapping_auth.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/sru_modmapping_auth.tt index 98a95ce1c3..0e9c7b2b92 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/sru_modmapping_auth.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/sru_modmapping_auth.tt @@ -1,19 +1,18 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("SRU search field mapping for authorities") | html %] › - [% t("Z39.50/SRU servers") | html %] › - [% t("Administration") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("SRU search field mapping for authorities") | html %] + › [% t("Z39.50/SRU servers") | html %] › [% t("Administration") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %]
            -
            [% INCLUDE 'messages.inc' %]

            SRU search field mapping for authorities

            @@ -83,17 +82,17 @@
            - - + + [% MACRO jsinclude BLOCK %] [% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/systempreferences.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/systempreferences.tt index c7eff8a401..cd7936b44a 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/systempreferences.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/systempreferences.tt @@ -4,24 +4,28 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% IF ( add_form ) %] - [% IF ( modify ) %] - [% tx("Modify system preference '{system_preference}'", { system_preference = searchfield }) | html %] - [% ELSE %] - [% t("New system preference") | html %] - [% END %] › - [% END %] - [% IF ( delete_confirm ) %] - [% tx("Confirm deletion of system preference '{system_preference}'", { system_preference = searchfield }) | html %] › - [% END %] - [% IF ( delete_confirmed ) %] - [% t("System preference deleted") | html %] › - [% END %] - [% t("Local use system preferences") | html %] › - [% t("Administration") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% IF ( add_form ) %] + [% IF ( modify ) %] + [% tx("Modify system preference '{system_preference}'", { system_preference = searchfield }) | html %] + [% ELSE %] + [% t("New system preference") | html %] + [% END %] + › + [% END %] + [% IF ( delete_confirm ) %] + [% tx("Confirm deletion of system preference '{system_preference}'", { system_preference = searchfield }) | html %] + › + [% END %] + [% IF ( delete_confirmed ) %] + [% t("System preference deleted") | html %] + › + [% END %] + [% t("Local use system preferences") | html %] + › [% t("Administration") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -79,7 +83,7 @@ [% WRAPPER 'main-container.inc' aside='prefs-menu' %] -[% IF ( add_form ) %] + [% IF ( add_form ) %]

            [% IF ( modify ) %] [% tx("Modify system preference '{system_preference}'", { system_preference = searchfield }) | html %] @@ -89,176 +93,198 @@

            - [% INCLUDE 'csrf-token.inc' %] -
            - System preference details -
              -
            1. -
            2. [% IF ( searchfield ) %]Variable: [% searchfield | html %] - [% ELSE %][% END %]
            3. -
            4. - [% IF ( type_free ) %] - - [% ELSIF ( type_upload ) %] - - [% ELSIF ( type_textarea || type_htmlarea ) %] - [% IF ( type_htmlarea ) && ( Koha.Preference('UseWYSIWYGinSystemPreferences') ) %] - - [% ELSE %] - - [% END %] - [% ELSIF ( type_choice ) %] -
            5. +
            6. [% IF ( searchfield ) %] + Variable: [% searchfield | html %] + [% ELSE %] + + [% END %]
            7. +
            8. + [% IF ( type_free ) %] + + [% ELSIF ( type_upload ) %] + + [% ELSIF ( type_textarea || type_htmlarea ) %] + [% IF ( type_htmlarea ) && ( Koha.Preference('UseWYSIWYGinSystemPreferences') ) %] + [% ELSE %] - - + + [% END %] + [% ELSIF ( type_choice ) %] + + [% END %] + [% IF ( type_langselector ) %] + [% IF ( languages_loop ) %] + + [% FOREACH languages_loo IN languages_loop %] + + [% END %] +
              + [% IF ( languages_loo.plural ) %] + [% IF ( languages_loo.native_description ) %][% languages_loo.native_description | html %][% ELSE %][% languages_loo.rfc4646_subtag | html %][% END %] + [% FOREACH sublanguages_loo IN languages_loo.sublanguages_loop %] +
              + [% IF ( sublanguages_loo.sublanguage_current ) %] + + [% ELSE %] + + [% END %]
              + [% END %] + [% ELSE %] + [% IF ( languages_loo.current ) %] + + [% ELSE %] + + [% END %] + [% END %] +
              [% END %] [% END %] - - [% END %] - [% IF ( type_langselector ) %] - [% IF ( languages_loop ) %] - - [% FOREACH languages_loo IN languages_loop %] - - [% END %] -
              - [% IF ( languages_loo.plural ) %] - [% IF ( languages_loo.native_description ) %][% languages_loo.native_description | html %][% ELSE %][% languages_loo.rfc4646_subtag | html %][% END %] - [% FOREACH sublanguages_loo IN languages_loo.sublanguages_loop %]
              - [% IF ( sublanguages_loo.sublanguage_current ) %] - + [% IF ( type_yesno ) %] + [% IF ( value_yes ) %] + + [% ELSE %] + + [% END %] + + [% IF ( value_no ) %] + + [% ELSE %] + + [% END %] + + [% END %] + + +
            9. + +
              Note: change the variable type to one of the dropdown values as needed
            10. + +
              (a choice list for choice (separated by |) or cols|rows for texarea)
              +
            11. + + + +
              + [% IF ( return_tab ) %] + Cancel [% ELSE %] - - [% END %]
              - [% END %] - - [% ELSE %] - [% IF ( languages_loo.current ) %] - - [% ELSE %] - - [% END %] - [% END %] -
              - [% END %] - - [% END %] - - [% IF ( type_yesno ) %] - [% IF ( value_yes ) %] - [% ELSE %] - [% END %] - - [% IF ( value_no ) %] - [% ELSE %] - [% END %] - - [% END %] -
            12. - -
            13. - -
              Note: change the variable type to one of the dropdown values as needed
              -
            14. - -
              (a choice list for choice (separated by |) or cols|rows for texarea)
              -
            15. -
            -
            - -
            - [% IF ( return_tab ) %] - Cancel - [% ELSE %] - Cancel - [% END %] -
            - +
            [% END %] @@ -298,135 +324,168 @@ [% END %] [% IF ( else ) %] + - - -

            Local use system preferences

            -
            - - - - - - - - [% FOREACH loo IN loop %] - - - - [% IF ( loo.oneline ) %] - [% SET td_class = 'single-line' %] - [% END %] - -
            PreferenceExplanationValueActions
            [% loo.variable | html %] [% loo.explanation | html %] -
            - [% INCLUDE 'csrf-token.inc' %] - [% IF ( loo.type_free ) %] - - [% END %] - [% IF ( loo.type_upload ) %] - - [% END %] - [% IF ( loo.type_textarea ) || ( loo.type_htmlarea ) %] - [% IF ( loo.type_htmlarea ) && ( Koha.Preference('UseWYSIWYGinSystemPreferences') ) %] - - [% ELSE %] - - - [% END %] - [% END %] - [% IF ( loo.type_choice ) %] - - [% END %] - [% IF ( loo.type_langselector ) %] - [% IF ( loo.languages_loop ) %] - - [% FOREACH languages_loo IN loo.languages_loop %] - - - - + +
            - [% IF ( languages_loo.plural ) %] - [% IF ( languages_loo.native_description ) %][% languages_loo.native_description | html %][% ELSE %][% languages_loo.rfc4646_subtag | html %][% END %] - [% FOREACH sublanguages_loo IN languages_loo.sublanguages_loop %] + + + [% END %] - - [% ELSE %] - [% IF ( languages_loo.current ) %] - - [% ELSE %] - - [% END %] - [% END %] - - [% END %] -
            - [% IF ( sublanguages_loo.sublanguage_current ) %] - Edit + Delete
            - [% END %] - - [% END %] - - [% IF ( loo.type_yesno ) %] - [% IF ( loo.value_yes ) %] - [% ELSE %] - [% END %] - - [% IF ( loo.value_no ) %] - [% ELSE %] - [% END %] - - [% END %] - - - - - - - -
            Edit Delete
            + [% END %] -
            - [% END %] - [% END %] [% MACRO jsinclude BLOCK %] @@ -435,15 +494,15 @@ [% IF ( else ) %] [% INCLUDE 'datatables.inc' %] [% END %] [% END %] [% INCLUDE 'intranet-bottom.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/z3950servers.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/z3950servers.tt index 4d72c3f5d3..cac044ecf3 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/admin/z3950servers.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/admin/z3950servers.tt @@ -12,18 +12,22 @@ [% SET servertype = "Z39.50" %] [% END %] -[% FILTER collapse %] - [% IF op == 'edit' %] - [% tx("Modify {servertype} server '{servername}'", { servertype = servertype, servername = server.servername }) | html %] › - [% ELSIF op == 'add' %] - [% tx("New {servertype} server", { servertype = servertype }) | html %] › - [% ELSIF searchfield %] - [% tx("Search results for '{search_keyword}'", { search_keyword = searchfield }) | html %] › - [% END %] - [% t("Z39.50/SRU servers") | html %] › - [% t("Administration") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% IF op == 'edit' %] + [% tx("Modify {servertype} server '{servername}'", { servertype = servertype, servername = server.servername }) | html %] + › + [% ELSIF op == 'add' %] + [% tx("New {servertype} server", { servertype = servertype }) | html %] + › + [% ELSIF searchfield %] + [% tx("Search results for '{search_keyword}'", { search_keyword = searchfield }) | html %] + › + [% END %] + [% t("Z39.50/SRU servers") | html %] + › [% t("Administration") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -48,12 +52,10 @@ [% WRAPPER breadcrumb_item bc_active= 1 %] [% tx("Modify {servertype} server '{servername}'", { servertype = servertype, servername = server.servername }) | html %] [% END %] - [% ELSIF op == 'add' %] [% WRAPPER breadcrumb_item bc_active= 1 %] [% tx("New {servertype} server", { servertype = servertype }) | html %] [% END %] - [% ELSIF searchfield %] [% WRAPPER breadcrumb_item bc_active= 1 %] [% tx("Search results for '{search_keyword}'", { search_keyword = searchfield }) | html %] @@ -68,198 +70,201 @@ [% WRAPPER 'main-container.inc' aside='admin-menu' %] -[% IF msg_deleted %] -
            Z39.50/SRU server deleted ([% msg_add | html %])
            -[% ELSIF msg_updated %] -
            Z39.50/SRU server updated ([% msg_add | html %])
            -[% ELSIF msg_added %] -
            Z39.50/SRU server added ([% msg_add | html %])
            -[% ELSIF msg_notfound %] -
            Error: Server with ID [% msg_add | html %] not found
            -[% END %] - -[% IF ( add_form ) %] -
            - [% INCLUDE 'csrf-token.inc' %] - [% IF op == 'edit' %] -

            [% tx("Modify {servertype} server '{servername}'", { servertype = servertype, servername = server.servername }) | html %]

            - - [% ELSE %] -

            [% tx("New {servertype} server", { servertype = servertype }) | html %]

            - [% END %] - - - -
            -
              -
            1. - [% IF server.servername %] - - [% ELSE %] - - [% END %] - Required -
            2. - -
            3. Required - [% IF (server.servertype||type) == 'sru' %] -
              Includes the domain part, but the path part of the URL should go into Database.
              - [% END %] -
            4. -
            5. Required -
            6. -
            7. Required -
            8. -
            9. -
            10. -
            11. -
            12. -
            13. - - [% IF ( server.checked ) %] - - [% ELSE %] - - [% END %] - Searched by default. -
            14. -
            15. - - -
              Display order.
              -
            16. - [% IF (server.servertype||type) == 'zed' %] -
            17. - - -
              Additional PQF attributes added to each query.
              -
            18. - [% END %] - -
            19. - - -
              Z39.50 can send records in various formats. Choose one.
              -
            20. - -
            21. - - -
              Z39.50 can send records in various encodings. Choose one.
              -
            22. - -
            23. - - seconds -
              Enter 0 to disable.
              -
            24. -
            25. - -
            26. - [% IF (server.servertype||type) == 'sru' %] -
            27. - - -
              Separate options by commas. Example: sru=get,sru_version=1.1. See also http://www.indexdata.com/yaz/doc/zoom.html.
              -
            28. -
            29. - - - -
            30. - [% END %] -
            31. - - -
              Separate multiple filenames by commas.
              -
            32. - -
            -
            - -
            Cancel
            -
            -[% END %] - -[% IF op == 'list' %] - -

            Z39.50/SRU servers

            - [% IF searchfield %] -

            - [% tx("Searching by target starting with '{search_keyword}'", { search_keyword = searchfield }) | html %] -

            + [% IF msg_deleted %] +
            Z39.50/SRU server deleted ([% msg_add | html %])
            + [% ELSIF msg_updated %] +
            Z39.50/SRU server updated ([% msg_add | html %])
            + [% ELSIF msg_added %] +
            Z39.50/SRU server added ([% msg_add | html %])
            + [% ELSIF msg_notfound %] +
            Error: Server with ID [% msg_add | html %] not found
            [% END %] -
            - + [% IF ( add_form ) %] + + [% INCLUDE 'csrf-token.inc' %] + [% IF op == 'edit' %] +

            [% tx("Modify {servertype} server '{servername}'", { servertype = servertype, servername = server.servername }) | html %]

            + + [% ELSE %] +

            [% tx("New {servertype} server", { servertype = servertype }) | html %]

            + [% END %] - - - - [% FOREACH loo IN loop %] - - - - - - - - [% END %] - -
            TargetHostname/PortDatabaseUseridPasswordPreselectedRankSyntaxEncodingTimeoutRecord typeAttributesActions
            [% loo.servername | html %][% loo.host | html %]:[% loo.port | html %][% loo.db | html %][% loo.userid | html %][% IF loo.password %]########[% END %][% IF ( loo.checked ) %]Yes[% ELSE %]No[% END %][% loo.rank | html %][% loo.syntax | html %][% loo.encoding | html %][% loo.timeout | html %][% IF ( loo.recordtype == 'biblio' ) %] - Bibliographic - [% ELSIF ( loo.recordtype == 'authority' ) %] - Authority - [% END %] - [% loo.attributes | html %] -
            - - Actions - - -
            -
            -
            -[% END %] + [% END %] +
          1. + + +
            Z39.50 can send records in various formats. Choose one.
            +
          2. + +
          3. + + +
            Z39.50 can send records in various encodings. Choose one.
            +
          4. + +
          5. + + seconds +
            Enter 0 to disable.
            +
          6. +
          7. + +
          8. + [% IF (server.servertype||type) == 'sru' %] +
          9. + + +
            Separate options by commas. Example: sru=get,sru_version=1.1. See also http://www.indexdata.com/yaz/doc/zoom.html.
            +
          10. +
          11. + + + +
          12. + [% END %] +
          13. + + +
            Separate multiple filenames by commas.
            +
          14. + + + +
            Cancel
            + + [% END %] + + [% IF op == 'list' %] + +

            Z39.50/SRU servers

            + [% IF searchfield %] +

            [% tx("Searching by target starting with '{search_keyword}'", { search_keyword = searchfield }) | html %]

            + [% END %] + +
            + + + + + [% FOREACH loo IN loop %] + + + + + + + [% END %] + +
            TargetHostname/PortDatabaseUseridPasswordPreselectedRankSyntaxEncodingTimeoutRecord typeAttributesActions
            [% loo.servername | html %][% loo.host | html %]:[% loo.port | html %][% loo.db | html %][% loo.userid | html %][% IF loo.password %]########[% END %][% IF ( loo.checked ) %]Yes[% ELSE %]No[% END %][% loo.rank | html %] [% loo.syntax | html %][% loo.encoding | html %][% loo.timeout | html %][% IF ( loo.recordtype == 'biblio' ) %] + Bibliographic + [% ELSIF ( loo.recordtype == 'authority' ) %] + Authority + [% END %] + [% loo.attributes | html %] +
            + Actions + +
            +
            +
            + + [% END %] [% END %] [% MACRO jsinclude BLOCK %] @@ -267,7 +272,6 @@ [% IF op == 'list' %] [% INCLUDE 'datatables.inc' %] [% END %] - [% Asset.js( "lib/sortable/Sortable.min.js" ) | $raw %] [% Asset.js("js/cataloging.js") | $raw %] - [% Asset.css("css/addbiblio.css") | $raw %] - [% WRAPPER 'header.inc' %] - [% INCLUDE 'authorities-search.inc' %] - [% END %] -
            -
            Loading, please wait...
            -
            +[% WRAPPER 'header.inc' %] + [% INCLUDE 'authorities-search.inc' %] +[% END %] +
            +
            Loading, please wait...
            +
            [% WRAPPER 'sub-header.inc' %] [% WRAPPER breadcrumbs %] @@ -427,138 +429,156 @@ [% WRAPPER breadcrumb_item bc_active= 1 %] Modify authority #[% authid | html %] ([% authtypetext | html %]) [% END %] - [% ELSE %] [% WRAPPER breadcrumb_item bc_active= 1 %] Adding authority [% authtypetext | html %] [% END %] - [% END %] [% END #/ WRAPPER breadcrumbs %] [% END #/ WRAPPER sub-header.inc %] [% WRAPPER 'main-container.inc' wide_centered => 1 %] + [% IF ( authid ) %] +

            Modify authority #[% authid | html %] [% authtypetext | html %]

            + [% ELSE %] +

            Adding authority [% authtypetext | html %]

            + [% END %] + +
            + + [% IF ( duplicateauthid ) %] +
            +

            Duplicate record suspected

            +

            Is this a duplicate of + [% duplicateauthvalue | html %] + ?

            + +

            + Yes: Edit existing authority +

            +

            + No: Save as new authority +

            +
            + [% END # /IF duplicateauthid %] + +
            + [% INCLUDE 'csrf-token.inc' %] + + + + + + + + + + +
            + +
            [% IF ( authid ) %] -

            Modify authority #[% authid | html %] [% authtypetext | html %]

            + Replace record via Z39.50/SRU search [% ELSE %] -

            Adding authority [% authtypetext | html %]

            + Z39.50/SRU search [% END %] - -
            - - [% IF ( duplicateauthid ) %] -
            -

            Duplicate record suspected

            -

            Is this a duplicate of [% duplicateauthvalue | html %] ?

            - -

            - Yes: Edit existing authority -

            -

            - No: Save as new authority -

            -
            - [% END # /IF duplicateauthid %] - - - [% INCLUDE 'csrf-token.inc' %] - - - - - - - - - - -
            - -
            - [% IF ( authid ) %] - Replace record via Z39.50/SRU search +
            +
            + +
            - + + +
            + [% IF ( authid ) %] + Cancel + [% ELSE %] + Cancel + [% END %] +
            +
            +
            + [% IF ( BIG_LOOP && BIG_LOOP.size > 1 ) %] + [% WRAPPER tabs_nav %] + [%- FOREACH BIG_LOO IN BIG_LOOP -%] + [% IF loop.first %] + [% SET bt_active = 1 %] + [% ELSE %] + [% SET bt_active = 0 %] + [% END %] + [% WRAPPER tab_item tabname= "tab${BIG_LOO.number}XX" bt_active= bt_active %] + [% BIG_LOO.number | html %] + [% END %] + [%- END -%] + [% END # /WRAPPER tabs_nav %] + [% END %] + -
            - -
            - [% IF ( authid ) %] - Cancel - [% ELSE %] - Cancel [% END %] -
            -
            -
            - [% IF ( BIG_LOOP && BIG_LOOP.size > 1 ) %] - [% WRAPPER tabs_nav %] - [%- FOREACH BIG_LOO IN BIG_LOOP -%] - [% IF loop.first %] - [% SET bt_active = 1 %] - [% ELSE %] - [% SET bt_active = 0 %] - [% END %] - [% WRAPPER tab_item tabname= "tab${BIG_LOO.number}XX" bt_active= bt_active %] - [% BIG_LOO.number | html %] - [% END %] - [%- END -%] - [% END # /WRAPPER tabs_nav %] - [% END %] -
              - [% FOREACH BIG_LOO IN BIG_LOOP %] - [% IF loop.first %][% SET tab_selected = "tab_selected" %][% ELSE %][% SET tab_selected = "" %][% END %] - [% FOREACH innerloo IN BIG_LOO.innerloop %] - [% IF ( innerloo.tag ) %] -
            • - [% innerloo.tag | uri %] -
            • - [% END %] - [% END %] - [% END %] -
            -
            -
            -
            - [% IF count %] - Used in [% count | html %] record(s) - [% ELSE %] - This authority is not used in any records. [% END %] -
            + [% END %] +
          + + + +
          + [% IF count %] + Used in [% count | html %] record(s) + [% ELSE %] + This authority is not used in any records. + [% END %] +
          - + [% WRAPPER tabs id= "authoritytabs" %] [% WRAPPER tab_panels %] [% FOREACH BIG_LOO IN BIG_LOOP %] @@ -782,31 +802,31 @@ [% END # /WRAPPER tabs %] -
          - [% FOREACH hidden_loo IN hidden_loop %] - - - - - - [% END %] -
          - [% IF ( oldauthnumtagfield ) %] - - - - - - - - - - [% END %] +
          + [% FOREACH hidden_loo IN hidden_loop %] + + + + + + [% END %] +
          + + [% IF ( oldauthnumtagfield ) %] + + + + + + + + + + [% END %] + - - - [% INCLUDE 'modals/cataloguing_create_av.inc' %] - [% INCLUDE 'modals/edit_authority_preview.inc' %] + [% INCLUDE 'modals/cataloguing_create_av.inc' %] + [% INCLUDE 'modals/edit_authority_preview.inc' %] [% END %] [% INCLUDE 'intranet-bottom.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/authorities/blinddetail-biblio-search.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/authorities/blinddetail-biblio-search.tt index 71fb20d4ce..3812099def 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/authorities/blinddetail-biblio-search.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/authorities/blinddetail-biblio-search.tt @@ -2,18 +2,18 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Authority details") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Authority details") | html %] + › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] [% WRAPPER 'main-container.inc' %] - -
          Loading
          - +
          Loading
          [% END %] [% MACRO jsinclude BLOCK %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/authorities/detail.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/authorities/detail.tt index 2e37e4d435..68cd69c455 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/authorities/detail.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/authorities/detail.tt @@ -5,15 +5,16 @@ [% SET footerjs = 1 %] [% PROCESS 'authorities.inc' %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% IF ( unknownauthid ) %] - [% t("Unknown authority record") | html %] - [% ELSE %] - [% tx("Details for authority #{authid} ({authtypetext})", { authid = authid, authtypetext = authtypetext }) | html %] - [% END %] › - [% t("Authorities") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% IF ( unknownauthid ) %] + [% t("Unknown authority record") | html %] + [% ELSE %] + [% tx("Details for authority #{authid} ({authtypetext})", { authid = authid, authtypetext = authtypetext }) | html %] + [% END %] + › [% t("Authorities") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] [% Asset.css("css/addbiblio.css") | $raw %] [% IF ( displayhierarchy ) %] @@ -43,94 +44,93 @@ [% END #/ WRAPPER sub-header.inc %] [% WRAPPER 'main-container.inc' %] - [% INCLUDE 'authorities-toolbar.inc' %] -
          - [% INCLUDE 'csrf-token.inc' %] - - -
          + [% INCLUDE 'authorities-toolbar.inc' %] +
          + [% INCLUDE 'csrf-token.inc' %] + + +
          - [% IF ( displayhierarchy ) %] -
          - [% PROCESS showhierarchy trees = loophierarchies %] -
          - [% END %] + [% IF ( displayhierarchy ) %] +
          [% PROCESS showhierarchy trees = loophierarchies %]
          + [% END %] + [% IF ( unknownauthid ) %] +

          Authority does not exist

          +
          The authority record you requested does not exist ([% errauthid | html %]).
          + [% ELSE %] +

          Authority #[% authid | html %] ([% authtypetext | html %])

          - [% IF ( unknownauthid ) %] -

          Authority does not exist

          -
          The authority record you requested does not exist ([% errauthid | html %]).
          +
          + [% IF count %] + Used in [% count | html %] record(s) [% ELSE %] + This authority is not used in any records. + [% END %] +
          -

          Authority #[% authid | html %] ([% authtypetext | html %])

          + [% IF html %] + [% html | $raw %] + [% ELSE %] -
          - [% IF count %] - Used in [% count | html %] record(s) - [% ELSE %] - This authority is not used in any records. + [% WRAPPER tabs id= "authoritiestabs" %] + [% WRAPPER tabs_nav %] + [% FOREACH BIG_LOO IN BIG_LOOP %] + [% WRAPPER tab_item tabname= "tab${ BIG_LOO.number }XX" %] + [% BIG_LOO.number | html %] + [% END %] [% END %] -
          + [% END # /WRAPPER tabs_nav %] - [% IF html %] - [% html | $raw %] - [% ELSE %] + [% WRAPPER tab_panels %] + [% FOREACH BIG_LOO IN BIG_LOOP %] + [% WRAPPER tab_panel tabname="tab${ BIG_LOO.number }XX" %] + [% FOREACH innerloo IN BIG_LOO.innerloop %] +
          + [% IF ( innerloo.tag_number ) %] +
          + [% innerloo.tag_number | html %] + [% IF (innerloo.defined("ind1") ) %] + [% innerloo.ind1 | html %][% innerloo.ind2 | html %] + [% END %] + [% IF (innerloo.tag_desc) %] + - [% innerloo.tag_desc | html %] + [% END %] +
          + + [% END # /IF ( innerloo.tag_number ) %] - [% WRAPPER tabs id= "authoritiestabs" %] - [% WRAPPER tabs_nav %] - [% FOREACH BIG_LOO IN BIG_LOOP %] - [% WRAPPER tab_item tabname= "tab${ BIG_LOO.number }XX" %] - [% BIG_LOO.number | html %] - [% END %] - [% END %] - [% END # /WRAPPER tabs_nav %] - - [% WRAPPER tab_panels %] - [% FOREACH BIG_LOO IN BIG_LOOP %] - [% WRAPPER tab_panel tabname="tab${ BIG_LOO.number }XX" %] - [% FOREACH innerloo IN BIG_LOO.innerloop %] -
          - [% IF ( innerloo.tag_number ) %] -
          - [% innerloo.tag_number | html %] - [% IF (innerloo.defined("ind1") ) %] - [% innerloo.ind1 | html %][% innerloo.ind2 | html %] + [% FOREACH subfiel IN innerloo.subfield %] +
          +
          + [% UNLESS ( subfiel.hide_marc ) %] + [% subfiel.marc_subfield | html %] + [% END %] + [% subfiel.long_desc | html %] +
          + +
          + + [% IF ( subfiel.is_url ) %] + [% subfiel.marc_value | html %] + [% ELSE %] + [% subfiel.marc_value | html %] [% END %] - [% IF (innerloo.tag_desc) %] - - [% innerloo.tag_desc | html %] - [% END %] -
          - [% END # /IF ( innerloo.tag_number ) %] - - [% FOREACH subfiel IN innerloo.subfield %] -
          -
          - [% UNLESS ( subfiel.hide_marc ) %] - [% subfiel.marc_subfield | html %] - [% END %] - [% subfiel.long_desc | html %] -
          -
          - - [% IF ( subfiel.is_url ) %] - [% subfiel.marc_value | html %] - [% ELSE %] - [% subfiel.marc_value | html %] - [% END %] - -
          -
          - [% END #/FOREACH subfiel %] -
          - [% END # /FOREACH innerloo %] - [% END # /tab_panel#tab${ BIG_LOO.number }XX %] - [% END # /FOREACH BIG_LOO %] - [% END # /WRAPPER tab_panels %] - [% END # /WRAPPER tabs %] - - [% END # /IF html %] - - [% END # /IF ( unknownauthid ) %] + +
          + +
          + + [% END #/FOREACH subfiel %] +
          + + [% END # /FOREACH innerloo %] + [% END # /tab_panel#tab${ BIG_LOO.number }XX %] + [% END # /FOREACH BIG_LOO %] + [% END # /WRAPPER tab_panels %] + [% END # /WRAPPER tabs %] + [% END # /IF html %] + [% END # /IF ( unknownauthid ) %] [% END %] [% MACRO jsinclude BLOCK %] @@ -140,49 +140,49 @@ [% END %] [% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/authorities/merge.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/authorities/merge.tt index ce88e1e14a..9f4e2a7c05 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/authorities/merge.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/authorities/merge.tt @@ -5,16 +5,23 @@ [% PROCESS 'merge-record.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Merging records") | html %] › - [% t("Authorities") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Merging records") | html %] + › [% t("Authorities") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -35,128 +42,133 @@ div#result { margin-top: 1em; } [% END #/ WRAPPER sub-header.inc %] [% WRAPPER 'main-container.inc' wide_full => 1 %] +

          Merging records

          -

          Merging records

          + [% IF ( errors ) %] -[% IF ( errors ) %] + [% FOREACH error IN errors %] +
          + [% IF error.code == 'WRONG_COUNT' %] + Number of records provided for merging: [% error.value | html %]. Currently only 2 records can be merged at a time. + [% ELSIF error.code == 'DESTRUCTIVE_MERGE' %] + You cannot merge a record with itself. Please select two different authorities. + [% ELSIF error.code == 'WRONG_FRAMEWORK' %] + The default framework cannot be used, or the framework does not exist. Please select another framework for merging. + [% ELSIF error.code == 'EMPTY_MARC' %] + Sorry, but we did not find any MARC tags in the reference record. + [% ELSIF error.code == 'MISSING_RECORD' %] + Sorry, but we did not find a record for number: [% error.value | html %]. + [% ELSE %] + [% error | html %] + [% END %] +
          + [% END %] + [% ELSIF ( result ) %] +

          The merging was successful. View the merged record.

          + [% ELSIF ( choosereference ) %] +

          Please choose which record will be the reference for the merge. The record chosen as reference will be kept, and the other will be deleted.

          +
          +
          + Merge reference +
            +
          1. +
          2. - [% FOREACH error IN errors %] -
            - [% IF error.code == 'WRONG_COUNT' %] - Number of records provided for merging: [% error.value | html %]. Currently only 2 records can be merged at a time. - [% ELSIF error.code == 'DESTRUCTIVE_MERGE' %] - You cannot merge a record with itself. Please select two different authorities. - [% ELSIF error.code == 'WRONG_FRAMEWORK' %] - The default framework cannot be used, or the framework does not exist. Please select another framework for merging. - [% ELSIF error.code == 'EMPTY_MARC' %] - Sorry, but we did not find any MARC tags in the reference record. - [% ELSIF error.code == 'MISSING_RECORD' %] - Sorry, but we did not find a record for number: [% error.value | html %]. - [% ELSE %] - [% error | html %] + [% IF frameworkselect %] +
          3. +
          4. + [% END %] +
          + + + +
          +
          + +
          +
          + [% ELSE %] +
          + [% INCLUDE 'csrf-token.inc' %] + +
          +
          [% PROCESS mergesource sourcerecords=records %]
          +
          [% PROCESS mergetarget authtypetext=frameworktext %]
          +
          + + + + + + + [% IF multipleauthtypes %] +
          Multiple authority types are used. There may be data loss when merging.
          [% END %] - + +
          + + +
          +
          [% END %] - -[% ELSIF ( result ) %] - -

          The merging was successful. View the merged record.

          - -[% ELSIF ( choosereference ) %] - -

          Please choose which record will be the reference for the merge. The record chosen as reference will be kept, and the other will be deleted.

          -
          -
          - Merge reference -
            -
          1. -
          2. - - [% IF frameworkselect %] -
          3. -
          4. - [% END %] -
          - - - -
          -
          - -
          -
          - -[% ELSE %] - -
          - [% INCLUDE 'csrf-token.inc' %] - -
          -
          -[% PROCESS mergesource sourcerecords=records %] -
          -
          -[% PROCESS mergetarget authtypetext=frameworktext %] -
          -
          - - - - - - -[% IF multipleauthtypes %] -
          Multiple authority types are used. There may be data loss when merging.
          -[% END %] - -
          - - -
          -
          - -[% END %] - [% END %] [% MACRO jsinclude BLOCK %] [% INCLUDE 'authorities_js.inc' %] [% Asset.js("js/merge-record.js") | $raw %] [% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/authorities/searchresultlist-auth.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/authorities/searchresultlist-auth.tt index d331b581e4..dd0f402d93 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/authorities/searchresultlist-auth.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/authorities/searchresultlist-auth.tt @@ -5,20 +5,22 @@ [% SET footerjs = 1 %] [% PROCESS 'authorities-search-results.inc' %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Cataloging authority plugin") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Cataloging authority plugin") | html %] + › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] [% Asset.css("css/addbiblio.css") | $raw %] @@ -28,25 +30,34 @@
            [% IF ( displayprev ) %]
          • - + Previous
          • [% END %] [% FOREACH number IN numbers %] [% IF ( number.highlight ) %] -
          • - [% number.number | html %] +
          • [% number.number | html %]
          • [% ELSE %]
          • - - [% number.number | html %] + + [% number.number | html %]
          • [% END %] [% END %] [% IF ( displaynext ) %]
          • - + Next
          • @@ -57,21 +68,20 @@ [% END %] - [% WRAPPER 'main-container.inc' %] +[% WRAPPER 'main-container.inc' %] +

            Authority search results

            + [% INCLUDE 'auth-finder-search.inc' %] + [% IF ( result ) %] +

            Results [% from | html %] to [% to | html %] of [% total | html %]

            + [% PROCESS 'result_page_numbers' %] + [% ELSE %] +
            +

            No results found

            +
            + [% END %] -

            Authority search results

            - [% INCLUDE 'auth-finder-search.inc' %] - [% IF ( result ) %] -

            Results [% from | html %] to [% to | html %] of [% total | html %]

            - [% PROCESS 'result_page_numbers' %] - [% ELSE %] -
            -

            No results found

            -
            - [% END %] - - [% IF ( result ) %] -
            + [% IF ( result ) %] +
            @@ -101,29 +111,32 @@ [% END %] [% IF Koha.Preference('ShowHeadingUse') %] - + [% END %] - + [% END %]
            Summary
              -
            • [% IF resul.main %][% ELSE %][% END %] Main/Added Entry
            • -
            • [% IF resul.subject %][% ELSE %][% END %] Subject
            • -
            • [% IF resul.series %][% ELSE %][% END %] Series Title
            • -
              +
            • [% IF resul.main %][% ELSE %][% END %] Main/Added Entry
            • +
            • [% IF resul.subject %][% ELSE %][% END %] Subject
            • +
            • [% IF resul.series %][% ELSE %][% END %] Series Title
            • +
            [% IF resul.summary && resul.summary.authorized && resul.summary.authorized.size > 1 %] [% FOREACH authorized IN resul.summary.authorized %] [% loop.count | html %] [% END %] - [% ELSE %] + [% ELSE %] Choose - [% END %] + [% END %] Edit authority Edit authority
            [% PROCESS 'result_page_numbers' %] - [% END %] - + [% END %] [% END %] [% INCLUDE 'authority-detail-modal.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/authorities/searchresultlist.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/authorities/searchresultlist.tt index e4da33f9fe..3894e37fe0 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/authorities/searchresultlist.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/authorities/searchresultlist.tt @@ -5,21 +5,22 @@ [% SET footerjs = 1 %] [% PROCESS 'authorities-search-results.inc' %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Authority search results") | html %] › - [% t("Authorities") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Authority search results") | html %] + › [% t("Authorities") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] [% Asset.css("css/addbiblio.css") | $raw %] @@ -42,108 +43,115 @@ [% WRAPPER 'main-container.inc' %] [% INCLUDE 'authorities-toolbar.inc' %] -

            Authority search results

            +

            Authority search results

            - -
            - [% IF ( query_error ) %] -

            Error: [% query_error | html %]

            - [% END %] + +
            + [% IF ( query_error ) %] +

            Error: [% query_error | html %]

            + [% END %] - [% IF ( total ) %] -
            [% pagination_bar | $raw %]
            + [% IF ( total ) %] +
            [% pagination_bar | $raw %]
            -

            - Results [% from | html %] to [% to | html %] of [% total | html %] -

            +

            Results [% from | html %] to [% to | html %] of [% total | html %]

            -
            - - - - - [% UNLESS ( isEDITORS ) %] - - [% END %] - [% IF Koha.Preference('ShowHeadingUse') %] - - [% END %] - [% IF ( CAN_user_editauthorities ) %] - - [% END %] - - [% FOREACH resul IN result %] - - - - [% UNLESS ( resul.isEDITORS ) %] - +
            +
            SummaryHeading typeUsed inHeading use 
            - [% IF resul.html %] - [% resul.html | $raw %] - [% ELSE %] - [% PROCESS authresult summary=resul.summary authid=resul.authid %] - [% END %] - [% resul.authtype | html %] - [% IF resul.used > 0 %] - [% resul.used | html %] record(s) - [% ELSE %] - 0 records - [% END %] -
            + + + + [% UNLESS ( isEDITORS ) %] + + [% END %] + [% IF Koha.Preference('ShowHeadingUse') %] + + [% END %] + [% IF ( CAN_user_editauthorities ) %] + + [% END %] + + [% FOREACH resul IN result %] + + + + [% UNLESS ( resul.isEDITORS ) %] + + [% END %] + [% IF Koha.Preference('ShowHeadingUse') %] + + [% END %] + [% IF ( CAN_user_editauthorities ) %] + + [% END %] + + [% END %] +
            SummaryHeading typeUsed inHeading use 
            + [% IF resul.html %] + [% resul.html | $raw %] + [% ELSE %] + [% PROCESS authresult summary=resul.summary authid=resul.authid %] + [% END %] + [% resul.authtype | html %] + [% IF resul.used > 0 %] + [% resul.used | html %] record(s) + [% ELSE %] + 0 records + [% END %] +
              +
            • [% IF resul.main %][% ELSE %][% END %] Main/Added Entry
            • +
            • [% IF resul.subject %][% ELSE %][% END %] Subject
            • +
            • [% IF resul.series %][% ELSE %][% END %] Series Title
            • +
            +
            + Actions + +
            +
            +
            + + [% INCLUDE 'authority-detail-modal.inc' %] + +
            [% pagination_bar | $raw %]
            + [% ELSE %] + No results found [% END %] - [% IF Koha.Preference('ShowHeadingUse') %] -
              -
            • [% IF resul.main %][% ELSE %][% END %] Main/Added Entry
            • -
            • [% IF resul.subject %][% ELSE %][% END %] Subject
            • -
            • [% IF resul.series %][% ELSE %][% END %] Series Title
            • -
            - [% END %] - [% IF ( CAN_user_editauthorities ) %] - -
            - - Actions - -
            - - [% END %] - - [% END %] -
            - - [% INCLUDE 'authority-detail-modal.inc' %] - -
            [% pagination_bar | $raw %]
            - - [% ELSE %] - No results found - [% END %] -
            + [% END %] [% MACRO jsinclude BLOCK %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/basket/basket.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/basket/basket.tt index b9909ea283..d39795a4db 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/basket/basket.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/basket/basket.tt @@ -6,8 +6,7 @@ [% SET footerjs = 1 %] [% BLOCK controls %]

            - Select all Clear all - | Selected records: + Select all Clear all | Selected records: Remove [% IF ( loggedinusername ) %] @@ -28,11 +27,12 @@

            [% END %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Your cart") | html %] › - [% t("Catalog") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Your cart") | html %] + › [% t("Catalog") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -40,320 +40,330 @@ [% WRAPPER 'main-container.inc' wide_centered => 1 %] -
            +
            +

            Your cart

            -

            Your cart

            +
            + [% IF ( verbose ) %] + Brief display + [% ELSE %] + More details + [% END %] -
            - [% IF ( verbose ) %] - Brief display - [% ELSE %] - More details + Send +
            + Download + +
            + Print + Empty and close + Hide window +
            + + [% IF ( verbose ) %] + [% PROCESS controls %] +
            + [% FOREACH BIBLIO_RESULT IN BIBLIO_RESULTS %] +

            + + [% INCLUDE 'biblio-title.inc' biblio=BIBLIO_RESULT %] + [% IF ( BIBLIO_RESULT.author ) %][% BIBLIO_RESULT.author | html %][% END %] +

            + + + +
            + + [% IF ( BIBLIO_RESULT.isbn ) %] + + + + [% END %] - Send -
            - Download - -
            - Print - Empty and close - Hide window - + [% IF ( BIBLIO_RESULT.HASAUTHORS ) %] + + + + + [% END %] + [% IF ( BIBLIO_RESULT.publishercode ) %] + + + + + [% END %] - [% IF ( verbose ) %] - [% PROCESS controls %] - - [% FOREACH BIBLIO_RESULT IN BIBLIO_RESULTS %] -

            - - [% INCLUDE 'biblio-title.inc' biblio=BIBLIO_RESULT %] - [% IF ( BIBLIO_RESULT.author ) %] [% BIBLIO_RESULT.author | html %][% END %] -

            + [% IF ( BIBLIO_RESULT.pages ) %] + + + + + [% END %] + + [% IF ( BIBLIO_RESULT.seriestitle ) %] + + + + + [% END %] + + [% IF ( BIBLIO_RESULT.MARCSUBJCTS ) %] + + + + + [% END %] + + [% IF ( BIBLIO_RESULT.copyrightdate ) %] + + + + [% END %] + + [% IF ( BIBLIO_RESULT.MARCNOTES ) %] + + + + + [% END %] + + [% IF ( BIBLIO_RESULT.unititle ) %] + + + + + [% END %] + + [% IF ( BIBLIO_RESULT.serial ) %] + + + + + [% END %] + + [% IF ( BIBLIO_RESULT.dewey ) %] + + + + + [% END %] + + [% IF ( BIBLIO_RESULT.classification ) %] + + + + + [% END %] + + [% IF ( BIBLIO_RESULT.lccn ) %] + + + + + [% END %] + + [% IF BIBLIO_RESULT.MARCURLS.size %] + + + + + [% END %] + + [% IF BIBLIO_RESULT.HOSTITEMENTRIES || BIBLIO_RESULT.HOSTINFO %] + + + + + [% END %] + + + + + +
            ISBN[% BIBLIO_RESULT.isbn | html %]
            Author(s) + [% IF ( BIBLIO_RESULT.author ) %] +

            [% BIBLIO_RESULT.author | html %]

            + [% END %] + [% IF ( BIBLIO_RESULT.MARCAUTHORS ) %] + [% FOREACH MARCAUTHOR IN BIBLIO_RESULT.MARCAUTHORS %] +

            + [% FOREACH MARCAUTHOR_SUBFIELDS_LOO IN MARCAUTHOR.MARCAUTHOR_SUBFIELDS_LOOP %] + [% MARCAUTHOR_SUBFIELDS_LOO.separator | html %] + [% MARCAUTHOR_SUBFIELDS_LOO.value | html %] + [% END %] +

            + [% END %] + [% END %] +
            Publisher[% BIBLIO_RESULT.place | html %] [% BIBLIO_RESULT.publishercode | html %] [% BIBLIO_RESULT.publicationyear | html %]
            Details[% BIBLIO_RESULT.pages | html %] [% BIBLIO_RESULT.illus | html %] [% BIBLIO_RESULT.item('size') | html %]
            Collection [% BIBLIO_RESULT.seriestitle | html %]
            Subject(s) + [% FOREACH MARCSUBJCT IN BIBLIO_RESULT.MARCSUBJCTS %] +

            + [% FOREACH MARCSUBJECT_SUBFIELDS_LOO IN MARCSUBJCT.MARCSUBJECT_SUBFIELDS_LOOP %] + [% MARCSUBJECT_SUBFIELDS_LOO.separator | html %][% MARCSUBJECT_SUBFIELDS_LOO.value | html %] + [% END %] +

            + [% END %] +
            Copyright [% BIBLIO_RESULT.copyrightdate | html %]
            Notes + [% FOREACH MARCNOTE IN BIBLIO_RESULT.MARCNOTES %] +

            + [% IF MARCNOTE.marcnote.match('^https?://\S+$') %] + - [% MARCNOTE.marcnote | html %] + [% ELSE %] + - [% MARCNOTE.marcnote | html %] + [% END %] +

            + [% END %] +
            Unified title [% BIBLIO_RESULT.unititle | html %]
            Serial[% BIBLIO_RESULT.serial | html %]
            Dewey[% BIBLIO_RESULT.dewey | html %]
            Classification [% BIBLIO_RESULT.classification | html %]
            LCCN [% BIBLIO_RESULT.lccn | html %]
            URL(s) + [% FOREACH MARCurl IN BIBLIO_RESULT.MARCURLS %] + [% IF MARCurl.part %]

            [% MARCurl.part | html %]

            [% END %] + [% MARCurl.linktext | html %] + [% IF MARCurl.notes %] + [% FOREACH note IN MARCurl.notes %] +

            [% note.note | html %]

            + [% END %] + [% END %] + [% END %] +
            In + [% IF BIBLIO_RESULT.HOSTITEMENTRIES %] +

            [% INCLUDE 'biblio-title.inc' link = 1 biblio=BIBLIO_RESULT.HOSTITEMENTRIES %] [% BIBLIO_RESULT.RELATEDPARTS | html %]

            + [% ELSE %] +

            [% BIBLIO_RESULT.HOSTINFO | html %]

            + [% END %] +
            Location(s) + [% IF BIBLIO_RESULT.ITEM_RESULTS.count %] + [% FOREACH ITEM_RESULT IN BIBLIO_RESULT.ITEM_RESULTS %] +

            + [% Branches.GetName(ITEM_RESULT.holdingbranch) | html %] + [% AuthorisedValues.GetDescriptionByKohaField( kohafield => 'items.location', authorised_value => ITEM_RESULT.location ) | html %] + [% IF ( ITEM_RESULT.itemcallnumber ) %] + ([% ITEM_RESULT.itemcallnumber | html %]) + [% END %] +

            + [% END %] + [% ELSE %] + This record has no items. + [% END %] +
            +
            + [% END # /FOREACH BIBLIO_RESULT %] +
            + [%# /bookbag_form %] + [% ELSE # IF verbose %] +
            + [% PROCESS controls %] + +
            + + + + + + + + + + + [% FOREACH BIBLIO_RESULT IN BIBLIO_RESULTS %] + + + + + + + [% END # /FOREACH BIBLIO_RESULT %] +
             TitleItem type + Items +
            + + + [% INCLUDE 'biblio-title.inc' biblio=BIBLIO_RESULT link = 1 %] + [% BIBLIO_RESULT.author | html %] +

            + [% IF ( BIBLIO_RESULT.publishercode ) %] + - [% BIBLIO_RESULT.publishercode | html %] + [% IF ( BIBLIO_RESULT.place ) %] + [% BIBLIO_RESULT.place | html %] + [% END %] + [% END %] + [% IF ( BIBLIO_RESULT.pages ) %] + - [% BIBLIO_RESULT.pages | html %] + [% IF ( BIBLIO_RESULT.item('size') ) %] + [% BIBLIO_RESULT.item('size') | html %] + [% END %] + [% END %] +

            + [% IF ( BIBLIO_RESULT.notes ) %] +

            [% BIBLIO_RESULT.notes | html %]

            + [% END %] + [% IF BIBLIO_RESULT.HOSTITEMENTRIES || BIBLIO_RESULT.HOSTINFO %] +

            In: + [% IF BIBLIO_RESULT.HOSTITEMENTRIES %] + [% INCLUDE 'biblio-title.inc' link = 1 biblio=BIBLIO_RESULT.HOSTITEMENTRIES %] + [% BIBLIO_RESULT.RELATEDPARTS | html %] + [% ELSE %] + [% BIBLIO_RESULT.HOSTINFO | html %] + [% END %] +

            + [% END %] - + +
            [% BIBLIO_RESULT.description | html %] + [% IF ( BIBLIO_RESULT.ITEM_RESULTS ) %] + [% FOREACH ITEM_RESULT IN BIBLIO_RESULT.ITEM_RESULTS %] +
            + + + [% ITEM_RESULT.itemcallnumber | html %] + + [% Branches.GetName(ITEM_RESULT.holdingbranch) | html %] + [% AuthorisedValues.GetDescriptionByKohaField( kohafield => 'items.location', authorised_value => ITEM_RESULT.location ) | html %] + +
            + [% END %] + [% ELSE %] + This record has no items. + [% END %] +
            +
            +
            + [% END # /IF verbose %] -
            - - [% IF ( BIBLIO_RESULT.isbn ) %] - - - - - [% END %] + + + + +[%# /.container %] - [% IF ( BIBLIO_RESULT.HASAUTHORS ) %] - - - - - [% END %] +[% INCLUDE 'intranet-bottom.inc' popup_window=1 %] +[% INCLUDE 'datatables.inc' %] +[% Asset.js("js/cart.js") | $raw %] - [% IF ( BIBLIO_RESULT.publishercode ) %] - - - - - [% END %] - - [% IF ( BIBLIO_RESULT.pages ) %] - - - - - [% END %] - - [% IF ( BIBLIO_RESULT.seriestitle ) %] - - - - - [% END %] - - [% IF ( BIBLIO_RESULT.MARCSUBJCTS ) %] - - - - - [% END %] - - [% IF ( BIBLIO_RESULT.copyrightdate ) %] - - - - [% END %] - - [% IF ( BIBLIO_RESULT.MARCNOTES ) %] - - - - - [% END %] - - [% IF ( BIBLIO_RESULT.unititle ) %] - - - - - [% END %] - - [% IF ( BIBLIO_RESULT.serial ) %] - - - - - [% END %] - - [% IF ( BIBLIO_RESULT.dewey ) %] - - - - - [% END %] - - [% IF ( BIBLIO_RESULT.classification ) %] - - - - - [% END %] - - [% IF ( BIBLIO_RESULT.lccn ) %] - - - - - [% END %] - - - [% IF BIBLIO_RESULT.MARCURLS.size %] - - - - - [% END %] - - [% IF BIBLIO_RESULT.HOSTITEMENTRIES || BIBLIO_RESULT.HOSTINFO %] - - - - - [% END %] - - - - - -
            ISBN[% BIBLIO_RESULT.isbn | html %]
            Author(s) - [% IF ( BIBLIO_RESULT.author ) %] -

            [% BIBLIO_RESULT.author | html %]

            - [% END %] - [% IF ( BIBLIO_RESULT.MARCAUTHORS ) %] - [% FOREACH MARCAUTHOR IN BIBLIO_RESULT.MARCAUTHORS %] -

            - [% FOREACH MARCAUTHOR_SUBFIELDS_LOO IN MARCAUTHOR.MARCAUTHOR_SUBFIELDS_LOOP %] - [% MARCAUTHOR_SUBFIELDS_LOO.separator | html %] - [% MARCAUTHOR_SUBFIELDS_LOO.value | html %] - [% END %] -

            - [% END %] - [% END %] -
            Publisher[% BIBLIO_RESULT.place | html %] [% BIBLIO_RESULT.publishercode | html %] [% BIBLIO_RESULT.publicationyear | html %] -
            Details[% BIBLIO_RESULT.pages | html %] [% BIBLIO_RESULT.illus | html %] [% BIBLIO_RESULT.item('size') | html %]
            Collection [% BIBLIO_RESULT.seriestitle | html %]
            Subject(s) - [% FOREACH MARCSUBJCT IN BIBLIO_RESULT.MARCSUBJCTS %] -

            - [% FOREACH MARCSUBJECT_SUBFIELDS_LOO IN MARCSUBJCT.MARCSUBJECT_SUBFIELDS_LOOP %] - [% MARCSUBJECT_SUBFIELDS_LOO.separator | html %][% MARCSUBJECT_SUBFIELDS_LOO.value | html %] - [% END %] -

            - [% END %] -
            Copyright [% BIBLIO_RESULT.copyrightdate | html %]
            Notes - [% FOREACH MARCNOTE IN BIBLIO_RESULT.MARCNOTES %] -

            - [% IF MARCNOTE.marcnote.match('^https?://\S+$') %] - - [% MARCNOTE.marcnote | html %] - [% ELSE %] - - [% MARCNOTE.marcnote | html %] - [% END %] - [% END %] -

            Unified title [% BIBLIO_RESULT.unititle | html %]
            Serial[% BIBLIO_RESULT.serial | html %]
            Dewey[% BIBLIO_RESULT.dewey | html %]
            Classification [% BIBLIO_RESULT.classification | html %]
            LCCN [% BIBLIO_RESULT.lccn | html %]
            URL(s) - [% FOREACH MARCurl IN BIBLIO_RESULT.MARCURLS %] - [% IF MARCurl.part %]

            [% MARCurl.part | html %]

            [% END %] - [% MARCurl.linktext | html %] - [% IF MARCurl.notes %] - [% FOREACH note IN MARCurl.notes %] -

            [% note.note | html %]

            - [% END %] - [% END %] - [% END %] -
            In - [% IF BIBLIO_RESULT.HOSTITEMENTRIES %] -

            [% INCLUDE 'biblio-title.inc' link = 1 biblio=BIBLIO_RESULT.HOSTITEMENTRIES %] [% BIBLIO_RESULT.RELATEDPARTS | html %]

            - [% ELSE %] -

            [% BIBLIO_RESULT.HOSTINFO | html %]

            - [% END %] -
            Location(s) - [% IF BIBLIO_RESULT.ITEM_RESULTS.count %] - [% FOREACH ITEM_RESULT IN BIBLIO_RESULT.ITEM_RESULTS %] -

            - [% Branches.GetName(ITEM_RESULT.holdingbranch) | html %] - - [% AuthorisedValues.GetDescriptionByKohaField( kohafield => 'items.location', authorised_value => ITEM_RESULT.location ) | html %] - - [% IF ( ITEM_RESULT.itemcallnumber ) %] - ([% ITEM_RESULT.itemcallnumber | html %]) - [% END %] -

            - [% END %] - [% ELSE %] - This record has no items. - [% END %] -
            -
            - [% END # /FOREACH BIBLIO_RESULT %] - [%# /bookbag_form %] - - [% ELSE # IF verbose %] - -
            - [% PROCESS controls %] - -
            - - - - - - - - - - - [% FOREACH BIBLIO_RESULT IN BIBLIO_RESULTS %] - - - - - - - [% END # /FOREACH BIBLIO_RESULT %] -
             TitleItem type - Items -
            - - - [% INCLUDE 'biblio-title.inc' biblio=BIBLIO_RESULT link = 1 %] - [% BIBLIO_RESULT.author | html %] -

            - [% IF ( BIBLIO_RESULT.publishercode ) %] - - [% BIBLIO_RESULT.publishercode | html %] - [% IF ( BIBLIO_RESULT.place ) %] - [% BIBLIO_RESULT.place | html %] - [% END %] - [% END %] - [% IF ( BIBLIO_RESULT.pages ) %] - - [% BIBLIO_RESULT.pages | html %] - [% IF ( BIBLIO_RESULT.item('size') ) %] - [% BIBLIO_RESULT.item('size') | html %] - [% END %] - [% END %] -

            - [% IF ( BIBLIO_RESULT.notes ) %] -

            [% BIBLIO_RESULT.notes | html %]

            - [% END %] - [% IF BIBLIO_RESULT.HOSTITEMENTRIES || BIBLIO_RESULT.HOSTINFO %] -

            In: - [% IF BIBLIO_RESULT.HOSTITEMENTRIES %] - [% INCLUDE 'biblio-title.inc' link = 1 biblio=BIBLIO_RESULT.HOSTITEMENTRIES %] [% BIBLIO_RESULT.RELATEDPARTS | html %] - [% ELSE %] - [% BIBLIO_RESULT.HOSTINFO | html %] - [% END %] -

            - [% END %] - - -
            [% BIBLIO_RESULT.description | html %] - [% IF ( BIBLIO_RESULT.ITEM_RESULTS ) %] - [% FOREACH ITEM_RESULT IN BIBLIO_RESULT.ITEM_RESULTS %] -
            - - - [% ITEM_RESULT.itemcallnumber | html %] - - [% Branches.GetName(ITEM_RESULT.holdingbranch) | html %] - - [% AuthorisedValues.GetDescriptionByKohaField( kohafield => 'items.location', authorised_value => ITEM_RESULT.location ) | html %] - - -
            - [% END %] - [% ELSE %] - This record has no items. - [% END %] -
            -
            -
            - [% END # /IF verbose %] - -
            - -
            - -
            [%# /.container %] - - [% INCLUDE 'intranet-bottom.inc' popup_window=1 %] - [% INCLUDE 'datatables.inc' %] - [% Asset.js("js/cart.js") | $raw %] - - + diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/basket/downloadcart.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/basket/downloadcart.tt index 8845abedb0..09fe80fc5c 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/basket/downloadcart.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/basket/downloadcart.tt @@ -1,39 +1,41 @@ [% USE raw %] [% PROCESS 'i18n.inc' %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Download cart") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Download cart") | html %] + › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] [% IF ( format ) %]

            Your download should begin automatically.

            [% ELSE %] -
            -
            - Download cart -
            1. - -
            2. -
            -
            -
            - - Cancel -
            + +
            + Download cart +
            1. + +
            2. +
            +
            +
            + + Cancel +
            - [% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/basket/sendbasketform.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/basket/sendbasketform.tt index 36b62d240c..5edd03c7e3 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/basket/sendbasketform.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/basket/sendbasketform.tt @@ -1,65 +1,68 @@ [% USE raw %] [% PROCESS 'i18n.inc' %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Sending your cart") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Sending your cart") | html %] + › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] -
            [% IF ( email_add ) %] +
            [% IF ( email_add ) %] - [% IF ( SENT ) %] -
            -

            Message sent

            -

            The cart was sent to: [% email_add | html %]

            -
            - [% END %] - [% IF ( error ) %] -
            Problem sending the cart...
            - [% END %] + [% IF ( SENT ) %] +
            +

            Message sent

            +

            The cart was sent to: [% email_add | html %]

            +
            + [% END %] + [% IF ( error ) %] +
            Problem sending the cart...
            + [% END %] - + + [% INCLUDE 'csrf-token.inc' %] -[% ELSE %] - -[% INCLUDE 'blocking_errors.inc' %] - -

            Sending your cart

            -
            -Enter message details -
            1. - - -
            2. -
            3. - - -
            4. -
            -
            - - [% INCLUDE 'csrf-token.inc' %] - - - - -[% END %]
            + + + [% END %]
            diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/batch/print-notices.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/batch/print-notices.tt index 322ab172dc..d7ccd43ea5 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/batch/print-notices.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/batch/print-notices.tt @@ -1,12 +1,14 @@ [% USE raw %] [% PROCESS 'i18n.inc' %] [% INCLUDE 'doc-head-open.inc' %] - [% FILTER collapse %] +<title + >[% FILTER collapse %] [% tx("Print notices for {today}", { today = today }) | html %] - [% END %] + [% END %] - - + + - [% IF ( stylesheet ) %] - - [% END %] +[% IF ( stylesheet ) %] + +[% END %] - [% FOREACH message IN messages %] +[% FOREACH message IN messages %]
            [% IF ( message.is_html ) %] [% message.content | $raw %] @@ -31,7 +33,7 @@
            [% message.content | $raw %]
            [% END %]
            - [% END %] +[% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/bookings/list.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/bookings/list.tt index ef67c8ca20..54a6853922 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/bookings/list.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/bookings/list.tt @@ -5,20 +5,20 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Bookings") | html %] › - [% INCLUDE 'biblio-title-head.inc' %] › - [% t("Catalog") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Bookings") | html %] + › [% INCLUDE 'biblio-title-head.inc' %] › [% t("Catalog") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] - + } + @@ -42,23 +42,23 @@ [% END #/ WRAPPER sub-header.inc %] [% WRAPPER 'main-container.inc' aside='biblio-view-menu' %] -
            - [% INCLUDE 'cat-toolbar.inc' %] -

            Bookings for [% INCLUDE 'biblio-title-head.inc' %]

            -
            -
            -
            - Show expired - Show cancelled -
            +
            + [% INCLUDE 'cat-toolbar.inc' %] +

            Bookings for [% INCLUDE 'biblio-title-head.inc' %]

            +
            + -
            +
            +
            +
            [% END %] - [% INCLUDE modals/cancel_booking.inc %] +[% INCLUDE modals/cancel_booking.inc %] - [% MACRO jsinclude BLOCK %] +[% MACRO jsinclude BLOCK %] [% Asset.js("lib/vis-timeline/vis-timeline-graph2d.min.js") | $raw %] [% INCLUDE 'datatables.inc' %] [% INCLUDE 'columns_settings.inc' %] @@ -68,368 +68,372 @@ [% INCLUDE 'js-date-format.inc' %] [% Asset.js("lib/dayjs/plugin/isSameOrAfter.js") | $raw %] [% Asset.js("lib/dayjs/plugin/isSameOrBefore.js") | $raw %] - - + + [% Asset.js("js/modals/place_booking.js") | $raw %] [% Asset.js("js/cancel_booking_modal.js") | $raw %] [% Asset.js("js/combobox.js") | $raw %] - - [% END %] + $.when(items, bookings).then( + function(items, bookings){ + var itemsSet = new vis.DataSet([{ + id: 0, + content: _("Record level") + }]); + for (item of items[0]) { + itemsSet.add({ + id: item.item_id, + content: _("Item %s").format(item.external_id), + }); + } + + var bookingsSet = new vis.DataSet(); + for (booking of bookings[0]){ + const isActive = ["new", "pending", "active"].includes(booking.status); + const patronContent = $patron_to_html(booking.patron, { + display_cardnumber: true, + url: false + }); + bookingsSet.add({ + id: booking.booking_id, + booking: booking.booking_id, + patron: booking.patron_id, + pickup_library: booking.pickup_library_id, + start: dayjs(booking.start_date).toDate(), + end: dayjs(booking.end_date).toDate(), + content: !isActive ? `${patronContent}` : patronContent, + [% IF CAN_user_circulate_manage_bookings %] + editable: booking.status !== "cancelled" ? { remove: true, updateTime: true } : false, + [% ELSE %] + editable: false, + [% END %] + type: 'range', + group: booking.item_id ?? 0, + }); + } + + const cancelledItems = document.querySelectorAll('#bookings-timeline .vis-item.vis-range.cancelled'); + cancelledItems.forEach(item => { + item.style.background = 'repeating-linear-gradient(' + + '135deg,' + + 'rgba(211, 211, 211, 0.5) 0,' + + 'rgba(211, 211, 211, 0.5) 10px,' + + 'transparent 10px,' + + 'transparent 20px' + + ');'; + }); + + var container = document.getElementById('bookings-timeline'); + var options = { + stack: true, + verticalScroll: true, + orientation: { + axis: "both", + item: "top" + }, + timeAxis: {scale: 'day', step: 1}, + dataAttributes: [ 'booking' ], + + // always snap to full days, independent of the scale + snap: function (date, scale, step) { + let offset = date.getTimezoneOffset() * 60 * 1000; + let day = 24 * 60 * 60 * 1000; + let seconds = Math.round(date / day) * day; + return seconds + offset; + }, + + // prevent overlapping bookings + onMoving: function (item, callback) { + var overlapping = bookingsSet.get({ + filter: function(testItem) { + if (testItem.id == item.id) { + return false; + } + if (testItem.group != item.group) { + return false; + } + return ((item.start < testItem.end) && (item.end > testItem.start)); + } + }); + + if (overlapping.length == 0) { + callback(item); + } + }, + + // action events + onMove: function (data, callback) { + let startDate = dayjs(data.start); + + // set end datetime hours and minutes to the end of the day + let endDate = dayjs(data.end).endOf('day'); + + $('#placeBookingModal').modal('show', $(''.format(row.booking_id, biblionumber, row.item_id, row.patron_id, row.pickup_library_id, row.start_date, row.end_date, _("Edit")); + result += ''.format(row.booking_id, _("Cancel")); + } + [% END %] + return result; + } + }] + }, undefined, 0, additional_filters); + + document + .getElementById("expired_filter") + .addEventListener("click", (e) => + handleFilter( + e, + { active: _("Hide expired"), inactive: _("Show expired") }, + filterStates, + ), + ); + + document + .getElementById("cancelled_filter") + .addEventListener("click", (e) => + handleFilter( + e, + { active: _("Hide cancelled"), inactive: _("Show cancelled") }, + filterStates, + ), + ); + + $("#cancellation-reason").comboBox({ + displayProperty: 'name', + placeholder: _("Select or type a reason"), + }); + + function handleFilter(e, text, filterStates) { + const target = e.target; + const { filter } = target.dataset; + if (target.classList.contains("filtered")) { + filterStates[filter] = false; + target.innerHTML = ` ${text.inactive}`; + } else { + filterStates[filter] = true; + target.innerHTML = ` ${text.active}`; + } + + bookings_table.DataTable().ajax.reload(() => { + bookings_table + .DataTable() + .column("status:name") + .visible(filterStates[filter], false); + }); + + target.classList.toggle("filtered"); + } + }); + +[% END %] [% INCLUDE 'intranet-bottom.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/catalogue/ISBDdetail.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/catalogue/ISBDdetail.tt index b9e805cf30..8fdd39fb2c 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/catalogue/ISBDdetail.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/catalogue/ISBDdetail.tt @@ -4,16 +4,17 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% IF ( unknownbiblionumber ) %] - [% t("Unknown record") | html %] - [% ELSE %] - [% title_in_title = INCLUDE 'biblio-title-head.inc' %] - [% tx("ISBD details for {title}", { title = title_in_title }) | html %] - [% END %] › - [% t("Catalog") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% IF ( unknownbiblionumber ) %] + [% t("Unknown record") | html %] + [% ELSE %] + [% title_in_title = INCLUDE 'biblio-title-head.inc' %] + [% tx("ISBD details for {title}", { title = title_in_title }) | html %] + [% END %] + › [% t("Catalog") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -44,41 +45,43 @@ [% END #/ WRAPPER sub-header.inc %] [% WRAPPER 'main-container.inc' aside='biblio-view-menu' %] - [% INCLUDE 'cat-toolbar.inc' %] -

            - [% IF ( unknownbiblionumber ) %] - Unknown record - [% ELSE %] - ISBD details for [% INCLUDE 'biblio-title-head.inc' %] - [% END %] -

            + [% INCLUDE 'cat-toolbar.inc' %] +

            + [% IF ( unknownbiblionumber ) %] + Unknown record + [% ELSE %] + ISBD details for [% INCLUDE 'biblio-title-head.inc' %] + [% END %] +

            - [% IF ( unknownbiblionumber ) %] -
            The record you requested does not exist ([% biblionumber | html %]).
            - [% ELSE %] + [% IF ( unknownbiblionumber ) %] +
            The record you requested does not exist ([% biblionumber | html %]).
            + [% ELSE %] - [% IF ( ocoins ) %] - - - [% END %] + [% IF ( ocoins ) %] + + + [% END %] -
            - [% ISBD | $raw %] -
            - [% END %] +
            [% ISBD | $raw %]
            + [% END %] [% END %] - [% IF ( Koha.Preference('CatalogConcerns') ) %] +[% IF ( Koha.Preference('CatalogConcerns') ) %] [% INCLUDE 'modals/add_catalog_concern.inc' %] - [% END %] +[% END %] [% MACRO jsinclude BLOCK %] [% INCLUDE 'catalog-strings.inc' %] [% Asset.js("lib/dayjs/dayjs.min.js") | $raw %] [% Asset.js("lib/dayjs/plugin/isSameOrAfter.js") | $raw %] [% Asset.js("lib/dayjs/plugin/isSameOrBefore.js") | $raw %] - - + + [% INCLUDE 'calendar.inc' %] [% INCLUDE 'select2.inc' %] [% Asset.js("js/catalog.js") | $raw %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/catalogue/MARCdetail.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/catalogue/MARCdetail.tt index 3460073174..0b7138a255 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/catalogue/MARCdetail.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/catalogue/MARCdetail.tt @@ -4,16 +4,17 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% IF ( unknownbiblionumber ) %] - [% t("Unknown record") | html %] - [% ELSE %] - [% title_in_title = INCLUDE 'biblio-title-head.inc' %] - [% tx("MARC details for {title}", { title = title_in_title }) | html %] - [% END %] › - [% t("Catalog") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% IF ( unknownbiblionumber ) %] + [% t("Unknown record") | html %] + [% ELSE %] + [% title_in_title = INCLUDE 'biblio-title-head.inc' %] + [% tx("MARC details for {title}", { title = title_in_title }) | html %] + [% END %] + › [% t("Catalog") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -46,156 +47,165 @@ [% WRAPPER 'main-container.inc' aside='biblio-view-menu' %] -[% INCLUDE 'cat-toolbar.inc' %] + [% INCLUDE 'cat-toolbar.inc' %] -[% UNLESS ( popup ) %] -

            MARC record: [% biblionumber | html %] ( [% bibliotitle | html %] )

            -[% END %] - -

            With framework :

            -[% IF ( ocoins ) %] - - -[% END %] - - -[% BLOCK show_tab_html %] - [% WRAPPER tab_panel tabname="${ tab_id }" %] - [% FOREACH tab0X IN tab_data %] -
            - [% IF ( tab0X.tag ) %] -
            - [% tab0X.tag | html %] - [% IF ( tab0X.tag_ind ) %] - [% tab0X.tag_ind.substr(0, 1) | html %][% tab0X.tag_ind.substr(1, 1) | html %] - [% END %] - [% IF (tab0X.tag_desc) %] - [% tab0X.tag_desc | html %][% END %] -
            - [% END %] - [% FOREACH subfiel IN tab0X.subfield %] -

            -   - [% UNLESS ( subfiel.hide_marc ) %][% subfiel.marc_subfield | html %][% END %] - [% subfiel.short_desc | html %] - [% IF ( subfiel.is_url ) %][% subfiel.marc_value | html %][% ELSE %][% subfiel.marc_value | html %][% END %] - [% IF ( subfiel.link ) %] - - - - [% END %] - [% IF ( subfiel.authority ) %] - - - - [% END %] -

            - [% END %] -
            - [% END %] - [% END # /tab_panel#tab${tab_id} %] -[% END %] - - [% WRAPPER tabs id= "bibliotabs" %] - [% WRAPPER tabs_nav %] - [% IF ( tab0XX ) %] - [% WRAPPER tab_item tabname= "tab0XX" %] 0 [% END %] - [% END %] - [% IF ( tab1XX ) %] - [% WRAPPER tab_item tabname= "tab1XX" %] 1 [% END %] - [% END %] - [% IF ( tab2XX ) %] - [% WRAPPER tab_item tabname= "tab2XX" %] 2 [% END %] - [% END %] - [% IF ( tab3XX ) %] - [% WRAPPER tab_item tabname= "tab3XX" %] 3 [% END %] - [% END %] - [% IF ( tab4XX ) %] - [% WRAPPER tab_item tabname= "tab4XX" %] 4 [% END %] - [% END %] - [% IF ( tab5XX ) %] - [% WRAPPER tab_item tabname= "tab5XX" %] 5 [% END %] - [% END %] - [% IF ( tab6XX ) %] - [% WRAPPER tab_item tabname= "tab6XX" %] 6 [% END %] - [% END %] - [% IF ( tab7XX ) %] - [% WRAPPER tab_item tabname= "tab7XX" %] 7 [% END %] - [% END %] - [% IF ( tab8XX ) %] - [% WRAPPER tab_item tabname= "tab8XX" %] 8 [% END %] - [% END %] - [% IF ( tab9XX ) %] - [% WRAPPER tab_item tabname= "tab9XX" %] 9 [% END %] - [% END %] - [% IF ( tab10XX ) %] - [% WRAPPER tab_item tabname= "tab10XX" %] Item(s) [% END %] - [% END %] - [% END # /WRAPPER tabs_nav %] - - [% WRAPPER tab_panels %] - [% PROCESS show_tab_html tab_id="tab0XX" tab_data=tab0XX %] - - [% PROCESS show_tab_html tab_id="tab1XX" tab_data=tab1XX %] - - [% PROCESS show_tab_html tab_id="tab2XX" tab_data=tab2XX %] - - [% PROCESS show_tab_html tab_id="tab3XX" tab_data=tab3XX %] - - [% PROCESS show_tab_html tab_id="tab4XX" tab_data=tab4XX %] - - [% PROCESS show_tab_html tab_id="tab5XX" tab_data=tab5XX %] - - [% PROCESS show_tab_html tab_id="tab6XX" tab_data=tab6XX %] - - [% PROCESS show_tab_html tab_id="tab7XX" tab_data=tab7XX %] - - [% PROCESS show_tab_html tab_id="tab8XX" tab_data=tab8XX %] - - [% PROCESS show_tab_html tab_id="tab9XX" tab_data=tab9XX %] - - [% IF ( tab10XX ) %] - [% WRAPPER tab_panel tabname="tab10XX" %] - - - [% FOREACH header IN item_header_loop %] - - [% END %] - - [% FOREACH item IN item_loop %] - - [% FOREACH sf_code IN item_subfield_codes %] - - [% END %] - - [% END %] -
            [% header | html %]
            [% item.$sf_code | $raw %]
            - [% END # /tab_panel#tab10XX %] - [% END # /IF tab10XX %] - [% END # /tab_panels %] - [% END # /WRAPPER tabs %] - -[% END %] - - [% IF ( Koha.Preference('CatalogConcerns') ) %] - [% INCLUDE 'modals/add_catalog_concern.inc' %] + [% UNLESS ( popup ) %] +

            MARC record: [% biblionumber | html %] ( [% bibliotitle | html %] )

            [% END %] +

            With framework : + +

            + [% IF ( ocoins ) %] + + + [% END %] + + [% BLOCK show_tab_html %] + [% WRAPPER tab_panel tabname="${ tab_id }" %] + [% FOREACH tab0X IN tab_data %] +
            + [% IF ( tab0X.tag ) %] +
            + [% tab0X.tag | html %] + [% IF ( tab0X.tag_ind ) %] + [% tab0X.tag_ind.substr(0, 1) | html %][% tab0X.tag_ind.substr(1, 1) | html %] + [% END %] + [% IF (tab0X.tag_desc) %] - [% tab0X.tag_desc | html %][% END %] +
            + [% END %] + [% FOREACH subfiel IN tab0X.subfield %] +

            +   [% UNLESS ( subfiel.hide_marc ) %][% subfiel.marc_subfield | html %][% END %] + [% subfiel.short_desc | html %] + [% IF ( subfiel.is_url ) %][% subfiel.marc_value | html %][% ELSE %][% subfiel.marc_value | html %][% END %] + [% IF ( subfiel.link ) %] + + + + [% END %] + [% IF ( subfiel.authority ) %] + + + + [% END %] +

            + [% END %] +
            + + [% END %] + [% END # /tab_panel#tab${tab_id} %] + [% END %] + + [% WRAPPER tabs id= "bibliotabs" %] + [% WRAPPER tabs_nav %] + [% IF ( tab0XX ) %] + [% WRAPPER tab_item tabname= "tab0XX" %]0[% END %] + [% END %] + [% IF ( tab1XX ) %] + [% WRAPPER tab_item tabname= "tab1XX" %]1[% END %] + [% END %] + [% IF ( tab2XX ) %] + [% WRAPPER tab_item tabname= "tab2XX" %]2[% END %] + [% END %] + [% IF ( tab3XX ) %] + [% WRAPPER tab_item tabname= "tab3XX" %]3[% END %] + [% END %] + [% IF ( tab4XX ) %] + [% WRAPPER tab_item tabname= "tab4XX" %]4[% END %] + [% END %] + [% IF ( tab5XX ) %] + [% WRAPPER tab_item tabname= "tab5XX" %]5[% END %] + [% END %] + [% IF ( tab6XX ) %] + [% WRAPPER tab_item tabname= "tab6XX" %]6[% END %] + [% END %] + [% IF ( tab7XX ) %] + [% WRAPPER tab_item tabname= "tab7XX" %]7[% END %] + [% END %] + [% IF ( tab8XX ) %] + [% WRAPPER tab_item tabname= "tab8XX" %]8[% END %] + [% END %] + [% IF ( tab9XX ) %] + [% WRAPPER tab_item tabname= "tab9XX" %]9[% END %] + [% END %] + [% IF ( tab10XX ) %] + [% WRAPPER tab_item tabname= "tab10XX" %]Item(s)[% END %] + [% END %] + [% END # /WRAPPER tabs_nav %] + + [% WRAPPER tab_panels %] + [% PROCESS show_tab_html tab_id="tab0XX" tab_data=tab0XX %] + + [% PROCESS show_tab_html tab_id="tab1XX" tab_data=tab1XX %] + + [% PROCESS show_tab_html tab_id="tab2XX" tab_data=tab2XX %] + + [% PROCESS show_tab_html tab_id="tab3XX" tab_data=tab3XX %] + + [% PROCESS show_tab_html tab_id="tab4XX" tab_data=tab4XX %] + + [% PROCESS show_tab_html tab_id="tab5XX" tab_data=tab5XX %] + + [% PROCESS show_tab_html tab_id="tab6XX" tab_data=tab6XX %] + + [% PROCESS show_tab_html tab_id="tab7XX" tab_data=tab7XX %] + + [% PROCESS show_tab_html tab_id="tab8XX" tab_data=tab8XX %] + + [% PROCESS show_tab_html tab_id="tab9XX" tab_data=tab9XX %] + + [% IF ( tab10XX ) %] + [% WRAPPER tab_panel tabname="tab10XX" %] + + + [% FOREACH header IN item_header_loop %] + + [% END %] + + [% FOREACH item IN item_loop %] + + [% FOREACH sf_code IN item_subfield_codes %] + + [% END %] + + [% END %] +
            [% header | html %]
            [% item.$sf_code | $raw %]
            + [% END # /tab_panel#tab10XX %] + [% END # /IF tab10XX %] + [% END # /tab_panels %] + [% END # /WRAPPER tabs %] +[% END %] + +[% IF ( Koha.Preference('CatalogConcerns') ) %] + [% INCLUDE 'modals/add_catalog_concern.inc' %] +[% END %] + [% MACRO jsinclude BLOCK %] [% INCLUDE 'catalog-strings.inc' %] [% Asset.js("lib/dayjs/dayjs.min.js") | $raw %] [% Asset.js("lib/dayjs/plugin/isSameOrAfter.js") | $raw %] [% Asset.js("lib/dayjs/plugin/isSameOrBefore.js") | $raw %] - - + + [% INCLUDE 'calendar.inc' %] [% INCLUDE 'select2.inc' %] [% Asset.js("js/catalog.js") | $raw %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/catalogue/advsearch.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/catalogue/advsearch.tt index df2a041c10..c9b603d563 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/catalogue/advsearch.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/catalogue/advsearch.tt @@ -5,11 +5,12 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Advanced search") | html %] › - [% t("Catalog") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Advanced search") | html %] + › [% t("Catalog") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -18,13 +19,9 @@ [% FOREACH ln_loo IN ln_loop %] [% IF ( ln_loo.selected or selected == ln_loo.iso639_2_code ) %] - + [% ELSE %] - + [% END %] [% END %] @@ -44,98 +41,98 @@ [% END #/ WRAPPER sub-header.inc %] [% WRAPPER 'main-container.inc' %] -
            -
            + +
            + + +
            + +
            + [% ELSE %] -
            There are no images for this record.
            - [% END %] - [% IF ( CAN_user_tools_upload_local_cover_images ) %] -
            -

            - Upload an image file: - [% IF itemnumber %] - [% SET upload_link = '/cgi-bin/koha/tools/upload-cover-image.pl?itemnumber=' _ itemnumber _ '&filetype=image' %] - [% ELSE %] - [% SET upload_link = '/cgi-bin/koha/tools/upload-cover-image.pl?biblionumber=' _ biblionumber _ '&filetype=image' %] - [% END %] - - Upload -

            + [% IF itemnumber %] +
            There are no images for this item.
            + [% ELSE %] +
            There are no images for this record.
            + [% END %] + [% IF ( CAN_user_tools_upload_local_cover_images ) %] +
            +

            + Upload an image file: + [% IF itemnumber %] + [% SET upload_link = '/cgi-bin/koha/tools/upload-cover-image.pl?itemnumber=' _ itemnumber _ '&filetype=image' %] + [% ELSE %] + [% SET upload_link = '/cgi-bin/koha/tools/upload-cover-image.pl?biblionumber=' _ biblionumber _ '&filetype=image' %] + [% END %] + Upload +

            + [% END %] [% END %] + [% ELSE %] +
            Local images have not been enabled by your system administrator.
            [% END %] -[% ELSE %] -
            Local images have not been enabled by your system administrator.
            [% END %] -[% END %] - - [% IF ( Koha.Preference('CatalogConcerns') ) %] +[% IF ( Koha.Preference('CatalogConcerns') ) %] [% INCLUDE 'modals/add_catalog_concern.inc' %] - [% END %] +[% END %] [% MACRO jsinclude BLOCK %] [% INCLUDE 'catalog-strings.inc' %] [% Asset.js("lib/dayjs/dayjs.min.js") | $raw %] [% Asset.js("lib/dayjs/plugin/isSameOrAfter.js") | $raw %] [% Asset.js("lib/dayjs/plugin/isSameOrBefore.js") | $raw %] - - + + [% INCLUDE 'calendar.inc' %] [% INCLUDE 'select2.inc' %] [% Asset.js("js/catalog.js") | $raw %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/catalogue/issuehistory.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/catalogue/issuehistory.tt index 851b721be0..ca95717b7d 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/catalogue/issuehistory.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/catalogue/issuehistory.tt @@ -7,12 +7,13 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% title_in_title = INCLUDE 'biblio-title-head.inc' %] - [% tx("Checkout history for {title}", { title = title_in_title }) | html %] › - [% t("Catalog") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% title_in_title = INCLUDE 'biblio-title-head.inc' %] + [% tx("Checkout history for {title}", { title = title_in_title }) | html %] + › [% t("Catalog") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -37,92 +38,96 @@ [% END #/ WRAPPER sub-header.inc %] [% WRAPPER 'main-container.inc' aside='biblio-view-menu' %] -

            Checkout history for [% INCLUDE 'biblio-title.inc' %]

            -[% IF biblio.author %]

            by [% biblio.author | html %]

            [% END %] +

            Checkout history for [% INCLUDE 'biblio-title.inc' %]

            + [% IF biblio.author %]

            by [% biblio.author | html %]

            [% END %] -[% SET show_patron_column = Koha.Preference('intranetreadinghistory') AND CAN_user_circulate_circulate_remaining_permissions %] + [% SET show_patron_column = Koha.Preference('intranetreadinghistory') AND CAN_user_circulate_circulate_remaining_permissions %] -
            - [% IF checkouts %] -

            Checked out [% checkouts.size | html %] times

            - - - [% IF show_patron_column %] - - [% END %] - - - [% IF Koha.Preference('RecordStaffUserOnCheckout') %] - - [% ELSE %] - - [% END %] - - - - - - - [% SET anonymous_patron_id = Koha.Preference('AnonymousPatron') || 0 %] - [% FOREACH checkout IN checkouts %] - - [% IF show_patron_column %] - -
            PatronBarcodeChecked out fromChecked out byChecked out byRenewedCheckout onDue dateCheckin on
            - [% IF checkout.patron %][%# Not set for deleted patron records %] - [% IF checkout.patron.id == anonymous_patron_id %] - Anonymized - [% ELSE %] - [% INCLUDE 'patron-title.inc' patron => checkout.patron hide_patron_infos_if_needed=1 %] - [% END %] +
            + [% IF checkouts %] +

            Checked out [% checkouts.size | html %] times

            + + + [% IF show_patron_column %] + [% END %] - - [% END %] - - - - + + [% IF Koha.Preference('RecordStaffUserOnCheckout') %] + + [% ELSE %] + + [% END %] + + + + + + + [% SET anonymous_patron_id = Koha.Preference('AnonymousPatron') || 0 %] + [% FOREACH checkout IN checkouts %] + + [% IF show_patron_column %] + [% END %] - [% ELSE %] - No - [% END %] - - - - + + + + + + + + + [% END %] + +
            Patron - [% IF checkout.item.barcode %] [%# FIXME This test is not mandatory I think %] - [% checkout.item.barcode | html %] - [% ELSE %] -   - [% END %][% IF checkout.branchcode %] - [% Branches.GetName( checkout.branchcode ) | html %] - [% ELSE %] -   - [% END %][% IF checkout.issuer_id %] - - [% INCLUDE 'patron-title.inc' patron=checkout.issuer %] - - [% END %][% IF checkout.renewals_count %] - Yes[% IF checkout.lastreneweddate %], last on: [% checkout.lastreneweddate |$KohaDates with_hours => 1 %] + BarcodeChecked out fromChecked out byChecked out byRenewedCheckout onDue dateCheckin on
            + [% IF checkout.patron %] + [%# Not set for deleted patron records %] + [% IF checkout.patron.id == anonymous_patron_id %] + Anonymized + [% ELSE %] + [% INCLUDE 'patron-title.inc' patron => checkout.patron hide_patron_infos_if_needed=1 %] + [% END %] + [% END %] + - [% checkout.issuedate |$KohaDates with_hours => 1 %] - - [% checkout.date_due | $KohaDates as_due_date => 1 %] - - [% checkout.returndate |$KohaDates with_hours => 1 %] -
            + [% IF checkout.item.barcode %] + [%# FIXME This test is not mandatory I think %] + [% checkout.item.barcode | html %] + [% ELSE %] +   + [% END %][% IF checkout.branchcode %] + [% Branches.GetName( checkout.branchcode ) | html %] + [% ELSE %] +   + [% END %][% IF checkout.issuer_id %] + [% INCLUDE 'patron-title.inc' patron=checkout.issuer %] + [% END %][% IF checkout.renewals_count %] + Yes[% IF checkout.lastreneweddate %] + , last on: [% checkout.lastreneweddate |$KohaDates with_hours => 1 %] + [% END %] + [% ELSE %] + No + [% END %] [% checkout.issuedate |$KohaDates with_hours => 1 %] [% checkout.date_due | $KohaDates as_due_date => 1 %] [% checkout.returndate |$KohaDates with_hours => 1 %]
            + [% ELSE %] +

            [% biblio.title | html %][% IF biblio.author %], by [% biblio.author | html %][% END %] has never been checked out.

            [% END %] -
            - [% ELSE %] -

            - [% biblio.title | html %][% IF biblio.author %], by [% biblio.author | html %][% END %] has never been checked out.

            - - [% END %] -
            +
            [% END %] [% MACRO jsinclude BLOCK %] -[% INCLUDE 'datatables.inc' %] -[% INCLUDE 'columns_settings.inc' %] + [% INCLUDE 'datatables.inc' %] + [% INCLUDE 'columns_settings.inc' %] - + + [% INCLUDE 'calendar.inc' %] [% INCLUDE 'select2.inc' %] [% Asset.js("js/catalog.js") | $raw %] @@ -101,20 +108,20 @@ [% Asset.js("js/modals/add_catalog_concern.js") | $raw %] [% END %] [% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/catalogue/moredetail.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/catalogue/moredetail.tt index aa5ce1257b..0943da4f42 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/catalogue/moredetail.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/catalogue/moredetail.tt @@ -7,14 +7,19 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% title_in_title = INCLUDE 'biblio-title-head.inc' %] - [% tx("Item details for {title}", { title = title_in_title }) | html %] › - [% t("Catalog") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% title_in_title = INCLUDE 'biblio-title-head.inc' %] + [% tx("Item details for {title}", { title = title_in_title }) | html %] + › [% t("Catalog") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] - + [% USE KohaDates %] @@ -37,473 +42,488 @@ [% END #/ WRAPPER sub-header.inc %] [% WRAPPER 'main-container.inc' aside='biblio-view-menu' %] - [% INCLUDE 'cat-toolbar.inc' %] + [% INCLUDE 'cat-toolbar.inc' %] -

            Item details for [% INCLUDE 'biblio-title-head.inc' %]

            +

            Item details for [% INCLUDE 'biblio-title-head.inc' %]

            -
            -
            -

            [% title | html %]

            - [% IF ( subtitle ) %] -

            [% FOREACH subtitl IN subtitle %] [% subtitl | html %][% END %]

            +
            +
            +

            [% title | html %]

            + [% IF ( subtitle ) %] +

            [% FOREACH subtitl IN subtitle %][% subtitl | html %][% END %]

            + [% END %] + [% IF ( author ) %] +

            by [% author | html %]

            + [% END %] +
            +
            +
              +
            1. Biblionumber: [% biblionumber | html %] 
            2. + [% UNLESS ( item_level_itypes ) %] +
            3. Item type: [% itemtypename | html %] 
            4. [% END %] - [% IF ( author ) %] -

              by [% author | html %]

              + [% IF ( rentalcharge ) %] +
            5. Rental charge:[% rentalcharge | $Price %] 
            6. [% END %] -
              -
              -
                -
              1. Biblionumber: [% biblionumber | html %] 
              2. - [% UNLESS ( item_level_itypes ) %] -
              3. Item type: [% itemtypename | html %] 
              4. - [% END %] - [% IF ( rentalcharge ) %] -
              5. Rental charge:[% rentalcharge | $Price %] 
              6. - [% END %] - [% IF ( rentalcharge_daily ) %] -
              7. Daily rental charge:[% rentalcharge_daily | $Price %] 
              8. - [% END %] - [% IF ( rentalcharge_hourly ) %] -
              9. Hourly rental charge:[% rentalcharge_hourly | $Price %] 
              10. - [% END %] -
              11. ISBN: [% isbn | html %] 
              12. -
              13. Publication details:[% place | html %] [% publishercode | html %] [% publicationyear | html %] 
              14. - [% IF ( volumeddesc ) %] -
              15. Volume: [% volumeddesc | html %]
              16. - [% END %] -
              17. Physical details: [% pages | html %] [% illus | html %] [% size | html %] 
              18. - [% IF ( bnotes ) %] -
              19. Notes: [% bnotes | html %]
              20. - [% END %] -
              21. - No. of items: - [% count | html %] - [% IF ( hiddencount ) %] - total ([% showncount | html %] shown / [% hiddencount | html %] hidden) - Show all items - [% END %] -
              22. -
              -
              -
              -
            - - [% IF ( ONLY_ONE ) %] -
            You are only viewing one item. View all
            - [% END %] - - [% IF updated_exclude_from_local_holds_priority.defined %] -
            - [% IF updated_exclude_from_local_holds_priority %] - Exclude from local holds priority updated to 'Yes' - [% ELSE %] - Exclude from local holds priority updated to 'No' + [% IF ( rentalcharge_daily ) %] +
          • Daily rental charge:[% rentalcharge_daily | $Price %] 
          • + [% END %] + [% IF ( rentalcharge_hourly ) %] +
          • Hourly rental charge:[% rentalcharge_hourly | $Price %] 
          • + [% END %] +
          • ISBN: [% isbn | html %] 
          • +
          • Publication details:[% place | html %] [% publishercode | html %] [% publicationyear | html %] 
          • + [% IF ( volumeddesc ) %] +
          • Volume: [% volumeddesc | html %]
          • + [% END %] +
          • Physical details: [% pages | html %] [% illus | html %] [% size | html %] 
          • + [% IF ( bnotes ) %] +
          • Notes: [% bnotes | html %]
          • + [% END %] +
          • + No. of items: + [% count | html %] + [% IF ( hiddencount ) %] + total ([% showncount | html %] shown / [% hiddencount | html %] hidden) + Show all items [% END %] -
          • - [% END %] + + + +
            + +
            + +
            + - [% FOREACH ITEM_DAT IN ITEM_DATA %] -
            - [% SET not_for_loan = 0 %] - [% IF ITEM_DAT.notforloan || ITEM_DAT.effective_itemtype.notforloan %] - [% SET not_for_loan = 1 %] - [% SET not_for_loan_description = AuthorisedValues.GetDescriptionByKohaField( kohafield => 'items.notforloan', authorised_value => item.notforloan ) %] + [% IF ( ONLY_ONE ) %] +
            You are only viewing one item. View all
            + [% END %] + + [% IF updated_exclude_from_local_holds_priority.defined %] +
            + [% IF updated_exclude_from_local_holds_priority %] + Exclude from local holds priority updated to 'Yes' + [% ELSE %] + Exclude from local holds priority updated to 'No' + [% END %] +
            + [% END %] + + [% FOREACH ITEM_DAT IN ITEM_DATA %] +
            + [% SET not_for_loan = 0 %] + [% IF ITEM_DAT.notforloan || ITEM_DAT.effective_itemtype.notforloan %] + [% SET not_for_loan = 1 %] + [% SET not_for_loan_description = AuthorisedValues.GetDescriptionByKohaField( kohafield => 'items.notforloan', authorised_value => item.notforloan ) %] + [% END %] +
            +

            Barcode [% ITEM_DAT.barcode | html %] [% IF not_for_loan %][% not_for_loan_description | html %][% END %]

            + +

            + Item information + [% UNLESS ( ITEM_DAT.nomod ) %] + [% IF ( CAN_user_editcatalogue_edit_items ) %] + Edit item [% END %] -
            -

            - Barcode [% ITEM_DAT.barcode | html %] [% IF not_for_loan %][% not_for_loan_description | html %] [% END %] -

            + [% END %] +

            -

            - Item information - [% UNLESS ( ITEM_DAT.nomod ) %] - [% IF ( CAN_user_editcatalogue_edit_items ) %] - Edit item +
            +
              +
            1. Home library: [% Branches.GetName( ITEM_DAT.homebranch ) | html %] 
            2. + [% IF ( item_level_itypes ) %] +
            3. Item type: [% ITEM_DAT.itype | html %] 
            4. + [% END %] + [% IF ( ITEM_DAT.ccode) %] +
            5. Collection: [% ITEM_DAT.ccode | html %]
            6. + [% END %] +
            7. Item call number: [% ITEM_DAT.itemcallnumber | html %]
            8. + [% IF ( ITEM_DAT.displaycopy ) %] +
            9. Copy number: [% ITEM_DAT.copyvol | html %] 
            10. + [% END %] + [% IF ( ITEM_DAT.location ) %] +
            11. + Shelving location: + [% AuthorisedValues.GetDescriptionByKohaField( kohafield => 'items.location', authorised_value => ITEM_DAT.location ) | html %] +
            12. + [% END %] + [% IF ( ITEM_DAT.replacementprice ) %] +
            13. Replacement price: [% ITEM_DAT.replacementprice | $Price %] 
            14. + [% END %] + [% IF ITEM_DAT.materials %] +
            15. Materials specified: [% ITEM_DAT.materials | html %]
            16. + [% END %] +
            + +
            + +

            + + +
            +

            + Statuses + [% IF ( ITEM_DAT.status_advisory ) %] + ([% IF ( not_for_loan ) %] + [% IF not_for_loan_description %] + [% not_for_loan_description | html %] + [% ELSE %] + Not for loan + [% END %] + [% END %] + [% IF ( ITEM_DAT.itemlost ) %]Lost[% END %] + [% IF ( ITEM_DAT.damaged ) %]Damaged[% END %] + [% IF ( ITEM_DAT.withdrawn ) %]Withdrawn[% END %] + ) + [% END %] +

            + +
            +
              +
            1. Current library: [% Branches.GetName( ITEM_DAT.holdingbranch ) | html %] 
            2. +
            3. + Checkout status: + [% SET checkout = ITEM_DAT.object.checkout %] + [% IF ( checkout ) %] + Checked out to [% INCLUDE 'patron-title.inc' patron => checkout.patron hide_patron_infos_if_needed=1 %] + [% IF ( checkout.lastreneweddate ) %] + Last renewed [% checkout.lastreneweddate | $KohaDates %], + [% END %] + [% IF ( checkout.date_due ) %] + Due back on [% checkout.date_due | $KohaDates as_due_date => 1 %] + [% ELSE %] + Not checked out + [% END %] + [% END %] +
            4. + [% IF ITEM_DAT.object.checkout.renewals_count %] +
            5. + Current renewals: + [% ITEM_DAT.object.checkout.renewals_count | html %] [ + View ] +
            6. + [% END %] + [% IF itemlostloop %] +
            7. + Lost status: + [% IF ( CAN_user_circulate ) %] + [% SET ClaimReturnedLostValue = Koha.Preference('ClaimReturnedLostValue') %] +
              + [% INCLUDE 'csrf-token.inc' %] + + + + + + + + + + + [% IF ClaimReturnedLostValue && ITEM_DAT.has_return_claim %] +

              Item has been claimed as returned.

              + [% END %] +
              + [% ELSE %] + [% FOREACH itemlostloo IN itemlostloop %] + [% IF ( itemlostloo.selected ) %] + [% itemlostloo.lib | html %] + [% END %] [% END %] [% END %] - +
            8. + [% IF ITEM_DAT.itemlost != "" && ITEM_DAT.itemlost_on %] +
            9. Lost on:[% ITEM_DAT.itemlost_on | $KohaDates %]
            10. + [% END %] + [% END %] -
              -
                -
              1. Home library: [% Branches.GetName( ITEM_DAT.homebranch ) | html %] 
              2. - [% IF ( item_level_itypes ) %] -
              3. Item type: [% ITEM_DAT.itype | html %] 
              4. - [% END %] - [% IF ( ITEM_DAT.ccode) %] -
              5. Collection: [% ITEM_DAT.ccode | html %]
              6. - [% END %] -
              7. Item call number: [% ITEM_DAT.itemcallnumber | html %]
              8. - [% IF ( ITEM_DAT.displaycopy ) %] -
              9. Copy number: [% ITEM_DAT.copyvol | html %] 
              10. - [% END %] - [% IF ( ITEM_DAT.location ) %] -
              11. - Shelving location: - [% AuthorisedValues.GetDescriptionByKohaField( kohafield => 'items.location', authorised_value => ITEM_DAT.location ) | html %] -
              12. - [% END %] - [% IF ( ITEM_DAT.replacementprice ) %] -
              13. Replacement price: [% ITEM_DAT.replacementprice | $Price %] 
              14. - [% END %] - [% IF ITEM_DAT.materials %] -
              15. Materials specified: [% ITEM_DAT.materials | html %]
              16. - [% END %] -
              -
              -
            - -
            -

            - Statuses - [% IF ( ITEM_DAT.status_advisory ) %] - ([% IF ( not_for_loan ) %] - [% IF not_for_loan_description %] - [% not_for_loan_description | html %] - [% ELSE %] - Not for loan + [% IF itemdamagedloop %] +
          • + Damaged status: + [% IF ( CAN_user_circulate ) %] +
            + [% INCLUDE 'csrf-token.inc' %] + + + + + + +
            + [% ELSE %] + [% FOREACH itemdamagedloo IN itemdamagedloop %] + [% IF ( itemdamagedloo.selected ) %] + [% itemdamagedloo.lib | html %] [% END %] [% END %] - [% IF ( ITEM_DAT.itemlost ) %]Lost[% END %] - [% IF ( ITEM_DAT.damaged ) %]Damaged[% END %] - [% IF ( ITEM_DAT.withdrawn ) %]Withdrawn[% END %] - ) [% END %] -
          • + + [% IF ITEM_DAT.damaged != "" && ITEM_DAT.damaged_on %] +
          • Damaged on:[% ITEM_DAT.damaged_on | $KohaDates %]
          • + [% END %] + [% END %] -
            -
              -
            1. Current library: [% Branches.GetName( ITEM_DAT.holdingbranch ) | html %] 
            2. -
            3. - Checkout status: - [% SET checkout = ITEM_DAT.object.checkout %] - [% IF ( checkout ) %] - Checked out to [% INCLUDE 'patron-title.inc' patron => checkout.patron hide_patron_infos_if_needed=1 %] - [% IF ( checkout.lastreneweddate ) %] - Last renewed [% checkout.lastreneweddate | $KohaDates %], - [% END %] - [% IF ( checkout.date_due ) %] - Due back on [% checkout.date_due | $KohaDates as_due_date => 1 %] - [% ELSE %] - Not checked out - [% END %] - [% END %] -
            4. - [% IF ITEM_DAT.object.checkout.renewals_count %] -
            5. - Current renewals: - [% ITEM_DAT.object.checkout.renewals_count | html %] - [ View ] -
            6. - [% END %] - [% IF itemlostloop %] -
            7. - Lost status: - [% IF ( CAN_user_circulate ) %] - [% SET ClaimReturnedLostValue = Koha.Preference('ClaimReturnedLostValue') %] -
              - [% INCLUDE 'csrf-token.inc' %] - - - - - - - - - - - [% IF ClaimReturnedLostValue && ITEM_DAT.has_return_claim %] -

              Item has been claimed as returned.

              - [% END %] -
              - [% ELSE %] - [% FOREACH itemlostloo IN itemlostloop %] - [% IF ( itemlostloo.selected ) %] - [% itemlostloo.lib | html %] - [% END %] - [% END %] - [% END %] -
            8. - [% IF ITEM_DAT.itemlost != "" && ITEM_DAT.itemlost_on %] -
            9. Lost on:[% ITEM_DAT.itemlost_on | $KohaDates %]
            10. - [% END %] - [% END %] - - [% IF itemdamagedloop %] -
            11. - Damaged status: - [% IF ( CAN_user_circulate ) %] -
              - [% INCLUDE 'csrf-token.inc' %] - - - - - - -
              - [% ELSE %] - [% FOREACH itemdamagedloo IN itemdamagedloop %] - [% IF ( itemdamagedloo.selected ) %] - [% itemdamagedloo.lib | html %] - [% END %] - [% END %] - [% END %] -
            12. - [% IF ITEM_DAT.damaged != "" && ITEM_DAT.damaged_on %] -
            13. Damaged on:[% ITEM_DAT.damaged_on | $KohaDates %]
            14. - [% END %] - [% END %] - - [% IF itemwithdrawnloop %] -
            15. - Withdrawn status: - [% IF ( CAN_user_circulate ) %] -
              - [% INCLUDE 'csrf-token.inc' %] - - - - - - -
              - [% ELSE %] - [% FOREACH itemwithdrawn IN itemwithdrawnloop %] - [% IF itemwithdrawn.authorised_value == ITEM_DAT.withdrawn %] - [% itemwithdrawn.lib | html %] - [% END %] - [% END %] - [% END %] -
            16. - [% IF ITEM_DAT.withdrawn != "" && ITEM_DAT.withdrawn_on %] -
            17. Withdrawn on:[% ITEM_DAT.withdrawn_on | $KohaDates %]
            18. - [% END %] - [% END %] - -
            -
            -
            - -
            -

            Priority

            -
            -
              -
            1. - Exclude from local holds priority: -
              - [% INCLUDE 'csrf-token.inc' %] - - - - + + + - - -
              -
            2. -
            3. - - Bookable: - - [% IF ( CAN_user_circulate ) %] -
              - [% INCLUDE 'csrf-token.inc' %] - - - - - - -
              - [% ELSE %] - [% IF ITEM_DAT.bookable == 1 %] Yes [% ELSIF ITEM_DAT.bookable == 0 %] No [% ELSE %] Follow item type [% END %] - [% END %] - Item type bookable: [% IF ITEM_DAT.effective_itemtype.bookable == 1 %]Yes[% ELSE %]No[% END %] -
            4. - -
            -
            -
            - -
            -

            History

            -
            -
              - - [% IF ITEM_DAT.basketno %] -
            1. - Order date: - [% IF ( CAN_user_acquisition_order_manage ) %] - [% ITEM_DAT.orderdate | $KohaDates %] - [% ELSE %] - [% ITEM_DAT.orderdate | $KohaDates %] [% END %] -
            2. -
            3. - Vendor: - [% ITEM_DAT.vendor | html %] -
            4. - [% END %] - - [% IF ITEM_DAT.dateaccessioned %] -
            5. - Accession date: - [% IF ( CAN_user_acquisition_order_receive && ITEM_DAT.invoiceid ) %] - [% ITEM_DAT.dateaccessioned | $KohaDates %] - [% ELSE %] - [% ITEM_DAT.dateaccessioned | $KohaDates %] - [% END %] -
            6. - [% END %] - - [% IF ( ITEM_DAT.invoicenumber ) %] -
            7. - Invoice number: - [% ITEM_DAT.invoicenumber | html %] -
            8. - [% END %] - -
            9. - Total checkouts: - [% IF ( ITEM_DAT.issues ) %] - [% ITEM_DAT.issues | html %] - [% ELSE %] - 0 + + + + + [% ELSE %] + [% FOREACH itemwithdrawn IN itemwithdrawnloop %] + [% IF itemwithdrawn.authorised_value == ITEM_DAT.withdrawn %] + [% itemwithdrawn.lib | html %] [% END %] - (View item's checkout history) -
            10. + [% END %] + [% END %] + + [% IF ITEM_DAT.withdrawn != "" && ITEM_DAT.withdrawn_on %] +
            11. Withdrawn on:[% ITEM_DAT.withdrawn_on | $KohaDates %]
            12. + [% END %] + [% END %] +
            + +
            + +
            + -
          • - Last seen: - [% IF ( ITEM_DAT.datelastseen ) %] - [% ITEM_DAT.datelastseen | $KohaDates with_hours => 1 %] - [%END %] -
          • -
          • - Last borrowed: - [% IF (ITEM_DAT.datelastborrowed ) %][% ITEM_DAT.datelastborrowed | $KohaDates %][% END %] -
          • - [% IF Koha.Preference('StoreLastBorrower') && ITEM_DAT.object.last_returned_by %] - [% SET last_returned_by = ITEM_DAT.object.last_returned_by.cardnumber || ITEM_DAT.object.last_returned_by.borrowernumber %] -
          • - Last returned by: - [% last_returned_by | html %] -
          • +
            +

            Priority

            +
            +
              +
            1. + Exclude from local holds priority: +
              + [% INCLUDE 'csrf-token.inc' %] + + + + - [% INCLUDE 'csrf-token.inc' %] - - - -
              + + + + +
            2. +
            3. + Bookable: + [% IF ( CAN_user_circulate ) %] +
              + [% INCLUDE 'csrf-token.inc' %] + + + + + + +
              + [% ELSE %] + [% IF ITEM_DAT.bookable == 1 %]Yes[% ELSIF ITEM_DAT.bookable == 0 %]No[% ELSE %]Follow item type[% END %] + [% END %] + Item type bookable: [% IF ITEM_DAT.effective_itemtype.bookable == 1 %]Yes[% ELSE %]No[% END %] +
            4. +
            + +
            + +
            + -
          • - Non-public note: - [% IF ( CAN_user_editcatalogue_edit_items ) %] -
            - [% INCLUDE 'csrf-token.inc' %] - - - -
            - [% ELSE %] - [% ITEM_DAT.itemnotes_nonpublic | html %] - [% END %] -
          • - -
            -
            -
            - [% END # /FOREACH ITEM_DAT %] -
            +
            +

            History

            +
            +
              + [% IF ITEM_DAT.basketno %] +
            1. + Order date: + [% IF ( CAN_user_acquisition_order_manage ) %] + [% ITEM_DAT.orderdate | $KohaDates %] + [% ELSE %] + [% ITEM_DAT.orderdate | $KohaDates %] + [% END %] +
            2. +
            3. + Vendor: + [% ITEM_DAT.vendor | html %] +
            4. + [% END %] + + [% IF ITEM_DAT.dateaccessioned %] +
            5. + Accession date: + [% IF ( CAN_user_acquisition_order_receive && ITEM_DAT.invoiceid ) %] + [% ITEM_DAT.dateaccessioned | $KohaDates %] + [% ELSE %] + [% ITEM_DAT.dateaccessioned | $KohaDates %] + [% END %] +
            6. + [% END %] + + [% IF ( ITEM_DAT.invoicenumber ) %] +
            7. + Invoice number: + [% ITEM_DAT.invoicenumber | html %] +
            8. + [% END %] + +
            9. + Total checkouts: + [% IF ( ITEM_DAT.issues ) %] + [% ITEM_DAT.issues | html %] + [% ELSE %] + 0 + [% END %] + (View item's checkout history) +
            10. + +
            11. + Last seen: + [% IF ( ITEM_DAT.datelastseen ) %] + [% ITEM_DAT.datelastseen | $KohaDates with_hours => 1 %] + [% END %] +
            12. +
            13. + Last borrowed: + [% IF (ITEM_DAT.datelastborrowed ) %][% ITEM_DAT.datelastborrowed | $KohaDates %][% END %] +
            14. + [% IF Koha.Preference('StoreLastBorrower') && ITEM_DAT.object.last_returned_by %] + [% SET last_returned_by = ITEM_DAT.object.last_returned_by.cardnumber || ITEM_DAT.object.last_returned_by.borrowernumber %] +
            15. + Last returned by: + [% last_returned_by | html %] +
            16. + [% END %] + [% FOR i IN ITEM_DAT.old_issues %] + [% SET b = i.patron %] +
            17. + [% IF loop.first %] + Last borrower: + [% ELSE %] + Previous borrower: + [% END %] + [% SET last_or_previous_borrower = b.cardnumber || b.borrowernumber %] + [% last_or_previous_borrower | html %]  +
            18. + [% END %] + [% IF ( ITEM_DAT.paidfor ) %] +
            19. + Paid for?: + [% INCLUDE 'patron-title.inc' patron=ITEM_DAT.paidfor.patron hide_patron_infos_if_needed=1 %] on [% ITEM_DAT.paidfor.created_on | $KohaDates %] +
            20. + [% END %] + + [% IF ( ITEM_DAT.enumchron ) %] +
            21. + Serial enumeration: + [% ITEM_DAT.enumchron | html %]  +
            22. + [% END %] + +
            23. + Public note: + [% IF ( CAN_user_editcatalogue_edit_items ) %] +
              + [% INCLUDE 'csrf-token.inc' %] + + + +
              + [% ELSE %] + [% ITEM_DAT.itemnotes | html %] + [% END %] +
            24. + +
            25. + Non-public note: + [% IF ( CAN_user_editcatalogue_edit_items ) %] +
              + [% INCLUDE 'csrf-token.inc' %] + + + +
              + [% ELSE %] + [% ITEM_DAT.itemnotes_nonpublic | html %] + [% END %] +
            26. +
            + +
            + +
            + +
            + + [% END # /FOREACH ITEM_DAT %] +
            + [% END %] [% IF ( Koha.Preference('CatalogConcerns') ) %] -[% INCLUDE 'modals/add_catalog_concern.inc' %] + [% INCLUDE 'modals/add_catalog_concern.inc' %] [% END %] [% MACRO jsinclude BLOCK %] @@ -512,8 +532,12 @@ [% INCLUDE 'js-date-format.inc' %] [% Asset.js("lib/dayjs/plugin/isSameOrAfter.js") | $raw %] [% Asset.js("lib/dayjs/plugin/isSameOrBefore.js") | $raw %] - - + + [% INCLUDE 'js-patron-format.inc' %] [% INCLUDE 'calendar.inc' %] [% INCLUDE 'select2.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/catalogue/results.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/catalogue/results.tt index d29f940525..ade947fd89 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/catalogue/results.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/catalogue/results.tt @@ -11,27 +11,28 @@ [% USE AuthorisedValues %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% IF ( searchdesc ) %] - [% IF ( query_desc ) %] - [% IF ( limit_desc ) %] - [% tx("Results of search for {query_desc} with limit(s): '{limit_desc}'", { query_desc = query_desc, limit_desc = limit_desc }) | html %] +<title + >[% FILTER collapse %] + [% IF ( searchdesc ) %] + [% IF ( query_desc ) %] + [% IF ( limit_desc ) %] + [% tx("Results of search for {query_desc} with limit(s): '{limit_desc}'", { query_desc = query_desc, limit_desc = limit_desc }) | html %] + [% ELSE %] + [% tx("Results of search for {query_desc}", { query_desc = query_desc }) | html %] + [% END %] [% ELSE %] - [% tx("Results of search for {query_desc}", { query_desc = query_desc }) | html %] + [% IF ( limit_desc ) %] + [% tx("Results of search for {limit_desc}", { limit_desc = limit_desc }) | html %] + [% ELSE %] + [% t("Results of search") | html %] + [% END %] [% END %] [% ELSE %] - [% IF ( limit_desc ) %] - [% tx("Results of search for {limit_desc}", { limit_desc = limit_desc }) | html %] - [% ELSE %] - [% t("Results of search") | html %] - [% END %] + [% t("You did not specify any search criteria") | html %] [% END %] - [% ELSE %] - [% t("You did not specify any search criteria") | html %] - [% END %] › - [% t("Catalog") | html %] › - [% t("Koha") | html %] -[% END %] + › [% t("Catalog") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -66,706 +67,855 @@ [% END #/ WRAPPER sub-header.inc %] [% WRAPPER 'main-container.inc' aside='facets' %] +

            Search results

            -

            Search results

            + [% IF ( total ) %] +

            + [% total | html %] result(s) found + [% IF ( query_desc ) %]for '[% query_desc | html %]'[% END %][% IF limit_desc %] +  with limit(s): '[% limit_desc | html %]' + [% END %][% IF ( LibraryName ) %]in [% LibraryName | html %] Catalog[% END %]. +

            - [% IF ( total ) %] - -

            - [% total | html %] result(s) found [% IF ( query_desc ) %]for '[% query_desc | html %]'[% END %][% IF limit_desc %] with limit(s): '[% limit_desc | html %]'[% END %][% IF ( LibraryName ) %] in [% LibraryName | html %] Catalog[% END %]. -

            - - [% UNLESS scan %] - + [% UNLESS scan %] + Edit this search - [% IF ( Koha.Preference('SavedSearchFilters') && CAN_user_parameters_manage_search_filters ) %] - | Save search as filter + [% IF ( Koha.Preference('SavedSearchFilters') && CAN_user_parameters_manage_search_filters ) %] + | Save search as filter + [% END %] + +
            + +
            + +
            +
            + Select all + Clear all + | + [% IF Koha.Preference("StaffHighlightedWords") == 1 %] + Unhighlight + Highlight + | [% END %] -
            - -
            + [% IF (Koha.Preference("intranetbookbag")) %] + + [% END %] -
            -
            - Select all - Clear all - | - [% IF Koha.Preference("StaffHighlightedWords") == 1 %] - Unhighlight - Highlight - | - [% END %] - - [% IF (Koha.Preference("intranetbookbag")) %] - - [% END %] - - [% IF Koha.Preference('virtualshelves') %] -
            - - +
            + [% END # /IF virtualshelves %] - [% IF ( searchdesc ) %] - [% BLOCK sort_search_query ~%] - [%~ FOREACH QUERY_INPUT IN QUERY_INPUTS ~%] - &[% QUERY_INPUT.input_name | uri %]=[% QUERY_INPUT.input_value | uri %] - [%~ END ~%] - [%~ FOREACH LIMIT_INPUT IN LIMIT_INPUTS ~%] - &[% LIMIT_INPUT.input_name | uri %]=[% LIMIT_INPUT.input_value | uri %] - [%~ END ~%] - [%~ END %] - [% END %] - -
            - + [% IF ( CAN_user_reserveforothers_place_holds && DisplayMultiPlaceHold ) %] + [% IF ( holdfor or holdforclub ) %] +
            + + -
            - - [% IF Koha.Preference('numSearchResultsDropdown') %] - - [% END %] - -
            -
            - [% INCLUDE 'csrf-token.inc' %] - - - -
            -
            - [% END %] - - [% ELSE # /IF total %] - - - -
            -

            No results found

            - [% IF ( searchdesc ) %] -

            - No results match your search [% IF ( query_desc ) %]for '[% query_desc | html %]'[% END %][% IF ( limit_desc ) %] with limit(s): '[% limit_desc | html %]'[% END %][% IF ( LibraryName ) %] in [% LibraryName | html %] Catalog[% END %]. -

            - [% IF CAN_user_acquisition_order_manage && searchtoorder_basketno && searchtoorder_vendorid %][%# Coming from the basket or vendor view %] -

            View basket

            - [% END %] - - Edit this search - - [% IF ( Koha.Preference('SavedSearchFilters') && CAN_user_parameters_manage_search_filters ) %] - | Save search as filter - [% END %] +
            [% ELSE %] -

            You did not specify any search criteria.

            - [% END %] -
            - [% END # /IF total %] + + [% END # /IF holfor %] + [% END # /IF CAN_user_reserveforothers_place_holds %] - [% IF ( query_error ) %] -

            Error: [% query_error | html %]

            - [% END %] - - - [% IF ( total ) %] - [% IF ( scan ) %] -
            -

            Scan index

            -
            - - - [% IF ( scan_search_term_to_use ) %] - - [% ELSE %] - Scan index for: - [% END %] - - -
            - -
            - - - - - - [% FOREACH SEARCH_RESULT IN SEARCH_RESULTS %] - - - - - [% END %] -
            Term/PhraseCount
            - [% SEARCH_RESULT.title | html %] - - [% SEARCH_RESULT.author | html %] -
            -
            -
            - [% ELSE # /IF scan %] - -
            - [% INCLUDE 'page-numbers.inc' %] - -
            - [% IF ( searchdesc ) %] - [% FOREACH QUERY_INPUT IN QUERY_INPUTS %] - - [% END %] - [% FOREACH LIMIT_INPUT IN LIMIT_INPUTS %] - - [% END %] - [% END %] - - - - - - [% IF ( CoverImagePlugins || AmazonCoverImages || LocalCoverImages || ( SyndeticsCovers ) || (Koha.Preference('CustomCoverImages') && Koha.Preference('CustomCoverImagesURL')) ) %] - - [% END %] - - - - - - [% SET MaxSearchResultsItemsPerRecordStatusCheck = Koha.Preference('MaxSearchResultsItemsPerRecordStatusCheck') %] - - [% FOREACH SEARCH_RESULT IN SEARCH_RESULTS %] - - [% IF ( CoverImagePlugins || AmazonCoverImages || LocalCoverImages || IntranetCoce || ( SyndeticsCovers ) || (Koha.Preference('CustomCoverImages') && Koha.Preference('CustomCoverImagesURL')) ) %] - -[% END # /IF( AmazonCoverImages || LocalCoverImages || IntranetCoce )%] + [% END # /IF total %] - + [% IF ( query_error ) %] +

            Error: [% query_error | html %]

            + [% END %] - + + [% END # /FOREACH SEARCH_RESULT %] + +
             ResultsLocation
            -
            - [% IF ( LocalCoverImages && SEARCH_RESULT.has_local_cover_image ) %] -
            - - Local cover image - -
            Local cover image
            -
            - [% END %] - - [% IF ( AmazonCoverImages && SEARCH_RESULT.normalized_isbn ) %] -
            - - Cover image from Amazon.com - -
            Amazon cover image
            -
            - [% END # /IF AmazonCoverImages %] - - [% IF ( SyndeticsCovers ) %] - [% IF ( SEARCH_RESULT.normalized_isbn || SEARCH_RESULT.normalized_upc || SEARCH_RESULT.normalized_oclc ) %] -
            - - Cover from Syndetics - -
            Syndetics cover image
            + [% IF Koha.Preference('BrowseResultSelection') %] + [% END %] - [% END %] - [% IF ( IntranetCoce && CoceProviders && SEARCH_RESULT.normalized_isbn ) %] - [% coce_id = SEARCH_RESULT.normalized_ean || SEARCH_RESULT.normalized_isbn %] - [% IF ( coce_id ) %] -
            - - - -
            Coce cover image
            -
            - [% END %] - [% END %] + [% IF ( CAN_user_editcatalogue_edit_catalogue ) %] + - [% IF Koha.Preference('CustomCoverImages') && Koha.Preference('CustomCoverImagesURL') %] - [% SET custom_cover_image_url = SEARCH_RESULT.biblio_object.custom_cover_image_url %] - [% IF custom_cover_image_url %] -
            - - Custom cover image - -
            Custom cover image
            +
            + + [% IF ( CAN_user_tools_records_batchmod || CAN_user_tools_records_batchdel || CAN_user_editcatalogue_edit_catalogue ) %] + + [% END %] +
            + [% END %] + + [% IF ( searchdesc ) %] + [% BLOCK sort_search_query ~%] + [%~ FOREACH QUERY_INPUT IN QUERY_INPUTS ~%] + &[% QUERY_INPUT.input_name | uri %]=[% QUERY_INPUT.input_value | uri %] + [%~ END ~%] + [%~ FOREACH LIMIT_INPUT IN LIMIT_INPUTS ~%] + &[% LIMIT_INPUT.input_name | uri %]=[% LIMIT_INPUT.input_value | uri %] + [%~ END ~%] + [%~ END %] + [% END %] + +
            + +
            + + + [% IF Koha.Preference('numSearchResultsDropdown') %] + + + [% END %] +
            + + + [% INCLUDE 'csrf-token.inc' %] + + + + +
            + + [% END %] + [% ELSE # /IF total %] + + +
            +

            No results found

            + [% IF ( searchdesc ) %] +

            + No results match your search + [% IF ( query_desc ) %]for '[% query_desc | html %]'[% END %][% IF ( limit_desc ) %] +  with limit(s): '[% limit_desc | html %]' + [% END %][% IF ( LibraryName ) %]in [% LibraryName | html %] Catalog[% END %]. +

            + [% IF CAN_user_acquisition_order_manage && searchtoorder_basketno && searchtoorder_vendorid %] + [%# Coming from the basket or vendor view %] +

            View basket

            [% END %] + + Edit this search + + [% IF ( Koha.Preference('SavedSearchFilters') && CAN_user_parameters_manage_search_filters ) %] + | Save search as filter + [% END %] + [% ELSE %] +

            You did not specify any search criteria.

            [% END %]
            -
            - - - [% IF ( !item_level_itypes ) || Koha.Preference('BiblioItemtypeInfo') %] -
            - [% IF !noItemTypeImages && SEARCH_RESULT.imageurl %] - [%  SEARCH_RESULT.description | html %] - [% END %] - [% SEARCH_RESULT.description | html %] + + [% IF ( total ) %] + [% IF ( scan ) %] +
            +

            Scan index

            +
            + + + [% IF ( scan_search_term_to_use ) %] + + [% ELSE %] + Scan index for: + [% END %] + + +
            + +
            + + + + + + [% FOREACH SEARCH_RESULT IN SEARCH_RESULTS %] + + + + + [% END %] +
            Term/PhraseCount
            + [% SEARCH_RESULT.title | html %] + [% SEARCH_RESULT.author | html %]
            +
            +
            + [% ELSE # /IF scan %] +
            + [% INCLUDE 'page-numbers.inc' %] + +
            + [% IF ( searchdesc ) %] + [% FOREACH QUERY_INPUT IN QUERY_INPUTS %] + + [% END %] + [% FOREACH LIMIT_INPUT IN LIMIT_INPUTS %] + + [% END %] + [% END %] + + + + + + [% IF ( CoverImagePlugins || AmazonCoverImages || LocalCoverImages || ( SyndeticsCovers ) || (Koha.Preference('CustomCoverImages') && Koha.Preference('CustomCoverImagesURL')) ) %] + + [% END %] + + + + + + [% SET MaxSearchResultsItemsPerRecordStatusCheck = Koha.Preference('MaxSearchResultsItemsPerRecordStatusCheck') %] + + [% FOREACH SEARCH_RESULT IN SEARCH_RESULTS %] + + [% IF ( CoverImagePlugins || AmazonCoverImages || LocalCoverImages || IntranetCoce || ( SyndeticsCovers ) || (Koha.Preference('CustomCoverImages') && Koha.Preference('CustomCoverImagesURL')) ) %] + + [% END # /IF( AmazonCoverImages || LocalCoverImages || IntranetCoce ) %] - [% IF ( CAN_user_acquisition_order_manage ) %] - [% IF ( searchtoorder_basketno && searchtoorder_vendorid ) %] - | Add order - [% END %] - [% END %] + - [% IF ( OPACBaseURL ) %] - - | OPAC view - - [% END %] -

            - + + + - - [% END # /FOREACH SEARCH_RESULT %] - -
             ResultsLocation
            +
            + [% IF ( LocalCoverImages && SEARCH_RESULT.has_local_cover_image ) %] +
            + + Local cover image + +
            Local cover image
            [% END %] - [% SEARCH_RESULT.result_number | html %]. - [% SEARCH_RESULT.XSLTResultsRecord | $raw %] + [% IF ( AmazonCoverImages && SEARCH_RESULT.normalized_isbn ) %] +
            + + Cover image from Amazon.com + +
            Amazon cover image
            +
            + [% END # /IF AmazonCoverImages %] -

            - [% IF ( SEARCH_RESULT.norequests ) %] - No holds allowed - [% ELSE %] - [% IF CAN_user_reserveforothers_place_holds %] - Holds ([% SEARCH_RESULT.biblio_object.holds.count | html %]) - [% IF ( holdfor ) %] | Place hold for [% INCLUDE 'patron-title.inc' patron => holdfor_patron no_title => 1 no_cardnumber => 1 %][% END %] - [% IF ( holdforclub ) %] | Place hold for [% holdforclub_name | html %][% END %] - [% ELSE %] - Holds ([% SEARCH_RESULT.biblio_object.holds.count | html %]) - [% END %] - [% END # /IF SEARCH_RESULT.norequests %] - [% IF Koha.Preference('UseRecalls') and CAN_user_recalls %] - | Recalls ([% SEARCH_RESULT.biblio_object.recalls.search( completed => 0 ).count | html %]) + [% IF ( SyndeticsCovers ) %] + [% IF ( SEARCH_RESULT.normalized_isbn || SEARCH_RESULT.normalized_upc || SEARCH_RESULT.normalized_oclc ) %] +

            + + Cover from Syndetics + +
            Syndetics cover image
            +
            [% END %] + [% END %] - [% IF Koha.Preference('intranetbookbag') == 1 %] - [% IF ( SEARCH_RESULT.incart ) %] - | In your cart (remove) - [% ELSE %] - | Add to cart - [% END %] - [% END # / IF intranetbookbag %] - - [% IF Koha.Preference('ArticleRequests') %] - | Request article + [% IF ( IntranetCoce && CoceProviders && SEARCH_RESULT.normalized_isbn ) %] + [% coce_id = SEARCH_RESULT.normalized_ean || SEARCH_RESULT.normalized_isbn %] + [% IF ( coce_id ) %] +
            + + + +
            Coce cover image
            +
            [% END %] + [% END %] - [% IF ( CAN_user_editcatalogue_edit_catalogue ) %] - | Edit record - [% END %] - [% IF ( CAN_user_editcatalogue_edit_items ) %] - | Edit items + [% IF Koha.Preference('CustomCoverImages') && Koha.Preference('CustomCoverImagesURL') %] + [% SET custom_cover_image_url = SEARCH_RESULT.biblio_object.custom_cover_image_url %] + [% IF custom_cover_image_url %] +
            + + Custom cover image + +
            Custom cover image
            +
            [% END %] + [% END %] +
            +
            + + + [% IF ( !item_level_itypes ) || Koha.Preference('BiblioItemtypeInfo') %] +
            + [% IF !noItemTypeImages && SEARCH_RESULT.imageurl %] + [% SEARCH_RESULT.description | html %] + [% END %] + [% SEARCH_RESULT.description | html %] +
            + [% END %] -
            -
            - [% IF ( SEARCH_RESULT.items_count ) %] -
            - [% IF MaxSearchResultsItemsPerRecordStatusCheck && SEARCH_RESULT.items_count > MaxSearchResultsItemsPerRecordStatusCheck %] - - [% tnx('{count} item', '{count} items', SEARCH_RESULT.items_count, {count = SEARCH_RESULT.items_count}) | html %][% IF ( SEARCH_RESULT.availablecount ) %], [% SEARCH_RESULT.availablecount | html %] available:[% ELSE %], None available[% END %] - + [% SEARCH_RESULT.result_number | html %]. + [% SEARCH_RESULT.XSLTResultsRecord | $raw %] + +

            + [% IF ( SEARCH_RESULT.norequests ) %] + No holds allowed + [% ELSE %] + [% IF CAN_user_reserveforothers_place_holds %] + Holds ([% SEARCH_RESULT.biblio_object.holds.count | html %]) + [% IF ( holdfor ) %] + | + Place hold for [% INCLUDE 'patron-title.inc' patron => holdfor_patron no_title => 1 no_cardnumber => 1 %] + [% END %] + [% IF ( holdforclub ) %] + | + Place hold for [% holdforclub_name | html %] + [% END %] + [% ELSE %] + Holds ([% SEARCH_RESULT.biblio_object.holds.count | html %]) + [% END %] + [% END # /IF SEARCH_RESULT.norequests %] + [% IF Koha.Preference('UseRecalls') and CAN_user_recalls %] + | + Recalls ([% SEARCH_RESULT.biblio_object.recalls.search( completed => 0 ).count | html %]) + [% END %] + + [% IF Koha.Preference('intranetbookbag') == 1 %] + [% IF ( SEARCH_RESULT.incart ) %] + | In your cart + (remove) + [% ELSE %] + | Add to cart + + [% END %] + [% END # / IF intranetbookbag %] + + [% IF Koha.Preference('ArticleRequests') %] + | Request article + [% END %] + + [% IF ( CAN_user_editcatalogue_edit_catalogue ) %] + | Edit record + [% END %] + [% IF ( CAN_user_editcatalogue_edit_items ) %] + | Edit items + [% END %] + + [% IF ( CAN_user_acquisition_order_manage ) %] + [% IF ( searchtoorder_basketno && searchtoorder_vendorid ) %] + | + Add order + [% END %] + [% END %] + + [% IF ( OPACBaseURL ) %] + + | OPAC view + + [% END %] +

            + +
            +
            + [% IF ( SEARCH_RESULT.items_count ) %] +
            + [% IF MaxSearchResultsItemsPerRecordStatusCheck && SEARCH_RESULT.items_count > MaxSearchResultsItemsPerRecordStatusCheck %] + + [% tnx('{count} item', '{count} items', SEARCH_RESULT.items_count, {count = SEARCH_RESULT.items_count}) | html %][% IF ( SEARCH_RESULT.availablecount ) %] + , [% SEARCH_RESULT.availablecount | html %] available: [% ELSE %] - [% tnx('{count} item', '{count} items', SEARCH_RESULT.items_count, {count = SEARCH_RESULT.items_count}) | html %][% IF ( SEARCH_RESULT.availablecount ) %], [% SEARCH_RESULT.availablecount | html %] available:[% ELSE %], None available[% END %] + , None available [% END %] -
            - - [% BLOCK search_result_items %] - [% IF status_count == "onloancount" %] - [% IF SEARCH_RESULT.${status_count} > 0 %] -
            [% SEARCH_RESULT.${status_count} | html %] checked out:
            - [% END %] - [% ELSIF status_count == "othercount" %] - [% IF SEARCH_RESULT.${status_count} > 0 %] -
            [% SEARCH_RESULT.${status_count} | html %] unavailable:
            - [% END %] - [% END %] - [% IF SEARCH_RESULT.${items_loop}.size > 0 %] -
              - [% FOREACH items_loo IN SEARCH_RESULT.${items_loop} %] - [% IF item_level_itypes && !noItemTypeImages && items_loo.imageurl %] - [% SET li_class='result_itype_image'%] - [% END %] -
            • - [% IF item_level_itypes && !noItemTypeImages && items_loo.imageurl %] - [% items_loo.description | html %] - [% END %] - [% IF ( items_loo.branchname ) %] - [% items_loo.branchname | html %] - [% END %] - [% IF ( items_loo.location ) %] - [% items_loo.location | html %] - [% END %] - [% IF ( items_loo.collectioncode ) %] - [% items_loo.collectioncode | html %] - [% END %] - - [% IF ( items_loo.itemcallnumber ) %] - [% items_loo.itemcallnumber | html %] - [% END %] -
              - [% IF ( items_loo.withdrawn ) %] - ([% AuthorisedValues.GetDescriptionByKohaField( kohafield => 'items.withdrawn', authorised_value => items_loo.withdrawn ) | html %]) - [% END %] - [% IF ( items_loo.itemlost ) %] - ([% AuthorisedValues.GetDescriptionByKohaField( kohafield => 'items.itemlost', authorised_value => items_loo.itemlost ) | html %]) - [% END %] - [% IF ( items_loo.damaged ) %] - ([% AuthorisedValues.GetDescriptionByKohaField( kohafield => 'items.damaged', authorised_value => items_loo.damaged ) | html %]) - [% END %] - [% IF ( items_loo.intransit ) %] - (In transit) - [% END %] - [% IF ( items_loo.onhold ) %] - (On hold) - [% END %] - [% IF ( items_loo.notforloan ) %] - [% items_loo.notforloan | html %] - [% END %] - [% items_loo.count | html %] -
              - - [% IF status_count == "onloancount" %] - - Due: [% items_loo.due_date | $KohaDates %] - - [% END %] - - [% IF item_level_itypes && items_loo.description %] - [% items_loo.description | html %] - [% END %] -
            • - [% END # /FOREACH other_items_loo %] -
            - [% END # /IF SEARCH_RESULT.${items_loop}.size %] - [% END # /BLOCK search_result_items %] - - [% PROCESS search_result_items status_count="availablecount" items_loop="available_items_loop" %] - - [% PROCESS search_result_items status_count="onloancount" items_loop="onloan_items_loop" %] - - [% PROCESS search_result_items status_count="othercount" items_loop="other_items_loop" %] - - - [% ELSE # /IF ( SEARCH_RESULT.items_count ) %] - - [% IF ( SEARCH_RESULT.ALTERNATEHOLDINGS.size ) %] - Other holdings: -
              - [% FOREACH ALTERNATEHOLDING IN SEARCH_RESULT.ALTERNATEHOLDINGS %] -
            • [% ALTERNATEHOLDING.holding | html %]
            • - [% END %] -
            + + [% ELSE %] + [% tnx('{count} item', '{count} items', SEARCH_RESULT.items_count, {count = SEARCH_RESULT.items_count}) | html %][% IF ( SEARCH_RESULT.availablecount ) %] + , [% SEARCH_RESULT.availablecount | html %] available: [% ELSE %] - No items + , None available [% END %] - [% END # /IF ( SEARCH_RESULT.items_count ) %] -
            -
            -
            -
            - [% END # /IF scan %] - [% INCLUDE 'page-numbers.inc' %] - [% ELSE #/IF total %] - - [% END #/IF total %] + [% END %] +
            + - [% IF ( Koha.Preference('SavedSearchFilters') && CAN_user_parameters_manage_search_filters ) %] - + +
            + +
            + + [% END # /IF scan %] + [% INCLUDE 'page-numbers.inc' %] + [% ELSE #/IF total %] + + [% END #/IF total %] + + [% IF ( Koha.Preference('SavedSearchFilters') && CAN_user_parameters_manage_search_filters ) %] + + [% END %] -
            - - - -
            - -
            - - -
            +
            + + + +
            +
            + + +
            [% END %] - - + + [% MACRO jsinclude BLOCK %] [% Asset.js("js/browser.js") | $raw %] [% Asset.js("js/coce.js") | $raw %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/catalogue/search-history.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/catalogue/search-history.tt index ea0107e203..8a1b840c8d 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/catalogue/search-history.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/catalogue/search-history.tt @@ -5,11 +5,12 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Search history") | html %] › - [% t("Catalog") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Search history") | html %] + › [% t("Catalog") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -31,291 +32,289 @@ [% END #/ WRAPPER sub-header.inc %] [% WRAPPER 'main-container.inc' %] +

            Search history

            -

            Search history

            + [% WRAPPER tabs id= "tabs" %] + [% WRAPPER tabs_nav %] + [% WRAPPER tab_item tabname= "biblio_tab" bt_active= 1 %]Catalog[% END %] + [% WRAPPER tab_item tabname= "authority_tab" %]Authority[% END %] + [% END # /WRAPPER tabs_nav %] - [% WRAPPER tabs id= "tabs" %] - [% WRAPPER tabs_nav %] - [% WRAPPER tab_item tabname= "biblio_tab" bt_active= 1 %] Catalog [% END %] - [% WRAPPER tab_item tabname= "authority_tab" %] Authority [% END %] - [% END # /WRAPPER tabs_nav %] + [% WRAPPER tab_panels %] + [% WRAPPER tab_panel tabname="biblio_tab" bt_active= 1 %] + [% IF ( current_biblio_searches ) %] +

            Current session

            +
            + [% INCLUDE 'csrf-token.inc' %] +

            + Select all visible rows + | + Clear selection on visible rows + | + + Select searches to: + Delete + +

            + + + + + + + + + + + + [% FOREACH s IN current_biblio_searches %] + + + + + + + [% END %] + +
            DateSearchResults
            [% s.time |$KohaDates with_hours => 1 %][% s.query_desc | html %][% s.total | html %]
            +
            + [% END %] - [% WRAPPER tab_panels %] - [% WRAPPER tab_panel tabname="biblio_tab" bt_active= 1 %] - [% IF ( current_biblio_searches ) %] -

            Current session

            -
            - [% INCLUDE 'csrf-token.inc' %] -

            - Select all visible rows - | - Clear selection on visible rows - | - - Select searches to: - Delete - -

            - - - - - - - - - - - - [% FOREACH s IN current_biblio_searches %] - - - - - - - [% END %] - -
            DateSearchResults
            [% s.time |$KohaDates with_hours => 1 %][% s.query_desc | html %][% s.total | html %]
            -
            - [% END %] + [% IF ( current_biblio_searches && previous_biblio_searches) %] +
            + [% END %] - [% IF ( current_biblio_searches && previous_biblio_searches) %] -
            - [% END %] + [% IF ( previous_biblio_searches ) %] +

            Previous sessions

            +
            + [% INCLUDE 'csrf-token.inc' %] +

            + Select all visible rows + | + Clear selection on visible rows + | + + Select searches to: + Delete + +

            + + + + + + + + + + + + [% FOREACH s IN previous_biblio_searches %] + + + + + + + [% END %] + +
            DateSearchResults
            [% s.time |$KohaDates with_hours => 1 %][% s.query_desc | html %][% s.total | html %]
            +
            + [% END %] - [% IF ( previous_biblio_searches ) %] -

            Previous sessions

            -
            - [% INCLUDE 'csrf-token.inc' %] -

            - Select all visible rows - | - Clear selection on visible rows - | - - Select searches to: - Delete - -

            - - - - - - - - - - - - [% FOREACH s IN previous_biblio_searches %] - - - - - - - [% END %] - -
            DateSearchResults
            [% s.time |$KohaDates with_hours => 1 %][% s.query_desc | html %][% s.total | html %]
            -
            - [% END %] + [% IF !current_biblio_searches && !previous_biblio_searches %] +

            Your catalog search history is empty.

            + [% END %] + [% END # /tab_panel#biblio_tab %] - [% IF !current_biblio_searches && !previous_biblio_searches %] -

            Your catalog search history is empty.

            - [% END %] - [% END # /tab_panel#biblio_tab %] + [% WRAPPER tab_panel tabname="authority_tab" %] + [% IF ( current_authority_searches ) %] +

            Current session

            +
            + [% INCLUDE 'csrf-token.inc' %] +

            + Select all visible rows + | + Clear selection on visible rows + | + + Select searches to: + Delete + +

            + + + + + + + + + + + + [% FOREACH s IN current_authority_searches %] + + + + + + + [% END %] + +
            DateSearchResults
            [% s.time |$KohaDates with_hours => 1 %][% s.query_desc | html %][% s.total | html %]
            +
            + [% END %] - [% WRAPPER tab_panel tabname="authority_tab" %] - [% IF ( current_authority_searches ) %] -

            Current session

            -
            - [% INCLUDE 'csrf-token.inc' %] -

            - Select all visible rows - | - Clear selection on visible rows - | - - Select searches to: - Delete - -

            - - - - - - - - - - - - [% FOREACH s IN current_authority_searches %] - - - - - - - [% END %] - -
            DateSearchResults
            [% s.time |$KohaDates with_hours => 1 %][% s.query_desc | html %][% s.total | html %]
            -
            - [% END %] + [% IF ( current_authority_searches && previous_authority_searches) %] +
            + [% END %] - [% IF ( current_authority_searches && previous_authority_searches) %] -
            - [% END %] + [% IF ( previous_authority_searches ) %] +

            Previous sessions

            +
            + [% INCLUDE 'csrf-token.inc' %] +

            + Select all visible rows + | + Clear selection on visible rows + | + + Select searches to: + Delete + +

            + + + + + + + + + + + + [% FOREACH s IN previous_authority_searches %] + + + + + + + [% END %] + +
            DateSearchResults
            [% s.time |$KohaDates with_hours => 1 %][% s.query_desc | html %][% s.total | html %]
            +
            + [% END %] - [% IF ( previous_authority_searches ) %] -

            Previous sessions

            -
            - [% INCLUDE 'csrf-token.inc' %] -

            - Select all visible rows - | - Clear selection on visible rows - | - - Select searches to: - Delete - -

            - - - - - - - - - - - - [% FOREACH s IN previous_authority_searches %] - - - - - - - [% END %] - -
            DateSearchResults
            [% s.time |$KohaDates with_hours => 1 %][% s.query_desc | html %][% s.total | html %]
            -
            - [% END %] - - [% IF !current_authority_searches && !previous_authority_searches %] -

            Your authority search history is empty.

            - [% END %] - [% END # /tab_panel#authority_tab %] - [% END # /WRAPPER tab_panels %] - [% END # /WRAPPER tabs %] + [% IF !current_authority_searches && !previous_authority_searches %] +

            Your authority search history is empty.

            + [% END %] + [% END # /tab_panel#authority_tab %] + [% END # /WRAPPER tab_panels %] + [% END # /WRAPPER tabs %] [% END %] [% MACRO jsinclude BLOCK %] [% INCLUDE 'datatables.inc' %] [% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/catalogue/showelastic.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/catalogue/showelastic.tt index d083c2b88e..c90d443e42 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/catalogue/showelastic.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/catalogue/showelastic.tt @@ -1,25 +1,22 @@ [% INCLUDE 'doc-head-open.inc' %] [% USE raw %] -[% FILTER collapse %] - Elasticsearch record › - [% t("Catalog") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + Elasticsearch record › [% t("Catalog") | html %] › [% t("Koha") | html %] + [% END %] -
            -
            -    
            +
             
            diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/catalogue/showmarc.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/catalogue/showmarc.tt index 4adac534e9..4eaa487684 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/catalogue/showmarc.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/catalogue/showmarc.tt @@ -1,16 +1,17 @@ [% USE raw %] [% PROCESS 'i18n.inc' %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("MARC import") | html %] › - [% t("Cataloging") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("MARC import") | html %] + › [% t("Cataloging") | html %] › [% t("Koha") | html %] + [% END %]
            -
            [% MARC_FORMATTED | html %] 
            +
            [% MARC_FORMATTED | html %] 
            diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/catalogue/stockrotation.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/catalogue/stockrotation.tt index a7e72b5563..1b2e2a861b 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/catalogue/stockrotation.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/catalogue/stockrotation.tt @@ -5,12 +5,13 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% title_in_title = INCLUDE 'biblio-title-head.inc' %] - [% tx("Stock rotation details for {title}", { title = title_in_title }) | html %] › - [% t("Catalog") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% title_in_title = INCLUDE 'biblio-title-head.inc' %] + [% tx("Stock rotation details for {title}", { title = title_in_title }) | html %] + › [% t("Catalog") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -34,161 +35,159 @@ [% END #/ WRAPPER sub-header.inc %] [% WRAPPER 'main-container.inc' aside='biblio-view-menu' %] - -
            - - [% IF no_op_set %] -

            Stock rotation details for [% INCLUDE 'biblio-title.inc' %]

            - [% IF rotas.count > 0 && items.size > 0 %] -
            - - - - - - - - - - - - - - [% FOREACH item IN items %] +
            + [% IF no_op_set %] +

            Stock rotation details for [% INCLUDE 'biblio-title.inc' %]

            + [% IF rotas.count > 0 && items.size > 0 %] +
            +
            + - - - - - - - + + + + + + + - [% END %] - - -
            - [% END %] - [% IF !items || items.size == 0 %] -

            No physical items for this record

            - [% END %] - [% IF !rotas || rotas.count == 0 %] -

            There are no rotas with stages assigned

            - [% END %] - [% ELSIF op == 'confirm_remove_from_rota' %] -
            -

            Are you sure you want to remove this item from it's rota?

            -
            -
            - [% INCLUDE 'csrf-token.inc' %] - - - - - -
            - No + + + [% FOREACH item IN items %] + + [% item.bib_item.barcode | html %] + [% item.bib_item.itemcallnumber | html %] + [% item.rota.title | html %] + + [% IF item.rota %] + [% IF !item.rota.active %] + + Inactive + + [% ELSE %] + Active + [% END %] + [% END %] + + + [% IF item.bib_item.get_transfer %] + Yes + [% ELSE %] + No + [% END %] + + + [% FOREACH this_stage IN item.stages %] + [% SET span_class = 'stage' %] + [% IF this_stage.stage_id == item.stockrotationitem.stage.stage_id %] + [% SET span_class = 'stage highlight_stage' %] + [% END %] + + [% Branches.GetName(this_stage.branchcode_id) | html %] ([% this_stage.duration | html %]) + » + [% END %] + [% IF item.stages.size > 0 %] + [% IF item.rota.cyclical %] + START + [% ELSE %] + END + [% END %] + [% END %] + + + [% IF item.stockrotationitem %] + [% in_transit = item.bib_item.get_transfer %] + [% IF !in_transit && item.stages.size > 1 %] +
            + [% INCLUDE 'csrf-token.inc' %] + + + + + +
            + [% ELSE %] + Move to next stage + [% END %] + + [% IF !in_transit %] +
            + [% INCLUDE 'csrf-token.inc' %] + + + + + +
            + [% ELSE %] + + [% IF item.stockrotationitem.indemand %] + Remove "In demand" + [% ELSE %] + Add "In demand" + [% END %] + + [% END %] + + + + Remove from rota + + [% ELSE %] +
            + [% INCLUDE 'csrf-token.inc' %] + + + + + +
            + [% END %] + + + [% END %] + + +
            + + [% END %] + [% IF !items || items.size == 0 %] +

            No physical items for this record

            + [% END %] + [% IF !rotas || rotas.count == 0 %] +

            There are no rotas with stages assigned

            + [% END %] + [% ELSIF op == 'confirm_remove_from_rota' %] +
            +

            Are you sure you want to remove this item from it's rota?

            +
            +
            + [% INCLUDE 'csrf-token.inc' %] + + + + + +
            + No +
            -
            - [% END %] - -
            - + [% END %] +
            [% END %] [% MACRO jsinclude BLOCK %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/addbiblio.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/addbiblio.tt index ee1354d054..ff3fe9f8d8 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/addbiblio.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/addbiblio.tt @@ -4,15 +4,16 @@ [% USE HtmlTags %] [% PROCESS 'i18n.inc' %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% IF( biblionumber ) %] - [% tx("Editing {title} (Record number {biblionumber})", { title = title, biblionumber = biblionumber }) | html %] - [% ELSE %] - [% t("Add MARC record") | html %] - [% END %] › - [% t("Cataloging") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% IF( biblionumber ) %] + [% tx("Editing {title} (Record number {biblionumber})", { title = title, biblionumber = biblionumber }) | html %] + [% ELSE %] + [% t("Add MARC record") | html %] + [% END %] + › [% t("Cataloging") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] [% INCLUDE 'calendar.inc' %] [% Asset.js( "lib/sortable/Sortable.min.js" ) | $raw %] @@ -29,789 +30,788 @@ [% Asset.js("js/browser.js") | $raw %] [% Asset.css("css/addbiblio.css") | $raw %] -
            -
            Loading, please wait...
            -
            +
            +
            Loading, please wait...
            +
            - [% WRAPPER 'header.inc' %] - [% INCLUDE 'cataloging-search.inc' %] - [% END %] +[% WRAPPER 'header.inc' %] + [% INCLUDE 'cataloging-search.inc' %] +[% END %] [% WRAPPER 'sub-header.inc' %] [% WRAPPER breadcrumbs %] @@ -832,68 +832,76 @@ $(document).ready(function(){ [% END #/ WRAPPER breadcrumbs %] [% END #/ WRAPPER sub-header.inc %] - [% WRAPPER 'main-container.inc' wide_centered => 1 %] - [% IF ( INVALID_METADATA ) %] -
            -

            Errors found

            -

            This record had encoding issues, non-xml characters have been stripped in order to allow editing. Please be cautious when saving that some data may have been removed from the record.

            -
            [% INVALID_METADATA | html %]
            -
            +[% WRAPPER 'main-container.inc' wide_centered => 1 %] + [% IF ( INVALID_METADATA ) %] +
            +

            Errors found

            +

            This record had encoding issues, non-xml characters have been stripped in order to allow editing. Please be cautious when saving that some data may have been removed from the record.

            +
            [% INVALID_METADATA | html %]
            +
            + [% END %] + + [% IF ( Koha.Preference('EnableAdvancedCatalogingEditor') && CAN_user_editcatalogue_advanced_editor ) %] +
            + + +
            + [% END %] + +
            + +

            + [% IF ( biblionumber ) %] + Editing [% title | html | $HtmlTags tag="em" %] (Record number [% biblionumber | html %]) + [% ELSE %] + [% IF (circborrowernumber) %] + Add MARC record (fast cataloging) + [% ELSE %] + Add MARC record + [% END %] + [% END %] +

            + + [% UNLESS ( number ) %] + + [% IF ( duplicatebiblionumber ) %] +
            +

            Duplicate record suspected

            +

            Is this a duplicate of + [% duplicatetitle | html %] + ?

            + [% IF ( CAN_user_editcatalogue_edit_items ) %] +
            + + +
            + [% ELSE %] +
            + + +
            [% END %] - - [% IF ( Koha.Preference('EnableAdvancedCatalogingEditor') && CAN_user_editcatalogue_advanced_editor ) %] -
            - - -
            - [% END %] - -
            - -

            - [% IF ( biblionumber ) %] - Editing [% title | html | $HtmlTags tag="em" %] (Record number [% biblionumber | html %]) +
            + [% IF ( CAN_user_editcatalogue_edit_items ) %] + [% ELSE %] - [% IF (circborrowernumber) %] - Add MARC record (fast cataloging) - [% ELSE %] - Add MARC record - [% END %] + [% END %] -

            - - [% UNLESS ( number ) %] - - [% IF ( duplicatebiblionumber ) %] -
            -

            Duplicate record suspected

            -

            Is this a duplicate of [% duplicatetitle | html %] ?

            - [% IF ( CAN_user_editcatalogue_edit_items ) %] - - - - - [% ELSE %] -
            - - -
            - [% END %] -
            - [% IF ( CAN_user_editcatalogue_edit_items ) %] - - [% ELSE %] - - [% END %] -
            -
            - [% END # /IF duplicatebiblionumber %] - [% END # /UNLESS number %] - - + +
            + + [% END # /IF duplicatebiblionumber %] + [% END # /UNLESS number %] + [% IF ( done ) %] [% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/additem.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/additem.tt index ec5424c8f0..72ec98529e 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/additem.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/additem.tt @@ -7,17 +7,19 @@ [% USE TablesSettings %] [% PROCESS 'i18n.inc' %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Items") | html %] › - [% IF ( biblio.author ) %] - [% tx("{title} by {author}", { title = biblio.title, author = biblio.author }) | html %] - [% ELSE %] - [% biblio.title | html %] - [% END %] - [% tx("(Record #{biblionumber})", { biblionumber = biblio.biblionumber }) | html %] › - [% t("Cataloging") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Items") | html %] + › + [% IF ( biblio.author ) %] + [% tx("{title} by {author}", { title = biblio.title, author = biblio.author }) | html %] + [% ELSE %] + [% biblio.title | html %] + [% END %] + [% tx("(Record #{biblionumber})", { biblionumber = biblio.biblionumber }) | html %] + › [% t("Cataloging") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] [% Asset.css("css/addbiblio.css") | $raw %] [% INCLUDE 'datatables.inc' %] @@ -36,18 +38,18 @@ [% INCLUDE 'str/cataloging_additem.inc' %] [% Asset.js("js/cataloging_additem.js") | $raw %] [% Asset.js("js/form-submit.js") | $raw %] - - + .flatpickr_wrapper { + flex-basis: 50%; + } + @@ -63,339 +65,372 @@ [% WRAPPER breadcrumb_item %] [% IF ( biblio.author ) %] - [% tx('Edit {title} by {author}', { title = biblio.title, author = biblio.author }) | html %] ([% tp('Bibliographic record number', 'Record #') | html %] [% biblio.biblionumber | html %]) + [% tx('Edit {title} by {author}', { title = biblio.title, author = biblio.author }) | html %] + ([% tp('Bibliographic record number', 'Record #') | html %] [% biblio.biblionumber | html %]) [% ELSE %] - [% tx('Edit {title}', title = biblio.title) | html %] ([% tp('Bibliographic record number', 'Record #') | html %] [% biblio.biblionumber | html %]) + [% tx('Edit {title}', title = biblio.title) | html %] + ([% tp('Bibliographic record number', 'Record #') | html %] [% biblio.biblionumber | html %]) [% END %] [% END %] [% WRAPPER breadcrumb_item bc_active= 1 %] - [% tp('Items attached to a bibliographic record', 'Items') | html %] + [% tp('Items attached to a bibliographic record', 'Items') | html %] [% END %] [% END #/ WRAPPER breadcrumbs %] [% END #/ WRAPPER sub-header.inc %] [% WRAPPER 'main-container.inc' wide_full => 1 %] - [% INCLUDE 'messages.inc' %] - [% IF item_doesnt_exist %] - - [% END %] -

            Items for [% biblio.title | html %] [% IF ( biblio.author ) %] by [% biblio.author | html %][% END %] (Record #[% biblio.biblionumber | html %])

            - Jump to add item form - -[% IF ( barcode_not_unique ) %]
            Error saving item: Barcode must be unique.
            [% END %] -[% IF ( no_next_barcode ) %]
            Error saving items: Unable to automatically determine values for barcodes. No item has been inserted.
            [% END %] -[% IF ( book_on_loan ) %]
            Cannot delete: item is checked out.
            [% END %] -[% IF ( book_reserved ) %]
            Cannot delete: item has a waiting hold.
            [% END %] -[% IF ( not_same_branch ) %]
            Cannot delete: The items do not belong to your library.
            [% END %] -[% IF ( linked_analytics ) %]
            Cannot delete: item has linked analytics..
            [% END %] -[% IF last_item_for_hold %]
            Cannot delete: Last item for bibliographic record with biblio-level hold on it.
            [% END %] -[% IF item_not_found %]
            Cannot delete: Item not found.
            [% END %] - -
            - [% IF items %] - [% SET date_fields = [ 'dateaccessioned', 'onloan', 'datelastseen', 'datelastborrowed', 'replacementpricedate' ] %] -
            - - - - - [% FOREACH item_header IN item_header_loop %] - - [% END %] - - - - [% FOREACH item IN items %] - [% SET can_be_edited = ! ( Koha.Preference('IndependentBranches') && ! logged_in_user.is_superlibrarian && item.homebranch != Branches.GetLoggedInBranchname() ) %] - [% SET tr_class = '' %] - [% IF item.itemnumber == itemnumber%] - [% UNLESS can_be_edited %] - [% SET tr_class='active' %] - [% ELSE %] - [% SET tr_class='active editable' %] - [% END %] - [% ELSIF can_be_edited %] - [% SET tr_class='editable' %] - [% END %] - - [% UNLESS can_be_edited %] - - [% ELSE %] - - [% END %] - [% FOREACH header IN item_header_loop %] - [% SET attribute = header.attribute %] - [% SET can_mod = item.nomod ? "nomod" : "canmod" %] - [% IF attribute AND date_fields.grep('^' _ attribute _ '$').size %] - [% IF attribute == 'datelastseen' %] - - [% ELSE %] - - [% END %] - [% ELSIF ( item.$attribute && ( attribute == 'price' || attribute == 'replacementprice' ) ) %] - - [% ELSIF item.$attribute && attribute == 'itemcallnumber' %] - - [% ELSE %] - - [% END %] - [% END %] - - [% END %] - -
              - [% item_header.header_value | html %] -
              -
            - - Actions - - -
            -
            [% item.$attribute | $KohaDates with_hours => 1 %][% item.$attribute | $KohaDates %][% item.$attribute | $Price %][% item.$attribute | html %][% item.$attribute | html %]
            -
            - [% END %] - -
            -
            - [% INCLUDE 'biblio-view-menu.inc' %] -
            -
            - -
            -
            - [% INCLUDE 'csrf-token.inc' %] - - [% IF (popup) %] - - [% END %] - - [% IF op != 'cud-saveitem' %] -

            Add item [% IF (circborrowernumber) %](fast cataloging)[% END %]

            - [% ELSE %] -

            Edit item #[% itemnumber | html %][% IF ( barcode ) %] / Barcode [% barcode | html %][% END %]

            - [% END %] - - [% IF item_templates.owned.count || item_templates.shared.count %] -
            -
            - -
            -
            - -
            -
            - -
            - -
            - -
            - -
            - -
            + [% INCLUDE 'messages.inc' %] + [% IF item_doesnt_exist %] + [% END %] +

            Items for [% biblio.title | html %] [% IF ( biblio.author ) %]by [% biblio.author | html %][% END %] (Record #[% biblio.biblionumber | html %])

            + Jump to add item form -
            - [% PROCESS subfields_for_item subfields => subfields %] -
            - [% IF op != 'add_item' %] - + [% IF ( barcode_not_unique ) %]
            Error saving item: Barcode must be unique.
            [% END %] + [% IF ( no_next_barcode ) %]
            Error saving items: Unable to automatically determine values for barcodes. No item has been inserted.
            [% END %] + [% IF ( book_on_loan ) %]
            Cannot delete: item is checked out.
            [% END %] + [% IF ( book_reserved ) %]
            Cannot delete: item has a waiting hold.
            [% END %] + [% IF ( not_same_branch ) %]
            Cannot delete: The items do not belong to your library.
            [% END %] + [% IF ( linked_analytics ) %] +
            Cannot delete: item has linked analytics..
            [% END %] + [% IF last_item_for_hold %]
            Cannot delete: Last item for bibliographic record with biblio-level hold on it.
            [% END %] + [% IF item_not_found %]
            Cannot delete: Item not found.
            [% END %] -[% IF item_groups.size && op != 'cud-saveitem' && CAN_user_editcatalogue_manage_item_groups %] -
            - Add to item group - [% FOREACH ig IN item_groups %] - - [% END %] -
              -
            1. - - + + + +
            2. + Delete + + [% END %] + [% END %] + [% IF ( OPACBaseURL ) %] +
            3. OPAC view
            4. + [% END %] +
          + + + [% END %] + [% FOREACH header IN item_header_loop %] + [% SET attribute = header.attribute %] + [% SET can_mod = item.nomod ? "nomod" : "canmod" %] + [% IF attribute AND date_fields.grep('^' _ attribute _ '$').size %] + [% IF attribute == 'datelastseen' %] + [% item.$attribute | $KohaDates with_hours => 1 %] + [% ELSE %] + [% item.$attribute | $KohaDates %] + [% END %] + [% ELSIF ( item.$attribute && ( attribute == 'price' || attribute == 'replacementprice' ) ) %] + [% item.$attribute | $Price %] + [% ELSIF item.$attribute && attribute == 'itemcallnumber' %] + [% item.$attribute | html %] + [% ELSE %] + [% item.$attribute | html %] + [% END %] + [% END %] + [% END %] - - - - - - - -
          -
        • - - - Required -
        • -
        • - - -
          Display order must be numerical
          -
        • + +
          - - -[% END %] + + [% END %] -
          [% IF op != 'cud-saveitem' %] - - - - - - - - - -
          - - - Cancel -

          Maximum currently set to 1000. The barcode you enter will be incremented for each additional item.

          -
          + + + + + + + +
          + + + + Cancel +

          Maximum currently set to 1000. The barcode you enter will be incremented for each additional item.

          +
          - - - -
          - Save template -
          - + + + +
          + Save template +
          + +
          + +
          + + + + Required + +
          + +
          + +
          + +
          + + Cancel +
          +
          + [% ELSE %] + [% IF op != 'add_item' %] + + [% END %] + + + Cancel + [% END %]
          + + [%# Fields for fast cataloging %] + + + + + [%# End fields for fast cataloging %] + + + [% INCLUDE 'modals/cataloguing_create_av.inc' %] + + + + - -
          - - - - Required - -
          - -
          - -
          - -
          - - Cancel -
          -
          - - [% ELSE %] - [% IF op != 'add_item' %] - - [% END %] - - - Cancel - [% END %] - - [%# Fields for fast cataloging %] - - - - - [%# End fields for fast cataloging %] - - - - - [% INCLUDE 'modals/cataloguing_create_av.inc' %] - - - - - + + + [% END %] [% MACRO jsinclude BLOCK %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/cataloging-home.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/cataloging-home.tt index 3fbf701cf5..15cdf690cd 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/cataloging-home.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/cataloging-home.tt @@ -5,17 +5,19 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Cataloging") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Cataloging") | html %] + › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] - [% WRAPPER 'header.inc' %] - [% INCLUDE 'cataloging-search.inc' %] - [% END %] +[% WRAPPER 'header.inc' %] + [% INCLUDE 'cataloging-search.inc' %] +[% END %] [% WRAPPER 'sub-header.inc' %] [% WRAPPER breadcrumbs %] @@ -26,244 +28,234 @@ [% END #/ WRAPPER sub-header.inc %] [% WRAPPER 'main-container.inc' %] - [% IF ( CAN_user_editcatalogue_edit_catalogue ) %] -
          - [% IF Koha.Preference( 'EnableAdvancedCatalogingEditor' ) == 1 && CAN_user_editcatalogue_advanced_editor %] - Advanced editor + [% IF ( CAN_user_editcatalogue_edit_catalogue ) %] +
          + [% IF Koha.Preference( 'EnableAdvancedCatalogingEditor' ) == 1 && CAN_user_editcatalogue_advanced_editor %] + Advanced editor + [% END %] +
          + + +
          - [% END # /IF CAN_user_editcatalogue_edit_catalogue %] - -

          Cataloging

          - -
          - -
          - [% IF ( CAN_user_tools_stage_marc_import || CAN_user_tools_manage_staged_marc ) %] -

          Import

          - + +
          + [% IF servers.count > 0 %] +
          + + +
          - -
          - - [% IF ( CAN_user_tools_items_batchmod || CAN_user_tools_items_batchdel || CAN_user_tools_records_batchmod || CAN_user_tools_records_batchdel || CAN_user_tools_marc_modification_templates ) %] -

          Batch editing

          - - [% END %] - - [% IF ( CAN_user_tools_items_batchmod || ( CAN_user_stockrotation_manage_rotas && Koha.Preference('StockRotation') ) ) %] -

          Automation

          -
            - [% IF ( CAN_user_tools_items_batchmod ) %] -
          • - Item modifications by age -
          • - [% END %] - [% IF ( CAN_user_stockrotation_manage_rotas && Koha.Preference('StockRotation') ) %] -
          • - Stock rotation -
          • - [% END %] -
          - [% END %] - -
          - -
          - - [% IF ( CAN_user_tools_label_creator || CAN_user_tools_upload_local_cover_images ) %] -

          Tools

          - - [% END %] - - [% IF ( CAN_user_parameters ) %] -

          Administration

          - - [% END %] - -
          +
          + [% END # /IF servers.count %] +
          + + [% END # /IF CAN_user_editcatalogue_edit_catalogue %] - [%- SET StaffCataloguingHome = AdditionalContents.get( location => "StaffCataloguingHome", lang => lang, library => Branches.GetLoggedInBranchcode ) -%] - [%- FOREACH block IN StaffCataloguingHome.content -%] -
          - [%- block.content | $raw -%] -
          - [%- END -%] +

          Cataloging

          + +
          +
          + [% IF ( CAN_user_tools_stage_marc_import || CAN_user_tools_manage_staged_marc ) %] +

          Import

          + + [% END %] + + [% IF ( CAN_user_tools_export_catalog ) %] +

          Export

          + + [% END %] + + [% IF ( CAN_user_tools_inventory || ( ( Koha.Preference('OpacCatalogConcerns') || Koha.Preference('CatalogConcerns') ) && CAN_user_editcatalogue_edit_catalogue ) ) %] +

          Reports

          +
            + [% IF ( CAN_user_tools_inventory ) %] +
          • + Inventory +
          • + [% END %] + + [% IF ( ( Koha.Preference('OpacCatalogConcerns') || Koha.Preference('CatalogConcerns') ) && CAN_user_editcatalogue_edit_catalogue ) %] +
          • + Catalog concerns +
          • + [% END %] +
          + [% END %] + [% IF ( fast_cataloging && CAN_user_editcatalogue_fast_cataloging ) %] +

          Fast cataloging

          +
            + [% IF ( CAN_user_editcatalogue_fast_cataloging ) %] +
          • + Fast cataloging +
          • + [% END %] +
          + [% END %] +
          + +
          + [% IF ( CAN_user_tools_items_batchmod || CAN_user_tools_items_batchdel || CAN_user_tools_records_batchmod || CAN_user_tools_records_batchdel || CAN_user_tools_marc_modification_templates ) %] +

          Batch editing

          + + [% END %] + + [% IF ( CAN_user_tools_items_batchmod || ( CAN_user_stockrotation_manage_rotas && Koha.Preference('StockRotation') ) ) %] +

          Automation

          +
            + [% IF ( CAN_user_tools_items_batchmod ) %] +
          • + Item modifications by age +
          • + [% END %] + [% IF ( CAN_user_stockrotation_manage_rotas && Koha.Preference('StockRotation') ) %] +
          • + Stock rotation +
          • + [% END %] +
          + [% END %] +
          + +
          + [% IF ( CAN_user_tools_label_creator || CAN_user_tools_upload_local_cover_images ) %] +

          Tools

          + + [% END %] + + [% IF ( CAN_user_parameters ) %] +

          Administration

          + + [% END %] +
          +
          + + [%- SET StaffCataloguingHome = AdditionalContents.get( location => "StaffCataloguingHome", lang => lang, library => Branches.GetLoggedInBranchcode ) -%] + [%- FOREACH block IN StaffCataloguingHome.content -%] +
          [%- block.content | $raw -%]
          + [%- END -%] [% END %] [% MACRO jsinclude BLOCK %] - + /* provide Z3950 search points */ + function GetZ3950Terms(fw){ + var strQuery="&frameworkcode=" + fw; + return strQuery; + } + [% END %] [% INCLUDE 'intranet-bottom.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/concerns.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/concerns.tt index 05ecb68828..315952cb49 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/concerns.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/concerns.tt @@ -7,56 +7,57 @@ [% SET footerjs = 1 %] [% USE TablesSettings %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Catalog concerns") | html %] › - [% t("Cataloging") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Catalog concerns") | html %] + › [% t("Cataloging") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] - [% INCLUDE 'header.inc' %] - [% INCLUDE 'cataloging-search.inc' %] +[% INCLUDE 'header.inc' %] +[% INCLUDE 'cataloging-search.inc' %] - [% WRAPPER 'sub-header.inc' %] - [% WRAPPER breadcrumbs %] - [% WRAPPER breadcrumb_item %] - Cataloging +[% WRAPPER 'sub-header.inc' %] + [% WRAPPER breadcrumbs %] + [% WRAPPER breadcrumb_item %] + Cataloging + [% END %] + [% WRAPPER breadcrumb_item bc_active= 1 %] + Catalog concerns + [% END %] + [% END #/ WRAPPER breadcrumbs %] +[% END #/ WRAPPER sub-header.inc %] + +[% WRAPPER 'main-container.inc' aside='cat-menu' %] +

          Catalog concerns

          + +
          +
          + Include resolved + + [% FOR st IN status %] + | Filter [% st.lib | html %] + [% END %] - [% WRAPPER breadcrumb_item bc_active= 1 %] - Catalog concerns - [% END %] - [% END #/ WRAPPER breadcrumbs %] - [% END #/ WRAPPER sub-header.inc %] +
          - [% WRAPPER 'main-container.inc' aside='cat-menu' %] -

          Catalog concerns

          - -
          -
          - Include resolved - - [% FOR st IN status %] - | Filter [% st.lib | html %] - - [% END %] -
          - - - - - - - - - - - -
          ReportedDetailsTitleStatusActions
          -
          - [% END %] - [% INCLUDE 'modals/display_ticket.inc' %] + + + + + + + + + + +
          ReportedDetailsTitleStatusActions
          +
          +[% END %] +[% INCLUDE 'modals/display_ticket.inc' %] [% MACRO jsinclude BLOCK %] [% INCLUDE 'datatables.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/editor.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/editor.tt index 8a5d6649d2..e6cb5cc169 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/editor.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/editor.tt @@ -3,11 +3,12 @@ [% PROCESS 'i18n.inc' %] [% USE Koha %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Editor") | html %] › - [% t("Cataloging") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Editor") | html %] + › [% t("Cataloging") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] [% Asset.css("css/cateditor.css") | $raw %] [% Asset.css("lib/codemirror/codemirror.min.css") | $raw %] @@ -17,9 +18,9 @@ -
          -
          Loading, please wait...
          -
          +
          +
          Loading, please wait...
          +
          [% WRAPPER 'header.inc' %] [% INCLUDE 'cat-search.inc' %] @@ -43,111 +44,108 @@
          [% INCLUDE 'messages.inc' %] -[% IF Koha.Preference('EnableAdvancedCatalogingEditor') %] -
          - - -
          -[% END %] - -

          Cataloging editor

          - - -
          - -
          - -
          - - - -
          - - -
          - - -
          - - - -
          - [%# CodeMirror instance will be inserted here %] -
          -
          -
          -
          -
          -
          -
          + +

          Cataloging editor

          + +
          + +
          + +
          + + + +
          + + +
          + + +
          + + + +
          + [%# CodeMirror instance will be inserted here %] +
          +
          +
          +
          +
          -
          + +
          -
          - - + + + + - + + + + + + - + + [% MACRO jsinclude BLOCK %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/marc21_field_008_classifications.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/marc21_field_008_classifications.tt index 8b849a8ee7..8d26e05e12 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/marc21_field_008_classifications.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/marc21_field_008_classifications.tt @@ -2,11 +2,12 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("008 builder") | html %] › - [% t("Classifications") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("008 builder") | html %] + › [% t("Classifications") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -15,195 +16,195 @@
          - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
          00-05- Date entered on file[% f1 | html %]
          - -
          - -
          - -
          - -
          - -
          - -
          - -
          - -
          + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
          00-05- Date entered on file[% f1 | html %]
          + +
          + +
          + +
          + +
          + +
          + +
          + +
          + +
          -
          + + [% MACRO jsinclude BLOCK %] [% END %] [% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_100.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_100.tt index 432d6a9125..9587c9dcf3 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_100.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_100.tt @@ -2,838 +2,803 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("UNIMARC field 100 builder") | html %] -[% END %] +[% FILTER collapse %] + [% t("UNIMARC field 100 builder") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] -

          UNIMARC field 100 builder

          -
          -
          - - - - - - - - - -
          - + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - + + + + - - - - + + + + - - - - + + + + - - - - + - [% IF ( f8f ) %] - - [% ELSE %] - - [% END %] + + + + - [% IF ( f8g ) %] - - [% ELSE %] - - [% END %] + + + + - [% IF ( f8h ) %] - - [% ELSE %] - - [% END %] - [% IF ( f8u ) %] - - [% ELSE %] - - [% END %] - [% IF ( f8y ) %] - - [% ELSE %] - - [% END %] - [% IF ( f8z ) %] - - [% ELSE %] - - [% END %] - - - - - - - - - - - - - - - - - - - - + + + + + - - - - + [% IF ( f1250 ) %] + + [% ELSE %] + + [% END %] + + + + - + - [% IF ( f1350 ) %] - - [% ELSE %] - - [% END %] - - - + + + + - - - - + + + - - + +
          + +
          + -
          - +
          + -
          - +
          + -
          - +
          + -
          - +
          + +
          - -
          - -
          + +
          - + -
          - + +
          + +
          - -
          +
          - +
          + + - [% IF ( f15dc ) %] - - [% ELSE %] - - [% END %] - [% IF ( f15ea ) %] - - [% ELSE %] - - [% END %] - [% IF ( f15eb ) %] - - [% ELSE %] - - [% END %] - [% IF ( f15ec ) %] - - [% ELSE %] - - [% END %] - [% IF ( f15ed ) %] - - [% ELSE %] - - [% END %] - [% IF ( f15ee ) %] - - [% ELSE %] - - [% END %] - [% IF ( f15ef ) %] - - [% ELSE %] - - [% END %] - [% IF ( f15eg ) %] - - [% ELSE %] - - [% END %] - [% IF ( f15eh ) %] - - [% ELSE %] - - [% END %] - [% IF ( f15fa ) %] - - [% ELSE %] - - [% END %] - [% IF ( f15ga ) %] - - [% ELSE %] - - [% END %] - [% IF ( f15ha ) %] - - [% ELSE %] - - [% END %] - [% IF ( f15ia ) %] - - [% ELSE %] - - [% END %] - [% IF ( f15ib ) %] - - [% ELSE %] - - [% END %] - [% IF ( f15ic ) %] - - [% ELSE %] - - [% END %] - [% IF ( f15id ) %] - - [% ELSE %] - - [% END %] - [% IF ( f15ie ) %] - - [% ELSE %] - - [% END %] - [% IF ( f15ja ) %] - - [% ELSE %] - - [% END %] - [% IF ( f15jb ) %] - - [% ELSE %] - - [% END %] - [% IF ( f15jc ) %] - - [% ELSE %] - - [% END %] - [% IF ( f15jd ) %] - - [% ELSE %] - - [% END %] - [% IF ( f15je ) %] - - [% ELSE %] - - [% END %] - [% IF ( f15jf ) %] - - [% ELSE %] - - [% END %] - [% IF ( f15jg ) %] - - [% ELSE %] - - [% END %] - [% IF ( f15ka ) %] - - [% ELSE %] - - [% END %] - [% IF ( f15la ) %] - - [% ELSE %] - - [% END %] - [% IF ( f15lb ) %] - - [% ELSE %] - - [% END %] - [% IF ( f15lc ) %] - - [% ELSE %] - - [% END %] - [% IF ( f15ld ) %] - - [% ELSE %] - - [% END %] - [% IF ( f15le ) %] - - [% ELSE %] - - [% END %] - [% IF ( f15lf ) %] - - [% ELSE %] - - [% END %] - [% IF ( f15ma ) %] - - [% ELSE %] - - [% END %] - [% IF ( f15mb ) %] - - [% ELSE %] - - [% END %] - [% IF ( f15na ) %] - - [% ELSE %] - - [% END %] - [% IF ( f15nb ) %] - - [% ELSE %] - - [% END %] - [% IF ( f15nc ) %] - - [% ELSE %] - - [% END %] - [% IF ( f15oa ) %] - - [% ELSE %] - - [% END %] - [% IF ( f15pa ) %] - - [% ELSE %] - - [% END %] - [% IF ( f15zz ) %] - - [% ELSE %] - - [% END %] - -
          -
          - - -
          + + [% MACRO jsinclude BLOCK %] [% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_128a.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_128a.tt index 87586ecec2..f9c83f2859 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_128a.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_128a.tt @@ -2,388 +2,390 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("UNIMARC field 128a builder") | html %] › - [% t("Cataloguing") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("UNIMARC field 128a builder") | html %] + › [% t("Cataloguing") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] -

          UNIMARC field 128a builder

          -
          -
          - - - - -
          - -
          -
          +

          UNIMARC field 128a builder

          + +
          + + + + +
          + +
          +
          + - - -
          + + [% MACRO jsinclude BLOCK %] + + + + + + + [% INCLUDE 'popup-bottom.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_146b.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_146b.tt index 879df10438..b2e5439a69 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_146b.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_146b.tt @@ -1,151 +1,144 @@ [% USE raw %] [% PROCESS 'i18n.inc' %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Framework plugin unimarc_field_146b") | html %] › - [% t("Cataloguing") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Framework plugin unimarc_field_146b") | html %] + › [% t("Cataloguing") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] -
          -

          Framework plugin for UNIMARC 146$b

          +
          +

          Framework plugin for UNIMARC 146$b

          -
          -
          - + +
          + -
          - -
          - -

          A number between 0 and 99 (inclusive)

          -
          +
          + +
          + +

          A number between 0 and 99 (inclusive)

          -
          - -
          - + + [% FOREACH optgroup IN category_optgroups %] + + [% FOREACH option IN optgroup.options %] + [% IF option.value == category %] + + [% ELSE %] + [% END %] - - [% END %] - -
          -
          - -
          - -
          - -
          -
          - -
          - -
          - -
          -
          - -
          - -
          - -
          -
          -
          - -
          - -
          + + [% END %] +
          - +
          - +
          + +
          + +
          +
          + +
          + +
          + +
          +
          +
          + +
          + +
          +
          +
          + + + [% INCLUDE 'select2.inc' %] - - -[% INCLUDE 'popup-bottom.inc' %] + [% INCLUDE 'popup-bottom.inc' %] +
          diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_146c.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_146c.tt index 404b3dd254..efdea28cb6 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_146c.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_146c.tt @@ -1,151 +1,145 @@ [% USE raw %] [% PROCESS 'i18n.inc' %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Framework plugin unimarc_field_146c") | html %] › - [% t("Cataloguing") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Framework plugin unimarc_field_146c") | html %] + › [% t("Cataloguing") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] -
          -

          Framework plugin for UNIMARC 146$c

          +
          +

          Framework plugin for UNIMARC 146$c

          -
          -
          - + +
          + -
          - -
          - -

          A number between 0 and 99 (inclusive)

          -
          +
          + +
          + +

          A number between 0 and 99 (inclusive)

          -
          - -
          - + + [% FOREACH optgroup IN category_optgroups %] + + [% FOREACH option IN optgroup.options %] + [% IF option.value == category %] + + [% ELSE %] + [% END %] - - [% END %] - -
          -
          - -
          - -
          - -
          + + [% END %] +
          +
          -
          - -
          - + + [% FOREACH option IN tessitura_options %] + [% IF option.value == tessitura %] + + [% ELSE %] + [% END %] - -
          + [% END %] +
          +
          -
          - -
          - + + [% FOREACH option IN number_of_hands_or_keys_options %] + [% IF option.value == number_of_hands_or_keys %] + + [% ELSE %] + [% END %] - -
          + [% END %] +
          -
          - -
          - + + [% FOREACH option IN other_options %] + [% IF option.value == other %] + + [% ELSE %] + [% END %] - -
          + [% END %] +
          -
          - - +
          +
          + - + + [% INCLUDE 'select2.inc' %] - - -[% INCLUDE 'popup-bottom.inc' %] + [% INCLUDE 'popup-bottom.inc' %] +
          diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_146d.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_146d.tt index c75f29b644..6dd66ccb26 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_146d.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_146d.tt @@ -1,126 +1,122 @@ [% USE raw %] [% PROCESS 'i18n.inc' %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Framework plugin unimarc_field_146d") | html %] › - [% t("Cataloguing") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Framework plugin unimarc_field_146d") | html %] + › [% t("Cataloguing") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] -
          -

          Framework plugin for UNIMARC 146$d

          +
          +

          Framework plugin for UNIMARC 146$d

          -
          -
          - + +
          + -
          - -
          - -

          A number between 0 and 99 (inclusive)

          -
          +
          + +
          + +

          A number between 0 and 99 (inclusive)

          +
          -
          - -
          - + + [% FOREACH optgroup IN category_optgroups %] + + [% FOREACH option IN optgroup.options %] + [% IF option.value == category %] + + [% ELSE %] + [% END %] - - [% END %] - -
          -
          - -
          - -
          - -

          A number between 0 and 99 (inclusive)

          -
          -
          - -
          - -
          - -
          + + [% END %] +
          -
          - -
          - -
          -
          -
          +
          - +
          -
          +
          + +
          + +
          +
          +
          + +
          + +
          +
          +
          + + + + [% INCLUDE 'select2.inc' %] - - -[% INCLUDE 'popup-bottom.inc' %] + [% INCLUDE 'popup-bottom.inc' %] +
          diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_146e.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_146e.tt index 4c3ff1def5..fe873df072 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_146e.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_146e.tt @@ -1,152 +1,145 @@ [% USE raw %] [% PROCESS 'i18n.inc' %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Framework plugin unimarc_field_146e") | html %] › - [% t("Cataloguing") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Framework plugin unimarc_field_146e") | html %] + › [% t("Cataloguing") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] -
          -

          Framework plugin for UNIMARC 146$e

          +
          +

          Framework plugin for UNIMARC 146$e

          -
          -
          - + +
          + -
          - -
          - -

          A number between 0 and 99 (inclusive)

          -
          +
          + +
          + +

          A number between 0 and 99 (inclusive)

          -
          - -
          - + + [% FOREACH optgroup IN category_optgroups %] + + [% FOREACH option IN optgroup.options %] + [% IF option.value == category %] + + [% ELSE %] + [% END %] - - [% END %] - -
          -
          - -
          - -
          - +
          +
          + +
          + +
          + -
          + [% END %] +
          +
          -
          - -
          - + + [% FOREACH option IN number_of_hands_or_keys_options %] + [% IF option.value == number_of_hands_or_keys %] + + [% ELSE %] + [% END %] - -
          + [% END %] +
          +
          -
          - -
          - + + [% FOREACH option IN other_options %] + [% IF option.value == other %] + + [% ELSE %] + [% END %] - -
          + [% END %] +
          -
          - -
          - + + [% FOREACH option IN other2_options %] + [% IF option.value == other2 %] + + [% ELSE %] + [% END %] - -
          + [% END %] +
          -
          +
          +
          + - - - -
          - - [% INCLUDE 'select2.inc' %] - - - + + +
          +[% INCLUDE 'select2.inc' %] + + [% INCLUDE 'popup-bottom.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_146f.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_146f.tt index 4a0a80bde6..a340e6d226 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_146f.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_146f.tt @@ -1,152 +1,145 @@ [% USE raw %] [% PROCESS 'i18n.inc' %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Framework plugin unimarc_field_146e") | html %] › - [% t("Cataloguing") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Framework plugin unimarc_field_146e") | html %] + › [% t("Cataloguing") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] -
          -

          Framework plugin for UNIMARC 146$f

          +
          +

          Framework plugin for UNIMARC 146$f

          -
          -
          - + +
          + -
          - -
          - -

          A number between 0 and 99 (inclusive)

          -
          +
          + +
          + +

          A number between 0 and 99 (inclusive)

          -
          - -
          - + + [% FOREACH optgroup IN category_optgroups %] + + [% FOREACH option IN optgroup.options %] + [% IF option.value == category %] + + [% ELSE %] + [% END %] - - [% END %] - -
          -
          - -
          - -
          - +
          +
          + +
          + +
          + -
          + [% END %] +
          +
          -
          - -
          - + + [% FOREACH option IN number_of_hands_or_keys_options %] + [% IF option.value == number_of_hands_or_keys %] + + [% ELSE %] + [% END %] - -
          + [% END %] +
          +
          -
          - -
          - + + [% FOREACH option IN other_options %] + [% IF option.value == other %] + + [% ELSE %] + [% END %] - -
          + [% END %] +
          -
          - -
          - + + [% FOREACH option IN other2_options %] + [% IF option.value == other2 %] + + [% ELSE %] + [% END %] - -
          + [% END %] +
          -
          +
          +
          + - - - -
          - - [% INCLUDE 'select2.inc' %] - - - + + +
          +[% INCLUDE 'select2.inc' %] + + [% INCLUDE 'popup-bottom.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_146h.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_146h.tt index cfea53a598..350775c811 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_146h.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_146h.tt @@ -1,69 +1,66 @@ [% USE raw %] [% PROCESS 'i18n.inc' %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Framework plugin unimarc_field_146h") | html %] › - [% t("Cataloguing") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Framework plugin unimarc_field_146h") | html %] + › [% t("Cataloguing") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] -
          -

          Framework plugin for UNIMARC 146$h

          +
          +

          Framework plugin for UNIMARC 146$h

          -
          -
          - + +
          + -
          - -
          - -

          - A number between 0 and 999 (inclusive) -

          -
          +
          + +
          + +

          A number between 0 and 999 (inclusive)

          -
          - -
          - + [% FOREACH option IN options %] + [% IF option.value == category %] + + [% ELSE %] + [% END %] - -
          + [% END %] +
          -
          - - - - -
          - - +
          +
          + + + +
          + [% INCLUDE 'popup-bottom.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_146i.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_146i.tt index cd1f3a0bd1..70c5982d67 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_146i.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_146i.tt @@ -1,69 +1,66 @@ [% USE raw %] [% PROCESS 'i18n.inc' %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Framework plugin unimarc_field_146i") | html %] › - [% t("Cataloguing") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Framework plugin unimarc_field_146i") | html %] + › [% t("Cataloguing") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] -
          -

          Framework plugin for UNIMARC 146$i

          +
          +

          Framework plugin for UNIMARC 146$i

          -
          -
          - + +
          + -
          - -
          - -

          - A number between 0 and 999 (inclusive) -

          -
          +
          + +
          + +

          A number between 0 and 999 (inclusive)

          -
          - -
          - + [% FOREACH option IN options %] + [% IF option.value == category %] + + [% ELSE %] + [% END %] - -
          + [% END %] +
          -
          - - - - -
          - - +
          +
          + + + +
          + [% INCLUDE 'popup-bottom.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_181-2.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_181-2.tt index 498bd97308..5ff336aaa5 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_181-2.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_181-2.tt @@ -1,66 +1,66 @@ [% USE raw %] [% PROCESS 'i18n.inc' %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("UNIMARC field 181-2 builder") | html %] › - [% t("Cataloguing") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("UNIMARC field 181-2 builder") | html %] + › [% t("Cataloguing") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] -

          UNIMARC field 181-2 builder

          +

          UNIMARC field 181-2 builder

          -
          -
          - - - - + +
          - + + + - -
          + -
          - + [% IF ( f0 == "frcarr" ) %] + + [% ELSE %] + + [% END %] + +
          +
          + - - -
          + + - [% INCLUDE 'popup-bottom.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_181a.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_181a.tt index 8ed26aba43..79120a323a 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_181a.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_181a.tt @@ -1,151 +1,150 @@ [% USE raw %] [% PROCESS 'i18n.inc' %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("UNIMARC field 181a builder") | html %] › - [% t("Cataloguing") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("UNIMARC field 181a builder") | html %] + › [% t("Cataloguing") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] -

          UNIMARC field 181a builder

          +

          UNIMARC field 181a builder

          -
          -
          - - - -
          - + + + - - - - + + + + - + [% IF ( f2 == "" ) %] + + [% ELSE %] + + [% END %] + + + +
          + -
          - +
          + -
          + + -
          -
          - - - -
          + + - [% INCLUDE 'popup-bottom.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_181b.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_181b.tt index 5e1294f725..7bbaaa0bcb 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_181b.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_181b.tt @@ -1,259 +1,257 @@ [% USE raw %] [% PROCESS 'i18n.inc' %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("UNIMARC field 181b builder") | html %] › - [% t("Cataloguing") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("UNIMARC field 181b builder") | html %] + › [% t("Cataloguing") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] -

          UNIMARC field 181b builder

          +

          UNIMARC field 181b builder

          -
          -
          - - - - + +
          - + + + - - - - + + + + - - - - + + + + - - - - + + + + + + + + - - - - + + + + - - - - - - -
          + -
          - +
          + -
          - +
          + -
          + [% IF ( f3 == " " ) %] + + [% ELSE %] + + [% END %] + +
          + - [% IF ( f4 == "a" ) %] - - [% ELSE %] - - [% END %] + [% IF ( f4 == "b" ) %] + + [% ELSE %] + + [% END %] - [% IF ( f4 == "b" ) %] - - [% ELSE %] - - [% END %] + [% IF ( f4 == "c" ) %] + + [% ELSE %] + + [% END %] - [% IF ( f4 == "c" ) %] - - [% ELSE %] - - [% END %] + [% IF ( f4 == "d" ) %] + + [% ELSE %] + + [% END %] - [% IF ( f4 == "d" ) %] - - [% ELSE %] - - [% END %] + [% IF ( f4 == "e" ) %] + + [% ELSE %] + + [% END %] - [% IF ( f4 == "e" ) %] - - [% ELSE %] - - [% END %] + [% IF ( f4 == "" ) %] + + [% ELSE %] + + [% END %] + +
          + -
          - +
          + -
          - -
          - - - - - + [% IF ( f6 == "" ) %] + + [% ELSE %] + + [% END %] + +
          +
          + + + - [% INCLUDE 'popup-bottom.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_181c.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_181c.tt index 1686b1a768..3e8d5c2619 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_181c.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_181c.tt @@ -1,195 +1,192 @@ [% USE raw %] [% PROCESS 'i18n.inc' %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("UNIMARC field 181c builder") | html %] › - [% t("Cataloguing") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("UNIMARC field 181c builder") | html %] + › [% t("Cataloguing") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] -

          UNIMARC field 181c builder

          +

          UNIMARC field 181c builder

          -
          -
          - - - - + +
          - + + + - - -
          + -
          - - - - - + [% IF ( f1 == "zzz" ) %] + + [% ELSE %] + + [% END %] + +
          +
          + + + - [% INCLUDE 'popup-bottom.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_182-2.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_182-2.tt index e01094084f..88d7243e2e 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_182-2.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_182-2.tt @@ -1,67 +1,66 @@ [% USE raw %] [% PROCESS 'i18n.inc' %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("UNIMARC field 182-2 builder") | html %] › - [% t("Cataloguing") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("UNIMARC field 182-2 builder") | html %] + › [% t("Cataloguing") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] -

          UNIMARC field 182-2 builder

          +

          UNIMARC field 182-2 builder

          -
          -
          - - - - + +
          - + + + - -
          + -
          - - - - - + [% IF ( f0 == "frcarr" ) %] + + [% ELSE %] + + [% END %] + +
          +
          + + + - [% INCLUDE 'popup-bottom.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_182a.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_182a.tt index 12b7af3a47..b26e3763ab 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_182a.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_182a.tt @@ -1,25 +1,26 @@ [% USE raw %] [% PROCESS 'i18n.inc' %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("UNIMARC field 182a builder") | html %] › - [% t("Cataloguing") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("UNIMARC field 182a builder") | html %] + › [% t("Cataloguing") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] -

          UNIMARC field 182a builder

          +

          UNIMARC field 182a builder

          -
          -
          - - - -
          - + + + - + + + +
          + -
          + + -
          -
          - - - -
          + + - [% INCLUDE 'popup-bottom.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_182c.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_182c.tt index 04dbfafc2a..97b7c64b17 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_182c.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_182c.tt @@ -1,104 +1,102 @@ [% USE raw %] [% PROCESS 'i18n.inc' %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("UNIMARC field 182c builder") | html %] › - [% t("Cataloguing") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("UNIMARC field 182c builder") | html %] + › [% t("Cataloguing") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] -

          UNIMARC field 182c builder

          +

          UNIMARC field 182c builder

          -
          -
          - - - - + +
          - + + + - - -
          + -
          - - - - - + [% IF ( f1 == "z" ) %] + + [% ELSE %] + + [% END %] + +
          +
          + + + - [% INCLUDE 'popup-bottom.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_183-2.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_183-2.tt index 0231344b40..df2b83f359 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_183-2.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_183-2.tt @@ -1,65 +1,65 @@ [% USE raw %] [% PROCESS 'i18n.inc' %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("UNIMARC field 183-2 builder") | html %] › - [% t("Cataloguing") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("UNIMARC field 183-2 builder") | html %] + › [% t("Cataloguing") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] -

          UNIMARC field 183-2 builder

          +

          UNIMARC field 183-2 builder

          -
          -
          - - - - + +
          - + + + - -
          + -
          - - - - - + [% IF ( f0 == "frcarr" ) %] + + [% ELSE %] + + [% END %] + +
          +
          + + + - [% INCLUDE 'popup-bottom.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_183a.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_183a.tt index dd0d076d96..a3dffcfbb6 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_183a.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_183a.tt @@ -1,403 +1,401 @@ [% USE raw %] [% PROCESS 'i18n.inc' %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("UNIMARC field 183a builder") | html %] › - [% t("Cataloguing") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("UNIMARC field 183a builder") | html %] + › [% t("Cataloguing") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] -

          UNIMARC field 183a builder

          -
          -
          - - - + +
          - + + - -
          + -
          - - - - - + + [% IF ( f1 == "zu" ) %] + + [% ELSE %] + + [% END %] + + +
          +
          + + + - [% INCLUDE 'popup-bottom.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_210c.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_210c.tt index f1b9cd0eda..72f3f6320d 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_210c.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/cataloguing/value_builder/unimarc_field_210c.tt @@ -3,92 +3,91 @@ [% PROCESS 'authorities-search-results.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("UNIMARC field 210c builder") | html %] › - [% t("Cataloguing") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("UNIMARC field 210c builder") | html %] + › [% t("Cataloguing") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %]

          UNIMARC field 210c builder

          -

          Search for authority type: PERSO_NAME

          -
          - [% INCLUDE 'csrf-token.inc' %] -
          - - - - - - - - - - -
            -
          1. - - - -
          2. -
          -
          -
          - -
          -
          - [% IF ( total ) %] -

          Authority search results

          -
          - [% pagination_bar | $raw %] -
          [% END %] -

          - [% IF ( total ) %] -  Results [% from | html %] to [% to | html %] of [% total | html %]

          - [% ELSE %] -   No results found
          - [% END %] -

          +

          Search for authority type: PERSO_NAME

          +
          + [% INCLUDE 'csrf-token.inc' %] +
          + + + + + + + + + + +
            +
          1. + + + +
          2. +
          +
          +
          + +
          +
          [% IF ( total ) %] -
          - +

          Authority search results

          +
          [% pagination_bar | $raw %]
          +[% END %] +

          + [% IF ( total ) %] +  Results [% from | html %] to [% to | html %] of [% total | html %]

          + [% ELSE %] +   No results found
          + [% END %] +

          +[% IF ( total ) %] +
          +
          + + + + + + + [% FOREACH resul IN result %] - - - - - - [% FOREACH resul IN result %] - - - - - + + + - - [% END %] -
          SummaryHeading typeUsedGet it!
          SummaryHeading typeUsedGet it!
          [% PROCESS authresult summary=resul.summary authid=resul.authid %][% resul.summary.label | html %][% resul.used | html %] times + [% PROCESS authresult summary=resul.summary authid=resul.authid %][% resul.summary.label | html %][% resul.used | html %] times [% IF ( resul.to_report ) %] [% END %] -
          -
          + + + [% END %] + +
          [% END %] - [% IF ( total ) %]
          - [% pagination_bar | $raw %] -
          - [% END %] +[% IF ( total ) %] +
          [% pagination_bar | $raw %]
          +[% END %] +
          -
          - - + + + + + + [% MACRO jsinclude BLOCK %] [% INCLUDE 'calendar.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/circ/printslip.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/circ/printslip.tt index 1b0fdd3a30..a4d3d52f73 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/circ/printslip.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/circ/printslip.tt @@ -6,35 +6,38 @@ [% UNLESS slips && slips.size %] [% SET slips = [{content => slip, is_html => !plain, style => style, id => id }] %] [% END %] -[% FILTER collapse %] -[% IF ( caller == 'hold-transfer' ) %] - [% t("Hold transfer print receipt") | html %] › - [% t("Circulation") | html %] › -[% ELSIF ( caller == 'transfer' ) %] - [% t("Transfers print receipt") | html %] › - [% t("Circulation") | html %] › -[% ELSIF ( caller == 'members' ) %] - [% tx("Print receipt for {borrowernumber}", { borrowernumber = borrowernumber }) | html %] › - [% t("Patrons") | html %] › -[% ELSIF ( caller == 'recall' ) %] - [% t("Recall print receipt") | html %] › - [% t("Circulation") | html %] › -[% ELSIF ( title ) %][%# FIXME title is never defined %] - [% title | html %] › - [% t("Patrons") | html %] › -[% END %] - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% IF ( caller == 'hold-transfer' ) %] + [% t("Hold transfer print receipt") | html %] + › [% t("Circulation") | html %] › + [% ELSIF ( caller == 'transfer' ) %] + [% t("Transfers print receipt") | html %] + › [% t("Circulation") | html %] › + [% ELSIF ( caller == 'members' ) %] + [% tx("Print receipt for {borrowernumber}", { borrowernumber = borrowernumber }) | html %] + › [% t("Patrons") | html %] › + [% ELSIF ( caller == 'recall' ) %] + [% t("Recall print receipt") | html %] + › [% t("Circulation") | html %] › + [% ELSIF ( title ) %] + [%# FIXME title is never defined %] + [% title | html %] + › [% t("Patrons") | html %] › + [% END %] + [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] [% Asset.css("css/print.css") | $raw %] [% IF ( Koha.Preference('SlipCSS') ) %] - + [% END %] [% FOR slip IN slips %] [% IF slip.style %] - + [% END %] @@ -43,21 +46,23 @@ [% INCLUDE 'slip-print.inc' #printThenClose %] -
          +
          [% FOR slip IN slips %]
          - [% UNLESS slip.is_html %] -
          +            [% UNLESS slip.is_html %]
          +                
                           [% IF ( slip.content ) %][% slip.content | html %][% ELSE %]No slip template found[% END %]
          -            
          - [% ELSE %] - [% IF ( slip.content ) %][% slip.content | $raw %][% ELSE %]No slip template found[% END %] - [% END %] +
          + [% ELSE %] + [% IF ( slip.content ) %][% slip.content | $raw %][% ELSE %]No slip template found[% END %] + [% END %]
          - [% IF slips.size > 1 && !loop.last%] -
          + [% IF slips.size > 1 && !loop.last %] +
          [% END %] [% END %] -
          +
          + [% INCLUDE 'intranet-bottom.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/circ/renew.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/circ/renew.tt index 98224219e7..b16bf80201 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/circ/renew.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/circ/renew.tt @@ -6,11 +6,12 @@ [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% tx("Renew {title}", { title = title }) | html %] › - [% t("Circulation") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% tx("Renew {title}", { title = title }) | html %] + › [% t("Circulation") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -33,214 +34,209 @@ [% SET aside = Koha.Preference('CircSidebar') ? 'circ-nav' : '' %] [% WRAPPER 'main-container.inc' aside=aside %] - [% IF error %] -
          -

          Cannot renew:

          + [% IF error %] +
          +

          Cannot renew:

          - [% IF error == "no_item" %] + [% IF error == "no_item" %] +

          No item matches this barcode

          + [% ELSIF error == "no_checkout" %] +

          [% INCLUDE 'biblio-title.inc' biblio=item.biblio link = 1 %] ( + [% item.barcode | html %] + ) is not checked out to a patron.

          + [% ELSIF error == "too_many" %] +

          [% INCLUDE 'biblio-title.inc' biblio=item.biblio link = 1 %] ( [% item.barcode | html %] ) has been renewed the maximum number of times by [% borrower.firstname | html %] [% borrower.surname | html %] ( + [% borrower.cardnumber | html %] )

          -

          No item matches this barcode

          - - [% ELSIF error == "no_checkout" %] - -

          [% INCLUDE 'biblio-title.inc' biblio=item.biblio link = 1 %] ( [% item.barcode | html %] ) is not checked out to a patron.

          - - [% ELSIF error == "too_many" %] - -

          [% INCLUDE 'biblio-title.inc' biblio=item.biblio link = 1 %] ( [% item.barcode | html %] ) has been renewed the maximum number of times by [% borrower.firstname | html %] [% borrower.surname | html %] ( [% borrower.cardnumber | html %] )

          - - [% IF Koha.Preference('AllowRenewalLimitOverride') %] -
          - [% INCLUDE 'csrf-token.inc' %] - - - - - -
          - [% END %] - - [% ELSIF error == "too_unseen" %] - -

          [% INCLUDE 'biblio-title.inc' biblio=item.biblio %] ( [% item.barcode | html %] ) has been renewed the maximum number of consecutive times without being seen by the library )

          - - [% IF Koha.Preference('AllowRenewalLimitOverride') %] -
          - [% INCLUDE 'csrf-token.inc' %] - - - - -
          - [% END %] - - [% ELSIF error == "too_soon" %] - -

          [% INCLUDE 'biblio-title.inc' biblio=item.biblio link = 1 %] ( [% item.barcode | html %] ) cannot be renewed before [% soonestrenewdate | $KohaDates %].

          - - [% IF Koha.Preference('AllowRenewalLimitOverride') %] -
          - [% INCLUDE 'csrf-token.inc' %] - - - - -
          - [% END %] - - [% ELSIF error == "auto_too_soon" %] - -

          [% INCLUDE 'biblio-title.inc' biblio=item.biblio link = 1 %] ( [% item.barcode | html %] ) has been scheduled for automatic renewal and cannot be renewed before [% soonestrenewdate | $KohaDates %].

          - - [% IF Koha.Preference('AllowRenewalLimitOverride') %] -
          - [% INCLUDE 'csrf-token.inc' %] - - - - -
          - [% END %] - - [% ELSIF error == "auto_too_late" %] - -

          [% INCLUDE 'biblio-title.inc' biblio=item.biblio link = 1 %] ( [% item.barcode | html %] ) has been scheduled for automatic renewal and cannot be renewed anymore since [% latestautorenewdate | $KohaDates %].

          - - [% IF Koha.Preference('AllowRenewalLimitOverride') %] -
          - [% INCLUDE 'csrf-token.inc' %] - - - - -
          - [% END %] - - [% ELSIF error == "auto_account_expired" %] - -

          [% INCLUDE 'biblio-title.inc' biblio=item.biblio link = 1 %] ( [% item.barcode | html %] ) has been scheduled for automatic renewal and cannot be renewed because the patron's account is expired

          - - [% IF Koha.Preference('AllowRenewalLimitOverride') %] -
          - [% INCLUDE 'csrf-token.inc' %] - - - - -
          - [% END %] - - [% ELSIF error == "auto_renew" or error == "auto_too_much_oweing" %] - -

          [% INCLUDE 'biblio-title.inc' biblio=item.biblio link = 1 %] ( [% item.barcode | html %] ) has been scheduled for automatic renewal.

          - - [% IF Koha.Preference('AllowRenewalLimitOverride') %] -
          - [% INCLUDE 'csrf-token.inc' %] - - - - -
          - [% END %] - - [% ELSIF error == "on_reserve" %] - -

          [% INCLUDE 'biblio-title.inc' biblio=item.biblio link = 1 %] ( [% item.barcode | html %] ): This item is on hold for another patron.

          - -
          - [% INCLUDE 'csrf-token.inc' %] - - - -
          - - -
          - - -
          - - [% ELSIF error == "patron_restricted" %] - -

          [% borrower.firstname | html %] [% borrower.surname | html %] ( [% borrower.cardnumber | html %] ) is currently restricted.

          - - [% ELSIF error == "item_denied_renewal" %] - -

          Item is not allowed renewal.

          - - [% ELSIF error == "onsite_checkout" %] -

          Item cannot be renewed because it's an onsite checkout

          - - [% ELSIF error == 'recalled' %] -

          This item has been recalled.

          - - [% ELSE %] - - [% error | html %] - - [% END %] - -
          - - -
          -
          - [% END %] - - [% IF date_due %] -
          -

          Item renewed:

          -

          - [% INCLUDE 'biblio-title.inc' biblio=item.biblio link = 1 %] - ( [% item.barcode | html %] ) - renewed for - [% borrower.firstname | html %] [% borrower.surname | html %] ( [% borrower.cardnumber | html %] ) - now due on [% date_due | $KohaDates as_due_date => 1 %] -

          -
          - [% END %] - - [% UNLESS error %] -
          - [% INCLUDE 'csrf-token.inc' %] - -
          -

          Renew

          - - [% IF Koha.Preference('UnseenRenewals') %] -
          - -
          -
          - - -
          - [% ELSE %] - - - [% END %] + [% IF Koha.Preference('AllowRenewalLimitOverride') %] + + [% INCLUDE 'csrf-token.inc' %] + + - + + + + [% END %] + [% ELSIF error == "too_unseen" %] +

          [% INCLUDE 'biblio-title.inc' biblio=item.biblio %] ( [% item.barcode | html %] ) has been renewed the maximum number of consecutive times without being seen by the library )

          -
          -
          - -
          -
          -
          + [% IF Koha.Preference('AllowRenewalLimitOverride') %] +
          + [% INCLUDE 'csrf-token.inc' %] + + + + +
          + [% END %] + [% ELSIF error == "too_soon" %] +

          [% INCLUDE 'biblio-title.inc' biblio=item.biblio link = 1 %] ( [% item.barcode | html %] ) cannot be renewed before [% soonestrenewdate | $KohaDates %].

          + [% IF Koha.Preference('AllowRenewalLimitOverride') %] +
          + [% INCLUDE 'csrf-token.inc' %] + + + + +
          + [% END %] + [% ELSIF error == "auto_too_soon" %] +

          [% INCLUDE 'biblio-title.inc' biblio=item.biblio link = 1 %] ( [% item.barcode | html %] ) has been scheduled for automatic renewal and cannot be renewed before [% soonestrenewdate | $KohaDates %].

          + [% IF Koha.Preference('AllowRenewalLimitOverride') %] +
          + [% INCLUDE 'csrf-token.inc' %] + + + + +
          + [% END %] + [% ELSIF error == "auto_too_late" %] +

          [% INCLUDE 'biblio-title.inc' biblio=item.biblio link = 1 %] ( [% item.barcode | html %] ) has been scheduled for automatic renewal and cannot be renewed anymore since [% latestautorenewdate | $KohaDates %].

          + + [% IF Koha.Preference('AllowRenewalLimitOverride') %] +
          + [% INCLUDE 'csrf-token.inc' %] + + + + +
          + [% END %] + [% ELSIF error == "auto_account_expired" %] +

          [% INCLUDE 'biblio-title.inc' biblio=item.biblio link = 1 %] ( [% item.barcode | html %] ) has been scheduled for automatic renewal and cannot be renewed because the patron's account is expired

          + + [% IF Koha.Preference('AllowRenewalLimitOverride') %] +
          + [% INCLUDE 'csrf-token.inc' %] + + + + +
          + [% END %] + [% ELSIF error == "auto_renew" or error == "auto_too_much_oweing" %] +

          [% INCLUDE 'biblio-title.inc' biblio=item.biblio link = 1 %] ( [% item.barcode | html %] ) has been scheduled for automatic renewal.

          + + [% IF Koha.Preference('AllowRenewalLimitOverride') %] +
          + [% INCLUDE 'csrf-token.inc' %] + + + + +
          + [% END %] + [% ELSIF error == "on_reserve" %] +

          [% INCLUDE 'biblio-title.inc' biblio=item.biblio link = 1 %] ( [% item.barcode | html %] ): This item is on hold for another patron.

          + +
          + [% INCLUDE 'csrf-token.inc' %] + + + +
          + + +
          + +
          + [% ELSIF error == "patron_restricted" %] +

          [% borrower.firstname | html %] [% borrower.surname | html %] ( [% borrower.cardnumber | html %] ) is currently + restricted.

          + [% ELSIF error == "item_denied_renewal" %] +

          Item is not allowed renewal.

          + [% ELSIF error == "onsite_checkout" %] +

          Item cannot be renewed because it's an onsite checkout

          + [% ELSIF error == 'recalled' %] +

          This item has been recalled.

          + [% ELSE %] + + [% error | html %] [% END %] +
          + + +
          +
          + [% END %] + + [% IF date_due %] +
          +

          Item renewed:

          +

          + [% INCLUDE 'biblio-title.inc' biblio=item.biblio link = 1 %] ( + [% item.barcode | html %] + ) renewed for [% borrower.firstname | html %] [% borrower.surname | html %] ( [% borrower.cardnumber | html %] ) now due + on [% date_due | $KohaDates as_due_date => 1 %] +

          +
          + [% END %] + + [% UNLESS error %] +
          + [% INCLUDE 'csrf-token.inc' %] + +
          +

          Renew

          + + [% IF Koha.Preference('UnseenRenewals') %] +
          + +
          +
          + + +
          + [% ELSE %] + + [% END %] + + + +
          +
          + +
          + +
          +
          +
          + [% END %] [% END %] [% MACRO jsinclude BLOCK %] [% INCLUDE 'calendar.inc' %] [% IF error %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/circ/request-article.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/circ/request-article.tt index ebea690bf0..08b217a5f2 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/circ/request-article.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/circ/request-article.tt @@ -16,11 +16,12 @@ [% SET categories = Categories.all.unblessed %] [% SET columns = ['name', 'address', 'cardnumber', 'dateofbirth', 'category', 'branch', 'phone'] %] [% PROCESS "patron-search.inc" %] -[% FILTER collapse %] - [% t("Request article") | html %] › - [% t("Circulation") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Request article") | html %] + › [% t("Circulation") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -68,7 +69,7 @@ [% END %] - [% WRAPPER 'header.inc' %] +[% WRAPPER 'header.inc' %] [% INCLUDE 'circ-search.inc' %] [% END %] @@ -93,265 +94,250 @@ [% END #/ WRAPPER sub-header.inc %] [% WRAPPER 'main-container.inc' aside='biblio-view-menu' %] +

          Request article from [% INCLUDE 'biblio-title.inc' link = 1 %]

          + [% IF error_message %] +
          + [% SWITCH error_message %] + [% CASE 'article_request_limit_reached' %] +

          Patron reached daily limit.

          + [% CASE 'article_request_unhandled_exception' %] +

          An error has occurred. Check the logs for details.

          + [% END %] +
          + [% END %] + [% UNLESS patron %] +
          + + [% PROCESS patron_search_filters_simple %] + [% PROCESS patron_search_table table_id => 'table_borrowers', open_on_row_click => 1 %] +
          + [% ELSE %] + [% IF biblio.can_article_request( patron ) %] + [% IF article_request_fee > 0 %] +
          Patron will be charged with [% article_request_fee | $Price %] for every request
          + [% END %] +
          + [% INCLUDE 'csrf-token.inc' %] + + + -

          Request article from [% INCLUDE 'biblio-title.inc' link = 1 %]

          - [% IF error_message %] -
          - [% SWITCH error_message %] - [% CASE 'article_request_limit_reached' %]

          Patron reached daily limit.

          - [% CASE 'article_request_unhandled_exception' %]

          An error has occurred. Check the logs for details.

          - [% END %] -
          - [% END %] - [% UNLESS patron %] -
          - - [% PROCESS patron_search_filters_simple %] - [% PROCESS patron_search_table table_id => 'table_borrowers', open_on_row_click => 1 %] -
          - [% ELSE %] - [% IF biblio.can_article_request( patron ) %] - [% IF article_request_fee > 0 %] -
          - Patron will be charged with [% article_request_fee | $Price %] for every request -
          - [% END %] - - [% INCLUDE 'csrf-token.inc' %] - - - +
          + Place article request from [% biblio.title | html %] for [% patron.firstname | html %] [% patron.surname | html %] ( [% patron.cardnumber | html %] ) +
            +
          1. + + +
          2. -
            - Place article request from [% biblio.title | html %] for [% patron.firstname | html %] [% patron.surname | html %] ( [% patron.cardnumber | html %] ) -
              -
            1. - - -
            2. +
            3. + + +
            4. -
            5. - - -
            6. +
            7. + + +
            8. -
            9. - - -
            10. +
            11. + + +
            12. -
            13. - - -
            14. +
            15. + + +
            16. -
            17. - - -
            18. +
            19. + + +
            20. -
            21. - - -
            22. +
            23. + + +
            24. -
            25. - - -
            26. +
            27. + + +
            28. -
            29. - - -
            30. +
            31. + + +
            32. -
            33. - - -
            34. +
            35. + + +
            36. -
            37. - - -
            38. +
            39. + + +
            40. +
            +
            -
          3. - - + [% ELSE %] + [% END %] - -
          4. -
          -
          - - [% SET article_request_type = biblio.article_request_type( patron ) %] - [% IF article_request_type != 'bib_only' %] -
          - - - - - - - - - - - - - - - [% FOREACH item IN biblio.items %] - [% IF item.can_article_request( patron ) %] - - - - - - - - - [% END %] - [% END %] - - [% IF article_request_type != 'item_only' %] - - - - - [% END %] - -
          Select item:
           Item typeBarcodeHome libraryCall numberEnumeration
          - [% IF article_request_type == 'item_only' && !checked %] - [% SET checked = 1 %] - - [% ELSE %] - - [% END %] - - [% ItemTypes.GetDescription( item.itype ) | html %] - - [% item.barcode | html %] - - [% Branches.GetName( item.homebranch ) | html %] - - [% item.itemcallnumber | html %] - - [% item.enumchron | html %] -
          - - - Any item -
          -
          + + [% ItemTypes.GetDescription( item.itype ) | html %] + [% item.barcode | html %] + [% Branches.GetName( item.homebranch ) | html %] + [% item.itemcallnumber | html %] + [% item.enumchron | html %] + + [% END %] [% END %] -

          - -

          -
          - [% ELSE %] - No article requests can be made for this record. - [% END %] - - [% END %] - - [% SET biblio_current_article_requests = Context.Scalar( Context.Scalar( biblio, 'article_requests' ), 'filter_by_current' ) %] - [% IF biblio_current_article_requests.count > 0 && !patron %] -
          - Current article requests - - - - - - - - - - - - - - - - - - - - - - [% FOREACH ar IN biblio_current_article_requests %] + [% IF article_request_type != 'item_only' %] - - - - - - - - - - - - - - - + [% END %] -
          Placed onPatronTitleAuthorVolumeIssueDateTOCPagesChaptersPatron notesFormatItemStatusPickup library 
          [% ar.created_on | $KohaDates %][% ar.borrower.firstname | html %] [% ar.borrower.surname | html %][% ar.title | html %][% ar.author | html %][% ar.volume | html %][% ar.issue | html %][% ar.date | html %][% IF ar.toc_request %]Yes[% END %][% ar.pages | html %][% ar.chapters | html %][% ar.patron_notes | html %][% IF ar.format == 'PHOTOCOPY' %]Copy[% ELSIF ar.format == 'SCAN' %]Scan[% END %] - [% IF ar.item %] - [% ar.item.barcode | html %] - [% END %] - - [% IF ar.status == 'PENDING' %] - Pending - [% ELSIF ar.status == 'PROCESSING' %] - Processing - [% ELSIF ar.status == 'REQUESTED' %] - New - [% ELSIF ar.status == 'COMPLETED' %] - Completed - [% ELSIF ar.status == 'CANCELED' %] - Canceled - [% END %] - - - - - - - - + Any item
          -
          - [% PROCESS cancel_modal %] - [% END %] + + + [% END %] + +

          + +

          + + [% ELSE %] + No article requests can be made for this record. + [% END %] + [% END %] + + [% SET biblio_current_article_requests = Context.Scalar( Context.Scalar( biblio, 'article_requests' ), 'filter_by_current' ) %] + [% IF biblio_current_article_requests.count > 0 && !patron %] +
          + Current article requests + + + + + + + + + + + + + + + + + + + + + + [% FOREACH ar IN biblio_current_article_requests %] + + + + + + + + + + + + + + + + + + + [% END %] +
          Placed onPatronTitleAuthorVolumeIssueDateTOCPagesChaptersPatron notesFormatItemStatusPickup library 
          [% ar.created_on | $KohaDates %][% ar.borrower.firstname | html %] [% ar.borrower.surname | html %][% ar.title | html %][% ar.author | html %][% ar.volume | html %][% ar.issue | html %][% ar.date | html %][% IF ar.toc_request %]Yes[% END %][% ar.pages | html %][% ar.chapters | html %][% ar.patron_notes | html %][% IF ar.format == 'PHOTOCOPY' %]Copy[% ELSIF ar.format == 'SCAN' %]Scan[% END %] + [% IF ar.item %] + [% ar.item.barcode | html %] + [% END %] + + [% IF ar.status == 'PENDING' %] + Pending + [% ELSIF ar.status == 'PROCESSING' %] + Processing + [% ELSIF ar.status == 'REQUESTED' %] + New + [% ELSIF ar.status == 'COMPLETED' %] + Completed + [% ELSIF ar.status == 'CANCELED' %] + Canceled + [% END %] + + + + + + + + +
          +
          + [% PROCESS cancel_modal %] + [% END %] [% END %] [% MACRO jsinclude BLOCK %] [% INCLUDE 'datatables.inc' %] [% INCLUDE 'select2.inc' %] - - [% PROCESS patron_search_js table_id => 'table_borrowers', categories => categories, libraries => libraries, columns => columns, open_on_row_click => 1, on_click_url => '/cgi-bin/koha/circ/request-article.pl?biblionumber=' _ biblio.biblionumber, redirect_if_one_result => 1, redirect_url => '/cgi-bin/koha/circ/request-article.pl?biblionumber=' _ biblio.biblionumber %] - [% END %] [% INCLUDE 'intranet-bottom.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/circ/reserveratios.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/circ/reserveratios.tt index 5044527f98..6282468516 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/circ/reserveratios.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/circ/reserveratios.tt @@ -9,16 +9,23 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Hold ratios") | html %] › - [% t("Circulation") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Hold ratios") | html %] + › [% t("Circulation") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -44,161 +51,165 @@
          [% INCLUDE 'messages.inc' %] -

          Hold ratios to calculate items needed

          -

          Calculated on [% todaysdate | $KohaDates %]. From [% from | $KohaDates %] - to [% to | $KohaDates %]

          -

          These items have a hold ratio ≥ [% ratio | html %].

          -
          [% sql | html %]
          +

          Hold ratios to calculate items needed

          +

          Calculated on [% todaysdate | $KohaDates %]. From [% from | $KohaDates %] to [% to | $KohaDates %]

          +

          These items have a hold ratio ≥ [% ratio | html %].

          +
          [% sql | html %]
          -[% IF ( reserveloop ) %] -
          - - - - - - - - - - - - - - - - - - [% FOREACH reserveloo IN reserveloop %] - - - - - - -
          HoldsItemsHold ratioTitleHome librariesHolding librariesLocationItypeCollectionCall numbersItems needed

          [% reserveloo.reservecount | html %]

          [% reserveloo.itemcount | html %]

          [% reserveloo.thisratio | html %] - [% INCLUDE 'biblio-title.inc' biblio=reserveloo link = 1 %][% IF ( reserveloo.author ) %] by [% reserveloo.author | html %][% END %] - -
            - [% FOREACH homebranch IN reserveloo.homebranch_list %] -
          • [% Branches.GetName ( homebranch ) | html %]
          • + [% IF ( reserveloop ) %] +
            + + + + + + + + + + + + + + + + + + [% FOREACH reserveloo IN reserveloop %] + + + + + + + + + + + + + [% END %] - - - - - - - - - + +
            HoldsItemsHold ratioTitleHome librariesHolding librariesLocationItypeCollectionCall numbersItems needed

            [% reserveloo.reservecount | html %]

            [% reserveloo.itemcount | html %]

            [% reserveloo.thisratio | html %] [% INCLUDE 'biblio-title.inc' biblio=reserveloo link = 1 %][% IF ( reserveloo.author ) %]by [% reserveloo.author | html %][% END %] +
              + [% FOREACH homebranch IN reserveloo.homebranch_list %] +
            • [% Branches.GetName ( homebranch ) | html %]
            • + [% END %] +
            +
            +
              + [% FOREACH holdingbranch IN reserveloo.holdingbranch_list %] +
            • [% Branches.GetName ( holdingbranch ) | html %]
            • + [% END %] +
            +
            +
              + [% FOREACH location IN reserveloo.location %] +
            • [% AuthorisedValues.GetDescriptionByKohaField( kohafield => 'items.location', authorised_value => location ) | html %]
            • + [% END %] +
            +
            +
              + [% FOREACH itype IN reserveloo.itype %] +
            • [% ItemTypes.GetDescription( itype ) | html %]
            • + [% END %] +
            +
            +
              + [% FOREACH ccode IN reserveloo.ccode %] +
            • [% AuthorisedValues.GetDescriptionByKohaField( kohafield => 'items.ccode', authorised_value => ccode ) | html %]
            • + [% END %] +
            +
            +
              + [% FOREACH listcall IN reserveloo.listcall %] +
            • [% listcall | html %]
            • + [% END %] +
            +
            +

            + [% IF ( reserveloo.thisratio_atleast1 ) %] + [% IF ( CAN_user_acquisition && basketno && booksellerid ) %] + + [% reserveloo.copies_to_buy | html %] to order + [% ELSE %] + [% reserveloo.copies_to_buy | html %] to order + [% END %] + [% IF ( reserveloo.pendingorders ) %]
            [% reserveloo.pendingorders | html %] pending[% END %] + [% ELSE %] + 0 to order + [% END %] +

            +
            -
              - [% FOREACH holdingbranch IN reserveloo.holdingbranch_list %] -
            • [% Branches.GetName ( holdingbranch ) | html %]
            • - [% END %] -
            -
            -
              - [% FOREACH location IN reserveloo.location %] -
            • [% AuthorisedValues.GetDescriptionByKohaField( kohafield => 'items.location', authorised_value => location ) | html %]
            • - [% END %] -
            -
            -
              - [% FOREACH itype IN reserveloo.itype %] -
            • [% ItemTypes.GetDescription( itype ) | html %]
            • - [% END %] -
            -
            -
              - [% FOREACH ccode IN reserveloo.ccode %] -
            • [% AuthorisedValues.GetDescriptionByKohaField( kohafield => 'items.ccode', authorised_value => ccode ) | html %]
            • - [% END %] -
            -
            -
              - [% FOREACH listcall IN reserveloo.listcall %] -
            • [% listcall | html %]
            • - [% END %] -
            -
            -

            - [% IF ( reserveloo.thisratio_atleast1 ) %] - [% IF ( CAN_user_acquisition && basketno && booksellerid ) %] - [% reserveloo.copies_to_buy | html %] to order - [% ELSE %] - [% reserveloo.copies_to_buy | html %] to order - [% END %] - [% IF ( reserveloo.pendingorders ) %]
            [% reserveloo.pendingorders | html %] pending[% END %] - [% ELSE %] - 0 to order - [% END %] -

            -
            +
            + + [% ELSE %] + No items found. [% END %] -
          -
          -[% ELSE %] - No items found. -[% END %] -
          - + +
          -
          - - + + + + + + [% MACRO jsinclude BLOCK %] [% INCLUDE 'calendar.inc' %] @@ -206,18 +217,18 @@ [% INCLUDE 'columns_settings.inc' %] + $(document).ready(function() { + KohaTable("holds-ratios", { + "order": [ [2,'desc'], [3,'asc'] ], + "columnDefs": [ + { "type": "anti-the", "targets": [ "anti-the" ] }, + { "type": "natural", "targets": [ "natural" ] }, + ], + "pagingType": "full", + "autoWidth": false + }, table_settings); + }); + [% END %] [% INCLUDE 'intranet-bottom.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/circ/returns.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/circ/returns.tt index 14e722d741..39c7500712 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/circ/returns.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/circ/returns.tt @@ -11,15 +11,16 @@ [% SET footerjs = 1 %] [% BLOCK display_bormessagepref %] [% IF ( bormessagepref ) %] -
        • Patron notification: +
        • Patron notification: [% FOREACH mtt IN bormessagepref.keys %] - [%~ IF ( mtt == 'email' ) %] Email[% END ~%] - [%~ IF ( mtt == 'phone' ) %] Phone[% END ~%] - [%~ IF ( mtt == 'sms' ) %] SMS[% END ~%] - [%~ UNLESS loop.last %], [% ELSE %].[% END ~%] + [%~ IF ( mtt == 'email' ) %]Email[% END ~%] + [%~ IF ( mtt == 'phone' ) %]Phone[% END ~%] + [%~ IF ( mtt == 'sms' ) %]SMS[% END ~%] + [%~ UNLESS loop.last %],[% ELSE %].[% END ~%] [% END %]
        • - [% ELSE %] + [% ELSE %]
        • Patron is not notified.
        • [% END %] [% END %] @@ -29,1399 +30,1438 @@ [% END %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% tx("Check in {title}", { title = title }) | html %] › - [% t("Circulation") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% tx("Check in {title}", { title = title }) | html %] + › [% t("Circulation") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] - + - [% WRAPPER 'header.inc' %] - [% INCLUDE 'checkin-search.inc' %] +[% WRAPPER 'header.inc' %] + [% INCLUDE 'checkin-search.inc' %] +[% END %] + +[% WRAPPER 'sub-header.inc' %] + [% WRAPPER breadcrumbs %] + [% WRAPPER breadcrumb_item %] + Circulation + [% END %] + [% WRAPPER breadcrumb_item bc_active= 1 %] + Check in + [% END %] + [% END #/ WRAPPER breadcrumbs %] +[% END #/ WRAPPER sub-header.inc %] + +[% SET aside = Koha.Preference('CircSidebar') ? 'circ-nav' : '' %] +[% WRAPPER 'main-container.inc' aside=aside %] + + [% BLOCK all_checkin_messages %] + [% IF hold_auto_filled %] +
          + [% IF ( reservenotes ) %] +

          Notes: [% reservenotes | html %]

          + [% END %] +

          Hold filled for:

          +
            +
          • + [% INCLUDE 'patron-title.inc' patron=patron hide_patron_infos_if_needed=1 invert_name=1 %] + - [% patron.category.description | html %] +
          • + + [% INCLUDE display_holdpatron_address %] + + [% IF ( patron.phone ) %] +
          • [% patron.phone | html %]
          • + [% END %] + + [% IF ( patron.email ) %] +
          • + [% IF ( transfertodo ) %] + [% patron.email | html %] + [% ELSE %] + [% patron.email | html %] + [% END %] +
          • + [% END %] + + [% UNLESS ( transfertodo) %] + [% INCLUDE display_bormessagepref %] + [% END %] + + [% IF ( patron.is_debarred ) %] +
          • Patron is RESTRICTED
          • + [% END %] + + [% IF ( patron.gonenoaddress ) %] +
          • Patron's address is in doubt
          • + [% END %] +
          + + [% IF ( transfertodo ) %] +

          Transfer to: [% Branches.GetName( destbranch ) | html %]

          + [% ELSE %] +

          Hold at [% Branches.GetName( destbranch ) | html %]

          + [% END %] + + Print +
          + + [% END # /IF hold_auto_filled %] + + [% IF ( trigger && !transfertodo ) %] +
          +

          Reason for transfer

          +

          + [%- SWITCH trigger -%] + + [%- CASE 'Manual' -%] + Manual + [%- CASE 'StockrotationAdvance' -%] + Stock rotation advance + [%- CASE 'StockrotationRepatriation' -%] + Stock rotation repatriation + [%- CASE 'ReturnToHome' -%] + Return to home library + [%- CASE 'ReturnToHolding' -%] + Return to holding library + [%- CASE 'RotatingCollection' -%] + Rotating collection + [%- CASE 'Reserve' -%] + Hold + [%- CASE 'LostReserve' -%] + Lost hold + [%- CASE 'CancelReserve' -%] + Cancelled hold + [%- CASE 'TransferCancellation' -%] + Transfer was cancelled whilst in transit + [%- CASE 'Recall' -%] + Recall + [%- CASE 'RecallCancellation' -%] + Cancelled recall + [%- END -%] +

          +
          + [% END %] + + [% IF privacy == 2 AND NOT Koha.Preference('AnonymousPatron') %] +
          + Error: + This patron has requested their circulation history be anonymized on check-in, but the AnonymousPatron system preference is empty or incorrect. +
          + [% ELSIF NOT Koha.Preference('AnonymousPatron') AND Koha.Preference('OPACPrivacy') %] +
          + Error: + The system preference OPACPrivacy is set but AnonymousPatron is not! Please correct this before continuing circulation. +
          + [% END %] + + [% IF additional_materials && !needs_confirm && !multiple_confirmed %] +
          + Note about the accompanying materials: + [% additional_materials | html %] +
          + [% END %] + + [% IF ( collectionItemNeedsTransferred ) %] +
          +

          Please transfer item to: [% Branches.GetName( collectionBranch ) | html %]

          +

          [% item.barcode | html %]: [% title | html %]

          +

          This item is part of a rotating collection.

          +

          +
          + [% END %] + + + [% IF ( issue.note) %] +
          +

          Patron note

          +

          [% issue.notedate | $KohaDates %]

          +

          [% title | html %] [% author | html %]

          +

          [% issue.note | html %]

          +
          + [% END %] + + + [% IF ( fines ) %] +
          +

          Patron has outstanding fines of [% fines | html %].

          +

          Make payment.

          +
          + [% END %] + + + [% IF ( ClaimAutoResolved ) %] +
          +

          The previously claimed returned item has been found, automatically resolving the associated claim.

          +
          + [% ELSIF( ReturnClaims ) %] +
          +

          This item has been claimed as returned by:

          +
            + [% FOREACH rc IN ReturnClaims %] +
          • + [% INCLUDE 'patron-title.inc' patron=rc.patron hide_patron_infos_if_needed=1 invert_name=1 %] + Resolve +
          • + [% END %] +
          +
          + [% END %] + + + [% IF ( waiting_holds ) %] +
          +

          [% INCLUDE 'patron-title.inc' patron=issue.patron hide_patron_infos_if_needed=1 invert_name=1 %] has [% waiting_holds | html %] hold(s) waiting for pickup.

          +

          Check out to this patron.

          +
          + [% END %] + + + [% IF return_date_was_overriden && issue.patron.is_debarred %] +
          +

          [% INCLUDE 'patron-title.inc' patron=issue.patron hide_patron_infos_if_needed=1 invert_name=1 %] is restricted. Please verify this patron should still be restricted.

          +
          + [% END %] + + + [% IF missing_items %] +
          +

          Bundle had missing items

          +

          Bundle contents list updated

          +

          + View updated contents list + View list of missing items +

          +
          + [% END %] + + + [% IF unexpected_items %] +
          +

          Bundle had unexpected items

          +

          Please place the following items to one side

          +
            + [% FOREACH unexpected_item IN unexpected_items %] +
          • [% INCLUDE 'biblio-title.inc' biblio=unexpected_item.biblio %] - [% unexpected_item.barcode | html %]
          • + [% END %] +
          +
          + [% END %] + + + [% IF InBundle %] +
          +

          Item belongs in bundle

          +

          This item belongs to a bundle: [% INCLUDE 'biblio-title.inc' biblio=InBundle.biblio %] - [% InBundle.barcode | html %]

          +

          +
          + [% END %] + + [% IF ( errmsgloop ) %] +
          +

          Check in message

          + [% IF itembiblionumber %] +

          [% item.barcode | html %]: [% title | html %]

          + [% END %] + [% FOREACH errmsgloo IN errmsgloop %] + [% IF ( errmsgloo.NotForLoanStatusUpdated ) %] +

          + [% IF errmsgloo.NotForLoanStatusUpdated.to == 'ONLYMESSAGE' %] + [% AuthorisedValues.GetByCode( 'NOT_LOAN', errmsgloo.NotForLoanStatusUpdated.from ) | html %] + [% ELSE %] + Not for loan status updated. +
          Old value: + [% IF errmsgloo.NotForLoanStatusUpdated.from %] + [% AuthorisedValues.GetDescriptionByKohaField( kohafield => 'items.notforloan', authorised_value => errmsgloo.NotForLoanStatusUpdated.from ) | html %]. + [% ELSE %] + Available for loan. + [% END %]
          New value: + [% IF errmsgloo.NotForLoanStatusUpdated.to %] + [% AuthorisedValues.GetDescriptionByKohaField( kohafield => 'items.notforloan', authorised_value => errmsgloo.NotForLoanStatusUpdated.to ) | html %]. + [% ELSE %] + Available for loan. + [% END %] + [% END %] +

          + [% END %] + [% IF ( errmsgloo.ItemLocationUpdated ) %] +

          + Item shelving location updated. +
          Old value: + [% IF errmsgloo.ItemLocationUpdated.from %] + [% SET av_description = AuthorisedValues.GetDescriptionByKohaField( kohafield => 'items.location', authorised_value => errmsgloo.ItemLocationUpdated.from ) %] + [% IF errmsgloo.ItemLocationUpdated.from == '' %] + empty + [% ELSIF av_description == '' %] + [% errmsgloo.ItemLocationUpdated.from | html %] + (No description available) + [% ELSE %] + [% av_description | html %] + [% END %] + [% ELSE %] + "Blank" + [% END %] +
          New value: + [% IF errmsgloo.ItemLocationUpdated.to %] + [% SET av_description = AuthorisedValues.GetDescriptionByKohaField( kohafield => 'items.location', authorised_value => errmsgloo.ItemLocationUpdated.to ) %] + [% IF errmsgloo.ItemLocationUpdated.to == '' %] + empty + [% ELSIF av_description == '' %] + [% errmsgloo.ItemLocationUpdated.to | html %] + (Not an authorized value) + [% ELSE %] + [% av_description | html %] + [% END %] + [% ELSE %] + "Blank" + [% END %] +

          + [% END %] + [% IF ( errmsgloo.badbarcode ) %] +

          No item with barcode: [% errmsgloo.msg | html %]

          + [% END %] + [% IF ( errmsgloo.notissued ) %] +

          Not checked out.

          + [% END %] + [% IF ( errmsgloo.localuse) %] +

          Local use recorded

          + [% END %] + [% IF ( errmsgloo.transferred ) %] +

          Item received from [% Branches.GetName( errmsgloo.transferred ) | html %]

          + [% END %] + [% IF ( errmsgloo.waslost ) %] + [% IF Koha.Preference('BlockReturnOfLostItems') %] +

          Item is lost, cannot be checked in.

          + [% ELSE %] +

          Item was lost, now found.

          + [% END %] + [% IF LostItemFeeRefunded and not Koha.Preference('BlockReturnOfLostItems') %] +

          A refund for the lost item charge has been applied to the borrowing patron's account.

          + [% ELSIF LostItemFeeCharged and not Koha.Preference('BlockReturnOfLostItems') %] +

          A refund for the lost item charge has been applied to the borrowing patron's account, and new overdue charge has been calculated and applied.

          + [% ELSIF LostItemFeeRestored and not Koha.Preference('BlockReturnOfLostItems') %] +

          A refund for the lost item charge has been applied to the borrowing patron's account and if an overdue fine was forgiven when the item was marked as lost, it has been reverted.

          + [% ELSIF LostItemPaymentNotRefunded and not Koha.Preference('BlockReturnOfLostItems') %] +

          No refund was applied to the patron's account for the previously paid lost item charge as the payment was made more than [% Koha.Preference('NoRefundOnLostFinesPaidAge') | html %] days ago.

          + [% ELSIF Koha.Preference('BlockReturnOfLostItems') %] +
          Cannot check in
          +

          NOT CHECKED IN

          + [% ELSE %] +

          Any lost item fees for this item will remain on the patron's account.

          + [% END %] + [% IF ProcessingFeeRefunded and not Koha.Preference('BlockReturnOfLostItems') %] +

          A refund for the lost item processing charge has been applied to the borrowing patron's account.

          + [% ELSE %] +

          Any processing fees for this item will remain on the patron's account.

          + [% END %] + [% END %] + [% IF ( errmsgloo.withdrawn ) %] + [% IF Koha.Preference('BlockReturnOfWithdrawnItems') %] +
          Cannot check in
          +

          NOT CHECKED IN

          + [% END %] +

          + Item has been withdrawn + [% item_withdrawn_lib = AuthorisedValues.GetDescriptionByKohaField( kohafield => 'items.withdrawn', authorised_value => item.withdrawn ) %] + [% IF (item_withdrawn_lib) %]([% item_withdrawn_lib | html %])[% END %] +

          + [% END %] + [% IF ( errmsgloo.debarred ) %] +

          [% errmsgloo.debarname | html %]([% errmsgloo.debarcardnumber | html %]) is now debarred until + [% errmsgloo.debarred | $KohaDates %].

          + [% END %] + [% IF ( errmsgloo.prevdebarred ) %] +

          Reminder: Patron was earlier restricted until [% errmsgloo.prevdebarred | $KohaDates %].

          + [% END %] + [% IF ( errmsgloo.foreverdebarred ) %] +

          Reminder: Patron has an indefinite restriction.

          + [% END %] + [% IF errmsgloo.data_corrupted %] +

          The item has not been checked in due to a configuration issue in your system. You must ask an administrator to take a look at the about page and correct all + errors shown on the "System information" tab

          + [% END %] + [% END # /FOREACH errmsgloo %] +
          + + [% END #/IF errmsgloop %] + + [% IF ( checkinmsg ) %] + [% IF ( checkinmsgtype == 'alert' ) %] + [% SET div_class='warning' %] + [% ELSE %] + [% SET div_class='info' %] + [% END %] +
          +

          [% checkinmsg | html_line_break %]

          +
          + [% END # /IF checkinmsg %] + + [% IF bundle_items && !missing_items %] +
          +

          Bundle verified

          +

          The bundle content was verified

          +

          View contents list

          +
          + [% END %] + [% END # /BLOCK all_checkin_messages %] + + [% IF needs_confirm %] + [% END %] - [% WRAPPER 'sub-header.inc' %] - [% WRAPPER breadcrumbs %] - [% WRAPPER breadcrumb_item %] - Circulation - [% END %] - [% WRAPPER breadcrumb_item bc_active= 1 %] - Check in - [% END %] - [% END #/ WRAPPER breadcrumbs %] - [% END #/ WRAPPER sub-header.inc %] - - [% SET aside = Koha.Preference('CircSidebar') ? 'circ-nav' : '' %] - [% WRAPPER 'main-container.inc' aside=aside %] - - [% BLOCK all_checkin_messages %] - [% IF hold_auto_filled %] -
          - [% IF ( reservenotes ) %] -

          Notes: [% reservenotes | html %]

          + [% IF items_bundle_return_confirmation %] + + [% END %] + + [% IF wrongbranch %] + + + [% END # /IF wrongbranch %] + + + [% UNLESS ( hold_auto_filled && diffbranch ) %] + [% IF WrongTransfer && !transfertodo %] + [% IF Koha.Preference('TransfersBlockCirc') %] + [% SET div_class='block' %] + [% ELSE %] + [% SET div_class='noblock' %] + [% END %] + + + [% END # /IF WrongTransfer && !transfertodo %] + [% END # /UNLESS hold_auto_filled && diffbranch %] + + [% IF ( found ) %] + [% IF ( waiting ) %] + + + [% END # /IF waiting %] + + [% IF (transfer || needstransfer) && !(reserved and !recalled and !waitingrecall) %] + [% IF Koha.Preference('TransfersBlockCirc') %] + [% SET div_class='block' %] + [% ELSE %] + [% SET div_class='noblock' %] + [% END %] + + + [% END # /IF transfer || needstransfer %] + + + [% IF ( reserved and !recalled and !waitingrecall ) %] + + + [% END # /IF riloop %] +[% END %] - [% END %] +[% IF ( ReturnClaims ) %] + [% INCLUDE 'modals/resolve_return_claim.inc' %] +[% END %] - [% IF ( ReturnClaims ) %] - [% INCLUDE 'modals/resolve_return_claim.inc' %] - [% END %] +[% INCLUDE 'modals/bundle_contents.inc' %] - [% INCLUDE 'modals/bundle_contents.inc' %] - - [% IF ( missing_items ) %] - - - [% END %] + + + +
          + + + + + + + + + +[% END %] [% IF ( Koha.Preference('CatalogConcerns') ) %] -[% INCLUDE 'modals/add_catalog_concern.inc' %] + [% INCLUDE 'modals/add_catalog_concern.inc' %] [% END %] [% MACRO jsinclude BLOCK %] @@ -1685,7 +1725,6 @@ [% END %] }); - [% END %] [% INCLUDE 'intranet-bottom.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/circ/set-library.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/circ/set-library.tt index 121a5e31e3..757ffdab05 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/circ/set-library.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/circ/set-library.tt @@ -7,18 +7,24 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% IF Koha.Preference('UseCirculationDesks') %] - [% t("Set library and desk") | html %] › - [% ELSE %] - [% t("Set library") | html %] › - [% END %] - [% t("Circulation") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% IF Koha.Preference('UseCirculationDesks') %] + [% t("Set library and desk") | html %] + › + [% ELSE %] + [% t("Set library") | html %] + › + [% END %] + [% t("Circulation") | html %] + › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -39,60 +45,64 @@ [% SET aside = Koha.Preference('CircSidebar') ? 'circ-nav' : '' %] [% WRAPPER 'main-container.inc' aside=aside %] -

          Set library

          -
          - [% INCLUDE 'csrf-token.inc' %] - - [% IF ( CAN_user_superlibrarian || CAN_user_loggedinlibrary ) %] -
          - Set library -
            -
          1. -
          2. -
          -
          - [% ELSE %] - - [% END %] +

          Set library

          + + [% INCLUDE 'csrf-token.inc' %] + + [% IF ( CAN_user_superlibrarian || CAN_user_loggedinlibrary ) %] +
          + Set library +
            +
          1. +
          2. +
          +
          + [% ELSE %] + + [% END %] - [% IF Koha.Preference('UseCirculationDesks') && Desks.all %] -
          - Set desk -
            -
          1. -
          2. -
          -
          - [% END %] - [% IF Koha.Preference('UseCashRegisters') %] -
          - Set cash register -
            -
          1. - - -
          2. -
          -
          - [% END %] -
          - - Cancel -
          -
          - -
          -
          - + [% IF Koha.Preference('UseCirculationDesks') && Desks.all %] +
          + Set desk +
            +
          1. +
          2. +
          +
          + [% END %] + [% IF Koha.Preference('UseCashRegisters') %] +
          + Set cash register +
            +
          1. + + +
          2. +
          +
          + [% END %] +
          + + Cancel +
          +
          + +
          + + [% END %] [% INCLUDE 'intranet-bottom.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/circ/transfers_to_send.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/circ/transfers_to_send.tt index b23c211621..4b204fb825 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/circ/transfers_to_send.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/circ/transfers_to_send.tt @@ -8,11 +8,12 @@ [% SET footerjs = 1 %] [% PROCESS 'transfer_reasons.inc' %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Transfers to send") | html %] › - [% t("Circulation") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Transfers to send") | html %] + › [% t("Circulation") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -34,62 +35,63 @@ [% SET aside = Koha.Preference('CircSidebar') ? 'circ-nav' : '' %] [% WRAPPER 'main-container.inc' aside=aside %] +

          Transfers requested of your library as of [% show_date | $KohaDates %]

          -

          Transfers requested of your library as of [% show_date | $KohaDates %]

          - - [% IF libraries.count %] -

          Your library is the origin for the following transfer(s)

          -
          - [% FOREACH library IN libraries %] - [% IF ( library.branchcode ) %] -
          - - - - - - - - - - - - - - - [% FOREACH transfer IN library.inbound_transfers %] - [% UNLESS transfer.datesent %] - - - - - - - - - - [% END %] + [% IF libraries.count %] +

          Your library is the origin for the following transfer(s)

          +
          + [% FOREACH library IN libraries %] + [% IF ( library.branchcode ) %] +
          +
          Sending to [% library.branchname | html %]
          Date of requestTitleReasonOn loanHome libraryCall numberActions
          - [% transfer.daterequested | $KohaDates %] - - [% INCLUDE 'biblio-title.inc' biblio = transfer.item.biblio link = 1 %][% IF ( transfer.item.biblio.author ) %] by [% transfer.item.biblio.author | html %][% END %] - [% IF ( transfer.item.effective_itemtype ) %] ([% ItemTypes.GetDescription( transfer.item.effective_itemtype ) | html %])[% END %] -
          Barcode: [% transfer.item.barcode | html %] -

          [% PROCESS transfer_reason transfer=transfer %]

          [% IF transfer.item.onloan %]Due [% transfer.item.onloan | $KohaDates %][% ELSE %]On shelf[% END %][% Branches.GetName( transfer.item.homebranch ) | html %][% transfer.item.itemcallnumber | html %] - [% IF transfer.reason == 'StockrotationAdvance' %] - Mark "In demand" - [% END %] -
          + + + + + + + + + + + + + + [% FOREACH transfer IN library.inbound_transfers %] + [% UNLESS transfer.datesent %] + + + + + + + + -
          Sending to [% library.branchname | html %]
          Date of requestTitleReasonOn loanHome libraryCall numberActions
          [% transfer.daterequested | $KohaDates %] + [% INCLUDE 'biblio-title.inc' biblio = transfer.item.biblio link = 1 %][% IF ( transfer.item.biblio.author ) %]by [% transfer.item.biblio.author | html %][% END %] + [% IF ( transfer.item.effective_itemtype ) %]([% ItemTypes.GetDescription( transfer.item.effective_itemtype ) | html %])[% END %] +
          Barcode: [% transfer.item.barcode | html %] +

          [% PROCESS transfer_reason transfer=transfer %]

          [% IF transfer.item.onloan %]Due [% transfer.item.onloan | $KohaDates %][% ELSE %]On shelf[% END %][% Branches.GetName( transfer.item.homebranch ) | html %][% transfer.item.itemcallnumber | html %] + [% IF transfer.reason == 'StockrotationAdvance' %] + Mark "In demand" [% END %] -
          -
          + + + [% END %] [% END %] - [% END %] -
          - [% ELSE %] -

          No transfers to send

          - [% END %] - + + + + + [% END %] + [% END %] + + [% ELSE %] +

          No transfers to send

          + [% END %] [% END %] [% MACRO jsinclude BLOCK %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/circ/transferstoreceive.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/circ/transferstoreceive.tt index cfe81f67e5..f757bf9f7f 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/circ/transferstoreceive.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/circ/transferstoreceive.tt @@ -6,11 +6,12 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Transfers to receive") | html %] › - [% t("Circulation") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Transfers to receive") | html %] + › [% t("Circulation") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -32,69 +33,80 @@ [% SET aside = Koha.Preference('CircSidebar') ? 'circ-nav' : '' %] [% WRAPPER 'main-container.inc' aside=aside %] - -

          Transfers made to your library as of [% show_date | $KohaDates %]

          - [% IF ( branchesloop ) %] +

          Transfers made to your library as of [% show_date | $KohaDates %]

          + [% IF ( branchesloop ) %]

          Your library is the destination for the following transfer(s)

          - [% IF ( latetransfers ) %]

          Transfers are considered late after [% TransfersMaxDaysWarning | html %] days.

          [% END %] + [% IF ( latetransfers ) %]

          Transfers are considered late after [% TransfersMaxDaysWarning | html %] days.

          [% END %]
          - [% FOREACH branchesloo IN branchesloop %] - [% IF ( branchesloo.branchcode ) %] -
          - - - - - - - - - - - [% FOREACH reser IN branchesloo.reserv %] - [% SET tr_class = '' %] - [% IF ( reser.messcompa ) %] - [% tr_class = 'problem' %] + [% FOREACH branchesloo IN branchesloop %] + [% IF ( branchesloo.branchcode ) %] +
          +
          Coming from [% branchesloo.branchname | html %]
          Date of transferTitleOn hold forHome libraryCall number 
          + + + + + + + + + + [% FOREACH reser IN branchesloo.reserv %] + [% SET tr_class = '' %] + [% IF ( reser.messcompa ) %] + [% tr_class = 'problem' %] + [% END %] + + + + + + + + + [% END %] +
          Coming from [% branchesloo.branchname | html %]
          Date of transferTitleOn hold forHome libraryCall number 

          [% reser.datetransfer | $KohaDates %]

          [% IF ( reser.messcompa ) %]Transfer is [% reser.diff | html %] days late[% END %]
          + [% INCLUDE 'biblio-title.inc' biblio=reser link = 1 %] [% IF ( reser.author ) %]by [% reser.author | html %][% END %] + [% IF ( reser.itemtype ) %]([% reser.itemtype | html %])[% END %] +
          Barcode: [% reser.barcode | html %] +
          [% IF ( reser.patron ) %] + + [% reser.patron.surname | html %][% IF ( reser.patron.firstname ) %], [% reser.patron.firstname | html %][% END %] + + [% IF ( reser.patron.phone ) %]
          [% reser.patron.phone | html %][% END %] + [% IF ( reser.patron.notice_email_address ) %] +
          + [% BLOCK subject %]Hold:[% END %] + [% reser.patron.notice_email_address | html %] + [% END %] + [% ELSIF ( reser.recall ) %] + Recall requested by + [% reser.recall.patron.surname | html %][% IF reser.recall.patron.firstname %], [% reser.recall.patron.firstname | html %][% END %] ([% reser.recall.patron.cardnumber | html %]) + [% ELSE %] +

          None

          + [% END %] +
          [% IF reser.homebranch %][% Branches.GetName( reser.homebranch ) | html %][% END %][% reser.itemcallnumber | html %] Cancel transfer
          +
          + [% END %] - -

          [% reser.datetransfer | $KohaDates %]

          [% IF ( reser.messcompa ) %]Transfer is [% reser.diff | html %] days late[% END %] - - [% INCLUDE 'biblio-title.inc' biblio=reser link = 1 %] [% IF ( reser.author ) %]by [% reser.author | html %][% END %] - [% IF ( reser.itemtype ) %] ([% reser.itemtype | html %])[% END %] -
          Barcode: [% reser.barcode | html %] - - [% IF ( reser.patron ) %] - - [% reser.patron.surname | html %][%IF ( reser.patron.firstname ) %], [% reser.patron.firstname | html %][% END %] - - [% IF ( reser.patron.phone ) %]
          [% reser.patron.phone | html %][% END %] - [% IF ( reser.patron.notice_email_address ) %] -
          - [% BLOCK subject %]Hold:[% END %] - - [% reser.patron.notice_email_address | html %] - - [% END %] - [% ELSIF ( reser.recall ) %] - Recall requested by [% reser.recall.patron.surname | html %][% IF reser.recall.patron.firstname %], [% reser.recall.patron.firstname | html %][% END %] ([% reser.recall.patron.cardnumber | html %]) - [% ELSE %] -

          None

          - [% END %] - - [% IF reser.homebranch %][% Branches.GetName( reser.homebranch ) | html %][% END %] - [% reser.itemcallnumber | html %] - Cancel transfer - - [% END %] - -
          [% END %] - [% END %] [% ELSE %]

          No transfers to receive

          [% END %] - [% END %] [% MACRO jsinclude BLOCK %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/circ/view_holdsqueue.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/circ/view_holdsqueue.tt index 6a124e75f6..c7e0040cd1 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/circ/view_holdsqueue.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/circ/view_holdsqueue.tt @@ -9,13 +9,18 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Holds queue") | html %] › - [% t("Circulation") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Holds queue") | html %] + › [% t("Circulation") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] - + @@ -35,7 +40,6 @@ [% WRAPPER breadcrumb_item bc_active= 1 %] Results [% END %] - [% ELSE %] [% WRAPPER breadcrumb_item bc_active= 1 %] Holds queue @@ -49,215 +53,227 @@
          + [% IF ( total || Koha.Preference('CircSidebar') ) %] + [% SET div_class='col-md-10 order-md-2 order-sm-1' %] + [% ELSE %] + [% SET div_class='col-md-10 offset-md-1 col-lg-8 offset-lg-2' %] + [% END %] +
          + [% INCLUDE 'messages.inc' %] - [% IF ( total || Koha.Preference('CircSidebar') ) %] - [% SET div_class='col-md-10 order-md-2 order-sm-1' %] - [% ELSE %] - [% SET div_class='col-md-10 offset-md-1 col-lg-8 offset-lg-2' %] - [% END %] -
          - [% INCLUDE 'messages.inc' %] +

          Holds queue

          -

          Holds queue

          - -[% IF ( run_report ) %] - [% IF ( total ) %] -
          [% total | html %] items found for - [% IF ( branchlimit ) %][% Branches.GetName( branchlimit ) | html %][% ELSE %]All libraries[% END %] - [% IF ( itemtypeslimit ) %] and item type: [% ItemTypes.GetDescription( itemtypeslimit ) | html %][% END %] - [% IF ( ccodeslimit ) %] and collection: [% AuthorisedValues.GetDescriptionByKohaField( kohafield => 'items.ccode' authorised_value = ccodeslimit ) | html %][% END %] - [% IF ( locationslimit ) %] and shelving location: [% AuthorisedValues.GetDescriptionByKohaField( kohafield => 'items.location' authorised_value = locationslimit ) | html %][% END %] -
          - [% ELSE %] -
          No items found.
          - [% END %] - [% IF ( itemsloop ) %] -
          - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - [% FOREACH itemsloo IN itemsloop %] - - - - - - - - - - - - - - - - - - - - [% END %] - -
          TitleAuthorPublication detailsCurrent libraryHome libraryCollectionShelving locationItem typeCall numberCopy numberEnumerationBarcodePatronPatron categorySend toDateNotes
          - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
          -

          - [% INCLUDE 'biblio-title.inc' biblio=itemsloo.biblio link = 1 %] -

          -
          [% itemsloo.biblionumber | html %]
          -
          [% itemsloo.biblio.author | html %] -
          - [% IF ( itemsloo.biblio.biblioitem.editionstatement ) %]
          [% itemsloo.biblio.biblioitem.editionstatement | html %]
          [% END %] - [% IF ( itemsloo.biblio.biblioitem.publishercode ) %][% itemsloo.biblio.biblioitem.publishercode | html %][% END %] - - [% IF ( itemsloo.biblio.biblioitem.publicationyear ) %] - , [% itemsloo.biblio.biblioitem.publicationyear | html %] - [% ELSIF ( itemsloo.biblio.copyrightdate ) %] - , [% itemsloo.biblio.copyrightdate | html %] - [% END %] - - [% IF ( itemsloo.biblio.biblioitem.pages ) %]: [% itemsloo.biblio.biblioitem.pages | html %] [% END %] - - [% IF ( itemsloo.biblio.biblioitem.size ) %][% itemsloo.biblio.biblioitem.size | html %][% END %] - - [% IF ( itemsloo.biblio.biblioitem.isbn ) %]ISBN: [% itemsloo.biblio.biblioitem.isbn | html %][% END %] -
          -
          [% Branches.GetName( itemsloo.holdingbranch ) | html %][% Branches.GetName( itemsloo.item.homebranch ) | html %][% AuthorisedValues.GetDescriptionByKohaField( kohafield => 'items.ccode', authorised_value => itemsloo.item.ccode ) | html %][% AuthorisedValues.GetDescriptionByKohaField( kohafield => 'items.location', authorised_value => itemsloo.item.location ) | html %][% ItemTypes.GetDescription( itemsloo.item.effective_itemtype ) | html %][% itemsloo.item.itemcallnumber | html %][% itemsloo.item.copynumber | html %][% itemsloo.item.enumchron | html %] - [% IF ( itemsloo.item_level_request ) %] - Only item: [% itemsloo.barcode | html %] - [% ELSIF itemsloo.item.item_group %] - [% itemsloo.barcode | html %] or any item from item group [% itemsloo.item.item_group.description | html %] + [% IF ( run_report ) %] + [% IF ( total ) %] +
          [% total | html %] items found for + [% IF ( branchlimit ) %][% Branches.GetName( branchlimit ) | html %][% ELSE %]All libraries[% END %] + [% IF ( itemtypeslimit ) %]and item type: [% ItemTypes.GetDescription( itemtypeslimit ) | html %][% END %] + [% IF ( ccodeslimit ) %]and collection: [% AuthorisedValues.GetDescriptionByKohaField( kohafield => 'items.ccode' authorised_value = ccodeslimit ) | html %][% END %] + [% IF ( locationslimit ) %]and shelving location: [% AuthorisedValues.GetDescriptionByKohaField( kohafield => 'items.location' authorised_value = locationslimit ) | html %][% END %] +
          [% ELSE %] - [% itemsloo.barcode | html %] or any available +
          No items found.
          [% END %] -
          -

          - [% INCLUDE 'patron-title.inc' invert_name=1 patron=itemsloo.patron hide_patron_infos_if_needed=1 link_to="circulation_reserves" %] -

          - [% UNLESS Koha.Preference('HidePatronName') %] -

          [% itemsloo.patron.phone | html %]

          - [% IF itemsloo.patron.notice_email_address %] -

          - - [% itemsloo.patron.notice_email_address | html %] -

          - [% END %] - [% END %] -
          [% itemsloo.patron.category.description | html %] ([% itemsloo.patron.categorycode | html %])[% Branches.GetName( itemsloo.pickbranch ) | html %][% itemsloo.reservedate | $KohaDates %][% itemsloo.notes | html %]
          -
          - [% END %] - [% END %] + [% IF ( itemsloop ) %] +
          + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + [% FOREACH itemsloo IN itemsloop %] + + + + + + + + + + + + + + + + + + + + [% END %] + +
          TitleAuthorPublication detailsCurrent libraryHome libraryCollectionShelving locationItem typeCall numberCopy numberEnumerationBarcodePatronPatron categorySend toDateNotes
          + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
          +

          [% INCLUDE 'biblio-title.inc' biblio=itemsloo.biblio link = 1 %]

          +
          [% itemsloo.biblionumber | html %]
          +
          [% itemsloo.biblio.author | html %] +
          + [% IF ( itemsloo.biblio.biblioitem.editionstatement ) %]
          [% itemsloo.biblio.biblioitem.editionstatement | html %]
          [% END %] + [% IF ( itemsloo.biblio.biblioitem.publishercode ) %][% itemsloo.biblio.biblioitem.publishercode | html %][% END %] + + [% IF ( itemsloo.biblio.biblioitem.publicationyear ) %] + , [% itemsloo.biblio.biblioitem.publicationyear | html %] + [% ELSIF ( itemsloo.biblio.copyrightdate ) %] + , [% itemsloo.biblio.copyrightdate | html %] + [% END %] + + [% IF ( itemsloo.biblio.biblioitem.pages ) %]: [% itemsloo.biblio.biblioitem.pages | html %][% END %] + + [% IF ( itemsloo.biblio.biblioitem.size ) %][% itemsloo.biblio.biblioitem.size | html %][% END %] + + [% IF ( itemsloo.biblio.biblioitem.isbn ) %]ISBN: [% itemsloo.biblio.biblioitem.isbn | html %][% END %] +
          +
          [% Branches.GetName( itemsloo.holdingbranch ) | html %][% Branches.GetName( itemsloo.item.homebranch ) | html %][% AuthorisedValues.GetDescriptionByKohaField( kohafield => 'items.ccode', authorised_value => itemsloo.item.ccode ) | html %][% AuthorisedValues.GetDescriptionByKohaField( kohafield => 'items.location', authorised_value => itemsloo.item.location ) | html %][% ItemTypes.GetDescription( itemsloo.item.effective_itemtype ) | html %][% itemsloo.item.itemcallnumber | html %][% itemsloo.item.copynumber | html %][% itemsloo.item.enumchron | html %] + [% IF ( itemsloo.item_level_request ) %] + Only item: + [% itemsloo.barcode | html %] + [% ELSIF itemsloo.item.item_group %] + [% itemsloo.barcode | html %] + or any item from item group [% itemsloo.item.item_group.description | html %] + [% ELSE %] + [% itemsloo.barcode | html %] + or any available + [% END %] + +

          [% INCLUDE 'patron-title.inc' invert_name=1 patron=itemsloo.patron hide_patron_infos_if_needed=1 link_to="circulation_reserves" %]

          + [% UNLESS Koha.Preference('HidePatronName') %] +

          [% itemsloo.patron.phone | html %]

          + [% IF itemsloo.patron.notice_email_address %] +

          + [% itemsloo.patron.notice_email_address | html %] +

          + [% END %] + [% END %] +
          [% itemsloo.patron.category.description | html %] ([% itemsloo.patron.categorycode | html %])[% Branches.GetName( itemsloo.pickbranch ) | html %][% itemsloo.reservedate | $KohaDates %][% itemsloo.notes | html %]
          +
          + + [% END %] + [% END %] [% UNLESS ( total ) %] [% branchlimit = Branches.GetLoggedInBranchcode %] [% PROCESS filter_form %] [% END %] - -
          +
          + [% IF ( total || Koha.Preference('CircSidebar') ) %]
          -
          +
          + [% END %] -
          - + + - - - + + + + + + [% BLOCK filter_form %]
          diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/circ/waitingreserves.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/circ/waitingreserves.tt index 7a9fb6abfd..3f29fff560 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/circ/waitingreserves.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/circ/waitingreserves.tt @@ -8,11 +8,12 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Holds awaiting pickup") | html %] › - [% t("Circulation") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Holds awaiting pickup") | html %] + › [% t("Circulation") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -34,155 +35,154 @@ [% SET aside = Koha.Preference('CircSidebar') ? 'circ-nav' : '' %] [% WRAPPER 'main-container.inc' aside=aside %] - -

          Holds awaiting pickup for your library on: [% show_date | $KohaDates %]

          -

          - [% IF ( all_branches_link ) %] - - View all libraries - [% END %] -

          - [% IF reject_result_error %] -
          - [% IF reject_result_error.invalid_status %] -

          There was a problem rejecting the cancellation request. Cannot reject an already completed cancellation request.

          - [% ELSE %] -

          Some error occurred while rejecting the cancellation request. Please check the logs

          - [% END %] -
          - [% END %] - [% IF ( cancel_result ) %] - [% FOREACH cancel_result %] - [% IF ( messagetransfert ) %] -
          -

          This item is on hold for pick-up at [% Branches.GetName( branchname ) | html %]

          -

          [% nextreservtitle | html %] is on hold for [% nextreservsurname | html %], [% nextreservfirstname | html %]. - Please retain this item and check it in to process the hold. -

          - - - -
          - [% END # /IF messagetransfert%] - [% IF ( waiting ) %] -
          -

          This item is on hold for pick-up at your library

          -

          [% nextreservtitle | html %] is on hold for [% nextreservsurname | html %], [% nextreservfirstname | html %]. - Please retain this item and check it in to process the hold. -

          -
          - -
          -
          - [% END # /IF waiting %] - [% END # /FOREACH cancel_result %] - [% ELSE %] - [% IF enqueued %] -
          -

          The job has been enqueued! It will be processed as soon as possible.

          -

          View detail of the enqueued job

          -
          - [% END %] - - [% WRAPPER tabs id= "resultlist" %] - [% WRAPPER tabs_nav %] - [% WRAPPER tab_item tabname= "holdswaiting" bt_active= 1 %] - Holds waiting: [% reservecount | html %] - [% END %] - [% WRAPPER tab_item tabname= "holdsover" %] - Holds waiting past their expiration date: [% overcount | html %] - [% END %] - [% WRAPPER tab_item tabname= "holdscancelled" %] - Holds with cancellation requests: [% cancel_reqs_count | html %] - [% END %] - [% END # /WRAPPER tabs_nav %] - - [% WRAPPER tab_panels %] - [% WRAPPER tab_panel tabname="holdswaiting" bt_active= 1 %] - [% IF ( reserveloop ) %] -
          - -
          - [% INCLUDE waiting_holds.inc table_name='holdst' reserveloop=reserveloop tab='holdwaiting' %] - [% ELSE %] -
          No holds found.
          - [% END %] - [% END # /tab_panel#holdswaiting %] - - [% WRAPPER tab_panel tabname="holdsover" %] - [% IF ( overloop ) %] -
          - -
          -
          - [% INCLUDE 'csrf-token.inc' %] - - - - [% IF TransferWhenCancelAllWaitingHolds %] - - [% ELSE %] - - [% END %] -
          -
          -
          - [% UNLESS TransferWhenCancelAllWaitingHolds %] -
          Only items that need not be transferred will be cancelled (TransferWhenCancelAllWaitingHolds syspref)
          - [% END %] - [% INCLUDE waiting_holds.inc table_name='holdso' reserveloop=overloop tab='holdsover' %] - [% ELSE %] -
          No holds found.
          - [% END # /IF( overloop ) %] - [% END # /tab_panel#holdsover %] - - [% WRAPPER tab_panel tabname="holdscancelled" %] - [% IF cancel_reqs_count %] -
          - -
          - [% INCLUDE waiting_holds.inc select_column='1' table_name='holdscr' reserveloop=cancel_reqs tab='holdscr' %] - [% ELSE %] -
          No holds found.
          - [% END %] - [% END # /tab_panel#holdscancelled %] - [% END # /WRAPPER tab_panels %] - [% END # /WRAPPER tabs %] - - [% END # /IF ( cancel_result ) %] +

          Holds awaiting pickup for your library on: [% show_date | $KohaDates %]

          +

          + [% IF ( all_branches_link ) %] + View all libraries + [% END %] +

          + [% IF reject_result_error %] +
          + [% IF reject_result_error.invalid_status %] +

          There was a problem rejecting the cancellation request. Cannot reject an already completed cancellation request.

          + [% ELSE %] +

          Some error occurred while rejecting the cancellation request. Please check the logs

          + [% END %] +
          [% END %] - + + [% END %] [% END %] [% MACRO jsinclude BLOCK %] [% INCLUDE 'datatables.inc' %] [% Asset.js("js/tools-menu.js") | $raw %] [% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/clubs/clubs-add-modify.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/clubs/clubs-add-modify.tt index 1687351123..e296f53a2a 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/clubs/clubs-add-modify.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/clubs/clubs-add-modify.tt @@ -7,16 +7,16 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% IF club %] - [% tx("Modify club {club_name}", { club_name = club.name }) | html %] - [% ELSE %] - [% tx("Create a new {club_template} club", { club_template = club_template.name }) | html %] - [% END %] › - [% t("Patron clubs") | html %] › - [% t("Tools") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% IF club %] + [% tx("Modify club {club_name}", { club_name = club.name }) | html %] + [% ELSE %] + [% tx("Create a new {club_template} club", { club_template = club_template.name }) | html %] + [% END %] + › [% t("Patron clubs") | html %] › [% t("Tools") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -44,105 +44,101 @@ [% END #/ WRAPPER sub-header.inc %] [% WRAPPER 'main-container.inc' %] +
          + [% INCLUDE 'csrf-token.inc' %] + + + - - [% INCLUDE 'csrf-token.inc' %] - - - +
          + +

          + [% IF club %] + Modify club [% club.name | html | $HtmlTags tag="em" %] + [% ELSE %] + Create a new [% club_template.name | html | $HtmlTags tag="em" %] club + [% END %] +

          +
          -
          +
            +
          1. + + + Required +
          2. - -

            - [% IF club %] - Modify club [% club.name | html | $HtmlTags tag="em" %] +
          3. + + +
          4. + +
          5. + + +
          6. + +
          7. + + +
          8. + +
          9. + + +
          10. + + [% IF club %] + [% FOREACH f IN club.club_fields %] +
          11. + + + + + [% IF f.club_template_field.authorised_value_category %] + [% ELSE %] - Create a new [% club_template.name | html | $HtmlTags tag="em" %] club + [% END %] -
          12. -
            - -
              -
            1. - - - Required
            2. - + [% END %] + [% ELSE %] + [% FOREACH f IN club_template.club_template_fields %]
            3. - - -
            4. + -
            5. - - -
            6. - -
            7. - - -
            8. - -
            9. - - -
            10. - - [% IF club %] - [% FOREACH f IN club.club_fields %] -
            11. - - - - - [% IF f.club_template_field.authorised_value_category %] - - [% ELSE %] - + + [% IF f.authorised_value_category %] + + [% ELSE %] + [% END %] - [% ELSE %] - [% FOREACH f IN club_template.club_template_fields %] -
            12. - +
            13. + [% END %] + [% END %] +
            +
          - - [% IF f.authorised_value_category %] - - [% ELSE %] - - [% END %] - - [% END %] - [% END %] - - - -
          - -
          - - Cancel -
          -
          +
          + + Cancel +
          + [% END %] [% MACRO jsinclude BLOCK %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/clubs/clubs.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/clubs/clubs.tt index bf12d26979..644ce4969d 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/clubs/clubs.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/clubs/clubs.tt @@ -6,11 +6,12 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Patron clubs") | html %] › - [% t("Tools") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Patron clubs") | html %] + › [% t("Tools") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -32,170 +33,164 @@ [% END #/ WRAPPER sub-header.inc %] [% WRAPPER 'main-container.inc' aside='tools-menu' %] +

          Patron clubs

          -

          Patron clubs

          + [% IF club_template %] +
          + [% IF stored == 'updated' %] +

          Club template [% club_template.name | html %] was updated.

          + [% ELSE %] +

          Club template [% club_template.name | html %] was saved.

          + [% END %] +
          + [% ELSIF club %] +
          + [% IF stored == 'updated' %] +

          Club [% club.name | html %] was updated.

          + [% ELSE %] +

          Club [% club.name | html %] was saved.

          + [% END %] +
          + [% END %] - [% IF club_template %] -
          - [% IF stored == 'updated' %] -

          Club template [% club_template.name | html %] was updated.

          - [% ELSE %] -

          Club template [% club_template.name | html %] was saved.

          - [% END %] -
          - [% ELSIF club %] -
          - [% IF stored == 'updated' %] -

          Club [% club.name | html %] was updated.

          - [% ELSE %] -

          Club [% club.name | html %] was saved.

          - [% END %] -
          - [% END %] +

          Club templates

          -

          Club templates

          + [% IF CAN_user_clubs_edit_templates %] + + [% END %] - [% IF CAN_user_clubs_edit_templates %] - - [% END %] - - [% IF club_templates.count %] -
          - - - - - - - - - - - - - [% FOREACH t IN club_templates %] - - - - - - - - + [% IF club_templates.count %] +
          +
          NameDescriptionPublic enrollmentEmail requiredLibraryActions
          [% t.name | html %][% t.description | html %] - [% IF t.is_enrollable_from_opac %] - Yes - [% ELSE %] - No - [% END %] - - [% IF t.is_email_required %] - Yes - [% ELSE %] - No - [% END %] - [% Branches.GetName( t.branchcode ) | html %] - [% IF CAN_user_clubs_edit_templates %] - - Edit - - - Delete - - [% END %] -
          + + + + + + + + + + + + [% FOREACH t IN club_templates %] + + + + -
          NameDescriptionPublic enrollmentEmail requiredLibraryActions
          [% t.name | html %][% t.description | html %] + [% IF t.is_enrollable_from_opac %] + Yes + [% ELSE %] + No [% END %] -
          -
          - [% ELSE %] -
          No club templates defined.
          - [% END %] - -

          Clubs

          - - [% IF CAN_user_clubs_edit_clubs %] -
          -
          - [% IF club_templates.count %] - - [% ELSE %] - - [% END %] - -
          -
          - [% END %] - - [% IF clubs.count %] -
          - [% INCLUDE 'clubs-table.inc' %] -
          - [% ELSE %] - [% IF club_templates.count %] -
          No clubs defined.
          - [% ELSE %] -
          No clubs defined. A club template must be defined before a club can be defined.
          + + [% Branches.GetName( t.branchcode ) | html %] + + [% IF CAN_user_clubs_edit_templates %] + Edit + Delete + [% END %] + + [% END %] - [% END %] + + + + + [% ELSE %] +
          No club templates defined.
          + [% END %] +

          Clubs

          + + [% IF CAN_user_clubs_edit_clubs %] +
          +
          + [% IF club_templates.count %] + + [% ELSE %] + + [% END %] + +
          +
          + [% END %] + + [% IF clubs.count %] +
          [% INCLUDE 'clubs-table.inc' %]
          + + [% ELSE %] + [% IF club_templates.count %] +
          No clubs defined.
          + [% ELSE %] +
          No clubs defined. A club template must be defined before a club can be defined.
          + [% END %] + [% END %] [% END %] [% MACRO jsinclude BLOCK %] [% INCLUDE 'datatables.inc' %] [% Asset.js("js/tools-menu.js") | $raw %] [% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/clubs/patron-clubs-tab.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/clubs/patron-clubs-tab.tt index 5aa1614d8c..b2e2c5bc37 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/clubs/patron-clubs-tab.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/clubs/patron-clubs-tab.tt @@ -21,12 +21,8 @@ [% e.date_enrolled | $KohaDates %] [% IF CAN_user_clubs_enroll %] - - + + [% END %] @@ -36,7 +32,6 @@ [% END %] [% IF clubs %] -

          Clubs not enrolled in

          @@ -55,9 +50,7 @@ [% IF CAN_user_clubs_enroll %] [% END %] @@ -65,44 +58,43 @@
          [% c.description | html %] - +
          [% END %] - diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/clubs/patron-enroll.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/clubs/patron-enroll.tt index 8db62bdf25..a25dedbf67 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/clubs/patron-enroll.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/clubs/patron-enroll.tt @@ -1,8 +1,6 @@ [% USE AuthorisedValues %] -

          - Enroll in [% club.name | html %] -

          +

          Enroll in [% club.name | html %]

          @@ -11,47 +9,47 @@
            - [% IF club_enrollment_fields %] - [% FOREACH f IN club.club_template.club_template_enrollment_fields %] - [% FOREACH c IN club_enrollment_fields %] - [% IF f.id == c.club_template_enrollment_field_id %] -
          1. - - [% IF f.authorised_value_category %] - + [% FOREACH a IN AuthorisedValues.Get( f.authorised_value_category ) %] + [% IF a.authorised_value == c.value %] + + [% ELSE %] + + [% END %] [% END %] - [% END %] - - [% ELSE %] - - [% END %] - [% f.description | html %] -
          2. + + [% ELSE %] + + [% END %] + [% f.description | html %] + + [% END %] [% END %] [% END %] + [% ELSE %] + [% FOREACH f IN club.club_template.club_template_enrollment_fields %] +
          3. + + [% IF f.authorised_value_category %] + + [% ELSE %] + + [% END %] + [% f.description | html %] +
          4. + [% END %] [% END %] - [% ELSE %] - [% FOREACH f IN club.club_template.club_template_enrollment_fields %] -
          5. - - [% IF f.authorised_value_category %] - - [% ELSE %] - - [% END %] - [% f.description | html %] -
          6. - [% END %] - [% END %]
          7. Finish enrollment Cancel @@ -60,37 +58,36 @@
          - diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/clubs/templates-add-modify.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/clubs/templates-add-modify.tt index 359e4f1632..86838b098a 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/clubs/templates-add-modify.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/clubs/templates-add-modify.tt @@ -6,21 +6,22 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% IF club_template %] - [% tx("Modify club template {club_template}", { club_template = club_template.name }) | html %] › - [% ELSE %] - [% t("New club template") | html %] - [% END %] › - [% t("Patron clubs") | html %] › - [% t("Tools") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% IF club_template %] + [% tx("Modify club template {club_template}", { club_template = club_template.name }) | html %] + › + [% ELSE %] + [% t("New club template") | html %] + [% END %] + › [% t("Patron clubs") | html %] › [% t("Tools") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -49,165 +50,156 @@ [% END #/ WRAPPER sub-header.inc %] [% WRAPPER 'main-container.inc' %] +
          + [% INCLUDE 'csrf-token.inc' %] + + +

          + [% IF club_template %] + Modify club template [% club_template.name | html | $HtmlTags tag="em" %] + [% ELSE %] + New club template + [% END %] +

          - - [% INCLUDE 'csrf-token.inc' %] - - -

          - [% IF club_template %] - Modify club template [% club_template.name | html | $HtmlTags tag="em" %] +
          +
            +
          1. + + + Required +
          2. + +
          3. + + +
          4. + +
          5. + + [% IF club_template.is_enrollable_from_opac %] + [% ELSE %] - New club template + [% END %] -

          + If a template allows public enrollment, patrons can enroll in a club based on this template from the public catalog. + +
        • + + [% IF club_template.is_email_required %] + + [% ELSE %] + + [% END %] + If set, a club based on this template can only be enrolled in by patrons with a valid email address. +
        • -
          -
            -
          1. - - - Required -
          2. +
          3. + + +
            If set, only librarians logged in with this branch will be able to modify this club template.
            +
          4. +
          +
          -
        • - - -
        • +
          + Club fields: +

          These fields will be used in the creation of clubs based on this template

          +
          + [% FOREACH f IN club_template.club_template_fields %] +
          +
            + +
          1. + + +
          2. -
          3. - - [% IF club_template.is_enrollable_from_opac %] - - [% ELSE %] - - [% END %] - If a template allows public enrollment, patrons can enroll in a club based on this template from the public catalog. -
          4. +
          5. + + +
          6. -
          7. - - [% IF club_template.is_email_required %] - - [% ELSE %] - - [% END %] - If set, a club based on this template can only be enrolled in by patrons with a valid email address. -
          8. +
          9. + + +
          10. -
          11. - - -
            If set, only librarians logged in with this branch will be able to modify this club template.
            -
          12. - -
          -
          - -
          - Club fields: -

          These fields will be used in the creation of clubs based on this template

          -
          - [% FOREACH f IN club_template.club_template_fields %] -
          -
            - -
          1. - - -
          2. - -
          3. - - -
          4. - -
          5. - - -
          6. - -
          7. - - -
          8. -
          -
          - [% END %] +
        • + + +
        • +
          -
          - - Add new field - -
          -
          + [% END %] + +
          + Add new field +
          + -
          - Enrollment fields -

          These fields will be used when enrolling a patron in a club based on this template

          -
          - [% FOREACH f IN club_template.club_template_enrollment_fields %] -
          -
            -
          1. -   - Enrollment field -
          2. -
          3. - - - -
          4. +
            + Enrollment fields +

            These fields will be used when enrolling a patron in a club based on this template

            +
            + [% FOREACH f IN club_template.club_template_enrollment_fields %] +
            +
              +
            1. +   + Enrollment field +
            2. +
            3. + + + +
            4. -
            5. - - -
            6. +
            7. + + +
            8. -
            9. - - -
            10. +
            11. + + +
            12. -
            13. - - -
            14. -
            -
            - [% END %] +
          5. + + +
          6. +
          -
          - - Add new field - -
          -
          - -
          - - - Cancel -
          -
          + [% END %] + +
          + Add new field +
          + +
          + + + Cancel +
          + [% END %] - [% MACRO jsinclude BLOCK %] [% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/course_reserves/add_items-step1.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/course_reserves/add_items-step1.tt index e4e5bacd17..89e683d0b0 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/course_reserves/add_items-step1.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/course_reserves/add_items-step1.tt @@ -3,12 +3,12 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Add reserves") | html %] › - [% course.course_name | html %] › - [% t("Course reserves") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Add reserves") | html %] + › [% course.course_name | html %] › [% t("Course reserves") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -23,7 +23,7 @@ Course reserves [% END %] [% WRAPPER breadcrumb_item %] - [% course.course_name | html %][%- IF course.section -%] - [% course.section | html %][%- END -%] + [% course.course_name | html %][%- IF course.section -%]- [% course.section | html %][%- END -%] [% END %] [% WRAPPER breadcrumb_item bc_active= 1 %] Add reserves @@ -32,56 +32,56 @@ [% END #/ WRAPPER sub-header.inc %] [% WRAPPER 'main-container.inc' %] -

          Add reserves for [% course.course_name | html %]

          +

          Add reserves for [% course.course_name | html %]

          - [% IF ERROR_ITEM_NOT_FOUND %] - [% IF UNKNOWN_BARCODE %] -
          No item found with barcode [% UNKNOWN_BARCODE | html %]
          - [% ELSIF UNKNOWN_BIBLIONUMBER %] -
          No bibliographic record found with biblionumber [% UNKNOWN_BIBLIONUMBER | html %]
          - [% ELSE %] -
          No item or bibliographic record found
          - [% END %] + [% IF ERROR_ITEM_NOT_FOUND %] + [% IF UNKNOWN_BARCODE %] +
          No item found with barcode [% UNKNOWN_BARCODE | html %]
          + [% ELSIF UNKNOWN_BIBLIONUMBER %] +
          No bibliographic record found with biblionumber [% UNKNOWN_BIBLIONUMBER | html %]
          + [% ELSE %] +
          No item or bibliographic record found
          [% END %] + [% END %] -
          - [% INCLUDE 'csrf-token.inc' %] - - + + [% INCLUDE 'csrf-token.inc' %] + + -
          - Add items: scan barcode -
            -
          1. - - -
          2. -
          -
          +
          + Add items: scan barcode +
            +
          1. + + +
          2. +
          +
          -
          - Or use biblionumber of a bibliographic record -
            -
          1. - - -
          2. -
          -
          +
          + Or use biblionumber of a bibliographic record +
            +
          1. + + +
          2. +
          +
          -
          - +
          + - Cancel -
          - + Cancel +
          + [% END %] [% MACRO jsinclude BLOCK %] [% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/course_reserves/batch_rm_items.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/course_reserves/batch_rm_items.tt index fff1929a54..6099852425 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/course_reserves/batch_rm_items.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/course_reserves/batch_rm_items.tt @@ -4,11 +4,12 @@ [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Remove reserves") | html %] › - [% t("Course reserves") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Remove reserves") | html %] + › [% t("Course reserves") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -29,64 +30,65 @@ [% END #/ WRAPPER sub-header.inc %] [% WRAPPER 'main-container.inc' %] -

          Batch remove reserves

          - [% IF action == 'display_form' %] -
          - [% INCLUDE 'csrf-token.inc' %] - -
          - Remove items: scan barcodes -
            -
          1. - - -
          2. -
          -
          -
          -

          All course reserve items will be deleted from all courses to which they are attached.

          - - Cancel -
          -
          +

          Batch remove reserves

          + [% IF action == 'display_form' %] +
          + [% INCLUDE 'csrf-token.inc' %] + +
          + Remove items: scan barcodes +
            +
          1. + + +
          2. +
          +
          +
          +

          All course reserve items will be deleted from all courses to which they are attached.

          + + Cancel +
          +
          + [% END %] + + [% IF action == 'display_results' %] +

          Results

          + +

          Items removed

          + [% IF item_and_count > 0 %] +

          The following items were removed from all courses:

          +
            + [% FOREACH i IN item_and_count %] +
          • [% txn('{title} ({barcode}) was removed from {count} course.', '{title} ({barcode}) was removed from {count} courses.', i.delcount, { title = i.delitem.biblio.title, barcode = i.delitem.barcode, count = i.delcount }) | html %]
          • + [% END %] +
          + [% ELSE %] + No valid item barcodes found. [% END %] - [% IF action == 'display_results' %] -

          Results

          - -

          Items removed

          - [% IF item_and_count > 0 %] -

          The following items were removed from all courses:

          -
            - [% FOREACH i IN item_and_count %] -
          • [% txn('{title} ({barcode}) was removed from {count} course.', '{title} ({barcode}) was removed from {count} courses.', i.delcount, { title = i.delitem.biblio.title, barcode = i.delitem.barcode, count = i.delcount }) | html %]
          • - [% END %] -
          - [% ELSE %] - No valid item barcodes found. - [% END %] - - - [% IF invalid_barcodes.size > 0 %] -

          Invalid barcodes

          -

          The following invalid barcodes were skipped:

          -
            - [% FOREACH b IN invalid_barcodes %] -
          • [% b | html %]
          • - [% END %] -
          - [% END %] - -

          - Return -

          + [% IF invalid_barcodes.size > 0 %] +

          Invalid barcodes

          +

          The following invalid barcodes were skipped:

          +
            + [% FOREACH b IN invalid_barcodes %] +
          • [% b | html %]
          • + [% END %] +
          [% END %] + +

          + Return +

          + [% END %] [% END %] [% MACRO jsinclude BLOCK %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/course_reserves/invalid-course.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/course_reserves/invalid-course.tt index 58a4473a96..92f4dcedc1 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/course_reserves/invalid-course.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/course_reserves/invalid-course.tt @@ -2,11 +2,13 @@ [% USE Koha %] [% PROCESS 'i18n.inc' %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Invalid course") | html %] - [% t("Course reserves") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Invalid course") | html %] + [% t("Course reserves") | html %] + › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -26,10 +28,8 @@ [% END #/ WRAPPER sub-header.inc %] [% WRAPPER 'main-container.inc' %] - -
          -

          Invalid course!

          -
          - +
          +

          Invalid course!

          +
          [% END %] [% INCLUDE 'intranet-bottom.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/erm/erm.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/erm/erm.tt index 768c8e8596..461826c158 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/erm/erm.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/erm/erm.tt @@ -7,10 +7,12 @@ [% SET footerjs = 1 %] [% PROCESS 'patron-search.inc' %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("E-resource management") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("E-resource management") | html %] + › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -19,41 +21,38 @@ [% INCLUDE 'erm-search.inc' %] [% END %] -
          +
          + -[% MACRO jsinclude BLOCK %] - [% INCLUDE 'calendar.inc' %] - [% INCLUDE 'datatables.inc' %] - [% INCLUDE 'columns_settings.inc' %] - [% INCLUDE 'js-patron-format.inc' %] - [% INCLUDE 'js-date-format.inc' %] + [% MACRO jsinclude BLOCK %] + [% INCLUDE 'calendar.inc' %] + [% INCLUDE 'datatables.inc' %] + [% INCLUDE 'columns_settings.inc' %] + [% INCLUDE 'js-patron-format.inc' %] + [% INCLUDE 'js-date-format.inc' %] + - - [% Asset.js("js/vue/dist/erm.js") | $raw %] - [% INCLUDE 'select2.inc' %] - [% SET columns = ['cardnumber','name','category','branch','action'] %] - [% SET filter = "erm_users" %] - [% PROCESS patron_search_modal columns => columns, modal_title => t("Select user") %] - [% PROCESS patron_search_js columns => columns, actions => ["select"], preview_on_name_click => 1 %] - -[% END %] -[% INCLUDE 'intranet-bottom.inc' %] + const logged_in_user = [% To.json(logged_in_user.unblessed) | $raw %]; + + [% Asset.js("js/vue/dist/erm.js") | $raw %] + [% INCLUDE 'select2.inc' %] + [% SET columns = ['cardnumber','name','category','branch','action'] %] + [% SET filter = "erm_users" %] + [% PROCESS patron_search_modal columns => columns, modal_title => t("Select user") %] + [% PROCESS patron_search_js columns => columns, actions => ["select"], preview_on_name_click => 1 %] + [% END %] + [% INCLUDE 'intranet-bottom.inc' %] +
          diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/errors/errorpage.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/errors/errorpage.tt index 10df8d58d0..9838845d68 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/errors/errorpage.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/errors/errorpage.tt @@ -2,10 +2,12 @@ [% USE Koha %] [% PROCESS 'i18n.inc' %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% tx("Error {error_number}", {error_number = errno }) | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% tx("Error {error_number}", {error_number = errno }) | html %] + › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -17,33 +19,30 @@ [% WRAPPER 'sub-header.inc' %] [% WRAPPER breadcrumbs %] [% WRAPPER breadcrumb_item %] - - [% tx("Error {error_number}", {error_number = errno }) | html %] - + [% tx("Error {error_number}", {error_number = errno }) | html %] [% END %] [% END #/ WRAPPER breadcrumbs %] [% END #/ WRAPPER sub-header.inc %] [% WRAPPER 'main-container.inc' %] -

          An error has occurred!

          [% tx("Error {error_number}", {error_number = errno }) | html %]

          - [% IF ( csrf_error ) %] - [% INCLUDE 'blocking_errors.inc' blocking_error => csrf_error %] - [% ELSE %] -

          This message may have been caused by any of the following reasons:

          -
            -
          • You made use of an external link to an item that is no longer available
          • -
          • You followed an outdated link e.g. from a search engine or a bookmark
          • -
          • You tried to access a page that needs authentication
          • -
          • An internal link in the client is broken and the page does not exist
          • -
          - [% END %] -

          What's next?

          -
            -
          • Use top menu bar to navigate to another part of Koha.
          • -
          • To report a broken link or any other issue, please contact the Koha administrator. Send email
          • + [% IF ( csrf_error ) %] + [% INCLUDE 'blocking_errors.inc' blocking_error => csrf_error %] + [% ELSE %] +

            This message may have been caused by any of the following reasons:

            +
              +
            • You made use of an external link to an item that is no longer available
            • +
            • You followed an outdated link e.g. from a search engine or a bookmark
            • +
            • You tried to access a page that needs authentication
            • +
            • An internal link in the client is broken and the page does not exist
            + [% END %] +

            What's next?

            +
              +
            • Use top menu bar to navigate to another part of Koha.
            • +
            • To report a broken link or any other issue, please contact the Koha administrator. Send email
            • +
            [% END %] [% INCLUDE 'intranet-bottom.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/ill/ill-requests.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/ill/ill-requests.tt index 7444aff9c1..61cc4e792c 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/ill/ill-requests.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/ill/ill-requests.tt @@ -9,10 +9,12 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("ILL requests") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("ILL requests") | html %] + › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -54,664 +56,649 @@ [% WRAPPER 'main-container.inc' wide_centered => ( op == 'illlist' ? 0 : 1 ) aside = ( op == 'illlist' ? 'ill-filter' : '' ) %] - [% IF op == 'illlist' %] - - [% END %] - -
            + [% IF op == 'illlist' %] + + [% END %] +
            [% IF !backends_available || !has_branch || ill_deprecated_backend_freeform_is_installed %]
            ILL module configuration problem. Take a look at the about page
            [% ELSE %] - [% INCLUDE 'ill-toolbar.inc' %] - [% INCLUDE 'ill-batch-modal.inc' %] + [% INCLUDE 'ill-toolbar.inc' %] + [% INCLUDE 'ill-batch-modal.inc' %] - [% IF whole.error %] -

            Error performing operation

            - -

            We encountered an error:

            -

            + [% IF whole.error %] +

            Error performing operation

            + +

            We encountered an error:

            +

            [% SWITCH whole.status %] - [% CASE 'invalid_patron' %] + [% CASE 'invalid_patron' %]

            The patron ID you entered is invalid.
            - [% CASE 'invalid_biblio' %] + [% CASE 'invalid_biblio' %]
            The bibliographic record ID you entered is invalid.
            - [% CASE %] + [% CASE %]
            [% whole.message | html %] ([% whole.status | html %])
            [% END %] -

            - [% END %] +

            + [% END %] - [% IF whole.success %] -

            [% whole.success | html %]

            - [% END %] + [% IF whole.success %] +

            [% whole.success | html %]

            + [% END %] - [% IF op == 'cud-create' %] -

            New ILL request

            - [% PROCESS $whole.template %] - - [% ELSIF op == 'confirm' %] -

            Confirm ILL request

            - [% PROCESS $whole.template %] - - [% ELSIF op == 'cud-cancel' and !whole.error %] -

            Cancel a confirmed request

            - [% PROCESS $whole.template %] - - [% ELSIF op == 'check_out' and !whole.error %] - [% IF !whole.stage || whole.stage == 'form' %] -

            Issue requested item to [% INCLUDE 'patron-title.inc' patron = request.patron %]

            - [% IF !request.biblio_id || request.biblio_id.length == 0 %] + [% IF op == 'cud-create' %] +

            New ILL request

            + [% PROCESS $whole.template %] + [% ELSIF op == 'confirm' %] +

            Confirm ILL request

            + [% PROCESS $whole.template %] + [% ELSIF op == 'cud-cancel' and !whole.error %] +

            Cancel a confirmed request

            + [% PROCESS $whole.template %] + [% ELSIF op == 'check_out' and !whole.error %] + [% IF !whole.stage || whole.stage == 'form' %] +

            Issue requested item to [% INCLUDE 'patron-title.inc' patron = request.patron %]

            + [% IF !request.biblio_id || request.biblio_id.length == 0 %]
            This item cannot be checked out as it has no bibliographic record associated with it
            - [% END %] - [% IF whole.value.errors.itemcount %] + [% END %] + [% IF whole.value.errors.itemcount %]
            The bibliographic record for this request has multiple items, it should only have one. Please fix this then try again.
            - [% END %] - [% IF whole.value.errors.item_creation %] + [% END %] + [% IF whole.value.errors.item_creation %]
            An unknown error occurred while trying to add an item
            - [% END %] - [% IF whole.value.errors.item_check_out %] + [% END %] + [% IF whole.value.errors.item_check_out %]
            An unknown error occurred while trying to check out the item
            - [% END %] - [% IF whole.value.check_out_errors %] - [% IF whole.value.check_out_errors.error.STATS %] -
            - Local use recorded -
            - [% ELSIF whole.value.check_out_errors.error.UNKNOWN_BARCODE %] -
            - The bibliographic record's item contains an unknown (or empty) barcode. -
            - [% ELSE %] + [% END %] + [% IF whole.value.check_out_errors %] + [% IF whole.value.check_out_errors.error.STATS %] +
            Local use recorded
            + [% ELSIF whole.value.check_out_errors.error.UNKNOWN_BARCODE %] +
            The bibliographic record's item contains an unknown (or empty) barcode.
            + [% ELSE %]
            There was a problem checking this item out, please check for problems with the patron's account
            - [% END %] [% END %] - [% IF request.biblio_id && request.biblio_id.length > 0 && !whole.value.check_out_errors.error.STATS %] -
            - [% INCLUDE 'csrf-token.inc' %] -
            - Check out details - [% items = whole.value.biblio.items.unblessed %] - [% IF items.size == 1 %] -

            The bibliographic record for this request already has an item attached to it, you are about to check it out

            - [% ELSE %] -

            A bibliographic record for this request exists, but no item. You are about to create an item and check it out

            - [% END %] -
              -
            1. - - - [% IF whole.value.errors.inhouse %] - You must choose a valid patron - [% END %] -
              If you do not wish to check out the item to [% INCLUDE 'patron-title.inc' patron = request.patron %] and would rather issue it to an in-house statistical patron, choose the patron here
              -
            2. -
            3. - - [% IF items.size != 1 %] - - [% ELSE %] - [% FOREACH type IN whole.value.itemtypes %] - [% IF type.itemtype == items.0.itype %] - [% type.description | html %] - [% END %] - [% END %] - [% END %] - [% IF whole.value.errors.item_type %] - You must choose an item type - [% END %] -
            4. - [% IF items.size == 1 %] -
            5. - - [% items.0.barcode | html %] -
            6. - [% END %] -
            7. - - [% branchcode = items.size == 1 ? items.0.homebranch : params.branchcode ? params.branchcode : request.branchcode %] - [% IF items.size != 1 %] - - [% ELSE %] - [% FOREACH branch IN whole.value.libraries.unblessed %] - [% IF branch.branchcode == branchcode %] - [% branch.branchname | html %] - [% END %] - [% END %] - [% END %] - [% IF whole.value.errors.branchcode %] - You must choose a library - [% END %] -
            8. -
            9. - - [% INCLUDE 'date-format.inc' %] -
              If you do not specify a due date, it will be set according to circulation rules
              -
            10. -
            -
            -
            - - - [% IF items.size == 1 %] - - - [% END %] - - - Cancel -
            -
            - [% END %] - [% IF whole.value.check_out_errors.error.STATS %] - Return to request - [% END %] - [% ELSIF whole.stage == 'done_check_out' %] -

            Item checked out

            -
            - Check out details -
              -
            1. - - [% INCLUDE 'patron-title.inc' patron = whole.value.patron %] -
            2. -
            3. - - [% whole.value.check_out.date_due | $KohaDates as_due_date => 1 %] -
            4. -
            -
            -
            - Return to request -
            [% END %] - - [% ELSIF op == 'generic_confirm' %] -

            Place request with partner libraries

            - [% IF error %] - [% IF error == 'no_target_email' %] -
            - No target email addresses found. Either select at least - one partner or check your ILL partner library records. -
            - [% ELSIF error == 'no_library_email' %] -
            - Your library has no usable email address. Please set it. -
            - [% ELSIF error == 'unkown_error' %] -
            - Unknown error processing your request. Contact your administrator. -
            - [% END %] - [% END %] - - [% IF whole.value.partners %] - [% ill_url = "/cgi-bin/koha/ill/ill-requests.pl?op=illview&illrequest_id=" _ request.illrequest_id %] + [% IF request.biblio_id && request.biblio_id.length > 0 && !whole.value.check_out_errors.error.STATS %]
            [% INCLUDE 'csrf-token.inc' %]
            - Interlibrary loan request details + Check out details + [% items = whole.value.biblio.items.unblessed %] + [% IF items.size == 1 %] +

            The bibliographic record for this request already has an item attached to it, + you are about to check it out

            + [% ELSE %] +

            A bibliographic record for this request exists, but no item. You are about to create an item and check it out

            + [% END %]
              -
            1. - - -
            2. -
            3. - - + + [% FOREACH stat IN whole.value.statistical %] + [% IF stat.borrowernumber == params.inhouse %] + + [% ELSE %] + [% END %] [% END %] - [% IF Koha.Preference('ILLCheckAvailability') %] -
              Partners available for searching: none
              - + [% IF whole.value.errors.inhouse %] + You must choose a valid patron + [% END %] +
              If you do not wish to check out the item to [% INCLUDE 'patron-title.inc' patron = request.patron %] and would rather issue it to an in-house statistical patron, choose the patron here
              +
            4. +
            5. + + [% IF items.size != 1 %] + + [% ELSE %] + [% FOREACH type IN whole.value.itemtypes %] + [% IF type.itemtype == items.0.itype %] + [% type.description | html %] + [% END %] + [% END %] + [% END %] + [% IF whole.value.errors.item_type %] + You must choose an item type [% END %]
            6. -
            7. - - + [% IF items.size == 1 %] +
            8. + + [% items.0.barcode | html %] +
            9. + [% END %] +
            10. + + [% branchcode = items.size == 1 ? items.0.homebranch : params.branchcode ? params.branchcode : request.branchcode %] + [% IF items.size != 1 %] + + [% ELSE %] + [% FOREACH branch IN whole.value.libraries.unblessed %] + [% IF branch.branchcode == branchcode %] + [% branch.branchname | html %] + [% END %] + [% END %] + [% END %] + [% IF whole.value.errors.branchcode %] + You must choose a library + [% END %]
            11. -
            12. - - +
            13. + + [% INCLUDE 'date-format.inc' %] +
              If you do not specify a due date, it will be set according to circulation rules
            - - -
            - - Cancel + + + [% IF items.size == 1 %] + + + [% END %] + + + Cancel
            - [% IF Koha.Preference('ILLCheckAvailability') %] -
          - [% END %] +
        • ERROR: [% e.error | $raw %]
        • + [% END %] + + [% END %] - [% UNLESS error OR atomic_updates.error.size OR has_update_errors %] -

          Everything went okay. Update done.

          -

          Continue to log in to Koha

          - [% ELSE %] -
          -
          - [% INCLUDE 'csrf-token.inc' %] - - -

          -
          -
          - [% END %] - [% END # / IF updatestructure %] -
          - - + [% UNLESS error OR atomic_updates.error.size OR has_update_errors %] +

          Everything went okay. Update done.

          +

          Continue to log in to Koha

          + [% ELSE %] +
          +
          + [% INCLUDE 'csrf-token.inc' %] + + +

          +
          +
          + [% END %] + [% END # / IF updatestructure %] + + + + [% IF ( selectframeworks ) %] [% MACRO jsinclude BLOCK %] [% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/labels/label-edit-template.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/labels/label-edit-template.tt index 41c15b024d..d0ba92c35c 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/labels/label-edit-template.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/labels/label-edit-template.tt @@ -2,23 +2,22 @@ [% USE Koha %] [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] - [% INCLUDE 'doc-head-open.inc' %] - [% FILTER collapse %] +[% INCLUDE 'doc-head-open.inc' %] +<title + >[% FILTER collapse %] [% IF( template_id ) %] [% tx("Edit label template {template_id}", { template_id = template_id }) | html %] [% ELSE %] [% t("New label template") | html %] - [% END %] › - [% t("Templates") | html %] › - [% t("Label creator") | html %] › - [% t("Cataloging") | html %] › - [% t("Koha") | html %] - [% END %] - [% INCLUDE 'doc-head-close.inc' %] + [% END %] + › [% t("Templates") | html %] › [% t("Label creator") | html %] › [% t("Cataloging") | html %] › [% t("Koha") | html %] + [% END %] +[% INCLUDE 'doc-head-close.inc' %] - [% WRAPPER 'header.inc' %] +[% WRAPPER 'header.inc' %] [% INCLUDE 'cat-search.inc' %] [% END %] @@ -43,151 +42,147 @@ [% END #/ WRAPPER breadcrumbs %] [% END #/ WRAPPER sub-header.inc %] - [% WRAPPER 'main-container.inc' aside='cat-menu' %] - [% INCLUDE 'labels-toolbar.inc' %] +[% WRAPPER 'main-container.inc' aside='cat-menu' %] + [% INCLUDE 'labels-toolbar.inc' %] - [% IF ( template_id ) %] -

          Edit label template [% template_id | html %]

          - [% ELSE %] -

          New label template

          - [% END %] + [% IF ( template_id ) %] +

          Edit label template [% template_id | html %]

          + [% ELSE %] +

          New label template

          + [% END %] -
          -
          -
          -
          -
            -
          1. - Template ID:[% IF ( template_id ) %][% template_id | html %][% ELSE %]N/A[% END %] -
          2. -
          3. - - -
          4. -
          5. - - -
          6. -
          7. - - -
          8. -
          9. - - -
          10. -
          11. - - -
          12. -
          13. - - -
          14. -
          15. - - -
          16. - -
          -
          -
          -
          -
          -
          1. - - -
          2. -
          3. - - -
          4. -
          5. - - -
          6. -
          7. - - -
          8. -
          9. - - -
          10. -
          11. - - -
          12. -
          13. - - -
          14. -
          15. - - -
          16. - -
          17. - - [% IF ( profile_list ) %] - +
          18. +
          19. + + +
          20. +
          21. + + - [% END %] - [% IF ( profile_list.size == 1 ) %] -
            - Make a new printer profile. - [% END %] -
          22. -
          -
          -
          -
          -
          - [% INCLUDE 'csrf-token.inc' %] - - [% IF ( template_id ) %] - + + [% END %] + + +
        • + + +
        • +
        • + + +
        • +
        • + + +
        • +
        • + + +
        • + +
          + +
          +
          +
          1. + + +
          2. +
          3. + + +
          4. +
          5. + + +
          6. +
          7. + + +
          8. +
          9. + + +
          10. +
          11. + + +
          12. +
          13. + + +
          14. +
          15. + + +
          16. + +
          17. + + [% IF ( profile_list ) %] + [% END %] - Cancel -
          - + [% IF ( profile_list.size == 1 ) %] +
          + Make a new printer profile. + [% END %] + + + +
          + +
          + [% INCLUDE 'csrf-token.inc' %] + + [% IF ( template_id ) %] + + [% END %] + Cancel +
          + [% END %] [% MACRO jsinclude BLOCK %] - [% INCLUDE 'popup-bottom.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/mana/mana-report-search-result.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/mana/mana-report-search-result.tt index 93d95f5ea6..a2a929857a 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/mana/mana-report-search-result.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/mana/mana-report-search-result.tt @@ -1 +1 @@ -[% INCLUDE 'mana/mana-report-search-result.inc' %] \ No newline at end of file +[% INCLUDE 'mana/mana-report-search-result.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/mana/mana-subscription-search-result.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/mana/mana-subscription-search-result.tt index 9863be7ed7..0c44f7ad85 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/mana/mana-subscription-search-result.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/mana/mana-subscription-search-result.tt @@ -1 +1 @@ -[% INCLUDE 'mana/mana-subscription-search-result.inc' %] \ No newline at end of file +[% INCLUDE 'mana/mana-subscription-search-result.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/members/accountline-details.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/members/accountline-details.tt index 846bfeafda..44e3adeb00 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/members/accountline-details.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/members/accountline-details.tt @@ -9,16 +9,16 @@ [% SET footerjs = 1 %] [% PROCESS 'accounts.inc' %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% IF type == 'credit' %] - [% t("Details of credit") | html %] - [% ELSE %] - [% t("Details of debit") | html %] - [% END %] › - [% INCLUDE 'patron-title.inc' no_html = 1 %] › - [% t("Patrons") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% IF type == 'credit' %] + [% t("Details of credit") | html %] + [% ELSE %] + [% t("Details of debit") | html %] + [% END %] + › [% INCLUDE 'patron-title.inc' no_html = 1 %] › [% t("Patrons") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -58,172 +58,164 @@ [% WRAPPER 'main-container.inc' aside='circ-menu' %] - [% INCLUDE 'members-toolbar.inc' borrowernumber=patron.borrowernumber %] + [% INCLUDE 'members-toolbar.inc' borrowernumber=patron.borrowernumber %] -

          Transaction details

          +

          Transaction details

          - [% IF accountline %] - -
          - [% IF accountline.credit_type_code %] -

          Details of credit

          - [% ELSIF accountline.debit_type_code %] -

          Details of debit

          - [% END %] - - - - - - - - - - - [% FOREACH field IN available_additional_fields %] - - [% END %] - - - - - - - - - - - - - - - - - - - [% INCLUDE 'additional-fields-display.inc' available=available_additional_fields values=additional_field_values value_only=1 is_table_cell=1 %] - - - - - - - -
          DateDescriptionBarcodeDue dateReturn dateNote[% field.name | html %]AmountOutstandingLibrarian
          - [% accountline.date | $KohaDates %] - - [%- PROCESS account_type_description account=accountline -%] - [%- IF accountline.payment_type -%] - , [% AuthorisedValues.GetByCode('PAYMENT_TYPE', accountline.payment_type) | html %] - [%- END =%] - [%- IF accountline.description -%] - , [% accountline.description | html %] - [%- END -%] - -   - [% IF ( accountline.itemnumber ) %] - [% SET biblio = accountline.item.biblio %] - [% biblio.title | html %] - [% END %] - - [% IF ( accountline.itemnumber ) %] - [% accountline.item.barcode | html %] - [% END %] - - [% IF ( accountline.issue_id ) %] - [% accountline.checkout.date_due | $KohaDates as_due_date => 1 %] - [% END %] - - [% IF ( accountline.issue_id ) %] - [% accountline.checkout.returndate | $KohaDates with_hours => 1 %] - [% END %] - - [% accountline.note | html_line_break %] - - [% accountline.amount | $Price %] - - [% accountline.amountoutstanding | $Price %] - - [% IF accountline.manager_id %] - [% INCLUDE 'patron-title.inc' patron => accountline.manager, hide_patron_infos_if_needed => 1, no_cardnumber => 1 %] - [% END %] -
          -
          - -
          -

          History

          - - - - - - - - - - - - - - - - - - - - - [% FOREACH ao IN account_offsets %] - [% IF ao.credit_id == accountline.accountlines_id %] - [% SET offset_accountline = ao.debit %] - [% ELSIF ao.debit_id == accountline.accountlines_id %] - [% SET offset_accountline = ao.credit %] - [% END %] - - [%- BLOCK ao_description -%] - [%- SWITCH ao.type -%] - [%- CASE 'CREATE' -%]Created - [%- CASE 'OVERDUE_INCREASE' -%]Increase - [%- CASE 'OVERDUE_DECREASE' -%]Decrease - [%- CASE 'APPLY' -%]Applied - [%- CASE 'VOID' -%]Reversed - [%- END -%] - [%- END -%] - - - - - - - [%- IF offset_accountline -%] - - - - [%- ELSE -%] - - - - [%- END -%] - - - [% END %] - -
          DateChangeActionRelated transaction
          IncreaseDecreaseTypeAmountLibrarianNote
          [% ao.created_on | $KohaDates with_hours => 1%][%- IF ao.amount > 0 -%][% ao.amount | $Price %][% END %][%- IF ao.amount < 0 -%][% ao.amount | $Price %][% END %] - [% PROCESS ao_description ao=ao %] - - [% PROCESS account_type_description account=offset_accountline %] ([% offset_accountline.id | html %]) - - [% offset_accountline.amount | $Price %] - - [% IF offset_accountline.manager_id %] - [% INCLUDE 'patron-title.inc' patron => offset_accountline.manager, hide_patron_infos_if_needed => 1, no_cardnumber => 1 %] - [% END %] - [% offset_accountline.note | html %]
          -
          - [% ELSE %] -
          - Account not found -
          + [% IF accountline %] +
          + [% IF accountline.credit_type_code %] +

          Details of credit

          + [% ELSIF accountline.debit_type_code %] +

          Details of debit

          [% END %] + + + + + + + + + + + [% FOREACH field IN available_additional_fields %] + + [% END %] + + + + + + + + + + + + + + + + + + + [% INCLUDE 'additional-fields-display.inc' available=available_additional_fields values=additional_field_values value_only=1 is_table_cell=1 %] + + + + + + + +
          DateDescriptionBarcodeDue dateReturn dateNote[% field.name | html %]AmountOutstandingLibrarian
          [% accountline.date | $KohaDates %] + [%- PROCESS account_type_description account=accountline -%] + [%- IF accountline.payment_type -%] + , [% AuthorisedValues.GetByCode('PAYMENT_TYPE', accountline.payment_type) | html %] + [%- END = %] + [%- IF accountline.description -%] + , [% accountline.description | html %] + [%- END -%] +   + [% IF ( accountline.itemnumber ) %] + [% SET biblio = accountline.item.biblio %] + [% biblio.title | html %] + [% END %] + + [% IF ( accountline.itemnumber ) %] + [% accountline.item.barcode | html %] + [% END %] + + [% IF ( accountline.issue_id ) %] + [% accountline.checkout.date_due | $KohaDates as_due_date => 1 %] + [% END %] + + [% IF ( accountline.issue_id ) %] + [% accountline.checkout.returndate | $KohaDates with_hours => 1 %] + [% END %] + [% accountline.note | html_line_break %] [% accountline.amount | $Price %] [% accountline.amountoutstanding | $Price %] + [% IF accountline.manager_id %] + [% INCLUDE 'patron-title.inc' patron => accountline.manager, hide_patron_infos_if_needed => 1, no_cardnumber => 1 %] + [% END %] +
          +
          + + +
          +

          History

          + + + + + + + + + + + + + + + + + + + + + [% FOREACH ao IN account_offsets %] + [% IF ao.credit_id == accountline.accountlines_id %] + [% SET offset_accountline = ao.debit %] + [% ELSIF ao.debit_id == accountline.accountlines_id %] + [% SET offset_accountline = ao.credit %] + [% END %] + + [%- BLOCK ao_description -%] + [%- SWITCH ao.type -%] + + [%- CASE 'CREATE' -%] + Created + [%- CASE 'OVERDUE_INCREASE' -%] + Increase + [%- CASE 'OVERDUE_DECREASE' -%] + Decrease + [%- CASE 'APPLY' -%] + Applied + [%- CASE 'VOID' -%] + Reversed + [%- END -%] + [%- END -%] + + + + + + + [%- IF offset_accountline -%] + + + + [%- ELSE -%] + + + + [%- END -%] + + + [% END %] + +
          DateChangeActionRelated transaction
          IncreaseDecreaseTypeAmountLibrarianNote
          [% ao.created_on | $KohaDates with_hours => 1 %][%- IF ao.amount > 0 -%][% ao.amount | $Price %][% END %][%- IF ao.amount < 0 -%][% ao.amount | $Price %][% END %] [% PROCESS ao_description ao=ao %] [% PROCESS account_type_description account=offset_accountline %] ([% offset_accountline.id | html %]) [% offset_accountline.amount | $Price %] + [% IF offset_accountline.manager_id %] + [% INCLUDE 'patron-title.inc' patron => offset_accountline.manager, hide_patron_infos_if_needed => 1, no_cardnumber => 1 %] + [% END %] + [% offset_accountline.note | html %]
          +
          + + [% ELSE %] +
          Account not found
          + [% END %] [% END %] [% MACRO jsinclude BLOCK %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/members/alert-subscriptions.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/members/alert-subscriptions.tt index 0d02b8c519..e239cb4860 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/members/alert-subscriptions.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/members/alert-subscriptions.tt @@ -1,7 +1,7 @@ [% USE raw %] [% USE Koha %] [% USE Asset %] -[% USE AuthorisedValues %] +[% USE AuthorisedValues %] [% USE Branches %] [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] @@ -31,60 +31,61 @@ [% WRAPPER 'main-container.inc' aside='circ-menu' %] - [% INCLUDE 'members-toolbar.inc' %] -

          Alert subscriptions

          + [% INCLUDE 'members-toolbar.inc' %] +

          Alert subscriptions

          - [% IF patron.alert_subscriptions.count %] -
          - - - - - - - - - - - + [% IF patron.alert_subscriptions.count %] +
          +
          ISSNTitleLibraryLocationCall numberActions
          + + + + + + + + + + - - [% FOREACH sub IN patron.alert_subscriptions %] - - - - - - - - - [% END %] - -
          ISSNTitleLibraryLocationCall numberActions
          - [% IF sub.biblio.biblioitem.issn %][% sub.biblio.biblioitem.issn | html %][% END %] - - [% sub.biblio.title | html %] [% sub.biblio.subtitle | html %] - - [% IF ( sub.branchcode ) %][% Branches.GetName( sub.branchcode ) | html %][% END %] - - [% IF ( sub.location ) %][% AuthorisedValues.GetDescriptionByKohaField( kohafield => 'items.location', authorised_value => sub.location ) | html %][% END %] - - [% IF ( sub.callnumber ) %][% sub.callnumber | html %][% END %] - -
          - [% INCLUDE 'csrf-token.inc' %] - - - - -
          -
          -
          - [% ELSE %] -
          -

          This patron has not subscribed to email alerts for any subscriptions.

          -
          - [% END %] + + [% FOREACH sub IN patron.alert_subscriptions %] + + [% IF sub.biblio.biblioitem.issn %][% sub.biblio.biblioitem.issn | html %][% END %] + + [% sub.biblio.title | html %] [% sub.biblio.subtitle | html %] + + [% IF ( sub.branchcode ) %][% Branches.GetName( sub.branchcode ) | html %][% END %] + [% IF ( sub.location ) %][% AuthorisedValues.GetDescriptionByKohaField( kohafield => 'items.location', authorised_value => sub.location ) | html %][% END %] + [% IF ( sub.callnumber ) %][% sub.callnumber | html %][% END %] + +
          + [% INCLUDE 'csrf-token.inc' %] + + + + +
          + + + [% END %] + + + + + [% ELSE %] +
          +

          This patron has not subscribed to email alerts for any subscriptions.

          +
          + [% END %] [% END %] [% MACRO jsinclude BLOCK %] @@ -92,12 +93,11 @@ [% Asset.js("js/members-menu.js") | $raw %] [% INCLUDE 'datatables.inc' %] [% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/members/files.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/members/files.tt index 4db1ea5710..2f60223bd1 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/members/files.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/members/files.tt @@ -7,11 +7,13 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Files for") | html %] [% INCLUDE 'patron-title.inc' no_html = 1 %] › - [% t("Patrons") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Files for") | html %] + [% INCLUDE 'patron-title.inc' no_html = 1 %] + › [% t("Patrons") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -36,97 +38,98 @@ [% WRAPPER 'main-container.inc' aside='circ-menu' %] - [% INCLUDE 'members-toolbar.inc' %] + [% INCLUDE 'members-toolbar.inc' %] -

          Files

          +

          Files

          - [% IF errors %] -
          - [% IF errors.empty_upload %]The file you are attempting to upload has no contents.[% END %] - [% IF errors.no_file %]You did not select a file to upload.[% END %] - [% IF errors.upload_failed %]The upload failed. More information may be in the system logs.[% END %] -
          - [% END %] + [% IF errors %] +
          + [% IF errors.empty_upload %]The file you are attempting to upload has no contents.[% END %] + [% IF errors.no_file %]You did not select a file to upload.[% END %] + [% IF errors.upload_failed %]The upload failed. More information may be in the system logs.[% END %] +
          + [% END %] - [% IF ( files ) %] -
          - - - - - - - - [% IF CAN_user_borrowers_edit_borrowers %][% END %] - - + [% IF ( files ) %] +
          +
          NameTypeDescriptionUploaded 
          + + + + + + + [% IF CAN_user_borrowers_edit_borrowers %][% END %] + + - - [% FOREACH f IN files %] - - - - - - [% IF CAN_user_borrowers_edit_borrowers %] - - [% END %] - - [% END %] - -
          NameTypeDescriptionUploaded 
          [% f.file_name | html %][% f.file_type | html %][% f.file_description | html %][% f.date_uploaded | $KohaDates %] -
          - [% INCLUDE 'csrf-token.inc' %] - - - - -
          -
          -
          - [% ELSE %] -
          -

          This patron has no files attached.

          -
          - [% END %] + + [% FOREACH f IN files %] + + [% f.file_name | html %] + [% f.file_type | html %] + [% f.file_description | html %] + [% f.date_uploaded | $KohaDates %] + [% IF CAN_user_borrowers_edit_borrowers %] + +
          + [% INCLUDE 'csrf-token.inc' %] + + + + +
          + + [% END %] + + [% END %] + + + + [% ELSE %] +
          +

          This patron has no files attached.

          +
          + [% END %] -
          - [% INCLUDE 'csrf-token.inc' %] -
          - Upload new file -
            -
          1. - - + + [% INCLUDE 'csrf-token.inc' %] +
            + Upload new file +
              +
            1. + + - -
            2. + + -
            3. - -
            -
            -
            - -
            -
          2. +
          3. +
          +
          +
          + +
          + [% END %] [% MACRO jsinclude BLOCK %] [% INCLUDE 'str/members-menu.inc' %] [% Asset.js("js/members-menu.js") | $raw %] [% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/members/holdshistory.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/members/holdshistory.tt index 7f405369ca..5b3cd3c49e 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/members/holdshistory.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/members/holdshistory.tt @@ -9,11 +9,13 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Holds history for") | html %] [% INCLUDE 'patron-title.inc' no_html = 1 %] › - [% t("Patrons") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Holds history for") | html %] + [% INCLUDE 'patron-title.inc' no_html = 1 %] + › [% t("Patrons") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -38,90 +40,83 @@ [% WRAPPER 'main-container.inc' aside='circ-menu' %] -[% INCLUDE 'members-toolbar.inc' %] -

          Holds history

          + [% INCLUDE 'members-toolbar.inc' %] +

          Holds history

          -[% UNLESS Koha.Preference('IntranetReadingHistoryHolds') %] -
          Staff members are not allowed to access patron's holds history
          -[% ELSIF is_anonymous %] -
          This is the anonymous patron, so no holds history is displayed.
          -[% ELSIF ( !holds ) %] -
          This patron has no holds history.
          -[% ELSE %] + [% UNLESS Koha.Preference('IntranetReadingHistoryHolds') %] +
          Staff members are not allowed to access patron's holds history
          + [% ELSIF is_anonymous %] +
          This is the anonymous patron, so no holds history is displayed.
          + [% ELSIF ( !holds ) %] +
          This patron has no holds history.
          + [% ELSE %] -[% SET show_itemtype_column = Koha.Preference('AllowHoldItemTypeSelection') %] + [% SET show_itemtype_column = Koha.Preference('AllowHoldItemTypeSelection') %] -
          - - - - - - - - - - - - - [% IF show_itemtype_column %] - - [% END %] - - - - - [% FOREACH hold IN holds %] - - - - - - - - - - - [% IF show_itemtype_column %] - - [% END %] - - - [% END %] - -
          TitleAuthorBarcodeCall numberLibraryHold dateExpiration dateWaiting dateCancellation dateRequested item typeStatus
          [% INCLUDE 'biblio-title.inc' biblio=hold.biblio link = 1 %][% hold.biblio.author | html %][% hold.item.barcode | html %][% hold.item.itemcallnumber | html %][% Branches.GetName( hold.branchcode ) | html %][% hold.reservedate | $KohaDates %] - [% hold.expirationdate | $KohaDates %] - - [% hold.waitingdate | $KohaDates %] - - [% hold.cancellationdate | $KohaDates %] - - [% IF hold.itemtype %] - [% ItemTypes.GetDescription( hold.itemtype ) | html %] - [% ELSE %] - Any item type - [% END %] - - [% IF hold.found == 'F' %] - Fulfilled - [% ELSIF hold.cancellationdate %] - Cancelled - [% IF hold.cancellation_reason %] - ([% AuthorisedValues.GetByCode('HOLD_CANCELLATION', hold.cancellation_reason) | html %]) - [% END %] - [% ELSIF hold.found == 'W' %] - Waiting - [% ELSIF hold.found == 'P' %] - Processing - [% ELSIF hold.found == 'T' %] - In transit - [% ELSE %] - Pending - [% END %] -
          -
          - -[% END %] +
          + + + + + + + + + + + + + [% IF show_itemtype_column %] + + [% END %] + + + + + [% FOREACH hold IN holds %] + + + + + + + + + + + [% IF show_itemtype_column %] + + [% END %] + + + [% END %] + +
          TitleAuthorBarcodeCall numberLibraryHold dateExpiration dateWaiting dateCancellation dateRequested item typeStatus
          [% INCLUDE 'biblio-title.inc' biblio=hold.biblio link = 1 %][% hold.biblio.author | html %][% hold.item.barcode | html %][% hold.item.itemcallnumber | html %][% Branches.GetName( hold.branchcode ) | html %][% hold.reservedate | $KohaDates %] [% hold.expirationdate | $KohaDates %] [% hold.waitingdate | $KohaDates %] [% hold.cancellationdate | $KohaDates %] + [% IF hold.itemtype %] + [% ItemTypes.GetDescription( hold.itemtype ) | html %] + [% ELSE %] + Any item type + [% END %] + + [% IF hold.found == 'F' %] + Fulfilled + [% ELSIF hold.cancellationdate %] + Cancelled + [% IF hold.cancellation_reason %] + ([% AuthorisedValues.GetByCode('HOLD_CANCELLATION', hold.cancellation_reason) | html %]) + [% END %] + [% ELSIF hold.found == 'W' %] + Waiting + [% ELSIF hold.found == 'P' %] + Processing + [% ELSIF hold.found == 'T' %] + In transit + [% ELSE %] + Pending + [% END %] +
          +
          + [% END %] [% END %] [% MACRO jsinclude BLOCK %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/members/housebound.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/members/housebound.tt index a5fbc6cf35..10d6ead820 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/members/housebound.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/members/housebound.tt @@ -7,11 +7,13 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Details for") | html %] [% INCLUDE 'patron-title.inc' no_html = 1 %] › - [% t("Housebound") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Details for") | html %] + [% INCLUDE 'patron-title.inc' no_html = 1 %] + › [% t("Housebound") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -23,43 +25,51 @@ [% BLOCK 'homebound-details' %]
            -
          1. - Delivery day: - [% hpd = housebound_profile.day %] - [% IF hpd == 'any' %]Any - [% ELSIF hpd == 'monday' %]Monday - [% ELSIF hpd == 'tuesday' %]Tuesday - [% ELSIF hpd == 'wednesday' %]Wednesday - [% ELSIF hpd == 'thursday' %]Thursday - [% ELSIF hpd == 'friday' %]Friday - [% ELSIF hpd == 'saturday' %]Saturday - [% ELSIF hpd == 'sunday' %]Sunday - [% END %] -
          2. -
          3. - Frequency: - [% AuthorisedValues.GetByCode( 'HSBND_FREQ', housebound_profile.frequency, 0 ) || housebound_profile.frequency | html %] -
          4. -
          5. - Material:
            - [% housebound_profile.fav_itemtypes | html | html_line_break %] -
          6. -
          7. - Subjects:
            - [% housebound_profile.fav_subjects | html | html_line_break %] -
          8. -
          9. - Authors:
            - [% housebound_profile.fav_authors | html | html_line_break %] -
          10. -
          11. - Referral:
            - [% housebound_profile.referral | html | html_line_break %] -
          12. -
          13. - Notes:
            - [% housebound_profile.notes | html | html_line_break %] -
          14. +
          15. + Delivery day: + [% hpd = housebound_profile.day %] + [% IF hpd == 'any' %] + Any + [% ELSIF hpd == 'monday' %] + Monday + [% ELSIF hpd == 'tuesday' %] + Tuesday + [% ELSIF hpd == 'wednesday' %] + Wednesday + [% ELSIF hpd == 'thursday' %] + Thursday + [% ELSIF hpd == 'friday' %] + Friday + [% ELSIF hpd == 'saturday' %] + Saturday + [% ELSIF hpd == 'sunday' %] + Sunday + [% END %] +
          16. +
          17. + Frequency: + [% AuthorisedValues.GetByCode( 'HSBND_FREQ', housebound_profile.frequency, 0 ) || housebound_profile.frequency | html %] +
          18. +
          19. + Material:
            + [% housebound_profile.fav_itemtypes | html | html_line_break %] +
          20. +
          21. + Subjects:
            + [% housebound_profile.fav_subjects | html | html_line_break %] +
          22. +
          23. + Authors:
            + [% housebound_profile.fav_authors | html | html_line_break %] +
          24. +
          25. + Referral:
            + [% housebound_profile.referral | html | html_line_break %] +
          26. +
          27. + Notes:
            + [% housebound_profile.notes | html | html_line_break %] +
          [% END %] @@ -80,360 +90,328 @@ [% WRAPPER 'main-container.inc' aside='circ-menu' %] - [% INCLUDE 'members-toolbar.inc' %] + [% INCLUDE 'members-toolbar.inc' %] -

          Housebound details for [% INCLUDE 'patron-title.inc' %]

          +

          Housebound details for [% INCLUDE 'patron-title.inc' %]

          - [% FOR m IN messages %] -
          - [% SWITCH m.code %] - [% CASE 'error_on_profile_store' %] - An error occurred whilst updating this housebound profile - [% CASE 'error_on_profile_create' %] - An error occurred whilst creating this housebound profile - [% CASE 'error_on_visit_load' %] - An error occurred whilst loading the housebound visit - [% CASE 'error_on_visit_delete' %] - An error occurred whilst deleting a housebound visit - [% CASE 'error_on_visit_store' %] - An error occurred whilst updating a housebound visit - [% CASE 'error_on_visit_create' %] - An error occurred whilst creating a new housebound visit - [% CASE %] - [% m.code | html %] - [% END %] - Please try again later -
          + [% FOR m IN messages %] +
          + [% SWITCH m.code %] + [% CASE 'error_on_profile_store' %] + An error occurred whilst updating this housebound profile + [% CASE 'error_on_profile_create' %] + An error occurred whilst creating this housebound profile + [% CASE 'error_on_visit_load' %] + An error occurred whilst loading the housebound visit + [% CASE 'error_on_visit_delete' %] + An error occurred whilst deleting a housebound visit + [% CASE 'error_on_visit_store' %] + An error occurred whilst updating a housebound visit + [% CASE 'error_on_visit_create' %] + An error occurred whilst creating a new housebound visit + [% CASE %] + [% m.code | html %] [% END %] + Please try again later +
          + [% END %] - - [% IF ( op == 'update_or_create' ) %] -
          - [% INCLUDE 'csrf-token.inc' %] - - [% IF ( housebound_profile ) %] - - [% ELSE %] - - [% END %] -
          - Manage housebound profile -
            + + [% IF ( op == 'update_or_create' ) %] + + [% INCLUDE 'csrf-token.inc' %] + + [% IF ( housebound_profile ) %] + + [% ELSE %] + + [% END %] +
            + Manage housebound profile +
            1. - - - Required -
            2. -
            3. - - - Required -
            4. -
            5. - - [% IF ( housebound_profile ) %] - - [% ELSE %] - - [% END %] -
            6. -
            7. - - [% IF ( housebound_profile ) %] - - [% ELSE %] - - [% END %] -
            8. -
            9. - - [% IF ( housebound_profile ) %] - - [% ELSE %] - - [% END %] -
            10. -
            11. - - [% IF ( housebound_profile ) %] - - [% ELSE %] - - [% END %] -
            12. -
            13. - - [% IF ( housebound_profile ) %] - - [% ELSE %] - - [% END %] -
            14. -
            -
            -
            - - - Cancel - -
            - - - - [% ELSIF ( op == 'visit_update_or_create' ) %] -

            Manage housebound deliveries

            -
            - [% INCLUDE 'csrf-token.inc' %] - [% IF ( visit ) %] - - - [% ELSE %] - - [% END %] - -
            - Delivery details -
              -
            1. - - [% IF ( visit ) %] - - [% ELSE %] - - [% END %] - Required -
              [% INCLUDE 'date-format.inc' %]
              -
            2. -
            3. - - - Required -
            4. -
            5. - - - Required -
            6. -
            7. - - - Required -
            8. -
            -
            -
            - - - Cancel - -
            -
            -
            -

            Housebound details

            - [% PROCESS 'homebound-details' %] - -
            - [% ELSIF ( housebound_profile ) %] -
            - [% PROCESS 'homebound-details' %] -
            - Edit -
            -
            - -
            -

            Deliveries

            - [% housebound_visits = housebound_profile.housebound_visits %] - [% IF housebound_visits.count > 0 %] - - - - - - - - - - - - [% FOREACH entry IN housebound_visits %] - - - - - - - + + -
            IDDateChooserDelivererActions
            [% entry.id | html %][% entry.appointment_date | $KohaDates %] ([% entry.day_segment | html %]) - - [% INCLUDE 'patron-title.inc' patron = entry.chooser invert_name = 0 %] - - - - [% INCLUDE 'patron-title.inc' patron = entry.deliverer invert_name = 0 %] - - - Edit -
            - [% INCLUDE 'csrf-token.inc' %] - - - - -
            -
            - [% END %] - -
            + [% IF ( housebound_profile.day == 'monday' ) %] + + [% ELSE %] + + [% END %] + [% IF ( housebound_profile.day == 'tuesday' ) %] + + [% ELSE %] + + [% END %] + [% IF ( housebound_profile.day == 'wednesday' ) %] + + [% ELSE %] + + [% END %] + [% IF ( housebound_profile.day == 'thursday' ) %] + + [% ELSE %] + + [% END %] + [% IF ( housebound_profile.day == 'friday' ) %] + + [% ELSE %] + + [% END %] + [% IF ( housebound_profile.day == 'saturday' ) %] + + [% ELSE %] + + [% END %] + [% IF ( housebound_profile.day == 'sunday' ) %] + + [% ELSE %] + + [% END %] + [% ELSE %] + + + + + + + + + [% END %] + + Required + +
          1. + + + Required +
          2. +
          3. + + [% IF ( housebound_profile ) %] + + [% ELSE %] + + [% END %] +
          4. +
          5. + + [% IF ( housebound_profile ) %] + + [% ELSE %] + + [% END %] +
          6. +
          7. + + [% IF ( housebound_profile ) %] + + [% ELSE %] + + [% END %] +
          8. +
          9. + + [% IF ( housebound_profile ) %] + + [% ELSE %] + + [% END %] +
          10. +
          11. + + [% IF ( housebound_profile ) %] + + [% ELSE %] + + [% END %] +
          12. +
          +
          +
          + + Cancel +
          + + + [% ELSIF ( op == 'visit_update_or_create' ) %] +

          Manage housebound deliveries

          +
          + [% INCLUDE 'csrf-token.inc' %] + [% IF ( visit ) %] + + + [% ELSE %] + [% END %] + +
          + Delivery details +
            +
          1. + + [% IF ( visit ) %] + + [% ELSE %] + + [% END %] + Required +
            [% INCLUDE 'date-format.inc' %]
            +
          2. +
          3. + + + Required +
          4. +
          5. + + + Required +
          6. +
          7. + + + Required +
          8. +
          +
          +
          + + Cancel +
          +
          +
          +

          Housebound details

          + [% PROCESS 'homebound-details' %] + +
          + + [% ELSIF ( housebound_profile ) %] +
          + [% PROCESS 'homebound-details' %] +
          + Edit +
          +
          + +
          +

          Deliveries

          + [% housebound_visits = housebound_profile.housebound_visits %] + [% IF housebound_visits.count > 0 %] + + + + + + + + + + + + [% FOREACH entry IN housebound_visits %] + + + + + + + + [% END %] + +
          IDDateChooserDelivererActions
          [% entry.id | html %][% entry.appointment_date | $KohaDates %] ([% entry.day_segment | html %]) + [% INCLUDE 'patron-title.inc' patron = entry.chooser invert_name = 0 %] + + [% INCLUDE 'patron-title.inc' patron = entry.deliverer invert_name = 0 %] + + Edit +
          + [% INCLUDE 'csrf-token.inc' %] + + + + +
          +
          + [% END %] + +
          + + [% END %] [% END %] [% MACRO jsinclude BLOCK %] @@ -441,14 +419,14 @@ [% INCLUDE 'datatables.inc' %] [% INCLUDE 'columns_settings.inc' %] [% INCLUDE 'str/members-menu.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/members/ill-requests.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/members/ill-requests.tt index 37b44fd969..67a019fc49 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/members/ill-requests.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/members/ill-requests.tt @@ -9,16 +9,18 @@ [% USE TablesSettings %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("ILL requests history for") | html %] [% INCLUDE 'patron-title.inc' no_html = 1 %] › - [% t("Patrons") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("ILL requests history for") | html %] + [% INCLUDE 'patron-title.inc' no_html = 1 %] + › [% t("Patrons") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] - [% WRAPPER 'header.inc' %] +[% WRAPPER 'header.inc' %] [% INCLUDE 'patron-search-header.inc' %] [% END %] @@ -37,31 +39,29 @@ [% END #/ WRAPPER sub-header.inc %] [% WRAPPER 'main-container.inc' aside='circ-menu' %] - [% INCLUDE 'messages.inc' %] - [% INCLUDE 'members-toolbar.inc' %] -

          ILL requests history

          -
          - [% INCLUDE 'ill-list-table.inc' %] -
          + [% INCLUDE 'messages.inc' %] + [% INCLUDE 'members-toolbar.inc' %] +

          ILL requests history

          +
          [% INCLUDE 'ill-list-table.inc' %]
          [% END %] - [% MACRO jsinclude BLOCK %] - [% INCLUDE 'str/members-menu.inc' %] - [% Asset.js("js/members-menu.js") | $raw %] - [% INCLUDE 'datatables.inc' %] - [% INCLUDE 'columns_settings.inc' %] - [% INCLUDE 'js-biblio-format.inc' %] - [% INCLUDE 'js-patron-format.inc' %] - [% INCLUDE 'calendar.inc' %] - - [% INCLUDE 'ill-list-table-strings.inc' %] - [% Asset.js("js/ill-list-table.js") | $raw %] - [% END %] + var ill_table_actions = [% table_actions | $raw %]; + + [% INCLUDE 'ill-list-table-strings.inc' %] + [% Asset.js("js/ill-list-table.js") | $raw %] +[% END %] [% INCLUDE 'intranet-bottom.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/members/mancredit.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/members/mancredit.tt index f9fcba7376..cd1e5021b4 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/members/mancredit.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/members/mancredit.tt @@ -8,11 +8,12 @@ [% PROCESS 'accounts.inc' %] [% INCLUDE 'doc-head-open.inc' %] [% SET registers = Registers.all( { filters => { current_branch => 1 } } ) %] -[% FILTER collapse %] - [% t("Create manual credit") | html %] › - [% t("Patrons") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Create manual credit") | html %] + › [% t("Patrons") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -37,80 +38,83 @@ [% WRAPPER 'main-container.inc' aside='circ-menu' %] - [% INCLUDE 'members-toolbar.inc' %] + [% INCLUDE 'members-toolbar.inc' %] -

          Manual credit

          +

          Manual credit

          - -
          - -
          -
          -
          - - - [% INCLUDE 'csrf-token.inc' %] + +
          + + +
          +
          + + + + [% INCLUDE 'csrf-token.inc' %] -
          - Manual credit -
            -
          1. - - -
          2. -
          3. -
          4. -
          5. -
          6. Example: 5.00
          7. - [% INCLUDE 'transaction_types.inc' type="credit" %] - [% IF Koha.Preference('UseCashRegisters') %] -
          8. - - - - - [% IF Koha.Preference('RequireCashRegister') %] - Required - [% END %] -
          9. +
            + Manual credit +
              +
            1. + + +
            2. +
            3. +
            4. +
            5. +
            6. Example: 5.00
            7. + [% INCLUDE 'transaction_types.inc' type="credit" %] + [% IF Koha.Preference('UseCashRegisters') %] +
            8. + - [% IF available_additional_fields %] - [% INCLUDE 'additional-fields-entry.inc' available=available_additional_fields values=additional_field_values %] + + + [% IF Koha.Preference('RequireCashRegister') %] + Required + [% END %] +
            9. [% END %] +
            +
            -
            Cancel
            - -
          -
          -
          + [% IF available_additional_fields %] + [% INCLUDE 'additional-fields-entry.inc' available=available_additional_fields values=additional_field_values %] + [% END %] +
          Cancel
          + +
          + +
          + +
          + [% END %] [% MACRO jsinclude BLOCK %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/members/maninvoice.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/members/maninvoice.tt index 9539214c3a..9e195f728f 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/members/maninvoice.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/members/maninvoice.tt @@ -7,11 +7,12 @@ [% SET footerjs = 1 %] [% PROCESS 'accounts.inc' %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Create manual invoice") | html %] › - [% t("Patrons") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Create manual invoice") | html %] + › [% t("Patrons") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -35,38 +36,35 @@ [% END #/ WRAPPER sub-header.inc %] [% WRAPPER 'main-container.inc' aside='circ-menu' %] - [% INCLUDE 'members-toolbar.inc' %] + [% INCLUDE 'members-toolbar.inc' %] -

          Manual invoice

          +

          Manual invoice

          - -
          - -
          -
          + +
          + + +
          +
          [% IF error == 'itemnumber' %] -
          - Error: Invalid item barcode entered, please try again -
          +
          Error: Invalid item barcode entered, please try again
          [% ELSIF error %] -
          - An error occurred, please try again: [% error | html %] -
          +
          An error occurred, please try again: [% error | html %]
          [% END %]
          @@ -79,11 +77,11 @@ @@ -92,7 +90,10 @@
        • -
        • Example: 5.00
        • +
        • Example: 5.00
        • @@ -106,11 +107,12 @@ Cancel
          - -
          -
          -
          - +
          + +
          + +
          + [% END %] [% MACRO jsinclude BLOCK %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/members/member-flags.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/members/member-flags.tt index f31f83fd23..2299ab5301 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/members/member-flags.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/members/member-flags.tt @@ -6,11 +6,13 @@ [% SET footerjs = 1 %] [% PROCESS 'permissions.inc' %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Set permissions for") | html %] [% INCLUDE 'patron-title.inc' no_html = 1 %] › - [% t("Patrons") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Set permissions for") | html %] + [% INCLUDE 'patron-title.inc' no_html = 1 %] + › [% t("Patrons") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -34,86 +36,90 @@ [% END #/ WRAPPER sub-header.inc %] [% WRAPPER 'main-container.inc' aside='circ-menu' %] -[% INCLUDE 'members-toolbar.inc' %] + [% INCLUDE 'members-toolbar.inc' %] -
          - [% INCLUDE 'csrf-token.inc' %] - - -

          Set permissions for [% INCLUDE 'patron-title.inc' no_html = 1 %]

          + + [% INCLUDE 'csrf-token.inc' %] + + +

          Set permissions for [% INCLUDE 'patron-title.inc' no_html = 1 %]

          -
          -
          - - Cancel - Show all - Hide all - - Select all - - - Clear all - +
          +
          + + Cancel + Show all + Hide all + Select all + Clear all -
          - - - +
          + + + +
          + + Paste permissions +
          + + +
          - - Paste permissions -
          - - -
          -
          -
          - [% FOREACH loo IN loop %] -
          - [% IF ( loo.checked ) %] - [% IF disable_superlibrarian_privs && loo.bit == 0 %] - - - [% ELSE %] - - [% END %] - [% ELSE %] - [% IF disable_superlibrarian_privs && loo.bit == 0 %] - - [% ELSE %] - - [% END %] - [% END # /IF loo.checked %] - - [% IF ( loo.flag == "superlibrarian" ) %]
          This permission grants access to all areas. If selected, specific sub-permissions cannot be selected.
          [% END %] - [% IF ( loo.sub_perm_loop ) %] - Hide details - Show details -
          - [% FOREACH sub_perm_loo IN loo.sub_perm_loop %] -
          - [% IF ( sub_perm_loo.checked ) %] - - [% ELSE %] - +
          + [% FOREACH loo IN loop %] +
          + [% IF ( loo.checked ) %] + [% IF disable_superlibrarian_privs && loo.bit == 0 %] + + + [% ELSE %] + + [% END %] + [% ELSE %] + [% IF disable_superlibrarian_privs && loo.bit == 0 %] + + [% ELSE %] + + [% END %] + [% END # /IF loo.checked %] + + [% IF ( loo.flag == "superlibrarian" ) %]
          This permission grants access to all areas. If selected, specific sub-permissions cannot be selected.
          [% END %] + [% IF ( loo.sub_perm_loop ) %] + Hide details + Show details +
          + [% FOREACH sub_perm_loo IN loo.sub_perm_loop %] +
          + [% IF ( sub_perm_loo.checked ) %] + + [% ELSE %] + + [% END %] + +
          [% END %] -
          - [% END %] -
          - [% END # /IF loo.sub_perm_loop %] -
          - [% END # /FOREACH loo %] + + [% END # /IF loo.sub_perm_loop %] +
          + + [% END # /FOREACH loo %] +
          -
          - - + + [% END %] [% MACRO jsinclude BLOCK %] @@ -317,7 +323,6 @@ } }); } - [% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/members/member-password.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/members/member-password.tt index b96cdb4999..83b5a20fbe 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/members/member-password.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/members/member-password.tt @@ -5,15 +5,17 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% IF ( newpassword ) %] - [% t("Password updated") | html %] - [% ELSE %] - [% t("Update password for") | html %] [% INCLUDE 'patron-title.inc' no_html = 1 %] - [% END %] › - [% t("Patrons") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% IF ( newpassword ) %] + [% t("Password updated") | html %] + [% ELSE %] + [% t("Update password for") | html %] + [% INCLUDE 'patron-title.inc' no_html = 1 %] + [% END %] + › [% t("Patrons") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -42,79 +44,82 @@ [% WRAPPER 'main-container.inc' aside='circ-menu' %] -[% INCLUDE 'members-toolbar.inc' %] + [% INCLUDE 'members-toolbar.inc' %] -[% IF ( newpassword ) %] -

          Password updated

          + [% IF ( newpassword ) %] +

          Password updated

          + [% ELSE %] +
          + + + + [% IF ( errormsg ) %] +
          +

          The following errors have occurred:

          +
            + [% IF ( BADUSERID ) %] +
          • You have entered a username that already exists. Please choose another one.
          • + [% END %] + [% IF ( ERROR_password_too_short ) %] +
          • Password must be at least [% patron.category.effective_min_password_length | html %] characters long.
          • + [% END %] + [% IF ( ERROR_password_too_weak ) %] +
          • Password must contain at least one digit, one lowercase and one uppercase.
          • + [% END %] + [% IF ( ERROR_password_has_whitespaces ) %] +
          • Password must not contain leading or trailing whitespaces.
          • + [% END %] + [% IF ( ERROR_from_plugin ) %] +
          • The password was rejected by a plugin.
          • + [% END %] + [% IF ( NOPERMISSION ) %] +
          • You do not have permission to edit this patron's login information.
          • + [% END %] + [% IF ( NOMATCH ) %] +
          • The passwords entered do not match. Please re-enter the new password.
          • + [% END %] +
          +
          + [% END %] -[% ELSE %] +

          + Change username and/or password for [% patron.firstname | html %] [% patron.surname | html %] +

          - - - - - [% IF ( errormsg ) %] -
          -

          The following errors have occurred:

          -
            - [% IF ( BADUSERID ) %] -
          • You have entered a username that already exists. Please choose another one.
          • - [% END %] - [% IF ( ERROR_password_too_short ) %] -
          • Password must be at least [% patron.category.effective_min_password_length | html %] characters long.
          • - [% END %] - [% IF ( ERROR_password_too_weak ) %] -
          • Password must contain at least one digit, one lowercase and one uppercase.
          • - [% END %] - [% IF ( ERROR_password_has_whitespaces ) %] -
          • Password must not contain leading or trailing whitespaces.
          • - [% END %] - [% IF ( ERROR_from_plugin ) %] -
          • The password was rejected by a plugin.
          • - [% END %] - [% IF ( NOPERMISSION ) %] -
          • You do not have permission to edit this patron's login information.
          • - [% END %] - [% IF ( NOMATCH ) %] -
          • The passwords entered do not match. Please re-enter the new password.
          • - [% END %] -
          -
          - [% END %] - -

          - Change username and/or password for [% patron.firstname | html %] [% patron.surname | html %] -

          - -
          -
            -
          1. -
          2. - [% SET password_pattern = ".{" _ patron.category.effective_min_password_length _ ",}" %] - [% IF patron.category.effective_require_strong_password %] - [% SET password_pattern = '(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{' _ patron.category.effective_min_password_length _ ',}' %] +
            +
              +
            1. + [% SET password_pattern = ".{" _ patron.category.effective_min_password_length _ ",}" %] + [% IF patron.category.effective_require_strong_password %] + [% SET password_pattern = '(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{' _ patron.category.effective_min_password_length _ ',}' %] + [% END %] +
            2. + + +
            3. +
            4. + + +
              Koha cannot display existing passwords. Leave the field blank to leave password unchanged.
              +
            5. +
            +
            +
            + [% INCLUDE 'csrf-token.inc' %] + + Cancel +
            + [% END %] -
          3. - - -
          4. -
          5. - - -
            Koha cannot display existing passwords. Leave the field blank to leave password unchanged.
            -
          6. -
          -
          -
          - [% INCLUDE 'csrf-token.inc' %] - - Cancel -
          -[% END %] - - - + [% END %] [% MACRO jsinclude BLOCK %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/members/member.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/members/member.tt index b12ddfb1ce..9fecbdd2ce 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/members/member.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/members/member.tt @@ -14,13 +14,16 @@ [% SET searchtype = searchtype || Koha.Preference('DefaultPatronSearchMethod') %] [% PROCESS 'patron-search.inc' %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% IF ( searching ) %] - [% t("Search results") | html %] › - [% END %] - [% t("Patrons") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% IF ( searching ) %] + [% t("Search results") | html %] + › + [% END %] + [% t("Patrons") | html %] + › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -43,125 +46,137 @@
          [% INCLUDE 'messages.inc' %] - [% IF CAN_user_tools_manage_patron_lists %] -
          - Added patrons to . -
          - [% END %] + [% IF CAN_user_tools_manage_patron_lists %] +
          Added patrons to .
          + [% END %] - [% INCLUDE 'patron-toolbar.inc' %] - [% INCLUDE 'noadd-warnings.inc' %] + [% INCLUDE 'patron-toolbar.inc' %] + [% INCLUDE 'noadd-warnings.inc' %] - [% IF CAN_user_borrowers_edit_borrowers && pending_borrower_modifications %] - - [% END %] - -
          - [% IF CAN_user_tools_manage_patron_lists || CAN_user_borrowers_edit_borrowers %] - - [% IF CAN_user_tools_edit_patrons %] -
          - [% INCLUDE 'csrf-token.inc' %] - - -
          - [% END %] +
          + [% IF CAN_user_tools_manage_patron_lists || CAN_user_borrowers_edit_borrowers %] + + [% END %] + + [% IF CAN_user_borrowers_edit_borrowers || CAN_user_tools_manage_patron_lists %] + [% columns.unshift('checkbox') | html %] + [% END %] + [% PROCESS patron_search_table table_id => 'memberresultst' columns => columns %] +
          + [% IF CAN_user_tools_edit_patrons %] +
          + [% INCLUDE 'csrf-token.inc' %] + + +
          + [% END %] [%- SET StaffPatronsHome = AdditionalContents.get( location => "StaffPatronsHome", lang => lang, library => Branches.GetLoggedInBranchcode ) -%] [%- FOREACH block IN StaffPatronsHome.content -%] -
          - [%- block.content | $raw -%] -
          +
          [%- block.content | $raw -%]
          [%- END -%] -
          -
          +
          +
          [% PROCESS patron_search_filters categories => categories, libraries => libraries, filters => ['search_field', 'search_type', 'category', 'branch'], search_filter => searchmember %] -
          -
          - + + + + + + - - + [% UNLESS ( op == 'add_form' ) %] +
          + +
          + + [% END %] + + + + [% MACRO jsinclude BLOCK %] [% INCLUDE 'calendar.inc' %] @@ -1947,7 +1979,6 @@ legend.collapsed i.fa.fa-caret-down::before { var TalkingTechItivaPhoneNotification = [% Koha.Preference('TalkingTechItivaPhoneNotification') || 0 | html %]; var PhoneNotification = [% Koha.Preference('PhoneNotification') || 0 | html %]; - [% Asset.js("js/members.js") | $raw %] [% Asset.js("js/messaging-preference-form.js") | $raw %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/members/members-update.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/members/members-update.tt index 05de68a301..81e2ceaec7 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/members/members-update.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/members/members-update.tt @@ -8,11 +8,12 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Update patron records") | html %] › - [% t("Patrons") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Update patron records") | html %] + › [% t("Patrons") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -22,69 +23,121 @@ [% END %] [% BLOCK display_names %] -[% SWITCH field %] -[% CASE 'branchcode' %]Home library (branchcode) -[% CASE 'surname' %]Surname -[% CASE 'firstname' %]First name -[% CASE 'preferred_name' %]Preferred name -[% CASE 'middle_name' %]Middle name -[% CASE 'title' %]Title -[% CASE 'othernames' %]Other names -[% CASE 'initials' %]Initials -[% CASE 'pronouns' %]Pronouns -[% CASE 'streetnumber' %]Street number -[% CASE 'streettype' %]Street type -[% CASE 'address' %]Address -[% CASE 'address2' %]Address 2 -[% CASE 'city' %]City -[% CASE 'state' %]State -[% CASE 'zipcode' %]ZIP/Postal code -[% CASE 'country' %]Country -[% CASE 'email' %]Email -[% CASE 'phone' %]Primary phone -[% CASE 'mobile' %]Other phone -[% CASE 'fax' %]Fax -[% CASE 'emailpro' %]Secondary email -[% CASE 'phonepro' %]Secondary phone -[% CASE 'B_streetnumber' %]Alternate address: Street number -[% CASE 'B_streettype' %]Alternate address: Street type -[% CASE 'B_address' %]Alternate address: Address -[% CASE 'B_address2' %]Alternate address: Address 2 -[% CASE 'B_city' %]Alternate address: City -[% CASE 'B_state' %]Alternate address: State -[% CASE 'B_zipcode' %]Alternate address: ZIP/Postal code -[% CASE 'B_email' %]Alternate address: Email -[% CASE 'B_phone' %]Alternate address: Phone -[% CASE 'contactnote' %]Alternate address: Contact note -[% CASE 'dateofbirth' %]Date of birth -[% CASE 'contactname' %]Contact: Last name -[% CASE 'contactfirstname' %]Contact: First name -[% CASE 'contacttitle' %]Contact: Title -[% CASE 'relationship' %]Contact: Relationship -[% CASE 'sex' %]Gender -[% CASE 'autorenew_checkouts' %]Auto-renewal -[% CASE 'altcontactfirstname' %]Alternate contact: First name -[% CASE 'altcontactsurname' %]Alternate contact: Surname -[% CASE 'altcontactaddress1' %]Alternate contact: Address -[% CASE 'altcontactaddress2' %]Alternate contact: Address 2 -[% CASE 'altcontactaddress3' %]Alternate contact: City -[% CASE 'altcontactstate' %]Alternate contact: State -[% CASE 'altcontactzipcode' %]Alternate contact: ZIP/Postal code -[% CASE 'altcontactcountry' %]Alternate contact: Country -[% CASE 'altcontactphone' %]Alternate contact: Phone -[% CASE 'smsalertnumber' %]SMS alert number -[% CASE 'extended_attributes' %]Additional attributes and identifiers -[% CASE %][% field | html %] -[% END %] + [% SWITCH field %] + [% CASE 'branchcode' %] + Home library (branchcode) + [% CASE 'surname' %] + Surname + [% CASE 'firstname' %] + First name + [% CASE 'preferred_name' %] + Preferred name + [% CASE 'middle_name' %] + Middle name + [% CASE 'title' %] + Title + [% CASE 'othernames' %] + Other names + [% CASE 'initials' %] + Initials + [% CASE 'pronouns' %] + Pronouns + [% CASE 'streetnumber' %] + Street number + [% CASE 'streettype' %] + Street type + [% CASE 'address' %] + Address + [% CASE 'address2' %] + Address 2 + [% CASE 'city' %] + City + [% CASE 'state' %] + State + [% CASE 'zipcode' %] + ZIP/Postal code + [% CASE 'country' %] + Country + [% CASE 'email' %] + Email + [% CASE 'phone' %] + Primary phone + [% CASE 'mobile' %] + Other phone + [% CASE 'fax' %] + Fax + [% CASE 'emailpro' %] + Secondary email + [% CASE 'phonepro' %] + Secondary phone + [% CASE 'B_streetnumber' %] + Alternate address: Street number + [% CASE 'B_streettype' %] + Alternate address: Street type + [% CASE 'B_address' %] + Alternate address: Address + [% CASE 'B_address2' %] + Alternate address: Address 2 + [% CASE 'B_city' %] + Alternate address: City + [% CASE 'B_state' %] + Alternate address: State + [% CASE 'B_zipcode' %] + Alternate address: ZIP/Postal code + [% CASE 'B_email' %] + Alternate address: Email + [% CASE 'B_phone' %] + Alternate address: Phone + [% CASE 'contactnote' %] + Alternate address: Contact note + [% CASE 'dateofbirth' %] + Date of birth + [% CASE 'contactname' %] + Contact: Last name + [% CASE 'contactfirstname' %] + Contact: First name + [% CASE 'contacttitle' %] + Contact: Title + [% CASE 'relationship' %] + Contact: Relationship + [% CASE 'sex' %] + Gender + [% CASE 'autorenew_checkouts' %] + Auto-renewal + [% CASE 'altcontactfirstname' %] + Alternate contact: First name + [% CASE 'altcontactsurname' %] + Alternate contact: Surname + [% CASE 'altcontactaddress1' %] + Alternate contact: Address + [% CASE 'altcontactaddress2' %] + Alternate contact: Address 2 + [% CASE 'altcontactaddress3' %] + Alternate contact: City + [% CASE 'altcontactstate' %] + Alternate contact: State + [% CASE 'altcontactzipcode' %] + Alternate contact: ZIP/Postal code + [% CASE 'altcontactcountry' %] + Alternate contact: Country + [% CASE 'altcontactphone' %] + Alternate contact: Phone + [% CASE 'smsalertnumber' %] + SMS alert number + [% CASE 'extended_attributes' %] + Additional attributes and identifiers + [% CASE %] + [% field | html %] + [% END %] [% END %] [% BLOCK display_extended_attributes %] [% IF attrs and attrs.size > 1 %] -
            - [% FOREACH attr IN attrs %] -
          • [% PROCESS display_attribute attr=attr type=type %]
          • - [% END %] -
          +
            + [% FOREACH attr IN attrs %] +
          • [% PROCESS display_attribute attr=attr type=type %]
          • + [% END %] +
          [% ELSIF attrs %] [% PROCESS display_attribute attr=attrs.0 type=type %] [% END %] @@ -110,108 +163,109 @@ [% END #/ WRAPPER sub-header.inc %] [% WRAPPER 'main-container.inc' %] +

          Update patron records

          + [% IF PendingModifications %] +
          + [% INCLUDE 'csrf-token.inc' %] + [% WRAPPER accordion panelgroup_id="pending_updates" %] + [% FOREACH pm IN PendingModifications %] + [% SET borrowernumber = pm.borrowernumber %] + [% WRAPPER accordion_item %] + [% WRAPPER accordion_heading panel_id="panel-${pm.borrowernumber}" %] + [% borrowers.$borrowernumber.surname | html %][% IF ( borrowers.$borrowernumber.firstname ) %], [% borrowers.$borrowernumber.firstname | html %][% END %] + - [% Categories.GetName( borrowers.$borrowernumber.categorycode ) | html %] ([% Branches.GetName( borrowers.$borrowernumber.branchcode ) | html %]) ([% borrowers.$borrowernumber.cardnumber | html %]) - Requested + on [% pm.timestamp | $KohaDates with_hours = 1 %] + [% END %] + [% WRAPPER accordion_panel panel_id="panel-${pm.borrowernumber}" %] +
          + -

          Update patron records

          - [% IF PendingModifications %] - - [% INCLUDE 'csrf-token.inc' %] - [% WRAPPER accordion panelgroup_id="pending_updates" %] - [% FOREACH pm IN PendingModifications %] - [% SET borrowernumber = pm.borrowernumber %] - [% WRAPPER accordion_item %] - [% WRAPPER accordion_heading panel_id="panel-${pm.borrowernumber}" %] - [% borrowers.$borrowernumber.surname | html %][% IF ( borrowers.$borrowernumber.firstname ) %], [% borrowers.$borrowernumber.firstname | html %][% END %] - [% Categories.GetName( borrowers.$borrowernumber.categorycode ) | html %] ([% Branches.GetName( borrowers.$borrowernumber.branchcode ) | html %]) ([% borrowers.$borrowernumber.cardnumber | html %]) - Requested on [% pm.timestamp | $KohaDates with_hours = 1 %] - [% END %] - [% WRAPPER accordion_panel panel_id="panel-${pm.borrowernumber}" %] + -
          + +  |  Patron details +
          - + [% IF borrowers.$borrowernumber.gonenoaddress > 0 %] +
          +

          Patron's address in doubt

          +

          The Gone no address flag is set for this patron. If this modification request resolves the issue, please unset the flag.

          + + +
          + [% END %] + [% IF !pm.extended_attributes and pm.size > 3 or pm.extended_attributes and pm.size > 4 %] + [%# timestamp+verification_token+borrowernumber=3 %] +
          + + + + + + - - - - -  |  Patron details - - - [% IF borrowers.$borrowernumber.gonenoaddress > 0 %] -
          -

          Patron's address in doubt

          -

          The Gone no address flag is set for this patron. If this modification request resolves the issue, please unset the flag.

          - - -
          - [% END %] - - [% IF !pm.extended_attributes and pm.size > 3 or pm.extended_attributes and pm.size > 4 %] - [%# timestamp+verification_token+borrowernumber=3 %] -
          -
          FieldOld valueNew value
          - - - - - - - - [% FOREACH key IN pm.keys %] - [% IF ( key != "timestamp" and key != "extended_attributes" ) %] - [% IF ( ( pm.$key OR borrowers.$borrowernumber.$key ) && ( pm.$key != borrowers.$borrowernumber.$key ) ) %] - - - [% IF ( key == "dateofbirth" ) %] - - - [% ELSIF key == 'branchcode' %] - - - [% ELSE %] - - - [% END %] - - [% END %] - [% END %] - [% END %] -
          FieldOld valueNew value
          [% PROCESS display_names field = key %][% borrowers.$borrowernumber.$key | $KohaDates %][% pm.$key | $KohaDates %][% Branches.GetName( borrowers.$borrowernumber.$key ) | html %][% Branches.GetName( pm.$key ) | html %][% borrowers.$borrowernumber.$key | html %][% pm.$key | html %]
          -
          - [% END # /!pm.extended_attributes %] - [% IF borrowers.$borrowernumber.modified_attributes %] -
          -

          [% PROCESS display_names field='extended_attributes' %]

          - - - - - - - [% FOREACH attribute_group IN borrowers.$borrowernumber.modified_attributes %] + [% FOREACH key IN pm.keys %] + [% IF ( key != "timestamp" and key != "extended_attributes" ) %] + [% IF ( ( pm.$key OR borrowers.$borrowernumber.$key ) && ( pm.$key != borrowers.$borrowernumber.$key ) ) %] - - - + + [% IF ( key == "dateofbirth" ) %] + + + [% ELSIF key == 'branchcode' %] + + + [% ELSE %] + + + [% END %] [% END %] -
          FieldOld valueNew value
          [% attribute_group.type.description | html %][% PROCESS display_extended_attributes attrs=attribute_group.before type=attribute_group.type %][% PROCESS display_extended_attributes attrs=attribute_group.after type=attribute_group.type %][% PROCESS display_names field = key %][% borrowers.$borrowernumber.$key | $KohaDates %][% pm.$key | $KohaDates %][% Branches.GetName( borrowers.$borrowernumber.$key ) | html %][% Branches.GetName( pm.$key ) | html %][% borrowers.$borrowernumber.$key | html %][% pm.$key | html %]
          -
          - [% END # / borrowers.$borrowernumber.modified_attributes %] - [% END %] - [% END %] - [% END # /FOREACH pm %] - [% END # /collapse %] -
          - - -
          - - [% ELSE %] -
          -

          There are no pending patron modifications.

          -
          - [% END %] - + [% END %] + [% END %] + +
          + + [% END # /!pm.extended_attributes %] + [% IF borrowers.$borrowernumber.modified_attributes %] +
          +

          [% PROCESS display_names field='extended_attributes' %]

          + + + + + + + [% FOREACH attribute_group IN borrowers.$borrowernumber.modified_attributes %] + + + + + + [% END %] +
          FieldOld valueNew value
          [% attribute_group.type.description | html %][% PROCESS display_extended_attributes attrs=attribute_group.before type=attribute_group.type %][% PROCESS display_extended_attributes attrs=attribute_group.after type=attribute_group.type %]
          +
          + + [% END # / borrowers.$borrowernumber.modified_attributes %] + [% END %] + [% END %] + [% END # /FOREACH pm %] + [% END # /collapse %] +
          + + +
          + + [% ELSE %] +
          +

          There are no pending patron modifications.

          +
          + [% END %] [% END %] [% MACRO jsinclude BLOCK %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/members/merge-patrons.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/members/merge-patrons.tt index b6908714a1..c912466d4e 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/members/merge-patrons.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/members/merge-patrons.tt @@ -7,11 +7,12 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Merge patron records") | html %] › - [% t("Patrons") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Merge patron records") | html %] + › [% t("Patrons") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] [% FILTER collapse %] +[% FILTER collapse %] + [% t("Summary for") | html %] + [% INCLUDE 'patron-title.inc' no_html = 1 %] + › [% t("Patrons") | html %] › [% t("Koha") | html %] + [% END %] +[% INCLUDE 'doc-head-close.inc' %] + -
          -

          Account summary: [% INCLUDE 'patron-title.inc' no_html = 1 %] ›

          -
          -
            - [% PROCESS 'display-address-style' %] -
          • [% IF ( patron.phone ) %][% patron.phone | html %][% ELSE %](no phone number on file)[% END %]
          • -
          • [% IF ( patron.email ) %][% patron.email | html %][% ELSE %](no primary email on file)[% END %]
          • - [% IF ( patron.emailpro ) %] -
          • [% patron.emailpro | html %]
          • - [% END %] -
          • Registration date: [% patron.dateenrolled | $KohaDates %]
          • -
          • Expiration date: [% patron.dateexpiry | $KohaDates %]
          • -
          • Library: [% Branches.GetName( patron.branchcode ) | html %]
          • -
          • Category: [% patron.category.description | html %]
          • -
          -
          +
          +

          Account summary: [% INCLUDE 'patron-title.inc' no_html = 1 %] ›

          +
          +
            + [% PROCESS 'display-address-style' %] +
          • [% IF ( patron.phone ) %][% patron.phone | html %][% ELSE %](no phone number on file)[% END %]
          • +
          • [% IF ( patron.email ) %][% patron.email | html %][% ELSE %](no primary email on file)[% END %]
          • + [% IF ( patron.emailpro ) %] +
          • [% patron.emailpro | html %]
          • + [% END %] +
          • Registration date: [% patron.dateenrolled | $KohaDates %]
          • +
          • Expiration date: [% patron.dateexpiry | $KohaDates %]
          • +
          • Library: [% Branches.GetName( patron.branchcode ) | html %]
          • +
          • Category: [% patron.category.description | html %]
          • +
          +
          - [% IF ( issues ) %] -

          Items checked out

          - - + [% IF ( issues ) %] +

          Items checked out

          + + + + + + + + + + + + + + + + + [% FOREACH issue IN issues %] - - - - - - - - - - + + + + + + + + + + - - - [% FOREACH issue IN issues %] - - - - - - - - - - - - - [% END %] - - - - - - - - - - - - - - - - - [% END %] + [% END %] + + + + + + + + + + Totals: + [% totaldue | $Price %] + [% totalprice | $Price %] + + + + + [% END %] [% IF ( reserves ) %]

          Pending holds

          @@ -128,12 +124,12 @@

          Account fines and payments

          - - - - - - + + + + + + @@ -153,15 +149,9 @@ [% account.item.biblio.title | html %] [% END %] - - - + + + [% END %] @@ -169,18 +159,15 @@ - - - + + + [% END %] -
          +
          + [% MACRO jsinclude BLOCK %] [% INCLUDE 'slip-print.inc' #printThenClose %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/members/moremember.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/members/moremember.tt index 0f586f296c..f0d61473a7 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/members/moremember.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/members/moremember.tt @@ -13,716 +13,736 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% UNLESS blocking_error %] - [% t("Patron details for") | html %] [% INCLUDE 'patron-title.inc' no_html = 1 %] - [% END %] › - [% t("Patrons") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% UNLESS blocking_error %] + [% t("Patron details for") | html %] + [% INCLUDE 'patron-title.inc' no_html = 1 %] + [% END %] + › [% t("Patrons") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] - [% WRAPPER 'header.inc' %] - [% INCLUDE 'patron-search-header.inc' %] - [% END %] +[% WRAPPER 'header.inc' %] + [% INCLUDE 'patron-search-header.inc' %] +[% END %] - [% WRAPPER 'sub-header.inc' %] - [% WRAPPER breadcrumbs %] +[% WRAPPER 'sub-header.inc' %] + [% WRAPPER breadcrumbs %] + [% WRAPPER breadcrumb_item %] + Patrons + [% END %] + [% UNLESS blocking_error %] [% WRAPPER breadcrumb_item %] - Patrons + [% INCLUDE 'patron-title.inc' %] [% END %] - [% UNLESS blocking_error %] - [% WRAPPER breadcrumb_item %] - - [% INCLUDE 'patron-title.inc' %] - - [% END %] - [% WRAPPER breadcrumb_item bc_active= 1 %] - Details - [% END %] + [% WRAPPER breadcrumb_item bc_active= 1 %] + Details [% END %] - [% END #/ WRAPPER breadcrumbs %] - [% END #/ WRAPPER sub-header.inc %] + [% END %] + [% END #/ WRAPPER breadcrumbs %] +[% END #/ WRAPPER sub-header.inc %] - [% WRAPPER 'main-container.inc' aside='circ-menu' %] +[% WRAPPER 'main-container.inc' aside='circ-menu' %] - [% INCLUDE 'members-toolbar.inc' %] + [% INCLUDE 'members-toolbar.inc' %] - [% IF is_anonymous %] -
          This is the anonymous patron.
          - [% END %] - - [% IF ( error ) %] -
          - [% IF ( error == 'CANT_DELETE_STAFF' ) %] -

          Unable to delete staff user

          -

          Insufficient privileges.

          - [% END %] - [% IF ( error == 'CANT_DELETE_YOURSELF' ) %] -

          Not allowed to delete own account

          -

          Deleting your own account would lock you out of Koha.

          - [% END %] - [% IF ( error == 'CANT_DELETE_OTHERLIBRARY' ) %] -

          Unable to delete patrons from other libraries with current settings

          -

          Insufficient privileges.

          - [% END %] - [% IF ( error == 'CANT_DELETE_ANONYMOUS_PATRON' ) %] -

          Unable to delete patron that is set as AnonymousPatron

          -

          This patron cannot be deleted while set as AnonymousPatron in the system preferences.

          - [% END %] - [% IF ( error == 'CANT_DELETE' ) %] -

          Unable to delete patron

          -

          Insufficient privileges.

          - [% END %] -
          - [% END %] - -
          - - [% IF ( was_renewed ) %] -
          - Patron's account has been renewed until [% patron.dateexpiry | $KohaDates %] -
          - [% END %] - - [% messages = INCLUDE 'patron_messages.inc' moremember = 1 | trim %] - [% IF messages %] -
          -
          - [% messages | $raw %] -
          -
          - [% END %] - -
          -

          [% INCLUDE 'patron-title.inc' no_html = 1 %]

          - - [% IF patron.pronouns %] -
          ([% patron.pronouns | html %])
          - [% END %] -
          - -
          - -
          - -
          -

          Contact information

          - [% IF CAN_user_borrowers_edit_borrowers %] - [% IF ( guarantor.borrowernumber ) %] - Edit - [% ELSE %] - Edit - [% END %] - [% END %] -
          - - [% IF ( patron.othernames ) %]
          “[% patron.othernames | html %]”
          [% END %] - -
          -
            - [% PROCESS 'display-address-style' %] -
          -
          - -
          -
            - [% IF ( patron.preferred_name && patron.firstname ) %] -
          1. - First name: - [% patron.firstname | html %] -
          2. - [% END %] - [% IF ( patron.phone ) %] -
          3. - Primary phone: - [% patron.phone | html %] -
          4. - [% END %] - [% IF ( patron.phonepro ) %] -
          5. - Secondary phone: - [% patron.phonepro | html %] -
          6. - [% END %] - [% IF ( patron.mobile ) %] -
          7. - Other phone: - [% patron.mobile | html %] -
          8. - [% END %] - [% IF ( patron.fax ) %] -
          9. - Fax: - [% patron.fax | html %] -
          10. - [% END %] - [% IF ( patron.email ) %] - - [% END %] - [% IF ( patron.emailpro ) %] - - [% END %] - [% UNLESS ( I ) %] - [% IF ( patron.initials ) %] -
          11. - Initials: - [% patron.initials | html %] -
          12. - [% END %] - [% IF ( patron.dateofbirth ) %] -
          13. - Date of birth: - [% INCLUDE 'patron-age.inc' %] -
          14. - [% END %] - [% IF ( patron.sex ) %] -
          15. - Gender: - [% IF ( patron.sex == 'F' ) %]Female[% ELSIF ( patron.sex == 'M' ) %]Male[% ELSIF (patron.sex == 'O' ) %][% tp('gender', 'Other') | html %][% ELSE %][% patron.sex | html %][% END %] -
          16. - [% END %] - [% END %] - [% IF Koha.Preference("borrowerRelationship") %] -
          17. - Show checkouts to guarantor: - [% IF patron.privacy_guarantor_checkouts %] - Yes - [% ELSE %] - No - [% END %] -
          18. - -
          19. - Show charges to guarantor: - [% IF patron.privacy_guarantor_fines %] - Yes - [% ELSE %] - No - [% END %] -
          20. - [% END %] - [% IF guarantees %] -
          21. - Guarantees: -
              - [% IF guarantees_fines and guarantees_fines > 0 %] -
            • - Charges: - Patron's guarantees collectively owe [% guarantees_fines | $Price %]. - See all charges. -
            • - [% END %] - [% FOREACH guarantee IN guarantees %] - [% IF logged_in_user.can_see_patron_infos( guarantee ) %] -
            • [% guarantee.firstname | html %] [% guarantee.surname | html %]
            • - [% ELSE %] -
            • [% guarantee.preferred_name | html %] [% guarantee.surname | html %]
            • - [% END %] - [% END %] -
            -
          22. - [% ELSIF guarantor_relationships.count > 0 OR ( patron.contactfirstname OR patron.contactname ) %] -
          23. - [% IF guarantor_relationships.count > 1 OR guarantor_relationships.count == 0 AND ( patron.contactfirstname OR patron.contactname ) %] - Guarantors: - [% ELSE %] - Guarantor: - [% END %] - -
          24. - [% END %] - - [% IF ( patron.primary_contact_method ) %] -
          25. - Main contact method: - [% SWITCH patron.primary_contact_method %] - [% CASE 'phone' %] - Primary phone - [% CASE 'phonepro' %] - Secondary phone - [% CASE 'mobile' %] - Other phone - [% CASE 'email' %] - Primary email - [% CASE 'emailpro' %] - Secondary email - [% CASE 'fax' %] - Fax - [% END %] -
          26. - [% END %] -
          -
          [%# /div.rows %] -
          [%# /div#patron-information %] - - [% IF Koha.Preference('HouseboundModule') %] -
          - [% IF ( housebound_role.housebound_chooser == 1 OR housebound_role.housebound_deliverer == 1 ) %] -
          -

          Housebound roles

          - [% IF CAN_user_borrowers_edit_borrowers %] - Edit - [% END %] -
          -
          -
            -
          1. - Chooser: - [% IF ( housebound_role.housebound_chooser == 1 ) %] - Yes - [% ELSE %] - No - [% END %] -
          2. -
          3. - Deliverer: - [% IF ( housebound_role.housebound_deliverer == 1 ) %] - Yes - [% ELSE %] - No - [% END %] -
          4. -
          -
          - [% ELSE %] -
          -

          Housebound roles

          - [% IF CAN_user_borrowers_edit_borrowers %] - Add - [% END %] -
          - [% END %] -
          [%#/ div#houseboundroles %] - [% END %] - - [% IF Koha.Preference('ExtendedPatronAttributes') %] - [% UNLESS ( no_patron_attribute_types ) %] -
          - [% IF ( attributes_loop ) %] -
          -

          Additional attributes and identifiers

          - [% IF CAN_user_borrowers_edit_borrowers %] - Edit - [% END %] -
          - [% FOREACH attribute IN attributes_loop %] - [% IF attribute.class %] - [% SET div_id = 'aai_' _ attribute.class %] - [% ELSE %] - [% SET div_id = 'aai' %] - [% END %] -
          -

          [% attribute.lib | html %]

          -
            - [% FOREACH item IN attribute.items %] -
          1. - [% item.type.description | html %]: - [% IF item.type.is_date %] - [% item.description | $KohaDates %] - [% ELSE %] - [% item.description | html_line_break %] - [% END %] -
          2. - [% END %] -
          -
          - [% END %] -
          -
          - [% ELSE %] -
          -

          Additional attributes and identifiers

          - [% IF CAN_user_borrowers_edit_borrowers %] - Add - [% END %] -
          - [% END %] -
          [%# /div#patron-extended-attributes %] - [% END %] - [% END %] - - [% IF ( EnhancedMessagingPreferences ) %] -
          -
          -

          Patron messaging preferences

          - [% IF CAN_user_borrowers_edit_borrowers %] - Edit - [% END %] -
          - [% INCLUDE 'messaging-preference-form.inc' %] - [% IF Koha.Preference('SMSSendDriver') %] -
          -
            - [% IF patron.smsalertnumber %] -
          1. - SMS number: - [% patron.smsalertnumber | html %] -
          2. - [% END %] - [% IF Koha.Preference( 'SMSSendDriver') == 'Email' && patron.sms_provider.name %] -
          3. - SMS provider: - [% patron.sms_provider.name | html %] -
          4. - [% END %] -
          -
          - [% END %] -
          [%# /div#patron-messaging-prefs %] - [% END %] - -
          - -
          -
          -
          -

          Library use

          - [% IF CAN_user_borrowers_edit_borrowers %] - Edit - [% END %] -
          -
          -
            -
          1. - Card number: - [% patron.cardnumber | html %] -
          2. -
          3. - Borrowernumber: - [% patron.borrowernumber | html %] -
          4. -
          5. - Category: - [% patron.category.description | html %] ([% patron.categorycode | html %]) -
          6. -
          7. - Registration date: - [% patron.dateenrolled | $KohaDates %] -
          8. - - [% IF ( patron.date_renewed ) %] -
          9. - Renewal date: - [% patron.date_renewed | $KohaDates %] -
          10. - [% END %] - -
          11. - Expiration date: - [% IF ( was_renewed ) %] - [% patron.dateexpiry | $KohaDates %] - [% ELSIF ( patron.is_expired ) %] - - [% patron.dateexpiry | $KohaDates %] - Expired - Renew or Edit details - - [% ELSIF ( patron.is_going_to_expire ) %] - [% patron.dateexpiry | $KohaDates %] - Patron expires soon - Renew or Edit details - [% ELSE %] - [% patron.dateexpiry | $KohaDates %] - [% END %] -
          12. -
          13. - Library: - [% Branches.GetName( patron.branchcode ) | html %] -
          14. - - [% IF Koha.Preference( 'OPACPrivacy') %] -
          15. - Privacy pref: - [% IF ( patron.privacy == 0 ) %]Forever[% END %] - [% IF ( patron.privacy == 1 ) %]Default[% END %] - [% IF ( patron.privacy == 2 ) %]Never[% END %] -
          16. - [% END %] - - [% IF ( patron.sort1 ) %] -
          17. - Sort field 1: - [% AuthorisedValues.GetByCode('Bsort1', patron.sort1) | html %] -
          18. - [% END %] - [% IF ( patron.sort2 ) %] -
          19. - Sort field 2: - [% AuthorisedValues.GetByCode('Bsort2', patron.sort2) | html %] -
          20. - [% END %] - [% UNLESS ( patron.autorenew_checkouts ) %] -
          21. - Auto-renewal: - Patron has opted out -
          22. - [% END %] -
          23. - Username: - [% patron.userid | html %] -
          24. -
          25. - Password: - [% IF ( patron.password ) %] - ******* - [% ELSE %] - Undefined - [% END %] -
          26. - [% IF CAN_user_superlibrarian %] -
          27. - Password expires: - [% IF ( patron.password_expiration_date ) %] - [% patron.password_expiration_date | $KohaDates %] - [% ELSE %] - Never - [% END %] -
          28. - [% END %] -
          29. - Protected: - [% IF ( patron.protected == 1 ) %] - Yes - [% ELSE %] - No - [% END %] -
          30. - - [% IF ( patron.borrowernotes ) %] -
          31. - Circulation note:
            - [% patron.borrowernotes | $raw | html_line_break %] -
          32. - [% END %] - - [% IF ( patron.opacnote ) %] -
          33. - OPAC note:
            - [% patron.opacnote | html | html_line_break %] -
          34. - [% END %] - - [% IF ( Koha.Preference('CheckPrevCheckout') == 'softyes' || Koha.Preference('CheckPrevCheckout') == 'softno' ) %] -
          35. - Check previous checkouts: - [% IF ( patron.checkprevcheckout == 'yes' ) %] - Yes - [% ELSIF ( patron.checkprevcheckout == 'no' ) %] - No - [% ELSE %] - Inherited - [% END %] -
          36. - [% END %] - - [% IF Koha.Preference('TranslateNotices') %] -
          37. - Preferred language for notices: - [% translated_language | html %] -
          38. - [% END %] - -
          39. - [% IF patron.gonenoaddress %] - Address in doubt: - Yes - [% ELSE %] - Address in doubt: - No - [% END %] -
          40. - -
          41. - [% IF patron.lost %] - Card lost: - Yes - [% ELSE %] - Card lost: - No - [% END %] -
          42. -
          -
          [%# /div.rows %] -
          [%# /div#patron-library-details %] - -
          - [% IF ( patron.B_phone || patron.B_email || patron.contactnote || patron.B_address || patron.B_address2 || patron.B_city || patron.B_zipcode || patron.B_country ) %] -
          -

          Alternate address

          - [% IF CAN_user_borrowers_edit_borrowers %] - Edit - [% END %] -
          -
          -
            - [% PROCESS 'display-alt-address-style' %] -
          -
          -
          -
            - [% IF ( patron.B_phone ) %] -
          1. - Phone: - [% patron.B_phone |html %] -
          2. - [% END %] - - [% IF ( patron.B_email ) %] - - [% END %] - - [% IF ( patron.contactnote ) %] -
          3. - Contact note: - [% patron.contactnote |html %] -
          4. - [% END %] -
          -
          - [% ELSE %] -
          -

          Alternate address

          - [% IF CAN_user_borrowers_edit_borrowers %] - Add - [% END %] -
          - [% END %] -
          [%# /div#patron-alternate-address %] - -
          - [% IF ( patron.altcontactsurname || patron.altcontactfirstname || patron.altcontactaddress1 || patron.altcontactaddress2 || patron.altcontactaddress3 || patron.altcontactstate || patron.altcontactzipcode || patron.altcontactcountry || patron.altcontactphone ) %] -
          -

          Alternative contact

          - [% IF CAN_user_borrowers_edit_borrowers %] - Edit - [% END %] -
          -
          -
            - [% IF ( patron.altcontactsurname ) %] -
          1. - Surname: - [% patron.altcontactsurname | html %] -
          2. - [% END %] - [% IF ( patron.altcontactfirstname ) %] -
          3. - First name: - [% patron.altcontactfirstname | html %] -
          4. - [% END %] - [% IF ( patron.altcontactaddress1 ) %] -
          5. - Address: - [% patron.altcontactaddress1 | html %] -
          6. - [% END %] - [% IF ( patron.altcontactaddress2 ) %] -
          7. - Address 2: - [% patron.altcontactaddress2 | html %] -
          8. - [% END %] - [% IF ( patron.altcontactaddress3 ) %] -
          9. - City: - [% patron.altcontactaddress3 | html %] -
          10. - [% END %] - - [% IF ( patron.altcontactstate ) %] -
          11. - State: - [% patron.altcontactstate | html %] -
          12. - [% END %] - [% IF ( patron.altcontactzipcode ) %] -
          13. - ZIP/Postal code: - [% patron.altcontactzipcode | html %] -
          14. - [% END %] - [% IF ( patron.altcontactcountry ) %] -
          15. - Country: - [% patron.altcontactcountry | html %] -
          16. - [% END %] - [% IF ( patron.altcontactphone ) %] -
          17. - Phone: - [% patron.altcontactphone | html %] -
          18. - [% END %] -
          -
          [%# /div.rows %] - [% ELSE %] -
          -

          Alternative contact

          - [% IF CAN_user_borrowers_edit_borrowers %] - Add - [% END %] -
          - [% END %] -
          [%# /div#patron-alternative-contact %] - - [% IF Koha.Preference('EnableBorrowerFiles') %] -
          -
          -

          Files

          - Manage - - [% IF ( files ) %] -
          -
            - [% FOREACH f IN files %] -
          1. - [% f.file_name | html %] - [% IF ( f.file_description ) %] - - [% f.file_description | html %] - [% END %] -
          2. - [% END # /FOREACH f %] -
          -
          - [% END # /IF files %] - -
          -
          - [% END # /IF EnableBorrowerFiles %] - -
          -
          - - [% INCLUDE 'patron-detail-tabs.inc' patronpage = "borrower" %] + [% IF is_anonymous %] +
          This is the anonymous patron.
          [% END %] - [% IF Koha.Preference('ClaimReturnedLostValue') || Koha.Preference('BundleLostValue') %] - [% INCLUDE 'modals/resolve_return_claim.inc' %] + + [% IF ( error ) %] +
          + [% IF ( error == 'CANT_DELETE_STAFF' ) %] +

          Unable to delete staff user

          +

          Insufficient privileges.

          + [% END %] + [% IF ( error == 'CANT_DELETE_YOURSELF' ) %] +

          Not allowed to delete own account

          +

          Deleting your own account would lock you out of Koha.

          + [% END %] + [% IF ( error == 'CANT_DELETE_OTHERLIBRARY' ) %] +

          Unable to delete patrons from other libraries with current settings

          +

          Insufficient privileges.

          + [% END %] + [% IF ( error == 'CANT_DELETE_ANONYMOUS_PATRON' ) %] +

          Unable to delete patron that is set as AnonymousPatron

          +

          This patron cannot be deleted while set as AnonymousPatron in the system preferences.

          + [% END %] + [% IF ( error == 'CANT_DELETE' ) %] +

          Unable to delete patron

          +

          Insufficient privileges.

          + [% END %] +
          + [% END %] + +
          + [% IF ( was_renewed ) %] +
          Patron's account has been renewed until [% patron.dateexpiry | $KohaDates %]
          [% END %] - [% INCLUDE modals/cancel_booking.inc %] + [% messages = INCLUDE 'patron_messages.inc' moremember = 1 | trim %] + [% IF messages %] +
          +
          [% messages | $raw %]
          +
          + [% END %] + +
          +

          [% INCLUDE 'patron-title.inc' no_html = 1 %]

          + + [% IF patron.pronouns %] +
          ([% patron.pronouns | html %])
          + [% END %] +
          + +
          +
          +
          +

          Contact information

          + [% IF CAN_user_borrowers_edit_borrowers %] + [% IF ( guarantor.borrowernumber ) %] + Edit + [% ELSE %] + Edit + [% END %] + [% END %] +
          + + [% IF ( patron.othernames ) %]
          “[% patron.othernames | html %]”
          [% END %] + +
          +
            + [% PROCESS 'display-address-style' %] +
          +
          + +
          +
            + [% IF ( patron.preferred_name && patron.firstname ) %] +
          1. + First name: + [% patron.firstname | html %] +
          2. + [% END %] + [% IF ( patron.phone ) %] +
          3. + Primary phone: + [% patron.phone | html %] +
          4. + [% END %] + [% IF ( patron.phonepro ) %] +
          5. + Secondary phone: + [% patron.phonepro | html %] +
          6. + [% END %] + [% IF ( patron.mobile ) %] +
          7. + Other phone: + [% patron.mobile | html %] +
          8. + [% END %] + [% IF ( patron.fax ) %] +
          9. + Fax: + [% patron.fax | html %] +
          10. + [% END %] + [% IF ( patron.email ) %] + + [% END %] + [% IF ( patron.emailpro ) %] + + [% END %] + [% UNLESS ( I ) %] + [% IF ( patron.initials ) %] +
          11. + Initials: + [% patron.initials | html %] +
          12. + [% END %] + [% IF ( patron.dateofbirth ) %] +
          13. + Date of birth: + [% INCLUDE 'patron-age.inc' %] +
          14. + [% END %] + [% IF ( patron.sex ) %] +
          15. + Gender: + [% IF ( patron.sex == 'F' ) %] + Female + [% ELSIF ( patron.sex == 'M' ) %] + Male + [% ELSIF (patron.sex == 'O' ) %] + [% tp('gender', 'Other') | html %] + [% ELSE %] + [% patron.sex | html %] + [% END %] +
          16. + [% END %] + [% END %] + [% IF Koha.Preference("borrowerRelationship") %] +
          17. + Show checkouts to guarantor: + [% IF patron.privacy_guarantor_checkouts %] + Yes + [% ELSE %] + No + [% END %] +
          18. + +
          19. + Show charges to guarantor: + [% IF patron.privacy_guarantor_fines %] + Yes + [% ELSE %] + No + [% END %] +
          20. + [% END %] + [% IF guarantees %] +
          21. + Guarantees: +
              + [% IF guarantees_fines and guarantees_fines > 0 %] +
            • + Charges: + Patron's guarantees collectively owe [% guarantees_fines | $Price %]. + See all charges. +
            • + [% END %] + [% FOREACH guarantee IN guarantees %] + [% IF logged_in_user.can_see_patron_infos( guarantee ) %] +
            • [% guarantee.firstname | html %] [% guarantee.surname | html %]
            • + [% ELSE %] +
            • [% guarantee.preferred_name | html %] [% guarantee.surname | html %]
            • + [% END %] + [% END %] +
            +
          22. + [% ELSIF guarantor_relationships.count > 0 OR ( patron.contactfirstname OR patron.contactname ) %] +
          23. + [% IF guarantor_relationships.count > 1 OR guarantor_relationships.count == 0 AND ( patron.contactfirstname OR patron.contactname ) %] + Guarantors: + [% ELSE %] + Guarantor: + [% END %] + +
          24. + [% END %] + + [% IF ( patron.primary_contact_method ) %] +
          25. + Main contact method: + [% SWITCH patron.primary_contact_method %] + [% CASE 'phone' %] + Primary phone + [% CASE 'phonepro' %] + Secondary phone + [% CASE 'mobile' %] + Other phone + [% CASE 'email' %] + Primary email + [% CASE 'emailpro' %] + Secondary email + [% CASE 'fax' %] + Fax + [% END %] +
          26. + [% END %] +
          +
          + [%# /div.rows %] +
          + [%# /div#patron-information %] + + [% IF Koha.Preference('HouseboundModule') %] +
          + [% IF ( housebound_role.housebound_chooser == 1 OR housebound_role.housebound_deliverer == 1 ) %] +
          +

          Housebound roles

          + [% IF CAN_user_borrowers_edit_borrowers %] + Edit + [% END %] +
          +
          +
            +
          1. + Chooser: + [% IF ( housebound_role.housebound_chooser == 1 ) %] + Yes + [% ELSE %] + No + [% END %] +
          2. +
          3. + Deliverer: + [% IF ( housebound_role.housebound_deliverer == 1 ) %] + Yes + [% ELSE %] + No + [% END %] +
          4. +
          +
          + [% ELSE %] +
          +

          Housebound roles

          + [% IF CAN_user_borrowers_edit_borrowers %] + Add + [% END %] +
          + [% END %] +
          + [%#/ div#houseboundroles %] + [% END %] + + [% IF Koha.Preference('ExtendedPatronAttributes') %] + [% UNLESS ( no_patron_attribute_types ) %] +
          + [% IF ( attributes_loop ) %] +
          +

          Additional attributes and identifiers

          + [% IF CAN_user_borrowers_edit_borrowers %] + Edit + [% END %] +
          + [% FOREACH attribute IN attributes_loop %] + [% IF attribute.class %] + [% SET div_id = 'aai_' _ attribute.class %] + [% ELSE %] + [% SET div_id = 'aai' %] + [% END %] +
          +

          [% attribute.lib | html %]

          +
            + [% FOREACH item IN attribute.items %] +
          1. + [% item.type.description | html %]: + [% IF item.type.is_date %] + [% item.description | $KohaDates %] + [% ELSE %] + [% item.description | html_line_break %] + [% END %] +
          2. + [% END %] +
          +
          + [% END %] +
          + [% ELSE %] +
          +

          Additional attributes and identifiers

          + [% IF CAN_user_borrowers_edit_borrowers %] + Add + [% END %] +
          + [% END %] +
          + [%# /div#patron-extended-attributes %] + [% END %] + [% END %] + + [% IF ( EnhancedMessagingPreferences ) %] +
          +
          +

          Patron messaging preferences

          + [% IF CAN_user_borrowers_edit_borrowers %] + Edit + [% END %] +
          + [% INCLUDE 'messaging-preference-form.inc' %] + [% IF Koha.Preference('SMSSendDriver') %] +
          +
            + [% IF patron.smsalertnumber %] +
          1. + SMS number: + [% patron.smsalertnumber | html %] +
          2. + [% END %] + [% IF Koha.Preference( 'SMSSendDriver') == 'Email' && patron.sms_provider.name %] +
          3. + SMS provider: + [% patron.sms_provider.name | html %] +
          4. + [% END %] +
          +
          + [% END %] +
          + [%# /div#patron-messaging-prefs %] + [% END %] +
          + + +
          +
          +
          +

          Library use

          + [% IF CAN_user_borrowers_edit_borrowers %] + Edit + [% END %] +
          +
          +
            +
          1. + Card number: + [% patron.cardnumber | html %] +
          2. +
          3. + Borrowernumber: + [% patron.borrowernumber | html %] +
          4. +
          5. + Category: + [% patron.category.description | html %] ([% patron.categorycode | html %]) +
          6. +
          7. + Registration date: + [% patron.dateenrolled | $KohaDates %] +
          8. + + [% IF ( patron.date_renewed ) %] +
          9. + Renewal date: + [% patron.date_renewed | $KohaDates %] +
          10. + [% END %] + +
          11. + Expiration date: + [% IF ( was_renewed ) %] + [% patron.dateexpiry | $KohaDates %] + [% ELSIF ( patron.is_expired ) %] + + [% patron.dateexpiry | $KohaDates %] + Expired + Renew or + Edit details + + [% ELSIF ( patron.is_going_to_expire ) %] + [% patron.dateexpiry | $KohaDates %] + Patron expires soon + Renew or + Edit details + [% ELSE %] + [% patron.dateexpiry | $KohaDates %] + [% END %] +
          12. +
          13. + Library: + [% Branches.GetName( patron.branchcode ) | html %] +
          14. + + [% IF Koha.Preference( 'OPACPrivacy') %] +
          15. + Privacy pref: + [% IF ( patron.privacy == 0 ) %]Forever[% END %] + [% IF ( patron.privacy == 1 ) %]Default[% END %] + [% IF ( patron.privacy == 2 ) %]Never[% END %] +
          16. + [% END %] + + [% IF ( patron.sort1 ) %] +
          17. + Sort field 1: + [% AuthorisedValues.GetByCode('Bsort1', patron.sort1) | html %] +
          18. + [% END %] + [% IF ( patron.sort2 ) %] +
          19. + Sort field 2: + [% AuthorisedValues.GetByCode('Bsort2', patron.sort2) | html %] +
          20. + [% END %] + [% UNLESS ( patron.autorenew_checkouts ) %] +
          21. + Auto-renewal: + Patron has opted out +
          22. + [% END %] +
          23. + Username: + [% patron.userid | html %] +
          24. +
          25. + Password: + [% IF ( patron.password ) %] + ******* + [% ELSE %] + Undefined + [% END %] +
          26. + [% IF CAN_user_superlibrarian %] +
          27. + Password expires: + [% IF ( patron.password_expiration_date ) %] + [% patron.password_expiration_date | $KohaDates %] + [% ELSE %] + Never + [% END %] +
          28. + [% END %] +
          29. + Protected: + [% IF ( patron.protected == 1 ) %] + Yes + [% ELSE %] + No + [% END %] +
          30. + + [% IF ( patron.borrowernotes ) %] +
          31. + Circulation note:
            + [% patron.borrowernotes | $raw | html_line_break %] +
          32. + [% END %] + + [% IF ( patron.opacnote ) %] +
          33. + OPAC note:
            + [% patron.opacnote | html | html_line_break %] +
          34. + [% END %] + + [% IF ( Koha.Preference('CheckPrevCheckout') == 'softyes' || Koha.Preference('CheckPrevCheckout') == 'softno' ) %] +
          35. + Check previous checkouts: + [% IF ( patron.checkprevcheckout == 'yes' ) %] + Yes + [% ELSIF ( patron.checkprevcheckout == 'no' ) %] + No + [% ELSE %] + Inherited + [% END %] +
          36. + [% END %] + + [% IF Koha.Preference('TranslateNotices') %] +
          37. + Preferred language for notices: + [% translated_language | html %] +
          38. + [% END %] + +
          39. + [% IF patron.gonenoaddress %] + Address in doubt: + Yes + [% ELSE %] + Address in doubt: + No + [% END %] +
          40. + +
          41. + [% IF patron.lost %] + Card lost: + Yes + [% ELSE %] + Card lost: + No + [% END %] +
          42. +
          +
          + [%# /div.rows %] +
          + [%# /div#patron-library-details %] + +
          + [% IF ( patron.B_phone || patron.B_email || patron.contactnote || patron.B_address || patron.B_address2 || patron.B_city || patron.B_zipcode || patron.B_country ) %] +
          +

          Alternate address

          + [% IF CAN_user_borrowers_edit_borrowers %] + Edit + [% END %] +
          +
          +
            + [% PROCESS 'display-alt-address-style' %] +
          +
          +
          +
            + [% IF ( patron.B_phone ) %] +
          1. + Phone: + [% patron.B_phone |html %] +
          2. + [% END %] + + [% IF ( patron.B_email ) %] + + [% END %] + + [% IF ( patron.contactnote ) %] +
          3. + Contact note: + [% patron.contactnote |html %] +
          4. + [% END %] +
          +
          + [% ELSE %] +
          +

          Alternate address

          + [% IF CAN_user_borrowers_edit_borrowers %] + Add + [% END %] +
          + [% END %] +
          + [%# /div#patron-alternate-address %] + +
          + [% IF ( patron.altcontactsurname || patron.altcontactfirstname || patron.altcontactaddress1 || patron.altcontactaddress2 || patron.altcontactaddress3 || patron.altcontactstate || patron.altcontactzipcode || patron.altcontactcountry || patron.altcontactphone ) %] +
          +

          Alternative contact

          + [% IF CAN_user_borrowers_edit_borrowers %] + Edit + [% END %] +
          +
          +
            + [% IF ( patron.altcontactsurname ) %] +
          1. + Surname: + [% patron.altcontactsurname | html %] +
          2. + [% END %] + [% IF ( patron.altcontactfirstname ) %] +
          3. + First name: + [% patron.altcontactfirstname | html %] +
          4. + [% END %] + [% IF ( patron.altcontactaddress1 ) %] +
          5. + Address: + [% patron.altcontactaddress1 | html %] +
          6. + [% END %] + [% IF ( patron.altcontactaddress2 ) %] +
          7. + Address 2: + [% patron.altcontactaddress2 | html %] +
          8. + [% END %] + [% IF ( patron.altcontactaddress3 ) %] +
          9. + City: + [% patron.altcontactaddress3 | html %] +
          10. + [% END %] + + [% IF ( patron.altcontactstate ) %] +
          11. + State: + [% patron.altcontactstate | html %] +
          12. + [% END %] + [% IF ( patron.altcontactzipcode ) %] +
          13. + ZIP/Postal code: + [% patron.altcontactzipcode | html %] +
          14. + [% END %] + [% IF ( patron.altcontactcountry ) %] +
          15. + Country: + [% patron.altcontactcountry | html %] +
          16. + [% END %] + [% IF ( patron.altcontactphone ) %] +
          17. + Phone: + [% patron.altcontactphone | html %] +
          18. + [% END %] +
          +
          + [%# /div.rows %] + [% ELSE %] +
          +

          Alternative contact

          + [% IF CAN_user_borrowers_edit_borrowers %] + Add + [% END %] +
          + [% END %] +
          + [%# /div#patron-alternative-contact %] + + [% IF Koha.Preference('EnableBorrowerFiles') %] +
          +
          +

          Files

          + Manage + + [% IF ( files ) %] +
          +
            + [% FOREACH f IN files %] +
          1. + [% f.file_name | html %] + [% IF ( f.file_description ) %] + - [% f.file_description | html %] + [% END %] +
          2. + [% END # /FOREACH f %] +
          +
          + [% END # /IF files %] +
          + +
          + + [% END # /IF EnableBorrowerFiles %] +
          + +
          + + + [% INCLUDE 'patron-detail-tabs.inc' patronpage = "borrower" %] +[% END %] +[% IF Koha.Preference('ClaimReturnedLostValue') || Koha.Preference('BundleLostValue') %] + [% INCLUDE 'modals/resolve_return_claim.inc' %] +[% END %] + +[% INCLUDE modals/cancel_booking.inc %] [% MACRO jsinclude BLOCK %] [% INCLUDE 'datatables.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/members/notices.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/members/notices.tt index 8a531b91aa..1cacdb14ab 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/members/notices.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/members/notices.tt @@ -7,176 +7,209 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Sent notices for") | html %] [% INCLUDE 'patron-title.inc' no_html = 1 %] - [% t("Patrons") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Sent notices for") | html %] + [% INCLUDE 'patron-title.inc' no_html = 1 %] + [% t("Patrons") | html %] + › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] - [% WRAPPER 'header.inc' %] +[% WRAPPER 'header.inc' %] [% INCLUDE 'patron-search-header.inc' %] [% END %] - [% WRAPPER 'sub-header.inc' %] - [% WRAPPER breadcrumbs %] - [% WRAPPER breadcrumb_item %] - Patrons - [% END %] - [% WRAPPER breadcrumb_item %] - - [% INCLUDE 'patron-title.inc' %] - - [% END %] - [% WRAPPER breadcrumb_item bc_active= 1 %] - Sent notices - [% END %] - [% END #/ WRAPPER breadcrumbs %] - [% END #/ WRAPPER sub-header.inc %] +[% WRAPPER 'sub-header.inc' %] + [% WRAPPER breadcrumbs %] + [% WRAPPER breadcrumb_item %] + Patrons + [% END %] + [% WRAPPER breadcrumb_item %] + [% INCLUDE 'patron-title.inc' %] + [% END %] + [% WRAPPER breadcrumb_item bc_active= 1 %] + Sent notices + [% END %] + [% END #/ WRAPPER breadcrumbs %] +[% END #/ WRAPPER sub-header.inc %] - [% WRAPPER 'main-container.inc' aside='circ-menu' %] +[% WRAPPER 'main-container.inc' aside='circ-menu' %] - [% INCLUDE 'members-toolbar.inc' %] -

          Sent notices for [% INCLUDE 'patron-title.inc' %]

          + [% INCLUDE 'members-toolbar.inc' %] +

          Sent notices for [% INCLUDE 'patron-title.inc' %]

          - [% IF ( QUEUED_MESSAGES ) %] -
          - - - - - - - - - - - - - [% FOREACH QUEUED_MESSAGE IN QUEUED_MESSAGES %] - - - - - - - - + [% IF ( QUEUED_MESSAGES ) %] +
          +
          NoticeTypeStatusUpdated onTime createdDelivery note
          - [% QUEUED_MESSAGE.subject | html %] - - - [% IF ( QUEUED_MESSAGE.message_transport_type == 'email' ) %]email - [% ELSIF ( QUEUED_MESSAGE.message_transport_type == 'print' ) %]print - [% ELSIF ( QUEUED_MESSAGE.message_transport_type == 'feed' ) %]feed - [% ELSIF ( QUEUED_MESSAGE.message_transport_type == 'sms' ) %]sms - [% ELSE %][% QUEUED_MESSAGE.message_transport_type | html %][% END %] - - [% IF ( QUEUED_MESSAGE.status == 'sent' ) %]sent - [% ELSIF ( QUEUED_MESSAGE.status == 'pending' ) %]pending - [% ELSIF ( QUEUED_MESSAGE.status == 'failed' ) %]failed - [% ELSIF ( QUEUED_MESSAGE.status == 'deleted' ) %]deleted - [% ELSE %][% QUEUED_MESSAGE.status | html %][% END %] - [% IF ( QUEUED_MESSAGE.status != 'pending' ) %] -
          -
          - [% INCLUDE 'csrf-token.inc' %] - - - -
          -
          - [% END %] -
          [% QUEUED_MESSAGE.updated_on | $KohaDates with_hours => 1 %][% QUEUED_MESSAGE.time_queued | $KohaDates with_hours => 1 %] - [% IF ( QUEUED_MESSAGE.failure_code ) %] - [% IF ( QUEUED_MESSAGE.failure_code == "INVALID_BORNUMBER" ) %]Invalid borrowernumber [% borrowernumber | html %] - [% ELSIF ( QUEUED_MESSAGE.failure_code == 'NO_EMAIL' ) %]Unable to find an email address for this patron - [% ELSIF (matches = QUEUED_MESSAGE.failure_code.match('INVALID_EMAIL:(\w+)') ) %]Invalid [% matches.0 | html %] email address found [% borrowernumber | html %] - [% ELSIF ( QUEUED_MESSAGE.failure_code == 'NO_FROM' ) %]Missing from email address - [% ELSIF ( QUEUED_MESSAGE.failure_code == 'MISSING_SMS' ) %]Missing SMS number - [% ELSIF ( QUEUED_MESSAGE.failure_code == 'DUPLICATE_MESSAGE' ) %]Message is duplicate - [% ELSIF ( QUEUED_MESSAGE.failure_code == 'NO_NOTES' ) %]No notes from SMS driver - [% ELSIF ( QUEUED_MESSAGE.failure_code == 'SMS_SEND_DRIVER_MISSING' ) %]The SMS driver could not be loaded - [% ELSIF ( QUEUED_MESSAGE.failure_code == 'SENDMAIL' ) %]Unhandled email failure, check the logs for further details - [% ELSIF ( QUEUED_MESSAGE.failure_code == "UNKNOWN_ERROR" ) %]Unknown error - [% ELSE %] - Message failed to send with the following error: [% QUEUED_MESSAGE.failure_code | html %] - [% END %] - [% END %] - [% IF ( QUEUED_MESSAGE.status == 'sent' ) %] - [% IF ( QUEUED_MESSAGE.from_address ) %] - From: [% QUEUED_MESSAGE.from_address | html %] - [% END %] - [% IF ( QUEUED_MESSAGE.to_address ) %] - To: [% QUEUED_MESSAGE.to_address | html %] - [% END %] - [% IF ( QUEUED_MESSAGE.cc_address ) %] - CC: [% QUEUED_MESSAGE.cc_address | html %] - [% END %] - [% END %] -
          + + + + + + + + + + + + [% FOREACH QUEUED_MESSAGE IN QUEUED_MESSAGES %] + + + + + + + -
          NoticeTypeStatusUpdated onTime createdDelivery note
          + [% QUEUED_MESSAGE.subject | html %] + + + [% IF ( QUEUED_MESSAGE.message_transport_type == 'email' ) %] + email + [% ELSIF ( QUEUED_MESSAGE.message_transport_type == 'print' ) %] + print + [% ELSIF ( QUEUED_MESSAGE.message_transport_type == 'feed' ) %] + feed + [% ELSIF ( QUEUED_MESSAGE.message_transport_type == 'sms' ) %] + sms + [% ELSE %] + [% QUEUED_MESSAGE.message_transport_type | html %] + [% END %] + + [% IF ( QUEUED_MESSAGE.status == 'sent' ) %] + sent + [% ELSIF ( QUEUED_MESSAGE.status == 'pending' ) %] + pending + [% ELSIF ( QUEUED_MESSAGE.status == 'failed' ) %] + failed + [% ELSIF ( QUEUED_MESSAGE.status == 'deleted' ) %] + deleted + [% ELSE %] + [% QUEUED_MESSAGE.status | html %] + [% END %] + [% IF ( QUEUED_MESSAGE.status != 'pending' ) %] +
          +
          + [% INCLUDE 'csrf-token.inc' %] + + + +
          +
          + [% END %] +
          [% QUEUED_MESSAGE.updated_on | $KohaDates with_hours => 1 %][% QUEUED_MESSAGE.time_queued | $KohaDates with_hours => 1 %] + [% IF ( QUEUED_MESSAGE.failure_code ) %] + [% IF ( QUEUED_MESSAGE.failure_code == "INVALID_BORNUMBER" ) %] + Invalid borrowernumber [% borrowernumber | html %] + [% ELSIF ( QUEUED_MESSAGE.failure_code == 'NO_EMAIL' ) %] + Unable to find an email address for this patron + [% ELSIF (matches = QUEUED_MESSAGE.failure_code.match('INVALID_EMAIL:(\w+)') ) %] + Invalid [% matches.0 | html %] email address found [% borrowernumber | html %] + [% ELSIF ( QUEUED_MESSAGE.failure_code == 'NO_FROM' ) %] + Missing from email address + [% ELSIF ( QUEUED_MESSAGE.failure_code == 'MISSING_SMS' ) %] + Missing SMS number + [% ELSIF ( QUEUED_MESSAGE.failure_code == 'DUPLICATE_MESSAGE' ) %] + Message is duplicate + [% ELSIF ( QUEUED_MESSAGE.failure_code == 'NO_NOTES' ) %] + No notes from SMS driver + [% ELSIF ( QUEUED_MESSAGE.failure_code == 'SMS_SEND_DRIVER_MISSING' ) %] + The SMS driver could not be loaded + [% ELSIF ( QUEUED_MESSAGE.failure_code == 'SENDMAIL' ) %] + Unhandled email failure, check the logs for further details + [% ELSIF ( QUEUED_MESSAGE.failure_code == "UNKNOWN_ERROR" ) %] + Unknown error + [% ELSE %] + Message failed to send with the following error: [% QUEUED_MESSAGE.failure_code | html %] [% END %] -
          -
          - [% ELSE %] -
          There is no record of any messages that have been sent to this patron.
          + [% END %] + [% IF ( QUEUED_MESSAGE.status == 'sent' ) %] + [% IF ( QUEUED_MESSAGE.from_address ) %] + From: [% QUEUED_MESSAGE.from_address | html %] + [% END %] + [% IF ( QUEUED_MESSAGE.to_address ) %] + To: [% QUEUED_MESSAGE.to_address | html %] + [% END %] + [% IF ( QUEUED_MESSAGE.cc_address ) %] + CC: [% QUEUED_MESSAGE.cc_address | html %] + [% END %] + [% END %] + + [% END %] - + + + + + [% ELSE %] +
          There is no record of any messages that have been sent to this patron.
          [% END %] - - +[% END %] + + + [% MACRO jsinclude BLOCK %] [% INCLUDE 'datatables.inc' %] [% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/members/readingrec.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/members/readingrec.tt index 341e2f9ce4..41e7e8b896 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/members/readingrec.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/members/readingrec.tt @@ -8,11 +8,14 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Circulation history for") | html %] [% INCLUDE 'patron-title.inc' no_html = 1 %] - [% t("Patrons") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Circulation history for") | html %] + [% INCLUDE 'patron-title.inc' no_html = 1 %] + [% t("Patrons") | html %] + › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -37,22 +40,22 @@ [% WRAPPER 'main-container.inc' aside='circ-menu' %] -[% INCLUDE 'members-toolbar.inc' %] -

          Circulation history

          + [% INCLUDE 'members-toolbar.inc' %] +

          Circulation history

          -[% UNLESS checkouts %][% checkouts = [] %][% END %] -[% UNLESS old_checkouts %][% old_checkouts = [] %][% END %] -[% SET all_checkouts = checkouts.merge(old_checkouts) %] -[% UNLESS Koha.Preference('intranetreadinghistory') %] -
          Staff members are not allowed to access patron's checkout history
          -[% ELSIF is_anonymous %] -
          This is the anonymous patron, so no circulation history is displayed. To get a list of anonymized loans, please run a report.
          -[% ELSIF ( patron.privacy == 2) %] -
          This patron has set the privacy rules to never keeping a circulation history.
          -[% ELSIF ( !all_checkouts.size ) %] -
          This patron has no circulation history.
          -[% ELSE %] -
          + [% UNLESS checkouts %][% checkouts = [] %][% END %] + [% UNLESS old_checkouts %][% old_checkouts = [] %][% END %] + [% SET all_checkouts = checkouts.merge(old_checkouts) %] + [% UNLESS Koha.Preference('intranetreadinghistory') %] +
          Staff members are not allowed to access patron's checkout history
          + [% ELSIF is_anonymous %] +
          This is the anonymous patron, so no circulation history is displayed. To get a list of anonymized loans, please run a report.
          + [% ELSIF ( patron.privacy == 2) %] +
          This patron has set the privacy rules to never keeping a circulation history.
          + [% ELSIF ( !all_checkouts.size ) %] +
          This patron has no circulation history.
          + [% ELSE %] +
          [% BLOCK table_readingrec %] @@ -81,23 +84,19 @@ [% SET biblio = item.biblio %] - - + + - + - + - + [% IF Koha.Preference('RecordStaffUserOnCheckout') %] [% SET issuer = checkout.issuer %] [% END %] - + [% IF checkout.returndate %] - + [% ELSE %] [% END %] @@ -141,9 +139,9 @@ [% IF Koha.Preference('OnSiteCheckouts') %] [% WRAPPER tabs id= "tabs" %] [% WRAPPER tabs_nav %] - [% WRAPPER tab_item tabname= "tab_all" bt_active= 1 %] All [% END %] - [% WRAPPER tab_item tabname= "tab_checkout" %] Checkouts [% END %] - [% WRAPPER tab_item tabname= "tab_onsite_checkout" %] On-site checkouts [% END %] + [% WRAPPER tab_item tabname= "tab_all" bt_active= 1 %]All[% END %] + [% WRAPPER tab_item tabname= "tab_checkout" %]Checkouts[% END %] + [% WRAPPER tab_item tabname= "tab_onsite_checkout" %]On-site checkouts[% END %] [% END # /WRAPPER tabs_nav %] [% WRAPPER tab_panels %] [% WRAPPER tab_panel tabname="readingrec" bt_active= 1 %] @@ -152,12 +150,10 @@ [% END # /WRAPPER tab_panels %] [% END # /WRAPPER tabs %] [% ELSE %] -
          - [% INCLUDE table_readingrec %] -
          +
          [% INCLUDE table_readingrec %]
          + [% END # /IF Koha.Preference('OnSiteCheckouts') %] -[% END %] - + [% END %] [% END %] [% MACRO jsinclude BLOCK %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/members/recallshistory.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/members/recallshistory.tt index c790c7c3c2..b6c4c24665 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/members/recallshistory.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/members/recallshistory.tt @@ -5,35 +5,34 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Recalls history for") | html %] [% INCLUDE 'patron-title.inc' %] - [% t("Patrons") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Recalls history for") | html %] + [% INCLUDE 'patron-title.inc' %] + [% t("Patrons") | html %] + › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] - [% WRAPPER 'header.inc' %] - [% INCLUDE 'patron-search-header.inc' %] - [% END %] +[% WRAPPER 'header.inc' %] + [% INCLUDE 'patron-search-header.inc' %] +[% END %] - - [% WRAPPER 'main-container.inc' aside='circ-menu' %] - [% INCLUDE 'members-toolbar.inc' %] -

          Recalls history

          - [% IF Koha.Preference('UseRecalls') %] - - - [% INCLUDE 'recalls.inc' %] - [% ELSE %] -
          Recalls have not been enabled. Enable the UseRecalls system preference to use recalls.
          - [% END %] + +[% WRAPPER 'main-container.inc' aside='circ-menu' %] + [% INCLUDE 'members-toolbar.inc' %] +

          Recalls history

          + [% IF Koha.Preference('UseRecalls') %] + + + [% INCLUDE 'recalls.inc' %] + [% ELSE %] +
          Recalls have not been enabled. Enable the UseRecalls system preference to use recalls.
          [% END %] +[% END %] [% MACRO jsinclude BLOCK %] [% INCLUDE 'datatables.inc' %] [% INCLUDE 'columns_settings.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/members/routing-lists.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/members/routing-lists.tt index 28fbb489cd..a773aebfcb 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/members/routing-lists.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/members/routing-lists.tt @@ -6,11 +6,14 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Subscription routing lists for") | html %] [% INCLUDE 'patron-title.inc' no_html = 1 %] - [% t("Patrons") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Subscription routing lists for") | html %] + [% INCLUDE 'patron-title.inc' no_html = 1 %] + [% t("Patrons") | html %] + › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -34,67 +37,61 @@ [% END #/ WRAPPER sub-header.inc %] [% WRAPPER 'main-container.inc' aside='circ-menu' %] - [% INCLUDE 'members-toolbar.inc' %] + [% INCLUDE 'members-toolbar.inc' %] -

          Subscription routing lists for [% INCLUDE 'patron-title.inc' %]

          - -

          Search subscriptions:

          -[% IF ( routing ) %][% END %] - - +

          Subscription routing lists for [% INCLUDE 'patron-title.inc' %]

          + +

          Search subscriptions:

          + [% IF ( routing ) %][% END %] + + + + -[% SET routinglists = patron.get_routing_lists %] -

          -[% UNLESS ( routinglists ) %] -0 subscription routing lists -[% ELSIF ( routinglists.count == 1 ) %] -[% routinglists.count | html %] subscription routing list -[% ELSE %] -[% routinglists.count | html %] subscription routing lists -[% END %] -

          - -
          - -[% IF ( routinglists ) %] -
          - [% IF checkout.onsite_checkout %][% issuetype = 'onsite_checkout' | html %] - [% ELSE %][% issuetype = 'standard_checkout' | html %] + [% IF checkout.onsite_checkout %] + [% issuetype = 'onsite_checkout' | html %] + [% ELSE %] + [% issuetype = 'standard_checkout' | html %] [% END %] [% issuetype | html %] - [% checkout.timestamp | $KohaDates with_hours => 1 %] - - [% INCLUDE 'biblio-title.inc' biblio=biblio link = 1 %] - [% checkout.timestamp | $KohaDates with_hours => 1 %] [% INCLUDE 'biblio-title.inc' biblio=biblio link = 1 %] [% biblio.author | html %] - [% item.itemcallnumber | html %] - [% item.itemcallnumber | html %] [% IF item.enumchron %] @@ -105,31 +104,30 @@ [% END %] [% item.barcode | html %][% item.barcode | html %] [% checkout.renewals_count | html %] [% IF checkout.renewals_count > 0 %] [ View ] [% END %] - [% checkout.issuedate | $KohaDates with_hours => 1 %] - [% checkout.issuedate | $KohaDates with_hours => 1 %] [% Branches.GetName( checkout.branchcode ) | html %][% issuer.firstname | html %] [% issuer.surname | html %] - [% checkout.date_due | $KohaDates as_due_date => 1 %] - [% checkout.date_due | $KohaDates as_due_date => 1 %] - [% checkout.returndate | $KohaDates with_hours => 1 %] - [% checkout.returndate | $KohaDates with_hours => 1 %] - Checked out + Checked out
          - - - - - - - - - [% FOREACH routinglist IN routinglists %] - - - - - - [% END %] - -
          Subscription titlePositionRouting list
          - - [% routinglist.subscription.biblio.title | html %] - - - [% routinglist.ranking | html %] - - - Edit routing list - - - -
          -[% ELSE %] -

          Patron does not belong to any subscription routing lists.

          - - -[% END %] - - + [% SET routinglists = patron.get_routing_lists %] +

          + [% UNLESS ( routinglists ) %] + 0 subscription routing lists + [% ELSIF ( routinglists.count == 1 ) %] + [% routinglists.count | html %] subscription routing list + [% ELSE %] + [% routinglists.count | html %] subscription routing lists + [% END %] +

          +
          + [% IF ( routinglists ) %] + + + + + + + + + + [% FOREACH routinglist IN routinglists %] + + + + + + [% END %] + +
          Subscription titlePositionRouting list
          + [% routinglist.subscription.biblio.title | html %] + [% routinglist.ranking | html %] + Edit routing list + + +
          + [% ELSE %] +

          Patron does not belong to any subscription routing lists.

          + + + [% END %] +
          [% END %] [% MACRO jsinclude BLOCK %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/members/statistics.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/members/statistics.tt index 88e715df34..043687feff 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/members/statistics.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/members/statistics.tt @@ -6,13 +6,15 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% UNLESS blocking_error %] - [% t("Statistics for") | html %] [% INCLUDE 'patron-title.inc' no_html = 1 %] - [% END %] › - [% t("Patrons") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% UNLESS blocking_error %] + [% t("Statistics for") | html %] + [% INCLUDE 'patron-title.inc' no_html = 1 %] + [% END %] + › [% t("Patrons") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -37,14 +39,14 @@ [% WRAPPER 'main-container.inc' aside='circ-menu' %] - [% INCLUDE 'members-toolbar.inc' %] + [% INCLUDE 'members-toolbar.inc' %] -

          Statistics for [% INCLUDE 'patron-title.inc' %]

          - [% IF ( datas.size ) %] -
          - - - +

          Statistics for [% INCLUDE 'patron-title.inc' %]

          + [% IF ( datas.size ) %] +
          +
          + + [% FOREACH cn IN column_names %] - - + + - - [% FOREACH r IN datas %] - - [% FOREACH c IN r %] - - [% END %] - - [% END %] - - + + [% FOREACH r IN datas %] - - - - - + [% FOREACH c IN r %] + + [% END %] - -
          [% SWITCH cn %] @@ -67,33 +69,33 @@ Today's checkouts Today's checkins Total checkouts
          [% c | html %]
          TOTAL[% count_total_precedent_state | html %][% count_total_issues | html %][% count_total_issues_returned | html %][% count_total_actual_state | html %][% c | html %]
          -
          - [% ELSE %] -
          There are no statistics for this patron.
          - [% END %] - + [% END %] + + + + TOTAL + [% count_total_precedent_state | html %] + [% count_total_issues | html %] + [% count_total_issues_returned | html %] + [% count_total_actual_state | html %] + + + + + + [% ELSE %] +
          There are no statistics for this patron.
          + [% END %] [% END %] [% MACRO jsinclude BLOCK %] @@ -101,11 +103,13 @@ [% Asset.js("js/members-menu.js") | $raw %] [% INCLUDE 'datatables.inc' %] [% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/members/two_factor_auth.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/members/two_factor_auth.tt index 064891dc20..3359686eff 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/members/two_factor_auth.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/members/two_factor_auth.tt @@ -4,11 +4,12 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Two-factor authentication") | html %] › - [% t("Patrons") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Two-factor authentication") | html %] + › [% t("Patrons") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -33,55 +34,53 @@ [% WRAPPER 'main-container.inc' aside='circ-menu' %] - [% INCLUDE 'members-toolbar.inc' %] + [% INCLUDE 'members-toolbar.inc' %] -

          Manage two-factor authentication

          +

          Manage two-factor authentication

          - [% IF ( missing_key ) %] -
          -

          - Operation cannot proceed, please define an encryption key in your configuration. -

          -
          - [% ELSE %] - [% PROCESS registration_form %] + [% IF ( missing_key ) %] +
          +

          Operation cannot proceed, please define an encryption key in your configuration.

          +
          + [% ELSE %] + [% PROCESS registration_form %] -
          -
          -
          Status: Enabled
          +
          +
          +
          Status: Enabled
          -
          - [% INCLUDE 'csrf-token.inc' %] - - -
          -
          +
          + [% INCLUDE 'csrf-token.inc' %] + + +
          +
          -
          -
          Status: Disabled
          - [% IF Koha.Preference('TwoFactorAuthentication') == 'enforced' %] -
          Two-factor authentication is mandatory to login. If you do not enable now it will be asked at your next login.
          - [% END %] - - -
          -
          +
          +
          Status: Disabled
          + [% IF Koha.Preference('TwoFactorAuthentication') == 'enforced' %] +
          Two-factor authentication is mandatory to login. If you do not enable now it will be asked at your next login.
          [% END %] + + +
          +
          + [% END %] [% END %] [% MACRO jsinclude BLOCK %] [% INCLUDE 'str/members-menu.inc' %] [% Asset.js("js/members-menu.js") | $raw %] [% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/members/update-child.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/members/update-child.tt index fdd35738e7..3403a229bf 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/members/update-child.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/members/update-child.tt @@ -3,82 +3,82 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Choose adult category") | html %] › - [% t("Patrons") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Choose adult category") | html %] + › [% t("Patrons") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] -
          +
          + [% IF ( MULTI ) %] +

          Choose adult category

          -[% IF ( MULTI ) %] - -

          Choose adult category

          - - [% IF patron_categories %] -
          - [% INCLUDE 'csrf-token.inc' %] -
          - - - - - - - - - - [% FOREACH patron_category IN patron_categories %] + [% IF patron_categories %] + + [% INCLUDE 'csrf-token.inc' %] +
          +
           CodeDescription
          + - - - + + + - [% END %] - -
          - - [% patron_category.categorycode | html %] CodeDescription
          - - - -
          - -
          + + + [% FOREACH patron_category IN patron_categories %] + + + + + [% patron_category.categorycode | html %] + + + [% END %] + + + + + + + + + [% END %] [% END %] -[% END %] -
          - +
          + [% MACRO jsinclude BLOCK %] [% INCLUDE 'datatables.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/offline_circ/enqueue_koc.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/offline_circ/enqueue_koc.tt index 667eead59c..d6413e7ae8 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/offline_circ/enqueue_koc.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/offline_circ/enqueue_koc.tt @@ -2,11 +2,12 @@ [% USE Koha %] [% PROCESS 'i18n.inc' %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Add offline circulations to queue") | html %] › - [% t("Circulation") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Add offline circulations to queue") | html %] + › [% t("Circulation") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -26,22 +27,22 @@ [% END #/ WRAPPER sub-header.inc %] [% WRAPPER 'main-container.inc' %] +

          Koha offline circulation

          +
          +

          Your file was uploaded. Once all files are uploaded, please process them in pending offline circulation actions.

          -

          Koha offline circulation

          -
          -

          Your file was uploaded. Once all files are uploaded, please process them in pending offline circulation actions.

          - - [% FOREACH message IN messages %] - [% IF ( message.message ) %] - [% IF ( message.ERROR_file_version ) %] -

          Warning: This file is version [% message.upload_version | html %], but I only know how to import version [% message.current_version | html %]. I'll try my best.

          - [% END %] - [% END %] + [% FOREACH message IN messages %] + [% IF ( message.message ) %] + [% IF ( message.ERROR_file_version ) %] +

          Warning: This file is version [% message.upload_version | html %], but I only know how to import version [% message.current_version | html %]. I'll try my best.

          [% END %] + [% END %] + [% END %] -

          Upload another KOC file

          +

          Upload another KOC file

          -

          View pending offline circulation actions

          -
          +

          View pending offline circulation actions

          +
          + [% END %] [% INCLUDE 'intranet-bottom.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/offline_circ/list.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/offline_circ/list.tt index 80e3be7434..b285cf113a 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/offline_circ/list.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/offline_circ/list.tt @@ -4,17 +4,18 @@ [% USE KohaDates %] [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] - [% INCLUDE "doc-head-open.inc" %] - [% FILTER collapse %] - [% t("Offline circulation") | html %] › - [% t("Circulation") | html %] › - [% t("Koha") | html %] - [% END %] - [% INCLUDE "doc-head-close.inc" %] +[% INCLUDE "doc-head-open.inc" %] +[% FILTER collapse %] + [% t("Offline circulation") | html %] + › [% t("Circulation") | html %] › [% t("Koha") | html %] + [% END %] +[% INCLUDE "doc-head-close.inc" %] - [% WRAPPER 'header.inc' %] +[% WRAPPER 'header.inc' %] [% INCLUDE 'circ-search.inc' %] [% END %] @@ -30,15 +31,14 @@ [% END #/ WRAPPER sub-header.inc %] [% WRAPPER 'main-container.inc' %] -

          Offline circulation

          +

          Offline circulation

          - [% IF ( pending_operations ) %] - -
          -

          - Check all - Uncheck all -

          + [% IF ( pending_operations ) %] + +

          + Check all + Uncheck all +

          @@ -61,14 +61,14 @@
          [% SWITCH ( operation.action ) -%] - [% CASE "issue" -%] - Check out - [% CASE "return" -%] - Check in - [% CASE "payment" -%] - Payment - [% CASE # default case -%] - [% operation.action | html %] + [% CASE "issue" -%] + Check out + [% CASE "return" -%] + Check in + [% CASE "payment" -%] + Payment + [% CASE # default case -%] + [% operation.action | html %] [% END -%] @@ -92,70 +92,68 @@ [% END %]
          -
          - -

          For the selected operations: - -

          - -
          - - [% ELSE %] - -

          There are no pending offline operations.

          - - [% END %] + + +

          For the selected operations: + +

          + + [% ELSE %] +

          There are no pending offline operations.

          + [% END %] [% END %] [% MACRO jsinclude BLOCK %] + [% END %] [% INCLUDE 'installer-intranet-bottom.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/onboarding/onboardingstep3.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/onboarding/onboardingstep3.tt index 2fb347a9a9..8bbe027f57 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/onboarding/onboardingstep3.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/onboarding/onboardingstep3.tt @@ -3,135 +3,139 @@ [% USE Asset %] [% PROCESS 'i18n.inc' %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Create Koha administrator patron") | html %] › - [% t("Web installer") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Create Koha administrator patron") | html %] + › [% t("Web installer") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'installer-doc-head-close.inc' %] -
          -
          -
          - -

          Web installer › Create Koha administrator patron

          +
          +
          +
          + +

          Web installer › Create Koha administrator patron

          - [% INCLUDE 'onboarding_messages.inc' %] + [% INCLUDE 'onboarding_messages.inc' %] -
          +
          +
            +
          1. Installation
          2. +
          3. Onboarding +
              +
            1. Create a library
            2. +
            3. Create a patron category
            4. +
            5. Create Koha administrator patron
            6. +
            7. Create a new item type
            8. +
            9. Create a new circulation rule
            10. +
            +
          4. +
          +
          + +

          Now we will create a patron with superlibrarian permissions. Log in with this to access Koha as a staff member with all permissions.

          +
          + [% INCLUDE 'csrf-token.inc' %] +
          + + +

          Administrator identity

            -
          1. Installation
          2. -
          3. Onboarding -
              -
            1. Create a library
            2. -
            3. Create a patron category
            4. -
            5. Create Koha administrator patron
            6. -
            7. Create a new item type
            8. -
            9. Create a new circulation rule
            10. -
            +
          4. + + + Required +
          5. +
          6. + + + Required
          -
          -

          - Now we will create a patron with superlibrarian permissions. Log in with this to access Koha as a staff member with all permissions. -

          - - [% INCLUDE 'csrf-token.inc' %] -
          - - -

          Administrator identity

          -
            -
          1. - - - Required -
          2. -
          3. - - - Required -
          4. -
          - -
            -
          1. - - [% IF patrons && patrons > 1 %] - - [% ELSE %] - +
              +
            1. + + [% IF patrons && patrons > 1 %] + + [% ELSE %] + + [% END %] + Required +
            2. +
            3. + + + + Required +
            4. +
            5. + + + Required

              + Note: If you installed sample patron categories please select the "Staff" option in the patron categories dropdown box. +
            6. +
            - - - - Required -
          2. -
          3. - - - Required

            - Note: If you installed sample patron categories please select the "Staff" option in the patron categories dropdown box. -
          4. -
          +

          Administrator account permissions

          +
            +
          1. + + + superlibrarian +
          2. +
          -

          Administrator account permissions

          -
            -
          1. - - - superlibrarian -
          2. -
          +

          Administrator login

          +
            +
          1. + + + Required +
          2. +
          3. + + + Required +
          4. +
          5. + + + Required +
          6. +
          +

          + To create another patron, go to: + Patrons › New patron +

          +

          + To edit patron permissions, go to: + More › Set permissions +

          +
          -

          Administrator login

          -
            -
          1. - - - Required -
          2. -
          3. - - - Required -
          4. -
          5. - - - Required -
          6. -
          -

          - To create another patron, go to: - Patrons › New patron -

          -

          - To edit patron permissions, go to: - More › Set permissions -

          - - - - -
          -
          -
          + + +
          + +
          + +
          + [% MACRO jsinclude BLOCK %] [% INCLUDE 'validator-strings.inc' %] @@ -141,4 +145,3 @@ [% END %] [% INCLUDE 'installer-intranet-bottom.inc' %] - diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/onboarding/onboardingstep4.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/onboarding/onboardingstep4.tt index d3103d87fa..90fc2a8767 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/onboarding/onboardingstep4.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/onboarding/onboardingstep4.tt @@ -1,77 +1,87 @@ [% USE raw %] [% PROCESS 'i18n.inc' %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Create a new item type") | html %] › - [% t("Web installer") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Create a new item type") | html %] + › [% t("Web installer") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'installer-doc-head-close.inc' %] -
          -
          -
          - -

          Web installer › Create a new item type

          +
          +
          +
          + +

          Web installer › Create a new item type

          - [% INCLUDE 'onboarding_messages.inc' %] + [% INCLUDE 'onboarding_messages.inc' %] -
          +
          +
            +
          1. Installation
          2. +
          3. Onboarding +
              +
            1. Create a library
            2. +
            3. Create a patron category
            4. +
            5. Create Koha administrator patron
            6. +
            7. Create a new item type
            8. +
            9. Create a new circulation rule
            10. +
            +
          4. +
          +
          + + + +

          Item types are used to group related items. Examples of item types might be books, CDs, or DVDs.

          +

          When adding to your institution's catalog you will create an item of a particular item type.

          +

          + Important: Item types are what you apply circulation rules to. Circulation rules govern how your institution will lend its items: Checkout length, renewal policy, hold policy, etc. For example a circulation rule applied to + the DVD item type may enforce a payment of $1.00 for checking out any DVD.

          + +
          + [% INCLUDE 'csrf-token.inc' %] +
          + +
            -
          1. Installation
          2. -
          3. Onboarding -
              -
            1. Create a library
            2. -
            3. Create a patron category
            4. -
            5. Create Koha administrator patron
            6. -
            7. Create a new item type
            8. -
            9. Create a new circulation rule
            10. -
            +
          4. + + + Required +
          5. + +
          6. + + + Required
          -
          - - -

          Item types are used to group related items. Examples of item types might be books, CDs, or DVDs.

          -

          When adding to your institution's catalog you will create an item of a particular item type.

          -

          Important: Item types are what you apply circulation rules to. Circulation rules govern how your institution will lend its items: Checkout length, renewal policy, hold policy, etc. For example a circulation rule applied to the DVD item type may enforce a payment of $1.00 for checking out any DVD.

          - - - [% INCLUDE 'csrf-token.inc' %] -
          - - -
            -
          1. - - - Required -
          2. - -
          3. - - - Required -
          4. -
          - -

          To create another item type later and for more settings go to: - Administration › Item types -

          - -
          - -
          -
          -
          +

          + To create another item type later and for more settings go to: + Administration › Item types +

          + + + +
          + +
          + +
          + [% MACRO jsinclude BLOCK %] [% INCLUDE 'validator-strings.inc' %] [% INCLUDE 'installer-strings.inc' %] - + [% END %] [% INCLUDE 'installer-intranet-bottom.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/onboarding/onboardingstep5.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/onboarding/onboardingstep5.tt index 0b82786767..114e03a1bc 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/onboarding/onboardingstep5.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/onboarding/onboardingstep5.tt @@ -1,186 +1,188 @@ [% USE raw %] [% PROCESS 'i18n.inc' %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% IF all_done %] - [% t("Onboarding complete") | html %] - [% ELSE %] - [% t("Create circulation rule") | html %] - [% END %] › - [% t("Web installer") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% IF all_done %] + [% t("Onboarding complete") | html %] + [% ELSE %] + [% t("Create circulation rule") | html %] + [% END %] + › [% t("Web installer") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'installer-doc-head-close.inc' %] -
          -
          -
          - +
          +
          +
          + - [% IF all_done %] + [% IF all_done %] +

          Web installer › Complete

          + [% INCLUDE 'onboarding_messages.inc' %] -

          Web installer › Complete

          - [% INCLUDE 'onboarding_messages.inc' %] +
          +
            +
          1. Installation
          2. +
          3. Onboarding
          4. +
          +
          -
          +

          Congratulations you have finished and are ready to use Koha

          + Start using Koha + [% ELSE %] +

          Web installer › Create a new circulation rule

          + + [% INCLUDE 'onboarding_messages.inc' %] + +
          +
            +
          1. Installation
          2. +
          3. Onboarding +
              +
            1. Create a library
            2. +
            3. Create a patron category
            4. +
            5. Create Koha administrator patron
            6. +
            7. Create a new item type
            8. +
            9. Create a new circulation rule
            10. +
            +
          4. +
          +
          + +
          + [% INCLUDE 'csrf-token.inc' %] +
          + +
            -
          1. Installation
          2. -
          3. Onboarding
          4. -
          -
          +
        • + + + Required +
        • +
        • + + + Required +
        • -

          Congratulations you have finished and are ready to use Koha

          - Start using Koha +
        • + + + Required +
        • +
        • + + + Required +
        • - [% ELSE %] +
        • + + + Required +
        • +
        • + + + Required +
        • +
        • + + + Required +
        • - [% INCLUDE 'onboarding_messages.inc' %] +
        • + + + Required +
        • -
          -
            -
          1. Installation
          2. -
          3. Onboarding -
              -
            1. Create a library
            2. -
            3. Create a patron category
            4. -
            5. Create Koha administrator patron
            6. -
            7. Create a new item type
            8. -
            9. Create a new circulation rule
            10. -
            +
          4. + + +
          5. + +
          6. + + +
          7. + +
          8. + + +
          9. + +
          10. + +
          -
          +

          + To create circulation rule, go to: + Administration › Circulation and fine rules +

          + - - [% INCLUDE 'csrf-token.inc' %] -
          - - -
            -
          1. - - - Required -
          2. -
          3. - - - Required -
          4. - -
          5. - - - Required -
          6. -
          7. - - - Required -
          8. - -
          9. - - - Required -
          10. -
          11. - - - Required -
          12. -
          13. - - - Required -
          14. - -
          15. - - - Required -
          16. - -
          17. - - -
          18. - -
          19. - - -
          20. - -
          21. - - -
          22. - -
          23. - - -
          24. -
          -

          - To create circulation rule, go to: - Administration › Circulation and fine rules -

          - -
          - - - - [% END %] -
          -
          -
          + + + [% END %] +
          + +
          + +
          + [% MACRO jsinclude BLOCK %] [% INCLUDE 'validator-strings.inc' %] [% INCLUDE 'installer-strings.inc' %] - + [% END %] [% INCLUDE 'installer-intranet-bottom.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/patron_lists/add-modify.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/patron_lists/add-modify.tt index 871d82599b..61c58ab6ae 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/patron_lists/add-modify.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/patron_lists/add-modify.tt @@ -4,87 +4,83 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% IF list.patron_list_id %] - [% tx("Modify patron list '{list_name}'", { list_name = list.name }) | html %] - [% ELSE %] - [% t("New patron list") | html %] - [% END %] › - [% t("Patron lists") | html %] › - [% t("Tools") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% IF list.patron_list_id %] + [% tx("Modify patron list '{list_name}'", { list_name = list.name }) | html %] + [% ELSE %] + [% t("New patron list") | html %] + [% END %] + › [% t("Patron lists") | html %] › [% t("Tools") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] -[% WRAPPER 'header.inc' %] +[% WRAPPER 'header.inc' %] [% INCLUDE 'cat-search.inc' %] [% END %] - [% WRAPPER 'sub-header.inc' %] - [% WRAPPER breadcrumbs %] - [% WRAPPER breadcrumb_item %] - Tools - [% END %] - [% WRAPPER breadcrumb_item %] - Patron lists - [% END %] - [% WRAPPER breadcrumb_item bc_active= 1 %] - [% IF list.patron_list_id %] - [% tx("Modify patron list '{list_name}'", { list_name = list.name }) | html %] - [% ELSE %] - New patron list - [% END %] - [% END %] - [% END #/ WRAPPER breadcrumbs %] - [% END #/ WRAPPER sub-header.inc %] - - [% WRAPPER 'main-container.inc' %] -

          +[% WRAPPER 'sub-header.inc' %] + [% WRAPPER breadcrumbs %] + [% WRAPPER breadcrumb_item %] + Tools + [% END %] + [% WRAPPER breadcrumb_item %] + Patron lists + [% END %] + [% WRAPPER breadcrumb_item bc_active= 1 %] [% IF list.patron_list_id %] [% tx("Modify patron list '{list_name}'", { list_name = list.name }) | html %] [% ELSE %] New patron list [% END %] -

          + [% END %] + [% END #/ WRAPPER breadcrumbs %] +[% END #/ WRAPPER sub-header.inc %] -
          - [% INCLUDE 'csrf-token.inc' %] -
          +[% WRAPPER 'main-container.inc' %] +

          + [% IF list.patron_list_id %] + [% tx("Modify patron list '{list_name}'", { list_name = list.name }) | html %] + [% ELSE %] + New patron list + [% END %] +

          - Patron list details + + [% INCLUDE 'csrf-token.inc' %] +
          + Patron list details -
            -
          1. - - -
          2. +
              +
            1. + + +
            2. -
            3. - - [% IF list.shared %] - - [% ELSE %] - - [% END %] -
            4. +
            5. + + [% IF list.shared %] + + [% ELSE %] + + [% END %] +
            6. -
            7. - Owner: [% logged_in_user.userid | html %] -
            8. -
            +
          3. Owner: [% logged_in_user.userid | html %]
          4. +
          +
          -
          - -
          - - - - Cancel -
          -
          - [% END %] +
          + + + + Cancel +
          + +[% END %] [% MACRO jsinclude BLOCK %] [% Asset.js("js/tools-menu.js") | $raw %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/patron_lists/list.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/patron_lists/list.tt index 3fe05c9981..67bd3ee8da 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/patron_lists/list.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/patron_lists/list.tt @@ -7,12 +7,12 @@ [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] [% INCLUDE 'columns_settings.inc' %] -[% FILTER collapse %] - [% list.name | html %] › - [% t("Patron lists") | html %] › - [% t("Tools") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% list.name | html %] + › [% t("Patron lists") | html %] › [% t("Tools") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] [% END %] [% INCLUDE 'blocking_errors.inc' %] @@ -23,17 +24,18 @@
          - [% IF slip %] - [% IF plain %] -
          +    [% IF slip %]
          +        [% IF plain %]
          +            
                 [% slip | html %]
          -    
          +
          + [% ELSE %] + [% slip | $raw %] + [% END %] [% ELSE %] - [% slip | $raw %] + No print template found [% END %] - [% ELSE %] - No print template found - [% END %]
          [% MACRO jsinclude BLOCK %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/pos/register.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/pos/register.tt index 15878a0352..5a7a740b94 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/pos/register.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/pos/register.tt @@ -8,10 +8,12 @@ [% SET footerjs = 1 %] [% PROCESS 'accounts.inc' %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% tx("Transaction history for {register}", { register = register.name }) | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% tx("Transaction history for {register}", { register = register.name }) | html %] + › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -28,75 +30,77 @@ [% END #/ WRAPPER breadcrumbs %] [% END #/ WRAPPER sub-header.inc %] - [% WRAPPER 'main-container.inc' aside='pos-menu' %] - [% IF ( error_registers ) %] -
          -

          - You must have at least one cash register associated with the library before you can record payments. -

          - [% IF ( CAN_user_parameters_manage_cash_registers ) %] -
          - - -
          - [% END %] -
          - [% ELSE %] + [% IF ( error_registers ) %] +
          +

          You must have at least one cash register associated with the library before you can record payments.

          + [% IF ( CAN_user_parameters_manage_cash_registers ) %] +
          + + +
          + [% END %] +
          + [% ELSE %] - [% IF ( error_cashup_permission ) %] -
          - You do not have permission to perform cashup actions. + [% IF ( error_cashup_permission ) %] +
          You do not have permission to perform cashup actions.
          + [% END %] + + [% IF ( error_refund_permission ) %] +
          You do not have permission to perform refund actions.
          + [% END %] + + [% IF ( CAN_user_cash_management_cashup ) %] +
          +
          - [% END %] + [% END %] - [% IF ( error_refund_permission ) %] -
          - You do not have permission to perform refund actions. -
          - [% END %] - - [% IF ( CAN_user_cash_management_cashup ) %] -
          - -
          - [% END %] - -

          Transaction history for [% register.name | html %]

          - -

          Summary

          -
            - [% IF register.last_cashup %] -
          • Last cashup: [% register.last_cashup.timestamp | $KohaDates with_hours => 1 %] (Summary)
          • - [% END %] -
          • Float: [% register.starting_float | $Price %]
          • -
          • Total income (cash): [% accountlines.credits_total * -1 | $Price %] ([% accountlines.credits_total(payment_type => [ 'CASH', 'SIP00' ]) * -1 | $Price %])
          • -
          • Total outgoing (cash): [% accountlines.debits_total * -1 | $Price %] ([% accountlines.debits_total( payment_type => [ 'CASH', 'SIP00' ]) * -1 | $Price %])
          • -
          • Total bankable: [% accountlines.total( payment_type => [ 'CASH', 'SIP00' ]) * -1 | $Price %]
          • -
          +

          Transaction history for [% register.name | html %]

          +

          Summary

          +
            [% IF register.last_cashup %] -

            Transactions since [% register.last_cashup.timestamp | $KohaDates with_hours => 1 %]

            - [% ELSE %] -

            Transactions to date

            +
          • Last cashup: [% register.last_cashup.timestamp | $KohaDates with_hours => 1 %] (Summary)
          • [% END %] -
            - - - - - - - - - - - - - - [% FOREACH accountline IN accountlines %] - [% IF accountline.is_credit %] +
          • Float: [% register.starting_float | $Price %]
          • +
          • Total income (cash): [% accountlines.credits_total * -1 | $Price %] ([% accountlines.credits_total(payment_type => [ 'CASH', 'SIP00' ]) * -1 | $Price %])
          • +
          • Total outgoing (cash): [% accountlines.debits_total * -1 | $Price %] ([% accountlines.debits_total( payment_type => [ 'CASH', 'SIP00' ]) * -1 | $Price %])
          • +
          • Total bankable: [% accountlines.total( payment_type => [ 'CASH', 'SIP00' ]) * -1 | $Price %]
          • + + + [% IF register.last_cashup %] +

            Transactions since [% register.last_cashup.timestamp | $KohaDates with_hours => 1 %]

            + [% ELSE %] +

            Transactions to date

            + [% END %] +
            +
            IDDATATransactionDescriptionPriceTotalActions
            + + + + + + + + + + + + + [% FOREACH accountline IN accountlines %] + [% IF accountline.is_credit %] [% IF accountline.credit_offsets.count == 1 %] @@ -105,52 +109,228 @@ - + - [% ELSE %] + [% ELSE %] [% FOREACH credit IN accountline.credit_offsets %] - [% IF credit.debit %] - - - - - - - - - + [% IF credit.debit %] + + + + + + + + + + [% END %] [% END %] + [% END %] + [% ELSE %] + [% FOREACH debit IN accountline.debit_offsets %] + [% IF debit.credit %] + + + + + + + + + [% END %] + [% END %] + [% END %] + [% END %] + + + + + + + + +
            IDDATATransactionDescriptionPriceTotalActions
            [%- PROCESS account_type_description account=accountline -%] ([% AuthorisedValues.GetByCode( 'PAYMENT_TYPE', accountline.payment_type ) | html %]) [% accountline.amount * -1 | $Price %]
            [% accountline.accountlines_id | html %]{ "type": "credit", "identifier": "[%- accountline.credit_number | html -%]", "description": "[%- PROCESS account_type_description account=accountline -%] ([% AuthorisedValues.GetByCode( 'PAYMENT_TYPE', accountline.payment_type ) | html %])", "amount": "[% accountline.amount * -1 | $Price %]", "timestamp": "[% accountline.timestamp | $KohaDates with_hours => 1 %]" } - [%- PROCESS account_type_description account=credit.debit -%] - [%- IF credit.debit.description -%] ([% credit.debit.description | html %])[%- END -%] - [%- IF ( credit.debit.itemnumber ) -%] ([% credit.debit.item.biblio.title | html %])[%- END -%] - [% credit.debit.amount | $Price %] - [% IF CAN_user_cash_management_anonymous_refund && !(credit.debit.status == 'REFUNDED') && !(credit.debit.debit_type_code == 'PAYOUT') %] - - [% ELSIF CAN_user_updatecharges_refund && !(credit.debit.status == 'REFUNDED') && credit.debit.borrowernumber && !(credit.debit.debit_type_code == 'PAYOUT') %] - - [% END %] -
            [% accountline.accountlines_id | html %]{ "type": "credit", "identifier": "[%- accountline.credit_number | html -%]", "description": "[%- PROCESS account_type_description account=accountline -%] + ([% AuthorisedValues.GetByCode( 'PAYMENT_TYPE', accountline.payment_type ) | html %])", "amount": "[% accountline.amount * -1 | $Price %]", "timestamp": + "[% accountline.timestamp | $KohaDates with_hours => 1 %]" } + [%- PROCESS account_type_description account=credit.debit -%] + [%- IF credit.debit.description -%]([% credit.debit.description | html %])[%- END -%] + [%- IF ( credit.debit.itemnumber ) -%] + ([% credit.debit.item.biblio.title | html %]) + [%- END -%] + [% credit.debit.amount | $Price %] + [% IF CAN_user_cash_management_anonymous_refund && !(credit.debit.status == 'REFUNDED') && !(credit.debit.debit_type_code == 'PAYOUT') %] + + [% ELSIF CAN_user_updatecharges_refund && !(credit.debit.status == 'REFUNDED') && credit.debit.borrowernumber && !(credit.debit.debit_type_code == 'PAYOUT') %] + + [% END %] +
            [% accountline.accountlines_id | html %]{ "type": "debit", "identifier": "[%- accountline.credit_number | html -%]", "description": "[%- PROCESS account_type_description account=accountline -%] + ([% AuthorisedValues.GetByCode( 'PAYMENT_TYPE', accountline.payment_type ) | html %])", "amount": "[% accountline.amount * -1 | $Price %]", "timestamp": + "[% accountline.timestamp | $KohaDates with_hours => 1 %]" } + [%- PROCESS account_type_description account=debit.credit -%] + [%- IF debit.credit.description %][% debit.credit.description | html %][%- END -%] + [%- IF ( debit.credit.itemnumber ) -%] + ([% debit.credit.item.biblio.title | html %]) + [%- END -%] + [% debit.credit.amount | $Price %] + [%- IF debit.credit.credit_type_code == 'REFUND' -%] + Details + [%- END -%] +
            Total income: [% accountlines.total * -1 | $Price %]
            +
            + [% END %] + + [% IF register.cashups %] +

            Older transactions

            +
            +
            + Please select a date range to display transactions for: +
              +
            1. + + + + + [% INCLUDE 'date-format.inc' %] +
            2. +
            +
            + +
            + + +
            +
            + + [% IF trange_f %] +
            + + + + + + + + + + + + [% FOREACH accountline IN past_accountlines %] + [% IF accountline.is_credit %] + [% FOREACH credit IN accountline.credit_offsets %] + [% IF credit.debit %] + + + + + + + + + + [% END %] [% END %] [% ELSE %] [% FOREACH debit IN accountline.debit_offsets %] - [% IF debit.credit %] - - - - - - - - - - [% END %] + [% IF debit.credit %] + + + + + + + + + + [% END %] [% END %] [% END %] [% END %] @@ -158,188 +338,100 @@ - +
            IDDATATransactionDescriptionPriceTotalActions
            [% accountline.accountlines_id | html %]{ "type": "credit", "identifier": "[%- accountline.credit_number | html -%]", "description": "[%- PROCESS account_type_description account=accountline -%] + ([% AuthorisedValues.GetByCode( 'PAYMENT_TYPE', accountline.payment_type ) | html %])", "amount": "[% accountline.amount * -1 | $Price %]", "timestamp": + "[% accountline.timestamp | $KohaDates with_hours => 1 %]" } + [%- PROCESS account_type_description account=credit.debit -%] + [%- IF credit.debit.description -%]([% credit.debit.description | html %])[%- END -%] + [%- IF ( credit.debit.itemnumber ) -%] + ([% credit.debit.item.biblio.title | html %]) + [%- END -%] + [% credit.debit.amount | $Price %] + [% IF CAN_user_cash_management_anonymous_refund && !(credit.debit.status == 'REFUNDED') && !(credit.debit.debit_type_code == 'PAYOUT') %] + + [% ELSIF CAN_user_updatecharges_refund && !(credit.debit.status == 'REFUNDED') && credit.debit.borrowernumber && !(credit.debit.debit_type_code == 'PAYOUT') %] + + [% END %] +
            [% accountline.accountlines_id | html %]{ "type": "debit", "identifier": "[%- accountline.credit_number | html -%]", "description": "[%- PROCESS account_type_description account=accountline -%] ([% AuthorisedValues.GetByCode( 'PAYMENT_TYPE', accountline.payment_type ) | html %])", "amount": "[% accountline.amount * -1 | $Price %]", "timestamp": "[% accountline.timestamp | $KohaDates with_hours => 1 %]" } - [%- PROCESS account_type_description account=debit.credit -%] - [%- IF debit.credit.description %][% debit.credit.description | html %][%- END -%] - [%- IF ( debit.credit.itemnumber ) -%] ([% debit.credit.item.biblio.title | html %])[%- END -%] - [% debit.credit.amount | $Price %] - [%- IF debit.credit.credit_type_code == 'REFUND' -%] Details[%- END -%] -
            [% accountline.accountlines_id | html %]{ "type": "debit", "identifier": "[%- accountline.credit_number | html -%]", "description": "[%- PROCESS account_type_description account=accountline -%] + ([% AuthorisedValues.GetByCode( 'PAYMENT_TYPE', accountline.payment_type ) | html %])", "amount": "[% accountline.amount * -1 | $Price %]", "timestamp": + "[% accountline.timestamp | $KohaDates with_hours => 1 %]" } + [%- PROCESS account_type_description account=debit.credit -%] + [%- IF debit.credit.description %][% debit.credit.description | html %][%- END -%] + [%- IF ( debit.credit.itemnumber ) -%] + ([% debit.credit.item.biblio.title | html %]) + [%- END -%] + [% debit.credit.amount | $Price %] + [%- IF debit.credit.credit_type_code == 'REFUND' -%] + Details + [%- END -%] +
            Total income: [% accountlines.total * -1 | $Price %][% past_accountlines.total * -1 | $Price %]
            - [% END %] - - [% IF register.cashups %] -

            Older transactions

            -
            -
            - Please select a date range to display transactions for: -
              -
            1. - - - - - [% INCLUDE 'date-format.inc' %] -
            2. -
            -
            - -
            - - -
            -
            - - [% IF trange_f %] -
            - - - - - - - - - - - - [% FOREACH accountline IN past_accountlines %] - [% IF accountline.is_credit %] - [% FOREACH credit IN accountline.credit_offsets %] - [% IF credit.debit %] - - - - - - - - - - [% END %] - [% END %] - [% ELSE %] - [% FOREACH debit IN accountline.debit_offsets %] - [% IF debit.credit %] - - - - - - - - - - [% END %] - [% END %] - [% END %] - [% END %] - - - - - - - - -
            IDDATATransactionDescriptionPriceTotalActions
            [% accountline.accountlines_id | html %]{ "type": "credit", "identifier": "[%- accountline.credit_number | html -%]", "description": "[%- PROCESS account_type_description account=accountline -%] ([% AuthorisedValues.GetByCode( 'PAYMENT_TYPE', accountline.payment_type ) | html %])", "amount": "[% accountline.amount * -1 | $Price %]", "timestamp": "[% accountline.timestamp | $KohaDates with_hours => 1 %]" } - [%- PROCESS account_type_description account=credit.debit -%] - [%- IF credit.debit.description -%] ([% credit.debit.description | html %])[%- END -%] - [%- IF ( credit.debit.itemnumber ) -%] ([% credit.debit.item.biblio.title | html %])[%- END -%] - [% credit.debit.amount | $Price %] - [% IF CAN_user_cash_management_anonymous_refund && !(credit.debit.status == 'REFUNDED') && !(credit.debit.debit_type_code == 'PAYOUT') %] - - [% ELSIF CAN_user_updatecharges_refund && !(credit.debit.status == 'REFUNDED') && credit.debit.borrowernumber && !(credit.debit.debit_type_code == 'PAYOUT') %] - - [% END %] -
            [% accountline.accountlines_id | html %]{ "type": "debit", "identifier": "[%- accountline.credit_number | html -%]", "description": "[%- PROCESS account_type_description account=accountline -%] ([% AuthorisedValues.GetByCode( 'PAYMENT_TYPE', accountline.payment_type ) | html %])", "amount": "[% accountline.amount * -1 | $Price %]", "timestamp": "[% accountline.timestamp | $KohaDates with_hours => 1 %]" } - [%- PROCESS account_type_description account=debit.credit -%] - [%- IF debit.credit.description %][% debit.credit.description | html %][%- END -%] - [%- IF ( debit.credit.itemnumber ) -%] ([% debit.credit.item.biblio.title | html %])[%- END -%] - [% debit.credit.amount | $Price %] - [%- IF debit.credit.credit_type_code == 'REFUND' -%] Details[%- END -%] -
            Total income: [% past_accountlines.total * -1 | $Price %]
            -
            - [% END %] - -
            -

            Cashup history

            -
            - - - - - - - - - -
            DateCashierAmountActions
            -
            - [% END %] + + [% END %] +
            +

            Cashup history

            +
            + + + + + + + + + +
            DateCashierAmountActions
            +
            + [% END %] [% END %] - - +
          + + + + + + + + + - - +[% INCLUDE 'modals/cashup_summary.inc' %] - [% INCLUDE 'modals/cashup_summary.inc' %] - - [% MACRO jsinclude BLOCK %] +[% MACRO jsinclude BLOCK %] [% INCLUDE 'datatables.inc' %] [% INCLUDE 'format_price.inc' %] [% INCLUDE 'js-date-format.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/pos/registers.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/pos/registers.tt index 9cac64cd6b..79eebe1dec 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/pos/registers.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/pos/registers.tt @@ -6,213 +6,232 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% tx("Cash summary for {library}", { library = library.branchname }) | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% tx("Cash summary for {library}", { library = library.branchname }) | html %] + › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] - [% WRAPPER 'header.inc' %] +[% WRAPPER 'header.inc' %] [% INCLUDE 'circ-search.inc' %] [% END %] - [% WRAPPER 'sub-header.inc' %] - [% WRAPPER breadcrumbs %] - [% WRAPPER breadcrumb_item bc_active= 1 %] - Cash summary for [% library.branchname | html %] +[% WRAPPER 'sub-header.inc' %] + [% WRAPPER breadcrumbs %] + [% WRAPPER breadcrumb_item bc_active= 1 %] + Cash summary for [% library.branchname | html %] + [% END %] + [% END #/ WRAPPER breadcrumbs %] +[% END #/ WRAPPER sub-header.inc %] + +[% WRAPPER 'main-container.inc' aside='pos-menu' %] + [% IF ( error_registers ) %] +
          +

          You must have at least one cash register associated with the library before you can record payments.

          + [% IF ( CAN_user_parameters_manage_cash_registers ) %] +
          + + +
          [% END %] - [% END #/ WRAPPER breadcrumbs %] - [% END #/ WRAPPER sub-header.inc %] +
          + [% ELSE %] - [% WRAPPER 'main-container.inc' aside='pos-menu' %] - [% IF ( error_registers ) %] -
          -

          - You must have at least one cash register associated with the library before you can record payments. -

          - [% IF ( CAN_user_parameters_manage_cash_registers ) %] -
          - - -
          + [% IF ( error_cashup_permission ) %] +
          You do not have permission to perform cashup actions.
          + [% END %] + + [% IF CAN_user_cash_management_cashup %] +
          + +
          + [% END %] + +

          Cash summary for [% library.branchname | html %]

          + +

          Summary

          +
            +
          • Total income (cash):
          • +
          • Total outgoing (cash):
          • +
          • Total bankable:
          • +
          + +
          + + + + + + + + + + + [% IF CAN_user_cash_management_cashup %] + + [% END %] + + + + [% SET bankable = 0, ctotal = 0, dtotal = 0, cctotal = 0, cdtotal = 0 %] + [% FOREACH register IN registers %] + + + + + + + + + [% IF CAN_user_cash_management_cashup %] + [% END %] - - [% ELSE %] - - [% IF ( error_cashup_permission ) %] -
          - You do not have permission to perform cashup actions. -
          + [% END %] + + + + + + + + [% IF CAN_user_cash_management_cashup %] + + [% END %] + + +
          Register nameRegister descriptionLast cashupFloatBankableIncome (cash)Outgoing (cash)Actions
          [% register.name | html %][% register.description | html %] + [%- IF register.last_cashup -%] + [% register.last_cashup.timestamp | $KohaDates with_hours => 1 %] + (Summary) + [%- ELSE -%] + No last cashup + [%- END -%] + [% register.starting_float | $Price %] + [% SET rbankable = ( register.outstanding_accountlines.total( payment_type => [ 'CASH', 'SIP00' ]) * -1 ) %] + [% SET bankable = bankable + rbankable %] + [% rbankable | $Price %] + + [% SET rctotal = ( register.outstanding_accountlines.credits_total * -1 ) %] + [% SET rcctotal = ( register.outstanding_accountlines.credits_total( payment_type => [ 'CASH', 'SIP00' ]) * -1 ) %] + [% rctotal | $Price %] + ([% rcctotal | $Price %]) [% SET ctotal = ctotal + rctotal %] + [% SET cctotal = cctotal + rcctotal %] + + [% SET rdtotal = ( register.outstanding_accountlines.debits_total * -1 ) %] + [% SET rcdtotal = ( register.outstanding_accountlines.debits_total( payment_type => [ 'CASH', 'SIP00' ]) * -1 ) %] + [% rdtotal | $Price %] + ([% rcdtotal | $Price %]) [% SET dtotal = dtotal + rdtotal %] + [% SET cdtotal = cdtotal + rcdtotal %] + + +
          Totals:[% bankable | $Price %][% ctotal | $Price %] ([% cctotal | $Price %])[% dtotal | $Price %] ([% cdtotal | $Price %]) + +
          +
          + + [% END %] +[% END %] - [% IF CAN_user_cash_management_cashup %] -
          - -
          - [% END %] + + + -

          Cash summary for [% library.branchname | html %]

          + + + -

          Summary

          -
            -
          • Total income (cash):
          • -
          • Total outgoing (cash):
          • -
          • Total bankable:
          • -
          +[% INCLUDE 'modals/cashup_summary.inc' %] -
          - - - - - - - - - - - [% IF CAN_user_cash_management_cashup %] - - [% END %] - - - - [% SET bankable = 0, ctotal = 0, dtotal = 0, cctotal = 0, cdtotal = 0 %] - [% FOREACH register IN registers %] - - - - - - - - - [% IF CAN_user_cash_management_cashup %] - - [% END %] - - [% END %] - - - - - - - - [% IF CAN_user_cash_management_cashup %] - - [% END %] - - -
          Register nameRegister descriptionLast cashupFloatBankableIncome (cash)Outgoing (cash)Actions
          [% register.name | html %][% register.description | html %] - [%- IF register.last_cashup -%] - [% register.last_cashup.timestamp | $KohaDates with_hours => 1 %] (Summary) - [%- ELSE -%] - No last cashup - [%- END -%] - [% register.starting_float | $Price %] - [% SET rbankable = ( register.outstanding_accountlines.total( payment_type => [ 'CASH', 'SIP00' ]) * -1 ) %] - [% SET bankable = bankable + rbankable %] - [% rbankable | $Price %] - - [% SET rctotal = ( register.outstanding_accountlines.credits_total * -1 ) %] - [% SET rcctotal = ( register.outstanding_accountlines.credits_total( payment_type => [ 'CASH', 'SIP00' ]) * -1 ) %] - [% rctotal | $Price %] ([% rcctotal | $Price %]) - [% SET ctotal = ctotal + rctotal %] - [% SET cctotal = cctotal + rcctotal %] - - [% SET rdtotal = ( register.outstanding_accountlines.debits_total * -1 ) %] - [% SET rcdtotal = ( register.outstanding_accountlines.debits_total( payment_type => [ 'CASH', 'SIP00' ]) * -1 ) %] - [% rdtotal | $Price %] ([% rcdtotal | $Price %]) - [% SET dtotal = dtotal + rdtotal %] - [% SET cdtotal = cdtotal + rcdtotal %] - - -
          Totals:[% bankable | $Price %][% ctotal | $Price %] ([% cctotal | $Price %])[% dtotal | $Price %] ([% cdtotal | $Price %]) - -
          -
          - [% END %] +[% MACRO jsinclude BLOCK %] + [% INCLUDE 'datatables.inc' %] + [% INCLUDE 'format_price.inc' %] + [% INCLUDE 'js-date-format.inc' %] + [% Asset.js("js/cashup_modal.js") | $raw %] + [% Asset.js("js/modal_printer.js") | $raw %] + - [% END %] + }); + +[% END %] [% INCLUDE 'intranet-bottom.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/preservation/home.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/preservation/home.tt index 14771f064e..072aa730b9 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/preservation/home.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/preservation/home.tt @@ -8,9 +8,7 @@ [% SET footerjs = 1 %] [% PROCESS 'i18n.inc' %] [% INCLUDE 'doc-head-open.inc' %] - - Preservation › Koha - + Preservation › Koha [% INCLUDE 'doc-head-close.inc' %] @@ -19,28 +17,25 @@ [% INCLUDE 'preservation-search.inc' %] [% END %] -
          +
          + -[% MACRO jsinclude BLOCK %] - [% INCLUDE 'calendar.inc' %] - [% INCLUDE 'datatables.inc' %] - [% INCLUDE 'columns_settings.inc' %] - [% INCLUDE 'js-patron-format.inc' %] - [% INCLUDE 'js-date-format.inc' %] - [% INCLUDE 'js-biblio-format.inc' %] + [% MACRO jsinclude BLOCK %] + [% INCLUDE 'calendar.inc' %] + [% INCLUDE 'datatables.inc' %] + [% INCLUDE 'columns_settings.inc' %] + [% INCLUDE 'js-patron-format.inc' %] + [% INCLUDE 'js-date-format.inc' %] + [% INCLUDE 'js-biblio-format.inc' %] + - - [% Asset.js("js/vue/dist/preservation.js") | $raw %] - -[% END %] -[% INCLUDE 'intranet-bottom.inc' %] + const csrf_token = "[% Koha.GenerateCSRF | $raw %]"; + + [% Asset.js("js/vue/dist/preservation.js") | $raw %] + [% END %] + [% INCLUDE 'intranet-bottom.inc' %] +
          diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/recalls/recalls_old_queue.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/recalls/recalls_old_queue.tt index 21ea5f58e3..b381db6d85 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/recalls/recalls_old_queue.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/recalls/recalls_old_queue.tt @@ -5,11 +5,12 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Old recalls") | html %] › - [% t("Circulation") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Old recalls") | html %] + › [% t("Circulation") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -30,14 +31,13 @@ [% SET aside = Koha.Preference('CircSidebar') ? 'circ-nav' : '' %] [% WRAPPER 'main-container.inc' aside=aside %] -

          Old recalls

          - [% IF Koha.Preference('UseRecalls') %] -
          - [% INCLUDE 'recalls.inc' %] -
          - [% ELSE %] -
          Recalls have not been enabled. Enable the UseRecalls system preference to use recalls.
          - [% END %] +

          Old recalls

          + [% IF Koha.Preference('UseRecalls') %] +
          [% INCLUDE 'recalls.inc' %]
          + + [% ELSE %] +
          Recalls have not been enabled. Enable the UseRecalls system preference to use recalls.
          + [% END %] [% END %] [% MACRO jsinclude BLOCK %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/recalls/recalls_overdue.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/recalls/recalls_overdue.tt index efd55850aa..ed4eec6f48 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/recalls/recalls_overdue.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/recalls/recalls_overdue.tt @@ -5,11 +5,12 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Overdue recalls") | html %] › - [% t("Circulation") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Overdue recalls") | html %] + › [% t("Circulation") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -30,26 +31,27 @@ [% SET aside = Koha.Preference('CircSidebar') ? 'circ-nav' : '' %] [% WRAPPER 'main-container.inc' aside=aside %] -

          Overdue recalls

          - [% IF Koha.Preference('UseRecalls') %] - [% IF recalls.count %] -
          -
          - [% INCLUDE 'csrf-token.inc' %] - - Select all - [% INCLUDE 'recalls.inc' %] -
          - -
          -
          -
          - [% ELSE %] -
          There are no recalls to show.
          - [% END %] +

          Overdue recalls

          + [% IF Koha.Preference('UseRecalls') %] + [% IF recalls.count %] +
          +
          + [% INCLUDE 'csrf-token.inc' %] + + Select all + [% INCLUDE 'recalls.inc' %] +
          + +
          +
          +
          + [% ELSE %] -
          Recalls have not been enabled. Enable the UseRecalls system preference to use recalls.
          +
          There are no recalls to show.
          [% END %] + [% ELSE %] +
          Recalls have not been enabled. Enable the UseRecalls system preference to use recalls.
          + [% END %] [% END %] [% MACRO jsinclude BLOCK %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/recalls/recalls_queue.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/recalls/recalls_queue.tt index 064ef30c02..911df1abc8 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/recalls/recalls_queue.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/recalls/recalls_queue.tt @@ -5,11 +5,12 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Recalls queue") | html %] › - [% t("Circulation") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Recalls queue") | html %] + › [% t("Circulation") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -30,27 +31,27 @@ [% SET aside = Koha.Preference('CircSidebar') ? 'circ-nav' : '' %] [% WRAPPER 'main-container.inc' aside=aside %] - -

          Recalls queue

          - [% IF Koha.Preference('UseRecalls') %] - [% IF recalls.count %] -
          -
          - [% INCLUDE 'csrf-token.inc' %] - - Select all - [% INCLUDE 'recalls.inc' %] -
          - -
          -
          -
          - [% ELSE %] -
          There are no recalls to show.
          - [% END %] +

          Recalls queue

          + [% IF Koha.Preference('UseRecalls') %] + [% IF recalls.count %] +
          +
          + [% INCLUDE 'csrf-token.inc' %] + + Select all + [% INCLUDE 'recalls.inc' %] +
          + +
          +
          +
          + [% ELSE %] -
          Recalls have not been enabled. Enable the UseRecalls system preference to use recalls.
          +
          There are no recalls to show.
          [% END %] + [% ELSE %] +
          Recalls have not been enabled. Enable the UseRecalls system preference to use recalls.
          + [% END %] [% END %] [% MACRO jsinclude BLOCK %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/recalls/recalls_to_pull.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/recalls/recalls_to_pull.tt index 94a0b8ab18..5df3b0cd83 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/recalls/recalls_to_pull.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/recalls/recalls_to_pull.tt @@ -8,11 +8,12 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Recalls to pull") | html %] › - [% t("Circulation") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Recalls to pull") | html %] + › [% t("Circulation") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -33,43 +34,45 @@ [% SET aside = Koha.Preference('CircSidebar') ? 'circ-nav' : '' %] [% WRAPPER 'main-container.inc' aside=aside %] - -

          Recalls to pull

          - The following recalls could be fulfilled by available items. - - [% IF Koha.Preference('UseRecalls') %] - [% IF recalls %] -
          - - - - - - - - - - - - - - - - - - - - [% FOREACH recall IN recalls %] +

          Recalls to pull

          + The following recalls could be fulfilled by available items. + [% IF Koha.Preference('UseRecalls') %] + [% IF recalls %] +
          +
          Pull this many itemsItems availablePatrons with recallsFirst patronTitleLibrariesAvailable call numbersAvailable copy numbersAvailable enumerationAvailable item typesAvailable locationsEarliest recall date 
          + + + + + + + + + + + + + + + + + + + [% FOREACH recall IN recalls %] - + - [% END %] - -
          Pull this many itemsItems availablePatrons with recallsFirst patronTitleLibrariesAvailable call numbersAvailable copy numbersAvailable enumerationAvailable item typesAvailable locationsEarliest recall date 
          [% recall.pull_count | html %] [% recall.items_count | html %] [% recall.patrons_count | html %][% recall.first_recall.patron.firstname | html %] [% recall.first_recall.patron.surname | html %][% recall.first_recall.patron.firstname | html %] [% recall.first_recall.patron.surname | html %] [% INCLUDE 'biblio-title.inc' biblio=recall.first_recall.biblio link=1 %] - [% IF recall.biblio.author %] by [% recall.biblio.author | html %][% END %] + [% IF recall.biblio.author %]by [% recall.biblio.author | html %][% END %] [% recall.item.enumchron | html %] - [% IF ( recall.item ) %]
          Barcode: [% recall.item.barcode | html %][% END %] + [% IF ( recall.item ) %]
          Barcode: [% recall.item.barcode | html %][% END %]
            @@ -119,48 +122,52 @@
          [% INCLUDE 'csrf-token.inc' %] - - + + [% IF recall.first_recall.in_transit %] - + [% ELSE %] [% END %]
          -
          - [% ELSE %] -
          There are no recalls to pull.
          - [% END %] + [% END %] + + +
          + [% ELSE %] -
          Recalls have not been enabled. Enable the UseRecalls system preference to use recalls.
          +
          There are no recalls to pull.
          [% END %] - + [% ELSE %] +
          Recalls have not been enabled. Enable the UseRecalls system preference to use recalls.
          + [% END %] [% END %] [% MACRO jsinclude BLOCK %] [% INCLUDE 'datatables.inc' %] [% INCLUDE 'columns_settings.inc' %] [% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/reports/orders_by_budget.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/reports/orders_by_budget.tt index 8136845c93..03182f666f 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/reports/orders_by_budget.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/reports/orders_by_budget.tt @@ -7,11 +7,12 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Orders by fund") | html %] › - [% t("Reports") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Orders by fund") | html %] + › [% t("Reports") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -41,118 +42,128 @@ [% WRAPPER 'main-container.inc' aside='reports-menu' %] -[% IF ( current_budget_name ) %]

          Orders for fund '[% current_budget_name | html %]'

          -[% ELSE %]

          Orders by fund

          -[% END %] + [% IF ( current_budget_name ) %] +

          Orders for fund '[% current_budget_name | html %]'

          + [% ELSE %] +

          Orders by fund

          + [% END %] -[% IF ( get_orders ) %] - [% IF ( ordersloop ) %] -
          - - - - - - - - - - - - - - - - - - - - - - - [% FOREACH ordersloo IN ordersloop %] - - - - - - - - - - - - - - - - - - - [% END %] - - + [% IF ( get_orders ) %] + [% IF ( ordersloop ) %] +
          +
          FundBasketBasket nameBasket byTitleCurrencyList priceRRPBudgeted costQuantityTotal RRPTotal costEntry dateDate receivedInternal noteVendor note
          [% ordersloo.budget_name | html %] [% ordersloo.basketno | html %][% ordersloo.basketname | html %][% ordersloo.authorisedbyname | html %] [% ordersloo.title | html %][% ordersloo.currency | html %][% ordersloo.listprice | $Price %][% ordersloo.rrp | $Price %][% ordersloo.ecost | $Price %][% ordersloo.quantity | html %][% ordersloo.total_rrp | $Price %][% ordersloo.total_ecost | $Price %][% ordersloo.entrydate | $KohaDates %][% ordersloo.datereceived | $KohaDates %][% ordersloo.order_internalnote | html %][% ordersloo.order_vendornote | html %]
          TOTAL[% total_quantity | html %][% total_rrp | $Price %][% total_ecost | $Price %]
          + + + + + + + + + + + + + + + + + + + + + + [% FOREACH ordersloo IN ordersloop %] + + + + + + + + + + + + + + + + + + + [% END %] + +
          FundBasketBasket nameBasket byTitleCurrencyList priceRRPBudgeted costQuantityTotal RRPTotal costEntry dateDate receivedInternal noteVendor note
          [% ordersloo.budget_name | html %] [% ordersloo.basketno | html %][% ordersloo.basketname | html %][% ordersloo.authorisedbyname | html %] [% ordersloo.title | html %][% ordersloo.currency | html %][% ordersloo.listprice | $Price %][% ordersloo.rrp | $Price %][% ordersloo.ecost | $Price %][% ordersloo.quantity | html %][% ordersloo.total_rrp | $Price %][% ordersloo.total_ecost | $Price %][% ordersloo.entrydate | $KohaDates %][% ordersloo.datereceived | $KohaDates %][% ordersloo.order_internalnote | html %][% ordersloo.order_vendornote | html %]
          TOTAL[% total_quantity | html %][% total_rrp | $Price %][% total_ecost | $Price %]
          - [% END %] -[% ELSE %] -
          -
          - Filters -
          1. - - - -
          -
          + [% ELSE %] + +
          + Filters +
          1. + + +
          +
          -
          - Output -
          1. -
          2. - - - - - - -
          -
          +
          + Output +
          1. +
          2. + + + + + + +
          +
          -
          - -
          +
          + +
          - -[% END %] - + [% END %] [% END %] [% MACRO jsinclude BLOCK %] @@ -177,7 +188,6 @@ }); } ); - [% END %] [% INCLUDE 'intranet-bottom.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/reports/reports-home.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/reports/reports-home.tt index f841b53dc8..2d8517da1c 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/reports/reports-home.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/reports/reports-home.tt @@ -2,10 +2,12 @@ [% USE Koha %] [% PROCESS 'i18n.inc' %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Reports") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Reports") | html %] + › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -28,109 +30,106 @@

          Reports

          - [% IF ( CAN_user_reports_execute_reports || CAN_user_reports_create_reports ) %] -
          -

          Guided reports

          - [% IF ( CAN_user_reports_create_reports ) %] -

          - Create guided report -

          -

          - Create from SQL -

          - [% END %] +
          +

          Guided reports

          + [% IF ( CAN_user_reports_create_reports ) %]

          - Use saved + Create guided report

          -
          - - - - - -
          -
          +

          + Create from SQL +

          + [% END %] +

          + Use saved +

          +
          + + + + + +
          +
          [% END %] -
          -

          Reports dictionary

          - -
          +
          +

          Reports dictionary

          + +
          -
          -

          Statistics wizards

          - -
          +
          +

          Statistics wizards

          + +
          - [% IF plugins_enabled %] -
          -

          Report plugins

          - -
          - [% END %] - -
          - -
          - - - - -
          -

          Other

          - -
          - [% IF ( Koha.Preference('Mana') == 2 ) %] -
          - Knowledgebase -

          You haven't decided if you want to activate Mana Knowledge Base. Change your Mana KB settings.

          -
          - [% END %] + [% IF plugins_enabled %] +
          +

          Report plugins

          + +
          + [% END %]
          -
          + +
          + + + + +
          +

          Other

          + +
          + [% IF ( Koha.Preference('Mana') == 2 ) %] +
          + Knowledgebase +

          You haven't decided if you want to activate Mana Knowledge Base. Change your Mana KB settings.

          +
          + [% END %] +
          +
          +
          -
          - [% Koha.Preference('IntranetReportsHomeHTML') | $raw %] -
          +
          [% Koha.Preference('IntranetReportsHomeHTML') | $raw %]
          [% INCLUDE 'intranet-bottom.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/reports/reserves_stats.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/reports/reserves_stats.tt index bacfb19e0c..b6bd70130f 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/reports/reserves_stats.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/reports/reserves_stats.tt @@ -4,28 +4,36 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% IF ( do_it ) %] - [% t("Results") | html %] › - [% END %] - [% t("Holds statistics") | html %] › - [% t("Reports") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% IF ( do_it ) %] + [% t("Results") | html %] + › + [% END %] + [% t("Holds statistics") | html %] + › [% t("Reports") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] [% BLOCK reservestatus %] [% IF field == 'reservestatus' %] - [% SWITCH value %] - [% CASE 'C'%]Cancelled - [% CASE 'F'%]Filled - [% CASE 'P'%]Placed - [% CASE 'W'%]Waiting - [% END %] + [% SWITCH value %] + [% CASE 'C' %] + Cancelled + [% CASE 'F' %] + Filled + [% CASE 'P' %] + Placed + [% CASE 'W' %] + Waiting + [% END %] [% ELSE %] [% value | html %] [% END %] @@ -57,309 +65,340 @@ [% END #/ WRAPPER sub-header.inc %] [% WRAPPER 'main-container.inc' aside='reports-menu' %] +

          Holds statistics

          + [% IF ( do_it ) %] + [% IF ( mainloop ) %] + [% IF ( loopfilter ) %] +

          Filtered on:

          +
            + [% FOREACH loopfilte IN loopfilter %] + [% SET li_class = '' %] + [% IF ( loopfilte.err ) %] + [% li_class = 'error' %] + [% ELSIF ( loopfilte.sql ) %] + [% li_class = 'sql' %] + [% END %] +
          • + [% IF loopfilte.err %] + Error: + [% END %] -

            Holds statistics

            -[% IF ( do_it ) %] - [% IF ( mainloop ) %] - [% IF ( loopfilter ) %] -

            Filtered on:

            -
              - [% FOREACH loopfilte IN loopfilter %] - [% SET li_class = '' %] - [% IF ( loopfilte.err ) %] - [% li_class = 'error' %] - [% ELSIF ( loopfilte.sql ) %] - [% li_class = 'sql' %] - [% END %] -
            • - [% IF loopfilte.err %] - Error: - [% END %] - - [% loopfilte.crit | html %] [% loopfilte.filter | html %] -
            • - [% END %] -
            - [% END %] - - [% FOREACH mainloo IN mainloop %] - - - - - [% FOREACH loopco IN mainloo.loopcol %] - - [% END %] - - - [% FOREACH loopro IN mainloo.looprow %] - - - [% FOREACH loopcel IN loopro.loopcell %] - + [% loopfilte.crit | html %] + [% loopfilte.filter | html %] + [% END %] - + + [% END %] + + [% FOREACH mainloo IN mainloop %] +
            [% mainloo.line | html %] / [% mainloo.column | html %][% PROCESS reservestatus field=mainloo.column value=loopco.coltitle_display %]TOTAL
            [% PROCESS reservestatus field=mainloo.line value=loopro.rowtitle_display %] - [% IF ( loopcel.url_complement ) %][% loopcel.value | html %][% ELSE %][% loopcel.value | html %][% END %] - [% loopro.totalrow | html %]
            + + + [% FOREACH loopco IN mainloo.loopcol %] + + [% END %] + - [% END %] - - - [% FOREACH loopfoote IN mainloo.loopfooter %] - - [% END %] - - -
            [% mainloo.line | html %] / [% mainloo.column | html %][% PROCESS reservestatus field=mainloo.column value=loopco.coltitle_display %]TOTAL
            TOTAL[% loopfoote.totalcol | html %][% mainloo.total | html %]
            - [% END %] - [% END %] -[% ELSE %] - -
            -
            - Holds statistics - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - [% IF ( hassort1 ) %] - - - - - - [% END %] - [% IF ( hassort2 ) %] - - - - - - [% END %] - -
            TitleRowColumnFilter
            Hold status - Cancelled - Filled - Placed - Waiting -
            Hold date - - - - - -
            Notification date - - - - - -
            Reminder date - - - - - -
            Waiting date - - - - - -
            Cancellation date - - - - - -
            Patron category -
            Item type -
            Pickup library -
            Holding library -
            Home library -
            Collection -
            Shelving location -
            Item call numberFrom (inclusive) to (exclusive)
            Patron sort 1 -
            Patron sort 2 -

            - -
            Cell value
            1. -
            - -
            - Output -
              -
            1. - -
            2. -
            3. - - - - - -
            4. -
            -
            + [% END %] + [% ELSE %] + +
            + Holds statistics + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + [% IF ( hassort1 ) %] + + + + + + [% END %] + [% IF ( hassort2 ) %] + + + + + + [% END %] +
            TitleRowColumnFilter
            Hold status + Cancelled Filled + Placed Waiting +
            Hold date + + -
            - - - -
            - -[% END %] + + +
            Notification date + + + + +
            Reminder date + + + + + +
            Waiting date + + + + + +
            Cancellation date + + + + + +
            Patron category +
            Item type +
            Pickup library +
            Holding library +
            Home library +
            Collection +
            Shelving location +
            Item call numberFrom (inclusive) to (exclusive)
            Patron sort 1 +
            Patron sort 2 +

            + +
            Cell value
            1. +
            + +
            + Output +
              +
            1. +
            2. + + + + +
            3. +
            +
            + +
            + + + +
            + + [% END %] [% END %] [% MACRO jsinclude BLOCK %] [% INCLUDE 'calendar.inc' %] - [% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/reports/serials_stats.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/reports/serials_stats.tt index d7b0b7212d..682d7bb321 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/reports/serials_stats.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/reports/serials_stats.tt @@ -6,14 +6,17 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Serials subscriptions stats") | html %] › - [% t("Reports") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Serials subscriptions stats") | html %] + › [% t("Reports") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -43,123 +46,112 @@ [% END #/ WRAPPER sub-header.inc %] [% WRAPPER 'main-container.inc' aside='reports-menu' %] - -

            Serials subscriptions

            -[% IF ( do_it ) %] - - - - - - - - - - - - - - - [% FOREACH data IN datas %] +

            Serials subscriptions

            + [% IF ( do_it ) %] +
            VendorTitleSubscription IDLibraryCall numberSubscription beginSubscription endExpired? / Closed?
            + - - - - - - - - + + + + + + + + - [% END %] - -
            [% data.name | html %][% data.title | html %][% data.subscriptionid | html %][% Branches.GetName( data.branchcode ) | html %][% data.callnumber | html %][% data.startdate | $KohaDates %][% data.enddate | $KohaDates %] - [% IF data.closed %] - Closed - [% ELSIF data.expired %] - Expired - [% END %] - VendorTitleSubscription IDLibraryCall numberSubscription beginSubscription endExpired? / Closed?
            + + + [% FOREACH data IN datas %] + + [% data.name | html %] + [% data.title | html %] + [% data.subscriptionid | html %] + [% Branches.GetName( data.branchcode ) | html %] + [% data.callnumber | html %] + [% data.startdate | $KohaDates %] + [% data.enddate | $KohaDates %] + + [% IF data.closed %] + Closed + [% ELSIF data.expired %] + Expired + [% END %] + + + [% END %] + + + [% ELSE %] +
            +
            +
              +
            1. + +
            2. + + +
            3. +
            4. + + +
            5. +
            +
            -[% ELSE %] - - -
            -
              -
            1. - - - -
            2. - - - -
            3. -
            4. - - -
            5. -
            -
            - - -
            - Output -
              -
            1. - -
            2. -
            3. - - - - - -
            4. -
            -
            - -
            - - - -
            -
            -[% END %] +
            + Output +
              +
            1. +
            2. + + + + +
            3. +
            +
            +
            + + + +
            + + [% END %] [% END %] [% MACRO jsinclude BLOCK %] -[% INCLUDE 'datatables.inc' %] + [% INCLUDE 'datatables.inc' %] [% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/reserve/request.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/reserve/request.tt index 1644c55061..4b74435b50 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/reserve/request.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/reserve/request.tt @@ -22,23 +22,26 @@ [% SET categories = Categories.all.unblessed %] [% SET columns = ['name', 'cardnumber', 'dateofbirth', 'category', 'branch', 'address', 'phone'] %] [% PROCESS "patron-search.inc" %] -[% FILTER collapse %] - [% UNLESS ( multi_hold ) %] - [% title_in_title = INCLUDE 'biblio-title-head.inc' %] - [% tx("Place a hold on {title}", { title = title_in_title }) | html %] › - [% ELSE %] - [% t("Confirm holds") | html %] › - [% END %] - [% t("Holds") | html %] › - [% t("Circulation") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% UNLESS ( multi_hold ) %] + [% title_in_title = INCLUDE 'biblio-title-head.inc' %] + [% tx("Place a hold on {title}", { title = title_in_title }) | html %] + › + [% ELSE %] + [% t("Confirm holds") | html %] + › + [% END %] + [% t("Holds") | html %] + › [% t("Circulation") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] [% FILTER collapse %] [% END %] @@ -147,33 +150,33 @@ [%# No sidebar menu when placing multiple holds or biblio not found %] [% SET aside = (multi_hold || nobiblio) ? '' : 'biblio-view-menu' %] [% WRAPPER 'main-container.inc' aside=aside wide_centered=1 %] -

            Holds

            +

            Holds

            - [% IF ( nobiblio ) %] -
            - [%IF (multi_hold) %] - Cannot place hold: one or more records don't exist. - [% ELSE %] - Cannot place hold: this record doesn't exist. - [% END %] -
            + [% IF ( nobiblio ) %] +
            + [% IF (multi_hold) %] + Cannot place hold: one or more records don't exist. + [% ELSE %] + Cannot place hold: this record doesn't exist. [% END %] - [% IF ( noitems ) %] -
            - [%IF (multi_hold) %] - Cannot place hold: one or more records without items attached. - [% ELSE %] - Cannot place hold: this record has no items attached. - [% END %] -
            +
            + [% END %] + [% IF ( noitems ) %] +
            + [% IF (multi_hold) %] + Cannot place hold: one or more records without items attached. + [% ELSE %] + Cannot place hold: this record has no items attached. [% END %] +
            + [% END %] - [% IF ( failed_holds ) %] -
            - One or more holds were not placed due to following errors: -
              - [% FOREACH fail IN failed_holds %] -
            • + [% IF ( failed_holds ) %] +
              + One or more holds were not placed due to following errors: +
                + [% FOREACH fail IN failed_holds %] +
              • [% SWITCH fail %] [% CASE 'damaged' %] Item is damaged @@ -212,351 +215,436 @@ [% CASE %] Error: [% fail | html %] [% END %] +
              • + [% END %] +
              +
              + [% END %] + + [% UNLESS ( multi_hold ) %] +

              Place a hold on [% INCLUDE 'biblio-title.inc' link = 1 %] [% IF biblio.author %]by [% biblio.author | html %][% END %]

              + [% ELSE %] +

              + [% IF ( patron ) %] + Place holds + [% ELSE %] + [% IF clubcount %] + Search patrons or clubs + [% ELSE %] + Search patrons + [% END %] + [% END %] +

              + [% END %] + + [% UNLESS club OR patron OR patron.borrowernumber OR noitems OR nobiblio %] + [% IF ( messageborrower ) %] +
              +

              Patron not found

              +

              No patron with this name, please, try another

              +
              + [% END %] + + [% IF ( messageclub ) %] +
              +

              Club not found

              +

              No club with this name, please, try another

              +
              + [% END %] +
              + [% UNLESS multi_hold %] + [% IF clubcount %] +

              Search patrons or clubs

              + [% ELSE %] +

              Search patrons

              + [% END %] + [% END %] + + [% WRAPPER tabs id= "circ_holds_select" %] + [% WRAPPER tabs_nav %] + [% WRAPPER tab_item tabname= "holds_patronsearch_pane" bt_active= 1 %]Patrons[% END %] + [% IF clubcount %] + [% WRAPPER tab_item tabname= "holds_clubsearch_pane" %]Clubs[% END %] + [% END %] + [% END # /WRAPPER tabs_nav %] + + [% WRAPPER tab_panels %] + [% WRAPPER tab_panel tabname="holds_patronsearch_pane" bt_active= 1 %] + [% PROCESS patron_search_filters_simple %] + + [% PROCESS patron_search_table table_id => 'table_borrowers', open_on_row_click => 1 %] + [% END # /tab_panel# %] + [% IF clubcount %] + [% WRAPPER tab_panel tabname="holds_clubsearch_pane" %] +
              +
              Enter club ID or partial name:
              + + + + [% FOREACH biblionumber IN biblionumbers %] + + [% END %] +
              + + [% IF clubs %] + [% INCLUDE 'clubs-table.inc' destination = "holds" %] + [% END %] + [% END # /tab_panel# %] + [% END # /IF clubcount %] + [% END # /WRAPPER tab_panels %] + [% END # /WRAPPER tabs %] +
              + [% ELSIF club %] +
              +
              + Hold details +
              + [% INCLUDE 'csrf-token.inc' %] + + + [% IF ( multi_hold ) %] + + [% FOREACH biblioloo IN biblioloop %] + [% UNLESS biblioloo.none_avail %] + + + + [% END %] + [% END %] + [% ELSE %] + + + + [% END # /IF multi_hold %] +
                +
              1. Club: [% club.name | html %]
              2. +
              3. Description: [% club.description | html %]
              4. +
              5. + + +
              6. +
              7. + + +
              8. +
              +

              Members

              +
                + [% FOREACH member IN members %] + [% SET patron = member.patron %] +
              1. +
                [% INCLUDE 'patron-title.inc' patron => patron no_title => 1 no_cardnumber => 1 hide_patron_infos_if_needed => 1 %]
                + [% IF member.exceeded_maxreserves %] +
                + + Too many holds: Patron can only place a maximum of [% maxreserves | html %] total holds. +
                + [% END %] + [% IF ( patron.is_expired ) %] +
                + + Account has expired +
                + [% END %] + [% IF patron.is_debarred %] +
                + + Patron has restrictions +
                + [% END %] + [% IF member.amount_outstanding && Koha.Preference('maxoutstanding') && member.amount_outstanding > Koha.Preference('maxoutstanding') %] +
                + + Patron has outstanding fines: [% member.amount_outstanding | $Price %] +
                + [% END %] + + [% IF ( member.diffbranch ) %] +
                + + Pickup library is different. Patron's home library: ([% Branches.GetName(patron.branchcode) | html %] / [% patron.branchcode | html %] ) +
                + [% END %]
              2. [% END %] -
            -
            - [% END %] - - [% UNLESS ( multi_hold ) %] -

            Place a hold on [% INCLUDE 'biblio-title.inc' link = 1 %] [% IF biblio.author %] by [% biblio.author | html %][% END %]

            - [% ELSE %] -

            - [% IF ( patron ) %] - Place holds - [% ELSE %] - [% IF clubcount %] - Search patrons or clubs - [% ELSE %] - Search patrons - [% END %] - [% END %] -

            - [% END %] - - [% UNLESS club OR patron OR patron.borrowernumber OR noitems OR nobiblio %] - [% IF ( messageborrower ) %] -
            -

            Patron not found

            -

            No patron with this name, please, try another

            -
            - [% END %] - - [% IF ( messageclub ) %] -
            -

            Club not found

            -

            No club with this name, please, try another

            -
            - [% END %] -
            - [% UNLESS multi_hold %] - [% IF clubcount %] -

            Search patrons or clubs

            - [% ELSE %] -

            Search patrons

            - [% END %] - [% END %] - - [% WRAPPER tabs id= "circ_holds_select" %] - [% WRAPPER tabs_nav %] - [% WRAPPER tab_item tabname= "holds_patronsearch_pane" bt_active= 1 %] Patrons [% END %] - [% IF clubcount %] - [% WRAPPER tab_item tabname= "holds_clubsearch_pane" %] Clubs [% END %] + + [% UNLESS ( multi_hold ) %] +
            + +
            + [% ELSE %] + + + + + [% UNLESS Koha.Preference('item-level_itypes') %] + [% END %] - [% END # /WRAPPER tabs_nav %] - - [% WRAPPER tab_panels %] - [% WRAPPER tab_panel tabname="holds_patronsearch_pane" bt_active= 1 %] - [% PROCESS patron_search_filters_simple %] - - [% PROCESS patron_search_table table_id => 'table_borrowers', open_on_row_click => 1 %] - [% END # /tab_panel# %] - [% IF clubcount %] - [% WRAPPER tab_panel tabname="holds_clubsearch_pane" %] - -
            Enter club ID or partial name:
            - - - - [% FOREACH biblionumber IN biblionumbers %] - - [% END %] - - - [% IF clubs %] - [% INCLUDE 'clubs-table.inc' destination = "holds" %] + + + + [% FOREACH biblioloo IN biblioloop %] + + + + [% UNLESS Koha.Preference('item-level_itypes') %] + + [% END %] + + + + [% END # /FOREACH biblioloo %] +
             TitleItem type PriorityInformation
            + [% UNLESS ( biblioloo.warn ) %] + [% END %] - [% END # /tab_panel# %] - [% END # /IF clubcount %] - [% END # /WRAPPER tab_panels %] - [% END # /WRAPPER tabs %] - - [% ELSIF club %] -
            -
            +
            +
              +
            • + [% biblioloo.title | html %] + [% IF biblioloo.author %]by [% biblioloo.author | html %][% END %] +
            • + [% IF ( biblioloo.publicationyear ) %] +
            • Publication year: [% biblioloo.publicationyear | html %]
            • + [% END %] +
            + [% IF ( biblioloo.warn ) %] + + [% END %] +
            + [% biblioloo.itemtype.translated_description | html %] + [% biblioloo.rank | html %] + [% IF ( biblioloo.checked_previously ) %] + Patron has previously checked out this title
            + [% END %] + [% IF ( biblioloo.alreadyres ) %] +
              +
            • [% INCLUDE 'patron-title.inc' patron => patron no_title => 1 no_cardnumber => 1 hide_patron_infos_if_needed => 1 %] already has a hold on this item
            • +
            + [% END %] + [% IF ( biblioloo.none_avail || biblioloo.noitems ) %] +
            • No items are available to be placed on hold
            + [% END %] +
            + + [% END %] + +
            + [% ELSIF NOT ( noitems || nobiblio ) # /UNLESS patron %] + + [% IF ( checked_previously && !multi_hold ) %] +
            +
              +
            • Patron has previously checked out this title
            • +
            +
            + [% END %] + + [% IF ( no_reserves_allowed || exceeded_maxreserves || exceeded_holds_per_record || alreadyreserved || none_available || alreadypossession || ageRestricted || recall ) %] +
            + [% UNLESS ( multi_hold ) %] +

            Cannot place hold

            +
              + [% IF ( no_reserves_allowed ) %] +
            • No holds allowed: [% INCLUDE 'patron-title.inc' patron => patron no_title => 1 no_cardnumber => 1 hide_patron_infos_if_needed => 1 %] cannot place a hold on any of these items.
            • + [% ELSIF ( exceeded_maxreserves ) %] +
            • Too many holds: [% INCLUDE 'patron-title.inc' patron => patron no_title => 1 no_cardnumber => 1 hide_patron_infos_if_needed => 1 %] can only place a maximum of [% maxreserves | html %] total + holds.
            • + [% ELSIF ( exceeded_holds_per_record ) %] +
            • Too many holds for this record: [% INCLUDE 'patron-title.inc' patron => patron no_title => 1 no_cardnumber => 1 hide_patron_infos_if_needed => 1 %] can only place a maximum of + [% max_holds_for_record | html %] hold(s) on this record.
            • + [% ELSIF ( alreadypossession ) %] +
            • [% INCLUDE 'patron-title.inc' patron => patron no_title => 1 no_cardnumber => 1 hide_patron_infos_if_needed => 1 hide_patron_infos_if_needed => 1 %] is already in possession of one item.
            • + [% ELSIF ( alreadyreserved ) %] +
            • [% INCLUDE 'patron-title.inc' patron => patron no_title => 1 no_cardnumber => 1 hide_patron_infos_if_needed => 1 %] already has a hold on this item.
            • + [% ELSIF ( ageRestricted ) %] +
            • Age restricted
            • + [% ELSIF ( none_available ) %] +
            • No items are available to be placed on hold.
            • + [% ELSIF ( maxreserves ) %] +
            • Too many holds: + [% INCLUDE 'patron-title.inc' patron => patron no_title => 1 no_cardnumber => 1 hide_patron_infos_if_needed => 1 no_title => 1 no_cardnumber => 1 hide_patron_infos_if_needed => 1 %] has too many holds.
            • + [% ELSIF ( recall ) %] +
            • [% INCLUDE 'patron-title.inc' patron => patron no_title => 1 no_cardnumber => 1 hide_patron_infos_if_needed => 1 %] has already placed a recall on this item.
            • + [% END # /IF exceeded_maxreserves %] +
            + [% ELSE # UNLESS multi_hold %] +

            Cannot place hold on some items

            + [% IF (no_reserves_allowed ) %] +
          • No holds allowed: [% INCLUDE 'patron-title.inc' patron => patron no_title => 1 no_cardnumber => 1 hide_patron_infos_if_needed => 1 %] cannot place holds on some of these title's items.
          • + [% ELSIF ( exceeded_maxreserves ) %] +
          • Too many holds: [% INCLUDE 'patron-title.inc' patron => patron no_title => 1 no_cardnumber => 1 hide_patron_infos_if_needed => 1 %] can place [% new_reserves_allowed | html %] of the requested + [% new_reserves_count | html %] holds for a maximum of [% maxreserves | html %] total holds.
          • + [% ELSIF ( exceeded_holds_per_record ) %] + [% FOREACH biblioloo IN biblioloop %] + [% IF (biblioloo.tooManyHoldsForThisRecord) %] +
          • Too many holds for [% biblioloo.title | html %]: + [% INCLUDE 'patron-title.inc' patron => patron no_title => 1 no_cardnumber => 1 hide_patron_infos_if_needed => 1 %] can only place a maximum of [% max_holds_for_record | html %] hold(s) on this + record.
          • + [% END %] + [% END %] + [% ELSIF ( none_available ) %] +
          • No items available: One or more records have no items that can be held
          • + [% END # /IF exceeded_maxreserves %] + [% END # /UNLESS multi_hold %] +
            + [% END # /IF ( exceeded_maxreserves || ... %] + + [% IF ( patron.is_expired || diffbranch || patron.is_debarred || ( amount_outstanding && Koha.Preference('maxoutstanding') && amount_outstanding > Koha.Preference('maxoutstanding') ) ) %] +
            +
              + [% IF ( patron.is_expired ) %] +
            • [% INCLUDE 'patron-title.inc' patron => patron no_title => 1 no_cardnumber => 1 hide_patron_infos_if_needed => 1 %]: Account has expired
            • + [% END %] + + [% IF patron.is_debarred %] +
            • [% INCLUDE 'patron-title.inc' patron => patron no_title => 1 no_cardnumber => 1 hide_patron_infos_if_needed => 1 %]: Patron has restrictions
            • + [% END %] + + [% IF amount_outstanding && Koha.Preference('maxoutstanding') && amount_outstanding > Koha.Preference('maxoutstanding') %] +
            • [% INCLUDE 'patron-title.inc' patron => patron no_title => 1 no_cardnumber => 1 hide_patron_infos_if_needed => 1 link_to => 'members_pay' %]: + Patron has outstanding fines: [% amount_outstanding | $Price %]
            • + [% END %] + + [% IF ( diffbranch ) %] +
            • Pickup library is different. Patron: [% INCLUDE 'patron-title.inc' patron => patron no_title => 1 no_cardnumber => 1 hide_patron_infos_if_needed => 1 %] Patron's home library: + ([% Branches.GetName(patron.branchcode) | html %] / [% patron.branchcode | html %] )
            • + [% END %] +
            + +
            + [% END # /IF patron.is_expired || diffbranch ... %] + + [% IF ( messageborrower ) %] +
            +

            Patron not found:

            +

            Name or barcode not found. Please try an other

            +
            + [% END %] + +
            + + [% UNLESS ( multi_hold ) %] +
            + [% INCLUDE 'csrf-token.inc' %] +
            Hold details - - [% INCLUDE 'csrf-token.inc' %] - - [% IF ( multi_hold ) %] - - [% FOREACH biblioloo IN biblioloop %] - [% UNLESS biblioloo.none_avail %] - - - - [% END %] + + [% FOREACH biblionumber IN biblionumbers %] + + [% END %] + + + + +
              +
            1. + Patron: + [% IF ( patron.borrowernumber ) %] + [% INCLUDE 'patron-title.inc' patron => patron no_title => 1 hide_patron_infos_if_needed => 1 %] + [% ELSE %] + Not defined yet [% END %] - [% ELSE %] - - - - [% END # /IF multi_hold %] -
                + + +
              1. + Estimated priority: + [% fixedRank | html %] +
              2. + +
              3. + + +
              4. + + [% IF Koha.Preference('AllowHoldItemTypeSelection') %]
              5. - Club: [% club.name | html %] -
              6. -
              7. - Description: [% club.description | html %] -
              8. -
              9. - - + + [%- FOREACH itemtype IN available_itemtypes %] + + [%- END %]
              10. -
              11. - - -
              12. -
              -

              Members

              -
                - [% FOREACH member IN members %] - [% SET patron = member.patron %] -
              1. -
                [% INCLUDE 'patron-title.inc' patron => patron no_title => 1 no_cardnumber => 1 hide_patron_infos_if_needed => 1 %]
                - [% IF member.exceeded_maxreserves %] -
                - - Too many holds: Patron can only place a maximum of [% maxreserves | html %] total holds. -
                - [% END %] - [% IF ( patron.is_expired ) %] -
                - - Account has expired -
                - [% END %] - [% IF patron.is_debarred %] -
                - - Patron has restrictions -
                - [% END %] - [% IF member.amount_outstanding && Koha.Preference('maxoutstanding') && member.amount_outstanding > Koha.Preference('maxoutstanding') %] -
                - - Patron has outstanding fines: [% member.amount_outstanding | $Price %] -
                - [% END %] - - [% IF ( member.diffbranch ) %] -
                - - Pickup library is different. Patron's home library: ([% Branches.GetName(patron.branchcode) | html %] / [% patron.branchcode | html %] ) -
                - [% END %] -
              2. - [% END %] -
              - [% UNLESS ( multi_hold ) %] -
              - -
              - [% ELSE %] - - - - - [% UNLESS Koha.Preference('item-level_itypes') %] - - [% END %] - - - - [% FOREACH biblioloo IN biblioloop %] - - - - [% UNLESS Koha.Preference('item-level_itypes') %] - - [% END %] - - - - [% END # /FOREACH biblioloo %] -
               TitleItem typePriorityInformation
              - [% UNLESS ( biblioloo.warn ) %] - - [% END %] - -
                -
              • - [% biblioloo.title | html %] - [% IF biblioloo.author %] by [% biblioloo.author | html %][% END %] -
              • - [% IF ( biblioloo.publicationyear ) %] -
              • - Publication year: [% biblioloo.publicationyear | html %] -
              • - [% END %] -
              - [% IF ( biblioloo.warn ) %] - - [% END %] -
              - [% biblioloo.itemtype.translated_description | html %] - [% biblioloo.rank | html %] - [% IF ( biblioloo.checked_previously ) %] - Patron has previously checked out this title
              - [% END %] - [% IF ( biblioloo.alreadyres ) %] -
                -
              • - [% INCLUDE 'patron-title.inc' patron => patron no_title => 1 no_cardnumber => 1 hide_patron_infos_if_needed => 1 %] already has a hold on this item -
              • -
              - [% END %] - [% IF ( biblioloo.none_avail || biblioloo.noitems ) %] -
              • No items are available to be placed on hold
              - [% END %] -
              [% END %] -
            2. + + [% IF ( Koha.Preference('AllowHoldDateInFuture') ) %] +
            3. + + +
            4. + [% END %] + +
            5. + + +
            6. + +
            7. + + + A non priority hold doesn't prevent a current checkout from renewing +
            8. +
            - [% ELSIF NOT ( noitems || nobiblio ) # /UNLESS patron %] - - [% IF ( checked_previously && !multi_hold ) %] -
            -
              -
            • Patron has previously checked out this title
            • -
            -
            - [% END %] - - [% IF ( no_reserves_allowed || exceeded_maxreserves || exceeded_holds_per_record || alreadyreserved || none_available || alreadypossession || ageRestricted || recall ) %] -
            - - [% UNLESS ( multi_hold ) %] -

            Cannot place hold

            -
              - [% IF ( no_reserves_allowed ) %] -
            • No holds allowed: [% INCLUDE 'patron-title.inc' patron => patron no_title => 1 no_cardnumber => 1 hide_patron_infos_if_needed => 1 %] cannot place a hold on any of these items.
            • - [% ELSIF ( exceeded_maxreserves ) %] -
            • Too many holds: [% INCLUDE 'patron-title.inc' patron => patron no_title => 1 no_cardnumber => 1 hide_patron_infos_if_needed => 1 %] can only place a maximum of [% maxreserves | html %] total holds.
            • - [% ELSIF ( exceeded_holds_per_record ) %] -
            • Too many holds for this record: [% INCLUDE 'patron-title.inc' patron => patron no_title => 1 no_cardnumber => 1 hide_patron_infos_if_needed => 1 %] can only place a maximum of [% max_holds_for_record | html %] hold(s) on this record.
            • - [% ELSIF ( alreadypossession ) %] -
            • [% INCLUDE 'patron-title.inc' patron => patron no_title => 1 no_cardnumber => 1 hide_patron_infos_if_needed => 1 hide_patron_infos_if_needed => 1 %] is already in possession of one item.
            • - [% ELSIF ( alreadyreserved ) %] -
            • [% INCLUDE 'patron-title.inc' patron => patron no_title => 1 no_cardnumber => 1 hide_patron_infos_if_needed => 1 %] already has a hold on this item.
            • - [% ELSIF ( ageRestricted ) %] -
            • Age restricted
            • - [% ELSIF ( none_available ) %] -
            • No items are available to be placed on hold.
            • - [% ELSIF ( maxreserves ) %] -
            • Too many holds: [% INCLUDE 'patron-title.inc' patron => patron no_title => 1 no_cardnumber => 1 hide_patron_infos_if_needed => 1 no_title => 1 no_cardnumber => 1 hide_patron_infos_if_needed => 1 %] has too many holds.
            • - [% ELSIF ( recall ) %] -
            • [% INCLUDE 'patron-title.inc' patron => patron no_title => 1 no_cardnumber => 1 hide_patron_infos_if_needed => 1 %] has already placed a recall on this item.
            • - [% END # /IF exceeded_maxreserves %] -
            - [% ELSE # UNLESS multi_hold %] -

            Cannot place hold on some items

            - [% IF (no_reserves_allowed ) %] -
          • No holds allowed: [% INCLUDE 'patron-title.inc' patron => patron no_title => 1 no_cardnumber => 1 hide_patron_infos_if_needed => 1 %] cannot place holds on some of these title's items.
          • - [% ELSIF ( exceeded_maxreserves ) %] -
          • Too many holds: [% INCLUDE 'patron-title.inc' patron => patron no_title => 1 no_cardnumber => 1 hide_patron_infos_if_needed => 1 %] can place [% new_reserves_allowed | html %] of the requested [% new_reserves_count | html %] holds for a maximum of [% maxreserves | html %] total holds.
          • - [% ELSIF ( exceeded_holds_per_record ) %] - [% FOREACH biblioloo IN biblioloop %] - [% IF (biblioloo.tooManyHoldsForThisRecord) %] -
          • Too many holds for [% biblioloo.title | html %]: [% INCLUDE 'patron-title.inc' patron => patron no_title => 1 no_cardnumber => 1 hide_patron_infos_if_needed => 1 %] can only place a maximum of [% max_holds_for_record | html %] hold(s) on this record.
          • - [% END %] - [% END %] - [% ELSIF ( none_available ) %] -
          • No items available: One or more records have no items that can be held
          • - [% END # /IF exceeded_maxreserves %] - [% END # /UNLESS multi_hold %] -
            - [% END # /IF ( exceeded_maxreserves || ... %] - - [% IF ( patron.is_expired || diffbranch || patron.is_debarred || ( amount_outstanding && Koha.Preference('maxoutstanding') && amount_outstanding > Koha.Preference('maxoutstanding') ) ) %] -
            -
              - [% IF ( patron.is_expired ) %] -
            • [% INCLUDE 'patron-title.inc' patron => patron no_title => 1 no_cardnumber => 1 hide_patron_infos_if_needed => 1 %]: Account has expired
            • - [% END %] - - [% IF patron.is_debarred %] -
            • [% INCLUDE 'patron-title.inc' patron => patron no_title => 1 no_cardnumber => 1 hide_patron_infos_if_needed => 1 %]: Patron has restrictions
            • - [% END %] - - [% IF amount_outstanding && Koha.Preference('maxoutstanding') && amount_outstanding > Koha.Preference('maxoutstanding') %] -
            • [% INCLUDE 'patron-title.inc' patron => patron no_title => 1 no_cardnumber => 1 hide_patron_infos_if_needed => 1 link_to => 'members_pay' %]: Patron has outstanding fines: [% amount_outstanding | $Price %]
            • - [% END %] - - [% IF ( diffbranch ) %] -
            • Pickup library is different. Patron: [% INCLUDE 'patron-title.inc' patron => patron no_title => 1 no_cardnumber => 1 hide_patron_infos_if_needed => 1 %] Patron's home library: ([% Branches.GetName(patron.branchcode) | html %] / [% patron.branchcode | html %] )
            • - [% END %] -
            -
            - [% END # /IF patron.is_expired || diffbranch ... %] - - [% IF ( messageborrower ) %] -
            -

            Patron not found:

            -

            Name or barcode not found. Please try an other

            -
            - [% END %] - -
            -
            - - [% UNLESS ( multi_hold ) %] -
            - [% INCLUDE 'csrf-token.inc' %] - -
            - Hold details - - - [% FOREACH biblionumber IN biblionumbers %] - - [% END %] - - - - +
            + + [% IF force_hold_level == 'item' || force_hold_level == 'item_group' %] + + [% ELSIF force_hold_level == 'record' %] + + + (Required) + [% ELSE %] + + [% END %] + + + +
            + [% IF force_hold_level == 'item' # Patron has placed a item level hold previously for this record %] + + + Hold must be item level + + [% ELSIF force_hold_level == 'item_group' # Patron has placed an item group level hold previously for this record %] + + + Hold must be item group level + + [% ELSE %]
            1. - Patron: - [% IF ( patron.borrowernumber ) %] - [% INCLUDE 'patron-title.inc' patron => patron no_title => 1 hide_patron_infos_if_needed => 1 %] - [% ELSE %] - Not defined yet - [% END %] -
            2. - -
            3. - Estimated priority: - [% fixedRank | html %] -
            4. - -
            5. - - + +
            6. [% IF Koha.Preference('AllowHoldItemTypeSelection') %] @@ -570,124 +658,50 @@ [% END %] - - [% IF ( Koha.Preference('AllowHoldDateInFuture') ) %] -
            7. - - -
            8. - [% END %] - -
            9. - - -
            10. - -
            11. - - - A non priority hold doesn't prevent a current checkout from renewing -
            12. + [% UNLESS remaining_holds_for_record == 1 %] +
            13. + + +
            14. + [% ELSE %] + + [% END %]
            -
            -
            - - [% IF force_hold_level == 'item' || force_hold_level == 'item_group' %] - - [% ELSIF force_hold_level == 'record' %] - - - (Required) - [% ELSE %] - - [% END %] - - - -
            - [% IF force_hold_level == 'item' # Patron has placed a item level hold previously for this record %] - - - Hold must be item level - - [% ELSIF force_hold_level == 'item_group' # Patron has placed an item group level hold previously for this record %] - - - Hold must be item group level - + [% END %] + +
            + [% IF ( patron.borrowernumber ) %] + [% IF ( override_required ) %] + + [% ELSIF ( none_available ) %] + [% ELSE %] -
              - -
            1. - - -
            2. - - [% IF Koha.Preference('AllowHoldItemTypeSelection') %] -
            3. - - -
            4. - [% END %] - [% UNLESS remaining_holds_for_record == 1 %] -
            5. - - -
            6. - [% ELSE %] - - [% END %] -
            + [% END %] - - -
            - [% IF ( patron.borrowernumber ) %] - [% IF ( override_required ) %] - - [% ELSIF ( none_available ) %] - - [% ELSE %] - - [% END %] - [% END %] -
            -
            + [% END %]
            +
            +
            -
            +
            - [% biblio_info = biblioloop.0 %] - - [% IF Koha.Preference('EnableItemGroupHolds') && biblio_info.object.item_groups.count %] -
            - - [% IF force_hold_level == 'item_group' %] - - (Required) - [% ELSIF force_hold_level == 'item' || force_hold_level == 'record' %] - - [% ELSE %] - - [% END %] - - + [% biblio_info = biblioloop.0 %] + + [% IF Koha.Preference('EnableItemGroupHolds') && biblio_info.object.item_groups.count %] +
            + + [% IF force_hold_level == 'item_group' %] + + (Required) + [% ELSIF force_hold_level == 'item' || force_hold_level == 'record' %] + + [% ELSE %] + + [% END %] + + -
            +
            [% IF force_hold_level == 'record' # Patron has placed a record level hold previously for this record %] @@ -702,10 +716,7 @@
            • - [% PROCESS options_for_libraries libraries => Branches.pickup_locations({ search_params => { biblio => biblionumber, patron => patron }, selected => pickup }) %]
            • @@ -753,691 +764,674 @@
            [% END %] -
            - [% IF ( patron.borrowernumber ) %] - [% IF ( override_required ) %] - - [% ELSIF ( none_available ) %] - - [% ELSE %] - - [% END %] +
            + [% IF ( patron.borrowernumber ) %] + [% IF ( override_required ) %] + + [% ELSIF ( none_available ) %] + + [% ELSE %] + [% END %] -
            + [% END %]
            +
            + [% END %] + + +
            + + [% IF force_hold_level == 'item' %] + + (Required) + [% ELSIF force_hold_level == 'record' || force_hold_level == 'item_group' %] + + [% ELSE %] + [% END %] - + + -
            - - [% IF force_hold_level == 'item' %] - - (Required) - [% ELSIF force_hold_level == 'record' || force_hold_level == 'item_group' %] - - [% ELSE %] - - [% END %] - - +
            +
              + [% UNLESS Koha.Preference('item-level_itypes') %] +
            1. + Item type: + [% biblio_info.itemtype.translated_description | html %] +
            2. + [% END %] -
              -
                - [% UNLESS Koha.Preference('item-level_itypes') %] -
              1. - Item type: - [% biblio_info.itemtype.translated_description | html %] -
              2. + [% IF ( biblio_info.biblioitem.publicationyear ) %] +
              3. + Publication year: + [% biblio_info.biblioitem.publicationyear | html %] +
              4. + [% END %] +
              + + + + + + + [% IF Koha.Preference('item-level_itypes') %] + [% END %] - - [% IF ( biblio_info.biblioitem.publicationyear ) %] -
            3. - Publication year: - [% biblio_info.biblioitem.publicationyear | html %] -
            4. + + [% IF Koha.Preference('EnableItemGroupHolds') && biblio_info.object.item_groups.count %] + [% END %] - - -
              HoldAllowed pickup locationsItem typeBarcodeItem group
              - - - - - [% IF Koha.Preference('item-level_itypes') %] - - [% END %] - - [% IF Koha.Preference('EnableItemGroupHolds') && biblio_info.object.item_groups.count %] - - [% END %] - - - [% IF itemdata_ccode %] - - [% END %] - - - [% IF itemdata_enumchron %] - - [% END %] - - - - - [% SET selected = 0 %] - [% FOREACH itemloo IN biblio_info.itemloop %] - [% UNLESS ( itemloo.hide ) %] - - - + + [% IF itemdata_ccode %] + + [% END %] + + + [% IF itemdata_enumchron %] + + [% END %] + + + + + [% SET selected = 0 %] + [% FOREACH itemloo IN biblio_info.itemloop %] + [% UNLESS ( itemloo.hide ) %] + + + - [% IF Koha.Preference('item-level_itypes') %] - - [% END %] - - [% IF Koha.Preference('EnableItemGroupHolds') && biblio_info.object.item_groups.count %] - - [% END %] - - - [% IF itemdata_ccode %] - - [% END %] - - - [% IF itemdata_enumchron %] - - [% END %] - - - [% END # / UNLESS itemloo.hide %] - [% END # /FOREACH itemloo %] - -
              HoldAllowed pickup locationsItem typeBarcodeItem groupHome libraryLast locationCollectionCall numberCopy numberVol no.Information
              - [% IF force_hold_level == 'record' # Patron has placed a record level hold previously for this record %] - - - Hold must be record level - - [% ELSIF force_hold_level == 'item_group' %] - - - Hold must be item group level - - [% ELSIF ( itemloo.available ) %] - - [% ELSIF ( itemloo.override ) %] - - - [% ELSE %] - - - [% IF itemloo.not_holdable %] - [% IF itemloo.not_holdable == 'damaged' %] - Item damaged - [% ELSIF itemloo.not_holdable == 'ageRestricted' %] - Age restricted - [% ELSIF itemloo.not_holdable == 'tooManyHoldsForThisRecord' %] - Exceeded max holds per record - [% ELSIF itemloo.not_holdable == 'tooManyReservesToday' %] - Daily hold limit reached for patron - [% ELSIF itemloo.not_holdable == 'tooManyReserves' %] - Too many holds - [% ELSIF itemloo.not_holdable == 'notReservable' %] - Not holdable - [% ELSIF itemloo.not_holdable == 'cannotReserveFromOtherBranches' %] - Patron is from different library - [% ELSIF itemloo.not_holdable == 'branchNotInHoldGroup' %] - Cannot place hold from patron's library - [% ELSIF itemloo.not_holdable == 'itemAlreadyOnHold' %] - Patron already has hold for this item - [% ELSIF itemloo.not_holdable == 'cannotBeTransferred' %] - Cannot be transferred to pickup library - [% ELSIF itemloo.not_holdable == 'pickupNotInHoldGroup' %] - Only pickup locations within the same hold group are allowed - [% ELSIF itemloo.not_holdable == 'noReservesAllowed' %] - No holds are allowed on this item - [% ELSIF itemloo.not_holdable == 'libraryNotPickupLocation' %] - Library is not a pickup location - [% ELSIF itemloo.not_holdable == 'no_valid_pickup_location' %] - No valid pickup location - [% ELSIF itemloo.not_holdable == 'notforloan' %] - Not for loan - [% ELSE %] - [% itemloo.not_holdable | html %] - [% END %] - [% END %] - - [% END # /IF force_hold_level %] - - [% IF (itemloo.pickup_locations_count > 0) || Koha.Preference('AllowHoldPolicyOverride') %] - Home libraryLast locationCollectionCall numberCopy numberVol no.Information
              + [% IF force_hold_level == 'record' # Patron has placed a record level hold previously for this record %] + + + Hold must be record level + + [% ELSIF force_hold_level == 'item_group' %] + + + Hold must be item group level + + [% ELSIF ( itemloo.available ) %] + + [% ELSIF ( itemloo.override ) %] + + + [% ELSE %] + + + [% IF itemloo.not_holdable %] + [% IF itemloo.not_holdable == 'damaged' %] + Item damaged + [% ELSIF itemloo.not_holdable == 'ageRestricted' %] + Age restricted + [% ELSIF itemloo.not_holdable == 'tooManyHoldsForThisRecord' %] + Exceeded max holds per record + [% ELSIF itemloo.not_holdable == 'tooManyReservesToday' %] + Daily hold limit reached for patron + [% ELSIF itemloo.not_holdable == 'tooManyReserves' %] + Too many holds + [% ELSIF itemloo.not_holdable == 'notReservable' %] + Not holdable + [% ELSIF itemloo.not_holdable == 'cannotReserveFromOtherBranches' %] + Patron is from different library + [% ELSIF itemloo.not_holdable == 'branchNotInHoldGroup' %] + Cannot place hold from patron's library + [% ELSIF itemloo.not_holdable == 'itemAlreadyOnHold' %] + Patron already has hold for this item + [% ELSIF itemloo.not_holdable == 'cannotBeTransferred' %] + Cannot be transferred to pickup library + [% ELSIF itemloo.not_holdable == 'pickupNotInHoldGroup' %] + Only pickup locations within the same hold group are allowed + [% ELSIF itemloo.not_holdable == 'noReservesAllowed' %] + No holds are allowed on this item + [% ELSIF itemloo.not_holdable == 'libraryNotPickupLocation' %] + Library is not a pickup location + [% ELSIF itemloo.not_holdable == 'no_valid_pickup_location' %] + No valid pickup location + [% ELSIF itemloo.not_holdable == 'notforloan' %] + Not for loan + [% ELSE %] + [% itemloo.not_holdable | html %] + [% END %] + [% END %] + + [% END # /IF force_hold_level %] + + [% IF (itemloo.pickup_locations_count > 0) || Koha.Preference('AllowHoldPolicyOverride') %] + - [% END %] - - [% UNLESS ( noItemTypeImages ) %] - [% IF ( itemloo.itemtype.image_location) %]
              [% END %] - [% END %] - [% itemloo.itemtype.translated_description | html %] -
              - [% itemloo.barcode | html %] - - [% itemloo.object.item_group.description | html %] - - [% Branches.GetName( itemloo.homebranch ) | html %] - - [% Branches.GetName( itemloo.holdingbranch ) | html %] - - [% IF ( itemloo.ccode ) %][% AuthorisedValues.GetDescriptionByKohaField( kohafield => 'items.ccode', authorised_value => itemloo.ccode ) | html %][% END %] - - [% itemloo.itemcallnumber | html %] - - [% IF ( itemloo.copynumber ) %][% itemloo.copynumber | html %][% ELSE %] [% END %] - - [% itemloo.enumchron | html %] - - [% IF ( itemloo.onloan ) %] - Due [% itemloo.date_due | $KohaDates as_due_date => 1 %] - [% ELSE %] - [% IF ( itemloo.transfertwhen ) %] - In transit from [% Branches.GetName( itemloo.transfertfrom ) | html %], - to [% Branches.GetName( itemloo.transfertto ) | html %], since [% itemloo.transfertwhen | $KohaDates %] - [% END %] - [% END %] - - [% IF ( itemloo.reservedate ) %] - [% IF ( itemloo.nocancel ) %] - Can't be cancelled when item is in transit - [% ELSE %] - [% IF ( itemloo.waitingdate ) %] - [% IF ( itemloo.canreservefromotherbranches ) %] - Waiting for [% INCLUDE 'patron-title.inc' patron=itemloo.ReservedFor %] at [% Branches.GetName( itemloo.ExpectedAtLibrary ) | html %] since [% itemloo.waitingdate | $KohaDates %] - [% ELSE %] - Waiting at [% Branches.GetName( itemloo.ExpectedAtLibrary ) | html %] since [% itemloo.waitingdate | $KohaDates %] - [% END %] - [% ELSE %] - [% IF ( itemloo.canreservefromotherbranches ) %] - [% IF itemloo.reservedate %] - On hold for [% INCLUDE 'patron-title.inc' patron=itemloo.ReservedFor %] expected at [% Branches.GetName( itemloo.ExpectedAtLibrary ) | html %] since - [% ELSE %] - On hold expected at [% Branches.GetName( itemloo.ExpectedAtLibrary ) | html %] - [% END %] - [% ELSIF itemloo.reservedate %] - On hold expected at [% Branches.GetName( itemloo.ExpectedAtLibrary ) | html %] since [% itemloo.reservedate | $KohaDates %] - [% ELSE %] - On hold expected at [% Branches.GetName( itemloo.ExpectedAtLibrary ) | html %] - [% END %] - [% END %] - [% END # /IF itemloo.nocancel %] - [% ELSE %] - Not on hold - [% END # /IF itemloo.reservedate %] - - [% IF itemloo.item_level_holds == "N" %] -
              Item level hold not allowed from OPAC - [% ELSIF itemloo.item_level_holds == "F" %] -
              Item level hold forced from OPAC - [% END %] - - [% IF ( itemloo.itemlost ) %] - [% AuthorisedValues.GetDescriptionByKohaField( kohafield => 'items.itemlost', authorised_value => itemloo.itemlost ) | html %] - [% END %] - - [% IF ( itemloo.damaged ) %] - [% AuthorisedValues.GetDescriptionByKohaField( kohafield => 'items.damaged', authorised_value => itemloo.damaged ) | html %] - [% END %] - - [% IF ( itemloo.withdrawn ) %] - [% AuthorisedValues.GetDescriptionByKohaField( kohafield => 'items.withdrawn', authorised_value => itemloo.withdrawn ) | html %] - [% END %] - - [% IF ( itemloo.notforloan ) %] - Not for loan ([% AuthorisedValues.GetDescriptionByKohaField( kohafield => 'items.notforloan', authorised_value => itemloo.notforloan ) | html %]) - [% ELSIF ( itemloo.notforloanitype ) %] - Not for loan (Itemtype not for loan) - [% END %] -
              - - [% IF hiddencount %] -

              - Show all items ([% hiddencount | html %] hidden) -

              - [% END # /IF hiddencount %] -
              - [% IF ( patron.borrowernumber ) %] - [% IF ( override_required ) %] - - [% ELSIF ( none_available ) %] - - [% ELSE %] - - [% END %] - [% END %] -
              - -
              -
            - - - [% ELSE # /UNLESS multi_hold %] -
            -
            - Hold details - [% INCLUDE 'csrf-token.inc' %] - - - - - [% FOREACH biblioloo IN biblioloop %] - - [% UNLESS biblioloo.none_avail %] - - + [% END %] + + [% IF Koha.Preference('item-level_itypes') %] + + [% UNLESS ( noItemTypeImages ) %] + [% IF ( itemloo.itemtype.image_location) %]
            [% END %] + [% END %] + [% itemloo.itemtype.translated_description | html %] + [% END %] - -
              - -
            1. - Patron: - [% IF ( patron.borrowernumber ) %] - [% INCLUDE 'patron-title.inc' patron => patron no_title => 1 hide_patron_infos_if_needed => 1 %] + [% itemloo.barcode | html %] + [% IF Koha.Preference('EnableItemGroupHolds') && biblio_info.object.item_groups.count %] + [% itemloo.object.item_group.description | html %] + [% END %] + [% Branches.GetName( itemloo.homebranch ) | html %] + [% Branches.GetName( itemloo.holdingbranch ) | html %] + [% IF itemdata_ccode %] + [% IF ( itemloo.ccode ) %][% AuthorisedValues.GetDescriptionByKohaField( kohafield => 'items.ccode', authorised_value => itemloo.ccode ) | html %][% END %] + [% END %] + [% itemloo.itemcallnumber | html %] + [% IF ( itemloo.copynumber ) %][% itemloo.copynumber | html %][% ELSE %] [% END %] + [% IF itemdata_enumchron %] + [% itemloo.enumchron | html %] + [% END %] + + [% IF ( itemloo.onloan ) %] + Due [% itemloo.date_due | $KohaDates as_due_date => 1 %] [% ELSE %] - Not defined yet - [% END %] -
            2. - - -
            3. - - -
            4. -
            5. - - -
            6. - [% IF ( Koha.Preference('AllowHoldDateInFuture') ) %] -
            7. - - -
            8. - [% END %] - -
            9. - - -
            10. - -
            - - - - - - [% UNLESS Koha.Preference('item-level_itypes') %] - - [% END %] - - - - [% FOREACH biblioloo IN biblioloop %] - - - - - [% UNLESS Koha.Preference('item-level_itypes') %] - + [% END # /IF itemloo.nocancel %] + [% ELSE %] + Not on hold + [% END # /IF itemloo.reservedate %] + + [% IF itemloo.item_level_holds == "N" %] +
            Item level hold not allowed from OPAC + [% ELSIF itemloo.item_level_holds == "F" %] +
            Item level hold forced from OPAC [% END %] - - - - [% END # /FOREACH biblioloo %] -
             Pickup locationTitleItem typePriorityInformation
            - [% UNLESS ( biblioloo.warn ) %] - + [% IF ( itemloo.transfertwhen ) %] + In transit from [% Branches.GetName( itemloo.transfertfrom ) | html %], to [% Branches.GetName( itemloo.transfertto ) | html %], since + [% itemloo.transfertwhen | $KohaDates %] [% END %] - - [% UNLESS ( biblioloo.none_avail || biblioloo.noitems ) %] - - [% END %] - -
              -
            • - [% biblioloo.title | html %] - [% IF biblioloo.author %] by [% biblioloo.author | html %][% END %] -
            • - [% IF ( biblioloo.publicationyear ) %] -
            • - Publication year: [% biblioloo.publicationyear | html %] -
            • [% END %] -
            - [% IF ( biblioloo.warn ) %] - - [% END %] -
            - [% biblioloo.itemtype.translated_description | html %] - [% biblioloo.rank | html %] - [% IF ( biblioloo.checked_previously ) %] - Patron has previously checked out this title
            - [% END %] - [% IF ( biblioloo.alreadyres ) %] -
              -
            • - [% INCLUDE 'patron-title.inc' patron => patron no_title => 1 no_cardnumber => 1 hide_patron_infos_if_needed => 1 %] already has a hold on this item -
            • -
            - [% END %] - [% IF ( biblioloo.none_avail || biblioloo.noitems ) %] -
            • No items are available to be placed on hold
            - [% END %] -
            -
            -
            - [% IF ( patron AND patron.borrowernumber ) %] - [% IF ( override_required ) %] - - [% ELSIF ( no_bibs_available ) %] - - [% ELSIF ( none_available ) %] - - [% ELSE %] - - [% END %] - [% END # /IF patron %] -
            -
            - [% END # /UNLESS multi_hold %] + [% IF ( itemloo.itemlost ) %] + [% AuthorisedValues.GetDescriptionByKohaField( kohafield => 'items.itemlost', authorised_value => itemloo.itemlost ) | html %] + [% END %] - [% END %] + [% IF ( itemloo.damaged ) %] + [% AuthorisedValues.GetDescriptionByKohaField( kohafield => 'items.damaged', authorised_value => itemloo.damaged ) | html %] + [% END %] - [% UNLESS ( patron ) %] - [% UNLESS borrowers %] - [% SET hold_count = biblio.holds.count | html %] - [% IF hold_count %] - - [% IF always_show_holds == 'DONT' %] - - [% UNLESS reserveloop %] - Show holds ([% hold_count | html %]) - [% END %] - [% ELSE %] - - [% END %] - [% END %] - [% END %] - [% IF ( reserveloop ) %] -
            - [% INCLUDE 'csrf-token.inc' %] - [% IF ( multi_hold ) %] - [% FOREACH biblionumber IN biblionumbers %] - - [% END %] - [% END %] + [% IF ( itemloo.withdrawn ) %] + [% AuthorisedValues.GetDescriptionByKohaField( kohafield => 'items.withdrawn', authorised_value => itemloo.withdrawn ) | html %] + [% END %] - [% IF enqueued %] -
            -

            The job has been enqueued! It will be processed as soon as possible.

            -

            View detail of the enqueued job

            -
            - [% END %] + [% IF ( itemloo.notforloan ) %] + Not for loan ([% AuthorisedValues.GetDescriptionByKohaField( kohafield => 'items.notforloan', authorised_value => itemloo.notforloan ) | html %]) + [% ELSIF ( itemloo.notforloanitype ) %] + Not for loan (Itemtype not for loan) + [% END %] + + + [% END # / UNLESS itemloo.hide %] + [% END # /FOREACH itemloo %] + + + -

            Existing holds

            -
            -
            - - -
            -
            - -
            -
            -
            +
            +
            + + + + [% ELSE # /UNLESS multi_hold %] +
            +
            + Hold details + [% INCLUDE 'csrf-token.inc' %] + + + + + [% FOREACH biblioloo IN biblioloop %] + + [% UNLESS biblioloo.none_avail %] + + + [% END %] + [% END %] +
              +
            1. + Patron: + [% IF ( patron.borrowernumber ) %] + [% INCLUDE 'patron-title.inc' patron => patron no_title => 1 hide_patron_infos_if_needed => 1 %] + [% ELSE %] + Not defined yet + [% END %] +
            2. + +
            3. + + +
            4. +
            5. + + +
            6. + [% IF ( Koha.Preference('AllowHoldDateInFuture') ) %] +
            7. + + +
            8. + [% END %] + +
            9. + + +
            10. +
            + + + + + + [% UNLESS Koha.Preference('item-level_itypes') %] + + [% END %] + + + [% FOREACH biblioloo IN biblioloop %] - [% IF ( biblioloo.reserveloop ) %] -
            - [% IF ( multi_hold ) %] -

            - - [% biblioloo.title | html %] - [% biblioloo.reserveloop.size | html %] [% tn('Hold', 'Holds', biblioloo.reserveloop.size) | $raw %] -

            +
            + + + + [% UNLESS Koha.Preference('item-level_itypes') %] + + [% END %] + + + + [% END # /FOREACH biblioloo %] +
             Pickup locationTitleItem typePriorityInformation
            + [% UNLESS ( biblioloo.warn ) %] + [% END %] - - [% IF Koha.Preference('HoldsSplitQueue') == 'branch' %] - - [% SET branchcodes = [] %] - - [% FOREACH h IN biblioloo.reserveloop %] - [% branchcodes.push( h.branchcode ) %] + + [% UNLESS ( biblioloo.none_avail || biblioloo.noitems ) %] + + [% END %] + +
              +
            • + [% biblioloo.title | html %] + [% IF biblioloo.author %]by [% biblioloo.author | html %][% END %] +
            • + [% IF ( biblioloo.publicationyear ) %] +
            • Publication year: [% biblioloo.publicationyear | html %]
            • [% END %] - [% branchcodes = branchcodes.unique %] - [% IF ( branchcodes.empty ) %] -
              - There are no holds on this title. -
              - [% ELSE %] +
            + [% IF ( biblioloo.warn ) %] + + [% END %] +
            + [% biblioloo.itemtype.translated_description | html %] + [% biblioloo.rank | html %] + [% IF ( biblioloo.checked_previously ) %] + Patron has previously checked out this title
            + [% END %] + [% IF ( biblioloo.alreadyres ) %] +
              +
            • [% INCLUDE 'patron-title.inc' patron => patron no_title => 1 no_cardnumber => 1 hide_patron_infos_if_needed => 1 %] already has a hold on this item
            • +
            + [% END %] + [% IF ( biblioloo.none_avail || biblioloo.noitems ) %] +
            • No items are available to be placed on hold
            + [% END %] +
            + +
            +
            + [% IF ( patron AND patron.borrowernumber ) %] + [% IF ( override_required ) %] + + [% ELSIF ( no_bibs_available ) %] + + [% ELSIF ( none_available ) %] + + [% ELSE %] + + [% END %] + [% END # /IF patron %] +
            + +
            + + [% END # /UNLESS multi_hold %] + [% END %] - [% FOREACH b IN branchcodes.sort %] + [% UNLESS ( patron ) %] + [% UNLESS borrowers %] + [% SET hold_count = biblio.holds.count | html %] + [% IF hold_count %] + + [% IF always_show_holds == 'DONT' %] + + [% UNLESS reserveloop %] + Show holds ([% hold_count | html %]) + [% END %] + [% ELSE %] + + [% END %] + [% END %] + [% END %] + [% IF ( reserveloop ) %] +
            + [% INCLUDE 'csrf-token.inc' %] + [% IF ( multi_hold ) %] + [% FOREACH biblionumber IN biblionumbers %] + + [% END %] + [% END %] + + [% IF enqueued %] +
            +

            The job has been enqueued! It will be processed as soon as possible.

            +

            View detail of the enqueued job

            +
            + [% END %] + +

            Existing holds

            +
            +
            + + +
            +
            + +
            + +
            +
            + [% FOREACH biblioloo IN biblioloop %] + [% IF ( biblioloo.reserveloop ) %] +
            + [% IF ( multi_hold ) %] +

            + [% biblioloo.title | html %] + [% biblioloo.reserveloop.size | html %] [% tn('Hold', 'Holds', biblioloo.reserveloop.size) | $raw %] +

            + [% END %] + + [% IF Koha.Preference('HoldsSplitQueue') == 'branch' %] + + [% SET branchcodes = [] %] + + [% FOREACH h IN biblioloo.reserveloop %] + [% branchcodes.push( h.branchcode ) %] + [% END %] + [% branchcodes = branchcodes.unique %] + [% IF ( branchcodes.empty ) %] +
            There are no holds on this title.
            + [% ELSE %] + + [% FOREACH b IN branchcodes.sort %] + [% SET holds_by_branch = [] %] + [% FOREACH h IN biblioloo.reserveloop %] + [% IF h.branchcode == b %] + [% holds_by_branch.push( h ) %] + [% END %] + [% END %] +
            +

            [% Branches.GetName( b ) | html %]

            + + [% INCLUDE holds_table.inc holds=holds_by_branch %] +
            + [% END # /FOREACh b %] + [% END # /IF ( branchcodes.empty ) %] + [% ELSIF Koha.Preference('HoldsSplitQueue') == 'itemtype' %] + + [% SET itemtypes = [] %] + + [% FOREACH h IN biblioloo.reserveloop %] + [% SET hold_itemtype = h.object.item.effective_itemtype || h.itemtype %] + [% itemtypes.push( hold_itemtype ) %] + [% END %] + [% itemtypes = itemtypes.unique %] + [% IF ( itemtypes.empty ) %] +
            There are no holds on this title.
            + [% ELSE %] + + [% FOREACH i IN itemtypes.sort %] + [% SET holds_by_itemtype = [] %] + [% FOREACH h IN biblioloo.reserveloop %] + [% SET hold_itemtype = h.object.item.effective_itemtype || h.itemtype %] + [% IF hold_itemtype == i %] + [% holds_by_itemtype.push( h ) %] + [% END %] + [% END %] + +
            + [% IF i %] +

            [% ItemTypes.GetDescription( i ) | html %]

            + [% ELSE %] +

            Any item type

            + [% END %] + [% INCLUDE holds_table.inc holds=holds_by_itemtype %] +
            + [% END # /FOREACH i %] + [% END # /IF ( itemtypes.empty ) %] + [% ELSIF Koha.Preference('HoldsSplitQueue') == 'branch_itemtype' %] + [% SET branchcodes = [] %] + + [% FOREACH h IN biblioloo.reserveloop %] + [% branchcodes.push( h.branchcode ) %] + [% END %] + [% branchcodes = branchcodes.unique %] + [% IF ( branchcodes.empty ) %] +
            There are no holds on this title.
            + [% ELSE %] + + [% FOREACH b IN branchcodes.sort %] +
            +

            [% Branches.GetName( b ) | html %]

            [% SET holds_by_branch = [] %] [% FOREACH h IN biblioloo.reserveloop %] [% IF h.branchcode == b %] [% holds_by_branch.push( h ) %] [% END %] [% END %] -
            -

            [% Branches.GetName( b ) | html %]

            - [% INCLUDE holds_table.inc holds=holds_by_branch %] -
            - [% END # /FOREACh b %] - [% END # /IF ( branchcodes.empty ) %] - - [% ELSIF Koha.Preference('HoldsSplitQueue') == 'itemtype' %] - - [% SET itemtypes = [] %] - - [% FOREACH h IN biblioloo.reserveloop %] - [% SET hold_itemtype = h.object.item.effective_itemtype || h.itemtype %] - [% itemtypes.push( hold_itemtype ) %] - [% END %] - [% itemtypes = itemtypes.unique %] - [% IF ( itemtypes.empty ) %] -
            - There are no holds on this title. -
            - [% ELSE %] - - [% FOREACH i IN itemtypes.sort %] - [% SET holds_by_itemtype = [] %] - [% FOREACH h IN biblioloo.reserveloop %] + [% SET itemtypes = [] %] + [% FOREACH h IN holds_by_branch %] [% SET hold_itemtype = h.object.item.effective_itemtype || h.itemtype %] - [% IF hold_itemtype == i %] - [% holds_by_itemtype.push( h ) %] - [% END %] + [% itemtypes.push( hold_itemtype ) %] [% END %] + [% itemtypes = itemtypes.unique %] -
            - [% IF i %] -

            [% ItemTypes.GetDescription( i ) | html %]

            - [% ELSE %] -

            Any item type

            - [% END %] - [% INCLUDE holds_table.inc holds=holds_by_itemtype %] -
            - [% END # /FOREACH i %] - [% END # /IF ( itemtypes.empty ) %] - - [% ELSIF Koha.Preference('HoldsSplitQueue') == 'branch_itemtype' %] - [% SET branchcodes = [] %] - - [% FOREACH h IN biblioloo.reserveloop %] - [% branchcodes.push( h.branchcode ) %] - [% END %] - [% branchcodes = branchcodes.unique %] - [% IF ( branchcodes.empty ) %] -
            - There are no holds on this title. -
            - [% ELSE %] - - [% FOREACH b IN branchcodes.sort %] -
            -

            [% Branches.GetName( b ) | html %]

            - [% SET holds_by_branch = [] %] - [% FOREACH h IN biblioloo.reserveloop %] - [% IF h.branchcode == b %] - [% holds_by_branch.push( h ) %] - [% END %] - [% END %] - - [% SET itemtypes = [] %] - [% FOREACH h IN holds_by_branch %] - [% SET hold_itemtype = h.object.item.effective_itemtype || h.itemtype %] - [% itemtypes.push( hold_itemtype ) %] - [% END %] - [% itemtypes = itemtypes.unique %] - - [% FOREACH i IN itemtypes.sort %] -
            -
            - [% IF i %] - [% ItemTypes.GetDescription( i ) | html %] - [% ELSE %] - Any item type - [% END %] -
            - - [% SET holds_by_itemtype = [] %] - [% FOREACH h IN holds_by_branch %] - [% SET hold_itemtype = h.object.item.effective_itemtype || h.itemtype %] - [% IF hold_itemtype == i %] - [% holds_by_itemtype.push( h ) %] - [% END %] + [% FOREACH i IN itemtypes.sort %] +
            +
            + [% IF i %] + [% ItemTypes.GetDescription( i ) | html %] + [% ELSE %] + Any item type [% END %] - [% INCLUDE holds_table.inc holds=holds_by_itemtype %] -
            - [% END %] -
            - [% END # /FOREACH b %] - [% END # /IF ( branchcodes.empty ) %] + - [% ELSE %] - - [% IF ( biblioloo.reserveloop.size ) %] - [% INCLUDE holds_table.inc holds=biblioloo.reserveloop %] - [% ELSE %] -
            - There are no holds on this title. + [% SET holds_by_itemtype = [] %] + [% FOREACH h IN holds_by_branch %] + [% SET hold_itemtype = h.object.item.effective_itemtype || h.itemtype %] + [% IF hold_itemtype == i %] + [% holds_by_itemtype.push( h ) %] + [% END %] + [% END %] + [% INCLUDE holds_table.inc holds=holds_by_itemtype %] +
            + + [% END %]
            - [% END %] + + [% END # /FOREACH b %] + [% END # /IF ( branchcodes.empty ) %] + [% ELSE %] - [% END # /IF HoldsSplitQueue %] -
            - [% END # /IF biblioloo.reserveloop %] - [% END # FOREACH biblioloo %] -
            - - [% END # IF reserveloop %] - [% END # UNLESS patron %] + [% IF ( biblioloo.reserveloop.size ) %] + [% INCLUDE holds_table.inc holds=biblioloo.reserveloop %] + [% ELSE %] +
            There are no holds on this title.
            + [% END %] + [% END # /IF HoldsSplitQueue %] +
            + + [% END # /IF biblioloo.reserveloop %] + [% END # FOREACH biblioloo %] + + + + [% END # IF reserveloop %] + [% END # UNLESS patron %] [% END %] - +
            - - - + + + + + + [% INCLUDE 'intranet-bottom.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/serials/serials-home.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/serials/serials-home.tt index db7fbef22c..f00c053aa5 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/serials/serials-home.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/serials/serials-home.tt @@ -7,10 +7,12 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% tx("Serials {biblionumber}", { biblionumber = biblionumber }) | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% tx("Serials {biblionumber}", { biblionumber = biblionumber }) | html %] + › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -28,19 +30,16 @@ [% WRAPPER 'main-container.inc' aside='serials-menu' %] - [% INCLUDE 'serials-toolbar.inc' %] + [% INCLUDE 'serials-toolbar.inc' %] -

            Serials

            +

            Serials

            - [% INCLUDE 'serials-advsearch.inc' %] - - [%- SET StaffSerialsHome = AdditionalContents.get( location => "StaffSerialsHome", lang => lang, library => Branches.GetLoggedInBranchcode ) -%] - [%- FOREACH block IN StaffSerialsHome.content -%] -
            - [%- block.content | $raw -%] -
            - [%- END -%] + [% INCLUDE 'serials-advsearch.inc' %] + [%- SET StaffSerialsHome = AdditionalContents.get( location => "StaffSerialsHome", lang => lang, library => Branches.GetLoggedInBranchcode ) -%] + [%- FOREACH block IN StaffSerialsHome.content -%] +
            [%- block.content | $raw -%]
            + [%- END -%] [% END %] [% MACRO jsinclude BLOCK %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/serials/serials-search.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/serials/serials-search.tt index 01b497093e..a62ed79046 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/serials/serials-search.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/serials/serials-search.tt @@ -8,291 +8,297 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Search results") | html %] › - [% t("Serials") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Search results") | html %] + › [% t("Serials") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] - + - [% WRAPPER 'header.inc' %] +[% WRAPPER 'header.inc' %] [% INCLUDE 'serials-search.inc' %] [% END %] - [% WRAPPER 'sub-header.inc' %] - [% WRAPPER breadcrumbs %] - [% IF ( done_searched ) %] - [% WRAPPER breadcrumb_item %] - Serials - [% END %] - [% WRAPPER breadcrumb_item bc_active= 1 %] - Search results - [% END %] - [% ELSE %] - [% WRAPPER breadcrumb_item bc_active= 1 %] - Serials - [% END %] +[% WRAPPER 'sub-header.inc' %] + [% WRAPPER breadcrumbs %] + [% IF ( done_searched ) %] + [% WRAPPER breadcrumb_item %] + Serials [% END %] - [% END #/ WRAPPER breadcrumbs %] - [% END #/ WRAPPER sub-header.inc %] - - [% url_params = [] %] - [% FOREACH param IN CGI.params.pairs %] - [% escaped_value = BLOCK %][% param.value | uri %][% END %] - [% url_params.push(param.key _ '=' _ escaped_value) %] - [% END %] - - [% SET referrer = '/cgi-bin/koha/serials/serials-search.pl?' %] - [% referrer = BLOCK %][% referrer | url %][% url_params.join("&") |uri %][% END %] - [% SET edit_action_link = '/cgi-bin/koha/serials/subscription-batchedit.pl?referrer=' _ referrer %] - - [% BLOCK subscriptions_table %] -
            - [% INCLUDE 'csrf-token.inc' %] - [% IF closed %] - [% SET tab = 'closed' %] - [% ELSE %] - [% SET tab = 'opened' %] + [% WRAPPER breadcrumb_item bc_active= 1 %] + Search results [% END %] - [% IF CAN_user_serials_edit_subscription %] -
            - Select all - | - Clear all - - | Actions: - Edit selected serials - -
            + [% ELSE %] + [% WRAPPER breadcrumb_item bc_active= 1 %] + Serials [% END %] - - - - - - - - - - - [% UNLESS closed %] - - [% END %] - [% FOR field IN additional_fields_for_subscription %] - - [% END %] - - - - - [% FOREACH subscription IN subscriptions %] - [% UNLESS subscription.cannotdisplay %] - - - - - - - - - [% UNLESS closed %] - + [% END %] + [% END #/ WRAPPER breadcrumbs %] +[% END #/ WRAPPER sub-header.inc %] + +[% url_params = [] %] +[% FOREACH param IN CGI.params.pairs %] + [% escaped_value = BLOCK %][% param.value | uri %][% END %] + [% url_params.push(param.key _ '=' _ escaped_value) %] +[% END %] + +[% SET referrer = '/cgi-bin/koha/serials/serials-search.pl?' %] +[% referrer = BLOCK %][% referrer | url %][% url_params.join("&") |uri %][% END %] +[% SET edit_action_link = '/cgi-bin/koha/serials/subscription-batchedit.pl?referrer=' _ referrer %] + +[% BLOCK subscriptions_table %] +
            + [% INCLUDE 'csrf-token.inc' %] + [% IF closed %] + [% SET tab = 'closed' %] + [% ELSE %] + [% SET tab = 'opened' %] + [% END %] + [% IF CAN_user_serials_edit_subscription %] +
            + Select all + | + Clear all + + | Actions: + Edit selected serials + +
            + [% END %] +
            ISSNTitleNotesLibraryLocationCall numberExpiration date[% field.name | html %]Actions
            - [% UNLESS subscription.cannotedit %] - - [% ELSE %] - - [% END %] - - [% IF ( subscription.issn ) %] - [% subscription.issn | html %] - [% END %] - - [% subscription.title | html %] [% subscription.subtitle | html %] [% subscription.part_number | html %] [%subscription.part_name | html %] - - [% IF ( subscription.publicnotes ) %][% subscription.publicnotes | html %][% END %] - [% IF ( subscription.internalnotes ) %]([% subscription.internalnotes | html %])[% END %] - - [% IF ( subscription.branchcode ) %][% Branches.GetName( subscription.branchcode ) | html %][% END %] - - [% IF ( subscription.location ) %] - [% AuthorisedValues.GetDescriptionByKohaField( kohafield => 'items.location', authorised_value => subscription.location ) | html %] - [% END %] - - [% IF ( subscription.callnumber ) %][% subscription.callnumber | html %][% END %] - - [% subscription.enddate | $KohaDates %] -
            + + + + + + + + + + [% UNLESS closed %] + + [% END %] + [% FOR field IN additional_fields_for_subscription %] + + [% END %] + + + + + [% FOREACH subscription IN subscriptions %] + [% UNLESS subscription.cannotdisplay %] + + + + + + + + + [% UNLESS closed %] + + [% END %] - [% INCLUDE 'additional-fields-display.inc' available=additional_fields_for_subscription values=subscription.additional_field_values value_only=1 is_table_cell=1 %] + [% INCLUDE 'additional-fields-display.inc' available=additional_fields_for_subscription values=subscription.additional_field_values value_only=1 is_table_cell=1 %] - + + [% END # IF closed %] + + + + + [% END # /UNLESS subscription.cannotdisplay %] + [% END # /FOREACH subscription %] + + + + + + + + + + + [% SET column_num = 6 %] + [% UNLESS closed %] + + [% SET column_num = column_num + 1 %] + [% END %] + [% FOR field IN additional_fields_for_subscription %] + + [% END %] + + + +
            ISSNTitleNotesLibraryLocationCall numberExpiration date[% field.name | html %]Actions
            + [% UNLESS subscription.cannotedit %] + + [% ELSE %] + [% END %] + + [% IF ( subscription.issn ) %] + [% subscription.issn | html %] + [% END %] + + [% subscription.title | html %] [% subscription.subtitle | html %] [% subscription.part_number | html %] [% subscription.part_name | html %] + + [% IF ( subscription.publicnotes ) %][% subscription.publicnotes | html %][% END %] + [% IF ( subscription.internalnotes ) %]([% subscription.internalnotes | html %])[% END %] + [% IF ( subscription.branchcode ) %][% Branches.GetName( subscription.branchcode ) | html %][% END %] + [% IF ( subscription.location ) %] + [% AuthorisedValues.GetDescriptionByKohaField( kohafield => 'items.location', authorised_value => subscription.location ) | html %] + [% END %] + [% IF ( subscription.callnumber ) %][% subscription.callnumber | html %][% END %] [% subscription.enddate | $KohaDates %] -
            - [% IF closed %] - - Actions - - - [% ELSE %] -
            - [% IF ( CAN_user_serials_receive_serials ) %] - [%# There should be no space between these two buttons, it would render badly %] - Serial receive - [% ELSE %] - Actions +
            +
            + [% IF closed %] + Actions +
            -
            +
            +[% END # /BLOCK subscriptions_table %] - - [% END # /UNLESS subscription.cannotdisplay %] - [% END # /FOREACH subscription %] - - - - - - - - - - - [% SET column_num = 6 %] - [% UNLESS closed %] - - [% SET column_num = column_num + 1 %] - [% END %] - [% FOR field IN additional_fields_for_subscription %] - - [% END %] - - - - - - [% END # /BLOCK subscriptions_table %] +[% SET asides = ['serials-menu'] %] +[% IF done_searched && !mana %][% asides.unshift('serials-advsearch_brief') %][% END %] +[% WRAPPER 'main-container.inc' asides=asides %] - [% SET asides = ['serials-menu'] %] - [% IF done_searched && !mana %][% asides.unshift('serials-advsearch_brief') %][% END %] - [% WRAPPER 'main-container.inc' asides=asides %] + [% INCLUDE 'serials-toolbar.inc' %] - [% INCLUDE 'serials-toolbar.inc' %] + [% IF ( mana ) %] + [% IF ( done_searched ) %] +

            Mana subscriptions ([% total | html %] found)

            + [% ELSE %] +

            Mana subscriptions search

            + [% END %] + [% ELSE %] + [% IF ( done_searched ) %] + [% IF orig_total > total %] +
            +

            The search originally produced [% orig_total | html %] results and was limited to [% total | html %].

            +
            + [% END %] +

            Serials subscriptions ([% total | html %] found)

            + [% ELSE %] +

            Serials subscriptions search

            + [% END %] + [% END %] - [% IF ( mana ) %] - [% IF ( done_searched ) %] -

            Mana subscriptions ([% total | html %] found)

            - [% ELSE %] -

            Mana subscriptions search

            - [% END %] + [% UNLESS ( done_searched ) %] + [% INCLUDE 'serials-advsearch.inc' %] + [% END # /UNLESS ( done_searched ) %] + + [% IF ( done_searched ) %] + [% IF ( total ) %] + + [% WRAPPER tabs id= "serialstabs" %] + [% WRAPPER tabs_nav %] + [% IF mana %] + [% WRAPPER tab_item tabname= "mana" bt_active= 1 %]Mana ([% total || 0 | html %])[% END %] [% ELSE %] - [% IF ( done_searched ) %] - [% IF orig_total > total %] -
            -

            The search originally produced [% orig_total | html %] results and was limited to [% total | html %].

            + [% WRAPPER tab_item tabname= "opened" bt_active= 1 %]Open ([% openedsubscriptions.size || 0 | html %])[% END %] + [% WRAPPER tab_item tabname= "closed" %]Closed ([% closedsubscriptions.size || 0 | html %])[% END %] + [% END %] + [% END # /WRAPPER tabs_nav %] + [% WRAPPER tab_panels %] + [% IF mana %] + [% WRAPPER tab_panel tabname="mana" bt_active= 1 %] + [% INCLUDE 'mana/mana-subscription-search-result.inc' %] + [% END # /WRAPPER tab_panel#mana %] + [% ELSE %] + [% WRAPPER tab_panel tabname="opened" bt_active= 1 %] + [% IF openedsubscriptions %] + [% INCLUDE subscriptions_table subscriptions = openedsubscriptions %] + [% ELSE %] +
            +

            Your search returned no open subscriptions.

            [% END %] -

            Serials subscriptions ([% total | html %] found)

            - [% ELSE %] -

            Serials subscriptions search

            - [% END %] - [% END %] - - [% UNLESS ( done_searched ) %] - [% INCLUDE 'serials-advsearch.inc' %] - [% END # /UNLESS ( done_searched )%] - - [% IF ( done_searched ) %] - [% IF ( total ) %] - - [% WRAPPER tabs id= "serialstabs" %] - [% WRAPPER tabs_nav %] - [% IF mana %] - [% WRAPPER tab_item tabname= "mana" bt_active= 1 %] Mana ([% total || 0 | html %]) [% END %] - [% ELSE %] - [% WRAPPER tab_item tabname= "opened" bt_active= 1 %] Open ([% openedsubscriptions.size || 0 | html %]) [% END %] - [% WRAPPER tab_item tabname= "closed" %] Closed ([% closedsubscriptions.size || 0 | html %]) [% END %] - [% END %] - [% END # /WRAPPER tabs_nav %] - [% WRAPPER tab_panels %] - [% IF mana %] - [% WRAPPER tab_panel tabname="mana" bt_active= 1 %] - [% INCLUDE 'mana/mana-subscription-search-result.inc' %] - [% END # /WRAPPER tab_panel#mana %] - [% ELSE %] - [% WRAPPER tab_panel tabname="opened" bt_active= 1 %] - [% IF openedsubscriptions %] - [% INCLUDE subscriptions_table subscriptions = openedsubscriptions %] - [% ELSE %] -
            -

            Your search returned no open subscriptions.

            -
            - [% END %] - [% END # /WRAPPER tab_panel#opened %] - [% WRAPPER tab_panel tabname="closed" %] - [% IF closedsubscriptions %] - [% INCLUDE subscriptions_table subscriptions = closedsubscriptions closed = 1 %] - [% ELSE %] -
            -

            Your search returned no closed subscriptions.

            -
            - [% END %] - [% END # /WRAPPER tab_panel#closed %] - [% END # /IF mana %] - [% END # /WRAPPER tab_panels %] - [% END # /WRAPPER tabs#serialstabs %] - - [% ELSE %] -
            -

            Your search returned no results.

            -
            - [% END # IF ( total ) %] - [% END # /IF done_searched %] - - [% END %] + [% END # /WRAPPER tab_panel#opened %] + [% WRAPPER tab_panel tabname="closed" %] + [% IF closedsubscriptions %] + [% INCLUDE subscriptions_table subscriptions = closedsubscriptions closed = 1 %] + [% ELSE %] +
            +

            Your search returned no closed subscriptions.

            +
            + [% END %] + [% END # /WRAPPER tab_panel#closed %] + [% END # /IF mana %] + [% END # /WRAPPER tab_panels %] + [% END # /WRAPPER tabs#serialstabs %] + [% ELSE %] +
            +

            Your search returned no results.

            +
            + [% END # IF ( total ) %] + [% END # /IF done_searched %] +[% END %] [% MACRO jsinclude BLOCK %] [% INCLUDE 'calendar.inc' %] @@ -302,7 +308,6 @@ [% Asset.js("js/serials-toolbar.js") | $raw %] -[% END %] + + [% END %] -[% INCLUDE 'intranet-bottom.inc' popup_window=1 %] + [% INCLUDE 'intranet-bottom.inc' popup_window=1 %] +
            diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/serials/viewalerts.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/serials/viewalerts.tt index c8a8e87037..a5a3581f8b 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/serials/viewalerts.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/serials/viewalerts.tt @@ -2,12 +2,12 @@ [% USE Koha %] [% PROCESS 'i18n.inc' %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Alert subscribers") | html %] › - [% bibliotitle | html %] › - [% t("Serials") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Alert subscribers") | html %] + › [% bibliotitle | html %] › [% t("Serials") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -30,32 +30,28 @@ [% END #/ WRAPPER sub-header.inc %] [% WRAPPER 'main-container.inc' aside='serials-menu' %] +

            Alert subscribers for [% bibliotitle | html %]

            +

            Subscription: [% bibliotitle | html %] #[% subscriptionid | html %]

            -

            Alert subscribers for [% bibliotitle | html %]

            -

            - Subscription: [% bibliotitle | html %] #[% subscriptionid | html %] -

            - -
            - - [% IF subscribers.count %] - - - - - [% FOREACH subscriber IN subscribers %] - - - - [% END %] -
            Patron name
            - [% INCLUDE 'patron-title.inc' patron=subscriber %] -
            - [% ELSE %] -

            There are no patrons subscribed to this subscription serial alert.

            - [% END %] -
            - +
            + [% IF subscribers.count %] + + + + + [% FOREACH subscriber IN subscribers %] + + + + [% END %] +
            Patron name
            + [% INCLUDE 'patron-title.inc' patron=subscriber %] +
            + [% ELSE %] +

            There are no patrons subscribed to this subscription serial alert.

            + [% END %] +
            + [% END %] [% INCLUDE 'intranet-bottom.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/services/itemrecorddisplay.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/services/itemrecorddisplay.tt index 89ea3838ef..412ba08f89 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/services/itemrecorddisplay.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/services/itemrecorddisplay.tt @@ -1,33 +1,33 @@ [% USE raw %]
              - [% FOREACH iteminfo IN iteminformation %] -
            1. -
              - [% IF (iteminfo.mandatory) %] - - [% ELSE %] - - [% END %] - [% IF ( iteminfo.marc_value.type == 'select' ) %] - - [% ELSE %] - [% iteminfo.marc_value | $raw %] - [% END %] - - - - - - [% IF (iteminfo.mandatory) %] Required[% END %] -
              -
            2. - [% END %] + [% FOREACH iteminfo IN iteminformation %] +
            3. +
              + [% IF (iteminfo.mandatory) %] + + [% ELSE %] + + [% END %] + [% IF ( iteminfo.marc_value.type == 'select' ) %] + + [% ELSE %] + [% iteminfo.marc_value | $raw %] + [% END %] + + + + + + [% IF (iteminfo.mandatory) %]Required[% END %] +
              +
            4. + [% END %]
            diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/suggestion/suggestion.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/suggestion/suggestion.tt index edc4e9c190..98d7c5df35 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/suggestion/suggestion.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/suggestion/suggestion.tt @@ -9,20 +9,24 @@ [% PROCESS 'patron-search.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% IF op == 'save' %] - [% IF ( suggestionid ) %] - [% tx("Edit suggestion #{suggestion_number}", { suggestion_number = suggestionid }) | html %] › - [% ELSE %] - [% t("Add suggestion") | html %] › +<title + >[% FILTER collapse %] + [% IF op == 'save' %] + [% IF ( suggestionid ) %] + [% tx("Edit suggestion #{suggestion_number}", { suggestion_number = suggestionid }) | html %] + › + [% ELSE %] + [% t("Add suggestion") | html %] + › + [% END %] + [% ELSIF ( op == 'show' ) %] + [% tx("Show suggestion #{suggestion_number}", { suggestion_number = suggestionid }) | html %] + › [% END %] - [% ELSIF ( op == 'show' ) %] - [% tx("Show suggestion #{suggestion_number}", { suggestion_number = suggestionid }) | html %] › - [% END %] - [% t("Suggestions") | html %] › - [% t("Acquisitions") | html %] › - [% t("Koha") | html %] -[% END %] + [% t("Suggestions") | html %] + › [% t("Acquisitions") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] [% IF op == 'else' %] [% FILTER collapse %] @@ -42,7 +46,7 @@ left: 50%; margin-left: -100px; margin-top: -10px; - padding: .5em; + padding: 0.5em; position: absolute; text-align: center; top: 180px; @@ -54,861 +58,1124 @@ - [% WRAPPER 'header.inc' %] - [% INCLUDE 'cat-search.inc' %] - [% END %] +[% WRAPPER 'header.inc' %] + [% INCLUDE 'cat-search.inc' %] +[% END %] - [% WRAPPER 'sub-header.inc' %] - [% WRAPPER breadcrumbs %] +[% WRAPPER 'sub-header.inc' %] + [% WRAPPER breadcrumbs %] + [% WRAPPER breadcrumb_item %] + Acquisitions + [% END %] + [% IF ( op == 'save' || op == 'show' ) %] [% WRAPPER breadcrumb_item %] - Acquisitions + Suggestions [% END %] - [% IF ( op == 'save' || op == 'show' ) %] - [% WRAPPER breadcrumb_item %] - Suggestions - [% END %] - [% END %] - [% IF op == 'save' %] - [% IF ( suggestionid ) %] - [% WRAPPER breadcrumb_item bc_active= 1 %] - Edit suggestion #[% suggestionid | html %] - [% END %] - [% ELSE %] - [% WRAPPER breadcrumb_item bc_active= 1 %] - Add suggestion - [% END %] - [% END %] - [% ELSIF ( op == 'show' ) %] + [% END %] + [% IF op == 'save' %] + [% IF ( suggestionid ) %] [% WRAPPER breadcrumb_item bc_active= 1 %] - Show suggestion #[% suggestionid | html %] + Edit suggestion #[% suggestionid | html %] [% END %] [% ELSE %] [% WRAPPER breadcrumb_item bc_active= 1 %] - Suggestions management + Add suggestion [% END %] [% END %] - [% END #/ WRAPPER breadcrumbs %] - [% END #/ WRAPPER sub-header.inc %] - - [% IF ( op == 'show' ) %] -
            -
            -
            - [% INCLUDE 'messages.inc' %] - -
            - [% IF CAN_user_suggestions_suggestions_manage %] - Edit - [% END %] - [% IF CAN_user_suggestions_suggestions_delete %] -
            - [% INCLUDE 'csrf-token.inc' %] - - - -
            - [% END %] -
            - -
            - Bibliographic information -
              - [% IF ( title ) %] -
            1. - Title: - [% IF suggestion.biblionumber %] - [% suggestion.title | html %] - [% ELSE %] - [% title | html %] - [% END %] -
            2. - [% END %] - [% IF ( author ) %] -
            3. - Author: - [% author | html %] -
            4. - [% END %] - [% IF ( copyrightdate ) %] -
            5. - Copyright date: - [% copyrightdate | html %] -
            6. - [% END %] - [% IF ( isbn ) %] -
            7. - ISBN or ISSN or other standard number: - [% isbn | html %] -
            8. - [% END %] - [% IF ( publishercode ) %] -
            9. - Publisher: - [% publishercode | html %] -
            10. - [% END %] - [% IF ( place ) %] -
            11. - Publication place: - [% place | html %] -
            12. - [% END %] - [% IF ( collectiontitle ) %] -
            13. - Collection title: - [% collectiontitle | html %] -
            14. - [% END %] - [% IF ( itemtype ) %] -
            15. - Document type: - [% AuthorisedValues.GetByCode( 'SUGGEST_FORMAT', itemtype, 0 ) | html %] -
            16. - [% END %] - [% IF ( patron_reason_loop ) %] -
            17. - Reason for suggestion: - [% FOREACH patron_reason_loo IN patron_reason_loop %] - [% IF patron_reason_loo.authorised_value == patronreason %] - [% patron_reason_loo.lib | html %] - [% END %] - [% END %] -
            18. - [% END %] - [% IF ( note ) %] -
            19. - Notes: - [% note | html %] -
            20. - [% END %] - [% IF ( staff_note ) %] -
            21. - Notes: - [% staff_note | html %] -
            22. - [% END %] -
            -
            - -
            - Suggestion management -
              -
            1. - Status: - [% SET status_found = 0 %] - [% IF ( STATUS == 'ASKED' ) %] - Pending - [% SET status_found = 1 %] - [% ELSIF ( STATUS == 'ACCEPTED' ) %] - Accepted - [% SET status_found = 1 %] - [% ELSIF ( STATUS == 'CHECKED' ) %] - Checked - [% SET status_found = 1 %] - [% ELSIF ( STATUS == 'REJECTED' ) %] - Rejected - [% SET status_found = 1 %] - [% ELSIF ( STATUS == 'ORDERED' ) %] - Ordered - [% SET status_found = 1 %] - [% ELSIF ( STATUS == 'AVAILABLE' ) %] - Available - [% SET status_found = 1 %] - [% ELSE %] - [% FOREACH s IN SuggestionStatuses %] - [% IF STATUS == s.authorised_value %] - [% s.lib | html %] - [% SET status_found = 1 %] - [% END %] - [% END %] - [% END %] -
            2. -
            3. - Reason: - [% IF ( reason ) %] - [% AuthorisedValues.GetByCode( 'SUGGEST', reason, 0 ) | html %] - [% END %] -
            4. -
            - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
             DateBy
            [% tp('purchase suggestion created by', 'Created by:') | html %][% suggesteddate | $KohaDates %] - [% IF ( suggestedby_patron.borrowernumber ) %] - [% suggestedby_patron.surname | html %], [% suggestedby_patron.firstname | html %] ([% suggestedby_patron.cardnumber | html %]) - [% Branches.GetName( suggestedby_patron.branchcode ) | html %] ([% suggestedby_patron.category.description | html %]) - [% END %] -
            Managed by:[% manageddate | $KohaDates %] - [% IF ( managedby_patron.borrowernumber ) %] - [% managedby_patron.surname | html %], [% managedby_patron.firstname | html %] ([% managedby_patron.cardnumber | html %]) - [% Branches.GetName( managedby_patron.branchcode ) | html %] ([% managedby_patron.category.description | html %]) - [% END %] -
            Accepted on:[% accepteddate | $KohaDates %] - [% IF ( acceptedby_patron.borrowernumber ) %] - [% acceptedby_patron.surname | html %], [% acceptedby_patron.firstname | html %] ([% acceptedby_patron.cardnumber | html %]) - [% Branches.GetName( acceptedby_patron.branchcode ) | html %] ([% acceptedby_patron.category.description | html %]) - [% END %] -
            Last modification on:[% lastmodificationdate | $KohaDates %] - [% IF ( lastmodificationby_patron.borrowernumber ) %] - [% lastmodificationby_patron.surname | html %], [% lastmodificationby_patron.firstname | html %] ([% lastmodificationby_patron.cardnumber | html %]) - [% Branches.GetName( lastmodificationby_patron.branchcode ) | html %] ([% lastmodificationby_patron.category.description | html %]) - [% END %] -
            -
            - -
            - Acquisition information -
              -
            1. - Library: - [% Branches.GetName( branchcode ) | html %] -
            2. -
            3. - Fund: - [% budgetname | html %] -
            4. -
            5. - Copies: - [% quantity | html %] -
            6. -
            7. - Currency: - [% currency | html %] -
            8. -
            9. - Price: - [% price | $Price %] -
            10. -
            11. - Total - [% total | $Price %] -
            12. -
            -
            - -
            - << Back to suggestions -
            - -
            -
            -
            - [% ELSE # IF op == "show" %] - - [% IF op == 'save' %] - [% SET div_class = "col-md-8 offset-md-2" %] + [% ELSIF ( op == 'show' ) %] + [% WRAPPER breadcrumb_item bc_active= 1 %] + Show suggestion #[% suggestionid | html %] + [% END %] [% ELSE %] - [% SET div_class = "col-md-10 order-md-2 order-sm-1" %] - [% END %] -
            -
            -
            - [% INCLUDE 'messages.inc' %] - - [% IF op == 'save' %] - [% FOR m IN messages %] -
            - [% SWITCH m.code %] - [% CASE 'biblio_exists' %] - A similar document already exists: [% m.title | html %]. Click on "Confirm your suggestion" to ignore this message. - [% CASE 'manager_not_enough_permissions' %] - The manager you selected does not have sufficient permissions. - [% CASE 'no_manage_permission' %] - You do not have permissions to manage suggestions - [% CASE 'no_create_permission' %] - You do not have permissions to create suggestions - [% CASE 'no_delete_permission' %] - You do not have permissions to delete suggestions - [% CASE %] - [% m.code | html %] - [% END %] -
            + [% WRAPPER breadcrumb_item bc_active= 1 %] + Suggestions management [% END %] + [% END %] + [% END #/ WRAPPER breadcrumbs %] +[% END #/ WRAPPER sub-header.inc %] -
            - [% INCLUDE 'csrf-token.inc' %] - - - [% IF ( suggestionid ) %] -

            Edit purchase suggestion #[% suggestionid | html %]

            - - [% ELSE %] -

            Enter a new purchase suggestion

            - [% END %] +[% IF ( op == 'show' ) %] +
            +
            +
            + [% INCLUDE 'messages.inc' %] + +
            + [% IF CAN_user_suggestions_suggestions_manage %] + Edit + [% END %] + [% IF CAN_user_suggestions_suggestions_delete %] + + [% INCLUDE 'csrf-token.inc' %] + + + + + [% END %] +
            Bibliographic information
              -
            1. - - - Required -
            2. -
            3. - - -
            4. -
            5. - - -
            6. -
            7. - - -
            8. -
            9. - - -
            10. -
            11. - - -
            12. -
            13. - - -
            14. -
            15. - - [% PROCESS 'av-build-dropbox.inc' name="itemtype", category="SUGGEST_FORMAT", size=20, default=itemtype, empty=1 %] -
            16. - [% IF patron_reason_loop %] + [% IF ( title ) %]
            17. - - + Title: + [% IF suggestion.biblionumber %] + [% suggestion.title | html %] + [% ELSE %] + [% title | html %] + [% END %]
            18. - [% END # /IF patron_reason_loop %] -
            19. - - -
            20. -
            21. - - -
            22. + [% END %] + [% IF ( author ) %] +
            23. + Author: + [% author | html %] +
            24. + [% END %] + [% IF ( copyrightdate ) %] +
            25. + Copyright date: + [% copyrightdate | html %] +
            26. + [% END %] + [% IF ( isbn ) %] +
            27. + ISBN or ISSN or other standard number: + [% isbn | html %] +
            28. + [% END %] + [% IF ( publishercode ) %] +
            29. + Publisher: + [% publishercode | html %] +
            30. + [% END %] + [% IF ( place ) %] +
            31. + Publication place: + [% place | html %] +
            32. + [% END %] + [% IF ( collectiontitle ) %] +
            33. + Collection title: + [% collectiontitle | html %] +
            34. + [% END %] + [% IF ( itemtype ) %] +
            35. + Document type: + [% AuthorisedValues.GetByCode( 'SUGGEST_FORMAT', itemtype, 0 ) | html %] +
            36. + [% END %] + [% IF ( patron_reason_loop ) %] +
            37. + Reason for suggestion: + [% FOREACH patron_reason_loo IN patron_reason_loop %] + [% IF patron_reason_loo.authorised_value == patronreason %] + [% patron_reason_loo.lib | html %] + [% END %] + [% END %] +
            38. + [% END %] + [% IF ( note ) %] +
            39. + Notes: + [% note | html %] +
            40. + [% END %] + [% IF ( staff_note ) %] +
            41. + Notes: + [% staff_note | html %] +
            42. + [% END %]
            Suggestion management
              - [% IF ( suggestionid ) %] -
            1. - - -
            2. -
            3. - - - - - [% IF other_reason %] - - [% ELSE %] - - [% END %] - Cancel - -
            4. - [% END %]
            5. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
               DateByAction
              - - - [% INCLUDE 'date-format.inc' %] - - - [% IF ( suggestedby_patron.borrowernumber ) %] - [% suggestedby_patron.surname | html %], [% suggestedby_patron.firstname | html %] ([% suggestedby_patron.cardnumber | html %]) [% Branches.GetName( suggestedby_patron.branchcode ) | html %] ([% suggestedby_patron.category.description | html %]) - [% END %] - - Set to patron -
              - - - [% INCLUDE 'date-format.inc' %] - - - [% IF ( acceptedby_patron.borrowernumber ) %] - [% acceptedby_patron.surname | html %], [% acceptedby_patron.firstname | html %] ([% acceptedby_patron.cardnumber | html %]) - [% Branches.GetName( acceptedby_patron.branchcode ) | html %] ([% acceptedby_patron.category.description | html %]) - [% END %] -
              - - - [% lastmodificationdate | $KohaDates %] - - [% IF lastmodificationby_patron %] - [% INCLUDE 'patron-title.inc' patron=lastmodificationby_patron hide_patron_infos_if_needed=1 %] [% Branches.GetName( lastmodificationby_patron.branchcode ) | html %] ([% lastmodificationby_patron.category.description | html %]) - [% END %] -
              + Status: + [% SET status_found = 0 %] + [% IF ( STATUS == 'ASKED' ) %] + Pending + [% SET status_found = 1 %] + [% ELSIF ( STATUS == 'ACCEPTED' ) %] + Accepted + [% SET status_found = 1 %] + [% ELSIF ( STATUS == 'CHECKED' ) %] + Checked + [% SET status_found = 1 %] + [% ELSIF ( STATUS == 'REJECTED' ) %] + Rejected + [% SET status_found = 1 %] + [% ELSIF ( STATUS == 'ORDERED' ) %] + Ordered + [% SET status_found = 1 %] + [% ELSIF ( STATUS == 'AVAILABLE' ) %] + Available + [% SET status_found = 1 %] + [% ELSE %] + [% FOREACH s IN SuggestionStatuses %] + [% IF STATUS == s.authorised_value %] + [% s.lib | html %] + [% SET status_found = 1 %] + [% END %] + [% END %] + [% END %]
            6. - - [% INCLUDE 'date-format.inc' %] -
            7. -
            8. - -
              - - [% IF CAN_user_suggestions_suggestions_manage %] - You - [% ELSE %] - Nobody - [% END %] - - [% IF managedby_patron.borrowernumber && logged_in_user.borrowernumber != managedby_patron.borrowernumber %] - | Previously was [% INCLUDE 'patron-title.inc' patron=managedby_patron hide_patron_infos_if_needed=1 %] [% Branches.GetName( managedby_patron.branchcode ) | html %] ([% managedby_patron.category.description | html %]) - [% END %] -
              - Select manager - [% IF managedby_patron.borrowernumber && logged_in_user.borrowernumber != managedby_patron.borrowernumber %] - Keep existing manager - [% END %] - [% IF CAN_user_suggestions_suggestions_manage %] - - [% END %] - -
              - - -
              + Reason: + [% IF ( reason ) %] + [% AuthorisedValues.GetByCode( 'SUGGEST', reason, 0 ) | html %] + [% END %]
            + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
             DateBy
            [% tp('purchase suggestion created by', 'Created by:') | html %][% suggesteddate | $KohaDates %] + [% IF ( suggestedby_patron.borrowernumber ) %] + [% suggestedby_patron.surname | html %], [% suggestedby_patron.firstname | html %] ([% suggestedby_patron.cardnumber | html %]) + [% Branches.GetName( suggestedby_patron.branchcode ) | html %] ([% suggestedby_patron.category.description | html %]) + [% END %] +
            Managed by:[% manageddate | $KohaDates %] + [% IF ( managedby_patron.borrowernumber ) %] + [% managedby_patron.surname | html %], [% managedby_patron.firstname | html %] ([% managedby_patron.cardnumber | html %]) + [% Branches.GetName( managedby_patron.branchcode ) | html %] ([% managedby_patron.category.description | html %]) + [% END %] +
            Accepted on:[% accepteddate | $KohaDates %] + [% IF ( acceptedby_patron.borrowernumber ) %] + [% acceptedby_patron.surname | html %], [% acceptedby_patron.firstname | html %] ([% acceptedby_patron.cardnumber | html %]) + [% Branches.GetName( acceptedby_patron.branchcode ) | html %] ([% acceptedby_patron.category.description | html %]) + [% END %] +
            Last modification on:[% lastmodificationdate | $KohaDates %] + [% IF ( lastmodificationby_patron.borrowernumber ) %] + [% lastmodificationby_patron.surname | html %], [% lastmodificationby_patron.firstname | html %] ([% lastmodificationby_patron.cardnumber | html %]) + [% Branches.GetName( lastmodificationby_patron.branchcode ) | html %] ([% lastmodificationby_patron.category.description | html %]) + [% END %] +
            Acquisition information
            1. - - + Library: + [% Branches.GetName( branchcode ) | html %]
            2. - [% PROCESS funds_dropdown %] + Fund: + [% budgetname | html %]
            3. - - + Copies: + [% quantity | html %]
            4. - - [% FOREACH c IN currencies %] - - - [% END %] - + Currency: + [% currency | html %]
            5. - - + Price: + [% price | $Price %]
            6. - - + Total + [% total | $Price %]
            -
            +
            - - [% IF ( suggestionid ) %] - - [% IF ( need_confirm ) %] - - - [% ELSE %] - - [% END %] - Cancel - [% ELSE %] - - [% IF ( need_confirm ) %] - - - [% ELSE %] - - [% END %] - Cancel - [% END %] -
            - - [% END %] - - [% IF op == 'else' %] -
            - [% IF CAN_user_suggestions_suggestions_create %] - New purchase suggestion - [% END %] + << Back to suggestions +
            + + + + + +[% ELSE # IF op == "show" %] -

            Suggestions management

            + [% IF op == 'save' %] + [% SET div_class = "col-md-8 offset-md-2" %] + [% ELSE %] + [% SET div_class = "col-md-10 order-md-2 order-sm-1" %] + [% END %] +
            +
            +
            + [% INCLUDE 'messages.inc' %] - [% IF ( displayby != "branchcode" ) %] - - - [% END %] - - [% FOR m IN messages %] -
            - [% SWITCH m.code %] - [% CASE 'already_exists' %] - The suggestion has not been added. A suggestion with this title already exists (suggestion #[% m.id | html %]) - [% CASE 'biblio_exists' %] - A similar document already exists: [% m.title | html %]. Click on "Confirm your suggestion" to ignore this message. - [% CASE %] - [% m.code | html %] - [% END %] -
            - [% END # /FOR m %] - - [% WRAPPER tabs id= "suggestiontabs" %] - [% WRAPPER tabs_nav %] - [% FOREACH suggestion IN suggestions %] - [% WRAPPER tab_item tabname= suggestion.suggestiontype %] - [% IF ( suggestion.suggestiontypelabel ) %] - [% IF (suggestion.suggestiontypelabel == "Pending") %]Pending - [% ELSIF (suggestion.suggestiontypelabel == "Accepted") %]Accepted - [% ELSIF (suggestion.suggestiontypelabel == "Checked") %]Checked - [% ELSIF (suggestion.suggestiontypelabel == "Rejected") %]Rejected - [% ELSIF (suggestion.suggestiontypelabel == "Available") %]Available - [% ELSIF (suggestion.suggestiontypelabel == "Ordered") %]Ordered - [% ELSIF (suggestion.suggestiontypelabel == "Unknown") %]Status unknown - [% ELSIF (suggestion.suggestiontypelabel == "__ANY__") %]Any - [% ELSE %][% suggestion.suggestiontypelabel | html %][% END %] - [% ELSE %] - [% IF ( suggestion.suggestiontype ) %] - [% AuthorisedValues.GetByCode( 'SUGGEST_STATUS', suggestion.suggestiontype ) | html %] - [% ELSE %] - No name - [% END %] + [% IF op == 'save' %] + [% FOR m IN messages %] +
            + [% SWITCH m.code %] + [% CASE 'biblio_exists' %] + A similar document already exists: [% m.title | html %]. Click on "Confirm your suggestion" to ignore this message. + [% CASE 'manager_not_enough_permissions' %] + The manager you selected does not have sufficient permissions. + [% CASE 'no_manage_permission' %] + You do not have permissions to manage suggestions + [% CASE 'no_create_permission' %] + You do not have permissions to create suggestions + [% CASE 'no_delete_permission' %] + You do not have permissions to delete suggestions + [% CASE %] + [% m.code | html %] [% END %] - ([% suggestion.suggestions.size| html %]) +
            + + [% END %] + +
            + [% INCLUDE 'csrf-token.inc' %] + + + [% IF ( suggestionid ) %] +

            Edit purchase suggestion #[% suggestionid | html %]

            + + [% ELSE %] +

            Enter a new purchase suggestion

            [% END %] - [% END # /FOREACH suggestion %] - [% END # /WRAPPER tabs_nav %] - [% WRAPPER tab_panels %] - [% FOREACH suggestion IN suggestions %] - [% WRAPPER tab_panel tabname= suggestion.suggestiontype %] - - [% INCLUDE 'csrf-token.inc' %] - [%# filled by click event %] - -
            -
            - [% INCLUDE 'csrf-token.inc' %] - [%# filled by submit %] +
            + Bibliographic information +
              +
            1. + + + Required +
            2. +
            3. + + +
            4. +
            5. + + +
            6. +
            7. + + +
            8. +
            9. + + +
            10. +
            11. + + +
            12. +
            13. + + +
            14. +
            15. + + [% PROCESS 'av-build-dropbox.inc' name="itemtype", category="SUGGEST_FORMAT", size=20, default=itemtype, empty=1 %] +
            16. + [% IF patron_reason_loop %] +
            17. + + +
            18. + [% END # /IF patron_reason_loop %] +
            19. + + +
            20. +
            21. + + +
            22. +
            +
            - [% IF suggestion.suggestions.size %] -

            - Check all | Uncheck all -

            +
            + Suggestion management +
              + [% IF ( suggestionid ) %] +
            1. + + +
            2. +
            3. + + + + + [% IF other_reason %] + + [% ELSE %] + + [% END %] + Cancel + +
            4. + [% END %] +
            5. + - - - - - - - - - - - - - - - - + + + + - [% FOREACH s IN suggestion.suggestions %] - - - - - - - - - - - - - - - - - - - [% END # /FOREACH s %] + + + + + + + + + + + + + + + + + + -
               SuggestionSuggested bySuggester categorySuggested onPatron reasonManaged byManaged onLast modification byLast modification onLast updatedLibraryFundNon-public noteStatus  DateByAction
              - - - - [% s.title | html %][% IF ( s.author ) %], by [% s.author | html %][% END %] - -
              - [% IF ( s.copyrightdate ) %] - © [% s.copyrightdate | html %] - [% END %] - [% IF ( s.volumedesc ) %] - ; Volume:[% s.volumedesc | html %] - [% END %] - [% IF ( s.isbn ) %] - ; ISBN: [% s.isbn | html %] - [% END %] - [% IF ( s.publishercode ) %] - ; Published by [% s.publishercode | html %] - [% END %] - [% IF ( s.publicationyear ) %] - in [% s.publicationyear | html %] - [% END %] - [% IF ( s.place ) %] - in [% s.place | html %] - [% END %] - [% IF ( s.collectiontitle ) %] - ; [% s.collectiontitle | html %] - [% END %] - [% IF ( s.itemtype ) %] - ; [% AuthorisedValues.GetByCode( 'SUGGEST_FORMAT', s.itemtype, 0 ) | html %] - [% END %] -
              - [% IF ( s.note ) %] -
              [% s.note | html %]
              - [% END %] - [% IF s.archived %] -
              Archived - [% END %] -
              - [% SET suggester = s.suggester %] - [% suggester.surname | html %][% IF suggester.firstname %], [% suggester.firstname | html %][% END %] [% IF suggester.cardnumber %]([% suggester.cardnumber | html %])[% END %] - - [% suggester.category.description | html %] - - [% IF ( s.suggesteddate ) %][% s.suggesteddate | $KohaDates %][% END %] - [% AuthorisedValues.GetByCode( 'OPAC_SUG', s.patronreason ) | html %] - [% SET manager = s.manager %] - [% manager.surname | html %][% IF manager.firstname %], [% manager.firstname | html %][% END %] - - [% IF ( s.manageddate ) %][% s.manageddate | $KohaDates %][% END %] - - [% SET last_modifier = s.last_modifier %] - [% last_modifier.surname | html %][% IF last_modifier.firstname %], [% last_modifier.firstname | html %][% END %] - - [% IF ( s.lastmodificationdate ) %][% s.lastmodificationdate | $KohaDates %][% END %] - - [% s.lastmodificationdate | $KohaDates %] - - [% Branches.GetName( s.branchcode ) | html %] - - [% s.fund.budget_name | html %] - - [% s.staff_note | html %] - - [% IF s.STATUS == 'ASKED' %] - Pending - [% ELSIF s.STATUS == 'ACCEPTED' %] - Accepted - [% ELSIF s.STATUS == 'ORDERED' %] - Ordered - [% ELSIF s.STATUS == 'REJECTED' %] - Rejected - [% ELSIF s.STATUS == 'CHECKED' %] - Checked - [% ELSIF s.STATUS == 'AVAILABLE' %] - Available - [% ELSIF AuthorisedValues.GetByCode( 'SUGGEST_STATUS', s.STATUS ) %] - [% AuthorisedValues.GetByCode( 'SUGGEST_STATUS', s.STATUS ) | html %] - [% ELSE %] - Status unknown - [% END %] - - [% IF ( s.reason ) %] -
              ([% s.reason | html %]) - [% END %] -
              - [% IF CAN_user_suggestions_suggestions_manage %] -
              - Edit - -
              - [% ELSIF CAN_user_suggestions_suggestions_delete %] - - [% END %] -
              + + [% INCLUDE 'date-format.inc' %] + + [% IF ( suggestedby_patron.borrowernumber ) %] + [% suggestedby_patron.surname | html %], [% suggestedby_patron.firstname | html %] ([% suggestedby_patron.cardnumber | html %]) + [% Branches.GetName( suggestedby_patron.branchcode ) | html %] ([% suggestedby_patron.category.description | html %]) + [% END %] + + Set to patron +
              + + [% INCLUDE 'date-format.inc' %] + + [% IF ( acceptedby_patron.borrowernumber ) %] + [% acceptedby_patron.surname | html %], [% acceptedby_patron.firstname | html %] ([% acceptedby_patron.cardnumber | html %]) + [% Branches.GetName( acceptedby_patron.branchcode ) | html %] ([% acceptedby_patron.category.description | html %]) + [% END %] +
              + + [% lastmodificationdate | $KohaDates %] + [% IF lastmodificationby_patron %] + [% INCLUDE 'patron-title.inc' patron=lastmodificationby_patron hide_patron_infos_if_needed=1 %] + [% Branches.GetName( lastmodificationby_patron.branchcode ) | html %] + ([% lastmodificationby_patron.category.description | html %]) + [% END %] +
              - -
              -
              -

              Change selected suggestions

              -
              -
              -
              + +
            6. +
            7. + + [% INCLUDE 'date-format.inc' %] +
            8. +
            9. + +
              + + [% IF CAN_user_suggestions_suggestions_manage %] + You + [% ELSE %] + Nobody + [% END %] + + [% IF managedby_patron.borrowernumber && logged_in_user.borrowernumber != managedby_patron.borrowernumber %] + | Previously was [% INCLUDE 'patron-title.inc' patron=managedby_patron hide_patron_infos_if_needed=1 %] [% Branches.GetName( managedby_patron.branchcode ) | html %] + ([% managedby_patron.category.description | html %]) + [% END %] +
              + Select manager + [% IF managedby_patron.borrowernumber && logged_in_user.borrowernumber != managedby_patron.borrowernumber %] + Keep existing manager + [% END %] [% IF CAN_user_suggestions_suggestions_manage %] -
              -
              -
              - - + [% END %] +
              + + +
              + +
            10. +
            +
            + +
            + Acquisition information +
              +
            1. + + +
            2. +
            3. [% PROCESS funds_dropdown %]
            4. +
            5. + + +
            6. +
            7. + + [% FOREACH c IN currencies %] + + + [% END %] + +
            8. +
            9. + + +
            10. +
            11. + + +
            12. +
            +
            + + +
            + + [% IF ( suggestionid ) %] + + [% IF ( need_confirm ) %] + + + [% ELSE %] + + [% END %] + Cancel + [% ELSE %] + + [% IF ( need_confirm ) %] + + + [% ELSE %] + + [% END %] + Cancel + [% END %] +
            + +
            + + [% END %] + + [% IF op == 'else' %] +
            + [% IF CAN_user_suggestions_suggestions_create %] + New purchase suggestion + [% END %] +
            + +

            Suggestions management

            + + [% IF ( displayby != "branchcode" ) %] + + + [% END %] + + [% FOR m IN messages %] +
            + [% SWITCH m.code %] + [% CASE 'already_exists' %] + The suggestion has not been added. A suggestion with this title already exists (suggestion #[% m.id | html %]) + [% CASE 'biblio_exists' %] + A similar document already exists: [% m.title | html %]. Click on "Confirm your suggestion" to ignore this message. + [% CASE %] + [% m.code | html %] + [% END %] +
            + + [% END # /FOR m %] + + [% WRAPPER tabs id= "suggestiontabs" %] + [% WRAPPER tabs_nav %] + [% FOREACH suggestion IN suggestions %] + [% WRAPPER tab_item tabname= suggestion.suggestiontype %] + [% IF ( suggestion.suggestiontypelabel ) %] + [% IF (suggestion.suggestiontypelabel == "Pending") %] + Pending + [% ELSIF (suggestion.suggestiontypelabel == "Accepted") %] + Accepted + [% ELSIF (suggestion.suggestiontypelabel == "Checked") %] + Checked + [% ELSIF (suggestion.suggestiontypelabel == "Rejected") %] + Rejected + [% ELSIF (suggestion.suggestiontypelabel == "Available") %] + Available + [% ELSIF (suggestion.suggestiontypelabel == "Ordered") %] + Ordered + [% ELSIF (suggestion.suggestiontypelabel == "Unknown") %] + Status unknown + [% ELSIF (suggestion.suggestiontypelabel == "__ANY__") %] + Any + [% ELSE %] + [% suggestion.suggestiontypelabel | html %] + [% END %] + [% ELSE %] + [% IF ( suggestion.suggestiontype ) %] + [% AuthorisedValues.GetByCode( 'SUGGEST_STATUS', suggestion.suggestiontype ) | html %] + [% ELSE %] + No name + [% END %] + [% END %] + ([% suggestion.suggestions.size| html %]) + [% END %] + [% END # /FOREACH suggestion %] + [% END # /WRAPPER tabs_nav %] + + [% WRAPPER tab_panels %] + [% FOREACH suggestion IN suggestions %] + [% WRAPPER tab_panel tabname= suggestion.suggestiontype %] +
            + [% INCLUDE 'csrf-token.inc' %] + [%# filled by click event %] + +
            +
            + [% INCLUDE 'csrf-token.inc' %] + [%# filled by submit %] + + [% IF suggestion.suggestions.size %] +

            Check all | Uncheck all

            + + + + + + + + + + + + + + + + + + + + + + + + [% FOREACH s IN suggestion.suggestions %] + + + + + + + + + + + + + + + + + + + [% END # /FOREACH s %] + +
             SuggestionSuggested bySuggester categorySuggested onPatron reasonManaged byManaged onLast modification byLast modification onLast updatedLibraryFundNon-public noteStatus 
            + + + + [% s.title | html %][% IF ( s.author ) %], by [% s.author | html %][% END %] + +
            + [% IF ( s.copyrightdate ) %] + © [% s.copyrightdate | html %] + [% END %] + [% IF ( s.volumedesc ) %] + ; Volume:[% s.volumedesc | html %] + [% END %] + [% IF ( s.isbn ) %] + ; ISBN: [% s.isbn | html %] + [% END %] + [% IF ( s.publishercode ) %] + ; Published by [% s.publishercode | html %] + [% END %] + [% IF ( s.publicationyear ) %] + in [% s.publicationyear | html %] + [% END %] + [% IF ( s.place ) %] + in [% s.place | html %] + [% END %] + [% IF ( s.collectiontitle ) %] + ; [% s.collectiontitle | html %] + [% END %] + [% IF ( s.itemtype ) %] + ; [% AuthorisedValues.GetByCode( 'SUGGEST_FORMAT', s.itemtype, 0 ) | html %] + [% END %] +
            + [% IF ( s.note ) %] +
            [% s.note | html %]
            + [% END %] + [% IF s.archived %] +
            Archived + [% END %] +
            + [% SET suggester = s.suggester %] + [% suggester.surname | html %][% IF suggester.firstname %], [% suggester.firstname | html %][% END %] + [% IF suggester.cardnumber %]([% suggester.cardnumber | html %])[% END %] + [% suggester.category.description | html %] [% IF ( s.suggesteddate ) %][% s.suggesteddate | $KohaDates %][% END %] [% AuthorisedValues.GetByCode( 'OPAC_SUG', s.patronreason ) | html %] + [% SET manager = s.manager %] + [% manager.surname | html %][% IF manager.firstname %], [% manager.firstname | html %][% END %] + [% IF ( s.manageddate ) %][% s.manageddate | $KohaDates %][% END %] + [% SET last_modifier = s.last_modifier %] + [% last_modifier.surname | html %][% IF last_modifier.firstname %], [% last_modifier.firstname | html %][% END %] + [% IF ( s.lastmodificationdate ) %][% s.lastmodificationdate | $KohaDates %][% END %] [% s.lastmodificationdate | $KohaDates %] [% Branches.GetName( s.branchcode ) | html %] [% s.fund.budget_name | html %] [% s.staff_note | html %] + [% IF s.STATUS == 'ASKED' %] + Pending + [% ELSIF s.STATUS == 'ACCEPTED' %] + Accepted + [% ELSIF s.STATUS == 'ORDERED' %] + Ordered + [% ELSIF s.STATUS == 'REJECTED' %] + Rejected + [% ELSIF s.STATUS == 'CHECKED' %] + Checked + [% ELSIF s.STATUS == 'AVAILABLE' %] + Available + [% ELSIF AuthorisedValues.GetByCode( 'SUGGEST_STATUS', s.STATUS ) %] + [% AuthorisedValues.GetByCode( 'SUGGEST_STATUS', s.STATUS ) | html %] + [% ELSE %] + Status unknown + [% END %] + + [% IF ( s.reason ) %] +
            ([% s.reason | html %]) + [% END %] +
            + [% IF CAN_user_suggestions_suggestions_manage %] +
            + Edit + +
            + [% ELSIF CAN_user_suggestions_suggestions_delete %] + + [% END %] +
            + + +
            +
            +

            Change selected suggestions

            +
            +
            +
            + [% IF CAN_user_suggestions_suggestions_manage %] +
            +
            +
            + + + + + + + + + Cancel + +
            +
            +
            + + + +
            +
            + + +
            +
            + + [% PROCESS 'av-build-dropbox.inc' name="suggestion_itemtype", category="SUGGEST_FORMAT", size = 20 %] +
            +
            + + + +
            +
            + + +
            +
            + Update manager + Select manager + +
            +
            + + + + +
            +
            + + [% END %] + + [% IF CAN_user_suggestions_suggestions_delete %] +
            +
            + Delete selected +
            +
            + + + +
            +
            + + [% END %] + + [% IF CAN_user_suggestions_suggestions_manage %] +
            +
            + Archive selected +
            + + + +
            +
            +
            + + [% END %] +
            + + [% ELSE %] + No results. + [% END # /IF ( suggestion.suggestions_loop ) %] +
            + + [% END # /tab_panel# %] + [% END # /FOREACH suggestion %] + [% END # /WRAPPER tab_panels %] + [% END # /WRAPPER tabs %] + [% END # /IF op == 'else' %] +
            + + + [% UNLESS op == 'save' %] + [% UNLESS ( op == 'show' ) %] +
            +
            - -
            -
            - - [% PROCESS 'av-build-dropbox.inc' name="suggestion_itemtype", category="SUGGEST_FORMAT", size = 20 %] -
            -
            - - - -
            -
            - -
            -
            - Update manager - Select manager - -
            -
            - - - - -
            -
            - [% END %] - - [% IF CAN_user_suggestions_suggestions_delete %] -
            -
            - Delete selected -
            -
            - - - -
            -
            - [% END %] - - [% IF CAN_user_suggestions_suggestions_manage %] -
            -
            - Archive selected -
            - - - -
            -
            -
            - [% END %] -
            - - [% ELSE %] - No results. - [% END # /IF ( suggestion.suggestions_loop ) %] - - [% END # /tab_panel# %] - [% END # /FOREACH suggestion %] - [% END # /WRAPPER tab_panels %] - [% END # /WRAPPER tabs %] - [% END # /IF op == 'else' %] - -
            - - [% UNLESS op == 'save' %] - [% UNLESS ( op == 'show' ) %] -
            -
          • +
          • + + +
          • +
          • + + +
          • + + + +
            + +
            -

            - Acquisition information -

            -
            -
              -
            1. - [% PROCESS funds_dropdown %] -
            2. -
            -
            -
            - -
            +

            + Acquisition information +

            +
            +
              +
            1. [% PROCESS funds_dropdown %]
            2. +
            +
            + +
            + +
            -
            -
              -
            1. - -
            2. -
            +
            +
              +
            1. + +
            2. +
            +
            - - - + + + + + - [% INCLUDE 'acquisitions-menu.inc' %] - - - - [% END # /UNLESS ( op == 'show' ) %] - [% END # /UNLESS op == 'save' %] - - - - [% END # /IF op == "show" %] + [% INCLUDE 'acquisitions-menu.inc' %] + + + + [% END # /UNLESS ( op == 'show' ) %] + [% END # /UNLESS op == 'save' %] + + + + +[% END # /IF op == "show" %] [% BLOCK funds_dropdown %] @@ -1311,7 +1361,6 @@ [% MACRO jsinclude BLOCK %] [% INCLUDE 'calendar.inc' %] - - [% IF ( op == 'show' || op == 'else' ) %] [% END %] - [% IF op == 'save' %] + [% IF op == 'save' %] [% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/tags/review.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/tags/review.tt index b8bf303eed..b093e27764 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/tags/review.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/tags/review.tt @@ -5,266 +5,300 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] - [% FILTER collapse %] +<title + >[% FILTER collapse %] [% IF ( filter_approved_ok ) %] - [% t("Approved") | html %] › + [% t("Approved") | html %] + › [% ELSIF ( filter_approved_pending ) %] - [% t("Pending") | html %] › + [% t("Pending") | html %] + › [% ELSIF ( filter_approved_rej ) %] - [% t("Rejected") | html %] › + [% t("Rejected") | html %] + › [% END %] - [% t("Tags") | html %] › - [% t("Tools") | html %] › - [% t("Koha") | html %] - [% END %] - [% INCLUDE 'doc-head-close.inc' %] - [% FILTER collapse %][% END %] + +[% END %] - [% WRAPPER 'header.inc' %] - [% INCLUDE 'cat-search.inc' %] - [% END %] +[% WRAPPER 'header.inc' %] + [% INCLUDE 'cat-search.inc' %] +[% END %] - [% WRAPPER 'sub-header.inc' %] - [% WRAPPER breadcrumbs %] +[% WRAPPER 'sub-header.inc' %] + [% WRAPPER breadcrumbs %] + [% WRAPPER breadcrumb_item %] + Tools + [% END %] + [% IF ( filter_approved_ok || filter_approved_pending || filter_approved_rej ) %] [% WRAPPER breadcrumb_item %] - Tools + Tags [% END %] - [% IF ( filter_approved_ok || filter_approved_pending || filter_approved_rej ) %] - [% WRAPPER breadcrumb_item %] - Tags - [% END %] - [% ELSE %] - [% WRAPPER breadcrumb_item bc_active= 1 %] - Tags - [% END %] + [% ELSE %] + [% WRAPPER breadcrumb_item bc_active= 1 %] + Tags [% END %] - [% IF ( filter_approved_ok ) %] - [% WRAPPER breadcrumb_item bc_active= 1 %] - [% t("Approved") | html %] - [% END %] - [% ELSIF ( filter_approved_pending ) %] - [% WRAPPER breadcrumb_item bc_active= 1 %] - [% t("Pending") | html %] - [% END %] - [% ELSIF ( filter_approved_rej ) %] - [% WRAPPER breadcrumb_item bc_active= 1 %] - [% t("Rejected") | html %] - [% END %] + [% END %] + [% IF ( filter_approved_ok ) %] + [% WRAPPER breadcrumb_item bc_active= 1 %] + [% t("Approved") | html %] [% END %] - [% END #/ WRAPPER breadcrumbs %] - [% END #/ WRAPPER sub-header.inc %] + [% ELSIF ( filter_approved_pending ) %] + [% WRAPPER breadcrumb_item bc_active= 1 %] + [% t("Pending") | html %] + [% END %] + [% ELSIF ( filter_approved_rej ) %] + [% WRAPPER breadcrumb_item bc_active= 1 %] + [% t("Rejected") | html %] + [% END %] + [% END %] + [% END #/ WRAPPER breadcrumbs %] +[% END #/ WRAPPER sub-header.inc %] [% WRAPPER 'main-container.inc' asides=['tags-filter', 'tools-menu'] %] +

            Tags

            -

            Tags

            +
            +
            +
            + [% INCLUDE 'csrf-token.inc' %] +

            + [% IF ( filter_approved_all ) %]Displaying all terms[% END %] + [% IF ( filter_approved_ok ) %]Displaying approved terms[% END %] + [% IF ( filter_approved_pending ) %]Displaying pending terms[% END %] + [% IF ( filter_approved_rej ) %]Displaying rejected terms[% END %] +

            -
            -
            - - [% INCLUDE 'csrf-token.inc' %] -

            - [% IF ( filter_approved_all ) %]Displaying all terms[% END %] - [% IF ( filter_approved_ok ) %]Displaying approved terms[% END %] - [% IF ( filter_approved_pending ) %]Displaying pending terms[% END %] - [% IF ( filter_approved_rej ) %]Displaying rejected terms[% END %] -

            - - [% IF ( op_count ) %] -
            - [% IF ( op == 'cud-approve' ) %] Approved - [% ELSIF ( op == 'cud-reject' ) %] Rejected - [% ELSIF ( op == 'test' ) %] Tested - [% ELSE %]Unknown operation ([% op | html %]) on - [% END %] - [% op_count | html %] Term(s). -
            - [% END # /IF op_count %] - [% IF ( message_loop ) %] -
            - [% FOREACH message_loo IN message_loop %] - [% IF ( message_loo.failed_ok ) %] - Error: Failed to approve term ([% message_loo.failed_ok | html %]). - [% ELSIF ( message_loo.failed_rej ) %] - Error: Failed to reject term ([% message_loo.failed_rej | html %]). - [% ELSIF ( message_loo.approver ) %] - No match for user ([% message_loo.approver | html %]). FILTER REQUIRES BORROWERNUMBER (not name). - [% ELSIF ( message_loo.approved_by ) %] - Error: No match for borrowernumber ([% message_loo.approved_by | html %]). - [% ELSE %]Unrecognized error! - [% END %] - [% END %] -
            - [% END # /IF message_loop %] - [% IF ( pagination_bar ) %] -
            - [% pagination_bar | $raw %] -
            - [% END %] - [% IF ( tagloop ) %] -
            -

            - - - - - - - - - [% UNLESS ( filter_approved_pending ) %][% END %] - - - - - [% FOREACH tagloo IN tagloop %] - - - - - - - [% IF ( tagloo.approved ) %] - - - - [% ELSE %] - - [% UNLESS ( filter_approved_pending ) %] - - [% END %] - [% END # /IF ( tagloo.approved ) %] - - [% END # /FOREACH tagloo %] - -
             StatusTermWeightDateReviewerActions
            - [% IF ( tagloo.approved == 0 ) %] - - [% ELSIF ( tagloo.approved == 1 ) %] - - [% ELSE %] - - [% END %] - - [% IF ( tagloo.approved == -1 ) %] - - [% ELSIF ( tagloo.approved == 1 ) %] - - [% ELSE %] - - [% END %] - - [% tagloo.term | html %] - - [% tagloo.weight_total | html %] - - [% tagloo.date_approved | $KohaDates %] - - [% IF ( tagloo.approved_by_name ) %] - [% tagloo.approved_by_name | html %] - [% END %] - - - - -  
            -
            - [% END %] - [% IF ( tagloop ) %] -
            - - -
            - [% END %] - -
            -
            - -
            + [% IF ( op_count ) %] +
            + [% IF ( op == 'cud-approve' ) %] + Approved + [% ELSIF ( op == 'cud-reject' ) %] + Rejected + [% ELSIF ( op == 'test' ) %] + Tested + [% ELSE %] + Unknown operation ([% op | html %]) on + [% END %] + [% op_count | html %] Term(s).
            + [% END # /IF op_count %] + [% IF ( message_loop ) %] +
            + [% FOREACH message_loo IN message_loop %] + [% IF ( message_loo.failed_ok ) %] + Error: Failed to approve term ([% message_loo.failed_ok | html %]). + [% ELSIF ( message_loo.failed_rej ) %] + Error: Failed to reject term ([% message_loo.failed_rej | html %]). + [% ELSIF ( message_loo.approver ) %] + No match for user ([% message_loo.approver | html %]). FILTER REQUIRES BORROWERNUMBER (not name). + [% ELSIF ( message_loo.approved_by ) %] + Error: No match for borrowernumber ([% message_loo.approved_by | html %]). + [% ELSE %] + Unrecognized error! + [% END %] + [% END %] +
            + [% END # /IF message_loop %] + [% IF ( pagination_bar ) %] +
            [% pagination_bar | $raw %]
            + [% END %] + [% IF ( tagloop ) %] +
            +

            + + + + + + + + + [% UNLESS ( filter_approved_pending ) %][% END %] + + + + + [% FOREACH tagloo IN tagloop %] + + + + + + + [% IF ( tagloo.approved ) %] + + + [% ELSE %] + + [% UNLESS ( filter_approved_pending ) %] + + [% END %] + [% END # /IF ( tagloo.approved ) %] + + [% END # /FOREACH tagloo %] + +
             StatusTermWeightDateReviewerActions
            + [% IF ( tagloo.approved == 0 ) %] + + [% ELSIF ( tagloo.approved == 1 ) %] + + [% ELSE %] + + [% END %] + + [% IF ( tagloo.approved == -1 ) %] + + [% ELSIF ( tagloo.approved == 1 ) %] + + [% ELSE %] + + [% END %] + + [% tagloo.term | html %] + [% tagloo.weight_total | html %] [% tagloo.date_approved | $KohaDates %] + [% IF ( tagloo.approved_by_name ) %] + [% tagloo.approved_by_name | html %] + [% END %] + + + + +  
            + +
            + + [% END %] + [% IF ( tagloop ) %] +
            + + +
            + [% END %] + +
            + +
            + +
            + +
            [% END %] [% MACRO jsinclude BLOCK %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/tools/access_files.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/tools/access_files.tt index 0b87aff911..18e044fff3 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/tools/access_files.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/tools/access_files.tt @@ -5,10 +5,12 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Access files") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Access files") | html %] + › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -28,53 +30,51 @@ [% END #/ WRAPPER sub-header.inc %] [% WRAPPER 'main-container.inc' aside='tools-menu' %] -

            Access files

            -[% IF ( error_no_dir ) %] -
            Error: Files could not be found because the "access_dir" option was not set in "koha-conf.xml". Contact your system administrator to add this option.
            -[% ELSE %] - [% IF ( files_loop ) %] -
            - - - - - - - - - - [% FOREACH file IN files_loop %] - - - - - - [% END %] - -
            NameSize (bytes)Date last modified
            [% file.name | html %][% file.size | html %][% file.date | $KohaDates %]
            -
            + [% IF ( error_no_dir ) %] +
            Error: Files could not be found because the "access_dir" option was not set in "koha-conf.xml". Contact your system administrator to add this option.
            [% ELSE %] -
            No files found.
            + [% IF ( files_loop ) %] +
            + + + + + + + + + + [% FOREACH file IN files_loop %] + + + + + + [% END %] + +
            NameSize (bytes)Date last modified
            [% file.name | html %][% file.size | html %][% file.date | $KohaDates %]
            +
            + [% ELSE %] +
            No files found.
            + [% END %] [% END %] [% END %] -[% END %] - [% MACRO jsinclude BLOCK %] [% Asset.js("js/tools-menu.js") | $raw %] [% INCLUDE 'datatables.inc' %] + $(document).ready(function () { + $("#files").dataTable( + $.extend(true, {}, dataTablesDefaults, { + columnDefs: [{ targets: [-1], orderSequence: ["desc", "asc"], searchable: false }], + paginate: false, + }) + ); + }); + [% END %] [% INCLUDE 'intranet-bottom.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/tools/additional-contents.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/tools/additional-contents.tt index 50b8a554c6..7487064420 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/tools/additional-contents.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/tools/additional-contents.tt @@ -34,15 +34,16 @@ [% t("HTML customizations") | html %] [% END %] [% END %] -[% FILTER collapse %] - [% IF op == 'add_form' %] - [% PROCESS page_heading %] › - [% END %] - [% PROCESS page_section %] › - [% t("Additional content") | html %] › - [% t("Tools") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% IF op == 'add_form' %] + [% PROCESS page_heading %] + › + [% END %] + [% PROCESS page_section %] + › [% t("Additional content") | html %] › [% t("Tools") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] [% IF ( wysiwyg ) %] [% SET editmode = "wysiwyg" %] @@ -57,24 +58,24 @@ } [% END %] - + @@ -119,44 +120,41 @@
            -
            - [% INCLUDE 'messages.inc' %] +
            + [% INCLUDE 'messages.inc' %] - [% FOR m IN messages %] -
            - [% SWITCH m.code %] - [% CASE 'error_on_update' %] - An error occurred when updating this content. Perhaps it already exists. - [% CASE 'error_on_insert' %] - An error occurred when adding this content. Check the logs for details. - [% CASE 'error_on_delete' %] - An error occurred when deleting this content. Check the logs for details. - [% CASE 'success_on_update' %] - Content updated successfully. - [% CASE 'success_on_insert' %] - Content added successfully. - [% CASE 'success_on_delete' %] - Content deleted successfully. - [% CASE %] - [% m.code | html %] - [% END %] + [% FOR m IN messages %] +
            + [% SWITCH m.code %] + [% CASE 'error_on_update' %] + An error occurred when updating this content. Perhaps it already exists. + [% CASE 'error_on_insert' %] + An error occurred when adding this content. Check the logs for details. + [% CASE 'error_on_delete' %] + An error occurred when deleting this content. Check the logs for details. + [% CASE 'success_on_update' %] + Content updated successfully. + [% CASE 'success_on_insert' %] + Content added successfully. + [% CASE 'success_on_delete' %] + Content deleted successfully. + [% CASE %] + [% m.code | html %] + [% END %] +
            + [% END %] + + [% IF op == 'add_form' %] + [% PROCESS add_form %] + [% ELSE %] + [% PROCESS list %] + [% END %] +
            - [% END %] - - [% IF op == 'add_form' %] - [% PROCESS add_form %] - [% ELSE %] - [% PROCESS list %] - [% END %] - - - -
            + [% IF op != 'add_form' %] -
            -
            +
            + [% END %] -
            - + + + + [% BLOCK add_form %]

            [% PROCESS page_heading %]

            @@ -269,19 +268,19 @@
            [% INCLUDE 'date-format.inc' %] [% IF category == 'news' %] -
            News will still be accessible by direct URL if expired. +
            News will still be accessible by direct URL if expired. [% END %]
            [% UNLESS category == 'pages' %] -
          • - - [% IF ( additional_content.number ) %] - - [% ELSE %] - - [% END %] -
          • +
          • + + [% IF ( additional_content.number ) %] + + [% ELSE %] + + [% END %] +
          • [% END %] @@ -293,9 +292,9 @@ [% WRAPPER tabs_nav %] [% FOR language IN languages %] [% IF language.lang == 'default' %] - [% WRAPPER tab_item tabname= "lang_default" %] Default [% END %] + [% WRAPPER tab_item tabname= "lang_default" %]Default[% END %] [% ELSE %] - [% WRAPPER tab_item tabname= "lang_${language.lang}" %] [% language.description | html %] [% END %] + [% WRAPPER tab_item tabname= "lang_${language.lang}" %][% language.description | html %][% END %] [% END %] [% END %] [% END # /WRAPPER tabs_nav %] @@ -308,11 +307,13 @@
            1. - +
            2. - +
            3. @@ -325,7 +326,7 @@ [% ELSE %]
              - +
              [% END # /IF languages.size %] @@ -333,12 +334,10 @@ [% END %] [% BLOCK list %] -
              - New entry + New entry
            -
            - - Cancel -
            - - - +
            +
            +
            +

            Hints

            +
              +
            • Search in the calendar the day you want to set as holiday.
            • +
            • Click the date to add or edit a holiday.
            • +
            • Enter a title and description for the holiday.
            • +
            • Specify how the holiday should repeat.
            • +
            • Click Save to finish.
            • +
            +

            Key

            +

            + Working day + Unique holiday + Holiday repeating weekly + Holiday repeating yearly + Holiday exception +

            +
            + -
            -

            Calendar information

            - -
            -
            -
            - [% INCLUDE 'csrf-token.inc' %] - - - - - -
            -
            -
            -
            +
            + + + [% IF ( EXCEPTION_HOLIDAYS_LOOP ) %] +

            Exceptions

            + + + + + + + + + + + [% FOREACH EXCEPTION_HOLIDAYS_LOO IN EXCEPTION_HOLIDAYS_LOOP %] + + + + + + [% END %] + +
            DateTitleDescription
            + [% EXCEPTION_HOLIDAYS_LOO.DATE | html %] + [% EXCEPTION_HOLIDAYS_LOO.TITLE | html %][% EXCEPTION_HOLIDAYS_LOO.DESCRIPTION | html %]
            + + [% END # /IF ( EXCEPTION_HOLIDAYS_LOOP ) %] -
            -
            -
            -

            Hints

            -
              -
            • Search in the calendar the day you want to set as holiday.
            • -
            • Click the date to add or edit a holiday.
            • -
            • Enter a title and description for the holiday.
            • -
            • Specify how the holiday should repeat.
            • -
            • Click Save to finish.
            • -
            -

            Key

            -

            - Working day - Unique holiday - Holiday repeating weekly - Holiday repeating yearly - Holiday exception -

            -
            + [% IF ( WEEK_DAYS_LOOP ) %] +

            Weekly - Repeatable holidays

            + + + + + + + + + + [% FOREACH WEEK_DAYS_LOO IN WEEK_DAYS_LOOP %] + + + + + + [% END %] + +
            Day of weekTitleDescription
            [% WEEK_DAYS_LOO.KEY | html %][% WEEK_DAYS_LOO.TITLE | html %][% WEEK_DAYS_LOO.DESCRIPTION | html %]
            + + [% END # / IF ( WEEK_DAYS_LOOP ) %] -
            - - - [% IF ( EXCEPTION_HOLIDAYS_LOOP ) %] -

            Exceptions

            - - - - - - - - - - - [% FOREACH EXCEPTION_HOLIDAYS_LOO IN EXCEPTION_HOLIDAYS_LOOP %] - - - - - - [% END %] - -
            DateTitleDescription
            - - [% EXCEPTION_HOLIDAYS_LOO.DATE | html %] - - [% EXCEPTION_HOLIDAYS_LOO.TITLE | html %][% EXCEPTION_HOLIDAYS_LOO.DESCRIPTION | html %]
            - [% END # /IF ( EXCEPTION_HOLIDAYS_LOOP ) %] + [% IF ( DAY_MONTH_HOLIDAYS_LOOP ) %] +

            Yearly - Repeatable holidays

            + + + + [% IF ( dateformat == "metric" ) %] + + [% ELSE %] + + [% END %] + + + + + + [% FOREACH DAY_MONTH_HOLIDAYS_LOO IN DAY_MONTH_HOLIDAYS_LOOP %] + + + + + + [% END %] + +
            Day/monthMonth/dayTitleDescription
            [% DAY_MONTH_HOLIDAYS_LOO.DATE | html %] [% DAY_MONTH_HOLIDAYS_LOO.TITLE | html %][% DAY_MONTH_HOLIDAYS_LOO.DESCRIPTION | html %]
            + + [% END # /IF ( DAY_MONTH_HOLIDAYS_LOOP ) %] - [% IF ( WEEK_DAYS_LOOP ) %] -

            Weekly - Repeatable holidays

            - - - - - - - - - - [% FOREACH WEEK_DAYS_LOO IN WEEK_DAYS_LOOP %] - - - - - - [% END %] - -
            Day of weekTitleDescription
            [% WEEK_DAYS_LOO.KEY | html %][% WEEK_DAYS_LOO.TITLE | html %][% WEEK_DAYS_LOO.DESCRIPTION | html %]
            - [% END # / IF ( WEEK_DAYS_LOOP ) %] - - [% IF ( DAY_MONTH_HOLIDAYS_LOOP ) %] -

            Yearly - Repeatable holidays

            - - - - [% IF ( dateformat == "metric" ) %] - - [% ELSE %] - - [% END %] - - - - - - [% FOREACH DAY_MONTH_HOLIDAYS_LOO IN DAY_MONTH_HOLIDAYS_LOOP %] - - - - - - [% END %] - -
            Day/monthMonth/dayTitleDescription
            - [% DAY_MONTH_HOLIDAYS_LOO.DATE | html %] - [% DAY_MONTH_HOLIDAYS_LOO.TITLE | html %][% DAY_MONTH_HOLIDAYS_LOO.DESCRIPTION | html %]
            - [% END # /IF ( DAY_MONTH_HOLIDAYS_LOOP ) %] - - [% IF ( HOLIDAYS_LOOP ) %] -

            Unique holidays

            - - - - - - - - - - - [% FOREACH HOLIDAYS_LOO IN HOLIDAYS_LOOP %] - - - - - - [% END %] - -
            DateTitleDescription
            - - [% HOLIDAYS_LOO.DATE | html %] - - [% HOLIDAYS_LOO.TITLE | html %][% HOLIDAYS_LOO.DESCRIPTION.replace('\\\r\\\n', '
            ') | html %]
            - [% END # /IF ( HOLIDAYS_LOOP ) %] -
            -
            -
            -
            + [% IF ( HOLIDAYS_LOOP ) %] +

            Unique holidays

            + + + + + + + + + + + [% FOREACH HOLIDAYS_LOO IN HOLIDAYS_LOOP %] + + + + + + [% END %] + +
            DateTitleDescription
            + [% HOLIDAYS_LOO.DATE | html %] + [% HOLIDAYS_LOO.TITLE | html %][% HOLIDAYS_LOO.DESCRIPTION.replace('\\\r\\\n', '
            ') | html %]
            + + [% END # /IF ( HOLIDAYS_LOOP ) %] + + + + + + + + [% END %] [% MACRO jsinclude BLOCK %] [% INCLUDE 'calendar.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/tools/import_borrowers.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/tools/import_borrowers.tt index 2ee6bc1e19..c39b4115cb 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/tools/import_borrowers.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/tools/import_borrowers.tt @@ -5,19 +5,27 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% IF ( uploadborrowers ) %] - [% t("Results") | html %] › - [% END %] - [% t("Import patrons") | html %] › - [% t("Tools") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% IF ( uploadborrowers ) %] + [% t("Results") | html %] + › + [% END %] + [% t("Import patrons") | html %] + › [% t("Tools") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -47,50 +55,47 @@ [% END #/ WRAPPER sub-header.inc %] [% WRAPPER 'main-container.inc' aside='tools-menu' %] - -

            Import patrons

            -
            +

            Import patrons

            +
            [% IF ( uploadborrowers ) %]
            -

            Import results

            -
              -
            • - [% tpx("Patron import", "{count_of_imported_records} imported records", {count_of_imported_records = imported}) | html %] - [% IF ( lastimported ) %] - [% tpx("Patron import", "(last was {last_imported_record})", {last_imported_record = lastimported}) | html %] +

              Import results

              +
                +
              • + [% tpx("Patron import", "{count_of_imported_records} imported records", {count_of_imported_records = imported}) | html %] + [% IF ( lastimported ) %] + [% tpx("Patron import", "(last was {last_imported_record})", {last_imported_record = lastimported}) | html %] + [% END %] +
              • + [% IF imported and patronlistname %] +
              • Patron list with imported patrons: [% patronlistname | html %]
              • [% END %] - - [% IF imported and patronlistname %] -
              • Patron list with imported patrons: [% patronlistname | html %]
              • - [% END %] -
              • - [% tpx("Patron import", "{count_of_overwritten_records} overwritten records", {count_of_overwritten_records = overwritten}) | html %] - [% IF ( lastoverwritten ) %] - [% tpx("Patron import", "(last was {last_overwritten_record})", {last_overwritten_record = lastoverwritten}) | html %] - [% END %] -
              • -
              • - [% tpx("Patron import", "{count_of_existing_records} not imported because they are already in borrowers table and overwrite is disabled ", {count_of_existing_records = alreadyindb}) | html %] - [% IF ( lastalreadyindb ) %] - [% tpx("Patron import", "(last was {last_existing_record})", {last_existing_record = lastalreadyindb}) | html %] - [% END %] -
              • -
              • - [% tpx("Patron import", "{count_of_invalid_records} not imported because they are not in the expected format", {count_of_invalid_records = invalid}) | html %] - [% IF ( lastinvalid ) %] - [% tpx("Patron import", "(last was {last_invalid_record})", {last_invalid_record = lastinvalid}) | html %] - [% END %] -
              • - [% tpx("Patron import", "{total} records parsed", {total = total}) | html %] -
              • -
              • Back to Tools
              • -
              +
            • + [% tpx("Patron import", "{count_of_overwritten_records} overwritten records", {count_of_overwritten_records = overwritten}) | html %] + [% IF ( lastoverwritten ) %] + [% tpx("Patron import", "(last was {last_overwritten_record})", {last_overwritten_record = lastoverwritten}) | html %] + [% END %] +
            • +
            • + [% tpx("Patron import", "{count_of_existing_records} not imported because they are already in borrowers table and overwrite is disabled ", {count_of_existing_records = alreadyindb}) | html %] + [% IF ( lastalreadyindb ) %] + [% tpx("Patron import", "(last was {last_existing_record})", {last_existing_record = lastalreadyindb}) | html %] + [% END %] +
            • +
            • + [% tpx("Patron import", "{count_of_invalid_records} not imported because they are not in the expected format", {count_of_invalid_records = invalid}) | html %] + [% IF ( lastinvalid ) %] + [% tpx("Patron import", "(last was {last_invalid_record})", {last_invalid_record = lastinvalid}) | html %] + [% END %]
            • [% tpx("Patron import", "{total} records parsed", {total = total}) | html %]
            • +
            • Back to Tools
            • +
            - [% IF ( feedback ) %] -

            + [% IF ( feedback ) %] +

            -
            -

            Feedback

            +
            +

            Feedback

            -
            - [% END %] +
            + [% END %] - [% IF ( errors ) %] -

            + [% IF ( errors ) %] +

            -
            -

            Error analysis

            -
              - [% FOREACH e IN errors %] - [% IF ( e.badheader ) %]
            • Header row could not be parsed
            • [% END %] +
              +

              Error analysis

              +
                + [% FOREACH e IN errors %] + [% IF ( e.badheader ) %]
              • Header row could not be parsed
              • [% END %] - [% FOREACH missing_critical IN e.missing_criticals %] -
              • - Line [% missing_critical.line | html %] + [% FOREACH missing_critical IN e.missing_criticals %] +
              • + Line [% missing_critical.line | html %] - [% IF ( missing_critical.badparse ) %] - could not be parsed! - [% ELSIF ( missing_critical.bad_date ) %] - has "[% missing_critical.key | html %]" in unrecognized format: "[% missing_critical.value | html %]" - [% ELSE %] - Critical field "[% missing_critical.key | html %]" - - [% IF ( missing_critical.branch_map ) %] - has unrecognized value "[% missing_critical.value | html %]" - [% ELSIF ( missing_critical.category_map ) %] - has unrecognized value "[% missing_critical.value | html %]" + [% IF ( missing_critical.badparse ) %] + could not be parsed! + [% ELSIF ( missing_critical.bad_date ) %] + has "[% missing_critical.key | html %]" in unrecognized format: "[% missing_critical.value | html %]" [% ELSE %] - missing + Critical field "[% missing_critical.key | html %]" + + [% IF ( missing_critical.branch_map ) %] + has unrecognized value "[% missing_critical.value | html %]" + [% ELSIF ( missing_critical.category_map ) %] + has unrecognized value "[% missing_critical.value | html %]" + [% ELSE %] + missing + [% END %] + (borrowernumber: [% missing_critical.borrowernumber | html %]; surname: [% missing_critical.surname | html %]). [% END %] - (borrowernumber: [% missing_critical.borrowernumber | html %]; surname: [% missing_critical.surname | html %]). - [% END %] +
                + [% missing_critical.lineraw | html %] +
              • + [% END %] -
                - [% missing_critical.lineraw | html %] - + [% IF e.invalid_cardnumber %] +
              • Card number [% e.cardnumber | html %] is not a valid card number [% IF e.borrowernumber %](for patron with borrowernumber [% e.borrowernumber | html %])[% END %]
              • + [% END %] + [% IF e.duplicate_userid %] +
              • Userid [% e.userid | html %] is already used by another patron.
              • + [% END %] + [% IF e.passwd_too_short %] +
              • Password is too short for patron with borrowernumber [% e.borrowernumber | html %]. Minimum length is [% e.min_length | html %], length is [% e.length | html %]
              • + [% END %] + [% IF e.passwd_whitespace %] +
              • Password contains whitespace for patron with borrowernumber [% e.borrowernumber | html %].
              • + [% END %] + [% IF e.passwd_too_weak %] +
              • Password is too weak for patron with borrowernumber [% e.borrowernumber | html %].
              • + [% END %] + [% IF e.passwd_plugin_err %] +
              • Password plugin error for patron with borrowernumber [% e.borrowernumber | html %].
              • + [% END %] + [% IF e.passwd_unknown_err %] +
              • Password error for patron with borrowernumber [% e.borrowernumber | html %].
              • + [% END %] + [% IF e.patron_attribute_unique_id_constraint %] +
              • + [% IF e.borrowernumber %] + Patron attribute [% e.attribute.code | html %] must be unique for patron with borrowernumber [% e.borrowernumber | html %]. + [% ELSE %] + Patron attribute [% e.attribute.code | html %] must be unique for patron [% e.patron_id | html %]. + [% END %] +
              • + [% END %] + [% IF e.patron_attribute_invalid_type %] +
              • + [% IF e.borrowernumber %] + Patron attribute [% e.attribute_type_code | html %] is invalid for patron with borrowernumber [% e.borrowernumber | html %]. + [% ELSE %] + Patron attribute [% e.attribute_type_code | html %] is invalid for patron [% e.patron_id | html %]. + [% END %] +
              • + [% END %] + [% IF e.patron_attribute_non_repeatable %] +
              • + [% IF e.borrowernumber %] + Patron attribute [% e.attribute.code | html %] is non-repeatable for patron with borrowernumber [% e.borrowernumber | html %]. + [% ELSE %] + Patron attribute [% e.attribute.code | html %] is non-repeatable for patron [% e.patron_id | html %]. + [% END %] +
              • + [% END %] [% END %] - - [% IF e.invalid_cardnumber %] -
              • - Card number [% e.cardnumber | html %] is not a valid card number - [% IF e.borrowernumber %] (for patron with borrowernumber [% e.borrowernumber | html %])[% END %] -
              • - [% END %] - [% IF e.duplicate_userid %] -
              • - Userid [% e.userid | html %] is already used by another patron. -
              • - [% END %] - [% IF e.passwd_too_short %] -
              • - Password is too short for patron with borrowernumber [% e.borrowernumber | html %]. Minimum length is [% e.min_length | html %], length is [% e.length | html %] -
              • - [% END %] - [% IF e.passwd_whitespace %] -
              • - Password contains whitespace for patron with borrowernumber [% e.borrowernumber | html %]. -
              • - [% END %] - [% IF e.passwd_too_weak %] -
              • - Password is too weak for patron with borrowernumber [% e.borrowernumber | html %]. -
              • - [% END %] - [% IF e.passwd_plugin_err %] -
              • - Password plugin error for patron with borrowernumber [% e.borrowernumber | html %]. -
              • - [% END %] - [% IF e.passwd_unknown_err %] -
              • - Password error for patron with borrowernumber [% e.borrowernumber | html %]. -
              • - [% END %] - [% IF e.patron_attribute_unique_id_constraint %] -
              • - [% IF e.borrowernumber %] - Patron attribute [% e.attribute.code | html %] must be unique for patron with borrowernumber [% e.borrowernumber | html %]. - [% ELSE %] - Patron attribute [% e.attribute.code | html %] must be unique for patron [% e.patron_id | html %]. - [% END %] -
              • - [% END %] - [% IF e.patron_attribute_invalid_type %] -
              • - [% IF e.borrowernumber %] - Patron attribute [% e.attribute_type_code | html %] is invalid for patron with borrowernumber [% e.borrowernumber | html %]. - [% ELSE %] - Patron attribute [% e.attribute_type_code | html %] is invalid for patron [% e.patron_id | html %]. - [% END %] -
              • - [% END %] - [% IF e.patron_attribute_non_repeatable %] -
              • - [% IF e.borrowernumber %] - Patron attribute [% e.attribute.code | html %] is non-repeatable for patron with borrowernumber [% e.borrowernumber | html %]. - [% ELSE %] - Patron attribute [% e.attribute.code | html %] is non-repeatable for patron [% e.patron_id | html %]. - [% END %] -
              • - [% END %] - [% END %] -
              -
              - [% END %] +
            +
            + [% END %]
            [% ELSE %]
            -
              -
            • Select a file to import into the borrowers table
            • -
            • If a card number exists in the table, you can choose whether to ignore the new one or overwrite the old one.
            • -
            +
              +
            • Select a file to import into the borrowers table
            • +
            • If a card number exists in the table, you can choose whether to ignore the new one or overwrite the old one.
            • +
            -
            - [% INCLUDE 'csrf-token.inc' %] - -
            - Import into the borrowers table + + [% INCLUDE 'csrf-token.inc' %] + +
            + Import into the borrowers table -
              -
            1. - - -
            2. +
                +
              1. + + +
              2. -
              3. - - - List name will be file name with timestamp -
              4. -
              -
            +
          • + + + List name will be file name with timestamp +
          • + +
            -
            - Field to use for record matching -
              -
            1. - -
            2. -
            -
            +
            + Field to use for record matching +
              +
            1. + +
            2. +
            +
            -
            - - Enter default values - - +
            + + Enter default values + + - +
            +
            + + Preserve existing values + + + + +
            + +
            + If matching record is already in the borrowers table: + +
              +
            1. + +
            2. + +
            3. + +
                +
              1. + + +
              2. +
              3. + + +
              4. +
              +
            4. +
            +
            + + [% IF ( Koha.Preference('ExtendedPatronAttributes') == 1 ) %] +
            + Patron attributes + +
              +
            1. + +
            2. +
            +
            [% END %] - [% END %] - [% IF ( Koha.Preference('ExtendedPatronAttributes') == 1 ) %] -
          • - - - patron_attributes -
          • - [% END %] +
            + Welcome email +
              +
            1. + + + WELCOME notice is used +
            2. +
            +
            - -
            -
            - - Preserve existing values - - - - -
            - -
            - If matching record is already in the borrowers table: - -
              -
            1. - -
            2. - -
            3. - -
                -
              1. - - -
              2. -
              3. - - -
              4. -
              -
            4. -
            -
            - - [% IF ( Koha.Preference('ExtendedPatronAttributes') == 1 ) %] -
            - Patron attributes - -
              -
            1. - -
            2. - -
            3. - -
            4. -
            -
            +
            + +
            +
            +
            [% END %] -
            - Welcome email -
              -
            1. - - - WELCOME notice is used -
            2. -
            -
            - -
            - -
            - - -
            -[% END %] - -
            -
            -

            Notes:

            -
              -
            • The first line in the file must be a header row defining which columns you are supplying in the import file.
            • - -
            • - - Download a Starter CSV file with all the columns. - - [% tp("CSV file", "Values are comma-separated.") | html %] -
            • - -
            • - OR choose which fields you want to supply from the following list: +
              +
              +

              Notes:

                +
              • The first line in the file must be a header row defining which columns you are supplying in the import file.
              • +
              • - [% FOREACH columnkey IN borrower_fields.keys.sort %]'[% columnkey | html %]', [% END %] + + Download a Starter CSV file with all the columns. + + [% tp("CSV file", "Values are comma-separated.") | html %]
              • + +
              • + OR choose which fields you want to supply from the following list: +
                  +
                • [% FOREACH columnkey IN borrower_fields.keys.sort %]'[% columnkey | html %]',[% END %]
                • +
                +
              • + + [% IF ( Koha.Preference('ExtendedPatronAttributes') ) %] +
              • + If loading patron attributes, the 'patron_attributes' field should contain a comma-separated list of attribute types and values. The attribute type code and a colon should precede each value. For example: + INSTID:12345,LANG:fr or STARTDATE:January 1 2010,TRACK:Day. If an input record has more than one attribute, the fields should either be entered as an unquoted string (previous + examples), or with each field wrapped in separate double quotes and delimited by a comma: "STARTDATE:January 1, 2010","TRACK:Day". The second syntax would be required if the + data might have a comma in it, like a date string. +
              • + [% END %] + +
              • Required fields: The fields 'surname', 'branchcode', and 'categorycode' are required and 'branchcode' and 'categorycode' must match valid entries in your database.
              • + +
              • + 'password' should be stored in plaintext, and will be converted to a Bcrypt hash (if your passwords are already encrypted, talk to your system administrator about options). Passwords will not be updated on overwrite + unless replace passwords option is checked. +
              • + +
              • Date formats should match your system preference, and must be zero-padded, e.g. '01/02/2008'. Alternatively, you can supply dates in ISO format (e.g., '2010-10-28').
              -
            • - - [% IF ( Koha.Preference('ExtendedPatronAttributes') ) %] -
            • - If loading patron attributes, the 'patron_attributes' field should contain a comma-separated list of attribute types and values. The attribute type code and a colon should precede each value. For example: INSTID:12345,LANG:fr or STARTDATE:January 1 2010,TRACK:Day. If an input record has more than one attribute, the fields should either be entered as an unquoted string (previous examples), or with each field wrapped in separate double quotes and delimited by a comma: "STARTDATE:January 1, 2010","TRACK:Day". The second syntax would be required if the data might have a comma in it, like a date string. -
            • - [% END %] - -
            • - Required fields: The fields 'surname', 'branchcode', and 'categorycode' are required and 'branchcode' and 'categorycode' must match valid entries in your database. -
            • - -
            • - 'password' should be stored in plaintext, and will be converted to a Bcrypt hash (if your passwords are already encrypted, talk to your system administrator about options). Passwords will not be updated on overwrite unless replace passwords option is checked. -
            • - -
            • - Date formats should match your system preference, and must be zero-padded, e.g. '01/02/2008'. Alternatively, - you can supply dates in ISO format (e.g., '2010-10-28'). -
            • -
            +
            +
            - - - [% END %] [% MACRO jsinclude BLOCK %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/tools/inventory.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/tools/inventory.tt index 2edc71763c..081435fba5 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/tools/inventory.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/tools/inventory.tt @@ -8,14 +8,16 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% IF (loop) %] - [% t("Results") | html %] › - [% END %] - [% t("Inventory") | html %] › - [% t("Cataloging") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% IF (loop) %] + [% t("Results") | html %] + › + [% END %] + [% t("Inventory") | html %] + › [% t("Cataloging") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] [% FILTER collapse %] - [% WRAPPER 'header.inc' %] +[% WRAPPER 'header.inc' %] [% INCLUDE 'cat-search.inc' %] [% END %] - [% WRAPPER 'sub-header.inc' %] - [% WRAPPER breadcrumbs %] +[% WRAPPER 'sub-header.inc' %] + [% WRAPPER breadcrumbs %] + [% WRAPPER breadcrumb_item %] + Cataloging + [% END %] + [% IF ( import_batch_id || job_enqueued ) %] [% WRAPPER breadcrumb_item %] - Cataloging + Manage staged MARC records [% END %] - [% IF ( import_batch_id || job_enqueued ) %] - [% WRAPPER breadcrumb_item %] - Manage staged MARC records - [% END %] + [% END %] + [% IF ( import_batch_id ) %] + [% WRAPPER breadcrumb_item bc_active= 1 %] + Batch [% import_batch_id | html %] [% END %] - [% IF ( import_batch_id ) %] - [% WRAPPER breadcrumb_item bc_active= 1 %] - Batch [% import_batch_id | html %] - [% END %] - [% ELSIF ( job_enqueued ) %] - [% WRAPPER breadcrumb_item bc_active= 1 %] - [% t("Job enqueued") | html %] - [% END %] + [% ELSIF ( job_enqueued ) %] + [% WRAPPER breadcrumb_item bc_active= 1 %] + [% t("Job enqueued") | html %] + [% END %] + [% ELSE %] + [% WRAPPER breadcrumb_item bc_active= 1 %] + Manage staged MARC records + [% END %] + [% END %] + [% END #/ WRAPPER breadcrumbs %] +[% END #/ WRAPPER sub-header.inc %] + +[% WRAPPER 'main-container.inc' aside='cat-menu' %] +

            Manage staged MARC records

            + [% IF ( import_batch_id ) %] +

            Batch [% import_batch_id | html %]

            + [% END %] + [% FOREACH message IN messages %] + [% SET div_class = '' %] + [% SET div_style = '' %] + [% IF message.type == 'success' %] + [% SET div_class="alert alert-info" %] + [% ELSIF message.type == 'warning' %] + [% SET div_class="alert alert-warning" %] + [% ELSIF message.type == 'error' %] + [% SET div_class="alert alert-warning" %] + [% SET div_style="margin:auto;" %] + [% END %] +
            + [% IF message.code == 'cannot_enqueue_job' %] + Cannot enqueue this job. + [% END %] + [% IF message.error %] + (The error was: [% message.error | html %], see the Koha log file for more information). + [% END %] +
            + [% END %] + + [% IF job_enqueued %] +
            +

            The job has been enqueued!

            +

            It will be processed as soon as possible.

            +

            View detail of the enqueued job

            + [% ELSIF ( label_batch_msg ) %] + [% IF ( alert ) %] + [% SET div_class="alert" %] + [% ELSE %] + [% SET div_class="alert alert-info" %] + [% END %] +
            +

            + [% IF ( label_batch_msg == "error" ) %] + Error attempting to create label batch. Please ask your system administrator to check the log for more details. + [% ELSE %] + Label batch #[% label_batch_msg | html %] created. + [% END %] +

            +
            + [% END %] + + [% IF ( did_clean ) %] +
            Cleaned import batch #[% import_batch_id | html %]
            + [% END %] + + [% IF ( did_delete ) %] +
            Import batch deleted successfully
            + [% END %] + + [% UNLESS batch_list || batch_info || job_enqueued %] +
            +

            No records have been staged.

            +

            Stage MARC records for import.

            +
            + [% END %] + + [% IF ( batch_info ) %] + [% IF ( rematch_attempted ) %] + [% IF ( rematch_failed ) %] +
            Failed to apply different matching rule
            [% ELSE %] - [% WRAPPER breadcrumb_item bc_active= 1 %] - Manage staged MARC records - [% END %] +
            Applied different matching rule. Number of records matched now [% num_with_matches | html %]
            [% END %] - [% END #/ WRAPPER breadcrumbs %] - [% END #/ WRAPPER sub-header.inc %] + [% END %] - [% WRAPPER 'main-container.inc' aside='cat-menu' %] -

            Manage staged MARC records

            - [% IF ( import_batch_id ) %] -

            Batch [% import_batch_id | html %]

            - [% END %] - [% FOREACH message IN messages %] - [% SET div_class = '' %] - [% SET div_style = '' %] - [% IF message.type == 'success' %] - [% SET div_class="alert alert-info" %] - [% ELSIF message.type == 'warning' %] - [% SET div_class="alert alert-warning" %] - [% ELSIF message.type == 'error' %] - [% SET div_class="alert alert-warning" %] - [% SET div_style="margin:auto;" %] - [% END %] -
            - [% IF message.code == 'cannot_enqueue_job' %] - Cannot enqueue this job. - [% END %] - [% IF message.error %] - (The error was: [% message.error | html %], see the Koha log file for more information). - [% END %] -
            - [% END %] + [% IF ( changed_overlay_action ) %] +
            Changed action if matching record found
            + [% END %] - [% IF job_enqueued %] -
            -

            The job has been enqueued!

            -

            It will be processed as soon as possible.

            -

            View detail of the enqueued job -

            + [% IF ( changed_nomatch_action ) %] +
            Changed action if no match found
            + [% END %] - [% ELSIF ( label_batch_msg ) %] - [% IF ( alert ) %] - [% SET div_class="alert" %] + [% IF ( changed_item_action ) %] +
            Changed item processing option
            + [% END %] + + [% UNLESS job_enqueued %] +
            +
              +
            1. File name: [% file_name | html %]
            2. +
            3. Profile: [% IF (profile) %][% profile | html %][% ELSE %](none)[% END %]
            4. +
            5. Comments: [% IF ( comments ) %][% comments | html %][% ELSE %](none)[% END %]
            6. +
            7. Type: [% IF ( record_type == 'auth' ) %]Authority records[% ELSE %]Bibliographic records[% END %]
            8. +
            9. Staged: [% upload_timestamp | $KohaDates with_hours=1 %]
            10. +
            11. Status: + [% IF ( import_status == 'cleaned' ) %] + Cleaned + [% ELSIF ( import_status == 'imported' ) %] + Imported + [% ELSIF ( import_status == 'importing' ) %] + Importing + [% ELSIF ( import_status == 'reverted' ) %] + Reverted + [% ELSIF ( import_status == 'reverting' ) %] + Reverting + [% ELSIF ( import_status == 'staged' ) %] + Staged [% ELSE %] - [% SET div_class="alert alert-info" %] + [% import_status | html %] [% END %] -
              -

              - [% IF ( label_batch_msg == "error" ) %] - Error attempting to create label batch. Please ask your system administrator to check the log for more details. - [% ELSE %] - Label batch #[% label_batch_msg | html %] created. - [% END %] -

              -
              - [% END %] - - [% IF ( did_clean ) %] -
              Cleaned import batch #[% import_batch_id | html %]
              - [% END %] - - [% IF ( did_delete ) %] -
              Import batch deleted successfully
              - [% END %] - - [% UNLESS batch_list || batch_info || job_enqueued %] -
              -

              No records have been staged.

              -

              Stage MARC records for import.

              -
              - [% END %] - - [% IF ( batch_info ) %] - [% IF ( rematch_attempted ) %] - [% IF ( rematch_failed ) %] -
              Failed to apply different matching rule
              - [% ELSE %] -
              Applied different matching rule. Number of records matched now - [% num_with_matches | html %] -
              - [% END %] - [% END %] - - [% IF ( changed_overlay_action ) %] -
              Changed action if matching record found
              - [% END %] - - [% IF ( changed_nomatch_action ) %] -
              Changed action if no match found
              - [% END %] - - [% IF ( changed_item_action ) %] -
              Changed item processing option
              - [% END %] - - [% UNLESS job_enqueued %] -
              -
                -
              1. File name: [% file_name | html %]
              2. -
              3. Profile: [% IF (profile) %][% profile | html %][% ELSE %](none)[% END %]
              4. -
              5. Comments: [% IF ( comments ) %][% comments | html %][% ELSE %](none)[% END %]
              6. -
              7. Type: [% IF ( record_type == 'auth' ) %]Authority records[% ELSE %]Bibliographic records[% END %]
              8. -
              9. Staged: [% upload_timestamp | $KohaDates with_hours=1 %]
              10. -
              11. Status: - [% IF ( import_status == 'cleaned' ) %] - Cleaned - [% ELSIF ( import_status == 'imported' ) %] - Imported - [% ELSIF ( import_status == 'importing' ) %] - Importing - [% ELSIF ( import_status == 'reverted' ) %] - Reverted - [% ELSIF ( import_status == 'reverting' ) %] - Reverting - [% ELSIF ( import_status == 'staged' ) %] - Staged - [% ELSE %] - [% import_status | html %] +
              12. +
              +
              + + [% IF ( can_commit ) %] +
              + [% INCLUDE 'csrf-token.inc' %] + + + +
              +
                +
              1. + + + Changed. Reset +
              2. +
              3. + + [% INCLUDE 'tools-overlay-action.inc' %] Changed. Reset +
              4. +
              5. + + [% INCLUDE 'tools-nomatch-action.inc' %] Changed. Reset +
              6. + [% IF ( record_type == 'biblio' ) %] +
              7. + + [% INCLUDE 'tools-item-action.inc' %] Changed. Reset
              8. -
              -
              - [% IF ( can_commit ) %] - - [% INCLUDE 'csrf-token.inc' %] - - - + [% ELSE %] + + [% END %] +
            +
            +
            + +
            +
            + [% INCLUDE 'csrf-token.inc' %] + + + [% IF ( record_type != 'auth' ) %]
            1. - - + + [% FOREACH framework IN frameworks %] + [% END %] - Changed. Reset +
              New bibliographic records will use this framework
            2. - - [% INCLUDE 'tools-overlay-action.inc' %] Changed. Reset -
            3. -
            4. - - [% INCLUDE 'tools-nomatch-action.inc' %] Changed. Reset -
            5. - [% IF ( record_type == 'biblio' ) %] -
            6. - - [% INCLUDE 'tools-item-action.inc' %] Changed. Reset -
            7. - [% ELSE %] - - [% END %] -
            -
            -
            -
            -
            -
            - [% INCLUDE 'csrf-token.inc' %] - - - [% IF ( record_type != 'auth' ) %] -
            -
              -
            1. - - -
              New bibliographic records will use this framework
              -
            2. -
            3. - - -
              Replacement records will use this framework
              -
            4. -
            -
            - [% END %] -
            - -
            -
            -
            - [% END %] - - [% UNLESS can_commit %] -
            -
              -
            1. - Matching rule applied: - [% IF ( current_matcher_id ) %] - [% current_matcher_code | html %] ([% current_matcher_description | html %]) - [% ELSE %] - No matching rule in effect - [% END %] -
            2. -
            3. - xAction if matching record found: - [% IF ( overlay_action == 'replace' ) %] - Replace existing record with incoming record - [% ELSIF ( overlay_action == 'create_new' ) %] - Add incoming record - [% ELSIF ( overlay_action == 'ignore' ) %] - Ignore incoming record (its items may still be processed) - [% ELSE %] - [% overlay_action | html %] - [% END %] -
            4. -
            5. - Action if no match found: - [% IF ( nomatch_action == 'create_new' ) %] - Add incoming record - [% ELSIF ( nomatch_action == 'ignore' ) %] - Ignore incoming record (its items may still be processed) - [% ELSE %] - [% nomatch_action | html %] - [% END %] -
            6. - [% IF ( record_type == 'biblio' ) %] -
            7. - Item processing: - [% IF ( item_action == 'always_add' ) %] - Always add items - [% ELSIF ( item_action == 'add_only_for_matches' ) %] - Add items only if matching bib was found - [% ELSIF ( item_action == 'add_only_for_new' ) %] - Add items only if no matching bib was found - [% ELSIF ( item_action == 'ignore' ) %] - Ignore items - [% ELSE %] - [% item_action | html %] + + +
              Replacement records will use this framework
              +
            - - [% IF ( can_revert ) %] -
            - [% INCLUDE 'csrf-token.inc' %] - - -
            -
            - [% END # /IF can_revert %] - - [% END #/UNLESS can_commit %] - [% END #/UNLESS job_enqueue %] - - [% END # /IF batch_info %] - -
            - - [% IF ( batch_list ) %] - [% IF ( pages ) %] - [% PROCESS pagination %] [% END %] -
            - - - - - - - - - - - - - - - - - [% FOREACH batch_lis IN batch_list %] - - - - - - - - - - - - - [% END # /FOREACH batch_lis %] - -
            #File nameProfileCommentsTypeStatusStaged# Records# ItemsAction
            [% batch_lis.import_batch_id | html %][% batch_lis.file_name | html %][% batch_lis.profile | html %][% batch_lis.comments | html %][% IF ( batch_lis.record_type == 'auth' ) %]Authority[% ELSE %]Bibliographic[% END %] - [% IF ( batch_lis.import_status == 'cleaned' ) %] - Cleaned - [% ELSIF ( batch_lis.import_status == 'imported' ) %] - Imported - [% ELSIF ( batch_lis.import_status == 'importing' ) %] - Importing - [% ELSIF ( batch_lis.import_status == 'reverted' ) %] - Reverted - [% ELSIF ( batch_lis.import_status == 'reverting' ) %] - Reverting - [% ELSIF ( batch_lis.import_status == 'staged' ) %] - Staged - [% ELSE %] - [% batch_lis.import_status | html %] - [% END %] - [% batch_lis.upload_timestamp | $KohaDates with_hours=1 %][% batch_lis.num_records | html %][% batch_lis.num_items | html %] - [% IF ( batch_lis.num_items && batch_lis.import_status == 'imported' ) %] - (Create label batch) - [% END %] - - [% IF ( batch_lis.can_clean ) %] -
            - [% INCLUDE 'csrf-token.inc' %] - - - -
            - [% ELSIF ( batch_lis.import_status == 'cleaned' ) %] -
            - [% INCLUDE 'csrf-token.inc' %] - - - -
            - [% END %] -
            -
            +
            + +
            + + +
            + [% END %] - [% IF ( pages ) %] - [% PROCESS pagination %] + [% UNLESS can_commit %] +
            +
              +
            1. + Matching rule applied: + [% IF ( current_matcher_id ) %] + [% current_matcher_code | html %] + ([% current_matcher_description | html %]) + [% ELSE %] + No matching rule in effect + [% END %] +
            2. +
            3. + xAction if matching record found: + [% IF ( overlay_action == 'replace' ) %] + Replace existing record with incoming record + [% ELSIF ( overlay_action == 'create_new' ) %] + Add incoming record + [% ELSIF ( overlay_action == 'ignore' ) %] + Ignore incoming record (its items may still be processed) + [% ELSE %] + [% overlay_action | html %] + [% END %] +
            4. +
            5. + Action if no match found: + [% IF ( nomatch_action == 'create_new' ) %] + Add incoming record + [% ELSIF ( nomatch_action == 'ignore' ) %] + Ignore incoming record (its items may still be processed) + [% ELSE %] + [% nomatch_action | html %] + [% END %] +
            6. + [% IF ( record_type == 'biblio' ) %] +
            7. + Item processing: + [% IF ( item_action == 'always_add' ) %] + Always add items + [% ELSIF ( item_action == 'add_only_for_matches' ) %] + Add items only if matching bib was found + [% ELSIF ( item_action == 'add_only_for_new' ) %] + Add items only if no matching bib was found + [% ELSIF ( item_action == 'ignore' ) %] + Ignore items + [% ELSE %] + [% item_action | html %] + [% END %] +
            8. [% END %] - [% END # /IF batch_lis %] +
            +
            - [% IF import_batch_id && !did_clean %] -
            - - - - - - - - - - - - -
            #CitationStatusMatch typeMatch detailsDiffRecord
            + [% IF ( can_revert ) %] +
            + [% INCLUDE 'csrf-token.inc' %] + + +
            +
            + [% END # /IF can_revert %] + [% END #/UNLESS can_commit %] + [% END #/UNLESS job_enqueue %] + [% END # /IF batch_info %] + +
            + + [% IF ( batch_list ) %] + [% IF ( pages ) %] + [% PROCESS pagination %] + [% END %] +
            + + + + + + + + + + + + + + + + + [% FOREACH batch_lis IN batch_list %] + + + + + + + + + + + + + [% END # /FOREACH batch_lis %] + +
            #File nameProfileCommentsTypeStatusStaged# Records# ItemsAction
            [% batch_lis.import_batch_id | html %][% batch_lis.file_name | html %][% batch_lis.profile | html %][% batch_lis.comments | html %][% IF ( batch_lis.record_type == 'auth' ) %]Authority[% ELSE %]Bibliographic[% END %] + [% IF ( batch_lis.import_status == 'cleaned' ) %] + Cleaned + [% ELSIF ( batch_lis.import_status == 'imported' ) %] + Imported + [% ELSIF ( batch_lis.import_status == 'importing' ) %] + Importing + [% ELSIF ( batch_lis.import_status == 'reverted' ) %] + Reverted + [% ELSIF ( batch_lis.import_status == 'reverting' ) %] + Reverting + [% ELSIF ( batch_lis.import_status == 'staged' ) %] + Staged + [% ELSE %] + [% batch_lis.import_status | html %] + [% END %] + [% batch_lis.upload_timestamp | $KohaDates with_hours=1 %][% batch_lis.num_records | html %][% batch_lis.num_items | html %] + [% IF ( batch_lis.num_items && batch_lis.import_status == 'imported' ) %] + (Create label batch) + [% END %] + + [% IF ( batch_lis.can_clean ) %] +
            + [% INCLUDE 'csrf-token.inc' %] + + + +
            + [% ELSIF ( batch_lis.import_status == 'cleaned' ) %] +
            + [% INCLUDE 'csrf-token.inc' %] + + + +
            + [% END %] +
            +
            + + + [% IF ( pages ) %] + [% PROCESS pagination %] + [% END %] + [% END # /IF batch_lis %] + + [% IF import_batch_id && !did_clean %] +
            + + + + + + + + + + + + +
            #CitationStatusMatch typeMatch detailsDiffRecord
            +
            + + + + [% END # /IF import_batch_id %] +[% END %] [% MACRO jsinclude BLOCK %] [% Asset.js("lib/jquery/plugins/humanmsg.js") | $raw %] [% INCLUDE 'datatables.inc' %] @@ -628,7 +643,6 @@ ); [% END %] }); - [% END %] [% INCLUDE 'intranet-bottom.inc' %] @@ -637,8 +651,12 @@
              [% FOREACH page IN pages %] [% IF ( page.current_page && page.page_number > 1 ) %] -
            • First
            • -
            • Previous
            • +
            • First
            • +
            • Previous
            • [% END %] [% END %] [% FOREACH page IN pages %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/tools/marc_modification_templates.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/tools/marc_modification_templates.tt index 22a9c11645..d7954480c3 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/tools/marc_modification_templates.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/tools/marc_modification_templates.tt @@ -13,14 +13,16 @@ [% END %] [% END %] [% END %] -[% FILTER collapse %] - [% IF ( template_name ) %] - [% tx("Actions for template '{template_name}'", template_name = template_name ) | html %] › - [% END %] - [% t("MARC modification templates") | html %] › - [% t("Cataloging") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% IF ( template_name ) %] + [% tx("Actions for template '{template_name}'", template_name = template_name ) | html %] + › + [% END %] + [% t("MARC modification templates") | html %] + › [% t("Cataloging") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] [% FILTER collapse %] @@ -43,52 +52,53 @@
              -
              -
              - [% INCLUDE 'messages.inc' %] -

              Compare matched records

              +
              +
              + [% INCLUDE 'messages.inc' %] +

              Compare matched records

              -
              -

              [% RECORDTITLE | html %]

              -
              -

              Original

              - [% IF ( ERROR_FORMATTED1 ) %] -
              -

              The record ID [% RECORDID | html %] doesn't match any existing record.

              -
              - [% ELSE %] -
              [% MARC_FORMATTED1 | html %]
              - [% END %] -
              -
              -

              Imported

              - [% IF ( ERROR_FORMATTED2 ) %] -
              -

              The import ID number [% IMPORTID | html %] doesn't match any existing record.

              -
              - [% ELSE %] -

              [% IMPORTTITLE | html %]

              -
              [% MARC_FORMATTED2 | html %] 
              - [% END %] +
              +

              [% RECORDTITLE | html %]

              +
              +

              Original

              + [% IF ( ERROR_FORMATTED1 ) %] +
              +

              The record ID [% RECORDID | html %] doesn't match any existing record.

              +
              + [% ELSE %] +
              [% MARC_FORMATTED1 | html %]
              + [% END %] +
              +
              +

              Imported

              + [% IF ( ERROR_FORMATTED2 ) %] +
              +

              The import ID number [% IMPORTID | html %] doesn't match any existing record.

              +
              + [% ELSE %] +

              [% IMPORTTITLE | html %]

              +
              [% MARC_FORMATTED2 | html %] 
              + [% END %] +
              +
              + Return to staged MARC batch [% batchid | html %] +
              -
              - Return to staged MARC batch [% batchid | html %] -
              -
              -
              +
            + [% MACRO jsinclude BLOCK %] [% Asset.js("js/tools-menu.js") | $raw %] [% Asset.js("lib/jsdiff/jsdiff.min.js") | $raw %] [% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/tools/stage-marc-import.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/tools/stage-marc-import.tt index 5a08cfa0dc..d5ff4771b5 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/tools/stage-marc-import.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/tools/stage-marc-import.tt @@ -4,17 +4,23 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% IF ( job_enqueued ) %] - [% t("Job enqueued") | html %] › - [% END %] - [% t("Stage MARC records for import") | html %] › - [% t("Cataloging") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% IF ( job_enqueued ) %] + [% t("Job enqueued") | html %] + › + [% END %] + [% t("Stage MARC records for import") | html %] + › [% t("Cataloging") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] [% Asset.css("css/humanmsg.css") | $raw %] @@ -48,206 +54,208 @@ [% WRAPPER 'main-container.inc' aside='cat-menu' %] - [% FOREACH message IN messages %] - [% SET message_class = "alert-info" %] - [% IF message.type == 'success' %] - [% message_class = "alert-info" %] - [% ELSIF message.type == 'warning' %] - [% message_class = "alert-warning" %] - [% ELSIF message.type == 'error' %] - [% message_class = "alert-warning" %] - [% END %] -
            - [% IF message.code == 'cannot_enqueue_job' %] - Cannot enqueue this job. - [% END %] - [% IF message.error %] - (The error was: [% message.error | html %], see the Koha log file for more information). - [% END %] -
            + [% FOREACH message IN messages %] + [% SET message_class = "alert-info" %] + [% IF message.type == 'success' %] + [% message_class = "alert-info" %] + [% ELSIF message.type == 'warning' %] + [% message_class = "alert-warning" %] + [% ELSIF message.type == 'error' %] + [% message_class = "alert-warning" %] [% END %] - - [% IF job_enqueued %] - - -

            MARC staging

            -
            -

            The job has been enqueued!

            -

            It will be processed as soon as possible.

            - [% INCLUDE "job_progress.inc" job_id=job_id %] -

            View detail of the enqueued job -

            -
            - [% ELSE %] -

            Stage MARC records for import

            -
              -
            • Select a MARC file to stage in the import reservoir. It will be parsed, and each valid record staged for later import into the catalog.
            • -
            • You can enter a name for this import. It may be useful, when creating a record, to remember where the suggested MARC data comes from!
            • -
            -
            -
            -Upload a file to stage -
              -
            1. -
              - - -
              -
            2. -
            -
            -
            - - -
            - -
            -
            Upload progress: - - 0% -
            -
            -
            -
            - -
            - Pre-fill values with profile? -
              -
            1. - - -
              When you select a profile it pre-fills your form with profile values.
              -
              Later you can modify your form and that's what matters on import.
              -
            2. -
            -
            - -
            - [% INCLUDE 'csrf-token.inc' %] - -[% IF basketno && booksellerid %] - - -[% END %] - -
            - - Settings -
            1. - - - -
            2. -
            3. - - -
            4. -
            5. - - -
            6. -
            7. - - -
            8. -
            + [% IF message.error %] + (The error was: [% message.error | html %], see the Koha log file for more information). + [% END %] + + [% END %] - [% IF MarcModificationTemplatesLoop %] -
            - Modify records using a MARC modification template? -
              -
            1. - - -
            2. -
            -
            - [% END %] + [% IF job_enqueued %] + -
            - Look for existing records in catalog? -
            1. - -
            2. -
            3. - [% INCLUDE 'tools-overlay-action.inc' %] -
            4. -
            5. - [% INCLUDE 'tools-nomatch-action.inc' %] -
            6. -
            -
            -
            - Check for embedded item record data? -
              -
            1. - - -
            2. -
            3. - - -
            4. -
            -
              -
            1. - [% INCLUDE 'tools-item-action.inc' %] -
            2. -
            -
            +

            MARC staging

            +
            +

            The job has been enqueued!

            +

            It will be processed as soon as possible.

            + [% INCLUDE "job_progress.inc" job_id=job_id %] +

            View detail of the enqueued job

            +
            + [% ELSE %] +

            Stage MARC records for import

            +
              +
            • Select a MARC file to stage in the import reservoir. It will be parsed, and each valid record staged for later import into the catalog.
            • +
            • You can enter a name for this import. It may be useful, when creating a record, to remember where the suggested MARC data comes from!
            • +
            + +
            + Upload a file to stage +
              +
            1. +
              + + +
              +
            2. +
            +
            +
            + + +
            -
            - Save profile -
              -
            1. - - - - -
            2. -
            -
            +
            +
            Upload progress: + + 0% +
            +
            +
            +
            -
            - -
            +
            + Pre-fill values with profile? +
              +
            1. + + +
              When you select a profile it pre-fills your form with profile values.
              +
              Later you can modify your form and that's what matters on import.
              +
            2. +
            +
            - -[% END %] +
            + [% INCLUDE 'csrf-token.inc' %] + + [% IF basketno && booksellerid %] + + + [% END %] + +
            + + Settings +
            1. + + +
            2. +
            3. + + +
            4. +
            5. + + +
            6. +
            7. + + +
            8. +
            + [% IF MarcModificationTemplatesLoop %] +
            + Modify records using a MARC modification template? +
              +
            1. + + +
            2. +
            +
            + [% END %] + +
            + Look for existing records in catalog? +
            1. + +
            2. +
            3. + [% INCLUDE 'tools-overlay-action.inc' %] +
            4. +
            5. + [% INCLUDE 'tools-nomatch-action.inc' %] +
            6. +
            +
            +
            + Check for embedded item record data? +
              +
            1. + + +
            2. +
            3. + + +
            4. +
            +
              +
            1. + [% INCLUDE 'tools-item-action.inc' %] +
            2. +
            +
            + +
            + Save profile +
              +
            1. + + + + +
            2. +
            +
            + +
            + +
            +
            + [% END %] [% END %] [% MACRO jsinclude BLOCK %] @@ -508,8 +516,6 @@ select.change(); }); } - - [% END %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/tools/stockrotation.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/tools/stockrotation.tt index af6d20d333..6bd670be11 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/tools/stockrotation.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/tools/stockrotation.tt @@ -7,30 +7,40 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% IF (op == 'create_edit_rota' && rota.rota_id) %] - [% tx("Modify rota '{rota_title}'", rota_title = rota.title ) %] › - [% ELSIF (op == 'create_edit_rota' && !rota.rota_id) %] - [% t("New rota") | html %] › - [% ELSIF (op == 'manage_stages') %] - [% tx("Manage stages for '{rota_title}'", rota_title = rota.title ) %] › - [% ELSIF (op == 'create_edit_stage' && stage.id) %] - [% tx("Modify {library} stage", library = Branches.GetName(stage.branchcode_id) ) %] › - [% tx("Manage stages for '{rota_title}'", rota_title = rota.title ) %] › - [% ELSIF (op == 'create_edit_stage' && !stage.id) %] - [% t("New stage") | html %] › - [% ELSIF (op == 'manage_items') %] - [% tx("Manage items for '{rota_title}'", rota_title = rota.title ) %] › - [% ELSIF op == 'add_items_to_rota' %] - [% t("Add items" ) | html %] › - [% tx("Manage items for '{rota_title}'", rota_title = rota.title ) %] › - [% END # /IF (op == 'create_edit_rota' %] - [% t("Stock rotation") | html %] › - [% t("Cataloging") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% IF (op == 'create_edit_rota' && rota.rota_id) %] + [% tx("Modify rota '{rota_title}'", rota_title = rota.title ) %] + › + [% ELSIF (op == 'create_edit_rota' && !rota.rota_id) %] + [% t("New rota") | html %] + › + [% ELSIF (op == 'manage_stages') %] + [% tx("Manage stages for '{rota_title}'", rota_title = rota.title ) %] + › + [% ELSIF (op == 'create_edit_stage' && stage.id) %] + [% tx("Modify {library} stage", library = Branches.GetName(stage.branchcode_id) ) %] + › [% tx("Manage stages for '{rota_title}'", rota_title = rota.title ) %] › + [% ELSIF (op == 'create_edit_stage' && !stage.id) %] + [% t("New stage") | html %] + › + [% ELSIF (op == 'manage_items') %] + [% tx("Manage items for '{rota_title}'", rota_title = rota.title ) %] + › + [% ELSIF op == 'add_items_to_rota' %] + [% t("Add items" ) | html %] + › [% tx("Manage items for '{rota_title}'", rota_title = rota.title ) %] › + [% END # /IF (op == 'create_edit_rota' %] + [% t("Stock rotation") | html %] + › [% t("Cataloging") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] - + @@ -101,539 +111,577 @@
            [% INCLUDE 'messages.inc' %] -
            +
            + [% IF no_op_set %] - [% IF no_op_set %] + [% INCLUDE 'stockrotation-toolbar.inc' %] - [% INCLUDE 'stockrotation-toolbar.inc' %] +

            Stock rotation

            -

            Stock rotation

            - - [% IF existing_rotas.size > 0 %] -
            - - - - - - - - - - - - - [% FOREACH rota IN existing_rotas %] + [% IF existing_rotas.size > 0 %] +
            +
            NameCyclicalActiveDescriptionNumber of itemsActions
            + - - - - - - + + + + + + - [% END %] - -
            [% rota.title | html %][% rota.cyclical ? 'Yes' : 'No' | html %][% rota.active ? 'Yes' : 'No' | html %][% rota.description | html %][% rota.stockrotationitems.count | html %] - - - Edit - -
            - - -
            -
            - [% INCLUDE 'csrf-token.inc' %] - - - -
            - - - Delete - -
            NameCyclicalActiveDescriptionNumber of itemsActions
            -
            - [% END %] - - [% ELSIF (op == 'create_edit_rota') %] - - [% IF rota.rota_id %] -

            [% tx("Modify rota '{rota_title}'", rota_title = rota.title ) %]

            - [% ELSE %] -

            New rota

            - [% END %] - - [% IF error == 'invalid_form' %] -
            -

            There was a problem with your form submission

            -
            - [% END %] - -
            - [% INCLUDE 'csrf-token.inc' %] -
            -
              -
            1. - - - Required -
            2. -
            3. - - -
            4. -
            5. - - -
            6. -
            -
            -
            - - Cancel -
            - [% IF rota.rota_id %] - - [% END %] - -
            - - [% ELSIF (op == 'manage_stages') %] - - [% INCLUDE 'stockrotation-toolbar.inc' %] - - [% IF error == 'invalid_form' %] -
            -

            There was a problem with your form submission

            -
            - [% END %] - -

            [% tx("Manage stages for '{rota_title}'", rota_title = rota.title ) %]

            -
            - - - - - - -
            - - - - - [% IF existing_stages.size > 0 %] -
            -
            - Stages can be re-ordered by using the handle to drag and drop them to their new position -
            -
            - Library - Duration (days) -
            -
              - [% FOREACH stage IN existing_stages %] -
            • - - [% IF existing_stages.size > 1 %] - - [% END %] - [% Branches.GetName(stage.branchcode_id) | html %] - - [% stage.duration | html %] - - - Edit - - - Delete - - -
            • - [% END %] -
            -
            - [% ELSE %] - -
            -

            This rota has no stages.

            -

            -
            - - [% END %] - -

            Return to rotas

            - - [% ELSIF (op == 'create_edit_stage') %] - - [% IF stage.id %] -

            [% tx("Modify {library} stage", library = Branches.GetName(stage.branchcode_id) ) %]

            - [% ELSE %] -

            New stage

            - [% END %] - - [% IF error == 'invalid_form' %] -
            -

            There was a problem with your form submission

            -
            - [% END %] - -
            - [% INCLUDE 'csrf-token.inc' %] -
            -
              -
            1. - - - Required -
            2. -
            3. - - - Required -
            4. -
            -
            -
            - - Cancel -
            - - - -
            - [% ELSIF (op == 'confirm_delete_rota') %] - -
            -

            Are you sure you want to delete this rota?

            - [% IF sritemstotal > 0 %] - [% IF sritemstotal == 1 %] -

            [% sritemstotal | html %] item is still attached to this rota, that item will remain at its current stage libraries.

            - [% ELSE %] -

            [% sritemstotal | html %] items are still attached to this rota, those items will remain at their current stage libraries.

            - [% END %] - [% END %] -
            -
            - [% INCLUDE 'csrf-token.inc' %] - - - -
            - No -
            -
            - [% ELSIF (op == 'confirm_delete_stage') %] - -
            -

            Are you sure you want to delete this stage?

            - [% IF stage.stockrotationitems.count > 0 %] -

            This stage contains the following item(s):

            -
              - [% FOREACH sritem IN stage.stockrotationitems %] -
            • [% sritem.item.biblio.title | html %] (Barcode: [% sritem.item.barcode | html %])
            • - [% END %] -
            - [% END %] -
            -
            - [% INCLUDE 'csrf-token.inc' %] - - - -
            - No -
            -
            - [% ELSIF (op == 'manage_items') %] - - [% INCLUDE 'stockrotation-toolbar.inc' %] - - [% IF error %] -
            - [% IF error == "item_not_found" %] -

            The item was not found

            - [% ELSIF error == "already_on_rota" %] -

            This item is already on this rota

            - [% END %] -
            - [% END %] - -

            [% tx("Manage items for '{rota_title}'", rota_title = rota.title ) %]

            - - - - - [% IF sritems.count > 0 %] -
            - - - - - - - - - - - - - - [% FOREACH sritem IN sritems %] - [%- SET transfer = sritem.item.get_transfer -%] - - - - - - - - + [% FOREACH rota IN existing_rotas %] + + + + + + + - - [% END %] - -
            BarcodeTitleAuthorCall numberIn transitStages & duration in days
            (current stage highlighted)
            Actions
            [% sritem.item.barcode | html %][% sritem.item.biblio.title | html %][% sritem.item.biblio.author | html %][% sritem.item.itemcallnumber | html %][% IF ( transfer ) %] - [% IF (transfer.reason.match('Stockrotation.*')) %] - [% IF (transfer.datesent) %] - In transit from [% Branches.GetName( transfer.frombranch ) | html %] to [% Branches.GetName( transfer.tobranch ) | html %] since [% transfer.datesent | $KohaDates %] - [% ELSE %] - Transit pending from [% Branches.GetName( transfer.frombranch ) | html %] to [% Branches.GetName( transfer.tobranch ) | html %] since [% transfer.daterequested | $KohaDates %] - [% END %] - [% END %] - [% END %] - - [%- FOREACH this_stage IN stages -%] - [% SET stage_class = "stage" %] - [%- IF this_stage.stage_id == sritem.stage.stage_id -%] - [% stage_class = stage_class _ " highlight_stage" %] - [%- END -%] - - [%- Branches.GetName(this_stage.branchcode_id) | html -%] ([%- this_stage.duration | html -%]) - » - [%- END -%] - [%- IF stages.size > 0 -%] - [% rota.cyclical ? 'START' : 'END' | html %] - [%- END -%] - - [%- IF stages.size < 2 -%] - - [%- ELSE -%] - [% SET button_title = "" %] - [% IF transfer %] - [% button_title = "Item is in transit, it will be directed to new stage when checked in" %] - [% END %] - - Move to next stage - [%- END -%] - - [%- IF !transfer -%] - - [%- IF sritem.indemand -%] - Remove "In demand" - [%- ELSE -%] - Add "In demand" - [%- END -%] + +
            [% rota.title | html %][% rota.cyclical ? 'Yes' : 'No' | html %][% rota.active ? 'Yes' : 'No' | html %][% rota.description | html %][% rota.stockrotationitems.count | html %] + + + Edit - [%- END -%] - - [%- IF !transfer -%] - - Remove from rota - [%- ELSE -%] - Remove from rota - [%- END -%] -
            -
            - [% ELSE %] - -
            -

            There are no items assigned to this rota.

            -

            -
            - - [% END %] - -

            Return to rotas

            - - [% ELSIF op == 'add_items_to_rota' %] - -

            [% tx("Add items to rota '{rota_title}'", rota_title = rota.title ) %]

            -

            Results

            -
            - [% IF barcode_status.ok.size > 0 %] -

            Items added to rota:

            -
              - [% FOREACH item_ok IN barcode_status.ok %] -
            • [% item_ok.biblio.title | html %]
            • - [% END %] -
            +
            + + +
            +
            + [% INCLUDE 'csrf-token.inc' %] + + + +
            + + + Delete + + + + [% END %] + +
            [% END %] - [% IF barcode_status.on_this.size > 0 %] -

            Items already on this rota:

            -
              - [% FOREACH item_on_this IN barcode_status.on_this %] -
            • [% item_on_this.biblio.title | html %]
            • - [% END %] -
            - [% END %] - [% IF barcode_status.not_found.size > 0 %] -

            Barcodes not found:

            -
              - [% FOREACH barcode_not_found IN barcode_status.not_found %] -
            • [% barcode_not_found | html %]
            • - [% END %] -
            - [% END %] - [% IF barcode_status.on_other.size > 0 %] -

            Items found on other rotas:

            -
              - [% FOREACH item_on_other IN barcode_status.on_other %] -
            • [% item_on_other.biblio.title | html %]
            • - [% END %] -
            - [% END %] -
            + [% ELSIF (op == 'create_edit_rota') %] - [% IF barcode_status.on_other.size > 0 %] -
            + [% IF rota.rota_id %] +

            [% tx("Modify rota '{rota_title}'", rota_title = rota.title ) %]

            + [% ELSE %] +

            New rota

            + [% END %] + + [% IF error == 'invalid_form' %] +
            +

            There was a problem with your form submission

            +
            + [% END %] + + [% INCLUDE 'csrf-token.inc' %] -
            - Select items to move to this rota: - [% FOREACH item_on_other IN barcode_status.on_other %] -
          • [% item_on_other.biblio.title | html %] (Currently on "[% item_on_other.stockrotationitem.stage.rota.title | html %]")
          • - [% END %] - +
            +
              +
            1. + + + Required +
            2. +
            3. + + +
            4. +
            5. + + +
            6. +
            + Cancel
            - - + [% IF rota.rota_id %] + + [% END %] + + [% ELSIF (op == 'manage_stages') %] + + [% INCLUDE 'stockrotation-toolbar.inc' %] + + [% IF error == 'invalid_form' %] +
            +

            There was a problem with your form submission

            +
            + [% END %] + +

            [% tx("Manage stages for '{rota_title}'", rota_title = rota.title ) %]

            +
            + + + + + + +
            + + + + + + [% IF existing_stages.size > 0 %] +
            +
            Stages can be re-ordered by using the handle to drag and drop them to their new position
            +
            + Library + Duration (days) +
            +
              + [% FOREACH stage IN existing_stages %] +
            • + + [% IF existing_stages.size > 1 %] + + [% END %] + [% Branches.GetName(stage.branchcode_id) | html %] + + [% stage.duration | html %] + + Edit + Delete + +
            • + [% END %] +
            +
            + [% ELSE %] +
            +

            This rota has no stages.

            +

            +
            + [% END %] + +

            Return to rotas

            + [% ELSIF (op == 'create_edit_stage') %] + + [% IF stage.id %] +

            [% tx("Modify {library} stage", library = Branches.GetName(stage.branchcode_id) ) %]

            + [% ELSE %] +

            New stage

            + [% END %] + + [% IF error == 'invalid_form' %] +
            +

            There was a problem with your form submission

            +
            + [% END %] + +
            + [% INCLUDE 'csrf-token.inc' %] +
            +
              +
            1. + + + Required +
            2. +
            3. + + + Required +
            4. +
            +
            +
            + + Cancel +
            + + + +
            + [% ELSIF (op == 'confirm_delete_rota') %] +
            +

            Are you sure you want to delete this rota?

            + [% IF sritemstotal > 0 %] + [% IF sritemstotal == 1 %] +

            [% sritemstotal | html %] item is still attached to this rota, that item will remain at its current stage libraries.

            + [% ELSE %] +

            [% sritemstotal | html %] items are still attached to this rota, those items will remain at their current stage libraries.

            + [% END %] + [% END %] +
            +
            + [% INCLUDE 'csrf-token.inc' %] + + + +
            + No +
            +
            + [% ELSIF (op == 'confirm_delete_stage') %] +
            +

            Are you sure you want to delete this stage?

            + [% IF stage.stockrotationitems.count > 0 %] +

            This stage contains the following item(s):

            +
              + [% FOREACH sritem IN stage.stockrotationitems %] +
            • [% sritem.item.biblio.title | html %] (Barcode: [% sritem.item.barcode | html %])
            • + [% END %] +
            + [% END %] +
            +
            + [% INCLUDE 'csrf-token.inc' %] + + + +
            + No +
            +
            + [% ELSIF (op == 'manage_items') %] + + [% INCLUDE 'stockrotation-toolbar.inc' %] + + [% IF error %] +
            + [% IF error == "item_not_found" %] +

            The item was not found

            + [% ELSIF error == "already_on_rota" %] +

            This item is already on this rota

            + [% END %] +
            + [% END %] + +

            [% tx("Manage items for '{rota_title}'", rota_title = rota.title ) %]

            + + + + + + [% IF sritems.count > 0 %] +
            + + + + + + + + + + + + + + [% FOREACH sritem IN sritems %] + [%- SET transfer = sritem.item.get_transfer -%] + + + + + + + + + + [% END %] + +
            BarcodeTitleAuthorCall numberIn transitStages & duration in days
            (current stage highlighted)
            Actions
            [% sritem.item.barcode | html %][% sritem.item.biblio.title | html %][% sritem.item.biblio.author | html %][% sritem.item.itemcallnumber | html %][% IF ( transfer ) %] + [% IF (transfer.reason.match('Stockrotation.*')) %] + [% IF (transfer.datesent) %] + In transit from [% Branches.GetName( transfer.frombranch ) | html %] to [% Branches.GetName( transfer.tobranch ) | html %] since [% transfer.datesent | $KohaDates %] + [% ELSE %] + Transit pending from [% Branches.GetName( transfer.frombranch ) | html %] to [% Branches.GetName( transfer.tobranch ) | html %] since + [% transfer.daterequested | $KohaDates %] + [% END %] + [% END %] + [% END %] + + [%- FOREACH this_stage IN stages -%] + [% SET stage_class = "stage" %] + [%- IF this_stage.stage_id == sritem.stage.stage_id -%] + [% stage_class = stage_class _ " highlight_stage" %] + [%- END -%] + [%- Branches.GetName(this_stage.branchcode_id) | html -%] ([%- this_stage.duration | html -%]) » + [%- END -%] + [%- IF stages.size > 0 -%] + [% rota.cyclical ? 'START' : 'END' | html %] + [%- END -%] + + [%- IF stages.size < 2 -%] + + [%- ELSE -%] + [% SET button_title = "" %] + [% IF transfer %] + [% button_title = "Item is in transit, it will be directed to new stage when checked in" %] + [% END %] + + Move to next stage + [%- END -%] + + [%- IF !transfer -%] + + [%- IF sritem.indemand -%] + Remove "In demand" + [%- ELSE -%] + Add "In demand" + [%- END -%] + + [%- END -%] + + [%- IF !transfer -%] + + Remove from rota + [%- ELSE -%] + Remove from rota + [%- END -%] +
            +
            + + [% ELSE %] +
            +

            There are no items assigned to this rota.

            +

            +
            + [% END %] + +

            Return to rotas

            + [% ELSIF op == 'add_items_to_rota' %] +

            [% tx("Add items to rota '{rota_title}'", rota_title = rota.title ) %]

            +

            Results

            +
            + [% IF barcode_status.ok.size > 0 %] +

            Items added to rota:

            +
              + [% FOREACH item_ok IN barcode_status.ok %] +
            • [% item_ok.biblio.title | html %]
            • + [% END %] +
            + [% END %] + [% IF barcode_status.on_this.size > 0 %] +

            Items already on this rota:

            +
              + [% FOREACH item_on_this IN barcode_status.on_this %] +
            • [% item_on_this.biblio.title | html %]
            • + [% END %] +
            + [% END %] + [% IF barcode_status.not_found.size > 0 %] +

            Barcodes not found:

            +
              + [% FOREACH barcode_not_found IN barcode_status.not_found %] +
            • [% barcode_not_found | html %]
            • + [% END %] +
            + [% END %] + [% IF barcode_status.on_other.size > 0 %] +

            Items found on other rotas:

            +
              + [% FOREACH item_on_other IN barcode_status.on_other %] +
            • [% item_on_other.biblio.title | html %]
            • + [% END %] +
            + [% END %] +
            + + [% IF barcode_status.on_other.size > 0 %] +
            + [% INCLUDE 'csrf-token.inc' %] +
            + Select items to move to this rota: + [% FOREACH item_on_other IN barcode_status.on_other %] +
          • [% item_on_other.biblio.title | html %] (Currently on + "[% item_on_other.stockrotationitem.stage.rota.title | html %]")
          • + [% END %] +
            +
            + +
            + + +
            + [% END %] +

            Return to rota

            [% END %] -

            Return to rota

            - - [% END %] -
            - +
            - + +
            -
            - - + + + + + + [% MACRO jsinclude BLOCK %] [% INCLUDE 'datatables.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/tools/tools-home.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/tools/tools-home.tt index a6a079b7cf..bf1d14de86 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/tools/tools-home.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/tools/tools-home.tt @@ -4,15 +4,17 @@ [% USE Registers %] [% PROCESS 'i18n.inc' %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("Tools") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("Tools") | html %] + › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] [% WRAPPER 'header.inc' %] -[% INCLUDE 'cat-search.inc' %] + [% INCLUDE 'cat-search.inc' %] [% END %] [% WRAPPER 'sub-header.inc' %] @@ -24,175 +26,177 @@ [% END #/ WRAPPER sub-header.inc %] [% WRAPPER 'main-container.inc' %] -

            Tools

            -
            -
            - [% IF ( CAN_user_tools_manage_patron_lists || CAN_user_clubs || CAN_user_tools_moderate_comments || CAN_user_tools_import_patrons || CAN_user_tools_edit_notices || CAN_user_tools_edit_notice_status_triggers || CAN_user_tools_label_creator || CAN_user_tools_delete_anonymize_patrons || CAN_user_tools_edit_patrons || CAN_user_tools_batch_extend_due_dates || CAN_user_tools_moderate_tags || CAN_user_tools_rotating_collections || ( CAN_user_tools_batch_upload_patron_images && Koha.Preference('patronimages') ) ) %] -

            Patrons and circulation

            - [% END %] -
            - [% IF (CAN_user_tools_manage_patron_lists) %] -
            Patron lists
            -
            Manage lists of patrons
            +

            Tools

            +
            +
            + [% IF ( CAN_user_tools_manage_patron_lists || CAN_user_clubs || CAN_user_tools_moderate_comments || CAN_user_tools_import_patrons || CAN_user_tools_edit_notices || CAN_user_tools_edit_notice_status_triggers || CAN_user_tools_label_creator || CAN_user_tools_delete_anonymize_patrons || CAN_user_tools_edit_patrons || CAN_user_tools_batch_extend_due_dates || CAN_user_tools_moderate_tags || CAN_user_tools_rotating_collections || ( CAN_user_tools_batch_upload_patron_images && Koha.Preference('patronimages') ) ) %] +

            Patrons and circulation

            + [% END %] +
            + [% IF (CAN_user_tools_manage_patron_lists) %] +
            Patron lists
            +
            Manage lists of patrons
            + [% END %] + + [% IF (CAN_user_clubs) %] +
            Patron clubs
            +
            Manage patron clubs
            + [% END %] + + [% IF ( CAN_user_tools_moderate_comments ) %] +
            + Comments + [% IF ( pendingcomments ) %] + [% pendingcomments | html %] [% END %] +
            +
            Moderate patron comments
            + [% END %] - [% IF (CAN_user_clubs) %] -
            Patron clubs
            -
            Manage patron clubs
            + [% IF ( CAN_user_tools_import_patrons ) %] +
            Import patrons
            +
            Import patron data
            + [% END %] + + [% IF ( CAN_user_tools_edit_notices ) %] +
            Notices and slips
            +
            Define notices (print and email notification messages for overdues, etc.)
            + [% END %] + + [% IF ( CAN_user_tools_edit_notice_status_triggers ) %] +
            Overdue notice/status triggers
            +
            Set notice/status triggers for overdue items
            + [% END %] + + [% IF ( CAN_user_tools_label_creator ) %] +
            Patron card creator
            +
            Create printable patron cards
            + [% END %] + + [% IF ( CAN_user_tools_delete_anonymize_patrons ) %] +
            Batch patron deletion and anonymization
            +
            Batch delete patrons and delete patron circulation history
            + [% END %] + + [% IF ( CAN_user_tools_edit_patrons ) %] +
            Batch patron modification
            +
            Modify patrons in batch
            + [% END %] + + [% IF ( CAN_user_tools_batch_extend_due_dates ) %] +
            Batch extend due dates
            +
            Modify the due date checkouts in batch
            + [% END %] + + [% IF ( CAN_user_tools_moderate_tags ) %] +
            + Tags + [% IF ( pendingtags ) %] + [% pendingtags | html %] [% END %] +
            +
            Moderate patron tags
            + [% END %] - [% IF ( CAN_user_tools_moderate_comments ) %] -
            - Comments - [% IF ( pendingcomments ) %] - [% pendingcomments | html %] - [% END %] -
            -
            Moderate patron comments
            - [% END %] + [% IF ( CAN_user_tools_batch_upload_patron_images && Koha.Preference('patronimages') ) %] +
            Upload patron images
            +
            Upload patron images in a batch or one at a time
            + [% END %] - [% IF ( CAN_user_tools_import_patrons ) %] -
            Import patrons
            -
            Import patron data
            - [% END %] + [% IF ( CAN_user_tools_rotating_collections ) %] +
            Rotating collections
            +
            Manage rotating collections
            + [% END %] +
            +
            + - [% IF ( CAN_user_tools_edit_notices ) %] -
            Notices and slips
            -
            Define notices (print and email notification messages for overdues, etc.)
            - [% END %] +
            + [% IF ( CAN_user_tools_edit_calendar || CAN_user_tools_manage_csv_profiles || CAN_user_tools_view_system_logs || CAN_user_tools_edit_additional_contents || CAN_user_tools_schedule_tasks || CAN_user_tools_edit_quotes || ( plugins_enabled && CAN_user_plugins_tool ) || CAN_user_tools_upload_general_files || CAN_user_tools_access_files ) %] +

            Additional tools

            + [% END %] +
            + [% IF ( CAN_user_tools_edit_calendar ) %] +
            Calendar
            +
            Define days when the library is closed
            + [% END %] - [% IF ( CAN_user_tools_edit_notice_status_triggers ) %] -
            Overdue notice/status triggers
            -
            Set notice/status triggers for overdue items
            - [% END %] + [% IF ( CAN_user_tools_manage_csv_profiles ) %] +
            CSV profiles
            +
            Manage CSV export profiles
            + [% END %] - [% IF ( CAN_user_tools_label_creator ) %] -
            Patron card creator
            -
            Create printable patron cards
            - [% END %] + [% IF ( CAN_user_tools_view_system_logs ) %] +
            Log viewer
            +
            Browse the system logs
            + [% END %] - [% IF ( CAN_user_tools_delete_anonymize_patrons ) %] -
            Batch patron deletion and anonymization
            -
            Batch delete patrons and delete patron circulation history
            - [% END %] + [% IF ( CAN_user_tools_edit_additional_contents ) %] +
            News
            +
            Write news for the OPAC and staff interfaces
            - [% IF ( CAN_user_tools_edit_patrons ) %] -
            Batch patron modification
            -
            Modify patrons in batch
            - [% END %] +
            HTML customizations
            +
            Write HTML customizations
            - [% IF ( CAN_user_tools_batch_extend_due_dates ) %] -
            Batch extend due dates
            -
            Modify the due date checkouts in batch
            - [% END %] +
            Pages
            +
            Write custom pages
            + [% END %] - [% IF ( CAN_user_tools_moderate_tags ) %] -
            - Tags - [% IF ( pendingtags ) %] - [% pendingtags | html %] - [% END %] -
            -
            Moderate patron tags
            - [% END %] + [% IF ( CAN_user_tools_schedule_tasks ) %] +
            Task scheduler
            +
            Schedule tasks to run
            + [% END %] - [% IF ( CAN_user_tools_batch_upload_patron_images && Koha.Preference('patronimages') ) %] -
            Upload patron images
            -
            Upload patron images in a batch or one at a time
            - [% END %] + [% IF ( CAN_user_tools_edit_quotes ) %] +
            Quote editor
            +
            Manage 'Quote of the day' quotes
            + [% END %] - [% IF ( CAN_user_tools_rotating_collections ) %] -
            Rotating collections
            -
            Manage rotating collections
            - [% END %] -
            -
            + [% IF ( plugins_enabled && CAN_user_plugins_tool && tool_plugins ) %] +
            Tool plugins
            +
            + Use tool plugins + +
            + [% END %] -
            - [% IF ( CAN_user_tools_edit_calendar || CAN_user_tools_manage_csv_profiles || CAN_user_tools_view_system_logs || CAN_user_tools_edit_additional_contents || CAN_user_tools_schedule_tasks || CAN_user_tools_edit_quotes || ( plugins_enabled && CAN_user_plugins_tool ) || CAN_user_tools_upload_general_files || CAN_user_tools_access_files ) %] -

            Additional tools

            - [% END %] -
            - [% IF ( CAN_user_tools_edit_calendar ) %] -
            Calendar
            -
            Define days when the library is closed
            - [% END %] + [% IF ( CAN_user_tools_upload_general_files ) %] +
            Uploads
            +
            Upload any type of file, manage uploads
            + [% END %] - [% IF ( CAN_user_tools_manage_csv_profiles ) %] -
            CSV profiles
            -
            Manage CSV export profiles
            - [% END %] + [% IF CAN_user_tools_access_files %] +
            Access files
            +
            Access files stored on the server, like log files or reports
            + [% END %] - [% IF ( CAN_user_tools_view_system_logs ) %] -
            Log viewer
            -
            Browse the system logs
            - [% END %] + [% IF ( Koha.Preference('OPACReportProblem') && CAN_user_problem_reports ) %] +
            OPAC problem reports
            +
            Manage OPAC problem reports submitted by patrons
            + [% END %] +
            - [% IF ( CAN_user_tools_edit_additional_contents ) %] -
            News
            -
            Write news for the OPAC and staff interfaces
            + [% IF ( Koha.Preference('UseCashRegisters') && ( CAN_user_cash_management_cashup || CAN_user_cash_management_anonymous_refund ) ) %] +

            Cash management

            +
            +
            Cash summary for [% Branches.GetLoggedInBranchname | html %]
            +
            View cash takings for the current library
            -
            HTML customizations
            -
            Write HTML customizations
            - -
            Pages
            -
            Write custom pages
            - [% END %] - - [% IF ( CAN_user_tools_schedule_tasks ) %] -
            Task scheduler
            -
            Schedule tasks to run
            - [% END %] - - [% IF ( CAN_user_tools_edit_quotes ) %] -
            Quote editor
            -
            Manage 'Quote of the day' quotes
            - [% END %] - - [% IF ( plugins_enabled && CAN_user_plugins_tool && tool_plugins ) %] -
            Tool plugins
            -
            - Use tool plugins - -
            - [% END %] - - [% IF ( CAN_user_tools_upload_general_files ) %] -
            Uploads
            -
            Upload any type of file, manage uploads
            - [% END %] - - [% IF CAN_user_tools_access_files %] -
            Access files
            -
            Access files stored on the server, like log files or reports
            - [% END %] - - [% IF ( Koha.Preference('OPACReportProblem') && CAN_user_problem_reports ) %] -
            OPAC problem reports
            -
            Manage OPAC problem reports submitted by patrons
            - [% END %] -
            - - [% IF ( Koha.Preference('UseCashRegisters') && ( CAN_user_cash_management_cashup || CAN_user_cash_management_anonymous_refund ) ) %] -

            Cash management

            -
            -
            Cash summary for [% Branches.GetLoggedInBranchname | html %]
            -
            View cash takings for the current library
            - -
            Transaction history for [% Registers.session_register_name | html %]
            -
            View transaction history for the current cash register
            -
            - [% END %] - -
            -
            +
            Transaction history for [% Registers.session_register_name | html %]
            +
            View transaction history for the current cash register
            +
            + [% END %] +
            + +
            + [% END %] [% INCLUDE 'intranet-bottom.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/tools/upload-images.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/tools/upload-images.tt index 3f237e71c7..b440096787 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/tools/upload-images.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/tools/upload-images.tt @@ -4,14 +4,17 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% IF ( biblio ) %] - [% t("Upload local cover image for ") | html %] [% INCLUDE 'biblio-title-head.inc' %] › - [% END %] - [% t("Upload local cover image") | html %] › - [% t("Cataloging") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% IF ( biblio ) %] + [% t("Upload local cover image for ") | html %] + [% INCLUDE 'biblio-title-head.inc' %] + › + [% END %] + [% t("Upload local cover image") | html %] + › [% t("Cataloging") | html %] › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] [% FILTER collapse %] [% END %] @@ -124,173 +127,187 @@ [% WRAPPER 'main-container.inc' aside='cat-menu' %] - [% UNLESS itemnumber || biblionumber %] -

            Upload local cover image

            - [% ELSIF biblio %] -

            - Upload local cover image for [% INCLUDE 'biblio-title.inc' %] - [% IF ( itemnumber ) %], Item number: [% itemnumber | html %][% END %] -

            - [% ELSIF itemnumber %] -

            Upload local cover image for item number: [% itemnumber | html %]

            + [% UNLESS itemnumber || biblionumber %] +

            Upload local cover image

            + [% ELSIF biblio %] +

            + Upload local cover image for [% INCLUDE 'biblio-title.inc' %] + [% IF ( itemnumber ) %], Item number: [% itemnumber | html %][% END %] +

            + [% ELSIF itemnumber %] +

            Upload local cover image for item number: [% itemnumber | html %]

            + [% END %] + + [% IF ( uploadimage ) %] +

            Image upload results :

            +
            + [% IF ( error ) %] +
            + [% IF ( error == 'UZIPFAIL' ) %] +

            Failed to unzip archive.
            Please ensure you are uploading a valid zip file and try again.

            + [% ELSIF ( error == 'OPNLINK' ) %] +

            Cannot open folder index (idlink.txt or datalink.txt) to read.
            Please verify that it exists.

            + [% ELSIF ( error == 'OPNIMG' ) %] +

            Cannot process file as an image.
            Please ensure you only upload GIF, JPEG, PNG, or XPM images.

            + [% ELSIF ( error == 'DELERR' ) %] +

            Unrecognized or missing field delimiter.
            Please verify that you are using either a single quote or a tab.

            + [% ELSIF ( error == 'DBERR' ) %] +

            Unable to save image to database.

            + [% ELSE %] +

            An unknown error has occurred.
            Please review the error log for more details.

            + [% END %] +
            + [% END # /IF error %] +

            [% total | html %] images found

            + +
            +
            + + [% END # /IF uploadimage %] + +
              + [% UNLESS itemnumber || biblionumber %] +
            • Select an image file or ZIP file to upload. The tool will accept images in GIF, JPEG, PNG, and XPM formats.
            • + [% ELSE %] +
            • Select an image file to upload. The tool will accept images in GIF, JPEG, PNG, and XPM formats.
            • + [% END %] +
            + +
            + [% IF ( cover_images ) %] + [% SET column_class = "col-sm-9" %] + [% ELSE %] + [% SET column_class = "col-sm-12" %] + [% END %] +
            +
            +
            +
            + + +
            + +
            + Drop files here or click to select a file + [%# FIXME Remove the following div and use #message instead %] +
            +
            + +
            +
            Upload progress: + + 0% +
            +
            +
            +
            +
            + + +
            + [% INCLUDE 'csrf-token.inc' %] + + + + [% IF itemnumber %] + + + [% ELSIF biblionumber %] + + [% END %] - [% IF ( uploadimage ) %] -

            Image upload results :

            -
            - [% IF ( error ) %] -
            - [% IF ( error == 'UZIPFAIL' ) %] -

            Failed to unzip archive.
            Please ensure you are uploading a valid zip file and try again.

            - [% ELSIF ( error == 'OPNLINK' ) %] -

            Cannot open folder index (idlink.txt or datalink.txt) to read.
            Please verify that it exists.

            - [% ELSIF ( error == 'OPNIMG' ) %] -

            Cannot process file as an image.
            Please ensure you only upload GIF, JPEG, PNG, or XPM images.

            - [% ELSIF ( error == 'DELERR' ) %] -

            Unrecognized or missing field delimiter.
            Please verify that you are using either a single quote or a tab.

            - [% ELSIF ( error == 'DBERR' ) %] -

            Unable to save image to database.

            +
            +
              + [% UNLESS itemnumber || biblionumber %] +
            1. + [% IF (filetype != 'image' ) %] + [% ELSE %] -

              An unknown error has occurred.
              Please review the error log for more details.

              + [% END %] -
            - [% END # /IF error %] -

            [% total | html %] images found

            - -
            -
            - [% END # /IF uploadimage %] + + +
          • + [% IF (filetype == 'image' ) %] + + [% ELSE %] + + [% END %] + +
          • +
          • + + +
          • + [% END %] +
          • + +
          • + + -
              - [% UNLESS itemnumber || biblionumber %] -
            • Select an image file or ZIP file to upload. The tool will accept images in GIF, JPEG, PNG, and XPM formats.
            • +
              + + [% IF ( biblionumber ) %] + Cancel [% ELSE %] -
            • Select an image file to upload. The tool will accept images in GIF, JPEG, PNG, and XPM formats.
            • + Cancel [% END %] -
            + +
            + +
            + -
            - [% IF ( cover_images ) %] - [% SET column_class = "col-sm-9" %] - [% ELSE %] - [% SET column_class = "col-sm-12" %] - [% END %] -
            - -
            -
            -
            - - -
            - -
            - Drop files here or click to select a file - [%# FIXME Remove the following div and use #message instead %] -
            -
            - -
            -
            Upload progress: - - - 0% -
            -
            -
            -
            -
            - -
            - [% INCLUDE 'csrf-token.inc' %] - - - - [% IF itemnumber %] - - - [% ELSIF biblionumber %] - - - [% END %] - - -
            -
              - [% UNLESS itemnumber || biblionumber %] -
            1. - [% IF (filetype != 'image' ) %] - - [% ELSE %] - - [% END %] - -
            2. -
            3. - [% IF (filetype == 'image' ) %] - - [% ELSE %] - - [% END %] - -
            4. -
            5. - - -
            6. + [% IF ( cover_images.size ) %] +
            -
            - -
            - - [% IF ( biblionumber ) %] - Cancel - [% ELSE %] - Cancel - [% END %] -
            -
            -
            - - [% IF ( cover_images.size ) %] -
            -

            Existing images

            - -
            - [% END # /IF images.size %] - -
            + + Delete image + + [% END # /IF img %] + [% END # /FOREACH img %] +
          + + + + [% END # /IF images.size %] + + [% END %] [% MACRO jsinclude BLOCK %] [% END #/print %] - [% END %] [% INCLUDE 'intranet-bottom.inc' %] diff --git a/koha-tmpl/intranet-tmpl/prog/en/modules/virtualshelves/tables/shelves_results.tt b/koha-tmpl/intranet-tmpl/prog/en/modules/virtualshelves/tables/shelves_results.tt index f47f7c6273..c8f9522626 100644 --- a/koha-tmpl/intranet-tmpl/prog/en/modules/virtualshelves/tables/shelves_results.tt +++ b/koha-tmpl/intranet-tmpl/prog/en/modules/virtualshelves/tables/shelves_results.tt @@ -2,74 +2,65 @@ [% USE KohaDates %] [% USE To %] [% PROCESS 'i18n.inc' %] -{ - "draw": [% draw | html %], - "recordsTotal": [% recordsTotal | html %], - "recordsFiltered": [% recordsFiltered | html %], - "data": [ - [% FOREACH d IN data %] - { - "dt_public": - "[% d.public | html %]", - "dt_shelfname": - "[% d.shelfname | html | $To %]", - "dt_count": - "[% tnx('{count} item', '{count} items', count, { count = d.count }) | $raw %]", - "dt_is_shared": - "[% IF d.public %]Public[% ELSIF d.is_shared %]Shared[% ELSE %]Private[% END %]", - "dt_owner": - "[% d.firstname | html | $To %] [% d.surname | html | $To %]", - "dt_sortby": - [% IF d.sortby == "author" %]"Author"[% ELSIF d.sortby == "copyrightdate" %]"Year"[% ELSIF d.sortby == "itemcallnumber" %]"Call number"[% ELSIF d.sortby == "dateadded" %]"Date added"[% ELSE %]"Title"[% END %], - "dt_created_on": - "[% d.created_on | $KohaDates %]", - "dt_modification_time": - "[% d.modification_time | $KohaDates %]", - "dt_action": - "[% PROCESS action_form shelfnumber=d.shelfnumber can_manage_shelf=d.can_manage_shelf can_delete_shelf=d.can_delete_shelf type=d.type %]" - }[% UNLESS loop.last %],[% END %] - [% END %] - ] -} - +{ "draw": [% draw | html %], "recordsTotal": [% recordsTotal | html %], "recordsFiltered": [% recordsFiltered | html %], "data": [ +[% FOREACH d IN data %] + { "dt_public": "[% d.public | html %]", "dt_shelfname": "[% d.shelfname | html | $To %]", "dt_count": + "[% tnx('{count} item', '{count} items', count, { count = d.count }) | $raw %]", "dt_is_shared": "[% IF d.public %]Public[% ELSIF d.is_shared %]Shared[% ELSE %]Private[% END %]", "dt_owner": "[% d.firstname | html | $To %] [% d.surname | html | $To %]", "dt_sortby": + [% IF d.sortby == "author" %] + "Author" + [% ELSIF d.sortby == "copyrightdate" %] + "Year" + [% ELSIF d.sortby == "itemcallnumber" %] + "Call number" + [% ELSIF d.sortby == "dateadded" %] + "Date added" + [% ELSE %] + "Title" + [% END %], + "dt_created_on": "[% d.created_on | $KohaDates %]", "dt_modification_time": "[% d.modification_time | $KohaDates %]", "dt_action": + "[% PROCESS action_form shelfnumber=d.shelfnumber can_manage_shelf=d.can_manage_shelf can_delete_shelf=d.can_delete_shelf type=d.type %]" }[% UNLESS loop.last %],[% END %] +[% END %] +] } [% BLOCK action_form -%] -[%~ SET action_block = '' ~%] -[%~ IF can_manage_shelf OR can_delete_shelf ~%] - [%~ shelfnumber = shelfnumber | html ~%] - [%~ public = public | html ~%] - [%~ IF can_manage_shelf ~%] - [%~ action_block = '
          ' ~%] - [%~ action_block = action_block _ '' ~%] - [%~ action_block = action_block _ '' ~%] - [%~ action_block = action_block _ '' ~%] - [%~ action_block = action_block _ '' ~%] - [%~ action_block = action_block _ '' ~%] - [%~ action_block = action_block _ '
          ' ~%] + [%~ SET action_block = '' ~%] + [%~ IF can_manage_shelf OR can_delete_shelf ~%] + [%~ shelfnumber = shelfnumber | html ~%] + [%~ public = public | html ~%] + [%~ IF can_manage_shelf ~%] + [%~ action_block = '
          ' ~%] + [%~ action_block = action_block _ '' ~%] + [%~ action_block = action_block _ '' ~%] + [%~ action_block = action_block _ '' ~%] + [%~ action_block = action_block _ '' ~%] + [%~ action_block = action_block _ '' ~%] + [%~ action_block = action_block _ '
          ' ~%] + [%~ END ~%] + [%~ IF can_delete_shelf ~%] + [%~ action_block = action_block _ '
          ' ~%] + [%~ action_block = BLOCK ~%][%~ action_block | $raw ~%][%~ INCLUDE 'csrf-token.inc' | trim ~%][%~ END ~%] + [%~ action_block = action_block _ '' ~%] + [%~ action_block = action_block _ '' ~%] + [%~ action_block = action_block _ '' ~%] + [%~ action_block = action_block _ '' ~%] + [%~ action_block = action_block _ '' ~%] + [%~ action_block = action_block _ '' ~%] + [%~ action_block = action_block _ '
          ' ~%] + [%~ END ~%] + [%~ IF public AND allow_transfer ~%] + [%~ action_block = action_block _ '
          ' ~%] + [%~ action_block = action_block _ '' ~%] + [%~ action_block = action_block _ '' ~%] + [%~ action_block = action_block _ '' ~%] + [%~ action_block = action_block _ '' ~%] + [%~ action_block = action_block _ '' ~%] + [%~ action_block = action_block _ '' ~%] + [%~ action_block = action_block _ '
          ' ~%] + [%~ END ~%] + [%~ ELSE ~%] + [%~ SET action_block = 'None' ~%] [%~ END ~%] - [%~ IF can_delete_shelf ~%] - [%~ action_block = action_block _ '
          ' ~%] - [%~ action_block = BLOCK ~%][%~ action_block | $raw ~%][%~ INCLUDE 'csrf-token.inc' | trim ~%][%~ END ~%] - [%~ action_block = action_block _ '' ~%] - [%~ action_block = action_block _ '' ~%] - [%~ action_block = action_block _ '' ~%] - [%~ action_block = action_block _ '' ~%] - [%~ action_block = action_block _ '' ~%] - [%~ action_block = action_block _ '' ~%] - [%~ action_block = action_block _ '
          ' ~%] - [%~ END ~%] - [%~ IF public AND allow_transfer ~%] - [%~ action_block = action_block _ '
          ' ~%] - [%~ action_block = action_block _ '' ~%] - [%~ action_block = action_block _ '' ~%] - [%~ action_block = action_block _ '' ~%] - [%~ action_block = action_block _ '' ~%] - [%~ action_block = action_block _ '' ~%] - [%~ action_block = action_block _ '' ~%] - [%~ action_block = action_block _ '
          ' ~%] - [%~ END ~%] -[%~ ELSE ~%] - [%~ SET action_block = 'None' ~%] -[%~ END ~%] -[%~ To.json(action_block) | $raw ~%] - + [%~ To.json(action_block) | $raw ~%] [%~ END ~%] diff --git a/koha-tmpl/intranet-tmpl/prog/js/acq.js b/koha-tmpl/intranet-tmpl/prog/js/acq.js index 059cd4cea2..760e9e1dae 100644 --- a/koha-tmpl/intranet-tmpl/prog/js/acq.js +++ b/koha-tmpl/intranet-tmpl/prog/js/acq.js @@ -5,33 +5,38 @@ //input validation: // acqui/uncertainprice.tmpl uses this function uncheckbox(form, field) { - var price = new Number(form.elements['price' + field].value); + var price = new Number(form.elements["price" + field].value); var tmpprice = ""; - var errmsg = __("ERROR: Price is not a valid number, please check the price and try again!"); + var errmsg = __( + "ERROR: Price is not a valid number, please check the price and try again!" + ); if (isNaN(price)) { alert(errmsg); - for(var i=0; i 0) { return false; } @@ -39,30 +44,33 @@ function isNull(f,noalert) { } //Function returns false if v is not a number (if maybenull is 0, it also returns an error if the number is 0) -function isNum(v,maybenull) { +function isNum(v, maybenull) { var n = new Number(v.value); if (isNaN(n)) { return false; } - if (maybenull==0 && v.value=='') { - - - return false; + if (maybenull == 0 && v.value == "") { + return false; } return true; } - //a logging function (a bit buggy, might open millions of log pages when initializing, but works fine after... function log(message) { if (!log.window_ || log.window_.closed) { - var win = window.open("", null, "width=400,height=200," + - "scrollbars=yes,resizable=yes,status=no," + - "location=no,menubar=no,toolbar=no"); + var win = window.open( + "", + null, + "width=400,height=200," + + "scrollbars=yes,resizable=yes,status=no," + + "location=no,menubar=no,toolbar=no" + ); if (!win) return; var doc = win.document; - doc.write("Debug Log" + - ""); + doc.write( + "Debug Log" + + "" + ); doc.close(); log.window_ = win; } @@ -72,127 +80,137 @@ function log(message) { } //======================================================================= -function getElementsByClass( searchClass, domNode, tagName) { +function getElementsByClass(searchClass, domNode, tagName) { if (domNode == null) domNode = document; - if (tagName == null) tagName = '*'; + if (tagName == null) tagName = "*"; var el = new Array(); var tags = domNode.getElementsByTagName(tagName); - var tcl = " "+searchClass+" "; - for(i=0,j=0; i 0 ) { - remainingTotal.style.color = 'green'; - } else { // if its negative, make it red.. - remainingTotal.style.color = 'red'; + if (remainingNew == 0) { + remainingTotal.style.color = "black"; + } else if (remainingNew > 0) { + remainingTotal.style.color = "green"; + } else { + // if its negative, make it red.. + remainingTotal.style.color = "red"; } - remainingTotal.textContent = remainingNew.toFixed(2) ; + remainingTotal.textContent = remainingNew.toFixed(2); } function autoFillRow(bud_id) { + var remainingTotal = document.getElementById("budget_est_" + bud_id); + var remainingNew = new Number(); + var budgetTotal = document.getElementById( + "budget_tot_" + bud_id + ).textContent; + var arr = getElementsByClass("plan_entry_" + bud_id); - var remainingTotal = document.getElementById("budget_est_"+bud_id); - var remainingNew = new Number; - var budgetTotal = document.getElementById("budget_tot_"+bud_id ).textContent; - var arr = getElementsByClass("plan_entry_" + bud_id); - - budgetTotal = budgetTotal.replace(/\,/, ""); - var qty = new Number; -// get the totals + budgetTotal = budgetTotal.replace(/\,/, ""); + var qty = new Number(); + // get the totals var novalueArr = new Array(); - for ( var i=0, len=arr.length; i


          "); + win.document.write( + "


          " + ); win.document.write(etc); - win.document.write("

          "); + win.document.write( + "
          " + ); win.document.write("
          "); } - //======================================================================= // NEXT BLOCK IS USED BY NEWORDERBEMPTY -function updateCosts(){ +function updateCosts() { var quantity = new Number($("#quantity").val()); var discount = new Number($("#discount").val()); - var listprice = new Number($("#listprice").val()); + var listprice = new Number($("#listprice").val()); var currcode = new String($("#currency").val()); - var exchangerate = new Number($("#currency_rate_"+currcode).val()); - var gst_on=false; + var exchangerate = new Number($("#currency_rate_" + currcode).val()); + var gst_on = false; - var rrp = new Number(listprice*exchangerate); - var rep = new Number(listprice*exchangerate); + var rrp = new Number(listprice * exchangerate); + var rep = new Number(listprice * exchangerate); var ecost = rrp; - if ( 100-discount != 100 ) { //Prevent rounding issues if no discount - ecost = new Number(Math.floor(rrp * (100 - discount )) / 100); + if (100 - discount != 100) { + //Prevent rounding issues if no discount + ecost = new Number(Math.floor(rrp * (100 - discount)) / 100); } - var total = new Number( ecost * quantity); + var total = new Number(ecost * quantity); $("#rrp").val(rrp.toFixed(2)); $("#replacementprice").val(rep.toFixed(2)); $("#ecost").val(ecost.toFixed(2)); @@ -208,26 +226,34 @@ function syncReplacementPrice(sourceId, targetId) { } // Calculates total amount in a suggestion -function calcNewsuggTotal(){ +function calcNewsuggTotal() { //collect values - var quantity = Number(document.getElementById('quantity').value); - var currcode = String(document.getElementById('currency').value); - var price = Number(document.getElementById('price').value); - var exchangerate = Number(document.getElementById('currency_rate_'+currcode).value); + var quantity = Number(document.getElementById("quantity").value); + var currcode = String(document.getElementById("currency").value); + var price = Number(document.getElementById("price").value); + var exchangerate = Number( + document.getElementById("currency_rate_" + currcode).value + ); - var total = Number(quantity*price*exchangerate); + var total = Number(quantity * price * exchangerate); - document.getElementById('total').value = total.toFixed(2); - document.getElementById('price').value = price.toFixed(2); + document.getElementById("total").value = total.toFixed(2); + document.getElementById("price").value = price.toFixed(2); return true; } -function getAuthValueDropbox( name, cat, destination, selected ) { - if ( typeof(selected) == 'undefined' ) { +function getAuthValueDropbox(name, cat, destination, selected) { + if (typeof selected == "undefined") { selected = ""; } if (cat == null || cat == "") { - $(destination).replaceWith(' ' ); + $(destination).replaceWith( + ' ' + ); return; } $.ajax({ @@ -235,163 +261,198 @@ function getAuthValueDropbox( name, cat, destination, selected ) { data: { name: name, category: cat, - default: selected + default: selected, }, async: false, - success: function(data){ - if(data === "0"){ - $(destination).replaceWith(' ' ); - }else{ + success: function (data) { + if (data === "0") { + $(destination).replaceWith( + ' ' + ); + } else { $(destination).replaceWith(data); } - } + }, }); } //USED BY NEWORDEREMPTY.PL function totalExceedsBudget(budgetId, total) { - var xmlhttp = null; xmlhttp = new XMLHttpRequest(); - if ( typeof xmlhttp.overrideMimeType != 'undefined') { - xmlhttp.overrideMimeType('text/xml'); + if (typeof xmlhttp.overrideMimeType != "undefined") { + xmlhttp.overrideMimeType("text/xml"); } - var url = '../acqui/check_budget_total.pl?budget_id=' + budgetId + "&total=" + total; - xmlhttp.open('GET', url, false); + var url = + "../acqui/check_budget_total.pl?budget_id=" + + budgetId + + "&total=" + + total; + xmlhttp.open("GET", url, false); xmlhttp.send(null); - xmlhttp.onreadystatechange = function() { + xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { + actTotal = eval(xmlhttp.responseText); - actTotal = eval ( xmlhttp.responseText ); - - if ( Math.abs(actTotal) < Math.abs(total) ) { - // if budget is to low :( - return true ; + if (Math.abs(actTotal) < Math.abs(total)) { + // if budget is to low :( + return true; } else { return false; } } - } + }; } - //USED BY AQBUDGETS.TMPL function budgetExceedsParent(budgetTotal, budgetId, newBudgetParent, periodID) { - - var xmlhttp = null; xmlhttp = new XMLHttpRequest(); - if ( typeof xmlhttp.overrideMimeType != 'undefined') { - xmlhttp.overrideMimeType('text/xml'); + if (typeof xmlhttp.overrideMimeType != "undefined") { + xmlhttp.overrideMimeType("text/xml"); } -// make the call... yawn -// var url = '../admin/check_parent_total.pl?budget_id=' + budgetId + '&parent_id=' + newBudgetParent + "&total=" + budgetTotal + "&period_id="+ periodID ; + // make the call... yawn + // var url = '../admin/check_parent_total.pl?budget_id=' + budgetId + '&parent_id=' + newBudgetParent + "&total=" + budgetTotal + "&period_id="+ periodID ; + var url = + "../admin/check_parent_total.pl?total=" + + budgetTotal + + "&period_id=" + + periodID; - var url = '../admin/check_parent_total.pl?total=' + budgetTotal + "&period_id="+ periodID ; + if (budgetId) { + url += "&budget_id=" + budgetId; + } + if (newBudgetParent) { + url += "&parent_id=" + newBudgetParent; + } -if (budgetId ) { url += '&budget_id=' + budgetId }; -if ( newBudgetParent ) { url += '&parent_id=' + newBudgetParent}; - - - xmlhttp.open('GET', url, false); + xmlhttp.open("GET", url, false); xmlhttp.send(null); - xmlhttp.onreadystatechange = function() { + xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { - // stupid JS... + // stupid JS... } else { - // wait for the call to complete + // wait for the call to complete } }; - var result = eval ( xmlhttp.responseText ); + var result = eval(xmlhttp.responseText); - if (result == '1') { - return "- " + __("Fund amount exceeds parent allocation") + "\n"; - } else if (result == '2') { - return "- " + __("Fund amount exceeds period allocation") + "\n"; - } else { - return false; + if (result == "1") { + return "- " + __("Fund amount exceeds parent allocation") + "\n"; + } else if (result == "2") { + return "- " + __("Fund amount exceeds period allocation") + "\n"; + } else { + return false; } } - - - //USED BY AQBUDGETS.TMPL function checkBudgetParent(budgetId, newBudgetParent) { var xmlhttp = null; xmlhttp = new XMLHttpRequest(); - if ( typeof xmlhttp.overrideMimeType != 'undefined') { - xmlhttp.overrideMimeType('text/xml'); + if (typeof xmlhttp.overrideMimeType != "undefined") { + xmlhttp.overrideMimeType("text/xml"); } - var url = '../admin/check_budget_parent.pl?budget_id=' + budgetId + '&new_parent=' + newBudgetParent; - xmlhttp.open('GET', url, false); + var url = + "../admin/check_budget_parent.pl?budget_id=" + + budgetId + + "&new_parent=" + + newBudgetParent; + xmlhttp.open("GET", url, false); xmlhttp.send(null); - xmlhttp.onreadystatechange = function() { + xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { - // do something with the results + // do something with the results } else { - // wait for the call to complete + // wait for the call to complete } }; - var result = eval ( xmlhttp.responseText ); + var result = eval(xmlhttp.responseText); - if (result == '1') { - return "- " + __("New budget-parent is beneath budget") + "\n"; -// } else if (result == '2') { -// return "- New budget-parent has insufficent funds\n"; -// } else { -// return false; + if (result == "1") { + return "- " + __("New budget-parent is beneath budget") + "\n"; + // } else if (result == '2') { + // return "- New budget-parent has insufficent funds\n"; + // } else { + // return false; } } function hideColumn(num) { - $("#hideall,#showall").prop("checked", false).parent().removeClass("selected"); - $("#"+num).parent().removeClass("selected"); - var hide = Number(num.replace("col","")) + 2; + $("#hideall,#showall") + .prop("checked", false) + .parent() + .removeClass("selected"); + $("#" + num) + .parent() + .removeClass("selected"); + var hide = Number(num.replace("col", "")) + 2; // hide header and cells matching the index - $("#plan td:nth-child("+hide+"),#plan th:nth-child("+hide+")").toggle(); + $( + "#plan td:nth-child(" + hide + "),#plan th:nth-child(" + hide + ")" + ).toggle(); } -function showColumn(num){ +function showColumn(num) { $("#hideall").prop("checked", false).parent().removeClass("selected"); - $("#"+num).parent().addClass("selected"); + $("#" + num) + .parent() + .addClass("selected"); // set the index of the table column to hide - show = Number(num.replace("col","")) + 2; + show = Number(num.replace("col", "")) + 2; // hide header and cells matching the index - $("#plan td:nth-child("+show+"),#plan th:nth-child("+show+")").toggle(); + $( + "#plan td:nth-child(" + show + "),#plan th:nth-child(" + show + ")" + ).toggle(); } -function showAllColumns(){ - $("#selections").find("input:checkbox").each(function () { - $(this).prop("checked", true); - }); +function showAllColumns() { + $("#selections") + .find("input:checkbox") + .each(function () { + $(this).prop("checked", true); + }); $("#selections span").addClass("selected"); $("#plan td:nth-child(2),#plan tr th:nth-child(2)").nextAll().show(); $("#hideall").prop("checked", false).parent().removeClass("selected"); } -function hideAllColumns(){ +function hideAllColumns() { var allCols = $("#plan th").length; - $("#selections").find("input:checkbox").each(function () { - $(this).prop("checked", false); - }); + $("#selections") + .find("input:checkbox") + .each(function () { + $(this).prop("checked", false); + }); $("#selections span").removeClass("selected"); - $("#plan td:nth-child(2),#plan th:nth-child(2)").nextUntil("th:nth-child("+(allCols-1)+"),td:nth-child("+(allCols-1)+")").hide(); // hide all but the last two columns + $("#plan td:nth-child(2),#plan th:nth-child(2)") + .nextUntil( + "th:nth-child(" + + (allCols - 1) + + "),td:nth-child(" + + (allCols - 1) + + ")" + ) + .hide(); // hide all but the last two columns $("#hideall").prop("checked", true).parent().addClass("selected"); } -$(document).ready(function(){ - $("#deleteVendorModal").on("shown.bs.modal", function(e){ +$(document).ready(function () { + $("#deleteVendorModal").on("shown.bs.modal", function (e) { var button = $(e.relatedTarget); - var item = button.data('booksellerid'); - $('#booksellerid').val(item); + var item = button.data("booksellerid"); + $("#booksellerid").val(item); }); }); diff --git a/koha-tmpl/intranet-tmpl/prog/js/acquisitions-menu.js b/koha-tmpl/intranet-tmpl/prog/js/acquisitions-menu.js index 313ae0f5ef..bf6ec45f54 100644 --- a/koha-tmpl/intranet-tmpl/prog/js/acquisitions-menu.js +++ b/koha-tmpl/intranet-tmpl/prog/js/acquisitions-menu.js @@ -1,20 +1,26 @@ -function searchToOrder( basketno, vendorid ){ +function searchToOrder(basketno, vendorid) { var date = new Date(); var cookieData = ""; - date.setTime(date.getTime() + (10 * 60 * 1000)); + date.setTime(date.getTime() + 10 * 60 * 1000); cookieData += basketno + "/" + vendorid; - Cookies.set("searchToOrder", cookieData, { path: "/", expires: date, sameSite: 'Lax' }); + Cookies.set("searchToOrder", cookieData, { + path: "/", + expires: date, + sameSite: "Lax", + }); } -$(document).ready(function() { +$(document).ready(function () { var path = location.pathname.substring(1); if (path.indexOf("invoice") >= 0) { - $('#navmenulist a[href$="/cgi-bin/koha/acqui/invoices.pl"]').addClass("current"); + $('#navmenulist a[href$="/cgi-bin/koha/acqui/invoices.pl"]').addClass( + "current" + ); } - $("body").on("click", "#searchtoorder", function(){ + $("body").on("click", "#searchtoorder", function () { var vendorid = $(this).data("booksellerid"); var basketno = $(this).data("basketno"); - searchToOrder( basketno, vendorid ); + searchToOrder(basketno, vendorid); }); }); diff --git a/koha-tmpl/intranet-tmpl/prog/js/additem.js b/koha-tmpl/intranet-tmpl/prog/js/additem.js index 5bad33ba4f..462e8db8f3 100644 --- a/koha-tmpl/intranet-tmpl/prog/js/additem.js +++ b/koha-tmpl/intranet-tmpl/prog/js/additem.js @@ -1,125 +1,178 @@ /* global __ */ /* exported addItem checkCount showItem deleteItemBlock clearItemBlock check_additem */ -function addItem( node, unique_item_fields ) { +function addItem(node, unique_item_fields) { var item_form = $(node).closest("div"); var index = item_form.attr("id"); //We need to verify the item form before saving var empty_item_mandatory = CheckMandatorySubfields(item_form); if (empty_item_mandatory > 0) { - var _alertString= __("Form not submitted because of the following problem(s)")+"\n"; + var _alertString = + __("Form not submitted because of the following problem(s)") + "\n"; - _alertString +="-------------------------------------------------------------------\n\n"; _alertString += - "\n- " + __("%s item mandatory fields empty").format(empty_item_mandatory); + "-------------------------------------------------------------------\n\n"; + _alertString += + "\n- " + + __("%s item mandatory fields empty").format(empty_item_mandatory); alert(_alertString); return false; } var current_qty = parseInt($("#quantity").val()); var max_qty; - if($("#quantity_to_receive").length != 0){ + if ($("#quantity_to_receive").length != 0) { max_qty = parseInt($("#quantity_to_receive").val()); - } else { + } else { max_qty = 99999; } - if ( $("#items_list table").find('tr[idblock="' + index + '"]').length == 0 ) { - if ( current_qty < max_qty ) { - if ( current_qty < max_qty - 1 ) + if ( + $("#items_list table").find('tr[idblock="' + index + '"]').length == 0 + ) { + if (current_qty < max_qty) { + if (current_qty < max_qty - 1) cloneItemBlock(index, unique_item_fields); addItemInList(index, unique_item_fields); - $("#" + index).find("input[name='buttonPlus']").val( __("Update item") ); - $("#"+ index).find("input[name='buttonPlusMulti']").remove(); - $("#" + index).find("input[name='multiValue']").remove(); - $("#quantity").val(current_qty + 1).change(); - } else if ( current_qty >= max_qty ) { - alert( __("You can't receive any more items") ); + $("#" + index) + .find("input[name='buttonPlus']") + .val(__("Update item")); + $("#" + index) + .find("input[name='buttonPlusMulti']") + .remove(); + $("#" + index) + .find("input[name='multiValue']") + .remove(); + $("#quantity") + .val(current_qty + 1) + .change(); + } else if (current_qty >= max_qty) { + alert(__("You can't receive any more items")); } } else { - if ( current_qty < max_qty ) - cloneItemBlock(index, unique_item_fields); + if (current_qty < max_qty) cloneItemBlock(index, unique_item_fields); var tr = constructTrNode(index); - $("#items_list table").find('tr[idblock="' + index + '"]:first').replaceWith(tr); + $("#items_list table") + .find('tr[idblock="' + index + '"]:first') + .replaceWith(tr); } $("#" + index).hide(); } -function addMulti( count, node, unique_item_fields){ - var index = $(node).closest("div").attr('id'); +function addMulti(count, node, unique_item_fields) { + var index = $(node).closest("div").attr("id"); var countItemsBefore = $("#items_list tbody tr").length; - var current_qty = parseInt( $('#quantity').val(), 10 ); - $("#procModal").modal('show'); + var current_qty = parseInt($("#quantity").val(), 10); + $("#procModal").modal("show"); $("#" + index).hide(); - for(var i=0;i"; - var edit_link = " " - + ( __("Edit") ) + ""; - var del_link = " " - + ( __("Delete") ) + ""; + var edit_link = + " " + + __("Edit") + + ""; + var del_link = + " " + + __("Delete") + + ""; result += "" + edit_link + " " + del_link + ""; - for(var i in fields) { + for (var i in fields) { var field = fields[i]; var field_elt = $("#" + index) - .find("[name='kohafield'][value='items."+field+"']") + .find("[name='kohafield'][value='items." + field + "']") .prevAll("[name='field_value']")[0]; var field_value; - if($(field_elt).is('select')) { + if ($(field_elt).is("select")) { field_value = $(field_elt).find("option:selected").text(); } else { field_value = $(field_elt).val(); } if (field_value == undefined) { - field_value = ''; + field_value = ""; } result += "" + field_value + ""; } @@ -132,7 +185,7 @@ function addItemInList(index, unique_item_fields, callback) { $("#items_list").show(); var tr = constructTrNode(index, unique_item_fields); $("#items_list table tbody").append(tr); - if (typeof callback === "function"){ + if (typeof callback === "function") { callback(); } } @@ -141,186 +194,257 @@ function deleteItemBlock(node_a, index, unique_item_fields) { $("#" + index).remove(); var current_qty = parseInt($("#quantity").val()); var max_qty; - if($("#quantity_to_receive").length != 0) { + if ($("#quantity_to_receive").length != 0) { max_qty = parseInt($("#quantity_to_receive").val()); } else { max_qty = 99999; } - $("#quantity").val(current_qty - 1).change(); - $(node_a).parents('tr').remove(); - if(current_qty - 1 == 0) - $("#items_list").hide(); + $("#quantity") + .val(current_qty - 1) + .change(); + $(node_a).parents("tr").remove(); + if (current_qty - 1 == 0) $("#items_list").hide(); - if ( $("#quantity").val() <= max_qty - 1) { - if ( $("#outeritemblock").children("div :visible").length == 0 ) { + if ($("#quantity").val() <= max_qty - 1) { + if ($("#outeritemblock").children("div :visible").length == 0) { $("#outeritemblock").children("div:last").show(); } } - if ( $("#quantity").val() == 0 && $("#outeritemblock > div").length == 0) { + if ($("#quantity").val() == 0 && $("#outeritemblock > div").length == 0) { cloneItemBlock(0, unique_item_fields); } } function cloneItemBlock(index, unique_item_fields, callback) { var original; - if(index) { + if (index) { original = $("#" + index); //original
          } var dont_copy_fields = new Array(); - if(unique_item_fields) { - dont_copy_fields = unique_item_fields.split('|'); - for(var i in dont_copy_fields) { + if (unique_item_fields) { + dont_copy_fields = unique_item_fields.split("|"); + for (var i in dont_copy_fields) { dont_copy_fields[i] = "items." + dont_copy_fields[i]; } } $.ajax({ url: "/cgi-bin/koha/services/itemrecorddisplay.pl", - dataType: 'html', + dataType: "html", data: { - frameworkcode: 'ACQ' + frameworkcode: "ACQ", }, - success: function(data) { + success: function (data) { /* Create the item block */ - var random = Math.floor(Math.random()*100000); // get a random itemid. - var clone = $("
          ", { id: 'itemblock'+random }); + var random = Math.floor(Math.random() * 100000); // get a random itemid. + var clone = $("
          ", { id: "itemblock" + random }); $("#outeritemblock").append(clone); $(clone).append(data); /* Change all itemid fields value */ - $(clone).find("input[name='itemid']").each(function(){ - $(this).val(random); - }); + $(clone) + .find("input[name='itemid']") + .each(function () { + $(this).val(random); + }); /* Add buttons + and Clear */ - var buttonPlus = "
          "; - buttonPlus += ''; - buttonPlus += ''; - buttonPlus += ''; - buttonPlus += ''; + var buttonPlus = '
          '; + buttonPlus += + ''; + buttonPlus += + ''; + buttonPlus += + ''; + buttonPlus += + '"; buttonPlus += "
          "; $(clone).append(buttonPlus); /* Copy values from the original block (input) */ - $(original).find("input[name='field_value']").each(function(){ - var kohafield = $(this).siblings("input[name='kohafield']").val(); - if($(this).val() && $.inArray(kohafield,dont_copy_fields) == -1) { - $(this).closest("li div").attr("id").match(/^(subfield.)/); - var id = RegExp.$1; - var value = $(this).val(); - $(clone).find("div[id^='"+id+"'] input[name='field_value']").val(value); - } - }); + $(original) + .find("input[name='field_value']") + .each(function () { + var kohafield = $(this) + .siblings("input[name='kohafield']") + .val(); + if ( + $(this).val() && + $.inArray(kohafield, dont_copy_fields) == -1 + ) { + $(this) + .closest("li div") + .attr("id") + .match(/^(subfield.)/); + var id = RegExp.$1; + var value = $(this).val(); + $(clone) + .find( + "div[id^='" + + id + + "'] input[name='field_value']" + ) + .val(value); + } + }); /* Copy values from the original block (select) */ - $(original).find("select[name='field_value']").each(function(){ - var kohafield = $(this).siblings("input[name='kohafield']").val(); - if($(this).val() && $.inArray(kohafield,dont_copy_fields) == -1) { - $(this).parent("div").attr("id").match(/^(subfield.)/); - var id = RegExp.$1; - var value = $(this).val(); - $(clone).find("div[id^='"+id+"'] select[name='field_value']").val(value); - } - }); + $(original) + .find("select[name='field_value']") + .each(function () { + var kohafield = $(this) + .siblings("input[name='kohafield']") + .val(); + if ( + $(this).val() && + $.inArray(kohafield, dont_copy_fields) == -1 + ) { + $(this) + .parent("div") + .attr("id") + .match(/^(subfield.)/); + var id = RegExp.$1; + var value = $(this).val(); + $(clone) + .find( + "div[id^='" + + id + + "'] select[name='field_value']" + ) + .val(value); + } + }); - if (typeof callback === "function"){ - var cloneIndex = "itemblock"+random; + if (typeof callback === "function") { + var cloneIndex = "itemblock" + random; callback(cloneIndex); } BindPluginEvents(data); - } + }, }); } function BindPluginEvents(data) { -// the script tag in data for plugins contains a document ready that binds -// the events for the plugin -// when we append, this code does not get executed anymore; so we do it here - var events= data.match(/BindEventstag_\d+_subfield_._\d+/g); - if ( events == null ) return; - for(var i=0; i"); + fieldname + + " '" + + sorted_arr[i] + + "' " + + __("is duplicated") + + "
          " + ); success = false; } } } // If there is a duplication, we raise an error - if ( success == false ) { + if (success == false) { $(".order_error").show(); return false; } $.ajax({ - url: '/cgi-bin/koha/acqui/check_uniqueness.pl', + url: "/cgi-bin/koha/acqui/check_uniqueness.pl", async: false, - dataType: 'json', + dataType: "json", data: data, - success: function(data) { + success: function (data) { for (var field in data) { success = false; - for (var i=0; i < data[field].length; i++) { + for (var i = 0; i < data[field].length; i++) { var value = data[field][i]; $(".order_error").append( - field + " '" + value + "' " - + __("already exists in database") - + "
          " + field + + " '" + + value + + "' " + + __("already exists in database") + + "
          " ); } } - } + }, }); - if ( success == false ) { + if (success == false) { $(".order_error").show(); } return success; } - diff --git a/koha-tmpl/intranet-tmpl/prog/js/additional-fields-entry.js b/koha-tmpl/intranet-tmpl/prog/js/additional-fields-entry.js index a50ba9e33a..a9e3f286c9 100644 --- a/koha-tmpl/intranet-tmpl/prog/js/additional-fields-entry.js +++ b/koha-tmpl/intranet-tmpl/prog/js/additional-fields-entry.js @@ -37,4 +37,4 @@ var original = $(node).parent(); $("input", original).val(""); } -})(); \ No newline at end of file +})(); diff --git a/koha-tmpl/intranet-tmpl/prog/js/addorderiso2709.js b/koha-tmpl/intranet-tmpl/prog/js/addorderiso2709.js index 332712a3a7..4d3ba2eb02 100644 --- a/koha-tmpl/intranet-tmpl/prog/js/addorderiso2709.js +++ b/koha-tmpl/intranet-tmpl/prog/js/addorderiso2709.js @@ -1,27 +1,31 @@ /* global dataTablesDefaults __ template_path */ -$(document).ready(function() { +$(document).ready(function () { $("#Aform").preventDoubleFormSubmit(); - $("#files").dataTable($.extend(true, {}, dataTablesDefaults, { - "columnDefs": [ - { "orderable": false, "searchable": false, "targets": [ 'NoSort' ] }, - { "type": "anti-the", "targets": [ "anti-the" ] } - ], - "pagingType": "full", - "order": [] - }) ); + $("#files").dataTable( + $.extend(true, {}, dataTablesDefaults, { + columnDefs: [ + { orderable: false, searchable: false, targets: ["NoSort"] }, + { type: "anti-the", targets: ["anti-the"] }, + ], + pagingType: "full", + order: [], + }) + ); checkOrderBudgets(); var all_budget_id = $("#all_budget_id"); - $("#all_budget_id,[name='budget_id'],.budget_code_item,[name='import_record_id']").on("change", function(){ + $( + "#all_budget_id,[name='budget_id'],.budget_code_item,[name='import_record_id']" + ).on("change", function () { checkOrderBudgets(); }); $(".order_details").hide(); - $('input:checkbox[name="import_record_id"]').change(function(){ + $('input:checkbox[name="import_record_id"]').change(function () { var container = $(this).parents("tr"); - if ( $(this).is(':checked') ) { + if ($(this).is(":checked")) { $(container).addClass("order-selected"); $(container).removeClass("order-unselected"); $(container).find(".order_details").toggle(true); @@ -30,52 +34,62 @@ $(document).ready(function() { $(container).removeClass("order-selected"); $(container).find(".order_details").toggle(false); } - } ); + }); $("input:checkbox").prop("checked", false); - $("div.biblio.order-unselected select").prop('disabled', false); - $("div.biblio.order-unselected input").prop('disabled', false); + $("div.biblio.order-unselected select").prop("disabled", false); + $("div.biblio.order-unselected input").prop("disabled", false); - $("#checkAll").click(function(e){ + $("#checkAll").click(function (e) { e.preventDefault(); - $("input:checkbox[name='import_record_id']").prop("checked", true).change(); + $("input:checkbox[name='import_record_id']") + .prop("checked", true) + .change(); }); - $("#unCheckAll").click(function(e){ + $("#unCheckAll").click(function (e) { e.preventDefault(); - $("input:checkbox[name='import_record_id']").prop("checked", false).change(); + $("input:checkbox[name='import_record_id']") + .prop("checked", false) + .change(); }); - $("input#add_order").on("click", function(e){ + $("input#add_order").on("click", function (e) { e.preventDefault(); - if ( $("input:checkbox[name='import_record_id']:checked").length < 1 ) { - alert( __("There is no record selected") ); + if ($("input:checkbox[name='import_record_id']:checked").length < 1) { + alert(__("There is no record selected")); return false; } var error = 0; - $("input:checkbox[name='import_record_id']:checked").parents('fieldset').find('input[name="quantity"]').each(function(){ - if ( $(this).val().length < 1 || isNaN( $(this).val() ) ) { - error++; - } - }); - if ( error > 0 ) { - alert(error + " " + __("quantity values are not filled in or are not numbers") ); + $("input:checkbox[name='import_record_id']:checked") + .parents("fieldset") + .find('input[name="quantity"]') + .each(function () { + if ($(this).val().length < 1 || isNaN($(this).val())) { + error++; + } + }); + if (error > 0) { + alert( + error + + " " + + __("quantity values are not filled in or are not numbers") + ); return false; - } error = checkOrderBudgets(); - if ( error > 0 ) { - alert( __("Some funds are not defined in item records") ); + if (error > 0) { + alert(__("Some funds are not defined in item records")); return false; } if (0 < CheckMandatorySubfields(this.form)) { // Open the item tab - $('.nav-tabs .items_info').tab('show'); + $(".nav-tabs .items_info").tab("show"); - alert(__('Some required item subfields are not set')); + alert(__("Some required item subfields are not set")); return false; } @@ -84,53 +98,63 @@ $(document).ready(function() { $(this.form).submit(); }); - $(".previewData").on("click", function(e){ + $(".previewData").on("click", function (e) { e.preventDefault(); var ltitle = $(this).text(); var page = $(this).attr("href"); $("#dataPreviewLabel").text(ltitle); $("#dataPreview .modal-body").load(page + " div"); - $('#dataPreview').modal("show"); + $("#dataPreview").modal("show"); }); - $("#dataPreview").on("hidden.bs.modal", function(e){ + $("#dataPreview").on("hidden.bs.modal", function (e) { e.preventDefault(); $("#dataPreviewLabel").html(""); - $("#dataPreview .modal-body").html("
          \"\" " + __("Loading") + "
          "); + $("#dataPreview .modal-body").html( + '
          ' + + __("Loading") + + "
          " + ); }); }); -function disableUnchecked(){ - $("fieldset.biblio.order-unselected").each(function(){ +function disableUnchecked() { + $("fieldset.biblio.order-unselected").each(function () { $(this).remove(); }); return 1; } -function checkOrderBudgets(){ +function checkOrderBudgets() { var unset_funds = 0; var all_budget_id = $("#all_budget_id"); // If we don't have an overarching default set we need to check each selected order - if ( !all_budget_id.val() ) { - $("fieldset.biblio.rows.order-selected").each(function(){ + if (!all_budget_id.val()) { + $("fieldset.biblio.rows.order-selected").each(function () { var default_order_fund = $(this).find("[name='budget_id']"); // For each order we see if budget is set for order - if( !default_order_fund.val() ){ + if (!default_order_fund.val()) { $(this).find(".item_fund.required").show(); //If not we need to check each item on the order var item_funds = $(this).find(".budget_code_item"); - if( item_funds.length ){ - item_funds.each(function(){ - if( !$(this).val() ){ - $(this).addClass('required').prop("required", true); + if (item_funds.length) { + item_funds.each(function () { + if (!$(this).val()) { + $(this).addClass("required").prop("required", true); unset_funds++; } else { - $(this).removeClass('required').prop("required", false); + $(this) + .removeClass("required") + .prop("required", false); } }); } else { //If the order has no items defined then the order level fund is required - default_order_fund.addClass('required').prop("required", true); + default_order_fund + .addClass("required") + .prop("required", true); $(this).find(".fund span.required").show(); $(this).find(".item_fund.required").hide(); unset_funds++; @@ -138,22 +162,26 @@ function checkOrderBudgets(){ } else { $(this).find(".fund span.required").hide(); // If fund is set for order then none of the others are required - $(this).find(".budget_code_item").each(function(){ - if( !$(this).val() ){ - $(this).val( default_order_fund.val() ); - $(this).removeClass('required').prop("required", false); - } - }); - $(this).removeClass('required').prop("required", false); + $(this) + .find(".budget_code_item") + .each(function () { + if (!$(this).val()) { + $(this).val(default_order_fund.val()); + $(this) + .removeClass("required") + .prop("required", false); + } + }); + $(this).removeClass("required").prop("required", false); } }); } else { // Default is set overall, we just need to populate it through // to each order/item - $("[name='budget_id'],.budget_code_item").each(function(){ - if( !$(this).val() ){ - $(this).val( all_budget_id.val() ); - $(this).removeClass('required').prop("required", false); + $("[name='budget_id'],.budget_code_item").each(function () { + if (!$(this).val()) { + $(this).val(all_budget_id.val()); + $(this).removeClass("required").prop("required", false); $(".item_fund.required").hide(); $(".fund span.required").hide(); } diff --git a/koha-tmpl/intranet-tmpl/prog/js/admin-menu.js b/koha-tmpl/intranet-tmpl/prog/js/admin-menu.js index f7b69c77fe..fa171232ce 100644 --- a/koha-tmpl/intranet-tmpl/prog/js/admin-menu.js +++ b/koha-tmpl/intranet-tmpl/prog/js/admin-menu.js @@ -1,14 +1,30 @@ -$(document).ready(function() { +$(document).ready(function () { var path = location.pathname.substring(1); - if (path == "cgi-bin/koha/admin/marctagstructure.pl" || path == "cgi-bin/koha/admin/marc_subfields_structure.pl") { - $('#navmenulist a[href$="/cgi-bin/koha/admin/biblio_framework.pl"]').addClass("current"); - } else if (path == "cgi-bin/koha/admin/auth_tag_structure.pl" || path == "cgi-bin/koha/admin/auth_subfields_structure.pl") { - $('#navmenulist a[href$="/cgi-bin/koha/admin/authtypes.pl"]').addClass("current"); + if ( + path == "cgi-bin/koha/admin/marctagstructure.pl" || + path == "cgi-bin/koha/admin/marc_subfields_structure.pl" + ) { + $( + '#navmenulist a[href$="/cgi-bin/koha/admin/biblio_framework.pl"]' + ).addClass("current"); + } else if ( + path == "cgi-bin/koha/admin/auth_tag_structure.pl" || + path == "cgi-bin/koha/admin/auth_subfields_structure.pl" + ) { + $('#navmenulist a[href$="/cgi-bin/koha/admin/authtypes.pl"]').addClass( + "current" + ); } else if (path == "cgi-bin/koha/admin/oai_set_mappings.pl") { - $('#navmenulist a[href$="/cgi-bin/koha/admin/oai_sets.pl"]').addClass("current"); + $('#navmenulist a[href$="/cgi-bin/koha/admin/oai_sets.pl"]').addClass( + "current" + ); } else if (path == "cgi-bin/koha/admin/items_search_field.pl") { - $('#navmenulist a[href$="/cgi-bin/koha/admin/items_search_fields.pl"]').addClass("current"); + $( + '#navmenulist a[href$="/cgi-bin/koha/admin/items_search_fields.pl"]' + ).addClass("current"); } else if (path == "cgi-bin/koha/admin/clone-rules.pl") { - $('#navmenulist a[href$="/cgi-bin/koha/admin/smart-rules.pl"]').addClass("current"); + $( + '#navmenulist a[href$="/cgi-bin/koha/admin/smart-rules.pl"]' + ).addClass("current"); } }); diff --git a/koha-tmpl/intranet-tmpl/prog/js/ajax.js b/koha-tmpl/intranet-tmpl/prog/js/ajax.js index 805a05fbaa..7f3d7f51e1 100644 --- a/koha-tmpl/intranet-tmpl/prog/js/ajax.js +++ b/koha-tmpl/intranet-tmpl/prog/js/ajax.js @@ -1,88 +1,100 @@ -if ( KOHA === undefined ) var KOHA = {}; +if (KOHA === undefined) var KOHA = {}; KOHA.AJAX = { - Submit: function ( options ) { + Submit: function (options) { var error_callback = options.error; - $.extend( options, { + $.extend(options, { cache: false, - dataType: 'json', - type: 'POST', - error: function ( xhr, stat, error ) { KOHA.AJAX.BaseError( error_callback, xhr, stat, error ); } - } ); - $.ajax( options ); + dataType: "json", + type: "POST", + error: function (xhr, stat, error) { + KOHA.AJAX.BaseError(error_callback, xhr, stat, error); + }, + }); + $.ajax(options); }, - BaseError: function ( callback, xhr, stat, e ) { + BaseError: function (callback, xhr, stat, e) { KOHA.xhr = xhr; - if ( !xhr.getResponseHeader( 'content-type' ).match( 'application/json' ) ) { + if (!xhr.getResponseHeader("content-type").match("application/json")) { // Something really failed - humanMsg.displayAlert( __("Internal Server Error, please reload the page") ); + humanMsg.displayAlert( + __("Internal Server Error, please reload the page") + ); return; } - var error = eval( '(' + xhr.responseText + ')' ); + var error = eval("(" + xhr.responseText + ")"); - if ( error.type == 'auth' ) { - humanMsg.displayMsg( __("You need to log in again, your session has timed out") ); + if (error.type == "auth") { + humanMsg.displayMsg( + __("You need to log in again, your session has timed out") + ); } - if ( callback ) { - callback( error ); + if (callback) { + callback(error); } else { - humanMsg.displayAlert( __("Error; your data might not have been saved") ); + humanMsg.displayAlert( + __("Error; your data might not have been saved") + ); } }, - MarkRunning: function ( selector, text ) { + MarkRunning: function (selector, text) { text = text || __("Loading..."); - $( selector ) - .prop('disabled', true) - .each( function () { - var $spinner = $( '' ); + $(selector) + .prop("disabled", true) + .each(function () { + var $spinner = $(''); var selector_type = this.localName; if (selector_type === undefined) selector_type = this.nodeName; // IE only - switch ( selector_type.toLowerCase() ) { - case 'input': - $( this ).data( 'original-text', this.value ); + switch (selector_type.toLowerCase()) { + case "input": + $(this).data("original-text", this.value); this.value = text; break; - case 'a': - $( this ) - .data( 'original-text', $( this ).text ) - .text( text ) - .before( $spinner ) - .bind( 'click.disabled', function () { return false; } ); + case "a": + $(this) + .data("original-text", $(this).text) + .text(text) + .before($spinner) + .bind("click.disabled", function () { + return false; + }); break; - case 'button': - $( this ) - .data( 'original-text', $( this ).text() ) - .text( text ) - .prepend( $spinner ); + case "button": + $(this) + .data("original-text", $(this).text()) + .text(text) + .prepend($spinner); break; } - } ); + }); }, - MarkDone: function ( selector ) { - $( selector ) - .prop('disabled', false) - .each( function () { + MarkDone: function (selector) { + $(selector) + .prop("disabled", false) + .each(function () { var selector_type = this.localName; if (selector_type === undefined) selector_type = this.nodeName; // IE only - switch ( selector_type.toLowerCase() ) { - case 'input': - this.value = $( this ).data( 'original-text' ); + switch (selector_type.toLowerCase()) { + case "input": + this.value = $(this).data("original-text"); break; - case 'a': - $( this ) - .text( $( this ).data( 'original-text' ) ) - .unbind( 'click.disabled' ) - .prevAll( 'span.loading' ).remove(); + case "a": + $(this) + .text($(this).data("original-text")) + .unbind("click.disabled") + .prevAll("span.loading") + .remove(); break; - case 'button': - $( this ) - .text( $( this ).data( 'original-text' ) ) - .find( 'span.loading' ).remove(); + case "button": + $(this) + .text($(this).data("original-text")) + .find("span.loading") + .remove(); break; } - } ) - .removeData( 'original-text' ); - } + }) + .removeData("original-text"); + }, }; diff --git a/koha-tmpl/intranet-tmpl/prog/js/audio_alerts.js b/koha-tmpl/intranet-tmpl/prog/js/audio_alerts.js index 7ec084ee00..874309c1c3 100644 --- a/koha-tmpl/intranet-tmpl/prog/js/audio_alerts.js +++ b/koha-tmpl/intranet-tmpl/prog/js/audio_alerts.js @@ -1,9 +1,9 @@ /* global __ */ -$(document).ready(function() { +$(document).ready(function () { var checkboxes = $(".del-checkbox"); var checkedcheckboxes = 0; - checkboxes.on("change", function() { + checkboxes.on("change", function () { if ($(".del-checkbox:checked").length > 0) { checkedcheckboxes = 1; $("#delete-alerts").removeClass("disabled"); @@ -22,39 +22,39 @@ $(document).ready(function() { }); var soundfield = $("#sound"); - var playsound = $('#play-sound'); + var playsound = $("#play-sound"); - soundfield.on("change", function() { + soundfield.on("change", function () { enablePlayButton($(this).val(), playsound); }); $(".edit-alert").hide(); $("#new-alert-form").hide(); - $("#newalert").on("click", function(e) { + $("#newalert").on("click", function (e) { e.preventDefault(); - $("#new-alert-form").show(0, function() { + $("#new-alert-form").show(0, function () { $("#selector").focus(); }); $("#toolbar, #delete-alert-form").hide(); - $("#op-add-edit").val('cud-add'); + $("#op-add-edit").val("cud-add"); }); - $('#koha-sounds').on('change', function() { + $("#koha-sounds").on("change", function () { soundfield.val(this.value); enablePlayButton($(this).val(), playsound); }); - playsound.on('click', function(e) { + playsound.on("click", function (e) { e.preventDefault(); - if (soundfield.val() !== '') { + if (soundfield.val() !== "") { playSound(soundfield.val()); } else { alert(__("Please select or enter a sound.")); } }); - $('#cancel-edit').on('click', function(e) { + $("#cancel-edit").on("click", function (e) { e.preventDefault(); enablePlayButton("", playsound); @@ -68,19 +68,21 @@ $(document).ready(function() { $(".create-alert").show(); $("#new-alert-form").hide(); $("#delete-alert-form").show(); - $("#op-add-edit").val('cud-add'); + $("#op-add-edit").val("cud-add"); }); - $('#delete-alert-form').on('submit', function() { + $("#delete-alert-form").on("submit", function () { if (checkedcheckboxes == 1) { - return confirm(__("Are you sure you want to delete the selected audio alerts?")); + return confirm( + __("Are you sure you want to delete the selected audio alerts?") + ); } else { alert(__("Check the box next to the alert you want to delete.")); return false; } }); - $(".edit").on("click", function(e) { + $(".edit").on("click", function (e) { e.preventDefault(); var elt = this; var id = $(this).data("soundid"); @@ -92,7 +94,7 @@ $(document).ready(function() { }); function enablePlayButton(sound_field_value, playbutton) { - if (sound_field_value !== '') { + if (sound_field_value !== "") { playbutton.removeClass("disabled"); } else { playbutton.addClass("disabled"); @@ -100,7 +102,7 @@ function enablePlayButton(sound_field_value, playbutton) { } function EditAlert(elt, id, precedence, selector, sound) { - $("#op-add-edit").val('cud-edit'); + $("#op-add-edit").val("cud-edit"); $("#new-alert-form").show(); $("#delete-alert-form").hide(); $("#toolbar").hide(); @@ -110,5 +112,5 @@ function EditAlert(elt, id, precedence, selector, sound) { $("#selector").val(selector); $("#sound").val(sound); $("#koha-sounds").val(sound); - enablePlayButton(sound, $('#play-sound')); + enablePlayButton(sound, $("#play-sound")); } diff --git a/koha-tmpl/intranet-tmpl/prog/js/auth-finder-search.js b/koha-tmpl/intranet-tmpl/prog/js/auth-finder-search.js index 5bdf7db81a..bb84b525e6 100644 --- a/koha-tmpl/intranet-tmpl/prog/js/auth-finder-search.js +++ b/koha-tmpl/intranet-tmpl/prog/js/auth-finder-search.js @@ -1,141 +1,152 @@ /* global index authtypecode */ -$(document).ready(function(){ - $("#clear").on("click",function(e){ +$(document).ready(function () { + $("#clear").on("click", function (e) { e.preventDefault(); - finderjump('blinddetail-biblio-search.pl?authid=0&index=' + index ); + finderjump("blinddetail-biblio-search.pl?authid=0&index=" + index); }); - $("#createnew").on("click",function(e){ + $("#createnew").on("click", function (e) { e.preventDefault(); - finderjump('authorities.pl?index=' + index + '&authtypecode=' + authtypecode, 'full' ); + finderjump( + "authorities.pl?index=" + index + "&authtypecode=" + authtypecode, + "full" + ); }); // marclistanywhere - $( "#value_any" ).autocomplete({ - source: function(request, response) { + $("#value_any").autocomplete({ + source: function (request, response) { $.ajax({ url: "/cgi-bin/koha/authorities/ysearch.pl", dataType: "json", data: { - authtypecode : authtypecode, + authtypecode: authtypecode, term: request.term, op: "do_search", type: "intranet", and_or: "and", operator: "start", orderby: "HeadingAsc", - querytype: "all" + querytype: "all", + }, + success: function (data) { + response( + $.map(data, function (item) { + return { + label: item.summary, + value: item.summary, + }; + }) + ); }, - success: function(data) { - response( $.map( data, function( item ) { - return { - label: item.summary, - value: item.summary - }; - })); - } }); }, - select: function( event, ui ) { + select: function (event, ui) { $("#marclistanywhere").val("exact"); }, minLength: 3, }); // marclistheading - $( "#value_match" ).autocomplete({ - source: function(request, response) { + $("#value_match").autocomplete({ + source: function (request, response) { $.ajax({ url: "/cgi-bin/koha/authorities/ysearch.pl", dataType: "json", data: { - authtypecode : authtypecode, + authtypecode: authtypecode, term: request.term, op: "do_search", type: "intranet", and_or: "and", operator: "start", orderby: "HeadingAsc", - querytype: "match" + querytype: "match", + }, + success: function (data) { + response( + $.map(data, function (item) { + return { + label: item.summary, + value: item.summary, + }; + }) + ); }, - success: function(data) { - response( $.map( data, function( item ) { - return { - label: item.summary, - value: item.summary - }; - })); - } }); }, - select: function( event, ui ) { + select: function (event, ui) { $("#marclistheading").val("exact"); }, minLength: 3, }); // mainentry - $( "#value_main" ).autocomplete({ - source: function(request, response) { + $("#value_main").autocomplete({ + source: function (request, response) { $.ajax({ url: "/cgi-bin/koha/authorities/ysearch.pl", dataType: "json", data: { - authtypecode : authtypecode, + authtypecode: authtypecode, term: request.term, op: "do_search", type: "intranet", and_or: "and", operator: "start", orderby: "HeadingAsc", - querytype: "mainentry" + querytype: "mainentry", + }, + success: function (data) { + response( + $.map(data, function (item) { + return { + label: item.summary, + value: item.summary, + }; + }) + ); }, - success: function(data) { - response( $.map( data, function( item ) { - return { - label: item.summary, - value: item.summary - }; - })); - } }); }, - select: function( event, ui ) { + select: function (event, ui) { $("#mainentry").val("exact"); }, minLength: 3, }); // mainmainentry - $( "#value_mainstr" ).autocomplete({ - source: function(request, response) { + $("#value_mainstr").autocomplete({ + source: function (request, response) { $.ajax({ url: "/cgi-bin/koha/authorities/ysearch.pl", dataType: "json", data: { - authtypecode : authtypecode, + authtypecode: authtypecode, term: request.term, op: "do_search", type: "intranet", and_or: "and", operator: "start", orderby: "HeadingAsc", - querytype: "mainmainentry" + querytype: "mainmainentry", + }, + success: function (data) { + response( + $.map(data, function (item) { + return { + label: item.summary, + value: item.summary, + }; + }) + ); }, - success: function(data) { - response( $.map( data, function( item ) { - return { - label: item.summary, - value: item.summary - }; - })); - } }); }, - select: function( event, ui ) { + select: function (event, ui) { $("#mainmainentry").val("exact"); }, minLength: 3, }); - $("#clear-form").click(function(){ - setTimeout(function(){ - $(":input[type='text']").val(''); + $("#clear-form").click(function () { + setTimeout(function () { + $(":input[type='text']").val(""); $("#mainmainentry").val("contains"); $("#mainentry").val("contains"); $("#marclistheading").val("contains"); @@ -146,10 +157,14 @@ $(document).ready(function(){ }); }); -function finderjump(page, full){ - var window_size = ''; - if( full != "full"){ - window_size = 'width=100,height=100,'; +function finderjump(page, full) { + var window_size = ""; + if (full != "full") { + window_size = "width=100,height=100,"; } - window.open(page,'', window_size + 'resizable=yes,toolbar=false,scrollbars=yes,top'); + window.open( + page, + "", + window_size + "resizable=yes,toolbar=false,scrollbars=yes,top" + ); } diff --git a/koha-tmpl/intranet-tmpl/prog/js/authorities-detail-modal.js b/koha-tmpl/intranet-tmpl/prog/js/authorities-detail-modal.js index d91b047258..b546ae66dd 100644 --- a/koha-tmpl/intranet-tmpl/prog/js/authorities-detail-modal.js +++ b/koha-tmpl/intranet-tmpl/prog/js/authorities-detail-modal.js @@ -1,23 +1,36 @@ /* global template_path */ -$(document).ready(function(){ - $(".authority_preview a").on("click", function(e){ +$(document).ready(function () { + $(".authority_preview a").on("click", function (e) { e.preventDefault(); var authid = $(this).data("authid"); - $.get("/cgi-bin/koha/authorities/detail.pl", { authid : authid }, function( data ){ - var auth_detail = $(data).find("#authoritiestabs"); - auth_detail.find("ul").remove(); - auth_detail.removeClass("toptabs"); - auth_detail.find("> div").removeClass("tab-content"); - auth_detail.find("> div > div").removeClass("tab-pane").removeAttr("role"); - $("#authorityDetail .modal-title").html(__("Authority") + " " + authid ); - $("#authorityDetail .modal-body").html( auth_detail ); - }); + $.get( + "/cgi-bin/koha/authorities/detail.pl", + { authid: authid }, + function (data) { + var auth_detail = $(data).find("#authoritiestabs"); + auth_detail.find("ul").remove(); + auth_detail.removeClass("toptabs"); + auth_detail.find("> div").removeClass("tab-content"); + auth_detail + .find("> div > div") + .removeClass("tab-pane") + .removeAttr("role"); + $("#authorityDetail .modal-title").html( + __("Authority") + " " + authid + ); + $("#authorityDetail .modal-body").html(auth_detail); + } + ); $("#authorityDetail").modal("show"); }); - $("#authorityDetail").on("hidden.bs.modal", function(){ - $("#authorityDetail .modal-body, #authorityDetail .modal-title").html(""); - $("#authorityDetail .modal-body").html("\"\""); + $("#authorityDetail").on("hidden.bs.modal", function () { + $("#authorityDetail .modal-body, #authorityDetail .modal-title").html( + "" + ); + $("#authorityDetail .modal-body").html( + '' + ); }); }); diff --git a/koha-tmpl/intranet-tmpl/prog/js/authtype.js b/koha-tmpl/intranet-tmpl/prog/js/authtype.js index 229cf187bd..9b2c22c00a 100644 --- a/koha-tmpl/intranet-tmpl/prog/js/authtype.js +++ b/koha-tmpl/intranet-tmpl/prog/js/authtype.js @@ -2,69 +2,108 @@ var importing = false; -$(document).ready(function() { - $("#authtypes").dataTable($.extend(true, {}, dataTablesDefaults, { - "columnDefs": [ - { "targets": [ -1 ], "orderable": false, "searchable": false }, - { "targets": [ 0, 1 ], "type": "natural" }, - ], - "ordering": true, - "pagingType": "full" - })); +$(document).ready(function () { + $("#authtypes").dataTable( + $.extend(true, {}, dataTablesDefaults, { + columnDefs: [ + { targets: [-1], orderable: false, searchable: false }, + { targets: [0, 1], type: "natural" }, + ], + ordering: true, + pagingType: "full", + }) + ); $("body").css("cursor", "auto"); - $('.import_export_options').hide(); - $('a.import_export_fw').click(function() { + $(".import_export_options").hide(); + $("a.import_export_fw").click(function () { if (!importing) { - $('.import_export_options').hide(); - $(this).next().show('slide'); + $(".import_export_options").hide(); + $(this).next().show("slide"); } return false; }); - $('.import_export_close').click(function() { + $(".import_export_close").click(function () { if (!importing) { - $('.import_export_options').fadeOut('fast'); + $(".import_export_options").fadeOut("fast"); $("body").css("cursor", "auto"); return false; } }); - $('.input_import').val(""); + $(".input_import").val(""); - var matches = new RegExp("\\?error_import_export=(.+)$").exec(window.location.search); + var matches = new RegExp("\\?error_import_export=(.+)$").exec( + window.location.search + ); if (matches && matches.length > 1) { - alert(__("Error importing the authority type %s").format(decodeURIComponent(matches[1]))); + alert( + __("Error importing the authority type %s").format( + decodeURIComponent(matches[1]) + ) + ); } - $('input.input_import').change( function() { + $("input.input_import").change(function () { var filename = $(this).val(); - if ( ! /(?:\.csv|\.ods)$/.test(filename)) { - $(this).css("background-color","yellow"); - alert(__("Please select a CSV (.csv) or ODS (.ods) spreadsheet file.")); + if (!/(?:\.csv|\.ods)$/.test(filename)) { + $(this).css("background-color", "yellow"); + alert( + __("Please select a CSV (.csv) or ODS (.ods) spreadsheet file.") + ); $(this).val(""); - $(this).css("background-color","white"); + $(this).css("background-color", "white"); } }); - $('form.form_export').submit(function() { - $('.modal').modal("hide"); + $("form.form_export").submit(function () { + $(".modal").modal("hide"); return true; }); - $('form.form_import').submit(function() { - var id = $(this).attr('id'); - var obj = $('#' + id + ' input:file'); + $("form.form_import").submit(function () { + var id = $(this).attr("id"); + var obj = $("#" + id + " input:file"); if (/(?:\.csv|\.ods)$/.test(obj.val())) { - if (confirm(__("Do you really want to import the authority type fields and subfields? This will overwrite the current configuration. For safety reasons please use the export option to make a backup"))) { - var authtypecode = $('#' + id + ' input:hidden[name=authtypecode]').val(); - $('#importing_' + authtypecode).find("span").html(__("Importing to authority type: %s. Importing from file: %s").format("" + authtypecode + "", "" + obj.val().replace(new RegExp("^.+[/\\\\]"),"") + "")); - if (navigator.userAgent.toLowerCase().indexOf('msie') != -1) { + if ( + confirm( + __( + "Do you really want to import the authority type fields and subfields? This will overwrite the current configuration. For safety reasons please use the export option to make a backup" + ) + ) + ) { + var authtypecode = $( + "#" + id + " input:hidden[name=authtypecode]" + ).val(); + $("#importing_" + authtypecode) + .find("span") + .html( + __( + "Importing to authority type: %s. Importing from file: %s" + ).format( + "" + authtypecode + "", + "" + + obj + .val() + .replace(new RegExp("^.+[/\\\\]"), "") + + "" + ) + ); + if (navigator.userAgent.toLowerCase().indexOf("msie") != -1) { var timestamp = new Date().getTime(); - $('#importing_' + authtypecode).find("img").attr('src', '[% interface | html %]/[% theme | html %]/img/loading-small.gif' + '?' +timestamp); + $("#importing_" + authtypecode) + .find("img") + .attr( + "src", + "[% interface | html %]/[% theme | html %]/img/loading-small.gif" + + "?" + + timestamp + ); } - $('#importing_' + authtypecode).css('display', 'block'); - if (navigator.userAgent.toLowerCase().indexOf('firefox') == -1) $("body").css("cursor", "progress"); + $("#importing_" + authtypecode).css("display", "block"); + if (navigator.userAgent.toLowerCase().indexOf("firefox") == -1) + $("body").css("cursor", "progress"); importing = true; $(".modal-footer,.btn-close").hide(); return true; @@ -72,14 +111,13 @@ $(document).ready(function() { return false; } } - obj.css("background-color","yellow"); + obj.css("background-color", "yellow"); alert(__("Please select a CSV (.csv) or ODS (.ods) spreadsheet file.")); obj.val(""); - bj.css("background-color","white"); + bj.css("background-color", "white"); return false; }); - $("#authtypecode").on("blur",function(){ + $("#authtypecode").on("blur", function () { toUC(this); }); - }); diff --git a/koha-tmpl/intranet-tmpl/prog/js/automatic_item_modification_by_age.js b/koha-tmpl/intranet-tmpl/prog/js/automatic_item_modification_by_age.js index 09c4da1fc8..4ff5dc46c1 100644 --- a/koha-tmpl/intranet-tmpl/prog/js/automatic_item_modification_by_age.js +++ b/koha-tmpl/intranet-tmpl/prog/js/automatic_item_modification_by_age.js @@ -1,19 +1,19 @@ function clear_inputs(node, new_node) { var selects = $(node).find("select"); - $(selects).each(function(i) { + $(selects).each(function (i) { var select = this; $(new_node).find("select").eq(i).val($(select).val()); }); var inputs = $(node).find("input"); - $(inputs).each(function(i) { + $(inputs).each(function (i) { var input = this; $(new_node).find("input").eq(i).val($(input).val()); }); } -function remove_block_action( link ) { +function remove_block_action(link) { var blocks = $(link).parent().parent(); - if( $(blocks).find(".block").length > 2 ) { + if ($(blocks).find(".block").length > 2) { $(blocks).find("a.remove_block").show(); } else { $(blocks).find("a.remove_block").hide(); @@ -21,10 +21,10 @@ function remove_block_action( link ) { $(link).parent().remove(); } -function remove_rule_action( link ) { - if( $("#rules").find(".rule").length < 2 ) { - $("#rules").hide(); - $("#norules").show(); +function remove_rule_action(link) { + if ($("#rules").find(".rule").length < 2) { + $("#rules").hide(); + $("#norules").show(); } $(link).parent().parent().remove(); update_rule_count(); @@ -33,92 +33,106 @@ function remove_rule_action( link ) { function clone_block(block) { var new_block = $(block).clone(1); clear_inputs(block, new_block); - $(new_block).find('a.remove_block').show(); + $(new_block).find("a.remove_block").show(); var blocks = $(block).parent(); $(blocks).append(new_block); - $(blocks).find('a.remove_block').click(function(e){ - e.preventDefault(); - remove_block_action($(this)); - }).show(); + $(blocks) + .find("a.remove_block") + .click(function (e) { + e.preventDefault(); + remove_block_action($(this)); + }) + .show(); } -function update_rule_count(){ +function update_rule_count() { rules = $(".rulecount"); - rules.each( function( i ){ - $(this).text( i + 1 ); + rules.each(function (i) { + $(this).text(i + 1); }); } -$(document).ready(function() { +$(document).ready(function () { $("#new_rule .remove_rule").hide(); $("#new_rule a.remove_block").hide(); - $("#rules a.remove_block").click(function(e){ + $("#rules a.remove_block").click(function (e) { e.preventDefault(); remove_block_action($(this)); }); - $("#rules .remove_rule").click(function(e){ + $("#rules .remove_rule").click(function (e) { e.preventDefault(); remove_rule_action($(this)); }); var unique_id = $(".rule").length + 1; - $(".add_rule").click(function(e){ + $(".add_rule").click(function (e) { e.preventDefault(); var rule = $("#new_rule"); var rules = $("#rules"); var new_rule = rule.clone(1); - new_rule.removeAttr('id'); - new_rule.attr('class', 'rule'); + new_rule.removeAttr("id"); + new_rule.attr("class", "rule"); clear_inputs(rule, new_rule); - new_rule.find("select[name='condition_field']").attr('name', 'condition_field_' + unique_id); - new_rule.find("select[name='substitution_field']").attr('name', 'substitution_field_' + unique_id); - new_rule.find("input[name='condition_value']").attr('name', 'condition_value_' + unique_id); - new_rule.find("input[name='substitution_value']").attr('name', 'substitution_value_' + unique_id); - new_rule.find("input[name='age']").attr('name', 'age_' + unique_id); - new_rule.find("select[name='agefield']").attr('name', 'agefield_' + unique_id); + new_rule + .find("select[name='condition_field']") + .attr("name", "condition_field_" + unique_id); + new_rule + .find("select[name='substitution_field']") + .attr("name", "substitution_field_" + unique_id); + new_rule + .find("input[name='condition_value']") + .attr("name", "condition_value_" + unique_id); + new_rule + .find("input[name='substitution_value']") + .attr("name", "substitution_value_" + unique_id); + new_rule.find("input[name='age']").attr("name", "age_" + unique_id); + new_rule + .find("select[name='agefield']") + .attr("name", "agefield_" + unique_id); new_rule.find("input[name='unique_id']").val(unique_id); $("#rules").append(new_rule); update_rule_count(); var scrollToPoint = new_rule.position(); - window.scroll(0, scrollToPoint.top - $("#toolbar").height() ); + window.scroll(0, scrollToPoint.top - $("#toolbar").height()); - if( $("#rules").find(".rule").length > 0 ) { - $("#rules").show(); - $("#norules").hide(); + if ($("#rules").find(".rule").length > 0) { + $("#rules").show(); + $("#norules").hide(); } - if( $("#rules").find(".conditions > .condition").length > 1 ) { - + if ($("#rules").find(".conditions > .condition").length > 1) { } - if( $("#rules").find(".conditions > .condition").length > 1 ) { - + if ($("#rules").find(".conditions > .condition").length > 1) { } - new_rule.find('.remove_rule').click(function(e){ - e.preventDefault(); - remove_rule_action( $(this) ); - }).show(); - new_rule.find('.add_rule').remove(); + new_rule + .find(".remove_rule") + .click(function (e) { + e.preventDefault(); + remove_rule_action($(this)); + }) + .show(); + new_rule.find(".add_rule").remove(); unique_id++; }); - $("a.add_block").click(function(e){ + $("a.add_block").click(function (e) { e.preventDefault(); - clone_block( $(this).parent() ); + clone_block($(this).parent()); }); - if( $("#rules").find(".rule").length < 1 ) { - $("#rules").hide(); - $("#norules").show(); + if ($("#rules").find(".rule").length < 1) { + $("#rules").hide(); + $("#norules").show(); } - $("#rules .rule .blocks").each(function(){ - if ( $(this).find(".block").length == 1 ) { + $("#rules .rule .blocks").each(function () { + if ($(this).find(".block").length == 1) { $(this).find("a.remove_block").hide(); } }); jQuery.validator.addClassRules("age", { - digits: true + digits: true, }); $("#rules_form").validate(); diff --git a/koha-tmpl/intranet-tmpl/prog/js/basket.js b/koha-tmpl/intranet-tmpl/prog/js/basket.js index 4de6731936..2c34006ec9 100644 --- a/koha-tmpl/intranet-tmpl/prog/js/basket.js +++ b/koha-tmpl/intranet-tmpl/prog/js/basket.js @@ -12,10 +12,10 @@ var nameParam = "bib_list"; var valCookie = readCookie(nameCookie); var basketcount; -if(valCookie){ +if (valCookie) { var arrayRecords = valCookie.split("/"); - if(arrayRecords.length > 0){ - basketcount = arrayRecords.length-1; + if (arrayRecords.length > 0) { + basketcount = arrayRecords.length - 1; } else { basketcount = ""; } @@ -25,17 +25,16 @@ if(valCookie){ function writeCookie(name, val, wd) { if (wd) { - parent.opener.document.cookie = name + "=" + val + "; SameSite=Lax; path=/"; - } - else { + parent.opener.document.cookie = + name + "=" + val + "; SameSite=Lax; path=/"; + } else { parent.document.cookie = name + "=" + val + "; SameSite=Lax; path=/"; } } -function readCookieValue (str, val_beg) { +function readCookieValue(str, val_beg) { var val_end = str.indexOf(";", val_end); - if (val_end == -1) - val_end = str.length; + if (val_end == -1) val_end = str.length; return str.substring(val_beg, val_end); } @@ -44,27 +43,29 @@ function readCookie(name, wd) { var str_cookie = ""; if (wd) { str_cookie = parent.opener.document.cookie; - } - else { + } else { str_cookie = parent.document.cookie; } // fixed - getting the part of the basket that is bib_list var cookie_parts = str_cookie.split(";"); - for(var i=0;i < cookie_parts.length;i++) { + for (var i = 0; i < cookie_parts.length; i++) { var c = cookie_parts[i]; - while (c.charAt(0)==' ') c = c.substring(1,c.length); - if(c.indexOf(str_name) === 0) return c.substring(str_name.length,c.length); + while (c.charAt(0) == " ") c = c.substring(1, c.length); + if (c.indexOf(str_name) === 0) + return c.substring(str_name.length, c.length); } return null; } function delCookie(name) { var exp = new Date(); - exp.setTime(exp.getTime()-1); - if(parent.opener){ - parent.opener.document.cookie = name + "=null; SameSite=Lax; path=/; expires=" + exp.toGMTString(); + exp.setTime(exp.getTime() - 1); + if (parent.opener) { + parent.opener.document.cookie = + name + "=null; SameSite=Lax; path=/; expires=" + exp.toGMTString(); } else { - document.cookie = name + "=null; SameSite=Lax; path=/; expires=" + exp.toGMTString(); + document.cookie = + name + "=null; SameSite=Lax; path=/; expires=" + exp.toGMTString(); } } @@ -75,33 +76,38 @@ function delCookie(name) { function openBasket() { var strCookie = ""; var valCookie = readCookie(nameCookie); - if ( valCookie ) { + if (valCookie) { strCookie = nameParam + "=" + valCookie; } - if ( strCookie ) { + if (strCookie) { var iW = 820; var iH = 450; - var optWin = "status=yes,scrollbars=yes,resizable=yes,toolbar=no,location=yes,height="+iH+",width="+iW; + var optWin = + "status=yes,scrollbars=yes,resizable=yes,toolbar=no,location=yes,height=" + + iH + + ",width=" + + iW; var loc = CGIBIN + "basket/basket.pl?" + strCookie; var basket = open(loc, "basket", optWin); - if (window.focus) { basket.focus(); } - } - else { - showCartUpdate( __("Your cart is currently empty") ); + if (window.focus) { + basket.focus(); + } + } else { + showCartUpdate(__("Your cart is currently empty")); } } -function addRecord(val, selection,NoMsgAlert) { +function addRecord(val, selection, NoMsgAlert) { var valCookie = readCookie(nameCookie); var write = 0; - if ( ! valCookie ) { // empty basket - valCookie = val + '/'; + if (!valCookie) { + // empty basket + valCookie = val + "/"; write = 1; updateBasket(1); - } - else { + } else { // is this record already in the basket ? var found = false; var arrayRecords = valCookie.split("/"); @@ -111,16 +117,15 @@ function addRecord(val, selection,NoMsgAlert) { break; } } - if ( found ) { + if (found) { if (selection) { return 0; } - if (! NoMsgAlert ) { - showCartUpdate( __("This record is already in your cart") ); + if (!NoMsgAlert) { + showCartUpdate(__("This record is already in your cart")); } - } - else { - valCookie += val + '/'; + } else { + valCookie += val + "/"; write = 1; updateBasket(arrayRecords.length); } @@ -128,60 +133,75 @@ function addRecord(val, selection,NoMsgAlert) { if (write) { writeCookie(nameCookie, valCookie); - if (selection) { // when adding a selection of records - updateLink(val,"add"); + if (selection) { + // when adding a selection of records + updateLink(val, "add"); return 1; } - if (! NoMsgAlert ) { - showCartUpdate( __("This record has been added to your cart") ); - updateLink(val,"add"); + if (!NoMsgAlert) { + showCartUpdate(__("This record has been added to your cart")); + updateLink(val, "add"); } } } -function AllAreChecked(s){ - if (! s.length){ return false;} +function AllAreChecked(s) { + if (!s.length) { + return false; + } var l = s.length; - for (var i=0; i < l; i++) { - if(! s[i].checked) { return false; } + for (var i = 0; i < l; i++) { + if (!s[i].checked) { + return false; + } } return true; } -function SelectAll(){ - if(document.bookbag_form.biblionumber.length > 0) { +function SelectAll() { + if (document.bookbag_form.biblionumber.length > 0) { var checky = AllAreChecked(document.bookbag_form.biblionumber); var l = document.bookbag_form.biblionumber.length; - for (var i=0; i < l; i++) { - document.bookbag_form.biblionumber[i].checked = (checky) ? false : true; + for (var i = 0; i < l; i++) { + document.bookbag_form.biblionumber[i].checked = checky + ? false + : true; } } } -function addMultiple(biblist){ +function addMultiple(biblist) { var c_value = ""; var i = 0; - if( biblist && biblist.length > 0 ) { - for ( i=0; i < biblist.length; i++ ) { + if (biblist && biblist.length > 0) { + for (i = 0; i < biblist.length; i++) { if (biblist[i].checked) { c_value = c_value + biblist[i].value + "/"; } } } else { var bibnums = getContextBiblioNumbers(); - if ( bibnums.length > 0 ) { - for ( i = 0 ; i < bibnums.length ; i++ ) { + if (bibnums.length > 0) { + for (i = 0; i < bibnums.length; i++) { c_value = c_value + bibnums[i] + "/"; } } else { - if(document.bookbag_form.biblionumber.length > 0) { - for ( i=0; i < document.bookbag_form.biblionumber.length; i++ ) { + if (document.bookbag_form.biblionumber.length > 0) { + for ( + i = 0; + i < document.bookbag_form.biblionumber.length; + i++ + ) { if (document.bookbag_form.biblionumber[i].checked) { - c_value = c_value + document.bookbag_form.biblionumber[i].value + "/"; + c_value = + c_value + + document.bookbag_form.biblionumber[i].value + + "/"; } } } else { - c_value = c_value + document.bookbag_form.biblionumber.value + "/"; + c_value = + c_value + document.bookbag_form.biblionumber.value + "/"; } } } @@ -194,11 +214,10 @@ function addSelRecords(valSel) { var arrayRecords = valSel.split("/"); var i = 0; var nbAdd = 0; - for (i=0;i nbAdd) { msg = __("%s record(s) added to your cart").format(nbAdd); msg += "
          "; - msg += __("%s already in your cart").format((i-nbAdd)); - } - else { + msg += __("%s already in your cart").format(i - nbAdd); + } else { msg = __("%s record(s) added to your cart").format(nbAdd); } - } - else { + } else { if (i < 1) { msg = __("No record was selected"); - } - else { - msg = __("No record was added to your cart (already in your cart)!"); + } else { + msg = __( + "No record was added to your cart (already in your cart)!" + ); } } showCartUpdate(msg); } -function showCartUpdate(msg){ +function showCartUpdate(msg) { // set body of popup window $("#cartDetails").html(msg); showCart(); - setTimeout(hideCart,2000); + setTimeout(hideCart, 2000); } -function showListsUpdate(msg){ +function showListsUpdate(msg) { // set body of popup window alert(msg); } function selRecord(num, status) { var str = document.myform.records.value; - if (status){ - str += num+"/"; - } - else { + if (status) { + str += num + "/"; + } else { str = delRecord(num, str); } document.myform.records.value = str; } -function delSingleRecord(biblionumber){ +function delSingleRecord(biblionumber) { var valCookie = readCookie(nameCookie); var arrayRecords = valCookie.split("/"); - var pos = jQuery.inArray(biblionumber,arrayRecords); - arrayRecords.splice(pos,1); + var pos = jQuery.inArray(biblionumber, arrayRecords); + arrayRecords.splice(pos, 1); valCookie = arrayRecords.join("/"); - writeCookie( nameCookie, valCookie ); - updateBasket( arrayRecords.length-1 ); - updateLink(biblionumber,"del"); + writeCookie(nameCookie, valCookie); + updateBasket(arrayRecords.length - 1); + updateLink(biblionumber, "del"); showCartUpdate(__("The record has been removed from your cart")); } @@ -267,28 +284,29 @@ function delSelRecords() { var s; if (valCookie) { var str = document.myform.records.value; - if (str.length > 0){ + if (str.length > 0) { recordsSel = 1; var str2 = valCookie; - while (!end){ + while (!end) { s = str.indexOf("/"); - if (s>0){ + if (s > 0) { var num = str.substring(0, s); - str = delRecord(num,str); - str2 = delRecord(num,str2); - updateLink(num,"del",top.opener); + str = delRecord(num, str); + str2 = delRecord(num, str2); + updateLink(num, "del", top.opener); } else { end = 1; } } - if (str2.length === 0) { // equivalent to emptying the basket + if (str2.length === 0) { + // equivalent to emptying the basket var rep = false; rep = confirm(__("Are you sure you want to empty your cart?")); if (rep) { delCookie(nameCookie); document.location = "about:blank"; - updateBasket(0,top.opener); + updateBasket(0, top.opener); window.close(); } else { return; @@ -304,28 +322,29 @@ function delSelRecords() { valCookie = readCookie(nameCookie, 1); strCookie = nameParam + "=" + valCookie; var arrayRecords = valCookie.split("/"); - updateBasket(arrayRecords.length-1,top.opener); + updateBasket(arrayRecords.length - 1, top.opener); document.location = CGIBIN + "basket/basket.pl?" + strCookie; - } - else { + } else { alert(__("No record was selected")); } } -function delRecord (n, s) { +function delRecord(n, s) { var re = /\d/; var aux = s; var found = 0; var pos = -1; while (!found) { - pos = aux.indexOf(n, pos+1); - var charAfter = aux.charAt(pos+n.length); // character right after the researched string - if (charAfter.match(re)) { // record number inside another one + pos = aux.indexOf(n, pos + 1); + var charAfter = aux.charAt(pos + n.length); // character right after the researched string + if (charAfter.match(re)) { + // record number inside another one continue; - } - else { // good record number - aux = s.substring(0, pos)+ s.substring(pos+n.length+1, s.length); + } else { + // good record number + aux = + s.substring(0, pos) + s.substring(pos + n.length + 1, s.length); s = aux; found = 1; } @@ -334,20 +353,20 @@ function delRecord (n, s) { return s; } -function delBasket(context,rep) { - if (rep === undefined){ +function delBasket(context, rep) { + if (rep === undefined) { rep = confirm(__("Are you sure you want to empty your cart?")); } if (rep) { - if(context == "popup"){ + if (context == "popup") { delCookie(nameCookie); updateAllLinks(top.opener); document.location = "about:blank"; - updateBasket(0,top.opener); + updateBasket(0, top.opener); window.close(); } else { delCookie(nameCookie); - updateBasket(0,top.opener); + updateBasket(0, top.opener); } } } @@ -355,12 +374,14 @@ function delBasket(context,rep) { function quit() { if (document.myform.records.value) { var rep = false; - rep = confirm(__("Are you sure you want to remove the selected records?")); + rep = confirm( + __("Are you sure you want to remove the selected records?") + ); if (rep) { delSelRecords(); } } - updateBasket(arrayRecords.length-1,top.opener); + updateBasket(arrayRecords.length - 1, top.opener); window.close(); } @@ -368,7 +389,7 @@ function sendBasket() { var valCookie = readCookie(nameCookie); var strCookie = nameParam + "=" + valCookie; var loc = CGIBIN + "basket/sendbasket.pl?" + strCookie; - openWindow( loc, "win_form" ); + openWindow(loc, "win_form"); } function downloadBasket() { @@ -377,7 +398,11 @@ function downloadBasket() { var loc = CGIBIN + "basket/downloadcart.pl?" + strCookie; - open(loc,"win_form",'scrollbars=no,resizable=no,height=300,width=450,top=50,left=100'); + open( + loc, + "win_form", + "scrollbars=no,resizable=no,height=300,width=450,top=50,left=100" + ); } function printBasket() { @@ -406,13 +431,17 @@ function showLess() { document.location = loc; } -function updateBasket(updated_value,target) { - if(target){ - target.$('#basketcount').html(" ("+updated_value+")"); - target.$('#cartDetails').html(__("Records in your cart: %s").format(updated_value)); +function updateBasket(updated_value, target) { + if (target) { + target.$("#basketcount").html(" (" + updated_value + ")"); + target + .$("#cartDetails") + .html(__("Records in your cart: %s").format(updated_value)); } else { - $('#basketcount').html(" ("+updated_value+")"); - $('#cartDetails').html(__("Records in your cart: %s").format(updated_value)); + $("#basketcount").html(" (" + updated_value + ")"); + $("#cartDetails").html( + __("Records in your cart: %s").format(updated_value) + ); } } @@ -422,9 +451,11 @@ function openBiblio(openerURL) { } function addSelToShelf() { - var items = document.getElementById('records').value; - if(items){ - document.location = "/cgi-bin/koha/virtualshelves/addbybiblionumber.pl?biblionumber="+items; + var items = document.getElementById("records").value; + if (items) { + document.location = + "/cgi-bin/koha/virtualshelves/addbybiblionumber.pl?biblionumber=" + + items; } else { alert(__("No record was selected")); } @@ -433,20 +464,22 @@ function addSelToShelf() { /// vShelfAdd() builds url string for multiple-biblio adds. function vShelfAdd(biblist) { - var bibs = new Array; + var bibs = new Array(); var i; - if( biblist && biblist.length > 0 ) { - for ( i=0; i < biblist.length; i++ ) { + if (biblist && biblist.length > 0) { + for (i = 0; i < biblist.length; i++) { if (biblist[i].checked) { - bibs.push("biblionumber=" + biblist[i].value); + bibs.push("biblionumber=" + biblist[i].value); } } - if (bibs.length === 0) { showListsUpdate(__("No record was selected")); } + if (bibs.length === 0) { + showListsUpdate(__("No record was selected")); + } return bibs.join("&"); } else { var bibnums = getContextBiblioNumbers(); - if ( bibnums.length > 0 ) { - for ( i = 0 ; i < bibnums.length ; i++ ) { + if (bibnums.length > 0) { + for (i = 0; i < bibnums.length; i++) { bibs.push("biblionumber=" + bibnums[i]); } return bibs.join("&"); @@ -456,43 +489,47 @@ function vShelfAdd(biblist) { } } -function showCart(){ +function showCart() { var position = $("#cartmenulink").offset(); var toolbarh = $(".floating").outerHeight(); var scrolld = $(window).scrollTop(); var top = position.top + $("#cartmenulink").outerHeight(); - if( scrolld > top ){ + if (scrolld > top) { top = scrolld + toolbarh + 15; } var left = position.left; $("#cartDetails") - .css("position","absolute") - .css("top",top) - .css("left",left) - .css("z-index",1000); + .css("position", "absolute") + .css("top", top) + .css("left", left) + .css("z-index", 1000); $("#cartDetails").fadeIn("fast"); } -function hideCart(){ +function hideCart() { $("#cartDetails").fadeOut("fast"); } -function updateLink(val, op, target){ +function updateLink(val, op, target) { var cart = target ? target.$("#cart" + val) : $("#cart" + val); var cartR = target ? target.$("#cartR" + val) : $("#cartR" + val); - if(op == "add"){ - if( cart.hasClass("btn") ){ + if (op == "add") { + if (cart.hasClass("btn")) { /* Cart link is a button with an icon */ - cart.html(" " + __("Add to cart")).addClass("incart"); + cart.html( + ' ' + __("Add to cart") + ).addClass("incart"); cart.hide(); } else { - cart.html( __("In your cart") ).addClass("incart"); + cart.html(__("In your cart")).addClass("incart"); } cartR.show(); } else { if (cart.hasClass("btn")) { - cart.html(" " + __("Add to cart")).addClass("addtocart"); + cart.html( + ' ' + __("Add to cart") + ).addClass("addtocart"); cart.show(); } else { cart.html(__("Add to cart")).addClass("addtocart"); @@ -501,23 +538,27 @@ function updateLink(val, op, target){ } } -function updateAllLinks(target){ +function updateAllLinks(target) { var cart = target ? target.$("a.incart") : $("a.incart"); var cartR = target ? target.$(".cartRemove") : $(".cartRemove"); - if( cart.hasClass("btn") ){ + if (cart.hasClass("btn")) { /* Cart link is a button with an icon */ - cart.html(" " + __("Add to cart")).addClass("incart"); + cart.html( + ' ' + __("Add to cart") + ).addClass("incart"); cartR.hide(); } else { - cart.html( __("In your cart") ).addClass("incart"); + cart.html(__("In your cart")).addClass("incart"); } cart.show(); } -$(document).ready(function(){ - $("#cartmenulink").click(function( e ){ +$(document).ready(function () { + $("#cartmenulink").click(function (e) { e.preventDefault(); openBasket(); }); - if(basketcount){ updateBasket(basketcount); } + if (basketcount) { + updateBasket(basketcount); + } }); diff --git a/koha-tmpl/intranet-tmpl/prog/js/biblio_framework.js b/koha-tmpl/intranet-tmpl/prog/js/biblio_framework.js index 39e9678846..a030485278 100644 --- a/koha-tmpl/intranet-tmpl/prog/js/biblio_framework.js +++ b/koha-tmpl/intranet-tmpl/prog/js/biblio_framework.js @@ -1,81 +1,115 @@ /* global __ */ /* Import/Export from/to spreadsheet */ - var importing = false; +var importing = false; - $(document).ready(function() { - $("#table_biblio_frameworks").dataTable($.extend(true, {}, dataTablesDefaults, { - "columnDefs": [ - { "targets": [ -1 ], "orderable": false, "searchable": false }, - { "targets": [ 0, 1 ], "type": "natural" }, +$(document).ready(function () { + $("#table_biblio_frameworks").dataTable( + $.extend(true, {}, dataTablesDefaults, { + columnDefs: [ + { targets: [-1], orderable: false, searchable: false }, + { targets: [0, 1], type: "natural" }, ], - "ordering": true, - "pagingType": "full" - })); + ordering: true, + pagingType: "full", + }) + ); - $("body").css("cursor", "auto"); - $('.import_export_options').hide(); - $('a.import_export_fw').click(function() { - if (!importing) { - $('.import_export_options').hide(); - $(this).next().show('slide'); - } - return false; - }); - $('.import_export_close').click(function() { - if (!importing) { - $('.import_export_options').fadeOut('fast'); - $("body").css("cursor", "auto"); - return false; - } - }); - $('.input_import').val(""); - - var matches = new RegExp("\\?error_import_export=(.+)$").exec(window.location.search); - if (matches && matches.length > 1) { - alert( __("Error importing the framework") + " %s".format(decodeURIComponent(matches[1]))); + $("body").css("cursor", "auto"); + $(".import_export_options").hide(); + $("a.import_export_fw").click(function () { + if (!importing) { + $(".import_export_options").hide(); + $(this).next().show("slide"); } - - $('input.input_import').change( function() { - var filename = $(this).val(); - if ( ! /(?:\.csv|\.ods|\.xml)$/.test(filename)) { - $(this).css("background-color","yellow"); - alert( __("Please select a CSV (.csv) or ODS (.ods) spreadsheet file.") ); - $(this).val(""); - $(this).css("background-color","white"); - } - }); - $('form.form_export').submit(function() { - $('.modal').modal("hide"); - return true; - }); - $('form.form_import').submit(function() { - var id = $(this).attr('id'); - var obj = $('#' + id + ' input:file'); - if (/(?:\.csv|\.ods|\.xml)$/.test(obj.val())) { - var frameworkcode = $('#' + id + ' input:hidden[name=frameworkcode]').val(); - var MSG_OVERWRITE_WARNING = __("Are you sure you want to replace the fields and subfields for the %s framework structure? The existing structure will be overwritten! For safety reasons, it is recommended to use the export option to make a backup first.").format( frameworkcode ); - if (confirm( MSG_OVERWRITE_WARNING )) { - $('#importing_' + frameworkcode).find("span").html( __("Importing to framework: %s. Importing from file: %s.").format("" + frameworkcode + "", "" + obj.val().replace(new RegExp("^.+[/\\\\]"), "") + "")); - if (navigator.userAgent.toLowerCase().indexOf('msie') != -1) { - var timestamp = new Date().getTime(); - $('#importing_' + frameworkcode).find("img").attr('src', template_path + '/img/spinner-small.gif' + '?' +timestamp); - } - $('#importing_' + frameworkcode).css('display', 'block'); - if (navigator.userAgent.toLowerCase().indexOf('firefox') == -1) $("body").css("cursor", "progress"); - importing = true; - $(".modal-footer,.btn-close").hide(); - return true; - } else - return false; - } - obj.css("background-color","yellow"); - alert( __("Please select a CSV (.csv) or ODS (.ods) spreadsheet file.") ); - obj.val(""); - obj.css("background-color","white"); - return false; - }); - $("#frameworkcode").on("blur",function(){ - toUC(this); - }); + return false; }); + $(".import_export_close").click(function () { + if (!importing) { + $(".import_export_options").fadeOut("fast"); + $("body").css("cursor", "auto"); + return false; + } + }); + $(".input_import").val(""); + + var matches = new RegExp("\\?error_import_export=(.+)$").exec( + window.location.search + ); + if (matches && matches.length > 1) { + alert( + __("Error importing the framework") + + " %s".format(decodeURIComponent(matches[1])) + ); + } + + $("input.input_import").change(function () { + var filename = $(this).val(); + if (!/(?:\.csv|\.ods|\.xml)$/.test(filename)) { + $(this).css("background-color", "yellow"); + alert( + __("Please select a CSV (.csv) or ODS (.ods) spreadsheet file.") + ); + $(this).val(""); + $(this).css("background-color", "white"); + } + }); + $("form.form_export").submit(function () { + $(".modal").modal("hide"); + return true; + }); + $("form.form_import").submit(function () { + var id = $(this).attr("id"); + var obj = $("#" + id + " input:file"); + if (/(?:\.csv|\.ods|\.xml)$/.test(obj.val())) { + var frameworkcode = $( + "#" + id + " input:hidden[name=frameworkcode]" + ).val(); + var MSG_OVERWRITE_WARNING = __( + "Are you sure you want to replace the fields and subfields for the %s framework structure? The existing structure will be overwritten! For safety reasons, it is recommended to use the export option to make a backup first." + ).format(frameworkcode); + if (confirm(MSG_OVERWRITE_WARNING)) { + $("#importing_" + frameworkcode) + .find("span") + .html( + __( + "Importing to framework: %s. Importing from file: %s." + ).format( + "" + frameworkcode + "", + "" + + obj + .val() + .replace(new RegExp("^.+[/\\\\]"), "") + + "" + ) + ); + if (navigator.userAgent.toLowerCase().indexOf("msie") != -1) { + var timestamp = new Date().getTime(); + $("#importing_" + frameworkcode) + .find("img") + .attr( + "src", + template_path + + "/img/spinner-small.gif" + + "?" + + timestamp + ); + } + $("#importing_" + frameworkcode).css("display", "block"); + if (navigator.userAgent.toLowerCase().indexOf("firefox") == -1) + $("body").css("cursor", "progress"); + importing = true; + $(".modal-footer,.btn-close").hide(); + return true; + } else return false; + } + obj.css("background-color", "yellow"); + alert(__("Please select a CSV (.csv) or ODS (.ods) spreadsheet file.")); + obj.val(""); + obj.css("background-color", "white"); + return false; + }); + $("#frameworkcode").on("blur", function () { + toUC(this); + }); +}); diff --git a/koha-tmpl/intranet-tmpl/prog/js/browser.js b/koha-tmpl/intranet-tmpl/prog/js/browser.js index d51f78723a..5a28fc8f19 100644 --- a/koha-tmpl/intranet-tmpl/prog/js/browser.js +++ b/koha-tmpl/intranet-tmpl/prog/js/browser.js @@ -1,29 +1,30 @@ /* global __ */ -if ( KOHA === undefined ) var KOHA = {}; +if (KOHA === undefined) var KOHA = {}; KOHA.browser = function (searchid, biblionumber) { var me = this; if (!searchid) { // We are generating a clean numeric datetime representation so we can easily compare them using the default javascript lexigraphic sorter. - searchid = 'scs_' + (new Date()).getTime(); // scs for Staff Client Search + searchid = "scs_" + new Date().getTime(); // scs for Staff Client Search } me.searchid = searchid; - var searches_stored = localStorage.getItem('searches'); + var searches_stored = localStorage.getItem("searches"); var current_search; var searches = {}; - if ( searches_stored ) { + if (searches_stored) { searches = JSON.parse(searches_stored); current_search = searches[me.searchid]; // Remove old entries var searchids = Object.keys(searches); var nb_searches = searchids.length; - if ( nb_searches > 20 ) { // No need to keep more than 20 searches + if (nb_searches > 20) { + // No need to keep more than 20 searches searchids = searchids.sort(); - for ( var i = 0 ; i < nb_searches - 20 ; i++ ) { + for (var i = 0; i < nb_searches - 20; i++) { delete searches[searchids[i]]; } } @@ -32,48 +33,90 @@ KOHA.browser = function (searchid, biblionumber) { var browseRecords = function (movement) { var newSearchPos = me.curPos + movement; if (newSearchPos > current_search.results.length - 1) { - window.location = '/cgi-bin/koha/catalogue/search.pl?' + current_search.query + '&limit=' + current_search.limit + '&sort_by=' + current_search.sort + '&gotoPage=detail.pl&gotoNumber=first&searchid=' + me.searchid + '&offset=' + newSearchPos; + window.location = + "/cgi-bin/koha/catalogue/search.pl?" + + current_search.query + + "&limit=" + + current_search.limit + + "&sort_by=" + + current_search.sort + + "&gotoPage=detail.pl&gotoNumber=first&searchid=" + + me.searchid + + "&offset=" + + newSearchPos; } else if (newSearchPos < 0) { - window.location = '/cgi-bin/koha/catalogue/search.pl?' + current_search.query + '&limit=' + current_search.limit + '&sort_by=' + current_search.sort + '&gotoPage=detail.pl&gotoNumber=last&searchid=' + me.searchid + '&offset=' + (me.offset - current_search.pagelen); + window.location = + "/cgi-bin/koha/catalogue/search.pl?" + + current_search.query + + "&limit=" + + current_search.limit + + "&sort_by=" + + current_search.sort + + "&gotoPage=detail.pl&gotoNumber=last&searchid=" + + me.searchid + + "&offset=" + + (me.offset - current_search.pagelen); } else { - window.location = window.location.href.replace('biblionumber=' + biblionumber, 'biblionumber=' + current_search.results[newSearchPos]); + window.location = window.location.href.replace( + "biblionumber=" + biblionumber, + "biblionumber=" + current_search.results[newSearchPos] + ); } - } + }; me.create = function (offset, query, limit, sort, newresults, total) { if (current_search) { - if (offset === parseInt(current_search.offset) - newresults.length) { - current_search.results = newresults.concat(current_search.results); - } else if (searchOffset = parseInt(current_search.offset) + newresults.length) { - current_search.results = current_search.results.concat(newresults); + if ( + offset === + parseInt(current_search.offset) - newresults.length + ) { + current_search.results = newresults.concat( + current_search.results + ); + } else if ( + (searchOffset = + parseInt(current_search.offset) + newresults.length) + ) { + current_search.results = + current_search.results.concat(newresults); } else { delete current_search; } } if (!current_search) { - current_search = { offset: offset, + current_search = { + offset: offset, query: query, limit: limit, - sort: sort, + sort: sort, pagelen: newresults.length, results: newresults, total: total, - searchid: searchid + searchid: searchid, }; } searches[me.searchid] = current_search; - localStorage.setItem('searches', JSON.stringify(searches)); + localStorage.setItem("searches", JSON.stringify(searches)); $(document).ready(function () { - $('#searchresults table tr a[href*="/detail.pl"]').each(function(){ - $(this).attr('href', $(this).attr('href') + '&searchid=' + me.searchid ); - }); + $('#searchresults table tr a[href*="/detail.pl"]').each( + function () { + $(this).attr( + "href", + $(this).attr("href") + "&searchid=" + me.searchid + ); + } + ); }); }; me.show = function () { if (current_search) { me.curPos = $.inArray(biblionumber, current_search.results); - if ( parseInt(current_search.offset ) + me.curPos <= current_search.pagelen ) { // First page + if ( + parseInt(current_search.offset) + me.curPos <= + current_search.pagelen + ) { + // First page me.offset = 0; } else { me.offset = parseInt(current_search.offset) - 1; @@ -81,35 +124,81 @@ KOHA.browser = function (searchid, biblionumber) { $(document).ready(function () { if (me.curPos > -1) { - var searchURL = '/cgi-bin/koha/catalogue/search.pl?' + current_search.query + '&limit=' + current_search.limit + '&sort_by=' + current_search.sort + '&searchid=' + me.searchid + '&offset=' + me.offset; + var searchURL = + "/cgi-bin/koha/catalogue/search.pl?" + + current_search.query + + "&limit=" + + current_search.limit + + "&sort_by=" + + current_search.sort + + "&searchid=" + + me.searchid + + "&offset=" + + me.offset; var prevbutton; var nextbutton; - if (me.curPos === 0 && parseInt(current_search.offset) === 1) { - prevbutton = ''; + if ( + me.curPos === 0 && + parseInt(current_search.offset) === 1 + ) { + prevbutton = + ''; } else { - prevbutton = ''; + prevbutton = + ''; } - if (parseInt(current_search.offset) + me.curPos == current_search.total) { - nextbutton = ''; + if ( + parseInt(current_search.offset) + me.curPos == + current_search.total + ) { + nextbutton = + ''; } else { - nextbutton = ''; + nextbutton = + ''; } - $('#menu').before('
          ' + prevbutton + nextbutton + '
          '); - $('a#browse-previous').click(function (ev) { + $("#menu").before( + '
          ' + + prevbutton + + nextbutton + + "
          " + ); + $("a#browse-previous").click(function (ev) { ev.preventDefault(); browseRecords(-1); }); - $('a#browse-next').click(function (ev) { + $("a#browse-next").click(function (ev) { ev.preventDefault(); browseRecords(1); }); - $('a[href*="biblionumber="]').not('a[target="_blank"]').click(function (ev) { - ev.preventDefault(); - var url = new URL($(this).attr('href'), window.location.origin); - url.searchParams.set('searchid', me.searchid); - window.location = url.href; - }); - $('form[name="f"]').append(''); + $('a[href*="biblionumber="]') + .not('a[target="_blank"]') + .click(function (ev) { + ev.preventDefault(); + var url = new URL( + $(this).attr("href"), + window.location.origin + ); + url.searchParams.set("searchid", me.searchid); + window.location = url.href; + }); + $('form[name="f"]').append( + '' + ); } }); } @@ -118,12 +207,25 @@ KOHA.browser = function (searchid, biblionumber) { me.show_back_link = function () { if (current_search) { $(document).ready(function () { - var searchURL = '/cgi-bin/koha/catalogue/search.pl?' + current_search.query + '&limit=' + current_search.limit + '&sort_by=' + current_search.sort + '&searchid=' + me.searchid; - $('#previous_search_link').replaceWith(''); + var searchURL = + "/cgi-bin/koha/catalogue/search.pl?" + + current_search.query + + "&limit=" + + current_search.limit + + "&sort_by=" + + current_search.sort + + "&searchid=" + + me.searchid; + $("#previous_search_link").replaceWith( + '" + ); }); } }; - return me; }; diff --git a/koha-tmpl/intranet-tmpl/prog/js/calendar.js b/koha-tmpl/intranet-tmpl/prog/js/calendar.js index 24a86e5bcd..d5af71b562 100644 --- a/koha-tmpl/intranet-tmpl/prog/js/calendar.js +++ b/koha-tmpl/intranet-tmpl/prog/js/calendar.js @@ -1,26 +1,30 @@ /* global debug sentmsg __ dateformat_pref flatpickr_dateformat_string bidi calendarFirstDayOfWeek */ /* exported DateTime_from_syspref flatpickr_weekdays flatpickr_months */ -var MSG_PLEASE_ENTER_A_VALID_DATE = ( __("Please enter a valid date (should match %s).") ); +var MSG_PLEASE_ENTER_A_VALID_DATE = __( + "Please enter a valid date (should match %s)." +); if (debug > 1) { - alert("dateformat: " + dateformat_pref + "\ndebug is on (level " + debug + ")"); + alert( + "dateformat: " + dateformat_pref + "\ndebug is on (level " + debug + ")" + ); } function is_valid_date(date) { // An empty string is considered as a valid date for convenient reasons. - if (date === '') return 1; + if (date === "") return 1; var dateformat = flatpickr_dateformat_string; - if (dateformat == 'us') { + if (dateformat == "us") { if (date.search(/^\d{2}\/\d{2}\/\d{4}($|\s)/) == -1) return 0; - dateformat = 'm/d/Y'; - } else if (dateformat == 'metric') { + dateformat = "m/d/Y"; + } else if (dateformat == "metric") { if (date.search(/^\d{2}\/\d{2}\/\d{4}($|\s)/) == -1) return 0; - dateformat = 'd/m/Y'; - } else if (dateformat == 'iso') { + dateformat = "d/m/Y"; + } else if (dateformat == "iso") { if (date.search(/^\d{4}-\d{2}-\d{2}($|\s)/) == -1) return 0; - dateformat = 'Y-m-d'; - } else if (dateformat == 'dmydot') { + dateformat = "Y-m-d"; + } else if (dateformat == "dmydot") { if (date.search(/^\d{2}\.\d{2}\.\d{4}($|\s)/) == -1) return 0; - dateformat = 'd.m.Y'; + dateformat = "d.m.Y"; } try { flatpickr.parseDate(date, dateformat); @@ -32,21 +36,21 @@ function is_valid_date(date) { function get_dateformat_str(dateformat) { var dateformat_str; - if (dateformat == 'us') { - dateformat_str = 'mm/dd/yyyy'; - } else if (dateformat == 'metric') { - dateformat_str = 'dd/mm/yyyy'; - } else if (dateformat == 'iso') { - dateformat_str = 'yyyy-mm-dd'; - } else if (dateformat == 'dmydot') { - dateformat_str = 'dd.mm.yyyy'; + if (dateformat == "us") { + dateformat_str = "mm/dd/yyyy"; + } else if (dateformat == "metric") { + dateformat_str = "dd/mm/yyyy"; + } else if (dateformat == "iso") { + dateformat_str = "yyyy-mm-dd"; + } else if (dateformat == "dmydot") { + dateformat_str = "dd.mm.yyyy"; } return dateformat_str; } function validate_date(dateText, inst) { if (!is_valid_date(dateText)) { - var dateformat_str = get_dateformat_str( dateformat_pref ); + var dateformat_str = get_dateformat_str(dateformat_pref); alert(MSG_PLEASE_ENTER_A_VALID_DATE.format(dateformat_str)); inst.clear(); } @@ -56,16 +60,18 @@ function Date_from_syspref(dstring) { var dateX = dstring.split(/[-/.]/); if (debug > 1 && sentmsg < 1) { sentmsg++; - alert("Date_from_syspref(" + dstring + ") splits to:\n" + dateX.join("\n")); + alert( + "Date_from_syspref(" + dstring + ") splits to:\n" + dateX.join("\n") + ); } if (dateformat_pref === "iso") { - return new Date(dateX[0], (dateX[1] - 1), dateX[2]); // YYYY-MM-DD to (YYYY,m(0-11),d) + return new Date(dateX[0], dateX[1] - 1, dateX[2]); // YYYY-MM-DD to (YYYY,m(0-11),d) } else if (dateformat_pref === "us") { - return new Date(dateX[2], (dateX[0] - 1), dateX[1]); // MM/DD/YYYY to (YYYY,m(0-11),d) + return new Date(dateX[2], dateX[0] - 1, dateX[1]); // MM/DD/YYYY to (YYYY,m(0-11),d) } else if (dateformat_pref === "metric") { - return new Date(dateX[2], (dateX[1] - 1), dateX[0]); // DD/MM/YYYY to (YYYY,m(0-11),d) + return new Date(dateX[2], dateX[1] - 1, dateX[0]); // DD/MM/YYYY to (YYYY,m(0-11),d) } else if (dateformat_pref === "dmydot") { - return new Date(dateX[2], (dateX[1] - 1), dateX[0]); // DD.MM.YYYY to (YYYY,m(0-11),d) + return new Date(dateX[2], dateX[1] - 1, dateX[0]); // DD.MM.YYYY to (YYYY,m(0-11),d) } else { if (debug > 0) { alert("KOHA ERROR - Unrecognized date format: " + dateformat_pref); @@ -120,26 +126,69 @@ function DateTime_from_syspref(date_time) { }); */ -jQuery.validator.addMethod("is_date_after", - function (value, element, params) { - var from = Date_from_syspref($(params).val()); - var to = Date_from_syspref(value); - return to > from; - }); +jQuery.validator.addMethod("is_date_after", function (value, element, params) { + var from = Date_from_syspref($(params).val()); + var to = Date_from_syspref(value); + return to > from; +}); -jQuery.validator.addMethod("date_on_or_after", +jQuery.validator.addMethod( + "date_on_or_after", function (value, element, params) { var from = Date_from_syspref($(params).val()); var to = Date_from_syspref(value); return to >= from; - }); + } +); var flatpickr_weekdays = { - shorthand: [ __("Sun"), __("Mon"), __("Tue"), __("Wed"), __("Thu"), __("Fri"), __("Sat")], - longhand: [ __("Sunday"), __("Monday"), __("Tuesday"), __("Wednesday"), __("Thursday"), __("Friday"), __("Saturday") ] + shorthand: [ + __("Sun"), + __("Mon"), + __("Tue"), + __("Wed"), + __("Thu"), + __("Fri"), + __("Sat"), + ], + longhand: [ + __("Sunday"), + __("Monday"), + __("Tuesday"), + __("Wednesday"), + __("Thursday"), + __("Friday"), + __("Saturday"), + ], }; var flatpickr_months = { - shorthand: [ __("Jan"), __("Feb"), __("Mar"), __("Apr"), __("May"), __("Jun"), __("Jul"), __("Aug"), __("Sep"), __("Oct"), __("Nov"), __("Dec")], - longhand: [ __("January"), __("February"), __("March"), __("April"), __("May"), __("June"), __("July"), __("August"), __("September"), __("October"), __("November"), __("December")] + shorthand: [ + __("Jan"), + __("Feb"), + __("Mar"), + __("Apr"), + __("May"), + __("Jun"), + __("Jul"), + __("Aug"), + __("Sep"), + __("Oct"), + __("Nov"), + __("Dec"), + ], + longhand: [ + __("January"), + __("February"), + __("March"), + __("April"), + __("May"), + __("June"), + __("July"), + __("August"), + __("September"), + __("October"), + __("November"), + __("December"), + ], }; diff --git a/koha-tmpl/intranet-tmpl/prog/js/cart.js b/koha-tmpl/intranet-tmpl/prog/js/cart.js index 0514331af7..bd723eea3c 100644 --- a/koha-tmpl/intranet-tmpl/prog/js/cart.js +++ b/koha-tmpl/intranet-tmpl/prog/js/cart.js @@ -1,31 +1,32 @@ /* global __ dataTablesDefaults showMore showLess delSelRecords addSelToShelf sendBasket printBasket delBasket openBiblio selRecord */ -function placeHold () { +function placeHold() { var checkedItems = $("input:checkbox:checked"); if ($(checkedItems).size() === 0) { - alert( __("No item was selected") ); + alert(__("No item was selected")); return false; } var bib_params = []; - $(checkedItems).each(function() { + $(checkedItems).each(function () { var bib = $(this).val(); bib_params.push("biblionumber=" + bib); }); if (bib_params.length > 1) { - bib_params.push('multi_hold=1'); + bib_params.push("multi_hold=1"); } - window.opener.location = "/cgi-bin/koha/reserve/request.pl?" + bib_params.join('&'); + window.opener.location = + "/cgi-bin/koha/reserve/request.pl?" + bib_params.join("&"); window.close(); } -function resultsBatchProcess( op ){ - if( op == "edit" || op == "delete" ){ +function resultsBatchProcess(op) { + if (op == "edit" || op == "delete") { let checkedItems = $(".select_record:checked"); - if ( checkedItems.size() === 0 ) { - alert( __("No item was selected") ); + if (checkedItems.size() === 0) { + alert(__("No item was selected")); return false; } else { /* Dynamically create a form in the parent window so that */ @@ -34,26 +35,36 @@ function resultsBatchProcess( op ){ const body = window.opener.document.getElementsByTagName("body"); let f = document.createElement("form"); f.setAttribute("method", "post"); - if( op == "edit" ){ + if (op == "edit") { /* batch edit selected records */ - f.setAttribute("action", "/cgi-bin/koha/tools/batch_record_modification.pl"); - } else if( op == "delete" ){ + f.setAttribute( + "action", + "/cgi-bin/koha/tools/batch_record_modification.pl" + ); + } else if (op == "delete") { /* batch delete selected records */ - f.setAttribute("action", "/cgi-bin/koha/tools/batch_delete_records.pl"); + f.setAttribute( + "action", + "/cgi-bin/koha/tools/batch_delete_records.pl" + ); } - f.innerHTML = ''; - f.innerHTML += ''; + f.innerHTML = + ''; + f.innerHTML += + ''; let textarea = document.createElement("textarea"); textarea.setAttribute("name", "bib_list"); textarea.setAttribute("style", "display:none"); - checkedItems.each(function() { - params.push( $(this).val() ); + checkedItems.each(function () { + params.push($(this).val()); }); textarea.value = params.join("/"); - f.append( textarea ); - body[0].append( f ); + f.append(textarea); + body[0].append(f); f.submit(); window.close(); } @@ -62,7 +73,7 @@ function resultsBatchProcess( op ){ } } -$(document).ready(function(){ +$(document).ready(function () { $("#items-popover").popover(); $("#CheckAll").click(function (e) { @@ -80,69 +91,71 @@ $(document).ready(function(){ }); $(".holdsep").text("| "); - $(".hold").text( __("Place hold") ); + $(".hold").text(__("Place hold")); $("#downloadcartc").empty(); - $("#itemst").dataTable($.extend(true, {}, dataTablesDefaults, { - "dom": 't', - "columnDefs": [ - { "orderable": false, "searchable": false, "targets": [ 'NoSort' ] }, - { "type": "anti-the", "targets": [ "anti-the" ] }, - { "type": "callnumbers", "targets": [ "callnumbers"] } - ], - "order": [[ 1, "asc" ]], - "paging": false - })); + $("#itemst").dataTable( + $.extend(true, {}, dataTablesDefaults, { + dom: "t", + columnDefs: [ + { orderable: false, searchable: false, targets: ["NoSort"] }, + { type: "anti-the", targets: ["anti-the"] }, + { type: "callnumbers", targets: ["callnumbers"] }, + ], + order: [[1, "asc"]], + paging: false, + }) + ); - $(".showdetails").on("click",function(e){ + $(".showdetails").on("click", function (e) { e.preventDefault(); - if( $(this).hasClass("showmore") ){ + if ($(this).hasClass("showmore")) { showMore(); } else { showLess(); } }); - $("#remove_from_cart").on("click",function(e){ + $("#remove_from_cart").on("click", function (e) { e.preventDefault(); delSelRecords(); }); - $("#add_to_list").on("click",function(e){ + $("#add_to_list").on("click", function (e) { e.preventDefault(); addSelToShelf(); }); - $("#place_hold").on("click",function(e){ + $("#place_hold").on("click", function (e) { e.preventDefault(); placeHold(); }); - $("#send_cart").on("click",function(e){ + $("#send_cart").on("click", function (e) { e.preventDefault(); sendBasket(); }); - $("#print_cart").on("click",function(e){ + $("#print_cart").on("click", function (e) { e.preventDefault(); printBasket(); }); - $("#empty_cart").on("click",function(e){ + $("#empty_cart").on("click", function (e) { e.preventDefault(); - delBasket('popup'); + delBasket("popup"); }); - $(".title").on("click",function(e){ + $(".title").on("click", function (e) { e.preventDefault(); - openBiblio( this.href ); + openBiblio(this.href); }); - $(".select_record").on("change",function(){ - selRecord( this.value, this.checked ); + $(".select_record").on("change", function () { + selRecord(this.value, this.checked); }); - $(".results_batch_op").on("click", function(e){ + $(".results_batch_op").on("click", function (e) { e.preventDefault(); var op = $(this).data("op"); - resultsBatchProcess( op ); + resultsBatchProcess(op); }); }); diff --git a/koha-tmpl/intranet-tmpl/prog/js/cashup_modal.js b/koha-tmpl/intranet-tmpl/prog/js/cashup_modal.js index a28e32a8ff..f5921558be 100644 --- a/koha-tmpl/intranet-tmpl/prog/js/cashup_modal.js +++ b/koha-tmpl/intranet-tmpl/prog/js/cashup_modal.js @@ -1,44 +1,83 @@ -$(document).ready(function() { - $('#cashupSummaryModal').on('show.bs.modal', function(e) { +$(document).ready(function () { + $("#cashupSummaryModal").on("show.bs.modal", function (e) { var button = $(e.relatedTarget); - var cashup = button.data('cashup'); - var description = button.data('register'); + var cashup = button.data("cashup"); + var description = button.data("register"); var summary_modal = $(this); - summary_modal.find('#register_description').text(description); + summary_modal.find("#register_description").text(description); $.ajax({ - url: '/api/v1/cashups/' + cashup, + url: "/api/v1/cashups/" + cashup, headers: { - 'x-koha-embed': 'summary' + "x-koha-embed": "summary", }, async: false, - success: function(data) { + success: function (data) { let from_date = $datetime(data.summary.from_date); - summary_modal.find('#from_date').text(from_date); + summary_modal.find("#from_date").text(from_date); let to_date = $datetime(data.summary.to_date); - summary_modal.find('#to_date').text(to_date); - var tbody = summary_modal.find('tbody') + summary_modal.find("#to_date").text(to_date); + var tbody = summary_modal.find("tbody"); tbody.empty(); for (out of data.summary.payout_grouped) { - if (out.credit_type_code == 'REFUND') { - tbody.append('' + __x('{credit_type_description} against {debit_type_description}', { 'credit_type_description': escape_str(out.credit_type.description), 'debit_type_description': escape_str(out.related_debit.debit_type.description) }) + '- ' + out.total.format_price() + ''); + if (out.credit_type_code == "REFUND") { + tbody.append( + "" + + __x( + "{credit_type_description} against {debit_type_description}", + { + credit_type_description: escape_str( + out.credit_type.description + ), + debit_type_description: escape_str( + out.related_debit.debit_type + .description + ), + } + ) + + "- " + + out.total.format_price() + + "" + ); } else { - tbody.append('' + escape_str(out.credit_type.description) + '- ' + out.total.format_price() + ''); + tbody.append( + "" + + escape_str(out.credit_type.description) + + "- " + + out.total.format_price() + + "" + ); } } for (income of data.summary.income_grouped) { - tbody.append('' + escape_str(income.debit_type.description) + '' + income.total.format_price() + ''); + tbody.append( + "" + + escape_str(income.debit_type.description) + + "" + + income.total.format_price() + + "" + ); } - var tfoot = summary_modal.find('tfoot'); + var tfoot = summary_modal.find("tfoot"); tfoot.empty(); - tfoot.append('Total' + data.summary.total.format_price() + ''); + tfoot.append( + "Total" + + data.summary.total.format_price() + + "" + ); for (type of data.summary.total_grouped) { if (type.total !== 0) { - tfoot.append('' + escape_str(type.payment_type) + '' + type.total.format_price() + ''); + tfoot.append( + "" + + escape_str(type.payment_type) + + "" + + type.total.format_price() + + "" + ); } } - } + }, }); }); }); diff --git a/koha-tmpl/intranet-tmpl/prog/js/catalog.js b/koha-tmpl/intranet-tmpl/prog/js/catalog.js index ec37cb0894..bbd96152dd 100644 --- a/koha-tmpl/intranet-tmpl/prog/js/catalog.js +++ b/koha-tmpl/intranet-tmpl/prog/js/catalog.js @@ -1,58 +1,106 @@ /* global __ biblionumber count holdcount countorders countdeletedorders searchid addRecord delSingleRecord */ /* exported GetZ3950Terms PopupZ3950Confirmed */ /* IF ( CAN_user_editcatalogue_edit_catalogue ) */ - /* this function open a popup to search on z3950 server. */ - function PopupZ3950() { - var strQuery = GetZ3950Terms(); - if(strQuery){ - window.open("/cgi-bin/koha/cataloguing/z3950_search.pl?biblionumber=" + biblionumber + strQuery,"z3950search",'width=740,height=450,location=yes,toolbar=no,scrollbars=yes,resize=yes'); - } +/* this function open a popup to search on z3950 server. */ +function PopupZ3950() { + var strQuery = GetZ3950Terms(); + if (strQuery) { + window.open( + "/cgi-bin/koha/cataloguing/z3950_search.pl?biblionumber=" + + biblionumber + + strQuery, + "z3950search", + "width=740,height=450,location=yes,toolbar=no,scrollbars=yes,resize=yes" + ); } - function PopupZ3950Confirmed() { - if (confirm( __("Please note that this external search could replace the current record.") )) { - PopupZ3950(); - } +} +function PopupZ3950Confirmed() { + if ( + confirm( + __( + "Please note that this external search could replace the current record." + ) + ) + ) { + PopupZ3950(); } +} /* END IF( CAN_user_editcatalogue_edit_catalogue ) */ -function addToCart(){ - addRecord( biblionumber ); +function addToCart() { + addRecord(biblionumber); } function addToShelf() { - openWindow('/cgi-bin/koha/virtualshelves/addbybiblionumber.pl?biblionumber=' + biblionumber,'Add_to_virtualshelf'); + openWindow( + "/cgi-bin/koha/virtualshelves/addbybiblionumber.pl?biblionumber=" + + biblionumber, + "Add_to_virtualshelf" + ); +} +function printBiblio() { + window.print(); } -function printBiblio() {window.print(); } /* IF CAN_user_editcatalogue_edit_catalogue or ( frameworkcode == 'FA' and CAN_user_editcatalogue_fast_cataloging ) */ function confirm_deletion(link) { var order_manage_permission = $(link).data("order-manage"); var is_confirmed; - if (count > 0){ - is_confirmed = alert(__("%s item(s) are attached to this record. You must delete all items before deleting this record.").format(count)); - } else if (countorders > 0){ - if( order_manage_permission ){ - is_confirmed = confirm(__("Warning: This record is used in %s order(s). These orders will be cancelled. Are you sure you want to delete this record?").format(countorders)); + if (count > 0) { + is_confirmed = alert( + __( + "%s item(s) are attached to this record. You must delete all items before deleting this record." + ).format(count) + ); + } else if (countorders > 0) { + if (order_manage_permission) { + is_confirmed = confirm( + __( + "Warning: This record is used in %s order(s). These orders will be cancelled. Are you sure you want to delete this record?" + ).format(countorders) + ); } else { - is_confirmed = alert(__("%s order(s) are using this record. You need order managing permissions to delete this record.").format(countorders)); + is_confirmed = alert( + __( + "%s order(s) are using this record. You need order managing permissions to delete this record." + ).format(countorders) + ); } - } else if (countdeletedorders > 0){ - if( order_manage_permission ){ - is_confirmed = confirm(__("%s deleted order(s) are using this record. Are you sure you want to delete this record?").format(countdeletedorders)); + } else if (countdeletedorders > 0) { + if (order_manage_permission) { + is_confirmed = confirm( + __( + "%s deleted order(s) are using this record. Are you sure you want to delete this record?" + ).format(countdeletedorders) + ); } else { - is_confirmed = alert(__("%s deleted order(s) are using this record. You need order managing permissions to delete this record.").format(countdeletedorders)); + is_confirmed = alert( + __( + "%s deleted order(s) are using this record. You need order managing permissions to delete this record." + ).format(countdeletedorders) + ); } - } else if ( holdcount > 0 ) { - is_confirmed = confirm( __("%s holds(s) for this record. Are you sure you want to delete this record?").format(holdcount)); - } else if (subscriptionscount > 0){ - is_confirmed = alert(__("%s subscription(s) are attached to this record. You must delete all subscription before deleting this record.").format(subscriptionscount)); + } else if (holdcount > 0) { + is_confirmed = confirm( + __( + "%s holds(s) for this record. Are you sure you want to delete this record?" + ).format(holdcount) + ); + } else if (subscriptionscount > 0) { + is_confirmed = alert( + __( + "%s subscription(s) are attached to this record. You must delete all subscription before deleting this record." + ).format(subscriptionscount) + ); } else { - is_confirmed = confirm( __("Are you sure you want to delete this record?") ); + is_confirmed = confirm( + __("Are you sure you want to delete this record?") + ); } if (is_confirmed) { - $("#deletebiblio").unbind('click'); - return $(link).siblings('form').submit(); + $("#deletebiblio").unbind("click"); + return $(link).siblings("form").submit(); } else { return false; } @@ -63,11 +111,21 @@ function confirm_deletion(link) { /* IF CAN_user_editcatalogue_edit_items or ( frameworkcode == 'FA' and CAN_user_editcatalogue_fast_cataloging ) */ function confirm_items_deletion(link) { - if ( holdcount > 0 ) { - alert(__("%s hold(s) on this record. You must delete all holds before deleting all items.").format(holdcount)); - } else if ( count > 0 ) { - if (confirm(__("Are you sure you want to delete the %s attached items?").format(count))) { - return $(link).siblings('form').submit(); + if (holdcount > 0) { + alert( + __( + "%s hold(s) on this record. You must delete all holds before deleting all items." + ).format(holdcount) + ); + } else if (count > 0) { + if ( + confirm( + __( + "Are you sure you want to delete the %s attached items?" + ).format(count) + ) + ) { + return $(link).siblings("form").submit(); } else { return false; } @@ -78,20 +136,20 @@ function confirm_items_deletion(link) { /* END IF CAN_user_editcatalogue_edit_items or ( frameworkcode == 'FA' and CAN_user_editcatalogue_fast_cataloging ) */ -$(document).ready(function() { - $("#z3950copy").click(function(){ +$(document).ready(function () { + $("#z3950copy").click(function () { PopupZ3950(); return false; }); - $("#deletebiblio").click(function(){ + $("#deletebiblio").click(function () { confirm_deletion(this); return false; }); - $("#deleteallitems").click(function(){ + $("#deleteallitems").click(function () { confirm_items_deletion(this); return false; }); - $("#printbiblio").click(function(){ + $("#printbiblio").click(function () { printBiblio(); return false; }); @@ -108,10 +166,12 @@ $(document).ready(function() { var selection_id = this.id; var biblionumber = selection_id.replace("cartR", ""); delSingleRecord(biblionumber); - $(".addtocart").html(" " + __("Add to cart")); + $(".addtocart").html( + ' ' + __("Add to cart") + ); }); - $("#addtoshelf").click(function(){ + $("#addtoshelf").click(function () { addToShelf(); $(".btn-group").removeClass("open"); return false; @@ -122,12 +182,22 @@ $(document).ready(function() { e.preventDefault(); var shelfnumber = $(this).data("shelfnumber"); if ($(this).hasClass("morelists")) { - openWindow('/cgi-bin/koha/virtualshelves/addbybiblionumber.pl?biblionumber=' + biblionumber); + openWindow( + "/cgi-bin/koha/virtualshelves/addbybiblionumber.pl?biblionumber=" + + biblionumber + ); } else if ($(this).hasClass("newlist")) { - openWindow('/cgi-bin/koha/virtualshelves/addbybiblionumber.pl?newshelf=1&biblionumber=' + biblionumber); + openWindow( + "/cgi-bin/koha/virtualshelves/addbybiblionumber.pl?newshelf=1&biblionumber=" + + biblionumber + ); } else { - openWindow('/cgi-bin/koha/virtualshelves/addbybiblionumber.pl?shelfnumber=' + shelfnumber + '&confirm=1&biblionumber=' + biblionumber); + openWindow( + "/cgi-bin/koha/virtualshelves/addbybiblionumber.pl?shelfnumber=" + + shelfnumber + + "&confirm=1&biblionumber=" + + biblionumber + ); } }); - }); diff --git a/koha-tmpl/intranet-tmpl/prog/js/cataloging.js b/koha-tmpl/intranet-tmpl/prog/js/cataloging.js index 2cb734ef6e..2fee76f4d0 100644 --- a/koha-tmpl/intranet-tmpl/prog/js/cataloging.js +++ b/koha-tmpl/intranet-tmpl/prog/js/cataloging.js @@ -8,73 +8,96 @@ /* Functions developed for addbiblio.tt and authorities.tt */ // returns the fieldcode based upon tag div id -function getFieldCode(tagDivId){ +function getFieldCode(tagDivId) { // format : tag__... - return tagDivId.substr(3+1,3); + return tagDivId.substr(3 + 1, 3); } //returns the field and subfieldcode based upon subfield div id -function getFieldAndSubfieldCode(subfieldDivId){ +function getFieldAndSubfieldCode(subfieldDivId) { // format : subfield... - return subfieldDivId.substr(8,3+1); + return subfieldDivId.substr(8, 3 + 1); } //returns the subfieldcode based upon subfieldid writing -function getSubfieldCode(tagsubfieldid){ +function getSubfieldCode(tagsubfieldid) { // 3 : tag +3 : tagnumber +4 : number of _ +8 subfield -1 begins at 0 - return tagsubfieldid.substr(3+3+4+8-1,1); + return tagsubfieldid.substr(3 + 3 + 4 + 8 - 1, 1); } // Take the base of tagsubfield information (removing the subfieldcodes and subfieldindexes) // returns the filter -function getTagInputnameFilter(tagsubfieldid){ - var tagsubfield=tagsubfieldid.substr(0,tagsubfieldid.lastIndexOf("_")); - var tagcode=tagsubfield.substr(tagsubfield.lastIndexOf("_")); - tagsubfield=tagsubfield.substr(0,tagsubfield.lastIndexOf("_")); - tagsubfield=tagsubfield.substr(0,tagsubfield.lastIndexOf("_")); - tagsubfield=tagsubfield+"_."+tagcode; +function getTagInputnameFilter(tagsubfieldid) { + var tagsubfield = tagsubfieldid.substr(0, tagsubfieldid.lastIndexOf("_")); + var tagcode = tagsubfield.substr(tagsubfield.lastIndexOf("_")); + tagsubfield = tagsubfield.substr(0, tagsubfield.lastIndexOf("_")); + tagsubfield = tagsubfield.substr(0, tagsubfield.lastIndexOf("_")); + tagsubfield = tagsubfield + "_." + tagcode; return tagsubfield; } // if source is "auth", we are editing an authority otherwise it is a biblio -function openAuth(tagsubfieldid,authtype,source) { +function openAuth(tagsubfieldid, authtype, source) { // let's take the base of tagsubfield information (removing the indexes and the codes - var element=document.getElementById(tagsubfieldid); - var tagsubfield=getTagInputnameFilter(tagsubfieldid); - var elementsubfcode=getSubfieldCode(element.name); - var mainmainstring=element.value; + var element = document.getElementById(tagsubfieldid); + var tagsubfield = getTagInputnameFilter(tagsubfieldid); + var elementsubfcode = getSubfieldCode(element.name); + var mainmainstring = element.value; var mainstring = new Array(); - var ul = element.closest('ul'); - var inputs = ul ? ul.getElementsByTagName('input') : element.parentNode.getElementsByTagName('input'); - for (var myindex =0; myindex - var lis = original.getElementsByTagName('li'); - for(var i=0,lislen = lis.length ; i show all subfields - lis[i].style.display = 'flex'; - } else if (lis[i].style.display == 'none') { + lis[i].style.display = "flex"; + } else if (lis[i].style.display == "none") { // show - lis[i].style.display = 'flex'; + lis[i].style.display = "flex"; } else { // hide - lis[i].style.display = 'none'; + lis[i].style.display = "none"; } } } @@ -83,72 +106,107 @@ function ExpandField() { var current_select2; var Select2Utils = { - removeSelect2: function(selects) { + removeSelect2: function (selects) { if ($.fn.select2) { - $(selects).each(function(){ - $(this).select2('destroy'); + $(selects).each(function () { + $(this).select2("destroy"); }); } }, - initSelect2: function(selects) { + initSelect2: function (selects) { if ($.fn.select2) { - if ( window.auth_values_creation === undefined || ! auth_values_creation ) { - $(selects).select2().on("select2:clear", function () { - $(this).on("select2:opening.cancelOpen", function (evt) { - evt.preventDefault(); - $(this).off("select2:opening.cancelOpen"); + if ( + window.auth_values_creation === undefined || + !auth_values_creation + ) { + $(selects) + .select2() + .on("select2:clear", function () { + $(this).on( + "select2:opening.cancelOpen", + function (evt) { + evt.preventDefault(); + $(this).off("select2:opening.cancelOpen"); + } + ); }); - }); } else { - $(selects).each(function(){ - if ( !$(this).data("category") ) { - $(this).select2().on("select2:clear", function () { - $(this).on("select2:opening.cancelOpen", function (evt) { - evt.preventDefault(); - $(this).off("select2:opening.cancelOpen"); + $(selects).each(function () { + if (!$(this).data("category")) { + $(this) + .select2() + .on("select2:clear", function () { + $(this).on( + "select2:opening.cancelOpen", + function (evt) { + evt.preventDefault(); + $(this).off( + "select2:opening.cancelOpen" + ); + } + ); }); - }); } else { - $(this).select2({ - tags: true, - createTag: function (tag) { - return { - id: tag.term, - text: tag.term, - newTag: true - }; - }, - templateResult: function(state) { - if (state.newTag) { - return state.text + " " + __("(select to create)"); + $(this) + .select2({ + tags: true, + createTag: function (tag) { + return { + id: tag.term, + text: tag.term, + newTag: true, + }; + }, + templateResult: function (state) { + if (state.newTag) { + return ( + state.text + + " " + + __("(select to create)") + ); + } + return state.text; + }, + }) + .on("select2:select", function (e) { + if (e.params.data.newTag) { + current_select2 = this; + var category = $(this).data("category"); + $("#avCreate #new_av_category").html( + category + ); + $("#avCreate input[name='category']").val( + category + ); + $("#avCreate input[name='value']").val(""); + $( + "#avCreate input[name='description']" + ).val(e.params.data.text); + + $(this) + .val($(this).find("option:first").val()) + .trigger("change"); + $("#avCreate").modal("show"); } - return state.text; - } - }).on("select2:select", function(e) { - if(e.params.data.newTag){ - current_select2 = this; - var category = $(this).data("category"); - $("#avCreate #new_av_category").html(category); - $("#avCreate input[name='category']").val(category); - $("#avCreate input[name='value']").val(''); - $("#avCreate input[name='description']").val(e.params.data.text); + }) + .on("select2:clear", function () { + $(this).on( + "select2:opening.cancelOpen", + function (evt) { + evt.preventDefault(); - $(this).val($(this).find("option:first").val()).trigger('change'); - $('#avCreate').modal("show"); - } - }).on("select2:clear", function () { - $(this).on("select2:opening.cancelOpen", function (evt) { - evt.preventDefault(); - - $(this).off("select2:opening.cancelOpen"); + $(this).off( + "select2:opening.cancelOpen" + ); + } + ); }); - }); } }); } } - } + }, }; /** @@ -158,298 +216,407 @@ var Select2Utils = { */ function CloneField(index, hideMarc, advancedMARCEditor) { var original = document.getElementById(index); //original
        • - Select2Utils.removeSelect2($(original).find('select')); + Select2Utils.removeSelect2($(original).find("select")); var clone = original.cloneNode(true); var new_key = CreateKey(); - var new_id = original.getAttribute('id')+new_key; + var new_id = original.getAttribute("id") + new_key; - clone.setAttribute('id',new_id); // setting a new id for the parent li + clone.setAttribute("id", new_id); // setting a new id for the parent li - var divs = Array.from(clone.getElementsByTagName('li')).concat(Array.from(clone.getElementsByTagName('div'))); + var divs = Array.from(clone.getElementsByTagName("li")).concat( + Array.from(clone.getElementsByTagName("div")) + ); // if hide_marc, indicators are hidden fields // setting a new name for the new indicator - for(var i=0; i < 2; i++) { - var indicator = clone.getElementsByTagName('input')[i]; - indicator.setAttribute('name',indicator.getAttribute('name')+new_key); + for (var i = 0; i < 2; i++) { + var indicator = clone.getElementsByTagName("input")[i]; + indicator.setAttribute( + "name", + indicator.getAttribute("name") + new_key + ); } // settings all subfields var divslen = divs.length; - for( i=0; i < divslen ; i++ ){ // foreach div/li - if( divs[i].getAttribute("id") && divs[i].getAttribute("id").match(/^subfield/)){ // if it s a subfield + for (i = 0; i < divslen; i++) { + // foreach div/li + if ( + divs[i].getAttribute("id") && + divs[i].getAttribute("id").match(/^subfield/) + ) { + // if it s a subfield // set the attribute for the new 'li' subfields - divs[i].setAttribute('id',divs[i].getAttribute('id')+new_key); + divs[i].setAttribute("id", divs[i].getAttribute("id") + new_key); - var inputs = divs[i].getElementsByTagName('input'); + var inputs = divs[i].getElementsByTagName("input"); var id_input = ""; var olddiv; var oldcontrol; - for( j = 0 ; j < inputs.length ; j++ ) { - if(inputs[j].getAttribute("id") && inputs[j].getAttribute("id").match(/^tag_/) ){ + for (j = 0; j < inputs.length; j++) { + if ( + inputs[j].getAttribute("id") && + inputs[j].getAttribute("id").match(/^tag_/) + ) { inputs[j].value = ""; //Remove the color added by the automatic linker - $(inputs[j]).removeClass("matching_authority_field no_matching_authority_field"); + $(inputs[j]).removeClass( + "matching_authority_field no_matching_authority_field" + ); } } - var textareas = divs[i].getElementsByTagName('textarea'); - for( j = 0 ; j < textareas.length ; j++ ) { - if(textareas[j].getAttribute("id") && textareas[j].getAttribute("id").match(/^tag_/) ){ + var textareas = divs[i].getElementsByTagName("textarea"); + for (j = 0; j < textareas.length; j++) { + if ( + textareas[j].getAttribute("id") && + textareas[j].getAttribute("id").match(/^tag_/) + ) { textareas[j].value = ""; } } // Remove the status icons added by the automatic linker - $(divs[i]).find('.subfield_status').remove(); - if( inputs.length > 0 ){ - inputs[0].setAttribute('id',inputs[0].getAttribute('id')+new_key); - inputs[0].setAttribute('name',inputs[0].getAttribute('name')+new_key); + $(divs[i]).find(".subfield_status").remove(); + if (inputs.length > 0) { + inputs[0].setAttribute( + "id", + inputs[0].getAttribute("id") + new_key + ); + inputs[0].setAttribute( + "name", + inputs[0].getAttribute("name") + new_key + ); try { - id_input = inputs[1].getAttribute('id')+new_key; - inputs[1].setAttribute('id',id_input); - inputs[1].setAttribute('name',inputs[1].getAttribute('name')+new_key); - } catch(e) { - try{ // it s a select if it is not an input - var selects = divs[i].getElementsByTagName('select'); - id_input = selects[0].getAttribute('id')+new_key; - selects[0].setAttribute('id',id_input); - selects[0].setAttribute('name',selects[0].getAttribute('name')+new_key); + id_input = inputs[1].getAttribute("id") + new_key; + inputs[1].setAttribute("id", id_input); + inputs[1].setAttribute( + "name", + inputs[1].getAttribute("name") + new_key + ); + } catch (e) { + try { + // it s a select if it is not an input + var selects = divs[i].getElementsByTagName("select"); + id_input = selects[0].getAttribute("id") + new_key; + selects[0].setAttribute("id", id_input); + selects[0].setAttribute( + "name", + selects[0].getAttribute("name") + new_key + ); selects[0].selectedIndex = -1; - }catch(e2){ // it is a textarea if it s not a select or an input - var textareas = divs[i].getElementsByTagName('textarea'); - if( textareas.length > 0 ){ - id_input = textareas[0].getAttribute('id')+new_key; - textareas[0].setAttribute('id',id_input); - textareas[0].setAttribute('name',textareas[0].getAttribute('name')+new_key); + } catch (e2) { + // it is a textarea if it s not a select or an input + var textareas = + divs[i].getElementsByTagName("textarea"); + if (textareas.length > 0) { + id_input = + textareas[0].getAttribute("id") + new_key; + textareas[0].setAttribute("id", id_input); + textareas[0].setAttribute( + "name", + textareas[0].getAttribute("name") + new_key + ); } } } - if( $(inputs[1]).hasClass('framework_plugin') ) { - olddiv= original.getElementsByTagName('li')[i]; - oldcontrol= olddiv.getElementsByTagName('input')[1]; - AddEventHandlers( oldcontrol,inputs[1],id_input ); + if ($(inputs[1]).hasClass("framework_plugin")) { + olddiv = original.getElementsByTagName("li")[i]; + oldcontrol = olddiv.getElementsByTagName("input")[1]; + AddEventHandlers(oldcontrol, inputs[1], id_input); } } // when cloning a subfield, re set its label too. try { - var labels = divs[i].getElementsByTagName('label'); - labels[0].setAttribute('for', id_input); - } - catch(e) { + var labels = divs[i].getElementsByTagName("label"); + labels[0].setAttribute("for", id_input); + } catch (e) { // do nothing if label does not exist. } // setting its '+' and '-' buttons try { - var anchors = divs[i].getElementsByTagName('a'); + var anchors = divs[i].getElementsByTagName("a"); for (var j = 0; j < anchors.length; j++) { - if(anchors[j].getAttribute('class') == 'buttonPlus'){ - anchors[j].setAttribute('onclick',"CloneSubfield('" + divs[i].getAttribute('id') + "','" + advancedMARCEditor + "'); return false;"); - } else if (anchors[j].getAttribute('class') == 'buttonMinus') { - anchors[j].setAttribute('onclick',"UnCloneField('" + divs[i].getAttribute('id') + "'); return false;"); + if (anchors[j].getAttribute("class") == "buttonPlus") { + anchors[j].setAttribute( + "onclick", + "CloneSubfield('" + + divs[i].getAttribute("id") + + "','" + + advancedMARCEditor + + "'); return false;" + ); + } else if ( + anchors[j].getAttribute("class") == "buttonMinus" + ) { + anchors[j].setAttribute( + "onclick", + "UnCloneField('" + + divs[i].getAttribute("id") + + "'); return false;" + ); } } - } - catch(e){ + } catch (e) { // do nothig if ButtonPlus & CloneButtonPlus don t exist. } // button ... - var spans=0; + var spans = 0; try { - spans = divs[i].getElementsByTagName('a'); - } catch(e) { + spans = divs[i].getElementsByTagName("a"); + } catch (e) { // no spans } - if(spans){ + if (spans) { var buttonDot; - if(!CloneButtonPlus){ // it s impossible to have + ... (buttonDot AND buttonPlus) + if (!CloneButtonPlus) { + // it s impossible to have + ... (buttonDot AND buttonPlus) buttonDot = spans[0]; - if(buttonDot){ + if (buttonDot) { // 2 possibilities : - try{ - if( $(buttonDot).hasClass('framework_plugin') ) { - olddiv= original.getElementsByTagName('li')[i]; - oldcontrol= olddiv.getElementsByTagName('a')[0]; - AddEventHandlers(oldcontrol,buttonDot,id_input); + try { + if ($(buttonDot).hasClass("framework_plugin")) { + olddiv = original.getElementsByTagName("li")[i]; + oldcontrol = + olddiv.getElementsByTagName("a")[0]; + AddEventHandlers( + oldcontrol, + buttonDot, + id_input + ); } try { // do not copy the script section. - var script = spans[0].getElementsByTagName('script')[0]; + var script = + spans[0].getElementsByTagName("script")[0]; spans[0].removeChild(script); - } catch(e) { + } catch (e) { // do nothing if there is no script } - } catch(e){ + } catch (e) { // } } } } - - } else { // it's a indicator div - if ( divs[i].getAttribute("id") && divs[i].getAttribute('id').match(/^div_indicator/)) { - + } else { + // it's a indicator div + if ( + divs[i].getAttribute("id") && + divs[i].getAttribute("id").match(/^div_indicator/) + ) { // setting a new id for the indicator div - divs[i].setAttribute('id',divs[i].getAttribute('id')+new_key); + divs[i].setAttribute( + "id", + divs[i].getAttribute("id") + new_key + ); - inputs = divs[i].getElementsByTagName('input'); - inputs[0].setAttribute('id',inputs[0].getAttribute('id')+new_key); - inputs[1].setAttribute('id',inputs[1].getAttribute('id')+new_key); + inputs = divs[i].getElementsByTagName("input"); + inputs[0].setAttribute( + "id", + inputs[0].getAttribute("id") + new_key + ); + inputs[1].setAttribute( + "id", + inputs[1].getAttribute("id") + new_key + ); var CloneButtonPlus; try { - anchors = divs[i].getElementsByTagName('a'); - for ( j = 0; j < anchors.length; j++) { - if (anchors[j].getAttribute('class') == 'buttonPlus') { - anchors[j].setAttribute('onclick',"CloneField('" + new_id + "','" + hideMarc + "','" + advancedMARCEditor + "'); return false;"); - } else if (anchors[j].getAttribute('class') == 'buttonMinus') { - anchors[j].setAttribute('onclick',"UnCloneField('" + new_id + "'); return false;"); - } else if (anchors[j].getAttribute('class') == 'expandfield') { - anchors[j].setAttribute('data-field_id',new_id); + anchors = divs[i].getElementsByTagName("a"); + for (j = 0; j < anchors.length; j++) { + if (anchors[j].getAttribute("class") == "buttonPlus") { + anchors[j].setAttribute( + "onclick", + "CloneField('" + + new_id + + "','" + + hideMarc + + "','" + + advancedMARCEditor + + "'); return false;" + ); + } else if ( + anchors[j].getAttribute("class") == "buttonMinus" + ) { + anchors[j].setAttribute( + "onclick", + "UnCloneField('" + new_id + "'); return false;" + ); + } else if ( + anchors[j].getAttribute("class") == "expandfield" + ) { + anchors[j].setAttribute("data-field_id", new_id); } } - } - catch(e){ + } catch (e) { // do nothig CloneButtonPlus doesn't exist. } - } } } // insert this line on the page - original.parentNode.insertBefore(clone,original.nextSibling); + original.parentNode.insertBefore(clone, original.nextSibling); - $(clone).find("ul.sortable_subfield").each((i, e) => { - Sortable.create(e, { - handle: '.handle', - direction: 'vertical', - animation: 150, + $(clone) + .find("ul.sortable_subfield") + .each((i, e) => { + Sortable.create(e, { + handle: ".handle", + direction: "vertical", + animation: 150, + }); }); - }); - Select2Utils.initSelect2($(original).find('select')); - Select2Utils.initSelect2($(clone).find('select')); + Select2Utils.initSelect2($(original).find("select")); + Select2Utils.initSelect2($(clone).find("select")); } - /** * To clone a subfield * @param index * @param advancedMARCEditor '0' for false, '1' for true */ -function CloneSubfield(index, advancedMARCEditor){ +function CloneSubfield(index, advancedMARCEditor) { var original = document.getElementById(index); //original
          - Select2Utils.removeSelect2($(original).find('select')); + Select2Utils.removeSelect2($(original).find("select")); var clone = original.cloneNode(true); var new_key = CreateKey(); // set the attribute for the new 'li' subfields - var inputs = clone.getElementsByTagName('input'); - var selects = clone.getElementsByTagName('select'); - var textareas = clone.getElementsByTagName('textarea'); + var inputs = clone.getElementsByTagName("input"); + var selects = clone.getElementsByTagName("select"); + var textareas = clone.getElementsByTagName("textarea"); var linkid; var oldcontrol; // input var id_input = ""; - for(var i=0,len=inputs.length; i 1) { canUnclone = true; } @@ -473,7 +640,9 @@ function UnCloneField(index) { // unclone a subfield, check if there will remain one subfield var subfieldCode = getFieldAndSubfieldCode(index); // subfield divs of same field with id begining with original field and subfield field code - var cloneSubfields = $(original).parent().children('.subfield_line[id^="subfield'+subfieldCode+'"]'); + var cloneSubfields = $(original) + .parent() + .children('.subfield_line[id^="subfield' + subfieldCode + '"]'); if (cloneSubfields.length > 1) { canUnclone = true; } @@ -483,19 +652,19 @@ function UnCloneField(index) { original.parentNode.removeChild(original); } else { // clear inputs, but don't delete - $(":input.input_marceditor", original).each(function(){ + $(":input.input_marceditor", original).each(function () { // thanks to http://www.learningjquery.com/2007/08/clearing-form-data for // hint about clearing selects correctly var type = this.type; var tag = this.tagName.toLowerCase(); - if (type == 'text' || type == 'password' || tag == 'textarea') { + if (type == "text" || type == "password" || tag == "textarea") { this.value = ""; - } else if (type == 'checkbox' || type == 'radio') { + } else if (type == "checkbox" || type == "radio") { this.checked = false; - } else if (tag == 'select') { + } else if (tag == "select") { this.selectedIndex = -1; // required for Select2 to be able to update its control - $(this).trigger('change'); + $(this).trigger("change"); } }); $(":input.indicator", original).val(""); @@ -505,7 +674,7 @@ function UnCloneField(index) { /** * This function create a random number */ -function CreateKey(){ +function CreateKey() { return parseInt(Math.random() * 100000); } @@ -515,57 +684,60 @@ function CreateKey(){ * To clone a subfield.
          * @param original subfield div to clone */ -function CloneItemSubfield(original){ - Select2Utils.removeSelect2($(original).find('select')); +function CloneItemSubfield(original) { + Select2Utils.removeSelect2($(original).find("select")); var clone = original.cloneNode(true); var new_key = CreateKey(); // set the attribute for the new 'li' subfields - var inputs = clone.getElementsByTagName('input'); - var selects = clone.getElementsByTagName('select'); - var textareas = clone.getElementsByTagName('textarea'); + var inputs = clone.getElementsByTagName("input"); + var selects = clone.getElementsByTagName("select"); + var textareas = clone.getElementsByTagName("textarea"); // input (except hidden type) var id_input = ""; - for(var i=0,len=inputs.length; i { Sortable.create(e, { - handle: '.handle', - direction: 'vertical', + handle: ".handle", + direction: "vertical", animation: 150, }); }); } -$(document).ready(function() { - $("input.input_marceditor, input.indicator").addClass('noEnterSubmit'); - $(document).ajaxSuccess(function() { - $("input.input_marceditor, input.indicator").addClass('noEnterSubmit'); +$(document).ready(function () { + $("input.input_marceditor, input.indicator").addClass("noEnterSubmit"); + $(document).ajaxSuccess(function () { + $("input.input_marceditor, input.indicator").addClass("noEnterSubmit"); }); - if ( window.editor === undefined ) { // TODO This does not work with the advanced editor + if (window.editor === undefined) { + // TODO This does not work with the advanced editor Select2Utils.initSelect2($('.subfield_line select[data-category=""]')); // branches, itemtypes and cn_source Select2Utils.initSelect2($('.subfield_line select[data-category!=""]')); } - $("#avCreate").on("hidden.bs.modal", function(){ + $("#avCreate").on("hidden.bs.modal", function () { add_new_av.resetForm(); /* resets form state for jQuery Validate plugin */ $("#add_new_av")[0].reset(); $(".avCreate_error").hide(); }); var add_new_av = $("#add_new_av").validate({ - submitHandler: function(form) { - var category = form.category.value; - var value = form.value.value; - var description = form.description.value; + submitHandler: function (form) { + var category = form.category.value; + var value = form.value.value; + var description = form.description.value; var opac_description = form.opac_description.value; const client = APIClient.authorised_value; - client.values.create({category, value, description, opac_description}).then( - success => { - $('#avCreate').modal('hide'); + client.values + .create({ category, value, description, opac_description }) + .then( + success => { + $("#avCreate").modal("hide"); - $(current_select2).append(''); - $("#avCreate").modal("hide"); - }, - error => { - $(".avCreate_error").html(__("Something went wrong. Maybe the value already exists?")).show(); - } - ); + $(current_select2).append( + '" + ); + $("#avCreate").modal("hide"); + }, + error => { + $(".avCreate_error") + .html( + __( + "Something went wrong. Maybe the value already exists?" + ) + ) + .show(); + } + ); return false; - } + }, }); - }); diff --git a/koha-tmpl/intranet-tmpl/prog/js/cataloging_additem.js b/koha-tmpl/intranet-tmpl/prog/js/cataloging_additem.js index d4f28bbf84..c2e34ceebe 100644 --- a/koha-tmpl/intranet-tmpl/prog/js/cataloging_additem.js +++ b/koha-tmpl/intranet-tmpl/prog/js/cataloging_additem.js @@ -3,50 +3,71 @@ var browser = KOHA.browser(searchid, parseInt(biblionumber, 10)); browser.show(); -$(document).ready(function(){ - +$(document).ready(function () { // Remove the onclick event defined in browser.js, // otherwise the deletion confirmation will not work correctly - $('a[href*="biblionumber="]').off('click'); + $('a[href*="biblionumber="]').off("click"); - if( popup && op != 'cud-saveitem' ){ + if (popup && op != "cud-saveitem") { window.close(); } $("fieldset.rows input, fieldset.rows select").addClass("noEnterSubmit"); /* Inline edit/delete links */ var biblionumber = $("input[name='biblionumber']").val(); - $("tr.editable").each(function(){ - $(this).find("td:not(:first)").on('click', function(){ - var rowid = $(this).parent().attr("id"); - var num_rowid = rowid.replace("row",""); - $(".linktools").remove(); - var edit_link = $(''); - $(edit_link).text( LABEL_EDIT_ITEM ); - var delete_link = $(''); - $(delete_link).text( LABEL_DELETE_ITEM ); - var tools_node = $(''); - $(tools_node).append(edit_link); - $(tools_node).append(delete_link); - $(this).append(tools_node); - }); + $("tr.editable").each(function () { + $(this) + .find("td:not(:first)") + .on("click", function () { + var rowid = $(this).parent().attr("id"); + var num_rowid = rowid.replace("row", ""); + $(".linktools").remove(); + var edit_link = $( + '' + ); + $(edit_link).text(LABEL_EDIT_ITEM); + var delete_link = $( + '' + ); + $(delete_link).text(LABEL_DELETE_ITEM); + var tools_node = $(''); + $(tools_node).append(edit_link); + $(tools_node).append(delete_link); + $(this).append(tools_node); + }); }); - $("#addnewitem").click(function(){ - if ( confirm( MSG_CONFIRM_ADD_ITEM ) ){ - window.location.href = "/cgi-bin/koha/cataloguing/additem.pl?biblionumber=" + biblionumber; + $("#addnewitem").click(function () { + if (confirm(MSG_CONFIRM_ADD_ITEM)) { + window.location.href = + "/cgi-bin/koha/cataloguing/additem.pl?biblionumber=" + + biblionumber; } }); // Skip the first column - table_settings['columns'].unshift( { cannot_be_toggled: "1" } ); + table_settings["columns"].unshift({ cannot_be_toggled: "1" }); - var itemst = KohaTable("itemst", { - "paging": false, - "info": false, - "autoWidth": false, - "bKohaColumnsUseNames": true - }, table_settings); + var itemst = KohaTable( + "itemst", + { + paging: false, + info: false, + autoWidth: false, + bKohaColumnsUseNames: true, + }, + table_settings + ); var multiCopyControl = $("#add_multiple_copies_span"); var addMultipleBlock = $("#addmultiple"); @@ -55,15 +76,15 @@ $(document).ready(function(){ var saveTemplateBlock = $("#savetemplate"); multiCopyControl.hide(); - $("#add_multiple_copies").on("click",function(e){ + $("#add_multiple_copies").on("click", function (e) { e.preventDefault; addMultipleBlock.toggle(); saveTemplateBlock.toggle(); addSingleBlock.toggle(); multiCopyControl.toggle(); - $('body,html').animate({ scrollTop: $('body').height() }, 100); + $("body,html").animate({ scrollTop: $("body").height() }, 100); }); - $("#cancel_add_multiple").on("click",function(e){ + $("#cancel_add_multiple").on("click", function (e) { e.preventDefault(); addMultipleBlock.toggle(); saveTemplateBlock.toggle(); @@ -72,37 +93,37 @@ $(document).ready(function(){ }); saveAsTemplateControl.hide(); - $("#save_as_template").on("click",function(e){ + $("#save_as_template").on("click", function (e) { e.preventDefault; saveTemplateBlock.toggle(); saveAsTemplateControl.toggle(); - $('#template_name').focus(); + $("#template_name").focus(); }); - $("#cancel_save_as_template").on("click",function(e){ + $("#cancel_save_as_template").on("click", function (e) { e.preventDefault(); saveTemplateBlock.toggle(); saveAsTemplateControl.toggle(); }); - $("#template_id").on("change", function() { + $("#template_id").on("change", function () { let option = $(this).find(":selected"); - if ( option.data("editor") ) { + if (option.data("editor")) { $("#delete_template_submit").removeAttr("disabled"); } else { $("#delete_template_submit").attr("disabled", "disabled"); } - if ( option.val() != 0 ) { + if (option.val() != 0) { $("#load_template_submit").removeAttr("disabled"); } else { $("#load_template_submit").attr("disabled", "disabled"); } }); $("#template_id").change(); // Trigger to enable delete button if patron's template is in use - $("#replace_template_id").on("change", function() { + $("#replace_template_id").on("change", function () { let selected = $(this).find(":selected"); - if ( selected.val() > 0 ) { + if (selected.val() > 0) { $("#template_name_block").hide(); $("#template_is_shared").prop("checked", selected.data("shared")); } else { @@ -112,49 +133,51 @@ $(document).ready(function(){ }); // Add new item to an item group - if ( has_item_groups ) { - $('#item-group-add-or-create-form-description-block').hide(); - $('#item-group-add-or-create-form-no-add').attr('selected', 'selected' ); + if (has_item_groups) { + $("#item-group-add-or-create-form-description-block").hide(); + $("#item-group-add-or-create-form-no-add").attr("selected", "selected"); - $('#item-group-add-or-create-form-select').on('change', function(){ - if ( $(this).val() == 'create' ) { - $('#item-group-add-or-create-form-description') - .addClass('required') - .attr( 'required', 'required' ); - $('#item-group-add-or-create-form-description-block').show(); + $("#item-group-add-or-create-form-select").on("change", function () { + if ($(this).val() == "create") { + $("#item-group-add-or-create-form-description") + .addClass("required") + .attr("required", "required"); + $("#item-group-add-or-create-form-description-block").show(); } else { - $('#item-group-add-or-create-form-description') - .removeClass('required') - .removeAttr('required'); - $('#item-group-add-or-create-form-description-block').hide(); + $("#item-group-add-or-create-form-description") + .removeClass("required") + .removeAttr("required"); + $("#item-group-add-or-create-form-description-block").hide(); } }); } - - $(document).on('click', '.delete', function(e) { + $(document).on("click", ".delete", function (e) { e.preventDefault(); if (confirmDelete(MSG_CONFIRM_DELETE_ITEM)) { return $("#" + $(this).data("item") + "-delete-item-form").submit(); } - }) ; + }); /* On page load, check for location.hash in the page URL */ /* If present the location hash will be used to scroll to the relevant anchor */ var hash = location.hash; - var hashPieces = hash.split('?'); - if( hashPieces[0] !== "" ){ - $( hashPieces[0] )[0].scrollIntoView(); + var hashPieces = hash.split("?"); + if (hashPieces[0] !== "") { + $(hashPieces[0])[0].scrollIntoView(); } - $("#newitem_jump").on("click", function(e){ + $("#newitem_jump").on("click", function (e) { e.preventDefault(); document.getElementById("additema").scrollIntoView(); }); }); function CheckTemplateForm(f) { - if ( $('#replace_template_id').val() == "0" && $('#template_name').val() == "" ) { + if ( + $("#replace_template_id").val() == "0" && + $("#template_name").val() == "" + ) { alert(__("Template name is required.")); return false; } else { @@ -166,32 +189,35 @@ function Check(f) { var total_mandatory = CheckMandatorySubfields(f); var total_important = CheckImportantSubfields(f); var alertString2; - if (total_mandatory==0) { + if (total_mandatory == 0) { // Explanation about this line: // In case of limited edition permission, we have to prevent user from modifying some fields. // But there is no such thing as readonly attribute for select elements. // So we use disabled instead. But disabled prevent values from being passed through the form at submit. // So we "un-disable" the elements just before submitting. // That's a bit clumsy, and if someone comes up with a better solution, feel free to improve that. - $("select.input_marceditor").prop('disabled', false); + $("select.input_marceditor").prop("disabled", false); } else { alertString2 = MSG_FORM_NOT_SUBMITTED; - alertString2 += "\n------------------------------------------------------------------------------------\n"; - alertString2 += "\n- " + MSG_MANDATORY_FIELDS_EMPTY.format(total_mandatory); + alertString2 += + "\n------------------------------------------------------------------------------------\n"; + alertString2 += + "\n- " + MSG_MANDATORY_FIELDS_EMPTY.format(total_mandatory); } - if(total_important > 0){ - if( !alertString2 ){ + if (total_important > 0) { + if (!alertString2) { alertString2 = ""; } - alertString2 += "\n\n " + MSG_IMPORTANT_FIELDS_EMPTY.format(total_important); + alertString2 += + "\n\n " + MSG_IMPORTANT_FIELDS_EMPTY.format(total_important); alertString2 += "\n\n " + MSG_CONFIRM_SAVE; } - if(alertString2){ - if(total_mandatory){ - alert(alertString2); - }else{ + if (alertString2) { + if (total_mandatory) { + alert(alertString2); + } else { var a = confirm(alertString2); - if( a ){ + if (a) { return true; } } @@ -201,18 +227,21 @@ function Check(f) { } function CheckMultipleAdd(f) { - if (!f || isNaN(f) || !parseInt(f) == f || f <= 0) { - alert( MSG_ENTER_NUM_ITEMS ); + alert(MSG_ENTER_NUM_ITEMS); return false; } // Add a soft-limit of 99 with a reminder about potential data entry error - if (f>99) { - return confirm( MSG_ADD_MULTIPLE_ITEMS.format(f)); + if (f > 99) { + return confirm(MSG_ADD_MULTIPLE_ITEMS.format(f)); } } -function Dopop(link,i) { - var defaultvalue=document.forms[0].field_value[i].value; - var newin=window.open(link+"&result=" + defaultvalue,"valuebuilder",'width=500,height=400,toolbar=false,scrollbars=yes'); +function Dopop(link, i) { + var defaultvalue = document.forms[0].field_value[i].value; + var newin = window.open( + link + "&result=" + defaultvalue, + "valuebuilder", + "width=500,height=400,toolbar=false,scrollbars=yes" + ); } diff --git a/koha-tmpl/intranet-tmpl/prog/js/charts.js b/koha-tmpl/intranet-tmpl/prog/js/charts.js index 4a3e8005db..99463d0084 100644 --- a/koha-tmpl/intranet-tmpl/prog/js/charts.js +++ b/koha-tmpl/intranet-tmpl/prog/js/charts.js @@ -1,21 +1,27 @@ -function create_chart(headers, results, x_element, y_elements, y_groups, options) { - +function create_chart( + headers, + results, + x_element, + y_elements, + y_groups, + options +) { var type = options.type; var horizontal = options.horizontal; var lines = options.lines; var data; var axis; - if (type != 'pie') { + if (type != "pie") { var columns = build_columns(headers, results, x_element, y_elements); var groups = build_group(y_elements, y_groups); var x_values = build_xvalues(headers, results, x_element); axis = { x: { - type: 'category', - categories: x_values - } + type: "category", + categories: x_values, + }, }; data = { @@ -23,21 +29,18 @@ function create_chart(headers, results, x_element, y_elements, y_groups, options groups: groups, type: type, }; - - } - else { + } else { var columns = build_pie_columns(headers, results, x_element); data = { columns: columns, type: type, }; - } - if (type == 'bar') { + if (type == "bar") { var types = {}; - $.each(lines, function(index, value) { - types[value] = 'line'; + $.each(lines, function (index, value) { + types[value] = "line"; }); data.types = types; @@ -47,7 +50,7 @@ function create_chart(headers, results, x_element, y_elements, y_groups, options } var chart = c3.generate({ - bindto: '#chart', + bindto: "#chart", data: data, axis: axis, }); @@ -60,20 +63,20 @@ function build_pie_columns(headers, results, x_element) { var x_index; //Get x_element index. - $.each(headers, function(index, value) { + $.each(headers, function (index, value) { if (value.cell == x_element) { x_index = index; } }); - $.each(results, function(index, value) { + $.each(results, function (index, value) { var cells = value.cells; - $.each( cells, function(i, value) { + $.each(cells, function (i, value) { if (i == x_index) { columns[index] = [value.cell]; } }); - $.each( cells, function(i, value) { + $.each(cells, function (i, value) { if (i != x_index) { columns[index].push(value.cell); } @@ -88,15 +91,15 @@ function build_xvalues(headers, results, x_element) { x_values = []; //Get x_element index. - $.each(headers, function(index, value) { + $.each(headers, function (index, value) { if (value.cell == x_element) { h_index = index; } }); - $.each( results, function (i, value) { + $.each(results, function (i, value) { var cells = value.cells; - $.each( cells, function(index, value) { + $.each(cells, function (index, value) { if (index == h_index) { x_values.push(value.cell); } @@ -104,14 +107,13 @@ function build_xvalues(headers, results, x_element) { }); return x_values; - } function build_group(y_elements, y_groups) { var groups_hash = {}; var groups = []; - $.each(y_groups, function(index, value) { + $.each(y_groups, function (index, value) { var related_y = y_elements.shift(); if (!$.isArray(groups_hash[value])) { groups_hash[value] = []; @@ -119,7 +121,7 @@ function build_group(y_elements, y_groups) { groups_hash[value].push(related_y); }); - $.each(groups_hash, function(key, value) { + $.each(groups_hash, function (key, value) { if (value.length !== 0) { groups.push(value); } @@ -134,20 +136,20 @@ function build_columns(headers, results, x_element, y_elements) { var y_values = {}; // Keep order of headers using array index. - $.each( headers, function(index, value) { + $.each(headers, function (index, value) { if (value.cell == x_element) { x_index = index; } - header_index.push(value.cell) + header_index.push(value.cell); }); - $.each( y_elements, function(index, element) { + $.each(y_elements, function (index, element) { y_values[element] = [element]; }); - $.each( results, function (i, value) { + $.each(results, function (i, value) { var cells = value.cells; - $.each( cells, function(index, value) { + $.each(cells, function (index, value) { if (index != x_index) { y_values[header_index[index]].push(value.cell); } @@ -155,7 +157,7 @@ function build_columns(headers, results, x_element, y_elements) { }); var columns = []; - $.each( y_values, function(key, value) { + $.each(y_values, function (key, value) { columns.push(value); }); diff --git a/koha-tmpl/intranet-tmpl/prog/js/checkout_renewals_modal.js b/koha-tmpl/intranet-tmpl/prog/js/checkout_renewals_modal.js index fd8441d741..46418afd03 100644 --- a/koha-tmpl/intranet-tmpl/prog/js/checkout_renewals_modal.js +++ b/koha-tmpl/intranet-tmpl/prog/js/checkout_renewals_modal.js @@ -1,29 +1,59 @@ -$(document).ready(function(){ +$(document).ready(function () { // Display the modal containing checkout renewals details - $('.checkout_renewals_view').on('click', function(e) { + $(".checkout_renewals_view").on("click", function (e) { e.preventDefault(); - $('#checkoutRenewals #incomplete').html('').hide(); - $('#checkoutRenewals #results').html('').hide(); - $('#checkoutRenewals').modal("show"); - var renewals = $(this).data('renewals'); - var checkoutID = $(this).data('issueid'); - $('#checkoutRenewals #retrieving').show(); - $.get({ 'url': '/api/v1/checkouts/'+checkoutID+'/renewals', 'headers': { 'x-koha-embed': 'renewer' } }, function(data) { - if (data.length < renewals) { - $('#checkoutRenewals #incomplete').append(__("Note: %s out of %s renewals have been logged").format(data.length, renewals)).show(); + $("#checkoutRenewals #incomplete").html("").hide(); + $("#checkoutRenewals #results").html("").hide(); + $("#checkoutRenewals").modal("show"); + var renewals = $(this).data("renewals"); + var checkoutID = $(this).data("issueid"); + $("#checkoutRenewals #retrieving").show(); + $.get( + { + url: "/api/v1/checkouts/" + checkoutID + "/renewals", + headers: { "x-koha-embed": "renewer" }, + }, + function (data) { + if (data.length < renewals) { + $("#checkoutRenewals #incomplete") + .append( + __( + "Note: %s out of %s renewals have been logged" + ).format(data.length, renewals) + ) + .show(); + } + var items = data.map(function (item) { + return createLi(item); + }); + $("#checkoutRenewals #retrieving").hide(); + $("#checkoutRenewals #results").append(items).show(); } - var items = data.map(function(item) { - return createLi(item); - }); - $('#checkoutRenewals #retrieving').hide(); - $('#checkoutRenewals #results').append(items).show(); - }); + ); }); function createLi(renewal) { - if(renewal.renewal_type === "Manual"){ - return '
        • ' + $datetime(renewal.timestamp) + ' ' + __("Renewed by") + ' ' + $patron_to_html(renewal.renewer) + " " + __("manually") + '
        • '; + if (renewal.renewal_type === "Manual") { + return ( + '
        • ' + + $datetime(renewal.timestamp) + + " " + + __("Renewed by") + + ' ' + + $patron_to_html(renewal.renewer) + + " " + + __("manually") + + "
        • " + ); } else { - return '
        • ' + $datetime(renewal.timestamp) + ' ' + __("Renewal type:") + ' ' + __("Automatic") + '
        • '; + return ( + '
        • ' + + $datetime(renewal.timestamp) + + " " + + __("Renewal type:") + + ' ' + + __("Automatic") + + "
        • " + ); } } }); diff --git a/koha-tmpl/intranet-tmpl/prog/js/checkouts.js b/koha-tmpl/intranet-tmpl/prog/js/checkouts.js index 394d319cbb..3e25f13ae5 100644 --- a/koha-tmpl/intranet-tmpl/prog/js/checkouts.js +++ b/koha-tmpl/intranet-tmpl/prog/js/checkouts.js @@ -1,37 +1,41 @@ /* global __ */ function CheckRenewCheckinBoxes() { - $('#RenewChecked').prop('disabled', !$('.renew:checked').length ); - $('#CheckinChecked').prop('disabled', !$('.checkin:checked').length ); + $("#RenewChecked").prop("disabled", !$(".renew:checked").length); + $("#CheckinChecked").prop("disabled", !$(".checkin:checked").length); } function RefreshIssuesTable() { - var table = $('#issues-table').DataTable(); - var renewchecked = $('input[name=renew]:checked').map(function(){ - return this.value; - }).get(); - var checkinchecked = $('input[name=checkin]:checked').map(function(){ - return this.value; - }).get(); - table.ajax.reload( function() { + var table = $("#issues-table").DataTable(); + var renewchecked = $("input[name=renew]:checked") + .map(function () { + return this.value; + }) + .get(); + var checkinchecked = $("input[name=checkin]:checked") + .map(function () { + return this.value; + }) + .get(); + table.ajax.reload(function () { var checkout_count = table.page.info().recordsTotal; - $('.checkout_count').text(checkout_count); - renewchecked.forEach( function(item) { - $('.renew[value="'+item+'"]').prop('checked' , true ); + $(".checkout_count").text(checkout_count); + renewchecked.forEach(function (item) { + $('.renew[value="' + item + '"]').prop("checked", true); }); - checkinchecked.forEach( function(item) { - $('.checkin[value="'+item+'"]').prop('checked' , true ); + checkinchecked.forEach(function (item) { + $('.checkin[value="' + item + '"]').prop("checked", true); }); CheckRenewCheckinBoxes(); }); } function LoadIssuesTable() { - $('#issues-table-loading-message').hide(); - $('#issues-table').show(); - $('#issues-table-actions').show(); - var msg_loading = __('Loading... you may continue scanning.'); + $("#issues-table-loading-message").hide(); + $("#issues-table").show(); + $("#issues-table-actions").show(); + var msg_loading = __("Loading... you may continue scanning."); if (!AllowCirculate) { table_settings_issues_table.columns.find( c => c.columnname == "renew" @@ -50,429 +54,652 @@ function LoadIssuesTable() { c => c.columnname == "export" ).is_hidden = 1; } - issuesTable = KohaTable("issues-table", { - "language": { - "emptyTable": msg_loading, - "processing": msg_loading, - }, - "autoWidth": false, - "dom": '<"table_controls"B>rt', - "columns": [ - { - "data": function( oObj ) { - return oObj.sort_order; - } + issuesTable = KohaTable( + "issues-table", + { + language: { + emptyTable: msg_loading, + processing: msg_loading, }, - { - "data": function( oObj ) { - if ( oObj.issued_today ) { - return "" + __("Today's checkouts") + ""; + autoWidth: false, + dom: '<"table_controls"B>rt', + columns: [ + { + data: function (oObj) { + return oObj.sort_order; + }, + }, + { + data: function (oObj) { + if (oObj.issued_today) { + return ( + "" + + __("Today's checkouts") + + "" + ); + } else { + return ( + "" + + __("Previous checkouts") + + "" + ); + } + }, + }, + { + data: "date_due", + visible: false, + }, + { + orderData: 2, // Sort on hidden unformatted date due column + data: function (oObj) { + let date_due_formatted = $datetime(oObj.date_due, { + as_due_date: true, + no_tz_adjust: true, + }); + var due = oObj.date_due_overdue + ? "" + + date_due_formatted + + "" + : oObj.date_due_today + ? "" + + date_due_formatted + + "" + : date_due_formatted; + + due = + "" + + due + + ""; + + if (oObj.lost && oObj.claims_returned) { + due += + "" + + oObj.lost.escapeHtml() + + ""; + } else if (oObj.lost) { + due += + "" + + oObj.lost.escapeHtml() + + ""; + } + + if (oObj.damaged) { + due += + "" + + oObj.damaged.escapeHtml() + + ""; + } + + var patron_note = + " "; + due += "
          " + patron_note; + + return due; + }, + }, + { + data: function (oObj) { + let title = + "" + + (oObj.title ? oObj.title.escapeHtml() : ""); + var ymd = flatpickr.formatDate(new Date(), "Y-m-d"); + + $.each(oObj.subtitle, function (index, value) { + title += " " + value.escapeHtml(); + }); + + title += " " + oObj.part_number + " " + oObj.part_name; + + if (oObj.enumchron) { + title += + " (" + + oObj.enumchron.escapeHtml() + + ")"; + } + + title += ""; + + if (oObj.author) { + title += + " " + + __("by _AUTHOR_").replace( + "_AUTHOR_", + " " + oObj.author.escapeHtml() + ); + } + + if (oObj.itemnotes) { + var span_class = "text-muted"; + if ( + flatpickr.formatDate( + new Date(oObj.issuedate), + "Y-m-d" + ) == ymd + ) { + span_class = "circ-hlt"; + } + title += + " - " + + oObj.itemnotes.escapeHtml() + + ""; + } + + if (oObj.itemnotes_nonpublic) { + var span_class = "text-danger"; + if ( + flatpickr.formatDate( + new Date(oObj.issuedate), + "Y-m-d" + ) == ymd + ) { + span_class = "circ-hlt"; + } + title += + " - " + + oObj.itemnotes_nonpublic.escapeHtml() + + ""; + } + + var onsite_checkout = ""; + if (oObj.onsite_checkout == 1) { + onsite_checkout += + " (" + + __("On-site checkout") + + ")"; + } + + if (oObj.recalled == 1) { + title += + " - " + + __( + "This item has been recalled and the due date updated" + ) + + "."; + } + + title += + " " + + "" + + (oObj.barcode ? oObj.barcode.escapeHtml() : "") + + "" + + onsite_checkout; + + return title; + }, + type: "anti-the", + }, + { + data: function (oObj) { + return oObj.recordtype_description.escapeHtml(); + }, + }, + { + data: function (oObj) { + return oObj.itemtype_description.escapeHtml(); + }, + }, + { + data: function (oObj) { + return oObj.collection + ? oObj.collection.escapeHtml() + : ""; + }, + }, + { + data: function (oObj) { + return oObj.location ? oObj.location.escapeHtml() : ""; + }, + }, + { + data: function (oObj) { + return oObj.homebranch + ? oObj.homebranch.escapeHtml() + : ""; + }, + }, + { + data: "issuedate", + visible: false, + }, + { + orderData: 10, // Sort on hidden unformatted issuedate column + data: function (oObj) { + return $datetime(oObj.issuedate, { + no_tz_adjust: true, + }); + }, + }, + { + data: function (oObj) { + return oObj.branchname + ? oObj.branchname.escapeHtml() + : ""; + }, + }, + { + data: function (oObj) { + return oObj.itemcallnumber + ? oObj.itemcallnumber.escapeHtml() + : ""; + }, + }, + { + data: function (oObj) { + return oObj.copynumber + ? oObj.copynumber.escapeHtml() + : ""; + }, + }, + { + data: function (oObj) { + if (!oObj.charge) oObj.charge = 0; + return ( + '' + + parseFloat(oObj.charge).format_price() + + "" + ); + }, + className: "nowrap", + }, + { + data: function (oObj) { + if (!oObj.fine) oObj.fine = 0; + return ( + '' + + parseFloat(oObj.fine).format_price() + + "" + ); + }, + className: "nowrap", + }, + { + data: function (oObj) { + if (!oObj.price) oObj.price = 0; + return ( + '' + + parseFloat(oObj.price).format_price() + + "" + ); + }, + className: "nowrap", + }, + { + orderable: false, + data: function (oObj) { + var content = ""; + var msg = ""; + var span_style = ""; + var span_class = ""; + + if (oObj.can_renew) { + // Do nothing + } else if (oObj.can_renew_error == "recalled") { + msg += + "" + + "" + + __("Recalled") + + "" + + ""; + + span_style = "display: none"; + span_class = "renewals-allowed-recalled"; + } else if (oObj.can_renew_error == "booked") { + msg += + "" + + "" + + __("Booked") + + "" + + ""; + span_style = "display: none"; + span_class = "renewals-allowed-booked"; + } else if (oObj.can_renew_error == "on_reserve") { + msg += + "" + + "" + + __("On hold") + + "" + + ""; + + span_style = "display: none"; + span_class = "renewals-allowed-on_reserve"; + } else if (oObj.can_renew_error == "too_many") { + msg += + "" + + __("Not renewable") + + ""; + + span_style = "display: none"; + span_class = "renewals-allowed"; + } else if (oObj.can_renew_error == "too_unseen") { + msg += + "" + + __("Must be renewed at the library") + + ""; + span_class = "renewals-allowed"; + } else if (oObj.can_renew_error == "restriction") { + msg += + "" + + __("Not allowed: patron restricted") + + ""; + + span_style = "display: none"; + span_class = "renewals-allowed"; + } else if (oObj.can_renew_error == "overdue") { + msg += + "" + + __("Not allowed: overdue") + + ""; + + span_style = "display: none"; + span_class = "renewals-allowed"; + } else if (oObj.can_renew_error == "too_soon") { + msg += + "" + + __("No renewal before %s").format( + oObj.can_renew_date + ) + + ""; + + span_style = "display: none"; + span_class = "renewals-allowed"; + } else if (oObj.can_renew_error == "auto_too_late") { + msg += + "" + + __( + "Can no longer be auto-renewed - number of checkout days exceeded" + ) + + ""; + + span_style = "display: none"; + span_class = "renewals-allowed"; + } else if ( + oObj.can_renew_error == "auto_too_much_oweing" + ) { + msg += + "" + + __( + "Automatic renewal failed, patron has unpaid fines" + ) + + ""; + + span_style = "display: none"; + span_class = "renewals-allowed"; + } else if ( + oObj.can_renew_error == "auto_account_expired" + ) { + msg += + "" + + __( + "Automatic renewal failed, account expired" + ) + + ""; + + span_style = "display: none"; + span_class = "renewals-allowed"; + } else if (oObj.can_renew_error == "onsite_checkout") { + // Don't display something if it's an onsite checkout + } else if ( + oObj.can_renew_error == "item_denied_renewal" + ) { + content += + "" + + __("Renewal denied by syspref") + + ""; + + span_style = "display: none"; + span_class = "renewals-allowed"; + } else { + msg += + "" + + oObj.can_renew_error + + ""; + + span_style = "display: none"; + span_class = "renewals-allowed"; + } + + var can_force_renew = + oObj.onsite_checkout == 0 && + (oObj.can_renew_error != "on_reserve" || + (oObj.can_renew_error == "on_reserve" && + AllowRenewalOnHoldOverride)) + ? true + : false; + var can_renew = + oObj.renewals_remaining > 0 && + (!oObj.can_renew_error || + oObj.can_renew_error == "too_unseen"); + content += ""; + if (can_renew || can_force_renew) { + content += + "" + + oObj.renewals_count + + ""; + content += + "" + + "" + + ""; + } + content += msg; + if (can_renew || can_force_renew) { + content += "("; + content += __x( + "{renewals_left} of {renewals_allowed} renewals remaining", + { + renewals_left: oObj.renewals_remaining, + renewals_allowed: oObj.renewals_allowed, + } + ); + if (UnseenRenewals && oObj.unseen_allowed) { + content += __x( + " and {renewals_left} of {renewals_allowed} unseen renewals remaining", + { + renewals_left: oObj.unseen_remaining, + renewals_allowed: oObj.unseen_allowed, + } + ); + } + content += ")"; + } + if (oObj.auto_renew) { + content += "("; + content += __("Scheduled for automatic renewal"); + content += ")"; + } + + return content; + }, + }, + { + orderable: false, + data: function (oObj) { + if (oObj.can_renew_error == "recalled") { + return ( + "" + + __("Recalled") + + "" + ); + } else if (oObj.can_renew_error == "on_reserve") { + return ( + "" + + __("On hold") + + "" + ); + } else if (oObj.materials) { + return __("Confirm (%s)").format( + oObj.materials.escapeHtml() + ); + } else { + return ( + "" + ); + } + }, + }, + { + orderable: false, + data: function (oObj) { + let content = ""; + + if (oObj.return_claim_id) { + content = + '' + + oObj.return_claim_created_on_formatted + + ""; + } else if (ClaimReturnedLostValue) { + content = + ' ' + + __("Claim returned") + + ""; + } else { + content = + ' ' + + __("Claim returned") + + ""; + } + return content; + }, + }, + { + orderable: false, + data: function (oObj) { + var s = + ""; + + s += + ""; + return s; + }, + }, + ], + footerCallback: function (nRow, aaData, iStart, iEnd, aiDisplay) { + var total_charge = 0; + var total_fine = 0; + var total_price = 0; + for (var i = 0; i < aaData.length; i++) { + total_charge += aaData[i]["charge"] * 1; + total_fine += aaData[i]["fine"] * 1; + total_price += aaData[i]["price"] * 1; + } + $("#totaldue").html(total_charge.format_price()); + $("#totalfine").html(total_fine.format_price()); + $("#totalprice").html(total_price.format_price()); + }, + paging: false, + processing: true, + serverSide: false, + ajax: { + url: "/cgi-bin/koha/svc/checkouts?borrowernumber=%s".format( + borrowernumber + ), + }, + rowGroup: { + dataSrc: "issued_today", + startRender: function (rows, group) { + if (group) { + return __("Today's checkouts"); } else { - return "" + __("Previous checkouts") + ""; + return __("Previous checkouts"); } - } + }, }, - { - "data": "date_due", - "visible": false, - }, - { - "orderData": 2, // Sort on hidden unformatted date due column - "data": function( oObj ) { - let date_due_formatted = $datetime(oObj.date_due, { as_due_date: true, no_tz_adjust: true }); - var due = oObj.date_due_overdue - ? "" + date_due_formatted + "" - : oObj.date_due_today - ? "" + date_due_formatted + "" - : date_due_formatted; + initComplete: function (oSettings, json) { + CheckRenewCheckinBoxes(); - due = "" + due + ""; - - if ( oObj.lost && oObj.claims_returned ) { - due += "" + oObj.lost.escapeHtml() + ""; - } else if ( oObj.lost ) { - due += "" + oObj.lost.escapeHtml() + ""; - } - - if ( oObj.damaged ) { - due += "" + oObj.damaged.escapeHtml() + ""; - } - - var patron_note = " "; - due +="
          " + patron_note; - - return due; - } - }, - { - "data": function ( oObj ) { - let title = "" - + (oObj.title ? oObj.title.escapeHtml() : '' ); - var ymd = flatpickr.formatDate(new Date(), "Y-m-d"); - - $.each(oObj.subtitle, function( index, value ) { - title += " " + value.escapeHtml(); + // Build a summary of checkouts grouped by itemtype + var checkoutsByItype = json.aaData.reduce(function (obj, row) { + obj[row.type_for_stat] = (obj[row.type_for_stat] || 0) + 1; + return obj; + }, {}); + var ul = $("
          [% END # /IF ENABLE_OPAC_PAYMENTS && DISPLAY_PAYMENT_BLOCK %] diff --git a/koha-tmpl/opac-tmpl/bootstrap/en/includes/accounts.inc b/koha-tmpl/opac-tmpl/bootstrap/en/includes/accounts.inc index dfd026a240..b3e397ba20 100644 --- a/koha-tmpl/opac-tmpl/bootstrap/en/includes/accounts.inc +++ b/koha-tmpl/opac-tmpl/bootstrap/en/includes/accounts.inc @@ -1,63 +1,104 @@ [%- BLOCK account_type_description -%] - [%- IF account.credit_type_code -%] - [%- PROCESS credit_type_description credit_type_code = account.credit_type_code -%] - [%- ELSIF account.debit_type_code -%] - [%- PROCESS debit_type_description debit_type_code = account.debit_type_code -%] - [%- END -%] - [%- PROCESS account_status_description account=account -%] + [%- IF account.credit_type_code -%] + [%- PROCESS credit_type_description credit_type_code = account.credit_type_code -%] + [%- ELSIF account.debit_type_code -%] + [%- PROCESS debit_type_description debit_type_code = account.debit_type_code -%] + [%- END -%] + [%- PROCESS account_status_description account=account -%] [%- END -%] [%- BLOCK debit_type_description -%] [%- SWITCH debit_type_code -%] - [%- CASE 'ACCOUNT' -%]Account creation fee - [%- CASE 'ACCOUNT_RENEW' -%]Account renewal fee - [%- CASE 'ARTICLE_REQUEST' -%]Article request fee - [%- CASE 'LOST' -%]Lost item - [%- CASE 'MANUAL' -%]Manual fee - [%- CASE 'NEW_CARD' -%]New card - [%- CASE 'OVERDUE' -%]Fine - [%- CASE 'PROCESSING' -%]Lost item processing fee - [%- CASE 'RENT' -%]Rental fee - [%- CASE 'RENT_DAILY' -%]Daily rental fee - [%- CASE 'RENT_RENEW' -%]Renewal of rental item - [%- CASE 'RENT_DAILY_RENEW' -%]Renewal of daily rental item - [%- CASE 'RESERVE' -%]Hold fee - [%- CASE 'RESERVE_EXPIRED' -%]Hold waiting too long - [%- CASE 'PAYOUT' -%]Payment from library to patron - [%- CASE 'VOID' -%]Credit has been voided - [%- CASE -%][% debit_type.description | html %] + + [%- CASE 'ACCOUNT' -%] + Account creation fee + [%- CASE 'ACCOUNT_RENEW' -%] + Account renewal fee + [%- CASE 'ARTICLE_REQUEST' -%] + Article request fee + [%- CASE 'LOST' -%] + Lost item + [%- CASE 'MANUAL' -%] + Manual fee + [%- CASE 'NEW_CARD' -%] + New card + [%- CASE 'OVERDUE' -%] + Fine + [%- CASE 'PROCESSING' -%] + Lost item processing fee + [%- CASE 'RENT' -%] + Rental fee + [%- CASE 'RENT_DAILY' -%] + Daily rental fee + [%- CASE 'RENT_RENEW' -%] + Renewal of rental item + [%- CASE 'RENT_DAILY_RENEW' -%] + Renewal of daily rental item + [%- CASE 'RESERVE' -%] + Hold fee + [%- CASE 'RESERVE_EXPIRED' -%] + Hold waiting too long + [%- CASE 'PAYOUT' -%] + Payment from library to patron + [%- CASE 'VOID' -%] + Credit has been voided + [%- CASE -%] + [% debit_type.description | html %] [%- END -%] [%- END -%] [%- BLOCK credit_type_description -%] [%- SWITCH credit_type_code -%] - [%- CASE 'CANCELLATION' -%]Cancelled charge - [%- CASE 'CREDIT' -%]Credit - [%- CASE 'DISCOUNT' -%]Discount - [%- CASE 'FORGIVEN' -%]Forgiven - [%- CASE 'LOST_FOUND' -%]Lost item fee refund - [%- CASE 'OVERPAYMENT' -%]Overpayment refund - [%- CASE 'PAYMENT' -%]Payment - [%- CASE 'PROCESSING_FOUND' -%]Lost item processing fee refund - [%- CASE 'PURCHASE' -%]Purchase - [%- CASE 'REFUND' -%]Refund - [%- CASE 'WRITEOFF' -%]Writeoff - [%- CASE -%][% credit_type.description | html %] + + [%- CASE 'CANCELLATION' -%] + Cancelled charge + [%- CASE 'CREDIT' -%] + Credit + [%- CASE 'DISCOUNT' -%] + Discount + [%- CASE 'FORGIVEN' -%] + Forgiven + [%- CASE 'LOST_FOUND' -%] + Lost item fee refund + [%- CASE 'OVERPAYMENT' -%] + Overpayment refund + [%- CASE 'PAYMENT' -%] + Payment + [%- CASE 'PROCESSING_FOUND' -%] + Lost item processing fee refund + [%- CASE 'PURCHASE' -%] + Purchase + [%- CASE 'REFUND' -%] + Refund + [%- CASE 'WRITEOFF' -%] + Writeoff + [%- CASE -%] + [% credit_type.description | html %] [%- END -%] [%- END -%] [%- BLOCK account_status_description -%] [%- SWITCH account.status -%] - [%- CASE 'UNRETURNED' -%] (Accruing) - [%- CASE 'RETURNED' -%] (Returned) - [%- CASE 'REPLACED' -%] (Replaced) - [%- CASE 'REFUNDED' -%] (Refunded) - [%- CASE 'FORGIVEN' -%] (Forgiven) - [%- CASE 'VOID' -%] (Voided) - [%- CASE 'LOST' -%] (Lost) - [%- CASE 'CANCELLED' -%] (Cancelled) - [%- CASE -%] + + [%- CASE 'UNRETURNED' -%] + (Accruing) + [%- CASE 'RETURNED' -%] + (Returned) + [%- CASE 'REPLACED' -%] + (Replaced) + [%- CASE 'REFUNDED' -%] + (Refunded) + [%- CASE 'FORGIVEN' -%] + (Forgiven) + [%- CASE 'VOID' -%] + (Voided) + [%- CASE 'LOST' -%] + (Lost) + [%- CASE 'CANCELLED' -%] + (Cancelled) + [%- CASE -%] + [%- END -%] [%- END -%] diff --git a/koha-tmpl/opac-tmpl/bootstrap/en/includes/authorities-search-results.inc b/koha-tmpl/opac-tmpl/bootstrap/en/includes/authorities-search-results.inc index 1dbe3a603d..73ae2bf5b3 100644 --- a/koha-tmpl/opac-tmpl/bootstrap/en/includes/authorities-search-results.inc +++ b/koha-tmpl/opac-tmpl/bootstrap/en/includes/authorities-search-results.inc @@ -1,49 +1,56 @@ [% BLOCK showreference %] -[%# Parameters: %] -[%# heading: the heading itself %] -[%# linkType: currently 'seefrom' or 'seealso', controls the label for the entry %] -[%# type: %] -[%# authid: if it is a linked authority, its authid %] + [%# Parameters: %] + [%# heading: the heading itself %] + [%# linkType: currently 'seefrom' or 'seealso', controls the label for the entry %] + [%# type: %] + [%# authid: if it is a linked authority, its authid %] [% SET authidurl = '/cgi-bin/koha/opac-authoritiesdetail.pl?authid=' %] [% SET searchurl = '/cgi-bin/koha/opac-authorities-home.pl?op=do_search&type=opac&operator=contains&marclist=mainentry&and_or=and&orderby=HeadingAsc&value=' %] [% IF marcflavour == 'UNIMARC' %] [% SWITCH type %] - [% CASE 'broader' %] - BT: [% heading | html %] - [% CASE 'narrower' %] - NT: [% heading | html %] - [% CASE 'seefrom' %] - UF: [% heading | html %] - [% CASE 'seealso' %] - RT: [% heading | html %] + [% CASE 'broader' %] + BT: [% heading | html %] + [% CASE 'narrower' %] + NT: [% heading | html %] + [% CASE 'seefrom' %] + UF: [% heading | html %] + [% CASE 'seealso' %] + RT: [% heading | html %] [% END %] [% ELSE %] - [% IF ( linkType=='seealso' ) %] - [% IF ( authid ) %] - [% heading | html %] + [% IF ( linkType=='seealso' ) %] + [% IF ( authid ) %] + [% heading | html %] + [% ELSE %] + [% heading | html %] + [% END %] [% ELSE %] - [% heading | html %] + [% heading | html %] [% END %] - [% ELSE %] - [% heading | html %] - [% END %] [% UNLESS ( type=='seefrom' || type=='seealso' ) %] [% SWITCH type %] - [% CASE 'earlier' %](Earlier heading) - [% CASE 'later' %](Later heading) - [% CASE 'acronym' %](Acronym) - [% CASE 'musical' %](Musical composition) - [% CASE 'broader' %](Broader heading) - [% CASE 'narrower' %](Narrower heading) - [% CASE 'parent' %](Immediate parent body) - [% CASE %] - [% IF type %]([% type | html %])[% END %] - [% END %] - + [% CASE 'earlier' %] + (Earlier heading) + [% CASE 'later' %] + (Later heading) + [% CASE 'acronym' %] + (Acronym) + [% CASE 'musical' %] + (Musical composition) + [% CASE 'broader' %] + (Broader heading) + [% CASE 'narrower' %] + (Narrower heading) + [% CASE 'parent' %] + (Immediate parent body) + [% CASE %] + [% IF type %]([% type | html %])[% END %] + [% END %] + [% END # / UNLESS seefrom %] [% END # / IF marcflavour = 'UNIMARC' %] [% END # / BLOCK showreference %] @@ -51,15 +58,13 @@ [% BLOCK authresult %] [% IF ( summary.label ) %][% summary.label | html %]:[% END %] [% IF summary.summary %] -
          - [% summary.summary | html %] -
          +
          [% summary.summary | html %]
          [% END %] [% UNLESS ( summary.summaryonly ) %]
          [% FOREACH authorize IN summary.authorized %] [% authorize.heading | html %] - [% UNLESS loop.last %] | [% END %] + [% UNLESS loop.last %]|[% END %] [% END %]
          [% IF summary.equalterm.size %] @@ -84,7 +89,7 @@
          [% FOREACH see IN summary.seealso %] [% PROCESS showreference heading=see.heading linkType="" type=see.type search='' %] - [% IF ! loop.last %] ; [% END %] + [% IF ! loop.last %];[% END %] [% END %]
          [% END %] @@ -93,7 +98,7 @@ [% FOREACH other IN summary.otherscript %] [% PROCESS language lang=other.lang | trim %]: [% other.term | html %] - [% IF ! loop.last %] ; [% END %] + [% IF ! loop.last %];[% END %] [% END %]
          [% END %] @@ -105,20 +110,20 @@
          [% END %] [% IF ( summary.seefrom.size >= 1 ) %] - used for/see from: + used for/see from: [% FOREACH seefro IN summary.seefrom %]
          - [%# Following on one line for translatability %] - [% PROCESS showreference heading=seefro.heading linkType='seefrom' type=seefro.type %] + [%# Following on one line for translatability %] + [% PROCESS showreference heading=seefro.heading linkType='seefrom' type=seefro.type %]
          [% END %] [% END %] [% IF ( summary.seealso.size >= 1 ) %] - see also: + see also: [% FOREACH seeals IN summary.seealso %]
          - [%# Following on one line for translatability %] - [% PROCESS showreference heading=seeals.heading linkType='seealso' type=seeals.type authid=seeals.authid %] + [%# Following on one line for translatability %] + [% PROCESS showreference heading=seeals.heading linkType='seealso' type=seeals.type authid=seeals.authid %]
          [% END %] [% END %] @@ -127,25 +132,25 @@ [% END # / BLOCK authresult %] [% BLOCK notesmodal %] - - - [% END %] +
          + + + + [% END %] [% END %] [% IF ( showpriority ) %] - - [% HOLD.priority | html %] - + [% HOLD.priority | html %] [% END %] [% IF Koha.Preference('OpacHoldNotes') %] [% HOLD.reservenotes | html | html_line_break %] @@ -150,7 +147,7 @@ [% ELSIF ( HOLD.is_in_processing ) %] Item in processing [% ELSIF ( HOLD.suspend ) %] - Suspended[% IF ( HOLD.suspend_until ) %] until [% HOLD.suspend_until | $KohaDates %][% END %] + Suspended[% IF ( HOLD.suspend_until ) %]until [% HOLD.suspend_until | $KohaDates %][% END %] [% ELSE %] [% IF HOLD.itemtype %] Pending for next available item of item type '[% ItemTypes.GetDescription( HOLD.itemtype ) | html %]' @@ -173,7 +170,14 @@ [% ELSE %] [% IF AutoResumeSuspendedHolds %] [%- SET subtitles = HOLD.biblio.subtitle.split(' \| ') -%] - Suspend + Suspend [% ELSE %]
          [% INCLUDE 'csrf-token.inc' %] @@ -183,7 +187,7 @@
          [% END # / IF AutoResumeSuspendedHolds %] [% END # / IF HOLD.suspend %] - [% END # / IF ( HOLD.is_cancelable_from_opac )%] + [% END # / IF ( HOLD.is_cancelable_from_opac ) %] [% END # / IF SuspendHoldsOpac %] [% IF ! onlyinfo %] @@ -194,7 +198,9 @@ - + [% ELSIF HOLD.is_waiting && HOLD.cancellation_requestable_from_opac %]
          @@ -202,7 +208,9 @@ - +
          [% END %] @@ -229,7 +237,7 @@ [% END %] -
          +
          [% INCLUDE 'csrf-token.inc' %] diff --git a/koha-tmpl/opac-tmpl/bootstrap/en/includes/html_helpers.inc b/koha-tmpl/opac-tmpl/bootstrap/en/includes/html_helpers.inc index 0f818c2579..8f8cc44535 100644 --- a/koha-tmpl/opac-tmpl/bootstrap/en/includes/html_helpers.inc +++ b/koha-tmpl/opac-tmpl/bootstrap/en/includes/html_helpers.inc @@ -5,7 +5,7 @@ [% ELSE %] - [% END%] + [% END %] [% END %] [% END %] @@ -51,13 +51,9 @@ [% BLOCK tabs %] [% IF id %] -
          - [% content | $raw %] -
          +
          [% content | $raw %]
          [% ELSE %] -
          - [% content | $raw %] -
          +
          [% content | $raw %]
          [% END %] [% END %] @@ -81,27 +77,31 @@ [% ELSE %] [% SET our_tab_id = tabname %] [% END %] - + [% content | $raw %] [% END %] [% BLOCK tab_panels %] -
          - [% content | $raw %] -
          +
          [% content | $raw %]
          [% END %] [% BLOCK tab_panel %] [% IF ( bt_active ) %] -
          - [% content| $raw %] -
          +
          [% content| $raw %]
          [% ELSE %] -
          - [% content| $raw %] -
          +
          [% content| $raw %]
          [% END %] [% END %] @@ -159,14 +159,10 @@ [% BLOCK breadcrumb_item %] [% IF ( bc_active ) %] [% ELSE %] - + [% END %] [% END %] diff --git a/koha-tmpl/opac-tmpl/bootstrap/en/includes/ill-availability-table.inc b/koha-tmpl/opac-tmpl/bootstrap/en/includes/ill-availability-table.inc index bd99743147..4214b36ba1 100644 --- a/koha-tmpl/opac-tmpl/bootstrap/en/includes/ill-availability-table.inc +++ b/koha-tmpl/opac-tmpl/bootstrap/en/includes/ill-availability-table.inc @@ -11,7 +11,6 @@ Date - - +
          diff --git a/koha-tmpl/opac-tmpl/bootstrap/en/includes/item-status.inc b/koha-tmpl/opac-tmpl/bootstrap/en/includes/item-status.inc index 2d19d918ce..33c4130635 100644 --- a/koha-tmpl/opac-tmpl/bootstrap/en/includes/item-status.inc +++ b/koha-tmpl/opac-tmpl/bootstrap/en/includes/item-status.inc @@ -9,8 +9,7 @@ [%#- not use an API to fetch items that populates item.datedue. -%] [% UNLESS item.isa('Koha::Item') %] -
          Programming error, item-status.inc must be called with a Koha::Item object.
          - [% STOP %] +
          Programming error, item-status.inc must be called with a Koha::Item object.
          [% STOP %]
          [% END %] [% SET transfer = item.get_transfer %] @@ -51,7 +50,9 @@ [% SET itemavailable = 0 %] [% IF onsite_checkout %] [% IF ( Koha.Preference('OPACShowCheckoutName') ) %] - Currently in local use by [% checkout_patron.firstname | html %] [% checkout_patron.surname | html %] [% IF ( checkout_patron.cardnumber ) %]([% checkout_patron.cardnumber | html %])[% END %] + Currently in local use by [% checkout_patron.firstname | html %] [% checkout_patron.surname | html %] [% IF ( checkout_patron.cardnumber ) %]([% checkout_patron.cardnumber | html %])[% END %] [% ELSE %] Currently in local use [% END %] @@ -69,10 +70,10 @@ [% END %] [% END %] -[% IF transfertwhen %] [%# transfertwhen is set in C4::Search, do not have it for course reserves %] +[% IF transfertwhen %] + [%# transfertwhen is set in C4::Search, do not have it for course reserves %] [% SET itemavailable = 0 %] - In transit from [% Branches.GetName( transfertfrom ) | html %] - to [% Branches.GetName( transfertto ) | html %] since [% transfertwhen | $KohaDates %] + In transit from [% Branches.GetName( transfertfrom ) | html %] to [% Branches.GetName( transfertto ) | html %] since [% transfertwhen | $KohaDates %] [% END %] [% IF waiting OR item.holds.processing.count %] @@ -90,7 +91,6 @@ [% END %] [% END %] - [% SET restricted_lib = AuthorisedValues.GetDescriptionByKohaField( kohafield => 'items.restricted', authorised_value => item.restricted, opac => 1 ) %] [% IF item.notforloan %] [% SET itemavailable = 0 %] diff --git a/koha-tmpl/opac-tmpl/bootstrap/en/includes/js-biblio-format.inc b/koha-tmpl/opac-tmpl/bootstrap/en/includes/js-biblio-format.inc index 7d125e2060..72e37775da 100644 --- a/koha-tmpl/opac-tmpl/bootstrap/en/includes/js-biblio-format.inc +++ b/koha-tmpl/opac-tmpl/bootstrap/en/includes/js-biblio-format.inc @@ -1,5 +1,6 @@ + - - [% IF Koha.Preference( 'opacbookbag' ) == 1 %] [% Asset.js("js/basket.js") | $raw %] [% ELSIF ( Koha.Preference( 'virtualshelves' ) == 1 ) %] [% Asset.js("js/basket.js") | $raw %] [% ELSE %] - + [% END %] [% IF Koha.Preference( 'opacuserlogin' ) == 1 %][% IF Koha.Preference( 'TagsEnabled' ) == 1 %][% Asset.js("js/tags.js") | $raw %][% END %][% END %] @@ -148,32 +164,32 @@ [% IF ( BakerTaylorEnabled ) %] [% Asset.js("js/bakertaylorimages.js") | $raw %] [% END %] [% IF Koha.Preference( 'OpacNewsLibrarySelect' ) %] - + [% END %] [% Asset.js("lib/js-cookie/js.cookie-3.0.1.min.js") | $raw %] [% Asset.js("js/show-password-toggle.js") | $raw %] [% INCLUDE 'js-date-format.inc' %] [% INCLUDE 'js-biblio-format.inc' %] @@ -192,9 +208,7 @@ $(document).ready(function() { [% SET SCOUserJS = Koha.Preference('SCOUserJS') %] [% IF ( SCOUserJS ) %] [% END %] [% END %] diff --git a/koha-tmpl/opac-tmpl/bootstrap/en/includes/opac-detail-sidebar.inc b/koha-tmpl/opac-tmpl/bootstrap/en/includes/opac-detail-sidebar.inc index a0ddc377be..03e74f148c 100644 --- a/koha-tmpl/opac-tmpl/bootstrap/en/includes/opac-detail-sidebar.inc +++ b/koha-tmpl/opac-tmpl/bootstrap/en/includes/opac-detail-sidebar.inc @@ -6,55 +6,81 @@ [% IF Koha.Preference( 'opacuserlogin' ) == 1 %] [% IF Koha.Preference( 'OPACHoldRequests' ) == 1 %] [% IF ( ReservableItems ) %] -
        • Place hold
        • +
        • Place hold
        • [% END %] [% END %] [% END %] [% IF Koha.Preference('UseRecalls') %] -
        • - Place recall
        • +
        • Place recall
        • [% END %] -
        • Print
        • -
        • Cite
        • +
        • Print
        • +
        • Cite
        • [% IF Koha.Preference( 'opacuserlogin' ) == 1 %] [% IF artreqpossible %] -
        • Request article
        • +
        • Request article
        • [% END %] [% END %] [% IF Koha.Preference( 'virtualshelves' ) == 1 %] [% IF ( ( Koha.Preference( 'opacuserlogin' ) == 1 ) && loggedinusername ) %] -
        • Save to your lists
        • +
        • Save to your lists
        • [% END %] [% END %] [% IF Koha.Preference( 'opacbookbag' ) == 1 %] [% IF ( incart ) %] -
        • In your cart (remove)
        • +
        • In your cart + (remove)
        • [% ELSE %] -
        • Add to your cart
        • +
        • Add to your cart +
        • [% END %] [% END %] [% IF ( suggestion ) %] -
        • Suggest for purchase
        • +
        • Suggest for purchase
        • [% END %] [% IF Koha.Preference('OpacCatalogConcerns') %] -
        • Report a concern
        • +
        • Report a concern
        • [% END %] [% IF ( OpacHighlightedWords && query_desc ) %] -
        • - Unhighlight - Highlight -
        • +
        • + Unhighlight + Highlight +
        • [% END %] - [% IF ( Koha.Preference('OPACDetailQRCode' ) ) %]
        • Send to device @@ -75,22 +101,34 @@ [% ELSE %] [% SWITCH option %] - [% CASE 'bibtex' %]BIBTEX - [% CASE 'endnote' %]EndNote - [% CASE 'marcxml' %]MARCXML - [% CASE 'marc8' %]MARC (non-Unicode/MARC-8) - [% CASE 'utf8' %]MARC (Unicode/UTF-8) - [% CASE 'marcstd' %]MARC (Unicode/UTF-8, Standard) - [% CASE 'mods' %]MODS (XML) - [% CASE 'ris' %]RIS - [% CASE 'isbd' %]ISBD + [% CASE 'bibtex' %] + BIBTEX + [% CASE 'endnote' %] + EndNote + [% CASE 'marcxml' %] + MARCXML + [% CASE 'marc8' %] + MARC (non-Unicode/MARC-8) + [% CASE 'utf8' %] + MARC (Unicode/UTF-8) + [% CASE 'marcstd' %] + MARC (Unicode/UTF-8, Standard) + [% CASE 'mods' %] + MODS (XML) + [% CASE 'ris' %] + RIS + [% CASE 'isbd' %] + ISBD [% END %] [% END %] [% END %] -
        • -
          - + + + + + + [% END %] @@ -138,14 +176,17 @@ - - + + - - - + + + + + + diff --git a/koha-tmpl/opac-tmpl/bootstrap/en/includes/opac-facets.inc b/koha-tmpl/opac-tmpl/bootstrap/en/includes/opac-facets.inc index 4014ebe3cc..180eee8561 100644 --- a/koha-tmpl/opac-tmpl/bootstrap/en/includes/opac-facets.inc +++ b/koha-tmpl/opac-tmpl/bootstrap/en/includes/opac-facets.inc @@ -9,74 +9,76 @@

          Refine your search

          + + +
          -
          - + + + + + + [% END # /IF ( listResults ) %] - + + [% END # / IF OpacBrowseResults && busc %] [% INCLUDE 'opac-detail-sidebar.inc' %] @@ -1088,36 +1173,55 @@ [% SET SocialNetworks = Koha.Preference('SocialNetworks') %] [% FOREACH network IN SocialNetworks.split(",") %] [% SWITCH network -%] - [% CASE "facebook" -%] -
          - [% CASE "linkedin" -%] -
          - [% CASE "email" -%] -
          + [% CASE "facebook" -%] +
          + [% CASE "linkedin" -%] +
          + [% CASE "email" -%] +
          [% END # /SWITCH network -%] [% END # /FOREACH network %] - + + [% END # /IF SocialNetworks %] - - - + + + + + +
          [% IF ( LibraryThingForLibrariesID ) %] - - + + [% END %] [% IF ( NovelistSelectProfile && ( normalized_isbn || normalized_upc ) ) %] - + [% END %] [% IF ( Babeltheque && Babeltheque_url_js ) %] - + [% END %] -
          - - + + + + + + [% IF ( OPACPopupAuthorsSearch ) %] @@ -1131,16 +1235,18 @@ - - - + + + + + + [% END %] @@ -1158,9 +1264,12 @@ Visit web site - - - + + + + + + [% INCLUDE 'opac-bottom.inc' %] @@ -1171,7 +1280,6 @@ Holdings - [% IF Koha.Preference('OPACLocalCoverImages') && ( tab == 'holdings' && itemloop_has_images || tab == 'otherholdings' && otheritemloop_has_images ) %] Cover image [% END %] @@ -1205,7 +1313,7 @@ [% IF ( itemdata_copynumber ) %] Copy number [% END %] - Status + Status [% IF ( itemdata_itemnotes ) %] Notes [% END %] @@ -1229,207 +1337,215 @@ [% FOREACH ITEM_RESULT IN items %] - - [% IF Koha.Preference('OPACLocalCoverImages') && ( tab == 'holdings' && itemloop_has_images || tab == 'otherholdings' && otheritemloop_has_images ) %] - -
          -
          - [% FOR image IN ITEM_RESULT.cover_images %] -
          - - Local cover image - -
          - [% END %] + [% IF Koha.Preference('OPACLocalCoverImages') && ( tab == 'holdings' && itemloop_has_images || tab == 'otherholdings' && otheritemloop_has_images ) %] + +
          +
          + [% FOR image IN ITEM_RESULT.cover_images %] +
          + + Local cover image + +
          + [% END %] +
          -
          - - [% END %] - - [% IF ( item_level_itypes ) %] - - [% UNLESS ( Koha.Preference('OpacNoItemTypeImages') ) %] - [% IF ( ITEM_RESULT.imageurl ) %] - [% ITEM_RESULT.description | html %] - [% END %] - [% END %] - [% ITEM_RESULT.description | html %] - - [% END %] - [% IF ( OpacLocationBranchToDisplay == 'holding' || OpacLocationBranchToDisplay == 'both' ) %] - [%# Show opac_info or branchurl from holding library %] - [% SET holding_library_name = Branches.GetName( ITEM_RESULT.holdingbranch ) %] - [% SET holding_library_url = Branches.GetURL( ITEM_RESULT.holdingbranch ) %] - - - - - [% IF ( ITEM_RESULT.holding_library_info ) %] - - [% holding_library_name | html %] - - [% ELSIF holding_library_url %] - - [% holding_library_name | html %] - - [% ELSE %] - [% holding_library_name | html %] - [% END %] - - [% IF ( Koha.Preference('OpacLocationOnDetail') == 'holding' || Koha.Preference('OpacLocationOnDetail') == 'both' ) %] - [% ITEM_RESULT.location_description | html %] - [% END %] - - - [% END %] - - [% IF ( OpacLocationBranchToDisplay == 'home' || OpacLocationBranchToDisplay == 'both' ) %] - [%# Show opac_info or branchurl from home library %] - [% SET home_library_name = Branches.GetName( ITEM_RESULT.homebranch ) %] - [% SET home_library_url = Branches.GetURL( ITEM_RESULT.homebranch ) %] - - - - - [% IF ( ITEM_RESULT.home_library_info ) %] - - [% home_library_name | html %] - - [% ELSIF home_library_url %] - - [% home_library_name | html %] - - [% ELSE %] - [% home_library_name | html %] - [% END %] - - [% IF ( Koha.Preference('OpacLocationOnDetail') == 'home' || Koha.Preference('OpacLocationOnDetail') == 'both' ) %] - [% ITEM_RESULT.location_description | html %] - [% END %] - - - [% END %] - - [% IF ( itemdata_ccode ) %] - [% ITEM_RESULT.ccode | html %] - [% END %] - - [% IF ( Koha.Preference('OpacLocationOnDetail') == 'column' && itemdata_location ) %] - [% ITEM_RESULT.location_description | html %] - [% END %] - - [% IF ( itemdata_itemcallnumber ) %] - - [% IF ( ITEM_RESULT.itemcallnumber ) %] - [% ITEM_RESULT.itemcallnumber | html %] - [% IF ( OPACShelfBrowser ) %] - [% IF ( ITEM_RESULT.itemnumber == starting_itemnumber ) %] - (Browse shelf(Opens below)) - [% ELSE %] - (Browse shelf(Opens below)) - [% END %] - [% END %] - [% END %] - - [% END %] - - [% IF ( itemdata_materials ) %] - [% ITEM_RESULT.materials | html %] - [% END %] - - [% IF ( itemdata_enumchron ) %] - [% SET serial = ITEM_RESULT.serial %] - - [% IF ITEM_RESULT.enumchron && serial.serialseq %] - [% ITEM_RESULT.enumchron | html %] - [% IF ( serial.serialseq && ITEM_RESULT.enumchron!=serial.serialseq ) %] - -- - [% serial.serialseq | html %] - [% END %] - [% ELSIF ITEM_RESULT.enumchron %] - [% ITEM_RESULT.enumchron | html %] - [% ELSIF serial.serialseq %] - [% serial.serialseq | html %] - [% END %] - [% IF ( serial.publisheddate ) %] - ([% serial.publisheddate | $KohaDates %]) - [% END %] - - [% END %] - [% IF ( itemdata_uri ) %] - - [% IF ITEM_RESULT.uri %] - [%# Initialize two helper vars %] - [% SET target_attr = ''; SET rel_attr = '' %] - [% IF Koha.Preference('OPACURLOpenInNewWindow') %][% SET target_attr = '_blank'; SET rel_attr = 'noreferrer' %][% END %] - - [%# Check if there are multiple URIs; in the single case we only use pref URLLinkText or Link to resource %] - [% SET uris = ITEM_RESULT.uri.split(' \| ') %] - [% IF uris.size > 1 %] - [% FOREACH uri IN uris %] - [% IF trackclicks == 'track' || trackclicks == 'anonymous' %] - [% uri | html %] - [% ELSE %] - [% uri | html %] - [% END %] - [% END %] - [% ELSE %] - [% IF trackclicks == 'track' || trackclicks == 'anonymous' %] - - [% IF Koha.Preference('URLLinkText') %][% Koha.Preference('URLLinkText') | html %][% ELSE %]Link to resource[% END %] - - [% ELSE %] - - [% IF Koha.Preference('URLLinkText') %][% Koha.Preference('URLLinkText') | html %][% ELSE %]Link to resource[% END %] - - [% END %] - [% END %] + [% END %] - - [% END # /IF itemdata_uri %] - [% IF ( itemdata_copynumber ) %][% ITEM_RESULT.copynumber | html %][% END %] - [% INCLUDE 'item-status.inc' item = ITEM_RESULT.object include_schema_org = 1 %] - [% IF ( itemdata_itemnotes ) %][% ITEM_RESULT.itemnotes | $raw %][% END %] - [% IF item_checkouts %] - [% ITEM_RESULT.checkout.date_due | $KohaDates as_due_date => 1 %] - [% END %] - [% IF ( itemdata_barcode ) %] - [% ITEM_RESULT.barcode | html %] - [% END %] - - [% IF item_level_holds > 0 %] - - [% IF holds_count.defined %] [% ITEM_RESULT.holds_count | html %] [% END %] - [% IF ITEM_RESULT.priority %] - [% IF holds_count.defined %] - (priority [% ITEM_RESULT.priority | html %]) - [% ELSE %] - [% ITEM_RESULT.priority | html %] - [% END %] - [% END %] - - [% END %] - - [% IF ShowCourseReservesHeader %] - - [% IF ITEM_RESULT.course_reserves %] - [% FOREACH r IN ITEM_RESULT.course_reserves %] - [% IF r.course.enabled == 'yes' %] -

          - - [% r.course.course_name | html %] - - [% IF r.course.section %] [% r.course.section | html %] [% END %] - [% IF r.course.term %] [% AuthorisedValues.GetByCode( 'TERM', r.course.term, 1 ) | html %] [% END %] - -

          + [% IF ( item_level_itypes ) %] + + [% UNLESS ( Koha.Preference('OpacNoItemTypeImages') ) %] + [% IF ( ITEM_RESULT.imageurl ) %] + [% ITEM_RESULT.description | html %] [% END %] [% END %] - [% END %] - - [% END # /IF ShowCourseReservesHeader %] - + [% ITEM_RESULT.description | html %] + + [% END %] + [% IF ( OpacLocationBranchToDisplay == 'holding' || OpacLocationBranchToDisplay == 'both' ) %] + [%# Show opac_info or branchurl from holding library %] + [% SET holding_library_name = Branches.GetName( ITEM_RESULT.holdingbranch ) %] + [% SET holding_library_url = Branches.GetURL( ITEM_RESULT.holdingbranch ) %] + + + + + [% IF ( ITEM_RESULT.holding_library_info ) %] + + [% holding_library_name | html %] + + [% ELSIF holding_library_url %] + [% holding_library_name | html %] + [% ELSE %] + [% holding_library_name | html %] + [% END %] + + [% IF ( Koha.Preference('OpacLocationOnDetail') == 'holding' || Koha.Preference('OpacLocationOnDetail') == 'both' ) %] + [% ITEM_RESULT.location_description | html %] + [% END %] + + [% END %] + + [% IF ( OpacLocationBranchToDisplay == 'home' || OpacLocationBranchToDisplay == 'both' ) %] + [%# Show opac_info or branchurl from home library %] + [% SET home_library_name = Branches.GetName( ITEM_RESULT.homebranch ) %] + [% SET home_library_url = Branches.GetURL( ITEM_RESULT.homebranch ) %] + + + + + [% IF ( ITEM_RESULT.home_library_info ) %] + + [% home_library_name | html %] + + [% ELSIF home_library_url %] + [% home_library_name | html %] + [% ELSE %] + [% home_library_name | html %] + [% END %] + + [% IF ( Koha.Preference('OpacLocationOnDetail') == 'home' || Koha.Preference('OpacLocationOnDetail') == 'both' ) %] + [% ITEM_RESULT.location_description | html %] + [% END %] + + [% END %] + + [% IF ( itemdata_ccode ) %] + [% ITEM_RESULT.ccode | html %] + [% END %] + + [% IF ( Koha.Preference('OpacLocationOnDetail') == 'column' && itemdata_location ) %] + [% ITEM_RESULT.location_description | html %] + [% END %] + + [% IF ( itemdata_itemcallnumber ) %] + + [% IF ( ITEM_RESULT.itemcallnumber ) %] + [% ITEM_RESULT.itemcallnumber | html %] + [% IF ( OPACShelfBrowser ) %] + [% IF ( ITEM_RESULT.itemnumber == starting_itemnumber ) %] + (Browse shelf(Opens below)) + [% ELSE %] + (Browse shelf(Opens below)) + [% END %] + [% END %] + [% END %] + + [% END %] + + [% IF ( itemdata_materials ) %] + [% ITEM_RESULT.materials | html %] + [% END %] + + [% IF ( itemdata_enumchron ) %] + [% SET serial = ITEM_RESULT.serial %] + + [% IF ITEM_RESULT.enumchron && serial.serialseq %] + [% ITEM_RESULT.enumchron | html %] + [% IF ( serial.serialseq && ITEM_RESULT.enumchron!=serial.serialseq ) %] + -- + [% serial.serialseq | html %] + [% END %] + [% ELSIF ITEM_RESULT.enumchron %] + [% ITEM_RESULT.enumchron | html %] + [% ELSIF serial.serialseq %] + [% serial.serialseq | html %] + [% END %] + [% IF ( serial.publisheddate ) %] + ([% serial.publisheddate | $KohaDates %]) + [% END %] + + [% END %] + [% IF ( itemdata_uri ) %] + + [% IF ITEM_RESULT.uri %] + [%# Initialize two helper vars %] + [% SET target_attr = ''; SET rel_attr = '' %] + [% IF Koha.Preference('OPACURLOpenInNewWindow') %][% SET target_attr = '_blank'; SET rel_attr = 'noreferrer' %][% END %] + + [%# Check if there are multiple URIs; in the single case we only use pref URLLinkText or Link to resource %] + [% SET uris = ITEM_RESULT.uri.split(' \| ') %] + [% IF uris.size > 1 %] + [% FOREACH uri IN uris %] + [% IF trackclicks == 'track' || trackclicks == 'anonymous' %] + [% uri | html %] + [% ELSE %] + [% uri | html %] + [% END %] + [% END %] + [% ELSE %] + [% IF trackclicks == 'track' || trackclicks == 'anonymous' %] + + [% IF Koha.Preference('URLLinkText') %][% Koha.Preference('URLLinkText') | html %][% ELSE %]Link to resource[% END %] + + [% ELSE %] + + [% IF Koha.Preference('URLLinkText') %][% Koha.Preference('URLLinkText') | html %][% ELSE %]Link to resource[% END %] + + [% END %] + [% END %] + [% END %] + + [% END # /IF itemdata_uri %] + [% IF ( itemdata_copynumber ) %][% ITEM_RESULT.copynumber | html %][% END %] + [% INCLUDE 'item-status.inc' item = ITEM_RESULT.object include_schema_org = 1 %] + [% IF ( itemdata_itemnotes ) %][% ITEM_RESULT.itemnotes | $raw %][% END %] + [% IF item_checkouts %] + [% ITEM_RESULT.checkout.date_due | $KohaDates as_due_date => 1 %] + [% END %] + + [% IF ( itemdata_barcode ) %] + [% ITEM_RESULT.barcode | html %] + [% END %] + + [% IF item_level_holds > 0 %] + + [% IF holds_count.defined %][% ITEM_RESULT.holds_count | html %][% END %] + [% IF ITEM_RESULT.priority %] + [% IF holds_count.defined %] + (priority [% ITEM_RESULT.priority | html %]) + [% ELSE %] + [% ITEM_RESULT.priority | html %] + [% END %] + [% END %] + + [% END %] + + [% IF ShowCourseReservesHeader %] + + [% IF ITEM_RESULT.course_reserves %] + [% FOREACH r IN ITEM_RESULT.course_reserves %] + [% IF r.course.enabled == 'yes' %] +

          + + [% r.course.course_name | html %] + + [% IF r.course.section %][% r.course.section | html %][% END %] + [% IF r.course.term %][% AuthorisedValues.GetByCode( 'TERM', r.course.term, 1 ) | html %][% END %] + +

          + [% END %] + [% END %] + [% END %] + + [% END # /IF ShowCourseReservesHeader %] + [% END %] @@ -1472,7 +1588,6 @@ [% IF OpenLibraryCovers || OpenLibrarySearch %] [% Asset.js("js/openlibrary.js") | $raw %] [% END %] - - [% END %] - [% END # / IF format %] - [% ELSE %] -

          Download list unsuccessful

          -
          -

          You do not have permission to download this list.

          -
          +
          +
          + + Required +
          - [% END # / invalidlist %] - -
          - - - - - - [% INCLUDE 'opac-bottom.inc' %] - [% BLOCK jsinclude %] - + [% END %] + [% END # / IF format %] + [% ELSE %] +

          Download list unsuccessful

          +
          +

          You do not have permission to download this list.

          +
          + [% END # / invalidlist %] + + + + + + + + + + +[% INCLUDE 'opac-bottom.inc' %] +[% BLOCK jsinclude %] + - [% END %] + }); + +[% END %] diff --git a/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-full-serial-issues.tt b/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-full-serial-issues.tt index 324cb6a0bf..cb8dafccc7 100644 --- a/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-full-serial-issues.tt +++ b/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-full-serial-issues.tt @@ -11,71 +11,73 @@ [% INCLUDE 'doc-head-close.inc' %] [% BLOCK cssinclude %] [% FILTER collapse %] - + #subtabs { + margin-top: 1em; + } + .action .btn { + font-size: 90%; + width: 100%; + } + .menu-collapse { + padding: 0.5em; + } + a.currentsubtab { + background-color: #ffc; + } + [% END %] [% END %] [% INCLUDE 'bodytag.inc' bodyid='opac-full-serial-issues' bodyclass='scrollto' %] [% INCLUDE 'masthead.inc' %] -
          - [% WRAPPER breadcrumbs %] - [% WRAPPER breadcrumb_item %] - Details for [% bibliotitle | html %] - [% END %] - [% WRAPPER breadcrumb_item bc_active= 1 %] - Full subscription history - [% END %] - [% END #/ WRAPPER breadcrumbs %] +
          + [% WRAPPER breadcrumbs %] + [% WRAPPER breadcrumb_item %] + Details for [% bibliotitle | html %] + [% END %] + [% WRAPPER breadcrumb_item bc_active= 1 %] + Full subscription history + [% END %] + [% END #/ WRAPPER breadcrumbs %] -
          -
          -
          -
          -
          - -

          Refine your search

          +
          +
          +
          +
          +
          + +

          Refine your search

          - -
          -
          - -
          -
          -
          - [% UNLESS ( popup ) %] -

          Full subscription history for [% bibliotitle | html %]

          -
          - Normal view - Brief history - Full history -
          - [% END %] - -
          - Show year: - [% FOREACH year IN years %] - [% IF ( year.year ) %] - [% year.year | html %] - [% END %] - [% END %] + +
          + + +
          + +
          +
          + [% UNLESS ( popup ) %] +

          Full subscription history for [% bibliotitle | html %]

          +
          + Normal view + Brief history + Full history
          + [% END %] +
          + Show year: [% FOREACH year IN years %] - [% SET div_style = "display:none" %] - [% IF loop.first %] - [% div_style = "display:block" %] + [% IF ( year.year ) %] + [% year.year | html %] [% END %] -
          - - - + [% END %] + + + [% FOREACH year IN years %] + [% SET div_style = "display:none" %] + [% IF loop.first %] + [% div_style = "display:block" %] + [% END %] +
          +
          Subscriptions
          + + + + + + + + + + + + + + + [% FOREACH serial IN year.serials %] - - - - - - - - - - - - [% FOREACH serial IN year.serials %] - - - - - - [% IF ( serial.status2 && serial.planneddate ) %] - [% ELSE %] - +   [% END %] - - - - - [% END %] - -
          Subscriptions
          DateLibraryLocationNotesDate receivedNumberStatusSubscription
          DateLibraryLocationNotesDate receivedNumberStatusSubscription
          - [% IF ( serial.publisheddate ) %] - [% IF serial.publisheddatetext %] - [% serial.publisheddatetext | html %] - [% ELSE %] - [% serial.publisheddate | $KohaDates %] - [% END %] + + [% IF ( serial.publisheddate ) %] + [% IF serial.publisheddatetext %] + [% serial.publisheddatetext | html %] [% ELSE %] -   + [% serial.publisheddate | $KohaDates %] [% END %] - [% Branches.GetName( serial.branchcode ) | html %][% AuthorisedValues.GetDescriptionByKohaField( kohafield => 'items.location', authorised_value => serial.location, opac => 1 ) | html %][% serial.notes | html %] - [% serial.planneddate | $KohaDates %] - -   - [% serial.serialseq | html %] - [% INCLUDE 'serial-status.inc' serial = serial %] - [% serial.subscriptionid | html %]
          -
          - [% END # / FOREACH year %] -
          -
          -
          -
          -
          + + [% Branches.GetName( serial.branchcode ) | html %] + [% AuthorisedValues.GetDescriptionByKohaField( kohafield => 'items.location', authorised_value => serial.location, opac => 1 ) | html %] + [% serial.notes | html %] + [% IF ( serial.status2 && serial.planneddate ) %] + [% serial.planneddate | $KohaDates %] + [% ELSE %] +   + [% END %] + [% serial.serialseq | html %] + [% INCLUDE 'serial-status.inc' serial = serial %] + [% serial.subscriptionid | html %] + + [% END %] + + +
          + + [% END # / FOREACH year %] +
          + +
          + +
          + +
          + +
          + [% INCLUDE 'opac-bottom.inc' %] [% BLOCK jsinclude %] diff --git a/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-holdshistory.tt b/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-holdshistory.tt index cca64a6274..2d5c2c8184 100644 --- a/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-holdshistory.tt +++ b/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-holdshistory.tt @@ -14,9 +14,8 @@ [% INCLUDE 'doc-head-close.inc' %] [% BLOCK cssinclude %] [% END %] @@ -56,9 +55,7 @@
          - +
          @@ -84,119 +81,120 @@
          [% UNLESS unlimit %] -

          - Showing 50 items. Show all items -

          +

          Showing 50 items. Show all items

          [% ELSE %] -

          - Showing all items. Show 50 items -

          +

          Showing all items. Show 50 items

          [% END %]
          - - - - - - - - - [% IF show_itemtype_column %] - - [% END %] - + + + + + + + + + [% IF show_itemtype_column %] + + [% END %] + - [% FOREACH hold IN holds %] - - - - - - - - - - [% IF show_itemtype_column %] - + [% FOREACH hold IN holds %] + + + + + + + + + + [% IF show_itemtype_column %] + + [% END %] + + [% END %] - - - [% END %]
          Holds history
          TitleAuthorBarcodeLibraryHold dateExpiration dateWaiting dateCancellation dateRequested item typeStatusTitleAuthorBarcodeLibraryHold dateExpiration dateWaiting dateCancellation dateRequested item typeStatus
          [% INCLUDE 'biblio-title.inc' biblio=hold.biblio link=>1 %][% hold.biblio.author | html %][% hold.item.barcode | html %][% Branches.GetName( hold.branchcode ) | html %][% hold.reservedate | $KohaDates %] - [% IF hold.expirationdate %] - [% hold.expirationdate | $KohaDates %] - [% END %] - - [% IF hold.waitingdate %] - [% hold.waitingdate | $KohaDates %] - [% END %] - - [% IF hold.cancellationdate %] - [% hold.cancellationdate | $KohaDates %] - [% END %] - - [% IF hold.itemtype %] - [% ItemTypes.GetDescription( hold.itemtype ) | html %] - [% ELSE %] - Any item type - [% END %] -
          [% INCLUDE 'biblio-title.inc' biblio=hold.biblio link=>1 %][% hold.biblio.author | html %][% hold.item.barcode | html %][% Branches.GetName( hold.branchcode ) | html %][% hold.reservedate | $KohaDates %] + [% IF hold.expirationdate %] + [% hold.expirationdate | $KohaDates %] + [% END %] + + [% IF hold.waitingdate %] + [% hold.waitingdate | $KohaDates %] + [% END %] + + [% IF hold.cancellationdate %] + [% hold.cancellationdate | $KohaDates %] + [% END %] + + [% IF hold.itemtype %] + [% ItemTypes.GetDescription( hold.itemtype ) | html %] + [% ELSE %] + Any item type + [% END %] + + [% IF hold.found == 'F' %] + Fulfilled + [% ELSIF hold.cancellationdate %] + Cancelled + [% IF hold.cancellation_reason %] + ([% AuthorisedValues.GetByCode('HOLD_CANCELLATION', hold.cancellation_reason, 1) | html %]) + [% END %] + [% ELSIF hold.found == 'W' %] + [% IF hold.cancellation_requests.count == 0 %] + Waiting + [% ELSE %] + Cancelled + [% END %] + [% ELSIF hold.found == 'T' %] + In transit + [% ELSE %] + Pending + [% END %] +
          - [% IF hold.found == 'F' %] - Fulfilled - [% ELSIF hold.cancellationdate %] - Cancelled - [% IF hold.cancellation_reason %] - ([% AuthorisedValues.GetByCode('HOLD_CANCELLATION', hold.cancellation_reason, 1) | html %]) - [% END %] - [% ELSIF hold.found == 'W' %] - [% IF hold.cancellation_requests.count == 0 %] - Waiting - [% ELSE %] - Cancelled - [% END %] - [% ELSIF hold.found == 'T' %] - In transit - [% ELSE %] - Pending - [% END %] -
          -
          -
          +
          + +
          + [% END # / IF old_holds_count %] - - - - - + + + + + + + + + + [% INCLUDE 'opac-bottom.inc' %] [% BLOCK jsinclude %] -[% INCLUDE 'datatables.inc' %] -[% INCLUDE 'columns_settings.inc' %] - + [% END %] diff --git a/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-ics.tt b/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-ics.tt index 8ba6fc71a3..ed752437f9 100644 --- a/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-ics.tt +++ b/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-ics.tt @@ -1,9 +1,9 @@ [%# First line will be summary, second line will be description. Avoid indenting. Var newline added to avoid translating problems. -%] [%- newline="\n" | html -%] [%- IF overdue == 1 -%] -[% title | html %] is overdue -[%- newline | html -%]Your copy of [% title | html %] (barcode [% barcode | html %]) is overdue + [% title | html %] + is overdue [%- newline | html -%]Your copy of [% title | html %] (barcode [% barcode | html %]) is overdue [%- ELSE -%] -[% title | html %] is due -[%- newline | html -%]Your copy of [% title | html %] (barcode [% barcode | html %]) is due back at the library today + [% title | html %] + is due [%- newline | html -%]Your copy of [% title | html %] (barcode [% barcode | html %]) is due back at the library today [%- END -%] diff --git a/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-idref.tt b/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-idref.tt index 202ca28fe4..78dbee485d 100644 --- a/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-idref.tt +++ b/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-idref.tt @@ -3,74 +3,74 @@ [% INCLUDE 'doc-head-close.inc' %] [% BLOCK cssinclude %] - + [% END %] [% INCLUDE 'bodytag.inc' bodyid='idref' bodyclass='scrollto' %]
          - [% IF error %] - This ppn is not found on the idref service. - [% ELSE %] - [% FOREACH role IN content %] -
          -

          [% role.role_name | html %] ([% role.count | html %])

          -
          - - - - - - - - - - - [% FOREACH doc IN role.docs %] - - - - - - [% END %] - -
          [% role.role_name | html %]
          CitationKohaSudoc
          [% doc.citation | html %]KohaSudoc
          -
          -
          + [% IF error %] + This ppn is not found on the idref service. + [% ELSE %] + [% FOREACH role IN content %] +
          +

          [% role.role_name | html %] ([% role.count | html %])

          +
          + + + + + + + + + + + [% FOREACH doc IN role.docs %] + + + + + + [% END %] + +
          [% role.role_name | html %]
          CitationKohaSudoc
          [% doc.citation | html %]KohaSudoc
          +
          +
          + [% END %] [% END %] - [% END %]
          [% BLOCK jsinclude %] -[% INCLUDE 'datatables.inc' %] - + $(".role").click(function () { + var docs_node = $(this).parent().find("div.docs"); + if ($(docs_node).is(":visible")) { + $(".docs").hide(); + } else { + $(".docs").hide(); + docs_node.show(); + } + }); + $(".docs").hide(); + }); + [% END %] -[% INCLUDE 'opac-bottom.inc' is_popup=1%] +[% INCLUDE 'opac-bottom.inc' is_popup=1 %] diff --git a/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-illrequests.tt b/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-illrequests.tt index 681e4261c5..0c87dca21b 100644 --- a/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-illrequests.tt +++ b/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-illrequests.tt @@ -10,7 +10,8 @@ [% INCLUDE 'doc-head-open.inc' %] Your interlibrary loan requests › [% IF ( LibraryNameTitle ) %][% LibraryNameTitle | html %][% ELSE %]Koha online[% END %] catalog [% INCLUDE 'doc-head-close.inc' %] -[% BLOCK cssinclude %][% END %] +[% BLOCK cssinclude %] +[% END %] [% INCLUDE 'bodytag.inc' bodyid='opac-illrequests' bodyclass='scrollto' %] [% BLOCK messages %] @@ -57,9 +58,7 @@
          [% IF ( OpacNav||loggedinusername ) && !print %]
          - +
          [% END %] @@ -79,16 +78,12 @@

          [% IF ( ILLModuleCopyrightClearance ) %] -

          - [% PROCESS koha_news_block news => ILLModuleCopyrightClearance %] -
          +
          [% PROCESS koha_news_block news => ILLModuleCopyrightClearance %]
          [% END %]

          [% USE link_url = url('/cgi-bin/koha/opac-illrequests.pl', whole.value.other) %] - Yes - No + Yes + No
          [% ELSE %] [% INCLUDE messages %] @@ -156,16 +151,10 @@ [% type = request.get_type %] [% request.id | html %] - - [% IF request.metadata.Author %][% request.metadata.Author | html %][% ELSE %]N/A[% END %] - - - [% IF request.metadata.Title %][% request.metadata.Title | html %][% ELSE %]N/A[% END %] - + [% IF request.metadata.Author %][% request.metadata.Author | html %][% ELSE %]N/A[% END %] + [% IF request.metadata.Title %][% request.metadata.Title | html %][% ELSE %]N/A[% END %] [% request.backend | html %] - - [% IF type %][% type | html %][% ELSE %]N/A[% END %] - + [% IF type %][% type | html %][% ELSE %]N/A[% END %] [% request.status_alias ? request.statusalias.lib_opac : request.capabilities.$status.name | html %] [% request.placed | $KohaDates %] [% request.updated | $KohaDates %] @@ -239,19 +228,19 @@
          [% END %] - [% IF can_patron_place_ill_in_opac %] -
          - - - [% IF !request.completed %] - [% IF request.status == "NEW" %] - Request cancellation + [% IF can_patron_place_ill_in_opac %] +
          + + + [% IF !request.completed %] + [% IF request.status == "NEW" %] + Request cancellation + [% END %] + [% END %] - - [% END %] - Cancel -
          - [% END %] + Cancel +
          + [% END %] [% ELSIF op == 'availability' %]

          Interlibrary loan item availability

          @@ -263,18 +252,18 @@ [% FOREACH key IN whole.keys %] [% value = whole.$key %] [% IF key != 'custom_key' && key != 'custom_value' && key != 'csrf_token' %] - + [% END %] [% END %] [% custom_keys = whole.custom_key.split('\0') %] [% custom_values = whole.custom_value.split('\0') %] [% i = 0 %] [% FOREACH custom_key IN custom_keys %] - - - [% i = i + 1 %] + + + [% i = i + 1 %] [% END %] - +
          If you can't find what you are looking for, you can or @@ -285,7 +274,8 @@

          [% service.name | html %]

          [% INCLUDE 'ill-availability-table.inc' service=service %] [% END %] -
          + + [% ELSIF op == 'typedisclaimer' %]

          ILL request disclaimer

          @@ -297,7 +287,7 @@ [% disclaimer.text | $raw %] [% SET disc_av_category_code = AuthorisedValues.GetAuthValueDropbox(disclaimer.av_cat) %] [% IF disc_av_category_code.count %] -
          +
          + [% END %] [% END %] [% custom_keys = whole.custom_key.split('\0') %] [% custom_values = whole.custom_value.split('\0') %] [% i = 0 %] [% FOREACH custom_key IN custom_keys %] - - - [% i = i + 1 %] + + + [% i = i + 1 %] [% END %] - + Cancel
          [% END # / IF op == 'cud-create' %] - + + [% END # /IF !backends_available %] - - - - + + + + + + + + [% INCLUDE 'opac-bottom.inc' %] @@ -358,7 +353,7 @@ [% IF op == 'availability' %] [% Asset.js("js/ill-availability.js") | $raw %] diff --git a/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-imageviewer.tt b/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-imageviewer.tt index e934144631..c03567dcfc 100644 --- a/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-imageviewer.tt +++ b/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-imageviewer.tt @@ -9,29 +9,29 @@ [% BLOCK cssinclude %] [% END %] @@ -39,69 +39,77 @@ [% INCLUDE 'bodytag.inc' bodyid='opac-imageviewer' %] [% INCLUDE 'masthead.inc' %] -
          - [% WRAPPER breadcrumbs %] - [% WRAPPER breadcrumb_item %] - [% INCLUDE 'biblio-title.inc' link = 1 %] - [% END %] - [% WRAPPER breadcrumb_item bc_active= 1 %] - Images - [% END %] - [% END #/ WRAPPER breadcrumbs %] +
          + [% WRAPPER breadcrumbs %] + [% WRAPPER breadcrumb_item %] + [% INCLUDE 'biblio-title.inc' link = 1 %] + [% END %] + [% WRAPPER breadcrumb_item bc_active= 1 %] + Images + [% END %] + [% END #/ WRAPPER breadcrumbs %] -
          -
          - [% SET column_class = "col order-first order-md-first order-lg-2" %] - [% IF ( OpacNav || OpacNavBottom ) %] - [% column_class = "col-10 order-first order-md-first order-lg-2" %] -
          - +
          +
          + [% SET column_class = "col order-first order-md-first order-lg-2" %] + [% IF ( OpacNav || OpacNavBottom ) %] + [% column_class = "col-10 order-first order-md-first order-lg-2" %] +
          + +
          + [% END %] + +
          +
          +
          +

          Images for [% INCLUDE 'biblio-title.inc' link=> 1 %] [% biblio.author | html %]

          - [% END %] + +
          + -
          -
          -
          -

          Images for [% INCLUDE 'biblio-title.inc' link=> 1 %] [% biblio.author | html %] -

          -
          -
          +
          +
          +
          +
          + +
          +
          + +
          + -
          -
          -
          -
          - -
          -
          -
          - - [% IF OPACLocalCoverImages == 1 %] - [% IF images.size %] -
          -
          - [% FOREACH image IN images %] - + [% IF OPACLocalCoverImages == 1 %] + [% IF images.size %] + - [% END %] - [% ELSE %] - Unfortunately, images are not enabled for this catalog at this time. + + [% END %] +
          + +
          + [% END %] -
          -
          -
          -
          -
          + [% ELSE %] + Unfortunately, images are not enabled for this catalog at this time. + [% END %] +
          + +
          + +
          + +
          + +
          + [% INCLUDE 'opac-bottom.inc' %] [% BLOCK jsinclude %] diff --git a/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-issue-note.tt b/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-issue-note.tt index bbc73e9a72..dee76e666c 100644 --- a/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-issue-note.tt +++ b/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-issue-note.tt @@ -8,7 +8,8 @@ [% INCLUDE 'doc-head-open.inc' %] Editing checkout note for [% title | html %] › [% IF ( LibraryNameTitle ) %][% LibraryNameTitle | html %][% ELSE %]Koha online[% END %] catalog [% INCLUDE 'doc-head-close.inc' %] -[% BLOCK cssinclude %][% END %] +[% BLOCK cssinclude %] +[% END %] [% INCLUDE 'bodytag.inc' bodyid='opac-issue-note' %] [% INCLUDE 'masthead.inc' %] @@ -26,43 +27,46 @@ Editing checkout note for '[% title | html %]' [% author | html %] - + +
          - +

          Editing checkout note for [% title | html %] [% author | html %]

          - [% IF not(Koha.Preference("AllowCheckoutNotes")) %] - Checkout notes have not been enabled. Please contact the library. - [% ELSE %] -
          - [% INCLUDE 'csrf-token.inc' %] - Edit checkout note -
          - - - - - - -
          -
          - Cancel -
          -
          - [% END %] -
          -
          -
          -
          - -
          + [% IF not(Koha.Preference("AllowCheckoutNotes")) %] + Checkout notes have not been enabled. Please contact the library. + [% ELSE %] +
          + [% INCLUDE 'csrf-token.inc' %] + Edit checkout note +
          + + + + + + +
          +
          Cancel
          +
          + + [% END %] + + + + + + + + + + [% INCLUDE 'opac-bottom.inc' %] -[% BLOCK jsinclude %][% END %] +[% BLOCK jsinclude %] +[% END %] diff --git a/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-library.tt b/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-library.tt index 0ec0f5ae1b..5eb981e67c 100644 --- a/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-library.tt +++ b/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-library.tt @@ -8,16 +8,17 @@ [% SET OpacNavBottom = AdditionalContents.get( location => "OpacNavBottom", lang => lang, library => logged_in_user.branchcode || default_branch, blocktitle => 0 ) %] [% INCLUDE 'doc-head-open.inc' %] - [% IF ( library ) %] - [% library.branchname | html %] › + [% IF ( library ) %] + [% library.branchname | html %] + › [% END %] - Libraries - › -[% IF ( LibraryNameTitle ) %] + Libraries › + [% IF ( LibraryNameTitle ) %] [% LibraryNameTitle | html %] [% ELSE %] Koha online - [% END %] catalog + [% END %] + catalog [% INCLUDE 'doc-head-close.inc' %] [% BLOCK cssinclude %] @@ -26,7 +27,7 @@ margin-top: 1rem; margin-bottom: 1rem; border: 0; - border-bottom: 1px solid rgba(0,0,0,.1); + border-bottom: 1px solid rgba(0, 0, 0, 0.1); } [% END %] @@ -36,15 +37,12 @@ [% INCLUDE 'masthead.inc' %] [% BLOCK library_description %] -
          - [% IF OpacLibraryInfo %][% OpacLibraryInfo.content | $raw %][% END %] -
          +
          [% IF OpacLibraryInfo %][% OpacLibraryInfo.content | $raw %][% END %]
          [% END %] [% BLOCK library_info %] -
          - [% PROCESS 'display-library-address' %] -
          +
          [% PROCESS 'display-library-address' %]
          + [% IF ( library.branchphone ) %]

          Phone: [% library.branchphone | html %]

          [% END %] @@ -82,53 +80,54 @@ [% IF ( OpacNav || OpacNavBottom ) %] [% column_class = "col-10 order-first order-md-first order-lg-2" %]
          - +
          [% END %]
          - [% IF ( library ) %] -
          -

          [% library.branchname | html %]

          -
          -
          - [% PROCESS library_info %] - [% IF ( OpacLibraryInfo ) %] -
          -
          - [% PROCESS library_description %] -
          - [% END %] + [% IF ( library ) %] +
          +

          [% library.branchname | html %]

          +
          +
          + [% PROCESS library_info %] + [% IF ( OpacLibraryInfo ) %] +
          +
          + [% PROCESS library_description %] +
          + [% END %] +
          -
          - - [% ELSE %] -
          -

          Libraries

          - [% SET div_class = "section_library" %] - [% FOREACH library IN libraries %] - [% IF ( branchcode == library.branchcode ) %] - [% div_class = "section_library current" %] + + [% ELSE %] +
          +

          Libraries

          + [% SET div_class = "section_library" %] + [% FOREACH library IN libraries %] + [% IF ( branchcode == library.branchcode ) %] + [% div_class = "section_library current" %] + [% END %] +
          +

          + [% library.branchname | html %] +

          + [% PROCESS library_info %] +
          [% END %] -
          -

          - - [% library.branchname | html %] - -

          - [% PROCESS library_info %] -
          - [% END %] -
          - [% END # /IF library %] - -
          -
          -
          -
          + + + [% END # /IF library %] + + + + + + + + [% INCLUDE 'opac-bottom.inc' %] -[% BLOCK jsinclude %][% END %] +[% BLOCK jsinclude %] +[% END %] diff --git a/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-main.tt b/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-main.tt index f50539628c..476bc3c323 100644 --- a/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-main.tt +++ b/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-main.tt @@ -17,7 +17,8 @@ [% IF ( LibraryNameTitle ) %][% LibraryNameTitle | html %][% ELSE %]Koha online[% END %] catalog [% INCLUDE 'doc-head-close.inc' %] -[% BLOCK cssinclude %][% END %] +[% BLOCK cssinclude %] +[% END %] [% INCLUDE 'bodytag.inc' bodyid='opac-main' %] [% INCLUDE 'masthead.inc' %] @@ -29,6 +30,7 @@ [% news_item.title | html %] [% END %] [% ELSE %] + [% END %] [% END #/ WRAPPER breadcrumbs %] @@ -37,276 +39,274 @@ [% container_id = "loggedin" %] [% END %]
          - -
          - [% IF ( OpacNav || OpacNavBottom ) %] -
          - -
          -
          + [% UNLESS news_id %] + + [% END %] +
          + [% ELSIF news_id %] + +
          This news item does not exist.
          + [% ELSE %] + + [% IF Koha.Preference( 'OpacNewsLibrarySelect' ) %] +
          +
          +
          No news to display.
          +
          +
          +
          + [% END %] + [% END # IF koha_news %] + + [% UNLESS news_item # Don't show under single news item %] + [% IF ( daily_quote ) %] +
          +

          Quote of the day

          +
          [% daily_quote.text | html %] ~ [% daily_quote.source | html %]
          +
          + [% END %] + + [% IF ( OpacMainUserBlock ) %] + [% PROCESS koha_news_block news => OpacMainUserBlock %] + [% END %] + [% END %] + + + + [% IF ( ( Koha.Preference( 'opacuserlogin' ) == 1 ) || OpacNavRight ) %] +
          + [% IF Koha.Preference( 'opacuserlogin' ) == 1 %] + [% UNLESS ( loggedinusername ) %] + [% UNLESS ( casAuthentication || shibbolethAuthentication || Koha.Preference('opacShibOnly') ) %] +
          +
          + [% INCLUDE 'csrf-token.inc' %] + +
          + Log in to your account: + [% IF ( Koha.Preference('GoogleOpenIDConnect') == 1 ) %] + Log in with Google +

          If you do not have a Google account, but do have a local account, you can still log in:

          + [% END # /IF GoogleOpenIDConnect %] + [% SET identity_providers = AuthClient.get_providers('opac') %] + [% IF ( ! identity_providers.empty ) %] + [% FOREACH provider IN identity_providers %] +

          + + [% IF provider.icon_url %] + + [% ELSE %] + + [% END %] + Log in with [% provider.description | html %] + +

          + [% END %] +
          +

          If you do not have an external account, but do have a local account, you can still log in:

          + [% END # /IF identity_providers.size %] + + [% IF ( OpacLoginInstructions ) %] +
          [% PROCESS koha_news_block news => OpacLoginInstructions %]
          + [% END %] + [% IF Koha.Preference('OpacPasswordChange') && Categories.can_any_reset_password %] + + [% END %] + [% IF Koha.Preference('PatronSelfRegistration') && Categories.all( categorycode => Koha.Preference('PatronSelfRegistrationDefaultCategory') ).count %] + + [% END %] +
          +
          +
          + + [% END # /casAuthentication %] + [% ELSE %] + [% IF Koha.Preference('OPACUserSummary') && dashboard_info %] + + [% END %] + [% END # /loggedinusername %] + [% END # /opacuserlogin %] + [% PROCESS koha_news_block news => OpacNavRight %] +
          + + [% END # /opacuserlogin || OpacNavRight %] + + + + + + [% INCLUDE 'opac-bottom.inc' %] -[% BLOCK jsinclude %][% END %] +[% BLOCK jsinclude %] +[% END %] diff --git a/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-memberentry-update-submitted.tt b/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-memberentry-update-submitted.tt index 09214b7840..72c095a80d 100644 --- a/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-memberentry-update-submitted.tt +++ b/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-memberentry-update-submitted.tt @@ -6,47 +6,50 @@ [% INCLUDE 'doc-head-open.inc' %] Updates submitted › [% IF ( LibraryNameTitle ) %][% LibraryNameTitle | html %][% ELSE %]Koha online[% END %] catalog [% INCLUDE 'doc-head-close.inc' %] -[% BLOCK cssinclude %][% END %] +[% BLOCK cssinclude %] +[% END %] [% INCLUDE 'bodytag.inc' bodyid='opac-patron-update-submitted' %] [% INCLUDE 'masthead.inc' %] -
          +
          + [% WRAPPER breadcrumbs %] + [% WRAPPER breadcrumb_item %] + [% INCLUDE 'patron-title.inc' patron = logged_in_user %] + [% END %] + [% WRAPPER breadcrumb_item %] + Your personal details + [% END %] + [% WRAPPER breadcrumb_item bc_active= 1 %] + Updates submitted + [% END %] + [% END #/ WRAPPER breadcrumbs %] - [% WRAPPER breadcrumbs %] - [% WRAPPER breadcrumb_item %] - [% INCLUDE 'patron-title.inc' patron = logged_in_user %] - [% END %] - [% WRAPPER breadcrumb_item %] - Your personal details - [% END %] - [% WRAPPER breadcrumb_item bc_active= 1 %] - Updates submitted - [% END %] - [% END #/ WRAPPER breadcrumbs %] - -
          -
          -
          - + +
          + +
          + +
          + [% INCLUDE 'opac-bottom.inc' %] -[% BLOCK jsinclude %][% END %] +[% BLOCK jsinclude %] +[% END %] diff --git a/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-memberentry.tt b/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-memberentry.tt index cba9749df1..c86f9f39e1 100644 --- a/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-memberentry.tt +++ b/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-memberentry.tt @@ -33,20 +33,20 @@ [% END %] [% INCLUDE 'doc-head-open.inc' %] - [% IF op == 'edit' %]Update your personal details[% ELSE %]Register a new account[% END %] › [% IF ( LibraryNameTitle ) %][% LibraryNameTitle | html %][% ELSE %]Koha online[% END %] catalog +[% IF op == 'edit' %]Update your personal details[% ELSE %]Register a new account[% END %] › [% IF ( LibraryNameTitle ) %][% LibraryNameTitle | html %][% ELSE %]Koha online[% END %] catalog [% INCLUDE 'doc-head-close.inc' %] -[% BLOCK cssinclude %][% END %] +[% BLOCK cssinclude %] +[% END %] [% IF op == 'edit' %] -[% INCLUDE 'bodytag.inc' bodyid='opac-patron-update' %] + [% INCLUDE 'bodytag.inc' bodyid='opac-patron-update' %] [% ELSE %] - + [% END %] [% INCLUDE 'masthead.inc' %]
          - [% WRAPPER breadcrumbs %] [% IF op == 'edit' %] [% WRAPPER breadcrumb_item %] @@ -65,12 +65,9 @@
          - +
          -

          Your personal details

          [% SET container_id = "add-content" %] @@ -78,200 +75,230 @@ [% container_id = "update-account" %] [% END %]
          - - [% IF op == 'edit' %] - [% UNLESS OPACPatronDetails %] -
          To make changes to your record please contact the library.
          - [% END %] - [% IF nochanges %] -
          No changes were made.
          - [% END %] - [% END %] - - [% IF empty_mandatory_fields %] -
          You have not filled out all required fields. Please fill in all missing fields and resubmit.
          - [% END %] - - [% IF invalid_form_fields %] -
          The following fields contain invalid information: -
            - [% FOREACH field IN invalid_form_fields %] - [% IF field == "email" %]
          • Contact information: primary email address
          • [% END %] - [% IF field == "emailpro" %]
          • Contact information: secondary email address
          • [% END %] - [% IF field == "B_email" %]
          • Alternate address information: email address
          • [% END %] - [% IF field == "password_match" %]
          • Passwords do not match! password
          • [% END %] - [% IF field == "password_too_short" %] -
          • Password must be at least [% patron.category.effective_min_password_length | html %] characters long.
          • - [% END %] - [% IF field == "password_too_weak" %] -
          • Password must contain at least one digit, one lowercase and one uppercase.
          • - [% END %] - [% IF field == "password_has_whitespaces" %] -
          • Password must not contain leading or trailing whitespaces.
          • - [% END %] - [% IF field == "duplicate_email" %] -
          • This email address already exists in our database.
          • - [% END %] - [% IF field == "email_match" %] -
          • Emails do not match! confirm email address
          • - [% END %] - [% IF field == "ERROR_age_limitations" %] -
          • Patron's age is incorrect for their category.
          • - [% END %] - [% END %] -
          - Please correct and resubmit. -
          - [% END %] - - [% IF cardnumber_wrong_length || cardnumber_already_exists %] -
          - [% IF cardnumber_wrong_length %] - The entered card number is the wrong length. - [% ELSIF cardnumber_already_exists %] - The entered card number is already in use. + [% IF op == 'edit' %] + [% UNLESS OPACPatronDetails %] +
          To make changes to your record please contact the library.
          [% END %] - Please correct and resubmit. -
          - [% END %] - - [% IF error_type OR error_info %] -
        • -

          There were problems processing your registration. Please contact your library for help.

          - [% IF error_type == 'Koha::Exceptions::Patron::InvalidUserid' %] -

          Error: Userid is not valid

          - [% ELSE %] -

          Error [% error_type | html %]: [% error_info | html %]

          + [% IF nochanges %] +
          No changes were made.
          [% END %] -
        • - [% END %] + [% END %] - [% IF failed_captcha %] -
          You typed in the wrong characters in the box before submitting. Please try again.
          - [% END %] + [% IF empty_mandatory_fields %] +
          You have not filled out all required fields. Please fill in all missing fields and resubmit.
          + [% END %] - [% IF has_guarantor_flag && !Koha.Preference('OPACPrivacy') && ( Koha.Preference('AllowPatronToSetCheckoutsVisibilityForGuarantor') || Koha.Preference('AllowPatronToSetFinesVisibilityForGuarantor') ) %] -
          -
          -
          - Privacy -
            - [% IF Koha.Preference('AllowPatronToSetCheckoutsVisibilityForGuarantor') %] -
          1. - - - - Update - - -
          2. + [% IF invalid_form_fields %] +
            The following fields contain invalid information: +
              + [% FOREACH field IN invalid_form_fields %] + [% IF field == "email" %]
            • Contact information: primary email address
            • [% END %] + [% IF field == "emailpro" %]
            • Contact information: secondary email address
            • [% END %] + [% IF field == "B_email" %]
            • Alternate address information: email address
            • [% END %] + [% IF field == "password_match" %]
            • Passwords do not match! password
            • [% END %] + [% IF field == "password_too_short" %] +
            • Password must be at least [% patron.category.effective_min_password_length | html %] characters long.
            • [% END %] - - [% IF Koha.Preference('AllowPatronToSetFinesVisibilityForGuarantor') %] -
            • - - - - Update - - -
            • + [% IF field == "password_too_weak" %] +
            • Password must contain at least one digit, one lowercase and one uppercase.
            • [% END %] - -
            • - - Guaranteed by - [% FOREACH gr IN patron.guarantor_relationships %] - [% SET g = gr.guarantor %] - [% g.preferred_name | html %] [% g.middle_name | html %] [% g.surname | html %] - [%- IF ! loop.last %], [% END %] - [% END %] - -
            • -
          -
          + [% IF field == "password_has_whitespaces" %] +
        • Password must not contain leading or trailing whitespaces.
        • + [% END %] + [% IF field == "duplicate_email" %] +
        • This email address already exists in our database.
        • + [% END %] + [% IF field == "email_match" %] +
        • Emails do not match! confirm email address
        • + [% END %] + [% IF field == "ERROR_age_limitations" %] +
        • Patron's age is incorrect for their category.
        • + [% END %] + [% END %] + + Please correct and resubmit.
          -
          - [% END %] - - [% IF ( extended_unique_id_failed_code ) %] -
          [% extended_unique_id_failed_description _ ': ' | html %] Value is already in use ([% extended_unique_id_failed_value | html %])
          - [% END %] - -
          - [% INCLUDE 'csrf-token.inc' %] - - [% FOREACH field = ['streetnumber' 'streettype' 'cardnumber' 'branchcode' 'categorycode' 'title' 'surname' 'firstname' 'preferred_name' 'middle_name' 'dateofbirth' 'initials' 'pronouns' 'othernames' 'address' 'address2' 'city' 'state' 'zipcode' 'country' 'phone' 'phonepro' 'mobile' 'email' 'emailpro' 'fax' 'B_streettype' 'B_streetnumber' 'B_address' 'B_address2' 'B_city' 'B_state' 'B_zipcode' 'B_country' 'B_phone' 'B_email' 'contactnote' 'altcontactsurname' 'altcontactfirstname' 'altcontactaddress1' 'altcontactaddress2' 'altcontactaddress3' 'altcontactstate' 'altcontactzipcode' 'altcontactcountry' 'altcontactphone' 'password' 'lang' ] %] - [% IF mandatory.defined( field ) %] - [% SET required.$field = 'required' %] [% END %] - [% END %] - [%# Following on one line for translatability %] - [% UNLESS ( hidden.defined('cardnumber') || ( !borrower && Koha.Preference('autoMemberNum') ) ) && hidden.defined('dateexpiry') && hidden.defined('branchcode') && hidden.defined('categorycode') %] + [% IF cardnumber_wrong_length || cardnumber_already_exists %] +
          + [% IF cardnumber_wrong_length %] + The entered card number is the wrong length. + [% ELSIF cardnumber_already_exists %] + The entered card number is already in use. + [% END %] + Please correct and resubmit. +
          + [% END %] + + [% IF error_type OR error_info %] +
        • +

          There were problems processing your registration. Please contact your library for help.

          + [% IF error_type == 'Koha::Exceptions::Patron::InvalidUserid' %] +

          Error: Userid is not valid

          + [% ELSE %] +

          Error [% error_type | html %]: [% error_info | html %]

          + [% END %] +
        • + [% END %] + + [% IF failed_captcha %] +
          You typed in the wrong characters in the box before submitting. Please try again.
          + [% END %] + + [% IF has_guarantor_flag && !Koha.Preference('OPACPrivacy') && ( Koha.Preference('AllowPatronToSetCheckoutsVisibilityForGuarantor') || Koha.Preference('AllowPatronToSetFinesVisibilityForGuarantor') ) %]
          -
          +
          + Privacy +
            + [% IF Koha.Preference('AllowPatronToSetCheckoutsVisibilityForGuarantor') %] +
          1. + + + + Update + + +
          2. + [% END %] - Library + [% IF Koha.Preference('AllowPatronToSetFinesVisibilityForGuarantor') %] +
          3. + + + + Update + + +
          4. + [% END %] + +
          5. + + Guaranteed by + [% FOREACH gr IN patron.guarantor_relationships %] + [% SET g = gr.guarantor %] + [% g.preferred_name | html %] + [% g.middle_name | html %] + [% g.surname | html %] + [%- IF ! loop.last %],[% END %] + [% END %] + +
          6. +
          +
          +
          +
          + [% END %] + + [% IF ( extended_unique_id_failed_code ) %] +
          [% extended_unique_id_failed_description _ ': ' | html %] Value is already in use ([% extended_unique_id_failed_value | html %])
          + [% END %] + + + [% INCLUDE 'csrf-token.inc' %] + + [% FOREACH field = ['streetnumber' 'streettype' 'cardnumber' 'branchcode' 'categorycode' 'title' 'surname' 'firstname' 'preferred_name' 'middle_name' 'dateofbirth' 'initials' 'pronouns' 'othernames' 'address' 'address2' 'city' 'state' 'zipcode' 'country' 'phone' 'phonepro' 'mobile' 'email' 'emailpro' 'fax' 'B_streettype' 'B_streetnumber' 'B_address' 'B_address2' 'B_city' 'B_state' 'B_zipcode' 'B_country' 'B_phone' 'B_email' 'contactnote' 'altcontactsurname' 'altcontactfirstname' 'altcontactaddress1' 'altcontactaddress2' 'altcontactaddress3' 'altcontactstate' 'altcontactzipcode' 'altcontactcountry' 'altcontactphone' 'password' 'lang' ] %] + [% IF mandatory.defined( field ) %] + [% SET required.$field = 'required' %] + [% END %] + [% END %] + + [%# Following on one line for translatability %] + [% UNLESS ( hidden.defined('cardnumber') || ( !borrower && Koha.Preference('autoMemberNum') ) ) && hidden.defined('dateexpiry') && hidden.defined('branchcode') && hidden.defined('categorycode') %] +
          +
          +
          + Library
            [% UNLESS hidden.defined('cardnumber') || ( !borrower && Koha.Preference('autoMemberNum') ) %] -
          1. +
          2. + - - - [% IF borrower && !(cardnumber_wrong_length || cardnumber_already_exists) && op == 'edit' %] - [% borrower.cardnumber | html %] - [% ELSE %] - [% IF minlength_cardnumber == maxlength_cardnumber %] - -
            Required
            -
            Card number must be exactly [% minlength_cardnumber | html %] characters.
            - [% ELSIF minlength_cardnumber && maxlength_cardnumber %] - -
            Required
            -
            Card number must be between [% minlength_cardnumber | html %] and [% maxlength_cardnumber | html %] characters.
            - [% ELSIF maxlength_cardnumber %] - -
            Required
            -
            Card number can be up to [% maxlength_cardnumber | html %] characters.
            + [% IF borrower && !(cardnumber_wrong_length || cardnumber_already_exists) && op == 'edit' %] + [% borrower.cardnumber | html %] [% ELSE %] - -
            Required
            -
            There is no minimum or maximum character length.
            + [% IF minlength_cardnumber == maxlength_cardnumber %] + +
            Required
            +
            Card number must be exactly [% minlength_cardnumber | html %] characters.
            + [% ELSIF minlength_cardnumber && maxlength_cardnumber %] + +
            Required
            +
            Card number must be between [% minlength_cardnumber | html %] and [% maxlength_cardnumber | html %] characters.
            + [% ELSIF maxlength_cardnumber %] + +
            Required
            +
            Card number can be up to [% maxlength_cardnumber | html %] characters.
            + [% ELSE %] + +
            Required
            +
            There is no minimum or maximum character length.
            + [% END %] [% END %] - [% END %] -
          3. + [% END %] [% IF op != 'new' %] [% UNLESS hidden.defined('userid') %] -
          4. - - [% borrower.userid | html %] -
          5. +
          6. + + [% borrower.userid | html %] +
          7. [% END %] [% END %] [% UNLESS hidden.defined('dateexpiry') %] -
          8. - - [% borrower.dateexpiry | $KohaDates %] -
          9. +
          10. + + [% borrower.dateexpiry | $KohaDates %] +
          11. [% END %] [% UNLESS hidden.defined('branchcode') %] @@ -304,8 +331,7 @@ [% UNLESS hidden.defined('categorycode') %]
          12. - + [% IF borrower %] [% Categories.GetName( borrower.categorycode ) | html %] @@ -314,9 +340,20 @@ @@ -326,986 +363,1010 @@ [% END %]
          -
          -
          - [% END # / defined 'branchcode' %] - - [%# Following on one line for translatability %] - [% UNLESS hidden.defined('title') && hidden.defined('surname') && hidden.defined('firstname') && hidden.defined('preferred_name') && hidden.defined('middle_name') && hidden.defined('dateofbirth') && hidden.defined('initials') && hidden.defined('pronouns') && hidden.defined('othernames') && hidden.defined('sex') %] -
          -
          -
          - Identity - -
            - [% UNLESS hidden.defined('title') || !Koha.Preference('BorrowersTitles') %] -
          1. - - - -
            Required
            -
          2. - [% END %] - - [% UNLESS hidden.defined('surname') %] -
          3. - - - -
            Required
            -
          4. - [% END %] - - [% UNLESS hidden.defined('firstname') %] -
          5. - - - -
            Required
            -
          6. - [% END %] - - [% UNLESS hidden.defined('middle_name') %] -
          7. - - - -
            Required
            -
          8. - [% END %] - - [% UNLESS hidden.defined('preferred_name') %] -
          9. - - - -
            Required
            -
          10. - [% END %] - - [% UNLESS hidden.defined('dateofbirth') %] -
          11. - - - - -
            Required
            -
          12. - [% END %] - - [% UNLESS hidden.defined('initials') %] -
          13. - - - -
            Required
            -
          14. - [% END %] - - [% UNLESS hidden.defined('pronouns') %] -
          15. - - - -
            Required
            -
          16. - [% END %] - - [% UNLESS hidden.defined('othernames') %] -
          17. - - - -
            Required
            -
          18. - [% END %] - - [% UNLESS hidden.defined('sex') %] -
          19. -
            - - [% IF borrower.sex == 'F' %] - - [% ELSE %] - - [% END %] - - - [% IF borrower.sex == 'M' %] - - [% ELSE %] - - [% END %] - - - [% IF borrower.sex == 'O' %] - - [% ELSE %] - - [% END %] - - - [% IF borrower.sex == '' %] - - [% ELSE %] - - [% END %] -
          20. - [% END %] -
          -
          -
          - [% IF ( display_patron_image ) %] -
          -

          - -

          - [% END %] -
          - [% END # /UNLESS fields hidden %] + +
          + + [% END # / defined 'branchcode' %] - [%# Following on one line for translatability %] - [% UNLESS hidden.defined('streetnumber') && hidden.defined('address') && hidden.defined('address2') && hidden.defined('city') && hidden.defined('state') && hidden.defined('zipcode') && hidden.defined('country') %] -
          -
          -
          - Main address + [%# Following on one line for translatability %] + [% UNLESS hidden.defined('title') && hidden.defined('surname') && hidden.defined('firstname') && hidden.defined('preferred_name') && hidden.defined('middle_name') && hidden.defined('dateofbirth') && hidden.defined('initials') && hidden.defined('pronouns') && hidden.defined('othernames') && hidden.defined('sex') %] +
          +
          +
          + Identity -
            - [% IF Koha.Preference('AddressFormat') != 'de' %][% INCLUDE streetnumber %][% END %] - - [% SET roadtypes = AuthorisedValues.GetAuthValueDropbox('ROADTYPE') %] - [% IF roadtypes.count %] - [% UNLESS hidden.defined('streettype') %] +
              + [% UNLESS hidden.defined('title') || !Koha.Preference('BorrowersTitles') %]
            1. - + - - [% FOR roadtype IN roadtypes %] - [% IF roadtype.authorised_value == patron.streettype %] - + [% FOREACH mt IN Koha.Preference('BorrowersTitles').split('\|') %] + [% IF mt == borrower.title %] + [% ELSE %] - + [% END %] [% END %] -
              Required
              +
              Required
            2. [% END %] - [% END %] - [% UNLESS hidden.defined('address') %] -
            3. - - - -
              Required
              -
            4. - [% END %] - - [% IF Koha.Preference('AddressFormat') == 'de' %][% INCLUDE streetnumber %][% END %] - - [% UNLESS hidden.defined('address2') %] -
            5. - - - -
              Required
              -
            6. - [% END %] - - [% UNLESS hidden.defined('city') %] -
            7. - - - -
              Required
              -
            8. - [% END %] - - [% UNLESS hidden.defined('state') %] -
            9. - - - -
              Required
              -
            10. - [% END %] - - [% UNLESS hidden.defined('zipcode') %] -
            11. - - - -
              Required
              -
            12. - [% END %] - - [% UNLESS hidden.defined('country') %] -
            13. - - - -
              Required
              -
            14. - [% END %] - -
            -
          -
          -
          - [% END %] - - [%# Following on one line for translatability %] - [% UNLESS hidden.defined('phone') && hidden.defined('phonepro') && hidden.defined('mobile') && hidden.defined('email') && hidden.defined('emailpro') && hidden.defined('fax') %] -
          -
          -
          - Contact information - -
            - [% UNLESS hidden.defined('phone') %] -
          1. - - - -
            Required
            -
          2. - [% END %] - - [% UNLESS hidden.defined('phonepro') %] -
          3. - - - -
            Required
            -
          4. - [% END %] - - [% UNLESS hidden.defined('mobile') %] -
          5. - - - -
            Required
            -
          6. - [% END %] - - [% UNLESS hidden.defined('email') %] -
          7. - - - -
            Required
            -
          8. - - [% IF op != 'edit' and Koha.Preference('PatronSelfRegistrationConfirmEmail') %] + [% UNLESS hidden.defined('surname') %]
          9. - + - + +
            Required
            +
          10. + [% END %] + + [% UNLESS hidden.defined('firstname') %] +
          11. + + + +
            Required
            +
          12. + [% END %] + + [% UNLESS hidden.defined('middle_name') %] +
          13. + + + +
            Required
            +
          14. + [% END %] + + [% UNLESS hidden.defined('preferred_name') %] +
          15. + + + +
            Required
            +
          16. + [% END %] + + [% UNLESS hidden.defined('dateofbirth') %] +
          17. + + + + +
            Required
            +
          18. + [% END %] + + [% UNLESS hidden.defined('initials') %] +
          19. + + + +
            Required
            +
          20. + [% END %] + + [% UNLESS hidden.defined('pronouns') %] +
          21. + + + +
            Required
            +
          22. + [% END %] + + [% UNLESS hidden.defined('othernames') %] +
          23. + + + +
            Required
            +
          24. + [% END %] + + [% UNLESS hidden.defined('sex') %] +
          25. +
            + + [% IF borrower.sex == 'F' %] + + [% ELSE %] + + [% END %] + + + [% IF borrower.sex == 'M' %] + + [% ELSE %] + + [% END %] + + + [% IF borrower.sex == 'O' %] + + [% ELSE %] + + [% END %] + + + [% IF borrower.sex == '' %] + + [% ELSE %] + + [% END %] +
          26. + [% END %] +
          +
          +
          + + [% IF ( display_patron_image ) %] +
          +

          + +

          +
          + [% END %] +
          + + [% END # /UNLESS fields hidden %] + + [%# Following on one line for translatability %] + [% UNLESS hidden.defined('streetnumber') && hidden.defined('address') && hidden.defined('address2') && hidden.defined('city') && hidden.defined('state') && hidden.defined('zipcode') && hidden.defined('country') %] +
          +
          +
          + Main address + +
            + [% IF Koha.Preference('AddressFormat') != 'de' %][% INCLUDE streetnumber %][% END %] + + [% SET roadtypes = AuthorisedValues.GetAuthValueDropbox('ROADTYPE') %] + [% IF roadtypes.count %] + [% UNLESS hidden.defined('streettype') %] +
          1. + + + +
            Required
            +
          2. + [% END %] + [% END %] + + [% UNLESS hidden.defined('address') %] +
          3. + + + +
            Required
            +
          4. + [% END %] + + [% IF Koha.Preference('AddressFormat') == 'de' %][% INCLUDE streetnumber %][% END %] + + [% UNLESS hidden.defined('address2') %] +
          5. + + + +
            Required
            +
          6. + [% END %] + + [% UNLESS hidden.defined('city') %] +
          7. + + + +
            Required
            +
          8. + [% END %] + + [% UNLESS hidden.defined('state') %] +
          9. + + + +
            Required
            +
          10. + [% END %] + + [% UNLESS hidden.defined('zipcode') %] +
          11. + + + +
            Required
            +
          12. + [% END %] + + [% UNLESS hidden.defined('country') %] +
          13. + + + +
            Required
            +
          14. + [% END %] +
          +
          +
          + +
          + + [% END %] + + [%# Following on one line for translatability %] + [% UNLESS hidden.defined('phone') && hidden.defined('phonepro') && hidden.defined('mobile') && hidden.defined('email') && hidden.defined('emailpro') && hidden.defined('fax') %] +
          +
          +
          + Contact information + +
            + [% UNLESS hidden.defined('phone') %] +
          1. + + + +
            Required
            +
          2. + [% END %] + + [% UNLESS hidden.defined('phonepro') %] +
          3. + + + +
            Required
            +
          4. + [% END %] + + [% UNLESS hidden.defined('mobile') %] +
          5. + + + +
            Required
            +
          6. + [% END %] + + [% UNLESS hidden.defined('email') %] +
          7. + + +
            Required
          8. - [% END %] - [% END %] - [% UNLESS hidden.defined('emailpro') %] -
          9. - + [% IF op != 'edit' and Koha.Preference('PatronSelfRegistrationConfirmEmail') %] +
          10. + - -
            Required
            -
          11. - [% END %] - - [% UNLESS hidden.defined('fax') %] -
          12. - - - -
            Required
            -
          13. - [% END %] - - [% UNLESS hidden.defined('primary_contact_method') %] -
          14. - [% IF ( mandatory.defined('primary_contact_method') ) %] - - [% ELSE %] - + +
            Required
            +
          15. [% END %] + [% END %] - - [% IF ( mandatory.defined('primary_contact_method') ) %]Required[% END %] - - [% UNLESS hidden.defined('lang') %] + [% UNLESS hidden.defined('emailpro') %]
          16. - [% IF ( mandatory.defined('lang') ) %] - - [% ELSE %] - - [% END %] - - [% IF ( mandatory.defined('lang') ) %]
            Required
            [% END %] + + + +
            Required
          17. [% END %] - [% END %] -
          -
          -
          -
          - [% END %] - [%# Following on one line for translatability %] - [% UNLESS hidden.defined('B_streetnumber') && hidden.defined('B_address') && hidden.defined('B_address2') && hidden.defined('B_city') && hidden.defined('B_state') && hidden.defined('B_zipcode') && hidden.defined('B_country') && hidden.defined('B_phone') && hidden.defined('B_email') && hidden.defined('contactnote') %] -
          -
          -
          - Alternate address - -
            - [% IF Koha.Preference('AddressFormat') != 'de' %][% INCLUDE B_streetnumber %][% END %] - - [% SET roadtypes = AuthorisedValues.GetAuthValueDropbox('ROADTYPE') %] - [% IF roadtypes.count %] - [% UNLESS hidden.defined('B_streettype') %] + [% UNLESS hidden.defined('fax') %]
          1. - + - +
            Required
            +
          2. + [% END %] + + [% UNLESS hidden.defined('primary_contact_method') %] +
          3. + [% IF ( mandatory.defined('primary_contact_method') ) %] + + [% ELSE %] + + [% END %] + + -
            Required
            + [% IF ( mandatory.defined('primary_contact_method') ) %]Required[% END %]
          4. - [% END %] - [% END %] - [% UNLESS hidden.defined('B_address') %] -
          5. - - - -
            Required
            -
          6. - [% END %] - - [% IF Koha.Preference('AddressFormat') == 'de' %][% INCLUDE streetnumber %][% END %] - - [% UNLESS hidden.defined('B_address2') %] -
          7. - - - -
            Required
            -
          8. - [% END %] - - [% UNLESS hidden.defined('B_city') %] -
          9. - - - -
            Required
            -
          10. - [% END %] - - [% UNLESS hidden.defined('B_state') %] -
          11. - - - -
            Required
            -
          12. - [% END %] - - [% UNLESS hidden.defined('B_zipcode') %] -
          13. - - - -
            Required
            -
          14. - [% END %] - - [% UNLESS hidden.defined('B_country') %] -
          15. - - - -
            Required
            -
          16. - [% END %] - - [% UNLESS hidden.defined('B_phone') %] -
          17. - - - -
            Required
            -
          18. - [% END %] - - [% UNLESS hidden.defined('B_email') %] -
          19. - - - -
            Required
            -
          20. - [% END %] - - [% UNLESS hidden.defined('contactnote') %] -
          21. - - - -
            Required
            -
          22. - [% END %] - -
          -
          -
          -
          - [% END %] - - [%# Following on one line for translatability %] - [% UNLESS hidden.defined('altcontactsurname') && hidden.defined('altcontactfirstname') && hidden.defined('altcontactaddress1') && hidden.defined('altcontactaddress2') && hidden.defined('altcontactaddress3') && hidden.defined('altcontactstate') && hidden.defined('altcontactzipcode') && hidden.defined('altcontactcountry') && hidden.defined('altcontactphone') %] -
          -
          -
          - Alternate contact - -
            - [% UNLESS hidden.defined('altcontactsurname') %] -
          1. - - - -
            Required
            -
          2. - [% END %] - - [% UNLESS hidden.defined('altcontactfirstname') %] -
          3. - - - -
            Required
            -
          4. - [% END %] - - [% UNLESS hidden.defined('altcontactaddress1') %] -
          5. - - - -
            Required
            -
          6. - [% END %] - - [% UNLESS hidden.defined('altcontactaddress2') %] -
          7. - - - -
            Required
            -
          8. - [% END %] - - [% UNLESS hidden.defined('altcontactaddress3') %] -
          9. - - - -
            Required
            -
          10. - [% END %] - - [% UNLESS hidden.defined('altcontactstate') %] -
          11. - - - -
            Required
            -
          12. - [% END %] - - [% UNLESS hidden.defined('altcontactzipcode') %] -
          13. - - - -
            Required
            -
          14. - [% END %] - - [% UNLESS hidden.defined('altcontactcountry') %] -
          15. - - - -
            Required
            -
          16. - [% END %] - - [% UNLESS hidden.defined('altcontactphone') %] -
          17. - - - -
            Required
            -
          18. - [% END %] -
          -
          -
          -
          - [% END %] - - [% UNLESS op == 'edit' || hidden.defined('password') %] -
          -
          -
          - Password -
          - [% IF patron %] - [% IF ( patron.category.effective_require_strong_password ) %] -

          Your password must contain at least [% patron.category.effective_min_password_length | html %] characters, including UPPERCASE, lowercase and numbers.

          - [% ELSE %] -

          Your password must be at least [% patron.category.effective_min_password_length | html %] characters long.

          - [% END %] - [% ELSE %] -

          - [% END %] - [% UNLESS mandatory.defined('password') %] -

          If you do not enter a password a system generated password will be created.

          - [% END %] -
          - -
            -
          1. - -
            Required
            -
          2. -
          3. - -
            Required
            -
          4. -
          -
          -
          -
          - [% END %] - - [% IF ( Koha.Preference('ExtendedPatronAttributes') && patron_attribute_classes.size ) %] -
          -
          - [% SET fieldset_id = "" %] - [% SET legend = "Additional information" %] - [% FOREACH pa_class IN patron_attribute_classes %] - [% IF pa_class.class %] - [% fieldset_id = "aai_" _ pa_loo.class %] - [% legend = pa_class.lib %] - [% END %] -
          - [% legend | html %] -
            - [% FOREACH pa IN pa_class.items %] - [% FOREACH pa_value IN pa.values %] - [% IF loop.first %][% END %] - [% form_id = 'patron-attr-' _ Math.int( Math.rand(1000000) ) %] -
          1. - [% IF pa.type.mandatory && pa.type.opac_editable %] - + [% UNLESS hidden.defined('lang') %] +
          2. + [% IF ( mandatory.defined('lang') ) %] + [% ELSE %] - + [% END %] - [% IF pa.type.opac_editable %] - - [% IF ( pa.type.authorised_value_category ) %] - + + [% FOR language IN languages %] + [% FOR sublanguage IN language.sublanguages_loop %] + [% IF language.plural %] + [% IF sublanguage.rfc4646_subtag == borrower.lang %] + [% ELSE %] - + [% END %] - [% END %] - - [% ELSE %] - [% IF ( pa.type.is_date && pa.type.mandatory ) %] - - [% ELSIF ( pa.type.is_date && !pa.type.mandatory ) %] - - [% ELSE %] - - [% END %] - [% END %] -
            - [% IF ( !pa.type.is_date ) %] - Clear - [% END %] - [% IF ( pa.type.repeatable ) %] - New - [% END %] - [% IF pa.type.mandatory %] - Required - [% END %] -
            - [% ELSE %] - [% IF ( pa.type.authorised_value_category ) %] - [% AuthorisedValues.GetByCode( pa.type.authorised_value_category, pa_value, 1 ) | html_line_break %] - [% ELSIF ( pa.type.is_date ) %] - [% pa_value | $KohaDates %] - [% ELSE %] - [% pa_value | html_line_break %] - [% END %] - [% END %] + [% ELSE %] + [% IF sublanguage.rfc4646_subtag == borrower.lang %] + + [% ELSE %] + + [% END %] + [% END # /IF language.plural %] + [% END # /FOR sublanguage %] + [% END #/FOR language %] + + + [% IF ( mandatory.defined('lang') ) %]
            Required
            [% END %]
          3. [% END %] [% END %]
          - [% END %] -
          -
          - [% END %] +
          + +
          + + [% END %] + + [%# Following on one line for translatability %] + [% UNLESS hidden.defined('B_streetnumber') && hidden.defined('B_address') && hidden.defined('B_address2') && hidden.defined('B_city') && hidden.defined('B_state') && hidden.defined('B_zipcode') && hidden.defined('B_country') && hidden.defined('B_phone') && hidden.defined('B_email') && hidden.defined('contactnote') %] +
          +
          +
          + Alternate address + +
            + [% IF Koha.Preference('AddressFormat') != 'de' %][% INCLUDE B_streetnumber %][% END %] + + [% SET roadtypes = AuthorisedValues.GetAuthValueDropbox('ROADTYPE') %] + [% IF roadtypes.count %] + [% UNLESS hidden.defined('B_streettype') %] +
          1. + + + +
            Required
            +
          2. + [% END %] + [% END %] + [% UNLESS hidden.defined('B_address') %] +
          3. + + + +
            Required
            +
          4. + [% END %] + + [% IF Koha.Preference('AddressFormat') == 'de' %][% INCLUDE streetnumber %][% END %] + + [% UNLESS hidden.defined('B_address2') %] +
          5. + + + +
            Required
            +
          6. + [% END %] + + [% UNLESS hidden.defined('B_city') %] +
          7. + + + +
            Required
            +
          8. + [% END %] + + [% UNLESS hidden.defined('B_state') %] +
          9. + + + +
            Required
            +
          10. + [% END %] + + [% UNLESS hidden.defined('B_zipcode') %] +
          11. + + + +
            Required
            +
          12. + [% END %] + + [% UNLESS hidden.defined('B_country') %] +
          13. + + + +
            Required
            +
          14. + [% END %] + + [% UNLESS hidden.defined('B_phone') %] +
          15. + + + +
            Required
            +
          16. + [% END %] + + [% UNLESS hidden.defined('B_email') %] +
          17. + + + +
            Required
            +
          18. + [% END %] + + [% UNLESS hidden.defined('contactnote') %] +
          19. + + + +
            Required
            +
          20. + [% END %] +
          +
          +
          + +
          + + [% END %] + + [%# Following on one line for translatability %] + [% UNLESS hidden.defined('altcontactsurname') && hidden.defined('altcontactfirstname') && hidden.defined('altcontactaddress1') && hidden.defined('altcontactaddress2') && hidden.defined('altcontactaddress3') && hidden.defined('altcontactstate') && hidden.defined('altcontactzipcode') && hidden.defined('altcontactcountry') && hidden.defined('altcontactphone') %] +
          +
          +
          + Alternate contact + +
            + [% UNLESS hidden.defined('altcontactsurname') %] +
          1. + + + +
            Required
            +
          2. + [% END %] + + [% UNLESS hidden.defined('altcontactfirstname') %] +
          3. + + + +
            Required
            +
          4. + [% END %] + + [% UNLESS hidden.defined('altcontactaddress1') %] +
          5. + + + +
            Required
            +
          6. + [% END %] + + [% UNLESS hidden.defined('altcontactaddress2') %] +
          7. + + + +
            Required
            +
          8. + [% END %] + + [% UNLESS hidden.defined('altcontactaddress3') %] +
          9. + + + +
            Required
            +
          10. + [% END %] + + [% UNLESS hidden.defined('altcontactstate') %] +
          11. + + + +
            Required
            +
          12. + [% END %] + + [% UNLESS hidden.defined('altcontactzipcode') %] +
          13. + + + +
            Required
            +
          14. + [% END %] + + [% UNLESS hidden.defined('altcontactcountry') %] +
          15. + + + +
            Required
            +
          16. + [% END %] + + [% UNLESS hidden.defined('altcontactphone') %] +
          17. + + + +
            Required
            +
          18. + [% END %] +
          +
          +
          + +
          + + [% END %] + + [% UNLESS op == 'edit' || hidden.defined('password') %] +
          +
          +
          + Password +
          + [% IF patron %] + [% IF ( patron.category.effective_require_strong_password ) %] +

          Your password must contain at least [% patron.category.effective_min_password_length | html %] characters, including UPPERCASE, lowercase and numbers.

          + [% ELSE %] +

          Your password must be at least [% patron.category.effective_min_password_length | html %] characters long.

          + [% END %] + [% ELSE %] +

          + [% END %] + [% UNLESS mandatory.defined('password') %] +

          If you do not enter a password a system generated password will be created.

          + [% END %] +
          + +
            +
          1. + +
            Required
            +
          2. +
          3. + +
            Required
            +
          4. +
          +
          +
          + +
          + + [% END %] + + [% IF ( Koha.Preference('ExtendedPatronAttributes') && patron_attribute_classes.size ) %] +
          +
          + [% SET fieldset_id = "" %] + [% SET legend = "Additional information" %] + [% FOREACH pa_class IN patron_attribute_classes %] + [% IF pa_class.class %] + [% fieldset_id = "aai_" _ pa_loo.class %] + [% legend = pa_class.lib %] + [% END %] +
          + [% legend | html %] +
            + [% FOREACH pa IN pa_class.items %] + [% FOREACH pa_value IN pa.values %] + [% IF loop.first %][% END %] + [% form_id = 'patron-attr-' _ Math.int( Math.rand(1000000) ) %] +
          1. + [% IF pa.type.mandatory && pa.type.opac_editable %] + + [% ELSE %] + + [% END %] + [% IF pa.type.opac_editable %] + + [% IF ( pa.type.authorised_value_category ) %] + + [% ELSE %] + [% IF ( pa.type.is_date && pa.type.mandatory ) %] + + [% ELSIF ( pa.type.is_date && !pa.type.mandatory ) %] + + [% ELSE %] + + [% END %] + [% END %] +
            + [% IF ( !pa.type.is_date ) %] + Clear + [% END %] + [% IF ( pa.type.repeatable ) %] + New + [% END %] + [% IF pa.type.mandatory %] + Required + [% END %] +
            + [% ELSE %] + [% IF ( pa.type.authorised_value_category ) %] + [% AuthorisedValues.GetByCode( pa.type.authorised_value_category, pa_value, 1 ) | html_line_break %] + [% ELSIF ( pa.type.is_date ) %] + [% pa_value | $KohaDates %] + [% ELSE %] + [% pa_value | html_line_break %] + [% END %] + [% END %] +
          2. + [% END %] + [% END %] +
          +
          + [% END %] +
          + +
          + + [% END %] + + [% IF Koha.Preference('PrivacyPolicyConsent') && op != 'edit' %] +
          +
          + +
          + +
          + + [% END %] + + [% UNLESS op == 'edit' %] +
          +
          +
          + Verification +
            +
          1. + + + +
            Required
            + + + Please type the following characters into the preceding box: [% captcha | html %] +
          2. +
          +
          +
          + +
          + + [% END %] - [% IF Koha.Preference('PrivacyPolicyConsent') && op != 'edit' %]
          - -
          -
          - [% END %] - - [% UNLESS op == 'edit' %] -
          -
          -
          - Verification -
            - -
          1. - - - -
            Required
            - - - Please type the following characters into the preceding box: [% captcha | html %] -
          2. -
          -
          -
          -
          - [% END %] - -
          -
          - [% IF op == 'edit' %] - [% IF OPACPatronDetails %] + [% IF op == 'edit' %] + [% IF OPACPatronDetails %] +
          + + +
          + [% END %] + [% ELSE %]
          - - + +
          [% END %] - [% ELSE %] -
          - - -
          - [% END %] -
          -
          - - - -
          -
          +
          + +
          + +
          + [% INCLUDE 'opac-bottom.inc' %] [% BLOCK jsinclude %] [% INCLUDE 'validator-strings.inc' %] [% Asset.js("lib/jquery/plugins/jquery.validate.min.js") | $raw %] [% INCLUDE 'calendar.inc' %] - [% PROCESS 'password_check.inc' new_password => 'borrower_password', category_selector => '#borrower_categorycode', RequireStrongPassword => patron ? patron.category.effective_require_strong_password : defaultCategory.effective_require_strong_password, minPasswordLength => patron ? patron.category.effective_min_password_length : defaultCategory.effective_min_password_length %] - [% END %] diff --git a/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-messaging.tt b/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-messaging.tt index 96d45a054d..115f5e5c89 100644 --- a/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-messaging.tt +++ b/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-messaging.tt @@ -6,13 +6,13 @@ [% INCLUDE 'doc-head-open.inc' %] Your messaging settings › [% IF ( LibraryNameTitle ) %][% LibraryNameTitle | html %][% ELSE %]Koha online[% END %] catalog [% INCLUDE 'doc-head-close.inc' %] -[% BLOCK cssinclude %][% END %] +[% BLOCK cssinclude %] +[% END %] [% INCLUDE 'bodytag.inc' bodyid='opac-messaging' %] [% INCLUDE 'masthead.inc' %]
          - [% WRAPPER breadcrumbs %] [% WRAPPER breadcrumb_item %] [% INCLUDE 'patron-title.inc' patron = logged_in_user %] @@ -25,23 +25,22 @@
          - +
          - [% IF Koha.Preference( 'EnhancedMessagingPreferencesOPAC' ) || Koha.Preference('TranslateNotices') %]

          Your messaging settings

          [% IF ( settings_updated ) %] -

          Settings updated

          +

          Settings updated

          [% END %]
          [% INCLUDE 'csrf-token.inc' %] - [% IF Koha.Preference( 'EnhancedMessagingPreferencesOPAC' ) %] + [% IF Koha.Preference( 'EnhancedMessagingPreferencesOPAC' ) %] @@ -52,136 +51,219 @@ [% IF ( TalkingTechItivaPhone ) %][% END %] [% IF Koha.Preference('PhoneNotification') %][% END %] - + - [% FOREACH messaging_preference IN messaging_preferences %] - [% NEXT IF !Koha.Preference( 'ILLModule' ) && messaging_preference.message_name.match('^Ill_') %] - [% NEXT IF !Koha.Preference('MembershipExpiryDaysNotice') && messaging_preference.Patron_Expiry %] - [% NEXT IF messaging_preference.Auto_Renewals && Koha.Preference('AutoRenewalNotices') != 'preferences' %] - [% NEXT IF !Koha.Preference('UseRecalls') && messaging_preference.message_name.match('^Recall_') %] - - + - [% IF ( messaging_preference.takes_days ) %] - + [% IF ( messaging_preference.takes_days ) %] + + [% ELSE %] + + [% END %] + [% IF ( SMSSendDriver ) %] + [% IF ( messaging_preference.transport_sms ) %] + [% ELSE %] - + [% END %] [% END %] - - [% ELSE %] - - [% END %] - [% IF ( SMSSendDriver ) %] - [% IF ( messaging_preference.transport_sms ) %] + [% IF Koha.Preference('PhoneNotification') %] + [% IF ( messaging_preference.transport_phone ) %] + + [% ELSE %] + + [% END %] + [% END %] + [% IF ( TalkingTechItivaPhone ) %] + [% IF ( messaging_preference.transport_itiva ) %] + + [% ELSE %] + + [% END %] + [% END %] + + [% IF ( messaging_preference.transport_email ) %] [% ELSE %] [% END %] - [% END %] - [% IF Koha.Preference('PhoneNotification') %] - [% IF ( messaging_preference.transport_phone ) %] + + [% IF ( messaging_preference.has_digest ) %] [% ELSE %] [% END %] - [% END %] - [% IF ( TalkingTechItivaPhone ) %] - [% IF ( messaging_preference.transport_itiva ) %] - - [% ELSE %] - - [% END %] - [% END %] - - [% IF ( messaging_preference.transport_email ) %] - - [% ELSE %] - - [% END %] - - [% IF ( messaging_preference.has_digest ) %] - - [% ELSE %] - - [% END %] - - - - [% END # / FOREACH messaging_preferences%] + + + [% END # / FOREACH messaging_preferences %]
          Your messaging settings
          PhonePhoneEmailDigests only Digests only +
          [% IF ( messaging_preference.Item_Due ) %]Item due - [% ELSIF ( messaging_preference.Advance_Notice ) %]Advance notice - [% ELSIF ( messaging_preference.Hold_Filled ) %]Hold filled - [% ELSIF ( messaging_preference.Hold_Reminder ) %]Hold reminder - [% ELSIF ( messaging_preference.Item_Check_in ) %]Item check-in - [% ELSIF ( messaging_preference.Item_Checkout ) %] - [% IF Koha.Preference( 'RenewalSendNotice' ) %] - Item checkout and renewal + [% FOREACH messaging_preference IN messaging_preferences %] + [% NEXT IF !Koha.Preference( 'ILLModule' ) && messaging_preference.message_name.match('^Ill_') %] + [% NEXT IF !Koha.Preference('MembershipExpiryDaysNotice') && messaging_preference.Patron_Expiry %] + [% NEXT IF messaging_preference.Auto_Renewals && Koha.Preference('AutoRenewalNotices') != 'preferences' %] + [% NEXT IF !Koha.Preference('UseRecalls') && messaging_preference.message_name.match('^Recall_') %] +
          [% IF ( messaging_preference.Item_Due ) %] + Item due + [% ELSIF ( messaging_preference.Advance_Notice ) %] + Advance notice + [% ELSIF ( messaging_preference.Hold_Filled ) %] + Hold filled + [% ELSIF ( messaging_preference.Hold_Reminder ) %] + Hold reminder + [% ELSIF ( messaging_preference.Item_Check_in ) %] + Item check-in + [% ELSIF ( messaging_preference.Item_Checkout ) %] + [% IF Koha.Preference( 'RenewalSendNotice' ) %] + Item checkout and renewal + [% ELSE %] + Item checkout + [% END %] + [% ELSIF ( messaging_preference.Patron_Expiry ) %] + Patron account expiry + [% ELSIF ( messaging_preference.Ill_ready ) %] + Interlibrary loan ready + [% ELSIF ( messaging_preference.Ill_unavailable ) %] + Interlibrary loan unavailable + [% ELSIF ( messaging_preference.Ill_update ) %] + Interlibrary loan updated + [% ELSIF ( messaging_preference.Auto_Renewals ) %] + Auto renewal + [% ELSIF ( messaging_preference.Recall_Waiting ) %] + Recall awaiting pickup + [% ELSIF ( messaging_preference.Recall_Requested ) %] + Return recalled item [% ELSE %] - Item checkout - [% END %] - [% ELSIF ( messaging_preference.Patron_Expiry ) %]Patron account expiry - [% ELSIF ( messaging_preference.Ill_ready ) %]Interlibrary loan ready - [% ELSIF ( messaging_preference.Ill_unavailable ) %]Interlibrary loan unavailable - [% ELSIF ( messaging_preference.Ill_update ) %]Interlibrary loan updated - [% ELSIF ( messaging_preference.Auto_Renewals ) %]Auto renewal - [% ELSIF ( messaging_preference.Recall_Waiting ) %]Recall awaiting pickup - [% ELSIF ( messaging_preference.Recall_Requested ) %]Return recalled item - [% ELSE %]Unknown [% END %]- + [% IF ( messaging_preference.transports_sms ) %] + + [% ELSE %] + + [% END %] + -- + [% IF ( messaging_preference.transports_phone ) %] + + [% ELSE %] + + [% END %] + - + [% IF ( messaging_preference.transports_itiva ) %] + + [% ELSE %] + + [% END %] + - - [% IF ( messaging_preference.transports_sms ) %] - + [% IF ( messaging_preference.transports_email ) %] + [% ELSE %] - + [% END %] - - [% IF ( messaging_preference.transports_phone ) %] - + [% IF ( messaging_preference.digest ) %] + [% ELSE %] - + [% END %] - - [% IF ( messaging_preference.transports_itiva ) %] - - [% ELSE %] - - [% END %] - - - [% IF ( messaging_preference.transports_email ) %] - - [% ELSE %] - - [% END %] - - - [% IF ( messaging_preference.digest ) %] - - [% ELSE %] - - [% END %] - -
          [% END %] @@ -190,9 +272,7 @@
            [% IF ( SMSSendDriver ) %] -
          1. - Notice: Some charges for text messages may be incurred when using this service. Please check with your mobile service provider if you have questions. -
          2. +
          3. Notice: Some charges for text messages may be incurred when using this service. Please check with your mobile service provider if you have questions.
          4. @@ -226,9 +306,13 @@ [% FOR sublanguage IN language.sublanguages_loop %] [% IF language.plural %] [% IF sublanguage.rfc4646_subtag == patron_lang %] - + [% ELSE %] - + [% END %] [% ELSE %] [% IF sublanguage.rfc4646_subtag == patron_lang %] @@ -239,7 +323,8 @@ [% END # /IF language.plural %] [% END # /FOR sublanguage %] [% END #/FOR language %] - + +
          5. [% END #/IF Koha.Preference('TranslateNotices') %]
          @@ -251,14 +336,19 @@ Cancel
          -
          +
          + [% ELSE %] -

          You are not allowed to call this page directly

          +

          You are not allowed to call this page directly

          [% END # /IF Koha.Preference( 'EnhancedMessagingPreferencesOPAC' ) %] -
          -
          -
          - + + + + + + + + [% INCLUDE 'opac-bottom.inc' %] [% BLOCK jsinclude %] diff --git a/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-mymessages.tt b/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-mymessages.tt index d83e47f17a..0f7a98f2c3 100644 --- a/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-mymessages.tt +++ b/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-mymessages.tt @@ -1,28 +1,28 @@ - - - + + + - - - - - - - - - [% FOREACH message_lis IN message_list %] - - [% message_lis.subject | html %] - + + + + + + + + + [% FOREACH message_lis IN message_list %] + + [% message_lis.subject | html %] + [% message_lis.title | html %] - [% message_lis.content | html %] - [% message_lis.time_queued | html %] - [% message_lis.title | html %] - - [% END %] - + [% message_lis.content | html %] + [% message_lis.time_queued | html %] + [% message_lis.title | html %] + + [% END %] + diff --git a/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-news-rss.tt b/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-news-rss.tt index c6365eaa2f..dcf7247ef0 100644 --- a/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-news-rss.tt +++ b/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-news-rss.tt @@ -1,19 +1,18 @@ -[% USE raw -%] - +[% USE raw -%] - - - News from [% IF ( LibraryNameTitle ) %][% LibraryNameTitle | html %][% ELSE %]the library[% END %] - + + + News from [% IF ( LibraryNameTitle ) %][% LibraryNameTitle | html %][% ELSE %]the library[% END %] + [% OPACBaseURL | html %]/cgi-bin/koha/opac-main.pl - - [% FOREACH newsitem IN koha_news %] - - [% newsitem.title | html %] - [% newsitem.content | $raw %] - [% OPACBaseURL | html %]/cgi-bin/koha/opac-main.pl#newsitem[% newsitem.additional_content_id | html %] - - [% END %] - + + [% FOREACH newsitem IN koha_news %] + + [% newsitem.title | html %] + [% newsitem.content | $raw %] + [% OPACBaseURL | html %]/cgi-bin/koha/opac-main.pl#newsitem[% newsitem.additional_content_id | html %] + + [% END %] + diff --git a/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-opensearch.tt b/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-opensearch.tt index 03a9e43c03..e710ff2988 100644 --- a/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-opensearch.tt +++ b/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-opensearch.tt @@ -1,14 +1,11 @@ [%- FILTER collapse -%] -[%- USE raw -%] -[%- USE Koha -%] -[%- PROCESS 'html_helpers.inc' -%] - - + [%- USE raw -%] + [%- USE Koha -%] + [%- PROCESS 'html_helpers.inc' -%] + [% IF ( opensearchdescription ) %] - - Catalog search - + Catalog search [% IF ( LibraryNameTitle ) %] Search the [% LibraryNameTitle | html %] catalog @@ -17,36 +14,33 @@ [% END %] UTF-8 - + [% IF ( Koha.Preference('OpacFavicon') ) %] [% Koha.Preference('OpacFavicon') | url %] [% ELSE %] [% Koha.Preference('OPACBaseURL') | url %][% interface | url %]/[% theme | url %]/images/favicon.ico [% END %] - + [% ELSE %] [% IF ( rss ) %] - + - - <![CDATA[[% LibraryName | html %] Search [% IF ( query_desc ) %]for '[% query_desc | html %]'[% END %][% IF ( limit_desc ) %] with limit(s): '[% limit_desc | html %]'[% END %]]]> - + <![CDATA[[% LibraryName | html %] Search [% IF ( query_desc ) %]for '[% query_desc | html %]'[% END %][% IF ( limit_desc ) %]with limit(s): '[% limit_desc | html %]'[% END %]]]> [% OPACBaseURL | url %]/cgi-bin/koha/opac-search.pl?[% query_cgi | replace('&', '&') | $raw %][% limit_cgi | replace('&', '&') | $raw %]&sort_by=[% sort_by | uri %]&format=rss - - - - + + [% total | html %] [% offset | html %] [% IF ( results_per_page ) %] @@ -54,7 +48,11 @@ [% ELSE %] 20 [% END %] - diff --git a/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-showreviews.tt b/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-showreviews.tt index c803ab0a1d..9b8973a84a 100644 --- a/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-showreviews.tt +++ b/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-showreviews.tt @@ -7,105 +7,115 @@ [% INCLUDE 'doc-head-open.inc' %] Recent comments › [% IF ( LibraryNameTitle ) %][% LibraryNameTitle | html %][% ELSE %]Koha online[% END %] catalog [% INCLUDE 'doc-head-close.inc' %] -[% BLOCK cssinclude %][% END %] - +[% BLOCK cssinclude %] +[% END %] + [% INCLUDE 'bodytag.inc' bodyid='opac-showreviews' bodyclass='scrollto' %] [% INCLUDE 'masthead.inc' %] -
          - [% WRAPPER breadcrumbs %] - [% WRAPPER breadcrumb_item bc_active= 1 %] - Recent comments +
          + [% WRAPPER breadcrumbs %] + [% WRAPPER breadcrumb_item bc_active= 1 %] + Recent comments + [% END %] + [% END #/ WRAPPER breadcrumbs %] + +
          +
          + [% SET column_class = "col order-first order-md-first order-lg-2" %] + [% IF ( OpacNav || OpacNavBottom ) %] + [% column_class = "col-10 order-first order-md-first order-lg-2" %] +
          + +
          [% END %] - [% END #/ WRAPPER breadcrumbs %] -
          -
          - [% SET column_class = "col order-first order-md-first order-lg-2" %] - [% IF ( OpacNav || OpacNavBottom ) %] - [% column_class = "col-10 order-first order-md-first order-lg-2" %] -
          - -
          - [% END %] - -
          -
          -

          Recent comments

          - - - [% FOREACH review IN reviews %] - - - - [% END # / FOREACH review %] -
          Comments
          -

          - [% INCLUDE 'biblio-title.inc' biblio=review link=> 1 %] - [% IF ( review.author ) %] - by [% review.author | html %] +

          +
          +

          Recent comments +

          + + + [% FOREACH review IN reviews %] + + - + + + [% END # / FOREACH review %] +
          Comments
          +

          + [% INCLUDE 'biblio-title.inc' biblio=review link=> 1 %] + [% IF ( review.author ) %] + by [% review.author | html %] + [% END %] +

          +

          + + Publication: + [% IF ( review.place ) %][% review.place | html %][% END %] + [% IF ( review.publishercode ) %][% review.publishercode | html %][% END %] + [% IF ( review.publicationyear ) %] + [% review.publicationyear | html %] + [% ELSE %] + [% IF ( review.copyrightdate ) %] + [% review.copyrightdate | html %] + [% END %] [% END %] -

          -

          + [% IF ( review.pages ) %]. [% review.pages | html %][% END %] + [% IF ( review.notes ) %], [% review.notes | html %][% END %] + [% IF ( review.size ) %][% review.size | html %][% END %] + + [% IF ( review.summary ) %] + [% review.summary | html %] + [% END %] + [% IF ( review.copyrightdate ) %] - Publication: - [% IF ( review.place ) %][% review.place | html %] [% END %] - [% IF ( review.publishercode ) %][% review.publishercode | html %][% END %] - [% IF ( review.publicationyear ) %] - [% review.publicationyear | html %] - [% ELSE %] - [% IF ( review.copyrightdate ) %] - [% review.copyrightdate | html %] - [% END %] - [% END %] - [% IF ( review.pages ) %]. [% review.pages | html %][% END %] - [% IF ( review.notes ) %], [% review.notes | html %][% END %] - [% IF ( review.size ) %] [% review.size | html %][% END %] - - [% IF ( review.summary ) %] - - [% review.summary | html %] - - [% END %] - [% IF ( review.copyrightdate ) %] - - Date: - [% review.copyrightdate | html %] - [% END %] -

          + Date: + [% review.copyrightdate | html %] + [% END %] +

          -

          - [% IF ( review.avatarurl ) %] - - [% END %] - [% FILTER html_break %] - [% review.review | html %] - [% END %] - - [% IF review.your_comment %] - Added [% review.datereviewed | $KohaDates %] by you - [% ELSE %] - [% IF ( review.borrowernumber && ShowReviewer != "none" ) %] - Added [% review.datereviewed | $KohaDates %] by - [% SWITCH ShowReviewer %] - [% CASE 'full' %] - [% review.borrtitle | html %] [% review.firstname | html %] [% review.surname | html %] - [% CASE 'first' %] - [% review.firstname | html %] - [% CASE 'surname' %] - [% review.surname | html %] - [% CASE 'firstandinitial' %] - [% review.firstname | html %] [% review.surname|truncate(2,'.') | html %] - [% CASE 'username' %] - [% review.userid | html %] - [% END %] +

          + [% IF ( review.avatarurl ) %] + + [% END %] + [% FILTER html_break %] + [% review.review | html %] + [% END %] + + [% IF review.your_comment %] + Added [% review.datereviewed | $KohaDates %] by you + [% ELSE %] + [% IF ( review.borrowernumber && ShowReviewer != "none" ) %] + Added [% review.datereviewed | $KohaDates %] by + [% SWITCH ShowReviewer %] + [% CASE 'full' %] + [% review.borrtitle | html %] + [% review.firstname | html %] + [% review.surname | html %] + [% CASE 'first' %] + [% review.firstname | html %] + [% CASE 'surname' %] + [% review.surname | html %] + [% CASE 'firstandinitial' %] + [% review.firstname | html %] + [% review.surname|truncate(2,'.') | html %] + [% CASE 'username' %] + [% review.userid | html %] [% END %] [% END %] - -

          -
          - + [% END %] + +

          +
          + [% IF ( OPACAmazonCoverImages ) %] [% IF ( review.normalized_isbn ) %] @@ -114,7 +124,11 @@ [% END %] [% END %] [% IF ( SyndeticsEnabled && SyndeticsCoverImages ) %] - + [% END %] [% IF ( GoogleJackets ) %] @@ -124,61 +138,65 @@ No cover image available [% END %] [% END %] - - [% bt_id = ( review.normalized_upc || review.normalized_isbn ) %] - [% IF ( BakerTaylorEnabled ) %] - [% IF ( bt_id ) %] - See Baker & Taylor - [% ELSE %] - No cover image available - [% END %] + + [% bt_id = ( review.normalized_upc || review.normalized_isbn ) %] + [% IF ( BakerTaylorEnabled ) %] + [% IF ( bt_id ) %] + See Baker & Taylor + [% ELSE %] + No cover image available [% END %] + [% END %] - [% IF Koha.Preference('OPACCustomCoverImages') AND Koha.Preference('CustomCoverImagesURL') %] - [% SET custom_cover_image_url = review.biblio_object.custom_cover_image_url %] - [% IF custom_cover_image_url %] - Cover image - [% END %] + [% IF Koha.Preference('OPACCustomCoverImages') AND Koha.Preference('CustomCoverImagesURL') %] + [% SET custom_cover_image_url = review.biblio_object.custom_cover_image_url %] + [% IF custom_cover_image_url %] + Cover image [% END %] + [% END %] +
          -
          - - [% IF ( PAGE_NUMBERS ) %] -
          - - [% IF ( previous_page_offset ) %] - << Previous + [% IF ( PAGE_NUMBERS ) %] +
          + + [% IF ( previous_page_offset ) %] + << Previous + [% ELSE %] + [% IF ( previous_page_first ) %] + << Previous + [% END %] + [% END %] + [% FOREACH PAGE_NUMBER IN PAGE_NUMBERS %] + [% IF ( PAGE_NUMBER.highlight ) %] + [% PAGE_NUMBER.pg | html %] [% ELSE %] - [% IF ( previous_page_first ) %] - << Previous - [% END %] + [% PAGE_NUMBER.pg | html %] [% END %] - [% FOREACH PAGE_NUMBER IN PAGE_NUMBERS %] - [% IF ( PAGE_NUMBER.highlight ) %] - [% PAGE_NUMBER.pg | html %] - [% ELSE %] - [% PAGE_NUMBER.pg | html %] - [% END %] - [% END %] - [% IF ( next_page_offset ) %] - Next >> - [% END %] -
          - [% END # / IF PAGE_NUMBERS %] -
          -
          -
          -
          -
          + [% END %] + [% IF ( next_page_offset ) %] + Next >> + [% END %] +
          + [% END # / IF PAGE_NUMBERS %] +
          + +
          + +
          + + + + + [% INCLUDE 'opac-bottom.inc' %] [% BLOCK jsinclude %] [% IF ( GoogleJackets ) %] diff --git a/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-suggestions.tt b/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-suggestions.tt index accaea1287..9587f799fc 100644 --- a/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-suggestions.tt +++ b/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-suggestions.tt @@ -10,55 +10,58 @@ [% SET OpacNavBottom = AdditionalContents.get( location => "OpacNavBottom", lang => lang, library => logged_in_user.branchcode || default_branch, blocktitle => 0 ) %] [% SET AllPublicBranches = Branches.all( search_params => { public => 1 }, selected => logged_in_user.branchcode ) %] [% INCLUDE 'doc-head-open.inc' %] -[% IF ( op_add_form ) %]Enter a new purchase suggestion[% END %] -[% IF ( op_else ) %]Purchase suggestions[% END %] › -[% IF ( LibraryNameTitle ) %][% LibraryNameTitle | html %][% ELSE %]Koha online[% END %] catalog +[% IF ( op_add_form ) %]Enter a new purchase suggestion[% END %] + [% IF ( op_else ) %]Purchase suggestions[% END %] + › [% IF ( LibraryNameTitle ) %][% LibraryNameTitle | html %][% ELSE %]Koha online[% END %] catalog [% INCLUDE 'doc-head-close.inc' %] -[% BLOCK cssinclude %][% END %] +[% BLOCK cssinclude %] +[% END %] [% IF ( loggedinusername ) %][% INCLUDE 'bodytag.inc' bodyid='opac-usersuggestions' bodyclass='scrollto' %][% ELSE %][% INCLUDE 'bodytag.inc' bodyid='opac-suggestions' bodyclass='scrollto' %][% END %] [% INCLUDE 'masthead.inc' %] -
          - [% WRAPPER breadcrumbs %] - [% IF ( logged_in_user ) %] - [% WRAPPER breadcrumb_item %] - [% INCLUDE 'patron-title.inc' patron = logged_in_user %] - [% END %] +
          + [% WRAPPER breadcrumbs %] + [% IF ( logged_in_user ) %] + [% WRAPPER breadcrumb_item %] + [% INCLUDE 'patron-title.inc' patron = logged_in_user %] [% END %] - [% IF ( op_add_form ) %] - [% WRAPPER breadcrumb_item %] - Purchase suggestions - [% END %] - [% WRAPPER breadcrumb_item bc_active= 1 %] - New purchase suggestion - [% END %] - [% ELSE %] - [% WRAPPER breadcrumb_item bc_active= 1 %] - Purchase suggestions - [% END %] + [% END %] + [% IF ( op_add_form ) %] + [% WRAPPER breadcrumb_item %] + Purchase suggestions [% END %] - [% END #/ WRAPPER breadcrumbs %] + [% WRAPPER breadcrumb_item bc_active= 1 %] + New purchase suggestion + [% END %] + [% ELSE %] + [% WRAPPER breadcrumb_item bc_active= 1 %] + Purchase suggestions + [% END %] + [% END %] + [% END #/ WRAPPER breadcrumbs %] -
          -
          -
          - -
          -
          - -
          - [% IF ( op_add_form ) %] -

          Your purchase suggestions

          - [% IF ( Koha.Preference('MaxTotalSuggestions') != '' && patrons_total_suggestions_count >= Koha.Preference('MaxTotalSuggestions') ) %] -

          You cannot place any more suggestions

          -

          You may only add up to [% Koha.Preference('MaxTotalSuggestions') | html %] suggestions in [% Koha.Preference('NumberOfSuggestionDays') | html %] days.

          - [% ELSIF ( Koha.Preference('MaxOpenSuggestions') != '' && patrons_pending_suggestions_count >= Koha.Preference('MaxOpenSuggestions') ) %] -

          You cannot place any more suggestions

          -

          You have reached your limit for suggestions you can place at this time ([% Koha.Preference('MaxOpenSuggestions') | html %]). Once the library has processed those suggestions you will be able to place more.

          - [% ELSE %] +
          +
          +
          + +
          +
          +
          + [% IF ( op_add_form ) %] +

          Your purchase suggestions

          + [% IF ( Koha.Preference('MaxTotalSuggestions') != '' && patrons_total_suggestions_count >= Koha.Preference('MaxTotalSuggestions') ) %] +

          You cannot place any more suggestions

          +

          You may only add up to [% Koha.Preference('MaxTotalSuggestions') | html %] suggestions in [% Koha.Preference('NumberOfSuggestionDays') | html %] days.

          + [% ELSIF ( Koha.Preference('MaxOpenSuggestions') != '' && patrons_pending_suggestions_count >= Koha.Preference('MaxOpenSuggestions') ) %] +

          You cannot place any more suggestions

          +

          You have reached your limit for suggestions you can place at this time ([% Koha.Preference('MaxOpenSuggestions') | html %]). Once the library has processed those suggestions you will be able to place + more.

          + [% ELSE %] [% IF ( opacsuggestion ) %] [% PROCESS koha_news_block news => opacsuggestion %] @@ -66,13 +69,18 @@

          Enter a new purchase suggestion

          Please fill out this form to make a purchase suggestion. You will receive an email when the library processes your suggestion.

          -

          Only certain fields (marked in red) are required, but the more information you enter the easier it will be for the librarians to find the title you're requesting. The "Notes" field can be used to provide any additional information.

          +

          Only certain fields (marked in red) are required, but the more information you enter the easier it will be for the librarians to find the title you're requesting. The "Notes" field can be used to provide + any additional information.

          [% END %] [% FOR m IN messages %]
          [% SWITCH m.code %] [% CASE 'biblio_exists' %] - A similar document already exists: [% m.title | html %]. Click on "Confirm your suggestion" to ignore this message. + A similar document already exists: [% m.title | html %]. Click on "Confirm your suggestion" to ignore this message. [% CASE %] [% m.code | html %] [% END %] @@ -86,7 +94,7 @@ [% IF Koha.Preference( 'OPACSuggestionAutoFill' ) %]
        • - +
        • [% END %]
        • @@ -104,20 +112,20 @@
        • [% UNLESS ( author_hidden ) %]
        • - [% IF biblionumber %] - - [% author | html %] - [% ELSIF ( author_required ) %] - - -
          Required
          - [% ELSE %] - - - [% END %] + [% IF biblionumber %] + + [% author | html %] + [% ELSIF ( author_required ) %] + + +
          Required
          + [% ELSE %] + + + [% END %]
        • [% END %] - [% UNLESS ( copyrightdate_hidden )%] + [% UNLESS ( copyrightdate_hidden ) %]
        • [% IF biblionumber %] @@ -143,11 +151,11 @@ [% isbn | html %] [% ELSIF ( isbn_required ) %] - +
          Required
          [% ELSE %] - + [% END %]
        • [% END %] @@ -192,7 +200,7 @@
          Required
          [% ELSE %] - + [% END %] [% END %] @@ -204,23 +212,23 @@
          Required
          [% ELSE %] - + [% END %] [% END %] - [% UNLESS ( itemtype_hidden )%] + [% UNLESS ( itemtype_hidden ) %]
        • - [% IF ( itemtype_required ) %] - - [% PROCESS 'av-build-dropbox.inc' name="itemtype", category="SUGGEST_FORMAT", size = 20, required = 1, blank = 1, default=itemtype %] -
          Required
          - [% ELSE %] - - [% PROCESS 'av-build-dropbox.inc' name="itemtype", category="SUGGEST_FORMAT", size = 20, blank = 1, default=itemtype %] - [% END %] + [% IF ( itemtype_required ) %] + + [% PROCESS 'av-build-dropbox.inc' name="itemtype", category="SUGGEST_FORMAT", size = 20, required = 1, blank = 1, default=itemtype %] +
          Required
          + [% ELSE %] + + [% PROCESS 'av-build-dropbox.inc' name="itemtype", category="SUGGEST_FORMAT", size = 20, blank = 1, default=itemtype %] + [% END %]
        • [% END %] - [% UNLESS ( branchcode_hidden || AllPublicBranches.size < 2 )%] + [% UNLESS ( branchcode_hidden || AllPublicBranches.size < 2 ) %]
        • [% IF ( branchcode_required ) %] @@ -238,36 +246,36 @@
        • [% END %] [% IF ( patron_reason_loop ) %] - [% UNLESS ( patronreason_hidden )%] -
        • - [% IF ( patronreason_required ) %] - - + + [% FOREACH patron_reason_loo IN patron_reason_loop %] + [% IF patron_reason_loo.authorised_value == patronreason %] + + [% ELSE %] + + [% END %] [% END %] - [% END %] - -
          Required
          - [% ELSE %] - - +
          Required
          + [% ELSE %] + + - [% END %] -
        • - [% END %] + + [% END %] + + [% END %] [% END %] [% UNLESS ( note_hidden ) %]
        • @@ -283,10 +291,7 @@ [% END %] -
        • - negcap -
        • - +
        • negcap
        • @@ -305,103 +310,107 @@ Cancel
          - [% END %] - [% END # IF op_add_form %] + [% END %] + [% END # IF op_add_form %] - [% IF ( op_else ) %] -

          - [% IF Koha.Preference( 'OPACViewOthersSuggestions' ) == 1 %] - Purchase suggestions + [% IF ( op_else ) %] +

          + [% IF Koha.Preference( 'OPACViewOthersSuggestions' ) == 1 %] + Purchase suggestions + [% ELSE %] + [% IF ( loggedinusername ) %] + Your purchase suggestions [% ELSE %] - [% IF ( loggedinusername ) %] - Your purchase suggestions - [% ELSE %] - Purchase suggestions + Purchase suggestions + [% END %] + [% END %] +

          + [% FOR m IN messages %] +
          + [% SWITCH m.code %] + [% CASE 'total_suggestions' %] + The suggestion has not been added. You have reached your limit for suggestions you can place at this time ([% Koha.Preference('MaxTotalSuggestions') | html %] in + [% Koha.Preference('NumberOfSuggestionDays') | html %] days). + [% CASE 'too_many' %] + The suggestion has not been added. You have reached your limit for suggestions you can place at this time ([% Koha.Preference('MaxOpenSuggestions') | html %]). Once the library has processed those + suggestions you will be able to place more. + [% CASE 'already_exists' %] + The suggestion has not been added. A suggestion with this title already exists. + [% CASE 'success_on_inserted' %] + Your suggestion has been submitted. + [% CASE %] + [% m.code | html %] + [% END %] +
          + [% END %] + + [% IF ( deleted ) %]
          The selected suggestions have been deleted.
          [% END %] + + [% IF (Koha.Preference( 'OPACViewOthersSuggestions' ) || loggedinusername) && (suggestions.size > 0 OR title_filter) %] + [% SET can_delete_suggestion = 0 %] +
          +
          + +
          +
          + +
          + [% IF Koha.Preference( 'OPACViewOthersSuggestions' ) %] + [% IF loggedinusername %] +
          + + +
          [% END %] [% END %] - - [% FOR m IN messages %] -
          - [% SWITCH m.code %] - [% CASE 'total_suggestions' %] - The suggestion has not been added. You have reached your limit for suggestions you can place at this time ([% Koha.Preference('MaxTotalSuggestions') | html %] in [% Koha.Preference('NumberOfSuggestionDays') | html %] days). - [% CASE 'too_many' %] - The suggestion has not been added. You have reached your limit for suggestions you can place at this time ([% Koha.Preference('MaxOpenSuggestions') | html %]). Once the library has processed those suggestions you will be able to place more. - [% CASE 'already_exists' %] - The suggestion has not been added. A suggestion with this title already exists. - [% CASE 'success_on_inserted' %] - Your suggestion has been submitted. - [% CASE %] - [% m.code | html %] - [% END %] +
          +
          - [% END %] - - [% IF ( deleted ) %]
          The selected suggestions have been deleted.
          [% END %] - - [% IF (Koha.Preference( 'OPACViewOthersSuggestions' ) || loggedinusername) && (suggestions.size > 0 OR title_filter) %] - [% SET can_delete_suggestion = 0 %] - -
          - -
          -
          - -
          - [% IF Koha.Preference( 'OPACViewOthersSuggestions' ) %] - [% IF loggedinusername %] -
          - - -
          - [% END %] - [% END %] -
          - -
          - - [% END %] - [% IF suggestions.size > 0 %] - [% SET can_delete_suggestion = 0 %] -
          - [% INCLUDE 'csrf-token.inc' %] - - [% IF ( loggedinusername || ( Koha.Preference( 'AnonSuggestions' ) == 1 ) ) %] -
          + + [% END %] + [% IF suggestions.size > 0 %] + [% SET can_delete_suggestion = 0 %] +
          + [% INCLUDE 'csrf-token.inc' %] + + [% IF ( loggedinusername || ( Koha.Preference( 'AnonSuggestions' ) == 1 ) ) %] +
          [% IF ( Koha.Preference('MaxTotalSuggestions') != '' && patrons_total_suggestions_count >= Koha.Preference('MaxTotalSuggestions') ) %] -

          You may only add up to [% Koha.Preference('MaxTotalSuggestions') | html %] suggestions in [% Koha.Preference('NumberOfSuggestionDays') | html %] days.

          +

          You may only add up to [% Koha.Preference('MaxTotalSuggestions') | html %] suggestions in [% Koha.Preference('NumberOfSuggestionDays') | html %] days.

          [% ELSIF ( Koha.Preference('MaxOpenSuggestions') != '' && patrons_pending_suggestions_count >= Koha.Preference('MaxOpenSuggestions') ) %] -

          You have reached your limit for suggestions you can place at this time ([% Koha.Preference('MaxOpenSuggestions') | html %]).

          -

          Once the library has processed those suggestions you will be able to place more.

          +

          You have reached your limit for suggestions you can place at this time ([% Koha.Preference('MaxOpenSuggestions') | html %]).

          +

          Once the library has processed those suggestions you will be able to place more.

          [% ELSE %] - New purchase suggestion + New purchase suggestion [% END %] -
          - [% END %] +
          + [% END %] - [% IF ( loggedinusername ) %] -
          -
          - -
          - + [% IF ( loggedinusername ) %] +
          +
          + - [% END %] +
          + [% END %] - [% IF Koha.Preference( 'OPACViewOthersSuggestions' ) == 1 || loggedinusername %] + [% IF Koha.Preference( 'OPACViewOthersSuggestions' ) == 1 || loggedinusername %] @@ -423,7 +432,14 @@ [% END %] @@ -437,17 +453,16 @@ [% END %]

          -

          [% IF ( suggestion.author ) %][% suggestion.author | html %],[% END %] - [% IF ( suggestion.copyrightdate ) %] - [% suggestion.copyrightdate | html %],[% END %] - [% IF ( suggestion.publishercode ) %] - [% suggestion.publishercode | html %][% END %] - [% IF ( suggestion.place ) %]([% suggestion.place | html %])[% END %] - [% IF ( suggestion.collectiontitle ) %] , [% suggestion.collectiontitle | html %][% END %] - [% IF ( suggestion.itemtype ) %] - [% AuthorisedValues.GetByCode( 'SUGGEST_FORMAT', suggestion.itemtype, 1 ) | html %][% END %] +

          [% IF ( suggestion.author ) %][% suggestion.author | html %],[% END %] + [% IF ( suggestion.copyrightdate ) %]- [% suggestion.copyrightdate | html %],[% END %] + [% IF ( suggestion.publishercode ) %]- [% suggestion.publishercode | html %][% END %] + [% IF ( suggestion.place ) %]([% suggestion.place | html %])[% END %] + [% IF ( suggestion.collectiontitle ) %], [% suggestion.collectiontitle | html %][% END %] + [% IF ( suggestion.itemtype ) %]- [% AuthorisedValues.GetByCode( 'SUGGEST_FORMAT', suggestion.itemtype, 1 ) | html %][% END %]

          - + [% END %] [% IF Koha.Preference( 'OpacSuggestionManagedBy' ) %] - + [% END %] @@ -483,166 +506,172 @@ [% END # / FOREACH suggestions %]
          Your purchase suggestions
          [% IF logged_in_user.borrowernumber == suggestion.suggester.borrowernumber %] [% SET can_delete_suggestion = 1 %] - + [% END %] - [% IF ( suggestion.suggesteddate ) %][% suggestion.suggesteddate |$KohaDates %][% END %] - [% IF ( suggestion.suggesteddate ) %][% suggestion.suggesteddate |$KohaDates %][% END %] [% IF ( suggestion.note ) %] [% suggestion.note | html %] @@ -461,21 +476,29 @@ - [% IF suggestion.managedby %] - [% INCLUDE 'patron-title.inc' patron = suggestion.manager %] - [% IF ( suggestion.manageddate ) %] - [% suggestion.manageddate | $KohaDates %][% END %] - [% END %] - + [% IF suggestion.managedby %] + [% INCLUDE 'patron-title.inc' patron = suggestion.manager %] + [% IF ( suggestion.manageddate ) %]- [% suggestion.manageddate | $KohaDates %][% END %] + [% END %] + - [% IF ( suggestion.STATUS == 'ASKED' ) %]Requested - [% ELSIF ( suggestion.STATUS == 'CHECKED' ) %]Checked by the library - [% ELSIF ( suggestion.STATUS == 'ACCEPTED' ) %]Accepted by the library - [% ELSIF ( suggestion.STATUS == 'ORDERED' ) %]Ordered by the library - [% ELSIF ( suggestion.STATUS == 'REJECTED' ) %]Suggestion declined - [% ELSIF ( suggestion.STATUS == 'AVAILABLE' ) %]Available in the library - [% ELSE %] [% AuthorisedValues.GetByCode( 'SUGGEST_STATUS', suggestion.STATUS, 1 ) | html %] [% END %] + [% IF ( suggestion.STATUS == 'ASKED' ) %] + Requested + [% ELSIF ( suggestion.STATUS == 'CHECKED' ) %] + Checked by the library + [% ELSIF ( suggestion.STATUS == 'ACCEPTED' ) %] + Accepted by the library + [% ELSIF ( suggestion.STATUS == 'ORDERED' ) %] + Ordered by the library + [% ELSIF ( suggestion.STATUS == 'REJECTED' ) %] + Suggestion declined + [% ELSIF ( suggestion.STATUS == 'AVAILABLE' ) %] + Available in the library + [% ELSE %] + [% AuthorisedValues.GetByCode( 'SUGGEST_STATUS', suggestion.STATUS, 1 ) | html %] + [% END %] [% IF ( suggestion.reason ) %]([% suggestion.reason | html %])[% END %]
          - [% END %] + [% END %] - [% IF ( loggedinusername && can_delete_suggestion ) %] -
          - -
          - [% END %] - + [% IF ( loggedinusername && can_delete_suggestion ) %] +
          + +
          + [% END %] + + [% ELSE %] + [% IF Koha.Preference( 'OPACViewOthersSuggestions' ) %] + [% IF title_filter %] + + [% ELSIF loggedinusername AND NOT suggested_by_anyone %] + + [% ELSE %] + + [% END %] [% ELSE %] - [% IF Koha.Preference( 'OPACViewOthersSuggestions' ) %] + [% IF ( loggedinusername ) %] [% IF title_filter %] - [% ELSIF loggedinusername AND NOT suggested_by_anyone %] - [% ELSE %] - + [% END %] [% ELSE %] - [% IF ( loggedinusername ) %] - [% IF title_filter %] - - [% ELSE %] - - [% END %] - [% ELSE %] - - [% END %] + [% END %] - [% IF ( loggedinusername || ( Koha.Preference( 'AnonSuggestions' ) == 1 ) ) %] - [% IF ( Koha.Preference('MaxTotalSuggestions') != '' && patrons_total_suggestions_count >= Koha.Preference('MaxTotalSuggestions') ) %] -

          You may only add up to [% Koha.Preference('MaxTotalSuggestions') | html %] suggestions in [% Koha.Preference('NumberOfSuggestionDays') | html %] days.

          - [% ELSIF ( Koha.Preference('MaxOpenSuggestions') != '' && patrons_pending_suggestions_count >= Koha.Preference('MaxOpenSuggestions') ) %] -

          You have reached your limit for suggestions you can place at this time.

          -

          Once the library has processed those suggestions you will be able to place more.

          - [% ELSE %] -

          New purchase suggestion

          - [% END %] + [% END %] + [% IF ( loggedinusername || ( Koha.Preference( 'AnonSuggestions' ) == 1 ) ) %] + [% IF ( Koha.Preference('MaxTotalSuggestions') != '' && patrons_total_suggestions_count >= Koha.Preference('MaxTotalSuggestions') ) %] +

          You may only add up to [% Koha.Preference('MaxTotalSuggestions') | html %] suggestions in [% Koha.Preference('NumberOfSuggestionDays') | html %] days.

          + [% ELSIF ( Koha.Preference('MaxOpenSuggestions') != '' && patrons_pending_suggestions_count >= Koha.Preference('MaxOpenSuggestions') ) %] +

          You have reached your limit for suggestions you can place at this time.

          +

          Once the library has processed those suggestions you will be able to place more.

          + [% ELSE %] +

          New purchase suggestion

          [% END %] - [% END # / IF suggestions.size %] - - [% END # IF op_else %] -
          -
          -
          -
          -
          + [% END %] + [% END # / IF suggestions.size %] + [% END # IF op_else %] +
          + +
          + +
          + +
          + +
          + [% INCLUDE 'opac-bottom.inc' %] [% BLOCK jsinclude %] -[% IF Koha.Preference("OPACSuggestionAutoFill") %] - [% Asset.js("js/autofill.js") | $raw %] -[% END %] -[% INCLUDE 'datatables.inc' %] - + + $(function() { + $("#suggestt").dataTable($.extend(true, {}, dataTablesDefaults, { + "order": [[ 1, "asc" ]], + "columnDefs": [ + [% IF ( loggedinusername ) %]{ "targets": [ 0 ], "sortable": false, "searchable": false }[% END %], + { "className": 'dtr-control', "orderable": false, "targets": -1 }, + { responsivePriority: 1, targets: 1 } + ], + "columns": [ + [% IF ( loggedinusername ) %]null,[% END %] + { "type": "anti-the" }, + null, + null, + [% IF Koha.Preference( 'OPACViewOthersSuggestions' ) == 1 %]null,[% END %] + [% IF Koha.Preference( 'OpacSuggestionManagedBy' ) %]null,[% END %] + null, + null + ], + "responsive": { + details: { + type: 'column', + target: -1 + } + }, + })); + [% IF ( loggedinusername ) %]$("span.clearall").html(""+_("Clear all")+"<\/a>"); + $("span.checkall").html(""+_("Select all")+"<\/a>"); + $("#CheckAll").on("click",function(e){ + e.preventDefault(); + $(".cb").prop("checked", true); + enableCheckboxActions(); + }); + $("#CheckNone").on("click",function(e){ + e.preventDefault(); + $(".cb").prop("checked", false); + enableCheckboxActions(); + }); + $(".cb").click(function(){ + enableCheckboxActions(); + }); + + enableCheckboxActions(); + + $(".removeitems").on("click", function(e) { + e.preventDefault(); + var selected_titles = $("input:checked"); + var title; + var yes_label; + var no_label; + var message = ""; + if ( selected_titles.size() < 1 ) { + alert( _("No suggestion was selected") ); + return false; + } else { + if( selected_titles.size() > 1 ){ + message = $("
            "); + title = _("Are you sure you want to delete these suggestions?"); + yes_label = _("Yes, delete suggestions"); + no_label = _("No, do not delete suggestions"); + selected_titles.each(function(){ + message.append( "
          • " + $(this).data("title") + "
          • " ); + }); + } else { + title = _("Are you sure you want to delete this suggestion?"); + yes_label = _("Yes, delete suggestion"); + no_label = _("No, do not delete suggestion"); + selected_titles.each(function(){ + message += $(this).data("title"); + }); + } + confirmModal( message, title, yes_label, no_label, function( result ){ + if( result ){ + $("#delete_suggestions").submit(); + } + }); + } + }); + [% END %] + }); + [% END %] diff --git a/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-tags.tt b/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-tags.tt index 2f7d03dc8e..c6a6b1fc77 100644 --- a/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-tags.tt +++ b/koha-tmpl/opac-tmpl/bootstrap/en/modules/opac-tags.tt @@ -20,13 +20,31 @@ [% INCLUDE 'doc-head-close.inc' %] [% BLOCK cssinclude %] $message"; + $message = + "$message"; $email->html_body($message); - } - else { + } else { $email->text_body($message); } @@ -387,20 +384,17 @@ foreach my $report_id (@ARGV) { user_name => $username, password => $password, } - ) - if $username; + ) if $username; $email->transport( $smtp_server->transport ); try { $email->send_or_die; - } - catch { + } catch { carp "Mail not sent: $_"; }; - } - else { + } else { print $message; } } -cronlogaction({ action => 'End', info => "COMPLETED" }); +cronlogaction( { action => 'End', info => "COMPLETED" } ); diff --git a/misc/cronjobs/serialsUpdate.pl b/misc/cronjobs/serialsUpdate.pl index 2d1ccaae03..a4a225aa19 100755 --- a/misc/cronjobs/serialsUpdate.pl +++ b/misc/cronjobs/serialsUpdate.pl @@ -24,12 +24,12 @@ use Koha::Script -cron; use C4::Context; use C4::Serials qw( GetSubscription GetNextDate ModSerialStatus ); use C4::Serials::Frequency; -use C4::Log qw( cronlogaction ); +use C4::Log qw( cronlogaction ); use Koha::DateUtils qw( dt_from_string ); -use Date::Calc qw( check_date Date_to_Days ); +use Date::Calc qw( check_date Date_to_Days ); use Getopt::Long qw( GetOptions ); -use Pod::Usage qw( pod2usage ); +use Pod::Usage qw( pod2usage ); =head1 NAME @@ -59,8 +59,8 @@ my $verbose = 0; my $note = ''; my $nonote = 0; -my $command_line_options = join(" ",@ARGV); -cronlogaction({ info => $command_line_options }); +my $command_line_options = join( " ", @ARGV ); +cronlogaction( { info => $command_line_options } ); GetOptions( 'help|h|?' => \$help, @@ -71,7 +71,7 @@ GetOptions( 'no-note' => \$nonote, ) or pod2usage(2); -pod2usage(1) if $help; +pod2usage(1) if $help; pod2usage( -verbose => 2 ) if $man; $verbose and !$confirm and print "### Database will not be modified ###\n"; @@ -108,14 +108,16 @@ my $sth = $dbh->prepare( $sth->execute(); while ( my $issue = $sth->fetchrow_hashref ) { - if ( $confirm ){ - ModSerialStatus( $issue->{serialid}, $issue->{serialseq}, + if ($confirm) { + ModSerialStatus( + $issue->{serialid}, $issue->{serialseq}, $issue->{planneddate}, $issue->{publisheddate}, $issue->{publisheddatetext}, - 3, $note ); + 3, $note + ); $verbose and print "Serial issue with id=" . $issue->{serialid} . " marked late\n"; } else { print "Serial issue with id=" . $issue->{serialid} . " would have been marked late\n"; } } -cronlogaction({ action => 'End', info => "COMPLETED" }); +cronlogaction( { action => 'End', info => "COMPLETED" } ); diff --git a/misc/cronjobs/share_usage_with_koha_community.pl b/misc/cronjobs/share_usage_with_koha_community.pl index be68035646..3a10b8dfbb 100755 --- a/misc/cronjobs/share_usage_with_koha_community.pl +++ b/misc/cronjobs/share_usage_with_koha_community.pl @@ -2,17 +2,17 @@ use Modern::Perl; -use Pod::Usage qw( pod2usage ); +use Pod::Usage qw( pod2usage ); use Getopt::Long qw( GetOptions ); use Koha::Script -cron; use C4::Context; use C4::UsageStats; use C4::Log qw( cronlogaction ); -use POSIX qw( strftime ); +use POSIX qw( strftime ); -my $command_line_options = join(" ",@ARGV); -cronlogaction({ info => $command_line_options }); +my $command_line_options = join( " ", @ARGV ); +cronlogaction( { info => $command_line_options } ); my ( $help, $verbose, $force, $quiet ); GetOptions( @@ -29,7 +29,7 @@ if ($help) { unless ( C4::Context->preference('UsageStats') ) { $quiet && exit; pod2usage( -q| + q| The UsageStats system preference is not set. If your library wants to share their usage statistics with the Koha community, you have to switch on this system preference @@ -46,7 +46,7 @@ C4::Context->set_preference( strftime( "%s", localtime ) ); -cronlogaction({ action => 'End', info => "COMPLETED" }); +cronlogaction( { action => 'End', info => "COMPLETED" } ); =head1 NAME diff --git a/misc/cronjobs/sitemap.pl b/misc/cronjobs/sitemap.pl index 4b4576a567..8fb474c91b 100755 --- a/misc/cronjobs/sitemap.pl +++ b/misc/cronjobs/sitemap.pl @@ -21,22 +21,21 @@ package Main; use Modern::Perl; use utf8; -use Pod::Usage qw( pod2usage ); +use Pod::Usage qw( pod2usage ); use Getopt::Long qw( GetOptions ); use Koha::Script -cron; use Koha::Sitemapper; - -my ($verbose, $help, $url, $dir, $short) = (0, 0, '', '.', 1); +my ( $verbose, $help, $url, $dir, $short ) = ( 0, 0, '', '.', 1 ); my $where; GetOptions( - 'verbose' => \$verbose, - 'help' => \$help, - 'url=s' => \$url, - 'dir=s' => \$dir, - 'short!' => \$short, - 'where=s' => \$where, + 'verbose' => \$verbose, + 'help' => \$help, + 'url=s' => \$url, + 'dir=s' => \$dir, + 'short!' => \$short, + 'where=s' => \$where, ); sub usage { @@ -63,7 +62,6 @@ my $sitemapper = Koha::Sitemapper->new( ); $sitemapper->run($where); - =head1 USAGE =over diff --git a/misc/cronjobs/social_data/update_social_data.pl b/misc/cronjobs/social_data/update_social_data.pl index 58e3dc0696..e0de0aa1ce 100755 --- a/misc/cronjobs/social_data/update_social_data.pl +++ b/misc/cronjobs/social_data/update_social_data.pl @@ -6,13 +6,12 @@ use Koha::Script -cron; use C4::Context; use C4::SocialData; -my $url = C4::Context->preference( "Babeltheque_url_update" ); -my $output_dir = qq{/tmp}; +my $url = C4::Context->preference("Babeltheque_url_update"); +my $output_dir = qq{/tmp}; my $output_filepath = qq{$output_dir/social_data.csv}; -system( qq{/bin/rm -f $output_filepath} ); -system( qq{/bin/rm -f $output_dir/social_data.csv.bz2} ); -system( qq{/usr/bin/wget $url -O $output_dir/social_data.csv.bz2 } ) == 0 or die "Can't get bz2 file from url $url ($?)"; -system( qq{/bin/bunzip2 $output_dir/social_data.csv.bz2 } ) == 0 or die "Can't extract bz2 file ($?)"; - +system(qq{/bin/rm -f $output_filepath}); +system(qq{/bin/rm -f $output_dir/social_data.csv.bz2}); +system(qq{/usr/bin/wget $url -O $output_dir/social_data.csv.bz2 }) == 0 or die "Can't get bz2 file from url $url ($?)"; +system(qq{/bin/bunzip2 $output_dir/social_data.csv.bz2 }) == 0 or die "Can't extract bz2 file ($?)"; C4::SocialData::update_data $output_filepath; diff --git a/misc/cronjobs/staticfines.pl b/misc/cronjobs/staticfines.pl index dafbbacb03..2d1895c251 100755 --- a/misc/cronjobs/staticfines.pl +++ b/misc/cronjobs/staticfines.pl @@ -31,10 +31,10 @@ use Date::Calc qw( Date_to_Days ); use Koha::Script -cron; use C4::Context; -use C4::Overdues qw( CalcFine checkoverdues GetFine Getoverdues ); -use C4::Calendar qw(); # don't need any exports from Calendar -use C4::Log qw( cronlogaction ); -use Getopt::Long qw( GetOptions ); +use C4::Overdues qw( CalcFine checkoverdues GetFine Getoverdues ); +use C4::Calendar qw(); # don't need any exports from Calendar +use C4::Log qw( cronlogaction ); +use Getopt::Long qw( GetOptions ); use List::MoreUtils qw( none ); use Koha::DateUtils qw( dt_from_string output_pref ); use Koha::Patrons; @@ -48,21 +48,21 @@ my @libraries; my $delay; my $useborrowerlibrary; my $borrowernumberlimit; -my $borrowersalreadyapplied; # hashref of borrowers for whom we already applied the fine, so it's only applied once -my $debug = 0; +my $borrowersalreadyapplied; # hashref of borrowers for whom we already applied the fine, so it's only applied once +my $debug = 0; my $bigdebug = 0; -my $command_line_options = join(" ",@ARGV); -cronlogaction({ info => $command_line_options }); +my $command_line_options = join( " ", @ARGV ); +cronlogaction( { info => $command_line_options } ); GetOptions( - 'h|help' => \$help, - 'v|verbose' => \$verbose, - 'c|category:s'=> \@pcategories, - 'l|library:s' => \@libraries, - 'd|delay:i' => \$delay, + 'h|help' => \$help, + 'v|verbose' => \$verbose, + 'c|category:s' => \@pcategories, + 'l|library:s' => \@libraries, + 'd|delay:i' => \$delay, 'u|use-borrower-library' => \$useborrowerlibrary, - 'b|borrower:i' => \$borrowernumberlimit + 'b|borrower:i' => \$borrowernumberlimit ); my $usage = << 'ENDUSAGE'; @@ -88,7 +88,7 @@ my $dbh = C4::Context->dbh; # Processing categories foreach (@pcategories) { - my ($category, $amount) = split(',', $_); + my ( $category, $amount ) = split( ',', $_ ); push @categories, $category; $catamounts{$category} = $amount; } @@ -106,30 +106,30 @@ CHECK { $branch_type = C4::Context->preference('HomeOrHoldingBranch') || 'homebranch'; $mode = C4::Context->preference('finesMode'); $dbname = C4::Context->config('database'); - $delim = "\t"; # ? C4::Context->preference('delimiter') || "\t"; + $delim = "\t"; # ? C4::Context->preference('delimiter') || "\t"; } INIT { $debug and print "Each line will contain the following fields:\n", - "From borrowers : ", join( ', ', @borrower_fields ), "\n", - "From items : ", join( ', ', @item_fields ), "\n", - "Per overdue: ", join( ', ', @other_fields ), "\n", - "Delimiter: '$delim'\n"; + "From borrowers : ", join( ', ', @borrower_fields ), "\n", + "From items : ", join( ', ', @item_fields ), "\n", + "Per overdue: ", join( ', ', @other_fields ), "\n", + "Delimiter: '$delim'\n"; } -$debug and (defined $borrowernumberlimit) and print "--borrower limitation: borrower $borrowernumberlimit\n"; -my ($numOverdueItems, $data); -if (defined $borrowernumberlimit) { - ($numOverdueItems, $data) = checkoverdues($borrowernumberlimit); +$debug and ( defined $borrowernumberlimit ) and print "--borrower limitation: borrower $borrowernumberlimit\n"; +my ( $numOverdueItems, $data ); +if ( defined $borrowernumberlimit ) { + ( $numOverdueItems, $data ) = checkoverdues($borrowernumberlimit); } else { - $data = Getoverdues(); + $data = Getoverdues(); $numOverdueItems = scalar @$data; } my $overdueItemsCounted = 0; my %calendars = (); -$today = dt_from_string; -$today_iso = $today->ymd; -my ($tyear, $tmonth, $tday) = split( /-/, $today_iso ); +$today = dt_from_string; +$today_iso = $today->ymd; +my ( $tyear, $tmonth, $tday ) = split( /-/, $today_iso ); $today_days = Date_to_Days( $tyear, $tmonth, $tday ); for ( my $i = 0 ; $i < scalar(@$data) ; $i++ ) { @@ -141,30 +141,40 @@ for ( my $i = 0 ; $i < scalar(@$data) ; $i++ ) { $datedue_days = Date_to_Days( split( /-/, $datedue_iso ) ); }; if ($@) { - warn "Error on date for borrower " . $data->[$i]->{'borrowernumber'} . ": $@date_due: " . $data->[$i]->{'date_due'} . "\ndatedue_days: " . $datedue_days . "\nSkipping"; - next; + warn "Error on date for borrower " + . $data->[$i]->{'borrowernumber'} + . ": $@date_due: " + . $data->[$i]->{'date_due'} + . "\ndatedue_days: " + . $datedue_days + . "\nSkipping"; + next; } my $due_str = output_pref( { dt => $datedue, dateonly => 1 } ); unless ( defined $data->[$i]->{'borrowernumber'} ) { - print STDERR "ERROR in Getoverdues line $i: issues.borrowernumber IS NULL. Repair 'issues' table now! Skipping record.\n"; - next; # Note: this doesn't solve everything. After NULL borrowernumber, multiple issues w/ real borrowernumbers can pile up. + print STDERR + "ERROR in Getoverdues line $i: issues.borrowernumber IS NULL. Repair 'issues' table now! Skipping record.\n"; + next + ; # Note: this doesn't solve everything. After NULL borrowernumber, multiple issues w/ real borrowernumbers can pile up. } my $patron = Koha::Patrons->find( $data->[$i]->{'borrowernumber'} ); # Skipping borrowers that are not in @categories - $bigdebug and warn "Skipping borrower from category " . $patron->categorycode if none { $patron->categorycode eq $_ } @categories; + $bigdebug and warn "Skipping borrower from category " . $patron->categorycode + if none { $patron->categorycode eq $_ } @categories; next if none { $patron->categorycode eq $_ } @categories; my $branchcode = - ( $useborrowerlibrary ) ? $patron->branchcode - : ( $control eq 'ItemHomeLibrary' ) ? $data->[$i]->{$branch_type} - : ( $control eq 'PatronLibrary' ) ? $patron->branchcode - : $data->[$i]->{branchcode}; + ($useborrowerlibrary) ? $patron->branchcode + : ( $control eq 'ItemHomeLibrary' ) ? $data->[$i]->{$branch_type} + : ( $control eq 'PatronLibrary' ) ? $patron->branchcode + : $data->[$i]->{branchcode}; + # In final case, CircControl must be PickupLibrary. (branchcode comes from issues table here). # Skipping branchcodes that are not in @libraries $bigdebug and warn "Skipping library $branchcode" if none { $branchcode eq $_ } @libraries; - next if none { $branchcode eq $_ } @libraries; + next if none { $branchcode eq $_ } @libraries; my $calendar; unless ( defined( $calendars{$branchcode} ) ) { @@ -175,7 +185,7 @@ for ( my $i = 0 ; $i < scalar(@$data) ; $i++ ) { # Reassing datedue_days if -delay specified in commandline $bigdebug and warn "Using commandline supplied delay : $delay" if ($delay); - $datedue_days += $delay if ($delay); + $datedue_days += $delay if ($delay); ( $datedue_days <= $today_days ) or next; # or it's not overdue, right? @@ -189,37 +199,46 @@ for ( my $i = 0 ; $i < scalar(@$data) ; $i++ ) { ); # Reassign fine's amount if specified in command-line - $amount = $catamounts{$patron->categorycode} if (defined $catamounts{$patron->categorycode}); + $amount = $catamounts{ $patron->categorycode } if ( defined $catamounts{ $patron->categorycode } ); # We check if there is already a fine for the given borrower - my $fine = GetFine(undef, $data->[$i]->{'borrowernumber'}); - if ($fine > 0) { - $debug and warn "There is already a fine for borrower " . $data->[$i]->{'borrowernumber'} . ". Nothing to do here. Skipping this borrower"; + my $fine = GetFine( undef, $data->[$i]->{'borrowernumber'} ); + if ( $fine > 0 ) { + $debug + and warn "There is already a fine for borrower " + . $data->[$i]->{'borrowernumber'} + . ". Nothing to do here. Skipping this borrower"; next; } # Don't update the fine if today is a holiday. # This ensures that dropbox mode will remove the correct amount of fine. - if ( $mode eq 'production' and !$borrowersalreadyapplied->{$data->[$i]->{'borrowernumber'}}) { + if ( $mode eq 'production' and !$borrowersalreadyapplied->{ $data->[$i]->{'borrowernumber'} } ) { + # If we're on a holiday, warn the user (if debug) that no fine will be applied - if($isHoliday) { - $debug and warn "Today is a holiday. The fine for borrower " . $data->[$i]->{'borrowernumber'} . " will not be applied"; + if ($isHoliday) { + $debug + and warn "Today is a holiday. The fine for borrower " + . $data->[$i]->{'borrowernumber'} + . " will not be applied"; } else { $debug and warn "Creating fine for borrower " . $data->[$i]->{'borrowernumber'} . " with amount : $amount"; # We mark this borrower as already processed - $borrowersalreadyapplied->{$data->[$i]->{'borrowernumber'}} = 1; + $borrowersalreadyapplied->{ $data->[$i]->{'borrowernumber'} } = 1; my $borrowernumber = $data->[$i]->{'borrowernumber'}; my $itemnumber = $data->[$i]->{'itemnumber'}; # And we create the fine - my $sth4 = $dbh->prepare( "SELECT title FROM biblio LEFT JOIN items ON biblio.biblionumber=items.biblionumber WHERE items.itemnumber=?" ); + my $sth4 = $dbh->prepare( + "SELECT title FROM biblio LEFT JOIN items ON biblio.biblionumber=items.biblionumber WHERE items.itemnumber=?" + ); $sth4->execute($itemnumber); my $title = $sth4->fetchrow; - my $desc = "staticfine"; - my $query = "INSERT INTO accountlines + my $desc = "staticfine"; + my $query = "INSERT INTO accountlines (borrowernumber,itemnumber,date,amount,description,debit_type_code,status,amountoutstanding) VALUES (?,?,now(),?,?,'OVERDUE','RETURNED',?)"; my $sth2 = $dbh->prepare($query); @@ -240,4 +259,4 @@ Number of Overdue Items: EOM } -cronlogaction({ action => 'End', info => "COMPLETED" }); +cronlogaction( { action => 'End', info => "COMPLETED" } ); diff --git a/misc/cronjobs/stockrotation.pl b/misc/cronjobs/stockrotation.pl index 1298921f9b..94f100c59c 100755 --- a/misc/cronjobs/stockrotation.pl +++ b/misc/cronjobs/stockrotation.pl @@ -128,20 +128,22 @@ my $ok = GetOptions( my ( $opt_name, $opt_value ) = @_; if ( $opt_value eq 'all' ) { $branch = 0; - } - else { - my $branches = Koha::Libraries->search( {}, - { order_by => { -asc => 'branchname' } } ); + } else { + my $branches = Koha::Libraries->search( + {}, + { order_by => { -asc => 'branchname' } } + ); my $brnch = $branches->find($opt_value); if ($brnch) { $branch = $brnch; return $brnch; - } - else { + } else { printf("Option $opt_name should be one of (name -> code):\n"); while ( my $candidate = $branches->next ) { - printf( " %-40s -> %s\n", - $candidate->branchname, $candidate->branchcode ); + printf( + " %-40s -> %s\n", + $candidate->branchname, $candidate->branchcode + ); } exit 1; } @@ -152,8 +154,7 @@ my $ok = GetOptions( my ( $opt_name, $opt_value ) = @_; if ( $opt_value eq 'full' || $opt_value eq 'email' ) { $report = $opt_value; - } - else { + } else { printf("Option $opt_name should be either 'email' or 'full'.\n"); exit 1; } @@ -166,7 +167,7 @@ exit 1 unless ($ok); $send_email++ if ($send_all); # if we send all, then we must want emails. -if ( $send_email && !$admin_email && ($report eq 'full')) { +if ( $send_email && !$admin_email && ( $report eq 'full' ) ) { printf("Sending the full report by email requires --admin-email.\n"); exit 1; } @@ -198,8 +199,7 @@ sub execute { my $reason = $item->{reason}; if ( $reason eq 'repatriation' ) { $item->{object}->repatriate; - } - elsif ( grep { $reason eq $_ } qw/in-demand advancement initiation/ ) { + } elsif ( grep { $reason eq $_ } qw/in-demand advancement initiation/ ) { $item->{object}->advance; } } @@ -242,30 +242,28 @@ sub report_full { Total items to be repatriated: %5u Total items to be advanced: %5u Total items in demand: %5u\n\n", - $data->{sum_rotas}, $data->{rotas_inactive}, $data->{rotas_active}, - $data->{sum_items}, $data->{items_inactive}, $data->{stationary}, - $data->{actionable}, $data->{initiable}, $data->{repatriable}, - $data->{advanceable}, $data->{indemand}; + $data->{sum_rotas}, $data->{rotas_inactive}, $data->{rotas_active}, + $data->{sum_items}, $data->{items_inactive}, $data->{stationary}, + $data->{actionable}, $data->{initiable}, $data->{repatriable}, + $data->{advanceable}, $data->{indemand}; if ( @{ $data->{rotas} } ) { # Per Rota details $body .= "ROTAS DETAIL\n"; $body .= "------------\n\n"; foreach my $rota ( @{ $data->{rotas} } ) { $body .= sprintf "Details for %s [%s]:\n", - $rota->{name}, $rota->{id}; + $rota->{name}, $rota->{id}; $body .= "\n Items:"; # Rota item details if ( @{ $rota->{items} } ) { $body .= - join( "", map { _print_item($_) } @{ $rota->{items} } ); - } - else { + join( "", map { _print_item($_) } @{ $rota->{items} } ); + } else { $body .= "\n No items to be processed for this rota.\n"; } $body .= "\n Log:"; # Rota log details if ( @{ $rota->{log} } ) { $body .= join( "", map { _print_item($_) } @{ $rota->{log} } ); - } - else { + } else { $body .= "\n No items in log for this rota.\n\n"; } } @@ -277,8 +275,8 @@ sub report_full { title => 'Stockrotation Report', content => $body # The body of the report }, - status => 1, # We have a meaningful report - no_branch_email => 1, # We don't expect branch email in report + status => 1, # We have a meaningful report + no_branch_email => 1, # We don't expect branch email in report } ]; } @@ -320,17 +318,15 @@ sub report_by_branch { if ($branch) { # Branch limited report push @{$out}, _report_per_branch( $branched->{ $branch->branchcode } ); - } - elsif ( $data->{actionable} ) { # Full email report + } elsif ( $data->{actionable} ) { # Full email report while ( my ( $branchcode_id, $details ) = each %{$branched} ) { push @{$out}, _report_per_branch($details) - if ( @{ $details->{items} } ); + if ( @{ $details->{items} } ); } - } - else { + } else { push @{$out}, { - body => "No actionable items at any libraries.\n\n", # The body of the report - no_branch_email => 1, # We don't expect branch email in report + body => "No actionable items at any libraries.\n\n", # The body of the report + no_branch_email => 1, # We don't expect branch email in report }; } return $out; @@ -365,7 +361,7 @@ sub _report_per_branch { message_transport_type => 'email', substitute => { branch => $branch } ) - ) + ) { return { letter => $letter, @@ -399,11 +395,11 @@ sub _print_item { On loan?: %s Status: %s Current Library: %s [%s]\n\n", - $item->{title} || "N/A", $item->{author} || "N/A", - $item->{callnumber} || "N/A", $item->{location} || "N/A", - $item->{barcode} || "N/A", $item->{onloan} ? 'Yes' : 'No', - $item->{reason} || "N/A", $item->{branch}->branchname, - $item->{branch}->branchcode; + $item->{title} || "N/A", $item->{author} || "N/A", + $item->{callnumber} || "N/A", $item->{location} || "N/A", + $item->{barcode} || "N/A", $item->{onloan} ? 'Yes' : 'No', + $item->{reason} || "N/A", $item->{branch}->branchname, + $item->{branch}->branchcode; } =head3 emit @@ -427,14 +423,14 @@ die. sub emit { my ($params) = @_; -# REPORT is an arrayref of at least 2 elements: -# - The header for the report, which will be repeated for each part -# - a "part" for each report we want to emit -# PARTS are hashrefs: -# - part->{status}: a boolean indicating whether the reported part is empty or not -# - part->{email_address}: the email address to send the report to -# - part->{no_branch_email}: a boolean indicating that we are missing a branch email -# - part->{letter}: a GetPreparedLetter hash as returned by the C4::Letters module + # REPORT is an arrayref of at least 2 elements: + # - The header for the report, which will be repeated for each part + # - a "part" for each report we want to emit + # PARTS are hashrefs: + # - part->{status}: a boolean indicating whether the reported part is empty or not + # - part->{email_address}: the email address to send the report to + # - part->{no_branch_email}: a boolean indicating that we are missing a branch email + # - part->{letter}: a GetPreparedLetter hash as returned by the C4::Letters module my $report = $params->{report}; my $header = shift @{$report}; my $parts = $report; @@ -451,10 +447,9 @@ sub emit { my $addressee; if ( $part->{email_address} ) { $addressee = $part->{email_address}; - } - elsif ( !$part->{no_branch_email} ) { + } elsif ( !$part->{no_branch_email} ) { $addressee = C4::Context->preference('KohaAdminEmailAddress') - if ( C4::Context->preference('KohaAdminEmailAddress') ); + if ( C4::Context->preference('KohaAdminEmailAddress') ); } if ( $params->{send_email} ) { # Only email if emails requested @@ -465,9 +460,7 @@ sub emit { to_address => $addressee, message_transport_type => 'email', } - ) - or warn - "can't enqueue letter $part->{letter} for $addressee"; + ) or warn "can't enqueue letter $part->{letter} for $addressee"; } # Copy to admin? @@ -478,20 +471,14 @@ sub emit { to_address => $params->{admin_email}, message_transport_type => 'email', } - ) - or warn - "can't enqueue letter $part->{letter} for $params->{admin_email}"; + ) or warn "can't enqueue letter $part->{letter} for $params->{admin_email}"; } - } - else { - my $email = - "-------- Email message --------" . "\n\n"; + } else { + my $email = "-------- Email message --------" . "\n\n"; $email .= "To: $addressee\n"; $email .= "Cc: " . $params->{admin_email} . "\n" - if ( $params->{admin_email} ); - $email .= "Subject: " - . $part->{letter}->{title} . "\n\n" - . $part->{letter}->{content}; + if ( $params->{admin_email} ); + $email .= "Subject: " . $part->{letter}->{title} . "\n\n" . $part->{letter}->{content}; push @emails, $email; } } @@ -503,7 +490,7 @@ sub emit { # The final message is the header + body of this part. my $msg = $header; $msg .= "No database updates have been performed.\n\n" - unless ( $params->{execute} ); + unless ( $params->{execute} ); # Append email reports to message $msg .= join( "\n\n", @emails ); @@ -514,7 +501,7 @@ sub emit { #### Main Code # Compile Stockrotation Report data -my $rotas = Koha::StockRotationRotas->search(undef,{ order_by => { '-asc' => 'title' }}); +my $rotas = Koha::StockRotationRotas->search( undef, { order_by => { '-asc' => 'title' } } ); my $data = $rotas->investigate; # Perform db updates if requested @@ -523,7 +510,7 @@ execute($data) if ($execute); # Emit Reports my $out_report = {}; $out_report = report_by_branch( $data, $branch ) if $report eq 'email'; -$out_report = report_full( $data, $branch ) if $report eq 'full'; +$out_report = report_full( $data, $branch ) if $report eq 'full'; emit( { admin_email => $admin_email, diff --git a/misc/cronjobs/thirdparty/TalkingTech_itiva_inbound.pl b/misc/cronjobs/thirdparty/TalkingTech_itiva_inbound.pl index 6b876c9dbb..0dff8e8413 100755 --- a/misc/cronjobs/thirdparty/TalkingTech_itiva_inbound.pl +++ b/misc/cronjobs/thirdparty/TalkingTech_itiva_inbound.pl @@ -21,7 +21,7 @@ use strict; use warnings; use Getopt::Long qw( GetOptions ); -use Pod::Usage qw( pod2usage ); +use Pod::Usage qw( pod2usage ); use Koha::Script -cron; use C4::Context; @@ -31,9 +31,8 @@ sub usage { exit; } -die - "TalkingTechItivaPhoneNotification system preference not activated... dying\n" - unless ( C4::Context->preference("TalkingTechItivaPhoneNotification") ); +die "TalkingTechItivaPhoneNotification system preference not activated... dying\n" + unless ( C4::Context->preference("TalkingTechItivaPhoneNotification") ); # Database handle my $dbh = C4::Context->dbh; @@ -70,8 +69,7 @@ if ( defined $infile ) { $total++; } close($IN); -} -else { +} else { die pod2usage( -verbose => 1 ); } @@ -113,18 +111,15 @@ sub update_notice { if ( $status =~ m/SUCCESS/i ) { $status = 'sent'; - } - elsif ( $status =~ m/FAIL/i ) { + } elsif ( $status =~ m/FAIL/i ) { $status = 'failed'; - } - else { + } else { warn "unexpected status $status for message ID $message_id\n"; return 0; } - my $query = -"UPDATE message_queue SET status = ? WHERE message_id = ? and status = 'pending'"; - my $sth = $dbh->prepare($query); + my $query = "UPDATE message_queue SET status = ? WHERE message_id = ? and status = 'pending'"; + my $sth = $dbh->prepare($query); my $result = $sth->execute( $status, $message_id ); return $result; diff --git a/misc/cronjobs/thirdparty/TalkingTech_itiva_outbound.pl b/misc/cronjobs/thirdparty/TalkingTech_itiva_outbound.pl index dfc6812be6..e3226722b5 100755 --- a/misc/cronjobs/thirdparty/TalkingTech_itiva_outbound.pl +++ b/misc/cronjobs/thirdparty/TalkingTech_itiva_outbound.pl @@ -21,7 +21,7 @@ use strict; use warnings; use Getopt::Long qw( GetOptions ); -use Pod::Usage qw( pod2usage ); +use Pod::Usage qw( pod2usage ); use Koha::Script -cron; use C4::Context; @@ -38,7 +38,7 @@ sub usage { } die "TalkingTechItivaPhoneNotification system preference not activated... dying\n" - unless ( C4::Context->preference("TalkingTechItivaPhoneNotification") ); + unless ( C4::Context->preference("TalkingTechItivaPhoneNotification") ); # Database handle my $dbh = C4::Context->dbh; @@ -88,7 +88,7 @@ pod2usage( -verbose => 1 ) if $help; if ($patron_branchcode) { die("Invalid branchcode '$patron_branchcode' passed in -pb --patron-branchcode parameter") - unless Koha::Libraries->search( { branchcode => $patron_branchcode } )->count; + unless Koha::Libraries->search( { branchcode => $patron_branchcode } )->count; } # output log or STDOUT @@ -97,7 +97,7 @@ if ( defined $outfile ) { open( $OUT, '>', "$outfile" ) || die("Cannot open output file"); } else { print "No output file defined; printing to STDOUT\n" - if ( defined $verbose ); + if ( defined $verbose ); $OUT = *STDOUT || die "Couldn't duplicate STDOUT: $!"; } @@ -108,38 +108,39 @@ my ( $if_patron_field_equals_field, $if_patron_field_equals_value ); if $skip_patrons_with_field_match; foreach my $type (@types) { - $type = uc($type); #just in case lower or mixed-case was supplied + $type = uc($type); #just in case lower or mixed-case was supplied my $module = $type_module_map->{$type}; #since the module is required to get the letter my $code = $type_notice_map->{$type}; #to get the Koha name of the notice my @loop; if ( $type eq 'OVERDUE' ) { - @loop = GetOverdueIssues( $patron_branchcode ); + @loop = GetOverdueIssues($patron_branchcode); } elsif ( $type eq 'PREOVERDUE' ) { - @loop = GetPredueIssues( $patron_branchcode ); + @loop = GetPredueIssues($patron_branchcode); } elsif ( $type eq 'RESERVE' ) { - @loop = GetWaitingHolds( $patron_branchcode ); + @loop = GetWaitingHolds($patron_branchcode); } else { print "Unknown or unsupported message type $type; skipping...\n" - if ( defined $verbose ); + if ( defined $verbose ); next; } my $patrons; foreach my $issues (@loop) { - $patrons->{$issues->{borrowernumber}} ||= Koha::Patrons->find( $issues->{borrowernumber} ) if $skip_patrons_with_email; + $patrons->{ $issues->{borrowernumber} } ||= Koha::Patrons->find( $issues->{borrowernumber} ) + if $skip_patrons_with_email; next if $skip_patrons_with_email && $patrons->{ $issues->{borrowernumber} }->notice_email_address; next if $skip_patrons_with_field_match && $patrons->{ $issues->{borrowernumber} }->$if_patron_field_equals_field eq $if_patron_field_equals_value; - my $date_dt = dt_from_string ( $issues->{'date_due'} ); - my $due_date = output_pref( { dt => $date_dt, dateonly => 1, dateformat =>'metric' } ); + my $date_dt = dt_from_string( $issues->{'date_due'} ); + my $due_date = output_pref( { dt => $date_dt, dateonly => 1, dateformat => 'metric' } ); my $letter = C4::Letters::GetPreparedLetter( module => $module, letter_code => $code, - lang => 'default', # It does not sound useful to send a lang here + lang => 'default', # It does not sound useful to send a lang here tables => { borrowers => $issues->{'borrowernumber'}, biblio => $issues->{'biblionumber'}, @@ -153,7 +154,8 @@ foreach my $type (@types) { my $message_id = 0; if ($outfile) { $message_id = C4::Letters::EnqueueLetter( - { letter => $letter, + { + letter => $letter, borrowernumber => $issues->{'borrowernumber'}, message_transport_type => 'itiva', } @@ -163,9 +165,11 @@ foreach my $type (@types) { $issues->{title} =~ s/'//g; $issues->{title} =~ s/"//g; - print $OUT "\"$format\",\"$language\",\"$type\",\"$issues->{level}\",\"$issues->{cardnumber}\",\"$issues->{patron_title}\",\"$issues->{firstname}\","; + print $OUT + "\"$format\",\"$language\",\"$type\",\"$issues->{level}\",\"$issues->{cardnumber}\",\"$issues->{patron_title}\",\"$issues->{firstname}\","; print $OUT "\"$issues->{surname}\",\"$issues->{phone}\",\"$issues->{email}\",\"$library_code\","; - print $OUT "\"$issues->{site}\",\"$issues->{site_name}\",\"$issues->{barcode}\",\"$due_date\",\"$issues->{title}\",\"$message_id\"\n"; + print $OUT + "\"$issues->{site}\",\"$issues->{site_name}\",\"$issues->{barcode}\",\"$due_date\",\"$issues->{title}\",\"$message_id\"\n"; } } @@ -251,11 +255,12 @@ Items and holds from other libraries will still be included for the given patron =cut sub GetOverdueIssues { - my ( $patron_branchcode ) = @_; + my ($patron_branchcode) = @_; my $patron_branchcode_filter = $patron_branchcode ? "AND borrowers.branchcode = '$patron_branchcode'" : q{}; - my $query = "SELECT borrowers.borrowernumber, borrowers.cardnumber, borrowers.title as patron_title, borrowers.firstname, borrowers.surname, + my $query = + "SELECT borrowers.borrowernumber, borrowers.cardnumber, borrowers.title as patron_title, borrowers.firstname, borrowers.surname, borrowers.phone, borrowers.email, borrowers.branchcode, biblio.biblionumber, biblio.title, items.barcode, issues.date_due, max(overduerules.branchcode) as rulebranch, TO_DAYS(NOW())-TO_DAYS(date_due) as daysoverdue, delay1, delay2, delay3, issues.branchcode as site, branches.branchname as site_name @@ -293,11 +298,12 @@ sub GetOverdueIssues { } sub GetPredueIssues { - my ( $patron_branchcode ) = @_; + my ($patron_branchcode) = @_; my $patron_branchcode_filter = $patron_branchcode ? "AND borrowers.branchcode = '$patron_branchcode'" : q{}; - my $query = "SELECT borrowers.borrowernumber, borrowers.cardnumber, borrowers.title as patron_title, borrowers.firstname, borrowers.surname, + my $query = + "SELECT borrowers.borrowernumber, borrowers.cardnumber, borrowers.title as patron_title, borrowers.firstname, borrowers.surname, borrowers.phone, borrowers.email, borrowers.branchcode, biblio.biblionumber, biblio.title, items.barcode, issues.date_due, issues.branchcode as site, branches.branchname as site_name FROM borrowers JOIN issues USING (borrowernumber) @@ -323,11 +329,12 @@ sub GetPredueIssues { } sub GetWaitingHolds { - my ( $patron_branchcode ) = @_; + my ($patron_branchcode) = @_; my $patron_branchcode_filter = $patron_branchcode ? "AND borrowers.branchcode = '$patron_branchcode'" : q{}; - my $query = "SELECT borrowers.borrowernumber, borrowers.cardnumber, borrowers.title as patron_title, borrowers.firstname, borrowers.surname, borrowers.categorycode, + my $query = + "SELECT borrowers.borrowernumber, borrowers.cardnumber, borrowers.title as patron_title, borrowers.firstname, borrowers.surname, borrowers.categorycode, borrowers.phone, borrowers.email, borrowers.branchcode, biblio.biblionumber, biblio.title, items.barcode, reserves.waitingdate, reserves.branchcode AS site, branches.branchname AS site_name, TO_DAYS(NOW())-TO_DAYS(reserves.waitingdate) AS days_since_waiting, @@ -344,11 +351,11 @@ sub GetWaitingHolds { AND message_name = 'Hold_Filled' $patron_branchcode_filter "; - my $sth = $dbh->prepare($query); + my $sth = $dbh->prepare($query); $sth->execute(); my @results; while ( my $issue = $sth->fetchrow_hashref() ) { - my $item = Koha::Items->find({ barcode => $issue->{barcode} }); + my $item = Koha::Items->find( { barcode => $issue->{barcode} } ); my $daysmode = Koha::CirculationRules->get_effective_daysmode( { categorycode => $issue->{categorycode}, @@ -361,19 +368,20 @@ sub GetWaitingHolds { my $waiting_date = dt_from_string( $issue->{waitingdate}, 'sql' ); - $issue->{'date_due'} = output_pref({dt => dt_from_string($issue->{expirationdate}), dateformat => 'iso' }); - $issue->{'level'} = 1; # only one level for Hold Waiting notifications + $issue->{'date_due'} = output_pref( { dt => dt_from_string( $issue->{expirationdate} ), dateformat => 'iso' } ); + $issue->{'level'} = 1; # only one level for Hold Waiting notifications my $days_to_subtract = 0; if ( $calendar->is_holiday($waiting_date) ) { my $next_open_day = $calendar->next_open_days( $waiting_date, 1 ); - $days_to_subtract = $calendar->days_between($waiting_date, $next_open_day)->days; + $days_to_subtract = $calendar->days_between( $waiting_date, $next_open_day )->days; } $issue->{'days_since_waiting'} = $issue->{'days_since_waiting'} - $days_to_subtract; if ( ( grep $_ eq $issue->{'days_since_waiting'}, @holds_waiting_days_to_call ) - || !scalar(@holds_waiting_days_to_call) ) { + || !scalar(@holds_waiting_days_to_call) ) + { push @results, $issue; } } diff --git a/misc/cronjobs/writeoff_debts.pl b/misc/cronjobs/writeoff_debts.pl index ec990c41a3..4c9dea6fc3 100755 --- a/misc/cronjobs/writeoff_debts.pl +++ b/misc/cronjobs/writeoff_debts.pl @@ -4,7 +4,7 @@ use Modern::Perl; use feature 'say'; use Getopt::Long qw( GetOptions ); -use Pod::Usage qw( pod2usage ); +use Pod::Usage qw( pod2usage ); use Koha::Account::Lines; use Koha::DateUtils qw( dt_from_string ); @@ -38,12 +38,12 @@ if ( !$file && !@type && !$before && !$after && !@category_code ) { } my $where = { 'amountoutstanding' => { '>' => 0 } }; -my $attr = {}; +my $attr = {}; if ($file) { my @accounts_from_file; open( my $fh, '<:encoding(UTF-8)', $file ) - or die "Could not open file '$file' $!"; + or die "Could not open file '$file' $!"; while ( my $line = <$fh> ) { chomp($line); push @accounts_from_file, $line; @@ -57,7 +57,7 @@ if (@type) { } my $dtf; -if ($before||$after) { +if ( $before || $after ) { $dtf = Koha::Database->new->schema->storage->datetime_parser; } @@ -77,19 +77,19 @@ if (@category_code) { } my $lines = Koha::Account::Lines->search( $where, $attr ); -if ( $verbose ) { +if ($verbose) { print "Attempting to write off " . $lines->count . " debts"; - print " of type " . join(',',@type) if @type; - print " added before " . $before if $before; - print " from the passed list" if $file; + print " of type " . join( ',', @type ) if @type; + print " added before " . $before if $before; + print " from the passed list" if $file; print "\n"; } while ( my $line = $lines->next ) { say "Skipping " . $line->accountlines_id . "; Not a debt" and next - if $line->is_credit && $verbose > 1; + if $line->is_credit && $verbose > 1; say "Skipping " . $line->accountlines_id . "; Is a PAYOUT" and next - if $line->debit_type_code eq 'PAYOUT' && $verbose > 1; + if $line->debit_type_code eq 'PAYOUT' && $verbose > 1; if ($confirm) { $line->_result->result_source->schema->txn_do( @@ -119,11 +119,7 @@ while ( my $line = $lines->next ) { )->store(); # Link writeoff to charge - $writeoff->apply( - { - debits => [$line] - } - ); + $writeoff->apply( { debits => [$line] } ); $writeoff->status('APPLIED')->store(); # Update status of original debit @@ -135,8 +131,7 @@ while ( my $line = $lines->next ) { if ($verbose) { if ($confirm) { say "Accountline " . $line->accountlines_id . " written off"; - } - else { + } else { say "Accountline " . $line->accountlines_id . " will be written off"; } } diff --git a/misc/devel/add_missing_filters.pl b/misc/devel/add_missing_filters.pl index 51e7c1da5a..d68df44461 100755 --- a/misc/devel/add_missing_filters.pl +++ b/misc/devel/add_missing_filters.pl @@ -2,16 +2,16 @@ use Modern::Perl; -use File::Slurp qw( read_file write_file ); -use Pod::Usage qw( pod2usage ); +use File::Slurp qw( read_file write_file ); +use Pod::Usage qw( pod2usage ); use Getopt::Long qw( GetOptions ); use t::lib::QA::TemplateFilters; my ( $help, $verbose, @files ); GetOptions( - 'h|help' => \$help, - 'v|verbose' => \$verbose, + 'h|help' => \$help, + 'v|verbose' => \$verbose, ) || pod2usage(1); @files = @ARGV; @@ -19,26 +19,25 @@ GetOptions( pod2usage(1) if $help or not @files; my $i; -my $total = scalar @files; +my $total = scalar @files; my $num_width = length $total; -for my $file ( @ARGV ) { - if ( $verbose ) { +for my $file (@ARGV) { + if ($verbose) { print sprintf "|%-25s| %${num_width}s / %s (%.2f%%)\r", - '=' x (24*$i++/$total). '>', - $i, $total, 100*$i/+$total; + '=' x ( 24 * $i++ / $total ) . '>', + $i, $total, 100 * $i / +$total; flush STDOUT; } - my $content = read_file( $file ); + my $content = read_file($file); my $new_content = t::lib::QA::TemplateFilters::fix_filters($content); $new_content .= "\n"; if ( $content ne $new_content ) { say "$file -- Modified"; - write_file($file, $new_content); + write_file( $file, $new_content ); } } - =head1 NAME add_missing_filters.pl - Will add the missing filters to the template files given in parameters. diff --git a/misc/devel/auto_rebase.pl b/misc/devel/auto_rebase.pl index 5c76bca273..ab28e42a73 100755 --- a/misc/devel/auto_rebase.pl +++ b/misc/devel/auto_rebase.pl @@ -77,7 +77,7 @@ $new_branch ||= "$source_branch-rebased"; say BLUE "Creating a temporary branch '$tmp_src_branch'..."; try { - $git->checkout('-b', $tmp_src_branch); + $git->checkout( '-b', $tmp_src_branch ); } catch { say MAGENTA $_->error; say RED sprintf "Cannot create and checkout branch '%s'.", $tmp_src_branch; @@ -110,7 +110,7 @@ unless ( $git->branch( $source_branch, '--contains', $commit_before_tidy ) ) { # Create a new branch say BLUE "Creating a new branch '$new_branch' starting at the end of the tidy commits..."; try { - $git->checkout('-b', $new_branch, $tidy_commit); + $git->checkout( '-b', $new_branch, $tidy_commit ); } catch { say MAGENTA $_->error; say RED sprintf "Cannot create and checkout branch '%s'.", $new_branch; @@ -141,13 +141,13 @@ unless ($nb_commits) { # Apply each commit to the new branch my @commits = reverse $git->RUN( 'log', '--format=%h', "$tmp_src_branch~$nb_commits..$tmp_src_branch" ); say BLUE sprintf "Processing %s commits...", scalar(@commits); -while ( my ($i, $commit) = each @commits ) { - say BLUE sprintf "\tProcessing commit %s... (%s/%s)", $commit, $i+1, scalar @commits; +while ( my ( $i, $commit ) = each @commits ) { + say BLUE sprintf "\tProcessing commit %s... (%s/%s)", $commit, $i + 1, scalar @commits; # Get the list of modified files in this commit my @modified_files = $git->diff_tree( '--no-commit-id', '--name-only', '-r', $commit ); - FILE: while ( my ( $ii, $file ) = each @modified_files ) { - say BLUE sprintf "\t\tProcessing file %s... (%s/%s)", $file, $ii+1, scalar @modified_files; +FILE: while ( my ( $ii, $file ) = each @modified_files ) { + say BLUE sprintf "\t\tProcessing file %s... (%s/%s)", $file, $ii + 1, scalar @modified_files; # Retrieve the content of the file from this commit my @content = try { @@ -162,7 +162,7 @@ while ( my ($i, $commit) = each @commits ) { } }; - next unless @content; # We removed the file + next unless @content; # We removed the file write_file( $file, join "\n", @content ); diff --git a/misc/devel/coverage.pl b/misc/devel/coverage.pl index a4d09344cc..29185251b2 100755 --- a/misc/devel/coverage.pl +++ b/misc/devel/coverage.pl @@ -48,22 +48,20 @@ prints this help text use Modern::Perl; use C4::Context; -use Cwd qw( getcwd ); +use Cwd qw( getcwd ); use Getopt::Long qw( GetOptions ); -use Pod::Usage qw( pod2usage ); +use Pod::Usage qw( pod2usage ); my $help; -GetOptions( - "h|help" => \$help -); +GetOptions( "h|help" => \$help ); pod2usage(1) if defined $help; #Die if you are not in your Koha src directory my $KOHA_PATH = C4::Context->config("intranetdir"); die "ERROR : You are not in Koha src/ directory" - unless $KOHA_PATH eq getcwd; + unless $KOHA_PATH eq getcwd; # Delete old coverage system("cover -delete"); @@ -74,6 +72,6 @@ system("PERL5OPT=-MDevel::Cover /usr/bin/prove -r t/"); #Create the HTML output system("cover"); say("file://$KOHA_PATH/cover_db/coverage.html") - unless !-e "$KOHA_PATH/cover_db/coverage.html"; + unless !-e "$KOHA_PATH/cover_db/coverage.html"; -1; \ No newline at end of file +1; diff --git a/misc/devel/get_prepared_letter.pl b/misc/devel/get_prepared_letter.pl index 5ef852cb25..c972a9fc86 100755 --- a/misc/devel/get_prepared_letter.pl +++ b/misc/devel/get_prepared_letter.pl @@ -70,14 +70,16 @@ documentation of GetPreparedLetter for more informations. use Modern::Perl; use Getopt::Long qw( GetOptions ); -use JSON qw( decode_json ); -use Pod::Usage qw( pod2usage ); +use JSON qw( decode_json ); +use Pod::Usage qw( pod2usage ); use C4::Letters qw( GetPreparedLetter ); my $help; -my ( $module, $letter_code, $branchcode, $message_transport_type, $lang, - $repeat, $tables, $loops ); +my ( + $module, $letter_code, $branchcode, $message_transport_type, $lang, + $repeat, $tables, $loops +); GetOptions( 'help' => \$help, diff --git a/misc/devel/install_plugins.pl b/misc/devel/install_plugins.pl index 2ccc68a15b..ccd3e676ee 100755 --- a/misc/devel/install_plugins.pl +++ b/misc/devel/install_plugins.pl @@ -19,7 +19,7 @@ use Modern::Perl; use Getopt::Long qw( GetOptions ); -use Pod::Usage qw( pod2usage ); +use Pod::Usage qw( pod2usage ); use Koha::Script; @@ -32,15 +32,16 @@ GetOptions( 'help|?' => \$help ); pod2usage(1) if $help; unless ( C4::Context->config("enable_plugins") ) { - print -"The plugin system must be enabled for one to be able to install plugins\n"; + print "The plugin system must be enabled for one to be able to install plugins\n"; exit 1; } -my @existing_plugins = Koha::Plugins->new()->GetPlugins({ - all => 1, - verbose => 1, # warns about plugins failing to load -}); +my @existing_plugins = Koha::Plugins->new()->GetPlugins( + { + all => 1, + verbose => 1, # warns about plugins failing to load + } +); my $existing_plugins; for my $existing_plugin (@existing_plugins) { $existing_plugins->{ $existing_plugin->{metadata}->{name} } = $existing_plugin->{metadata}->{version}; @@ -52,31 +53,26 @@ unless (@installed_plugins) { if ( ref($plugins_dir) eq 'ARRAY' ) { print "No plugins found\n"; print "pluginsdir contains: \n" . join( "\n", @{$plugins_dir} ) . "\n"; - } - else { + } else { print "No plugins found at $plugins_dir\n"; } exit 0; } for my $installed_plugin (@installed_plugins) { - if ( !exists( $existing_plugins->{ $installed_plugin->{metadata}->{name} } ) - ) - { + if ( !exists( $existing_plugins->{ $installed_plugin->{metadata}->{name} } ) ) { print "Installed " - . $installed_plugin->{metadata}->{name} - . " version " - . $installed_plugin->{metadata}->{version} . "\n"; - } - elsif ( $existing_plugins->{ $installed_plugin->{metadata}->{name} } ne - $installed_plugin->{metadata}->{version} ) + . $installed_plugin->{metadata}->{name} + . " version " + . $installed_plugin->{metadata}->{version} . "\n"; + } elsif ( $existing_plugins->{ $installed_plugin->{metadata}->{name} } ne $installed_plugin->{metadata}->{version} ) { print "Upgraded " - . $installed_plugin->{metadata}->{name} - . " from version " - . $existing_plugins->{ $installed_plugin->{metadata}->{name} } - . " to version " - . $installed_plugin->{metadata}->{version} . "\n"; + . $installed_plugin->{metadata}->{name} + . " from version " + . $existing_plugins->{ $installed_plugin->{metadata}->{name} } + . " to version " + . $installed_plugin->{metadata}->{version} . "\n"; } } print "All plugins successfully re-initialised\n"; diff --git a/misc/devel/koha_perl_deps.pl b/misc/devel/koha_perl_deps.pl index 415728299a..63fcb16a52 100755 --- a/misc/devel/koha_perl_deps.pl +++ b/misc/devel/koha_perl_deps.pl @@ -1,9 +1,9 @@ #!/usr/bin/perl -use Getopt::Long qw( GetOptions ); -use Pod::Usage qw( pod2usage ); +use Getopt::Long qw( GetOptions ); +use Pod::Usage qw( pod2usage ); use Term::ANSIColor qw( color ); -use FindBin; # we need to enforce which C4::Installer is used in case more than one is installed +use FindBin; # we need to enforce which C4::Installer is used in case more than one is installed use lib $FindBin::Bin; @@ -11,40 +11,40 @@ use C4::Installer::PerlModules; use Modern::Perl; -my $help = 0; -my $missing = 0; +my $help = 0; +my $missing = 0; my $installed = 0; -my $upgrade = 0; -my $all = 0; -my $color = 0; -my $brief = 0; -my $req = 0; +my $upgrade = 0; +my $all = 0; +my $color = 0; +my $brief = 0; +my $req = 0; GetOptions( - 'h|help|?' => \$help, - 'm|missing' => \$missing, - 'i|installed' => \$installed, - 'u|upgrade' => \$upgrade, - 'a|all' => \$all, - 'b|brief' => \$brief, - 'r|required' => \$req, - 'c|color' => \$color, - ); + 'h|help|?' => \$help, + 'm|missing' => \$missing, + 'i|installed' => \$installed, + 'u|upgrade' => \$upgrade, + 'a|all' => \$all, + 'b|brief' => \$brief, + 'r|required' => \$req, + 'c|color' => \$color, +); -pod2usage(1) if $help || (!$missing && !$installed && !$upgrade && !$all); +pod2usage(1) if $help || ( !$missing && !$installed && !$upgrade && !$all ); my $koha_pm = C4::Installer::PerlModules->new; $koha_pm->versions_info; my @pm = (); -push @pm, 'missing_pm' if $missing || $all; -push @pm, 'upgrade_pm' if $upgrade || $all; +push @pm, 'missing_pm' if $missing || $all; +push @pm, 'upgrade_pm' if $upgrade || $all; push @pm, 'current_pm' if $installed || $all; -if (!$brief) { +if ( !$brief ) { print color 'bold blue' if $color; - print" + print " Installed Required Module is Module Name Version Version Required -------------------------------------------------------------------------------------------- @@ -57,25 +57,27 @@ foreach my $type (@pm) { $mod_type =~ s/_pm$//; my $pm = $koha_pm->get_attr($type); foreach (@$pm) { - foreach my $pm (keys(%$_)) { + foreach my $pm ( keys(%$_) ) { print color 'yellow' if $type eq 'upgrade_pm' && $color; - print color 'red' if $type eq 'missing_pm' && $color; - print color 'green' if $type eq 'current_pm' && $color; - my $required = ($_->{$pm}->{'required'}?'Yes':'No'); - my $current_version = ($color ? $_->{$pm}->{'cur_ver'} : - $type eq 'missing_pm' || $type eq 'upgrade_pm' ? $_->{$pm}->{'cur_ver'}." *" : $_->{$pm}->{'cur_ver'}); - if (!$brief) { - if (($req && $required eq 'Yes') || !$req) { -format = + print color 'red' if $type eq 'missing_pm' && $color; + print color 'green' if $type eq 'current_pm' && $color; + my $required = ( $_->{$pm}->{'required'} ? 'Yes' : 'No' ); + my $current_version = ( + $color ? $_->{$pm}->{'cur_ver'} + : $type eq 'missing_pm' || $type eq 'upgrade_pm' ? $_->{$pm}->{'cur_ver'} . " *" + : $_->{$pm}->{'cur_ver'} + ); + if ( !$brief ) { + if ( ( $req && $required eq 'Yes' ) || !$req ) { + format = @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< @<<<<<<<<<<<<<<<< @<<<<<<<<<<<<<<<< @<<<<< $pm, $current_version, $_->{$pm}->{'min_ver'}, $required . -write; + write; $count++; } - } - else { - if (($req && $required eq 'Yes') || !$req) { + } else { + if ( ( $req && $required eq 'Yes' ) || !$req ) { print "$pm\n"; $count++; } @@ -84,7 +86,7 @@ write; } } -if (!$brief) { +if ( !$brief ) { print color 'bold blue' if $color; my $footer = " -------------------------------------------------------------------------------------------- @@ -92,8 +94,7 @@ Total modules reported: $count "; if ($color) { $footer .= "\n\n"; - } - else { + } else { $footer .= "* Module is missing or requires an upgrade.\n\n"; } diff --git a/misc/devel/update_dbix_class_files.pl b/misc/devel/update_dbix_class_files.pl index 747c000708..ea78a1fc6a 100755 --- a/misc/devel/update_dbix_class_files.pl +++ b/misc/devel/update_dbix_class_files.pl @@ -22,12 +22,12 @@ use Modern::Perl; use DBIx::Class::Schema::Loader qw/ make_schema_at /; use Getopt::Long qw( GetOptions ); -use Pod::Usage qw( pod2usage ); +use Pod::Usage qw( pod2usage ); my %db_defaults = ( driver => 'mysql', - host => 'localhost', - port => '3306', + host => 'localhost', + port => '3306', ); my $path = "./"; @@ -57,14 +57,14 @@ GetOptions( # If we were asked for usage instructions, do it pod2usage(1) if defined $help; -if (defined $koha_conf) { - if ($koha_conf eq '' and not defined $ENV{KOHA_CONF}) { +if ( defined $koha_conf ) { + if ( $koha_conf eq '' and not defined $ENV{KOHA_CONF} ) { print STDERR "Error: KOHA_CONF is not defined\n"; exit(1); } $koha_conf ||= $ENV{KOHA_CONF}; - unless (-r $koha_conf) { + unless ( -r $koha_conf ) { print STDERR "Error: File $koha_conf does not exist or is not readable\n"; exit(1); } @@ -78,21 +78,21 @@ if (defined $koha_conf) { $context->set_context; $db_defaults{driver} = $context->config('db_scheme'); - $db_defaults{host} = $context->config('hostname'); - $db_defaults{port} = $context->config('port'); - $db_defaults{name} = $context->config('database'); - $db_defaults{user} = $context->config('user'); + $db_defaults{host} = $context->config('hostname'); + $db_defaults{port} = $context->config('port'); + $db_defaults{name} = $context->config('database'); + $db_defaults{user} = $context->config('user'); $db_defaults{passwd} = $context->config('pass'); } $db_driver //= $db_defaults{driver}; -$db_host //= $db_defaults{host}; -$db_port //= $db_defaults{port}; -$db_name //= $db_defaults{name}; -$db_user //= $db_defaults{user}; +$db_host //= $db_defaults{host}; +$db_port //= $db_defaults{port}; +$db_name //= $db_defaults{name}; +$db_user //= $db_defaults{user}; $db_passwd //= $db_defaults{passwd}; -if (! defined $db_name ) { +if ( !defined $db_name ) { print "Error: \'db_name\' parameter is mandatory.\n"; pod2usage(1); } else { diff --git a/misc/export_borrowers.pl b/misc/export_borrowers.pl index b6a19d4dd8..5c316d62c9 100755 --- a/misc/export_borrowers.pl +++ b/misc/export_borrowers.pl @@ -73,7 +73,7 @@ GetOptions( 'field|f=s' => \@fields, 'separator|s=s' => \$separator, 'show-header|H' => \$show_header, - 'where|w=s' => \$where, + 'where|w=s' => \$where, 'help|h' => \$help ) or print_usage, exit 1; @@ -87,10 +87,10 @@ my $dbh = C4::Context->dbh; my $query = "SELECT borrowernumber FROM borrowers"; $query .= " WHERE $where" if ($where); $query .= " ORDER BY borrowernumber"; -my $sth = $dbh->prepare($query); +my $sth = $dbh->prepare($query); $sth->execute; -unless ( $separator ) { +unless ($separator) { $separator = C4::Context->csv_delimiter; } @@ -99,11 +99,11 @@ my $csv = Text::CSV->new( { sep_char => $separator, binary => 1, formula => 'emp # If the user did not specify any field to export, we assume they want them all # We retrieve the first borrower informations to get field names my ($borrowernumber) = $sth->fetchrow_array or die "No borrower to export"; -my $patron = Koha::Patrons->find( $borrowernumber ); # FIXME Now is_expired is no longer available - # We will have to use Koha::Patron and allow method calls +my $patron = Koha::Patrons->find($borrowernumber); # FIXME Now is_expired is no longer available + # We will have to use Koha::Patron and allow method calls my $category = $patron->category; -my $member = $patron->unblessed; -$member->{description} = $category->description; +my $member = $patron->unblessed; +$member->{description} = $category->description; $member->{category_type} = $category->category_type; @fields = keys %$member unless (@fields); @@ -113,33 +113,19 @@ if ($show_header) { print $csv->string . "\n"; } -$csv->combine( - map { - ( defined $member->{$_} and !ref $member->{$_} ) - ? $member->{$_} - : '' - } @fields -); -die "Invalid character at borrower $borrowernumber: [" - . $csv->error_input . "]\n" - if ( !defined( $csv->string ) ); +$csv->combine( map { ( defined $member->{$_} and !ref $member->{$_} ) ? $member->{$_} : '' } @fields ); +die "Invalid character at borrower $borrowernumber: [" . $csv->error_input . "]\n" + if ( !defined( $csv->string ) ); print $csv->string . "\n"; while ( my $borrowernumber = $sth->fetchrow_array ) { - my $patron = Koha::Patrons->find( $borrowernumber ); + my $patron = Koha::Patrons->find($borrowernumber); my $category = $patron->category; - my $member = $patron->unblessed; - $member->{description} = $category->description; + my $member = $patron->unblessed; + $member->{description} = $category->description; $member->{category_type} = $category->category_type; - $csv->combine( - map { - ( defined $member->{$_} and !ref $member->{$_} ) - ? $member->{$_} - : '' - } @fields - ); - die "Invalid character at borrower $borrowernumber: [" - . $csv->error_input . "]\n" - if ( !defined( $csv->string ) ); + $csv->combine( map { ( defined $member->{$_} and !ref $member->{$_} ) ? $member->{$_} : '' } @fields ); + die "Invalid character at borrower $borrowernumber: [" . $csv->error_input . "]\n" + if ( !defined( $csv->string ) ); print $csv->string . "\n"; } diff --git a/misc/exportauth.pl b/misc/exportauth.pl index 14e30884d2..5fc3dd4f2f 100755 --- a/misc/exportauth.pl +++ b/misc/exportauth.pl @@ -1,23 +1,26 @@ #!/usr/bin/perl -## This script allows you to export a rel_2_2 bibliographic db in +## This script allows you to export a rel_2_2 bibliographic db in #MARC21 format from the command line. # use strict; + #use warnings; FIXME - Bug 2505 use Koha::Script; use C4::Context; use C4::Auth; my $outfile = $ARGV[0]; -open(my $fh, '>', $outfile) or die $!; -my $dbh=C4::Context->dbh; -#$dbh->do("set character_set_client='latin5'"); +open( my $fh, '>', $outfile ) or die $!; +my $dbh = C4::Context->dbh; + +#$dbh->do("set character_set_client='latin5'"); $dbh->do("set character_set_connection='utf8'"); -#$dbh->do("set character_set_results='latin5'"); -my $sth=$dbh->prepare("select marc from auth_header order by authid"); + +#$dbh->do("set character_set_results='latin5'"); +my $sth = $dbh->prepare("select marc from auth_header order by authid"); $sth->execute(); -while (my ($marc) = $sth->fetchrow) { +while ( my ($marc) = $sth->fetchrow ) { print $fh $marc; - } +} close($fh); diff --git a/misc/import_patrons.pl b/misc/import_patrons.pl index 5d702d8f6f..b01a845c41 100755 --- a/misc/import_patrons.pl +++ b/misc/import_patrons.pl @@ -20,7 +20,7 @@ use Modern::Perl; use Getopt::Long qw( GetOptions ); -use Pod::Usage qw( pod2usage ); +use Pod::Usage qw( pod2usage ); use Koha::Script; use Koha::Patrons::Import; diff --git a/misc/link_bibs_to_authorities.pl b/misc/link_bibs_to_authorities.pl index 650de1d8e3..7137a6e54a 100755 --- a/misc/link_bibs_to_authorities.pl +++ b/misc/link_bibs_to_authorities.pl @@ -26,10 +26,10 @@ use C4::Biblio qw( ); use C4::Log qw( cronlogaction ); use Koha::Biblios; -use Getopt::Long qw( GetOptions ); -use Pod::Usage qw( pod2usage ); -use Time::HiRes qw( time ); -use POSIX qw( ceil strftime ); +use Getopt::Long qw( GetOptions ); +use Pod::Usage qw( pod2usage ); +use Time::HiRes qw( time ); +use POSIX qw( ceil strftime ); use Module::Load::Conditional qw( can_load ); use Koha::Database; @@ -54,8 +54,8 @@ my $commit = 100; my $tagtolink; my $allowrelink = C4::Context->preference("LinkerRelink") // ''; -my $command_line_options = join(" ", @ARGV); -my $result = GetOptions( +my $command_line_options = join( " ", @ARGV ); +my $result = GetOptions( 'v|verbose' => \$verbose, 't|test' => \$test_only, 'l|link-report' => \$link_report, @@ -74,8 +74,7 @@ if ( not $result or $want_help ) { cronlogaction( { info => $command_line_options } ); -my $linker_module = - "C4::Linker::" . ( C4::Context->preference("LinkerModule") || 'Default' ); +my $linker_module = "C4::Linker::" . ( C4::Context->preference("LinkerModule") || 'Default' ); unless ( can_load( modules => { $linker_module => undef } ) ) { $linker_module = 'C4::Linker::Default'; unless ( can_load( modules => { $linker_module => undef } ) ) { @@ -96,27 +95,26 @@ my $num_bad_bibs = 0; my %unlinked_headings; my %linked_headings; my %fuzzy_headings; -my $dbh = C4::Context->dbh; +my $dbh = C4::Context->dbh; my @updated_biblios = (); -my $indexer = Koha::SearchEngine::Indexer->new({ index => $Koha::SearchEngine::BIBLIOS_INDEX }); +my $indexer = Koha::SearchEngine::Indexer->new( { index => $Koha::SearchEngine::BIBLIOS_INDEX } ); my $schema = Koha::Database->schema; $schema->txn_begin; -process_bibs( $linker, $bib_limit, $auth_limit, $commit, { tagtolink => $tagtolink, allowrelink => $allowrelink }); +process_bibs( $linker, $bib_limit, $auth_limit, $commit, { tagtolink => $tagtolink, allowrelink => $allowrelink } ); exit 0; sub process_bibs { my ( $linker, $bib_limit, $auth_limit, $commit, $args ) = @_; - my $tagtolink = $args->{tagtolink}; + my $tagtolink = $args->{tagtolink}; my $allowrelink = $args->{allowrelink}; - my $bib_where = ''; - my $starttime = time(); + my $bib_where = ''; + my $starttime = time(); if ($bib_limit) { $bib_where = "WHERE $bib_limit"; } - my $sql = - "SELECT biblionumber FROM biblio $bib_where ORDER BY biblionumber ASC"; + my $sql = "SELECT biblionumber FROM biblio $bib_where ORDER BY biblionumber ASC"; my $sth = $dbh->prepare($sql); $sth->execute(); my $linker_args = { tagtolink => $tagtolink, allowrelink => $allowrelink }; @@ -141,10 +139,10 @@ sub process_bibs { for ( values %unlinked_headings ) { $headings_unlinked += $_; } for ( values %fuzzy_headings ) { $headings_fuzzy += $_; } - my $endtime = time(); - my $totaltime = ceil (($endtime - $starttime) * 1000); - $starttime = strftime('%D %T', localtime($starttime)); - $endtime = strftime('%D %T', localtime($endtime)); + my $endtime = time(); + my $totaltime = ceil( ( $endtime - $starttime ) * 1000 ); + $starttime = strftime( '%D %T', localtime($starttime) ); + $endtime = strftime( '%D %T', localtime($endtime) ); my $summary = <<_SUMMARY_; @@ -173,9 +171,7 @@ Linked headings (from most frequent to least): _LINKED_HEADER_ - @keys = sort { - $linked_headings{$b} <=> $linked_headings{$a} or "\L$a" cmp "\L$b" - } keys %linked_headings; + @keys = sort { $linked_headings{$b} <=> $linked_headings{$a} or "\L$a" cmp "\L$b" } keys %linked_headings; foreach my $key (@keys) { print "$key:\t" . $linked_headings{$key} . " occurrences\n"; } @@ -187,10 +183,7 @@ Unlinked headings (from most frequent to least): _UNLINKED_HEADER_ - @keys = sort { - $unlinked_headings{$b} <=> $unlinked_headings{$a} - or "\L$a" cmp "\L$b" - } keys %unlinked_headings; + @keys = sort { $unlinked_headings{$b} <=> $unlinked_headings{$a} or "\L$a" cmp "\L$b" } keys %unlinked_headings; foreach my $key (@keys) { print "$key:\t" . $unlinked_headings{$key} . " occurrences\n"; } @@ -202,9 +195,7 @@ Fuzzily-matched headings (from most frequent to least): _FUZZY_HEADER_ - @keys = sort { - $fuzzy_headings{$b} <=> $fuzzy_headings{$a} or "\L$a" cmp "\L$b" - } keys %fuzzy_headings; + @keys = sort { $fuzzy_headings{$b} <=> $fuzzy_headings{$a} or "\L$a" cmp "\L$b" } keys %fuzzy_headings; foreach my $key (@keys) { print "$key:\t" . $fuzzy_headings{$key} . " occurrences\n"; } @@ -215,12 +206,13 @@ _FUZZY_HEADER_ sub process_bib { my $linker = shift; my $biblionumber = shift; - my $args = shift; + my $args = shift; my $tagtolink = $args->{tagtolink}; - my $allowrelink = $args->{allowrelink}; - my $biblio = Koha::Biblios->find($biblionumber); + my $allowrelink = $args->{allowrelink}; + my $biblio = Koha::Biblios->find($biblionumber); my $record; eval { $record = $biblio->metadata->record; }; + unless ( defined $record ) { warn "Could not retrieve bib $biblionumber from the database - record is corrupt."; $num_bad_bibs++; @@ -262,12 +254,18 @@ sub process_bib { ); } if ( not $test_only ) { - ModBiblio( $record, $biblionumber, $frameworkcode, { - disable_autolink => 1, - skip_holds_queue => 1, - skip_record_index =>1 - }); + ModBiblio( + $record, + $biblionumber, + $frameworkcode, + { + disable_autolink => 1, + skip_holds_queue => 1, + skip_record_index => 1 + } + ); push @updated_biblios, $biblionumber; + #Last param is to note ModBiblio was called from linking script and bib should not be linked again $num_bibs_modified++; } diff --git a/misc/load_yaml.pl b/misc/load_yaml.pl index 6eece29637..db80903249 100755 --- a/misc/load_yaml.pl +++ b/misc/load_yaml.pl @@ -25,8 +25,8 @@ use C4::Context; use C4::Installer; sub print_usage { - ( my $basename = $0 ) =~ s|.*/||; - print < \$help, - 'load' => \$load, - 'file|f=s@' => \@files, + 'help|h' => \$help, + 'load' => \$load, + 'file|f=s@' => \@files, ) or print_usage, exit 1; -if ($help or not @files or not $load) { +if ( $help or not @files or not $load ) { print_usage; exit; } my $installer = C4::Installer->new; -if ( $load ) { - for my $f ( @files ) { +if ($load) { + for my $f (@files) { my $error = $installer->load_sql($f); say $error if $error; } diff --git a/misc/maintenance/UNIMARC_fix_collectiontitle.pl b/misc/maintenance/UNIMARC_fix_collectiontitle.pl index 0577878e91..251378f072 100755 --- a/misc/maintenance/UNIMARC_fix_collectiontitle.pl +++ b/misc/maintenance/UNIMARC_fix_collectiontitle.pl @@ -13,15 +13,17 @@ sub process { my $dbh = C4::Context->dbh; - my $sth = $dbh->prepare(qq{UPDATE marc_subfield_structure SET kohafield='biblioitems.collectiontitle' where kohafield='biblio.seriestitle' and not tagfield like "4__"}); + my $sth = $dbh->prepare( + qq{UPDATE marc_subfield_structure SET kohafield='biblioitems.collectiontitle' where kohafield='biblio.seriestitle' and not tagfield like "4__"} + ); return $sth->execute(); - } -if (lc(C4::Context->preference('marcflavour')) eq "unimarc"){ -print "count subfields changed :".process()." kohafields biblio.seriestitle changed into biblioitems.collectiontitle"; -} -else { - print "this script is UNIMARC only and should be used only on unimarc databases\n"; +if ( lc( C4::Context->preference('marcflavour') ) eq "unimarc" ) { + print "count subfields changed :" + . process() + . " kohafields biblio.seriestitle changed into biblioitems.collectiontitle"; +} else { + print "this script is UNIMARC only and should be used only on unimarc databases\n"; } diff --git a/misc/maintenance/UNIMARC_sync_date_created_with_marc_biblio.pl b/misc/maintenance/UNIMARC_sync_date_created_with_marc_biblio.pl index 5abed38bef..d9700a687c 100755 --- a/misc/maintenance/UNIMARC_sync_date_created_with_marc_biblio.pl +++ b/misc/maintenance/UNIMARC_sync_date_created_with_marc_biblio.pl @@ -17,8 +17,7 @@ sub _read_marc_code { my ( $field, $subfield ); if ( $input =~ /^(\d{3})$/ ) { $field = $1; - } - elsif ( $input =~ /^(\d{3})(\w)$/ ) { + } elsif ( $input =~ /^(\d{3})(\w)$/ ) { $field = $1; $subfield = $2; } @@ -34,7 +33,7 @@ GetOptions( 'date-created-marc|c:s' => \$date_created_marc, 'date-modified-marc|m:s' => \$date_modified_marc, ); -my $debug = 0; # FIXME pass an option for that? +my $debug = 0; # FIXME pass an option for that? $verbose = 1 if $debug; # display help ? @@ -50,9 +49,9 @@ $date_created_marc = '099c' unless $date_created_marc; my ( $c_field, $c_subfield ) = _read_marc_code($date_created_marc); die "date-created-marc '$date_created_marc' is not correct." unless $c_field; die "date-created-marc field is greated that 009, it should have a subfield." - if ( $c_field > 9 && !defined $c_subfield ); + if ( $c_field > 9 && !defined $c_subfield ); die "date-created-marc field is lower that 010, it should not have a subfield." - if ( $c_field < 10 && defined $c_subfield ); + if ( $c_field < 10 && defined $c_subfield ); if ($verbose) { print "Date created on $c_field"; print $c_subfield if defined $c_subfield; # use of defined to allow 0 @@ -64,13 +63,12 @@ $date_modified_marc = '099d' unless $date_modified_marc; my ( $m_field, $m_subfield ) = _read_marc_code($date_modified_marc); die "date-modified-marc '$date_modified_marc' is not correct." unless $m_field; die "date-modified-marc field is greated that 009, it should have a subfield." - if ( $m_field > 9 && !defined $m_subfield ); + if ( $m_field > 9 && !defined $m_subfield ); die "date-modified-marc field is lower that 010, it should not have a subfield." - if ( $m_field < 10 && defined $m_subfield ); -die -"When date-created-marc and date-modified-marc are on same field, they should have distinct subfields" - if ( $c_field eq $m_field ) - && ( !defined $c_subfield + if ( $m_field < 10 && defined $m_subfield ); +die "When date-created-marc and date-modified-marc are on same field, they should have distinct subfields" + if ( $c_field eq $m_field ) + && ( !defined $c_subfield || !defined $m_subfield || $c_subfield eq $m_subfield ); if ($verbose) { @@ -85,7 +83,7 @@ my $sth_prepared; sub updateMarc { my $id = shift; my $biblio = Koha::Biblios->find($id); - $biblio &&= $biblio->metadata->record; + $biblio &&= $biblio->metadata->record; unless ($biblio) { $debug and warn '[ERROR] Bibliographic record not found.'; @@ -98,18 +96,18 @@ sub updateMarc { my $c_marc_value; if ($c_marc_field) { $c_marc_value = - defined $c_subfield - ? $c_marc_field->subfield($c_subfield) - : $c_marc_field->data(); + defined $c_subfield + ? $c_marc_field->subfield($c_subfield) + : $c_marc_field->data(); } $c_marc_value = '' unless defined $c_marc_value; my $m_marc_value; if ($m_marc_field) { $m_marc_value = - defined $m_subfield - ? $m_marc_field->subfield($m_subfield) - : $m_marc_field->data(); + defined $m_subfield + ? $m_marc_field->subfield($m_subfield) + : $m_marc_field->data(); } $m_marc_value ||= ''; @@ -126,7 +124,7 @@ sub updateMarc { $sth_prepared->execute($id); my $bibliorow = $sth_prepared->fetchrow_hashref; my $frameworkcode = $bibliorow->{'frameworkcode'}; - my $c_db_value = $bibliorow->{'datecreatediso'} || ''; + my $c_db_value = $bibliorow->{'datecreatediso'} || ''; my $m_db_value = $bibliorow->{'datemodifiediso'} || ''; # do nothing if already sync @@ -140,13 +138,8 @@ sub updateMarc { # date created field unless ($c_marc_field) { if ( defined $c_subfield ) { - $biblio->add_fields( - MARC::Field->new( - $c_field, ' ', ' ', $c_subfield => $c_db_value - ) - ); - } - else { + $biblio->add_fields( MARC::Field->new( $c_field, ' ', ' ', $c_subfield => $c_db_value ) ); + } else { $biblio->add_fields( MARC::Field->new( $c_field, $c_db_value ) ); } $debug and warn "[WARN] $c_field did not exist."; @@ -156,12 +149,10 @@ sub updateMarc { if ( $m_field eq $c_field ) { $m_marc_field = $c_marc_field; } - } - else { + } else { if ( defined $c_subfield ) { $c_marc_field->update( $c_subfield, $c_db_value ); - } - else { + } else { $c_marc_field->update($c_db_value); } } @@ -169,24 +160,17 @@ sub updateMarc { # date last modified field unless ($m_marc_field) { if ( defined $m_subfield ) { - $biblio->add_fields( - MARC::Field->new( - $m_field, ' ', ' ', $m_subfield => $m_db_value - ) - ); - } - else { + $biblio->add_fields( MARC::Field->new( $m_field, ' ', ' ', $m_subfield => $m_db_value ) ); + } else { $biblio->add_fields( MARC::Field->new( $m_field, $m_db_value ) ); } $debug and warn "[WARN] $m_field did not exist."; $m_marc_field = $biblio->field($m_field); - } - else { + } else { if ( defined $m_subfield ) { $m_marc_field->update( $m_subfield, $m_db_value ); - } - else { + } else { $m_marc_field->update($m_db_value); } } @@ -231,15 +215,13 @@ sub process { if ( lc( C4::Context->preference('marcflavour') ) eq "unimarc" ) { $verbose - and !$run - and print "*** Not in run mode, modifications will not be applyed ***\n"; + and !$run + and print "*** Not in run mode, modifications will not be applyed ***\n"; $verbose and print "================================\n"; process(); -} -else { - print -"This script is UNIMARC only and should be used only on UNIMARC databases\n"; +} else { + print "This script is UNIMARC only and should be used only on UNIMARC databases\n"; } sub print_usage { diff --git a/misc/maintenance/auth_show_hidden_data.pl b/misc/maintenance/auth_show_hidden_data.pl index fdab635768..12d3f633f0 100755 --- a/misc/maintenance/auth_show_hidden_data.pl +++ b/misc/maintenance/auth_show_hidden_data.pl @@ -17,13 +17,12 @@ # You should have received a copy of the GNU General Public License # along with Koha; if not, see . - # This script walks through your authority marc records and tells you # which hidden fields in the framework still contain data. use Modern::Perl; use Getopt::Long qw( GetOptions ); -use Pod::Usage qw( pod2usage ); +use Pod::Usage qw( pod2usage ); use Koha::Script; use Koha::Authorities; @@ -38,39 +37,41 @@ if ( !$confirm || $help ) { } our $hidden_fields = Koha::Authority::Subfields->search( - { hidden => { '!=' => 0 }}, + { hidden => { '!=' => 0 } }, ); our $results = {}; my $auths = Koha::Authorities->search( {}, { order_by => 'authid' } ); my $count = 0; -while( my $record = $auths->next ) { +while ( my $record = $auths->next ) { last if $max && $count >= $max; - scan_record( $record ); + scan_record($record); $count++; } report_results(); sub scan_record { - my ( $record ) = @_; - my $id = $record->authid; - my $type = $record->authtypecode; - my $marc = Koha::MetadataRecord::Authority->get_from_authid($id)->record; - foreach my $fld ( $marc->fields ) { # does not include leader - my @subfields = $fld->is_control_field + my ($record) = @_; + my $id = $record->authid; + my $type = $record->authtypecode; + my $marc = Koha::MetadataRecord::Authority->get_from_authid($id)->record; + foreach my $fld ( $marc->fields ) { # does not include leader + my @subfields = + $fld->is_control_field ? '@' : map { $_->[0] } $fld->subfields; - foreach my $sub ( @subfields ) { - next if $results->{ $type } && $results->{ $type }->{ $fld->tag } && $results->{ $type }->{ $fld->tag }->{ $sub }; - if( $hidden_fields->find($type, $fld->tag, $sub) ) { - $results->{ $type }->{ $fld->tag }->{ $sub } = 1; + foreach my $sub (@subfields) { + next if $results->{$type} && $results->{$type}->{ $fld->tag } && $results->{$type}->{ $fld->tag }->{$sub}; + if ( $hidden_fields->find( $type, $fld->tag, $sub ) ) { + $results->{$type}->{ $fld->tag }->{$sub} = 1; } } } + # To be overcomplete, check the leader too :) - if( $marc->leader ) { - if( $hidden_fields->find($type, '000', '@') ) { - $results->{ $type }->{ '000' }->{ '@' } = 1; + if ( $marc->leader ) { + if ( $hidden_fields->find( $type, '000', '@' ) ) { + $results->{$type}->{'000'}->{'@'} = 1; } } } @@ -78,15 +79,16 @@ sub scan_record { sub report_results { my $cnt = 0; foreach my $fw ( sort keys %$results ) { - foreach my $tag ( sort keys %{$results->{$fw}} ) { - foreach my $sub ( sort keys %{$results->{$fw}->{$tag}} ) { - print "\nFramework ".($fw||'Default').", $tag, $sub contains data but is hidden"; + foreach my $tag ( sort keys %{ $results->{$fw} } ) { + foreach my $sub ( sort keys %{ $results->{$fw}->{$tag} } ) { + print "\nFramework " . ( $fw || 'Default' ) . ", $tag, $sub contains data but is hidden"; $cnt++; } } } - if( $cnt ) { - print "\n\nNOTE: You should consider removing the hidden attribute of these framework fields in order to not lose data in those fields when editing authority records.\n"; + if ($cnt) { + print + "\n\nNOTE: You should consider removing the hidden attribute of these framework fields in order to not lose data in those fields when editing authority records.\n"; } else { print "\nNo hidden (sub)fields containing data were found!\n"; } diff --git a/misc/maintenance/borrowers-force-messaging-defaults.pl b/misc/maintenance/borrowers-force-messaging-defaults.pl index be5bbb029d..6e27a7c3ba 100755 --- a/misc/maintenance/borrowers-force-messaging-defaults.pl +++ b/misc/maintenance/borrowers-force-messaging-defaults.pl @@ -24,43 +24,40 @@ use Koha::Script; use C4::Context; use C4::Members::Messaging; use Getopt::Long qw( GetOptions ); -use Pod::Usage qw( pod2usage ); - +use Pod::Usage qw( pod2usage ); sub usage { pod2usage( -verbose => 2 ); exit; } - sub force_borrower_messaging_defaults { - my ($doit, $since, $not_expired, $no_overwrite, $category, $branchcode, $message_name ) = @_; + my ( $doit, $since, $not_expired, $no_overwrite, $category, $branchcode, $message_name ) = @_; print "Since: $since\n" if $since; my $dbh = C4::Context->dbh; $dbh->{AutoCommit} = 0; - my $sql = -q|SELECT DISTINCT bo.borrowernumber, bo.categorycode FROM borrowers bo + my $sql = q|SELECT DISTINCT bo.borrowernumber, bo.categorycode FROM borrowers bo LEFT JOIN borrower_message_preferences mp USING (borrowernumber) WHERE 1|; - if ( $since ) { + if ($since) { $sql .= " AND bo.dateenrolled >= ?"; } if ($not_expired) { - $sql .= " AND bo.dateexpiry >= NOW()" + $sql .= " AND bo.dateexpiry >= NOW()"; } - if( $no_overwrite ) { + if ($no_overwrite) { $sql .= " AND mp.borrowernumber IS NULL"; } $sql .= " AND bo.categorycode = ?" if $category; - $sql .= " AND bo.branchcode = ?" if $branchcode; + $sql .= " AND bo.branchcode = ?" if $branchcode; my $sth = $dbh->prepare($sql); - $sth->execute($since || (), $category || (), $branchcode || () ); + $sth->execute( $since || (), $category || (), $branchcode || () ); my $cnt = 0; - while ( my ($borrowernumber, $categorycode) = $sth->fetchrow ) { + while ( my ( $borrowernumber, $categorycode ) = $sth->fetchrow ) { print "$borrowernumber: $categorycode\n"; next unless $doit; my $options = { @@ -75,7 +72,6 @@ WHERE 1|; print "Total borrowers updated: $cnt\n" if $doit; } - my ( $doit, $since, $help, $not_expired, $no_overwrite, $category, $branchcode, $message_name ); my $result = GetOptions( 'doit' => \$doit, diff --git a/misc/maintenance/check_syspref_cache.pl b/misc/maintenance/check_syspref_cache.pl index 18be7926e6..3e5d3b6acd 100755 --- a/misc/maintenance/check_syspref_cache.pl +++ b/misc/maintenance/check_syspref_cache.pl @@ -17,8 +17,8 @@ use Modern::Perl; use Getopt::Long qw( GetOptions ); -use Pod::Usage qw( pod2usage ); -use Encode qw( encode_utf8 ); +use Pod::Usage qw( pod2usage ); +use Encode qw( encode_utf8 ); use Koha::Script; use Koha::Caches; @@ -45,16 +45,16 @@ GetOptions( 'man' => \$man, ); -pod2usage(1) if $help; +pod2usage(1) if $help; pod2usage( -verbose => 2 ) if $man; my $syspref_cache = Koha::Caches->get_instance('syspref'); -my $prefs = Koha::Config::SysPrefs->search(); +my $prefs = Koha::Config::SysPrefs->search(); -while (my $pref = $prefs->next) { - my $var = lc $pref->variable; +while ( my $pref = $prefs->next ) { + my $var = lc $pref->variable; my $cached_var = $syspref_cache->get_from_cache("syspref_$var"); - next unless defined $cached_var; #If not defined in cache we will fetch from DB so this case is OK + next unless defined $cached_var; #If not defined in cache we will fetch from DB so this case is OK say encode_utf8( sprintf( "%s: value in cache is '%s' and value in db is '%s'", $var, $cached_var, $pref->value ) ) - unless $cached_var eq $pref->value; + unless $cached_var eq $pref->value; } diff --git a/misc/maintenance/cmp_sysprefs.pl b/misc/maintenance/cmp_sysprefs.pl index 1a7afdf63a..3e16a2c850 100755 --- a/misc/maintenance/cmp_sysprefs.pl +++ b/misc/maintenance/cmp_sysprefs.pl @@ -28,7 +28,7 @@ use Modern::Perl; use open OUT => ':encoding(UTF-8)', ':std'; use Getopt::Long qw( GetOptions ); -use Pod::Usage qw( pod2usage ); +use Pod::Usage qw( pod2usage ); use Koha::Script; use C4::Context; @@ -81,7 +81,7 @@ if ( $cmd =~ /^c/i && $filename ) { my $cmp = ComparePrefs( $dbprefs, $fileprefs ); PrintCompare( $cmp, "database", "file $filename" ); HandleCompareChanges( $cmp, $dbprefs, $fileprefs ) - if $compare_add || $compare_del || $compare_upd; + if $compare_add || $compare_del || $compare_upd; } #restore prefs @@ -152,7 +152,8 @@ sub ComparePrefs { } sub ReadPrefsFromDb { - my $sql = 'SELECT variable AS orgkey, LOWER(variable) AS variable, value, type FROM systempreferences ORDER BY variable'; + my $sql = + 'SELECT variable AS orgkey, LOWER(variable) AS variable, value, type FROM systempreferences ORDER BY variable'; my $hash = $dbh->selectall_hashref( $sql, 'variable' ); return $hash; } @@ -194,7 +195,7 @@ sub SavePrefsToDb { #will not erase everything! you can do that in mysql :) foreach my $k ( keys %$hash ) { - my $v = $hash->{$k}->{value} eq 'NULL' ? undef : $hash->{$k}->{value}; + my $v = $hash->{$k}->{value} eq 'NULL' ? undef : $hash->{$k}->{value}; my $kwc = $hash->{$k}->{orgkey} // $k; my $type = $hash->{$k}->{type} // 'Free'; @@ -213,14 +214,14 @@ sub InsertIgnoreOnePref { 'INSERT IGNORE INTO systempreferences (variable, value, type) VALUES (?,?,?)', undef, ( $kwc, $v, $t ) ); - return !defined($i) || $i eq '0E0'? 0: $i; + return !defined($i) || $i eq '0E0' ? 0 : $i; } sub UpdateOnePref { my ( $k, $v ) = @_; return 0 if lc $k eq 'version'; my $i = $dbh->do( 'UPDATE systempreferences SET value=? WHERE variable=?', undef, ( $v, $k ) ); - return !defined($i) || $i eq '0E0'? 0: $i; + return !defined($i) || $i eq '0E0' ? 0 : $i; } sub DeleteOnePref { @@ -231,19 +232,19 @@ sub DeleteOnePref { $sql .= " AND COALESCE(explanation,'')='' AND COALESCE(options,'')=''"; } my $i = $dbh->do( $sql, undef, ($k) ); - return !defined($i) || $i eq '0E0'? 0: $i; + return !defined($i) || $i eq '0E0' ? 0 : $i; } sub CheckVersionPref { #additional precaution #if there are versions, compare them my ($hash) = @_; - my $hv = exists $hash->{version}? $hash->{version}->{value}: undef; + my $hv = exists $hash->{version} ? $hash->{version}->{value} : undef; return if !defined $hv; my ($dv) = $dbh->selectrow_array( 'SELECT value FROM systempreferences WHERE variable LIKE ?', undef, ('version') ); - return if !defined $dv; + return if !defined $dv; die "Versions do not match ($dv, $hv)" if $dv ne $hv; } diff --git a/misc/maintenance/compare_es_to_db.pl b/misc/maintenance/compare_es_to_db.pl index b79f739789..394449b743 100755 --- a/misc/maintenance/compare_es_to_db.pl +++ b/misc/maintenance/compare_es_to_db.pl @@ -39,15 +39,17 @@ use Koha::Biblios; use Koha::Items; use Koha::SearchEngine::Elasticsearch; -foreach my $index ( ('biblios','authorities') ){ +foreach my $index ( ( 'biblios', 'authorities' ) ) { print "=================\n"; print "Checking $index\n"; - my @db_records = $index eq 'biblios' ? Koha::Biblios->search()->get_column('biblionumber') : Koha::Authorities->search()->get_column('authid'); + my @db_records = + $index eq 'biblios' + ? Koha::Biblios->search()->get_column('biblionumber') + : Koha::Authorities->search()->get_column('authid'); - my $searcher = Koha::SearchEngine::Elasticsearch->new({ index => $index }); - my $es = $searcher->get_elasticsearch(); - my $count = $es->indices->stats( index => $searcher->index_name ) - ->{_all}{primaries}{docs}{count}; + my $searcher = Koha::SearchEngine::Elasticsearch->new( { index => $index } ); + my $es = $searcher->get_elasticsearch(); + my $count = $es->indices->stats( index => $searcher->index_name )->{_all}{primaries}{docs}{count}; print "Count in db for $index is " . scalar @db_records . ", count in Elasticsearch is $count\n"; # Now we get all the ids from Elasticsearch @@ -67,29 +69,29 @@ foreach my $index ( ('biblios','authorities') ){ # Fetching each record, pushing the id into the array my $i = 1; print "Fetching Elasticsearch records ids"; - while (my $doc = $scroll->next ){ - print "." if !($i % 500); - print "\n$i records retrieved" if !($i % 5000); + while ( my $doc = $scroll->next ) { + print "." if !( $i % 500 ); + print "\n$i records retrieved" if !( $i % 5000 ); push @es_ids, $doc->{_id}; $i++; } # Fetch values for providing record links my $es_params = $searcher->get_elasticsearch_params; - my $es_base = "$es_params->{nodes}[0]/".$searcher->index_name; + my $es_base = "$es_params->{nodes}[0]/" . $searcher->index_name; my $opac_base = C4::Context->preference('OPACBaseURL'); print "\nComparing arrays, this may take a while\n"; - my @koha_problems = sort { $a <=> $b } array_minus(@db_records, @es_ids); - my @es_problems = sort { $a <=> $b } array_minus(@es_ids, @db_records); + my @koha_problems = sort { $a <=> $b } array_minus( @db_records, @es_ids ); + my @es_problems = sort { $a <=> $b } array_minus( @es_ids, @db_records ); print "All records match\n" unless ( @koha_problems || @es_problems ); - if ( @koha_problems ){ + if (@koha_problems) { print "=================\n"; print "Records that exist in Koha but not in ES\n"; - for my $problem ( @koha_problems ){ + for my $problem (@koha_problems) { if ( $index eq 'biblios' ) { print " #$problem"; print " Visit here to see record: $opac_base/cgi-bin/koha/opac-detail.pl?biblionumber=$problem\n"; @@ -100,10 +102,10 @@ foreach my $index ( ('biblios','authorities') ){ } } - if ( @es_problems ){ + if (@es_problems) { print "=================\n"; print "Records that exist in ES but not in Koha\n"; - for my $problem ( @es_problems ){ + for my $problem (@es_problems) { print " #$problem"; print " Enter this command to view record: curl $es_base/data/$problem?pretty=true\n"; } diff --git a/misc/maintenance/fix_accountlines_date.pl b/misc/maintenance/fix_accountlines_date.pl index 670b35dc01..738e04822a 100755 --- a/misc/maintenance/fix_accountlines_date.pl +++ b/misc/maintenance/fix_accountlines_date.pl @@ -22,7 +22,7 @@ use warnings; use Koha::Script; use C4::Context; -use Getopt::Long qw( GetOptions ); +use Getopt::Long qw( GetOptions ); use Koha::DateUtils qw( dt_from_string output_pref ); =head1 NAME @@ -79,18 +79,18 @@ only if there is a problem and with the '-n' option. =cut -my $mode = ''; +my $mode = ''; my $want_help = 0; -my $limit = -1; -my $done = 0; -my $DEBUG = 0; +my $limit = -1; +my $done = 0; +my $DEBUG = 0; # Regexes for the two date formats -our $US_DATE = '((0\d|1[0-2])\/([0-2]\d|3[01])\/(\d{4}))'; +our $US_DATE = '((0\d|1[0-2])\/([0-2]\d|3[01])\/(\d{4}))'; our $METRIC_DATE = '(([0-2]\d|3[01])\/(0\d|1[0-2])\/(\d{4}))'; sub print_usage { - print <<_USAGE_ + print <<_USAGE_; $0: Fix the date code in the description of fines Due to the multiple scripts used to update fines in earlier versions of Koha, @@ -107,47 +107,46 @@ _USAGE_ } my $result = GetOptions( - 'm=s' => \$mode, - 'd' => \$DEBUG, - 'n=i' => \$limit, - 'help|h' => \$want_help, + 'm=s' => \$mode, + 'd' => \$DEBUG, + 'n=i' => \$limit, + 'help|h' => \$want_help, ); -if (not $result or $want_help or ($mode ne 'us' and $mode ne 'metric')) { +if ( not $result or $want_help or ( $mode ne 'us' and $mode ne 'metric' ) ) { print_usage(); exit 0; } our $dbh = C4::Context->dbh; $dbh->{AutoCommit} = 0; -my $sth = $dbh->prepare(" +my $sth = $dbh->prepare( " SELECT accountlines_id, description FROM accountlines WHERE accounttype in ('FU', 'F', 'M') -;"); +;" ); $sth->execute(); -my $update_sth = $dbh->prepare(' +my $update_sth = $dbh->prepare( ' UPDATE accountlines SET description = ? WHERE accountlines_id = ? -;'); +;' ); - -while (my $accountline = $sth->fetchrow_hashref) { +while ( my $accountline = $sth->fetchrow_hashref ) { my $description = $accountline->{'description'}; - my $updated = 0; + my $updated = 0; - if ($mode eq 'us') { - if ($description =~ /$US_DATE/) { # mm/dd/yyyy - my $date = output_pref( { dt => dt_from_string( $1, 'us' ), dateonly => 1} ); - print "Converting $1 (us) to " . $date . "\n" if $DEBUG;i - $description =~ s/$US_DATE/$date/; + if ( $mode eq 'us' ) { + if ( $description =~ /$US_DATE/ ) { # mm/dd/yyyy + my $date = output_pref( { dt => dt_from_string( $1, 'us' ), dateonly => 1 } ); + print "Converting $1 (us) to " . $date . "\n" if $DEBUG; + i $description =~ s/$US_DATE/$date/; $updated = 1; } - } elsif ($mode eq 'metric') { - if ($description =~ /$METRIC_DATE/) { # dd/mm/yyyy - my $date = output_pref( { dt => dt_from_string( $1, 'metric' ), dateonly => 1} ); + } elsif ( $mode eq 'metric' ) { + if ( $description =~ /$METRIC_DATE/ ) { # dd/mm/yyyy + my $date = output_pref( { dt => dt_from_string( $1, 'metric' ), dateonly => 1 } ); print "Converting $1 (metric) to " . $date . "\n" if $DEBUG; $description =~ s/$METRIC_DATE/$date/; $updated = 2; @@ -155,11 +154,11 @@ while (my $accountline = $sth->fetchrow_hashref) { } print "Changing description from '" . $accountline->{'description'} . "' to '" . $description . "'\n" if $DEBUG; - $update_sth->execute($description, $accountline->{'accountlines_id'}); + $update_sth->execute( $description, $accountline->{'accountlines_id'} ); $done++; - last if ($done == $limit); # $done can't be -1, so this works + last if ( $done == $limit ); # $done can't be -1, so this works } $dbh->commit(); diff --git a/misc/maintenance/fix_accountlines_rmdupfines_bug8253.pl b/misc/maintenance/fix_accountlines_rmdupfines_bug8253.pl index 608c6aaa7b..7d15206a71 100755 --- a/misc/maintenance/fix_accountlines_rmdupfines_bug8253.pl +++ b/misc/maintenance/fix_accountlines_rmdupfines_bug8253.pl @@ -27,7 +27,7 @@ use Getopt::Long qw( GetOptions ); use Data::Dumper; sub print_usage { - print <<_USAGE_ + print <<_USAGE_; $0: Remove duplicate fines Due to bug 8253, upgrading from Koha 3.6 to 3.8 may introduce duplicate fines. @@ -44,14 +44,13 @@ my $help; my $confirm; my $result = GetOptions( 'confirm|c' => \$confirm, - 'help|h' => \$help, + 'help|h' => \$help, ); if ( $help || !$confirm ) { print_usage(); exit 0; } - my $dbh = C4::Context->dbh; my $query = " @@ -64,13 +63,12 @@ my $sth = $dbh->prepare($query); $sth->execute(); my $results = $sth->fetchall_arrayref( {} ); -$query = -"SELECT * FROM accountlines WHERE description LIKE ? AND description NOT LIKE ?"; -$sth = $dbh->prepare($query); +$query = "SELECT * FROM accountlines WHERE description LIKE ? AND description NOT LIKE ?"; +$sth = $dbh->prepare($query); foreach my $keeper (@$results) { - warn "WORKING ON KEEPER: " . Data::Dumper::Dumper( $keeper ); + warn "WORKING ON KEEPER: " . Data::Dumper::Dumper($keeper); my ($description_to_match) = split( / 23:59/, $keeper->{'description'} ); $description_to_match .= '%'; @@ -82,21 +80,19 @@ foreach my $keeper (@$results) { while ( my $f = $sth->fetchrow_hashref() ) { - warn "DELETING: " . Data::Dumper::Dumper( $f ); + warn "DELETING: " . Data::Dumper::Dumper($f); if ( $f->{'amountoutstanding'} < $keeper->{'amountoutstanding'} ) { $keeper->{'amountoutstanding'} = $f->{'amountoutstanding'}; $has_changed = 1; } - my $sql = - "DELETE FROM accountlines WHERE accountlines_id = ?"; + my $sql = "DELETE FROM accountlines WHERE accountlines_id = ?"; $dbh->do( $sql, undef, $f->{'accountlines_id'} ); } if ($has_changed) { - my $sql = - "UPDATE accountlines SET amountoutstanding = ? WHERE accountlines_id = ?"; + my $sql = "UPDATE accountlines SET amountoutstanding = ? WHERE accountlines_id = ?"; $dbh->do( $sql, undef, $keeper->{'amountoutstanding'}, $keeper->{'accountlines_id'} diff --git a/misc/maintenance/fix_mysql_constraints.pl b/misc/maintenance/fix_mysql_constraints.pl index 79599cdac4..c0afd3e5ef 100755 --- a/misc/maintenance/fix_mysql_constraints.pl +++ b/misc/maintenance/fix_mysql_constraints.pl @@ -20,39 +20,39 @@ use Modern::Perl; use Getopt::Long qw( GetOptions ); -use Pod::Usage qw( pod2usage ); -use Try::Tiny qw( catch try ); +use Pod::Usage qw( pod2usage ); +use Try::Tiny qw( catch try ); use Koha::Script; use C4::Context; - -my ($doit, $alterengine, $help); +my ( $doit, $alterengine, $help ); my $result = GetOptions( 'doit' => \$doit, 'alterengine' => \$alterengine, 'help|h' => \$help, ); - sub usage { pod2usage( -verbose => 2 ); exit; } - sub fix_mysql_constraints { my ($doit) = @_; # Get all current DB constraints my $dbh = C4::Context->dbh; - $dbh->{RaiseError} = 1; + $dbh->{RaiseError} = 1; $dbh->{ShowErrorStatement} = 1; - my $database = C4::Context->config('database'); - my %db_constraint = map { $_->[0] => undef } @{$dbh->selectall_arrayref( - "SELECT CONSTRAINT_NAME + my $database = C4::Context->config('database'); + my %db_constraint = map { $_->[0] => undef } @{ + $dbh->selectall_arrayref( + "SELECT CONSTRAINT_NAME FROM information_schema.table_constraints WHERE constraint_schema = '$database' - AND CONSTRAINT_TYPE != 'PRIMARY KEY' ")}; + AND CONSTRAINT_TYPE != 'PRIMARY KEY' " + ) + }; my $base_dir = C4::Context->config('intranetdir'); open my $fh, "<", "$base_dir/installer/data/mysql/kohastructure.sql" @@ -60,17 +60,18 @@ sub fix_mysql_constraints { my $table_name; my $engine_altered; + # FIXME: This hide problem. But if you run this script, it means that you # have already identified issues with your Koha DB integrity, and will fix # any necessary tables requiring records deleting. $dbh->do("SET FOREIGN_KEY_CHECKS=0"); my $line = <$fh>; - while ( $line ) { + while ($line) { if ( $line =~ /CREATE TABLE (.*?) / ) { $table_name = $1; $table_name =~ s/\`//g; $engine_altered = 0; - $line = <$fh>; + $line = <$fh>; next; } unless ( $line =~ /CONSTRAINT /i ) { @@ -78,7 +79,7 @@ sub fix_mysql_constraints { next; } my $constraint = $line; - CONTRAINT_LOOP: + CONTRAINT_LOOP: while ( $constraint !~ /,/ ) { $line = <$fh>; last CONTRAINT_LOOP if $line =~ /ENGINE/i; @@ -91,11 +92,11 @@ sub fix_mysql_constraints { $constraint =~ s/,$//; my ($name) = $constraint =~ /CONSTRAINT (.*?) /; $name =~ s/\`//g; - unless ( exists($db_constraint{$name}) ) { + unless ( exists( $db_constraint{$name} ) ) { if ( $alterengine && !$engine_altered ) { my $sql = "ALTER TABLE $table_name ENGINE = 'InnoDB'"; say $sql; - if ( $doit ) { + if ($doit) { try { $dbh->do($sql) if $doit; $engine_altered = 1; @@ -106,7 +107,7 @@ sub fix_mysql_constraints { } my $sql = "ALTER TABLE $table_name ADD $constraint"; say $sql; - if ( $doit ) { + if ($doit) { try { $dbh->do($sql) if $doit; } catch { @@ -118,7 +119,6 @@ sub fix_mysql_constraints { } } - usage() if $help; fix_mysql_constraints($doit); diff --git a/misc/maintenance/fix_tags_weight.pl b/misc/maintenance/fix_tags_weight.pl index ff7e3d7835..4ed53333c0 100755 --- a/misc/maintenance/fix_tags_weight.pl +++ b/misc/maintenance/fix_tags_weight.pl @@ -29,7 +29,7 @@ use Koha::Tags::Approvals; use Koha::Tags::Indexes; use Getopt::Long qw( GetOptions ); -use Pod::Usage qw( pod2usage ); +use Pod::Usage qw( pod2usage ); =head1 NAME @@ -74,7 +74,7 @@ GetOptions( pod2usage(1) if $help; fix_tags_approval($verbose); -fix_tags_index( $verbose ); +fix_tags_index($verbose); sub fix_tags_approval { @@ -83,6 +83,7 @@ sub fix_tags_approval { print "Fix tags_approval\n=================\n" if $verbose; my $dbh = C4::Context->dbh; + # Search the terms in tags_all that don't exist in tags_approval my $sth = $dbh->prepare( q{ @@ -105,6 +106,7 @@ sub fix_tags_approval { } my $approvals = Koha::Tags::Approvals->search; + # Recalculate weight_total for all tags_approval rows while ( my $approval = $approvals->next ) { my $count = Koha::Tags->search( { term => $approval->term } )->count; @@ -122,14 +124,8 @@ sub fix_tags_index { print "Fix tags_index\n==============\n" if $verbose; while ( my $index = $indexes->next ) { - my $count - = Koha::Tags->search( { term => $index->term, biblionumber => $index->biblionumber } ) - ->count; - print $index->term . "/" - . $index->biblionumber . "\t|\t" - . $index->weight - . "\t=>\t" - . $count . "\n" + my $count = Koha::Tags->search( { term => $index->term, biblionumber => $index->biblionumber } )->count; + print $index->term . "/" . $index->biblionumber . "\t|\t" . $index->weight . "\t=>\t" . $count . "\n" if $verbose; $index->weight($count)->store; } diff --git a/misc/maintenance/generate_MARC21Languages.pl b/misc/maintenance/generate_MARC21Languages.pl index 37888a66eb..eb23a21495 100755 --- a/misc/maintenance/generate_MARC21Languages.pl +++ b/misc/maintenance/generate_MARC21Languages.pl @@ -19,10 +19,10 @@ # use Modern::Perl; -use XML::Simple qw( XMLin ); -use Pod::Usage qw( pod2usage ); +use XML::Simple qw( XMLin ); +use Pod::Usage qw( pod2usage ); use Getopt::Long qw( GetOptions ); -use Carp qw( croak ); +use Carp qw( croak ); use open ':std', ':encoding(UTF-8)'; @@ -39,13 +39,13 @@ my $tempfile = '/tmp/languages.xml'; GetOptions( 'o|output:s' => \$outfile, - 'url:s' => \$sourceurl, - 'help|h' => \$help, + 'url:s' => \$sourceurl, + 'help|h' => \$help, ); usage() if $help; -system( qq{/usr/bin/wget $sourceurl -O $tempfile } ) == 0 +system(qq{/usr/bin/wget $sourceurl -O $tempfile }) == 0 or croak "Can't wget $sourceurl ($?)"; my $ref = XMLin($tempfile); @@ -53,17 +53,16 @@ my $languages = $ref->{'languages'}->{'language'}; # output log or STDOUT my $out_handle; -if (defined $outfile) { +if ( defined $outfile ) { open( $out_handle, ">", $outfile ) || croak("Cannot open output file"); } else { open( $out_handle, q{>}, "&STDOUT" ) || croak("Couldn't duplicate STDOUT: $!"); } generate_header($out_handle); -generate_body($out_handle, $languages); +generate_body( $out_handle, $languages ); generate_footer($out_handle); close $out_handle; - sub generate_body { my ( $file_handle, $language_list ) = @_; diff --git a/misc/maintenance/process_record_through_filter.pl b/misc/maintenance/process_record_through_filter.pl index 9582867604..4b2d14cb77 100755 --- a/misc/maintenance/process_record_through_filter.pl +++ b/misc/maintenance/process_record_through_filter.pl @@ -11,14 +11,14 @@ use Koha::Script; use Koha::Biblios; use Koha::RecordProcessor; -my $biblio = Koha::Biblios->find($ARGV[0]); -unless ( $biblio ) { +my $biblio = Koha::Biblios->find( $ARGV[0] ); +unless ($biblio) { print "Bibliographic record not found\n"; exit; } my $record = $biblio->metadata->record; print "Before: " . $record->as_formatted() . "\n"; -my $processor = Koha::RecordProcessor->new( { filters => ( $ARGV[1] ) }); +my $processor = Koha::RecordProcessor->new( { filters => ( $ARGV[1] ) } ); $record = $processor->process($record); print "After : " . $record->as_formatted() . "\n"; diff --git a/misc/maintenance/pseudonymize_statistics.pl b/misc/maintenance/pseudonymize_statistics.pl index 1e51a1b498..51930b422b 100755 --- a/misc/maintenance/pseudonymize_statistics.pl +++ b/misc/maintenance/pseudonymize_statistics.pl @@ -48,7 +48,6 @@ print "Searching for statistics before $before\n" if $verbose; my $statistics = Koha::Statistics->search( { datetime => { '<=' => $before } } ); print $statistics->count() . " statistics found\n" if $verbose; - my $existing_pseudo_stats = Koha::PseudonymizedTransactions->search( { datetime => { '<=' => $before } } )->count; if ( $statistics->count && $existing_pseudo_stats ) { diff --git a/misc/maintenance/remove_items_from_biblioitems.pl b/misc/maintenance/remove_items_from_biblioitems.pl index 82d729481b..8f38880a67 100755 --- a/misc/maintenance/remove_items_from_biblioitems.pl +++ b/misc/maintenance/remove_items_from_biblioitems.pl @@ -20,7 +20,7 @@ use strict; use warnings; -$|=1; +$| = 1; use Koha::Script; use C4::Context; @@ -28,12 +28,12 @@ use C4::Biblio qw( GetFrameworkCode ModBiblio ); use Koha::Biblios; use Getopt::Long qw( GetOptions ); -my ($wherestring, $run, $silent, $want_help); +my ( $wherestring, $run, $silent, $want_help ); my $result = GetOptions( - 'where:s' => \$wherestring, - '--run' => \$run, - '--silent' => \$silent, - 'help|h' => \$want_help, + 'where:s' => \$wherestring, + '--run' => \$run, + '--silent' => \$silent, + 'help|h' => \$want_help, ); if ( not $result or not $run or $want_help ) { @@ -41,23 +41,22 @@ if ( not $result or not $run or $want_help ) { exit 0; } -my $dbh = C4::Context->dbh; -my $count = 0; -my $querysth = qq{SELECT biblionumber from biblioitems }; -$querysth .= " WHERE $wherestring " if ($wherestring); +my $dbh = C4::Context->dbh; +my $count = 0; +my $querysth = qq{SELECT biblionumber from biblioitems }; +$querysth .= " WHERE $wherestring " if ($wherestring); my $query = $dbh->prepare($querysth); $query->execute; -while (my $biblionumber = $query->fetchrow){ +while ( my $biblionumber = $query->fetchrow ) { $count++; - print "." unless $silent; - print "\r$count" unless ($silent or ($count % 100)); + print "." unless $silent; + print "\r$count" unless ( $silent or ( $count % 100 ) ); my $biblio = Koha::Biblios->find($biblionumber); my $record = $biblio->metadata->record; if ($record) { - ModBiblio($record, $biblionumber, GetFrameworkCode($biblionumber)) ; - } - else { + ModBiblio( $record, $biblionumber, GetFrameworkCode($biblionumber) ); + } else { print "error in $biblionumber : can't parse biblio"; } } diff --git a/misc/maintenance/sanitize_records.pl b/misc/maintenance/sanitize_records.pl index 430d89d6a7..541d9110f5 100755 --- a/misc/maintenance/sanitize_records.pl +++ b/misc/maintenance/sanitize_records.pl @@ -25,10 +25,12 @@ use C4::Context; use C4::Biblio; use Koha::Biblios; use Getopt::Long qw( GetOptions ); -use Pod::Usage qw( pod2usage ); +use Pod::Usage qw( pod2usage ); -my ( $help, $verbose, $confirm, $biblionumbers, $reindex, $filename, - $auto_search, $fix_ampersand ); +my ( + $help, $verbose, $confirm, $biblionumbers, $reindex, $filename, + $auto_search, $fix_ampersand +); my $result = GetOptions( 'h|help' => \$help, 'v|verbose' => \$verbose, @@ -51,13 +53,12 @@ if ($help) { unless ( $filename or $biblionumbers or $auto_search ) { pod2usage( -exitval => 1, - -message => - qq{\n\tAt least one record number source should be provided.\n} + -message => qq{\n\tAt least one record number source should be provided.\n} ); } if ( $filename and $biblionumbers - or $filename and $auto_search + or $filename and $auto_search or $biblionumbers and $auto_search ) { pod2usage( @@ -72,8 +73,7 @@ my @biblionumbers; #or if we want to use findAmp() sub if ($auto_search) { @biblionumbers = biblios_to_sanitize(); -} -elsif ($filename) { +} elsif ($filename) { if ( -e $filename ) { open( my $fh, '<', $filename ) || die("Can't open $filename ($!)"); while (<$fh>) { @@ -82,16 +82,13 @@ elsif ($filename) { push @biblionumbers, split( " |,", $line ); } close $fh; - } - else { + } else { pod2usage( -exitval => 1, - -message => -qq{\n\tThis filename does not exist. Please verify the path is correct.\n} + -message => qq{\n\tThis filename does not exist. Please verify the path is correct.\n} ); } -} -else { +} else { @biblionumbers = split m|,|, $biblionumbers if $biblionumbers; } @@ -111,7 +108,7 @@ for my $biblionumber (@biblionumbers) { next; } my $biblio = Koha::Biblios->find($biblionumber); - unless ( $biblio ) { + unless ($biblio) { say " skipping. ERROR: biblionumber not found." if $verbose; next; } @@ -121,8 +118,7 @@ for my $biblionumber (@biblionumbers) { next; } - my ( $cleaned_record, $has_been_modified ) = - C4::Charset::SanitizeRecord( $record, $biblionumber ); + my ( $cleaned_record, $has_been_modified ) = C4::Charset::SanitizeRecord( $record, $biblionumber ); if ($has_been_modified) { my $frameworkcode = C4::Biblio::GetFrameworkCode($record); @@ -130,17 +126,13 @@ for my $biblionumber (@biblionumbers) { if $confirm; push @changes, $biblionumber; say " Done!" if $verbose; - } - else { + } else { say " Nothing to do." if $verbose; } } if ($verbose) { - say "Total: " - . @changes - . " records " - . ( $confirm ? "cleaned!" : "to clean." ); + say "Total: " . @changes . " records " . ( $confirm ? "cleaned!" : "to clean." ); } if ( $reindex and $confirm and @changes ) { @@ -148,7 +140,7 @@ if ( $reindex and $confirm and @changes ) { my $kohapath = C4::Context->config('intranetdir'); my $cmd = qq| $kohapath/misc/migration_tools/rebuild_zebra.pl -b -v -where "biblionumber IN ( | - . join( ',', @changes ) . q| )" + . join( ',', @changes ) . q| )" |; system($cmd); } diff --git a/misc/maintenance/search_for_data_inconsistencies.pl b/misc/maintenance/search_for_data_inconsistencies.pl index 4c0eddf792..ebe3204ed3 100755 --- a/misc/maintenance/search_for_data_inconsistencies.pl +++ b/misc/maintenance/search_for_data_inconsistencies.pl @@ -29,53 +29,60 @@ use Koha::Patrons; use C4::Biblio qw( GetMarcFromKohaField ); { - my $items = Koha::Items->search({ -or => { homebranch => undef, holdingbranch => undef }}); - if ( $items->count ) { new_section("Not defined items.homebranch and/or items.holdingbranch")} + my $items = Koha::Items->search( { -or => { homebranch => undef, holdingbranch => undef } } ); + if ( $items->count ) { new_section("Not defined items.homebranch and/or items.holdingbranch") } while ( my $item = $items->next ) { if ( not $item->homebranch and not $item->holdingbranch ) { - new_item(sprintf "Item with itemnumber=%s does not have homebranch and holdingbranch defined", $item->itemnumber); + new_item( + sprintf "Item with itemnumber=%s does not have homebranch and holdingbranch defined", + $item->itemnumber + ); } elsif ( not $item->homebranch ) { - new_item(sprintf "Item with itemnumber=%s does not have homebranch defined", $item->itemnumber); + new_item( sprintf "Item with itemnumber=%s does not have homebranch defined", $item->itemnumber ); } else { - new_item(sprintf "Item with itemnumber=%s does not have holdingbranch defined", $item->itemnumber); + new_item( sprintf "Item with itemnumber=%s does not have holdingbranch defined", $item->itemnumber ); } } - if ( $items->count ) { new_hint("Edit these items and set valid homebranch and/or holdingbranch")} + if ( $items->count ) { new_hint("Edit these items and set valid homebranch and/or holdingbranch") } } { # No join possible, FK is missing at DB level - my @auth_types = Koha::Authority::Types->search->get_column('authtypecode'); - my $authorities = Koha::Authorities->search({authtypecode => { 'not in' => \@auth_types } }); - if ( $authorities->count ) {new_section("Invalid auth_header.authtypecode")} + my @auth_types = Koha::Authority::Types->search->get_column('authtypecode'); + my $authorities = Koha::Authorities->search( { authtypecode => { 'not in' => \@auth_types } } ); + if ( $authorities->count ) { new_section("Invalid auth_header.authtypecode") } while ( my $authority = $authorities->next ) { - new_item(sprintf "Authority with authid=%s does not have a code defined (%s)", $authority->authid, $authority->authtypecode); + new_item( + sprintf "Authority with authid=%s does not have a code defined (%s)", $authority->authid, + $authority->authtypecode + ); } - if ( $authorities->count ) {new_hint("Go to 'Home › Administration › Authority types' to define them")} + if ( $authorities->count ) { new_hint("Go to 'Home › Administration › Authority types' to define them") } } { if ( C4::Context->preference('item-level_itypes') ) { - my $items_without_itype = Koha::Items->search( { -or => [itype => undef,itype => ''] } ); + my $items_without_itype = Koha::Items->search( { -or => [ itype => undef, itype => '' ] } ); if ( $items_without_itype->count ) { new_section("Items do not have itype defined"); while ( my $item = $items_without_itype->next ) { - if (defined $item->biblioitem->itemtype && $item->biblioitem->itemtype ne '' ) { + if ( defined $item->biblioitem->itemtype && $item->biblioitem->itemtype ne '' ) { new_item( - sprintf "Item with itemnumber=%s does not have a itype value, biblio's item type will be used (%s)", + sprintf + "Item with itemnumber=%s does not have a itype value, biblio's item type will be used (%s)", $item->itemnumber, $item->biblioitem->itemtype ); } else { new_item( - sprintf "Item with itemnumber=%s does not have a itype value, additionally no item type defined for biblionumber=%s", + sprintf + "Item with itemnumber=%s does not have a itype value, additionally no item type defined for biblionumber=%s", $item->itemnumber, $item->biblioitem->biblionumber ); - } + } } new_hint("The system preference item-level_itypes expects item types to be defined at item level"); } - } - else { + } else { my $biblioitems_without_itemtype = Koha::Biblioitems->search( { itemtype => undef } ); if ( $biblioitems_without_itemtype->count ) { new_section("Biblioitems do not have itemtype defined"); @@ -91,7 +98,8 @@ use C4::Biblio qw( GetMarcFromKohaField ); my @itemtypes = Koha::ItemTypes->search->get_column('itemtype'); if ( C4::Context->preference('item-level_itypes') ) { - my $items_with_invalid_itype = Koha::Items->search( { -and => [itype => { not_in => \@itemtypes }, itype => { '!=' => '' }] } ); + my $items_with_invalid_itype = + Koha::Items->search( { -and => [ itype => { not_in => \@itemtypes }, itype => { '!=' => '' } ] } ); if ( $items_with_invalid_itype->count ) { new_section("Items have invalid itype defined"); while ( my $item = $items_with_invalid_itype->next ) { @@ -100,13 +108,12 @@ use C4::Biblio qw( GetMarcFromKohaField ); $item->itemnumber, $item->biblionumber, $item->itype ); } - new_hint("The items must have a itype value that is defined in the item types of Koha (Home › Administration › Item types administration)"); + new_hint( + "The items must have a itype value that is defined in the item types of Koha (Home › Administration › Item types administration)" + ); } - } - else { - my $biblioitems_with_invalid_itemtype = Koha::Biblioitems->search( - { itemtype => { not_in => \@itemtypes } } - ); + } else { + my $biblioitems_with_invalid_itemtype = Koha::Biblioitems->search( { itemtype => { not_in => \@itemtypes } } ); if ( $biblioitems_with_invalid_itemtype->count ) { new_section("Biblioitems do not have itemtype defined"); while ( my $biblioitem = $biblioitems_with_invalid_itemtype->next ) { @@ -115,16 +122,18 @@ use C4::Biblio qw( GetMarcFromKohaField ); $biblioitem->biblioitemnumber ); } - new_hint("The biblioitems must have a itemtype value that is defined in the item types of Koha (Home › Administration › Item types administration)"); + new_hint( + "The biblioitems must have a itemtype value that is defined in the item types of Koha (Home › Administration › Item types administration)" + ); } } my ( @decoding_errors, @ids_not_in_marc ); my $biblios = Koha::Biblios->search; - my ( $biblio_tag, $biblio_subfield ) = C4::Biblio::GetMarcFromKohaField( "biblio.biblionumber" ); - my ( $biblioitem_tag, $biblioitem_subfield ) = C4::Biblio::GetMarcFromKohaField( "biblioitems.biblioitemnumber" ); + my ( $biblio_tag, $biblio_subfield ) = C4::Biblio::GetMarcFromKohaField("biblio.biblionumber"); + my ( $biblioitem_tag, $biblioitem_subfield ) = C4::Biblio::GetMarcFromKohaField("biblioitems.biblioitemnumber"); while ( my $biblio = $biblios->next ) { - my $record = eval{$biblio->metadata->record;}; + my $record = eval { $biblio->metadata->record; }; if ($@) { push @decoding_errors, $@; next; @@ -144,31 +153,33 @@ use C4::Biblio qw( GetMarcFromKohaField ); } if ( $biblionumber != $biblio->biblionumber ) { push @ids_not_in_marc, - { + { biblionumber => $biblio->biblionumber, biblionumber_in_marc => $biblionumber, - }; + }; } if ( $biblioitemnumber != $biblio->biblioitem->biblioitemnumber ) { push @ids_not_in_marc, - { - biblionumber => $biblio->biblionumber, - biblioitemnumber => $biblio->biblioitem->biblioitemnumber, + { + biblionumber => $biblio->biblionumber, + biblioitemnumber => $biblio->biblioitem->biblioitemnumber, biblioitemnumber_in_marc => $biblionumber, - }; + }; } } - if ( @decoding_errors ) { + if (@decoding_errors) { new_section("Bibliographic records have invalid MARCXML"); new_item($_) for @decoding_errors; - new_hint("The bibliographic records must have a valid MARCXML or you will face encoding issues or wrong displays"); + new_hint( + "The bibliographic records must have a valid MARCXML or you will face encoding issues or wrong displays"); } if (@ids_not_in_marc) { new_section("Bibliographic records have MARCXML without biblionumber or biblioitemnumber"); for my $id (@ids_not_in_marc) { if ( exists $id->{biblioitemnumber} ) { new_item( - sprintf(q{Biblionumber %s has biblioitemnumber '%s' but should be '%s' in %s$%s}, + sprintf( + q{Biblionumber %s has biblioitemnumber '%s' but should be '%s' in %s$%s}, $id->{biblionumber}, $id->{biblioitemnumber}, $id->{biblioitemnumber_in_marc}, @@ -176,10 +187,10 @@ use C4::Biblio qw( GetMarcFromKohaField ); $biblioitem_subfield, ) ); - } - else { + } else { new_item( - sprintf(q{Biblionumber %s has '%s' in %s$%s}, + sprintf( + q{Biblionumber %s has '%s' in %s$%s}, $id->{biblionumber}, $id->{biblionumber_in_marc}, $biblio_tag, @@ -194,24 +205,23 @@ use C4::Biblio qw( GetMarcFromKohaField ); { my @framework_codes = Koha::BiblioFrameworks->search()->get_column('frameworkcode'); - push @framework_codes,""; # The default is not stored in frameworks, we need to force it + push @framework_codes, ""; # The default is not stored in frameworks, we need to force it my $invalid_av_per_framework = {}; - foreach my $frameworkcode ( @framework_codes ) { + foreach my $frameworkcode (@framework_codes) { + # We are only checking fields that are mapped to DB fields - my $msss = Koha::MarcSubfieldStructures->search({ - frameworkcode => $frameworkcode, - authorised_value => { - '!=' => [ -and => ( undef, '' ) ] - }, - kohafield => { - '!=' => [ -and => ( undef, '' ) ] + my $msss = Koha::MarcSubfieldStructures->search( + { + frameworkcode => $frameworkcode, + authorised_value => { '!=' => [ -and => ( undef, '' ) ] }, + kohafield => { '!=' => [ -and => ( undef, '' ) ] } } - }); + ); while ( my $mss = $msss->next ) { my $kohafield = $mss->kohafield; - my $av = $mss->authorised_value; - next if grep {$_ eq $av} qw( branches itemtypes cn_source ); # internal categories + my $av = $mss->authorised_value; + next if grep { $_ eq $av } qw( branches itemtypes cn_source ); # internal categories my $avs = Koha::AuthorisedValues->search_by_koha_field( { @@ -225,46 +235,45 @@ use C4::Biblio qw( GetMarcFromKohaField ); } else { $tmp_kohafield =~ s|items|me|; } + # replace items.attr with me.attr # We are only checking biblios with items my $items = Koha::Items->search( { - $tmp_kohafield => - { - -not_in => [ $avs->get_column('authorised_value'), '' ], - '!=' => undef, - }, + $tmp_kohafield => { + -not_in => [ $avs->get_column('authorised_value'), '' ], + '!=' => undef, + }, 'biblio.frameworkcode' => $frameworkcode }, { join => [ 'biblioitem', 'biblio' ] } ); if ( $items->count ) { - $invalid_av_per_framework->{ $frameworkcode }->{$av} = - { items => $items, kohafield => $kohafield }; + $invalid_av_per_framework->{$frameworkcode}->{$av} = + { items => $items, kohafield => $kohafield }; } } } if (%$invalid_av_per_framework) { new_section('Wrong values linked to authorised values'); for my $frameworkcode ( keys %$invalid_av_per_framework ) { - while ( my ( $av_category, $v ) = each %{$invalid_av_per_framework->{$frameworkcode}} ) { + while ( my ( $av_category, $v ) = each %{ $invalid_av_per_framework->{$frameworkcode} } ) { my $items = $v->{items}; my $kohafield = $v->{kohafield}; my ( $table, $column ) = split '\.', $kohafield; my $output; while ( my $i = $items->next ) { - my $value = $table eq 'items' - ? $i->$column - : $table eq 'biblio' - ? $i->biblio->$column - : $i->biblioitem->$column; + my $value = + $table eq 'items' ? $i->$column + : $table eq 'biblio' ? $i->biblio->$column + : $i->biblioitem->$column; $output .= " {" . $i->itemnumber . " => " . $value . "}\n"; } new_item( sprintf( - "The Framework *%s* is using the authorised value's category *%s*, " - . "but the following %s do not have a value defined ({itemnumber => value }):\n%s", + "The Framework *%s* is using the authorised value's category *%s*, " + . "but the following %s do not have a value defined ({itemnumber => value }):\n%s", $frameworkcode, $av_category, $kohafield, $output ) ); @@ -274,19 +283,21 @@ use C4::Biblio qw( GetMarcFromKohaField ); } { - my $biblios = Koha::Biblios->search({ - -or => [ - title => '', - title => undef, - ] - }); + my $biblios = Koha::Biblios->search( + { + -or => [ + title => '', + title => undef, + ] + } + ); if ( $biblios->count ) { - my ( $title_tag, $title_subtag ) = C4::Biblio::GetMarcFromKohaField( 'biblio.title' ); + my ( $title_tag, $title_subtag ) = C4::Biblio::GetMarcFromKohaField('biblio.title'); my $title_field = $title_tag // ''; - $title_field .= '$'.$title_subtag if $title_subtag; + $title_field .= '$' . $title_subtag if $title_subtag; new_section("Biblio without title $title_field"); while ( my $biblio = $biblios->next ) { - new_item(sprintf "Biblio with biblionumber=%s does not have title defined", $biblio->biblionumber); + new_item( sprintf "Biblio with biblionumber=%s does not have title defined", $biblio->biblionumber ); } new_hint("Edit these bibliographic records to define a title"); } @@ -298,7 +309,7 @@ use C4::Biblio qw( GetMarcFromKohaField ); -not => { -or => { 'me.dateofbirth' => undef, - -and => { + -and => { 'categorycode.dateofbirthrequired' => undef, 'categorycode.upperagelimit' => undef, } @@ -318,8 +329,8 @@ use C4::Biblio qw( GetMarcFromKohaField ); my $category = $invalid_patron->category; new_item( sprintf "Patron borrowernumber=%s has an invalid age of %s for their category '%s' (%s to %s)", - $invalid_patron->borrowernumber, $invalid_patron->get_age, $category->categorycode, - $category->dateofbirthrequired // '0', $category->upperagelimit // 'unlimited' + $invalid_patron->borrowernumber, $invalid_patron->get_age, $category->categorycode, + $category->dateofbirthrequired // '0', $category->upperagelimit // 'unlimited' ); } new_hint("You may change the patron's category automatically with misc/cronjobs/update_patrons_category.pl"); @@ -451,16 +462,17 @@ use C4::Biblio qw( GetMarcFromKohaField ); } sub new_section { - my ( $name ) = @_; + my ($name) = @_; say "\n== $name =="; } sub new_item { - my ( $name ) = @_; + my ($name) = @_; say "\t* $name"; } + sub new_hint { - my ( $name ) = @_; + my ($name) = @_; say "=> $name"; } diff --git a/misc/maintenance/sync_db_comments.pl b/misc/maintenance/sync_db_comments.pl index 641645894c..d11d5ceae8 100755 --- a/misc/maintenance/sync_db_comments.pl +++ b/misc/maintenance/sync_db_comments.pl @@ -21,7 +21,7 @@ use Modern::Perl; use Getopt::Long qw( GetOptions ); -use Pod::Usage qw( pod2usage ); +use Pod::Usage qw( pod2usage ); use C4::Context; use Koha::Database::Commenter; @@ -30,39 +30,42 @@ sub alert_dry_run { print "-- DRY RUN\n" if $_[0]->{dry_run}; } my $cmd_args = {}; GetOptions( - 'clear' => \$cmd_args->{clear}, - 'commit|c' => \$cmd_args->{commit}, - 'database:s' => \$cmd_args->{database}, - 'help|h' => \$cmd_args->{help}, - 'renumber' => \$cmd_args->{renumber}, - 'reset' => \$cmd_args->{reset}, - 'schema:s' => \$cmd_args->{schema_file}, - 'table:s' => \$cmd_args->{table}, - 'verbose|v' => \$cmd_args->{verbose}, + 'clear' => \$cmd_args->{clear}, + 'commit|c' => \$cmd_args->{commit}, + 'database:s' => \$cmd_args->{database}, + 'help|h' => \$cmd_args->{help}, + 'renumber' => \$cmd_args->{renumber}, + 'reset' => \$cmd_args->{reset}, + 'schema:s' => \$cmd_args->{schema_file}, + 'table:s' => \$cmd_args->{table}, + 'verbose|v' => \$cmd_args->{verbose}, ); $cmd_args->{dry_run} = !$cmd_args->{commit}; -my $commenter = Koha::Database::Commenter->new({ - database => delete $cmd_args->{database}, dbh => C4::Context->dbh, schema_file => delete $cmd_args->{schema_file}, -}); +my $commenter = Koha::Database::Commenter->new( + { + database => delete $cmd_args->{database}, dbh => C4::Context->dbh, + schema_file => delete $cmd_args->{schema_file}, + } +); my $messages = $cmd_args->{verbose} || $cmd_args->{dry_run} ? [] : undef; -if( $cmd_args->{help} ) { +if ( $cmd_args->{help} ) { pod2usage( -verbose => 2 ); -} elsif( ($cmd_args->{clear}||0) + ($cmd_args->{renumber}||0) + ($cmd_args->{reset}||0) > 1 ) { +} elsif ( ( $cmd_args->{clear} || 0 ) + ( $cmd_args->{renumber} || 0 ) + ( $cmd_args->{reset} || 0 ) > 1 ) { print "You cannot pass the clear, renumber and reset flags together\n"; -} elsif( delete $cmd_args->{clear} ) { - alert_dry_run( $cmd_args ); +} elsif ( delete $cmd_args->{clear} ) { + alert_dry_run($cmd_args); $commenter->clear( $cmd_args, $messages ); -} elsif( delete $cmd_args->{reset} ) { - alert_dry_run( $cmd_args ); +} elsif ( delete $cmd_args->{reset} ) { + alert_dry_run($cmd_args); $commenter->reset_to_schema( $cmd_args, $messages ); -} elsif( delete $cmd_args->{renumber} ) { - alert_dry_run( $cmd_args ); +} elsif ( delete $cmd_args->{renumber} ) { + alert_dry_run($cmd_args); $commenter->renumber( $cmd_args, $messages ); } else { pod2usage( -verbose => 1 ); } -print join("\n", @$messages), "\n" if $messages && @$messages; +print join( "\n", @$messages ), "\n" if $messages && @$messages; __END__ diff --git a/misc/maintenance/touch_all_biblios.pl b/misc/maintenance/touch_all_biblios.pl index dd026137e1..632c6e4058 100755 --- a/misc/maintenance/touch_all_biblios.pl +++ b/misc/maintenance/touch_all_biblios.pl @@ -29,7 +29,6 @@ use C4::Biblio qw( ModBiblio ); use Koha::Biblios; use Pod::Usage qw( pod2usage ); - sub usage { pod2usage( -verbose => 2 ); exit; @@ -39,9 +38,9 @@ sub usage { my $dbh = C4::Context->dbh; # Benchmarking variables -my $startime = time(); -my $goodcount = 0; -my $badcount = 0; +my $startime = time(); +my $goodcount = 0; +my $badcount = 0; my $totalcount = 0; # Options @@ -51,57 +50,57 @@ my $help; my $outfile; GetOptions( - 'o|output:s' => \$outfile, - 'v' => \$verbose, - 'where:s' => \$whereclause, - 'help|h' => \$help, + 'o|output:s' => \$outfile, + 'v' => \$verbose, + 'where:s' => \$whereclause, + 'help|h' => \$help, ); usage() if $help; if ($whereclause) { - $whereclause = "WHERE $whereclause"; + $whereclause = "WHERE $whereclause"; } # output log or STDOUT my $fh; -if (defined $outfile) { - open ($fh, '>', $outfile) || die ("Cannot open output file"); +if ( defined $outfile ) { + open( $fh, '>', $outfile ) || die("Cannot open output file"); } else { - open($fh, '>&', \*STDOUT) || die ("Couldn't duplicate STDOUT: $!"); + open( $fh, '>&', \*STDOUT ) || die("Couldn't duplicate STDOUT: $!"); } my $sth1 = $dbh->prepare("SELECT biblionumber, frameworkcode FROM biblio $whereclause"); $sth1->execute(); # fetch info from the search -while (my ($biblionumber, $frameworkcode) = $sth1->fetchrow_array){ - my $biblio = Koha::Biblios->find($biblionumber); - my $record = $biblio->metadata->record; +while ( my ( $biblionumber, $frameworkcode ) = $sth1->fetchrow_array ) { + my $biblio = Koha::Biblios->find($biblionumber); + my $record = $biblio->metadata->record; -my $modok = ModBiblio( $record, $biblionumber, $frameworkcode, { skip_holds_queue => 1 } ); + my $modok = ModBiblio( $record, $biblionumber, $frameworkcode, { skip_holds_queue => 1 } ); - if ($modok) { - $goodcount++; - print $fh "Touched biblio $biblionumber\n" if (defined $verbose); - } else { - $badcount++; - print $fh "ERROR WITH BIBLIO $biblionumber !!!!\n"; - } + if ($modok) { + $goodcount++; + print $fh "Touched biblio $biblionumber\n" if ( defined $verbose ); + } else { + $badcount++; + print $fh "ERROR WITH BIBLIO $biblionumber !!!!\n"; + } - $totalcount++; + $totalcount++; } close($fh); # Benchmarking -my $endtime = time(); -my $time = $endtime-$startime; -my $accuracy = $totalcount ? ($goodcount / $totalcount) * 100 : 0; # this is a percentage +my $endtime = time(); +my $time = $endtime - $startime; +my $accuracy = $totalcount ? ( $goodcount / $totalcount ) * 100 : 0; # this is a percentage my $averagetime = 0; $averagetime = $time / $totalcount if $totalcount; print "Good: $goodcount, Bad: $badcount (of $totalcount) in $time seconds\n"; -printf "Accuracy: %.2f%%\nAverage time per record: %.6f seconds\n", $accuracy, $averagetime if (defined $verbose); +printf "Accuracy: %.2f%%\nAverage time per record: %.6f seconds\n", $accuracy, $averagetime if ( defined $verbose ); print "You may wish to run the build_holds_queue.pl script now if you are using RealTimeHoldsQueue\n" if $goodcount; =head1 NAME diff --git a/misc/maintenance/touch_all_items.pl b/misc/maintenance/touch_all_items.pl index ddc9a821ce..33b8fbf815 100755 --- a/misc/maintenance/touch_all_items.pl +++ b/misc/maintenance/touch_all_items.pl @@ -28,7 +28,6 @@ use C4::Context; use Koha::Items; use Pod::Usage qw( pod2usage ); - sub usage { pod2usage( -verbose => 2 ); exit; @@ -38,9 +37,9 @@ sub usage { my $dbh = C4::Context->dbh; # Benchmarking variables -my $startime = time(); -my $goodcount = 0; -my $badcount = 0; +my $startime = time(); +my $goodcount = 0; +my $badcount = 0; my $totalcount = 0; # Options @@ -50,24 +49,24 @@ my $help; my $outfile; GetOptions( - 'o|output:s' => \$outfile, - 'v' => \$verbose, - 'where:s' => \$whereclause, - 'help|h' => \$help, + 'o|output:s' => \$outfile, + 'v' => \$verbose, + 'where:s' => \$whereclause, + 'help|h' => \$help, ); usage() if $help; if ($whereclause) { - $whereclause = "WHERE $whereclause"; + $whereclause = "WHERE $whereclause"; } # output log or STDOUT my $fh; -if (defined $outfile) { - open ($fh, '>', $outfile) || die ("Cannot open output file"); +if ( defined $outfile ) { + open( $fh, '>', $outfile ) || die("Cannot open output file"); } else { - open($fh, '>&', \*STDOUT) || die ("Couldn't duplicate STDOUT: $!"); + open( $fh, '>&', \*STDOUT ) || die("Couldn't duplicate STDOUT: $!"); } # FIXME Would be better to call Koha::Items->search here @@ -75,39 +74,39 @@ my $sth_fetch = $dbh->prepare("SELECT biblionumber, itemnumber, itemcallnumber F $sth_fetch->execute(); # fetch info from the search -while (my ($biblionumber, $itemnumber, $itemcallnumber) = $sth_fetch->fetchrow_array){ +while ( my ( $biblionumber, $itemnumber, $itemcallnumber ) = $sth_fetch->fetchrow_array ) { - my $item = Koha::Items->find($itemnumber); - next unless $item; + my $item = Koha::Items->find($itemnumber); + next unless $item; - for my $c (qw( itemcallnumber cn_source ) ){ - $item->make_column_dirty($c); - } + for my $c (qw( itemcallnumber cn_source )) { + $item->make_column_dirty($c); + } - eval { $item->store }; - my $modok = $@ ? 0 : 1; + eval { $item->store }; + my $modok = $@ ? 0 : 1; - if ($modok) { - $goodcount++; - print $fh "Touched item $itemnumber\n" if (defined $verbose); - } else { - $badcount++; - print $fh "ERROR WITH ITEM $itemnumber !!!!\n"; - } + if ($modok) { + $goodcount++; + print $fh "Touched item $itemnumber\n" if ( defined $verbose ); + } else { + $badcount++; + print $fh "ERROR WITH ITEM $itemnumber !!!!\n"; + } - $totalcount++; + $totalcount++; } close($fh); # Benchmarking -my $endtime = time(); -my $time = $endtime-$startime; -my $accuracy = $totalcount ? ($goodcount / $totalcount) * 100 : 0; # this is a percentage +my $endtime = time(); +my $time = $endtime - $startime; +my $accuracy = $totalcount ? ( $goodcount / $totalcount ) * 100 : 0; # this is a percentage my $averagetime = 0; $averagetime = $time / $totalcount if $totalcount; print "Good: $goodcount, Bad: $badcount (of $totalcount) in $time seconds\n"; -printf "Accuracy: %.2f%%\nAverage time per record: %.6f seconds\n", $accuracy, $averagetime if (defined $verbose); +printf "Accuracy: %.2f%%\nAverage time per record: %.6f seconds\n", $accuracy, $averagetime if ( defined $verbose ); =head1 NAME diff --git a/misc/maintenance/update_authorities.pl b/misc/maintenance/update_authorities.pl index e4bf74df06..b753d967f6 100755 --- a/misc/maintenance/update_authorities.pl +++ b/misc/maintenance/update_authorities.pl @@ -19,9 +19,9 @@ use Modern::Perl; -use Getopt::Long qw( GetOptions ); +use Getopt::Long qw( GetOptions ); use List::MoreUtils qw( uniq ); -use Pod::Usage qw( pod2usage ); +use Pod::Usage qw( pod2usage ); use Koha::Script; use C4::AuthoritiesMarc qw/AddAuthority DelAuthority GetAuthority merge/; @@ -46,22 +46,22 @@ if ( $delete and $merge and $renumber ) { pod2usage(q|Only one action parameter can be passed (delete, merge or renumber)|); } -if( $delete ) { +if ($delete) { delete_auth( \@authid ); -} elsif( $merge ) { +} elsif ($merge) { pod2usage(q|Reference parameter is missing|) unless $reference; merge_auth( \@authid, $reference ); -} elsif( $renumber ) { +} elsif ($renumber) { renumber( \@authid ); } else { pod2usage(1); } sub delete_auth { - my ( $auths ) = @_; + my ($auths) = @_; foreach my $authid ( uniq(@$auths) ) { - if( $confirm ) { - DelAuthority({ authid => $authid }); # triggers a merge (read: cleanup) + if ($confirm) { + DelAuthority( { authid => $authid } ); # triggers a merge (read: cleanup) print "Removing $authid\n" if $verbose; } else { print "Would have removed $authid\n" if $verbose; @@ -74,28 +74,36 @@ sub merge_auth { return unless $reference; - my $marc_ref = GetAuthority( $reference ) || die "Reference record $reference not found\n"; + my $marc_ref = GetAuthority($reference) || die "Reference record $reference not found\n"; + # First update all linked biblios of reference - merge({ mergefrom => $reference, MARCfrom => $marc_ref, mergeto => $reference, MARCto => $marc_ref, override_limit => 1 }) if $confirm; + merge( + { + mergefrom => $reference, MARCfrom => $marc_ref, mergeto => $reference, MARCto => $marc_ref, + override_limit => 1 + } + ) if $confirm; # Merge all authid's into reference my $marc; foreach my $authid ( uniq(@$auths) ) { next if $authid == $reference; $marc = GetAuthority($authid); - if( !$marc ) { + if ( !$marc ) { print "Authority id $authid ignored, does not exist.\n"; next; } - if( $confirm ) { - merge({ - mergefrom => $authid, - MARCfrom => $marc, - mergeto => $reference, - MARCto => $marc_ref, - override_limit => 1 - }); - DelAuthority({ authid => $authid, skip_merge => 1 }); + if ($confirm) { + merge( + { + mergefrom => $authid, + MARCfrom => $marc, + mergeto => $reference, + MARCto => $marc_ref, + override_limit => 1 + } + ); + DelAuthority( { authid => $authid, skip_merge => 1 } ); print "Record $authid merged into reference $reference.\n" if $verbose; } else { print "Would have merged record $authid into reference $reference.\n" if $verbose; @@ -104,19 +112,20 @@ sub merge_auth { } sub renumber { - my ( $auths ) = @_; + my ($auths) = @_; foreach my $authid ( uniq(@$auths) ) { - if( my $authority = Koha::Authorities->find($authid) ) { - my $marc = GetAuthority( $authid ); - if( $confirm ) { + if ( my $authority = Koha::Authorities->find($authid) ) { + my $marc = GetAuthority($authid); + if ($confirm) { AddAuthority( $marc, $authid, $authority->authtypecode ); - # AddAuthority contains an update of 001, 005 etc. + + # AddAuthority contains an update of 001, 005 etc. print "Renumbered $authid\n" if $verbose; } else { print "Would have renumbered $authid\n" if $verbose; } } else { - print "Record $authid not found!\n" if $verbose; + print "Record $authid not found!\n" if $verbose; } } } diff --git a/misc/migration_tools/22_to_30/convert_to_utf8.pl b/misc/migration_tools/22_to_30/convert_to_utf8.pl index 8afbb4f541..bf9a396b63 100755 --- a/misc/migration_tools/22_to_30/convert_to_utf8.pl +++ b/misc/migration_tools/22_to_30/convert_to_utf8.pl @@ -9,7 +9,7 @@ use C4::Context; my $dbh = C4::Context->dbh(); my $sth = $dbh->prepare("Show tables"); $sth->execute(); -while (my @table = $sth->fetchrow_array()) { +while ( my @table = $sth->fetchrow_array() ) { print "Altering table $table[0]\n"; my $alter_query = "ALTER TABLE $table[0] convert to CHARACTER SET UTF8 collate utf8_general_ci"; my $sth2 = $dbh->prepare($alter_query); diff --git a/misc/migration_tools/22_to_30/export_Authorities.pl b/misc/migration_tools/22_to_30/export_Authorities.pl index bed75f27c7..ecc311ae79 100755 --- a/misc/migration_tools/22_to_30/export_Authorities.pl +++ b/misc/migration_tools/22_to_30/export_Authorities.pl @@ -1,59 +1,65 @@ #!/usr/bin/perl use Modern::Perl; use C4::Context; + #use MARC::File::XML(BinaryEncoding=>"utf8"); #use MARC::File::USMARC; use C4::AuthoritiesMarc; use POSIX; + #MARC::File::XML::default_record_format("UNIMARCAUTH"); my $dbh = C4::Context->dbh; -my $rq= $dbh->prepare(qq| +my $rq = $dbh->prepare( + qq| SELECT authid,authtypecode FROM auth_header - |); -my $filename= shift @ARGV; + | +); +my $filename = shift @ARGV; $rq->execute; + #ATTENTION : Mettre la base en utf8 auparavant. #BEWARE : Set database into utf8 before. #open FILEOUTPUT,">:utf8", "$filename" or die "unable to open $filename"; -while (my ($authid,$authtypecode)=$rq->fetchrow){ - my $record=AUTHgetauthority($dbh,$authid); - if (! utf8::is_utf8($record)) { - utf8::decode($record); - } - - if (C4::Context->preference('marcflavour') eq "UNIMARC"){ - $record->leader(' nac 22 1u 4500'); - my @time = localtime(time); - my $time = sprintf('%04d%02d%02d', $time[5] + 1900, $time[4] + 1, $time[3]); - my $string= ($time=~m/([0-9\-]+)/) ? $1 : undef; - $string=~s/\-//g; - $string = sprintf("%-*s",26, $string); - substr($string,9,6,"frey50"); - unless ($record->subfield('100',"a")){ - $record->insert_fields_ordered(MARC::Field->new('100',"","","a"=>$string)); - } - if ($record->field('152')){ - if ($record->subfield('152','b')){ - } else { - $record->field('152')->add_subfields("b"=>$authtypecode); - } - } else { - $record->insert_fields_ordered(MARC::Field->new('152',"","","b"=>$authtypecode)); - } - unless ($record->field('001')){ - $record->insert_fields_ordered(MARC::Field->new('001',$authid)); - } - - AUTHmodauthority($dbh,$authid,$record,1); - } else { - $record->encoding( 'UTF-8' ); - } -# warn $record->as_usmarc; - # warn $record->as_formatted; - # warn $record->as_usmarc; +while ( my ( $authid, $authtypecode ) = $rq->fetchrow ) { + my $record = AUTHgetauthority( $dbh, $authid ); + if ( !utf8::is_utf8($record) ) { + utf8::decode($record); + } - print $record->as_usmarc(); + if ( C4::Context->preference('marcflavour') eq "UNIMARC" ) { + $record->leader(' nac 22 1u 4500'); + my @time = localtime(time); + my $time = sprintf( '%04d%02d%02d', $time[5] + 1900, $time[4] + 1, $time[3] ); + my $string = ( $time =~ m/([0-9\-]+)/ ) ? $1 : undef; + $string =~ s/\-//g; + $string = sprintf( "%-*s", 26, $string ); + substr( $string, 9, 6, "frey50" ); + unless ( $record->subfield( '100', "a" ) ) { + $record->insert_fields_ordered( MARC::Field->new( '100', "", "", "a" => $string ) ); + } + if ( $record->field('152') ) { + if ( $record->subfield( '152', 'b' ) ) { + } else { + $record->field('152')->add_subfields( "b" => $authtypecode ); + } + } else { + $record->insert_fields_ordered( MARC::Field->new( '152', "", "", "b" => $authtypecode ) ); + } + unless ( $record->field('001') ) { + $record->insert_fields_ordered( MARC::Field->new( '001', $authid ) ); + } + + AUTHmodauthority( $dbh, $authid, $record, 1 ); + } else { + $record->encoding('UTF-8'); + } + + # warn $record->as_usmarc; + # warn $record->as_formatted; + # warn $record->as_usmarc; + + print $record->as_usmarc(); } -close ; +close; diff --git a/misc/migration_tools/22_to_30/export_Authorities_xml.pl b/misc/migration_tools/22_to_30/export_Authorities_xml.pl index 2aefe5b62d..09b605b578 100755 --- a/misc/migration_tools/22_to_30/export_Authorities_xml.pl +++ b/misc/migration_tools/22_to_30/export_Authorities_xml.pl @@ -1,44 +1,49 @@ #!/usr/bin/perl use Modern::Perl; use C4::Context; -use MARC::File::XML(BinaryEncoding=>"utf8"); +use MARC::File::XML( BinaryEncoding => "utf8" ); use C4::AuthoritiesMarc; use POSIX; MARC::File::XML::default_record_format("UNIMARCAUTH"); my $dbh = C4::Context->dbh; -my $rq= $dbh->prepare(qq| +my $rq = $dbh->prepare( + qq| SELECT authid FROM auth_header - |); -my $filename= shift @ARGV; + | +); +my $filename = shift @ARGV; $rq->execute; + #ATTENTION : Mettre la base en utf8 auparavant. #BEWARE : Set database into utf8 before. -while (my ($authid)=$rq->fetchrow){ -open my $fileoutput, '>:encoding(UTF-8)', "./$filename/$authid.xml" or die "unable to open $filename"; - my $record=AUTHgetauthority($dbh,$authid); - if (! utf8::is_utf8($record)) { - utf8::decode($record); - } - -# if (C4::Context->preference('marcflavour') eq "UNIMARC"){ - $record->leader(' nac 22 1u 4500'); - my @time = localtime(time); - my $time = sprintf('%04d%02d%02d', $time[5] + 1900, $time[4] + 1, $time[3]); - my $string = ($time=~m/([0-9\-]+)/) ? $1 : undef; - $string=~s/\-//g; - $string = sprintf("%-*s",26, $string); - substr($string,9,6,"frey50"); - unless ($record->subfield(100,"a")){ - $record->insert_fields_ordered(MARC::Field->new(100,"","","a"=>$string)); - } - unless ($record->subfield('001')){ - $record->insert_fields_ordered(MARC::Field->new('001',$authid)); - } - # } else { -# $record->encoding( 'UTF-8' ); -# } - print {$fileoutput} $record->as_xml(); -close $fileoutput; +while ( my ($authid) = $rq->fetchrow ) { + open my $fileoutput, '>:encoding(UTF-8)', "./$filename/$authid.xml" or die "unable to open $filename"; + my $record = AUTHgetauthority( $dbh, $authid ); + if ( !utf8::is_utf8($record) ) { + utf8::decode($record); + } + + # if (C4::Context->preference('marcflavour') eq "UNIMARC"){ + $record->leader(' nac 22 1u 4500'); + my @time = localtime(time); + my $time = sprintf( '%04d%02d%02d', $time[5] + 1900, $time[4] + 1, $time[3] ); + my $string = ( $time =~ m/([0-9\-]+)/ ) ? $1 : undef; + $string =~ s/\-//g; + $string = sprintf( "%-*s", 26, $string ); + substr( $string, 9, 6, "frey50" ); + + unless ( $record->subfield( 100, "a" ) ) { + $record->insert_fields_ordered( MARC::Field->new( 100, "", "", "a" => $string ) ); + } + unless ( $record->subfield('001') ) { + $record->insert_fields_ordered( MARC::Field->new( '001', $authid ) ); + } + + # } else { + # $record->encoding( 'UTF-8' ); + # } + print {$fileoutput} $record->as_xml(); + close $fileoutput; } diff --git a/misc/migration_tools/22_to_30/missing090field.pl b/misc/migration_tools/22_to_30/missing090field.pl index 32a11e722a..f705f7d9a1 100755 --- a/misc/migration_tools/22_to_30/missing090field.pl +++ b/misc/migration_tools/22_to_30/missing090field.pl @@ -3,6 +3,7 @@ # Written by TG on 01/10/2005 # Revised by Joshua Ferraro on 03/31/2006 use strict; + #use warnings; FIXME - Bug 2505 # Koha modules used @@ -12,65 +13,69 @@ use C4::Biblio qw( GetMarcFromKohaField ModBiblioMarc ); use Koha::Biblios; use MARC::File::USMARC; -$|=1; +$| = 1; my $dbh = C4::Context->dbh; -my $sth=$dbh->prepare("SELECT biblionumber, biblioitemnumber FROM biblioitems"); +my $sth = $dbh->prepare("SELECT biblionumber, biblioitemnumber FROM biblioitems"); $sth->execute(); -my $i=1; -while (my ($biblionumber,$biblioitemnumber)=$sth->fetchrow ){ - my $biblio = Koha::Biblios->find($biblionumber); - my $record = $biblio->metadata->record; +my $i = 1; +while ( my ( $biblionumber, $biblioitemnumber ) = $sth->fetchrow ) { + my $biblio = Koha::Biblios->find($biblionumber); + my $record = $biblio->metadata->record; print "."; - print "\r$i" unless $i %100; - MARCmodbiblionumber($biblionumber,$biblioitemnumber,$record); + print "\r$i" unless $i % 100; + MARCmodbiblionumber( $biblionumber, $biblioitemnumber, $record ); } -sub MARCmodbiblionumber{ - my ($biblionumber,$biblioitemnumber,$record)=@_; - +sub MARCmodbiblionumber { + my ( $biblionumber, $biblioitemnumber, $record ) = @_; + return unless $record; - my ($tagfield,$biblionumtagsubfield) = &GetMarcFromKohaField( "biblio.biblionumber" ); - my ($tagfield2,$biblioitemtagsubfield) = &GetMarcFromKohaField( "biblio.biblioitemnumber" ); - - my $update=0; - if (defined $record) { + my ( $tagfield, $biblionumtagsubfield ) = &GetMarcFromKohaField("biblio.biblionumber"); + my ( $tagfield2, $biblioitemtagsubfield ) = &GetMarcFromKohaField("biblio.biblioitemnumber"); + + my $update = 0; + if ( defined $record ) { my $tag = $record->field($tagfield); + #warn "ICI : ".$record->as_formatted if $record->subfield('090','a') eq '11546'; - + # check that we have biblionumber at the right place, otherwise, update or create the field. - if ($tagfield <10) { - unless ($tag && $tag->data() == $biblionumber) { + if ( $tagfield < 10 ) { + unless ( $tag && $tag->data() == $biblionumber ) { if ($tag) { $tag->update($biblionumber); } else { - my $newrec = MARC::Field->new( $tagfield, $biblionumber); + my $newrec = MARC::Field->new( $tagfield, $biblionumber ); $record->insert_fields_ordered($newrec); } - $update=1; + $update = 1; } } else { - unless ($tag && $tag->subfield($biblionumtagsubfield) == $biblionumber) { - if($tag) { - $tag->update($tagfield => $biblionumber); + unless ( $tag && $tag->subfield($biblionumtagsubfield) == $biblionumber ) { + if ($tag) { + $tag->update( $tagfield => $biblionumber ); } else { - my $newrec = MARC::Field->new( $tagfield,'','', $biblionumtagsubfield => $biblionumber,$biblioitemtagsubfield=>$biblioitemnumber); + my $newrec = MARC::Field->new( + $tagfield, '', '', $biblionumtagsubfield => $biblionumber, + $biblioitemtagsubfield => $biblioitemnumber + ); $record->insert_fields_ordered($newrec); } - $update=1; + $update = 1; } } } else { - warn "problem with :".$biblionumber." , record undefined"; + warn "problem with :" . $biblionumber . " , record undefined"; } - - if ($update){ - &ModBiblioMarc($record,$biblionumber); + if ($update) { + &ModBiblioMarc( $record, $biblionumber ); print "\n modified : $biblionumber \n"; } - + } + END; diff --git a/misc/migration_tools/22_to_30/move_marc_to_authheader.pl b/misc/migration_tools/22_to_30/move_marc_to_authheader.pl index 53069bff01..477c6e0f6b 100755 --- a/misc/migration_tools/22_to_30/move_marc_to_authheader.pl +++ b/misc/migration_tools/22_to_30/move_marc_to_authheader.pl @@ -3,6 +3,7 @@ # script to shift marc to biblioitems # scraped from updatedatabase for dev week by chris@katipo.co.nz use strict; + #use warnings; FIXME - Bug 2505 use C4::Context; use C4::AuthoritiesMarc; @@ -12,52 +13,52 @@ use MARC::File::XML ( BinaryEncoding => 'utf8' ); print "moving MARC record to marc_header table\n"; my $dbh = C4::Context->dbh(); + # changing marc field type $dbh->do('ALTER TABLE auth_header CHANGE marc marc BLOB NULL DEFAULT NULL '); # adding marc xml, just for convenience -$dbh->do( -'ALTER TABLE auth_header ADD marcxml LONGTEXT CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ' -); +$dbh->do('ALTER TABLE auth_header ADD marcxml LONGTEXT CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL '); -$|=1; # flushes output +$| = 1; # flushes output # moving data from marc_subfield_value to biblio my $sth = $dbh->prepare('select authid,authtypecode from auth_header'); $sth->execute; -my $sth_update = - $dbh->prepare( - 'update auth_header set marc=?,marcxml=? where authid=?'); -my $totaldone = 0; -while ( my ( $authid,$authtypecode ) = $sth->fetchrow ) { -# my $authtypecode = AUTHfind_authtypecode($dbh,$authid); +my $sth_update = $dbh->prepare('update auth_header set marc=?,marcxml=? where authid=?'); +my $totaldone = 0; +while ( my ( $authid, $authtypecode ) = $sth->fetchrow ) { + + # my $authtypecode = AUTHfind_authtypecode($dbh,$authid); my $record = old_AUTHgetauthority( $dbh, $authid ); $record->leader(' nac 22 1u 4500'); my $string; - $string=~s/\-//g; - $string = sprintf("%-*s",26, $string); - substr($string,9,6,"frey50"); - unless ($record->subfield(100,"a") and length($record->subfield(100,"a")) == 26 ){ - $record->insert_fields_ordered(MARC::Field->new(100,"","","a"=>$string)); + $string =~ s/\-//g; + $string = sprintf( "%-*s", 26, $string ); + substr( $string, 9, 6, "frey50" ); + unless ( $record->subfield( 100, "a" ) and length( $record->subfield( 100, "a" ) ) == 26 ) { + $record->insert_fields_ordered( MARC::Field->new( 100, "", "", "a" => $string ) ); } - if ($record->field(152)){ - if ($record->subfield('152','b')){ - } else { - $record->field('152')->add_subfields("b"=>$authtypecode); - } + if ( $record->field(152) ) { + if ( $record->subfield( '152', 'b' ) ) { + } else { + $record->field('152')->add_subfields( "b" => $authtypecode ); + } } else { - $record->insert_fields_ordered(MARC::Field->new(152,"","","b"=>$authtypecode)); + $record->insert_fields_ordered( MARC::Field->new( 152, "", "", "b" => $authtypecode ) ); } - unless ($record->field('001')){ - $record->insert_fields_ordered(MARC::Field->new('001',$authid)); + unless ( $record->field('001') ) { + $record->insert_fields_ordered( MARC::Field->new( '001', $authid ) ); } - #Force UTF-8 in record leaded $record->encoding('UTF-8'); -# warn "REC : ".$record->as_formatted; - $sth_update->execute( $record->as_usmarc(),$record->as_xml("UNIMARCAUTH"), - $authid ); + + # warn "REC : ".$record->as_formatted; + $sth_update->execute( + $record->as_usmarc(), $record->as_xml("UNIMARCAUTH"), + $authid + ); $totaldone++; print "\r$totaldone" unless ( $totaldone % 100 ); } @@ -68,59 +69,70 @@ print "\rdone\n"; # before moving it to marcxml field. # sub old_AUTHgetauthority { -# Returns MARC::Record of the biblio passed in parameter. - my ($dbh,$authid)=@_; + + # Returns MARC::Record of the biblio passed in parameter. + my ( $dbh, $authid ) = @_; my $record = MARC::Record->new(); -#---- TODO : the leader is missing - $record->leader(' '); - my $sth=$dbh->prepare("select authid,subfieldid,tag,tagorder,tag_indicator,subfieldcode,subfieldorder,subfieldvalue + + #---- TODO : the leader is missing + $record->leader(' '); + my $sth = $dbh->prepare( + "select authid,subfieldid,tag,tagorder,tag_indicator,subfieldcode,subfieldorder,subfieldvalue from auth_subfield_table where authid=? order by tag,tagorder,subfieldorder - "); - $sth->execute($authid); - my $prevtagorder=1; - my $prevtag='XXX'; - my $previndicator; - my $field; # for >=10 tags - my $prevvalue; # for <10 tags - while (my $row=$sth->fetchrow_hashref) { - if ($row->{tagorder} ne $prevtagorder || $row->{tag} ne $prevtag) { - $previndicator.=" "; - if ($prevtag <10) { - $record->add_fields((sprintf "%03s",$prevtag),$prevvalue) unless $prevtag eq "XXX"; # ignore the 1st loop - } else { - $record->add_fields($field) unless $prevtag eq "XXX"; - } - undef $field; - $prevtagorder=$row->{tagorder}; - $prevtag = $row->{tag}; - $previndicator=$row->{tag_indicator}; - if ($row->{tag}<10) { - $prevvalue = $row->{subfieldvalue}; - } else { - $field = MARC::Field->new((sprintf "%03s",$prevtag), substr($row->{tag_indicator}.' ',0,1), substr($row->{tag_indicator}.' ',1,1), $row->{'subfieldcode'}, $row->{'subfieldvalue'} ); - } - } else { - if ($row->{tag} <10) { - $record->add_fields((sprintf "%03s",$row->{tag}), $row->{'subfieldvalue'}); - } else { - $field->add_subfields($row->{'subfieldcode'}, $row->{'subfieldvalue'} ); - } - $prevtag= $row->{tag}; - $previndicator=$row->{tag_indicator}; - } - } - # the last has not been included inside the loop... do it now ! - if ($prevtag ne "XXX") { # check that we have found something. Otherwise, prevtag is still XXX and we - # must return an empty record, not make MARC::Record fail because we try to - # create a record with XXX as field :-( - if ($prevtag <10) { - $record->add_fields($prevtag,$prevvalue); - } else { - # my $field = MARC::Field->new( $prevtag, "", "", %subfieldlist); - $record->add_fields($field); - } - } - return $record; + " + ); + $sth->execute($authid); + my $prevtagorder = 1; + my $prevtag = 'XXX'; + my $previndicator; + my $field; # for >=10 tags + my $prevvalue; # for <10 tags + + while ( my $row = $sth->fetchrow_hashref ) { + if ( $row->{tagorder} ne $prevtagorder || $row->{tag} ne $prevtag ) { + $previndicator .= " "; + if ( $prevtag < 10 ) { + $record->add_fields( ( sprintf "%03s", $prevtag ), $prevvalue ) + unless $prevtag eq "XXX"; # ignore the 1st loop + } else { + $record->add_fields($field) unless $prevtag eq "XXX"; + } + undef $field; + $prevtagorder = $row->{tagorder}; + $prevtag = $row->{tag}; + $previndicator = $row->{tag_indicator}; + if ( $row->{tag} < 10 ) { + $prevvalue = $row->{subfieldvalue}; + } else { + $field = MARC::Field->new( + ( sprintf "%03s", $prevtag ), substr( $row->{tag_indicator} . ' ', 0, 1 ), + substr( $row->{tag_indicator} . ' ', 1, 1 ), $row->{'subfieldcode'}, $row->{'subfieldvalue'} + ); + } + } else { + if ( $row->{tag} < 10 ) { + $record->add_fields( ( sprintf "%03s", $row->{tag} ), $row->{'subfieldvalue'} ); + } else { + $field->add_subfields( $row->{'subfieldcode'}, $row->{'subfieldvalue'} ); + } + $prevtag = $row->{tag}; + $previndicator = $row->{tag_indicator}; + } + } + + # the last has not been included inside the loop... do it now ! + if ( $prevtag ne "XXX" ) { # check that we have found something. Otherwise, prevtag is still XXX and we + # must return an empty record, not make MARC::Record fail because we try to + # create a record with XXX as field :-( + if ( $prevtag < 10 ) { + $record->add_fields( $prevtag, $prevvalue ); + } else { + + # my $field = MARC::Field->new( $prevtag, "", "", %subfieldlist); + $record->add_fields($field); + } + } + return $record; } diff --git a/misc/migration_tools/22_to_30/move_marc_to_biblioitems.pl b/misc/migration_tools/22_to_30/move_marc_to_biblioitems.pl index 417cc3a1f9..9452ab10c9 100755 --- a/misc/migration_tools/22_to_30/move_marc_to_biblioitems.pl +++ b/misc/migration_tools/22_to_30/move_marc_to_biblioitems.pl @@ -1,5 +1,6 @@ #!/usr/bin/perl use Modern::Perl; + # script to shift marc to biblioitems # scraped from updatedatabase for dev week by chris@katipo.co.nz use C4::Context; @@ -16,34 +17,36 @@ my $dbh = C4::Context->dbh(); # changing marc field type $dbh->do('ALTER TABLE `biblioitems` CHANGE `marc` `marc` LONGBLOB NULL DEFAULT NULL '); + # adding marc xml, just for convenience $dbh->do('ALTER TABLE `biblioitems` ADD `marcxml` LONGTEXT CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL '); + # moving data from marc_subfield_value to biblio my $sth = $dbh->prepare('select bibid,biblionumber from marc_biblio'); $sth->execute; my $sth_update = $dbh->prepare('update biblioitems set marc=?, marcxml=? where biblionumber=?'); -my $totaldone=0; +my $totaldone = 0; -$|=1; +$| = 1; + +while ( my ( $bibid, $biblionumber ) = $sth->fetchrow ) { + my $record = LocalMARCgetbiblio( $dbh, $bibid ); -while (my ($bibid,$biblionumber) = $sth->fetchrow) { - my $record = LocalMARCgetbiblio($dbh,$bibid); #Force UTF-8 in record leader $record->encoding('UTF-8'); my $marcflavour; - if (C4::Context->preference("marcflavour")=~/unimarc/i){ - $marcflavour="UNIMARC"; + if ( C4::Context->preference("marcflavour") =~ /unimarc/i ) { + $marcflavour = "UNIMARC"; } else { - $marcflavour="USMARC"; + $marcflavour = "USMARC"; } - $sth_update->execute($record->as_usmarc(),$record->as_xml_record($marcflavour),$biblionumber); + $sth_update->execute( $record->as_usmarc(), $record->as_xml_record($marcflavour), $biblionumber ); $totaldone++; print "."; - print "\r$totaldone" unless ($totaldone % 100); + print "\r$totaldone" unless ( $totaldone % 100 ); } print "\rdone\n"; - # # this sub is a copy of Biblio.pm, version 2.2.4 # It is useful only once, for moving from 2.2 to 3.0 @@ -57,24 +60,23 @@ sub LocalMARCgetbiblio { # Returns MARC::Record of the biblio passed in parameter. my ( $dbh, $bibid ) = @_; my $record = MARC::Record->new(); -# warn "". $bidid; - my $sth = - $dbh->prepare( -"select bibid,subfieldid,tag,tagorder,tag_indicator,subfieldcode,subfieldorder,subfieldvalue,valuebloblink + # warn "". $bidid; + + my $sth = $dbh->prepare( + "select bibid,subfieldid,tag,tagorder,tag_indicator,subfieldcode,subfieldorder,subfieldvalue,valuebloblink from marc_subfield_table where bibid=? order by tag,tagorder,subfieldorder " ); - my $sth2 = - $dbh->prepare( - "select subfieldvalue from marc_blob_subfield where blobidlink=?"); + my $sth2 = $dbh->prepare("select subfieldvalue from marc_blob_subfield where blobidlink=?"); $sth->execute($bibid); my $prevtagorder = 1; my $prevtag = 'XXX'; my $previndicator; my $field; # for >=10 tags my $prevvalue; # for <10 tags + while ( my $row = $sth->fetchrow_hashref ) { if ( $row->{'valuebloblink'} ) { #---- search blob if there is one @@ -86,13 +88,13 @@ sub LocalMARCgetbiblio { if ( $row->{tagorder} ne $prevtagorder || $row->{tag} ne $prevtag ) { $previndicator .= " "; if ( $prevtag < 10 ) { - if ($prevtag ne '000') { - $record->add_fields( ( sprintf "%03s", $prevtag ), $prevvalue ) unless $prevtag eq "XXX"; # ignore the 1st loop + if ( $prevtag ne '000' ) { + $record->add_fields( ( sprintf "%03s", $prevtag ), $prevvalue ) + unless $prevtag eq "XXX"; # ignore the 1st loop } else { - $record->leader(sprintf("%24s",$prevvalue)); + $record->leader( sprintf( "%24s", $prevvalue ) ); } - } - else { + } else { $record->add_fields($field) unless $prevtag eq "XXX"; } undef $field; @@ -101,8 +103,7 @@ sub LocalMARCgetbiblio { $previndicator = $row->{tag_indicator}; if ( $row->{tag} < 10 ) { $prevvalue = $row->{subfieldvalue}; - } - else { + } else { $field = MARC::Field->new( ( sprintf "%03s", $prevtag ), substr( $row->{tag_indicator} . ' ', 0, 1 ), @@ -111,15 +112,17 @@ sub LocalMARCgetbiblio { $row->{'subfieldvalue'} ); } - } - else { + } else { if ( $row->{tag} < 10 ) { - $record->add_fields( ( sprintf "%03s", $row->{tag} ), - $row->{'subfieldvalue'} ); - } - else { - $field->add_subfields( $row->{'subfieldcode'}, - $row->{'subfieldvalue'} ); + $record->add_fields( + ( sprintf "%03s", $row->{tag} ), + $row->{'subfieldvalue'} + ); + } else { + $field->add_subfields( + $row->{'subfieldcode'}, + $row->{'subfieldvalue'} + ); } $prevtag = $row->{tag}; $previndicator = $row->{tag_indicator}; @@ -127,35 +130,33 @@ sub LocalMARCgetbiblio { } # the last has not been included inside the loop... do it now ! - if ( $prevtag ne "XXX" ) - { # check that we have found something. Otherwise, prevtag is still XXX and we - # must return an empty record, not make MARC::Record fail because we try to - # create a record with XXX as field :-( + if ( $prevtag ne "XXX" ) { # check that we have found something. Otherwise, prevtag is still XXX and we + # must return an empty record, not make MARC::Record fail because we try to + # create a record with XXX as field :-( if ( $prevtag < 10 ) { $record->add_fields( $prevtag, $prevvalue ); - } - else { + } else { # my $field = MARC::Field->new( $prevtag, "", "", %subfieldlist); $record->add_fields($field); } } - if (C4::Context->preference('marcflavour')=~/unimarc/i){ - $record->leader(' nac 22 1u 4500'); - my $string; - if ($record->field(100)) { - $string = substr($record->subfield(100,"a")." ",0,35); - my $f100 = $record->field(100); - $record->delete_field($f100); - } else { - $string = POSIX::strftime("%Y%m%d", localtime); - $string=~s/\-//g; - $string = sprintf("%-*s",35, $string); - } - substr($string,22,6,"frey50"); - unless ($record->subfield(100,"a")){ - $record->insert_fields_ordered(MARC::Field->new(100,"","","a"=>"$string")); - } + if ( C4::Context->preference('marcflavour') =~ /unimarc/i ) { + $record->leader(' nac 22 1u 4500'); + my $string; + if ( $record->field(100) ) { + $string = substr( $record->subfield( 100, "a" ) . " ", 0, 35 ); + my $f100 = $record->field(100); + $record->delete_field($f100); + } else { + $string = POSIX::strftime( "%Y%m%d", localtime ); + $string =~ s/\-//g; + $string = sprintf( "%-*s", 35, $string ); + } + substr( $string, 22, 6, "frey50" ); + unless ( $record->subfield( 100, "a" ) ) { + $record->insert_fields_ordered( MARC::Field->new( 100, "", "", "a" => "$string" ) ); + } } return $record; diff --git a/misc/migration_tools/22_to_30/rebuild_leader.pl b/misc/migration_tools/22_to_30/rebuild_leader.pl index 77475f0fa4..3e19840023 100755 --- a/misc/migration_tools/22_to_30/rebuild_leader.pl +++ b/misc/migration_tools/22_to_30/rebuild_leader.pl @@ -3,6 +3,7 @@ # Written by TG on 01/10/2005 # Revised by Joshua Ferraro on 03/31/2006 use strict; + #use warnings; FIXME - Bug 2505 # Koha modules used @@ -11,40 +12,43 @@ use C4::Context; use C4::Biblio qw( ModBiblioMarc ); use MARC::File::USMARC; - my $dbh = C4::Context->dbh; -my $sth=$dbh->prepare("select m.bibid,b.biblioitemnumber from marc_biblio m left join biblioitems b on b.biblionumber=m.biblionumber "); - $sth->execute(); +my $sth = $dbh->prepare( + "select m.bibid,b.biblioitemnumber from marc_biblio m left join biblioitems b on b.biblionumber=m.biblionumber "); +$sth->execute(); -while (my ($biblionumber,$biblioitemnumber)=$sth->fetchrow ){ - my $record = MARCgetbiblio($dbh,$biblionumber); - - MARCmodleader($biblionumber,$record); - -} +while ( my ( $biblionumber, $biblioitemnumber ) = $sth->fetchrow ) { + my $record = MARCgetbiblio( $dbh, $biblionumber ); -sub MARCmodleader{ -my ($biblionumber,$record)=@_; - -my $update=0; -#warn "".$record->leader(); -#if (length($record->leader())>24){ -# $record->leader(substr($record->leader,0,24)); -# $update =1; -#} elsif (length($record->leader())<24){ - $record->leader(' nac 22 1u 4500'); - $update=1; -#} - -warn "leader : ".$record->leader if ($biblionumber==2262); -foreach ($record->field('995')) { - $record->delete_field($_); -} -if ($update){ - &ModBiblioMarc($record,$biblionumber); - print "$biblionumber \n"; -} + MARCmodleader( $biblionumber, $record ); } + +sub MARCmodleader { + my ( $biblionumber, $record ) = @_; + + my $update = 0; + + #warn "".$record->leader(); + #if (length($record->leader())>24){ + # $record->leader(substr($record->leader,0,24)); + # $update =1; + #} elsif (length($record->leader())<24){ + $record->leader(' nac 22 1u 4500'); + $update = 1; + + #} + + warn "leader : " . $record->leader if ( $biblionumber == 2262 ); + foreach ( $record->field('995') ) { + $record->delete_field($_); + } + if ($update) { + &ModBiblioMarc( $record, $biblionumber ); + print "$biblionumber \n"; + } + +} + END; diff --git a/misc/migration_tools/22_to_30/rebuild_unimarc_100.pl b/misc/migration_tools/22_to_30/rebuild_unimarc_100.pl index b0c5dc50b7..0d8094d98d 100755 --- a/misc/migration_tools/22_to_30/rebuild_unimarc_100.pl +++ b/misc/migration_tools/22_to_30/rebuild_unimarc_100.pl @@ -3,6 +3,7 @@ # Written by TG on 01/10/2005 # Revised by Joshua Ferraro on 03/31/2006 use strict; + #use warnings; FIXME - Bug 2505 # Koha modules used @@ -12,48 +13,51 @@ use C4::Biblio qw( ModBiblioMarc ); use Koha::Biblios; use MARC::File::USMARC; - my $dbh = C4::Context->dbh; -my $sth=$dbh->prepare("select biblionumber,timestamp from biblioitems"); - $sth->execute(); +my $sth = $dbh->prepare("select biblionumber,timestamp from biblioitems"); +$sth->execute(); -$|=1; # flushes output +$| = 1; # flushes output print "Creating/updating field 100 if needed\n"; -while (my ($biblionumber,$time)=$sth->fetchrow ){ -# my $record; -# print "record : $biblionumber \n"; +while ( my ( $biblionumber, $time ) = $sth->fetchrow ) { + + # my $record; + # print "record : $biblionumber \n"; my $biblio = Koha::Biblios->find($biblionumber); my $record = $biblio ? $biblio->metadata->record : undef; -# print "=> ".$record->as_formatted; - MARCmodrecord($biblionumber,$record,$time) if ($record); -# + + # print "=> ".$record->as_formatted; + MARCmodrecord( $biblionumber, $record, $time ) if ($record); + # } sub MARCmodrecord { - my ($biblionumber,$record,$time)=@_; -# warn "AVANT : ".$record->as_formatted; - my $update=0; - $record->leader(' nac 22 1u 4500'); - $update=1; - my $string; - if ($record->field(100)) { - $string = substr($record->subfield(100,"a")." ",0,35); - my $f100 = $record->field(100); - $record->delete_field($f100); - } else { - $string = POSIX::strftime("%Y%m%d", localtime); - $string=~s/\-//g; - $string = sprintf("%-*s",35, $string); - } - substr($string,22,6,"frey50"); - unless ($record->subfield(100,"a")){ - $record->insert_fields_ordered(MARC::Field->new(100,"","","a"=>"$string")); - } - if ($update){ - &ModBiblioMarc($record,$biblionumber); + my ( $biblionumber, $record, $time ) = @_; + + # warn "AVANT : ".$record->as_formatted; + my $update = 0; + $record->leader(' nac 22 1u 4500'); + $update = 1; + my $string; + if ( $record->field(100) ) { + $string = substr( $record->subfield( 100, "a" ) . " ", 0, 35 ); + my $f100 = $record->field(100); + $record->delete_field($f100); + } else { + $string = POSIX::strftime( "%Y%m%d", localtime ); + $string =~ s/\-//g; + $string = sprintf( "%-*s", 35, $string ); + } + substr( $string, 22, 6, "frey50" ); + unless ( $record->subfield( 100, "a" ) ) { + $record->insert_fields_ordered( MARC::Field->new( 100, "", "", "a" => "$string" ) ); + } + if ($update) { + &ModBiblioMarc( $record, $biblionumber ); print "\r$biblionumber" unless ( $biblionumber % 100 ); } } + END; diff --git a/misc/migration_tools/buildCOUNTRY.pl b/misc/migration_tools/buildCOUNTRY.pl index 9329ac0e59..facdf7db69 100755 --- a/misc/migration_tools/buildCOUNTRY.pl +++ b/misc/migration_tools/buildCOUNTRY.pl @@ -3,6 +3,7 @@ # delete FROM `marc_subfield_table` WHERE tag = "606" AND subfieldcode = 9; use strict; + #use warnings; FIXME - Bug 2505 # Koha modules used @@ -12,19 +13,19 @@ use C4::AuthoritiesMarc; use Time::HiRes qw( gettimeofday ); use Getopt::Long qw( GetOptions ); -my ( $fields, $number,$language) = ('',0); -my ($version, $verbose, $test_parameter, $delete); +my ( $fields, $number, $language ) = ( '', 0 ); +my ( $version, $verbose, $test_parameter, $delete ); GetOptions( - 'h' => \$version, - 'd' => \$delete, - 't' => \$test_parameter, + 'h' => \$version, + 'd' => \$delete, + 't' => \$test_parameter, 's:s' => \$fields, - 'v' => \$verbose, - 'l:s' => \$language, + 'v' => \$verbose, + 'l:s' => \$language, ); -if ($version or !$fields) { - print < 'english', - 'fre' => 'french' - ); + 'eng' => 'english', + 'fre' => 'french' +); %codesiso = ( - 'an' => 'Antilles Néerlandaises', - 'at' => 'Autriche', - 'cr' => 'Costa Rica', - 'er' => 'Erythrée', - 'fr' => ' France', - 'in' => 'Inde', - 'is' => 'Islande', - 'lt' => 'Lituanie', - 'nd' => 'Pays Bas', - 'nf' => 'Norfolk', - 'ng' => 'Nigéria', - 'pa' => 'Manama', - 'pn' => 'Pitcairn', - 're' => 'Réunion (ile)', - 'sp' => 'Espagne', - 'us' => 'Etats Unis', - ) if $language eq 'fr'; + 'an' => 'Antilles Néerlandaises', + 'at' => 'Autriche', + 'cr' => 'Costa Rica', + 'er' => 'Erythrée', + 'fr' => ' France', + 'in' => 'Inde', + 'is' => 'Islande', + 'lt' => 'Lituanie', + 'nd' => 'Pays Bas', + 'nf' => 'Norfolk', + 'ng' => 'Nigéria', + 'pa' => 'Manama', + 'pn' => 'Pitcairn', + 're' => 'Réunion (ile)', + 'sp' => 'Espagne', + 'us' => 'Etats Unis', +) if $language eq 'fr'; my $dbh = C4::Context->dbh; if ($delete) { - print "deleting country list\n"; - $dbh->do("delete from authorised_values where category='COUNTRY'"); + print "deleting country list\n"; + $dbh->do("delete from authorised_values where category='COUNTRY'"); } if ($test_parameter) { - print "TESTING MODE ONLY\n DOING NOTHING\n===============\n"; + print "TESTING MODE ONLY\n DOING NOTHING\n===============\n"; } my $starttime = gettimeofday; -my $sth = $dbh->prepare("SELECT count(*) as tot,subfieldvalue FROM marc_subfield_table WHERE tag + subfieldcode IN $fields group by subfieldvalue"); +my $sth = $dbh->prepare( + "SELECT count(*) as tot,subfieldvalue FROM marc_subfield_table WHERE tag + subfieldcode IN $fields group by subfieldvalue" +); $sth->execute; -my $i=1; +my $i = 1; print "=========================\n"; my $sth2 = $dbh->prepare("insert into authorised_values (category, authorised_value, lib) values (?,?,?)"); -while (my ($tot,$langue) = $sth->fetchrow) { - $sth2->execute('COUNTRY',$langue,$langue?$codesiso{$langue}:$langue); - print "$langue is unknown is iso list (used $tot times)\n" unless $codesiso{$langue}; +while ( my ( $tot, $langue ) = $sth->fetchrow ) { + $sth2->execute( 'COUNTRY', $langue, $langue ? $codesiso{$langue} : $langue ); + print "$langue is unknown is iso list (used $tot times)\n" unless $codesiso{$langue}; } print "=========================\n"; diff --git a/misc/migration_tools/buildEDITORS.pl b/misc/migration_tools/buildEDITORS.pl index 816b5892a0..f7a9ee260b 100755 --- a/misc/migration_tools/buildEDITORS.pl +++ b/misc/migration_tools/buildEDITORS.pl @@ -2,6 +2,7 @@ # script that rebuild EDITORS use strict; + #use warnings; FIXME - Bug 2505 # Koha modules used @@ -15,8 +16,8 @@ use Koha::Biblios; use Time::HiRes qw( gettimeofday ); use Getopt::Long qw( GetOptions ); -my ( $input_marc_file, $number) = ('',0); -my ($version, $verbose, $test_parameter, $confirm,$delete); +my ( $input_marc_file, $number ) = ( '', 0 ); +my ( $version, $verbose, $test_parameter, $confirm, $delete ); GetOptions( 'h' => \$version, 'd' => \$delete, @@ -25,8 +26,8 @@ GetOptions( 'c' => \$confirm, ); -if ($version or !$confirm) { - print <dbh; if ($delete) { - print "deleting EDITORS\n"; - my $del1 = $dbh->prepare("delete from auth_subfield_table where authid=?"); - my $del2 = $dbh->prepare("delete from auth_word where authid=?"); - my $sth = $dbh->prepare("select authid from auth_header where authtypecode='EDITORS'"); - $sth->execute; - while (my ($authid) = $sth->fetchrow) { - $del1->execute($authid); - $del2->execute($authid); - } - $dbh->do("delete from auth_header where authtypecode='EDITORS'"); + print "deleting EDITORS\n"; + my $del1 = $dbh->prepare("delete from auth_subfield_table where authid=?"); + my $del2 = $dbh->prepare("delete from auth_word where authid=?"); + my $sth = $dbh->prepare("select authid from auth_header where authtypecode='EDITORS'"); + $sth->execute; + while ( my ($authid) = $sth->fetchrow ) { + $del1->execute($authid); + $del2->execute($authid); + } + $dbh->do("delete from auth_header where authtypecode='EDITORS'"); } if ($test_parameter) { - print "TESTING MODE ONLY\n DOING NOTHING\n===============\n"; + print "TESTING MODE ONLY\n DOING NOTHING\n===============\n"; } -$|=1; # flushes output +$| = 1; # flushes output my $starttime = gettimeofday; -my $sth = $dbh->prepare("select bibid from marc_biblio"); +my $sth = $dbh->prepare("select bibid from marc_biblio"); $sth->execute; -my $i=1; +my $i = 1; my $counter; my %hash; -while (my ($bibid) = $sth->fetchrow) { - my $biblio = Koha::Biblios->find($bibid); - my $record = $biblio->metadata->record; - my $isbnField = $record->field('010'); - next unless $isbnField; - my $isbn=$isbnField->subfield('a'); - my $seg1; - if(substr($isbn, 0, 1) <=7) { - $seg1 = substr($isbn, 0, 1); - } elsif(substr($isbn, 0, 2) <= 94) { - $seg1 = substr($isbn, 0, 2); - } elsif(substr($isbn, 0, 3) <= 995) { - $seg1 = substr($isbn, 0, 3); - } elsif(substr($isbn, 0, 4) <= 9989) { - $seg1 = substr($isbn, 0, 4); - } else { - $seg1 = substr($isbn, 0, 5); - } - my $x = substr($isbn, length($seg1)); - my $seg2; - if(substr($x, 0, 2) <= 19) { -# if(sTmp2 < 10) sTmp2 = "0" sTmp2; - $seg2 = substr($x, 0, 2); - } elsif(substr($x, 0, 3) <= 699) { - $seg2 = substr($x, 0, 3); - } elsif(substr($x, 0, 4) <= 8399) { - $seg2 = substr($x, 0, 4); - } elsif(substr($x, 0, 5) <= 89999) { - $seg2 = substr($x, 0, 5); - } elsif(substr($x, 0, 6) <= 9499999) { - $seg2 = substr($x, 0, 6); - } else { - $seg2 = substr($x, 0, 7); - } - $counter++; - print "."; - my $timeneeded = gettimeofday - $starttime; - print "$counter in $timeneeded s\n" unless ($counter % 100); - - my $field = $record->field('210'); - my $editor; - $editor=$field->subfield('c') if $field; - - $field = $record->field('225'); - my $collection; - $collection=$field->subfield('a') if $field; - -# print "WARNING : editor empty for ".$record->as_formatted unless $editor and !$verbose; - $hash{$seg1.$seg2}->{editors} = $editor unless ($hash{$seg1.$seg2}->{editors}); - $hash{$seg1.$seg2}->{collections}->{$collection}++ if $collection; +while ( my ($bibid) = $sth->fetchrow ) { + my $biblio = Koha::Biblios->find($bibid); + my $record = $biblio->metadata->record; + my $isbnField = $record->field('010'); + next unless $isbnField; + my $isbn = $isbnField->subfield('a'); + my $seg1; + if ( substr( $isbn, 0, 1 ) <= 7 ) { + $seg1 = substr( $isbn, 0, 1 ); + } elsif ( substr( $isbn, 0, 2 ) <= 94 ) { + $seg1 = substr( $isbn, 0, 2 ); + } elsif ( substr( $isbn, 0, 3 ) <= 995 ) { + $seg1 = substr( $isbn, 0, 3 ); + } elsif ( substr( $isbn, 0, 4 ) <= 9989 ) { + $seg1 = substr( $isbn, 0, 4 ); + } else { + $seg1 = substr( $isbn, 0, 5 ); + } + my $x = substr( $isbn, length($seg1) ); + my $seg2; + if ( substr( $x, 0, 2 ) <= 19 ) { + + # if(sTmp2 < 10) sTmp2 = "0" sTmp2; + $seg2 = substr( $x, 0, 2 ); + } elsif ( substr( $x, 0, 3 ) <= 699 ) { + $seg2 = substr( $x, 0, 3 ); + } elsif ( substr( $x, 0, 4 ) <= 8399 ) { + $seg2 = substr( $x, 0, 4 ); + } elsif ( substr( $x, 0, 5 ) <= 89999 ) { + $seg2 = substr( $x, 0, 5 ); + } elsif ( substr( $x, 0, 6 ) <= 9499999 ) { + $seg2 = substr( $x, 0, 6 ); + } else { + $seg2 = substr( $x, 0, 7 ); + } + $counter++; + print "."; + my $timeneeded = gettimeofday - $starttime; + print "$counter in $timeneeded s\n" unless ( $counter % 100 ); + + my $field = $record->field('210'); + my $editor; + $editor = $field->subfield('c') if $field; + + $field = $record->field('225'); + my $collection; + $collection = $field->subfield('a') if $field; + + # print "WARNING : editor empty for ".$record->as_formatted unless $editor and !$verbose; + + $hash{ $seg1 . $seg2 }->{editors} = $editor unless ( $hash{ $seg1 . $seg2 }->{editors} ); + $hash{ $seg1 . $seg2 }->{collections}->{$collection}++ if $collection; } -foreach my $isbnstart (sort keys %hash) { - print "$isbnstart -- ".$hash{$isbnstart}->{editors} if $verbose; - my $collections = $hash{$isbnstart}->{collections}; - my $seriestitlelist; - foreach my $collection (sort keys %$collections) { - print " CC $collection : ".$collections->{$collection} if $verbose; - $seriestitlelist.=$collection."|"; - } - my $authorityRecord = MARC::Record->new(); - my $newfield = MARC::Field->new(200,'','','a' => "".$isbnstart, - 'b' => "".$hash{$isbnstart}->{editors}, - 'c' => "".$seriestitlelist); - $authorityRecord->insert_fields_ordered($newfield); - my $authid=AUTHaddauthority($dbh,$authorityRecord,'','EDITORS'); +foreach my $isbnstart ( sort keys %hash ) { + print "$isbnstart -- " . $hash{$isbnstart}->{editors} if $verbose; + my $collections = $hash{$isbnstart}->{collections}; + my $seriestitlelist; + foreach my $collection ( sort keys %$collections ) { + print " CC $collection : " . $collections->{$collection} if $verbose; + $seriestitlelist .= $collection . "|"; + } + my $authorityRecord = MARC::Record->new(); + my $newfield = MARC::Field->new( + 200, '', '', 'a' => "" . $isbnstart, + 'b' => "" . $hash{$isbnstart}->{editors}, + 'c' => "" . $seriestitlelist + ); + $authorityRecord->insert_fields_ordered($newfield); + my $authid = AUTHaddauthority( $dbh, $authorityRecord, '', 'EDITORS' ); -# print $authorityRecord->as_formatted."\n"; - print "\n" if $verbose; + # print $authorityRecord->as_formatted."\n"; + print "\n" if $verbose; } exit; @@ -173,7 +178,7 @@ exit; # print "*"; # #create authority. # my $authorityRecord = MARC::Record->new(); -# my $newfield = MARC::Field->new(210,'','','a' => "".$authentry, +# my $newfield = MARC::Field->new(210,'','','a' => "".$authentry, # 'b' => "".$field->subfield('b'), # 'c' => "".$field->subfield('c'), # ); @@ -188,7 +193,7 @@ exit; # my $isOK = 0; # foreach my $in7xx ($inbiblio->field($fieldnumber)) { # # !!!!! ici, il faut reconstruire l'entr� de la table de hachage comme ci dessus -# # sinon, +# # sinon, # my $inEntry = $in7xx->subfield('a'); # $inEntry =~ s/���e/g; # $inEntry =~ s/��a/g; @@ -208,7 +213,7 @@ exit; # my $isOK = 0; # foreach my $in7xx ($inbiblio->field($fieldnumber)) { # # !!!!! ici, il faut reconstruire l'entr� de la table de hachage comme ci dessus -# # sinon, +# # sinon, # my $inEntry = $in7xx->subfield('a'); # $inEntry =~ s/���e/g; # $inEntry =~ s/��a/g; @@ -228,7 +233,7 @@ exit; # my $isOK = 0; # foreach my $in7xx ($inbiblio->field($fieldnumber)) { # # !!!!! ici, il faut reconstruire l'entr� de la table de hachage comme ci dessus -# # sinon, +# # sinon, # my $inEntry = $in7xx->subfield('a'); # $inEntry =~ s/���e/g; # $inEntry =~ s/��a/g; diff --git a/misc/migration_tools/buildLANG.pl b/misc/migration_tools/buildLANG.pl index bdef6dd9d3..27dabb30ac 100755 --- a/misc/migration_tools/buildLANG.pl +++ b/misc/migration_tools/buildLANG.pl @@ -3,6 +3,7 @@ # delete FROM `marc_subfield_table` WHERE tag = "606" AND subfieldcode = 9; use strict; + #use warnings; FIXME - Bug 2505 # Koha modules used @@ -12,19 +13,19 @@ use C4::AuthoritiesMarc; use Time::HiRes qw( gettimeofday ); use Getopt::Long qw( GetOptions ); -my ( $fields, $number,$language) = ('',0); -my ($version, $verbose, $test_parameter, $delete); +my ( $fields, $number, $language ) = ( '', 0 ); +my ( $version, $verbose, $test_parameter, $delete ); GetOptions( - 'h' => \$version, - 'd' => \$delete, - 't' => \$test_parameter, + 'h' => \$version, + 'd' => \$delete, + 't' => \$test_parameter, 's:s' => \$fields, - 'v' => \$verbose, - 'l:s' => \$language, + 'v' => \$verbose, + 'l:s' => \$language, ); -if ($version or !$fields) { - print < 'english', - 'fre' => 'french' - ); + 'eng' => 'english', + 'fre' => 'french' +); %codesiso = ( - 'mis' => 'diverses', - 'und' => 'inconnue', - 'mul' => 'multilingue', - 'ger' => 'allemand', - 'eng' => 'anglais', - 'afr' => 'afrikaans', - 'akk' => 'akkadien', - 'amh' => 'amharique', - 'ang' => 'anglo-saxon (ca. 450-1100)', - 'arc' => 'araméen', - 'ara' => 'arabe', - 'arm' => 'arménien', - 'baq' => 'basque', - 'ber' => 'berbere', - 'bre' => 'breton', - 'bul' => 'bulgare', - 'cat' => 'catalan', - 'chi' => 'chinois', - 'cop' => 'copte', - 'cro' => 'croate', - 'cze' => 'tchèque', - 'dan' => 'danois', - 'dum' => 'néerlandais moyen (ca. 1050-1350)', - 'dut' => 'néerlandais', - 'spa' => 'espagnol', - 'egy' => 'egyptien', - 'esp' => 'espéranto', - 'fin' => 'finnois', - 'fra' => 'français ancien', - 'fre' => 'français', - 'frm' => 'français moyen (ca. 1400-1600)', - 'fro' => 'français ancien (842-ca. 1400)', - 'gmh' => 'allemand, moyen haut (ca. 1050-1500)', - 'got' => 'gothique', - 'grc' => 'grec classique', - 'gre' => 'grec moderne', - 'heb' => 'hébreu', - 'hin' => 'hindi', - 'hun' => 'hongrois', - 'ind' => 'indonésien', - 'ine' => 'indo-européennes, autres', - 'ita' => 'italien', - 'jap' => 'japonais', - 'jpn' => 'japonais', - 'kor' => 'coréen', - 'lan' => 'occitan (post 1500)', - 'lat' => 'latin', - 'map' => 'malayo-polynésiennes, autres', - 'mla' => 'malgache', - 'nic' => 'nigéro-congolaises, autres', - 'nor' => 'norvégien', - 'per' => 'persan', - 'pro' => 'provencal ancien (jusqu\'à 1500)', - 'pol' => 'polonais', - 'por' => 'portugais', - 'rom' => 'tzigane', - 'rum' => 'roumain', - 'rus' => 'russe', - 'sam' => 'samaritain', - 'san' => 'sanskrit', - 'scr' => 'serbo-croate', - 'sem' => 'sémitique, autres langues', - 'ser' => 'serbe', - 'sla' => 'slave, autres langues', - 'slo' => 'slovène', - 'syr' => 'syriaque', - 'swe' => 'suedois', - 'tib' => 'tibétain', - 'tur' => 'turc', - 'uga' => 'ougaritique', - 'ukr' => 'ukraine', - 'wel' => 'gallois', - 'yid' => 'yiddish', - ) if $language eq 'fr'; + 'mis' => 'diverses', + 'und' => 'inconnue', + 'mul' => 'multilingue', + 'ger' => 'allemand', + 'eng' => 'anglais', + 'afr' => 'afrikaans', + 'akk' => 'akkadien', + 'amh' => 'amharique', + 'ang' => 'anglo-saxon (ca. 450-1100)', + 'arc' => 'araméen', + 'ara' => 'arabe', + 'arm' => 'arménien', + 'baq' => 'basque', + 'ber' => 'berbere', + 'bre' => 'breton', + 'bul' => 'bulgare', + 'cat' => 'catalan', + 'chi' => 'chinois', + 'cop' => 'copte', + 'cro' => 'croate', + 'cze' => 'tchèque', + 'dan' => 'danois', + 'dum' => 'néerlandais moyen (ca. 1050-1350)', + 'dut' => 'néerlandais', + 'spa' => 'espagnol', + 'egy' => 'egyptien', + 'esp' => 'espéranto', + 'fin' => 'finnois', + 'fra' => 'français ancien', + 'fre' => 'français', + 'frm' => 'français moyen (ca. 1400-1600)', + 'fro' => 'français ancien (842-ca. 1400)', + 'gmh' => 'allemand, moyen haut (ca. 1050-1500)', + 'got' => 'gothique', + 'grc' => 'grec classique', + 'gre' => 'grec moderne', + 'heb' => 'hébreu', + 'hin' => 'hindi', + 'hun' => 'hongrois', + 'ind' => 'indonésien', + 'ine' => 'indo-européennes, autres', + 'ita' => 'italien', + 'jap' => 'japonais', + 'jpn' => 'japonais', + 'kor' => 'coréen', + 'lan' => 'occitan (post 1500)', + 'lat' => 'latin', + 'map' => 'malayo-polynésiennes, autres', + 'mla' => 'malgache', + 'nic' => 'nigéro-congolaises, autres', + 'nor' => 'norvégien', + 'per' => 'persan', + 'pro' => 'provencal ancien (jusqu\'à 1500)', + 'pol' => 'polonais', + 'por' => 'portugais', + 'rom' => 'tzigane', + 'rum' => 'roumain', + 'rus' => 'russe', + 'sam' => 'samaritain', + 'san' => 'sanskrit', + 'scr' => 'serbo-croate', + 'sem' => 'sémitique, autres langues', + 'ser' => 'serbe', + 'sla' => 'slave, autres langues', + 'slo' => 'slovène', + 'syr' => 'syriaque', + 'swe' => 'suedois', + 'tib' => 'tibétain', + 'tur' => 'turc', + 'uga' => 'ougaritique', + 'ukr' => 'ukraine', + 'wel' => 'gallois', + 'yid' => 'yiddish', +) if $language eq 'fr'; my $dbh = C4::Context->dbh; if ($delete) { - print "deleting lang list\n"; - $dbh->do("delete from authorised_values where category='LANG'"); + print "deleting lang list\n"; + $dbh->do("delete from authorised_values where category='LANG'"); } if ($test_parameter) { - print "TESTING MODE ONLY\n DOING NOTHING\n===============\n"; + print "TESTING MODE ONLY\n DOING NOTHING\n===============\n"; } my $starttime = gettimeofday; -my $sth = $dbh->prepare("SELECT DISTINCT subfieldvalue FROM marc_subfield_table WHERE tag + subfieldcode IN $fields order by subfieldvalue"); +my $sth = $dbh->prepare( + "SELECT DISTINCT subfieldvalue FROM marc_subfield_table WHERE tag + subfieldcode IN $fields order by subfieldvalue" +); $sth->execute; -my $i=1; +my $i = 1; print "=========================\n"; my $sth2 = $dbh->prepare("insert into authorised_values (category, authorised_value, lib) values (?,?,?)"); -while (my ($langue) = $sth->fetchrow) { - $sth2->execute('LANG',$langue,$langue?$codesiso{$langue}:$langue); - print "lang : $langue is unknown is iso list\n" unless $codesiso{$langue}; +while ( my ($langue) = $sth->fetchrow ) { + $sth2->execute( 'LANG', $langue, $langue ? $codesiso{$langue} : $langue ); + print "lang : $langue is unknown is iso list\n" unless $codesiso{$langue}; } print "=========================\n"; diff --git a/misc/migration_tools/build_oai_sets.pl b/misc/migration_tools/build_oai_sets.pl index 24b842b4de..ff9769cc8b 100755 --- a/misc/migration_tools/build_oai_sets.pl +++ b/misc/migration_tools/build_oai_sets.pl @@ -40,11 +40,11 @@ use Modern::Perl; use MARC::Record; use MARC::File::XML; use List::MoreUtils qw( uniq ); -use Getopt::Std qw( getopts ); +use Getopt::Std qw( getopts ); use Koha::Script; use C4::Context; -use C4::Charset qw( StripNonXmlChars ); +use C4::Charset qw( StripNonXmlChars ); use C4::OAI::Sets qw( AddOAISetsBiblios CalcOAISetsBiblio @@ -58,18 +58,18 @@ use Koha::Biblio::Metadata; my %opts; $Getopt::Std::STANDARD_HELP_VERSION = 1; -my $go = getopts('vo:l:ihr', \%opts); +my $go = getopts( 'vo:l:ihr', \%opts ); -if(!$go or $opts{h}){ +if ( !$go or $opts{h} ) { &print_usage; exit; } -my $verbose = $opts{v}; -my $offset = $opts{o}; -my $length = $opts{l}; +my $verbose = $opts{v}; +my $offset = $opts{o}; +my $length = $opts{l}; my $embed_items = $opts{i}; -my $reset = $opts{r}; +my $reset = $opts{r}; my $dbh = C4::Context->dbh; @@ -90,15 +90,15 @@ my $query = qq{ AND `schema` = ? ORDER BY biblionumber ASC }; -if($length) { +if ($length) { $query .= "LIMIT $length"; - if($offset) { + if ($offset) { $query .= " OFFSET $offset"; } } my $sth = $dbh->prepare($query); -$sth->execute( C4::Context->preference('marcflavour'), C4::Context->preference('marcflavour')); -my $results = $sth->fetchall_arrayref({}); +$sth->execute( C4::Context->preference('marcflavour'), C4::Context->preference('marcflavour') ); +my $results = $sth->fetchall_arrayref( {} ); print "done.\n" if $verbose; # Build lists of parents sets @@ -106,11 +106,11 @@ my $sets = GetOAISets; my $parentsets; foreach my $set (@$sets) { my $setSpec = $set->{'spec'}; - while($setSpec =~ /^(.+):(.+)$/) { - my $parent = $1; + while ( $setSpec =~ /^(.+):(.+)$/ ) { + my $parent = $1; my $parent_set = GetOAISetBySpec($parent); - if($parent_set) { - push @{ $parentsets->{$set->{'id'}} }, $parent_set->{'id'}; + if ($parent_set) { + push @{ $parentsets->{ $set->{'id'} } }, $parent_set->{'id'}; $setSpec = $parent; } else { last; @@ -118,30 +118,29 @@ foreach my $set (@$sets) { } } -my $num_biblios = scalar @$results; -my $i = 1; +my $num_biblios = scalar @$results; +my $i = 1; my $sets_biblios = {}; foreach my $res (@$results) { my $biblionumber = $res->{'biblionumber'}; - my $marcxml = $res->{'metadata'}; - if($verbose and $i % 1000 == 0) { - my $percent = ($i * 100) / $num_biblios; - $percent = sprintf("%.2f", $percent); + my $marcxml = $res->{'metadata'}; + if ( $verbose and $i % 1000 == 0 ) { + my $percent = ( $i * 100 ) / $num_biblios; + $percent = sprintf( "%.2f", $percent ); say "Progression: $i/$num_biblios ($percent %)"; } + # The following lines are copied from GetMarcBiblio # We don't call GetMarcBiblio to avoid a sql query to be executed each time $marcxml = StripNonXmlChars($marcxml); - MARC::File::XML->default_record_format(C4::Context->preference('marcflavour')); + MARC::File::XML->default_record_format( C4::Context->preference('marcflavour') ); my $record; - eval { - $record = MARC::Record::new_from_xml($marcxml, "UTF-8", C4::Context->preference('marcflavour')); - }; - if($@) { + eval { $record = MARC::Record::new_from_xml( $marcxml, "UTF-8", C4::Context->preference('marcflavour') ); }; + if ($@) { warn "(biblio $biblionumber) Error while creating record from marcxml: $@"; next; } - if( $embed_items && !($res->{'deleted'}) ) { + if ( $embed_items && !( $res->{'deleted'} ) ) { $record = Koha::Biblio::Metadata->record( { record => $record, @@ -151,7 +150,7 @@ foreach my $res (@$results) { ); } - my @biblio_sets = CalcOAISetsBiblio($record, $mappings); + my @biblio_sets = CalcOAISetsBiblio( $record, $mappings ); foreach my $set_id (@biblio_sets) { push @{ $sets_biblios->{$set_id} }, $biblionumber; foreach my $parent_set_id ( @{ $parentsets->{$set_id} } ) { @@ -163,15 +162,15 @@ foreach my $res (@$results) { say "Progression: done." if $verbose; say "Summary:"; -foreach my $set_id (keys %$sets_biblios) { +foreach my $set_id ( keys %$sets_biblios ) { $sets_biblios->{$set_id} = [ uniq @{ $sets_biblios->{$set_id} } ]; - my $set = GetOAISet($set_id); + my $set = GetOAISet($set_id); my $setSpec = $set->{'spec'}; - say "Set '$setSpec': ". scalar(@{$sets_biblios->{$set_id}}) ." biblios"; + say "Set '$setSpec': " . scalar( @{ $sets_biblios->{$set_id} } ) . " biblios"; } print "Updating database... "; -if($reset) { +if ($reset) { ModOAISetsBiblios( {} ); } AddOAISetsBiblios($sets_biblios); diff --git a/misc/migration_tools/bulkmarcimport.pl b/misc/migration_tools/bulkmarcimport.pl index 70721f0529..a36e5c6ed5 100755 --- a/misc/migration_tools/bulkmarcimport.pl +++ b/misc/migration_tools/bulkmarcimport.pl @@ -356,6 +356,7 @@ RECORD: while () { next; } } + # transcode the record to UTF8 if needed & applicable. if ( $record->encoding() eq 'MARC-8' and not $skip_marc8_conversion ) { my ( $guessed_charset, $charset_errors ); diff --git a/misc/migration_tools/checkNonIndexedBiblios.pl b/misc/migration_tools/checkNonIndexedBiblios.pl index 490b226912..004465cce7 100755 --- a/misc/migration_tools/checkNonIndexedBiblios.pl +++ b/misc/migration_tools/checkNonIndexedBiblios.pl @@ -30,13 +30,13 @@ use Getopt::Long qw( GetOptions ); use Koha::SearchEngine::Search; -my ( $help, $confirm, $zebraqueue, $silent,$stealth ); +my ( $help, $confirm, $zebraqueue, $silent, $stealth ); GetOptions( - 'c' => \$confirm, - 'h' => \$help, - 'z' => \$zebraqueue, - 's' => \$silent, + 'c' => \$confirm, + 'h' => \$help, + 'z' => \$zebraqueue, + 's' => \$silent, 'st' => \$stealth ); @@ -45,39 +45,41 @@ if ( $help || ( !$confirm ) ) { exit 0; } -my $dbh = C4::Context->dbh; -my $i = 0; +my $dbh = C4::Context->dbh; +my $i = 0; my $count = 0; # flushes output $| = 1; -my $sth = $dbh->prepare("SELECT biblionumber FROM biblio"); -my $sth_insert = $dbh->prepare("INSERT INTO zebraqueue (biblio_auth_number,operation,server,done) VALUES (?,'specialUpdate','biblioserver',0)"); +my $sth = $dbh->prepare("SELECT biblionumber FROM biblio"); +my $sth_insert = $dbh->prepare( + "INSERT INTO zebraqueue (biblio_auth_number,operation,server,done) VALUES (?,'specialUpdate','biblioserver',0)"); -my $searcher = Koha::SearchEngine::Search->new({index => 'biblios'}); +my $searcher = Koha::SearchEngine::Search->new( { index => 'biblios' } ); # We get all biblios $sth->execute; my ($nbhits); + # We check for each biblio while ( my ($biblionumber) = $sth->fetchrow ) { - (undef,undef,$nbhits) = $searcher->simple_search_compat("Local-number=$biblionumber"); + ( undef, undef, $nbhits ) = $searcher->simple_search_compat("Local-number=$biblionumber"); print "biblionumber $biblionumber not indexed\n" unless $nbhits || $stealth; -# If -z option we put the biblio in zebraqueue - if ($zebraqueue && !$nbhits){ + + # If -z option we put the biblio in zebraqueue + if ( $zebraqueue && !$nbhits ) { $sth_insert->execute($biblionumber); print "$biblionumber inserted in zebraqueue\n" unless $stealth; } $i++; print "$i done\n" unless $i % 1000 || $silent || $stealth; - $count++ unless $nbhits; + $count++ unless $nbhits; } -if ($count > 0 && $zebraqueue){ +if ( $count > 0 && $zebraqueue ) { print "\t$count bibliorecords not indexed and inserted in zebraqueue\n"; -} -else{ +} else { print "\t$count bibliorecords not indexed\n"; } diff --git a/misc/migration_tools/create_analytical_rel.pl b/misc/migration_tools/create_analytical_rel.pl index 1df2d55be2..ecc01d9166 100755 --- a/misc/migration_tools/create_analytical_rel.pl +++ b/misc/migration_tools/create_analytical_rel.pl @@ -1,6 +1,7 @@ #!/usr/bin/perl use strict; + #use warnings; FIXME - Bug 2505 use Koha::Script; @@ -18,23 +19,23 @@ my $do_update = 0; my $wherestrings; my $result = GetOptions( - 'run-update' => \$do_update, - 'where=s@' => \$wherestrings, - 'h|help' => \$want_help, + 'run-update' => \$do_update, + 'where=s@' => \$wherestrings, + 'h|help' => \$want_help, ); -if (not $result or $want_help or not $do_update) { +if ( not $result or $want_help or not $do_update ) { print_usage(); exit 0; } -my $num_bibs_processed = 0; -my $num_bibs_modified = 0; -my $num_noitem_forbarcode = 0; -my $num_nobarcode_inhostfield =0; -my $num_hostfields_unabletomodify =0; -my $num_bad_bibs = 0; -my $dbh = C4::Context->dbh; +my $num_bibs_processed = 0; +my $num_bibs_modified = 0; +my $num_noitem_forbarcode = 0; +my $num_nobarcode_inhostfield = 0; +my $num_hostfields_unabletomodify = 0; +my $num_bad_bibs = 0; +my $dbh = C4::Context->dbh; $dbh->{AutoCommit} = 0; process_bibs(); @@ -44,16 +45,16 @@ exit 0; sub process_bibs { my $sql = "SELECT biblionumber FROM biblio JOIN biblioitems USING (biblionumber)"; - $sql.="WHERE ". join(" AND ",@$wherestrings) if ($wherestrings); - $sql.="ORDER BY biblionumber ASC"; + $sql .= "WHERE " . join( " AND ", @$wherestrings ) if ($wherestrings); + $sql .= "ORDER BY biblionumber ASC"; my $sth = $dbh->prepare($sql); - eval{$sth->execute();}; - if ($@){ die "error $@";}; - while (my ($biblionumber) = $sth->fetchrow_array()) { + eval { $sth->execute(); }; + if ($@) { die "error $@"; } + while ( my ($biblionumber) = $sth->fetchrow_array() ) { $num_bibs_processed++; process_bib($biblionumber); - if (($num_bibs_processed % 100) == 0) { + if ( ( $num_bibs_processed % 100 ) == 0 ) { print_progress_and_commit($num_bibs_processed); } } @@ -78,16 +79,17 @@ sub process_bib { my $biblio = Koha::Biblios->find($biblionumber); my $record = $biblio->metadata->record; - unless (defined $record) { + unless ( defined $record ) { print "\nCould not retrieve bib $biblionumber from the database - record is corrupt.\n"; $num_bad_bibs++; return; } - #loop through each host field and populate subfield 0 and 9 + + #loop through each host field and populate subfield 0 and 9 my $analyticfield = '773'; foreach my $hostfield ( $record->field($analyticfield) ) { - if(my $barcode = $hostfield->subfield('o')){ - my $item = Koha::Items->find({ barcode => $barcode }); + if ( my $barcode = $hostfield->subfield('o') ) { + my $item = Koha::Items->find( { barcode => $barcode } ); if ($item) { my $modif; if ( $hostfield->subfield('0') ne $biblionumber ) { @@ -107,16 +109,15 @@ sub process_bib { $num_hostfields_unabletomodify++; } } - } - else { + } else { warn "No item record found for barcode $barcode"; $num_noitem_forbarcode++; } - } else{ - warn "No barcode in host field for biblionumber $biblionumber"; - $num_nobarcode_inhostfield++; - } - } + } else { + warn "No barcode in host field for biblionumber $biblionumber"; + $num_nobarcode_inhostfield++; + } + } } sub print_progress_and_commit { diff --git a/misc/migration_tools/ifla/update.pl b/misc/migration_tools/ifla/update.pl index 25e5ec097a..404afd2c78 100755 --- a/misc/migration_tools/ifla/update.pl +++ b/misc/migration_tools/ifla/update.pl @@ -19,10 +19,10 @@ use Modern::Perl; -use Date::Format qw( time2str ); +use Date::Format qw( time2str ); use File::Basename qw( basename ); -use FindBin qw( $Bin ); -use Getopt::Long qw( GetOptions ); +use FindBin qw( $Bin ); +use Getopt::Long qw( GetOptions ); use Locale::PO; use YAML::XS; use utf8; @@ -34,10 +34,10 @@ my $po_file; my $dump_pot; my $force; GetOptions( - 'help' => \$help, + 'help' => \$help, 'po-file=s' => \$po_file, - 'dump-pot' => \$dump_pot, - 'force' => \$force, + 'dump-pot' => \$dump_pot, + 'force' => \$force, ) or die 'Error in command line arguments'; if ($help) { @@ -68,115 +68,117 @@ EOT exit 0; } -my $defaults = YAML::XS::LoadFile("$Bin/data/defaults.yml"); +my $defaults = YAML::XS::LoadFile("$Bin/data/defaults.yml"); my $authorised_values = YAML::XS::LoadFile("$Bin/data/authorised_values.yml"); -my $authtypes = YAML::XS::LoadFile("$Bin/data/authtypes.yml"); +my $authtypes = YAML::XS::LoadFile("$Bin/data/authtypes.yml"); my @authtags; my @authsubfields; for my $authfw (qw(default CLASS CO EXP FAM GENRE_FORM NP NTEXP NTWORK PA PERS PUB SAUTTIT SNC SNG TM TU WORK)) { my $file = YAML::XS::LoadFile("$Bin/data/auth/$authfw.yml"); - push @authtags, @{ $file->{authtags} }; + push @authtags, @{ $file->{authtags} }; push @authsubfields, @{ $file->{authsubfields} }; } -my $biblio = YAML::XS::LoadFile("$Bin/data/biblio/default.yml"); -my @tags = @{ $biblio->{tags} }; +my $biblio = YAML::XS::LoadFile("$Bin/data/biblio/default.yml"); +my @tags = @{ $biblio->{tags} }; my @subfields = @{ $biblio->{subfields} }; my $translations = {}; if ($dump_pot) { $translations->{''} = Locale::PO->new( - -msgid => '', - -msgstr => "Project-Id-Version: Koha\n" . - "POT-Creation-Date: " . time2str('%Y-%m-%d %R%z', time) . "\n" . - "MIME-Version: 1.0\n" . - "Content-Type: text/plain; charset=UTF-8\n" . - "Content-Transfer-Encoding: 8bit\n", + -msgid => '', + -msgstr => "Project-Id-Version: Koha\n" + . "POT-Creation-Date: " + . time2str( '%Y-%m-%d %R%z', time ) . "\n" + . "MIME-Version: 1.0\n" + . "Content-Type: text/plain; charset=UTF-8\n" + . "Content-Transfer-Encoding: 8bit\n", ); - while (my ($category, $values) = each %$authorised_values) { + while ( my ( $category, $values ) = each %$authorised_values ) { foreach my $authorised_value (@$values) { - $translations->{$authorised_value->{lib}} = Locale::PO->new( - -msgid => $authorised_value->{lib}, + $translations->{ $authorised_value->{lib} } = Locale::PO->new( + -msgid => $authorised_value->{lib}, -msgstr => '', ); } } for my $tag (@tags) { - $translations->{$tag->{liblibrarian}} = Locale::PO->new( - -msgid => $tag->{liblibrarian}, + $translations->{ $tag->{liblibrarian} } = Locale::PO->new( + -msgid => $tag->{liblibrarian}, -msgstr => '', ); } for my $subfield (@subfields) { - $translations->{$subfield->{liblibrarian}} = Locale::PO->new( - -msgid => $subfield->{liblibrarian}, + $translations->{ $subfield->{liblibrarian} } = Locale::PO->new( + -msgid => $subfield->{liblibrarian}, -msgstr => '', ); } for my $authtype (@$authtypes) { - $translations->{$authtype->{authtypetext}} = Locale::PO->new( - -msgid => $authtype->{authtypetext}, + $translations->{ $authtype->{authtypetext} } = Locale::PO->new( + -msgid => $authtype->{authtypetext}, -msgstr => '', ); } for my $authtag (@authtags) { - $translations->{$authtag->{liblibrarian}} = Locale::PO->new( - -msgid => $authtag->{liblibrarian}, + $translations->{ $authtag->{liblibrarian} } = Locale::PO->new( + -msgid => $authtag->{liblibrarian}, -msgstr => '', ); } for my $authsubfield (@authsubfields) { - $translations->{$authsubfield->{liblibrarian}} = Locale::PO->new( - -msgid => $authsubfield->{liblibrarian}, + $translations->{ $authsubfield->{liblibrarian} } = Locale::PO->new( + -msgid => $authsubfield->{liblibrarian}, -msgstr => '', - );; + ); } - Locale::PO->save_file_fromhash("$Bin/language/template.pot", $translations, 'utf8'); + Locale::PO->save_file_fromhash( "$Bin/language/template.pot", $translations, 'utf8' ); exit 0; } if ($po_file) { - $translations = Locale::PO->load_file_ashash($po_file, 'utf8'); + $translations = Locale::PO->load_file_ashash( $po_file, 'utf8' ); } sub t { my ($string) = @_; my $quoted_string = Locale::PO->quote($string); - unless (exists $translations->{$quoted_string} and $translations->{$quoted_string}) { + unless ( exists $translations->{$quoted_string} and $translations->{$quoted_string} ) { return $string; } - return Locale::PO->dequote($translations->{$quoted_string}->msgstr); + return Locale::PO->dequote( $translations->{$quoted_string}->msgstr ); } - -my $schema = Koha::Database->new()->schema(); -my $authorised_value_rs = $schema->resultset('AuthorisedValue'); +my $schema = Koha::Database->new()->schema(); +my $authorised_value_rs = $schema->resultset('AuthorisedValue'); my $authorised_value_category_rs = $schema->resultset('AuthorisedValueCategory'); -my $marc_tag_structure_rs = $schema->resultset('MarcTagStructure'); -my $marc_subfield_structure_rs = $schema->resultset('MarcSubfieldStructure'); -my $auth_type_rs = $schema->resultset('AuthType'); -my $auth_tag_structure_rs = $schema->resultset('AuthTagStructure'); -my $auth_subfield_structure_rs = $schema->resultset('AuthSubfieldStructure'); +my $marc_tag_structure_rs = $schema->resultset('MarcTagStructure'); +my $marc_subfield_structure_rs = $schema->resultset('MarcSubfieldStructure'); +my $auth_type_rs = $schema->resultset('AuthType'); +my $auth_tag_structure_rs = $schema->resultset('AuthTagStructure'); +my $auth_subfield_structure_rs = $schema->resultset('AuthSubfieldStructure'); my $av_defaults = $defaults->{av}; -while (my ($category, $values) = each %$authorised_values) { +while ( my ( $category, $values ) = each %$authorised_values ) { foreach my $authorised_value (@$values) { - foreach my $key (keys %$av_defaults) { - unless (exists $authorised_value->{$key}) { + foreach my $key ( keys %$av_defaults ) { + unless ( exists $authorised_value->{$key} ) { $authorised_value->{$key} = $av_defaults->{$key}; } } $authorised_value->{category} = $category; - $authorised_value->{lib} = t($authorised_value->{lib}); + $authorised_value->{lib} = t( $authorised_value->{lib} ); my $value = $authorised_value->{authorised_value}; - my $av = $authorised_value_rs->find({ - category => $category, - authorised_value => $value, - }); + my $av = $authorised_value_rs->find( + { + category => $category, + authorised_value => $value, + } + ); if ($av) { say "Authorised value already exists ($category, $value)"; if ($force) { @@ -187,11 +189,13 @@ while (my ($category, $values) = each %$authorised_values) { } my $cat = $authorised_value_category_rs->find($category); - if (!$cat) { + if ( !$cat ) { say "Adding authorised value category $category"; - $authorised_value_category_rs->create({ - category_name => $category, - }); + $authorised_value_category_rs->create( + { + category_name => $category, + } + ); } say "Adding authorised value ($category, $value)"; @@ -201,14 +205,14 @@ while (my ($category, $values) = each %$authorised_values) { my $tag_defaults = $defaults->{tag}; for my $tag (@tags) { - foreach my $key (keys %$tag_defaults) { - unless (exists $tag->{$key}) { + foreach my $key ( keys %$tag_defaults ) { + unless ( exists $tag->{$key} ) { $tag->{$key} = $tag_defaults->{$key}; } } - $tag->{liblibrarian} = t($tag->{liblibrarian}); + $tag->{liblibrarian} = t( $tag->{liblibrarian} ); - my $mts = $marc_tag_structure_rs->find('', $tag->{tagfield}); + my $mts = $marc_tag_structure_rs->find( '', $tag->{tagfield} ); if ($mts) { say "Field already exists: " . $tag->{tagfield}; if ($force) { @@ -222,51 +226,54 @@ for my $tag (@tags) { $marc_tag_structure_rs->create($tag); } -my @mss = $marc_subfield_structure_rs->search({ frameworkcode => '' }); +my @mss = $marc_subfield_structure_rs->search( { frameworkcode => '' } ); my %tab_for_field; foreach my $mss (@mss) { next if $mss->tab < 0; - next if exists $tab_for_field{$mss->tagfield}; - $tab_for_field{$mss->tagfield} = $mss->tab; + next if exists $tab_for_field{ $mss->tagfield }; + $tab_for_field{ $mss->tagfield } = $mss->tab; } my $subfield_defaults = $defaults->{subfield}; for my $subfield (@subfields) { - foreach my $key (keys %$subfield_defaults) { - unless (exists $subfield->{$key}) { + foreach my $key ( keys %$subfield_defaults ) { + unless ( exists $subfield->{$key} ) { $subfield->{$key} = $subfield_defaults->{$key}; } } - $subfield->{liblibrarian} = t($subfield->{liblibrarian}); + $subfield->{liblibrarian} = t( $subfield->{liblibrarian} ); # If other subfields exist in this field, use the same tab - if (exists $tab_for_field{$subfield->{tagfield}}) { - $subfield->{tab} = $tab_for_field{$subfield->{tagfield}}; + if ( exists $tab_for_field{ $subfield->{tagfield} } ) { + $subfield->{tab} = $tab_for_field{ $subfield->{tagfield} }; } - my $mss = $marc_subfield_structure_rs->find('', $subfield->{tagfield}, $subfield->{tagsubfield}); + my $mss = $marc_subfield_structure_rs->find( '', $subfield->{tagfield}, $subfield->{tagsubfield} ); if ($mss) { - say sprintf('Subfield already exists: %s$%s', $subfield->{tagfield}, $subfield->{tagsubfield}); + say sprintf( 'Subfield already exists: %s$%s', $subfield->{tagfield}, $subfield->{tagsubfield} ); if ($force) { - say sprintf('Force mode is active, updating subfield %s$%s', $subfield->{tagfield}, $subfield->{tagsubfield}); + say sprintf( + 'Force mode is active, updating subfield %s$%s', $subfield->{tagfield}, + $subfield->{tagsubfield} + ); # Do not modify the tab of existing subfield my %values = %$subfield; delete $values{tab}; - $mss->update(\%values); + $mss->update( \%values ); } next; } - say sprintf('Adding subfield %s$%s', $subfield->{tagfield}, $subfield->{tagsubfield}); + say sprintf( 'Adding subfield %s$%s', $subfield->{tagfield}, $subfield->{tagsubfield} ); $marc_subfield_structure_rs->create($subfield); } for my $authtype (@$authtypes) { - $authtype->{authtypetext} = t($authtype->{authtypetext}); + $authtype->{authtypetext} = t( $authtype->{authtypetext} ); - my $at = $auth_type_rs->find($authtype->{authtypecode}); + my $at = $auth_type_rs->find( $authtype->{authtypecode} ); if ($at) { say "Authority type already exists: " . $authtype->{authtypecode}; if ($force) { @@ -282,24 +289,27 @@ for my $authtype (@$authtypes) { my $authtag_defaults = $defaults->{authtag}; for my $authtag (@authtags) { - foreach my $key (keys %$authtag_defaults) { - unless (exists $authtag->{$key}) { + foreach my $key ( keys %$authtag_defaults ) { + unless ( exists $authtag->{$key} ) { $authtag->{$key} = $authtag_defaults->{$key}; } } - $authtag->{liblibrarian} = t($authtag->{liblibrarian}); + $authtag->{liblibrarian} = t( $authtag->{liblibrarian} ); - my $ats = $auth_tag_structure_rs->find($authtag->{authtypecode}, $authtag->{tagfield}); + my $ats = $auth_tag_structure_rs->find( $authtag->{authtypecode}, $authtag->{tagfield} ); if ($ats) { - say sprintf('Auth field already exists: %s (%s)', $authtag->{tagfield}, $authtag->{authtypecode}); + say sprintf( 'Auth field already exists: %s (%s)', $authtag->{tagfield}, $authtag->{authtypecode} ); if ($force) { - say sprintf('Force mode is active, updating auth field %s (%s)', $authtag->{tagfield}, $authtag->{authtypecode}); + say sprintf( + 'Force mode is active, updating auth field %s (%s)', $authtag->{tagfield}, + $authtag->{authtypecode} + ); $ats->update($authtag); } next; } - say sprintf('Adding auth field %s (%s)', $authtag->{tagfield}, $authtag->{authtypecode}); + say sprintf( 'Adding auth field %s (%s)', $authtag->{tagfield}, $authtag->{authtypecode} ); $auth_tag_structure_rs->create($authtag); } @@ -310,40 +320,52 @@ foreach my $ass (@ass) { $tab_for_authfield{$authtypecode} //= {}; next if $ass->tab < 0; - next if exists $tab_for_authfield{$authtypecode}->{$ass->tagfield}; + next if exists $tab_for_authfield{$authtypecode}->{ $ass->tagfield }; - $tab_for_authfield{$authtypecode}->{$ass->tagfield} = $ass->tab; + $tab_for_authfield{$authtypecode}->{ $ass->tagfield } = $ass->tab; } my $authsubfield_defaults = $defaults->{authsubfield}; for my $authsubfield (@authsubfields) { - foreach my $key (keys %$authsubfield_defaults) { - unless (exists $authsubfield->{$key}) { + foreach my $key ( keys %$authsubfield_defaults ) { + unless ( exists $authsubfield->{$key} ) { $authsubfield->{$key} = $authsubfield_defaults->{$key}; } } - $authsubfield->{liblibrarian} = t($authsubfield->{liblibrarian}); + $authsubfield->{liblibrarian} = t( $authsubfield->{liblibrarian} ); # If other subfields exist in this field, use the same tab - if (exists $tab_for_authfield{$authsubfield->{authtypecode}}->{$authsubfield->{tagfield}}) { - $authsubfield->{tab} = $tab_for_authfield{$authsubfield->{authtypecode}}->{$authsubfield->{tagfield}}; + if ( exists $tab_for_authfield{ $authsubfield->{authtypecode} }->{ $authsubfield->{tagfield} } ) { + $authsubfield->{tab} = $tab_for_authfield{ $authsubfield->{authtypecode} }->{ $authsubfield->{tagfield} }; } - my $ass = $auth_subfield_structure_rs->find($authsubfield->{authtypecode}, $authsubfield->{tagfield}, $authsubfield->{tagsubfield}); + my $ass = $auth_subfield_structure_rs->find( + $authsubfield->{authtypecode}, $authsubfield->{tagfield}, + $authsubfield->{tagsubfield} + ); if ($ass) { - say sprintf('Auth subfield already exists: %s$%s (%s)', $authsubfield->{tagfield}, $authsubfield->{tagsubfield}, $authsubfield->{authtypecode}); + say sprintf( + 'Auth subfield already exists: %s$%s (%s)', $authsubfield->{tagfield}, + $authsubfield->{tagsubfield}, $authsubfield->{authtypecode} + ); if ($force) { - say sprintf('Force mode is active, updating auth subfield %s$%s (%s)', $authsubfield->{tagfield}, $authsubfield->{tagsubfield}, $authsubfield->{authtypecode}); + say sprintf( + 'Force mode is active, updating auth subfield %s$%s (%s)', $authsubfield->{tagfield}, + $authsubfield->{tagsubfield}, $authsubfield->{authtypecode} + ); # Do not modify the tab of existing subfield my %values = %$authsubfield; delete $values{tab}; - $ass->update(\%values); + $ass->update( \%values ); } next; } - say sprintf('Adding auth subfield %s$%s (%s)', $authsubfield->{tagfield}, $authsubfield->{tagsubfield}, $authsubfield->{authtypecode}); + say sprintf( + 'Adding auth subfield %s$%s (%s)', $authsubfield->{tagfield}, $authsubfield->{tagsubfield}, + $authsubfield->{authtypecode} + ); $auth_subfield_structure_rs->create($authsubfield); } diff --git a/misc/migration_tools/import_lexile.pl b/misc/migration_tools/import_lexile.pl index c30ec0e468..480b822b36 100755 --- a/misc/migration_tools/import_lexile.pl +++ b/misc/migration_tools/import_lexile.pl @@ -34,7 +34,7 @@ use Text::CSV; use Koha::Script; use C4::Context; use C4::Biblio qw( ModBiblio ); -use C4::Koha qw( GetVariationsOfISBN ); +use C4::Koha qw( GetVariationsOfISBN ); use Koha::Biblios; use Koha::Database; @@ -97,7 +97,7 @@ if ( $help || !$file || !$confirm ) { my $schema = Koha::Database->new()->schema(); my $csv = Text::CSV->new( { binary => 1, sep_char => "\t", formula => 'empty' } ) - or die "Cannot use CSV: " . Text::CSV->error_diag(); + or die "Cannot use CSV: " . Text::CSV->error_diag(); open my $fh, "<:encoding(utf8)", $file or die "test.csv: $!"; @@ -137,11 +137,10 @@ while ( my $row = $csv->getline_hr($fh) ) { my @likes = map { { isbn => { like => '%' . $_ . '%' } } } @isbns; my @biblionumbers = - $schema->resultset('Biblioitem')->search( { -or => \@likes } ) - ->get_column('biblionumber')->all(); + $schema->resultset('Biblioitem')->search( { -or => \@likes } )->get_column('biblionumber')->all(); say "Found matching records! Biblionumbers: " . join( " ,", @biblionumbers ) - if ( @biblionumbers && $verbose > 2 ); + if ( @biblionumbers && $verbose > 2 ); foreach my $biblionumber (@biblionumbers) { $counter++; @@ -152,13 +151,13 @@ while ( my $row = $csv->getline_hr($fh) ) { say "Found matching record! Biblionumber: $biblionumber"; if ( $verbose > 2 ) { - my $biblio = Koha::Biblios->find( $biblionumber ); + my $biblio = Koha::Biblios->find($biblionumber); say "Title from record: " . $biblio->title - if $biblio->title; + if $biblio->title; say "Author from record: " . $biblio->author - if $biblio->author; + if $biblio->author; say "ISBN from record: " . $biblio->biblioitem->isbn - if $biblio->biblioitem->isbn; + if $biblio->biblioitem->isbn; } say "Title: " . $row->{Title}; say "Author: " . $row->{Author}; @@ -171,8 +170,7 @@ while ( my $row = $csv->getline_hr($fh) ) { my $lexile_score_field; for my $field ( $record->field($field_number) ) { if ( defined( $field->subfield($subfield_source) ) - && $field->subfield($subfield_source) eq - $subfield_source_value ) + && $field->subfield($subfield_source) eq $subfield_source_value ) { $lexile_score_field = $field; last; # Each item can only have one lexile score @@ -186,8 +184,7 @@ while ( my $row = $csv->getline_hr($fh) ) { $subfield_target_audience_note => $row->{Lexile}, $subfield_source => $subfield_source_value, ); - } - else { + } else { my $field = MARC::Field->new( $field_number, '8', '#', $subfield_target_audience_note => $row->{Lexile}, @@ -196,7 +193,7 @@ while ( my $row = $csv->getline_hr($fh) ) { $record->append_fields($field); } - ModBiblio( $record, $biblionumber, undef, { overlay_context => { source => 'import_lexile' } } ) unless ( $test ); + ModBiblio( $record, $biblionumber, undef, { overlay_context => { source => 'import_lexile' } } ) unless ($test); } } diff --git a/misc/migration_tools/koha-svc.pl b/misc/migration_tools/koha-svc.pl index 396f9e73ea..3455970d26 100755 --- a/misc/migration_tools/koha-svc.pl +++ b/misc/migration_tools/koha-svc.pl @@ -23,7 +23,7 @@ use strict; use LWP::UserAgent; use File::Slurp qw( read_file write_file ); -if ( $#ARGV >= 3 && ! caller ) { # process command-line params only if not called as module! +if ( $#ARGV >= 3 && !caller ) { # process command-line params only if not called as module! my ( $url, $user, $password, $biblionumber, $file ) = @ARGV; my $svc = Koha::SVC->new( @@ -33,9 +33,9 @@ if ( $#ARGV >= 3 && ! caller ) { # process command-line params only if not calle debug => 0, ); - if ( ! $file ) { - my $marcxml = $svc->get( $biblionumber ); - my $file = "bib-$biblionumber.xml"; + if ( !$file ) { + my $marcxml = $svc->get($biblionumber); + my $file = "bib-$biblionumber.xml"; write_file $file , $marcxml; print "saved $file ", -s $file, " bytes\n"; print $marcxml; @@ -133,11 +133,11 @@ sub new { =cut sub get { - my ($self,$biblionumber) = @_; + my ( $self, $biblionumber ) = @_; my $url = $self->{url}; warn "# get $url/bib/$biblionumber\n" if $self->{debug}; - my $resp = $self->{ua}->get( "$url/bib/$biblionumber" ); + my $resp = $self->{ua}->get("$url/bib/$biblionumber"); die $resp->status_line unless $resp->is_success; return $resp->decoded_content; } diff --git a/misc/migration_tools/rebuild_zebra.pl b/misc/migration_tools/rebuild_zebra.pl index 2598f5d7f4..b62f5a02a3 100755 --- a/misc/migration_tools/rebuild_zebra.pl +++ b/misc/migration_tools/rebuild_zebra.pl @@ -19,13 +19,13 @@ use Modern::Perl; use Koha::Script; use C4::Context; -use Getopt::Long qw( GetOptions ); -use Fcntl qw( LOCK_EX LOCK_NB LOCK_UN ); -use File::Temp qw( tempdir ); -use File::Path qw( mkpath rmtree ); -use C4::Biblio qw( GetXmlBiblio ); +use Getopt::Long qw( GetOptions ); +use Fcntl qw( LOCK_EX LOCK_NB LOCK_UN ); +use File::Temp qw( tempdir ); +use File::Path qw( mkpath rmtree ); +use C4::Biblio qw( GetXmlBiblio ); use C4::AuthoritiesMarc qw( GetAuthority GetAuthorityXML ); -use C4::Items qw( Item2Marc ); +use C4::Items qw( Item2Marc ); use Koha::RecordProcessor; use Koha::Caches; use XML::LibXML; @@ -36,10 +36,11 @@ use constant LOCK_FILENAME => 'rebuild..LCK'; # # -$|=1; # flushes output +$| = 1; # flushes output + # If the cron job starts us in an unreadable dir, we will break without # this. -chdir $ENV{HOME} if (!(-r '.')); +chdir $ENV{HOME} if ( !( -r '.' ) ); my $daemon_mode; my $daemon_sleep = 5; my $directory; @@ -60,15 +61,15 @@ my $length; my $where; my $offset; my $run_as_root; -my $run_user = (getpwuid($<))[0]; +my $run_user = ( getpwuid($<) )[0]; my $wait_for_lock = 0; my $use_flock; -my $table = 'biblioitems'; +my $table = 'biblioitems'; my $is_memcached = Koha::Caches->get_instance->memcached_cache; -my $verbose_logging = 0; +my $verbose_logging = 0; my $zebraidx_log_opt = " -v none,fatal,warn "; -my $result = GetOptions( +my $result = GetOptions( 'daemon' => \$daemon_mode, 'sleep:i' => \$daemon_sleep, 'd:s' => \$directory, @@ -94,85 +95,90 @@ my $result = GetOptions( 't|table:s' => \$table, ); -if (not $result or $want_help) { +if ( not $result or $want_help ) { print_usage(); exit 0; } -if ( $as_xml ) { +if ($as_xml) { warn "Warning: You passed -x which is already the default and is now deprecated\n"; - undef $as_xml; # Should not be used later + undef $as_xml; # Should not be used later } -if( not defined $run_as_root and $run_user eq 'root') { +if ( not defined $run_as_root and $run_user eq 'root' ) { my $msg = "Warning: You are running this script as the user 'root'.\n"; - $msg .= "If this is intentional you must explicitly specify this using the -run-as-root switch\n"; - $msg .= "Please do '$0 --help' to see usage.\n"; + $msg .= "If this is intentional you must explicitly specify this using the -run-as-root switch\n"; + $msg .= "Please do '$0 --help' to see usage.\n"; die $msg; } -if ($process_zebraqueue and ($skip_export or $reset)) { +if ( $process_zebraqueue and ( $skip_export or $reset ) ) { my $msg = "Cannot specify -r or -s if -z is specified\n"; - $msg .= "Please do '$0 --help' to see usage.\n"; + $msg .= "Please do '$0 --help' to see usage.\n"; die $msg; } -if ($process_zebraqueue and $do_not_clear_zebraqueue) { +if ( $process_zebraqueue and $do_not_clear_zebraqueue ) { my $msg = "Cannot specify both -y and -z\n"; - $msg .= "Please do '$0 --help' to see usage.\n"; + $msg .= "Please do '$0 --help' to see usage.\n"; die $msg; } if ($daemon_mode) { + # incompatible flags handled above: help, reset, and do_not_clear_zebraqueue - if ($skip_export or $keep_export or $skip_index or - $where or $length or $offset) { + if ( $skip_export + or $keep_export + or $skip_index + or $where + or $length + or $offset ) + { my $msg = "Cannot specify -s, -k, -I, -where, -length, or -offset with -daemon.\n"; - $msg .= "Please do '$0 --help' to see usage.\n"; + $msg .= "Please do '$0 --help' to see usage.\n"; die $msg; } unless ($is_memcached) { warn "Warning: script running in daemon mode, without recommended caching system (memcached).\n"; } - $authorities = 1; - $biblios = 1; + $authorities = 1; + $biblios = 1; $process_zebraqueue = 1; } -if (not $biblios and not $authorities) { +if ( not $biblios and not $authorities ) { my $msg = "Must specify -b or -a to reindex bibs or authorities\n"; - $msg .= "Please do '$0 --help' to see usage.\n"; + $msg .= "Please do '$0 --help' to see usage.\n"; die $msg; } our @tables_allowed_for_select = ( 'biblioitems', 'items', 'biblio', 'biblio_metadata' ); unless ( grep { $_ eq $table } @tables_allowed_for_select ) { die "Cannot specify -t|--table with value '$table'. Only " - . ( join ', ', @tables_allowed_for_select ) - . " are allowed."; + . ( join ', ', @tables_allowed_for_select ) + . " are allowed."; } - # -v is for verbose, which seems backwards here because of how logging is set # on the CLI of zebraidx. It works this way. The default is to not log much -if ($verbose_logging >= 2) { +if ( $verbose_logging >= 2 ) { $zebraidx_log_opt = '-v none,fatal,warn,all'; } my $use_tempdir = 0; unless ($directory) { $use_tempdir = 1; - $directory = tempdir(CLEANUP => ($keep_export ? 0 : 1)); + $directory = tempdir( CLEANUP => ( $keep_export ? 0 : 1 ) ); } - -my $biblioserverdir = C4::Context->zebraconfig('biblioserver')->{directory}; +my $biblioserverdir = C4::Context->zebraconfig('biblioserver')->{directory}; my $authorityserverdir = C4::Context->zebraconfig('authorityserver')->{directory}; my $kohadir = C4::Context->config('intranetdir'); -my ($biblionumbertagfield,$biblionumbertagsubfield) = C4::Biblio::GetMarcFromKohaField( "biblio.biblionumber" ); -my ($biblioitemnumbertagfield,$biblioitemnumbertagsubfield) = C4::Biblio::GetMarcFromKohaField( "biblioitems.biblioitemnumber" ); +my ( $biblionumbertagfield, $biblionumbertagsubfield ) = C4::Biblio::GetMarcFromKohaField("biblio.biblionumber"); +my ( $biblioitemnumbertagfield, $biblioitemnumbertagsubfield ) = + C4::Biblio::GetMarcFromKohaField("biblioitems.biblioitemnumber"); my $marcxml_open = q{ @@ -188,30 +194,31 @@ my $marcxml_close = q{ # does not exist and cannot be created, we fall back on /tmp - which will # always work. -my ($lockfile, $LockFH); +my ( $lockfile, $LockFH ); foreach ( C4::Context->config("zebra_lockdir"), '/var/lock/zebra_' . C4::Context->config('database'), '/tmp/zebra_' . C4::Context->config('database') -) { + ) +{ #we try three possibilities (we really want to lock :) next if !$_; - ($LockFH, $lockfile) = _create_lockfile($_.'/rebuild'); + ( $LockFH, $lockfile ) = _create_lockfile( $_ . '/rebuild' ); last if defined $LockFH; } -if( !defined $LockFH ) { +if ( !defined $LockFH ) { print "WARNING: Could not create lock file $lockfile: $!\n"; print "Please check your koha-conf.xml for ZEBRA_LOCKDIR.\n"; print "Verify file permissions for it too.\n"; - $use_flock = 0; # we disable file locking now and will continue - # without it - # note that this mimics old behavior (before we used - # the lockfile) -}; + $use_flock = 0; # we disable file locking now and will continue + # without it + # note that this mimics old behavior (before we used + # the lockfile) +} my $start_time = time(); -if ( $verbose_logging ) { - my $pretty_time = POSIX::strftime("%H:%M:%S",localtime($start_time)); +if ($verbose_logging) { + my $pretty_time = POSIX::strftime( "%H:%M:%S", localtime($start_time) ); print "Zebra configuration information\n"; print "================================\n"; print "Zebra biblio directory = $biblioserverdir\n"; @@ -240,38 +247,39 @@ my $dbh; # See http://bugs.koha-community.org/bugzilla3/show_bug.cgi?id=11078 for details. if ($daemon_mode) { while (1) { + # For incremental updates, skip the update if the updates are locked - if (_flock($LockFH, LOCK_EX|LOCK_NB)) { + if ( _flock( $LockFH, LOCK_EX | LOCK_NB ) ) { eval { $dbh = C4::Context->dbh; - if( zebraqueue_not_empty() ) { + if ( zebraqueue_not_empty() ) { Koha::Caches->flush_L1_caches() if $is_memcached; do_one_pass(); } }; - if ($@ && $verbose_logging) { + if ( $@ && $verbose_logging ) { warn "Warning : $@\n"; } - _flock($LockFH, LOCK_UN); + _flock( $LockFH, LOCK_UN ); } sleep $daemon_sleep; } } else { + # all one-off invocations - my $lock_mode = ($wait_for_lock) ? LOCK_EX : LOCK_EX|LOCK_NB; - if (_flock($LockFH, $lock_mode)) { + my $lock_mode = ($wait_for_lock) ? LOCK_EX : LOCK_EX | LOCK_NB; + if ( _flock( $LockFH, $lock_mode ) ) { $dbh = C4::Context->dbh; do_one_pass(); - _flock($LockFH, LOCK_UN); + _flock( $LockFH, LOCK_UN ); } else { print "Skipping rebuild/update because flock failed on $lockfile: $!\n"; } } - -if ( $verbose_logging ) { +if ($verbose_logging) { print "====================\n"; - print "Indexing complete: ". pretty_time() . "\n"; + print "Indexing complete: " . pretty_time() . "\n"; print "====================\n"; print "CLEANING\n"; print "====================\n"; @@ -288,25 +296,32 @@ if ($keep_export) { print "if you just want to rebuild zebra after changing zebra config files\n"; } else { unless ($use_tempdir) { + # if we're using a temporary directory # created by File::Temp, it will be removed # automatically. - rmtree($directory, 0, 1); + rmtree( $directory, 0, 1 ); print "directory $directory deleted\n"; } } sub do_one_pass { if ($authorities) { - index_records('authority', $directory, $skip_export, $skip_index, $process_zebraqueue, $nosanitize, $do_not_clear_zebraqueue, $verbose_logging, $zebraidx_log_opt, $authorityserverdir); + index_records( + 'authority', $directory, $skip_export, $skip_index, $process_zebraqueue, $nosanitize, + $do_not_clear_zebraqueue, $verbose_logging, $zebraidx_log_opt, $authorityserverdir + ); } else { - print "skipping authorities\n" if ( $verbose_logging ); + print "skipping authorities\n" if ($verbose_logging); } if ($biblios) { - index_records('biblio', $directory, $skip_export, $skip_index, $process_zebraqueue, $nosanitize, $do_not_clear_zebraqueue, $verbose_logging, $zebraidx_log_opt, $biblioserverdir); + index_records( + 'biblio', $directory, $skip_export, $skip_index, $process_zebraqueue, $nosanitize, + $do_not_clear_zebraqueue, $verbose_logging, $zebraidx_log_opt, $biblioserverdir + ); } else { - print "skipping biblios\n" if ( $verbose_logging ); + print "skipping biblios\n" if ($verbose_logging); } } @@ -316,15 +331,14 @@ sub do_one_pass { sub zebraqueue_not_empty { my $where_str; - if ($authorities && $biblios) { + if ( $authorities && $biblios ) { $where_str = 'done = 0;'; } elsif ($biblios) { $where_str = 'server = "biblioserver" AND done = 0;'; } else { $where_str = 'server = "authorityserver" AND done = 0;'; } - my $query = - $dbh->prepare('SELECT COUNT(*) FROM zebraqueue WHERE ' . $where_str ); + my $query = $dbh->prepare( 'SELECT COUNT(*) FROM zebraqueue WHERE ' . $where_str ); $query->execute; my $count = $query->fetchrow_arrayref->[0]; @@ -336,60 +350,68 @@ sub zebraqueue_not_empty { # If they don't, then zebra is likely to spit the dummy. This returns true # if the directories had to be created, false otherwise. sub check_zebra_dirs { - my ($base) = shift() . '/'; + my ($base) = shift() . '/'; my $needed_repairing = 0; - my @dirs = ( '', 'key', 'register', 'shadow', 'tmp' ); + my @dirs = ( '', 'key', 'register', 'shadow', 'tmp' ); foreach my $dir (@dirs) { my $bdir = $base . $dir; - if (! -d $bdir) { + if ( !-d $bdir ) { $needed_repairing = 1; mkdir $bdir || die "Unable to create '$bdir': $!\n"; print "$0: needed to create '$bdir'\n"; } } return $needed_repairing; -} # ---------- end of subroutine check_zebra_dirs ---------- +} # ---------- end of subroutine check_zebra_dirs ---------- sub index_records { - my ($record_type, $directory, $skip_export, $skip_index, $process_zebraqueue, $nosanitize, $do_not_clear_zebraqueue, $verbose_logging, $zebraidx_log_opt, $server_dir) = @_; + my ( + $record_type, $directory, $skip_export, $skip_index, $process_zebraqueue, $nosanitize, + $do_not_clear_zebraqueue, $verbose_logging, $zebraidx_log_opt, $server_dir + ) = @_; my $num_records_exported = 0; - my $records_deleted = {}; - my $need_reset = check_zebra_dirs($server_dir); + my $records_deleted = {}; + my $need_reset = check_zebra_dirs($server_dir); if ($need_reset) { print "$0: found broken zebra server directories: forcing a rebuild\n"; $reset = 1; } - if ($skip_export && $verbose_logging) { + if ( $skip_export && $verbose_logging ) { print "====================\n"; print "SKIPPING $record_type export\n"; print "====================\n"; } else { - if ( $verbose_logging ) { + if ($verbose_logging) { print "====================\n"; print "exporting $record_type " . pretty_time() . "\n"; print "====================\n"; } - mkdir "$directory" unless (-d $directory); - mkdir "$directory/$record_type" unless (-d "$directory/$record_type"); + mkdir "$directory" unless ( -d $directory ); + mkdir "$directory/$record_type" unless ( -d "$directory/$record_type" ); if ($process_zebraqueue) { my $entries; - unless ( $process_zebraqueue_skip_deletes ) { - $entries = select_zebraqueue_records($record_type, 'deleted'); - mkdir "$directory/del_$record_type" unless (-d "$directory/del_$record_type"); - $records_deleted = generate_deleted_marc_records($record_type, $entries, "$directory/del_$record_type"); + unless ($process_zebraqueue_skip_deletes) { + $entries = select_zebraqueue_records( $record_type, 'deleted' ); + mkdir "$directory/del_$record_type" unless ( -d "$directory/del_$record_type" ); + $records_deleted = + generate_deleted_marc_records( $record_type, $entries, "$directory/del_$record_type" ); mark_zebraqueue_batch_done($entries); } - $entries = select_zebraqueue_records($record_type, 'updated'); - mkdir "$directory/upd_$record_type" unless (-d "$directory/upd_$record_type"); - $num_records_exported = export_marc_records_from_list($record_type,$entries, "$directory/upd_$record_type", $records_deleted); + $entries = select_zebraqueue_records( $record_type, 'updated' ); + mkdir "$directory/upd_$record_type" unless ( -d "$directory/upd_$record_type" ); + $num_records_exported = export_marc_records_from_list( + $record_type, $entries, "$directory/upd_$record_type", + $records_deleted + ); mark_zebraqueue_batch_done($entries); } else { my $sth = select_all_records($record_type); - $num_records_exported = export_marc_records_from_sth($record_type, $sth, "$directory/$record_type", $nosanitize); + $num_records_exported = + export_marc_records_from_sth( $record_type, $sth, "$directory/$record_type", $nosanitize ); unless ($do_not_clear_zebraqueue) { mark_all_zebraqueue_done($record_type); } @@ -406,49 +428,58 @@ sub index_records { print "====================\n"; } } else { - if ( $verbose_logging ) { + if ($verbose_logging) { print "====================\n"; print "REINDEXING zebra " . pretty_time() . "\n"; print "====================\n"; } my $record_fmt = 'marcxml'; if ($process_zebraqueue) { - do_indexing($record_type, 'adelete', "$directory/del_$record_type", $reset, $noshadow, $record_fmt, $zebraidx_log_opt) - if %$records_deleted; - do_indexing($record_type, 'update', "$directory/upd_$record_type", $reset, $noshadow, $record_fmt, $zebraidx_log_opt) - if $num_records_exported; + do_indexing( + $record_type, 'adelete', "$directory/del_$record_type", $reset, $noshadow, $record_fmt, + $zebraidx_log_opt + ) if %$records_deleted; + do_indexing( + $record_type, 'update', "$directory/upd_$record_type", $reset, $noshadow, $record_fmt, + $zebraidx_log_opt + ) if $num_records_exported; } else { - do_indexing($record_type, 'update', "$directory/$record_type", $reset, $noshadow, $record_fmt, $zebraidx_log_opt) - if ($num_records_exported or $skip_export); + do_indexing( + $record_type, 'update', "$directory/$record_type", $reset, $noshadow, $record_fmt, + $zebraidx_log_opt + ) if ( $num_records_exported or $skip_export ); } } } - sub select_zebraqueue_records { - my ($record_type, $update_type) = @_; + my ( $record_type, $update_type ) = @_; - my $server = ($record_type eq 'biblio') ? 'biblioserver' : 'authorityserver'; - my $op = ($update_type eq 'deleted') ? 'recordDelete' : 'specialUpdate'; + my $server = ( $record_type eq 'biblio' ) ? 'biblioserver' : 'authorityserver'; + my $op = ( $update_type eq 'deleted' ) ? 'recordDelete' : 'specialUpdate'; - my $sth = $dbh->prepare("SELECT id, biblio_auth_number + my $sth = $dbh->prepare( + "SELECT id, biblio_auth_number FROM zebraqueue WHERE server = ? AND operation = ? AND done = 0 - ORDER BY id DESC"); - $sth->execute($server, $op); - my $entries = $sth->fetchall_arrayref({}); + ORDER BY id DESC" + ); + $sth->execute( $server, $op ); + my $entries = $sth->fetchall_arrayref( {} ); } sub mark_all_zebraqueue_done { my ($record_type) = @_; - my $server = ($record_type eq 'biblio') ? 'biblioserver' : 'authorityserver'; + my $server = ( $record_type eq 'biblio' ) ? 'biblioserver' : 'authorityserver'; - my $sth = $dbh->prepare("UPDATE zebraqueue SET done = 1 + my $sth = $dbh->prepare( + "UPDATE zebraqueue SET done = 1 WHERE server = ? - AND done = 0"); + AND done = 0" + ); $sth->execute($server); } @@ -458,7 +489,7 @@ sub mark_zebraqueue_batch_done { $dbh->{AutoCommit} = 0; my $sth = $dbh->prepare("UPDATE zebraqueue SET done = 1 WHERE id = ?"); $dbh->commit(); - foreach my $id (map { $_->{id} } @$entries) { + foreach my $id ( map { $_->{id} } @$entries ) { $sth->execute($id); } $dbh->{AutoCommit} = 1; @@ -466,14 +497,14 @@ sub mark_zebraqueue_batch_done { sub select_all_records { my $record_type = shift; - return ($record_type eq 'biblio') ? select_all_biblios() : select_all_authorities(); + return ( $record_type eq 'biblio' ) ? select_all_biblios() : select_all_authorities(); } sub select_all_authorities { - my $strsth=qq{SELECT authid FROM auth_header}; - $strsth.=qq{ WHERE $where } if ($where); - $strsth.=qq{ LIMIT $length } if ($length && !$offset); - $strsth.=qq{ LIMIT $offset,$length } if ($length && $offset); + my $strsth = qq{SELECT authid FROM auth_header}; + $strsth .= qq{ WHERE $where } if ($where); + $strsth .= qq{ LIMIT $length } if ( $length && !$offset ); + $strsth .= qq{ LIMIT $offset,$length } if ( $length && $offset ); my $sth = $dbh->prepare($strsth); $sth->execute(); return $sth; @@ -481,18 +512,18 @@ sub select_all_authorities { sub select_all_biblios { $table = 'biblioitems' - unless grep { $_ eq $table } @tables_allowed_for_select; + unless grep { $_ eq $table } @tables_allowed_for_select; my $strsth = qq{ SELECT DISTINCT biblionumber FROM $table }; - $strsth.=qq{ WHERE $where } if ($where); - $strsth.=qq{ LIMIT $length } if ($length && !$offset); - $strsth.=qq{ LIMIT $offset,$length } if ($offset); + $strsth .= qq{ WHERE $where } if ($where); + $strsth .= qq{ LIMIT $length } if ( $length && !$offset ); + $strsth .= qq{ LIMIT $offset,$length } if ($offset); my $sth = $dbh->prepare($strsth); $sth->execute(); return $sth; } sub export_marc_records_from_sth { - my ($record_type, $sth, $directory, $nosanitize) = @_; + my ( $record_type, $sth, $directory, $nosanitize ) = @_; my $num_exported = 0; open my $fh, '>:encoding(UTF-8) ', "$directory/exported_records" or die $!; @@ -500,56 +531,54 @@ sub export_marc_records_from_sth { print {$fh} $marcxml_open; my $i = 0; - my ( $itemtag, $itemsubfield ) = C4::Biblio::GetMarcFromKohaField( "items.itemnumber" ); - while (my ($record_number) = $sth->fetchrow_array) { - print "." if ( $verbose_logging ); - print "\r$i" unless ($i++ %100 or !$verbose_logging); - if ( $nosanitize ) { - my $marcxml = $record_type eq 'biblio' - ? GetXmlBiblio( $record_number ) - : GetAuthorityXML( $record_number ); - if ($record_type eq 'biblio'){ + my ( $itemtag, $itemsubfield ) = C4::Biblio::GetMarcFromKohaField("items.itemnumber"); + while ( my ($record_number) = $sth->fetchrow_array ) { + print "." if ($verbose_logging); + print "\r$i" unless ( $i++ % 100 or !$verbose_logging ); + if ($nosanitize) { + my $marcxml = + $record_type eq 'biblio' + ? GetXmlBiblio($record_number) + : GetAuthorityXML($record_number); + if ( $record_type eq 'biblio' ) { my $biblio = Koha::Biblios->find($record_number); next unless $biblio; my $items = $biblio->items; - if ($items->count){ + if ( $items->count ) { my $record = MARC::Record->new; $record->encoding('UTF-8'); my @itemsrecord; - for my $item ( @{$items->unblessed} ) { - my $record = Item2Marc($item, $record_number); + for my $item ( @{ $items->unblessed } ) { + my $record = Item2Marc( $item, $record_number ); push @itemsrecord, $record->field($itemtag); } $record->insert_fields_ordered(@itemsrecord); my $itemsxml = $record->as_xml_record(); $marcxml = - substr($marcxml, 0, length($marcxml)-10) . - substr($itemsxml, index($itemsxml, "\n", 0) + 10); + substr( $marcxml, 0, length($marcxml) - 10 ) + . substr( $itemsxml, index( $itemsxml, "\n", 0 ) + 10 ); } } + # extra test to ensure that result is valid XML; otherwise # Zebra won't parse it in DOM mode - eval { - my $doc = $tester->parse_string($marcxml); - }; + eval { my $doc = $tester->parse_string($marcxml); }; if ($@) { warn "Error exporting record $record_number ($record_type): $@\n"; next; } - if ( $marcxml ) { + if ($marcxml) { $marcxml =~ s!<\?xml version="1.0" encoding="UTF-8"\?>\n!!; print {$fh} $marcxml; $num_exported++; } next; } - my ($marc) = get_corrected_marc_record($record_type, $record_number); - if (defined $marc) { + my ($marc) = get_corrected_marc_record( $record_type, $record_number ); + if ( defined $marc ) { eval { - my $rec = $marc->as_xml_record(C4::Context->preference('marcflavour')); - eval { - my $doc = $tester->parse_string($rec); - }; + my $rec = $marc->as_xml_record( C4::Context->preference('marcflavour') ); + eval { my $doc = $tester->parse_string($rec); }; if ($@) { die "invalid XML: $@"; } @@ -563,7 +592,7 @@ sub export_marc_records_from_sth { } } } - print "\nRecords exported: $num_exported " . pretty_time() . "\n" if ( $verbose_logging ); + print "\nRecords exported: $num_exported " . pretty_time() . "\n" if ($verbose_logging); print {$fh} $marcxml_close; close $fh; @@ -571,7 +600,7 @@ sub export_marc_records_from_sth { } sub export_marc_records_from_list { - my ($record_type, $entries, $directory, $records_deleted) = @_; + my ( $record_type, $entries, $directory, $records_deleted ) = @_; my $num_exported = 0; open my $fh, '>:encoding(UTF-8)', "$directory/exported_records" or die $!; @@ -582,25 +611,27 @@ sub export_marc_records_from_list { # Skip any deleted records. We check for this anyway, but this reduces error spam my %found = %$records_deleted; - foreach my $record_number ( map { $_->{biblio_auth_number} } - grep { !$found{ $_->{biblio_auth_number} }++ } - @$entries ) { - print "." if ( $verbose_logging ); - print "\r$i" unless ($i++ %100 or !$verbose_logging); - my ($marc) = get_corrected_marc_record($record_type, $record_number); - if (defined $marc) { + foreach my $record_number ( + map { $_->{biblio_auth_number} } + grep { !$found{ $_->{biblio_auth_number} }++ } @$entries + ) + { + print "." if ($verbose_logging); + print "\r$i" unless ( $i++ % 100 or !$verbose_logging ); + my ($marc) = get_corrected_marc_record( $record_type, $record_number ); + if ( defined $marc ) { eval { - my $rec = $marc->as_xml_record(C4::Context->preference('marcflavour')); + my $rec = $marc->as_xml_record( C4::Context->preference('marcflavour') ); $rec =~ s!<\?xml version="1.0" encoding="UTF-8"\?>\n!!; print {$fh} $rec; $num_exported++; }; if ($@) { - warn "Error exporting record $record_number ($record_type) XML"; + warn "Error exporting record $record_number ($record_type) XML"; } } } - print "\nRecords exported: $num_exported " . pretty_time() . "\n" if ( $verbose_logging ); + print "\nRecords exported: $num_exported " . pretty_time() . "\n" if ($verbose_logging); print {$fh} $marcxml_close; @@ -610,7 +641,7 @@ sub export_marc_records_from_list { sub generate_deleted_marc_records { - my ($record_type, $entries, $directory) = @_; + my ( $record_type, $entries, $directory ) = @_; my $records_deleted = {}; open my $fh, '>:encoding(UTF-8)', "$directory/exported_records" or die $!; @@ -618,28 +649,29 @@ sub generate_deleted_marc_records { print {$fh} $marcxml_open; my $i = 0; - foreach my $record_number (map { $_->{biblio_auth_number} } @$entries ) { - print "\r$i" unless ($i++ %100 or !$verbose_logging); - print "." if ( $verbose_logging ); + foreach my $record_number ( map { $_->{biblio_auth_number} } @$entries ) { + print "\r$i" unless ( $i++ % 100 or !$verbose_logging ); + print "." if ($verbose_logging); my $marc = MARC::Record->new(); - if ($record_type eq 'biblio') { - fix_biblio_ids($marc, $record_number, $record_number); + if ( $record_type eq 'biblio' ) { + fix_biblio_ids( $marc, $record_number, $record_number ); } else { - fix_authority_id($marc, $record_number); + fix_authority_id( $marc, $record_number ); } - if (C4::Context->preference("marcflavour") eq "UNIMARC") { + if ( C4::Context->preference("marcflavour") eq "UNIMARC" ) { fix_unimarc_100($marc); } - my $rec = $marc->as_xml_record(C4::Context->preference('marcflavour')); + my $rec = $marc->as_xml_record( C4::Context->preference('marcflavour') ); + # Remove the record's XML header $rec =~ s!<\?xml version="1.0" encoding="UTF-8"\?>\n!!; print {$fh} $rec; $records_deleted->{$record_number} = 1; } - print "\nRecords exported: $i " . pretty_time() . "\n" if ( $verbose_logging ); + print "\nRecords exported: $i " . pretty_time() . "\n" if ($verbose_logging); print {$fh} $marcxml_close; @@ -656,8 +688,7 @@ sub get_corrected_marc_record { fix_leader($marc); if ( $record_type eq 'authority' ) { fix_authority_id( $marc, $record_number ); - } - elsif ( $record_type eq 'biblio' ) { + } elsif ( $record_type eq 'biblio' ) { my @filters; my @other_headings; @@ -691,15 +722,16 @@ sub get_corrected_marc_record { } sub get_raw_marc_record { - my ($record_type, $record_number) = @_; + my ( $record_type, $record_number ) = @_; my $marc; - if ($record_type eq 'biblio') { + if ( $record_type eq 'biblio' ) { eval { my $biblio = Koha::Biblios->find($record_number); $marc = $biblio->metadata_record( { embed_items => 1 } ); }; - if ($@ || !$marc) { + if ( $@ || !$marc ) { + # here we do warn since catching an exception # means that the bib was found but failed # to be parsed @@ -717,6 +749,7 @@ sub get_raw_marc_record { } sub fix_leader { + # FIXME - this routine is suspect # It blanks the Leader/00-05 and Leader/12-16 to # force them to be recalculated correct when @@ -727,23 +760,23 @@ sub fix_leader { my $marc = shift; my $leader = $marc->leader; - substr($leader, 0, 5) = ' '; - substr($leader, 10, 7) = '22 '; - $marc->leader(substr($leader, 0, 24)); + substr( $leader, 0, 5 ) = ' '; + substr( $leader, 10, 7 ) = '22 '; + $marc->leader( substr( $leader, 0, 24 ) ); } sub fix_biblio_ids { + # FIXME - it is essential to ensure that the biblionumber is present, # otherwise, Zebra will choke on the record. However, this # logic belongs in the relevant C4::Biblio APIs. - my $marc = shift; + my $marc = shift; my $biblionumber = shift; my $biblioitemnumber; if (@_) { $biblioitemnumber = shift; } else { - my $sth = $dbh->prepare( - "SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=?"); + my $sth = $dbh->prepare("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber=?"); $sth->execute($biblionumber); ($biblioitemnumber) = $sth->fetchrow_array; $sth->finish; @@ -761,57 +794,58 @@ sub fix_biblio_ids { # On the other hand, this better for now than what rebuild_zebra.pl used to # do, which was duplicate the code for inserting the biblionumber # and biblioitemnumber - C4::Biblio::_koha_marc_update_bib_ids($marc, '', $biblionumber, $biblioitemnumber); + C4::Biblio::_koha_marc_update_bib_ids( $marc, '', $biblionumber, $biblioitemnumber ); return 1; } sub fix_authority_id { + # FIXME - as with fix_biblio_ids, the authid must be present # for Zebra's sake. However, this really belongs # in C4::AuthoritiesMarc. - my ($marc, $authid) = @_; - unless ($marc->field('001') and $marc->field('001')->data() eq $authid){ - $marc->delete_field($marc->field('001')); - $marc->insert_fields_ordered(MARC::Field->new('001',$authid)); + my ( $marc, $authid ) = @_; + unless ( $marc->field('001') and $marc->field('001')->data() eq $authid ) { + $marc->delete_field( $marc->field('001') ); + $marc->insert_fields_ordered( MARC::Field->new( '001', $authid ) ); } } sub fix_unimarc_100 { + # FIXME - again, if this is necessary, it belongs in C4::AuthoritiesMarc. my $marc = shift; my $string; - my $length_100a = length($marc->subfield( 100, "a" )); - if ( $length_100a and $length_100a == 36 ) { + my $length_100a = length( $marc->subfield( 100, "a" ) ); + if ( $length_100a and $length_100a == 36 ) { $string = $marc->subfield( 100, "a" ); my $f100 = $marc->field(100); $marc->delete_field($f100); - } - else { + } else { $string = POSIX::strftime( "%Y%m%d", localtime ); $string =~ s/\-//g; $string = sprintf( "%-*s", 35, $string ); } substr( $string, 22, 6, "frey50" ); - $length_100a = length($marc->subfield( 100, "a" )); + $length_100a = length( $marc->subfield( 100, "a" ) ); unless ( $length_100a and $length_100a == 36 ) { - $marc->delete_field($marc->field(100)); - $marc->insert_grouped_field(MARC::Field->new( 100, "", "", "a" => $string )); + $marc->delete_field( $marc->field(100) ); + $marc->insert_grouped_field( MARC::Field->new( 100, "", "", "a" => $string ) ); } } sub do_indexing { - my ($record_type, $op, $record_dir, $reset_index, $noshadow, $record_format, $zebraidx_log_opt) = @_; + my ( $record_type, $op, $record_dir, $reset_index, $noshadow, $record_format, $zebraidx_log_opt ) = @_; - my $zebra_server = ($record_type eq 'biblio') ? 'biblioserver' : 'authorityserver'; - my $zebra_db_name = ($record_type eq 'biblio') ? 'biblios' : 'authorities'; + my $zebra_server = ( $record_type eq 'biblio' ) ? 'biblioserver' : 'authorityserver'; + my $zebra_db_name = ( $record_type eq 'biblio' ) ? 'biblios' : 'authorities'; my $zebra_config = C4::Context->zebraconfig($zebra_server)->{'config'}; my $zebra_db_dir = C4::Context->zebraconfig($zebra_server)->{'directory'}; $noshadow //= ''; - if ($noshadow or $reset_index) { + if ( $noshadow or $reset_index ) { $noshadow = '-n'; } @@ -821,39 +855,42 @@ sub do_indexing { } sub _flock { + # test if flock is present; if so, use it; if not, return true # op refers to the official flock operations including LOCK_EX, # LOCK_UN, etc. # combining LOCK_EX with LOCK_NB returns immediately - my ($fh, $op)= @_; - if( !defined($use_flock) ) { + my ( $fh, $op ) = @_; + if ( !defined($use_flock) ) { + #check if flock is present; if not, you will have a fatal error - my $lock_acquired = eval { flock($fh, $op) }; + my $lock_acquired = eval { flock( $fh, $op ) }; + # assuming that $fh and $op are fine(..), an undef $lock_acquired # means no flock $use_flock = defined($lock_acquired) ? 1 : 0; print "Warning: flock could not be used!\n" if $verbose_logging && !$use_flock; - return 1 if !$use_flock; + return 1 if !$use_flock; return $lock_acquired; } else { return 1 if !$use_flock; - return flock($fh, $op); + return flock( $fh, $op ); } } -sub _create_lockfile { #returns undef on failure - my $dir= shift; - unless (-d $dir) { - eval { mkpath($dir, 0, oct(755)) }; +sub _create_lockfile { #returns undef on failure + my $dir = shift; + unless ( -d $dir ) { + eval { mkpath( $dir, 0, oct(755) ) }; return if $@; } - return if !open my $fh, q{>}, $dir.'/'.LOCK_FILENAME; - return ( $fh, $dir.'/'.LOCK_FILENAME ); + return if !open my $fh, q{>}, $dir . '/' . LOCK_FILENAME; + return ( $fh, $dir . '/' . LOCK_FILENAME ); } sub pretty_time { use integer; - my $now = time; + my $now = time; my $elapsed = $now - $start_time; local $_ = $elapsed; my ( $h, $m, $s ); @@ -863,8 +900,8 @@ sub pretty_time { $_ /= 60; $h = $_ % 24; - my $now_pretty = POSIX::strftime("%H:%M:%S",localtime($now)); - my $elapsed_pretty = sprintf "[%02d:%02d:%02d]",$h,$m,$s; + my $now_pretty = POSIX::strftime( "%H:%M:%S", localtime($now) ); + my $elapsed_pretty = sprintf "[%02d:%02d:%02d]", $h, $m, $s; return "$now_pretty $elapsed_pretty"; } diff --git a/misc/migration_tools/remove_unused_authorities.pl b/misc/migration_tools/remove_unused_authorities.pl index 4283cea2f2..19cbc5c4a4 100755 --- a/misc/migration_tools/remove_unused_authorities.pl +++ b/misc/migration_tools/remove_unused_authorities.pl @@ -25,14 +25,14 @@ use Modern::Perl; use Koha::Script; use C4::Context; use C4::AuthoritiesMarc qw( DelAuthority ); -use C4::Log qw( cronlogaction ); -use Getopt::Long qw( GetOptions ); +use C4::Log qw( cronlogaction ); +use Getopt::Long qw( GetOptions ); use Koha::SearchEngine::Search; my @authtypes; -my ($confirm, $test, $want_help); -my $command_line_options = join(" ", @ARGV); +my ( $confirm, $test, $want_help ); +my $command_line_options = join( " ", @ARGV ); GetOptions( 'aut|authtypecode:s' => \@authtypes, 'c|confirm' => \$confirm, @@ -40,7 +40,7 @@ GetOptions( 'h|help' => \$want_help, ); -if ( $want_help || !($test || $confirm) ) { +if ( $want_help || !( $test || $confirm ) ) { print_usage(); exit 0; } @@ -51,56 +51,59 @@ if ($test) { print "*** Testing only, authorities will not be deleted. ***\n"; } if (@authtypes) { - print "Restricted to authority type(s) : ".join(',', @authtypes).".\n"; + print "Restricted to authority type(s) : " . join( ',', @authtypes ) . ".\n"; } my $searcher = Koha::SearchEngine::Search->new( { index => 'biblios' } ); my $checksearch; if ( C4::Context->preference("SearchEngine") eq 'Zebra' ) { + # Check server state - my $errZebraConnection = C4::Context->Zconn("biblioserver",0)->errcode(); + my $errZebraConnection = C4::Context->Zconn( "biblioserver", 0 )->errcode(); if ( $errZebraConnection == 10000 ) { die "Zebra server seems not to be available. This script needs Zebra runs."; - } elsif ( $errZebraConnection ) { + } elsif ($errZebraConnection) { die "Error from Zebra: $errZebraConnection"; } $checksearch = q{an,alwaysmatches=''}; -} -else { +} else { $checksearch = q{an:*}; } + # Check search on authority number as at least one result -my ($err,$res,$nb) = $searcher->simple_search_compat($checksearch,0,10); -unless ($nb > 0) { +my ( $err, $res, $nb ) = $searcher->simple_search_compat( $checksearch, 0, 10 ); +unless ( $nb > 0 ) { die "Searching authority number in biblio records seems not to be available : $checksearch"; } -my $dbh=C4::Context->dbh; +my $dbh = C4::Context->dbh; + # prepare the request to retrieve all authorities of the requested types my $rqsql = q{ SELECT authid,authtypecode FROM auth_header }; -$rqsql .= q{ WHERE authtypecode IN (}.join(',',map{ '?' }@authtypes).')' if @authtypes; +$rqsql .= q{ WHERE authtypecode IN (} . join( ',', map { '?' } @authtypes ) . ')' if @authtypes; my $rqselect = $dbh->prepare($rqsql); -$|=1; +$| = 1; $rqselect->execute(@authtypes); -my $counter=0; -my $totdeleted=0; -my $totundeleted=0; -while (my $data=$rqselect->fetchrow_hashref){ +my $counter = 0; +my $totdeleted = 0; +my $totundeleted = 0; +while ( my $data = $rqselect->fetchrow_hashref ) { $counter++; - print 'authid='.$data->{'authid'}; - print ' type='.$data->{'authtypecode'}; - my $bibliosearch = 'an:'.$data->{'authid'}; + print 'authid=' . $data->{'authid'}; + print ' type=' . $data->{'authtypecode'}; + my $bibliosearch = 'an:' . $data->{'authid'}; + # search for biblios mapped - my ($err,$res,$used) = $searcher->simple_search_compat($bibliosearch,0,10); - if (defined $err) { + my ( $err, $res, $used ) = $searcher->simple_search_compat( $bibliosearch, 0, 10 ); + if ( defined $err ) { print "\n"; warn "Error: $err on search for biblios $bibliosearch\n"; next; } - unless ($used > 0){ + unless ( $used > 0 ) { unless ($test) { - DelAuthority({ authid => $data->{'authid'}, skip_merge => 1 }); + DelAuthority( { authid => $data->{'authid'}, skip_merge => 1 } ); print " : deleted"; } else { print " : can be deleted"; diff --git a/misc/migration_tools/switch_marc21_series_info.pl b/misc/migration_tools/switch_marc21_series_info.pl index 654b0f7d30..cba1fe8441 100755 --- a/misc/migration_tools/switch_marc21_series_info.pl +++ b/misc/migration_tools/switch_marc21_series_info.pl @@ -39,14 +39,14 @@ my $result = GetOptions( 'f' => \$update_frameworks, 'h|help' => \$show_help, 'v' => \$verbose, - ); +); # warn and exit if we're running UNIMARC -if (C4::Context->preference('MARCFLAVOUR') eq 'UNIMARC') { +if ( C4::Context->preference('MARCFLAVOUR') eq 'UNIMARC' ) { print "This script is useless when you're running UNIMARC\n"; exit 0; } -if ( ! $result || $show_help ) { +if ( !$result || $show_help ) { print_usage(); exit 0; } @@ -85,19 +85,18 @@ my $bibs_sth = $dbh->prepare( | ); -unless ( $commit ) { +unless ($commit) { print_usage(); } print "Examining MARC records...\n"; $count_sth->execute( C4::Context->preference('marcflavour') ); -my ( $num_records ) = $count_sth->fetchrow; +my ($num_records) = $count_sth->fetchrow; -unless ( $commit ) { - if ( $num_records ) { +unless ($commit) { + if ($num_records) { print "This action would change $num_records MARC records\n"; - } - else { + } else { print "There appears to be no series information to change\n"; } print "Please run this again with the '-c' option to change the records\n"; @@ -126,46 +125,46 @@ my %fields = ( '6' => 'link', '8' => 'ln', }, - ); +); $bibs_sth->execute( C4::Context->preference('marcflavour') ); -while ( my ( $biblionumber ) = $bibs_sth->fetchrow ) { - my $framework = GetFrameworkCode( $biblionumber ) || ''; - my ( @newfields ); +while ( my ($biblionumber) = $bibs_sth->fetchrow ) { + my $framework = GetFrameworkCode($biblionumber) || ''; + my (@newfields); # Get biblio marc my $biblio = Koha::Biblios->find($biblionumber); - $biblio &&= $biblio->metadata->record; + $biblio &&= $biblio->metadata->record; - foreach my $field ( $biblio->field( '440' ) ) { + foreach my $field ( $biblio->field('440') ) { my @newsubfields; my @linksubfields; my $has_links = '0'; foreach my $subfield ( sort keys %{ $fields{'440'} } ) { - my @values = $field->subfield( $subfield ); + my @values = $field->subfield($subfield); if ( $add_links && @values ) { if ( $subfield eq 'w' || $subfield eq '0' ) { $has_links = '1'; } - foreach my $v ( @values ) { + foreach my $v (@values) { push @linksubfields, ( $subfield, $v ); } } if ( $subfield eq 'a' ) { - my @numbers = $field->subfield( 'n' ); - my @parts = $field->subfield( 'p' ); - my $i = 0; + my @numbers = $field->subfield('n'); + my @parts = $field->subfield('p'); + my $i = 0; while ( $i < @numbers || $i < @parts ) { - my @strings = grep {$_} ( $values[$i], $numbers[$i], $parts[$i] ); + my @strings = grep { $_ } ( $values[$i], $numbers[$i], $parts[$i] ); $values[$i] = join ' ', @strings; $i++; } } if ( $fields{'490'}{$subfield} ) { - foreach my $v ( @values ) { + foreach my $v (@values) { push @newsubfields, ( $subfield, $v ); } } @@ -176,77 +175,80 @@ while ( my ( $biblionumber ) = $bibs_sth->fetchrow ) { '830', $field->indicator(1), $field->indicator(2), @linksubfields - ); + ); push @newfields, $link_field; } - if ( @newsubfields ) { - my $new_field = MARC::Field->new( '490', $has_links, '', - @newsubfields ); + if (@newsubfields) { + my $new_field = MARC::Field->new( + '490', $has_links, '', + @newsubfields + ); push @newfields, $new_field; } - $biblio->delete_fields( $field ); + $biblio->delete_fields($field); } - foreach my $field ( $biblio->field( '490' ) ) { + foreach my $field ( $biblio->field('490') ) { my @newsubfields; foreach my $subfield ( sort keys %{ $fields{'490'} } ) { - my @values = $field->subfield( $subfield ); + my @values = $field->subfield($subfield); if ( $fields{'440'}{$subfield} ) { - foreach my $v ( @values ) { + foreach my $v (@values) { push @newsubfields, ( $subfield, $v ); } } } - if ( @newsubfields ) { - my $new_field = MARC::Field->new( '440', '', '', - @newsubfields ); + if (@newsubfields) { + my $new_field = MARC::Field->new( + '440', '', '', + @newsubfields + ); push @newfields, $new_field; } - $biblio->delete_fields( $field ); + $biblio->delete_fields($field); } - $biblio->insert_fields_ordered( @newfields ); + $biblio->insert_fields_ordered(@newfields); - if ( $verbose ) { + if ($verbose) { print "Changing MARC for biblio number $biblionumber.\n"; - } - else { + } else { print "."; } ModBiblioMarc( $biblio, $biblionumber ); } print "\n"; -if ( $update_frameworks ) { +if ($update_frameworks) { print "Updating Koha to MARC mappings for seriestitle and volume\n"; # set new mappings for koha fields $dbh->do( -"UPDATE marc_subfield_structure SET kohafield='biblio.seriestitle' + "UPDATE marc_subfield_structure SET kohafield='biblio.seriestitle' WHERE tagfield='490' AND tagsubfield='a'" ); $dbh->do( -"UPDATE marc_subfield_structure SET kohafield='biblioitems.volume' + "UPDATE marc_subfield_structure SET kohafield='biblioitems.volume' WHERE tagfield='490' AND tagsubfield='v'" ); # empty old koha fields $dbh->do( -"UPDATE marc_subfield_structure SET kohafield='' + "UPDATE marc_subfield_structure SET kohafield='' WHERE kohafield='biblio.seriestitle' AND tagfield='440' AND tagsubfield='a'" - ); + ); $dbh->do( -"UPDATE marc_subfield_structure SET kohafield='' + "UPDATE marc_subfield_structure SET kohafield='' WHERE kohafield='biblioitems.volume' AND tagfield='440' AND tagsubfield='v'" - ); + ); $dbh->do( -"UPDATE marc_subfield_structure SET kohafield='' + "UPDATE marc_subfield_structure SET kohafield='' WHERE kohafield='biblioitems.number' AND tagfield='440' AND tagsubfield='n'" - ); + ); } sub print_usage { diff --git a/misc/migration_tools/upgradeitems.pl b/misc/migration_tools/upgradeitems.pl index 40844bf560..c044614a06 100755 --- a/misc/migration_tools/upgradeitems.pl +++ b/misc/migration_tools/upgradeitems.pl @@ -1,6 +1,7 @@ #!/usr/bin/perl use strict; + #use warnings; FIXME - Bug 2505 use Koha::Script; @@ -8,46 +9,46 @@ use C4::Context; use C4::Items qw( ModItemFromMarc ); use Koha::Biblios; -my $dbh=C4::Context->dbh; +my $dbh = C4::Context->dbh; -if (C4::Context->preference("marcflavour") ne "UNIMARC") { +if ( C4::Context->preference("marcflavour") ne "UNIMARC" ) { print "this script is for UNIMARC only\n"; exit; } -my $rqbiblios=$dbh->prepare("SELECT biblionumber from biblioitems"); -my $rqitemnumber=$dbh->prepare("SELECT itemnumber, biblionumber from items where itemnumber = ? and biblionumber = ?"); +my $rqbiblios = $dbh->prepare("SELECT biblionumber from biblioitems"); +my $rqitemnumber = + $dbh->prepare("SELECT itemnumber, biblionumber from items where itemnumber = ? and biblionumber = ?"); $rqbiblios->execute; -$|=1; -while (my ($biblionumber)= $rqbiblios->fetchrow_array){ +$| = 1; +while ( my ($biblionumber) = $rqbiblios->fetchrow_array ) { my $biblio = Koha::Biblios->find($biblionumber); my $record = $biblio->metadata->record; - foreach my $itemfield ($record->field('995')){ - my $marcitem=MARC::Record->new(); + foreach my $itemfield ( $record->field('995') ) { + my $marcitem = MARC::Record->new(); $marcitem->encoding('UTF-8'); - $marcitem->append_fields($itemfield); + $marcitem->append_fields($itemfield); - - my $itemnum; - my @itemnumbers = $itemfield->subfield('9'); - foreach my $itemnumber ( @itemnumbers ){ - $rqitemnumber->execute($itemnumber, $biblionumber); - if( my $row = $rqitemnumber->fetchrow_hashref ){ - $itemnum = $row->{itemnumber}; - } + my $itemnum; + my @itemnumbers = $itemfield->subfield('9'); + foreach my $itemnumber (@itemnumbers) { + $rqitemnumber->execute( $itemnumber, $biblionumber ); + if ( my $row = $rqitemnumber->fetchrow_hashref ) { + $itemnum = $row->{itemnumber}; + } } - eval{ - if($itemnum){ - ModItemFromMarc($marcitem,$biblionumber,$itemnum) - }else{ - die("$biblionumber"); - } + eval { + if ($itemnum) { + ModItemFromMarc( $marcitem, $biblionumber, $itemnum ); + } else { + die("$biblionumber"); + } }; print "\r$biblionumber"; - if ($@){ + if ($@) { warn "Problem with : $biblionumber : $@"; warn $record->as_formatted; - } - } + } + } } diff --git a/misc/mod_zebraqueue.pl b/misc/mod_zebraqueue.pl index ab1aa7b2b3..3b8a3073f2 100755 --- a/misc/mod_zebraqueue.pl +++ b/misc/mod_zebraqueue.pl @@ -21,7 +21,7 @@ use Modern::Perl; use Getopt::Long qw( GetOptions ); -use Pod::Usage qw( pod2usage ); +use Pod::Usage qw( pod2usage ); use Koha::Script; use C4::Biblio qw( ModZebra ); diff --git a/misc/process_ill_updates.pl b/misc/process_ill_updates.pl index a773eb8480..302d0951a2 100755 --- a/misc/process_ill_updates.pl +++ b/misc/process_ill_updates.pl @@ -25,15 +25,15 @@ use Koha::Script; use Koha::ILL::Requests; # Command line option values -my $get_help = 0; -my $statuses = ""; -my $status_alias = ""; -my $status_to = ""; +my $get_help = 0; +my $statuses = ""; +my $status_alias = ""; +my $status_to = ""; my $status_alias_to = ""; -my $backend = ""; -my $dry_run = 0; -my $delay = 0; -my $debug = 0; +my $backend = ""; +my $dry_run = 0; +my $delay = 0; +my $debug = 0; my $options = GetOptions( 'h|help' => \$get_help, @@ -52,17 +52,17 @@ if ($get_help) { exit 1; } -if (!$backend) { +if ( !$backend ) { print "No backend specified\n"; exit 0; } # First check we can proceed -my $cfg = Koha::ILL::Request::Config->new; -my $backends = $cfg->available_backends; -my $has_branch = $cfg->has_branch; +my $cfg = Koha::ILL::Request::Config->new; +my $backends = $cfg->available_backends; +my $has_branch = $cfg->has_branch; my $backends_available = ( scalar @{$backends} > 0 ); -if (!$has_branch || $backends_available == 0) { +if ( !$has_branch || $backends_available == 0 ) { print "Unable to proceed:\n"; print "Branch configured: $has_branch\n"; print "Backends available: $backends_available\n"; @@ -70,24 +70,22 @@ if (!$has_branch || $backends_available == 0) { } # Get all required requests -my @statuses_arr = split(/:/, $statuses); -my @status_alias_arr = split(/:/, $status_alias); +my @statuses_arr = split( /:/, $statuses ); +my @status_alias_arr = split( /:/, $status_alias ); -my $where = { - backend => $backend -}; +my $where = { backend => $backend }; -if (scalar @statuses_arr > 0) { - my @or = grep(!/null/, @statuses_arr); - if (scalar @or < scalar @statuses_arr) { +if ( scalar @statuses_arr > 0 ) { + my @or = grep( !/null/, @statuses_arr ); + if ( scalar @or < scalar @statuses_arr ) { push @or, undef; } $where->{status} = \@or; } -if (scalar @status_alias_arr > 0) { - my @or = grep(!/null/, @status_alias_arr); - if (scalar @or < scalar @status_alias_arr) { +if ( scalar @status_alias_arr > 0 ) { + my @or = grep( !/null/, @status_alias_arr ); + if ( scalar @or < scalar @status_alias_arr ) { push @or, undef; } $where->{status_alias} = \@or; @@ -98,7 +96,7 @@ debug_msg($where); my $requests = Koha::ILL::Requests->search($where); -debug_msg("Processing " . $requests->count . " requests"); +debug_msg( "Processing " . $requests->count . " requests" ); # Create an options hashref to pass to processors my $options_to_pass = { @@ -112,9 +110,10 @@ my $options_to_pass = { # The progress log my $output = []; -while (my $request = $requests->next) { - debug_msg("- Request ID " . $request->illrequest_id); +while ( my $request = $requests->next ) { + debug_msg( "- Request ID " . $request->illrequest_id ); my $update = $request->backend_get_update($options_to_pass); + # The log for this request my $update_log = { request_id => $request->illrequest_id, @@ -122,6 +121,7 @@ while (my $request = $requests->next) { processors_run => [] }; if ($update) { + # Currently we make an assumption, this may need revisiting # if we need to extend the functionality: # @@ -135,9 +135,11 @@ while (my $request = $requests->next) { # # Attach any request processors $request->attach_processors($update); + # Attach any processors from this request's backend $request->_backend->attach_processors($update); my $processor_results = $update->run_processors($options_to_pass); + # Update our progress log $update_log->{processors_run} = $processor_results; } @@ -147,35 +149,35 @@ while (my $request = $requests->next) { print_summary($output); sub print_summary { - my ( $log ) = @_; + my ($log) = @_; - my $timestamp = POSIX::strftime("%d/%m/%Y %H:%M:%S\n", localtime); + my $timestamp = POSIX::strftime( "%d/%m/%Y %H:%M:%S\n", localtime ); print "Run details:\n"; - foreach my $entry(@{$log}) { - my @processors_run = @{$entry->{processors_run}}; + foreach my $entry ( @{$log} ) { + my @processors_run = @{ $entry->{processors_run} }; print "Request ID: " . $entry->{request_id} . "\n"; print " Processing by: " . $entry->{processed_by} . "\n"; print " Number of processors run: " . scalar @processors_run . "\n"; - if (scalar @processors_run > 0) { + if ( scalar @processors_run > 0 ) { print " Processor details:\n"; - foreach my $processor(@processors_run) { + foreach my $processor (@processors_run) { print " Processor name: " . $processor->{name} . "\n"; - print " Success messages: " . join(", ", @{$processor->{result}->{success}}) . "\n"; - print " Error messages: " . join(", ", @{$processor->{result}->{error}}) . "\n"; + print " Success messages: " . join( ", ", @{ $processor->{result}->{success} } ) . "\n"; + print " Error messages: " . join( ", ", @{ $processor->{result}->{error} } ) . "\n"; } } } - print "Job completed at $timestamp\n====================================\n\n" + print "Job completed at $timestamp\n====================================\n\n"; } sub debug_msg { - my ( $msg ) = @_; + my ($msg) = @_; - if (!$debug) { + if ( !$debug ) { return; } - if (ref $msg eq 'HASH') { + if ( ref $msg eq 'HASH' ) { use Data::Dumper; $msg = Dumper $msg; } diff --git a/misc/recreateIssueStatistics.pl b/misc/recreateIssueStatistics.pl index 8032019440..ce49d26181 100755 --- a/misc/recreateIssueStatistics.pl +++ b/misc/recreateIssueStatistics.pl @@ -17,7 +17,6 @@ # You should have received a copy of the GNU General Public License # along with Koha; if not, see . - # Re-create statistics from issues and old_issues tables use strict; @@ -31,143 +30,163 @@ use Koha::Items; my $dbh = C4::Context->dbh; # Options -my $issues = 0; +my $issues = 0; my $returns = 0; -my $help = 0; +my $help = 0; -GetOptions ('issues' => \$issues, 'returns' => \$returns, 'help|?|h' => \$help); +GetOptions( 'issues' => \$issues, 'returns' => \$returns, 'help|?|h' => \$help ); # Show usage -if ($help == 1) { - print ("Usage : perl $0 [--issues] [--returns]\n\n"); - print (" issues: process only issues\n"); - print (" returns: process only returns\n"); - exit 0; +if ( $help == 1 ) { + print("Usage : perl $0 [--issues] [--returns]\n\n"); + print(" issues: process only issues\n"); + print(" returns: process only returns\n"); + exit 0; } -if ($issues == 0 && $returns == 0) { - $issues = 1; +if ( $issues == 0 && $returns == 0 ) { + $issues = 1; $returns = 1; } # Counters -my $count_issues = 0; +my $count_issues = 0; my $count_renewals = 0; -my $count_returns = 0; +my $count_returns = 0; # Issues and renewals can be found in both issues and old_issues tables -if ($issues == 1) { - foreach my $table ('issues', 'old_issues') { - # Getting issues - print "looking for missing issues from $table\n"; - my $query = "SELECT borrowernumber, branchcode, itemnumber, issuedate, renewals_count, lastreneweddate from $table where itemnumber is not null"; - my $sth = $dbh->prepare($query); - $sth->execute; - # Looking for missing issues - while (my $hashref = $sth->fetchrow_hashref) { - my $ctnquery = "SELECT count(*) as cnt FROM statistics WHERE borrowernumber = ? AND itemnumber = ? AND DATE(datetime) = ? AND type = 'issue'"; - my $substh = $dbh->prepare($ctnquery); - $substh->execute($hashref->{'borrowernumber'}, $hashref->{'itemnumber'}, $hashref->{'issuedate'}); - my $count = $substh->fetchrow_hashref->{'cnt'}; - if ($count == 0) { - # Inserting missing issue - my $insert = "INSERT INTO statistics (datetime, branch, value, type, other, itemnumber, itemtype, borrowernumber) +if ( $issues == 1 ) { + foreach my $table ( 'issues', 'old_issues' ) { + + # Getting issues + print "looking for missing issues from $table\n"; + my $query = + "SELECT borrowernumber, branchcode, itemnumber, issuedate, renewals_count, lastreneweddate from $table where itemnumber is not null"; + my $sth = $dbh->prepare($query); + $sth->execute; + + # Looking for missing issues + while ( my $hashref = $sth->fetchrow_hashref ) { + my $ctnquery = + "SELECT count(*) as cnt FROM statistics WHERE borrowernumber = ? AND itemnumber = ? AND DATE(datetime) = ? AND type = 'issue'"; + my $substh = $dbh->prepare($ctnquery); + $substh->execute( $hashref->{'borrowernumber'}, $hashref->{'itemnumber'}, $hashref->{'issuedate'} ); + my $count = $substh->fetchrow_hashref->{'cnt'}; + if ( $count == 0 ) { + + # Inserting missing issue + my $insert = + "INSERT INTO statistics (datetime, branch, value, type, other, itemnumber, itemtype, borrowernumber) VALUES(?, ?, ?, ?, ?, ?, ?, ?)"; - $substh = $dbh->prepare($insert); - my $item = Koha::Items->find($hashref->{'itemnumber'}); - my $itemtype = $item->effective_itemtype; + $substh = $dbh->prepare($insert); + my $item = Koha::Items->find( $hashref->{'itemnumber'} ); + my $itemtype = $item->effective_itemtype; - $substh->execute( - $hashref->{'issuedate'}, - $hashref->{'branchcode'}, - 0, - 'issue', - '', - $hashref->{'itemnumber'}, - $itemtype, - $hashref->{'borrowernumber'} - ); - print "date: $hashref->{'issuedate'} branchcode: $hashref->{'branchcode'} type: issue itemnumber: $hashref->{'itemnumber'} itype: $itemtype borrowernumber: $hashref->{'borrowernumber'}\n"; - $count_issues++; - } + $substh->execute( + $hashref->{'issuedate'}, + $hashref->{'branchcode'}, + 0, + 'issue', + '', + $hashref->{'itemnumber'}, + $itemtype, + $hashref->{'borrowernumber'} + ); + print + "date: $hashref->{'issuedate'} branchcode: $hashref->{'branchcode'} type: issue itemnumber: $hashref->{'itemnumber'} itype: $itemtype borrowernumber: $hashref->{'borrowernumber'}\n"; + $count_issues++; + } - # Looking for missing renewals - if ($hashref->{'renewals_count'} && $hashref->{'renewals_count'} > 0 ) { - # This is the not-so accurate part : - # We assume that there are missing renewals, based on the last renewal date - # Maybe should this be deactivated by default ? - my $ctnquery = "SELECT count(*) as cnt FROM statistics WHERE borrowernumber = ? AND itemnumber = ? AND DATE(datetime) = ? AND type = 'renew'"; - my $substh = $dbh->prepare($ctnquery); - $substh->execute($hashref->{'borrowernumber'}, $hashref->{'itemnumber'}, $hashref->{'lastreneweddate'}); + # Looking for missing renewals + if ( $hashref->{'renewals_count'} && $hashref->{'renewals_count'} > 0 ) { - my $missingrenewalscount = $hashref->{'renewals_count'} - $substh->fetchrow_hashref->{'cnt'}; - print "We assume $missingrenewalscount renewals are missing. Creating them\n" if ($missingrenewalscount > 0); - for (my $i = 0; $i < $missingrenewalscount; $i++) { + # This is the not-so accurate part : + # We assume that there are missing renewals, based on the last renewal date + # Maybe should this be deactivated by default ? + my $ctnquery = + "SELECT count(*) as cnt FROM statistics WHERE borrowernumber = ? AND itemnumber = ? AND DATE(datetime) = ? AND type = 'renew'"; + my $substh = $dbh->prepare($ctnquery); + $substh->execute( + $hashref->{'borrowernumber'}, $hashref->{'itemnumber'}, + $hashref->{'lastreneweddate'} + ); - # Inserting missing renewals - my $insert = "INSERT INTO statistics (datetime, branch, value, type, other, itemnumber, itemtype, borrowernumber) + my $missingrenewalscount = $hashref->{'renewals_count'} - $substh->fetchrow_hashref->{'cnt'}; + print "We assume $missingrenewalscount renewals are missing. Creating them\n" + if ( $missingrenewalscount > 0 ); + for ( my $i = 0 ; $i < $missingrenewalscount ; $i++ ) { + + # Inserting missing renewals + my $insert = + "INSERT INTO statistics (datetime, branch, value, type, other, itemnumber, itemtype, borrowernumber) VALUES(?, ?, ?, ?, ?, ?, ?, ?)"; - $substh = $dbh->prepare($insert); - my $item = Koha::Items->find($hashref->{'itemnumber'}); - my $itemtype = $item->effective_itemtype; + $substh = $dbh->prepare($insert); + my $item = Koha::Items->find( $hashref->{'itemnumber'} ); + my $itemtype = $item->effective_itemtype; - $substh->execute( - $hashref->{'lastreneweddate'}, - $hashref->{'branchcode'}, - 0, - 'renew', - '', - $hashref->{'itemnumber'}, - $itemtype, - $hashref->{'borrowernumber'} - ); - print "date: $hashref->{'lastreneweddate'} branchcode: $hashref->{'branchcode'} type: renew itemnumber: $hashref->{'itemnumber'} itype: $itemtype borrowernumber: $hashref->{'borrowernumber'}\n"; - $count_renewals++; + $substh->execute( + $hashref->{'lastreneweddate'}, + $hashref->{'branchcode'}, + 0, + 'renew', + '', + $hashref->{'itemnumber'}, + $itemtype, + $hashref->{'borrowernumber'} + ); + print + "date: $hashref->{'lastreneweddate'} branchcode: $hashref->{'branchcode'} type: renew itemnumber: $hashref->{'itemnumber'} itype: $itemtype borrowernumber: $hashref->{'borrowernumber'}\n"; + $count_renewals++; - } + } - } - } + } + } } } # Getting returns -if ($returns == 1) { +if ( $returns == 1 ) { print "looking for missing returns from old_issues\n"; my $query = "SELECT * from old_issues where itemnumber is not null"; - my $sth = $dbh->prepare($query); + my $sth = $dbh->prepare($query); $sth->execute; - # Looking for missing returns - while (my $hashref = $sth->fetchrow_hashref) { - my $ctnquery = "SELECT count(*) as cnt FROM statistics WHERE borrowernumber = ? AND itemnumber = ? AND DATE(datetime) = ? AND type = 'return'"; - my $substh = $dbh->prepare($ctnquery); - $substh->execute($hashref->{'borrowernumber'}, $hashref->{'itemnumber'}, $hashref->{'returndate'}); - my $count = $substh->fetchrow_hashref->{'cnt'}; - if ($count == 0) { - # Inserting missing issue - my $insert = "INSERT INTO statistics (datetime, branch, value, type, other, itemnumber, itemtype, borrowernumber) - VALUES(?, ?, ?, ?, ?, ?, ?, ?)"; - $substh = $dbh->prepare($insert); - my $item = Koha::Items->find($hashref->{'itemnumber'}); - my $itemtype = $item->effective_itemtype; - $substh->execute( - $hashref->{'returndate'}, - $hashref->{'branchcode'}, - 0, - 'return', - '', - $hashref->{'itemnumber'}, - $itemtype, - $hashref->{'borrowernumber'} - ); - print "date: $hashref->{'returndate'} branchcode: $hashref->{'branchcode'} type: return itemnumber: $hashref->{'itemnumber'} itype: $itemtype borrowernumber: $hashref->{'borrowernumber'}\n"; - $count_returns++; - } + # Looking for missing returns + while ( my $hashref = $sth->fetchrow_hashref ) { + my $ctnquery = + "SELECT count(*) as cnt FROM statistics WHERE borrowernumber = ? AND itemnumber = ? AND DATE(datetime) = ? AND type = 'return'"; + my $substh = $dbh->prepare($ctnquery); + $substh->execute( $hashref->{'borrowernumber'}, $hashref->{'itemnumber'}, $hashref->{'returndate'} ); + my $count = $substh->fetchrow_hashref->{'cnt'}; + if ( $count == 0 ) { + + # Inserting missing issue + my $insert = + "INSERT INTO statistics (datetime, branch, value, type, other, itemnumber, itemtype, borrowernumber) + VALUES(?, ?, ?, ?, ?, ?, ?, ?)"; + $substh = $dbh->prepare($insert); + my $item = Koha::Items->find( $hashref->{'itemnumber'} ); + my $itemtype = $item->effective_itemtype; + + $substh->execute( + $hashref->{'returndate'}, + $hashref->{'branchcode'}, + 0, + 'return', + '', + $hashref->{'itemnumber'}, + $itemtype, + $hashref->{'borrowernumber'} + ); + print + "date: $hashref->{'returndate'} branchcode: $hashref->{'branchcode'} type: return itemnumber: $hashref->{'itemnumber'} itype: $itemtype borrowernumber: $hashref->{'borrowernumber'}\n"; + $count_returns++; + } } } -print "Missing issues added: $count_issues\n" if $issues; +print "Missing issues added: $count_issues\n" if $issues; print "Missing renewals added: $count_renewals\n" if $issues; -print "Missing returns added: $count_returns\n" if $returns; +print "Missing returns added: $count_returns\n" if $returns; diff --git a/misc/sax_parser_print.pl b/misc/sax_parser_print.pl index 5d3a1acf9e..b00263fe5f 100755 --- a/misc/sax_parser_print.pl +++ b/misc/sax_parser_print.pl @@ -10,6 +10,9 @@ print "Koha wants something like: XML::LibXML::SAX::Parser=HASH(0x81fe220) You have: $parser\n"; -print "Looks " . - ($parser =~ /^XML::LibXML::SAX::Parser=HASH/ ? - "good.\n" : "bad, check the Koha wiki documentation at https://wiki.koha-community.org.\n"); +print "Looks " + . ( + $parser =~ /^XML::LibXML::SAX::Parser=HASH/ + ? "good.\n" + : "bad, check the Koha wiki documentation at https://wiki.koha-community.org.\n" + ); diff --git a/misc/sax_parser_test.pl b/misc/sax_parser_test.pl index e18cacdbb0..a946045ad1 100755 --- a/misc/sax_parser_test.pl +++ b/misc/sax_parser_test.pl @@ -6,23 +6,24 @@ use warnings; use XML::SAX; use Encode qw( encode_utf8 ); -my $parser = XML::SAX::ParserFactory->parser( -Handler => MySAXHandler->new -); +my $parser = XML::SAX::ParserFactory->parser( Handler => MySAXHandler->new ); binmode STDOUT, ':encoding(UTF-8)'; print "\x{65}\x{301}\n"; -$parser->parse_string(encode_utf8("\x{65}\x{301}")); +$parser->parse_string( encode_utf8("\x{65}\x{301}") ); $parser->parse_string("\xEF\xBB\xBF\x{65}\x{301}"); package MySAXHandler; use base qw(XML::SAX::Base); + sub start_document { - my ($self, $doc) = @_; - # process document start event + my ( $self, $doc ) = @_; + + # process document start event } sub start_element { - my ($self, $el) = @_; - # process element start event + my ( $self, $el ) = @_; + + # process element start event } diff --git a/misc/search_tools/export_elasticsearch_mappings.pl b/misc/search_tools/export_elasticsearch_mappings.pl index 1fdc4512ac..445858f73c 100755 --- a/misc/search_tools/export_elasticsearch_mappings.pl +++ b/misc/search_tools/export_elasticsearch_mappings.pl @@ -62,14 +62,14 @@ use Koha::SearchEngine::Elasticsearch; use YAML::XS; use Getopt::Long qw( GetOptions ); -use Pod::Usage qw( pod2usage ); +use Pod::Usage qw( pod2usage ); my $type = ''; my $man; GetOptions( - 't|type=s' => \$type, - 'man' => \$man, + 't|type=s' => \$type, + 'man' => \$man, ); pod2usage( -exitstatus => 0, -verbose => 2 ) if $man; @@ -79,7 +79,7 @@ if ( $type && $type !~ /^(marc21|unimarc)$/ ) { pod2usage(1); } -my $mappings = Koha::SearchEngine::Elasticsearch::raw_elasticsearch_mappings( $type ); +my $mappings = Koha::SearchEngine::Elasticsearch::raw_elasticsearch_mappings($type); binmode STDOUT, ":encoding(UTF-8)"; print Encode::decode_utf8( YAML::XS::Dump($mappings) ); diff --git a/misc/search_tools/rebuild_elasticsearch.pl b/misc/search_tools/rebuild_elasticsearch.pl index 58fa298830..43dc6452e2 100755 --- a/misc/search_tools/rebuild_elasticsearch.pl +++ b/misc/search_tools/rebuild_elasticsearch.pl @@ -127,16 +127,16 @@ use Koha::SearchEngine::Elasticsearch::Indexer; use MARC::Field; use Modern::Perl; use Pod::Usage qw( pod2usage ); -use Try::Tiny qw( catch try ); +use Try::Tiny qw( catch try ); my $verbose = 0; -my $commit = 5000; -my ($delete, $reset, $help, $man, $processes); -my ($index_biblios, $index_authorities); -my (@biblionumbers,@authids,$where); +my $commit = 5000; +my ( $delete, $reset, $help, $man, $processes ); +my ( $index_biblios, $index_authorities ); +my ( @biblionumbers, @authids, $where ); my $desc; -$|=1; # flushes output +$| = 1; # flushes output GetOptions( 'c|commit=i' => \$commit, @@ -155,51 +155,54 @@ GetOptions( ); # Default is to do both -unless ($index_authorities || $index_biblios) { +unless ( $index_authorities || $index_biblios ) { $index_authorities = $index_biblios = 1; } -if ($processes && ( @biblionumbers || @authids) ) { +if ( $processes && ( @biblionumbers || @authids ) ) { die "Argument p|processes cannot be combined with bn|bnumber or ai|authid"; } -pod2usage(1) if $help; +pod2usage(1) if $help; pod2usage( -exitstatus => 0, -verbose => 2 ) if $man; _sanity_check(); -if ($reset){ +if ($reset) { Koha::SearchEngine::Elasticsearch->reset_elasticsearch_mappings; $delete = 1; } -_verify_index_state($Koha::SearchEngine::Elasticsearch::BIBLIOS_INDEX, $delete) if ($index_biblios); -_verify_index_state($Koha::SearchEngine::Elasticsearch::AUTHORITIES_INDEX, $delete) if ($index_authorities); +_verify_index_state( $Koha::SearchEngine::Elasticsearch::BIBLIOS_INDEX, $delete ) if ($index_biblios); +_verify_index_state( $Koha::SearchEngine::Elasticsearch::AUTHORITIES_INDEX, $delete ) if ($index_authorities); my $slice_index = 0; my $slice_count = ( $processes //= 1 ); my %iterator_options; -if ($slice_count > 1) { +if ( $slice_count > 1 ) { + # Fire up child processes for processing slices from 2 on. This main process will handle slice 1. $slice_index = 0; - for (my $proc = 1; $proc < $slice_count; $proc++) { + for ( my $proc = 1 ; $proc < $slice_count ; $proc++ ) { my $pid = fork(); die "Failed to fork a child process\n" unless defined $pid; - if ($pid == 0) { + if ( $pid == 0 ) { + # Child process, give it a slice to process $slice_index = $proc; last; } } + # Fudge the commit count a bit to spread out the Elasticsearch commits $commit *= 1 + 0.10 * $slice_index; - $commit = int( $commit ); - _log(1, "Processing slice @{[$slice_index + 1]} of $slice_count\n"); + $commit = int($commit); + _log( 1, "Processing slice @{[$slice_index + 1]} of $slice_count\n" ); $iterator_options{slice} = { index => $slice_index, count => $slice_count }; } -if( $desc ){ +if ($desc) { $iterator_options{desc} = 1; } @@ -209,12 +212,12 @@ if ($where) { my $next; if ($index_biblios) { - _log(1, "Indexing biblios\n"); + _log( 1, "Indexing biblios\n" ); if (@biblionumbers) { $next = sub { my $r = shift @biblionumbers; return () unless defined $r; - return ($r, Koha::BiblioUtils->get_from_biblionumber($r, item_data => 1 )); + return ( $r, Koha::BiblioUtils->get_from_biblionumber( $r, item_data => 1 ) ); }; } else { my $records = Koha::BiblioUtils->get_all_biblios_iterator(%iterator_options); @@ -222,16 +225,16 @@ if ($index_biblios) { $records->next(); } } - _do_reindex($next, $Koha::SearchEngine::Elasticsearch::BIBLIOS_INDEX); + _do_reindex( $next, $Koha::SearchEngine::Elasticsearch::BIBLIOS_INDEX ); } if ($index_authorities) { - _log(1, "Indexing authorities\n"); + _log( 1, "Indexing authorities\n" ); if (@authids) { $next = sub { my $r = shift @authids; return () unless defined $r; my $a = Koha::MetadataRecord::Authority->get_from_authid($r); - return ($r, $a); + return ( $r, $a ); }; } else { my $records = Koha::MetadataRecord::Authority->get_all_authorities_iterator(%iterator_options); @@ -239,12 +242,13 @@ if ($index_authorities) { $records->next(); } } - _do_reindex($next, $Koha::SearchEngine::Elasticsearch::AUTHORITIES_INDEX); + _do_reindex( $next, $Koha::SearchEngine::Elasticsearch::AUTHORITIES_INDEX ); } -if ($slice_index == 0) { +if ( $slice_index == 0 ) { + # Main process, wait for children - for (my $proc = 1; $proc < $processes; $proc++) { + for ( my $proc = 1 ; $proc < $processes ; $proc++ ) { wait(); } } @@ -262,21 +266,22 @@ Checks the index state and recreates it if requested. sub _verify_index_state { my ( $index_name, $recreate ) = @_; - _log(1, "Checking state of $index_name index\n"); + _log( 1, "Checking state of $index_name index\n" ); my $indexer = Koha::SearchEngine::Elasticsearch::Indexer->new( { index => $index_name } ); if ($recreate) { - _log(1, "Dropping and recreating $index_name index\n"); + _log( 1, "Dropping and recreating $index_name index\n" ); $indexer->drop_index() if $indexer->index_exists(); $indexer->create_index(); - } - elsif (!$indexer->index_exists) { + } elsif ( !$indexer->index_exists ) { + # Create index if does not exist $indexer->create_index(); - } elsif ($indexer->is_index_status_ok) { + } elsif ( $indexer->is_index_status_ok ) { + # Update mapping unless index is some kind of problematic state $indexer->update_mappings(); - } elsif ($indexer->is_index_status_recreate_required) { + } elsif ( $indexer->is_index_status_recreate_required ) { warn qq/Index "$index_name" has status "recreate required", suggesting it should be recreated/; } } @@ -303,7 +308,7 @@ sub _do_reindex { my $record = $record->record; $count++; if ( $verbose == 1 ) { - _log( 1, "$count records processed\n" ) if ( $count % 1000 == 0); + _log( 1, "$count records processed\n" ) if ( $count % 1000 == 0 ); } else { _log( 2, "$id\n" ); } @@ -313,13 +318,13 @@ sub _do_reindex { if ( !( --$commit_count ) ) { _log( 1, "Committing $commit records...\n" ); my $response; - try{ + try { $response = $indexer->update_index( \@id_buffer, \@commit_buffer ); _handle_response($response); _log( 1, "Commit complete\n" ); } catch { - _log(1,"Elasticsearch exception thrown: ".$_->type."\n"); - _log(2,"Details: ".$_->details."\n"); + _log( 1, "Elasticsearch exception thrown: " . $_->type . "\n" ); + _log( 2, "Details: " . $_->details . "\n" ); }; $commit_count = $commit; @id_buffer = (); @@ -343,6 +348,7 @@ Checks some basic stuff to ensure that it's sane before we start. =cut sub _sanity_check { + # Do we have an elasticsearch block defined? my $conf = C4::Context->config('elasticsearch'); die "No 'elasticsearch' block is defined in koha-conf.xml.\n" if ( !$conf ); @@ -356,14 +362,17 @@ Parse the return from update_index and display errors depending on verbosity of sub _handle_response { my ($response) = @_; - if( $response->{errors} eq 'true' ){ + if ( $response->{errors} eq 'true' ) { _log( 1, "There were errors during indexing\n" ); - if ( $verbose > 1 ){ - foreach my $item (@{$response->{items}}){ + if ( $verbose > 1 ) { + foreach my $item ( @{ $response->{items} } ) { next unless defined $item->{index}->{error}; - print "Record #" . $item->{index}->{_id} . " " . - $item->{index}->{error}->{reason} . " (" . $item->{index}->{error}->{type} . ") : " . - $item->{index}->{error}->{caused_by}->{type} . " (" . $item->{index}->{error}->{caused_by}->{reason} . ")\n"; + print "Record #" + . $item->{index}->{_id} . " " + . $item->{index}->{error}->{reason} . " (" + . $item->{index}->{error}->{type} . ") : " + . $item->{index}->{error}->{caused_by}->{type} . " (" + . $item->{index}->{error}->{caused_by}->{reason} . ")\n"; } } } @@ -381,7 +390,7 @@ include a trailing newline automatically. =cut sub _log { - my ($level, $msg) = @_; + my ( $level, $msg ) = @_; - print "[$$] $msg" if ($verbose >= $level); + print "[$$] $msg" if ( $verbose >= $level ); } diff --git a/misc/sip_cli_emulator.pl b/misc/sip_cli_emulator.pl index 95ee8f5f56..38b6f7c96b 100755 --- a/misc/sip_cli_emulator.pl +++ b/misc/sip_cli_emulator.pl @@ -121,7 +121,7 @@ $| = 1; print "Attempting socket connection to $host:$port..."; my $socket = IO::Socket::INET->new("$host:$port") - or die "failed! : $!\n"; + or die "failed! : $!\n"; say "connected!"; my $handlers = { @@ -137,8 +137,7 @@ my $handlers = { sc_status_request => { name => 'SC Status', subroutine => \&build_sc_status_command_message, - parameters => { - }, + parameters => {}, }, patron_status_request => { name => 'Patron Status Request', @@ -268,9 +267,9 @@ my $handlers = { transaction_id => $transaction_id, }, optional => [ - 'fee_type', # has default - 'payment_type', # has default - 'currency_type', #has default + 'fee_type', # has default + 'payment_type', # has default + 'currency_type', #has default 'terminal_password', 'patron_password', 'fee_identifier', @@ -281,18 +280,18 @@ my $handlers = { name => 'Hold', subroutine => \&build_hold_command_message, parameters => { - hold_mode => $hold_mode eq '-' ? '-' : '+', - transaction_date => $transaction_date, - expiration_date => undef, - pickup_location => $pickup_location, - hold_type => undef, - institution_id => $location_code, - patron_identifier => $patron_identifier, - patron_password => $patron_password, - item_identifier => $item_identifier, - title_identifier => undef, - terminal_password => $terminal_password, - fee_acknowledged => $fee_acknowledged, + hold_mode => $hold_mode eq '-' ? '-' : '+', + transaction_date => $transaction_date, + expiration_date => undef, + pickup_location => $pickup_location, + hold_type => undef, + institution_id => $location_code, + patron_identifier => $patron_identifier, + patron_password => $patron_password, + item_identifier => $item_identifier, + title_identifier => undef, + terminal_password => $terminal_password, + fee_acknowledged => $fee_acknowledged, }, optional => [ 'expiration_date', @@ -316,8 +315,7 @@ if ( $data =~ '^941' ) { ## we are logged in my $data = run_command_message($m); } -} -else { +} else { say "Login Failed!"; } @@ -371,10 +369,10 @@ sub build_login_command_message { my $location_code = $params->{location_code}; return - LOGIN . "00" - . build_field( FID_LOGIN_UID, $login_user_id ) - . build_field( FID_LOGIN_PWD, $login_password ) - . build_field( FID_LOCATION_CODE, $location_code ); + LOGIN . "00" + . build_field( FID_LOGIN_UID, $login_user_id ) + . build_field( FID_LOGIN_PWD, $login_password ) + . build_field( FID_LOCATION_CODE, $location_code ); } sub build_sc_status_command_message { @@ -393,13 +391,13 @@ sub build_patron_status_request_command_message { my $patron_password = $params->{patron_password}; return - PATRON_STATUS_REQ - . LANGUAGE - . $transaction_date - . build_field( FID_INST_ID, $institution_id ) - . build_field( FID_PATRON_ID, $patron_identifier ) - . build_field( FID_TERMINAL_PWD, $terminal_password ) - . build_field( FID_PATRON_PWD, $patron_password ); + PATRON_STATUS_REQ + . LANGUAGE + . $transaction_date + . build_field( FID_INST_ID, $institution_id ) + . build_field( FID_PATRON_ID, $patron_identifier ) + . build_field( FID_TERMINAL_PWD, $terminal_password ) + . build_field( FID_PATRON_PWD, $patron_password ); } sub build_patron_information_command_message { @@ -414,21 +412,21 @@ sub build_patron_information_command_message { my $end_item = $params->{end_item}; my $summary = $params->{summary}; - $summary //= " "; + $summary //= " "; $start_item //= ""; - $end_item //= ""; + $end_item //= ""; return - PATRON_INFO - . LANGUAGE - . $transaction_date - . $summary - . build_field( FID_INST_ID, $institution_id ) - . build_field( FID_PATRON_ID, $patron_identifier ) - . build_field( FID_TERMINAL_PWD, $terminal_password ) - . build_field( FID_PATRON_PWD, $patron_password, { optional => 1 } ) - . build_field( FID_START_ITEM, $start_item, { optional => 1 } ) - . build_field( FID_END_ITEM, $end_item, { optional => 1 } ); + PATRON_INFO + . LANGUAGE + . $transaction_date + . $summary + . build_field( FID_INST_ID, $institution_id ) + . build_field( FID_PATRON_ID, $patron_identifier ) + . build_field( FID_TERMINAL_PWD, $terminal_password ) + . build_field( FID_PATRON_PWD, $patron_password, { optional => 1 } ) + . build_field( FID_START_ITEM, $start_item, { optional => 1 } ) + . build_field( FID_END_ITEM, $end_item, { optional => 1 } ); } sub build_item_information_command_message { @@ -440,19 +438,19 @@ sub build_item_information_command_message { my $terminal_password = $params->{terminal_password}; return - ITEM_INFORMATION - . LANGUAGE - . $transaction_date - . build_field( FID_INST_ID, $institution_id ) - . build_field( FID_ITEM_ID, $item_identifier ) - . build_field( FID_TERMINAL_PWD, $terminal_password ); + ITEM_INFORMATION + . LANGUAGE + . $transaction_date + . build_field( FID_INST_ID, $institution_id ) + . build_field( FID_ITEM_ID, $item_identifier ) + . build_field( FID_TERMINAL_PWD, $terminal_password ); } sub build_checkout_command_message { my ($params) = @_; my $SC_renewal_policy = $params->{SC_renewal_policy} || 'N'; - my $no_block = $params->{no_block} || 'N'; + my $no_block = $params->{no_block} || 'N'; my $transaction_date = $params->{transaction_date}; my $nb_due_date = $params->{nb_due_date}; my $institution_id = $params->{institution_id}; @@ -465,25 +463,25 @@ sub build_checkout_command_message { my $cancel = $params->{cancel} || 'N'; $SC_renewal_policy = $SC_renewal_policy eq 'Y' ? 'Y' : 'N'; - $no_block = $no_block eq 'Y' ? 'Y' : 'N'; - $cancel = $cancel eq 'Y' ? 'Y' : 'N'; + $no_block = $no_block eq 'Y' ? 'Y' : 'N'; + $cancel = $cancel eq 'Y' ? 'Y' : 'N'; $nb_due_date ||= $transaction_date; return - CHECKOUT - . $SC_renewal_policy - . $no_block - . $transaction_date - . $nb_due_date - . build_field( FID_INST_ID, $institution_id ) - . build_field( FID_PATRON_ID, $patron_identifier ) - . build_field( FID_ITEM_ID, $item_identifier ) - . build_field( FID_TERMINAL_PWD, $terminal_password ) - . build_field( FID_ITEM_PROPS, $item_properties, { optional => 1 } ) - . build_field( FID_PATRON_PWD, $patron_password, { optional => 1 } ) - . build_field( FID_FEE_ACK, $fee_acknowledged, { optional => 1 } ) - . build_field( FID_CANCEL, $cancel, { optional => 1 } ); + CHECKOUT + . $SC_renewal_policy + . $no_block + . $transaction_date + . $nb_due_date + . build_field( FID_INST_ID, $institution_id ) + . build_field( FID_PATRON_ID, $patron_identifier ) + . build_field( FID_ITEM_ID, $item_identifier ) + . build_field( FID_TERMINAL_PWD, $terminal_password ) + . build_field( FID_ITEM_PROPS, $item_properties, { optional => 1 } ) + . build_field( FID_PATRON_PWD, $patron_password, { optional => 1 } ) + . build_field( FID_FEE_ACK, $fee_acknowledged, { optional => 1 } ) + . build_field( FID_CANCEL, $cancel, { optional => 1 } ); } sub build_checkin_command_message { @@ -500,21 +498,21 @@ sub build_checkin_command_message { my $cancel = $params->{cancel} || 'N'; $no_block = $no_block eq 'Y' ? 'Y' : 'N'; - $cancel = $cancel eq 'Y' ? 'Y' : 'N'; + $cancel = $cancel eq 'Y' ? 'Y' : 'N'; $return_date ||= $transaction_date; return - CHECKIN - . $no_block - . $transaction_date - . $return_date - . build_field( FID_CURRENT_LOCN, $current_location ) - . build_field( FID_INST_ID, $institution_id ) - . build_field( FID_ITEM_ID, $item_identifier ) - . build_field( FID_TERMINAL_PWD, $terminal_password ) - . build_field( FID_ITEM_PROPS, $item_properties, { optional => 1 } ) - . build_field( FID_CANCEL, $cancel, { optional => 1 } ); + CHECKIN + . $no_block + . $transaction_date + . $return_date + . build_field( FID_CURRENT_LOCN, $current_location ) + . build_field( FID_INST_ID, $institution_id ) + . build_field( FID_ITEM_ID, $item_identifier ) + . build_field( FID_TERMINAL_PWD, $terminal_password ) + . build_field( FID_ITEM_PROPS, $item_properties, { optional => 1 } ) + . build_field( FID_CANCEL, $cancel, { optional => 1 } ); } sub build_hold_command_message { @@ -534,19 +532,19 @@ sub build_hold_command_message { my $fee_acknowledged = $params->{fee_acknowledged}; return - HOLD - . $hold_mode - . $transaction_date - . build_field( FID_EXPIRATION, $expiration_date, { optional => 1 } ) - . build_field( FID_PICKUP_LOCN, $pickup_location, { optional => 1 } ) - . build_field( FID_HOLD_TYPE, $hold_type, { optional => 1 } ) - . build_field( FID_INST_ID, $institution_id ) - . build_field( FID_PATRON_ID, $patron_identifier ) - . build_field( FID_PATRON_PWD, $patron_password, { optional => 1 } ) - . build_field( FID_ITEM_ID, $item_identifier, { optional => 1 } ) - . build_field( FID_TITLE_ID, $title_identifier, { optional => 1 } ) - . build_field( FID_TERMINAL_PWD, $terminal_password, { optional => 1 } ) - . build_field( FID_FEE_ACK, $fee_acknowledged, { optional => 1 } ); + HOLD + . $hold_mode + . $transaction_date + . build_field( FID_EXPIRATION, $expiration_date, { optional => 1 } ) + . build_field( FID_PICKUP_LOCN, $pickup_location, { optional => 1 } ) + . build_field( FID_HOLD_TYPE, $hold_type, { optional => 1 } ) + . build_field( FID_INST_ID, $institution_id ) + . build_field( FID_PATRON_ID, $patron_identifier ) + . build_field( FID_PATRON_PWD, $patron_password, { optional => 1 } ) + . build_field( FID_ITEM_ID, $item_identifier, { optional => 1 } ) + . build_field( FID_TITLE_ID, $title_identifier, { optional => 1 } ) + . build_field( FID_TERMINAL_PWD, $terminal_password, { optional => 1 } ) + . build_field( FID_FEE_ACK, $fee_acknowledged, { optional => 1 } ); } sub build_renew_command_message { @@ -566,32 +564,32 @@ sub build_renew_command_message { my $fee_acknowledged = $params->{fee_acknowledged}; $third_party_allowed = $third_party_allowed eq 'Y' ? 'Y' : 'N'; - $no_block = $no_block eq 'Y' ? 'Y' : 'N'; + $no_block = $no_block eq 'Y' ? 'Y' : 'N'; $nb_due_date ||= $transaction_date; return - RENEW - . $third_party_allowed - . $no_block - . $transaction_date - . $nb_due_date - . build_field( FID_INST_ID, $institution_id ) - . build_field( FID_PATRON_ID, $patron_identifier ) - . build_field( FID_PATRON_PWD, $patron_password, { optional => 1 } ) - . build_field( FID_ITEM_ID, $item_identifier ) - . build_field( FID_TITLE_ID, $title_identifier ) - . build_field( FID_TERMINAL_PWD, $terminal_password ) - . build_field( FID_ITEM_PROPS, $item_properties, { optional => 1 } ) - . build_field( FID_FEE_ACK, $fee_acknowledged, { optional => 1 } ); + RENEW + . $third_party_allowed + . $no_block + . $transaction_date + . $nb_due_date + . build_field( FID_INST_ID, $institution_id ) + . build_field( FID_PATRON_ID, $patron_identifier ) + . build_field( FID_PATRON_PWD, $patron_password, { optional => 1 } ) + . build_field( FID_ITEM_ID, $item_identifier ) + . build_field( FID_TITLE_ID, $title_identifier ) + . build_field( FID_TERMINAL_PWD, $terminal_password ) + . build_field( FID_ITEM_PROPS, $item_properties, { optional => 1 } ) + . build_field( FID_FEE_ACK, $fee_acknowledged, { optional => 1 } ); } sub build_fee_paid_command_message { my ($params) = @_; my $transaction_date = $params->{transaction_date}; - my $fee_type = $params->{fee_type} || '01'; - my $payment_type = $params->{payment_type} || '00'; + my $fee_type = $params->{fee_type} || '01'; + my $payment_type = $params->{payment_type} || '00'; my $currency_type = $params->{currency_type} || 'USD'; my $fee_amount = $params->{fee_amount}; my $institution_id = $params->{location_code}; @@ -602,18 +600,18 @@ sub build_fee_paid_command_message { my $transaction_id = $params->{transaction_id}; return - FEE_PAID - . $transaction_date - . $fee_type - . $payment_type - . $currency_type - . build_field( FID_FEE_AMT, $fee_amount ) - . build_field( FID_INST_ID, $institution_id ) - . build_field( FID_PATRON_ID, $patron_identifier ) - . build_field( FID_TERMINAL_PWD, $terminal_password, { optional => 1 } ) - . build_field( FID_PATRON_PWD, $patron_password, { optional => 1 } ) - . build_field( FID_FEE_ID, $fee_identifier, { optional => 1 } ) - . build_field( FID_TRANSACTION_ID, $transaction_id, { optional => 1 } ); + FEE_PAID + . $transaction_date + . $fee_type + . $payment_type + . $currency_type + . build_field( FID_FEE_AMT, $fee_amount ) + . build_field( FID_INST_ID, $institution_id ) + . build_field( FID_PATRON_ID, $patron_identifier ) + . build_field( FID_TERMINAL_PWD, $terminal_password, { optional => 1 } ) + . build_field( FID_PATRON_PWD, $patron_password, { optional => 1 } ) + . build_field( FID_FEE_ID, $fee_identifier, { optional => 1 } ) + . build_field( FID_TRANSACTION_ID, $transaction_id, { optional => 1 } ); } sub build_field { @@ -623,7 +621,7 @@ sub build_field { return q{} if ( $params->{optional} && !$value ); - return $field_identifier . (($value) ? $value : '') . '|'; + return $field_identifier . ( ($value) ? $value : '' ) . '|'; } sub help { diff --git a/misc/stage_file.pl b/misc/stage_file.pl index 90d2b6ebc4..8d82000399 100755 --- a/misc/stage_file.pl +++ b/misc/stage_file.pl @@ -23,27 +23,28 @@ use Modern::Perl; use Koha::Script; use C4::Context; -use C4::ImportBatch qw( RecordsFromISO2709File RecordsFromMARCXMLFile BatchStageMarcRecords SetImportBatchMatcher SetImportBatchOverlayAction SetImportBatchNoMatchAction SetImportBatchItemAction BatchFindDuplicates ); +use C4::ImportBatch + qw( RecordsFromISO2709File RecordsFromMARCXMLFile BatchStageMarcRecords SetImportBatchMatcher SetImportBatchOverlayAction SetImportBatchNoMatchAction SetImportBatchItemAction BatchFindDuplicates ); use C4::Matcher; use C4::MarcModificationTemplates qw( GetModificationTemplates ); -use Getopt::Long qw( GetOptions ); +use Getopt::Long qw( GetOptions ); $| = 1; # command-line parameters -my $record_type = "biblio"; -my $encoding = "UTF-8"; -my $authorities = 0; -my $match = 0; -my $add_items = 0; -my $input_file = ""; +my $record_type = "biblio"; +my $encoding = "UTF-8"; +my $authorities = 0; +my $match = 0; +my $add_items = 0; +my $input_file = ""; my $batch_comment = ""; -my $want_help = 0; +my $want_help = 0; my $no_replace; my $format = 'ISO2709'; my $no_create; -my $item_action = 'always_add'; -my $marc_mod_template = ''; +my $item_action = 'always_add'; +my $marc_mod_template = ''; my $marc_mod_template_id = undef; my $result = GetOptions( @@ -61,29 +62,29 @@ my $result = GetOptions( 'h|help' => \$want_help ); -if($marc_mod_template ne '') { - my @templates = GetModificationTemplates(); - foreach my $this_template (@templates) { - if($this_template->{'name'} eq $marc_mod_template) { - if(!defined $marc_mod_template_id) { - $marc_mod_template_id = $this_template->{'template_id'}; - } else { - print "WARNING: MARC modification template name " . - "'$marc_mod_template' matches multiple templates. " . - "Please fix this issue before proceeding.\n"; - exit 1; - } - } - } +if ( $marc_mod_template ne '' ) { + my @templates = GetModificationTemplates(); + foreach my $this_template (@templates) { + if ( $this_template->{'name'} eq $marc_mod_template ) { + if ( !defined $marc_mod_template_id ) { + $marc_mod_template_id = $this_template->{'template_id'}; + } else { + print "WARNING: MARC modification template name " + . "'$marc_mod_template' matches multiple templates. " + . "Please fix this issue before proceeding.\n"; + exit 1; + } + } + } - if(!defined $marc_mod_template_id ) { - die "Can't locate MARC modification template '$marc_mod_template'\n"; - } + if ( !defined $marc_mod_template_id ) { + die "Can't locate MARC modification template '$marc_mod_template'\n"; + } } $record_type = 'auth' if ($authorities); -if (not $result or $input_file eq "" or $want_help) { +if ( not $result or $input_file eq "" or $want_help ) { print_usage(); exit 0; } @@ -93,7 +94,7 @@ if ( $format !~ /^(MARCXML|ISO2709)$/i ) { exit 0; } -unless (-r $input_file) { +unless ( -r $input_file ) { die "$0: cannot open input file $input_file: $!\n"; } @@ -119,51 +120,55 @@ $dbh->commit(); exit 0; sub process_batch { - my ( $params ) = @_; #Possible params are: format input_file record_type match add_items batch_comment encoding no_replace no_create item_action - my $format = $params->{format} // ''; + my ($params) = @_ + ; #Possible params are: format input_file record_type match add_items batch_comment encoding no_replace no_create item_action + my $format = $params->{format} // ''; my $record_type = $params->{record_type} // 'biblio'; my ( $errors, $marc_records ); - if( $format eq 'ISO2709' ) { - ( $errors, $marc_records ) = C4::ImportBatch::RecordsFromISO2709File( - $params->{input_file}, $record_type, $params->{encoding} ); - } elsif( $format eq 'MARCXML' ) { - ( $errors, $marc_records ) = C4::ImportBatch::RecordsFromMARCXMLFile( - $params->{input_file}, $params->{encoding} ); + if ( $format eq 'ISO2709' ) { + ( $errors, $marc_records ) = + C4::ImportBatch::RecordsFromISO2709File( $params->{input_file}, $record_type, $params->{encoding} ); + } elsif ( $format eq 'MARCXML' ) { + ( $errors, $marc_records ) = + C4::ImportBatch::RecordsFromMARCXMLFile( $params->{input_file}, $params->{encoding} ); } - warn ( join ',', @$errors ) if @$errors; + warn( join ',', @$errors ) if @$errors; my $num_input_records = ($marc_records) ? scalar(@$marc_records) : 0; print "... staging MARC records -- please wait\n"; + #FIXME: We should really allow the use of marc modification frameworks and to_marc plugins here if possible - my ( $batch_id, $num_valid_records, $num_items, @import_errors ) = - BatchStageMarcRecords( + my ( $batch_id, $num_valid_records, $num_items, @import_errors ) = BatchStageMarcRecords( $record_type, $params->{encoding}, $marc_records, $params->{input_file}, $params->{'marc_mod_template_id'}, $params->{batch_comment}, '', $params->{add_items}, 0, 100, \&print_progress_and_commit - ); + ); print "... finished staging MARC records\n"; my $num_with_matches = 0; if ( $params->{match} ) { my $matcher = C4::Matcher->fetch( $params->{match} ); - if (defined $matcher) { + if ( defined $matcher ) { SetImportBatchMatcher( $batch_id, $params->{match} ); - } elsif ($record_type eq 'biblio') { + } elsif ( $record_type eq 'biblio' ) { $matcher = C4::Matcher->new($record_type); - $matcher->add_simple_matchpoint('isbn', 1000, '020', 'a', -1, 0, ''); - $matcher->add_simple_required_check('245', 'a', -1, 0, '', - '245', 'a', -1, 0, ''); + $matcher->add_simple_matchpoint( 'isbn', 1000, '020', 'a', -1, 0, '' ); + $matcher->add_simple_required_check( + '245', 'a', -1, 0, '', + '245', 'a', -1, 0, '' + ); } + # set default record overlay behavior SetImportBatchOverlayAction( $batch_id, $params->{no_replace} ? 'ignore' : 'replace' ); - SetImportBatchNoMatchAction( $batch_id, $params->{no_create} ? 'ignore' : 'create_new' ); + SetImportBatchNoMatchAction( $batch_id, $params->{no_create} ? 'ignore' : 'create_new' ); SetImportBatchItemAction( $batch_id, $params->{item_action} ); print "... looking for matches with records already in database\n"; - $num_with_matches = BatchFindDuplicates($batch_id, $matcher, 10, 100, \&print_progress_and_commit); + $num_with_matches = BatchFindDuplicates( $batch_id, $matcher, 10, 100, \&print_progress_and_commit ); print "... finished looking for matches\n"; } @@ -178,12 +183,12 @@ Number of input records: $num_input_records Number of valid records: $num_valid_records Number of invalid records: $num_invalid_records _SUMMARY_ - if( $params->{match} ) { + if ( $params->{match} ) { print "Number of records matched: $num_with_matches\n"; } else { print "Incoming records not matched against existing records (--match option not supplied)\n"; } - if ($record_type eq 'biblio') { + if ( $record_type eq 'biblio' ) { if ( $params->{add_items} ) { print "Number of items parsed: $num_items\n"; } else { diff --git a/misc/translator/LangInstaller.pm b/misc/translator/LangInstaller.pm index 15bee8355a..849c2869d7 100644 --- a/misc/translator/LangInstaller.pm +++ b/misc/translator/LangInstaller.pm @@ -20,41 +20,40 @@ package LangInstaller; use Modern::Perl; use C4::Context; + # WARNING: Any other tested YAML library fails to work properly in this # script content # FIXME Really? use YAML::XS; use Locale::PO; -use FindBin qw( $Bin ); +use FindBin qw( $Bin ); use File::Path qw( make_path ); use File::Copy; sub set_lang { - my ($self, $lang) = @_; + my ( $self, $lang ) = @_; - $self->{lang} = $lang; - $self->{po_path_lang} = C4::Context->config('intrahtdocs') . - "/prog/$lang/modules/admin/preferences"; + $self->{lang} = $lang; + $self->{po_path_lang} = C4::Context->config('intrahtdocs') . "/prog/$lang/modules/admin/preferences"; } sub new { - my ($class, $lang, $pref_only, $verbose) = @_; + my ( $class, $lang, $pref_only, $verbose ) = @_; - my $self = { }; + my $self = {}; - $self->{path_pref_en} = C4::Context->config('intrahtdocs') . - '/prog/en/modules/admin/preferences'; + $self->{path_pref_en} = C4::Context->config('intrahtdocs') . '/prog/en/modules/admin/preferences'; set_lang( $self, $lang ) if $lang; - $self->{pref_only} = $pref_only; - $self->{verbose} = $verbose; - $self->{process} = "$Bin/tmpl_process3.pl " . ($verbose ? '' : '-q'); - $self->{path_po} = "$Bin/po"; - $self->{po} = {}; - $self->{domain} = 'Koha'; - $self->{msgfmt} = `which msgfmt`; - $self->{po2json} = "$Bin/po2json"; - $self->{gzip} = `which gzip`; - $self->{gunzip} = `which gunzip`; + $self->{pref_only} = $pref_only; + $self->{verbose} = $verbose; + $self->{process} = "$Bin/tmpl_process3.pl " . ( $verbose ? '' : '-q' ); + $self->{path_po} = "$Bin/po"; + $self->{po} = {}; + $self->{domain} = 'Koha'; + $self->{msgfmt} = `which msgfmt`; + $self->{po2json} = "$Bin/po2json"; + $self->{gzip} = `which gzip`; + $self->{gunzip} = `which gunzip`; chomp $self->{msgfmt}; chomp $self->{gzip}; chomp $self->{gunzip}; @@ -67,7 +66,7 @@ sub new { # Get all available language codes opendir $fh, $self->{path_po}; - my @langs = map { ($_) =~ /(.*)-pref/ } + my @langs = map { ($_) =~ /(.*)-pref/ } grep { $_ =~ /.*-pref/ } readdir($fh); closedir $fh; $self->{langs} = \@langs; @@ -85,7 +84,7 @@ sub new { # OPAC themes opendir my $dh, C4::Context->config('opachtdocs'); for my $theme ( grep { not /^\.|lib|xslt/ } readdir($dh) ) { - push @{$self->{interface}}, { + push @{ $self->{interface} }, { name => "OPAC $theme", dir => "$opachtdocs/$theme", suffix => "-opac-$theme.po", @@ -94,13 +93,14 @@ sub new { # MARC flavours (hardcoded list) for ( "MARC21", "UNIMARC" ) { + # search for strings on staff & opac marc files my $dirs = C4::Context->config('intrahtdocs') . '/prog'; opendir $fh, C4::Context->config('opachtdocs'); for ( grep { not /^\.|\.\.|lib$|xslt/ } readdir($fh) ) { $dirs .= ' ' . "$opachtdocs/$_"; } - push @{$self->{interface}}, { + push @{ $self->{interface} }, { name => "$_", dir => $dirs, suffix => "-marc-$_.po", @@ -108,26 +108,32 @@ sub new { } # EN YAML installer files - push @{$self->{installer}}, { - name => "YAML installer files", - dirs => [ 'installer/data/mysql/en/mandatory', - 'installer/data/mysql/en/optional'], + push @{ $self->{installer} }, { + name => "YAML installer files", + dirs => [ + 'installer/data/mysql/en/mandatory', + 'installer/data/mysql/en/optional' + ], suffix => "-installer.po", }; # EN MARC21 YAML installer files - push @{$self->{installer}}, { - name => "MARC21 YAML installer files", - dirs => [ 'installer/data/mysql/en/marcflavour/marc21/mandatory', - 'installer/data/mysql/en/marcflavour/marc21/optional'], + push @{ $self->{installer} }, { + name => "MARC21 YAML installer files", + dirs => [ + 'installer/data/mysql/en/marcflavour/marc21/mandatory', + 'installer/data/mysql/en/marcflavour/marc21/optional' + ], suffix => "-installer-MARC21.po", }; # EN UNIMARC YAML installer files - push @{$self->{installer}}, { - name => "UNIMARC YAML installer files", - dirs => [ 'installer/data/mysql/en/marcflavour/unimarc/mandatory', - 'installer/data/mysql/en/marcflavour/unimarc/optional'], + push @{ $self->{installer} }, { + name => "UNIMARC YAML installer files", + dirs => [ + 'installer/data/mysql/en/marcflavour/unimarc/mandatory', + 'installer/data/mysql/en/marcflavour/unimarc/optional' + ], suffix => "-installer-UNIMARC.po", }; @@ -144,12 +150,12 @@ sub po_filename { } sub get_trans_text { - my ($self, $msgid, $default) = @_; + my ( $self, $msgid, $default ) = @_; - my $po = $self->{po}->{Locale::PO->quote($msgid)}; + my $po = $self->{po}->{ Locale::PO->quote($msgid) }; if ( $po and not defined( $po->fuzzy() ) ) { - my $msgstr = Locale::PO->dequote($po->msgstr); - if ($msgstr and length($msgstr) > 0) { + my $msgstr = Locale::PO->dequote( $po->msgstr ); + if ( $msgstr and length($msgstr) > 0 ) { return $msgstr; } } @@ -158,30 +164,31 @@ sub get_trans_text { } sub get_translated_tab_content { - my ($self, $file, $tab_content) = @_; + my ( $self, $file, $tab_content ) = @_; if ( ref($tab_content) eq 'ARRAY' ) { - return $self->get_translated_prefs($file, $tab_content); + return $self->get_translated_prefs( $file, $tab_content ); } my $translated_tab_content = { map { - my $section = $_; + my $section = $_; my $sysprefs = $tab_content->{$section}; - my $msgid = sprintf('%s %s', $file, $section); + my $msgid = sprintf( '%s %s', $file, $section ); - $self->get_trans_text($msgid, $section) => $self->get_translated_prefs($file, $sysprefs); + $self->get_trans_text( $msgid, $section ) => $self->get_translated_prefs( $file, $sysprefs ); } keys %$tab_content }; if ( keys %$translated_tab_content != keys %$tab_content ) { my %duplicates; - for my $section (keys %$tab_content) { - push @{$duplicates{$self->get_trans_text("$file $section", $section)}}, $section; + for my $section ( keys %$tab_content ) { + push @{ $duplicates{ $self->get_trans_text( "$file $section", $section ) } }, $section; } - for my $translation (keys %duplicates) { - if (@{$duplicates{$translation}} > 1) { - warn qq(In file "$file", "$translation" is a translation for sections ") . join('", "', @{$duplicates{$translation}}) . '"'; + for my $translation ( keys %duplicates ) { + if ( @{ $duplicates{$translation} } > 1 ) { + warn qq(In file "$file", "$translation" is a translation for sections ") + . join( '", "', @{ $duplicates{$translation} } ) . '"'; } } } @@ -190,18 +197,14 @@ sub get_translated_tab_content { } sub get_translated_prefs { - my ($self, $file, $sysprefs) = @_; + my ( $self, $file, $sysprefs ) = @_; my $translated_prefs = [ map { my ($pref_elt) = grep { ref($_) eq 'HASH' && exists $_->{pref} } @$_; my $pref_name = $pref_elt ? $pref_elt->{pref} : ''; - my $translated_syspref = [ - map { - $self->get_translated_pref($file, $pref_name, $_); - } @$_ - ]; + my $translated_syspref = [ map { $self->get_translated_pref( $file, $pref_name, $_ ); } @$_ ]; $translated_syspref; } @$sysprefs @@ -211,27 +214,27 @@ sub get_translated_prefs { } sub get_translated_pref { - my ($self, $file, $pref_name, $syspref) = @_; + my ( $self, $file, $pref_name, $syspref ) = @_; - unless (ref($syspref)) { + unless ( ref($syspref) ) { $syspref //= ''; - my $msgid = sprintf('%s#%s# %s', $file, $pref_name, $syspref); - return $self->get_trans_text($msgid, $syspref); + my $msgid = sprintf( '%s#%s# %s', $file, $pref_name, $syspref ); + return $self->get_trans_text( $msgid, $syspref ); } my $translated_pref = { map { - my $key = $_; + my $key = $_; my $value = $syspref->{$key}; my $translated_value = $value; - if (($key eq 'choices' || $key eq 'multiple' || $key eq 'multiple_sortable') && ref($value) eq 'HASH') { + if ( ( $key eq 'choices' || $key eq 'multiple' || $key eq 'multiple_sortable' ) && ref($value) eq 'HASH' ) { $translated_value = { map { - my $msgid = sprintf('%s#%s# %s', $file, $pref_name, $value->{$_}); - $_ => $self->get_trans_text($msgid, $value->{$_}) + my $msgid = sprintf( '%s#%s# %s', $file, $pref_name, $value->{$_} ); + $_ => $self->get_trans_text( $msgid, $value->{$_} ) } keys %$value - } + }; } $key => $translated_value @@ -249,46 +252,46 @@ sub install_prefs { exit; } - $self->{po} = Locale::PO->load_file_ashash($self->po_filename("-pref.po"), 'utf8'); + $self->{po} = Locale::PO->load_file_ashash( $self->po_filename("-pref.po"), 'utf8' ); - for my $file ( @{$self->{pref_files}} ) { + for my $file ( @{ $self->{pref_files} } ) { my $pref = YAML::XS::LoadFile( $self->{path_pref_en} . "/$file" ); my $translated_pref = { map { - my $tab = $_; + my $tab = $_; my $tab_content = $pref->{$tab}; - $self->get_trans_text($file, $tab) => $self->get_translated_tab_content($file, $tab_content); + $self->get_trans_text( $file, $tab ) => $self->get_translated_tab_content( $file, $tab_content ); } keys %$pref }; if ( keys %$translated_pref != keys %$pref ) { my %duplicates; - for my $tab (keys %$pref) { - push @{$duplicates{$self->get_trans_text($file, $tab)}}, $tab; + for my $tab ( keys %$pref ) { + push @{ $duplicates{ $self->get_trans_text( $file, $tab ) } }, $tab; } - for my $translation (keys %duplicates) { - if (@{$duplicates{$translation}} > 1) { - warn qq(In file "$file", "$translation" is a translation for tabs ") . join('", "', @{$duplicates{$translation}}) . '"'; + for my $translation ( keys %duplicates ) { + if ( @{ $duplicates{$translation} } > 1 ) { + warn qq(In file "$file", "$translation" is a translation for tabs ") + . join( '", "', @{ $duplicates{$translation} } ) . '"'; } } } my $file_trans = $self->{po_path_lang} . "/$file"; print "Write $file\n" if $self->{verbose}; - YAML::XS::DumpFile($file_trans, $translated_pref); + YAML::XS::DumpFile( $file_trans, $translated_pref ); } } - sub install_tmpl { - my ($self, $files) = @_; + my ( $self, $files ) = @_; say "Install templates" if $self->{verbose}; - for my $trans ( @{$self->{interface}} ) { - my @t_dirs = split(" ", $trans->{dir}); - for my $t_dir ( @t_dirs ) { - my @files = @$files; + for my $trans ( @{ $self->{interface} } ) { + my @t_dirs = split( " ", $trans->{dir} ); + for my $t_dir (@t_dirs) { + my @files = @$files; my @nomarc = (); print " Install templates '$trans->{name}'\n", @@ -301,19 +304,19 @@ sub install_tmpl { my $lang_dir = "$t_dir/$self->{lang}"; $lang_dir =~ s|/en/|/$self->{lang}/|; mkdir $lang_dir unless -d $lang_dir; - # if installing MARC po file, only touch corresponding files - my $marc = ( $trans->{name} =~ /MARC/ )?"-m \"$trans->{name}\"":""; # for MARC translations - # if not installing MARC po file, ignore all MARC files - @nomarc = ( 'marc21', 'unimarc' ) if ( $trans->{name} !~ /MARC/ ); # hardcoded MARC variants - system - "$self->{process} install " . - "-i $trans_dir " . - "-o $lang_dir ". - "-s $self->{path_po}/$self->{lang}$trans->{suffix} -r " . - "$marc " . - ( @files ? ' -f ' . join ' -f ', @files : '') . - ( @nomarc ? ' -n ' . join ' -n ', @nomarc : ''); + # if installing MARC po file, only touch corresponding files + my $marc = ( $trans->{name} =~ /MARC/ ) ? "-m \"$trans->{name}\"" : ""; # for MARC translations + # if not installing MARC po file, ignore all MARC files + @nomarc = ( 'marc21', 'unimarc' ) if ( $trans->{name} !~ /MARC/ ); # hardcoded MARC variants + + system "$self->{process} install " + . "-i $trans_dir " + . "-o $lang_dir " + . "-s $self->{path_po}/$self->{lang}$trans->{suffix} -r " + . "$marc " + . ( @files ? ' -f ' . join ' -f ', @files : '' ) + . ( @nomarc ? ' -n ' . join ' -n ', @nomarc : '' ); } } } @@ -326,52 +329,58 @@ sub translate_yaml { my $po_file = $self->po_filename( $target->{suffix} ); return $srcyml unless ( -e $po_file ); - my $po_ref = Locale::PO->load_file_ashash( $po_file, 'utf8' ); + my $po_ref = Locale::PO->load_file_ashash( $po_file, 'utf8' ); - my $dstyml = YAML::XS::LoadFile( $srcyml ); + my $dstyml = YAML::XS::LoadFile($srcyml); # translate fields in table rows my @tables = @{ $dstyml->{'tables'} }; - for my $table ( @tables ) { # each table - my $table_name = ( keys %$table )[0]; + for my $table (@tables) { # each table + my $table_name = ( keys %$table )[0]; my @translatable = @{ $table->{$table_name}->{translatable} }; - my @rows = @{ $table->{$table_name}->{rows} }; - my @multiline = @{ $table->{$table_name}->{'multiline'} }; # to check multiline values - for my $row ( @rows ) { # each row - for my $field ( @translatable ) { # each translatable field - if ( @multiline and grep { $_ eq $field } @multiline ) { # multiline fields, only notices ATM - foreach my $line ( @{$row->{$field}} ) { + my @rows = @{ $table->{$table_name}->{rows} }; + my @multiline = @{ $table->{$table_name}->{'multiline'} }; # to check multiline values + for my $row (@rows) { # each row + for my $field (@translatable) { # each translatable field + if ( @multiline and grep { $_ eq $field } @multiline ) { # multiline fields, only notices ATM + foreach my $line ( @{ $row->{$field} } ) { my @ttvar; - while ( $line =~ s/(<<.*?>>|\[\%.*?\%\]|<.*?>)/\%s/ ) { # put placeholders, save matches + while ( $line =~ s/(<<.*?>>|\[\%.*?\%\]|<.*?>)/\%s/ ) { # put placeholders, save matches my $var = $1; push @ttvar, $var; } - if ( $line =~ /^(\s|%s|-|[[:punct:]]|\(|\))*$/ ) { # ignore non strings - while ( @ttvar ) { # restore placeholders + if ( $line =~ /^(\s|%s|-|[[:punct:]]|\(|\))*$/ ) { # ignore non strings + while (@ttvar) { # restore placeholders my $var = shift @ttvar; $line =~ s/\%s/$var/; } next; } else { - my $po = $po_ref->{"\"$line\""}; # quoted key - if ( $po and not defined( $po->fuzzy() ) # not fuzzy - and length( $po->msgid() ) > 2 # not empty msgid - and length( $po->msgstr() ) > 2 ) { # not empty msgstr + my $po = $po_ref->{"\"$line\""}; # quoted key + if ( + $po and not defined( $po->fuzzy() ) # not fuzzy + and length( $po->msgid() ) > 2 # not empty msgid + and length( $po->msgstr() ) > 2 + ) + { # not empty msgstr $line = $po->dequote( $po->msgstr() ); } - while ( @ttvar ) { # restore placeholders + while (@ttvar) { # restore placeholders my $var = shift @ttvar; $line =~ s/\%s/$var/; } } } } else { - next unless defined $row->{$field}; # next if null value - my $po = $po_ref->{"\"$row->{$field}\""}; # quoted key - if ( $po and not defined( $po->fuzzy() ) # not fuzzy - and length( $po->msgid() ) > 2 # not empty msgid - and length( $po->msgstr() ) > 2 ) { # not empty msgstr + next unless defined $row->{$field}; # next if null value + my $po = $po_ref->{"\"$row->{$field}\""}; # quoted key + if ( + $po and not defined( $po->fuzzy() ) # not fuzzy + and length( $po->msgid() ) > 2 # not empty msgid + and length( $po->msgstr() ) > 2 + ) + { # not empty msgstr $row->{$field} = $po->dequote( $po->msgstr() ); } } @@ -382,9 +391,11 @@ sub translate_yaml { # translate descriptions for my $description ( @{ $dstyml->{'description'} } ) { my $po = $po_ref->{"\"$description\""}; - if ( $po and not defined( $po->fuzzy() ) - and length( $po->msgid() ) > 2 - and length( $po->msgstr() ) > 2 ) { + if ( $po + and not defined( $po->fuzzy() ) + and length( $po->msgid() ) > 2 + and length( $po->msgstr() ) > 2 ) + { $description = $po->dequote( $po->msgstr() ); } } @@ -398,7 +409,7 @@ sub install_installer { my $intradir = C4::Context->config('intranetdir'); my $db_scheme = C4::Context->config('db_scheme'); - my $langdir = "$intradir/installer/data/$db_scheme/$self->{lang}"; + my $langdir = "$intradir/installer/data/$db_scheme/$self->{lang}"; say "Install installer files\n" if $self->{verbose}; @@ -408,11 +419,11 @@ sub install_installer { ( my $tdir = "$dir" ) =~ s|/en/|/$self->{lang}/|; make_path("$intradir/$tdir"); - opendir( my $dh, "$intradir/$dir" ) or die ("Can't open $intradir/$dir"); - my @files = grep { ! /^\.+$/ } readdir($dh); + opendir( my $dh, "$intradir/$dir" ) or die("Can't open $intradir/$dir"); + my @files = grep { !/^\.+$/ } readdir($dh); close($dh); - for my $file ( @files ) { + for my $file (@files) { if ( $file =~ /yml$/ ) { my $translated_yaml = translate_yaml( $self, $target, "$intradir/$dir/$file" ); YAML::XS::DumpFile( "$intradir/$tdir/$file", $translated_yaml ); @@ -427,10 +438,10 @@ sub install_installer { sub locale_name { my $self = shift; - my ($language, $region, $country) = split /-/, $self->{lang}; + my ( $language, $region, $country ) = split /-/, $self->{lang}; $country //= $region; my $locale = $language; - if ($country && length($country) == 2) { + if ( $country && length($country) == 2 ) { $locale .= '_' . $country; } @@ -440,10 +451,10 @@ sub locale_name { sub install_messages { my ($self) = @_; - my $locale = $self->locale_name(); - my $modir = "$self->{path_po}/$locale/LC_MESSAGES"; - my $pofile = "$self->{path_po}/$self->{lang}-messages.po"; - my $mofile = "$modir/$self->{domain}.mo"; + my $locale = $self->locale_name(); + my $modir = "$self->{path_po}/$locale/LC_MESSAGES"; + my $pofile = "$self->{path_po}/$self->{lang}-messages.po"; + my $mofile = "$modir/$self->{domain}.mo"; my $js_pofile = "$self->{path_po}/$self->{lang}-messages-js.po"; unless ( -f $pofile && -f $js_pofile ) { @@ -455,14 +466,14 @@ sub install_messages { system "$self->{msgfmt} -o $mofile $pofile"; my $js_locale_data = 'var json_locale_data = {"Koha":' . `$self->{po2json} $js_pofile` . '};'; - my $progdir = C4::Context->config('intrahtdocs') . '/prog'; + my $progdir = C4::Context->config('intrahtdocs') . '/prog'; mkdir "$progdir/$self->{lang}/js"; open my $fh, '>', "$progdir/$self->{lang}/js/locale_data.js"; print $fh $js_locale_data; close $fh; my $opachtdocs = C4::Context->config('opachtdocs'); - opendir(my $dh, $opachtdocs); + opendir( my $dh, $opachtdocs ); for my $theme ( grep { not /^\.|lib|xslt/ } readdir($dh) ) { mkdir "$opachtdocs/$theme/$self->{lang}/js"; open my $fh, '>', "$opachtdocs/$theme/$self->{lang}/js/locale_data.js"; @@ -472,13 +483,13 @@ sub install_messages { } sub compress { - my ($self, $files) = @_; - my @langs = $self->{lang} ? ($self->{lang}) : $self->get_all_langs(); - for my $lang ( @langs ) { - $self->set_lang( $lang ); + my ( $self, $files ) = @_; + my @langs = $self->{lang} ? ( $self->{lang} ) : $self->get_all_langs(); + for my $lang (@langs) { + $self->set_lang($lang); opendir( my $dh, $self->{path_po} ); my @files = grep { $_ =~ /^$self->{lang}.*po$/ } readdir $dh; - foreach my $file ( @files ) { + foreach my $file (@files) { say "Compress file $file" if $self->{verbose}; system "$self->{gzip} -9 $self->{path_po}/$file"; } @@ -486,13 +497,13 @@ sub compress { } sub uncompress { - my ($self, $files) = @_; - my @langs = $self->{lang} ? ($self->{lang}) : $self->get_all_langs(); - for my $lang ( @langs ) { + my ( $self, $files ) = @_; + my @langs = $self->{lang} ? ( $self->{lang} ) : $self->get_all_langs(); + for my $lang (@langs) { opendir( my $dh, $self->{path_po} ); - $self->set_lang( $lang ); + $self->set_lang($lang); my @files = grep { $_ =~ /^$self->{lang}.*po.gz$/ } readdir $dh; - foreach my $file ( @files ) { + foreach my $file (@files) { say "Uncompress file $file" if $self->{verbose}; system "$self->{gunzip} $self->{path_po}/$file"; } @@ -500,11 +511,11 @@ sub uncompress { } sub install { - my ($self, $files) = @_; + my ( $self, $files ) = @_; return unless $self->{lang}; $self->uncompress(); - if ($self->{pref_only}) { + if ( $self->{pref_only} ) { $self->install_prefs(); } else { $self->install_tmpl($files); @@ -514,18 +525,15 @@ sub install { } } - sub get_all_langs { my $self = shift; opendir( my $dh, $self->{path_po} ); - my @files = grep { $_ =~ /-pref.(po|po.gz)$/ } - readdir $dh; + my @files = grep { $_ =~ /-pref.(po|po.gz)$/ } readdir $dh; @files = map { $_ =~ s/-pref.(po|po.gz)$//r } @files; } 1; - =head1 NAME LangInstaller.pm - Handle templates and preferences translation diff --git a/misc/translator/TmplTokenizer.pm b/misc/translator/TmplTokenizer.pm index 1e95c54879..ab2f5a5eef 100644 --- a/misc/translator/TmplTokenizer.pm +++ b/misc/translator/TmplTokenizer.pm @@ -21,7 +21,6 @@ A wrapper for the functionality found in TTParser to allow an easier transition ############################################################################### - use vars qw( $pedantic_attribute_error_in_nonpedantic_mode_p ); use vars qw( $pedantic_tmpl_var_use_in_nonpedantic_mode_p ); use vars qw( $pedantic_error_markup_in_pcdata_p ); @@ -30,45 +29,52 @@ use vars qw( $pedantic_error_markup_in_pcdata_p ); # Hideous stuff use vars qw( $re_xsl $re_end_entity $re_tmpl_var); + BEGIN { - $re_tmpl_var = q{\[%\s*[get|set|default]?\s*[\w\.]+\s*[|.*?]?\s*%\]}; - $re_xsl = q{<\/?(?:xsl:)(?:[\s\-a-zA-Z0-9"'\/\.\[\]\@\(\):=,$]+)\/?>}; - $re_end_entity = '(?:;|$|(?=\s))'; # semicolon or before-whitespace + $re_tmpl_var = q{\[%\s*[get|set|default]?\s*[\w\.]+\s*[|.*?]?\s*%\]}; + $re_xsl = q{<\/?(?:xsl:)(?:[\s\-a-zA-Z0-9"'\/\.\[\]\@\(\):=,$]+)\/?>}; + $re_end_entity = '(?:;|$|(?=\s))'; # semicolon or before-whitespace } + # End of the hideous stuff use vars qw( $serial ); ############################################################################### -sub FATAL_P () {'fatal-p'} -sub SYNTAXERROR_P () {'syntaxerror-p'} +sub FATAL_P () { 'fatal-p' } +sub SYNTAXERROR_P () { 'syntaxerror-p' } + +sub FILENAME () { 'input' } -sub FILENAME () {'input'} #sub HANDLE () {'handle'} #sub READAHEAD () {'readahead'} -sub LINENUM_START () {'lc_0'} -sub LINENUM () {'lc'} -sub CDATA_MODE_P () {'cdata-mode-p'} -sub CDATA_CLOSE () {'cdata-close'} -#sub PCDATA_MODE_P () {'pcdata-mode-p'} # additional submode for CDATA -sub JS_MODE_P () {'js-mode-p'} # cdata-mode-p must also be true +sub LINENUM_START () { 'lc_0' } +sub LINENUM () { 'lc' } +sub CDATA_MODE_P () { 'cdata-mode-p' } +sub CDATA_CLOSE () { 'cdata-close' } -sub ALLOW_CFORMAT_P () {'allow-cformat-p'} +#sub PCDATA_MODE_P () {'pcdata-mode-p'} # additional submode for CDATA +sub JS_MODE_P () { 'js-mode-p' } # cdata-mode-p must also be true + +sub ALLOW_CFORMAT_P () { 'allow-cformat-p' } sub new { shift; my ($filename) = @_; + #open my $handle,$filename or die "can't open $filename"; my $parser = C4::TTParser->new; - $parser->build_tokens( $filename ); + $parser->build_tokens($filename); bless { - filename => $filename, - _parser => $parser -# , handle => $handle -# , readahead => [] - } , __PACKAGE__; + filename => $filename, + _parser => $parser + + # , handle => $handle + # , readahead => [] + }, + __PACKAGE__; } ############################################################################### @@ -82,96 +88,107 @@ sub filename { sub fatal_p { my $this = shift; - return $this->{+FATAL_P}; + return $this->{ +FATAL_P }; } # work around, currently not implemented sub syntaxerror_p { -# my $this = shift; -# return $this->{+SYNTAXERROR_P}; + + # my $this = shift; + # return $this->{+SYNTAXERROR_P}; return 0; } sub js_mode_p { my $this = shift; - return $this->{+JS_MODE_P}; + return $this->{ +JS_MODE_P }; } sub allow_cformat_p { my $this = shift; - return $this->{+ALLOW_CFORMAT_P}; + return $this->{ +ALLOW_CFORMAT_P }; } # Simple setters sub _set_fatal { my $this = shift; - $this->{+FATAL_P} = $_[0]; + $this->{ +FATAL_P } = $_[0]; return $this; } sub _set_js_mode { my $this = shift; - $this->{+JS_MODE_P} = $_[0]; + $this->{ +JS_MODE_P } = $_[0]; return $this; } #used in xgettext, tmpl_process3 sub set_allow_cformat { my $this = shift; - $this->{+ALLOW_CFORMAT_P} = $_[0]; + $this->{ +ALLOW_CFORMAT_P } = $_[0]; return $this; } ############################################################################### use vars qw( $js_EscapeSequence ); + BEGIN { # Perl quoting is really screwed up, but this common subexp is way too long $js_EscapeSequence = q{\\\\(?:['"\\\\bfnrt]|[^0-7xu]|[0-3]?[0-7]{1,2}|x[\da-fA-F]{2}|u[\da-fA-F]{4})}; } -sub parenleft () { '(' } +sub parenleft () { '(' } sub parenright () { ')' } sub _split_js { my ($s0) = @_; my @it = (); - while (length $s0) { - if ($s0 =~ /^\s+/s) { # whitespace - push @it, $&; - $s0 = $'; - } elsif ($s0 =~ /^\/\/[^\r\n]*(?:[\r\n]|$)/s) { # C++-style comment - push @it, $&; - $s0 = $'; - } elsif ($s0 =~ /^\/\*(?:(?!\*\/).)*\*\//s) { # C-style comment + while ( length $s0 ) { + if ( $s0 =~ /^\s+/s ) { # whitespace push @it, $&; $s0 = $'; - # Keyword or identifier, ECMA-262 p.13 (section 7.5) - } elsif ($s0 =~ /^[A-Z_\$][A-Z\d_\$]*/is) { # IdentifierName + } elsif ( $s0 =~ /^\/\/[^\r\n]*(?:[\r\n]|$)/s ) { # C++-style comment push @it, $&; $s0 = $'; - # Punctuator, ECMA-262 p.13 (section 7.6) - } elsif ($s0 =~ /^(?:[\(\){}\[\];]|>>>=|<<=|>>=|[-\+\*\/\&\|\^\%]=|>>>|<<|>>|--|\+\+|\|\||\&\&|==|<=|>=|!=|[=><,!~\?:\.\-\+\*\/\&\|\^\%])/s) { + } elsif ( $s0 =~ /^\/\*(?:(?!\*\/).)*\*\//s ) { # C-style comment push @it, $&; $s0 = $'; - # DecimalLiteral, ECMA-262 p.14 (section 7.7.3); note: bug in the spec - } elsif ($s0 =~ /^(?:0|[1-9]\d+(?:\.\d*(?:[eE][-\+]?\d+)?)?)/s) { + + # Keyword or identifier, ECMA-262 p.13 (section 7.5) + } elsif ( $s0 =~ /^[A-Z_\$][A-Z\d_\$]*/is ) { # IdentifierName push @it, $&; $s0 = $'; - # HexIntegerLiteral, ECMA-262 p.15 (section 7.7.3) - } elsif ($s0 =~ /^0[xX][\da-fA-F]+/s) { + + # Punctuator, ECMA-262 p.13 (section 7.6) + } elsif ( $s0 =~ + /^(?:[\(\){}\[\];]|>>>=|<<=|>>=|[-\+\*\/\&\|\^\%]=|>>>|<<|>>|--|\+\+|\|\||\&\&|==|<=|>=|!=|[=><,!~\?:\.\-\+\*\/\&\|\^\%])/s + ) + { push @it, $&; $s0 = $'; - # OctalIntegerLiteral, ECMA-262 p.15 (section 7.7.3) - } elsif ($s0 =~ /^0[\da-fA-F]+/s) { + + # DecimalLiteral, ECMA-262 p.14 (section 7.7.3); note: bug in the spec + } elsif ( $s0 =~ /^(?:0|[1-9]\d+(?:\.\d*(?:[eE][-\+]?\d+)?)?)/s ) { push @it, $&; $s0 = $'; - # StringLiteral, ECMA-262 p.17 (section 7.7.4) - # XXX SourceCharacter doesn't seem to be defined (?) - } elsif ($s0 =~ /^(?:"(?:(?!["\\\r\n]).|$js_EscapeSequence)*"|'(?:(?!['\\\r\n]).|$js_EscapeSequence)*')/os) { + + # HexIntegerLiteral, ECMA-262 p.15 (section 7.7.3) + } elsif ( $s0 =~ /^0[xX][\da-fA-F]+/s ) { push @it, $&; $s0 = $'; - } elsif ($s0 =~ /^./) { # UNKNOWN TOKEN !!! + + # OctalIntegerLiteral, ECMA-262 p.15 (section 7.7.3) + } elsif ( $s0 =~ /^0[\da-fA-F]+/s ) { + push @it, $&; + $s0 = $'; + + # StringLiteral, ECMA-262 p.17 (section 7.7.4) + # XXX SourceCharacter doesn't seem to be defined (?) + } elsif ( $s0 =~ /^(?:"(?:(?!["\\\r\n]).|$js_EscapeSequence)*"|'(?:(?!['\\\r\n]).|$js_EscapeSequence)*')/os ) { + push @it, $&; + $s0 = $'; + } elsif ( $s0 =~ /^./ ) { # UNKNOWN TOKEN !!! push @it, $&; $s0 = $'; } @@ -179,105 +196,110 @@ sub _split_js { return @it; } -sub STATE_UNDERSCORE () { 1 } -sub STATE_PARENLEFT () { 2 } +sub STATE_UNDERSCORE () { 1 } +sub STATE_PARENLEFT () { 2 } sub STATE_STRING_LITERAL () { 3 } # XXX This is a crazy hack. I don't want to write an ECMAScript parser. # XXX A scanner is one thing; a parser another thing. sub _identify_js_translatables { - my @input = @_; + my @input = @_; my @output = (); + # We mark a JavaScript translatable string as in C, i.e., _("literal") # For simplicity, we ONLY look for "_" "(" StringLiteral ")" - for (my $i = 0, my $state = 0, my($j, $q, $s); $i <= $#input; $i += 1) { -# warn $input[$i]; + for ( my $i = 0, my $state = 0, my ( $j, $q, $s ) ; $i <= $#input ; $i += 1 ) { + + # warn $input[$i]; my $reset_state_p = 0; - push @output, [0, $input[$i]]; - if ($input[$i] !~ /\S/s) { - ; - } elsif ($state == 0) { - $state = STATE_UNDERSCORE if $input[$i] eq '_'; - } elsif ($state == STATE_UNDERSCORE) { - $state = $input[$i] eq parenleft ? STATE_PARENLEFT : 0; - } elsif ($state == STATE_PARENLEFT) { - if ($input[$i] =~ /^(['"])(.*)\1$/s) { - ($state, $j, $q, $s) = (STATE_STRING_LITERAL, $#output, $1, $2); - } else { + push @output, [ 0, $input[$i] ]; + if ( $input[$i] !~ /\S/s ) { + ; + } elsif ( $state == 0 ) { + $state = STATE_UNDERSCORE if $input[$i] eq '_'; + } elsif ( $state == STATE_UNDERSCORE ) { + $state = $input[$i] eq parenleft ? STATE_PARENLEFT : 0; + } elsif ( $state == STATE_PARENLEFT ) { + if ( $input[$i] =~ /^(['"])(.*)\1$/s ) { + ( $state, $j, $q, $s ) = ( STATE_STRING_LITERAL, $#output, $1, $2 ); + } else { + $state = 0; + } + } elsif ( $state == STATE_STRING_LITERAL ) { + if ( $input[$i] eq parenright ) { + $output[$j] = [ 1, $output[$j]->[1], $q, $s ]; + } $state = 0; - } - } elsif ($state == STATE_STRING_LITERAL) { - if ($input[$i] eq parenright) { - $output[$j] = [1, $output[$j]->[1], $q, $s]; - } - $state = 0; } else { - die "identify_js_translatables internal error: Unknown state $state" + die "identify_js_translatables internal error: Unknown state $state"; } } -# use Data::Dumper; -# warn Dumper \@output; + + # use Data::Dumper; + # warn Dumper \@output; return \@output; } ############################################################################### sub string_canon { - my $s = shift; - # Fold all whitespace into single blanks - $s =~ s/\s+/ /g; - $s =~ s/^\s+//g; - return $s; + my $s = shift; + + # Fold all whitespace into single blanks + $s =~ s/\s+/ /g; + $s =~ s/^\s+//g; + return $s; } # safer version used internally, preserves new lines sub string_canon_safe { - my $s = shift; - # fold tabs and spaces into single spaces - $s =~ s/[\ \t]+/ /gs; - return $s; + my $s = shift; + + # fold tabs and spaces into single spaces + $s =~ s/[\ \t]+/ /gs; + return $s; } - -sub _quote_cformat{ - my $s = shift; - $s =~ s/%/%%/g; - return $s; +sub _quote_cformat { + my $s = shift; + $s =~ s/%/%%/g; + return $s; } -sub _formalize_string_cformat{ - my $s = shift; - return _quote_cformat( string_canon_safe($s) ); +sub _formalize_string_cformat { + my $s = shift; + return _quote_cformat( string_canon_safe($s) ); } -sub _formalize{ - my $t = shift; - if( $t->type == C4::TmplTokenType::DIRECTIVE ){ - return '%s'; - } elsif( $t->type == C4::TmplTokenType::TEXT ){ - return _formalize_string_cformat( $t->string ); - } elsif( $t->type == C4::TmplTokenType::TAG ){ - if( $t->string =~ m/^a\b/is ){ - return '
            '; - } elsif( $t->string =~ m/^input\b/is ){ - if( lc $t->attributes->{'type'}->[1] eq 'text' ){ - return '%S'; - } else{ - return '%p'; - } - } else{ - return _quote_cformat $t->string; - } - } else{ - return _quote_cformat $t->string; - } +sub _formalize { + my $t = shift; + if ( $t->type == C4::TmplTokenType::DIRECTIVE ) { + return '%s'; + } elsif ( $t->type == C4::TmplTokenType::TEXT ) { + return _formalize_string_cformat( $t->string ); + } elsif ( $t->type == C4::TmplTokenType::TAG ) { + if ( $t->string =~ m/^a\b/is ) { + return ''; + } elsif ( $t->string =~ m/^input\b/is ) { + if ( lc $t->attributes->{'type'}->[1] eq 'text' ) { + return '%S'; + } else { + return '%p'; + } + } else { + return _quote_cformat $t->string; + } + } else { + return _quote_cformat $t->string; + } } # internal parametization, used within next_token # method that takes in an array of TEXT and DIRECTIVE tokens (DIRECTIVEs must be GET) and return a C4::TmplTokenType::TEXT_PARAMETRIZED -sub _parametrize_internal{ - my $this = shift; +sub _parametrize_internal { + my $this = shift; my @parts = @_; + # my $s = ""; # for my $item (@parts){ # if( $item->type == C4::TmplTokenType::TEXT ){ @@ -288,6 +310,7 @@ sub _parametrize_internal{ # } # } my $s = join( "", map { _formalize $_ } @parts ); + # should both the string and form be $s? maybe only the later? posibly the former.... # used line number from first token, should suffice my $t = C4::TmplToken->new( $s, C4::TmplTokenType::TEXT_PARAMETRIZED, $parts[0]->line_number, $this->filename ); @@ -299,46 +322,47 @@ sub _parametrize_internal{ sub next_token { my $self = shift; my $next; -# warn "in next_token"; + + # warn "in next_token"; # parts that make up a text_parametrized (future children of the token) my @parts = (); - while(1){ + while (1) { $next = $self->{_parser}->next_token; - if (! $next){ - if (@parts){ + if ( !$next ) { + if (@parts) { return $self->_parametrize_internal(@parts); - } - else { + } else { return; } } + # if cformat mode is off, dont bother parametrizing, just return them as they come return $next unless $self->allow_cformat_p; - if( $next->type == C4::TmplTokenType::TEXT ){ + if ( $next->type == C4::TmplTokenType::TEXT ) { push @parts, $next; - } -# elsif( $next->type == C4::TmplTokenType::DIRECTIVE && $next->string =~ m/\[%\s*\w+\s*%\]/ ){ - elsif( $next->type == C4::TmplTokenType::DIRECTIVE ){ + } + + # elsif( $next->type == C4::TmplTokenType::DIRECTIVE && $next->string =~ m/\[%\s*\w+\s*%\]/ ){ + elsif ( $next->type == C4::TmplTokenType::DIRECTIVE ) { push @parts, $next; - } - elsif ( $next->type == C4::TmplTokenType::CDATA){ + } elsif ( $next->type == C4::TmplTokenType::CDATA ) { $self->_set_js_mode(1); - my $s0 = $next->string; + my $s0 = $next->string; my @head = (); my @tail = (); - if ($s0 =~ /^(\s*\[%\s*)(.*)(\s%=]\s*)$/s) { + if ( $s0 =~ /^(\s*\[%\s*)(.*)(\s%=]\s*)$/s ) { push @head, $1; - push @tail, $3; + push @tail, $3; $s0 = $2; } push @head, _split_js($s0); - $next->set_js_data(_identify_js_translatables(@head, @tail) ); - return $next unless @parts; - $self->{_parser}->unshift_token($next); + $next->set_js_data( _identify_js_translatables( @head, @tail ) ); + return $next unless @parts; + $self->{_parser}->unshift_token($next); return $self->_parametrize_internal(@parts); - } - else { + } else { + # if there is nothing in parts, return this token return $next unless @parts; @@ -355,117 +379,114 @@ sub next_token { # function taken from old version # used by tmpl_process3 sub parametrize { - my($fmt_0, $cformat_p, $t, $f) = @_; + my ( $fmt_0, $cformat_p, $t, $f ) = @_; my $it = ''; if ($cformat_p) { - my @params = $t->parameters_and_fields; - for (my $n = 0, my $fmt = $fmt_0; length $fmt;) { - if ($fmt =~ /^[^%]+/) { - $fmt = $'; - $it .= $&; - } elsif ($fmt =~ /^%%/) { - $fmt = $'; - $it .= '%'; - } elsif ($fmt =~ /^%(?:(\d+)\$)?(?:(\d+)(?:\.(\d+))?)?s/s) { - $n += 1; - my($i, $width, $prec) = ((defined $1? $1: $n), $2, $3); - $fmt = $'; - if (defined $width && defined $prec && !$width && !$prec) { - ; - } elsif (defined $params[$i - 1]) { - my $param = $params[$i - 1]; - warn_normal("$fmt_0: $&: Expected a TMPL_VAR, but found a " - . $param->type->to_string . "\n", undef) - if $param->type != C4::TmplTokenType::DIRECTIVE; - warn_normal("$fmt_0: $&: Unsupported " - . "field width or precision\n", undef) - if defined $width || defined $prec; - warn_normal("$fmt_0: $&: Parameter $i not known", undef) - unless defined $param; - $it .= defined $f? &$f( $param ): $param->string; - } - } elsif ($fmt =~ /^%(?:(\d+)\$)?(?:(\d+)(?:\.(\d+))?)?([pS])/s) { - $n += 1; - my($i, $width, $prec, $conv) = ((defined $1? $1: $n), $2, $3, $4); - $fmt = $'; + my @params = $t->parameters_and_fields; + for ( my $n = 0, my $fmt = $fmt_0 ; length $fmt ; ) { + if ( $fmt =~ /^[^%]+/ ) { + $fmt = $'; + $it .= $&; + } elsif ( $fmt =~ /^%%/ ) { + $fmt = $'; + $it .= '%'; + } elsif ( $fmt =~ /^%(?:(\d+)\$)?(?:(\d+)(?:\.(\d+))?)?s/s ) { + $n += 1; + my ( $i, $width, $prec ) = ( ( defined $1 ? $1 : $n ), $2, $3 ); + $fmt = $'; + if ( defined $width && defined $prec && !$width && !$prec ) { + ; + } elsif ( defined $params[ $i - 1 ] ) { + my $param = $params[ $i - 1 ]; + warn_normal( + "$fmt_0: $&: Expected a TMPL_VAR, but found a " . $param->type->to_string . "\n", + undef + ) if $param->type != C4::TmplTokenType::DIRECTIVE; + warn_normal( "$fmt_0: $&: Unsupported " . "field width or precision\n", undef ) + if defined $width || defined $prec; + warn_normal( "$fmt_0: $&: Parameter $i not known", undef ) + unless defined $param; + $it .= defined $f ? &$f($param) : $param->string; + } + } elsif ( $fmt =~ /^%(?:(\d+)\$)?(?:(\d+)(?:\.(\d+))?)?([pS])/s ) { + $n += 1; + my ( $i, $width, $prec, $conv ) = ( ( defined $1 ? $1 : $n ), $2, $3, $4 ); + $fmt = $'; - my $param = $params[$i - 1]; - if (!defined $param) { - warn_normal("$fmt_0: $&: Parameter $i not known", undef); - } else { - if ($param->type == C4::TmplTokenType::TAG - && $param->string =~ /^attributes? - lc($param->attributes->{'type'}->[1]): undef; - if ($conv eq 'S') { - warn_normal("$fmt_0: $&: Expected type=text, " - . "but found type=$type", undef) - unless $type eq 'text'; - } elsif ($conv eq 'p') { - warn_normal("$fmt_0: $&: Expected type=radio, " - . "but found type=$type", undef) - unless $type eq 'radio'; - } - } else { - warn_normal("$&: Expected an INPUT, but found a " - . $param->type->to_string . "\n", undef) - } - warn_normal("$fmt_0: $&: Unsupported " - . "field width or precision\n", undef) - if defined $width || defined $prec; - $it .= defined $f? &$f( $param ): $param->string; - } - } elsif ($fmt =~ /^%[^%a-zA-Z]*[a-zA-Z]/) { - $fmt = $'; - $it .= $&; - die "$&: Unknown or unsupported format specification\n"; #XXX - } else { - die "$&: Completely confused parametrizing -- msgid: $fmt_0\n";#XXX - } - } + my $param = $params[ $i - 1 ]; + if ( !defined $param ) { + warn_normal( "$fmt_0: $&: Parameter $i not known", undef ); + } else { + if ( $param->type == C4::TmplTokenType::TAG + && $param->string =~ /^attributes ? lc( $param->attributes->{'type'}->[1] ) : undef; + if ( $conv eq 'S' ) { + warn_normal( "$fmt_0: $&: Expected type=text, " . "but found type=$type", undef ) + unless $type eq 'text'; + } elsif ( $conv eq 'p' ) { + warn_normal( "$fmt_0: $&: Expected type=radio, " . "but found type=$type", undef ) + unless $type eq 'radio'; + } + } else { + warn_normal( "$&: Expected an INPUT, but found a " . $param->type->to_string . "\n", undef ); + } + warn_normal( "$fmt_0: $&: Unsupported " . "field width or precision\n", undef ) + if defined $width || defined $prec; + $it .= defined $f ? &$f($param) : $param->string; + } + } elsif ( $fmt =~ /^%[^%a-zA-Z]*[a-zA-Z]/ ) { + $fmt = $'; + $it .= $&; + die "$&: Unknown or unsupported format specification\n"; #XXX + } else { + die "$&: Completely confused parametrizing -- msgid: $fmt_0\n"; #XXX + } + } } my @anchors = $t->anchors; - for (my $n = 0, my $fmt = $it, $it = ''; length $fmt;) { - if ($fmt =~ /^(?:(?!).)+/is) { - $fmt = $'; - $it .= $&; - } elsif ($fmt =~ /^/is) { - $n += 1; - my $i = $1; - $fmt = $'; - my $anchor = $anchors[$i - 1]; - warn_normal("$&: Anchor $1 not found for msgid \"$fmt_0\"", undef) #FIXME - unless defined $anchor; - $it .= $anchor->string; - } else { - die "Completely confused decoding anchors: $fmt\n";#XXX - } + for ( my $n = 0, my $fmt = $it, $it = '' ; length $fmt ; ) { + if ( $fmt =~ /^(?:(?!).)+/is ) { + $fmt = $'; + $it .= $&; + } elsif ( $fmt =~ /^/is ) { + $n += 1; + my $i = $1; + $fmt = $'; + my $anchor = $anchors[ $i - 1 ]; + warn_normal( "$&: Anchor $1 not found for msgid \"$fmt_0\"", undef ) #FIXME + unless defined $anchor; + $it .= $anchor->string; + } else { + die "Completely confused decoding anchors: $fmt\n"; #XXX + } } return $it; } - # Other simple functions (These are not methods) sub blank_p { - my($s) = @_; + my ($s) = @_; return $s =~ /^(?:\s|\ $re_end_entity|$re_tmpl_var|$re_xsl)*$/osi; } sub trim { - my($s0) = @_; - my $l0 = length $s0; - my $s = $s0; - $s =~ s/^(\s|\ $re_end_entity)+//os; my $l1 = $l0 - length $s; - $s =~ s/(\s|\ $re_end_entity)+$//os; my $l2 = $l0 - $l1 - length $s; - return wantarray? (substr($s0, 0, $l1), $s, substr($s0, $l0 - $l2)): $s; + my ($s0) = @_; + my $l0 = length $s0; + my $s = $s0; + $s =~ s/^(\s|\ $re_end_entity)+//os; + my $l1 = $l0 - length $s; + $s =~ s/(\s|\ $re_end_entity)+$//os; + my $l2 = $l0 - $l1 - length $s; + return wantarray ? ( substr( $s0, 0, $l1 ), $s, substr( $s0, $l0 - $l2 ) ) : $s; } sub charset_canon { - my($charset) = @_; + my ($charset) = @_; $charset = uc($charset); $charset = "$1-$2" if $charset =~ /^(ISO|UTF)(\d.*)/i; - $charset = 'Big5' if $charset eq 'BIG5'; # "Big5" must be in mixed case + $charset = 'Big5' if $charset eq 'BIG5'; # "Big5" must be in mixed case return $charset; } @@ -473,7 +494,7 @@ use vars qw( @latin1_utf8 ); @latin1_utf8 = ( "\302\200", "\302\201", "\302\202", "\302\203", "\302\204", "\302\205", "\302\206", "\302\207", "\302\210", "\302\211", "\302\212", "\302\213", - "\302\214", "\302\215", undef, undef, "\302\220", "\302\221", + "\302\214", "\302\215", undef, undef, "\302\220", "\302\221", "\302\222", "\302\223", "\302\224", "\302\225", "\302\226", "\302\227", "\302\230", "\302\231", "\302\232", "\302\233", "\302\234", "\302\235", "\302\236", "\302\237", "\302\240", "\302\241", "\302\242", "\302\243", @@ -492,16 +513,17 @@ use vars qw( @latin1_utf8 ); "\303\254", "\303\255", "\303\256", "\303\257", "\303\260", "\303\261", "\303\262", "\303\263", "\303\264", "\303\265", "\303\266", "\303\267", "\303\270", "\303\271", "\303\272", "\303\273", "\303\274", "\303\275", - "\303\276", "\303\277" ); + "\303\276", "\303\277" +); sub charset_convert { - my($s, $charset_in, $charset_out) = @_; - if ($s !~ /[\200-\377]/s) { # FIXME: don't worry about iso2022 for now - ; - } elsif ($charset_in eq 'ISO-8859-1' && $charset_out eq 'UTF-8') { - $s =~ s/[\200-\377]/ $latin1_utf8[ord($&) - 128] /egs; - } elsif ($charset_in ne $charset_out) { - VerboseWarnings::warn_normal "conversion from $charset_in to $charset_out is not supported\n", undef; + my ( $s, $charset_in, $charset_out ) = @_; + if ( $s !~ /[\200-\377]/s ) { # FIXME: don't worry about iso2022 for now + ; + } elsif ( $charset_in eq 'ISO-8859-1' && $charset_out eq 'UTF-8' ) { + $s =~ s/[\200-\377]/ $latin1_utf8[ord($&) - 128] /egs; + } elsif ( $charset_in ne $charset_out ) { + VerboseWarnings::warn_normal "conversion from $charset_in to $charset_out is not supported\n", undef; } return $s; } diff --git a/misc/translator/VerboseWarnings.pm b/misc/translator/VerboseWarnings.pm index e2ee42377b..2b3d9f9181 100644 --- a/misc/translator/VerboseWarnings.pm +++ b/misc/translator/VerboseWarnings.pm @@ -17,10 +17,11 @@ verbose warnings. ############################################################################### -our (@ISA, @EXPORT_OK); +our ( @ISA, @EXPORT_OK ); + BEGIN { require Exporter; - @ISA = qw(Exporter); + @ISA = qw(Exporter); @EXPORT_OK = qw( pedantic_p warn_additional @@ -37,7 +38,7 @@ use vars qw( $appName $input $input_abbr $pedantic_p $pedantic_tag $quiet); use vars qw( $warned $erred ); sub set_application_name { - my($s) = @_; + my ($s) = @_; $appName = $& if !defined $appName && $s =~ /[^\/]+$/; } @@ -46,15 +47,15 @@ sub application_name { } sub set_input_file_name { - my($s) = @_; - $input = $s; + my ($s) = @_; + $input = $s; $input_abbr = $& if defined $s && $s =~ /[^\/]+$/; } sub set_pedantic_mode { - my($p) = @_; - $pedantic_p = $p; - $pedantic_tag = $pedantic_p? '': ' (negligible)'; + my ($p) = @_; + $pedantic_p = $p; + $pedantic_tag = $pedantic_p ? '' : ' (negligible)'; } sub pedantic_p { @@ -62,61 +63,63 @@ sub pedantic_p { } sub construct_warn_prefix { - my($prefix, $lc) = @_; + my ( $prefix, $lc ) = @_; die "construct_warn_prefix called before set_application_name" - unless defined $appName; + unless defined $appName; die "construct_warn_prefix called before set_input_file_name" - unless defined $input || !defined $lc; # be a bit lenient + unless defined $input || !defined $lc; # be a bit lenient die "construct_warn_prefix called before set_pedantic_mode" - unless defined $pedantic_tag; + unless defined $pedantic_tag; # FIXME: The line number is not accurate, but should be "close enough" # FIXME: This wording is worse than what was there, but it's wrong to # FIXME: hard-code this thing in each warn statement. Need improvement. - return "$appName: $prefix: " . (defined $lc? "$input_abbr: line $lc: ": defined $input_abbr? "$input_abbr: ": ''); + return "$appName: $prefix: " + . ( defined $lc ? "$input_abbr: line $lc: " : defined $input_abbr ? "$input_abbr: " : '' ); } sub warn_additional { - my($msg, $lc) = @_; - my $prefix = construct_warn_prefix('Warning', $lc); + my ( $msg, $lc ) = @_; + my $prefix = construct_warn_prefix( 'Warning', $lc ); $msg .= "\n" unless $msg =~ /\n$/s; warn "$prefix$msg"; } sub warn_normal { - my($msg, $lc) = @_; + my ( $msg, $lc ) = @_; $warned += 1; - warn_additional($msg, $lc); + warn_additional( $msg, $lc ); } sub warn_pedantic { - my($msg, $lc, $flag) = @_; - my $prefix = construct_warn_prefix("Warning$pedantic_tag", $lc); + my ( $msg, $lc, $flag ) = @_; + my $prefix = construct_warn_prefix( "Warning$pedantic_tag", $lc ); $msg .= "\n" unless $msg =~ /\n$/s; - warn "$prefix$msg" if ($pedantic_p || !$$flag) && $quiet; - if (!$pedantic_p) { - $prefix = construct_warn_prefix("Warning$pedantic_tag", undef); - warn $prefix."Further similar negligible warnings will not be reported, use --pedantic for details\n" unless ($$flag || !$quiet); - $$flag = 1; + warn "$prefix$msg" if ( $pedantic_p || !$$flag ) && $quiet; + if ( !$pedantic_p ) { + $prefix = construct_warn_prefix( "Warning$pedantic_tag", undef ); + warn $prefix . "Further similar negligible warnings will not be reported, use --pedantic for details\n" + unless ( $$flag || !$quiet ); + $$flag = 1; } $warned += 1; } sub error_additional { - my($msg, $lc) = @_; - my $prefix = construct_warn_prefix('ERROR', $lc); + my ( $msg, $lc ) = @_; + my $prefix = construct_warn_prefix( 'ERROR', $lc ); $msg .= "\n" unless $msg =~ /\n$/s; warn "$prefix$msg"; } sub error_normal { - my($msg, $lc) = @_; + my ( $msg, $lc ) = @_; $erred += 1; - error_additional($msg, $lc); + error_additional( $msg, $lc ); } sub warned { - return $warned; # number of times warned + return $warned; # number of times warned } 1; diff --git a/misc/translator/tmpl_process3.pl b/misc/translator/tmpl_process3.pl index 5e4865d6a9..7b4d3c81f8 100755 --- a/misc/translator/tmpl_process3.pl +++ b/misc/translator/tmpl_process3.pl @@ -15,9 +15,10 @@ using gettext-compatible translation files =cut use strict; + #use warnings; FIXME - Bug 2505 use File::Basename qw( fileparse ); -use Getopt::Long qw( GetOptions ); +use Getopt::Long qw( GetOptions ); use Locale::PO; use TmplTokenizer; use VerboseWarnings qw( pedantic_p warn_additional warn_normal warn_pedantic error_additional error_normal ); @@ -29,156 +30,169 @@ use vars qw( @excludes $exclude_regex ); use vars qw( $recursive_p ); use vars qw( $pedantic_p ); use vars qw( $href ); -use vars qw( $type ); # file extension (DOS form without the dot) to match +use vars qw( $type ); # file extension (DOS form without the dot) to match use vars qw( $charset_in $charset_out ); ############################################################################### sub find_translation { - my($s) = @_; + my ($s) = @_; my $key = $s; - if ($s =~ /\S/s) { - $key = TmplTokenizer::string_canon($key); - $key = TmplTokenizer::charset_convert($key, $charset_in, $charset_out); - $key = Locale::PO->quote($key); + if ( $s =~ /\S/s ) { + $key = TmplTokenizer::string_canon($key); + $key = TmplTokenizer::charset_convert( $key, $charset_in, $charset_out ); + $key = Locale::PO->quote($key); } - if (defined $href->{$key} && !$href->{$key}->fuzzy && length Locale::PO->dequote($href->{$key}->msgstr)){ - if ($s =~ /^(\s+)/){ - return $1 . Locale::PO->dequote($href->{$key}->msgstr); - } - else { - return Locale::PO->dequote($href->{$key}->msgstr); - } - } - else { - return $s; + if ( defined $href->{$key} && !$href->{$key}->fuzzy && length Locale::PO->dequote( $href->{$key}->msgstr ) ) { + if ( $s =~ /^(\s+)/ ) { + return $1 . Locale::PO->dequote( $href->{$key}->msgstr ); + } else { + return Locale::PO->dequote( $href->{$key}->msgstr ); + } + } else { + return $s; } } sub text_replace_tag { - my($t, $attr) = @_; + my ( $t, $attr ) = @_; my $it; my @ttvar; # value [tag=input], meta - my $tag = ($t =~ /^<(\S+)/s) ? lc($1) : undef; + my $tag = ( $t =~ /^<(\S+)/s ) ? lc($1) : undef; my $translated_p = 0; - for my $a ('alt', 'content', 'title', 'value', 'label', 'placeholder', 'aria-label') { - if ($attr->{$a}) { - next if $a eq 'label' && $tag ne 'optgroup'; - next if $a eq 'content' && $tag ne 'meta'; - next if $a eq 'value' && ($tag ne 'input' || (ref $attr->{'type'} && $attr->{'type'}->[1] =~ /^(?:checkbox|hidden|radio)$/)); # FIXME + for my $a ( 'alt', 'content', 'title', 'value', 'label', 'placeholder', 'aria-label' ) { + if ( $attr->{$a} ) { + next if $a eq 'label' && $tag ne 'optgroup'; + next if $a eq 'content' && $tag ne 'meta'; + next + if $a eq 'value' + && ( $tag ne 'input' + || ( ref $attr->{'type'} && $attr->{'type'}->[1] =~ /^(?:checkbox|hidden|radio)$/ ) ); # FIXME - my($key, $val, $val_orig, $order) = @{$attr->{$a}}; #FIXME - if ($val =~ /\S/s) { - # for selected attributes replace '[%..%]' with '%s' and remember matches - if ( $a =~ /title|value|alt|content|placeholder|aria-label/ ) { - while ( $val =~ s/(\[\%.*?\%\])/\%s/ ) { - my $var = $1; - push @ttvar, $1; + my ( $key, $val, $val_orig, $order ) = @{ $attr->{$a} }; #FIXME + if ( $val =~ /\S/s ) { + + # for selected attributes replace '[%..%]' with '%s' and remember matches + if ( $a =~ /title|value|alt|content|placeholder|aria-label/ ) { + while ( $val =~ s/(\[\%.*?\%\])/\%s/ ) { + my $var = $1; + push @ttvar, $1; + } } - } - # find translation for transformed attributes - my $s = find_translation($val); - # replace '%s' with original content (in order) on translated string, this is fragile! - if ( $a =~ /title|value|alt|content|placeholder|aria-label/ and @ttvar ) { - while ( @ttvar ) { - my $var = shift @ttvar; - $s =~ s/\%s/$var/; + + # find translation for transformed attributes + my $s = find_translation($val); + + # replace '%s' with original content (in order) on translated string, this is fragile! + if ( $a =~ /title|value|alt|content|placeholder|aria-label/ and @ttvar ) { + while (@ttvar) { + my $var = shift @ttvar; + $s =~ s/\%s/$var/; + } + } + if ( $attr->{$a}->[1] ne $s ) { #FIXME + $attr->{$a}->[1] = $s; # FIXME + $attr->{$a}->[2] = ( $s =~ /"/s ) ? "'$s'" : "\"$s\""; #FIXME + $translated_p = 1; } - } - if ($attr->{$a}->[1] ne $s) { #FIXME - $attr->{$a}->[1] = $s; # FIXME - $attr->{$a}->[2] = ($s =~ /"/s)? "'$s'": "\"$s\""; #FIXME - $translated_p = 1; } } } - } if ($translated_p) { - $it = "<$tag" - . join('', map { if ($_ ne '/'){ - sprintf(' %s="%s"', $_, $attr->{$_}->[1]); - } - else { - sprintf(' %s',$_); - } - - } sort { - $attr->{$a}->[3] <=> $attr->{$b}->[3] #FIXME - || $a cmp $b # Sort attributes BZ 22236 - } keys %$attr); + $it = "<$tag" . join( + '', + map { + if ( $_ ne '/' ) { + sprintf( ' %s="%s"', $_, $attr->{$_}->[1] ); + } else { + sprintf( ' %s', $_ ); + } + + } sort { + $attr->{$a}->[3] <=> $attr->{$b}->[3] #FIXME + || $a cmp $b # Sort attributes BZ 22236 + } keys %$attr + ); $it .= '>'; - } - else { + } else { $it = $t; } return $it; } sub text_replace { - my($h, $output) = @_; - for (;;) { - my $s = TmplTokenizer::next_token($h); - last unless defined $s; - my($kind, $t, $attr) = ($s->type, $s->string, $s->attributes); - if ($kind eq C4::TmplTokenType::TEXT) { - print $output find_translation($t); - } elsif ($kind eq C4::TmplTokenType::TEXT_PARAMETRIZED) { - my $fmt = find_translation($s->form); - print $output TmplTokenizer::parametrize($fmt, 1, $s, sub { - $_ = $_[0]; - my($kind, $t, $attr) = ($_->type, $_->string, $_->attributes); - $kind == C4::TmplTokenType::TAG && %$attr? - text_replace_tag($t, $attr): $t }); - } elsif ($kind eq C4::TmplTokenType::TAG && %$attr) { - print $output text_replace_tag($t, $attr); - } elsif ($s->has_js_data) { - for my $t (@{$s->js_data}) { - # FIXME for this whole block - if ($t->[0]) { - printf $output "%s%s%s", $t->[2], find_translation($t->[3]), - $t->[2]; - } else { - print $output $t->[1]; + my ( $h, $output ) = @_; + for ( ; ; ) { + my $s = TmplTokenizer::next_token($h); + last unless defined $s; + my ( $kind, $t, $attr ) = ( $s->type, $s->string, $s->attributes ); + if ( $kind eq C4::TmplTokenType::TEXT ) { + print $output find_translation($t); + } elsif ( $kind eq C4::TmplTokenType::TEXT_PARAMETRIZED ) { + my $fmt = find_translation( $s->form ); + print $output TmplTokenizer::parametrize( + $fmt, 1, $s, + sub { + $_ = $_[0]; + my ( $kind, $t, $attr ) = ( $_->type, $_->string, $_->attributes ); + $kind == C4::TmplTokenType::TAG && %$attr ? text_replace_tag( $t, $attr ) : $t; + } + ); + } elsif ( $kind eq C4::TmplTokenType::TAG && %$attr ) { + print $output text_replace_tag( $t, $attr ); + } elsif ( $s->has_js_data ) { + for my $t ( @{ $s->js_data } ) { + + # FIXME for this whole block + if ( $t->[0] ) { + printf $output "%s%s%s", $t->[2], find_translation( $t->[3] ), + $t->[2]; + } else { + print $output $t->[1]; + } + } + } elsif ( defined $t ) { + + # Quick fix to bug 4472 + $t = " \@in_dirs, - 'filename|f=s' => \@filenames, - 'match|m=s' => \@match, - 'nomatch|n=s' => \@nomatch, - 'outputdir|o=s' => \$out_dir, - 'recursive|r' => \$recursive_p, - 'str-file|s=s' => \$str_file, - 'exclude|x=s' => \@excludes, - 'quiet|q' => \$quiet, - 'pedantic-warnings|pedantic' => sub { $pedantic_p = 1 }, - 'help' => \&usage, + 'input|i=s' => \@in_dirs, + 'filename|f=s' => \@filenames, + 'match|m=s' => \@match, + 'nomatch|n=s' => \@nomatch, + 'outputdir|o=s' => \$out_dir, + 'recursive|r' => \$recursive_p, + 'str-file|s=s' => \$str_file, + 'exclude|x=s' => \@excludes, + 'quiet|q' => \$quiet, + 'pedantic-warnings|pedantic' => sub { $pedantic_p = 1 }, + 'help' => \&usage, ) || usage_error(); VerboseWarnings::set_application_name($0); @@ -270,87 +285,93 @@ usage_error('You must at least specify input and string list filenames.') $type = "tt|inc|xsl|xml|def" if !defined($type); # Check the inputs for being directories -for my $in_dir ( @in_dirs ) { - usage_error("$in_dir: Input must be a directory.\n" - . "(Symbolic links are not supported at the moment)") +for my $in_dir (@in_dirs) { + usage_error( "$in_dir: Input must be a directory.\n" . "(Symbolic links are not supported at the moment)" ) unless -d $in_dir; } # Generates the global exclude regular expression -$exclude_regex = '(?:'.join('|', @excludes).')' if @excludes; +$exclude_regex = '(?:' . join( '|', @excludes ) . ')' if @excludes; my @in_files; + # Generate the list of input files if a directory is specified # input is a directory, generates list of files to process -for my $fn ( @filenames ) { +for my $fn (@filenames) { die "You cannot specify input files and directories at the same time.\n" if -d $fn; } -for my $in_dir ( @in_dirs ) { - $in_dir =~ s/\/$//; # strips the trailing / if any - @in_files = ( @in_files, listfiles($in_dir, $type, $action)); +for my $in_dir (@in_dirs) { + $in_dir =~ s/\/$//; # strips the trailing / if any + @in_files = ( @in_files, listfiles( $in_dir, $type, $action ) ); } # restores the string list from file -$href = Locale::PO->load_file_ashash($str_file, 'utf-8'); +$href = Locale::PO->load_file_ashash( $str_file, 'utf-8' ); # guess the charsets. HTML::Templates defaults to iso-8859-1 -if (defined $href) { +if ( defined $href ) { die "$str_file: PO file is corrupted, or not a PO file\n" unless defined $href->{'""'}; $charset_out = TmplTokenizer::charset_canon($2) if $href->{'""'}->msgstr =~ /\bcharset=(["']?)([^;\s"'\\]+)\1/; - $charset_in = $charset_out; -# for my $msgid (keys %$href) { -# if ($msgid =~ /\bcharset=(["']?)([^;\s"'\\]+)\1/) { -# my $candidate = TmplTokenizer::charset_canon $2; -# die "Conflicting charsets in msgid: $charset_in vs $candidate => $msgid\n" -# if defined $charset_in && $charset_in ne $candidate; -# $charset_in = $candidate; -# } -# } + $charset_in = $charset_out; + + # for my $msgid (keys %$href) { + # if ($msgid =~ /\bcharset=(["']?)([^;\s"'\\]+)\1/) { + # my $candidate = TmplTokenizer::charset_canon $2; + # die "Conflicting charsets in msgid: $charset_in vs $candidate => $msgid\n" + # if defined $charset_in && $charset_in ne $candidate; + # $charset_in = $candidate; + # } + # } # BUG6464: check consistency of PO messages # - count number of '%s' in msgid and msgstr for my $msg ( values %$href ) { - my $id_count = split(/%s/, $msg->{msgid}) - 1; - my $str_count = split(/%s/, $msg->{msgstr}) - 1; - next if $id_count == $str_count || - $msg->{msgstr} eq '""' || - grep { /fuzzy/ } @{$msg->{_flags}}; - warn_normal( - "unconsistent %s count: ($id_count/$str_count):\n" . - " line: " . $msg->{loaded_line_number} . "\n" . - " msgid: " . $msg->{msgid} . "\n" . - " msgstr: " . $msg->{msgstr} . "\n", undef); + my $id_count = split( /%s/, $msg->{msgid} ) - 1; + my $str_count = split( /%s/, $msg->{msgstr} ) - 1; + next + if $id_count == $str_count + || $msg->{msgstr} eq '""' + || grep { /fuzzy/ } @{ $msg->{_flags} }; + warn_normal( "unconsistent %s count: ($id_count/$str_count):\n" + . " line: " + . $msg->{loaded_line_number} . "\n" + . " msgid: " + . $msg->{msgid} . "\n" + . " msgstr: " + . $msg->{msgstr} + . "\n", undef ); } } # set our charset in to UTF-8 -if (!defined $charset_in) { +if ( !defined $charset_in ) { $charset_in = TmplTokenizer::charset_canon('UTF-8'); - warn "Warning: Can't determine original templates' charset, defaulting to $charset_in\n" unless ( $quiet ); + warn "Warning: Can't determine original templates' charset, defaulting to $charset_in\n" unless ($quiet); } + # set our charset out to UTF-8 -if (!defined $charset_out) { +if ( !defined $charset_out ) { $charset_out = TmplTokenizer::charset_canon('UTF-8'); - warn "Warning: Charset Out defaulting to $charset_out\n" unless ( $quiet ); + warn "Warning: Charset Out defaulting to $charset_out\n" unless ($quiet); } my $st; -if ($action eq 'install') { - if(!defined($out_dir)) { - usage_error("You must specify an output directory when using the install method."); +if ( $action eq 'install' ) { + if ( !defined($out_dir) ) { + usage_error("You must specify an output directory when using the install method."); } - + if ( scalar @in_dirs > 1 ) { - usage_error("You must specify only one input directory when using the install method."); + usage_error("You must specify only one input directory when using the install method."); } my $in_dir = shift @in_dirs; - if ($in_dir eq $out_dir) { - warn "You must specify a different input and output directory.\n"; - exit -1; + if ( $in_dir eq $out_dir ) { + warn "You must specify a different input and output directory.\n"; + exit -1; } # Make sure the output directory exists @@ -358,28 +379,29 @@ if ($action eq 'install') { -d $out_dir || die "$out_dir: The directory does not exist\n"; # Try to open the file, because Locale::PO doesn't check :-/ - open(my $fh, '<', $str_file) || die "$str_file: $!\n"; + open( my $fh, '<', $str_file ) || die "$str_file: $!\n"; close $fh; # creates the new tmpl file using the new translation for my $input (@in_files) { die "Assertion failed" - unless substr($input, 0, length($in_dir) + 1) eq "$in_dir/"; + unless substr( $input, 0, length($in_dir) + 1 ) eq "$in_dir/"; - my $target = $out_dir . substr($input, length($in_dir)); - my $targetdir = ($target =~ /[^\/]+$/s) ? $` : undef; + my $target = $out_dir . substr( $input, length($in_dir) ); + my $targetdir = ( $target =~ /[^\/]+$/s ) ? $` : undef; - if (!defined $type || $input =~ /\.(?:$type)$/) { - my $h = TmplTokenizer->new( $input ); - $h->set_allow_cformat( 1 ); + if ( !defined $type || $input =~ /\.(?:$type)$/ ) { + my $h = TmplTokenizer->new($input); + $h->set_allow_cformat(1); VerboseWarnings::set_input_file_name($input); - mkdir_recursive($targetdir) unless -d $targetdir; + mkdir_recursive($targetdir) unless -d $targetdir; print STDERR "Creating $target...\n" unless $quiet; open( my $fh, ">:encoding(UTF-8)", "$target" ) || die "$target: $!\n"; text_replace( $h, $fh ); close $fh; } else { - # just copying the file + + # just copying the file mkdir_recursive($targetdir) unless -d $targetdir; system("cp -f '$input' '$target'") == 0 or warn "Cannot copy $input to $target"; print STDERR "Copying $input...\n" unless $quiet; @@ -390,7 +412,7 @@ if ($action eq 'install') { usage_error('Unknown action specified.'); } -if ($st == 0) { +if ( $st == 0 ) { printf "The %s seems to be successful.\n", $action unless $quiet; } else { printf "%s FAILED.\n", "\u$action" unless $quiet; diff --git a/misc/translator/xgettext.pl b/misc/translator/xgettext.pl index f11b868d8d..828bf50b80 100755 --- a/misc/translator/xgettext.pl +++ b/misc/translator/xgettext.pl @@ -47,37 +47,37 @@ our $OUTPUT; ############################################################################### sub string_negligible_p { - my($t) = @_; # a string - # Don't emit pure whitespace, pure numbers, pure punctuation, - # single letters, or TMPL_VAR's. - # Punctuation should arguably be translated. But without context - # they are untranslatable. Note that $t is a string, not a token object. + my ($t) = @_; # a string + # Don't emit pure whitespace, pure numbers, pure punctuation, + # single letters, or TMPL_VAR's. + # Punctuation should arguably be translated. But without context + # they are untranslatable. Note that $t is a string, not a token object. return !$extract_all_p && ( - TmplTokenizer::blank_p($t) # blank or TMPL_VAR - || $t =~ /^\d+$/ # purely digits - || $t =~ /^[-\+\.,:;!\?'"%\(\)\[\]\|]+$/ # punctuation w/o context - || $t =~ /^[A-Za-z]$/ # single letters - || $t =~ /^(&[a-z]+;|&#\d+;|&#x[0-9a-fA-F]+;|%%|%s|\s|[[:punct:]])*$/ # html entities,placeholder,punct, ... - || ( $t =~ /^\[\%.*\%\]$/ and $t !~ /\%\].*\[\%/ ) # pure TT entities - || $t =~ /^\s*<\?.*\?>/ # ignore xml prolog - ) + TmplTokenizer::blank_p($t) # blank or TMPL_VAR + || $t =~ /^\d+$/ # purely digits + || $t =~ /^[-\+\.,:;!\?'"%\(\)\[\]\|]+$/ # punctuation w/o context + || $t =~ /^[A-Za-z]$/ # single letters + || $t =~ /^(&[a-z]+;|&#\d+;|&#x[0-9a-fA-F]+;|%%|%s|\s|[[:punct:]])*$/ # html entities,placeholder,punct, ... + || ( $t =~ /^\[\%.*\%\]$/ and $t !~ /\%\].*\[\%/ ) # pure TT entities + || $t =~ /^\s*<\?.*\?>/ # ignore xml prolog + ); } sub token_negligible_p { my ($x) = @_; my $t = $x->type; return !$extract_all_p && ( - $t == C4::TmplTokenType::TEXT() ? string_negligible_p( $x->string ) + $t == C4::TmplTokenType::TEXT() ? string_negligible_p( $x->string ) : $t == C4::TmplTokenType::DIRECTIVE() ? 1 : $t == C4::TmplTokenType::TEXT_PARAMETRIZED() && join( '', map { my $t = $_->type; - $t == C4::TmplTokenType::DIRECTIVE() ? '1' - : $t == C4::TmplTokenType::TAG() ? '' - : token_negligible_p($_) ? '' - : '1' + $t == C4::TmplTokenType::DIRECTIVE() ? '1' + : $t == C4::TmplTokenType::TAG() ? '' + : token_negligible_p($_) ? '' + : '1' } @{ $x->children } ) eq '' ); @@ -86,12 +86,13 @@ sub token_negligible_p { ############################################################################### sub remember { - my($token, $string) = @_; + my ( $token, $string ) = @_; + # If we determine that the string is negligible, don't bother to remember - unless (string_negligible_p( $string ) || token_negligible_p( $token )) { - my $key = TmplTokenizer::string_canon( $string ); + unless ( string_negligible_p($string) || token_negligible_p($token) ) { + my $key = TmplTokenizer::string_canon($string); $text{$key} = [] unless defined $text{$key}; - push @{$text{$key}}, $token; + push @{ $text{$key} }, $token; } } @@ -99,62 +100,66 @@ sub remember { sub string_list { my @t = keys %text; + # The real gettext tools seems to sort case sensitively; I don't know why @t = sort { $a cmp $b } @t if $sort eq 's'; @t = sort { - my @aa = sort { $a->pathname cmp $b->pathname - || $a->line_number <=> $b->line_number } @{$text{$a}}; - my @bb = sort { $a->pathname cmp $b->pathname - || $a->line_number <=> $b->line_number } @{$text{$b}}; - $aa[0]->pathname cmp $bb[0]->pathname - || $aa[0]->line_number <=> $bb[0]->line_number; - } @t if $sort eq 'F'; + my @aa = sort { $a->pathname cmp $b->pathname || $a->line_number <=> $b->line_number } @{ $text{$a} }; + my @bb = sort { $a->pathname cmp $b->pathname || $a->line_number <=> $b->line_number } @{ $text{$b} }; + $aa[0]->pathname cmp $bb[0]->pathname + || $aa[0]->line_number <=> $bb[0]->line_number; + } @t if $sort eq 'F'; return @t; } - ############################################################################### +############################################################################### sub text_extract { - my($h) = @_; - for (;;) { + my ($h) = @_; + for ( ; ; ) { my $s = TmplTokenizer::next_token($h); last unless defined $s; - my($kind, $t, $attr) = ($s->type, $s->string, $s->attributes); + my ( $kind, $t, $attr ) = ( $s->type, $s->string, $s->attributes ); die sprintf( "Incorrect structure found at %s:%s: '%s'", $s->pathname, $s->line_number, $s->string ) if $kind eq C4::TmplTokenType::TAG && !$attr; - if ($kind eq C4::TmplTokenType::TEXT) { - if ($t =~ /\S/s && $t !~ /form =~ /\S/s && $s->form !~ /form ); - } - } elsif ($kind eq C4::TmplTokenType::TAG && %$attr) { + if ( $kind eq C4::TmplTokenType::TEXT ) { + if ( $t =~ /\S/s && $t !~ /form =~ /\S/s && $s->form !~ /form ); + } + } elsif ( $kind eq C4::TmplTokenType::TAG && %$attr ) { + # value [tag=input], meta my $tag; $tag = lc($1) if $t =~ /^<(\S+)/s; - for my $a ('alt', 'title', 'value', 'label', 'placeholder', 'aria-label') { - if ($attr->{$a}) { + for my $a ( 'alt', 'title', 'value', 'label', 'placeholder', 'aria-label' ) { + if ( $attr->{$a} ) { next if $a eq 'label' && $tag ne 'optgroup'; - next if $a eq 'value' && ($tag ne 'input' - || (ref $attr->{'type'} && $attr->{'type'}->[1] =~ /^(?:hidden|radio|checkbox)$/)); # FIXME + next + if $a eq 'value' + && ( $tag ne 'input' + || ( ref $attr->{'type'} && $attr->{'type'}->[1] =~ /^(?:hidden|radio|checkbox)$/ ) ); # FIXME next if $tag eq 'meta'; - my($key, $val, $val_orig, $order) = @{$attr->{$a}}; #FIXME + my ( $key, $val, $val_orig, $order ) = @{ $attr->{$a} }; #FIXME $val = TmplTokenizer::trim($val); + # for selected attributes replace '[%..%]' with '%s' globally if ( $a =~ /title|value|alt|placeholder|aria-label/ ) { $val =~ s/\[\%.*?\%\]/\%s/g; } + # save attribute text for translation remember( $s, $val ) if $val =~ /\S/s; } } - } elsif ($s->has_js_data) { - for my $t (@{$s->js_data}) { - remember( $s, $t->[3] ) if $t->[0]; # FIXME + } elsif ( $s->has_js_data ) { + for my $t ( @{ $s->js_data } ) { + remember( $s, $t->[3] ) if $t->[0]; # FIXME } } } @@ -163,13 +168,15 @@ sub text_extract { ############################################################################### sub generate_po_file { + # We don't emit the Plural-Forms header; it's meaningless for us - my $pot_charset = (defined $charset_out? $charset_out: 'CHARSET'); + my $pot_charset = ( defined $charset_out ? $charset_out : 'CHARSET' ); $pot_charset = TmplTokenizer::charset_canon($pot_charset); + # Time stamps aren't exactly right semantically. I don't know how to fix it. - my $time = POSIX::strftime('%Y-%m-%d %H:%M%z', localtime(time)); + my $time = POSIX::strftime( '%Y-%m-%d %H:%M%z', localtime(time) ); my $time_pot = $time; - my $time_po = $po_mode_p? $time: 'YEAR-MO-DA HO:MI+ZONE'; + my $time_po = $po_mode_p ? $time : 'YEAR-MO-DA HO:MI+ZONE'; print $OUTPUT <pathname cmp $b->pathname - || $a->line_number cmp $b->line_number - } @{$text{$t}}; + my @ordered_tokens = + sort { $a->pathname cmp $b->pathname || $a->line_number cmp $b->line_number } @{ $text{$t} }; my $token = $ordered_tokens[0]; if ( $token->type == C4::TmplTokenType::TEXT_PARAMETRIZED ) { @@ -210,16 +215,14 @@ EOF $n += 1; my $type = $param->type; my $subtype = ( $type == C4::TmplTokenType::TAG - && $param->string =~ /^attributes->{'type'}->[1] : undef ); + && $param->string =~ /^attributes->{'type'}->[1] : undef ); my $fmt = TmplTokenizer::_formalize($param); $fmt =~ s/^%/%$n\$/; if ( $type == C4::TmplTokenType::DIRECTIVE ) { # $type = "Template::Toolkit Directive"; $type = $param->string =~ /\[%(.*?)%\]/is ? $1 : 'ERROR'; - my $name = $param->string =~ /\bname=(["']?)([^\s"']+)\1/is? - $2: undef; + my $name = $param->string =~ /\bname=(["']?)([^\s"']+)\1/is ? $2 : undef; printf $OUTPUT "#. %s: %s\n", $fmt, "$type" . ( defined $name ? " name=$name" : '' ); } else { @@ -227,7 +230,8 @@ EOF my $value; $value = $param->attributes->{'value'} unless $subtype =~ /^(?:text)$/; - printf $OUTPUT "#. %s: %s\n", $fmt, "type=$subtype" + printf $OUTPUT "#. %s: %s\n", $fmt, + "type=$subtype" . ( defined $name ? " name=$name->[1]" : '' ) . ( defined $value ? " value=$value->[1]" : '' ); } @@ -240,12 +244,10 @@ EOF print $OUTPUT "#. META http-equiv=$type\n" if defined $type; } elsif ( $token->string =~ /^<([a-z0-9]+)/is ) { my $tag = uc($1); - my $type = ( lc($tag) eq 'input'? - $token->attributes->{'type'}: undef ); + my $type = ( lc($tag) eq 'input' ? $token->attributes->{'type'} : undef ); my $name = $token->attributes->{'name'}; - printf $OUTPUT "#. %s\n", $tag - . (defined $type? " type=$type->[1]": '') - . (defined $name? " name=$name->[1]": ''); + printf $OUTPUT "#. %s\n", + $tag . ( defined $type ? " type=$type->[1]" : '' ) . ( defined $name ? " name=$name->[1]" : '' ); } } elsif ( $token->has_js_data ) { printf $OUTPUT "#. For the first occurrence,\n" if @{ $text{$t} } > 1; @@ -270,7 +272,7 @@ EOF printf $OUTPUT "#, c-format\n" if $cformat_p; my $msgid = TmplTokenizer::string_canon( TmplTokenizer::charset_convert( $t, $charset_in, $charset_out ) ); - printf $OUTPUT "msgid %s\n", ( defined $msgid && length $msgid ? Locale::PO->quote($msgid) : q{""} ); + printf $OUTPUT "msgid %s\n", ( defined $msgid && length $msgid ? Locale::PO->quote($msgid) : q{""} ); printf $OUTPUT "msgstr %s\n\n", ( defined $translation{$t} ? Locale::PO->quote( $translation{$t} ) : q{""} ); } } @@ -278,38 +280,39 @@ EOF ############################################################################### sub convert_translation_file { - open(my $INPUT, '<:encoding(utf-8)', $convert_from) || die "$convert_from: $!\n"; + open( my $INPUT, '<:encoding(utf-8)', $convert_from ) || die "$convert_from: $!\n"; VerboseWarnings::set_input_file_name($convert_from); while (<$INPUT>) { - chomp; - my($msgid, $msgstr) = split(/\t/); - die "$convert_from: $.: Malformed tmpl_process input (no tab)\n" - unless defined $msgstr; + chomp; + my ( $msgid, $msgstr ) = split(/\t/); + die "$convert_from: $.: Malformed tmpl_process input (no tab)\n" + unless defined $msgstr; - # Fixup some of the bad strings - $msgid =~ s/^SELECTED>//; + # Fixup some of the bad strings + $msgid =~ s/^SELECTED>//; - # Create dummy token - my $token = TmplToken->new( $msgid, C4::TmplTokenType::UNKNOWN, undef, undef ); - remember( $token, $msgid ); - $msgstr =~ s/^(?:LIMIT;|LIMITED;)//g; # unneeded for tmpl_process3 - $translation{$msgid} = $msgstr unless $msgstr eq '*****'; + # Create dummy token + my $token = TmplToken->new( $msgid, C4::TmplTokenType::UNKNOWN, undef, undef ); + remember( $token, $msgid ); + $msgstr =~ s/^(?:LIMIT;|LIMITED;)//g; # unneeded for tmpl_process3 + $translation{$msgid} = $msgstr unless $msgstr eq '*****'; - if ($msgid =~ /\bcharset=(["']?)([^;\s"']+)\1/s) { - my $candidate = TmplTokenizer::charset_canon($2); - die "Conflicting charsets in msgid: $candidate vs $charset_in\n" - if defined $charset_in && $charset_in ne $candidate; - $charset_in = $candidate; - } - if ($msgstr =~ /\bcharset=(["']?)([^;\s"']+)\1/s) { - my $candidate = TmplTokenizer::charset_canon($2); - die "Conflicting charsets in msgid: $candidate vs $charset_out\n" - if defined $charset_out && $charset_out ne $candidate; - $charset_out = $candidate; - } + if ( $msgid =~ /\bcharset=(["']?)([^;\s"']+)\1/s ) { + my $candidate = TmplTokenizer::charset_canon($2); + die "Conflicting charsets in msgid: $candidate vs $charset_in\n" + if defined $charset_in && $charset_in ne $candidate; + $charset_in = $candidate; + } + if ( $msgstr =~ /\bcharset=(["']?)([^;\s"']+)\1/s ) { + my $candidate = TmplTokenizer::charset_canon($2); + die "Conflicting charsets in msgid: $candidate vs $charset_out\n" + if defined $charset_out && $charset_out ne $candidate; + $charset_out = $candidate; + } } + # The following assumption is correct; that's what HTML::Template assumes - if (!defined $charset_in) { + if ( !defined $charset_in ) { $charset_in = $charset_out = TmplTokenizer::charset_canon('utf-8'); warn "Warning: Can't determine original templates' charset, defaulting to $charset_in\n"; } @@ -318,8 +321,8 @@ sub convert_translation_file { ############################################################################### sub usage { - my($exitcode) = @_; - my $h = $exitcode? *STDERR: *STDOUT; + my ($exitcode) = @_; + my $h = $exitcode ? *STDERR : *STDOUT; print $h < \$extract_all_p, - 'charset=s' => sub { $charset_in = $charset_out = $_[1] }, # INTERNAL - 'convert-from=s' => \$convert_from, - 'D|directory=s' => \$directory, - 'disable-fuzzy' => \$disable_fuzzy_p, # INTERNAL - 'f|files-from=s' => \$files_from, - 'I|input-charset=s' => \$charset_in, # INTERNAL - 'pedantic-warnings|pedantic' => sub { $pedantic_p = 1 }, - 'O|output-charset=s' => \$charset_out, # INTERNAL - 'output|o=s' => \$output, - 'po-mode' => \$po_mode_p, # INTERNAL - 's|sort-output' => sub { $sort = 's' }, - 'F|sort-by-file' => sub { $sort = 'F' }, - 'v|verbose' => \$verbose_p, - 'help' => sub { usage(0) }, + 'a|extract-all' => \$extract_all_p, + 'charset=s' => sub { $charset_in = $charset_out = $_[1] }, # INTERNAL + 'convert-from=s' => \$convert_from, + 'D|directory=s' => \$directory, + 'disable-fuzzy' => \$disable_fuzzy_p, # INTERNAL + 'f|files-from=s' => \$files_from, + 'I|input-charset=s' => \$charset_in, # INTERNAL + 'pedantic-warnings|pedantic' => sub { $pedantic_p = 1 }, + 'O|output-charset=s' => \$charset_out, # INTERNAL + 'output|o=s' => \$output, + 'po-mode' => \$po_mode_p, # INTERNAL + 's|sort-output' => sub { $sort = 's' }, + 'F|sort-by-file' => sub { $sort = 'F' }, + 'v|verbose' => \$verbose_p, + 'help' => sub { usage(0) }, ) || usage_error; VerboseWarnings::set_application_name($0); VerboseWarnings::set_pedantic_mode($pedantic_p); usage_error('Missing mandatory option -f') - unless defined $files_from || defined $convert_from; + unless defined $files_from || defined $convert_from; $directory = '.' unless defined $directory; usage_error('You cannot specify both --convert-from and --files-from') - if defined $convert_from && defined $files_from; + if defined $convert_from && defined $files_from; -if (defined $output && $output ne '-') { +if ( defined $output && $output ne '-' ) { print STDERR "$0: Opening output file \"$output\"\n" if $verbose_p; - open($OUTPUT, '>:encoding(utf-8)', $output) || die "$output: $!\n"; + open( $OUTPUT, '>:encoding(utf-8)', $output ) || die "$output: $!\n"; } else { print STDERR "$0: Outputting to STDOUT...\n" if $verbose_p; - open($OUTPUT, q{>}, "&STDOUT"); + open( $OUTPUT, q{>}, "&STDOUT" ); } -if (defined $files_from) { +if ( defined $files_from ) { print STDERR "$0: Opening input file list \"$files_from\"\n" if $verbose_p; - open(my $INPUT, '<:encoding(utf-8)', $files_from) || die "$files_from: $!\n"; + open( my $INPUT, '<:encoding(utf-8)', $files_from ) || die "$files_from: $!\n"; while (<$INPUT>) { - chomp; - my $input = /^\//? $_: "$directory/$_"; - my $h = TmplTokenizer->new( $input ); - $h->set_allow_cformat( 1 ); - VerboseWarnings::set_input_file_name($input); - print STDERR "$0: Processing file \"$input\"\n" if $verbose_p; - text_extract( $h ); + chomp; + my $input = /^\// ? $_ : "$directory/$_"; + my $h = TmplTokenizer->new($input); + $h->set_allow_cformat(1); + VerboseWarnings::set_input_file_name($input); + print STDERR "$0: Processing file \"$input\"\n" if $verbose_p; + text_extract($h); } close $INPUT; } else { @@ -416,8 +419,7 @@ if (defined $files_from) { generate_po_file; warn "This input will not work with Mozilla standards-compliant mode\n", undef - if TmplTokenizer::syntaxerror_p; - + if TmplTokenizer::syntaxerror_p; exit(-1) if TmplTokenizer::fatal_p; diff --git a/misc/workers/background_jobs_worker.pl b/misc/workers/background_jobs_worker.pl index c034d22ca2..f070c3cf64 100755 --- a/misc/workers/background_jobs_worker.pl +++ b/misc/workers/background_jobs_worker.pl @@ -70,20 +70,20 @@ $SIG{'PIPE'} = 'IGNORE'; # See BZ 35111; added to ignore PIPE error when conn my ( $help, @queues ); my $max_processes = $ENV{MAX_PROCESSES}; -$max_processes ||= C4::Context->config('background_jobs_worker')->{max_processes} if C4::Context->config('background_jobs_worker'); +$max_processes ||= C4::Context->config('background_jobs_worker')->{max_processes} + if C4::Context->config('background_jobs_worker'); $max_processes ||= 1; my $mq_timeout = $ENV{MQ_TIMEOUT} // 10; my $not_found_retries = {}; -my $max_retries = $ENV{MAX_RETRIES} || 10; +my $max_retries = $ENV{MAX_RETRIES} || 10; GetOptions( 'm|max-processes=i' => \$max_processes, - 'h|help' => \$help, - 'queue=s' => \@queues, + 'h|help' => \$help, + 'queue=s' => \@queues, ) || pod2usage(1); - pod2usage(0) if $help; unless (@queues) { @@ -99,7 +99,8 @@ try { my $pm = Parallel::ForkManager->new($max_processes); -if ( $conn ) { +if ($conn) { + # FIXME cf note in Koha::BackgroundJob about $namespace my $namespace = C4::Context->config('memcached_namespace'); for my $queue (@queues) { @@ -113,9 +114,10 @@ if ( $conn ) { } } while (1) { - if ( $conn ) { + if ($conn) { my $frame = $conn->receive_frame( { timeout => $mq_timeout } ); if ( !defined $frame ) { + # timeout or connection issue? $pm->reap_finished_children; next; # will reconnect automatically @@ -123,14 +125,15 @@ while (1) { my $args = try { my $body = $frame->body; - decode_json($body); # TODO Should this be from_json? Check utf8 flag. + decode_json($body); # TODO Should this be from_json? Check utf8 flag. } catch { - Koha::Logger->get({ interface => 'worker' })->warn(sprintf "Frame not processed - %s", $_); + Koha::Logger->get( { interface => 'worker' } )->warn( sprintf "Frame not processed - %s", $_ ); return; }; - unless ( $args ) { - Koha::Logger->get({ interface => 'worker' })->warn(sprintf "Frame does not have correct args, ignoring it"); + unless ($args) { + Koha::Logger->get( { interface => 'worker' } ) + ->warn( sprintf "Frame does not have correct args, ignoring it" ); $conn->nack( { frame => $frame, requeue => 'false' } ); next; } @@ -173,12 +176,13 @@ while (1) { $pm->finish; } else { - my $jobs = Koha::BackgroundJobs->search({ status => 'new', queue => \@queues }); + my $jobs = Koha::BackgroundJobs->search( { status => 'new', queue => \@queues } ); while ( my $job = $jobs->next ) { my $args = try { - $job->json->decode($job->data); + $job->json->decode( $job->data ); } catch { - Koha::Logger->get({ interface => 'worker' })->warn(sprintf "Cannot decode data for job id=%s", $job->id); + Koha::Logger->get( { interface => 'worker' } ) + ->warn( sprintf "Cannot decode data for job id=%s", $job->id ); $job->status('failed')->store; return; }; diff --git a/misc/workers/es_indexer_daemon.pl b/misc/workers/es_indexer_daemon.pl index 9e900b7195..aa2f2a9db2 100755 --- a/misc/workers/es_indexer_daemon.pl +++ b/misc/workers/es_indexer_daemon.pl @@ -64,14 +64,13 @@ use Koha::BackgroundJobs; use Koha::SearchEngine; use Koha::SearchEngine::Indexer; - my ( $help, $batch_size ); my $not_found_retries = {}; -my $max_retries = $ENV{MAX_RETRIES} || 10; +my $max_retries = $ENV{MAX_RETRIES} || 10; GetOptions( - 'h|help' => \$help, + 'h|help' => \$help, 'b|batch_size=s' => \$batch_size ) || pod2usage(1); @@ -81,7 +80,7 @@ $batch_size //= 10; warn "Not using Elasticsearch" unless C4::Context->preference('SearchEngine') eq 'Elasticsearch'; -my $logger = Koha::Logger->get({ interface => 'worker' }); +my $logger = Koha::Logger->get( { interface => 'worker' } ); my $conn; try { @@ -90,7 +89,8 @@ try { warn sprintf "Cannot connect to the message broker, the jobs will be processed anyway (%s)", $_; }; -if ( $conn ) { +if ($conn) { + # FIXME cf note in Koha::BackgroundJob about $namespace my $namespace = C4::Context->config('memcached_namespace'); $conn->subscribe( @@ -110,23 +110,25 @@ my @jobs = (); while (1) { - if ( $conn ) { + if ($conn) { my $frame = $conn->receive_frame; if ( !defined $frame ) { + # maybe log connection problems next; # will reconnect automatically } my $args = try { my $body = $frame->body; - decode_json($body); # TODO Should this be from_json? Check utf8 flag. + decode_json($body); # TODO Should this be from_json? Check utf8 flag. } catch { - Koha::Logger->get({ interface => 'worker' })->warn(sprintf "Frame not processed - %s", $_); + Koha::Logger->get( { interface => 'worker' } )->warn( sprintf "Frame not processed - %s", $_ ); return; }; - unless ( $args ) { - Koha::Logger->get({ interface => 'worker' })->warn(sprintf "Frame does not have correct args, ignoring it"); + unless ($args) { + Koha::Logger->get( { interface => 'worker' } ) + ->warn( sprintf "Frame does not have correct args, ignoring it" ); $conn->nack( { frame => $frame, requeue => 'false' } ); next; } @@ -170,8 +172,7 @@ while (1) { } } else { - @jobs = Koha::BackgroundJobs->search( - { status => 'new', queue => 'elastic_index' } )->as_list; + @jobs = Koha::BackgroundJobs->search( { status => 'new', queue => 'elastic_index' } )->as_list; commit(@jobs); @jobs = (); sleep 10; @@ -186,13 +187,16 @@ sub commit { my @bib_records; my @auth_records; - my $jobs = Koha::BackgroundJobs->search( { id => [ map { $_->id } @jobs ] }); + my $jobs = Koha::BackgroundJobs->search( { id => [ map { $_->id } @jobs ] } ); + # Start - $jobs->update({ - progress => 0, - status => 'started', - started_on => \'NOW()', - }); + $jobs->update( + { + progress => 0, + status => 'started', + started_on => \'NOW()', + } + ); for my $job (@jobs) { my $args = try { @@ -232,9 +236,11 @@ sub commit { } # Finish - $jobs->update({ - progress => 1, - status => 'finished', - ended_on => \'NOW()', - }); + $jobs->update( + { + progress => 1, + status => 'finished', + ended_on => \'NOW()', + } + ); } diff --git a/misc/z3950_responder.pl b/misc/z3950_responder.pl index 3c782c4090..b6afee3521 100755 --- a/misc/z3950_responder.pl +++ b/misc/z3950_responder.pl @@ -20,8 +20,8 @@ use Modern::Perl; use File::Basename qw( fileparse ); -use Getopt::Long qw( GetOptions :config no_ignore_case ); -use Pod::Usage qw( pod2usage ); +use Getopt::Long qw( GetOptions :config no_ignore_case ); +use Pod::Usage qw( pod2usage ); use Koha::Config; use Koha::Z3950Responder; @@ -105,7 +105,7 @@ my $add_status_multi_subfield; my $debug = 0; my $help; my $man; -my $prefetch = 20; +my $prefetch = 20; my $config_dir = ''; my @yaz_options; @@ -117,19 +117,20 @@ sub add_yaz_option { } sub pass_yaz_option { - my ( $opt_name ) = @_; + my ($opt_name) = @_; push @yaz_options, "-$opt_name"; } GetOptions( - '-h|help' => \$help, - '--man' => \$man, - '--debug' => \$debug, - '--add-item-status=s' => \$add_item_status_subfield, + '-h|help' => \$help, + '--man' => \$man, + '--debug' => \$debug, + '--add-item-status=s' => \$add_item_status_subfield, '--add-status-multi-subfield' => \$add_status_multi_subfield, - '--prefetch=i' => \$prefetch, - '--config-dir=s' => \$config_dir, + '--prefetch=i' => \$prefetch, + '--config-dir=s' => \$config_dir, + # Pass through YAZ options. 'a=s' => \&add_yaz_option, 'v=s' => \&add_yaz_option, @@ -143,35 +144,37 @@ GetOptions( 'C=s' => \&add_yaz_option, 'm=s' => \&add_yaz_option, 'w=s' => \&add_yaz_option, - 'z' => \&pass_yaz_option, - 'K' => \&pass_yaz_option, - 'i' => \&pass_yaz_option, - 'D' => \&pass_yaz_option, - 'S' => \&pass_yaz_option, - 'T' => \&pass_yaz_option, - '1' => \&pass_yaz_option + 'z' => \&pass_yaz_option, + 'K' => \&pass_yaz_option, + 'i' => \&pass_yaz_option, + 'D' => \&pass_yaz_option, + 'S' => \&pass_yaz_option, + 'T' => \&pass_yaz_option, + '1' => \&pass_yaz_option ) || pod2usage(2); -pod2usage(1) if $help; +pod2usage(1) if $help; pod2usage( -verbose => 2 ) if $man; # If config_dir is not defined, default to z3950 under the Koha config directory -if (!$config_dir) { - (undef, $config_dir) = fileparse(Koha::Config->guess_koha_conf); +if ( !$config_dir ) { + ( undef, $config_dir ) = fileparse( Koha::Config->guess_koha_conf ); $config_dir .= 'z3950/'; } else { - $config_dir .= '/' if ($config_dir !~ /\/$/); + $config_dir .= '/' if ( $config_dir !~ /\/$/ ); } # Create and start the server. -my $z = Koha::Z3950Responder->new( { - add_item_status_subfield => $add_item_status_subfield, - add_status_multi_subfield => $add_status_multi_subfield, - debug => $debug, - num_to_prefetch => $prefetch, - config_dir => $config_dir, - yaz_options => [ @yaz_options, @ARGV ], -} ); +my $z = Koha::Z3950Responder->new( + { + add_item_status_subfield => $add_item_status_subfield, + add_status_multi_subfield => $add_status_multi_subfield, + debug => $debug, + num_to_prefetch => $prefetch, + config_dir => $config_dir, + yaz_options => [ @yaz_options, @ARGV ], + } +); $z->start(); diff --git a/offline_circ/enqueue_koc.pl b/offline_circ/enqueue_koc.pl index 7e1745008a..d20c37d235 100755 --- a/offline_circ/enqueue_koc.pl +++ b/offline_circ/enqueue_koc.pl @@ -20,9 +20,9 @@ use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Output qw( output_html_with_http_headers ); -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Context; use C4::Accounts; use C4::Circulation qw( AddOfflineOperation ); @@ -32,19 +32,20 @@ use Koha::Checkouts; use Koha::UploadedFiles; use Koha::Items; - # this is the file version number that we're coded against. my $FILE_VERSION = '1.0'; my $query = CGI->new; my @output; -my ($template, $loggedinuser, $cookie) = get_template_and_user({ - template_name => "offline_circ/enqueue_koc.tt", - query => $query, - type => "intranet", - flagsrequired => { circulate => "circulate_remaining_permissions" }, -}); +my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "offline_circ/enqueue_koc.tt", + query => $query, + type => "intranet", + flagsrequired => { circulate => "circulate_remaining_permissions" }, + } +); my $fileID = $query->param('uploadedfileid'); my $op = $query->param('op') // q{}; @@ -53,32 +54,32 @@ my $op = $query->param('op') // q{}; our $dbh = C4::Context->dbh(); if ( $op eq 'cud-enqueue' && $fileID ) { - my $upload = Koha::UploadedFiles->find($fileID); - my $fh = $upload? $upload->file_handle: undef; - my @input_lines = $fh? <$fh>: (); + my $upload = Koha::UploadedFiles->find($fileID); + my $fh = $upload ? $upload->file_handle : undef; + my @input_lines = $fh ? <$fh> : (); $fh->close if $fh; my $header_line = shift @input_lines; my $file_info = parse_header_line($header_line); - if ($file_info->{'Version'} ne $FILE_VERSION) { + if ( $file_info->{'Version'} ne $FILE_VERSION ) { push @output, { - message => 1, + message => 1, ERROR_file_version => 1, - upload_version => $file_info->{'Version'}, - current_version => $FILE_VERSION + upload_version => $file_info->{'Version'}, + current_version => $FILE_VERSION }; } - my $userid = C4::Context->userenv->{id}; + my $userid = C4::Context->userenv->{id}; my $branchcode = C4::Context->userenv->{branch}; - foreach my $line (@input_lines) { + foreach my $line (@input_lines) { my $command_line = parse_command_line($line); - my $timestamp = $command_line->{'date'} . ' ' . $command_line->{'time'}; - my $action = $command_line->{'command'}; - my $barcode = $command_line->{'barcode'}; - my $cardnumber = $command_line->{'cardnumber'}; - my $amount = $command_line->{'amount'}; + my $timestamp = $command_line->{'date'} . ' ' . $command_line->{'time'}; + my $action = $command_line->{'command'}; + my $barcode = $command_line->{'barcode'}; + my $cardnumber = $command_line->{'cardnumber'}; + my $amount = $command_line->{'amount'}; AddOfflineOperation( $userid, $branchcode, $timestamp, $action, $barcode, $cardnumber, $amount ); } @@ -111,7 +112,7 @@ sub parse_header_line { chomp($header_line); $header_line =~ s/\r//g; - my @fields = split( /\t/, $header_line ); + my @fields = split( /\t/, $header_line ); my %header_info = map { split( /=/, $_ ) } @fields; return \%header_info; } @@ -182,7 +183,7 @@ sub _get_borrowernumber_from_barcode { return unless $barcode; - my $item = Koha::Items->find({ barcode => $barcode }); + my $item = Koha::Items->find( { barcode => $barcode } ); return unless $item; my $issue = Koha::Checkouts->find( { itemnumber => $item->itemnumber } ); diff --git a/offline_circ/list.pl b/offline_circ/list.pl index 2838a18530..6883d98b36 100755 --- a/offline_circ/list.pl +++ b/offline_circ/list.pl @@ -20,9 +20,9 @@ use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Output qw( output_html_with_http_headers ); -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Context; use C4::Circulation qw( GetOfflineOperations GetOfflineOperation ); use C4::Members; @@ -32,21 +32,23 @@ use Koha::Items; my $query = CGI->new; -my ($template, $loggedinuser, $cookie) = get_template_and_user({ - template_name => "offline_circ/list.tt", - query => $query, - type => "intranet", - flagsrequired => { circulate => "circulate_remaining_permissions" }, -}); +my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "offline_circ/list.tt", + query => $query, + type => "intranet", + flagsrequired => { circulate => "circulate_remaining_permissions" }, + } +); my $operations = GetOfflineOperations; for (@$operations) { - my $item = $_->{barcode} ? Koha::Items->find({ barcode => $_->{barcode} }) : undef; + my $item = $_->{barcode} ? Koha::Items->find( { barcode => $_->{barcode} } ) : undef; if ($item) { my $biblio = $item->biblio; - $_->{'bibliotitle'} = $biblio->title; - $_->{'biblionumber'} = $biblio->biblionumber; + $_->{'bibliotitle'} = $biblio->title; + $_->{'biblionumber'} = $biblio->biblionumber; } my $patron = @@ -57,12 +59,12 @@ for (@$operations) { if ($patron) { $_->{'borrowernumber'} = $patron->borrowernumber; - $_->{'borrower'} = ($patron->firstname ? $patron->firstname:'').' '.$patron->surname; + $_->{'borrower'} = ( $patron->firstname ? $patron->firstname : '' ) . ' ' . $patron->surname; } - $_->{'actionissue'} = $_->{'action'} eq 'issue'; - $_->{'actionreturn'} = $_->{'action'} eq 'return'; - $_->{'actionpayment'} = $_->{'action'} eq 'payment'; + $_->{'actionissue'} = $_->{'action'} eq 'issue'; + $_->{'actionreturn'} = $_->{'action'} eq 'return'; + $_->{'actionpayment'} = $_->{'action'} eq 'payment'; } -$template->param(pending_operations => $operations); +$template->param( pending_operations => $operations ); output_html_with_http_headers $query, $cookie, $template->output; diff --git a/offline_circ/process.pl b/offline_circ/process.pl index 9e6121aea4..7448a3f391 100755 --- a/offline_circ/process.pl +++ b/offline_circ/process.pl @@ -20,29 +20,31 @@ use Modern::Perl; -use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); use C4::Circulation qw( GetOfflineOperation ProcessOfflineOperation DeleteOfflineOperation ); my $query = CGI->new; -my ($template, $loggedinuser, $cookie) = get_template_and_user({ - template_name => "offline_circ/list.tt", - query => $query, - type => "intranet", - flagsrequired => { circulate => "circulate_remaining_permissions" }, -}); +my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "offline_circ/list.tt", + query => $query, + type => "intranet", + flagsrequired => { circulate => "circulate_remaining_permissions" }, + } +); my $operationid = $query->param('operationid'); -my $op = $query->param('op') || q{}; +my $op = $query->param('op') || q{}; my $result; if ( $op eq 'cud-process' ) { - my $operation = GetOfflineOperation( $operationid ); - $result = ProcessOfflineOperation( $operation ); + my $operation = GetOfflineOperation($operationid); + $result = ProcessOfflineOperation($operation); } elsif ( $op eq 'cud-delete' ) { - $result = DeleteOfflineOperation( $operationid ); + $result = DeleteOfflineOperation($operationid); } -print CGI::header('-type'=>'text/plain', '-charset'=>'utf-8'); +print CGI::header( '-type' => 'text/plain', '-charset' => 'utf-8' ); print $result; diff --git a/offline_circ/process_koc.pl b/offline_circ/process_koc.pl index 84d714fb35..c64c911a18 100755 --- a/offline_circ/process_koc.pl +++ b/offline_circ/process_koc.pl @@ -23,10 +23,10 @@ use Modern::Perl; use CGI qw ( -utf8 ); use C4::Output qw( output_html_with_http_headers ); -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Context; use C4::Circulation qw( barcodedecode AddRenewal AddIssue MarkIssueReturned ); -use C4::Items qw( ModDateLastSeen ); +use C4::Items qw( ModDateLastSeen ); use Koha::UploadedFiles; use Koha::Account; use Koha::Checkouts; @@ -41,50 +41,51 @@ my $FILE_VERSION = '1.0'; our $query = CGI->new; -my ($template, $loggedinuser, $cookie) = get_template_and_user({ - template_name => "offline_circ/process_koc.tt", - query => $query, - type => "intranet", - flagsrequired => { circulate => "circulate_remaining_permissions" }, -}); +my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "offline_circ/process_koc.tt", + query => $query, + type => "intranet", + flagsrequired => { circulate => "circulate_remaining_permissions" }, + } +); - -my $fileID=$query->param('uploadedfileid'); -my $op = $query->param('op') || q{}; -my %cookies = CGI::Cookie->fetch(); +my $fileID = $query->param('uploadedfileid'); +my $op = $query->param('op') || q{}; +my %cookies = CGI::Cookie->fetch(); my $sessionID = $cookies{'CGISESSID'}->value; ## 'Local' globals. -our $dbh = C4::Context->dbh(); -our @output = (); ## For storing messages to be displayed to the user +our $dbh = C4::Context->dbh(); +our @output = (); ## For storing messages to be displayed to the user if ( $op eq 'cud-upload' && $fileID ) { - my $upload = Koha::UploadedFiles->find( $fileID ); - my $fh = $upload? $upload->file_handle: undef; - my $filename = $upload? $upload->filename: undef; - my @input_lines = $fh? <$fh>: (); + my $upload = Koha::UploadedFiles->find($fileID); + my $fh = $upload ? $upload->file_handle : undef; + my $filename = $upload ? $upload->filename : undef; + my @input_lines = $fh ? <$fh> : (); $fh->close if $fh; my $header_line = shift @input_lines; my $file_info = parse_header_line($header_line); - if ($file_info->{'Version'} ne $FILE_VERSION) { + if ( $file_info->{'Version'} ne $FILE_VERSION ) { push @output, { - message => 1, + message => 1, ERROR_file_version => 1, - upload_version => $file_info->{'Version'}, - current_version => $FILE_VERSION + upload_version => $file_info->{'Version'}, + current_version => $FILE_VERSION }; } my $i = 0; - foreach my $line (@input_lines) { + foreach my $line (@input_lines) { $i++; my $command_line = parse_command_line($line); # map command names in the file to subroutine names my %dispatch_table = ( - issue => \&kocIssueItem, - 'return' => \&kocReturnItem, - payment => \&kocMakePayment, + issue => \&kocIssueItem, + 'return' => \&kocReturnItem, + payment => \&kocMakePayment, ); # call the right sub name, passing the hashref of command_line to it. @@ -95,8 +96,8 @@ if ( $op eq 'cud-upload' && $fileID ) { } } - $template->param(transactions_loaded => 1); - $template->param(messages => \@output); + $template->param( transactions_loaded => 1 ); + $template->param( messages => \@output ); } output_html_with_http_headers $query, $cookie, $template->output; @@ -123,7 +124,7 @@ sub parse_header_line { chomp($header_line); $header_line =~ s/\r//g; - my @fields = split( /\t/, $header_line ); + my @fields = split( /\t/, $header_line ); my %header_info = map { split( /=/, $_ ) } @fields; return \%header_info; } @@ -187,16 +188,16 @@ sub kocIssueItem { $circ->{barcode} = barcodedecode( $circ->{barcode} ) if $circ->{barcode}; my $branchcode = C4::Context->userenv->{branch}; - my $patron = Koha::Patrons->find( { cardnumber => $circ->{cardnumber} } ); - my $item = Koha::Items->find({ barcode => $circ->{barcode} }); - my $issue = Koha::Checkouts->find( { itemnumber => $item->itemnumber } ); - my $biblio = $item->biblio; + my $patron = Koha::Patrons->find( { cardnumber => $circ->{cardnumber} } ); + my $item = Koha::Items->find( { barcode => $circ->{barcode} } ); + my $issue = Koha::Checkouts->find( { itemnumber => $item->itemnumber } ); + my $biblio = $item->biblio; - if ( $issue ) { ## Item is currently checked out to another person. - #warn "Item Currently Issued."; + if ($issue) { ## Item is currently checked out to another person. + #warn "Item Currently Issued."; - if ( $issue->borrowernumber eq $patron->borrowernumber ) { ## Issued to this person already, renew it. - #warn "Item issued to this member already, renewing."; + if ( $issue->borrowernumber eq $patron->borrowernumber ) { ## Issued to this person already, renew it. + #warn "Item issued to this member already, renewing."; C4::Circulation::AddRenewal( { @@ -207,70 +208,73 @@ sub kocIssueItem { ) unless (DEBUG); push @output, { - renew => 1, - title => $biblio->title, - biblionumber => $biblio->biblionumber, - barcode => $item->barcode, - firstname => $patron->firstname, - surname => $patron->surname, + renew => 1, + title => $biblio->title, + biblionumber => $biblio->biblionumber, + barcode => $item->barcode, + firstname => $patron->firstname, + surname => $patron->surname, borrowernumber => $patron->borrowernumber, - cardnumber => $patron->cardnumber, - datetime => $circ->datetime + cardnumber => $patron->cardnumber, + datetime => $circ->datetime }; } else { + #warn "Item issued to a different member."; #warn "Date of previous issue: $issue->issuedate"; #warn "Date of this issue: $circ->{'date'}"; my ( $i_y, $i_m, $i_d ) = split( /-/, $issue->issuedate ); my ( $c_y, $c_m, $c_d ) = split( /-/, $circ->{'date'} ); - if ( Date_to_Days( $i_y, $i_m, $i_d ) < Date_to_Days( $c_y, $c_m, $c_d ) ) { ## Current issue to a different persion is older than this issue, return and issue. - C4::Circulation::AddIssue( $patron, $circ->{'barcode'}, undef, undef, $circ->{'date'} ) unless ( DEBUG ); + if ( Date_to_Days( $i_y, $i_m, $i_d ) < Date_to_Days( $c_y, $c_m, $c_d ) ) + { ## Current issue to a different persion is older than this issue, return and issue. + C4::Circulation::AddIssue( $patron, $circ->{'barcode'}, undef, undef, $circ->{'date'} ) unless (DEBUG); push @output, { - issue => 1, - title => $biblio->title, - biblionumber => $biblio->biblionumber, - barcode => $item->barcode, - firstname => $patron->firstname, - surname => $patron->surname, + issue => 1, + title => $biblio->title, + biblionumber => $biblio->biblionumber, + barcode => $item->barcode, + firstname => $patron->firstname, + surname => $patron->surname, borrowernumber => $patron->borrowernumber, - cardnumber => $patron->cardnumber, - datetime => $circ->datetime + cardnumber => $patron->cardnumber, + datetime => $circ->datetime }; - } else { ## Current issue is *newer* than this issue, write a 'returned' issue, as the item is most likely in the hands of someone else now. - #warn "Current issue to another member is newer. Doing nothing"; + } else + { ## Current issue is *newer* than this issue, write a 'returned' issue, as the item is most likely in the hands of someone else now. + #warn "Current issue to another member is newer. Doing nothing"; ## This situation should only happen of the Offline Circ data is *really* old. ## FIXME: write line to old_issues and statistics } } - } else { ## Item is not checked out to anyone at the moment, go ahead and issue it - C4::Circulation::AddIssue( $patron, $circ->{'barcode'}, undef, undef, $circ->{'date'} ) unless ( DEBUG ); + } else { ## Item is not checked out to anyone at the moment, go ahead and issue it + C4::Circulation::AddIssue( $patron, $circ->{'barcode'}, undef, undef, $circ->{'date'} ) unless (DEBUG); push @output, { - issue => 1, - title => $biblio->title, - biblionumber => $biblio->biblionumber, - barcode => $item->barcode, - firstname => $patron->firstname, - surname => $patron->surname, + issue => 1, + title => $biblio->title, + biblionumber => $biblio->biblionumber, + barcode => $item->barcode, + firstname => $patron->firstname, + surname => $patron->surname, borrowernumber => $patron->borrowernumber, - cardnumber => $patron->cardnumber, - datetime =>$circ->datetime + cardnumber => $patron->cardnumber, + datetime => $circ->datetime }; } } sub kocReturnItem { - my ( $circ ) = @_; + my ($circ) = @_; $circ->{barcode} = barcodedecode( $circ->{barcode} ) if $circ->{barcode}; - my $item = Koha::Items->find({ barcode => $circ->{barcode} }); - my $biblio = $item->biblio; + my $item = Koha::Items->find( { barcode => $circ->{barcode} } ); + my $biblio = $item->biblio; my $borrowernumber = _get_borrowernumber_from_barcode( $circ->{'barcode'} ); - if ( $borrowernumber ) { - my $patron = Koha::Patrons->find( $borrowernumber ); + if ($borrowernumber) { + my $patron = Koha::Patrons->find($borrowernumber); C4::Circulation::MarkIssueReturned( $borrowernumber, $item->itemnumber, @@ -282,7 +286,7 @@ sub kocReturnItem { ModDateLastSeen( $item->itemnumber ); push @output, - { + { return => 1, title => $biblio->title, biblionumber => $biblio->biblionumber, @@ -292,11 +296,11 @@ sub kocReturnItem { surname => $patron->surname, cardnumber => $patron->cardnumber, datetime => $circ->{'datetime'} - }; + }; } else { push @output, { ERROR_no_borrower_from_item => 1, - badbarcode => $circ->{'barcode'} + badbarcode => $circ->{'barcode'} }; } } @@ -305,22 +309,22 @@ sub kocMakePayment { my ($circ) = @_; my $cardnumber = $circ->{cardnumber}; - my $amount = $circ->{amount}; + my $amount = $circ->{amount}; my $patron = Koha::Patrons->find( { cardnumber => $cardnumber } ); Koha::Account->new( { patron_id => $patron->id } ) - ->pay( { amount => $amount, interface => C4::Context->interface } ); + ->pay( { amount => $amount, interface => C4::Context->interface } ); push @output, - { + { payment => 1, amount => $circ->{'amount'}, firstname => $patron->firstname, surname => $patron->surname, cardnumber => $patron->cardnumber, borrower => $patron->id, - }; + }; } =head2 _get_borrowernumber_from_barcode @@ -336,7 +340,7 @@ sub _get_borrowernumber_from_barcode { return unless $barcode; - my $item = Koha::Items->find({ barcode => $barcode }); + my $item = Koha::Items->find( { barcode => $barcode } ); return unless $item; my $issue = Koha::Checkouts->find( { itemnumber => $item->itemnumber } ); diff --git a/offline_circ/service.pl b/offline_circ/service.pl index 2d7ad951db..2897a139dd 100755 --- a/offline_circ/service.pl +++ b/offline_circ/service.pl @@ -20,8 +20,8 @@ use Modern::Perl; -use CGI qw ( -utf8 ); -use C4::Auth qw( check_api_auth check_cookie_auth ); +use CGI qw ( -utf8 ); +use C4::Auth qw( check_api_auth check_cookie_auth ); use C4::Circulation qw( AddOfflineOperation ProcessOfflineOperation ); use Koha::DateUtils qw( dt_from_string ); use DateTime::TimeZone; @@ -33,12 +33,12 @@ my $cgi = CGI->new; my $nocookie = $cgi->param('nocookie') || 0; # get the status of the user, this will check his credentials and rights -my ($status, $cookie, $sessionId) = C4::Auth::check_api_auth($cgi, undef); -($status) = C4::Auth::check_cookie_auth($cgi, undef) if ($status ne 'ok' && !$nocookie); +my ( $status, $cookie, $sessionId ) = C4::Auth::check_api_auth( $cgi, undef ); +($status) = C4::Auth::check_cookie_auth( $cgi, undef ) if ( $status ne 'ok' && !$nocookie ); my $result; -if ($status eq 'ok') { # if authentication is ok +if ( $status eq 'ok' ) { # if authentication is ok my $userid = $cgi->param('userid') || ''; my $branchcode = $cgi->param('branchcode') || ''; @@ -46,18 +46,19 @@ if ($status eq 'ok') { # if authentication is ok my $action = $cgi->param('action') || ''; my $barcode = $cgi->param('barcode') || ''; my $amount = $cgi->param('amount') || 0; - $barcode =~ s/^\s+//; - $barcode =~ s/\s+$//; + $barcode =~ s/^\s+//; + $barcode =~ s/\s+$//; my $cardnumber = $cgi->param('cardnumber') || ''; $cardnumber =~ s/^\s+//; $cardnumber =~ s/\s+$//; # KOCT send UTC timestamp, it should be converted to local timezone - my $dt = dt_from_string($timestamp, 'iso', DateTime::TimeZone->new(name => 'UTC')); - $dt->set_time_zone(C4::Context->tz); + my $dt = dt_from_string( $timestamp, 'iso', DateTime::TimeZone->new( name => 'UTC' ) ); + $dt->set_time_zone( C4::Context->tz ); $timestamp = $dt->ymd('-') . ' ' . $dt->hms(':'); - if ( $cgi->param('pending') eq 'true' ) { # if the 'pending' flag is true, we store the operation in the db instead of directly processing them + if ( $cgi->param('pending') eq 'true' ) + { # if the 'pending' flag is true, we store the operation in the db instead of directly processing them $result = AddOfflineOperation( $userid, $branchcode, @@ -70,21 +71,21 @@ if ($status eq 'ok') { # if authentication is ok } else { $result = ProcessOfflineOperation( { - 'userid' => $userid, - 'branchcode' => $branchcode, - 'timestamp' => $timestamp, - 'action' => $action, - 'barcode' => $barcode, - 'cardnumber' => $cardnumber, - 'amount' => $amount + 'userid' => $userid, + 'branchcode' => $branchcode, + 'timestamp' => $timestamp, + 'action' => $action, + 'barcode' => $barcode, + 'cardnumber' => $cardnumber, + 'amount' => $amount } ); } - print CGI::header('-type'=>'text/plain', '-charset'=>'utf-8'); + print CGI::header( '-type' => 'text/plain', '-charset' => 'utf-8' ); print $result; exit; } -print CGI::header('-type'=>'text/plain', '-charset'=>'utf-8', '-status' => '401 Unauthorized'); +print CGI::header( '-type' => 'text/plain', '-charset' => 'utf-8', '-status' => '401 Unauthorized' ); print $result; diff --git a/opac/clubs/clubs-tab.pl b/opac/clubs/clubs-tab.pl index 8c3f758375..61344314c6 100755 --- a/opac/clubs/clubs-tab.pl +++ b/opac/clubs/clubs-tab.pl @@ -21,7 +21,7 @@ use Modern::Perl; use CGI; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use Koha::Patrons; @@ -29,9 +29,9 @@ my $cgi = CGI->new; my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "clubs/clubs-tab.tt", - query => $cgi, - type => "opac", + template_name => "clubs/clubs-tab.tt", + query => $cgi, + type => "opac", } ); @@ -40,7 +40,7 @@ my $borrowernumber = $cgi->param('borrowernumber'); my $borrower = Koha::Patrons->find($borrowernumber); my @enrollments = $borrower->get_club_enrollments->as_list; -my @clubs = $borrower->get_enrollable_clubs( my $opac = 1 )->as_list; +my @clubs = $borrower->get_enrollable_clubs( my $opac = 1 )->as_list; $template->param( enrollments => \@enrollments, diff --git a/opac/clubs/enroll.pl b/opac/clubs/enroll.pl index a71990196f..2f04417fca 100755 --- a/opac/clubs/enroll.pl +++ b/opac/clubs/enroll.pl @@ -21,7 +21,7 @@ use Modern::Perl; use CGI; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use Koha::Clubs; @@ -29,9 +29,9 @@ my $cgi = CGI->new; my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "clubs/enroll.tt", - query => $cgi, - type => "opac", + template_name => "clubs/enroll.tt", + query => $cgi, + type => "opac", } ); diff --git a/opac/errors/400.pl b/opac/errors/400.pl index e34e18c092..e993018172 100755 --- a/opac/errors/400.pl +++ b/opac/errors/400.pl @@ -15,10 +15,9 @@ # You should have received a copy of the GNU General Public License # along with Koha; if not, see . - use Modern::Perl; -use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_with_http_headers ); use C4::Context; use List::MoreUtils qw( any ); @@ -33,7 +32,7 @@ my ( $template, $loggedinuser, $cookie ) = get_template_and_user( authnotrequired => 1, } ); -$template->param ( +$template->param( admin => $admin, errno => 400, ); @@ -41,6 +40,7 @@ my $status = '400 Bad Request'; if ( C4::Context->is_internal_PSGI_request() ) { $status = '200 OK'; } + #NOTE: We're not setting/updating the cookie here $cookie = ''; output_with_http_headers $query, $cookie, $template->output, 'html', $status; diff --git a/opac/errors/401.pl b/opac/errors/401.pl index 432691859b..6a397fb773 100755 --- a/opac/errors/401.pl +++ b/opac/errors/401.pl @@ -15,10 +15,9 @@ # You should have received a copy of the GNU General Public License # along with Koha; if not, see . - use Modern::Perl; -use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_with_http_headers ); use C4::Context; use List::MoreUtils qw( any ); @@ -33,7 +32,7 @@ my ( $template, $loggedinuser, $cookie ) = get_template_and_user( authnotrequired => 1, } ); -$template->param ( +$template->param( admin => $admin, errno => 401, ); @@ -41,6 +40,7 @@ my $status = '401 Unauthorized'; if ( C4::Context->is_internal_PSGI_request() ) { $status = '200 OK'; } + #NOTE: We're not setting/updating the cookie here $cookie = ''; output_with_http_headers $query, $cookie, $template->output, 'html', $status; diff --git a/opac/errors/402.pl b/opac/errors/402.pl index edc710860b..e582bfd279 100755 --- a/opac/errors/402.pl +++ b/opac/errors/402.pl @@ -15,10 +15,9 @@ # You should have received a copy of the GNU General Public License # along with Koha; if not, see . - use Modern::Perl; -use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_with_http_headers ); use C4::Context; use List::MoreUtils qw( any ); @@ -33,7 +32,7 @@ my ( $template, $loggedinuser, $cookie ) = get_template_and_user( authnotrequired => 1, } ); -$template->param ( +$template->param( admin => $admin, errno => 402, ); @@ -41,6 +40,7 @@ my $status = '402 Payment Required'; if ( C4::Context->is_internal_PSGI_request() ) { $status = '200 OK'; } + #NOTE: We're not setting/updating the cookie here $cookie = ''; output_with_http_headers $query, $cookie, $template->output, 'html', $status; diff --git a/opac/errors/403.pl b/opac/errors/403.pl index 3a3fb24118..9c49ee330c 100755 --- a/opac/errors/403.pl +++ b/opac/errors/403.pl @@ -15,10 +15,9 @@ # You should have received a copy of the GNU General Public License # along with Koha; if not, see . - use Modern::Perl; -use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_with_http_headers ); use C4::Context; use List::MoreUtils qw( any ); @@ -33,9 +32,9 @@ my ( $template, $loggedinuser, $cookie ) = get_template_and_user( authnotrequired => 1, } ); -$template->param ( - admin => $admin, - errno => 403, +$template->param( + admin => $admin, + errno => 403, csrf_error => $ENV{'plack.middleware.Koha.CSRF'}, ); @@ -43,6 +42,7 @@ my $status = '403 Forbidden'; if ( C4::Context->is_internal_PSGI_request() ) { $status = '200 OK'; } + #NOTE: We're not setting/updating the cookie here $cookie = ''; output_with_http_headers $query, $cookie, $template->output, 'html', $status; diff --git a/opac/errors/404.pl b/opac/errors/404.pl index 4d4b687385..23eb462114 100755 --- a/opac/errors/404.pl +++ b/opac/errors/404.pl @@ -15,10 +15,9 @@ # You should have received a copy of the GNU General Public License # along with Koha; if not, see . - use Modern::Perl; -use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_with_http_headers ); use C4::Context; use List::MoreUtils qw( any ); @@ -33,7 +32,7 @@ my ( $template, $loggedinuser, $cookie ) = get_template_and_user( authnotrequired => 1, } ); -$template->param ( +$template->param( admin => $admin, errno => 404, ); @@ -41,6 +40,7 @@ my $status = '404 Not Found'; if ( C4::Context->is_internal_PSGI_request() ) { $status = '200 OK'; } + #NOTE: We're not setting/updating the cookie here $cookie = ''; output_with_http_headers $query, $cookie, $template->output, 'html', $status; diff --git a/opac/errors/500.pl b/opac/errors/500.pl index b0985be6bf..0c7515d32b 100755 --- a/opac/errors/500.pl +++ b/opac/errors/500.pl @@ -15,10 +15,9 @@ # You should have received a copy of the GNU General Public License # along with Koha; if not, see . - use Modern::Perl; -use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_with_http_headers ); use C4::Context; use List::MoreUtils qw( any ); @@ -33,7 +32,7 @@ my ( $template, $loggedinuser, $cookie ) = get_template_and_user( authnotrequired => 1, } ); -$template->param ( +$template->param( admin => $admin, errno => 500, ); @@ -41,6 +40,7 @@ my $status = '500 Internal Server Error'; if ( C4::Context->is_internal_PSGI_request() ) { $status = '200 OK'; } + #NOTE: We're not setting/updating the cookie here $cookie = ''; output_with_http_headers $query, $cookie, $template->output, 'html', $status; diff --git a/opac/external/overdrive/auth.pl b/opac/external/overdrive/auth.pl index d70f574681..49b4d32de4 100755 --- a/opac/external/overdrive/auth.pl +++ b/opac/external/overdrive/auth.pl @@ -25,31 +25,29 @@ use URI::Escape qw( uri_escape ); use Koha::Logger; use Koha::ExternalContent::OverDrive; -my $logger = Koha::Logger->get({ interface => 'opac' }); -my $cgi = CGI->new; +my $logger = Koha::Logger->get( { interface => 'opac' } ); +my $cgi = CGI->new; my ( $user, $cookie, $sessionID, $flags ) = checkauth( $cgi, 1, {}, 'opac' ); -my ($redirect_page, $error); -if ($user && $sessionID) { - my $od = Koha::ExternalContent::OverDrive->new({ koha_session_id => $sessionID }); +my ( $redirect_page, $error ); +if ( $user && $sessionID ) { + my $od = Koha::ExternalContent::OverDrive->new( { koha_session_id => $sessionID } ); if ( my $auth_code = $cgi->param('code') ) { - my $base_url = $cgi->url(-base => 1); + my $base_url = $cgi->url( -base => 1 ); local $@; - $redirect_page = eval { $od->auth_by_code($auth_code, $base_url) }; + $redirect_page = eval { $od->auth_by_code( $auth_code, $base_url ) }; if ($@) { $logger->error($@); $error = $od->error_message($@); } - } - else { + } else { $error = "Missing OverDrive auth code"; } $redirect_page ||= $od->get_return_page_from_koha_session; -} -else { +} else { $error = "User not logged in"; } $redirect_page ||= "/cgi-bin/koha/opac-user.pl"; my $uri = URI->new($redirect_page); -$uri->query_form( $uri->query_form, overdrive_tab => 1, overdrive_error => uri_escape($error || "") ); +$uri->query_form( $uri->query_form, overdrive_tab => 1, overdrive_error => uri_escape( $error || "" ) ); print $cgi->redirect($redirect_page); diff --git a/opac/ilsdi.pl b/opac/ilsdi.pl index 4cf4818aa4..280b7ab83c 100755 --- a/opac/ilsdi.pl +++ b/opac/ilsdi.pl @@ -20,13 +20,13 @@ use Modern::Perl; use C4::ILSDI::Services; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use C4::Context; use List::MoreUtils qw( any ); -use XML::Simple qw( XMLout ); -use CGI qw ( -utf8 ); +use XML::Simple qw( XMLout ); +use CGI qw ( -utf8 ); use Net::Netmask; =head1 DLF ILS-DI for Koha @@ -54,7 +54,7 @@ my @services = ( # Level 2: Elementary OPAC supplement # 'HarvestAuthorityRecords', # OAI-PMH # 'HarvestHoldingsRecords', # OAI-PMH - 'GetRecords', # Note that we can use OAI-PMH for this too + 'GetRecords', # Note that we can use OAI-PMH for this too # 'Search', # TODO # 'Scan', # TODO @@ -94,7 +94,7 @@ my %required = ( 'RenewLoan' => [ 'patron_id', 'item_id' ], 'HoldTitle' => [ 'patron_id', 'bib_id', 'request_location' ], 'HoldItem' => [ 'patron_id', 'bib_id', 'item_id' ], - 'CancelHold' => [ 'patron_id', 'item_id' ], + 'CancelHold' => [ 'patron_id', 'item_id' ], ); # List of optional arguments @@ -105,19 +105,21 @@ my %optional = ( 'GetAuthorityRecords' => ['schema'], 'LookupPatron' => ['id_type'], 'AuthenticatePatron' => [], - 'GetPatronInfo' => [ 'show_contact', 'show_fines', 'show_holds', 'show_loans', 'loans_per_page', 'loans_page', 'show_attributes' ], - 'GetPatronStatus' => [], - 'GetServices' => [], - 'RenewLoan' => ['desired_due_date'], - 'HoldTitle' => [ 'pickup_location', 'start_date', 'expiry_date' ], - 'HoldItem' => [ 'pickup_location', 'start_date', 'expiry_date' ], - 'CancelHold' => [], + 'GetPatronInfo' => + [ 'show_contact', 'show_fines', 'show_holds', 'show_loans', 'loans_per_page', 'loans_page', 'show_attributes' ], + 'GetPatronStatus' => [], + 'GetServices' => [], + 'RenewLoan' => ['desired_due_date'], + 'HoldTitle' => [ 'pickup_location', 'start_date', 'expiry_date' ], + 'HoldItem' => [ 'pickup_location', 'start_date', 'expiry_date' ], + 'CancelHold' => [], ); # If no service is requested, display the online documentation unless ( $cgi->param('service') ) { my ( $template, $loggedinuser, $cookie ) = get_template_and_user( - { template_name => "ilsdi.tt", + { + template_name => "ilsdi.tt", query => $cgi, type => "opac", authnotrequired => 1, @@ -130,14 +132,15 @@ unless ( $cgi->param('service') ) { # Set the userenv C4::Context->set_userenv( undef, undef, undef, 'ILSDI', 'ILSDI', - undef, undef, undef, undef, undef, + undef, undef, undef, undef, undef, ); C4::Context->interface('opac'); # If user requested a service description, then display it if ( scalar $cgi->param('service') eq "Describe" and any { scalar $cgi->param('verb') eq $_ } @services ) { my ( $template, $loggedinuser, $cookie ) = get_template_and_user( - { template_name => "ilsdi.tt", + { + template_name => "ilsdi.tt", query => $cgi, type => "opac", authnotrequired => 1, @@ -150,13 +153,13 @@ if ( scalar $cgi->param('service') eq "Describe" and any { scalar $cgi->param('v # any output after this point will be UTF-8 XML binmode STDOUT, ':encoding(UTF-8)'; -print CGI::header('-type'=>'text/xml', '-charset'=>'utf-8'); +print CGI::header( '-type' => 'text/xml', '-charset' => 'utf-8' ); my $out; # If ILS-DI module is disabled in System->Preferences, redirect to 404 unless ( C4::Context->preference('ILS-DI') ) { - $out->{'code'} = "NotAllowed"; + $out->{'code'} = "NotAllowed"; $out->{'message'} = "ILS-DI is disabled."; } @@ -172,7 +175,7 @@ if (@AuthorizedIPs) { # If no filter set, allow access to everybody } } unless ($authorized) { - $out->{'code'} = "NotAllowed"; + $out->{'code'} = "NotAllowed"; $out->{'message'} = "Unauthorized IP address: $ENV{REMOTE_ADDR}."; } } @@ -190,15 +193,15 @@ if ( $service and any { $service eq $_ } @services ) { $paramhash{$_} = 1 for @names; # check for missing parameters - for ( @parmsrequired ) { + for (@parmsrequired) { unless ( exists $paramhash{$_} ) { - $out->{'code'} = "MissingParameter"; - $out->{'message'} = "The required parameter ".$_." is missing."; + $out->{'code'} = "MissingParameter"; + $out->{'message'} = "The required parameter " . $_ . " is missing."; } } # check for illegal parameters - for my $name ( @names ) { + for my $name (@names) { my $found = 0; for my $name2 (@parmsall) { if ( $name eq $name2 ) { @@ -206,17 +209,17 @@ if ( $service and any { $service eq $_ } @services ) { } } if ( $found == 0 && $name ne 'service' ) { - $out->{'code'} = "IllegalParameter"; - $out->{'message'} = "The parameter ".$name." is illegal."; + $out->{'code'} = "IllegalParameter"; + $out->{'message'} = "The parameter " . $name . " is illegal."; } } # check for multiple parameters - for ( @names ) { + for (@names) { my @values = $cgi->multi_param($_); if ( $#values != 0 ) { - $out->{'code'} = "MultipleValuesNotAllowed"; - $out->{'message'} = "Multiple values not allowed for the parameter ".$_."."; + $out->{'code'} = "MultipleValuesNotAllowed"; + $out->{'message'} = "Multiple values not allowed for the parameter " . $_ . "."; } } @@ -230,7 +233,8 @@ if ( $service and any { $service eq $_ } @services ) { # Variable functions my $sub = do { -# no strict 'refs'; + + # no strict 'refs'; my $symbol = 'C4::ILSDI::Services::' . $service; \&{"$symbol"}; }; diff --git a/opac/maintenance.pl b/opac/maintenance.pl index 11b02bd2c9..c87d1eb973 100755 --- a/opac/maintenance.pl +++ b/opac/maintenance.pl @@ -17,8 +17,8 @@ use Modern::Perl; -use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use Koha; @@ -36,16 +36,19 @@ my ( $template, $borrowernumber, $cookie ) = get_template_and_user( my $koha_db_version = C4::Context->preference('Version'); my $kohaversion = Koha::version(); + # Strip dots from version $kohaversion =~ s/\.//g if defined $kohaversion; $koha_db_version =~ s/\.//g if defined $koha_db_version; -if ( !defined $koha_db_version || # DB not populated - $kohaversion > $koha_db_version || # Update needed - C4::Context->preference('OpacMaintenance') ) { # Maintenance mode enabled +if ( + !defined $koha_db_version || # DB not populated + $kohaversion > $koha_db_version || # Update needed + C4::Context->preference('OpacMaintenance') + ) +{ # Maintenance mode enabled output_html_with_http_headers $query, '', $template->output; -} -else { +} else { print $query->redirect("/cgi-bin/koha/opac-main.pl"); } diff --git a/opac/oai.pl b/opac/oai.pl index f6a778663e..e7ebfbfb1f 100755 --- a/opac/oai.pl +++ b/opac/oai.pl @@ -18,25 +18,22 @@ # You should have received a copy of the GNU General Public License # along with Koha; if not, see . - use Modern::Perl; -use CGI qw( :standard -oldstyle_urls -utf8 ); +use CGI qw( :standard -oldstyle_urls -utf8 ); use vars qw( $GZIP ); use C4::Context; use Koha::OAI::Server::Repository; - BEGIN { eval { require PerlIO::gzip }; $GZIP = ($@) ? 0 : 1; } unless ( C4::Context->preference('OAI-PMH') ) { - print - header( - -type => 'text/plain; charset=utf-8', - -charset => 'utf-8', - -status => '404 OAI-PMH service is disabled', + print header( + -type => 'text/plain; charset=utf-8', + -charset => 'utf-8', + -status => '404 OAI-PMH service is disabled', ), "OAI-PMH service is disabled"; exit; @@ -45,16 +42,15 @@ unless ( C4::Context->preference('OAI-PMH') ) { my @encodings = http('HTTP_ACCEPT_ENCODING'); if ( $GZIP && grep { defined($_) && $_ eq 'gzip' } @encodings ) { print header( - -type => 'text/xml; charset=utf-8', - -charset => 'utf-8', - -Content-Encoding => 'gzip', + -type => 'text/xml; charset=utf-8', + -charset => 'utf-8', + -Content-Encoding => 'gzip', ); binmode( STDOUT, ":gzip" ); -} -else { +} else { print header( - -type => 'text/xml; charset=utf-8', - -charset => 'utf-8', + -type => 'text/xml; charset=utf-8', + -charset => 'utf-8', ); } diff --git a/opac/opac-ISBDdetail.pl b/opac/opac-ISBDdetail.pl index 7ebef0432f..34b7560b02 100755 --- a/opac/opac-ISBDdetail.pl +++ b/opac/opac-ISBDdetail.pl @@ -18,7 +18,6 @@ # You should have received a copy of the GNU General Public License # along with Koha; if not, see . - =head1 NAME opac-ISBDdetail.pl - script to show a biblio in ISBD format @@ -44,17 +43,17 @@ use Modern::Perl; use C4::Auth qw( get_template_and_user ); use C4::Context; use C4::Output qw( parametrized_url output_html_with_http_headers ); -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Biblio qw( CountItemsIssued GetISBDView GetMarcISSN TransformMarcToKoha ); -use C4::Record qw( marc2cites );; +use C4::Record qw( marc2cites ); use C4::Reserves qw( IsAvailableForItemLevelRequest ); -use C4::Serials qw( CountSubscriptionFromBiblionumber SearchSubscriptions GetLatestSerials ); -use C4::Koha qw( +use C4::Serials qw( CountSubscriptionFromBiblionumber SearchSubscriptions GetLatestSerials ); +use C4::Koha qw( GetNormalizedEAN GetNormalizedISBN GetNormalizedOCLCNumber @@ -67,11 +66,11 @@ use Koha::RecordProcessor; use Koha::Biblios; use Koha::Util::MARC; -my $query = CGI->new(); +my $query = CGI->new(); my $biblionumber = $query->param('biblionumber'); my $biblio; $biblio = Koha::Biblios->find( $biblionumber, { prefetch => [ 'metadata', 'items' ] } ) if $biblionumber; -if( !$biblio ) { +if ( !$biblio ) { print $query->redirect('/cgi-bin/koha/errors/404.pl'); exit; } @@ -91,21 +90,23 @@ my $patron = Koha::Patrons->find($loggedinuser); my $opachiddenitems_rules = C4::Context->yaml_preference('OpacHiddenItems'); unless ( $patron and $patron->category->override_hidden_items ) { + # only skip this check if there's a logged in user # and its category overrides OpacHiddenItems - if ( $biblio->hidden_in_opac({ rules => $opachiddenitems_rules }) ) { - print $query->redirect('/cgi-bin/koha/errors/404.pl'); # escape early + if ( $biblio->hidden_in_opac( { rules => $opachiddenitems_rules } ) ) { + print $query->redirect('/cgi-bin/koha/errors/404.pl'); # escape early exit; } } my $record = $biblio->metadata->record; -my @items = $biblio->items->filter_by_visible_in_opac({ patron => $patron })->as_list; +my @items = $biblio->items->filter_by_visible_in_opac( { patron => $patron } )->as_list; my $metadata_extractor = $biblio->metadata_extractor; my $record_processor = Koha::RecordProcessor->new( - { filters => [ 'EmbedItems', 'ViewPolicy' ], + { + filters => [ 'EmbedItems', 'ViewPolicy' ], options => { interface => 'opac', frameworkcode => $biblio->frameworkcode, @@ -116,14 +117,15 @@ my $record_processor = Koha::RecordProcessor->new( $record_processor->process($record); # get biblionumbers stored in the cart -if(my $cart_list = $query->cookie("bib_list")){ - my @cart_list = split(/\//, $cart_list); - if ( grep {$_ eq $biblionumber} @cart_list) { +if ( my $cart_list = $query->cookie("bib_list") ) { + my @cart_list = split( /\//, $cart_list ); + if ( grep { $_ eq $biblionumber } @cart_list ) { $template->param( incart => 1 ); } } my $marcflavour = C4::Context->preference("marcflavour"); + # some useful variables for enhanced content; # in each case, we're grabbing the first value we find in # the record and normalizing it @@ -145,23 +147,23 @@ $template->param( #coping with subscriptions my $subscriptionsnumber = CountSubscriptionFromBiblionumber($biblionumber); -my $dat = TransformMarcToKoha({ record => $record }); +my $dat = TransformMarcToKoha( { record => $record } ); -my @subscriptions = SearchSubscriptions({ biblionumber => $biblionumber, orderby => 'title' }); +my @subscriptions = SearchSubscriptions( { biblionumber => $biblionumber, orderby => 'title' } ); my @subs; foreach my $subscription (@subscriptions) { my %cell; - my $serials_to_display; + my $serials_to_display; $cell{subscriptionid} = $subscription->{subscriptionid}; $cell{subscriptionnotes} = $subscription->{notes}; $cell{branchcode} = $subscription->{branchcode}; #get the three latest serials. - $serials_to_display = $subscription->{opacdisplaycount}; - $serials_to_display = C4::Context->preference('OPACSerialIssueDisplayCount') unless $serials_to_display; - $cell{opacdisplaycount} = $serials_to_display; + $serials_to_display = $subscription->{opacdisplaycount}; + $serials_to_display = C4::Context->preference('OPACSerialIssueDisplayCount') unless $serials_to_display; + $cell{opacdisplaycount} = $serials_to_display; $cell{latestserials} = - GetLatestSerials( $subscription->{subscriptionid}, $serials_to_display ); + GetLatestSerials( $subscription->{subscriptionid}, $serials_to_display ); push @subs, \%cell; } @@ -170,11 +172,13 @@ $template->param( subscriptionsnumber => $subscriptionsnumber, ); -my $res = GetISBDView({ - 'record' => $record, - 'template' => 'opac', - 'framework' => $biblio->frameworkcode -}); +my $res = GetISBDView( + { + 'record' => $record, + 'template' => 'opac', + 'framework' => $biblio->frameworkcode + } +); # Count the number of items that allow holds at the 'All libraries' rule level my $holdable_items = $biblio->items->filter_by_for_hold->count; @@ -198,13 +202,13 @@ $template->param( #Search for title in links my $control_number = $metadata_extractor->get_control_number(); -my $marcissns = GetMarcISSN ( $record, $marcflavour ); -my $issn = $marcissns->[0] || ''; +my $marcissns = GetMarcISSN( $record, $marcflavour ); +my $issn = $marcissns->[0] || ''; -if (my $search_for_title = C4::Context->preference('OPACSearchForTitleIn')){ - $dat->{title} =~ s/\/+$//; # remove trailing slash - $dat->{title} =~ s/\s+$//; # remove trailing space - my $oclc_no = Koha::Util::MARC::oclc_number( $record ); +if ( my $search_for_title = C4::Context->preference('OPACSearchForTitleIn') ) { + $dat->{title} =~ s/\/+$//; # remove trailing slash + $dat->{title} =~ s/\s+$//; # remove trailing space + my $oclc_no = Koha::Util::MARC::oclc_number($record); $search_for_title = parametrized_url( $search_for_title, { @@ -217,16 +221,15 @@ if (my $search_for_title = C4::Context->preference('OPACSearchForTitleIn')){ OCLC_NO => $oclc_no, } ); - $template->param('OPACSearchForTitleIn' => $search_for_title); + $template->param( 'OPACSearchForTitleIn' => $search_for_title ); } -if( C4::Context->preference('ArticleRequests') ) { - my $itemtype = Koha::ItemTypes->find($biblio->itemtype); - my $artreqpossible = $patron - ? $biblio->can_article_request( $patron ) - : $itemtype - ? $itemtype->may_article_request - : q{}; +if ( C4::Context->preference('ArticleRequests') ) { + my $itemtype = Koha::ItemTypes->find( $biblio->itemtype ); + my $artreqpossible = + $patron ? $biblio->can_article_request($patron) + : $itemtype ? $itemtype->may_article_request + : q{}; $template->param( artreqpossible => $artreqpossible ); } diff --git a/opac/opac-MARCdetail.pl b/opac/opac-MARCdetail.pl index 63957e7d0b..1f99235f6e 100755 --- a/opac/opac-MARCdetail.pl +++ b/opac/opac-MARCdetail.pl @@ -19,7 +19,6 @@ # You should have received a copy of the GNU General Public License # along with Koha; if not, see . - =head1 NAME opac-MARCdetail.pl : script to show a biblio in MARC format @@ -48,7 +47,7 @@ use Modern::Perl; use C4::Auth qw( get_template_and_user ); use C4::Context; use C4::Output qw( parametrized_url output_html_with_http_headers ); -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Biblio qw( CountItemsIssued GetAuthorisedValueDesc @@ -57,10 +56,10 @@ use C4::Biblio qw( GetMarcStructure TransformMarcToKoha ); -use C4::Record qw( marc2cites ); +use C4::Record qw( marc2cites ); use C4::Reserves qw( IsAvailableForItemLevelRequest ); use C4::Members; -use C4::Koha qw( GetNormalizedISBN ); +use C4::Koha qw( GetNormalizedISBN ); use List::MoreUtils qw( uniq ); use Koha::Biblios; use Koha::CirculationRules; @@ -74,7 +73,7 @@ use Koha::Util::MARC; my $query = CGI->new(); my $biblionumber = $query->param('biblionumber'); -if ( ! $biblionumber ) { +if ( !$biblionumber ) { print $query->redirect("/cgi-bin/koha/errors/404.pl"); exit; } @@ -98,17 +97,18 @@ if ( !$biblio ) { } unless ( $patron and $patron->category->override_hidden_items ) { + # only skip this check if there's a logged in user # and its category overrides OpacHiddenItems - if ( $biblio->hidden_in_opac({ rules => C4::Context->yaml_preference('OpacHiddenItems') }) ) { - print $query->redirect('/cgi-bin/koha/errors/404.pl'); # escape early + if ( $biblio->hidden_in_opac( { rules => C4::Context->yaml_preference('OpacHiddenItems') } ) ) { + print $query->redirect('/cgi-bin/koha/errors/404.pl'); # escape early exit; } } my $metadata_extractor = $biblio->metadata_extractor; -my $items = $biblio->items->filter_by_visible_in_opac({ patron => $patron }); +my $items = $biblio->items->filter_by_visible_in_opac( { patron => $patron } ); my $framework = $biblio ? $biblio->frameworkcode : q{}; my $tagslib = &GetMarcStructure( 0, $framework ); @@ -127,18 +127,18 @@ if ( !$record ) { } # get biblionumbers stored in the cart -if(my $cart_list = $query->cookie("bib_list")){ - my @cart_list = split(/\//, $cart_list); - if ( grep {$_ eq $biblionumber} @cart_list) { +if ( my $cart_list = $query->cookie("bib_list") ) { + my @cart_list = split( /\//, $cart_list ); + if ( grep { $_ eq $biblionumber } @cart_list ) { $template->param( incart => 1 ); } } -my ($bt_tag,$bt_subtag) = GetMarcFromKohaField( 'biblio.title' ); +my ( $bt_tag, $bt_subtag ) = GetMarcFromKohaField('biblio.title'); $template->param( bibliotitle => $biblio->title, -) if $tagslib->{$bt_tag}->{$bt_subtag}->{hidden} <= 0 && # <=0 OPAC visible. - $tagslib->{$bt_tag}->{$bt_subtag}->{hidden} > -8; # except -8; + ) if $tagslib->{$bt_tag}->{$bt_subtag}->{hidden} <= 0 && # <=0 OPAC visible. + $tagslib->{$bt_tag}->{$bt_subtag}->{hidden} > -8; # except -8; # Count the number of items that allow holds at the 'All libraries' rule level my $holdable_items = $biblio->items->filter_by_for_hold->count; @@ -189,51 +189,51 @@ for ( my $tabloop = 0 ; $tabloop <= 9 ; $tabloop++ ) { # if tag <10, there's no subfield, use the "@" trick if ( $fields[$x_i]->tag() < 10 ) { next - if ( - $tagslib->{ $fields[$x_i]->tag() }->{'@'}->{tab} ne $tabloop ); + if ( $tagslib->{ $fields[$x_i]->tag() }->{'@'}->{tab} ne $tabloop ); next if ( $tagslib->{ $fields[$x_i]->tag() }->{'@'}->{hidden} > 0 ); my %subfield_data; $subfield_data{marc_lib} = - $tagslib->{ $fields[$x_i]->tag() }->{'@'}->{lib}; + $tagslib->{ $fields[$x_i]->tag() }->{'@'}->{lib}; $subfield_data{marc_value} = $fields[$x_i]->data(); $subfield_data{marc_subfield} = '@'; $subfield_data{marc_tag} = $fields[$x_i]->tag(); push( @subfields_data, \%subfield_data ); - } - else { - my @subf = $fields[$x_i]->subfields; + } else { + my @subf = $fields[$x_i]->subfields; my $previous = ''; + # loop through each subfield for my $i ( 0 .. $#subf ) { - $subf[$i][0] = "@" unless defined($subf[$i][0]); + $subf[$i][0] = "@" unless defined( $subf[$i][0] ); my $sf_def = $tagslib->{ $fields[$x_i]->tag() }; $sf_def = $sf_def->{ $subf[$i][0] } if defined($sf_def); - my ($tab,$hidden,$lib); - $tab = $sf_def->{tab} if defined($sf_def); - $tab = $tab // int($fields[$x_i]->tag()/100); + my ( $tab, $hidden, $lib ); + $tab = $sf_def->{tab} if defined($sf_def); + $tab = $tab // int( $fields[$x_i]->tag() / 100 ); $hidden = $sf_def->{hidden} if defined($sf_def); $hidden = $hidden // 0; next if ( $tab != $tabloop ); next if ( $hidden > 0 ); my %subfield_data; - $lib = $sf_def->{lib} if defined($sf_def); - $lib = $lib // '--'; - $subfield_data{marc_lib} = ($lib eq $previous) ? '--' : $lib; - $previous = $lib; - $subfield_data{link} = $sf_def->{link}; + $lib = $sf_def->{lib} if defined($sf_def); + $lib = $lib // '--'; + $subfield_data{marc_lib} = ( $lib eq $previous ) ? '--' : $lib; + $previous = $lib; + $subfield_data{link} = $sf_def->{link}; $subf[$i][1] =~ s/\n//g; + if ( $sf_def->{isurl} ) { $subfield_data{marc_value} = "$subf[$i][1]"; - } - elsif ( defined($sf_def->{kohafield}) && $sf_def->{kohafield} eq "biblioitems.isbn" ) { + } elsif ( defined( $sf_def->{kohafield} ) && $sf_def->{kohafield} eq "biblioitems.isbn" ) { $subfield_data{marc_value} = $subf[$i][1]; - } - else { + } else { if ( $sf_def->{authtypecode} ) { $subfield_data{authority} = $fields[$x_i]->subfield(9); } - $subfield_data{marc_value} = GetAuthorisedValueDesc( $fields[$x_i]->tag(), - $subf[$i][0], $subf[$i][1], '', $tagslib, '', 'opac' ); + $subfield_data{marc_value} = GetAuthorisedValueDesc( + $fields[$x_i]->tag(), + $subf[$i][0], $subf[$i][1], '', $tagslib, '', 'opac' + ); } $subfield_data{marc_subfield} = $subf[$i][0]; $subfield_data{marc_tag} = $fields[$x_i]->tag(); @@ -243,23 +243,19 @@ for ( my $tabloop = 0 ; $tabloop <= 9 ; $tabloop++ ) { if ( $#subfields_data >= 0 ) { my %tag_data; if ( ( $fields[$x_i]->tag() eq $fields[ $x_i - 1 ]->tag() ) - && ( C4::Context->preference('LabelMARCView') eq 'economical' ) - ) + && ( C4::Context->preference('LabelMARCView') eq 'economical' ) ) { $tag_data{tag} = ""; - } - else { + } else { if ( C4::Context->preference('hide_marc') ) { $tag_data{tag} = $tagslib->{ $fields[$x_i]->tag() }->{lib}; - } - else { + } else { my $sf_def = $tagslib->{ $fields[$x_i]->tag() }; my $lib; $lib = $sf_def->{lib} if defined($sf_def); $lib = $lib // ''; - $tag_data{tag} = $fields[$x_i]->tag() . ' ' - . C4::Koha::display_marc_indicators($fields[$x_i]) - . " - $lib"; + $tag_data{tag} = + $fields[$x_i]->tag() . ' ' . C4::Koha::display_marc_indicators( $fields[$x_i] ) . " - $lib"; } } my @tmp = @subfields_data; @@ -271,7 +267,6 @@ for ( my $tabloop = 0 ; $tabloop <= 9 ; $tabloop++ ) { $template->param( "tab" . $tabloop . "XX" => \@loop_data ); } - # now, build item tab ! # the main difference is that datas are in lines and not in columns : thus, we build the first, then the values... # loop through each tag @@ -279,8 +274,7 @@ for ( my $tabloop = 0 ; $tabloop <= 9 ; $tabloop++ ) { # then construct template. # $record has already had all the item fields filtered above. my @fields = $record->fields(); -my %witness - ; #---- stores the list of subfields used at least once, with the "meaning" of the code +my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code my @item_subfield_codes; my @item_loop; foreach my $field (@fields) { @@ -291,51 +285,51 @@ foreach my $field (@fields) { # loop through each subfield for my $i ( 0 .. $#subf ) { my $sf_def = $tagslib->{ $field->tag() }->{ $subf[$i][0] }; - next if ( ($sf_def->{tab}||0) != 10 ); - next if ( ($sf_def->{hidden}||0) > 0 ); + next if ( ( $sf_def->{tab} || 0 ) != 10 ); + next if ( ( $sf_def->{hidden} || 0 ) > 0 ); push @item_subfield_codes, $subf[$i][0]; $witness{ $subf[$i][0] } = $sf_def->{lib}; # Allow repeatables (BZ 13574) - if( $item->{$subf[$i][0]} ) { - $item->{$subf[$i][0]} .= ' | '; + if ( $item->{ $subf[$i][0] } ) { + $item->{ $subf[$i][0] } .= ' | '; } else { - $item->{$subf[$i][0]} = q{}; + $item->{ $subf[$i][0] } = q{}; } if ( $sf_def->{isurl} ) { $item->{ $subf[$i][0] } .= "$subf[$i][1]"; - } - elsif ( $sf_def->{kohafield} eq "biblioitems.isbn" ) { + } elsif ( $sf_def->{kohafield} eq "biblioitems.isbn" ) { $item->{ $subf[$i][0] } .= $subf[$i][1]; - } - else { - $item->{ $subf[$i][0] } .= GetAuthorisedValueDesc( $field->tag(), $subf[$i][0], - $subf[$i][1], '', $tagslib, '', 'opac' ) // q{}; + } else { + $item->{ $subf[$i][0] } .= GetAuthorisedValueDesc( + $field->tag(), $subf[$i][0], + $subf[$i][1], '', $tagslib, '', 'opac' + ) // q{}; } my $kohafield = $tagslib->{ $field->tag() }->{ $subf[$i][0] }->{kohafield}; $item->{ $subf[$i][0] } = output_pref( { str => $item->{ $subf[$i][0] }, dateonly => 1 } ) - if grep { $kohafield eq $_ } - qw( items.dateaccessioned items.onloan items.datelastseen items.datelastborrowed items.replacementpricedate ); + if grep { $kohafield eq $_ } + qw( items.dateaccessioned items.onloan items.datelastseen items.datelastborrowed items.replacementpricedate ); } push @item_loop, $item if $item; } -my ( $holdingbrtagf, $holdingbrtagsubf ) = - &GetMarcFromKohaField( "items.holdingbranch" ); +my ( $holdingbrtagf, $holdingbrtagsubf ) = &GetMarcFromKohaField("items.holdingbranch"); @item_loop = - sort { ($a->{$holdingbrtagsubf}||'') cmp ($b->{$holdingbrtagsubf}||'') } @item_loop; + sort { ( $a->{$holdingbrtagsubf} || '' ) cmp( $b->{$holdingbrtagsubf} || '' ) } @item_loop; @item_subfield_codes = uniq @item_subfield_codes; + # fill item info my @item_header_loop; -for my $subfield_code ( @item_subfield_codes ) { +for my $subfield_code (@item_subfield_codes) { push @item_header_loop, $witness{$subfield_code}; - for my $item_data ( @item_loop ) { - $item_data->{$subfield_code} ||= " " - } + for my $item_data (@item_loop) { + $item_data->{$subfield_code} ||= " "; + } } if ( C4::Context->preference("OPACISBD") ) { @@ -350,10 +344,10 @@ my $control_number = $metadata_extractor->get_control_number(); my $marcissns = GetMarcISSN( $record, $marcflavour ); my $issn = $marcissns->[0] || ''; -if (my $search_for_title = C4::Context->preference('OPACSearchForTitleIn')){ - $dat->{title} =~ s/\/+$//; # remove trailing slash - $dat->{title} =~ s/\s+$//; # remove trailing space - my $oclc_no = Koha::Util::MARC::oclc_number( $record ); +if ( my $search_for_title = C4::Context->preference('OPACSearchForTitleIn') ) { + $dat->{title} =~ s/\/+$//; # remove trailing slash + $dat->{title} =~ s/\s+$//; # remove trailing space + my $oclc_no = Koha::Util::MARC::oclc_number($record); $search_for_title = parametrized_url( $search_for_title, { @@ -366,20 +360,19 @@ if (my $search_for_title = C4::Context->preference('OPACSearchForTitleIn')){ OCLC_NO => $oclc_no, } ); - $template->param('OPACSearchForTitleIn' => $search_for_title); + $template->param( 'OPACSearchForTitleIn' => $search_for_title ); } -if( C4::Context->preference('ArticleRequests') ) { - my $itemtype = Koha::ItemTypes->find($biblio->itemtype); - my $artreqpossible = $patron - ? $biblio->can_article_request( $patron ) - : $itemtype - ? $itemtype->may_article_request - : q{}; +if ( C4::Context->preference('ArticleRequests') ) { + my $itemtype = Koha::ItemTypes->find( $biblio->itemtype ); + my $artreqpossible = + $patron ? $biblio->can_article_request($patron) + : $itemtype ? $itemtype->may_article_request + : q{}; $template->param( artreqpossible => $artreqpossible ); } -my $norequests = ! $biblio->items->filter_by_for_hold->count; +my $norequests = !$biblio->items->filter_by_for_hold->count; $template->param( item_loop => \@item_loop, item_header_loop => \@item_header_loop, diff --git a/opac/opac-account-pay-return.pl b/opac/opac-account-pay-return.pl index bdfbcfcb1a..b7e30026c6 100755 --- a/opac/opac-account-pay-return.pl +++ b/opac/opac-account-pay-return.pl @@ -47,8 +47,7 @@ if ($can_handle_payment) { cgi => $cgi, } ); -} -else { +} else { print $cgi->redirect("/cgi-bin/koha/errors/404.pl"); exit; } diff --git a/opac/opac-account-pay.pl b/opac/opac-account-pay.pl index 1e0dbf8f06..278bc085c6 100755 --- a/opac/opac-account-pay.pl +++ b/opac/opac-account-pay.pl @@ -36,13 +36,14 @@ my $payment_method = $cgi->param('payment_method'); my @accountlines = $cgi->multi_param('accountline'); my $use_plugin = Koha::Plugins::Handler->run( - { class => $payment_method, + { + class => $payment_method, method => 'opac_online_payment', cgi => $cgi, } ); -unless ( $use_plugin ) { +unless ($use_plugin) { print $cgi->redirect("/cgi-bin/koha/errors/404.pl"); exit; } @@ -54,9 +55,9 @@ unless ( $op eq 'cud-pay' ) { my ( $template, $borrowernumber, $cookie ) = get_template_and_user( { - template_name => "opac-account-pay-error.tt", - query => $cgi, - type => "opac", + template_name => "opac-account-pay-error.tt", + query => $cgi, + type => "opac", } ); diff --git a/opac/opac-account.pl b/opac/opac-account.pl index c47bd58644..08aa9ab5b4 100755 --- a/opac/opac-account.pl +++ b/opac/opac-account.pl @@ -18,11 +18,10 @@ # You should have received a copy of the GNU General Public License # along with Koha; if not, see . - use Modern::Perl; use CGI qw ( -utf8 ); use C4::Members; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use Koha::Account::Lines; use Koha::Patrons; @@ -31,21 +30,20 @@ use Koha::Plugins; my $query = CGI->new; my ( $template, $borrowernumber, $cookie ) = get_template_and_user( { - template_name => "opac-account.tt", - query => $query, - type => "opac", + template_name => "opac-account.tt", + query => $query, + type => "opac", } ); -my $patron = Koha::Patrons->find( $borrowernumber ); -my $account = $patron->account; -my $accountlines = $account->lines->search({ amountoutstanding => { '>=' => 0 }}); -my $total_outstanding = $accountlines->total_outstanding; +my $patron = Koha::Patrons->find($borrowernumber); +my $account = $patron->account; +my $accountlines = $account->lines->search( { amountoutstanding => { '>=' => 0 } } ); +my $total_outstanding = $accountlines->total_outstanding; my $outstanding_credits = $account->outstanding_credits; -if ( C4::Context->preference('AllowPatronToSetFinesVisibilityForGuarantor') - || C4::Context->preference('AllowStaffToSetFinesVisibilityForGuarantor') - ) +if ( C4::Context->preference('AllowPatronToSetFinesVisibilityForGuarantor') + || C4::Context->preference('AllowStaffToSetFinesVisibilityForGuarantor') ) { my @relatives; @@ -70,26 +68,28 @@ if ( C4::Context->preference('AllowPatronToSetFinesVisibilityForGuarantor') $template->param( relatives => \@relatives ); } - $template->param( ACCOUNT_LINES => $accountlines, total => $total_outstanding, outstanding_credits => $outstanding_credits, accountview => 1, - message => scalar $query->param('message') || q{}, + message => scalar $query->param('message') || q{}, message_value => scalar $query->param('message_value') || q{}, - payment => scalar $query->param('payment') || q{}, + payment => scalar $query->param('payment') || q{}, payment_error => scalar $query->param('payment-error') || q{}, ); if ( C4::Context->config("enable_plugins") ) { - my @plugins = Koha::Plugins->new()->GetPlugins({ - method => 'opac_online_payment', - }); + my @plugins = Koha::Plugins->new()->GetPlugins( + { + method => 'opac_online_payment', + } + ); + # Only pass in plugins where opac online payment is enabled @plugins = grep { $_->opac_online_payment } @plugins; $template->param( - plugins => \@plugins, + plugins => \@plugins, payment_methods => scalar @plugins > 0 ); } diff --git a/opac/opac-addbybiblionumber.pl b/opac/opac-addbybiblionumber.pl index 3ea34220fd..23c03ab0de 100755 --- a/opac/opac-addbybiblionumber.pl +++ b/opac/opac-addbybiblionumber.pl @@ -20,9 +20,9 @@ use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Output qw( output_html_with_http_headers ); -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use Koha::Biblios; use Koha::Virtualshelves; @@ -49,20 +49,26 @@ if ( scalar(@biblionumbers) == 1 ) { } my ( $template, $loggedinuser, $cookie ) = get_template_and_user( - { template_name => "opac-addbybiblionumber.tt", - query => $query, - type => "opac", + { + template_name => "opac-addbybiblionumber.tt", + query => $query, + type => "opac", } ); -if( $op && $op !~ /^cud-/ ) { +if ( $op && $op !~ /^cud-/ ) { $authorized = 0; } elsif ($newvirtualshelf) { - if ($loggedinuser > 0 - and ( !$public + if ( + $loggedinuser > 0 + and ( !$public or $public and $loggedinuser > 0 && C4::Context->preference('OpacAllowPublicListCreation') ) - ) { - my $shelf = eval { Koha::Virtualshelf->new( { shelfname => $newvirtualshelf, public => $public, owner => $loggedinuser, } )->store; }; + ) + { + my $shelf = eval { + Koha::Virtualshelf->new( { shelfname => $newvirtualshelf, public => $public, owner => $loggedinuser, } ) + ->store; + }; if ( $@ or not $shelf ) { $errcode = 1; $authorized = 0; @@ -84,7 +90,7 @@ if( $op && $op !~ /^cud-/ ) { $shelf->add_biblio( $biblionumber, $loggedinuser ); } $template->param( - WINDOW_CLOSE => 1, + WINDOW_CLOSE => 1, ); } else { $authorized = 0; @@ -104,28 +110,31 @@ if( $op && $op !~ /^cud-/ ) { } else { if ( $loggedinuser > 0 ) { my $private_shelves = Koha::Virtualshelves->search( - { public => 0, - owner => $loggedinuser, + { + public => 0, + owner => $loggedinuser, allow_change_from_owner => 1, }, { order_by => 'shelfname' } ); my $shelves_shared_with_me = Koha::Virtualshelves->search( - { public => 0, + { + public => 0, 'virtualshelfshares.borrowernumber' => $loggedinuser, allow_change_from_others => 1, }, { join => 'virtualshelfshares', } ); my $public_shelves; - if ( $loggedinuser ) { - if ( Koha::Patrons->find( $loggedinuser )->can_patron_change_permitted_staff_lists ) { + if ($loggedinuser) { + if ( Koha::Patrons->find($loggedinuser)->can_patron_change_permitted_staff_lists ) { $public_shelves = Koha::Virtualshelves->search( - { public => 1, - -or => [ + { + public => 1, + -or => [ -and => { allow_change_from_owner => 1, - owner => $loggedinuser, + owner => $loggedinuser, }, allow_change_from_others => 1, allow_change_from_staff => 1, @@ -134,46 +143,49 @@ if( $op && $op !~ /^cud-/ ) { }, { order_by => 'shelfname' } ); - } elsif ( Koha::Patrons->find( $loggedinuser )->can_patron_change_staff_only_lists ) { + } elsif ( Koha::Patrons->find($loggedinuser)->can_patron_change_staff_only_lists ) { $public_shelves = Koha::Virtualshelves->search( - { public => 1, - -or => [ + { + public => 1, + -or => [ -and => { allow_change_from_owner => 1, - owner => $loggedinuser, + owner => $loggedinuser, }, - allow_change_from_others => 1, - allow_change_from_staff => 1 + allow_change_from_others => 1, + allow_change_from_staff => 1 ], }, { order_by => 'shelfname' } ); } else { $public_shelves = Koha::Virtualshelves->search( - { public => 1, - -or => [ + { + public => 1, + -or => [ -and => { allow_change_from_owner => 1, - owner => $loggedinuser, + owner => $loggedinuser, }, allow_change_from_others => 1, ], }, - {order_by => 'shelfname' } + { order_by => 'shelfname' } ); } } else { $public_shelves = Koha::Virtualshelves->search( - { public => 1, - -or => [ + { + public => 1, + -or => [ -and => { allow_change_from_owner => 1, - owner => $loggedinuser, + owner => $loggedinuser, }, allow_change_from_others => 1, ], }, - {order_by => 'shelfname' } + { order_by => 'shelfname' } ); } @@ -189,10 +201,11 @@ if( $op && $op !~ /^cud-/ ) { if ($authorized) { for my $biblionumber (@biblionumbers) { - my $biblio = Koha::Biblios->find( $biblionumber ); + my $biblio = Koha::Biblios->find($biblionumber); push( @biblios, - { biblionumber => $biblionumber, + { + biblionumber => $biblionumber, title => $biblio->title, subtitle => $biblio->subtitle, medium => $biblio->medium, @@ -209,7 +222,7 @@ if ($authorized) { ); $template->param( - newshelf => $newshelf || 0, + newshelf => $newshelf || 0, OpacAllowPublicListCreation => C4::Context->preference('OpacAllowPublicListCreation'), ); } diff --git a/opac/opac-alert-subscribe.pl b/opac/opac-alert-subscribe.pl index 97ef88b133..de11502401 100755 --- a/opac/opac-alert-subscribe.pl +++ b/opac/opac-alert-subscribe.pl @@ -18,8 +18,8 @@ # along with Koha; if not, see . use Modern::Perl; -use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use C4::Context; use C4::Serials qw( GetSubscription ); diff --git a/opac/opac-alert-subscriptions.pl b/opac/opac-alert-subscriptions.pl index 86d1385f45..63bc439a2a 100755 --- a/opac/opac-alert-subscriptions.pl +++ b/opac/opac-alert-subscriptions.pl @@ -18,7 +18,7 @@ # along with Koha; if not, see . use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Auth qw( get_template_and_user ); use C4::Context; use C4::Output qw( output_html_with_http_headers ); diff --git a/opac/opac-article-request-cancel.pl b/opac/opac-article-request-cancel.pl index e926a5f506..4e30776d21 100755 --- a/opac/opac-article-request-cancel.pl +++ b/opac/opac-article-request-cancel.pl @@ -29,21 +29,20 @@ my $query = CGI->new; my ( $template, $borrowernumber, $cookie ) = get_template_and_user( { - template_name => "opac-account.tt", - query => $query, - type => "opac", + template_name => "opac-account.tt", + query => $query, + type => "opac", } ); my $id = $query->param('id'); -if ( $id ) { - my $ar = Koha::ArticleRequests->find( $id ); +if ($id) { + my $ar = Koha::ArticleRequests->find($id); if ( !$ar ) { print $query->redirect("/cgi-bin/koha/errors/404.pl"); exit; - } - elsif ( $ar->borrowernumber != $borrowernumber ) { + } elsif ( $ar->borrowernumber != $borrowernumber ) { print $query->redirect("/cgi-bin/koha/errors/403.pl"); exit; } diff --git a/opac/opac-authorities-home.pl b/opac/opac-authorities-home.pl index bddcdc0115..88435684ce 100755 --- a/opac/opac-authorities-home.pl +++ b/opac/opac-authorities-home.pl @@ -19,8 +19,8 @@ use Modern::Perl; -use CGI qw ( -utf8 ); -use URI::Escape qw( uri_escape_utf8 ); +use CGI qw ( -utf8 ); +use URI::Escape qw( uri_escape_utf8 ); use Array::Utils qw(intersect); use C4::Auth qw( get_template_and_user ); @@ -37,24 +37,24 @@ use Koha::SearchEngine::Search; use Koha::SearchEngine::QueryBuilder; my $query = CGI->new; -my $op = $query->param('op') || ''; +my $op = $query->param('op') || ''; my $authtypecode = $query->param('authtypecode') || ''; my $dbh = C4::Context->dbh; -my $startfrom = $query->param('startfrom') || 1; +my $startfrom = $query->param('startfrom') || 1; my $resultsperpage = $query->param('resultsperpage') || 20; -my $authid = $query->param('authid'); +my $authid = $query->param('authid'); my ( $template, $loggedinuser, $cookie ); -my $authority_types = Koha::Authority::Types->search({}, { order_by => ['authtypetext']}); +my $authority_types = Koha::Authority::Types->search( {}, { order_by => ['authtypetext'] } ); if ( $op eq "do_search" ) { my @input_marclist = $query->multi_param('marclist'); - my @and_or = $query->multi_param('and_or'); - my @excluding = $query->multi_param('excluding'); - my @operator = $query->multi_param('operator'); - my $orderby = $query->param('orderby'); - my @value = $query->multi_param('value'); + my @and_or = $query->multi_param('and_or'); + my @excluding = $query->multi_param('excluding'); + my @operator = $query->multi_param('operator'); + my $orderby = $query->param('orderby'); + my @value = $query->multi_param('value'); $value[0] ||= q||; # validation of "Where" @@ -62,15 +62,14 @@ if ( $op eq "do_search" ) { my @marclist = intersect( @input_marclist, @valid_marc_list ); @marclist = ('all') unless @marclist; - my $builder = Koha::SearchEngine::QueryBuilder->new( - { index => $Koha::SearchEngine::AUTHORITIES_INDEX } ); - my $searcher = Koha::SearchEngine::Search->new( - { index => $Koha::SearchEngine::AUTHORITIES_INDEX } ); - my $search_query = $builder->build_authorities_query_compat( \@marclist, \@and_or, - \@excluding, \@operator, \@value, $authtypecode, $orderby ); + my $builder = Koha::SearchEngine::QueryBuilder->new( { index => $Koha::SearchEngine::AUTHORITIES_INDEX } ); + my $searcher = Koha::SearchEngine::Search->new( { index => $Koha::SearchEngine::AUTHORITIES_INDEX } ); + my $search_query = $builder->build_authorities_query_compat( + \@marclist, \@and_or, + \@excluding, \@operator, \@value, $authtypecode, $orderby + ); my $offset = ( $startfrom - 1 ) * $resultsperpage + 1; - my ( $results, $total ) = - $searcher->search_auth_compat( $search_query, $offset, $resultsperpage ); + my ( $results, $total ) = $searcher->search_auth_compat( $search_query, $offset, $resultsperpage ); ( $template, $loggedinuser, $cookie ) = get_template_and_user( { template_name => "opac-authoritiessearchresultlist.tt", @@ -82,18 +81,19 @@ if ( $op eq "do_search" ) { $template->param( search_query => $search_query ) if C4::Context->preference('DumpSearchQueryTemplate'); # multi page display gestion - my $value_url = uri_escape_utf8($value[0]); - my $base_url = "opac-authorities-home.pl?" - ."marclist=$marclist[0]" - ."&and_or=$and_or[0]" - ."&excluding=$excluding[0]" - ."&operator=$operator[0]" - ."&value=$value_url" - ."&resultsperpage=$resultsperpage" - ."&type=opac" - ."&op=do_search" - ."&authtypecode=$authtypecode" - ."&orderby=$orderby"; + my $value_url = uri_escape_utf8( $value[0] ); + my $base_url = + "opac-authorities-home.pl?" + . "marclist=$marclist[0]" + . "&and_or=$and_or[0]" + . "&excluding=$excluding[0]" + . "&operator=$operator[0]" + . "&value=$value_url" + . "&resultsperpage=$resultsperpage" + . "&type=opac" + . "&op=do_search" + . "&authtypecode=$authtypecode" + . "&orderby=$orderby"; my $from = ( $startfrom - 1 ) * $resultsperpage + 1; my $to; @@ -103,25 +103,24 @@ if ( $op eq "do_search" ) { if ( $total < $startfrom * $resultsperpage ) { $to = $total; - } - else { + } else { $to = $startfrom * $resultsperpage; } my $AuthorityXSLTOpacResultsDisplay = C4::Context->preference('AuthorityXSLTOpacResultsDisplay'); - if ($results && $AuthorityXSLTOpacResultsDisplay) { + if ( $results && $AuthorityXSLTOpacResultsDisplay ) { my $lang = C4::Languages::getlanguage(); foreach my $result (@$results) { - my $authority = Koha::Authorities->find($result->{authid}); + my $authority = Koha::Authorities->find( $result->{authid} ); next unless $authority; my $authtypecode = $authority->authtypecode; - my $xsl = $AuthorityXSLTOpacResultsDisplay; + my $xsl = $AuthorityXSLTOpacResultsDisplay; $xsl =~ s/\{langcode\}/$lang/g; $xsl =~ s/\{authtypecode\}/$authtypecode/g; my $xslt_engine = Koha::XSLT::Base->new; - my $output = $xslt_engine->transform({ xml => $authority->marcxml, file => $xsl }); - if ($xslt_engine->err) { + my $output = $xslt_engine->transform( { xml => $authority->marcxml, file => $xsl } ); + if ( $xslt_engine->err ) { warn "XSL transformation failed ($xsl): " . $xslt_engine->err; next; } @@ -134,13 +133,14 @@ if ( $op eq "do_search" ) { $base_url, int( $total / $resultsperpage ) + 1, $startfrom, 'startfrom' ), - total => $total, - from => $from, - to => $to, + total => $total, + from => $from, + to => $to, ); - unless (C4::Context->preference('OPACShowUnusedAuthorities')) { -# TODO implement usage counts in the indexes to filter during searching + unless ( C4::Context->preference('OPACShowUnusedAuthorities') ) { + + # TODO implement usage counts in the indexes to filter during searching my @usedauths = grep { $_->{used} > 0 } @$results; $results = \@usedauths; } @@ -148,31 +148,36 @@ if ( $op eq "do_search" ) { $template->param( result => $results ) if $results; # Opac search history - if (C4::Context->preference('EnableOpacSearchHistory')) { - if ( $startfrom == 1) { - my $path_info = $query->url(-path_info=>1); - my $query_cgi_history = $query->url(-query=>1); + if ( C4::Context->preference('EnableOpacSearchHistory') ) { + if ( $startfrom == 1 ) { + my $path_info = $query->url( -path_info => 1 ); + my $query_cgi_history = $query->url( -query => 1 ); $query_cgi_history =~ s/^$path_info\?//; $query_cgi_history =~ s/;/&/g; - unless ( $loggedinuser ) { - my $new_search = C4::Search::History::add_to_session({ - cgi => $query, + unless ($loggedinuser) { + my $new_search = C4::Search::History::add_to_session( + { + cgi => $query, query_desc => $value[0], - query_cgi => $query_cgi_history, - total => $total, - type => "authority", - }); + query_cgi => $query_cgi_history, + total => $total, + type => "authority", + } + ); } else { + # To the session (the user is logged in) - C4::Search::History::add({ - userid => $loggedinuser, - sessionid => $query->cookie("CGISESSID"), - query_desc => $value[0], - query_cgi => $query_cgi_history, - total => $total, - type => "authority", - }); + C4::Search::History::add( + { + userid => $loggedinuser, + sessionid => $query->cookie("CGISESSID"), + query_desc => $value[0], + query_cgi => $query_cgi_history, + total => $total, + type => "authority", + } + ); } } } @@ -181,15 +186,14 @@ if ( $op eq "do_search" ) { $template->param( startfrom => $startfrom, resultsperpage => $resultsperpage, - countfuzzy => !(C4::Context->preference('OPACShowUnusedAuthorities')), + countfuzzy => !( C4::Context->preference('OPACShowUnusedAuthorities') ), resultcount => scalar @$results, authtypecode => $authtypecode, authtypetext => $authority_types->find($authtypecode)->authtypetext, isEDITORS => $authtypecode eq 'EDITORS', ); -} -else { +} else { ( $template, $loggedinuser, $cookie ) = get_template_and_user( { template_name => "opac-authorities-home.tt", diff --git a/opac/opac-authoritiesdetail.pl b/opac/opac-authoritiesdetail.pl index 2d271c1f86..2b5e5a8651 100755 --- a/opac/opac-authoritiesdetail.pl +++ b/opac/opac-authoritiesdetail.pl @@ -38,13 +38,13 @@ parameters tables. use Modern::Perl; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Biblio qw( GetMarcUrls ); use C4::Context; use C4::Languages; -use C4::Output qw( output_html_with_http_headers ); +use C4::Output qw( output_html_with_http_headers ); use C4::AuthoritiesMarc qw( GetAuthority BuildSummary GetTagsLabels GenerateHierarchy ); -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Koha; use Koha::Authorities; @@ -57,7 +57,7 @@ my $dbh = C4::Context->dbh; my $display_hierarchy = C4::Context->preference("AuthDisplayHierarchy"); my $marcflavour = C4::Context->preference("marcflavour"); -my $show_marc = $query->param('marc'); +my $show_marc = $query->param('marc'); # open template my ( $template, $loggedinuser, $cookie ) = get_template_and_user( @@ -71,24 +71,24 @@ my ( $template, $loggedinuser, $cookie ) = get_template_and_user( my $authid = $query->param('authid'); $authid = int($authid); -my $record = GetAuthority( $authid ); -if ( ! $record ) { - print $query->redirect("/cgi-bin/koha/errors/404.pl"); # escape early +my $record = GetAuthority($authid); +if ( !$record ) { + print $query->redirect("/cgi-bin/koha/errors/404.pl"); # escape early exit; } -my $authority = Koha::Authorities->find( $authid ); +my $authority = Koha::Authorities->find($authid); my $authtypecode = $authority ? $authority->authtypecode : q{}; -if ($display_hierarchy){ +if ($display_hierarchy) { $template->{VARS}->{'displayhierarchy'} = $display_hierarchy; - $template->{VARS}->{'loophierarchies'} = GenerateHierarchy($authid); + $template->{VARS}->{'loophierarchies'} = GenerateHierarchy($authid); } my $count = $authority ? $authority->get_usage_count : 0; my $authority_types = Koha::Authority::Types->search( {}, { order_by => ['authtypecode'] } ); -my $marcurlsarray = GetMarcUrls( $record, $marcflavour ); +my $marcurlsarray = GetMarcUrls( $record, $marcflavour ); $template->param( authority_types => $authority_types, @@ -101,10 +101,7 @@ $template->param( # find the marc field/subfield used in biblio by this authority if ($show_marc) { my $tagslib = GetTagsLabels( 0, $authtypecode ); - my $sth = - $dbh->prepare( - "select distinct tagfield from marc_subfield_structure where authtypecode=?" - ); + my $sth = $dbh->prepare("select distinct tagfield from marc_subfield_structure where authtypecode=?"); $sth->execute($authtypecode); my $biblio_fields; while ( my ($tagfield) = $sth->fetchrow ) { @@ -112,56 +109,55 @@ if ($show_marc) { } chop $biblio_fields; -# fill arrays + # fill arrays my @loop_data = (); -# loop through each tag - my @fields = $record->fields(); + # loop through each tag + my @fields = $record->fields(); foreach my $field (@fields) { my @subfields_data; -# skip UNIMARC fields <200, they are useless for a patron - next if $marcflavour eq 'UNIMARC' && $field->tag() <200; + # skip UNIMARC fields <200, they are useless for a patron + next if $marcflavour eq 'UNIMARC' && $field->tag() < 200; -# if tag <10, there's no subfield, use the "@" trick + # if tag <10, there's no subfield, use the "@" trick if ( $field->tag() < 10 ) { next if ( $tagslib->{ $field->tag() }->{'@'}->{hidden} ); my %subfield_data; - $subfield_data{marc_lib} = $tagslib->{ $field->tag() }->{'@'}->{lib}; - $subfield_data{marc_value} = $field->data(); + $subfield_data{marc_lib} = $tagslib->{ $field->tag() }->{'@'}->{lib}; + $subfield_data{marc_value} = $field->data(); $subfield_data{marc_subfield} = '@'; $subfield_data{marc_tag} = $field->tag(); push( @subfields_data, \%subfield_data ); - } - elsif ( $marcflavour eq 'MARC21' && $field->tag() eq 667 ) { + } elsif ( $marcflavour eq 'MARC21' && $field->tag() eq 667 ) { + # tagfield 667 is a nonpublic general note in MARC21, which shouldn't be shown in the OPAC - } - else { + } else { my @subf = $field->subfields; -# loop through each subfield + # loop through each subfield for my $i ( 0 .. $#subf ) { $subf[$i][0] = "@" unless defined $subf[$i][0]; next if ( $tagslib->{ $field->tag() }->{ $subf[$i][0] }->{hidden} ); -# skip useless subfields (for patrons) + + # skip useless subfields (for patrons) next if $subf[$i][0] =~ /7|8|9/; my %subfield_data; $subfield_data{marc_lib} = $tagslib->{ $field->tag() }->{ $subf[$i][0] }->{lib}; $subfield_data{marc_subfield} = $subf[$i][0]; $subfield_data{marc_tag} = $field->tag(); - $subfield_data{isurl} = $tagslib->{ $field->tag() }->{ $subf[$i][0] }->{isurl}; - $subfield_data{marc_value} = $subf[$i][1]; + $subfield_data{isurl} = $tagslib->{ $field->tag() }->{ $subf[$i][0] }->{isurl}; + $subfield_data{marc_value} = $subf[$i][1]; push( @subfields_data, \%subfield_data ); } } if ( $#subfields_data >= 0 ) { my %tag_data; $tag_data{tag} = - $field->tag() - . ' ' - . C4::Koha::display_marc_indicators($field) - . ' - ' . $tagslib->{ $field->tag() }->{lib}; + $field->tag() . ' ' + . C4::Koha::display_marc_indicators($field) . ' - ' + . $tagslib->{ $field->tag() }->{lib}; $tag_data{subfield} = \@subfields_data; push( @loop_data, \%tag_data ); } @@ -179,19 +175,19 @@ if ($show_marc) { $xsl =~ s/\{langcode\}/$lang/g; $xsl =~ s/\{authtypecode\}/$authtypecode/g; my $xslt_engine = Koha::XSLT::Base->new; - my $output = $xslt_engine->transform({ xml => $authority->marcxml, file => $xsl }); - if ($xslt_engine->err) { + my $output = $xslt_engine->transform( { xml => $authority->marcxml, file => $xsl } ); + if ( $xslt_engine->err ) { warn "XSL transformation failed ($xsl): " . $xslt_engine->err; next; } - $template->param(html => $output); + $template->param( html => $output ); } else { - my $summary = BuildSummary($record, $authid, $authtypecode); - $template->param(summary => $summary); + my $summary = BuildSummary( $record, $authid, $authtypecode ); + $template->param( summary => $summary ); } if ( C4::Context->preference('OPACAuthorIdentifiersAndInformation') ) { - my $authority = Koha::Authorities->find($authid); + my $authority = Koha::Authorities->find($authid); my $information = $authority->get_identifiers_and_information; $template->param( author_information => $information ); } diff --git a/opac/opac-basket.pl b/opac/opac-basket.pl index e4ed044a85..e96b7d55ec 100755 --- a/opac/opac-basket.pl +++ b/opac/opac-basket.pl @@ -26,7 +26,7 @@ use C4::Biblio qw( GetMarcSubjects GetMarcUrls ); -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use Koha::RecordProcessor; use Koha::CsvProfiles; @@ -36,7 +36,7 @@ use Koha::Items; my $query = CGI->new; -my ( $template, $borrowernumber, $cookie ) = get_template_and_user ( +my ( $template, $borrowernumber, $cookie ) = get_template_and_user( { template_name => "opac-basket.tt", query => $query, @@ -45,64 +45,66 @@ my ( $template, $borrowernumber, $cookie ) = get_template_and_user ( } ); -my $bib_list = $query->param('bib_list'); -my $verbose = $query->param('verbose'); +my $bib_list = $query->param('bib_list'); +my $verbose = $query->param('verbose'); -if ($verbose) { $template->param( verbose => 1 ); } +if ($verbose) { $template->param( verbose => 1 ); } my @bibs = split( /\//, $bib_list ); my @results; -my $num = 1; +my $num = 1; my $marcflavour = C4::Context->preference('marcflavour'); -if (C4::Context->preference('TagsEnabled')) { - $template->param(TagsEnabled => 1); - foreach (qw(TagsShowOnList TagsInputOnList)) { - C4::Context->preference($_) and $template->param($_ => 1); - } +if ( C4::Context->preference('TagsEnabled') ) { + $template->param( TagsEnabled => 1 ); + foreach (qw(TagsShowOnList TagsInputOnList)) { + C4::Context->preference($_) and $template->param( $_ => 1 ); + } } my $logged_in_user = Koha::Patrons->find($borrowernumber); -my $record_processor = Koha::RecordProcessor->new({ filters => 'ViewPolicy' }); -my $rules = C4::Context->yaml_preference('OpacHiddenItems'); +my $record_processor = Koha::RecordProcessor->new( { filters => 'ViewPolicy' } ); +my $rules = C4::Context->yaml_preference('OpacHiddenItems'); -foreach my $biblionumber ( @bibs ) { +foreach my $biblionumber (@bibs) { $template->param( biblionumber => $biblionumber ); - my $biblio = Koha::Biblios->find( $biblionumber ) or next; - my $dat = { %{$biblio->unblessed}, %{$biblio->biblioitem->unblessed} }; + my $biblio = Koha::Biblios->find($biblionumber) or next; + my $dat = { %{ $biblio->unblessed }, %{ $biblio->biblioitem->unblessed } }; # No filtering on the item records needed for the record itself # since the only reason item information is grabbed is because of branchcodes. - my $record = $biblio->metadata->record; - my $framework = &GetFrameworkCode( $biblionumber ); - $record_processor->options({ - interface => 'opac', - frameworkcode => $framework - }); + my $record = $biblio->metadata->record; + my $framework = &GetFrameworkCode($biblionumber); + $record_processor->options( + { + interface => 'opac', + frameworkcode => $framework + } + ); $record_processor->process($record); next unless $record; - my $marcnotesarray = $biblio->get_marc_notes({ opac => 1 }); + my $marcnotesarray = $biblio->get_marc_notes( { opac => 1 } ); my $marcauthorsarray = $biblio->get_marc_contributors; my $marcsubjctsarray = GetMarcSubjects( $record, $marcflavour ); - my $marcseriesarray = GetMarcSeries ($record,$marcflavour); - my $marcurlsarray = GetMarcUrls ($record,$marcflavour); + my $marcseriesarray = GetMarcSeries( $record, $marcflavour ); + my $marcurlsarray = GetMarcUrls( $record, $marcflavour ); # If every item is hidden, then the biblio should be hidden too. next - if $biblio->hidden_in_opac({ rules => $rules }); + if $biblio->hidden_in_opac( { rules => $rules } ); my $hasauthors = 0; - if($dat->{'author'} || @$marcauthorsarray) { - $hasauthors = 1; + if ( $dat->{'author'} || @$marcauthorsarray ) { + $hasauthors = 1; } - # COinS format FIXME: for books Only - my $fmt = substr $record->leader(), 6,2; - my $fmts; - $fmts->{'am'} = 'book'; - $dat->{ocoins_format} = $fmts->{$fmt}; + # COinS format FIXME: for books Only + my $fmt = substr $record->leader(), 6, 2; + my $fmts; + $fmts->{'am'} = 'book'; + $dat->{ocoins_format} = $fmts->{$fmt}; if ( $num % 2 == 1 ) { $dat->{'even'} = 1; @@ -110,17 +112,17 @@ foreach my $biblionumber ( @bibs ) { $num++; $dat->{biblionumber} = $biblionumber; - $dat->{ITEM_RESULTS} = $biblio->items->filter_by_visible_in_opac({ patron => $logged_in_user }); - $dat->{MARCNOTES} = $marcnotesarray; - $dat->{MARCSUBJCTS} = $marcsubjctsarray; - $dat->{MARCAUTHORS} = $marcauthorsarray; - $dat->{MARCSERIES} = $marcseriesarray; - $dat->{MARCURLS} = $marcurlsarray; - $dat->{HASAUTHORS} = $hasauthors; + $dat->{ITEM_RESULTS} = $biblio->items->filter_by_visible_in_opac( { patron => $logged_in_user } ); + $dat->{MARCNOTES} = $marcnotesarray; + $dat->{MARCSUBJCTS} = $marcsubjctsarray; + $dat->{MARCAUTHORS} = $marcauthorsarray; + $dat->{MARCSERIES} = $marcseriesarray; + $dat->{MARCURLS} = $marcurlsarray; + $dat->{HASAUTHORS} = $hasauthors; my ( $host, $relatedparts, $hostinfo ) = $biblio->get_marc_host; $dat->{HOSTITEMENTRIES} = $host; - $dat->{RELATEDPARTS} = $relatedparts; - $dat->{HOSTINFO} = $hostinfo; + $dat->{RELATEDPARTS} = $relatedparts; + $dat->{HOSTINFO} = $hostinfo; push( @results, $dat ); } @@ -130,9 +132,8 @@ my $resultsarray = \@results; # my $itemsarray=\@items; $template->param( - csv_profiles => Koha::CsvProfiles->search( - { type => 'marc', used_for => 'export_records', staff_only => 0 } ), - bib_list => $bib_list, + csv_profiles => Koha::CsvProfiles->search( { type => 'marc', used_for => 'export_records', staff_only => 0 } ), + bib_list => $bib_list, BIBLIO_RESULTS => $resultsarray, ); diff --git a/opac/opac-blocked.pl b/opac/opac-blocked.pl index a604fefdbd..f7668de586 100755 --- a/opac/opac-blocked.pl +++ b/opac/opac-blocked.pl @@ -18,8 +18,8 @@ # along with Koha; if not, see . use Modern::Perl; -use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_with_http_headers ); use C4::Context; diff --git a/opac/opac-browse.pl b/opac/opac-browse.pl index bde1e716aa..410109b547 100755 --- a/opac/opac-browse.pl +++ b/opac/opac-browse.pl @@ -49,31 +49,28 @@ if ( !$api ) { authnotrequired => ( C4::Context->preference("OpacPublic") ? 1 : 0 ), } ); - $template->param(); + $template->param(); output_html_with_http_headers $query, $cookie, $template->output; - -} -elsif ( $api eq 'GetSuggestions' ) { +} elsif ( $api eq 'GetSuggestions' ) { my $fuzzie = $query->param('fuzziness'); my $prefix = $query->param('prefix'); my $field = $query->param('field'); -# Under a persistent environment, we should probably not reinit this every time. + # Under a persistent environment, we should probably not reinit this every time. my $browser = Koha::SearchEngine::Elasticsearch::Browse->new( { index => 'biblios' } ); - my $res = $browser->browse( $prefix, $field, { fuzziness => $fuzzie } ); + my $res = $browser->browse( $prefix, $field, { fuzziness => $fuzzie } ); my %seen; my @sorted = - grep { !$seen{$_->{text}}++ } - sort { lc($a->{text}) cmp lc($b->{text}) } @$res; + grep { !$seen{ $_->{text} }++ } + sort { lc( $a->{text} ) cmp lc( $b->{text} ) } @$res; print CGI::header( -type => 'application/json', -charset => 'utf-8' ); print to_json( \@sorted ); -} -elsif ( $api eq 'GetResults' ) { +} elsif ( $api eq 'GetResults' ) { my $term = $query->param('term'); my $field = $query->param('field'); @@ -81,9 +78,9 @@ elsif ( $api eq 'GetResults' ) { my $searcher = Koha::SearchEngine::Elasticsearch::Search->new( { index => $Koha::SearchEngine::Elasticsearch::BIBLIOS_INDEX } ); - my $query = { query => { term => { $field.".raw" => $term } } } ; + my $query = { query => { term => { $field . ".raw" => $term } } }; my $results = $searcher->search( $query, undef, 500 ); - my @output = _filter_for_output( $results->{hits}->{hits} ); + my @output = _filter_for_output( $results->{hits}->{hits} ); print CGI::header( -type => 'application/json', -charset => 'utf-8' @@ -98,16 +95,16 @@ sub _filter_for_output { my @output; foreach my $rec (@$records) { my $biblionumber = $rec->{_id}; - my $biblio = Koha::Biblios->find( $biblionumber ); + my $biblio = Koha::Biblios->find($biblionumber); next unless $biblio; push @output, - { - id => $biblionumber, + { + id => $biblionumber, title => $biblio->title, subtitle => $biblio->subtitle, - author => $biblio->author, - }; - }; - my @sorted = sort { lc($a->{title}) cmp lc($b->{title}) } @output; + author => $biblio->author, + }; + } + my @sorted = sort { lc( $a->{title} ) cmp lc( $b->{title} ) } @output; return @sorted; } diff --git a/opac/opac-browser.pl b/opac/opac-browser.pl index 806d468bb7..4bd1c1d4c7 100755 --- a/opac/opac-browser.pl +++ b/opac/opac-browser.pl @@ -17,7 +17,6 @@ # You should have received a copy of the GNU General Public License # along with Koha; if not, see . - =head1 opac-browser.pl TODO :: Description here @@ -29,7 +28,7 @@ use Modern::Perl; use C4::Auth qw( get_template_and_user ); use C4::Context; use C4::Output qw( output_html_with_http_headers ); -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); my $query = CGI->new; @@ -46,19 +45,19 @@ my ( $template, $loggedinuser, $cookie ) = get_template_and_user( ); # the level of browser to display -my $level = $query->param('level') || 0; +my $level = $query->param('level') || 0; my $filter = $query->param('cud-filter'); $filter = '' unless defined $filter; -$level++; # the level passed is the level of the PREVIOUS list, not the current one. Thus the ++ +$level++; # the level passed is the level of the PREVIOUS list, not the current one. Thus the ++ # build this level loop my $sth = $dbh->prepare("SELECT * FROM browser WHERE level=? and classification like ? ORDER BY classification"); -$sth->execute($level,$filter."%"); +$sth->execute( $level, $filter . "%" ); my @level_loop; -my $i=0; -while (my $line = $sth->fetchrow_hashref) { +my $i = 0; +while ( my $line = $sth->fetchrow_hashref ) { $line->{description} =~ s/\((.*)\)//g; - push @level_loop,$line; + push @level_loop, $line; } my $have_hierarchy = 0; @@ -66,28 +65,29 @@ my $have_hierarchy = 0; # now rebuild hierarchy loop $filter =~ s/\.//g; my @hierarchy_loop; -if ($filter eq '' and $level == 1) { +if ( $filter eq '' and $level == 1 ) { + # we're starting from the top $have_hierarchy = 1 if @level_loop; unless (@level_loop) { - $sth->execute(1, "%"); - while (my $line = $sth->fetchrow_hashref) { + $sth->execute( 1, "%" ); + while ( my $line = $sth->fetchrow_hashref ) { $line->{description} =~ s/\((.*)\)//g; - push @level_loop,$line; + push @level_loop, $line; } } } else { $sth = $dbh->prepare("SELECT * FROM browser where classification=?"); - for (my $i=1;$i <=length($filter);$i++) { - $sth->execute(substr($filter,0,$i)); + for ( my $i = 1 ; $i <= length($filter) ; $i++ ) { + $sth->execute( substr( $filter, 0, $i ) ); my $line = $sth->fetchrow_hashref; - push @hierarchy_loop,$line; + push @hierarchy_loop, $line; } $have_hierarchy = 1 if @hierarchy_loop; } $template->param( - LEVEL_LOOP => \@level_loop, + LEVEL_LOOP => \@level_loop, HIERARCHY_LOOP => \@hierarchy_loop, have_hierarchy => $have_hierarchy, ); diff --git a/opac/opac-changelanguage.pl b/opac/opac-changelanguage.pl index eb1c296074..3283d709a6 100755 --- a/opac/opac-changelanguage.pl +++ b/opac/opac-changelanguage.pl @@ -20,8 +20,8 @@ use CGI qw ( -utf8 ); use C4::Templates; use Koha::Util::Navigation; -my $query = CGI->new; +my $query = CGI->new; my $language = $query->param('language'); -my $url = Koha::Util::Navigation::local_referer($query, { remove_language => 1 }); +my $url = Koha::Util::Navigation::local_referer( $query, { remove_language => 1 } ); C4::Templates::setlanguagecookie( $query, $language, $url ); diff --git a/opac/opac-course-details.pl b/opac/opac-course-details.pl index 415cade52f..29c420882c 100755 --- a/opac/opac-course-details.pl +++ b/opac/opac-course-details.pl @@ -22,7 +22,7 @@ use Modern::Perl; use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use C4::CourseReserves qw( GetCourse GetCourseReserve GetCourseReserves ); @@ -30,7 +30,8 @@ use C4::CourseReserves qw( GetCourse GetCourseReserve GetCourseReserves ); my $cgi = CGI->new; my ( $template, $borrowernumber, $cookie ) = get_template_and_user( - { template_name => "opac-course-details.tt", + { + template_name => "opac-course-details.tt", query => $cgi, type => "opac", authnotrequired => 1, @@ -41,7 +42,7 @@ my $course_id = $cgi->param('course_id'); die("No course_id given") unless ($course_id); -my $course = GetCourse($course_id); +my $course = GetCourse($course_id); my $course_reserves = GetCourseReserves( course_id => $course_id, include_items => 1, include_count => 1 ); $template->param( diff --git a/opac/opac-course-reserves.pl b/opac/opac-course-reserves.pl index e5d474b5ee..ee631a54a7 100755 --- a/opac/opac-course-reserves.pl +++ b/opac/opac-course-reserves.pl @@ -22,7 +22,7 @@ use Modern::Perl; use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use C4::CourseReserves qw( SearchCourses ); @@ -30,7 +30,8 @@ use C4::CourseReserves qw( SearchCourses ); my $cgi = CGI->new; my ( $template, $borrowernumber, $cookie ) = get_template_and_user( - { template_name => "opac-course-reserves.tt", + { + template_name => "opac-course-reserves.tt", query => $cgi, type => "opac", authnotrequired => 1, diff --git a/opac/opac-curbside-pickups.pl b/opac/opac-curbside-pickups.pl index 0486a4433f..8f986b75e8 100755 --- a/opac/opac-curbside-pickups.pl +++ b/opac/opac-curbside-pickups.pl @@ -15,12 +15,11 @@ # You should have received a copy of the GNU General Public License # along with Koha; if not, see . - use Modern::Perl; use CGI qw ( -utf8 ); use Try::Tiny; use C4::Members; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use Koha::DateUtils qw( dt_from_string ); @@ -32,13 +31,13 @@ use Koha::Patrons; my $input = CGI->new; my ( $template, $borrowernumber, $cookie ) = get_template_and_user( { - template_name => "opac-curbside-pickups.tt", - query => $input, - type => "opac", + template_name => "opac-curbside-pickups.tt", + query => $input, + type => "opac", } ); -unless( C4::Context->preference('CurbsidePickup') ) { +unless ( C4::Context->preference('CurbsidePickup') ) { print $input->redirect("/cgi-bin/koha/errors/404.pl"); exit; } @@ -46,7 +45,7 @@ unless( C4::Context->preference('CurbsidePickup') ) { my $op = $input->param('op') || 'list'; my $logged_in_patron = Koha::Patrons->find($borrowernumber); -my $branchcode = $input->param('pickup_branch'); +my $branchcode = $input->param('pickup_branch'); my @messages; if ( $op eq 'cud-create-pickup' ) { @@ -66,8 +65,8 @@ if ( $op eq 'cud-create-pickup' ) { } catch { if ( $_->isa('Koha::Exceptions::CurbsidePickup::NotEnabled') ) { push @messages, { - type => 'error', - code => 'not_enabled', + type => 'error', + code => 'not_enabled', }; } elsif ( $_->isa('Koha::Exceptions::CurbsidePickup::LibraryIsClosed') ) { push @messages, { @@ -77,8 +76,8 @@ if ( $op eq 'cud-create-pickup' ) { }; } elsif ( $_->isa('Koha::Exceptions::CurbsidePickup::NoWaitingHolds') ) { push @messages, { - type => 'error', - code => 'no_waiting_holds', + type => 'error', + code => 'no_waiting_holds', }; } elsif ( $_->isa('Koha::Exceptions::CurbsidePickup::TooManyPickups') ) { push @messages, { @@ -88,40 +87,36 @@ if ( $op eq 'cud-create-pickup' ) { }; } elsif ( $_->isa('Koha::Exceptions::CurbsidePickup::NoMatchingSlots') ) { push @messages, { - type => 'error', - code => 'no_matching_slots', + type => 'error', + code => 'no_matching_slots', }; } elsif ( $_->isa('Koha::Exceptions::CurbsidePickup::NoMorePickupsAvailable') ) { push @messages, { - type => 'error', - code => 'no_more_pickups_available', + type => 'error', + code => 'no_more_pickups_available', }; } else { warn $_; push @messages, { - type => 'error', - code => 'something_wrong_happened', + type => 'error', + code => 'something_wrong_happened', }; } } -} -elsif ( $op eq 'cud-cancel-pickup' ) { +} elsif ( $op eq 'cud-cancel-pickup' ) { my $id = $input->param('pickup_id'); - my $curbside_pickup = Koha::CurbsidePickups->search( - { borrowernumber => $borrowernumber } )->find($id); + my $curbside_pickup = Koha::CurbsidePickups->search( { borrowernumber => $borrowernumber } )->find($id); $curbside_pickup->delete - if $curbside_pickup - && !$curbside_pickup->delivered_datetime; -} -elsif ( $op eq 'cud-arrival-alert' ) { + if $curbside_pickup + && !$curbside_pickup->delivered_datetime; +} elsif ( $op eq 'cud-arrival-alert' ) { my $id = $input->param('pickup_id'); - my $curbside_pickup = Koha::CurbsidePickups->search( - { borrowernumber => $borrowernumber } )->find($id); + my $curbside_pickup = Koha::CurbsidePickups->search( { borrowernumber => $borrowernumber } )->find($id); $curbside_pickup->mark_patron_has_arrived if $curbside_pickup; push @messages, { type => 'message', code => 'library_notified', - } + }; } $template->param( @@ -146,4 +141,4 @@ $template->param( ); output_html_with_http_headers $input, $cookie, $template->output, undef, - { force_no_caching => 1 }; + { force_no_caching => 1 }; diff --git a/opac/opac-detail.pl b/opac/opac-detail.pl index 348e509f6a..b7680060c7 100755 --- a/opac/opac-detail.pl +++ b/opac/opac-detail.pl @@ -19,23 +19,22 @@ # You should have received a copy of the GNU General Public License # along with Koha; if not, see . - use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Acquisition qw( SearchOrders ); -use C4::Auth qw( get_template_and_user get_session ); -use C4::Koha qw( +use C4::Auth qw( get_template_and_user get_session ); +use C4::Koha qw( getitemtypeimagelocation GetNormalizedEAN GetNormalizedISBN GetNormalizedOCLCNumber GetNormalizedUPC ); -use C4::Search qw( new_record_from_zebra searchResults getRecords ); +use C4::Search qw( new_record_from_zebra searchResults getRecords ); use C4::Serials qw( CountSubscriptionFromBiblionumber SearchSubscriptions GetLatestSerials ); -use C4::Output qw( parametrized_url output_html_with_http_headers ); -use C4::Biblio qw( +use C4::Output qw( parametrized_url output_html_with_http_headers ); +use C4::Biblio qw( CountItemsIssued GetBiblioData GetMarcISBN @@ -44,12 +43,12 @@ use C4::Biblio qw( GetMarcSubjects GetMarcUrls ); -use C4::Record qw( marc2cites ); -use C4::Tags qw( get_tags ); -use C4::XISBN qw( get_xisbns ); -use C4::External::Amazon qw( get_amazon_tld ); +use C4::Record qw( marc2cites ); +use C4::Tags qw( get_tags ); +use C4::XISBN qw( get_xisbns ); +use C4::External::Amazon qw( get_amazon_tld ); use C4::External::BakerTaylor qw( image_url link_url ); -use C4::External::Syndetics qw( +use C4::External::Syndetics qw( get_syndetics_anotes get_syndetics_excerpt get_syndetics_index @@ -58,10 +57,10 @@ use C4::External::Syndetics qw( get_syndetics_toc ); use C4::Members; -use C4::XSLT qw( XSLTParse4Display ); +use C4::XSLT qw( XSLTParse4Display ); use C4::ShelfBrowser qw( GetNearbyItems ); -use C4::Reserves qw( GetReserveStatus IsAvailableForItemLevelRequest ); -use C4::Charset qw( SetUTF8Flag ); +use C4::Reserves qw( GetReserveStatus IsAvailableForItemLevelRequest ); +use C4::Charset qw( SetUTF8Flag ); use MARC::Field; use List::MoreUtils qw( any ); use C4::HTML5Media; @@ -103,12 +102,12 @@ my ( $template, $borrowernumber, $cookie ) = get_template_and_user( } ); -my $patron = Koha::Patrons->find( $borrowernumber ); +my $patron = Koha::Patrons->find($borrowernumber); -my $biblio = Koha::Biblios->find( $biblionumber ); +my $biblio = Koha::Biblios->find($biblionumber); my $record = $biblio ? $biblio->metadata->record : undef; unless ( $biblio && $record ) { - print $query->redirect("/cgi-bin/koha/errors/404.pl"); # escape early + print $query->redirect("/cgi-bin/koha/errors/404.pl"); # escape early exit; } @@ -121,10 +120,11 @@ if ($specific_item) { } unless ( $patron and $patron->category->override_hidden_items ) { + # only skip this check if there's a logged in user # and its category overrides OpacHiddenItems - if ( $biblio->hidden_in_opac({ rules => C4::Context->yaml_preference('OpacHiddenItems') }) ) { - print $query->redirect('/cgi-bin/koha/errors/404.pl'); # escape early + if ( $biblio->hidden_in_opac( { rules => C4::Context->yaml_preference('OpacHiddenItems') } ) ) { + print $query->redirect('/cgi-bin/koha/errors/404.pl'); # escape early exit; } if ( $items->count >= 1 ) { @@ -132,22 +132,26 @@ unless ( $patron and $patron->category->override_hidden_items ) { } } -my $framework = $biblio ? $biblio->frameworkcode : q{}; -my $record_processor = Koha::RecordProcessor->new({ - filters => 'ViewPolicy', - options => { - interface => 'opac', - frameworkcode => $framework +my $framework = $biblio ? $biblio->frameworkcode : q{}; +my $record_processor = Koha::RecordProcessor->new( + { + filters => 'ViewPolicy', + options => { + interface => 'opac', + frameworkcode => $framework + } } -}); +); $record_processor->process($record); # redirect if opacsuppression is enabled and biblio is suppressed -if (C4::Context->preference('OpacSuppression')) { +if ( C4::Context->preference('OpacSuppression') ) { + # FIXME hardcoded; the suppression flag ought to be materialized # as a column on biblio or the like - my $opacsuppressionfield = '942'; + my $opacsuppressionfield = '942'; my $opacsuppressionfieldvalue = $record->field($opacsuppressionfield); + # redirect to opac-blocked info page or 404? my $opacsuppressionredirect; if ( C4::Context->preference("OpacSuppressionRedirect") ) { @@ -155,14 +159,15 @@ if (C4::Context->preference('OpacSuppression')) { } else { $opacsuppressionredirect = "/cgi-bin/koha/errors/404.pl"; } - if ( $opacsuppressionfieldvalue && - $opacsuppressionfieldvalue->subfield("n") && - $opacsuppressionfieldvalue->subfield("n") == 1) { + if ( $opacsuppressionfieldvalue + && $opacsuppressionfieldvalue->subfield("n") + && $opacsuppressionfieldvalue->subfield("n") == 1 ) + { # if OPAC suppression by IP address - if (C4::Context->preference('OpacSuppressionByIPRange')) { + if ( C4::Context->preference('OpacSuppressionByIPRange') ) { my $IPAddress = $ENV{'REMOTE_ADDR'}; - my $IPRange = C4::Context->preference('OpacSuppressionByIPRange'); - if ($IPAddress !~ /^$IPRange/) { + my $IPRange = C4::Context->preference('OpacSuppressionByIPRange'); + if ( $IPAddress !~ /^$IPRange/ ) { print $query->redirect($opacsuppressionredirect); exit; } @@ -173,363 +178,409 @@ if (C4::Context->preference('OpacSuppression')) { } } -$template->param( - biblio => $biblio -); +$template->param( biblio => $biblio ); # get biblionumbers stored in the cart my @cart_list; -if($query->cookie("bib_list")){ +if ( $query->cookie("bib_list") ) { my $cart_list = $query->cookie("bib_list"); - @cart_list = split(/\//, $cart_list); - if ( grep {$_ eq $biblionumber} @cart_list) { + @cart_list = split( /\//, $cart_list ); + if ( grep { $_ eq $biblionumber } @cart_list ) { $template->param( incart => 1 ); } } - SetUTF8Flag($record); -my $marcflavour = C4::Context->preference("marcflavour"); -my $ean = GetNormalizedEAN( $record, $marcflavour ); +my $marcflavour = C4::Context->preference("marcflavour"); +my $ean = GetNormalizedEAN( $record, $marcflavour ); my $OpacBrowseResults = C4::Context->preference("OpacBrowseResults"); # We look for the busc param to build the simple paging from the search if ($OpacBrowseResults) { -my $session = get_session($query->cookie("CGISESSID")); -my %paging = (previous => {}, next => {}); -if ($session->param('busc')) { - use URI::Escape qw( uri_escape_utf8 uri_unescape ); + my $session = get_session( $query->cookie("CGISESSID") ); + my %paging = ( previous => {}, next => {} ); + if ( $session->param('busc') ) { + use URI::Escape qw( uri_escape_utf8 uri_unescape ); - # Rebuild the string to store on session - # param value is URI encoded and params separator is HTML encode (&) - sub rebuildBuscParam - { - my $arrParamsBusc = shift; + # Rebuild the string to store on session + # param value is URI encoded and params separator is HTML encode (&) + sub rebuildBuscParam { + my $arrParamsBusc = shift; - my $pasarParams = ''; - my $j = 0; - for (keys %$arrParamsBusc) { - if ($_ =~ /^(?:query|listBiblios|newlistBiblios|query_type|simple_query|total|offset|offsetSearch|next|previous|count|expand|scan)/) { - if (defined($arrParamsBusc->{$_})) { - $pasarParams .= '&' if ($j); - $pasarParams .= $_ . '=' . Encode::decode('UTF-8', uri_escape_utf8( $arrParamsBusc->{$_} )); - $j++; - } - } else { - for my $value (@{$arrParamsBusc->{$_}}) { - next if !defined($value); - $pasarParams .= '&' if ($j); - $pasarParams .= $_ . '=' . Encode::decode('UTF-8', uri_escape_utf8($value)); - $j++; - } - } - } - return $pasarParams; - }#rebuildBuscParam - - # Search given the current values from the busc param - sub searchAgain - { - my ($arrParamsBusc, $offset, $results_per_page, $patron) = @_; - - my $itemtypes = { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search_with_localization->unblessed } }; - my @servers; - @servers = @{$arrParamsBusc->{'server'}} if $arrParamsBusc->{'server'}; - @servers = ("biblioserver") unless (@servers); - - my ($default_sort_by, @sort_by); - $default_sort_by = C4::Context->default_catalog_sort_by; - @sort_by = @{$arrParamsBusc->{'sort_by'}} if $arrParamsBusc->{'sort_by'}; - $sort_by[0] = $default_sort_by if !$sort_by[0] && defined($default_sort_by); - my ($error, $results_hashref, $facets); - eval { - my $searcher = Koha::SearchEngine::Search->new( - { index => $Koha::SearchEngine::BIBLIOS_INDEX } ); - my $json = JSON->new->utf8->allow_nonref(1); - ($error, $results_hashref, $facets) = $searcher->search_compat($json->decode($arrParamsBusc->{'query'}),$arrParamsBusc->{'simple_query'},\@sort_by,\@servers,$results_per_page,$offset,undef,$itemtypes,$arrParamsBusc->{'query_type'},$arrParamsBusc->{'scan'}); - }; - my $hits; - my @newresults; - my $search_context = { - interface => 'opac', - patron => $patron, - }; - for (my $i=0;$i<@servers;$i++) { - my $server = $servers[$i]; - $hits = $results_hashref->{$server}->{"hits"}; - @newresults = searchResults( $search_context, '', $hits, $results_per_page, $offset, $arrParamsBusc->{'scan'}, $results_hashref->{$server}->{"RECORDS"}); - } - return \@newresults; - }#searchAgain - - # Build the current list of biblionumbers in this search - sub buildListBiblios - { - my ($newresultsRef, $results_per_page) = @_; - - my $listBiblios = ''; - my $j = 0; - foreach (@$newresultsRef) { - my $bibnum = ($_->{biblionumber})?$_->{biblionumber}:0; - $listBiblios .= $bibnum . ','; - $j++; - last if ($j == $results_per_page); - } - chop $listBiblios if ($listBiblios =~ /,$/); - return $listBiblios; - }#buildListBiblios - - my $busc = $session->param("busc"); - my @arrBusc = split(/\&(?:amp;)?/, $busc); - my ($key, $value); - my %arrParamsBusc = (); - for (@arrBusc) { - ($key, $value) = split(/=/, $_, 2); - if ($key =~ /^(?:query|listBiblios|newlistBiblios|query_type|simple_query|next|previous|total|offset|offsetSearch|count|expand|scan)/) { - $arrParamsBusc{$key} = uri_unescape($value); - } else { - unless (exists($arrParamsBusc{$key})) { - $arrParamsBusc{$key} = []; - } - push @{$arrParamsBusc{$key}}, uri_unescape($value); - } - } - my $searchAgain = 0; - my $count = C4::Context->preference('OPACnumSearchResults') || 20; - my $results_per_page = ($arrParamsBusc{'count'} && $arrParamsBusc{'count'} =~ /^[0-9]+?/)?$arrParamsBusc{'count'}:$count; - $arrParamsBusc{'count'} = $results_per_page; - my $offset = ($arrParamsBusc{'offset'} && $arrParamsBusc{'offset'} =~ /^[0-9]+?/)?$arrParamsBusc{'offset'}:0; - # The value OPACnumSearchResults has changed and the search has to be rebuild - if ($count != $results_per_page) { - if (exists($arrParamsBusc{'listBiblios'}) && $arrParamsBusc{'listBiblios'} =~ /^[0-9]+(?:,[0-9]+)*$/) { - my $indexBiblio = 0; - my @arrBibliosAux = split(',', $arrParamsBusc{'listBiblios'}); - for (@arrBibliosAux) { - last if ($_ == $biblionumber); - $indexBiblio++; - } - $indexBiblio += $offset; - $offset = int($indexBiblio / $count) * $count; - $arrParamsBusc{'offset'} = $offset; - } - $arrParamsBusc{'count'} = $count; - $results_per_page = $count; - my $newresultsRef = searchAgain(\%arrParamsBusc, $offset, $results_per_page, $patron); - $arrParamsBusc{'listBiblios'} = buildListBiblios($newresultsRef, $results_per_page); - delete $arrParamsBusc{'previous'} if (exists($arrParamsBusc{'previous'})); - delete $arrParamsBusc{'next'} if (exists($arrParamsBusc{'next'})); - delete $arrParamsBusc{'offsetSearch'} if (exists($arrParamsBusc{'offsetSearch'})); - delete $arrParamsBusc{'newlistBiblios'} if (exists($arrParamsBusc{'newlistBiblios'})); - my $newbusc = rebuildBuscParam(\%arrParamsBusc); - $session->param("busc" => $newbusc); - @arrBusc = split(/\&(?:amp;)?/, $newbusc); - } else { - my $modifyListBiblios = 0; - # We come from a previous click - if (exists($arrParamsBusc{'previous'})) { - $modifyListBiblios = 1 if ($biblionumber == $arrParamsBusc{'previous'}); - delete $arrParamsBusc{'previous'}; - } elsif (exists($arrParamsBusc{'next'})) { # We come from a next click - $modifyListBiblios = 2 if ($biblionumber == $arrParamsBusc{'next'}); - delete $arrParamsBusc{'next'}; - } - if ($modifyListBiblios) { - if (exists($arrParamsBusc{'newlistBiblios'})) { - my $listBibliosAux = $arrParamsBusc{'listBiblios'}; - $arrParamsBusc{'listBiblios'} = $arrParamsBusc{'newlistBiblios'}; - my @arrAux = split(',', $listBibliosAux); - $arrParamsBusc{'newlistBiblios'} = $listBibliosAux; - if ($modifyListBiblios == 1) { - $arrParamsBusc{'next'} = $arrAux[0]; - $paging{'next'}->{biblionumber} = $arrAux[0]; - }else { - $arrParamsBusc{'previous'} = $arrAux[$#arrAux]; - $paging{'previous'}->{biblionumber} = $arrAux[$#arrAux]; - } - } else { - delete $arrParamsBusc{'listBiblios'}; - } - my $offsetAux = $arrParamsBusc{'offset'}; - $arrParamsBusc{'offset'} = $arrParamsBusc{'offsetSearch'}; - $arrParamsBusc{'offsetSearch'} = $offsetAux; - $offset = $arrParamsBusc{'offset'}; - my $newbusc = rebuildBuscParam(\%arrParamsBusc); - $session->param("busc" => $newbusc); - @arrBusc = split(/\&(?:amp;)?/, $newbusc); - } - } - my $buscParam = ''; - my $j = 0; - # Rebuild the query for the button "back to results" - for (@arrBusc) { - unless ($_ =~ /^(?:query|listBiblios|newlistBiblios|query_type|simple_query|next|previous|total|count|offsetSearch)/) { - $buscParam .= '&' unless ($j == 0); - $buscParam .= $_; # string already URI encoded - $j++; - } - } - $template->param('busc' => $buscParam); - my $offsetSearch; - my @arrBiblios; - # We are inside the list of biblios and we don't have to search - if (exists($arrParamsBusc{'listBiblios'}) && $arrParamsBusc{'listBiblios'} =~ /^[0-9]+(?:,[0-9]+)*$/) { - @arrBiblios = split(',', $arrParamsBusc{'listBiblios'}); - if (@arrBiblios) { - # We are at the first item of the list - if ($arrBiblios[0] == $biblionumber) { - if (@arrBiblios > 1) { - for (my $j = 1; $j < @arrBiblios; $j++) { - next unless ($arrBiblios[$j]); - $paging{'next'}->{biblionumber} = $arrBiblios[$j]; - last; + my $pasarParams = ''; + my $j = 0; + for ( keys %$arrParamsBusc ) { + if ( $_ =~ + /^(?:query|listBiblios|newlistBiblios|query_type|simple_query|total|offset|offsetSearch|next|previous|count|expand|scan)/ + ) + { + if ( defined( $arrParamsBusc->{$_} ) ) { + $pasarParams .= '&' if ($j); + $pasarParams .= $_ . '=' . Encode::decode( 'UTF-8', uri_escape_utf8( $arrParamsBusc->{$_} ) ); + $j++; } - } - # search again if we are not at the first searching list - if ($offset && !$arrParamsBusc{'previous'}) { - $searchAgain = 1; - $offsetSearch = $offset - $results_per_page; - } - # we are at the last item of the list - } elsif ($arrBiblios[$#arrBiblios] == $biblionumber) { - for (my $j = $#arrBiblios - 1; $j >= 0; $j--) { - next unless ($arrBiblios[$j]); - $paging{'previous'}->{biblionumber} = $arrBiblios[$j]; - last; - } - if (!$offset) { - # search again if we are at the first list and there is more results - $searchAgain = 1 if (!$arrParamsBusc{'next'} && $arrParamsBusc{'total'} != @arrBiblios); } else { - # search again if we aren't at the first list and there is more results - $searchAgain = 1 if (!$arrParamsBusc{'next'} && $arrParamsBusc{'total'} > ($offset + @arrBiblios)); + for my $value ( @{ $arrParamsBusc->{$_} } ) { + next if !defined($value); + $pasarParams .= '&' if ($j); + $pasarParams .= $_ . '=' . Encode::decode( 'UTF-8', uri_escape_utf8($value) ); + $j++; + } } - $offsetSearch = $offset + $results_per_page if ($searchAgain); + } + return $pasarParams; + } #rebuildBuscParam + + # Search given the current values from the busc param + sub searchAgain { + my ( $arrParamsBusc, $offset, $results_per_page, $patron ) = @_; + + my $itemtypes = { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search_with_localization->unblessed } }; + my @servers; + @servers = @{ $arrParamsBusc->{'server'} } if $arrParamsBusc->{'server'}; + @servers = ("biblioserver") unless (@servers); + + my ( $default_sort_by, @sort_by ); + $default_sort_by = C4::Context->default_catalog_sort_by; + @sort_by = @{ $arrParamsBusc->{'sort_by'} } if $arrParamsBusc->{'sort_by'}; + $sort_by[0] = $default_sort_by if !$sort_by[0] && defined($default_sort_by); + my ( $error, $results_hashref, $facets ); + eval { + my $searcher = Koha::SearchEngine::Search->new( { index => $Koha::SearchEngine::BIBLIOS_INDEX } ); + my $json = JSON->new->utf8->allow_nonref(1); + ( $error, $results_hashref, $facets ) = $searcher->search_compat( + $json->decode( $arrParamsBusc->{'query'} ), + $arrParamsBusc->{'simple_query'}, \@sort_by, \@servers, $results_per_page, $offset, undef, + $itemtypes, $arrParamsBusc->{'query_type'}, $arrParamsBusc->{'scan'} + ); + }; + my $hits; + my @newresults; + my $search_context = { + interface => 'opac', + patron => $patron, + }; + for ( my $i = 0 ; $i < @servers ; $i++ ) { + my $server = $servers[$i]; + $hits = $results_hashref->{$server}->{"hits"}; + @newresults = searchResults( + $search_context, '', $hits, $results_per_page, $offset, $arrParamsBusc->{'scan'}, + $results_hashref->{$server}->{"RECORDS"} + ); + } + return \@newresults; + } #searchAgain + + # Build the current list of biblionumbers in this search + sub buildListBiblios { + my ( $newresultsRef, $results_per_page ) = @_; + + my $listBiblios = ''; + my $j = 0; + foreach (@$newresultsRef) { + my $bibnum = ( $_->{biblionumber} ) ? $_->{biblionumber} : 0; + $listBiblios .= $bibnum . ','; + $j++; + last if ( $j == $results_per_page ); + } + chop $listBiblios if ( $listBiblios =~ /,$/ ); + return $listBiblios; + } #buildListBiblios + + my $busc = $session->param("busc"); + my @arrBusc = split( /\&(?:amp;)?/, $busc ); + my ( $key, $value ); + my %arrParamsBusc = (); + for (@arrBusc) { + ( $key, $value ) = split( /=/, $_, 2 ); + if ( $key =~ + /^(?:query|listBiblios|newlistBiblios|query_type|simple_query|next|previous|total|offset|offsetSearch|count|expand|scan)/ + ) + { + $arrParamsBusc{$key} = uri_unescape($value); } else { - for (my $j = 1; $j < $#arrBiblios; $j++) { - if ($arrBiblios[$j] == $biblionumber) { - for (my $z = $j - 1; $z >= 0; $z--) { - next unless ($arrBiblios[$z]); - $paging{'previous'}->{biblionumber} = $arrBiblios[$z]; + unless ( exists( $arrParamsBusc{$key} ) ) { + $arrParamsBusc{$key} = []; + } + push @{ $arrParamsBusc{$key} }, uri_unescape($value); + } + } + my $searchAgain = 0; + my $count = C4::Context->preference('OPACnumSearchResults') || 20; + my $results_per_page = + ( $arrParamsBusc{'count'} && $arrParamsBusc{'count'} =~ /^[0-9]+?/ ) ? $arrParamsBusc{'count'} : $count; + $arrParamsBusc{'count'} = $results_per_page; + my $offset = + ( $arrParamsBusc{'offset'} && $arrParamsBusc{'offset'} =~ /^[0-9]+?/ ) ? $arrParamsBusc{'offset'} : 0; + + # The value OPACnumSearchResults has changed and the search has to be rebuild + if ( $count != $results_per_page ) { + if ( exists( $arrParamsBusc{'listBiblios'} ) && $arrParamsBusc{'listBiblios'} =~ /^[0-9]+(?:,[0-9]+)*$/ ) { + my $indexBiblio = 0; + my @arrBibliosAux = split( ',', $arrParamsBusc{'listBiblios'} ); + for (@arrBibliosAux) { + last if ( $_ == $biblionumber ); + $indexBiblio++; + } + $indexBiblio += $offset; + $offset = int( $indexBiblio / $count ) * $count; + $arrParamsBusc{'offset'} = $offset; + } + $arrParamsBusc{'count'} = $count; + $results_per_page = $count; + my $newresultsRef = searchAgain( \%arrParamsBusc, $offset, $results_per_page, $patron ); + $arrParamsBusc{'listBiblios'} = buildListBiblios( $newresultsRef, $results_per_page ); + delete $arrParamsBusc{'previous'} if ( exists( $arrParamsBusc{'previous'} ) ); + delete $arrParamsBusc{'next'} if ( exists( $arrParamsBusc{'next'} ) ); + delete $arrParamsBusc{'offsetSearch'} if ( exists( $arrParamsBusc{'offsetSearch'} ) ); + delete $arrParamsBusc{'newlistBiblios'} if ( exists( $arrParamsBusc{'newlistBiblios'} ) ); + my $newbusc = rebuildBuscParam( \%arrParamsBusc ); + $session->param( "busc" => $newbusc ); + @arrBusc = split( /\&(?:amp;)?/, $newbusc ); + } else { + my $modifyListBiblios = 0; + + # We come from a previous click + if ( exists( $arrParamsBusc{'previous'} ) ) { + $modifyListBiblios = 1 if ( $biblionumber == $arrParamsBusc{'previous'} ); + delete $arrParamsBusc{'previous'}; + } elsif ( exists( $arrParamsBusc{'next'} ) ) { # We come from a next click + $modifyListBiblios = 2 if ( $biblionumber == $arrParamsBusc{'next'} ); + delete $arrParamsBusc{'next'}; + } + if ($modifyListBiblios) { + if ( exists( $arrParamsBusc{'newlistBiblios'} ) ) { + my $listBibliosAux = $arrParamsBusc{'listBiblios'}; + $arrParamsBusc{'listBiblios'} = $arrParamsBusc{'newlistBiblios'}; + my @arrAux = split( ',', $listBibliosAux ); + $arrParamsBusc{'newlistBiblios'} = $listBibliosAux; + if ( $modifyListBiblios == 1 ) { + $arrParamsBusc{'next'} = $arrAux[0]; + $paging{'next'}->{biblionumber} = $arrAux[0]; + } else { + $arrParamsBusc{'previous'} = $arrAux[$#arrAux]; + $paging{'previous'}->{biblionumber} = $arrAux[$#arrAux]; + } + } else { + delete $arrParamsBusc{'listBiblios'}; + } + my $offsetAux = $arrParamsBusc{'offset'}; + $arrParamsBusc{'offset'} = $arrParamsBusc{'offsetSearch'}; + $arrParamsBusc{'offsetSearch'} = $offsetAux; + $offset = $arrParamsBusc{'offset'}; + my $newbusc = rebuildBuscParam( \%arrParamsBusc ); + $session->param( "busc" => $newbusc ); + @arrBusc = split( /\&(?:amp;)?/, $newbusc ); + } + } + my $buscParam = ''; + my $j = 0; + + # Rebuild the query for the button "back to results" + for (@arrBusc) { + unless ( $_ =~ + /^(?:query|listBiblios|newlistBiblios|query_type|simple_query|next|previous|total|count|offsetSearch)/ ) + { + $buscParam .= '&' unless ( $j == 0 ); + $buscParam .= $_; # string already URI encoded + $j++; + } + } + $template->param( 'busc' => $buscParam ); + my $offsetSearch; + my @arrBiblios; + + # We are inside the list of biblios and we don't have to search + if ( exists( $arrParamsBusc{'listBiblios'} ) && $arrParamsBusc{'listBiblios'} =~ /^[0-9]+(?:,[0-9]+)*$/ ) { + @arrBiblios = split( ',', $arrParamsBusc{'listBiblios'} ); + if (@arrBiblios) { + + # We are at the first item of the list + if ( $arrBiblios[0] == $biblionumber ) { + if ( @arrBiblios > 1 ) { + for ( my $j = 1 ; $j < @arrBiblios ; $j++ ) { + next unless ( $arrBiblios[$j] ); + $paging{'next'}->{biblionumber} = $arrBiblios[$j]; last; } - for (my $z = $j + 1; $z < @arrBiblios; $z++) { - next unless ($arrBiblios[$z]); - $paging{'next'}->{biblionumber} = $arrBiblios[$z]; + } + + # search again if we are not at the first searching list + if ( $offset && !$arrParamsBusc{'previous'} ) { + $searchAgain = 1; + $offsetSearch = $offset - $results_per_page; + } + + # we are at the last item of the list + } elsif ( $arrBiblios[$#arrBiblios] == $biblionumber ) { + for ( my $j = $#arrBiblios - 1 ; $j >= 0 ; $j-- ) { + next unless ( $arrBiblios[$j] ); + $paging{'previous'}->{biblionumber} = $arrBiblios[$j]; + last; + } + if ( !$offset ) { + + # search again if we are at the first list and there is more results + $searchAgain = 1 if ( !$arrParamsBusc{'next'} && $arrParamsBusc{'total'} != @arrBiblios ); + } else { + + # search again if we aren't at the first list and there is more results + $searchAgain = 1 + if ( !$arrParamsBusc{'next'} && $arrParamsBusc{'total'} > ( $offset + @arrBiblios ) ); + } + $offsetSearch = $offset + $results_per_page if ($searchAgain); + } else { + for ( my $j = 1 ; $j < $#arrBiblios ; $j++ ) { + if ( $arrBiblios[$j] == $biblionumber ) { + for ( my $z = $j - 1 ; $z >= 0 ; $z-- ) { + next unless ( $arrBiblios[$z] ); + $paging{'previous'}->{biblionumber} = $arrBiblios[$z]; + last; + } + for ( my $z = $j + 1 ; $z < @arrBiblios ; $z++ ) { + next unless ( $arrBiblios[$z] ); + $paging{'next'}->{biblionumber} = $arrBiblios[$z]; + last; + } last; } + } + } + } + $offsetSearch = 0 if ( defined($offsetSearch) && $offsetSearch < 0 ); + } + if ($searchAgain) { + my $newresultsRef = searchAgain( \%arrParamsBusc, $offsetSearch, $results_per_page, $patron ); + my @newresults = @$newresultsRef; + + # build the new listBiblios + my $listBiblios = buildListBiblios( \@newresults, $results_per_page ); + unless ( exists( $arrParamsBusc{'listBiblios'} ) ) { + $arrParamsBusc{'listBiblios'} = $listBiblios; + @arrBiblios = split( ',', $arrParamsBusc{'listBiblios'} ); + } else { + $arrParamsBusc{'newlistBiblios'} = $listBiblios; + } + + # From the new list we build again the next and previous result + if (@arrBiblios) { + if ( $arrBiblios[0] == $biblionumber ) { + for ( my $j = $#newresults ; $j >= 0 ; $j-- ) { + next unless ( $newresults[$j] ); + $paging{'previous'}->{biblionumber} = $newresults[$j]->{biblionumber}; + $arrParamsBusc{'previous'} = $paging{'previous'}->{biblionumber}; + $arrParamsBusc{'offsetSearch'} = $offsetSearch; + last; + } + } elsif ( $arrBiblios[$#arrBiblios] == $biblionumber ) { + for ( my $j = 0 ; $j < @newresults ; $j++ ) { + next unless ( $newresults[$j] ); + $paging{'next'}->{biblionumber} = $newresults[$j]->{biblionumber}; + $arrParamsBusc{'next'} = $paging{'next'}->{biblionumber}; + $arrParamsBusc{'offsetSearch'} = $offsetSearch; last; } } } + + # build new busc param + my $newbusc = rebuildBuscParam( \%arrParamsBusc ); + $session->param( "busc" => $newbusc ); } - $offsetSearch = 0 if (defined($offsetSearch) && $offsetSearch < 0); - } - if ($searchAgain) { - my $newresultsRef = searchAgain(\%arrParamsBusc, $offsetSearch, $results_per_page, $patron); - my @newresults = @$newresultsRef; - # build the new listBiblios - my $listBiblios = buildListBiblios(\@newresults, $results_per_page); - unless (exists($arrParamsBusc{'listBiblios'})) { - $arrParamsBusc{'listBiblios'} = $listBiblios; - @arrBiblios = split(',', $arrParamsBusc{'listBiblios'}); - } else { - $arrParamsBusc{'newlistBiblios'} = $listBiblios; + my ( $numberBiblioPaging, $dataBiblioPaging ); + + # Previous biblio + $numberBiblioPaging = $paging{'previous'}->{biblionumber}; + if ($numberBiblioPaging) { + $template->param( 'previousBiblionumber' => $numberBiblioPaging ); + $dataBiblioPaging = Koha::Biblios->find($numberBiblioPaging); + $template->param( 'previousTitle' => $dataBiblioPaging->title ) if $dataBiblioPaging; } - # From the new list we build again the next and previous result - if (@arrBiblios) { - if ($arrBiblios[0] == $biblionumber) { - for (my $j = $#newresults; $j >= 0; $j--) { - next unless ($newresults[$j]); - $paging{'previous'}->{biblionumber} = $newresults[$j]->{biblionumber}; - $arrParamsBusc{'previous'} = $paging{'previous'}->{biblionumber}; - $arrParamsBusc{'offsetSearch'} = $offsetSearch; - last; - } - } elsif ($arrBiblios[$#arrBiblios] == $biblionumber) { - for (my $j = 0; $j < @newresults; $j++) { - next unless ($newresults[$j]); - $paging{'next'}->{biblionumber} = $newresults[$j]->{biblionumber}; - $arrParamsBusc{'next'} = $paging{'next'}->{biblionumber}; - $arrParamsBusc{'offsetSearch'} = $offsetSearch; - last; - } - } + + # Next biblio + $numberBiblioPaging = $paging{'next'}->{biblionumber}; + if ($numberBiblioPaging) { + $template->param( 'nextBiblionumber' => $numberBiblioPaging ); + $dataBiblioPaging = Koha::Biblios->find($numberBiblioPaging); + $template->param( 'nextTitle' => $dataBiblioPaging->title ) if $dataBiblioPaging; } - # build new busc param - my $newbusc = rebuildBuscParam(\%arrParamsBusc); - $session->param("busc" => $newbusc); + + # Partial list of biblio results + my @listResults; + for ( my $j = 0 ; $j < @arrBiblios ; $j++ ) { + next unless ( $arrBiblios[$j] ); + $dataBiblioPaging = Koha::Biblios->find( $arrBiblios[$j] ) if ( $arrBiblios[$j] != $biblionumber ); + next unless $dataBiblioPaging; + push @listResults, + { + index => $j + 1 + $offset, biblionumber => $arrBiblios[$j], + title => ( $arrBiblios[$j] == $biblionumber ) ? '' : $dataBiblioPaging->title, + author => ( $arrBiblios[$j] != $biblionumber && $dataBiblioPaging->author ) + ? $dataBiblioPaging->author + : '', part_number => ( $arrBiblios[$j] == $biblionumber ) ? '' : $dataBiblioPaging->part_number, + part_name => ( $arrBiblios[$j] == $biblionumber ) ? '' : $dataBiblioPaging->part_name, + url => ( $arrBiblios[$j] == $biblionumber ) ? '' : 'opac-detail.pl?biblionumber=' . $arrBiblios[$j] + }; + } + $template->param( 'listResults' => \@listResults ) if (@listResults); + $template->param( + 'indexPag' => 1 + $offset, 'totalPag' => $arrParamsBusc{'total'}, + 'indexPagEnd' => scalar(@arrBiblios) + $offset + ); + $template->param( 'offset' => $offset ); } - my ($numberBiblioPaging, $dataBiblioPaging); - # Previous biblio - $numberBiblioPaging = $paging{'previous'}->{biblionumber}; - if ($numberBiblioPaging) { - $template->param( 'previousBiblionumber' => $numberBiblioPaging ); - $dataBiblioPaging = Koha::Biblios->find( $numberBiblioPaging ); - $template->param('previousTitle' => $dataBiblioPaging->title) if $dataBiblioPaging; - } - # Next biblio - $numberBiblioPaging = $paging{'next'}->{biblionumber}; - if ($numberBiblioPaging) { - $template->param( 'nextBiblionumber' => $numberBiblioPaging ); - $dataBiblioPaging = Koha::Biblios->find( $numberBiblioPaging ); - $template->param('nextTitle' => $dataBiblioPaging->title) if $dataBiblioPaging; - } - # Partial list of biblio results - my @listResults; - for (my $j = 0; $j < @arrBiblios; $j++) { - next unless ($arrBiblios[$j]); - $dataBiblioPaging = Koha::Biblios->find( $arrBiblios[$j] ) if ($arrBiblios[$j] != $biblionumber); - next unless $dataBiblioPaging; - push @listResults, {index => $j + 1 + $offset, biblionumber => $arrBiblios[$j], title => ($arrBiblios[$j] == $biblionumber)?'':$dataBiblioPaging->title, author => ($arrBiblios[$j] != $biblionumber && $dataBiblioPaging->author)?$dataBiblioPaging->author:'', part_number => ($arrBiblios[$j] == $biblionumber)?'':$dataBiblioPaging->part_number, part_name => ($arrBiblios[$j] == $biblionumber)?'':$dataBiblioPaging->part_name, url => ($arrBiblios[$j] == $biblionumber)?'':'opac-detail.pl?biblionumber=' . $arrBiblios[$j]}; - } - $template->param('listResults' => \@listResults) if (@listResults); - $template->param('indexPag' => 1 + $offset, 'totalPag' => $arrParamsBusc{'total'}, 'indexPagEnd' => scalar(@arrBiblios) + $offset); - $template->param( 'offset' => $offset ); -} } $items = Koha::Items->search_ordered( [ 'me.biblionumber' => $biblionumber, - 'me.itemnumber' => { - -in => [ - $biblio->host_items->get_column('itemnumber') - ] - } + 'me.itemnumber' => { -in => [ $biblio->host_items->get_column('itemnumber') ] } ], { prefetch => [ 'issue', 'homebranch', 'holdingbranch' ] } -)->filter_by_visible_in_opac({ patron => $patron }) unless $specific_item; +)->filter_by_visible_in_opac( { patron => $patron } ) + unless $specific_item; -my $dat = &GetBiblioData($biblionumber); +my $dat = &GetBiblioData($biblionumber); my $HideMARC = $record_processor->filters->[0]->should_hide_marc( { frameworkcode => $dat->{'frameworkcode'}, interface => 'opac', - } ); + } +); my $itemtypes = { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search_with_localization->unblessed } }; + # imageurl: my $itemtype = $dat->{'itemtype'}; -if ( $itemtype ) { +if ($itemtype) { $dat->{'imageurl'} = getitemtypeimagelocation( 'opac', $itemtypes->{$itemtype}->{'imageurl'} ); $dat->{'description'} = $itemtypes->{$itemtype}->{translated_description}; } -my $shelflocations = - { map { $_->{authorised_value} => $_->{opac_description} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => $dat->{frameworkcode}, kohafield => 'items.location' } ) }; -my $collections = - { map { $_->{authorised_value} => $_->{opac_description} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => $dat->{frameworkcode}, kohafield => 'items.ccode' } ) }; -my $copynumbers = - { map { $_->{authorised_value} => $_->{opac_description} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => $dat->{frameworkcode}, kohafield => 'items.copynumber' } ) }; +my $shelflocations = { + map { $_->{authorised_value} => $_->{opac_description} } Koha::AuthorisedValues->get_descriptions_by_koha_field( + { frameworkcode => $dat->{frameworkcode}, kohafield => 'items.location' } + ) +}; +my $collections = { + map { $_->{authorised_value} => $_->{opac_description} } Koha::AuthorisedValues->get_descriptions_by_koha_field( + { frameworkcode => $dat->{frameworkcode}, kohafield => 'items.ccode' } + ) +}; +my $copynumbers = { + map { $_->{authorised_value} => $_->{opac_description} } Koha::AuthorisedValues->get_descriptions_by_koha_field( + { frameworkcode => $dat->{frameworkcode}, kohafield => 'items.copynumber' } + ) +}; #coping with subscriptions my $subscriptionsnumber = CountSubscriptionFromBiblionumber($biblionumber); -my @subscriptions = SearchSubscriptions({ biblionumber => $biblionumber, orderby => 'title' }); +my @subscriptions = SearchSubscriptions( { biblionumber => $biblionumber, orderby => 'title' } ); my @subs; -$dat->{'serial'}=1 if $subscriptionsnumber; +$dat->{'serial'} = 1 if $subscriptionsnumber; foreach my $subscription (@subscriptions) { my $serials_to_display; my %cell; @@ -545,15 +596,16 @@ foreach my $subscription (@subscriptions) { $cell{closed} = $subscription->{closed}; $cell{letter} = $subscription->{letter}; $cell{biblionumber} = $subscription->{biblionumber}; + #get the three latest serials. - $serials_to_display = $subscription->{opacdisplaycount}; - $serials_to_display = C4::Context->preference('OPACSerialIssueDisplayCount') unless $serials_to_display; - $cell{opacdisplaycount} = $serials_to_display; + $serials_to_display = $subscription->{opacdisplaycount}; + $serials_to_display = C4::Context->preference('OPACSerialIssueDisplayCount') unless $serials_to_display; + $cell{opacdisplaycount} = $serials_to_display; $cell{latestserials} = - GetLatestSerials( $subscription->{subscriptionid}, $serials_to_display ); - if ( $borrowernumber ) { + GetLatestSerials( $subscription->{subscriptionid}, $serials_to_display ); + if ($borrowernumber) { my $subscription_object = Koha::Subscriptions->find( $subscription->{subscriptionid} ); - my $subscriber = $subscription_object->subscribers->find( $borrowernumber ); + my $subscriber = $subscription_object->subscribers->find($borrowernumber); $cell{hasalert} = 1 if $subscriber; } push @subs, \%cell; @@ -561,73 +613,73 @@ foreach my $subscription (@subscriptions) { $dat->{'count'} = $items->count; -my (%item_reserves, %priority); -my ($show_holds_count, $show_priority); +my ( %item_reserves, %priority ); +my ( $show_holds_count, $show_priority ); for ( C4::Context->preference("OPACShowHoldQueueDetails") ) { - m/holds/o and $show_holds_count = 1; - m/priority/ and $show_priority = 1; + m/holds/o and $show_holds_count = 1; + m/priority/ and $show_priority = 1; } my $has_hold; -if ( $show_holds_count || $show_priority) { +if ( $show_holds_count || $show_priority ) { my $holds = $biblio->holds; - $template->param( holds_count => $holds->count ); + $template->param( holds_count => $holds->count ); while ( my $hold = $holds->next ) { $item_reserves{ $hold->itemnumber }++ if $hold->itemnumber; - if ($show_priority && $hold->borrowernumber == $borrowernumber) { + if ( $show_priority && $hold->borrowernumber == $borrowernumber ) { $has_hold = 1; $hold->itemnumber - ? ($priority{ $hold->itemnumber } = $hold->priority) - : ($template->param( priority => $hold->priority )); + ? ( $priority{ $hold->itemnumber } = $hold->priority ) + : ( $template->param( priority => $hold->priority ) ); } } } -$template->param( show_priority => $has_hold ) ; +$template->param( show_priority => $has_hold ); my %itemfields; -my (@itemloop, @otheritemloop); +my ( @itemloop, @otheritemloop ); my $currentbranch = C4::Context->userenv ? C4::Context->userenv->{branch} : undef; -if ($currentbranch and C4::Context->preference('OpacSeparateHoldings')) { - $template->param(SeparateHoldings => 1); +if ( $currentbranch and C4::Context->preference('OpacSeparateHoldings') ) { + $template->param( SeparateHoldings => 1 ); } -my $separatebranch = C4::Context->preference('OpacSeparateHoldingsBranch'); -my $viewallitems = $query->param('viewallitems'); +my $separatebranch = C4::Context->preference('OpacSeparateHoldingsBranch'); +my $viewallitems = $query->param('viewallitems'); my $max_items_to_display = C4::Context->preference('OpacMaxItemsToDisplay') // 50; # Get component parts details my $showcomp = C4::Context->preference('ShowComponentRecords'); my ( $parts, $show_analytics ); if ( $showcomp eq 'both' || $showcomp eq 'opac' ) { - if ( my $components = $biblio->get_marc_components(C4::Context->preference('MaxComponentRecords')) ) { - $show_analytics = 1 if @{$components}; # just show link when having results + if ( my $components = $biblio->get_marc_components( C4::Context->preference('MaxComponentRecords') ) ) { + $show_analytics = 1 if @{$components}; # just show link when having results for my $part ( @{$components} ) { $part = C4::Search::new_record_from_zebra( 'biblioserver', $part ); - my $id = Koha::SearchEngine::Search::extract_biblionumber( $part ); + my $id = Koha::SearchEngine::Search::extract_biblionumber($part); push @{$parts}, - XSLTParse4Display( + XSLTParse4Display( { biblionumber => $id, record => $part, xsl_syspref => 'OPACXSLTResultsDisplay', fix_amps => 1, } - ); + ); } $template->param( ComponentParts => $parts ); my ( $comp_query, $comp_query_str, $comp_sort ) = $biblio->get_components_query; my $cpq = $comp_query_str . "&sort_by=" . $comp_sort; $template->param( ComponentPartsQuery => $cpq ); } -} else { # check if we should show analytics anyway - $show_analytics = 1 if @{$biblio->get_marc_components(1)}; # count matters here, results does not +} else { # check if we should show analytics anyway + $show_analytics = 1 if @{ $biblio->get_marc_components(1) }; # count matters here, results does not } # Display volumes link my $show_volumes = @{ $biblio->get_marc_volumes(1) } ? 1 : 0; # XSLT processing of some stuff -my $variables = {}; -my $lang = C4::Languages::getlanguage(); +my $variables = {}; +my $lang = C4::Languages::getlanguage(); my @plugin_responses = Koha::Plugins->call( 'opac_detail_xslt_variables', { @@ -636,25 +688,27 @@ my @plugin_responses = Koha::Plugins->call( patron_id => $borrowernumber, }, ); -for my $plugin_variables ( @plugin_responses ) { +for my $plugin_variables (@plugin_responses) { $variables = { %$variables, %$plugin_variables }; } $variables->{anonymous_session} = $borrowernumber ? 0 : 1; $variables->{show_analytics_link} = $show_analytics; $variables->{show_volumes_link} = $show_volumes; $template->param( - XSLTBloc => XSLTParse4Display({ - biblionumber => $biblionumber, - record => $record->clone(), - xsl_syspref => 'OPACXSLTDetailsDisplay', - fix_amps => 1, - xslt_variables => $variables, - }), + XSLTBloc => XSLTParse4Display( + { + biblionumber => $biblionumber, + record => $record->clone(), + xsl_syspref => 'OPACXSLTDetailsDisplay', + fix_amps => 1, + xslt_variables => $variables, + } + ), ); # Get items on order -if ( C4::Context->preference('OPACAcquisitionDetails' ) ) { - my $orders = $biblio->orders->filter_by_active; +if ( C4::Context->preference('OPACAcquisitionDetails') ) { + my $orders = $biblio->orders->filter_by_active; my $total_quantity = 0; while ( my $order = $orders->next ) { $total_quantity += $order->quantity; @@ -679,23 +733,23 @@ if ( not $viewallitems and $items->count > $max_items_to_display ) { too_many_items => 1, items_count => $items->count, ); -} -else { +} else { my $library_info; while ( my $item = $items->next ) { my $item_info = $item->unblessed; $item_info->{holds_count} = $item_reserves{ $item->itemnumber }; if ( $item_info->{holds_count} && $item_info->{holds_count} > 0 ) { $item_level_holds = 1; } - $item_info->{priority} = $priority{ $item->itemnumber }; + $item_info->{priority} = $priority{ $item->itemnumber }; # Get opac_info from Additional contents for home and holding library my ( $opac_info_home, $opac_info_holding ); - $opac_info_holding = $library_info->{ $item->holdingbranch } // $item->holding_branch->opac_info({ lang => $lang }); + $opac_info_holding = $library_info->{ $item->holdingbranch } + // $item->holding_branch->opac_info( { lang => $lang } ); $library_info->{ $item->holdingbranch } = $opac_info_holding; - $opac_info_home = $library_info->{ $item->homebranch } // $item->home_branch->opac_info({ lang => $lang }); + $opac_info_home = $library_info->{ $item->homebranch } // $item->home_branch->opac_info( { lang => $lang } ); $library_info->{ $item->homebranch } = $opac_info_home; - $item_info->{holding_library_info} = $opac_info_holding->content if $opac_info_holding; - $item_info->{home_library_info} = $opac_info_home->content if $opac_info_home; + $item_info->{holding_library_info} = $opac_info_holding->content if $opac_info_holding; + $item_info->{home_library_info} = $opac_info_home->content if $opac_info_home; # We only need to check if we haven't determined holds can be placed # and if we don't have patron, we have already decided @@ -705,26 +759,27 @@ else { # get collection code description, too my $ccode = $item->ccode; $item_info->{'ccode'} = $collections->{$ccode} - if defined($ccode) - && $collections - && exists( $collections->{$ccode} ); + if defined($ccode) + && $collections + && exists( $collections->{$ccode} ); my $copynumber = $item->copynumber; $item_info->{copynumber} = $copynumbers->{$copynumber} - if ( defined($copynumbers) + if ( defined($copynumbers) && defined($copynumber) && exists( $copynumbers->{$copynumber} ) ); if ( defined $item->location ) { - $item_info->{'location_description'} = - $shelflocations->{ $item->location }; + $item_info->{'location_description'} = $shelflocations->{ $item->location }; } my $itemtype = $item->itemtype; - $item_info->{'imageurl'} = getitemtypeimagelocation( 'opac', - $itemtypes->{ $itemtype->itemtype }->{'imageurl'} ); + $item_info->{'imageurl'} = getitemtypeimagelocation( + 'opac', + $itemtypes->{ $itemtype->itemtype }->{'imageurl'} + ); $item_info->{'description'} = - $itemtypes->{ $itemtype->itemtype }->{translated_description}; + $itemtypes->{ $itemtype->itemtype }->{translated_description}; $item_info->{checkout} = $item->checkout; if ( $item_info->{checkout} && $item_info->{checkout} > 0 ) { $item_checkouts = 1; } @@ -736,20 +791,18 @@ else { } # FIXME The following must be Koha::Item->serial - my $serial_item = Koha::Serial::Items->find($item->itemnumber); - if ( $serial_item ) { - my $serial = Koha::Serials->find($serial_item->serialid); + my $serial_item = Koha::Serial::Items->find( $item->itemnumber ); + if ($serial_item) { + my $serial = Koha::Serials->find( $serial_item->serialid ); $item_info->{serial} = $serial if $serial; } $item_info->{object} = $item; - if ( C4::Context->preference("OPACLocalCoverImages") == 1 ) { $item_info->{cover_images} = $item->cover_images; } - if ( C4::Context->preference('UseCourseReserves') ) { $item_info->{course_reserves} = GetItemCourseReservesInfo( itemnumber => $item->itemnumber ); } @@ -764,13 +817,11 @@ else { if ( $itembranch and $itembranch eq $currentbranch ) { push @itemloop, $item_info; $itemloop_has_images++ if $item->cover_images->count; - } - else { + } else { push @otheritemloop, $item_info; $otheritemloop_has_images++ if $item->cover_images->count; } - } - else { + } else { push @itemloop, $item_info; $itemloop_has_images++ if $item->cover_images->count; } @@ -786,23 +837,22 @@ $template->param( ); # Display only one tab if one items list is empty -if (scalar(@itemloop) == 0 || scalar(@otheritemloop) == 0) { - $template->param(SeparateHoldings => 0); - if (scalar(@itemloop) == 0) { +if ( scalar(@itemloop) == 0 || scalar(@otheritemloop) == 0 ) { + $template->param( SeparateHoldings => 0 ); + if ( scalar(@itemloop) == 0 ) { @itemloop = @otheritemloop; } } -my $marcnotesarray = $biblio->get_marc_notes({ opac => 1, record => $record }); +my $marcnotesarray = $biblio->get_marc_notes( { opac => 1, record => $record } ); -if( C4::Context->preference('ArticleRequests') ) { - my $patron = $borrowernumber ? Koha::Patrons->find($borrowernumber) : undef; - my $itemtype = Koha::ItemTypes->find($biblio->itemtype); - my $artreqpossible = $patron - ? $biblio->can_article_request( $patron ) - : $itemtype - ? $itemtype->may_article_request - : q{}; +if ( C4::Context->preference('ArticleRequests') ) { + my $patron = $borrowernumber ? Koha::Patrons->find($borrowernumber) : undef; + my $itemtype = Koha::ItemTypes->find( $biblio->itemtype ); + my $artreqpossible = + $patron ? $biblio->can_article_request($patron) + : $itemtype ? $itemtype->may_article_request + : q{}; $template->param( artreqpossible => $artreqpossible ); } @@ -820,31 +870,31 @@ $template->param( OpacStarRatings => C4::Context->preference("OpacStarRatings"), ); -if (C4::Context->preference("AlternateHoldingsField") && $items->count == 0) { - my $fieldspec = C4::Context->preference("AlternateHoldingsField"); - my $subfields = substr $fieldspec, 3; - my $holdingsep = C4::Context->preference("AlternateHoldingsSeparator") || ' '; +if ( C4::Context->preference("AlternateHoldingsField") && $items->count == 0 ) { + my $fieldspec = C4::Context->preference("AlternateHoldingsField"); + my $subfields = substr $fieldspec, 3; + my $holdingsep = C4::Context->preference("AlternateHoldingsSeparator") || ' '; my @alternateholdingsinfo = (); - my @holdingsfields = $record->field(substr $fieldspec, 0, 3); + my @holdingsfields = $record->field( substr $fieldspec, 0, 3 ); for my $field (@holdingsfields) { - my %holding = ( holding => '' ); + my %holding = ( holding => '' ); my $havesubfield = 0; - for my $subfield ($field->subfields()) { - if ((index $subfields, $$subfield[0]) >= 0) { - $holding{'holding'} .= $holdingsep if (length $holding{'holding'} > 0); + for my $subfield ( $field->subfields() ) { + if ( ( index $subfields, $$subfield[0] ) >= 0 ) { + $holding{'holding'} .= $holdingsep if ( length $holding{'holding'} > 0 ); $holding{'holding'} .= $$subfield[1]; $havesubfield++; } } if ($havesubfield) { - push(@alternateholdingsinfo, \%holding); + push( @alternateholdingsinfo, \%holding ); } } $template->param( - ALTERNATEHOLDINGS => \@alternateholdingsinfo, - ); + ALTERNATEHOLDINGS => \@alternateholdingsinfo, + ); } # FIXME: The template uses this hash directly. Need to filter. @@ -856,19 +906,19 @@ foreach ( keys %{$dat} ) { # some useful variables for enhanced content; # in each case, we're grabbing the first value we find in # the record and normalizing it -my $upc = GetNormalizedUPC($record,$marcflavour); -my $oclc = GetNormalizedOCLCNumber($record,$marcflavour); -my $isbn = GetNormalizedISBN(undef,$record,$marcflavour); +my $upc = GetNormalizedUPC( $record, $marcflavour ); +my $oclc = GetNormalizedOCLCNumber( $record, $marcflavour ); +my $isbn = GetNormalizedISBN( undef, $record, $marcflavour ); my $content_identifier_exists; if ( $isbn or $ean or $oclc or $upc ) { $content_identifier_exists = 1; } $template->param( - normalized_upc => $upc, - normalized_ean => $ean, - normalized_oclc => $oclc, - normalized_isbn => $isbn, - content_identifier_exists => $content_identifier_exists, + normalized_upc => $upc, + normalized_ean => $ean, + normalized_oclc => $oclc, + normalized_isbn => $isbn, + content_identifier_exists => $content_identifier_exists, ); # Catch the exception as Koha::Biblio::Metadata->record can explode if the MARCXML is invalid @@ -881,11 +931,9 @@ if ( C4::Context->preference('OPACComments') ) { $reviews = Koha::Reviews->search( { biblionumber => $biblionumber, - -or => { approved => 1, borrowernumber => $borrowernumber } + -or => { approved => 1, borrowernumber => $borrowernumber } }, - { - order_by => { -desc => 'datereviewed' } - } + { order_by => { -desc => 'datereviewed' } } )->unblessed; my $libravatar_enabled = 0; if ( C4::Context->preference('ShowReviewer') and C4::Context->preference('ShowReviewerPhoto') ) { @@ -898,10 +946,11 @@ if ( C4::Context->preference('OPACComments') ) { } } for my $review (@$reviews) { - my $review_patron = Koha::Patrons->find( $review->{borrowernumber} ); # FIXME Should be Koha::Review->reviewer or similar + my $review_patron = + Koha::Patrons->find( $review->{borrowernumber} ); # FIXME Should be Koha::Review->reviewer or similar # setting some borrower info into this hash - if ( $review_patron ) { + if ($review_patron) { $review->{patron} = $review_patron; if ( $libravatar_enabled and $review_patron->email ) { $review->{avatarurl} = libravatar_url( email => $review_patron->email, https => $ENV{HTTPS} ); @@ -929,7 +978,7 @@ $template->param( ); # Lists -if (C4::Context->preference("virtualshelves") ) { +if ( C4::Context->preference("virtualshelves") ) { my $shelves = Koha::Virtualshelves->search( { biblionumber => $biblionumber, @@ -943,18 +992,15 @@ if (C4::Context->preference("virtualshelves") ) { } # XISBN Stuff -if (C4::Context->preference("OPACFRBRizeEditions")==1) { - eval { - $template->param( - XISBNS => scalar get_xisbns($isbn, $biblionumber) - ); - }; +if ( C4::Context->preference("OPACFRBRizeEditions") == 1 ) { + eval { $template->param( XISBNS => scalar get_xisbns( $isbn, $biblionumber ) ); }; if ($@) { warn "XISBN Failed $@"; } } # Serial Collection my @sc_fields = $record->field(955); -my @lc_fields = $marcflavour eq 'UNIMARC' +my @lc_fields = + $marcflavour eq 'UNIMARC' ? $record->field(930) : $record->field(852); my @serialcollections = (); @@ -962,207 +1008,221 @@ my @serialcollections = (); foreach my $sc_field (@sc_fields) { my %row_data; - $row_data{text} = $sc_field->subfield('r'); - $row_data{branch} = $sc_field->subfield('9'); + $row_data{text} = $sc_field->subfield('r'); + $row_data{branch} = $sc_field->subfield('9'); foreach my $lc_field (@lc_fields) { $row_data{itemcallnumber} = $marcflavour eq 'UNIMARC' - ? $lc_field->subfield('a') # 930$a - : $lc_field->subfield('h') # 852$h - if ($sc_field->subfield('5') eq $lc_field->subfield('5')); + ? $lc_field->subfield('a') # 930$a + : $lc_field->subfield('h') # 852$h + if ( $sc_field->subfield('5') eq $lc_field->subfield('5') ); } - if ($row_data{text} && $row_data{branch}) { - push (@serialcollections, \%row_data); + if ( $row_data{text} && $row_data{branch} ) { + push( @serialcollections, \%row_data ); } } -if (scalar(@serialcollections) > 0) { +if ( scalar(@serialcollections) > 0 ) { $template->param( - serialcollection => 1, - serialcollections => \@serialcollections); + serialcollection => 1, + serialcollections => \@serialcollections + ); } # Local cover Images stuff -if (C4::Context->preference("OPACLocalCoverImages")){ - $template->param(OPACLocalCoverImages => 1); +if ( C4::Context->preference("OPACLocalCoverImages") ) { + $template->param( OPACLocalCoverImages => 1 ); } # HTML5 Media -if ( (C4::Context->preference("HTML5MediaEnabled") eq 'both') or (C4::Context->preference("HTML5MediaEnabled") eq 'opac') ) { - $template->param( C4::HTML5Media->gethtml5media($record)); +if ( ( C4::Context->preference("HTML5MediaEnabled") eq 'both' ) + or ( C4::Context->preference("HTML5MediaEnabled") eq 'opac' ) ) +{ + $template->param( C4::HTML5Media->gethtml5media($record) ); } my $syndetics_elements; if ( C4::Context->preference("SyndeticsEnabled") ) { - $template->param("SyndeticsEnabled" => 1); - $template->param("SyndeticsClientCode" => C4::Context->preference("SyndeticsClientCode")); - eval { - $syndetics_elements = &get_syndetics_index($isbn,$upc,$oclc); - for my $element (values %$syndetics_elements) { - $template->param("Syndetics$element"."Exists" => 1 ); - #warn "Exists: "."Syndetics$element"."Exists"; - } + $template->param( "SyndeticsEnabled" => 1 ); + $template->param( "SyndeticsClientCode" => C4::Context->preference("SyndeticsClientCode") ); + eval { + $syndetics_elements = &get_syndetics_index( $isbn, $upc, $oclc ); + for my $element ( values %$syndetics_elements ) { + $template->param( "Syndetics$element" . "Exists" => 1 ); + + #warn "Exists: "."Syndetics$element"."Exists"; + } }; warn $@ if $@; } -if ( C4::Context->preference("SyndeticsEnabled") - && C4::Context->preference("SyndeticsSummary") - && ( exists($syndetics_elements->{'SUMMARY'}) || exists($syndetics_elements->{'AVSUMMARY'}) ) ) { - eval { - my $syndetics_summary = &get_syndetics_summary($isbn,$upc,$oclc, $syndetics_elements); - $template->param( SYNDETICS_SUMMARY => $syndetics_summary ); - }; - warn $@ if $@; +if ( C4::Context->preference("SyndeticsEnabled") + && C4::Context->preference("SyndeticsSummary") + && ( exists( $syndetics_elements->{'SUMMARY'} ) || exists( $syndetics_elements->{'AVSUMMARY'} ) ) ) +{ + eval { + my $syndetics_summary = &get_syndetics_summary( $isbn, $upc, $oclc, $syndetics_elements ); + $template->param( SYNDETICS_SUMMARY => $syndetics_summary ); + }; + warn $@ if $@; } -if ( C4::Context->preference("SyndeticsEnabled") - && C4::Context->preference("SyndeticsTOC") - && exists($syndetics_elements->{'TOC'}) ) { - eval { - my $syndetics_toc = &get_syndetics_toc($isbn,$upc,$oclc); - $template->param( SYNDETICS_TOC => $syndetics_toc ); - }; - warn $@ if $@; +if ( C4::Context->preference("SyndeticsEnabled") + && C4::Context->preference("SyndeticsTOC") + && exists( $syndetics_elements->{'TOC'} ) ) +{ + eval { + my $syndetics_toc = &get_syndetics_toc( $isbn, $upc, $oclc ); + $template->param( SYNDETICS_TOC => $syndetics_toc ); + }; + warn $@ if $@; } -if ( C4::Context->preference("SyndeticsEnabled") +if ( C4::Context->preference("SyndeticsEnabled") && C4::Context->preference("SyndeticsExcerpt") - && exists($syndetics_elements->{'DBCHAPTER'}) ) { + && exists( $syndetics_elements->{'DBCHAPTER'} ) ) +{ eval { - my $syndetics_excerpt = &get_syndetics_excerpt($isbn,$upc,$oclc); - $template->param( SYNDETICS_EXCERPT => $syndetics_excerpt ); + my $syndetics_excerpt = &get_syndetics_excerpt( $isbn, $upc, $oclc ); + $template->param( SYNDETICS_EXCERPT => $syndetics_excerpt ); }; - warn $@ if $@; + warn $@ if $@; } -if ( C4::Context->preference("SyndeticsEnabled") - && C4::Context->preference("SyndeticsReviews")) { +if ( C4::Context->preference("SyndeticsEnabled") + && C4::Context->preference("SyndeticsReviews") ) +{ eval { - my $syndetics_reviews = &get_syndetics_reviews($isbn,$upc,$oclc,$syndetics_elements); - $template->param( SYNDETICS_REVIEWS => $syndetics_reviews ); + my $syndetics_reviews = &get_syndetics_reviews( $isbn, $upc, $oclc, $syndetics_elements ); + $template->param( SYNDETICS_REVIEWS => $syndetics_reviews ); }; - warn $@ if $@; + warn $@ if $@; } -if ( C4::Context->preference("SyndeticsEnabled") +if ( C4::Context->preference("SyndeticsEnabled") && C4::Context->preference("SyndeticsAuthorNotes") - && exists($syndetics_elements->{'ANOTES'}) ) { + && exists( $syndetics_elements->{'ANOTES'} ) ) +{ eval { - my $syndetics_anotes = &get_syndetics_anotes($isbn,$upc,$oclc); - $template->param( SYNDETICS_ANOTES => $syndetics_anotes ); + my $syndetics_anotes = &get_syndetics_anotes( $isbn, $upc, $oclc ); + $template->param( SYNDETICS_ANOTES => $syndetics_anotes ); }; warn $@ if $@; } # LibraryThingForLibraries ID Code and Tabbed View Option -if( C4::Context->preference('LibraryThingForLibrariesEnabled') ) -{ -$template->param(LibraryThingForLibrariesID => -C4::Context->preference('LibraryThingForLibrariesID') ); -$template->param(LibraryThingForLibrariesTabbedView => -C4::Context->preference('LibraryThingForLibrariesTabbedView') ); -} +if ( C4::Context->preference('LibraryThingForLibrariesEnabled') ) { + $template->param( LibraryThingForLibrariesID => C4::Context->preference('LibraryThingForLibrariesID') ); + $template->param( + LibraryThingForLibrariesTabbedView => C4::Context->preference('LibraryThingForLibrariesTabbedView') ); +} # Novelist Select -if( C4::Context->preference('NovelistSelectEnabled') ) -{ -$template->param(NovelistSelectProfile => C4::Context->preference('NovelistSelectProfile') ); -$template->param(NovelistSelectPassword => C4::Context->preference('NovelistSelectPassword') ); -$template->param(NovelistSelectView => C4::Context->preference('NovelistSelectView') ); -} - +if ( C4::Context->preference('NovelistSelectEnabled') ) { + $template->param( NovelistSelectProfile => C4::Context->preference('NovelistSelectProfile') ); + $template->param( NovelistSelectPassword => C4::Context->preference('NovelistSelectPassword') ); + $template->param( NovelistSelectView => C4::Context->preference('NovelistSelectView') ); +} # Babelthèque if ( C4::Context->preference("Babeltheque") ) { - $template->param( - Babeltheque => 1, + $template->param( + Babeltheque => 1, Babeltheque_url_js => C4::Context->preference("Babeltheque_url_js"), ); } # Social Networks -if ( C4::Context->preference( "SocialNetworks" ) ) { - $template->param( current_url => C4::Context->preference('OPACBaseURL') . "/cgi-bin/koha/opac-detail.pl?biblionumber=$biblionumber" ); +if ( C4::Context->preference("SocialNetworks") ) { + $template->param( current_url => C4::Context->preference('OPACBaseURL') + . "/cgi-bin/koha/opac-detail.pl?biblionumber=$biblionumber" ); $template->param( SocialNetworks => 1 ); } # Shelf Browser Stuff -if (C4::Context->preference("OPACShelfBrowser")) { +if ( C4::Context->preference("OPACShelfBrowser") ) { my $starting_itemnumber = $query->param('shelfbrowse_itemnumber'); - if (defined($starting_itemnumber)) { - $template->param( OpenOPACShelfBrowser => 1) if $starting_itemnumber; + if ( defined($starting_itemnumber) ) { + $template->param( OpenOPACShelfBrowser => 1 ) if $starting_itemnumber; my $nearby = GetNearbyItems($starting_itemnumber); $template->param( - starting_itemnumber => $starting_itemnumber, - starting_homebranch => $nearby->{starting_homebranch}->{description}, - starting_location => $nearby->{starting_location}->{description}, - starting_ccode => $nearby->{starting_ccode}->{description}, + starting_itemnumber => $starting_itemnumber, + starting_homebranch => $nearby->{starting_homebranch}->{description}, + starting_location => $nearby->{starting_location}->{description}, + starting_ccode => $nearby->{starting_ccode}->{description}, shelfbrowser_prev_item => $nearby->{prev_item}, shelfbrowser_next_item => $nearby->{next_item}, - shelfbrowser_items => $nearby->{items}, + shelfbrowser_items => $nearby->{items}, ); # in which tab shelf browser should open ? - if (grep { $starting_itemnumber == $_->{itemnumber} } @itemloop) { - $template->param(shelfbrowser_tab => 'holdings'); + if ( grep { $starting_itemnumber == $_->{itemnumber} } @itemloop ) { + $template->param( shelfbrowser_tab => 'holdings' ); } else { - $template->param(shelfbrowser_tab => 'otherholdings'); + $template->param( shelfbrowser_tab => 'otherholdings' ); } } } -$template->param( AmazonTld => get_amazon_tld() ) if ( C4::Context->preference("OPACAmazonCoverImages")); +$template->param( AmazonTld => get_amazon_tld() ) if ( C4::Context->preference("OPACAmazonCoverImages") ); -if (C4::Context->preference("BakerTaylorEnabled")) { - $template->param( - BakerTaylorEnabled => 1, - BakerTaylorImageURL => &image_url(), - BakerTaylorLinkURL => &link_url(), - BakerTaylorBookstoreURL => C4::Context->preference('BakerTaylorBookstoreURL'), - ); - my ($bt_user, $bt_pass); - if ($isbn and - $bt_user = C4::Context->preference('BakerTaylorUsername') and - $bt_pass = C4::Context->preference('BakerTaylorPassword') ) - { - $template->param( - BakerTaylorContentURL => - sprintf("https://contentcafe2.btol.com/ContentCafeClient/ContentCafe.aspx?UserID=%s&Password=%s&ItemKey=%s&Options=Y", - $bt_user,$bt_pass,$isbn) - ); - } +if ( C4::Context->preference("BakerTaylorEnabled") ) { + $template->param( + BakerTaylorEnabled => 1, + BakerTaylorImageURL => &image_url(), + BakerTaylorLinkURL => &link_url(), + BakerTaylorBookstoreURL => C4::Context->preference('BakerTaylorBookstoreURL'), + ); + my ( $bt_user, $bt_pass ); + if ( $isbn + and $bt_user = C4::Context->preference('BakerTaylorUsername') + and $bt_pass = C4::Context->preference('BakerTaylorPassword') ) + { + $template->param( + BakerTaylorContentURL => sprintf( + "https://contentcafe2.btol.com/ContentCafeClient/ContentCafe.aspx?UserID=%s&Password=%s&ItemKey=%s&Options=Y", + $bt_user, $bt_pass, $isbn + ) + ); + } } my $tag_quantity; -if (C4::Context->preference('TagsEnabled') and $tag_quantity = C4::Context->preference('TagsShowOnDetail')) { - $template->param( - TagsEnabled => 1, - TagsShowOnDetail => $tag_quantity, - TagsInputOnDetail => C4::Context->preference('TagsInputOnDetail') - ); - $template->param(TagLoop => get_tags({biblionumber=>$biblionumber, approved=>1, - 'sort'=>'-weight', limit=>$tag_quantity})); +if ( C4::Context->preference('TagsEnabled') and $tag_quantity = C4::Context->preference('TagsShowOnDetail') ) { + $template->param( + TagsEnabled => 1, + TagsShowOnDetail => $tag_quantity, + TagsInputOnDetail => C4::Context->preference('TagsInputOnDetail') + ); + $template->param( + TagLoop => get_tags( + { + biblionumber => $biblionumber, approved => 1, + 'sort' => '-weight', limit => $tag_quantity + } + ) + ); } -if (C4::Context->preference("OPACURLOpenInNewWindow")) { +if ( C4::Context->preference("OPACURLOpenInNewWindow") ) { + # These values are going to be read by Javascript, at least in the case # of the google covers - $template->param(covernewwindow => 'true'); + $template->param( covernewwindow => 'true' ); } else { - $template->param(covernewwindow => 'false'); + $template->param( covernewwindow => 'false' ); } -$template->param(borrowernumber => $borrowernumber); +$template->param( borrowernumber => $borrowernumber ); if ( C4::Context->preference('OpacStarRatings') !~ /disable/ ) { - my $ratings = Koha::Ratings->search({ biblionumber => $biblionumber }); - my $my_rating = $borrowernumber ? $ratings->search({ borrowernumber => $borrowernumber })->next : undef; + my $ratings = Koha::Ratings->search( { biblionumber => $biblionumber } ); + my $my_rating = $borrowernumber ? $ratings->search( { borrowernumber => $borrowernumber } )->next : undef; $template->param( - ratings => $ratings, + ratings => $ratings, my_rating => $my_rating, ); } @@ -1172,10 +1232,10 @@ my $control_number = $metadata_extractor->get_control_number(); my $marcissns = GetMarcISSN( $record, $marcflavour ); my $issn = $marcissns->[0] || ''; -if (my $search_for_title = C4::Context->preference('OPACSearchForTitleIn')){ - $dat->{title} =~ s/\/+$//; # remove trailing slash - $dat->{title} =~ s/\s+$//; # remove trailing space - my $oclc_no = Koha::Util::MARC::oclc_number( $record ); +if ( my $search_for_title = C4::Context->preference('OPACSearchForTitleIn') ) { + $dat->{title} =~ s/\/+$//; # remove trailing slash + $dat->{title} =~ s/\s+$//; # remove trailing space + my $oclc_no = Koha::Util::MARC::oclc_number($record); $search_for_title = parametrized_url( $search_for_title, { @@ -1188,11 +1248,12 @@ if (my $search_for_title = C4::Context->preference('OPACSearchForTitleIn')){ OCLC_NO => $oclc_no, } ); - $template->param('OPACSearchForTitleIn' => $search_for_title); + $template->param( 'OPACSearchForTitleIn' => $search_for_title ); } #IDREF if ( C4::Context->preference("IDREF") ) { + # If the record comes from the SUDOC if ( $record->field('009') ) { my $unimarc3 = $record->field("009")->data; @@ -1207,34 +1268,26 @@ if ( C4::Context->preference("IDREF") ) { # We try to select the best default tab to show, according to what # the user wants, and what's available for display my $opac_serial_default = C4::Context->preference('opacSerialDefaultTab'); -my $defaulttab = - $viewallitems - ? 'holdings' : - $opac_serial_default eq 'subscriptions' && $subscriptionsnumber - ? 'subscriptions' : - $opac_serial_default eq 'titlenotes' && $subscriptionsnumber - ? 'descriptions' : - $opac_serial_default eq 'serialcollection' && @serialcollections > 0 - ? 'serialcollection' : - $opac_serial_default eq 'holdings' && scalar (@itemloop) > 0 - ? 'holdings' : - ( $showcomp eq 'both' || $showcomp eq 'opac' ) && scalar (@itemloop) == 0 && $parts - ? 'components' : - scalar (@itemloop) == 0 - ? 'media' : - $subscriptionsnumber - ? 'subscriptions' : - @serialcollections > 0 - ? 'serialcollection' : 'subscriptions'; -$template->param('defaulttab' => $defaulttab); +my $defaulttab = + $viewallitems ? 'holdings' + : $opac_serial_default eq 'subscriptions' && $subscriptionsnumber ? 'subscriptions' + : $opac_serial_default eq 'titlenotes' && $subscriptionsnumber ? 'descriptions' + : $opac_serial_default eq 'serialcollection' && @serialcollections > 0 ? 'serialcollection' + : $opac_serial_default eq 'holdings' && scalar(@itemloop) > 0 ? 'holdings' + : ( $showcomp eq 'both' || $showcomp eq 'opac' ) && scalar(@itemloop) == 0 && $parts ? 'components' + : scalar(@itemloop) == 0 ? 'media' + : $subscriptionsnumber ? 'subscriptions' + : @serialcollections > 0 ? 'serialcollection' + : 'subscriptions'; +$template->param( 'defaulttab' => $defaulttab ); -if (C4::Context->preference('OPACLocalCoverImages') == 1) { +if ( C4::Context->preference('OPACLocalCoverImages') == 1 ) { $template->param( localimages => $biblio->cover_images ); } $template->{VARS}->{OPACPopupAuthorsSearch} = C4::Context->preference('OPACPopupAuthorsSearch'); -if (C4::Context->preference('OpacHighlightedWords')) { +if ( C4::Context->preference('OpacHighlightedWords') ) { $template->{VARS}->{query_desc} = $query->param('query_desc'); } $template->{VARS}->{'trackclicks'} = C4::Context->preference('TrackClicks'); @@ -1252,11 +1305,10 @@ if ( C4::Context->preference('OPACAuthorIdentifiersAndInformation') ) { my $information = $authority->get_identifiers_and_information; next unless $information; my ($name) = - map { $_->{value} } - grep { $_->{code} eq 'a' ? $_ : () } - @{ $author->{MARCAUTHOR_SUBFIELDS_LOOP} }; + map { $_->{value} } + grep { $_->{code} eq 'a' ? $_ : () } @{ $author->{MARCAUTHOR_SUBFIELDS_LOOP} }; push @author_information, - { authid => $authid, name => $name, information => $information}; + { authid => $authid, name => $name, information => $information }; } $template->param( author_information => \@author_information ); } diff --git a/opac/opac-discharge.pl b/opac/opac-discharge.pl index d232ea5722..04325fa930 100755 --- a/opac/opac-discharge.pl +++ b/opac/opac-discharge.pl @@ -21,7 +21,7 @@ use Modern::Perl; use Carp qw( carp ); use C4::Auth qw( get_template_and_user ); -use CGI qw( -utf8 ); +use CGI qw( -utf8 ); use C4::Context; use C4::Output qw( output_html_with_http_headers ); use Koha::Patrons; @@ -37,41 +37,47 @@ unless ( C4::Context->preference('useDischarge') ) { my $op = $input->param("op") // ''; # Getting the template and auth -my ( $template, $loggedinuser, $cookie ) = get_template_and_user({ - template_name => "opac-discharge.tt", - query => $input, - type => "opac", -}); +my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "opac-discharge.tt", + query => $input, + type => "opac", + } +); -my $can_be_discharged = Koha::Patron::Discharge::can_be_discharged({ borrowernumber => $loggedinuser }); -if ($can_be_discharged == 0) { +my $can_be_discharged = Koha::Patron::Discharge::can_be_discharged( { borrowernumber => $loggedinuser } ); +if ( $can_be_discharged == 0 ) { $template->param( has_checkouts => 1 ); } -my $pending = Koha::Patron::Discharge::count({ - borrowernumber => $loggedinuser, - pending => 1, -}); -my $available = Koha::Patron::Discharge::is_discharged({borrowernumber => $loggedinuser}); +my $pending = Koha::Patron::Discharge::count( + { + borrowernumber => $loggedinuser, + pending => 1, + } +); +my $available = Koha::Patron::Discharge::is_discharged( { borrowernumber => $loggedinuser } ); if ( $op eq 'cud-request' ) { - if ($pending || $available) { + if ( $pending || $available ) { + # Request already done print $input->redirect("/cgi-bin/koha/opac-discharge.pl"); exit; } - my $success = Koha::Patron::Discharge::request({ - borrowernumber => $loggedinuser, - }); + my $success = Koha::Patron::Discharge::request( + { + borrowernumber => $loggedinuser, + } + ); if ($success) { $template->param( success => 1 ); - } - else { + } else { $template->param( has_issues => 1 ); } -} -elsif ( $op eq 'get' ) { +} elsif ( $op eq 'get' ) { unless ($available) { + # No valid discharge to get print $input->redirect("/cgi-bin/koha/opac-discharge.pl"); exit; @@ -79,11 +85,13 @@ elsif ( $op eq 'get' ) { eval { # Getting member data - my $patron = Koha::Patrons->find( $loggedinuser ); - my $pdf_path = Koha::Patron::Discharge::generate_as_pdf({ - borrowernumber => $loggedinuser, - branchcode => $patron->branchcode, - }); + my $patron = Koha::Patrons->find($loggedinuser); + my $pdf_path = Koha::Patron::Discharge::generate_as_pdf( + { + borrowernumber => $loggedinuser, + branchcode => $patron->branchcode, + } + ); binmode(STDOUT); print $input->header( @@ -96,15 +104,15 @@ elsif ( $op eq 'get' ) { close $fh; print @lines; }; - if ( $@ ) { + if ($@) { carp $@; - $template->param( messages => [ {type => 'error', code => 'unable_to_generate_pdf'} ] ); + $template->param( messages => [ { type => 'error', code => 'unable_to_generate_pdf' } ] ); } else { + # no error, pdf is sent, so stop sending data to browser exit; } -} -else { +} else { $template->param( available => $available, pending => $pending, diff --git a/opac/opac-dismiss-message.pl b/opac/opac-dismiss-message.pl index 9ee8f61eb7..928ee9037a 100755 --- a/opac/opac-dismiss-message.pl +++ b/opac/opac-dismiss-message.pl @@ -20,8 +20,8 @@ use Modern::Perl; use CGI qw ( -utf8 ); use C4::Context; -use C4::Output qw( output_html_with_http_headers ); -use C4::Auth qw( get_template_and_user ); +use C4::Output qw( output_html_with_http_headers ); +use C4::Auth qw( get_template_and_user ); use Koha::DateUtils qw( dt_from_string ); use Koha::Patrons; @@ -30,9 +30,9 @@ my $op = $query->param('op') // q{}; my ( $template, $borrowernumber, $cookie ) = get_template_and_user( { - template_name => "opac-user.tt", - query => $query, - type => "opac", + template_name => "opac-user.tt", + query => $query, + type => "opac", } ); @@ -46,12 +46,13 @@ unless ($message) { } unless ( $op =~ /^cud-/ && $message ) { + # exit early print $query->redirect("/cgi-bin/koha/opac-user.pl"); exit; } -$message->update({ patron_read_date => dt_from_string }); +$message->update( { patron_read_date => dt_from_string } ); print $query->redirect("/cgi-bin/koha/opac-user.pl"); diff --git a/opac/opac-downloadcart.pl b/opac/opac-downloadcart.pl index 764d91d3f4..4d4f4b71ec 100755 --- a/opac/opac-downloadcart.pl +++ b/opac/opac-downloadcart.pl @@ -19,10 +19,10 @@ use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use Encode qw( encode ); -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Biblio qw( GetFrameworkCode GetISBDView ); use C4::Output qw( output_html_with_http_headers ); use C4::Record; @@ -34,7 +34,7 @@ use Koha::RecordProcessor; use utf8; my $query = CGI->new(); -my ( $template, $borrowernumber, $cookie ) = get_template_and_user ( +my ( $template, $borrowernumber, $cookie ) = get_template_and_user( { template_name => "opac-downloadcart.tt", query => $query, @@ -44,10 +44,10 @@ my ( $template, $borrowernumber, $cookie ) = get_template_and_user ( ); my $bib_list = $query->param('bib_list'); -my $format = $query->param('format'); -my $dbh = C4::Context->dbh; +my $format = $query->param('format'); +my $dbh = C4::Context->dbh; -if ($bib_list && $format) { +if ( $bib_list && $format ) { my $patron = Koha::Patrons->find($borrowernumber); @@ -58,8 +58,8 @@ if ($bib_list && $format) { my $extension; my $type; - # CSV - if ($format =~ /^\d+$/) { + # CSV + if ( $format =~ /^\d+$/ ) { my $csv_profile = Koha::CsvProfiles->find($format); if ( not $csv_profile or $csv_profile->staff_only ) { @@ -67,13 +67,11 @@ if ($bib_list && $format) { exit; } - $output = marc2csv(\@bibs, $format); + $output = marc2csv( \@bibs, $format ); # Other formats } else { - my $record_processor = Koha::RecordProcessor->new({ - filters => 'ViewPolicy' - }); + my $record_processor = Koha::RecordProcessor->new( { filters => 'ViewPolicy' } ); foreach my $biblionumber (@bibs) { my $biblio = Koha::Biblios->find($biblionumber); @@ -84,33 +82,35 @@ if ($bib_list && $format) { patron => $patron, } ); - my $framework = &GetFrameworkCode( $biblio ); - $record_processor->options({ - interface => 'opac', - frameworkcode => $framework - }); + my $framework = &GetFrameworkCode($biblio); + $record_processor->options( + { + interface => 'opac', + frameworkcode => $framework + } + ); $record_processor->process($record); next unless $record; - if ($format eq 'iso2709') { + if ( $format eq 'iso2709' ) { + #NOTE: If we don't explicitly UTF-8 encode the output, #the browser will guess the encoding, and it won't always choose UTF-8. - $output .= encode("UTF-8", $record->as_usmarc()) // q{}; - } - elsif ($format eq 'ris') { + $output .= encode( "UTF-8", $record->as_usmarc() ) // q{}; + } elsif ( $format eq 'ris' ) { $output .= marc2ris($record); - } - elsif ($format eq 'bibtex') { - $output .= marc2bibtex($record, $biblio->biblionumber); - } - elsif ( $format eq 'isbd' ) { - my $framework = GetFrameworkCode( $biblio ); - $output .= GetISBDView({ - 'record' => $record, - 'template' => 'opac', - 'framework' => $framework, - }); + } elsif ( $format eq 'bibtex' ) { + $output .= marc2bibtex( $record, $biblio->biblionumber ); + } elsif ( $format eq 'isbd' ) { + my $framework = GetFrameworkCode($biblio); + $output .= GetISBDView( + { + 'record' => $record, + 'template' => 'opac', + 'framework' => $framework, + } + ); $extension = "txt"; $type = "text/plain"; } @@ -118,16 +118,16 @@ if ($bib_list && $format) { } # If it was a CSV export we change the format after the export so the file extension is fine - $format = "csv" if ($format =~ m/^\d+$/); + $format = "csv" if ( $format =~ m/^\d+$/ ); print $query->header( - -type => ($type) ? $type : 'application/octet-stream', + -type => ($type) ? $type : 'application/octet-stream', -'Content-Transfer-Encoding' => 'binary', - -attachment => ($extension) ? "cart.$format.$extension" : "cart.$format" + -attachment => ($extension) ? "cart.$format.$extension" : "cart.$format" ); print $output; -} else { +} else { $template->param( csv_profiles => Koha::CsvProfiles->search( { diff --git a/opac/opac-downloadshelf.pl b/opac/opac-downloadshelf.pl index 0d6f9e88a0..41f2cac3a5 100755 --- a/opac/opac-downloadshelf.pl +++ b/opac/opac-downloadshelf.pl @@ -21,7 +21,7 @@ use Modern::Perl; use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Biblio qw( GetFrameworkCode GetISBDView ); use C4::Output qw( output_html_with_http_headers ); use C4::Record; @@ -35,12 +35,12 @@ use utf8; my $query = CGI->new; # if virtualshelves is disabled, leave immediately -if ( ! C4::Context->preference('virtualshelves') ) { +if ( !C4::Context->preference('virtualshelves') ) { print $query->redirect("/cgi-bin/koha/errors/404.pl"); exit; } -my ( $template, $borrowernumber, $cookie ) = get_template_and_user ( +my ( $template, $borrowernumber, $cookie ) = get_template_and_user( { template_name => "opac-downloadshelf.tt", query => $query, @@ -49,26 +49,25 @@ my ( $template, $borrowernumber, $cookie ) = get_template_and_user ( } ); -my $patron = Koha::Patrons->find( $borrowernumber ); +my $patron = Koha::Patrons->find($borrowernumber); my $shelfnumber = $query->param('shelfnumber'); -my $format = $query->param('format'); -my $context = $query->param('context'); +my $format = $query->param('format'); +my $context = $query->param('context'); -my $shelf = Koha::Virtualshelves->find( $shelfnumber ); -if ( $shelf and $shelf->can_be_viewed( $borrowernumber ) ) { +my $shelf = Koha::Virtualshelves->find($shelfnumber); +if ( $shelf and $shelf->can_be_viewed($borrowernumber) ) { - if ($shelfnumber && $format) { + if ( $shelfnumber && $format ) { - - my $contents = $shelf->get_contents; + my $contents = $shelf->get_contents; my $marcflavour = C4::Context->preference('marcflavour'); my $output; my $extension; my $type; - # CSV - if ($format =~ /^\d+$/) { + # CSV + if ( $format =~ /^\d+$/ ) { my $csv_profile = Koha::CsvProfiles->find($format); if ( not $csv_profile or $csv_profile->staff_only ) { @@ -80,12 +79,11 @@ if ( $shelf and $shelf->can_be_viewed( $borrowernumber ) ) { while ( my $content = $contents->next ) { push @biblios, $content->biblionumber; } - $output = marc2csv(\@biblios, $format); - # Other formats + $output = marc2csv( \@biblios, $format ); + + # Other formats } else { - my $record_processor = Koha::RecordProcessor->new({ - filters => 'ViewPolicy' - }); + my $record_processor = Koha::RecordProcessor->new( { filters => 'ViewPolicy' } ); while ( my $content = $contents->next ) { my $biblionumber = $content->biblionumber; @@ -98,28 +96,29 @@ if ( $shelf and $shelf->can_be_viewed( $borrowernumber ) ) { } ); my $framework = $biblio->frameworkcode; - $record_processor->options({ - interface => 'opac', - frameworkcode => $framework - }); + $record_processor->options( + { + interface => 'opac', + frameworkcode => $framework + } + ); $record_processor->process($record); next unless $record; - if ($format eq 'iso2709') { + if ( $format eq 'iso2709' ) { $output .= $record->as_usmarc(); - } - elsif ($format eq 'ris' ) { + } elsif ( $format eq 'ris' ) { $output .= marc2ris($record); - } - elsif ($format eq 'bibtex') { - $output .= marc2bibtex($record, $biblionumber); - } - elsif ( $format eq 'isbd' ) { - $output .= GetISBDView({ - 'record' => $record, - 'template' => 'opac', - 'framework' => $framework, - }); + } elsif ( $format eq 'bibtex' ) { + $output .= marc2bibtex( $record, $biblionumber ); + } elsif ( $format eq 'isbd' ) { + $output .= GetISBDView( + { + 'record' => $record, + 'template' => 'opac', + 'framework' => $framework, + } + ); $extension = "txt"; $type = "text/plain"; } @@ -127,22 +126,22 @@ if ( $shelf and $shelf->can_be_viewed( $borrowernumber ) ) { } # If it was a CSV export we change the format after the export so the file extension is fine - $format = "csv" if ($format =~ m/^\d+$/); + $format = "csv" if ( $format =~ m/^\d+$/ ); print $query->header( - -type => ($type) ? $type : 'application/octet-stream', + -type => ($type) ? $type : 'application/octet-stream', -'Content-Transfer-Encoding' => 'binary', - -attachment => ($extension) ? "shelf.$format.$extension" : "shelf.$format" + -attachment => ($extension) ? "shelf.$format.$extension" : "shelf.$format" ); print $output; } else { # if modal context is passed set a variable so that page markup can be different - if($context eq "modal"){ - $template->param(modal => 1); + if ( $context eq "modal" ) { + $template->param( modal => 1 ); } else { - $template->param(fullpage => 1); + $template->param( fullpage => 1 ); } $template->param( csv_profiles => Koha::CsvProfiles->search( @@ -158,6 +157,6 @@ if ( $shelf and $shelf->can_be_viewed( $borrowernumber ) ) { } } else { - $template->param(invalidlist => 1); + $template->param( invalidlist => 1 ); output_html_with_http_headers $query, $cookie, $template->output; } diff --git a/opac/opac-export.pl b/opac/opac-export.pl index 7eb2f3ae85..3cb829b453 100755 --- a/opac/opac-export.pl +++ b/opac/opac-export.pl @@ -34,10 +34,10 @@ use Koha::RecordProcessor; use List::MoreUtils qw(none any); -my $query = CGI->new; -my $op=$query->param("op")||''; #op=export is currently the only use -my $format=$query->param("format")||'utf8'; -my $biblionumber = $query->param("bib")||0; +my $query = CGI->new; +my $op = $query->param("op") || ''; #op=export is currently the only use +my $format = $query->param("format") || 'utf8'; +my $biblionumber = $query->param("bib") || 0; $biblionumber = int($biblionumber); my $error = q{}; @@ -45,11 +45,13 @@ my @dc_subtypes = qw(rdfdc oaidc srwdc); my @valid_formats = split( ',', C4::Context->preference('OpacExportOptions') // '' ); if ( any { $_ eq 'dc' } @valid_formats ) { + # DC enabled, add @dc_subtypes to @valid_formats @valid_formats = ( @valid_formats, @dc_subtypes ); } if ( !scalar @valid_formats || none { $format eq $_ } @valid_formats ) { + # bad request: either the feature is disabled, or requested a format the # library hasn't made available print $query->redirect("/cgi-bin/koha/errors/400.pl"); @@ -63,30 +65,30 @@ my $patron; if ($userenv) { my $borrowernumber = $userenv->{'number'}; if ($borrowernumber) { - $patron = Koha::Patrons->find( $borrowernumber ); + $patron = Koha::Patrons->find($borrowernumber); } } -my $include_items = ($format =~ /bibtex/) ? 0 : 1; -my $biblio = Koha::Biblios->find($biblionumber); -my $marc = $biblio - ? $biblio->metadata_record( +my $include_items = ( $format =~ /bibtex/ ) ? 0 : 1; +my $biblio = Koha::Biblios->find($biblionumber); +my $marc = $biblio + ? $biblio->metadata_record( { embed_items => 1, interface => 'opac', patron => $patron, } - ) - : undef; + ) + : undef; -if(!$marc) { +if ( !$marc ) { print $query->redirect("/cgi-bin/koha/errors/404.pl"); exit; } my $metadata_extractor = $biblio->metadata_extractor; -my $file_id = $biblionumber; +my $file_id = $biblionumber; my $file_pre = "bib-"; if ( C4::Context->preference('DefaultSaveRecordFileID') eq 'controlnumber' ) { my $control_number = $metadata_extractor->get_control_number(); @@ -96,100 +98,93 @@ if ( C4::Context->preference('DefaultSaveRecordFileID') eq 'controlnumber' ) { } } -my $framework = $biblio->frameworkcode; -my $record_processor = Koha::RecordProcessor->new({ - filters => 'ViewPolicy', - options => { - interface => 'opac', - frameworkcode => $framework +my $framework = $biblio->frameworkcode; +my $record_processor = Koha::RecordProcessor->new( + { + filters => 'ViewPolicy', + options => { + interface => 'opac', + frameworkcode => $framework + } } -}); +); $record_processor->process($marc); -if ($format =~ /endnote/) { - $marc = marc2endnote($marc); +if ( $format =~ /endnote/ ) { + $marc = marc2endnote($marc); $format = 'endnote'; -} -elsif ($format =~ /marcxml/) { - $marc = marc2marcxml($marc); +} elsif ( $format =~ /marcxml/ ) { + $marc = marc2marcxml($marc); $format = 'marcxml'; -} -elsif ($format=~ /mods/) { - $marc = marc2modsxml($marc); +} elsif ( $format =~ /mods/ ) { + $marc = marc2modsxml($marc); $format = 'mods'; -} -elsif ($format =~ /ris/) { - $marc = marc2ris($marc); +} elsif ( $format =~ /ris/ ) { + $marc = marc2ris($marc); $format = 'ris'; -} -elsif ($format =~ /bibtex/) { - $marc = marc2bibtex($marc,$biblionumber); +} elsif ( $format =~ /bibtex/ ) { + $marc = marc2bibtex( $marc, $biblionumber ); $format = 'bibtex'; -} -elsif ($format =~ /^(dc|oaidc|srwdc|rdfdc)$/i ) { +} elsif ( $format =~ /^(dc|oaidc|srwdc|rdfdc)$/i ) { + # TODO: Dublin Core leaks fields marked hidden by framework. - $marc = marc2dcxml($marc, undef, $biblionumber, $format); + $marc = marc2dcxml( $marc, undef, $biblionumber, $format ); $format = "dublin-core.xml"; -} -elsif ($format =~ /marc8/) { - ($error,$marc) = changeEncoding($marc,"MARC","MARC21","MARC-8"); - $marc = $marc->as_usmarc() unless $error; +} elsif ( $format =~ /marc8/ ) { + ( $error, $marc ) = changeEncoding( $marc, "MARC", "MARC21", "MARC-8" ); + $marc = $marc->as_usmarc() unless $error; $format = 'marc8'; -} -elsif ($format =~ /utf8/) { - C4::Charset::SetUTF8Flag($marc,1); - $marc = $marc->as_usmarc(); +} elsif ( $format =~ /utf8/ ) { + C4::Charset::SetUTF8Flag( $marc, 1 ); + $marc = $marc->as_usmarc(); $format = 'utf8'; -} -elsif ($format =~ /marcstd/) { - C4::Charset::SetUTF8Flag($marc,1); - ($error,$marc) = marc2marc($marc, 'marcstd', C4::Context->preference('marcflavour')); +} elsif ( $format =~ /marcstd/ ) { + C4::Charset::SetUTF8Flag( $marc, 1 ); + ( $error, $marc ) = marc2marc( $marc, 'marcstd', C4::Context->preference('marcflavour') ); $format = 'marcstd'; -} -elsif ( $format =~ /isbd/ ) { - $marc = GetISBDView({ - 'record' => $marc, - 'template' => 'opac', - 'framework' => $framework, - }); +} elsif ( $format =~ /isbd/ ) { + $marc = GetISBDView( + { + 'record' => $marc, + 'template' => 'opac', + 'framework' => $framework, + } + ); $format = 'isbd'; -} -else { - $error= "Format $format is not supported."; +} else { + $error = "Format $format is not supported."; } -if ($error){ +if ($error) { print $query->header(); print $query->start_html(); print "

            An error occurred

            "; print $query->escapeHTML("$error"); print $query->end_html(); -} -else { - if ($format eq 'marc8'){ +} else { + if ( $format eq 'marc8' ) { print $query->header( - -type => 'application/marc', - -charset=>'ISO-2022', - -attachment=>"$file_pre$file_id.$format"); - } - elsif ( $format eq 'isbd' ) { + -type => 'application/marc', + -charset => 'ISO-2022', + -attachment => "$file_pre$file_id.$format" + ); + } elsif ( $format eq 'isbd' ) { print $query->header( -type => 'text/plain', -charset => 'utf-8', - -attachment => "$file_pre$file_id.txt" + -attachment => "$file_pre$file_id.txt" ); - } - elsif ( $format eq 'ris' ) { + } elsif ( $format eq 'ris' ) { print $query->header( - -type => 'text/plain', - -charset => 'utf-8', + -type => 'text/plain', + -charset => 'utf-8', -attachment => "$file_pre$file_id.$format" ); } else { binmode STDOUT, ':encoding(UTF-8)'; print $query->header( - -type => 'application/octet-stream', - -charset => 'utf-8', + -type => 'application/octet-stream', + -charset => 'utf-8', -attachment => "$file_pre$file_id.$format" ); } diff --git a/opac/opac-holdshistory.pl b/opac/opac-holdshistory.pl index e869128a37..8203bf84af 100755 --- a/opac/opac-holdshistory.pl +++ b/opac/opac-holdshistory.pl @@ -15,12 +15,11 @@ # You should have received a copy of the GNU General Public License # along with Koha; if not, see . - use Modern::Perl; use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use Koha::Patrons; @@ -38,9 +37,9 @@ unless ( C4::Context->preference('OPACHoldsHistory') ) { my ( $template, $patron_id, $cookie ) = get_template_and_user( { - template_name => "opac-holdshistory.tt", - query => $query, - type => "opac" + template_name => "opac-holdshistory.tt", + query => $query, + type => "opac" } ); @@ -50,38 +49,34 @@ my $sort = $query->param('sort'); $sort = 'reservedate' unless $sort; my $unlimit = $query->param('unlimit'); -my $ops = { - prefetch => ['biblio', 'item'], +my $ops = { + prefetch => [ 'biblio', 'item' ], order_by => $sort }; $ops->{rows} = 50 unless $unlimit; -my $holds = Koha::Holds->search({ - borrowernumber => $patron_id -}, $ops); +my $holds = Koha::Holds->search( { borrowernumber => $patron_id }, $ops ); -my $old_holds = Koha::Old::Holds->search({ - borrowernumber => $patron_id -}, $ops); +my $old_holds = Koha::Old::Holds->search( { borrowernumber => $patron_id }, $ops ); -while (my $hold = $holds->next) { +while ( my $hold = $holds->next ) { push @all_holds, $hold; } -while (my $hold = $old_holds->next) { +while ( my $hold = $old_holds->next ) { push @all_holds, $hold; } -if($sort eq 'reservedate') { - @all_holds = sort {$b->$sort cmp $a->$sort} @all_holds; +if ( $sort eq 'reservedate' ) { + @all_holds = sort { $b->$sort cmp $a->$sort } @all_holds; } else { - my ($obj, $col) = split /\./, $sort; - @all_holds = sort { ( $a->$obj && $a->$obj->$col || '' ) cmp ( $b->$obj && $b->$obj->$col || '' ) } @all_holds; + my ( $obj, $col ) = split /\./, $sort; + @all_holds = sort { ( $a->$obj && $a->$obj->$col || '' ) cmp( $b->$obj && $b->$obj->$col || '' ) } @all_holds; } -unless($unlimit) { - @all_holds = splice(@all_holds, 0, 50); +unless ($unlimit) { + @all_holds = splice( @all_holds, 0, 50 ); } $template->param( diff --git a/opac/opac-ics.pl b/opac/opac-ics.pl index ba1f6c6329..4fac925a5b 100755 --- a/opac/opac-ics.pl +++ b/opac/opac-ics.pl @@ -29,29 +29,30 @@ use DateTime::Format::ICal; use DateTime::Event::ICal; use URI; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use Koha::DateUtils qw( dt_from_string ); my $query = CGI->new; my ( $template, $borrowernumber, $cookie ) = get_template_and_user( { - template_name => "opac-ics.tt", - query => $query, - type => "opac", + template_name => "opac-ics.tt", + query => $query, + type => "opac", } ); # Create Calendar my $calendar = Data::ICal->new(); -my $patron = Koha::Patrons->find( $borrowernumber ); +my $patron = Koha::Patrons->find($borrowernumber); my $pending_checkouts = $patron->pending_checkouts; -my $timestamp = dt_from_string(undef,undef,"UTC"); #Get current time in UTC +my $timestamp = dt_from_string( undef, undef, "UTC" ); #Get current time in UTC while ( my $c = $pending_checkouts->next ) { - my $issue = $c->unblessed_all_relateds; + my $issue = $c->unblessed_all_relateds; my $vevent = Data::ICal::Entry::Event->new(); + # Send some values to the template to generate summary and description $issue->{overdue} = $c->is_overdue; $template->param( @@ -59,21 +60,24 @@ while ( my $c = $pending_checkouts->next ) { title => $issue->{'title'}, barcode => $issue->{'barcode'}, ); + # Catch the result of the template and split on newline - my ($summary,$description) = split /\n/, $template->output; + my ( $summary, $description ) = split /\n/, $template->output; my ( $datestart, $datestart_local ); - if ($issue->{'overdue'} && $issue->{'overdue'} == 1) { + if ( $issue->{'overdue'} && $issue->{'overdue'} == 1 ) { + # Not much use adding an event in the past for a book that is overdue # so we set datestart = now - $datestart = $timestamp->clone(); + $datestart = $timestamp->clone(); $datestart_local = $datestart->clone(); } else { - $datestart = dt_from_string($issue->{'date_due'}); + $datestart = dt_from_string( $issue->{'date_due'} ); $datestart_local = $datestart->clone(); $datestart->set_time_zone('UTC'); } + # Create a UID that includes the issue number and the domain - my $domain = ''; + my $domain = ''; my $baseurl = C4::Context->preference('OPACBaseURL'); if ( $baseurl ne '' ) { my $url = URI->new($baseurl); @@ -82,17 +86,19 @@ while ( my $c = $pending_checkouts->next ) { warn "Make sure the systempreference OPACBaseURL is set!"; } my $uid = 'issue-' . $issue->{'issue_id'} . '@' . $domain; + # Create the event my $dtstart; - if ($issue->{'overdue'} && $issue->{'overdue'} == 1) { + if ( $issue->{'overdue'} && $issue->{'overdue'} == 1 ) { + # It's already overdue so make it due as an all day event today $dtstart = [ $datestart->ymd(q{}), { VALUE => 'DATE' } ]; } elsif ( $datestart_local->hour eq '23' && $datestart_local->minute eq '59' ) { + # Checkouts due at 23:59 are "all day events" $dtstart = [ $datestart->ymd(q{}), { VALUE => 'DATE' } ]; - } - else { # Checkouts due any other time are instantaneous events at the date and time due + } else { # Checkouts due any other time are instantaneous events at the date and time due $dtstart = DateTime::Format::ICal->format_datetime($datestart); } @@ -103,6 +109,7 @@ while ( my $c = $pending_checkouts->next ) { dtstart => $dtstart, uid => $uid, ); + # Add it to the calendar $calendar->add_entry($vevent); } diff --git a/opac/opac-idref.pl b/opac/opac-idref.pl index 795842215f..1ca62858fb 100755 --- a/opac/opac-idref.pl +++ b/opac/opac-idref.pl @@ -42,7 +42,7 @@ my ( $template, $borrowernumber, $cookie ) = get_template_and_user( my $ua = LWP::UserAgent->new; # See http://documentation.abes.fr/aideidrefdeveloppeur/index.html#MicroWebBiblio -my $base = 'http://www.idref.fr/services/biblio/'; +my $base = 'http://www.idref.fr/services/biblio/'; my $unimarc3 = $cgi->param('unimarc3'); my $request = HTTP::Request->new( @@ -51,40 +51,42 @@ my $request = HTTP::Request->new( ); $request->protocol('HTTP/1.1'); my $response = $ua->request($request); -if ( not $response->is_success) { - $template->param(error => $base.$unimarc3.'.json'); +if ( not $response->is_success ) { + $template->param( error => $base . $unimarc3 . '.json' ); output_html_with_http_headers $cgi, $cookie, $template->output; exit; } -my $content = Encode::decode("utf8", $response->content); -my $json = from_json( $content ); +my $content = Encode::decode( "utf8", $response->content ); +my $json = from_json($content); my $r; -my @results = ref $json->{sudoc}{result} eq "ARRAY" - ? @{ $json->{sudoc}{result} } - : ($json->{sudoc}{result}); +my @results = + ref $json->{sudoc}{result} eq "ARRAY" + ? @{ $json->{sudoc}{result} } + : ( $json->{sudoc}{result} ); for my $result (@results) { my $role_node = $result->{'role'}; my @roles = - ref $role_node eq "ARRAY" - ? @$role_node - : ($role_node); + ref $role_node eq "ARRAY" + ? @$role_node + : ($role_node); for my $role (@roles) { - my @docs = ref $role->{doc} eq "ARRAY" + my @docs = + ref $role->{doc} eq "ARRAY" ? @{ $role->{doc} } : $role->{doc}; push @$r, - { + { role_name => $role->{roleName}, count => $role->{count}, docs => \@docs, - }; + }; } } $template->param( - content => $r, + content => $r, unimarc3 => $unimarc3, ); diff --git a/opac/opac-illrequests.pl b/opac/opac-illrequests.pl index bb746547a3..bcce23bd69 100755 --- a/opac/opac-illrequests.pl +++ b/opac/opac-illrequests.pl @@ -21,11 +21,11 @@ use Modern::Perl; use JSON qw( encode_json ); -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Auth qw( get_template_and_user ); use C4::Koha; use C4::Output qw( output_html_with_http_headers ); -use POSIX qw( strftime ); +use POSIX qw( strftime ); use Koha::ILL::Request::Config; use Koha::ILL::Requests; @@ -43,20 +43,22 @@ my $query = CGI->new; our $params = $query->Vars(); # if illrequests is disabled, leave immediately -if ( ! C4::Context->preference('ILLModule') ) { +if ( !C4::Context->preference('ILLModule') ) { print $query->redirect("/cgi-bin/koha/errors/404.pl"); exit; } -my ( $template, $loggedinuser, $cookie ) = get_template_and_user({ - template_name => "opac-illrequests.tt", - query => $query, - type => "opac", -}); +my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "opac-illrequests.tt", + query => $query, + type => "opac", + } +); # Are we able to actually work? -my $reduced = C4::Context->preference('ILLOpacbackends'); -my $backends = Koha::ILL::Request::Config->new->available_backends($reduced); +my $reduced = C4::Context->preference('ILLOpacbackends'); +my $backends = Koha::ILL::Request::Config->new->available_backends($reduced); my $backends_available = ( scalar @{$backends} > 0 ); $template->param( backends_available => $backends_available ); my $patron = Koha::Patrons->find($loggedinuser); @@ -66,8 +68,9 @@ my $op = Koha::ILL::Request->get_op_param_deprecation( 'opac', $params ); my ( $illrequest_id, $request ); if ( $illrequest_id = $params->{illrequest_id} ) { $request = Koha::ILL::Requests->find($illrequest_id); + # Make sure the request belongs to the logged in user - if( !$request || $request->borrowernumber != $loggedinuser ) { + if ( !$request || $request->borrowernumber != $loggedinuser ) { print $query->redirect("/cgi-bin/koha/errors/404.pl"); exit; } @@ -81,68 +84,53 @@ if ( ( $op eq 'cud-create' || $op eq 'cancreq' || $op eq 'cud-update' ) && !$can if ( $op eq 'list' ) { - my $requests = Koha::ILL::Requests->search( - { borrowernumber => $loggedinuser } - ); + my $requests = Koha::ILL::Requests->search( { borrowernumber => $loggedinuser } ); $template->param( requests => $requests, backends => $backends ); -} elsif ( $op eq 'view') { - $template->param( - request => $request - ); +} elsif ( $op eq 'view' ) { + $template->param( request => $request ); + +} elsif ( $op eq 'cud-update' ) { + $request->notesopac( $params->{notesopac} )->store; -} elsif ( $op eq 'cud-update') { - $request->notesopac($params->{notesopac})->store; # Send a notice to staff alerting them of the update $request->send_staff_notice('ILL_REQUEST_MODIFIED'); print $query->redirect( - '/cgi-bin/koha/opac-illrequests.pl?op=view&illrequest_id=' - . $illrequest_id - . '&message=1' ); + '/cgi-bin/koha/opac-illrequests.pl?op=view&illrequest_id=' . $illrequest_id . '&message=1' ); exit; -} elsif ( $op eq 'cancreq') { +} elsif ( $op eq 'cancreq' ) { $request->status('CANCREQ')->store; print $query->redirect( - '/cgi-bin/koha/opac-illrequests.pl?op=view&illrequest_id=' - . $illrequest_id - . '&message=1' ); + '/cgi-bin/koha/opac-illrequests.pl?op=view&illrequest_id=' . $illrequest_id . '&message=1' ); exit; } elsif ( $op eq 'cud-create' ) { - if (!$params->{backend}) { + if ( !$params->{backend} ) { my $req = Koha::ILL::Request->new; - $template->param( - backends => $req->available_backends - ); + $template->param( backends => $req->available_backends ); } else { $params->{backend} = 'Standard' if $params->{backend} eq 'FreeForm'; - my $request = Koha::ILL::Request->new - ->load_backend($params->{backend}); + my $request = Koha::ILL::Request->new->load_backend( $params->{backend} ); # Before request creation operations - Preparation - my $availability = - Koha::ILL::Request::Workflow::Availability->new( $params, 'opac' ); - my $type_disclaimer = - Koha::ILL::Request::Workflow::TypeDisclaimer->new( $params, 'opac' ); + my $availability = Koha::ILL::Request::Workflow::Availability->new( $params, 'opac' ); + my $type_disclaimer = Koha::ILL::Request::Workflow::TypeDisclaimer->new( $params, 'opac' ); # ILLCheckAvailability operation - if ($availability->show_availability($request)) { + if ( $availability->show_availability($request) ) { $op = 'availability'; - $template->param( - $availability->availability_template_params($params) - ); + $template->param( $availability->availability_template_params($params) ); output_html_with_http_headers $query, $cookie, $template->output, undef, { force_no_caching => 1 }; exit; - # ILLModuleDisclaimerByType operation - } elsif ( $type_disclaimer->show_type_disclaimer($request)) { + + # ILLModuleDisclaimerByType operation + } elsif ( $type_disclaimer->show_type_disclaimer($request) ) { $op = 'typedisclaimer'; - $template->param( - $type_disclaimer->type_disclaimer_template_params($params) - ); + $template->param( $type_disclaimer->type_disclaimer_template_params($params) ); output_html_with_http_headers $query, $cookie, $template->output, undef, { force_no_caching => 1 }; @@ -157,19 +145,20 @@ if ( $op eq 'list' ) { $params->{lang} = C4::Languages::getlanguage($query); my $backend_result = $request->backend_create($params); - if ($backend_result->{stage} eq 'copyrightclearance') { + if ( $backend_result->{stage} eq 'copyrightclearance' ) { $template->param( - stage => $backend_result->{stage}, - whole => $backend_result + stage => $backend_result->{stage}, + whole => $backend_result ); } else { $template->param( - types => [ "Book", "Article", "Journal" ], - branches => Koha::Libraries->search->unblessed, - whole => $backend_result, - request => $request + types => [ "Book", "Article", "Journal" ], + branches => Koha::Libraries->search->unblessed, + whole => $backend_result, + request => $request ); - if ($backend_result->{stage} eq 'commit') { + if ( $backend_result->{stage} eq 'commit' ) { + # After creation actions if ( $params->{type_disclaimer_submitted} ) { $type_disclaimer->after_request_created( $params, $request ); diff --git a/opac/opac-image.pl b/opac/opac-image.pl index 040bd2d7cb..cb5016e955 100755 --- a/opac/opac-image.pl +++ b/opac/opac-image.pl @@ -57,19 +57,18 @@ imagenumber, a random image is selected. =cut -my ( $image ); +my ($image); if ( C4::Context->preference("OPACLocalCoverImages") ) { - my $imagenumber = $input->param('imagenumber'); + my $imagenumber = $input->param('imagenumber'); my $biblionumber = $input->param('biblionumber'); if ( defined $imagenumber ) { $imagenumber = $input->param('imagenumber'); - $image = Koha::CoverImages->find($imagenumber); + $image = Koha::CoverImages->find($imagenumber); unless ($image) { print $input->redirect("/cgi-bin/koha/errors/404.pl"); exit; } - } - elsif ( defined $biblionumber ) { + } elsif ( defined $biblionumber ) { my $biblio = Koha::Biblios->find($biblionumber); unless ($biblio) { print $input->redirect("/cgi-bin/koha/errors/404.pl"); @@ -85,14 +84,14 @@ if ( C4::Context->preference("OPACLocalCoverImages") ) { $image ||= Koha::CoverImages->no_image; my $image_data = - $input->param('thumbnail') - ? $image->thumbnail - : $image->imagefile; + $input->param('thumbnail') + ? $image->thumbnail + : $image->imagefile; print $input->header( - -type => $image->mimetype, - -expires => '+30m', - -Content_Length => length($image_data) + -type => $image->mimetype, + -expires => '+30m', + -Content_Length => length($image_data) ), $image_data; =head1 AUTHOR diff --git a/opac/opac-imageviewer.pl b/opac/opac-imageviewer.pl index bacbf848a7..4d7f815856 100755 --- a/opac/opac-imageviewer.pl +++ b/opac/opac-imageviewer.pl @@ -19,8 +19,8 @@ use Modern::Perl; -use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use Koha::Biblios; @@ -38,14 +38,15 @@ my ( $template, $borrowernumber, $cookie ) = get_template_and_user( ); my $biblionumber = $query->param('biblionumber') || $query->param('bib'); -my $imagenumber = $query->param('imagenumber'); -unless ( $biblionumber ) { +my $imagenumber = $query->param('imagenumber'); +unless ($biblionumber) { + # Retrieving the biblio from the imagenumber my $image = Koha::CoverImages->find($imagenumber); - my $item = Koha::Items->find($image->{itemnumber}); + my $item = Koha::Items->find( $image->{itemnumber} ); $biblionumber = $item->biblionumber; } -my $biblio = Koha::Biblios->find( $biblionumber ); +my $biblio = Koha::Biblios->find($biblionumber); if ( C4::Context->preference("OPACLocalCoverImages") ) { my $images = !$imagenumber ? Koha::Biblios->find($biblionumber)->cover_images->as_list : []; @@ -53,7 +54,7 @@ if ( C4::Context->preference("OPACLocalCoverImages") ) { OPACLocalCoverImages => 1, images => $images, biblionumber => $biblionumber, - imagenumber => (@$images ? $images->[0]->imagenumber : $imagenumber), + imagenumber => ( @$images ? $images->[0]->imagenumber : $imagenumber ), ); } diff --git a/opac/opac-issue-note.pl b/opac/opac-issue-note.pl index c3e6c40799..9d47a9f1fc 100755 --- a/opac/opac-issue-note.pl +++ b/opac/opac-issue-note.pl @@ -24,7 +24,7 @@ use C4::Koha; use C4::Context; use C4::Scrubber; use C4::Output qw( output_html_with_http_headers ); -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Letters; use Koha::Checkouts; use Koha::DateUtils qw( dt_from_string ); @@ -34,13 +34,13 @@ my $query = CGI->new; my ( $template, $borrowernumber, $cookie ) = get_template_and_user( { - template_name => "opac-issue-note.tt", - query => $query, - type => "opac", + template_name => "opac-issue-note.tt", + query => $query, + type => "opac", } ); -my $patron = Koha::Patrons->find( $borrowernumber ); +my $patron = Koha::Patrons->find($borrowernumber); $template->param( firstname => $patron->firstname, surname => $patron->surname, @@ -48,16 +48,17 @@ $template->param( ); my $issue_id = $query->param('issue_id'); -my $issue = $patron->checkouts->find( $issue_id ); +my $issue = $patron->checkouts->find($issue_id); + +unless ($issue) { -unless ( $issue ) { # exit early print $query->redirect("/cgi-bin/koha/opac-user.pl"); exit; } my $itemnumber = $issue->itemnumber; -my $biblio = $issue->item->biblio; +my $biblio = $issue->item->biblio; $template->param( issue_id => $issue_id, title => $biblio->title, @@ -68,34 +69,36 @@ $template->param( my $op = $query->param('op') || ""; if ( $op eq 'cud-issuenote' && C4::Context->preference('AllowCheckoutNotes') && $issue ) { - my $note = $query->param('note'); - my $scrubber = C4::Scrubber->new(); + my $note = $query->param('note'); + my $scrubber = C4::Scrubber->new(); my $clean_note = $scrubber->scrub($note); - if ( $issue->set({ notedate => dt_from_string(), note => $clean_note, noteseen => 0 })->store ) { - if ($clean_note) { # only send email if note not empty + if ( $issue->set( { notedate => dt_from_string(), note => $clean_note, noteseen => 0 } )->store ) { + if ($clean_note) { # only send email if note not empty my $branch = Koha::Libraries->find( $issue->branchcode ); - my $letter = C4::Letters::GetPreparedLetter ( - module => 'circulation', + my $letter = C4::Letters::GetPreparedLetter( + module => 'circulation', letter_code => 'CHECKOUT_NOTE', - branchcode => $branch, - lang => $patron->lang, - tables => { - 'biblio' => $biblio->biblionumber, + branchcode => $branch, + lang => $patron->lang, + tables => { + 'biblio' => $biblio->biblionumber, 'borrowers' => $borrowernumber, }, ); - my $to_address = $branch->inbound_email_address; + my $to_address = $branch->inbound_email_address; my $reply_address = $patron->email || $patron->emailpro || $patron->B_email; - C4::Letters::EnqueueLetter({ - letter => $letter, - message_transport_type => 'email', - borrowernumber => $patron->borrowernumber, - to_address => $to_address, - reply_address => $reply_address, - }); + C4::Letters::EnqueueLetter( + { + letter => $letter, + message_transport_type => 'email', + borrowernumber => $patron->borrowernumber, + to_address => $to_address, + reply_address => $reply_address, + } + ); } } print $query->redirect("/cgi-bin/koha/opac-user.pl"); diff --git a/opac/opac-library.pl b/opac/opac-library.pl index e4200f5741..ff3c079845 100755 --- a/opac/opac-library.pl +++ b/opac/opac-library.pl @@ -19,7 +19,7 @@ use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Auth qw( get_template_and_user ); use C4::Context; use C4::Output qw( output_html_with_http_headers ); @@ -45,13 +45,13 @@ my ( $template, $borrowernumber, $cookie ) = get_template_and_user( ); my $library; -if( $template->{VARS}->{singleBranchMode} ) { - $library = Koha::Libraries->search({ public => 1 })->next; -} elsif( $branchcode ) { - $library = Koha::Libraries->search({ branchcode => $branchcode, public => 1 })->next; +if ( $template->{VARS}->{singleBranchMode} ) { + $library = Koha::Libraries->search( { public => 1 } )->next; +} elsif ($branchcode) { + $library = Koha::Libraries->search( { branchcode => $branchcode, public => 1 } )->next; } -if( $library ) { +if ($library) { $template->param( library => $library ); } else { my $libraries = Koha::Libraries->search( { public => 1 }, { order_by => ['branchname'] } ); diff --git a/opac/opac-main.pl b/opac/opac-main.pl index 9cc772a25e..465d46aaa3 100755 --- a/opac/opac-main.pl +++ b/opac/opac-main.pl @@ -17,10 +17,9 @@ # You should have received a copy of the GNU General Public License # along with Koha; if not, see . - use Modern::Perl; -use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use Koha::Quotes; use C4::Members; @@ -43,62 +42,69 @@ my ( $template, $borrowernumber, $cookie ) = get_template_and_user( my $casAuthentication = C4::Context->preference('casAuthentication'); $template->param( - casAuthentication => $casAuthentication, + casAuthentication => $casAuthentication, ); my $homebranch = $ENV{OPAC_BRANCH_DEFAULT}; -if (C4::Context->userenv) { +if ( C4::Context->userenv ) { $homebranch = C4::Context->userenv->{'branch'}; } -if (defined $input->param('branch') and length $input->param('branch')) { +if ( defined $input->param('branch') and length $input->param('branch') ) { $homebranch = $input->param('branch'); +} elsif ( C4::Context->userenv and defined $input->param('branch') and length $input->param('branch') == 0 ) { + $homebranch = ""; } -elsif (C4::Context->userenv and defined $input->param('branch') and length $input->param('branch') == 0 ){ - $homebranch = ""; -} - my $news_id = $input->param('news_id'); $template->param( news_id => $news_id ); # For dashboard -my $patron = Koha::Patrons->find( $borrowernumber ); +my $patron = Koha::Patrons->find($borrowernumber); -if ( $patron ) { - my $checkouts = Koha::Checkouts->search({ borrowernumber => $borrowernumber })->count; +if ($patron) { + my $checkouts = Koha::Checkouts->search( { borrowernumber => $borrowernumber } )->count; my ( $overdues_count, $overdues ) = checkoverdues($borrowernumber); - my $holds_pending = Koha::Holds->search({ borrowernumber => $borrowernumber, found => undef })->count; - my $holds_waiting = Koha::Holds->search({ borrowernumber => $borrowernumber })->waiting->count; + my $holds_pending = Koha::Holds->search( { borrowernumber => $borrowernumber, found => undef } )->count; + my $holds_waiting = Koha::Holds->search( { borrowernumber => $borrowernumber } )->waiting->count; my $patron_messages = Koha::Patron::Messages->search( - { - borrowernumber => $borrowernumber, - message_type => 'B', - }); - my $patron_note = $patron->opacnote; - my $total = $patron->account->balance; + { + borrowernumber => $borrowernumber, + message_type => 'B', + } + ); + my $patron_note = $patron->opacnote; + my $total = $patron->account->balance; my $saving_display = C4::Context->preference('OPACShowSavings'); - my $savings = 0; + my $savings = 0; if ( $saving_display =~ /summary/ ) { $savings = $patron->get_savings; } - if ( $checkouts > 0 || $overdues_count > 0 || $holds_pending > 0 || $holds_waiting > 0 || $total > 0 || $patron_note || $patron_messages->count || $savings > 0 ) { + if ( $checkouts > 0 + || $overdues_count > 0 + || $holds_pending > 0 + || $holds_waiting > 0 + || $total > 0 + || $patron_note + || $patron_messages->count + || $savings > 0 ) + { $template->param( - dashboard_info => 1, - checkouts => $checkouts, - overdues => $overdues_count, - holds_pending => $holds_pending, - holds_waiting => $holds_waiting, - total_owing => $total, - patron_messages => $patron_messages, - opacnote => $patron_note, - savings => $savings, + dashboard_info => 1, + checkouts => $checkouts, + overdues => $overdues_count, + holds_pending => $holds_pending, + holds_waiting => $holds_waiting, + total_owing => $total, + patron_messages => $patron_messages, + opacnote => $patron_note, + savings => $savings, ); } } $template->param( branchcode => $homebranch ) if $homebranch; $template->param( - daily_quote => Koha::Quotes->get_daily_quote(), + daily_quote => Koha::Quotes->get_daily_quote(), ); output_html_with_http_headers $input, $cookie, $template->output; diff --git a/opac/opac-memberentry.pl b/opac/opac-memberentry.pl index 28b7a1aa26..ce650168c9 100755 --- a/opac/opac-memberentry.pl +++ b/opac/opac-memberentry.pl @@ -17,14 +17,14 @@ use Modern::Perl; -use CGI qw ( -utf8 ); -use Digest::MD5 qw( md5_base64 md5_hex ); -use JSON qw( to_json ); +use CGI qw ( -utf8 ); +use Digest::MD5 qw( md5_base64 md5_hex ); +use JSON qw( to_json ); use List::MoreUtils qw( any each_array uniq ); -use String::Random qw( random_string ); +use String::Random qw( random_string ); use Try::Tiny; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use C4::Context; use C4::Letters qw( GetPreparedLetter EnqueueLetter SendQueuedMessages ); @@ -66,14 +66,14 @@ if ( $borrowernumber && ( $op eq 'cud-create' || $op eq 'new' ) ) { if ( $op eq q{} ) { if ($borrowernumber) { $op = 'edit'; - } - else { + } else { $op = 'new'; } } my $PatronSelfRegistrationDefaultCategory = C4::Context->preference('PatronSelfRegistrationDefaultCategory'); -my $defaultCategory = Koha::Patron::Categories->find($PatronSelfRegistrationDefaultCategory); +my $defaultCategory = Koha::Patron::Categories->find($PatronSelfRegistrationDefaultCategory); + # Having a valid PatronSelfRegistrationDefaultCategory is mandatory if ( !C4::Context->preference('PatronSelfRegistration') && !$borrowernumber || ( ( $op eq 'new' || $op eq 'cud-create' ) && !$defaultCategory ) ) @@ -88,17 +88,17 @@ my $params = {}; if ( $op eq 'cud-create' || $op eq 'new' ) { my @PatronSelfRegistrationLibraryList = split '\|', C4::Context->preference('PatronSelfRegistrationLibraryList'); $params = { branchcode => { -in => \@PatronSelfRegistrationLibraryList } } - if @PatronSelfRegistrationLibraryList; + if @PatronSelfRegistrationLibraryList; } my $libraries = Koha::Libraries->search( $params, { order_by => ['branchname'] } ); my ( $min, $max ) = Koha::Policy::Patrons::Cardnumber->get_valid_length(); if ( defined $min ) { - $template->param( - minlength_cardnumber => $min, - maxlength_cardnumber => $max - ); - } + $template->param( + minlength_cardnumber => $min, + maxlength_cardnumber => $max + ); +} my $translated_languages = C4::Languages::getTranslatedLanguages( 'opac', C4::Context->preference('template') ); @@ -112,16 +112,16 @@ $template->param( languages => $translated_languages, ); -my $attributes = ParsePatronAttributes($borrowernumber,$cgi); +my $attributes = ParsePatronAttributes( $borrowernumber, $cgi ); my $conflicting_attribute = 0; foreach my $attr (@$attributes) { my $attribute = Koha::Patron::Attribute->new($attr); if ( !$attribute->unique_ok ) { - my $attr_type = Koha::Patron::Attribute::Types->find($attr->{code}); + my $attr_type = Koha::Patron::Attribute::Types->find( $attr->{code} ); $template->param( - extended_unique_id_failed_code => $attr->{code}, - extended_unique_id_failed_value => $attr->{attribute}, + extended_unique_id_failed_code => $attr->{code}, + extended_unique_id_failed_value => $attr->{attribute}, extended_unique_id_failed_description => $attr_type->description, ); $conflicting_attribute = 1; @@ -135,15 +135,17 @@ if ( $op eq 'cud-create' ) { %borrower = DelEmptyFields(%borrower); $borrower{categorycode} ||= $PatronSelfRegistrationDefaultCategory; - my @empty_mandatory_fields = (CheckMandatoryFields( \%borrower, $op ), CheckMandatoryAttributes( \%borrower, $attributes ) ); - my $invalidformfields = CheckForInvalidFields(\%borrower); + my @empty_mandatory_fields = + ( CheckMandatoryFields( \%borrower, $op ), CheckMandatoryAttributes( \%borrower, $attributes ) ); + my $invalidformfields = CheckForInvalidFields( \%borrower ); delete $borrower{'password2'}; my $is_cardnumber_valid; if ( !grep { $_ eq 'cardnumber' } @empty_mandatory_fields ) { + # No point in checking the cardnumber if it's missing and mandatory, it'll just generate a # spurious length warning. - my $patron = Koha::Patrons->find($borrower{borrowernumber}); - $is_cardnumber_valid = Koha::Policy::Patrons::Cardnumber->is_valid($borrower{cardnumber}, $patron); + my $patron = Koha::Patrons->find( $borrower{borrowernumber} ); + $is_cardnumber_valid = Koha::Policy::Patrons::Cardnumber->is_valid( $borrower{cardnumber}, $patron ); unless ($is_cardnumber_valid) { for my $m ( @{ $is_cardnumber_valid->messages } ) { my $message = $m->message; @@ -164,24 +166,16 @@ if ( $op eq 'cud-create' ) { borrower => \%borrower ); $template->param( patron_attribute_classes => GeneratePatronAttributesForm( undef, $attributes ) ); - } - elsif ( - md5_base64( uc( $cgi->param('captcha') ) ) ne $cgi->param('captcha_digest') ) - { + } elsif ( md5_base64( uc( $cgi->param('captcha') ) ) ne $cgi->param('captcha_digest') ) { $template->param( failed_captcha => 1, borrower => \%borrower ); $template->param( patron_attribute_classes => GeneratePatronAttributesForm( undef, $attributes ) ); - } elsif ( !$libraries->find($borrower{branchcode}) ) { - die "Branchcode not allowed"; # They hack the form - } - else { - if ( - C4::Context->preference( - 'PatronSelfRegistrationVerifyByEmail') - ) - { + } elsif ( !$libraries->find( $borrower{branchcode} ) ) { + die "Branchcode not allowed"; # They hack the form + } else { + if ( C4::Context->preference('PatronSelfRegistrationVerifyByEmail') ) { ( $template, $borrowernumber, $cookie ) = get_template_and_user( { template_name => "opac-registration-email-sent.tt", @@ -192,12 +186,14 @@ if ( $op eq 'cud-create' ) { ); $template->param( 'email' => $borrower{'email'} ); - my $verification_token = md5_hex( time().{}.rand().{}.$$ ); + my $verification_token = md5_hex( time() . {} . rand() . {} . $$ ); while ( Koha::Patron::Modifications->search( { verification_token => $verification_token } )->count() ) { - $verification_token = md5_hex( time().{}.rand().{}.$$ ); + $verification_token = md5_hex( time() . {} . rand() . {} . $$ ); } - $borrower{password} = Koha::AuthUtils::generate_password(Koha::Patron::Categories->find($borrower{categorycode})) unless $borrower{password}; + $borrower{password} = + Koha::AuthUtils::generate_password( Koha::Patron::Categories->find( $borrower{categorycode} ) ) + unless $borrower{password}; $borrower{verification_token} = $verification_token; $borrower{extended_attributes} = to_json($attributes); @@ -207,7 +203,7 @@ if ( $op eq 'cud-create' ) { my $letter = C4::Letters::GetPreparedLetter( module => 'members', letter_code => 'OPAC_REG_VERIFY', - lang => 'default', # Patron does not have a preferred language defined yet + lang => 'default', # Patron does not have a preferred language defined yet tables => { borrower_modifications => $verification_token, }, @@ -218,26 +214,28 @@ if ( $op eq 'cud-create' ) { letter => $letter, message_transport_type => 'email', to_address => $borrower{'email'}, - from_address => - C4::Context->preference('KohaAdminEmailAddress'), + from_address => C4::Context->preference('KohaAdminEmailAddress'), } ); C4::Letters::SendQueuedMessages( { message_id => $message_id } ) if $message_id; - } - else { - $borrower{password} ||= Koha::AuthUtils::generate_password(Koha::Patron::Categories->find($borrower{categorycode})); + } else { + $borrower{password} ||= + Koha::AuthUtils::generate_password( Koha::Patron::Categories->find( $borrower{categorycode} ) ); my $consent_dt = delete $borrower{gdpr_proc_consent}; my $patron; try { $patron = Koha::Patron->new( \%borrower )->store; - Koha::Patron::Consent->new({ borrowernumber => $patron->borrowernumber, type => 'GDPR_PROCESSING', given_on => $consent_dt })->store if $patron && $consent_dt; + Koha::Patron::Consent->new( + { borrowernumber => $patron->borrowernumber, type => 'GDPR_PROCESSING', given_on => $consent_dt } ) + ->store + if $patron && $consent_dt; C4::Members::Messaging::SetMessagingPreferencesFromDefaults( { borrowernumber => $patron->borrowernumber, categorycode => $patron->categorycode } ); } catch { my $type = ref($_); my $info = "$_"; $template->param( error_type => $type, error_info => $info ); - $template->param( borrower => \%borrower ); + $template->param( borrower => \%borrower ); }; ( $template, $borrowernumber, $cookie ) = get_template_and_user( @@ -249,19 +247,21 @@ if ( $op eq 'cud-create' ) { } ) if $patron; - if ( $patron ) { + if ($patron) { $patron->extended_attributes->filter_by_branch_limitations->delete; $patron->extended_attributes($attributes); $template->param( password_cleartext => $patron->plain_text_password ); - $template->param( borrower => $patron->unblessed ); + $template->param( borrower => $patron->unblessed ); $template->param( confirmed => 1 ); # If 'AutoEmailNewUser' syspref is on, email user their account details from the 'notice' that matches the user's branchcode. if ( C4::Context->preference("AutoEmailNewUser") ) { + #look for defined primary email address, if blank - attempt to use borr.email and borr.emailpro instead my $emailaddr = $patron->notice_email_address; + # if we manage to find a valid email address, send notice if ($emailaddr) { eval { @@ -297,29 +297,25 @@ if ( $op eq 'cud-create' ) { } } - $template->param( - PatronSelfRegistrationAdditionalInstructions => - C4::Context->preference( - 'PatronSelfRegistrationAdditionalInstructions') - ); + $template->param( PatronSelfRegistrationAdditionalInstructions => + C4::Context->preference('PatronSelfRegistrationAdditionalInstructions') ); } } -} -elsif ( $op eq 'cud-update' ) { +} elsif ( $op eq 'cud-update' ) { - my $borrower = Koha::Patrons->find( $borrowernumber )->unblessed; + my $borrower = Koha::Patrons->find($borrowernumber)->unblessed; my %borrower = ParseCgiForBorrower($cgi); $borrower{borrowernumber} = $borrowernumber; - my @empty_mandatory_fields = grep { $_ ne 'password' } # password is not required when editing personal details - ( CheckMandatoryFields( \%borrower, $op ), CheckMandatoryAttributes( \%borrower, $attributes ) ); - my $invalidformfields = CheckForInvalidFields(\%borrower); + my @empty_mandatory_fields = grep { $_ ne 'password' } # password is not required when editing personal details + ( CheckMandatoryFields( \%borrower, $op ), CheckMandatoryAttributes( \%borrower, $attributes ) ); + my $invalidformfields = CheckForInvalidFields( \%borrower ); # Send back the data to the template %borrower = ( %$borrower, %borrower ); - if (@empty_mandatory_fields || @$invalidformfields) { + if ( @empty_mandatory_fields || @$invalidformfields ) { $template->param( empty_mandatory_fields => \@empty_mandatory_fields, invalid_form_fields => $invalidformfields, @@ -328,8 +324,8 @@ elsif ( $op eq 'cud-update' ) { $template->param( patron_attribute_classes => GeneratePatronAttributesForm( $borrowernumber, $attributes ) ); $template->param( op => 'edit' ); - } - else { + } else { + # If preferred name is not included but firstname is then set preferred_name to firstname $borrower{preferred_name} = $borrower{firstname} if defined $borrower{firstname} && !defined $borrower{preferred_name}; @@ -347,59 +343,59 @@ elsif ( $op eq 'cud-update' ) { } ); - $borrower_changes{borrowernumber} = $borrowernumber; + $borrower_changes{borrowernumber} = $borrowernumber; $borrower_changes{extended_attributes} = to_json($extended_attributes_changes); - Koha::Patron::Modifications->search({ borrowernumber => $borrowernumber })->delete; + Koha::Patron::Modifications->search( { borrowernumber => $borrowernumber } )->delete; my $m = Koha::Patron::Modification->new( \%borrower_changes )->store(); + #Automatically approve patron profile changes if set in syspref - if (C4::Context->preference('AutoApprovePatronProfileSettings')) { + if ( C4::Context->preference('AutoApprovePatronProfileSettings') ) { + # Need to get the object from database, otherwise it is not complete enough to allow deletion # when approval has been performed. - my $tmp_m = Koha::Patron::Modifications->find({borrowernumber => $borrowernumber}); + my $tmp_m = Koha::Patron::Modifications->find( { borrowernumber => $borrowernumber } ); $tmp_m->approve() if $tmp_m; } - my $patron = Koha::Patrons->find( $borrowernumber ); + my $patron = Koha::Patrons->find($borrowernumber); $template->param( borrower => $patron->unblessed ); - } - else { - my $patron = Koha::Patrons->find( $borrowernumber ); + } else { + my $patron = Koha::Patrons->find($borrowernumber); $template->param( - op => 'edit', - nochanges => 1, - borrower => $patron->unblessed, + op => 'edit', + nochanges => 1, + borrower => $patron->unblessed, patron_attribute_classes => GeneratePatronAttributesForm( $borrowernumber, $attributes ), ); } } -} -elsif ( $op eq 'edit' ) { #Display logged in borrower's data - my $patron = Koha::Patrons->find( $borrowernumber ); +} elsif ( $op eq 'edit' ) { #Display logged in borrower's data + my $patron = Koha::Patrons->find($borrowernumber); my $borrower = $patron->unblessed; $template->param( - borrower => $borrower, - hidden => GetHiddenFields( $mandatory, 'edit' ), + borrower => $borrower, + hidden => GetHiddenFields( $mandatory, 'edit' ), ); - if (C4::Context->preference('OPACpatronimages')) { + if ( C4::Context->preference('OPACpatronimages') ) { $template->param( display_patron_image => 1 ) if $patron->image; } - $template->param( patron_attribute_classes => GeneratePatronAttributesForm( $borrowernumber ) ); + $template->param( patron_attribute_classes => GeneratePatronAttributesForm($borrowernumber) ); } else { + # Render self-registration page $template->param( patron_attribute_classes => GeneratePatronAttributesForm() ); } -my $captcha = random_string("CCCCC"); -my $patron_param = Koha::Patrons->find( $borrowernumber ); -$template->param( - has_guarantor_flag => $patron_param->guarantor_relationships->guarantors->_resultset->count -) if $patron_param; +my $captcha = random_string("CCCCC"); +my $patron_param = Koha::Patrons->find($borrowernumber); +$template->param( has_guarantor_flag => $patron_param->guarantor_relationships->guarantors->_resultset->count ) + if $patron_param; $template->param( captcha => $captcha, @@ -413,13 +409,15 @@ sub GetHiddenFields { my ( $mandatory, $op ) = @_; my %hidden_fields; - my $BorrowerUnwantedField = $op eq 'edit' || $op eq 'cud-update' ? - C4::Context->preference( "PatronSelfModificationBorrowerUnwantedField" ) : - C4::Context->preference( "PatronSelfRegistrationBorrowerUnwantedField" ); + my $BorrowerUnwantedField = + $op eq 'edit' || $op eq 'cud-update' + ? C4::Context->preference("PatronSelfModificationBorrowerUnwantedField") + : C4::Context->preference("PatronSelfRegistrationBorrowerUnwantedField"); my @fields = split( /\|/, $BorrowerUnwantedField || q|| ); foreach (@fields) { next unless m/\w/o; + #Don't hide mandatory fields next if $mandatory->{$_}; $hidden_fields{$_} = 1; @@ -433,9 +431,10 @@ sub GetMandatoryFields { my %mandatory_fields; - my $BorrowerMandatoryField = $op eq 'edit' || $op eq 'cud-update' ? - C4::Context->preference("PatronSelfModificationMandatoryField") : - C4::Context->preference("PatronSelfRegistrationBorrowerMandatoryField"); + my $BorrowerMandatoryField = + $op eq 'edit' || $op eq 'cud-update' + ? C4::Context->preference("PatronSelfModificationMandatoryField") + : C4::Context->preference("PatronSelfRegistrationBorrowerMandatoryField"); my @fields = split( /\|/, $BorrowerMandatoryField ); push @fields, 'gdpr_proc_consent' if C4::Context->preference('PrivacyPolicyConsent') && $op eq 'cud-create'; @@ -446,8 +445,7 @@ sub GetMandatoryFields { if ( $op eq 'cud-create' || $op eq 'new' ) { $mandatory_fields{'email'} = 1 - if C4::Context->preference( - 'PatronSelfRegistrationVerifyByEmail'); + if C4::Context->preference('PatronSelfRegistrationVerifyByEmail'); } return \%mandatory_fields; @@ -463,19 +461,19 @@ sub CheckMandatoryFields { foreach my $key ( keys %$mandatory_fields ) { push( @empty_mandatory_fields, $key ) - unless ( defined( $borrower->{$key} ) && $borrower->{$key} ); + unless ( defined( $borrower->{$key} ) && $borrower->{$key} ); } return @empty_mandatory_fields; } -sub CheckMandatoryAttributes{ +sub CheckMandatoryAttributes { my ( $borrower, $attributes ) = @_; my @empty_mandatory_fields; - for my $attribute (@$attributes ) { - my $attr = Koha::Patron::Attribute::Types->find($attribute->{code}); + for my $attribute (@$attributes) { + my $attr = Koha::Patron::Attribute::Types->find( $attribute->{code} ); push @empty_mandatory_fields, $attribute->{code} if $attr && $attr->mandatory && $attribute->{attribute} =~ m|^\s*$|; } @@ -486,37 +484,38 @@ sub CheckMandatoryAttributes{ sub CheckForInvalidFields { my $borrower = shift; my @invalidFields; - if ($borrower->{'email'}) { - unless ( Koha::Email->is_valid($borrower->{email}) ) { - push(@invalidFields, "email"); + if ( $borrower->{'email'} ) { + unless ( Koha::Email->is_valid( $borrower->{email} ) ) { + push( @invalidFields, "email" ); } elsif ( C4::Context->preference("PatronSelfRegistrationEmailMustBeUnique") ) { - my $patrons_with_same_email = Koha::Patrons->search( # FIXME Should be search_limited? + my $patrons_with_same_email = Koha::Patrons->search( # FIXME Should be search_limited? { email => $borrower->{email}, ( exists $borrower->{borrowernumber} - ? ( borrowernumber => - { '!=' => $borrower->{borrowernumber} } ) + ? ( borrowernumber => { '!=' => $borrower->{borrowernumber} } ) : () ) } )->count; - if ( $patrons_with_same_email ) { + if ($patrons_with_same_email) { push @invalidFields, "duplicate_email"; } } elsif ( C4::Context->preference("PatronSelfRegistrationConfirmEmail") && $borrower->{'email'} ne $borrower->{'repeat_email'} - && !defined $borrower->{borrowernumber} ) { + && !defined $borrower->{borrowernumber} ) + { push @invalidFields, "email_match"; } + # email passed all tests, so prevent attempting to store repeat_email delete $borrower->{'repeat_email'}; } - if ($borrower->{'emailpro'}) { - push(@invalidFields, "emailpro") unless Koha::Email->is_valid($borrower->{'emailpro'}); + if ( $borrower->{'emailpro'} ) { + push( @invalidFields, "emailpro" ) unless Koha::Email->is_valid( $borrower->{'emailpro'} ); } - if ($borrower->{'B_email'}) { - push(@invalidFields, "B_email") unless Koha::Email->is_valid($borrower->{'B_email'}); + if ( $borrower->{'B_email'} ) { + push( @invalidFields, "B_email" ) unless Koha::Email->is_valid( $borrower->{'B_email'} ); } if ( defined $borrower->{'password'} and $borrower->{'password'} ne $borrower->{'password2'} ) @@ -524,12 +523,17 @@ sub CheckForInvalidFields { push( @invalidFields, "password_match" ); } if ( $borrower->{'password'} ) { - my ( $is_valid, $error ) = Koha::AuthUtils::is_password_valid( $borrower->{password}, Koha::Patron::Categories->find($borrower->{categorycode}||C4::Context->preference('PatronSelfRegistrationDefaultCategory')) ); - unless ( $is_valid ) { - push @invalidFields, 'password_too_short' if $error eq 'too_short'; - push @invalidFields, 'password_too_weak' if $error eq 'too_weak'; - push @invalidFields, 'password_has_whitespaces' if $error eq 'has_whitespaces'; - } + my ( $is_valid, $error ) = Koha::AuthUtils::is_password_valid( + $borrower->{password}, + Koha::Patron::Categories->find( + $borrower->{categorycode} || C4::Context->preference('PatronSelfRegistrationDefaultCategory') + ) + ); + unless ($is_valid) { + push @invalidFields, 'password_too_short' if $error eq 'too_short'; + push @invalidFields, 'password_too_weak' if $error eq 'too_weak'; + push @invalidFields, 'password_has_whitespaces' if $error eq 'has_whitespaces'; + } } if ( $borrower->{'dateofbirth'} ) { @@ -557,6 +561,7 @@ sub ParseCgiForBorrower { if ( $field !~ '^borrower_password' ) { $borrower{$key} = $scrubber->scrub( scalar $cgi->param($field) ); } else { + # Allow html characters for passwords $borrower{$key} = $cgi->param($field); } @@ -564,23 +569,33 @@ sub ParseCgiForBorrower { } # Replace checkbox 'agreed' by datetime in gdpr_proc_consent - $borrower{gdpr_proc_consent} = dt_from_string if $borrower{gdpr_proc_consent} && $borrower{gdpr_proc_consent} eq 'agreed'; + $borrower{gdpr_proc_consent} = dt_from_string + if $borrower{gdpr_proc_consent} && $borrower{gdpr_proc_consent} eq 'agreed'; - delete $borrower{$_} for qw/borrowernumber date_renewed debarred debarredcomment flags privacy privacy_guarantor_fines privacy_guarantor_checkouts checkprevcheckout updated_on lastseen login_attempts overdrive_auth_token anonymized/; # See also members/memberentry.pl - delete $borrower{$_} for qw/dateenrolled dateexpiry borrowernotes opacnote sort1 sort2 sms_provider_id autorenew_checkouts gonenoaddress lost relationship/; # On OPAC only - delete $borrower{$_} for split( /\s*\|\s*/, C4::Context->preference('PatronSelfRegistrationBorrowerUnwantedField') || q{} ); + delete $borrower{$_} + for + qw/borrowernumber date_renewed debarred debarredcomment flags privacy privacy_guarantor_fines privacy_guarantor_checkouts checkprevcheckout updated_on lastseen login_attempts overdrive_auth_token anonymized/ + ; # See also members/memberentry.pl + delete $borrower{$_} + for + qw/dateenrolled dateexpiry borrowernotes opacnote sort1 sort2 sms_provider_id autorenew_checkouts gonenoaddress lost relationship/ + ; # On OPAC only + delete $borrower{$_} + for split( /\s*\|\s*/, C4::Context->preference('PatronSelfRegistrationBorrowerUnwantedField') || q{} ); return %borrower; } sub DelUnchangedFields { my ( $borrowernumber, %new_data ) = @_; + # get the mandatory fields so we can get the hidden fields - my $mandatory = GetMandatoryFields('edit'); - my $patron = Koha::Patrons->find( $borrowernumber ); + my $mandatory = GetMandatoryFields('edit'); + my $patron = Koha::Patrons->find($borrowernumber); my $current_data = $patron->unblessed; + # get the hidden fields so we don't obliterate them should they have data patrons aren't allowed to modify - my $hidden_fields = GetHiddenFields($mandatory, 'edit'); + my $hidden_fields = GetHiddenFields( $mandatory, 'edit' ); foreach my $key ( keys %new_data ) { next @@ -606,7 +621,8 @@ sub DelEmptyFields { sub FilterUnchangedAttributes { my ( $borrowernumber, $entered_attributes ) = @_; - my @patron_attributes = grep {$_->type->opac_editable ? $_ : ()} Koha::Patron::Attributes->search({ borrowernumber => $borrowernumber })->as_list; + my @patron_attributes = grep { $_->type->opac_editable ? $_ : () } + Koha::Patron::Attributes->search( { borrowernumber => $borrowernumber } )->as_list; my $patron_attribute_types; foreach my $attr (@patron_attributes) { @@ -614,43 +630,47 @@ sub FilterUnchangedAttributes { } my $passed_attribute_types; - foreach my $attr (@{ $entered_attributes }) { - $passed_attribute_types->{ $attr->{ code } } += 1; + foreach my $attr ( @{$entered_attributes} ) { + $passed_attribute_types->{ $attr->{code} } += 1; } my @changed_attributes; # Loop through the current patron attributes - foreach my $attribute_type ( keys %{ $patron_attribute_types } ) { - if ( ( $patron_attribute_types->{$attribute_type} // q{} ) ne ( $passed_attribute_types->{$attribute_type} // q{} ) ) { + foreach my $attribute_type ( keys %{$patron_attribute_types} ) { + if ( ( $patron_attribute_types->{$attribute_type} // q{} ) ne + ( $passed_attribute_types->{$attribute_type} // q{} ) ) + { # count differs, overwrite all attributes for given type foreach my $attr ( @{$entered_attributes} ) { push @changed_attributes, $attr if $attr->{code} eq $attribute_type; } } else { + # count matches, check values my $changes = 0; - foreach my $attr (grep { $_->code eq $attribute_type } @patron_attributes) { + foreach my $attr ( grep { $_->code eq $attribute_type } @patron_attributes ) { $changes = 1 - unless any { $_->{ value } eq $attr->attribute } @{ $entered_attributes }; + unless any { $_->{value} eq $attr->attribute } @{$entered_attributes}; last if $changes; } - if ( $changes ) { - foreach my $attr (@{ $entered_attributes }) { + if ($changes) { + foreach my $attr ( @{$entered_attributes} ) { push @changed_attributes, $attr - if $attr->{ code } eq $attribute_type; + if $attr->{code} eq $attribute_type; } } } } # Loop through passed attributes, looking for new ones - foreach my $attribute_type ( keys %{ $passed_attribute_types } ) { - if ( !defined $patron_attribute_types->{ $attribute_type } ) { + foreach my $attribute_type ( keys %{$passed_attribute_types} ) { + if ( !defined $patron_attribute_types->{$attribute_type} ) { + # YAY, new stuff - foreach my $attr (grep { $_->{code} eq $attribute_type } @{ $entered_attributes }) { + foreach my $attr ( grep { $_->{code} eq $attribute_type } @{$entered_attributes} ) { push @changed_attributes, $attr; } } @@ -663,14 +683,14 @@ sub GeneratePatronAttributesForm { my ( $borrowernumber, $entered_attributes ) = @_; # Get all attribute types and the values for this patron (if applicable) - my @types = grep { $_->opac_editable() or $_->opac_display } # FIXME filter using DBIC + my @types = grep { $_->opac_editable() or $_->opac_display } # FIXME filter using DBIC Koha::Patron::Attribute::Types->search()->as_list(); if ( scalar(@types) == 0 ) { return []; } my @displayable_attributes = grep { $_->type->opac_display ? $_ : () } - Koha::Patron::Attributes->search({ borrowernumber => $borrowernumber })->as_list; + Koha::Patron::Attributes->search( { borrowernumber => $borrowernumber } )->as_list; my %attr_values = (); @@ -680,8 +700,7 @@ sub GeneratePatronAttributesForm { foreach my $attr (@$entered_attributes) { push @{ $attr_values{ $attr->{code} } }, $attr->{attribute}; } - } - elsif ( defined $borrowernumber ) { + } elsif ( defined $borrowernumber ) { my @editable_attributes = grep { $_->type->opac_editable ? $_ : () } @displayable_attributes; foreach my $attr (@editable_attributes) { push @{ $attr_values{ $attr->code } }, $attr->attribute; @@ -700,12 +719,13 @@ sub GeneratePatronAttributesForm { foreach my $attr_type (@types) { push @{ $items_by_class{ $attr_type->class() } }, { type => $attr_type, + # If editable, make sure there's at least one empty entry, # to make the template's job easier values => $attr_values{ $attr_type->code() } || [''] - } + } unless !defined $attr_values{ $attr_type->code() } - and !$attr_type->opac_editable; + and !$attr_type->opac_editable; } # Finally, build a list of containing classes @@ -713,8 +733,7 @@ sub GeneratePatronAttributesForm { foreach my $class (@classes) { next unless ( $items_by_class{$class} ); - my $av = Koha::AuthorisedValues->search( - { category => 'PA_CLASS', authorised_value => $class } ); + my $av = Koha::AuthorisedValues->search( { category => 'PA_CLASS', authorised_value => $class } ); my $lib = $av->count ? $av->next->opac_description : $class; @@ -735,8 +754,8 @@ sub ParsePatronAttributes { my @codes = $cgi->multi_param('patron_attribute_code'); my @values = $cgi->multi_param('patron_attribute_value'); - my @editable_attribute_types - = map { $_->code } Koha::Patron::Attribute::Types->search({ opac_editable => 1 })->as_list; + my @editable_attribute_types = + map { $_->code } Koha::Patron::Attribute::Types->search( { opac_editable => 1 } )->as_list; my $ea = each_array( @codes, @values ); my @attributes; @@ -746,14 +765,15 @@ sub ParsePatronAttributes { my $scrubber = C4::Scrubber->new(); while ( my ( $code, $value ) = $ea->() ) { if ( any { $_ eq $code } @editable_attribute_types ) { + # It is an editable attribute if ( !defined($value) or $value eq '' ) { $delete_candidates->{$code} = 1 unless $delete_candidates->{$code}; - } - else { + } else { + # we've got a value - push @attributes, { code => $code, attribute => $scrubber->scrub( $value ) }; + push @attributes, { code => $code, attribute => $scrubber->scrub($value) }; # 'code' is no longer a delete candidate delete $delete_candidates->{$code} @@ -763,9 +783,10 @@ sub ParsePatronAttributes { } foreach my $code ( keys %{$delete_candidates} ) { - if ( !$borrowernumber # self-registration - || Koha::Patron::Attributes->search({ - borrowernumber => $borrowernumber, code => $code })->count > 0 ) + if ( + !$borrowernumber # self-registration + || Koha::Patron::Attributes->search( { borrowernumber => $borrowernumber, code => $code } )->count > 0 + ) { push @attributes, { code => $code, attribute => '' } unless any { $_->{code} eq $code } @attributes; @@ -775,5 +796,4 @@ sub ParsePatronAttributes { return \@attributes; } - 1; diff --git a/opac/opac-messaging.pl b/opac/opac-messaging.pl index a3eab4d74f..1a311cf157 100755 --- a/opac/opac-messaging.pl +++ b/opac/opac-messaging.pl @@ -29,24 +29,25 @@ use C4::Form::MessagingPreferences; use Koha::Patrons; use Koha::SMS::Providers; -my $query = CGI->new(); +my $query = CGI->new(); my $opac_messaging = C4::Context->preference('EnhancedMessagingPreferencesOPAC'); -unless ( ( $opac_messaging or C4::Context->preference('TranslateNotices') ) and - C4::Context->preference('EnhancedMessagingPreferences') ) { +unless ( ( $opac_messaging or C4::Context->preference('TranslateNotices') ) + and C4::Context->preference('EnhancedMessagingPreferences') ) +{ print $query->redirect("/cgi-bin/koha/errors/404.pl"); exit; } my ( $template, $borrowernumber, $cookie ) = get_template_and_user( { - template_name => 'opac-messaging.tt', - query => $query, - type => 'opac', + template_name => 'opac-messaging.tt', + query => $query, + type => 'opac', } ); -my $patron = Koha::Patrons->find( $borrowernumber ); # FIXME and if borrowernumber is invalid? +my $patron = Koha::Patrons->find($borrowernumber); # FIXME and if borrowernumber is invalid? my $messaging_options; $messaging_options = C4::Members::Messaging::GetMessagingOptions() if $opac_messaging; @@ -54,35 +55,41 @@ $messaging_options = C4::Members::Messaging::GetMessagingOptions() if $opac_mess my $op = $query->param('op') || q{}; if ( $op eq 'cud-modify' ) { - if( $opac_messaging ) { - my $sms = $query->param('SMSnumber'); + if ($opac_messaging) { + my $sms = $query->param('SMSnumber'); my $sms_provider_id = $query->param('sms_provider_id'); - $patron->set({ - smsalertnumber => $sms, - sms_provider_id => $sms_provider_id, - })->store; + $patron->set( + { + smsalertnumber => $sms, + sms_provider_id => $sms_provider_id, + } + )->store; - C4::Form::MessagingPreferences::handle_form_action($query, { borrowernumber => $patron->borrowernumber }, $template); + C4::Form::MessagingPreferences::handle_form_action( + $query, { borrowernumber => $patron->borrowernumber }, + $template + ); } if ( C4::Context->preference('TranslateNotices') ) { - $patron->set({ lang => scalar $query->param('lang') })->store; + $patron->set( { lang => scalar $query->param('lang') } )->store; } } -C4::Form::MessagingPreferences::set_form_values({ borrowernumber => $patron->borrowernumber }, $template) if $opac_messaging; +C4::Form::MessagingPreferences::set_form_values( { borrowernumber => $patron->borrowernumber }, $template ) + if $opac_messaging; $template->param( messagingview => 1, - SMSnumber => $patron->smsalertnumber, # FIXME This is already sent 2 lines above + SMSnumber => $patron->smsalertnumber, # FIXME This is already sent 2 lines above SMSSendDriver => C4::Context->preference("SMSSendDriver"), TalkingTechItivaPhone => C4::Context->preference("TalkingTechItivaPhoneNotification"), ); -if( $opac_messaging && C4::Context->preference("SMSSendDriver") eq 'Email' ) { +if ( $opac_messaging && C4::Context->preference("SMSSendDriver") eq 'Email' ) { my @providers = Koha::SMS::Providers->search( {}, { order_by => 'name' } )->as_list; $template->param( - sms_providers => \@providers, + sms_providers => \@providers, sms_provider_id => $patron->sms_provider_id, ); } @@ -92,7 +99,7 @@ my $new_session_id = $query->cookie('CGISESSID'); if ( C4::Context->preference('TranslateNotices') ) { my $translated_languages = C4::Languages::getTranslatedLanguages( 'opac', C4::Context->preference('template') ); $template->param( - languages => $translated_languages, + languages => $translated_languages, patron_lang => $patron->lang, ); } diff --git a/opac/opac-modrequest-suspend.pl b/opac/opac-modrequest-suspend.pl index eeff53182d..f494fb0462 100755 --- a/opac/opac-modrequest-suspend.pl +++ b/opac/opac-modrequest-suspend.pl @@ -20,16 +20,16 @@ use Modern::Perl; use CGI qw ( -utf8 ); use C4::Output; use C4::Reserves qw( SuspendAll ); -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use Koha::Patrons; my $query = CGI->new; my ( $template, $borrowernumber, $cookie ) = get_template_and_user( { - template_name => "opac-account.tt", - query => $query, - type => "opac", + template_name => "opac-account.tt", + query => $query, + type => "opac", } ); @@ -46,8 +46,7 @@ if ( $op eq 'cud-suspend' ) { my $patron = Koha::Patrons->find($borrowernumber); my $hold = $patron->holds->find($reserve_id); $hold->resume if $hold && $hold->is_cancelable_from_opac; -} -elsif( $op eq 'cud-suspend_all' || $op eq 'cud-unsuspend_all' ) { +} elsif ( $op eq 'cud-suspend_all' || $op eq 'cud-unsuspend_all' ) { SuspendAll( borrowernumber => $borrowernumber, suspend => $suspend, diff --git a/opac/opac-modrequest.pl b/opac/opac-modrequest.pl index f8ebd16988..13e4387a92 100755 --- a/opac/opac-modrequest.pl +++ b/opac/opac-modrequest.pl @@ -4,7 +4,6 @@ #written 2/1/00 by chris@katipo.oc.nz #last update 27/1/2000 by chris@katipo.co.nz - # Copyright 2000-2002 Katipo Communications # # This file is part of Koha. @@ -32,16 +31,16 @@ use Koha::Holds; my $query = CGI->new; my ( $template, $borrowernumber, $cookie ) = get_template_and_user( - { - template_name => "opac-account.tt", - query => $query, - type => "opac", + { + template_name => "opac-account.tt", + query => $query, + type => "opac", } ); -my $op = $query->param('op'); -my $reserve_id = $query->param('reserve_id'); -my $new_pickup_location = $query->param('new_pickup_location'); +my $op = $query->param('op'); +my $reserve_id = $query->param('reserve_id'); +my $new_pickup_location = $query->param('new_pickup_location'); if ( $reserve_id && $borrowernumber ) { @@ -56,20 +55,18 @@ if ( $reserve_id && $borrowernumber ) { if ( $op eq 'cud-request_cancellation' ) { $hold->add_cancellation_request - if $hold->cancellation_requestable_from_opac; - } - elsif ( $op eq 'cud-change_branch' && $new_pickup_location ) { + if $hold->cancellation_requestable_from_opac; + } elsif ( $op eq 'cud-change_branch' && $new_pickup_location ) { + + if ( $hold->can_update_pickup_location_opac ) { + $hold->set_pickup_location( { library_id => $new_pickup_location } ); + } else { - if ($hold->can_update_pickup_location_opac) { - $hold->set_pickup_location({ library_id => $new_pickup_location }); - } - else { # whatcha tryin to do? print $query->redirect('/cgi-bin/koha/errors/403.pl'); exit; } - } - elsif ( $op eq 'cud-cancel' && $hold->is_cancelable_from_opac ) { + } elsif ( $op eq 'cud-cancel' && $hold->is_cancelable_from_opac ) { $hold->cancel; } } diff --git a/opac/opac-mymessages.pl b/opac/opac-mymessages.pl index 6acebadc4d..255d0bf636 100755 --- a/opac/opac-mymessages.pl +++ b/opac/opac-mymessages.pl @@ -30,17 +30,21 @@ my $query = CGI->new(); my ( $template, $borrowernumber, $cookie ) = get_template_and_user( { - template_name => 'opac-mymessages.tt', - query => $query, - type => 'opac', + template_name => 'opac-mymessages.tt', + query => $query, + type => 'opac', } ); +my $messages = C4::Letters::GetRSSMessages( + { + borrowernumber => $borrowernumber, + limit => 20 + } +); -my $messages = C4::Letters::GetRSSMessages( { borrowernumber => $borrowernumber, - limit => 20 } ); - -$template->param( message_list => $messages, - ); +$template->param( + message_list => $messages, +); output_html_with_http_headers $query, $cookie, $template->output, undef, { force_no_caching => 1 }; diff --git a/opac/opac-news-rss.pl b/opac/opac-news-rss.pl index 60d700e3e8..047bcb32ac 100755 --- a/opac/opac-news-rss.pl +++ b/opac/opac-news-rss.pl @@ -17,10 +17,9 @@ # You should have received a copy of the GNU General Public License # along with Koha; if not, see . - use Modern::Perl; use CGI; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use Koha::AdditionalContents; @@ -38,14 +37,15 @@ my ( $template, $borrowernumber, $cookie ) = get_template_and_user( # Get the news to display # use cookie setting for language, bug default to syspref if it's not set -my ($theme, $news_lang, $availablethemes) = C4::Templates::themelanguage(C4::Context->config('opachtdocs'),'opac-main.tt','opac',$input); +my ( $theme, $news_lang, $availablethemes ) = + C4::Templates::themelanguage( C4::Context->config('opachtdocs'), 'opac-main.tt', 'opac', $input ); my $branchcode = $input->param('branchcode'); my $koha_news = Koha::AdditionalContents->search_for_display( { category => 'news', - location => ['opac_only', 'staff_and_opac'], + location => [ 'opac_only', 'staff_and_opac' ], lang => $news_lang, library_id => $branchcode, } diff --git a/opac/opac-overdrive-search.pl b/opac/opac-overdrive-search.pl index a56d1530ea..8e1d205074 100755 --- a/opac/opac-overdrive-search.pl +++ b/opac/opac-overdrive-search.pl @@ -43,10 +43,10 @@ my ( $template, $loggedinuser, $cookie ) = get_template_and_user( } ); -$template->{'VARS'}->{'q'} = $cgi->param('q'); -$template->{'VARS'}->{'limit'} = C4::Context->preference('OPACnumSearchResults') || 20; +$template->{'VARS'}->{'q'} = $cgi->param('q'); +$template->{'VARS'}->{'limit'} = C4::Context->preference('OPACnumSearchResults') || 20; $template->{'VARS'}->{'OPACnumSearchResults'} = C4::Context->preference('OPACnumSearchResults') || 20; -$template->{'VARS'}->{'OverDriveLibraryID'} = C4::Context->preference('OverDriveLibraryID'); -$template->param(overdrive_error => scalar $cgi->param('overdrive_error')); +$template->{'VARS'}->{'OverDriveLibraryID'} = C4::Context->preference('OverDriveLibraryID'); +$template->param( overdrive_error => scalar $cgi->param('overdrive_error') ); output_html_with_http_headers $cgi, $cookie, $template->output; diff --git a/opac/opac-page.pl b/opac/opac-page.pl index 0a35c21433..ec8dd995e3 100755 --- a/opac/opac-page.pl +++ b/opac/opac-page.pl @@ -17,9 +17,9 @@ use Modern::Perl; -use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); -use C4::Output qw( output_html_with_http_headers ); +use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); +use C4::Output qw( output_html_with_http_headers ); use C4::Languages qw( getlanguage ); use Koha::AdditionalContents; @@ -37,13 +37,17 @@ my ( $template, $borrowernumber, $cookie ) = get_template_and_user( my $page_id = $query->param('page_id'); my $homebranch = $ENV{OPAC_BRANCH_DEFAULT}; -if (C4::Context->userenv) { +if ( C4::Context->userenv ) { $homebranch = C4::Context->userenv->{'branch'}; } my $page = Koha::AdditionalContents->find($page_id); -if ( !$page || $page->category ne 'pages' || $page->branchcode && $page->branchcode != $homebranch || $page->location ne 'opac_only' && $page->location ne 'staff_and_opac' ) { +if ( !$page + || $page->category ne 'pages' + || $page->branchcode && $page->branchcode != $homebranch + || $page->location ne 'opac_only' && $page->location ne 'staff_and_opac' ) +{ print $query->redirect('/cgi-bin/koha/errors/404.pl'); exit; } diff --git a/opac/opac-passwd.pl b/opac/opac-passwd.pl index 666e359a1b..820a2b80d4 100755 --- a/opac/opac-passwd.pl +++ b/opac/opac-passwd.pl @@ -30,17 +30,17 @@ use Koha::Patrons; use Try::Tiny qw( catch try ); my $query = CGI->new; -my $op = $query->param('op') || q{}; +my $op = $query->param('op') || q{}; my ( $template, $borrowernumber, $cookie ) = get_template_and_user( { - template_name => "opac-passwd.tt", - query => $query, - type => "opac", + template_name => "opac-passwd.tt", + query => $query, + type => "opac", } ); -my $patron = Koha::Patrons->find( $borrowernumber ); +my $patron = Koha::Patrons->find($borrowernumber); if ( $patron->category->effective_change_password ) { if ( $query->param('Oldkey') && $query->param('Newkey') @@ -48,21 +48,20 @@ if ( $patron->category->effective_change_password ) { { die "op must be set" unless $op eq 'cud-change_password'; my $error; - my $new_password = $query->param('Newkey'); + my $new_password = $query->param('Newkey'); my $confirm_password = $query->param('Confirm'); if ( C4::Auth::checkpw_hash( scalar $query->param('Oldkey'), $patron->password ) ) { if ( $new_password ne $confirm_password ) { - $template->param( 'Ask_data' => '1' ); - $template->param( 'Error_messages' => '1' ); - $template->param( 'passwords_mismatch' => '1' ); + $template->param( 'Ask_data' => '1' ); + $template->param( 'Error_messages' => '1' ); + $template->param( 'passwords_mismatch' => '1' ); } else { try { - $patron->set_password({ password => $new_password }); + $patron->set_password( { password => $new_password } ); $template->param( 'password_updated' => '1' ); $template->param( 'borrowernumber' => $borrowernumber ); - } - catch { + } catch { $error = 'password_too_short' if $_->isa('Koha::Exceptions::Password::TooShort'); $error = 'password_too_weak' @@ -71,8 +70,7 @@ if ( $patron->category->effective_change_password ) { if $_->isa('Koha::Exceptions::Password::WhitespaceCharacters'); }; } - } - else { + } else { $error = 'WrongPass'; } if ($error) { @@ -83,17 +81,17 @@ if ( $patron->category->effective_change_password ) { ); } - } - else { + } else { # Called Empty, Ask for data. $template->param( 'Ask_data' => '1' ); - if (!$query->param('Oldkey') && ($query->param('Newkey') || $query->param('Confirm'))){ + if ( !$query->param('Oldkey') && ( $query->param('Newkey') || $query->param('Confirm') ) ) { + # Old password is empty but one of the others isn't $template->param( 'Error_messages' => '1' ); $template->param( 'WrongPass' => '1' ); - } - elsif ($query->param('Oldkey') && (!$query->param('Newkey') || !$query->param('Confirm'))){ + } elsif ( $query->param('Oldkey') && ( !$query->param('Newkey') || !$query->param('Confirm') ) ) { + # Oldpassword is entered but one of the other fields is empty $template->param( 'Error_messages' => '1' ); $template->param( 'PassMismatch' => '1' ); @@ -106,5 +104,4 @@ $template->param( passwdview => 1, ); - output_html_with_http_headers $query, $cookie, $template->output, undef, { force_no_caching => 1 }; diff --git a/opac/opac-password-recovery.pl b/opac/opac-password-recovery.pl index e66df099d5..85ed8b405c 100755 --- a/opac/opac-password-recovery.pl +++ b/opac/opac-password-recovery.pl @@ -3,7 +3,7 @@ use Modern::Perl; use CGI; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use C4::Context; use Koha::Patron::Password::Recovery qw( @@ -16,7 +16,7 @@ use Koha::Patron::Password::Recovery qw( use Koha::Patrons; my $query = CGI->new; use HTML::Entities; -use Try::Tiny qw( catch try ); +use Try::Tiny qw( catch try ); use List::Util qw( any ); my ( $template, $dummy, $cookie ) = get_template_and_user( @@ -28,7 +28,7 @@ my ( $template, $dummy, $cookie ) = get_template_and_user( } ); -my $op = $query->param('op') // q{}; +my $op = $query->param('op') // q{}; my $email = $query->param('email') // q{}; my $password = $query->param('newPassword'); my $repeatPassword = $query->param('repeatPassword'); @@ -55,27 +55,34 @@ if ( $op eq 'cud-sendEmail' || $op eq 'cud-resendEmail' ) { #try with the main email my $borrower; my $search_results; + # Find the borrower by userid, card number, or email if ($username) { - $search_results = Koha::Patrons->search( { -or => { userid => $username, cardnumber => $username }, login_attempts => { '!=', Koha::Patron::ADMINISTRATIVE_LOCKOUT } } ); - } - elsif ($email) { - $search_results = Koha::Patrons->search( { -or => { email => $email, emailpro => $email, B_email => $email }, login_attempts => { '!=', Koha::Patron::ADMINISTRATIVE_LOCKOUT } } ); + $search_results = Koha::Patrons->search( + { + -or => { userid => $username, cardnumber => $username }, + login_attempts => { '!=', Koha::Patron::ADMINISTRATIVE_LOCKOUT } + } + ); + } elsif ($email) { + $search_results = Koha::Patrons->search( + { + -or => { email => $email, emailpro => $email, B_email => $email }, + login_attempts => { '!=', Koha::Patron::ADMINISTRATIVE_LOCKOUT } + } + ); } - if ( !defined $search_results || $search_results->count < 1) { + if ( !defined $search_results || $search_results->count < 1 ) { $hasError = 1; $errNoBorrowerFound = 1; - } - elsif ( $username && $search_results->count > 1) { # Multiple accounts for username + } elsif ( $username && $search_results->count > 1 ) { # Multiple accounts for username $hasError = 1; $errNoBorrowerFound = 1; - } - elsif ( $email && $search_results->count > 1) { # Muliple accounts for E-Mail - $hasError = 1; + } elsif ( $email && $search_results->count > 1 ) { # Muliple accounts for E-Mail + $hasError = 1; $errMultipleAccountsForEmail = 1; - } - elsif ( $borrower = $search_results->next() ) { # One matching borrower + } elsif ( $borrower = $search_results->next() ) { # One matching borrower if ( $borrower->category->effective_reset_password ) { @@ -86,7 +93,7 @@ if ( $op eq 'cud-sendEmail' || $op eq 'cud-resendEmail' ) { # Is the given email one of the borrower's ? if ( $email && !( any { lc($_) eq lc($email) } @emails ) ) { - $hasError = 1; + $hasError = 1; $errNoBorrowerFound = 1; } @@ -102,57 +109,52 @@ if ( $op eq 'cud-sendEmail' || $op eq 'cud-resendEmail' ) { if ( ValidateBorrowernumber( $borrower->borrowernumber ) ) { $hasError = 1; $errAlreadyStartRecovery = 1; - } - else { + } else { DeleteExpiredPasswordRecovery( $borrower->borrowernumber ); } } + # Set the $email, if we don't have one. if ( !$hasError && !$email ) { $email = $firstNonEmptyEmail; } - } - else { + } else { $hasError = 1; $errResetForbidden = 1; } - } - else { # 0 matching borrower + } else { # 0 matching borrower $hasError = 1; $errNoBorrowerFound = 1; } if ($hasError) { $template->param( - hasError => 1, - errNoBorrowerFound => $errNoBorrowerFound, - errAlreadyStartRecovery => $errAlreadyStartRecovery, - errNoBorrowerEmail => $errNoBorrowerEmail, + hasError => 1, + errNoBorrowerFound => $errNoBorrowerFound, + errAlreadyStartRecovery => $errAlreadyStartRecovery, + errNoBorrowerEmail => $errNoBorrowerEmail, errMultipleAccountsForEmail => $errMultipleAccountsForEmail, - errResetForbidden => $errResetForbidden, - password_recovery => 1, - email => HTML::Entities::encode($email), - username => $username + errResetForbidden => $errResetForbidden, + password_recovery => 1, + email => HTML::Entities::encode($email), + username => $username ); - } - elsif ( SendPasswordRecoveryEmail( $borrower, $email ) ) { # generate uuid and send recovery email + } elsif ( SendPasswordRecoveryEmail( $borrower, $email ) ) { # generate uuid and send recovery email $template->param( mail_sent => 1, email => $email ); - } - else { # if it doesn't work.... + } else { # if it doesn't work.... $template->param( hasError => 1, password_recovery => 1, sendmailError => 1 ); } -} -elsif ( $op eq 'cud-reset_password' ) { +} elsif ( $op eq 'cud-reset_password' ) { ( $borrower_number, $username ) = GetValidLinkInfo($uniqueKey); my $error; - my $min_password_length = C4::Context->preference('minPasswordLength'); + my $min_password_length = C4::Context->preference('minPasswordLength'); my $require_strong_password = C4::Context->preference('RequireStrongPassword'); if ( not $borrower_number ) { $error = 'errLinkNotValid'; @@ -160,43 +162,39 @@ elsif ( $op eq 'cud-reset_password' ) { $error = 'errPassNotMatch'; } else { my $borrower = Koha::Patrons->find($borrower_number); - $min_password_length = $borrower->category->effective_min_password_length; + $min_password_length = $borrower->category->effective_min_password_length; $require_strong_password = $borrower->category->effective_require_strong_password; try { - $borrower->set_password({ password => $password, action => 'RESET PASS' }); + $borrower->set_password( { password => $password, action => 'RESET PASS' } ); CompletePasswordRecovery($uniqueKey); $template->param( password_reset_done => 1, username => $username ); - } - catch { + } catch { if ( $_->isa('Koha::Exceptions::Password::TooShort') ) { $error = 'password_too_short'; - } - elsif ( $_->isa('Koha::Exceptions::Password::WhitespaceCharacters') ) { + } elsif ( $_->isa('Koha::Exceptions::Password::WhitespaceCharacters') ) { $error = 'password_has_whitespaces'; - } - elsif ( $_->isa('Koha::Exceptions::Password::TooWeak') ) { + } elsif ( $_->isa('Koha::Exceptions::Password::TooWeak') ) { $error = 'password_too_weak'; } }; } - if ( $error ) { + if ($error) { $template->param( - new_password => 1, - email => $email, - uniqueKey => $uniqueKey, - hasError => 1, - $error => 1, - minPasswordLength => $min_password_length, + new_password => 1, + email => $email, + uniqueKey => $uniqueKey, + hasError => 1, + $error => 1, + minPasswordLength => $min_password_length, RequireStrongPassword => $require_strong_password ); } -} -elsif ($uniqueKey) { #reset password form - #check if the link is valid +} elsif ($uniqueKey) { #reset password form + #check if the link is valid ( $borrower_number, $username ) = GetValidLinkInfo($uniqueKey); if ( !$borrower_number ) { @@ -206,17 +204,16 @@ elsif ($uniqueKey) { #reset password form my $borrower = Koha::Patrons->find($borrower_number); $template->param( - new_password => 1, - email => $email, - uniqueKey => $uniqueKey, - username => $username, - errLinkNotValid => $errLinkNotValid, - hasError => ( $errLinkNotValid ? 1 : 0 ), - minPasswordLength => $borrower ? $borrower->category->effective_min_password_length : undef, + new_password => 1, + email => $email, + uniqueKey => $uniqueKey, + username => $username, + errLinkNotValid => $errLinkNotValid, + hasError => ( $errLinkNotValid ? 1 : 0 ), + minPasswordLength => $borrower ? $borrower->category->effective_min_password_length : undef, RequireStrongPassword => $borrower ? $borrower->category->effective_require_strong_password : undef, ); -} -else { #password recovery form (to send email) +} else { #password recovery form (to send email) $template->param( password_recovery => 1 ); } diff --git a/opac/opac-patron-consent.pl b/opac/opac-patron-consent.pl index 565417d6fa..80f47faaa8 100755 --- a/opac/opac-patron-consent.pl +++ b/opac/opac-patron-consent.pl @@ -20,21 +20,23 @@ use Modern::Perl; use CGI qw/-utf8/; -use C4::Auth qw( get_template_and_user ); -use C4::Output qw( output_html_with_http_headers ); +use C4::Auth qw( get_template_and_user ); +use C4::Output qw( output_html_with_http_headers ); use Koha::DateUtils qw( dt_from_string ); use Koha::Exceptions::Patron; use Koha::Patrons; my $query = CGI->new; -my $op = $query->param('op') // q{}; -my $vars = $query->Vars; +my $op = $query->param('op') // q{}; +my $vars = $query->Vars; -my ( $template, $borrowernumber, $cookie ) = get_template_and_user({ - template_name => "opac-patron-consent.tt", - query => $query, - type => "opac", -}); +my ( $template, $borrowernumber, $cookie ) = get_template_and_user( + { + template_name => "opac-patron-consent.tt", + query => $query, + type => "opac", + } +); my $patron = Koha::Patrons->find($borrowernumber) or Koha::Exceptions::Patron->throw("Patron id $borrowernumber not found"); @@ -42,27 +44,32 @@ my $patron = Koha::Patrons->find($borrowernumber) # Get consent types and values my @consents; my $consent_types = Koha::Patron::Consents->available_types; -foreach my $consent_type ( sort keys %$consent_types) { +foreach my $consent_type ( sort keys %$consent_types ) { push @consents, $patron->consent($consent_type); } # Handle saves here my $needs_redirect; -foreach my $consent ( @consents ) { - my $check = $vars->{ "check_".$consent->type }; +foreach my $consent (@consents) { + my $check = $vars->{ "check_" . $consent->type }; next if !defined($check); # no choice made $needs_redirect = 1 - if $consent->type eq q/GDPR_PROCESSING/ && !$check && C4::Context->preference('PrivacyPolicyConsent') eq 'Enforced'; + if $consent->type eq q/GDPR_PROCESSING/ + && !$check + && C4::Context->preference('PrivacyPolicyConsent') eq 'Enforced'; next if $consent->given_on && $check || $consent->refused_on && !$check; - # No update if no consent change - $consent->set({ - given_on => $check ? dt_from_string() : undef, - refused_on => $check ? undef : dt_from_string(), - })->store; + + # No update if no consent change + $consent->set( + { + given_on => $check ? dt_from_string() : undef, + refused_on => $check ? undef : dt_from_string(), + } + )->store; } # If user refused GDPR consent and we enforce GDPR, logout (when saving) -if( $needs_redirect ) { +if ($needs_redirect) { print $query->redirect('/cgi-bin/koha/opac-main.pl?logout.x=1'); exit; } diff --git a/opac/opac-patron-image.pl b/opac/opac-patron-image.pl index dccba229eb..4a2428a318 100755 --- a/opac/opac-patron-image.pl +++ b/opac/opac-patron-image.pl @@ -21,32 +21,32 @@ use Modern::Perl; use C4::Members; use CGI qw ( -utf8 ); -use CGI::Cookie; # need to check cookies before having CGI parse the POST request +use CGI::Cookie; # need to check cookies before having CGI parse the POST request use C4::Auth qw( check_cookie_auth ); use Koha::Patron::Images; my $query = CGI->new; -unless (C4::Context->preference('OPACpatronimages')) { - print $query->header(status => '403 Forbidden - displaying patron images in the OPAC not enabled'); +unless ( C4::Context->preference('OPACpatronimages') ) { + print $query->header( status => '403 Forbidden - displaying patron images in the OPAC not enabled' ); exit; } my ($auth_status) = check_cookie_auth( $query->cookie('CGISESSID') ); -if( $auth_status ne 'ok' ) { +if ( $auth_status ne 'ok' ) { print CGI::header( '-status' => '401' ); exit 0; } -my $userenv = C4::Context->userenv; +my $userenv = C4::Context->userenv; my $patron_image = $userenv ? Koha::Patron::Images->find( $userenv->{number} ) : undef; if ($patron_image) { print $query->header( -type => $patron_image->mimetype, -Content_Length => length( $patron_image->imagefile ) - ), - $patron_image->imagefile; + ), + $patron_image->imagefile; } else { - print $query->header(status => '404 patron image not found'); + print $query->header( status => '404 patron image not found' ); } diff --git a/opac/opac-privacy.pl b/opac/opac-privacy.pl index 1b4e41ac30..62b9b5dc7a 100755 --- a/opac/opac-privacy.pl +++ b/opac/opac-privacy.pl @@ -27,44 +27,49 @@ use Koha::Patrons; my $query = CGI->new; # if OPACPrivacy is disabled, leave immediately -if ( ! C4::Context->preference('OPACPrivacy') || ! C4::Context->preference('opacreadinghistory') ) { +if ( !C4::Context->preference('OPACPrivacy') || !C4::Context->preference('opacreadinghistory') ) { print $query->redirect("/cgi-bin/koha/errors/404.pl"); exit; } my ( $template, $borrowernumber, $cookie ) = get_template_and_user( { - template_name => "opac-privacy.tt", - query => $query, - type => "opac", + template_name => "opac-privacy.tt", + query => $query, + type => "opac", } ); -my $op = $query->param("op"); -my $privacy = $query->param("privacy"); +my $op = $query->param("op"); +my $privacy = $query->param("privacy"); my $privacy_guarantor_checkouts = $query->param("privacy_guarantor_checkouts"); my $privacy_guarantor_fines = $query->param("privacy_guarantor_fines"); -my $patron = Koha::Patrons->find( $borrowernumber ); +my $patron = Koha::Patrons->find($borrowernumber); if ( $op eq "cud-update_privacy" ) { - if ( $patron ) { - $patron->set({ - privacy => $privacy, - privacy_guarantor_checkouts => defined $privacy_guarantor_checkouts?$privacy_guarantor_checkouts:$patron->privacy_guarantor_checkouts, - privacy_guarantor_fines => defined $privacy_guarantor_fines?$privacy_guarantor_fines:$patron->privacy_guarantor_fines, - })->store; + if ($patron) { + $patron->set( + { + privacy => $privacy, + privacy_guarantor_checkouts => defined $privacy_guarantor_checkouts + ? $privacy_guarantor_checkouts + : $patron->privacy_guarantor_checkouts, + privacy_guarantor_fines => defined $privacy_guarantor_fines + ? $privacy_guarantor_fines + : $patron->privacy_guarantor_fines, + } + )->store; $template->param( 'privacy_updated' => 1 ); } -} -elsif ( $op eq "cud-delete_record" ) { +} elsif ( $op eq "cud-delete_record" ) { my $holds = $query->param('holds'); my $checkouts = $query->param('checkouts'); my $all = $query->param('all'); $template->param( delete_all_quested => 1 ) - if $all; + if $all; if ( $all or $checkouts ) { diff --git a/opac/opac-ratings.pl b/opac/opac-ratings.pl index 5d78f023fa..5b7b25fce2 100755 --- a/opac/opac-ratings.pl +++ b/opac/opac-ratings.pl @@ -36,7 +36,7 @@ use Koha::Ratings; my $query = CGI->new(); # auth required to add ratings -my ($userid, $cookie, $sessionID) = checkauth( $query, 0, {}, 'opac' ); +my ( $userid, $cookie, $sessionID ) = checkauth( $query, 0, {}, 'opac' ); my $loggedinuser = C4::Context->userenv->{'number'}; my $op = $query->param('op') || q{}; @@ -46,21 +46,19 @@ my $rating_value = $query->param('rating'); # If JS is disabled and a user click on "Rate me" without selecting a rate unless ( $biblionumber and $rating_value ) { - print $query->redirect( - "/cgi-bin/koha/opac-detail.pl?biblionumber=$biblionumber"); + print $query->redirect("/cgi-bin/koha/opac-detail.pl?biblionumber=$biblionumber"); exit; } if ( $op eq 'cud-add' ) { if ( !$rating_old_value ) { - my $rating = Koha::Rating->new( { biblionumber => $biblionumber, borrowernumber => $loggedinuser, rating_value => $rating_value, }); + my $rating = Koha::Rating->new( + { biblionumber => $biblionumber, borrowernumber => $loggedinuser, rating_value => $rating_value, } ); $rating->store if $rating; - } - else { - my $rating = Koha::Ratings->find( { biblionumber => $biblionumber, borrowernumber => $loggedinuser }); + } else { + my $rating = Koha::Ratings->find( { biblionumber => $biblionumber, borrowernumber => $loggedinuser } ); $rating->rating_value($rating_value)->store if $rating; } } -print $query->redirect( - "/cgi-bin/koha/opac-detail.pl?biblionumber=$biblionumber"); +print $query->redirect("/cgi-bin/koha/opac-detail.pl?biblionumber=$biblionumber"); diff --git a/opac/opac-readingrecord.pl b/opac/opac-readingrecord.pl index a671ca0f01..c08a8740e0 100755 --- a/opac/opac-readingrecord.pl +++ b/opac/opac-readingrecord.pl @@ -15,7 +15,6 @@ # You should have received a copy of the GNU General Public License # along with Koha; if not, see . - use Modern::Perl; use CGI qw ( -utf8 ); @@ -33,40 +32,35 @@ use Koha::ItemTypes; my $query = CGI->new; # if opacreadinghistory is disabled, leave immediately -if ( ! C4::Context->preference('opacreadinghistory') ) { +if ( !C4::Context->preference('opacreadinghistory') ) { print $query->redirect("/cgi-bin/koha/errors/404.pl"); exit; } my ( $template, $borrowernumber, $cookie ) = get_template_and_user( { - template_name => "opac-readingrecord.tt", - query => $query, - type => "opac", + template_name => "opac-readingrecord.tt", + query => $query, + type => "opac", } ); -my $patron = Koha::Patrons->find( $borrowernumber ); -my @itemtypes = Koha::ItemTypes->search_with_localization->as_list; -my %item_types = map { - $_->itemtype => $_ -} @itemtypes; -$template->param(item_types => \%item_types); +my $patron = Koha::Patrons->find($borrowernumber); +my @itemtypes = Koha::ItemTypes->search_with_localization->as_list; +my %item_types = map { $_->itemtype => $_ } @itemtypes; +$template->param( item_types => \%item_types ); # get the record my $order = $query->param('order') || ''; if ( $order eq 'title' ) { $template->param( orderbytitle => 1 ); -} -elsif ( $order eq 'author' ) { +} elsif ( $order eq 'author' ) { $template->param( orderbyauthor => 1 ); -} -else { +} else { $order = "date_due desc"; $template->param( orderbydate => 1 ); } - my $limit = $query->param('limit'); $limit //= ''; $limit = ( $limit eq 'full' ) ? 0 : 50; @@ -93,20 +87,20 @@ my $old_checkouts = [ )->as_list ]; -if (C4::Context->preference('BakerTaylorEnabled')) { - $template->param( - JacketImages=>1, - BakerTaylorEnabled => 1, - BakerTaylorImageURL => &image_url(), - BakerTaylorLinkURL => &link_url(), - BakerTaylorBookstoreURL => C4::Context->preference('BakerTaylorBookstoreURL'), - ); +if ( C4::Context->preference('BakerTaylorEnabled') ) { + $template->param( + JacketImages => 1, + BakerTaylorEnabled => 1, + BakerTaylorImageURL => &image_url(), + BakerTaylorLinkURL => &link_url(), + BakerTaylorBookstoreURL => C4::Context->preference('BakerTaylorBookstoreURL'), + ); } -for(qw(AmazonCoverImages GoogleJackets)) { # BakerTaylorEnabled handled above - C4::Context->preference($_) or next; - $template->param($_=>1); - $template->param(JacketImages=>1); +for (qw(AmazonCoverImages GoogleJackets)) { # BakerTaylorEnabled handled above + C4::Context->preference($_) or next; + $template->param( $_ => 1 ); + $template->param( JacketImages => 1 ); } my $saving_display = C4::Context->preference('OPACShowSavings'); @@ -115,8 +109,8 @@ if ( $saving_display =~ /checkouthistory/ ) { } $template->param( - checkouts => $checkouts, - old_checkouts => $old_checkouts, + checkouts => $checkouts, + old_checkouts => $old_checkouts, limit => $limit, readingrecview => 1, ); diff --git a/opac/opac-recall.pl b/opac/opac-recall.pl index eed014cbf5..4076e04d63 100755 --- a/opac/opac-recall.pl +++ b/opac/opac-recall.pl @@ -18,122 +18,134 @@ # along with Koha; if not, see . use Modern::Perl; -use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use C4::Context; my $query = CGI->new; my ( $template, $borrowernumber, $cookie ) = get_template_and_user( { - template_name => "opac-recall.tt", - query => $query, - type => "opac", + template_name => "opac-recall.tt", + query => $query, + type => "opac", } ); -my $op = $query->param('op') || ''; +my $op = $query->param('op') || ''; my $biblionumber = $query->param('biblionumber'); -my $biblio = Koha::Biblios->find( $biblionumber ); +my $biblio = Koha::Biblios->find($biblionumber); if ( C4::Context->preference('UseRecalls') ) { - my $patron = Koha::Patrons->find( $borrowernumber ); + my $patron = Koha::Patrons->find($borrowernumber); my $error; - unless ( $biblio->can_be_recalled({ patron => $patron }) ) { $error = 'unavailable'; } + unless ( $biblio->can_be_recalled( { patron => $patron } ) ) { $error = 'unavailable'; } - my $items = Koha::Items->search({ biblionumber => $biblionumber })->as_list; + my $items = Koha::Items->search( { biblionumber => $biblionumber } )->as_list; # check if already recalled - my $recalled = $biblio->recalls->filter_by_current->search({ patron_id => $borrowernumber })->count; + my $recalled = $biblio->recalls->filter_by_current->search( { patron_id => $borrowernumber } )->count; if ( defined $recalled and $recalled > 0 ) { - my $recalls_per_record = Koha::CirculationRules->get_effective_rule({ - categorycode => $patron->categorycode, - branchcode => undef, - itemtype => undef, - rule_name => 'recalls_per_record' - }); - if ( defined $recalls_per_record and $recalls_per_record->rule_value and $recalled >= $recalls_per_record->rule_value ){ + my $recalls_per_record = Koha::CirculationRules->get_effective_rule( + { + categorycode => $patron->categorycode, + branchcode => undef, + itemtype => undef, + rule_name => 'recalls_per_record' + } + ); + if ( defined $recalls_per_record + and $recalls_per_record->rule_value + and $recalled >= $recalls_per_record->rule_value ) + { $error = 'duplicate'; } } # submitting recall request - if ($op eq 'cud-request'){ + if ( $op eq 'cud-request' ) { + + if ( defined $error and $error eq 'unavailable' ) { - if ( defined $error and $error eq 'unavailable' ){ # no items available for recall print $query->redirect("/cgi-bin/koha/opac-recall.pl?biblionumber=$biblionumber&error=unavailable"); - } elsif ( !defined $error ){ + } elsif ( !defined $error ) { + # can recall - my $level = $query->param('type'); - my $pickuploc = $query->param('pickup'); - my $expdate = $query->param('expirationdate'); + my $level = $query->param('type'); + my $pickuploc = $query->param('pickup'); + my $expdate = $query->param('expirationdate'); my $itemnumber = $query->param('itemnumber'); my ( $recall, $due_interval, $due_date ); if ( $level eq 'itemlevel' and defined $itemnumber ) { - my $item = Koha::Items->find( $itemnumber ); - if ( $item->can_be_recalled({ patron => $patron }) ) { - ( $recall, $due_interval, $due_date ) = Koha::Recalls->add_recall({ - patron => $patron, - biblio => $biblio, - branchcode => $pickuploc, - item => $item, - expirationdate => $expdate, - interface => 'OPAC', - }); + my $item = Koha::Items->find($itemnumber); + if ( $item->can_be_recalled( { patron => $patron } ) ) { + ( $recall, $due_interval, $due_date ) = Koha::Recalls->add_recall( + { + patron => $patron, + biblio => $biblio, + branchcode => $pickuploc, + item => $item, + expirationdate => $expdate, + interface => 'OPAC', + } + ); } else { $error = 'cannot'; } } else { - if ( $biblio->can_be_recalled({ patron => $patron }) ) { - ( $recall, $due_interval, $due_date ) = Koha::Recalls->add_recall({ - patron => $patron, - biblio => $biblio, - branchcode => $pickuploc, - expirationdate => $expdate, - interface => 'OPAC', - }); + if ( $biblio->can_be_recalled( { patron => $patron } ) ) { + ( $recall, $due_interval, $due_date ) = Koha::Recalls->add_recall( + { + patron => $patron, + biblio => $biblio, + branchcode => $pickuploc, + expirationdate => $expdate, + interface => 'OPAC', + } + ); } else { $error = 'cannot'; } } if ( defined $recall ) { $template->param( - success => 1, + success => 1, due_interval => $due_interval, - due_date => $due_date, + due_date => $due_date, ); } else { $error = 'failed'; } } - } elsif ($op eq 'cud-cancel'){ + } elsif ( $op eq 'cud-cancel' ) { my $recall_id = $query->param('recall_id'); - Koha::Recalls->find( $recall_id )->set_cancelled; + Koha::Recalls->find($recall_id)->set_cancelled; print $query->redirect('/cgi-bin/koha/opac-user.pl'); } - my $branches = Koha::Libraries->search(); + my $branches = Koha::Libraries->search(); my $single_branch_mode = $branches->count == 1; $template->param( - biblio => $biblio, - error => $error, - items => $items, + biblio => $biblio, + error => $error, + items => $items, single_branch_mode => $single_branch_mode, - branches => $branches, + branches => $branches, ); } else { + # UseRecalls disabled $template->param( nosyspref => 1, - biblio => $biblio, + biblio => $biblio, ); } diff --git a/opac/opac-recalls.pl b/opac/opac-recalls.pl index 8f094a2176..3ec6a3abd1 100755 --- a/opac/opac-recalls.pl +++ b/opac/opac-recalls.pl @@ -17,25 +17,25 @@ # along with Koha; if not, see . use Modern::Perl; -use CGI qw ( -utf8 ); -use Encode qw( encode ); -use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); +use Encode qw( encode ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use Koha::Recalls; my $input = CGI->new; my ( $template, $borrowernumber, $cookie ) = get_template_and_user( - { - template_name => "opac-recalls.tt", - query => $input, - type => "opac", - } + { + template_name => "opac-recalls.tt", + query => $input, + type => "opac", + } ); -my $recalls = Koha::Recalls->search({ patron_id => $borrowernumber }, { order_by => { -desc => 'created_date' } }); +my $recalls = Koha::Recalls->search( { patron_id => $borrowernumber }, { order_by => { -desc => 'created_date' } } ); $template->param( - RECALLS => $recalls, - recallsview => 1 + RECALLS => $recalls, + recallsview => 1 ); output_html_with_http_headers $input, $cookie, $template->output, undef, { force_no_caching => 1 }; diff --git a/opac/opac-registration-verify.pl b/opac/opac-registration-verify.pl index d3ae183384..a05c2d16a3 100755 --- a/opac/opac-registration-verify.pl +++ b/opac/opac-registration-verify.pl @@ -22,7 +22,7 @@ use Try::Tiny; use C4::Auth qw( get_template_and_user ); use C4::Context; -use C4::Output qw( output_html_with_http_headers ); +use C4::Output qw( output_html_with_http_headers ); use C4::Letters qw( GetPreparedLetter EnqueueLetter SendQueuedMessages ); use C4::Members; use C4::Members::Messaging qw( SetMessagingPreferencesFromDefaults ); @@ -42,7 +42,7 @@ unless ( C4::Context->preference('PatronSelfRegistration') ) { } my $token = $cgi->param('token'); -my $op = $cgi->param('op'); +my $op = $cgi->param('op'); my $confirmed; if ( $op && $op eq 'cud-confirmed' ) { $confirmed = 1; @@ -74,12 +74,12 @@ if ( $rego_found } ); $template->param( "token" => $token ); -} -elsif ( $rego_found +} elsif ( $rego_found and $confirmed ) { my $patron_attrs = $m->unblessed; - $patron_attrs->{password} ||= Koha::AuthUtils::generate_password(Koha::Patron::Categories->find($patron_attrs->{categorycode})); + $patron_attrs->{password} ||= + Koha::AuthUtils::generate_password( Koha::Patron::Categories->find( $patron_attrs->{categorycode} ) ); my $consent_dt = delete $patron_attrs->{gdpr_proc_consent}; $patron_attrs->{categorycode} ||= C4::Context->preference('PatronSelfRegistrationDefaultCategory'); delete $patron_attrs->{timestamp}; @@ -89,8 +89,10 @@ elsif ( $rego_found my $patron; try { - $patron = Koha::Patron->new( $patron_attrs )->store; - Koha::Patron::Consent->new({ borrowernumber => $patron->borrowernumber, type => 'GDPR_PROCESSING', given_on => $consent_dt })->store if $patron && $consent_dt; + $patron = Koha::Patron->new($patron_attrs)->store; + Koha::Patron::Consent->new( + { borrowernumber => $patron->borrowernumber, type => 'GDPR_PROCESSING', given_on => $consent_dt } )->store + if $patron && $consent_dt; C4::Members::Messaging::SetMessagingPreferencesFromDefaults( { borrowernumber => $patron->borrowernumber, categorycode => $patron->categorycode } ); } catch { @@ -99,9 +101,9 @@ elsif ( $rego_found }; if ($patron) { - if( $m->extended_attributes ){ - $m->borrowernumber( $patron->borrowernumber); - $m->changed_fields(['extended_attributes']); + if ( $m->extended_attributes ) { + $m->borrowernumber( $patron->borrowernumber ); + $m->changed_fields( ['extended_attributes'] ); $m->approve(); } else { $m->delete(); @@ -117,12 +119,14 @@ elsif ( $rego_found $template->param( "confirmed" => 1 ); $template->param( password_cleartext => $patron->plain_text_password ); - $template->param( borrower => $patron ); + $template->param( borrower => $patron ); # If 'AutoEmailNewUser' syspref is on, email user their account details from the 'notice' that matches the user's branchcode. if ( C4::Context->preference("AutoEmailNewUser") ) { + # Look up correct email address taking EmailFieldPrimary into account my $emailaddr = $patron->notice_email_address; + # if we manage to find a valid email address, send notice if ($emailaddr) { eval { @@ -157,24 +161,26 @@ elsif ( $rego_found $patron->notify_library_of_registration($notify_library); } - $template->param( - PatronSelfRegistrationAdditionalInstructions => - C4::Context->preference( - 'PatronSelfRegistrationAdditionalInstructions') - ); + $template->param( PatronSelfRegistrationAdditionalInstructions => + C4::Context->preference('PatronSelfRegistrationAdditionalInstructions') ); - my ($theme, $news_lang, $availablethemes) = C4::Templates::themelanguage(C4::Context->config('opachtdocs'),'opac-registration-confirmation.tt','opac',$cgi); + my ( $theme, $news_lang, $availablethemes ) = C4::Templates::themelanguage( + C4::Context->config('opachtdocs'), 'opac-registration-confirmation.tt', + 'opac', $cgi + ); $template->param( news_lang => $news_lang ); } } -if( !$template ) { # Missing token, patron exception, etc. - ( $template, $borrowernumber, $cookie ) = get_template_and_user({ - template_name => "opac-registration-invalid.tt", - type => "opac", - query => $cgi, - authnotrequired => C4::Context->preference("OpacPublic") ? 1 : 0, - }); +if ( !$template ) { # Missing token, patron exception, etc. + ( $template, $borrowernumber, $cookie ) = get_template_and_user( + { + template_name => "opac-registration-invalid.tt", + type => "opac", + query => $cgi, + authnotrequired => C4::Context->preference("OpacPublic") ? 1 : 0, + } + ); $template->param( error_type => $error_type, error_info => $error_info ); } diff --git a/opac/opac-renew.pl b/opac/opac-renew.pl index cbee9c7a44..2e4c9467ea 100755 --- a/opac/opac-renew.pl +++ b/opac/opac-renew.pl @@ -20,27 +20,26 @@ # You should have received a copy of the GNU General Public License # along with Koha; if not, see . - use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Circulation qw( CanBookBeRenewed AddRenewal ); -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Context; use C4::Members; use Koha::Items; use Koha::Patrons; my $query = CGI->new; -my $op = $query->param('op') || q{}; +my $op = $query->param('op') || q{}; die "op must be set" unless $op eq 'cud-renew'; my ( $template, $borrowernumber, $cookie ) = get_template_and_user( - { - template_name => "opac-user.tt", - query => $query, - type => "opac", - } + { + template_name => "opac-user.tt", + query => $query, + type => "opac", + } ); my @issues = $query->multi_param('issue'); @@ -49,25 +48,17 @@ my $opacrenew = C4::Context->preference("OpacRenewalAllowed"); my $errorstring = q{}; my $renewed = q{}; -my $patron = Koha::Patrons->find( $borrowernumber ); +my $patron = Koha::Patrons->find($borrowernumber); if ( $patron->category->effective_BlockExpiredPatronOpacActions_contains('renew') && $patron->is_expired ) { $errorstring = 'card_expired'; -} -else { +} else { my @renewed; - my $issues = Koha::Checkouts->search( - { - issue_id => { -in => \@issues } - }, { - prefetch => 'item' - } - ); - while( my $issue = $issues->next) { - my ( $status, $error ) = - CanBookBeRenewed( $patron, $issue ); + my $issues = Koha::Checkouts->search( { issue_id => { -in => \@issues } }, { prefetch => 'item' } ); + while ( my $issue = $issues->next ) { + my ( $status, $error ) = CanBookBeRenewed( $patron, $issue ); if ( $status == 1 && $opacrenew == 1 ) { AddRenewal( { @@ -77,8 +68,7 @@ else { } ); push( @renewed, $issue->itemnumber ); - } - else { + } else { $errorstring .= $error . "|"; } } diff --git a/opac/opac-reportproblem.pl b/opac/opac-reportproblem.pl index f3842482af..7478224099 100755 --- a/opac/opac-reportproblem.pl +++ b/opac/opac-reportproblem.pl @@ -18,10 +18,10 @@ # along with Koha; if not, see . use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use Try::Tiny qw( catch try ); -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use C4::Letters; use Koha::ProblemReport; @@ -48,11 +48,11 @@ if ( !C4::Context->preference('OPACReportProblem') print $input->redirect("/cgi-bin/koha/errors/404.pl"); } -my $referer = Koha::Util::Navigation::local_referer($input ); +my $referer = Koha::Util::Navigation::local_referer($input); $referer = Encode::decode_utf8 uri_unescape $referer, -my $patron = Koha::Patrons->find($borrowernumber); -my $library = $patron->library; + my $patron = Koha::Patrons->find($borrowernumber); +my $library = $patron->library; my $username = $patron->userid; my @messages; @@ -65,8 +65,8 @@ $template->param( my $op = $input->param('op') || ''; if ( $op eq 'cud-addreport' ) { - my $subject = $input->param('subject'); - my $message = $input->param('message'); + my $subject = $input->param('subject'); + my $message = $input->param('message'); my $problempage = $input->param('problempage'); $problempage = Encode::decode_utf8 uri_unescape $problempage; my $recipient = $input->param('recipient') || 'admin'; @@ -89,34 +89,39 @@ if ( $op eq 'cud-addreport' ) { # send notice to library my $letter = C4::Letters::GetPreparedLetter( - module => 'members', + module => 'members', letter_code => 'PROBLEM_REPORT', - branchcode => $problem->branchcode, - tables => { - 'problem_reports', $problem->reportid - } + branchcode => $problem->branchcode, + tables => { 'problem_reports', $problem->reportid } ); - my $transport = 'email'; + my $transport = 'email'; my $reply_address = $patron->email || $patron->emailpro || $patron->B_email; - if ( $recipient eq 'library' and defined($library->inbound_email_address) and $library->inbound_email_address ne C4::Context->preference('KohaAdminEmailAddress') ) { + if ( $recipient eq 'library' + and defined( $library->inbound_email_address ) + and $library->inbound_email_address ne C4::Context->preference('KohaAdminEmailAddress') ) + { # the problem report is intended for a librarian and will be received at a library email address - C4::Letters::EnqueueLetter({ - letter => $letter, - borrowernumber => $borrowernumber, - message_transport_type => $transport, - to_address => $library->inbound_email_address, - reply_address => $reply_address, - }); + C4::Letters::EnqueueLetter( + { + letter => $letter, + borrowernumber => $borrowernumber, + message_transport_type => $transport, + to_address => $library->inbound_email_address, + reply_address => $reply_address, + } + ); } else { - C4::Letters::EnqueueLetter({ - letter => $letter, - borrowernumber => $borrowernumber, - message_transport_type => $transport, - to_address => C4::Context->preference('KohaAdminEmailAddress'), - reply_address => $reply_address, - }); + C4::Letters::EnqueueLetter( + { + letter => $letter, + borrowernumber => $borrowernumber, + message_transport_type => $transport, + to_address => C4::Context->preference('KohaAdminEmailAddress'), + reply_address => $reply_address, + } + ); } push @messages, { @@ -129,8 +134,7 @@ if ( $op eq 'cud-addreport' ) { ); } ); - } - catch { + } catch { warn "Something wrong happened when sending the report problem: $_"; push @messages, { type => 'error', diff --git a/opac/opac-request-article.pl b/opac/opac-request-article.pl index d9bd885eed..1d0bf8aded 100755 --- a/opac/opac-request-article.pl +++ b/opac/opac-request-article.pl @@ -21,7 +21,7 @@ use Modern::Perl; use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use Koha::Biblios; @@ -35,16 +35,16 @@ my $cgi = CGI->new; my ( $template, $borrowernumber, $cookie ) = get_template_and_user( { - template_name => "opac-request-article.tt", - query => $cgi, - type => "opac", + template_name => "opac-request-article.tt", + query => $cgi, + type => "opac", } ); -my $op = $cgi->param('op') || q{}; +my $op = $cgi->param('op') || q{}; my $biblionumber = $cgi->param('biblionumber'); -my $biblio = Koha::Biblios->find($biblionumber); -if( !$biblio ) { +my $biblio = Koha::Biblios->find($biblionumber); +if ( !$biblio ) { print $cgi->redirect("/cgi-bin/koha/errors/404.pl"); exit; } @@ -64,7 +64,6 @@ if ( $op eq 'cud-create' ) { my $format = $cgi->param('format') || undef; my $toc_request = $cgi->param('toc_request'); - my $success; try { @@ -89,52 +88,46 @@ if ( $op eq 'cud-create' ) { $success = 1; } catch { if ( blessed $_ and $_->isa('Koha::Exceptions::ArticleRequest::LimitReached') ) { - $template->param( - error_message => 'article_request_limit_reached' - ); - } - else { + $template->param( error_message => 'article_request_limit_reached' ); + } else { Koha::Logger->get->debug("Unhandled exception when placing an article request ($_)"); - $template->param( - error_message => 'article_request_unhandled_exception' - ); + $template->param( error_message => 'article_request_unhandled_exception' ); } }; - if ( $success ) { + if ($success) { print $cgi->redirect("/cgi-bin/koha/opac-user.pl?opac-user-article-requests=1"); exit; } -# Should we redirect? -} -elsif ( !$op && C4::Context->preference('ArticleRequestsOpacHostRedirection') ) { - # Conditions: no items, host item entry (MARC21 773) - my ( $host, $pageinfo ) = $biblio->get_marc_host( { no_items => 1 } ); - if ($host) { - $template->param( - pageinfo => $pageinfo, - title => $biblio->title, - author => $biblio->author - ); - $biblio = $host; - } + + # Should we redirect? +} elsif ( !$op && C4::Context->preference('ArticleRequestsOpacHostRedirection') ) { + + # Conditions: no items, host item entry (MARC21 773) + my ( $host, $pageinfo ) = $biblio->get_marc_host( { no_items => 1 } ); + if ($host) { + $template->param( + pageinfo => $pageinfo, + title => $biblio->title, + author => $biblio->author + ); + $biblio = $host; + } } my $patron = Koha::Patrons->find($borrowernumber); -if(!$patron->can_request_article) { - $template->param( - error_message => 'article_request_limit_reached' - ); +if ( !$patron->can_request_article ) { + $template->param( error_message => 'article_request_limit_reached' ); } $template->param( article_request_fee => $patron->article_request_fee ) - if $op ne 'cud-create'; + if $op ne 'cud-create'; $template->param( - biblio => $biblio, - patron => $patron, - op => $op, + biblio => $biblio, + patron => $patron, + op => $op, accepted => scalar $cgi->param('accepted'), ); diff --git a/opac/opac-reserve.pl b/opac/opac-reserve.pl index 002a7b13bf..f6e184e547 100755 --- a/opac/opac-reserve.pl +++ b/opac/opac-reserve.pl @@ -1,6 +1,5 @@ #!/usr/bin/perl - # Copyright Katipo Communications 2002 # Copyright Koha Development team 2012 # @@ -21,13 +20,13 @@ use Modern::Perl; -use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); -use C4::Koha qw( getitemtypeimagelocation getitemtypeimagesrc ); +use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); +use C4::Koha qw( getitemtypeimagelocation getitemtypeimagesrc ); use C4::Circulation qw( GetBranchItemRule ); -use C4::Reserves qw( CanItemBeReserved CanBookBeReserved AddReserve IsAvailableForItemLevelRequest GetReserveFee ); -use C4::Biblio qw( GetBiblioData GetFrameworkCode ); -use C4::Output qw( output_html_with_http_headers ); +use C4::Reserves qw( CanItemBeReserved CanBookBeReserved AddReserve IsAvailableForItemLevelRequest GetReserveFee ); +use C4::Biblio qw( GetBiblioData GetFrameworkCode ); +use C4::Output qw( output_html_with_http_headers ); use C4::Context; use C4::Members; use C4::Overdues; @@ -49,26 +48,26 @@ my $query = CGI->new; my $op = $query->param('op') // q{}; # if OPACHoldRequests (for placing holds) is disabled, leave immediately -if ( ! C4::Context->preference('OPACHoldRequests') ) { +if ( !C4::Context->preference('OPACHoldRequests') ) { print $query->redirect("/cgi-bin/koha/errors/404.pl"); exit; } my ( $template, $borrowernumber, $cookie ) = get_template_and_user( { - template_name => "opac-reserve.tt", - query => $query, - type => "opac", + template_name => "opac-reserve.tt", + query => $query, + type => "opac", } ); -my $patron = Koha::Patrons->find( $borrowernumber, { prefetch => ['categorycode'] } ); +my $patron = Koha::Patrons->find( $borrowernumber, { prefetch => ['categorycode'] } ); my $category = $patron->category; my $can_place_hold_if_available_at_pickup = C4::Context->preference('OPACHoldsIfAvailableAtPickup'); -unless ( $can_place_hold_if_available_at_pickup ) { +unless ($can_place_hold_if_available_at_pickup) { my @patron_categories = split ',', C4::Context->preference('OPACHoldsIfAvailableAtPickupExceptions'); - if ( @patron_categories ) { + if (@patron_categories) { my $categorycode = $patron->categorycode; $can_place_hold_if_available_at_pickup = grep { $_ eq $categorycode } @patron_categories; } @@ -79,12 +78,12 @@ my $itemtypes = { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search_with_l # There are two ways of calling this script, with a single biblio num # or multiple biblio nums. my $biblionumbers = $query->param('biblionumbers'); -my $reserveMode = $query->param('reserve_mode'); -if ($reserveMode && ($reserveMode eq 'single')) { +my $reserveMode = $query->param('reserve_mode'); +if ( $reserveMode && ( $reserveMode eq 'single' ) ) { my $bib = $query->param('single_bib'); $biblionumbers = "$bib/"; } -if (! $biblionumbers) { +if ( !$biblionumbers ) { $biblionumbers = $query->param('biblionumber'); } @@ -101,8 +100,9 @@ $template->param( biblionumbers => $biblionumbers ); # Each biblio number is suffixed with '/', e.g. "1/2/3/" my @biblionumbers = split /\//, $biblionumbers; if ( $#biblionumbers < 0 && $op ne 'cud-place_reserve' ) { + # TODO: New message? - $template->param(message=>1, no_biblionumber=>1); + $template->param( message => 1, no_biblionumber => 1 ); output_html_with_http_headers $query, $cookie, $template->output, undef, { force_no_caching => 1 }; exit; } @@ -112,25 +112,26 @@ if ( $#biblionumbers < 0 && $op ne 'cud-place_reserve' ) { # Here we check that the borrower can actually make reserves Stage 1. # # -my $noreserves = 0; +my $noreserves = 0; if ( $category->effective_BlockExpiredPatronOpacActions_contains('hold') ) { if ( $patron->is_expired ) { + # cannot reserve, their card has expired and the rules set mean this is not allowed $noreserves = 1; $template->param( message => 1, expired_patron => 1 ); } } -my $maxoutstanding = C4::Context->preference("maxoutstanding"); +my $maxoutstanding = C4::Context->preference("maxoutstanding"); my $amountoutstanding = $patron->account->balance; -if ( $amountoutstanding && ($amountoutstanding > $maxoutstanding) ) { +if ( $amountoutstanding && ( $amountoutstanding > $maxoutstanding ) ) { my $amount = sprintf "%.02f", $amountoutstanding; $template->param( message => 1 ); $noreserves = 1; $template->param( too_much_oweing => $amount ); } -if ( $patron->gonenoaddress && ($patron->gonenoaddress == 1) ) { +if ( $patron->gonenoaddress && ( $patron->gonenoaddress == 1 ) ) { $noreserves = 1; $template->param( message => 1, @@ -138,7 +139,7 @@ if ( $patron->gonenoaddress && ($patron->gonenoaddress == 1) ) { ); } -if ( $patron->lost && ($patron->lost == 1) ) { +if ( $patron->lost && ( $patron->lost == 1 ) ) { $noreserves = 1; $template->param( message => 1, @@ -156,7 +157,7 @@ if ( $patron->is_debarred ) { ); } -my $holds = $patron->holds; +my $holds = $patron->holds; my $reserves_count = $holds->count; $template->param( RESERVES => $holds->unblessed ); if ( $maxreserves && ( $reserves_count >= $maxreserves ) ) { @@ -165,14 +166,13 @@ if ( $maxreserves && ( $reserves_count >= $maxreserves ) ) { $template->param( too_many_reserves => $holds->count ); } -if( $noreserves ){ +if ($noreserves) { output_html_with_http_headers $query, $cookie, $template->output, undef, { force_no_caching => 1 }; exit; } - # pass the pickup branch along.... -my $branch = $query->param('branch') || $patron->branchcode || C4::Context->userenv->{branch} || '' ; +my $branch = $query->param('branch') || $patron->branchcode || C4::Context->userenv->{branch} || ''; $template->param( branch => $branch ); # @@ -190,12 +190,13 @@ if ( $op eq 'cud-place_reserve' ) { # List is composed of alternating biblio/item/branch my $selectedItems = $query->param('selecteditems'); - if ($query->param('reserve_mode') eq 'single') { + if ( $query->param('reserve_mode') eq 'single' ) { + # This indicates non-JavaScript mode, so there was # only a single biblio number selected. - my $bib = $query->param('single_bib'); + my $bib = $query->param('single_bib'); my $item = $query->param("checkitem_$bib"); - if ($item eq 'any') { + if ( $item eq 'any' ) { $item = ''; } my $branch = $query->param('branch'); @@ -208,8 +209,8 @@ if ( $op eq 'cud-place_reserve' ) { # Make sure there is a biblionum/itemnum/branch triplet for each item. # The itemnum can be 'any', meaning next available. my $selectionCount = @selectedItems; - if (($selectionCount == 0) || (($selectionCount % 3) != 0)) { - $template->param(message=>1, bad_data=>1); + if ( ( $selectionCount == 0 ) || ( ( $selectionCount % 3 ) != 0 ) ) { + $template->param( message => 1, bad_data => 1 ); output_html_with_http_headers $query, $cookie, $template->output, undef, { force_no_caching => 1 }; exit; } @@ -223,22 +224,23 @@ if ( $op eq 'cud-place_reserve' ) { my $canreserve = 0; my $singleBranchMode = Koha::Libraries->search->count == 1; - if ( $singleBranchMode || ! C4::Context->preference("OPACAllowUserToChooseBranch") ) - { # single branch mode or disabled user choosing + if ( $singleBranchMode || !C4::Context->preference("OPACAllowUserToChooseBranch") ) + { # single branch mode or disabled user choosing $branch = $patron->branchcode; } # FIXME We shouldn't need to fetch the item here - my $item = $itemNum ? Koha::Items->find( $itemNum ) : undef; + my $item = $itemNum ? Koha::Items->find($itemNum) : undef; + # When choosing a specific item, the default pickup library should be dictated by the default hold policy - if ( ! C4::Context->preference("OPACAllowUserToChooseBranch") && $item ) { + if ( !C4::Context->preference("OPACAllowUserToChooseBranch") && $item ) { my $type = $item->effective_itemtype; my $reserves_control_branch = Koha::Policy::Holds->holds_control_library( $item, $patron ); my $rule = GetBranchItemRule( $reserves_control_branch, $type ); if ( $rule->{hold_fulfillment_policy} eq 'any' || $rule->{hold_fulfillment_policy} eq 'patrongroup' ) { $branch = $patron->branchcode; - } elsif ( $rule->{hold_fulfillment_policy} eq 'holdgroup' ){ + } elsif ( $rule->{hold_fulfillment_policy} eq 'holdgroup' ) { $branch = $item->homebranch; } else { my $policy = $rule->{hold_fulfillment_policy}; @@ -247,7 +249,7 @@ if ( $op eq 'cud-place_reserve' ) { } # if we have an item, we are placing the hold on the item's bib, in case of analytics - if ( $item ) { + if ($item) { $biblioNum = $item->biblionumber; } @@ -265,19 +267,18 @@ if ( $op eq 'cud-place_reserve' ) { $itemtype = undef if $itemNum; my $biblio = Koha::Biblios->find($biblioNum); - my $rank = $biblio->holds->search( { found => [ { "!=" => "W" }, undef ] } )->count + 1; - if ( $item ) { + my $rank = $biblio->holds->search( { found => [ { "!=" => "W" }, undef ] } )->count + 1; + if ($item) { my $status = CanItemBeReserved( $patron, $item, $branch, { get_from_cache => 1 } )->{status}; - if( $status eq 'OK' ){ + if ( $status eq 'OK' ) { $canreserve = 1; } else { push @failed_holds, $status; } - } - else { + } else { my $status = CanBookBeReserved( $borrowernumber, $biblioNum, $branch, { itemtype => $itemtype } )->{status}; - if( $status eq 'OK'){ + if ( $status eq 'OK' ) { $canreserve = 1; } else { push @failed_holds, $status; @@ -286,7 +287,7 @@ if ( $op eq 'cud-place_reserve' ) { # Inserts a null into the 'itemnumber' field of 'reserves' table. $itemNum = undef; } - my $notes = $query->param('notes_'.$biblioNum)||''; + my $notes = $query->param( 'notes_' . $biblioNum ) || ''; my $item_group_id = $query->param("item_group_id_$biblioNum") || undef; if ( $maxreserves @@ -296,10 +297,13 @@ if ( $op eq 'cud-place_reserve' ) { $canreserve = 0; } - unless ( $can_place_hold_if_available_at_pickup ) { - my $items_in_this_library = Koha::Items->search({ biblionumber => $biblioNum, holdingbranch => $branch }); - my $nb_of_items_issued = $items_in_this_library->search({ 'issue.itemnumber' => { not => undef }}, { join => 'issue' })->count; - my $nb_of_items_unavailable = $items_in_this_library->search({ -or => { lost => { '!=' => 0 }, damaged => { '!=' => 0 }, } }); + unless ($can_place_hold_if_available_at_pickup) { + my $items_in_this_library = Koha::Items->search( { biblionumber => $biblioNum, holdingbranch => $branch } ); + my $nb_of_items_issued = + $items_in_this_library->search( { 'issue.itemnumber' => { not => undef } }, { join => 'issue' } ) + ->count; + my $nb_of_items_unavailable = + $items_in_this_library->search( { -or => { lost => { '!=' => 0 }, damaged => { '!=' => 0 }, } } ); if ( $items_in_this_library->count > $nb_of_items_issued + $nb_of_items_unavailable ) { $canreserve = 0; push @failed_holds, 'items_available'; @@ -324,7 +328,7 @@ if ( $op eq 'cud-place_reserve' ) { item_group_id => $item_group_id, } ); - if( $reserve_id ){ + if ($reserve_id) { ++$reserve_cnt; } else { push @failed_holds, 'not_placed'; @@ -332,7 +336,9 @@ if ( $op eq 'cud-place_reserve' ) { } } - print $query->redirect("/cgi-bin/koha/opac-user.pl?" . ( @failed_holds ? "failed_holds=" . join('|',@failed_holds) : q|| ) . "&opac-user-holds=1"); + print $query->redirect( "/cgi-bin/koha/opac-user.pl?" + . ( @failed_holds ? "failed_holds=" . join( '|', @failed_holds ) : q|| ) + . "&opac-user-holds=1" ); exit; } @@ -342,45 +348,39 @@ if ( $op eq 'cud-place_reserve' ) { # # -my %biblioDataHash; # Hash of biblionumber to biblio/biblioitems record. +my %biblioDataHash; # Hash of biblionumber to biblio/biblioitems record. foreach my $biblioNumber (@biblionumbers) { my $biblioData = GetBiblioData($biblioNumber); $biblioDataHash{$biblioNumber} = $biblioData; - my $biblio = Koha::Biblios->find( $biblioNumber ); + my $biblio = Koha::Biblios->find($biblioNumber); next unless $biblio; my $items = Koha::Items->search_ordered( [ 'me.biblionumber' => $biblioNumber, - 'me.itemnumber' => { - -in => [ - $biblio->host_items->get_column('itemnumber') - ] - } + 'me.itemnumber' => { -in => [ $biblio->host_items->get_column('itemnumber') ] } ], { prefetch => [ 'issue', 'homebranch', 'holdingbranch' ] } - )->filter_by_visible_in_opac({ patron => $patron }); + )->filter_by_visible_in_opac( { patron => $patron } ); - $biblioData->{items} = [$items->as_list]; # FIXME Potentially a lot in memory here! + $biblioData->{items} = [ $items->as_list ]; # FIXME Potentially a lot in memory here! # Compute the priority rank. $biblioData->{object} = $biblio; - my $reservecount = $biblio->holds->search({ found => [ {"!=" => "W"},undef] })->count; + my $reservecount = $biblio->holds->search( { found => [ { "!=" => "W" }, undef ] } )->count; $biblioData->{reservecount} = $reservecount; - $biblioData->{rank} = $reservecount + 1; + $biblioData->{rank} = $reservecount + 1; } - -my $requested_reserves_count = scalar( @biblionumbers ); +my $requested_reserves_count = scalar(@biblionumbers); if ( $maxreserves && ( $reserves_count + $requested_reserves_count > $maxreserves ) ) { $template->param( new_reserves_allowed => $maxreserves - $reserves_count ); } $template->param( select_item_types => 1 ); - # # # Build the template parameters that will show the info @@ -388,14 +388,14 @@ $template->param( select_item_types => 1 ); # # -my $biblioLoop = []; -my $numBibsAvailable = 0; +my $biblioLoop = []; +my $numBibsAvailable = 0; my $itemdata_enumchron = 0; -my $itemdata_ccode = 0; -my $anyholdable = 0; -my $itemLevelTypes = C4::Context->preference('item-level_itypes'); -my $pickup_locations = Koha::Libraries->search({ pickup_location => 1 }); -$template->param('item_level_itypes' => $itemLevelTypes); +my $itemdata_ccode = 0; +my $anyholdable = 0; +my $itemLevelTypes = C4::Context->preference('item-level_itypes'); +my $pickup_locations = Koha::Libraries->search( { pickup_location => 1 } ); +$template->param( 'item_level_itypes' => $itemLevelTypes ); my $patron_unblessed = $patron->unblessed; foreach my $biblioNum (@biblionumbers) { @@ -405,56 +405,57 @@ foreach my $biblioNum (@biblionumbers) { # Get relevant biblio data. my $biblioData = $biblioDataHash{$biblioNum}; - if (! $biblioData) { - $template->param(message=>1, bad_biblionumber=>$biblioNum); + if ( !$biblioData ) { + $template->param( message => 1, bad_biblionumber => $biblioNum ); output_html_with_http_headers $query, $cookie, $template->output, undef, { force_no_caching => 1 }; exit; } my @not_available_at = (); - my $biblio = $biblioData->{object}; + my $biblio = $biblioData->{object}; foreach my $library ( $pickup_locations->as_list ) { - push( @not_available_at, $library->branchcode ) unless $biblio->can_be_transferred({ to => $library }); + push( @not_available_at, $library->branchcode ) unless $biblio->can_be_transferred( { to => $library } ); } my $frameworkcode = GetFrameworkCode( $biblioData->{biblionumber} ); - $biblioLoopIter{biblionumber} = $biblioData->{biblionumber}; - $biblioLoopIter{title} = $biblioData->{title}; - $biblioLoopIter{subtitle} = $biblioData->{'subtitle'}; - $biblioLoopIter{medium} = $biblioData->{medium}; - $biblioLoopIter{part_number} = $biblioData->{part_number}; - $biblioLoopIter{part_name} = $biblioData->{part_name}; - $biblioLoopIter{author} = $biblioData->{author}; - $biblioLoopIter{rank} = $biblioData->{rank}; - $biblioLoopIter{reservecount} = $biblioData->{reservecount}; + $biblioLoopIter{biblionumber} = $biblioData->{biblionumber}; + $biblioLoopIter{title} = $biblioData->{title}; + $biblioLoopIter{subtitle} = $biblioData->{'subtitle'}; + $biblioLoopIter{medium} = $biblioData->{medium}; + $biblioLoopIter{part_number} = $biblioData->{part_number}; + $biblioLoopIter{part_name} = $biblioData->{part_name}; + $biblioLoopIter{author} = $biblioData->{author}; + $biblioLoopIter{rank} = $biblioData->{rank}; + $biblioLoopIter{reservecount} = $biblioData->{reservecount}; $biblioLoopIter{already_reserved} = $biblioData->{already_reserved}; - $biblioLoopIter{object} = $biblio; + $biblioLoopIter{object} = $biblio; - if (!$itemLevelTypes && $biblioData->{itemtype}) { - $biblioLoopIter{translated_description} = $itemtypes->{$biblioData->{itemtype}}{translated_description}; - $biblioLoopIter{imageurl} = getitemtypeimagesrc() . "/". $itemtypes->{$biblioData->{itemtype}}{imageurl}; + if ( !$itemLevelTypes && $biblioData->{itemtype} ) { + $biblioLoopIter{translated_description} = $itemtypes->{ $biblioData->{itemtype} }{translated_description}; + $biblioLoopIter{imageurl} = getitemtypeimagesrc() . "/" . $itemtypes->{ $biblioData->{itemtype} }{imageurl}; } - - $biblioLoopIter{itemLoop} = []; - my $numCopiesAvailable = 0; + my $numCopiesAvailable = 0; my $numCopiesOPACAvailable = 0; + # iterating through all items first to check if any of them available # to pass this value further inside down to IsAvailableForItemLevelRequest to # it's complicated logic to analyse. # (before this loop was inside that sub loop so it was O(n^2) ) - foreach my $item (@{$biblioData->{items}}) { + foreach my $item ( @{ $biblioData->{items} } ) { my $item_info = $item->unblessed; $item_info->{holding_branch} = $item->holding_branch; $item_info->{home_branch} = $item->home_branch; if ($itemLevelTypes) { my $itemtype = $item->itemtype; - $item_info->{'imageurl'} = getitemtypeimagelocation( 'opac', - $itemtypes->{ $itemtype->itemtype }->{'imageurl'} ); + $item_info->{'imageurl'} = getitemtypeimagelocation( + 'opac', + $itemtypes->{ $itemtype->itemtype }->{'imageurl'} + ); $item_info->{'translated_description'} = - $itemtypes->{ $itemtype->itemtype }->{translated_description}; + $itemtypes->{ $itemtype->itemtype }->{translated_description}; } # checking for holds @@ -470,8 +471,8 @@ foreach my $biblioNum (@biblionumbers) { if ( $transfer && $transfer->in_transit ) { $item_info->{transfertwhen} = $transfer->datesent; $item_info->{transfertfrom} = $transfer->frombranch; - $item_info->{transfertto} = $transfer->tobranch; - $item_info->{nocancel} = 1; + $item_info->{transfertto} = $transfer->tobranch; + $item_info->{nocancel} = 1; } # if the items belongs to a host record, show link to host record @@ -482,22 +483,25 @@ foreach my $biblioNum (@biblionumbers) { my $branch = Koha::Policy::Holds->holds_control_library( $item, $patron ); - my $policy_holdallowed = - CanItemBeReserved( $patron, $item, undef, { get_from_cache => 1 } )->{status} eq 'OK' && - IsAvailableForItemLevelRequest($item, $patron, undef); + my $policy_holdallowed = CanItemBeReserved( $patron, $item, undef, { get_from_cache => 1 } )->{status} eq 'OK' + && IsAvailableForItemLevelRequest( $item, $patron, undef ); if ($policy_holdallowed) { - my $opac_hold_policy = Koha::CirculationRules->get_opacitemholds_policy( { item => $item, patron => $patron } ); - if ( $opac_hold_policy ne 'N' ) { # If Y or F + my $opac_hold_policy = + Koha::CirculationRules->get_opacitemholds_policy( { item => $item, patron => $patron } ); + if ( $opac_hold_policy ne 'N' ) { # If Y or F $item_info->{available} = 1; $numCopiesOPACAvailable++; $biblioLoopIter{force_hold} = 1 if $opac_hold_policy eq 'F'; } $numCopiesAvailable++; - unless ( $can_place_hold_if_available_at_pickup ) { - my $items_in_this_library = Koha::Items->search({ biblionumber => $item->biblionumber, holdingbranch => $item->holdingbranch, notforloan => 0 }); - my $nb_of_items_issued = $items_in_this_library->search({ 'issue.itemnumber' => { not => undef }}, { join => 'issue' })->count; + unless ($can_place_hold_if_available_at_pickup) { + my $items_in_this_library = Koha::Items->search( + { biblionumber => $item->biblionumber, holdingbranch => $item->holdingbranch, notforloan => 0 } ); + my $nb_of_items_issued = + $items_in_this_library->search( { 'issue.itemnumber' => { not => undef } }, { join => 'issue' } ) + ->count; if ( $items_in_this_library->count > $nb_of_items_issued ) { push @not_available_at, $item->holdingbranch; } @@ -505,39 +509,41 @@ foreach my $biblioNum (@biblionumbers) { } # Show serial enumeration when needed - if ($item_info->{enumchron}) { + if ( $item_info->{enumchron} ) { $itemdata_enumchron = 1; } + # Show collection when needed - if ($item_info->{ccode}) { + if ( $item_info->{ccode} ) { $itemdata_ccode = 1; } - push @{$biblioLoopIter{itemLoop}}, $item_info; + push @{ $biblioLoopIter{itemLoop} }, $item_info; } $template->param( itemdata_enumchron => $itemdata_enumchron, itemdata_ccode => $itemdata_ccode, ); - if ($numCopiesAvailable > 0) { + if ( $numCopiesAvailable > 0 ) { $numBibsAvailable++; $biblioLoopIter{bib_available} = 1; - $biblioLoopIter{holdable} = 1; - $biblioLoopIter{itemholdable} = 1 if $numCopiesOPACAvailable; + $biblioLoopIter{holdable} = 1; + $biblioLoopIter{itemholdable} = 1 if $numCopiesOPACAvailable; } - if ($biblioLoopIter{already_reserved}) { - $biblioLoopIter{holdable} = undef; + if ( $biblioLoopIter{already_reserved} ) { + $biblioLoopIter{holdable} = undef; $biblioLoopIter{itemholdable} = undef; } if ( $biblioLoopIter{holdable} ) { @not_available_at = uniq @not_available_at; - $biblioLoopIter{not_available_at} = \@not_available_at ; + $biblioLoopIter{not_available_at} = \@not_available_at; } - unless ( $can_place_hold_if_available_at_pickup ) { + unless ($can_place_hold_if_available_at_pickup) { @not_available_at = uniq @not_available_at; - $biblioLoopIter{not_available_at} = \@not_available_at ; + $biblioLoopIter{not_available_at} = \@not_available_at; + # The record is not holdable is not available at any of the libraries if ( Koha::Libraries->search->count == @not_available_at ) { $biblioLoopIter{holdable} = 0; @@ -549,17 +555,19 @@ foreach my $biblioNum (@biblionumbers) { $biblioLoopIter{$status} = 1; if ( $biblioLoopIter{holdable} and C4::Context->preference('AllowHoldItemTypeSelection') ) { + # build the allowed item types loop my $rs = $biblio->items->search_ordered( undef, - { select => [ { distinct => 'itype' } ], + { + select => [ { distinct => 'itype' } ], as => 'item_type' } ); my @item_types = - grep { CanBookBeReserved( $borrowernumber, $biblioNum, $branch, { itemtype => $_ } )->{status} eq 'OK' } - $rs->get_column('item_type'); + grep { CanBookBeReserved( $borrowernumber, $biblioNum, $branch, { itemtype => $_ } )->{status} eq 'OK' } + $rs->get_column('item_type'); $biblioLoopIter{allowed_item_types} = \@item_types; } @@ -581,10 +589,10 @@ foreach my $biblioNum (@biblionumbers) { } )->forced_hold_level(); if ($forced_hold_level) { - $biblioLoopIter{force_hold} = 1 if $forced_hold_level eq 'item'; - $biblioLoopIter{force_hold} = 0 if $forced_hold_level eq 'item_group'; - $biblioLoopIter{itemholdable} = 0 if $forced_hold_level eq 'record'; - $biblioLoopIter{itemholdable} = 0 if $forced_hold_level eq 'item_group'; + $biblioLoopIter{force_hold} = 1 if $forced_hold_level eq 'item'; + $biblioLoopIter{force_hold} = 0 if $forced_hold_level eq 'item_group'; + $biblioLoopIter{itemholdable} = 0 if $forced_hold_level eq 'record'; + $biblioLoopIter{itemholdable} = 0 if $forced_hold_level eq 'item_group'; $biblioLoopIter{forced_hold_level} = $forced_hold_level; } @@ -596,28 +604,29 @@ foreach my $biblioNum (@biblionumbers) { $anyholdable = 1 if $biblioLoopIter{holdable}; } -unless ($pickup_locations->count) { +unless ( $pickup_locations->count ) { $numBibsAvailable = 0; - $anyholdable = 0; + $anyholdable = 0; $template->param( - message => 1, + message => 1, no_pickup_locations => 1 ); } -if ( $numBibsAvailable == 0 || $anyholdable == 0) { +if ( $numBibsAvailable == 0 || $anyholdable == 0 ) { $template->param( none_available => 1 ); } -if (scalar @biblionumbers > 1) { - $template->param( multi_hold => 1); +if ( scalar @biblionumbers > 1 ) { + $template->param( multi_hold => 1 ); } -my $show_notes=C4::Context->preference('OpacHoldNotes'); -$template->param(OpacHoldNotes=>$show_notes); +my $show_notes = C4::Context->preference('OpacHoldNotes'); +$template->param( OpacHoldNotes => $show_notes ); # display infos -$template->param(bibitemloop => $biblioLoop); +$template->param( bibitemloop => $biblioLoop ); + # can set reserve date in future if ( C4::Context->preference('AllowHoldDateInFuture') && C4::Context->preference('OPACAllowHoldDateInFuture') ) diff --git a/opac/opac-reset-password.pl b/opac/opac-reset-password.pl index 969e10f517..834bea16ec 100755 --- a/opac/opac-reset-password.pl +++ b/opac/opac-reset-password.pl @@ -51,57 +51,46 @@ if ( $op eq 'cud-update' ) { if ( $patron && $patron->password_expiration_date ) { if ( $patron->account_locked ) { $template->param( error => 'account_locked' ); - } - elsif ( $currentpassword && $newpassword && $confirmpassword ) { + } elsif ( $currentpassword && $newpassword && $confirmpassword ) { my $error; if ( C4::Auth::checkpw_hash( $currentpassword, $patron->password ) ) { if ( $newpassword ne $confirmpassword ) { $template->param( 'error' => 'passwords_mismatch' ); - } - elsif ( $currentpassword eq $newpassword ) { + } elsif ( $currentpassword eq $newpassword ) { $template->param( 'error' => 'no_change' ); - } - else { + } else { try { $patron->set_password( { password => $newpassword } ); $template->param( 'password_updated' => '1' ); $template->param( 'staff_access' => 1 ) - if $patron->has_permission( { catalogue => 1 } ); - } - catch { + if $patron->has_permission( { catalogue => 1 } ); + } catch { $error = 'password_too_short' - if $_->isa('Koha::Exceptions::Password::TooShort'); + if $_->isa('Koha::Exceptions::Password::TooShort'); $error = 'password_too_weak' - if $_->isa('Koha::Exceptions::Password::TooWeak'); + if $_->isa('Koha::Exceptions::Password::TooWeak'); $error = 'password_has_whitespaces' - if $_->isa( - 'Koha::Exceptions::Password::WhitespaceCharacters'); + if $_->isa('Koha::Exceptions::Password::WhitespaceCharacters'); $template->param( 'error' => $error ); }; } - } - else { + } else { $template->param( 'error' => 'invalid_credentials' ); - $patron->update( - { login_attempts => $patron->login_attempts + 1 } ) - if !$patron->account_locked; + $patron->update( { login_attempts => $patron->login_attempts + 1 } ) + if !$patron->account_locked; } - } - else { + } else { $template->param( 'incomplete_form' => '1' ); } - } - elsif ( !$patron ) { + } elsif ( !$patron ) { template->param( 'error' => 'invalid_credentials' ); - } - elsif ( !$patron->password_expiration_date ) { + } elsif ( !$patron->password_expiration_date ) { $template->param( 'error' => 'no_expire' ); - } - else { + } else { $template->param( 'error' => 'unknown' ); } } output_html_with_http_headers $query, $cookie, $template->output, undef, - { force_no_caching => 1 }; + { force_no_caching => 1 }; diff --git a/opac/opac-restrictedpage.pl b/opac/opac-restrictedpage.pl index b438b7f010..b5f37f33d8 100755 --- a/opac/opac-restrictedpage.pl +++ b/opac/opac-restrictedpage.pl @@ -20,15 +20,14 @@ use Modern::Perl; use CGI; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); -my $localNetwork = C4::Context->preference('RestrictedPageLocalIPs'); -my $userIP = $ENV{'REMOTE_ADDR'}; +my $localNetwork = C4::Context->preference('RestrictedPageLocalIPs'); +my $userIP = $ENV{'REMOTE_ADDR'}; my $withinNetwork = 0; -foreach my $IPRange ( split( ',', $localNetwork ) ) -{ +foreach my $IPRange ( split( ',', $localNetwork ) ) { $withinNetwork = ( $userIP =~ /^$IPRange/ ); last if $withinNetwork; } diff --git a/opac/opac-retrieve-file.pl b/opac/opac-retrieve-file.pl index 3f6e6c8d3b..e98f139491 100755 --- a/opac/opac-retrieve-file.pl +++ b/opac/opac-retrieve-file.pl @@ -27,26 +27,31 @@ use C4::Output qw( output_html_with_http_headers ); use Koha::UploadedFiles; my $input = CGI::->new; -my $hash = $input->param('id'); # historically called id (used in URLs?) +my $hash = $input->param('id'); # historically called id (used in URLs?) -my $rec = Koha::UploadedFiles->search({ - hashvalue => $hash, public => 1, - # DO NOT REMOVE the public flag: this is an opac script ! -})->next; -my $fh = $rec? $rec->file_handle: undef; +my $rec = Koha::UploadedFiles->search( + { + hashvalue => $hash, public => 1, -if( !$rec || !$fh ) { - my ( $template, $user, $cookie ) = get_template_and_user({ - query => $input, - template_name => 'opac-retrieve-file.tt', - type => 'opac', - authnotrequired => 1, - }); + # DO NOT REMOVE the public flag: this is an opac script ! + } +)->next; +my $fh = $rec ? $rec->file_handle : undef; + +if ( !$rec || !$fh ) { + my ( $template, $user, $cookie ) = get_template_and_user( + { + query => $input, + template_name => 'opac-retrieve-file.tt', + type => 'opac', + authnotrequired => 1, + } + ); $template->param( hash => $hash ); output_html_with_http_headers $input, $cookie, $template->output; } else { print Encode::encode_utf8( $input->header( $rec->httpheaders ) ); - while( <$fh> ) { + while (<$fh>) { print $_; } $fh->close; diff --git a/opac/opac-review.pl b/opac/opac-review.pl index 814cd60f75..5f3ba40490 100755 --- a/opac/opac-review.pl +++ b/opac/opac-review.pl @@ -18,8 +18,8 @@ # along with Koha; if not, see . use Modern::Perl; -use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use C4::Scrubber; @@ -45,52 +45,53 @@ my ( $template, $borrowernumber, $cookie ) = get_template_and_user( # FIXME: need to allow user to delete their own comment(s) my ( $clean, @errors, $savedreview ); -my $biblio = Koha::Biblios->find( $biblionumber ); +my $biblio = Koha::Biblios->find($biblionumber); -if( !$biblio ) { +if ( !$biblio ) { push @errors, { nobiblio => 1 }; -} elsif( $reviewid ) { # edit existing one, check on creator - $savedreview = Koha::Reviews->search({ reviewid => $reviewid, borrowernumber => $borrowernumber })->next; +} elsif ($reviewid) { # edit existing one, check on creator + $savedreview = Koha::Reviews->search( { reviewid => $reviewid, borrowernumber => $borrowernumber } )->next; push @errors, { unauthorized => 1 } if !$savedreview; -} else { # this check prevents adding multiple comments - # FIXME biblionumber, borrowernumber should be a unique key of reviews - $savedreview = Koha::Reviews->search({ biblionumber => $biblionumber, borrowernumber => $borrowernumber })->next; - $review = $savedreview? $savedreview->review: $review; +} else { # this check prevents adding multiple comments + # FIXME biblionumber, borrowernumber should be a unique key of reviews + $savedreview = Koha::Reviews->search( { biblionumber => $biblionumber, borrowernumber => $borrowernumber } )->next; + $review = $savedreview ? $savedreview->review : $review; } -if( $op =~ /^cud-/ && !@errors && defined $review ) { - if ($review !~ /\S/) { - push @errors, {empty=>1}; - } else { - $clean = C4::Scrubber->new('comment')->scrub($review); - if ($clean !~ /\S/) { - push @errors, {scrubbed_all=>1}; - } else { - if ($clean ne $review) { - push @errors, {scrubbed=>$clean}; - } +if ( $op =~ /^cud-/ && !@errors && defined $review ) { + if ( $review !~ /\S/ ) { + push @errors, { empty => 1 }; + } else { + $clean = C4::Scrubber->new('comment')->scrub($review); + if ( $clean !~ /\S/ ) { + push @errors, { scrubbed_all => 1 }; + } else { + if ( $clean ne $review ) { + push @errors, { scrubbed => $clean }; + } if ($savedreview) { $savedreview->set( { - review => $clean, - approved => 0, - datereviewed => dt_from_string + review => $clean, + approved => 0, + datereviewed => dt_from_string } )->store; } else { $reviewid = Koha::Review->new( - { biblionumber => $biblionumber, + { + biblionumber => $biblionumber, borrowernumber => $borrowernumber, review => $clean, datereviewed => dt_from_string } )->store->reviewid; } - unless (@errors){ $template->param(WINDOW_CLOSE=>1); } - } - } + unless (@errors) { $template->param( WINDOW_CLOSE => 1 ); } + } + } } -(@errors ) and $template->param( ERRORS=>\@errors); +(@errors) and $template->param( ERRORS => \@errors ); $review = $clean; $review ||= $savedreview->review if $savedreview; $template->param( diff --git a/opac/opac-routing-lists.pl b/opac/opac-routing-lists.pl index 299bb29e78..20c092b4e5 100755 --- a/opac/opac-routing-lists.pl +++ b/opac/opac-routing-lists.pl @@ -15,11 +15,10 @@ # You should have received a copy of the GNU General Public License # along with Koha; if not, see . - use Modern::Perl; use CGI qw ( -utf8 ); use C4::Members; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use Koha::Patrons; @@ -30,16 +29,15 @@ unless ( C4::Context->preference('RoutingSerials') ) { exit; } - my ( $template, $borrowernumber, $cookie ) = get_template_and_user( { - template_name => "opac-routing-lists.tt", - query => $query, - type => "opac", + template_name => "opac-routing-lists.tt", + query => $query, + type => "opac", } ); -my $patron = Koha::Patrons->find( $borrowernumber ); +my $patron = Koha::Patrons->find($borrowernumber); $template->param( routinglistsview => 1, diff --git a/opac/opac-search-history.pl b/opac/opac-search-history.pl index 85f807fd48..4276ad97ee 100755 --- a/opac/opac-search-history.pl +++ b/opac/opac-search-history.pl @@ -20,139 +20,140 @@ use Modern::Perl; use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Context; use C4::Output qw( output_html_with_http_headers ); use C4::Search::History; - - my $cgi = CGI->new; # Getting the template and auth -my ($template, $loggedinuser, $cookie) = get_template_and_user( +my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "opac-search-history.tt", - query => $cgi, - type => "opac", + template_name => "opac-search-history.tt", + query => $cgi, + type => "opac", authnotrequired => ( C4::Context->preference("OpacPublic") ? 1 : 0 ), } ); unless ( C4::Context->preference("EnableOpacSearchHistory") ) { - print $cgi->redirect("/cgi-bin/koha/errors/404.pl"); # escape early + print $cgi->redirect("/cgi-bin/koha/errors/404.pl"); # escape early exit; } -my $type = $cgi->param('type'); -my $op = $cgi->param('op') || q{}; +my $type = $cgi->param('type'); +my $op = $cgi->param('op') || q{}; my $previous = $cgi->param('previous'); # If the user is not logged in, we deal with the session -unless ( $loggedinuser ) { - # Deleting search history - if ( $op eq 'cud-delete') { - # Deleting session's search history - my @id = $cgi->multi_param('id'); - my $all = not scalar( @id ); +unless ($loggedinuser) { - my $type = $cgi->param('type'); + # Deleting search history + if ( $op eq 'cud-delete' ) { + + # Deleting session's search history + my @id = $cgi->multi_param('id'); + my $all = not scalar(@id); + + my $type = $cgi->param('type'); my @searches = (); - unless ( $all ) { - @searches = C4::Search::History::get_from_session({ cgi => $cgi }); - if ( $type ) { + unless ($all) { + @searches = C4::Search::History::get_from_session( { cgi => $cgi } ); + if ($type) { @searches = map { $_->{type} ne $type ? $_ : () } @searches; } - if ( @id ) { - @searches = map { my $search = $_; ( grep { $_ eq $search->{id} } @id ) ? () : $_ } @searches; + if (@id) { + @searches = map { + my $search = $_; + ( grep { $_ eq $search->{id} } @id ) ? () : $_ + } @searches; } } - C4::Search::History::set_to_session({ cgi => $cgi, search_history => \@searches }); + C4::Search::History::set_to_session( { cgi => $cgi, search_history => \@searches } ); # Redirecting to this same url so the user won't see the search history link in the header - print $cgi->redirect(-uri => '/cgi-bin/koha/opac-search-history.pl'); - # Showing search history + print $cgi->redirect( -uri => '/cgi-bin/koha/opac-search-history.pl' ); + + # Showing search history } else { + # Getting the searches from session - my @current_searches = C4::Search::History::get_from_session({ - cgi => $cgi, - }); + my @current_searches = C4::Search::History::get_from_session( + { + cgi => $cgi, + } + ); - my @current_biblio_searches = map { - $_->{type} eq 'biblio' ? $_ : () - } @current_searches; + my @current_biblio_searches = map { $_->{type} eq 'biblio' ? $_ : () } @current_searches; - my @current_authority_searches = map { - $_->{type} eq 'authority' ? $_ : () - } @current_searches; + my @current_authority_searches = map { $_->{type} eq 'authority' ? $_ : () } @current_searches; $template->param( - current_biblio_searches => \@current_biblio_searches, + current_biblio_searches => \@current_biblio_searches, current_authority_searches => \@current_authority_searches, ); } } else { + # And if the user is logged in, we deal with the database my $dbh = C4::Context->dbh; # Deleting search history if ( $op eq 'cud-delete' ) { my @id = $cgi->multi_param('id'); - if ( @id ) { + if (@id) { C4::Search::History::delete( { userid => $loggedinuser, - id => [ @id ], + id => [@id], } ); } else { C4::Search::History::delete( { - userid => $loggedinuser, + userid => $loggedinuser, } ); } + # Redirecting to this same url so the user won't see the search history link in the header - print $cgi->redirect(-uri => '/cgi-bin/koha/opac-search-history.pl'); + print $cgi->redirect( -uri => '/cgi-bin/koha/opac-search-history.pl' ); - # Showing search history + # Showing search history } else { - my $current_searches = C4::Search::History::get({ - userid => $loggedinuser, - sessionid => $cgi->cookie("CGISESSID") - }); - my @current_biblio_searches = map { - $_->{type} eq 'biblio' ? $_ : () - } @$current_searches; + my $current_searches = C4::Search::History::get( + { + userid => $loggedinuser, + sessionid => $cgi->cookie("CGISESSID") + } + ); + my @current_biblio_searches = map { $_->{type} eq 'biblio' ? $_ : () } @$current_searches; - my @current_authority_searches = map { - $_->{type} eq 'authority' ? $_ : () - } @$current_searches; + my @current_authority_searches = map { $_->{type} eq 'authority' ? $_ : () } @$current_searches; - my $previous_searches = C4::Search::History::get({ - userid => $loggedinuser, - sessionid => $cgi->cookie("CGISESSID"), - previous => 1 - }); + my $previous_searches = C4::Search::History::get( + { + userid => $loggedinuser, + sessionid => $cgi->cookie("CGISESSID"), + previous => 1 + } + ); - my @previous_biblio_searches = map { - $_->{type} eq 'biblio' ? $_ : () - } @$previous_searches; + my @previous_biblio_searches = map { $_->{type} eq 'biblio' ? $_ : () } @$previous_searches; - my @previous_authority_searches = map { - $_->{type} eq 'authority' ? $_ : () - } @$previous_searches; + my @previous_authority_searches = map { $_->{type} eq 'authority' ? $_ : () } @$previous_searches; $template->param( - current_biblio_searches => \@current_biblio_searches, - current_authority_searches => \@current_authority_searches, - previous_biblio_searches => \@previous_biblio_searches, + current_biblio_searches => \@current_biblio_searches, + current_authority_searches => \@current_authority_searches, + previous_biblio_searches => \@previous_biblio_searches, previous_authority_searches => \@previous_authority_searches, ); } } -$template->param(searchhistoryview => 1); +$template->param( searchhistoryview => 1 ); output_html_with_http_headers $cgi, $cookie, $template->output, undef, { force_no_caching => 1 }; diff --git a/opac/opac-search.pl b/opac/opac-search.pl index d52f96d01a..9f906784c9 100755 --- a/opac/opac-search.pl +++ b/opac/opac-search.pl @@ -24,7 +24,7 @@ use Modern::Perl; ## STEP 1. Load things that are used in both search page and -# results page and decide which template to load, operations +# results page and decide which template to load, operations # to perform, etc. ## load Koha modules use C4::Context; @@ -32,25 +32,26 @@ use List::MoreUtils q/any/; use Try::Tiny; use Encode; -use Data::Dumper; # TODO remove +use Data::Dumper; # TODO remove use Koha::SearchEngine::Search; use Koha::SearchEngine::QueryBuilder; my $searchengine = C4::Context->preference("SearchEngine"); -my ($builder, $searcher); -#$searchengine = 'Zebra'; # XXX -$builder = Koha::SearchEngine::QueryBuilder->new({index => 'biblios'}); -$searcher = Koha::SearchEngine::Search->new({index => 'biblios'}); +my ( $builder, $searcher ); -use C4::Output qw( output_html_with_http_headers pagination_bar output_with_http_headers ); -use C4::Auth qw( get_template_and_user get_session ); +#$searchengine = 'Zebra'; # XXX +$builder = Koha::SearchEngine::QueryBuilder->new( { index => 'biblios' } ); +$searcher = Koha::SearchEngine::Search->new( { index => 'biblios' } ); + +use C4::Output qw( output_html_with_http_headers pagination_bar output_with_http_headers ); +use C4::Auth qw( get_template_and_user get_session ); use C4::Languages qw( getlanguage getLanguages ); -use C4::Search qw( searchResults ); +use C4::Search qw( searchResults ); use C4::Search::History; use C4::Biblio qw( GetXmlBiblio CountItemsIssued ); -use C4::Koha qw( GetItemTypesCategorized getitemtypeimagelocation GetAuthorisedValues ); -use C4::Tags qw( get_tags ); +use C4::Koha qw( GetItemTypesCategorized getitemtypeimagelocation GetAuthorisedValues ); +use C4::Tags qw( get_tags ); use C4::SocialData; use C4::External::OverDrive; use C4::External::BakerTaylor qw( image_url link_url ); @@ -76,39 +77,44 @@ use CGI qw('-no_undef_params' -utf8); my $cgi = CGI->new; my $branch_group_limit = $cgi->param("branch_group_limit"); -if ( $branch_group_limit ) { +if ($branch_group_limit) { if ( $branch_group_limit =~ /^multibranchlimit-/ ) { + # branch_group_limit is deprecated, it should no longer be used # For search groups we are going to convert this branch_group_limit CGI # parameter into a multibranchlimit limit CGI parameter for the purposes of # actually performing the query $cgi->param( - -name => 'limit', - -values => 'multibranchlimit:' . substr($branch_group_limit, 17) + -name => 'limit', + -values => 'multibranchlimit:' . substr( $branch_group_limit, 17 ) ); } else { $cgi->append( - -name => 'limit', - -values => [ $branch_group_limit ] + -name => 'limit', + -values => [$branch_group_limit] ); } } -my ($template,$borrowernumber,$cookie); +my ( $template, $borrowernumber, $cookie ); + # decide which template to use my $template_name; -my $template_type = 'basic'; -my @params = $cgi->multi_param("limit"); +my $template_type = 'basic'; +my @params = $cgi->multi_param("limit"); my @searchCategories = $cgi->multi_param('searchcat'); my $format = $cgi->param("format") || ''; -if ($format =~ /(rss|atom|opensearchdescription)/) { +if ( $format =~ /(rss|atom|opensearchdescription)/ ) { $template_name = 'opac-opensearch.tt'; -} -elsif ((@params>=1) || (defined $cgi->param("q") && $cgi->param("q") ne "") || ($cgi->param('multibranchlimit')) || ($cgi->param('limit-yr')) || @searchCategories ) { +} elsif ( ( @params >= 1 ) + || ( defined $cgi->param("q") && $cgi->param("q") ne "" ) + || ( $cgi->param('multibranchlimit') ) + || ( $cgi->param('limit-yr') ) + || @searchCategories ) +{ $template_name = 'opac-results.tt'; -} -else { +} else { $template_name = 'opac-advsearch.tt'; $template_type = 'advsearch'; } @@ -116,61 +122,62 @@ else { $format = 'rss' if $format =~ /^rss2?$/; # load the template -($template, $borrowernumber, $cookie) = get_template_and_user({ - template_name => $template_name, - query => $cgi, - type => "opac", - authnotrequired => ( C4::Context->preference("OpacPublic") ? 1 : 0 ), +( $template, $borrowernumber, $cookie ) = get_template_and_user( + { + template_name => $template_name, + query => $cgi, + type => "opac", + authnotrequired => ( C4::Context->preference("OpacPublic") ? 1 : 0 ), } ); -my $patron = Koha::Patrons->find( $borrowernumber ); +my $patron = Koha::Patrons->find($borrowernumber); my $lang = C4::Languages::getlanguage($cgi); -if ($template_name eq 'opac-results.tt') { - $template->param('COinSinOPACResults' => C4::Context->preference('COinSinOPACResults')); +if ( $template_name eq 'opac-results.tt' ) { + $template->param( 'COinSinOPACResults' => C4::Context->preference('COinSinOPACResults') ); } # get biblionumbers stored in the cart my @cart_list; -if($cgi->cookie("bib_list")){ +if ( $cgi->cookie("bib_list") ) { my $cart_list = $cgi->cookie("bib_list"); - @cart_list = split(/\//, $cart_list); + @cart_list = split( /\//, $cart_list ); } -if ($format eq 'rss' or $format eq 'opensearchdescription' or $format eq 'atom') { - $template->param($format => 1); +if ( $format eq 'rss' or $format eq 'opensearchdescription' or $format eq 'atom' ) { + $template->param( $format => 1 ); + #NOTE: opensearchdescription doesn't actually use timestamp... - $template->param(timestamp => strftime("%Y-%m-%dT%H:%M:%S-00:00", gmtime)) if ($format eq 'atom'); + $template->param( timestamp => strftime( "%Y-%m-%dT%H:%M:%S-00:00", gmtime ) ) if ( $format eq 'atom' ); + # FIXME - the timestamp is a hack - the biblio update timestamp should be used for each # entry, but not sure if that's worth an extra database query for each bib } #NOTE: Return now for 'opensearchdescription' BZ 32639 -if ( $format && $format eq 'opensearchdescription' ){ +if ( $format && $format eq 'opensearchdescription' ) { my $content_type = $format; output_with_http_headers $cgi, $cookie, $template->output, $content_type; exit; } -if (C4::Context->preference("marcflavour") eq "UNIMARC" ) { - $template->param('UNIMARC' => 1); -} -elsif (C4::Context->preference("marcflavour") eq "MARC21" ) { - $template->param('usmarc' => 1); +if ( C4::Context->preference("marcflavour") eq "UNIMARC" ) { + $template->param( 'UNIMARC' => 1 ); +} elsif ( C4::Context->preference("marcflavour") eq "MARC21" ) { + $template->param( 'usmarc' => 1 ); } $template->param( 'OPACNoResultsFound' => C4::Context->preference('OPACNoResultsFound') ); -$template->param( - OpacStarRatings => C4::Context->preference("OpacStarRatings") ); +$template->param( OpacStarRatings => C4::Context->preference("OpacStarRatings") ); -if (C4::Context->preference('BakerTaylorEnabled')) { +if ( C4::Context->preference('BakerTaylorEnabled') ) { $template->param( - BakerTaylorEnabled => 1, - BakerTaylorImageURL => &image_url(), - BakerTaylorLinkURL => &link_url(), + BakerTaylorEnabled => 1, + BakerTaylorImageURL => &image_url(), + BakerTaylorLinkURL => &link_url(), BakerTaylorBookstoreURL => C4::Context->preference('BakerTaylorBookstoreURL'), ); } @@ -179,7 +186,7 @@ if (C4::Context->preference('BakerTaylorEnabled')) { # Deprecated, but preserved because it's interesting :-) # The same thing can be accomplished with mod_rewrite in # a more elegant way -# +# #my $rewrite_flag; #my $uri = $cgi->url(-base => 1); #my $relative_url = $cgi->url(-relative=>1); @@ -201,18 +208,16 @@ if (C4::Context->preference('BakerTaylorEnabled')) { # load the branches -if ($cgi->param("returntosearch")) { - $template->param('ReturnToSearch' => 1); +if ( $cgi->param("returntosearch") ) { + $template->param( 'ReturnToSearch' => 1 ); } -if ($cgi->cookie("search_path_code")) { +if ( $cgi->cookie("search_path_code") ) { my $pathcode = $cgi->cookie("search_path_code"); - if ($pathcode eq 'ads') { - $template->param('ReturnPath' => '/cgi-bin/koha/opac-search.pl?returntosearch=1'); - } - elsif ($pathcode eq 'exs') { - $template->param('ReturnPath' => '/cgi-bin/koha/opac-search.pl?expanded_options=1&returntosearch=1'); - } - else { + if ( $pathcode eq 'ads' ) { + $template->param( 'ReturnPath' => '/cgi-bin/koha/opac-search.pl?returntosearch=1' ); + } elsif ( $pathcode eq 'exs' ) { + $template->param( 'ReturnPath' => '/cgi-bin/koha/opac-search.pl?expanded_options=1&returntosearch=1' ); + } else { warn "ReturnPath switch error"; } } @@ -229,114 +234,129 @@ if ( $template_type && $template_type eq 'advsearch' ) { # load the Type stuff my $itemtypes = GetItemTypesCategorized; + # add translated_description to itemtypes foreach my $itemtype ( keys %{$itemtypes} ) { + # Itemtypes search categories don't have (yet) translated descriptions, they are auth values (and could still have no descriptions too BZ 18400) # If 'iscat' (see ITEMTYPECAT) then there is no itemtype and the description is not translated - my $translated_description = $itemtypes->{$itemtype}->{iscat} - ? $itemtypes->{$itemtype}->{description} - : Koha::ItemTypes->find($itemtype)->translated_description; - $itemtypes->{$itemtype}->{translated_description} = $translated_description || $itemtypes->{$itemtype}->{description} || q{}; + my $translated_description = + $itemtypes->{$itemtype}->{iscat} + ? $itemtypes->{$itemtype}->{description} + : Koha::ItemTypes->find($itemtype)->translated_description; + $itemtypes->{$itemtype}->{translated_description} = + $translated_description || $itemtypes->{$itemtype}->{description} || q{}; } # the index parameter is different for item-level itemtypes -my $itype_or_itemtype = (C4::Context->preference("item-level_itypes"))?'itype':'itemtype'; +my $itype_or_itemtype = ( C4::Context->preference("item-level_itypes") ) ? 'itype' : 'itemtype'; my @advancedsearchesloop; my $cnt; my $advanced_search_types = C4::Context->preference("OpacAdvancedSearchTypes") || "itemtypes"; -my @advanced_search_types = split(/\|/, $advanced_search_types); +my @advanced_search_types = split( /\|/, $advanced_search_types ); my $hidingrules = C4::Context->yaml_preference('OpacHiddenItems') // {}; -my @sorted_itemtypes = sort { $itemtypes->{$a}->{translated_description} cmp $itemtypes->{$b}->{translated_description} } keys %$itemtypes; +my @sorted_itemtypes = + sort { $itemtypes->{$a}->{translated_description} cmp $itemtypes->{$b}->{translated_description} } keys %$itemtypes; foreach my $advanced_srch_type (@advanced_search_types) { $advanced_srch_type =~ s/^\s*//; $advanced_srch_type =~ s/\s*$//; - if ($advanced_srch_type eq 'itemtypes') { - # itemtype is a special case, since it's not defined in authorized values + if ( $advanced_srch_type eq 'itemtypes' ) { + + # itemtype is a special case, since it's not defined in authorized values my @itypesloop; - foreach my $thisitemtype ( @sorted_itemtypes ) { - next if $hidingrules->{itype} && any { $_ eq $thisitemtype } @{$hidingrules->{itype}}; - next if $hidingrules->{itemtype} && any { $_ eq $thisitemtype } @{$hidingrules->{itemtype}}; - my %row =( number=>$cnt++, - ccl => "$itype_or_itemtype,phr", - code => $thisitemtype, - description => $itemtypes->{$thisitemtype}->{translated_description}, - imageurl=> getitemtypeimagelocation( 'opac', $itemtypes->{$thisitemtype}->{'imageurl'} ), - cat => $itemtypes->{$thisitemtype}->{'iscat'}, - hideinopac => $itemtypes->{$thisitemtype}->{'hideinopac'}, + foreach my $thisitemtype (@sorted_itemtypes) { + next if $hidingrules->{itype} && any { $_ eq $thisitemtype } @{ $hidingrules->{itype} }; + next if $hidingrules->{itemtype} && any { $_ eq $thisitemtype } @{ $hidingrules->{itemtype} }; + my %row = ( + number => $cnt++, + ccl => "$itype_or_itemtype,phr", + code => $thisitemtype, + description => $itemtypes->{$thisitemtype}->{translated_description}, + imageurl => getitemtypeimagelocation( 'opac', $itemtypes->{$thisitemtype}->{'imageurl'} ), + cat => $itemtypes->{$thisitemtype}->{'iscat'}, + hideinopac => $itemtypes->{$thisitemtype}->{'hideinopac'}, searchcategory => $itemtypes->{$thisitemtype}->{'searchcategory'}, ); if ( !$itemtypes->{$thisitemtype}->{'hideinopac'} ) { push @itypesloop, \%row; } - } - my %search_code = ( advanced_search_type => $advanced_srch_type, - code_loop => \@itypesloop ); + } + my %search_code = ( + advanced_search_type => $advanced_srch_type, + code_loop => \@itypesloop + ); push @advancedsearchesloop, \%search_code; } else { - # covers all the other cases: non-itemtype authorized values - my $advsearchtypes = GetAuthorisedValues($advanced_srch_type, 'opac'); + + # covers all the other cases: non-itemtype authorized values + my $advsearchtypes = GetAuthorisedValues( $advanced_srch_type, 'opac' ); my @authvalueloop; - for my $thisitemtype (@$advsearchtypes) { + for my $thisitemtype (@$advsearchtypes) { my $hiding_key = lc $thisitemtype->{category}; $hiding_key = "location" if $hiding_key eq 'loc'; - next if $hidingrules->{$hiding_key} && any { $_ eq $thisitemtype->{authorised_value} } @{$hidingrules->{$hiding_key}}; - my %row =( - number=>$cnt++, - ccl => $advanced_srch_type, - code => $thisitemtype->{authorised_value}, - description => $thisitemtype->{'lib_opac'} || $thisitemtype->{'lib'}, + next + if $hidingrules->{$hiding_key} && any { $_ eq $thisitemtype->{authorised_value} } + @{ $hidingrules->{$hiding_key} }; + my %row = ( + number => $cnt++, + ccl => $advanced_srch_type, + code => $thisitemtype->{authorised_value}, + description => $thisitemtype->{'lib_opac'} || $thisitemtype->{'lib'}, searchcategory => $itemtypes->{$thisitemtype}->{'searchcategory'}, - imageurl => getitemtypeimagelocation( 'opac', $thisitemtype->{'imageurl'} ), - ); - push @authvalueloop, \%row; - } - my %search_code = ( advanced_search_type => $advanced_srch_type, - code_loop => \@authvalueloop ); + imageurl => getitemtypeimagelocation( 'opac', $thisitemtype->{'imageurl'} ), + ); + push @authvalueloop, \%row; + } + my %search_code = ( + advanced_search_type => $advanced_srch_type, + code_loop => \@authvalueloop + ); push @advancedsearchesloop, \%search_code; } } -$template->param(advancedsearchesloop => \@advancedsearchesloop); +$template->param( advancedsearchesloop => \@advancedsearchesloop ); my $default_sort_by = C4::Context->default_catalog_sort_by; # The following should only be loaded if we're bringing up the advanced search template if ( $template_type && $template_type eq 'advsearch' ) { + # load the servers (used for searching -- to do federated searching, etc.) - my $primary_servers_loop;# = displayPrimaryServers(); - $template->param(outer_servers_loop => $primary_servers_loop,); - + my $primary_servers_loop; # = displayPrimaryServers(); + $template->param( outer_servers_loop => $primary_servers_loop, ); + my $secondary_servers_loop; - $template->param(outer_sup_servers_loop => $secondary_servers_loop,); + $template->param( outer_sup_servers_loop => $secondary_servers_loop, ); # set the default sorting if ($default_sort_by) { $template->param( sort_by => $default_sort_by ); } - my @advsearch_limits = split /,/, C4::Context->preference('OpacAdvSearchOptions'); + my @advsearch_limits = split /,/, C4::Context->preference('OpacAdvSearchOptions'); my @advsearch_more_limits = split /,/, - C4::Context->preference('OpacAdvSearchMoreOptions'); + C4::Context->preference('OpacAdvSearchMoreOptions'); $template->param( - uc( C4::Context->preference("marcflavour") ) => 1, # we already did this for UNIMARC - advsearch => 1, - OpacAdvSearchOptions => \@advsearch_limits, - OpacAdvSearchMoreOptions => \@advsearch_more_limits, + uc( C4::Context->preference("marcflavour") ) => 1, # we already did this for UNIMARC + advsearch => 1, + OpacAdvSearchOptions => \@advsearch_limits, + OpacAdvSearchMoreOptions => \@advsearch_more_limits, ); # use the global setting by default if ( C4::Context->preference("expandedSearchOption") == 1 ) { $template->param( expanded_options => C4::Context->preference("expandedSearchOption") ); } + # but let the user override it - if (defined $cgi->param('expanded_options')) { - if ( ($cgi->param('expanded_options') == 0) || ($cgi->param('expanded_options') == 1 ) ) { - $template->param( expanded_options => scalar $cgi->param('expanded_options')); + if ( defined $cgi->param('expanded_options') ) { + if ( ( $cgi->param('expanded_options') == 0 ) || ( $cgi->param('expanded_options') == 1 ) ) { + $template->param( expanded_options => scalar $cgi->param('expanded_options') ); } } - output_html_with_http_headers $cgi, $cookie, $template->output; exit; } @@ -357,11 +377,11 @@ if ( $params->{tag} ) { # String with params with the search criteria for the paging in opac-detail # param value is URI encoded and params separator is HTML encode (&) my $pasarParams = ''; -my $j = 0; -for (keys %$params) { +my $j = 0; +for ( keys %$params ) { my @pasarParam = $cgi->multi_param($_); - for my $paramValue(@pasarParam) { - $pasarParams .= '&' if ($j > 0); + for my $paramValue (@pasarParam) { + $pasarParams .= '&' if ( $j > 0 ); $pasarParams .= uri_escape_utf8($_) . '=' . uri_escape_utf8($paramValue); $j++; } @@ -371,21 +391,24 @@ for (keys %$params) { # sort by is used to sort the query # in theory can have more than one but generally there's just one my @sort_by; -my @allowed_sortby = qw /acqdate_asc acqdate_dsc author_az author_za call_number_asc call_number_dsc popularity_asc popularity_dsc pubdate_asc pubdate_dsc relevance title_az title_za/; +my @allowed_sortby = + qw /acqdate_asc acqdate_dsc author_az author_za call_number_asc call_number_dsc popularity_asc popularity_dsc pubdate_asc pubdate_dsc relevance title_az title_za/; @sort_by = $cgi->multi_param('sort_by'); $sort_by[0] = $default_sort_by if !$sort_by[0] && defined($default_sort_by); foreach my $sort (@sort_by) { if ( grep { $_ eq $sort } @allowed_sortby ) { - $template->param($sort => 1); + $template->param( $sort => 1 ); } } -$template->param('sort_by' => $sort_by[0]); +$template->param( 'sort_by' => $sort_by[0] ); # Use the servers defined, or just search our local catalog(default) my @servers = $cgi->multi_param('server'); unless (@servers) { + #FIXME: this should be handled using Context.pm @servers = ("biblioserver"); + # @servers = C4::Context->config("biblioserver"); } @@ -395,30 +418,31 @@ my @operators = $cgi->multi_param('op'); @operators = map { uri_unescape($_) } @operators; # indexes are query qualifiers, like 'title', 'author', etc. They -# can be single or multiple parameters separated by comma: kw,right-Truncation +# can be single or multiple parameters separated by comma: kw,right-Truncation my @indexes = $cgi->multi_param('idx'); @indexes = map { uri_unescape($_) } @indexes; # if a simple index (only one) display the index used in the top search box -if ($indexes[0] && !$indexes[1]) { - my $idx = "ms_".$indexes[0]; - $idx =~ s/\,/comma/g; # template toolkit doesn't like variables with a , in it - $idx =~ s/-/dash/g; # template toolkit doesn't like variables with a dash in it - $template->param($idx => 1); +if ( $indexes[0] && !$indexes[1] ) { + my $idx = "ms_" . $indexes[0]; + $idx =~ s/\,/comma/g; # template toolkit doesn't like variables with a , in it + $idx =~ s/-/dash/g; # template toolkit doesn't like variables with a dash in it + $template->param( $idx => 1 ); } + # an operand can be a single term, a phrase, or a complete ccl query my @operands = $cgi->multi_param('q'); @operands = map { uri_unescape($_) } @operands; -$template->{VARS}->{querystring} = join(' ', @operands); +$template->{VARS}->{querystring} = join( ' ', @operands ); # if a simple search, display the value in the search box my $basic_search = 0; -if ($operands[0] && !$operands[1]) { +if ( $operands[0] && !$operands[1] ) { my $ms_query = $operands[0]; $ms_query =~ s/ #\S+//; - $template->param(ms_value => $ms_query); - $basic_search=1; + $template->param( ms_value => $ms_query ); + $basic_search = 1; } # limits are use to limit to results to a pre-defined category such as branch or language @@ -429,69 +453,68 @@ my @nolimits = $cgi->multi_param('nolimit'); my %is_nolimit = map { $_ => 1 } @nolimits; @limits = grep { not $is_nolimit{$_} } @limits; -if (@searchCategories > 0) { +if ( @searchCategories > 0 ) { my @tabcat; foreach my $typecategory (@searchCategories) { - push @tabcat, Koha::ItemTypes->search({ searchcategory => $typecategory })->get_column('itemtype'); + push @tabcat, Koha::ItemTypes->search( { searchcategory => $typecategory } )->get_column('itemtype'); } foreach my $itemtypeInCategory (@tabcat) { - push (@limits, "mc-$itype_or_itemtype,phr:".$itemtypeInCategory); + push( @limits, "mc-$itype_or_itemtype,phr:" . $itemtypeInCategory ); } } @limits = map { uri_unescape($_) } @limits; - my $available; -foreach my $limit(@limits) { - if ($limit =~/available/) { +foreach my $limit (@limits) { + if ( $limit =~ /available/ ) { $available = 1; } } -$template->param(available => $available); +$template->param( available => $available ); # append year limits if they exist -if ($params->{'limit-yr'}) { - if ($params->{'limit-yr'} =~ /\d{4}/) { +if ( $params->{'limit-yr'} ) { + if ( $params->{'limit-yr'} =~ /\d{4}/ ) { push @limits, "yr,st-numeric=$params->{'limit-yr'}"; - } - else { + } else { + #FIXME: Should return a error to the user, incorect date format specified } } # Params that can only have one value -my $scan = $params->{'scan'}; -my $count = C4::Context->preference('OPACnumSearchResults') || 20; -my $countRSS = C4::Context->preference('numSearchRSSResults') || 50; -my $results_per_page = $params->{'count'} || $count; -my $offset = $params->{'offset'} || 0; +my $scan = $params->{'scan'}; +my $count = C4::Context->preference('OPACnumSearchResults') || 20; +my $countRSS = C4::Context->preference('numSearchRSSResults') || 50; +my $results_per_page = $params->{'count'} || $count; +my $offset = $params->{'offset'} || 0; $offset = 0 if $offset < 0; my $page = $cgi->param('page') || 1; -$offset = ($page-1)*$results_per_page if $page>1; +$offset = ( $page - 1 ) * $results_per_page if $page > 1; my $hits; my $weight_search = $cgi->param('advsearch') ? $cgi->param('weight_search') || 0 : 1; # Define some global variables -my ($error,$query,$simple_query,$query_cgi,$query_desc,$limit,$limit_cgi,$limit_desc,$query_type); +my ( $error, $query, $simple_query, $query_cgi, $query_desc, $limit, $limit_cgi, $limit_desc, $query_type ); my $suppress = 0; -if (C4::Context->preference('OpacSuppression')) { +if ( C4::Context->preference('OpacSuppression') ) { + # OPAC suppression by IP address - if (C4::Context->preference('OpacSuppressionByIPRange')) { + if ( C4::Context->preference('OpacSuppressionByIPRange') ) { my $IPAddress = $ENV{'REMOTE_ADDR'}; - my $IPRange = C4::Context->preference('OpacSuppressionByIPRange'); - $suppress = ($IPAddress !~ /^$IPRange/); - } - else { + my $IPRange = C4::Context->preference('OpacSuppressionByIPRange'); + $suppress = ( $IPAddress !~ /^$IPRange/ ); + } else { $suppress = 1; } } ## I. BUILD THE QUERY -( $error,$query,$simple_query,$query_cgi,$query_desc,$limit,$limit_cgi,$limit_desc,$query_type) - = $builder->build_query_compat( +( $error, $query, $simple_query, $query_cgi, $query_desc, $limit, $limit_cgi, $limit_desc, $query_type ) = + $builder->build_query_compat( \@operators, \@operands, \@indexes, @@ -500,18 +523,18 @@ if (C4::Context->preference('OpacSuppression')) { 0, $lang, { - suppress => $suppress, - is_opac => 1, + suppress => $suppress, + is_opac => 1, weighted_fields => $weight_search } -); + ); $template->param( search_query => $query ) if C4::Context->preference('DumpSearchQueryTemplate'); sub _input_cgi_parse { my @elements; my $query_cgi = shift or return @elements; - for my $this_cgi ( split('&',$query_cgi) ) { + for my $this_cgi ( split( '&', $query_cgi ) ) { next unless $this_cgi; $this_cgi =~ /(.*?)=(.*)/; push @elements, { input_name => $1, input_value => Encode::decode_utf8( uri_unescape($2) ) }; @@ -521,59 +544,64 @@ sub _input_cgi_parse { ## parse the query_cgi string and put it into a form suitable for s my @query_inputs = _input_cgi_parse($query_cgi); -$template->param ( QUERY_INPUTS => \@query_inputs ); +$template->param( QUERY_INPUTS => \@query_inputs ); ## parse the limit_cgi string and put it into a form suitable for s my @limit_inputs = $limit_cgi ? _input_cgi_parse($limit_cgi) : (); # OpenURL my @OpenURL_itypes; -if (C4::Context->preference('OPACShowOpenURL')) { +if ( C4::Context->preference('OPACShowOpenURL') ) { @OpenURL_itypes = split( /\s/, C4::Context->preference('OPACOpenURLItemTypes') ); $template->param( - OPACShowOpenURL => 1, - OpenURLResolverURL => C4::Context->preference('OpenURLResolverURL'), - OpenURLText => C4::Context->preference('OpenURLText'), + OPACShowOpenURL => 1, + OpenURLResolverURL => C4::Context->preference('OpenURLResolverURL'), + OpenURLText => C4::Context->preference('OpenURLText'), OpenURLImageLocation => C4::Context->preference('OpenURLImageLocation') ); } -$template->param ( LIMIT_INPUTS => \@limit_inputs ); -$template->param ( OPACResultsSidebar => C4::Context->preference('OPACResultsSidebar')); +$template->param( LIMIT_INPUTS => \@limit_inputs ); +$template->param( OPACResultsSidebar => C4::Context->preference('OPACResultsSidebar') ); ## II. DO THE SEARCH AND GET THE RESULTS -my $total = 0; # the total results for the whole set -my $facets; # this object stores the faceted results that display on the left-hand of the results page +my $total = 0; # the total results for the whole set +my $facets; # this object stores the faceted results that display on the left-hand of the results page my $results_hashref; if ($tag) { - $query_cgi = "tag=" . uri_escape_utf8( $tag ) . "&" . $query_cgi; - my $taglist = get_tags({term=>$tag, approved=>1}); - $results_hashref->{biblioserver}->{hits} = scalar (@$taglist); + $query_cgi = "tag=" . uri_escape_utf8($tag) . "&" . $query_cgi; + my $taglist = get_tags( { term => $tag, approved => 1 } ); + $results_hashref->{biblioserver}->{hits} = scalar(@$taglist); my @marclist = map { C4::Biblio::GetXmlBiblio( $_->{biblionumber} ) } @$taglist; $results_hashref->{biblioserver}->{RECORDS} = \@marclist; + # FIXME: tag search and standard search should work together, not exclusively # FIXME: Because search and standard search don't work together OpacHiddenItems # displays search results which should be hidden. # FIXME: No facets for tags search. } else { my $json = JSON->new->utf8->allow_nonref(1); - $pasarParams .= '&query=' . uri_escape_utf8($json->encode($query)); + $pasarParams .= '&query=' . uri_escape_utf8( $json->encode($query) ); $pasarParams .= '&count=' . uri_escape_utf8($results_per_page); $pasarParams .= '&simple_query=' . uri_escape_utf8($simple_query); $pasarParams .= '&query_type=' . uri_escape_utf8($query_type) if ($query_type); - my $itemtypes_nocategory = { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search_with_localization->unblessed } }; + my $itemtypes_nocategory = + { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search_with_localization->unblessed } }; eval { - ($error, $results_hashref, $facets) = $searcher->search_compat($query,$simple_query,\@sort_by,\@servers,$results_per_page,$offset,undef,$itemtypes_nocategory,$query_type,$scan,1); -}; + ( $error, $results_hashref, $facets ) = $searcher->search_compat( + $query, $simple_query, \@sort_by, \@servers, $results_per_page, $offset, undef, + $itemtypes_nocategory, $query_type, $scan, 1 + ); + }; } # use Data::Dumper; print STDERR "-" x 25, "\n", Dumper($results_hashref); -if (not $tag and ( $@ || $error)) { +if ( not $tag and ( $@ || $error ) ) { my $query_error = q{}; $query_error .= $error if $error; - $query_error .= $@ if $@; - $template->param(query_error => $query_error); + $query_error .= $@ if $@; + $template->param( query_error => $query_error ); output_html_with_http_headers $cgi, $cookie, $template->output; exit; } @@ -583,7 +611,7 @@ if (not $tag and ( $@ || $error)) { my @sup_results_array; my $search_context = {}; $search_context->{'interface'} = 'opac'; -if (C4::Context->preference('OpacHiddenItemsExceptions')){ +if ( C4::Context->preference('OpacHiddenItemsExceptions') ) { $search_context->{patron} = $patron; } @@ -592,23 +620,23 @@ my $variables = { anonymous_session => ($borrowernumber) ? 0 : 1 }; my @plugin_responses = Koha::Plugins->call( 'opac_results_xslt_variables', { - lang => $lang, - patron_id => $borrowernumber + lang => $lang, + patron_id => $borrowernumber } ); -for my $plugin_variables ( @plugin_responses ) { +for my $plugin_variables (@plugin_responses) { $variables = { %$variables, %$plugin_variables }; } -for (my $i=0;$i<@servers;$i++) { +for ( my $i = 0 ; $i < @servers ; $i++ ) { my $server = $servers[$i]; - if ($server && $server =~/biblioserver/) { # this is the local bibliographic server + if ( $server && $server =~ /biblioserver/ ) { # this is the local bibliographic server $hits = $results_hashref->{$server}->{"hits"} // 0; - if ( $hits == 0 && $basic_search ){ - $operands[0] = '"'.$operands[0].'"'; #quote it + if ( $hits == 0 && $basic_search ) { + $operands[0] = '"' . $operands[0] . '"'; #quote it ## I. BUILD THE QUERY - ( $error,$query,$simple_query,$query_cgi,$query_desc,$limit,$limit_cgi,$limit_desc,$query_type) - = $builder->build_query_compat( + ( $error, $query, $simple_query, $query_cgi, $query_desc, $limit, $limit_cgi, $limit_desc, $query_type ) = + $builder->build_query_compat( \@operators, \@operands, \@indexes, @@ -617,30 +645,37 @@ for (my $i=0;$i<@servers;$i++) { 0, $lang, { - suppress => $suppress, - is_opac => 1, + suppress => $suppress, + is_opac => 1, weighted_fields => $weight_search } - ); + ); my $quoted_results_hashref; - my $itemtypes_nocategory = { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search_with_localization->unblessed } }; + my $itemtypes_nocategory = + { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search_with_localization->unblessed } }; eval { - ($error, $quoted_results_hashref, $facets) = $searcher->search_compat($query,$simple_query,\@sort_by,\@servers,$results_per_page,$offset,undef,$itemtypes_nocategory,$query_type,$scan,1); + ( $error, $quoted_results_hashref, $facets ) = $searcher->search_compat( + $query, $simple_query, \@sort_by, \@servers, $results_per_page, $offset, + undef, $itemtypes_nocategory, $query_type, $scan, 1 + ); }; my $quoted_hits = $quoted_results_hashref->{$server}->{"hits"} // 0; - if ( $quoted_hits ){ + if ($quoted_hits) { $results_hashref->{'biblioserver'} = $quoted_results_hashref->{'biblioserver'}; $hits = $quoted_hits; } } - my $page = $cgi->param('page') || 0; - my @newresults = searchResults( $search_context, $query_desc, $hits, $results_per_page, $offset, $scan, - $results_hashref->{$server}->{"RECORDS"}, $variables); + my $page = $cgi->param('page') || 0; + my @newresults = searchResults( + $search_context, $query_desc, $hits, $results_per_page, $offset, $scan, + $results_hashref->{$server}->{"RECORDS"}, $variables + ); $hits = 0 unless @newresults; my $art_req_itypes; - if( C4::Context->preference('ArticleRequests') ) { - $art_req_itypes = Koha::CirculationRules->guess_article_requestable_itemtypes({ $patron ? ( categorycode => $patron->categorycode ) : () }); + if ( C4::Context->preference('ArticleRequests') ) { + $art_req_itypes = Koha::CirculationRules->guess_article_requestable_itemtypes( + { $patron ? ( categorycode => $patron->categorycode ) : () } ); } foreach my $res (@newresults) { @@ -648,37 +683,41 @@ for (my $i=0;$i<@servers;$i++) { # must define a value for size if not present in DB # in order to avoid problems generated by the default size value in TT if ( not exists $res->{'size'} ) { $res->{'size'} = "" } + # while we're checking each line, see if item is in the cart - if ( grep {$_ eq $res->{'biblionumber'}} @cart_list) { + if ( grep { $_ eq $res->{'biblionumber'} } @cart_list ) { $res->{'incart'} = 1; } - if ( C4::Context->preference( "Babeltheque" ) and $res->{normalized_isbn} ) { - if( my $isbn = Business::ISBN->new( $res->{normalized_isbn} ) ) { + if ( C4::Context->preference("Babeltheque") and $res->{normalized_isbn} ) { + if ( my $isbn = Business::ISBN->new( $res->{normalized_isbn} ) ) { $isbn = $isbn->as_isbn13->as_string; $isbn =~ s/-//g; - my $social_datas = C4::SocialData::get_data( $isbn ); - if ( $social_datas ) { + my $social_datas = C4::SocialData::get_data($isbn); + if ($social_datas) { for my $key ( keys %$social_datas ) { $res->{$key} = $$social_datas{$key}; - if ( $key eq 'score_avg' ){ - $res->{score_int} = sprintf("%.0f", $$social_datas{score_avg} ); + if ( $key eq 'score_avg' ) { + $res->{score_int} = sprintf( "%.0f", $$social_datas{score_avg} ); } } } } } - if (C4::Context->preference('TagsEnabled') and - C4::Context->preference('TagsShowOnList')) { + if ( C4::Context->preference('TagsEnabled') + and C4::Context->preference('TagsShowOnList') ) + { if ( my $bibnum = $res->{biblionumber} ) { - $res->{itemsissued} = CountItemsIssued( $bibnum ); - $res->{'TagLoop'} = get_tags({ - biblionumber => $bibnum, - approved => 1, - sort => '-weight', - limit => C4::Context->preference('TagsShowOnList') - }); + $res->{itemsissued} = CountItemsIssued($bibnum); + $res->{'TagLoop'} = get_tags( + { + biblionumber => $bibnum, + approved => 1, + sort => '-weight', + limit => C4::Context->preference('TagsShowOnList') + } + ); } } @@ -690,28 +729,30 @@ for (my $i=0;$i<@servers;$i++) { ); if ( C4::Context->preference('OpacStarRatings') eq 'all' ) { - my $ratings = Koha::Ratings->search({ biblionumber => $res->{biblionumber} }); + my $ratings = Koha::Ratings->search( { biblionumber => $res->{biblionumber} } ); $res->{ratings} = $ratings; - $res->{my_rating} = $borrowernumber ? $ratings->search({ borrowernumber => $borrowernumber })->next : undef; + $res->{my_rating} = + $borrowernumber ? $ratings->search( { borrowernumber => $borrowernumber } )->next : undef; } # BZ17530: 'Intelligent' guess if result can be article requested - $res->{artreqpossible} = ( $art_req_itypes->{ $res->{itemtype} // q{} } || $art_req_itypes->{ '*' } ) ? 1 : q{}; + $res->{artreqpossible} = + ( $art_req_itypes->{ $res->{itemtype} // q{} } || $art_req_itypes->{'*'} ) ? 1 : q{}; if ( C4::Context->preference('OPACLocalCoverImages') ) { $res->{has_local_cover_image} = $res->{biblio_object} ? $res->{biblio_object}->cover_images->count : 0; } } - if ($results_hashref->{$server}->{"hits"}){ + if ( $results_hashref->{$server}->{"hits"} ) { $total = $total + $hits; } # Opac search history - if (C4::Context->preference('EnableOpacSearchHistory')) { - unless ( $offset ) { - my $path_info = $cgi->url(-path_info=>1); - my $query_cgi_history = $cgi->url(-query=>1); + if ( C4::Context->preference('EnableOpacSearchHistory') ) { + unless ($offset) { + my $path_info = $cgi->url( -path_info => 1 ); + my $query_cgi_history = $cgi->url( -query => 1 ); $query_cgi_history =~ s/^$path_info\?//; $query_cgi_history =~ s/;/&/g; my $query_desc_history = join ", ", grep { defined $_ } $query_desc, $limit_desc; @@ -762,75 +803,84 @@ for (my $i=0;$i<@servers;$i++) { exit; } if ($hits) { + # We build the encrypted list of first OPACnumSearchResults biblios to pass with the search criteria for paging on opac-detail $pasarParams .= '&listBiblios='; my $j = 0; foreach (@newresults) { - my $bibnum = ($_->{biblionumber})?$_->{biblionumber}:0; + my $bibnum = ( $_->{biblionumber} ) ? $_->{biblionumber} : 0; $pasarParams .= uri_escape_utf8($bibnum) . ','; $j++; - last if ($j == $results_per_page); + last if ( $j == $results_per_page ); } - chop $pasarParams if ($pasarParams =~ /,$/); - $pasarParams .= '&total=' . uri_escape_utf8( int($total) ) if ($pasarParams !~ /total=(?:[0-9]+)?/); + chop $pasarParams if ( $pasarParams =~ /,$/ ); + $pasarParams .= '&total=' . uri_escape_utf8( int($total) ) if ( $pasarParams !~ /total=(?:[0-9]+)?/ ); if ($pasarParams) { - my $session = get_session($cgi->cookie("CGISESSID")); - $session->param('busc' => $pasarParams); + my $session = get_session( $cgi->cookie("CGISESSID") ); + $session->param( 'busc' => $pasarParams ); } - $template->param(total => $hits); + $template->param( total => $hits ); my $limit_cgi_not_availablity = $limit_cgi; $limit_cgi_not_availablity =~ s/&limit=available//g if defined $limit_cgi_not_availablity; - $template->param(limit_cgi_not_availablity => $limit_cgi_not_availablity); - $template->param(limit_cgi => $limit_cgi); - $template->param(countrss => $countRSS ); - $template->param(query_cgi => $query_cgi); - $template->param(query_desc => $query_desc); - $template->param(limit_desc => $limit_desc); - $template->param(offset => $offset); - if ($query_desc || $limit_desc) { - $template->param(searchdesc => 1); + $template->param( limit_cgi_not_availablity => $limit_cgi_not_availablity ); + $template->param( limit_cgi => $limit_cgi ); + $template->param( countrss => $countRSS ); + $template->param( query_cgi => $query_cgi ); + $template->param( query_desc => $query_desc ); + $template->param( limit_desc => $limit_desc ); + $template->param( offset => $offset ); + + if ( $query_desc || $limit_desc ) { + $template->param( searchdesc => 1 ); } - $template->param(results_per_page => $results_per_page); + $template->param( results_per_page => $results_per_page ); my $hide = keys %$hidingrules ? 1 : 0; $template->param( - SEARCH_RESULTS => \@newresults, + SEARCH_RESULTS => \@newresults, suppress_result_number => $hide, - ); + ); if ( C4::Context->preference("OPACLocalCoverImages") ) { $template->param( OPACLocalCoverImages => 1 ); } ## Build the page numbers on the bottom of the page - my ( $page_numbers, $hits_to_paginate, $pages, $current_page_number, $previous_page_offset, $next_page_offset, $last_page_offset ) = - Koha::SearchEngine::Search->pagination_bar( - { - hits => $hits, - max_result_window => $searcher->max_result_window, - results_per_page => $results_per_page, - offset => $offset, - sort_by => \@sort_by - } + my ( + $page_numbers, $hits_to_paginate, $pages, $current_page_number, $previous_page_offset, + $next_page_offset, $last_page_offset + ) + = Koha::SearchEngine::Search->pagination_bar( + { + hits => $hits, + max_result_window => $searcher->max_result_window, + results_per_page => $results_per_page, + offset => $offset, + sort_by => \@sort_by + } ); $template->param( hits_to_paginate => $hits_to_paginate, current_page_number => $current_page_number, pages => $pages ); - $template->param( PAGE_NUMBERS => $page_numbers, - last_page_offset => $last_page_offset, - previous_page_offset => $previous_page_offset) unless $pages < 2; - $template->param(next_page_offset => $next_page_offset) unless $pages eq $current_page_number; + $template->param( + PAGE_NUMBERS => $page_numbers, + last_page_offset => $last_page_offset, + previous_page_offset => $previous_page_offset + ) unless $pages < 2; + $template->param( next_page_offset => $next_page_offset ) unless $pages eq $current_page_number; } + # no hits else { my $nohits = C4::Context->preference('OPACNoResultsFound'); - if ($nohits and $nohits=~/{QUERY_KW}/){ + if ( $nohits and $nohits =~ /{QUERY_KW}/ ) { + # extracting keywords in case of relaunching search - (my $query_kw=$query_desc)=~s/ and|or / /g; - my @query_kw=($query_kw=~ /([-\w]+\b)(?:[^:]|$)/g); - $query_kw=join('+',@query_kw); - $nohits=~s/{QUERY_KW}/$query_kw/g; - $template->param('OPACNoResultsFound' =>$nohits); + ( my $query_kw = $query_desc ) =~ s/ and|or / /g; + my @query_kw = ( $query_kw =~ /([-\w]+\b)(?:[^:]|$)/g ); + $query_kw = join( '+', @query_kw ); + $nohits =~ s/{QUERY_KW}/$query_kw/g; + $template->param( 'OPACNoResultsFound' => $nohits ); } $template->param( searchdesc => 1, @@ -840,27 +890,30 @@ for (my $i=0;$i<@servers;$i++) { limit_cgi => $limit_cgi ); } - } # end of the if local - # asynchronously search the authority server - elsif ($server && $server =~/authorityserver/) { # this is the local authority server + } # end of the if local + # asynchronously search the authority server + elsif ( $server && $server =~ /authorityserver/ ) { # this is the local authority server my @inner_sup_results_array; - for my $sup_record ( @{$results_hashref->{$server}->{"RECORDS"}} ) { + for my $sup_record ( @{ $results_hashref->{$server}->{"RECORDS"} } ) { my $marc_record_object = MARC::Record->new_from_usmarc($sup_record); - my $title_field = $marc_record_object->field(100); + my $title_field = $marc_record_object->field(100); push @inner_sup_results_array, { 'title' => $title_field->subfield('a'), - 'link' => "&idx=an&q=".$marc_record_object->field('001')->as_string(), + 'link' => "&idx=an&q=" . $marc_record_object->field('001')->as_string(), }; } my $servername = $server; - push @sup_results_array, { servername => $servername, - inner_sup_results_loop => \@inner_sup_results_array} if @inner_sup_results_array; + push @sup_results_array, { + servername => $servername, + inner_sup_results_loop => \@inner_sup_results_array + } if @inner_sup_results_array; } - # FIXME: can add support for other targets as needed here - $template->param( outer_sup_results_loop => \@sup_results_array); -} #/end of the for loop -for my $facet ( @$facets ) { + # FIXME: can add support for other targets as needed here + $template->param( outer_sup_results_loop => \@sup_results_array ); +} #/end of the for loop + +for my $facet (@$facets) { for my $entry ( @{ $facet->{facets} } ) { my $index = $entry->{type_link_value}; my $value = $entry->{facet_link_value}; @@ -868,29 +921,29 @@ for my $facet ( @$facets ) { } } -my @search_filters = Koha::SearchFilters->search({ opac => 1 }, { order_by => "name" })->as_list; +my @search_filters = Koha::SearchFilters->search( { opac => 1 }, { order_by => "name" } )->as_list; my %active_filters; -foreach my $sf (@search_filters){ - $active_filters{$sf->id} = 1 if grep { "search_filter:".$sf->id eq $_->{input_value} } @limit_inputs; +foreach my $sf (@search_filters) { + $active_filters{ $sf->id } = 1 if grep { "search_filter:" . $sf->id eq $_->{input_value} } @limit_inputs; } $template->param( search_filters => \@search_filters, active_filters => \%active_filters, ) if C4::Context->preference('SavedSearchFilters'); - $template->param( - #classlist => $classlist, - total => $total, - opacfacets => 1, - facets_loop => $facets, - displayFacetCount=> C4::Context->preference('displayFacetCount')||0, - scan => $scan, - search_error => $error, + + #classlist => $classlist, + total => $total, + opacfacets => 1, + facets_loop => $facets, + displayFacetCount => C4::Context->preference('displayFacetCount') || 0, + scan => $scan, + search_error => $error, ); -if ($query_desc || $limit_desc) { - $template->param(searchdesc => 1); +if ( $query_desc || $limit_desc ) { + $template->param( searchdesc => 1 ); } # VI. BUILD THE TEMPLATE @@ -914,15 +967,14 @@ $template->param( add_to_some_public_shelves => $some_public_shelves, ); -my $content_type = ($format eq 'rss' or $format eq 'atom' or $format eq 'opensearchdescription') ? $format : 'html'; +my $content_type = ( $format eq 'rss' or $format eq 'atom' or $format eq 'opensearchdescription' ) ? $format : 'html'; $template->{VARS}->{DidYouMean} = - ( defined C4::Context->preference('OPACdidyoumean') - && C4::Context->preference('OPACdidyoumean') =~ m/enable/ ); + ( defined C4::Context->preference('OPACdidyoumean') && C4::Context->preference('OPACdidyoumean') =~ m/enable/ ); -if ($offset == 0) { - $template->param(firstPage => 1); +if ( $offset == 0 ) { + $template->param( firstPage => 1 ); } - $template->param( borrowernumber => $borrowernumber); +$template->param( borrowernumber => $borrowernumber ); output_with_http_headers $cgi, $cookie, $template->output, $content_type; diff --git a/opac/opac-sendbasket.pl b/opac/opac-sendbasket.pl index 0dad061093..466870b8d8 100755 --- a/opac/opac-sendbasket.pl +++ b/opac/opac-sendbasket.pl @@ -42,7 +42,7 @@ my ( $template, $borrowernumber, $cookie ) = get_template_and_user( my $patron = Koha::Patrons->find($borrowernumber); my $user_email = $patron ? $patron->notice_email_address : undef; -my $op = $query->param('op') || q{}; +my $op = $query->param('op') || q{}; my $bib_list = $query->param('bib_list') || ''; my $email_add = $query->param('email_add'); @@ -59,8 +59,7 @@ if ( $op eq "cud-send" && $email_add && $user_email ) { if ( !defined $iso2709 ) { $template->param( error => 'NO_BODY' ); - } - else { + } else { my %loops = ( biblio => \@bibs, ); my %substitute = ( comment => $comment, ); @@ -100,9 +99,9 @@ if ( $op eq "cud-send" && $email_add && $user_email ) { $template->param( email_add => $email_add ); output_html_with_http_headers $query, $cookie, $template->output, undef, - { force_no_caching => 1 }; + { force_no_caching => 1 }; -} elsif( !$user_email ) { +} elsif ( !$user_email ) { $template->param( email_add => 1, error => 'NO_REPLY_ADDRESS' ); output_html_with_http_headers $query, $cookie, $template->output; @@ -115,5 +114,5 @@ if ( $op eq "cud-send" && $email_add && $user_email ) { virtualshelves => C4::Context->preference("virtualshelves"), ); output_html_with_http_headers $query, $cookie, $template->output, undef, - { force_no_caching => 1 }; + { force_no_caching => 1 }; } diff --git a/opac/opac-sendshelf.pl b/opac/opac-sendshelf.pl index 0a03d23f41..6674509c99 100755 --- a/opac/opac-sendshelf.pl +++ b/opac/opac-sendshelf.pl @@ -21,14 +21,14 @@ use Modern::Perl; use CGI qw ( -utf8 ); use Encode; -use Carp qw( carp ); +use Carp qw( carp ); use Try::Tiny qw( catch try ); -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Biblio qw( - GetFrameworkCode - GetMarcISBN - GetMarcSubjects + GetFrameworkCode + GetMarcISBN + GetMarcSubjects ); use C4::Output qw( output_html_with_http_headers ); use Koha::Biblios; @@ -77,12 +77,10 @@ if ( $shelf and $shelf->can_be_viewed($borrowernumber) ) { if ( !defined $iso2709 ) { carp "Error sending mail: empty list"; $template->param( error => 1 ); - } - elsif ( !defined $user_email or $user_email eq '' ) { + } elsif ( !defined $user_email or $user_email eq '' ) { carp "Error sending mail: sender's email address is invalid"; $template->param( error => 1 ); - } - else { + } else { my %loops = ( biblio => \@biblionumbers, ); my %substitute = ( @@ -129,23 +127,21 @@ if ( $shelf and $shelf->can_be_viewed($borrowernumber) ) { email => $email, ); output_html_with_http_headers $query, $cookie, $template->output, - undef, { force_no_caching => 1 }; + undef, { force_no_caching => 1 }; - } - else { + } else { $template->param( shelfid => $shelfid, url => "/cgi-bin/koha/opac-sendshelf.pl", ); output_html_with_http_headers $query, $cookie, $template->output, - undef, { force_no_caching => 1 }; + undef, { force_no_caching => 1 }; } -} -else { +} else { $template->param( invalidlist => 1, url => "/cgi-bin/koha/opac-sendshelf.pl", ); output_html_with_http_headers $query, $cookie, $template->output, undef, - { force_no_caching => 1 }; + { force_no_caching => 1 }; } diff --git a/opac/opac-serial-issues.pl b/opac/opac-serial-issues.pl index b84b176498..4f389e7295 100755 --- a/opac/opac-serial-issues.pl +++ b/opac/opac-serial-issues.pl @@ -17,12 +17,12 @@ # You should have received a copy of the GNU General Public License # along with Koha; if not, see . - use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Auth qw( get_template_and_user ); -use C4::Serials qw( GetFullSubscription GetFullSubscriptionsFromBiblionumber PrepareSerialsData GetSubscription GetSubscriptionsFromBiblionumber ); +use C4::Serials + qw( GetFullSubscription GetFullSubscriptionsFromBiblionumber PrepareSerialsData GetSubscription GetSubscriptionsFromBiblionumber ); use C4::Output qw( output_html_with_http_headers ); use C4::Context; @@ -44,12 +44,13 @@ if ( $selectview eq "full" ) { authnotrequired => 1, } ); - my $subscriptions = GetFullSubscriptionsFromBiblionumber($biblionumber); - my $subscriptioninformation=PrepareSerialsData($subscriptions); + my $subscriptions = GetFullSubscriptionsFromBiblionumber($biblionumber); + my $subscriptioninformation = PrepareSerialsData($subscriptions); + # PrepareSerialsData does some bogus stuff that the template could handle # But at least it sorts the array by the year field so we dont have to # find 'manage' if its there - if ($subscriptioninformation->[0]->{year} eq 'manage') { + if ( $subscriptioninformation->[0]->{year} eq 'manage' ) { shift @{$subscriptioninformation}; } @@ -57,14 +58,14 @@ if ( $selectview eq "full" ) { if ($loggedinuser) { foreach (@$subscriptions) { my $subscription = Koha::Subscriptions->find( $_->{subscriptionid} ); - my $subscriber = $subscription->subscribers->find( $loggedinuser ); + my $subscriber = $subscription->subscribers->find($loggedinuser); $_->{hasalert} = 1 if $subscriber; } } my $title = $subscriptions->[0]->{bibliotitle}; my $yearmin = $subscriptions->[0]->{year}; - my $yearmax = $subscriptions->[ -1 ]->{year}; + my $yearmax = $subscriptions->[-1]->{year}; $template->param( biblionumber => scalar $query->param('biblionumber'), @@ -76,8 +77,7 @@ if ( $selectview eq "full" ) { virtualshelves => C4::Context->preference("virtualshelves"), ); -} -else { +} else { ( $template, $loggedinuser, $cookie ) = get_template_and_user( { template_name => "opac-serial-issues.tt", @@ -88,21 +88,22 @@ else { ); my $subscriptions = GetSubscriptionsFromBiblionumber($biblionumber); + # now, check is there is an alert subscription for one of the subscriptions if ($loggedinuser) { foreach (@$subscriptions) { my $subscription = Koha::Subscriptions->find( $_->{subscriptionid} ); - my $subscriber = $subscription->subscribers->find( $loggedinuser ); + my $subscriber = $subscription->subscribers->find($loggedinuser); $_->{hasalert} = 1 if $subscriber; } } - my $title = $subscriptions->[0]->{bibliotitle}; + my $title = $subscriptions->[0]->{bibliotitle}; $template->param( biblionumber => scalar $query->param('biblionumber'), subscription_LOOP => $subscriptions, - bibliotitle => $title, + bibliotitle => $title, ); } output_html_with_http_headers $query, $cookie, $template->output; diff --git a/opac/opac-shareshelf.pl b/opac/opac-shareshelf.pl index 25b739f384..c4dec0c18d 100755 --- a/opac/opac-shareshelf.pl +++ b/opac/opac-shareshelf.pl @@ -19,7 +19,7 @@ use Modern::Perl; -use constant KEYLENGTH => 10; +use constant KEYLENGTH => 10; use constant SHELVES_URL => '/cgi-bin/koha/opac-shelves.pl?display=privateshelves&viewshelf='; use CGI qw ( -utf8 ); @@ -36,7 +36,7 @@ use Koha::Virtualshelfshares; # if virtualshelves is disabled, leave immediately our $query = CGI->new; -if ( ! C4::Context->preference('virtualshelves') ) { +if ( !C4::Context->preference('virtualshelves') ) { print $query->redirect("/cgi-bin/koha/errors/404.pl"); exit; } @@ -50,9 +50,9 @@ my $pvar = _init(); ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => 'opac-shareshelf.tt', - query => $query, - type => "opac", + template_name => 'opac-shareshelf.tt', + query => $query, + type => "opac", } ); @@ -70,9 +70,9 @@ output_html_with_http_headers $query, $cookie, $template->output, undef, { force sub _init { my $param = {}; - $param->{shelfnumber} = $query->param('shelfnumber') || 0; + $param->{shelfnumber} = $query->param('shelfnumber') || 0; $param->{addrlist} = $query->param('invite_address') || ''; - $param->{key} = $query->param('key') || ''; + $param->{key} = $query->param('key') || ''; $param->{appr_addr} = []; $param->{fail_addr} = []; $param->{errcode} = check_common_errors($param); @@ -86,10 +86,10 @@ sub _init { #get some list details my $shelf; my $shelfnumber = $param->{shelfnumber}; - $shelf = Koha::Virtualshelves->find( $shelfnumber ) unless $param->{errcode}; + $shelf = Koha::Virtualshelves->find($shelfnumber) unless $param->{errcode}; $param->{shelfname} = $shelf ? $shelf->shelfname : q||; - $param->{owner} = $shelf ? $shelf->owner : -1; - $param->{public} = $shelf ? $shelf->public : 0; + $param->{owner} = $shelf ? $shelf->owner : -1; + $param->{public} = $shelf ? $shelf->public : 0; return $param; } @@ -120,8 +120,7 @@ sub confirm_invite { if ( @{ $param->{appr_addr} } ) { send_invitekey($param); $op = 'invited'; - } - else { + } else { $param->{errcode} = 6; #not one valid address } } @@ -132,11 +131,13 @@ sub show_accept { # Main reason for checking the key here is not to expose shelfname # to people who dont have the key - my $key = keytostring( stringtokey( $param->{key}, 0 ), 1 ); - my $shared_shelves = Koha::Virtualshelfshares->search({ - shelfnumber => $param->{shelfnumber}, - invitekey => $key, - }); + my $key = keytostring( stringtokey( $param->{key}, 0 ), 1 ); + my $shared_shelves = Koha::Virtualshelfshares->search( + { + shelfnumber => $param->{shelfnumber}, + invitekey => $key, + } + ); return if $shared_shelves->count; $param->{errcode} = 7; # not accepted: key invalid or expired } @@ -145,31 +146,35 @@ sub handle_accept { my ($param) = @_; my $shelfnumber = $param->{shelfnumber}; - my $shelf = Koha::Virtualshelves->find( $shelfnumber ); + my $shelf = Koha::Virtualshelves->find($shelfnumber); # The key for accepting is checked later in Koha::Virtualshelfshare # You must not be the owner and the list must be private - if( !$shelf ) { + if ( !$shelf ) { $param->{errcode} = 2; - } elsif( $shelf->public ) { + } elsif ( $shelf->public ) { $param->{errcode} = 5; - } elsif( $shelf->owner == $loggedinuser ) { + } elsif ( $shelf->owner == $loggedinuser ) { $param->{errcode} = 8; } return if $param->{errcode}; # Look for shelfnumber and invitekey in shares, expiration check later - my $key = keytostring( stringtokey( $param->{key}, 0 ), 1 ); - my $shared_shelves = Koha::Virtualshelfshares->search({ - shelfnumber => $param->{shelfnumber}, - invitekey => $key, - }); - my $shared_shelf = $shared_shelves ? $shared_shelves->next : undef; # we pick the first, but there should only be one + my $key = keytostring( stringtokey( $param->{key}, 0 ), 1 ); + my $shared_shelves = Koha::Virtualshelfshares->search( + { + shelfnumber => $param->{shelfnumber}, + invitekey => $key, + } + ); + my $shared_shelf = + $shared_shelves ? $shared_shelves->next : undef; # we pick the first, but there should only be one - if ( $shared_shelf ) { + if ($shared_shelf) { my $is_accepted = eval { $shared_shelf->accept( $key, $loggedinuser ) }; - if( $is_accepted ) { + if ($is_accepted) { notify_owner($param); + #redirect to view of this shared list print $query->redirect( -uri => SHELVES_URL . $param->{shelfnumber}, @@ -178,7 +183,7 @@ sub handle_accept { exit; } } - $param->{errcode} = 7; # not accepted: key invalid or expired + $param->{errcode} = 7; # not accepted: key invalid or expired } sub notify_owner { @@ -196,7 +201,7 @@ sub notify_owner { branchcode => C4::Context->userenv->{"branch"}, lang => $patron->lang, tables => { borrowers => $loggedinuser, }, - substitute => { listname => $param->{shelfname}, }, + substitute => { listname => $param->{shelfname}, }, ); #send letter to queue @@ -204,15 +209,15 @@ sub notify_owner { { letter => $letter, message_transport_type => 'email', - from_address => C4::Context->preference('KohaAdminEmailAddress'), - to_address => $toaddr, + from_address => C4::Context->preference('KohaAdminEmailAddress'), + to_address => $toaddr, } ); } sub process_addrlist { my ($param) = @_; - my @temp = split /[,:;]/, $param->{addrlist}; + my @temp = split /[,:;]/, $param->{addrlist}; my @appr_addr; my @fail_addr; foreach my $a (@temp) { @@ -220,8 +225,7 @@ sub process_addrlist { $a =~ s/\s+$//; if ( Koha::Email->is_valid($a) ) { push @appr_addr, $a; - } - else { + } else { push @fail_addr, $a; } } @@ -233,10 +237,10 @@ sub send_invitekey { my ($param) = @_; my $fromaddr = C4::Context->preference('KohaAdminEmailAddress'); my $url = - C4::Context->preference('OPACBaseURL') - . "/cgi-bin/koha/opac-shareshelf.pl?shelfnumber=" - . $param->{shelfnumber} - . "&op=accept&key="; + C4::Context->preference('OPACBaseURL') + . "/cgi-bin/koha/opac-shareshelf.pl?shelfnumber=" + . $param->{shelfnumber} + . "&op=accept&key="; #TODO Waiting for the right http or https solution (BZ 8952 a.o.) @@ -245,9 +249,10 @@ sub send_invitekey { my @newkey = randomlist( KEYLENGTH, 64 ); #generate a new key #add a preliminary share record - my $shelf = Koha::Virtualshelves->find( $param->{shelfnumber} ); - my $key = keytostring( \@newkey, 1 ); - my $is_shared = eval { $shelf->share( $key ); }; + my $shelf = Koha::Virtualshelves->find( $param->{shelfnumber} ); + my $key = keytostring( \@newkey, 1 ); + my $is_shared = eval { $shelf->share($key); }; + # TODO Better error handling, catch the exceptions if ( $@ or not $is_shared ) { push @{ $param->{fail_addr} }, $a; @@ -260,7 +265,7 @@ sub send_invitekey { module => 'lists', letter_code => 'SHARE_INVITE', branchcode => C4::Context->userenv->{"branch"}, - lang => 'default', # Not sure how we could use something more useful else here + lang => 'default', # Not sure how we could use something more useful else here tables => { borrowers => $loggedinuser, }, substitute => { listname => $param->{shelfname}, @@ -293,8 +298,8 @@ sub check_owner_category { sub load_template_vars { my ($param) = @_; - my $appr = join '; ', @{ $param->{appr_addr} }; - my $fail = join '; ', @{ $param->{fail_addr} }; + my $appr = join '; ', @{ $param->{appr_addr} }; + my $fail = join '; ', @{ $param->{fail_addr} }; $template->param( op => $op, errcode => $param->{errcode}, diff --git a/opac/opac-shelves.pl b/opac/opac-shelves.pl index 24f4ee90e9..e7dfc65c58 100755 --- a/opac/opac-shelves.pl +++ b/opac/opac-shelves.pl @@ -19,11 +19,11 @@ use Modern::Perl; -use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); -use C4::Biblio qw( GetBiblioData GetFrameworkCode ); +use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); +use C4::Biblio qw( GetBiblioData GetFrameworkCode ); use C4::External::BakerTaylor qw( image_url link_url ); -use C4::Koha qw( +use C4::Koha qw( GetNormalizedEAN GetNormalizedISBN GetNormalizedOCLCNumber @@ -31,8 +31,8 @@ use C4::Koha qw( ); use C4::Members; use C4::Output qw( pagination_bar output_with_http_headers ); -use C4::Tags qw( get_tags ); -use C4::XSLT qw( XSLTParse4Display ); +use C4::Tags qw( get_tags ); +use C4::XSLT qw( XSLTParse4Display ); use Koha::Biblios; use Koha::Biblioitems; @@ -46,8 +46,8 @@ use Koha::Virtualshelfshares; use Koha::Virtualshelves; use Koha::RecordProcessor; -use constant ANYONE => 2; -use constant STAFF => 3; +use constant ANYONE => 2; +use constant STAFF => 3; use constant PERMITTED => 4; my $query = CGI->new; @@ -55,7 +55,7 @@ my $query = CGI->new; my $template_name = $query->param('rss') ? "opac-shelves-rss.tt" : "opac-shelves.tt"; # if virtualshelves is disabled, leave immediately -if ( ! C4::Context->preference('virtualshelves') ) { +if ( !C4::Context->preference('virtualshelves') ) { print $query->redirect("/cgi-bin/koha/errors/404.pl"); exit; } @@ -63,23 +63,27 @@ if ( ! C4::Context->preference('virtualshelves') ) { my $op = $query->param('op') || 'list'; my ( $template, $loggedinuser, $cookie ); -if( $op eq 'view' || $op eq 'list' ){ - ( $template, $loggedinuser, $cookie ) = get_template_and_user({ +if ( $op eq 'view' || $op eq 'list' ) { + ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { template_name => $template_name, query => $query, type => "opac", authnotrequired => ( C4::Context->preference("OpacPublic") ? 1 : 0 ), - }); + } + ); } else { - ( $template, $loggedinuser, $cookie ) = get_template_and_user({ + ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { template_name => $template_name, query => $query, type => "opac", authnotrequired => 0, - }); + } + ); } -if (C4::Context->preference("BakerTaylorEnabled")) { +if ( C4::Context->preference("BakerTaylorEnabled") ) { $template->param( BakerTaylorImageURL => &image_url(), BakerTaylorLinkURL => &link_url(), @@ -95,17 +99,18 @@ my ( $shelf, $shelfnumber, @messages ); # PART 1: Perform a few actions if ( $op eq 'add_form' ) { + # Only pass default $shelf = { allow_change_from_owner => 1 }; } elsif ( $op eq 'edit_form' ) { $shelfnumber = $query->param('shelfnumber'); $shelf = Koha::Virtualshelves->find($shelfnumber); - if ( $shelf ) { + if ($shelf) { $public = $shelf->public; my $patron = Koha::Patrons->find( $shelf->owner ); $template->param( owner => $patron, ); - unless ( $shelf->can_be_managed( $loggedinuser ) ) { + unless ( $shelf->can_be_managed($loggedinuser) ) { push @messages, { type => 'error', code => 'unauthorized_on_update' }; $op = 'list'; } @@ -113,18 +118,19 @@ if ( $op eq 'add_form' ) { push @messages, { type => 'error', code => 'does_not_exist' }; } } elsif ( $op eq 'cud-add' ) { - if ( $loggedinuser ) { + if ($loggedinuser) { my $allow_changes_from = $query->param('allow_changes_from'); eval { $shelf = Koha::Virtualshelf->new( - { shelfname => scalar $query->param('shelfname'), - sortfield => scalar $query->param('sortfield'), - public => $public, - allow_change_from_owner => $allow_changes_from > 0, - allow_change_from_others => $allow_changes_from == ANYONE, - allow_change_from_staff => $allow_changes_from == STAFF, + { + shelfname => scalar $query->param('shelfname'), + sortfield => scalar $query->param('sortfield'), + public => $public, + allow_change_from_owner => $allow_changes_from > 0, + allow_change_from_others => $allow_changes_from == ANYONE, + allow_change_from_staff => $allow_changes_from == STAFF, allow_change_from_permitted_staff => $allow_changes_from == PERMITTED, - owner => scalar $loggedinuser, + owner => scalar $loggedinuser, } ); $shelf->store; @@ -145,19 +151,19 @@ if ( $op eq 'add_form' ) { } elsif ( $op eq 'cud-edit' ) { $shelfnumber = $query->param('shelfnumber'); $shelf = Koha::Virtualshelves->find($shelfnumber); - if ( $shelf ) { + if ($shelf) { $op = $referer; my $sortfield = $query->param('sortfield'); $sortfield = 'title' unless grep { $_ eq $sortfield } qw( title author copyrightdate itemcallnumber dateadded ); - if ( $shelf->can_be_managed( $loggedinuser ) ) { + if ( $shelf->can_be_managed($loggedinuser) ) { $shelf->shelfname( scalar $query->param('shelfname') ); - $shelf->sortfield( $sortfield ); + $shelf->sortfield($sortfield); my $allow_changes_from = $query->param('allow_changes_from'); $shelf->allow_change_from_owner( $allow_changes_from > 0 ); $shelf->allow_change_from_others( $allow_changes_from == ANYONE ); $shelf->allow_change_from_staff( $allow_changes_from == STAFF ); $shelf->allow_change_from_permitted_staff( $allow_changes_from == PERMITTED ); - $shelf->public( $public ); + $shelf->public($public); eval { $shelf->store }; if ($@) { @@ -176,7 +182,7 @@ if ( $op eq 'add_form' ) { $shelfnumber = $query->param('shelfnumber'); $shelf = Koha::Virtualshelves->find($shelfnumber); if ($shelf) { - if ( $shelf->can_be_deleted( $loggedinuser ) ) { + if ( $shelf->can_be_deleted($loggedinuser) ) { eval { $shelf->delete; }; if ($@) { push @messages, { type => 'error', code => ref($@), msg => $@ }; @@ -192,12 +198,12 @@ if ( $op eq 'add_form' ) { $op = $referer; } elsif ( $op eq 'cud-remove_share' ) { $shelfnumber = $query->param('shelfnumber'); - $shelf = Koha::Virtualshelves->find($shelfnumber); + $shelf = Koha::Virtualshelves->find($shelfnumber); if ($shelf) { - my $removed = eval { $shelf->remove_share( $loggedinuser ); }; + my $removed = eval { $shelf->remove_share($loggedinuser); }; if ($@) { push @messages, { type => 'error', code => ref($@), msg => $@ }; - } elsif ( $removed ) { + } elsif ($removed) { push @messages, { type => 'message', code => 'success_on_remove_share' }; } else { push @messages, { type => 'error', code => 'error_on_remove_share' }; @@ -209,16 +215,16 @@ if ( $op eq 'add_form' ) { } elsif ( $op eq 'cud-add_biblio' ) { $shelfnumber = $query->param('shelfnumber'); - $shelf = Koha::Virtualshelves->find($shelfnumber); + $shelf = Koha::Virtualshelves->find($shelfnumber); if ($shelf) { - if( my $barcode = $query->param('barcode') ) { - my $item = Koha::Items->find({ barcode => $barcode }); - if ( $item ) { - if ( $shelf->can_biblios_be_added( $loggedinuser ) ) { + if ( my $barcode = $query->param('barcode') ) { + my $item = Koha::Items->find( { barcode => $barcode } ); + if ($item) { + if ( $shelf->can_biblios_be_added($loggedinuser) ) { my $added = eval { $shelf->add_biblio( $item->biblionumber, $loggedinuser ); }; if ($@) { push @messages, { type => 'error', code => ref($@), msg => $@ }; - } elsif ( $added ) { + } elsif ($added) { push @messages, { type => 'message', code => 'success_on_add_biblio' }; } else { push @messages, { type => 'message', code => 'error_on_add_biblio' }; @@ -236,21 +242,21 @@ if ( $op eq 'add_form' ) { $op = $referer; } elsif ( $op eq 'cud-remove_biblios' ) { $shelfnumber = $query->param('shelfnumber'); - $shelf = Koha::Virtualshelves->find($shelfnumber); + $shelf = Koha::Virtualshelves->find($shelfnumber); my @biblionumber = $query->multi_param('biblionumber'); if ($shelf) { - if ( $shelf->can_biblios_be_removed( $loggedinuser ) ) { + if ( $shelf->can_biblios_be_removed($loggedinuser) ) { my $number_of_biblios_removed = eval { $shelf->remove_biblios( { - biblionumbers => \@biblionumber, + biblionumbers => \@biblionumber, borrowernumber => $loggedinuser, } ); }; if ($@) { push @messages, { type => 'error', code => ref($@), msg => $@ }; - } elsif ( $number_of_biblios_removed ) { + } elsif ($number_of_biblios_removed) { push @messages, { type => 'message', code => 'success_on_remove_biblios' }; } else { push @messages, { type => 'error', code => 'no_biblio_removed' }; @@ -262,36 +268,41 @@ if ( $op eq 'add_form' ) { push @messages, { type => 'error', code => 'does_not_exist' }; } $op = 'view'; -} elsif( $op eq 'cud-transfer' ) { +} elsif ( $op eq 'cud-transfer' ) { $shelfnumber = $query->param('shelfnumber'); - $shelf = Koha::Virtualshelves->find($shelfnumber) if $shelfnumber; - my $new_owner = $query->param('new_owner'); # borrowernumber or undef - my $error_code = $shelf - ? $shelf->cannot_be_transferred({ by => $loggedinuser, to => $new_owner, interface => 'opac' }) + $shelf = Koha::Virtualshelves->find($shelfnumber) if $shelfnumber; + my $new_owner = $query->param('new_owner'); # borrowernumber or undef + my $error_code = + $shelf + ? $shelf->cannot_be_transferred( { by => $loggedinuser, to => $new_owner, interface => 'opac' } ) : 'does_not_exist'; - if( !$new_owner && $error_code eq 'missing_to_parameter' ) { # show transfer form + if ( !$new_owner && $error_code eq 'missing_to_parameter' ) { # show transfer form my $patrons = []; - my $shares = $shelf->get_shares->search({ borrowernumber => { '!=' => undef } }); - while( my $share = $shares->next ) { + my $shares = $shelf->get_shares->search( { borrowernumber => { '!=' => undef } } ); + while ( my $share = $shares->next ) { my $email = $share->sharee->notice_email_address; push @$patrons, { email => $email, borrowernumber => $share->get_column('borrowernumber') } if $email; } - if( @$patrons ) { + if (@$patrons) { $template->param( shared_users => $patrons ); $op = 'cud-transfer'; } else { push @messages, { type => 'error', code => 'no_email_found' }; } - } elsif( $error_code ) { + } elsif ($error_code) { push @messages, { type => 'error', code => $error_code }; $op = 'list'; - } else { # transfer; remove new_owner from virtualshelfshares, add loggedinuser - $shelf->_result->result_source->schema->txn_do( sub { - $shelf->get_shares->search({ borrowernumber => $new_owner })->delete; - Koha::Virtualshelfshare->new({ shelfnumber => $shelfnumber, borrowernumber => $loggedinuser, sharedate => dt_from_string })->store; - $shelf->owner($new_owner)->store; - }); + } else { # transfer; remove new_owner from virtualshelfshares, add loggedinuser + $shelf->_result->result_source->schema->txn_do( + sub { + $shelf->get_shares->search( { borrowernumber => $new_owner } )->delete; + Koha::Virtualshelfshare->new( + { shelfnumber => $shelfnumber, borrowernumber => $loggedinuser, sharedate => dt_from_string } ) + ->store; + $shelf->owner($new_owner)->store; + } + ); $op = 'list'; } } @@ -300,21 +311,23 @@ if ( $op eq 'add_form' ) { if ( $op eq 'view' ) { $shelfnumber ||= $query->param('shelfnumber'); $shelf = Koha::Virtualshelves->find($shelfnumber); - if ( $shelf ) { - if ( $shelf->can_be_viewed( $loggedinuser ) ) { + if ($shelf) { + if ( $shelf->can_be_viewed($loggedinuser) ) { $public = $shelf->public; # Sortfield param may still include sort order with :asc or :desc, but direction overrides it - my( $sortfield, $direction ); - if( $query->param('sortfield') ){ + my ( $sortfield, $direction ); + if ( $query->param('sortfield') ) { ( $sortfield, $direction ) = split /:/, $query->param('sortfield'); } else { $sortfield = $shelf->sortfield; $direction = 'asc'; } $direction = $query->param('direction') if $query->param('direction'); - $direction = 'asc' if !$direction or ( $direction ne 'asc' and $direction ne 'desc' ); - $sortfield = 'title' if !$sortfield or !grep { $_ eq $sortfield } qw( title author copyrightdate itemcallnumber dateadded ); + $direction = 'asc' if !$direction or ( $direction ne 'asc' and $direction ne 'desc' ); + $sortfield = 'title' + if !$sortfield + or !grep { $_ eq $sortfield } qw( title author copyrightdate itemcallnumber dateadded ); my $rows; if ( $query->param('print') or $query->param('rss') ) { @@ -336,22 +349,23 @@ if ( $op eq 'view' ) { # get biblionumbers stored in the cart my @cart_list; - if(my $cart_list = $query->cookie('bib_list')){ - @cart_list = split(/\//, $cart_list); + if ( my $cart_list = $query->cookie('bib_list') ) { + @cart_list = split( /\//, $cart_list ); } - my $patron = Koha::Patrons->find( $loggedinuser ); + my $patron = Koha::Patrons->find($loggedinuser); - my $categorycode; # needed for may_article_request - if( C4::Context->preference('ArticleRequests') ) { + my $categorycode; # needed for may_article_request + if ( C4::Context->preference('ArticleRequests') ) { $categorycode = $patron ? $patron->categorycode : undef; } - my $record_processor = Koha::RecordProcessor->new({ filters => 'ViewPolicy' }); + my $record_processor = Koha::RecordProcessor->new( { filters => 'ViewPolicy' } ); my $art_req_itypes; - if( C4::Context->preference('ArticleRequests') ) { - $art_req_itypes = Koha::CirculationRules->guess_article_requestable_itemtypes({ $patron ? ( categorycode => $patron->categorycode ) : () }); + if ( C4::Context->preference('ArticleRequests') ) { + $art_req_itypes = Koha::CirculationRules->guess_article_requestable_itemtypes( + { $patron ? ( categorycode => $patron->categorycode ) : () } ); } my @items_info; @@ -363,26 +377,29 @@ if ( $op eq 'view' ) { my $framework = GetFrameworkCode($biblionumber); $record_processor->options( { - interface => 'opac', - frameworkcode => $framework - }); + interface => 'opac', + frameworkcode => $framework + } + ); $record_processor->process($record); my $marcflavour = C4::Context->preference("marcflavour"); - my $itemtype = Koha::Biblioitems->search({ biblionumber => $content->biblionumber })->next->itemtype; - $itemtype = Koha::ItemTypes->find( $itemtype ); - if( $itemtype ) { - $this_item->{imageurl} = C4::Koha::getitemtypeimagelocation( 'opac', $itemtype->imageurl ); - $this_item->{description} = $itemtype->description; #FIXME Should not it be translated_description? - $this_item->{notforloan} = $itemtype->notforloan; + my $itemtype = Koha::Biblioitems->search( { biblionumber => $content->biblionumber } )->next->itemtype; + $itemtype = Koha::ItemTypes->find($itemtype); + if ($itemtype) { + $this_item->{imageurl} = C4::Koha::getitemtypeimagelocation( 'opac', $itemtype->imageurl ); + $this_item->{description} = $itemtype->description; #FIXME Should not it be translated_description? + $this_item->{notforloan} = $itemtype->notforloan; } $this_item->{'coins'} = $biblio->get_coins; $this_item->{'normalized_upc'} = GetNormalizedUPC( $record, $marcflavour ); $this_item->{'normalized_ean'} = GetNormalizedEAN( $record, $marcflavour ); $this_item->{'normalized_oclc'} = GetNormalizedOCLCNumber( $record, $marcflavour ); $this_item->{'normalized_isbn'} = GetNormalizedISBN( undef, $record, $marcflavour ); + # BZ17530: 'Intelligent' guess if result can be article requested - $this_item->{artreqpossible} = ( $art_req_itypes->{ $this_item->{itemtype} // q{} } || $art_req_itypes->{ '*' } ) ? 1 : q{}; + $this_item->{artreqpossible} = + ( $art_req_itypes->{ $this_item->{itemtype} // q{} } || $art_req_itypes->{'*'} ) ? 1 : q{}; unless ( defined $this_item->{size} ) { @@ -390,29 +407,29 @@ if ( $op eq 'view' ) { $this_item->{size} = q||; } - if (C4::Context->preference('TagsEnabled') and C4::Context->preference('TagsShowOnList')) { - $this_item->{TagLoop} = get_tags({ - biblionumber => $biblionumber, approved=>1, 'sort'=>'-weight', - limit => C4::Context->preference('TagsShowOnList'), - }); + if ( C4::Context->preference('TagsEnabled') and C4::Context->preference('TagsShowOnList') ) { + $this_item->{TagLoop} = get_tags( + { + biblionumber => $biblionumber, approved => 1, 'sort' => '-weight', + limit => C4::Context->preference('TagsShowOnList'), + } + ); } - my $items = $biblio->items->filter_by_visible_in_opac({ patron => $patron }); + my $items = $biblio->items->filter_by_visible_in_opac( { patron => $patron } ); my $allow_onshelf_holds; while ( my $item = $items->next ) { # This method must take a Koha::Items rs - $allow_onshelf_holds ||= Koha::CirculationRules->get_onshelfholds_policy( - { item => $item, patron => $patron } ); + $allow_onshelf_holds ||= + Koha::CirculationRules->get_onshelfholds_policy( { item => $item, patron => $patron } ); } $this_item->{allow_onshelf_holds} = $allow_onshelf_holds; - $this_item->{'ITEM_RESULTS'} = $items; + $this_item->{'ITEM_RESULTS'} = $items; - my $variables = { - anonymous_session => ($loggedinuser) ? 0 : 1 - }; + my $variables = { anonymous_session => ($loggedinuser) ? 0 : 1 }; $this_item->{XSLTBloc} = XSLTParse4Display( { biblionumber => $biblionumber, @@ -424,20 +441,18 @@ if ( $op eq 'view' ) { } ); - - if ( grep {$_ eq $biblionumber} @cart_list) { + if ( grep { $_ eq $biblionumber } @cart_list ) { $this_item->{incart} = 1; } $this_item->{biblio_object} = $biblio; $this_item->{biblionumber} = $biblionumber; - $this_item->{shelves} = - Koha::Virtualshelves->get_shelves_containing_record( + $this_item->{shelves} = Koha::Virtualshelves->get_shelves_containing_record( { biblionumber => $biblionumber, borrowernumber => $loggedinuser, } - ); + ); push @items_info, $this_item; } @@ -449,20 +464,24 @@ if ( $op eq 'view' ) { itemsloop => \@items_info, sortfield => $sortfield, direction => $direction, - csv_profiles => Koha::CsvProfiles->search( + csv_profiles => Koha::CsvProfiles->search( { type => 'marc', used_for => 'export_records', staff_only => 0 } - ), + ), ); - if ( $page ) { + if ($page) { my $pager = $contents->pager; $template->param( pagination_bar => pagination_bar( - q||, $pager->last_page - $pager->first_page + 1, - $page, "page", { op => 'view', shelfnumber => $shelf->shelfnumber, sortfield => $sortfield, direction => $direction, } + q||, $pager->last_page - $pager->first_page + 1, + $page, "page", + { + op => 'view', shelfnumber => $shelf->shelfnumber, sortfield => $sortfield, + direction => $direction, + } ), ); } @@ -494,26 +513,27 @@ if ( $op eq 'view' ) { } } elsif ( $op eq 'list' ) { my $shelves; - my ( $rows ) = ( 20 ); + my ($rows) = (20); if ( !$public ) { - $shelves = Koha::Virtualshelves->get_private_shelves({ page => $page, rows => $rows, borrowernumber => $loggedinuser, }); + $shelves = Koha::Virtualshelves->get_private_shelves( + { page => $page, rows => $rows, borrowernumber => $loggedinuser, } ); } else { - $shelves = Koha::Virtualshelves->get_public_shelves({ page => $page, rows => $rows, }); + $shelves = Koha::Virtualshelves->get_public_shelves( { page => $page, rows => $rows, } ); } my $pager = $shelves->pager; $template->param( - shelves => $shelves, + shelves => $shelves, pagination_bar => pagination_bar( - q||, $pager->last_page - $pager->first_page + 1, + q||, $pager->last_page - $pager->first_page + 1, $page, "page", { op => 'list', public => $public, } ), ); } -my ($staffuser, $permitteduser); -$staffuser = Koha::Patrons->find( $loggedinuser )->can_patron_change_staff_only_lists if $loggedinuser; -$permitteduser = Koha::Patrons->find( $loggedinuser )->can_patron_change_permitted_staff_lists if $loggedinuser; +my ( $staffuser, $permitteduser ); +$staffuser = Koha::Patrons->find($loggedinuser)->can_patron_change_staff_only_lists if $loggedinuser; +$permitteduser = Koha::Patrons->find($loggedinuser)->can_patron_change_permitted_staff_lists if $loggedinuser; $template->param( op => $op, @@ -527,5 +547,5 @@ $template->param( permitteduser => $permitteduser ); -my $content_type = $query->param('rss')? 'rss' : 'html'; +my $content_type = $query->param('rss') ? 'rss' : 'html'; output_with_http_headers $query, $cookie, $template->output, $content_type; diff --git a/opac/opac-showmarc.pl b/opac/opac-showmarc.pl index 57c63fede1..745633a2c7 100755 --- a/opac/opac-showmarc.pl +++ b/opac/opac-showmarc.pl @@ -26,36 +26,38 @@ use Encode; # Koha modules used use C4::Context; use C4::Output qw( output_html_with_http_headers ); -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::ImportBatch; use C4::XSLT; use C4::Templates; use Koha::RecordProcessor; -my $input = CGI->new; -my ( $template, $loggedinuser, $cookie ) = get_template_and_user({ - template_name => "opac-showmarc.tt", - query => $input, - type => "opac", - authnotrequired => ( C4::Context->preference("OpacPublic") ? 1 : 0 ), -}); +my $input = CGI->new; +my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "opac-showmarc.tt", + query => $input, + type => "opac", + authnotrequired => ( C4::Context->preference("OpacPublic") ? 1 : 0 ), + } +); my $biblionumber = $input->param('id'); -unless ( $biblionumber ) { +unless ($biblionumber) { print $input->redirect("/cgi-bin/koha/errors/400.pl"); exit; } my $biblio; -$biblio = Koha::Biblios->find( $biblionumber, { prefetch => [ 'metadata' ] } ); +$biblio = Koha::Biblios->find( $biblionumber, { prefetch => ['metadata'] } ); -unless ( $biblio ) { +unless ($biblio) { print $input->redirect('/cgi-bin/koha/errors/404.pl'); exit; } -my $view= $input->param('viewas') || 'marc'; +my $view = $input->param('viewas') || 'marc'; my $record_processor = Koha::RecordProcessor->new( { @@ -69,22 +71,21 @@ my $record_processor = Koha::RecordProcessor->new( my $record = $biblio->metadata->record; -if(!ref $record) { +if ( !ref $record ) { print $input->redirect("/cgi-bin/koha/errors/404.pl"); exit; } $record_processor->process($record); -if ($view eq 'card' || $view eq 'html') { - my $xml = $record->as_xml; - my $xsl = $view eq 'card' ? 'compact.xsl' : 'plainMARC.xsl'; +if ( $view eq 'card' || $view eq 'html' ) { + my $xml = $record->as_xml; + my $xsl = $view eq 'card' ? 'compact.xsl' : 'plainMARC.xsl'; my $htdocs = C4::Context->config('opachtdocs'); - my ($theme, $lang) = C4::Templates::themelanguage($htdocs, $xsl, 'opac', $input); + my ( $theme, $lang ) = C4::Templates::themelanguage( $htdocs, $xsl, 'opac', $input ); $xsl = "$htdocs/$theme/$lang/xslt/$xsl"; - output_html_with_http_headers $input, undef, Encode::encode_utf8(C4::XSLT::engine->transform($xml, $xsl)); -} -else { #view eq marc + output_html_with_http_headers $input, undef, Encode::encode_utf8( C4::XSLT::engine->transform( $xml, $xsl ) ); +} else { #view eq marc $template->param( MARC_FORMATTED => $record->as_formatted ); output_html_with_http_headers $input, $cookie, $template->output; } diff --git a/opac/opac-showreviews.pl b/opac/opac-showreviews.pl index 7a72214bbf..590c3db576 100755 --- a/opac/opac-showreviews.pl +++ b/opac/opac-showreviews.pl @@ -20,7 +20,7 @@ use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Auth qw( get_template_and_user ); use C4::Koha qw( GetNormalizedEAN @@ -28,7 +28,7 @@ use C4::Koha qw( GetNormalizedOCLCNumber GetNormalizedUPC ); -use C4::Output qw( output_html_with_http_headers ); +use C4::Output qw( output_html_with_http_headers ); use Koha::DateUtils qw( dt_from_string ); use Koha::Biblios; use Koha::Patrons; @@ -36,17 +36,17 @@ use Koha::Reviews; use POSIX qw( ceil floor ); my $template_name; -my $query = CGI->new; -my $format = $query->param("format") || ''; -my $count = C4::Context->preference('OPACnumSearchResults') || 20; -my $results_per_page = $query->param('count') || $count; -my $offset = $query->param('offset') || 0; -my $page = floor( $offset / $results_per_page ) + 1; +my $query = CGI->new; +my $format = $query->param("format") || ''; +my $count = C4::Context->preference('OPACnumSearchResults') || 20; +my $results_per_page = $query->param('count') || $count; +my $offset = $query->param('offset') || 0; +my $page = floor( $offset / $results_per_page ) + 1; -if ($format eq "rss") { +if ( $format eq "rss" ) { $template_name = "opac-showreviews-rss.tt"; } else { - $template_name = "opac-showreviews.tt", + $template_name = "opac-showreviews.tt",; } my ( $template, $borrowernumber, $cookie ) = &get_template_and_user( @@ -58,17 +58,17 @@ my ( $template, $borrowernumber, $cookie ) = &get_template_and_user( } ); -if($format eq "rss"){ - my $lastbuilddate = dt_from_string; +if ( $format eq "rss" ) { + my $lastbuilddate = dt_from_string; my $lastbuilddate_output = $lastbuilddate->strftime("%a, %d %b %Y %H:%M:%S %z"); $template->param( - rss => 1, + rss => 1, timestamp => $lastbuilddate_output - ); + ); } my $libravatar_enabled = 0; -if ( C4::Context->preference('ShowReviewer') and C4::Context->preference('ShowReviewerPhoto')) { +if ( C4::Context->preference('ShowReviewer') and C4::Context->preference('ShowReviewerPhoto') ) { eval { require Libravatar::URL; Libravatar::URL->import(); @@ -81,115 +81,126 @@ if ( C4::Context->preference('ShowReviewer') and C4::Context->preference('ShowRe my $reviews = Koha::Reviews->search( { approved => 1 }, { - rows => $results_per_page, - page => $page, + rows => $results_per_page, + page => $page, order_by => { -desc => 'datereviewed' }, } )->unblessed; -my $marcflavour = C4::Context->preference("marcflavour"); -my $hits = Koha::Reviews->search({ approved => 1 })->count; -my $i = 0; -for my $result (@$reviews){ +my $marcflavour = C4::Context->preference("marcflavour"); +my $hits = Koha::Reviews->search( { approved => 1 } )->count; +my $i = 0; +for my $result (@$reviews) { my $biblionumber = $result->{biblionumber}; - my $biblio = Koha::Biblios->find( $biblionumber ); - my $biblioitem = $biblio->biblioitem; - my $record = $biblio->metadata->record; - $result->{normalized_upc} = GetNormalizedUPC($record,$marcflavour); - $result->{normalized_ean} = GetNormalizedEAN($record,$marcflavour); - $result->{normalized_oclc} = GetNormalizedOCLCNumber($record,$marcflavour); - $result->{normalized_isbn} = GetNormalizedISBN(undef,$record,$marcflavour); - $result->{title} = $biblio->title; - $result->{subtitle} = $biblio->subtitle; - $result->{medium} = $biblio->medium; - $result->{part_number} = $biblio->part_number; - $result->{part_name} = $biblio->part_name; - $result->{author} = $biblio->author; - $result->{place} = $biblioitem->place; - $result->{publishercode} = $biblioitem->publishercode; - $result->{copyrightdate} = $biblio->copyrightdate; - $result->{pages} = $biblioitem->pages; - $result->{size} = $biblioitem->size; - $result->{notes} = $biblioitem->notes; - $result->{timestamp} = $biblioitem->timestamp; + my $biblio = Koha::Biblios->find($biblionumber); + my $biblioitem = $biblio->biblioitem; + my $record = $biblio->metadata->record; + $result->{normalized_upc} = GetNormalizedUPC( $record, $marcflavour ); + $result->{normalized_ean} = GetNormalizedEAN( $record, $marcflavour ); + $result->{normalized_oclc} = GetNormalizedOCLCNumber( $record, $marcflavour ); + $result->{normalized_isbn} = GetNormalizedISBN( undef, $record, $marcflavour ); + $result->{title} = $biblio->title; + $result->{subtitle} = $biblio->subtitle; + $result->{medium} = $biblio->medium; + $result->{part_number} = $biblio->part_number; + $result->{part_name} = $biblio->part_name; + $result->{author} = $biblio->author; + $result->{place} = $biblioitem->place; + $result->{publishercode} = $biblioitem->publishercode; + $result->{copyrightdate} = $biblio->copyrightdate; + $result->{pages} = $biblioitem->pages; + $result->{size} = $biblioitem->size; + $result->{notes} = $biblioitem->notes; + $result->{timestamp} = $biblioitem->timestamp; - $result->{biblio_object} = $biblio; # TODO Use this variable directly in the template + $result->{biblio_object} = $biblio; # TODO Use this variable directly in the template my $patron = Koha::Patrons->find( $result->{borrowernumber} ); - if ( $patron ) { + if ($patron) { $result->{borrtitle} = $patron->title; $result->{firstname} = $patron->firstname; - $result->{surname} = $patron->surname; - $result->{userid} = $patron->userid; - if ($libravatar_enabled and $patron->email) { - $result->{avatarurl} = libravatar_url(email => $patron->email, size => 40, https => $ENV{HTTPS}); - } + $result->{surname} = $patron->surname; + $result->{userid} = $patron->userid; + if ( $libravatar_enabled and $patron->email ) { + $result->{avatarurl} = libravatar_url( email => $patron->email, size => 40, https => $ENV{HTTPS} ); + } - if ($result->{borrowernumber} eq $borrowernumber) { + if ( $result->{borrowernumber} eq $borrowernumber ) { $result->{your_comment} = 1; } } - if($format eq "rss"){ + if ( $format eq "rss" ) { my $rsstimestamp = eval { dt_from_string( $result->{datereviewed} ); }; - $rsstimestamp = dt_from_string unless ( $rsstimestamp ); #default to today if something went wrong + $rsstimestamp = dt_from_string unless ($rsstimestamp); #default to today if something went wrong my $rsstimestamp_output = $rsstimestamp->strftime("%a, %d %b %Y %H:%M:%S %z"); $result->{timestamp} = $rsstimestamp_output; } } ## Build the page numbers on the bottom of the page - my @page_numbers; - my $previous_page_first; - my $previous_page_offset; - # total number of pages there will be - my $pages = ceil($hits / $results_per_page); - # default page number - my $current_page_number = 1; - $current_page_number = ($offset / $results_per_page + 1) if $offset; - if($offset - $results_per_page == 0){ - $previous_page_first = 1; - } elsif ($offset - $results_per_page > 0){ - $previous_page_offset = $offset - $results_per_page; - } - my $next_page_offset = $offset + $results_per_page; - # If we're within the first 10 pages, keep it simple - if ($current_page_number < 10) { - # just show the first 10 pages - # Loop through the pages - my $pages_to_show = 10; - $pages_to_show = $pages if $pages<10; - for ($i=1; $i<=$pages_to_show;$i++) { - # the offset for this page - my $this_offset = (($i*$results_per_page)-$results_per_page); - # the page number for this page - my $this_page_number = $i; - # it should only be highlighted if it's the current page - my $highlight; - $highlight = 1 if ($this_page_number == $current_page_number); - # put it in the array - push @page_numbers, { offset => $this_offset, pg => $this_page_number, highlight => $highlight }; +my @page_numbers; +my $previous_page_first; +my $previous_page_offset; - } +# total number of pages there will be +my $pages = ceil( $hits / $results_per_page ); - } - # now, show twenty pages, with the current one smack in the middle - else { - for ($i=$current_page_number; $i<=($current_page_number + 20 );$i++) { - my $this_offset = ((($i-9)*$results_per_page)-$results_per_page); - my $this_page_number = $i-9; - my $highlight; - $highlight = 1 if ($this_page_number == $current_page_number); - if ($this_page_number <= $pages) { - push @page_numbers, { offset => $this_offset, pg => $this_page_number, highlight => $highlight }; - } - } - } -$template->param( PAGE_NUMBERS => \@page_numbers, - previous_page_first => $previous_page_first, - previous_page_offset => $previous_page_offset) unless $pages < 2; -$template->param(next_page_offset => $next_page_offset) unless $pages eq $current_page_number; +# default page number +my $current_page_number = 1; +$current_page_number = ( $offset / $results_per_page + 1 ) if $offset; +if ( $offset - $results_per_page == 0 ) { + $previous_page_first = 1; +} elsif ( $offset - $results_per_page > 0 ) { + $previous_page_offset = $offset - $results_per_page; +} +my $next_page_offset = $offset + $results_per_page; + +# If we're within the first 10 pages, keep it simple +if ( $current_page_number < 10 ) { + + # just show the first 10 pages + # Loop through the pages + my $pages_to_show = 10; + $pages_to_show = $pages if $pages < 10; + for ( $i = 1 ; $i <= $pages_to_show ; $i++ ) { + + # the offset for this page + my $this_offset = ( ( $i * $results_per_page ) - $results_per_page ); + + # the page number for this page + my $this_page_number = $i; + + # it should only be highlighted if it's the current page + my $highlight; + $highlight = 1 if ( $this_page_number == $current_page_number ); + + # put it in the array + push @page_numbers, { offset => $this_offset, pg => $this_page_number, highlight => $highlight }; + + } + +} + +# now, show twenty pages, with the current one smack in the middle +else { + for ( $i = $current_page_number ; $i <= ( $current_page_number + 20 ) ; $i++ ) { + my $this_offset = ( ( ( $i - 9 ) * $results_per_page ) - $results_per_page ); + my $this_page_number = $i - 9; + my $highlight; + $highlight = 1 if ( $this_page_number == $current_page_number ); + if ( $this_page_number <= $pages ) { + push @page_numbers, { offset => $this_offset, pg => $this_page_number, highlight => $highlight }; + } + } +} +$template->param( + PAGE_NUMBERS => \@page_numbers, + previous_page_first => $previous_page_first, + previous_page_offset => $previous_page_offset +) unless $pages < 2; +$template->param( next_page_offset => $next_page_offset ) unless $pages eq $current_page_number; $template->param( - reviews => $reviews, + reviews => $reviews, results_per_page => $results_per_page, ); diff --git a/opac/opac-suggestions.pl b/opac/opac-suggestions.pl index 528bd9ccd7..775affbe8c 100755 --- a/opac/opac-suggestions.pl +++ b/opac/opac-suggestions.pl @@ -17,13 +17,12 @@ use Modern::Perl; - use CGI qw ( -utf8 ); use Encode; use C4::Auth qw( get_template_and_user ); use C4::Members; -use C4::Koha qw( GetAuthorisedValues ); -use C4::Output qw( output_html_with_http_headers ); +use C4::Koha qw( GetAuthorisedValues ); +use C4::Output qw( output_html_with_http_headers ); use C4::Suggestions qw( DelSuggestion MarcRecordFromNewSuggestion @@ -39,13 +38,13 @@ use Koha::Suggestions; use Koha::DateUtils qw( dt_from_string ); -my $input = CGI->new; -my $op = $input->param('op') || 'else'; -my $biblionumber = $input->param('biblionumber'); -my $negcaptcha = $input->param('negcap'); +my $input = CGI->new; +my $op = $input->param('op') || 'else'; +my $biblionumber = $input->param('biblionumber'); +my $negcaptcha = $input->param('negcap'); my $suggested_by_anyone = $input->param('suggested_by_anyone') || 0; -my $title_filter = $input->param('title_filter'); -my $need_confirm = 0; +my $title_filter = $input->param('title_filter'); +my $need_confirm = 0; my $suggestion = { biblionumber => scalar $input->param('biblionumber'), @@ -64,16 +63,22 @@ my $suggestion = { }; # If a spambot accidentally populates the 'negcap' field in the suggestions form, then silently skip and return. -if ($negcaptcha ) { +if ($negcaptcha) { print $input->redirect("/cgi-bin/koha/opac-suggestions.pl"); exit; } my ( $template, $borrowernumber, $cookie, @messages ); -my $deleted = $input->param('deleted'); +my $deleted = $input->param('deleted'); my $submitted = $input->param('submitted'); -if ( ( C4::Context->preference("AnonSuggestions") and Koha::Patrons->find( C4::Context->preference("AnonymousPatron") ) ) or ( C4::Context->preference("OPACViewOthersSuggestions") and $op eq 'else' ) ) { +if ( + ( + C4::Context->preference("AnonSuggestions") and Koha::Patrons->find( C4::Context->preference("AnonymousPatron") ) + ) + or ( C4::Context->preference("OPACViewOthersSuggestions") and $op eq 'else' ) + ) +{ ( $template, $borrowernumber, $cookie ) = get_template_and_user( { template_name => "opac-suggestions.tt", @@ -82,20 +87,19 @@ if ( ( C4::Context->preference("AnonSuggestions") and Koha::Patrons->find( C4::C authnotrequired => ( C4::Context->preference("OpacPublic") ? 1 : 0 ), } ); -} -else { +} else { ( $template, $borrowernumber, $cookie ) = get_template_and_user( { - template_name => "opac-suggestions.tt", - query => $input, - type => "opac", + template_name => "opac-suggestions.tt", + query => $input, + type => "opac", } ); } # If suggestions are turned off, or this patron belongs to a category not allowed to make suggestions (suggestionPatronCategoryExceptions syspref) we redirect to 404 error. This will also redirect guest suggestions if ( defined $borrowernumber && !C4::Context->preference('AnonSuggestions') ) { - if ( (!Koha::Patrons->find( $borrowernumber )->category->can_make_suggestions) ) { + if ( ( !Koha::Patrons->find($borrowernumber)->category->can_make_suggestions ) ) { print $input->redirect("/cgi-bin/koha/errors/404.pl"); exit; } @@ -104,27 +108,27 @@ if ( defined $borrowernumber && !C4::Context->preference('AnonSuggestions') ) { my $suggested_by; if ( $op eq 'else' ) { if ( C4::Context->preference("OPACViewOthersSuggestions") ) { - if ( $borrowernumber ) { + if ($borrowernumber) { + # A logged in user is able to see suggestions from others - $suggested_by = $suggested_by_anyone + $suggested_by = + $suggested_by_anyone ? undef : $borrowernumber; } + # else: Non logged in user is able to see all suggestions - } - else { - if ( $borrowernumber ) { + } else { + if ($borrowernumber) { $suggested_by = $borrowernumber; - } - else { + } else { $suggested_by = -1; } } } else { - if ( $borrowernumber ) { + if ($borrowernumber) { $suggested_by = $borrowernumber; - } - else { + } else { $suggested_by = C4::Context->preference("AnonymousPatron"); } } @@ -132,60 +136,68 @@ if ( $op eq 'else' ) { $suggestion = { map { my $p = $suggestion->{$_}; + # Keep parameters that are not an empty string ( defined $p && $p ne '' ? ( $_ => $p ) : () ) } keys %$suggestion }; $suggestion->{suggestedby} = $borrowernumber; -if ( $op eq "cud-add_validate" && not $biblionumber ) { # If we are creating the suggestion from an existing record we do not want to search for duplicates +if ( $op eq "cud-add_validate" && not $biblionumber ) +{ # If we are creating the suggestion from an existing record we do not want to search for duplicates $op = 'cud-add_confirm'; my $biblio = MarcRecordFromNewSuggestion($suggestion); - if ( my ($duplicatebiblionumber, $duplicatetitle) = FindDuplicate($biblio) ) { - push @messages, { type => 'error', code => 'biblio_exists', id => $duplicatebiblionumber, title => $duplicatetitle }; + if ( my ( $duplicatebiblionumber, $duplicatetitle ) = FindDuplicate($biblio) ) { + push @messages, + { type => 'error', code => 'biblio_exists', id => $duplicatebiblionumber, title => $duplicatetitle }; $need_confirm = 1; - $op = 'add_form'; + $op = 'add_form'; } } my $patrons_pending_suggestions_count = 0; -my $patrons_total_suggestions_count = 0; -if ( $borrowernumber ){ - if ( C4::Context->preference("MaxTotalSuggestions") ne '' && C4::Context->preference("NumberOfSuggestionDays") ne '' ) { - my $suggesteddate_from = dt_from_string()->subtract(days=>C4::Context->preference("NumberOfSuggestionDays")); - $patrons_total_suggestions_count = Koha::Suggestions->search({ suggestedby => $borrowernumber, suggesteddate => { '>=' => $suggesteddate_from } })->count; +my $patrons_total_suggestions_count = 0; +if ($borrowernumber) { + if ( C4::Context->preference("MaxTotalSuggestions") ne '' + && C4::Context->preference("NumberOfSuggestionDays") ne '' ) + { + my $suggesteddate_from = + dt_from_string()->subtract( days => C4::Context->preference("NumberOfSuggestionDays") ); + $patrons_total_suggestions_count = Koha::Suggestions->search( + { suggestedby => $borrowernumber, suggesteddate => { '>=' => $suggesteddate_from } } )->count; } if ( C4::Context->preference("MaxOpenSuggestions") ne '' ) { - $patrons_pending_suggestions_count = Koha::Suggestions->search({ suggestedby => $borrowernumber, STATUS => 'ASKED' } )->count ; + $patrons_pending_suggestions_count = + Koha::Suggestions->search( { suggestedby => $borrowernumber, STATUS => 'ASKED' } )->count; } } if ( $op eq "cud-add_confirm" ) { my $suggestions = Koha::Suggestions->search($suggestion); - if ( C4::Context->preference("MaxTotalSuggestions") ne '' && $patrons_total_suggestions_count >= C4::Context->preference("MaxTotalSuggestions") ) + if ( C4::Context->preference("MaxTotalSuggestions") ne '' + && $patrons_total_suggestions_count >= C4::Context->preference("MaxTotalSuggestions") ) { push @messages, { type => 'error', code => 'total_suggestions' }; - } - elsif ( C4::Context->preference("MaxOpenSuggestions") ne '' && $patrons_pending_suggestions_count >= C4::Context->preference("MaxOpenSuggestions") ) #only check limit for signed in borrowers + } elsif ( C4::Context->preference("MaxOpenSuggestions") ne '' + && $patrons_pending_suggestions_count >= + C4::Context->preference("MaxOpenSuggestions") ) #only check limit for signed in borrowers { push @messages, { type => 'error', code => 'too_many' }; - } - elsif ( $suggestions->count >= 1 ) { + } elsif ( $suggestions->count >= 1 ) { #some suggestion are answering the request Donot Add while ( my $suggestion = $suggestions->next ) { push @messages, - { + { type => 'error', code => 'already_exists', id => $suggestion->suggestionid - }; + }; last; } - } - else { - for my $f ( split(/\s*\,\s*/, C4::Context->preference("OPACSuggestionUnwantedFields") ) ) { + } else { + for my $f ( split( /\s*\,\s*/, C4::Context->preference("OPACSuggestionUnwantedFields") ) ) { delete $suggestion->{$f}; } @@ -193,22 +205,24 @@ if ( $op eq "cud-add_confirm" ) { foreach my $suggest ( keys %$suggestion ) { # Don't know why the encode is needed for Perl v5.10 here - $suggestion->{$suggest} = Encode::encode( "utf8", - $scrubber->scrub( $suggestion->{$suggest} ) ); + $suggestion->{$suggest} = Encode::encode( + "utf8", + $scrubber->scrub( $suggestion->{$suggest} ) + ); } $suggestion->{suggesteddate} = dt_from_string; - $suggestion->{branchcode} = $input->param('branchcode') || C4::Context->userenv->{"branch"}; - $suggestion->{STATUS} = 'ASKED'; - if ( $biblionumber ) { + $suggestion->{branchcode} = $input->param('branchcode') || C4::Context->userenv->{"branch"}; + $suggestion->{STATUS} = 'ASKED'; + if ($biblionumber) { my $biblio = Koha::Biblios->find($biblionumber); - $suggestion->{biblionumber} = $biblio->biblionumber; - $suggestion->{title} = $biblio->title; - $suggestion->{author} = $biblio->author; - $suggestion->{copyrightdate} = $biblio->copyrightdate; - $suggestion->{isbn} = $biblio->biblioitem->isbn; - $suggestion->{publishercode} = $biblio->biblioitem->publishercode; + $suggestion->{biblionumber} = $biblio->biblionumber; + $suggestion->{title} = $biblio->title; + $suggestion->{author} = $biblio->author; + $suggestion->{copyrightdate} = $biblio->copyrightdate; + $suggestion->{isbn} = $biblio->biblioitem->isbn; + $suggestion->{publishercode} = $biblio->biblioitem->publishercode; $suggestion->{collectiontitle} = $biblio->biblioitem->collectiontitle; - $suggestion->{place} = $biblio->biblioitem->place; + $suggestion->{place} = $biblio->biblioitem->place; } Koha::Suggestion->new($suggestion)->store(); @@ -221,16 +235,18 @@ if ( $op eq "cud-add_confirm" ) { $op = 'else'; } -my $suggestions = [ Koha::Suggestions->search_limited( - { - $suggestion->{suggestedby} - ? ( suggestedby => $suggestion->{suggestedby} ) - : (), - $title_filter - ? ( title => $title_filter ) - : (), - } -)->as_list ]; +my $suggestions = [ + Koha::Suggestions->search_limited( + { + $suggestion->{suggestedby} + ? ( suggestedby => $suggestion->{suggestedby} ) + : (), + $title_filter + ? ( title => $title_filter ) + : (), + } + )->as_list +]; if ( $op eq "cud-delete" ) { my @delete_field = $input->multi_param("delete_field"); @@ -242,16 +258,16 @@ if ( $op eq "cud-delete" ) { exit; } -my $patron_reason_loop = GetAuthorisedValues("OPAC_SUG", "opac"); +my $patron_reason_loop = GetAuthorisedValues( "OPAC_SUG", "opac" ); my @mandatoryfields; if ( $op eq 'add_form' ) { my $fldsreq_sp = C4::Context->preference("OPACSuggestionMandatoryFields") || 'title'; - @mandatoryfields = sort split(/\s*\|\s*/, $fldsreq_sp); + @mandatoryfields = sort split( /\s*\|\s*/, $fldsreq_sp ); foreach (@mandatoryfields) { - $template->param( $_."_required" => 1); + $template->param( $_ . "_required" => 1 ); } - if ( $biblionumber ) { + if ($biblionumber) { my $biblio = Koha::Biblios->find($biblionumber); $suggestion = { biblionumber => $biblio->biblionumber, @@ -268,27 +284,27 @@ if ( $op eq 'add_form' ) { my @unwantedfields; { - last unless ($op eq 'add_form'); + last unless ( $op eq 'add_form' ); my $fldsreq_sp = C4::Context->preference("OPACSuggestionUnwantedFields"); - @unwantedfields = sort split(/\s*\|\s*/, $fldsreq_sp); + @unwantedfields = sort split( /\s*\|\s*/, $fldsreq_sp ); foreach (@unwantedfields) { - $template->param( $_."_hidden" => 1); + $template->param( $_ . "_hidden" => 1 ); } } $template->param( %$suggestion, - suggestions => $suggestions, - patron_reason_loop => $patron_reason_loop, - "op_$op" => 1, - $op => 1, - messages => \@messages, - suggestionsview => 1, - suggested_by_anyone => $suggested_by_anyone, - title_filter => $title_filter, + suggestions => $suggestions, + patron_reason_loop => $patron_reason_loop, + "op_$op" => 1, + $op => 1, + messages => \@messages, + suggestionsview => 1, + suggested_by_anyone => $suggested_by_anyone, + title_filter => $title_filter, patrons_pending_suggestions_count => $patrons_pending_suggestions_count, - need_confirm => $need_confirm, - patrons_total_suggestions_count => $patrons_total_suggestions_count, + need_confirm => $need_confirm, + patrons_total_suggestions_count => $patrons_total_suggestions_count, ); output_html_with_http_headers $input, $cookie, $template->output, undef, { force_no_caching => 1 }; diff --git a/opac/opac-tags.pl b/opac/opac-tags.pl index e9333dee16..7a65538c1b 100755 --- a/opac/opac-tags.pl +++ b/opac/opac-tags.pl @@ -17,7 +17,6 @@ # You should have received a copy of the GNU General Public License # along with Koha; if not, see . - =head1 NAME opac-tags.pl @@ -33,7 +32,7 @@ C4::Scrubber is used to remove all markup content from the sumitted text. use Modern::Perl; use CGI qw ( -utf8 ); -use CGI::Cookie; # need to check cookies before having CGI parse the POST request +use CGI::Cookie; # need to check cookies before having CGI parse the POST request use Array::Utils qw( array_minus ); use C4::Auth qw( check_cookie_auth get_template_and_user ); @@ -50,33 +49,32 @@ use C4::Tags qw( use C4::XSLT qw( XSLTParse4Display ); use Koha::Biblios; - use Koha::Logger; use Koha::Biblios; use Koha::CirculationRules; -my %newtags = (); -my @deltags = (); -my %counts = (); -my @errors = (); +my %newtags = (); +my @deltags = (); +my %counts = (); +my @errors = (); my $perBibResults = {}; # Indexes of @errors that do not apply to a particular biblionumber. my @globalErrorIndexes = (); -sub ajax_auth_cgi { # returns CGI object - my $needed_flags = shift; - my %cookies = CGI::Cookie->fetch; - my $input = CGI->new; - my $sessid = $cookies{'CGISESSID'}->value; - my ($auth_status) = check_cookie_auth($sessid, $needed_flags); - if ($auth_status ne "ok") { - output_with_http_headers $input, undef, - "window.alert('Your CGI session cookie ($sessid) is not current. " . - "Please refresh the page and try again.');\n", 'js'; - exit 0; - } - return $input; +sub ajax_auth_cgi { # returns CGI object + my $needed_flags = shift; + my %cookies = CGI::Cookie->fetch; + my $input = CGI->new; + my $sessid = $cookies{'CGISESSID'}->value; + my ($auth_status) = check_cookie_auth( $sessid, $needed_flags ); + if ( $auth_status ne "ok" ) { + output_with_http_headers $input, undef, + "window.alert('Your CGI session cookie ($sessid) is not current. " + . "Please refresh the page and try again.');\n", 'js'; + exit 0; + } + return $input; } # The trick here is to support multiple tags added to multiple biblios in one POST. @@ -85,14 +83,14 @@ sub ajax_auth_cgi { # returns CGI object # For lack of anything more compelling, we just use "newtag[biblionumber]" # We split the value into tags at comma and semicolon -my $is_ajax = is_ajax(); -my $openadds = C4::Context->preference('TagsModeration') ? 0 : 1; -my $query = ($is_ajax) ? &ajax_auth_cgi({}) : CGI->new(); -foreach ($query->param) { +my $is_ajax = is_ajax(); +my $openadds = C4::Context->preference('TagsModeration') ? 0 : 1; +my $query = ($is_ajax) ? &ajax_auth_cgi( {} ) : CGI->new(); +foreach ( $query->param ) { if (/^newtag(.*)/) { my $biblionumber = $1; - unless ($biblionumber =~ /^\d+$/) { - push @errors, {+'badparam' => $_ }; + unless ( $biblionumber =~ /^\d+$/ ) { + push @errors, { +'badparam' => $_ }; push @globalErrorIndexes, $#errors; next; } @@ -102,17 +100,19 @@ foreach ($query->param) { } } -my $add_op = (scalar(keys %newtags) + scalar(@deltags)) ? 1 : 0; -my ($template, $loggedinuser, $cookie); +my $add_op = ( scalar( keys %newtags ) + scalar(@deltags) ) ? 1 : 0; +my ( $template, $loggedinuser, $cookie ); if ($is_ajax) { - $loggedinuser = C4::Context->userenv->{'number'}; # must occur AFTER auth + $loggedinuser = C4::Context->userenv->{'number'}; # must occur AFTER auth } else { - ($template, $loggedinuser, $cookie) = get_template_and_user({ - template_name => "opac-tags.tt", - query => $query, - type => "opac", - authnotrequired => ($add_op ? 0 : 1), # auth required to add tags - }); + ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "opac-tags.tt", + query => $query, + type => "opac", + authnotrequired => ( $add_op ? 0 : 1 ), # auth required to add tags + } + ); } unless ( C4::Context->preference('TagsEnabled') ) { @@ -121,47 +121,49 @@ unless ( C4::Context->preference('TagsEnabled') ) { } if ($add_op) { - unless ($loggedinuser) { - push @errors, {+'cud-login' => 1 }; + unless ($loggedinuser) { + push @errors, { +'cud-login' => 1 }; push @globalErrorIndexes, $#errors; - %newtags=(); # zero out any attempted additions - @deltags=(); # zero out any attempted deletions - } + %newtags = (); # zero out any attempted additions + @deltags = (); # zero out any attempted deletions + } } -my $op = $query->param('op') || q{}; +my $op = $query->param('op') || q{}; my $dels = 0; if ( $op eq 'cud-add' ) { my $scrubber; - my @newtags_keys = (keys %newtags); - if (scalar @newtags_keys) { + my @newtags_keys = ( keys %newtags ); + if ( scalar @newtags_keys ) { $scrubber = C4::Scrubber->new(); foreach my $biblionumber (@newtags_keys) { - my $bibResults = {adds=>0, errors=>[]}; - my @values = split /[;,]/, $newtags{$biblionumber}; + my $bibResults = { adds => 0, errors => [] }; + my @values = split /[;,]/, $newtags{$biblionumber}; foreach (@values) { s/^\s*(.+)\s*$/$1/; my $clean_tag = $scrubber->scrub($_); - unless ($clean_tag eq $_) { - if ($clean_tag =~ /\S/) { - push @errors, {scrubbed=>$clean_tag}; - push @{$bibResults->{errors}}, {scrubbed=>$clean_tag}; + unless ( $clean_tag eq $_ ) { + if ( $clean_tag =~ /\S/ ) { + push @errors, { scrubbed => $clean_tag }; + push @{ $bibResults->{errors} }, { scrubbed => $clean_tag }; } else { - push @errors, {scrubbed_all_bad=>1}; - push @{$bibResults->{errors}}, {scrubbed_all_bad=>1}; - next; # we don't add it if there's nothing left! + push @errors, { scrubbed_all_bad => 1 }; + push @{ $bibResults->{errors} }, { scrubbed_all_bad => 1 }; + next; # we don't add it if there's nothing left! } } - my $result = ($openadds) ? - add_tag($biblionumber,$clean_tag,$loggedinuser,$loggedinuser) : # pre-approved - add_tag($biblionumber,$clean_tag,$loggedinuser) ; + my $result = + ($openadds) ? add_tag( $biblionumber, $clean_tag, $loggedinuser, $loggedinuser ) : # pre-approved + add_tag( $biblionumber, $clean_tag, $loggedinuser ); if ($result) { $counts{$biblionumber}++; $bibResults->{adds}++; } else { - push @errors, {failed_add_tag=>$clean_tag}; - push @{$bibResults->{errors}}, {failed_add_tag=>$clean_tag}; - Koha::Logger->get->warn("add_tag($biblionumber,$clean_tag,$loggedinuser...) returned bad result (" . (defined $result ? $result : 'UNDEF') .")"); + push @errors, { failed_add_tag => $clean_tag }; + push @{ $bibResults->{errors} }, { failed_add_tag => $clean_tag }; + Koha::Logger->get->warn( "add_tag($biblionumber,$clean_tag,$loggedinuser...) returned bad result (" + . ( defined $result ? $result : 'UNDEF' ) + . ")" ); } } $perBibResults->{$biblionumber} = $bibResults; @@ -169,18 +171,18 @@ if ( $op eq 'cud-add' ) { } } elsif ( $op eq 'cud-del' ) { foreach (@deltags) { - if (remove_tag($_,$loggedinuser)) { + if ( remove_tag( $_, $loggedinuser ) ) { $dels++; } else { - push @errors, {failed_delete=>$_}; + push @errors, { failed_delete => $_ }; } } } if ($is_ajax) { - my $sum = 0; - foreach (values %counts) {$sum += $_;} - my $js_reply = sprintf("response = {\n\tadded: %d,\n\tdeleted: %d,\n\terrors: %d",$sum,$dels,scalar @errors); + my $sum = 0; + foreach ( values %counts ) { $sum += $_; } + my $js_reply = sprintf( "response = {\n\tadded: %d,\n\tdeleted: %d,\n\terrors: %d", $sum, $dels, scalar @errors ); # If no add attempts were made, flag global errors. if (@globalErrorIndexes) { @@ -193,62 +195,63 @@ if ($is_ajax) { } $js_reply .= "\n\t]"; } - - my $err_string = ''; - if (scalar @errors) { - $err_string = ",\n\talerts: ["; # open response_function - my $i = 1; - foreach (@errors) { - my $key = (keys %$_)[0]; - $err_string .= "\n\t\t KOHA.Tags.tag_message.$key(\"" . $_->{$key} . '")'; - if($i < scalar @errors){ $err_string .= ","; } - $i++; - } - $err_string .= "\n\t]\n"; # close response_function - } + + my $err_string = ''; + if ( scalar @errors ) { + $err_string = ",\n\talerts: ["; # open response_function + my $i = 1; + foreach (@errors) { + my $key = ( keys %$_ )[0]; + $err_string .= "\n\t\t KOHA.Tags.tag_message.$key(\"" . $_->{$key} . '")'; + if ( $i < scalar @errors ) { $err_string .= ","; } + $i++; + } + $err_string .= "\n\t]\n"; # close response_function + } # Add per-biblionumber results for use on results page my $js_perbib = ""; - for my $bib (keys %$perBibResults) { + for my $bib ( keys %$perBibResults ) { my $bibResult = $perBibResults->{$bib}; my $js_bibres = ",\n\t$bib: {\n\t\tadded: $bibResult->{adds}"; $js_bibres .= ",\n\t\terrors: ["; my $i = 0; - foreach (@{$bibResult->{errors}}) { + foreach ( @{ $bibResult->{errors} } ) { $js_bibres .= "," if ($i); - my $key = (keys %$_)[0]; - $js_bibres .= "\n\t\t\t KOHA.Tags.tag_message.$key(\"" . $_->{$key} . '")'; + my $key = ( keys %$_ )[0]; + $js_bibres .= "\n\t\t\t KOHA.Tags.tag_message.$key(\"" . $_->{$key} . '")'; $i++; } $js_bibres .= "\n\t\t]\n\t}"; $js_perbib .= $js_bibres; } - output_with_http_headers($query, undef, "$js_reply\n$err_string\n$js_perbib\n};", 'js'); - exit; + output_with_http_headers( $query, undef, "$js_reply\n$err_string\n$js_perbib\n};", 'js' ); + exit; } my $results = []; my $my_tags = []; if ($loggedinuser) { - my $patron = Koha::Patrons->find( { borrowernumber => $loggedinuser } ); - my $rules = C4::Context->yaml_preference('OpacHiddenItems'); - my $should_hide = ( $rules ) ? 1 : 0; - $my_tags = get_tag_rows({borrowernumber=>$loggedinuser}); - my $my_approved_tags = get_approval_rows({ approved => 1 }); + my $patron = Koha::Patrons->find( { borrowernumber => $loggedinuser } ); + my $rules = C4::Context->yaml_preference('OpacHiddenItems'); + my $should_hide = ($rules) ? 1 : 0; + $my_tags = get_tag_rows( { borrowernumber => $loggedinuser } ); + my $my_approved_tags = get_approval_rows( { approved => 1 } ); my $art_req_itypes; - if( C4::Context->preference('ArticleRequests') ) { - $art_req_itypes = Koha::CirculationRules->guess_article_requestable_itemtypes({ $patron ? ( categorycode => $patron->categorycode ) : () }); + if ( C4::Context->preference('ArticleRequests') ) { + $art_req_itypes = Koha::CirculationRules->guess_article_requestable_itemtypes( + { $patron ? ( categorycode => $patron->categorycode ) : () } ); } # get biblionumbers stored in the cart my @cart_list; - if($query->cookie("bib_list")){ + if ( $query->cookie("bib_list") ) { my $cart_list = $query->cookie("bib_list"); - @cart_list = split(/\//, $cart_list); + @cart_list = split( /\//, $cart_list ); } foreach my $tag (@$my_tags) { @@ -264,31 +267,30 @@ if ($loggedinuser) { next unless $record; my @hidden_items; if ($should_hide) { - my $items = $biblio->items->search_ordered; + my $items = $biblio->items->search_ordered; my @all_itemnumbers = $items->get_column('itemnumber'); - my @items_to_show = $items->filter_by_visible_in_opac({ opac => 1, patron => $patron })->as_list; + my @items_to_show = $items->filter_by_visible_in_opac( { opac => 1, patron => $patron } )->as_list; @hidden_items = array_minus( @all_itemnumbers, @items_to_show ); } next - if ( + if ( ( !$patron or ( $patron and !$patron->category->override_hidden_items ) ) and $biblio->hidden_in_opac( { rules => $rules } ) - ); - $tag->{title} = $biblio->title; - $tag->{subtitle} = $biblio->subtitle; - $tag->{medium} = $biblio->medium; + ); + $tag->{title} = $biblio->title; + $tag->{subtitle} = $biblio->subtitle; + $tag->{medium} = $biblio->medium; $tag->{part_number} = $biblio->part_number; - $tag->{part_name} = $biblio->part_name; - $tag->{author} = $biblio->author; - # BZ17530: 'Intelligent' guess if result can be article requested - $tag->{artreqpossible} = ( $art_req_itypes->{ $tag->{itemtype} // q{} } || $art_req_itypes->{ '*' } ) ? 1 : q{}; + $tag->{part_name} = $biblio->part_name; + $tag->{author} = $biblio->author; - my $variables = { - anonymous_session => ($loggedinuser) ? 0 : 1 - }; + # BZ17530: 'Intelligent' guess if result can be article requested + $tag->{artreqpossible} = ( $art_req_itypes->{ $tag->{itemtype} // q{} } || $art_req_itypes->{'*'} ) ? 1 : q{}; + + my $variables = { anonymous_session => ($loggedinuser) ? 0 : 1 }; $tag->{XSLTBloc} = XSLTParse4Display( { biblionumber => $tag->{biblionumber}, @@ -303,48 +305,51 @@ if ($loggedinuser) { my $date = $tag->{date_created} || ''; $date =~ /\s+(\d{2}\:\d{2}\:\d{2})/; $tag->{time_created_display} = $1; - $tag->{approved} = ( grep { $_->{term} eq $tag->{term} and $_->{approved} } @$my_approved_tags ); - $tag->{visible} = 1; + $tag->{approved} = ( grep { $_->{term} eq $tag->{term} and $_->{approved} } @$my_approved_tags ); + $tag->{visible} = 1; + # while we're checking each line, see if item is in the cart - if ( grep {$_ eq $biblio->biblionumber} @cart_list) { + if ( grep { $_ eq $biblio->biblionumber } @cart_list ) { $tag->{incart} = 1; } } } -$template->param(tagsview => 1); +$template->param( tagsview => 1 ); if ($add_op) { - my $adds = 0; - for (values %counts) {$adds += $_;} - $template->param( - add_op => 1, - added_count => $adds, - deleted_count => $dels, - ); + my $adds = 0; + for ( values %counts ) { $adds += $_; } + $template->param( + add_op => 1, + added_count => $adds, + deleted_count => $dels, + ); } else { - my ($arg,$limit,$mine); - my $hardmax = 100; # you might disagree what this value should be, but there definitely should be a max - $limit = $query->param('limit') || $hardmax; - $mine = $query->param('mine') || 0; # set if the patron want to see only his own tags. - ($limit =~ /^\d+$/ and $limit <= $hardmax) or $limit = $hardmax; - $template->param(limit => $limit); - my $arghash = {approved=>1, limit=>$limit, 'sort'=>'-weight_total'}; + my ( $arg, $limit, $mine ); + my $hardmax = 100; # you might disagree what this value should be, but there definitely should be a max + $limit = $query->param('limit') || $hardmax; + $mine = $query->param('mine') || 0; # set if the patron want to see only his own tags. + ( $limit =~ /^\d+$/ and $limit <= $hardmax ) or $limit = $hardmax; + $template->param( limit => $limit ); + my $arghash = { approved => 1, limit => $limit, 'sort' => '-weight_total' }; $arghash->{'borrowernumber'} = $loggedinuser if $mine; - # ($openadds) or $arghash->{approved} = 1; + + # ($openadds) or $arghash->{approved} = 1; if ( $arg = $query->param('tag') ) { $arghash->{term} = $arg; } + # Bug 36785: Do not pass biblionumber: get_approval_rows does not 'recognize' biblionumber - $results = get_approval_rows($arghash); - stratify_tags(10, $results); # work out the differents sizes for things - my $count = scalar @$results; - $template->param(TAGLOOP_COUNT => $count, mine => $mine); + $results = get_approval_rows($arghash); + stratify_tags( 10, $results ); # work out the differents sizes for things + my $count = scalar @$results; + $template->param( TAGLOOP_COUNT => $count, mine => $mine ); } -(scalar @errors ) and $template->param(ERRORS => \@errors); -my @orderedresult = sort { uc($a->{'term'}) cmp uc($b->{'term'}) } @$results; -(scalar @$results) and $template->param(TAGLOOP => \@orderedresult ); -(scalar @$my_tags) and $template->param(MY_TAGS => $my_tags); +( scalar @errors ) and $template->param( ERRORS => \@errors ); +my @orderedresult = sort { uc( $a->{'term'} ) cmp uc( $b->{'term'} ) } @$results; +( scalar @$results ) and $template->param( TAGLOOP => \@orderedresult ); +( scalar @$my_tags ) and $template->param( MY_TAGS => $my_tags ); output_html_with_http_headers $query, $cookie, $template->output; __END__ diff --git a/opac/opac-tags_subject.pl b/opac/opac-tags_subject.pl index 8af9c29ad4..d4b908485c 100755 --- a/opac/opac-tags_subject.pl +++ b/opac/opac-tags_subject.pl @@ -17,7 +17,6 @@ # You should have received a copy of the GNU General Public License # along with Koha; if not, see . - =head1 opac-tags_subject.pl TODO :: Description here @@ -29,7 +28,7 @@ use Modern::Perl; use C4::Auth qw( get_template_and_user ); use C4::Context; use C4::Output qw( output_html_with_http_headers ); -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); my $query = CGI->new; @@ -51,26 +50,26 @@ my $sth = $dbh->prepare("SELECT entry,weight FROM tags ORDER BY weight DESC LIMI $sth->execute($number); my %result; -my $max=0; -my $min=9999; -my ($entry,$weight); -while (($entry,$weight) = $sth->fetchrow) { - $result{$entry}=$weight; - $max = $weight if $weight > $max; - $min = $weight if $weight < $min; +my $max = 0; +my $min = 9999; +my ( $entry, $weight ); +while ( ( $entry, $weight ) = $sth->fetchrow ) { + $result{$entry} = $weight; + $max = $weight if $weight > $max; + $min = $weight if $weight < $min; } $min++ if $min == $max; my @loop; -foreach my $entry (sort keys %result) { +foreach my $entry ( sort keys %result ) { my %line; - $line{entry} = $entry; - $line{weight} = int(($result{$entry}-$min)/($max-$min)*25)+10; + $line{entry} = $entry; + $line{weight} = int( ( $result{$entry} - $min ) / ( $max - $min ) * 25 ) + 10; push @loop, \%line; } $template->param( - LOOP => \@loop, + LOOP => \@loop, number => $number ); diff --git a/opac/opac-topissues.pl b/opac/opac-topissues.pl index 43830ccfd5..7c1f4b103d 100755 --- a/opac/opac-topissues.pl +++ b/opac/opac-topissues.pl @@ -1,6 +1,5 @@ #!/usr/bin/perl - # Copyright 2000-2002 Katipo Communications # Parts Copyright Catalyst IT 2011 # @@ -21,11 +20,11 @@ use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Auth qw( get_template_and_user ); use C4::Context; use C4::Search; -use C4::Output qw( output_html_with_http_headers ); +use C4::Output qw( output_html_with_http_headers ); use C4::Circulation qw( GetTopIssues ); =head1 NAME @@ -39,12 +38,12 @@ plugin that shows a stats on borrowers my $input = CGI->new; # if OpacTopissue is disabled, leave immediately -if ( ! C4::Context->preference('OpacTopissue') ) { +if ( !C4::Context->preference('OpacTopissue') ) { print $input->redirect("/cgi-bin/koha/errors/404.pl"); exit; } -my ($template, $borrowernumber, $cookie) = get_template_and_user( +my ( $template, $borrowernumber, $cookie ) = get_template_and_user( { template_name => 'opac-topissues.tt', query => $input, @@ -53,42 +52,43 @@ my ($template, $borrowernumber, $cookie) = get_template_and_user( } ); my $dbh = C4::Context->dbh; + # Displaying results -my $do_it = $input->param('do_it') || 0; # as form been posted +my $do_it = $input->param('do_it') || 0; # as form been posted my $limit = $input->param('limit'); -$limit = 10 unless ($limit && $limit =~ /^\d+$/); # control user input for SQL query +$limit = 10 unless ( $limit && $limit =~ /^\d+$/ ); # control user input for SQL query $limit = 100 if $limit > 100; my $branch = $input->param('branch') || ''; -if (!$do_it && C4::Context->userenv && C4::Context->userenv->{'branch'} ) { - $branch = C4::Context->userenv->{'branch'}; # select user branch by default +if ( !$do_it && C4::Context->userenv && C4::Context->userenv->{'branch'} ) { + $branch = C4::Context->userenv->{'branch'}; # select user branch by default } -my $itemtype = $input->param('itemtype') || ''; -my $timeLimit = $input->param('timeLimit') || 3; +my $itemtype = $input->param('itemtype') || ''; +my $timeLimit = $input->param('timeLimit') || 3; my $advanced_search_types = C4::Context->preference('OpacAdvancedSearchTypes'); my @advanced_search_types = split /\|/, $advanced_search_types; my $params = { - count => $limit, - branch => $branch, + count => $limit, + branch => $branch, newness => $timeLimit < 999 ? $timeLimit * 30 : undef, }; @advanced_search_types = grep /^(ccode|itemtypes)$/, @advanced_search_types; foreach my $type (@advanced_search_types) { - if ($type eq 'itemtypes') { + if ( $type eq 'itemtypes' ) { $type = 'itemtype'; } $params->{$type} = $input->param($type); - $template->param('selected_' . $type => scalar $input->param($type)); + $template->param( 'selected_' . $type => scalar $input->param($type) ); } my @results = GetTopIssues($params); $template->param( - limit => $limit, - branch => $branch, + limit => $limit, + branch => $branch, timeLimit => $timeLimit, - results => \@results, + results => \@results, ); output_html_with_http_headers $input, $cookie, $template->output; diff --git a/opac/opac-user.pl b/opac/opac-user.pl index bd1137c5ac..b841afd827 100755 --- a/opac/opac-user.pl +++ b/opac/opac-user.pl @@ -16,7 +16,6 @@ # You should have received a copy of the GNU General Public License # along with Koha; if not, see . - use Modern::Perl; use CGI qw ( -utf8 ); @@ -29,9 +28,9 @@ use C4::Koha qw( GetNormalizedUPC GetNormalizedOCLCNumber ); -use C4::Circulation qw( CanBookBeRenewed GetRenewCount GetIssuingCharges ); +use C4::Circulation qw( CanBookBeRenewed GetRenewCount GetIssuingCharges ); use C4::External::BakerTaylor qw( image_url link_url ); -use C4::Reserves qw( GetReserveStatus ); +use C4::Reserves qw( GetReserveStatus ); use C4::Members; use C4::Output qw( output_html_with_http_headers ); use Koha::Account::Lines; @@ -52,7 +51,7 @@ use Koha::Recalls; use constant ATTRIBUTE_SHOW_BARCODE => 'SHOW_BCODE'; use Scalar::Util qw( looks_like_number ); -use Date::Calc qw( Date_to_Days Today ); +use Date::Calc qw( Date_to_Days Today ); my $query = CGI->new; @@ -67,9 +66,9 @@ if ( C4::Context->preference('casAuthentication') ) { my ( $template, $borrowernumber, $cookie ) = get_template_and_user( { - template_name => "opac-user.tt", - query => $query, - type => "opac", + template_name => "opac-user.tt", + query => $query, + type => "opac", } ); @@ -81,24 +80,24 @@ for ( C4::Context->preference("OPACShowHoldQueueDetails") ) { } my $patronupdate = $query->param('patronupdate'); -my $canrenew = 1; +my $canrenew = 1; $template->param( shibbolethAuthentication => C4::Context->config('useshibboleth') ); # get borrower information .... -my $patron = Koha::Patrons->find( $borrowernumber ); +my $patron = Koha::Patrons->find($borrowernumber); -if( $op eq 'cud-update_arc' && C4::Context->preference("AllowPatronToControlAutorenewal") ){ +if ( $op eq 'cud-update_arc' && C4::Context->preference("AllowPatronToControlAutorenewal") ) { my $autorenew_checkouts = $query->param('borrower_autorenew_checkouts'); - $patron->autorenew_checkouts( $autorenew_checkouts )->store() if defined $autorenew_checkouts; + $patron->autorenew_checkouts($autorenew_checkouts)->store() if defined $autorenew_checkouts; } my $borr = $patron->unblessed; -my ( $today_year, $today_month, $today_day) = Today(); -my ($warning_year, $warning_month, $warning_day) = split /-/, $borr->{'dateexpiry'}; +my ( $today_year, $today_month, $today_day ) = Today(); +my ( $warning_year, $warning_month, $warning_day ) = split /-/, $borr->{'dateexpiry'}; -my $debar = Koha::Patrons->find( $borrowernumber )->is_debarred; +my $debar = Koha::Patrons->find($borrowernumber)->is_debarred; my $userdebarred; if ($debar) { @@ -107,13 +106,17 @@ if ($debar) { if ( $debar ne "9999-12-31" ) { $borr->{'userdebarreddate'} = $debar; } + # FIXME looks like $available is not needed # If a user is discharged they have a validated discharge available - my $available = Koha::Patron::Discharge::count({ - borrowernumber => $borrowernumber, - validated => 1, - }); - $template->param( 'discharge_available' => $available && Koha::Patron::Discharge::is_discharged({borrowernumber => $borrowernumber}) ); + my $available = Koha::Patron::Discharge::count( + { + borrowernumber => $borrowernumber, + validated => 1, + } + ); + $template->param( 'discharge_available' => $available + && Koha::Patron::Discharge::is_discharged( { borrowernumber => $borrowernumber } ) ); } if ( $userdebarred || $borr->{'gonenoaddress'} || $borr->{'lost'} ) { @@ -122,12 +125,12 @@ if ( $userdebarred || $borr->{'gonenoaddress'} || $borr->{'lost'} ) { } my $amountoutstanding = $patron->account->balance; -my $no_renewal_amt = C4::Context->preference( 'OPACFineNoRenewals' ); -$no_renewal_amt = undef unless looks_like_number( $no_renewal_amt ); +my $no_renewal_amt = C4::Context->preference('OPACFineNoRenewals'); +$no_renewal_amt = undef unless looks_like_number($no_renewal_amt); my $amountoutstandingfornewal = - C4::Context->preference("OPACFineNoRenewalsIncludeCredit") - ? $amountoutstanding - : $patron->account->outstanding_debits->total_outstanding; + C4::Context->preference("OPACFineNoRenewalsIncludeCredit") + ? $amountoutstanding + : $patron->account->outstanding_debits->total_outstanding; if ( C4::Context->preference('OpacRenewalAllowed') && defined($no_renewal_amt) @@ -136,26 +139,29 @@ if ( C4::Context->preference('OpacRenewalAllowed') $borr->{'flagged'} = 1; $canrenew = 0; $template->param( - renewal_blocked_fines => $no_renewal_amt, + renewal_blocked_fines => $no_renewal_amt, renewal_blocked_fines_amountoutstanding => $amountoutstandingfornewal, ); } my $maxoutstanding = C4::Context->preference('maxoutstanding'); -if ( $amountoutstanding && ( $amountoutstanding > $maxoutstanding ) ){ +if ( $amountoutstanding && ( $amountoutstanding > $maxoutstanding ) ) { $borr->{blockedonfines} = 1; } # Warningdate is the date that the warning starts appearing if ( $borr->{'dateexpiry'} && C4::Context->preference('NotifyBorrowerDeparture') ) { - my $days_to_expiry = Date_to_Days( $warning_year, $warning_month, $warning_day ) - Date_to_Days( $today_year, $today_month, $today_day ); + my $days_to_expiry = Date_to_Days( $warning_year, $warning_month, $warning_day ) - + Date_to_Days( $today_year, $today_month, $today_day ); if ( $days_to_expiry < 0 ) { + #borrower card has expired, warn the borrower $borr->{'warnexpired'} = $borr->{'dateexpiry'}; } elsif ( $days_to_expiry < C4::Context->preference('NotifyBorrowerDeparture') ) { + # borrower card soon to expire, warn the borrower $borr->{'warndeparture'} = $borr->{dateexpiry}; - if (C4::Context->preference('ReturnBeforeExpiry')){ + if ( C4::Context->preference('ReturnBeforeExpiry') ) { $borr->{'returnbeforeexpiry'} = 1; } } @@ -170,13 +176,13 @@ if ( $saving_display =~ /user/ ) { my $renew_error = $query->param('renew_error'); $template->param( - amountoutstanding => $amountoutstanding, - borrowernumber => $borrowernumber, - patron_flagged => $borr->{flagged}, - surname => $borr->{surname}, - RENEW_ERROR => $renew_error, - borrower => $borr, - ); + amountoutstanding => $amountoutstanding, + borrowernumber => $borrowernumber, + patron_flagged => $borr->{flagged}, + surname => $borr->{surname}, + RENEW_ERROR => $renew_error, + borrower => $borr, +); #get issued items .... @@ -184,7 +190,7 @@ my $count = 0; my $overdues_count = 0; my @overdues; my @issuedat; -my $itemtypes = { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search_with_localization->unblessed } }; +my $itemtypes = { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search_with_localization->unblessed } }; my $pending_checkouts = $patron->pending_checkouts->search( {}, { @@ -193,12 +199,13 @@ my $pending_checkouts = $patron->pending_checkouts->search( } ); my $are_renewable_items = 0; -if ( $pending_checkouts->count ) { # Useless test +if ( $pending_checkouts->count ) { # Useless test while ( my $c = $pending_checkouts->next ) { my $issue = $c->unblessed_all_relateds; + # check for reserves my $restype = GetReserveStatus( $issue->{'itemnumber'} ); - if ( $restype ) { + if ($restype) { $issue->{'reserved'} = 1; } @@ -216,7 +223,7 @@ if ( $pending_checkouts->count ) { # Useless test my $rental_fines = Koha::Account::Lines->search( { borrowernumber => $patron->borrowernumber, - amountoutstanding => { '>' => 0 }, + amountoutstanding => { '>' => 0 }, debit_type_code => { 'LIKE' => 'RENT_%' }, itemnumber => $issue->{itemnumber} } @@ -224,7 +231,7 @@ if ( $pending_checkouts->count ) { # Useless test $issue->{rentalfines} = $rental_fines->total_outstanding; # check if item is renewable - my ($status, $renewerror, $info) = CanBookBeRenewed( $patron, $c ); + my ( $status, $renewerror, $info ) = CanBookBeRenewed( $patron, $c ); ( $issue->{'renewcount'}, $issue->{'renewsallowed'}, @@ -232,10 +239,11 @@ if ( $pending_checkouts->count ) { # Useless test $issue->{'unseencount'}, $issue->{'unseenallowed'}, $issue->{'unseenleft'} - ) = GetRenewCount($patron, $c->item); - ( $issue->{'renewalfee'}, $issue->{'renewalitemtype'} ) = GetIssuingCharges( $issue->{'itemnumber'}, $borrowernumber ); + ) = GetRenewCount( $patron, $c->item ); + ( $issue->{'renewalfee'}, $issue->{'renewalitemtype'} ) = + GetIssuingCharges( $issue->{'itemnumber'}, $borrowernumber ); $issue->{itemtype_object} = Koha::ItemTypes->find( $c->item->effective_itemtype ); - if($status && C4::Context->preference("OpacRenewalAllowed")){ + if ( $status && C4::Context->preference("OpacRenewalAllowed") ) { $are_renewable_items = 1; $issue->{'status'} = $status; } @@ -243,15 +251,15 @@ if ( $pending_checkouts->count ) { # Useless test $issue->{'renewed'} = $renewed{ $issue->{'itemnumber'} }; if ($renewerror) { - $issue->{'too_many'} = 1 if $renewerror eq 'too_many'; - $issue->{'too_unseen'} = 1 if $renewerror eq 'too_unseen'; - $issue->{'on_reserve'} = 1 if $renewerror eq 'on_reserve'; - $issue->{'norenew_overdue'} = 1 if $renewerror eq 'overdue'; - $issue->{'auto_renew'} = 1 if $renewerror eq 'auto_renew'; - $issue->{'auto_too_soon'} = 1 if $renewerror eq 'auto_too_soon'; - $issue->{'auto_too_late'} = 1 if $renewerror eq 'auto_too_late'; - $issue->{'auto_too_much_oweing'} = 1 if $renewerror eq 'auto_too_much_oweing'; - $issue->{'item_denied_renewal'} = 1 if $renewerror eq 'item_denied_renewal'; + $issue->{'too_many'} = 1 if $renewerror eq 'too_many'; + $issue->{'too_unseen'} = 1 if $renewerror eq 'too_unseen'; + $issue->{'on_reserve'} = 1 if $renewerror eq 'on_reserve'; + $issue->{'norenew_overdue'} = 1 if $renewerror eq 'overdue'; + $issue->{'auto_renew'} = 1 if $renewerror eq 'auto_renew'; + $issue->{'auto_too_soon'} = 1 if $renewerror eq 'auto_too_soon'; + $issue->{'auto_too_late'} = 1 if $renewerror eq 'auto_too_late'; + $issue->{'auto_too_much_oweing'} = 1 if $renewerror eq 'auto_too_much_oweing'; + $issue->{'item_denied_renewal'} = 1 if $renewerror eq 'item_denied_renewal'; $issue->{'item_issued_to_other_patron'} = 1 if $renewerror eq 'item_issued_to_other_patron'; if ( $renewerror eq 'too_soon' ) { @@ -264,29 +272,30 @@ if ( $pending_checkouts->count ) { # Useless test push @overdues, $issue; $overdues_count++; $issue->{'overdue'} = 1; - } - else { + } else { $issue->{'issued'} = 1; } + # imageurl: my $itemtype = $issue->{'itemtype'}; - if ( $itemtype ) { + if ($itemtype) { $issue->{'imageurl'} = getitemtypeimagelocation( 'opac', $itemtypes->{$itemtype}->{'imageurl'} ); $issue->{'description'} = $itemtypes->{$itemtype}->{'description'}; } if ( C4::Context->preference('OpacStarRatings') eq 'all' ) { - my $ratings = Koha::Ratings->search({ biblionumber => $issue->{biblionumber} }); + my $ratings = Koha::Ratings->search( { biblionumber => $issue->{biblionumber} } ); $issue->{ratings} = $ratings; - $issue->{my_rating} = $borrowernumber ? $ratings->search({ borrowernumber => $borrowernumber })->next : undef; + $issue->{my_rating} = + $borrowernumber ? $ratings->search( { borrowernumber => $borrowernumber } )->next : undef; } - my $biblio_object = Koha::Biblios->find($issue->{biblionumber}); + my $biblio_object = Koha::Biblios->find( $issue->{biblionumber} ); $issue->{biblio_object} = $biblio_object; push @issuedat, $issue; $count++; - my $isbn = GetNormalizedISBN($issue->{'isbn'}); + my $isbn = GetNormalizedISBN( $issue->{'isbn'} ); $issue->{normalized_isbn} = $isbn; if ( C4::Context->preference('BakerTaylorEnabled') @@ -305,8 +314,9 @@ if ( $pending_checkouts->count ) { # Useless test } if ( C4::Context->preference('UseRecalls') ) { - my $maybe_recalls = Koha::Recalls->search({ biblio_id => $issue->{biblionumber}, item_id => [ undef, $issue->{itemnumber} ], completed => 0 }); - while( my $recall = $maybe_recalls->next ) { + my $maybe_recalls = Koha::Recalls->search( + { biblio_id => $issue->{biblionumber}, item_id => [ undef, $issue->{itemnumber} ], completed => 0 } ); + while ( my $recall = $maybe_recalls->next ) { if ( $recall->checkout and $recall->checkout->issue_id == $issue->{issue_id} ) { $issue->{recall} = 1; last; @@ -316,16 +326,17 @@ if ( $pending_checkouts->count ) { # Useless test } } my $overduesblockrenewing = C4::Context->preference('OverduesBlockRenewing'); -$canrenew = 0 if ($overduesblockrenewing ne 'allow' and $overdues_count == $count) || !$are_renewable_items; +$canrenew = 0 if ( $overduesblockrenewing ne 'allow' and $overdues_count == $count ) || !$are_renewable_items; -$template->param( ISSUES => \@issuedat ); -$template->param( issues_count => $count ); -$template->param( canrenew => $canrenew ); +$template->param( ISSUES => \@issuedat ); +$template->param( issues_count => $count ); +$template->param( canrenew => $canrenew ); $template->param( OVERDUES => \@overdues ); $template->param( overdues_count => $overdues_count ); -my $show_barcode = Koha::Patron::Attribute::Types->search( # FIXME we should not need this search - { code => ATTRIBUTE_SHOW_BARCODE } )->count; +my $show_barcode = Koha::Patron::Attribute::Types->search( # FIXME we should not need this search + { code => ATTRIBUTE_SHOW_BARCODE } +)->count; if ($show_barcode) { my $patron_show_barcode = $patron->get_extended_attribute(ATTRIBUTE_SHOW_BARCODE); undef $show_barcode if $patron_show_barcode and not $patron_show_barcode->attribute; @@ -336,8 +347,8 @@ $template->param( show_barcode => 1 ) if $show_barcode; my $reserves = $patron->holds->filter_out_has_cancellation_requests; $template->param( - RESERVES => $reserves, - showpriority => $show_priority, + RESERVES => $reserves, + showpriority => $show_priority, ); if ( C4::Context->preference('UseRecalls') ) { @@ -345,33 +356,33 @@ if ( C4::Context->preference('UseRecalls') ) { $template->param( RECALLS => $recalls ); } -if (C4::Context->preference('BakerTaylorEnabled')) { +if ( C4::Context->preference('BakerTaylorEnabled') ) { $template->param( - BakerTaylorEnabled => 1, - BakerTaylorImageURL => &image_url(), - BakerTaylorLinkURL => &link_url(), + BakerTaylorEnabled => 1, + BakerTaylorImageURL => &image_url(), + BakerTaylorLinkURL => &link_url(), BakerTaylorBookstoreURL => C4::Context->preference('BakerTaylorBookstoreURL'), ); } -if (C4::Context->preference("OPACAmazonCoverImages") or - C4::Context->preference("GoogleJackets") or - C4::Context->preference("BakerTaylorEnabled") or - C4::Context->preference("SyndeticsCoverImages") or - ( C4::Context->preference('OPACCustomCoverImages') and C4::Context->preference('CustomCoverImagesURL') ) -) { - $template->param(JacketImages=>1); +if ( C4::Context->preference("OPACAmazonCoverImages") + or C4::Context->preference("GoogleJackets") + or C4::Context->preference("BakerTaylorEnabled") + or C4::Context->preference("SyndeticsCoverImages") + or ( C4::Context->preference('OPACCustomCoverImages') and C4::Context->preference('CustomCoverImagesURL') ) ) +{ + $template->param( JacketImages => 1 ); } $template->param( - overdrive_error => scalar $query->param('overdrive_error') || undef, - overdrive_tab => scalar $query->param('overdrive_tab') || 0, + overdrive_error => scalar $query->param('overdrive_error') || undef, + overdrive_tab => scalar $query->param('overdrive_tab') || 0, ); my $patron_messages = Koha::Patron::Messages->search( { borrowernumber => $borrowernumber, - message_type => 'B', + message_type => 'B', } ); @@ -379,6 +390,7 @@ if ( C4::Context->preference('AllowPatronToSetCheckoutsVisibilityForGuarantor' || C4::Context->preference('AllowStaffToSetCheckoutsVisibilityForGuarantor') ) { my @relatives; + # Filter out guarantees that don't want guarantor to see checkouts foreach my $gr ( $patron->guarantee_relationships->as_list ) { my $g = $gr->guarantee; @@ -391,6 +403,7 @@ if ( C4::Context->preference('AllowPatronToSetFinesVisibilityForGuarantor') || C4::Context->preference('AllowStaffToSetFinesVisibilityForGuarantor') ) { my @relatives_with_fines; + # Filter out guarantees that don't want guarantor to see checkouts foreach my $gr ( $patron->guarantee_relationships->as_list ) { my $g = $gr->guarantee; @@ -401,7 +414,7 @@ if ( C4::Context->preference('AllowPatronToSetFinesVisibilityForGuarantor') if ( C4::Context->preference("ArticleRequests") ) { $template->param( - current_article_requests => [$patron->article_requests->filter_by_current->as_list], + current_article_requests => [ $patron->article_requests->filter_by_current->as_list ], ); } @@ -435,11 +448,11 @@ if ($search_query) { # if not an empty string this indicates to return # back to the page we triggered the login from my $return = $query->param('return'); -if ( $return ) { +if ($return) { my $uri_syspref = C4::Context->preference('OPACBaseURL'); - if ( $uri_syspref ){ + if ($uri_syspref) { my $uri = URI->new($uri_syspref); - if ( $uri->isa('URI::http') && $uri->host() ){ + if ( $uri->isa('URI::http') && $uri->host() ) { my $return_uri = URI->new($return); $return_uri->scheme( $uri->scheme() ); $return_uri->authority( $uri->authority() ); diff --git a/opac/sci/sci-main.pl b/opac/sci/sci-main.pl index d2fdca9e10..34d433a53f 100755 --- a/opac/sci/sci-main.pl +++ b/opac/sci/sci-main.pl @@ -19,13 +19,13 @@ use Modern::Perl; use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Circulation qw( AddReturn ); -use C4::Output qw( output_html_with_http_headers ); +use C4::Output qw( output_html_with_http_headers ); use Koha::Items; use List::MoreUtils qw( uniq ); -use Try::Tiny qw( catch try ); +use Try::Tiny qw( catch try ); my $cgi = CGI->new; @@ -40,10 +40,10 @@ $cgi->param( -name => 'sci_user_login', -values => [1] ); my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "sci/sci-main.tt", - flagsrequired => { self_check => 'self_checkin_module' }, - query => $cgi, - type => "opac" + template_name => "sci/sci-main.tt", + flagsrequired => { self_check => 'self_checkin_module' }, + query => $cgi, + type => "opac" } ); @@ -66,7 +66,7 @@ if ( $op eq 'cud-check_in' ) { foreach my $barcode (@barcodes) { try { my ( $success, $messages, $checkout, $patron ); - my $item = Koha::Items->find( { barcode => $barcode } ); + my $item = Koha::Items->find( { barcode => $barcode } ); my $human_required = 0; if ( C4::Context->preference("CircConfirmItemParts") && defined($item) @@ -77,28 +77,25 @@ if ( $op eq 'cud-check_in' ) { $messages->{additional_materials} = 1; } - ( $success, $messages, $checkout, $patron ) = - AddReturn( $barcode, $library ) unless $human_required; + ( $success, $messages, $checkout, $patron ) = AddReturn( $barcode, $library ) unless $human_required; if ($success) { push @success, - { + { barcode => $barcode, messages => $messages, checkout => $checkout, patron => $patron - }; - } - else { + }; + } else { push @errors, - { + { barcode => $barcode, messages => $messages, checkout => $checkout, patron => $patron - }; + }; } - } - catch { + } catch { push @errors, { barcode => $barcode, messages => 'unknown_error' }; }; } diff --git a/opac/sco/help.pl b/opac/sco/help.pl index e24bfa0ef8..027e309bb2 100755 --- a/opac/sco/help.pl +++ b/opac/sco/help.pl @@ -1,7 +1,7 @@ #!/usr/bin/perl # # This code (originally from circulation.pl) has been modified by: -# Trendsetters, +# Trendsetters, # dan, and # Christina Lee. # @@ -20,15 +20,14 @@ # You should have received a copy of the GNU General Public License # along with Koha; if not, see . - use Modern::Perl; use CGI qw ( -utf8 ); -use C4::Auth qw( in_iprange get_template_and_user ); +use C4::Auth qw( in_iprange get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); my $query = CGI->new; -unless ( in_iprange(C4::Context->preference('SelfCheckAllowByIPRanges')) ) { +unless ( in_iprange( C4::Context->preference('SelfCheckAllowByIPRanges') ) ) { print $query->redirect("/cgi-bin/koha/opac-main.pl"); exit; } @@ -42,18 +41,18 @@ my ( $template, $borrowernumber, $cookie ) = get_template_and_user( } ); -if (C4::Context->preference('SelfCheckoutByLogin')) { - $template->param(SelfCheckoutByLogin => 1); +if ( C4::Context->preference('SelfCheckoutByLogin') ) { + $template->param( SelfCheckoutByLogin => 1 ); } my $selfchecktimeout = 120; -if (C4::Context->preference('SelfCheckTimeout')) { - $selfchecktimeout = C4::Context->preference('SelfCheckTimeout'); +if ( C4::Context->preference('SelfCheckTimeout') ) { + $selfchecktimeout = C4::Context->preference('SelfCheckTimeout'); } -$template->param(SelfCheckTimeout => $selfchecktimeout); +$template->param( SelfCheckTimeout => $selfchecktimeout ); -if (C4::Context->preference('SelfCheckHelpMessage')) { - $template->param(SelfCheckHelpMessage => C4::Context->preference('SelfCheckHelpMessage')); +if ( C4::Context->preference('SelfCheckHelpMessage') ) { + $template->param( SelfCheckHelpMessage => C4::Context->preference('SelfCheckHelpMessage') ); } $template->param( diff --git a/opac/sco/printslip.pl b/opac/sco/printslip.pl index cc24c0d9d6..a43d9a2981 100755 --- a/opac/sco/printslip.pl +++ b/opac/sco/printslip.pl @@ -25,62 +25,64 @@ It is called from sco-main.pl =cut - use Modern::Perl; use CGI qw ( -utf8 ); use C4::Context; -use C4::Auth qw( in_iprange get_session get_template_and_user ); -use C4::Output qw( output_html_with_http_headers ); +use C4::Auth qw( in_iprange get_session get_template_and_user ); +use C4::Output qw( output_html_with_http_headers ); use C4::Members qw( IssueSlip ); - my $input = CGI->new; -unless (C4::Context->preference('WebBasedSelfCheck')) { +unless ( C4::Context->preference('WebBasedSelfCheck') ) { + # redirect to OPAC home if self-check is not enabled print $input->redirect("/cgi-bin/koha/opac-main.pl"); exit; } -unless ( in_iprange(C4::Context->preference('SelfCheckAllowByIPRanges')) ) { +unless ( in_iprange( C4::Context->preference('SelfCheckAllowByIPRanges') ) ) { + # redirect to OPAC home if self-checkout not permitted from current IP print $input->redirect("/cgi-bin/koha/opac-main.pl"); exit; } -$input->param(-name=>'sco_user_login',-values=>[1]); +$input->param( -name => 'sco_user_login', -values => [1] ); # patrons still need to be able to print receipts my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "sco/printslip.tt", - flagsrequired => { self_check => "self_checkout_module" }, - query => $input, - type => "opac", + template_name => "sco/printslip.tt", + flagsrequired => { self_check => "self_checkout_module" }, + query => $input, + type => "opac", } ); -my $jwt = $input->cookie('JWT'); -my $patronid = $jwt ? Koha::Token->new->decode_jwt({ token => $jwt }) : undef; -my $patron = $patronid ? Koha::Patrons->find( { cardnumber => $patronid } ) : undef; +my $jwt = $input->cookie('JWT'); +my $patronid = $jwt ? Koha::Token->new->decode_jwt( { token => $jwt } ) : undef; +my $patron = $patronid ? Koha::Patrons->find( { cardnumber => $patronid } ) : undef; -unless ( $patron ) { - print $input->header(-type => 'text/plain', -status => '403 Forbidden'); +unless ($patron) { + print $input->header( -type => 'text/plain', -status => '403 Forbidden' ); exit; } my $print = $input->param('print'); my $error = $input->param('error'); -my ($slip, $is_html); -if (my $letter = IssueSlip (Koha::Patrons->find( $loggedinuser )->branchcode, $patron->borrowernumber, $print eq "qslip")) { - $slip = $letter->{content}; +my ( $slip, $is_html ); +if ( my $letter = + IssueSlip( Koha::Patrons->find($loggedinuser)->branchcode, $patron->borrowernumber, $print eq "qslip" ) ) +{ + $slip = $letter->{content}; $is_html = $letter->{is_html}; } -$template->{VARS}->{slip} = $slip; -$template->{VARS}->{plain} = !$is_html; +$template->{VARS}->{slip} = $slip; +$template->{VARS}->{plain} = !$is_html; $template->{VARS}->{borrowernumber} = $patron->borrowernumber; -$template->{VARS}->{stylesheet} = C4::Context->preference("SlipCSS"); -$template->{VARS}->{error} = $error; +$template->{VARS}->{stylesheet} = C4::Context->preference("SlipCSS"); +$template->{VARS}->{error} = $error; output_html_with_http_headers $input, $cookie, $template->output; diff --git a/opac/sco/sco-main.pl b/opac/sco/sco-main.pl index 25503fe916..9ecae7c76c 100755 --- a/opac/sco/sco-main.pl +++ b/opac/sco/sco-main.pl @@ -148,7 +148,7 @@ my $confirm_required = 0; my $return_only = 0; my $batch_checkouts_allowed; -if ( $patron ) { +if ($patron) { my @batch_category_codes = split ',', C4::Context->preference('SCOBatchCheckoutsValidCategories'); my $categorycode = $patron->categorycode; if ( $categorycode && grep { $_ eq $categorycode } @batch_category_codes ) { diff --git a/opac/sco/sco-patron-image.pl b/opac/sco/sco-patron-image.pl index 5564003566..90564ed7d8 100755 --- a/opac/sco/sco-patron-image.pl +++ b/opac/sco/sco-patron-image.pl @@ -26,17 +26,17 @@ use Koha::Patrons; my ( $query, $response ) = C4::Service->init( self_check => 'self_checkout_module' ); -unless (C4::Context->preference('WebBasedSelfCheck')) { - print $query->header(status => '403 Forbidden - web-based self-check not enabled'); +unless ( C4::Context->preference('WebBasedSelfCheck') ) { + print $query->header( status => '403 Forbidden - web-based self-check not enabled' ); exit; } -unless (C4::Context->preference('ShowPatronImageInWebBasedSelfCheck')) { - print $query->header(status => '403 Forbidden - displaying patron images in self-check not enabled'); +unless ( C4::Context->preference('ShowPatronImageInWebBasedSelfCheck') ) { + print $query->header( status => '403 Forbidden - displaying patron images in self-check not enabled' ); exit; } -unless ( in_iprange(C4::Context->preference('SelfCheckAllowByIPRanges')) ) { - print $query->header(status => '403 Forbidden - functionality not available from your location'); +unless ( in_iprange( C4::Context->preference('SelfCheckAllowByIPRanges') ) ) { + print $query->header( status => '403 Forbidden - functionality not available from your location' ); exit; } @@ -56,8 +56,8 @@ if ($patron_image) { print $query->header( -type => $patron_image->mimetype, -Content_Length => length( $patron_image->imagefile ) - ), - $patron_image->imagefile; + ), + $patron_image->imagefile; } else { - print $query->header(status => '404 patron image not found'); + print $query->header( status => '404 patron image not found' ); } diff --git a/opac/svc/auth/googleopenidconnect b/opac/svc/auth/googleopenidconnect index 5a18c87a38..a6af900866 100755 --- a/opac/svc/auth/googleopenidconnect +++ b/opac/svc/auth/googleopenidconnect @@ -31,7 +31,7 @@ # use Modern::Perl; -use CGI qw ( -utf8 escape ); +use CGI qw ( -utf8 escape ); use C4::Auth qw{ checkauth get_session get_template_and_user }; use C4::Context; use C4::Output; @@ -42,14 +42,12 @@ use HTTP::Request::Common qw{ POST }; use JSON; use MIME::Base64 qw{ decode_base64url }; -my $discoveryDocURL = - 'https://accounts.google.com/.well-known/openid-configuration'; +my $discoveryDocURL = 'https://accounts.google.com/.well-known/openid-configuration'; my $authendpoint = ''; my $tokenendpoint = ''; my $scope = 'openid email profile'; -my $host = C4::Context->preference('OPACBaseURL') // q{}; -my $restricttodomain = C4::Context->preference('GoogleOpenIDConnectDomain') - // q{}; +my $host = C4::Context->preference('OPACBaseURL') // q{}; +my $restricttodomain = C4::Context->preference('GoogleOpenIDConnectDomain') // q{}; # protocol is assumed in OPACBaseURL see bug 5010. my $redirecturl = $host . '/cgi-bin/koha/svc/auth/googleopenidconnect'; @@ -78,9 +76,9 @@ sub loginfailed { $cgi_query->param( 'OpenIDConnectFailed' => $reason ); my ( $template, $borrowernumber, $cookie ) = get_template_and_user( { - template_name => 'opac-user.tt', - query => $cgi_query, - type => 'opac', + template_name => 'opac-user.tt', + query => $cgi_query, + type => 'opac', } ); $template->param( 'invalidGoogleOpenIDConnectLogin' => $reason ); @@ -90,19 +88,20 @@ sub loginfailed { } if ( defined $query->param('error') ) { - loginfailed( $query, - 'An authentication error occurred. (Error:' - . $query->param('error') - . ')' ); -} -elsif ( defined $query->param('code') ) { + loginfailed( + $query, + 'An authentication error occurred. (Error:' . $query->param('error') . ')' + ); +} elsif ( defined $query->param('code') ) { my $stateclaim = $query->param('state'); my $session = get_session( $query->cookie('CGISESSID') ); if ( $session->param('google-openid-state') ne $stateclaim ) { $session->clear( ["google-openid-state"] ); $session->flush(); - loginfailed( $query, - 'Authentication failed. Your session has an unexpected state.' ); + loginfailed( + $query, + 'Authentication failed. Your session has an unexpected state.' + ); } $session->clear( ["google-openid-state"] ); $session->flush(); @@ -127,17 +126,21 @@ elsif ( defined $query->param('code') ) { my $json = decode_json($response); if ( exists( $json->{'id_token'} ) ) { if ( lc( $json->{'token_type'} ) ne 'bearer' ) { - loginfailed( $query, - 'Authentication failed. Incorrect token type.' ); + loginfailed( + $query, + 'Authentication failed. Incorrect token type.' + ); } my $idtoken = $json->{'id_token'}; -# Normally we'd have to validate the token - but google says not to worry here (Avoids another library!) -# See https://developers.google.com/identity/protocols/OpenIDConnect#obtainuserinfo for rationale + # Normally we'd have to validate the token - but google says not to worry here (Avoids another library!) + # See https://developers.google.com/identity/protocols/OpenIDConnect#obtainuserinfo for rationale my @segments = split( '\.', $idtoken ); unless ( scalar(@segments) == 3 ) { - loginfailed( $query, - 'Login token broken: either too many or too few segments.' ); + loginfailed( + $query, + 'Login token broken: either too many or too few segments.' + ); } my ( $header, $claims, $validation ) = @segments; $claims = decode_base64url($claims); @@ -145,24 +148,27 @@ elsif ( defined $query->param('code') ) { if ( ( $claims_json->{'iss'} ne ( 'https://' . $issuer ) ) && ( $claims_json->{'iss'} ne $issuer ) ) { - loginfailed( $query, + loginfailed( + $query, "Authentication failed. Issuer of authentication isn't Google." ); } if ( ref( $claims_json->{'aud'} ) eq 'ARRAY' ) { - warn "Audience is an array of size: " - . scalar( @$claims_json->{'aud'} ); - if ( scalar( @$claims_json->{'aud'} ) > 1 ) - { # We don't want any other audiences - loginfailed( $query, - "Authentication failed. Unexpected audience provided." ); + warn "Audience is an array of size: " . scalar( @$claims_json->{'aud'} ); + if ( scalar( @$claims_json->{'aud'} ) > 1 ) { # We don't want any other audiences + loginfailed( + $query, + "Authentication failed. Unexpected audience provided." + ); } } if ( ( $claims_json->{'aud'} ne $clientid ) || ( $claims_json->{'azp'} ne $clientid ) ) { - loginfailed( $query, - "Authentication failed. Unexpected audience." ); + loginfailed( + $query, + "Authentication failed. Unexpected audience." + ); } if ( $claims_json->{'exp'} < time() ) { loginfailed( $query, 'Sorry, your authentication has timed out.' ); @@ -173,73 +179,75 @@ elsif ( defined $query->param('code') ) { if ( ( $restricttodomain ne q{} ) && ( index( $email, $restricttodomain ) < 0 ) ) { - loginfailed( $query, -'The email you have used is not valid for this library. Email addresses should conclude with ' - . $restricttodomain - . ' .' ); - } - else { + loginfailed( + $query, + 'The email you have used is not valid for this library. Email addresses should conclude with ' + . $restricttodomain . ' .' + ); + } else { my $error_feedback = -'The email address you are trying to use is not associated with a borrower at this library.'; + 'The email address you are trying to use is not associated with a borrower at this library.'; my $auto_registration = C4::Context->preference('GoogleOpenIDConnectAutoRegister') // q{0}; - my $borrower = Koha::Patrons->find( { email => $email } ); - if (! $borrower && $auto_registration==1) { - my $firstname = $claims_json->{'given_name'} // q{}; - my $surname = $claims_json->{'family_name'} // q{}; - my $delimiter = $firstname ? q{.} : q{}; - my $userid = $firstname . $delimiter . $surname; - my $categorycode = C4::Context->preference('GoogleOpenIDConnectDefaultCategory') // q{}; - my $patron_category = Koha::Patron::Categories->find( $categorycode ); - my $branchcode = C4::Context->preference('GoogleOpenIDConnectDefaultBranch') // q{}; - my $library = Koha::Libraries->find( $branchcode ); - if (defined $patron_category && defined $library) { + my $borrower = Koha::Patrons->find( { email => $email } ); + if ( !$borrower && $auto_registration == 1 ) { + my $firstname = $claims_json->{'given_name'} // q{}; + my $surname = $claims_json->{'family_name'} // q{}; + my $delimiter = $firstname ? q{.} : q{}; + my $userid = $firstname . $delimiter . $surname; + my $categorycode = C4::Context->preference('GoogleOpenIDConnectDefaultCategory') // q{}; + my $patron_category = Koha::Patron::Categories->find($categorycode); + my $branchcode = C4::Context->preference('GoogleOpenIDConnectDefaultBranch') // q{}; + my $library = Koha::Libraries->find($branchcode); + + if ( defined $patron_category && defined $library ) { my $password = undef; + # TODO errors handling! - my $borrower = Koha::Patron->new({ - firstname => $firstname, - surname => $surname, - email => $email, - categorycode => $categorycode, - branchcode => $branchcode, - userid => $userid, - password => $password - })->store; + my $borrower = Koha::Patron->new( + { + firstname => $firstname, + surname => $surname, + email => $email, + categorycode => $categorycode, + branchcode => $branchcode, + userid => $userid, + password => $password + } + )->store; } else { - $error_feedback = 'The GoogleOpenIDConnectDefaultBranch or GoogleOpenIDConnectDefaultCategory system preferences are not configured properly. Please contact the library with this error message.'; + $error_feedback = + 'The GoogleOpenIDConnectDefaultBranch or GoogleOpenIDConnectDefaultCategory system preferences are not configured properly. Please contact the library with this error message.'; } } my ( $userid, $cookie, $session_id ) = - checkauth( $query, 1, {}, 'opac', $email ); + checkauth( $query, 1, {}, 'opac', $email ); if ($userid) { # A user with this email is registered in koha #handle redirect to main.pl, for private opac my $uri; - if (C4::Context->preference('OpacPublic') ) { - $uri = '/cgi-bin/koha/opac-user.pl'; + if ( C4::Context->preference('OpacPublic') ) { + $uri = '/cgi-bin/koha/opac-user.pl'; } else { - $uri = '/cgi-bin/koha/opac-main.pl'; + $uri = '/cgi-bin/koha/opac-main.pl'; } print $query->redirect( -uri => $uri, -cookie => $cookie ); - } - else { + } else { loginfailed( $query, $error_feedback ); } } - } - else { - loginfailed( $query, -'Unexpectedly, no email seems to be associated with that acccount.' + } else { + loginfailed( + $query, + 'Unexpectedly, no email seems to be associated with that acccount.' ); } - } - else { + } else { loginfailed( $query, 'Failed to get proper credentials from Google.' ); } -} -else { +} else { my $session = get_session( $query->cookie('CGISESSID') ); my $openidstate = 'auth_'; $openidstate .= sprintf( "%x", rand 16 ) for 1 .. 32; @@ -251,16 +259,16 @@ else { loginfailed( $query, 'Unable to discover authorisation endpoint.' ); } my $authorisationurl = - $authendpoint . '?' - . 'response_type=code&' - . 'redirect_uri=' - . escape($redirecturl) . q{&} - . 'client_id=' - . escape($clientid) . q{&} - . 'scope=' - . escape($scope) . q{&} - . 'state=' - . escape($openidstate); + $authendpoint . '?' + . 'response_type=code&' + . 'redirect_uri=' + . escape($redirecturl) . q{&} + . 'client_id=' + . escape($clientid) . q{&} + . 'scope=' + . escape($scope) . q{&} + . 'state=' + . escape($openidstate); if ( $prompt || ( defined $prompt && length $prompt > 0 ) ) { $authorisationurl .= '&prompt=' . escape($prompt); } diff --git a/opac/svc/checkout_notes b/opac/svc/checkout_notes index e8281d90fc..c38c18fdbb 100755 --- a/opac/svc/checkout_notes +++ b/opac/svc/checkout_notes @@ -41,9 +41,9 @@ svc/checkout_notes - Web service for setting patron notes on items =cut # AJAX requests -my $is_ajax = is_ajax(); -my $query = CGI->new; -my ( $auth_status ) = check_cookie_auth( $query->cookie('CGISESSID'), {} ); +my $is_ajax = is_ajax(); +my $query = CGI->new; +my ($auth_status) = check_cookie_auth( $query->cookie('CGISESSID'), {} ); if ( $auth_status ne "ok" ) { exit 0; } @@ -52,64 +52,68 @@ if ($is_ajax) { # Issue Note if ( $op eq 'cud-add_note' && C4::Context->preference('AllowCheckoutNotes') ) { - my $scrubber = C4::Scrubber->new(); - my $note = $query->param('note'); - my $issue_id = $query->param('issue_id'); + my $scrubber = C4::Scrubber->new(); + my $note = $query->param('note'); + my $issue_id = $query->param('issue_id'); my $clean_note = $scrubber->scrub($note); - my $status = "saved"; - my ($patron, $issue); + my $status = "saved"; + my ( $patron, $issue ); - my ( $template, $borrowernumber, $cookie ) = C4::Auth::get_template_and_user({ - template_name => "opac-user.tt", - query => $query, - type => "opac", - authnotrequired => 1, - }); + my ( $template, $borrowernumber, $cookie ) = C4::Auth::get_template_and_user( + { + template_name => "opac-user.tt", + query => $query, + type => "opac", + authnotrequired => 1, + } + ); # verify issue_id if ( $issue_id =~ /\d+/ ) { - $patron = Koha::Patrons->find( $borrowernumber ); - $issue = Koha::Checkouts->find($issue_id); + $patron = Koha::Patrons->find($borrowernumber); + $issue = Koha::Checkouts->find($issue_id); if ( $issue->borrowernumber != $borrowernumber ) { $status = "fail"; } } if ( $issue && $status eq "saved" ) { - $issue->set({ notedate => dt_from_string(), note => $clean_note, noteseen => 0 })->store; - if($clean_note) { # only send email if note not empty - my $branch = Koha::Libraries->find( $issue->branchcode ); + $issue->set( { notedate => dt_from_string(), note => $clean_note, noteseen => 0 } )->store; + if ($clean_note) { # only send email if note not empty + my $branch = Koha::Libraries->find( $issue->branchcode ); my $biblionumber = $issue->item->biblionumber; - my $letter = C4::Letters::GetPreparedLetter ( - module => 'circulation', + my $letter = C4::Letters::GetPreparedLetter( + module => 'circulation', letter_code => 'CHECKOUT_NOTE', - branchcode => $branch, - tables => { - 'biblio' => $biblionumber, + branchcode => $branch, + tables => { + 'biblio' => $biblionumber, 'borrowers' => $borrowernumber, - 'issues' => $issue->itemnumber, + 'issues' => $issue->itemnumber, }, ); - my $to_address = $branch->inbound_email_address; + my $to_address = $branch->inbound_email_address; my $reply_address = $patron->email || $patron->emailpro || $patron->B_email; - C4::Letters::EnqueueLetter({ - letter => $letter, - message_transport_type => 'email', - borrowernumber => $patron->borrowernumber, - to_address => $to_address, - reply_address => $reply_address, - }); - } else { # note empty, i.e removed + C4::Letters::EnqueueLetter( + { + letter => $letter, + message_transport_type => 'email', + borrowernumber => $patron->borrowernumber, + to_address => $to_address, + reply_address => $reply_address, + } + ); + } else { # note empty, i.e removed $status = "removed"; } } else { $status = "fail"; } - my $json = encode_json ( { status => $status, note => $clean_note, issue_id => $issue_id } ); - output_with_http_headers($query, undef, $json, 'json'); + my $json = encode_json( { status => $status, note => $clean_note, issue_id => $issue_id } ); + output_with_http_headers( $query, undef, $json, 'json' ); exit; - } # END Issue Note + } # END Issue Note } diff --git a/opac/svc/club/cancel_enrollment b/opac/svc/club/cancel_enrollment index e4f5dc5bf1..d97a6da2fd 100755 --- a/opac/svc/club/cancel_enrollment +++ b/opac/svc/club/cancel_enrollment @@ -28,8 +28,8 @@ use Koha::Club::Enrollments; my $cgi = CGI->new; -my ( $auth_status ) = - check_cookie_auth( $cgi->cookie('CGISESSID') ); +my ($auth_status) = + check_cookie_auth( $cgi->cookie('CGISESSID') ); if ( $auth_status ne "ok" ) { exit 0; } diff --git a/opac/svc/overdrive b/opac/svc/overdrive index 679200f7c4..86e02413cd 100755 --- a/opac/svc/overdrive +++ b/opac/svc/overdrive @@ -19,16 +19,16 @@ # along with Koha; if not, see . use Modern::Perl; -use CGI qw ( -utf8 ); -use JSON qw(encode_json); -use C4::Auth qw( checkauth ); +use CGI qw ( -utf8 ); +use JSON qw(encode_json); +use C4::Auth qw( checkauth ); use C4::Output qw( output_with_http_headers ); use Koha::Logger; use Koha::Patrons; use Koha::Library::OverDriveInfos; use Koha::ExternalContent::OverDrive; -my $logger = Koha::Logger->get({ interface => 'opac' }); +my $logger = Koha::Logger->get( { interface => 'opac' } ); our $cgi = CGI->new; my $page_url = $cgi->referer(); @@ -37,108 +37,108 @@ $user && $sessionID or response_bad_request("User not logged in"); my $action = $cgi->param('action') or response_bad_request("No 'action' specified"); -my $od = Koha::ExternalContent::OverDrive->new({ koha_session_id => $sessionID }); +my $od = Koha::ExternalContent::OverDrive->new( { koha_session_id => $sessionID } ); my %data = ( - is_logged_in => JSON::false, + is_logged_in => JSON::false, ); local $@; eval { - { - $action eq 'cud-login' && do { - my $password = $cgi->param("password") // q{} ; - my $patron = Koha::Patrons->find({ userid => $user }); - my $branch_info = $patron ? Koha::Library::OverDriveInfos->find( $patron->branchcode ) : undef; - my $od_username; - if ( C4::Context->preference('OverDriveUsername') eq 'cardnumber' ){ - $od_username = $patron ? $patron->cardnumber : undef; - } else { - $od_username = $user; - } - my $branch_authname = $branch_info ? $branch_info->authname : undef; - my $authname = $branch_authname || C4::Context->preference('OverDriveAuthname'); - $od->auth_by_userid($od_username, $password,C4::Context->preference('OverDriveWebsiteID'),$authname); - $data{login_success} = 1; + { + $action eq 'cud-login' && do { + my $password = $cgi->param("password") // q{}; + my $patron = Koha::Patrons->find( { userid => $user } ); + my $branch_info = $patron ? Koha::Library::OverDriveInfos->find( $patron->branchcode ) : undef; + my $od_username; + if ( C4::Context->preference('OverDriveUsername') eq 'cardnumber' ) { + $od_username = $patron ? $patron->cardnumber : undef; + } else { + $od_username = $user; + } + my $branch_authname = $branch_info ? $branch_info->authname : undef; + my $authname = $branch_authname || C4::Context->preference('OverDriveAuthname'); + $od->auth_by_userid( $od_username, $password, C4::Context->preference('OverDriveWebsiteID'), $authname ); + $data{login_success} = 1; + last; + }; + + if ( $od->is_logged_in ) { + $data{is_logged_in} = JSON::true; + + $action eq 'cud-logout' && do { + $od->forget(); + $data{login_url} = $od->auth_url($page_url); + $data{is_logged_in} = JSON::false; last; }; - if ($od->is_logged_in) { - $data{is_logged_in} = JSON::true; + $action eq 'account' && do { + $data{account} = $od->patron; + $data{checkouts} = $od->checkouts; + $data{holds} = $od->holds; + last; + }; - $action eq 'cud-logout' && do { - $od->forget(); - $data{login_url} = $od->auth_url($page_url); - $data{is_logged_in} = JSON::false; - last; - }; + $action eq 'cud-checkout' && do { + my $id = $cgi->param('id') + or response_bad_request("No 'id' specified"); + my $format = $cgi->param('format'); + $data{action} = $od->checkout( $id, $format ); + $data{checkouts} = $od->checkouts; + $data{holds} = $od->holds; + last; + }; - $action eq 'account' && do { - $data{account} = $od->patron; - $data{checkouts} = $od->checkouts; - $data{holds} = $od->holds; - last; - }; + $action eq 'cud-checkout-format' && do { + my $id = $cgi->param('id') + or response_bad_request("No 'id' specified"); + my $format = $cgi->param('format') + or response_bad_request("No 'format' specified"); + $data{action} = $od->lock_format( $id, $format ); + $data{checkouts} = $od->checkouts; + last; + }; - $action eq 'cud-checkout' && do { - my $id = $cgi->param('id') - or response_bad_request("No 'id' specified"); - my $format = $cgi->param('format'); - $data{action} = $od->checkout($id, $format); - $data{checkouts} = $od->checkouts; - $data{holds} = $od->holds; - last; - }; + $action eq 'download-url' && do { + my $id = $cgi->param('id') + or response_bad_request("No 'id' specified"); + $data{action} = $od->checkout_download_url($id); + last; + }; - $action eq 'cud-checkout-format' && do { - my $id = $cgi->param('id') - or response_bad_request("No 'id' specified"); - my $format = $cgi->param('format') - or response_bad_request("No 'format' specified"); - $data{action} = $od->lock_format($id, $format); - $data{checkouts} = $od->checkouts; - last; - }; + $action eq 'cud-return' && do { + my $id = $cgi->param('id') + or response_bad_request("No 'id' specified"); + local $@; + $data{action} = eval { $od->return($id) }; + $data{action} = $@ if $@; + $data{checkouts} = $od->checkouts; + last; + }; - $action eq 'download-url' && do { - my $id = $cgi->param('id') - or response_bad_request("No 'id' specified"); - $data{action} = $od->checkout_download_url($id); - last; - }; + $action eq 'cud-place-hold' && do { + my $id = $cgi->param('id') + or response_bad_request("No 'id' specified"); + $data{action} = $od->place_hold($id); + $data{holds} = $od->holds; + last; + }; - $action eq 'cud-return' && do { - my $id = $cgi->param('id') - or response_bad_request("No 'id' specified"); - local $@; - $data{action} = eval { $od->return($id) }; - $data{action} = $@ if $@; - $data{checkouts} = $od->checkouts; - last; - }; + $action eq 'cud-remove-hold' && do { + my $id = $cgi->param('id') + or response_bad_request("No 'id' specified"); + local $@; + $data{action} = eval { $od->remove_hold($id) }; + $data{action} = $@ if $@; + $data{holds} = $od->holds; + last; + }; - $action eq 'cud-place-hold' && do { - my $id = $cgi->param('id') - or response_bad_request("No 'id' specified"); - $data{action} = $od->place_hold($id); - $data{holds} = $od->holds; - last; - }; - - $action eq 'cud-remove-hold' && do { - my $id = $cgi->param('id') - or response_bad_request("No 'id' specified"); - local $@; - $data{action} = eval { $od->remove_hold($id) }; - $data{action} = $@ if $@; - $data{holds} = $od->holds; - last; - }; - - response_bad_request("Invalid 'action': $action"); - } + response_bad_request("Invalid 'action': $action"); } + } }; if ($@) { - if ($od->is_not_authenticated_error("$@")) { + if ( $od->is_not_authenticated_error("$@") ) { $logger->debug("OverDrive session timeout"); $data{is_logged_in} = JSON::false; } else { @@ -147,15 +147,15 @@ if ($@) { } } -response(\%data); - +response( \%data ); sub response_bad_request { my ($error) = @_; - response({error => $error}, "400 $error"); + response( { error => $error }, "400 $error" ); } + sub response { - my ($data, $status_line) = @_; + my ( $data, $status_line ) = @_; $status_line ||= "200 OK"; output_with_http_headers $cgi, undef, encode_json($data), 'json', $status_line; exit; diff --git a/opac/svc/overdrive_proxy b/opac/svc/overdrive_proxy index 9422079b7d..b23f74017d 100755 --- a/opac/svc/overdrive_proxy +++ b/opac/svc/overdrive_proxy @@ -47,38 +47,43 @@ my $query = CGI->new; my $token; -if ( !(C4::Context->preference('OverDriveClientKey') && C4::Context->preference('OverDriveClientSecret')) || !( $token = GetOverDriveToken() ) ) { +if ( !( C4::Context->preference('OverDriveClientKey') && C4::Context->preference('OverDriveClientSecret') ) + || !( $token = GetOverDriveToken() ) ) +{ print $query->header( -status => '400 Bad Request', ); - print to_json({ - error => 'invalid_client', - error_description => 'OverDrive login failed' - }); + print to_json( + { + error => 'invalid_client', + error_description => 'OverDrive login failed' + } + ); exit; } -my $version = $query->param('version') // 1; +my $version = $query->param('version') // 1; my $fixed_query = $query->query_string; $fixed_query =~ tr/;/&/; -my $request = HTTP::Request::Common::GET( "https://api.overdrive.com/v$version" . $query->path_info . '?' . $fixed_query ); +my $request = + HTTP::Request::Common::GET( "https://api.overdrive.com/v$version" . $query->path_info . '?' . $fixed_query ); $request->header( Authorization => $token ); my $ua = LWP::UserAgent->new( "Koha " . Koha::version() ); -my $response = $ua->request( $request ) ; +my $response = $ua->request($request); if ( $response->code eq '500' ) { - print $query->header( - -status => '500 Internal Server Error' - ); + print $query->header( -status => '500 Internal Server Error' ); warn "OverDrive request failed: " . $response->message; - print to_json({ - error => 'invalid_client', - error_description => 'OverDrive request failed' - }); + print to_json( + { + error => 'invalid_client', + error_description => 'OverDrive request failed' + } + ); exit; } diff --git a/opac/svc/report b/opac/svc/report index 434cd4a13e..8d9c851f04 100755 --- a/opac/svc/report +++ b/opac/svc/report @@ -23,7 +23,7 @@ use Modern::Perl; -use C4::Output qw(output_with_http_headers); +use C4::Output qw(output_with_http_headers); use C4::Reports::Guided qw( execute_query ); use Koha::Reports; use JSON; @@ -31,9 +31,9 @@ use CGI qw ( -utf8 ); use Koha::Caches; -my $query = CGI->new(); -my $report_id = $query->param('id'); -my $report_name = $query->param('name'); +my $query = CGI->new(); +my $report_id = $query->param('id'); +my $report_name = $query->param('name'); my $report_annotation = $query->param('annotated'); my $report_recs = Koha::Reports->search( $report_name ? { 'report_name' => $report_name } : { 'id' => $report_id } ); @@ -46,17 +46,17 @@ $report_id = $report_rec->id; die "Sorry this report is not public\n" unless $report_rec->public; my @sql_params = $query->multi_param('sql_params'); -my @param_names = $query->multi_param('param_names'); +my @param_names = $query->multi_param('param_names'); -my $cache = Koha::Caches->get_instance(); +my $cache = Koha::Caches->get_instance(); my $cache_active = $cache->is_cache_active; -my ($cache_key, $json_text); +my ( $cache_key, $json_text ); if ($cache_active) { $cache_key = - "opac:report:" - . ( $report_name ? "name:$report_name:" : "id:$report_id:" ) - . join( '-', @sql_params ) - . join( '_'. @param_names ); + "opac:report:" + . ( $report_name ? "name:$report_name:" : "id:$report_id:" ) + . join( '-', @sql_params ) + . join( '_' . @param_names ); $json_text = $cache->get_from_cache($cache_key); } @@ -67,30 +67,30 @@ unless ($json_text) { my ( $sth, $errors ) = execute_query( { - sql => $sql, - offset => 0, - limit => $limit, - report_id => $report_id, + sql => $sql, + offset => 0, + limit => $limit, + report_id => $report_id, } ); if ($sth) { my $lines; if ($report_annotation) { - $lines = $sth->fetchall_arrayref({}); - } - else { + $lines = $sth->fetchall_arrayref( {} ); + } else { $lines = $sth->fetchall_arrayref; } $json_text = encode_json($lines); if ($cache_active) { - $cache->set_in_cache( $cache_key, $json_text, - { expiry => $report_rec->cache_expiry } ); + $cache->set_in_cache( + $cache_key, $json_text, + { expiry => $report_rec->cache_expiry } + ); } - } - else { + } else { $json_text = encode_json($errors); } } -output_with_http_headers( $query, undef, $json_text, 'json'); +output_with_http_headers( $query, undef, $json_text, 'json' ); diff --git a/opac/svc/shelfbrowser.pl b/opac/svc/shelfbrowser.pl index d9797c2e4e..2f11fa2c72 100755 --- a/opac/svc/shelfbrowser.pl +++ b/opac/svc/shelfbrowser.pl @@ -5,7 +5,7 @@ use CGI qw ( -utf8 ); use C4::Auth qw( get_template_and_user ); use C4::Context; -use C4::Output qw( output_html_with_http_headers ); +use C4::Output qw( output_html_with_http_headers ); use C4::ShelfBrowser qw( GetNearbyItems ); my $cgi = CGI->new; @@ -20,19 +20,19 @@ my ( $template, $borrowernumber, $cookie ) = get_template_and_user( ); # Shelf Browser Stuff -if (C4::Context->preference("OPACShelfBrowser")) { +if ( C4::Context->preference("OPACShelfBrowser") ) { my $starting_itemnumber = $cgi->param('shelfbrowse_itemnumber'); - if (defined($starting_itemnumber)) { + if ( defined($starting_itemnumber) ) { my $nearby = GetNearbyItems($starting_itemnumber); $template->param( - starting_homebranch => $nearby->{starting_homebranch}->{description}, - starting_location => $nearby->{starting_location}->{description}, - starting_ccode => $nearby->{starting_ccode}->{description}, + starting_homebranch => $nearby->{starting_homebranch}->{description}, + starting_location => $nearby->{starting_location}->{description}, + starting_ccode => $nearby->{starting_ccode}->{description}, shelfbrowser_prev_item => $nearby->{prev_item}, shelfbrowser_next_item => $nearby->{next_item}, - shelfbrowser_items => $nearby->{items}, - OpenOPACShelfBrowser => 1, + shelfbrowser_items => $nearby->{items}, + OpenOPACShelfBrowser => 1, ); } } diff --git a/opac/svc/suggestion b/opac/svc/suggestion index 0f8cd5d0d4..9305153430 100755 --- a/opac/svc/suggestion +++ b/opac/svc/suggestion @@ -56,7 +56,7 @@ use Modern::Perl; use C4::Auth qw( get_template_and_user ); use C4::Context; use C4::Output qw( output_html_with_http_headers ); -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use JSON; use Koha::SuggestionEngine; @@ -81,28 +81,26 @@ my ( $template, $loggedinuser, $cookie ) = get_template_and_user( my @plugins = (); -my $pluginsconfig = from_json(C4::Context->preference('OPACdidyoumean') || '[]'); +my $pluginsconfig = from_json( C4::Context->preference('OPACdidyoumean') || '[]' ); foreach my $plugin (@$pluginsconfig) { - push @plugins, $plugin->{name} if ($plugin->{enabled}); + push @plugins, $plugin->{name} if ( $plugin->{enabled} ); } -unless ( @plugins ) { +unless (@plugins) { print $query->header; exit; } my $suggestor = Koha::SuggestionEngine->new( { plugins => \@plugins } ); -my $suggestions = - $suggestor->get_suggestions( { search => $search, count => $count } ); +my $suggestions = $suggestor->get_suggestions( { search => $search, count => $count } ); if ($render) { - $template->{VARS}->{render} = $render; + $template->{VARS}->{render} = $render; $template->{VARS}->{suggestions} = $suggestions if $suggestions; output_html_with_http_headers $query, $cookie, $template->output; -} -else { +} else { print $query->header; print to_json($suggestions); } diff --git a/opac/tracklinks.pl b/opac/tracklinks.pl index 2470359821..f170dd51b8 100755 --- a/opac/tracklinks.pl +++ b/opac/tracklinks.pl @@ -26,29 +26,28 @@ use C4::Output qw( output_error ); use Koha::Biblios; use Koha::Items; use Koha::Linktracker; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use List::MoreUtils qw( any ); -my $cgi = CGI->new; -my $uri = $cgi->param('uri') || ''; -my $biblionumber = $cgi->param('biblionumber');; +my $cgi = CGI->new; +my $uri = $cgi->param('uri') || ''; +my $biblionumber = $cgi->param('biblionumber'); my $itemnumber = $cgi->param('itemnumber'); -$uri =~ s/^\s+|\s+$//g if $uri; # trim +$uri =~ s/^\s+|\s+$//g if $uri; # trim my $tracking_method = C4::Context->preference('TrackClicks'); -unless ( $tracking_method ) { +unless ($tracking_method) { output_error( $cgi, '404' ); exit; } -my $tracker = Koha::Linktracker->new( - { trackingmethod => $tracking_method } ); -if ($uri && ($biblionumber || $itemnumber) ) { +my $tracker = Koha::Linktracker->new( { trackingmethod => $tracking_method } ); +if ( $uri && ( $biblionumber || $itemnumber ) ) { my $borrowernumber; # we have a uri and we want to track if ( $tracker->trackingmethod() eq 'track' ) { my ( $user, $cookie, $sessionID, $flags ) = - checkauth( $cgi, 1, {}, 'opac' ); + checkauth( $cgi, 1, {}, 'opac' ); my $userenv = C4::Context->userenv; if ( defined($userenv) @@ -61,17 +60,17 @@ if ($uri && ($biblionumber || $itemnumber) ) { # get borrower info } - my $biblio = Koha::Biblios->find($biblionumber); - my $record = eval{ $biblio->metadata->record }; - my $marc_urls = $record ? C4::Biblio::GetMarcUrls($record, C4::Context->preference('marcflavour')) : []; + my $biblio = Koha::Biblios->find($biblionumber); + my $record = eval { $biblio->metadata->record }; + my $marc_urls = $record ? C4::Biblio::GetMarcUrls( $record, C4::Context->preference('marcflavour') ) : []; my $search_crit = { uri => { -like => "%$uri%" } }; - if( $itemnumber ) { # itemnumber is leading over biblionumber + if ($itemnumber) { # itemnumber is leading over biblionumber $search_crit->{itemnumber} = $itemnumber; - } elsif( $biblionumber ) { + } elsif ($biblionumber) { $search_crit->{biblionumber} = $biblionumber; } if ( ( any { $_ eq $uri } map { $_->{MARCURL} } @$marc_urls ) - || Koha::Items->search( $search_crit )->count ) + || Koha::Items->search($search_crit)->count ) { $tracker->trackclick( { @@ -80,7 +79,7 @@ if ($uri && ($biblionumber || $itemnumber) ) { borrowernumber => $borrowernumber, itemnumber => $itemnumber } - ) if ( $tracker->trackingmethod() eq 'track' || $tracker->trackingmethod() eq 'anonymous' ); + ) if ( $tracker->trackingmethod() eq 'track' || $tracker->trackingmethod() eq 'anonymous' ); print $cgi->redirect($uri); exit; } diff --git a/patron_lists/add-modify.pl b/patron_lists/add-modify.pl index fac947f942..2f1426b5a4 100755 --- a/patron_lists/add-modify.pl +++ b/patron_lists/add-modify.pl @@ -21,8 +21,8 @@ use Modern::Perl; use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); -use C4::Output qw( output_html_with_http_headers ); +use C4::Auth qw( get_template_and_user ); +use C4::Output qw( output_html_with_http_headers ); use Koha::List::Patron qw( AddPatronList GetPatronLists ModPatronList ); my $cgi = CGI->new; @@ -30,15 +30,15 @@ my $op = $cgi->param('op') // q{}; my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "patron_lists/add-modify.tt", - query => $cgi, - type => "intranet", + template_name => "patron_lists/add-modify.tt", + query => $cgi, + type => "intranet", flagsrequired => { tools => 'manage_patron_lists' }, } ); -my $id = $cgi->param('patron_list_id'); -my $name = $cgi->param('name'); +my $id = $cgi->param('patron_list_id'); +my $name = $cgi->param('name'); my $shared = $cgi->param('shared') ? 1 : 0; if ($id) { @@ -50,11 +50,9 @@ if ( $op eq 'cud-add_modify' && $name ) { if ($id) { ModPatronList( { patron_list_id => $id, name => $name, shared => $shared } ); print $cgi->redirect('lists.pl'); - } - else { + } else { my $list = AddPatronList( { name => $name, shared => $shared } ); - print $cgi->redirect( - "list.pl?patron_list_id=" . $list->patron_list_id() ); + print $cgi->redirect( "list.pl?patron_list_id=" . $list->patron_list_id() ); } exit; diff --git a/patron_lists/list.pl b/patron_lists/list.pl index 3ecf1a8172..63c9f52098 100755 --- a/patron_lists/list.pl +++ b/patron_lists/list.pl @@ -21,8 +21,8 @@ use Modern::Perl; use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); -use C4::Output qw( output_html_with_http_headers ); +use C4::Auth qw( get_template_and_user ); +use C4::Output qw( output_html_with_http_headers ); use Koha::List::Patron qw( AddPatronsToList DelPatronsFromList @@ -35,34 +35,35 @@ my $op = $cgi->param('op') // q{}; my ( $template, $logged_in_user, $cookie ) = get_template_and_user( { - template_name => "patron_lists/list.tt", - query => $cgi, - type => "intranet", + template_name => "patron_lists/list.tt", + query => $cgi, + type => "intranet", flagsrequired => { tools => 'manage_patron_lists' }, } ); my ($list) = - GetPatronLists( { patron_list_id => scalar $cgi->param('patron_list_id') } ); + GetPatronLists( { patron_list_id => scalar $cgi->param('patron_list_id') } ); my @existing = $list->patron_list_patrons; my $patrons_by_id = $cgi->param('patrons_by_id'); -my $id_column = $cgi->param('id_column'); +my $id_column = $cgi->param('id_column'); if ( $op eq 'cud-add' && $patrons_by_id ) { - push my @patrons_list, uniq( split(/\s\n/, $patrons_by_id) ); + push my @patrons_list, uniq( split( /\s\n/, $patrons_by_id ) ); my %add_params; $add_params{list} = $list; - $add_params{ $id_column } = \@patrons_list; - my @results = AddPatronsToList(\%add_params); - my $id = $id_column eq 'borrowernumbers' ? 'borrowernumber' : 'cardnumber'; - my %found = map { $_->borrowernumber->$id => 1 } @results; - my %exist = map { $_->borrowernumber->$id => 1 } @existing; - my (@not_found, @existed); - foreach my $patron ( @patrons_list ){ - push (@not_found, $patron) unless defined $found{$patron}; - push (@existed, $patron) if defined $exist{$patron}; + $add_params{$id_column} = \@patrons_list; + my @results = AddPatronsToList( \%add_params ); + my $id = $id_column eq 'borrowernumbers' ? 'borrowernumber' : 'cardnumber'; + my %found = map { $_->borrowernumber->$id => 1 } @results; + my %exist = map { $_->borrowernumber->$id => 1 } @existing; + my ( @not_found, @existed ); + + foreach my $patron (@patrons_list) { + push( @not_found, $patron ) unless defined $found{$patron}; + push( @existed, $patron ) if defined $exist{$patron}; } $template->param( not_found => \@not_found, @@ -72,12 +73,12 @@ if ( $op eq 'cud-add' && $patrons_by_id ) { } my @patrons_to_add = $cgi->multi_param('patrons_to_add'); -if ( $op eq 'cud-add' && @patrons_to_add) { +if ( $op eq 'cud-add' && @patrons_to_add ) { AddPatronsToList( { list => $list, cardnumbers => \@patrons_to_add } ); } my @patrons_to_remove = $cgi->multi_param('patrons_to_remove'); -if ( $op eq 'cud-delete' && @patrons_to_remove) { +if ( $op eq 'cud-delete' && @patrons_to_remove ) { DelPatronsFromList( { list => $list, patron_list_patrons => \@patrons_to_remove } ); } diff --git a/patron_lists/lists.pl b/patron_lists/lists.pl index f599cd164b..11e883c1f1 100755 --- a/patron_lists/lists.pl +++ b/patron_lists/lists.pl @@ -21,17 +21,17 @@ use Modern::Perl; use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); -use C4::Output qw( output_html_with_http_headers ); +use C4::Auth qw( get_template_and_user ); +use C4::Output qw( output_html_with_http_headers ); use Koha::List::Patron qw( GetPatronLists ); my $cgi = CGI->new; my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "patron_lists/lists.tt", - query => $cgi, - type => "intranet", + template_name => "patron_lists/lists.tt", + query => $cgi, + type => "intranet", flagsrequired => { tools => 'manage_patron_lists' }, } ); diff --git a/patron_lists/patrons.pl b/patron_lists/patrons.pl index f97fcf4662..a859b740d5 100755 --- a/patron_lists/patrons.pl +++ b/patron_lists/patrons.pl @@ -21,17 +21,17 @@ use Modern::Perl; use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); -use C4::Output qw( output_html_with_http_headers ); +use C4::Auth qw( get_template_and_user ); +use C4::Output qw( output_html_with_http_headers ); use Koha::List::Patron qw( AddPatronList GetPatronLists ModPatronList ); my $cgi = CGI->new; my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "patron_lists/add-modify.tt", - query => $cgi, - type => "intranet", + template_name => "patron_lists/add-modify.tt", + query => $cgi, + type => "intranet", flagsrequired => { tools => 'manage_patron_lists' }, } ); @@ -47,8 +47,7 @@ if ($id) { if ($name) { if ($id) { ModPatronList( { patron_list_id => $id, name => $name } ); - } - else { + } else { AddPatronList( { name => $name } ); } diff --git a/patroncards/create-pdf.pl b/patroncards/create-pdf.pl index a6ba2bbd4b..dc4b56a663 100755 --- a/patroncards/create-pdf.pl +++ b/patroncards/create-pdf.pl @@ -18,12 +18,12 @@ # along with Koha; if not, see . use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Auth qw( get_template_and_user ); use Graphics::Magick; use XML::Simple qw( XMLin ); -use POSIX qw( ceil ); -use Storable qw( dclone ); +use POSIX qw( ceil ); +use Storable qw( dclone ); use autouse 'Data::Dumper' => qw(Dumper); use C4::Context; @@ -35,23 +35,25 @@ use Koha::Patron::Images; my $cgi = CGI->new; -my ( $template, $loggedinuser, $cookie ) = get_template_and_user({ - template_name => "labels/label-home.tt", - query => $cgi, - type => "intranet", - flagsrequired => { tools => 'label_creator' }, - }); -my $batch_id = $cgi->param('batch_id') || undef; -my $template_id = $cgi->param('template_id') || undef; -my $layout_id = $cgi->param('layout_id') || undef; +my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "labels/label-home.tt", + query => $cgi, + type => "intranet", + flagsrequired => { tools => 'label_creator' }, + } +); +my $batch_id = $cgi->param('batch_id') || undef; +my $template_id = $cgi->param('template_id') || undef; +my $layout_id = $cgi->param('layout_id') || undef; my $layout_back_id = $cgi->param('layout_back_id') || undef; -my $start_card = $cgi->param('start_card') || 1; -my @label_ids = $cgi->multi_param('label_id'); -my @borrower_numbers = $cgi->multi_param('borrower_number'); -my $patronlist_id = $cgi->param('patronlist_id'); -my $order_by = $cgi->param('order_by') || undef; +my $start_card = $cgi->param('start_card') || 1; +my @label_ids = $cgi->multi_param('label_id'); +my @borrower_numbers = $cgi->multi_param('borrower_number'); +my $patronlist_id = $cgi->param('patronlist_id'); +my $order_by = $cgi->param('order_by') || undef; -my $items = undef; # items = cards +my $items = undef; # items = cards my $new_page = 0; # Wrap pdf creation part into an eval, some vars need scope outside eval @@ -62,238 +64,249 @@ my $cardscount = 0; #Note fo bug 14138: Indenting follows in separate patch to ease review eval { -$pdf_file = (@label_ids || @borrower_numbers ? "card_single_" . scalar(@label_ids || @borrower_numbers) : "card_batch_$batch_id"); + $pdf_file = ( + @label_ids || @borrower_numbers + ? "card_single_" . scalar( @label_ids || @borrower_numbers ) + : "card_batch_$batch_id" + ); -$pdf = C4::Creators::PDF->new(InitVars => 0); -my $batch = C4::Patroncards::Batch->retrieve(batch_id => $batch_id); -my $pc_template = C4::Patroncards::Template->retrieve(template_id => $template_id, profile_id => 1); -my $layout = C4::Patroncards::Layout->retrieve(layout_id => $layout_id); -my $layout_back = $layout_back_id ? C4::Patroncards::Layout->retrieve(layout_id => $layout_back_id) : undef; + $pdf = C4::Creators::PDF->new( InitVars => 0 ); + my $batch = C4::Patroncards::Batch->retrieve( batch_id => $batch_id ); + my $pc_template = C4::Patroncards::Template->retrieve( template_id => $template_id, profile_id => 1 ); + my $layout = C4::Patroncards::Layout->retrieve( layout_id => $layout_id ); + my $layout_back = $layout_back_id ? C4::Patroncards::Layout->retrieve( layout_id => $layout_back_id ) : undef; -$| = 1; + $| = 1; -# set the paper size -my $lower_left_x = 0; -my $lower_left_y = 0; -my $upper_right_x = $pc_template->get_attr('page_width'); -my $upper_right_y = $pc_template->get_attr('page_height'); + # set the paper size + my $lower_left_x = 0; + my $lower_left_y = 0; + my $upper_right_x = $pc_template->get_attr('page_width'); + my $upper_right_y = $pc_template->get_attr('page_height'); -$pdf->Compress(1); # comment this out to debug pdf files, but be sure to uncomment it in production or you may be very sorry... -$pdf->Mbox($lower_left_x, $lower_left_y, $upper_right_x, $upper_right_y); + $pdf->Compress(1) + ; # comment this out to debug pdf files, but be sure to uncomment it in production or you may be very sorry... + $pdf->Mbox( $lower_left_x, $lower_left_y, $upper_right_x, $upper_right_y ); -my ($llx, $lly) = 0,0; -(undef, undef, $llx, $lly) = $pc_template->get_label_position($start_card); + my ( $llx, $lly ) = 0, 0; + ( undef, undef, $llx, $lly ) = $pc_template->get_label_position($start_card); -if (@label_ids) { - my $batch_items = $batch->get_attr('items'); - my @borrowernumbers; - grep { - my $label_id = $_; - push( @borrowernumbers, grep { $_->{'label_id'} == $label_id; } @{$batch_items} ); - } @label_ids; - @borrowernumbers = map { $_->{borrower_number} } @borrowernumbers; - @borrowernumbers = - map { $_->borrowernumber } - Koha::Patrons->search( { borrowernumber => { -in => \@borrowernumbers } }, { order_by => [$order_by] } ) - ->as_list - if ($order_by); - grep { push( @{$items}, { borrower_number => $_ } ); } @borrowernumbers; -} -elsif (@borrower_numbers) { - @borrower_numbers = - map { $_->borrowernumber } - Koha::Patrons->search( { borrowernumber => { -in => \@borrower_numbers } }, { order_by => [$order_by] } ) - ->as_list - if ($order_by); - grep { - push(@{$items}, {borrower_number => $_}); - } @borrower_numbers; -} -elsif ( $patronlist_id ) { - my ($list) = GetPatronLists( { patron_list_id => $patronlist_id } ); - my @borrowerlist = $list->patron_list_patrons()->search_related('borrowernumber') - ->get_column('borrowernumber')->all(); - @borrowerlist = map { $_->borrowernumber } Koha::Patrons->search( {borrowernumber => { -in => \@borrowerlist }}, { order_by => [$order_by]} )->as_list if($order_by); - grep { - push(@{$items}, {borrower_number => $_}); - } @borrowerlist; -} -else { - my $batch_items = $batch->get_attr('items'); - my @borrowernumbers = map { $_->{borrower_number} } @{$batch_items}; - @borrowernumbers = - map { $_->borrowernumber } - Koha::Patrons->search( { borrowernumber => { -in => \@borrowernumbers } }, { order_by => [$order_by] } ) - ->as_list - if ($order_by); - grep { - push(@{$items}, {borrower_number => $_}); - } @borrowernumbers; -} - -my $layout_xml = XMLin($layout->get_attr('layout_xml'), ForceArray => 1); -my $layout_back_xml = defined $layout_back ? XMLin($layout_back->get_attr('layout_xml'), ForceArray => 1) : undef; - -if ($layout_xml->{'page_side'} eq 'B') { # rearrange items on backside of page to swap columns - my $even = 1; - my $odd = 0; - my @swap_array = (); - while ($even <= (scalar(@{$items})+1)) { - push (@swap_array, @{$items}[$even]); - push (@swap_array, @{$items}[$odd]); - $even += 2; - $odd += 2; + if (@label_ids) { + my $batch_items = $batch->get_attr('items'); + my @borrowernumbers; + grep { + my $label_id = $_; + push( @borrowernumbers, grep { $_->{'label_id'} == $label_id; } @{$batch_items} ); + } @label_ids; + @borrowernumbers = map { $_->{borrower_number} } @borrowernumbers; + @borrowernumbers = + map { $_->borrowernumber } + Koha::Patrons->search( { borrowernumber => { -in => \@borrowernumbers } }, { order_by => [$order_by] } ) + ->as_list + if ($order_by); + grep { push( @{$items}, { borrower_number => $_ } ); } @borrowernumbers; + } elsif (@borrower_numbers) { + @borrower_numbers = + map { $_->borrowernumber } + Koha::Patrons->search( { borrowernumber => { -in => \@borrower_numbers } }, { order_by => [$order_by] } ) + ->as_list + if ($order_by); + grep { push( @{$items}, { borrower_number => $_ } ); } @borrower_numbers; + } elsif ($patronlist_id) { + my ($list) = GetPatronLists( { patron_list_id => $patronlist_id } ); + my @borrowerlist = + $list->patron_list_patrons()->search_related('borrowernumber')->get_column('borrowernumber')->all(); + @borrowerlist = + map { $_->borrowernumber } + Koha::Patrons->search( { borrowernumber => { -in => \@borrowerlist } }, { order_by => [$order_by] } ) + ->as_list + if ($order_by); + grep { push( @{$items}, { borrower_number => $_ } ); } @borrowerlist; + } else { + my $batch_items = $batch->get_attr('items'); + my @borrowernumbers = map { $_->{borrower_number} } @{$batch_items}; + @borrowernumbers = + map { $_->borrowernumber } + Koha::Patrons->search( { borrowernumber => { -in => \@borrowernumbers } }, { order_by => [$order_by] } ) + ->as_list + if ($order_by); + grep { push( @{$items}, { borrower_number => $_ } ); } @borrowernumbers; } - @{$items} = @swap_array; -} -# WARNING: Referential nightmare ahead... + my $layout_xml = XMLin( $layout->get_attr('layout_xml'), ForceArray => 1 ); + my $layout_back_xml = defined $layout_back ? XMLin( $layout_back->get_attr('layout_xml'), ForceArray => 1 ) : undef; + + if ( $layout_xml->{'page_side'} eq 'B' ) { # rearrange items on backside of page to swap columns + my $even = 1; + my $odd = 0; + my @swap_array = (); + while ( $even <= ( scalar( @{$items} ) + 1 ) ) { + push( @swap_array, @{$items}[$even] ); + push( @swap_array, @{$items}[$odd] ); + $even += 2; + $odd += 2; + } + @{$items} = @swap_array; + } + + # WARNING: Referential nightmare ahead... CARD_ITEMS: -foreach my $item (@{$items}) { - if ($item) { - my $print_layout_xml = (( ($cardscount % 2 == 1) && ( $layout_back_id ) ) ? - dclone($layout_back_xml) : dclone($layout_xml) ); # We must have a true copy of the layout xml hash, otherwise - # we modify the original template and very bad things happen. + foreach my $item ( @{$items} ) { + if ($item) { + my $print_layout_xml = + ( ( ( $cardscount % 2 == 1 ) && ($layout_back_id) ) ? dclone($layout_back_xml) : dclone($layout_xml) ) + ; # We must have a true copy of the layout xml hash, otherwise + # we modify the original template and very bad things happen. - $cardscount ++; - my $borrower_number = $item->{'borrower_number'}; - my $card_number = Koha::Patrons->find( $borrower_number)->cardnumber; + $cardscount++; + my $borrower_number = $item->{'borrower_number'}; + my $card_number = Koha::Patrons->find($borrower_number)->cardnumber; -# Set barcode data - $print_layout_xml->{'barcode'}->[0]->{'data'} = $card_number if $print_layout_xml->{'barcode'}; + # Set barcode data + $print_layout_xml->{'barcode'}->[0]->{'data'} = $card_number if $print_layout_xml->{'barcode'}; -# Create a new patroncard object - my $patron_card = C4::Patroncards::Patroncard->new( - batch_id => 1, - borrower_number => $borrower_number, - llx => $llx, # lower left corner of the card - lly => $lly, - height => $pc_template->get_attr('label_height'), # of the card - width => $pc_template->get_attr('label_width'), - layout => $print_layout_xml, - text_wrap_cols => 30, #FIXME: hardcoded, - ); + # Create a new patroncard object + my $patron_card = C4::Patroncards::Patroncard->new( + batch_id => 1, + borrower_number => $borrower_number, + llx => $llx, # lower left corner of the card + lly => $lly, + height => $pc_template->get_attr('label_height'), # of the card + width => $pc_template->get_attr('label_width'), + layout => $print_layout_xml, + text_wrap_cols => 30, #FIXME: hardcoded, + ); - $patron_card->draw_guide_box($pdf) if $print_layout_xml->{'guide_box'}; - $patron_card->draw_guide_grid($pdf) if $print_layout_xml->{'guide_grid'}; - $patron_card->draw_barcode($pdf) if $print_layout_xml->{'barcode'}; + $patron_card->draw_guide_box($pdf) if $print_layout_xml->{'guide_box'}; + $patron_card->draw_guide_grid($pdf) if $print_layout_xml->{'guide_grid'}; + $patron_card->draw_barcode($pdf) if $print_layout_xml->{'barcode'}; -# Do image foo and place binary image data into layout hash - my $image_data = {}; - my $error = undef; - my $images = $print_layout_xml->{'images'}; + # Do image foo and place binary image data into layout hash + my $image_data = {}; + my $error = undef; + my $images = $print_layout_xml->{'images'}; PROCESS_IMAGES: - foreach my $card_image (sort(keys %{$images})) { - if (grep{m/(source)/} keys(%{$images->{$card_image}->{'data_source'}->[0]})) { - if ($images->{$card_image}->{'data_source'}->[0]->{'image_source'} eq 'none') { - } - elsif ($images->{$card_image}->{'data_source'}->[0]->{'image_source'} eq 'patronimages') { - my $patron_image = Koha::Patron::Images->find($borrower_number); - if ($patron_image) { - $image_data->{'imagefile'} = $patron_image->imagefile; - } - else { - warn sprintf('No image exists for borrower number %s.', $borrower_number); + foreach my $card_image ( sort( keys %{$images} ) ) { + if ( grep { m/(source)/ } keys( %{ $images->{$card_image}->{'data_source'}->[0] } ) ) { + if ( $images->{$card_image}->{'data_source'}->[0]->{'image_source'} eq 'none' ) { + } elsif ( $images->{$card_image}->{'data_source'}->[0]->{'image_source'} eq 'patronimages' ) { + my $patron_image = Koha::Patron::Images->find($borrower_number); + if ($patron_image) { + $image_data->{'imagefile'} = $patron_image->imagefile; + } else { + warn sprintf( 'No image exists for borrower number %s.', $borrower_number ); + } + } elsif ( $images->{$card_image}->{'data_source'}->[0]->{'image_source'} eq 'creator_images' ) { + ## FIXME: The DB stuff here needs to be religated to a Koha::Creator::Images object -chris_n + my $dbh = C4::Context->dbh(); + $dbh->{LongReadLen} = 1000000; # allows us to read approx 1MB + $image_data = $dbh->selectrow_hashref( + "SELECT imagefile FROM creator_images WHERE image_name = \'$images->{$card_image}->{'data_source'}->[0]->{'image_name'}\'" + ); + warn sprintf( 'Database returned the following error: %s.', $error ) if $error; + unless ($image_data) { + warn sprintf( + 'Image does not exists in db table %s.', + $images->{$card_image}->{'data_source'}->[0]->{'image_name'} + ); + } + } else { + warn sprintf( + 'No retrieval method for image source %s.', + $images->{$card_image}->{'data_source'}->[0]->{'image_source'} + ); } + } else { + warn sprintf( "Unrecognized image data source: %s", $images->{$card_image}->{'data_source'} ); } - elsif ($images->{$card_image}->{'data_source'}->[0]->{'image_source'} eq 'creator_images') { - ## FIXME: The DB stuff here needs to be religated to a Koha::Creator::Images object -chris_n - my $dbh = C4::Context->dbh(); - $dbh->{LongReadLen} = 1000000; # allows us to read approx 1MB - $image_data = $dbh->selectrow_hashref("SELECT imagefile FROM creator_images WHERE image_name = \'$images->{$card_image}->{'data_source'}->[0]->{'image_name'}\'"); - warn sprintf('Database returned the following error: %s.', $error) if $error; - unless($image_data){ - warn sprintf('Image does not exists in db table %s.', $images->{$card_image}->{'data_source'}->[0]->{'image_name'}); - } - } - else { - warn sprintf('No retrieval method for image source %s.', $images->{$card_image}->{'data_source'}->[0]->{'image_source'}); - } + + my $binary_data = $image_data->{'imagefile'} || next PROCESS_IMAGES; + + # invoke the display image object... + my $image = Graphics::Magick->new; + $image->BlobToImage($binary_data); + + # invoke the alt (aka print) image object... + my $alt_image = Graphics::Magick->new; + $alt_image->BlobToImage($binary_data); + $alt_image->Set( magick => 'jpg', quality => 100 ); + + #To avoid pixelation have the image 5 times bigger and + #scale it down in PDF itself + my $oversize_factor = 8; + my $pdf_scale_factor = 1 / $oversize_factor; + + my $alt_width = ceil( $image->Get('width') ) + ; # the rounding up is important: Adobe reader does not handle long decimal numbers well + my $alt_height = ceil( $image->Get('height') ); + my $ratio = $alt_width / $alt_height; + my $display_height = ceil( $images->{$card_image}->{'Dx'} ); + my $display_width = ceil( $ratio * $display_height ); + + $image->Resize( + width => $oversize_factor * $display_width, + height => $oversize_factor * $display_height + ); + $image->Set( magick => 'jpg', quality => 100 ); + + # Write param for downsizing in pdf + $images->{$card_image}->{'scale'} = $pdf_scale_factor; + + # Write params for alt image... + $images->{$card_image}->{'alt'}->{'Sx'} = $oversize_factor * $alt_width; + $images->{$card_image}->{'alt'}->{'Sy'} = $oversize_factor * $alt_height; + $images->{$card_image}->{'alt'}->{'data'} = $alt_image->ImageToBlob(); + + # Write params for display image... + $images->{$card_image}->{'Sx'} = $oversize_factor * $display_width; + $images->{$card_image}->{'Sy'} = $oversize_factor * $display_height; + $images->{$card_image}->{'data'} = $image->ImageToBlob(); + + my $err = $patron_card->draw_image($pdf); + warn sprintf( "Error encountered while attempting to draw image %s, %s", $card_image, $err ) if $err; + + # Destroy all Graphics::Magick objects and related references + # or bad things will happen. + undef $image; + undef $alt_image; + undef $binary_data; } - else { - warn sprintf("Unrecognized image data source: %s", $images->{$card_image}->{'data_source'}); - } - - my $binary_data = $image_data->{'imagefile'} || next PROCESS_IMAGES; - -# invoke the display image object... - my $image = Graphics::Magick->new; - $image->BlobToImage($binary_data); - -# invoke the alt (aka print) image object... - my $alt_image = Graphics::Magick->new; - $alt_image->BlobToImage($binary_data); - $alt_image->Set(magick => 'jpg', quality => 100); - - #To avoid pixelation have the image 5 times bigger and - #scale it down in PDF itself - my $oversize_factor = 8; - my $pdf_scale_factor = 1 / $oversize_factor; - - my $alt_width = ceil($image->Get('width')); # the rounding up is important: Adobe reader does not handle long decimal numbers well - my $alt_height = ceil($image->Get('height')); - my $ratio = $alt_width / $alt_height; - my $display_height = ceil($images->{$card_image}->{'Dx'}); - my $display_width = ceil($ratio * $display_height); - - - $image->Resize(width => $oversize_factor * $display_width, height => $oversize_factor * $display_height); - $image->Set(magick => 'jpg', quality => 100); - -# Write param for downsizing in pdf - $images->{$card_image}->{'scale'} = $pdf_scale_factor; - -# Write params for alt image... - $images->{$card_image}->{'alt'}->{'Sx'} = $oversize_factor * $alt_width; - $images->{$card_image}->{'alt'}->{'Sy'} = $oversize_factor * $alt_height; - $images->{$card_image}->{'alt'}->{'data'} = $alt_image->ImageToBlob(); - -# Write params for display image... - $images->{$card_image}->{'Sx'} = $oversize_factor * $display_width; - $images->{$card_image}->{'Sy'} = $oversize_factor * $display_height; - $images->{$card_image}->{'data'} = $image->ImageToBlob(); - - my $err = $patron_card->draw_image($pdf); - warn sprintf ("Error encountered while attempting to draw image %s, %s", $card_image, $err) if $err; - # Destroy all Graphics::Magick objects and related references - # or bad things will happen. - undef $image; - undef $alt_image; - undef $binary_data; + $patron_card->draw_text($pdf); } - $patron_card->draw_text($pdf); - } - ($llx, $lly, $new_page) = $pc_template->get_next_label_pos(); + ( $llx, $lly, $new_page ) = $pc_template->get_next_label_pos(); - if ( ($cardscount % 2 == 1) && ( $layout_back_id ) ) { - $pdf->Page(); - redo; # Use same patron data again for backside in card printer + if ( ( $cardscount % 2 == 1 ) && ($layout_back_id) ) { + $pdf->Page(); + redo; # Use same patron data again for backside in card printer + } + + $pdf->Page() if $new_page; } - $pdf->Page() if $new_page; -} -# No errors occurred within eval, we can issue the pdf -$pdf_ok = 1 if ($cardscount > 0); -}; # end of eval block + # No errors occurred within eval, we can issue the pdf + $pdf_ok = 1 if ( $cardscount > 0 ); +}; # end of eval block if ($pdf_ok) { + #issue the pdf - print $cgi->header( -type => 'application/pdf', - -encoding => 'utf-8', - -attachment => "$pdf_file.pdf", - ); + print $cgi->header( + -type => 'application/pdf', + -encoding => 'utf-8', + -attachment => "$pdf_file.pdf", + ); $pdf->End(); -} -else { +} else { + # warn user that pdf is not created my $errparams = '&pdferr=1'; - $errparams .= "&errba=$batch_id" if $batch_id; + $errparams .= "&errba=$batch_id" if $batch_id; $errparams .= "&errpl=$patronlist_id" if $patronlist_id; - $errparams = $errparams.'&errpt='.$cgi->param('borrower_number') if $cgi->param('borrower_number'); - $errparams .= "&errlo=$layout_id" if $layout_id; + $errparams = $errparams . '&errpt=' . $cgi->param('borrower_number') if $cgi->param('borrower_number'); + $errparams .= "&errlo=$layout_id" if $layout_id; $errparams .= "&errtpl=$template_id" if $template_id; - $errparams .= "&errnocards=1" if !$cardscount; + $errparams .= "&errnocards=1" if !$cardscount; print $cgi->redirect("/cgi-bin/koha/patroncards/manage.pl?card_element=batch$errparams"); } diff --git a/patroncards/edit-batch.pl b/patroncards/edit-batch.pl index 3f41957cc6..a63012ff7d 100755 --- a/patroncards/edit-batch.pl +++ b/patroncards/edit-batch.pl @@ -18,14 +18,13 @@ # You should have received a copy of the GNU General Public License # along with Koha; if not, see . - use Modern::Perl; use CGI qw ( -utf8 ); use autouse 'Data::Dumper' => qw(Dumper); -use C4::Auth qw( get_template_and_user ); -use C4::Output qw( output_html_with_http_headers ); +use C4::Auth qw( get_template_and_user ); +use C4::Output qw( output_html_with_http_headers ); use C4::Creators qw( get_card_summary html_table ); use C4::Patroncards; use Koha::Patrons; @@ -33,127 +32,127 @@ use Koha::Patrons; my $cgi = CGI->new; my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "patroncards/edit-batch.tt", - query => $cgi, - type => "intranet", - flagsrequired => { tools => 'label_creator' }, + template_name => "patroncards/edit-batch.tt", + query => $cgi, + type => "intranet", + flagsrequired => { tools => 'label_creator' }, } ); -my $err = 0; -my $duplicate_count = undef; +my $err = 0; +my $duplicate_count = undef; my $duplicate_message = undef; -my $db_rows = {}; -my $batch = undef; -my $display_columns = [ {_summary => {label => 'Summary', link_field => 0}}, - {borrowernumber => {label => 'Borrower Number', link_field => 0}}, - {_action => {label => 'Actions ', link_field => 0}}, - {select => {label => 'Select', value => '_label_id'}}, - ]; -my $op = $cgi->param('op') || 'new'; -my $batch_id = $cgi->param('element_id') || $cgi->param('batch_id') || 0; +my $db_rows = {}; +my $batch = undef; +my $display_columns = [ + { _summary => { label => 'Summary', link_field => 0 } }, + { borrowernumber => { label => 'Borrower Number', link_field => 0 } }, + { _action => { label => 'Actions ', link_field => 0 } }, + { select => { label => 'Select', value => '_label_id' } }, +]; +my $op = $cgi->param('op') || 'new'; +my $batch_id = $cgi->param('element_id') || $cgi->param('batch_id') || 0; my $description = $cgi->param('description') || ''; my ( @label_ids, @item_numbers, @borrower_numbers ); -@label_ids = $cgi->multi_param('label_id') if $cgi->param('label_id'); -@item_numbers = $cgi->multi_param('item_number') if $cgi->param('item_number'); +@label_ids = $cgi->multi_param('label_id') if $cgi->param('label_id'); +@item_numbers = $cgi->multi_param('item_number') if $cgi->param('item_number'); @borrower_numbers = $cgi->multi_param('borrower_number') if $cgi->param('borrower_number'); -my $errstr = $cgi->param('error') || ''; +my $errstr = $cgi->param('error') || ''; my $bor_num_list = $cgi->param('bor_num_list') || undef; -my $branch_code = C4::Context->userenv->{'branch'}; +my $branch_code = C4::Context->userenv->{'branch'}; my @errors = ( 'pdferr', 'errnocards', 'errba', 'errpl', 'errpt', 'errlo', 'errtpl', ); foreach my $param (@errors) { my $error = $cgi->param($param) ? 1 : 0; $template->param( 'error_' . $param => $error ) - if $error; + if $error; } if ( $op eq 'cud-remove' ) { - $batch = C4::Patroncards::Batch->retrieve(batch_id => $batch_id); + $batch = C4::Patroncards::Batch->retrieve( batch_id => $batch_id ); foreach my $label_id (@label_ids) { $err = $batch->remove_item($label_id); } if ($err) { - print $cgi->redirect("edit-batch.pl?op=edit&batch_id=$batch_id&error=403"); # this allows us to avoid problems with the user hitting their refresh button + print $cgi->redirect("edit-batch.pl?op=edit&batch_id=$batch_id&error=403") + ; # this allows us to avoid problems with the user hitting their refresh button exit; } -} -elsif ($op eq 'cud-delete') { - $err = C4::Creators::Batch::delete(batch_id => $batch_id, branch_code => $branch_code); +} elsif ( $op eq 'cud-delete' ) { + $err = C4::Creators::Batch::delete( batch_id => $batch_id, branch_code => $branch_code ); if ($err) { print $cgi->redirect("edit-batch.pl?op=edit&batch_id=$batch_id&error=404"); exit; } -} -elsif ($op eq 'cud-add') { -if ($bor_num_list) { - my @bor_nums_unchecked = split /\n/, $bor_num_list; # $bor_num_list is effectively passed in as a separated list +} elsif ( $op eq 'cud-add' ) { + if ($bor_num_list) { + my @bor_nums_unchecked = split /\n/, + $bor_num_list; # $bor_num_list is effectively passed in as a separated list foreach my $number (@bor_nums_unchecked) { - $number =~ s/\r$//; # strip any naughty return chars - if ( Koha::Patrons->find( $number )) { # we must test in case an invalid borrowernumber is passed in; we effectively disgard them atm + $number =~ s/\r$//; # strip any naughty return chars + if ( Koha::Patrons->find($number) ) + { # we must test in case an invalid borrowernumber is passed in; we effectively disgard them atm my $borrower_number = $number; push @borrower_numbers, $borrower_number; } } } - if ($batch_id != 0) {$batch = C4::Patroncards::Batch->retrieve(batch_id => $batch_id);} - if ($batch_id == 0 || $batch == -2) {$batch = C4::Patroncards::Batch->new(branch_code => $branch_code);} + if ( $batch_id != 0 ) { $batch = C4::Patroncards::Batch->retrieve( batch_id => $batch_id ); } + if ( $batch_id == 0 || $batch == -2 ) { $batch = C4::Patroncards::Batch->new( branch_code => $branch_code ); } $template->param( description => $batch->{'description'} ); - if ($branch_code){ + if ($branch_code) { foreach my $borrower_number (@borrower_numbers) { $err = $batch->add_item($borrower_number); } - $batch_id = $batch->get_attr('batch_id') if $batch_id == 0; #update batch_id if we added to a new batch + $batch_id = $batch->get_attr('batch_id') if $batch_id == 0; #update batch_id if we added to a new batch if ($err) { print $cgi->redirect("edit-batch.pl?op=edit&batch_id=$batch_id&error=401"); exit; } - } - else { + } else { print $cgi->redirect("edit-batch.pl?op=edit&batch_id=$batch_id&error=402"); exit; } -} -elsif ( $op eq 'cud-dedup' ) { - $batch = C4::Patroncards::Batch->retrieve(batch_id => $batch_id); - $duplicate_count = $batch->remove_duplicates(); +} elsif ( $op eq 'cud-dedup' ) { + $batch = C4::Patroncards::Batch->retrieve( batch_id => $batch_id ); + $duplicate_count = $batch->remove_duplicates(); $duplicate_message = 1 if $duplicate_count != -1; - if ($duplicate_count == -1) { + if ( $duplicate_count == -1 ) { print $cgi->redirect("edit-batch.pl?op=edit&batch_id=$batch_id&error=405"); exit; } -} -elsif ($op eq 'edit_form') { - $batch = C4::Patroncards::Batch->retrieve(batch_id => $batch_id); +} elsif ( $op eq 'edit_form' ) { + $batch = C4::Patroncards::Batch->retrieve( batch_id => $batch_id ); $template->param( description => $batch->{'description'} ); -} -elsif ($op eq 'new') { - if ($branch_code eq '') { - warn sprintf('Batch edit interface called with an invalid/non-existent branch code: %s',$branch_code ? $branch_code : 'NULL'); +} elsif ( $op eq 'new' ) { + if ( $branch_code eq '' ) { + warn sprintf( + 'Batch edit interface called with an invalid/non-existent branch code: %s', + $branch_code ? $branch_code : 'NULL' + ); print $cgi->redirect("manage.pl?card_element=batch&error=203"); exit; } - $batch = C4::Patroncards::Batch->new(branch_code => $branch_code); + $batch = C4::Patroncards::Batch->new( branch_code => $branch_code ); $batch_id = $batch->get_attr('batch_id'); -} -else { - warn sprintf('Batch edit interface called an unsupported operation: %s',$op); +} else { + warn sprintf( 'Batch edit interface called an unsupported operation: %s', $op ); print $cgi->redirect("manage.pl?card_element=batch&error=202"); exit; } my $items = $batch->get_attr('items'); -$db_rows = get_card_summary(items => $items, batch_id => $batch_id); +$db_rows = get_card_summary( items => $items, batch_id => $batch_id ); -my $table = html_table($display_columns, $db_rows); +my $table = html_table( $display_columns, $db_rows ); $template->param( - op => $op, - batch_id => $batch_id, - table_loop => $table, - duplicate_message => $duplicate_message, - duplicate_count => $duplicate_count, - error => $errstr, - ); + op => $op, + batch_id => $batch_id, + table_loop => $table, + duplicate_message => $duplicate_message, + duplicate_count => $duplicate_count, + error => $errstr, +); output_html_with_http_headers $cgi, $cookie, $template->output; diff --git a/patroncards/edit-layout.pl b/patroncards/edit-layout.pl index 2bc9d1ea9b..8f9bce6a19 100755 --- a/patroncards/edit-layout.pl +++ b/patroncards/edit-layout.pl @@ -20,12 +20,12 @@ use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use XML::Simple qw( XMLin XMLout ); use autouse 'Data::Dumper' => qw(Dumper); -use C4::Auth qw( get_template_and_user ); -use C4::Output qw( output_html_with_http_headers ); +use C4::Auth qw( get_template_and_user ); +use C4::Output qw( output_html_with_http_headers ); use C4::Creators qw( get_all_image_names get_barcode_types @@ -38,115 +38,133 @@ use C4::Patroncards; my $cgi = CGI->new; my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "patroncards/edit-layout.tt", - query => $cgi, - type => "intranet", - flagsrequired => { tools => 'label_creator' }, + template_name => "patroncards/edit-layout.tt", + query => $cgi, + type => "intranet", + flagsrequired => { tools => 'label_creator' }, } ); -my $op = $cgi->param('op') || 'new'; # make 'new' the default operation if none is submitted -my $layout_id = $cgi->param('layout_id') || $cgi->param('element_id') || ''; +my $op = $cgi->param('op') || 'new'; # make 'new' the default operation if none is submitted +my $layout_id = $cgi->param('layout_id') || $cgi->param('element_id') || ''; my $layout_choice = $cgi->param('layout_choice') || ''; -my $layout = ''; -my $layout_xml = undef; +my $layout = ''; +my $layout_xml = undef; -my $units = get_unit_values(); -my $font_types = get_font_types(); +my $units = get_unit_values(); +my $font_types = get_font_types(); my $alignment_types = get_text_justification_types(); -my $barcode_types = get_barcode_types(); -my $image_sources = [ - {type => 'none', name => 'None', selected => 1}, - {type => 'patronimages', name => 'Patron Image', selected => 0}, - {type => 'creator_images', name => 'Other Image', selected => 0}, +my $barcode_types = get_barcode_types(); +my $image_sources = [ + { type => 'none', name => 'None', selected => 1 }, + { type => 'patronimages', name => 'Patron Image', selected => 0 }, + { type => 'creator_images', name => 'Other Image', selected => 0 }, ]; my $image_names = get_all_image_names(); -unshift @$image_names, {type => 'none', name => 'Select Image', selected => 1}; +unshift @$image_names, { type => 'none', name => 'Select Image', selected => 1 }; sub _set_selected { - my ($selection, $source_list) = @_; - my @select_list = (); # we must make a copy of the referent otherwise we modify the original which causes bad things to happen + my ( $selection, $source_list ) = @_; + my @select_list = + (); # we must make a copy of the referent otherwise we modify the original which causes bad things to happen my $selected = 0; - SET_SELECTED: +SET_SELECTED: foreach my $type (@$source_list) { - if (($selection) && ($type->{'type'} eq $selection)) { # even if there is no current selection we must still build the select box + if ( ($selection) && ( $type->{'type'} eq $selection ) ) + { # even if there is no current selection we must still build the select box $selected = 1; - } - else { + } else { $selected = 0; } - push @select_list, {type => $type->{'type'}, name => $type->{'name'}, selected => $selected}; - }; + push @select_list, { type => $type->{'type'}, name => $type->{'name'}, selected => $selected }; + } return \@select_list; } -if ($op eq 'edit_form') { - warn sprintf("Error performing '%s': No 'layout_id' passed in.", $op) unless ($layout_id); - $layout = C4::Patroncards::Layout->retrieve(layout_id => $layout_id); - $layout_xml = XMLin($layout->get_attr('layout_xml'), ForceArray => 1); -# Handle text fields... +if ( $op eq 'edit_form' ) { + warn sprintf( "Error performing '%s': No 'layout_id' passed in.", $op ) unless ($layout_id); + $layout = C4::Patroncards::Layout->retrieve( layout_id => $layout_id ); + $layout_xml = XMLin( $layout->get_attr('layout_xml'), ForceArray => 1 ); + + # Handle text fields... my $field_number = 0; - my @text_fields = (); - if ($layout_xml->{'text'}) { - while (scalar @{$layout_xml->{'text'}}) { + my @text_fields = (); + if ( $layout_xml->{'text'} ) { + while ( scalar @{ $layout_xml->{'text'} } ) { $field_number++; push @text_fields, ( - "field_" . $field_number => 1, # indicate field as currently "selected" for display in form - "field_" . $field_number . "_text" => shift @{$layout_xml->{'text'}}, - ); - my $field_params = shift @{$layout_xml->{'text'}}; + "field_" . $field_number => 1, # indicate field as currently "selected" for display in form + "field_" . $field_number . "_text" => shift @{ $layout_xml->{'text'} }, + ); + my $field_params = shift @{ $layout_xml->{'text'} }; push @text_fields, ( - "field_" . $field_number . "_llx" => $field_params->{'llx'}, - "field_" . $field_number . "_lly" => $field_params->{'lly'}, - "field_" . $field_number . "_height_scale" => $field_params->{'height_scale'}, - "field_" . $field_number . "_width_scale" => $field_params->{'width_scale'}, - "field_" . $field_number . "_font" => _set_selected($field_params->{'font'}, $font_types), - "field_" . $field_number . "_font_size" => $field_params->{'font_size'}, - "field_" . $field_number . "_text_alignment" => _set_selected($field_params->{'text_alignment'}, $alignment_types), - ); + "field_" . $field_number . "_llx" => $field_params->{'llx'}, + "field_" . $field_number . "_lly" => $field_params->{'lly'}, + "field_" . $field_number . "_height_scale" => $field_params->{'height_scale'}, + "field_" . $field_number . "_width_scale" => $field_params->{'width_scale'}, + "field_" . $field_number . "_font" => _set_selected( $field_params->{'font'}, $font_types ), + "field_" . $field_number . "_font_size" => $field_params->{'font_size'}, + "field_" + . $field_number + . "_text_alignment" => _set_selected( $field_params->{'text_alignment'}, $alignment_types ), + ); } } -# Handle fields not currently used - UNUSED_TEXT_FIELDS: - for (my $field = $field_number + 1; $field < 4; $field++) { # limit 3 text fields + # Handle fields not currently used +UNUSED_TEXT_FIELDS: + for ( my $field = $field_number + 1 ; $field < 4 ; $field++ ) { # limit 3 text fields push @text_fields, ( - "field_$field" . "_font" => get_font_types(), - "field_$field" . "_text_alignment" => get_text_justification_types(), - ); + "field_$field" . "_font" => get_font_types(), + "field_$field" . "_text_alignment" => get_text_justification_types(), + ); } -# Handle images... + # Handle images... my $image_count = 0; - my @images = (); - foreach my $image (keys %{$layout_xml->{'images'}}) { + my @images = (); + foreach my $image ( keys %{ $layout_xml->{'images'} } ) { $image_count++; - push @images, ( $image . "_image" => "$image", - $image . "_Dx" => $layout_xml->{'images'}->{$image}->{'Dx'}, - $image . "_Tx" => $layout_xml->{'images'}->{$image}->{'Tx'}, - $image . "_Ty" => $layout_xml->{'images'}->{$image}->{'Ty'}, - $image . "_image_source" => _set_selected($layout_xml->{'images'}->{$image}->{'data_source'}->[0]->{'image_source'}, $image_sources), - $image . "_image_name" => _set_selected($layout_xml->{'images'}->{$image}->{'data_source'}->[0]->{'image_name'}, $image_names), - ); - } - -# Handle image fields not currently used - UNUSED_IMAGE_FIELDS: - for (my $image = $image_count + 1; $image < 3; $image++) { #limit 2 images push @images, ( - "image_$image" . "_image_source" => $image_sources, - "image_$image" . "_image_name" => $image_names, - ); + $image . "_image" => "$image", + $image . "_Dx" => $layout_xml->{'images'}->{$image}->{'Dx'}, + $image . "_Tx" => $layout_xml->{'images'}->{$image}->{'Tx'}, + $image . "_Ty" => $layout_xml->{'images'}->{$image}->{'Ty'}, + $image + . "_image_source" => _set_selected( + $layout_xml->{'images'}->{$image}->{'data_source'}->[0]->{'image_source'}, $image_sources + ), + $image + . "_image_name" => + _set_selected( $layout_xml->{'images'}->{$image}->{'data_source'}->[0]->{'image_name'}, $image_names ), + ); } -# Handle barcodes... + # Handle image fields not currently used +UNUSED_IMAGE_FIELDS: + for ( my $image = $image_count + 1 ; $image < 3 ; $image++ ) { #limit 2 images + push @images, ( + "image_$image" . "_image_source" => $image_sources, + "image_$image" . "_image_name" => $image_names, + ); + } + + # Handle barcodes... my @barcode = (); - foreach my $barcode_param (keys %{$layout_xml->{'barcode'}->[0]}) { - push @barcode, (($barcode_param eq 'type' ? ("barcode_" . $barcode_param => _set_selected($layout_xml->{'barcode'}->[0]->{'type'}, $barcode_types)) : ("barcode_" . $barcode_param => $layout_xml->{'barcode'}->[0]->{$barcode_param}))); + foreach my $barcode_param ( keys %{ $layout_xml->{'barcode'}->[0] } ) { + push @barcode, + ( + ( + $barcode_param eq 'type' + ? ( "barcode_" + . $barcode_param => _set_selected( $layout_xml->{'barcode'}->[0]->{'type'}, $barcode_types ) ) + : ( "barcode_" . $barcode_param => $layout_xml->{'barcode'}->[0]->{$barcode_param} ) + ) + ); } - foreach my $unit (@$units){ - if ($unit->{'type'} eq $layout->get_attr('units')) { + foreach my $unit (@$units) { + if ( $unit->{'type'} eq $layout->get_attr('units') ) { $unit->{'selected'} = 1; } else { $unit->{'selected'} = 0; @@ -154,121 +172,114 @@ if ($op eq 'edit_form') { } $template->param( - layout_id => $layout->get_attr('layout_id') > -1 ? $layout->get_attr('layout_id') : '', - layout_name => $layout->get_attr('layout_name'), - page_side => ($layout_xml->{'page_side'} eq 'F' ? 0 : 1), - guide_box => $layout_xml->{'guide_box'}, - guide_grid => $layout_xml->{'guide_grid'}, - units => $units, - @barcode, - barcode_type => _set_selected($layout_xml->{'barcode'}->[0]->{'type'}, $barcode_types), - @text_fields, - @images, - guidebox => 0, + layout_id => $layout->get_attr('layout_id') > -1 ? $layout->get_attr('layout_id') : '', + layout_name => $layout->get_attr('layout_name'), + page_side => ( $layout_xml->{'page_side'} eq 'F' ? 0 : 1 ), + guide_box => $layout_xml->{'guide_box'}, + guide_grid => $layout_xml->{'guide_grid'}, + units => $units, + @barcode, + barcode_type => _set_selected( $layout_xml->{'barcode'}->[0]->{'type'}, $barcode_types ), + @text_fields, + @images, + guidebox => 0, ); output_html_with_http_headers $cgi, $cookie, $template->output; exit; -} -elsif ($op eq 'cud-save') { +} elsif ( $op eq 'cud-save' ) { my $format_string = undef; - my $layout = {}; - my $layout_name = undef; - my $layout_id = undef; - my $text_lines = []; - my $array_index = 0; - my $image_select = 0; + my $layout = {}; + my $layout_name = undef; + my $layout_id = undef; + my $text_lines = []; + my $array_index = 0; + my $image_select = 0; my $field_enabled = 0; - CGI_PARAMS: - foreach my $parameter ($cgi->multi_param()) { # parse the field values and build a hash of the layout for conversion to xml and storage in the db - if ($parameter =~ m/^field_([0-9])_(.*)$/) { +CGI_PARAMS: + + foreach my $parameter ( $cgi->multi_param() ) + { # parse the field values and build a hash of the layout for conversion to xml and storage in the db + if ( $parameter =~ m/^field_([0-9])_(.*)$/ ) { my $field_number = $1; - my $field_data = $2; + my $field_data = $2; $field_enabled = $field_number if $field_data eq 'enable'; next CGI_PARAMS unless $field_number == $field_enabled; - if ($field_data eq 'text') { + if ( $field_data eq 'text' ) { push @$text_lines, $cgi->multi_param($parameter); - if ($array_index <= 0) { + if ( $array_index <= 0 ) { $array_index++; + } else { + $array_index += 2; # after hitting 1, increment by 2 so counting odds } - else { - $array_index += 2; # after hitting 1, increment by 2 so counting odds - } - } - elsif ($array_index > 0) { + } elsif ( $array_index > 0 ) { $text_lines->[$array_index]->{$field_data} = $cgi->param($parameter); } - } - elsif ($parameter =~ m/^barcode_(.*)$/) { + } elsif ( $parameter =~ m/^barcode_(.*)$/ ) { $field_enabled = $1 if $1 eq 'print'; next CGI_PARAMS unless defined $field_enabled && $field_enabled eq 'print'; $layout->{'barcode'}->{$1} = $cgi->param($parameter); - } - elsif ($parameter =~m/^image_([0-9])_(.*)$/) { + } elsif ( $parameter =~ m/^image_([0-9])_(.*)$/ ) { my $image_number = $1; - my $image_data = $2; - $field_enabled = $image_number if $cgi->param("image_$image_number" . "_image_source") ne 'none'; + my $image_data = $2; + $field_enabled = $image_number if $cgi->param( "image_$image_number" . "_image_source" ) ne 'none'; next CGI_PARAMS unless $image_number == $field_enabled; - if ($image_data =~ m/^image_(.*)$/) { + if ( $image_data =~ m/^image_(.*)$/ ) { $layout->{'images'}->{"image_$image_number"}->{'data_source'}->{"image_$1"} = $cgi->param($parameter); - } - else { + } else { $layout->{'images'}->{"image_$image_number"}->{$image_data} = $cgi->param($parameter); } - } - else { - $layout_name = $cgi->param($parameter) if $parameter eq 'layout_name'; - $layout_id = $cgi->param($parameter) if $parameter eq 'layout_id'; - $layout->{'units'} = $cgi->param($parameter) if $parameter eq 'units'; - $layout->{'page_side'} = $cgi->param($parameter) if $parameter eq 'page_side'; - $layout->{'guide_box'} = $cgi->param($parameter) if $parameter eq 'guide_box'; + } else { + $layout_name = $cgi->param($parameter) if $parameter eq 'layout_name'; + $layout_id = $cgi->param($parameter) if $parameter eq 'layout_id'; + $layout->{'units'} = $cgi->param($parameter) if $parameter eq 'units'; + $layout->{'page_side'} = $cgi->param($parameter) if $parameter eq 'page_side'; + $layout->{'guide_box'} = $cgi->param($parameter) if $parameter eq 'guide_box'; $layout->{'guide_grid'} = $cgi->param($parameter) if $parameter eq 'guide_grid'; } } $layout->{'text'} = $text_lines; - my @params = (layout_name => $layout_name, layout_id => $layout_id, layout_xml => XMLout($layout)); - push(@params,units => $layout->{'units'}) if $layout->{'units'}; - if ($layout_id) { # if a label_id was passed in, this is an update to an existing layout - $layout = C4::Patroncards::Layout->retrieve(layout_id => $layout_id); + my @params = ( layout_name => $layout_name, layout_id => $layout_id, layout_xml => XMLout($layout) ); + push( @params, units => $layout->{'units'} ) if $layout->{'units'}; + if ($layout_id) { # if a label_id was passed in, this is an update to an existing layout + $layout = C4::Patroncards::Layout->retrieve( layout_id => $layout_id ); $layout->set_attr(@params); $layout_id = $layout->save(); - } - else { # if no label_id, this is a new layout so insert it - $layout = C4::Patroncards::Layout->new(@params); + } else { # if no label_id, this is a new layout so insert it + $layout = C4::Patroncards::Layout->new(@params); $layout_id = $layout->save(); } - print $cgi->redirect("manage.pl?card_element=layout" . ($layout_id == -1 ? "&element_id=$layout_id&op=$op&error=101" : '')); + print $cgi->redirect( + "manage.pl?card_element=layout" . ( $layout_id == -1 ? "&element_id=$layout_id&op=$op&error=101" : '' ) ); exit; -} -elsif ($op eq 'new') { # this is a new layout +} elsif ( $op eq 'new' ) { # this is a new layout $layout = C4::Patroncards::Layout->new(); my @fields = (); - for (my $field = 0; $field < 4; $field++) { # limit 3 text fields + for ( my $field = 0 ; $field < 4 ; $field++ ) { # limit 3 text fields push @fields, ( - "field_$field" . "_font" => get_font_types(), - "field_$field" . "_text_alignment" => get_text_justification_types(), - ); + "field_$field" . "_font" => get_font_types(), + "field_$field" . "_text_alignment" => get_text_justification_types(), + ); } my @images = (); - for (my $image = 0; $image < 3; $image++) { #limit 2 images + for ( my $image = 0 ; $image < 3 ; $image++ ) { #limit 2 images push @images, ( - "image_$image" . "_image_source" => $image_sources, - "image_$image" . "_image_name" => $image_names, - ); + "image_$image" . "_image_source" => $image_sources, + "image_$image" . "_image_name" => $image_names, + ); } $template->param( - units => get_unit_values(), - @fields, - barcode_type => get_barcode_types(), - @images, - ); + units => get_unit_values(), + @fields, + barcode_type => get_barcode_types(), + @images, + ); -output_html_with_http_headers $cgi, $cookie, $template->output; -exit; -} -else { # trap unsupported operation here - warn sprintf("Unsupported operation type submitted: %s", $op); + output_html_with_http_headers $cgi, $cookie, $template->output; + exit; +} else { # trap unsupported operation here + warn sprintf( "Unsupported operation type submitted: %s", $op ); print $cgi->redirect("manage.pl?card_element=layout&element_id=$layout_id&error=201"); exit; } diff --git a/patroncards/edit-profile.pl b/patroncards/edit-profile.pl index 2cf29ddaca..c724dcec13 100755 --- a/patroncards/edit-profile.pl +++ b/patroncards/edit-profile.pl @@ -22,65 +22,65 @@ use Modern::Perl; use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); -use C4::Output qw( output_html_with_http_headers ); +use C4::Auth qw( get_template_and_user ); +use C4::Output qw( output_html_with_http_headers ); use C4::Creators::Lib qw( get_all_templates get_unit_values ); use C4::Patroncards::Profile; my $cgi = CGI->new; my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "patroncards/edit-profile.tt", - query => $cgi, - type => "intranet", - flagsrequired => { tools => 'label_creator' }, + template_name => "patroncards/edit-profile.tt", + query => $cgi, + type => "intranet", + flagsrequired => { tools => 'label_creator' }, } ); -my $op = $cgi->param('op') || ''; -my $profile_id = $cgi->param('profile_id') || $cgi->param('element_id'); -my $profile = undef; -my $template_list = undef; +my $op = $cgi->param('op') || ''; +my $profile_id = $cgi->param('profile_id') || $cgi->param('element_id'); +my $profile = undef; +my $template_list = undef; my @label_template = (); my $units = get_unit_values(); -if ($op eq 'edit_form') { - $profile = C4::Patroncards::Profile->retrieve(profile_id => $profile_id); - $template_list = get_all_templates({ fields => [ qw( template_id template_code profile_id ) ] }); -} -elsif ($op eq 'cud-save') { +if ( $op eq 'edit_form' ) { + $profile = C4::Patroncards::Profile->retrieve( profile_id => $profile_id ); + $template_list = get_all_templates( { fields => [qw( template_id template_code profile_id )] } ); +} elsif ( $op eq 'cud-save' ) { my @params = ( - printer_name => scalar $cgi->param('printer_name'), - paper_bin => scalar $cgi->param('paper_bin'), - offset_horz => scalar $cgi->param('offset_horz'), - offset_vert => scalar $cgi->param('offset_vert'), - creep_horz => scalar $cgi->param('creep_horz'), - creep_vert => scalar $cgi->param('creep_vert'), - units => scalar $cgi->param('units'), + printer_name => scalar $cgi->param('printer_name'), + paper_bin => scalar $cgi->param('paper_bin'), + offset_horz => scalar $cgi->param('offset_horz'), + offset_vert => scalar $cgi->param('offset_vert'), + creep_horz => scalar $cgi->param('creep_horz'), + creep_vert => scalar $cgi->param('creep_vert'), + units => scalar $cgi->param('units'), ); - if ($profile_id) { # if a label_id was passed in, this is an update to an existing layout - $profile = C4::Patroncards::Profile->retrieve(profile_id => $profile_id); + if ($profile_id) { # if a label_id was passed in, this is an update to an existing layout + $profile = C4::Patroncards::Profile->retrieve( profile_id => $profile_id ); $profile->set_attr(@params); $profile->save(); - } - else { # if no label_id, this is a new layout so insert it + } else { # if no label_id, this is a new layout so insert it $profile = C4::Patroncards::Profile->new(@params); $profile->save(); } print $cgi->redirect("manage.pl?card_element=profile"); exit; -} -else { # if we get here, this is a new layout +} else { # if we get here, this is a new layout $profile = C4::Patroncards::Profile->new(); } if ($profile_id) { - @label_template = grep{($_->{'profile_id'} == $profile->get_attr('profile_id')) && ($_->{'template_id'} == $profile->get_attr('template_id'))} @$template_list; + @label_template = grep { + ( $_->{'profile_id'} == $profile->get_attr('profile_id') ) + && ( $_->{'template_id'} == $profile->get_attr('template_id') ) + } @$template_list; } foreach my $unit (@$units) { - if ($unit->{'type'} eq $profile->get_attr('units')) { + if ( $unit->{'type'} eq $profile->get_attr('units') ) { $unit->{'selected'} = 1; } } @@ -91,15 +91,15 @@ if ( $profile_id && $profile->get_attr('profile_id') > 0 ) { } $template->param( - label_template => $label_template[0]->{'template_code'} || '', - printer_name => $profile->get_attr('printer_name'), - paper_bin => $profile->get_attr('paper_bin'), - offset_horz => $profile->get_attr('offset_horz'), - offset_vert => $profile->get_attr('offset_vert'), - creep_horz => $profile->get_attr('creep_horz'), - creep_vert => $profile->get_attr('creep_vert'), - units => $units, - op => $op, + label_template => $label_template[0]->{'template_code'} || '', + printer_name => $profile->get_attr('printer_name'), + paper_bin => $profile->get_attr('paper_bin'), + offset_horz => $profile->get_attr('offset_horz'), + offset_vert => $profile->get_attr('offset_vert'), + creep_horz => $profile->get_attr('creep_horz'), + creep_vert => $profile->get_attr('creep_vert'), + units => $units, + op => $op, ); output_html_with_http_headers $cgi, $cookie, $template->output; diff --git a/patroncards/edit-template.pl b/patroncards/edit-template.pl index 804a2ee5e7..9c89e808dd 100755 --- a/patroncards/edit-template.pl +++ b/patroncards/edit-template.pl @@ -23,112 +23,116 @@ use Modern::Perl; use CGI qw ( -utf8 ); use autouse 'Data::Dumper' => qw(Dumper); -use C4::Auth qw( get_template_and_user ); -use C4::Output qw( output_html_with_http_headers ); +use C4::Auth qw( get_template_and_user ); +use C4::Output qw( output_html_with_http_headers ); use C4::Creators qw( get_all_profiles get_unit_values ); use C4::Patroncards; my $cgi = CGI->new; my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "patroncards/edit-template.tt", - query => $cgi, - type => "intranet", - flagsrequired => { tools => 'label_creator' }, + template_name => "patroncards/edit-template.tt", + query => $cgi, + type => "intranet", + flagsrequired => { tools => 'label_creator' }, } ); -my $op = $cgi->param('op') || ''; -my $template_id = $cgi->param('template_id') || $cgi->param('element_id'); +my $op = $cgi->param('op') || ''; +my $template_id = $cgi->param('template_id') || $cgi->param('element_id'); my $card_template = undef; -my $profile_list = undef; +my $profile_list = undef; my $units = get_unit_values(); -if ($op eq 'edit_form') { - $card_template = C4::Patroncards::Template->retrieve(template_id => $template_id); - $profile_list = get_all_profiles({ fields => [ qw( profile_id printer_name paper_bin ) ], filters => {template_id => [ $template_id, 0 ], creator => 'Patroncards'} } ); -} -elsif ($op eq 'cud-save') { - my @params = ( profile_id => scalar $cgi->param('profile_id') || 0, - template_code => scalar $cgi->param('template_code'), - template_desc => scalar $cgi->param('template_desc'), - page_width => scalar $cgi->param('page_width'), - page_height => scalar $cgi->param('page_height'), - label_width => scalar $cgi->param('card_width'), - label_height => scalar $cgi->param('card_height'), - top_margin => scalar $cgi->param('top_margin'), - left_margin => scalar $cgi->param('left_margin'), - cols => scalar $cgi->param('cols'), - rows => scalar $cgi->param('rows'), - col_gap => scalar $cgi->param('col_gap'), - row_gap => scalar $cgi->param('row_gap'), - units => scalar $cgi->param('units'), - ); - if ($template_id) { # if a template_id was passed in, this is an update to an existing template - $card_template = C4::Patroncards::Template->retrieve(template_id => $template_id); - if ($cgi->param('profile_id') && ($card_template->get_attr('template_id') != $cgi->param('profile_id'))) { - if ($card_template->get_attr('profile_id') > 0) { # no need to get the old one if there was no profile associated - my $old_profile = C4::Patroncards::Profile->retrieve(profile_id => $card_template->get_attr('profile_id')); - $old_profile->set_attr(template_id => 0); +if ( $op eq 'edit_form' ) { + $card_template = C4::Patroncards::Template->retrieve( template_id => $template_id ); + $profile_list = get_all_profiles( + { + fields => [qw( profile_id printer_name paper_bin )], + filters => { template_id => [ $template_id, 0 ], creator => 'Patroncards' } + } + ); +} elsif ( $op eq 'cud-save' ) { + my @params = ( + profile_id => scalar $cgi->param('profile_id') || 0, + template_code => scalar $cgi->param('template_code'), + template_desc => scalar $cgi->param('template_desc'), + page_width => scalar $cgi->param('page_width'), + page_height => scalar $cgi->param('page_height'), + label_width => scalar $cgi->param('card_width'), + label_height => scalar $cgi->param('card_height'), + top_margin => scalar $cgi->param('top_margin'), + left_margin => scalar $cgi->param('left_margin'), + cols => scalar $cgi->param('cols'), + rows => scalar $cgi->param('rows'), + col_gap => scalar $cgi->param('col_gap'), + row_gap => scalar $cgi->param('row_gap'), + units => scalar $cgi->param('units'), + ); + if ($template_id) { # if a template_id was passed in, this is an update to an existing template + $card_template = C4::Patroncards::Template->retrieve( template_id => $template_id ); + if ( $cgi->param('profile_id') && ( $card_template->get_attr('template_id') != $cgi->param('profile_id') ) ) { + if ( $card_template->get_attr('profile_id') > 0 ) + { # no need to get the old one if there was no profile associated + my $old_profile = + C4::Patroncards::Profile->retrieve( profile_id => $card_template->get_attr('profile_id') ); + $old_profile->set_attr( template_id => 0 ); $old_profile->save(); } - my $new_profile = C4::Patroncards::Profile->retrieve(profile_id => scalar $cgi->param('profile_id')); - $new_profile->set_attr(template_id => $card_template->get_attr('template_id')); + my $new_profile = C4::Patroncards::Profile->retrieve( profile_id => scalar $cgi->param('profile_id') ); + $new_profile->set_attr( template_id => $card_template->get_attr('template_id') ); $new_profile->save(); } $card_template->set_attr(@params); $card_template->save(); - } - else { # if no template_id, this is a new template so insert it + } else { # if no template_id, this is a new template so insert it $card_template = C4::Patroncards::Template->new(@params); die "Error: $card_template\n" if !ref($card_template); my $template_id = $card_template->save(); - if ($cgi->param('profile_id')) { - my $profile = C4::Patroncards::Profile->retrieve(profile_id => scalar $cgi->param('profile_id')); - $profile->set_attr(template_id => $template_id) if $template_id != $profile->get_attr('template_id'); + if ( $cgi->param('profile_id') ) { + my $profile = C4::Patroncards::Profile->retrieve( profile_id => scalar $cgi->param('profile_id') ); + $profile->set_attr( template_id => $template_id ) if $template_id != $profile->get_attr('template_id'); $profile->save(); } } print $cgi->redirect("manage.pl?card_element=template"); exit; -} -else { # if we get here, this is a new layout +} else { # if we get here, this is a new layout $card_template = C4::Patroncards::Template->new(); } if ($template_id) { foreach my $profile (@$profile_list) { - if ($profile->{'profile_id'} == $card_template->get_attr('profile_id')) { + if ( $profile->{'profile_id'} == $card_template->get_attr('profile_id') ) { $profile->{'selected'} = 1; - } - else { + } else { $profile->{'selected'} = 0; } } } foreach my $unit (@$units) { - if ($unit->{'type'} eq $card_template->get_attr('units')) { + if ( $unit->{'type'} eq $card_template->get_attr('units') ) { $unit->{'selected'} = 1; } } $template->param( - profile_list => $profile_list, - template_id => ($card_template->get_attr('template_id') > 0) ? $card_template->get_attr('template_id') : '', - template_code => $card_template->get_attr('template_code'), - template_desc => $card_template->get_attr('template_desc'), - page_width => $card_template->get_attr('page_width'), - page_height => $card_template->get_attr('page_height'), - card_width => $card_template->get_attr('label_width'), - card_height => $card_template->get_attr('label_height'), - top_margin => $card_template->get_attr('top_margin'), - left_margin => $card_template->get_attr('left_margin'), - cols => $card_template->get_attr('cols'), - rows => $card_template->get_attr('rows'), - col_gap => $card_template->get_attr('col_gap'), - row_gap => $card_template->get_attr('row_gap'), - units => $units, + profile_list => $profile_list, + template_id => ( $card_template->get_attr('template_id') > 0 ) ? $card_template->get_attr('template_id') : '', + template_code => $card_template->get_attr('template_code'), + template_desc => $card_template->get_attr('template_desc'), + page_width => $card_template->get_attr('page_width'), + page_height => $card_template->get_attr('page_height'), + card_width => $card_template->get_attr('label_width'), + card_height => $card_template->get_attr('label_height'), + top_margin => $card_template->get_attr('top_margin'), + left_margin => $card_template->get_attr('left_margin'), + cols => $card_template->get_attr('cols'), + rows => $card_template->get_attr('rows'), + col_gap => $card_template->get_attr('col_gap'), + row_gap => $card_template->get_attr('row_gap'), + units => $units, ); output_html_with_http_headers $cgi, $cookie, $template->output; diff --git a/patroncards/home.pl b/patroncards/home.pl index 93df48f3d3..930bb8282c 100755 --- a/patroncards/home.pl +++ b/patroncards/home.pl @@ -22,16 +22,16 @@ use Modern::Perl; use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); my $cgi = CGI->new; my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "patroncards/home.tt", - query => $cgi, - type => "intranet", - flagsrequired => { tools => 'label_creator' }, + template_name => "patroncards/home.tt", + query => $cgi, + type => "intranet", + flagsrequired => { tools => 'label_creator' }, } ); diff --git a/patroncards/image-manage.pl b/patroncards/image-manage.pl index c018cda753..dd171e673f 100755 --- a/patroncards/image-manage.pl +++ b/patroncards/image-manage.pl @@ -6,163 +6,163 @@ use CGI qw ( -utf8 ); use Graphics::Magick; use C4::Context; -use C4::Auth qw( get_template_and_user ); -use C4::Output qw( output_html_with_http_headers ); -use C4::Creators qw( html_table ); +use C4::Auth qw( get_template_and_user ); +use C4::Output qw( output_html_with_http_headers ); +use C4::Creators qw( html_table ); use C4::Patroncards qw( get_image put_image rm_image ); my $cgi = CGI->new; -my ($template, $loggedinuser, $cookie) = get_template_and_user({ - template_name => "patroncards/image-manage.tt", - query => $cgi, - type => "intranet", - flagsrequired => {tools => 'label_creator'}, - }); +my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "patroncards/image-manage.tt", + query => $cgi, + type => "intranet", + flagsrequired => { tools => 'label_creator' }, + } +); -my $file_name = $cgi->param('uploadfile') || ''; -my $image_name = $cgi->param('image_name') || $file_name; +my $file_name = $cgi->param('uploadfile') || ''; +my $image_name = $cgi->param('image_name') || $file_name; my $upload_file = $cgi->upload('uploadfile') || ''; -my $op = $cgi->param('op') || 'none'; -my @image_ids = $cgi->multi_param('image_id'); +my $op = $cgi->param('op') || 'none'; +my @image_ids = $cgi->multi_param('image_id'); my @errors = ( 'pdferr', 'errnocards', 'errba', 'errpl', 'errpt', 'errlo', 'errtpl', ); foreach my $param (@errors) { my $error = $cgi->param($param) ? 1 : 0; $template->param( 'error_' . $param => $error ) - if $error; + if $error; } -my $source_file = "$file_name"; # otherwise we end up with what amounts to a pointer to a filehandle rather than a user-friendly filename +my $source_file = "$file_name" + ; # otherwise we end up with what amounts to a pointer to a filehandle rather than a user-friendly filename -my $display_columns = { image => [ #{db column => {label => 'col label', is link? }}, - {image_id => {label => 'ID', link_field => 0}}, - {image_name => {label => 'Name', link_field => 0}}, - {_delete => {label => 'Delete', link_field => 0}}, - {select => {label => 'Select', value => 'image_id'}}, - ], +my $display_columns = { + image => [ #{db column => {label => 'col label', is link? }}, + { image_id => { label => 'ID', link_field => 0 } }, + { image_name => { label => 'Name', link_field => 0 } }, + { _delete => { label => 'Delete', link_field => 0 } }, + { select => { label => 'Select', value => 'image_id' } }, + ], }; -my $table = html_table($display_columns->{'image'}, get_image(undef, "image_id, image_name")); +my $table = html_table( $display_columns->{'image'}, get_image( undef, "image_id, image_name" ) ); my $image_limit = C4::Context->preference('ImageLimit') || ''; -my $errstr = ''; # NOTE: For error codes see error-messages.inc +my $errstr = ''; # NOTE: For error codes see error-messages.inc + +if ( $op eq 'cud-upload' ) { -if ($op eq 'cud-upload') { # Checking for duplicate image name - my $dbh = C4::Context->dbh; - my $query = "SELECT COUNT(*) FROM creator_images WHERE image_name=?"; - my ( $exists ) = $dbh->selectrow_array( $query, undef, $image_name ); - if ( $exists ) { + my $dbh = C4::Context->dbh; + my $query = "SELECT COUNT(*) FROM creator_images WHERE image_name=?"; + my ($exists) = $dbh->selectrow_array( $query, undef, $image_name ); + if ($exists) { $errstr = 304; $template->param( IMPORT_SUCCESSFUL => 0, - SOURCE_FILE => $source_file, - IMAGE_NAME => $image_name, - TABLE => $table, - error => $errstr, + SOURCE_FILE => $source_file, + IMAGE_NAME => $image_name, + TABLE => $table, + error => $errstr, ); } else { - if (!$upload_file) { - warn sprintf('An error occurred while attempting to upload file %s.', $source_file); + if ( !$upload_file ) { + warn sprintf( 'An error occurred while attempting to upload file %s.', $source_file ); $errstr = 301; $template->param( IMPORT_SUCCESSFUL => 0, - SOURCE_FILE => $source_file, - IMAGE_NAME => $image_name, - TABLE => $table, - error => $errstr, + SOURCE_FILE => $source_file, + IMAGE_NAME => $image_name, + TABLE => $table, + error => $errstr, ); - } - else { + } else { my $image = Graphics::Magick->new; - eval{$image->Read($cgi->tmpFileName($file_name));}; + eval { $image->Read( $cgi->tmpFileName($file_name) ); }; if ($@) { - warn sprintf('An error occurred while creating the image object: %s',$@); + warn sprintf( 'An error occurred while creating the image object: %s', $@ ); $errstr = 202; $template->param( IMPORT_SUCCESSFUL => 0, - SOURCE_FILE => $source_file, - IMAGE_NAME => $image_name, - TABLE => $table, - error => $errstr, + SOURCE_FILE => $source_file, + IMAGE_NAME => $image_name, + TABLE => $table, + error => $errstr, ); - } - else { + } else { my $errstr = ''; - my $size = $image->Get('filesize'); - $errstr = 302 if $size > 2097152; - $image->Set(magick => 'png'); # convert all images to png as this is a lossless format which is important for resizing operations later on - my $err = put_image($image_name, $image->ImageToBlob()) || '0'; + my $size = $image->Get('filesize'); + $errstr = 302 if $size > 2097152; + $image->Set( magick => 'png' ) + ; # convert all images to png as this is a lossless format which is important for resizing operations later on + my $err = put_image( $image_name, $image->ImageToBlob() ) || '0'; $errstr = 101 if $err == 1; $errstr = 303 if $err == 202; if ($errstr) { $template->param( IMPORT_SUCCESSFUL => 0, - SOURCE_FILE => $source_file, - IMAGE_NAME => $image_name, - TABLE => $table, - error => $errstr, - image_limit => $image_limit, + SOURCE_FILE => $source_file, + IMAGE_NAME => $image_name, + TABLE => $table, + error => $errstr, + image_limit => $image_limit, ); - } - else { - $table = html_table($display_columns->{'image'}, get_image(undef, "image_id, image_name")); # refresh table data after successfully performing save operation + } else { + $table = html_table( $display_columns->{'image'}, get_image( undef, "image_id, image_name" ) ) + ; # refresh table data after successfully performing save operation $template->param( IMPORT_SUCCESSFUL => 1, - SOURCE_FILE => $source_file, - IMAGE_NAME => $image_name, - TABLE => $table, + SOURCE_FILE => $source_file, + IMAGE_NAME => $image_name, + TABLE => $table, ); } } } } -} -elsif ($op eq 'cud-delete') { - my $err = ''; +} elsif ( $op eq 'cud-delete' ) { + my $err = ''; my $errstr = ''; if (@image_ids) { - $err = rm_image(\@image_ids); + $err = rm_image( \@image_ids ); $errstr = 102 if $err; - } - else { + } else { warn sprintf('No image ids passed in to delete.'); $errstr = 202; } if ($errstr) { $template->param( DELETE_SUCCESSFULL => 0, - IMAGE_IDS => join(', ', @image_ids), - TABLE => $table, - error => $errstr, - image_ids => join(',',@image_ids), + IMAGE_IDS => join( ', ', @image_ids ), + TABLE => $table, + error => $errstr, + image_ids => join( ',', @image_ids ), ); - } - else { - $table = html_table($display_columns->{'image'}, get_image(undef, "image_id, image_name")); # refresh table data after successfully performing delete operation + } else { + $table = html_table( $display_columns->{'image'}, get_image( undef, "image_id, image_name" ) ) + ; # refresh table data after successfully performing delete operation $template->param( DELETE_SUCCESSFULL => 1, - TABLE => $table, + TABLE => $table, ); } -} -elsif ($op eq 'none') { +} elsif ( $op eq 'none' ) { $template->param( IMPORT_SUCCESSFUL => 0, - SOURCE_FILE => $source_file, - IMAGE_NAME => $image_name, - TABLE => $table, + SOURCE_FILE => $source_file, + IMAGE_NAME => $image_name, + TABLE => $table, ); -} -else { # to trap unsupported operations - warn sprintf('Image upload interface called an unsupported operation: %s',$op); +} else { # to trap unsupported operations + warn sprintf( 'Image upload interface called an unsupported operation: %s', $op ); $errstr = 201; $template->param( IMPORT_SUCCESSFUL => 0, - SOURCE_FILE => $source_file, - IMAGE_NAME => $image_name, - TABLE => $table, - error => $errstr, + SOURCE_FILE => $source_file, + IMAGE_NAME => $image_name, + TABLE => $table, + error => $errstr, ); } diff --git a/patroncards/manage.pl b/patroncards/manage.pl index 4cb37f1f83..a439c35b41 100755 --- a/patroncards/manage.pl +++ b/patroncards/manage.pl @@ -23,8 +23,8 @@ use Modern::Perl; use CGI qw ( -utf8 ); use autouse 'Data::Dumper' => qw(Dumper); -use C4::Auth qw( get_template_and_user ); -use C4::Output qw( output_html_with_http_headers ); +use C4::Auth qw( get_template_and_user ); +use C4::Output qw( output_html_with_http_headers ); use C4::Creators qw( get_all_layouts get_all_profiles @@ -38,10 +38,10 @@ use Koha::List::Patron qw( GetPatronLists ); my $cgi = CGI->new; my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "patroncards/manage.tt", - query => $cgi, - type => "intranet", - flagsrequired => { tools => 'label_creator' }, + template_name => "patroncards/manage.tt", + query => $cgi, + type => "intranet", + flagsrequired => { tools => 'label_creator' }, } ); @@ -49,90 +49,109 @@ my @errors = ( 'pdferr', 'errnocards', 'errba', 'errpl', 'errpt', 'errlo', 'errt foreach my $param (@errors) { my $error = $cgi->param($param) ? 1 : 0; $template->param( 'error_' . $param => $error ) - if $error; + if $error; } -my $op = $cgi->param('op') || 'none'; -my $card_element = $cgi->param('card_element') || 'template'; # default to template management -my $element_id = $cgi->param('element_id') || 0; # there should never be an element with a id of 0 so this is a safe default +my $op = $cgi->param('op') || 'none'; +my $card_element = $cgi->param('card_element') || 'template'; # default to template management +my $element_id = + $cgi->param('element_id') || 0; # there should never be an element with a id of 0 so this is a safe default -my $db_rows = {}; -my $display_columns = { layout => [ # db column => {col label is link? - {layout_id => {label => 'Layout ID', link_field => 0}}, - {layout_name => {label => 'Layout', link_field => 0}}, - {_action => {label => 'Action', link_field => 0}}, - #{layout_xml => {label => 'Layout XML', link_field => 0}}, - {select => {label => 'Select', value => 'layout_id'}}, - ], - template => [ {template_id => {label => 'Template ID', link_field => 0}}, - {template_code => {label => 'Template Name', link_field => 0}}, - {template_desc => {label => 'Description', link_field => 0}}, - {_action => {label => 'Action', link_field => 0}}, - {select => {label => 'Select', value => 'template_id'}}, - ], - profile => [ {profile_id => {label => 'Profile ID', link_field => 0}}, - {printer_name => {label => 'Printer Name', link_field => 0}}, - {paper_bin => {label => 'Paper Bin', link_field => 0}}, - {_template_code => {label => 'Template Name', link_field => 0}}, # this display column does not have a corresponding db column in the profile table, hence the underscore - {_action => {label => 'Action', link_field => 0}}, - {select => {label => 'Select', value => 'profile_id'}}, - ], - batch => [ {batch_id => {label => 'Batch ID', link_field => 0}}, - {description => {label => 'Description', link_field => 0}}, - {_item_count => {label => 'Patron Count', link_field => 0}}, - {_action => {label => 'Actions', link_field => 0}}, - {select => {label => 'Select', value => 'batch_id'}}, - ], +my $db_rows = {}; +my $display_columns = { + layout => [ # db column => {col label is link? + { layout_id => { label => 'Layout ID', link_field => 0 } }, + { layout_name => { label => 'Layout', link_field => 0 } }, + { _action => { label => 'Action', link_field => 0 } }, + + #{layout_xml => {label => 'Layout XML', link_field => 0}}, + { select => { label => 'Select', value => 'layout_id' } }, + ], + template => [ + { template_id => { label => 'Template ID', link_field => 0 } }, + { template_code => { label => 'Template Name', link_field => 0 } }, + { template_desc => { label => 'Description', link_field => 0 } }, + { _action => { label => 'Action', link_field => 0 } }, + { select => { label => 'Select', value => 'template_id' } }, + ], + profile => [ + { profile_id => { label => 'Profile ID', link_field => 0 } }, + { printer_name => { label => 'Printer Name', link_field => 0 } }, + { paper_bin => { label => 'Paper Bin', link_field => 0 } }, + { _template_code => { label => 'Template Name', link_field => 0 } } + , # this display column does not have a corresponding db column in the profile table, hence the underscore + { _action => { label => 'Action', link_field => 0 } }, + { select => { label => 'Select', value => 'profile_id' } }, + ], + batch => [ + { batch_id => { label => 'Batch ID', link_field => 0 } }, + { description => { label => 'Description', link_field => 0 } }, + { _item_count => { label => 'Patron Count', link_field => 0 } }, + { _action => { label => 'Actions', link_field => 0 } }, + { select => { label => 'Select', value => 'batch_id' } }, + ], }; -my $errstr = ($cgi->param('error') ? $cgi->param('error') : ''); -my $branch_code = ($card_element eq 'batch' ? C4::Context->userenv->{'branch'} : ''); +my $errstr = ( $cgi->param('error') ? $cgi->param('error') : '' ); +my $branch_code = ( $card_element eq 'batch' ? C4::Context->userenv->{'branch'} : '' ); -if ($op eq 'cud-delete') { - my $err = 0; - my @element_ids = split(/,/, $element_id); +if ( $op eq 'cud-delete' ) { + my $err = 0; + my @element_ids = split( /,/, $element_id ); foreach my $element_id (@element_ids) { - if ($card_element eq 'layout') {$err = C4::Patroncards::Layout::delete(layout_id => $element_id);} - elsif ($card_element eq 'template') {$err = C4::Patroncards::Template::delete(template_id => $element_id);} - elsif ($card_element eq 'profile') {$err = C4::Patroncards::Profile::delete(profile_id => $element_id);} - elsif ($card_element eq 'batch') {$err = C4::Labels::Batch::delete(batch_id => $element_id, branch_code => $branch_code);} - else {warn sprintf("Unknown card element passed in for delete operation: %s.",$card_element); $errstr = 202;} + if ( $card_element eq 'layout' ) { $err = C4::Patroncards::Layout::delete( layout_id => $element_id ); } + elsif ( $card_element eq 'template' ) { + $err = C4::Patroncards::Template::delete( template_id => $element_id ); + } elsif ( $card_element eq 'profile' ) { + $err = C4::Patroncards::Profile::delete( profile_id => $element_id ); + } elsif ( $card_element eq 'batch' ) { + $err = C4::Labels::Batch::delete( batch_id => $element_id, branch_code => $branch_code ); + } else { + warn sprintf( "Unknown card element passed in for delete operation: %s.", $card_element ); + $errstr = 202; + } } - print $cgi->redirect("manage.pl?card_element=$card_element" . ($err ? "&error=102" : '')); + print $cgi->redirect( "manage.pl?card_element=$card_element" . ( $err ? "&error=102" : '' ) ); exit; -} -elsif ($op eq 'none') { - if ($card_element eq 'layout') {$db_rows = get_all_layouts( { filters => { creator => 'Patroncards' } });} - elsif ($card_element eq 'template') {$db_rows = get_all_templates( { filters => { creator => 'Patroncards' } });} - elsif ($card_element eq 'profile') {$db_rows = get_all_profiles( { filters => { creator => 'Patroncards' } });} - elsif ($card_element eq 'batch') {$db_rows = get_batch_summary( { filters => { branch_code => [ $branch_code, 'NB' ], creator => 'Patroncards' } });} - else {warn sprintf("Unknown card element passed in: %s.",$card_element); $errstr = 202;} -} -else { # trap unsupported operations here - warn sprintf('Manage interface called an unsupported operation: %s',$op); +} elsif ( $op eq 'none' ) { + if ( $card_element eq 'layout' ) { $db_rows = get_all_layouts( { filters => { creator => 'Patroncards' } } ); } + elsif ( $card_element eq 'template' ) { + $db_rows = get_all_templates( { filters => { creator => 'Patroncards' } } ); + } elsif ( $card_element eq 'profile' ) { + $db_rows = get_all_profiles( { filters => { creator => 'Patroncards' } } ); + } elsif ( $card_element eq 'batch' ) { + $db_rows = + get_batch_summary( { filters => { branch_code => [ $branch_code, 'NB' ], creator => 'Patroncards' } } ); + } else { + warn sprintf( "Unknown card element passed in: %s.", $card_element ); + $errstr = 202; + } +} else { # trap unsupported operations here + warn sprintf( 'Manage interface called an unsupported operation: %s', $op ); print $cgi->redirect("manage.pl?card_element=$card_element&error=201"); exit; } -my $table = html_table($display_columns->{$card_element}, $db_rows); +my $table = html_table( $display_columns->{$card_element}, $db_rows ); -$template->param(print => 1) if ($card_element eq 'batch'); -$template->param( patron_lists => [ GetPatronLists() ] ) if ($card_element eq 'batch'); +$template->param( print => 1 ) if ( $card_element eq 'batch' ); +$template->param( patron_lists => [ GetPatronLists() ] ) if ( $card_element eq 'batch' ); $template->param( - error => $errstr, + error => $errstr, ); $template->param( - op => $op, - element_id => $element_id, - table_loop => $table, - card_element => $card_element, - card_element_title => ($card_element eq 'layout' ? 'Layouts' : - $card_element eq 'template' ? 'Templates' : - $card_element eq 'profile' ? 'Profiles' : - $card_element eq 'batch' ? 'Batches' : - '' - ), + op => $op, + element_id => $element_id, + table_loop => $table, + card_element => $card_element, + card_element_title => ( + $card_element eq 'layout' ? 'Layouts' + : $card_element eq 'template' ? 'Templates' + : $card_element eq 'profile' ? 'Profiles' + : $card_element eq 'batch' ? 'Batches' + : '' + ), ); output_html_with_http_headers $cgi, $cookie, $template->output; diff --git a/patroncards/print.pl b/patroncards/print.pl index c9fb194310..91fe4f4284 100755 --- a/patroncards/print.pl +++ b/patroncards/print.pl @@ -22,127 +22,141 @@ use Modern::Perl; use CGI qw ( -utf8 ); use autouse 'Data::Dumper' => qw(Dumper); -use C4::Auth qw( get_template_and_user ); -use C4::Output qw( output_html_with_http_headers ); +use C4::Auth qw( get_template_and_user ); +use C4::Output qw( output_html_with_http_headers ); use C4::Creators qw( get_all_layouts get_all_templates get_output_formats ); my $cgi = CGI->new; my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "patroncards/print.tt", - query => $cgi, - type => "intranet", - flagsrequired => { tools => 'label_creator' }, + template_name => "patroncards/print.tt", + query => $cgi, + type => "intranet", + flagsrequired => { tools => 'label_creator' }, } ); -my $op = $cgi->param('op') || 'none'; -my @label_ids = $cgi->multi_param('label_id'); # this will handle individual card printing; we use label_id to maintain consistency with the column names in the creator_batches table -my @batch_ids = $cgi->multi_param('batch_id'); -my $patronlist_id = $cgi->param('patronlist_id') || undef; -my $layout_id = $cgi->param('layout_id') || undef; -my $layout_back_id = $cgi->param('layout_back_id') || undef; -my $template_id = $cgi->param('template_id') || undef; -my $start_card = $cgi->param('start_card') || 1; +my $op = $cgi->param('op') || 'none'; +my @label_ids = $cgi->multi_param('label_id') + ; # this will handle individual card printing; we use label_id to maintain consistency with the column names in the creator_batches table +my @batch_ids = $cgi->multi_param('batch_id'); +my $patronlist_id = $cgi->param('patronlist_id') || undef; +my $layout_id = $cgi->param('layout_id') || undef; +my $layout_back_id = $cgi->param('layout_back_id') || undef; +my $template_id = $cgi->param('template_id') || undef; +my $start_card = $cgi->param('start_card') || 1; my @borrower_numbers = $cgi->multi_param('borrower_number'); -my $output_format = $cgi->param('output_format') || 'pdf'; -my $referer = $cgi->param('referer') || undef; -my $order_by = $cgi->param('order_by') || undef; +my $output_format = $cgi->param('output_format') || 'pdf'; +my $referer = $cgi->param('referer') || undef; +my $order_by = $cgi->param('order_by') || undef; -my $layouts = undef; -my $templates = undef; -my $output_formats = undef; -my @batches = (); +my $layouts = undef; +my $templates = undef; +my $output_formats = undef; +my @batches = (); my $multi_batch_count = scalar(@batch_ids); -my $card_count = scalar(@label_ids); -my $borrower_count = scalar(@borrower_numbers); +my $card_count = scalar(@label_ids); +my $borrower_count = scalar(@borrower_numbers); -if ($op eq 'export') { +if ( $op eq 'export' ) { if (@label_ids) { my $label_id_param = '&label_id='; - $label_id_param .= join ('&label_id=',@label_ids); - push (@batches, {create_script => ($output_format eq 'pdf' ? 'create-pdf.pl' : 'create-csv.pl'), #FIXME csv not supported, no script? - batch_id => $batch_ids[0], - template_id => $template_id, - layout_id => $layout_id, - layout_back_id => $layout_back_id, - start_card => $start_card, - label_ids => $label_id_param, - card_count => scalar(@label_ids), - }); + $label_id_param .= join( '&label_id=', @label_ids ); + push( + @batches, + { + create_script => ( $output_format eq 'pdf' ? 'create-pdf.pl' : 'create-csv.pl' ) + , #FIXME csv not supported, no script? + batch_id => $batch_ids[0], + template_id => $template_id, + layout_id => $layout_id, + layout_back_id => $layout_back_id, + start_card => $start_card, + label_ids => $label_id_param, + card_count => scalar(@label_ids), + } + ); $template->param( - batches => \@batches, - referer => $referer, - order_by => $order_by, - ); - } - elsif (@borrower_numbers) { + batches => \@batches, + referer => $referer, + order_by => $order_by, + ); + } elsif (@borrower_numbers) { my $borrower_number_param = '&borrower_number='; - $borrower_number_param .= join ('&borrower_number=',@borrower_numbers); - push (@batches, {create_script => ($output_format eq 'pdf' ? 'create-pdf.pl' : 'create-csv.pl'), #FIXME csv not supported, no script? - template_id => $template_id, - layout_id => $layout_id, - layout_back_id => $layout_back_id, - start_card => $start_card, - borrower_numbers => $borrower_number_param, - card_count => scalar(@borrower_numbers), - }); + $borrower_number_param .= join( '&borrower_number=', @borrower_numbers ); + push( + @batches, + { + create_script => ( $output_format eq 'pdf' ? 'create-pdf.pl' : 'create-csv.pl' ) + , #FIXME csv not supported, no script? + template_id => $template_id, + layout_id => $layout_id, + layout_back_id => $layout_back_id, + start_card => $start_card, + borrower_numbers => $borrower_number_param, + card_count => scalar(@borrower_numbers), + } + ); $template->param( - batches => \@batches, - referer => $referer, - order_by => $order_by, - ); - } - elsif (@batch_ids) { + batches => \@batches, + referer => $referer, + order_by => $order_by, + ); + } elsif (@batch_ids) { foreach my $batch_id (@batch_ids) { - push (@batches, {create_script => ($output_format eq 'pdf' ? 'create-pdf.pl' : 'create-csv.pl'), #FIXME csv not supported, no script? - batch_id => $batch_id, - template_id => $template_id, - layout_id => $layout_id, - layout_back_id => $layout_back_id, - start_card => $start_card, - }); + push( + @batches, + { + create_script => ( $output_format eq 'pdf' ? 'create-pdf.pl' : 'create-csv.pl' ) + , #FIXME csv not supported, no script? + batch_id => $batch_id, + template_id => $template_id, + layout_id => $layout_id, + layout_back_id => $layout_back_id, + start_card => $start_card, + } + ); } $template->param( - batches => \@batches, - referer => $referer, - order_by => $order_by, - ); - } - elsif ($patronlist_id ) { + batches => \@batches, + referer => $referer, + order_by => $order_by, + ); + } elsif ($patronlist_id) { $template->param( - patronlist_id => $patronlist_id, - template_id => $template_id, - layout_id => $layout_id, - layout_back_id => $layout_back_id, - start_card => $start_card, - referer => $referer, - order_by => $order_by, - ); + patronlist_id => $patronlist_id, + template_id => $template_id, + layout_id => $layout_id, + layout_back_id => $layout_back_id, + start_card => $start_card, + referer => $referer, + order_by => $order_by, + ); } -} -elsif ($op eq 'none') { +} elsif ( $op eq 'none' ) { + # setup select menus for selecting layout and template for this run... $referer = $ENV{'HTTP_REFERER'}; $referer =~ s/^.*?:\/\/.*?(\/.*)$/$1/m; - @batch_ids = map { {batch_id => $_} } @batch_ids; - @label_ids = map { {label_id => $_} } @label_ids; - @borrower_numbers = map { {borrower_number => $_} } @borrower_numbers; - $templates = get_all_templates( { fields => [qw( template_id template_code ) ], filters => { creator => "Patroncards" } }); - $layouts = get_all_layouts({ fields => [ qw( layout_id layout_name ) ], filters => { creator => "Patroncards" } }); + @batch_ids = map { { batch_id => $_ } } @batch_ids; + @label_ids = map { { label_id => $_ } } @label_ids; + @borrower_numbers = map { { borrower_number => $_ } } @borrower_numbers; + $templates = + get_all_templates( { fields => [qw( template_id template_code )], filters => { creator => "Patroncards" } } ); + $layouts = get_all_layouts( { fields => [qw( layout_id layout_name )], filters => { creator => "Patroncards" } } ); $output_formats = get_output_formats(); $template->param( - batch_ids => \@batch_ids, - label_ids => \@label_ids, - borrower_numbers => \@borrower_numbers, - patronlist_id => $patronlist_id, - templates => $templates, - layouts => $layouts, - output_formats => $output_formats, - multi_batch_count => $multi_batch_count, - card_count => $card_count, - borrower_count => $borrower_count, - referer => $referer, - ); + batch_ids => \@batch_ids, + label_ids => \@label_ids, + borrower_numbers => \@borrower_numbers, + patronlist_id => $patronlist_id, + templates => $templates, + layouts => $layouts, + output_formats => $output_formats, + multi_batch_count => $multi_batch_count, + card_count => $card_count, + borrower_count => $borrower_count, + referer => $referer, + ); } output_html_with_http_headers $cgi, $cookie, $template->output; diff --git a/plugins/plugins-enable.pl b/plugins/plugins-enable.pl index 79cd88af88..f244c762b6 100755 --- a/plugins/plugins-enable.pl +++ b/plugins/plugins-enable.pl @@ -27,18 +27,20 @@ die("Koha plugins are disabled!") unless C4::Context->config("enable_plugins"); my $input = CGI->new; -my ( $auth_status ) = check_cookie_auth( $input->cookie('CGISESSID'), { plugins => 'manage' } ); -if( $auth_status ne 'ok' ) { +my ($auth_status) = check_cookie_auth( $input->cookie('CGISESSID'), { plugins => 'manage' } ); +if ( $auth_status ne 'ok' ) { print CGI::header( '-status' => '401' ); exit 0; } -my $class = $input->param('class'); +my $class = $input->param('class'); my $method = $input->param('method'); -Koha::Plugins::Handler->run({ - class => $class, - method => $method -}); +Koha::Plugins::Handler->run( + { + class => $class, + method => $method + } +); print $input->redirect("/cgi-bin/koha/plugins/plugins-home.pl"); diff --git a/plugins/plugins-home.pl b/plugins/plugins-home.pl index 60b3cde213..5152f40214 100755 --- a/plugins/plugins-home.pl +++ b/plugins/plugins-home.pl @@ -21,25 +21,26 @@ use Modern::Perl; use CGI qw ( -utf8 ); -use JSON qw( from_json ); +use JSON qw( from_json ); use LWP::Simple qw( get ); use Koha::Plugins; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use C4::Context; my $plugins_enabled = C4::Context->config("enable_plugins"); -my $input = CGI->new; -my $method = $input->param('method'); +my $input = CGI->new; +my $method = $input->param('method'); my $plugin_search = $input->param('plugin-search'); my ( $template, $borrowernumber, $cookie ) = get_template_and_user( - { template_name => ($plugins_enabled) ? "plugins/plugins-home.tt" : "plugins/plugins-disabled.tt", + { + template_name => ($plugins_enabled) ? "plugins/plugins-home.tt" : "plugins/plugins-disabled.tt", query => $input, type => "intranet", - flagsrequired => { plugins => '*' }, + flagsrequired => { plugins => '*' }, } ); @@ -67,23 +68,24 @@ if ($plugins_enabled) { my $repos = C4::Context->config('plugin_repos'); # Fix data structure if only one repo defined - if ( ref($repos->{repo}) eq 'HASH' ) { + if ( ref( $repos->{repo} ) eq 'HASH' ) { $repos = { repo => [ $repos->{repo} ] }; } foreach my $r ( @{ $repos->{repo} } ) { if ( $r->{service} eq 'github' ) { - my $url = "https://api.github.com/search/repositories?q=$plugin_search+user:$r->{org_name}+in:name,description"; + my $url = + "https://api.github.com/search/repositories?q=$plugin_search+user:$r->{org_name}+in:name,description"; my $response = from_json( get($url) ); foreach my $result ( @{ $response->{items} } ) { next unless $result->{name} =~ /^koha-plugin-/; my $releases = $result->{url} . "/releases/latest"; my $release_info = get($releases); next unless $release_info; - my $release = from_json( $release_info ); + my $release = from_json($release_info); my $tag_name = $release->{tag_name}; - for my $asset ( @{$release->{assets}} ) { - if ($asset->{browser_download_url} =~ m/\.kpz$/) { + for my $asset ( @{ $release->{assets} } ) { + if ( $asset->{browser_download_url} =~ m/\.kpz$/ ) { $result->{install_name} = $asset->{name}; $result->{install_url} = $asset->{browser_download_url}; $result->{tag_name} = $tag_name; @@ -91,16 +93,16 @@ if ($plugins_enabled) { } push( @results, { repo => $r, result => $result } ); } - } - elsif ( $r->{service} eq 'gitlab' ) { + } elsif ( $r->{service} eq 'gitlab' ) { my $org_name = $r->{org_name}; - my $url = "https://gitlab.com/api/v4/groups/$org_name/projects?with_issues_enabled=no\&with_merge_requests_enabled=no\&with_shared=no\&include_subgroups=yes\&search=koha-plugin+$plugin_search"; + my $url = + "https://gitlab.com/api/v4/groups/$org_name/projects?with_issues_enabled=no\&with_merge_requests_enabled=no\&with_shared=no\&include_subgroups=yes\&search=koha-plugin+$plugin_search"; my $response = from_json( get($url) ); - foreach my $result ( @{ $response } ) { + foreach my $result ( @{$response} ) { next unless $result->{name} =~ /^koha-plugin-/; - my $project_id = $result->{id}; - my $description = $result->{description} // ''; - my $web_url = $result->{web_url}; + my $project_id = $result->{id}; + my $description = $result->{description} // ''; + my $web_url = $result->{web_url}; my $releases_url = "https://gitlab.com/api/v4/projects/$project_id/releases"; my $releases_info = get($releases_url); next unless $releases_info; diff --git a/plugins/plugins-uninstall.pl b/plugins/plugins-uninstall.pl index 76385647b8..886126a0b1 100755 --- a/plugins/plugins-uninstall.pl +++ b/plugins/plugins-uninstall.pl @@ -31,10 +31,11 @@ die("Koha plugins are disabled!") unless C4::Context->config("enable_plugins"); my $input = CGI->new; my ( $template, $loggedinuser, $cookie ) = get_template_and_user( - { template_name => "plugins/plugins-upload.tt", - query => $input, - type => "intranet", - flagsrequired => { plugins => 'manage' }, + { + template_name => "plugins/plugins-upload.tt", + query => $input, + type => "intranet", + flagsrequired => { plugins => 'manage' }, } ); diff --git a/plugins/plugins-upload.pl b/plugins/plugins-upload.pl index b158f51662..bfd353f219 100755 --- a/plugins/plugins-upload.pl +++ b/plugins/plugins-upload.pl @@ -19,7 +19,7 @@ use Modern::Perl; use Archive::Extract; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use List::Util qw( any ); use Mojo::UserAgent; use File::Temp; @@ -35,7 +35,7 @@ my $plugins_enabled = C4::Context->config("enable_plugins"); my $plugins_restricted = C4::Context->config("plugins_restricted"); my $plugins_restart = C4::Context->config("plugins_restart"); -my $input = CGI->new; +my $input = CGI->new; my $uploadlocation = $input->param('uploadlocation'); my ( $template, $loggedinuser, $cookie ) = get_template_and_user( @@ -51,7 +51,7 @@ my ( $template, $loggedinuser, $cookie ) = get_template_and_user( $template->param( plugins_restart => $plugins_restart ); # Early exist if uploads are not enabled direct upload attempted when uploads are restricted -if (!$plugins_enabled) { +if ( !$plugins_enabled ) { output_html_with_http_headers $input, $cookie, $template->output; exit; } elsif ( $plugins_restricted && !$uploadlocation ) { diff --git a/plugins/run.pl b/plugins/run.pl index 4570844291..fa02f94f61 100755 --- a/plugins/run.pl +++ b/plugins/run.pl @@ -22,7 +22,7 @@ use Modern::Perl; use CGI qw ( -utf8 ); use Koha::Plugins::Handler; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use C4::Context; @@ -34,14 +34,15 @@ my $class = $cgi->param('class'); my $method = $cgi->param('method'); my ( $template, $borrowernumber, $cookie ) = get_template_and_user( - { template_name => "plugins/plugins-disabled.tt", - query => $cgi, - type => "intranet", - flagsrequired => { plugins => $method }, + { + template_name => "plugins/plugins-disabled.tt", + query => $cgi, + type => "intranet", + flagsrequired => { plugins => $method }, } ); -if ( $plugins_enabled ) { +if ($plugins_enabled) { my $plugin = Koha::Plugins::Handler->run( { class => $class, method => $method, cgi => $cgi } ); } else { output_html_with_http_headers( $cgi, $cookie, $template->output ); diff --git a/pos/pay.pl b/pos/pay.pl index 45cd1119c8..390b48696b 100755 --- a/pos/pay.pl +++ b/pos/pay.pl @@ -50,12 +50,12 @@ my $logged_in_user = Koha::Patrons->find($loggedinuser) or die "Not logged in"; my $library_id = C4::Context->userenv->{'branch'}; my $registerid = $input->param('registerid'); -my $op = $input->param('op') || ''; +my $op = $input->param('op') || ''; -my $invoice_types = - Koha::Account::DebitTypes->search_with_library_limits( +my $invoice_types = Koha::Account::DebitTypes->search_with_library_limits( { can_be_sold => 1, archived => 0 }, - {}, $library_id ); + {}, $library_id +); $template->param( invoice_types => $invoice_types ); if ( $op eq 'cud-pay' ) { @@ -112,8 +112,8 @@ if ( $op eq 'cud-send' ) { { letter => $letter, message_transport_type => 'email', - from_address => C4::Context->preference('KohaAdminEmailAddress'), - to_address => $toaddr, + from_address => C4::Context->preference('KohaAdminEmailAddress'), + to_address => $toaddr, } ); diff --git a/pos/printreceipt.pl b/pos/printreceipt.pl index 70833c3dce..e615bfbd8e 100755 --- a/pos/printreceipt.pl +++ b/pos/printreceipt.pl @@ -19,9 +19,9 @@ use Modern::Perl; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_and_exit_if_error output_and_exit output_html_with_http_headers ); -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use Koha::Account::Lines; use Koha::Notice::Templates; @@ -50,7 +50,7 @@ output_and_exit_if_error( } ) if $patron; # Payment could have been anonymous -my $lang = $patron ? $patron->lang : $template->lang; +my $lang = $patron ? $patron->lang : $template->lang; my $letter = C4::Letters::GetPreparedLetter( module => 'pos', letter_code => 'RECEIPT', diff --git a/pos/register.pl b/pos/register.pl index 53bb5d2325..2043ded9ce 100755 --- a/pos/register.pl +++ b/pos/register.pl @@ -19,7 +19,7 @@ use Modern::Perl; use CGI; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use C4::Context; @@ -40,7 +40,7 @@ my ( $template, $loggedinuser, $cookie, $user_flags ) = get_template_and_user( } ); my $logged_in_user = Koha::Patrons->find($loggedinuser) or die "Not logged in"; -my $schema = Koha::Database->new->schema; +my $schema = Koha::Database->new->schema; my $library_id = C4::Context->userenv->{'branch'}; my $registerid = $input->param('registerid') // C4::Context->userenv->{'register_id'}; @@ -51,11 +51,9 @@ my $registers = Koha::Cash::Registers->search( if ( !$registers->count ) { $template->param( error_registers => 1 ); -} -else { +} else { if ( !$registerid ) { - my $default_register = Koha::Cash::Registers->find( - { branch => $library_id, branch_default => 1 } ); + my $default_register = Koha::Cash::Registers->find( { branch => $library_id, branch_default => 1 } ); $registerid = $default_register->id if $default_register; } $registerid = $registers->next->id if !$registerid; @@ -66,7 +64,7 @@ else { ); my $cash_register = Koha::Cash::Registers->find( { id => $registerid } ); - my $accountlines = $cash_register->outstanding_accountlines(); + my $accountlines = $cash_register->outstanding_accountlines(); $template->param( register => $cash_register, accountlines => $accountlines @@ -75,9 +73,9 @@ else { my $transactions_range_from = $input->param('trange_f'); my $last_cashup = $cash_register->last_cashup; my $transactions_range_to = - $input->param('trange_t') ? $input->param('trange_t') - : $last_cashup ? $last_cashup->timestamp - : ''; + $input->param('trange_t') ? $input->param('trange_t') + : $last_cashup ? $last_cashup->timestamp + : ''; my $end = dt_from_string($transactions_range_to); $end = $end->set( { hour => 23, minute => 59, second => 59 } ); # To should be 'inclusive' @@ -112,17 +110,15 @@ else { amount => $cash_register->outstanding_accountlines->total } ); - } - else { + } else { $template->param( error_cashup_permission => 1 ); } - } - elsif ( $op eq 'cud-refund' ) { + } elsif ( $op eq 'cud-refund' ) { if ( $logged_in_user->has_permission( { cash_management => 'anonymous_refund' } ) ) { - my $amount = $input->param('amount'); - my $quantity = $input->param('quantity'); - my $accountline_id = $input->param('accountline'); - my $refund_type = $input->param('refund_type'); + my $amount = $input->param('amount'); + my $quantity = $input->param('quantity'); + my $accountline_id = $input->param('accountline'); + my $refund_type = $input->param('refund_type'); my $accountline = Koha::Account::Lines->find($accountline_id); $schema->txn_do( @@ -150,8 +146,7 @@ else { } ); - } - else { + } else { $template->param( error_refund_permission => 1 ); } } diff --git a/pos/registers.pl b/pos/registers.pl index 7a9c3a1699..65accdf10c 100755 --- a/pos/registers.pl +++ b/pos/registers.pl @@ -19,7 +19,7 @@ use Modern::Perl; use CGI; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use C4::Context; @@ -49,8 +49,7 @@ my $registers = Koha::Cash::Registers->search( if ( !$registers->count ) { $template->param( error_registers => 1 ); -} -else { +} else { $template->param( registers => $registers ); } @@ -66,8 +65,7 @@ if ( $op eq 'cashup' ) { amount => $register->outstanding_accountlines->total } ); - } - else { + } else { for my $register ( $registers->as_list ) { $register->add_cashup( { @@ -77,8 +75,7 @@ if ( $op eq 'cashup' ) { ); } } - } - else { + } else { $template->param( error_cashup_permission => 1 ); } } diff --git a/preservation/print_slip.pl b/preservation/print_slip.pl index 153508c3d6..5ad589d3b7 100755 --- a/preservation/print_slip.pl +++ b/preservation/print_slip.pl @@ -18,7 +18,7 @@ use Modern::Perl; use CGI qw ( -utf8 ); use C4::Context; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_and_exit_if_error output_and_exit output_html_with_http_headers ); use C4::Letters; use Koha::Patrons; diff --git a/recalls/recall_pickup_slip.pl b/recalls/recall_pickup_slip.pl index 247e03686b..29debc76b1 100755 --- a/recalls/recall_pickup_slip.pl +++ b/recalls/recall_pickup_slip.pl @@ -21,24 +21,24 @@ use Modern::Perl; use CGI qw ( -utf8 ); use C4::Context; use C4::Output qw( output_html_with_http_headers ); -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); my $input = CGI->new; my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "circ/printslip.tt", - query => $input, - type => "intranet", - flagsrequired => { circulate => "circulate_remaining_permissions" }, + template_name => "circ/printslip.tt", + query => $input, + type => "intranet", + flagsrequired => { circulate => "circulate_remaining_permissions" }, } ); my $recallid = $input->param('recall_id'); -my $recall = Koha::Recalls->find($recallid); +my $recall = Koha::Recalls->find($recallid); my $itemnumber; -if ( $recall->item_id ){ +if ( $recall->item_id ) { $itemnumber = $recall->item_id; } else { $itemnumber = $recall->checkout->itemnumber; @@ -46,15 +46,15 @@ if ( $recall->item_id ){ # Print slip to inform library staff of details of recall requester, so the item can be put aside for requester my $letter = C4::Letters::GetPreparedLetter( - module => 'circulation', - letter_code => 'RECALL_REQUESTER_DET', + module => 'circulation', + letter_code => 'RECALL_REQUESTER_DET', message_transport_type => 'print', - tables => { - 'branches' => $recall->pickup_library_id, - 'borrowers' => $recall->patron_id, - 'biblio' => $recall->biblio_id, - 'items' => $itemnumber, - 'recalls' => $recall->id, + tables => { + 'branches' => $recall->pickup_library_id, + 'borrowers' => $recall->patron_id, + 'biblio' => $recall->biblio_id, + 'items' => $itemnumber, + 'recalls' => $recall->id, } ); diff --git a/recalls/recalls_old_queue.pl b/recalls/recalls_old_queue.pl index f2b6cb311a..16b47d08e1 100755 --- a/recalls/recalls_old_queue.pl +++ b/recalls/recalls_old_queue.pl @@ -17,30 +17,30 @@ # along with Koha; if not, see . use Modern::Perl; -use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use Koha::BiblioFrameworks; my $query = CGI->new; my ( $template, $loggedinuser, $cookie, $flags ) = get_template_and_user( { - template_name => "recalls/recalls_old_queue.tt", - query => $query, - type => "intranet", - flagsrequired => { recalls => "manage_recalls" }, - debug => 1, + template_name => "recalls/recalls_old_queue.tt", + query => $query, + type => "intranet", + flagsrequired => { recalls => "manage_recalls" }, + debug => 1, } ); -my $recalls = Koha::Recalls->search({ completed => 1 }); +my $recalls = Koha::Recalls->search( { completed => 1 } ); $template->param( - recalls => $recalls, + recalls => $recalls, viewing_old => 1 ); # Checking if there is a Fast Cataloging Framework -$template->param( fast_cataloging => 1 ) if Koha::BiblioFrameworks->find( 'FA' ); +$template->param( fast_cataloging => 1 ) if Koha::BiblioFrameworks->find('FA'); # writing the template output_html_with_http_headers $query, $cookie, $template->output; diff --git a/recalls/recalls_overdue.pl b/recalls/recalls_overdue.pl index b4ca7e10ed..a514d9cc97 100755 --- a/recalls/recalls_overdue.pl +++ b/recalls/recalls_overdue.pl @@ -17,8 +17,8 @@ # along with Koha; if not, see . use Modern::Perl; -use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use Koha::BiblioFrameworks; use Koha::DateUtils; @@ -26,35 +26,36 @@ use Koha::DateUtils; my $query = CGI->new; my ( $template, $loggedinuser, $cookie, $flags ) = get_template_and_user( { - template_name => "recalls/recalls_overdue.tt", - query => $query, - type => "intranet", - flagsrequired => { recalls => "manage_recalls" }, - debug => 1, + template_name => "recalls/recalls_overdue.tt", + query => $query, + type => "intranet", + flagsrequired => { recalls => "manage_recalls" }, + debug => 1, } ); -my $op = $query->param('op') || 'list'; +my $op = $query->param('op') || 'list'; my @recall_ids = $query->multi_param('recall_ids'); if ( $op eq 'cud-cancel_multiple_recalls' ) { - foreach my $id ( @recall_ids ) { - Koha::Recalls->find( $id )->set_cancelled; + foreach my $id (@recall_ids) { + Koha::Recalls->find($id)->set_cancelled; } - $op = 'list' + $op = 'list'; } if ( $op eq 'list' ) { - my $recalls = Koha::Recalls->search({ status => 'overdue' }); + my $recalls = Koha::Recalls->search( { status => 'overdue' } ); + # will be set as Overdue by the misc/cronjobs/recall/overdue_recalls.pl cronjob $template->param( - recalls => $recalls, + recalls => $recalls, checkboxes => 1, ); } # Checking if there is a Fast Cataloging Framework -$template->param( fast_cataloging => 1 ) if Koha::BiblioFrameworks->find( 'FA' ); +$template->param( fast_cataloging => 1 ) if Koha::BiblioFrameworks->find('FA'); # writing the template output_html_with_http_headers $query, $cookie, $template->output; diff --git a/recalls/recalls_queue.pl b/recalls/recalls_queue.pl index 9d07894b4b..84a6483376 100755 --- a/recalls/recalls_queue.pl +++ b/recalls/recalls_queue.pl @@ -17,40 +17,39 @@ # along with Koha; if not, see . use Modern::Perl; -use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use Koha::BiblioFrameworks; my $query = CGI->new; my ( $template, $loggedinuser, $cookie, $flags ) = get_template_and_user( { - template_name => "recalls/recalls_queue.tt", - query => $query, - type => "intranet", - flagsrequired => { recalls => 'manage_recalls' }, - debug => 1, + template_name => "recalls/recalls_queue.tt", + query => $query, + type => "intranet", + flagsrequired => { recalls => 'manage_recalls' }, + debug => 1, } ); -my $op = $query->param('op') || 'list'; +my $op = $query->param('op') || 'list'; my @recall_ids = $query->multi_param('recall_ids'); if ( $op eq 'cud-cancel_multiple_recalls' ) { - foreach my $id ( @recall_ids ) { - Koha::Recalls->find( $id )->set_cancelled; + foreach my $id (@recall_ids) { + Koha::Recalls->find($id)->set_cancelled; } - $op = 'list' -} -elsif ( $op eq 'list' ) { - my $recalls = Koha::Recalls->search({ completed => 0 }); + $op = 'list'; +} elsif ( $op eq 'list' ) { + my $recalls = Koha::Recalls->search( { completed => 0 } ); $template->param( - recalls => $recalls, + recalls => $recalls, checkboxes => 1, ); } # Checking if there is a Fast Cataloging Framework -$template->param( fast_cataloging => 1 ) if Koha::BiblioFrameworks->find( 'FA' ); +$template->param( fast_cataloging => 1 ) if Koha::BiblioFrameworks->find('FA'); # writing the template output_html_with_http_headers $query, $cookie, $template->output; diff --git a/recalls/recalls_to_pull.pl b/recalls/recalls_to_pull.pl index 5548027e34..afc5372a29 100755 --- a/recalls/recalls_to_pull.pl +++ b/recalls/recalls_to_pull.pl @@ -17,28 +17,28 @@ # along with Koha; if not, see . use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use List::MoreUtils qw( uniq ); -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use Koha::BiblioFrameworks; my $query = CGI->new; my ( $template, $loggedinuser, $cookie, $flags ) = get_template_and_user( { - template_name => "recalls/recalls_to_pull.tt", - query => $query, - type => "intranet", - flagsrequired => { recalls => 'manage_recalls' }, - debug => 1, + template_name => "recalls/recalls_to_pull.tt", + query => $query, + type => "intranet", + flagsrequired => { recalls => 'manage_recalls' }, + debug => 1, } ); -my $op = $query->param('op') || 'list'; +my $op = $query->param('op') || 'list'; my $recall_id = $query->param('recall_id'); if ( $op eq 'cud-cancel' ) { - my $recall = Koha::Recalls->find( $recall_id ); + my $recall = Koha::Recalls->find($recall_id); if ( $recall->in_transit ) { C4::Items::ModItemTransfer( $recall->item->itemnumber, $recall->item->holdingbranch, @@ -50,27 +50,29 @@ if ( $op eq 'cud-cancel' ) { } if ( $op eq 'list' ) { - my @recalls = Koha::Recalls->search({ status => [ 'requested','overdue' ] })->as_list; + my @recalls = Koha::Recalls->search( { status => [ 'requested', 'overdue' ] } )->as_list; my @pull_list; my %seen_bib; - foreach my $recall ( @recalls ) { - if ( $seen_bib{$recall->biblio_id} ){ + foreach my $recall (@recalls) { + if ( $seen_bib{ $recall->biblio_id } ) { + # we've already looked at the recalls on this biblio next; } else { + # this is an unseen biblio - $seen_bib{$recall->biblio_id}++; + $seen_bib{ $recall->biblio_id }++; # get recall data about this biblio - my $biblio = $recall->biblio; + my $biblio = $recall->biblio; my @this_bib_recalls = $biblio->recalls->search( - { status => [ 'requested','overdue' ] }, + { status => [ 'requested', 'overdue' ] }, { order_by => { -asc => 'created_date' } } )->as_list; - my $recalls_count = scalar @this_bib_recalls; - my @unique_patrons = uniq @this_bib_recalls ; - my $patrons_count = scalar @unique_patrons; - my $first_recall = $this_bib_recalls[0]; + my $recalls_count = scalar @this_bib_recalls; + my @unique_patrons = uniq @this_bib_recalls; + my $patrons_count = scalar @unique_patrons; + my $first_recall = $this_bib_recalls[0]; my $items_count = 0; my @callnumbers; @@ -81,37 +83,48 @@ if ( $op eq 'list' ) { my @libraries; my @items = $biblio->items->as_list; - foreach my $item ( @items ) { - if ( $item->can_be_waiting_recall and !$item->checkout and Koha::Recalls->search({ item_id => $item->id, status => [ 'waiting','in_transit' ], completed => 0 })->count == 0 ) { + foreach my $item (@items) { + if ( + $item->can_be_waiting_recall + and !$item->checkout + and Koha::Recalls->search( + { item_id => $item->id, status => [ 'waiting', 'in_transit' ], completed => 0 } + )->count == 0 + ) + { # if item can be pulled to fulfill recall, collect item data $items_count++; - push( @callnumbers, $item->itemcallnumber ) if ( $item->itemcallnumber ); - push( @copynumbers, $item->copynumber ) if ( $item->copynumber ); - push( @enumchrons, $item->enumchron ) if ( $item->enumchron ); - push( @itemtypes, $item->effective_itemtype ) if ( $item->effective_itemtype ); - push( @locations, $item->location ) if ( $item->location ); - push( @libraries, $item->holdingbranch ) if ( $item->holdingbranch ); + push( @callnumbers, $item->itemcallnumber ) if ( $item->itemcallnumber ); + push( @copynumbers, $item->copynumber ) if ( $item->copynumber ); + push( @enumchrons, $item->enumchron ) if ( $item->enumchron ); + push( @itemtypes, $item->effective_itemtype ) if ( $item->effective_itemtype ); + push( @locations, $item->location ) if ( $item->location ); + push( @libraries, $item->holdingbranch ) if ( $item->holdingbranch ); } } if ( $items_count > 0 ) { - # don't push data if there are no items available for this recall + + # don't push data if there are no items available for this recall # get unique values - push( @pull_list, { - biblio => $biblio, - items_count => $items_count, - recalls_count => $recalls_count, - patrons_count => $patrons_count, - pull_count => $items_count <= $recalls_count ? $items_count : $recalls_count, - first_recall => $first_recall, - callnumbers => [ uniq @callnumbers ], - copynumbers => [ uniq @copynumbers ], - enumchrons => [ uniq @enumchrons ], - itemtypes => [ uniq @itemtypes ], - locations => [ uniq @locations ], - libraries => [ uniq @libraries ], - }); + push( + @pull_list, + { + biblio => $biblio, + items_count => $items_count, + recalls_count => $recalls_count, + patrons_count => $patrons_count, + pull_count => $items_count <= $recalls_count ? $items_count : $recalls_count, + first_recall => $first_recall, + callnumbers => [ uniq @callnumbers ], + copynumbers => [ uniq @copynumbers ], + enumchrons => [ uniq @enumchrons ], + itemtypes => [ uniq @itemtypes ], + locations => [ uniq @locations ], + libraries => [ uniq @libraries ], + } + ); } } } @@ -121,7 +134,7 @@ if ( $op eq 'list' ) { } # Checking if there is a Fast Cataloging Framework -$template->param( fast_cataloging => 1 ) if Koha::BiblioFrameworks->find( 'FA' ); +$template->param( fast_cataloging => 1 ) if Koha::BiblioFrameworks->find('FA'); # writing the template output_html_with_http_headers $query, $cookie, $template->output; diff --git a/recalls/recalls_waiting.pl b/recalls/recalls_waiting.pl index d8d51d1725..231db67ca4 100755 --- a/recalls/recalls_waiting.pl +++ b/recalls/recalls_waiting.pl @@ -17,8 +17,8 @@ # along with Koha; if not, see . use Modern::Perl; -use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use Koha::Recalls; use Koha::BiblioFrameworks; @@ -28,50 +28,50 @@ use Koha::Patrons; my $query = CGI->new; my ( $template, $loggedinuser, $cookie, $flags ) = get_template_and_user( { - template_name => "recalls/recalls_waiting.tt", - query => $query, - type => "intranet", - flagsrequired => { recalls => "manage_recalls" }, - debug => 1, + template_name => "recalls/recalls_waiting.tt", + query => $query, + type => "intranet", + flagsrequired => { recalls => "manage_recalls" }, + debug => 1, } ); my $op = $query->param('op') || 'list'; if ( $op eq 'cud-modify' ) { - my $expire = $query->param('expire') || ''; - my $revert = $query->param('revert') || ''; + my $expire = $query->param('expire') || ''; + my $revert = $query->param('revert') || ''; my $recall_id = $query->param('recall_id'); - if ( $expire ) { - Koha::Recalls->find( $recall_id )->set_expired({ interface => 'INTRANET' }); - } elsif ( $revert ) { - Koha::Recalls->find( $recall_id )->revert_waiting; + if ($expire) { + Koha::Recalls->find($recall_id)->set_expired( { interface => 'INTRANET' } ); + } elsif ($revert) { + Koha::Recalls->find($recall_id)->revert_waiting; } $op = 'list'; } if ( $op eq 'list' ) { - my @recalls = Koha::Recalls->search({ status => 'waiting' })->as_list; - my $borrower = Koha::Patrons->find( $loggedinuser ); + my @recalls = Koha::Recalls->search( { status => 'waiting' } )->as_list; + my $borrower = Koha::Patrons->find($loggedinuser); my @over; my $maxdelay = C4::Context->preference('RecallsMaxPickUpDelay') || 7; - my $today = dt_from_string(); - foreach my $r ( @recalls ){ + my $today = dt_from_string(); + foreach my $r (@recalls) { my $lastwaitingday = dt_from_string( $r->waiting_date )->add( days => $maxdelay ); - if ( $today > $lastwaitingday ){ + if ( $today > $lastwaitingday ) { push @over, $r; } } $template->param( - recalls => \@recalls, - recallscount => scalar @recalls, - over => \@over, - overcount => scalar @over, + recalls => \@recalls, + recallscount => scalar @recalls, + over => \@over, + overcount => scalar @over, ); } # Checking if there is a Fast Cataloging Framework -$template->param( fast_cataloging => 1 ) if Koha::BiblioFrameworks->find( 'FA' ); +$template->param( fast_cataloging => 1 ) if Koha::BiblioFrameworks->find('FA'); # writing the template output_html_with_http_headers $query, $cookie, $template->output; diff --git a/recalls/request.pl b/recalls/request.pl index b3cb7a3d97..6dc22c28d9 100755 --- a/recalls/request.pl +++ b/recalls/request.pl @@ -17,40 +17,40 @@ # along with Koha; if not, see . use Modern::Perl; -use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use C4::Search; use Koha::Recalls; use Koha::Biblios; my $input = CGI->new; -my ($template, $loggedinuser, $cookie)= get_template_and_user( +my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "recalls/request.tt", - query => $input, - type => "intranet", - flagsrequired => { recalls => "manage_recalls" }, - debug => 1, + template_name => "recalls/request.tt", + query => $input, + type => "intranet", + flagsrequired => { recalls => "manage_recalls" }, + debug => 1, } ); -my $op = $input->param('op') || 'list'; -my @recall_ids = $input->multi_param('recall_ids'); +my $op = $input->param('op') || 'list'; +my @recall_ids = $input->multi_param('recall_ids'); my $biblionumber = $input->param('biblionumber'); -my $recalls = Koha::Recalls->search({ biblio_id => $biblionumber, completed => 0 }); -my $biblio = Koha::Biblios->find( $biblionumber ); +my $recalls = Koha::Recalls->search( { biblio_id => $biblionumber, completed => 0 } ); +my $biblio = Koha::Biblios->find($biblionumber); if ( $op eq 'cud-cancel_multiple_recalls' ) { - foreach my $id ( @recall_ids ) { - Koha::Recalls->find( $id )->set_cancelled; + foreach my $id (@recall_ids) { + Koha::Recalls->find($id)->set_cancelled; } - $op = 'list' + $op = 'list'; } if ( $op eq 'list' ) { - $recalls = Koha::Recalls->search({ biblio_id => $biblionumber, completed => 0 }); - $biblio = Koha::Biblios->find( $biblionumber ); + $recalls = Koha::Recalls->search( { biblio_id => $biblionumber, completed => 0 } ); + $biblio = Koha::Biblios->find($biblionumber); } $template->param( diff --git a/reports/acquisitions_stats.pl b/reports/acquisitions_stats.pl index ab77472bc2..3837e770d4 100755 --- a/reports/acquisitions_stats.pl +++ b/reports/acquisitions_stats.pl @@ -20,12 +20,12 @@ use Modern::Perl; use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Context; use C4::Reports qw( GetDelimiterChoices ); -use C4::Output qw( output_html_with_http_headers ); -use C4::Koha qw( GetAuthorisedValues ); -use C4::Biblio qw( GetMarcSubfieldStructureFromKohaField ); +use C4::Output qw( output_html_with_http_headers ); +use C4::Koha qw( GetAuthorisedValues ); +use C4::Biblio qw( GetMarcSubfieldStructureFromKohaField ); use Koha::ItemTypes; use Koha::Libraries; @@ -53,30 +53,28 @@ my $basename = $input->param("basename"); my ( $template, $borrowernumber, $cookie ) = get_template_and_user( { - template_name => $fullreportname, - query => $input, - type => "intranet", - flagsrequired => { reports => '*' }, + template_name => $fullreportname, + query => $input, + type => "intranet", + flagsrequired => { reports => '*' }, } ); -our $sep = C4::Context->csv_delimiter(scalar $input->param("sep")); +our $sep = C4::Context->csv_delimiter( scalar $input->param("sep") ); $template->param( - do_it => $do_it, + do_it => $do_it, ); if ($do_it) { - my $results = - calculate( $line, $column, $podsp, $rodsp, $calc, \@filters ); + my $results = calculate( $line, $column, $podsp, $rodsp, $calc, \@filters ); if ( $output eq "screen" ) { $template->param( mainloop => $results ); output_html_with_http_headers $input, $cookie, $template->output; - } - else { + } else { print $input->header( -type => 'application/vnd.sun.xml.calc', - -encoding => 'utf-8', + -encoding => 'utf-8', -attachment => "$basename.csv", -name => "$basename.csv" ); @@ -104,13 +102,12 @@ if ($do_it) { print $sep. @$results[0]->{total}; } exit; -} -else { +} else { my $dbh = C4::Context->dbh; my $req; $req = $dbh->prepare("SELECT distinctrow id,name FROM aqbooksellers ORDER BY name"); $req->execute; - my $booksellers = $req->fetchall_arrayref({}); + my $booksellers = $req->fetchall_arrayref( {} ); $req = $dbh->prepare("SELECT DISTINCTROW budget_code, budget_name FROM aqbudgets ORDER BY budget_name"); $req->execute; @@ -122,14 +119,11 @@ else { $bselect{$value} = $desc; } my $Budgets = { - values => \@bselect, - labels => \%bselect, + values => \@bselect, + labels => \%bselect, }; - $req = - $dbh->prepare( -"SELECT DISTINCTROW sort1 FROM aqorders WHERE sort1 IS NOT NULL ORDER BY sort1" - ); + $req = $dbh->prepare("SELECT DISTINCTROW sort1 FROM aqorders WHERE sort1 IS NOT NULL ORDER BY sort1"); $req->execute; my @s1select; my %s1select; @@ -142,14 +136,11 @@ else { } } my $Sort1 = { - values => \@s1select, - labels => \%s1select, + values => \@s1select, + labels => \%s1select, }; - $req = - $dbh->prepare( -"SELECT DISTINCTROW sort2 FROM aqorders WHERE sort2 IS NOT NULL ORDER BY sort2" - ); + $req = $dbh->prepare("SELECT DISTINCTROW sort2 FROM aqorders WHERE sort2 IS NOT NULL ORDER BY sort2"); $req->execute; my @s2select; my %s2select; @@ -165,35 +156,35 @@ else { } } my $Sort2 = { - values => \@s2select, - labels => \%s2select, + values => \@s2select, + labels => \%s2select, }; my $CGIsepChoice = GetDelimiterChoices; - my $libraries = Koha::Libraries->search({}, { order_by => 'branchname' }); + my $libraries = Koha::Libraries->search( {}, { order_by => 'branchname' } ); my $ccode_subfield_structure = GetMarcSubfieldStructureFromKohaField('items.ccode')->[0]; # assuming one result.. my $ccode_label; my $ccode_avlist; - if($ccode_subfield_structure) { - $ccode_label = $ccode_subfield_structure->{liblibrarian}; - $ccode_avlist = GetAuthorisedValues($ccode_subfield_structure->{authorised_value}); + if ($ccode_subfield_structure) { + $ccode_label = $ccode_subfield_structure->{liblibrarian}; + $ccode_avlist = GetAuthorisedValues( $ccode_subfield_structure->{authorised_value} ); } my $itemtypes = Koha::ItemTypes->search_with_localization; $template->param( - booksellers => $booksellers, - itemtypes => $itemtypes, # FIXME Should use the TT plugin instead - Budgets => $Budgets, - hassort1 => $hassort1, - hassort2 => $hassort2, - Sort1 => $Sort1, - Sort2 => $Sort2, - CGIsepChoice => $CGIsepChoice, - branches => $libraries, - ccode_label => $ccode_label, - ccode_avlist => $ccode_avlist, + booksellers => $booksellers, + itemtypes => $itemtypes, # FIXME Should use the TT plugin instead + Budgets => $Budgets, + hassort1 => $hassort1, + hassort2 => $hassort2, + Sort1 => $Sort1, + Sort2 => $Sort2, + CGIsepChoice => $CGIsepChoice, + branches => $libraries, + ccode_label => $ccode_label, + ccode_avlist => $ccode_avlist, ); } @@ -220,22 +211,22 @@ sub calculate { # my @loopfilter; for ( my $i = 0 ; $i <= @$filters ; $i++ ) { - if( defined @$filters[$i] and @$filters[$i] ne '' ) { + if ( defined @$filters[$i] and @$filters[$i] ne '' ) { my %cell; if ( ( ( $i == 1 ) or ( $i == 3 ) ) and ( @$filters[ $i - 1 ] ) ) { $cell{err} = 1 if ( @$filters[$i] lt @$filters[ $i - 1 ] ); } $cell{filter} = @$filters[$i]; - $cell{crit} = $i; + $cell{crit} = $i; push @loopfilter, \%cell; } } my %filter; my %field; - foreach ($line, $column) { + foreach ( $line, $column ) { $filter{$_} = []; - $field{$_} = $_; + $field{$_} = $_; if ( $_ =~ /closedate/ ) { $filter{$_}->[0] = @$filters[0]; $filter{$_}->[1] = @$filters[1]; @@ -249,8 +240,7 @@ sub calculate { } else { $field{$a} = $a; } - } - elsif ( $_ =~ /received/ ) { + } elsif ( $_ =~ /received/ ) { $filter{$_}->[0] = @$filters[2]; $filter{$_}->[1] = @$filters[3]; my $a = $_; @@ -263,34 +253,27 @@ sub calculate { } else { $field{$a} = $a; } - } - elsif ( $_ =~ /bookseller/ ) { + } elsif ( $_ =~ /bookseller/ ) { $filter{$_}->[0] = @$filters[4]; - } - elsif ( $_ =~ /homebranch/ ) { + } elsif ( $_ =~ /homebranch/ ) { $filter{$_}->[0] = @$filters[5]; - } - elsif ( $_ =~ /ccode/ ) { + } elsif ( $_ =~ /ccode/ ) { $filter{$_}->[0] = @$filters[6]; - } - elsif ( $_ =~ /itemtype/ ) { + } elsif ( $_ =~ /itemtype/ ) { $filter{$_}->[0] = @$filters[7]; - } - elsif ( $_ =~ /budget/ ) { + } elsif ( $_ =~ /budget/ ) { $filter{$_}->[0] = @$filters[8]; - } - elsif ( $_ =~ /sort1/ ) { + } elsif ( $_ =~ /sort1/ ) { $filter{$_}->[0] = @$filters[9]; - } - elsif ( $_ =~ /sort2/ ) { + } elsif ( $_ =~ /sort2/ ) { $filter{$_}->[0] = @$filters[10]; } } my @linefilter = @{ $filter{$line} }; - my $linefield = $field{$line}; - my @colfilter = @{ $filter{$column} }; - my $colfield = $field{$column}; + my $linefield = $field{$line}; + my @colfilter = @{ $filter{$column} }; + my $colfield = $field{$column}; # 1st, loop rows. my $strsth = " @@ -308,20 +291,17 @@ sub calculate { if ( $linefilter[1] ) { if ( $linefilter[0] ) { $strsth .= " AND $line BETWEEN ? AND ? "; - } - else { + } else { $strsth .= " AND $line <= ? "; } - } - elsif ( + } elsif ( ( $linefilter[0] ) and ( ( $line =~ /closedate/ ) - or ( $line =~ /received/ )) - ) + or ( $line =~ /received/ ) ) + ) { $strsth .= " AND $line >= ? "; - } - elsif ( $linefilter[0] ) { + } elsif ( $linefilter[0] ) { $linefilter[0] =~ s/\*/%/g; $strsth .= " AND $line LIKE ? "; } @@ -332,11 +312,9 @@ sub calculate { my $sth = $dbh->prepare($strsth); if ( (@linefilter) and ( $linefilter[1] ) ) { $sth->execute( $linefilter[0], $linefilter[1] ); - } - elsif ( $linefilter[0] ) { + } elsif ( $linefilter[0] ) { $sth->execute( $linefilter[0] ); - } - else { + } else { $sth->execute; } while ( my ($celvalue) = $sth->fetchrow ) { @@ -365,20 +343,17 @@ sub calculate { if ( $colfilter[1] ) { if ( $colfilter[0] ) { $strsth2 .= " AND $column BETWEEN ? AND ? "; - } - else { + } else { $strsth2 .= " AND $column <= ? "; } - } - elsif ( + } elsif ( ( $colfilter[0] ) and ( ( $column =~ /closedate/ ) - or ( $line =~ /received/ )) - ) + or ( $line =~ /received/ ) ) + ) { $strsth2 .= " AND $column >= ? "; - } - elsif ( $colfilter[0] ) { + } elsif ( $colfilter[0] ) { $colfilter[0] =~ s/\*/%/g; $strsth2 .= " AND $column LIKE ? "; } @@ -389,13 +364,11 @@ sub calculate { my $sth2 = $dbh->prepare($strsth2); - if ( (@colfilter) and ($colfilter[1]) ) { + if ( (@colfilter) and ( $colfilter[1] ) ) { $sth2->execute( $colfilter[0], $colfilter[1] ); - } - elsif ( $colfilter[0] ) { + } elsif ( $colfilter[0] ) { $sth2->execute( $colfilter[0] ); - } - else { + } else { $sth2->execute; } while ( my $celvalue = $sth2->fetchrow ) { @@ -406,7 +379,7 @@ sub calculate { } } - my $i = 0; + my $i = 0; my $hilighted = -1; #Initialization of cell values..... @@ -446,36 +419,36 @@ sub calculate { if ( $process == 5 ); @$filters[0] =~ s/\*/%/g if ( @$filters[0] ); $strcalc .= " AND aqbasket.closedate >= '" . @$filters[0] . "'" - if ( @$filters[0] ); + if ( @$filters[0] ); @$filters[1] =~ s/\*/%/g if ( @$filters[1] ); $strcalc .= " AND aqbasket.closedate <= '" . @$filters[1] . "'" - if ( @$filters[1] ); + if ( @$filters[1] ); @$filters[2] =~ s/\*/%/g if ( @$filters[2] ); $strcalc .= " AND aqorders.datereceived >= '" . @$filters[2] . "'" - if ( @$filters[2] ); + if ( @$filters[2] ); @$filters[3] =~ s/\*/%/g if ( @$filters[3] ); $strcalc .= " AND aqorders.datereceived <= '" . @$filters[3] . "'" - if ( @$filters[3] ); + if ( @$filters[3] ); @$filters[4] =~ s/\*/%/g if ( @$filters[4] ); $strcalc .= " AND aqbooksellers.name LIKE '" . @$filters[4] . "'" - if ( @$filters[4] ); + if ( @$filters[4] ); $strcalc .= " AND items.homebranch = '" . @$filters[5] . "'" - if ( @$filters[5] ); + if ( @$filters[5] ); @$filters[6] =~ s/\*/%/g if ( @$filters[6] ); $strcalc .= " AND items.ccode = '" . @$filters[6] . "'" - if ( @$filters[6] ); + if ( @$filters[6] ); @$filters[7] =~ s/\*/%/g if ( @$filters[7] ); $strcalc .= " AND biblioitems.itemtype LIKE '" . @$filters[7] . "'" - if ( @$filters[7] ); + if ( @$filters[7] ); @$filters[8] =~ s/\*/%/g if ( @$filters[8] ); $strcalc .= " AND aqbudgets.budget_code LIKE '" . @$filters[8] . "'" - if ( @$filters[8] ); + if ( @$filters[8] ); @$filters[9] =~ s/\*/%/g if ( @$filters[9] ); $strcalc .= " AND aqorders.sort1 LIKE '" . @$filters[9] . "'" - if ( @$filters[9] ); + if ( @$filters[9] ); @$filters[10] =~ s/\*/%/g if ( @$filters[10] ); $strcalc .= " AND aqorders.sort2 LIKE '" . @$filters[10] . "'" - if ( @$filters[10] ); + if ( @$filters[10] ); $strcalc .= " GROUP BY $linefield, $colfield ORDER BY $linefield,$colfield"; my $dbcalc = $dbh->prepare($strcalc); @@ -496,20 +469,21 @@ sub calculate { foreach my $row ( sort keys %table ) { my @loopcell; + #@loopcol ensures the order for columns is common with column titles # and the number matches the number of columns foreach my $col (@loopcol) { my $value = $table{$row}->{ ( $col->{coltitle} eq "NULL" ) ? "zzEMPTY" : $col->{coltitle} }; - $value = sprintf("%.2f", $value) if($value and grep /$process/, (3,4,5)); + $value = sprintf( "%.2f", $value ) if ( $value and grep /$process/, ( 3, 4, 5 ) ); push @loopcell, { value => $value }; } my $r = { - rowtitle => ( $row eq "zzEMPTY" ) ? "NULL" : $row, + rowtitle => ( $row eq "zzEMPTY" ) ? "NULL" : $row, loopcell => \@loopcell, hilighted => ( $hilighted > 0 ), totalrow => $table{$row}->{totalrow} }; - $r->{totalrow} = sprintf("%.2f", $r->{totalrow}) if($r->{totalrow} and grep /$process/, (3,4,5)); + $r->{totalrow} = sprintf( "%.2f", $r->{totalrow} ) if ( $r->{totalrow} and grep /$process/, ( 3, 4, 5 ) ); push @looprow, $r; $hilighted = -$hilighted; } @@ -520,24 +494,25 @@ sub calculate { $total += $table{ ( $row->{rowtitle} eq "NULL" ) ? "zzEMPTY" : $row->{rowtitle} - }->{ + }->{ ( $col->{coltitle} eq "NULL" ) ? "zzEMPTY" : $col->{coltitle} - }; + }; } - $total = sprintf("%.2f", $total) if($total and grep /$process/, (3,4,5)); + $total = sprintf( "%.2f", $total ) if ( $total and grep /$process/, ( 3, 4, 5 ) ); push @loopfooter, { 'totalcol' => $total }; } # the header of the table $globalline{loopfilter} = \@loopfilter; + # the core of the table $globalline{looprow} = \@looprow; $globalline{loopcol} = \@loopcol; # # the foot (totals by borrower type) - $grantotal = sprintf("%.2f", $grantotal) if ($grantotal and grep /$process/, (3,4,5)); + $grantotal = sprintf( "%.2f", $grantotal ) if ( $grantotal and grep /$process/, ( 3, 4, 5 ) ); $globalline{loopfooter} = \@loopfooter; $globalline{total} = $grantotal; $globalline{line} = $line; diff --git a/reports/bor_issues_top.pl b/reports/bor_issues_top.pl index d4bf082813..3f1390d4f8 100755 --- a/reports/bor_issues_top.pl +++ b/reports/bor_issues_top.pl @@ -19,8 +19,8 @@ use Modern::Perl; -use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use C4::Context; use C4::Reports qw( GetDelimiterChoices ); @@ -36,58 +36,70 @@ plugin that shows a stats on borrowers =cut -my $input = CGI->new; +my $input = CGI->new; my $fullreportname = "reports/bor_issues_top.tt"; -my $do_it = $input->param('do_it'); -my $limit = $input->param("Limit"); -my $column = $input->param("Criteria"); -my @filters = $input->multi_param("Filter"); -my $output = $input->param("output"); -my $basename = $input->param("basename"); -my ($template, $borrowernumber, $cookie) - = get_template_and_user({template_name => $fullreportname, - query => $input, - type => "intranet", - flagsrequired => {reports => '*'}, - }); -our $sep = C4::Context->csv_delimiter(scalar $input->param("sep")); -$template->param(do_it => $do_it, - ); +my $do_it = $input->param('do_it'); +my $limit = $input->param("Limit"); +my $column = $input->param("Criteria"); +my @filters = $input->multi_param("Filter"); +my $output = $input->param("output"); +my $basename = $input->param("basename"); +my ( $template, $borrowernumber, $cookie ) = get_template_and_user( + { + template_name => $fullreportname, + query => $input, + type => "intranet", + flagsrequired => { reports => '*' }, + } +); +our $sep = C4::Context->csv_delimiter( scalar $input->param("sep") ); +$template->param( + do_it => $do_it, +); if ($do_it) { -# Displaying results - my $results = calculate($limit, $column, \@filters); - if ($output eq "screen"){ -# Printing results to screen - $template->param(mainloop => $results, limit=>$limit); + + # Displaying results + my $results = calculate( $limit, $column, \@filters ); + if ( $output eq "screen" ) { + + # Printing results to screen + $template->param( mainloop => $results, limit => $limit ); output_html_with_http_headers $input, $cookie, $template->output; } else { -# Printing to a csv file - print $input->header(-type => 'application/vnd.sun.xml.calc', - -encoding => 'utf-8', - -attachment=>"$basename.csv", - -filename=>"$basename.csv" ); + + # Printing to a csv file + print $input->header( + -type => 'application/vnd.sun.xml.calc', + -encoding => 'utf-8', + -attachment => "$basename.csv", + -filename => "$basename.csv" + ); my $cols = @$results[0]->{loopcol}; my $lines = @$results[0]->{looprow}; -# header top-left - print @$results[0]->{line} ."/". @$results[0]->{column} .$sep; - print "Patron".$sep; - print "Total".$sep; -# Other header - print join($sep, map {$_->{coltitle}} @$cols); + + # header top-left + print @$results[0]->{line} . "/" . @$results[0]->{column} . $sep; + print "Patron" . $sep; + print "Total" . $sep; + + # Other header + print join( $sep, map { $_->{coltitle} } @$cols ); print "\n"; -# Table - foreach my $line ( @$lines ) { + + # Table + foreach my $line (@$lines) { my $x = $line->{loopcell}; - print $line->{rowtitle}.$sep; - print '"'.$line->{patron}.'"'.$sep; - print join($sep, map {$_->{count}} @$x); + print $line->{rowtitle} . $sep; + print '"' . $line->{patron} . '"' . $sep; + print join( $sep, map { $_->{count} } @$x ); print "\n"; } -# footer + + # footer print "TOTAL"; $cols = @$results[0]->{loopfooter}; - print join($sep, map {$_->{total}} @$cols); - print $sep.@$results[0]->{total}; + print join( $sep, map { $_->{total} } @$cols ); + print $sep. @$results[0]->{total}; } exit; } @@ -95,100 +107,102 @@ if ($do_it) { my $dbh = C4::Context->dbh; # here each element returned by map is a hashref, get it? -my @mime = ( map { {type =>$_} } (split /[;:]/, 'CSV') ); # FIXME translation +my @mime = ( map { { type => $_ } } ( split /[;:]/, 'CSV' ) ); # FIXME translation my $delims = GetDelimiterChoices; -my $patron_categories = Koha::Patron::Categories->search_with_library_limits({}, {order_by => ['categorycode']}); -my $itemtypes = Koha::ItemTypes->search_with_localization; +my $patron_categories = Koha::Patron::Categories->search_with_library_limits( {}, { order_by => ['categorycode'] } ); +my $itemtypes = Koha::ItemTypes->search_with_localization; $template->param( - mimeloop => \@mime, - CGIseplist => $delims, - itemtypes => $itemtypes, -patron_categories => $patron_categories, + mimeloop => \@mime, + CGIseplist => $delims, + itemtypes => $itemtypes, + patron_categories => $patron_categories, ); output_html_with_http_headers $input, $cookie, $template->output; - sub calculate { - my ($limit, $column, $filters) = @_; + my ( $limit, $column, $filters ) = @_; my @loopcol; my @looprow; my %globalline; - my %columns; - my $grantotal =0; - my $dbh = C4::Context->dbh; + my %columns; + my $grantotal = 0; + my $dbh = C4::Context->dbh; - -# Checking filters + # Checking filters my @loopfilter; - my @cellmap = ( - "Issue From", - "Issue To", - "Return From", - "Return To", - "Branch", - "Doc Type", - "Bor Cat", - "Day", - "Month", - "Year" - ); - for (my $i=0;$i<=6;$i++) { + my @cellmap = ( + "Issue From", + "Issue To", + "Return From", + "Return To", + "Branch", + "Doc Type", + "Bor Cat", + "Day", + "Month", + "Year" + ); + for ( my $i = 0 ; $i <= 6 ; $i++ ) { my %cell; if ( @$filters[$i] ) { - if (($i==1) and (@$filters[$i-1])) { - $cell{err} = 1 if (@$filters[$i]<@$filters[$i-1]) ; + if ( ( $i == 1 ) and ( @$filters[ $i - 1 ] ) ) { + $cell{err} = 1 if ( @$filters[$i] < @$filters[ $i - 1 ] ); } $cell{filter} .= @$filters[$i]; - defined ($cellmap[$i]) and - $cell{crit} .= $cellmap[$i]; + defined( $cellmap[$i] ) + and $cell{crit} .= $cellmap[$i]; push @loopfilter, \%cell; } } my $colfield; my $colorder; - if ($column){ - $column = "old_issues." .$column if (($column=~/branchcode/) or ($column=~/timestamp/)); - $column = "items.itype" if $column=~/itemtype/; - $column = "borrowers." .$column if $column=~/categorycode/; - my @colfilter ; - if ($column =~ /timestamp/) { - $colfilter[0] = @$filters[0]; - $colfilter[1] = @$filters[1]; - } elsif ($column =~ /returndate/) { - $colfilter[0] = @$filters[2]; - $colfilter[1] = @$filters[3]; - } elsif ($column =~ /branchcode/) { - $colfilter[0] = @$filters[4]; - } elsif ($column =~ /itemtype/) { - $colfilter[0] = @$filters[5]; - } elsif ($column =~ /category/) { - $colfilter[0] = @$filters[6]; - } elsif ($column =~ /sort2/ ) { - # $colfilter[0] = @$filters[11]; - } - - # loop cols. - if ($column eq "Day") { + if ($column) { + $column = "old_issues." . $column if ( ( $column =~ /branchcode/ ) or ( $column =~ /timestamp/ ) ); + $column = "items.itype" if $column =~ /itemtype/; + $column = "borrowers." . $column if $column =~ /categorycode/; + my @colfilter; + if ( $column =~ /timestamp/ ) { + $colfilter[0] = @$filters[0]; + $colfilter[1] = @$filters[1]; + } elsif ( $column =~ /returndate/ ) { + $colfilter[0] = @$filters[2]; + $colfilter[1] = @$filters[3]; + } elsif ( $column =~ /branchcode/ ) { + $colfilter[0] = @$filters[4]; + } elsif ( $column =~ /itemtype/ ) { + $colfilter[0] = @$filters[5]; + } elsif ( $column =~ /category/ ) { + $colfilter[0] = @$filters[6]; + } elsif ( $column =~ /sort2/ ) { + + # $colfilter[0] = @$filters[11]; + } + + # loop cols. + if ( $column eq "Day" ) { + #Display by day $column = "old_issues.timestamp"; - $colfield .="dayname($column)"; - $colorder .="weekday($column)"; - } elsif ($column eq "Month") { + $colfield .= "dayname($column)"; + $colorder .= "weekday($column)"; + } elsif ( $column eq "Month" ) { + #Display by Month $column = "old_issues.timestamp"; - $colfield .="monthname($column)"; - $colorder .="month($column)"; - } elsif ($column eq "Year") { + $colfield .= "monthname($column)"; + $colorder .= "month($column)"; + } elsif ( $column eq "Year" ) { + #Display by Year $column = "old_issues.timestamp"; - $colfield .="Year($column)"; + $colfield .= "Year($column)"; $colorder .= $column; } else { $colfield .= $column; $colorder .= $column; - } + } my $strsth2; $strsth2 .= "SELECT DISTINCTROW $colfield @@ -197,43 +211,44 @@ sub calculate { LEFT JOIN items ON old_issues.itemnumber=items.itemnumber LEFT JOIN biblioitems ON (biblioitems.biblioitemnumber=items.biblioitemnumber) WHERE 1"; - if (($column=~/timestamp/) or ($column=~/returndate/)){ - if ($colfilter[1] and $colfilter[0]){ - $strsth2 .= " AND $column between '$colfilter[0]' AND '$colfilter[1]' " ; - } elsif ($colfilter[1]) { - $strsth2 .= " AND $column < '$colfilter[1]' " ; - } elsif ($colfilter[0]) { - $strsth2 .= " AND $column > '$colfilter[0]' " ; + if ( ( $column =~ /timestamp/ ) or ( $column =~ /returndate/ ) ) { + if ( $colfilter[1] and $colfilter[0] ) { + $strsth2 .= " AND $column between '$colfilter[0]' AND '$colfilter[1]' "; + } elsif ( $colfilter[1] ) { + $strsth2 .= " AND $column < '$colfilter[1]' "; + } elsif ( $colfilter[0] ) { + $strsth2 .= " AND $column > '$colfilter[0]' "; } - } elsif ($colfilter[0]) { + } elsif ( $colfilter[0] ) { $colfilter[0] =~ s/\*/%/g; - $strsth2 .= " AND $column LIKE '$colfilter[0]' " ; + $strsth2 .= " AND $column LIKE '$colfilter[0]' "; } - $strsth2 .=" GROUP BY $colfield"; - $strsth2 .=" ORDER BY $colorder"; + $strsth2 .= " GROUP BY $colfield"; + $strsth2 .= " ORDER BY $colorder"; my $sth2 = $dbh->prepare($strsth2); $sth2->execute; - while (my @row = $sth2->fetchrow) { - $columns{($row[0] ||'NULL')}++; + while ( my @row = $sth2->fetchrow ) { + $columns{ ( $row[0] || 'NULL' ) }++; push @loopcol, { coltitle => $row[0] || 'NULL' }; } - $strsth2 =~ s/old_issues/issues/g; - $sth2 = $dbh->prepare($strsth2); + $strsth2 =~ s/old_issues/issues/g; + $sth2 = $dbh->prepare($strsth2); $sth2->execute; - while (my @row = $sth2->fetchrow) { - $columns{($row[0] ||'NULL')}++; + while ( my @row = $sth2->fetchrow ) { + $columns{ ( $row[0] || 'NULL' ) }++; push @loopcol, { coltitle => $row[0] || 'NULL' }; } - }else{ + } else { $columns{''} = 1; } - my $strcalc ; + my $strcalc; -# Processing average loanperiods - $strcalc .= "SELECT CONCAT_WS('', borrowers.surname , \",\\t\", borrowers.firstname), COUNT(*) AS `RANK`, borrowers.borrowernumber AS ID"; + # Processing average loanperiods + $strcalc .= + "SELECT CONCAT_WS('', borrowers.surname , \",\\t\", borrowers.firstname), COUNT(*) AS `RANK`, borrowers.borrowernumber AS ID"; $strcalc .= " , $colfield " if ($colfield); $strcalc .= " FROM `old_issues` LEFT JOIN borrowers USING(borrowernumber) @@ -241,77 +256,77 @@ sub calculate { LEFT JOIN biblioitems USING(biblioitemnumber) WHERE old_issues.borrowernumber IS NOT NULL "; - my @filterterms = ( - 'old_issues.issuedate >', - 'old_issues.issuedate <', - 'old_issues.returndate >', - 'old_issues.returndate <', - 'old_issues.branchcode like', + my @filterterms = ( + 'old_issues.issuedate >', + 'old_issues.issuedate <', + 'old_issues.returndate >', + 'old_issues.returndate <', + 'old_issues.branchcode like', 'items.itype like', - 'borrowers.categorycode like', - ); - foreach ((@$filters)[0..9]) { - my $term = shift @filterterms; # go through both arrays in step - ($_) or next; - s/\*/%/g; - $strcalc .= " AND $term '$_' "; - } + 'borrowers.categorycode like', + ); + foreach ( (@$filters)[ 0 .. 9 ] ) { + my $term = shift @filterterms; # go through both arrays in step + ($_) or next; + s/\*/%/g; + $strcalc .= " AND $term '$_' "; + } $strcalc .= " GROUP BY borrowers.borrowernumber"; $strcalc .= ", $colfield" if ($column); $strcalc .= " ORDER BY `RANK` DESC"; - $strcalc .= ",$colfield " if ($colfield); + $strcalc .= ",$colfield " if ($colfield); $strcalc .= " LIMIT $limit" if ($limit); my $dbcalc = $dbh->prepare($strcalc); $dbcalc->execute; - my %patrons = (); - # DATA STRUCTURE is going to look like this: - # (2253=> {name=>"John Doe", - # allcols=>{MAIN=>12, MEDIA_LIB=>3} - # }, - # ) - while (my @data = $dbcalc->fetchrow) { - my ($row, $rank, $id, $col) = @data; - $col = "zzEMPTY" if (!defined($col)); - unless ($patrons{$id}) { - $patrons{$id} = {name=>$row, allcols=>{}, newcols=>{}, oldcols=>{}}; - } - $patrons{$id}->{oldcols}->{$col} = $rank; + my %patrons = (); + + # DATA STRUCTURE is going to look like this: + # (2253=> {name=>"John Doe", + # allcols=>{MAIN=>12, MEDIA_LIB=>3} + # }, + # ) + while ( my @data = $dbcalc->fetchrow ) { + my ( $row, $rank, $id, $col ) = @data; + $col = "zzEMPTY" if ( !defined($col) ); + unless ( $patrons{$id} ) { + $patrons{$id} = { name => $row, allcols => {}, newcols => {}, oldcols => {} }; + } + $patrons{$id}->{oldcols}->{$col} = $rank; } - - $strcalc =~ s/old_issues/issues/g; + $strcalc =~ s/old_issues/issues/g; $dbcalc = $dbh->prepare($strcalc); $dbcalc->execute; - while (my @data = $dbcalc->fetchrow) { - my ($row, $rank, $id, $col) = @data; - $col = "zzEMPTY" if (!defined($col)); - unless ($patrons{$id}) { - $patrons{$id} = {name=>$row, allcols=>{}, newcols=>{}, oldcols=>{}}; - } - $patrons{$id}->{newcols}->{$col} = $rank; + while ( my @data = $dbcalc->fetchrow ) { + my ( $row, $rank, $id, $col ) = @data; + $col = "zzEMPTY" if ( !defined($col) ); + unless ( $patrons{$id} ) { + $patrons{$id} = { name => $row, allcols => {}, newcols => {}, oldcols => {} }; + } + $patrons{$id}->{newcols}->{$col} = $rank; } - foreach my $id (keys %patrons) { - my @uniq = keys %{{ %{$patrons{$id}->{newcols}}, %{$patrons{$id}->{oldcols}} }}; # get uniq keys, see perlfaq4 - foreach (@uniq) { - my $count = ($patrons{$id}->{newcols}->{$_} || 0) + - ($patrons{$id}->{oldcols}->{$_} || 0); - $patrons{$id}->{allcols}->{$_} = $count; - $patrons{$id}->{total} += $count; - } - } - - my $i = 1; - my @cols_in_order = sort keys %columns; # if you want to order the columns, do something here - my @ranked_ids = sort { - $patrons{$b}->{total} <=> $patrons{$a}->{total} - || $patrons{$a}->{name} cmp $patrons{$b}->{name} - } keys %patrons; + foreach my $id ( keys %patrons ) { + my @uniq = + keys %{ { %{ $patrons{$id}->{newcols} }, %{ $patrons{$id}->{oldcols} } } }; # get uniq keys, see perlfaq4 + foreach (@uniq) { + my $count = ( $patrons{$id}->{newcols}->{$_} || 0 ) + ( $patrons{$id}->{oldcols}->{$_} || 0 ); + $patrons{$id}->{allcols}->{$_} = $count; + $patrons{$id}->{total} += $count; + } + } + + my $i = 1; + my @cols_in_order = sort keys %columns; # if you want to order the columns, do something here + my @ranked_ids = + sort { $patrons{$b}->{total} <=> $patrons{$a}->{total} || $patrons{$a}->{name} cmp $patrons{$b}->{name} } + keys %patrons; foreach my $id (@ranked_ids) { my @loopcell; - if($column){ + if ($column) { + # Total push @loopcell, { count => $patrons{$id}->{total}, @@ -322,32 +337,36 @@ sub calculate { }; $grantotal += $patrons{$id}->{allcols}->{$key}; } - }else{ + } else { push @loopcell, { count => $patrons{$id}->{total}, }; $grantotal += $patrons{$id}->{total}; } - push @looprow,{ 'rowtitle' => $i++ , - 'loopcell' => \@loopcell, - 'hilighted' => ($i%2), - 'patron' => $patrons{$id}->{name}, - 'reference' => $id, - }; + push @looprow, { + 'rowtitle' => $i++, + 'loopcell' => \@loopcell, + 'hilighted' => ( $i % 2 ), + 'patron' => $patrons{$id}->{name}, + 'reference' => $id, + }; + # use a limit, if a limit is defined - last if $i > $limit and $limit + last if $i > $limit and $limit; } # the header of the table - $globalline{loopfilter}=\@loopfilter; + $globalline{loopfilter} = \@loopfilter; + # the core of the table $globalline{looprow} = \@looprow; - $globalline{loopcol} = [ map {{coltitle=>$_}} @cols_in_order ] if ($column); - # the foot (totals by borrower type) + $globalline{loopcol} = [ map { { coltitle => $_ } } @cols_in_order ] if ($column); + + # the foot (totals by borrower type) $globalline{loopfooter} = []; - $globalline{total}= $grantotal; # FIXME: useless - $globalline{column} = $column; - return [\%globalline]; # reference to a 1 element array: that element is a hashref + $globalline{total} = $grantotal; # FIXME: useless + $globalline{column} = $column; + return [ \%globalline ]; # reference to a 1 element array: that element is a hashref } 1; diff --git a/reports/borrowers_out.pl b/reports/borrowers_out.pl index b5271d98a5..cbe2e1e149 100755 --- a/reports/borrowers_out.pl +++ b/reports/borrowers_out.pl @@ -19,10 +19,10 @@ use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Auth qw( get_template_and_user ); use C4::Context; -use C4::Output qw( output_html_with_http_headers ); +use C4::Output qw( output_html_with_http_headers ); use C4::Reports qw( GetDelimiterChoices ); use Koha::Patron::Categories; @@ -37,181 +37,200 @@ Plugin that shows a stats on borrowers =cut -my $input = CGI->new; -my $do_it=$input->param('do_it'); +my $input = CGI->new; +my $do_it = $input->param('do_it'); my $fullreportname = "reports/borrowers_out.tt"; -my $limit = $input->param("Limit"); -my $column = $input->param("Criteria"); -my @filters = $input->multi_param("Filter"); +my $limit = $input->param("Limit"); +my $column = $input->param("Criteria"); +my @filters = $input->multi_param("Filter"); -my $output = $input->param("output"); +my $output = $input->param("output"); my $basename = $input->param("basename"); -our $sep = C4::Context->csv_delimiter(scalar $input->param("sep")); -my ($template, $borrowernumber, $cookie) - = get_template_and_user({template_name => $fullreportname, - query => $input, - type => "intranet", - flagsrequired => {reports => '*'}, - }); -$template->param(do_it => $do_it, - ); +our $sep = C4::Context->csv_delimiter( scalar $input->param("sep") ); +my ( $template, $borrowernumber, $cookie ) = get_template_and_user( + { + template_name => $fullreportname, + query => $input, + type => "intranet", + flagsrequired => { reports => '*' }, + } +); +$template->param( + do_it => $do_it, +); if ($do_it) { -# Displaying results - my $results = calculate($limit, $column, \@filters); - if ($output eq "screen"){ -# Printing results to screen - $template->param(mainloop => $results); + + # Displaying results + my $results = calculate( $limit, $column, \@filters ); + if ( $output eq "screen" ) { + + # Printing results to screen + $template->param( mainloop => $results ); output_html_with_http_headers $input, $cookie, $template->output; exit; } else { -# Printing to a csv file - print $input->header(-type => 'application/vnd.sun.xml.calc', - -encoding => 'utf-8', - -attachment=>"$basename.csv", - -filename=>"$basename.csv" ); - my $cols = @$results[0]->{loopcol}; + + # Printing to a csv file + print $input->header( + -type => 'application/vnd.sun.xml.calc', + -encoding => 'utf-8', + -attachment => "$basename.csv", + -filename => "$basename.csv" + ); + my $cols = @$results[0]->{loopcol}; my $lines = @$results[0]->{looprow}; -# header top-right - print "num /". @$results[0]->{column} .$sep; -# Other header - foreach my $col ( @$cols ) { - print $col->{coltitle}.$sep; + + # header top-right + print "num /" . @$results[0]->{column} . $sep; + + # Other header + foreach my $col (@$cols) { + print $col->{coltitle} . $sep; } print "Total\n"; -# Table - foreach my $line ( @$lines ) { + + # Table + foreach my $line (@$lines) { my $x = $line->{loopcell}; - print $line->{rowtitle}.$sep; + print $line->{rowtitle} . $sep; foreach my $cell (@$x) { - my $cellvalue = defined $cell->{value} ? $cell->{value}.$sep : ''.$sep; + my $cellvalue = defined $cell->{value} ? $cell->{value} . $sep : '' . $sep; print $cellvalue; } -# print $line->{totalrow}; + + # print $line->{totalrow}; print "\n"; } -# footer + + # footer print "TOTAL"; $cols = @$results[0]->{loopfooter}; - foreach my $col ( @$cols ) { - print $sep.$col->{totalcol}; + foreach my $col (@$cols) { + print $sep. $col->{totalcol}; } - print $sep.@$results[0]->{total}; + print $sep. @$results[0]->{total}; exit; } -# Displaying choices + + # Displaying choices } else { my $dbh = C4::Context->dbh; - my $CGIextChoice = ( 'CSV' ); # FIXME translation - my $CGIsepChoice = GetDelimiterChoices; + my $CGIextChoice = ('CSV'); # FIXME translation + my $CGIsepChoice = GetDelimiterChoices; - my $patron_categories = Koha::Patron::Categories->search_with_library_limits({}, {order_by => ['categorycode']}); + my $patron_categories = + Koha::Patron::Categories->search_with_library_limits( {}, { order_by => ['categorycode'] } ); $template->param( - CGIextChoice => $CGIextChoice, - CGIsepChoice => $CGIsepChoice, - patron_categories => $patron_categories, - ); -output_html_with_http_headers $input, $cookie, $template->output; + CGIextChoice => $CGIextChoice, + CGIsepChoice => $CGIsepChoice, + patron_categories => $patron_categories, + ); + output_html_with_http_headers $input, $cookie, $template->output; } - sub calculate { - my ($line, $column, $filters) = @_; + my ( $line, $column, $filters ) = @_; my @mainloop; my @loopfooter; my @loopcol; my @looprow; my %globalline; - my $grantotal =0; -# extract parameters + my $grantotal = 0; + + # extract parameters my $dbh = C4::Context->dbh; -# Filters -# Checking filters -# + # Filters + # Checking filters + # my @loopfilter; - for (my $i=0;$i<=2;$i++) { + for ( my $i = 0 ; $i <= 2 ; $i++ ) { my %cell; if ( @$filters[$i] ) { - if (($i==1) and (@$filters[$i-1])) { - $cell{err} = 1 if (@$filters[$i]<@$filters[$i-1]) ; + if ( ( $i == 1 ) and ( @$filters[ $i - 1 ] ) ) { + $cell{err} = 1 if ( @$filters[$i] < @$filters[ $i - 1 ] ); } $cell{filter} .= @$filters[$i]; - $cell{crit} .="Bor Cat" if ($i==0); - $cell{crit} .="Without issues since" if ($i==1); + $cell{crit} .= "Bor Cat" if ( $i == 0 ); + $cell{crit} .= "Without issues since" if ( $i == 1 ); push @loopfilter, \%cell; } } my $colfield; my $colorder; - if ($column){ - $column = "borrowers.".$column if $column=~/categorycode/ || $column=~/branchcode/; - my @colfilter ; - $colfilter[0] = @$filters[0] if ($column =~ /category/ ) ; - # $colfilter[0] = @$filters[11] if ($column =~ /sort2/ ) ; - #warn "filtre col ".$colfilter[0]." ".$colfilter[1]; - - # loop cols. + if ($column) { + $column = "borrowers." . $column if $column =~ /categorycode/ || $column =~ /branchcode/; + my @colfilter; + $colfilter[0] = @$filters[0] if ( $column =~ /category/ ); + + # $colfilter[0] = @$filters[11] if ($column =~ /sort2/ ) ; + #warn "filtre col ".$colfilter[0]." ".$colfilter[1]; + + # loop cols. $colfield .= $column; $colorder .= $column; - + my $strsth2; $strsth2 .= "select distinct " . $dbh->quote($colfield) . " FROM borrowers WHERE 1"; my @query_args; if ( $colfilter[0] ) { $colfilter[0] =~ s/\*/%/g; - $strsth2 .= " and " . $dbh->quote($column) . "LIKE ?" ; + $strsth2 .= " and " . $dbh->quote($column) . "LIKE ?"; push @query_args, $colfilter[0]; } - $strsth2 .=" group by " . $dbh->quote($colfield); - $strsth2 .=" order by " . $dbh->quote($colorder); + $strsth2 .= " group by " . $dbh->quote($colfield); + $strsth2 .= " order by " . $dbh->quote($colorder); + # warn "". $strsth2; - - my $sth2 = $dbh->prepare( $strsth2 ); - $sth2->execute( @query_args ); - while (my ($celvalue) = $sth2->fetchrow) { + + my $sth2 = $dbh->prepare($strsth2); + $sth2->execute(@query_args); + while ( my ($celvalue) = $sth2->fetchrow ) { my %cell; - # my %ft; - # warn "coltitle :".$celvalue; + + # my %ft; + # warn "coltitle :".$celvalue; $cell{coltitle} = $celvalue; - # $ft{totalcol} = 0; + + # $ft{totalcol} = 0; push @loopcol, \%cell; } - # warn "fin des titres colonnes"; + + # warn "fin des titres colonnes"; } - - my $i=0; -# my @totalcol; - + + my $i = 0; + + # my @totalcol; + #Initialization of cell values..... my @table; - -# warn "init table"; - if($line) { - for (my $i=1;$i<=$line;$i++) { - foreach my $col ( @loopcol ) { - $table[$i]->{($col->{coltitle})?$col->{coltitle}:"Global"}=0; + + # warn "init table"; + if ($line) { + for ( my $i = 1 ; $i <= $line ; $i++ ) { + foreach my $col (@loopcol) { + $table[$i]->{ ( $col->{coltitle} ) ? $col->{coltitle} : "Global" } = 0; } } } + # preparing calculation + my $strcalc; -# preparing calculation - my $strcalc ; - -# Processing calculation + # Processing calculation $strcalc .= "SELECT CONCAT( borrowers.surname , \"\\t\",borrowers.firstname, \"\\t\", borrowers.cardnumber)"; $strcalc .= " , " . $dbh->quote($colfield) if ($colfield); $strcalc .= " FROM borrowers "; $strcalc .= "WHERE 1 "; - if(C4::Context->preference('IndependentBranches') && !C4::Context->IsSuperLibrarian()){ - $strcalc .= "AND branchcode = '".C4::Context->userenv->{branch}."' "; + if ( C4::Context->preference('IndependentBranches') && !C4::Context->IsSuperLibrarian() ) { + $strcalc .= "AND branchcode = '" . C4::Context->userenv->{branch} . "' "; } - my @query_args; if ( @$filters[0] ) { - @$filters[0]=~ s/\*/%/g; + @$filters[0] =~ s/\*/%/g; $strcalc .= " AND borrowers.categorycode like ?"; push @query_args, @$filters[0]; } @@ -228,66 +247,76 @@ sub calculate { } $strcalc .= ") "; $strcalc .= " group by borrowers.borrowernumber"; - $strcalc .= ", " . $dbh->quote($colfield) if ($column); + $strcalc .= ", " . $dbh->quote($colfield) if ($column); $strcalc .= " order by " . $dbh->quote($colfield) if ($colfield); my $max; if ($line) { if (@loopcol) { - $max = $line*@loopcol; - } else { $max=$line;} + $max = $line * @loopcol; + } else { + $max = $line; + } $strcalc .= " LIMIT 0,$max"; - } - - my $dbcalc = $dbh->prepare($strcalc); - $dbcalc->execute( @query_args ); -# warn "filling table"; - my $previous_col; - $i=1; - while (my @data = $dbcalc->fetchrow) { - my ($row, $col )=@data; - $col = "zzEMPTY" if (!defined($col)); - $i=1 if (($previous_col) and not($col eq $previous_col)); - $table[$i]->{$col}=$row; -# warn " $i $col $row"; - $i++; - $previous_col=$col; } - - push @loopcol,{coltitle => "Global"} if not($column); - - $max =(($line)?$line:@table -1); - for ($i=1; $i<=$max;$i++) { + + my $dbcalc = $dbh->prepare($strcalc); + $dbcalc->execute(@query_args); + + # warn "filling table"; + my $previous_col; + $i = 1; + while ( my @data = $dbcalc->fetchrow ) { + my ( $row, $col ) = @data; + $col = "zzEMPTY" if ( !defined($col) ); + $i = 1 if ( ($previous_col) and not( $col eq $previous_col ) ); + $table[$i]->{$col} = $row; + + # warn " $i $col $row"; + $i++; + $previous_col = $col; + } + + push @loopcol, { coltitle => "Global" } if not($column); + + $max = ( ($line) ? $line : @table - 1 ); + for ( $i = 1 ; $i <= $max ; $i++ ) { my @loopcell; + #@loopcol ensures the order for columns is common with column titles # and the number matches the number of columns - my $colcount=0; - foreach my $col ( @loopcol ) { + my $colcount = 0; + foreach my $col (@loopcol) { my $value; - if (@loopcol){ - $value =$table[$i]->{(($col->{coltitle} eq "NULL") or ($col->{coltitle} eq "Global"))?"zzEMPTY":$col->{coltitle}}; + if (@loopcol) { + $value = $table[$i]->{ + ( ( $col->{coltitle} eq "NULL" ) or ( $col->{coltitle} eq "Global" ) ) + ? "zzEMPTY" + : $col->{coltitle} + }; } else { - $value =$table[$i]->{"zzEMPTY"}; + $value = $table[$i]->{"zzEMPTY"}; } - push @loopcell, {value => $value} ; + push @loopcell, { value => $value }; } - push @looprow,{ 'rowtitle' => $i , - 'loopcell' => \@loopcell, - }; + push @looprow, { + 'rowtitle' => $i, + 'loopcell' => \@loopcell, + }; } - - # the header of the table - $globalline{loopfilter}=\@loopfilter; + $globalline{loopfilter} = \@loopfilter; + # the core of the table $globalline{looprow} = \@looprow; $globalline{loopcol} = \@loopcol; -# # the foot (totals by borrower type) + + # # the foot (totals by borrower type) $globalline{loopfooter} = \@loopfooter; - $globalline{total}= $grantotal; - $globalline{line} = $line; - $globalline{column} = $column; - push @mainloop,\%globalline; + $globalline{total} = $grantotal; + $globalline{line} = $line; + $globalline{column} = $column; + push @mainloop, \%globalline; return \@mainloop; } diff --git a/reports/borrowers_stats.pl b/reports/borrowers_stats.pl index 2aee2d1b2b..fafd85ab26 100755 --- a/reports/borrowers_stats.pl +++ b/reports/borrowers_stats.pl @@ -22,8 +22,8 @@ use CGI qw ( -utf8 ); use C4::Auth qw( get_template_and_user ); use C4::Context; -use C4::Koha qw( GetAuthorisedValues ); -use C4::Output qw( output_html_with_http_headers ); +use C4::Koha qw( GetAuthorisedValues ); +use C4::Output qw( output_html_with_http_headers ); use C4::Reports qw( GetDelimiterChoices ); use Koha::AuthorisedValues; @@ -41,147 +41,156 @@ plugin that shows a stats on borrowers =cut -my $input = CGI->new; -my $do_it=$input->param('do_it'); +my $input = CGI->new; +my $do_it = $input->param('do_it'); my $fullreportname = "reports/borrowers_stats.tt"; -my $line = $input->param("Line"); -my $column = $input->param("Column"); -my @filters = $input->multi_param("Filter"); -my $digits = $input->param("digits"); +my $line = $input->param("Line"); +my $column = $input->param("Column"); +my @filters = $input->multi_param("Filter"); +my $digits = $input->param("digits"); our $period = $input->param("period"); -my $borstat = $input->param("status"); +my $borstat = $input->param("status"); my $borstat1 = $input->param("activity"); -my $output = $input->param("output"); +my $output = $input->param("output"); my $basename = $input->param("basename"); -our $sep = C4::Context->csv_delimiter(scalar $input->param("sep")); +our $sep = C4::Context->csv_delimiter( scalar $input->param("sep") ); -my ($template, $borrowernumber, $cookie) - = get_template_and_user({template_name => $fullreportname, - query => $input, - type => "intranet", - flagsrequired => {reports => '*'}, - }); -$template->param(do_it => $do_it); +my ( $template, $borrowernumber, $cookie ) = get_template_and_user( + { + template_name => $fullreportname, + query => $input, + type => "intranet", + flagsrequired => { reports => '*' }, + } +); +$template->param( do_it => $do_it ); if ($do_it) { - my $attributes; - if (C4::Context->preference('ExtendedPatronAttributes')) { - $attributes = parse_extended_patron_attributes($input); + my $attributes; + if ( C4::Context->preference('ExtendedPatronAttributes') ) { + $attributes = parse_extended_patron_attributes($input); + } + my $results = calculate( $line, $column, $digits, $borstat, $borstat1, \@filters, $attributes ); + if ( $output eq "screen" ) { + $template->param( mainloop => $results ); + output_html_with_http_headers $input, $cookie, $template->output; + } else { + print $input->header( + -type => 'application/vnd.sun.xml.calc', + -encoding => 'utf-8', + -name => "$basename.csv", + -attachment => "$basename.csv" + ); + my $cols = @$results[0]->{loopcol}; + my $lines = @$results[0]->{looprow}; + print @$results[0]->{line} . "/" . @$results[0]->{column} . $sep; + foreach my $col (@$cols) { + print $col->{coltitle} . $sep; } - my $results = calculate($line, $column, $digits, $borstat,$borstat1 ,\@filters, $attributes); - if ($output eq "screen"){ - $template->param(mainloop => $results); - output_html_with_http_headers $input, $cookie, $template->output; - } else { - print $input->header(-type => 'application/vnd.sun.xml.calc', - -encoding => 'utf-8', - -name => "$basename.csv", - -attachment => "$basename.csv"); - my $cols = @$results[0]->{loopcol}; - my $lines = @$results[0]->{looprow}; - print @$results[0]->{line} ."/". @$results[0]->{column} .$sep; - foreach my $col ( @$cols ) { - print $col->{coltitle}.$sep; - } - print "Total\n"; - foreach my $line ( @$lines ) { - my $x = $line->{loopcell}; - print $line->{rowtitle}.$sep; - foreach my $cell (@$x) { - print $cell->{value}.$sep; - } - print $line->{totalrow}; - print "\n"; - } - print "TOTAL"; - $cols = @$results[0]->{loopfooter}; - foreach my $col ( @$cols ) { - print $sep.$col->{totalcol}; - } - print $sep.@$results[0]->{total}; - } - exit; # exit after do_it, regardless + print "Total\n"; + foreach my $line (@$lines) { + my $x = $line->{loopcell}; + print $line->{rowtitle} . $sep; + foreach my $cell (@$x) { + print $cell->{value} . $sep; + } + print $line->{totalrow}; + print "\n"; + } + print "TOTAL"; + $cols = @$results[0]->{loopfooter}; + foreach my $col (@$cols) { + print $sep. $col->{totalcol}; + } + print $sep. @$results[0]->{total}; + } + exit; # exit after do_it, regardless } else { - my $dbh = C4::Context->dbh; - my $req; - my $patron_categories = Koha::Patron::Categories->search({}, {order_by => ['description']}); + my $dbh = C4::Context->dbh; + my $req; + my $patron_categories = Koha::Patron::Categories->search( {}, { order_by => ['description'] } ); $template->param( patron_categories => $patron_categories ); - $req = $dbh->prepare("SELECT DISTINCTROW zipcode FROM borrowers WHERE zipcode IS NOT NULL AND zipcode <> '' ORDER BY zipcode"); - $req->execute; - $template->param( ZIP_LOOP => $req->fetchall_arrayref({})); - $req = $dbh->prepare("SELECT authorised_value,lib FROM authorised_values WHERE category='Bsort1' ORDER BY lib"); - $req->execute; - $template->param( SORT1_LOOP => $req->fetchall_arrayref({})); - $req = $dbh->prepare("SELECT DISTINCTROW sort2 AS value FROM borrowers WHERE sort2 IS NOT NULL AND sort2 <> '' ORDER BY sort2 LIMIT 200"); - # More than 200 items in a dropdown is not going to be useful anyway, and w/ 50,000 patrons we can destroy DB performance. - $req->execute; - $template->param( SORT2_LOOP => $req->fetchall_arrayref({})); - - my $CGIextChoice = ( 'CSV' ); # FIXME translation - my $CGIsepChoice=GetDelimiterChoices; - $template->param( - CGIextChoice => $CGIextChoice, - CGIsepChoice => $CGIsepChoice, + $req = $dbh->prepare( + "SELECT DISTINCTROW zipcode FROM borrowers WHERE zipcode IS NOT NULL AND zipcode <> '' ORDER BY zipcode"); + $req->execute; + $template->param( ZIP_LOOP => $req->fetchall_arrayref( {} ) ); + $req = $dbh->prepare("SELECT authorised_value,lib FROM authorised_values WHERE category='Bsort1' ORDER BY lib"); + $req->execute; + $template->param( SORT1_LOOP => $req->fetchall_arrayref( {} ) ); + $req = $dbh->prepare( + "SELECT DISTINCTROW sort2 AS value FROM borrowers WHERE sort2 IS NOT NULL AND sort2 <> '' ORDER BY sort2 LIMIT 200" ); - if (C4::Context->preference('ExtendedPatronAttributes')) { + + # More than 200 items in a dropdown is not going to be useful anyway, and w/ 50,000 patrons we can destroy DB performance. + $req->execute; + $template->param( SORT2_LOOP => $req->fetchall_arrayref( {} ) ); + + my $CGIextChoice = ('CSV'); # FIXME translation + my $CGIsepChoice = GetDelimiterChoices; + $template->param( + CGIextChoice => $CGIextChoice, + CGIsepChoice => $CGIsepChoice, + ); + if ( C4::Context->preference('ExtendedPatronAttributes') ) { patron_attributes_form($template); } } output_html_with_http_headers $input, $cookie, $template->output; sub calculate { - my ($line, $column, $digits, $status, $activity, $filters, $attr_filters) = @_; + my ( $line, $column, $digits, $status, $activity, $filters, $attr_filters ) = @_; - my @mainloop; - my @loopfooter; - my @loopcol; - my @loopline; - my @looprow; - my %globalline; - my $grantotal =0; -# extract parameters - my $dbh = C4::Context->dbh; + my @mainloop; + my @loopfooter; + my @loopcol; + my @loopline; + my @looprow; + my %globalline; + my $grantotal = 0; + + # extract parameters + my $dbh = C4::Context->dbh; # check parameters my @valid_names = qw(categorycode zipcode branchcode sex sort1 sort2); - if ($line =~ /^patron_attr\.(.*)/) { + if ( $line =~ /^patron_attr\.(.*)/ ) { my $attribute_type = $1; return unless Koha::Patron::Attribute::Types->find($attribute_type); } else { - return unless (grep { $_ eq $line } @valid_names); + return unless ( grep { $_ eq $line } @valid_names ); } - if ($column =~ /^patron_attr\.(.*)/) { + if ( $column =~ /^patron_attr\.(.*)/ ) { my $attribute_type = $1; return unless Koha::Patron::Attribute::Types->find($attribute_type); } else { - return unless (grep { $_ eq $column } @valid_names); + return unless ( grep { $_ eq $column } @valid_names ); } - return if ($digits and $digits !~ /^\d+$/); - return if ($status and (grep { $_ eq $status } qw(debarred gonenoaddress lost)) == 0); - return if ($activity and (grep { $_ eq $activity } qw(active nonactive)) == 0); + return if ( $digits and $digits !~ /^\d+$/ ); + return if ( $status and ( grep { $_ eq $status } qw(debarred gonenoaddress lost) ) == 0 ); + return if ( $activity and ( grep { $_ eq $activity } qw(active nonactive) ) == 0 ); # Filters my $linefilter; - if ( $line =~ /categorycode/ ) { $linefilter = @$filters[0]; } - elsif ( $line =~ /zipcode/ ) { $linefilter = @$filters[1]; } - elsif ( $line =~ /branchcode/ ) { $linefilter = @$filters[2]; } - elsif ( $line =~ /sex/ ) { $linefilter = @$filters[5]; } - elsif ( $line =~ /sort1/ ) { $linefilter = @$filters[6]; } - elsif ( $line =~ /sort2/ ) { $linefilter = @$filters[7]; } + if ( $line =~ /categorycode/ ) { $linefilter = @$filters[0]; } + elsif ( $line =~ /zipcode/ ) { $linefilter = @$filters[1]; } + elsif ( $line =~ /branchcode/ ) { $linefilter = @$filters[2]; } + elsif ( $line =~ /sex/ ) { $linefilter = @$filters[5]; } + elsif ( $line =~ /sort1/ ) { $linefilter = @$filters[6]; } + elsif ( $line =~ /sort2/ ) { $linefilter = @$filters[7]; } elsif ( $line =~ /^patron_attr\.(.*)$/ ) { $linefilter = $attr_filters->{$1}; } - else { $linefilter = ''; } + else { $linefilter = ''; } my $colfilter; - if ( $column =~ /categorycode/ ) { $colfilter = @$filters[0]; } - elsif ( $column =~ /zipcode/ ) { $colfilter = @$filters[1]; } - elsif ( $column =~ /branchcode/) { $colfilter = @$filters[2]; } - elsif ( $column =~ /sex/) { $colfilter = @$filters[5]; } - elsif ( $column =~ /sort1/) { $colfilter = @$filters[6]; } - elsif ( $column =~ /sort2/) { $colfilter = @$filters[7]; } - elsif ( $column =~ /^patron_attr\.(.*)$/) { $colfilter = $attr_filters->{$1}; } - else { $colfilter = ''; } + if ( $column =~ /categorycode/ ) { $colfilter = @$filters[0]; } + elsif ( $column =~ /zipcode/ ) { $colfilter = @$filters[1]; } + elsif ( $column =~ /branchcode/ ) { $colfilter = @$filters[2]; } + elsif ( $column =~ /sex/ ) { $colfilter = @$filters[5]; } + elsif ( $column =~ /sort1/ ) { $colfilter = @$filters[6]; } + elsif ( $column =~ /sort2/ ) { $colfilter = @$filters[7]; } + elsif ( $column =~ /^patron_attr\.(.*)$/ ) { $colfilter = $attr_filters->{$1}; } + else { $colfilter = ''; } my @loopfilter; - foreach my $i (0 .. scalar @$filters) { + foreach my $i ( 0 .. scalar @$filters ) { my %cell; if ( @$filters[$i] ) { if ( $i == 0 ) { $cell{crit} = "Cat code"; $cell{filter} = @$filters[$i]; } @@ -196,39 +205,41 @@ sub calculate { push @loopfilter, \%cell; } } - foreach my $type (keys %$attr_filters) { - if($attr_filters->{$type}) { + foreach my $type ( keys %$attr_filters ) { + if ( $attr_filters->{$type} ) { push @loopfilter, { - crit => "Attribute $type", + crit => "Attribute $type", filter => $attr_filters->{$type} - } + }; } } my @branchcodes = Koha::Libraries->search->get_column('branchcode'); - ($status ) and push @loopfilter,{crit=>"Status", filter=>$status }; - ($activity) and push @loopfilter,{crit=>"Activity",filter=>$activity}; -# year of activity - my ( $period_year, $period_month, $period_day )=Add_Delta_YM( Today(),-$period, 0); - my $newperioddate=$period_year."-".$period_month."-".$period_day; -# 1st, loop rows. - my $linefield; + ($status) and push @loopfilter, { crit => "Status", filter => $status }; + ($activity) and push @loopfilter, { crit => "Activity", filter => $activity }; + + # year of activity + my ( $period_year, $period_month, $period_day ) = Add_Delta_YM( Today(), -$period, 0 ); + my $newperioddate = $period_year . "-" . $period_month . "-" . $period_day; + + # 1st, loop rows. + my $linefield; my $line_attribute_type; - if ($line =~/^patron_attr\.(.*)$/) { + if ( $line =~ /^patron_attr\.(.*)$/ ) { $line_attribute_type = $1; - $line = 'borrower_attributes.attribute'; + $line = 'borrower_attributes.attribute'; } - if (($line =~/zipcode/) and ($digits)) { + if ( ( $line =~ /zipcode/ ) and ($digits) ) { $linefield = "left($line,$digits)"; } else { $linefield = $line; } - my $patron_categories = Koha::Patron::Categories->search({}, {order_by => ['categorycode']}); + my $patron_categories = Koha::Patron::Categories->search( {}, { order_by => ['categorycode'] } ); my $strsth; - my @strparams; # bind parameters for the query + my @strparams; # bind parameters for the query if ($line_attribute_type) { $strsth = "SELECT distinct attribute FROM borrower_attributes WHERE attribute IS NOT NULL AND code=?"; @@ -238,43 +249,44 @@ sub calculate { WHERE $line IS NOT NULL "; } - $linefilter =~ s/\*/%/g; - if ( $linefilter ) { - $strsth .= " AND $linefield LIKE ? " ; - push @strparams, $linefilter; - } - $strsth .= " AND $status='1' " if ($status); - $strsth .=" order by $linefield"; - - my $sth = $dbh->prepare($strsth); + $linefilter =~ s/\*/%/g; + if ($linefilter) { + $strsth .= " AND $linefield LIKE ? "; + push @strparams, $linefilter; + } + $strsth .= " AND $status='1' " if ($status); + $strsth .= " order by $linefield"; + + my $sth = $dbh->prepare($strsth); $sth->execute(@strparams); - while (my ($celvalue) = $sth->fetchrow) { - my %cell; - if ($celvalue) { - $cell{rowtitle} = $celvalue; - $cell{rowtitle_display} = ($patron_categories->find($celvalue)->description || "$celvalue\*") if ($line eq 'categorycode'); - } - $cell{totalrow} = 0; - push @loopline, \%cell; - } - -# 2nd, loop cols. - my $colfield; - - my $column_attribute_type; - if ($column =~/^patron_attr.(.*)$/) { - $column_attribute_type = $1; - $column = 'borrower_attributes.attribute'; + while ( my ($celvalue) = $sth->fetchrow ) { + my %cell; + if ($celvalue) { + $cell{rowtitle} = $celvalue; + $cell{rowtitle_display} = ( $patron_categories->find($celvalue)->description || "$celvalue\*" ) + if ( $line eq 'categorycode' ); + } + $cell{totalrow} = 0; + push @loopline, \%cell; } - if (($column =~/zipcode/) and ($digits)) { + # 2nd, loop cols. + my $colfield; + + my $column_attribute_type; + if ( $column =~ /^patron_attr.(.*)$/ ) { + $column_attribute_type = $1; + $column = 'borrower_attributes.attribute'; + } + + if ( ( $column =~ /zipcode/ ) and ($digits) ) { $colfield = "left($column,$digits)"; } else { $colfield = $column; } my $strsth2; - my @strparams2; # bind parameters for the query + my @strparams2; # bind parameters for the query if ($column_attribute_type) { $strsth2 = "SELECT DISTINCT attribute FROM borrower_attributes WHERE attribute IS NOT NULL AND code=?"; @@ -284,40 +296,43 @@ sub calculate { WHERE $column IS NOT NULL"; } - if ($colfilter) { - $colfilter =~ s/\*/%/g; - $strsth2 .= " AND $colfield LIKE ? "; + if ($colfilter) { + $colfilter =~ s/\*/%/g; + $strsth2 .= " AND $colfield LIKE ? "; push @strparams2, $colfield; - } - $strsth2 .= " AND $status='1' " if ($status); + } + $strsth2 .= " AND $status='1' " if ($status); $strsth2 .= " order by $colfield"; - my $sth2 = $dbh->prepare($strsth2); + my $sth2 = $dbh->prepare($strsth2); $sth2->execute(@strparams2); - while (my ($celvalue) = $sth2->fetchrow) { - my %cell; - if (defined $celvalue) { - $cell{coltitle} = $celvalue; - # $cell{coltitle_display} = ($colfield eq 'branchcode') ? $branches->{$celvalue}->{branchname} : $celvalue; - $cell{coltitle_display} = $patron_categories->find($celvalue)->description if ($column eq 'categorycode'); - } - push @loopcol, \%cell; - } + while ( my ($celvalue) = $sth2->fetchrow ) { + my %cell; + if ( defined $celvalue ) { + $cell{coltitle} = $celvalue; - my $i=0; - #Initialization of cell values..... - my %table; -# warn "init table"; - foreach my $row (@loopline) { - foreach my $col ( @loopcol ) { + # $cell{coltitle_display} = ($colfield eq 'branchcode') ? $branches->{$celvalue}->{branchname} : $celvalue; + $cell{coltitle_display} = $patron_categories->find($celvalue)->description if ( $column eq 'categorycode' ); + } + push @loopcol, \%cell; + } + + my $i = 0; + + #Initialization of cell values..... + my %table; + + # warn "init table"; + foreach my $row (@loopline) { + foreach my $col (@loopcol) { my $rowtitle = $row->{rowtitle} // ''; my $coltitle = $row->{coltitle} // ''; $table{$rowtitle}->{$coltitle} = 0; - } + } $row->{rowtitle} ||= ''; - $table{$row->{rowtitle}}->{totalrow}=0; - $table{$row->{rowtitle}}->{rowtitle_display} = $row->{rowtitle_display}; - } + $table{ $row->{rowtitle} }->{totalrow} = 0; + $table{ $row->{rowtitle} }->{rowtitle_display} = $row->{rowtitle_display}; + } # preparing calculation my $strcalc; @@ -335,12 +350,11 @@ sub calculate { } $strcalc .= " COUNT(*) FROM borrowers "; - foreach my $type (keys %$attr_filters) { - if ( - ($line_attribute_type and $line_attribute_type eq $type) - or ($column_attribute_type and $column_attribute_type eq $type) - or ($attr_filters->{$type}) - ) { + foreach my $type ( keys %$attr_filters ) { + if ( ( $line_attribute_type and $line_attribute_type eq $type ) + or ( $column_attribute_type and $column_attribute_type eq $type ) + or ( $attr_filters->{$type} ) ) + { $strcalc .= " LEFT JOIN borrower_attributes AS attribute_$type ON (borrowers.borrowernumber = attribute_$type.borrowernumber AND attribute_$type.code = " . $dbh->quote($type) . ") "; @@ -348,33 +362,40 @@ sub calculate { } $strcalc .= " WHERE 1 "; - @$filters[0]=~ s/\*/%/g if (@$filters[0]); - $strcalc .= " AND categorycode like '" . @$filters[0] ."'" if ( @$filters[0] ); - @$filters[1]=~ s/\*/%/g if (@$filters[1]); - $strcalc .= " AND zipcode like '" . @$filters[1] ."'" if ( @$filters[1] ); - @$filters[2]=~ s/\*/%/g if (@$filters[2]); - $strcalc .= " AND branchcode like '" . @$filters[2] ."'" if ( @$filters[2] ); - @$filters[3]=~ s/\*/%/g if (@$filters[3]); - $strcalc .= " AND dateofbirth > '" . @$filters[3] ."'" if ( @$filters[3] ); - @$filters[4]=~ s/\*/%/g if (@$filters[4]); - $strcalc .= " AND dateofbirth < '" . @$filters[4] ."'" if ( @$filters[4] ); - @$filters[5]=~ s/\*/%/g if (@$filters[5]); - $strcalc .= " AND sex like '" . @$filters[5] ."'" if ( @$filters[5] ); - @$filters[6]=~ s/\*/%/g if (@$filters[6]); - $strcalc .= " AND sort1 like '" . @$filters[6] ."'" if ( @$filters[6] ); - @$filters[7]=~ s/\*/%/g if (@$filters[7]); - $strcalc .= " AND sort2 like '" . @$filters[7] ."'" if ( @$filters[7] ); + @$filters[0] =~ s/\*/%/g if ( @$filters[0] ); + $strcalc .= " AND categorycode like '" . @$filters[0] . "'" if ( @$filters[0] ); + @$filters[1] =~ s/\*/%/g if ( @$filters[1] ); + $strcalc .= " AND zipcode like '" . @$filters[1] . "'" if ( @$filters[1] ); + @$filters[2] =~ s/\*/%/g if ( @$filters[2] ); + $strcalc .= " AND branchcode like '" . @$filters[2] . "'" if ( @$filters[2] ); + @$filters[3] =~ s/\*/%/g if ( @$filters[3] ); + $strcalc .= " AND dateofbirth > '" . @$filters[3] . "'" if ( @$filters[3] ); + @$filters[4] =~ s/\*/%/g if ( @$filters[4] ); + $strcalc .= " AND dateofbirth < '" . @$filters[4] . "'" if ( @$filters[4] ); + @$filters[5] =~ s/\*/%/g if ( @$filters[5] ); + $strcalc .= " AND sex like '" . @$filters[5] . "'" if ( @$filters[5] ); + @$filters[6] =~ s/\*/%/g if ( @$filters[6] ); + $strcalc .= " AND sort1 like '" . @$filters[6] . "'" if ( @$filters[6] ); + @$filters[7] =~ s/\*/%/g if ( @$filters[7] ); + $strcalc .= " AND sort2 like '" . @$filters[7] . "'" if ( @$filters[7] ); - foreach my $type (keys %$attr_filters) { - if($attr_filters->{$type}) { + foreach my $type ( keys %$attr_filters ) { + if ( $attr_filters->{$type} ) { my $filter = $attr_filters->{$type}; $filter =~ s/\*/%/g; $strcalc .= " AND attribute_$type.attribute LIKE '" . $filter . "' "; } } - $strcalc .= " AND borrowers.borrowernumber in (select distinct(borrowernumber) from old_issues where issuedate > '" . $newperioddate . "')" if ($activity eq 'active'); - $strcalc .= " AND borrowers.borrowernumber not in (select distinct(borrowernumber) from old_issues where issuedate > '" . $newperioddate . "' AND borrowernumber IS NOT NULL)" if ($activity eq 'nonactive'); - $strcalc .= " AND $status='1' " if ($status); + $strcalc .= + " AND borrowers.borrowernumber in (select distinct(borrowernumber) from old_issues where issuedate > '" + . $newperioddate . "')" + if ( $activity eq 'active' ); + $strcalc .= + " AND borrowers.borrowernumber not in (select distinct(borrowernumber) from old_issues where issuedate > '" + . $newperioddate + . "' AND borrowernumber IS NOT NULL)" + if ( $activity eq 'nonactive' ); + $strcalc .= " AND $status='1' " if ($status); $strcalc .= " GROUP BY "; if ($line_attribute_type) { @@ -388,69 +409,74 @@ sub calculate { $strcalc .= " $colfield "; } - my $dbcalc = $dbh->prepare($strcalc); - (scalar(@calcparams)) ? $dbcalc->execute(@calcparams) : $dbcalc->execute(); - - my $emptycol; - while (my ($row, $col, $value) = $dbcalc->fetchrow) { -# warn "filling table $row / $col / $value "; - $emptycol = 1 if (!defined($col)); - $col = "zzEMPTY" if (!defined($col)); - $row = "zzEMPTY" if (!defined($row)); - - $table{$row}->{$col}+=$value; - $table{$row}->{totalrow}+=$value; - $grantotal += $value; - } - - push @loopcol,{coltitle => "NULL"} if ($emptycol); - - foreach my $row (sort keys %table) { - my @loopcell; - #@loopcol ensures the order for columns is common with column titles - # and the number matches the number of columns - foreach my $col ( @loopcol ) { + my $dbcalc = $dbh->prepare($strcalc); + ( scalar(@calcparams) ) ? $dbcalc->execute(@calcparams) : $dbcalc->execute(); + + my $emptycol; + while ( my ( $row, $col, $value ) = $dbcalc->fetchrow ) { + + # warn "filling table $row / $col / $value "; + $emptycol = 1 if ( !defined($col) ); + $col = "zzEMPTY" if ( !defined($col) ); + $row = "zzEMPTY" if ( !defined($row) ); + + $table{$row}->{$col} += $value; + $table{$row}->{totalrow} += $value; + $grantotal += $value; + } + + push @loopcol, { coltitle => "NULL" } if ($emptycol); + + foreach my $row ( sort keys %table ) { + my @loopcell; + + #@loopcol ensures the order for columns is common with column titles + # and the number matches the number of columns + foreach my $col (@loopcol) { my $coltitle = $col->{coltitle} // ''; $coltitle = $coltitle eq "NULL" ? "zzEMPTY" : $coltitle; - my $value =$table{$row}->{$coltitle}; - push @loopcell, {value => $value}; - } - push @looprow,{ - 'rowtitle' => ($row eq "zzEMPTY")?"NULL":$row, - 'rowtitle_display' => $table{$row}->{rowtitle_display} || ($row eq "zzEMPTY" ? "NULL" : $row), - 'loopcell' => \@loopcell, - 'totalrow' => $table{$row}->{totalrow} - }; - } - - foreach my $col ( @loopcol ) { - my $total=0; - foreach my $row ( @looprow ) { + my $value = $table{$row}->{$coltitle}; + push @loopcell, { value => $value }; + } + push @looprow, { + 'rowtitle' => ( $row eq "zzEMPTY" ) ? "NULL" : $row, + 'rowtitle_display' => $table{$row}->{rowtitle_display} || ( $row eq "zzEMPTY" ? "NULL" : $row ), + 'loopcell' => \@loopcell, + 'totalrow' => $table{$row}->{totalrow} + }; + } + + foreach my $col (@loopcol) { + my $total = 0; + foreach my $row (@looprow) { my $rowtitle = $row->{rowtitle} // ''; - $rowtitle = ($rowtitle eq "NULL") ? "zzEMPTY" : $rowtitle; + $rowtitle = ( $rowtitle eq "NULL" ) ? "zzEMPTY" : $rowtitle; my $coltitle = $col->{coltitle} // ''; - $coltitle = ($coltitle eq "NULL") ? "zzEMPTY" : $coltitle; + $coltitle = ( $coltitle eq "NULL" ) ? "zzEMPTY" : $coltitle; $total += $table{$rowtitle}->{$coltitle} || 0; -# warn "value added ".$table{$row->{rowtitle}}->{$col->{coltitle}}. "for line ".$row->{rowtitle}; - } -# warn "summ for column ".$col->{coltitle}." = ".$total; - push @loopfooter, {'totalcol' => $total}; - } - - # the header of the table - $globalline{loopfilter}=\@loopfilter; - # the core of the table - $globalline{looprow} = \@looprow; - $globalline{loopcol} = \@loopcol; -# # the foot (totals by borrower type) - $globalline{loopfooter} = \@loopfooter; - $globalline{total}= $grantotal; - $globalline{line} = ($line_attribute_type) ? $line_attribute_type : $line; - $globalline{column} = ($column_attribute_type) ? $column_attribute_type : $column; - push @mainloop,\%globalline; - return \@mainloop; + # warn "value added ".$table{$row->{rowtitle}}->{$col->{coltitle}}. "for line ".$row->{rowtitle}; + } + + # warn "summ for column ".$col->{coltitle}." = ".$total; + push @loopfooter, { 'totalcol' => $total }; + } + + # the header of the table + $globalline{loopfilter} = \@loopfilter; + + # the core of the table + $globalline{looprow} = \@looprow; + $globalline{loopcol} = \@loopcol; + + # # the foot (totals by borrower type) + $globalline{loopfooter} = \@loopfooter; + $globalline{total} = $grantotal; + $globalline{line} = ($line_attribute_type) ? $line_attribute_type : $line; + $globalline{column} = ($column_attribute_type) ? $column_attribute_type : $column; + push @mainloop, \%globalline; + return \@mainloop; } sub parse_extended_patron_attributes { @@ -459,8 +485,8 @@ sub parse_extended_patron_attributes { my @params_names = $input->param; my %attr; foreach my $name (@params_names) { - if ($name =~ /^Filter_patron_attr\.(.*)$/) { - my $code = $1; + if ( $name =~ /^Filter_patron_attr\.(.*)$/ ) { + my $code = $1; my $value = $input->param($name); $attr{$code} = $value; } @@ -469,38 +495,36 @@ sub parse_extended_patron_attributes { return \%attr; } - sub patron_attributes_form { my $template = shift; - my $library_id = C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef; - my $attribute_types = Koha::Patron::Attribute::Types->search_with_library_limits({}, {}, $library_id); + my $library_id = C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef; + my $attribute_types = Koha::Patron::Attribute::Types->search_with_library_limits( {}, {}, $library_id ); my %items_by_class; while ( my $attr_type = $attribute_types->next ) { + # TODO The following can be simplified easily my $entry = { - class => $attr_type->class(), - code => $attr_type->code(), - description => $attr_type->description(), - repeatable => $attr_type->repeatable(), - category => $attr_type->authorised_value_category(), - category_code => $attr_type->category_code(), + class => $attr_type->class(), + code => $attr_type->code(), + description => $attr_type->description(), + repeatable => $attr_type->repeatable(), + category => $attr_type->authorised_value_category(), + category_code => $attr_type->category_code(), }; - my $newentry = { %$entry }; - if ($attr_type->authorised_value_category()) { - $newentry->{use_dropdown} = 1; - $newentry->{auth_val_loop} = GetAuthorisedValues( - $attr_type->authorised_value_category() - ); + my $newentry = {%$entry}; + if ( $attr_type->authorised_value_category() ) { + $newentry->{use_dropdown} = 1; + $newentry->{auth_val_loop} = GetAuthorisedValues( $attr_type->authorised_value_category() ); } push @{ $items_by_class{ $attr_type->class() } }, $newentry; } my @attribute_loop; foreach my $class ( sort keys %items_by_class ) { - my $av = Koha::AuthorisedValues->search({ category => 'PA_CLASS', authorised_value => $class }); + my $av = Koha::AuthorisedValues->search( { category => 'PA_CLASS', authorised_value => $class } ); my $lib = $av->count ? $av->next->lib : $class; push @attribute_loop, { class => $class, @@ -509,6 +533,6 @@ sub patron_attributes_form { }; } - $template->param(patron_attributes => \@attribute_loop); + $template->param( patron_attributes => \@attribute_loop ); } diff --git a/reports/cash_register_stats.pl b/reports/cash_register_stats.pl index 2a7de38101..e5ededba6b 100755 --- a/reports/cash_register_stats.pl +++ b/reports/cash_register_stats.pl @@ -20,32 +20,34 @@ use C4::Auth qw( get_template_and_user ); use CGI; use C4::Context; use C4::Reports qw( GetDelimiterChoices ); -use C4::Output qw( output_html_with_http_headers ); +use C4::Output qw( output_html_with_http_headers ); use DateTime; use Koha::DateUtils qw( dt_from_string ); -use List::Util qw( any ); +use List::Util qw( any ); use Koha::Account::CreditTypes; use Koha::Account::DebitTypes; -my $input = CGI->new; -my $dbh = C4::Context->dbh; +my $input = CGI->new; +my $dbh = C4::Context->dbh; -my ($template, $borrowernumber, $cookie) = get_template_and_user({ - template_name => "reports/cash_register_stats.tt", - query => $input, - type => "intranet", - flagsrequired => {reports => '*'}, -}); +my ( $template, $borrowernumber, $cookie ) = get_template_and_user( + { + template_name => "reports/cash_register_stats.tt", + query => $input, + type => "intranet", + flagsrequired => { reports => '*' }, + } +); -my $do_it = $input->param('do_it'); -my $output = $input->param("output"); -my $basename = $input->param("basename"); -my $transaction_type = $input->param("transaction_type") || 'ACT'; -my $manager_branchcode = $input->param("branch") || C4::Context->userenv->{'branch'}; +my $do_it = $input->param('do_it'); +my $output = $input->param("output"); +my $basename = $input->param("basename"); +my $transaction_type = $input->param("transaction_type") || 'ACT'; +my $manager_branchcode = $input->param("branch") || C4::Context->userenv->{'branch'}; $template->param( - do_it => $do_it, + do_it => $do_it, CGIsepChoice => GetDelimiterChoices, ); @@ -53,23 +55,20 @@ $template->param( my $fromDate = $input->param("from") || dt_from_string; my $toDate = $input->param("to") || dt_from_string; -my @debit_types = - Koha::Account::DebitTypes->search()->as_list; -my @credit_types = - Koha::Account::CreditTypes->search()->as_list; +my @debit_types = Koha::Account::DebitTypes->search()->as_list; +my @credit_types = Koha::Account::CreditTypes->search()->as_list; my $registerid; if ($do_it) { - my $whereTType = q{}; - my @extra_params; # if we add conditions to the select we need extra params + my @extra_params; # if we add conditions to the select we need extra params - if ($transaction_type eq 'ALL') { #All Transactions + if ( $transaction_type eq 'ALL' ) { #All Transactions $whereTType = q{}; - } elsif ($transaction_type eq 'ACT') { #Active + } elsif ( $transaction_type eq 'ACT' ) { #Active $whereTType = q{ AND credit_type_code IN ('PAYMENT','CREDIT') }; - } elsif ($transaction_type eq 'FORW') { + } elsif ( $transaction_type eq 'FORW' ) { $whereTType = q{ AND credit_type_code IN ('FORGIVEN','WRITEOFF') }; } else { if ( any { $transaction_type eq $_->code } @debit_types ) { @@ -86,7 +85,7 @@ if ($do_it) { } my $whereBranchCode = q{}; - if ($manager_branchcode ne 'ALL') { + if ( $manager_branchcode ne 'ALL' ) { $whereBranchCode = q{ AND al.branchcode = ?}; push @extra_params, $manager_branchcode; } @@ -119,72 +118,74 @@ if ($do_it) { $whereRegister ORDER BY al.date "; - my $sth_stats = $dbh->prepare($query) or die "Unable to prepare query " . $dbh->errstr; - $sth_stats->execute($fromDate, $toDate, @extra_params) or die "Unable to execute query " . $sth_stats->errstr; + my $sth_stats = $dbh->prepare($query) or die "Unable to prepare query " . $dbh->errstr; + $sth_stats->execute( $fromDate, $toDate, @extra_params ) or die "Unable to execute query " . $sth_stats->errstr; my @loopresult; my $grantotal = 0; - while ( my $row = $sth_stats->fetchrow_hashref()) { - $row->{amountoutstanding} = 0 if (!$row->{amountoutstanding}); - #if ((abs($row->{amount}) - $row->{amountoutstanding}) > 0) { - $row->{amount} = sprintf("%.2f", abs ($row->{amount})); - $row->{date} = dt_from_string($row->{date}, 'sql'); + while ( my $row = $sth_stats->fetchrow_hashref() ) { + $row->{amountoutstanding} = 0 if ( !$row->{amountoutstanding} ); + + #if ((abs($row->{amount}) - $row->{amountoutstanding}) > 0) { + $row->{amount} = sprintf( "%.2f", abs( $row->{amount} ) ); + $row->{date} = dt_from_string( $row->{date}, 'sql' ); + + push( @loopresult, $row ); + if ( $transaction_type eq 'ACT' && ( $row->{credit_type_code} !~ /^CREDIT$|^PAYMENT$/ ) ) { + pop @loopresult; + next; + } + if ( $row->{credit_type_code} =~ /^CREDIT$/ ) { + $grantotal -= abs( $row->{amount} ); + $row->{amount} = '-' . $row->{amount}; + } elsif ( $row->{credit_type_code} eq 'FORGIVEN' || $row->{credit_type_code} eq 'WRITEOFF' ) { + } else { + $grantotal += abs( $row->{amount} ); + } - push (@loopresult, $row); - if($transaction_type eq 'ACT' && ($row->{credit_type_code} !~ /^CREDIT$|^PAYMENT$/)){ - pop @loopresult; - next; - } - if($row->{credit_type_code} =~ /^CREDIT$/){ - $grantotal -= abs($row->{amount}); - $row->{amount} = '-' . $row->{amount}; - }elsif($row->{credit_type_code} eq 'FORGIVEN' || $row->{credit_type_code} eq 'WRITEOFF'){ - }else{ - $grantotal += abs($row->{amount}); - } #} } - $grantotal = sprintf("%.2f", $grantotal); + $grantotal = sprintf( "%.2f", $grantotal ); - if($output eq 'screen'){ + if ( $output eq 'screen' ) { $template->param( loopresult => \@loopresult, - total => $grantotal, + total => $grantotal, ); - } else{ - my $format = 'csv'; - my $reportname = $input->param('basename'); - my $reportfilename = $reportname ? "$reportname.$format" : "reportresults.$format" ; - my $delimiter = C4::Context->csv_delimiter; - my @rows; - foreach my $row (@loopresult) { - my @rowValues; - push @rowValues, $row->{mfirstname}. ' ' . $row->{msurname}, - $row->{cardnumber}, - $row->{bfirstname} . ' ' . $row->{bsurname}, - $row->{branchname}, - $row->{date}, - $row->{timestamp}, - $row->{type_description}, - $row->{note}, - $row->{amount}, - $row->{title}, - $row->{barcode}, - $row->{itype}; - push (@rows, \@rowValues) ; - } - my @total; - for (1..7){push(@total,"")}; - push(@total, $grantotal); + } else { + my $format = 'csv'; + my $reportname = $input->param('basename'); + my $reportfilename = $reportname ? "$reportname.$format" : "reportresults.$format"; + my $delimiter = C4::Context->csv_delimiter; + my @rows; + foreach my $row (@loopresult) { + my @rowValues; + push @rowValues, $row->{mfirstname} . ' ' . $row->{msurname}, + $row->{cardnumber}, + $row->{bfirstname} . ' ' . $row->{bsurname}, + $row->{branchname}, + $row->{date}, + $row->{timestamp}, + $row->{type_description}, + $row->{note}, + $row->{amount}, + $row->{title}, + $row->{barcode}, + $row->{itype}; + push( @rows, \@rowValues ); + } + my @total; + for ( 1 .. 7 ) { push( @total, "" ) } + push( @total, $grantotal ); print $input->header( -type => 'text/csv', - -encoding => 'utf-8', + -encoding => 'utf-8', -attachment => $reportfilename, -name => $reportfilename - ); - my $csvTemplate = C4::Templates::gettemplate('reports/csv/cash_register_stats.tt', 'intranet', $input); - $csvTemplate->param(sep => $delimiter, rows => \@rows, total => \@total ); + ); + my $csvTemplate = C4::Templates::gettemplate( 'reports/csv/cash_register_stats.tt', 'intranet', $input ); + $csvTemplate->param( sep => $delimiter, rows => \@rows, total => \@total ); print $csvTemplate->output; exit; } @@ -195,11 +196,11 @@ $template->param( beginDate => $fromDate, endDate => $toDate, transaction_type => $transaction_type, - branchloop => Koha::Libraries->search({}, { order_by => ['branchname'] })->unblessed, + branchloop => Koha::Libraries->search( {}, { order_by => ['branchname'] } )->unblessed, debit_types => \@debit_types, credit_types => \@credit_types, registerid => $registerid, - CGIsepChoice => GetDelimiterChoices, + CGIsepChoice => GetDelimiterChoices, ); output_html_with_http_headers $input, $cookie, $template->output; diff --git a/reports/cat_issues_top.pl b/reports/cat_issues_top.pl index d3d1e067b9..fe799ba917 100755 --- a/reports/cat_issues_top.pl +++ b/reports/cat_issues_top.pl @@ -1,6 +1,5 @@ #!/usr/bin/perl - # Copyright 2000-2002 Katipo Communications # # This file is part of Koha. @@ -20,10 +19,10 @@ use Modern::Perl; use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Context; -use C4::Output qw( output_html_with_http_headers ); -use C4::Koha qw( GetAuthorisedValues ); +use C4::Output qw( output_html_with_http_headers ); +use C4::Koha qw( GetAuthorisedValues ); use C4::Reports qw( GetDelimiterChoices ); use Koha::ItemTypes; @@ -35,67 +34,82 @@ plugin that shows a stats on borrowers =cut -my $input = CGI->new; -my $do_it=$input->param('do_it'); +my $input = CGI->new; +my $do_it = $input->param('do_it'); my $fullreportname = "reports/cat_issues_top.tt"; -my $limit = $input->param("Limit"); -my $column = $input->param("Criteria"); -my @filters = $input->multi_param("Filter"); +my $limit = $input->param("Limit"); +my $column = $input->param("Criteria"); +my @filters = $input->multi_param("Filter"); -my $output = $input->param("output"); +my $output = $input->param("output"); my $basename = $input->param("basename"); + #warn "calcul : ".$calc; -my ($template, $borrowernumber, $cookie) - = get_template_and_user({template_name => $fullreportname, - query => $input, - type => "intranet", - flagsrequired => { reports => '*'}, - }); -our $sep = C4::Context->csv_delimiter(scalar $input->param("sep")); -$template->param(do_it => $do_it, - ); +my ( $template, $borrowernumber, $cookie ) = get_template_and_user( + { + template_name => $fullreportname, + query => $input, + type => "intranet", + flagsrequired => { reports => '*' }, + } +); +our $sep = C4::Context->csv_delimiter( scalar $input->param("sep") ); +$template->param( + do_it => $do_it, +); if ($do_it) { -# Displaying results - my $results = calculate($limit, $column, \@filters); - if ($output eq "screen"){ -# Printing results to screen - $template->param(mainloop => $results, - limit => $limit); + + # Displaying results + my $results = calculate( $limit, $column, \@filters ); + if ( $output eq "screen" ) { + + # Printing results to screen + $template->param( + mainloop => $results, + limit => $limit + ); output_html_with_http_headers $input, $cookie, $template->output; exit; } else { -# Printing to a csv file - print $input->header(-type => 'application/vnd.sun.xml.calc', - -encoding => 'utf-8', - -attachment=>"$basename.csv", - -filename=>"$basename.csv" ); - my $cols = @$results[0]->{loopcol}; + + # Printing to a csv file + print $input->header( + -type => 'application/vnd.sun.xml.calc', + -encoding => 'utf-8', + -attachment => "$basename.csv", + -filename => "$basename.csv" + ); + my $cols = @$results[0]->{loopcol}; my $lines = @$results[0]->{looprow}; -# header top-right - print @$results[0]->{line} ."/". @$results[0]->{column} .$sep; -# Other header - foreach my $col ( @$cols ) { - print $col->{coltitle}.$sep; + + # header top-right + print @$results[0]->{line} . "/" . @$results[0]->{column} . $sep; + + # Other header + foreach my $col (@$cols) { + print $col->{coltitle} . $sep; } print "Total\n"; -# Table - foreach my $line ( @$lines ) { + + # Table + foreach my $line (@$lines) { my $x = $line->{loopcell}; - print $line->{rowtitle}.$sep; + print $line->{rowtitle} . $sep; foreach my $cell (@$x) { - print $cell->{value}.$sep; + print $cell->{value} . $sep; print $cell->{count} // ''; } print "\n"; } exit; } -# Displaying choices + + # Displaying choices } else { my $dbh = C4::Context->dbh; - - my $CGIextChoice = ( 'CSV' ); # FIXME translation - my $CGIsepChoice=GetDelimiterChoices; + + my $CGIextChoice = ('CSV'); # FIXME translation + my $CGIsepChoice = GetDelimiterChoices; #doctype my $itemtypes = Koha::ItemTypes->search_with_localization; @@ -104,126 +118,133 @@ if ($do_it) { my $ccodes = GetAuthorisedValues('CCODE'); my @ccodeloop; for my $thisccode (@$ccodes) { - my %row = (value => $thisccode->{authorised_value}, - description => $thisccode->{lib}, - ); - push @ccodeloop, \%row; + my %row = ( + value => $thisccode->{authorised_value}, + description => $thisccode->{lib}, + ); + push @ccodeloop, \%row; } - @ccodeloop = sort {$a->{value} cmp $b->{value}} @ccodeloop; + @ccodeloop = sort { $a->{value} cmp $b->{value} } @ccodeloop; #shelvingloc my $shelvinglocs = GetAuthorisedValues('LOC'); my @shelvinglocloop; for my $thisloc (@$shelvinglocs) { - my %row = (value => $thisloc->{authorised_value}, - description => $thisloc->{lib}, - ); - push @shelvinglocloop, \%row; + my %row = ( + value => $thisloc->{authorised_value}, + description => $thisloc->{lib}, + ); + push @shelvinglocloop, \%row; } - @shelvinglocloop = sort {$a->{value} cmp $b->{value}} @shelvinglocloop; + @shelvinglocloop = sort { $a->{value} cmp $b->{value} } @shelvinglocloop; - my $patron_categories = Koha::Patron::Categories->search_with_library_limits({}, {order_by => ['categorycode']}); + my $patron_categories = + Koha::Patron::Categories->search_with_library_limits( {}, { order_by => ['categorycode'] } ); $template->param( - CGIextChoice => $CGIextChoice, - CGIsepChoice => $CGIsepChoice, - itemtypes => $itemtypes, - ccodeloop =>\@ccodeloop, - shelvinglocloop =>\@shelvinglocloop, - patron_categories => $patron_categories, - ); -output_html_with_http_headers $input, $cookie, $template->output; + CGIextChoice => $CGIextChoice, + CGIsepChoice => $CGIsepChoice, + itemtypes => $itemtypes, + ccodeloop => \@ccodeloop, + shelvinglocloop => \@shelvinglocloop, + patron_categories => $patron_categories, + ); + output_html_with_http_headers $input, $cookie, $template->output; } - - - sub calculate { - my ($line, $column, $filters) = @_; + my ( $line, $column, $filters ) = @_; my @mainloop; my @loopcol; my @looprow; my %globalline; - my $grantotal =0; -# extract parameters + my $grantotal = 0; + + # extract parameters my $dbh = C4::Context->dbh; -# Filters -# Checking filters -# + # Filters + # Checking filters + # my @loopfilter; - for (my $i=0;$i<=12;$i++) { + for ( my $i = 0 ; $i <= 12 ; $i++ ) { my %cell; if ( @$filters[$i] ) { - if (($i==1) and (@$filters[$i-1])) { - $cell{err} = 1 if (@$filters[$i]<@$filters[$i-1]) ; + if ( ( $i == 1 ) and ( @$filters[ $i - 1 ] ) ) { + $cell{err} = 1 if ( @$filters[$i] < @$filters[ $i - 1 ] ); } $cell{filter} .= @$filters[$i]; - $cell{crit} .="Issue From" if ($i==0); - $cell{crit} .="Issue To" if ($i==1); - $cell{crit} .="Return From" if ($i==2); - $cell{crit} .="Return To" if ($i==3); - $cell{crit} .="Branch" if ($i==4); - $cell{crit} .="Doc Type" if ($i==5); - $cell{crit} .="Call number" if ($i==6); - $cell{crit} .="Collection code" if ($i==7); - $cell{crit} .="Shelving location" if ($i==8); - $cell{crit} .="Bor Cat" if ($i==9); - $cell{crit} .="Day" if ($i==10); - $cell{crit} .="Month" if ($i==11); - $cell{crit} .="Year" if ($i==12); + $cell{crit} .= "Issue From" if ( $i == 0 ); + $cell{crit} .= "Issue To" if ( $i == 1 ); + $cell{crit} .= "Return From" if ( $i == 2 ); + $cell{crit} .= "Return To" if ( $i == 3 ); + $cell{crit} .= "Branch" if ( $i == 4 ); + $cell{crit} .= "Doc Type" if ( $i == 5 ); + $cell{crit} .= "Call number" if ( $i == 6 ); + $cell{crit} .= "Collection code" if ( $i == 7 ); + $cell{crit} .= "Shelving location" if ( $i == 8 ); + $cell{crit} .= "Bor Cat" if ( $i == 9 ); + $cell{crit} .= "Day" if ( $i == 10 ); + $cell{crit} .= "Month" if ( $i == 11 ); + $cell{crit} .= "Year" if ( $i == 12 ); push @loopfilter, \%cell; } } my $colfield; my $colorder; - if ($column){ - $column = "old_issues.".$column if (($column=~/branchcode/) or ($column=~/issuedate/)); - if($column=~/itemtype/){ - $column = C4::Context->preference('item-level_itypes') ? "items.itype": "biblioitems.itemtype"; + if ($column) { + $column = "old_issues." . $column if ( ( $column =~ /branchcode/ ) or ( $column =~ /issuedate/ ) ); + if ( $column =~ /itemtype/ ) { + $column = C4::Context->preference('item-level_itypes') ? "items.itype" : "biblioitems.itemtype"; } - $column = "borrowers.".$column if $column=~/categorycode/; - my @colfilter ; - $colfilter[0] = @$filters[0] if ($column =~ /issuedate/ ) ; - $colfilter[1] = @$filters[1] if ($column =~ /issuedate/ ) ; - $colfilter[0] = @$filters[2] if ($column =~ /returndate/ ) ; - $colfilter[1] = @$filters[3] if ($column =~ /returndate/ ) ; - $colfilter[0] = @$filters[4] if ($column =~ /branch/ ) ; - $colfilter[0] = @$filters[5] if ($column =~ /itemtype/ ) ; - # These limits does not currently exist, maybe later? - # $colfilter[0] = @$filters[6] if ($column =~ /ccode/ ) ; - # $colfilter[0] = @$filters[7] if ($column =~ /location/ ) ; - $colfilter[0] = @$filters[8] if ($column =~ /category/ ) ; - # This commented out row (sort2) was not removed when adding new filters for ccode, shelving location and call number - # $colfilter[0] = @$filters[11] if ($column =~ /sort2/ ) ; - $colfilter[0] = @$filters[9] if ($column =~ /issuedate/ ) ; - $colfilter[0] = @$filters[10] if ($column =~ /issuedate/ ) ; - $colfilter[0] = @$filters[11] if ($column =~ /issuedate/ ) ; - #warn "filtre col ".$colfilter[0]." ".$colfilter[1]; - - # loop cols. - if ($column eq "Day") { + $column = "borrowers." . $column if $column =~ /categorycode/; + my @colfilter; + $colfilter[0] = @$filters[0] if ( $column =~ /issuedate/ ); + $colfilter[1] = @$filters[1] if ( $column =~ /issuedate/ ); + $colfilter[0] = @$filters[2] if ( $column =~ /returndate/ ); + $colfilter[1] = @$filters[3] if ( $column =~ /returndate/ ); + $colfilter[0] = @$filters[4] if ( $column =~ /branch/ ); + $colfilter[0] = @$filters[5] if ( $column =~ /itemtype/ ); + + # These limits does not currently exist, maybe later? + # $colfilter[0] = @$filters[6] if ($column =~ /ccode/ ) ; + # $colfilter[0] = @$filters[7] if ($column =~ /location/ ) ; + $colfilter[0] = @$filters[8] if ( $column =~ /category/ ); + + # This commented out row (sort2) was not removed when adding new filters for ccode, shelving location and call number + # $colfilter[0] = @$filters[11] if ($column =~ /sort2/ ) ; + $colfilter[0] = @$filters[9] if ( $column =~ /issuedate/ ); + $colfilter[0] = @$filters[10] if ( $column =~ /issuedate/ ); + $colfilter[0] = @$filters[11] if ( $column =~ /issuedate/ ); + + #warn "filtre col ".$colfilter[0]." ".$colfilter[1]; + + # loop cols. + if ( $column eq "Day" ) { + #Display by day $column = "old_issues.issuedate"; - $colfield .="dayname($column)"; - $colorder .="weekday($column)"; - } elsif ($column eq "Month") { + $colfield .= "dayname($column)"; + $colorder .= "weekday($column)"; + } elsif ( $column eq "Month" ) { + #Display by Month $column = "old_issues.issuedate"; - $colfield .="monthname($column)"; - $colorder .="month($column)"; - } elsif ($column eq "Year") { + $colfield .= "monthname($column)"; + $colorder .= "month($column)"; + } elsif ( $column eq "Year" ) { + #Display by Year $column = "old_issues.issuedate"; - $colfield .="Year($column)"; + $colfield .= "Year($column)"; $colorder .= $column; } else { $colfield .= $column; $colorder .= $column; - } - + } + my $strsth2; $strsth2 .= "SELECT distinctrow $colfield FROM `old_issues` @@ -231,59 +252,60 @@ sub calculate { LEFT JOIN items ON old_issues.itemnumber=items.itemnumber LEFT JOIN biblioitems ON biblioitems.biblioitemnumber=items.biblioitemnumber WHERE 1"; - if (($column=~/issuedate/) or ($column=~/returndate/)){ - if ($colfilter[1] and ($colfilter[0])){ - $strsth2 .= " and $column between '$colfilter[0]' and '$colfilter[1]' " ; - } elsif ($colfilter[1]) { - $strsth2 .= " and $column < '$colfilter[1]' " ; - } elsif ($colfilter[0]) { - $strsth2 .= " and $column > '$colfilter[0]' " ; + if ( ( $column =~ /issuedate/ ) or ( $column =~ /returndate/ ) ) { + if ( $colfilter[1] and ( $colfilter[0] ) ) { + $strsth2 .= " and $column between '$colfilter[0]' and '$colfilter[1]' "; + } elsif ( $colfilter[1] ) { + $strsth2 .= " and $column < '$colfilter[1]' "; + } elsif ( $colfilter[0] ) { + $strsth2 .= " and $column > '$colfilter[0]' "; } - } elsif ($colfilter[0]) { + } elsif ( $colfilter[0] ) { $colfilter[0] =~ s/\*/%/g; - $strsth2 .= " and $column LIKE '$colfilter[0]' " ; + $strsth2 .= " and $column LIKE '$colfilter[0]' "; } - $strsth2 .=" group by $colfield"; - $strsth2 .=" order by $colorder"; - - my $sth2 = $dbh->prepare( $strsth2 ); - if (( @colfilter ) and ($colfilter[1])){ - $sth2->execute("'".$colfilter[0]."'","'".$colfilter[1]."'"); - } elsif ($colfilter[0]) { - $sth2->execute($colfilter[0]); + $strsth2 .= " group by $colfield"; + $strsth2 .= " order by $colorder"; + + my $sth2 = $dbh->prepare($strsth2); + if ( (@colfilter) and ( $colfilter[1] ) ) { + $sth2->execute( "'" . $colfilter[0] . "'", "'" . $colfilter[1] . "'" ); + } elsif ( $colfilter[0] ) { + $sth2->execute( $colfilter[0] ); } else { $sth2->execute; } - - - while (my ($celvalue) = $sth2->fetchrow) { + + while ( my ($celvalue) = $sth2->fetchrow ) { my %cell; - $cell{coltitle} = ($celvalue?$celvalue:"NULL"); + $cell{coltitle} = ( $celvalue ? $celvalue : "NULL" ); push @loopcol, \%cell; } - # warn "fin des titres colonnes"; + + # warn "fin des titres colonnes"; } - - my $i=0; -# my @totalcol; - my $hilighted=-1; - + + my $i = 0; + + # my @totalcol; + my $hilighted = -1; + #Initialization of cell values..... my @table; - -# warn "init table"; - for (my $i=1;$i<=$line;$i++) { - foreach my $col ( @loopcol ) { -# warn " init table : $row->{rowtitle} / $col->{coltitle} "; - $table[$i]->{($col->{coltitle})?$col->{coltitle}:"total"}->{'name'}=0; + + # warn "init table"; + for ( my $i = 1 ; $i <= $line ; $i++ ) { + foreach my $col (@loopcol) { + + # warn " init table : $row->{rowtitle} / $col->{coltitle} "; + $table[$i]->{ ( $col->{coltitle} ) ? $col->{coltitle} : "total" }->{'name'} = 0; } } + # preparing calculation + my $strcalc; -# preparing calculation - my $strcalc ; - -# Processing average loanperiods + # Processing average loanperiods $strcalc .= "SELECT biblio.title, COUNT(biblio.biblionumber) AS `RANK`, biblio.biblionumber AS ID"; $strcalc .= " , $colfield " if ($colfield); $strcalc .= " FROM `old_issues` @@ -293,100 +315,117 @@ sub calculate { LEFT JOIN borrowers USING(borrowernumber) WHERE 1"; - @$filters[0]=~ s/\*/%/g if (@$filters[0]); - $strcalc .= " AND old_issues.issuedate > '" . @$filters[0] ."'" if ( @$filters[0] ); - @$filters[1]=~ s/\*/%/g if (@$filters[1]); - $strcalc .= " AND old_issues.issuedate < '" . @$filters[1] ."'" if ( @$filters[1] ); - @$filters[2]=~ s/\*/%/g if (@$filters[2]); - $strcalc .= " AND old_issues.returndate > '" . @$filters[2] ."'" if ( @$filters[2] ); - @$filters[3]=~ s/\*/%/g if (@$filters[3]); - $strcalc .= " AND old_issues.returndate < '" . @$filters[3] ."'" if ( @$filters[3] ); - @$filters[4]=~ s/\*/%/g if (@$filters[4]); - $strcalc .= " AND old_issues.branchcode like '" . @$filters[4] ."'" if ( @$filters[4] ); - @$filters[5]=~ s/\*/%/g if (@$filters[5]); - if ( @$filters[5] ){ - if(C4::Context->preference('item-level_itypes') ){ - $strcalc .= " AND items.itype like " - }else{ - $strcalc .= " AND biblioitems.itemtype like " - } - $strcalc .= "'" . @$filters[5] ."'" ; + @$filters[0] =~ s/\*/%/g if ( @$filters[0] ); + $strcalc .= " AND old_issues.issuedate > '" . @$filters[0] . "'" if ( @$filters[0] ); + @$filters[1] =~ s/\*/%/g if ( @$filters[1] ); + $strcalc .= " AND old_issues.issuedate < '" . @$filters[1] . "'" if ( @$filters[1] ); + @$filters[2] =~ s/\*/%/g if ( @$filters[2] ); + $strcalc .= " AND old_issues.returndate > '" . @$filters[2] . "'" if ( @$filters[2] ); + @$filters[3] =~ s/\*/%/g if ( @$filters[3] ); + $strcalc .= " AND old_issues.returndate < '" . @$filters[3] . "'" if ( @$filters[3] ); + @$filters[4] =~ s/\*/%/g if ( @$filters[4] ); + $strcalc .= " AND old_issues.branchcode like '" . @$filters[4] . "'" if ( @$filters[4] ); + @$filters[5] =~ s/\*/%/g if ( @$filters[5] ); + + if ( @$filters[5] ) { + if ( C4::Context->preference('item-level_itypes') ) { + $strcalc .= " AND items.itype like "; + } else { + $strcalc .= " AND biblioitems.itemtype like "; + } + $strcalc .= "'" . @$filters[5] . "'"; } - @$filters[6]=~ s/\*/%/g if (@$filters[6]); - $strcalc .= " AND itemcallnumber like '" . @$filters[6] ."'" if ( @$filters[6] ); - @$filters[7]=~ s/\*/%/g if (@$filters[7]); - $strcalc .= " AND ccode like '" . @$filters[7] ."'" if ( @$filters[7] ); - @$filters[8]=~ s/\*/%/g if (@$filters[8]); - $strcalc .= " AND location like '" . @$filters[8] ."'" if ( @$filters[8] ); - @$filters[9]=~ s/\*/%/g if (@$filters[9]); - $strcalc .= " AND borrowers.categorycode like '" . @$filters[9] ."'" if ( @$filters[9] ); - @$filters[10]=~ s/\*/%/g if (@$filters[10]); - $strcalc .= " AND dayname(old_issues.issuedate) like '" . @$filters[10]."'" if (@$filters[10]); - @$filters[11]=~ s/\*/%/g if (@$filters[11]); - $strcalc .= " AND monthname(old_issues.issuedate) like '" . @$filters[11]."'" if (@$filters[11]); - @$filters[12]=~ s/\*/%/g if (@$filters[12]); - $strcalc .= " AND year(old_issues.issuedate) like '" . @$filters[12] ."'" if ( @$filters[12] ); - + @$filters[6] =~ s/\*/%/g if ( @$filters[6] ); + $strcalc .= " AND itemcallnumber like '" . @$filters[6] . "'" if ( @$filters[6] ); + @$filters[7] =~ s/\*/%/g if ( @$filters[7] ); + $strcalc .= " AND ccode like '" . @$filters[7] . "'" if ( @$filters[7] ); + @$filters[8] =~ s/\*/%/g if ( @$filters[8] ); + $strcalc .= " AND location like '" . @$filters[8] . "'" if ( @$filters[8] ); + @$filters[9] =~ s/\*/%/g if ( @$filters[9] ); + $strcalc .= " AND borrowers.categorycode like '" . @$filters[9] . "'" if ( @$filters[9] ); + @$filters[10] =~ s/\*/%/g if ( @$filters[10] ); + $strcalc .= " AND dayname(old_issues.issuedate) like '" . @$filters[10] . "'" if ( @$filters[10] ); + @$filters[11] =~ s/\*/%/g if ( @$filters[11] ); + $strcalc .= " AND monthname(old_issues.issuedate) like '" . @$filters[11] . "'" if ( @$filters[11] ); + @$filters[12] =~ s/\*/%/g if ( @$filters[12] ); + $strcalc .= " AND year(old_issues.issuedate) like '" . @$filters[12] . "'" if ( @$filters[12] ); + $strcalc .= " group by biblio.biblionumber, biblio.title"; $strcalc .= ", $colfield" if ($column); $strcalc .= " order by `RANK` DESC"; $strcalc .= ", $colfield " if ($colfield); - + my $dbcalc = $dbh->prepare($strcalc); $dbcalc->execute; my %indice; - while (my @data = $dbcalc->fetchrow) { - my ($row, $rank, $id, $callnum, $ccode, $loc, $col )=@data; - $col = "zzEMPTY" if (!defined($col)); - $indice{$col}=1 if (not($indice{$col})); - $table[$indice{$col}]->{$col}->{'name'}=$row; - $table[$indice{$col}]->{$col}->{'count'}=$rank; - $table[$indice{$col}]->{$col}->{'link'}=$id; + while ( my @data = $dbcalc->fetchrow ) { + my ( $row, $rank, $id, $callnum, $ccode, $loc, $col ) = @data; + $col = "zzEMPTY" if ( !defined($col) ); + $indice{$col} = 1 if ( not( $indice{$col} ) ); + $table[ $indice{$col} ]->{$col}->{'name'} = $row; + $table[ $indice{$col} ]->{$col}->{'count'} = $rank; + $table[ $indice{$col} ]->{$col}->{'link'} = $id; $indice{$col}++; } - - push @loopcol,{coltitle => "Global"} if not($column); - - for ($i=1; $i<=$line;$i++) { + + push @loopcol, { coltitle => "Global" } if not($column); + + for ( $i = 1 ; $i <= $line ; $i++ ) { my @loopcell; + #@loopcol ensures the order for columns is common with column titles # and the number matches the number of columns - my $colcount=0; - foreach my $col ( @loopcol ) { + my $colcount = 0; + foreach my $col (@loopcol) { my $value; - my $count=0; + my $count = 0; my $link; - if (@loopcol){ - $value =$table[$i]->{(($col->{coltitle} eq "NULL") or ($col->{coltitle} eq "Global"))?"zzEMPTY":$col->{coltitle}}->{'name'}; - $count =$table[$i]->{(($col->{coltitle} eq "NULL") or ($col->{coltitle} eq "Global"))?"zzEMPTY":$col->{coltitle}}->{'count'}; - $link =$table[$i]->{(($col->{coltitle} eq "NULL") or ($col->{coltitle} eq "Global"))?"zzEMPTY":$col->{coltitle}}->{'link'}; + if (@loopcol) { + $value = $table[$i]->{ + ( ( $col->{coltitle} eq "NULL" ) or ( $col->{coltitle} eq "Global" ) ) + ? "zzEMPTY" + : $col->{coltitle} + }->{'name'}; + $count = $table[$i]->{ + ( ( $col->{coltitle} eq "NULL" ) or ( $col->{coltitle} eq "Global" ) ) + ? "zzEMPTY" + : $col->{coltitle} + }->{'count'}; + $link = $table[$i]->{ + ( ( $col->{coltitle} eq "NULL" ) or ( $col->{coltitle} eq "Global" ) ) + ? "zzEMPTY" + : $col->{coltitle} + }->{'link'}; } else { - $value =$table[$i]->{"zzEMPTY"}->{'name'}; - $count =$table[$i]->{"zzEMPTY"}->{'count'}; - $link =$table[$i]->{"zzEMPTY"}->{'link'}; + $value = $table[$i]->{"zzEMPTY"}->{'name'}; + $count = $table[$i]->{"zzEMPTY"}->{'count'}; + $link = $table[$i]->{"zzEMPTY"}->{'link'}; } - push @loopcell, {value => $value, count =>$count, reference => $link} ; + push @loopcell, { value => $value, count => $count, reference => $link }; } + #my $total = $table[$i]->{totalrow}/$colcount if ($colcount>0); - push @looprow,{ 'rowtitle' => $i , - 'loopcell' => \@loopcell, - 'hilighted' => ($hilighted >0), - }; + push @looprow, { + 'rowtitle' => $i, + 'loopcell' => \@loopcell, + 'hilighted' => ( $hilighted > 0 ), + }; $hilighted = -$hilighted; } -# - + # # the header of the table - $globalline{loopfilter}=\@loopfilter; + $globalline{loopfilter} = \@loopfilter; + # the core of the table $globalline{looprow} = \@looprow; $globalline{loopcol} = \@loopcol; -# # the foot (totals by borrower type) - $globalline{total}= $grantotal; - $globalline{line} = $line; + + # # the foot (totals by borrower type) + $globalline{total} = $grantotal; + $globalline{line} = $line; $globalline{column} = $column; - push @mainloop,\%globalline; + push @mainloop, \%globalline; return \@mainloop; } diff --git a/reports/catalog_by_itemtype.pl b/reports/catalog_by_itemtype.pl index fcaf5f17ef..912209cf62 100755 --- a/reports/catalog_by_itemtype.pl +++ b/reports/catalog_by_itemtype.pl @@ -19,7 +19,7 @@ use Modern::Perl; use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Context; use C4::Output qw( output_html_with_http_headers ); diff --git a/reports/catalogue_out.pl b/reports/catalogue_out.pl index c03dcb2d80..9cc540b858 100755 --- a/reports/catalogue_out.pl +++ b/reports/catalogue_out.pl @@ -23,6 +23,7 @@ use CGI qw ( -utf8 ); use C4::Auth qw( get_template_and_user ); use C4::Context; use C4::Output qw( output_html_with_http_headers ); + # use Date::Manip; # TODO: add not borrowed since date X criteria =head1 catalogue_out @@ -39,10 +40,10 @@ my @filters = $input->multi_param("Filter"); my ( $template, $borrowernumber, $cookie ) = get_template_and_user( { - template_name => "reports/catalogue_out.tt", - query => $input, - type => "intranet", - flagsrequired => { reports => 'execute_reports' }, + template_name => "reports/catalogue_out.tt", + query => $input, + type => "intranet", + flagsrequired => { reports => 'execute_reports' }, } ); @@ -76,8 +77,8 @@ sub calculate { if ( ( $i == 1 ) and ( @$filters[ $i - 1 ] ) ) { $cell{err} = 1 if ( @$filters[$i] < @$filters[ $i - 1 ] ); } - $cell{crit} = "homelibrary" if ( $i == 0 ); - $cell{crit} = "itemtype" if ( $i == 1 ); + $cell{crit} = "homelibrary" if ( $i == 0 ); + $cell{crit} = "itemtype" if ( $i == 1 ); push @loopfilter, \%cell; } } @@ -86,13 +87,13 @@ sub calculate { push @loopfilter, { crit => 'by', filter => $column }; my $tablename = ( $column =~ /branchcode/ ) ? 'branches' : 'items'; $column = - ( $column =~ /branchcode/ or $column =~ /itype/ ) - ? "$tablename.$column" - : $column; + ( $column =~ /branchcode/ or $column =~ /itype/ ) + ? "$tablename.$column" + : $column; my $strsth2 = - ( $tablename eq 'branches' ) - ? "SELECT $column as coltitle, count(items.itemnumber) AS coltitle_count FROM $tablename LEFT JOIN items ON items.homebranch=$column " - : "SELECT $column as coltitle, count(*) AS coltitle_count FROM $tablename "; + ( $tablename eq 'branches' ) + ? "SELECT $column as coltitle, count(items.itemnumber) AS coltitle_count FROM $tablename LEFT JOIN items ON items.homebranch=$column " + : "SELECT $column as coltitle, count(*) AS coltitle_count FROM $tablename "; if ( $tablename eq 'branches' ) { my $f = @$filters[0]; $f =~ s/\*/%/g; @@ -141,9 +142,9 @@ sub calculate { } if ($column) { $query .= " AND $column = ? GROUP BY items.itemnumber, $column "; + # placeholder handled below - } - else { + } else { $query .= " GROUP BY items.itemnumber "; } $query .= " ORDER BY items.itemcallnumber DESC, barcode"; @@ -154,20 +155,20 @@ sub calculate { if ($column) { foreach ( sort keys %columns ) { + # execute(@exe_args,$_) would fail when the array is empty # but @more_exe_args will work my (@more_exe_args) = @exe_args; push @more_exe_args, $_; $dbcalc->execute(@more_exe_args) - or die "Query execute(@more_exe_args) failed: $query"; + or die "Query execute(@more_exe_args) failed: $query"; while ( my $data = $dbcalc->fetchrow_hashref ) { my $col = $data->{col} || 'NULL'; $tables{$col} or $tables{$col} = []; push @{ $tables{$col} }, $data; } } - } - else { + } else { ( scalar @exe_args ) ? $dbcalc->execute(@exe_args) : $dbcalc->execute; while ( my $data = $dbcalc->fetchrow_hashref ) { my $col = $data->{col} || 'NULL'; @@ -187,14 +188,14 @@ sub calculate { $globalline{total_looptable_count} += $count; $globalline{total_coltitle_count} += $allitems; push @{ $globalline{looptables} }, - { + { looprow => \@temptable, coltitle => $tablename, coltitle_count => $allitems, looptable_count => $count, - looptable_first => ($count) ? $temptable[0]->{itemcallnumber} : '', + looptable_first => ($count) ? $temptable[0]->{itemcallnumber} : '', looptable_last => ($count) ? $temptable[-1]->{itemcallnumber} : '', - }; + }; } # the header of the table diff --git a/reports/catalogue_stats.pl b/reports/catalogue_stats.pl index dd9a773d42..aa19964766 100755 --- a/reports/catalogue_stats.pl +++ b/reports/catalogue_stats.pl @@ -1,6 +1,5 @@ #!/usr/bin/perl - # Copyright 2000-2002 Katipo Communications # # This file is part of Koha. @@ -20,12 +19,12 @@ use Modern::Perl; use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Context; -use C4::Output qw( output_html_with_http_headers ); -use C4::Koha qw( GetAuthorisedValues ); +use C4::Output qw( output_html_with_http_headers ); +use C4::Koha qw( GetAuthorisedValues ); use C4::Reports qw( GetDelimiterChoices ); -use C4::Biblio qw( GetMarcSubfieldStructureFromKohaField ); +use C4::Biblio qw( GetMarcSubfieldStructureFromKohaField ); use Koha::AuthorisedValues; use Koha::DateUtils qw( dt_from_string ); @@ -40,37 +39,40 @@ plugin that shows a stats on borrowers =cut our $debug = 0; -my $input = CGI->new; +my $input = CGI->new; my $fullreportname = "reports/catalogue_stats.tt"; -my $do_it = $input->param('do_it'); -my $line = $input->param("Line"); -my $column = $input->param("Column"); -my $cellvalue = $input->param("Cellvalue"); # one of 'items', 'biblios', 'deleteditems' -my @filters = $input->multi_param("Filter"); -my $cotedigits = $input->param("cotedigits"); -my $output = $input->param("output"); -my $basename = $input->param("basename"); -our $sep = C4::Context->csv_delimiter(scalar $input->param("sep")); +my $do_it = $input->param('do_it'); +my $line = $input->param("Line"); +my $column = $input->param("Column"); +my $cellvalue = $input->param("Cellvalue"); # one of 'items', 'biblios', 'deleteditems' +my @filters = $input->multi_param("Filter"); +my $cotedigits = $input->param("cotedigits"); +my $output = $input->param("output"); +my $basename = $input->param("basename"); +our $sep = C4::Context->csv_delimiter( scalar $input->param("sep") ); my $item_itype; -if(C4::Context->preference('item-level_itypes')) { - $item_itype = "items\.itype" + +if ( C4::Context->preference('item-level_itypes') ) { + $item_itype = "items\.itype"; } else { - $item_itype = "itemtype"; + $item_itype = "itemtype"; } -if(C4::Context->preference('marcflavour') ne "UNIMARC" && ($line=~ /publicationyear/ )) { +if ( C4::Context->preference('marcflavour') ne "UNIMARC" && ( $line =~ /publicationyear/ ) ) { $line = "copyrightdate"; } -if(C4::Context->preference('marcflavour') ne "UNIMARC" && ($column =~ /publicationyear/ )) { +if ( C4::Context->preference('marcflavour') ne "UNIMARC" && ( $column =~ /publicationyear/ ) ) { $column = "copyrightdate"; } -my ($template, $borrowernumber, $cookie) - = get_template_and_user({template_name => $fullreportname, - query => $input, - type => "intranet", - flagsrequired => {reports => '*'}, - }); -$template->param(do_it => $do_it); +my ( $template, $borrowernumber, $cookie ) = get_template_and_user( + { + template_name => $fullreportname, + query => $input, + type => "intranet", + flagsrequired => { reports => '*' }, + } +); +$template->param( do_it => $do_it ); if ($do_it) { my $results = calculate( $line, $column, $cellvalue, $cotedigits, \@filters ); if ( $output eq "screen" ) { @@ -109,33 +111,43 @@ if ($do_it) { exit; } } else { - my $dbh = C4::Context->dbh; - my $count=0; + my $dbh = C4::Context->dbh; + my $count = 0; my $itemtypes = Koha::ItemTypes->search_with_localization; - my @authvals = map { { code => $_->{authorised_value}, description => $_->{lib} } } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.ccode' }, { order_by => ['description'] } ); - my @locations = map { { code => $_->{authorised_value}, description => $_->{lib} } } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.location' }, { order_by => ['description'] } ); + my @authvals = + map { { code => $_->{authorised_value}, description => $_->{lib} } } + Koha::AuthorisedValues->get_descriptions_by_koha_field( + { frameworkcode => '', kohafield => 'items.ccode' }, + { order_by => ['description'] } + ); + my @locations = + map { { code => $_->{authorised_value}, description => $_->{lib} } } + Koha::AuthorisedValues->get_descriptions_by_koha_field( + { frameworkcode => '', kohafield => 'items.location' }, + { order_by => ['description'] } + ); foreach my $kohafield (qw(items.notforloan items.materials)) { my $subfield_structure = GetMarcSubfieldStructureFromKohaField($kohafield)->[0]; # assuming one result.. - if($subfield_structure) { + if ($subfield_structure) { my $avlist; my $avcategory = $subfield_structure->{authorised_value}; - if($avcategory) { + if ($avcategory) { $avlist = GetAuthorisedValues($avcategory); } my $kf = $kohafield; $kf =~ s/^items\.//; $template->param( - $kf => 1, - $kf."_label" => $subfield_structure->{liblibrarian}, - $kf."_avlist" => $avlist + $kf => 1, + $kf . "_label" => $subfield_structure->{liblibrarian}, + $kf . "_avlist" => $avlist ); } } - my @mime = ( map { +{type =>$_} } (split /[;:]/, 'CSV') ); # FIXME translation + my @mime = ( map { +{ type => $_ } } ( split /[;:]/, 'CSV' ) ); # FIXME translation $template->param( itemtypes => $itemtypes, @@ -151,7 +163,6 @@ output_html_with_http_headers $input, $cookie, $template->output; ## End of Main Body - sub calculate { my ( $line, $column, $cellvalue, $cotedigits, $filters ) = @_; my @mainloop; @@ -164,7 +175,7 @@ sub calculate { my $barcodelike = @$filters[16]; my $barcodefilter = @$filters[17]; my $not; - my $itemstable = ($cellvalue eq 'deleteditems') ? 'deleteditems' : 'items'; + my $itemstable = ( $cellvalue eq 'deleteditems' ) ? 'deleteditems' : 'items'; my $dbh = C4::Context->dbh; @@ -192,33 +203,33 @@ sub calculate { } $cell{filter} .= @$filters[$i]; $cell{crit} .= - ( $i == 0 ) ? "Item CallNumber From" - : ( $i == 1 ) ? "Item CallNumber To" - : ( $i == 2 ) ? "Item type" - : ( $i == 3 ) ? "Publisher" - : ( $i == 4 ) ? "Publication year From" - : ( $i == 5 ) ? "Publication year To" - : ( $i == 6 ) ? "Library" - : ( $i == 7 ) ? "Shelving Location" - : ( $i == 8 ) ? "Collection Code" - : ( $i == 9 ) ? "Status" - : ( $i == 10 ) ? "Materials" - : ( $i == 12 and $filters->[11] == 0 ) ? "Barcode (not like)" - : ( $i == 12 and $filters->[11] == 1 ) ? "Barcode (like)" - : ( $i == 13 ) ? "Date acquired (item) from" - : ( $i == 14 ) ? "Date acquired (item) to" - : ( $i == 15 ) ? "Date deleted (item) from" - : ( $i == 16 ) ? "Date deleted (item) to" - : ''; + ( $i == 0 ) ? "Item CallNumber From" + : ( $i == 1 ) ? "Item CallNumber To" + : ( $i == 2 ) ? "Item type" + : ( $i == 3 ) ? "Publisher" + : ( $i == 4 ) ? "Publication year From" + : ( $i == 5 ) ? "Publication year To" + : ( $i == 6 ) ? "Library" + : ( $i == 7 ) ? "Shelving Location" + : ( $i == 8 ) ? "Collection Code" + : ( $i == 9 ) ? "Status" + : ( $i == 10 ) ? "Materials" + : ( $i == 12 and $filters->[11] == 0 ) ? "Barcode (not like)" + : ( $i == 12 and $filters->[11] == 1 ) ? "Barcode (like)" + : ( $i == 13 ) ? "Date acquired (item) from" + : ( $i == 14 ) ? "Date acquired (item) to" + : ( $i == 15 ) ? "Date deleted (item) from" + : ( $i == 16 ) ? "Date deleted (item) to" + : ''; push @loopfilter, \%cell; } } - @$filters[13] = dt_from_string(@$filters[13])->date() if @$filters[13]; - @$filters[14] = dt_from_string(@$filters[14])->date() if @$filters[14]; - @$filters[15] = dt_from_string(@$filters[15])->date() if @$filters[15]; - @$filters[16] = dt_from_string(@$filters[16])->date() if @$filters[16]; + @$filters[13] = dt_from_string( @$filters[13] )->date() if @$filters[13]; + @$filters[14] = dt_from_string( @$filters[14] )->date() if @$filters[14]; + @$filters[15] = dt_from_string( @$filters[15] )->date() if @$filters[15]; + @$filters[16] = dt_from_string( @$filters[16] )->date() if @$filters[16]; my @linefilter; $linefilter[0] = @$filters[0] if ( $line =~ /items\.itemcallnumber/ ); @@ -232,10 +243,10 @@ sub calculate { $linefilter[0] = @$filters[4] if ( $line =~ /publicationyear/ ); $linefilter[1] = @$filters[5] if ( $line =~ /publicationyear/ ); - $linefilter[0] = @$filters[6] if ( $line =~ /items\.homebranch/ ); - $linefilter[0] = @$filters[7] if ( $line =~ /items\.location/ ); - $linefilter[0] = @$filters[8] if ( $line =~ /items\.ccode/ ); - $linefilter[0] = @$filters[9] if ( $line =~ /items\.notforloan/ ); + $linefilter[0] = @$filters[6] if ( $line =~ /items\.homebranch/ ); + $linefilter[0] = @$filters[7] if ( $line =~ /items\.location/ ); + $linefilter[0] = @$filters[8] if ( $line =~ /items\.ccode/ ); + $linefilter[0] = @$filters[9] if ( $line =~ /items\.notforloan/ ); $linefilter[0] = @$filters[10] if ( $line =~ /items\.materials/ ); $linefilter[0] = @$filters[13] if ( $line =~ /items\.dateaccessioned/ ); $linefilter[1] = @$filters[14] if ( $line =~ /items\.dateaccessioned/ ); @@ -253,10 +264,10 @@ sub calculate { $colfilter[0] = @$filters[3] if ( $column =~ /publishercode/ ); $colfilter[0] = @$filters[4] if ( $column =~ /publicationyear/ ); $colfilter[1] = @$filters[5] if ( $column =~ /publicationyear/ ); - $colfilter[0] = @$filters[6] if ( $column =~ /items\.homebranch/ ); - $colfilter[0] = @$filters[7] if ( $column =~ /items\.location/ ); - $colfilter[0] = @$filters[8] if ( $column =~ /items\.ccode/ ); - $colfilter[0] = @$filters[9] if ( $column =~ /items\.notforloan/ ); + $colfilter[0] = @$filters[6] if ( $column =~ /items\.homebranch/ ); + $colfilter[0] = @$filters[7] if ( $column =~ /items\.location/ ); + $colfilter[0] = @$filters[8] if ( $column =~ /items\.ccode/ ); + $colfilter[0] = @$filters[9] if ( $column =~ /items\.notforloan/ ); $colfilter[0] = @$filters[10] if ( $column =~ /items\.materials/ ); $colfilter[0] = @$filters[13] if ( $column =~ /items.dateaccessioned/ ); $colfilter[1] = @$filters[14] if ( $column =~ /items\.dateaccessioned/ ); @@ -265,7 +276,7 @@ sub calculate { # 1st, loop rows. my $origline = $line; - $line =~ s/^items\./deleteditems./ if($cellvalue eq "deleteditems"); + $line =~ s/^items\./deleteditems./ if ( $cellvalue eq "deleteditems" ); my $linefield; if ( ( $line =~ /itemcallnumber/ ) and ($cotedigits) ) { $linefield = "left($line,$cotedigits)"; @@ -300,26 +311,26 @@ sub calculate { } elsif ( $barcodefilter and $linefilter[0] ) { $sth->execute( $barcodefilter, $linefilter[0] ); } elsif ( $linefilter[0] ) { - $sth->execute($linefilter[0]); + $sth->execute( $linefilter[0] ); } elsif ($barcodefilter) { $sth->execute($barcodefilter); } else { $sth->execute(); } - my $rowauthvals = { map { $_->{authorised_value} => $_->{lib} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => $origline } ) }; + my $rowauthvals = { map { $_->{authorised_value} => $_->{lib} } + Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => $origline } ) }; while ( my ($celvalue) = $sth->fetchrow ) { my %cell; - if (defined $celvalue and $celvalue ne '') { - if($rowauthvals and $rowauthvals->{$celvalue}) { + if ( defined $celvalue and $celvalue ne '' ) { + if ( $rowauthvals and $rowauthvals->{$celvalue} ) { $cell{rowtitle} = $rowauthvals->{$celvalue}; } else { $cell{rowtitle} = $celvalue; } $cell{value} = $celvalue; - } - else { + } else { $cell{rowtitle} = "NULL"; - $cell{value} = "zzEMPTY"; + $cell{value} = "zzEMPTY"; } $cell{totalrow} = 0; push @loopline, \%cell; @@ -327,7 +338,7 @@ sub calculate { # 2nd, loop cols. my $origcolumn = $column; - $column =~ s/^items\./deleteditems./ if($cellvalue eq "deleteditems"); + $column =~ s/^items\./deleteditems./ if ( $cellvalue eq "deleteditems" ); my $colfield; if ( ( $column =~ /itemcallnumber/ ) and ($cotedigits) ) { $colfield = "left($column,$cotedigits)"; @@ -361,34 +372,36 @@ sub calculate { } elsif ( (@colfilter) and ( $colfilter[1] ) ) { $sth2->execute( $colfilter[0], $colfilter[1] ); } elsif ( $barcodefilter && $colfilter[0] ) { - $sth2->execute( $barcodefilter , $colfilter[0] ); - } elsif ( $colfilter[0]) { + $sth2->execute( $barcodefilter, $colfilter[0] ); + } elsif ( $colfilter[0] ) { $sth2->execute( $colfilter[0] ); } elsif ($barcodefilter) { $sth2->execute($barcodefilter); } else { $sth2->execute(); } - my $colauthvals = { map { $_->{authorised_value} => $_->{lib} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => $origcolumn } ) }; + my $colauthvals = + { map { $_->{authorised_value} => $_->{lib} } + Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => $origcolumn } ) + }; while ( my ($celvalue) = $sth2->fetchrow ) { my %cell; - if (defined $celvalue and $celvalue ne '') { - if($colauthvals and $colauthvals->{$celvalue}) { + if ( defined $celvalue and $celvalue ne '' ) { + if ( $colauthvals and $colauthvals->{$celvalue} ) { $cell{coltitle} = $colauthvals->{$celvalue}; } else { $cell{coltitle} = $celvalue; } $cell{value} = $celvalue; - } - else { + } else { $cell{coltitle} = "NULL"; - $cell{value} = "zzEMPTY"; + $cell{value} = "zzEMPTY"; } $cell{totalcol} = 0; push @loopcol, \%cell; } - my $i = 0; + my $i = 0; my $hilighted = -1; #Initialization of cell values..... @@ -403,7 +416,7 @@ sub calculate { # preparing calculation my $select_cellvalue = " COUNT(*) "; - $select_cellvalue = " COUNT(DISTINCT biblioitems.biblionumber) " if($cellvalue eq 'biblios'); + $select_cellvalue = " COUNT(DISTINCT biblioitems.biblionumber) " if ( $cellvalue eq 'biblios' ); my $strcalc = " SELECT $linefield, $colfield, $select_cellvalue FROM $itemstable @@ -431,7 +444,9 @@ sub calculate { } if ( @$filters[2] ) { - $strcalc .= " AND " . ( C4::Context->preference('item-level_itypes') ? "$itemstable.itype" : 'biblioitems.itemtype' ) . " LIKE ? "; + $strcalc .= " AND " + . ( C4::Context->preference('item-level_itypes') ? "$itemstable.itype" : 'biblioitems.itemtype' ) + . " LIKE ? "; @$filters[2] =~ s/\*/%/g; push @sqlargs, @$filters[2]; } @@ -443,17 +458,15 @@ sub calculate { push @sqlargs, @$filters[3]; } if ( @$filters[4] ) { - $strcalc .= " AND " . - (C4::Context->preference('marcflavour') eq 'UNIMARC' ? 'publicationyear' : 'copyrightdate') - . "> ? "; + $strcalc .= " AND " + . ( C4::Context->preference('marcflavour') eq 'UNIMARC' ? 'publicationyear' : 'copyrightdate' ) . "> ? "; @$filters[4] =~ s/\*/%/g; push @sqlargs, @$filters[4]; } if ( @$filters[5] ) { @$filters[5] =~ s/\*/%/g; - $strcalc .= " AND " . - (C4::Context->preference('marcflavour') eq 'UNIMARC' ? 'publicationyear' : 'copyrightdate') - . "< ? "; + $strcalc .= " AND " + . ( C4::Context->preference('marcflavour') eq 'UNIMARC' ? 'publicationyear' : 'copyrightdate' ) . "< ? "; push @sqlargs, @$filters[5]; } if ( @$filters[6] ) { @@ -508,30 +521,31 @@ sub calculate { while ( my ( $row, $col, $value ) = $dbcalc->fetchrow ) { - $col = "zzEMPTY" if ( !defined($col) ); - $row = "zzEMPTY" if ( !defined($row) ); + $col = "zzEMPTY" if ( !defined($col) ); + $row = "zzEMPTY" if ( !defined($row) ); $table{$row}->{$col} += $value; $table{$row}->{totalrow} += $value; $grantotal += $value; } - foreach my $row ( @loopline ) { + foreach my $row (@loopline) { my @loopcell; #@loopcol ensures the order for columns is common with column titles # and the number matches the number of columns foreach my $col (@loopcol) { - my $value = $table{$row->{value}}->{ $col->{value} }; + my $value = $table{ $row->{value} }->{ $col->{value} }; push @loopcell, { value => $value }; } push @looprow, - { 'rowtitle' => $row->{rowtitle}, - 'value' => $row->{value}, - 'loopcell' => \@loopcell, + { + 'rowtitle' => $row->{rowtitle}, + 'value' => $row->{value}, + 'loopcell' => \@loopcell, 'hilighted' => ( $hilighted *= -1 > 0 ), - 'totalrow' => $table{$row->{value}}->{totalrow} - }; + 'totalrow' => $table{ $row->{value} }->{totalrow} + }; } foreach my $col (@loopcol) { diff --git a/reports/dictionary.pl b/reports/dictionary.pl index c187282088..1446c0718a 100755 --- a/reports/dictionary.pl +++ b/reports/dictionary.pl @@ -17,10 +17,11 @@ # You should have received a copy of the GNU General Public License # along with Koha; if not, see . use Modern::Perl; -use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); use C4::Output qw( output_html_with_http_headers ); -use C4::Reports::Guided qw( get_from_dictionary get_columns get_column_type get_distinct_values save_dictionary delete_definition get_report_areas ); +use C4::Reports::Guided + qw( get_from_dictionary get_columns get_column_type get_distinct_values save_dictionary delete_definition get_report_areas ); use Koha::DateUtils qw( dt_from_string output_pref ); =head1 NAME @@ -31,13 +32,13 @@ Script to control the guided report creation =cut -my $input = CGI->new; +my $input = CGI->new; my $referer = $input->referer(); -my $op = $input->param('op') || q{list}; +my $op = $input->param('op') || q{list}; my $definition_name = $input->param('definition_name'); my $definition_description = $input->param('definition_description'); -my $area = $input->param('area') || ''; +my $area = $input->param('area') || ''; my ( $template, $borrowernumber, $cookie ) = get_template_and_user( { template_name => "reports/dictionary.tt", @@ -51,20 +52,18 @@ if ( $op eq 'add_form' ) { # display form allowing them to add a new definition $template->param( 'new_dictionary' => 1, ); -} -elsif ( $op eq 'cud-add_form_2' ) { +} elsif ( $op eq 'cud-add_form_2' ) { # Choosing the area $template->param( 'step_2' => 1, - 'areas' => areas( $area ), + 'areas' => areas($area), 'definition_name' => $definition_name, 'definition_description' => $definition_description, ); -} -elsif ( $op eq 'cud-add_form_3' ) { +} elsif ( $op eq 'cud-add_form_3' ) { # Choosing the columns $template->param( @@ -74,13 +73,12 @@ elsif ( $op eq 'cud-add_form_3' ) { 'definition_name' => $definition_name, 'definition_description' => $definition_description, ); -} -elsif ( $op eq 'cud-add_form_4' ) { +} elsif ( $op eq 'cud-add_form_4' ) { # Choosing the values - my @columns = $input->multi_param('columns'); - my $columnstring = join( ',', @columns ); + my @columns = $input->multi_param('columns'); + my $columnstring = join( ',', @columns ); my @column_loop; foreach my $column (@columns) { my %tmp_hash; @@ -95,7 +93,7 @@ elsif ( $op eq 'cud-add_form_4' ) { if ( $type eq 'DATE' || $type eq 'DATETIME' ) { $tmp_hash{'date'} = 1; } - if ($type eq 'TEXT' || $type eq 'MEDIUMTEXT'){ + if ( $type eq 'TEXT' || $type eq 'MEDIUMTEXT' ) { $tmp_hash{'text'} = 1; } @@ -105,19 +103,20 @@ elsif ( $op eq 'cud-add_form_4' ) { push @column_loop, \%tmp_hash; } - $template->param( 'step_4' => 1, - 'area' => $area, - 'definition_name' => $definition_name, - 'definition_description' => $definition_description, - 'columns' => \@column_loop, - 'columnstring' => $columnstring, - ); -} + $template->param( + 'step_4' => 1, + 'area' => $area, + 'definition_name' => $definition_name, + 'definition_description' => $definition_description, + 'columns' => \@column_loop, + 'columnstring' => $columnstring, + ); + +} elsif ( $op eq 'cud-add_form_5' ) { -elsif ( $op eq 'cud-add_form_5' ) { # Confirmation screen - my $columnstring = $input->param('columnstring'); - my @criteria = $input->multi_param('criteria_column'); + my $columnstring = $input->param('columnstring'); + my @criteria = $input->multi_param('criteria_column'); my $query_criteria; my @criteria_loop; @@ -152,6 +151,7 @@ elsif ( $op eq 'cud-add_form_5' ) { $query_criteria .= " AND $crit <= '$value'"; } } + # else we want all dates } } @@ -164,12 +164,12 @@ elsif ( $op eq 'cud-add_form_5' ) { 'columnstring' => $columnstring, 'criteria_loop' => \@criteria_loop, ); -} -elsif ( $op eq 'cud-add_form_6' ) { +} elsif ( $op eq 'cud-add_form_6' ) { + # Saving - my $area = $input->param('area'); - my $sql = $input->param('sql'); + my $area = $input->param('area'); + my $sql = $input->param('sql'); save_dictionary( $definition_name, $definition_description, $sql, $area ); $op = "list"; @@ -179,11 +179,12 @@ elsif ( $op eq 'cud-add_form_6' ) { $op = "list"; } -if ($op eq 'list'){ +if ( $op eq 'list' ) { + # view the dictionary we use to set up abstract variables such as all borrowers over fifty who live in a certain town my $definitions = get_from_dictionary($area); $template->param( - 'areas' => areas( $area ), + 'areas' => areas($area), 'start_dictionary' => 1, 'definitions' => $definitions, ); @@ -191,7 +192,6 @@ if ($op eq 'list'){ $template->param( 'referer' => $referer ); - output_html_with_http_headers $input, $cookie, $template->output; sub areas { @@ -200,7 +200,7 @@ sub areas { my $areas = get_report_areas(); my @a; - foreach my $area ( @$areas ) { + foreach my $area (@$areas) { push @a, { id => $area, selected => ( $area eq $selected ) diff --git a/reports/guided_reports.pl b/reports/guided_reports.pl index 2c9c176c65..70196334d9 100755 --- a/reports/guided_reports.pl +++ b/reports/guided_reports.pl @@ -23,9 +23,10 @@ use Text::CSV::Encoded; use Encode qw( decode ); use URI::Escape; use File::Temp; -use C4::Reports::Guided qw( delete_report get_report_areas convert_sql update_sql get_saved_reports get_results ValidateSQLParameters format_results get_report_types get_columns get_from_dictionary get_criteria build_query save_report execute_query nb_rows get_report_groups ); +use C4::Reports::Guided + qw( delete_report get_report_areas convert_sql update_sql get_saved_reports get_results ValidateSQLParameters format_results get_report_types get_columns get_from_dictionary get_criteria build_query save_report execute_query nb_rows get_report_groups ); use Koha::Reports; -use C4::Auth qw( get_template_and_user get_session ); +use C4::Auth qw( get_template_and_user get_session ); use C4::Output qw( pagination_bar output_html_with_http_headers ); use C4::Context; use Koha::Caches; @@ -39,7 +40,7 @@ use Koha::SharedContent; use Koha::Util::OpenDocument qw( generate_ods ); use Koha::Notice::Templates; use Koha::TemplateUtils qw( process_tt ); -use C4::ClassSource qw( GetClassSources ); +use C4::ClassSource qw( GetClassSources ); use C4::Scrubber; =head1 NAME @@ -52,35 +53,35 @@ Script to control the guided report creation =cut -my $input = CGI->new; +my $input = CGI->new; my $usecache = Koha::Caches->get_instance->memcached_cache; my $op = $input->param('op') // ''; my $flagsrequired; -if ( ( $op eq 'add_form' ) || ( $op eq 'add_form_sql' ) || ( $op eq 'edit_form' ) - || ( $op eq 'duplicate' ) ) { +if ( ( $op eq 'add_form' ) + || ( $op eq 'add_form_sql' ) + || ( $op eq 'edit_form' ) + || ( $op eq 'duplicate' ) ) +{ $flagsrequired = 'create_reports'; -} -elsif ( $op eq 'list' ) { +} elsif ( $op eq 'list' ) { $flagsrequired = 'execute_reports'; -} -elsif ( $op eq 'delete' ) { +} elsif ( $op eq 'delete' ) { $flagsrequired = 'delete_reports'; -} -else { +} else { $flagsrequired = '*'; } my ( $template, $borrowernumber, $cookie ) = get_template_and_user( { - template_name => "reports/guided_reports_start.tt", - query => $input, - type => "intranet", - flagsrequired => { reports => $flagsrequired }, + template_name => "reports/guided_reports_start.tt", + query => $input, + type => "intranet", + flagsrequired => { reports => $flagsrequired }, } ); my $session_id = $input->cookie('CGISESSID'); -my $session = $session_id ? get_session($session_id) : undef; +my $session = $session_id ? get_session($session_id) : undef; $template->param( templates => Koha::Notice::Templates->search( { module => 'report' } ) ); @@ -88,19 +89,19 @@ my $filter; if ( $input->param("filter_set") or $input->param('clear_filters') ) { $filter = {}; $filter->{$_} = $input->param("filter_$_") foreach qw/date author keyword group subgroup/; - $session->param('report_filter', $filter) if $session; + $session->param( 'report_filter', $filter ) if $session; $template->param( 'filter_set' => 1 ); -} -elsif ($session and not $input->param('clear_filters')) { +} elsif ( $session and not $input->param('clear_filters') ) { $filter = $session->param('report_filter'); } my @errors = (); if ( !$op ) { $template->param( 'start' => 1 ); + # show welcome page -} -elsif ( $op eq 'add_form' ) { +} elsif ( $op eq 'add_form' ) { + # build a new report $template->param( 'build1' => 1 ); $template->param( @@ -109,89 +110,86 @@ elsif ( $op eq 'add_form' ) { 'cache_expiry' => 300, 'public' => '0', ); -} -elsif ( $op eq 'cud-delete') { +} elsif ( $op eq 'cud-delete' ) { my @ids = $input->multi_param('id'); - delete_report( @ids ); + delete_report(@ids); $op = 'list'; -} -elsif ( $op eq 'show'){ +} elsif ( $op eq 'show' ) { - my $id = $input->param('id'); + my $id = $input->param('id'); my $report = Koha::Reports->find($id); $template->param( - 'id' => $id, - 'reportname' => $report->report_name, - 'notes' => $report->notes, - 'sql' => $report->savedsql, - 'showsql' => 1, - 'mana_success' => scalar $input->param('mana_success'), - 'mana_id' => $report->{mana_id}, + 'id' => $id, + 'reportname' => $report->report_name, + 'notes' => $report->notes, + 'sql' => $report->savedsql, + 'showsql' => 1, + 'mana_success' => scalar $input->param('mana_success'), + 'mana_id' => $report->{mana_id}, 'mana_comments' => $report->{comments} ); -} -elsif ( $op eq 'edit_form'){ - my $id = $input->param('id'); - my $report = Koha::Reports->find($id); - my $group = $report->report_group; - my $subgroup = $report->report_subgroup; - my $tables = get_tables(); +} elsif ( $op eq 'edit_form' ) { + my $id = $input->param('id'); + my $report = Koha::Reports->find($id); + my $group = $report->report_group; + my $subgroup = $report->report_subgroup; + my $tables = get_tables(); $template->param( - 'sql' => $report->savedsql, - 'reportname' => $report->report_name, - 'groups_with_subgroups' => groups_with_subgroups($group, $subgroup), - 'notes' => $report->notes, - 'id' => $id, - 'cache_expiry' => $report->cache_expiry, - 'public' => $report->public, - 'usecache' => $usecache, - 'editsql' => 1, - 'mana_id' => $report->{mana_id}, - 'mana_comments' => $report->{comments}, - 'tables' => $tables + 'sql' => $report->savedsql, + 'reportname' => $report->report_name, + 'groups_with_subgroups' => groups_with_subgroups( $group, $subgroup ), + 'notes' => $report->notes, + 'id' => $id, + 'cache_expiry' => $report->cache_expiry, + 'public' => $report->public, + 'usecache' => $usecache, + 'editsql' => 1, + 'mana_id' => $report->{mana_id}, + 'mana_comments' => $report->{comments}, + 'tables' => $tables ); -} -elsif ( $op eq 'cud-update_sql' || $op eq 'cud-update_and_run_sql' ){ - my $id = $input->param('id'); - my $sql = $input->param('sql'); - my $reportname = $input->param('reportname'); - my $group = $input->param('group'); - my $subgroup = $input->param('subgroup'); - my $notes = $input->param('notes'); - my $cache_expiry = $input->param('cache_expiry'); +} elsif ( $op eq 'cud-update_sql' || $op eq 'cud-update_and_run_sql' ) { + my $id = $input->param('id'); + my $sql = $input->param('sql'); + my $reportname = $input->param('reportname'); + my $group = $input->param('group'); + my $subgroup = $input->param('subgroup'); + my $notes = $input->param('notes'); + my $cache_expiry = $input->param('cache_expiry'); my $cache_expiry_units = $input->param('cache_expiry_units'); - my $public = $input->param('public'); - my $save_anyway = $input->param('save_anyway'); + my $public = $input->param('public'); + my $save_anyway = $input->param('save_anyway'); my @errors; my $tables = get_tables(); # if we have the units, then we came from creating a report from SQL and thus need to handle converting units - if( $cache_expiry_units ){ - if( $cache_expiry_units eq "minutes" ){ - $cache_expiry *= 60; - } elsif( $cache_expiry_units eq "hours" ){ - $cache_expiry *= 3600; # 60 * 60 - } elsif( $cache_expiry_units eq "days" ){ - $cache_expiry *= 86400; # 60 * 60 * 24 - } + if ($cache_expiry_units) { + if ( $cache_expiry_units eq "minutes" ) { + $cache_expiry *= 60; + } elsif ( $cache_expiry_units eq "hours" ) { + $cache_expiry *= 3600; # 60 * 60 + } elsif ( $cache_expiry_units eq "days" ) { + $cache_expiry *= 86400; # 60 * 60 * 24 + } } + # check $cache_expiry isn't too large, Memcached::set requires it to be less than 30 days or it will be treated as if it were an absolute time stamp - if( $cache_expiry >= 2592000 ){ - push @errors, {cache_expiry => $cache_expiry}; + if ( $cache_expiry >= 2592000 ) { + push @errors, { cache_expiry => $cache_expiry }; } - create_non_existing_group_and_subgroup($input, $group, $subgroup); + create_non_existing_group_and_subgroup( $input, $group, $subgroup ); - my ( $is_sql_valid, $validation_errors ) = Koha::Report->new({ savedsql => $sql })->is_sql_valid; - push(@errors, @$validation_errors) unless $is_sql_valid; + my ( $is_sql_valid, $validation_errors ) = Koha::Report->new( { savedsql => $sql } )->is_sql_valid; + push( @errors, @$validation_errors ) unless $is_sql_valid; if (@errors) { $template->param( - 'errors' => \@errors, - 'sql' => $sql, + 'errors' => \@errors, + 'sql' => $sql, ); } else { @@ -199,32 +197,37 @@ elsif ( $op eq 'cud-update_sql' || $op eq 'cud-update_and_run_sql' ){ my $problematic_authvals = ValidateSQLParameters($sql); if ( scalar @$problematic_authvals > 0 && not $save_anyway ) { + # There's at least one problematic parameter, report to the # GUI and provide all user input for further actions $template->param( - 'id' => $id, - 'sql' => $sql, - 'reportname' => $reportname, - 'group' => $group, - 'subgroup' => $subgroup, - 'notes' => $notes, - 'public' => $public, + 'id' => $id, + 'sql' => $sql, + 'reportname' => $reportname, + 'group' => $group, + 'subgroup' => $subgroup, + 'notes' => $notes, + 'public' => $public, 'problematic_authvals' => $problematic_authvals, 'warn_authval_problem' => 1, - 'phase_update' => 1, + 'phase_update' => 1, ); } else { + # No params problem found or asked to save anyway - update_sql( $id, { - sql => $sql, - name => $reportname, - group => $group, - subgroup => $subgroup, - notes => $notes, - public => $public, + update_sql( + $id, + { + sql => $sql, + name => $reportname, + group => $group, + subgroup => $subgroup, + notes => $notes, + public => $public, cache_expiry => $cache_expiry, - } ); + } + ); my $editsql = 1; if ( $op eq 'cud-update_and_run_sql' ) { @@ -237,7 +240,7 @@ elsif ( $op eq 'cud-update_sql' || $op eq 'cud-update_and_run_sql' ){ 'id' => $id, 'editsql' => $editsql, 'sql' => $sql, - 'groups_with_subgroups' => groups_with_subgroups($group, $subgroup), + 'groups_with_subgroups' => groups_with_subgroups( $group, $subgroup ), 'notes' => $notes, 'cache_expiry' => $cache_expiry, 'public' => $public, @@ -246,9 +249,9 @@ elsif ( $op eq 'cud-update_sql' || $op eq 'cud-update_and_run_sql' ){ ); logaction( "REPORTS", "MODIFY", $id, "$reportname | $sql" ) if C4::Context->preference("ReportsLog"); } - if ( $usecache ) { + if ($usecache) { $template->param( - cache_expiry => $cache_expiry, + cache_expiry => $cache_expiry, cache_expiry_units => $cache_expiry_units, ); } @@ -256,70 +259,70 @@ elsif ( $op eq 'cud-update_sql' || $op eq 'cud-update_and_run_sql' ){ $op = 'run'; } } -} -elsif ($op eq 'retrieve_results') { - my $id = $input->param('id'); - my $result = format_results( $id ); +} elsif ( $op eq 'retrieve_results' ) { + my $id = $input->param('id'); + my $result = format_results($id); $template->param( report_name => $result->{report_name}, notes => $result->{notes}, saved_results => $result->{results}, date_run => $result->{date_run}, ); -} -elsif ( $op eq 'cud-report' ) { +} elsif ( $op eq 'cud-report' ) { my $cache_expiry_units = $input->param('cache_expiry_units'), - my $cache_expiry = $input->param('cache_expiry'); + my $cache_expiry = $input->param('cache_expiry'); # we need to handle converting units - if( $cache_expiry_units eq "minutes" ){ - $cache_expiry *= 60; - } elsif( $cache_expiry_units eq "hours" ){ - $cache_expiry *= 3600; # 60 * 60 - } elsif( $cache_expiry_units eq "days" ){ - $cache_expiry *= 86400; # 60 * 60 * 24 + if ( $cache_expiry_units eq "minutes" ) { + $cache_expiry *= 60; + } elsif ( $cache_expiry_units eq "hours" ) { + $cache_expiry *= 3600; # 60 * 60 + } elsif ( $cache_expiry_units eq "days" ) { + $cache_expiry *= 86400; # 60 * 60 * 24 } - # check $cache_expiry isn't too large, Memcached::set requires it to be less than 30 days or it will be treated as if it were an absolute time stamp - if( $cache_expiry >= 2592000 ){ # oops, over the limit of 30 days - # report error to user - $template->param( - 'cache_error' => 1, - 'build1' => 1, - 'areas' => get_report_areas(), - 'cache_expiry' => $cache_expiry, - 'usecache' => $usecache, - 'public' => scalar $input->param('public'), - ); - } else { - # they have chosen a new report and the area to report on - $template->param( - 'build2' => 1, - 'area' => scalar $input->param('area'), - 'types' => get_report_types(), - 'cache_expiry' => $cache_expiry, - 'public' => scalar $input->param('public'), - ); - } -} -elsif ( $op eq 'cud-choose_type' ) { + # check $cache_expiry isn't too large, Memcached::set requires it to be less than 30 days or it will be treated as if it were an absolute time stamp + if ( $cache_expiry >= 2592000 ) { # oops, over the limit of 30 days + # report error to user + $template->param( + 'cache_error' => 1, + 'build1' => 1, + 'areas' => get_report_areas(), + 'cache_expiry' => $cache_expiry, + 'usecache' => $usecache, + 'public' => scalar $input->param('public'), + ); + } else { + + # they have chosen a new report and the area to report on + $template->param( + 'build2' => 1, + 'area' => scalar $input->param('area'), + 'types' => get_report_types(), + 'cache_expiry' => $cache_expiry, + 'public' => scalar $input->param('public'), + ); + } + +} elsif ( $op eq 'cud-choose_type' ) { + # they have chosen type and area # get area and type and pass them to the template my $area = $input->param('area'); my $type = $input->param('types'); $template->param( - 'build3' => 1, - 'area' => $area, - 'type' => $type, - columns => get_columns($area), + 'build3' => 1, + 'area' => $area, + 'type' => $type, + columns => get_columns($area), 'cache_expiry' => scalar $input->param('cache_expiry'), - 'public' => scalar $input->param('public'), + 'public' => scalar $input->param('public'), ); -} -elsif ( $op eq 'cud-choose_columns' ) { +} elsif ( $op eq 'cud-choose_columns' ) { + # we now know type, area, and columns # next step is the constraints my $area = $input->param('area'); @@ -328,45 +331,44 @@ elsif ( $op eq 'cud-choose_columns' ) { my $column = join( ',', @columns ); $template->param( - 'build4' => 1, - 'area' => $area, - 'type' => $type, - 'column' => $column, + 'build4' => 1, + 'area' => $area, + 'type' => $type, + 'column' => $column, definitions => get_from_dictionary($area), - criteria => get_criteria($area,$input), - 'public' => scalar $input->param('public'), + criteria => get_criteria( $area, $input ), + 'public' => scalar $input->param('public'), ); - if ( $usecache ) { + if ($usecache) { $template->param( - cache_expiry => scalar $input->param('cache_expiry'), + cache_expiry => scalar $input->param('cache_expiry'), cache_expiry_units => scalar $input->param('cache_expiry_units'), ); } -} - -elsif ( $op eq 'cud-choose_criteria' ) { - my $area = $input->param('area'); - my $type = $input->param('type'); - my $column = $input->param('column'); +} elsif ( $op eq 'cud-choose_criteria' ) { + my $area = $input->param('area'); + my $type = $input->param('type'); + my $column = $input->param('column'); my @definitions = $input->multi_param('definition'); - my $definition = join (',',@definitions); - my @criteria = $input->multi_param('criteria_column'); + my $definition = join( ',', @definitions ); + my @criteria = $input->multi_param('criteria_column'); my $query_criteria; foreach my $crit (@criteria) { my $value = $input->param( $crit . "_value" ); # If value is not defined, then it may be range values - if (!defined $value) { + if ( !defined $value ) { my $fromvalue = $input->param( "from_" . $crit . "_value" ); - my $tovalue = $input->param( "to_" . $crit . "_value" ); + my $tovalue = $input->param( "to_" . $crit . "_value" ); - if ($fromvalue && $tovalue) { + if ( $fromvalue && $tovalue ) { $query_criteria .= " AND $crit >= '$fromvalue' AND $crit <= '$tovalue'"; } } else { + # don't escape runtime parameters, they'll be at runtime - if ($value =~ /<<.*>>/) { + if ( $value =~ /<<.*>>/ ) { $query_criteria .= " AND $crit=$value"; } else { $query_criteria .= " AND $crit='$value'"; @@ -380,11 +382,11 @@ elsif ( $op eq 'cud-choose_criteria' ) { 'column' => $column, 'definition' => $definition, 'criteriastring' => $query_criteria, - 'public' => scalar $input->param('public'), + 'public' => scalar $input->param('public'), ); - if ( $usecache ) { + if ($usecache) { $template->param( - cache_expiry => scalar $input->param('cache_expiry'), + cache_expiry => scalar $input->param('cache_expiry'), cache_expiry_units => scalar $input->param('cache_expiry_units'), ); } @@ -395,24 +397,23 @@ elsif ( $op eq 'cud-choose_criteria' ) { # build structue for use by tmpl_loop to choose columns to order by # need to do something about the order of the order :) - # we also want to use the %columns hash to get the plain english names + # we also want to use the %columns hash to get the plain english names foreach my $col (@columns) { - my %total = (name => $col); - my @selects = map {+{ value => $_ }} (qw(sum min max avg count)); + my %total = ( name => $col ); + my @selects = map { +{ value => $_ } } (qw(sum min max avg count)); $total{'select'} = \@selects; push @total_by, \%total; } $template->param( 'total_by' => \@total_by ); -} -elsif ( $op eq 'cud-choose_operations' ) { - my $area = $input->param('area'); - my $type = $input->param('type'); - my $column = $input->param('column'); - my $criteria = $input->param('criteria'); - my $definition = $input->param('definition'); - my @total_by = $input->multi_param('total_by'); +} elsif ( $op eq 'cud-choose_operations' ) { + my $area = $input->param('area'); + my $type = $input->param('type'); + my $column = $input->param('column'); + my $criteria = $input->param('criteria'); + my $definition = $input->param('definition'); + my @total_by = $input->multi_param('total_by'); my $totals; foreach my $total (@total_by) { my $value = $input->param( $total . "_tvalue" ); @@ -427,8 +428,8 @@ elsif ( $op eq 'cud-choose_operations' ) { 'criteriastring' => $criteria, 'totals' => $totals, 'definition' => $definition, - 'cache_expiry' => scalar $input->param('cache_expiry'), - 'public' => scalar $input->param('public'), + 'cache_expiry' => scalar $input->param('cache_expiry'), + 'public' => scalar $input->param('public'), ); # get columns @@ -438,27 +439,27 @@ elsif ( $op eq 'cud-choose_operations' ) { # build structue for use by tmpl_loop to choose columns to order by # need to do something about the order of the order :) foreach my $col (@columns) { - my %order = (name => $col); - my @selects = map {+{ value => $_ }} (qw(asc desc)); + my %order = ( name => $col ); + my @selects = map { +{ value => $_ } } (qw(asc desc)); $order{'select'} = \@selects; push @order_by, \%order; } $template->param( 'order_by' => \@order_by ); -} -elsif ( $op eq 'cud-build_report' ) { +} elsif ( $op eq 'cud-build_report' ) { # now we have all the info we need and can build the sql - my $area = $input->param('area'); - my $type = $input->param('type'); - my $column = $input->param('column'); - my $crit = $input->param('criteria'); - my $totals = $input->param('totals'); - my $definition = $input->param('definition'); - my $query_criteria=$crit; + my $area = $input->param('area'); + my $type = $input->param('type'); + my $column = $input->param('column'); + my $crit = $input->param('criteria'); + my $totals = $input->param('totals'); + my $definition = $input->param('definition'); + my $query_criteria = $crit; + # split the columns up by , - my @columns = split( ',', $column ); + my @columns = split( ',', $column ); my @order_by = $input->multi_param('order_by'); my $query_orderby; @@ -466,116 +467,118 @@ elsif ( $op eq 'cud-build_report' ) { my $value = $input->param( $order . "_ovalue" ); if ($query_orderby) { $query_orderby .= ",$order $value"; - } - else { + } else { $query_orderby = " ORDER BY $order $value"; } } # get the sql - my $sql = - build_query( \@columns, $query_criteria, $query_orderby, $area, $totals, $definition ); + my $sql = build_query( \@columns, $query_criteria, $query_orderby, $area, $totals, $definition ); $template->param( - 'showreport' => 1, - 'area' => $area, - 'sql' => $sql, - 'type' => $type, + 'showreport' => 1, + 'area' => $area, + 'sql' => $sql, + 'type' => $type, 'cache_expiry' => scalar $input->param('cache_expiry'), - 'public' => scalar $input->param('public'), + 'public' => scalar $input->param('public'), ); -} -elsif ( $op eq 'save' ) { +} elsif ( $op eq 'save' ) { + # Save the report that has just been built my $area = $input->param('area'); my $sql = $input->param('sql'); my $type = $input->param('type'); $template->param( - 'save' => 1, - 'area' => $area, - 'sql' => $sql, - 'type' => $type, - 'cache_expiry' => scalar $input->param('cache_expiry'), - 'public' => scalar $input->param('public'), - 'groups_with_subgroups' => groups_with_subgroups($area), # in case we have a report group that matches area + 'save' => 1, + 'area' => $area, + 'sql' => $sql, + 'type' => $type, + 'cache_expiry' => scalar $input->param('cache_expiry'), + 'public' => scalar $input->param('public'), + 'groups_with_subgroups' => groups_with_subgroups($area), # in case we have a report group that matches area ); -} -elsif ( $op eq 'cud-save' ) { +} elsif ( $op eq 'cud-save' ) { + # save the sql pasted in by a user - my $area = $input->param('area'); - my $group = $input->param('group'); - my $subgroup = $input->param('subgroup'); - my $sql = $input->param('sql'); - my $name = $input->param('reportname'); - my $type = $input->param('types'); - my $notes = $input->param('notes'); - my $cache_expiry = $input->param('cache_expiry'); + my $area = $input->param('area'); + my $group = $input->param('group'); + my $subgroup = $input->param('subgroup'); + my $sql = $input->param('sql'); + my $name = $input->param('reportname'); + my $type = $input->param('types'); + my $notes = $input->param('notes'); + my $cache_expiry = $input->param('cache_expiry'); my $cache_expiry_units = $input->param('cache_expiry_units'); - my $public = $input->param('public'); - my $save_anyway = $input->param('save_anyway'); - my $tables = get_tables(); - + my $public = $input->param('public'); + my $save_anyway = $input->param('save_anyway'); + my $tables = get_tables(); # if we have the units, then we came from creating a report from SQL and thus need to handle converting units - if( $cache_expiry_units ){ - if( $cache_expiry_units eq "minutes" ){ - $cache_expiry *= 60; - } elsif( $cache_expiry_units eq "hours" ){ - $cache_expiry *= 3600; # 60 * 60 - } elsif( $cache_expiry_units eq "days" ){ - $cache_expiry *= 86400; # 60 * 60 * 24 - } - } - # check $cache_expiry isn't too large, Memcached::set requires it to be less than 30 days or it will be treated as if it were an absolute time stamp - if( $cache_expiry && $cache_expiry >= 2592000 ){ - push @errors, {cache_expiry => $cache_expiry}; + if ($cache_expiry_units) { + if ( $cache_expiry_units eq "minutes" ) { + $cache_expiry *= 60; + } elsif ( $cache_expiry_units eq "hours" ) { + $cache_expiry *= 3600; # 60 * 60 + } elsif ( $cache_expiry_units eq "days" ) { + $cache_expiry *= 86400; # 60 * 60 * 24 + } } - create_non_existing_group_and_subgroup($input, $group, $subgroup); + # check $cache_expiry isn't too large, Memcached::set requires it to be less than 30 days or it will be treated as if it were an absolute time stamp + if ( $cache_expiry && $cache_expiry >= 2592000 ) { + push @errors, { cache_expiry => $cache_expiry }; + } + + create_non_existing_group_and_subgroup( $input, $group, $subgroup ); ## FIXME this is AFTER entering a name to save the report under - my ( $is_sql_valid, $validation_errors ) = Koha::Report->new({ savedsql => $sql })->is_sql_valid; - push(@errors, @$validation_errors) unless $is_sql_valid; + my ( $is_sql_valid, $validation_errors ) = Koha::Report->new( { savedsql => $sql } )->is_sql_valid; + push( @errors, @$validation_errors ) unless $is_sql_valid; if (@errors) { $template->param( - 'errors' => \@errors, - 'sql' => $sql, - 'reportname'=> $name, - 'type' => $type, - 'notes' => $notes, + 'errors' => \@errors, + 'sql' => $sql, + 'reportname' => $name, + 'type' => $type, + 'notes' => $notes, 'cache_expiry' => $cache_expiry, - 'public' => $public, + 'public' => $public, ); } else { + # Check defined SQL parameters for authorised value validity my $problematic_authvals = ValidateSQLParameters($sql); if ( scalar @$problematic_authvals > 0 && not $save_anyway ) { + # There's at least one problematic parameter, report to the # GUI and provide all user input for further actions $template->param( - 'area' => $area, - 'group' => $group, - 'subgroup' => $subgroup, - 'sql' => $sql, - 'reportname' => $name, - 'type' => $type, - 'notes' => $notes, - 'public' => $public, + 'area' => $area, + 'group' => $group, + 'subgroup' => $subgroup, + 'sql' => $sql, + 'reportname' => $name, + 'type' => $type, + 'notes' => $notes, + 'public' => $public, 'problematic_authvals' => $problematic_authvals, 'warn_authval_problem' => 1, - 'phase_save' => 1 + 'phase_save' => 1 ); - if ( $usecache ) { + if ($usecache) { $template->param( - cache_expiry => $cache_expiry, + cache_expiry => $cache_expiry, cache_expiry_units => $cache_expiry_units, ); } } else { + # No params problem found or asked to save anyway - my $id = save_report( { + my $id = save_report( + { borrowernumber => $borrowernumber, sql => $sql, name => $name, @@ -586,39 +589,38 @@ elsif ( $op eq 'cud-save' ) { notes => $notes, cache_expiry => $cache_expiry, public => $public, - } ); - logaction( "REPORTS", "ADD", $id, "$name | $sql" ) if C4::Context->preference("ReportsLog"); + } + ); + logaction( "REPORTS", "ADD", $id, "$name | $sql" ) if C4::Context->preference("ReportsLog"); $template->param( - 'save_successful' => 1, - 'reportname' => $name, - 'id' => $id, - 'editsql' => 1, - 'sql' => $sql, - 'groups_with_subgroups' => groups_with_subgroups($group, $subgroup), - 'notes' => $notes, - 'cache_expiry' => $cache_expiry, - 'public' => $public, - 'usecache' => $usecache, - 'tables' => $tables + 'save_successful' => 1, + 'reportname' => $name, + 'id' => $id, + 'editsql' => 1, + 'sql' => $sql, + 'groups_with_subgroups' => groups_with_subgroups( $group, $subgroup ), + 'notes' => $notes, + 'cache_expiry' => $cache_expiry, + 'public' => $public, + 'usecache' => $usecache, + 'tables' => $tables ); } } -} -elsif ($op eq 'cud-share'){ - my $lang = $input->param('mana_language') || ''; +} elsif ( $op eq 'cud-share' ) { + my $lang = $input->param('mana_language') || ''; my $reportid = $input->param('reportid'); - my $result = Koha::SharedContent::send_entity($lang, $borrowernumber, $reportid, 'report'); - if ( $result ) { - print $input->redirect("/cgi-bin/koha/reports/guided_reports.pl?op=listmanamsg=".$result->{msg}); - }else{ + my $result = Koha::SharedContent::send_entity( $lang, $borrowernumber, $reportid, 'report' ); + if ($result) { + print $input->redirect( "/cgi-bin/koha/reports/guided_reports.pl?op=listmanamsg=" . $result->{msg} ); + } else { print $input->redirect("/cgi-bin/koha/reports/guided_reports.pl?op=list&manamsg=noanswer"); } -} -elsif ($op eq 'export'){ +} elsif ( $op eq 'export' ) { - # export results to tab separated text or CSV + # export results to tab separated text or CSV my $report_id = $input->param('id'); my $report = Koha::Reports->find($report_id); my $sql = $report->savedsql; @@ -630,13 +632,13 @@ elsif ($op eq 'export'){ $reportname ? "$report_id-$reportname-reportresults.$format" : "$report_id-reportresults.$format"; my $scrubber = C4::Scrubber->new(); - ($sql, undef) = $report->prep_report( \@param_names, \@sql_params, { export => 1 } ); + ( $sql, undef ) = $report->prep_report( \@param_names, \@sql_params, { export => 1 } ); my ( $sth, $q_errors ) = execute_query( { sql => $sql, report_id => $report_id } ); - unless ($q_errors and @$q_errors) { + unless ( $q_errors and @$q_errors ) { my ( $type, $content ); - if ($format eq 'tab') { + if ( $format eq 'tab' ) { $type = 'application/octet-stream'; - $content .= join("\t", header_cell_values($sth)) . "\n"; + $content .= join( "\t", header_cell_values($sth) ) . "\n"; $content = $scrubber->scrub( Encode::decode( 'UTF-8', $content ) ); while ( my $row = $sth->fetchrow_arrayref() ) { $content .= $scrubber->scrub( join( "\t", map { $_ // '' } @$row ) ) . "\n"; @@ -649,7 +651,8 @@ elsif ($op eq 'export'){ # Add BOM for UTF-8 encoded CSV $content .= "\xEF\xBB\xBF"; - my $csv = Text::CSV::Encoded->new({ encoding_out => 'UTF-8', sep_char => $delimiter, formula => 'empty' }); + my $csv = + Text::CSV::Encoded->new( { encoding_out => 'UTF-8', sep_char => $delimiter, formula => 'empty' } ); $csv or die "Text::CSV::Encoded->new({binary => 1}) FAILED: " . Text::CSV::Encoded->error_diag(); if ( $csv->combine( header_cell_values($sth) ) ) { $content .= $scrubber->scrub( Encode::decode( 'UTF-8', $csv->string() ) ) . "\n"; @@ -665,10 +668,9 @@ elsif ($op eq 'export'){ push @$q_errors, { combine => $csv->error_diag() }; } } - } - elsif ( $format eq 'ods' && C4::Context->preference('ReportsExportFormatODS') ) { + } elsif ( $format eq 'ods' && C4::Context->preference('ReportsExportFormatODS') ) { $type = 'application/vnd.oasis.opendocument.spreadsheet'; - my $ods_fh = File::Temp->new( UNLINK => 0 ); + my $ods_fh = File::Temp->new( UNLINK => 0 ); my $ods_filepath = $ods_fh->filename; my $ods_content; @@ -688,7 +690,7 @@ elsif ($op eq 'export'){ } # Process - generate_ods($ods_filepath, $ods_content); + generate_ods( $ods_filepath, $ods_content ); # Output binmode(STDOUT); @@ -699,8 +701,7 @@ elsif ($op eq 'export'){ ); print $_ while <$ods_fh>; unlink $ods_filepath; - } - elsif ( $format eq 'template' ) { + } elsif ( $format eq 'template' ) { my $template_id = $input->param('template'); my $notice_template = Koha::Notice::Templates->find($template_id); my $data = $sth->fetchall_arrayref( {} ); @@ -730,56 +731,55 @@ elsif ($op eq 'export'){ print $content; } - foreach my $err (@$q_errors, @errors) { - print "# ERROR: " . (map {$_ . ": " . $err->{$_}} keys %$err) . "\n"; - } # here we print all the non-fatal errors at the end. Not super smooth, but better than nothing. + foreach my $err ( @$q_errors, @errors ) { + print "# ERROR: " . ( map { $_ . ": " . $err->{$_} } keys %$err ) . "\n"; + } # here we print all the non-fatal errors at the end. Not super smooth, but better than nothing. exit; } $template->param( - 'sql' => $sql, - 'execute' => 1, - 'name' => 'Error exporting report!', - 'notes' => '', - 'errors' => $q_errors, + 'sql' => $sql, + 'execute' => 1, + 'name' => 'Error exporting report!', + 'notes' => '', + 'errors' => $q_errors, ); -} -elsif ( $op eq 'add_form_sql' || $op eq 'duplicate' ) { +} elsif ( $op eq 'add_form_sql' || $op eq 'duplicate' ) { - my ($group, $subgroup, $sql, $reportname, $notes); + my ( $group, $subgroup, $sql, $reportname, $notes ); if ( $input->param('sql') ) { $group = $input->param('report_group'); $subgroup = $input->param('report_subgroup'); - $sql = $input->param('sql') // ''; + $sql = $input->param('sql') // ''; $reportname = $input->param('reportname') // ''; - $notes = $input->param('notes') // ''; - } - elsif ( my $report_id = $input->param('id') ) { + $notes = $input->param('notes') // ''; + } elsif ( my $report_id = $input->param('id') ) { my $report = Koha::Reports->find($report_id); $group = $report->report_group; $subgroup = $report->report_subgroup; - $sql = $report->savedsql // ''; + $sql = $report->savedsql // ''; $reportname = $report->report_name // ''; - $notes = $report->notes // ''; + $notes = $report->notes // ''; } my $tables = get_tables(); $template->param( - sql => $sql, - reportname => $reportname, - notes => $notes, - 'create' => 1, - 'groups_with_subgroups' => groups_with_subgroups($group, $subgroup), - 'public' => '0', - 'cache_expiry' => 300, - 'usecache' => $usecache, - 'tables' => $tables, + sql => $sql, + reportname => $reportname, + notes => $notes, + 'create' => 1, + 'groups_with_subgroups' => groups_with_subgroups( $group, $subgroup ), + 'public' => '0', + 'cache_expiry' => 300, + 'usecache' => $usecache, + 'tables' => $tables, ); } -if ($op eq 'run'){ +if ( $op eq 'run' ) { + # execute a saved report my $limit = $input->param('limit') || 20; my $offset = 0; @@ -789,10 +789,9 @@ if ($op eq 'run'){ my $template_id = $input->param('template'); my $want_full_chart = $input->param('want_full_chart') || 0; - # offset algorithm - if ($input->param('page')) { - $offset = ($input->param('page') - 1) * $limit; + if ( $input->param('page') ) { + $offset = ( $input->param('page') - 1 ) * $limit; } $template->param( @@ -801,27 +800,31 @@ if ($op eq 'run'){ ); my ( $sql, $original_sql, $type, $name, $notes ); - if (my $report = Koha::Reports->find($report_id)) { + if ( my $report = Koha::Reports->find($report_id) ) { $sql = $original_sql = $report->savedsql; $name = $report->report_name; $notes = $report->notes; - my @rows = (); + my @rows = (); my @allrows = (); + # if we have at least 1 parameter, and it's not filled, then don't execute but ask for parameters - if ($sql =~ /<>/,$sql; + my @split = split /<<|>>/, $sql; my @tmpl_parameters; my @authval_errors; my %uniq_params; - for(my $i=0;$i<($#split/2);$i++) { - my ($text,$authorised_value_all) = split /\|/,$split[$i*2+1]; + for ( my $i = 0 ; $i < ( $#split / 2 ) ; $i++ ) { + my ( $text, $authorised_value_all ) = split /\|/, $split[ $i * 2 + 1 ]; my $sep = $authorised_value_all ? "|" : ""; - if( defined $uniq_params{$text.$sep.$authorised_value_all} ){ + if ( defined $uniq_params{ $text . $sep . $authorised_value_all } ) { next; - } else { $uniq_params{$text.$sep.$authorised_value_all} = "$i"; } - my ($authorised_value, $param_options) = split /:/, $authorised_value_all; + } else { + $uniq_params{ $text . $sep . $authorised_value_all } = "$i"; + } + my ( $authorised_value, $param_options ) = split /:/, $authorised_value_all; my $all; my $multiple; if ( $param_options eq "all" ) { @@ -832,86 +835,86 @@ if ($op eq 'run'){ my $input; my $labelid; if ( not defined $authorised_value ) { + # no authorised value input, provide a text box $input = "text"; } elsif ( $authorised_value eq "date" ) { + # require a date, provide a date picker $input = 'date'; } elsif ( $authorised_value eq "list" ) { + # require a list, provide a textarea $input = 'textarea'; } else { + # defined $authorised_value, and not 'date' - my $dbh=C4::Context->dbh; + my $dbh = C4::Context->dbh; my @authorised_values; my %authorised_lib; + # builds list, depending on authorised value... if ( $authorised_value eq "branches" ) { my $libraries = Koha::Libraries->search( {}, { order_by => ['branchname'] } ); while ( my $library = $libraries->next ) { push @authorised_values, $library->branchcode; - $authorised_lib{$library->branchcode} = $library->branchname; + $authorised_lib{ $library->branchcode } = $library->branchname; } - } - elsif ( $authorised_value eq "itemtypes" ) { + } elsif ( $authorised_value eq "itemtypes" ) { my $sth = $dbh->prepare("SELECT itemtype,description FROM itemtypes ORDER BY description"); $sth->execute; while ( my ( $itemtype, $description ) = $sth->fetchrow_array ) { push @authorised_values, $itemtype; $authorised_lib{$itemtype} = $description; } - } - elsif ( $authorised_value eq "biblio_framework" ) { - my @frameworks = Koha::BiblioFrameworks->search({}, { order_by => ['frameworktext'] })->as_list; + } elsif ( $authorised_value eq "biblio_framework" ) { + my @frameworks = + Koha::BiblioFrameworks->search( {}, { order_by => ['frameworktext'] } )->as_list; my $default_source = ''; - push @authorised_values,$default_source; + push @authorised_values, $default_source; $authorised_lib{$default_source} = 'Default'; foreach my $framework (@frameworks) { push @authorised_values, $framework->frameworkcode; - $authorised_lib{$framework->frameworkcode} = $framework->frameworktext; + $authorised_lib{ $framework->frameworkcode } = $framework->frameworktext; } - } - elsif ( $authorised_value eq "cn_source" ) { - my $class_sources = GetClassSources(); + } elsif ( $authorised_value eq "cn_source" ) { + my $class_sources = GetClassSources(); my $default_source = C4::Context->preference("DefaultClassificationSource"); - foreach my $class_source (sort keys %$class_sources) { - next unless $class_sources->{$class_source}->{'used'} or - ($class_source eq $default_source); + foreach my $class_source ( sort keys %$class_sources ) { + next + unless $class_sources->{$class_source}->{'used'} + or ( $class_source eq $default_source ); push @authorised_values, $class_source; $authorised_lib{$class_source} = $class_sources->{$class_source}->{'description'}; } - } - elsif ( $authorised_value eq "categorycode" ) { - my @patron_categories = Koha::Patron::Categories->search({}, { order_by => ['description']})->as_list; + } elsif ( $authorised_value eq "categorycode" ) { + my @patron_categories = + Koha::Patron::Categories->search( {}, { order_by => ['description'] } )->as_list; %authorised_lib = map { $_->categorycode => $_->description } @patron_categories; push @authorised_values, $_->categorycode for @patron_categories; - } - elsif ( $authorised_value eq "cash_registers" ) { + } elsif ( $authorised_value eq "cash_registers" ) { my $sth = $dbh->prepare("SELECT id, name FROM cash_registers ORDER BY description"); $sth->execute; while ( my ( $id, $name ) = $sth->fetchrow_array ) { push @authorised_values, $id; $authorised_lib{$id} = $name; } - } - elsif ( $authorised_value eq "debit_types" ) { + } elsif ( $authorised_value eq "debit_types" ) { my $sth = $dbh->prepare("SELECT code, description FROM account_debit_types ORDER BY code"); $sth->execute; while ( my ( $code, $description ) = $sth->fetchrow_array ) { - push @authorised_values, $code; - $authorised_lib{$code} = $description; + push @authorised_values, $code; + $authorised_lib{$code} = $description; } - } - elsif ( $authorised_value eq "credit_types" ) { + } elsif ( $authorised_value eq "credit_types" ) { my $sth = $dbh->prepare("SELECT code, description FROM account_credit_types ORDER BY code"); $sth->execute; while ( my ( $code, $description ) = $sth->fetchrow_array ) { - push @authorised_values, $code; - $authorised_lib{$code} = $description; + push @authorised_values, $code; + $authorised_lib{$code} = $description; } - } - else { - if ( Koha::AuthorisedValues->search({ category => $authorised_value })->count ) { + } else { + if ( Koha::AuthorisedValues->search( { category => $authorised_value } )->count ) { my $query = ' SELECT authorised_value,lib FROM authorised_values @@ -919,20 +922,26 @@ if ($op eq 'run'){ ORDER BY lib '; my $authorised_values_sth = $dbh->prepare($query); - $authorised_values_sth->execute( $authorised_value); + $authorised_values_sth->execute($authorised_value); while ( my ( $value, $lib ) = $authorised_values_sth->fetchrow_array ) { push @authorised_values, $value; $authorised_lib{$value} = $lib; + # For item location, we show the code and the libelle $authorised_lib{$value} = $lib; } } else { + # not exists $authorised_value_categories{$authorised_value}) - push @authval_errors, {'entry' => $text, - 'auth_val' => $authorised_value }; + push @authval_errors, { + 'entry' => $text, + 'auth_val' => $authorised_value + }; + # tell the template there's an error $template->param( auth_val_error => 1 ); + # skip scrolling list creation and params push next; } @@ -940,60 +949,67 @@ if ($op eq 'run'){ $labelid = $text; $labelid =~ s/\W//g; $input = { - name => "sql_params", - id => "sql_params_".$labelid, - values => \@authorised_values, - labels => \%authorised_lib, + name => "sql_params", + id => "sql_params_" . $labelid, + values => \@authorised_values, + labels => \%authorised_lib, }; } - push @tmpl_parameters, {'entry' => $text, 'input' => $input, 'labelid' => $labelid, 'name' => $text.$sep.$authorised_value_all, 'include_all' => $all, 'select_multiple' => $multiple }; + push @tmpl_parameters, + { + 'entry' => $text, 'input' => $input, 'labelid' => $labelid, + 'name' => $text . $sep . $authorised_value_all, 'include_all' => $all, + 'select_multiple' => $multiple + }; } - $template->param('sql' => $sql, - 'name' => $name, - 'notes' => $notes, - 'sql_params' => \@tmpl_parameters, - 'auth_val_errors' => \@authval_errors, - 'enter_params' => 1, - 'id' => $report_id, - ); + $template->param( + 'sql' => $sql, + 'name' => $name, + 'notes' => $notes, + 'sql_params' => \@tmpl_parameters, + 'auth_val_errors' => \@authval_errors, + 'enter_params' => 1, + 'id' => $report_id, + ); } else { - my ($sql,$header_types) = $report->prep_report( \@param_names, \@sql_params ); - $template->param(header_types => $header_types); + my ( $sql, $header_types ) = $report->prep_report( \@param_names, \@sql_params ); + $template->param( header_types => $header_types ); my ( $sth, $errors ) = execute_query( { - sql => $sql, - offset => $offset, - limit => $limit, - report_id => $report_id, + sql => $sql, + offset => $offset, + limit => $limit, + report_id => $report_id, } ); my $total; - if (!$sth) { + if ( !$sth ) { push @errors, "Report could not be run " . $errors; } elsif ( !$errors ) { $total = nb_rows($sql) || 0; my $headers = header_cell_loop($sth); - $template->param(header_row => $headers); - while (my $row = $sth->fetchrow_arrayref()) { + $template->param( header_row => $headers ); + while ( my $row = $sth->fetchrow_arrayref() ) { my @cells = map { +{ cell => $_ } } @$row; push @rows, { cells => \@cells }; } - if( $want_full_chart ){ + if ($want_full_chart) { my ( $sth2, $errors2 ) = execute_query( { sql => $sql, report_id => $report_id } ); - while (my $row = $sth2->fetchrow_arrayref()) { + while ( my $row = $sth2->fetchrow_arrayref() ) { my @cells = map { +{ cell => $_ } } @$row; push @allrows, { cells => \@cells }; } } - my $totpages = int($total/$limit) + (($total % $limit) > 0 ? 1 : 0); - my $url = "/cgi-bin/koha/reports/guided_reports.pl?id=$report_id&op=run&limit=$limit&want_full_chart=$want_full_chart"; + my $totpages = int( $total / $limit ) + ( ( $total % $limit ) > 0 ? 1 : 0 ); + my $url = + "/cgi-bin/koha/reports/guided_reports.pl?id=$report_id&op=run&limit=$limit&want_full_chart=$want_full_chart"; if (@param_names) { - $url = join('¶m_name=', $url, map { URI::Escape::uri_escape_utf8($_) } @param_names); + $url = join( '¶m_name=', $url, map { URI::Escape::uri_escape_utf8($_) } @param_names ); } if (@sql_params) { - $url = join('&sql_params=', $url, map { URI::Escape::uri_escape_utf8($_) } @sql_params); + $url = join( '&sql_params=', $url, map { URI::Escape::uri_escape_utf8($_) } @sql_params ); } if ($template_id) { @@ -1012,9 +1028,9 @@ if ($op eq 'run'){ } $template->param( - 'results' => \@rows, - 'allresults' => \@allrows, - 'pagination_bar' => pagination_bar($url, $totpages, scalar $input->param('page')), + 'results' => \@rows, + 'allresults' => \@allrows, + 'pagination_bar' => pagination_bar( $url, $totpages, scalar $input->param('page') ), 'unlimited_total' => $total, ); } @@ -1030,13 +1046,12 @@ if ($op eq 'run'){ 'param_names' => \@param_names, ); } - } - else { + } else { push @errors, { no_sql_for_id => $report_id }; } } -if ( $op eq 'list' || $op eq 'convert') { +if ( $op eq 'list' || $op eq 'convert' ) { if ( $op eq 'convert' ) { my $report_id = $input->param('id'); @@ -1061,13 +1076,13 @@ if ( $op eq 'list' || $op eq 'convert') { # use a saved report # get list of reports and display them - my $group = $input->param('group'); + my $group = $input->param('group'); my $subgroup = $input->param('subgroup'); - $filter->{group} = $group; + $filter->{group} = $group; $filter->{subgroup} = $subgroup; my $reports = get_saved_reports($filter); my $has_obsolete_reports; - for my $report ( @$reports ) { + for my $report (@$reports) { $report->{results} = C4::Reports::Guided::get_results( $report->{id} ); if ( $report->{savedsql} =~ m|biblioitems| and $report->{savedsql} =~ m|marcxml| ) { $report->{seems_obsolete} = 1; @@ -1075,7 +1090,7 @@ if ( $op eq 'list' || $op eq 'convert') { } } $template->param( - 'manamsg' => $input->param('manamsg') || '', + 'manamsg' => $input->param('manamsg') || '', 'saved1' => 1, 'savedreports' => $reports, 'usecache' => $usecache, @@ -1084,16 +1099,17 @@ if ( $op eq 'list' || $op eq 'convert') { has_obsolete_reports => $has_obsolete_reports, ); } + # pass $sth, get back an array of names for the column headers sub header_cell_values { my $sth = shift or return (); - return '' unless ($sth->{NAME}); - return @{$sth->{NAME}}; + return '' unless ( $sth->{NAME} ); + return @{ $sth->{NAME} }; } # pass $sth, get back a TMPL_LOOP-able set of names for the column headers sub header_cell_loop { - my @headers = map { +{ cell => decode('UTF-8',$_) } } header_cell_values (shift); + my @headers = map { +{ cell => decode( 'UTF-8', $_ ) } } header_cell_values(shift); return \@headers; } @@ -1104,52 +1120,52 @@ sub get_tables { my $tables = $cache->get_from_cache("Reports-SQL_tables-for-autocomplete"); return $tables - if $tables; + if $tables; $tables = C4::Reports::Guided->get_all_tables(); - for my $table (@{$tables}) { - my $sql = "SHOW COLUMNS FROM $table"; - my $rows = C4::Context->dbh->selectall_arrayref($sql, { Slice => {} }); - for my $row (@{$rows}) { - push @{$result->{$table}}, $row->{Field}; + for my $table ( @{$tables} ) { + my $sql = "SHOW COLUMNS FROM $table"; + my $rows = C4::Context->dbh->selectall_arrayref( $sql, { Slice => {} } ); + for my $row ( @{$rows} ) { + push @{ $result->{$table} }, $row->{Field}; } } - $cache->set_in_cache("Reports-SQL_tables-for-autocomplete",$result); + $cache->set_in_cache( "Reports-SQL_tables-for-autocomplete", $result ); return $result; } -foreach (1..6) { - $template->{VARS}->{'build' . $_} and last; +foreach ( 1 .. 6 ) { + $template->{VARS}->{ 'build' . $_ } and last; } -$template->param( 'referer' => $input->referer(), - ); +$template->param( + 'referer' => $input->referer(), +); output_html_with_http_headers $input, $cookie, $template->output; sub groups_with_subgroups { - my ($group, $subgroup) = @_; + my ( $group, $subgroup ) = @_; my $groups_with_subgroups = get_report_groups(); my @g_sg; - my @sorted_keys = sort { - $groups_with_subgroups->{$a}->{name} cmp $groups_with_subgroups->{$b}->{name} - } keys %$groups_with_subgroups; + my @sorted_keys = sort { $groups_with_subgroups->{$a}->{name} cmp $groups_with_subgroups->{$b}->{name} } + keys %$groups_with_subgroups; foreach my $g_id (@sorted_keys) { my $v = $groups_with_subgroups->{$g_id}; my @subgroups; - if (my $sg = $v->{subgroups}) { - foreach my $sg_id (sort { $sg->{$a} cmp $sg->{$b} } keys %$sg) { + if ( my $sg = $v->{subgroups} ) { + foreach my $sg_id ( sort { $sg->{$a} cmp $sg->{$b} } keys %$sg ) { push @subgroups, { - id => $sg_id, - name => $sg->{$sg_id}, - selected => ($group && $g_id eq $group && $subgroup && $sg_id eq $subgroup ), + id => $sg_id, + name => $sg->{$sg_id}, + selected => ( $group && $g_id eq $group && $subgroup && $sg_id eq $subgroup ), }; } } push @g_sg, { - id => $g_id, - name => $v->{name}, - selected => ($group && $g_id eq $group), + id => $g_id, + name => $v->{name}, + selected => ( $group && $g_id eq $group ), subgroups => \@subgroups, }; } @@ -1157,32 +1173,36 @@ sub groups_with_subgroups { } sub create_non_existing_group_and_subgroup { - my ($input, $group, $subgroup) = @_; - if (defined $group and $group ne '') { + my ( $input, $group, $subgroup ) = @_; + if ( defined $group and $group ne '' ) { my $report_groups = C4::Reports::Guided::get_report_groups; - if (not exists $report_groups->{$group}) { + if ( not exists $report_groups->{$group} ) { my $groupdesc = $input->param('groupdesc') // $group; - Koha::AuthorisedValue->new({ - category => 'REPORT_GROUP', - authorised_value => $group, - lib => $groupdesc, - })->store; - my $cache_key = "AuthorisedValues-REPORT_GROUP-0-".C4::Context->userenv->{"branch"}; - my $cache = Koha::Caches->get_instance(); - my $result = $cache->clear_from_cache($cache_key); + Koha::AuthorisedValue->new( + { + category => 'REPORT_GROUP', + authorised_value => $group, + lib => $groupdesc, + } + )->store; + my $cache_key = "AuthorisedValues-REPORT_GROUP-0-" . C4::Context->userenv->{"branch"}; + my $cache = Koha::Caches->get_instance(); + my $result = $cache->clear_from_cache($cache_key); } - if (defined $subgroup and $subgroup ne '') { - if (not exists $report_groups->{$group}->{subgroups}->{$subgroup}) { + if ( defined $subgroup and $subgroup ne '' ) { + if ( not exists $report_groups->{$group}->{subgroups}->{$subgroup} ) { my $subgroupdesc = $input->param('subgroupdesc') // $subgroup; - Koha::AuthorisedValue->new({ - category => 'REPORT_SUBGROUP', - authorised_value => $subgroup, - lib => $subgroupdesc, - lib_opac => $group, - })->store; - my $cache_key = "AuthorisedValues-REPORT_SUBGROUP-0-".C4::Context->userenv->{"branch"}; - my $cache = Koha::Caches->get_instance(); - my $result = $cache->clear_from_cache($cache_key); + Koha::AuthorisedValue->new( + { + category => 'REPORT_SUBGROUP', + authorised_value => $subgroup, + lib => $subgroupdesc, + lib_opac => $group, + } + )->store; + my $cache_key = "AuthorisedValues-REPORT_SUBGROUP-0-" . C4::Context->userenv->{"branch"}; + my $cache = Koha::Caches->get_instance(); + my $result = $cache->clear_from_cache($cache_key); } } } diff --git a/reports/issues_avg_stats.pl b/reports/issues_avg_stats.pl index e1270c9b7c..be0e665628 100755 --- a/reports/issues_avg_stats.pl +++ b/reports/issues_avg_stats.pl @@ -1,6 +1,5 @@ #!/usr/bin/perl - # Copyright 2000-2002 Katipo Communications # # This file is part of Koha. @@ -20,9 +19,9 @@ use Modern::Perl; use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Context; -use C4::Output qw( output_html_with_http_headers ); +use C4::Output qw( output_html_with_http_headers ); use C4::Reports qw( GetDelimiterChoices ); use Koha::ItemTypes; use Koha::Patron::Categories; @@ -36,74 +35,87 @@ plugin that shows a stats on borrowers =cut -my $input = CGI->new; -my $do_it=$input->param('do_it'); +my $input = CGI->new; +my $do_it = $input->param('do_it'); my $fullreportname = "reports/issues_avg_stats.tt"; -my $line = $input->param("Line"); -my $column = $input->param("Column"); -my @filters = $input->multi_param("Filter"); +my $line = $input->param("Line"); +my $column = $input->param("Column"); +my @filters = $input->multi_param("Filter"); -my $podsp = $input->param("IssueDisplay"); -my $rodsp = $input->param("ReturnDisplay"); -my $calc = $input->param("Cellvalue"); -my $output = $input->param("output"); +my $podsp = $input->param("IssueDisplay"); +my $rodsp = $input->param("ReturnDisplay"); +my $calc = $input->param("Cellvalue"); +my $output = $input->param("output"); my $basename = $input->param("basename"); #warn "calcul : ".$calc; -my ($template, $borrowernumber, $cookie) - = get_template_and_user({template_name => $fullreportname, - query => $input, - type => "intranet", - flagsrequired => {reports => '*'}, - }); -our $sep = C4::Context->csv_delimiter(scalar $input->param("sep")); -$template->param(do_it => $do_it, - ); +my ( $template, $borrowernumber, $cookie ) = get_template_and_user( + { + template_name => $fullreportname, + query => $input, + type => "intranet", + flagsrequired => { reports => '*' }, + } +); +our $sep = C4::Context->csv_delimiter( scalar $input->param("sep") ); +$template->param( + do_it => $do_it, +); if ($do_it) { -# Displaying results - my $results = calculate($line, $column, $rodsp, $podsp, $calc, \@filters); - if ($output eq "screen"){ -# Printing results to screen - $template->param(mainloop => $results); + + # Displaying results + my $results = calculate( $line, $column, $rodsp, $podsp, $calc, \@filters ); + if ( $output eq "screen" ) { + + # Printing results to screen + $template->param( mainloop => $results ); output_html_with_http_headers $input, $cookie, $template->output; exit; } else { -# Printing to a csv file - print $input->header(-type => 'application/vnd.sun.xml.calc', - -encoding => 'utf-8', - -attachment=>"$basename.csv", - -filename=>"$basename.csv" ); - my $cols = @$results[0]->{loopcol}; + + # Printing to a csv file + print $input->header( + -type => 'application/vnd.sun.xml.calc', + -encoding => 'utf-8', + -attachment => "$basename.csv", + -filename => "$basename.csv" + ); + my $cols = @$results[0]->{loopcol}; my $lines = @$results[0]->{looprow}; -# header top-right - print @$results[0]->{line} ."/". @$results[0]->{column} .$sep; -# Other header - foreach my $col ( @$cols ) { - print $col->{coltitle}.$sep; + + # header top-right + print @$results[0]->{line} . "/" . @$results[0]->{column} . $sep; + + # Other header + foreach my $col (@$cols) { + print $col->{coltitle} . $sep; } print "Total\n"; -# Table - foreach my $line ( @$lines ) { + + # Table + foreach my $line (@$lines) { my $x = $line->{loopcell}; - print $line->{rowtitle}.$sep; + print $line->{rowtitle} . $sep; foreach my $cell (@$x) { - print $cell->{value}.$sep; + print $cell->{value} . $sep; } print $line->{totalrow}; print "\n"; } -# footer + + # footer print "TOTAL"; $cols = @$results[0]->{loopfooter}; - foreach my $col ( @$cols ) { - print $sep.$col->{totalcol}; + foreach my $col (@$cols) { + print $sep. $col->{totalcol}; } - print $sep.@$results[0]->{total}; + print $sep. @$results[0]->{total}; exit; } -# Displaying choices + + # Displaying choices } else { - my $patron_categories = Koha::Patron::Categories->search({}, {order_by => ['description']}); + my $patron_categories = Koha::Patron::Categories->search( {}, { order_by => ['description'] } ); my $itemtypes = Koha::ItemTypes->search_with_localization; @@ -112,152 +124,152 @@ if ($do_it) { $req->execute; my @selects1; my $hassort1; - while (my ($value) =$req->fetchrow) { - $hassort1 =1 if ($value); + while ( my ($value) = $req->fetchrow ) { + $hassort1 = 1 if ($value); push @selects1, $value; } my $Sort1 = { - values => \@selects1, + values => \@selects1, }; - + $req = $dbh->prepare("select distinctrow sort2 from borrowers where sort2 is not null order by sort2"); $req->execute; my @selects2; my $hassort2; my $hglghtsort2; - while (my ($value) =$req->fetchrow) { - $hassort2 =1 if ($value); - $hglghtsort2= !($hassort1); + while ( my ($value) = $req->fetchrow ) { + $hassort2 = 1 if ($value); + $hglghtsort2 = !($hassort1); push @selects2, $value; } my $Sort2 = { - values => \@selects2, + values => \@selects2, }; - - my $CGIsepChoice=GetDelimiterChoices; - + + my $CGIsepChoice = GetDelimiterChoices; + $template->param( - patron_categories => $patron_categories, - itemtypes => $itemtypes, - hassort1 => $hassort1, - hassort2 => $hassort2, - HlghtSort2 => $hglghtsort2, - Sort1 => $Sort1, - Sort2 => $Sort2, - CGIsepChoice => $CGIsepChoice - ); -output_html_with_http_headers $input, $cookie, $template->output; + patron_categories => $patron_categories, + itemtypes => $itemtypes, + hassort1 => $hassort1, + hassort2 => $hassort2, + HlghtSort2 => $hglghtsort2, + Sort1 => $Sort1, + Sort2 => $Sort2, + CGIsepChoice => $CGIsepChoice + ); + output_html_with_http_headers $input, $cookie, $template->output; } - - - sub calculate { - my ($line, $column, $rodsp, $podsp, $process, $filters) = @_; + my ( $line, $column, $rodsp, $podsp, $process, $filters ) = @_; my @mainloop; my @loopfooter; my @loopcol; my @loopline; my @looprow; my %globalline; - my $grantotal =0; - my $itype = C4::Context->preference('item-level_itypes') ? "items.itype" : "biblioitems.itemtype"; -# extract parameters + my $grantotal = 0; + my $itype = C4::Context->preference('item-level_itypes') ? "items.itype" : "biblioitems.itemtype"; + + # extract parameters my $dbh = C4::Context->dbh; -# Filters -# Checking filters -# + # Filters + # Checking filters + # my @loopfilter; - for (my $i=0;$i<=6;$i++) { + for ( my $i = 0 ; $i <= 6 ; $i++ ) { my %cell; if ( @$filters[$i] ) { - if (($i==1) and (@$filters[$i-1])) { - $cell{err} = 1 if (@$filters[$i]<@$filters[$i-1]) ; + if ( ( $i == 1 ) and ( @$filters[ $i - 1 ] ) ) { + $cell{err} = 1 if ( @$filters[$i] < @$filters[ $i - 1 ] ); } $cell{filter} .= @$filters[$i]; - $cell{crit} .="Issue From" if ($i==0); - $cell{crit} .="Issue To" if ($i==1); - $cell{crit} .="Issue Month" if ($i==2); - $cell{crit} .="Issue Day" if ($i==3); - $cell{crit} .="Return From" if ($i==4); - $cell{crit} .="Return To" if ($i==5); - $cell{crit} .="Return Month" if ($i==6); - $cell{crit} .="Return Day" if ($i==7); - $cell{crit} .="Borrower Cat" if ($i==8); - $cell{crit} .="Doc Type" if ($i==9); - $cell{crit} .="Branch" if ($i==10); - $cell{crit} .="Sort1" if ($i==11); - $cell{crit} .="Sort2" if ($i==12); + $cell{crit} .= "Issue From" if ( $i == 0 ); + $cell{crit} .= "Issue To" if ( $i == 1 ); + $cell{crit} .= "Issue Month" if ( $i == 2 ); + $cell{crit} .= "Issue Day" if ( $i == 3 ); + $cell{crit} .= "Return From" if ( $i == 4 ); + $cell{crit} .= "Return To" if ( $i == 5 ); + $cell{crit} .= "Return Month" if ( $i == 6 ); + $cell{crit} .= "Return Day" if ( $i == 7 ); + $cell{crit} .= "Borrower Cat" if ( $i == 8 ); + $cell{crit} .= "Doc Type" if ( $i == 9 ); + $cell{crit} .= "Branch" if ( $i == 10 ); + $cell{crit} .= "Sort1" if ( $i == 11 ); + $cell{crit} .= "Sort2" if ( $i == 12 ); push @loopfilter, \%cell; } } - push @loopfilter,{crit=>"Issue Display",filter=>$rodsp} if ($rodsp); - push @loopfilter,{crit=>"Return Display",filter=>$podsp} if ($podsp); + push @loopfilter, { crit => "Issue Display", filter => $rodsp } if ($rodsp); + push @loopfilter, { crit => "Return Display", filter => $podsp } if ($podsp); - - my @linefilter; -# warn "filtres ".@filters[0]; -# warn "filtres ".@filters[1]; -# warn "filtres ".@filters[2]; -# warn "filtres ".@filters[3]; - $line = "old_issues.".$line if ($line=~/branchcode/) or ($line=~/timestamp/); - if ( $line=~/itemtype/ ) { $line = $itype; } - $linefilter[0] = @$filters[0] if ($line =~ /timestamp/ ) ; - $linefilter[1] = @$filters[1] if ($line =~ /timestamp/ ) ; - $linefilter[2] = @$filters[2] if ($line =~ /timestamp/ ) ; - $linefilter[3] = @$filters[3] if ($line =~ /timestamp/ ) ; - $linefilter[0] = @$filters[4] if ($line =~ /returndate/ ) ; - $linefilter[1] = @$filters[5] if ($line =~ /returndate/ ) ; - $linefilter[2] = @$filters[6] if ($line =~ /returndate/ ) ; - $linefilter[3] = @$filters[7] if ($line =~ /returndate/ ) ; - $linefilter[0] = @$filters[8] if ($line =~ /category/ ) ; - $linefilter[0] = @$filters[9] if ($line eq $itype); - $linefilter[0] = @$filters[10] if ($line =~ /branch/ ) ; - $linefilter[0] = @$filters[11] if ($line =~ /sort1/ ) ; - $linefilter[0] = @$filters[12] if ($line =~ /sort2/ ) ; - $column = "old_issues.".$column if (($column=~/branchcode/) or ($column=~/timestamp/)); - if ( $column=~/itemtype/ ) { $column = $itype; } - my @colfilter ; - $colfilter[0] = @$filters[0] if ($column =~ /timestamp/ ) ; - $colfilter[1] = @$filters[1] if ($column =~ /timestamp/ ) ; - $colfilter[2] = @$filters[2] if ($column =~ /timestamp/ ) ; - $colfilter[3] = @$filters[3] if ($column =~ /timestamp/ ) ; - $colfilter[0] = @$filters[4] if ($column =~ /returndate/ ) ; - $colfilter[1] = @$filters[5] if ($column =~ /returndate/ ) ; - $colfilter[2] = @$filters[6] if ($column =~ /returndate/ ) ; - $colfilter[3] = @$filters[7] if ($column =~ /returndate/ ) ; - $colfilter[0] = @$filters[8] if ($column =~ /category/ ) ; - $colfilter[0] = @$filters[9] if ($column eq $itype); - $colfilter[0] = @$filters[10] if ($column =~ /branch/ ) ; - $colfilter[0] = @$filters[11] if ($column =~ /sort1/ ) ; - $colfilter[0] = @$filters[12] if ($column =~ /sort2/ ) ; - -# 1st, loop rows. + # warn "filtres ".@filters[0]; + # warn "filtres ".@filters[1]; + # warn "filtres ".@filters[2]; + # warn "filtres ".@filters[3]; + $line = "old_issues." . $line if ( $line =~ /branchcode/ ) or ( $line =~ /timestamp/ ); + if ( $line =~ /itemtype/ ) { $line = $itype; } + $linefilter[0] = @$filters[0] if ( $line =~ /timestamp/ ); + $linefilter[1] = @$filters[1] if ( $line =~ /timestamp/ ); + $linefilter[2] = @$filters[2] if ( $line =~ /timestamp/ ); + $linefilter[3] = @$filters[3] if ( $line =~ /timestamp/ ); + $linefilter[0] = @$filters[4] if ( $line =~ /returndate/ ); + $linefilter[1] = @$filters[5] if ( $line =~ /returndate/ ); + $linefilter[2] = @$filters[6] if ( $line =~ /returndate/ ); + $linefilter[3] = @$filters[7] if ( $line =~ /returndate/ ); + $linefilter[0] = @$filters[8] if ( $line =~ /category/ ); + $linefilter[0] = @$filters[9] if ( $line eq $itype ); + $linefilter[0] = @$filters[10] if ( $line =~ /branch/ ); + $linefilter[0] = @$filters[11] if ( $line =~ /sort1/ ); + $linefilter[0] = @$filters[12] if ( $line =~ /sort2/ ); + + $column = "old_issues." . $column if ( ( $column =~ /branchcode/ ) or ( $column =~ /timestamp/ ) ); + if ( $column =~ /itemtype/ ) { $column = $itype; } + my @colfilter; + $colfilter[0] = @$filters[0] if ( $column =~ /timestamp/ ); + $colfilter[1] = @$filters[1] if ( $column =~ /timestamp/ ); + $colfilter[2] = @$filters[2] if ( $column =~ /timestamp/ ); + $colfilter[3] = @$filters[3] if ( $column =~ /timestamp/ ); + $colfilter[0] = @$filters[4] if ( $column =~ /returndate/ ); + $colfilter[1] = @$filters[5] if ( $column =~ /returndate/ ); + $colfilter[2] = @$filters[6] if ( $column =~ /returndate/ ); + $colfilter[3] = @$filters[7] if ( $column =~ /returndate/ ); + $colfilter[0] = @$filters[8] if ( $column =~ /category/ ); + $colfilter[0] = @$filters[9] if ( $column eq $itype ); + $colfilter[0] = @$filters[10] if ( $column =~ /branch/ ); + $colfilter[0] = @$filters[11] if ( $column =~ /sort1/ ); + $colfilter[0] = @$filters[12] if ( $column =~ /sort2/ ); + + # 1st, loop rows. my $linefield; - my $lineorder; - if ((($line =~/timestamp/) and ($podsp == 1)) or (($line =~/returndate/) and ($rodsp == 1))) { + my $lineorder; + if ( ( ( $line =~ /timestamp/ ) and ( $podsp == 1 ) ) or ( ( $line =~ /returndate/ ) and ( $rodsp == 1 ) ) ) { + #Display by day - $linefield .="dayname($line)"; - $lineorder .="weekday($line)"; - } elsif ((($line =~/timestamp/) and ($podsp == 2)) or (($line =~/returndate/) and ($rodsp == 2))) { + $linefield .= "dayname($line)"; + $lineorder .= "weekday($line)"; + } elsif ( ( ( $line =~ /timestamp/ ) and ( $podsp == 2 ) ) or ( ( $line =~ /returndate/ ) and ( $rodsp == 2 ) ) ) { + #Display by Month - $linefield .="monthname($line)"; - $lineorder .="month($line)"; - } elsif ((($line =~/timestamp/) and ($podsp == 3)) or (($line =~/returndate/) and ($rodsp == 3))) { + $linefield .= "monthname($line)"; + $lineorder .= "month($line)"; + } elsif ( ( ( $line =~ /timestamp/ ) and ( $podsp == 3 ) ) or ( ( $line =~ /returndate/ ) and ( $rodsp == 3 ) ) ) { + #Display by Year - $linefield .="Year($line)"; - $lineorder .= $line; - } elsif (($line=~/timestamp/) or ($line=~/returndate/)){ + $linefield .= "Year($line)"; + $lineorder .= $line; + } elsif ( ( $line =~ /timestamp/ ) or ( $line =~ /returndate/ ) ) { $linefield .= "date_format(\'$line\',\"%Y-%m-%d\")"; - $lineorder .= $line; + $lineorder .= $line; } else { $linefield .= $line; - $lineorder .= $line; - } - + $lineorder .= $line; + } + my $strsth; $strsth .= "select distinctrow $linefield FROM `old_issues` @@ -265,32 +277,32 @@ sub calculate { LEFT JOIN items ON old_issues.itemnumber=items.itemnumber LEFT JOIN biblioitems ON (biblioitems.biblioitemnumber=items.biblioitemnumber) WHERE 1"; - - if (($line=~/timestamp/) or ($line=~/returndate/)){ - if ($linefilter[1] and ($linefilter[0])){ - $strsth .= " AND $line BETWEEN '$linefilter[0]' AND '$linefilter[1]' " ; - } elsif ($linefilter[1]) { - $strsth .= " AND $line < \'$linefilter[1]\' " ; - } elsif ($linefilter[0]) { - $strsth .= " AND $line > \'$linefilter[0]\' " ; + + if ( ( $line =~ /timestamp/ ) or ( $line =~ /returndate/ ) ) { + if ( $linefilter[1] and ( $linefilter[0] ) ) { + $strsth .= " AND $line BETWEEN '$linefilter[0]' AND '$linefilter[1]' "; + } elsif ( $linefilter[1] ) { + $strsth .= " AND $line < \'$linefilter[1]\' "; + } elsif ( $linefilter[0] ) { + $strsth .= " AND $line > \'$linefilter[0]\' "; } - if ($linefilter[2]){ - $strsth .= " AND dayname($line) = '$linefilter[2]' " ; + if ( $linefilter[2] ) { + $strsth .= " AND dayname($line) = '$linefilter[2]' "; } - if ($linefilter[3]){ - $strsth .= " AND monthname($line) = '$linefilter[3]' " ; + if ( $linefilter[3] ) { + $strsth .= " AND monthname($line) = '$linefilter[3]' "; } - } elsif ($linefilter[0]) { + } elsif ( $linefilter[0] ) { $linefilter[0] =~ s/\*/%/g; - $strsth .= " AND $line LIKE '$linefilter[0]' " ; + $strsth .= " AND $line LIKE '$linefilter[0]' "; } - $strsth .=" GROUP BY $linefield"; - $strsth .=" ORDER BY $lineorder"; - - my $sth = $dbh->prepare( $strsth ); + $strsth .= " GROUP BY $linefield"; + $strsth .= " ORDER BY $lineorder"; + + my $sth = $dbh->prepare($strsth); $sth->execute; - while ( my ($celvalue) = $sth->fetchrow) { + while ( my ($celvalue) = $sth->fetchrow ) { my %cell; if ($celvalue) { $cell{rowtitle} = $celvalue; @@ -301,28 +313,33 @@ sub calculate { push @loopline, \%cell; } -# 2nd, loop cols. + # 2nd, loop cols. my $colfield; - my $colorder; - if ((($column =~/timestamp/) and ($podsp == 1)) or (($column =~/returndate/) and ($rodsp == 1))) { + my $colorder; + if ( ( ( $column =~ /timestamp/ ) and ( $podsp == 1 ) ) or ( ( $column =~ /returndate/ ) and ( $rodsp == 1 ) ) ) { + #Display by day - $colfield .="dayname($column)"; - $colorder .="weekday($column)"; - } elsif ((($column =~/timestamp/) and ($podsp == 2)) or (($column =~/returndate/) and ($rodsp == 2))) { + $colfield .= "dayname($column)"; + $colorder .= "weekday($column)"; + } elsif ( ( ( $column =~ /timestamp/ ) and ( $podsp == 2 ) ) + or ( ( $column =~ /returndate/ ) and ( $rodsp == 2 ) ) ) + { #Display by Month - $colfield .="monthname($column)"; - $colorder .="month($column)"; - } elsif ((($column =~/timestamp/) and ($podsp == 3)) or (($column =~/returndate/) and ($rodsp == 3))) { + $colfield .= "monthname($column)"; + $colorder .= "month($column)"; + } elsif ( ( ( $column =~ /timestamp/ ) and ( $podsp == 3 ) ) + or ( ( $column =~ /returndate/ ) and ( $rodsp == 3 ) ) ) + { #Display by Year - $colfield .="Year($column)"; + $colfield .= "Year($column)"; $colorder .= $column; - } elsif (($column=~/timestamp/) or ($column=~/returndate/)){ - $colfield .= 'date_format( '."'".$column."'". ', "%Y-%m-%d")'; + } elsif ( ( $column =~ /timestamp/ ) or ( $column =~ /returndate/ ) ) { + $colfield .= 'date_format( ' . "'" . $column . "'" . ', "%Y-%m-%d")'; $colorder .= $column; } else { $colfield .= $column; $colorder .= $column; - } + } my $strsth2; $strsth2 .= "SELECT distinctrow $colfield @@ -331,187 +348,216 @@ sub calculate { LEFT JOIN items ON items.itemnumber=old_issues.itemnumber LEFT JOIN biblioitems ON (biblioitems.biblioitemnumber=items.biblioitemnumber) WHERE 1"; - - if (($column=~/timestamp/) or ($column=~/returndate/)){ - if ($colfilter[1] and ($colfilter[0])){ - $strsth2 .= " AND $column BETWEEN '$colfilter[0]' AND '$colfilter[1]' " ; - } elsif ($colfilter[1]) { - $strsth2 .= " AND $column < '$colfilter[1]' " ; - } elsif ($colfilter[0]) { - $strsth2 .= " AND $column > '$colfilter[0]' " ; + + if ( ( $column =~ /timestamp/ ) or ( $column =~ /returndate/ ) ) { + if ( $colfilter[1] and ( $colfilter[0] ) ) { + $strsth2 .= " AND $column BETWEEN '$colfilter[0]' AND '$colfilter[1]' "; + } elsif ( $colfilter[1] ) { + $strsth2 .= " AND $column < '$colfilter[1]' "; + } elsif ( $colfilter[0] ) { + $strsth2 .= " AND $column > '$colfilter[0]' "; } - if ($colfilter[2]){ - $strsth2 .= " AND dayname($column) = '$colfilter[2]' " ; + if ( $colfilter[2] ) { + $strsth2 .= " AND dayname($column) = '$colfilter[2]' "; } - if ($colfilter[3]){ - $strsth2 .= " AND monthname($column) = '$colfilter[3]' " ; + if ( $colfilter[3] ) { + $strsth2 .= " AND monthname($column) = '$colfilter[3]' "; } - } elsif ($colfilter[0]) { + } elsif ( $colfilter[0] ) { $colfilter[0] =~ s/\*/%/g; - $strsth2 .= " AND $column LIKE '$colfilter[0]' " ; + $strsth2 .= " AND $column LIKE '$colfilter[0]' "; } - $strsth2 .=" GROUP BY $colfield"; - $strsth2 .=" ORDER BY $colorder"; - - my $sth2 = $dbh->prepare( $strsth2 ); + $strsth2 .= " GROUP BY $colfield"; + $strsth2 .= " ORDER BY $colorder"; + + my $sth2 = $dbh->prepare($strsth2); $sth2->execute; - while (my ($celvalue) = $sth2->fetchrow) { + while ( my ($celvalue) = $sth2->fetchrow ) { my %cell; my %ft; -# warn "coltitle :".$celvalue; + + # warn "coltitle :".$celvalue; $cell{coltitle} = $celvalue; - $ft{totalcol} = 0; + $ft{totalcol} = 0; push @loopcol, \%cell; } -# warn "fin des titres colonnes"; - my $i=0; - my $hilighted=-1; - + # warn "fin des titres colonnes"; + + my $i = 0; + my $hilighted = -1; + #Initialization of cell values..... my %table; my %wgttable; my %cnttable; - -# warn "init table"; - foreach my $row ( @loopline ) { - foreach my $col ( @loopcol ) { -# warn " init table : $row->{rowtitle} / $col->{coltitle} "; - $table{$row->{rowtitle}}->{$col->{coltitle}}=0; + + # warn "init table"; + foreach my $row (@loopline) { + foreach my $col (@loopcol) { + + # warn " init table : $row->{rowtitle} / $col->{coltitle} "; + $table{ $row->{rowtitle} }->{ $col->{coltitle} } = 0; } - $table{$row->{rowtitle}}->{totalrow}=0; + $table{ $row->{rowtitle} }->{totalrow} = 0; } -# preparing calculation - my $strcalc ; - -# Processing average loanperiods - $strcalc .= "SELECT $linefield, $colfield, "; - $strcalc .= " issuedate, returndate, COUNT(*) FROM `old_issues`,borrowers,biblioitems LEFT JOIN items ON (biblioitems.biblioitemnumber=items.biblioitemnumber) WHERE old_issues.itemnumber=items.itemnumber AND old_issues.borrowernumber=borrowers.borrowernumber"; + # preparing calculation + my $strcalc; + + # Processing average loanperiods + $strcalc .= "SELECT $linefield, $colfield, "; + $strcalc .= + " issuedate, returndate, COUNT(*) FROM `old_issues`,borrowers,biblioitems LEFT JOIN items ON (biblioitems.biblioitemnumber=items.biblioitemnumber) WHERE old_issues.itemnumber=items.itemnumber AND old_issues.borrowernumber=borrowers.borrowernumber"; + + @$filters[0] =~ s/\*/%/g if ( @$filters[0] ); + $strcalc .= " AND old_issues.timestamp > '" . @$filters[0] . "'" if ( @$filters[0] ); + @$filters[1] =~ s/\*/%/g if ( @$filters[1] ); + $strcalc .= " AND old_issues.timestamp < '" . @$filters[1] . "'" if ( @$filters[1] ); + @$filters[4] =~ s/\*/%/g if ( @$filters[4] ); + $strcalc .= " AND old_issues.returndate > '" . @$filters[4] . "'" if ( @$filters[4] ); + @$filters[5] =~ s/\*/%/g if ( @$filters[5] ); + $strcalc .= " AND old_issues.returndate < '" . @$filters[5] . "'" if ( @$filters[5] ); + @$filters[8] =~ s/\*/%/g if ( @$filters[8] ); + $strcalc .= " AND borrowers.categorycode like '" . @$filters[8] . "'" if ( @$filters[8] ); + @$filters[9] =~ s/\*/%/g if ( @$filters[9] ); + $strcalc .= " AND $itype like '" . @$filters[9] . "'" if ( @$filters[9] ); + @$filters[10] =~ s/\*/%/g if ( @$filters[10] ); + $strcalc .= " AND old_issues.branchcode like '" . @$filters[10] . "'" if ( @$filters[10] ); + @$filters[11] =~ s/\*/%/g if ( @$filters[11] ); + $strcalc .= " AND borrowers.sort1 like '" . @$filters[11] . "'" if ( @$filters[11] ); + @$filters[12] =~ s/\*/%/g if ( @$filters[12] ); + $strcalc .= " AND borrowers.sort2 like '" . @$filters[12] . "'" if ( @$filters[12] ); + $strcalc .= " AND dayname(timestamp) like '" . @$filters[2] . "'" if ( @$filters[2] ); + $strcalc .= " AND monthname(timestamp) like '" . @$filters[3] . "'" if ( @$filters[3] ); + $strcalc .= " AND dayname(returndate) like '" . @$filters[5] . "'" if ( @$filters[5] ); + $strcalc .= " AND monthname(returndate) like '" . @$filters[6] . "'" if ( @$filters[6] ); - @$filters[0]=~ s/\*/%/g if (@$filters[0]); - $strcalc .= " AND old_issues.timestamp > '" . @$filters[0] ."'" if ( @$filters[0] ); - @$filters[1]=~ s/\*/%/g if (@$filters[1]); - $strcalc .= " AND old_issues.timestamp < '" . @$filters[1] ."'" if ( @$filters[1] ); - @$filters[4]=~ s/\*/%/g if (@$filters[4]); - $strcalc .= " AND old_issues.returndate > '" . @$filters[4] ."'" if ( @$filters[4] ); - @$filters[5]=~ s/\*/%/g if (@$filters[5]); - $strcalc .= " AND old_issues.returndate < '" . @$filters[5] ."'" if ( @$filters[5] ); - @$filters[8]=~ s/\*/%/g if (@$filters[8]); - $strcalc .= " AND borrowers.categorycode like '" . @$filters[8] ."'" if ( @$filters[8] ); - @$filters[9]=~ s/\*/%/g if (@$filters[9]); - $strcalc .= " AND $itype like '" . @$filters[9] ."'" if ( @$filters[9] ); - @$filters[10]=~ s/\*/%/g if (@$filters[10]); - $strcalc .= " AND old_issues.branchcode like '" . @$filters[10] ."'" if ( @$filters[10] ); - @$filters[11]=~ s/\*/%/g if (@$filters[11]); - $strcalc .= " AND borrowers.sort1 like '" . @$filters[11] ."'" if ( @$filters[11] ); - @$filters[12]=~ s/\*/%/g if (@$filters[12]); - $strcalc .= " AND borrowers.sort2 like '" . @$filters[12] ."'" if ( @$filters[12] ); - $strcalc .= " AND dayname(timestamp) like '" . @$filters[2]."'" if (@$filters[2]); - $strcalc .= " AND monthname(timestamp) like '" . @$filters[3] ."'" if ( @$filters[3] ); - $strcalc .= " AND dayname(returndate) like '" . @$filters[5]."'" if (@$filters[5]); - $strcalc .= " AND monthname(returndate) like '" . @$filters[6] ."'" if ( @$filters[6] ); - $strcalc .= " group by $linefield, $colfield, issuedate, returndate order by $linefield, $colfield"; - + my $dbcalc = $dbh->prepare($strcalc); $dbcalc->execute; -# warn "filling table"; - my $issues_count=0; - my $loanlength; + + # warn "filling table"; + my $issues_count = 0; + my $loanlength; my $emptycol; - while (my @data = $dbcalc->fetchrow) { - my ($row, $col, $issuedate, $returndate, $weight)=@data; -# warn "filling table $row / $col / $issuedate / $returndate /$weight"; - $emptycol=1 if (!defined($col)); - $col = "zzEMPTY" if (!defined($col)); - $row = "zzEMPTY" if (!defined($row)); - # DateCalc returns => 0:0:WK:DD:HH:MM:SS the weeks, days, hours, minutes, - # and seconds between the two - $loanlength = Delta_Days(split(/-/,$issuedate),split (/-/,$returndate)) ; - # warn "512 Same row and col DateCalc returns :$loanlength with return ". $returndate ."issue ". $issuedate ."weight : ". $weight; - # warn "513 row :".$row." column :".$col; - $table{$row}->{$col}+=$weight*$loanlength; - # $table{$row}->{totalrow}+=$weight*$loanlength; - $cnttable{$row}->{$col}= 1; - $wgttable{$row}->{$col}+=$weight; + while ( my @data = $dbcalc->fetchrow ) { + my ( $row, $col, $issuedate, $returndate, $weight ) = @data; + + # warn "filling table $row / $col / $issuedate / $returndate /$weight"; + $emptycol = 1 if ( !defined($col) ); + $col = "zzEMPTY" if ( !defined($col) ); + $row = "zzEMPTY" if ( !defined($row) ); + + # DateCalc returns => 0:0:WK:DD:HH:MM:SS the weeks, days, hours, minutes, + # and seconds between the two + $loanlength = Delta_Days( split( /-/, $issuedate ), split( /-/, $returndate ) ); + + # warn "512 Same row and col DateCalc returns :$loanlength with return ". $returndate ."issue ". $issuedate ."weight : ". $weight; + # warn "513 row :".$row." column :".$col; + $table{$row}->{$col} += $weight * $loanlength; + + # $table{$row}->{totalrow}+=$weight*$loanlength; + $cnttable{$row}->{$col} = 1; + $wgttable{$row}->{$col} += $weight; } - - push @loopcol,{coltitle => "NULL"} if ($emptycol); - + + push @loopcol, { coltitle => "NULL" } if ($emptycol); + foreach my $row ( sort keys %table ) { my @loopcell; - #@loopcol ensures the order for columns is common with column titles - # and the number matches the number of columns - my $colcount=0; - foreach my $col ( @loopcol ) { + + #@loopcol ensures the order for columns is common with column titles + # and the number matches the number of columns + my $colcount = 0; + foreach my $col (@loopcol) { my $value; - if ($table{$row}->{ - ( ( $col->{coltitle} eq 'NULL' ) - or ( $col->{coltitle} eq q{} ) - ) ? 'zzEMPTY' : $col->{coltitle} + if ( + $table{$row}->{ + ( + ( $col->{coltitle} eq 'NULL' ) + or ( $col->{coltitle} eq q{} ) + ) ? 'zzEMPTY' : $col->{coltitle} } - ) { + ) + { $value = $table{$row}->{ - ( ( $col->{coltitle} eq 'NULL' ) - or ( $col->{coltitle} eq q{} ) - ) ? 'zzEMPTY' : $col->{coltitle} - } / $wgttable{$row}->{ - ( ( $col->{coltitle} eq 'NULL' ) - or ( $col->{coltitle} eq q{} ) - ) ? 'zzEMPTY' : $col->{coltitle} - }; + ( + ( $col->{coltitle} eq 'NULL' ) + or ( $col->{coltitle} eq q{} ) + ) ? 'zzEMPTY' : $col->{coltitle} + } / $wgttable{$row}->{ + ( + ( $col->{coltitle} eq 'NULL' ) + or ( $col->{coltitle} eq q{} ) + ) ? 'zzEMPTY' : $col->{coltitle} + }; } - $table{$row}->{(($col->{coltitle} eq "NULL")or ($col->{coltitle} eq ""))?"zzEMPTY":$col->{coltitle}} = $value; - $table{$row}->{totalrow}+=$value; + $table{$row} + ->{ ( ( $col->{coltitle} eq "NULL" ) or ( $col->{coltitle} eq "" ) ) ? "zzEMPTY" : $col->{coltitle} } = + $value; + $table{$row}->{totalrow} += $value; + #warn "row : $row col:$col $cnttable{$row}->{(($col->{coltitle} eq \"NULL\")or ($col->{coltitle} eq \"\"))?\"zzEMPTY\":$col->{coltitle}}"; - $colcount+=$cnttable{$row}->{(($col->{coltitle} eq "NULL")or ($col->{coltitle} eq ""))?"zzEMPTY":$col->{coltitle}}; - push @loopcell, {value => ($value)?sprintf("%.2f",$value):0 } ; + $colcount += $cnttable{$row} + ->{ ( ( $col->{coltitle} eq "NULL" ) or ( $col->{coltitle} eq "" ) ) ? "zzEMPTY" : $col->{coltitle} }; + push @loopcell, { value => ($value) ? sprintf( "%.2f", $value ) : 0 }; } + #warn "row : $row colcount:$colcount"; my $total; if ( $colcount > 0 ) { $total = $table{$row}->{totalrow} / $colcount; } push @looprow, - { 'rowtitle' => ( $row eq "zzEMPTY" ) ? "NULL" : $row, - 'loopcell' => \@loopcell, + { + 'rowtitle' => ( $row eq "zzEMPTY" ) ? "NULL" : $row, + 'loopcell' => \@loopcell, 'hilighted' => ( $hilighted > 0 ), 'totalrow' => ($total) ? sprintf( "%.2f", $total ) : 0 - }; + }; $hilighted = -$hilighted; } -# -# # warn "footer processing"; - foreach my $col ( @loopcol ) { - my $total=0; - my $nbrow=0; - foreach my $row ( @looprow ) { - $total += $cnttable{($row->{rowtitle} eq "NULL")?"zzEMPTY":$row->{rowtitle}}->{($col->{coltitle} eq "NULL")?"zzEMPTY":$col->{coltitle}}*$table{($row->{rowtitle} eq "NULL")?"zzEMPTY":$row->{rowtitle}}->{($col->{coltitle} eq "NULL")?"zzEMPTY":$col->{coltitle}}; - $nbrow +=$cnttable{($row->{rowtitle} eq "NULL")?"zzEMPTY":$row->{rowtitle}}->{($col->{coltitle} eq "NULL")?"zzEMPTY":$col->{coltitle}};; -# warn "value added ".$table{$row->{rowtitle}}->{$col->{coltitle}}. "for line ".$row->{rowtitle}; + # + # # warn "footer processing"; + foreach my $col (@loopcol) { + my $total = 0; + my $nbrow = 0; + foreach my $row (@looprow) { + $total += + $cnttable{ ( $row->{rowtitle} eq "NULL" ) ? "zzEMPTY" : $row->{rowtitle} } + ->{ ( $col->{coltitle} eq "NULL" ) ? "zzEMPTY" : $col->{coltitle} } * + $table{ ( $row->{rowtitle} eq "NULL" ) ? "zzEMPTY" : $row->{rowtitle} } + ->{ ( $col->{coltitle} eq "NULL" ) ? "zzEMPTY" : $col->{coltitle} }; + $nbrow += $cnttable{ ( $row->{rowtitle} eq "NULL" ) ? "zzEMPTY" : $row->{rowtitle} } + ->{ ( $col->{coltitle} eq "NULL" ) ? "zzEMPTY" : $col->{coltitle} }; + + # warn "value added ".$table{$row->{rowtitle}}->{$col->{coltitle}}. "for line ".$row->{rowtitle}; } -# warn "summ for column ".$col->{coltitle}." = ".$total; - $total = $total/$nbrow if ($nbrow); - push @loopfooter, {'totalcol' => ($total)?sprintf("%.2f",$total):0}; - + + # warn "summ for column ".$col->{coltitle}." = ".$total; + $total = $total / $nbrow if ($nbrow); + push @loopfooter, { 'totalcol' => ($total) ? sprintf( "%.2f", $total ) : 0 }; + } - # the header of the table - $globalline{loopfilter}=\@loopfilter; + $globalline{loopfilter} = \@loopfilter; + # the core of the table $globalline{looprow} = \@looprow; $globalline{loopcol} = \@loopcol; -# # the foot (totals by borrower type) + + # # the foot (totals by borrower type) $globalline{loopfooter} = \@loopfooter; - $globalline{total}= $grantotal; - $globalline{line} = $line; - $globalline{column} = $column; - push @mainloop,\%globalline; + $globalline{total} = $grantotal; + $globalline{line} = $line; + $globalline{column} = $column; + push @mainloop, \%globalline; return \@mainloop; } diff --git a/reports/issues_stats.pl b/reports/issues_stats.pl index 52e904ed5f..a3d3adf13e 100755 --- a/reports/issues_stats.pl +++ b/reports/issues_stats.pl @@ -23,8 +23,8 @@ use CGI qw ( -utf8 ); use C4::Auth qw( get_template_and_user ); use C4::Context; -use C4::Koha qw( GetAuthorisedValues ); -use C4::Output qw( output_html_with_http_headers ); +use C4::Koha qw( GetAuthorisedValues ); +use C4::Output qw( output_html_with_http_headers ); use C4::Reports qw( GetDelimiterChoices ); use Koha::AuthorisedValues; @@ -41,55 +41,67 @@ Plugin that shows circulation stats =cut -my $input = CGI->new; +my $input = CGI->new; my $fullreportname = "reports/issues_stats.tt"; -my $do_it = $input->param('do_it'); -my $line = $input->param("Line"); -my $column = $input->param("Column"); -my @filters = $input->multi_param("Filter"); -my $podsp = $input->param("DisplayBy"); -my $type = $input->param("PeriodTypeSel"); -my $daysel = $input->param("PeriodDaySel"); -my $monthsel = $input->param("PeriodMonthSel"); -my $calc = $input->param("Cellvalue"); -my $output = $input->param("output"); -my $basename = $input->param("basename"); +my $do_it = $input->param('do_it'); +my $line = $input->param("Line"); +my $column = $input->param("Column"); +my @filters = $input->multi_param("Filter"); +my $podsp = $input->param("DisplayBy"); +my $type = $input->param("PeriodTypeSel"); +my $daysel = $input->param("PeriodDaySel"); +my $monthsel = $input->param("PeriodMonthSel"); +my $calc = $input->param("Cellvalue"); +my $output = $input->param("output"); +my $basename = $input->param("basename"); my $attribute_filters; my $vars = $input->Vars; -foreach(keys %$vars) { - if(/^Filter_borrower_attributes\.(.*)/) { +foreach ( keys %$vars ) { + if (/^Filter_borrower_attributes\.(.*)/) { $attribute_filters->{$1} = $vars->{$_}; } } - -my ($template, $borrowernumber, $cookie) = get_template_and_user({ - template_name => $fullreportname, - query => $input, - type => "intranet", - flagsrequired => {reports => '*'}, -}); -our $sep = C4::Context->csv_delimiter(scalar $input->param("sep")); -$template->param(do_it => $do_it, +my ( $template, $borrowernumber, $cookie ) = get_template_and_user( + { + template_name => $fullreportname, + query => $input, + type => "intranet", + flagsrequired => { reports => '*' }, + } +); +our $sep = C4::Context->csv_delimiter( scalar $input->param("sep") ); +$template->param( + do_it => $do_it, ); our $itemtypes = Koha::ItemTypes->search_with_localization->unblessed; -our @patron_categories = Koha::Patron::Categories->search_with_library_limits({}, {order_by => ['description']})->as_list; +our @patron_categories = + Koha::Patron::Categories->search_with_library_limits( {}, { order_by => ['description'] } )->as_list; -our $locations = { map { ( $_->{authorised_value} => $_->{lib} ) } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.location' }, { order_by => ['description'] } ) }; -our $ccodes = { map { ( $_->{authorised_value} => $_->{lib} ) } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.ccode' }, { order_by => ['description'] } ) }; +our $locations = { + map { ( $_->{authorised_value} => $_->{lib} ) } Koha::AuthorisedValues->get_descriptions_by_koha_field( + { frameworkcode => '', kohafield => 'items.location' }, { order_by => ['description'] } + ) +}; +our $ccodes = { + map { ( $_->{authorised_value} => $_->{lib} ) } Koha::AuthorisedValues->get_descriptions_by_koha_field( + { frameworkcode => '', kohafield => 'items.ccode' }, { order_by => ['description'] } + ) +}; our $Bsort1 = GetAuthorisedValues("Bsort1"); our $Bsort2 = GetAuthorisedValues("Bsort2"); -my ($hassort1,$hassort2); -$hassort1=1 if $Bsort1; -$hassort2=1 if $Bsort2; +my ( $hassort1, $hassort2 ); +$hassort1 = 1 if $Bsort1; +$hassort2 = 1 if $Bsort2; if ($do_it) { + # Displaying results - my $results = calculate( $line, $column, $podsp, $type, $daysel, $monthsel, $calc, \@filters, $attribute_filters); + my $results = calculate( $line, $column, $podsp, $type, $daysel, $monthsel, $calc, \@filters, $attribute_filters ); if ( $output eq "screen" ) { # Printing results to screen @@ -127,56 +139,54 @@ if ($do_it) { # footer print "TOTAL"; $cols = @$results[0]->{loopfooter}; - print map {$sep.$_->{totalcol}} @$cols; - print $sep.@$results[0]->{total}; + print map { $sep . $_->{totalcol} } @$cols; + print $sep. @$results[0]->{total}; } exit; } - my $dbh = C4::Context->dbh; - # location list +# location list my @locations; -foreach (sort keys %$locations) { - push @locations, { code => $_, description => "$_ - " . $locations->{$_} }; +foreach ( sort keys %$locations ) { + push @locations, { code => $_, description => "$_ - " . $locations->{$_} }; } - + my @ccodes; -foreach (sort {$ccodes->{$a} cmp $ccodes->{$b}} keys %$ccodes) { - push @ccodes, { code => $_, description => $ccodes->{$_} }; +foreach ( sort { $ccodes->{$a} cmp $ccodes->{$b} } keys %$ccodes ) { + push @ccodes, { code => $_, description => $ccodes->{$_} }; } -my $CGIextChoice = ( 'CSV' ); # FIXME translation -my $CGIsepChoice=GetDelimiterChoices; +my $CGIextChoice = ('CSV'); # FIXME translation +my $CGIsepChoice = GetDelimiterChoices; -my $library_id = C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef; -my $attribute_types = Koha::Patron::Attribute::Types->search_with_library_limits({}, {}, $library_id); +my $library_id = C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef; +my $attribute_types = Koha::Patron::Attribute::Types->search_with_library_limits( {}, {}, $library_id ); my %attribute_types_by_class; -while ( my ( $attribute_type ) = $attribute_types->next ) { +while ( my ($attribute_type) = $attribute_types->next ) { $attribute_type = $attribute_type->unblessed; - if ($attribute_type->{authorised_value_category}) { - my $authorised_values = C4::Koha::GetAuthorisedValues( - $attribute_type->{authorised_value_category}); + if ( $attribute_type->{authorised_value_category} ) { + my $authorised_values = C4::Koha::GetAuthorisedValues( $attribute_type->{authorised_value_category} ); foreach my $authorised_value (@$authorised_values) { push @{ $attribute_type->{authorised_values} }, $authorised_value; } } - push @{ $attribute_types_by_class{$attribute_type->{class}} }, $attribute_type; + push @{ $attribute_types_by_class{ $attribute_type->{class} } }, $attribute_type; } $template->param( - categoryloop => \@patron_categories, - itemtypes => $itemtypes, - locationloop => \@locations, - ccodeloop => \@ccodes, - hassort1 => $hassort1, - hassort2 => $hassort2, - Bsort1 => $Bsort1, - Bsort2 => $Bsort2, - CGIextChoice => $CGIextChoice, - CGIsepChoice => $CGIsepChoice, + categoryloop => \@patron_categories, + itemtypes => $itemtypes, + locationloop => \@locations, + ccodeloop => \@ccodes, + hassort1 => $hassort1, + hassort2 => $hassort2, + Bsort1 => $Bsort1, + Bsort2 => $Bsort2, + CGIextChoice => $CGIextChoice, + CGIsepChoice => $CGIsepChoice, attribute_types_by_class => \%attribute_types_by_class, ); output_html_with_http_headers $input, $cookie, $template->output; @@ -193,14 +203,14 @@ sub calculate { # extract parameters my $dbh = C4::Context->dbh; - my ($line_attribute_type, $column_attribute_type); - if($line =~ /^borrower_attributes\.(.*)/) { + my ( $line_attribute_type, $column_attribute_type ); + if ( $line =~ /^borrower_attributes\.(.*)/ ) { $line_attribute_type = $1; - $line = "borrower_attributes.attribute"; + $line = "borrower_attributes.attribute"; } - if($column =~ /^borrower_attributes\.(.*)/) { + if ( $column =~ /^borrower_attributes\.(.*)/ ) { $column_attribute_type = $1; - $column = "borrower_attributes.attribute"; + $column = "borrower_attributes.attribute"; } # Filters @@ -213,59 +223,60 @@ sub calculate { if ( ( $i == 1 ) and ( @$filters[ $i - 1 ] ) ) { $cell{err} = 1 if ( @$filters[$i] < @$filters[ $i - 1 ] ); } - # format the dates filters, otherwise just fill as is + + # format the dates filters, otherwise just fill as is $cell{filter} = @$filters[$i]; - $cell{crit} = $i; + $cell{crit} = $i; push @loopfilter, \%cell; } - foreach (keys %$attribute_filters) { + foreach ( keys %$attribute_filters ) { next unless $attribute_filters->{$_}; push @loopfilter, { crit => "$_ =", filter => $attribute_filters->{$_} }; } push @loopfilter, { crit => "Event", filter => $type }; - push @loopfilter, { crit => "Display by", filter => $dsp } if ($dsp); - push @loopfilter, { crit => "Select Day", filter => $daysel } if ($daysel); + push @loopfilter, { crit => "Display by", filter => $dsp } if ($dsp); + push @loopfilter, { crit => "Select Day", filter => $daysel } if ($daysel); push @loopfilter, { crit => "Select Month", filter => $monthsel } if ($monthsel); my @linefilter; - my ( $colsource, $linesource ) = ('', ''); + my ( $colsource, $linesource ) = ( '', '' ); $linefilter[1] = @$filters[1] if ( $line =~ /datetime/ ); $linefilter[0] = - ( $line =~ /datetime/ ) ? @$filters[0] - : ( $line =~ /category/ ) ? @$filters[2] - : ( $line =~ /itemtype/ ) ? @$filters[3] - : ( $line =~ /^branch/ ) ? @$filters[4] - : ( $line =~ /ccode/ ) ? @$filters[5] - : ( $line =~ /location/ ) ? @$filters[6] - : ( $line =~ /sort1/ ) ? @$filters[9] - : ( $line =~ /sort2/ ) ? @$filters[10] - : ( $line =~ /homebranch/) ? @$filters[11] - : ( $line =~ /holdingbranch/) ? @$filters[12] - : ( $line =~ /borrowers.branchcode/ ) ? @$filters[13] - : ( $line_attribute_type ) ? $attribute_filters->{$line_attribute_type} - : undef; + ( $line =~ /datetime/ ) ? @$filters[0] + : ( $line =~ /category/ ) ? @$filters[2] + : ( $line =~ /itemtype/ ) ? @$filters[3] + : ( $line =~ /^branch/ ) ? @$filters[4] + : ( $line =~ /ccode/ ) ? @$filters[5] + : ( $line =~ /location/ ) ? @$filters[6] + : ( $line =~ /sort1/ ) ? @$filters[9] + : ( $line =~ /sort2/ ) ? @$filters[10] + : ( $line =~ /homebranch/ ) ? @$filters[11] + : ( $line =~ /holdingbranch/ ) ? @$filters[12] + : ( $line =~ /borrowers.branchcode/ ) ? @$filters[13] + : ($line_attribute_type) ? $attribute_filters->{$line_attribute_type} + : undef; if ( $line =~ /ccode/ or $line =~ /location/ or $line =~ /homebranch/ or $line =~ /holdingbranch/ ) { - $linesource = 'items'; - } + $linesource = 'items'; + } - my @colfilter; - $colfilter[1] = @$filters[1] if ($column =~ /datetime/); - $colfilter[0] = - ( $column =~ /datetime/ ) ? @$filters[0] - : ( $column =~ /category/ ) ? @$filters[2] - : ( $column =~ /itemtype/ ) ? @$filters[3] - : ( $column =~ /^branch/ ) ? @$filters[4] - : ( $column =~ /ccode/ ) ? @$filters[5] - : ( $column =~ /location/ ) ? @$filters[6] - : ( $column =~ /sort1/ ) ? @$filters[9] - : ( $column =~ /sort1/ ) ? @$filters[10] - : ( $column =~ /homebranch/) ? @$filters[11] - : ( $column =~ /holdingbranch/) ? @$filters[12] - : ( $column =~ /borrowers.branchcode/ ) ? @$filters[13] - : ( $column_attribute_type ) ? $attribute_filters->{$column_attribute_type} - : undef; + my @colfilter; + $colfilter[1] = @$filters[1] if ( $column =~ /datetime/ ); + $colfilter[0] = + ( $column =~ /datetime/ ) ? @$filters[0] + : ( $column =~ /category/ ) ? @$filters[2] + : ( $column =~ /itemtype/ ) ? @$filters[3] + : ( $column =~ /^branch/ ) ? @$filters[4] + : ( $column =~ /ccode/ ) ? @$filters[5] + : ( $column =~ /location/ ) ? @$filters[6] + : ( $column =~ /sort1/ ) ? @$filters[9] + : ( $column =~ /sort1/ ) ? @$filters[10] + : ( $column =~ /homebranch/ ) ? @$filters[11] + : ( $column =~ /holdingbranch/ ) ? @$filters[12] + : ( $column =~ /borrowers.branchcode/ ) ? @$filters[13] + : ($column_attribute_type) ? $attribute_filters->{$column_attribute_type} + : undef; if ( $column =~ /ccode/ or $column =~ /location/ or $column =~ /homebranch/ or $column =~ /holdingbranch/ ) { $colsource = 'items'; @@ -277,30 +288,30 @@ sub calculate { # by Day, Month, Year or Hour (1,2,3,4 respectively) $linefield = - ( $dsp == 1 ) ? " dayname($line)" - : ( $dsp == 2 ) ? "monthname($line)" - : ( $dsp == 3 ) ? " Year($line)" - : ( $dsp == 4 ) ? "extract(hour from $line)" - : 'date_format(`datetime`,"%Y-%m-%d")'; # Probably should be left alone or passed through Koha::Dates + ( $dsp == 1 ) ? " dayname($line)" + : ( $dsp == 2 ) ? "monthname($line)" + : ( $dsp == 3 ) ? " Year($line)" + : ( $dsp == 4 ) ? "extract(hour from $line)" + : 'date_format(`datetime`,"%Y-%m-%d")'; # Probably should be left alone or passed through Koha::Dates } else { $linefield = $line; } my $lineorder = - ( $linefield =~ /dayname/ ) ? "weekday($line)" - : ( $linefield =~ /^month/ ) ? " month($line)" - : $linefield; + ( $linefield =~ /dayname/ ) ? "weekday($line)" + : ( $linefield =~ /^month/ ) ? " month($line)" + : $linefield; my $strsth; - if($line_attribute_type) { + if ($line_attribute_type) { $strsth = "SELECT attribute FROM borrower_attributes WHERE code = '$line_attribute_type' "; } else { $strsth = "SELECT distinctrow $linefield FROM statistics "; # get stats on items if ccode or location, otherwise borrowers. $strsth .= - ( $linesource eq 'items' ) - ? " LEFT JOIN items ON (statistics.itemnumber = items.itemnumber) " - : " LEFT JOIN borrowers ON (statistics.borrowernumber = borrowers.borrowernumber) "; + ( $linesource eq 'items' ) + ? " LEFT JOIN items ON (statistics.itemnumber = items.itemnumber) " + : " LEFT JOIN borrowers ON (statistics.borrowernumber = borrowers.borrowernumber) "; $strsth .= " WHERE $line IS NOT NULL "; $strsth .= " AND $line != '' " if $line ne "datetime"; } @@ -323,7 +334,7 @@ sub calculate { $strsth .= " group by $linefield order by $lineorder "; push @loopfilter, { crit => 'SQL =', sql => 1, filter => $strsth }; my $sth = $dbh->prepare($strsth); - if ( (@linefilter) and ($linefilter[0]) and ($linefilter[1]) ) { + if ( (@linefilter) and ( $linefilter[0] ) and ( $linefilter[1] ) ) { $sth->execute( $linefilter[0], $linefilter[1] . " 23:59:59" ); } elsif ( $linefilter[1] ) { $sth->execute( $linefilter[1] . " 23:59:59" ); @@ -333,14 +344,15 @@ sub calculate { $sth->execute; } - my $itemtypes_map = { map { $_->{itemtype} => $_ } @{ $itemtypes } }; + my $itemtypes_map = { map { $_->{itemtype} => $_ } @{$itemtypes} }; while ( my ($celvalue) = $sth->fetchrow ) { - my %cell = ( rowtitle => $celvalue, totalrow => 0 ); # we leave 'rowtitle' as hash key (used when filling the table), and add coltitle_display + my %cell = ( rowtitle => $celvalue, totalrow => 0 ) + ; # we leave 'rowtitle' as hash key (used when filling the table), and add coltitle_display $cell{rowtitle_display} = - ( $line =~ /ccode/ ) ? $ccodes->{$celvalue} - : ( $line =~ /location/ ) ? $locations->{$celvalue} - : ( $line =~ /itemtype/ ) ? $itemtypes_map->{$celvalue}->{translated_description} - : $celvalue; # default fallback + ( $line =~ /ccode/ ) ? $ccodes->{$celvalue} + : ( $line =~ /location/ ) ? $locations->{$celvalue} + : ( $line =~ /itemtype/ ) ? $itemtypes_map->{$celvalue}->{translated_description} + : $celvalue; # default fallback if ( $line =~ /sort1/ ) { foreach (@$Bsort1) { ( $celvalue eq $_->{authorised_value} ) or next; @@ -351,9 +363,9 @@ sub calculate { ( $celvalue eq $_->{authorised_value} ) or next; $cell{rowtitle_display} = $_->{lib} and last; } - } elsif ($line =~ /category/) { - foreach my $patron_category ( @patron_categories ) { - ($celvalue eq $patron_category->categorycode) or next; + } elsif ( $line =~ /category/ ) { + foreach my $patron_category (@patron_categories) { + ( $celvalue eq $patron_category->categorycode ) or next; $cell{rowtitle_display} = $patron_category->description and last; } } @@ -367,29 +379,29 @@ sub calculate { #Display by Day, Month or Year (1,2,3 respectively) $colfield = - ( $dsp == 1 ) ? " dayname($column)" - : ( $dsp == 2 ) ? "monthname($column)" - : ( $dsp == 3 ) ? " Year($column)" - : ( $dsp == 4 ) ? "extract(hour from $column)" - : 'date_format(`datetime`,"%Y-%m-%d")'; # Probably should be left alone or passed through Koha::Dates + ( $dsp == 1 ) ? " dayname($column)" + : ( $dsp == 2 ) ? "monthname($column)" + : ( $dsp == 3 ) ? " Year($column)" + : ( $dsp == 4 ) ? "extract(hour from $column)" + : 'date_format(`datetime`,"%Y-%m-%d")'; # Probably should be left alone or passed through Koha::Dates } else { $colfield = $column; } $colorder = - ( $colfield =~ /dayname/ ) ? "weekday($column)" - : ( $colfield =~ /^month/ ) ? " month($column)" - : $colfield; + ( $colfield =~ /dayname/ ) ? "weekday($column)" + : ( $colfield =~ /^month/ ) ? " month($column)" + : $colfield; my $strsth2; - if($column_attribute_type) { + if ($column_attribute_type) { $strsth2 = "SELECT attribute FROM borrower_attributes WHERE code = '$column_attribute_type' "; } else { $strsth2 = "SELECT distinctrow $colfield FROM statistics "; # get stats on items if ccode or location, otherwise borrowers. $strsth2 .= - ( $colsource eq 'items' ) - ? "LEFT JOIN items ON (statistics.itemnumber = items.itemnumber) " - : "LEFT JOIN borrowers ON (statistics.borrowernumber = borrowers.borrowernumber) "; + ( $colsource eq 'items' ) + ? "LEFT JOIN items ON (statistics.itemnumber = items.itemnumber) " + : "LEFT JOIN borrowers ON (statistics.borrowernumber = borrowers.borrowernumber) "; $strsth2 .= " WHERE $column IS NOT NULL"; $strsth2 .= " AND $column != '' " if $column ne "datetime"; } @@ -402,18 +414,18 @@ sub calculate { } elsif ( $colfilter[0] ) { $strsth2 .= " AND $column >= ? "; } - $strsth2 .= " AND type ='". $type ."' " if $type; - $strsth2 .= " AND dayname(datetime) ='". $daysel ."' " if $daysel; - $strsth2 .= " AND monthname(datetime) ='". $monthsel ."' " if $monthsel; - } elsif ($colfilter[0]) { + $strsth2 .= " AND type ='" . $type . "' " if $type; + $strsth2 .= " AND dayname(datetime) ='" . $daysel . "' " if $daysel; + $strsth2 .= " AND monthname(datetime) ='" . $monthsel . "' " if $monthsel; + } elsif ( $colfilter[0] ) { $colfilter[0] =~ s/\*/%/g; - $strsth2 .= " AND $column LIKE ? " ; + $strsth2 .= " AND $column LIKE ? "; } $strsth2 .= " group by $colfield order by $colorder "; push @loopfilter, { crit => 'SQL =', sql => 1, filter => $strsth2 }; my $sth2 = $dbh->prepare($strsth2); - if ( (@colfilter) and ($colfilter[0]) and ($colfilter[1]) ) { + if ( (@colfilter) and ( $colfilter[0] ) and ( $colfilter[1] ) ) { $sth2->execute( $colfilter[0], $colfilter[1] . " 23:59:59" ); } elsif ( $colfilter[1] ) { $sth2->execute( $colfilter[1] . " 23:59:59" ); @@ -424,12 +436,13 @@ sub calculate { } while ( my ($celvalue) = $sth2->fetchrow ) { - my %cell = ( coltitle => $celvalue ); # we leave 'coltitle' as hash key (used when filling the table), and add coltitle_display + my %cell = ( coltitle => $celvalue ) + ; # we leave 'coltitle' as hash key (used when filling the table), and add coltitle_display $cell{coltitle_display} = - ( $column =~ /ccode/ ) ? $ccodes->{$celvalue} - : ( $column =~ /location/ ) ? $locations->{$celvalue} - : ( $column =~ /itemtype/ ) ? $itemtypes_map->{$celvalue}->{translated_description} - : $celvalue; # default fallback + ( $column =~ /ccode/ ) ? $ccodes->{$celvalue} + : ( $column =~ /location/ ) ? $locations->{$celvalue} + : ( $column =~ /itemtype/ ) ? $itemtypes_map->{$celvalue}->{translated_description} + : $celvalue; # default fallback if ( $column =~ /sort1/ ) { foreach (@$Bsort1) { ( $celvalue eq $_->{authorised_value} ) or next; @@ -440,9 +453,9 @@ sub calculate { ( $celvalue eq $_->{authorised_value} ) or next; $cell{coltitle_display} = $_->{lib} and last; } - } elsif ($column =~ /category/) { - foreach my $patron_category ( @patron_categories ) { - ($celvalue eq $patron_category->categorycode) or next; + } elsif ( $column =~ /category/ ) { + foreach my $patron_category (@patron_categories) { + ( $celvalue eq $patron_category->categorycode ) or next; $cell{coltitle_display} = $patron_category->description and last; } } @@ -453,29 +466,29 @@ sub calculate { my %table; foreach my $row (@loopline) { foreach my $col (@loopcol) { - table_set(\%table, $row->{rowtitle}, $col->{coltitle}, 0); + table_set( \%table, $row->{rowtitle}, $col->{coltitle}, 0 ); } - table_set(\%table, $row->{rowtitle}, 'totalrow', 0); + table_set( \%table, $row->{rowtitle}, 'totalrow', 0 ); } # preparing calculation my $strcalc = "SELECT "; - if($line_attribute_type) { + if ($line_attribute_type) { $strcalc .= "TRIM(attribute_$line_attribute_type.attribute) AS line_attribute, "; } else { $strcalc .= "TRIM($linefield), "; } - if($column_attribute_type) { + if ($column_attribute_type) { $strcalc .= "TRIM(attribute_$column_attribute_type.attribute) AS column_attribute, "; } else { $strcalc .= "TRIM($colfield), "; } $strcalc .= - ( $process == 1 ) ? " COUNT(*) " - : ( $process == 2 ) ? "(COUNT(DISTINCT borrowers.borrowernumber))" - : ( $process == 3 ) ? "(COUNT(DISTINCT statistics.itemnumber))" - : ( $process == 5 ) ? "(COUNT(DISTINCT items.biblionumber))" - : ''; + ( $process == 1 ) ? " COUNT(*) " + : ( $process == 2 ) ? "(COUNT(DISTINCT borrowers.borrowernumber))" + : ( $process == 3 ) ? "(COUNT(DISTINCT statistics.itemnumber))" + : ( $process == 5 ) ? "(COUNT(DISTINCT items.biblionumber))" + : ''; if ( $process == 4 ) { my $rqbookcount = $dbh->prepare("SELECT count(*) FROM items"); $rqbookcount->execute; @@ -486,65 +499,76 @@ sub calculate { FROM statistics LEFT JOIN borrowers ON statistics.borrowernumber=borrowers.borrowernumber "; - foreach (keys %$attribute_filters) { - if( - ($line_attribute_type and $line_attribute_type eq $_) + foreach ( keys %$attribute_filters ) { + if ( ( $line_attribute_type and $line_attribute_type eq $_ ) or $column_attribute_type and $column_attribute_type eq $_ - or $attribute_filters->{$_} - ) { - $strcalc .= " LEFT JOIN borrower_attributes AS attribute_$_ ON (statistics.borrowernumber = attribute_$_.borrowernumber AND attribute_$_.code = '$_') "; + or $attribute_filters->{$_} ) + { + $strcalc .= + " LEFT JOIN borrower_attributes AS attribute_$_ ON (statistics.borrowernumber = attribute_$_.borrowernumber AND attribute_$_.code = '$_') "; } } - $strcalc .= "LEFT JOIN (SELECT * FROM items UNION SELECT * FROM deleteditems) items ON statistics.itemnumber=items.itemnumber " - if ( $linefield =~ /^items\./ + $strcalc .= + "LEFT JOIN (SELECT * FROM items UNION SELECT * FROM deleteditems) items ON statistics.itemnumber=items.itemnumber " + if ( $linefield =~ /^items\./ or $colfield =~ /^items\./ or $process == 5 - or ( $colsource eq 'items' ) || @$filters[5] || @$filters[6] || @$filters[7] || @$filters[8] || @$filters[9] || @$filters[10] || @$filters[11] || @$filters[12] || @$filters[13] ); + or ( $colsource eq 'items' ) + || @$filters[5] + || @$filters[6] + || @$filters[7] + || @$filters[8] + || @$filters[9] + || @$filters[10] + || @$filters[11] + || @$filters[12] + || @$filters[13] ); $strcalc .= "WHERE 1=1 "; @$filters = map { my $f = $_; defined($f) and $f =~ s/\*/%/g; $f } @$filters; - $strcalc .= " AND statistics.datetime >= '" . @$filters[0] . "'" if ( @$filters[0] ); - $strcalc .= " AND statistics.datetime <= '" . @$filters[1] . " 23:59:59'" if ( @$filters[1] ); - $strcalc .= " AND borrowers.categorycode LIKE '" . @$filters[2] . "'" if ( @$filters[2] ); - $strcalc .= " AND statistics.itemtype LIKE '" . @$filters[3] . "'" if ( @$filters[3] ); - $strcalc .= " AND statistics.branch LIKE '" . @$filters[4] . "'" if ( @$filters[4] ); - $strcalc .= " AND items.ccode LIKE '" . @$filters[5] . "'" if ( @$filters[5] ); - $strcalc .= " AND items.location LIKE '" . @$filters[6] . "'" if ( @$filters[6] ); - $strcalc .= " AND items.itemcallnumber >='" . @$filters[7] . "'" if ( @$filters[7] ); - $strcalc .= " AND items.itemcallnumber <'" . @$filters[8] . "'" if ( @$filters[8] ); - $strcalc .= " AND borrowers.sort1 LIKE '" . @$filters[9] . "'" if ( @$filters[9] ); - $strcalc .= " AND borrowers.sort2 LIKE '" . @$filters[10] . "'" if ( @$filters[10] ); - $strcalc .= " AND items.homebranch LIKE '" . @$filters[11] . "'" if ( @$filters[11] ); - $strcalc .= " AND items.holdingbranch LIKE '" . @$filters[12] . "'" if ( @$filters[12] ); - $strcalc .= " AND borrowers.branchcode LIKE '" . @$filters[13] . "'" if ( @$filters[13] ); - $strcalc .= " AND dayname(datetime) LIKE '" . $daysel . "'" if ($daysel); - $strcalc .= " AND monthname(datetime) LIKE '" . $monthsel . "'" if ($monthsel); - $strcalc .= " AND statistics.type LIKE '" . $type . "'" if ($type); - foreach (keys %$attribute_filters) { - if($attribute_filters->{$_}) { + $strcalc .= " AND statistics.datetime >= '" . @$filters[0] . "'" if ( @$filters[0] ); + $strcalc .= " AND statistics.datetime <= '" . @$filters[1] . " 23:59:59'" if ( @$filters[1] ); + $strcalc .= " AND borrowers.categorycode LIKE '" . @$filters[2] . "'" if ( @$filters[2] ); + $strcalc .= " AND statistics.itemtype LIKE '" . @$filters[3] . "'" if ( @$filters[3] ); + $strcalc .= " AND statistics.branch LIKE '" . @$filters[4] . "'" if ( @$filters[4] ); + $strcalc .= " AND items.ccode LIKE '" . @$filters[5] . "'" if ( @$filters[5] ); + $strcalc .= " AND items.location LIKE '" . @$filters[6] . "'" if ( @$filters[6] ); + $strcalc .= " AND items.itemcallnumber >='" . @$filters[7] . "'" if ( @$filters[7] ); + $strcalc .= " AND items.itemcallnumber <'" . @$filters[8] . "'" if ( @$filters[8] ); + $strcalc .= " AND borrowers.sort1 LIKE '" . @$filters[9] . "'" if ( @$filters[9] ); + $strcalc .= " AND borrowers.sort2 LIKE '" . @$filters[10] . "'" if ( @$filters[10] ); + $strcalc .= " AND items.homebranch LIKE '" . @$filters[11] . "'" if ( @$filters[11] ); + $strcalc .= " AND items.holdingbranch LIKE '" . @$filters[12] . "'" if ( @$filters[12] ); + $strcalc .= " AND borrowers.branchcode LIKE '" . @$filters[13] . "'" if ( @$filters[13] ); + $strcalc .= " AND dayname(datetime) LIKE '" . $daysel . "'" if ($daysel); + $strcalc .= " AND monthname(datetime) LIKE '" . $monthsel . "'" if ($monthsel); + $strcalc .= " AND statistics.type LIKE '" . $type . "'" if ($type); + + foreach ( keys %$attribute_filters ) { + if ( $attribute_filters->{$_} ) { $strcalc .= " AND attribute_$_.attribute LIKE '" . $attribute_filters->{$_} . "'"; } } $strcalc .= " GROUP BY "; - if($line_attribute_type) { + if ($line_attribute_type) { $strcalc .= " line_attribute, "; } else { $strcalc .= " $linefield, "; } - if($column_attribute_type) { + if ($column_attribute_type) { $strcalc .= " column_attribute "; } else { $strcalc .= " $colfield "; } $strcalc .= " ORDER BY "; - if($line_attribute_type) { + if ($line_attribute_type) { $strcalc .= " line_attribute, "; } else { $strcalc .= " $lineorder, "; } - if($column_attribute_type) { + if ($column_attribute_type) { $strcalc .= " column_attribute "; } else { $strcalc .= " $colorder "; @@ -561,9 +585,9 @@ sub calculate { unless ( defined $row ) { $emptyrow = 1; } - table_inc(\%table, $row, $col, $value); - table_inc(\%table, $row, 'totalrow', $value); - $grantotal += $value; + table_inc( \%table, $row, $col, $value ); + table_inc( \%table, $row, 'totalrow', $value ); + $grantotal += $value; } push @loopcol, { coltitle => "NULL", coltitle_display => 'NULL' } if ($emptycol); push @loopline, { rowtitle => "NULL", rowtitle_display => 'NULL' } if ($emptyrow); @@ -574,20 +598,21 @@ sub calculate { #@loopcol ensures the order for columns is common with column titles # and the number matches the number of columns foreach my $col (@loopcol) { - my $value = table_get(\%table, $row->{rowtitle}, $col->{coltitle}); + my $value = table_get( \%table, $row->{rowtitle}, $col->{coltitle} ); push @loopcell, { value => $value }; } push @looprow, - { 'rowtitle_display' => $row->{rowtitle_display}, + { + 'rowtitle_display' => $row->{rowtitle_display}, 'rowtitle' => $row->{rowtitle}, 'loopcell' => \@loopcell, - 'totalrow' => table_get(\%table, $row->{rowtitle}, 'totalrow'), - }; + 'totalrow' => table_get( \%table, $row->{rowtitle}, 'totalrow' ), + }; } for my $col (@loopcol) { my $total = 0; foreach my $row (@looprow) { - $total += table_get(\%table, $row->{rowtitle}, $col->{coltitle}) || 0; + $total += table_get( \%table, $row->{rowtitle}, $col->{coltitle} ) || 0; } push @loopfooter, { 'totalcol' => $total }; } @@ -602,7 +627,7 @@ sub calculate { # # the foot (totals by borrower type) $globalline{loopfooter} = \@loopfooter; $globalline{total} = $grantotal; - $globalline{line} = $line_attribute_type ? $line_attribute_type : $line; + $globalline{line} = $line_attribute_type ? $line_attribute_type : $line; $globalline{column} = $column_attribute_type ? $column_attribute_type : $column; return [ ( \%globalline ) ]; } @@ -610,7 +635,7 @@ sub calculate { sub null_to_zzempty { my $string = shift; - if (!defined($string) or $string eq '' or uc($string) eq 'NULL') { + if ( !defined($string) or $string eq '' or uc($string) eq 'NULL' ) { return 'zzEMPTY'; } @@ -618,7 +643,7 @@ sub null_to_zzempty { } sub table_set { - my ($table, $row, $col, $val) = @_; + my ( $table, $row, $col, $val ) = @_; $row = $row // ''; $col = $col // ''; @@ -626,7 +651,7 @@ sub table_set { } sub table_get { - my ($table, $row, $col) = @_; + my ( $table, $row, $col ) = @_; $row = $row // ''; $col = $col // ''; @@ -634,7 +659,7 @@ sub table_get { } sub table_inc { - my ($table, $row, $col, $inc) = @_; + my ( $table, $row, $col, $inc ) = @_; $row = $row // ''; $col = $col // ''; diff --git a/reports/itemslost.pl b/reports/itemslost.pl index 80c84bb633..deacae1d8a 100755 --- a/reports/itemslost.pl +++ b/reports/itemslost.pl @@ -18,7 +18,6 @@ # You should have received a copy of the GNU General Public License # along with Koha; if not, see . - =head1 itemslost This script displays lost items. @@ -27,8 +26,8 @@ This script displays lost items. use Modern::Perl; -use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use Text::CSV::Encoded; use Koha::AuthorisedValues; @@ -37,51 +36,54 @@ use Koha::CsvProfiles; my $query = CGI->new; my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "reports/itemslost.tt", - query => $query, - type => "intranet", - flagsrequired => { reports => '*' }, + template_name => "reports/itemslost.tt", + query => $query, + type => "intranet", + flagsrequired => { reports => '*' }, } ); -my $params = $query->Vars; +my $params = $query->Vars; my $get_items = $params->{'get_items'}; -my $op = $query->param('op') || ''; +my $op = $query->param('op') || ''; if ( $op eq 'cud-export' ) { - my @itemnumbers = $query->multi_param('itemnumber'); + my @itemnumbers = $query->multi_param('itemnumber'); my $csv_profile_id = $query->param('csv_profile_id'); my @rows; if ($csv_profile_id) { + # FIXME This following code has the same logic as GetBasketAsCSV # We should refactor all the CSV export code # Note: For MARC it is already done in Koha::Exporter::Record but not for SQL CSV profiles type - my $csv_profile = Koha::CsvProfiles->find( $csv_profile_id ); + my $csv_profile = Koha::CsvProfiles->find($csv_profile_id); die "There is no valid csv profile given" unless $csv_profile; my $csv_profile_content = $csv_profile->content; my ( @headers, @fields ); - while ( $csv_profile_content =~ / + while ( + $csv_profile_content =~ / ([^=\|]+) # header =? ([^\|]*) # fieldname (table.row or row) \|? /gxms - ) { + ) + { my $header = $1; - my $field = ($2 eq '') ? $1 : $2; + my $field = ( $2 eq '' ) ? $1 : $2; - $header =~ s/^\s+|\s+$//g; # Trim whitespaces + $header =~ s/^\s+|\s+$//g; # Trim whitespaces push @headers, $header; - $field =~ s/[^\.]*\.{1}//; # Remove the table name if exists. - $field =~ s/^\s+|\s+$//g; # Trim whitespaces + $field =~ s/[^\.]*\.{1}//; # Remove the table name if exists. + $field =~ s/^\s+|\s+$//g; # Trim whitespaces push @fields, $field; } - my $items = Koha::Items->search({ itemnumber => { -in => \@itemnumbers } }); + my $items = Koha::Items->search( { itemnumber => { -in => \@itemnumbers } } ); while ( my $item = $items->next ) { my @row; my $all_fields = $item->unblessed; - $all_fields = { %$all_fields, %{$item->biblio->unblessed}, %{$item->biblioitem->unblessed} }; + $all_fields = { %$all_fields, %{ $item->biblio->unblessed }, %{ $item->biblioitem->unblessed } }; for my $field (@fields) { push @row, $all_fields->{$field}; } @@ -93,8 +95,8 @@ if ( $op eq 'cud-export' ) { my $csv = Text::CSV::Encoded->new( { encoding_out => 'UTF-8', sep_char => $delimiter, formula => 'empty' } ); $csv or die "Text::CSV::Encoded->new({binary => 1}) FAILED: " . Text::CSV::Encoded->error_diag(); $csv->combine(@headers); - my $content .= Encode::decode('UTF-8', $csv->string()) . "\n"; - for my $row ( @rows ) { + my $content .= Encode::decode( 'UTF-8', $csv->string() ) . "\n"; + for my $row (@rows) { $csv->combine(@$row); $content .= $csv->string . "\n"; } @@ -105,7 +107,7 @@ if ( $op eq 'cud-export' ) { print $content; exit; } -} elsif ( $get_items ) { +} elsif ($get_items) { my $branchfilter = $params->{'branchfilter'} || undef; my $barcodefilter = $params->{'barcodefilter'} || undef; my $itemtypesfilter = $params->{'itemtypesfilter'} || undef; @@ -131,8 +133,8 @@ if ( $op eq 'cud-export' ) { if ($itemtypesfilter) { if ( C4::Context->preference('item-level_itypes') ) { $params->{itype} = $itemtypesfilter; - } - else { + } else { + # We want a join on biblioitems $attributes = { join => 'biblioitem' }; $params->{'biblioitem.itemtype'} = $itemtypesfilter; @@ -150,10 +152,10 @@ if ( $op eq 'cud-export' ) { # getting all itemtypes my $itemtypes = Koha::ItemTypes->search_with_localization; -my $csv_profiles = Koha::CsvProfiles->search({ type => 'sql', used_for => 'export_lost_items' }); +my $csv_profiles = Koha::CsvProfiles->search( { type => 'sql', used_for => 'export_lost_items' } ); $template->param( - itemtypes => $itemtypes, + itemtypes => $itemtypes, csv_profiles => $csv_profiles, ); diff --git a/reports/orders_by_fund.pl b/reports/orders_by_fund.pl index c831bf2044..cc9e1b5343 100755 --- a/reports/orders_by_fund.pl +++ b/reports/orders_by_fund.pl @@ -18,7 +18,6 @@ # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place, # Suite 330, Boston, MA 02111-1307 USA - =head1 orders_by_budget This script displays all orders associated to a selected budget. @@ -27,10 +26,10 @@ This script displays all orders associated to a selected budget. use Modern::Perl; -use CGI qw( -utf8 ); -use C4::Auth qw( get_template_and_user ); -use C4::Output qw( output_html_with_http_headers ); -use C4::Budgets qw( GetBudgetsReport GetBudgetHierarchy ); +use CGI qw( -utf8 ); +use C4::Auth qw( get_template_and_user ); +use C4::Output qw( output_html_with_http_headers ); +use C4::Budgets qw( GetBudgetsReport GetBudgetHierarchy ); use C4::Acquisition qw( GetBasket get_rounded_price ); use C4::Context; use Koha::Biblios; @@ -38,52 +37,51 @@ use Koha::Biblios; my $query = CGI->new; my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "reports/orders_by_budget.tt", - query => $query, - type => "intranet", - flagsrequired => { reports => '*' }, + template_name => "reports/orders_by_budget.tt", + query => $query, + type => "intranet", + flagsrequired => { reports => '*' }, } ); -my $params = $query->Vars; +my $params = $query->Vars; my $get_orders = $params->{'get_orders'}; -if ( $get_orders ) { - my $budgetfilter = $params->{'budgetfilter'} || undef; +if ($get_orders) { + my $budgetfilter = $params->{'budgetfilter'} || undef; my $total_quantity = 0; - my $total_rrp = 0; - my $total_ecost = 0; + my $total_rrp = 0; + my $total_ecost = 0; my %budget_name; # Fetch the orders my @orders; - unless($budgetfilter) { + unless ($budgetfilter) { + # If no budget filter was selected, get the orders of all budgets my @budgets = C4::Budgets::GetBudgetsReport(); foreach my $budget (@budgets) { - push(@orders, $budget); - $budget_name{$budget->{'budget_id'}} = $budget->{'budget_name'}; + push( @orders, $budget ); + $budget_name{ $budget->{'budget_id'} } = $budget->{'budget_name'}; } - } - else { - if ($budgetfilter eq 'activebudgets') { - # If all active budgets's option was selected, get the orders of all active budgets - my @active_budgets = C4::Budgets::GetBudgetsReport(1); - foreach my $active_budget (@active_budgets) - { - push(@orders, $active_budget); - $budget_name{$active_budget->{'budget_id'}} = $active_budget->{'budget_name'}; - } - } - else { + } else { + if ( $budgetfilter eq 'activebudgets' ) { + + # If all active budgets's option was selected, get the orders of all active budgets + my @active_budgets = C4::Budgets::GetBudgetsReport(1); + foreach my $active_budget (@active_budgets) { + push( @orders, $active_budget ); + $budget_name{ $active_budget->{'budget_id'} } = $active_budget->{'budget_name'}; + } + } else { + # A budget filter was selected, only get the orders for the selected budget my @filtered_budgets = C4::Budgets::GetBudgetReport($budgetfilter); - foreach my $budget (@filtered_budgets) - { - push(@orders, $budget); - $budget_name{$budget->{'budget_id'}} = $budget->{'budget_name'}; + foreach my $budget (@filtered_budgets) { + push( @orders, $budget ); + $budget_name{ $budget->{'budget_id'} } = $budget->{'budget_name'}; } - if ($filtered_budgets[0]) { + if ( $filtered_budgets[0] ) { $template->param( current_budget_name => $filtered_budgets[0]->{'budget_name'}, ); @@ -93,50 +91,52 @@ if ( $get_orders ) { # Format the order's informations foreach my $order (@orders) { + # Get the title of the ordered item my $biblio = Koha::Biblios->find( $order->{biblionumber} ); - my $basket = C4::Acquisition::GetBasket($order->{'basketno'}); + my $basket = C4::Acquisition::GetBasket( $order->{'basketno'} ); - $order->{'basketname'} = $basket->{'basketname'}; + $order->{'basketname'} = $basket->{'basketname'}; $order->{'authorisedbyname'} = $basket->{'authorisedbyname'}; $order->{title} = $biblio ? $biblio->title : ''; $order->{title} ||= $order->{biblionumber}; - $order->{'total_rrp'} = get_rounded_price($order->{'quantity'}) * $order->{'rrp'}; - $order->{'total_ecost'} = get_rounded_price($order->{'quantity'}) * $order->{'ecost'}; + $order->{'total_rrp'} = get_rounded_price( $order->{'quantity'} ) * $order->{'rrp'}; + $order->{'total_ecost'} = get_rounded_price( $order->{'quantity'} ) * $order->{'ecost'}; # Format the currencies correctly $total_quantity += $order->{'quantity'}; - $total_rrp += $order->{'total_rrp'}; - $total_ecost += $order->{'total_ecost'}; + $total_rrp += $order->{'total_rrp'}; + $total_ecost += $order->{'total_ecost'}; # Get the budget's name - $order->{'budget_name'} = $budget_name{$order->{'budget_id'}}; + $order->{'budget_name'} = $budget_name{ $order->{'budget_id'} }; } # If we are outputting to screen, output to the template. - if($params->{"output"} eq 'screen') { + if ( $params->{"output"} eq 'screen' ) { $template->param( - total => scalar @orders, - ordersloop => \@orders, - get_orders => $get_orders, + total => scalar @orders, + ordersloop => \@orders, + get_orders => $get_orders, total_quantity => $total_quantity, - total_rrp => $total_rrp, - total_ecost => $total_ecost, + total_rrp => $total_rrp, + total_ecost => $total_ecost, ); } + # If we are outputting to a file, create it and exit. else { my $basename = $params->{"basename"}; - my $sep = C4::Context->csv_delimiter(scalar $params->{"sep"}); + my $sep = C4::Context->csv_delimiter( scalar $params->{"sep"} ); # TODO Use Text::CSV to generate the CSV file print $query->header( - -type => 'text/csv', - -encoding => 'utf-8', - -attachment => "$basename.csv", - -name => "$basename.csv" + -type => 'text/csv', + -encoding => 'utf-8', + -attachment => "$basename.csv", + -name => "$basename.csv" ); #binmode STDOUT, ":encoding(UTF-8)"; @@ -150,59 +150,60 @@ if ( $get_orders ) { my @rows; foreach my $order (@orders) { my @row; - push(@row, _surround($order->{'budget_name'})); - push(@row, _surround($order->{'basketno'})); - push(@row, _surround($order->{'basketname'})); - push(@row, _surround($order->{'authorisedbyname'})); - push(@row, _surround($order->{'biblionumber'})); - push(@row, _surround($order->{'title'})); - push(@row, _surround($order->{'currency'})); - push(@row, _surround($order->{'listprice'})); - push(@row, _surround($order->{'rrp'})); - push(@row, _surround($order->{'ecost'})); - push(@row, _surround($order->{'quantity'})); - push(@row, _surround($order->{'total_rrp'})); - push(@row, _surround($order->{'total_ecost'})); - push(@row, _surround($order->{'entrydate'})); - push(@row, _surround($order->{'datereceived'})); - push(@row, _surround($order->{'order_internalnote'})); - push(@row, _surround($order->{'order_vendornote'})); - push(@rows, \@row); + push( @row, _surround( $order->{'budget_name'} ) ); + push( @row, _surround( $order->{'basketno'} ) ); + push( @row, _surround( $order->{'basketname'} ) ); + push( @row, _surround( $order->{'authorisedbyname'} ) ); + push( @row, _surround( $order->{'biblionumber'} ) ); + push( @row, _surround( $order->{'title'} ) ); + push( @row, _surround( $order->{'currency'} ) ); + push( @row, _surround( $order->{'listprice'} ) ); + push( @row, _surround( $order->{'rrp'} ) ); + push( @row, _surround( $order->{'ecost'} ) ); + push( @row, _surround( $order->{'quantity'} ) ); + push( @row, _surround( $order->{'total_rrp'} ) ); + push( @row, _surround( $order->{'total_ecost'} ) ); + push( @row, _surround( $order->{'entrydate'} ) ); + push( @row, _surround( $order->{'datereceived'} ) ); + push( @row, _surround( $order->{'order_internalnote'} ) ); + push( @row, _surround( $order->{'order_vendornote'} ) ); + push( @rows, \@row ); } my @totalrow; - for(1..9){push(@totalrow, "")}; - push(@totalrow, _surround($total_quantity)); - push(@totalrow, _surround($total_rrp)); - push(@totalrow, _surround($total_ecost)); + for ( 1 .. 9 ) { push( @totalrow, "" ) } + push( @totalrow, _surround($total_quantity) ); + push( @totalrow, _surround($total_rrp) ); + push( @totalrow, _surround($total_ecost) ); - my $csvTemplate = C4::Templates::gettemplate('reports/csv/orders_by_budget.tt', 'intranet', $query); - $csvTemplate->param(sep => $sep, rows => \@rows, totalrow => \@totalrow); + my $csvTemplate = C4::Templates::gettemplate( 'reports/csv/orders_by_budget.tt', 'intranet', $query ); + $csvTemplate->param( sep => $sep, rows => \@rows, totalrow => \@totalrow ); print $csvTemplate->output; exit(0); } -} -else { +} else { + # Set file export choices my @outputFormats = ('CSV'); - my @CSVdelimiters =(',','#',qw(; tabulation \\ /)); + my @CSVdelimiters = ( ',', '#', qw(; tabulation \\ /) ); # getting all budgets - my $budgets = GetBudgetHierarchy; + my $budgets = GetBudgetHierarchy; my $budgetloop = []; - foreach my $budget (@{$budgets}) { - push @{$budgetloop},{ - value => $budget->{budget_id}, - description => $budget->{budget_name}, - period => $budget->{budget_period_description}, - active => $budget->{budget_period_active}, + foreach my $budget ( @{$budgets} ) { + push @{$budgetloop}, { + value => $budget->{budget_id}, + description => $budget->{budget_name}, + period => $budget->{budget_period_description}, + active => $budget->{budget_period_active}, }; } - @{$budgetloop} =sort { uc( $a->{description}) cmp uc( $b->{description}) } @{$budgetloop}; - $template->param( budgetsloop => \@{$budgetloop}, - outputFormatloop => \@outputFormats, - delimiterloop => \@CSVdelimiters, + @{$budgetloop} = sort { uc( $a->{description} ) cmp uc( $b->{description} ) } @{$budgetloop}; + $template->param( + budgetsloop => \@{$budgetloop}, + outputFormatloop => \@outputFormats, + delimiterloop => \@CSVdelimiters, delimiterPreference => C4::Context->preference('CSVDelimiter') ); } diff --git a/reports/reports-home.pl b/reports/reports-home.pl index dfd36e5f23..5a0c705d02 100755 --- a/reports/reports-home.pl +++ b/reports/reports-home.pl @@ -18,8 +18,8 @@ # along with Koha; if not, see . use Modern::Perl; -use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); my $query = CGI->new; diff --git a/reports/reserves_stats.pl b/reports/reserves_stats.pl index 103ab62356..40e47fa802 100755 --- a/reports/reserves_stats.pl +++ b/reports/reserves_stats.pl @@ -23,8 +23,8 @@ use CGI qw ( -utf8 ); use C4::Auth qw( get_template_and_user ); use C4::Context; -use C4::Koha qw( GetAuthorisedValues ); -use C4::Output qw( output_html_with_http_headers ); +use C4::Koha qw( GetAuthorisedValues ); +use C4::Output qw( output_html_with_http_headers ); use C4::Reports qw( GetDelimiterChoices ); use C4::Members; use Koha::AuthorisedValues; @@ -43,128 +43,151 @@ Plugin that shows reserve stats =cut -my $input = CGI->new; +my $input = CGI->new; my $fullreportname = "reports/reserves_stats.tt"; -my $do_it = $input->param('do_it'); -my $line = $input->param("Line"); -my $column = $input->param("Column"); -my $calc = $input->param("Cellvalue"); -my $output = $input->param("output"); -my $basename = $input->param("basename"); -my $hash_params = $input->Vars; +my $do_it = $input->param('do_it'); +my $line = $input->param("Line"); +my $column = $input->param("Column"); +my $calc = $input->param("Cellvalue"); +my $output = $input->param("output"); +my $basename = $input->param("basename"); +my $hash_params = $input->Vars; my $filter_hashref; -foreach my $filter (grep {$_ =~/^filter/} keys %$hash_params){ - my $filterstring=$filter; - $filterstring=~s/^filter_//g; - $$filter_hashref{$filterstring}=$$hash_params{$filter} if (defined $$hash_params{$filter} && $$hash_params{$filter} ne ""); + +foreach my $filter ( grep { $_ =~ /^filter/ } keys %$hash_params ) { + my $filterstring = $filter; + $filterstring =~ s/^filter_//g; + $$filter_hashref{$filterstring} = $$hash_params{$filter} + if ( defined $$hash_params{$filter} && $$hash_params{$filter} ne "" ); } -my ($template, $borrowernumber, $cookie) = get_template_and_user({ - template_name => $fullreportname, - query => $input, - type => "intranet", - flagsrequired => {reports => '*'}, -}); -our $sep = C4::Context->csv_delimiter(scalar $input->param("sep")); -$template->param(do_it => $do_it, +my ( $template, $borrowernumber, $cookie ) = get_template_and_user( + { + template_name => $fullreportname, + query => $input, + type => "intranet", + flagsrequired => { reports => '*' }, + } +); +our $sep = C4::Context->csv_delimiter( scalar $input->param("sep") ); +$template->param( + do_it => $do_it, ); -my @patron_categories = Koha::Patron::Categories->search_with_library_limits({}, {order_by => ['description']})->as_list; +my @patron_categories = + Koha::Patron::Categories->search_with_library_limits( {}, { order_by => ['description'] } )->as_list; -my $locations = { map { ( $_->{authorised_value} => $_->{lib} ) } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.location' }, { order_by => ['description'] } ) }; -my $ccodes = { map { ( $_->{authorised_value} => $_->{lib} ) } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.ccode' }, { order_by => ['description'] } ) }; +my $locations = { + map { ( $_->{authorised_value} => $_->{lib} ) } Koha::AuthorisedValues->get_descriptions_by_koha_field( + { frameworkcode => '', kohafield => 'items.location' }, { order_by => ['description'] } + ) +}; +my $ccodes = { + map { ( $_->{authorised_value} => $_->{lib} ) } Koha::AuthorisedValues->get_descriptions_by_koha_field( + { frameworkcode => '', kohafield => 'items.ccode' }, { order_by => ['description'] } + ) +}; my $Bsort1 = GetAuthorisedValues("Bsort1"); my $Bsort2 = GetAuthorisedValues("Bsort2"); -my ($hassort1,$hassort2); -$hassort1=1 if $Bsort1; -$hassort2=1 if $Bsort2; - +my ( $hassort1, $hassort2 ); +$hassort1 = 1 if $Bsort1; +$hassort2 = 1 if $Bsort2; if ($do_it) { -# Displaying results - my $results = calculate($line, $column, $calc, $filter_hashref); - if ($output eq "screen"){ -# Printing results to screen - $template->param(mainloop => $results); - output_html_with_http_headers $input, $cookie, $template->output; - } else { -# Printing to a csv file - print $input->header(-type => 'application/vnd.sun.xml.calc', - -encoding => 'utf-8', - -attachment=>"$basename.csv", - -filename=>"$basename.csv" ); - my $cols = @$results[0]->{loopcol}; - my $lines = @$results[0]->{looprow}; -# header top-right - print @$results[0]->{line} ."/". @$results[0]->{column} .$sep; -# Other header - foreach my $col ( @$cols ) { - print $col->{coltitle}.$sep; - } - print "Total\n"; -# Table - foreach my $line ( @$lines ) { - my $x = $line->{loopcell}; - print $line->{rowtitle}.$sep; - print map {$_->{value}.$sep} @$x; - print $line->{totalrow}, "\n"; - } -# footer + + # Displaying results + my $results = calculate( $line, $column, $calc, $filter_hashref ); + if ( $output eq "screen" ) { + + # Printing results to screen + $template->param( mainloop => $results ); + output_html_with_http_headers $input, $cookie, $template->output; + } else { + + # Printing to a csv file + print $input->header( + -type => 'application/vnd.sun.xml.calc', + -encoding => 'utf-8', + -attachment => "$basename.csv", + -filename => "$basename.csv" + ); + my $cols = @$results[0]->{loopcol}; + my $lines = @$results[0]->{looprow}; + + # header top-right + print @$results[0]->{line} . "/" . @$results[0]->{column} . $sep; + + # Other header + foreach my $col (@$cols) { + print $col->{coltitle} . $sep; + } + print "Total\n"; + + # Table + foreach my $line (@$lines) { + my $x = $line->{loopcell}; + print $line->{rowtitle} . $sep; + print map { $_->{value} . $sep } @$x; + print $line->{totalrow}, "\n"; + } + + # footer print "TOTAL"; $cols = @$results[0]->{loopfooter}; - print map {$sep.$_->{totalcol}} @$cols; - print $sep.@$results[0]->{total}; - } - exit; # exit either way after $do_it + print map { $sep . $_->{totalcol} } @$cols; + print $sep. @$results[0]->{total}; + } + exit; # exit either way after $do_it } my $dbh = C4::Context->dbh; my $itemtypes = Koha::ItemTypes->search_with_localization; - # location list +# location list my @locations; -foreach (sort keys %$locations) { - push @locations, { code => $_, description => "$_ - " . $locations->{$_} }; +foreach ( sort keys %$locations ) { + push @locations, { code => $_, description => "$_ - " . $locations->{$_} }; } - + my @ccodes; -foreach (sort {$ccodes->{$a} cmp $ccodes->{$b}} keys %$ccodes) { - push @ccodes, { code => $_, description => $ccodes->{$_} }; +foreach ( sort { $ccodes->{$a} cmp $ccodes->{$b} } keys %$ccodes ) { + push @ccodes, { code => $_, description => $ccodes->{$_} }; } # various -my $CGIextChoice = ( 'CSV' ); # FIXME translation -my $CGIsepChoice=GetDelimiterChoices; - +my $CGIextChoice = ('CSV'); # FIXME translation +my $CGIsepChoice = GetDelimiterChoices; + $template->param( categoryloop => \@patron_categories, - itemtypes => $itemtypes, - locationloop => \@locations, - ccodeloop => \@ccodes, - hassort1=> $hassort1, - hassort2=> $hassort2, - Bsort1 => $Bsort1, - Bsort2 => $Bsort2, - CGIextChoice => $CGIextChoice, - CGIsepChoice => $CGIsepChoice, + itemtypes => $itemtypes, + locationloop => \@locations, + ccodeloop => \@ccodes, + hassort1 => $hassort1, + hassort2 => $hassort2, + Bsort1 => $Bsort1, + Bsort2 => $Bsort2, + CGIextChoice => $CGIextChoice, + CGIsepChoice => $CGIsepChoice, ); output_html_with_http_headers $input, $cookie, $template->output; sub calculate { - my ($linefield, $colfield, $process, $filters_hashref) = @_; - my @loopfooter; - my @loopcol; - my @loopline; - my @looprow; - my %globalline; - my $grantotal =0; -# extract parameters - my $dbh = C4::Context->dbh; + my ( $linefield, $colfield, $process, $filters_hashref ) = @_; + my @loopfooter; + my @loopcol; + my @loopline; + my @looprow; + my %globalline; + my $grantotal = 0; -# Filters -# Checking filters -# + # extract parameters + my $dbh = C4::Context->dbh; + + # Filters + # Checking filters + # my @loopfilter; foreach my $filter ( keys %$filters_hashref ) { $filters_hashref->{$filter} =~ s/\*/%/; @@ -178,144 +201,155 @@ sub calculate { } } sort keys %$filters_hashref; + my $linesql = changeifreservestatus($linefield); + my $colsql = changeifreservestatus($colfield); + #Initialization of cell values..... - - my $linesql=changeifreservestatus($linefield); - my $colsql=changeifreservestatus($colfield); - #Initialization of cell values..... - - # preparing calculation + # preparing calculation my $strcalc = "(SELECT $linesql line, $colsql col, "; - $strcalc .= ($process == 1) ? " COUNT(*) calculation" : - ($process == 2) ? "(COUNT(DISTINCT reserves.borrowernumber)) calculation" : - ($process == 3) ? "(COUNT(DISTINCT reserves.itemnumber)) calculation" : - ($process == 4) ? "(COUNT(DISTINCT reserves.biblionumber)) calculation" : '*'; - $strcalc .= " + $strcalc .= + ( $process == 1 ) ? " COUNT(*) calculation" + : ( $process == 2 ) ? "(COUNT(DISTINCT reserves.borrowernumber)) calculation" + : ( $process == 3 ) ? "(COUNT(DISTINCT reserves.itemnumber)) calculation" + : ( $process == 4 ) ? "(COUNT(DISTINCT reserves.biblionumber)) calculation" + : '*'; + $strcalc .= " FROM (select * from reserves union select * from old_reserves) reserves LEFT JOIN borrowers USING (borrowernumber) "; - $strcalc .= "LEFT JOIN biblio ON reserves.biblionumber=biblio.biblionumber " - if ($linefield =~ /^biblio\./ or $colfield =~ /^biblio\./ or any {$_=~/biblio/}keys %$filters_hashref); - $strcalc .= "LEFT JOIN items ON reserves.itemnumber=items.itemnumber " - if ($linefield =~ /^items\./ or $colfield =~ /^items\./ or any {$_=~/items/}keys %$filters_hashref); + $strcalc .= "LEFT JOIN biblio ON reserves.biblionumber=biblio.biblionumber " + if ( $linefield =~ /^biblio\./ or $colfield =~ /^biblio\./ or any { $_ =~ /biblio/ } keys %$filters_hashref ); + $strcalc .= "LEFT JOIN items ON reserves.itemnumber=items.itemnumber " + if ( $linefield =~ /^items\./ or $colfield =~ /^items\./ or any { $_ =~ /items/ } keys %$filters_hashref ); - my @sqlparams; - my @sqlorparams; - my @sqlor; - my @sqlwhere; - foreach my $filter (keys %$filters_hashref){ - my $string; - my $stringfield=$filter; - $stringfield=~s/\_[a-z_]+$//; - if ($filter=~/ /){ - $string=$stringfield; - } - elsif ($filter=~/_or/){ - push @sqlor, qq{( }.changeifreservestatus($filter)." = ? ) "; - push @sqlorparams, $$filters_hashref{$filter}; - } - elsif ($filter=~/_endex$/){ - $string = " $stringfield < ? "; - } - elsif ($filter=~/_end$/){ - $string = " $stringfield <= ? "; - } - elsif ($filter=~/_begin$/){ - $string = " $stringfield >= ? "; - } - else { - $string = " $stringfield LIKE ? "; - } - if ($string){ - push @sqlwhere, $string; - push @sqlparams, $$filters_hashref{$filter}; - } - } + my @sqlparams; + my @sqlorparams; + my @sqlor; + my @sqlwhere; + foreach my $filter ( keys %$filters_hashref ) { + my $string; + my $stringfield = $filter; + $stringfield =~ s/\_[a-z_]+$//; + if ( $filter =~ / / ) { + $string = $stringfield; + } elsif ( $filter =~ /_or/ ) { + push @sqlor, qq{( } . changeifreservestatus($filter) . " = ? ) "; + push @sqlorparams, $$filters_hashref{$filter}; + } elsif ( $filter =~ /_endex$/ ) { + $string = " $stringfield < ? "; + } elsif ( $filter =~ /_end$/ ) { + $string = " $stringfield <= ? "; + } elsif ( $filter =~ /_begin$/ ) { + $string = " $stringfield >= ? "; + } else { + $string = " $stringfield LIKE ? "; + } + if ($string) { + push @sqlwhere, $string; + push @sqlparams, $$filters_hashref{$filter}; + } + } - $strcalc .= " WHERE ".join(" AND ",@sqlwhere) if (@sqlwhere); - $strcalc .= " AND (".join(" OR ",@sqlor).")" if (@sqlor); - $strcalc .= " GROUP BY line, col )"; - my $dbcalc = $dbh->prepare($strcalc); - push @loopfilter, {crit=>'SQL =', sql=>1, filter=>$strcalc}; - @sqlparams=(@sqlparams,@sqlorparams); - $dbcalc->execute(@sqlparams); - my $data = $dbcalc->fetchall_hashref([qw(line col)]); - my %cols_hash; - foreach my $row (keys %$data){ - push @loopline, $row; - foreach my $col (keys %{$$data{$row}}){ - $$data{$row}{totalrow}+=$$data{$row}{$col}{calculation}; - $grantotal+=$$data{$row}{$col}{calculation}; - $cols_hash{$col}=1 ; - } - } - my $urlbase="do_it=1&".join("&",map{"filter_$_=$$filters_hashref{$_}"} keys %$filters_hashref); - foreach my $row (sort @loopline) { - my @loopcell; - #@loopcol ensures the order for columns is common with column titles - # and the number matches the number of columns - foreach my $col (sort keys %cols_hash) { - push @loopcell, {value =>( $$data{$row}{$col}{calculation} or ""), - # url_complement=>($urlbase=~/&$/?$urlbase."&":$urlbase)."filter_$linefield=$row&filter_$colfield=$col" - } - } - push @looprow, { - 'rowtitle_display' => display_value($linefield,$row), - 'rowtitle' => $row, - 'loopcell' => \@loopcell, - 'totalrow' => $$data{$row}{totalrow} - }; - } - for my $col ( sort keys %cols_hash ) { - my $total = 0; - foreach my $row (@loopline) { - $total += $data->{$row}{$col}{calculation} if $data->{$row}{$col}{calculation}; - } - push @loopfooter, {'totalcol' => $total}; - push @loopcol, {'coltitle' => $col, - coltitle_display=>display_value($colfield,$col)}; - } - # the header of the table - $globalline{loopfilter}=\@loopfilter; - # the core of the table - $globalline{looprow} = \@looprow; - $globalline{loopcol} = \@loopcol; - # # the foot (totals by borrower type) - $globalline{loopfooter} = \@loopfooter; - $globalline{total} = $grantotal; - $globalline{line} = $linefield; - $globalline{column} = $colfield; - return [(\%globalline)]; + $strcalc .= " WHERE " . join( " AND ", @sqlwhere ) if (@sqlwhere); + $strcalc .= " AND (" . join( " OR ", @sqlor ) . ")" if (@sqlor); + $strcalc .= " GROUP BY line, col )"; + my $dbcalc = $dbh->prepare($strcalc); + push @loopfilter, { crit => 'SQL =', sql => 1, filter => $strcalc }; + @sqlparams = ( @sqlparams, @sqlorparams ); + $dbcalc->execute(@sqlparams); + my $data = $dbcalc->fetchall_hashref( [qw(line col)] ); + my %cols_hash; + + foreach my $row ( keys %$data ) { + push @loopline, $row; + foreach my $col ( keys %{ $$data{$row} } ) { + $$data{$row}{totalrow} += $$data{$row}{$col}{calculation}; + $grantotal += $$data{$row}{$col}{calculation}; + $cols_hash{$col} = 1; + } + } + my $urlbase = "do_it=1&" . join( "&", map { "filter_$_=$$filters_hashref{$_}" } keys %$filters_hashref ); + foreach my $row ( sort @loopline ) { + my @loopcell; + + #@loopcol ensures the order for columns is common with column titles + # and the number matches the number of columns + foreach my $col ( sort keys %cols_hash ) { + push @loopcell, { + value => ( $$data{$row}{$col}{calculation} or "" ), + + # url_complement=>($urlbase=~/&$/?$urlbase."&":$urlbase)."filter_$linefield=$row&filter_$colfield=$col" + }; + } + push @looprow, { + 'rowtitle_display' => display_value( $linefield, $row ), + 'rowtitle' => $row, + 'loopcell' => \@loopcell, + 'totalrow' => $$data{$row}{totalrow} + }; + } + for my $col ( sort keys %cols_hash ) { + my $total = 0; + foreach my $row (@loopline) { + $total += $data->{$row}{$col}{calculation} if $data->{$row}{$col}{calculation}; + } + push @loopfooter, { 'totalcol' => $total }; + push @loopcol, { + 'coltitle' => $col, + coltitle_display => display_value( $colfield, $col ) + }; + } + + # the header of the table + $globalline{loopfilter} = \@loopfilter; + + # the core of the table + $globalline{looprow} = \@looprow; + $globalline{loopcol} = \@loopcol; + + # # the foot (totals by borrower type) + $globalline{loopfooter} = \@loopfooter; + $globalline{total} = $grantotal; + $globalline{line} = $linefield; + $globalline{column} = $colfield; + return [ ( \%globalline ) ]; } sub display_value { my ( $crit, $value ) = @_; - my $locations = { map { ( $_->{authorised_value} => $_->{lib} ) } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.location' }, { order_by => ['description'] } ) }; - my $ccodes = { map { ( $_->{authorised_value} => $_->{lib} ) } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.ccode' }, { order_by => ['description'] } ) }; + my $locations = { + map { ( $_->{authorised_value} => $_->{lib} ) } Koha::AuthorisedValues->get_descriptions_by_koha_field( + { frameworkcode => '', kohafield => 'items.location' }, { order_by => ['description'] } + ) + }; + my $ccodes = { + map { ( $_->{authorised_value} => $_->{lib} ) } Koha::AuthorisedValues->get_descriptions_by_koha_field( + { frameworkcode => '', kohafield => 'items.ccode' }, { order_by => ['description'] } + ) + }; my $Bsort1 = GetAuthorisedValues("Bsort1"); my $Bsort2 = GetAuthorisedValues("Bsort2"); my $display_value = - ( $crit =~ /ccode/ ) ? $ccodes->{$value} - : ( $crit =~ /location/ ) ? $locations->{$value} - : ( $crit =~ /itemtype/ ) ? Koha::ItemTypes->find( $value )->translated_description - : ( $crit =~ /branch/ ) ? Koha::Libraries->find($value)->branchname - : $value; # default fallback - if ($crit =~ /sort1/) { + ( $crit =~ /ccode/ ) ? $ccodes->{$value} + : ( $crit =~ /location/ ) ? $locations->{$value} + : ( $crit =~ /itemtype/ ) ? Koha::ItemTypes->find($value)->translated_description + : ( $crit =~ /branch/ ) ? Koha::Libraries->find($value)->branchname + : $value; # default fallback + if ( $crit =~ /sort1/ ) { foreach (@$Bsort1) { - ($value eq $_->{authorised_value}) or next; + ( $value eq $_->{authorised_value} ) or next; $display_value = $_->{lib} and last; } - } - elsif ($crit =~ /sort2/) { + } elsif ( $crit =~ /sort2/ ) { foreach (@$Bsort2) { - ($value eq $_->{authorised_value}) or next; + ( $value eq $_->{authorised_value} ) or next; $display_value = $_->{lib} and last; } - } - elsif ( $crit =~ /category/ ) { - my @patron_categories = Koha::Patron::Categories->search_with_library_limits({}, {order_by => ['description']})->as_list; - foreach my $patron_category ( @patron_categories ) { + } elsif ( $crit =~ /category/ ) { + my @patron_categories = + Koha::Patron::Categories->search_with_library_limits( {}, { order_by => ['description'] } )->as_list; + foreach my $patron_category (@patron_categories) { ( $value eq $patron_category->categorycode ) or next; $display_value = $patron_category->description and last; } @@ -323,9 +357,11 @@ sub display_value { return $display_value; } -sub changeifreservestatus{ - my ( $field ) = @_; +sub changeifreservestatus { + my ($field) = @_; return $field unless $field =~ /reservestatus/; + # For reservestatus we return C- Cancelled, W- Waiting, F- Filled, P- Placed (or other like processing, transit etc.) - return q|CASE WHEN cancellationdate IS NOT NULL THEN 'C' WHEN found='W' THEN 'W' WHEN found='F' THEN 'F' ELSE 'P' END|; + return + q|CASE WHEN cancellationdate IS NOT NULL THEN 'C' WHEN found='W' THEN 'W' WHEN found='F' THEN 'F' ELSE 'P' END|; } diff --git a/reports/serials_stats.pl b/reports/serials_stats.pl index c6254241c1..a2375da6b8 100755 --- a/reports/serials_stats.pl +++ b/reports/serials_stats.pl @@ -19,9 +19,9 @@ use Modern::Perl; use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Context; -use C4::Output qw( output_html_with_http_headers ); +use C4::Output qw( output_html_with_http_headers ); use C4::Reports qw( GetDelimiterChoices ); use C4::Serials qw( GetExpirationDate HasSubscriptionExpired ); @@ -33,121 +33,129 @@ plugin that shows a stats on serials =cut -my $input = CGI->new; -my $templatename = "reports/serials_stats.tt"; -my $do_it = $input->param("do_it"); -my $bookseller = $input->param("bookseller"); -my $branchcode = $input->param("branchcode"); -my $expired = $input->param("expired"); -my $order = $input->param("order"); -my $output = $input->param("output"); -my $basename = $input->param("basename"); -our $sep = C4::Context->csv_delimiter(scalar $input->param("sep")); +my $input = CGI->new; +my $templatename = "reports/serials_stats.tt"; +my $do_it = $input->param("do_it"); +my $bookseller = $input->param("bookseller"); +my $branchcode = $input->param("branchcode"); +my $expired = $input->param("expired"); +my $order = $input->param("order"); +my $output = $input->param("output"); +my $basename = $input->param("basename"); +our $sep = C4::Context->csv_delimiter( scalar $input->param("sep") ); + +my ( $template, $borrowernumber, $cookie ) = get_template_and_user( + { + template_name => $templatename, + query => $input, + type => "intranet", + flagsrequired => { reports => '*' }, + } +); -my ($template, $borrowernumber, $cookie) - = get_template_and_user({template_name => $templatename, - query => $input, - type => "intranet", - flagsrequired => {reports => '*'}, - }); - - - my $dbh = C4::Context->dbh; -if($do_it){ +if ($do_it) { my $where = "WHERE 1 "; my @args; + # if a specific branchcode was selected - if( $branchcode ne '' ){ + if ( $branchcode ne '' ) { $where .= "AND branchcode = ? "; - push @args,$branchcode; - } - - # if a specific bookseller was selected - if($bookseller ne ''){ - $where .= "AND aqbooksellerid = ? "; - push @args,$bookseller; + push @args, $branchcode; } - my $sth = $dbh->prepare("SELECT * + # if a specific bookseller was selected + if ( $bookseller ne '' ) { + $where .= "AND aqbooksellerid = ? "; + push @args, $bookseller; + } + + my $sth = $dbh->prepare( + "SELECT * FROM subscription LEFT JOIN aqbooksellers ON (aqbooksellers.id=subscription.aqbooksellerid) LEFT JOIN biblio ON (biblio.biblionumber=subscription.biblionumber) $where - "); + " + ); $sth->execute(@args); - + ## hash generation of items by branchcode my @datas; - while(my $row = $sth->fetchrow_hashref){ - $row->{'enddate'} = GetExpirationDate($row->{'subscriptionid'}); - $row->{expired} = HasSubscriptionExpired($row->{subscriptionid}); - push @datas, $row if ( + while ( my $row = $sth->fetchrow_hashref ) { + $row->{'enddate'} = GetExpirationDate( $row->{'subscriptionid'} ); + $row->{expired} = HasSubscriptionExpired( $row->{subscriptionid} ); + push @datas, + $row if ( $expired or ( not $expired - and ( - not $row->{expired} - and not $row->{closed} - ) + and ( not $row->{expired} + and not $row->{closed} ) ) - ); + ); } - if($output eq 'screen'){ - $template->param(datas => \@datas, - do_it => 1); - }else{ + if ( $output eq 'screen' ) { + $template->param( + datas => \@datas, + do_it => 1 + ); + } else { binmode STDOUT, ':encoding(UTF-8)'; - print $input->header(-type => 'application/vnd.sun.xml.calc', - -encoding => 'utf-8', - -name => "$basename.csv", - -attachment => "$basename.csv"); - print "Vendor".$sep; - print "Title".$sep; - print "Subscription id".$sep; - print "Branch".$sep; - print "Callnumber".$sep; - print "Subscription Begin".$sep; + print $input->header( + -type => 'application/vnd.sun.xml.calc', + -encoding => 'utf-8', + -name => "$basename.csv", + -attachment => "$basename.csv" + ); + print "Vendor" . $sep; + print "Title" . $sep; + print "Subscription id" . $sep; + print "Branch" . $sep; + print "Callnumber" . $sep; + print "Subscription Begin" . $sep; print "Subscription End\n"; - - foreach my $item (@datas){ - print $item->{name}.$sep; - print $item->{title}.$sep; - print $item->{subscriptionid}.$sep; - print $item->{branchcode}.$sep; - print $item->{callnumber}.$sep; - print $item->{startdate}.$sep; - print $item->{enddate}."\n"; + + foreach my $item (@datas) { + print $item->{name} . $sep; + print $item->{title} . $sep; + print $item->{subscriptionid} . $sep; + print $item->{branchcode} . $sep; + print $item->{callnumber} . $sep; + print $item->{startdate} . $sep; + print $item->{enddate} . "\n"; } exit; } -}else{ +} else { ## We generate booksellers list my @booksellers; - - my $sth = $dbh->prepare("SELECT aqbooksellerid, aqbooksellers.name + + my $sth = $dbh->prepare( + "SELECT aqbooksellerid, aqbooksellers.name FROM subscription LEFT JOIN aqbooksellers ON (subscription.aqbooksellerid=aqbooksellers.id ) GROUP BY aqbooksellerid, aqbooksellers.name ORDER BY aqbooksellers.name ASC - "); + " + ); $sth->execute(); - - while(my $row = $sth->fetchrow_hashref){ - push(@booksellers,$row) + + while ( my $row = $sth->fetchrow_hashref ) { + push( @booksellers, $row ); } - my $CGIextChoice = ( 'CSV' ); # FIXME translation - my $CGIsepChoice=GetDelimiterChoices; - $template->param( - CGIextChoice => $CGIextChoice, - CGIsepChoice => $CGIsepChoice, + my $CGIextChoice = ('CSV'); # FIXME translation + my $CGIsepChoice = GetDelimiterChoices; + $template->param( + CGIextChoice => $CGIextChoice, + CGIsepChoice => $CGIsepChoice, booksellers => \@booksellers, ); } diff --git a/reserve/modrequest.pl b/reserve/modrequest.pl index fbf960a554..63f7a23e1b 100755 --- a/reserve/modrequest.pl +++ b/reserve/modrequest.pl @@ -4,7 +4,6 @@ #written 2/1/00 by chris@katipo.oc.nz #last update 27/1/2000 by chris@katipo.co.nz - # Copyright 2000-2002 Katipo Communications # # This file is part of Koha. @@ -30,49 +29,49 @@ use Try::Tiny; use C4::Output; use C4::Reserves qw( ModReserve ); -use C4::Auth qw( checkauth ); +use C4::Auth qw( checkauth ); use Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue; my $query = CGI->new; -checkauth($query, 0, { reserveforothers => '*' }, 'intranet'); +checkauth( $query, 0, { reserveforothers => '*' }, 'intranet' ); -my $op = $query->param('op') || 'cud-modifyall'; -my @reserve_id = $query->multi_param('reserve_id'); -my @rank = $query->multi_param('rank-request'); -my @borrower = $query->multi_param('borrowernumber'); -my @reservedates = $query->multi_param('reservedate'); +my $op = $query->param('op') || 'cud-modifyall'; +my @reserve_id = $query->multi_param('reserve_id'); +my @rank = $query->multi_param('rank-request'); +my @borrower = $query->multi_param('borrowernumber'); +my @reservedates = $query->multi_param('reservedate'); my @expirationdates = $query->multi_param('expirationdate'); -my @branch = $query->multi_param('pickup'); -my @itemnumber = $query->multi_param('itemnumber'); -my @biblionumber = $query->multi_param('biblionumber'); -my $count=@rank; +my @branch = $query->multi_param('pickup'); +my @itemnumber = $query->multi_param('itemnumber'); +my @biblionumber = $query->multi_param('biblionumber'); +my $count = @rank; @biblionumber = uniq @biblionumber; # Cancel or modify the queue list of reserves (without item linked) -if( $op eq 'cud-cancelall' || $op eq 'cud-modifyall' ) { - for (my $i=0;$i<$count;$i++){ +if ( $op eq 'cud-cancelall' || $op eq 'cud-modifyall' ) { + for ( my $i = 0 ; $i < $count ; $i++ ) { undef $itemnumber[$i] if !$itemnumber[$i]; - my $suspend_until = $query->param( "suspend_until_" . $reserve_id[$i] ); + my $suspend_until = $query->param( "suspend_until_" . $reserve_id[$i] ); my $cancellation_reason = $query->param("cancellation-reason"); - my $params = { - rank => $rank[$i], - reserve_id => $reserve_id[$i], + my $params = { + rank => $rank[$i], + reserve_id => $reserve_id[$i], expirationdate => $expirationdates[$i] || undef, - branchcode => $branch[$i], - itemnumber => $itemnumber[$i], + branchcode => $branch[$i], + itemnumber => $itemnumber[$i], defined $suspend_until ? ( suspend_until => $suspend_until ) : (), cancellation_reason => $cancellation_reason, }; - if (C4::Context->preference('AllowHoldDateInFuture')) { + if ( C4::Context->preference('AllowHoldDateInFuture') ) { $params->{reservedate} = $reservedates[$i] || undef; } try { ModReserve($params); } catch { - if ($_->isa('Koha::Exceptions::ObjectNotFound')){ + if ( $_->isa('Koha::Exceptions::ObjectNotFound') ) { warn $_; } else { $_->rethrow; @@ -94,21 +93,18 @@ if( $op eq 'cud-cancelall' || $op eq 'cud-modifyall' ) { } } my @biblio_ids = uniq @biblionumber; - Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue->new->enqueue( - { - biblio_ids => \@biblio_ids - } - ) if C4::Context->preference('RealTimeHoldsQueue'); + Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue->new->enqueue( { biblio_ids => \@biblio_ids } ) + if C4::Context->preference('RealTimeHoldsQueue'); } -my $from=$query->param('from'); +my $from = $query->param('from'); $from ||= q{}; -if ( $from eq 'borrower'){ +if ( $from eq 'borrower' ) { print $query->redirect("/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrower[0]"); -} elsif ( $from eq 'circ'){ +} elsif ( $from eq 'circ' ) { print $query->redirect("/cgi-bin/koha/circ/circulation.pl?borrowernumber=$borrower[0]"); } else { - my $url = URI->new("/cgi-bin/koha/reserve/request.pl"); - $url->query_form( biblionumber => [@biblionumber]); - print $query->redirect($url); + my $url = URI->new("/cgi-bin/koha/reserve/request.pl"); + $url->query_form( biblionumber => [@biblionumber] ); + print $query->redirect($url); } diff --git a/reserve/modrequest_suspendall.pl b/reserve/modrequest_suspendall.pl index 6d9c5f8b3d..91f1d4fb8e 100755 --- a/reserve/modrequest_suspendall.pl +++ b/reserve/modrequest_suspendall.pl @@ -4,7 +4,6 @@ #written 2/1/00 by chris@katipo.oc.nz #last update 27/1/2000 by chris@katipo.co.nz - # Copyright 2000-2002 Katipo Communications # # This file is part of Koha. @@ -26,26 +25,26 @@ use Modern::Perl; use CGI qw ( -utf8 ); use C4::Output; use C4::Reserves qw( SuspendAll ); -use C4::Auth qw( checkauth ); +use C4::Auth qw( checkauth ); my $query = CGI->new; -checkauth($query, 0, { reserveforothers => '*' }, 'intranet'); +checkauth( $query, 0, { reserveforothers => '*' }, 'intranet' ); -my $op = $query->param('op') || q{}; +my $op = $query->param('op') || q{}; my $borrowernumber = $query->param('borrowernumber'); my $suspend = $query->param('suspend'); my $suspend_until = $query->param('suspend_until'); -if( $op eq 'cud-suspendall' || $op eq 'cud-unsuspendall' ){ +if ( $op eq 'cud-suspendall' || $op eq 'cud-unsuspendall' ) { SuspendAll( borrowernumber => $borrowernumber, suspend_until => $suspend_until, suspend => $suspend ); } my $from = $query->param('from'); $from ||= q{}; -if ( $from eq 'borrower'){ +if ( $from eq 'borrower' ) { print $query->redirect("/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber"); -} elsif ( $from eq 'circ'){ +} elsif ( $from eq 'circ' ) { print $query->redirect("/cgi-bin/koha/circ/circulation.pl?borrowernumber=$borrowernumber"); } else { print $query->redirect("/cgi-bin/koha/circ/circulation.pl?borrowernumber=$borrowernumber"); diff --git a/reserve/request.pl b/reserve/request.pl index b9a3182d7c..c5e354aa7d 100755 --- a/reserve/request.pl +++ b/reserve/request.pl @@ -1,6 +1,5 @@ #!/usr/bin/perl - #written 2/1/00 by chris@katipo.oc.nz # Copyright 2000-2002 Katipo Communications # Parts Copyright 2011 Catalyst IT @@ -28,18 +27,19 @@ script to place reserves/requests use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use List::MoreUtils qw( uniq ); -use Date::Calc qw( Date_to_Days ); -use C4::Output qw( output_html_with_http_headers ); -use C4::Auth qw( get_template_and_user ); -use C4::Reserves qw( RevertWaitingStatus AlterPriority ToggleLowestPriority CanBookBeReserved GetMaxPatronHoldsForRecord CanItemBeReserved IsAvailableForItemLevelRequest ); -use C4::Items qw( get_hostitemnumbers_of ); -use C4::Koha qw( getitemtypeimagelocation ); -use C4::Serials qw( CountSubscriptionFromBiblionumber ); +use Date::Calc qw( Date_to_Days ); +use C4::Output qw( output_html_with_http_headers ); +use C4::Auth qw( get_template_and_user ); +use C4::Reserves + qw( RevertWaitingStatus AlterPriority ToggleLowestPriority CanBookBeReserved GetMaxPatronHoldsForRecord CanItemBeReserved IsAvailableForItemLevelRequest ); +use C4::Items qw( get_hostitemnumbers_of ); +use C4::Koha qw( getitemtypeimagelocation ); +use C4::Serials qw( CountSubscriptionFromBiblionumber ); use C4::Circulation qw( _GetCircControlBranch GetBranchItemRule ); use Koha::DateUtils qw( dt_from_string ); -use C4::Search qw( enabled_staff_search_views ); +use C4::Search qw( enabled_staff_search_views ); use Koha::Biblios; use Koha::Checkouts; @@ -53,24 +53,24 @@ use Koha::Patron::Attribute::Types; use Koha::Clubs; use Koha::BackgroundJob::BatchCancelHold; -my $dbh = C4::Context->dbh; +my $dbh = C4::Context->dbh; my $input = CGI->new; my ( $template, $borrowernumber, $cookie, $flags ) = get_template_and_user( { - template_name => "reserve/request.tt", - query => $input, - type => "intranet", - flagsrequired => { reserveforothers => 'place_holds' }, + template_name => "reserve/request.tt", + query => $input, + type => "intranet", + flagsrequired => { reserveforothers => 'place_holds' }, } ); my $showallitems = $input->param('showallitems'); -my $pickup = $input->param('pickup'); +my $pickup = $input->param('pickup'); my $itemtypes = { map { $_->itemtype => - { %{ $_->unblessed }, image_location => $_->image_location('intranet'), notforloan => $_->notforloan } + { %{ $_->unblessed }, image_location => $_->image_location('intranet'), notforloan => $_->notforloan } } Koha::ItemTypes->search_with_localization->as_list }; @@ -81,14 +81,14 @@ $findborrower =~ s|,| |g; my $findclub = $input->param('findclub'); $findclub = '' unless defined $findclub && !$findborrower; my $borrowernumber_hold = $input->param('borrowernumber') || ''; -my $club_hold = $input->param('club')||''; +my $club_hold = $input->param('club') || ''; my $messageborrower; my $messageclub; my $warnings; my $messages; my $exceeded_maxreserves; my $exceeded_holds_per_record; -my @failed_holds = $input->multi_param('failed_holds'); +my @failed_holds = $input->multi_param('failed_holds'); my $form_submitted = $input->param('form_submitted'); my $op = $input->param('op') || q{}; @@ -103,25 +103,21 @@ if ( $op eq 'cud-move' ) { my $hold_itemnumber = $input->param('itemnumber'); if ( $prev_priority == 0 && $next_priority == 1 ) { C4::Reserves::RevertWaitingStatus( { itemnumber => $hold_itemnumber } ); - } - else { + } else { AlterPriority( $where, $reserve_id, $prev_priority, $next_priority, $first_priority, $last_priority ); } -} -elsif ( $op eq 'cud-cancel' ) { +} elsif ( $op eq 'cud-cancel' ) { my $reserve_id = $input->param('reserve_id'); my $cancellation_reason = $input->param("cancellation-reason"); my $hold = Koha::Holds->find($reserve_id); $hold->cancel( { cancellation_reason => $cancellation_reason } ) if $hold; -} -elsif ( $op eq 'cud-setLowestPriority' ) { +} elsif ( $op eq 'cud-setLowestPriority' ) { my $reserve_id = $input->param('reserve_id'); ToggleLowestPriority($reserve_id); -} -elsif ( $op eq 'cud-suspend' ) { +} elsif ( $op eq 'cud-suspend' ) { my $reserve_id = $input->param('reserve_id'); my $suspend_until = $input->param('suspend_until'); my $hold = Koha::Holds->find($reserve_id); @@ -130,10 +126,9 @@ elsif ( $op eq 'cud-suspend' ) { my $reserve_id = $input->param('reserve_id'); my $hold = Koha::Holds->find($reserve_id); $hold->resume() if $hold; -} -elsif ( $op eq 'cud-cancel_bulk' ) { +} elsif ( $op eq 'cud-cancel_bulk' ) { my $cancellation_reason = $input->param("cancellation-reason"); - my @hold_ids = split( ',', scalar $input->param("ids")); + my @hold_ids = split( ',', scalar $input->param("ids") ); my $params = { reason => $cancellation_reason, hold_ids => \@hold_ids, @@ -186,8 +181,8 @@ $template->param( # If we have the borrowernumber because we've performed an action, then we # don't want to try to place another reserve. -if ($borrowernumber_hold && !$op) { - my $patron = Koha::Patrons->find( $borrowernumber_hold ); +if ( $borrowernumber_hold && !$op ) { + my $patron = Koha::Patrons->find($borrowernumber_hold); my $diffbranch; # we check the reserves of the user, and if they can reserve a document @@ -195,7 +190,7 @@ if ($borrowernumber_hold && !$op) { my $reserves_count = $patron->holds->count; - my $new_reserves_count = scalar( @biblionumbers ); + my $new_reserves_count = scalar(@biblionumbers); my $maxreserves = C4::Context->preference('maxreserves'); $template->param( maxreserves => $maxreserves ); @@ -204,9 +199,9 @@ if ($borrowernumber_hold && !$op) { && ( $reserves_count + $new_reserves_count > $maxreserves ) ) { my $new_reserves_allowed = - $maxreserves - $reserves_count > 0 - ? $maxreserves - $reserves_count - : 0; + $maxreserves - $reserves_count > 0 + ? $maxreserves - $reserves_count + : 0; $warnings = 1; $exceeded_maxreserves = 1; $template->param( @@ -224,32 +219,33 @@ if ($borrowernumber_hold && !$op) { my $amount_outstanding = $patron->account->balance; $template->param( - patron => $patron, - diffbranch => $diffbranch, - messages => $messages, - warnings => $warnings, - amount_outstanding => $amount_outstanding, + patron => $patron, + diffbranch => $diffbranch, + messages => $messages, + warnings => $warnings, + amount_outstanding => $amount_outstanding, ); } -if ($club_hold && !$borrowernumber_hold && !$op) { +if ( $club_hold && !$borrowernumber_hold && !$op ) { my $club = Koha::Clubs->find($club_hold); my $enrollments = $club->club_enrollments; - my $maxreserves = C4::Context->preference('maxreserves'); - my $new_reserves_count = scalar( @biblionumbers ); + my $maxreserves = C4::Context->preference('maxreserves'); + my $new_reserves_count = scalar(@biblionumbers); my @members; - while(my $enrollment = $enrollments->next) { + while ( my $enrollment = $enrollments->next ) { next if $enrollment->is_canceled; - my $member = { patron => $enrollment->patron }; + my $member = { patron => $enrollment->patron }; my $reserves_count = $enrollment->patron->holds->count; if ( $maxreserves && ( $reserves_count + $new_reserves_count > $maxreserves ) ) { - $member->{new_reserves_allowed} = $maxreserves - $reserves_count > 0 + $member->{new_reserves_allowed} = + $maxreserves - $reserves_count > 0 ? $maxreserves - $reserves_count : 0; $member->{exceeded_maxreserves} = 1; @@ -263,10 +259,10 @@ if ($club_hold && !$borrowernumber_hold && !$op) { } $template->param( - club => $club, - members => \@members, - maxreserves => $maxreserves, - new_reserves_count => $new_reserves_count + club => $club, + members => \@members, + maxreserves => $maxreserves, + new_reserves_count => $new_reserves_count ); } @@ -286,72 +282,65 @@ if ( ( $findborrower && $borrowernumber_hold || $findclub && $club_hold ) || ( !$findborrower && !$findclub ) ) { # FIXME launch another time GetMember perhaps until (Joubu: Why?) - my $patron = Koha::Patrons->find( $borrowernumber_hold ); + my $patron = Koha::Patrons->find($borrowernumber_hold); if ( $patron && $multi_hold ) { my @multi_pickup_locations = - Koha::Biblios->search( { biblionumber => \@biblionumbers } ) - ->pickup_locations( { patron => $patron } )->as_list; + Koha::Biblios->search( { biblionumber => \@biblionumbers } )->pickup_locations( { patron => $patron } ) + ->as_list; $template->param( multi_pickup_locations => \@multi_pickup_locations ); } - my $logged_in_patron = Koha::Patrons->find( $borrowernumber ); + my $logged_in_patron = Koha::Patrons->find($borrowernumber); my $wants_check; if ($patron) { $wants_check = $patron->wants_check_for_previous_checkout; } - my $itemdata_enumchron = 0; - my $itemdata_ccode = 0; - my @biblioloop = (); + my $itemdata_enumchron = 0; + my $itemdata_ccode = 0; + my @biblioloop = (); my $no_reserves_allowed = 0; - my $num_bibs_available = 0; + my $num_bibs_available = 0; foreach my $biblionumber (@biblionumbers) { next unless $biblionumber =~ m|^\d+$|; my %biblioloopiter = (); - my $biblio = Koha::Biblios->find( $biblionumber ); + my $biblio = Koha::Biblios->find($biblionumber); unless ($biblio) { $biblioloopiter{noitems} = 1; - $template->param('nobiblio' => 1); + $template->param( 'nobiblio' => 1 ); last; } $biblioloopiter{object} = $biblio; - if ( $patron ) { - { # CanBookBeReserved + if ($patron) { + { # CanBookBeReserved my $canReserve = CanBookBeReserved( $patron->borrowernumber, $biblionumber ); if ( $canReserve->{status} eq 'OK' ) { #All is OK and we can continue - } - elsif ( $canReserve->{status} eq 'noReservesAllowed' || $canReserve->{status} eq 'notReservable' ) { + } elsif ( $canReserve->{status} eq 'noReservesAllowed' || $canReserve->{status} eq 'notReservable' ) { $no_reserves_allowed = 1; - } - elsif ( $canReserve->{status} eq 'tooManyReserves' ) { + } elsif ( $canReserve->{status} eq 'tooManyReserves' ) { $exceeded_maxreserves = 1; $template->param( maxreserves => $canReserve->{limit} ); - } - elsif ( $canReserve->{status} eq 'tooManyHoldsForThisRecord' ) { + } elsif ( $canReserve->{status} eq 'tooManyHoldsForThisRecord' ) { $exceeded_holds_per_record = 1; $biblioloopiter{ $canReserve->{status} } = 1; - } - elsif ( $canReserve->{status} eq 'ageRestricted' ) { + } elsif ( $canReserve->{status} eq 'ageRestricted' ) { $template->param( $canReserve->{status} => 1 ); $biblioloopiter{ $canReserve->{status} } = 1; - } - elsif ( $canReserve->{status} eq 'alreadypossession' ) { - $template->param( $canReserve->{status} => 1); - $biblioloopiter{ $canReserve->{status} } = 1; - } - elsif ( $canReserve->{status} eq 'recall' ) { + } elsif ( $canReserve->{status} eq 'alreadypossession' ) { $template->param( $canReserve->{status} => 1 ); $biblioloopiter{ $canReserve->{status} } = 1; - } - else { + } elsif ( $canReserve->{status} eq 'recall' ) { + $template->param( $canReserve->{status} => 1 ); + $biblioloopiter{ $canReserve->{status} } = 1; + } else { $biblioloopiter{ $canReserve->{status} } = 1; } } @@ -372,10 +361,10 @@ if ( ( $findborrower && $borrowernumber_hold || $findclub && $club_hold ) # For a librarian to be able to place multiple record holds for a patron for a record, # we must find out what the maximum number of holds they can place for the patron is - my $max_holds_for_record = GetMaxPatronHoldsForRecord( $patron->borrowernumber, $biblionumber ); + my $max_holds_for_record = GetMaxPatronHoldsForRecord( $patron->borrowernumber, $biblionumber ); my $remaining_holds_for_record = $max_holds_for_record - $holds->count(); $biblioloopiter{remaining_holds_for_record} = $max_holds_for_record; - $template->param( max_holds_for_record => $max_holds_for_record ); + $template->param( max_holds_for_record => $max_holds_for_record ); $template->param( remaining_holds_for_record => $remaining_holds_for_record ); } @@ -389,33 +378,34 @@ if ( ( $findborrower && $borrowernumber_hold || $findclub && $club_hold ) push @items, @host_items; } - unless ( @items ) { + unless (@items) { + # FIXME Then why do we continue? - $template->param('noitems' => 1) unless ( $multi_hold ); + $template->param( 'noitems' => 1 ) unless ($multi_hold); $biblioloopiter{noitems} = 1; } if ( $club_hold or $borrowernumber_hold ) { my @available_itemtypes; my $num_items_available = 0; - my $num_override = 0; - my $hiddencount = 0; - my $num_alreadyheld = 0; + my $num_override = 0; + my $hiddencount = 0; + my $num_alreadyheld = 0; # iterating through all items first to check if any of them available # to pass this value further inside down to IsAvailableForItemLevelRequest to # it's complicated logic to analyse. # (before this loop was inside that sub loop so it was O(n^2) ) - for my $item_object ( @items ) { + for my $item_object (@items) { my $do_check; my $item = $item_object->unblessed; $item->{object} = $item_object; - if ( $patron ) { + if ($patron) { $do_check = $patron->do_check_for_previous_checkout($item) if $wants_check; if ( $do_check && $wants_check ) { $item->{checked_previously} = $do_check; - if ( $multi_hold ) { + if ($multi_hold) { $biblioloopiter{checked_previously} = $do_check; } else { $template->param( checked_previously => $do_check ); @@ -425,15 +415,15 @@ if ( ( $findborrower && $borrowernumber_hold || $findclub && $club_hold ) $item->{itemtype} = $itemtypes->{ $item_object->effective_itemtype }; - if($item->{biblionumber} ne $biblio->biblionumber){ + if ( $item->{biblionumber} ne $biblio->biblionumber ) { $item->{hosttitle} = Koha::Biblios->find( $item->{biblionumber} )->title; } # if the item is currently on loan, we display its return date and # change the background color my $issue = $item_object->checkout; - if ( $issue ) { # FIXME must be moved to the template - $item->{date_due} = $issue->date_due; + if ($issue) { # FIXME must be moved to the template + $item->{date_due} = $issue->date_due; $item->{backgroundcolor} = 'onloan'; } @@ -442,12 +432,12 @@ if ( ( $findborrower && $borrowernumber_hold || $findclub && $club_hold ) if ( my $first_hold = $holds->next ) { my $p = Koha::Patrons->find( $first_hold->borrowernumber ); - $item->{backgroundcolor} = 'reserved'; - $item->{reservedate} = $first_hold->reservedate; - $item->{ReservedFor} = $p; - $item->{reserve_id} = $first_hold->reserve_id; - $item->{ExpectedAtLibrary} = $first_hold->branchcode; - $item->{waitingdate} = $first_hold->waitingdate; + $item->{backgroundcolor} = 'reserved'; + $item->{reservedate} = $first_hold->reservedate; + $item->{ReservedFor} = $p; + $item->{reserve_id} = $first_hold->reserve_id; + $item->{ExpectedAtLibrary} = $first_hold->branchcode; + $item->{waitingdate} = $first_hold->waitingdate; } # Management of the notforloan document @@ -458,7 +448,7 @@ if ( ( $findborrower && $borrowernumber_hold || $findclub && $club_hold ) # Management of lost or long overdue items if ( $item->{itemlost} ) { $item->{backgroundcolor} = 'other'; - if ($logged_in_patron->category->hidelostitems && !$showallitems) { + if ( $logged_in_patron->category->hidelostitems && !$showallitems ) { $item->{hide} = 1; $hiddencount++; } @@ -469,8 +459,8 @@ if ( ( $findborrower && $borrowernumber_hold || $findclub && $club_hold ) if ( $transfer && $transfer->in_transit ) { $item->{transfertwhen} = $transfer->datesent; $item->{transfertfrom} = $transfer->frombranch; - $item->{transfertto} = $transfer->tobranch; - $item->{nocancel} = 1; + $item->{transfertto} = $transfer->tobranch; + $item->{nocancel} = 1; } # If there is no loan, return and transfer, we show a checkbox. @@ -480,7 +470,8 @@ if ( ( $findborrower && $borrowernumber_hold || $findclub && $club_hold ) # if independent branches is on we need to check if the person can reserve # for branches they arent logged in to if ( C4::Context->preference("IndependentBranches") ) { - if (! C4::Context->preference("canreservefromotherbranches")){ + if ( !C4::Context->preference("canreservefromotherbranches") ) { + # can't reserve items so need to check if item homebranch and userenv branch match if not we can't reserve my $userenv = C4::Context->userenv; unless ( C4::Context->IsSuperLibrarian ) { @@ -489,25 +480,26 @@ if ( ( $findborrower && $borrowernumber_hold || $findclub && $club_hold ) } } - if ( $patron ) { - my $branch = _GetCircControlBranch($item_object, $patron); + if ($patron) { + my $branch = _GetCircControlBranch( $item_object, $patron ); my $branchitemrule = GetBranchItemRule( $branch, $item->{'itype'} ); $item->{'holdallowed'} = $branchitemrule->{'holdallowed'}; - my $can_item_be_reserved = CanItemBeReserved( $patron, $item_object, undef, { get_from_cache => 1 } )->{status}; + my $can_item_be_reserved = + CanItemBeReserved( $patron, $item_object, undef, { get_from_cache => 1 } )->{status}; $item->{not_holdable} = $can_item_be_reserved unless ( $can_item_be_reserved eq 'OK' ); $item->{not_holdable} ||= 'notforloan' if ( $item->{notforloanitype} || $item->{notforloan} > 0 ); - - $item->{item_level_holds} = Koha::CirculationRules->get_opacitemholds_policy( { item => $item_object, patron => $patron } ); + $item->{item_level_holds} = + Koha::CirculationRules->get_opacitemholds_policy( { item => $item_object, patron => $patron } ); my $default_hold_pickup_location_pref = C4::Context->preference('DefaultHoldPickupLocation'); my $default_pickup_branch; - if( $default_hold_pickup_location_pref eq 'homebranch' ){ + if ( $default_hold_pickup_location_pref eq 'homebranch' ) { $default_pickup_branch = $item->{homebranch}; - } elsif ( $default_hold_pickup_location_pref eq 'holdingbranch' ){ + } elsif ( $default_hold_pickup_location_pref eq 'holdingbranch' ) { $default_pickup_branch = $item->{holdingbranch}; } else { $default_pickup_branch = C4::Context->userenv->{branch}; @@ -517,34 +509,38 @@ if ( ( $findborrower && $borrowernumber_hold || $findclub && $club_hold ) !$item->{cantreserve} && !$exceeded_maxreserves && $can_item_be_reserved eq 'OK' + # items_any_available defined outside of the current loop, # so we avoiding loop inside IsAvailableForItemLevelRequest: - && IsAvailableForItemLevelRequest($item_object, $patron, undef) - ) + && IsAvailableForItemLevelRequest( $item_object, $patron, undef ) + ) { # Send the pickup locations count to the UI, the pickup locations will be pulled using the API - my $pickup_locations = $item_object->pickup_locations({ patron => $patron }); + my $pickup_locations = $item_object->pickup_locations( { patron => $patron } ); $item->{pickup_locations_count} = $pickup_locations->count; - if ( $item->{pickup_locations_count} > 0 || C4::Context->preference('AllowHoldPolicyOverride') ) { + if ( $item->{pickup_locations_count} > 0 || C4::Context->preference('AllowHoldPolicyOverride') ) + { $num_items_available++; $item->{available} = 1; + # pass the holding branch for use as default - my $default_pickup_location = $pickup_locations->search({ branchcode => $default_pickup_branch })->next; + my $default_pickup_location = + $pickup_locations->search( { branchcode => $default_pickup_branch } )->next; $item->{default_pickup_location} = $default_pickup_location; - } - else { - $item->{available} = 0; + } else { + $item->{available} = 0; $item->{not_holdable} = "no_valid_pickup_location"; } push( @available_itemtypes, $item->{itype} ); - } - elsif ( C4::Context->preference('AllowHoldPolicyOverride') ) { + } elsif ( C4::Context->preference('AllowHoldPolicyOverride') ) { + # If AllowHoldPolicyOverride is set, it should override EVERY restriction, not just branch item rules # with the exception of itemAlreadyOnHold because, you know, the item is already on hold if ( $can_item_be_reserved ne 'itemAlreadyOnHold' ) { + # Send the pickup locations count to the UI, the pickup locations will be pulled using the API - my @pickup_locations = $item_object->pickup_locations({ patron => $patron })->as_list; + my @pickup_locations = $item_object->pickup_locations( { patron => $patron } )->as_list; $item->{pickup_locations_count} = scalar @pickup_locations; if ( @pickup_locations || C4::Context->preference('AllowHoldPolicyOverride') ) { @@ -553,29 +549,32 @@ if ( ( $findborrower && $borrowernumber_hold || $findclub && $club_hold ) my $default_pickup_location; - ($default_pickup_location) = grep { $_->branchcode eq $default_pickup_branch } @pickup_locations; + ($default_pickup_location) = + grep { $_->branchcode eq $default_pickup_branch } @pickup_locations; $item->{default_pickup_location} = $default_pickup_location; - } - else { - $item->{available} = 0; + } else { + $item->{available} = 0; $item->{not_holdable} = "no_valid_pickup_location"; } - } else { $num_alreadyheld++ } + } else { + $num_alreadyheld++; + } push( @available_itemtypes, $item->{itype} ); } else { + # If none of the conditions hold true, then neither override nor available is set and the item cannot be checked $item->{available} = 0; } - # Show serial enumeration when needed - if ($item->{enumchron}) { + if ( $item->{enumchron} ) { $itemdata_enumchron = 1; } + # Show collection when needed - if ($item->{ccode}) { + if ( $item->{ccode} ) { $itemdata_ccode = 1; } } @@ -587,17 +586,18 @@ if ( ( $findborrower && $borrowernumber_hold || $findclub && $club_hold ) # While we can't override an alreay held item, we should be able to override the others # Unless all items are already held - if ( $num_override > 0 && ($num_override + $num_alreadyheld) == scalar( @{ $biblioloopiter{itemloop} } ) ) { - # That is, if all items require an override + if ( $num_override > 0 && ( $num_override + $num_alreadyheld ) == scalar( @{ $biblioloopiter{itemloop} } ) ) + { + # That is, if all items require an override $template->param( override_required => 1 ); } elsif ( $num_items_available == 0 ) { $template->param( none_available => 1 ); - $biblioloopiter{warn} = 1; + $biblioloopiter{warn} = 1; $biblioloopiter{none_avail} = 1; } - $template->param( hiddencount => $hiddencount); + $template->param( hiddencount => $hiddencount ); - @available_itemtypes = uniq( @available_itemtypes ); + @available_itemtypes = uniq(@available_itemtypes); $template->param( available_itemtypes => \@available_itemtypes ); } @@ -606,7 +606,7 @@ if ( ( $findborrower && $borrowernumber_hold || $findclub && $club_hold ) my $always_show_holds = $input->cookie('always_show_holds'); $template->param( always_show_holds => $always_show_holds ); my $show_holds_now = $input->param('show_holds_now'); - unless( (defined $always_show_holds && $always_show_holds eq 'DONT') && !$show_holds_now ){ + unless ( ( defined $always_show_holds && $always_show_holds eq 'DONT' ) && !$show_holds_now ) { my $holds_count_per_patron = { map { $_->{borrowernumber} => $_->{hold_count} } @{ Koha::Holds->search( { biblionumber => $biblionumber }, @@ -618,14 +618,15 @@ if ( ( $findborrower && $borrowernumber_hold || $findclub && $club_hold ) )->unblessed } }; - my @reserves = Koha::Holds->search( { biblionumber => $biblionumber }, { order_by => 'priority' } )->as_list; + my @reserves = + Koha::Holds->search( { biblionumber => $biblionumber }, { order_by => 'priority' } )->as_list; foreach my $res ( sort { my $a_found = $a->found() || ''; my $b_found = $a->found() || ''; $a_found cmp $b_found; } @reserves - ) + ) { my %reserve; if ( $res->is_found() ) { @@ -636,13 +637,12 @@ if ( ( $findborrower && $borrowernumber_hold || $findclub && $club_hold ) $reserve{'itemnumber'} = $res->itemnumber(); $reserve{'wbrname'} = $res->branch()->branchname(); $reserve{'atdestination'} = $res->is_at_destination(); - $reserve{'desk_name'} = ( $res->desk() ) ? $res->desk()->desk_name() : '' ; - $reserve{'found'} = $res->is_found(); - $reserve{'inprocessing'} = $res->is_in_processing(); - $reserve{'intransit'} = $res->is_in_transit(); - } - elsif ( $res->priority() > 0 ) { - if ( my $item = $res->item() ) { + $reserve{'desk_name'} = ( $res->desk() ) ? $res->desk()->desk_name() : ''; + $reserve{'found'} = $res->is_found(); + $reserve{'inprocessing'} = $res->is_in_processing(); + $reserve{'intransit'} = $res->is_in_transit(); + } elsif ( $res->priority() > 0 ) { + if ( my $item = $res->item() ) { $reserve{'itemnumber'} = $item->id(); $reserve{'barcodenumber'} = $item->barcode(); $reserve{'item_level_hold'} = 1; @@ -655,7 +655,7 @@ if ( ( $findborrower && $borrowernumber_hold || $findclub && $club_hold ) $reserve{'patron'} = $res->borrower; $reserve{'notes'} = $res->reservenotes(); $reserve{'waiting_date'} = $res->waitingdate(); - $reserve{'ccode'} = $res->item() ? $res->item()->ccode() : undef; + $reserve{'ccode'} = $res->item() ? $res->item()->ccode() : undef; $reserve{'barcode'} = $res->item() ? $res->item()->barcode() : undef; $reserve{'priority'} = $res->priority(); $reserve{'lowestPriority'} = $res->lowestPriority(); @@ -679,36 +679,37 @@ if ( ( $findborrower && $borrowernumber_hold || $findclub && $club_hold ) my $time = time(); $template->param( - time => $time, - fixedRank => $fixedRank, - ); + time => $time, + fixedRank => $fixedRank, + ); # display infos $template->param( - itemdata_enumchron => $itemdata_enumchron, - itemdata_ccode => $itemdata_ccode, - date => dt_from_string, - biblionumber => $biblionumber, - findborrower => $findborrower, - biblio => $biblio, - holdsview => 1, - C4::Search::enabled_staff_search_views, - ); + itemdata_enumchron => $itemdata_enumchron, + itemdata_ccode => $itemdata_ccode, + date => dt_from_string, + biblionumber => $biblionumber, + findborrower => $findborrower, + biblio => $biblio, + holdsview => 1, + C4::Search::enabled_staff_search_views, + ); $biblioloopiter{biblionumber} = $biblionumber; - $biblioloopiter{title} = $biblio->title; - $biblioloopiter{author} = $biblio->author; - $biblioloopiter{rank} = $fixedRank; - $biblioloopiter{reserveloop} = \@reserveloop; + $biblioloopiter{title} = $biblio->title; + $biblioloopiter{author} = $biblio->author; + $biblioloopiter{rank} = $fixedRank; + $biblioloopiter{reserveloop} = \@reserveloop; if (@reserveloop) { $template->param( reserveloop => \@reserveloop ); } if ( $patron && $multi_hold ) { + # Add the valid pickup locations - my @pickup_locations = $biblio->pickup_locations({ patron => $patron })->as_list; - $biblioloopiter{pickup_locations} = \@pickup_locations; + my @pickup_locations = $biblio->pickup_locations( { patron => $patron } )->as_list; + $biblioloopiter{pickup_locations} = \@pickup_locations; $biblioloopiter{pickup_locations_codes} = [ map { $_->branchcode } @pickup_locations ]; } @@ -718,12 +719,13 @@ if ( ( $findborrower && $borrowernumber_hold || $findclub && $club_hold ) $template->param( no_bibs_available => 1 ) unless $num_bibs_available > 0; - $template->param( biblioloop => \@biblioloop ); - $template->param( no_reserves_allowed => $no_reserves_allowed ); - $template->param( exceeded_maxreserves => $exceeded_maxreserves ); + $template->param( biblioloop => \@biblioloop ); + $template->param( no_reserves_allowed => $no_reserves_allowed ); + $template->param( exceeded_maxreserves => $exceeded_maxreserves ); $template->param( exceeded_holds_per_record => $exceeded_holds_per_record ); + # FIXME: getting just the first bib's result doesn't seem right - $template->param( subscriptionsnumber => CountSubscriptionFromBiblionumber($biblionumbers[0])); + $template->param( subscriptionsnumber => CountSubscriptionFromBiblionumber( $biblionumbers[0] ) ); } unless ($multi_hold) { my $biblio = Koha::Biblios->find( $biblionumbers[0] ); @@ -734,7 +736,7 @@ $template->param( biblionumbers => \@biblionumbers ); # pass the userenv branch if no pickup location selected $template->param( pickup => $pickup || C4::Context->userenv->{branch} ); -$template->param(borrowernumber => $borrowernumber_hold); +$template->param( borrowernumber => $borrowernumber_hold ); $template->param( failed_holds => \@failed_holds ); @@ -744,9 +746,7 @@ output_html_with_http_headers $input, $cookie, $template->output; sub sort_borrowerlist { my $borrowerslist = shift; my $ref = []; - push @{$ref}, sort { - uc( $a->{surname} . $a->{firstname} ) cmp - uc( $b->{surname} . $b->{firstname} ) - } @{$borrowerslist}; + push @{$ref}, + sort { uc( $a->{surname} . $a->{firstname} ) cmp uc( $b->{surname} . $b->{firstname} ) } @{$borrowerslist}; return $ref; } diff --git a/reviews/reviewswaiting.pl b/reviews/reviewswaiting.pl index 1954482c0d..451ff28dbd 100755 --- a/reviews/reviewswaiting.pl +++ b/reviews/reviewswaiting.pl @@ -17,8 +17,8 @@ use Modern::Perl; -use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( pagination_bar output_html_with_http_headers ); use C4::Context; use Koha::Biblios; @@ -28,31 +28,29 @@ use Koha::Reviews; my $query = CGI->new; my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "reviews/reviewswaiting.tt", - query => $query, - type => "intranet", - flagsrequired => { tools => 'moderate_comments' }, + template_name => "reviews/reviewswaiting.tt", + query => $query, + type => "intranet", + flagsrequired => { tools => 'moderate_comments' }, } ); -my $op = $query->param('op') || ''; -my $status = $query->param('status') || 0; -my $reviewid = $query->param('reviewid'); -my $page = $query->param('page') || 1; -my $count = C4::Context->preference('numSearchResults') || 20; -my $total = Koha::Reviews->search_limited({ approved => $status })->count; +my $op = $query->param('op') || ''; +my $status = $query->param('status') || 0; +my $reviewid = $query->param('reviewid'); +my $page = $query->param('page') || 1; +my $count = C4::Context->preference('numSearchResults') || 20; +my $total = Koha::Reviews->search_limited( { approved => $status } )->count; my $biblionumber = $query->param('biblionumber'); if ( $op eq 'cud-approve' ) { - my $review = Koha::Reviews->find( $reviewid ); + my $review = Koha::Reviews->find($reviewid); $review->approve if $review; -} -elsif ( $op eq 'cud-unapprove' ) { - my $review = Koha::Reviews->find( $reviewid ); +} elsif ( $op eq 'cud-unapprove' ) { + my $review = Koha::Reviews->find($reviewid); $review->unapprove if $review; -} -elsif ( $op eq 'cud-delete' ) { - my $review = Koha::Reviews->find( $reviewid ); +} elsif ( $op eq 'cud-delete' ) { + my $review = Koha::Reviews->find($reviewid); $review->delete if $review; } @@ -64,20 +62,21 @@ if ( $op && $biblionumber ) { my $reviews = Koha::Reviews->search_limited( { approved => $status }, { - rows => $count, - page => $page, + rows => $count, + page => $page, order_by => { -desc => 'datereviewed' }, } )->unblessed; -for my $review ( @$reviews ) { - my $biblio = Koha::Biblios->find( $review->{biblionumber} ); +for my $review (@$reviews) { + my $biblio = Koha::Biblios->find( $review->{biblionumber} ); + # setting some borrower info into this hash $review->{bibliotitle} = $biblio->title; my $borrowernumber = $review->{borrowernumber}; - my $patron = Koha::Patrons->find( $borrowernumber); - if ( $patron ) { + my $patron = Koha::Patrons->find($borrowernumber); + if ($patron) { $review->{patron} = $patron; } } @@ -85,9 +84,10 @@ for my $review ( @$reviews ) { my $url = "/cgi-bin/koha/reviews/reviewswaiting.pl?status=$status"; $template->param( - status => $status, - reviews => $reviews, - pagination_bar => pagination_bar( $url, ( int( $total / $count ) ) + ( ( $total % $count ) > 0 ? 1 : 0 ), $page, "page" ) + status => $status, + reviews => $reviews, + pagination_bar => + pagination_bar( $url, ( int( $total / $count ) ) + ( ( $total % $count ) > 0 ? 1 : 0 ), $page, "page" ) ); output_html_with_http_headers $query, $cookie, $template->output; diff --git a/rotating_collections/addItems.pl b/rotating_collections/addItems.pl index 1872578095..ef9c5eb744 100755 --- a/rotating_collections/addItems.pl +++ b/rotating_collections/addItems.pl @@ -19,7 +19,7 @@ use Modern::Perl; use C4::Output qw( output_html_with_http_headers ); -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Context; use C4::RotatingCollections; @@ -28,23 +28,24 @@ use Koha::Items; use CGI qw ( -utf8 ); my $query = CGI->new; -my $op = $query->param('op') || q{}; +my $op = $query->param('op') || q{}; my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "rotating_collections/addItems.tt", - query => $query, - type => "intranet", - flagsrequired => { tools => 'rotating_collections' }, + template_name => "rotating_collections/addItems.tt", + query => $query, + type => "intranet", + flagsrequired => { tools => 'rotating_collections' }, } ); -if ( defined $op and - $op eq 'cud-add' ) { +if ( defined $op + and $op eq 'cud-add' ) +{ ## Add the given item to the collection my $colId = $query->param('colId'); my $barcode = $query->param('barcode'); my $removeItem = $query->param('removeItem'); - my $item = Koha::Items->find({barcode => $barcode}); + my $item = Koha::Items->find( { barcode => $barcode } ); my $itemnumber = $item ? $item->itemnumber : undef; my ( $success, $errorCode, $errorMessage ); @@ -52,8 +53,7 @@ if ( defined $op and $template->param( barcode => $barcode ); if ( !$removeItem ) { - ( $success, $errorCode, $errorMessage ) = - AddItemToCollection( $colId, $itemnumber ); + ( $success, $errorCode, $errorMessage ) = AddItemToCollection( $colId, $itemnumber ); $template->param( previousActionAdd => 1, @@ -61,16 +61,13 @@ if ( defined $op and if ($success) { $template->param( addSuccess => 1 ); - } - else { + } else { $template->param( addFailure => 1 ); $template->param( failureMessage => $errorMessage ); } - } - else { + } else { ## Remove the given item from the collection - ( $success, $errorCode, $errorMessage ) = - RemoveItemFromCollection( $colId, $itemnumber ); + ( $success, $errorCode, $errorMessage ) = RemoveItemFromCollection( $colId, $itemnumber ); $template->param( previousActionRemove => 1, @@ -79,8 +76,7 @@ if ( defined $op and if ($success) { $template->param( removeSuccess => 1 ); - } - else { + } else { $template->param( removeFailure => 1 ); $template->param( failureMessage => $errorMessage ); } @@ -89,7 +85,7 @@ if ( defined $op and } my ( $colId, $colTitle, $colDescription, $colBranchcode ) = - GetCollection( scalar $query->param('colId') ); + GetCollection( scalar $query->param('colId') ); my $collectionItems = GetItemsInCollection($colId); if ($collectionItems) { $template->param( collectionItemsLoop => $collectionItems ); diff --git a/rotating_collections/editCollections.pl b/rotating_collections/editCollections.pl index 0d473e49e5..43e3cd64a2 100755 --- a/rotating_collections/editCollections.pl +++ b/rotating_collections/editCollections.pl @@ -21,7 +21,7 @@ use Modern::Perl; use CGI qw ( -utf8 ); use C4::Output qw( output_html_with_http_headers ); -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Context; use C4::RotatingCollections; @@ -30,15 +30,15 @@ my $query = CGI->new; my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "rotating_collections/editCollections.tt", - query => $query, - type => "intranet", - flagsrequired => { tools => 'rotating_collections' }, + template_name => "rotating_collections/editCollections.tt", + query => $query, + type => "intranet", + flagsrequired => { tools => 'rotating_collections' }, } ); my $action = $query->param('action'); -my $op = $query->param('op'); +my $op = $query->param('op'); $template->param( op => $op ); # Create new Collection @@ -46,8 +46,7 @@ if ( $op eq 'cud-create' ) { my $title = $query->param('title'); my $description = $query->param('description'); - my ( $createdSuccessfully, $errorCode, $errorMessage ) = - CreateCollection( $title, $description ); + my ( $createdSuccessfully, $errorCode, $errorMessage ) = CreateCollection( $title, $description ); $template->param( previousActionCreate => 1, @@ -56,8 +55,7 @@ if ( $op eq 'cud-create' ) { if ($createdSuccessfully) { $template->param( createSuccess => 1 ); - } - else { + } else { $template->param( createFailure => 1 ); $template->param( failureMessage => $errorMessage ); } @@ -71,8 +69,7 @@ elsif ( $op eq 'cud-delete' ) { $template->param( previousActionDelete => 1 ); if ($success) { $template->param( deleteSuccess => 1 ); - } - else { + } else { $template->param( deleteFailure => 1 ); $template->param( failureMessage => $errorMessage ); } @@ -96,8 +93,7 @@ elsif ( $op eq 'cud-update' ) { my $title = $query->param('title'); my $description = $query->param('description'); - my ( $createdSuccessfully, $errorCode, $errorMessage ) = - UpdateCollection( $colId, $title, $description ); + my ( $createdSuccessfully, $errorCode, $errorMessage ) = UpdateCollection( $colId, $title, $description ); $template->param( previousActionUpdate => 1, @@ -106,8 +102,7 @@ elsif ( $op eq 'cud-update' ) { if ($createdSuccessfully) { $template->param( updateSuccess => 1 ); - } - else { + } else { $template->param( updateFailure => 1 ); $template->param( failureMessage => $errorMessage ); } diff --git a/rotating_collections/rotatingCollections.pl b/rotating_collections/rotatingCollections.pl index b350861d1e..d212767a63 100755 --- a/rotating_collections/rotatingCollections.pl +++ b/rotating_collections/rotatingCollections.pl @@ -21,7 +21,7 @@ use Modern::Perl; use CGI qw ( -utf8 ); use C4::Output qw( output_html_with_http_headers ); -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Context; use C4::RotatingCollections; @@ -29,10 +29,10 @@ my $query = CGI->new; my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "rotating_collections/rotatingCollections.tt", - query => $query, - type => "intranet", - flagsrequired => { tools => 'rotating_collections' }, + template_name => "rotating_collections/rotatingCollections.tt", + query => $query, + type => "intranet", + flagsrequired => { tools => 'rotating_collections' }, } ); diff --git a/rotating_collections/transferCollection.pl b/rotating_collections/transferCollection.pl index adc196eb4d..3c5bc7ae40 100755 --- a/rotating_collections/transferCollection.pl +++ b/rotating_collections/transferCollection.pl @@ -19,7 +19,7 @@ use Modern::Perl; use C4::Output qw( output_html_with_http_headers ); -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Context; use C4::RotatingCollections; @@ -33,26 +33,24 @@ my $toBranch = $query->param('toBranch'); my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "rotating_collections/transferCollection.tt", - query => $query, - type => "intranet", - flagsrequired => { tools => 'rotating_collections' }, + template_name => "rotating_collections/transferCollection.tt", + query => $query, + type => "intranet", + flagsrequired => { tools => 'rotating_collections' }, } ); ## Transfer collection my ( $success, $messages ); -if ( $op eq 'cud-transfer' && $toBranch) { - ( $success, $messages ) = - TransferCollection( $colId, $toBranch ); +if ( $op eq 'cud-transfer' && $toBranch ) { + ( $success, $messages ) = TransferCollection( $colId, $toBranch ); if ($success) { $template->param( transferSuccess => 1, messages => $messages ); - } - else { + } else { $template->param( transferFailure => 1, messages => $messages @@ -64,10 +62,10 @@ if ( $op eq 'cud-transfer' && $toBranch) { my ( $colTitle, $colDesc, $colBranchcode ); ( $colId, $colTitle, $colDesc, $colBranchcode ) = GetCollection($colId); $template->param( - colId => $colId, - colTitle => $colTitle, - colDesc => $colDesc, - colBranchcode => $colBranchcode, + colId => $colId, + colTitle => $colTitle, + colDesc => $colDesc, + colBranchcode => $colBranchcode, ); output_html_with_http_headers $query, $cookie, $template->output; diff --git a/serials/acqui-search-result.pl b/serials/acqui-search-result.pl index a2d1ae5b94..6566f2194d 100755 --- a/serials/acqui-search-result.pl +++ b/serials/acqui-search-result.pl @@ -20,7 +20,6 @@ # You should have received a copy of the GNU General Public License # along with Koha; if not, see . - =head1 NAME acqui-search-result.pl @@ -39,36 +38,40 @@ acqui-search-result.pl =cut - use Modern::Perl; -use C4::Auth qw( get_template_and_user ); -use C4::Output qw( output_html_with_http_headers ); -use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); +use C4::Output qw( output_html_with_http_headers ); +use CGI qw ( -utf8 ); use C4::Acquisition qw( SearchOrders ); use Koha::DateUtils qw( output_pref ); use Koha::Acquisition::Booksellers; -my $query=CGI->new; -my ($template, $loggedinuser, $cookie) - = get_template_and_user({template_name => "serials/acqui-search-result.tt", - query => $query, - type => "intranet", - flagsrequired => {serials => '*'}, - }); +my $query = CGI->new; +my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "serials/acqui-search-result.tt", + query => $query, + type => "intranet", + flagsrequired => { serials => '*' }, + } +); -my $supplier=$query->param('supplier'); +my $supplier = $query->param('supplier'); my @suppliers = Koha::Acquisition::Booksellers->search( - { name => { -like => "%$supplier%" } }, - { order_by => { -asc => 'name' } } )->as_list; + { name => { -like => "%$supplier%" } }, + { order_by => { -asc => 'name' } } +)->as_list; #build result page my $loop_suppliers = []; for my $s (@suppliers) { - my $orders = SearchOrders({ - booksellerid => $s->id, - pending => 1 - }); + my $orders = SearchOrders( + { + booksellerid => $s->id, + pending => 1 + } + ); my $loop_basket = []; for my $ord ( @{$orders} ) { @@ -81,15 +84,17 @@ for my $s (@suppliers) { }; } push @{$loop_suppliers}, { - loop_basket => $loop_basket, + loop_basket => $loop_basket, aqbooksellerid => $s->id, - name => $s->name, - active => $s->active, + name => $s->name, + active => $s->active, }; } -$template->param(loop_suppliers => $loop_suppliers, - supplier => $supplier, - count => scalar @suppliers); +$template->param( + loop_suppliers => $loop_suppliers, + supplier => $supplier, + count => scalar @suppliers +); output_html_with_http_headers $query, $cookie, $template->output; diff --git a/serials/acqui-search.pl b/serials/acqui-search.pl index 682b5bbe7d..2e9a035ef5 100755 --- a/serials/acqui-search.pl +++ b/serials/acqui-search.pl @@ -17,20 +17,19 @@ # You should have received a copy of the GNU General Public License # along with Koha; if not, see . - use Modern::Perl; -use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); my $query = CGI->new; my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "serials/acqui-search.tt", - query => $query, - type => "intranet", - flagsrequired => { serials => '*' }, + template_name => "serials/acqui-search.tt", + query => $query, + type => "intranet", + flagsrequired => { serials => '*' }, } ); diff --git a/serials/checkexpiration.pl b/serials/checkexpiration.pl index e253f1876b..ff2cc96eaa 100755 --- a/serials/checkexpiration.pl +++ b/serials/checkexpiration.pl @@ -16,7 +16,6 @@ # You should have received a copy of the GNU General Public License # along with Koha; if not, see . - =head1 NAME checkexpiration.pl @@ -43,10 +42,10 @@ The date to filter on. =cut use Modern::Perl; -use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); use C4::Serials qw( SearchSubscriptions GetExpirationDate ); -use C4::Output qw( output_html_with_http_headers ); +use C4::Output qw( output_html_with_http_headers ); use C4::Context; use Koha::DateUtils qw( dt_from_string ); @@ -54,38 +53,38 @@ use DateTime; my $query = CGI->new; -my ( $template, $loggedinuser, $cookie, $flags ) = get_template_and_user ( +my ( $template, $loggedinuser, $cookie, $flags ) = get_template_and_user( { - template_name => "serials/checkexpiration.tt", - query => $query, - type => "intranet", - flagsrequired => { serials => 'check_expiration' }, + template_name => "serials/checkexpiration.tt", + query => $query, + type => "intranet", + flagsrequired => { serials => 'check_expiration' }, } ); -my $title = $query->param('title'); -my $issn = $query->param('issn'); +my $title = $query->param('title'); +my $issn = $query->param('issn'); my $branch = $query->param('branch'); -my $date = $query->param('date'); +my $date = $query->param('date'); $date = eval { dt_from_string( scalar $query->param('date') ) } if $date; my $showhistoricexpired = $query->param('showhistoricexpired'); if ($date) { - my @subscriptions = SearchSubscriptions({ title => $title, issn => $issn, orderby => 'title' }); + my @subscriptions = SearchSubscriptions( { title => $title, issn => $issn, orderby => 'title' } ); my @subscriptions_loop; - foreach my $subscription ( @subscriptions ) { + foreach my $subscription (@subscriptions) { my $subscriptionid = $subscription->{'subscriptionid'}; my $expirationdate = GetExpirationDate($subscriptionid); $subscription->{expirationdate} = $expirationdate; - next if $expirationdate !~ /\d{4}-\d{2}-\d{2}/; # next if not in ISO format. + next if $expirationdate !~ /\d{4}-\d{2}-\d{2}/; # next if not in ISO format. next if $subscription->{closed}; - if ( !C4::Context->preference("IndependentBranches") + if ( !C4::Context->preference("IndependentBranches") or C4::Context->IsSuperLibrarian() - or ( ref $flags->{serials} and $flags->{serials}->{superserials} ) + or ( ref $flags->{serials} and $flags->{serials}->{superserials} ) or ( !ref $flags->{serials} and $flags->{serials} == 1 ) ) { $subscription->{cannotedit} = 0; @@ -93,10 +92,11 @@ if ($date) { next if $subscription->{cannotedit}; my $expirationdate_dt = dt_from_string( $expirationdate, 'iso' ); - my $today_dt = dt_from_string(); + my $today_dt = dt_from_string(); if ( DateTime->compare( $date, $expirationdate_dt ) == 1 && ( $showhistoricexpired || DateTime->compare( $expirationdate_dt, $today_dt ) == 1 ) - && ( !$branch || ( $subscription->{'branchcode'} eq $branch ) ) ) { + && ( !$branch || ( $subscription->{'branchcode'} eq $branch ) ) ) + { push @subscriptions_loop, $subscription; } } @@ -108,11 +108,11 @@ if ($date) { numsubscription => scalar @subscriptions_loop, date => $date, subscriptions_loop => \@subscriptions_loop, - searched => 1, + searched => 1, ); } -my $can_change_library;; +my $can_change_library; if ( !C4::Context->preference("IndependentBranches") or C4::Context->IsSuperLibrarian() or ( ref $flags->{serials} and $flags->{serials}->{superserials} ) @@ -121,10 +121,10 @@ if ( !C4::Context->preference("IndependentBranches") $can_change_library = 1; } -$template->param ( - (uc(C4::Context->preference("marcflavour"))) => 1, - can_change_library => $can_change_library, - branch => $branch, +$template->param( + ( uc( C4::Context->preference("marcflavour") ) ) => 1, + can_change_library => $can_change_library, + branch => $branch, ); output_html_with_http_headers $query, $cookie, $template->output; diff --git a/serials/claims.pl b/serials/claims.pl index 363541fedf..f2d3ede0b1 100755 --- a/serials/claims.pl +++ b/serials/claims.pl @@ -18,10 +18,10 @@ # along with Koha; if not, see . use Modern::Perl; -use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); use C4::Serials qw( GetSuppliersWithLateIssues GetLateOrMissingIssues updateClaim can_claim_subscription ); -use C4::Output qw( output_html_with_http_headers ); +use C4::Output qw( output_html_with_http_headers ); use C4::Context; use C4::Letters qw( GetLetters SendAlerts ); @@ -30,33 +30,35 @@ use Koha::CsvProfiles; my $input = CGI->new; -my $serialid = $input->param('serialid'); -my $op = $input->param('op'); -my $claimletter = $input->param('claimletter'); -my $supplierid = $input->param('supplierid'); +my $serialid = $input->param('serialid'); +my $op = $input->param('op'); +my $claimletter = $input->param('claimletter'); +my $supplierid = $input->param('supplierid'); my $suppliername = $input->param('suppliername'); # open template first (security & userenv set here) -my ($template, $loggedinuser, $cookie) -= get_template_and_user({template_name => 'serials/claims.tt', - query => $input, - type => 'intranet', - flagsrequired => {serials => 'claim_serials'}, - }); +my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => 'serials/claims.tt', + query => $input, + type => 'intranet', + flagsrequired => { serials => 'claim_serials' }, + } +); # supplierlist is returned in name order my $supplierlist = GetSuppliersWithLateIssues(); -for my $s (@{$supplierlist} ) { - $s->{count} = scalar GetLateOrMissingIssues($s->{id}); - if ($supplierid && $s->{id} == $supplierid) { +for my $s ( @{$supplierlist} ) { + $s->{count} = scalar GetLateOrMissingIssues( $s->{id} ); + if ( $supplierid && $s->{id} == $supplierid ) { $s->{selected} = 1; } } my $additional_fields = Koha::AdditionalFields->search( { tablename => 'subscription', searchable => 1 } ); -my @serialnums=$input->multi_param('serialid'); -if (@serialnums) { # i.e. they have been flagged to generate claims +my @serialnums = $input->multi_param('serialid'); +if (@serialnums) { # i.e. they have been flagged to generate claims my $err; eval { $err = SendAlerts( 'claimissues', \@serialnums, scalar $input->param("letter_code") ); @@ -64,8 +66,8 @@ if (@serialnums) { # i.e. they have been flagged to generate claims C4::Serials::updateClaim( \@serialnums ); } }; - if ( $@ ) { - $template->param(error_claim => $@); + if ($@) { + $template->param( error_claim => $@ ); } elsif ( ref $err and exists $err->{error} ) { if ( $err->{error} eq "no_email" ) { $template->param( error_claim => 'no_vendor_email' ); @@ -77,15 +79,15 @@ if (@serialnums) { # i.e. they have been flagged to generate claims } } -my $letters = GetLetters({ module => 'claimissues' }); +my $letters = GetLetters( { module => 'claimissues' } ); my @missingissues; if ($supplierid) { - my $supplier = Koha::Acquisition::Booksellers->find( $supplierid ); + my $supplier = Koha::Acquisition::Booksellers->find($supplierid); @missingissues = GetLateOrMissingIssues($supplierid); foreach my $issue (@missingissues) { $issue->{cannot_claim} = 1 - unless C4::Serials::can_claim_subscription($issue); + unless C4::Serials::can_claim_subscription($issue); $issue->{additional_field_values} = Koha::Subscriptions->find( $issue->{subscriptionid} )->get_additional_field_values_for_template; @@ -94,13 +96,13 @@ if ($supplierid) { } $template->param( - suploop => $supplierlist, - missingissues => \@missingissues, - supplierid => $supplierid, - claimletter => $claimletter, - additional_fields_for_subscription => $additional_fields, - csv_profiles => Koha::CsvProfiles->search({ type => 'sql', used_for => 'late_issues' }), - letters => $letters, - (uc(C4::Context->preference("marcflavour"))) => 1 - ); + suploop => $supplierlist, + missingissues => \@missingissues, + supplierid => $supplierid, + claimletter => $claimletter, + additional_fields_for_subscription => $additional_fields, + csv_profiles => Koha::CsvProfiles->search( { type => 'sql', used_for => 'late_issues' } ), + letters => $letters, + ( uc( C4::Context->preference("marcflavour") ) ) => 1 +); output_html_with_http_headers $input, $cookie, $template->output; diff --git a/serials/create-numberpattern.pl b/serials/create-numberpattern.pl index a28ef0d415..a2f37afa83 100755 --- a/serials/create-numberpattern.pl +++ b/serials/create-numberpattern.pl @@ -28,32 +28,37 @@ use C4::Auth qw( check_cookie_auth ); my $input = CGI->new; -my ($auth_status) = check_cookie_auth($input->cookie('CGISESSID'), { serials => '*' }); -if ($auth_status ne "ok") { - print $input->header(-type => 'text/plain', -status => '403 Forbidden'); +my ($auth_status) = check_cookie_auth( $input->cookie('CGISESSID'), { serials => '*' } ); +if ( $auth_status ne "ok" ) { + print $input->header( -type => 'text/plain', -status => '403 Forbidden' ); exit 0; } my $numberpattern; -foreach (qw/ numberingmethod label1 label2 label3 add1 add2 add3 - every1 every2 every3 setto1 setto2 setto3 whenmorethan1 whenmorethan2 - whenmorethan3 numbering1 numbering2 numbering3 locale /) { +foreach ( + qw/ numberingmethod label1 label2 label3 add1 add2 add3 + every1 every2 every3 setto1 setto2 setto3 whenmorethan1 whenmorethan2 + whenmorethan3 numbering1 numbering2 numbering3 locale / + ) +{ $numberpattern->{$_} = $input->param($_); } + # patternname is label in database $numberpattern->{'label'} = $input->param('patternname'); # Check if pattern already exist in database -my $dbh = C4::Context->dbh; +my $dbh = C4::Context->dbh; my $query = qq{ SELECT id FROM subscription_numberpatterns WHERE STRCMP(label, ?) = 0 }; my $sth = $dbh->prepare($query); -my $rv = $sth->execute($numberpattern->{'label'}); +my $rv = $sth->execute( $numberpattern->{'label'} ); my $numberpatternid; -if($rv == 0) { +if ( $rv == 0 ) { + # Pattern does not exists $numberpatternid = AddSubscriptionNumberpattern($numberpattern); } else { @@ -63,5 +68,5 @@ if($rv == 0) { } binmode STDOUT, ":encoding(UTF-8)"; -print $input->header(-type => 'text/plain', -charset => 'UTF-8'); +print $input->header( -type => 'text/plain', -charset => 'UTF-8' ); print "{\"numberpatternid\":\"$numberpatternid\"}"; diff --git a/serials/lateissues-export.pl b/serials/lateissues-export.pl index 12130d4434..a46b880cd7 100755 --- a/serials/lateissues-export.pl +++ b/serials/lateissues-export.pl @@ -36,11 +36,11 @@ if ( $auth_status ne "ok" ) { } my $supplierid = $query->param('supplierid'); -my @serialids = $query->multi_param('serialid'); -my $op = $query->param('op') || q{}; +my @serialids = $query->multi_param('serialid'); +my $op = $query->param('op') || q{}; my $csv_profile_id = $query->param('csv_profile'); -my $csv_profile = Koha::CsvProfiles->find( $csv_profile_id ); +my $csv_profile = Koha::CsvProfiles->find($csv_profile_id); die "There is no valid csv profile given" unless $csv_profile; my $delimiter = $csv_profile->csv_separator; @@ -58,29 +58,31 @@ my $csv = Text::CSV_XS->new( my $content = $csv_profile->content; my ( @headers, @fields ); -while ( $content =~ / +while ( + $content =~ / ([^=\|]+) # header =? ([^\|]*) # fieldname (table.row or row) \|? /gxms -) { + ) +{ my $header = $1; - my $field = ($2 eq '') ? $1 : $2; + my $field = ( $2 eq '' ) ? $1 : $2; - $header =~ s/^\s+|\s+$//g; # Trim whitespaces + $header =~ s/^\s+|\s+$//g; # Trim whitespaces push @headers, $header; - $field =~ s/[^.]+\.//; # Remove the table name if exists. - $field =~ s/^\s+|\s+$//g; # Trim whitespaces + $field =~ s/[^.]+\.//; # Remove the table name if exists. + $field =~ s/^\s+|\s+$//g; # Trim whitespaces push @fields, $field; } my @rows; -for my $serialid ( @serialids ) { - my @missingissues = GetLateOrMissingIssues($supplierid, $serialid); - my $issue = $missingissues[0]; +for my $serialid (@serialids) { + my @missingissues = GetLateOrMissingIssues( $supplierid, $serialid ); + my $issue = $missingissues[0]; my @row; - for my $field ( @fields ) { + for my $field (@fields) { push @row, $issue->{$field}; } push @rows, \@row; @@ -96,7 +98,7 @@ print $query->header( print join( $delimiter, @headers ) . "\n"; -for my $row ( @rows ) { +for my $row (@rows) { $csv->combine(@$row); my $string = $csv->string; print $string, "\n"; diff --git a/serials/reorder_members.pl b/serials/reorder_members.pl index 7edeb80909..e19d6c2487 100755 --- a/serials/reorder_members.pl +++ b/serials/reorder_members.pl @@ -19,8 +19,8 @@ # where the hierarchical order can be changed on the fly and a routing list can be # printed out use Modern::Perl; -use CGI qw ( -utf8 ); -use C4::Auth qw( checkauth ); +use CGI qw ( -utf8 ); +use C4::Auth qw( checkauth ); use C4::Serials qw( reorder_members ); my $query = CGI->new; @@ -32,6 +32,5 @@ checkauth( $query, 0, { serials => 'routing' }, 'intranet' ); reorder_members( $subscriptionid, $routingid, $rank ); -print $query->redirect( - "/cgi-bin/koha/serials/routing.pl?subscriptionid=$subscriptionid"); +print $query->redirect("/cgi-bin/koha/serials/routing.pl?subscriptionid=$subscriptionid"); diff --git a/serials/routing-preview.pl b/serials/routing-preview.pl index aa44f7e28b..778c3a38a5 100755 --- a/serials/routing-preview.pl +++ b/serials/routing-preview.pl @@ -21,8 +21,8 @@ use Modern::Perl; use CGI qw ( -utf8 ); use C4::Koha; -use C4::Auth qw( get_template_and_user ); -use C4::Output qw( output_html_with_http_headers ); +use C4::Auth qw( get_template_and_user ); +use C4::Output qw( output_html_with_http_headers ); use C4::Reserves qw( AddReserve ModReserve ); use C4::Context; use C4::Serials qw( delroutingmember getroutinglist GetSubscription GetSerials check_routing ); @@ -32,58 +32,61 @@ use Koha::Biblios; use Koha::Libraries; use Koha::Patrons; -my $query = CGI->new; +my $query = CGI->new; my $subscriptionid = $query->param('subscriptionid'); -my $issue = $query->param('issue'); +my $issue = $query->param('issue'); my $routingid; -my $op = $query->param('op') || q{}; +my $op = $query->param('op') || q{}; my $dbh = C4::Context->dbh; -if($op eq 'cud-delete'){ - delroutingmember($routingid,$subscriptionid); +if ( $op eq 'cud-delete' ) { + delroutingmember( $routingid, $subscriptionid ); my $sth = $dbh->prepare("UPDATE serial SET routingnotes = NULL WHERE subscriptionid = ?"); $sth->execute($subscriptionid); print $query->redirect("routing.pl?subscriptionid=$subscriptionid&op=new"); } -if($op eq 'cud-edit'){ +if ( $op eq 'cud-edit' ) { print $query->redirect("routing.pl?subscriptionid=$subscriptionid"); } my @routinglist = getroutinglist($subscriptionid); -my $subs = GetSubscription($subscriptionid); -my ($tmp ,@serials) = GetSerials($subscriptionid); -my ($template, $loggedinuser, $cookie); +my $subs = GetSubscription($subscriptionid); +my ( $tmp, @serials ) = GetSerials($subscriptionid); +my ( $template, $loggedinuser, $cookie ); my $library; -if($op eq 'cud-save_and_preview'){ +if ( $op eq 'cud-save_and_preview' ) { + # get biblio information.... my $biblionumber = $subs->{'bibnum'}; - my $biblio = Koha::Biblios->find( $biblionumber ); - my $items = $biblio->items->search_ordered; + my $biblio = Koha::Biblios->find($biblionumber); + my $items = $biblio->items->search_ordered; my $branch = - $items->count - ? $items->next->holding_branch->branchcode - : $subs->{branchcode}; + $items->count + ? $items->next->holding_branch->branchcode + : $subs->{branchcode}; $library = Koha::Libraries->find($branch); - if (C4::Context->preference('RoutingListAddReserves')){ + if ( C4::Context->preference('RoutingListAddReserves') ) { - my $notes; - my $title = $subs->{'bibliotitle'}; - for my $routing ( @routinglist ) { + my $notes; + my $title = $subs->{'bibliotitle'}; + for my $routing (@routinglist) { my $sth = $dbh->prepare('SELECT * FROM reserves WHERE biblionumber = ? AND borrowernumber = ? LIMIT 1'); - $sth->execute($biblionumber,$routing->{borrowernumber}); + $sth->execute( $biblionumber, $routing->{borrowernumber} ); my $reserve = $sth->fetchrow_hashref; - if($routing->{borrowernumber} == $reserve->{borrowernumber}){ - ModReserve({ - rank => $routing->{ranking}, - biblionumber => $biblionumber, - borrowernumber => $routing->{borrowernumber}, - branchcode => $branch - }); + if ( $routing->{borrowernumber} == $reserve->{borrowernumber} ) { + ModReserve( + { + rank => $routing->{ranking}, + biblionumber => $biblionumber, + borrowernumber => $routing->{borrowernumber}, + branchcode => $branch + } + ); } else { AddReserve( { @@ -95,10 +98,12 @@ if($op eq 'cud-save_and_preview'){ title => $title, } ); + } } } - } - print $query->redirect("/cgi-bin/koha/serials/subscription-detail.pl?subscriptionid=$subscriptionid&print_routing_list_issue=" . $query->param('issue_escaped')); + print $query->redirect( + "/cgi-bin/koha/serials/subscription-detail.pl?subscriptionid=$subscriptionid&print_routing_list_issue=" + . $query->param('issue_escaped') ); exit; } elsif ( $op eq 'print' ) { ( $template, $loggedinuser, $cookie ) = get_template_and_user( @@ -125,7 +130,7 @@ $template->param( libraryname => $library->branchname ) if $library; my $memberloop = []; for my $routing (@routinglist) { my $member = Koha::Patrons->find( $routing->{borrowernumber} )->unblessed; - $member->{name} = "$member->{firstname} $member->{surname}"; + $member->{name} = "$member->{firstname} $member->{surname}"; push @{$memberloop}, $member; } @@ -133,14 +138,14 @@ my $routingnotes = $serials[0]->{'routingnotes'}; $routingnotes =~ s/\n/\
            /g; $template->param( - title => $subs->{'bibliotitle'}, - issue => $issue, - issue_escaped => URI::Escape::uri_escape_utf8($issue), - subscriptionid => $subscriptionid, - memberloop => $memberloop, - routingnotes => $routingnotes, - hasRouting => check_routing($subscriptionid), - (uc(C4::Context->preference("marcflavour"))) => 1 - ); + title => $subs->{'bibliotitle'}, + issue => $issue, + issue_escaped => URI::Escape::uri_escape_utf8($issue), + subscriptionid => $subscriptionid, + memberloop => $memberloop, + routingnotes => $routingnotes, + hasRouting => check_routing($subscriptionid), + ( uc( C4::Context->preference("marcflavour") ) ) => 1 +); output_html_with_http_headers $query, $cookie, $template->output; diff --git a/serials/routing.pl b/serials/routing.pl index b8cd66e880..68abf057c4 100755 --- a/serials/routing.pl +++ b/serials/routing.pl @@ -15,7 +15,6 @@ # You should have received a copy of the GNU General Public License # along with Koha; if not, see . - =head1 Routing.pl script used to create a routing list for a serial subscription @@ -29,42 +28,43 @@ use Modern::Perl; use Try::Tiny; use CGI qw ( -utf8 ); use C4::Koha; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_and_exit output_html_with_http_headers ); use C4::Context; -use C4::Serials qw( GetSubscription delroutingmember addroutingmember getroutinglist GetSerials GetLatestSerials check_routing ); +use C4::Serials + qw( GetSubscription delroutingmember addroutingmember getroutinglist GetSerials GetLatestSerials check_routing ); use Koha::Patrons; use URI::Escape; -my $query = CGI->new; -my $subscriptionid = $query->param('subscriptionid'); -my $serialseq = $query->param('serialseq'); -my $routingid = $query->param('routingid'); +my $query = CGI->new; +my $subscriptionid = $query->param('subscriptionid'); +my $serialseq = $query->param('serialseq'); +my $routingid = $query->param('routingid'); my $borrowernumbers = $query->param('borrowernumbers'); -my $notes = $query->param('notes'); -my $op = $query->param('op') || q{}; -my $date_selected = $query->param('date_selected'); +my $notes = $query->param('notes'); +my $op = $query->param('op') || q{}; +my $date_selected = $query->param('date_selected'); $date_selected ||= q{}; my $dbh = C4::Context->dbh; my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => 'serials/routing.tt', - query => $query, - type => 'intranet', - flagsrequired => { serials => 'routing' }, + template_name => 'serials/routing.tt', + query => $query, + type => 'intranet', + flagsrequired => { serials => 'routing' }, } ); my $subs = GetSubscription($subscriptionid); -output_and_exit( $query, $cookie, $template, 'unknown_subscription') +output_and_exit( $query, $cookie, $template, 'unknown_subscription' ) unless $subs; -if($op eq 'cud-delete'){ - delroutingmember($routingid,$subscriptionid); +if ( $op eq 'cud-delete' ) { + delroutingmember( $routingid, $subscriptionid ); } if ( $op eq 'cud-add_new_recipients' ) { @@ -78,25 +78,25 @@ if ( $op eq 'cud-add_new_recipients' ) { }; } } -if($op eq 'cud-save'){ +if ( $op eq 'cud-save' ) { my $sth = $dbh->prepare('UPDATE serial SET routingnotes = ? WHERE subscriptionid = ?'); - $sth->execute($notes,$subscriptionid); + $sth->execute( $notes, $subscriptionid ); my $urldate = URI::Escape::uri_escape_utf8($date_selected); print $query->redirect("routing-preview.pl?subscriptionid=$subscriptionid&issue=$urldate"); } my @routinglist = getroutinglist($subscriptionid); -my ($count,@serials) = GetSerials($subscriptionid); -my $serialdates = GetLatestSerials($subscriptionid,$count); +my ( $count, @serials ) = GetSerials($subscriptionid); +my $serialdates = GetLatestSerials( $subscriptionid, $count ); my $dates = []; -foreach my $dateseq (@{$serialdates}) { +foreach my $dateseq ( @{$serialdates} ) { my $d = {}; $d->{publisheddate} = $dateseq->{publisheddate}; - $d->{serialseq} = $dateseq->{serialseq}; - $d->{serialid} = $dateseq->{serialid}; - if($date_selected eq $dateseq->{serialid}){ + $d->{serialseq} = $dateseq->{serialseq}; + $d->{serialid} = $dateseq->{serialid}; + if ( $date_selected eq $dateseq->{serialid} ) { $d->{selected} = ' selected'; } else { $d->{selected} = q{}; @@ -105,34 +105,33 @@ foreach my $dateseq (@{$serialdates}) { } my $member_loop = []; -for my $routing ( @routinglist ) { +for my $routing (@routinglist) { my $member = Koha::Patrons->find( $routing->{borrowernumber} )->unblessed; $member->{location} = $member->{branchcode}; - if ($member->{firstname} ) { + if ( $member->{firstname} ) { $member->{name} = $member->{firstname} . q| |; - } - else { + } else { $member->{name} = q{}; } - if ($member->{surname} ) { + if ( $member->{surname} ) { $member->{name} .= $member->{surname}; } - $member->{routingid}=$routing->{routingid} || q{}; - $member->{ranking} = $routing->{ranking} || q{}; + $member->{routingid} = $routing->{routingid} || q{}; + $member->{ranking} = $routing->{ranking} || q{}; - push(@{$member_loop}, $member); + push( @{$member_loop}, $member ); } $template->param( - title => $subs->{bibliotitle}, - subscriptionid => $subscriptionid, - memberloop => $member_loop, - op => $op eq 'new', - dates => $dates, - routingnotes => $serials[0]->{'routingnotes'}, - hasRouting => check_routing($subscriptionid), - (uc(C4::Context->preference("marcflavour"))) => 1 + title => $subs->{bibliotitle}, + subscriptionid => $subscriptionid, + memberloop => $member_loop, + op => $op eq 'new', + dates => $dates, + routingnotes => $serials[0]->{'routingnotes'}, + hasRouting => check_routing($subscriptionid), + ( uc( C4::Context->preference("marcflavour") ) ) => 1 - ); +); output_html_with_http_headers $query, $cookie, $template->output; diff --git a/serials/serials-collection.pl b/serials/serials-collection.pl index c6651ecef1..68baa5ed01 100755 --- a/serials/serials-collection.pl +++ b/serials/serials-collection.pl @@ -18,11 +18,11 @@ # You should have received a copy of the GNU General Public License # along with Koha; if not, see . - use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Auth qw( get_template_and_user ); -use C4::Serials qw( ModSerialStatus GetSubscription GetNextExpected GetNextSeq GetNextDate NewIssue HasSubscriptionExpired abouttoexpire check_routing GetFullSubscription PrepareSerialsData CountSubscriptionFromBiblionumber GetSubscriptionsFromBiblionumber GetFullSubscriptionsFromBiblionumber ); +use C4::Serials + qw( ModSerialStatus GetSubscription GetNextExpected GetNextSeq GetNextDate NewIssue HasSubscriptionExpired abouttoexpire check_routing GetFullSubscription PrepareSerialsData CountSubscriptionFromBiblionumber GetSubscriptionsFromBiblionumber GetFullSubscriptionsFromBiblionumber ); use C4::Output qw( output_and_exit output_html_with_http_headers ); use C4::Context; use Koha::Serial::Items; @@ -31,187 +31,200 @@ use Koha::DateUtils qw( dt_from_string ); use List::MoreUtils qw( uniq ); - -my $query = CGI->new; -my $op = $query->param('op') || q{}; -my $nbissues=$query->param('nbissues'); +my $query = CGI->new; +my $op = $query->param('op') || q{}; +my $nbissues = $query->param('nbissues'); my $date_received_today = $query->param('date_received_today') || 0; -my $dbh = C4::Context->dbh; +my $dbh = C4::Context->dbh; -my ($template, $loggedinuser, $cookie) - = get_template_and_user({template_name => "serials/serials-collection.tt", - query => $query, - type => "intranet", - flagsrequired => {serials => '*'}, - }); -my $biblionumber = $query->param('biblionumber'); +my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "serials/serials-collection.tt", + query => $query, + type => "intranet", + flagsrequired => { serials => '*' }, + } +); +my $biblionumber = $query->param('biblionumber'); my @subscriptionid = $query->multi_param('subscriptionid'); -my $skip_issues = $query->param('skip_issues') || 0; -my $count_forward = $skip_issues + 1; +my $skip_issues = $query->param('skip_issues') || 0; +my $count_forward = $skip_issues + 1; -@subscriptionid= uniq @subscriptionid; -@subscriptionid= sort @subscriptionid; +@subscriptionid = uniq @subscriptionid; +@subscriptionid = sort @subscriptionid; my $subscriptiondescs; my $subscriptions; -if($op eq 'cud-gennext' && @subscriptionid){ +if ( $op eq 'cud-gennext' && @subscriptionid ) { my $subscriptionid = $subscriptionid[0]; - my $sth = $dbh->prepare(" + my $sth = $dbh->prepare( " SELECT publisheddate, publisheddatetext, serialid, serialseq, planneddate, notes, routingnotes FROM serial WHERE status = 1 AND subscriptionid = ? - "); - my $status = defined( $nbissues ) ? 2 : 3; + " ); + my $status = defined($nbissues) ? 2 : 3; $nbissues ||= 1; - for ( my $i = 0; $i < $nbissues; $i++ ){ + for ( my $i = 0 ; $i < $nbissues ; $i++ ) { $sth->execute($subscriptionid); + # modify actual expected issue, to generate the next if ( my $issue = $sth->fetchrow_hashref ) { my $planneddate = $date_received_today ? dt_from_string : $issue->{planneddate}; - ModSerialStatus( $issue->{serialid}, $issue->{serialseq}, - $planneddate, $issue->{publisheddate}, - $issue->{publisheddatetext}, $status, $issue->{notes}, $count_forward ); + ModSerialStatus( + $issue->{serialid}, $issue->{serialseq}, + $planneddate, $issue->{publisheddate}, + $issue->{publisheddatetext}, $status, $issue->{notes}, $count_forward + ); } else { require C4::Serials::Numberpattern; my $subscription = GetSubscription($subscriptionid); - my $pattern = C4::Serials::Numberpattern::GetSubscriptionNumberpattern($subscription->{numberpattern}); - my $frequency = C4::Serials::Frequency::GetSubscriptionFrequency($subscription->{periodicity}); - my $expected = GetNextExpected($subscriptionid); + my $pattern = C4::Serials::Numberpattern::GetSubscriptionNumberpattern( $subscription->{numberpattern} ); + my $frequency = C4::Serials::Frequency::GetSubscriptionFrequency( $subscription->{periodicity} ); + my $expected = GetNextExpected($subscriptionid); my ( - $newserialseq, $newlastvalue1, $newlastvalue2, $newlastvalue3, - $newinnerloop1, $newinnerloop2, $newinnerloop3 - ) = GetNextSeq($subscription, $pattern, $frequency, $expected->{publisheddate}, $count_forward); + $newserialseq, $newlastvalue1, $newlastvalue2, $newlastvalue3, + $newinnerloop1, $newinnerloop2, $newinnerloop3 + ) = GetNextSeq( $subscription, $pattern, $frequency, $expected->{publisheddate}, $count_forward ); - ## We generate the next publication date - my $nextpublisheddate = GetNextDate($subscription, $expected->{publisheddate}, $frequency, 1); - my $planneddate = $date_received_today ? dt_from_string : $nextpublisheddate; - ## Creating the new issue - NewIssue( $newserialseq, $subscriptionid, $subscription->{'biblionumber'}, - 1, $planneddate, $nextpublisheddate, undef, - $issue->{notes}, $issue->{routingnotes} ); + ## We generate the next publication date + my $nextpublisheddate = GetNextDate( $subscription, $expected->{publisheddate}, $frequency, 1 ); + my $planneddate = $date_received_today ? dt_from_string : $nextpublisheddate; + ## Creating the new issue + NewIssue( + $newserialseq, $subscriptionid, $subscription->{'biblionumber'}, + 1, $planneddate, $nextpublisheddate, undef, + $issue->{notes}, $issue->{routingnotes} + ); - ## Updating the subscription seq status - my $squery = "UPDATE subscription SET lastvalue1=?, lastvalue2=?, lastvalue3=?, innerloop1=?, innerloop2=?, innerloop3=? + ## Updating the subscription seq status + my $squery = + "UPDATE subscription SET lastvalue1=?, lastvalue2=?, lastvalue3=?, innerloop1=?, innerloop2=?, innerloop3=? WHERE subscriptionid = ?"; - my $seqsth = $dbh->prepare($squery); - $seqsth->execute( - $newlastvalue1, $newlastvalue2, $newlastvalue3, $newinnerloop1, - $newinnerloop2, $newinnerloop3, $subscriptionid - ); + my $seqsth = $dbh->prepare($squery); + $seqsth->execute( + $newlastvalue1, $newlastvalue2, $newlastvalue3, $newinnerloop1, + $newinnerloop2, $newinnerloop3, $subscriptionid + ); } last if $nbissues == 1; last if HasSubscriptionExpired($subscriptionid) > 0; } - print $query->redirect('/cgi-bin/koha/serials/serials-collection.pl?subscriptionid='.$subscriptionid); + print $query->redirect( '/cgi-bin/koha/serials/serials-collection.pl?subscriptionid=' . $subscriptionid ); exit; } -my $countitems = 0; -my @serialsid = $query->multi_param('serialid'); +my $countitems = 0; +my @serialsid = $query->multi_param('serialid'); my $subscriptionid = $subscriptionid[0]; -if($op eq 'delete_confirm'){ - foreach my $serialid (@serialsid){ - $countitems += Koha::Serial::Items->search({serialid => $serialid})->count(); +if ( $op eq 'delete_confirm' ) { + foreach my $serialid (@serialsid) { + $countitems += Koha::Serial::Items->search( { serialid => $serialid } )->count(); } -}elsif($op eq 'cud-delete_confirmed'){ - if($query->param('delitems') eq "Yes"){ +} elsif ( $op eq 'cud-delete_confirmed' ) { + if ( $query->param('delitems') eq "Yes" ) { my @itemnumbers; - foreach my $serialid (@serialsid){ - my @ids = Koha::Serial::Items->search({serialid => $serialid})->get_column('itemnumber'); - push(@itemnumbers, @ids); + foreach my $serialid (@serialsid) { + my @ids = Koha::Serial::Items->search( { serialid => $serialid } )->get_column('itemnumber'); + push( @itemnumbers, @ids ); } - my $items = Koha::Items->search({ itemnumber => \@itemnumbers }); + my $items = Koha::Items->search( { itemnumber => \@itemnumbers } ); while ( my $item = $items->next ) { my $deleted = $item->safe_delete; - $template->param(error_delitem => 1) + $template->param( error_delitem => 1 ) unless $deleted; } } - for my $serialid (@serialsid){ + for my $serialid (@serialsid) { my $serial = Koha::Serials->find($serialid); - ModSerialStatus($serialid, $serial->serialseq, $serial->planneddate, $serial->publisheddate, $serial->publisheddatetext, 6, ""); + ModSerialStatus( + $serialid, $serial->serialseq, $serial->planneddate, $serial->publisheddate, + $serial->publisheddatetext, 6, "" + ); } } my $subscriptioncount; -my ($location, $callnumber); -if (@subscriptionid){ - my @subscriptioninformation=(); - my $closed = 0; - foreach my $subscriptionid (@subscriptionid){ - my $subs= GetSubscription($subscriptionid); - next unless $subs; - $closed = 1 if $subs->{closed}; +my ( $location, $callnumber ); +if (@subscriptionid) { + my @subscriptioninformation = (); + my $closed = 0; + foreach my $subscriptionid (@subscriptionid) { + my $subs = GetSubscription($subscriptionid); + next unless $subs; + $closed = 1 if $subs->{closed}; - ##these are display information - $subs->{'abouttoexpire'}=abouttoexpire($subs->{'subscriptionid'}); - $subs->{'subscriptionexpired'}=HasSubscriptionExpired($subs->{'subscriptionid'}); - $subs->{'subscriptionid'} = $subscriptionid; # FIXME - why was this lost ? - $location = $subs->{'location'}; - $callnumber = $subs->{callnumber}; - my $frequency = C4::Serials::Frequency::GetSubscriptionFrequency($subs->{periodicity}); - my $numberpattern = C4::Serials::Numberpattern::GetSubscriptionNumberpattern($subs->{numberpattern}); - $subs->{frequency} = $frequency; - $subs->{numberpattern} = $numberpattern; - $subs->{'hasRouting'} = check_routing($subscriptionid); - push @$subscriptiondescs,$subs; - my $tmpsubscription= GetFullSubscription($subscriptionid); - @subscriptioninformation=(@$tmpsubscription,@subscriptioninformation); - } + ##these are display information + $subs->{'abouttoexpire'} = abouttoexpire( $subs->{'subscriptionid'} ); + $subs->{'subscriptionexpired'} = HasSubscriptionExpired( $subs->{'subscriptionid'} ); + $subs->{'subscriptionid'} = $subscriptionid; # FIXME - why was this lost ? + $location = $subs->{'location'}; + $callnumber = $subs->{callnumber}; + my $frequency = C4::Serials::Frequency::GetSubscriptionFrequency( $subs->{periodicity} ); + my $numberpattern = C4::Serials::Numberpattern::GetSubscriptionNumberpattern( $subs->{numberpattern} ); + $subs->{frequency} = $frequency; + $subs->{numberpattern} = $numberpattern; + $subs->{'hasRouting'} = check_routing($subscriptionid); + push @$subscriptiondescs, $subs; + my $tmpsubscription = GetFullSubscription($subscriptionid); + @subscriptioninformation = ( @$tmpsubscription, @subscriptioninformation ); + } - output_and_exit( $query, $cookie, $template, 'unknown_subscription') unless @subscriptioninformation; + output_and_exit( $query, $cookie, $template, 'unknown_subscription' ) unless @subscriptioninformation; - $template->param(closed => $closed); - $subscriptions=PrepareSerialsData(\@subscriptioninformation); - $subscriptioncount = CountSubscriptionFromBiblionumber($subscriptiondescs->[0]{'biblionumber'}); + $template->param( closed => $closed ); + $subscriptions = PrepareSerialsData( \@subscriptioninformation ); + $subscriptioncount = CountSubscriptionFromBiblionumber( $subscriptiondescs->[0]{'biblionumber'} ); } else { - $subscriptiondescs = GetSubscriptionsFromBiblionumber($biblionumber); - foreach my $s (@$subscriptiondescs) { - my $frequency = C4::Serials::Frequency::GetSubscriptionFrequency($s->{periodicity}); - my $numberpattern = C4::Serials::Numberpattern::GetSubscriptionNumberpattern($s->{numberpattern}); - $s->{frequency} = $frequency; - $s->{numberpattern} = $numberpattern; - } - my $subscriptioninformation = GetFullSubscriptionsFromBiblionumber($biblionumber); - $subscriptions=PrepareSerialsData($subscriptioninformation); + $subscriptiondescs = GetSubscriptionsFromBiblionumber($biblionumber); + foreach my $s (@$subscriptiondescs) { + my $frequency = C4::Serials::Frequency::GetSubscriptionFrequency( $s->{periodicity} ); + my $numberpattern = C4::Serials::Numberpattern::GetSubscriptionNumberpattern( $s->{numberpattern} ); + $s->{frequency} = $frequency; + $s->{numberpattern} = $numberpattern; + } + my $subscriptioninformation = GetFullSubscriptionsFromBiblionumber($biblionumber); + $subscriptions = PrepareSerialsData($subscriptioninformation); } my $title = $subscriptiondescs->[0]{bibliotitle}; -my $yearmax=($subscriptions->[0]{year} eq "manage" && scalar(@$subscriptions)>1)? $subscriptions->[1]{year} :$subscriptions->[0]{year}; -my $yearmin=$subscriptions->[scalar(@$subscriptions)-1]{year}; -my $subscriptionidlist=""; -foreach my $subscription (@$subscriptiondescs){ - $subscriptionidlist.=$subscription->{'subscriptionid'}."," ; - $biblionumber = $subscription->{'bibnum'} unless ($biblionumber); - $subscription->{'hasRouting'} = check_routing($subscription->{'subscriptionid'}); +my $yearmax = + ( $subscriptions->[0]{year} eq "manage" && scalar(@$subscriptions) > 1 ) + ? $subscriptions->[1]{year} + : $subscriptions->[0]{year}; +my $yearmin = $subscriptions->[ scalar(@$subscriptions) - 1 ]{year}; +my $subscriptionidlist = ""; +foreach my $subscription (@$subscriptiondescs) { + $subscriptionidlist .= $subscription->{'subscriptionid'} . ","; + $biblionumber = $subscription->{'bibnum'} unless ($biblionumber); + $subscription->{'hasRouting'} = check_routing( $subscription->{'subscriptionid'} ); } chop $subscriptionidlist; $template->param( - subscriptionidlist => $subscriptionidlist, - biblionumber => $biblionumber, - subscriptions => $subscriptiondescs, - years => $subscriptions, - yearmin => $yearmin, - yearmax =>$yearmax, - bibliotitle => $title, - suggestion => C4::Context->preference("suggestion"), - virtualshelves => C4::Context->preference("virtualshelves"), - routing => C4::Context->preference("RoutingSerials"), - subscr=>scalar $query->param('subscriptionid'), - subscriptioncount => $subscriptioncount, - location => $location, - callnumber => $callnumber, - uc(C4::Context->preference("marcflavour")) => 1, - serialsadditems => $subscriptiondescs->[0]{'serialsadditems'}, - delete => ($op eq 'delete_confirm'), - subscriptionid => $subscriptionid, - countitems => $countitems, - serialnumber => scalar @serialsid, - serialsid => \@serialsid, - ); + subscriptionidlist => $subscriptionidlist, + biblionumber => $biblionumber, + subscriptions => $subscriptiondescs, + years => $subscriptions, + yearmin => $yearmin, + yearmax => $yearmax, + bibliotitle => $title, + suggestion => C4::Context->preference("suggestion"), + virtualshelves => C4::Context->preference("virtualshelves"), + routing => C4::Context->preference("RoutingSerials"), + subscr => scalar $query->param('subscriptionid'), + subscriptioncount => $subscriptioncount, + location => $location, + callnumber => $callnumber, + uc( C4::Context->preference("marcflavour") ) => 1, + serialsadditems => $subscriptiondescs->[0]{'serialsadditems'}, + delete => ( $op eq 'delete_confirm' ), + subscriptionid => $subscriptionid, + countitems => $countitems, + serialnumber => scalar @serialsid, + serialsid => \@serialsid, +); output_html_with_http_headers $query, $cookie, $template->output; diff --git a/serials/serials-edit.pl b/serials/serials-edit.pl index ef30c4eae8..a189ba0b29 100755 --- a/serials/serials-edit.pl +++ b/serials/serials-edit.pl @@ -64,12 +64,13 @@ op can be : use Modern::Perl; use CGI qw ( -utf8 ); use Encode; -use C4::Auth qw( get_template_and_user haspermission ); +use C4::Auth qw( get_template_and_user haspermission ); use C4::Biblio qw( GetMarcFromKohaField TransformHtmlToXml ); -use C4::Items qw( AddItemFromMarc ModItemFromMarc PrepareItemrecordDisplay ); +use C4::Items qw( AddItemFromMarc ModItemFromMarc PrepareItemrecordDisplay ); use C4::Output qw( output_html_with_http_headers ); use C4::Context; -use C4::Serials qw( GetSerials GetSerials2 GetSerialInformation HasSubscriptionExpired GetSubscription abouttoexpire NewIssue ModSerialStatus GetPreviousSerialid AddItem2Serial ); +use C4::Serials + qw( GetSerials GetSerials2 GetSerialInformation HasSubscriptionExpired GetSubscription abouttoexpire NewIssue ModSerialStatus GetPreviousSerialid AddItem2Serial ); use C4::Search qw( enabled_staff_search_views ); use Koha::DateUtils qw( dt_from_string ); @@ -77,20 +78,20 @@ use Koha::Items; use Koha::Serial::Items; use List::MoreUtils qw( uniq ); -use List::Util qw( min ); +use List::Util qw( min ); -my $query = CGI->new(); -my $dbh = C4::Context->dbh; -my @serialids = $query->multi_param('serialid'); -my @serialseqs = $query->multi_param('serialseq'); -my @planneddates = $query->multi_param('planneddate'); -my @publisheddates = $query->multi_param('publisheddate'); +my $query = CGI->new(); +my $dbh = C4::Context->dbh; +my @serialids = $query->multi_param('serialid'); +my @serialseqs = $query->multi_param('serialseq'); +my @planneddates = $query->multi_param('planneddate'); +my @publisheddates = $query->multi_param('publisheddate'); my @publisheddatetexts = $query->multi_param('publisheddatetext'); -my @status = $query->multi_param('status'); -my @notes = $query->multi_param('notes'); -my @subscriptionids = $query->multi_param('subscriptionid'); -my $op = $query->param('op'); -my $skip_issues = $query->param('skip_issues') || 0; +my @status = $query->multi_param('status'); +my @notes = $query->multi_param('notes'); +my @subscriptionids = $query->multi_param('subscriptionid'); +my $op = $query->param('op'); +my $skip_issues = $query->param('skip_issues') || 0; my $count_forward = $skip_issues + 1; @@ -103,7 +104,7 @@ my @errseq; # If user comes from subscription details unless (@serialids) { my $serstatus = $query->param('serstatus'); - my @statuses = split ',', $serstatus; + my @statuses = split ',', $serstatus; if ($serstatus) { foreach my $subscriptionid (@subscriptionids) { my @tmpser = GetSerials2( $subscriptionid, \@statuses ); @@ -112,9 +113,8 @@ unless (@serialids) { } } -unless ( @serialids ) { - my $string = - 'serials-collection.pl?subscriptionid=' . join ',', uniq @subscriptionids; +unless (@serialids) { + my $string = 'serials-collection.pl?subscriptionid=' . join ',', uniq @subscriptionids; $string =~ s/,$//; print $query->redirect($string); @@ -123,10 +123,10 @@ unless ( @serialids ) { my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => 'serials/serials-edit.tt', - query => $query, - type => 'intranet', - flagsrequired => { serials => 'receive_serials' }, + template_name => 'serials/serials-edit.tt', + query => $query, + type => 'intranet', + flagsrequired => { serials => 'receive_serials' }, } ); @@ -143,19 +143,15 @@ foreach my $serialid (@serialids) { && $serialid =~ /^[0-9]+$/ && !$processedserialid{$serialid} ) { - my $serinfo = GetSerialInformation($serialid); #TODO duplicates work done by GetSerials2 above + my $serinfo = GetSerialInformation($serialid); #TODO duplicates work done by GetSerials2 above $serinfo->{arriveddate} = $today; - $serinfo->{'editdisable'} = ( - ( - HasSubscriptionExpired( $serinfo->{subscriptionid} ) - && $serinfo->{'status1'} - ) - || $serinfo->{'cannotedit'} - ); - $serinfo->{editdisable} = 0 if C4::Auth::haspermission( C4::Context->userenv->{id}, { serials => 'receive_serials' } ); - $serinfo->{editdisable} ||= ($serinfo->{status8} and $serinfo->{closed}); + $serinfo->{'editdisable'} = ( ( HasSubscriptionExpired( $serinfo->{subscriptionid} ) && $serinfo->{'status1'} ) + || $serinfo->{'cannotedit'} ); + $serinfo->{editdisable} = 0 + if C4::Auth::haspermission( C4::Context->userenv->{id}, { serials => 'receive_serials' } ); + $serinfo->{editdisable} ||= ( $serinfo->{status8} and $serinfo->{closed} ); push @serialdatalist, $serinfo; $processedserialid{$serialid} = 1; } @@ -170,19 +166,19 @@ my %processedsubscriptionid; foreach my $subscriptionid (@subscriptionids) { #Do not process subscriptionid twice if it was already processed. - if ( $subscriptionid && !$processedsubscriptionid{$subscriptionid} ) - { + if ( $subscriptionid && !$processedsubscriptionid{$subscriptionid} ) { my $cell; if ( $serialdatalist[0]->{'serialsadditems'} ) { #Create New empty item - $cell = - PrepareItemrecordDisplay( $serialdatalist[0]->{'biblionumber'}, - '', GetSubscription($subscriptionid) ); + $cell = PrepareItemrecordDisplay( + $serialdatalist[0]->{'biblionumber'}, + '', GetSubscription($subscriptionid) + ); $cell->{serialsadditems} = 1; } $cell->{'subscriptionid'} = $subscriptionid; - $cell->{biblionumber} = $serialdatalist[0]->{'biblionumber'}; + $cell->{biblionumber} = $serialdatalist[0]->{'biblionumber'}; $cell->{'itemid'} = 'NNEW'; $cell->{'serialid'} = 'NEW'; $cell->{'issuesatonce'} = 1; @@ -190,11 +186,11 @@ foreach my $subscriptionid (@subscriptionids) { push @newserialloop, $cell; push @subscriptionloop, - { + { 'subscriptionid' => $subscriptionid, 'abouttoexpire' => abouttoexpire($subscriptionid), 'subscriptionexpired' => HasSubscriptionExpired($subscriptionid), - }; + }; $processedsubscriptionid{$subscriptionid} = 1; } } @@ -205,24 +201,24 @@ if ( $op and $op eq 'cud-serialchangestatus' ) { # Convert serialseqs to UTF-8 to prevent encoding problems foreach my $seq (@serialseqs) { - $seq = Encode::decode('UTF-8', $seq) unless Encode::is_utf8($seq); + $seq = Encode::decode( 'UTF-8', $seq ) unless Encode::is_utf8($seq); } my $newserial; for ( my $i = 0 ; $i <= $#serialids ; $i++ ) { - my ($plan_date, $pub_date); + my ( $plan_date, $pub_date ); - if (defined $planneddates[$i] && $planneddates[$i] ne 'XXX') { + if ( defined $planneddates[$i] && $planneddates[$i] ne 'XXX' ) { $plan_date = $planneddates[$i]; } - if (defined $publisheddates[$i] && $publisheddates[$i] ne 'XXX') { + if ( defined $publisheddates[$i] && $publisheddates[$i] ne 'XXX' ) { $pub_date = $publisheddates[$i]; } if ( $serialids[$i] && $serialids[$i] eq 'NEW' ) { if ( $serialseqs[$i] ) { - #IF newserial was provided a name Then we have to create a newSerial + #IF newserial was provided a name Then we have to create a newSerial ### FIXME if NewIssue is modified to use subscription biblionumber, then biblionumber would not be useful. $newserial = NewIssue( $serialseqs[$i], @@ -236,8 +232,7 @@ if ( $op and $op eq 'cud-serialchangestatus' ) { $serialdatalist[0]->{'routingnotes'} ); } - } - elsif ( $serialids[$i] ) { + } elsif ( $serialids[$i] ) { ModSerialStatus( $serialids[$i], $serialseqs[$i], @@ -250,24 +245,25 @@ if ( $op and $op eq 'cud-serialchangestatus' ) { ); } my $makePreviousSerialAvailable = C4::Context->preference('makePreviousSerialAvailable'); - if ($makePreviousSerialAvailable && $serialids[$i] ne "NEW") { + if ( $makePreviousSerialAvailable && $serialids[$i] ne "NEW" ) { + # We already have created the new expected serial at this point, so we get the second previous serial - my $previous = GetPreviousSerialid($subscriptionids[$i]); + my $previous = GetPreviousSerialid( $subscriptionids[$i] ); if ($previous) { - my $serialitem = Koha::Serial::Items->search( {serialid => $previous} )->next; + my $serialitem = Koha::Serial::Items->search( { serialid => $previous } )->next; my $itemnumber = $serialitem ? $serialitem->itemnumber : undef; if ($itemnumber) { # Getting the itemtype to set from the database - my $subscriptioninfos = GetSubscription($subscriptionids[$i]); + my $subscriptioninfos = GetSubscription( $subscriptionids[$i] ); # Changing the status to "available" and the itemtype according to the previousitemtype db field my $item = Koha::Items->find($itemnumber); $item->set( { notforloan => 0, - itype => $subscriptioninfos->{'previousitemtype'} + itype => $subscriptioninfos->{'previousitemtype'} } )->store; } @@ -283,45 +279,45 @@ if ( $op and $op eq 'cud-serialchangestatus' ) { my @serials = $query->multi_param('serial'); my @bibnums = $query->multi_param('bibnum'); my @itemid = $query->multi_param('itemid'); - my @num_copies = map { min($_, 1000); } $query->multi_param('number_of_copies'); + my @num_copies = map { min( $_, 1000 ); } $query->multi_param('number_of_copies'); #Rebuilding ALL the data for items into a hash # parting them on $itemid. my %itemhash; my $countdistinct = 0; - my $range = scalar(@itemid); + my $range = scalar(@itemid); for ( my $i = 0 ; $i < $range ; $i++ ) { unless ( $itemhash{ $itemid[$i] } ) { if ( $serials[$countdistinct] && $serials[$countdistinct] ne "NEW" ) { $itemhash{ $itemid[$i] }->{'serial'} = - $serials[$countdistinct]; - } - else { + $serials[$countdistinct]; + } else { $itemhash{ $itemid[$i] }->{'serial'} = $newserial; } - $itemhash{ $itemid[$i] }->{'bibnum'} = $bibnums[$countdistinct]; + $itemhash{ $itemid[$i] }->{'bibnum'} = $bibnums[$countdistinct]; $itemhash{ $itemid[$i] }->{'num_copies'} = $num_copies[$countdistinct]; $countdistinct++; } push @{ $itemhash{ $itemid[$i] }->{'tags'} }, $tags[$i]; push @{ $itemhash{ $itemid[$i] }->{'subfields'} }, $subfields[$i]; push @{ $itemhash{ $itemid[$i] }->{'field_values'} }, - $field_values[$i]; + $field_values[$i]; } foreach my $item ( keys %itemhash ) { - # Verify Itemization is "Valid", i.e. serial status is Arrived or Missing + # Verify Itemization is "Valid", i.e. serial status is Arrived or Missing my $index = -1; for ( my $i = 0 ; $i < scalar(@serialids) ; $i++ ) { - if ( + if ( $itemhash{$item}->{serial} eq $serialids[$i] || ( $itemhash{$item}->{serial} == $newserial && $serialids[$i] eq 'NEW' ) - ) { - $index = $i - } + ) + { + $index = $i; + } } if ( $index >= 0 && $status[$index] == 2 ) { my $xml = TransformHtmlToXml( @@ -336,87 +332,85 @@ if ( $op and $op eq 'cud-serialchangestatus' ) { my $bib_record = MARC::Record::new_from_xml( $xml, 'UTF-8' ); if ( $item =~ /^N/ ) { - $itemhash{$item}->{'num_copies'} //= 1; + $itemhash{$item}->{'num_copies'} //= 1; - for (my $copy = 0; $copy < $itemhash{$item}->{'num_copies'};){ + for ( my $copy = 0 ; $copy < $itemhash{$item}->{'num_copies'} ; ) { - # New Item + # New Item - # if autoBarcode is set to 'incremental', calculate barcode... - my ( $barcodetagfield, $barcodetagsubfield ) = GetMarcFromKohaField( 'items.barcode' ); - if ( C4::Context->preference('autoBarcode') eq - 'incremental' ) - { - if ( - !( - $bib_record->field($barcodetagfield) - && $bib_record->field($barcodetagfield)->subfield($barcodetagsubfield) - ) - ) - { - my $sth_barcode = $dbh->prepare( - 'select max(abs(barcode)) from items'); - $sth_barcode->execute; - my ($newbarcode) = $sth_barcode->fetchrow; + # if autoBarcode is set to 'incremental', calculate barcode... + my ( $barcodetagfield, $barcodetagsubfield ) = GetMarcFromKohaField('items.barcode'); + if ( C4::Context->preference('autoBarcode') eq 'incremental' ) { + if ( + !( + $bib_record->field($barcodetagfield) + && $bib_record->field($barcodetagfield)->subfield($barcodetagsubfield) + ) + ) + { + my $sth_barcode = $dbh->prepare('select max(abs(barcode)) from items'); + $sth_barcode->execute; + my ($newbarcode) = $sth_barcode->fetchrow; - # OK, we have the new barcode, add the entry in MARC record # FIXME -> should be using barcode plugin here. - $bib_record->field($barcodetagfield)->update( $barcodetagsubfield => ++$newbarcode ); - } - } - - # check for item barcode # being unique - my $exists; - if ( $bib_record->subfield( $barcodetagfield, $barcodetagsubfield ) ) { - my $barcode = $bib_record->subfield( $barcodetagfield, $barcodetagsubfield ); - - if ($copy > 0){ - use C4::Barcodes; - my $barcodeobj = C4::Barcodes->new; - my $newbarcode = $barcodeobj->next_value($barcode); - $barcode = $newbarcode; - $bib_record->field($barcodetagfield)->update($barcodetagsubfield => $barcode); + # OK, we have the new barcode, add the entry in MARC record # FIXME -> should be using barcode plugin here. + $bib_record->field($barcodetagfield)->update( $barcodetagsubfield => ++$newbarcode ); + } } - $exists = Koha::Items->find({barcode => $barcode}); + # check for item barcode # being unique + my $exists; + if ( $bib_record->subfield( $barcodetagfield, $barcodetagsubfield ) ) { + my $barcode = $bib_record->subfield( $barcodetagfield, $barcodetagsubfield ); + + if ( $copy > 0 ) { + use C4::Barcodes; + my $barcodeobj = C4::Barcodes->new; + my $newbarcode = $barcodeobj->next_value($barcode); + $barcode = $newbarcode; + $bib_record->field($barcodetagfield)->update( $barcodetagsubfield => $barcode ); + } + + $exists = Koha::Items->find( { barcode => $barcode } ); + } + + # push @errors,"barcode_not_unique" if($exists); + # if barcode exists, don't create, but report The problem. + if ($exists) { + push @errors, 'barcode_not_unique'; + push @errseq, { serialseq => $serialseqs[$index] }; + } else { + my ( $biblionumber, $bibitemnum, $itemnumber ) = AddItemFromMarc( + $bib_record, + $itemhash{$item}->{bibnum} + ); + AddItem2Serial( + $itemhash{$item}->{serial}, + $itemnumber + ); + } + $copy++; } - # push @errors,"barcode_not_unique" if($exists); - # if barcode exists, don't create, but report The problem. - if ($exists) { - push @errors, 'barcode_not_unique'; - push @errseq, { serialseq => $serialseqs[$index] }; - } - else { - my ( $biblionumber, $bibitemnum, $itemnumber ) = - AddItemFromMarc( $bib_record, - $itemhash{$item}->{bibnum} ); - AddItem2Serial( $itemhash{$item}->{serial}, - $itemnumber ); - } - $copy++; - } - - } # if ( $item =~ /^N/ ) { + } # if ( $item =~ /^N/ ) { else { #modify item - my ( $oldbiblionumber, $oldbibnum, $itemnumber ) = - ModItemFromMarc( $bib_record, - $itemhash{$item}->{'bibnum'}, $item ); + my ( $oldbiblionumber, $oldbibnum, $itemnumber ) = ModItemFromMarc( + $bib_record, + $itemhash{$item}->{'bibnum'}, $item + ); } } } } - - if ( @errors ) { + if (@errors) { $template->param( Errors => 1 ); - if ( @errseq ) { + if (@errseq) { $template->param( barcode_not_unique => 1, errseq => \@errseq ); } - } - else { + } else { my $redirect = 'serials-collection.pl?'; $redirect .= join( '&', map { 'subscriptionid=' . $_ } @subscriptionids ); print $query->redirect($redirect); @@ -425,15 +419,15 @@ if ( $op and $op eq 'cud-serialchangestatus' ) { my $location = $serialdatalist[0]->{'location'}; $template->param( - subscriptionid => $serialdatalist[0]->{subscriptionid}, - serialsadditems => $serialdatalist[0]->{'serialsadditems'}, - callnumber => $serialdatalist[0]->{'callnumber'}, - internalnotes => $serialdatalist[0]->{'internalnotes'}, - bibliotitle => $biblio->title, - biblionumber => $serialdatalist[0]->{'biblionumber'}, - serialslist => \@serialdatalist, - location => $location, - (uc(C4::Context->preference("marcflavour"))) => 1 + subscriptionid => $serialdatalist[0]->{subscriptionid}, + serialsadditems => $serialdatalist[0]->{'serialsadditems'}, + callnumber => $serialdatalist[0]->{'callnumber'}, + internalnotes => $serialdatalist[0]->{'internalnotes'}, + bibliotitle => $biblio->title, + biblionumber => $serialdatalist[0]->{'biblionumber'}, + serialslist => \@serialdatalist, + location => $location, + ( uc( C4::Context->preference("marcflavour") ) ) => 1 ); output_html_with_http_headers $query, $cookie, $template->output; diff --git a/serials/serials-home.pl b/serials/serials-home.pl index a0e4bc0185..9c59cad349 100755 --- a/serials/serials-home.pl +++ b/serials/serials-home.pl @@ -17,7 +17,6 @@ # You should have received a copy of the GNU General Public License # along with Koha; if not, see . - =head1 NAME serials-home.pl @@ -29,7 +28,7 @@ this script is the main page for serials/ =cut use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Auth qw( get_template_and_user ); use C4::Context; use C4::Output qw( output_html_with_http_headers ); @@ -40,16 +39,16 @@ my $routing = $query->param('routing') || C4::Context->preference("RoutingSerial my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "serials/serials-home.tt", - query => $query, - type => "intranet", - flagsrequired => { serials => '*' }, + template_name => "serials/serials-home.tt", + query => $query, + type => "intranet", + flagsrequired => { serials => '*' }, } ); $template->param( - routing => $routing, - (uc(C4::Context->preference("marcflavour"))) => 1 + routing => $routing, + ( uc( C4::Context->preference("marcflavour") ) ) => 1 ); output_html_with_http_headers $query, $cookie, $template->output; diff --git a/serials/serials-search.pl b/serials/serials-search.pl index 19eb7cea1d..6af807c328 100755 --- a/serials/serials-search.pl +++ b/serials/serials-search.pl @@ -17,7 +17,6 @@ # You should have received a copy of the GNU General Public License # along with Koha; if not, see . - =head1 NAME serials-search.pl @@ -29,62 +28,61 @@ this script is the search page for serials =cut use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Auth qw( get_template_and_user ); use C4::Context; -use C4::Output qw( output_html_with_http_headers ); +use C4::Output qw( output_html_with_http_headers ); use C4::Serials qw( CloseSubscription ReopenSubscription SearchSubscriptions check_routing ); use Koha::AdditionalFields; use Koha::DateUtils qw( dt_from_string ); use Koha::SharedContent; -my $query = CGI->new; -my $title = $query->param('title_filter') || ''; -my $ISSN = $query->param('ISSN_filter') || ''; -my $EAN = $query->param('EAN_filter') || ''; -my $callnumber = $query->param('callnumber_filter') || ''; -my $publisher = $query->param('publisher_filter') || ''; -my $bookseller = $query->param('bookseller_filter') || ''; -my $biblionumber = $query->param('biblionumber') || ''; -my $branch = $query->param('branch_filter') || ''; -my $location = $query->param('location_filter') || ''; +my $query = CGI->new; +my $title = $query->param('title_filter') || ''; +my $ISSN = $query->param('ISSN_filter') || ''; +my $EAN = $query->param('EAN_filter') || ''; +my $callnumber = $query->param('callnumber_filter') || ''; +my $publisher = $query->param('publisher_filter') || ''; +my $bookseller = $query->param('bookseller_filter') || ''; +my $biblionumber = $query->param('biblionumber') || ''; +my $branch = $query->param('branch_filter') || ''; +my $location = $query->param('location_filter') || ''; my $expiration_date = $query->param('expiration_date_filter') || ''; -my $routing = $query->param('routing') || C4::Context->preference("RoutingSerials"); -my $searched = $query->param('searched') || 0; -my $routinglist = $query->param('routinglist'); -my $mana = $query->param('mana') || 0; +my $routing = $query->param('routing') || C4::Context->preference("RoutingSerials"); +my $searched = $query->param('searched') || 0; +my $routinglist = $query->param('routinglist'); +my $mana = $query->param('mana') || 0; my @subscriptionids = $query->multi_param('subscriptionid'); -my $op = $query->param('op'); +my $op = $query->param('op'); my $orig_total; my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "serials/serials-search.tt", - query => $query, - type => "intranet", - flagsrequired => { serials => '*' }, + template_name => "serials/serials-search.tt", + query => $query, + type => "intranet", + flagsrequired => { serials => '*' }, } ); if ( $op and $op eq "close" ) { - for my $subscriptionid ( @subscriptionids ) { - C4::Serials::CloseSubscription( $subscriptionid ); + for my $subscriptionid (@subscriptionids) { + C4::Serials::CloseSubscription($subscriptionid); } } elsif ( $op and $op eq "reopen" ) { - for my $subscriptionid ( @subscriptionids ) { - C4::Serials::ReopenSubscription( $subscriptionid ); + for my $subscriptionid (@subscriptionids) { + C4::Serials::ReopenSubscription($subscriptionid); } } - my @additional_fields = Koha::AdditionalFields->search( { tablename => 'subscription', searchable => 1 } )->as_list; my @additional_field_filters; -for my $field ( @additional_fields ) { +for my $field (@additional_fields) { my $value = $query->param( 'additional_field_' . $field->id ); if ( defined $value and $value ne '' ) { push @additional_field_filters, { - id => $field->id, + id => $field->id, value => $value, }; } @@ -94,16 +92,18 @@ my @subscriptions; my $mana_statuscode; if ($searched) { if ($mana) { - my $result = Koha::SharedContent::search_entities("subscription",{ - title => $title, - issn => $ISSN, - ean => $EAN, - publisher => $publisher - }); + my $result = Koha::SharedContent::search_entities( + "subscription", + { + title => $title, + issn => $ISSN, + ean => $EAN, + publisher => $publisher + } + ); $mana_statuscode = $result->{code}; - @subscriptions = @{ $result->{data} }; - } - else { + @subscriptions = @{ $result->{data} }; + } else { my $subscriptions = SearchSubscriptions( { biblionumber => $biblionumber, @@ -121,45 +121,45 @@ if ($searched) { }, { results_limit => C4::Context->preference('SerialsSearchResultsLimit') } ); - @subscriptions = @{$subscriptions->{results}}; - $orig_total = $subscriptions->{total}; + @subscriptions = @{ $subscriptions->{results} }; + $orig_total = $subscriptions->{total}; } } if ($mana) { $template->param( - subscriptions => \@subscriptions, - statuscode => $mana_statuscode, - total => scalar @subscriptions, - title_filter => $title, - ISSN_filter => $ISSN, - EAN_filter => $EAN, - callnumber_filter => $callnumber, - publisher_filter => $publisher, - bookseller_filter => $bookseller, - branch_filter => $branch, - location_filter => $location, - expiration_date_filter => $expiration_date, - done_searched => $searched, - routing => $routing, - additional_field_filters => \@additional_field_filters, + subscriptions => \@subscriptions, + statuscode => $mana_statuscode, + total => scalar @subscriptions, + title_filter => $title, + ISSN_filter => $ISSN, + EAN_filter => $EAN, + callnumber_filter => $callnumber, + publisher_filter => $publisher, + bookseller_filter => $bookseller, + branch_filter => $branch, + location_filter => $location, + expiration_date_filter => $expiration_date, + done_searched => $searched, + routing => $routing, + additional_field_filters => \@additional_field_filters, additional_fields_for_subscription => \@additional_fields, - marcflavour => (uc(C4::Context->preference("marcflavour"))), - mana => $mana, - search_only => 1 + marcflavour => ( uc( C4::Context->preference("marcflavour") ) ), + mana => $mana, + search_only => 1 ); -} -else { +} else { + # to toggle between create or edit routing list options if ($routing) { - for my $subscription ( @subscriptions) { + for my $subscription (@subscriptions) { $subscription->{routingedit} = check_routing( $subscription->{subscriptionid} ); } } - my (@openedsubscriptions, @closedsubscriptions); - for my $sub ( @subscriptions ) { + my ( @openedsubscriptions, @closedsubscriptions ); + for my $sub (@subscriptions) { unless ( $sub->{closed} ) { push @openedsubscriptions, $sub unless $sub->{cannotdisplay}; @@ -171,37 +171,37 @@ else { my @branches = Koha::Libraries->search( {}, { order_by => ['branchcode'] } )->as_list; my @branches_loop; - foreach my $b ( @branches ) { + foreach my $b (@branches) { my $selected = 0; - $selected = 1 if( defined $branch and $branch eq $b->branchcode ); + $selected = 1 if ( defined $branch and $branch eq $b->branchcode ); push @branches_loop, { - branchcode => $b->branchcode, - branchname => $b->branchname, - selected => $selected, + branchcode => $b->branchcode, + branchname => $b->branchname, + selected => $selected, }; } $template->param( - openedsubscriptions => \@openedsubscriptions, - closedsubscriptions => \@closedsubscriptions, - total => @openedsubscriptions + @closedsubscriptions, - orig_total => $orig_total, - title_filter => $title, - ISSN_filter => $ISSN, - EAN_filter => $EAN, - callnumber_filter => $callnumber, - publisher_filter => $publisher, - bookseller_filter => $bookseller, - branch_filter => $branch, - location_filter => $location, - expiration_date_filter => $expiration_date, - branches_loop => \@branches_loop, - done_searched => $searched, - routing => $routing, - additional_field_filters => { map { $_->{id} => $_->{value} } @additional_field_filters }, + openedsubscriptions => \@openedsubscriptions, + closedsubscriptions => \@closedsubscriptions, + total => @openedsubscriptions + @closedsubscriptions, + orig_total => $orig_total, + title_filter => $title, + ISSN_filter => $ISSN, + EAN_filter => $EAN, + callnumber_filter => $callnumber, + publisher_filter => $publisher, + bookseller_filter => $bookseller, + branch_filter => $branch, + location_filter => $location, + expiration_date_filter => $expiration_date, + branches_loop => \@branches_loop, + done_searched => $searched, + routing => $routing, + additional_field_filters => { map { $_->{id} => $_->{value} } @additional_field_filters }, additional_fields_for_subscription => \@additional_fields, - marcflavour => (uc(C4::Context->preference("marcflavour"))), - mana => $mana + marcflavour => ( uc( C4::Context->preference("marcflavour") ) ), + mana => $mana ); } output_html_with_http_headers $query, $cookie, $template->output; diff --git a/serials/showpredictionpattern.pl b/serials/showpredictionpattern.pl index ae5e958ef3..19d414ccba 100755 --- a/serials/showpredictionpattern.pl +++ b/serials/showpredictionpattern.pl @@ -30,31 +30,32 @@ publication date, based on frequency and first publication date. use Modern::Perl; -use CGI qw ( -utf8 ); -use Date::Calc qw( Add_Delta_Days Add_Delta_YM Day_of_Week Delta_Days ); -use C4::Auth qw( get_template_and_user ); -use C4::Output qw( output_html_with_http_headers ); +use CGI qw ( -utf8 ); +use Date::Calc qw( Add_Delta_Days Add_Delta_YM Day_of_Week Delta_Days ); +use C4::Auth qw( get_template_and_user ); +use C4::Output qw( output_html_with_http_headers ); use C4::Serials qw( GetSubscription GetFictiveIssueNumber GetSeq GetSubscriptionIrregularities GetNextDate GetNextSeq ); use C4::Serials::Frequency; use Koha::DateUtils qw( dt_from_string ); my $input = CGI->new; -my ($template, $loggedinuser, $cookie, $flags) = get_template_and_user( { - template_name => 'serials/showpredictionpattern.tt', - query => $input, - type => 'intranet', - flagsrequired => { 'serials' => '*' }, -} ); +my ( $template, $loggedinuser, $cookie, $flags ) = get_template_and_user( + { + template_name => 'serials/showpredictionpattern.tt', + query => $input, + type => 'intranet', + flagsrequired => { 'serials' => '*' }, + } +); my $subscriptionid = $input->param('subscriptionid'); -my $frequencyid = $input->param('frequency'); +my $frequencyid = $input->param('frequency'); my $firstacquidate = $input->param('firstacquidate'); -my $nextacquidate = $input->param('nextacquidate'); -my $enddate = $input->param('to'); -my $subtype = $input->param('subtype'); -my $sublength = $input->param('sublength'); -my $custompattern = $input->param('custompattern'); - +my $nextacquidate = $input->param('nextacquidate'); +my $enddate = $input->param('to'); +my $subtype = $input->param('subtype'); +my $sublength = $input->param('sublength'); +my $custompattern = $input->param('custompattern'); my $frequency; if ( $frequencyid eq 'mana' ) { @@ -64,30 +65,29 @@ if ( $frequencyid eq 'mana' ) { 'description' => scalar $input->param('sfdescription') // '', 'unitsperissue' => scalar $input->param('unitsperissue') // '', 'issuesperunit' => scalar $input->param('issuesperunit') // '', - 'unit' => scalar $input->param('unit') // '' + 'unit' => scalar $input->param('unit') // '' }; -} -else { +} else { $frequency = GetSubscriptionFrequency($frequencyid); } my %pattern = ( numberingmethod => scalar $input->param('numberingmethod') // '', - numbering1 => scalar $input->param('numbering1') // '', - numbering2 => scalar $input->param('numbering2') // '', - numbering3 => scalar $input->param('numbering3') // '', - add1 => scalar $input->param('add1') // '', - add2 => scalar $input->param('add2') // '', - add3 => scalar $input->param('add3') // '', - whenmorethan1 => scalar $input->param('whenmorethan1') // '', - whenmorethan2 => scalar $input->param('whenmorethan2') // '', - whenmorethan3 => scalar $input->param('whenmorethan3') // '', - setto1 => scalar $input->param('setto1') // '', - setto2 => scalar $input->param('setto2') // '', - setto3 => scalar $input->param('setto3') // '', - every1 => scalar $input->param('every1') // '', - every2 => scalar $input->param('every2') // '', - every3 => scalar $input->param('every3') // '', + numbering1 => scalar $input->param('numbering1') // '', + numbering2 => scalar $input->param('numbering2') // '', + numbering3 => scalar $input->param('numbering3') // '', + add1 => scalar $input->param('add1') // '', + add2 => scalar $input->param('add2') // '', + add3 => scalar $input->param('add3') // '', + whenmorethan1 => scalar $input->param('whenmorethan1') // '', + whenmorethan2 => scalar $input->param('whenmorethan2') // '', + whenmorethan3 => scalar $input->param('whenmorethan3') // '', + setto1 => scalar $input->param('setto1') // '', + setto2 => scalar $input->param('setto2') // '', + setto3 => scalar $input->param('setto3') // '', + every1 => scalar $input->param('every1') // '', + every2 => scalar $input->param('every2') // '', + every3 => scalar $input->param('every3') // '', ); $firstacquidate = $firstacquidate ? dt_from_string($firstacquidate)->ymd : dt_from_string->ymd; @@ -98,76 +98,87 @@ $nextacquidate = $nextacquidate ? dt_from_string($nextacquidate)->ymd : $firstac my $date = $nextacquidate; my %subscription = ( - locale => scalar $input->param('locale') // '', - lastvalue1 => scalar $input->param('lastvalue1') // '', - lastvalue2 => scalar $input->param('lastvalue2') // '', - lastvalue3 => scalar $input->param('lastvalue3') // '', - innerloop1 => scalar $input->param('innerloop1') // '', - innerloop2 => scalar $input->param('innerloop2') // '', - innerloop3 => scalar $input->param('innerloop3') // '', - irregularity => '', - countissuesperunit => 1, - firstacquidate => $firstacquidate, + locale => scalar $input->param('locale') // '', + lastvalue1 => scalar $input->param('lastvalue1') // '', + lastvalue2 => scalar $input->param('lastvalue2') // '', + lastvalue3 => scalar $input->param('lastvalue3') // '', + innerloop1 => scalar $input->param('innerloop1') // '', + innerloop2 => scalar $input->param('innerloop2') // '', + innerloop3 => scalar $input->param('innerloop3') // '', + irregularity => '', + countissuesperunit => 1, + firstacquidate => $firstacquidate, ); my $issuenumber; -if(defined $subscriptionid) { - ($issuenumber) = C4::Serials::GetFictiveIssueNumber(\%subscription, $date, $frequency); +if ( defined $subscriptionid ) { + ($issuenumber) = C4::Serials::GetFictiveIssueNumber( \%subscription, $date, $frequency ); } else { $issuenumber = 1; } my @predictions_loop; -my ($calculated) = GetSeq(\%subscription, \%pattern); +my ($calculated) = GetSeq( \%subscription, \%pattern ); push @predictions_loop, { - number => $calculated, + number => $calculated, publicationdate => $date, - issuenumber => $issuenumber, - dow => Day_of_Week(split /-/, $date), + issuenumber => $issuenumber, + dow => Day_of_Week( split /-/, $date ), }; my @irreg = (); -if(defined $subscriptionid) { +if ( defined $subscriptionid ) { @irreg = C4::Serials::GetSubscriptionIrregularities($subscriptionid); - while(@irreg && $issuenumber > $irreg[0]) { + while ( @irreg && $issuenumber > $irreg[0] ) { shift @irreg; } - if(@irreg && $issuenumber == $irreg[0]){ + if ( @irreg && $issuenumber == $irreg[0] ) { $predictions_loop[0]->{'not_published'} = 1; shift @irreg; } } my $i = 1; -while( $i < 1000 ) { +while ( $i < 1000 ) { my %line; - if(defined $date){ - $date = GetNextDate(\%subscription, $date, $frequency); + if ( defined $date ) { + $date = GetNextDate( \%subscription, $date, $frequency ); } - if(defined $date){ + if ( defined $date ) { $line{'publicationdate'} = $date; - $line{'dow'} = Day_of_Week(split /-/, $date); + $line{'dow'} = Day_of_Week( split /-/, $date ); } # Check if we don't have exceed end date - if($sublength){ - if($subtype eq "issues" && $i >= $sublength){ + if ($sublength) { + if ( $subtype eq "issues" && $i >= $sublength ) { last; - } elsif($subtype eq "weeks" && $date && Delta_Days( split(/-/, $date), Add_Delta_Days( split(/-/, $firstacquidate), 7*$sublength - 1 ) ) < 0) { + } elsif ( $subtype eq "weeks" + && $date + && Delta_Days( split( /-/, $date ), Add_Delta_Days( split( /-/, $firstacquidate ), 7 * $sublength - 1 ) ) < + 0 ) + { last; - } elsif($subtype eq "months" && $date && (Delta_Days( split(/-/, $date), Add_Delta_YM( split(/-/, $firstacquidate), 0, $sublength) ) - 1) < 0 ) { + } elsif ( $subtype eq "months" + && $date + && ( Delta_Days( split( /-/, $date ), Add_Delta_YM( split( /-/, $firstacquidate ), 0, $sublength ) ) - 1 ) + < 0 ) + { last; } } - if($enddate && $date && Delta_Days( split(/-/, $date), split(/-/, $enddate) ) <= 0 ) { + if ( $enddate && $date && Delta_Days( split( /-/, $date ), split( /-/, $enddate ) ) <= 0 ) { last; } - ($calculated, $subscription{'lastvalue1'}, $subscription{'lastvalue2'}, $subscription{'lastvalue3'}, $subscription{'innerloop1'}, $subscription{'innerloop2'}, $subscription{'innerloop3'}) = GetNextSeq(\%subscription, \%pattern, $frequency, $date); + ( + $calculated, $subscription{'lastvalue1'}, $subscription{'lastvalue2'}, $subscription{'lastvalue3'}, + $subscription{'innerloop1'}, $subscription{'innerloop2'}, $subscription{'innerloop3'} + ) = GetNextSeq( \%subscription, \%pattern, $frequency, $date ); $issuenumber++; - $line{'number'} = $calculated; + $line{'number'} = $calculated; $line{'issuenumber'} = $issuenumber; - if(@irreg && $issuenumber == $irreg[0]){ + if ( @irreg && $issuenumber == $irreg[0] ) { $line{'not_published'} = 1; shift @irreg; } diff --git a/serials/subscription-add.pl b/serials/subscription-add.pl index 35ba10e05f..8dff969978 100755 --- a/serials/subscription-add.pl +++ b/serials/subscription-add.pl @@ -17,13 +17,14 @@ use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use Date::Calc qw( Add_Delta_Days Add_Delta_YM ); -use C4::Koha qw( GetAuthorisedValues ); -use C4::Auth qw( get_template_and_user ); +use C4::Koha qw( GetAuthorisedValues ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_and_exit output_html_with_http_headers ); use C4::Context; -use C4::Serials qw( GetSubscription GetNextExpected GetSerials GetSubscriptionLength NewSubscription ModNextExpected ModSubscription ); +use C4::Serials + qw( GetSubscription GetNextExpected GetSerials GetSubscriptionLength NewSubscription ModNextExpected ModSubscription ); use C4::Serials::Frequency; use C4::Serials::Numberpattern; use C4::Letters qw( GetLetters ); @@ -38,24 +39,22 @@ use Koha::Subscription::Frequency; use Koha::SharedContent; our $query = CGI->new; -my $op = $query->param('op') || ''; +my $op = $query->param('op') || ''; my $dbh = C4::Context->dbh; my $sub_length; - # Permission needed if it is a modification : edit_subscription # Permission needed otherwise (nothing or dup) : create_subscription -my $permission = - ( $op eq 'modify' || $op eq 'cud-modsubscription' ) ? "edit_subscription" : "create_subscription"; - -our ($template, $loggedinuser, $cookie) -= get_template_and_user({template_name => "serials/subscription-add.tt", - query => $query, - type => "intranet", - flagsrequired => {serials => $permission}, - }); - +my $permission = ( $op eq 'modify' || $op eq 'cud-modsubscription' ) ? "edit_subscription" : "create_subscription"; +our ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "serials/subscription-add.tt", + query => $query, + type => "intranet", + flagsrequired => { serials => $permission }, + } +); my $sub_on; @@ -66,54 +65,54 @@ my $mana_url = C4::Context->config('mana_config'); $template->param( 'mana_url' => $mana_url ); my $subscriptionid = $query->param('subscriptionid'); -if ($op eq 'modify' || $op eq 'dup' || $op eq 'cud-modsubscription') { +if ( $op eq 'modify' || $op eq 'dup' || $op eq 'cud-modsubscription' ) { $subs = GetSubscription($subscriptionid); - output_and_exit( $query, $cookie, $template, 'unknown_subscription') + output_and_exit( $query, $cookie, $template, 'unknown_subscription' ) unless $subs; ## FIXME : Check rights to edit if mod. Could/Should display an error message. - if ($subs->{'cannotedit'} && $op eq 'modify'){ - carp "Attempt to modify subscription $subscriptionid by ".C4::Context->userenv->{'id'}." not allowed"; - print $query->redirect("/cgi-bin/koha/serials/subscription-detail.pl?subscriptionid=$subscriptionid"); + if ( $subs->{'cannotedit'} && $op eq 'modify' ) { + carp "Attempt to modify subscription $subscriptionid by " . C4::Context->userenv->{'id'} . " not allowed"; + print $query->redirect("/cgi-bin/koha/serials/subscription-detail.pl?subscriptionid=$subscriptionid"); } - $firstissuedate = $subs->{firstacquidate} || ''; # in iso format. - if (!defined $subs->{letter}) { - $subs->{letter}= q{}; + $firstissuedate = $subs->{firstacquidate} || ''; # in iso format. + if ( !defined $subs->{letter} ) { + $subs->{letter} = q{}; } my $nextexpected = GetNextExpected($subscriptionid); - $nextexpected->{'isfirstissue'} = $nextexpected->{planneddate} eq $firstissuedate ; - $subs->{nextacquidate} = $nextexpected->{planneddate} if($op eq 'modify'); - unless($op eq 'cud-modsubscription') { + $nextexpected->{'isfirstissue'} = $nextexpected->{planneddate} eq $firstissuedate; + $subs->{nextacquidate} = $nextexpected->{planneddate} if ( $op eq 'modify' ); + unless ( $op eq 'cud-modsubscription' ) { foreach my $length_unit (qw(numberlength weeklength monthlength)) { - if ($subs->{$length_unit}) { - $sub_length=$subs->{$length_unit}; - $sub_on=$length_unit; + if ( $subs->{$length_unit} ) { + $sub_length = $subs->{$length_unit}; + $sub_on = $length_unit; last; } } $template->param( %{$subs} ); $template->param( - $op => 1, - "subtype_$sub_on" => 1, - sublength =>$sub_length, - history => ($op eq 'modify'), - firstacquiyear => substr($firstissuedate,0,4), - ); + $op => 1, + "subtype_$sub_on" => 1, + sublength => $sub_length, + history => ( $op eq 'modify' ), + firstacquiyear => substr( $firstissuedate, 0, 4 ), + ); - if($op eq 'modify') { + if ( $op eq 'modify' ) { my ($serials_number) = GetSerials($subscriptionid); - if($serials_number > 1) { - $template->param(more_than_one_serial => 1); + if ( $serials_number > 1 ) { + $template->param( more_than_one_serial => 1 ); } } } if ( $op eq 'dup' ) { my $dont_copy_fields = C4::Context->preference('SubscriptionDuplicateDroppedInput'); - my @fields_id = map { fieldid => $_ }, split '\|', $dont_copy_fields; + my @fields_id = map { fieldid => $_ }, split '\|', $dont_copy_fields; $template->param( dont_export_field_loop => \@fields_id ); } @@ -123,17 +122,18 @@ if ($op eq 'modify' || $op eq 'dup' || $op eq 'cud-modsubscription') { } my $locations_loop = GetAuthorisedValues("LOC"); -my $ccodes_loop = GetAuthorisedValues("CCODE"); +my $ccodes_loop = GetAuthorisedValues("CCODE"); $template->param( - branchcode => $subs->{branchcode}, - locations_loop=>$locations_loop, - ccodes_loop=>$ccodes_loop + branchcode => $subs->{branchcode}, + locations_loop => $locations_loop, + ccodes_loop => $ccodes_loop ); -my @additional_fields = Koha::AdditionalFields->search({ tablename => 'subscription' })->as_list; +my @additional_fields = Koha::AdditionalFields->search( { tablename => 'subscription' } )->as_list; my @additional_field_values; -@additional_field_values = Koha::Subscriptions->find($subscriptionid)->get_additional_field_values_for_template if $subscriptionid; +@additional_field_values = Koha::Subscriptions->find($subscriptionid)->get_additional_field_values_for_template + if $subscriptionid; $template->param( additional_fields => \@additional_fields, @@ -144,33 +144,43 @@ my $typeloop = { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search_with_lo # FIXME We should use the translated_description for item types my @typearg = - map { { code => $_, value => $typeloop->{$_}{'description'}, selected => ( ( $subs->{itemtype} and $_ eq $subs->{itemtype} ) ? "selected=\"selected\"" : "" ), } } sort keys %{$typeloop}; + map { + { + code => $_, value => $typeloop->{$_}{'description'}, + selected => ( ( $subs->{itemtype} and $_ eq $subs->{itemtype} ) ? "selected=\"selected\"" : "" ), + } + } sort keys %{$typeloop}; my @previoustypearg = - map { { code => $_, value => $typeloop->{$_}{'description'}, selected => ( ( $subs->{previousitemtype} and $_ eq $subs->{previousitemtype} ) ? "selected=\"selected\"" : "" ), } } sort keys %{$typeloop}; + map { + { + code => $_, value => $typeloop->{$_}{'description'}, selected => + ( ( $subs->{previousitemtype} and $_ eq $subs->{previousitemtype} ) ? "selected=\"selected\"" : "" ), + } + } sort keys %{$typeloop}; $template->param( - typeloop => \@typearg, - previoustypeloop => \@previoustypearg, - locations_loop=>$locations_loop, + typeloop => \@typearg, + previoustypeloop => \@previoustypearg, + locations_loop => $locations_loop, ); # prepare template variables common to all $op conditions: -$template->param('makePreviousSerialAvailable' => 1) if (C4::Context->preference('makePreviousSerialAvailable')); +$template->param( 'makePreviousSerialAvailable' => 1 ) if ( C4::Context->preference('makePreviousSerialAvailable') ); -if ($op!~/^mod/) { +if ( $op !~ /^mod/ ) { my $letters = get_letter_loop(); $template->param( letterloop => $letters ); } -if ($op eq 'cud-addsubscription') { +if ( $op eq 'cud-addsubscription' ) { redirect_add_subscription(); -} elsif ($op eq 'cud-modsubscription') { +} elsif ( $op eq 'cud-modsubscription' ) { redirect_mod_subscription(); } else { $template->param( - subtypes => [ qw( numberlength weeklength monthlength ) ], - subtype => $sub_on, + subtypes => [qw( numberlength weeklength monthlength )], + subtype => $sub_on, ); if ( $op ne 'cud-modsubscription' && $op ne 'dup' && $op ne 'modify' ) { @@ -179,50 +189,52 @@ if ($op eq 'cud-addsubscription') { } my $new_biblionumber = $query->param('biblionumber_for_new_subscription'); - if (defined $new_biblionumber) { - my $biblio = Koha::Biblios->find( $new_biblionumber ); - if (defined $biblio) { - $template->param(bibnum => $new_biblionumber); - $template->param(bibliotitle => $biblio->title); + if ( defined $new_biblionumber ) { + my $biblio = Koha::Biblios->find($new_biblionumber); + if ( defined $biblio ) { + $template->param( bibnum => $new_biblionumber ); + $template->param( bibliotitle => $biblio->title ); } } - $template->param((uc(C4::Context->preference("marcflavour"))) => 1); + $template->param( ( uc( C4::Context->preference("marcflavour") ) ) => 1 ); my @frequencies = GetSubscriptionFrequencies; my @frqloop; foreach my $freq (@frequencies) { my $selected = 0; - $selected = 1 if ($subs->{periodicity} and $freq->{id} eq $subs->{periodicity}); + $selected = 1 if ( $subs->{periodicity} and $freq->{id} eq $subs->{periodicity} ); my $row = { - id => $freq->{'id'}, + id => $freq->{'id'}, selected => $selected, - label => $freq->{'description'}, + label => $freq->{'description'}, }; push @frqloop, $row; } - $template->param(frequencies => \@frqloop); + $template->param( frequencies => \@frqloop ); my @numpatterns = GetSubscriptionNumberpatterns; my @numberpatternloop; foreach my $numpattern (@numpatterns) { my $selected = 0; - $selected = 1 if($subs->{numberpattern} and $numpattern->{id} eq $subs->{numberpattern}); + $selected = 1 if ( $subs->{numberpattern} and $numpattern->{id} eq $subs->{numberpattern} ); my $row = { - id => $numpattern->{'id'}, + id => $numpattern->{'id'}, selected => $selected, - label => $numpattern->{'label'}, + label => $numpattern->{'label'}, }; push @numberpatternloop, $row; } - $template->param(numberpatterns => \@numberpatternloop); + $template->param( numberpatterns => \@numberpatternloop ); - my $languages = [ map { - { - language => $_->{iso639_2_code}, - description => $_->{language_description} || $_->{language} - } - } @{ C4::Languages::getAllLanguages() } ]; + my $languages = [ + map { + { + language => $_->{iso639_2_code}, + description => $_->{language_description} || $_->{language} + } + } @{ C4::Languages::getAllLanguages() } + ]; $template->param( locales => $languages ); @@ -235,7 +247,7 @@ if ($op eq 'cud-addsubscription') { sub get_letter_loop { my ($selected_lettercode) = @_; $selected_lettercode //= ''; - my $letters = GetLetters({ module => 'serial' }); + my $letters = GetLetters( { module => 'serial' } ); return [ map { { @@ -243,32 +255,44 @@ sub get_letter_loop { lettername => $_->{name}, ( $_->{code} eq $selected_lettercode ? ( selected => 1 ) : () ), } - } @$letters + } @$letters ]; } sub _guess_enddate { - my ($startdate_iso, $frequencyid, $numberlength, $weeklength, $monthlength) = @_; - my ($year, $month, $day); + my ( $startdate_iso, $frequencyid, $numberlength, $weeklength, $monthlength ) = @_; + my ( $year, $month, $day ); my $enddate; - if($numberlength != 0) { + if ( $numberlength != 0 ) { my $frequency = GetSubscriptionFrequency($frequencyid); - if($frequency->{'unit'} eq 'day') { - ($year, $month, $day) = Add_Delta_Days(split(/-/, $startdate_iso), $numberlength * $frequency->{'unitsperissue'} / $frequency->{'issuesperunit'}); - } elsif($frequency->{'unit'} eq 'week') { - ($year, $month, $day) = Add_Delta_Days(split(/-/, $startdate_iso), $numberlength * 7 * $frequency->{'unitsperissue'} / $frequency->{'issuesperunit'}); - } elsif($frequency->{'unit'} eq 'month') { - ($year, $month, $day) = Add_Delta_YM(split(/-/, $startdate_iso), 0, $numberlength * $frequency->{'unitsperissue'} / $frequency->{'issuesperunit'}); - } elsif($frequency->{'unit'} eq 'year') { - ($year, $month, $day) = Add_Delta_YM(split(/-/, $startdate_iso), $numberlength * $frequency->{'unitsperissue'} / $frequency->{'issuesperunit'}, 0); + if ( $frequency->{'unit'} eq 'day' ) { + ( $year, $month, $day ) = Add_Delta_Days( + split( /-/, $startdate_iso ), + $numberlength * $frequency->{'unitsperissue'} / $frequency->{'issuesperunit'} + ); + } elsif ( $frequency->{'unit'} eq 'week' ) { + ( $year, $month, $day ) = Add_Delta_Days( + split( /-/, $startdate_iso ), + $numberlength * 7 * $frequency->{'unitsperissue'} / $frequency->{'issuesperunit'} + ); + } elsif ( $frequency->{'unit'} eq 'month' ) { + ( $year, $month, $day ) = Add_Delta_YM( + split( /-/, $startdate_iso ), 0, + $numberlength * $frequency->{'unitsperissue'} / $frequency->{'issuesperunit'} + ); + } elsif ( $frequency->{'unit'} eq 'year' ) { + ( $year, $month, $day ) = Add_Delta_YM( + split( /-/, $startdate_iso ), + $numberlength * $frequency->{'unitsperissue'} / $frequency->{'issuesperunit'}, 0 + ); } - } elsif($weeklength != 0) { - ($year, $month, $day) = Add_Delta_Days(split(/-/, $startdate_iso), $weeklength * 7); - } elsif($monthlength != 0) { - ($year, $month, $day) = Add_Delta_YM(split(/-/, $startdate_iso), 0, $monthlength); + } elsif ( $weeklength != 0 ) { + ( $year, $month, $day ) = Add_Delta_Days( split( /-/, $startdate_iso ), $weeklength * 7 ); + } elsif ( $monthlength != 0 ) { + ( $year, $month, $day ) = Add_Delta_YM( split( /-/, $startdate_iso ), 0, $monthlength ); } - if(defined $year) { - $enddate = sprintf("%04d-%02d-%02d", $year, $month, $day); + if ( defined $year ) { + $enddate = sprintf( "%04d-%02d-%02d", $year, $month, $day ); } else { undef $enddate; } @@ -277,7 +301,7 @@ sub _guess_enddate { sub redirect_add_subscription { my $periodicity = $query->param('frequency'); - if ($periodicity eq 'mana') { + if ( $periodicity eq 'mana' ) { my $subscription_freq = Koha::Subscription::Frequency->new()->set( { description => $query->param('sfdescription'), @@ -288,7 +312,7 @@ sub redirect_add_subscription { )->store(); $periodicity = $subscription_freq->id; } - my $numberpattern = Koha::Subscription::Numberpatterns->new_or_existing({ $query->Vars }); + my $numberpattern = Koha::Subscription::Numberpatterns->new_or_existing( { $query->Vars } ); my $auser = $query->param('user'); my $branchcode = $query->param('branchcode'); @@ -299,69 +323,74 @@ sub redirect_add_subscription { my $locale = $query->param('locale'); my $graceperiod = $query->param('graceperiod') || 0; - my $subtype = $query->param('subtype'); + my $subtype = $query->param('subtype'); my $sublength = $query->param('sublength'); - my ( $numberlength, $weeklength, $monthlength ) - = GetSubscriptionLength( $subtype, $sublength ); - my $add1 = $query->param('add1'); - my $lastvalue1 = $query->param('lastvalue1'); - my $innerloop1 = $query->param('innerloop1'); - my $innerloop2 = $query->param('innerloop2'); - my $lastvalue2 = $query->param('lastvalue2'); - my $lastvalue3 = $query->param('lastvalue3'); - my $innerloop3 = $query->param('innerloop3'); - my $status = 1; - my $biblionumber = $query->param('biblionumber'); - my $callnumber = $query->param('callnumber'); - my $notes = $query->param('notes'); - my $internalnotes = $query->param('internalnotes'); - my $letter = $query->param('letter'); - my $manualhistory = $query->param('manualhist') ? 1 : 0; - my $serialsadditems = $query->param('serialsadditems'); - my $staffdisplaycount = $query->param('staffdisplaycount'); - my $opacdisplaycount = $query->param('opacdisplaycount'); - my $location = $query->param('location'); - my $itemtype = $query->param('itemtype'); - my $previousitemtype = $query->param('previousitemtype'); - my $skip_serialseq = $query->param('skip_serialseq'); - my $ccode = $query->param('ccode'); + my ( $numberlength, $weeklength, $monthlength ) = GetSubscriptionLength( $subtype, $sublength ); + my $add1 = $query->param('add1'); + my $lastvalue1 = $query->param('lastvalue1'); + my $innerloop1 = $query->param('innerloop1'); + my $innerloop2 = $query->param('innerloop2'); + my $lastvalue2 = $query->param('lastvalue2'); + my $lastvalue3 = $query->param('lastvalue3'); + my $innerloop3 = $query->param('innerloop3'); + my $status = 1; + my $biblionumber = $query->param('biblionumber'); + my $callnumber = $query->param('callnumber'); + my $notes = $query->param('notes'); + my $internalnotes = $query->param('internalnotes'); + my $letter = $query->param('letter'); + my $manualhistory = $query->param('manualhist') ? 1 : 0; + my $serialsadditems = $query->param('serialsadditems'); + my $staffdisplaycount = $query->param('staffdisplaycount'); + my $opacdisplaycount = $query->param('opacdisplaycount'); + my $location = $query->param('location'); + my $itemtype = $query->param('itemtype'); + my $previousitemtype = $query->param('previousitemtype'); + my $skip_serialseq = $query->param('skip_serialseq'); + my $ccode = $query->param('ccode'); my $published_on_template = $query->param('published_on_template'); my $mana_id; if ( $query->param('mana_id') ne "" ) { $mana_id = $query->param('mana_id'); - Koha::SharedContent::increment_entity_value("subscription",$mana_id, "nbofusers"); + Koha::SharedContent::increment_entity_value( "subscription", $mana_id, "nbofusers" ); } - my $startdate = output_pref( { str => scalar $query->param('startdate'), dateonly => 1, dateformat => 'iso' } ); - my $enddate = output_pref( { str => scalar $query->param('enddate'), dateonly => 1, dateformat => 'iso' } ); - my $firstacquidate = output_pref( { str => scalar $query->param('firstacquidate'), dateonly => 1, dateformat => 'iso' } ); + my $startdate = output_pref( { str => scalar $query->param('startdate'), dateonly => 1, dateformat => 'iso' } ); + my $enddate = output_pref( { str => scalar $query->param('enddate'), dateonly => 1, dateformat => 'iso' } ); + my $firstacquidate = + output_pref( { str => scalar $query->param('firstacquidate'), dateonly => 1, dateformat => 'iso' } ); - if(!defined $enddate || $enddate eq '') { - if($subtype eq "issues") { - $enddate = _guess_enddate($firstacquidate, $periodicity, $numberlength, $weeklength, $monthlength) + if ( !defined $enddate || $enddate eq '' ) { + if ( $subtype eq "issues" ) { + $enddate = _guess_enddate( $firstacquidate, $periodicity, $numberlength, $weeklength, $monthlength ); } else { - $enddate = _guess_enddate($startdate, $periodicity, $numberlength, $weeklength, $monthlength) + $enddate = _guess_enddate( $startdate, $periodicity, $numberlength, $weeklength, $monthlength ); } } my $subscriptionid = NewSubscription( - $auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $biblionumber, - $startdate, $periodicity, $numberlength, $weeklength, - $monthlength, $lastvalue1, $innerloop1, $lastvalue2, $innerloop2, - $lastvalue3, $innerloop3, $status, $notes, $letter, $firstacquidate, - join(";",@irregularity), $numberpattern, $locale, $callnumber, - $manualhistory, $internalnotes, $serialsadditems, - $staffdisplaycount, $opacdisplaycount, $graceperiod, $location, $enddate, - $skip_serialseq, $itemtype, $previousitemtype, $mana_id, $ccode, $published_on_template + $auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $biblionumber, + $startdate, $periodicity, $numberlength, $weeklength, + $monthlength, $lastvalue1, $innerloop1, $lastvalue2, $innerloop2, + $lastvalue3, $innerloop3, $status, $notes, $letter, $firstacquidate, + join( ";", @irregularity ), $numberpattern, $locale, $callnumber, + $manualhistory, $internalnotes, $serialsadditems, + $staffdisplaycount, $opacdisplaycount, $graceperiod, $location, $enddate, + $skip_serialseq, $itemtype, $previousitemtype, $mana_id, $ccode, $published_on_template ); - if ( (C4::Context->preference('Mana') == 1) and ( grep { $_ eq "subscription" } split(/,/, C4::Context->preference('AutoShareWithMana'))) ){ - my $result = Koha::SharedContent::send_entity( $query->param('mana_language') || '', $loggedinuser, $subscriptionid, 'subscription'); + if ( ( C4::Context->preference('Mana') == 1 ) + and ( grep { $_ eq "subscription" } split( /,/, C4::Context->preference('AutoShareWithMana') ) ) ) + { + my $result = Koha::SharedContent::send_entity( + $query->param('mana_language') || '', $loggedinuser, $subscriptionid, + 'subscription' + ); $template->param( mana_msg => $result->{msg} ); } - my @additional_fields = Koha::Subscriptions->find($subscriptionid) - ->prepare_cgi_additional_field_values( $query, 'subscription' ); - Koha::Subscriptions->find($subscriptionid)->set_additional_fields(\@additional_fields); + my @additional_fields = + Koha::Subscriptions->find($subscriptionid)->prepare_cgi_additional_field_values( $query, 'subscription' ); + Koha::Subscriptions->find($subscriptionid)->set_additional_fields( \@additional_fields ); print $query->redirect("/cgi-bin/koha/serials/subscription-detail.pl?subscriptionid=$subscriptionid"); return; @@ -369,26 +398,28 @@ sub redirect_add_subscription { sub redirect_mod_subscription { my $subscriptionid = $query->param('subscriptionid'); - my @irregularity = $query->multi_param('irregularity'); - my $auser = $query->param('user'); + my @irregularity = $query->multi_param('irregularity'); + my $auser = $query->param('user'); my $librarian => scalar $query->param('librarian'), - my $branchcode = $query->param('branchcode'); - my $cost = $query->param('cost'); + my $branchcode = $query->param('branchcode'); + my $cost = $query->param('cost'); my $aqbooksellerid = $query->param('aqbooksellerid'); - my $biblionumber = $query->param('biblionumber'); - my $aqbudgetid = $query->param('aqbudgetid'); + my $biblionumber = $query->param('biblionumber'); + my $aqbudgetid = $query->param('aqbudgetid'); - my $startdate = output_pref( { str => scalar $query->param('startdate'), dateonly => 1, dateformat => 'iso' } ); - my $enddate = output_pref( { str => scalar $query->param('enddate'), dateonly => 1, dateformat => 'iso' } ); - my $firstacquidate = output_pref( { str => scalar $query->param('firstacquidate'), dateonly => 1, dateformat => 'iso' } ); + my $startdate = output_pref( { str => scalar $query->param('startdate'), dateonly => 1, dateformat => 'iso' } ); + my $enddate = output_pref( { str => scalar $query->param('enddate'), dateonly => 1, dateformat => 'iso' } ); + my $firstacquidate = + output_pref( { str => scalar $query->param('firstacquidate'), dateonly => 1, dateformat => 'iso' } ); - my $nextacquidate = $query->param('nextacquidate'); - $nextacquidate = $nextacquidate + my $nextacquidate = $query->param('nextacquidate'); + $nextacquidate = + $nextacquidate ? output_pref( { str => $nextacquidate, dateonly => 1, dateformat => 'iso' } ) : $firstacquidate; my $periodicity = $query->param('frequency'); - if ($periodicity eq 'mana') { + if ( $periodicity eq 'mana' ) { my $subscription_freq = Koha::Subscription::Frequency->new()->set( { description => $query->param('sfdescription'), @@ -399,75 +430,76 @@ sub redirect_mod_subscription { )->store(); $periodicity = $subscription_freq->id; } - my $numberpattern = Koha::Subscription::Numberpatterns->new_or_existing({ $query->Vars }); + my $numberpattern = Koha::Subscription::Numberpatterns->new_or_existing( { $query->Vars } ); - my $subtype = $query->param('subtype'); + my $subtype = $query->param('subtype'); my $sublength = $query->param('sublength'); - my ($numberlength, $weeklength, $monthlength) = GetSubscriptionLength( $subtype, $sublength ); - my $locale = $query->param('locale'); - my $lastvalue1 = $query->param('lastvalue1'); - my $innerloop1 = $query->param('innerloop1'); - my $lastvalue2 = $query->param('lastvalue2'); - my $innerloop2 = $query->param('innerloop2'); - my $lastvalue3 = $query->param('lastvalue3'); - my $innerloop3 = $query->param('innerloop3'); - my $status = 1; - my $callnumber = $query->param('callnumber'); - my $notes = $query->param('notes'); - my $internalnotes = $query->param('internalnotes'); - my $letter = $query->param('letter'); - my $manualhistory = $query->param('manualhist') ? 1 : 0; - my $serialsadditems = $query->param('serialsadditems'); - my $staffdisplaycount = $query->param('staffdisplaycount'); - my $opacdisplaycount = $query->param('opacdisplaycount'); - my $graceperiod = $query->param('graceperiod') || 0; - my $location = $query->param('location'); - my $itemtype = $query->param('itemtype'); - my $previousitemtype = $query->param('previousitemtype'); - my $skip_serialseq = $query->param('skip_serialseq'); - my $ccode = $query->param('ccode'); + my ( $numberlength, $weeklength, $monthlength ) = GetSubscriptionLength( $subtype, $sublength ); + my $locale = $query->param('locale'); + my $lastvalue1 = $query->param('lastvalue1'); + my $innerloop1 = $query->param('innerloop1'); + my $lastvalue2 = $query->param('lastvalue2'); + my $innerloop2 = $query->param('innerloop2'); + my $lastvalue3 = $query->param('lastvalue3'); + my $innerloop3 = $query->param('innerloop3'); + my $status = 1; + my $callnumber = $query->param('callnumber'); + my $notes = $query->param('notes'); + my $internalnotes = $query->param('internalnotes'); + my $letter = $query->param('letter'); + my $manualhistory = $query->param('manualhist') ? 1 : 0; + my $serialsadditems = $query->param('serialsadditems'); + my $staffdisplaycount = $query->param('staffdisplaycount'); + my $opacdisplaycount = $query->param('opacdisplaycount'); + my $graceperiod = $query->param('graceperiod') || 0; + my $location = $query->param('location'); + my $itemtype = $query->param('itemtype'); + my $previousitemtype = $query->param('previousitemtype'); + my $skip_serialseq = $query->param('skip_serialseq'); + my $ccode = $query->param('ccode'); my $published_on_template = $query->param('published_on_template'); my $mana_id; if ( $query->param('mana_id') ne "" ) { $mana_id = $query->param('mana_id'); - Koha::SharedContent::increment_entity_value("subscription",$mana_id, "nbofusers"); - } - else { + Koha::SharedContent::increment_entity_value( "subscription", $mana_id, "nbofusers" ); + } else { $mana_id = undef; } # Guess end date - if(!defined $enddate || $enddate eq '') { - if($subtype eq "issues") { - $enddate = _guess_enddate($nextacquidate, $periodicity, $numberlength, $weeklength, $monthlength); + if ( !defined $enddate || $enddate eq '' ) { + if ( $subtype eq "issues" ) { + $enddate = _guess_enddate( $nextacquidate, $periodicity, $numberlength, $weeklength, $monthlength ); } else { - $enddate = _guess_enddate($startdate, $periodicity, $numberlength, $weeklength, $monthlength); + $enddate = _guess_enddate( $startdate, $periodicity, $numberlength, $weeklength, $monthlength ); } } my $nextexpected = GetNextExpected($subscriptionid); + # If it's a mod, we need to check the current 'expected' issue, and mod it in the serials table if necessary. if ( $nextexpected->{planneddate} && $nextacquidate ne $nextexpected->{planneddate} ) { - ModNextExpected($subscriptionid, $nextacquidate); + ModNextExpected( $subscriptionid, $nextacquidate ); + # if we have not received any issues yet, then we also must change the firstacquidate for the subs. - $firstissuedate = $nextacquidate if($nextexpected->{isfirstissue}); + $firstissuedate = $nextacquidate if ( $nextexpected->{isfirstissue} ); } ModSubscription( - $auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $startdate, - $periodicity, $firstacquidate, join(";",@irregularity), - $numberpattern, $locale, $numberlength, $weeklength, $monthlength, $lastvalue1, - $innerloop1, $lastvalue2, $innerloop2, $lastvalue3, $innerloop3, - $status, $biblionumber, $callnumber, $notes, $letter, - $manualhistory, $internalnotes, $serialsadditems, $staffdisplaycount, - $opacdisplaycount, $graceperiod, $location, $enddate, $subscriptionid, - $skip_serialseq, $itemtype, $previousitemtype, $mana_id, $ccode, $published_on_template + $auser, $branchcode, $aqbooksellerid, $cost, $aqbudgetid, $startdate, + $periodicity, $firstacquidate, join( ";", @irregularity ), + $numberpattern, $locale, $numberlength, $weeklength, $monthlength, $lastvalue1, + $innerloop1, $lastvalue2, $innerloop2, $lastvalue3, $innerloop3, + $status, $biblionumber, $callnumber, $notes, $letter, + $manualhistory, $internalnotes, $serialsadditems, $staffdisplaycount, + $opacdisplaycount, $graceperiod, $location, $enddate, $subscriptionid, + $skip_serialseq, $itemtype, $previousitemtype, $mana_id, $ccode, $published_on_template ); my @additional_fields = Koha::Subscriptions->find($subscriptionid)->prepare_cgi_additional_field_values( $query, 'subscription' ); - Koha::Subscriptions->find($subscriptionid)->set_additional_fields(\@additional_fields); + Koha::Subscriptions->find($subscriptionid)->set_additional_fields( \@additional_fields ); print $query->redirect("/cgi-bin/koha/serials/subscription-detail.pl?subscriptionid=$subscriptionid"); return; diff --git a/serials/subscription-batchedit.pl b/serials/subscription-batchedit.pl index 676905cbba..da4e42c7f3 100755 --- a/serials/subscription-batchedit.pl +++ b/serials/subscription-batchedit.pl @@ -62,6 +62,7 @@ if ( $op eq 'cud-batchedit' ) { internalnotes => scalar $cgi->param('internalnotes'), serialsadditems => scalar $cgi->param('serialsadditems'), ); + # If we convert a blank string we get todays date, we should only convert enddate if it is not blank $params{'enddate'} = dt_from_string( scalar $cgi->param('enddate') ) if $cgi->param('enddate'); @@ -87,7 +88,7 @@ if ( $op eq 'cud-batchedit' ) { } } - $subscription->add_additional_fields($field_values, 'subscription'); + $subscription->add_additional_fields( $field_values, 'subscription' ); $subscription->store; } diff --git a/serials/subscription-bib-search.pl b/serials/subscription-bib-search.pl index c0f38193a6..973580ab6b 100755 --- a/serials/subscription-bib-search.pl +++ b/serials/subscription-bib-search.pl @@ -47,7 +47,7 @@ to multipage gestion. use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Koha qw( GetAuthorisedValues ); use C4::Auth qw( get_template_and_user ); use C4::Context; @@ -60,16 +60,15 @@ use Koha::SearchEngine; use Koha::SearchEngine::Search; my $input = CGI->new; -my $op = $input->param('op') || q{}; -my $dbh = C4::Context->dbh; +my $op = $input->param('op') || q{}; +my $dbh = C4::Context->dbh; my $startfrom = $input->param('startfrom'); $startfrom = 0 unless $startfrom; my ( $template, $loggedinuser, $cookie ); my $resultsperpage; -my $itype_or_itemtype = - ( C4::Context->preference("item-level_itypes") ) ? 'itype' : 'itemtype'; +my $itype_or_itemtype = ( C4::Context->preference("item-level_itypes") ) ? 'itype' : 'itemtype'; my $query = $input->param('q'); @@ -78,25 +77,25 @@ if ( $op eq "do_search" && $query ) { ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "serials/result.tt", - query => $input, - type => "intranet", - flagsrequired => { catalogue => 1, serials => '*' }, + template_name => "serials/result.tt", + query => $input, + type => "intranet", + flagsrequired => { catalogue => 1, serials => '*' }, } ); # add the limits if applicable my $itemtypelimit = $input->param('itemtypelimit'); my $ccodelimit = $input->param('ccodelimit'); - my $op = 'AND'; + my $op = 'AND'; $query .= " $op $itype_or_itemtype:$itemtypelimit" if $itemtypelimit; - $query .= " $op ccode:$ccodelimit" if $ccodelimit; + $query .= " $op ccode:$ccodelimit" if $ccodelimit; $resultsperpage = $input->param('resultsperpage'); $resultsperpage = 20 if ( !defined $resultsperpage ); - my $searcher = Koha::SearchEngine::Search->new({index => $Koha::SearchEngine::BIBLIOS_INDEX}); + my $searcher = Koha::SearchEngine::Search->new( { index => $Koha::SearchEngine::BIBLIOS_INDEX } ); my ( $error, $marcrecords, $total_hits ) = - $searcher->simple_search_compat( $query, $startfrom * $resultsperpage, $resultsperpage ); + $searcher->simple_search_compat( $query, $startfrom * $resultsperpage, $resultsperpage ); my $total = 0; if ( defined $marcrecords ) { $total = scalar @{$marcrecords}; @@ -113,20 +112,21 @@ if ( $op eq "do_search" && $query ) { for ( my $i = 0 ; $i < $total ; $i++ ) { my %resultsloop; my $marcrecord = C4::Search::new_record_from_zebra( 'biblioserver', $marcrecords->[$i] ); - my $biblio = TransformMarcToKoha({ record => $marcrecord }); + my $biblio = TransformMarcToKoha( { record => $marcrecord } ); #build the hash for the template. - $resultsloop{highlight} = ( $i % 2 ) ? (1) : (0); - $resultsloop{title} = $biblio->{'title'}; - $resultsloop{subtitle} = $biblio->{'subtitle'}; - $resultsloop{medium} = $biblio->{'medium'}; - $resultsloop{part_number} = $biblio->{'part_number'}; - $resultsloop{part_name} = $biblio->{'part_name'}; - $resultsloop{biblionumber} = $biblio->{'biblionumber'}; - $resultsloop{author} = $biblio->{'author'}; - $resultsloop{publishercode} = $biblio->{'publishercode'}; - $resultsloop{publicationyear} = $biblio->{'publicationyear'} ? $biblio->{'publicationyear'} : $biblio->{'copyrightdate'}; - $resultsloop{issn} = $biblio->{'issn'}; + $resultsloop{highlight} = ( $i % 2 ) ? (1) : (0); + $resultsloop{title} = $biblio->{'title'}; + $resultsloop{subtitle} = $biblio->{'subtitle'}; + $resultsloop{medium} = $biblio->{'medium'}; + $resultsloop{part_number} = $biblio->{'part_number'}; + $resultsloop{part_name} = $biblio->{'part_name'}; + $resultsloop{biblionumber} = $biblio->{'biblionumber'}; + $resultsloop{author} = $biblio->{'author'}; + $resultsloop{publishercode} = $biblio->{'publishercode'}; + $resultsloop{publicationyear} = + $biblio->{'publicationyear'} ? $biblio->{'publicationyear'} : $biblio->{'copyrightdate'}; + $resultsloop{issn} = $biblio->{'issn'}; push @results, \%resultsloop; } @@ -146,12 +146,12 @@ if ( $op eq "do_search" && $query ) { my $highlight = 0; ( $startfrom == ( $i - 1 ) ) && ( $highlight = 1 ); push @numbers, - { + { number => $i, highlight => $highlight, searchdata => \@results, startfrom => ( $i - 1 ) - }; + }; } } } @@ -162,8 +162,7 @@ if ( $op eq "do_search" && $query ) { if ( $total_hits < ( ( $startfrom + 1 ) * $resultsperpage ) ) { $to = $total; - } - else { + } else { $to = ( ( $startfrom + 1 ) * $resultsperpage ); } $template->param( @@ -184,24 +183,23 @@ if ( $op eq "do_search" && $query ) { else { ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "serials/subscription-bib-search.tt", - query => $input, - type => "intranet", - flagsrequired => { catalogue => 1, serials => '*' }, + template_name => "serials/subscription-bib-search.tt", + query => $input, + type => "intranet", + flagsrequired => { catalogue => 1, serials => '*' }, } ); # load the itemtypes my $itemtypes = { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search_with_localization->unblessed } }; my @itemtypesloop; + # FIXME This is uselessly complex, the iterator should be send to the template # FIXME The translated_description should be used foreach my $thisitemtype ( - sort { - $itemtypes->{$a}->{'description'} - cmp $itemtypes->{$b}->{'description'} - } keys %$itemtypes - ) + sort { $itemtypes->{$a}->{'description'} cmp $itemtypes->{$b}->{'description'} } + keys %$itemtypes + ) { my %row = ( code => $thisitemtype, @@ -213,8 +211,7 @@ else { # load Collection Codes my $authvalues = GetAuthorisedValues('CCODE'); my @ccodesloop; - for my $thisauthvalue ( sort { $a->{'lib'} cmp $b->{'lib'} } @$authvalues ) - { + for my $thisauthvalue ( sort { $a->{'lib'} cmp $b->{'lib'} } @$authvalues ) { my %row = ( code => $thisauthvalue->{'authorised_value'}, description => $thisauthvalue->{'lib'}, diff --git a/serials/subscription-detail.pl b/serials/subscription-detail.pl index 8140feb8c2..2562007fdd 100755 --- a/serials/subscription-detail.pl +++ b/serials/subscription-detail.pl @@ -16,9 +16,10 @@ # along with Koha; if not, see . use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Auth qw( get_template_and_user checkauth ); -use C4::Serials qw( CloseSubscription ReopenSubscription GetSubscription GetExpirationDate GetSerials HasSubscriptionStrictlyExpired CountIssues HasItems DelSubscription check_routing abouttoexpire can_edit_subscription ); +use C4::Serials + qw( CloseSubscription ReopenSubscription GetSubscription GetExpirationDate GetSerials HasSubscriptionStrictlyExpired CountIssues HasItems DelSubscription check_routing abouttoexpire can_edit_subscription ); use C4::Output qw( output_and_exit output_html_with_http_headers ); use C4::Context; use C4::Search qw( enabled_staff_search_views ); @@ -43,128 +44,137 @@ my $subscriptionid = $query->param('subscriptionid'); # Permission needed if it is a deletion (del) : delete_subscription # Permission needed otherwise : * -my $permission = ($op eq "cud-del") ? "delete_subscription" : "*"; +my $permission = ( $op eq "cud-del" ) ? "delete_subscription" : "*"; -my ($template, $loggedinuser, $cookie) -= get_template_and_user({template_name => "serials/subscription-detail.tt", - query => $query, - type => "intranet", - flagsrequired => {serials => $permission}, - }); +my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "serials/subscription-detail.tt", + query => $query, + type => "intranet", + flagsrequired => { serials => $permission }, + } +); my $subs = GetSubscription($subscriptionid); -output_and_exit( $query, $cookie, $template, 'unknown_subscription') +output_and_exit( $query, $cookie, $template, 'unknown_subscription' ) unless $subs; $subs->{enddate} ||= GetExpirationDate($subscriptionid); -my ($totalissues,@serialslist) = GetSerials($subscriptionid); -$totalissues-- if $totalissues; # the -1 is to have 0 if this is a new subscription (only 1 issue) +my ( $totalissues, @serialslist ) = GetSerials($subscriptionid); +$totalissues-- if $totalissues; # the -1 is to have 0 if this is a new subscription (only 1 issue) if ( $op eq "cud-close" ) { - C4::Serials::CloseSubscription( $subscriptionid ); + C4::Serials::CloseSubscription($subscriptionid); } elsif ( $op eq "cud-reopen" ) { - C4::Serials::ReopenSubscription( $subscriptionid ); + C4::Serials::ReopenSubscription($subscriptionid); } elsif ( $op eq "cud-del" ) { - if ($$subs{'cannotedit'}){ - carp "Attempt to delete subscription $subscriptionid by ".C4::Context->userenv->{'id'}." not allowed"; + if ( $$subs{'cannotedit'} ) { + carp "Attempt to delete subscription $subscriptionid by " . C4::Context->userenv->{'id'} . " not allowed"; print $query->redirect("/cgi-bin/koha/serials/subscription-detail.pl?subscriptionid=$subscriptionid"); exit; } # Asking for confirmation if the subscription has not strictly expired yet or if it has linked issues my $strictlyexpired = HasSubscriptionStrictlyExpired($subscriptionid); - my $linkedissues = CountIssues($subscriptionid); - my $countitems = HasItems($subscriptionid); - if ($strictlyexpired == 0 || $linkedissues > 0 || $countitems>0) { - $template->param(NEEDSCONFIRMATION => 1); - if ($strictlyexpired == 0) { $template->param("NOTEXPIRED" => 1); } - if ($linkedissues > 0) { $template->param("LINKEDISSUES" => 1); } - if ($countitems > 0) { $template->param("LINKEDITEMS" => 1); } + my $linkedissues = CountIssues($subscriptionid); + my $countitems = HasItems($subscriptionid); + if ( $strictlyexpired == 0 || $linkedissues > 0 || $countitems > 0 ) { + $template->param( NEEDSCONFIRMATION => 1 ); + if ( $strictlyexpired == 0 ) { $template->param( "NOTEXPIRED" => 1 ); } + if ( $linkedissues > 0 ) { $template->param( "LINKEDISSUES" => 1 ); } + if ( $countitems > 0 ) { $template->param( "LINKEDITEMS" => 1 ); } } else { $issueconfirmed = "1"; } + # If it's ok to delete the subscription, we do so - if ($issueconfirmed eq "1") { + if ( $issueconfirmed eq "1" ) { &DelSubscription($subscriptionid); print $query->redirect("/cgi-bin/koha/serials/serials-home.pl"); exit; } } elsif ( $op eq "share" ) { my $mana_language = $query->param('mana_language'); - my $result = Koha::SharedContent::send_entity($mana_language, $loggedinuser, $subscriptionid, 'subscription'); + my $result = Koha::SharedContent::send_entity( $mana_language, $loggedinuser, $subscriptionid, 'subscription' ); $template->param( mana_code => $result->{msg} ); $subs->{mana_id} = $result->{id}; } my $hasRouting = check_routing($subscriptionid); -(undef, $cookie, undef, undef) - = checkauth($query, 0, {catalogue => 1}, "intranet"); +( undef, $cookie, undef, undef ) = checkauth( $query, 0, { catalogue => 1 }, "intranet" ); # COMMENT hdl : IMHO, we should think about passing more and more data hash to template->param rather than duplicating code a new coding Guideline ? -for my $date ( qw(startdate enddate firstacquidate histstartdate histenddate) ) { +for my $date (qw(startdate enddate firstacquidate histstartdate histenddate)) { $subs->{$date} = output_pref( { str => $subs->{$date}, dateonly => 1 } ) if $subs->{$date}; } -my $av = Koha::AuthorisedValues->search({ category => 'LOC', authorised_value => $subs->{location} }); -$subs->{location} = $av->count ? $av->next->lib : ''; -$av = Koha::AuthorisedValues->search({ category => 'CCODE', authorised_value => $subs->{ccode} }); -$subs->{ccode} = $av->count ? $av->next->lib : ''; -$subs->{abouttoexpire} = abouttoexpire($subs->{subscriptionid}); -$template->param(%{ $subs }); -$template->param(biblionumber_for_new_subscription => $subs->{bibnum}); +my $av = Koha::AuthorisedValues->search( { category => 'LOC', authorised_value => $subs->{location} } ); +$subs->{location} = $av->count ? $av->next->lib : ''; +$av = Koha::AuthorisedValues->search( { category => 'CCODE', authorised_value => $subs->{ccode} } ); +$subs->{ccode} = $av->count ? $av->next->lib : ''; +$subs->{abouttoexpire} = abouttoexpire( $subs->{subscriptionid} ); +$template->param( %{$subs} ); +$template->param( biblionumber_for_new_subscription => $subs->{bibnum} ); my @irregular_issues = split /;/, $subs->{irregularity}; -my $frequency = C4::Serials::Frequency::GetSubscriptionFrequency($subs->{periodicity}); -my $numberpattern = C4::Serials::Numberpattern::GetSubscriptionNumberpattern($subs->{numberpattern}); +my $frequency = C4::Serials::Frequency::GetSubscriptionFrequency( $subs->{periodicity} ); +my $numberpattern = C4::Serials::Numberpattern::GetSubscriptionNumberpattern( $subs->{numberpattern} ); -my $subscription = Koha::Subscriptions->find( $subscriptionid ); +my $subscription = Koha::Subscriptions->find($subscriptionid); $template->param( available_additional_fields => Koha::AdditionalFields->search( { tablename => 'subscription' } ), - additional_field_values => $subscription->get_additional_field_values_for_template, + additional_field_values => $subscription->get_additional_field_values_for_template, ); # FIXME Do we want to hide canceled orders? -my $orders = Koha::Acquisition::Orders->search( { subscriptionid => $subscriptionid }, { order_by => [ { -desc => 'timestamp' }, \[ "field(orderstatus, 'ordered', 'partial', 'complete')" ] ] } ); +my $orders = Koha::Acquisition::Orders->search( + { subscriptionid => $subscriptionid }, + { order_by => [ { -desc => 'timestamp' }, \["field(orderstatus, 'ordered', 'partial', 'complete')"] ] } +); my $orders_grouped; while ( my $o = $orders->next ) { if ( $o->ordernumber == $o->parent_ordernumber ) { - $orders_grouped->{$o->parent_ordernumber}->{datereceived} = $o->datereceived; - $orders_grouped->{$o->parent_ordernumber}->{orderstatus} = $o->orderstatus; - $orders_grouped->{$o->parent_ordernumber}->{basket} = $o->basket; + $orders_grouped->{ $o->parent_ordernumber }->{datereceived} = $o->datereceived; + $orders_grouped->{ $o->parent_ordernumber }->{orderstatus} = $o->orderstatus; + $orders_grouped->{ $o->parent_ordernumber }->{basket} = $o->basket; } - $orders_grouped->{$o->parent_ordernumber}->{quantity} += $o->quantity; - $orders_grouped->{$o->parent_ordernumber}->{ecost_tax_excluded} += sprintf('%.2f', $o->ecost_tax_excluded * $o->quantity); - $orders_grouped->{$o->parent_ordernumber}->{ecost_tax_included} += sprintf('%.2f', $o->ecost_tax_included * $o->quantity); - $orders_grouped->{$o->parent_ordernumber}->{unitprice_tax_excluded} += sprintf('%.2f', $o->unitprice_tax_excluded * $o->quantity); - $orders_grouped->{$o->parent_ordernumber}->{unitprice_tax_included} += sprintf('%.2f', $o->unitprice_tax_included * $o->quantity); - push @{$orders_grouped->{$o->parent_ordernumber}->{orders}}, $o; + $orders_grouped->{ $o->parent_ordernumber }->{quantity} += $o->quantity; + $orders_grouped->{ $o->parent_ordernumber }->{ecost_tax_excluded} += + sprintf( '%.2f', $o->ecost_tax_excluded * $o->quantity ); + $orders_grouped->{ $o->parent_ordernumber }->{ecost_tax_included} += + sprintf( '%.2f', $o->ecost_tax_included * $o->quantity ); + $orders_grouped->{ $o->parent_ordernumber }->{unitprice_tax_excluded} += + sprintf( '%.2f', $o->unitprice_tax_excluded * $o->quantity ); + $orders_grouped->{ $o->parent_ordernumber }->{unitprice_tax_included} += + sprintf( '%.2f', $o->unitprice_tax_included * $o->quantity ); + push @{ $orders_grouped->{ $o->parent_ordernumber }->{orders} }, $o; } $template->param( - subscription => $subscription, - subscriptionid => $subscriptionid, - serialslist => \@serialslist, - hasRouting => $hasRouting, - routing => C4::Context->preference("RoutingSerials"), - totalissues => $totalissues, - cannotedit => (not C4::Serials::can_edit_subscription( $subs )), - frequency => $frequency, - numberpattern => $numberpattern, - has_X => ($numberpattern->{'numberingmethod'} =~ /{X}/) ? 1 : 0, - has_Y => ($numberpattern->{'numberingmethod'} =~ /{Y}/) ? 1 : 0, - has_Z => ($numberpattern->{'numberingmethod'} =~ /{Z}/) ? 1 : 0, - intranetstylesheet => C4::Context->preference('intranetstylesheet'), - intranetcolorstylesheet => C4::Context->preference('intranetcolorstylesheet'), - irregular_issues => scalar @irregular_issues, - orders_grouped => $orders_grouped, - (uc(C4::Context->preference("marcflavour"))) => 1, - mana_comments => $subs->{comments}, - print_routing_list_issue => scalar $query->param('print_routing_list_issue'), + subscription => $subscription, + subscriptionid => $subscriptionid, + serialslist => \@serialslist, + hasRouting => $hasRouting, + routing => C4::Context->preference("RoutingSerials"), + totalissues => $totalissues, + cannotedit => ( not C4::Serials::can_edit_subscription($subs) ), + frequency => $frequency, + numberpattern => $numberpattern, + has_X => ( $numberpattern->{'numberingmethod'} =~ /{X}/ ) ? 1 : 0, + has_Y => ( $numberpattern->{'numberingmethod'} =~ /{Y}/ ) ? 1 : 0, + has_Z => ( $numberpattern->{'numberingmethod'} =~ /{Z}/ ) ? 1 : 0, + intranetstylesheet => C4::Context->preference('intranetstylesheet'), + intranetcolorstylesheet => C4::Context->preference('intranetcolorstylesheet'), + irregular_issues => scalar @irregular_issues, + orders_grouped => $orders_grouped, + ( uc( C4::Context->preference("marcflavour") ) ) => 1, + mana_comments => $subs->{comments}, + print_routing_list_issue => scalar $query->param('print_routing_list_issue'), ); output_html_with_http_headers $query, $cookie, $template->output; diff --git a/serials/subscription-frequencies.pl b/serials/subscription-frequencies.pl index 8378f3be81..19a53010ce 100755 --- a/serials/subscription-frequencies.pl +++ b/serials/subscription-frequencies.pl @@ -31,35 +31,37 @@ use Modern::Perl; use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); -use C4::Output qw( output_html_with_http_headers ); +use C4::Auth qw( get_template_and_user ); +use C4::Output qw( output_html_with_http_headers ); use C4::Serials qw( GetSubscription ModSubscription DelSubscription ); use C4::Serials::Frequency; my $input = CGI->new; -my ($template, $loggedinuser, $cookie, $flags) = get_template_and_user( { - template_name => 'serials/subscription-frequencies.tt', - query => $input, - type => 'intranet', - flagsrequired => { 'serials' => 1 }, -} ); +my ( $template, $loggedinuser, $cookie, $flags ) = get_template_and_user( + { + template_name => 'serials/subscription-frequencies.tt', + query => $input, + type => 'intranet', + flagsrequired => { 'serials' => 1 }, + } +); my $op = $input->param('op'); -if($op && ($op eq 'new' || $op eq 'modify')) { +if ( $op && ( $op eq 'new' || $op eq 'modify' ) ) { my @units_loop; - push @units_loop, {val => $_} for (qw/ day week month year /); + push @units_loop, { val => $_ } for (qw/ day week month year /); - if($op eq 'modify') { + if ( $op eq 'modify' ) { my $frequencyid = $input->param('frequencyid'); - my $frequency = GetSubscriptionFrequency($frequencyid); + my $frequency = GetSubscriptionFrequency($frequencyid); foreach (@units_loop) { - if($frequency->{unit} and $_->{val} eq $frequency->{unit}) { + if ( $frequency->{unit} and $_->{val} eq $frequency->{unit} ) { $_->{selected} = 1; last; } } - $template->param( %$frequency ); + $template->param(%$frequency); } $template->param( @@ -70,7 +72,7 @@ if($op && ($op eq 'new' || $op eq 'modify')) { exit; } -if($op && ($op eq 'cud-savenew' || $op eq 'cud-savemod')) { +if ( $op && ( $op eq 'cud-savenew' || $op eq 'cud-savemod' ) ) { my $frequency; foreach (qw/ description unit issuesperunit unitsperissue displayorder /) { $frequency->{$_} = $input->param($_); @@ -83,13 +85,13 @@ if($op && ($op eq 'cud-savenew' || $op eq 'cud-savemod')) { $frequency->{issuesperunit} = 1 if $frequency->{issuesperunit} < 1; $frequency->{unitsperissue} = 1 if $frequency->{issuesperunit} != 1; - if($op eq 'cud-savemod') { + if ( $op eq 'cud-savemod' ) { $frequency->{id} = $input->param('id'); ModSubscriptionFrequency($frequency); } else { AddSubscriptionFrequency($frequency); } -} elsif($op && $op eq 'cud-del') { +} elsif ( $op && $op eq 'cud-del' ) { my $frequencyid = $input->param('frequencyid'); if ($frequencyid) { @@ -100,8 +102,8 @@ if($op && ($op eq 'cud-savenew' || $op eq 'cud-savemod')) { my @subs = GetSubscriptionsWithFrequency($frequencyid); if (@subs) { $template->param( - frequencyid => $frequencyid, - still_used => 1, + frequencyid => $frequencyid, + still_used => 1, subscriptions => \@subs ); } else { @@ -111,10 +113,9 @@ if($op && ($op eq 'cud-savenew' || $op eq 'cud-savemod')) { } } - my @frequencies = GetSubscriptionFrequencies(); -$template->param(frequencies_loop => \@frequencies); -$template->param($op => 1) if $op; +$template->param( frequencies_loop => \@frequencies ); +$template->param( $op => 1 ) if $op; output_html_with_http_headers $input, $cookie, $template->output; diff --git a/serials/subscription-frequency.pl b/serials/subscription-frequency.pl index 4d5208e898..288bf8c5f2 100755 --- a/serials/subscription-frequency.pl +++ b/serials/subscription-frequency.pl @@ -21,16 +21,16 @@ use Modern::Perl; use CGI qw ( -utf8 ); use C4::Context; use C4::Serials::Frequency qw( GetSubscriptionFrequency ); -use C4::Auth qw( check_cookie_auth ); -use JSON qw( to_json ); +use C4::Auth qw( check_cookie_auth ); +use JSON qw( to_json ); -my $input=CGI->new; -my $frqid=$input->param("frequency_id"); -my ($auth_status) = check_cookie_auth($input->cookie('CGISESSID'), { serials => '*' }); -if ($auth_status ne "ok") { +my $input = CGI->new; +my $frqid = $input->param("frequency_id"); +my ($auth_status) = check_cookie_auth( $input->cookie('CGISESSID'), { serials => '*' } ); +if ( $auth_status ne "ok" ) { exit 0; } -my $frequencyrecord=GetSubscriptionFrequency($frqid); +my $frequencyrecord = GetSubscriptionFrequency($frqid); binmode STDOUT, ":encoding(UTF-8)"; -print $input->header(-type => 'text/plain', -charset => 'UTF-8'); -print to_json( $frequencyrecord ); +print $input->header( -type => 'text/plain', -charset => 'UTF-8' ); +print to_json($frequencyrecord); diff --git a/serials/subscription-history.pl b/serials/subscription-history.pl index 101ef6f07e..74da961a3f 100755 --- a/serials/subscription-history.pl +++ b/serials/subscription-history.pl @@ -29,8 +29,8 @@ Modify subscription history use Modern::Perl; -use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use C4::Serials qw( ModSubscriptionHistory ModSubscription GetSubscriptionHistoryFromSubscriptionId GetSubscription ); @@ -38,33 +38,38 @@ use Koha::Biblios; use Koha::DateUtils qw( output_pref ); my $input = CGI->new; -my ($template, $loggedinuser, $cookie, $flags) = get_template_and_user( { - template_name => 'serials/subscription-history.tt', - query => $input, - type => 'intranet', - flagsrequired => { 'serials' => 'edit_subscription' }, -} ); +my ( $template, $loggedinuser, $cookie, $flags ) = get_template_and_user( + { + template_name => 'serials/subscription-history.tt', + query => $input, + type => 'intranet', + flagsrequired => { 'serials' => 'edit_subscription' }, + } +); -my $subscriptionid = $input->param('subscriptionid'); -my $op = $input->param('op'); +my $subscriptionid = $input->param('subscriptionid'); +my $op = $input->param('op'); -if(!defined $subscriptionid || $subscriptionid eq '') { +if ( !defined $subscriptionid || $subscriptionid eq '' ) { print $input->redirect('/cgi-bin/koha/serials/serials-home.pl'); exit; } -if($op && $op eq 'cud-mod') { - my $histstartdate = $input->param('histstartdate'); - my $histenddate = $input->param('histenddate'); - my $receivedlist = $input->param('receivedlist'); - my $missinglist = $input->param('missinglist'); - my $opacnote = $input->param('opacnote'); - my $librariannote = $input->param('librariannote'); +if ( $op && $op eq 'cud-mod' ) { + my $histstartdate = $input->param('histstartdate'); + my $histenddate = $input->param('histenddate'); + my $receivedlist = $input->param('receivedlist'); + my $missinglist = $input->param('missinglist'); + my $opacnote = $input->param('opacnote'); + my $librariannote = $input->param('librariannote'); $histstartdate = output_pref( { str => $histstartdate, dateonly => 1, dateformat => 'iso' } ); $histenddate = output_pref( { str => $histenddate, dateonly => 1, dateformat => 'iso' } ); - ModSubscriptionHistory( $subscriptionid, $histstartdate, $histenddate, $receivedlist, $missinglist, $opacnote, $librariannote ); + ModSubscriptionHistory( + $subscriptionid, $histstartdate, $histenddate, $receivedlist, $missinglist, $opacnote, + $librariannote + ); print $input->redirect("/cgi-bin/koha/serials/subscription-detail.pl?subscriptionid=$subscriptionid"); exit; @@ -73,14 +78,14 @@ if($op && $op eq 'cud-mod') { my $biblio = Koha::Biblios->find( $history->{biblionumber} ); $template->param( - subscriptionid => $subscriptionid, - title => $biblio->title, - histstartdate => $history->{'histstartdate'}, - histenddate => $history->{'histenddate'}, - receivedlist => $history->{'recievedlist'}, - missinglist => $history->{'missinglist'}, - opacnote => $history->{'opacnote'}, - librariannote => $history->{'librariannote'}, + subscriptionid => $subscriptionid, + title => $biblio->title, + histstartdate => $history->{'histstartdate'}, + histenddate => $history->{'histenddate'}, + receivedlist => $history->{'recievedlist'}, + missinglist => $history->{'missinglist'}, + opacnote => $history->{'opacnote'}, + librariannote => $history->{'librariannote'}, ); output_html_with_http_headers $input, $cookie, $template->output; diff --git a/serials/subscription-numberpattern.pl b/serials/subscription-numberpattern.pl index 645f6af04d..54ed29ef3b 100755 --- a/serials/subscription-numberpattern.pl +++ b/serials/subscription-numberpattern.pl @@ -18,23 +18,23 @@ # along with Koha; if not, see . use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Serials::Numberpattern qw( GetSubscriptionNumberpattern ); -use C4::Auth qw( check_cookie_auth ); -use JSON qw( to_json ); +use C4::Auth qw( check_cookie_auth ); +use JSON qw( to_json ); -my $input=CGI->new; +my $input = CGI->new; -my ($auth_status) = check_cookie_auth($input->cookie('CGISESSID'), { serials => '*' }); -if ($auth_status ne "ok") { - print $input->header(-type => 'text/plain', -status => '403 Forbidden'); +my ($auth_status) = check_cookie_auth( $input->cookie('CGISESSID'), { serials => '*' } ); +if ( $auth_status ne "ok" ) { + print $input->header( -type => 'text/plain', -status => '403 Forbidden' ); exit 0; } -my $numpatternid=$input->param("numberpattern_id"); +my $numpatternid = $input->param("numberpattern_id"); -my $numberpatternrecord=GetSubscriptionNumberpattern($numpatternid); +my $numberpatternrecord = GetSubscriptionNumberpattern($numpatternid); binmode STDOUT, ":encoding(UTF-8)"; -print $input->header(-type => 'text/plain', -charset => 'UTF-8'); -print to_json( $numberpatternrecord ); +print $input->header( -type => 'text/plain', -charset => 'UTF-8' ); +print to_json($numberpatternrecord); diff --git a/serials/subscription-numberpatterns.pl b/serials/subscription-numberpatterns.pl index 4b931edae8..9211240650 100755 --- a/serials/subscription-numberpatterns.pl +++ b/serials/subscription-numberpatterns.pl @@ -30,8 +30,8 @@ Manage numbering patterns use Modern::Perl; use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); -use C4::Output qw( output_html_with_http_headers ); +use C4::Auth qw( get_template_and_user ); +use C4::Output qw( output_html_with_http_headers ); use C4::Serials::Numberpattern qw( AddSubscriptionNumberpattern DelSubscriptionNumberpattern @@ -44,68 +44,70 @@ use C4::Serials::Numberpattern qw( use C4::Serials::Frequency qw( GetSubscriptionFrequencies ); my @NUMBERPATTERN_FIELDS = qw/ - label description numberingmethod displayorder - label1 label2 label3 add1 add2 add3 every1 every2 every3 - setto1 setto2 setto3 whenmorethan1 whenmorethan2 whenmorethan3 - numbering1 numbering2 numbering3 /; + label description numberingmethod displayorder + label1 label2 label3 add1 add2 add3 every1 every2 every3 + setto1 setto2 setto3 whenmorethan1 whenmorethan2 whenmorethan3 + numbering1 numbering2 numbering3 /; my $input = CGI->new; -my ($template, $loggedinuser, $cookie, $flags) = get_template_and_user( { - template_name => 'serials/subscription-numberpatterns.tt', - query => $input, - type => 'intranet', - flagsrequired => { 'serials' => "*" } -} ); +my ( $template, $loggedinuser, $cookie, $flags ) = get_template_and_user( + { + template_name => 'serials/subscription-numberpatterns.tt', + query => $input, + type => 'intranet', + flagsrequired => { 'serials' => "*" } + } +); my $op = $input->param('op'); -if($op && $op eq 'cud-savenew') { +if ( $op && $op eq 'cud-savenew' ) { my $label = $input->param('label'); my $numberpattern; - foreach(@NUMBERPATTERN_FIELDS) { + foreach (@NUMBERPATTERN_FIELDS) { $numberpattern->{$_} = $input->param($_); - if(defined $numberpattern->{$_} and $numberpattern->{$_} eq '') { + if ( defined $numberpattern->{$_} and $numberpattern->{$_} eq '' ) { $numberpattern->{$_} = undef; } } my $numberpattern2 = GetSubscriptionNumberpatternByName($label); - if(!defined $numberpattern2) { + if ( !defined $numberpattern2 ) { AddSubscriptionNumberpattern($numberpattern); } else { $op = 'new'; - $template->param(error_existing_numberpattern => 1); + $template->param( error_existing_numberpattern => 1 ); $template->param(%$numberpattern); } -} elsif ($op && $op eq 'cud-savemod') { - my $id = $input->param('id'); - my $label = $input->param('label'); +} elsif ( $op && $op eq 'cud-savemod' ) { + my $id = $input->param('id'); + my $label = $input->param('label'); my $numberpattern = GetSubscriptionNumberpattern($id); - my $mod_ok = 1; - if($numberpattern->{'label'} ne $label) { + my $mod_ok = 1; + if ( $numberpattern->{'label'} ne $label ) { my $numberpattern2 = GetSubscriptionNumberpatternByName($label); - if(defined $numberpattern2 && $id != $numberpattern2->{'id'}) { + if ( defined $numberpattern2 && $id != $numberpattern2->{'id'} ) { $mod_ok = 0; } } - if($mod_ok) { - foreach(@NUMBERPATTERN_FIELDS) { + if ($mod_ok) { + foreach (@NUMBERPATTERN_FIELDS) { $numberpattern->{$_} = $input->param($_) || undef; - if(defined $numberpattern->{$_} and $numberpattern->{$_} eq '') { + if ( defined $numberpattern->{$_} and $numberpattern->{$_} eq '' ) { $numberpattern->{$_} = undef; } } ModSubscriptionNumberpattern($numberpattern); } else { $op = 'cud-modify'; - $template->param(error_existing_numberpattern => 1); + $template->param( error_existing_numberpattern => 1 ); } } -if($op && ($op eq 'new' || $op eq 'modify')) { - if($op eq 'modify') { +if ( $op && ( $op eq 'new' || $op eq 'modify' ) ) { + if ( $op eq 'modify' ) { my $id = $input->param('id'); - if(defined $id) { + if ( defined $id ) { my $numberpattern = GetSubscriptionNumberpattern($id); $template->param(%$numberpattern); } else { @@ -113,23 +115,25 @@ if($op && ($op eq 'new' || $op eq 'modify')) { } } my @frequencies = GetSubscriptionFrequencies(); - my $languages = [ map { - { - language => $_->{iso639_2_code}, - description => $_->{language_description} || $_->{language} - } - } @{ C4::Languages::getAllLanguages() } ]; + my $languages = [ + map { + { + language => $_->{iso639_2_code}, + description => $_->{language_description} || $_->{language} + } + } @{ C4::Languages::getAllLanguages() } + ]; $template->param( - $op => 1, + $op => 1, frequencies_loop => \@frequencies, - locales => $languages, + locales => $languages, ); output_html_with_http_headers $input, $cookie, $template->output; exit; } -if($op && $op eq 'cud-del') { +if ( $op && $op eq 'cud-del' ) { my $id = $input->param('id'); if ($id) { my $confirm = $input->param('confirm'); @@ -139,8 +143,8 @@ if($op && $op eq 'cud-del') { my @subs = GetSubscriptionsWithNumberpattern($id); if (@subs) { $template->param( - id => $id, - still_used => 1, + id => $id, + still_used => 1, subscriptions => \@subs ); } else { diff --git a/serials/subscription-renew.pl b/serials/subscription-renew.pl index 982cb9dd4d..a4bb787ac2 100755 --- a/serials/subscription-renew.pl +++ b/serials/subscription-renew.pl @@ -17,7 +17,6 @@ # You should have received a copy of the GNU General Public License # along with Koha; if not, see . - =head1 NAME subscription-renew.pl @@ -45,48 +44,50 @@ Id of the subscription this script has to renew use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use Carp qw( carp ); use C4::Koha; use C4::Auth qw( get_template_and_user ); use C4::Context; -use C4::Auth qw( get_template_and_user ); -use C4::Output qw( output_and_exit output_html_with_http_headers ); -use C4::Serials qw( GetSubscription GetSubscriptionLength NewSubscription ReNewSubscription ); +use C4::Auth qw( get_template_and_user ); +use C4::Output qw( output_and_exit output_html_with_http_headers ); +use C4::Serials qw( GetSubscription GetSubscriptionLength NewSubscription ReNewSubscription ); use Koha::DateUtils qw( dt_from_string output_pref ); my $query = CGI->new; my $dbh = C4::Context->dbh; -my $op = $query->param('op') || 'display'; +my $op = $query->param('op') || 'display'; my @subscriptionids = $query->multi_param('subscriptionid'); -my $branchcode = $query->param('branchcode'); -my $sublength = $query->param('sublength'); -my $subtype = $query->param('subtype'); -my ($numberlength, $weeklength, $monthlength); +my $branchcode = $query->param('branchcode'); +my $sublength = $query->param('sublength'); +my $subtype = $query->param('subtype'); +my ( $numberlength, $weeklength, $monthlength ); my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "serials/subscription-renew.tt", - query => $query, - type => "intranet", - flagsrequired => { serials => 'renew_subscription' }, + template_name => "serials/subscription-renew.tt", + query => $query, + type => "intranet", + flagsrequired => { serials => 'renew_subscription' }, } ); if ( $op eq "cud-renew" ) { + # Do not use this script with op=renew and @subscriptionids > 1! my $subscriptionid = $subscriptionids[0]; - # Make sure the subscription exists - my $subscription = GetSubscription( $subscriptionid ); - output_and_exit( $query, $cookie, $template, 'unknown_subscription') unless $subscription; - if ($subscription->{cannotedit}){ - carp "Attempt to renew subscription $subscriptionid by ".C4::Context->userenv->{'id'}." not allowed"; - print $query->redirect("/cgi-bin/koha/serials/subscription-detail.pl?subscriptionid=$subscriptionid"); + # Make sure the subscription exists + my $subscription = GetSubscription($subscriptionid); + output_and_exit( $query, $cookie, $template, 'unknown_subscription' ) unless $subscription; + + if ( $subscription->{cannotedit} ) { + carp "Attempt to renew subscription $subscriptionid by " . C4::Context->userenv->{'id'} . " not allowed"; + print $query->redirect("/cgi-bin/koha/serials/subscription-detail.pl?subscriptionid=$subscriptionid"); } my $startdate = output_pref( { str => scalar $query->param('startdate'), dateonly => 1, dateformat => 'iso' } ); - ($numberlength, $weeklength, $monthlength) = GetSubscriptionLength( $subtype, $sublength ); + ( $numberlength, $weeklength, $monthlength ) = GetSubscriptionLength( $subtype, $sublength ); ReNewSubscription( { subscriptionid => $subscriptionid, @@ -100,8 +101,8 @@ if ( $op eq "cud-renew" ) { } ); } elsif ( $op eq 'cud-multi_renew' ) { - for my $subscriptionid ( @subscriptionids ) { - my $subscription = GetSubscription( $subscriptionid ); + for my $subscriptionid (@subscriptionids) { + my $subscription = GetSubscription($subscriptionid); next unless $subscription; next if $subscription->{cannotedit}; ReNewSubscription( @@ -115,11 +116,10 @@ if ( $op eq "cud-renew" ) { } ); } -} -elsif ( $op eq 'multi_renew' ) { +} elsif ( $op eq 'multi_renew' ) { my @subscriptions; - for my $subscriptionid ( @subscriptionids ) { - my $subscription = GetSubscription( $subscriptionid ); + for my $subscriptionid (@subscriptionids) { + my $subscription = GetSubscription($subscriptionid); next unless $subscription; next if $subscription->{cannotedit}; push @subscriptions, $subscription; @@ -128,22 +128,21 @@ elsif ( $op eq 'multi_renew' ) { $template->param( subscriptions => \@subscriptions, ); -} -else { +} else { my $subscriptionid = $subscriptionids[0]; - my $subscription = GetSubscription($subscriptionid); - output_and_exit( $query, $cookie, $template, 'unknown_subscription') unless $subscription; - if ($subscription->{'cannotedit'}){ - carp "Attempt to renew subscription $subscriptionid by ".C4::Context->userenv->{'id'}." not allowed"; - print $query->redirect("/cgi-bin/koha/serials/subscription-detail.pl?subscriptionid=$subscriptionid"); + my $subscription = GetSubscription($subscriptionid); + output_and_exit( $query, $cookie, $template, 'unknown_subscription' ) unless $subscription; + if ( $subscription->{'cannotedit'} ) { + carp "Attempt to renew subscription $subscriptionid by " . C4::Context->userenv->{'id'} . " not allowed"; + print $query->redirect("/cgi-bin/koha/serials/subscription-detail.pl?subscriptionid=$subscriptionid"); } my $newstartdate = output_pref( { str => $subscription->{enddate}, dateonly => 1 } ) or output_pref( { dt => dt_from_string, dateonly => 1 } ); $template->param( - startdate => $newstartdate, - subscription => $subscription, + startdate => $newstartdate, + subscription => $subscription, ); } diff --git a/serials/viewalerts.pl b/serials/viewalerts.pl index bb356c6331..3c5938704c 100755 --- a/serials/viewalerts.pl +++ b/serials/viewalerts.pl @@ -1,6 +1,5 @@ #!/usr/bin/perl - # Copyright 2000-2002 Katipo Communications # # This file is part of Koha. @@ -19,7 +18,7 @@ # along with Koha; if not, see . use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Auth qw( get_template_and_user ); use C4::Context; use C4::Output qw( output_html_with_http_headers ); @@ -28,16 +27,19 @@ use Koha::Subscriptions; my $input = CGI->new; -my ($template, $loggedinuser, $cookie) - = get_template_and_user({template_name => 'serials/viewalerts.tt', - query => $input, - type => "intranet", - flagsrequired => {serials => '*'}, - }); +my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => 'serials/viewalerts.tt', + query => $input, + type => "intranet", + flagsrequired => { serials => '*' }, + } +); my $subscriptionid = $input->param('subscriptionid'); -my $subscription = Koha::Subscriptions->find( $subscriptionid ); +my $subscription = Koha::Subscriptions->find($subscriptionid); + # FIXME raise a message if subscription does not exist (easy with 18403) my $subscribers = $subscription->subscribers; diff --git a/services/itemrecorddisplay.pl b/services/itemrecorddisplay.pl index f22faca846..ecdfba3b18 100755 --- a/services/itemrecorddisplay.pl +++ b/services/itemrecorddisplay.pl @@ -29,26 +29,28 @@ It uses PrepareItemrecordDisplay use Modern::Perl; -use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); -use C4::Items qw( PrepareItemrecordDisplay ); +use C4::Items qw( PrepareItemrecordDisplay ); my $input = CGI->new; -my ($template, $loggedinuser, $cookie, $flags) = get_template_and_user( { - template_name => 'services/itemrecorddisplay.tt', - query => $input, - type => 'intranet', - flagsrequired => {acquisition => '*'}, -} ); +my ( $template, $loggedinuser, $cookie, $flags ) = get_template_and_user( + { + template_name => 'services/itemrecorddisplay.tt', + query => $input, + type => 'intranet', + flagsrequired => { acquisition => '*' }, + } +); -my $biblionumber = $input->param('biblionumber') || ''; -my $itemnumber = $input->param('itemnumber') || ''; +my $biblionumber = $input->param('biblionumber') || ''; +my $itemnumber = $input->param('itemnumber') || ''; my $frameworkcode = $input->param('frameworkcode') || ''; -my $result = PrepareItemrecordDisplay($biblionumber, $itemnumber, undef, $frameworkcode); -unless($result) { - $result = PrepareItemrecordDisplay($biblionumber, $itemnumber, undef, ''); +my $result = PrepareItemrecordDisplay( $biblionumber, $itemnumber, undef, $frameworkcode ); +unless ($result) { + $result = PrepareItemrecordDisplay( $biblionumber, $itemnumber, undef, '' ); } $template->param(%$result); diff --git a/suggestion/suggestion.pl b/suggestion/suggestion.pl index 83ec65b230..362cac0a0e 100755 --- a/suggestion/suggestion.pl +++ b/suggestion/suggestion.pl @@ -19,13 +19,13 @@ use Modern::Perl; require Exporter; -use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers output_and_exit_if_error ); use C4::Suggestions; -use C4::Koha qw( GetAuthorisedValues ); +use C4::Koha qw( GetAuthorisedValues ); use C4::Budgets qw( GetBudget GetBudgets GetBudgetHierarchy CanUserUseBudget ); -use C4::Search qw( FindDuplicate GetDistinctValues ); +use C4::Search qw( FindDuplicate GetDistinctValues ); use C4::Members; use Koha::DateUtils qw( dt_from_string ); use Koha::AuthorisedValues; @@ -37,76 +37,81 @@ use Koha::Token; use URI::Escape qw( uri_escape ); -sub Init{ - my $suggestion= shift @_; +sub Init { + my $suggestion = shift @_; + # "Managed by" is used only when a suggestion is being edited (not when created) - if ($suggestion->{'suggesteddate'} eq "") { + if ( $suggestion->{'suggesteddate'} eq "" ) { + # new suggestion $suggestion->{suggesteddate} = dt_from_string; - $suggestion->{'suggestedby'} = C4::Context->userenv->{"number"} unless ($suggestion->{'suggestedby'}); - } - else { + $suggestion->{'suggestedby'} = C4::Context->userenv->{"number"} unless ( $suggestion->{'suggestedby'} ); + } else { + # editing of an existing suggestion $suggestion->{manageddate} = dt_from_string; - $suggestion->{'managedby'} = C4::Context->userenv->{"number"} unless ($suggestion->{'managedby'}); + $suggestion->{'managedby'} = C4::Context->userenv->{"number"} unless ( $suggestion->{'managedby'} ); } - $suggestion->{'branchcode'}=C4::Context->userenv->{"branch"} unless ($suggestion->{'branchcode'}); + $suggestion->{'branchcode'} = C4::Context->userenv->{"branch"} unless ( $suggestion->{'branchcode'} ); } -sub GetCriteriumDesc{ - my ($criteriumvalue,$displayby)=@_; - if ($displayby =~ /status/i) { +sub GetCriteriumDesc { + my ( $criteriumvalue, $displayby ) = @_; + if ( $displayby =~ /status/i ) { unless ( grep { /$criteriumvalue/ } qw(ASKED ACCEPTED REJECTED CHECKED ORDERED AVAILABLE) ) { - my $av = Koha::AuthorisedValues->search({ category => 'SUGGEST_STATUS', authorised_value => $criteriumvalue }); + my $av = + Koha::AuthorisedValues->search( { category => 'SUGGEST_STATUS', authorised_value => $criteriumvalue } ); return $av->count ? $av->next->lib : 'Unknown'; } - return ($criteriumvalue eq 'ASKED'?"Pending":ucfirst(lc( $criteriumvalue))) if ($displayby =~/status/i); + return ( $criteriumvalue eq 'ASKED' ? "Pending" : ucfirst( lc($criteriumvalue) ) ) + if ( $displayby =~ /status/i ); } if ( $displayby =~ /branchcode/ ) { return $criteriumvalue ? Koha::Libraries->find($criteriumvalue)->branchname : "__ANY__"; } if ( $displayby =~ /itemtype/ ) { - my $av = Koha::AuthorisedValues->search({ category => 'SUGGEST_FORMAT', authorised_value => $criteriumvalue }); + my $av = + Koha::AuthorisedValues->search( { category => 'SUGGEST_FORMAT', authorised_value => $criteriumvalue } ); return $av->count ? $av->next->lib : 'Unknown'; } - if ($displayby =~/suggestedby/||$displayby =~/managedby/||$displayby =~/acceptedby/){ - my $patron = Koha::Patrons->find( $criteriumvalue ); + if ( $displayby =~ /suggestedby/ || $displayby =~ /managedby/ || $displayby =~ /acceptedby/ ) { + my $patron = Koha::Patrons->find($criteriumvalue); return "" unless $patron; return $patron->surname . ", " . $patron->firstname; } - if ( $displayby =~ /budgetid/) { + if ( $displayby =~ /budgetid/ ) { my $budget = GetBudget($criteriumvalue); return "" unless $budget; return $$budget{budget_name}; } } -my $input = CGI->new; -my $redirect = $input->param('redirect'); -my $suggestedbyme = (defined $input->param('suggestedbyme')? $input->param('suggestedbyme'):1); -my $op = $input->param('op')||'else'; -my @editsuggestions = $input->multi_param('suggestionid'); -my $suggestedby = $input->param('suggestedby'); +my $input = CGI->new; +my $redirect = $input->param('redirect'); +my $suggestedbyme = ( defined $input->param('suggestedbyme') ? $input->param('suggestedbyme') : 1 ); +my $op = $input->param('op') || 'else'; +my @editsuggestions = $input->multi_param('suggestionid'); +my $suggestedby = $input->param('suggestedby'); my $returnsuggestedby = $input->param('returnsuggestedby'); -my $returnsuggested = $input->param('returnsuggested'); -my $managedby = $input->param('managedby'); -my $displayby = $input->param('displayby') || ''; -my $tabcode = $input->param('tabcode'); -my $save_confirmed = $input->param('save_confirmed') || 0; -my $notify = $input->param('notify'); -my $filter_archived = $input->param('filter_archived') || 0; -my $new_itemtype = $input->param('suggestion_itemtype'); -my $sugg_managedby = $input->param('suggestion_managedby'); +my $returnsuggested = $input->param('returnsuggested'); +my $managedby = $input->param('managedby'); +my $displayby = $input->param('displayby') || ''; +my $tabcode = $input->param('tabcode'); +my $save_confirmed = $input->param('save_confirmed') || 0; +my $notify = $input->param('notify'); +my $filter_archived = $input->param('filter_archived') || 0; +my $new_itemtype = $input->param('suggestion_itemtype'); +my $sugg_managedby = $input->param('suggestion_managedby'); -my $reasonsloop = GetAuthorisedValues("SUGGEST"); +my $reasonsloop = GetAuthorisedValues("SUGGEST"); -my $suggestion_ref = { $input->Vars }; +my $suggestion_ref = { $input->Vars }; delete $suggestion_ref->{$_} for qw(csrf_token suggestion_itemtype suggestion_managedby table_1_length); # get only the columns of Suggestion -my $schema = Koha::Database->new()->schema; -my $columns = ' '.join(' ', $schema->source('Suggestion')->columns).' '; -my $suggestion_only = { map { $columns =~ / $_ / ? ($_ => $suggestion_ref->{$_}) : () } keys %$suggestion_ref }; +my $schema = Koha::Database->new()->schema; +my $columns = ' ' . join( ' ', $schema->source('Suggestion')->columns ) . ' '; +my $suggestion_only = { map { $columns =~ / $_ / ? ( $_ => $suggestion_ref->{$_} ) : () } keys %$suggestion_ref }; $suggestion_only->{STATUS} = $suggestion_ref->{STATUS}; delete $$suggestion_ref{$_} @@ -118,7 +123,7 @@ foreach my $key ( keys %$suggestion_ref ) { delete $suggestion_ref->{$key} if $key =~ m{^DataTables_acqui_suggestions_suggestions}; } delete $suggestion_only->{branchcode} if $suggestion_only->{branchcode} eq '__ANY__'; -delete $suggestion_only->{budgetid} if $suggestion_only->{budgetid} eq '__ANY__'; +delete $suggestion_only->{budgetid} if $suggestion_only->{budgetid} eq '__ANY__'; unless ( $op eq 'cud-save' ) { while ( my ( $k, $v ) = each %$suggestion_only ) { @@ -138,7 +143,7 @@ my ( $template, $borrowernumber, $cookie, $userflags ) = get_template_and_user( my $librarian = Koha::Patrons->find($borrowernumber); $borrowernumber = $input->param('borrowernumber') if ( $input->param('borrowernumber') ); -$template->param('borrowernumber' => $borrowernumber); +$template->param( 'borrowernumber' => $borrowernumber ); my $branchfilter = $input->param('branchcode') || C4::Context->userenv->{'branch'}; ######################################### @@ -147,19 +152,21 @@ my $branchfilter = $input->param('branchcode') || C4::Context->userenv->{'branch my @messages; if ( $op =~ /cud-save/ ) { - output_and_exit_if_error($input, $cookie, $template, { check => 'csrf_token' }); + output_and_exit_if_error( $input, $cookie, $template, { check => 'csrf_token' } ); my @messages; - my $biblio = MarcRecordFromNewSuggestion({ - title => $suggestion_only->{title}, - author => $suggestion_only->{author}, + my $biblio = MarcRecordFromNewSuggestion( + { + title => $suggestion_only->{title}, + author => $suggestion_only->{author}, itemtype => $suggestion_only->{itemtype}, - isbn => $suggestion_only->{isbn}, - }); + isbn => $suggestion_only->{isbn}, + } + ); my $manager = Koha::Patrons->find( $suggestion_only->{managedby} ); - if ( $manager && not $manager->has_permission({suggestions => 'suggestions_manage'})) { + if ( $manager && not $manager->has_permission( { suggestions => 'suggestions_manage' } ) ) { push @messages, { type => 'error', code => 'manager_not_enough_permissions' }; $template->param( messages => \@messages, @@ -168,21 +175,24 @@ if ( $op =~ /cud-save/ ) { delete $suggestion_ref->{manageddate}; delete $suggestion_ref->{managedby}; Init($suggestion_ref); - } - elsif ( !$suggestion_only->{suggestionid} && ( my ($duplicatebiblionumber, $duplicatetitle) = FindDuplicate($biblio) ) && !$save_confirmed ) { - push @messages, { type => 'error', code => 'biblio_exists', id => $duplicatebiblionumber, title => $duplicatetitle }; + } elsif ( !$suggestion_only->{suggestionid} + && ( my ( $duplicatebiblionumber, $duplicatetitle ) = FindDuplicate($biblio) ) + && !$save_confirmed ) + { + push @messages, + { type => 'error', code => 'biblio_exists', id => $duplicatebiblionumber, title => $duplicatetitle }; $template->param( - messages => \@messages, + messages => \@messages, need_confirm => 1 ); delete $suggestion_ref->{suggesteddate}; delete $suggestion_ref->{manageddate}; Init($suggestion_ref); $op = 'save'; - } - else { + } else { + + for my $date_key (qw( suggesteddate manageddate accepteddate rejecteddate )) { - for my $date_key ( qw( suggesteddate manageddate accepteddate rejecteddate ) ) { # FIXME Do we need this? $suggestion_only->{$date_key} = dt_from_string( $suggestion_only->{$date_key} ) if $suggestion_only->{$date_key}; @@ -190,15 +200,15 @@ if ( $op =~ /cud-save/ ) { if ( $suggestion_only->{"STATUS"} ) { if ( my $tmpstatus = lc( $suggestion_only->{"STATUS"} ) =~ /ACCEPTED|REJECTED/i ) { - $suggestion_only->{ lc( $suggestion_only->{"STATUS"}) . "date" } = dt_from_string; - $suggestion_only->{ lc( $suggestion_only->{"STATUS"}) . "by" } = C4::Context->userenv->{number}; + $suggestion_only->{ lc( $suggestion_only->{"STATUS"} ) . "date" } = dt_from_string; + $suggestion_only->{ lc( $suggestion_only->{"STATUS"} ) . "by" } = C4::Context->userenv->{number}; } $suggestion_only->{manageddate} = dt_from_string; $suggestion_only->{"managedby"} ||= C4::Context->userenv->{number}; } my $otherreason = $input->param('other_reason'); - if ($suggestion_only->{reason} eq 'other' && $otherreason) { + if ( $suggestion_only->{reason} eq 'other' && $otherreason ) { $suggestion_only->{reason} = $otherreason; } @@ -206,9 +216,9 @@ if ( $op =~ /cud-save/ ) { $suggestion_only->{lastmodificationdate} = dt_from_string; $suggestion_only->{lastmodificationby} = C4::Context->userenv->{number}; - $suggestion_only->{branchcode} = undef - if exists $suggestion_only->{branchcode} - && $suggestion_only->{branchcode} eq ""; + $suggestion_only->{branchcode} = undef + if exists $suggestion_only->{branchcode} + && $suggestion_only->{branchcode} eq ""; if ( $librarian->has_permission( { 'suggestions' => 'suggestions_manage' } ) ) { &ModSuggestion($suggestion_only); @@ -217,10 +227,10 @@ if ( $op =~ /cud-save/ ) { $template->param( messages => \@messages, ); } - if ( $notify ) { - my $patron = Koha::Patrons->find( $suggestion_only->{managedby} ); + if ($notify) { + my $patron = Koha::Patrons->find( $suggestion_only->{managedby} ); my $email_address = $patron->notice_email_address; - if ($patron->notice_email_address) { + if ( $patron->notice_email_address ) { my $letter = C4::Letters::GetPreparedLetter( module => 'suggestions', @@ -244,16 +254,16 @@ if ( $op =~ /cud-save/ ) { } } else { ###FIXME:Search here if suggestion already exists. - my $suggestions= Koha::Suggestions->search_limited( $suggestion_only ); + my $suggestions = Koha::Suggestions->search_limited($suggestion_only); if ( $suggestions->count ) { + #some suggestion are answering the request Donot Add my @messages; while ( my $suggestion = $suggestions->next ) { push @messages, { type => 'error', code => 'already_exists', id => $suggestion->suggestionid }; } $template->param( messages => \@messages ); - } - else { + } else { ## Adding some informations related to suggestion if ( $librarian->has_permission( { 'suggestions' => 'suggestions_create' } ) ) { Koha::Suggestion->new($suggestion_only)->store(); @@ -262,38 +272,39 @@ if ( $op =~ /cud-save/ ) { $template->param( messages => \@messages ); } } + # empty fields, to avoid filter in "SearchSuggestion" } - map{delete $$suggestion_ref{$_} unless $_ eq 'branchcode' } keys %$suggestion_ref; + map { delete $$suggestion_ref{$_} unless $_ eq 'branchcode' } keys %$suggestion_ref; $op = 'else'; - if( $redirect eq 'purchase_suggestions' ) { + if ( $redirect eq 'purchase_suggestions' ) { print $input->redirect("/cgi-bin/koha/members/purchase-suggestions.pl?borrowernumber=$borrowernumber"); } } -} -elsif ( $op eq 'add_form' ) { +} elsif ( $op eq 'add_form' ) { + #Adds suggestion Init($suggestion_ref); - $op ='save'; -} -elsif ( $op eq 'edit_form' ) { + $op = 'save'; +} elsif ( $op eq 'edit_form' ) { + #Edit suggestion - $suggestion_ref=&GetSuggestion($$suggestion_ref{'suggestionid'}); + $suggestion_ref = &GetSuggestion( $$suggestion_ref{'suggestionid'} ); $suggestion_ref->{reasonsloop} = $reasonsloop; my $other_reason = 1; - foreach my $reason ( @{ $reasonsloop } ) { - if ($suggestion_ref->{reason} eq $reason->{lib}) { + foreach my $reason ( @{$reasonsloop} ) { + if ( $suggestion_ref->{reason} eq $reason->{lib} ) { $other_reason = 0; } } $other_reason = 0 unless $suggestion_ref->{reason}; - $template->param(other_reason => $other_reason); + $template->param( other_reason => $other_reason ); Init($suggestion_ref); - $op ='save'; -} -elsif ($op eq "cud-update_status" ) { + $op = 'save'; +} elsif ( $op eq "cud-update_status" ) { my $suggestion; + # set accepted/rejected/managed informations if applicable # ie= if the librarian has chosen some action on the suggestions my $STATUS = $input->param('STATUS'); @@ -301,10 +312,9 @@ elsif ($op eq "cud-update_status" ) { if ( $STATUS eq "ACCEPTED" ) { $suggestion = { accepteddate => dt_from_string, - acceptedby => C4::Context->userenv->{number}, + acceptedby => C4::Context->userenv->{number}, }; - } - elsif ( $STATUS eq "REJECTED" ) { + } elsif ( $STATUS eq "REJECTED" ) { $suggestion = { rejecteddate => dt_from_string, rejectedby => C4::Context->userenv->{number}, @@ -334,7 +344,7 @@ elsif ($op eq "cud-update_status" ) { $template->param( messages => \@messages, ); } redirect_with_params($input); -} elsif ($op eq "cud-delete" ) { +} elsif ( $op eq "cud-delete" ) { if ( $librarian->has_permission( { 'suggestions' => 'suggestions_delete' } ) ) { foreach my $delete_field (@editsuggestions) { &DelSuggestion( $borrowernumber, $delete_field, 'intranet' ); @@ -344,41 +354,36 @@ elsif ($op eq "cud-update_status" ) { push @messages, { type => 'error', code => 'no_delete_permission' }; $template->param( messages => \@messages, ); } -} -elsif ($op eq "cud-archive" ) { - Koha::Suggestions->find($_)->update({ archived => 1 }) for @editsuggestions; +} elsif ( $op eq "cud-archive" ) { + Koha::Suggestions->find($_)->update( { archived => 1 } ) for @editsuggestions; redirect_with_params($input); -} -elsif ($op eq "cud-unarchive" ) { - Koha::Suggestions->find($_)->update({ archived => 0 }) for @editsuggestions; +} elsif ( $op eq "cud-unarchive" ) { + Koha::Suggestions->find($_)->update( { archived => 0 } ) for @editsuggestions; redirect_with_params($input); -} -elsif ( $op eq 'cud-update_itemtype' ) { +} elsif ( $op eq 'cud-update_itemtype' ) { if ( $librarian->has_permission( { 'suggestions' => 'suggestions_manage' } ) ) { foreach my $suggestionid (@editsuggestions) { next unless $suggestionid; - &ModSuggestion({ suggestionid => $suggestionid, itemtype => $new_itemtype }); + &ModSuggestion( { suggestionid => $suggestionid, itemtype => $new_itemtype } ); } redirect_with_params($input); } else { push @messages, { type => 'error', code => 'no_manage_permission' }; $template->param( messages => \@messages, ); } -} -elsif ( $op eq 'cud-update_manager' ) { +} elsif ( $op eq 'cud-update_manager' ) { if ( $librarian->has_permission( { 'suggestions' => 'suggestions_manage' } ) ) { foreach my $suggestionid (@editsuggestions) { next unless $suggestionid; - &ModSuggestion({ suggestionid => $suggestionid, managedby => $sugg_managedby }); + &ModSuggestion( { suggestionid => $suggestionid, managedby => $sugg_managedby } ); } redirect_with_params($input); } else { push @messages, { type => 'error', code => 'no_manage_permission' }; $template->param( messages => \@messages, ); } -} -elsif ( $op eq 'show' ) { - $suggestion_ref=&GetSuggestion($$suggestion_ref{'suggestionid'}); +} elsif ( $op eq 'show' ) { + $suggestion_ref = &GetSuggestion( $$suggestion_ref{'suggestionid'} ); my $budget = GetBudget $$suggestion_ref{budgetid}; $$suggestion_ref{budgetname} = $$budget{budget_name}; Init($suggestion_ref); @@ -386,17 +391,19 @@ elsif ( $op eq 'show' ) { if ( $op eq 'else' ) { - $displayby||="STATUS"; + $displayby ||= "STATUS"; + # distinct values of display by - my $criteria_list=GetDistinctValues("suggestions.".$displayby); - my (@criteria_dv, $criteria_has_empty); + my $criteria_list = GetDistinctValues( "suggestions." . $displayby ); + my ( @criteria_dv, $criteria_has_empty ); foreach (@$criteria_list) { - if ($_->{value}) { + if ( $_->{value} ) { push @criteria_dv, $_->{value}; } else { $criteria_has_empty = 1; } } + # aggregate null and empty values under empty value push @criteria_dv, '' if $criteria_has_empty; @@ -407,6 +414,7 @@ if ( $op eq 'else' ) { { @criteria_dv = ( C4::Context->userenv->{'branch'} ); } + # Pending tab first if ( $displayby eq 'STATUS' ) { @criteria_dv = grep { $_ ne 'ASKED' } @criteria_dv; @@ -418,47 +426,50 @@ if ( $op eq 'else' ) { } my @allsuggestions; - foreach my $criteriumvalue ( @criteria_dv ) { + foreach my $criteriumvalue (@criteria_dv) { my $search_params = {%$suggestion_ref}; next - if $search_params->{STATUS} - && $displayby eq 'STATUS' - && $criteriumvalue ne $search_params->{STATUS}; + if $search_params->{STATUS} + && $displayby eq 'STATUS' + && $criteriumvalue ne $search_params->{STATUS}; # By default, display suggestions from current working branch my $definedvalue = defined $$suggestion_ref{$displayby} && $$suggestion_ref{$displayby} ne ""; - next if ( $definedvalue && $$suggestion_ref{$displayby} ne $criteriumvalue ) and ($displayby ne 'branchcode' && $branchfilter ne '__ANY__' ); + next + if ( $definedvalue && $$suggestion_ref{$displayby} ne $criteriumvalue ) + and ( $displayby ne 'branchcode' && $branchfilter ne '__ANY__' ); $search_params->{$displayby} = $criteriumvalue; # filter on date fields foreach my $field (qw( suggesteddate manageddate accepteddate )) { - my $from = delete $search_params->{"${field}_from"}; - my $to = delete $search_params->{"${field}_to"}; + my $from = delete $search_params->{"${field}_from"}; + my $to = delete $search_params->{"${field}_to"}; my $from_dt = $from && eval { dt_from_string($from) }; - my $to_dt = $to && eval { dt_from_string($to) }; + my $to_dt = $to && eval { dt_from_string($to) }; if ( $from_dt || $to_dt ) { my $dtf = Koha::Database->new->schema->storage->datetime_parser; if ( $from_dt && $to_dt ) { - $search_params->{$field} = { -between => [ $dtf->format_date($from_dt), $dtf->format_date($to_dt) ] }; - } elsif ( $from_dt ) { + $search_params->{$field} = + { -between => [ $dtf->format_date($from_dt), $dtf->format_date($to_dt) ] }; + } elsif ($from_dt) { $search_params->{$field} = { '>=' => $dtf->format_date($from_dt) }; - } elsif ( $to_dt ) { + } elsif ($to_dt) { $search_params->{$field} = { '<=' => $dtf->format_date($to_dt) }; } } } if ( $search_params->{budgetid} && $search_params->{budgetid} eq '__NONE__' ) { - $search_params->{budgetid} = [undef, '' ]; + $search_params->{budgetid} = [ undef, '' ]; } for my $f (qw (branchcode budgetid)) { delete $search_params->{$f} - if $search_params->{$f} eq '__ANY__' - || $search_params->{$f} eq ''; + if $search_params->{$f} eq '__ANY__' + || $search_params->{$f} eq ''; } for my $bi (qw (title author isbn publishercode copyrightdate collectiontitle)) { $search_params->{$bi} = { 'LIKE' => "%" . $search_params->{$bi} . "%" } if $search_params->{$bi}; @@ -468,37 +479,35 @@ if ( $op eq 'else' ) { my @suggestions = Koha::Suggestions->search_limited($search_params)->as_list; push @allsuggestions, - { - "suggestiontype" => $criteriumvalue || "suggest", + { + "suggestiontype" => $criteriumvalue || "suggest", "suggestiontypelabel" => GetCriteriumDesc( $criteriumvalue, $displayby ) || "", 'suggestions' => \@suggestions, 'reasonsloop' => $reasonsloop, - } - if scalar @suggestions > 0; + } + if scalar @suggestions > 0; delete $$suggestion_ref{$displayby} unless $definedvalue; } $template->param( - "displayby"=> $displayby, - "notabs"=> $displayby eq "", - suggestions => \@allsuggestions, + "displayby" => $displayby, + "notabs" => $displayby eq "", + suggestions => \@allsuggestions, ); } -$template->param( - "${_}_patron" => scalar Koha::Patrons->find( $suggestion_ref->{$_} ) ) - for qw(managedby suggestedby acceptedby lastmodificationby); +$template->param( "${_}_patron" => scalar Koha::Patrons->find( $suggestion_ref->{$_} ) ) + for qw(managedby suggestedby acceptedby lastmodificationby); $template->param( %$suggestion_ref, filter_archived => $filter_archived, - "op" =>$op, + "op" => $op, ); -if(defined($returnsuggested) and $returnsuggested ne "noone") -{ - print $input->redirect("/cgi-bin/koha/members/moremember.pl?borrowernumber=".$returnsuggested."#suggestions"); +if ( defined($returnsuggested) and $returnsuggested ne "noone" ) { + print $input->redirect( "/cgi-bin/koha/members/moremember.pl?borrowernumber=" . $returnsuggested . "#suggestions" ); } $template->param( @@ -508,7 +517,7 @@ $template->param( $template->param( returnsuggestedby => $returnsuggestedby ); my $patron_reason_loop = GetAuthorisedValues("OPAC_SUG"); -$template->param(patron_reason_loop=>$patron_reason_loop); +$template->param( patron_reason_loop => $patron_reason_loop ); # Budgets for suggestion add or edition my $sugg_budget_loop = []; @@ -517,44 +526,44 @@ foreach my $r ( @{$sugg_budgets} ) { next unless ( CanUserUseBudget( $borrowernumber, $r, $userflags ) ); my $selected = ( $$suggestion_ref{budgetid} && $r->{budget_id} eq $$suggestion_ref{budgetid} ) ? 1 : 0; push @{$sugg_budget_loop}, - { + { b_id => $r->{budget_id}, b_txt => $r->{budget_name}, b_active => $r->{budget_period_active}, selected => $selected, - }; + }; } @{$sugg_budget_loop} = sort { uc( $a->{b_txt} ) cmp uc( $b->{b_txt} ) } @{$sugg_budget_loop}; -$template->param( sugg_budgets => $sugg_budget_loop); +$template->param( sugg_budgets => $sugg_budget_loop ); -if( $suggestion_ref->{STATUS} ) { +if ( $suggestion_ref->{STATUS} ) { $template->param( - "statusselected_".$suggestion_ref->{STATUS} => 1, - selected_status => $suggestion_ref->{STATUS}, # We need template var selected_status in the second part of the template where template var suggestion.STATUS is out of scope + "statusselected_" . $suggestion_ref->{STATUS} => 1, + selected_status => $suggestion_ref->{STATUS} + , # We need template var selected_status in the second part of the template where template var suggestion.STATUS is out of scope ); } my $currencies = Koha::Acquisition::Currencies->search; $template->param( - currencies => $currencies, - suggestion => $suggestion_ref, - price => sprintf("%.2f", $$suggestion_ref{'price'}||0), - total => sprintf("%.2f", $$suggestion_ref{'total'}||0), + currencies => $currencies, + suggestion => $suggestion_ref, + price => sprintf( "%.2f", $$suggestion_ref{'price'} || 0 ), + total => sprintf( "%.2f", $$suggestion_ref{'total'} || 0 ), ); # lists of distinct values (without empty) for filters my %hashlists; -foreach my $field ( qw(managedby acceptedby suggestedby budgetid) ) { +foreach my $field (qw(managedby acceptedby suggestedby budgetid)) { my $values_list; $values_list = GetDistinctValues( "suggestions." . $field ); my @codes_list = map { - { 'code' => $$_{'value'}, - 'desc' => GetCriteriumDesc( $$_{'value'}, $field ) || $$_{'value'}, - 'selected' => ($$suggestion_ref{$field}) ? $$_{'value'} eq $$suggestion_ref{$field} : 0, + { + 'code' => $$_{'value'}, + 'desc' => GetCriteriumDesc( $$_{'value'}, $field ) || $$_{'value'}, + 'selected' => ( $$suggestion_ref{$field} ) ? $$_{'value'} eq $$suggestion_ref{$field} : 0, } - } grep { - $$_{'value'} - } @$values_list; + } grep { $$_{'value'} } @$values_list; @codes_list = sort { $a->{desc} cmp $b->{desc} } @codes_list; $hashlists{ lc($field) . "_loop" } = \@codes_list; } @@ -568,7 +577,7 @@ $template->param( output_html_with_http_headers $input, $cookie, $template->output; sub redirect_with_params { - my ( $input ) = @_; + my ($input) = @_; my $params = ''; foreach my $key ( qw( @@ -577,10 +586,10 @@ sub redirect_with_params { manageddate_from manageddate_to accepteddate_from accepteddate_to budgetid filter_archived ) - ) + ) { - $params .= $key . '=' . uri_escape(scalar $input->param($key)) . '&' - if defined($input->param($key)); + $params .= $key . '=' . uri_escape( scalar $input->param($key) ) . '&' + if defined( $input->param($key) ); } print $input->redirect("/cgi-bin/koha/suggestion/suggestion.pl?$params"); } diff --git a/svc/article_request b/svc/article_request index 3a9d56d731..94c30ee743 100755 --- a/svc/article_request +++ b/svc/article_request @@ -20,7 +20,7 @@ use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use JSON qw(to_json); use C4::Auth qw(check_cookie_auth); @@ -28,8 +28,8 @@ use Koha::ArticleRequests; my $cgi = CGI->new; -my ( $auth_status ) = - check_cookie_auth( $cgi->cookie('CGISESSID'), { circulate => 'circulate_remaining_permissions' } ); +my ($auth_status) = + check_cookie_auth( $cgi->cookie('CGISESSID'), { circulate => 'circulate_remaining_permissions' } ); if ( $auth_status ne "ok" ) { exit 0; } @@ -37,36 +37,32 @@ if ( $auth_status ne "ok" ) { binmode STDOUT, ':encoding(UTF-8)'; print $cgi->header( -type => 'application/json', -charset => 'UTF-8' ); -my $id = $cgi->param('id'); -my $op = $cgi->param('op') || q{}; +my $id = $cgi->param('id'); +my $op = $cgi->param('op') || q{}; my $notes = $cgi->param('notes'); my $ar = Koha::ArticleRequests->find($id); if ($ar) { if ( $op eq 'cud-cancel' ) { - $ar = $ar->cancel({ notes => $notes }); - } - elsif ( $op eq 'cud-process' ) { + $ar = $ar->cancel( { notes => $notes } ); + } elsif ( $op eq 'cud-process' ) { $ar = $ar->process(); - } - elsif ( $op eq 'cud-pending' ) { + } elsif ( $op eq 'cud-pending' ) { $ar = $ar->set_pending(); - } - elsif ( $op eq 'cud-complete' ) { + } elsif ( $op eq 'cud-complete' ) { $ar = $ar->complete(); - } - elsif ( $op eq 'cud-update_library_id' ) { + } elsif ( $op eq 'cud-update_library_id' ) { my $branchcode = $cgi->param('library_id'); - $ar->branchcode( $branchcode ) if $branchcode; + $ar->branchcode($branchcode) if $branchcode; $ar = $ar->store(); - } - elsif( $op eq 'cud-update_urls' ) { + } elsif ( $op eq 'cud-update_urls' ) { my $urls = $cgi->param('urls') // q{}; - $ar->urls( $urls ); + $ar->urls($urls); $ar = $ar->store(); + } else { + undef $ar; } - else { undef $ar; } } # FIXME do not return 200 if not success diff --git a/svc/authentication b/svc/authentication index 29d05206a5..8d6aa6b9d0 100755 --- a/svc/authentication +++ b/svc/authentication @@ -20,19 +20,19 @@ use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Auth qw/check_api_auth get_session/; use XML::Simple; my $query = CGI->new; -# The authentication strategy for the biblios web +# The authentication strategy for the biblios web # services is as follows. -# +# # 1. biblios POSTs to the authenticate API with URL-encoded # form parameters 'userid' and 'password'. If the credentials # belong to a valid user with the 'editcatalogue' privilege, -# a session cookie is returned and a Koha session created. Otherwise, an +# a session cookie is returned and a Koha session created. Otherwise, an # appropriate error is returned. # 2. For subsequent calls to the biblios APIs, the user agent # should submit the same session cookie. If the cookie is diff --git a/svc/authorised_values b/svc/authorised_values index 8b6821aa0f..104c5e5c5c 100755 --- a/svc/authorised_values +++ b/svc/authorised_values @@ -60,9 +60,9 @@ sub add_authorised_value { image_url => $av->imageurl, ); }; - C4::Service->return_error ( $@ ) if $@; + C4::Service->return_error($@) if $@; - C4::Service->return_success( $response ); + C4::Service->return_success($response); } C4::Service->dispatch( diff --git a/svc/barcode b/svc/barcode index e54e6e6d17..5914dc2b68 100755 --- a/svc/barcode +++ b/svc/barcode @@ -106,7 +106,7 @@ my %type_mapping = ( my $input = CGI->new; -my ( $auth_status ) = check_cookie_auth( $input->cookie('CGISESSID'), { catalogue => '*' } ); +my ($auth_status) = check_cookie_auth( $input->cookie('CGISESSID'), { catalogue => '*' } ); if ( $auth_status ne "ok" ) { exit 0; @@ -114,11 +114,11 @@ if ( $auth_status ne "ok" ) { binmode(STDOUT); -my $type = $input->param('type') || ''; -my $barcode = $input->param('barcode'); -my $notext = $input->param('notext') ? 1 : 0; -my $height = $input->param('height') || 50; -my $qrcode_modulesize = $input->param('modulesize') || "5"; # 1+ +my $type = $input->param('type') || ''; +my $barcode = $input->param('barcode'); +my $notext = $input->param('notext') ? 1 : 0; +my $height = $input->param('height') || 50; +my $qrcode_modulesize = $input->param('modulesize') || "5"; # 1+ my $image; # Validate the barcode type. Default to Code39 if no type or unsupported type sent. @@ -132,15 +132,17 @@ if ( $type eq 'Code39' ) { } eval { - if( $type eq "QRcode" ){ - $image = GD::Barcode->new('QRcode', $barcode, { Ecc => "M", ModuleSize => $qrcode_modulesize } )->plot->png(); + if ( $type eq "QRcode" ) { + $image = GD::Barcode->new( 'QRcode', $barcode, { Ecc => "M", ModuleSize => $qrcode_modulesize } )->plot->png(); } else { + # BZ 37464 - $type must be validated as GD::Barcode unsafely passes this argument directly to an eval{} block $image = GD::Barcode->new( $type, $barcode )->plot( NoText => $notext, Height => $height )->png(); } }; -if ( $@ ) { +if ($@) { + # problem creating image print header( -status => 500 ); } else { diff --git a/svc/bib b/svc/bib index 2353f01927..8ce54772bf 100755 --- a/svc/bib +++ b/svc/bib @@ -21,8 +21,8 @@ use Modern::Perl; -use CGI qw ( -utf8 ); -use C4::Auth qw( check_api_auth ); +use CGI qw ( -utf8 ); +use C4::Auth qw( check_api_auth ); use C4::Biblio qw( GetFrameworkCode ); use C4::Items; use XML::Simple; @@ -31,10 +31,10 @@ use Koha::Biblios; my $query = CGI->new; binmode STDOUT, ':encoding(UTF-8)'; -my ($status, $cookie, $sessionID) = check_api_auth($query, { editcatalogue => 'edit_catalogue'} ); -unless ($status eq "ok") { - print $query->header(-type => 'text/xml', -status => '403 Forbidden'); - print XMLout({ auth_status => $status }, NoAttr => 1, RootName => 'response', XMLDecl => 1); +my ( $status, $cookie, $sessionID ) = check_api_auth( $query, { editcatalogue => 'edit_catalogue' } ); +unless ( $status eq "ok" ) { + print $query->header( -type => 'text/xml', -status => '403 Forbidden' ); + print XMLout( { auth_status => $status }, NoAttr => 1, RootName => 'response', XMLDecl => 1 ); exit 0; } @@ -42,22 +42,22 @@ unless ($status eq "ok") { my $path_info = $query->path_info(); my $biblionumber = undef; -if ($path_info =~ m!^/(\d+)$!) { +if ( $path_info =~ m!^/(\d+)$! ) { $biblionumber = $1; } else { - print $query->header(-type => 'text/xml', -status => '400 Bad Request'); + print $query->header( -type => 'text/xml', -status => '400 Bad Request' ); } # are we retrieving, updating or deleting a bib? -if ($query->request_method eq "GET") { - fetch_bib($query, $biblionumber); -} elsif ($query->request_method eq "POST") { - update_bib($query, $biblionumber); -} elsif ($query->request_method eq "DELETE") { - delete_bib($query, $biblionumber); +if ( $query->request_method eq "GET" ) { + fetch_bib( $query, $biblionumber ); +} elsif ( $query->request_method eq "POST" ) { + update_bib( $query, $biblionumber ); +} elsif ( $query->request_method eq "DELETE" ) { + delete_bib( $query, $biblionumber ); } else { - print $query->header(-type => 'text/xml', -status => '405 Method not allowed'); - print XMLout({ error => 'Method not allowed' }, NoAttr => 1, RootName => 'response', XMLDecl => 1); + print $query->header( -type => 'text/xml', -status => '405 Method not allowed' ); + print XMLout( { error => 'Method not allowed' }, NoAttr => 1, RootName => 'response', XMLDecl => 1 ); exit 0; } @@ -85,29 +85,28 @@ sub fetch_bib { } sub update_bib { - my $query = shift; - my $biblionumber = shift; - my $biblio = Koha::Biblios->find( $biblionumber ); - my $old_record = $biblio->metadata; + my $query = shift; + my $biblionumber = shift; + my $biblio = Koha::Biblios->find($biblionumber); + my $old_record = $biblio->metadata; my $frameworkcode = $query->url_param('frameworkcode') // GetFrameworkCode($biblionumber); - unless (defined $old_record) { - print $query->header(-type => 'text/xml', -status => '404 Not Found'); + unless ( defined $old_record ) { + print $query->header( -type => 'text/xml', -status => '404 Not Found' ); return; } my $result = {}; - my $inxml = $query->param('POSTDATA'); - print $query->header(-type => 'text/xml', -charset => 'utf-8'); + my $inxml = $query->param('POSTDATA'); + print $query->header( -type => 'text/xml', -charset => 'utf-8' ); - my $record = eval {MARC::Record::new_from_xml( $inxml, "UTF-8", C4::Context->preference('marcflavour'))}; + my $record = eval { MARC::Record::new_from_xml( $inxml, "UTF-8", C4::Context->preference('marcflavour') ) }; my $do_not_escape = 0; if ($@) { $result->{'status'} = "failed"; - $result->{'error'} = $@; + $result->{'error'} = $@; } else { my $fullrecord = $record->clone(); - my ( $itemtag, $itemsubfield ) = - C4::Biblio::GetMarcFromKohaField( "items.itemnumber" ); + my ( $itemtag, $itemsubfield ) = C4::Biblio::GetMarcFromKohaField("items.itemnumber"); # delete any item tags foreach my $field ( $record->field($itemtag) ) { @@ -118,37 +117,39 @@ sub update_bib { foreach my $field ( $fullrecord->field($itemtag) ) { my $one_item_record = $record->clone(); $one_item_record->add_fields($field); - C4::Items::ModItemFromMarc( $one_item_record, $biblionumber, - $field->subfield($itemsubfield) ); + C4::Items::ModItemFromMarc( + $one_item_record, $biblionumber, + $field->subfield($itemsubfield) + ); } } C4::Biblio::ModBiblio( $record, $biblionumber, $frameworkcode ); - my $biblio = Koha::Biblios->find( $biblionumber ); + my $biblio = Koha::Biblios->find($biblionumber); my $new_record = $biblio->metadata_record( { embed_items => scalar $query->url_param('items') } ); - $result->{'status'} = "ok"; + $result->{'status'} = "ok"; $result->{'biblionumber'} = $biblionumber; my $xml = $new_record->as_xml_record(); $xml =~ s/<\?xml.*?\?>//i; - $result->{'marcxml'} = $xml; + $result->{'marcxml'} = $xml; $do_not_escape = 1; } - - print XMLout($result, NoAttr => 1, RootName => 'response', XMLDecl => 1, NoEscape => $do_not_escape); + + print XMLout( $result, NoAttr => 1, RootName => 'response', XMLDecl => 1, NoEscape => $do_not_escape ); } sub delete_bib { - my $query = shift; + my $query = shift; my $biblionumber = shift; - my $error = C4::Biblio::DelBiblio($biblionumber); + my $error = C4::Biblio::DelBiblio($biblionumber); - if (defined $error) { - print $query->header(-type => 'text/xml', -status => '400 Bad request'); - print XMLout({ error => $error }, NoAttr => 1, RootName => 'response', XMLDecl => 1); + if ( defined $error ) { + print $query->header( -type => 'text/xml', -status => '400 Bad request' ); + print XMLout( { error => $error }, NoAttr => 1, RootName => 'response', XMLDecl => 1 ); exit 0; } - print $query->header(-type => 'text/xml'); - print XMLout({ status => 'OK, biblio deleted' }, NoAttr => 1, RootName => 'response', XMLDecl => 1); + print $query->header( -type => 'text/xml' ); + print XMLout( { status => 'OK, biblio deleted' }, NoAttr => 1, RootName => 'response', XMLDecl => 1 ); } diff --git a/svc/bib_framework b/svc/bib_framework index 711b8f7913..a6125bac08 100755 --- a/svc/bib_framework +++ b/svc/bib_framework @@ -18,7 +18,7 @@ # along with Koha; if not, see . # use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Auth qw/check_api_auth/; use C4::Biblio; use C4::Items; @@ -27,37 +27,35 @@ use XML::Simple; binmode STDOUT, ':encoding(UTF-8)'; my $query = CGI->new; -my ($status, $cookie, $sessionID) = check_api_auth($query, { editcatalogue => 'edit_catalogue'} ); -unless ($status eq 'ok') { - print $query->header(-type => 'text/xml', -status => '403 Forbidden'); - print XMLout({ auth_status => $status }, NoAttr => 1, RootName => 'response', XMLDecl => 1); +my ( $status, $cookie, $sessionID ) = check_api_auth( $query, { editcatalogue => 'edit_catalogue' } ); +unless ( $status eq 'ok' ) { + print $query->header( -type => 'text/xml', -status => '403 Forbidden' ); + print XMLout( { auth_status => $status }, NoAttr => 1, RootName => 'response', XMLDecl => 1 ); exit 0; } # do initial validation -my $path_info = $query->path_info(); +my $path_info = $query->path_info(); my $biblionumber = undef; -if ($path_info =~ m!^/(\d+)$!) { +if ( $path_info =~ m!^/(\d+)$! ) { $biblionumber = $1; } else { - print $query->header(-type => 'text/xml', -status => '400 Bad Request'); + print $query->header( -type => 'text/xml', -status => '400 Bad Request' ); } -if ($query->request_method eq 'GET') { - fetch_bib_framework($query, $biblionumber); +if ( $query->request_method eq 'GET' ) { + fetch_bib_framework( $query, $biblionumber ); } else { - print $query->header(-type => 'text/xml', -status => '405 Method not allowed'); - print XMLout({ error => 'Method not allowed' }, NoAttr => 1, RootName => 'response', XMLDecl => 1); + print $query->header( -type => 'text/xml', -status => '405 Method not allowed' ); + print XMLout( { error => 'Method not allowed' }, NoAttr => 1, RootName => 'response', XMLDecl => 1 ); exit 0; } exit 0; sub fetch_bib_framework { - my $query = shift; - my $biblionumber = shift; - my $frameworkcode = C4::Biblio::GetFrameworkCode( $biblionumber ); - my $result = { - 'frameworkcode' => $frameworkcode - }; - print $query->header(-type => 'text/xml',-charset => 'utf-8',); - print XMLout($result, NoAttr => 1, RootName => 'response', XMLDecl => 1, NoEscape => 0); + my $query = shift; + my $biblionumber = shift; + my $frameworkcode = C4::Biblio::GetFrameworkCode($biblionumber); + my $result = { 'frameworkcode' => $frameworkcode }; + print $query->header( -type => 'text/xml', -charset => 'utf-8', ); + print XMLout( $result, NoAttr => 1, RootName => 'response', XMLDecl => 1, NoEscape => 0 ); } diff --git a/svc/bib_profile b/svc/bib_profile index 46ebe37963..0a930a9750 100755 --- a/svc/bib_profile +++ b/svc/bib_profile @@ -20,7 +20,7 @@ use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Auth qw/check_api_auth/; use C4::Context; use C4::Koha; @@ -29,13 +29,13 @@ use XML::Simple; my $query = CGI->new; -my ($status, $cookie, $sessionID) = check_api_auth($query, { editcatalogue => 'edit_catalogue'} ); +my ( $status, $cookie, $sessionID ) = check_api_auth( $query, { editcatalogue => 'edit_catalogue' } ); -if ($status eq "ok") { - print $query->header(-type => 'text/xml', cookie => $cookie); +if ( $status eq "ok" ) { + print $query->header( -type => 'text/xml', cookie => $cookie ); } else { - print $query->header(-type => 'text/xml', -status => '403 Forbidden'); - print XMLout({ auth_status => $status }, NoAttr => 1, RootName => 'response', XMLDecl => 1); + print $query->header( -type => 'text/xml', -status => '403 Forbidden' ); + print XMLout( { auth_status => $status }, NoAttr => 1, RootName => 'response', XMLDecl => 1 ); exit 0; } @@ -49,18 +49,23 @@ _get_mandatory_subfields($result); _get_reserved_tags($result); _get_bib_number_tag($result); _get_biblioitem_itemtypes($result); -print XMLout($result, NoAttr => 1, RootName => 'response', XMLDecl => 1, - GroupTags => {mandatory_tags => 'tag', mandatory_subfields => 'subfield', reserved_tags => 'tag', - valid_values => 'value'}); +print XMLout( + $result, NoAttr => 1, RootName => 'response', XMLDecl => 1, + GroupTags => { + mandatory_tags => 'tag', mandatory_subfields => 'subfield', reserved_tags => 'tag', + valid_values => 'value' + } +); exit 0; sub _get_mandatory_tags { my $result = shift; - my $sth = $dbh->prepare_cached("SELECT tagfield FROM marc_tag_structure WHERE frameworkcode = '' AND mandatory = 1"); + my $sth = + $dbh->prepare_cached("SELECT tagfield FROM marc_tag_structure WHERE frameworkcode = '' AND mandatory = 1"); $sth->execute(); my @tags = (); - while (my $row = $sth->fetchrow_arrayref) { + while ( my $row = $sth->fetchrow_arrayref ) { push @tags, $row->[0]; } $result->{'mandatory_tags'} = \@tags; @@ -68,15 +73,17 @@ sub _get_mandatory_tags { sub _get_mandatory_subfields { my $result = shift; - my $sth = $dbh->prepare_cached("SELECT tagfield, tagsubfield + my $sth = $dbh->prepare_cached( + "SELECT tagfield, tagsubfield FROM marc_subfield_structure WHERE frameworkcode = '' AND tagsubfield <> '\@' AND kohafield <> 'biblioitems.itemtype' - AND mandatory = 1"); + AND mandatory = 1" + ); $sth->execute(); my @subfields = (); - while (my $row = $sth->fetchrow_arrayref) { + while ( my $row = $sth->fetchrow_arrayref ) { push @subfields, { tag => $row->[0], subfield_label => $row->[1] }; } $result->{'mandatory_subfields'} = \@subfields; @@ -84,14 +91,16 @@ sub _get_mandatory_subfields { sub _get_reserved_tags { my $result = shift; - my $sth = $dbh->prepare_cached("SELECT DISTINCT tagfield + my $sth = $dbh->prepare_cached( + "SELECT DISTINCT tagfield FROM marc_subfield_structure WHERE frameworkcode = '' AND (kohafield = 'items.itemnumber' OR kohafield = 'biblioitems.itemtype' OR - kohafield = 'biblio.biblionumber')"); + kohafield = 'biblio.biblionumber')" + ); $sth->execute(); my @tags = (); - while (my $row = $sth->fetchrow_arrayref) { + while ( my $row = $sth->fetchrow_arrayref ) { push @tags, $row->[0]; } $result->{'reserved_tags'} = \@tags; @@ -99,31 +108,35 @@ sub _get_reserved_tags { sub _get_bib_number_tag { my $result = shift; - my $sth = $dbh->prepare_cached("SELECT tagfield, tagsubfield + my $sth = $dbh->prepare_cached( + "SELECT tagfield, tagsubfield FROM marc_subfield_structure WHERE frameworkcode = '' - AND kohafield = 'biblio.biblionumber'"); + AND kohafield = 'biblio.biblionumber'" + ); $sth->execute(); my @tags = (); - while (my $row = $sth->fetchrow_arrayref) { + while ( my $row = $sth->fetchrow_arrayref ) { push @tags, { tag => $row->[0], subfield => $row->[1] }; } $result->{'bib_number'} = \@tags; } sub _get_biblioitem_itemtypes { - my $result = shift; + my $result = shift; my $itemtypes = { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search_with_localization->unblessed } }; - my $sth = $dbh->prepare_cached("SELECT tagfield, tagsubfield + my $sth = $dbh->prepare_cached( + "SELECT tagfield, tagsubfield FROM marc_subfield_structure WHERE frameworkcode = '' - AND kohafield = 'biblioitems.itemtype'"); + AND kohafield = 'biblioitems.itemtype'" + ); $sth->execute(); my @tags = (); - while (my $row = $sth->fetchrow_arrayref) { + while ( my $row = $sth->fetchrow_arrayref ) { push @tags, { tag => $row->[0], subfield => $row->[1] }; } - my @valid_values = map { { code => $_, description => $itemtypes->{$_}->{'description'} } } sort keys %$itemtypes; - $result->{'special_entry'} = { field => \@tags, valid_values => \@valid_values }; - + my @valid_values = map { { code => $_, description => $itemtypes->{$_}->{'description'} } } sort keys %$itemtypes; + $result->{'special_entry'} = { field => \@tags, valid_values => \@valid_values }; + } diff --git a/svc/cataloguing/automatic_linker.pl b/svc/cataloguing/automatic_linker.pl index c132fe2473..c1b7559ccc 100755 --- a/svc/cataloguing/automatic_linker.pl +++ b/svc/cataloguing/automatic_linker.pl @@ -19,8 +19,8 @@ use Modern::Perl; use CGI; -use JSON qw( to_json ); -use C4::Auth qw( check_cookie_auth ); +use JSON qw( to_json ); +use C4::Auth qw( check_cookie_auth ); use C4::Biblio qw( BiblioAutoLink TransformHtmlToMarc ); use C4::Context; @@ -28,11 +28,13 @@ my $input = CGI->new; print $input->header('application/json'); # Check the user's permissions -my ( $auth_status ) = - C4::Auth::check_cookie_auth( $input->cookie('CGISESSID'), { - editauthorities => 1, - editcatalogue => 'edit_catalogue' - }); +my ($auth_status) = C4::Auth::check_cookie_auth( + $input->cookie('CGISESSID'), + { + editauthorities => 1, + editcatalogue => 'edit_catalogue' + } +); if ( $auth_status ne "ok" ) { print to_json( { status => 'UNAUTHORIZED' } ); exit 0; @@ -47,15 +49,15 @@ if ( $auth_status ne "ok" ) { my $json; -my $record = TransformHtmlToMarc($input,1); +my $record = TransformHtmlToMarc( $input, 1 ); -my ( $headings_changed, $results ) = BiblioAutoLink ( +my ( $headings_changed, $results ) = BiblioAutoLink( $record, scalar $input->param('frameworkcode'), 1 ); $json->{status} = 'OK'; -$json->{links} = $results->{details} || ''; +$json->{links} = $results->{details} || ''; print to_json($json); diff --git a/svc/cataloguing/control_num_sequences b/svc/cataloguing/control_num_sequences index 131c69d281..66395ef7df 100755 --- a/svc/cataloguing/control_num_sequences +++ b/svc/cataloguing/control_num_sequences @@ -26,18 +26,18 @@ use MARC::Record; our ( $query, $response ) = C4::Service->init( editcatalogue => 'edit_catalogue' ); sub get_and_increment { - my ( $control_num_sequence ) = @_; + my ($control_num_sequence) = @_; - my $schema = Koha::Database->new->schema(); - my $authval = $schema->resultset( 'AuthorisedValue' )->find( + my $schema = Koha::Database->new->schema(); + my $authval = $schema->resultset('AuthorisedValue')->find( { category => 'CONTROL_NUM_SEQUENCE', - lib => $control_num_sequence + lib => $control_num_sequence } ); if ( !$authval ) { - C4::Service->return_error( 'not_found' ); + C4::Service->return_error('not_found'); } my $value = $authval->authorised_value; @@ -46,12 +46,12 @@ sub get_and_increment { my ( $prefix, $num ) = ( $value =~ /(.+?)(\d+)$/ ); - $value = $prefix . sprintf( '%0*d', length( $num ), $num + 1 ); + $value = $prefix . sprintf( '%0*d', length($num), $num + 1 ); - $authval->authorised_value( $value ); + $authval->authorised_value($value); $authval->update(); - C4::Service->return_success( $response ); + C4::Service->return_success($response); } C4::Service->dispatch( diff --git a/svc/cataloguing/framework b/svc/cataloguing/framework index 1014ea5de9..c8e3b6b2e8 100755 --- a/svc/cataloguing/framework +++ b/svc/cataloguing/framework @@ -13,21 +13,21 @@ use Koha::Libraries; my ( $query, $response ) = C4::Service->init( editcatalogue => 'edit_catalogue' ); -my $frameworkcode = $query->param( 'frameworkcode' ) // ''; +my $frameworkcode = $query->param('frameworkcode') // ''; my $tagslib = C4::Biblio::GetMarcStructure( 1, $frameworkcode ); my @tags; foreach my $tag ( sort keys %$tagslib ) { - my $taglib = $tagslib->{$tag}; + my $taglib = $tagslib->{$tag}; my $taginfo = { map { $_, $taglib->{$_} } grep { length $_ > 1 } keys %$taglib }; $taginfo->{subfields} = [ map { [ $_, $taglib->{$_} ] } grep { length $_ == 1 } sort keys %$taglib ]; push @tags, [ $tag, $taginfo ]; } -my $schema = Koha::Database->new->schema; +my $schema = Koha::Database->new->schema; my $authorised_values = {}; my $branches = { map { $_->branchcode => $_->branchname } Koha::Libraries->search_filtered->as_list }; @@ -36,27 +36,34 @@ foreach my $thisbranch ( sort keys %$branches ) { push @{ $authorised_values->{branches} }, { value => $thisbranch, lib => $branches->{$thisbranch} }; } -$authorised_values->{itemtypes} = [ $schema->resultset( "Itemtype" )->search( undef, { - columns => [ { value => 'itemtype' }, { lib => "description" } ], - order_by => "description", - result_class => 'DBIx::Class::ResultClass::HashRefInflator' -} ) ]; +$authorised_values->{itemtypes} = [ + $schema->resultset("Itemtype")->search( + undef, + { + columns => [ { value => 'itemtype' }, { lib => "description" } ], + order_by => "description", + result_class => 'DBIx::Class::ResultClass::HashRefInflator' + } + ) +]; my $class_sources = C4::ClassSource::GetClassSources(); my $default_source = C4::Context->preference("DefaultClassificationSource"); -foreach my $class_source (sort keys %$class_sources) { - next unless $class_sources->{$class_source}->{'used'} or - ($class_source eq $default_source); - push @{ $authorised_values->{cn_source} }, { value => $class_source, lib => $class_sources->{$class_source}->{'description'} }; +foreach my $class_source ( sort keys %$class_sources ) { + next + unless $class_sources->{$class_source}->{'used'} + or ( $class_source eq $default_source ); + push @{ $authorised_values->{cn_source} }, + { value => $class_source, lib => $class_sources->{$class_source}->{'description'} }; } my $avs = C4::Koha::GetAuthorisedValues(); -for my $av ( @$avs ) { - push @{ $authorised_values->{$av->{category}} }, { value => $av->{authorised_value}, lib => $av->{lib} }; +for my $av (@$avs) { + push @{ $authorised_values->{ $av->{category} } }, { value => $av->{authorised_value}, lib => $av->{lib} }; } $response->param( framework => \@tags, authorised_values => $authorised_values ); -C4::Service->return_success( $response ); +C4::Service->return_success($response); diff --git a/svc/cataloguing/metasearch b/svc/cataloguing/metasearch index b56bb7031a..2392ceafcb 100755 --- a/svc/cataloguing/metasearch +++ b/svc/cataloguing/metasearch @@ -29,25 +29,27 @@ my ( $query_string, $servers ) = C4::Service->require_params( 'q', 'servers' ); my $server_errors = {}; -my $sort_key = $query->param( 'sort_key' ) || 'title'; -my $sort_direction = $query->param( 'sort_direction' ) || 'asc'; -my $offset = $query->param( 'offset' ) || 0; -my $page_size = $query->param( 'page_size' ) || 20; -my $fetched = $query->param( 'fetched' ) || 100; +my $sort_key = $query->param('sort_key') || 'title'; +my $sort_direction = $query->param('sort_direction') || 'asc'; +my $offset = $query->param('offset') || 0; +my $page_size = $query->param('page_size') || 20; +my $fetched = $query->param('fetched') || 100; -my $searcher = Koha::MetaSearcher->new( { - fetched => $fetched, - on_error => sub { - my ( $server, $exception ) = @_; +my $searcher = Koha::MetaSearcher->new( + { + fetched => $fetched, + on_error => sub { + my ( $server, $exception ) = @_; - $server_errors->{ $server->{id} } = $exception->message; - }, -} ); + $server_errors->{ $server->{id} } = $exception->message; + }, + } +); $searcher->resultset( $query->param('resultset') ) if ( $query->param('resultset') ); my @server_ids = split( /,/, $servers ); -my $stats = $searcher->search( \@server_ids, $query_string ); +my $stats = $searcher->search( \@server_ids, $query_string ); $searcher->sort( $sort_key, $sort_direction eq 'desc' ? -1 : 1 ); @@ -55,23 +57,23 @@ my @hits; foreach my $hit ( $searcher->results( $offset, $page_size ) ) { push @hits, { - server => $hit->{server}->{id}, + server => $hit->{server}->{id}, servername => $hit->{server}->{servername}, - index => $hit->{index}, - record => $hit->{record}->as_xml_record(), - metadata => $hit->{metadata} + index => $hit->{index}, + record => $hit->{record}->as_xml_record(), + metadata => $hit->{metadata} }; } $response->param( - resultset => $searcher->resultset, - sort_key => $sort_key, + resultset => $searcher->resultset, + sort_key => $sort_key, sort_direction => $sort_direction, - offset => $offset, - page_size => $page_size, - errors => $server_errors, - hits => \@hits, + offset => $offset, + page_size => $page_size, + errors => $server_errors, + hits => \@hits, %$stats ); -C4::Service->return_success( $response ); +C4::Service->return_success($response); diff --git a/svc/checkin b/svc/checkin index 48fa718543..9d9445f4f7 100755 --- a/svc/checkin +++ b/svc/checkin @@ -31,9 +31,10 @@ use Koha::Items; my $input = CGI->new; -my ( $auth_status ) = - check_cookie_auth( $input->cookie('CGISESSID'), - { circulate => 'circulate_remaining_permissions' } ); +my ($auth_status) = check_cookie_auth( + $input->cookie('CGISESSID'), + { circulate => 'circulate_remaining_permissions' } +); my $op = $input->param('op') || q{}; if ( $auth_status ne "ok" || $op ne "cud-checkin" ) { @@ -48,7 +49,7 @@ my $borrowernumber = $input->param('borrowernumber'); my $override_limit = $input->param('override_limit'); my $exempt_fine = $input->param('exempt_fine'); my $branchcode = $input->param('branchcode') - || C4::Context->userenv->{'branch'}; + || C4::Context->userenv->{'branch'}; # Expect these inputs to come in as JSON boolean values $override_limit = $override_limit ? $override_limit eq 'true' : undef; @@ -56,14 +57,14 @@ $exempt_fine = $exempt_fine ? $exempt_fine eq 'true' : undef; my $item = Koha::Items->find($itemnumber); -my $barcode = $item ? $item->barcode : undef; # We certainly will want to return an error code +my $barcode = $item ? $item->barcode : undef; # We certainly will want to return an error code my $data; $data->{itemnumber} = $itemnumber; $data->{borrowernumber} = $borrowernumber; $data->{branchcode} = $branchcode; -my $checkout = Koha::Checkouts->find({ itemnumber => $itemnumber }); +my $checkout = Koha::Checkouts->find( { itemnumber => $itemnumber } ); $data->{patronnote} = $checkout ? $checkout->note : q||; ( $data->{returned} ) = AddReturn( $barcode, $branchcode, $exempt_fine ); diff --git a/svc/checkout_notes b/svc/checkout_notes index be0f80d2c8..ce76603487 100755 --- a/svc/checkout_notes +++ b/svc/checkout_notes @@ -21,7 +21,7 @@ use Modern::Perl; use JSON qw( to_json ); use CGI; -use C4::Auth qw ( check_cookie_auth ); +use C4::Auth qw ( check_cookie_auth ); use C4::Output qw( is_ajax output_with_http_headers ); use Koha::Checkouts; @@ -34,22 +34,22 @@ svc/checkout_notes - Web service for managing patron notes set on issues =cut # AJAX requests -my $is_ajax = is_ajax(); -my $query = CGI->new; -my ( $auth_status ) = check_cookie_auth( $query->cookie('CGISESSID'), { circulate => 'manage_checkout_notes' } ); +my $is_ajax = is_ajax(); +my $query = CGI->new; +my ($auth_status) = check_cookie_auth( $query->cookie('CGISESSID'), { circulate => 'manage_checkout_notes' } ); if ( $auth_status ne "ok" ) { exit 0; } my $op = $query->param('op'); if ($is_ajax) { my $issue_id = $query->param('issue_id'); - my $issue = Koha::Checkouts->find($issue_id); - if ($op eq 'cud-seen'){ - $issue->set({ noteseen => 1 })->store; - } elsif ($op eq 'cud-notseen'){ - $issue->set({ noteseen => 0 })->store; + my $issue = Koha::Checkouts->find($issue_id); + if ( $op eq 'cud-seen' ) { + $issue->set( { noteseen => 1 } )->store; + } elsif ( $op eq 'cud-notseen' ) { + $issue->set( { noteseen => 0 } )->store; } - my $json = to_json ( { seen => $issue->noteseen } ); + my $json = to_json( { seen => $issue->noteseen } ); output_with_http_headers $query, undef, $json, 'js'; exit; } diff --git a/svc/checkouts b/svc/checkouts index dd8d1d0f82..a8c92354d7 100755 --- a/svc/checkouts +++ b/svc/checkouts @@ -22,9 +22,9 @@ use Modern::Perl; use CGI; use JSON qw(to_json); -use C4::Auth qw(check_cookie_auth haspermission); +use C4::Auth qw(check_cookie_auth haspermission); use C4::Circulation qw(GetIssuingCharges CanBookBeRenewed GetRenewCount ); -use C4::Overdues qw(GetFine); +use C4::Overdues qw(GetFine); use C4::Context; use Koha::AuthorisedValues; @@ -34,16 +34,17 @@ use Koha::ItemTypes; my $input = CGI->new; -my ( $auth_status, $session ) = check_cookie_auth( $input->cookie('CGISESSID')); -if( $auth_status ne 'ok' ) { +my ( $auth_status, $session ) = check_cookie_auth( $input->cookie('CGISESSID') ); +if ( $auth_status ne 'ok' ) { print CGI::header( '-status' => '401' ); exit 0; } -my $userid = $session->param('id'); +my $userid = $session->param('id'); -unless (haspermission($userid, { circulate => 'circulate_remaining_permissions' }) - || haspermission($userid, { borrowers => 'edit_borrowers' })) { +unless ( haspermission( $userid, { circulate => 'circulate_remaining_permissions' } ) + || haspermission( $userid, { borrowers => 'edit_borrowers' } ) ) +{ exit 0; } @@ -133,8 +134,7 @@ my $sql = ' if ( @borrowernumber == 1 ) { $sql .= '= ?'; -} -else { +} else { $sql .= ' IN (' . join( ',', ('?') x @borrowernumber ) . ') '; } push( @parameters, @borrowernumber ); @@ -145,11 +145,12 @@ my $dbh = C4::Context->dbh(); my $sth = $dbh->prepare($sql); $sth->execute(@parameters); -my $item_level_itypes = C4::Context->preference('item-level_itypes'); +my $item_level_itypes = C4::Context->preference('item-level_itypes'); my $claims_returned_lost_value = C4::Context->preference('ClaimReturnedLostValue'); -my $confirm_parts_required = C4::Context->preference("CircConfirmItemParts"); +my $confirm_parts_required = C4::Context->preference("CircConfirmItemParts"); -my $itemtypes = { map { $_->{itemtype} => $_->{translated_description} } @{ Koha::ItemTypes->search_with_localization->unblessed } }; +my $itemtypes = { map { $_->{itemtype} => $_->{translated_description} } + @{ Koha::ItemTypes->search_with_localization->unblessed } }; my @checkouts_today; my @checkouts_previous; @@ -158,17 +159,15 @@ while ( my $c = $sth->fetchrow_hashref() ) { my $fine = GetFine( $c->{itemnumber}, $c->{borrowernumber} ); my $checkout_obj = Koha::Checkouts->find( $c->{issue_id} ); - my ( $can_renew, $can_renew_error, $info ) = - CanBookBeRenewed( $checkout_obj->patron, $checkout_obj ); - my $can_renew_date = - $can_renew_error && $can_renew_error eq 'too_soon' - ? output_pref( + my ( $can_renew, $can_renew_error, $info ) = CanBookBeRenewed( $checkout_obj->patron, $checkout_obj ); + my $can_renew_date = $can_renew_error && $can_renew_error eq 'too_soon' + ? output_pref( { - dt => $info->{soonest_renew_date}, + dt => $info->{soonest_renew_date}, as_due_date => 1 } - ) - : undef; + ) + : undef; my ( $renewals_count, @@ -177,8 +176,7 @@ while ( my $c = $sth->fetchrow_hashref() ) { $unseen_count, $unseen_allowed, $unseen_remaining - ) = - GetRenewCount( $c->{borrowernumber}, $c->{itemnumber} ); + ) = GetRenewCount( $c->{borrowernumber}, $c->{itemnumber} ); my ( $itemtype, $recordtype, $type_for_stat ); $itemtype = $itemtypes->{ $c->{itype} } if $c->{itype}; @@ -213,25 +211,28 @@ while ( my $c = $sth->fetchrow_hashref() ) { } my $materials; if ( $c->{materials} && $confirm_parts_required ) { - my $descriptions = Koha::AuthorisedValues->get_description_by_koha_field({frameworkcode => '', kohafield =>'items.materials', authorised_value => $c->{materials} }); + my $descriptions = Koha::AuthorisedValues->get_description_by_koha_field( + { frameworkcode => '', kohafield => 'items.materials', authorised_value => $c->{materials} } ); $materials = $descriptions->{lib} // $c->{materials}; } - my @subtitles = split(/ \| /, $c->{'subtitle'} // '' ); + my @subtitles = split( / \| /, $c->{'subtitle'} // '' ); my $recalled = 0; if ( C4::Context->preference('UseRecalls') ) { - my $item = Koha::Items->find( $c->{itemnumber} ); + my $item = Koha::Items->find( $c->{itemnumber} ); my $recall = undef; $recall = $item->check_recalls if $item->can_be_waiting_recall; if ( defined $recall ) { if ( $recall->item_level ) { if ( $recall->item_id == $c->{itemnumber} ) { + # item-level recall on this item $recalled = 1; } else { $recalled = 0; } } else { + # biblio-level recall, but don't want to mark recalled if the recall has been allocated a different item if ( !$recall->waiting ) { $recalled = 1; @@ -244,14 +245,14 @@ while ( my $c = $sth->fetchrow_hashref() ) { DT_RowId => $c->{itemnumber} . '-' . $c->{borrowernumber}, title => $c->{title}, subtitle => \@subtitles, - medium => $c->{medium} // '', + medium => $c->{medium} // '', part_number => $c->{part_number} // '', - part_name => $c->{part_name} // '', + part_name => $c->{part_name} // '', author => $c->{author}, barcode => $c->{barcode}, type_for_stat => $type_for_stat || q{}, - itemtype_description => $itemtype || q{}, - recordtype_description => $recordtype || q{}, + itemtype_description => $itemtype || q{}, + recordtype_description => $recordtype || q{}, collection => $collection, location => $location, homebranch => $c->{homebranch}, @@ -260,7 +261,7 @@ while ( my $c = $sth->fetchrow_hashref() ) { branchcode => $c->{branchcode}, branchname => $c->{branchname}, itemcallnumber => $c->{itemcallnumber} || q{}, - copynumber => $c->{copynumber} || q{}, + copynumber => $c->{copynumber} || q{}, charge => $charge, fine => $fine, price => $c->{replacementprice} || q{}, @@ -273,7 +274,7 @@ while ( my $c = $sth->fetchrow_hashref() ) { issuedate => $c->{issuedate}, date_due => $c->{date_due}, date_due_overdue => $c->{date_due_overdue} ? JSON::true : JSON::false, - date_due_today => $c->{date_due_today} ? JSON::true : JSON::false, + date_due_today => $c->{date_due_today} ? JSON::true : JSON::false, timestamp => $c->{timestamp}, auto_renew => $c->{auto_renew}, onsite_checkout => $c->{onsite_checkout}, @@ -311,29 +312,26 @@ while ( my $c = $sth->fetchrow_hashref() ) { if ( $c->{not_issued_today} ) { push( @checkouts_previous, $checkout ); - } - else { + } else { push( @checkouts_today, $checkout ); } } - @checkouts_today = sort { $a->{timestamp} cmp $b->{timestamp} } @checkouts_today; # latest to earliest @checkouts_today = reverse(@checkouts_today) - if ( C4::Context->preference('todaysIssuesDefaultSortOrder') eq 'desc' ); # earliest to latest + if ( C4::Context->preference('todaysIssuesDefaultSortOrder') eq 'desc' ); # earliest to latest @checkouts_previous = - sort { $a->{date_due} cmp $b->{date_due} || $a->{timestamp} cmp $b->{timestamp} } - @checkouts_previous; # latest to earliest + sort { $a->{date_due} cmp $b->{date_due} || $a->{timestamp} cmp $b->{timestamp} } + @checkouts_previous; # latest to earliest @checkouts_previous = reverse(@checkouts_previous) - if ( C4::Context->preference('previousIssuesDefaultSortOrder') eq 'desc' ); # earliest to latest + if ( C4::Context->preference('previousIssuesDefaultSortOrder') eq 'desc' ); # earliest to latest my @checkouts = ( @checkouts_today, @checkouts_previous ); my $i = 1; map { $_->{sort_order} = $i++ } @checkouts; - my $data; $data->{'iTotalRecords'} = scalar @checkouts; $data->{'iTotalDisplayRecords'} = scalar @checkouts; diff --git a/svc/club/cancel_enrollment b/svc/club/cancel_enrollment index 1726fbe0b9..d9c76c7ed1 100755 --- a/svc/club/cancel_enrollment +++ b/svc/club/cancel_enrollment @@ -29,8 +29,8 @@ use Koha::Club::Enrollments; my $cgi = CGI->new; -my ( $auth_status ) = - check_cookie_auth( $cgi->cookie('CGISESSID'), { clubs => 'enroll' } ); +my ($auth_status) = + check_cookie_auth( $cgi->cookie('CGISESSID'), { clubs => 'enroll' } ); if ( $auth_status ne "ok" ) { exit 0; } diff --git a/svc/club/delete b/svc/club/delete index 1fb491ab81..7eb394b95b 100755 --- a/svc/club/delete +++ b/svc/club/delete @@ -28,7 +28,7 @@ use Koha::Clubs; my $cgi = CGI->new; -my ( $auth_status ) = check_cookie_auth( $cgi->cookie('CGISESSID'), { clubs => 'edit_clubs' } ); +my ($auth_status) = check_cookie_auth( $cgi->cookie('CGISESSID'), { clubs => 'edit_clubs' } ); if ( $auth_status ne "ok" ) { exit 0; } @@ -39,7 +39,7 @@ my $op = $cgi->param('op') || q{}; my $id = $cgi->param('id'); my $club = Koha::Clubs->find($id); -if ($club && $op eq 'cud-delete') { +if ( $club && $op eq 'cud-delete' ) { $success = $club->delete(); } diff --git a/svc/club/enroll b/svc/club/enroll index d2754577e2..4c62d702b3 100755 --- a/svc/club/enroll +++ b/svc/club/enroll @@ -37,7 +37,7 @@ if ( $auth_status ne "ok" ) { } my $op = $cgi->param('op') || q{}; -exit unless $op eq 'cud-enroll'; # FIXME could be nicer here. +exit unless $op eq 'cud-enroll'; # FIXME could be nicer here. my $id = $cgi->param('id'); my $borrowernumber = $cgi->param('borrowernumber'); diff --git a/svc/club/template/delete b/svc/club/template/delete index 07a862ba0f..83ba36bdcb 100755 --- a/svc/club/template/delete +++ b/svc/club/template/delete @@ -29,7 +29,7 @@ use Koha::Club::Templates; my $cgi = CGI->new; -my ( $auth_status ) = check_cookie_auth( $cgi->cookie('CGISESSID'), { clubs => 'edit_templates' } ); +my ($auth_status) = check_cookie_auth( $cgi->cookie('CGISESSID'), { clubs => 'edit_templates' } ); if ( $auth_status ne "ok" ) { exit 0; } @@ -40,7 +40,7 @@ my $op = $cgi->param('op') || q{}; my $id = $cgi->param('id'); my $club_template = Koha::Club::Templates->find($id); -if ($club_template && $op eq 'cud-delete') { +if ( $club_template && $op eq 'cud-delete' ) { $success = $club_template->delete(); } diff --git a/svc/config/systempreferences b/svc/config/systempreferences index f3f1494a90..e1cbc421ea 100755 --- a/svc/config/systempreferences +++ b/svc/config/systempreferences @@ -63,12 +63,12 @@ Used to set a single system preference. =cut sub set_preference { - my ( $preference ) = @_; + my ($preference) = @_; - my $value = join( ',', $query->param( 'value' ) ); + my $value = join( ',', $query->param('value') ); C4::Context->set_preference( $preference, $value ); - C4::Service->return_success( $response ); + C4::Service->return_success($response); } =head2 get_preference @@ -92,14 +92,12 @@ Used to get a single system preference. sub get_preference { my $preference = scalar $query->param('pref'); - my $value = C4::Context->preference( $preference ); + my $value = C4::Context->preference($preference); $response->param( value => $value ); - C4::Service->return_success( $response ); + C4::Service->return_success($response); } - - =head2 set_preferences =over 4 @@ -125,20 +123,20 @@ pref_virtualshelves=0 sub set_preferences { foreach my $param ( $query->param() ) { - my ( $pref ) = ( $param =~ /pref_(.*)/ ); + my ($pref) = ( $param =~ /pref_(.*)/ ); - next if ( !defined( $pref ) ); + next if ( !defined($pref) ); - my $value = join( ',', $query->multi_param( $param ) ); + my $value = join( ',', $query->multi_param($param) ); C4::Context->set_preference( $pref, $value ); } - C4::Service->return_success( $response ); + C4::Service->return_success($response); } C4::Service->dispatch( - [ 'POST /([A-Za-z0-9_-]+)', [ 'value' ], \&set_preference ], - [ 'POST /', [], \&set_preferences ], - [ 'GET /', [ 'pref' ], \&get_preference], + [ 'POST /([A-Za-z0-9_-]+)', ['value'], \&set_preference ], + [ 'POST /', [], \&set_preferences ], + [ 'GET /', ['pref'], \&get_preference ], ); diff --git a/svc/convert_report b/svc/convert_report index e88ae648cd..d6ea5c8649 100755 --- a/svc/convert_report +++ b/svc/convert_report @@ -21,33 +21,33 @@ use Modern::Perl; use C4::Reports::Guided; use Koha::Reports; -use C4::Auth qw( get_template_and_user get_session ); +use C4::Auth qw( get_template_and_user get_session ); use C4::Output qw( output_html_with_http_headers ); -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); -my $query = CGI->new(); +my $query = CGI->new(); my $report_id = $query->param('id'); my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "reports/convert_report.tt", - query => $query, - type => "intranet", - flagsrequired => { reports => 'execute_reports' }, + template_name => "reports/convert_report.tt", + query => $query, + type => "intranet", + flagsrequired => { reports => 'execute_reports' }, } ); -my $report = Koha::Reports->find( $report_id ); +my $report = Koha::Reports->find($report_id); my $params; -if ( $report ) { - my $sql = $report->savedsql; - my $updated_sql = C4::Reports::Guided::convert_sql( $sql ); +if ($report) { + my $sql = $report->savedsql; + my $updated_sql = C4::Reports::Guided::convert_sql($sql); $params = { msg => 'can_be_updated', updated_sql => $updated_sql, current_sql => $sql }; } else { $params = { msg => 'no_report' }; } -$template->param( %$params ); +$template->param(%$params); output_html_with_http_headers $query, $cookie, $template->output; diff --git a/svc/cover_images b/svc/cover_images index 629c19368c..4efe7c94a6 100755 --- a/svc/cover_images +++ b/svc/cover_images @@ -20,45 +20,44 @@ use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Auth qw/check_cookie_auth/; use Koha::CoverImages; use JSON qw/to_json/; my $input = CGI->new; -my ( $auth_status ) = - check_cookie_auth( - $input->cookie('CGISESSID'), - { tools => 'upload_local_cover_images' } ); +my ($auth_status) = check_cookie_auth( + $input->cookie('CGISESSID'), + { tools => 'upload_local_cover_images' } +); if ( $auth_status ne "ok" ) { exit 0; } -my $op = $input->param('op') || q{}; +my $op = $input->param('op') || q{}; my $imagenumber = $input->param('imagenumber'); my $response = q{}; if ( $op eq "cud-delete" ) { - eval { - Koha::CoverImages->find($imagenumber)->delete; - }; - if ( $@ ) { + eval { Koha::CoverImages->find($imagenumber)->delete; }; + if ($@) { $response = { imagenumber => $imagenumber, - deleted => 0, - error => "MSG_INVALID_IMAGENUMBER" + deleted => 0, + error => "MSG_INVALID_IMAGENUMBER" }; } else { $response = { imagenumber => $imagenumber, - deleted => 1 + deleted => 1 }; } } else { + # FIXME be nicer! # invalid op exit 0; @@ -66,8 +65,8 @@ if ( $op eq "cud-delete" ) { binmode STDOUT, ":encoding(UTF-8)"; print $input->header( - -type => 'application/json', + -type => 'application/json', -charset => 'UTF-8' ); -print to_json( $response ); +print to_json($response); diff --git a/svc/creator_batches b/svc/creator_batches index 8db67423a7..4d9303bf8f 100755 --- a/svc/creator_batches +++ b/svc/creator_batches @@ -23,7 +23,7 @@ use JSON qw( encode_json ); use CGI; use C4::Service; use C4::Context; -use C4::Auth qw( check_cookie_auth ); +use C4::Auth qw( check_cookie_auth ); use C4::Output qw( is_ajax output_with_http_headers ); use C4::Patroncards::Batch; use C4::Labels::Batch; @@ -37,33 +37,34 @@ svc/creator_batches - Web service for managing AJAX functionality for patroncard =cut # AJAX requests -my $is_ajax = is_ajax(); -my $cgi = CGI->new; -my ( $auth_status ) = check_cookie_auth( $cgi->cookie('CGISESSID'), { catalogue => 1 } ); +my $is_ajax = is_ajax(); +my $cgi = CGI->new; +my ($auth_status) = check_cookie_auth( $cgi->cookie('CGISESSID'), { catalogue => 1 } ); if ( $auth_status ne "ok" ) { exit 0; } my $op = $cgi->param('op') || q{}; -if ($is_ajax && $op eq 'cud-set_permission') { - my $batch_id = $cgi->param('batch_id'); +if ( $is_ajax && $op eq 'cud-set_permission' ) { + my $batch_id = $cgi->param('batch_id'); my $description = $cgi->param('newdescription'); - my $dbh = C4::Context->dbh; - my $status = 'success'; + my $dbh = C4::Context->dbh; + my $status = 'success'; eval { my $query = "UPDATE creator_batches SET description = ? WHERE batch_id = ?"; - my $sth = $dbh->prepare($query); - $sth->execute($description, $batch_id); + my $sth = $dbh->prepare($query); + $sth->execute( $description, $batch_id ); }; if ($@) { warn $@; undef $status; } - my $json = encode_json ( { status => $status, newdesc => $description } ); + my $json = encode_json( { status => $status, newdesc => $description } ); output_with_http_headers $cgi, undef, $json, 'js'; exit; } else { + # FIXME be nicer exit 0; } diff --git a/svc/holds b/svc/holds index eb40d2f2c7..898abbf588 100755 --- a/svc/holds +++ b/svc/holds @@ -33,9 +33,10 @@ use Koha::Libraries; my $input = CGI->new; -my ( $auth_status ) = - check_cookie_auth( $input->cookie('CGISESSID'), - { circulate => 'circulate_remaining_permissions' } ); +my ($auth_status) = check_cookie_auth( + $input->cookie('CGISESSID'), + { circulate => 'circulate_remaining_permissions' } +); if ( $auth_status ne "ok" ) { exit 0; @@ -45,34 +46,31 @@ my $branch = C4::Context->userenv->{'branch'}; my $schema = Koha::Database->new()->schema(); -my @sort_columns = - qw/reservedate title itemcallnumber barcode expirationdate priority/; +my @sort_columns = qw/reservedate title itemcallnumber barcode expirationdate priority/; my $borrowernumber = $input->param('borrowernumber'); my $offset = $input->param('iDisplayStart'); my $results_per_page = $input->param('iDisplayLength'); my $sorting_direction = $input->param('sSortDir_0') || 'desc'; my $iSortCol = $input->param('iSortCol_0') // 0; -my $sorting_column = $sort_columns[$iSortCol] // 'reservedate'; +my $sorting_column = $sort_columns[$iSortCol] // 'reservedate'; binmode STDOUT, ":encoding(UTF-8)"; print $input->header( -type => 'application/json', -charset => 'UTF-8' ); my $holds_rs = Koha::Holds->search( { borrowernumber => $borrowernumber }, - { - order_by => { "-$sorting_direction" => $sorting_column } - } + { order_by => { "-$sorting_direction" => $sorting_column } } ); my @holds; while ( my $h = $holds_rs->next() ) { - my $item = $h->item(); + my $item = $h->item(); my $item_group = $h->item_group(); my $biblionumber = $h->biblio()->biblionumber(); - my $desk_id = $h->desk_id; + my $desk_id = $h->desk_id; my $desk_name = ''; if ($desk_id) { $desk_name = $h->desk()->desk_name(); @@ -84,21 +82,21 @@ while ( my $h = $holds_rs->next() ) { $itemtype_limit = $itemtype->translated_description; } - my $libraries = Koha::Libraries->search({}, { order_by => ['branchname'] })->unblessed; - for my $library ( @$libraries ) { + my $libraries = Koha::Libraries->search( {}, { order_by => ['branchname'] } )->unblessed; + for my $library (@$libraries) { $library->{selected} = 1 if $library->{branchcode} eq $h->branchcode(); } - my $biblio = $h->biblio(); - my @subtitles = split(/ \| /, $biblio->subtitle() // ''); - my $hold = { + my $biblio = $h->biblio(); + my @subtitles = split( / \| /, $biblio->subtitle() // '' ); + my $hold = { DT_RowId => $h->reserve_id(), biblionumber => $biblionumber, title => $biblio->title(), subtitle => \@subtitles, - medium => $biblio->medium() // '', + medium => $biblio->medium() // '', part_number => $biblio->part_number() // '', - part_name => $biblio->part_name() // '', + part_name => $biblio->part_name() // '', author => $biblio->author(), reserve_id => $h->reserve_id(), branchcode => $h->branch()->branchname(), @@ -130,23 +128,20 @@ while ( my $h = $holds_rs->next() ) { $hold->{not_transfered} = 0; if ($item) { - $hold->{itemnumber} = $item->itemnumber(); - $hold->{barcode} = $item->barcode(); - $hold->{itemtype} = $item->effective_itemtype(); + $hold->{itemnumber} = $item->itemnumber(); + $hold->{barcode} = $item->barcode(); + $hold->{itemtype} = $item->effective_itemtype(); $hold->{itemtype_description} = $item->itemtype->description; - $hold->{enumchron} = $item->enumchron(); - $hold->{itemcallnumber} = $item->itemcallnumber() || q{}; + $hold->{enumchron} = $item->enumchron(); + $hold->{itemcallnumber} = $item->itemcallnumber() || q{}; my $transfer = $item->get_transfer; if ( $transfer && $transfer->in_transit ) { $hold->{color} = 'transferred'; $hold->{transferred} = 1; - $hold->{date_sent} = output_pref({ dt => dt_from_string($transfer->datesent) }); - $hold->{from_branch} = Koha::Libraries->find($transfer->frombranch)->branchname; - } - elsif ( $item->holding_branch() && $item->holding_branch()->branchcode() ne - $h->branch()->branchcode() ) - { + $hold->{date_sent} = output_pref( { dt => dt_from_string( $transfer->datesent ) } ); + $hold->{from_branch} = Koha::Libraries->find( $transfer->frombranch )->branchname; + } elsif ( $item->holding_branch() && $item->holding_branch()->branchcode() ne $h->branch()->branchcode() ) { $hold->{not_transferred} = 1; $hold->{not_transferred_by} = $h->item()->holding_branch()->branchname(); } diff --git a/svc/import_bib b/svc/import_bib index 27de935d50..8673bc3c3d 100755 --- a/svc/import_bib +++ b/svc/import_bib @@ -20,41 +20,43 @@ use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Auth qw/check_api_auth/; use C4::Context; -use C4::ImportBatch qw( GetWebserviceBatchId AddBiblioToBatch AddItemsToImportBiblio BatchFindDuplicates BatchCommitRecords ); +use C4::ImportBatch + qw( GetWebserviceBatchId AddBiblioToBatch AddItemsToImportBiblio BatchFindDuplicates BatchCommitRecords ); use C4::Matcher; use XML::Simple; + # use Carp::Always; my $query = CGI->new; binmode STDOUT, ':encoding(UTF-8)'; -my ($status, $cookie, $sessionID) = check_api_auth($query, { editcatalogue => 'edit_catalogue'} ); -unless ($status eq "ok") { - print $query->header(-type => 'text/xml', -status => '403 Forbidden'); - print XMLout({ auth_status => $status }, NoAttr => 1, RootName => 'response', XMLDecl => 1); +my ( $status, $cookie, $sessionID ) = check_api_auth( $query, { editcatalogue => 'edit_catalogue' } ); +unless ( $status eq "ok" ) { + print $query->header( -type => 'text/xml', -status => '403 Forbidden' ); + print XMLout( { auth_status => $status }, NoAttr => 1, RootName => 'response', XMLDecl => 1 ); exit 0; } my $xml; -if ($query->request_method eq "POST") { +if ( $query->request_method eq "POST" ) { $xml = $query->param('xml'); } if ($xml) { my %params = map { $_ => scalar $query->param($_) } $query->param; - my $result = import_bib($xml, \%params ); - print $query->header(-type => 'text/xml'); - print XMLout($result, NoAttr => 1, RootName => 'response', XMLDecl => 1); + my $result = import_bib( $xml, \%params ); + print $query->header( -type => 'text/xml' ); + print XMLout( $result, NoAttr => 1, RootName => 'response', XMLDecl => 1 ); } else { - print $query->header(-type => 'text/xml', -status => '400 Bad Request'); + print $query->header( -type => 'text/xml', -status => '400 Bad Request' ); } exit 0; sub import_bib { - my ($inxml, $params) = @_; + my ( $inxml, $params ) = @_; my $result = {}; @@ -62,35 +64,35 @@ sub import_bib { my $framework = delete $params->{framework} || ''; my $overlay_framework = $params->{overlay_framework}; - if (my $matcher_code = delete $params->{match}) { + if ( my $matcher_code = delete $params->{match} ) { $params->{matcher_id} = C4::Matcher::GetMatcherId($matcher_code); } my $batch_id = GetWebserviceBatchId($params); unless ($batch_id) { $result->{'status'} = "failed"; - $result->{'error'} = "Batch create error"; + $result->{'error'} = "Batch create error"; return $result; } my $marcflavour = C4::Context->preference('marcflavour') || 'MARC21'; - my $marc_record = eval {MARC::Record::new_from_xml( $inxml, "UTF-8", $marcflavour)}; + my $marc_record = eval { MARC::Record::new_from_xml( $inxml, "UTF-8", $marcflavour ) }; if ($@) { $result->{'status'} = "failed"; - $result->{'error'} = $@; + $result->{'error'} = $@; return $result; } - if(C4::Context->preference('autoControlNumber') eq 'biblionumber'){ + if ( C4::Context->preference('autoControlNumber') eq 'biblionumber' ) { my @control_num = $marc_record->field('001'); $marc_record->delete_fields(@control_num); } - my $import_record_id = AddBiblioToBatch($batch_id, 0, $marc_record, "utf8", 1); - my @import_items_ids = AddItemsToImportBiblio($batch_id, $import_record_id, $marc_record, 'UPDATE COUNTS'); + my $import_record_id = AddBiblioToBatch( $batch_id, 0, $marc_record, "utf8", 1 ); + my @import_items_ids = AddItemsToImportBiblio( $batch_id, $import_record_id, $marc_record, 'UPDATE COUNTS' ); - my $matcher = C4::Matcher->new($params->{record_type} || 'biblio'); - $matcher = C4::Matcher->fetch($params->{matcher_id}); - my $number_of_matches = BatchFindDuplicates($batch_id, $matcher); + my $matcher = C4::Matcher->new( $params->{record_type} || 'biblio' ); + $matcher = C4::Matcher->fetch( $params->{matcher_id} ); + my $number_of_matches = BatchFindDuplicates( $batch_id, $matcher ); # XXX we are ignoring the result of this; BatchCommitRecords( @@ -104,16 +106,19 @@ sub import_bib { my $dbh = C4::Context->dbh(); my $sth = $dbh->prepare("SELECT matched_biblionumber FROM import_biblios WHERE import_record_id =?"); $sth->execute($import_record_id); - my $biblionumber=$sth->fetchrow_arrayref->[0] || ''; + my $biblionumber = $sth->fetchrow_arrayref->[0] || ''; $sth = $dbh->prepare("SELECT overlay_status FROM import_records WHERE import_record_id =?"); $sth->execute($import_record_id); my $match_status = $sth->fetchrow_arrayref->[0] || 'no_match'; - my $url = C4::Context->preference('staffClientBaseURL') .'/cgi-bin/koha/catalogue/detail.pl?biblionumber='. $biblionumber; + my $url = + C4::Context->preference('staffClientBaseURL') + . '/cgi-bin/koha/catalogue/detail.pl?biblionumber=' + . $biblionumber; - $result->{'status'} = "ok"; + $result->{'status'} = "ok"; $result->{'import_batch_id'} = $batch_id; - $result->{'match_status'} = $match_status; - $result->{'biblionumber'} = $biblionumber; - $result->{'url'} = $url; + $result->{'match_status'} = $match_status; + $result->{'biblionumber'} = $biblionumber; + $result->{'url'} = $url; return $result; } diff --git a/svc/letters/get b/svc/letters/get index dabb8db10e..6cc08e58ff 100755 --- a/svc/letters/get +++ b/svc/letters/get @@ -47,13 +47,13 @@ Used to get letters with a given letter code. our ( $query, $response ) = C4::Service->init( tools => 'edit_notices' ); sub get_letters { - my $code = scalar $query->param('code'); + my $code = scalar $query->param('code'); my $branchcode = scalar $query->param('branchcode'); - my $letters = GetLetters({ code => $code, branchcode => $branchcode }); + my $letters = GetLetters( { code => $code, branchcode => $branchcode } ); $response->param( letters => $letters ); - C4::Service->return_success( $response ); + C4::Service->return_success($response); } C4::Service->dispatch( - [ 'GET /', [ 'code' ], \&get_letters ], + [ 'GET /', ['code'], \&get_letters ], ); diff --git a/svc/letters/preview b/svc/letters/preview index 8b7f5ac1a4..4ee9d33501 100755 --- a/svc/letters/preview +++ b/svc/letters/preview @@ -18,7 +18,7 @@ # along with Koha; if not, see . use Modern::Perl; -use CGI qw( -utf8 ); +use CGI qw( -utf8 ); use C4::Auth qw( get_template_and_user ); use C4::Context; use C4::Output qw( output_html_with_http_headers ); @@ -32,11 +32,11 @@ my $input = CGI->new; my ( $template, $borrowernumber, $cookie ) = get_template_and_user( { - template_name => "tools/preview_letter.tt", - query => $input, - type => "intranet", - flagsrequired => { tools => 'edit_notices' }, - debug => 1, + template_name => "tools/preview_letter.tt", + query => $input, + type => "intranet", + flagsrequired => { tools => 'edit_notices' }, + debug => 1, } ); @@ -47,8 +47,8 @@ my $title = $input->param('title'); my $is_html = $input->param('is_html'); my $data_preview = $input->param('data_preview'); -unless ( $data_preview ) { - $template->param( messages => [{ code => 'no_data_for_preview', type => 'error' }]); +unless ($data_preview) { + $template->param( messages => [ { code => 'no_data_for_preview', type => 'error' } ] ); output_html_with_http_headers $input, $cookie, $template->output; exit; } @@ -78,79 +78,81 @@ if ( $content =~ m/[^\n]*<<.*>>[^\n]*/so ) { # Today $tt_content =~ s#<>#[% today| \$KohaDates with_hours => 1 %]#sg; - - for my $date_field ( qw( - borrowers.dateofbirth - borrowers.dateenrolled - borrowers.dateexpiry - borrowers.debarred - items.dateaccessioned - items.datelastborrowed - items.datelastseen - items.onloan - serials.planneddate - serials.publisheddate - serials.claimdate - reserves.reservedate - reserves.waitingdate - reserves.expirationdate - suggestions.suggesteddate - suggestions.manageddate - suggestions.accepteddate - suggestions.rejecteddate - aqorders.entrydate - aqorders.datereceived - aqorders.datecancellationprinted - aqorders.budgetdate - aqorders.claimed_date - ) ) { + for my $date_field ( + qw( + borrowers.dateofbirth + borrowers.dateenrolled + borrowers.dateexpiry + borrowers.debarred + items.dateaccessioned + items.datelastborrowed + items.datelastseen + items.onloan + serials.planneddate + serials.publisheddate + serials.claimdate + reserves.reservedate + reserves.waitingdate + reserves.expirationdate + suggestions.suggesteddate + suggestions.manageddate + suggestions.accepteddate + suggestions.rejecteddate + aqorders.entrydate + aqorders.datereceived + aqorders.datecancellationprinted + aqorders.budgetdate + aqorders.claimed_date + ) + ) + { my ( $table, $field ) = split '\.', $date_field; my $new_field = - exists $table_mapping->{$table} - ? $table_mapping->{$table} . ".$field" - : "$table.$field"; + exists $table_mapping->{$table} + ? $table_mapping->{$table} . ".$field" + : "$table.$field"; $tt_content =~ s#<<$table\.$field>>#[% $new_field | \$KohaDates %]#sg; $tt_content =~ s#<<$table\.$field\s*|\s*dateonly>>#[% $new_field | \$KohaDates %]#sg; } - for my $datetime_field ( qw( - items.itemlost_on - items.withdrawn_on - issues.date_due - issues.returndate - issues.lastreneweddate - issues.issuedate - reserves.suspend_until - ) ) { + for my $datetime_field ( + qw( + items.itemlost_on + items.withdrawn_on + issues.date_due + issues.returndate + issues.lastreneweddate + issues.issuedate + reserves.suspend_until + ) + ) + { my ( $table, $field ) = split '\.', $datetime_field; my $new_field = - exists $table_mapping->{$table} - ? $table_mapping->{$table} . ".$field" - : "$table.$field"; + exists $table_mapping->{$table} + ? $table_mapping->{$table} . ".$field" + : "$table.$field"; $tt_content =~ s#<<$table\.$field>>#[% $new_field | \$KohaDates with_hours => 1 %]#sg; $tt_content =~ s#<<$table\.$field\s*|\s*dateonly>>#[% $new_field | \$KohaDates %]#sg; } - - while ( my ( $key, $value ) = each %$table_mapping ) { $tt_content =~ s|<<$key\.|<<$value.|sg; } $tt_content =~ s|<<|[% |sg; $tt_content =~ s|>>| %]|sg; - $fake_tt_letter = - { content => $tt_content, title => $title, is_html => $is_html }; + $fake_tt_letter = { content => $tt_content, title => $title, is_html => $is_html }; } my ( $rendered_message, $rendered_tt_message ) = (q||) x 2; my $messages_are_similar; my $letter_params = {}; if ( $code eq 'CHECKIN' ) { - my $item = Koha::Items->find( { barcode => $data_preview } ); + my $item = Koha::Items->find( { barcode => $data_preview } ); my $checkout = Koha::Checkouts->find( { itemnumber => $item->itemnumber } ); if ($checkout) { - my $patron = Koha::Patrons->find( $checkout->borrowernumber ); + my $patron = Koha::Patrons->find( $checkout->borrowernumber ); my $branchcode = C4::Circulation::_GetCircControlBranch( $item, $patron ); $letter_params = { tables => { @@ -163,19 +165,16 @@ if ( $code eq 'CHECKIN' ) { } }; push @messages, { code => 'not_checked_in_yet', type => 'message' }; - } - else { + } else { push @messages, { code => 'no_checkout', type => 'alert' }; $letter_params = {}; } -} -elsif ( $code eq 'CHECKOUT' ) { +} elsif ( $code eq 'CHECKOUT' ) { my ( $barcode, $borrowernumber ) = split '\|', $data_preview; - my $item = Koha::Items->find( { barcode => $barcode } ); - my $patron = Koha::Patrons->find( $borrowernumber ); - if ($item and $patron) { - my $branchcode = - C4::Circulation::_GetCircControlBranch( $item, $patron ); + my $item = Koha::Items->find( { barcode => $barcode } ); + my $patron = Koha::Patrons->find($borrowernumber); + if ( $item and $patron ) { + my $branchcode = C4::Circulation::_GetCircControlBranch( $item, $patron ); $letter_params = { tables => { issues => $item->itemnumber, @@ -187,13 +186,11 @@ elsif ( $code eq 'CHECKOUT' ) { } }; push @messages, { code => 'not_checked_out_yet', type => 'message' }; - } - else { + } else { push @messages, { code => 'no_item_or_no_patron', type => 'alert' }; $letter_params = {}; } -} -elsif ( $code eq 'HOLD_SLIP' ) { +} elsif ( $code eq 'HOLD_SLIP' ) { my ( $biblionumber, $borrowernumber ) = split '\|', $data_preview; my $hold = Koha::Holds->find( { borrowernumber => $borrowernumber, biblionumber => $biblionumber } ); if ($hold) { @@ -207,17 +204,16 @@ elsif ( $code eq 'HOLD_SLIP' ) { items => $hold->itemnumber, } }; - } - else { + } else { push @messages, { code => 'no_hold', type => 'alert' }; $letter_params = {}; } -} -else { +} else { push @messages, { type => 'alert', code => 'preview_not_available', letter_code => $code, }; } -if ( %$letter_params ) { +if (%$letter_params) { + # FIXME Be case here GetPreparedLetter modify $fake_letter $rendered_message = C4::Letters::GetPreparedLetter( letter => $fake_letter, @@ -228,8 +224,7 @@ if ( %$letter_params ) { letter => $fake_tt_letter, %$letter_params, ); - $messages_are_similar = - $rendered_message->{content} eq $rendered_tt_message->{content}; + $messages_are_similar = $rendered_message->{content} eq $rendered_tt_message->{content}; } } diff --git a/svc/localization b/svc/localization index 6eed60632c..f44d1a6c04 100755 --- a/svc/localization +++ b/svc/localization @@ -9,41 +9,49 @@ use Koha::Localizations; our ( $query, $response ) = C4::Service->init( parameters => 'manage_itemtypes' ); sub get_translations { - my $rs = Koha::Localizations->search({ entity => $query->param('entity'), code => $query->param('code') }); + my $rs = Koha::Localizations->search( { entity => $query->param('entity'), code => $query->param('code') } ); my @translations; while ( my $s = $rs->next ) { push @translations, { - id => $s->localization_id, - entity => $s->entity, - code => $s->code, - lang => $s->lang, - translation => $s->translation, - } + id => $s->localization_id, + entity => $s->entity, + code => $s->code, + lang => $s->lang, + translation => $s->translation, + }; } $response->param( translations => \@translations ); - C4::Service->return_success( $response ); + C4::Service->return_success($response); } sub update_translation { - my $id = $query->param('id'); + my $id = $query->param('id'); my $translation = $query->param('translation'); - my $lang = $query->param('lang'); + my $lang = $query->param('lang'); - my $localization = Koha::Localizations->find( $id ); + my $localization = Koha::Localizations->find($id); if ( defined $lang and $localization->lang ne $lang ) { - $localization->lang( $lang ) + $localization->lang($lang); } if ( defined $translation and $localization->translation ne $translation ) { - $localization->translation( $translation ) + $localization->translation($translation); } my %params; my $is_changed; if ( $localization->is_changed ) { $is_changed = 1; - unless ( Koha::Localizations->search( { entity => $localization->entity, code => $localization->code, lang => $lang, localization_id => { '!=' => $localization->localization_id }, } )->count ) { + unless ( + Koha::Localizations->search( + { + entity => $localization->entity, code => $localization->code, lang => $lang, + localization_id => { '!=' => $localization->localization_id }, + } + )->count + ) + { $localization->store; } else { - $params{error} = 1; + $params{error} = 1; $params{error_code} = 'already_exists'; } } @@ -56,21 +64,21 @@ sub update_translation { translation => $localization->translation, is_changed => $is_changed, ); - C4::Service->return_success( $response ); + C4::Service->return_success($response); } sub add_translation { - my $entity = $query->param('entity'); - my $code = $query->param('code'); - my $lang = $query->param('lang'); + my $entity = $query->param('entity'); + my $code = $query->param('code'); + my $lang = $query->param('lang'); my $translation = $query->param('translation'); - unless ( Koha::Localizations->search({entity => $entity, code => $code, lang => $lang, })->count ) { + unless ( Koha::Localizations->search( { entity => $entity, code => $code, lang => $lang, } )->count ) { my $localization = Koha::Localization->new( { - entity => $entity, - code => $code, - lang => $lang, + entity => $entity, + code => $code, + lang => $lang, translation => $translation, } ); @@ -86,19 +94,19 @@ sub add_translation { } else { $response->param( error => 1, error_code => 'already_exists', ); } - C4::Service->return_success( $response ); + C4::Service->return_success($response); } sub delete_translation { my $id = $query->param('id'); Koha::Localizations->find($id)->delete; $response->param( id => $id ); - C4::Service->return_success( $response ); + C4::Service->return_success($response); } C4::Service->dispatch( - [ 'GET /', [ 'id' ], \&get_translations ], - [ 'PUT /', [ 'id' ], \&update_translation ], - [ 'POST /', [ 'entity', 'code', 'lang', 'translation' ], \&add_translation ], - [ 'DELETE /', ['id'], \&delete_translation ], + [ 'GET /', ['id'], \&get_translations ], + [ 'PUT /', ['id'], \&update_translation ], + [ 'POST /', [ 'entity', 'code', 'lang', 'translation' ], \&add_translation ], + [ 'DELETE /', ['id'], \&delete_translation ], ); diff --git a/svc/mana/increment b/svc/mana/increment index ed7d401f2d..e121733e81 100755 --- a/svc/mana/increment +++ b/svc/mana/increment @@ -26,14 +26,14 @@ use C4::Auth qw(check_cookie_auth); use CGI; use JSON; - my $input = CGI->new; binmode STDOUT, ":encoding(UTF-8)"; print $input->header( -type => 'application/json', -charset => 'UTF-8' ); -my ( $auth_status ) = - check_cookie_auth( $input->cookie('CGISESSID'), - { serials => 'create_subscription' } ); +my ($auth_status) = check_cookie_auth( + $input->cookie('CGISESSID'), + { serials => 'create_subscription' } +); if ( $auth_status ne "ok" || $input->request_method ne "POST" ) { exit 0; diff --git a/svc/mana/search b/svc/mana/search index cb52061409..2a5ade46c5 100755 --- a/svc/mana/search +++ b/svc/mana/search @@ -22,7 +22,7 @@ use Modern::Perl; use Koha::SharedContent; use Koha::Subscription; -use C4::Auth qw(get_template_and_user); +use C4::Auth qw(get_template_and_user); use C4::Output qw( output_html_with_http_headers ); use CGI; @@ -30,7 +30,7 @@ use CGI; my $input = CGI->new; my $templatename; -if ($input->param( "resource" ) eq 'report') { +if ( $input->param("resource") eq 'report' ) { $templatename = "mana/mana-report-search-result.tt"; } else { $templatename = "mana/mana-subscription-search-result.tt"; @@ -38,9 +38,9 @@ if ($input->param( "resource" ) eq 'report') { my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => $templatename, - query => $input, - type => "intranet", + template_name => $templatename, + query => $input, + type => "intranet", # flagsrequired => { serials => $permission }, flagsrequired => { serials => 'create_subscription' }, @@ -48,26 +48,26 @@ my ( $template, $loggedinuser, $cookie ) = get_template_and_user( } ); -my ($identifier, $sub_mana_info); +my ( $identifier, $sub_mana_info ); $identifier = $input->param('id'); -$template->param( lowWarned => 5, warned => 10, highWarned => 20); -my $package = "Koha::".ucfirst($input->param( 'resource' )); +$template->param( lowWarned => 5, warned => 10, highWarned => 20 ); +my $package = "Koha::" . ucfirst( $input->param('resource') ); $sub_mana_info = $package->get_search_info($identifier); -$sub_mana_info->{ usecomments } = $input->param('usecomments'); +$sub_mana_info->{usecomments} = $input->param('usecomments'); my $resourcename = $input->param('resource'); -my $result = Koha::SharedContent::search_entities( $resourcename, $sub_mana_info); +my $result = Koha::SharedContent::search_entities( $resourcename, $sub_mana_info ); my $nbofcomment; -foreach my $resource (@{ $result->{data} }){ +foreach my $resource ( @{ $result->{data} } ) { $nbofcomment = 0; - foreach my $comment (@{ $resource->{comments} }){ + foreach my $comment ( @{ $resource->{comments} } ) { $nbofcomment += $comment->{nb}; } $resource->{nbofcomment} = $nbofcomment; } -$template->param( $input->param('resource')."s" => $result->{data} ); -$template->param( statuscode => $result->{code} ); -$template->param( msg => $result->{msg} ); +$template->param( $input->param('resource') . "s" => $result->{data} ); +$template->param( statuscode => $result->{code} ); +$template->param( msg => $result->{msg} ); output_html_with_http_headers $input, $cookie, $template->output; diff --git a/svc/mana/share b/svc/mana/share index 548a56797b..665bd5992d 100755 --- a/svc/mana/share +++ b/svc/mana/share @@ -30,18 +30,18 @@ my $input = CGI->new; binmode STDOUT, ":encoding(UTF-8)"; print $input->header( -type => 'application/json', -charset => 'UTF-8' ); -my ( $auth_status ) = - check_cookie_auth( $input->cookie('CGISESSID'), - { serials => 'create_subscription' } ); +my ($auth_status) = check_cookie_auth( + $input->cookie('CGISESSID'), + { serials => 'create_subscription' } +); if ( $auth_status ne "ok" || $input->request_method ne "POST" ) { exit 0; } - -my $resource_id = $input->param("resource_id"); +my $resource_id = $input->param("resource_id"); my $resource_type = $input->param("resource"); -my $comment = $input->param("message"); -my $result = Koha::SharedContent::comment_entity($resource_id, $resource_type, $comment); +my $comment = $input->param("message"); +my $result = Koha::SharedContent::comment_entity( $resource_id, $resource_type, $comment ); -print(to_json($result)); +print( to_json($result) ); diff --git a/svc/mana/use b/svc/mana/use index 3b405549d5..9b5e29e58a 100755 --- a/svc/mana/use +++ b/svc/mana/use @@ -27,14 +27,14 @@ use Koha::Report; use CGI; use JSON; - my $input = CGI->new; binmode STDOUT, ":encoding(UTF-8)"; print $input->header( -type => 'application/json', -charset => 'UTF-8' ); -my ( $auth_status ) = - check_cookie_auth( $input->cookie('CGISESSID'), - { serials => 'create_subscription' } ); +my ($auth_status) = check_cookie_auth( + $input->cookie('CGISESSID'), + { serials => 'create_subscription' } +); if ( $auth_status ne "ok" || $input->request_method ne "POST" ) { exit 0; @@ -44,13 +44,12 @@ my $result = Koha::SharedContent::get_entity_by_id( scalar $input->param('resource'), scalar $input->param('id') ); -my $package = "Koha::".ucfirst($input->param('resource')); +my $package = "Koha::" . ucfirst( $input->param('resource') ); my $resource; -if ( $input->param( 'saveinbase' )) { - $resource = { id => $package->new_from_mana($result->{data})->id }; -} -else{ +if ( $input->param('saveinbase') ) { + $resource = { id => $package->new_from_mana( $result->{data} )->id }; +} else { $resource = $result->{data}; } -print(to_json($resource)); +print( to_json($resource) ); diff --git a/svc/members/add_to_list b/svc/members/add_to_list index 9c53be4629..d523ceb3e2 100755 --- a/svc/members/add_to_list +++ b/svc/members/add_to_list @@ -20,13 +20,13 @@ use Modern::Perl; use CGI; -use C4::Auth qw( check_cookie_auth ); -use JSON qw( to_json ); +use C4::Auth qw( check_cookie_auth ); +use JSON qw( to_json ); use Koha::List::Patron qw( AddPatronList GetPatronLists AddPatronsToList ); my $input = CGI->new; -my ( $auth_status ) = check_cookie_auth( +my ($auth_status) = check_cookie_auth( $input->cookie('CGISESSID'), { tools => 'manage_patron_lists' }, ); @@ -39,29 +39,28 @@ my @borrowernumbers = $input->multi_param('borrowernumber'); my $response; binmode STDOUT, ":encoding(UTF-8)"; -if ($input->request_method eq "POST") { +if ( $input->request_method eq "POST" ) { if ($add_to_patron_list) { my $patron_list = []; if ( $add_to_patron_list eq 'new' ) { $patron_list = AddPatronList( { name => $new_patron_list } ); - } - else { + } else { $patron_list = - [ GetPatronLists( { patron_list_id => $add_to_patron_list } ) ]->[0]; + [ GetPatronLists( { patron_list_id => $add_to_patron_list } ) ]->[0]; } my @patrons_added_to_list = AddPatronsToList( { list => $patron_list, borrowernumbers => \@borrowernumbers } ); $response->{patron_list} = { patron_list_id => $patron_list->patron_list_id, name => $patron_list->name }; - $response->{patrons_added_to_list} = scalar( @patrons_added_to_list ); + $response->{patrons_added_to_list} = scalar(@patrons_added_to_list); } print $input->header( - -type => 'application/json', + -type => 'application/json', -charset => 'UTF-8' ); } else { - print $input->header(-type => 'text/xml', -status => '400 Bad Request'); + print $input->header( -type => 'text/xml', -status => '400 Bad Request' ); } -print to_json( $response ); +print to_json($response); diff --git a/svc/new_bib b/svc/new_bib index 18837ac853..da5a2a68be 100755 --- a/svc/new_bib +++ b/svc/new_bib @@ -20,7 +20,7 @@ use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Auth qw/check_api_auth/; use C4::Biblio; use C4::Items; @@ -32,17 +32,17 @@ use Koha::Biblios; my $query = CGI->new; binmode STDOUT, ':encoding(UTF-8)'; -my ($status, $cookie, $sessionID) = check_api_auth($query, { editcatalogue => 'edit_catalogue'} ); -unless ($status eq "ok") { - print $query->header(-type => 'text/xml', -status => '403 Forbidden'); - print XMLout({ auth_status => $status }, NoAttr => 1, RootName => 'response', XMLDecl => 1); +my ( $status, $cookie, $sessionID ) = check_api_auth( $query, { editcatalogue => 'edit_catalogue' } ); +unless ( $status eq "ok" ) { + print $query->header( -type => 'text/xml', -status => '403 Forbidden' ); + print XMLout( { auth_status => $status }, NoAttr => 1, RootName => 'response', XMLDecl => 1 ); exit 0; } -if ($query->request_method eq "POST") { +if ( $query->request_method eq "POST" ) { add_bib($query); } else { - print $query->header(-type => 'text/xml', -status => '400 Bad Request'); + print $query->header( -type => 'text/xml', -status => '400 Bad Request' ); } exit 0; @@ -50,34 +50,34 @@ exit 0; sub add_bib { my $query = shift; - my $result = {}; - my $inxml = $query->param('POSTDATA'); + my $result = {}; + my $inxml = $query->param('POSTDATA'); my $frameworkcode = $query->url_param('frameworkcode') // ''; - print $query->header(-type => 'text/xml', -charset => 'utf-8'); + print $query->header( -type => 'text/xml', -charset => 'utf-8' ); - my $marcflavour = C4::Context->preference('marcflavour') || 'MARC21'; - my $record = eval {MARC::Record::new_from_xml( $inxml, "UTF-8", $marcflavour)}; + my $marcflavour = C4::Context->preference('marcflavour') || 'MARC21'; + my $record = eval { MARC::Record::new_from_xml( $inxml, "UTF-8", $marcflavour ) }; my $do_not_escape = 0; if ($@) { $result->{'status'} = "failed"; - $result->{'error'} = $@; + $result->{'error'} = $@; } else { + # fix character set - if ($record->encoding() eq 'MARC-8') { - my ($guessed_charset, $charset_errors); - ($record, $guessed_charset, $charset_errors) = C4::Charset::MarcToUTF8Record($record, $marcflavour); + if ( $record->encoding() eq 'MARC-8' ) { + my ( $guessed_charset, $charset_errors ); + ( $record, $guessed_charset, $charset_errors ) = C4::Charset::MarcToUTF8Record( $record, $marcflavour ); } my $fullrecord = $record->clone(); # delete any item tags - my ( $itemtag, $itemsubfield ) = - C4::Biblio::GetMarcFromKohaField( "items.itemnumber" ); + my ( $itemtag, $itemsubfield ) = C4::Biblio::GetMarcFromKohaField("items.itemnumber"); foreach my $field ( $record->field($itemtag) ) { $record->delete_field($field); } my ( $biblionumber, $biblioitemnumber ) = C4::Biblio::AddBiblio( $record, $frameworkcode ); - my $biblio = Koha::Biblios->find( $biblionumber ); + my $biblio = Koha::Biblios->find($biblionumber); my $new_record = $biblio->metadata->record; if ( $query->url_param('items') ) { foreach my $field ( $fullrecord->field($itemtag) ) { @@ -87,15 +87,15 @@ sub add_bib { } } - $biblio = Koha::Biblios->find($biblionumber); - $new_record = $biblio->metadata_record( { embed_items => scalar $query->url_param('items') } ); - $result->{'status'} = "ok"; + $biblio = Koha::Biblios->find($biblionumber); + $new_record = $biblio->metadata_record( { embed_items => scalar $query->url_param('items') } ); + $result->{'status'} = "ok"; $result->{'biblionumber'} = $biblionumber; my $xml = $new_record->as_xml_record(); $xml =~ s/<\?xml.*?\?>//i; - $result->{'marcxml'} = $xml; + $result->{'marcxml'} = $xml; $do_not_escape = 1; } - - print XMLout($result, NoAttr => 1, RootName => 'response', XMLDecl => 1, NoEscape => $do_not_escape); + + print XMLout( $result, NoAttr => 1, RootName => 'response', XMLDecl => 1, NoEscape => $do_not_escape ); } diff --git a/svc/problem_reports b/svc/problem_reports index f84bcf38e0..f672c1412b 100755 --- a/svc/problem_reports +++ b/svc/problem_reports @@ -21,7 +21,7 @@ use Modern::Perl; use JSON qw( to_json ); use CGI; -use C4::Auth qw( check_cookie_auth ); +use C4::Auth qw( check_cookie_auth ); use C4::Output qw( is_ajax output_with_http_headers ); use Koha::ProblemReports; @@ -34,24 +34,24 @@ svc/problem_reports - Web service for managing OPAC problem reports =cut # AJAX requests -my $is_ajax = is_ajax(); -my $query = CGI->new; -my ( $auth_status ) = check_cookie_auth( $query->cookie('CGISESSID'), { problem_reports => 1 } ); +my $is_ajax = is_ajax(); +my $query = CGI->new; +my ($auth_status) = check_cookie_auth( $query->cookie('CGISESSID'), { problem_reports => 1 } ); if ( $auth_status ne "ok" ) { exit 0; } my $op = $query->param('op') || q{}; if ($is_ajax) { my $report_id = $query->param('report_id'); - my $report = Koha::ProblemReports->find($report_id); + my $report = Koha::ProblemReports->find($report_id); if ( $op eq 'cud-viewed' ) { - $report->set({ status => 'Viewed' })->store; + $report->set( { status => 'Viewed' } )->store; } elsif ( $op eq 'cud-closed' ) { - $report->set({ status => 'Closed' })->store; + $report->set( { status => 'Closed' } )->store; } elsif ( $op eq 'cud-new' ) { - $report->set({ status => 'New' })->store; + $report->set( { status => 'New' } )->store; } - my $json = to_json ( { status => $report->status } ); + my $json = to_json( { status => $report->status } ); output_with_http_headers $query, undef, $json, 'js'; exit; } diff --git a/svc/recall b/svc/recall index 02e2d8fa4b..6d0400f6b1 100755 --- a/svc/recall +++ b/svc/recall @@ -22,25 +22,25 @@ use CGI; use JSON qw(encode_json); use C4::Context; -use C4::Auth qw(check_cookie_auth); -use C4::Output qw(output_with_http_headers); +use C4::Auth qw(check_cookie_auth); +use C4::Output qw(output_with_http_headers); use C4::Circulation qw(AddReturn); use Koha::Recalls; my $input = CGI->new; -my $json = encode_json({ success => 0 }); +my $json = encode_json( { success => 0 } ); my ( $auth_status, $sessionID ) = check_cookie_auth( $input->cookie('CGISESSID'), { recall => 'manage_recalls' } ); if ( $auth_status ne "ok" ) { - print $input->header(-type => 'application/json', -status => '403 Forbidden'); + print $input->header( -type => 'application/json', -status => '403 Forbidden' ); exit 0; } my $recall_id = $input->param('recall_id'); -my $recall = Koha::Recalls->find( $recall_id ); -unless ( $recall ) { - my $json = encode_json({ success => 0 }); +my $recall = Koha::Recalls->find($recall_id); +unless ($recall) { + my $json = encode_json( { success => 0 } ); output_with_http_headers( $input, undef, $json, "json" ); exit; } @@ -48,34 +48,39 @@ unless ( $recall ) { my $op = $input->param('op'); if ( $op eq 'cud-cancel' ) { + # cancel recall $recall->set_cancelled; - if ( $recall->cancelled ){ - $json = encode_json({ success => 1 }); + if ( $recall->cancelled ) { + $json = encode_json( { success => 1 } ); } } elsif ( $op eq 'cud-expire' ) { + # expire recall - $recall->set_expired({ interface => 'INTRANET' }); - if ( $recall->expired ){ - $json = encode_json({ success => 1 }); + $recall->set_expired( { interface => 'INTRANET' } ); + if ( $recall->expired ) { + $json = encode_json( { success => 1 } ); } } elsif ( $op eq 'cud-revert' ) { + # revert recall waiting status $recall->revert_waiting; - if ( $recall->requested ){ - $json = encode_json({ success => 1 }); + if ( $recall->requested ) { + $json = encode_json( { success => 1 } ); } } elsif ( $op eq 'cud-overdue' ) { + # mark recall as overdue - $recall->set_overdue({ interface => 'INTRANET' }); - if ( $recall->overdue ){ - $json = encode_json({ success => 1 }); + $recall->set_overdue( { interface => 'INTRANET' } ); + if ( $recall->overdue ) { + $json = encode_json( { success => 1 } ); } } elsif ( $op eq 'cud-transit' ) { + # cancel recall and return item to home library if ( $recall->in_transit ) { C4::Items::ModItemTransfer( @@ -84,8 +89,8 @@ if ( $op eq 'cud-cancel' ) { ); } $recall->set_cancelled; - if ( $recall->cancelled ){ - $json = encode_json({ success => 1 }); + if ( $recall->cancelled ) { + $json = encode_json( { success => 1 } ); } } diff --git a/svc/records/preview b/svc/records/preview index 81431f160f..fa06b325fd 100755 --- a/svc/records/preview +++ b/svc/records/preview @@ -19,35 +19,36 @@ use Modern::Perl; use CGI; -use C4::Auth qw( get_template_and_user ); -use C4::Biblio qw( ApplyMarcOverlayRules ); +use C4::Auth qw( get_template_and_user ); +use C4::Biblio qw( ApplyMarcOverlayRules ); use C4::MarcModificationTemplates qw( ModifyRecordWithTemplate ); -use C4::Output qw( output_html_with_http_headers ); +use C4::Output qw( output_html_with_http_headers ); use Koha::MetadataRecord::Authority; use Koha::Patrons; -my $query = CGI->new(); -my $record_id = $query->param('record_id'); -my $record_type = $query->param('record_type') || 'biblio'; +my $query = CGI->new(); +my $record_id = $query->param('record_id'); +my $record_type = $query->param('record_type') || 'biblio'; my $overlay_context = $query->param('overlay_context'); -my $mmtid = $query->param('mmtid'); # Marc modification template id +my $mmtid = $query->param('mmtid'); # Marc modification template id my $record; if ( $record_type eq 'biblio' ) { - my $biblio = Koha::Biblios->find( $record_id ); + my $biblio = Koha::Biblios->find($record_id); $record = $biblio->metadata->record; } else { - my $authority = Koha::MetadataRecord::Authority->get_from_authid( $record_id ); + my $authority = Koha::MetadataRecord::Authority->get_from_authid($record_id); $record = $authority->record; } -my ( $template, $loggedinuser, $cookie ) = get_template_and_user({ - template_name => "catalogue/showmarc.tt", - query => $query, - type => "intranet", -}); - +my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "catalogue/showmarc.tt", + query => $query, + type => "intranet", + } +); if ($mmtid) { ModifyRecordWithTemplate( $mmtid, $record ); diff --git a/svc/renew b/svc/renew index 67a658b070..b995a6ef34 100755 --- a/svc/renew +++ b/svc/renew @@ -31,9 +31,10 @@ use Koha::DateUtils qw(output_pref dt_from_string); my $input = CGI->new; -my ( $auth_status ) = - check_cookie_auth( $input->cookie('CGISESSID'), - { circulate => 'circulate_remaining_permissions' } ); +my ($auth_status) = check_cookie_auth( + $input->cookie('CGISESSID'), + { circulate => 'circulate_remaining_permissions' } +); if ( $auth_status ne "ok" ) { exit 0; @@ -46,32 +47,32 @@ my $itemnumber = $input->param('itemnumber'); my $borrowernumber = $input->param('borrowernumber'); my $override_limit = $input->param('override_limit'); my $branchcode = $input->param('branchcode') - || C4::Context->userenv->{'branch'}; -my $seen = $input->param('seen'); + || C4::Context->userenv->{'branch'}; +my $seen = $input->param('seen'); my $date_due; if ( $input->param('date_due') ) { $date_due = dt_from_string( scalar $input->param('date_due') ); } my $data; -$data->{itemnumber} = $itemnumber; +$data->{itemnumber} = $itemnumber; $data->{borrowernumber} = $borrowernumber; -$data->{branchcode} = $branchcode; +$data->{branchcode} = $branchcode; my $patron = Koha::Patrons->find($borrowernumber); -my $item = Koha::Items->find($itemnumber); +my $item = Koha::Items->find($itemnumber); ( $data->{renew_okay}, $data->{error} ) = CanBookBeRenewed( $patron, $item->checkout, $override_limit ); # If we're allowing reserved items to be renewed... -if ( $data->{error} && $data->{error} eq 'on_reserve' && C4::Context->preference('AllowRenewalOnHoldOverride')) { +if ( $data->{error} && $data->{error} eq 'on_reserve' && C4::Context->preference('AllowRenewalOnHoldOverride') ) { $data->{renew_okay} = 1; - $data->{error} = undef; + $data->{error} = undef; } -if ( $data->{renew_okay} || ( $seen && $data->{error} eq 'too_unseen') ) { - try{ +if ( $data->{renew_okay} || ( $seen && $data->{error} eq 'too_unseen' ) ) { + try { $date_due = AddRenewal( { borrowernumber => $borrowernumber, @@ -81,9 +82,9 @@ if ( $data->{renew_okay} || ( $seen && $data->{error} eq 'too_unseen') ) { seen => $seen } ); - $data->{date_due} = output_pref( { dt => $date_due, as_due_date => 1 } ); + $data->{date_due} = output_pref( { dt => $date_due, as_due_date => 1 } ); $data->{renew_okay} = 1; - $data->{error} = undef; + $data->{error} = undef; } catch { if ( ref($_) eq 'Koha::Exceptions::Checkout::FailedRenewal' ) { $data->{error} = 'renewal_failed'; diff --git a/svc/report b/svc/report index b5aa5ddb2a..f5045c0b1b 100755 --- a/svc/report +++ b/svc/report @@ -20,58 +20,59 @@ use Modern::Perl; -use C4::Auth qw( check_api_auth ); +use C4::Auth qw( check_api_auth ); use C4::Reports::Guided qw( execute_query ); use Koha::Reports; use JSON qw( encode_json decode_json to_json ); -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use Koha::Caches; - -my $query = CGI->new(); -my $report_id = $query->param('id'); -my $report_name = $query->param('name'); +my $query = CGI->new(); +my $report_id = $query->param('id'); +my $report_name = $query->param('name'); my $report_annotation = $query->param('annotated'); my $report_recs = Koha::Reports->search( $report_name ? { 'report_name' => $report_name } : { 'id' => $report_id } ); -if (!$report_recs || $report_recs->count == 0 ) { die "There is no such report.\n"; } +if ( !$report_recs || $report_recs->count == 0 ) { die "There is no such report.\n"; } my $report_rec = $report_recs->next(); $report_id = $report_rec->id; my @sql_params = $query->multi_param('sql_params'); -my @param_names = $query->multi_param('param_names'); +my @param_names = $query->multi_param('param_names'); -my ($status, $cookie, $sessionID) = check_api_auth($query, { catalogue => '1'} ); -unless ($status eq "ok") { - print $query->header(-type => 'application/json', -status => '401 Unauthorized'); - print to_json({ auth_status => $status }); +my ( $status, $cookie, $sessionID ) = check_api_auth( $query, { catalogue => '1' } ); +unless ( $status eq "ok" ) { + print $query->header( -type => 'application/json', -status => '401 Unauthorized' ); + print to_json( { auth_status => $status } ); exit 0; } -my $cache = Koha::Caches->get_instance(); +my $cache = Koha::Caches->get_instance(); my $cache_active = $cache->is_cache_active; -my ($cache_key, $json_text); +my ( $cache_key, $json_text ); if ($cache_active) { - $cache_key = "intranet:report:".($report_name ? "report_name:$report_name:" : "id:$report_id:") - . join( '-', @sql_params ) - . join( '_'. @param_names ); + $cache_key = + "intranet:report:" + . ( $report_name ? "report_name:$report_name:" : "id:$report_id:" ) + . join( '-', @sql_params ) + . join( '_' . @param_names ); $json_text = $cache->get_from_cache($cache_key); } unless ($json_text) { - my $limit = C4::Context->preference("SvcMaxReportRows") || 10; + my $limit = C4::Context->preference("SvcMaxReportRows") || 10; my ( $sql, undef ) = $report_rec->prep_report( \@param_names, \@sql_params ); my ( $sth, $errors ) = execute_query( { - sql => $sql, - offset => 0, - limit => $limit, - report_id => $report_id, + sql => $sql, + offset => 0, + limit => $limit, + report_id => $report_id, } ); if ($errors) { @@ -79,9 +80,8 @@ unless ($json_text) { } else { my $lines; if ($report_annotation) { - $lines = $sth->fetchall_arrayref({}); - } - else { + $lines = $sth->fetchall_arrayref( {} ); + } else { $lines = $sth->fetchall_arrayref; } $json_text = encode_json($lines); @@ -93,7 +93,7 @@ unless ($json_text) { } print $query->header( - -charset => 'UTF-8', - -type => 'application/json' + -charset => 'UTF-8', + -type => 'application/json' ); print $json_text; diff --git a/svc/return_claims b/svc/return_claims index 42e48c55d5..e038a2ed5b 100755 --- a/svc/return_claims +++ b/svc/return_claims @@ -32,19 +32,15 @@ use Koha::Patrons; my $input = CGI->new; my ( $auth_status, $session ) = check_cookie_auth( $input->cookie('CGISESSID') ); -if( $auth_status ne 'ok' ) { +if ( $auth_status ne 'ok' ) { print CGI::header( '-status' => '401' ); exit 0; } -my $userid = $session->param('id'); +my $userid = $session->param('id'); -unless ( - haspermission( - $userid, { circulate => 'circulate_remaining_permissions' } - ) - || haspermission( $userid, { borrowers => 'edit_borrowers' } ) - ) +unless ( haspermission( $userid, { circulate => 'circulate_remaining_permissions' } ) + || haspermission( $userid, { borrowers => 'edit_borrowers' } ) ) { exit 0; } @@ -57,9 +53,9 @@ my $results_per_page = $input->param('iDisplayLength') || -1; my $sorting_column = $input->param('iSortCol_0') || q{}; $sorting_column = - ( $sorting_column && $sort_columns[$sorting_column] ) - ? $sort_columns[$sorting_column] - : 'created_on'; + ( $sorting_column && $sort_columns[$sorting_column] ) + ? $sort_columns[$sorting_column] + : 'created_on'; my $sorting_direction = $input->param('sSortDir_0') || q{}; $sorting_direction = $sorting_direction eq 'asc' ? 'asc' : 'desc'; @@ -93,25 +89,28 @@ my $dbh = C4::Context->dbh(); my $sth = $dbh->prepare($sql); $sth->execute($borrowernumber); -my $resolved = 0; +my $resolved = 0; my $unresolved = 0; my @return_claims; while ( my $claim = $sth->fetchrow_hashref() ) { - $claim->{created_on_formatted} = output_pref( { dt => dt_from_string( $claim->{created_on} ) } ) if $claim->{created_on}; - $claim->{updated_on_formatted} = output_pref( { dt => dt_from_string( $claim->{updated_on} ) } ) if $claim->{updated_on}; - $claim->{resolved_on_formatted} = output_pref( { dt => dt_from_string( $claim->{resolved_on} ) } ) if $claim->{resolved_on}; + $claim->{created_on_formatted} = output_pref( { dt => dt_from_string( $claim->{created_on} ) } ) + if $claim->{created_on}; + $claim->{updated_on_formatted} = output_pref( { dt => dt_from_string( $claim->{updated_on} ) } ) + if $claim->{updated_on}; + $claim->{resolved_on_formatted} = output_pref( { dt => dt_from_string( $claim->{resolved_on} ) } ) + if $claim->{resolved_on}; my $patron = $claim->{resolved_by} ? Koha::Patrons->find( $claim->{resolved_by} ) : undef; $claim->{resolved_by_data} = $patron->unblessed if $patron; my $resolution = $claim->{resolution} - ? Koha::AuthorisedValues->find( + ? Koha::AuthorisedValues->find( { category => 'RETURN_CLAIM_RESOLUTION', authorised_value => $claim->{resolution}, } - ) - : undef; + ) + : undef; $claim->{resolution_data} = $resolution->unblessed if $resolution; $claim->{resolved_on} ? $resolved++ : $unresolved++; diff --git a/svc/split_callnumbers b/svc/split_callnumbers index 7fc9deefd3..f902da09c6 100755 --- a/svc/split_callnumbers +++ b/svc/split_callnumbers @@ -8,16 +8,16 @@ use C4::ClassSplitRoutine::RegEx; our ( $query, $response ) = C4::Service->init( parameters => 'parameters_remaining_permissions' ); sub get_split_callnumbers { - my $regexs = from_json( $query->param('regexs') ); - my $c = $query->param('callnumbers'); + my $regexs = from_json( $query->param('regexs') ); + my $c = $query->param('callnumbers'); my @callnumbers = split "\n", $c; my @callnumbers_split; - for my $callnumber ( @callnumbers ) { - my @lines = C4::ClassSplitRoutine::RegEx::split_callnumber($callnumber, $regexs); + for my $callnumber (@callnumbers) { + my @lines = C4::ClassSplitRoutine::RegEx::split_callnumber( $callnumber, $regexs ); push @callnumbers_split, { inline => $callnumber, split => \@lines }; } $response->param( split_callnumbers => \@callnumbers_split ); - C4::Service->return_success( $response ); + C4::Service->return_success($response); } C4::Service->dispatch( diff --git a/svc/virtualshelves/search b/svc/virtualshelves/search index edb366d921..5b2fad33ae 100755 --- a/svc/virtualshelves/search +++ b/svc/virtualshelves/search @@ -3,30 +3,32 @@ use Modern::Perl; use CGI; -use C4::Auth qw( get_template_and_user ); -use C4::Output qw( output_with_http_headers ); +use C4::Auth qw( get_template_and_user ); +use C4::Output qw( output_with_http_headers ); use C4::Utils::DataTables::VirtualShelves qw( search ); my $input = CGI->new; exit unless $input->param('template_path'); -my ($template, $user, $cookie) = get_template_and_user({ - template_name => scalar $input->param('template_path'), - query => $input, - type => "intranet", - flagsrequired => { catalogue => 1 } -}); +my ( $template, $user, $cookie ) = get_template_and_user( + { + template_name => scalar $input->param('template_path'), + query => $input, + type => "intranet", + flagsrequired => { catalogue => 1 } + } +); -my $shelfname = $input->param('shelfname'); -my $count = $input->param('count'); -my $owner = $input->param('owner'); -my $public = $input->param('public'); -my $sortby = $input->param('sortby'); +my $shelfname = $input->param('shelfname'); +my $count = $input->param('count'); +my $owner = $input->param('owner'); +my $public = $input->param('public'); +my $sortby = $input->param('sortby'); my $allow_transfer = $input->param('allow_transfer'); -my $order_by = $input->param('order_by'); -my $start = $input->param('start'); -my $length = $input->param('length'); +my $order_by = $input->param('order_by'); +my $start = $input->param('start'); +my $length = $input->param('length'); # variable information for DataTables (id) my $draw = $input->param('draw'); @@ -45,12 +47,12 @@ my $results = C4::Utils::DataTables::VirtualShelves::search( ); $template->param( - draw => $draw, - recordsTotal => $results->{recordsTotal}, + draw => $draw, + recordsTotal => $results->{recordsTotal}, recordsFiltered => $results->{recordsFiltered}, - data => $results->{shelves}, - public => $public, - allow_transfer => $allow_transfer, + data => $results->{shelves}, + public => $public, + allow_transfer => $allow_transfer, ); output_with_http_headers $input, $cookie, $template->output, 'json'; diff --git a/t/00-check-atomic-updates.t b/t/00-check-atomic-updates.t index 75bab4576f..b867be00bb 100755 --- a/t/00-check-atomic-updates.t +++ b/t/00-check-atomic-updates.t @@ -36,6 +36,6 @@ SKIP: { next if $f eq 'skeleton.pl'; unlike( $f, qr/.*pl$/, "check for unhandled atomic updates: $f" ); } -}; +} done_testing(); diff --git a/t/00-deprecated.t b/t/00-deprecated.t index 6eba09deba..2c26e4af23 100755 --- a/t/00-deprecated.t +++ b/t/00-deprecated.t @@ -12,16 +12,19 @@ use Cwd; my @files_with_switch = do { my @files; local $/ = undef; - find( sub { - my $dir = getcwd(); - return if $dir =~ /blib/; - return unless /\.(pl|pm)$/; # Don't inspect non-Perl files - open my $fh, "<", $_; - my $content = <$fh>; - push @files, "$dir/$_" if $content =~ /switch\s*\(.*{/; - }, ( '.' ) ); + find( + sub { + my $dir = getcwd(); + return if $dir =~ /blib/; + return unless /\.(pl|pm)$/; # Don't inspect non-Perl files + open my $fh, "<", $_; + my $content = <$fh>; + push @files, "$dir/$_" if $content =~ /switch\s*\(.*{/; + }, + ('.') + ); @files; }; ok( !@files_with_switch, "Perl syntax: no use of switch statement" ) - or diag( "Files list: " . join(', ', @files_with_switch) ); + or diag( "Files list: " . join( ', ', @files_with_switch ) ); diff --git a/t/00-load.t b/t/00-load.t index d518f34fd1..e70f985049 100755 --- a/t/00-load.t +++ b/t/00-load.t @@ -32,20 +32,23 @@ use English qw( -no_match_vars ); # Loop through the C4:: modules my $lib = File::Spec->rel2abs('C4'); -find({ - bydepth => 1, - no_chdir => 1, - wanted => sub { - my $m = $_; - return unless $m =~ s/[.]pm$//; +find( + { + bydepth => 1, + no_chdir => 1, + wanted => sub { + my $m = $_; + return unless $m =~ s/[.]pm$//; - $m =~ s{^.*/C4/}{C4/}; - $m =~ s{/}{::}g; - return if $m =~ /Auth_with_ldap/; # Dont test this, it will fail on use - return if $m =~ /SIPServer/; # SIP Server module has old package usage - use_ok($m) || BAIL_OUT("***** PROBLEMS LOADING FILE '$m'"); + $m =~ s{^.*/C4/}{C4/}; + $m =~ s{/}{::}g; + return if $m =~ /Auth_with_ldap/; # Dont test this, it will fail on use + return if $m =~ /SIPServer/; # SIP Server module has old package usage + use_ok($m) || BAIL_OUT("***** PROBLEMS LOADING FILE '$m'"); + }, }, -}, $lib); + $lib +); # Loop through the Koha:: modules $lib = File::Spec->rel2abs('Koha'); @@ -56,8 +59,8 @@ find( wanted => sub { my $m = $_; return unless $m =~ s/[.]pm$//; - $m =~ s{^.*/Koha/}{Koha/}; - $m =~ s{/}{::}g; + $m =~ s{^.*/Koha/}{Koha/}; + $m =~ s{/}{::}g; if ( is_testable($m) ) { use_ok($m) || BAIL_OUT("***** PROBLEMS LOADING FILE '$m'"); } @@ -76,16 +79,13 @@ sub is_testable { my @needed_module_names; my $return_value = 1; if ( $module_name =~ /Koha::SearchEngine::Elasticsearch::Indexer/xsm ) { - @needed_module_names = ( 'Search::Elasticsearch' ); - } - elsif ( $module_name =~ /Koha::SearchEngine::Elasticsearch::Search/xsm ) { - @needed_module_names = ( 'Search::Elasticsearch' ); - } - elsif ( $module_name =~ /Koha::SearchEngine::Elasticsearch/xsm ) { - @needed_module_names = ( 'Search::Elasticsearch' ); - } - elsif ( $module_name =~ /^Koha::ExternalContent/xsm ) { - @needed_module_names = ( 'WebService::ILS' ); + @needed_module_names = ('Search::Elasticsearch'); + } elsif ( $module_name =~ /Koha::SearchEngine::Elasticsearch::Search/xsm ) { + @needed_module_names = ('Search::Elasticsearch'); + } elsif ( $module_name =~ /Koha::SearchEngine::Elasticsearch/xsm ) { + @needed_module_names = ('Search::Elasticsearch'); + } elsif ( $module_name =~ /^Koha::ExternalContent/xsm ) { + @needed_module_names = ('WebService::ILS'); } foreach my $current_name (@needed_module_names) { my $relative_pathname = $current_name; @@ -93,9 +93,7 @@ sub is_testable { $relative_pathname .= '.pm'; my $check_result = eval { require "$relative_pathname"; 1; }; if ($EVAL_ERROR) { - diag( -"Skipping testing of $module_name, because $current_name is not installed." - ); + diag("Skipping testing of $module_name, because $current_name is not installed."); $return_value = 0; } } diff --git a/t/00-merge-conflict-markers.t b/t/00-merge-conflict-markers.t index 86f7fa5f8c..a3f95a3c28 100755 --- a/t/00-merge-conflict-markers.t +++ b/t/00-merge-conflict-markers.t @@ -23,30 +23,37 @@ use File::Find; use IO::File; my @failures; -find({ - bydepth => 1, - no_chdir => 1, - wanted => sub { - my $file = $_; +find( + { + bydepth => 1, + no_chdir => 1, + wanted => sub { + my $file = $_; - return if $file =~ /\.(ico|jpg|gif|ogg|pdf|png|psd|swf|zip|.*\~)$/; - return unless -f $file; + return if $file =~ /\.(ico|jpg|gif|ogg|pdf|png|psd|swf|zip|.*\~)$/; + return unless -f $file; - my @name_parts = File::Spec->splitpath($file); - my %dirs = map { $_ => 1 } File::Spec->splitdir($name_parts[1]); - return if exists $dirs{'.git'}; + my @name_parts = File::Spec->splitpath($file); + my %dirs = map { $_ => 1 } File::Spec->splitdir( $name_parts[1] ); + return if exists $dirs{'.git'}; - my $fh = IO::File->new($file, 'r'); - my $marker_found = 0; - while (my $line = <$fh>) { - # could check for ^=====, but that's often used in text files - $marker_found++ if $line =~ m|^<<<<<<|; - $marker_found++ if $line =~ m|^>>>>>>|; - last if $marker_found; - } - close $fh; - push @failures, $file if $marker_found; -}, -}, File::Spec->curdir()); + my $fh = IO::File->new( $file, 'r' ); + my $marker_found = 0; + while ( my $line = <$fh> ) { -is( @failures, 0, 'Files should not contain merge markers' . ( @failures ? ( ' (' . join( ', ', @failures ) . ' )' ) : '' ) ); + # could check for ^=====, but that's often used in text files + $marker_found++ if $line =~ m|^<<<<<<|; + $marker_found++ if $line =~ m|^>>>>>>|; + last if $marker_found; + } + close $fh; + push @failures, $file if $marker_found; + }, + }, + File::Spec->curdir() +); + +is( + @failures, 0, + 'Files should not contain merge markers' . ( @failures ? ( ' (' . join( ', ', @failures ) . ' )' ) : '' ) +); diff --git a/t/00-testcritic.t b/t/00-testcritic.t index 66458df707..99f529f145 100755 --- a/t/00-testcritic.t +++ b/t/00-testcritic.t @@ -8,7 +8,7 @@ use English qw(-no_match_vars); eval { require Test::Perl::Critic; }; -if ( $EVAL_ERROR ) { +if ($EVAL_ERROR) { my $msg = 'Test::Perl::Critic required to criticise code,'; plan( skip_all => $msg ); } diff --git a/t/00-valid-xml.t b/t/00-valid-xml.t index 4cc8d9dd89..03c343799e 100755 --- a/t/00-valid-xml.t +++ b/t/00-valid-xml.t @@ -25,21 +25,24 @@ use XML::LibXML; my $parser = XML::LibXML->new(); -find({ - bydepth => 1, - no_chdir => 1, - wanted => sub { - my $file = $_; - return if $file =~ m|/node_modules/|i; - return unless $file =~ /(\.xml|\.xsl|\.xslt|\.xsd)$/i; - my $dom; - eval { $dom = $parser->parse_file($file); }; - if ($@) { - fail("$file parses"); - diag($@); - } else { - pass("$file parses"); - } +find( + { + bydepth => 1, + no_chdir => 1, + wanted => sub { + my $file = $_; + return if $file =~ m|/node_modules/|i; + return unless $file =~ /(\.xml|\.xsl|\.xslt|\.xsd)$/i; + my $dom; + eval { $dom = $parser->parse_file($file); }; + if ($@) { + fail("$file parses"); + diag($@); + } else { + pass("$file parses"); + } + }, }, -}, File::Spec->curdir()); + File::Spec->curdir() +); done_testing(); diff --git a/t/Acquisition/CanUserManageBasket.t b/t/Acquisition/CanUserManageBasket.t index 462189ecde..6c2957d189 100755 --- a/t/Acquisition/CanUserManageBasket.t +++ b/t/Acquisition/CanUserManageBasket.t @@ -9,61 +9,56 @@ use C4::Acquisition qw( GetBasket GetBasketUsers CanUserManageBasket ); local $SIG{__WARN__} = sub { warn $_[0] unless $_[0] =~ /redefined/ }; *C4::Acquisition::GetBasketUsers = \&Mock_GetBasketUsers; -*C4::Context::preference = \&Mock_preference; +*C4::Context::preference = \&Mock_preference; my $AcqViewBaskets; my %basketusers = ( 1 => [], - 2 => [1, 2], + 2 => [ 1, 2 ], 3 => [], - 4 => [1, 2], + 4 => [ 1, 2 ], ); # Borrowers my $borrower1 = { borrowernumber => 1, - branchcode => 'B1', + branchcode => 'B1', }; my $borrower2 = { borrowernumber => 2, - branchcode => 'B2', + branchcode => 'B2', }; my $borrower3 = { borrowernumber => 3, - branchcode => 'B3', + branchcode => 'B3', }; # Baskets my $basket1 = { - basketno => 1, + basketno => 1, authorisedby => 1 }; my $basket2 = { - basketno => 2, + basketno => 2, authorisedby => 2, }; my $basket3 = { - basketno => 3, + basketno => 3, authorisedby => 3, - branch => 'B1' + branch => 'B1' }; my $basket4 = { - basketno => 4, + basketno => 4, authorisedby => 4, - branch => 'B1' + branch => 'B1' }; - -my $flags = { - acquisition => { - order_manage => 1 - } -}; +my $flags = { acquisition => { order_manage => 1 } }; ################# # Start testing # @@ -76,37 +71,23 @@ my $flags = { $AcqViewBaskets = 'all'; # Simple cases where user can't manage basket -ok( not CanUserManageBasket($borrower1, $basket1, {}) ); -ok( not CanUserManageBasket($borrower1, $basket1, { - acquisition => 0 -}) ); -ok( not CanUserManageBasket($borrower1, $basket1, { - acquisition => { - order_manage => 0 - } -}) ); +ok( not CanUserManageBasket( $borrower1, $basket1, {} ) ); +ok( not CanUserManageBasket( $borrower1, $basket1, { acquisition => 0 } ) ); +ok( not CanUserManageBasket( $borrower1, $basket1, { acquisition => { order_manage => 0 } } ) ); # Simple cases where user can manage basket -ok( CanUserManageBasket($borrower1, $basket1, { - superlibrarian => 1 -}) ); -ok( CanUserManageBasket($borrower1, $basket1, { - acquisition => 1 -}) ); -ok( CanUserManageBasket($borrower1, $basket1, { - acquisition => { - order_manage_all => 1 - } -}) ); +ok( CanUserManageBasket( $borrower1, $basket1, { superlibrarian => 1 } ) ); +ok( CanUserManageBasket( $borrower1, $basket1, { acquisition => 1 } ) ); +ok( CanUserManageBasket( $borrower1, $basket1, { acquisition => { order_manage_all => 1 } } ) ); -ok( CanUserManageBasket($borrower1, $basket1, $flags) ); -ok( CanUserManageBasket($borrower1, $basket2, $flags) ); -ok( CanUserManageBasket($borrower1, $basket3, $flags) ); -ok( CanUserManageBasket($borrower1, $basket4, $flags) ); -ok( CanUserManageBasket($borrower2, $basket1, $flags) ); -ok( CanUserManageBasket($borrower2, $basket2, $flags) ); -ok( CanUserManageBasket($borrower2, $basket3, $flags) ); -ok( CanUserManageBasket($borrower2, $basket4, $flags) ); +ok( CanUserManageBasket( $borrower1, $basket1, $flags ) ); +ok( CanUserManageBasket( $borrower1, $basket2, $flags ) ); +ok( CanUserManageBasket( $borrower1, $basket3, $flags ) ); +ok( CanUserManageBasket( $borrower1, $basket4, $flags ) ); +ok( CanUserManageBasket( $borrower2, $basket1, $flags ) ); +ok( CanUserManageBasket( $borrower2, $basket2, $flags ) ); +ok( CanUserManageBasket( $borrower2, $basket3, $flags ) ); +ok( CanUserManageBasket( $borrower2, $basket4, $flags ) ); # ------------------------- # AcqViewBaskets = 'branch' @@ -115,38 +96,25 @@ ok( CanUserManageBasket($borrower2, $basket4, $flags) ); $AcqViewBaskets = 'branch'; # Simple cases where user can't manage basket -ok( not CanUserManageBasket($borrower1, $basket1, {}) ); -ok( not CanUserManageBasket($borrower1, $basket1, { - acquisition => 0 -}) ); -ok( not CanUserManageBasket($borrower1, $basket1, { - acquisition => { - order_manage => 0 - } -}) ); +ok( not CanUserManageBasket( $borrower1, $basket1, {} ) ); +ok( not CanUserManageBasket( $borrower1, $basket1, { acquisition => 0 } ) ); +ok( not CanUserManageBasket( $borrower1, $basket1, { acquisition => { order_manage => 0 } } ) ); # Simple cases where user can manage basket -ok( CanUserManageBasket($borrower1, $basket1, { - superlibrarian => 1 -}) ); -ok( CanUserManageBasket($borrower1, $basket1, { - acquisition => 1 -}) ); -ok( CanUserManageBasket($borrower1, $basket1, { - acquisition => { - order_manage_all => 1 - } -}) ); +ok( CanUserManageBasket( $borrower1, $basket1, { superlibrarian => 1 } ) ); +ok( CanUserManageBasket( $borrower1, $basket1, { acquisition => 1 } ) ); +ok( CanUserManageBasket( $borrower1, $basket1, { acquisition => { order_manage_all => 1 } } ) ); + +ok( CanUserManageBasket( $borrower1, $basket1, $flags ) ); +ok( CanUserManageBasket( $borrower1, $basket2, $flags ) ); +ok( CanUserManageBasket( $borrower1, $basket3, $flags ) ); +ok( CanUserManageBasket( $borrower1, $basket4, $flags ) ); +ok( CanUserManageBasket( $borrower2, $basket1, $flags ) ); +ok( CanUserManageBasket( $borrower2, $basket2, $flags ) ); -ok( CanUserManageBasket($borrower1, $basket1, $flags) ); -ok( CanUserManageBasket($borrower1, $basket2, $flags) ); -ok( CanUserManageBasket($borrower1, $basket3, $flags) ); -ok( CanUserManageBasket($borrower1, $basket4, $flags) ); -ok( CanUserManageBasket($borrower2, $basket1, $flags) ); -ok( CanUserManageBasket($borrower2, $basket2, $flags) ); # borrower2 is not on the same branch as basket3 and basket4 -ok( not CanUserManageBasket($borrower2, $basket3, $flags) ); -ok( not CanUserManageBasket($borrower2, $basket4, $flags) ); +ok( not CanUserManageBasket( $borrower2, $basket3, $flags ) ); +ok( not CanUserManageBasket( $borrower2, $basket4, $flags ) ); # ----------------------- # AcqViewBaskets = 'user' @@ -155,43 +123,32 @@ ok( not CanUserManageBasket($borrower2, $basket4, $flags) ); $AcqViewBaskets = 'user'; # Simple cases where user can't manage basket -ok( not CanUserManageBasket($borrower1, $basket1, {}) ); -ok( not CanUserManageBasket($borrower1, $basket1, { - acquisition => 0 -}) ); -ok( not CanUserManageBasket($borrower1, $basket1, { - acquisition => { - order_manage => 0 - } -}) ); +ok( not CanUserManageBasket( $borrower1, $basket1, {} ) ); +ok( not CanUserManageBasket( $borrower1, $basket1, { acquisition => 0 } ) ); +ok( not CanUserManageBasket( $borrower1, $basket1, { acquisition => { order_manage => 0 } } ) ); # Simple cases where user can manage basket -ok( CanUserManageBasket($borrower1, $basket1, { - superlibrarian => 1 -}) ); -ok( CanUserManageBasket($borrower1, $basket1, { - acquisition => 1 -}) ); -ok( CanUserManageBasket($borrower1, $basket1, { - acquisition => { - order_manage_all => 1 - } -}) ); +ok( CanUserManageBasket( $borrower1, $basket1, { superlibrarian => 1 } ) ); +ok( CanUserManageBasket( $borrower1, $basket1, { acquisition => 1 } ) ); +ok( CanUserManageBasket( $borrower1, $basket1, { acquisition => { order_manage_all => 1 } } ) ); + +ok( CanUserManageBasket( $borrower1, $basket1, $flags ) ); +ok( CanUserManageBasket( $borrower1, $basket2, $flags ) ); -ok( CanUserManageBasket($borrower1, $basket1, $flags) ); -ok( CanUserManageBasket($borrower1, $basket2, $flags) ); # basket3 is not managed or created by borrower1 -ok( not CanUserManageBasket($borrower1, $basket3, $flags) ); -ok( CanUserManageBasket($borrower1, $basket4, $flags) ); +ok( not CanUserManageBasket( $borrower1, $basket3, $flags ) ); +ok( CanUserManageBasket( $borrower1, $basket4, $flags ) ); + # basket 1 is not managed or created by borrower2 -ok( not CanUserManageBasket($borrower2, $basket1, $flags) ); -ok( CanUserManageBasket($borrower2, $basket2, $flags) ); +ok( not CanUserManageBasket( $borrower2, $basket1, $flags ) ); +ok( CanUserManageBasket( $borrower2, $basket2, $flags ) ); + # basket 3 is not managed or created by borrower2 -ok( not CanUserManageBasket($borrower2, $basket3, $flags) ); -ok( CanUserManageBasket($borrower2, $basket4, $flags) ); +ok( not CanUserManageBasket( $borrower2, $basket3, $flags ) ); +ok( CanUserManageBasket( $borrower2, $basket4, $flags ) ); # basket 4 is not managed by borrower3 but by other borrowers -ok( not CanUserManageBasket($borrower3, $basket4, $flags) ); +ok( not CanUserManageBasket( $borrower3, $basket4, $flags ) ); # Mocked subs @@ -204,8 +161,8 @@ sub Mock_GetBasketUsers { # C4::Context->preference sub Mock_preference { - my ($self, $variable) = @_; - if (lc($variable) eq 'acqviewbaskets') { + my ( $self, $variable ) = @_; + if ( lc($variable) eq 'acqviewbaskets' ) { return $AcqViewBaskets; } } diff --git a/t/Auth.t b/t/Auth.t index d5b2f1e7fa..d45dfa5703 100755 --- a/t/Auth.t +++ b/t/Auth.t @@ -23,15 +23,21 @@ use C4::Auth qw( in_iprange ); $ENV{REMOTE_ADDR} = '192.168.1.30'; -ok(in_iprange("192.168.1.30"), 'simple single ip matching remote ip'); -ok(!in_iprange("192.168.1.31"), 'simple single ip not match remote ip'); -ok(in_iprange("192.168.1.1/24"), 'simple ip range/24 with remote ip in it'); -ok(!in_iprange("192.168.2.1/24"), 'simple ip range/24 with remote ip not in it'); -ok(in_iprange("192.168.2.1/16"), 'simple ip range/16 with remote ip in it'); -ok(!in_iprange("192.168.1.10-30"), 'invalidly represented IP range with remote ip in it'); -ok(in_iprange("192.168.1.10-192.168.1.30"), 'validly represented ip range with remote ip in it'); -ok(in_iprange("127.0.0.1 192.168.1.30 192.168.2.10-192.168.2.25"), 'multiple ips and ranges, including the remote ip'); -ok(!in_iprange("127.0.0.1 8.8.8.8 192.168.2.1/24 192.168.3.1/24 192.168.1.1-192.168.1.29"), "multiple ip and ip ranges, with the remote ip in none of them"); -ok(in_iprange(""), "blank list given, no preference set - implies everything goes through."); -ok(in_iprange(), "no list given, no preference set - implies everything goes through."); -ok(in_iprange("192.168.1.1/36"), 'simple invalid ip range/36 with remote ip in it'); +ok( in_iprange("192.168.1.30"), 'simple single ip matching remote ip' ); +ok( !in_iprange("192.168.1.31"), 'simple single ip not match remote ip' ); +ok( in_iprange("192.168.1.1/24"), 'simple ip range/24 with remote ip in it' ); +ok( !in_iprange("192.168.2.1/24"), 'simple ip range/24 with remote ip not in it' ); +ok( in_iprange("192.168.2.1/16"), 'simple ip range/16 with remote ip in it' ); +ok( !in_iprange("192.168.1.10-30"), 'invalidly represented IP range with remote ip in it' ); +ok( in_iprange("192.168.1.10-192.168.1.30"), 'validly represented ip range with remote ip in it' ); +ok( + in_iprange("127.0.0.1 192.168.1.30 192.168.2.10-192.168.2.25"), + 'multiple ips and ranges, including the remote ip' +); +ok( + !in_iprange("127.0.0.1 8.8.8.8 192.168.2.1/24 192.168.3.1/24 192.168.1.1-192.168.1.29"), + "multiple ip and ip ranges, with the remote ip in none of them" +); +ok( in_iprange(""), "blank list given, no preference set - implies everything goes through." ); +ok( in_iprange(), "no list given, no preference set - implies everything goes through." ); +ok( in_iprange("192.168.1.1/36"), 'simple invalid ip range/36 with remote ip in it' ); diff --git a/t/AuthoritiesMarc_MARC21.t b/t/AuthoritiesMarc_MARC21.t index 4ed2e1dfb3..eed55b6458 100755 --- a/t/AuthoritiesMarc_MARC21.t +++ b/t/AuthoritiesMarc_MARC21.t @@ -1,6 +1,6 @@ #!/usr/bin/perl # -# This Koha test module is a stub! +# This Koha test module is a stub! # Add more tests here!!! use strict; @@ -15,48 +15,60 @@ use MARC::Record; use C4::AuthoritiesMarc qw( FindDuplicateAuthority ); BEGIN { - use_ok('C4::AuthoritiesMarc::MARC21', qw( default_auth_type_location fix_marc21_auth_type_location )); + use_ok( 'C4::AuthoritiesMarc::MARC21', qw( default_auth_type_location fix_marc21_auth_type_location ) ); } my @result = C4::AuthoritiesMarc::MARC21::default_auth_type_location(); -ok($result[0] eq '942', "testing default_auth_type_location has first value '942'"); -ok($result[1] eq 'a', "testing default_auth_type_location has first value 'a'"); +ok( $result[0] eq '942', "testing default_auth_type_location has first value '942'" ); +ok( $result[1] eq 'a', "testing default_auth_type_location has first value 'a'" ); my $marc_record = MARC::Record->new(); -is(C4::AuthoritiesMarc::MARC21::fix_marc21_auth_type_location($marc_record, '', ''), undef, "testing fix_marc21_auth_type_location returns undef with empty MARC record"); +is( + C4::AuthoritiesMarc::MARC21::fix_marc21_auth_type_location( $marc_record, '', '' ), undef, + "testing fix_marc21_auth_type_location returns undef with empty MARC record" +); subtest "FindDuplicateAuthority tests" => sub { plan tests => 2; - my $zebra_search_module = Test::MockModule->new( 'C4::Search' ); - $zebra_search_module->mock( 'SimpleSearch', sub { - my $query = shift; - return ( undef, [$query] ); - }); - $zebra_search_module->mock( 'new_record_from_zebra', sub { - my (undef, $query ) = @_; - my $marc = MARC::Record->new; - $marc->append_fields( - MARC::Field->new( '001', $query ), - ); - return $marc; - }); - my $es_search_module = Test::MockModule->new( 'Koha::SearchEngine::Elasticsearch::Search' ); - $es_search_module->mock( 'simple_search_compat', sub { - my (undef, $query) = @_; - return ( undef, [$query] ); - }); + my $zebra_search_module = Test::MockModule->new('C4::Search'); + $zebra_search_module->mock( + 'SimpleSearch', + sub { + my $query = shift; + return ( undef, [$query] ); + } + ); + $zebra_search_module->mock( + 'new_record_from_zebra', + sub { + my ( undef, $query ) = @_; + my $marc = MARC::Record->new; + $marc->append_fields( + MARC::Field->new( '001', $query ), + ); + return $marc; + } + ); + my $es_search_module = Test::MockModule->new('Koha::SearchEngine::Elasticsearch::Search'); + $es_search_module->mock( + 'simple_search_compat', + sub { + my ( undef, $query ) = @_; + return ( undef, [$query] ); + } + ); my $record = MARC::Record->new; $record->append_fields( - MARC::Field->new('155', '', '', a => 'Potato' ), + MARC::Field->new( '155', '', '', a => 'Potato' ), ); t::lib::Mocks::mock_preference( 'SearchEngine', 'Zebra' ); my ($query) = FindDuplicateAuthority( $record, "GENRE/FORM" ); - is( $query, q{at:"GENRE/FORM" AND he:"Potato"}, "Query formed correctly for Zebra"); + is( $query, q{at:"GENRE/FORM" AND he:"Potato"}, "Query formed correctly for Zebra" ); t::lib::Mocks::mock_preference( 'SearchEngine', 'Elasticsearch' ); ($query) = FindDuplicateAuthority( $record, "GENRE/FORM" ); - is( $query, q{at:"GENRE/FORM" AND he:"Potato"}, "Query formed correctly for Elasticsearch"); + is( $query, q{at:"GENRE/FORM" AND he:"Potato"}, "Query formed correctly for Elasticsearch" ); }; diff --git a/t/AuthoritiesMarc_UNIMARC.t b/t/AuthoritiesMarc_UNIMARC.t index 84febb8bbf..1779e4cb10 100755 --- a/t/AuthoritiesMarc_UNIMARC.t +++ b/t/AuthoritiesMarc_UNIMARC.t @@ -1,6 +1,6 @@ #!/usr/bin/perl # -# This Koha test module is a stub! +# This Koha test module is a stub! # Add more tests here!!! use strict; @@ -9,8 +9,8 @@ use warnings; use Test::More tests => 2; BEGIN { - use_ok('C4::AuthoritiesMarc::UNIMARC', qw( default_auth_type_location )); + use_ok( 'C4::AuthoritiesMarc::UNIMARC', qw( default_auth_type_location ) ); } my @test = C4::AuthoritiesMarc::UNIMARC::default_auth_type_location(); -ok(($test[0] == 152) && ($test[1] eq 'b'), "correct variables being returned"); +ok( ( $test[0] == 152 ) && ( $test[1] eq 'b' ), "correct variables being returned" ); diff --git a/t/Barcodes_EAN13.t b/t/Barcodes_EAN13.t index c3c9046a4c..664a80e2f8 100755 --- a/t/Barcodes_EAN13.t +++ b/t/Barcodes_EAN13.t @@ -8,5 +8,5 @@ use warnings; use Test::More tests => 1; BEGIN { - use_ok('C4::Barcodes::EAN13'); + use_ok('C4::Barcodes::EAN13'); } diff --git a/t/Barcodes_annual.t b/t/Barcodes_annual.t index b89d207e42..8c4de3e211 100755 --- a/t/Barcodes_annual.t +++ b/t/Barcodes_annual.t @@ -1,6 +1,6 @@ #!/usr/bin/perl # -# This Koha test module is a stub! +# This Koha test module is a stub! # Add more tests here!!! use strict; @@ -9,6 +9,6 @@ use warnings; use Test::More tests => 1; BEGIN { - use_ok('C4::Barcodes::annual'); + use_ok('C4::Barcodes::annual'); } diff --git a/t/Barcodes_hbyymmincr.t b/t/Barcodes_hbyymmincr.t index a2377d3add..fa5bc89b1d 100755 --- a/t/Barcodes_hbyymmincr.t +++ b/t/Barcodes_hbyymmincr.t @@ -1,6 +1,6 @@ #!/usr/bin/perl # -# This Koha test module is a stub! +# This Koha test module is a stub! # Add more tests here!!! use strict; @@ -9,6 +9,6 @@ use warnings; use Test::More tests => 1; BEGIN { - use_ok('C4::Barcodes::hbyymmincr'); + use_ok('C4::Barcodes::hbyymmincr'); } diff --git a/t/Barcodes_incremental.t b/t/Barcodes_incremental.t index 1bde5d3638..ca9f496499 100755 --- a/t/Barcodes_incremental.t +++ b/t/Barcodes_incremental.t @@ -1,6 +1,6 @@ #!/usr/bin/perl # -# This Koha test module is a stub! +# This Koha test module is a stub! # Add more tests here!!! use strict; @@ -9,6 +9,6 @@ use warnings; use Test::More tests => 1; BEGIN { - use_ok('C4::Barcodes::incremental'); + use_ok('C4::Barcodes::incremental'); } diff --git a/t/Biblio.t b/t/Biblio.t index 3fbf90402a..a521a52564 100755 --- a/t/Biblio.t +++ b/t/Biblio.t @@ -23,8 +23,10 @@ use Test::Warn; plan tests => 32; - -use_ok('C4::Biblio', qw( AddBiblio ModBiblio BiblioAutoLink LinkBibHeadingsToAuthorities GetMarcPrice GetMarcQuantity GetMarcISBN GetMarcISSN GetMarcSubjects GetMarcUrls GetMarcSeries TransformMarcToKoha ModBiblioMarc RemoveAllNsb UpdateTotalIssues )); +use_ok( + 'C4::Biblio', + qw( AddBiblio ModBiblio BiblioAutoLink LinkBibHeadingsToAuthorities GetMarcPrice GetMarcQuantity GetMarcISBN GetMarcISSN GetMarcSubjects GetMarcUrls GetMarcSeries TransformMarcToKoha ModBiblioMarc RemoveAllNsb UpdateTotalIssues ) +); my $db = Test::MockModule->new('Koha::Database'); $db->mock( _new_schema => sub { return Schema(); } ); @@ -32,102 +34,100 @@ $db->mock( _new_schema => sub { return Schema(); } ); my @arr; my $ret; -warning_is { @arr = AddBiblio(undef, q{}) } - { carped => 'AddBiblio called with undefined record'}, - "AddBiblio returns carped warning on undef record"; +warning_is { @arr = AddBiblio( undef, q{} ) } +{ carped => 'AddBiblio called with undefined record' }, + "AddBiblio returns carped warning on undef record"; my $elements = @arr; -is($elements, 0, 'Add Biblio returns empty array for undef record'); +is( $elements, 0, 'Add Biblio returns empty array for undef record' ); -warning_is { $ret = ModBiblio(undef, 0, '') } - { carped => 'No record passed to ModBiblio'}, - "ModBiblio returns carped warning on undef record"; +warning_is { $ret = ModBiblio( undef, 0, '' ) } +{ carped => 'No record passed to ModBiblio' }, + "ModBiblio returns carped warning on undef record"; -is( $ret, 0, 'ModBiblio returns zero if not passed rec'); +is( $ret, 0, 'ModBiblio returns zero if not passed rec' ); -warning_is { $ret = BiblioAutoLink(undef, q{}) } - { carped => 'Undefined record passed to BiblioAutoLink'}, - "BiblioAutoLink returns carped warning on undef record"; +warning_is { $ret = BiblioAutoLink( undef, q{} ) } +{ carped => 'Undefined record passed to BiblioAutoLink' }, + "BiblioAutoLink returns carped warning on undef record"; -is( $ret, 0, 'BiblioAutoLink returns zero if not passed rec'); +is( $ret, 0, 'BiblioAutoLink returns zero if not passed rec' ); -warning_is { @arr = LinkBibHeadingsToAuthorities(q{}, q{}) } - { carped => 'LinkBibHeadingsToAuthorities called on undefined bib record'}, - "LinkBibHeadingsToAuthorities returns carped warning on undef record"; +warning_is { @arr = LinkBibHeadingsToAuthorities( q{}, q{} ) } +{ carped => 'LinkBibHeadingsToAuthorities called on undefined bib record' }, + "LinkBibHeadingsToAuthorities returns carped warning on undef record"; -is($arr[0], 0, 'LinkBibHeadingsToAuthorities correct error return'); +is( $arr[0], 0, 'LinkBibHeadingsToAuthorities correct error return' ); -warning_is { $ret = GetMarcPrice(undef, 'MARC21') } - { carped => 'GetMarcPrice called on undefined record'}, - "GetMarcPrice returns carped warning on undef record"; +warning_is { $ret = GetMarcPrice( undef, 'MARC21' ) } +{ carped => 'GetMarcPrice called on undefined record' }, + "GetMarcPrice returns carped warning on undef record"; -ok( !defined $ret, 'GetMarcPrice returns undef if not passed rec'); +ok( !defined $ret, 'GetMarcPrice returns undef if not passed rec' ); -warning_is { $ret = GetMarcQuantity(undef, 'MARC21') } - { carped => 'GetMarcQuantity called on undefined record'}, - "GetMarcQuantity returns carped warning on undef record"; +warning_is { $ret = GetMarcQuantity( undef, 'MARC21' ) } +{ carped => 'GetMarcQuantity called on undefined record' }, + "GetMarcQuantity returns carped warning on undef record"; -ok( !defined $ret, 'GetMarcQuantity returns undef if not passed rec'); +ok( !defined $ret, 'GetMarcQuantity returns undef if not passed rec' ); warning_is { $ret = GetMarcISBN() } - { carped => 'GetMarcISBN called on undefined record'}, - "GetMarcISBN returns carped warning on undef record"; +{ carped => 'GetMarcISBN called on undefined record' }, + "GetMarcISBN returns carped warning on undef record"; -ok( !defined $ret, 'GetMarcISBN returns undef if not passed rec'); +ok( !defined $ret, 'GetMarcISBN returns undef if not passed rec' ); warning_is { $ret = GetMarcISSN() } - { carped => 'GetMarcISSN called on undefined record'}, - "GetMarcISSN returns carped warning on undef record"; +{ carped => 'GetMarcISSN called on undefined record' }, + "GetMarcISSN returns carped warning on undef record"; -ok( !defined $ret, 'GetMarcISSN returns undef if not passed rec'); +ok( !defined $ret, 'GetMarcISSN returns undef if not passed rec' ); warning_is { $ret = GetMarcSubjects() } - { carped => 'GetMarcSubjects called on undefined record'}, - "GetMarcSubjects returns carped warning on undef record"; +{ carped => 'GetMarcSubjects called on undefined record' }, + "GetMarcSubjects returns carped warning on undef record"; -ok( !defined $ret, 'GetMarcSubjects returns undef if not passed rec'); +ok( !defined $ret, 'GetMarcSubjects returns undef if not passed rec' ); warning_is { $ret = GetMarcUrls() } - { carped => 'GetMarcUrls called on undefined record'}, - "GetMarcUrls returns carped warning on undef record"; +{ carped => 'GetMarcUrls called on undefined record' }, + "GetMarcUrls returns carped warning on undef record"; -ok( !defined $ret, 'GetMarcUrls returns undef if not passed rec'); +ok( !defined $ret, 'GetMarcUrls returns undef if not passed rec' ); warning_is { $ret = GetMarcSeries() } - { carped => 'GetMarcSeries called on undefined record'}, - "GetMarcSeries returns carped warning on undef record"; +{ carped => 'GetMarcSeries called on undefined record' }, + "GetMarcSeries returns carped warning on undef record"; -ok( !defined $ret, 'GetMarcSeries returns undef if not passed rec'); +ok( !defined $ret, 'GetMarcSeries returns undef if not passed rec' ); my $hash_ref; -warning_is { $hash_ref = TransformMarcToKoha( undef) } - { carped => 'TransformMarcToKoha called with undefined record'}, - "TransformMarcToKoha returns carped warning on undef record"; +warning_is { $hash_ref = TransformMarcToKoha(undef) } +{ carped => 'TransformMarcToKoha called with undefined record' }, + "TransformMarcToKoha returns carped warning on undef record"; -isa_ok( $hash_ref, 'HASH'); +isa_ok( $hash_ref, 'HASH' ); $elements = keys %{$hash_ref}; -is($elements, 0, 'Empty hashref returned for undefined record in TransformMarcToKoha'); +is( $elements, 0, 'Empty hashref returned for undefined record in TransformMarcToKoha' ); warning_is { $ret = ModBiblioMarc() } - { carped => 'ModBiblioMarc passed an undefined record'}, - "ModBiblioMarc returns carped warning on undef record"; +{ carped => 'ModBiblioMarc passed an undefined record' }, + "ModBiblioMarc returns carped warning on undef record"; -ok( !defined $ret, 'ModBiblioMarc returns undef if not passed rec'); +ok( !defined $ret, 'ModBiblioMarc returns undef if not passed rec' ); warning_is { $ret = RemoveAllNsb() } - { carped => 'RemoveAllNsb called with undefined record'}, - "RemoveAllNsb returns carped warning on undef record"; - -ok( !defined $ret, 'RemoveAllNsb returns undef if not passed rec'); +{ carped => 'RemoveAllNsb called with undefined record' }, + "RemoveAllNsb returns carped warning on undef record"; +ok( !defined $ret, 'RemoveAllNsb returns undef if not passed rec' ); warnings_like { $ret = UpdateTotalIssues() } - [ - { carped => qr/UpdateTotalIssues could not get biblio/ } ], +[ { carped => qr/UpdateTotalIssues could not get biblio/ } ], "UpdateTotalIssues returns carped warnings if biblio record does not exist"; -ok( !defined $ret, 'UpdateTotalIssues returns carped warning if biblio record does not exist'); +ok( !defined $ret, 'UpdateTotalIssues returns carped warning if biblio record does not exist' ); diff --git a/t/Biblio/TransformHtmlToXml.t b/t/Biblio/TransformHtmlToXml.t index 0f10c28255..6d2de191e3 100755 --- a/t/Biblio/TransformHtmlToXml.t +++ b/t/Biblio/TransformHtmlToXml.t @@ -24,38 +24,40 @@ use XML::Simple; use C4::Biblio qw( TransformHtmlToXml ); - sub run_tests { my ($marc_flavour) = @_; - t::lib::Mocks::mock_preference('marcflavour', $marc_flavour); + t::lib::Mocks::mock_preference( 'marcflavour', $marc_flavour ); my ( $tags, $subfields ); if ( $marc_flavour eq 'UNIMARC' ) { - $tags= [ '001', '600', '200', '200', '400' ]; - $subfields = [ '', 'a', 'a', 'c', 'a' ]; + $tags = [ '001', '600', '200', '200', '400' ]; + $subfields = [ '', 'a', 'a', 'c', 'a' ]; } else { - $tags= [ '001', '100', '245', '245', '400' ]; - $subfields = [ '', 'a', 'a', 'c', 'a' ]; + $tags = [ '001', '100', '245', '245', '400' ]; + $subfields = [ '', 'a', 'a', 'c', 'a' ]; } my $values = [ '12345', 'author', 'title', 'resp', '' ]; - my $ind = [ ' ', '00', ' 9', ' ', ' ' ]; + my $ind = [ ' ', '00', ' 9', ' ', ' ' ]; - my $xml = TransformHtmlToXml( $tags, $subfields, $values, $ind, undef, $marc_flavour ); - my $xmlh = XML::Simple->new->XMLin( $xml ); + my $xml = TransformHtmlToXml( $tags, $subfields, $values, $ind, undef, $marc_flavour ); + my $xmlh = XML::Simple->new->XMLin($xml); # check number of controlfields is( ref $xmlh->{record}->{controlfield}, 'HASH', 'One controlfield' ); + # check datafields - my $cnt = @{$xmlh->{record}->{datafield}}; + my $cnt = @{ $xmlh->{record}->{datafield} }; if ( $marc_flavour eq 'UNIMARC' ) { - is( $cnt, 3, 'Three datafields' ); # 100$a is automatically created + is( $cnt, 3, 'Three datafields' ); # 100$a is automatically created } else { is( $cnt, 2, 'Two datafields' ); } + # check value of 245c is( $xmlh->{record}->{datafield}->[1]->{subfield}->[1]->{content}, 'resp', 'Check value' ); + # check second indicator of 245 is( $xmlh->{record}->{datafield}->[1]->{ind2}, '9', 'Check indicator' ); } diff --git a/t/Biblio2.t b/t/Biblio2.t index 858bac89bf..d015926a9f 100755 --- a/t/Biblio2.t +++ b/t/Biblio2.t @@ -9,47 +9,53 @@ use MARC::Record; use C4::Biblio qw( GetMarcFromKohaField ); subtest "_koha_marc_update_bib_ids basic Field", \&_koha_marc_update_bib_ids_simple; + sub _koha_marc_update_bib_ids_simple { my $module = Test::MockModule->new('C4::Biblio'); - $module->mock('GetMarcFromKohaField', sub { + $module->mock( + 'GetMarcFromKohaField', + sub { my ($source) = @_; - return ('999','c') if $source eq 'biblio.biblionumber'; - return ('999','d') if $source eq 'biblioitems.biblioitemnumber'; + return ( '999', 'c' ) if $source eq 'biblio.biblionumber'; + return ( '999', 'd' ) if $source eq 'biblioitems.biblioitemnumber'; } ); my $r = MARC::Record->new(); - C4::Biblio::_koha_marc_update_bib_ids($r, undef, 10, 20); - is($r->subfield('999', 'c'), 10, 'Biblionumber'); - is($r->subfield('999', 'd'), 20, 'Biblioitemnumber'); + C4::Biblio::_koha_marc_update_bib_ids( $r, undef, 10, 20 ); + is( $r->subfield( '999', 'c' ), 10, 'Biblionumber' ); + is( $r->subfield( '999', 'd' ), 20, 'Biblioitemnumber' ); - C4::Biblio::_koha_marc_update_bib_ids($r, undef, 10, 20); + C4::Biblio::_koha_marc_update_bib_ids( $r, undef, 10, 20 ); my @f = $r->field('999'); - is(scalar(@f), 1, 'Field not duplicated'); - is($r->subfield('999', 'c'), 10, 'Biblionumber'); - is($r->subfield('999', 'd'), 20, 'Biblioitemnumber'); + is( scalar(@f), 1, 'Field not duplicated' ); + is( $r->subfield( '999', 'c' ), 10, 'Biblionumber' ); + is( $r->subfield( '999', 'd' ), 20, 'Biblioitemnumber' ); } subtest "_koha_marc_update_bib_ids ControlField", \&_koha_marc_update_bib_ids_control; + sub _koha_marc_update_bib_ids_control { my $module = Test::MockModule->new('C4::Biblio'); - $module->mock('GetMarcFromKohaField', sub { + $module->mock( + 'GetMarcFromKohaField', + sub { my ($source) = @_; - return ('001',undef) if $source eq 'biblio.biblionumber'; - return ('004',undef) if $source eq 'biblioitems.biblioitemnumber'; + return ( '001', undef ) if $source eq 'biblio.biblionumber'; + return ( '004', undef ) if $source eq 'biblioitems.biblioitemnumber'; } ); my $r = MARC::Record->new(); - C4::Biblio::_koha_marc_update_bib_ids($r, undef, 10, 20); - is($r->field('001')->data(), 10, 'Biblionumber to control field'); - is($r->field('004')->data(), 20, 'Biblioitemnumber to control field'); + C4::Biblio::_koha_marc_update_bib_ids( $r, undef, 10, 20 ); + is( $r->field('001')->data(), 10, 'Biblionumber to control field' ); + is( $r->field('004')->data(), 20, 'Biblioitemnumber to control field' ); - C4::Biblio::_koha_marc_update_bib_ids($r, undef, 10, 20); + C4::Biblio::_koha_marc_update_bib_ids( $r, undef, 10, 20 ); my @f = $r->field('001'); - is(scalar(@f), 1, 'Control field not duplicated'); - is($r->field('001')->data(), 10, 'Biblionumber to control field'); - is($r->field('004')->data(), 20, 'Biblioitemnumber to control field'); + is( scalar(@f), 1, 'Control field not duplicated' ); + is( $r->field('001')->data(), 10, 'Biblionumber to control field' ); + is( $r->field('004')->data(), 20, 'Biblioitemnumber to control field' ); } done_testing(); diff --git a/t/Budgets.t b/t/Budgets.t index 96d0af4885..daa217f6c0 100755 --- a/t/Budgets.t +++ b/t/Budgets.t @@ -1,6 +1,6 @@ #!/usr/bin/perl # -# This Koha test module is a stub! +# This Koha test module is a stub! # Add more tests here!!! use strict; @@ -9,6 +9,6 @@ use warnings; use Test::More tests => 1; BEGIN { - use_ok('C4::Budgets'); + use_ok('C4::Budgets'); } diff --git a/t/Budgets/CanUserModifyBudget.t b/t/Budgets/CanUserModifyBudget.t index b2c8454d71..83905a18c1 100755 --- a/t/Budgets/CanUserModifyBudget.t +++ b/t/Budgets/CanUserModifyBudget.t @@ -11,15 +11,15 @@ local $SIG{__WARN__} = sub { warn $_[0] unless $_[0] =~ /redefined/ }; *C4::Budgets::GetBudgetUsers = \&Mock_GetBudgetUsers; my %budgetusers = ( - 1 => [], - 2 => [1], - 3 => [2], - 4 => [3], - 5 => [], - 6 => [1], - 7 => [2], - 8 => [3], - 9 => [], + 1 => [], + 2 => [1], + 3 => [2], + 4 => [3], + 5 => [], + 6 => [1], + 7 => [2], + 8 => [3], + 9 => [], 10 => [1], 11 => [2], 12 => [3], @@ -29,299 +29,288 @@ my %budgetusers = ( 16 => [3], ); -my $borrower1 = { - borrowernumber => 1 -}; -my $borrower2 = { - borrowernumber => 2 -}; +my $borrower1 = { borrowernumber => 1 }; +my $borrower2 = { borrowernumber => 2 }; my $budget1 = { - budget_id => 1, + budget_id => 1, budget_permission => 0, - budget_owner_id => undef, + budget_owner_id => undef, budget_branchcode => undef, }; my $budget2 = { - budget_id => 2, + budget_id => 2, budget_permission => 0, - budget_owner_id => undef, + budget_owner_id => undef, budget_branchcode => 'B1', }; my $budget3 = { - budget_id => 3, + budget_id => 3, budget_permission => 0, - budget_owner_id => 1, + budget_owner_id => 1, budget_branchcode => undef, }; my $budget4 = { - budget_id => 4, + budget_id => 4, budget_permission => 0, - budget_owner_id => 1, + budget_owner_id => 1, budget_branchcode => 'B1', }; my $budget5 = { - budget_id => 5, + budget_id => 5, budget_permission => 1, - budget_owner_id => undef, + budget_owner_id => undef, budget_branchcode => undef, }; my $budget6 = { - budget_id => 6, + budget_id => 6, budget_permission => 1, - budget_owner_id => undef, + budget_owner_id => undef, budget_branchcode => 'B1', }; my $budget7 = { - budget_id => 7, + budget_id => 7, budget_permission => 1, - budget_owner_id => 1, + budget_owner_id => 1, budget_branchcode => undef, }; my $budget8 = { - budget_id => 8, + budget_id => 8, budget_permission => 1, - budget_owner_id => 1, + budget_owner_id => 1, budget_branchcode => 'B1', }; my $budget9 = { - budget_id => 9, + budget_id => 9, budget_permission => 2, - budget_owner_id => undef, + budget_owner_id => undef, budget_branchcode => undef, }; my $budget10 = { - budget_id => 10, + budget_id => 10, budget_permission => 2, - budget_owner_id => undef, + budget_owner_id => undef, budget_branchcode => 'B1', }; my $budget11 = { - budget_id => 11, + budget_id => 11, budget_permission => 2, - budget_owner_id => 1, + budget_owner_id => 1, budget_branchcode => undef, }; my $budget12 = { - budget_id => 12, + budget_id => 12, budget_permission => 2, - budget_owner_id => 1, + budget_owner_id => 1, budget_branchcode => 'B1', }; my $budget13 = { - budget_id => 13, + budget_id => 13, budget_permission => 3, - budget_owner_id => undef, + budget_owner_id => undef, budget_branchcode => undef, }; my $budget14 = { - budget_id => 14, + budget_id => 14, budget_permission => 3, - budget_owner_id => undef, + budget_owner_id => undef, budget_branchcode => 'B1', }; my $budget15 = { - budget_id => 15, + budget_id => 15, budget_permission => 3, - budget_owner_id => 1, + budget_owner_id => 1, budget_branchcode => undef, }; my $budget16 = { - budget_id => 16, + budget_id => 16, budget_permission => 3, - budget_owner_id => 1, + budget_owner_id => 1, budget_branchcode => 'B1', }; ok( !CanUserModifyBudget( 0, undef, {} ), "CanUserModifyBudget evaluates to false if DB user is passed" ); -ok (CanUserModifyBudget($borrower1, $budget1, {superlibrarian => 1})); -ok (CanUserModifyBudget($borrower1, $budget1, { - acquisition => { - budget_manage_all => 1 - } -})); -ok (CanUserModifyBudget($borrower1, $budget1, {acquisition => 1})); +ok( CanUserModifyBudget( $borrower1, $budget1, { superlibrarian => 1 } ) ); +ok( CanUserModifyBudget( $borrower1, $budget1, { acquisition => { budget_manage_all => 1 } } ) ); +ok( CanUserModifyBudget( $borrower1, $budget1, { acquisition => 1 } ) ); -ok (!CanUserModifyBudget($borrower1, $budget1, {})); -ok (!CanUserModifyBudget($borrower1, $budget1, {acquisition => 0})); +ok( !CanUserModifyBudget( $borrower1, $budget1, {} ) ); +ok( !CanUserModifyBudget( $borrower1, $budget1, { acquisition => 0 } ) ); -my $flags = {acquisition => {budget_modify => 1}}; +my $flags = { acquisition => { budget_modify => 1 } }; -t::lib::Mocks::mock_userenv({ branchcode => 'B1' }); +t::lib::Mocks::mock_userenv( { branchcode => 'B1' } ); # Restriction is 'none' -ok (CanUserModifyBudget($borrower1, $budget1, $flags)); -ok (CanUserModifyBudget($borrower1, $budget2, $flags)); -ok (CanUserModifyBudget($borrower1, $budget3, $flags)); -ok (CanUserModifyBudget($borrower1, $budget4, $flags)); -ok (CanUserModifyBudget($borrower2, $budget1, $flags)); -ok (CanUserModifyBudget($borrower2, $budget2, $flags)); -ok (CanUserModifyBudget($borrower2, $budget3, $flags)); -ok (CanUserModifyBudget($borrower2, $budget4, $flags)); +ok( CanUserModifyBudget( $borrower1, $budget1, $flags ) ); +ok( CanUserModifyBudget( $borrower1, $budget2, $flags ) ); +ok( CanUserModifyBudget( $borrower1, $budget3, $flags ) ); +ok( CanUserModifyBudget( $borrower1, $budget4, $flags ) ); +ok( CanUserModifyBudget( $borrower2, $budget1, $flags ) ); +ok( CanUserModifyBudget( $borrower2, $budget2, $flags ) ); +ok( CanUserModifyBudget( $borrower2, $budget3, $flags ) ); +ok( CanUserModifyBudget( $borrower2, $budget4, $flags ) ); # Restriction is 'owner' -ok (CanUserModifyBudget($borrower1, $budget5, $flags)); -ok (CanUserModifyBudget($borrower1, $budget6, $flags)); -ok (CanUserModifyBudget($borrower1, $budget7, $flags)); -ok (CanUserModifyBudget($borrower1, $budget8, $flags)); -ok (CanUserModifyBudget($borrower2, $budget5, $flags)); -ok (CanUserModifyBudget($borrower2, $budget6, $flags)); -ok (!CanUserModifyBudget($borrower2, $budget7, $flags)); -ok (!CanUserModifyBudget($borrower2, $budget8, $flags)); +ok( CanUserModifyBudget( $borrower1, $budget5, $flags ) ); +ok( CanUserModifyBudget( $borrower1, $budget6, $flags ) ); +ok( CanUserModifyBudget( $borrower1, $budget7, $flags ) ); +ok( CanUserModifyBudget( $borrower1, $budget8, $flags ) ); +ok( CanUserModifyBudget( $borrower2, $budget5, $flags ) ); +ok( CanUserModifyBudget( $borrower2, $budget6, $flags ) ); +ok( !CanUserModifyBudget( $borrower2, $budget7, $flags ) ); +ok( !CanUserModifyBudget( $borrower2, $budget8, $flags ) ); # Restriction is 'owner, users and library' -ok (CanUserModifyBudget($borrower1, $budget9, $flags)); -ok (CanUserModifyBudget($borrower1, $budget10, $flags)); -ok (CanUserModifyBudget($borrower1, $budget11, $flags)); -ok (CanUserModifyBudget($borrower1, $budget12, $flags)); -ok (CanUserModifyBudget($borrower2, $budget9, $flags)); -ok (CanUserModifyBudget($borrower2, $budget10, $flags)); -ok (CanUserModifyBudget($borrower2, $budget11, $flags)); -ok (CanUserModifyBudget($borrower2, $budget12, $flags)); +ok( CanUserModifyBudget( $borrower1, $budget9, $flags ) ); +ok( CanUserModifyBudget( $borrower1, $budget10, $flags ) ); +ok( CanUserModifyBudget( $borrower1, $budget11, $flags ) ); +ok( CanUserModifyBudget( $borrower1, $budget12, $flags ) ); +ok( CanUserModifyBudget( $borrower2, $budget9, $flags ) ); +ok( CanUserModifyBudget( $borrower2, $budget10, $flags ) ); +ok( CanUserModifyBudget( $borrower2, $budget11, $flags ) ); +ok( CanUserModifyBudget( $borrower2, $budget12, $flags ) ); # Restriction is 'owner and users' -ok (!CanUserModifyBudget($borrower1, $budget13, $flags)); # no owner, no user -ok (CanUserModifyBudget($borrower1, $budget14, $flags)); -ok (CanUserModifyBudget($borrower1, $budget15, $flags)); -ok (CanUserModifyBudget($borrower1, $budget16, $flags)); -ok (!CanUserModifyBudget($borrower2, $budget13, $flags)); # no owner, no user -ok (!CanUserModifyBudget($borrower2, $budget14, $flags)); # No owner and user list contains borrower1 -ok (CanUserModifyBudget($borrower2, $budget15, $flags)); -ok (!CanUserModifyBudget($borrower2, $budget16, $flags)); +ok( !CanUserModifyBudget( $borrower1, $budget13, $flags ) ); # no owner, no user +ok( CanUserModifyBudget( $borrower1, $budget14, $flags ) ); +ok( CanUserModifyBudget( $borrower1, $budget15, $flags ) ); +ok( CanUserModifyBudget( $borrower1, $budget16, $flags ) ); +ok( !CanUserModifyBudget( $borrower2, $budget13, $flags ) ); # no owner, no user +ok( !CanUserModifyBudget( $borrower2, $budget14, $flags ) ); # No owner and user list contains borrower1 +ok( CanUserModifyBudget( $borrower2, $budget15, $flags ) ); +ok( !CanUserModifyBudget( $borrower2, $budget16, $flags ) ); -t::lib::Mocks::mock_userenv({ branchcode => 'B2' }); +t::lib::Mocks::mock_userenv( { branchcode => 'B2' } ); # Restriction is 'none' -ok (CanUserModifyBudget($borrower1, $budget1, $flags)); -ok (CanUserModifyBudget($borrower1, $budget2, $flags)); -ok (CanUserModifyBudget($borrower1, $budget3, $flags)); -ok (CanUserModifyBudget($borrower1, $budget4, $flags)); -ok (CanUserModifyBudget($borrower2, $budget1, $flags)); -ok (CanUserModifyBudget($borrower2, $budget2, $flags)); -ok (CanUserModifyBudget($borrower2, $budget3, $flags)); -ok (CanUserModifyBudget($borrower2, $budget4, $flags)); +ok( CanUserModifyBudget( $borrower1, $budget1, $flags ) ); +ok( CanUserModifyBudget( $borrower1, $budget2, $flags ) ); +ok( CanUserModifyBudget( $borrower1, $budget3, $flags ) ); +ok( CanUserModifyBudget( $borrower1, $budget4, $flags ) ); +ok( CanUserModifyBudget( $borrower2, $budget1, $flags ) ); +ok( CanUserModifyBudget( $borrower2, $budget2, $flags ) ); +ok( CanUserModifyBudget( $borrower2, $budget3, $flags ) ); +ok( CanUserModifyBudget( $borrower2, $budget4, $flags ) ); # Restriction is 'owner' -ok (CanUserModifyBudget($borrower1, $budget5, $flags)); -ok (CanUserModifyBudget($borrower1, $budget6, $flags)); -ok (CanUserModifyBudget($borrower1, $budget7, $flags)); -ok (CanUserModifyBudget($borrower1, $budget8, $flags)); -ok (CanUserModifyBudget($borrower2, $budget5, $flags)); -ok (CanUserModifyBudget($borrower2, $budget6, $flags)); -ok (!CanUserModifyBudget($borrower2, $budget7, $flags)); -ok (!CanUserModifyBudget($borrower2, $budget8, $flags)); +ok( CanUserModifyBudget( $borrower1, $budget5, $flags ) ); +ok( CanUserModifyBudget( $borrower1, $budget6, $flags ) ); +ok( CanUserModifyBudget( $borrower1, $budget7, $flags ) ); +ok( CanUserModifyBudget( $borrower1, $budget8, $flags ) ); +ok( CanUserModifyBudget( $borrower2, $budget5, $flags ) ); +ok( CanUserModifyBudget( $borrower2, $budget6, $flags ) ); +ok( !CanUserModifyBudget( $borrower2, $budget7, $flags ) ); +ok( !CanUserModifyBudget( $borrower2, $budget8, $flags ) ); # Restriction is 'owner, users and library' -ok (CanUserModifyBudget($borrower1, $budget9, $flags)); -ok (CanUserModifyBudget($borrower1, $budget10, $flags)); -ok (CanUserModifyBudget($borrower1, $budget11, $flags)); -ok (CanUserModifyBudget($borrower1, $budget12, $flags)); -ok (CanUserModifyBudget($borrower2, $budget9, $flags)); -ok (!CanUserModifyBudget($borrower2, $budget10, $flags)); # Limited to library B1 -ok (CanUserModifyBudget($borrower2, $budget11, $flags)); -ok (!CanUserModifyBudget($borrower2, $budget12, $flags)); +ok( CanUserModifyBudget( $borrower1, $budget9, $flags ) ); +ok( CanUserModifyBudget( $borrower1, $budget10, $flags ) ); +ok( CanUserModifyBudget( $borrower1, $budget11, $flags ) ); +ok( CanUserModifyBudget( $borrower1, $budget12, $flags ) ); +ok( CanUserModifyBudget( $borrower2, $budget9, $flags ) ); +ok( !CanUserModifyBudget( $borrower2, $budget10, $flags ) ); # Limited to library B1 +ok( CanUserModifyBudget( $borrower2, $budget11, $flags ) ); +ok( !CanUserModifyBudget( $borrower2, $budget12, $flags ) ); # Restriction is 'owner and users' -ok (!CanUserModifyBudget($borrower1, $budget13, $flags)); # No owner, no user -ok (CanUserModifyBudget($borrower1, $budget14, $flags)); -ok (CanUserModifyBudget($borrower1, $budget15, $flags)); -ok (CanUserModifyBudget($borrower1, $budget16, $flags)); -ok (!CanUserModifyBudget($borrower2, $budget13, $flags)); # No owner, no user -ok (!CanUserModifyBudget($borrower2, $budget14, $flags)); # No owner and user list contains borrower1 -ok (CanUserModifyBudget($borrower2, $budget15, $flags)); -ok (!CanUserModifyBudget($borrower2, $budget16, $flags)); - +ok( !CanUserModifyBudget( $borrower1, $budget13, $flags ) ); # No owner, no user +ok( CanUserModifyBudget( $borrower1, $budget14, $flags ) ); +ok( CanUserModifyBudget( $borrower1, $budget15, $flags ) ); +ok( CanUserModifyBudget( $borrower1, $budget16, $flags ) ); +ok( !CanUserModifyBudget( $borrower2, $budget13, $flags ) ); # No owner, no user +ok( !CanUserModifyBudget( $borrower2, $budget14, $flags ) ); # No owner and user list contains borrower1 +ok( CanUserModifyBudget( $borrower2, $budget15, $flags ) ); +ok( !CanUserModifyBudget( $borrower2, $budget16, $flags ) ); # Same tests as above, without budget_modify permission # All tests should failed -$flags = {acquisition => {order_manage => 1}}; +$flags = { acquisition => { order_manage => 1 } }; -t::lib::Mocks::mock_userenv({ branchcode => 'B1' }); +t::lib::Mocks::mock_userenv( { branchcode => 'B1' } ); # Restriction is 'none' -ok (!CanUserModifyBudget($borrower1, $budget1, $flags)); -ok (!CanUserModifyBudget($borrower1, $budget2, $flags)); -ok (!CanUserModifyBudget($borrower1, $budget3, $flags)); -ok (!CanUserModifyBudget($borrower1, $budget4, $flags)); -ok (!CanUserModifyBudget($borrower2, $budget1, $flags)); -ok (!CanUserModifyBudget($borrower2, $budget2, $flags)); -ok (!CanUserModifyBudget($borrower2, $budget3, $flags)); -ok (!CanUserModifyBudget($borrower2, $budget4, $flags)); +ok( !CanUserModifyBudget( $borrower1, $budget1, $flags ) ); +ok( !CanUserModifyBudget( $borrower1, $budget2, $flags ) ); +ok( !CanUserModifyBudget( $borrower1, $budget3, $flags ) ); +ok( !CanUserModifyBudget( $borrower1, $budget4, $flags ) ); +ok( !CanUserModifyBudget( $borrower2, $budget1, $flags ) ); +ok( !CanUserModifyBudget( $borrower2, $budget2, $flags ) ); +ok( !CanUserModifyBudget( $borrower2, $budget3, $flags ) ); +ok( !CanUserModifyBudget( $borrower2, $budget4, $flags ) ); # Restriction is 'owner' -ok (!CanUserModifyBudget($borrower1, $budget5, $flags)); -ok (!CanUserModifyBudget($borrower1, $budget6, $flags)); -ok (!CanUserModifyBudget($borrower1, $budget7, $flags)); -ok (!CanUserModifyBudget($borrower1, $budget8, $flags)); -ok (!CanUserModifyBudget($borrower2, $budget5, $flags)); -ok (!CanUserModifyBudget($borrower2, $budget6, $flags)); -ok (!CanUserModifyBudget($borrower2, $budget7, $flags)); -ok (!CanUserModifyBudget($borrower2, $budget8, $flags)); +ok( !CanUserModifyBudget( $borrower1, $budget5, $flags ) ); +ok( !CanUserModifyBudget( $borrower1, $budget6, $flags ) ); +ok( !CanUserModifyBudget( $borrower1, $budget7, $flags ) ); +ok( !CanUserModifyBudget( $borrower1, $budget8, $flags ) ); +ok( !CanUserModifyBudget( $borrower2, $budget5, $flags ) ); +ok( !CanUserModifyBudget( $borrower2, $budget6, $flags ) ); +ok( !CanUserModifyBudget( $borrower2, $budget7, $flags ) ); +ok( !CanUserModifyBudget( $borrower2, $budget8, $flags ) ); # Restriction is 'owner, users and library' -ok (!CanUserModifyBudget($borrower1, $budget9, $flags)); -ok (!CanUserModifyBudget($borrower1, $budget10, $flags)); -ok (!CanUserModifyBudget($borrower1, $budget11, $flags)); -ok (!CanUserModifyBudget($borrower1, $budget12, $flags)); -ok (!CanUserModifyBudget($borrower2, $budget9, $flags)); -ok (!CanUserModifyBudget($borrower2, $budget10, $flags)); -ok (!CanUserModifyBudget($borrower2, $budget11, $flags)); -ok (!CanUserModifyBudget($borrower2, $budget12, $flags)); +ok( !CanUserModifyBudget( $borrower1, $budget9, $flags ) ); +ok( !CanUserModifyBudget( $borrower1, $budget10, $flags ) ); +ok( !CanUserModifyBudget( $borrower1, $budget11, $flags ) ); +ok( !CanUserModifyBudget( $borrower1, $budget12, $flags ) ); +ok( !CanUserModifyBudget( $borrower2, $budget9, $flags ) ); +ok( !CanUserModifyBudget( $borrower2, $budget10, $flags ) ); +ok( !CanUserModifyBudget( $borrower2, $budget11, $flags ) ); +ok( !CanUserModifyBudget( $borrower2, $budget12, $flags ) ); # Restriction is 'owner and users' -ok (!CanUserModifyBudget($borrower1, $budget13, $flags)); -ok (!CanUserModifyBudget($borrower1, $budget14, $flags)); -ok (!CanUserModifyBudget($borrower1, $budget15, $flags)); -ok (!CanUserModifyBudget($borrower1, $budget16, $flags)); -ok (!CanUserModifyBudget($borrower2, $budget13, $flags)); -ok (!CanUserModifyBudget($borrower2, $budget14, $flags)); -ok (!CanUserModifyBudget($borrower2, $budget15, $flags)); -ok (!CanUserModifyBudget($borrower2, $budget16, $flags)); +ok( !CanUserModifyBudget( $borrower1, $budget13, $flags ) ); +ok( !CanUserModifyBudget( $borrower1, $budget14, $flags ) ); +ok( !CanUserModifyBudget( $borrower1, $budget15, $flags ) ); +ok( !CanUserModifyBudget( $borrower1, $budget16, $flags ) ); +ok( !CanUserModifyBudget( $borrower2, $budget13, $flags ) ); +ok( !CanUserModifyBudget( $borrower2, $budget14, $flags ) ); +ok( !CanUserModifyBudget( $borrower2, $budget15, $flags ) ); +ok( !CanUserModifyBudget( $borrower2, $budget16, $flags ) ); - -t::lib::Mocks::mock_userenv({ branchcode => 'B2' }); +t::lib::Mocks::mock_userenv( { branchcode => 'B2' } ); # Restriction is 'none' -ok (!CanUserModifyBudget($borrower1, $budget1, $flags)); -ok (!CanUserModifyBudget($borrower1, $budget2, $flags)); -ok (!CanUserModifyBudget($borrower1, $budget3, $flags)); -ok (!CanUserModifyBudget($borrower1, $budget4, $flags)); -ok (!CanUserModifyBudget($borrower2, $budget1, $flags)); -ok (!CanUserModifyBudget($borrower2, $budget2, $flags)); -ok (!CanUserModifyBudget($borrower2, $budget3, $flags)); -ok (!CanUserModifyBudget($borrower2, $budget4, $flags)); +ok( !CanUserModifyBudget( $borrower1, $budget1, $flags ) ); +ok( !CanUserModifyBudget( $borrower1, $budget2, $flags ) ); +ok( !CanUserModifyBudget( $borrower1, $budget3, $flags ) ); +ok( !CanUserModifyBudget( $borrower1, $budget4, $flags ) ); +ok( !CanUserModifyBudget( $borrower2, $budget1, $flags ) ); +ok( !CanUserModifyBudget( $borrower2, $budget2, $flags ) ); +ok( !CanUserModifyBudget( $borrower2, $budget3, $flags ) ); +ok( !CanUserModifyBudget( $borrower2, $budget4, $flags ) ); # Restriction is 'owner' -ok (!CanUserModifyBudget($borrower1, $budget5, $flags)); -ok (!CanUserModifyBudget($borrower1, $budget6, $flags)); -ok (!CanUserModifyBudget($borrower1, $budget7, $flags)); -ok (!CanUserModifyBudget($borrower1, $budget8, $flags)); -ok (!CanUserModifyBudget($borrower2, $budget5, $flags)); -ok (!CanUserModifyBudget($borrower2, $budget6, $flags)); -ok (!CanUserModifyBudget($borrower2, $budget7, $flags)); -ok (!CanUserModifyBudget($borrower2, $budget8, $flags)); +ok( !CanUserModifyBudget( $borrower1, $budget5, $flags ) ); +ok( !CanUserModifyBudget( $borrower1, $budget6, $flags ) ); +ok( !CanUserModifyBudget( $borrower1, $budget7, $flags ) ); +ok( !CanUserModifyBudget( $borrower1, $budget8, $flags ) ); +ok( !CanUserModifyBudget( $borrower2, $budget5, $flags ) ); +ok( !CanUserModifyBudget( $borrower2, $budget6, $flags ) ); +ok( !CanUserModifyBudget( $borrower2, $budget7, $flags ) ); +ok( !CanUserModifyBudget( $borrower2, $budget8, $flags ) ); # Restriction is 'owner, users and library' -ok (!CanUserModifyBudget($borrower1, $budget9, $flags)); -ok (!CanUserModifyBudget($borrower1, $budget10, $flags)); -ok (!CanUserModifyBudget($borrower1, $budget11, $flags)); -ok (!CanUserModifyBudget($borrower1, $budget12, $flags)); -ok (!CanUserModifyBudget($borrower2, $budget9, $flags)); -ok (!CanUserModifyBudget($borrower2, $budget10, $flags)); -ok (!CanUserModifyBudget($borrower2, $budget11, $flags)); -ok (!CanUserModifyBudget($borrower2, $budget12, $flags)); +ok( !CanUserModifyBudget( $borrower1, $budget9, $flags ) ); +ok( !CanUserModifyBudget( $borrower1, $budget10, $flags ) ); +ok( !CanUserModifyBudget( $borrower1, $budget11, $flags ) ); +ok( !CanUserModifyBudget( $borrower1, $budget12, $flags ) ); +ok( !CanUserModifyBudget( $borrower2, $budget9, $flags ) ); +ok( !CanUserModifyBudget( $borrower2, $budget10, $flags ) ); +ok( !CanUserModifyBudget( $borrower2, $budget11, $flags ) ); +ok( !CanUserModifyBudget( $borrower2, $budget12, $flags ) ); # Restriction is 'owner and users' -ok (!CanUserModifyBudget($borrower1, $budget13, $flags)); -ok (!CanUserModifyBudget($borrower1, $budget14, $flags)); -ok (!CanUserModifyBudget($borrower1, $budget15, $flags)); -ok (!CanUserModifyBudget($borrower1, $budget16, $flags)); -ok (!CanUserModifyBudget($borrower2, $budget13, $flags)); -ok (!CanUserModifyBudget($borrower2, $budget14, $flags)); -ok (!CanUserModifyBudget($borrower2, $budget15, $flags)); -ok (!CanUserModifyBudget($borrower2, $budget16, $flags)); - +ok( !CanUserModifyBudget( $borrower1, $budget13, $flags ) ); +ok( !CanUserModifyBudget( $borrower1, $budget14, $flags ) ); +ok( !CanUserModifyBudget( $borrower1, $budget15, $flags ) ); +ok( !CanUserModifyBudget( $borrower1, $budget16, $flags ) ); +ok( !CanUserModifyBudget( $borrower2, $budget13, $flags ) ); +ok( !CanUserModifyBudget( $borrower2, $budget14, $flags ) ); +ok( !CanUserModifyBudget( $borrower2, $budget15, $flags ) ); +ok( !CanUserModifyBudget( $borrower2, $budget16, $flags ) ); # Mocked subs diff --git a/t/Budgets/CanUserUseBudget.t b/t/Budgets/CanUserUseBudget.t index 5c528b4f88..e571c4f301 100755 --- a/t/Budgets/CanUserUseBudget.t +++ b/t/Budgets/CanUserUseBudget.t @@ -12,15 +12,15 @@ local $SIG{__WARN__} = sub { warn $_[0] unless $_[0] =~ /redefined/ }; *C4::Budgets::GetBudgetUsers = \&Mock_GetBudgetUsers; my %budgetusers = ( - 1 => [], - 2 => [1], - 3 => [2], - 4 => [3], - 5 => [], - 6 => [1], - 7 => [2], - 8 => [3], - 9 => [], + 1 => [], + 2 => [1], + 3 => [2], + 4 => [3], + 5 => [], + 6 => [1], + 7 => [2], + 8 => [3], + 9 => [], 10 => [1], 11 => [2], 12 => [3], @@ -30,210 +30,200 @@ my %budgetusers = ( 16 => [3], ); -my $borrower1 = { - borrowernumber => 1 -}; -my $borrower2 = { - borrowernumber => 2 -}; +my $borrower1 = { borrowernumber => 1 }; +my $borrower2 = { borrowernumber => 2 }; my $budget1 = { - budget_id => 1, + budget_id => 1, budget_permission => 0, - budget_owner_id => undef, + budget_owner_id => undef, budget_branchcode => undef, }; my $budget2 = { - budget_id => 2, + budget_id => 2, budget_permission => 0, - budget_owner_id => undef, + budget_owner_id => undef, budget_branchcode => 'B1', }; my $budget3 = { - budget_id => 3, + budget_id => 3, budget_permission => 0, - budget_owner_id => 1, + budget_owner_id => 1, budget_branchcode => undef, }; my $budget4 = { - budget_id => 4, + budget_id => 4, budget_permission => 0, - budget_owner_id => 1, + budget_owner_id => 1, budget_branchcode => 'B1', }; my $budget5 = { - budget_id => 5, + budget_id => 5, budget_permission => 1, - budget_owner_id => undef, + budget_owner_id => undef, budget_branchcode => undef, }; my $budget6 = { - budget_id => 6, + budget_id => 6, budget_permission => 1, - budget_owner_id => undef, + budget_owner_id => undef, budget_branchcode => 'B1', }; my $budget7 = { - budget_id => 7, + budget_id => 7, budget_permission => 1, - budget_owner_id => 1, + budget_owner_id => 1, budget_branchcode => undef, }; my $budget8 = { - budget_id => 8, + budget_id => 8, budget_permission => 1, - budget_owner_id => 1, + budget_owner_id => 1, budget_branchcode => 'B1', }; my $budget9 = { - budget_id => 9, + budget_id => 9, budget_permission => 2, - budget_owner_id => undef, + budget_owner_id => undef, budget_branchcode => undef, }; my $budget10 = { - budget_id => 10, + budget_id => 10, budget_permission => 2, - budget_owner_id => undef, + budget_owner_id => undef, budget_branchcode => 'B1', }; my $budget11 = { - budget_id => 11, + budget_id => 11, budget_permission => 2, - budget_owner_id => 1, + budget_owner_id => 1, budget_branchcode => undef, }; my $budget12 = { - budget_id => 12, + budget_id => 12, budget_permission => 2, - budget_owner_id => 1, + budget_owner_id => 1, budget_branchcode => 'B1', }; my $budget13 = { - budget_id => 13, + budget_id => 13, budget_permission => 3, - budget_owner_id => undef, + budget_owner_id => undef, budget_branchcode => undef, }; my $budget14 = { - budget_id => 14, + budget_id => 14, budget_permission => 3, - budget_owner_id => undef, + budget_owner_id => undef, budget_branchcode => 'B1', }; my $budget15 = { - budget_id => 15, + budget_id => 15, budget_permission => 3, - budget_owner_id => 1, + budget_owner_id => 1, budget_branchcode => undef, }; my $budget16 = { - budget_id => 16, + budget_id => 16, budget_permission => 3, - budget_owner_id => 1, + budget_owner_id => 1, budget_branchcode => 'B1', }; ok( !CanUserUseBudget( 0, undef, {} ), "CanUserUseBudget evaluates to false if DB user is passed" ); -ok (CanUserUseBudget($borrower1, $budget1, {superlibrarian => 1})); -ok (CanUserUseBudget($borrower1, $budget1, { - acquisition => { - budget_manage_all => 1 - } -})); -ok (CanUserUseBudget($borrower1, $budget1, {acquisition => 1})); +ok( CanUserUseBudget( $borrower1, $budget1, { superlibrarian => 1 } ) ); +ok( CanUserUseBudget( $borrower1, $budget1, { acquisition => { budget_manage_all => 1 } } ) ); +ok( CanUserUseBudget( $borrower1, $budget1, { acquisition => 1 } ) ); -ok (!CanUserUseBudget($borrower1, $budget1, {})); -ok (!CanUserUseBudget($borrower1, $budget1, {acquisition => 0})); +ok( !CanUserUseBudget( $borrower1, $budget1, {} ) ); +ok( !CanUserUseBudget( $borrower1, $budget1, { acquisition => 0 } ) ); -my $flags = {acquisition => {order_manage => 1}}; +my $flags = { acquisition => { order_manage => 1 } }; -t::lib::Mocks::mock_userenv({ branchcode => 'B1' }); +t::lib::Mocks::mock_userenv( { branchcode => 'B1' } ); # Restriction is 'none' -ok (CanUserUseBudget($borrower1, $budget1, $flags)); -ok (CanUserUseBudget($borrower1, $budget2, $flags)); -ok (CanUserUseBudget($borrower1, $budget3, $flags)); -ok (CanUserUseBudget($borrower1, $budget4, $flags)); -ok (CanUserUseBudget($borrower2, $budget1, $flags)); -ok (CanUserUseBudget($borrower2, $budget2, $flags)); -ok (CanUserUseBudget($borrower2, $budget3, $flags)); -ok (CanUserUseBudget($borrower2, $budget4, $flags)); +ok( CanUserUseBudget( $borrower1, $budget1, $flags ) ); +ok( CanUserUseBudget( $borrower1, $budget2, $flags ) ); +ok( CanUserUseBudget( $borrower1, $budget3, $flags ) ); +ok( CanUserUseBudget( $borrower1, $budget4, $flags ) ); +ok( CanUserUseBudget( $borrower2, $budget1, $flags ) ); +ok( CanUserUseBudget( $borrower2, $budget2, $flags ) ); +ok( CanUserUseBudget( $borrower2, $budget3, $flags ) ); +ok( CanUserUseBudget( $borrower2, $budget4, $flags ) ); # Restriction is 'owner' -ok (CanUserUseBudget($borrower1, $budget5, $flags)); -ok (CanUserUseBudget($borrower1, $budget6, $flags)); -ok (CanUserUseBudget($borrower1, $budget7, $flags)); -ok (CanUserUseBudget($borrower1, $budget8, $flags)); -ok (CanUserUseBudget($borrower2, $budget5, $flags)); -ok (CanUserUseBudget($borrower2, $budget6, $flags)); -ok (!CanUserUseBudget($borrower2, $budget7, $flags)); -ok (!CanUserUseBudget($borrower2, $budget8, $flags)); +ok( CanUserUseBudget( $borrower1, $budget5, $flags ) ); +ok( CanUserUseBudget( $borrower1, $budget6, $flags ) ); +ok( CanUserUseBudget( $borrower1, $budget7, $flags ) ); +ok( CanUserUseBudget( $borrower1, $budget8, $flags ) ); +ok( CanUserUseBudget( $borrower2, $budget5, $flags ) ); +ok( CanUserUseBudget( $borrower2, $budget6, $flags ) ); +ok( !CanUserUseBudget( $borrower2, $budget7, $flags ) ); +ok( !CanUserUseBudget( $borrower2, $budget8, $flags ) ); # Restriction is 'owner, users and library' -ok (CanUserUseBudget($borrower1, $budget9, $flags)); -ok (CanUserUseBudget($borrower1, $budget10, $flags)); -ok (CanUserUseBudget($borrower1, $budget11, $flags)); -ok (CanUserUseBudget($borrower1, $budget12, $flags)); -ok (CanUserUseBudget($borrower2, $budget9, $flags)); -ok (CanUserUseBudget($borrower2, $budget10, $flags)); -ok (CanUserUseBudget($borrower2, $budget11, $flags)); -ok (CanUserUseBudget($borrower2, $budget12, $flags)); +ok( CanUserUseBudget( $borrower1, $budget9, $flags ) ); +ok( CanUserUseBudget( $borrower1, $budget10, $flags ) ); +ok( CanUserUseBudget( $borrower1, $budget11, $flags ) ); +ok( CanUserUseBudget( $borrower1, $budget12, $flags ) ); +ok( CanUserUseBudget( $borrower2, $budget9, $flags ) ); +ok( CanUserUseBudget( $borrower2, $budget10, $flags ) ); +ok( CanUserUseBudget( $borrower2, $budget11, $flags ) ); +ok( CanUserUseBudget( $borrower2, $budget12, $flags ) ); # Restriction is 'owner and users' -ok (!CanUserUseBudget($borrower1, $budget13, $flags)); # No user, no owner -ok (CanUserUseBudget($borrower1, $budget14, $flags)); -ok (CanUserUseBudget($borrower1, $budget15, $flags)); -ok (CanUserUseBudget($borrower1, $budget16, $flags)); -ok (!CanUserUseBudget($borrower2, $budget13, $flags)); # No user, no owner -ok (!CanUserUseBudget($borrower2, $budget14, $flags)); # No owner and user list contains borrower1 -ok (CanUserUseBudget($borrower2, $budget15, $flags)); -ok (!CanUserUseBudget($borrower2, $budget16, $flags)); +ok( !CanUserUseBudget( $borrower1, $budget13, $flags ) ); # No user, no owner +ok( CanUserUseBudget( $borrower1, $budget14, $flags ) ); +ok( CanUserUseBudget( $borrower1, $budget15, $flags ) ); +ok( CanUserUseBudget( $borrower1, $budget16, $flags ) ); +ok( !CanUserUseBudget( $borrower2, $budget13, $flags ) ); # No user, no owner +ok( !CanUserUseBudget( $borrower2, $budget14, $flags ) ); # No owner and user list contains borrower1 +ok( CanUserUseBudget( $borrower2, $budget15, $flags ) ); +ok( !CanUserUseBudget( $borrower2, $budget16, $flags ) ); - -t::lib::Mocks::mock_userenv({ branchcode => 'B2' }); +t::lib::Mocks::mock_userenv( { branchcode => 'B2' } ); # Restriction is 'none' -ok (CanUserUseBudget($borrower1, $budget1, $flags)); -ok (CanUserUseBudget($borrower1, $budget2, $flags)); -ok (CanUserUseBudget($borrower1, $budget3, $flags)); -ok (CanUserUseBudget($borrower1, $budget4, $flags)); -ok (CanUserUseBudget($borrower2, $budget1, $flags)); -ok (CanUserUseBudget($borrower2, $budget2, $flags)); -ok (CanUserUseBudget($borrower2, $budget3, $flags)); -ok (CanUserUseBudget($borrower2, $budget4, $flags)); +ok( CanUserUseBudget( $borrower1, $budget1, $flags ) ); +ok( CanUserUseBudget( $borrower1, $budget2, $flags ) ); +ok( CanUserUseBudget( $borrower1, $budget3, $flags ) ); +ok( CanUserUseBudget( $borrower1, $budget4, $flags ) ); +ok( CanUserUseBudget( $borrower2, $budget1, $flags ) ); +ok( CanUserUseBudget( $borrower2, $budget2, $flags ) ); +ok( CanUserUseBudget( $borrower2, $budget3, $flags ) ); +ok( CanUserUseBudget( $borrower2, $budget4, $flags ) ); # Restriction is 'owner' -ok (CanUserUseBudget($borrower1, $budget5, $flags)); -ok (CanUserUseBudget($borrower1, $budget6, $flags)); -ok (CanUserUseBudget($borrower1, $budget7, $flags)); -ok (CanUserUseBudget($borrower1, $budget8, $flags)); -ok (CanUserUseBudget($borrower2, $budget5, $flags)); -ok (CanUserUseBudget($borrower2, $budget6, $flags)); -ok (!CanUserUseBudget($borrower2, $budget7, $flags)); -ok (!CanUserUseBudget($borrower2, $budget8, $flags)); +ok( CanUserUseBudget( $borrower1, $budget5, $flags ) ); +ok( CanUserUseBudget( $borrower1, $budget6, $flags ) ); +ok( CanUserUseBudget( $borrower1, $budget7, $flags ) ); +ok( CanUserUseBudget( $borrower1, $budget8, $flags ) ); +ok( CanUserUseBudget( $borrower2, $budget5, $flags ) ); +ok( CanUserUseBudget( $borrower2, $budget6, $flags ) ); +ok( !CanUserUseBudget( $borrower2, $budget7, $flags ) ); +ok( !CanUserUseBudget( $borrower2, $budget8, $flags ) ); # Restriction is 'owner, users and library' -ok (CanUserUseBudget($borrower1, $budget9, $flags)); -ok (CanUserUseBudget($borrower1, $budget10, $flags)); -ok (CanUserUseBudget($borrower1, $budget11, $flags)); -ok (CanUserUseBudget($borrower1, $budget12, $flags)); -ok (CanUserUseBudget($borrower2, $budget9, $flags)); -ok (!CanUserUseBudget($borrower2, $budget10, $flags)); # Limited to library B1 -ok (CanUserUseBudget($borrower2, $budget11, $flags)); -ok (!CanUserUseBudget($borrower2, $budget12, $flags)); +ok( CanUserUseBudget( $borrower1, $budget9, $flags ) ); +ok( CanUserUseBudget( $borrower1, $budget10, $flags ) ); +ok( CanUserUseBudget( $borrower1, $budget11, $flags ) ); +ok( CanUserUseBudget( $borrower1, $budget12, $flags ) ); +ok( CanUserUseBudget( $borrower2, $budget9, $flags ) ); +ok( !CanUserUseBudget( $borrower2, $budget10, $flags ) ); # Limited to library B1 +ok( CanUserUseBudget( $borrower2, $budget11, $flags ) ); +ok( !CanUserUseBudget( $borrower2, $budget12, $flags ) ); # Restriction is 'owner and users' -ok (!CanUserUseBudget($borrower1, $budget13, $flags)); # No owner, no user -ok (CanUserUseBudget($borrower1, $budget14, $flags)); -ok (CanUserUseBudget($borrower1, $budget15, $flags)); -ok (CanUserUseBudget($borrower1, $budget16, $flags)); -ok (!CanUserUseBudget($borrower2, $budget13, $flags)); # No owner, no user -ok (!CanUserUseBudget($borrower2, $budget14, $flags)); # No owner and user list contains borrower1 -ok (CanUserUseBudget($borrower2, $budget15, $flags)); -ok (!CanUserUseBudget($borrower2, $budget16, $flags)); - +ok( !CanUserUseBudget( $borrower1, $budget13, $flags ) ); # No owner, no user +ok( CanUserUseBudget( $borrower1, $budget14, $flags ) ); +ok( CanUserUseBudget( $borrower1, $budget15, $flags ) ); +ok( CanUserUseBudget( $borrower1, $budget16, $flags ) ); +ok( !CanUserUseBudget( $borrower2, $budget13, $flags ) ); # No owner, no user +ok( !CanUserUseBudget( $borrower2, $budget14, $flags ) ); # No owner and user list contains borrower1 +ok( CanUserUseBudget( $borrower2, $budget15, $flags ) ); +ok( !CanUserUseBudget( $borrower2, $budget16, $flags ) ); # Mocked subs diff --git a/t/Charset.t b/t/Charset.t index 3e92883e0b..1c99c64f7b 100755 --- a/t/Charset.t +++ b/t/Charset.t @@ -26,47 +26,56 @@ use utf8; use open ':std', ':encoding(utf8)'; BEGIN { - use_ok('C4::Charset', qw( NormalizeString SetUTF8Flag IsStringUTF8ish nsb_clean )); + use_ok( 'C4::Charset', qw( NormalizeString SetUTF8Flag IsStringUTF8ish nsb_clean ) ); } my $string; -ok(!defined(NormalizeString($string,undef,1)),'Uninitialized string case 1 normalizes to uninitialized string.'); +ok( + !defined( NormalizeString( $string, undef, 1 ) ), + 'Uninitialized string case 1 normalizes to uninitialized string.' +); $string = 'Sample'; -ok(defined(NormalizeString($string,undef,0)), 'Initialized string case 1 normalizes to some string.'); -ok(defined(NormalizeString($string,undef,1)), 'Initialized string case 2 normalizes to some string.'); -ok(defined(NormalizeString($string,1,0)), 'Initialized string case 3 normalizes to some string.'); -ok(defined(NormalizeString($string,1,1)), 'Initialized string case 4 normalizes to some string.'); +ok( defined( NormalizeString( $string, undef, 0 ) ), 'Initialized string case 1 normalizes to some string.' ); +ok( defined( NormalizeString( $string, undef, 1 ) ), 'Initialized string case 2 normalizes to some string.' ); +ok( defined( NormalizeString( $string, 1, 0 ) ), 'Initialized string case 3 normalizes to some string.' ); +ok( defined( NormalizeString( $string, 1, 1 ) ), 'Initialized string case 4 normalizes to some string.' ); my $octets = "abc"; -ok(IsStringUTF8ish($octets), "verify octets are valid UTF-8 (ASCII)"); +ok( IsStringUTF8ish($octets), "verify octets are valid UTF-8 (ASCII)" ); $octets = "flamb\xc3\xa9"; -ok(!Encode::is_utf8($octets), "verify that string does not have Perl UTF-8 flag on"); -ok(IsStringUTF8ish($octets), "verify octets are valid UTF-8 (LATIN SMALL LETTER E WITH ACUTE)"); -ok(!Encode::is_utf8($octets), "verify that IsStringUTF8ish does not magically turn Perl UTF-8 flag on"); +ok( !Encode::is_utf8($octets), "verify that string does not have Perl UTF-8 flag on" ); +ok( IsStringUTF8ish($octets), "verify octets are valid UTF-8 (LATIN SMALL LETTER E WITH ACUTE)" ); +ok( !Encode::is_utf8($octets), "verify that IsStringUTF8ish does not magically turn Perl UTF-8 flag on" ); $octets = "a\xc2" . "c"; -ok(!IsStringUTF8ish($octets), "verify octets are not valid UTF-8"); +ok( !IsStringUTF8ish($octets), "verify octets are not valid UTF-8" ); ok( !SetUTF8Flag(), 'SetUTF8Flag returns undef if no record passed' ); my $record = MARC::Record->new(); ok( !SetUTF8Flag($record), 'SetUTF8Flag returns undef if the record has no subfields' ); + # Add some fields/subfields $record->append_fields( - MARC::Field->new('100', ' ', ' ', a => 'Julio Cortazar'), - MARC::Field->new('245', ' ', ' ', a => 'Rayuela'), + MARC::Field->new( '100', ' ', ' ', a => 'Julio Cortazar' ), + MARC::Field->new( '245', ' ', ' ', a => 'Rayuela' ), ); + # Verify our data serves its purpose -ok( !Encode::is_utf8($record->subfield('100','a')) && - !Encode::is_utf8($record->subfield('245','a')), - 'Verify that the subfields are NOT set the UTF-8 flag yet' ); +ok( + !Encode::is_utf8( $record->subfield( '100', 'a' ) ) + && !Encode::is_utf8( $record->subfield( '245', 'a' ) ), + 'Verify that the subfields are NOT set the UTF-8 flag yet' +); SetUTF8Flag($record); -ok( Encode::is_utf8($record->subfield('100','a')) && - Encode::is_utf8($record->subfield('245','a')), - 'SetUTF8Flag sets the UTF-8 flag to all subfields' ); +ok( + Encode::is_utf8( $record->subfield( '100', 'a' ) ) + && Encode::is_utf8( $record->subfield( '245', 'a' ) ), + 'SetUTF8Flag sets the UTF-8 flag to all subfields' +); is( nsb_clean("˜Leœ Moyen Âge"), "Le Moyen Âge", "nsb_clean removes ˜ and œ" ); diff --git a/t/Circulation/AgeRestrictionMarkers.t b/t/Circulation/AgeRestrictionMarkers.t index 218b710cc1..2c4a6ce567 100755 --- a/t/Circulation/AgeRestrictionMarkers.t +++ b/t/Circulation/AgeRestrictionMarkers.t @@ -31,11 +31,11 @@ use C4::Circulation qw( GetAgeRestriction ); t::lib::Mocks::mock_preference( 'AgeRestrictionMarker', 'FSK|PEGI|Age|K' ); -is ( C4::Circulation::GetAgeRestriction('FSK 16'), '16', 'FSK 16 returns 16' ); -is ( C4::Circulation::GetAgeRestriction('PEGI 16'), '16', 'PEGI 16 returns 16' ); -is ( C4::Circulation::GetAgeRestriction('PEGI16'), '16', 'PEGI16 returns 16' ); -is ( C4::Circulation::GetAgeRestriction('Age 16'), '16', 'Age 16 returns 16' ); -is ( C4::Circulation::GetAgeRestriction('K16'), '16', 'K16 returns 16' ); +is( C4::Circulation::GetAgeRestriction('FSK 16'), '16', 'FSK 16 returns 16' ); +is( C4::Circulation::GetAgeRestriction('PEGI 16'), '16', 'PEGI 16 returns 16' ); +is( C4::Circulation::GetAgeRestriction('PEGI16'), '16', 'PEGI16 returns 16' ); +is( C4::Circulation::GetAgeRestriction('Age 16'), '16', 'Age 16 returns 16' ); +is( C4::Circulation::GetAgeRestriction('K16'), '16', 'K16 returns 16' ); subtest 'No age restriction' => sub { plan tests => 1; diff --git a/t/Circulation_barcodedecode.t b/t/Circulation_barcodedecode.t index d5f31c9533..7e2870b512 100755 --- a/t/Circulation_barcodedecode.t +++ b/t/Circulation_barcodedecode.t @@ -23,42 +23,45 @@ use Test::Warn; use C4::Context; use t::lib::Mocks; -use_ok('C4::Circulation', qw( barcodedecode )); +use_ok( 'C4::Circulation', qw( barcodedecode ) ); -t::lib::Mocks::mock_userenv({ branchcode => 'IMS' }); +t::lib::Mocks::mock_userenv( { branchcode => 'IMS' } ); our %inputs = ( - cuecat => ["26002315", '.C3nZC3nZC3nYD3b6ENnZCNnY.fHmc.C3D1Dxr2C3nZE3n7.', ".C3nZC3nZC3nYD3b6ENnZCNnY.fHmc.C3D1Dxr2C3nZE3n7.\r\n", - 'q.C3nZC3nZC3nWDNzYDxf2CNnY.fHmc.C3DWC3nZCNjXD3nW.', '.C3nZC3nZC3nWCxjWE3D1C3nX.cGf2.ENr7C3v7D3T3ENj3C3zYDNnZ.' ], - whitespace => [" 26002315", "26002315 ", "\n\t26002315\n", "whitespace removed"], - 'T-prefix' => [qw(T0031472 T32)], - 'libsuite8' => ['b000126', 'b12', 'B0126', 'IMS-B-126', 'ims-b-126','CD0000024','00123','11998'], - EAN13 => [qw(892685001928 695152)], - other => [qw(26002315 T0031472 T32 Alphanum123), "Alpha Num 345", " side spaces removed \n"], + cuecat => [ + "26002315", '.C3nZC3nZC3nYD3b6ENnZCNnY.fHmc.C3D1Dxr2C3nZE3n7.', + ".C3nZC3nZC3nYD3b6ENnZCNnY.fHmc.C3D1Dxr2C3nZE3n7.\r\n", + 'q.C3nZC3nZC3nWDNzYDxf2CNnY.fHmc.C3DWC3nZCNjXD3nW.', '.C3nZC3nZC3nWCxjWE3D1C3nX.cGf2.ENr7C3v7D3T3ENj3C3zYDNnZ.' + ], + whitespace => [ " 26002315", "26002315 ", "\n\t26002315\n", "whitespace removed" ], + 'T-prefix' => [qw(T0031472 T32)], + 'libsuite8' => [ 'b000126', 'b12', 'B0126', 'IMS-B-126', 'ims-b-126', 'CD0000024', '00123', '11998' ], + EAN13 => [qw(892685001928 695152)], + other => [ qw(26002315 T0031472 T32 Alphanum123), "Alpha Num 345", " side spaces removed \n" ], ); our %outputs = ( - cuecat => ["26002315", "046675000808", "046675000808", "043000112403", "978068484914051500"], - whitespace => [qw(26002315 26002315 26002315 whitespaceremoved)], - 'T-prefix' => [qw(T0031472 T0000002 )], - 'libsuite8' => ['IMS-b-126', 'IMS-b-12', 'IMS-B-126', 'IMS-B-126', 'ims-b-126','IMS-CD-24','IMS-b-123','IMS-b-11998'], - EAN13 => [qw(0892685001928 0000000695152)], - other => [qw(26002315 T0031472 T32 Alphanum123), "Alpha Num 345", "side spaces removed"], + cuecat => [ "26002315", "046675000808", "046675000808", "043000112403", "978068484914051500" ], + whitespace => [qw(26002315 26002315 26002315 whitespaceremoved)], + 'T-prefix' => [qw(T0031472 T0000002 )], + 'libsuite8' => + [ 'IMS-b-126', 'IMS-b-12', 'IMS-B-126', 'IMS-B-126', 'ims-b-126', 'IMS-CD-24', 'IMS-b-123', 'IMS-b-11998' ], + EAN13 => [qw(0892685001928 0000000695152)], + other => [ qw(26002315 T0031472 T32 Alphanum123), "Alpha Num 345", "side spaces removed" ], ); my @filters = sort keys %inputs; foreach my $filter (@filters) { - foreach my $datum (@{$inputs{$filter}}) { - my $expect = shift @{$outputs{$filter}} + foreach my $datum ( @{ $inputs{$filter} } ) { + my $expect = shift @{ $outputs{$filter} } or die "Internal Test Error: missing expected output for filter '$filter' on input '$datum'"; - my $output = C4::Circulation::barcodedecode($datum, $filter); - ok($output eq $expect, sprintf("%12s: %20s => %15s", $filter, "'$datum'", "'$expect'")); - ($output eq $expect) or diag "Bad output: '$output'"; + my $output = C4::Circulation::barcodedecode( $datum, $filter ); + ok( $output eq $expect, sprintf( "%12s: %20s => %15s", $filter, "'$datum'", "'$expect'" ) ); + ( $output eq $expect ) or diag "Bad output: '$output'"; } } -warnings_are - { C4::Circulation::barcodedecode(undef); } - [], +warnings_are { C4::Circulation::barcodedecode(undef); } +[], 'No warnings with undef barcode'; # T-prefix style is derived from zero-padded "Follett Classic Code 3 of 9". From: diff --git a/t/ClassSortRoutine.t b/t/ClassSortRoutine.t index be379a29e6..971cfdbf25 100755 --- a/t/ClassSortRoutine.t +++ b/t/ClassSortRoutine.t @@ -1,6 +1,6 @@ #!/usr/bin/perl # -# This Koha test module is a stub! +# This Koha test module is a stub! # Add more tests here!!! use strict; @@ -9,6 +9,6 @@ use warnings; use Test::More tests => 1; BEGIN { - use_ok('C4::ClassSortRoutine'); + use_ok('C4::ClassSortRoutine'); } diff --git a/t/ClassSortRoutine_Dewey.t b/t/ClassSortRoutine_Dewey.t index f4dc8e72e1..24f60ff5bc 100755 --- a/t/ClassSortRoutine_Dewey.t +++ b/t/ClassSortRoutine_Dewey.t @@ -1,6 +1,6 @@ #!/usr/bin/perl # -# This Koha test module is a stub! +# This Koha test module is a stub! # Add more tests here!!! use strict; @@ -9,33 +9,33 @@ use warnings; use Test::More tests => 10; BEGIN { - use_ok('C4::ClassSortRoutine::Dewey', qw( get_class_sort_key )); + use_ok( 'C4::ClassSortRoutine::Dewey', qw( get_class_sort_key ) ); } -my $cn_sort = C4::ClassSortRoutine::Dewey::get_class_sort_key(undef, undef ); -is($cn_sort,"","testing whitespace"); +my $cn_sort = C4::ClassSortRoutine::Dewey::get_class_sort_key( undef, undef ); +is( $cn_sort, "", "testing whitespace" ); -$cn_sort = C4::ClassSortRoutine::Dewey::get_class_sort_key("....","....."); -is($cn_sort,"","testing fullstops"); +$cn_sort = C4::ClassSortRoutine::Dewey::get_class_sort_key( "....", "....." ); +is( $cn_sort, "", "testing fullstops" ); -$cn_sort = C4::ClassSortRoutine::Dewey::get_class_sort_key("123","456"); -is($cn_sort,"123_456000000000000","testing numbers"); +$cn_sort = C4::ClassSortRoutine::Dewey::get_class_sort_key( "123", "456" ); +is( $cn_sort, "123_456000000000000", "testing numbers" ); -$cn_sort = C4::ClassSortRoutine::Dewey::get_class_sort_key("abc123","456"); -is($cn_sort,"ABC_123_456000000000000","testing alphanumeric"); +$cn_sort = C4::ClassSortRoutine::Dewey::get_class_sort_key( "abc123", "456" ); +is( $cn_sort, "ABC_123_456000000000000", "testing alphanumeric" ); -$cn_sort = C4::ClassSortRoutine::Dewey::get_class_sort_key("ab c123","45 6"); -is($cn_sort,"AB_C123_45_600000000000000","testing middle whitespace"); +$cn_sort = C4::ClassSortRoutine::Dewey::get_class_sort_key( "ab c123", "45 6" ); +is( $cn_sort, "AB_C123_45_600000000000000", "testing middle whitespace" ); -$cn_sort = C4::ClassSortRoutine::Dewey::get_class_sort_key("YR DVD 800.1",""); -my $cn_sort2 = C4::ClassSortRoutine::Dewey::get_class_sort_key("YR DVD 900",""); +$cn_sort = C4::ClassSortRoutine::Dewey::get_class_sort_key( "YR DVD 800.1", "" ); +my $cn_sort2 = C4::ClassSortRoutine::Dewey::get_class_sort_key( "YR DVD 900", "" ); ok( $cn_sort lt $cn_sort2, "testing prefix plus decimal" ); -$cn_sort = C4::ClassSortRoutine::Dewey::get_class_sort_key("971/P23w/v.1-2/pt.8",""); -is($cn_sort,"971_000000000000000_P23W_V_12_PT_8", "Test 1 for bug 8836"); +$cn_sort = C4::ClassSortRoutine::Dewey::get_class_sort_key( "971/P23w/v.1-2/pt.8", "" ); +is( $cn_sort, "971_000000000000000_P23W_V_12_PT_8", "Test 1 for bug 8836" ); -$cn_sort = C4::ClassSortRoutine::Dewey::get_class_sort_key("971.01 P23w v.1-2 pt.6-7",""); -is($cn_sort,"971_010000000000000_P23W_V_12_PT_67", "Test 2 for bug 8836"); +$cn_sort = C4::ClassSortRoutine::Dewey::get_class_sort_key( "971.01 P23w v.1-2 pt.6-7", "" ); +is( $cn_sort, "971_010000000000000_P23W_V_12_PT_67", "Test 2 for bug 8836" ); -$cn_sort = C4::ClassSortRoutine::Dewey::get_class_sort_key("971.01 P23w v.1-2 pt.7",""); -is($cn_sort,"971_010000000000000_P23W_V_12_PT_7", "Test 3 for bug 8836"); +$cn_sort = C4::ClassSortRoutine::Dewey::get_class_sort_key( "971.01 P23w v.1-2 pt.7", "" ); +is( $cn_sort, "971_010000000000000_P23W_V_12_PT_7", "Test 3 for bug 8836" ); diff --git a/t/ClassSortRoutine_Generic.t b/t/ClassSortRoutine_Generic.t index 09c3dd7292..95e25ac1da 100755 --- a/t/ClassSortRoutine_Generic.t +++ b/t/ClassSortRoutine_Generic.t @@ -1,6 +1,6 @@ #!/usr/bin/perl # -# This Koha test module is a stub! +# This Koha test module is a stub! # Add more tests here!!! use strict; @@ -9,16 +9,16 @@ use warnings; use Test::More tests => 3; BEGIN { - use_ok('C4::ClassSortRoutine::Generic', qw( get_class_sort_key )); + use_ok( 'C4::ClassSortRoutine::Generic', qw( get_class_sort_key ) ); } my $cn_class = "My class "; -my $cn_item = " hellO"; +my $cn_item = " hellO"; -my $cn_sort = C4::ClassSortRoutine::Generic::get_class_sort_key($cn_class, $cn_item); +my $cn_sort = C4::ClassSortRoutine::Generic::get_class_sort_key( $cn_class, $cn_item ); -is($cn_sort,"MY_CLASS_HELLO","testing cnsort"); +is( $cn_sort, "MY_CLASS_HELLO", "testing cnsort" ); -$cn_sort = C4::ClassSortRoutine::Generic::get_class_sort_key(undef, undef); +$cn_sort = C4::ClassSortRoutine::Generic::get_class_sort_key( undef, undef ); -is($cn_sort,"","Testing blank cnsort"); +is( $cn_sort, "", "Testing blank cnsort" ); diff --git a/t/ClassSortRoutine_LCC.t b/t/ClassSortRoutine_LCC.t index bfabee440d..da0f8e461e 100755 --- a/t/ClassSortRoutine_LCC.t +++ b/t/ClassSortRoutine_LCC.t @@ -1,6 +1,6 @@ #!/usr/bin/perl # -# This Koha test module is a stub! +# This Koha test module is a stub! # Add more tests here!!! use strict; @@ -9,22 +9,22 @@ use warnings; use Test::More tests => 10; BEGIN { - use_ok('C4::ClassSortRoutine::LCC', qw( get_class_sort_key )); + use_ok( 'C4::ClassSortRoutine::LCC', qw( get_class_sort_key ) ); } #Obvious cases -is(C4::ClassSortRoutine::LCC::get_class_sort_key(), "", "No arguments returns an empty string"); -is(C4::ClassSortRoutine::LCC::get_class_sort_key('a','b'), "A B", "Arguments 'a','b' return 'A B'"); +is( C4::ClassSortRoutine::LCC::get_class_sort_key(), "", "No arguments returns an empty string" ); +is( C4::ClassSortRoutine::LCC::get_class_sort_key( 'a', 'b' ), "A B", "Arguments 'a','b' return 'A B'" ); #spaces in arguements -is(C4::ClassSortRoutine::LCC::get_class_sort_key(' ','b'), "B", "Arguments ' ','b' return 'B'"); -is(C4::ClassSortRoutine::LCC::get_class_sort_key('a',' '), "A", "Arguments 'a',' ' return 'A'"); -is(C4::ClassSortRoutine::LCC::get_class_sort_key(' ',' '), "", "Arguments ' ',' ' return ''"); +is( C4::ClassSortRoutine::LCC::get_class_sort_key( ' ', 'b' ), "B", "Arguments ' ','b' return 'B'" ); +is( C4::ClassSortRoutine::LCC::get_class_sort_key( 'a', ' ' ), "A", "Arguments 'a',' ' return 'A'" ); +is( C4::ClassSortRoutine::LCC::get_class_sort_key( ' ', ' ' ), "", "Arguments ' ',' ' return ''" ); #'funky cases' based on regex in code -is(C4::ClassSortRoutine::LCC::get_class_sort_key('.','b'), "", "Arguments '.','b' return ''"); -is(C4::ClassSortRoutine::LCC::get_class_sort_key('....','........'), "", "Arguments '....','........' return ''"); -is(C4::ClassSortRoutine::LCC::get_class_sort_key('.','.'), "", "Arguments '.','.' return ''"); +is( C4::ClassSortRoutine::LCC::get_class_sort_key( '.', 'b' ), "", "Arguments '.','b' return ''" ); +is( C4::ClassSortRoutine::LCC::get_class_sort_key( '....', '........' ), "", "Arguments '....','........' return ''" ); +is( C4::ClassSortRoutine::LCC::get_class_sort_key( '.', '.' ), "", "Arguments '.','.' return ''" ); # list of example call numbers -- these # are intentionally in the _reverse_ of @@ -39,7 +39,6 @@ my @call_numbers = ( ); my @sorted_call_numbers = map { $_->{call_number} } - sort { $a->{sortkey} cmp $b->{sortkey} } - map { { call_number => $_, sortkey => C4::ClassSortRoutine::LCC::get_class_sort_key($_, '') } } - @call_numbers; -is_deeply(\@sorted_call_numbers, [ reverse @call_numbers ], 'LC call numbers sorted in correct order'); + sort { $a->{sortkey} cmp $b->{sortkey} } + map { { call_number => $_, sortkey => C4::ClassSortRoutine::LCC::get_class_sort_key( $_, '' ) } } @call_numbers; +is_deeply( \@sorted_call_numbers, [ reverse @call_numbers ], 'LC call numbers sorted in correct order' ); diff --git a/t/ClassSource.t b/t/ClassSource.t index ffb3104fcc..e0e4e16e2c 100755 --- a/t/ClassSource.t +++ b/t/ClassSource.t @@ -1,6 +1,6 @@ #!/usr/bin/perl # -# This Koha test module is a stub! +# This Koha test module is a stub! # Add more tests here!!! use strict; @@ -9,6 +9,6 @@ use warnings; use Test::More tests => 1; BEGIN { - use_ok('C4::ClassSource'); + use_ok('C4::ClassSource'); } diff --git a/t/Context.t b/t/Context.t index 9903719e8d..af37e46830 100755 --- a/t/Context.t +++ b/t/Context.t @@ -35,27 +35,27 @@ subtest 'yaml_preference() tests' => sub { my $data = [ 'uno', 'dos', { 'tres' => 'cuatro' } ]; - my $context = Test::MockModule->new( 'C4::Context' ); + my $context = Test::MockModule->new('C4::Context'); $context->mock( 'preference', YAML::XS::Dump($data) ); - my $pref = C4::Context->new->yaml_preference( 'nothing' ); + my $pref = C4::Context->new->yaml_preference('nothing'); is_deeply( $pref, $data, 'yaml_preference returns the right structure' ); $context->mock( 'preference', qq{- uno: dsa\n\t- dos: asd} ); - warning_like - { $pref = C4::Context->new->yaml_preference('nothing') } - qr/^Unable to parse nothing syspref/, + warning_like { $pref = C4::Context->new->yaml_preference('nothing') } + qr/^Unable to parse nothing syspref/, 'Invalid YAML on syspref throws a warning'; is( $pref, undef, 'Invalid YAML on syspref makes it return undef' ); - $context->mock( 'preference', sub { return '{ a : 1 }' }); + $context->mock( 'preference', sub { return '{ a : 1 }' } ); is( ref( C4::Context->new->yaml_preference('ItemsDeniedRenewal') ), 'HASH', 'Got a hash as expected' ); - $context->mock( 'preference', sub { return '[ 1, 2 ]' }); - warning_like { $pref = C4::Context->new->yaml_preference('ITEMSDENIEDRENEWAL') } qr/Hashref expected/, 'Array not accepted for ItemsDeniedRenewal'; + $context->mock( 'preference', sub { return '[ 1, 2 ]' } ); + warning_like { $pref = C4::Context->new->yaml_preference('ITEMSDENIEDRENEWAL') } qr/Hashref expected/, + 'Array not accepted for ItemsDeniedRenewal'; is( $pref, undef, 'Returned undef' ); - $context->unmock( 'preference' ); + $context->unmock('preference'); }; subtest 'multivalue_preference() tests' => sub { @@ -79,7 +79,7 @@ subtest 'needs_install() tests' => sub { t::lib::Mocks::mock_preference( 'Version', '3.0.0' ); is( C4::Context->needs_install, 0, 'Preference is defined, no need to install' ); - t::lib::Mocks::mock_preference( 'Version', undef ); # the behaviour when ->preference fails to fetch + t::lib::Mocks::mock_preference( 'Version', undef ); # the behaviour when ->preference fails to fetch is( C4::Context->needs_install, 1, "->preference(Version) is not defined, need to install" ); }; @@ -91,109 +91,137 @@ subtest 'csv_delimiter() tests' => sub { is( C4::Context->csv_delimiter, ',', "csv_delimiter returns comma if system preference CSVDelimiter is undefined" ); t::lib::Mocks::mock_preference( 'CSVDelimiter', '' ); - is( C4::Context->csv_delimiter, ',', "csv_delimiter returns comma if system preference CSVDelimiter is empty string" ); + is( + C4::Context->csv_delimiter, ',', + "csv_delimiter returns comma if system preference CSVDelimiter is empty string" + ); t::lib::Mocks::mock_preference( 'CSVDelimiter', ';' ); - is( C4::Context->csv_delimiter, ';', "csv_delimiter returns semicolon if system preference CSVDelimiter is semicolon" ); + is( + C4::Context->csv_delimiter, ';', + "csv_delimiter returns semicolon if system preference CSVDelimiter is semicolon" + ); t::lib::Mocks::mock_preference( 'CSVDelimiter', 'tabulation' ); - is( C4::Context->csv_delimiter, "\t", "csv_delimiter returns '\t' if system preference CSVDelimiter is tabulation" ); + is( + C4::Context->csv_delimiter, "\t", + "csv_delimiter returns '\t' if system preference CSVDelimiter is tabulation" + ); }; subtest 'default_catalog_sort_by() tests' => sub { plan tests => 5; - my $context = Test::MockModule->new( 'C4::Context' ); + my $context = Test::MockModule->new('C4::Context'); $context->mock( 'interface', 'intranet' ); t::lib::Mocks::mock_preference( 'defaultSortField', undef ); - is( C4::Context->default_catalog_sort_by, undef, "default_catalog_sort_by() returns undef if system preference defaultSortField is undefined" ); + is( + C4::Context->default_catalog_sort_by, undef, + "default_catalog_sort_by() returns undef if system preference defaultSortField is undefined" + ); t::lib::Mocks::mock_preference( 'defaultSortField', 'title' ); t::lib::Mocks::mock_preference( 'defaultSortOrder', 'az' ); - is( C4::Context->default_catalog_sort_by, 'title_az', "default_catalog_sort_by() returns concatenation of system preferences defaultSortField and defaultSortOrder" ); + is( + C4::Context->default_catalog_sort_by, 'title_az', + "default_catalog_sort_by() returns concatenation of system preferences defaultSortField and defaultSortOrder" + ); t::lib::Mocks::mock_preference( 'defaultSortField', 'relevance' ); - is( C4::Context->default_catalog_sort_by, 'relevance', "default_catalog_sort_by() returns only system preference defaultSortField if it is relevance" ); + is( + C4::Context->default_catalog_sort_by, 'relevance', + "default_catalog_sort_by() returns only system preference defaultSortField if it is relevance" + ); $context->mock( 'interface', 'opac' ); t::lib::Mocks::mock_preference( 'OPACdefaultSortField', 'pubdate' ); t::lib::Mocks::mock_preference( 'OPACdefaultSortOrder', 'desc' ); - is( C4::Context->default_catalog_sort_by, 'pubdate_desc', "default_catalog_sort_by() returns concatenation of system preferences OPACdefaultSortField and OPACdefaultSortOrder" ); + is( + C4::Context->default_catalog_sort_by, 'pubdate_desc', + "default_catalog_sort_by() returns concatenation of system preferences OPACdefaultSortField and OPACdefaultSortOrder" + ); t::lib::Mocks::mock_preference( 'OPACdefaultSortField', 'relevance' ); - is( C4::Context->default_catalog_sort_by, 'relevance', "default_catalog_sort_by() returns only system preference OPACdefaultSortField if it is relevance" ); + is( + C4::Context->default_catalog_sort_by, 'relevance', + "default_catalog_sort_by() returns only system preference OPACdefaultSortField if it is relevance" + ); - $context->unmock( 'interface' ); + $context->unmock('interface'); }; my $context = Test::MockModule->new('C4::Context'); my $userenv = {}; -$context->mock('userenv', sub { - return $userenv; -}); +$context->mock( + 'userenv', + sub { + return $userenv; + } +); local $SIG{__WARN__} = sub { die $_[0] }; eval { C4::Context::IsSuperLibrarian(); }; -like ( $@, qr/not defined/, "IsSuperLibrarian logs an error if no userenv is defined" ); +like( $@, qr/not defined/, "IsSuperLibrarian logs an error if no userenv is defined" ); $userenv->{flags} = 42; -my $is_super_librarian = eval{ C4::Context::IsSuperLibrarian() }; -is ( $@, q||, "IsSuperLibrarian does not log an error if userenv is defined" ); -is ( $is_super_librarian, 0, "With flag=42, it is not a super librarian" ); +my $is_super_librarian = eval { C4::Context::IsSuperLibrarian() }; +is( $@, q||, "IsSuperLibrarian does not log an error if userenv is defined" ); +is( $is_super_librarian, 0, "With flag=42, it is not a super librarian" ); $userenv->{flags} = 421; -$is_super_librarian = eval{ C4::Context::IsSuperLibrarian() }; -is ( $@, q||, "IsSuperLibrarian does not log an error if userenv is defined" ); -is ( $is_super_librarian, 1, "With flag=1, it is a super librarian" ); +$is_super_librarian = eval { C4::Context::IsSuperLibrarian() }; +is( $@, q||, "IsSuperLibrarian does not log an error if userenv is defined" ); +is( $is_super_librarian, 1, "With flag=1, it is a super librarian" ); $userenv->{flags} = undef; -$is_super_librarian = eval{ C4::Context::IsSuperLibrarian() }; -is ( $@, q||, "IsSuperLibrarian does not log an error if \$userenv->{flags} is undefined" ); -is ( $is_super_librarian, 0, "With flag=undef, it is not a super librarian" ); +$is_super_librarian = eval { C4::Context::IsSuperLibrarian() }; +is( $@, q||, "IsSuperLibrarian does not log an error if \$userenv->{flags} is undefined" ); +is( $is_super_librarian, 0, "With flag=undef, it is not a super librarian" ); $userenv->{flags} = 0; -$is_super_librarian = eval{ C4::Context::IsSuperLibrarian() }; -is ( $@, q||, "IsSuperLibrarian does not log an error if \$userenv->{flags} is equal to 0" ); -is ( $is_super_librarian, 0, "With flag=0, it is not a super librarian" ); +$is_super_librarian = eval { C4::Context::IsSuperLibrarian() }; +is( $@, q||, "IsSuperLibrarian does not log an error if \$userenv->{flags} is equal to 0" ); +is( $is_super_librarian, 0, "With flag=0, it is not a super librarian" ); # C4::Context::interface my $lastwarn; local $SIG{__WARN__} = sub { $lastwarn = $_[0] }; -is(C4::Context->interface, 'opac','interface defaults to opac'); -is(C4::Context->interface('foobar'), 'opac', 'interface foobar'); -like($lastwarn, qr/invalid interface : 'foobar'/, 'interface warn on foobar'); -is(C4::Context->interface, 'opac', 'interface still opac'); -is(C4::Context->interface('intranet'), 'intranet', 'interface intranet'); -is(C4::Context->interface, 'intranet', 'interface still intranet'); -is(C4::Context->interface('foobar'), 'intranet', 'interface foobar again'); -is(C4::Context->interface, 'intranet', 'interface still intranet'); -is(C4::Context->interface('OPAC'), 'opac', 'interface OPAC uc'); -is(C4::Context->interface, 'opac', 'interface still opac'); +is( C4::Context->interface, 'opac', 'interface defaults to opac' ); +is( C4::Context->interface('foobar'), 'opac', 'interface foobar' ); +like( $lastwarn, qr/invalid interface : 'foobar'/, 'interface warn on foobar' ); +is( C4::Context->interface, 'opac', 'interface still opac' ); +is( C4::Context->interface('intranet'), 'intranet', 'interface intranet' ); +is( C4::Context->interface, 'intranet', 'interface still intranet' ); +is( C4::Context->interface('foobar'), 'intranet', 'interface foobar again' ); +is( C4::Context->interface, 'intranet', 'interface still intranet' ); +is( C4::Context->interface('OPAC'), 'opac', 'interface OPAC uc' ); +is( C4::Context->interface, 'opac', 'interface still opac' ); + #Bug 14751 -is( C4::Context->interface( 'SiP' ), 'sip', 'interface SiP' ); -is( C4::Context->interface( 'COMMANDLINE' ), 'commandline', 'interface commandline uc' ); -is( C4::Context->interface( 'CRON' ), 'cron', 'interface cron uc' ); +is( C4::Context->interface('SiP'), 'sip', 'interface SiP' ); +is( C4::Context->interface('COMMANDLINE'), 'commandline', 'interface commandline uc' ); +is( C4::Context->interface('CRON'), 'cron', 'interface cron uc' ); { local %ENV = %ENV; delete $ENV{HTTPS}; - is( C4::Context->https_enabled, 0, "Undefined HTTPS env returns 0"); + is( C4::Context->https_enabled, 0, "Undefined HTTPS env returns 0" ); $ENV{HTTPS} = '1'; - is( C4::Context->https_enabled, 0, "Invalid 1 HTTPS env returns 0"); + is( C4::Context->https_enabled, 0, "Invalid 1 HTTPS env returns 0" ); $ENV{HTTPS} = 'off'; - is( C4::Context->https_enabled, 0, "off HTTPS env returns 0"); + is( C4::Context->https_enabled, 0, "off HTTPS env returns 0" ); $ENV{HTTPS} = 'OFF'; - is( C4::Context->https_enabled, 0, "OFF HTTPS env returns 0"); + is( C4::Context->https_enabled, 0, "OFF HTTPS env returns 0" ); $ENV{HTTPS} = 'on'; - is( C4::Context->https_enabled, 1, "on HTTPS env returns 1"); + is( C4::Context->https_enabled, 1, "on HTTPS env returns 1" ); $ENV{HTTPS} = 'ON'; - is( C4::Context->https_enabled, 1, "ON HTTPS env returns 1"); + is( C4::Context->https_enabled, 1, "ON HTTPS env returns 1" ); } subtest 'psgi_env and is_internal_PSGI_request' => sub { diff --git a/t/Contract.t b/t/Contract.t index 87df569a43..f32b32affd 100755 --- a/t/Contract.t +++ b/t/Contract.t @@ -1,6 +1,6 @@ #!/usr/bin/perl # -# This Koha test module is a stub! +# This Koha test module is a stub! # Add more tests here!!! use strict; @@ -9,6 +9,6 @@ use warnings; use Test::More tests => 1; BEGIN { - use_ok('C4::Contract'); + use_ok('C4::Contract'); } diff --git a/t/CookieManager.t b/t/CookieManager.t index 3df60d24a5..23a2c2c172 100755 --- a/t/CookieManager.t +++ b/t/CookieManager.t @@ -32,12 +32,12 @@ subtest 'new' => sub { t::lib::Mocks::mock_config( Koha::CookieManager::DENY_LIST_VAR, 'just_one' ); my $cmgr = Koha::CookieManager->new; - is( scalar keys %{$cmgr->{_remove_unless}}, 1, 'one entry' ); - is( exists $cmgr->{_secure}, 1, 'secure key found' ); + is( scalar keys %{ $cmgr->{_remove_unless} }, 1, 'one entry' ); + is( exists $cmgr->{_secure}, 1, 'secure key found' ); t::lib::Mocks::mock_config( Koha::CookieManager::DENY_LIST_VAR, [ 'two', 'entries' ] ); $cmgr = Koha::CookieManager->new; - is( scalar keys %{$cmgr->{_remove_unless}}, 2, 'two entries' ); + is( scalar keys %{ $cmgr->{_remove_unless} }, 2, 'two entries' ); }; subtest 'clear_unless' => sub { @@ -45,95 +45,101 @@ subtest 'clear_unless' => sub { t::lib::Mocks::mock_config( Koha::CookieManager::DENY_LIST_VAR, [ 'aap', 'noot' ] ); - my $q = CGI->new; + my $q = CGI->new; my $cmgr = Koha::CookieManager->new; - my $cookie1 = $q->cookie( -name => 'aap', -value => 'aap', -expires => '+1d' ); + my $cookie1 = $q->cookie( -name => 'aap', -value => 'aap', -expires => '+1d' ); my $cookie2 = $q->cookie( -name => 'noot', -value => 'noot' ); - my $cookie3 = $q->cookie( -name => 'wim', -value => q{wim}, -HttpOnly => 1 ); - my $cookie4 = $q->cookie( -name => 'aap', -value => q{aap2}, -HttpOnly => 1 ); - my $list = [ $cookie1, $cookie2, $cookie3, $cookie4, 'mies', 'zus' ]; # 4 cookies, 2 names + my $cookie3 = $q->cookie( -name => 'wim', -value => q{wim}, -HttpOnly => 1 ); + my $cookie4 = $q->cookie( -name => 'aap', -value => q{aap2}, -HttpOnly => 1 ); + my $list = [ $cookie1, $cookie2, $cookie3, $cookie4, 'mies', 'zus' ]; # 4 cookies, 2 names # No results expected - is( @{$cmgr->clear_unless}, 0, 'Empty list' ); - is( @{$cmgr->clear_unless( { hash => 1 }, [ 'array' ], $q )}, 0, 'Empty list for invalid arguments' ); + is( @{ $cmgr->clear_unless }, 0, 'Empty list' ); + is( @{ $cmgr->clear_unless( { hash => 1 }, ['array'], $q ) }, 0, 'Empty list for invalid arguments' ); # Pass list, expect 5 cookies (3 cleared, last aap kept) - my @rv = @{$cmgr->clear_unless( @$list )}; - is( @rv, 5, '5 expected' ); - is( $rv[0]->name, 'noot', '1st cookie' ); - is( $rv[1]->name, 'wim', '2nd cookie' ); - is( $rv[2]->name, 'aap', '3rd cookie' ); - is( $rv[3]->name, 'mies', '4th cookie' ); - is( $rv[4]->name, 'zus', '5th cookie' ); - is( $rv[0]->value, q{noot}, 'noot not empty' ); - is( $rv[1]->value, q{}, 'wim empty' ); - is( $rv[2]->value, q{aap2}, 'aap not empty' ); - is( $rv[3]->value, q{}, 'mies empty' ); - is( $rv[4]->value, q{}, 'zus empty' ); - is( $rv[1]->httponly, 0, 'cleared wim is not httponly' ); - is( $rv[2]->httponly, 1, 'aap httponly' ); + my @rv = @{ $cmgr->clear_unless(@$list) }; + is( @rv, 5, '5 expected' ); + is( $rv[0]->name, 'noot', '1st cookie' ); + is( $rv[1]->name, 'wim', '2nd cookie' ); + is( $rv[2]->name, 'aap', '3rd cookie' ); + is( $rv[3]->name, 'mies', '4th cookie' ); + is( $rv[4]->name, 'zus', '5th cookie' ); + is( $rv[0]->value, q{noot}, 'noot not empty' ); + is( $rv[1]->value, q{}, 'wim empty' ); + is( $rv[2]->value, q{aap2}, 'aap not empty' ); + is( $rv[3]->value, q{}, 'mies empty' ); + is( $rv[4]->value, q{}, 'zus empty' ); + is( $rv[1]->httponly, 0, 'cleared wim is not httponly' ); + is( $rv[2]->httponly, 1, 'aap httponly' ); # Test with numeric suffix (via regex) - t::lib::Mocks::mock_config( Koha::CookieManager::DENY_LIST_VAR, [ 'catalogue_editor_\d+' ] ); - $cmgr = Koha::CookieManager->new; - $cookie1 = $q->cookie( -name => 'catalogue_editor_abc', -value => '1', -expires => '+1y' ); - $cookie2 = $q->cookie( -name => 'catalogue_editor_345', -value => '1', -expires => '+1y' ); - $cookie3 = $q->cookie( -name => 'catalogue_editor_', -value => '1', -expires => '+1y' ); + t::lib::Mocks::mock_config( Koha::CookieManager::DENY_LIST_VAR, ['catalogue_editor_\d+'] ); + $cmgr = Koha::CookieManager->new; + $cookie1 = $q->cookie( -name => 'catalogue_editor_abc', -value => '1', -expires => '+1y' ); + $cookie2 = $q->cookie( -name => 'catalogue_editor_345', -value => '1', -expires => '+1y' ); + $cookie3 = $q->cookie( -name => 'catalogue_editor_', -value => '1', -expires => '+1y' ); $cookie4 = $q->cookie( -name => 'catalogue_editor_123x', -value => '1', -expires => '+1y' ); $list = [ $cookie1, $cookie2, $cookie3, $cookie4 ]; - @rv = @{$cmgr->clear_unless( @$list )}; - is_deeply( [ map { $_->value ? $_->name : () } @rv ], - [ 'catalogue_editor_345' ], - 'Cookie2 should be found only' ); + @rv = @{ $cmgr->clear_unless(@$list) }; + is_deeply( + [ map { $_->value ? $_->name : () } @rv ], + ['catalogue_editor_345'], + 'Cookie2 should be found only' + ); # Test with another regex (yes, highly realistic examples :) - t::lib::Mocks::mock_config( Koha::CookieManager::DENY_LIST_VAR, [ 'next_\w+_number\d{2}_(now|never)' ] ); + t::lib::Mocks::mock_config( Koha::CookieManager::DENY_LIST_VAR, ['next_\w+_number\d{2}_(now|never)'] ); $cmgr = Koha::CookieManager->new; my $cookie5; - $cookie1 = $q->cookie( -name => 'next_mynewword_number99_never', -value => '1', -expires => '+1y' ); #fine - $cookie2 = $q->cookie( -name => 'prefixed_next_mynewword_number99_never', -value => '1', -expires => '+1y' ); # wrong prefix - $cookie3 = $q->cookie( -name => 'next_mynew-word_number99_never', -value => '1', -expires => '+1y' ); # wrong: hyphen in word - $cookie4 = $q->cookie( -name => 'mynewword_number999_never', -value => '1', -expires => '+1y' ); # wrong: three digits - $cookie5 = $q->cookie( -name => 'next_mynewword_number99_always', -value => '1', -expires => '+1y' ); # wrong: always - @rv = @{$cmgr->clear_unless( $cookie1, $cookie2, $cookie3, $cookie4, $cookie5 )}; - is_deeply( [ map { $_->value ? $_->name : () } @rv ], [ 'next_mynewword_number99_never' ], 'Only cookie1 matched' ); + $cookie1 = $q->cookie( -name => 'next_mynewword_number99_never', -value => '1', -expires => '+1y' ); #fine + $cookie2 = $q->cookie( -name => 'prefixed_next_mynewword_number99_never', -value => '1', -expires => '+1y' ) + ; # wrong prefix + $cookie3 = $q->cookie( -name => 'next_mynew-word_number99_never', -value => '1', -expires => '+1y' ) + ; # wrong: hyphen in word + $cookie4 = + $q->cookie( -name => 'mynewword_number999_never', -value => '1', -expires => '+1y' ); # wrong: three digits + $cookie5 = + $q->cookie( -name => 'next_mynewword_number99_always', -value => '1', -expires => '+1y' ); # wrong: always + @rv = @{ $cmgr->clear_unless( $cookie1, $cookie2, $cookie3, $cookie4, $cookie5 ) }; + is_deeply( [ map { $_->value ? $_->name : () } @rv ], ['next_mynewword_number99_never'], 'Only cookie1 matched' ); }; subtest 'replace_in_list' => sub { plan tests => 13; - my $q = CGI->new; + my $q = CGI->new; my $cmgr = Koha::CookieManager->new; my $cookie1 = $q->cookie( -name => 'c1', -value => q{c1} ); my $cookie2 = $q->cookie( -name => 'c2', -value => q{c2} ); my $cookie3 = $q->cookie( -name => 'c3', -value => q{c3} ); - my $cookie4 = $q->cookie( -name => 'c2', -value => q{c4} ); # name c2 ! + my $cookie4 = $q->cookie( -name => 'c2', -value => q{c4} ); # name c2 ! # Unusual arguments (show that $cmgr handles the cookie mocks in Auth.t) my $res = $cmgr->replace_in_list( [ 1, 2, 3 ], 4 ); is( @$res, 0, 'No cookies' ); $res = $cmgr->replace_in_list( [ 1, 2, 3 ], $cookie1 ); - is( @$res, 1, 'One cookie added' ); + is( @$res, 1, 'One cookie added' ); is( $res->[0]->name, 'c1', '1st cookie' ); - $res = $cmgr->replace_in_list( [ $cookie2, 2, 3 ], 4 ); # filter 2,3 and ignore 4 - is( @$res, 1, 'One cookie found' ); + $res = $cmgr->replace_in_list( [ $cookie2, 2, 3 ], 4 ); # filter 2,3 and ignore 4 + is( @$res, 1, 'One cookie found' ); is( $res->[0]->name, 'c2', 'c2 found' ); # Pass c1 c2, add c3 $res = $cmgr->replace_in_list( [ $cookie1, $cookie2 ], $cookie3 ); - is( @$res, 3, 'Returns three' ); - is( $res->[2]->name, 'c3', '3rd cookie' ); + is( @$res, 3, 'Returns three' ); + is( $res->[2]->name, 'c3', '3rd cookie' ); is( $res->[2]->value, 'c3', 'value c3' ); # Pass c1 c2 c3 and replace c2 $res = $cmgr->replace_in_list( [ $cookie1, $cookie2, $cookie3 ], $cookie4 ); - is( @$res, 3, 'Returns three' ); - is( $res->[0]->name, 'c1', '1st cookie' ); - is( $res->[1]->name, 'c3', '2nd cookie' ); - is( $res->[2]->name, 'c2', '3rd cookie' ); + is( @$res, 3, 'Returns three' ); + is( $res->[0]->name, 'c1', '1st cookie' ); + is( $res->[1]->name, 'c3', '2nd cookie' ); + is( $res->[2]->name, 'c2', '3rd cookie' ); is( $res->[2]->value, 'c4', 'value replaced' ); }; diff --git a/t/Creators.t b/t/Creators.t index b1206af16a..ef3d6e9596 100755 --- a/t/Creators.t +++ b/t/Creators.t @@ -17,34 +17,33 @@ use File::Temp qw/ tempfile /; use Test::More tests => 41; BEGIN { - use_ok('C4::Creators'); - use_ok('C4::Creators::PDF', qw( Init Add Bookmark Compress Font FontSize Page StrWidth Text End )); + use_ok('C4::Creators'); + use_ok( 'C4::Creators::PDF', qw( Init Add Bookmark Compress Font FontSize Page StrWidth Text End ) ); } -my $pdf_creator = C4::Creators::PDF->new(InitVars => 0); -ok($pdf_creator, "testing new() works"); -if (-e $pdf_creator->{filename}) { - pass('testing pdf file created'); -} -else { - fail('testing pdf file created'); +my $pdf_creator = C4::Creators::PDF->new( InitVars => 0 ); +ok( $pdf_creator, "testing new() works" ); +if ( -e $pdf_creator->{filename} ) { + pass('testing pdf file created'); +} else { + fail('testing pdf file created'); } -ok($pdf_creator->Add(""), "testing Add() works"); -ok($pdf_creator->Bookmark({}), "testing Bookmark() works"); -ok($pdf_creator->Compress(1), "testing Compress() works"); +ok( $pdf_creator->Add(""), "testing Add() works" ); +ok( $pdf_creator->Bookmark( {} ), "testing Bookmark() works" ); +ok( $pdf_creator->Compress(1), "testing Compress() works" ); -is($pdf_creator->Font("H"), "Ft1", "testing Font() works"); -is($pdf_creator->FontSize(), '12', "testing FontSize() is set to 12 by default"); +is( $pdf_creator->Font("H"), "Ft1", "testing Font() works" ); +is( $pdf_creator->FontSize(), '12', "testing FontSize() is set to 12 by default" ); my @result = $pdf_creator->FontSize(14); -is($result[0], '14', "testing FontSize() can be set to a different value"); -$pdf_creator->FontSize(); # Reset font size before testing text width etc below +is( $result[0], '14', "testing FontSize() can be set to a different value" ); +$pdf_creator->FontSize(); # Reset font size before testing text width etc below -ok($pdf_creator->Page(), "testing Page() works"); +ok( $pdf_creator->Page(), "testing Page() works" ); my $expected_width; my $expected_offset; -if (C4::Context->config('ttf')) { +if ( C4::Context->config('ttf') ) { $expected_width = '23.044921875'; $expected_offset = '33.044921875'; } else { @@ -52,33 +51,36 @@ if (C4::Context->config('ttf')) { $expected_offset = '29.344'; } -is($pdf_creator->StrWidth("test", "H", 12), $expected_width, "testing StrWidth() returns correct point width"); +is( $pdf_creator->StrWidth( "test", "H", 12 ), $expected_width, "testing StrWidth() returns correct point width" ); -@result = $pdf_creator->Text(10, 10, "test"); -is($result[0], '10', "testing Text() writes from a given x-value"); -is($result[1], $expected_offset, "testing Text() writes to the correct x-value"); +@result = $pdf_creator->Text( 10, 10, "test" ); +is( $result[0], '10', "testing Text() writes from a given x-value" ); +is( $result[1], $expected_offset, "testing Text() writes to the correct x-value" ); my $font_types = C4::Creators::Lib::get_font_types(); isa_ok( $font_types, 'ARRAY', 'get_font_types' ); my $y = 50; -foreach my $font ( @$font_types ) { - ok( $pdf_creator->Font( $font->{type} ), 'Font ' . $font->{type} ); - ok( $pdf_creator->Text(10, $y, "\x{10C}evap\x{10D}i\x{107} " . $font->{name} . ' - ' . $font->{type} ), 'Text ' . $font->{name}); - $y += $pdf_creator->FontSize() * 1.2; +foreach my $font (@$font_types) { + ok( $pdf_creator->Font( $font->{type} ), 'Font ' . $font->{type} ); + ok( + $pdf_creator->Text( 10, $y, "\x{10C}evap\x{10D}i\x{107} " . $font->{name} . ' - ' . $font->{type} ), + 'Text ' . $font->{name} + ); + $y += $pdf_creator->FontSize() * 1.2; } SKIP: { skip "Skipping because without proper fonts these two tests fail", - 2 if ! $ENV{KOHA_CONF}; + 2 if !$ENV{KOHA_CONF}; - my ($fh, $filename) = tempfile(); - open( $fh, '>', $filename ); + my ( $fh, $filename ) = tempfile(); + open( $fh, '>', $filename ); select $fh; - ok($pdf_creator->End(), "testing End() works"); + ok( $pdf_creator->End(), "testing End() works" ); close($fh); - ok( -s $filename , "test file $filename created OK" ); + ok( -s $filename, "test file $filename created OK" ); unlink $filename unless $ENV{KEEP_PDF}; } diff --git a/t/DateUtils.t b/t/DateUtils.t index b26be34c53..e515b9b003 100755 --- a/t/DateUtils.t +++ b/t/DateUtils.t @@ -15,15 +15,15 @@ use Koha::DateUtils qw( dt_from_string output_pref format_sqldatetime flatpickr_ use t::lib::Mocks; -t::lib::Mocks::mock_preference('dateformat', 'us'); -t::lib::Mocks::mock_preference('TimeFormat', 'This_is_not_used_but_called'); +t::lib::Mocks::mock_preference( 'dateformat', 'us' ); +t::lib::Mocks::mock_preference( 'TimeFormat', 'This_is_not_used_but_called' ); my $tz = C4::Context->tz; isa_ok( $tz, 'DateTime::TimeZone', 'Context returns timezone object' ); -my $testdate_iso = '2011-06-16'; # Bloomsday 2011 -my $dt = dt_from_string( $testdate_iso, 'iso' ); +my $testdate_iso = '2011-06-16'; # Bloomsday 2011 +my $dt = dt_from_string( $testdate_iso, 'iso' ); isa_ok( $dt, 'DateTime', 'dt_from_string returns a DateTime object' ); @@ -35,59 +35,61 @@ $dt->set_minute(0); my $date_string; my $dateformat = C4::Context->preference('dateformat'); -cmp_ok output_pref({ dt => $dt, dateformat => $dateformat }), - 'eq', - output_pref($dt), - 'output_pref gives an hashref or a dt'; +cmp_ok output_pref( { dt => $dt, dateformat => $dateformat } ), + 'eq', + output_pref($dt), + 'output_pref gives an hashref or a dt'; -$date_string = output_pref({ dt => $dt, dateformat => 'iso', timeformat => '24hr' }); +$date_string = output_pref( { dt => $dt, dateformat => 'iso', timeformat => '24hr' } ); cmp_ok $date_string, 'eq', '2011-06-16 12:00', 'iso output'; -$date_string = output_pref({ dt => $dt, dateformat => 'iso', timeformat => '12hr' }); +$date_string = output_pref( { dt => $dt, dateformat => 'iso', timeformat => '12hr' } ); cmp_ok $date_string, 'eq', '2011-06-16 12:00 PM', 'iso output 12hr'; -$date_string = output_pref({ dt => $dt, dateformat => 'rfc3339' }); -like($date_string, qr/2011-06-16T12:00:00\+|-\d\d:\d\d/, 'RFC3339 output'); +$date_string = output_pref( { dt => $dt, dateformat => 'rfc3339' } ); +like( $date_string, qr/2011-06-16T12:00:00\+|-\d\d:\d\d/, 'RFC3339 output' ); -$date_string = output_pref({ dt => $dt, dateformat => 'rfc3339', dateonly => 1 }); -is($date_string, '2011-06-16', 'RFC3339 output'); +$date_string = output_pref( { dt => $dt, dateformat => 'rfc3339', dateonly => 1 } ); +is( $date_string, '2011-06-16', 'RFC3339 output' ); # "notime" doesn't actually mean anything in this context, but we # can't pass undef or output_pref will try to access the database -$date_string = output_pref({ dt => $dt, dateformat => 'iso', timeformat => 'notime', dateonly => 1 }); +$date_string = output_pref( { dt => $dt, dateformat => 'iso', timeformat => 'notime', dateonly => 1 } ); cmp_ok $date_string, 'eq', '2011-06-16', 'iso output (date only)'; -$date_string = output_pref({ dt => $dt, dateformat => 'us', timeformat => '24hr' }); +$date_string = output_pref( { dt => $dt, dateformat => 'us', timeformat => '24hr' } ); cmp_ok $date_string, 'eq', '06/16/2011 12:00', 'us output'; -$date_string = output_pref({ dt => $dt, dateformat => 'us', timeformat => '12hr' }); +$date_string = output_pref( { dt => $dt, dateformat => 'us', timeformat => '12hr' } ); cmp_ok $date_string, 'eq', '06/16/2011 12:00 PM', 'us output 12hr'; -$date_string = output_pref({ dt => $dt, dateformat => 'us', timeformat => 'notime', dateonly => 1 }); +$date_string = output_pref( { dt => $dt, dateformat => 'us', timeformat => 'notime', dateonly => 1 } ); cmp_ok $date_string, 'eq', '06/16/2011', 'us output (date only)'; # metric should return the French Revolutionary Calendar Really -$date_string = output_pref({ dt => $dt, dateformat => 'metric', timeformat => '24hr' }); +$date_string = output_pref( { dt => $dt, dateformat => 'metric', timeformat => '24hr' } ); cmp_ok $date_string, 'eq', '16/06/2011 12:00', 'metric output'; -$date_string = output_pref({ dt => $dt, dateformat => 'metric', timeformat => 'notime', dateonly => 1 }); +$date_string = output_pref( { dt => $dt, dateformat => 'metric', timeformat => 'notime', dateonly => 1 } ); cmp_ok $date_string, 'eq', '16/06/2011', 'metric output (date only)'; -$date_string = output_pref({ dt => $dt, dateformat => 'metric', timeformat => '24hr' }); +$date_string = output_pref( { dt => $dt, dateformat => 'metric', timeformat => '24hr' } ); cmp_ok $date_string, 'eq', '16/06/2011 12:00', - 'output_pref preserves non midnight HH:SS'; + 'output_pref preserves non midnight HH:SS'; my $dear_dirty_dublin = DateTime::TimeZone->new( name => 'Europe/Dublin' ); -my $new_dt = dt_from_string( '16/06/2011', 'metric', $dear_dirty_dublin ); +my $new_dt = dt_from_string( '16/06/2011', 'metric', $dear_dirty_dublin ); isa_ok( $new_dt, 'DateTime', 'Create DateTime with different timezone' ); -cmp_ok( $new_dt->ymd(), 'eq', $testdate_iso, - 'Returned Dublin object matches input' ); +cmp_ok( + $new_dt->ymd(), 'eq', $testdate_iso, + 'Returned Dublin object matches input' +); SKIP: { skip "Don't test execution time of dt_from_string on slow servers", 6 if $ENV{SLOW_SERVER}; - for ( qw/ 2014-01-01 2100-01-01 9999-01-01 / ) { + for (qw/ 2014-01-01 2100-01-01 9999-01-01 /) { my $duration = gettimeofday(); - $new_dt = dt_from_string($_, 'iso', $dear_dirty_dublin); + $new_dt = dt_from_string( $_, 'iso', $dear_dirty_dublin ); $duration = gettimeofday() - $duration; cmp_ok $duration, '<', 1, "Create DateTime with dt_from_string() for $_ with TZ in less than 1s"; $duration = gettimeofday(); @@ -95,7 +97,7 @@ SKIP: { $duration = gettimeofday() - $duration; cmp_ok $duration, '<', 1, "Create DateTime with output_pref() for $_ with TZ in less than 1s"; } -}; +} $new_dt = dt_from_string( '2011-06-16 12:00', 'sql' ); isa_ok( $new_dt, 'DateTime', 'Create DateTime from (mysql) sql' ); @@ -106,23 +108,31 @@ isa_ok( $new_dt, 'DateTime', 'Passed a DateTime dt_from_string returns it' ); my $ymd = '2012-01-01'; my $dt0 = dt_from_string( '00/01/2012', 'metric' ); -isa_ok( $dt0, 'DateTime', - 'dt_from_string returns a DateTime object passed a zero metric day' ); +isa_ok( + $dt0, 'DateTime', + 'dt_from_string returns a DateTime object passed a zero metric day' +); cmp_ok( $dt0->ymd(), 'eq', $ymd, 'Returned object corrects metric day 0' ); $dt0 = dt_from_string( '01/00/2012', 'us' ); -isa_ok( $dt0, 'DateTime', - 'dt_from_string returns a DateTime object passed a zero us day' ); +isa_ok( + $dt0, 'DateTime', + 'dt_from_string returns a DateTime object passed a zero us day' +); cmp_ok( $dt0->ymd(), 'eq', $ymd, 'Returned object corrects us day 0' ); $dt0 = dt_from_string( '2012-01-00', 'iso' ); -isa_ok( $dt0, 'DateTime', - 'dt_from_string returns a DateTime object passed a zero iso day' ); +isa_ok( + $dt0, 'DateTime', + 'dt_from_string returns a DateTime object passed a zero iso day' +); cmp_ok( $dt0->ymd(), 'eq', $ymd, 'Returned object corrects iso day 0' ); $dt0 = dt_from_string( '2012-01-00T12:00:00Z', 'rfc3339' ); -isa_ok( $dt0, 'DateTime', - 'dt_from_string returns a DateTime object passed a zero rfc3339 day' ); +isa_ok( + $dt0, 'DateTime', + 'dt_from_string returns a DateTime object passed a zero rfc3339 day' +); cmp_ok( $dt0->ymd(), 'eq', $ymd, 'Returned object corrects rfc3339 day 0' ); $dt0 = dt_from_string( '2012-01-01T23:59:00.0Z', 'rfc3339' ); @@ -138,14 +148,17 @@ $dt0 = dt_from_string( '2012-01-01T23:59:59.999+02:00', 'rfc3339' ); cmp_ok( $dt0->epoch(), 'eq', '1325455199', 'dt_from_string handles seconds with 3 decimal places and a timezone' ); eval { - $dt0 = dt_from_string( '2012-01-01T23:59:59.999Z+02:00', 'rfc3339' ); # Do not combine Z with +02 ! + $dt0 = dt_from_string( '2012-01-01T23:59:59.999Z+02:00', 'rfc3339' ); # Do not combine Z with +02 ! }; like( $@, qr/Invalid date format/, 'dt_from_string should die when passed a bad rfc3339 date string' ); eval { - $dt0 = dt_from_string('2021-11-03T10:16:59Z+00:00', 'iso'); # Z and +00 are the same, but should not be together + $dt0 = dt_from_string( '2021-11-03T10:16:59Z+00:00', 'iso' ); # Z and +00 are the same, but should not be together }; -like( $@, qr/.*does not match the date format \(iso\).*/, 'dt_from_string should die when passed a bad iso date string' ); +like( + $@, qr/.*does not match the date format \(iso\).*/, + 'dt_from_string should die when passed a bad iso date string' +); # ISO string tests subtest 'dt_from_string - iso format' => sub { @@ -162,25 +175,27 @@ subtest 'dt_from_string - iso format' => sub { # Dateonly my $dt_iso = dt_from_string( '2012-01-01', 'iso' ); cmp_ok( $dt_iso->epoch(), 'eq', '1325372400', 'dt_from_string handles dateonly string' ); + # Saturday December 31, 2011 23:00:00 (UTC) == Sunday January 01, 2012 00:00:00 Europe/Paris (CET/+01:00) - eval { - $dt_iso = dt_from_string( '2012-01-32', 'iso' ); - }; - like( $@, qr/^Validation failed/, 'Fail on invalid dateonly string'); + eval { $dt_iso = dt_from_string( '2012-01-32', 'iso' ); }; + like( $@, qr/^Validation failed/, 'Fail on invalid dateonly string' ); # Datetime $dt_iso = dt_from_string( '2012-01-01T23:59:59', 'iso' ); cmp_ok( $dt_iso->epoch(), 'eq', '1325458799', 'dt_from_string with no offset assumes "local"' ); + # Sunday January 01, 2012 22:59:59 (UTC) == Sunday January 01, 2012 23:59:59 Europe/Paris (CET/+01:00) # Datetime with timezone $dt_iso = dt_from_string( '2012-01-01T23:59:59Z', 'iso' ); cmp_ok( $dt_iso->epoch(), 'eq', '1325462399', 'dt_from_string with UTC prescribed as Z' ); + # Sunday January 01, 2012 23:59:59 (UTC) $dt_iso = dt_from_string( '2012-01-01T23:59:59+02:00', 'iso' ); cmp_ok( $dt_iso->epoch(), 'eq', '1325455199', 'dt_from_string with offset +02:00' ); + # Sunday January 01, 2012 21:59:59 (UTC) == Sunday January 01, 2012 23:59:59 Europe/Athens (EET/+02:00) # Allow +02 or +0200 too $dt_iso = dt_from_string( '2012-01-01T23:59:59+02', 'iso' ); @@ -202,40 +217,44 @@ my $formatted = format_sqldatetime( '2011-06-16 12:00:07', 'metric', '24hr' ); cmp_ok( $formatted, 'eq', '16/06/2011 12:00', 'format_sqldatetime conversion' ); $formatted = format_sqldatetime( undef, 'metric' ); -cmp_ok( $formatted, 'eq', q{}, - 'format_sqldatetime formats undef as empty string' ); +cmp_ok( + $formatted, 'eq', q{}, + 'format_sqldatetime formats undef as empty string' +); # Test the as_due_date parameter $dt = DateTime->new( - year => 2013, - month => 12, - day => 11, - hour => 23, - minute => 59, + year => 2013, + month => 12, + day => 11, + hour => 23, + minute => 59, ); -$date_string = output_pref({ dt => $dt, dateformat => 'metric', timeformat => '24hr', as_due_date => 1 }); +$date_string = output_pref( { dt => $dt, dateformat => 'metric', timeformat => '24hr', as_due_date => 1 } ); cmp_ok $date_string, 'eq', '11/12/2013', 'as_due_date with hours and timeformat 24hr'; -$date_string = output_pref({ dt => $dt, dateformat => 'metric', timeformat => '24hr', dateonly => 1, as_due_date => 1}); +$date_string = + output_pref( { dt => $dt, dateformat => 'metric', timeformat => '24hr', dateonly => 1, as_due_date => 1 } ); cmp_ok $date_string, 'eq', '11/12/2013', 'as_due_date without hours and timeformat 24hr'; -$date_string = output_pref({ dt => $dt, dateformat => 'metric', timeformat => '12hr', as_due_date => 1 }); +$date_string = output_pref( { dt => $dt, dateformat => 'metric', timeformat => '12hr', as_due_date => 1 } ); cmp_ok $date_string, 'eq', '11/12/2013', 'as_due_date with hours and timeformat 12hr'; -$date_string = output_pref({ dt => $dt, dateformat => 'metric', timeformat => '12hr', dateonly => 1, as_due_date => 1}); +$date_string = + output_pref( { dt => $dt, dateformat => 'metric', timeformat => '12hr', dateonly => 1, as_due_date => 1 } ); cmp_ok $date_string, 'eq', '11/12/2013', 'as_due_date without hours and timeformat 12hr'; # Test as_due_date for hourly loans $dt = DateTime->new( - year => 2013, - month => 12, - day => 11, - hour => 18, - minute => 35, + year => 2013, + month => 12, + day => 11, + hour => 18, + minute => 35, ); -$date_string = output_pref({ dt => $dt, dateformat => 'metric', timeformat => '24hr', as_due_date => 1 }); +$date_string = output_pref( { dt => $dt, dateformat => 'metric', timeformat => '24hr', as_due_date => 1 } ); cmp_ok $date_string, 'eq', '11/12/2013 18:35', 'as_due_date with hours and timeformat 24hr (non-midnight time)'; -$date_string = output_pref({ dt => $dt, dateformat => 'us', timeformat => '12hr', as_due_date => 1 }); +$date_string = output_pref( { dt => $dt, dateformat => 'us', timeformat => '12hr', as_due_date => 1 } ); cmp_ok $date_string, 'eq', '12/11/2013 06:35 PM', 'as_due_date with hours and timeformat 12hr (non-midnight time)'; my $now = DateTime->now; @@ -264,11 +283,11 @@ isa_ok( $dt, 'DateTime', 'dt_from_string should return a DateTime object if a DS # Test output_pref for invalid local time explosion $dt = DateTime->new( - year => 2017, - month => 3, - day => 26, - hour => 1, - minute => 35, + year => 2017, + month => 3, + day => 26, + hour => 1, + minute => 35, ); $module_context->mock( 'tz', @@ -276,11 +295,14 @@ $module_context->mock( return DateTime::TimeZone->new( name => 'Europe/London' ); } ); -is( output_pref( { dt => $dt, dateonly => 0 } ), '03/26/2017 01:35', 'output_pref should return even if an invalid DST time is passed' ); +is( + output_pref( { dt => $dt, dateonly => 0 } ), '03/26/2017 01:35', + 'output_pref should return even if an invalid DST time is passed' +); # Test dt_from_string -t::lib::Mocks::mock_preference('dateformat', 'metric'); -t::lib::Mocks::mock_preference('TimeFormat', '24hr'); +t::lib::Mocks::mock_preference( 'dateformat', 'metric' ); +t::lib::Mocks::mock_preference( 'TimeFormat', '24hr' ); # dt_from_string should take into account the dateformat pref, or the given parameter $dt = dt_from_string('31/01/2015'); @@ -299,10 +321,12 @@ is( ref($dt), 'DateTime', '01/01/2015 is a correct date in us format' ); $dt = dt_from_string( '01.01.2015', 'dmydot' ); is( ref($dt), 'DateTime', '01.01.2015 is a correct date in dmydot format' ); - # default value for hh and mm is 00:00 $dt = dt_from_string('31/01/2015'); -is( output_pref( { dt => $dt } ), '31/01/2015 00:00', 'dt_from_string should generate a DT object with 00:00 as default hh:mm' ); +is( + output_pref( { dt => $dt } ), '31/01/2015 00:00', + 'dt_from_string should generate a DT object with 00:00 as default hh:mm' +); $dt = dt_from_string('31/01/2015 12:34'); is( output_pref( { dt => $dt } ), '31/01/2015 12:34', 'dt_from_string should match hh:mm' ); @@ -316,87 +340,99 @@ is( output_pref( { dt => $dt, dateonly => 1 } ), '01/01/1900', 'dt_from_string s # fallback $dt = dt_from_string('2015-01-31 01:02:03'); -is( output_pref( {dt => $dt} ), '31/01/2015 01:02', 'dt_from_string should fallback to sql format' ); +is( output_pref( { dt => $dt } ), '31/01/2015 01:02', 'dt_from_string should fallback to sql format' ); # 12hr format $dt = dt_from_string('2015-01-31 01:02 AM'); -is( output_pref( {dt => $dt} ), '31/01/2015 01:02', 'dt_from_string ' ); +is( output_pref( { dt => $dt } ), '31/01/2015 01:02', 'dt_from_string ' ); $dt = dt_from_string('2015-01-31 01:02:03 AM'); -is( output_pref( {dt => $dt} ), '31/01/2015 01:02', 'dt_from_string ' ); +is( output_pref( { dt => $dt } ), '31/01/2015 01:02', 'dt_from_string ' ); $dt = dt_from_string('2015-01-31 01:02 PM'); -is( output_pref( {dt => $dt} ), '31/01/2015 13:02', 'dt_from_string ' ); +is( output_pref( { dt => $dt } ), '31/01/2015 13:02', 'dt_from_string ' ); $dt = dt_from_string('2015-01-31 01:02:03 PM'); -is( output_pref( {dt => $dt} ), '31/01/2015 13:02', 'dt_from_string ' ); +is( output_pref( { dt => $dt } ), '31/01/2015 13:02', 'dt_from_string ' ); $dt = dt_from_string('2015-01-31 12:02 AM'); -is( output_pref( {dt => $dt} ), '31/01/2015 00:02', 'dt_from_string ' ); +is( output_pref( { dt => $dt } ), '31/01/2015 00:02', 'dt_from_string ' ); $dt = dt_from_string('2015-01-31 12:02:03 AM'); -is( output_pref( {dt => $dt} ), '31/01/2015 00:02', 'dt_from_string ' ); +is( output_pref( { dt => $dt } ), '31/01/2015 00:02', 'dt_from_string ' ); subtest 'TimeFormat 12hr' => sub { plan tests => 4; $dt = DateTime->new( year => 2020, month => 5, day => 28, hour => 12, minute => 49 ); - t::lib::Mocks::mock_preference('TimeFormat', '12hr'); - my $output = output_pref({ dt => $dt, dateformat => 'iso' }); + t::lib::Mocks::mock_preference( 'TimeFormat', '12hr' ); + my $output = output_pref( { dt => $dt, dateformat => 'iso' } ); $dt = dt_from_string( $output, 'iso' ); - is( output_pref( {dt => $dt} ), '28/05/2020 12:49 PM', "12 NOON formatted correctly in 12hr format" ); - t::lib::Mocks::mock_preference('TimeFormat', '24hr'); - is( output_pref( {dt => $dt} ), '28/05/2020 12:49' , "12 NOON formatted correctly in 24hr format" ); + is( output_pref( { dt => $dt } ), '28/05/2020 12:49 PM', "12 NOON formatted correctly in 12hr format" ); + t::lib::Mocks::mock_preference( 'TimeFormat', '24hr' ); + is( output_pref( { dt => $dt } ), '28/05/2020 12:49', "12 NOON formatted correctly in 24hr format" ); $dt = DateTime->new( year => 2020, month => 5, day => 28, hour => 0, minute => 49 ); - t::lib::Mocks::mock_preference('TimeFormat', '12hr'); - $output = output_pref({ dt => $dt, dateformat => 'iso' }); - $dt = dt_from_string( $output, 'iso' ); - is( output_pref( {dt => $dt} ), '28/05/2020 12:49 AM', "12 MIDNIGHT formatted correctly in 12hr format" ); - t::lib::Mocks::mock_preference('TimeFormat', '24hr'); - is( output_pref( {dt => $dt} ), '28/05/2020 00:49', "12 MIDNIGHT formatted correctly in 24hr format" ); + t::lib::Mocks::mock_preference( 'TimeFormat', '12hr' ); + $output = output_pref( { dt => $dt, dateformat => 'iso' } ); + $dt = dt_from_string( $output, 'iso' ); + is( output_pref( { dt => $dt } ), '28/05/2020 12:49 AM', "12 MIDNIGHT formatted correctly in 12hr format" ); + t::lib::Mocks::mock_preference( 'TimeFormat', '24hr' ); + is( output_pref( { dt => $dt } ), '28/05/2020 00:49', "12 MIDNIGHT formatted correctly in 24hr format" ); }; # output_pref with no parameters, single parameter (no hash) is( output_pref(), undef, 'Call output_pref without parameters' ); try { - output_pref( 'no_dt' ); + output_pref('no_dt'); ok( 0, 'Passed single invalid dt to output_pref' ); } catch { - is( ref($_), 'Koha::Exceptions::WrongParameter', - 'Passed single invalid dt to output_pref' ); + is( + ref($_), 'Koha::Exceptions::WrongParameter', + 'Passed single invalid dt to output_pref' + ); }; # pass invalid dt via hash try { - output_pref({ dt => 'no_dt' }); + output_pref( { dt => 'no_dt' } ); ok( 0, 'Passed invalid dt in hash to output_pref' ); } catch { - is( ref($_), 'Koha::Exceptions::WrongParameter', - 'Passed invalid dt in hash to output_pref' ); + is( + ref($_), 'Koha::Exceptions::WrongParameter', + 'Passed invalid dt in hash to output_pref' + ); }; # output_pref with str parameter -is( output_pref( { 'str' => $testdate_iso, dateformat => 'iso', dateonly => 1 } ), $testdate_iso, 'output_pref should handle correctly the iso parameter' ); +is( + output_pref( { 'str' => $testdate_iso, dateformat => 'iso', dateonly => 1 } ), $testdate_iso, + 'output_pref should handle correctly the iso parameter' +); my $output_for_invalid_date; try { - $output_for_invalid_date = output_pref({ str => 'invalid_date' }); + $output_for_invalid_date = output_pref( { str => 'invalid_date' } ); ok( 0, 'Invalid date string passed to output_pref' ); } catch { - is( ref($_), 'Koha::Exceptions::WrongParameter', - 'Invalid date string passed to output_pref' ); + is( + ref($_), 'Koha::Exceptions::WrongParameter', + 'Invalid date string passed to output_pref' + ); }; is( $output_for_invalid_date, undef, 'No return value from output_pref' ); try { - output_pref({ 'str' => $testdate_iso, dt => $dt, dateformat => 'iso', dateonly => 1 }); + output_pref( { 'str' => $testdate_iso, dt => $dt, dateformat => 'iso', dateonly => 1 } ); ok( 0, 'output_pref should carp if str and dt parameters are passed together' ); } catch { - is( ref($_), 'Koha::Exceptions::WrongParameter', 'output_pref should throw an exception if str and dt parameters are passed together' ); + is( + ref($_), 'Koha::Exceptions::WrongParameter', + 'output_pref should throw an exception if str and dt parameters are passed together' + ); }; subtest 'flatpickr_date_format' => sub { plan tests => 4; - t::lib::Mocks::mock_preference('dateformat', 'iso'); - is( flatpickr_date_format(), 'Y-m-d', 'check fallback to pref' ); - is( flatpickr_date_format(q{}), undef, 'empty string' ); + t::lib::Mocks::mock_preference( 'dateformat', 'iso' ); + is( flatpickr_date_format(), 'Y-m-d', 'check fallback to pref' ); + is( flatpickr_date_format(q{}), undef, 'empty string' ); is( flatpickr_date_format('metric'), 'd/m/Y', 'check valid arg' ); - is( flatpickr_date_format('zz'), undef, 'wrong arg' ); + is( flatpickr_date_format('zz'), undef, 'wrong arg' ); }; # End of tests diff --git a/t/EdiInvoice.t b/t/EdiInvoice.t index 3800b75126..e6e6db3cd7 100755 --- a/t/EdiInvoice.t +++ b/t/EdiInvoice.t @@ -39,10 +39,14 @@ is( $msg_count, 6, 'correct message count returned' ); is( $messages->[0]->message_type, 'INVOIC', 'Message shows correct type' ); my $expected_date = '20140729'; -is( $messages->[0]->message_date, - $expected_date, 'Message date correctly returned' ); -is( $messages->[0]->tax_point_date, - $expected_date, 'Tax point date correctly returned' ); +is( + $messages->[0]->message_date, + $expected_date, 'Message date correctly returned' +); +is( + $messages->[0]->tax_point_date, + $expected_date, 'Tax point date correctly returned' +); my $expected_invoicenumber = '01975490'; @@ -51,8 +55,10 @@ my $invoicenumber = $messages->[1]->docmsg_number(); is( $messages->[0]->buyer_ean, '5013546121974', 'Buyer ean correct' ); is( $messages->[0]->supplier_ean, '5013546025078', 'Supplier ean correct' ); -is( $invoicenumber, $expected_invoicenumber, - 'correct invoicenumber extracted' ); +is( + $invoicenumber, $expected_invoicenumber, + 'correct invoicenumber extracted' +); my $lines = $messages->[1]->lineitems(); @@ -91,9 +97,9 @@ my $qty_invoiced = $lines->[7]->quantity_invoiced; is( $qty_invoiced, 1, 'quantity_invoiced returns correct value' ); -my ($lt, $excl) = Koha::EDI::_get_invoiced_price($lines->[7], 1); -is( $lt, 4.55, 'invoiced price calculated'); -is($excl, 4.55, 'Price excluding tax returned correctly'); +my ( $lt, $excl ) = Koha::EDI::_get_invoiced_price( $lines->[7], 1 ); +is( $lt, 4.55, 'invoiced price calculated' ); +is( $excl, 4.55, 'Price excluding tax returned correctly' ); -($lt, $excl) = Koha::EDI::_get_invoiced_price($lines->[7], 2); -is( $lt, 4.55 / 2, 'invoiced pricei calculated for copies > 1'); +( $lt, $excl ) = Koha::EDI::_get_invoiced_price( $lines->[7], 2 ); +is( $lt, 4.55 / 2, 'invoiced pricei calculated for copies > 1' ); diff --git a/t/Edifact.t b/t/Edifact.t index b7132df0e1..55d35d85df 100755 --- a/t/Edifact.t +++ b/t/Edifact.t @@ -37,11 +37,13 @@ is( $msg_count, 1, "correct message count returned" ); my $m = $msgs->[0]; is( $m->message_type, 'QUOTES', "Message shows correct type" ); -is( $m->message_reference_number, - 'MQ09791', "Message reference number returned" ); -is( $m->docmsg_number, 'Q741588', "Message docmsg number returned" ); -is( $m->message_date, '20140430', "Message date returned" ); -is( $m->buyer_ean, '5030670137480', 'buyer ean returned'); +is( + $m->message_reference_number, + 'MQ09791', "Message reference number returned" +); +is( $m->docmsg_number, 'Q741588', "Message docmsg number returned" ); +is( $m->message_date, '20140430', "Message date returned" ); +is( $m->buyer_ean, '5030670137480', 'buyer ean returned' ); my $lin = $m->lineitems(); @@ -50,11 +52,11 @@ is( $num_lines, 18, 'Correct number of lines in message' ); my $test_line = $lin->[-1]; -is( $test_line->line_item_number, 18, 'correct line number returned' ); -is( $test_line->item_number_id, '9780273761006', 'correct ean returned' ); -is( $test_line->quantity, 1, 'quantity returned' ); -is( $test_line->price_info, 114.97, 'price returned' ); -is( $test_line->price_info_inclusive, undef, 'discounted price undefined as expected' ); +is( $test_line->line_item_number, 18, 'correct line number returned' ); +is( $test_line->item_number_id, '9780273761006', 'correct ean returned' ); +is( $test_line->quantity, 1, 'quantity returned' ); +is( $test_line->price_info, 114.97, 'price returned' ); +is( $test_line->price_info_inclusive, undef, 'discounted price undefined as expected' ); my $test_title = 'International business [electronic resource]'; my $marcrec = $test_line->marc_record; @@ -95,7 +97,7 @@ is( $test_line_2->orderline_free_text, $ftx_string, "ftx note retrieved" ); my $filename2 = "$Bin/edi_testfiles/QUOTES_413514.CEQ"; -my $q2 = Koha::Edifact->new( { filename => $filename2, } ); +my $q2 = Koha::Edifact->new( { filename => $filename2, } ); my $messages = $q2->message_array(); my $orderlines = $messages->[0]->lineitems(); @@ -124,15 +126,15 @@ is( $y, 'ANF', 'Sequence code returned' ); $y = $ol->girfield( 'stock_category', 4 ); is( $y, 'RS', 'Copy stock category returned' ); -$y = $ol->girfield( 'library_rotation_plan', 0); +$y = $ol->girfield( 'library_rotation_plan', 0 ); is( $y, 'WRPC2', 'Library rotation plan returned' ); # test internal routines for prices -my $dp = Koha::EDI::_discounted_price(33.0, 9); +my $dp = Koha::EDI::_discounted_price( 33.0, 9 ); is( $dp, 6.03, 'Discount calculated' ); -$dp = Koha::EDI::_discounted_price(0.0, 9); +$dp = Koha::EDI::_discounted_price( 0.0, 9 ); is( $dp, 9.0, 'Discount calculated with discount = 0' ); -$dp = Koha::EDI::_discounted_price(0.0, 9, 8.0); -is( $dp, 8.0, 'Discount overridden by incoming calculated value'); +$dp = Koha::EDI::_discounted_price( 0.0, 9, 8.0 ); +is( $dp, 8.0, 'Discount overridden by incoming calculated value' ); diff --git a/t/Ediorder.t b/t/Ediorder.t index 1b89f8a9c5..7947b760c5 100755 --- a/t/Ediorder.t +++ b/t/Ediorder.t @@ -7,14 +7,13 @@ use Test::More tests => 13; use t::lib::Mocks; BEGIN { use_ok('Koha::Edifact::Order') } -t::lib::Mocks::mock_preference('EdifactLSQ', 'location'); +t::lib::Mocks::mock_preference( 'EdifactLSQ', 'location' ); # The following tests are for internal methods but they could # error spectacularly so best # Check that quoting is done correctly # -my $processed_text = - Koha::Edifact::Order::encode_text(q{string containing ?,',:,+}); +my $processed_text = Koha::Edifact::Order::encode_text(q{string containing ?,',:,+}); cmp_ok( $processed_text, 'eq', @@ -43,18 +42,22 @@ $data_to_encode .= 'C' x 10; cmp_ok( $segs[0], 'eq', -q{IMD+L+010+:::AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA:BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB'}, + q{IMD+L+010+:::AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA:BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB'}, 'IMD segment correctly chunked' ); -cmp_ok( $segs[1], 'eq', q{IMD+L+010+:::CCCCCCCCCC'}, - 'IMD segment correctly split across segments' ); +cmp_ok( + $segs[1], 'eq', q{IMD+L+010+:::CCCCCCCCCC'}, + 'IMD segment correctly split across segments' +); $data_to_encode .= '??'; # this used to cause an infinite loop @segs = Koha::Edifact::Order::imd_segment( $code, $data_to_encode ); -cmp_ok( $segs[1], 'eq', q{IMD+L+010+:::CCCCCCCCCC??'}, - 'IMD segment deals with quoted character at end' ); +cmp_ok( + $segs[1], 'eq', q{IMD+L+010+:::CCCCCCCCCC??'}, + 'IMD segment deals with quoted character at end' +); # special case for text ending in apostrophe e.g. nuthin' $data_to_encode .= q{?'}; @@ -67,19 +70,25 @@ cmp_ok( $data_to_encode =~ s/\?'$//; @segs = Koha::Edifact::Order::imd_segment( $code, $data_to_encode ); -cmp_ok( $segs[1], 'eq', q{IMD+L+010+:::CCCCCCCCCC??'}, - 'IMD segment deals with apostrophe preceded by quoted ? at end' ); +cmp_ok( + $segs[1], 'eq', q{IMD+L+010+:::CCCCCCCCCC??'}, + 'IMD segment deals with apostrophe preceded by quoted ? at end' +); my $isbn = '3540556753'; my $ean = '9783540556756'; my $seg = Koha::Edifact::Order::additional_product_id($isbn); -cmp_ok( $seg, 'eq', q{PIA+5+3540556753:IB'}, - 'isbn correctly encoded in PIA segment' ); +cmp_ok( + $seg, 'eq', q{PIA+5+3540556753:IB'}, + 'isbn correctly encoded in PIA segment' +); $seg = Koha::Edifact::Order::additional_product_id($ean); -cmp_ok( $seg, 'eq', q{PIA+5+9783540556756:EN'}, - 'ean correctly encoded in PIA segment' ); +cmp_ok( + $seg, 'eq', q{PIA+5+9783540556756:EN'}, + 'ean correctly encoded in PIA segment' +); my $orderfields = { budget_code => 'BUDGET', }; my @items = ( @@ -122,5 +131,7 @@ cmp_ok( 'First part of split Gir field OK' ); -cmp_ok( $gsegs[3], 'eq', q{GIR+002+S_I:LVT}, - 'Second part of split GIR field OK' ); +cmp_ok( + $gsegs[3], 'eq', q{GIR+002+S_I:LVT}, + 'Second part of split GIR field OK' +); diff --git a/t/Ediordrsp.t b/t/Ediordrsp.t index 6d410dc8b8..e31b8525a1 100755 --- a/t/Ediordrsp.t +++ b/t/Ediordrsp.t @@ -9,8 +9,7 @@ BEGIN { use_ok('Koha::Edifact') } my $filedir = "$Bin/edi_testfiles"; -my @files = map { "$filedir/$_" } - ( 'ordrsp1.CEA', 'ordrsp2.CEA', 'ordrsp3.CEA', 'ordrsp4.CEA' ); +my @files = map { "$filedir/$_" } ( 'ordrsp1.CEA', 'ordrsp2.CEA', 'ordrsp3.CEA', 'ordrsp4.CEA' ); my @responses; for my $filename (@files) { @@ -46,14 +45,22 @@ is( ); is( $lines->[1]->ordernumber(), 'P28838', 'Line 2 correct ordernumber' ); -is( $lines->[1]->action_notification(), - 'cancelled', 'Cancelled action returned' ); -is( $lines->[1]->coded_orderline_text(), - 'Out of print', 'OP returned and translated' ); +is( + $lines->[1]->action_notification(), + 'cancelled', 'Cancelled action returned' +); +is( + $lines->[1]->coded_orderline_text(), + 'Out of print', 'OP returned and translated' +); is( $lines->[2]->ordernumber(), 'P28846', 'Line 3 correct ordernumber' ); -is( $lines->[2]->action_notification(), - 'recorded', 'Accepted with change action returned' ); +is( + $lines->[2]->action_notification(), + 'recorded', 'Accepted with change action returned' +); -is( $lines->[0]->availability_date(), '19971120', - 'Availability date returned' ); +is( + $lines->[0]->availability_date(), '19971120', + 'Availability date returned' +); diff --git a/t/External/BakerTaylor.t b/t/External/BakerTaylor.t index e4809359c6..16a3ba9667 100755 --- a/t/External/BakerTaylor.t +++ b/t/External/BakerTaylor.t @@ -8,26 +8,28 @@ use Test::More tests => 9; use t::lib::Mocks; BEGIN { - use_ok('C4::External::BakerTaylor', qw( link_url image_url content_cafe_url http_jacket_link availability )); + use_ok( 'C4::External::BakerTaylor', qw( link_url image_url content_cafe_url http_jacket_link availability ) ); } # test with mocked prefs -my $username= "testing_username"; -my $password= "testing_password"; +my $username = "testing_username"; +my $password = "testing_password"; my $link_url = "http://wrongexample.com?ContentCafe.aspx?UserID=$username"; -t::lib::Mocks::mock_preference( 'BakerTaylorUsername', $username ); -t::lib::Mocks::mock_preference( 'BakerTaylorPassword', $password ); +t::lib::Mocks::mock_preference( 'BakerTaylorUsername', $username ); +t::lib::Mocks::mock_preference( 'BakerTaylorPassword', $password ); t::lib::Mocks::mock_preference( 'BakerTaylorBookstoreURL', $link_url ); -my $image_url = "https://contentcafe2.btol.com/ContentCafe/Jacket.aspx?UserID=$username&Password=$password&Options=Y&Return=T&Type=S&Value="; -my $content_cafe = "https://contentcafe2.btol.com/ContentCafeClient/ContentCafe.aspx?UserID=$username&Password=$password&Options=Y&ItemKey="; +my $image_url = + "https://contentcafe2.btol.com/ContentCafe/Jacket.aspx?UserID=$username&Password=$password&Options=Y&Return=T&Type=S&Value="; +my $content_cafe = + "https://contentcafe2.btol.com/ContentCafeClient/ContentCafe.aspx?UserID=$username&Password=$password&Options=Y&ItemKey="; -is( C4::External::BakerTaylor::image_url(), $image_url, "testing default image url"); -is( C4::External::BakerTaylor::image_url("aa"), $image_url."aa", "testing image url construction"); -is( C4::External::BakerTaylor::link_url(), $link_url, "testing default link url"); -is( C4::External::BakerTaylor::link_url("bb"), "${link_url}bb", "testing link url construction"); -is( C4::External::BakerTaylor::content_cafe_url(""), $content_cafe, "testing default content cafe url"); -is( C4::External::BakerTaylor::content_cafe_url("cc"), "${content_cafe}cc", "testing content cafe url construction"); -is( C4::External::BakerTaylor::http_jacket_link(""), undef, "testing empty http jacket link"); -is( C4::External::BakerTaylor::availability(""), undef, "testing empty availability"); +is( C4::External::BakerTaylor::image_url(), $image_url, "testing default image url" ); +is( C4::External::BakerTaylor::image_url("aa"), $image_url . "aa", "testing image url construction" ); +is( C4::External::BakerTaylor::link_url(), $link_url, "testing default link url" ); +is( C4::External::BakerTaylor::link_url("bb"), "${link_url}bb", "testing link url construction" ); +is( C4::External::BakerTaylor::content_cafe_url(""), $content_cafe, "testing default content cafe url" ); +is( C4::External::BakerTaylor::content_cafe_url("cc"), "${content_cafe}cc", "testing content cafe url construction" ); +is( C4::External::BakerTaylor::http_jacket_link(""), undef, "testing empty http jacket link" ); +is( C4::External::BakerTaylor::availability(""), undef, "testing empty availability" ); diff --git a/t/External/Syndetics.t b/t/External/Syndetics.t index e335c7458e..54f9192dd6 100755 --- a/t/External/Syndetics.t +++ b/t/External/Syndetics.t @@ -1,6 +1,6 @@ #!/usr/bin/perl # -# This Koha test module is a stub! +# This Koha test module is a stub! # Add more tests here!!! use strict; @@ -9,6 +9,6 @@ use warnings; use Test::More tests => 1; BEGIN { - use_ok('C4::External::Syndetics'); + use_ok('C4::External::Syndetics'); } diff --git a/t/Form_MessagingPreferences.t b/t/Form_MessagingPreferences.t index 483e1331e3..3b9b1f81d1 100755 --- a/t/Form_MessagingPreferences.t +++ b/t/Form_MessagingPreferences.t @@ -1,6 +1,6 @@ #!/usr/bin/perl # -# This Koha test module is a stub! +# This Koha test module is a stub! # Add more tests here!!! use strict; @@ -9,6 +9,6 @@ use warnings; use Test::More tests => 1; BEGIN { - use_ok('C4::Form::MessagingPreferences'); + use_ok('C4::Form::MessagingPreferences'); } diff --git a/t/HtmlTags.t b/t/HtmlTags.t index 3746d2c8c2..bbbae0e39e 100755 --- a/t/HtmlTags.t +++ b/t/HtmlTags.t @@ -11,15 +11,14 @@ use Test::More tests => 4; BEGIN { use_ok('Koha::Template::Plugin::HtmlTags'); } my $filter = Koha::Template::Plugin::HtmlTags->new(); -ok ($filter, "new()"); - +ok( $filter, "new()" ); # Test simple tag my $expected = '

            TEST

            '; -my $created = $filter->filter('TEST','', {tag => 'h1'} ); -is( $created, $expected, "Testing simple tag works: $expected - $created"); +my $created = $filter->filter( 'TEST', '', { tag => 'h1' } ); +is( $created, $expected, "Testing simple tag works: $expected - $created" ); # Test tag with attributes $expected = '

            TEST

            '; -$created = $filter->filter('TEST','', {tag => 'h1', attributes => 'class="MYCLASS" title="MYTITLE"'} ); -is($created, $expected, "Testing tag with attributes works: $expected - $created"); +$created = $filter->filter( 'TEST', '', { tag => 'h1', attributes => 'class="MYCLASS" title="MYTITLE"' } ); +is( $created, $expected, "Testing tag with attributes works: $expected - $created" ); diff --git a/t/ImportBatch.t b/t/ImportBatch.t index 7274879a3a..749f9b0640 100755 --- a/t/ImportBatch.t +++ b/t/ImportBatch.t @@ -25,26 +25,26 @@ use Test::More tests => 3; use t::lib::Mocks; BEGIN { - use_ok('C4::ImportBatch', qw( RecordsFromISO2709File RecordsFromMARCXMLFile )); + use_ok( 'C4::ImportBatch', qw( RecordsFromISO2709File RecordsFromMARCXMLFile ) ); } -t::lib::Mocks::mock_preference('marcflavour', 'MARC21'); +t::lib::Mocks::mock_preference( 'marcflavour', 'MARC21' ); subtest 'RecordsFromISO2709File' => sub { plan tests => 4; my ( $errors, $recs ); - my $file = create_file({ whitespace => 1, format => 'marc' }); + my $file = create_file( { whitespace => 1, format => 'marc' } ); ( $errors, $recs ) = C4::ImportBatch::RecordsFromISO2709File( $file, 'biblio', 'UTF-8' ); is( @$recs, 0, 'No records from empty marc file' ); - $file = create_file({ garbage => 1, format => 'marc' }); + $file = create_file( { garbage => 1, format => 'marc' } ); ( $errors, $recs ) = C4::ImportBatch::RecordsFromISO2709File( $file, 'biblio', 'UTF-8' ); is( @$recs, 1, 'Garbage returns one record' ); - my @fields = @$recs? $recs->[0]->fields: (); + my @fields = @$recs ? $recs->[0]->fields : (); is( @fields, 0, 'That is an empty record' ); - $file = create_file({ two => 1, format => 'marc' }); + $file = create_file( { two => 1, format => 'marc' } ); ( $errors, $recs ) = C4::ImportBatch::RecordsFromISO2709File( $file, 'biblio', 'UTF-8' ); is( @$recs, 2, 'File contains 2 records' ); @@ -54,41 +54,42 @@ subtest 'RecordsFromMARCXMLFile' => sub { plan tests => 3; my ( $errors, $recs ); - my $file = create_file({ whitespace => 1, format => 'marcxml' }); + my $file = create_file( { whitespace => 1, format => 'marcxml' } ); ( $errors, $recs ) = C4::ImportBatch::RecordsFromMARCXMLFile( $file, 'UTF-8' ); is( @$recs, 0, 'No records from empty marcxml file' ); - $file = create_file({ garbage => 1, format => 'marcxml' }); + $file = create_file( { garbage => 1, format => 'marcxml' } ); ( $errors, $recs ) = C4::ImportBatch::RecordsFromMARCXMLFile( $file, 'UTF-8' ); is( @$recs, 0, 'Garbage returns no records' ); - $file = create_file({ two => 1, format => 'marcxml' }); + $file = create_file( { two => 1, format => 'marcxml' } ); ( $errors, $recs ) = C4::ImportBatch::RecordsFromMARCXMLFile( $file, 'UTF-8' ); is( @$recs, 2, 'File has two records' ); }; sub create_file { - my ( $params ) = @_; + my ($params) = @_; my ( $fh, $name ) = tempfile( SUFFIX => '.' . $params->{format} ); - if( $params->{garbage} ) { + if ( $params->{garbage} ) { print $fh "Just some garbage\n\nAnd another line"; - } elsif( $params->{whitespace} ) { + } elsif ( $params->{whitespace} ) { print $fh " "; } elsif ( $params->{two} ) { my $rec1 = MARC::Record->new; my $rec2 = MARC::Record->new; - my $fld1 = MARC::Field->new('245','','','a','Title1'); - my $fld2 = MARC::Field->new('245','','','a','Title2'); - $rec1->append_fields( $fld1 ); - $rec2->append_fields( $fld2 ); - if( $params->{format} eq 'marcxml' ) { + my $fld1 = MARC::Field->new( '245', '', '', 'a', 'Title1' ); + my $fld2 = MARC::Field->new( '245', '', '', 'a', 'Title2' ); + $rec1->append_fields($fld1); + $rec2->append_fields($fld2); + if ( $params->{format} eq 'marcxml' ) { my $str = $rec1->as_xml; + # remove ending collection tag $str =~ s/<\/collection>//; print $fh $str; - $str = $rec2->as_xml_record; # no collection tag - # remove line from 2nd record, add collection + $str = $rec2->as_xml_record; # no collection tag + # remove line from 2nd record, add collection $str =~ s/<\?xml.*\n//; $str .= ''; print $fh $str; diff --git a/t/Installer_PerlModules.t b/t/Installer_PerlModules.t index 0a81da024d..e24cfcd93b 100755 --- a/t/Installer_PerlModules.t +++ b/t/Installer_PerlModules.t @@ -1,6 +1,6 @@ #!/usr/bin/perl # -# This Koha test module is a stub! +# This Koha test module is a stub! # Add more tests here!!! use Modern::Perl; @@ -9,16 +9,16 @@ use Test::More tests => 3; use Test::Warn; BEGIN { - use_ok('C4::Installer::PerlModules'); + use_ok('C4::Installer::PerlModules'); } subtest 'prereq_pm' => sub { my $modules; - ok ($modules = C4::Installer::PerlModules->new(), 'Tests modules object'); + ok( $modules = C4::Installer::PerlModules->new(), 'Tests modules object' ); my $prereq_pm = $modules->prereq_pm(); - ok (exists($prereq_pm->{"DBI"}), 'DBI required for installer to run'); - ok (exists($prereq_pm->{"CGI"}), 'CGI required for installer to run' ); - ok (exists($prereq_pm->{"YAML::XS"}), 'YAML::XS required for installer to run'); + ok( exists( $prereq_pm->{"DBI"} ), 'DBI required for installer to run' ); + ok( exists( $prereq_pm->{"CGI"} ), 'CGI required for installer to run' ); + ok( exists( $prereq_pm->{"YAML::XS"} ), 'YAML::XS required for installer to run' ); }; subtest 'versions_info' => sub { @@ -28,11 +28,11 @@ subtest 'versions_info' => sub { ok( exists $modules->{missing_pm}, 'versions_info fills the missing_pm key' ); ok( exists $modules->{upgrade_pm}, 'versions_info fills the upgrade_pm key' ); ok( exists $modules->{current_pm}, 'versions_info fills the current_pm key' ); - my $missing_modules = $modules->get_attr( 'missing_pm' ); - my $upgrade_modules = $modules->get_attr( 'upgrade_pm' ); - my $current_modules = $modules->get_attr( 'current_pm' ); - my $dbi_is_missing = grep { exists $_->{DBI} ? 1 : () } @$missing_modules; - my $dbi_is_upgrade = grep { exists $_->{DBI} ? 1 : () } @$upgrade_modules; - my $dbi_is_current = grep { exists $_->{DBI} ? 1 : () } @$current_modules; + my $missing_modules = $modules->get_attr('missing_pm'); + my $upgrade_modules = $modules->get_attr('upgrade_pm'); + my $current_modules = $modules->get_attr('current_pm'); + my $dbi_is_missing = grep { exists $_->{DBI} ? 1 : () } @$missing_modules; + my $dbi_is_upgrade = grep { exists $_->{DBI} ? 1 : () } @$upgrade_modules; + my $dbi_is_current = grep { exists $_->{DBI} ? 1 : () } @$current_modules; ok( $dbi_is_missing || $dbi_is_upgrade || $dbi_is_current, 'DBI should either be missing, upgrade or current' ); }; diff --git a/t/ItemCirculationAlertPreference.t b/t/ItemCirculationAlertPreference.t index d937c26fcb..0247b9b297 100755 --- a/t/ItemCirculationAlertPreference.t +++ b/t/ItemCirculationAlertPreference.t @@ -1,6 +1,6 @@ #!/usr/bin/perl # -# This Koha test module is a stub! +# This Koha test module is a stub! # Add more tests here!!! use strict; @@ -9,6 +9,6 @@ use warnings; use Test::More tests => 1; BEGIN { - use_ok('C4::ItemCirculationAlertPreference'); + use_ok('C4::ItemCirculationAlertPreference'); } diff --git a/t/Koha/Auth/Permissions.t b/t/Koha/Auth/Permissions.t index 4b398646f3..108373cfb6 100755 --- a/t/Koha/Auth/Permissions.t +++ b/t/Koha/Auth/Permissions.t @@ -99,7 +99,7 @@ subtest 'superlibrarian tests' => sub { 'updatecharges' => 0, }; - my $authz = Koha::Auth::Permissions->get_authz_from_flags({ flags => $flags }); + my $authz = Koha::Auth::Permissions->get_authz_from_flags( { flags => $flags } ); my $expected = { 'CAN_user_acquisition_budget_add_del' => 1, @@ -295,5 +295,5 @@ subtest 'superlibrarian tests' => sub { 'CAN_user_updatecharges' => 1, }; - is_deeply($authz,$expected,'Expected permissions generated for superlibrarian'); + is_deeply( $authz, $expected, 'Expected permissions generated for superlibrarian' ); }; diff --git a/t/Koha/Authority/ControlledIndicators.t b/t/Koha/Authority/ControlledIndicators.t index 1d51e3027d..748bdd0075 100755 --- a/t/Koha/Authority/ControlledIndicators.t +++ b/t/Koha/Authority/ControlledIndicators.t @@ -12,111 +12,129 @@ use Koha::Authority::ControlledIndicators; subtest "Simple tests" => sub { plan tests => 8; - t::lib::Mocks::mock_preference('AuthorityControlledIndicators', q| + t::lib::Mocks::mock_preference( + 'AuthorityControlledIndicators', q| marc21,600,ind1:auth1,ind2:x marc21,700,ind1:auth2, marc21,800,ind1:, - |); + | + ); my $oInd = Koha::Authority::ControlledIndicators->new; - is_deeply( $oInd->get({}), {}, 'Empty hash for no parameters' ); + is_deeply( $oInd->get( {} ), {}, 'Empty hash for no parameters' ); my $record = MARC::Record->new; $record->append_fields( MARC::Field->new( '100', '3', '4', a => 'My name' ), ); - my $res = $oInd->get({ - flavour => "MARC21", - report_tag => '100', - auth_record => $record, - biblio_tag => '600', - }); - is( $res->{ind1}, '3', 'Check 1st indicator' ); - is( exists $res->{ind2}, 1, 'Check existence of 2nd indicator key' ); - is( $res->{ind2}, 'x', 'Check 2nd indicator value' ); + my $res = $oInd->get( + { + flavour => "MARC21", + report_tag => '100', + auth_record => $record, + biblio_tag => '600', + } + ); + is( $res->{ind1}, '3', 'Check 1st indicator' ); + is( exists $res->{ind2}, 1, 'Check existence of 2nd indicator key' ); + is( $res->{ind2}, 'x', 'Check 2nd indicator value' ); - $res = $oInd->get({ - flavour => "MARC21", - report_tag => '100', - auth_record => $record, - biblio_tag => '700', - }); - is( $res->{ind1}, '4', 'Check 1st indicator' ); - is( exists $res->{ind2}, '', 'Check if 2nd indicator key does not exist' ); + $res = $oInd->get( + { + flavour => "MARC21", + report_tag => '100', + auth_record => $record, + biblio_tag => '700', + } + ); + is( $res->{ind1}, '4', 'Check 1st indicator' ); + is( exists $res->{ind2}, '', 'Check if 2nd indicator key does not exist' ); - $res = $oInd->get({ - flavour => "MARC21", - report_tag => '100', - auth_record => $record, - biblio_tag => '800', - }); - is( $res->{ind1}, '', 'ind1: clears 1st indicator' ); + $res = $oInd->get( + { + flavour => "MARC21", + report_tag => '100', + auth_record => $record, + biblio_tag => '800', + } + ); + is( $res->{ind1}, '', 'ind1: clears 1st indicator' ); is( exists $res->{ind2}, '', 'Check if 2nd indicator key does not exist' ); }; subtest "Tests for sub _thesaurus_info" => sub { plan tests => 10; - t::lib::Mocks::mock_preference('AuthorityControlledIndicators', q|marc21,600,ignored,ind2:thesaurus|); + t::lib::Mocks::mock_preference( 'AuthorityControlledIndicators', q|marc21,600,ignored,ind2:thesaurus| ); my $oInd = Koha::Authority::ControlledIndicators->new; my $record = MARC::Record->new; $record->append_fields( - MARC::Field->new( '008', (' 'x11).'a' ), + MARC::Field->new( '008', ( ' ' x 11 ) . 'a' ), MARC::Field->new( '040', '', '', f => 'very_special' ), ); # Case 1: LOC code a in auth record should become 0 in 6XX ind2 - my $res = $oInd->get({ - flavour => "MARC21", - report_tag => '100', - auth_record => $record, - biblio_tag => '600', - }); - is( $res->{ind2}, '0', 'Indicator matched for LOC headings' ); + my $res = $oInd->get( + { + flavour => "MARC21", + report_tag => '100', + auth_record => $record, + biblio_tag => '600', + } + ); + is( $res->{ind2}, '0', 'Indicator matched for LOC headings' ); is( $res->{sub2}, undef, 'No subfield 2' ); # Case 2: Code n (Not applicable) should become 4 (source not specified) - $record->field('008')->update( (' 'x11).'n' ); - $res = $oInd->get({ - flavour => "MARC21", - report_tag => '100', - auth_record => $record, - biblio_tag => '600', - }); - is( $res->{ind2}, '4', 'Source not specified' ); + $record->field('008')->update( ( ' ' x 11 ) . 'n' ); + $res = $oInd->get( + { + flavour => "MARC21", + report_tag => '100', + auth_record => $record, + biblio_tag => '600', + } + ); + is( $res->{ind2}, '4', 'Source not specified' ); is( $res->{sub2}, undef, 'No subfield 2' ); # Case 3: AAT thesaurus (and subfield $2) - $record->field('008')->update( (' 'x11).'r' ); - $res = $oInd->get({ - flavour => "MARC21", - report_tag => '100', - auth_record => $record, - biblio_tag => '600', - }); - is( $res->{ind2}, '7', 'AAT, see subfield 2' ); + $record->field('008')->update( ( ' ' x 11 ) . 'r' ); + $res = $oInd->get( + { + flavour => "MARC21", + report_tag => '100', + auth_record => $record, + biblio_tag => '600', + } + ); + is( $res->{ind2}, '7', 'AAT, see subfield 2' ); is( $res->{sub2}, 'aat', 'Subfield 2 verified' ); # Case 4: Code z triggers a fetch from 040$f (and subfield $2) - $record->field('008')->update( (' 'x11).'z' ); - $res = $oInd->get({ - flavour => "MARC21", - report_tag => '100', - auth_record => $record, - biblio_tag => '600', - }); - is( $res->{ind2}, '7', 'Code z, see subfield 2' ); + $record->field('008')->update( ( ' ' x 11 ) . 'z' ); + $res = $oInd->get( + { + flavour => "MARC21", + report_tag => '100', + auth_record => $record, + biblio_tag => '600', + } + ); + is( $res->{ind2}, '7', 'Code z, see subfield 2' ); is( $res->{sub2}, 'very_special', 'Subfield 2 from 040$f' ); # Case 5: Code e does not belong in 008/11 - $record->field('008')->update( (' 'x11).'e' ); - $res = $oInd->get({ - flavour => "MARC21", - report_tag => '100', - auth_record => $record, - biblio_tag => '600', - }); - is( $res->{ind2}, '4', 'Code e triggers not specified' ); + $record->field('008')->update( ( ' ' x 11 ) . 'e' ); + $res = $oInd->get( + { + flavour => "MARC21", + report_tag => '100', + auth_record => $record, + biblio_tag => '600', + } + ); + is( $res->{ind2}, '4', 'Code e triggers not specified' ); is( $res->{sub2}, undef, 'No subfield 2' ); }; diff --git a/t/Koha/Config.t b/t/Koha/Config.t index d394f65709..8809b34f6e 100755 --- a/t/Koha/Config.t +++ b/t/Koha/Config.t @@ -27,10 +27,12 @@ my $config_filepath = "$Bin/../data/koha-conf.xml"; subtest 'read_from_file() tests' => sub { plan tests => 3; - is( Koha::Config->read_from_file(undef), undef, - "Undef parameter makes function return undef"); + is( + Koha::Config->read_from_file(undef), undef, + "Undef parameter makes function return undef" + ); - my $got = eval { Koha::Config->read_from_file($config_filepath) }; + my $got = eval { Koha::Config->read_from_file($config_filepath) }; my $expected = { 'listen' => { 'biblioserver' => { @@ -42,33 +44,33 @@ subtest 'read_from_file() tests' => sub { }, 'server' => { 'biblioserver' => { - 'listenref' => 'biblioserver', - 'directory' => '/home/koha/var/lib/zebradb/biblios', - 'config' => '/home/koha/etc/zebradb/zebra-biblios-dom.cfg', - 'cql2rpn' => '/home/koha/etc/zebradb/pqf.properties', + 'listenref' => 'biblioserver', + 'directory' => '/home/koha/var/lib/zebradb/biblios', + 'config' => '/home/koha/etc/zebradb/zebra-biblios-dom.cfg', + 'cql2rpn' => '/home/koha/etc/zebradb/pqf.properties', 'xi:include' => [ { - 'href' => '/home/koha/etc/zebradb/retrieval-info-bib-dom.xml', + 'href' => '/home/koha/etc/zebradb/retrieval-info-bib-dom.xml', 'xmlns:xi' => 'http://www.w3.org/2001/XInclude' }, { 'xmlns:xi' => 'http://www.w3.org/2001/XInclude', - 'href' => '/home/koha/etc/zebradb/explain-biblios.xml' + 'href' => '/home/koha/etc/zebradb/explain-biblios.xml' } ], }, 'authorityserver' => { - 'listenref' => 'authorityserver', - 'directory' => '/home/koha/var/lib/zebradb/authorities', - 'config' => '/home/koha/etc/zebradb/zebra-authorities-dom.cfg', - 'cql2rpn' => '/home/koha/etc/zebradb/pqf.properties', + 'listenref' => 'authorityserver', + 'directory' => '/home/koha/var/lib/zebradb/authorities', + 'config' => '/home/koha/etc/zebradb/zebra-authorities-dom.cfg', + 'cql2rpn' => '/home/koha/etc/zebradb/pqf.properties', 'xi:include' => [ { 'xmlns:xi' => 'http://www.w3.org/2001/XInclude', - 'href' => '/home/koha/etc/zebradb/retrieval-info-auth-dom.xml' + 'href' => '/home/koha/etc/zebradb/retrieval-info-auth-dom.xml' }, { - 'href' => '/home/koha/etc/zebradb/explain-authorities.xml', + 'href' => '/home/koha/etc/zebradb/explain-authorities.xml', 'xmlns:xi' => 'http://www.w3.org/2001/XInclude' } ], @@ -76,62 +78,58 @@ subtest 'read_from_file() tests' => sub { }, 'serverinfo' => { 'biblioserver' => { - 'ccl2rpn' => '/home/koha/etc/zebradb/ccl.properties', - 'user' => 'kohauser', + 'ccl2rpn' => '/home/koha/etc/zebradb/ccl.properties', + 'user' => 'kohauser', 'password' => 'zebrastripes', }, 'authorityserver' => { - 'ccl2rpn' => '/home/koha/etc/zebradb/ccl.properties', - 'user' => 'kohauser', + 'ccl2rpn' => '/home/koha/etc/zebradb/ccl.properties', + 'user' => 'kohauser', 'password' => 'zebrastripes', } }, 'config' => { - 'db_scheme' => 'mysql', - 'database' => 'koha', - 'hostname' => 'localhost', - 'port' => '3306', - 'user' => 'kohaadmin', - 'pass' => 'katikoan', - 'tls' => 'no', - 'ca' => '', - 'cert' => '', - 'key' => '', - 'biblioserver' => 'biblios', - 'biblioservershadow' => '1', - 'authorityserver' => 'authorities', + 'db_scheme' => 'mysql', + 'database' => 'koha', + 'hostname' => 'localhost', + 'port' => '3306', + 'user' => 'kohaadmin', + 'pass' => 'katikoan', + 'tls' => 'no', + 'ca' => '', + 'cert' => '', + 'key' => '', + 'biblioserver' => 'biblios', + 'biblioservershadow' => '1', + 'authorityserver' => 'authorities', 'authorityservershadow' => '1', - 'pluginsdir' => '/home/koha/var/lib/plugins', - 'enable_plugins' => '0', - 'upload_path' => '', - 'tmp_path' => '', - 'intranetdir' => '/home/koha/src', - 'opacdir' => '/home/koha/src/opac', - 'opachtdocs' => '/home/koha/src/koha-tmpl/opac-tmpl', - 'intrahtdocs' => '/home/koha/src/koha-tmpl/intranet-tmpl', - 'includes' => '/home/koha/src/koha-tmpl/intranet-tmpl/prog/en/includes/', - 'logdir' => '/home/koha/var/log', - 'docdir' => '/home/koha/doc', - 'backupdir' => '/home/koha/var/spool', - 'mana_config' => 'https://mana-kb.koha-community.org', - 'backup_db_via_tools' => '0', + 'pluginsdir' => '/home/koha/var/lib/plugins', + 'enable_plugins' => '0', + 'upload_path' => '', + 'tmp_path' => '', + 'intranetdir' => '/home/koha/src', + 'opacdir' => '/home/koha/src/opac', + 'opachtdocs' => '/home/koha/src/koha-tmpl/opac-tmpl', + 'intrahtdocs' => '/home/koha/src/koha-tmpl/intranet-tmpl', + 'includes' => '/home/koha/src/koha-tmpl/intranet-tmpl/prog/en/includes/', + 'logdir' => '/home/koha/var/log', + 'docdir' => '/home/koha/doc', + 'backupdir' => '/home/koha/var/spool', + 'mana_config' => 'https://mana-kb.koha-community.org', + 'backup_db_via_tools' => '0', 'backup_conf_via_tools' => '0', - 'install_log' => '/home/koha/misc/koha-install-log', - 'useldapserver' => '1', - 'ldapserver' => { + 'install_log' => '/home/koha/misc/koha-install-log', + 'useldapserver' => '1', + 'ldapserver' => { ldapserver => { hostname => 'ldap://another_ldap_server:389', user => 'user', pass => 'password', - mapping => { - firstname => { - is => 'givenName' - } - } + mapping => { firstname => { is => 'givenName' } } } }, 'useshibboleth' => '0', - 'shibboleth' => { + 'shibboleth' => { 'autocreate' => '1', 'matchpoint' => 'userid', 'mapping' => { @@ -140,112 +138,112 @@ subtest 'read_from_file() tests' => sub { 'categorycode' => { 'content' => 'STAFF' }, }, }, - 'zebra_lockdir' => '/home/koha/var/lock/zebradb', - 'lockdir' => '__LOCK_DIR__', - 'use_zebra_facets' => '1', + 'zebra_lockdir' => '/home/koha/var/lock/zebradb', + 'lockdir' => '__LOCK_DIR__', + 'use_zebra_facets' => '1', 'zebra_max_record_size' => '1024', - 'log4perl_conf' => '/home/koha/etc/log4perl.conf', - 'memcached_servers' => '127.0.0.1:11211', - 'memcached_namespace' => 'KOHA', - 'template_cache_dir' => '/tmp/koha', + 'log4perl_conf' => '/home/koha/etc/log4perl.conf', + 'memcached_servers' => '127.0.0.1:11211', + 'memcached_namespace' => 'KOHA', + 'template_cache_dir' => '/tmp/koha', 'api_secret_passphrase' => 'CHANGEME', - 'access_dirs' => { + 'access_dirs' => { access_dir => [ '/dir_1', '/dir_2' ], }, 'ttf' => { 'font' => [ { - 'type' => 'TR', + 'type' => 'TR', 'content' => '/usr/share/fonts/truetype/dejavu/DejaVuSerif.ttf', }, { - 'type' => 'TB', + 'type' => 'TB', 'content' => '/usr/share/fonts/truetype/dejavu/DejaVuSerif-Bold.ttf', }, { - 'type' => 'TI', + 'type' => 'TI', 'content' => '/usr/share/fonts/truetype/dejavu/DejaVuSerif-Italic.ttf', }, { - 'type' => 'TBI', + 'type' => 'TBI', 'content' => '/usr/share/fonts/truetype/dejavu/DejaVuSerif-BoldItalic.ttf', }, { - 'type' => 'C', + 'type' => 'C', 'content' => '/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf', }, { - 'type' => 'CB', + 'type' => 'CB', 'content' => '/usr/share/fonts/truetype/dejavu/DejaVuSansMono-Bold.ttf', }, { - 'type' => 'CO', + 'type' => 'CO', 'content' => '/usr/share/fonts/truetype/dejavu/DejaVuSansMono-Oblique.ttf', }, { - 'type' => 'CBO', + 'type' => 'CBO', 'content' => '/usr/share/fonts/truetype/dejavu/DejaVuSansMono-BoldOblique.ttf', }, { - 'type' => 'H', + 'type' => 'H', 'content' => '/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf', }, { - 'type' => 'HO', + 'type' => 'HO', 'content' => '/usr/share/fonts/truetype/dejavu/DejaVuSans-Oblique.ttf', }, { - 'type' => 'HB', + 'type' => 'HB', 'content' => '/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf', }, { - 'type' => 'HBO', + 'type' => 'HBO', 'content' => '/usr/share/fonts/truetype/dejavu/DejaVuSans-BoldOblique.ttf', }, ], }, - 'sms_send_config' => '/home/koha/etc/sms_send/', + 'sms_send_config' => '/home/koha/etc/sms_send/', 'plack_max_requests' => '50', - 'plack_workers' => '2', - 'elasticsearch' => { + 'plack_workers' => '2', + 'elasticsearch' => { 'server' => [ 'localhost:9200', ], 'index_name' => 'koha_master', - 'cxn_pool' => 'Static', + 'cxn_pool' => 'Static', }, 'interlibrary_loans' => { 'backend_directory' => '/home/koha/src/Koha/Illbackends', - 'branch' => { - 'code' => 'CPL', + 'branch' => { + 'code' => 'CPL', 'prefix' => 'ILL', }, 'staff_request_comments' => 'hide', - 'reply_date' => 'hide', - 'digital_recipient' => 'branch', + 'reply_date' => 'hide', + 'digital_recipient' => 'branch', }, - 'timezone' => '', - 'bcrypt_settings' => '__BCRYPT_SETTINGS__', - 'encryption_key' => '__ENCRYPTION_KEY__', - 'dev_install' => '0', - 'strict_sql_modes' => '0', - 'plugin_repos' => '', + 'timezone' => '', + 'bcrypt_settings' => '__BCRYPT_SETTINGS__', + 'encryption_key' => '__ENCRYPTION_KEY__', + 'dev_install' => '0', + 'strict_sql_modes' => '0', + 'plugin_repos' => '', 'koha_xslt_security' => '', - 'smtp_server' => { - 'host' => 'localhost', - 'port' => '25', - 'timeout' => '120', - 'ssl_mode' => 'disabled', + 'smtp_server' => { + 'host' => 'localhost', + 'port' => '25', + 'timeout' => '120', + 'ssl_mode' => 'disabled', 'user_name' => '', - 'password' => '', - 'debug' => '0', + 'password' => '', + 'debug' => '0', }, 'message_broker' => { 'hostname' => 'localhost', - 'port' => '61613', + 'port' => '61613', 'username' => 'guest', 'password' => 'guest', - 'vhost' => '', + 'vhost' => '', }, }, }; @@ -253,20 +251,20 @@ subtest 'read_from_file() tests' => sub { # Reading a Perl script as XML should fail hopefully eval { Koha::Config->read_from_file("$Bin/$Script") }; - like( $@, qr{.*Error reading file.*}, 'File failing to read raises warning'); + like( $@, qr{.*Error reading file.*}, 'File failing to read raises warning' ); }; subtest 'get_instance' => sub { plan tests => 3; my $config = Koha::Config->get_instance($config_filepath); - isa_ok($config, 'Koha::Config', 'get_instance returns a Koha::Config object'); + isa_ok( $config, 'Koha::Config', 'get_instance returns a Koha::Config object' ); my $same_config = Koha::Config->get_instance($config_filepath); - is($config, $same_config, '2nd call to get_instance returns the same object'); + is( $config, $same_config, '2nd call to get_instance returns the same object' ); local $ENV{KOHA_CONF} = $config_filepath; my $default_config = Koha::Config->get_instance; - is($default_config, $config, 'get_instance without parameters reads $KOHA_CONF'); + is( $default_config, $config, 'get_instance without parameters reads $KOHA_CONF' ); }; subtest 'get' => sub { @@ -275,42 +273,42 @@ subtest 'get' => sub { my $config = Koha::Config->get_instance($config_filepath); is_deeply( - $config->get('biblioserver', 'listen'), + $config->get( 'biblioserver', 'listen' ), { content => 'unix:/home/koha/var/run/zebradb/bibliosocket' }, ); is_deeply( - $config->get('biblioserver', 'server'), + $config->get( 'biblioserver', 'server' ), { - 'listenref' => 'biblioserver', - 'directory' => '/home/koha/var/lib/zebradb/biblios', - 'config' => '/home/koha/etc/zebradb/zebra-biblios-dom.cfg', - 'cql2rpn' => '/home/koha/etc/zebradb/pqf.properties', + 'listenref' => 'biblioserver', + 'directory' => '/home/koha/var/lib/zebradb/biblios', + 'config' => '/home/koha/etc/zebradb/zebra-biblios-dom.cfg', + 'cql2rpn' => '/home/koha/etc/zebradb/pqf.properties', 'xi:include' => [ { - 'href' => '/home/koha/etc/zebradb/retrieval-info-bib-dom.xml', + 'href' => '/home/koha/etc/zebradb/retrieval-info-bib-dom.xml', 'xmlns:xi' => 'http://www.w3.org/2001/XInclude' }, { 'xmlns:xi' => 'http://www.w3.org/2001/XInclude', - 'href' => '/home/koha/etc/zebradb/explain-biblios.xml' + 'href' => '/home/koha/etc/zebradb/explain-biblios.xml' } ], }, ); is_deeply( - $config->get('biblioserver', 'serverinfo'), + $config->get( 'biblioserver', 'serverinfo' ), { - 'ccl2rpn' => '/home/koha/etc/zebradb/ccl.properties', - 'user' => 'kohauser', + 'ccl2rpn' => '/home/koha/etc/zebradb/ccl.properties', + 'user' => 'kohauser', 'password' => 'zebrastripes', }, ); - is($config->get('db_scheme'), 'mysql'); - is($config->get('ca'), ''); + is( $config->get('db_scheme'), 'mysql' ); + is( $config->get('ca'), '' ); - is($config->get('unicorn'), undef, 'returns undef if key does not exist'); - is_deeply([$config->get('unicorn')], [undef], 'returns undef even in list context'); + is( $config->get('unicorn'), undef, 'returns undef if key does not exist' ); + is_deeply( [ $config->get('unicorn') ], [undef], 'returns undef even in list context' ); }; diff --git a/t/Koha/Database/Columns.t b/t/Koha/Database/Columns.t index ff9191c678..9de820e344 100755 --- a/t/Koha/Database/Columns.t +++ b/t/Koha/Database/Columns.t @@ -24,10 +24,10 @@ use Encode; use Koha::Database::Columns; my $koha_i18n = Test::MockModule->new('Koha::I18N'); -$koha_i18n->mock('_base_directory', sub { "$Bin/../I18N/po" }); +$koha_i18n->mock( '_base_directory', sub { "$Bin/../I18N/po" } ); my $c4_languages = Test::MockModule->new('C4::Languages'); -$c4_languages->mock('getlanguage', sub { 'xx-XX' }); +$c4_languages->mock( 'getlanguage', sub { 'xx-XX' } ); my $columns = Koha::Database::Columns->columns; diff --git a/t/Koha/Email.t b/t/Koha/Email.t index 69fed9c875..ea323240e8 100755 --- a/t/Koha/Email.t +++ b/t/Koha/Email.t @@ -68,18 +68,18 @@ subtest 'create() tests' => sub { $email = Koha::Email->create( { - from => 'from@8.8.8.8', - to => 'to@example.com', - bcc => 'root@localhost', + from => 'from@8.8.8.8', + to => 'to@example.com', + bcc => 'root@localhost', } ); - is( $email->email->header('Bcc'), 'root@localhost', 'Non-FQDN (@localhost) supported' ); - is( $email->email->header('From'), 'from@8.8.8.8', 'IPs supported' ); + is( $email->email->header('Bcc'), 'root@localhost', 'Non-FQDN (@localhost) supported' ); + is( $email->email->header('From'), 'from@8.8.8.8', 'IPs supported' ); - t::lib::Mocks::mock_preference( 'SendAllEmailsTo', 'catchall@example.com' ); - t::lib::Mocks::mock_preference( 'ReplytoDefault', 'replytodefault@example.com' ); - t::lib::Mocks::mock_preference( 'ReturnpathDefault', 'returnpathdefault@example.com' ); + t::lib::Mocks::mock_preference( 'SendAllEmailsTo', 'catchall@example.com' ); + t::lib::Mocks::mock_preference( 'ReplytoDefault', 'replytodefault@example.com' ); + t::lib::Mocks::mock_preference( 'ReturnpathDefault', 'returnpathdefault@example.com' ); t::lib::Mocks::mock_preference( 'KohaAdminEmailAddress', 'kohaadminemailaddress@example.com' ); $email = Koha::Email->create( @@ -91,102 +91,111 @@ subtest 'create() tests' => sub { } ); - is( $email->email->header('From'), 'kohaadminemailaddress@example.com', 'KohaAdminEmailAddress is picked when no from passed' ); - is( $email->email->header('To'), 'catchall@example.com', 'SendAllEmailsTo overloads any address' ); - is( $email->email->header('Cc'), undef, 'SendAllEmailsTo overloads any address' ); - is( $email->email->header('Bcc'), undef, 'SendAllEmailsTo overloads any address' ); - is( $email->email->header('Reply-To'), 'replytodefault@example.com', 'ReplytoDefault picked when replyto not passed' ); - is( $email->email->header('Sender'), 'returnpathdefault@example.com', 'ReturnpathDefault picked when sender not passed' ); - is( $email->email->header('Subject'), '', 'No subject passed, empty string' ); - is( $email->email->body, $text_body, "Body set correctly" ); - like( $email->email->content_type, qr|text/plain|, "Content type set correctly"); - like( $email->email->content_type, qr|charset="?utf-8"?|, "Charset set correctly"); + is( + $email->email->header('From'), 'kohaadminemailaddress@example.com', + 'KohaAdminEmailAddress is picked when no from passed' + ); + is( $email->email->header('To'), 'catchall@example.com', 'SendAllEmailsTo overloads any address' ); + is( $email->email->header('Cc'), undef, 'SendAllEmailsTo overloads any address' ); + is( $email->email->header('Bcc'), undef, 'SendAllEmailsTo overloads any address' ); + is( + $email->email->header('Reply-To'), 'replytodefault@example.com', + 'ReplytoDefault picked when replyto not passed' + ); + is( + $email->email->header('Sender'), 'returnpathdefault@example.com', + 'ReturnpathDefault picked when sender not passed' + ); + is( $email->email->header('Subject'), '', 'No subject passed, empty string' ); + is( $email->email->body, $text_body, "Body set correctly" ); + like( $email->email->content_type, qr|text/plain|, "Content type set correctly" ); + like( $email->email->content_type, qr|charset="?utf-8"?|, "Charset set correctly" ); subtest 'exception cases' => sub { plan tests => 16; - throws_ok - { Koha::Email->create({ from => 'not_an_email' }); } - 'Koha::Exceptions::BadParameter', + throws_ok { Koha::Email->create( { from => 'not_an_email' } ); } + 'Koha::Exceptions::BadParameter', 'Exception thrown correctly'; like( "$@", qr/Invalid 'from' parameter: not_an_email/, 'Exception message correct' ); t::lib::Mocks::mock_preference( 'KohaAdminEmailAddress', 'not_an_email' ); - throws_ok - { Koha::Email->create({ }); } - 'Koha::Exceptions::BadParameter', + throws_ok { Koha::Email->create( {} ); } + 'Koha::Exceptions::BadParameter', 'Exception thrown correctly'; like( "$@", qr/Invalid 'from' parameter: not_an_email/, 'Exception message correct' ); t::lib::Mocks::mock_preference( 'KohaAdminEmailAddress', 'tomasito@mail.com' ); - t::lib::Mocks::mock_preference( 'SendAllEmailsTo', undef ); + t::lib::Mocks::mock_preference( 'SendAllEmailsTo', undef ); - throws_ok - { Koha::Email->create({ to => 'not_an_email' }); } - 'Koha::Exceptions::BadParameter', + throws_ok { Koha::Email->create( { to => 'not_an_email' } ); } + 'Koha::Exceptions::BadParameter', 'Exception thrown correctly'; like( "$@", qr/Invalid 'to' parameter: not_an_email/, 'Exception message correct' ); t::lib::Mocks::mock_preference( 'SendAllEmailsTo', 'not_an_email' ); - throws_ok - { Koha::Email->create({ }); } - 'Koha::Exceptions::BadParameter', + throws_ok { Koha::Email->create( {} ); } + 'Koha::Exceptions::BadParameter', 'Exception thrown correctly'; like( "$@", qr/Invalid 'to' parameter: not_an_email/, 'Exception message correct' ); t::lib::Mocks::mock_preference( 'SendAllEmailsTo', undef ); - throws_ok - { Koha::Email->create( + throws_ok { + Koha::Email->create( { to => 'tomasito@mail.com', reply_to => 'not_an_email' } - ); } - 'Koha::Exceptions::BadParameter', + ); + } + 'Koha::Exceptions::BadParameter', 'Exception thrown correctly'; like( "$@", qr/Invalid 'reply_to' parameter: not_an_email/, 'Exception message correct' ); - throws_ok - { Koha::Email->create( + throws_ok { + Koha::Email->create( { to => 'tomasito@mail.com', sender => 'not_an_email' } - ); } - 'Koha::Exceptions::BadParameter', + ); + } + 'Koha::Exceptions::BadParameter', 'Exception thrown correctly'; like( "$@", qr/Invalid 'sender' parameter: not_an_email/, 'Exception message correct' ); - throws_ok - { Koha::Email->create( + throws_ok { + Koha::Email->create( { to => 'tomasito@mail.com', cc => 'not_an_email' } - ); } - 'Koha::Exceptions::BadParameter', + ); + } + 'Koha::Exceptions::BadParameter', 'Exception thrown correctly'; like( "$@", qr/Invalid 'cc' parameter: not_an_email/, 'Exception message correct' ); - throws_ok - { Koha::Email->create( + throws_ok { + Koha::Email->create( { to => 'tomasito@mail.com', bcc => 'not_an_email' } - ); } - 'Koha::Exceptions::BadParameter', + ); + } + 'Koha::Exceptions::BadParameter', 'Exception thrown correctly'; like( "$@", qr/Invalid 'bcc' parameter: not_an_email/, 'Exception message correct' ); @@ -235,11 +244,12 @@ subtest 'send_or_die() tests' => sub { 'Bcc header set correctly' ); - $THE_email->send_or_die( - { transport => $transport, to => ['tomasito@mail.com'], from => 'returns@example.com' } ); - is_deeply( $args->{to}, ['tomasito@mail.com'], - 'If explicitly passed, "to" is preserved' ); - is( $args->{from}, 'returns@example.com', 'If explicitly pass, "from" is preserved'); + $THE_email->send_or_die( { transport => $transport, to => ['tomasito@mail.com'], from => 'returns@example.com' } ); + is_deeply( + $args->{to}, ['tomasito@mail.com'], + 'If explicitly passed, "to" is preserved' + ); + is( $args->{from}, 'returns@example.com', 'If explicitly pass, "from" is preserved' ); $THE_email->send_or_die( { transport => $transport } ); my @to = sort @{ $args->{to} }; @@ -253,22 +263,23 @@ subtest 'send_or_die() tests' => sub { ); is( $email->header_str('Bcc'), undef, 'The Bcc header is unset' ); my $from = $args->{from}; - is( $from, 'sender@example.com', 'If "from" is not explicitly passed, extract from Sender header' ); + is( $from, 'sender@example.com', 'If "from" is not explicitly passed, extract from Sender header' ); is( $email->header_str('Sender'), undef, 'The Sender header is unset' ); }; subtest 'is_valid' => sub { plan tests => 8; - is(Koha::Email->is_valid('Fróm '), 1); - is(Koha::Email->is_valid('from@example.com'), 1); - is(Koha::Email->is_valid(''), 1); - is(Koha::Email->is_valid('root@localhost'), 1); # See bug 28017 + is( Koha::Email->is_valid('Fróm '), 1 ); + is( Koha::Email->is_valid('from@example.com'), 1 ); + is( Koha::Email->is_valid(''), 1 ); + is( Koha::Email->is_valid('root@localhost'), 1 ); # See bug 28017 - is(Koha::Email->is_valid(''), 0); # "In accordance with RFC 822 and its descendants, this module demands that email addresses be ASCII only" - isnt(Koha::Email->is_valid('@example.com'), 1); - isnt(Koha::Email->is_valid('example.com'), 1); - isnt(Koha::Email->is_valid('from'), 1); + is( Koha::Email->is_valid(''), 0 ) + ; # "In accordance with RFC 822 and its descendants, this module demands that email addresses be ASCII only" + isnt( Koha::Email->is_valid('@example.com'), 1 ); + isnt( Koha::Email->is_valid('example.com'), 1 ); + isnt( Koha::Email->is_valid('from'), 1 ); }; subtest 'new_from_string() tests' => sub { @@ -276,7 +287,7 @@ subtest 'new_from_string() tests' => sub { plan tests => 1; my $html_body = '

            Title

            Message

            '; - my $email_1 = Koha::Email->create( + my $email_1 = Koha::Email->create( { from => 'Fróm ', to => 'Tö ', @@ -290,8 +301,8 @@ subtest 'new_from_string() tests' => sub { } ); - my $string = $email_1->as_string; - my $email_2 = Koha::Email->new_from_string( $string ); + my $string = $email_1->as_string; + my $email_2 = Koha::Email->new_from_string($string); is( $email_1->as_string, $email_2->as_string, 'Emails match' ); }; diff --git a/t/Koha/Exceptions.t b/t/Koha/Exceptions.t index 9a6ce3ab37..ac4a7e7d77 100755 --- a/t/Koha/Exceptions.t +++ b/t/Koha/Exceptions.t @@ -27,17 +27,15 @@ subtest 'Koha::Exceptions::Hold tests' => sub { use_ok('Koha::Exceptions::Hold'); - throws_ok - { Koha::Exceptions::Hold::CannotSuspendFound->throw( status => 'W' ); } - 'Koha::Exceptions::Hold::CannotSuspendFound', + throws_ok { Koha::Exceptions::Hold::CannotSuspendFound->throw( status => 'W' ); } + 'Koha::Exceptions::Hold::CannotSuspendFound', 'Exception is thrown :-D'; # stringify the exception is( "$@", 'Found hold cannot be suspended. Status=W', 'Exception stringified correctly' ); - throws_ok - { Koha::Exceptions::Hold::CannotSuspendFound->throw( "Manual message exception" ) } - 'Koha::Exceptions::Hold::CannotSuspendFound', + throws_ok { Koha::Exceptions::Hold::CannotSuspendFound->throw("Manual message exception") } + 'Koha::Exceptions::Hold::CannotSuspendFound', 'Exception is thrown :-D'; is( "$@", 'Manual message exception', 'Exception not stringified if manually passed' ); }; @@ -48,17 +46,15 @@ subtest 'Koha::Exceptions::Object::FKConstraint tests' => sub { use_ok('Koha::Exceptions::Object'); - throws_ok - { Koha::Exceptions::Object::FKConstraint->throw( broken_fk => 'nasty', value => 'fk' ); } - 'Koha::Exceptions::Object::FKConstraint', + throws_ok { Koha::Exceptions::Object::FKConstraint->throw( broken_fk => 'nasty', value => 'fk' ); } + 'Koha::Exceptions::Object::FKConstraint', 'Exception is thrown :-D'; # stringify the exception is( "$@", 'Invalid parameter passed, nasty=fk does not exist', 'Exception stringified correctly' ); - throws_ok - { Koha::Exceptions::Object::FKConstraint->throw( "Manual message exception" ) } - 'Koha::Exceptions::Object::FKConstraint', + throws_ok { Koha::Exceptions::Object::FKConstraint->throw("Manual message exception") } + 'Koha::Exceptions::Object::FKConstraint', 'Exception is thrown :-D'; is( "$@", 'Manual message exception', 'Exception not stringified if manually passed' ); @@ -73,11 +69,13 @@ subtest 'Koha::Exceptions::Object::FKConstraint tests' => sub { 'Koha::Exceptions::Object::BadValue exception is thrown :-D'; # stringify the exception - is( "$@", 'Invalid value passed, a_property=a_value expected type is datetime', 'Koha::Exceptions::Object::BadValue stringified correctly' ); + is( + "$@", 'Invalid value passed, a_property=a_value expected type is datetime', + 'Koha::Exceptions::Object::BadValue stringified correctly' + ); - throws_ok - { Koha::Exceptions::Object::BadValue->throw( "Manual message exception" ) } - 'Koha::Exceptions::Object::BadValue', + throws_ok { Koha::Exceptions::Object::BadValue->throw("Manual message exception") } + 'Koha::Exceptions::Object::BadValue', 'Koha::Exceptions::Object::BadValue is thrown :-D'; is( "$@", 'Manual message exception', 'Koha::Exceptions::Object::BadValue not stringified if manually passed' ); }; @@ -88,17 +86,15 @@ subtest 'Koha::Exceptions::Password tests' => sub { use_ok('Koha::Exceptions::Password'); - throws_ok - { Koha::Exceptions::Password::TooShort->throw( length => 4, min_length => 5 ); } - 'Koha::Exceptions::Password::TooShort', + throws_ok { Koha::Exceptions::Password::TooShort->throw( length => 4, min_length => 5 ); } + 'Koha::Exceptions::Password::TooShort', 'Exception is thrown :-D'; # stringify the exception is( "$@", 'Password length (4) is shorter than required (5)', 'Exception stringified correctly' ); - throws_ok - { Koha::Exceptions::Password::TooShort->throw( "Manual message exception" ) } - 'Koha::Exceptions::Password::TooShort', + throws_ok { Koha::Exceptions::Password::TooShort->throw("Manual message exception") } + 'Koha::Exceptions::Password::TooShort', 'Exception is thrown :-D'; is( "$@", 'Manual message exception', 'Exception not stringified if manually passed' ); }; @@ -110,24 +106,29 @@ subtest 'Koha::Exceptions::Metadata tests' => sub { use_ok('Koha::Exceptions::Metadata'); my $object = Test::MockObject->new; - $object->mock( 'id', 'an_id' ); + $object->mock( 'id', 'an_id' ); $object->mock( 'biblionumber', 'a_biblionumber' ); - $object->mock( 'format', 'a_format' ); - $object->mock( 'schema', 'a_schema' ); + $object->mock( 'format', 'a_format' ); + $object->mock( 'schema', 'a_schema' ); - throws_ok - { Koha::Exceptions::Metadata::Invalid->throw( - id => 'an_id', biblionumber => 'a_biblionumber', format => 'a_format', - schema => 'a_schema', decoding_error => 'a_nasty_error' ); } - 'Koha::Exceptions::Metadata::Invalid', + throws_ok { + Koha::Exceptions::Metadata::Invalid->throw( + id => 'an_id', biblionumber => 'a_biblionumber', format => 'a_format', + schema => 'a_schema', decoding_error => 'a_nasty_error' + ); + } + 'Koha::Exceptions::Metadata::Invalid', 'Exception is thrown :-D'; # stringify the exception - is( "$@", 'Invalid data, cannot decode metadata object (biblio_metadata.id=an_id, biblionumber=a_biblionumber, format=a_format, schema=a_schema, decoding_error=\'a_nasty_error\')', 'Exception stringified correctly' ); + is( + "$@", + 'Invalid data, cannot decode metadata object (biblio_metadata.id=an_id, biblionumber=a_biblionumber, format=a_format, schema=a_schema, decoding_error=\'a_nasty_error\')', + 'Exception stringified correctly' + ); - throws_ok - { Koha::Exceptions::Metadata::Invalid->throw( "Manual message exception" ) } - 'Koha::Exceptions::Metadata::Invalid', + throws_ok { Koha::Exceptions::Metadata::Invalid->throw("Manual message exception") } + 'Koha::Exceptions::Metadata::Invalid', 'Exception is thrown :-D'; is( "$@", 'Manual message exception', 'Exception not stringified if manually passed' ); }; @@ -138,17 +139,15 @@ subtest 'Koha::Exceptions::Patron::Relationship tests' => sub { use_ok('Koha::Exceptions::Patron::Relationship'); - throws_ok - { Koha::Exceptions::Patron::Relationship::InvalidRelationship->throw( no_relationship => 1 ); } - 'Koha::Exceptions::Patron::Relationship::InvalidRelationship', + throws_ok { Koha::Exceptions::Patron::Relationship::InvalidRelationship->throw( no_relationship => 1 ); } + 'Koha::Exceptions::Patron::Relationship::InvalidRelationship', 'Exception is thrown :-D'; # stringify the exception is( "$@", 'No relationship passed.', 'Exception stringified correctly' ); - throws_ok - { Koha::Exceptions::Patron::Relationship::InvalidRelationship->throw( relationship => 'some' ); } - 'Koha::Exceptions::Patron::Relationship::InvalidRelationship', + throws_ok { Koha::Exceptions::Patron::Relationship::InvalidRelationship->throw( relationship => 'some' ); } + 'Koha::Exceptions::Patron::Relationship::InvalidRelationship', 'Exception is thrown :-D'; # stringify the exception @@ -166,14 +165,14 @@ subtest 'Koha::Exceptions::Patron::Relationship tests' => sub { 'Koha::Exceptions::Patron::Relationship::DuplicateRelationship', 'Exception is thrown :-D'; # stringify the exception - is( "$@", + is( + "$@", "There already exists a relationship for the same guarantor ($guarantor_id) and guarantee ($guarantee_id) combination", 'Exception stringified correctly' ); - throws_ok - { Koha::Exceptions::Patron::Relationship::InvalidRelationship->throw( "Manual message exception" ) } - 'Koha::Exceptions::Patron::Relationship::InvalidRelationship', + throws_ok { Koha::Exceptions::Patron::Relationship::InvalidRelationship->throw("Manual message exception") } + 'Koha::Exceptions::Patron::Relationship::InvalidRelationship', 'Exception is thrown :-D'; is( "$@", 'Manual message exception', 'Exception not stringified if manually passed' ); }; @@ -182,18 +181,20 @@ subtest 'Koha::Exceptions::Object::NotInstantiated tests' => sub { plan tests => 4; - throws_ok - { Koha::Exceptions::Object::NotInstantiated->throw( - method => 'brain_explode', class => 'Koha::JD' ); } - 'Koha::Exceptions::Object::NotInstantiated', + throws_ok { + Koha::Exceptions::Object::NotInstantiated->throw( method => 'brain_explode', class => 'Koha::JD' ); + } + 'Koha::Exceptions::Object::NotInstantiated', 'Exception is thrown :-D'; # stringify the exception - is( "$@", 'Tried to access the \'brain_explode\' method, but Koha::JD is not instantiated', 'Exception stringified correctly' ); + is( + "$@", 'Tried to access the \'brain_explode\' method, but Koha::JD is not instantiated', + 'Exception stringified correctly' + ); - throws_ok - { Koha::Exceptions::Object::NotInstantiated->throw( "Manual message exception" ) } - 'Koha::Exceptions::Object::NotInstantiated', + throws_ok { Koha::Exceptions::Object::NotInstantiated->throw("Manual message exception") } + 'Koha::Exceptions::Object::NotInstantiated', 'Exception is thrown :-D'; is( "$@", 'Manual message exception', 'Exception not stringified if manually passed' ); }; @@ -208,13 +209,13 @@ subtest 'Koha::Exceptions::Patron::Attribute::* tests' => sub { my $attribute = 'ATTRIBUTE'; my $mocked_attribute = Test::MockObject->new(); - $mocked_attribute->mock('code', sub { return $code } ); - $mocked_attribute->mock('attribute', sub { return $attribute } ); + $mocked_attribute->mock( 'code', sub { return $code } ); + $mocked_attribute->mock( 'attribute', sub { return $attribute } ); - throws_ok - { Koha::Exceptions::Patron::Attribute::NonRepeatable->throw( - attribute => $mocked_attribute ); } - 'Koha::Exceptions::Patron::Attribute::NonRepeatable', + throws_ok { + Koha::Exceptions::Patron::Attribute::NonRepeatable->throw( attribute => $mocked_attribute ); + } + 'Koha::Exceptions::Patron::Attribute::NonRepeatable', 'Exception is thrown :-D'; # stringify the exception @@ -224,9 +225,8 @@ subtest 'Koha::Exceptions::Patron::Attribute::* tests' => sub { 'Exception stringified correctly' ); - throws_ok - { Koha::Exceptions::Patron::Attribute::NonRepeatable->throw( "Manual message exception" ) } - 'Koha::Exceptions::Patron::Attribute::NonRepeatable', + throws_ok { Koha::Exceptions::Patron::Attribute::NonRepeatable->throw("Manual message exception") } + 'Koha::Exceptions::Patron::Attribute::NonRepeatable', 'Exception is thrown :-D'; is( @@ -235,10 +235,10 @@ subtest 'Koha::Exceptions::Patron::Attribute::* tests' => sub { 'Exception not stringified if manually passed' ); - throws_ok - { Koha::Exceptions::Patron::Attribute::UniqueIDConstraint->throw( - attribute => $mocked_attribute ); } - 'Koha::Exceptions::Patron::Attribute::UniqueIDConstraint', + throws_ok { + Koha::Exceptions::Patron::Attribute::UniqueIDConstraint->throw( attribute => $mocked_attribute ); + } + 'Koha::Exceptions::Patron::Attribute::UniqueIDConstraint', 'Exception is thrown :-D'; # stringify the exception @@ -248,9 +248,8 @@ subtest 'Koha::Exceptions::Patron::Attribute::* tests' => sub { 'Exception stringified correctly' ); - throws_ok - { Koha::Exceptions::Patron::Attribute::UniqueIDConstraint->throw( "Manual message exception" ) } - 'Koha::Exceptions::Patron::Attribute::UniqueIDConstraint', + throws_ok { Koha::Exceptions::Patron::Attribute::UniqueIDConstraint->throw("Manual message exception") } + 'Koha::Exceptions::Patron::Attribute::UniqueIDConstraint', 'Exception is thrown :-D'; is( @@ -261,10 +260,10 @@ subtest 'Koha::Exceptions::Patron::Attribute::* tests' => sub { my $type = "SOME_TYPE"; - throws_ok - { Koha::Exceptions::Patron::Attribute::InvalidType->throw( - type => $type ); } - 'Koha::Exceptions::Patron::Attribute::InvalidType', + throws_ok { + Koha::Exceptions::Patron::Attribute::InvalidType->throw( type => $type ); + } + 'Koha::Exceptions::Patron::Attribute::InvalidType', 'Exception is thrown :-D'; # stringify the exception @@ -274,9 +273,8 @@ subtest 'Koha::Exceptions::Patron::Attribute::* tests' => sub { 'Exception stringified correctly' ); - throws_ok - { Koha::Exceptions::Patron::Attribute::InvalidType->throw( "Manual message exception" ) } - 'Koha::Exceptions::Patron::Attribute::InvalidType', + throws_ok { Koha::Exceptions::Patron::Attribute::InvalidType->throw("Manual message exception") } + 'Koha::Exceptions::Patron::Attribute::InvalidType', 'Exception is thrown :-D'; is( @@ -294,18 +292,17 @@ subtest 'Koha::Exceptions::Patron tests' => sub { my $type = 'yahey'; - throws_ok - { Koha::Exceptions::Patron::MissingMandatoryExtendedAttribute->throw( - type => $type ); } - 'Koha::Exceptions::Patron::MissingMandatoryExtendedAttribute', + throws_ok { + Koha::Exceptions::Patron::MissingMandatoryExtendedAttribute->throw( type => $type ); + } + 'Koha::Exceptions::Patron::MissingMandatoryExtendedAttribute', 'Exception is thrown :-D'; # stringify the exception is( "$@", "Missing mandatory extended attribute (type=$type)", 'Exception stringified correctly' ); - throws_ok - { Koha::Exceptions::Patron::MissingMandatoryExtendedAttribute->throw( "Manual message exception" ) } - 'Koha::Exceptions::Patron::MissingMandatoryExtendedAttribute', + throws_ok { Koha::Exceptions::Patron::MissingMandatoryExtendedAttribute->throw("Manual message exception") } + 'Koha::Exceptions::Patron::MissingMandatoryExtendedAttribute', 'Exception is thrown :-D'; is( "$@", 'Manual message exception', 'Exception not stringified if manually passed' ); }; @@ -318,19 +315,19 @@ subtest 'Koha::Exceptions::Plugin tests' => sub { my $plugin_class = 'yahey'; - throws_ok - { Koha::Exceptions::Plugin::InstallDied->throw( - plugin_class => $plugin_class ); } - 'Koha::Exceptions::Plugin::InstallDied', + throws_ok { + Koha::Exceptions::Plugin::InstallDied->throw( plugin_class => $plugin_class ); + } + 'Koha::Exceptions::Plugin::InstallDied', 'Exception is thrown :-D'; # stringify the exception is( "$@", "Calling 'install' died for plugin $plugin_class", 'Exception stringified correctly' ); - throws_ok - { Koha::Exceptions::Plugin::UpgradeDied->throw( - plugin_class => $plugin_class ); } - 'Koha::Exceptions::Plugin::UpgradeDied', + throws_ok { + Koha::Exceptions::Plugin::UpgradeDied->throw( plugin_class => $plugin_class ); + } + 'Koha::Exceptions::Plugin::UpgradeDied', 'Exception is thrown :-D'; # stringify the exception @@ -349,6 +346,7 @@ subtest 'Koha::Exceptions::Booking tests' => sub { # stringify the exception is( "$@", '[Adding or updating the booking would result in a clash]', 'Exception stringified correctly' ); + # FIXME: I don't understand why the stringified message here gets wrapped in square brackets... }; @@ -368,9 +366,8 @@ subtest 'Koha::Exception tests' => sub { my $exception_message = "This is a message"; - throws_ok - { Koha::Exceptions::Weird->throw( $exception_message ) } - 'Koha::Exception', + throws_ok { Koha::Exceptions::Weird->throw($exception_message) } + 'Koha::Exception', 'Exception is thrown :-D'; is( @@ -379,9 +376,8 @@ subtest 'Koha::Exception tests' => sub { 'Exception not stringified if manually passed' ); - throws_ok - { Koha::Exceptions::Weird->throw( a => "A", b => "B" ) } - 'Koha::Exception', + throws_ok { Koha::Exceptions::Weird->throw( a => "A", b => "B" ) } + 'Koha::Exception', 'Exception is thrown :-D'; is( @@ -390,9 +386,8 @@ subtest 'Koha::Exception tests' => sub { 'Exception stringified correctly' ); - throws_ok - { Koha::Exceptions::Weird->throw( a => "A" ) } - 'Koha::Exception', + throws_ok { Koha::Exceptions::Weird->throw( a => "A" ) } + 'Koha::Exception', 'Exception is thrown :-D'; is( @@ -401,9 +396,8 @@ subtest 'Koha::Exception tests' => sub { 'Exception stringified correctly, b skipped entirely' ); - throws_ok - { Koha::Exceptions::Weird->throw() } - 'Koha::Exception', + throws_ok { Koha::Exceptions::Weird->throw() } + 'Koha::Exception', 'Exception is thrown :-D'; is( @@ -418,9 +412,10 @@ subtest 'Passing parameters when throwing exception' => sub { use Koha::Exceptions; - throws_ok { Koha::Exceptions::WrongParameter->throw( name => 'wrong1', type => 'ARRAY', value => [ 1, 2 ] ) } qr/Koha::Exceptions::WrongParameter/, 'Exception thrown'; + throws_ok { Koha::Exceptions::WrongParameter->throw( name => 'wrong1', type => 'ARRAY', value => [ 1, 2 ] ) } + qr/Koha::Exceptions::WrongParameter/, 'Exception thrown'; my $desc = $@; - like( $desc, qr/name => wrong1/, 'Found name' ); - like( $desc, qr/type => ARRAY/, 'Found type' ); + like( $desc, qr/name => wrong1/, 'Found name' ); + like( $desc, qr/type => ARRAY/, 'Found type' ); like( $desc, qr/value => ARRAY\(\w+\)/, 'Found value' ); }; diff --git a/t/Koha/I18N.t b/t/Koha/I18N.t index 6524e66e80..7dfa623c41 100755 --- a/t/Koha/I18N.t +++ b/t/Koha/I18N.t @@ -11,52 +11,52 @@ BEGIN { } my $koha_i18n = Test::MockModule->new('Koha::I18N'); -$koha_i18n->mock('_base_directory', sub { "$Bin/I18N/po" }); +$koha_i18n->mock( '_base_directory', sub { "$Bin/I18N/po" } ); my $c4_languages = Test::MockModule->new('C4::Languages'); -$c4_languages->mock('getlanguage', sub { 'xx-XX' }); +$c4_languages->mock( 'getlanguage', sub { 'xx-XX' } ); # If you need to modify the MO file to add new tests # 1) msgunfmt -o Koha.po t/Koha/I18N/po/xx_XX/LC_MESSAGES/Koha.mo # 2) Edit Koha.po # 3) msgfmt -o t/Koha/I18N/po/xx_XX/LC_MESSAGES/Koha.mo Koha.po my @tests = ( - [ __('test') => 'test ツ' ], - [ __x('Hello {name}', name => 'World') => 'Hello World ツ' ], - [ __n('Singular', 'Plural', 0) => 'Zero ツ' ], - [ __n('Singular', 'Plural', 1) => 'Singular ツ' ], - [ __n('Singular', 'Plural', 2) => 'Plural ツ' ], - [ __n('Singular', 'Plural', 3) => 'Plural ツ' ], - [ __nx('one item', '{count} items', 0, count => 0) => 'no item ツ' ], - [ __nx('one item', '{count} items', 1, count => 1) => 'one item ツ' ], - [ __nx('one item', '{count} items', 2, count => 2) => '2 items ツ' ], - [ __nx('one item', '{count} items', 3, count => 3) => '3 items ツ' ], - [ __xn('one item', '{count} items', 0, count => 0) => 'no item ツ' ], - [ __xn('one item', '{count} items', 1, count => 1) => 'one item ツ' ], - [ __xn('one item', '{count} items', 2, count => 2) => '2 items ツ' ], - [ __xn('one item', '{count} items', 3, count => 3) => '3 items ツ' ], - [ __p('biblio', 'title') => 'title (biblio) ツ' ], - [ __p('patron', 'title') => 'title (patron) ツ' ], - [ __px('biblio', 'Remove item {id}', id => 42) => 'Remove item 42 (biblio) ツ' ], - [ __px('list', 'Remove item {id}', id => 42) => 'Remove item 42 (list) ツ' ], - [ __np('ctxt1', 'singular', 'plural', 0) => 'zero (ctxt1) ツ' ], - [ __np('ctxt1', 'singular', 'plural', 1) => 'singular (ctxt1) ツ' ], - [ __np('ctxt1', 'singular', 'plural', 2) => 'plural (ctxt1) ツ' ], - [ __np('ctxt1', 'singular', 'plural', 3) => 'plural (ctxt1) ツ' ], - [ __np('ctxt2', 'singular', 'plural', 0) => 'zero (ctxt2) ツ' ], - [ __np('ctxt2', 'singular', 'plural', 1) => 'singular (ctxt2) ツ' ], - [ __np('ctxt2', 'singular', 'plural', 2) => 'plural (ctxt2) ツ' ], - [ __np('ctxt2', 'singular', 'plural', 3) => 'plural (ctxt2) ツ' ], - [ __npx('biblio', 'one item', '{count} items', 0, count => 0) => 'no item (biblio) ツ' ], - [ __npx('biblio', 'one item', '{count} items', 1, count => 1) => 'one item (biblio) ツ' ], - [ __npx('biblio', 'one item', '{count} items', 2, count => 2) => '2 items (biblio) ツ' ], - [ __npx('biblio', 'one item', '{count} items', 3, count => 3) => '3 items (biblio) ツ' ], - [ __npx('list', 'one item', '{count} items', 0, count => 0) => 'no item (list) ツ' ], - [ __npx('list', 'one item', '{count} items', 1, count => 1) => 'one item (list) ツ' ], - [ __npx('list', 'one item', '{count} items', 2, count => 2) => '2 items (list) ツ' ], - [ __npx('list', 'one item', '{count} items', 3, count => 3) => '3 items (list) ツ' ], + [ __('test') => 'test ツ' ], + [ __x( 'Hello {name}', name => 'World' ) => 'Hello World ツ' ], + [ __n( 'Singular', 'Plural', 0 ) => 'Zero ツ' ], + [ __n( 'Singular', 'Plural', 1 ) => 'Singular ツ' ], + [ __n( 'Singular', 'Plural', 2 ) => 'Plural ツ' ], + [ __n( 'Singular', 'Plural', 3 ) => 'Plural ツ' ], + [ __nx( 'one item', '{count} items', 0, count => 0 ) => 'no item ツ' ], + [ __nx( 'one item', '{count} items', 1, count => 1 ) => 'one item ツ' ], + [ __nx( 'one item', '{count} items', 2, count => 2 ) => '2 items ツ' ], + [ __nx( 'one item', '{count} items', 3, count => 3 ) => '3 items ツ' ], + [ __xn( 'one item', '{count} items', 0, count => 0 ) => 'no item ツ' ], + [ __xn( 'one item', '{count} items', 1, count => 1 ) => 'one item ツ' ], + [ __xn( 'one item', '{count} items', 2, count => 2 ) => '2 items ツ' ], + [ __xn( 'one item', '{count} items', 3, count => 3 ) => '3 items ツ' ], + [ __p( 'biblio', 'title' ) => 'title (biblio) ツ' ], + [ __p( 'patron', 'title' ) => 'title (patron) ツ' ], + [ __px( 'biblio', 'Remove item {id}', id => 42 ) => 'Remove item 42 (biblio) ツ' ], + [ __px( 'list', 'Remove item {id}', id => 42 ) => 'Remove item 42 (list) ツ' ], + [ __np( 'ctxt1', 'singular', 'plural', 0 ) => 'zero (ctxt1) ツ' ], + [ __np( 'ctxt1', 'singular', 'plural', 1 ) => 'singular (ctxt1) ツ' ], + [ __np( 'ctxt1', 'singular', 'plural', 2 ) => 'plural (ctxt1) ツ' ], + [ __np( 'ctxt1', 'singular', 'plural', 3 ) => 'plural (ctxt1) ツ' ], + [ __np( 'ctxt2', 'singular', 'plural', 0 ) => 'zero (ctxt2) ツ' ], + [ __np( 'ctxt2', 'singular', 'plural', 1 ) => 'singular (ctxt2) ツ' ], + [ __np( 'ctxt2', 'singular', 'plural', 2 ) => 'plural (ctxt2) ツ' ], + [ __np( 'ctxt2', 'singular', 'plural', 3 ) => 'plural (ctxt2) ツ' ], + [ __npx( 'biblio', 'one item', '{count} items', 0, count => 0 ) => 'no item (biblio) ツ' ], + [ __npx( 'biblio', 'one item', '{count} items', 1, count => 1 ) => 'one item (biblio) ツ' ], + [ __npx( 'biblio', 'one item', '{count} items', 2, count => 2 ) => '2 items (biblio) ツ' ], + [ __npx( 'biblio', 'one item', '{count} items', 3, count => 3 ) => '3 items (biblio) ツ' ], + [ __npx( 'list', 'one item', '{count} items', 0, count => 0 ) => 'no item (list) ツ' ], + [ __npx( 'list', 'one item', '{count} items', 1, count => 1 ) => 'one item (list) ツ' ], + [ __npx( 'list', 'one item', '{count} items', 2, count => 2 ) => '2 items (list) ツ' ], + [ __npx( 'list', 'one item', '{count} items', 3, count => 3 ) => '3 items (list) ツ' ], ); foreach my $test (@tests) { - is($test->[0], decode_utf8($test->[1]), $test->[1]); + is( $test->[0], decode_utf8( $test->[1] ), $test->[1] ); } diff --git a/t/Koha/Middleware/RealIP.t b/t/Koha/Middleware/RealIP.t index 2ec8e51b89..0391f48cc4 100755 --- a/t/Koha/Middleware/RealIP.t +++ b/t/Koha/Middleware/RealIP.t @@ -26,117 +26,142 @@ use Test::Warn; use t::lib::Mocks; use_ok("Koha::Middleware::RealIP"); -my ($remote_address,$x_forwarded_for_header,$address); +my ( $remote_address, $x_forwarded_for_header, $address ); subtest "No X-Forwarded-For header" => sub { plan tests => 1; - $remote_address = "1.1.1.1"; + $remote_address = "1.1.1.1"; $x_forwarded_for_header = ""; - $address = Koha::Middleware::RealIP::get_real_ip( $remote_address, $x_forwarded_for_header ); - is($address,'1.1.1.1',"There is no X-Forwarded-For header, so just use the remote address"); + $address = Koha::Middleware::RealIP::get_real_ip( $remote_address, $x_forwarded_for_header ); + is( $address, '1.1.1.1', "There is no X-Forwarded-For header, so just use the remote address" ); }; subtest "No configuration" => sub { plan tests => 1; - $remote_address = "2.2.2.2"; + $remote_address = "2.2.2.2"; $x_forwarded_for_header = "1.1.1.1"; - $address = Koha::Middleware::RealIP::get_real_ip( $remote_address, $x_forwarded_for_header ); - is($address,'2.2.2.2',"No trusted proxies available, so don't trust 2.2.2.2 as a proxy, instead use it as the remote address"); + $address = Koha::Middleware::RealIP::get_real_ip( $remote_address, $x_forwarded_for_header ); + is( + $address, '2.2.2.2', + "No trusted proxies available, so don't trust 2.2.2.2 as a proxy, instead use it as the remote address" + ); }; subtest "Bad configuration" => sub { plan tests => 4; - $remote_address = "1.1.1.1"; + $remote_address = "1.1.1.1"; $x_forwarded_for_header = "2.2.2.2,3.3.3.3"; - t::lib::Mocks::mock_config('koha_trusted_proxies', 'bad configuration'); + t::lib::Mocks::mock_config( 'koha_trusted_proxies', 'bad configuration' ); warnings_are { $address = Koha::Middleware::RealIP::get_real_ip( $remote_address, $x_forwarded_for_header ); - } ["could not parse bad","could not parse configuration"],"Warn on misconfigured koha_trusted_proxies"; - is($address,'1.1.1.1',"koha_trusted_proxies is misconfigured so ignore the X-Forwarded-For header"); + } + [ "could not parse bad", "could not parse configuration" ], "Warn on misconfigured koha_trusted_proxies"; + is( $address, '1.1.1.1', "koha_trusted_proxies is misconfigured so ignore the X-Forwarded-For header" ); - $remote_address = "1.1.1.1"; + $remote_address = "1.1.1.1"; $x_forwarded_for_header = "2.2.2.2"; - t::lib::Mocks::mock_config('koha_trusted_proxies', 'bad 1.1.1.1'); + t::lib::Mocks::mock_config( 'koha_trusted_proxies', 'bad 1.1.1.1' ); warning_is { $address = Koha::Middleware::RealIP::get_real_ip( $remote_address, $x_forwarded_for_header ); - } "could not parse bad","Warn on partially misconfigured koha_trusted_proxies"; - is($address,'2.2.2.2',"koha_trusted_proxies contains an invalid value but still includes one correct value, which is relevant, so use X-Forwarded-For header"); + } + "could not parse bad", "Warn on partially misconfigured koha_trusted_proxies"; + is( + $address, '2.2.2.2', + "koha_trusted_proxies contains an invalid value but still includes one correct value, which is relevant, so use X-Forwarded-For header" + ); }; subtest "Fail proxy isn't trusted" => sub { plan tests => 1; - $remote_address = "2.2.2.2"; + $remote_address = "2.2.2.2"; $x_forwarded_for_header = "1.1.1.1"; - t::lib::Mocks::mock_config('koha_trusted_proxies', '3.3.3.3'); + t::lib::Mocks::mock_config( 'koha_trusted_proxies', '3.3.3.3' ); $address = Koha::Middleware::RealIP::get_real_ip( $remote_address, $x_forwarded_for_header ); - is($address,'2.2.2.2',"The 2.2.2.2 proxy isn't in our trusted list, so use it as the remote address"); + is( $address, '2.2.2.2', "The 2.2.2.2 proxy isn't in our trusted list, so use it as the remote address" ); }; subtest "The most recent proxy is trusted but the proxy before it is not trusted" => sub { plan tests => 1; - $remote_address = "3.3.3.3"; + $remote_address = "3.3.3.3"; $x_forwarded_for_header = "1.1.1.1, 2.2.2.2"; - t::lib::Mocks::mock_config('koha_trusted_proxies', '3.3.3.3'); + t::lib::Mocks::mock_config( 'koha_trusted_proxies', '3.3.3.3' ); $address = Koha::Middleware::RealIP::get_real_ip( $remote_address, $x_forwarded_for_header ); - is($address,'2.2.2.2',"We trust 3.3.3.3, but we don't trust 2.2.2.2, so use 2.2.2.2 as the remote address"); + is( $address, '2.2.2.2', "We trust 3.3.3.3, but we don't trust 2.2.2.2, so use 2.2.2.2 as the remote address" ); }; subtest "Success one proxy" => sub { plan tests => 1; - $remote_address = "2.2.2.2"; + $remote_address = "2.2.2.2"; $x_forwarded_for_header = "1.1.1.1"; - t::lib::Mocks::mock_config('koha_trusted_proxies', '2.2.2.2'); + t::lib::Mocks::mock_config( 'koha_trusted_proxies', '2.2.2.2' ); $address = Koha::Middleware::RealIP::get_real_ip( $remote_address, $x_forwarded_for_header ); - is($address,'1.1.1.1',"Trust proxy (2.2.2.2), so use the client IP from the X-Forwarded-For header for the remote address"); + is( + $address, '1.1.1.1', + "Trust proxy (2.2.2.2), so use the client IP from the X-Forwarded-For header for the remote address" + ); }; subtest "Success multiple proxies" => sub { plan tests => 1; - $remote_address = "2.2.2.2"; + $remote_address = "2.2.2.2"; $x_forwarded_for_header = "1.1.1.1,3.3.3.3"; - t::lib::Mocks::mock_config('koha_trusted_proxies', '2.2.2.2 3.3.3.3'); + t::lib::Mocks::mock_config( 'koha_trusted_proxies', '2.2.2.2 3.3.3.3' ); $address = Koha::Middleware::RealIP::get_real_ip( $remote_address, $x_forwarded_for_header ); - is($address,'1.1.1.1',"Trust multiple proxies (2.2.2.2 and 3.3.3.3), so use the X-Forwaded-For portion for the remote address"); + is( + $address, '1.1.1.1', + "Trust multiple proxies (2.2.2.2 and 3.3.3.3), so use the X-Forwaded-For portion for the remote address" + ); }; subtest "Test alternative configuration styles" => sub { plan tests => 2; - $remote_address = "2.2.2.2"; + $remote_address = "2.2.2.2"; $x_forwarded_for_header = "1.1.1.1"; - t::lib::Mocks::mock_config('koha_trusted_proxies', '2.2.2.0/24'); + t::lib::Mocks::mock_config( 'koha_trusted_proxies', '2.2.2.0/24' ); $address = Koha::Middleware::RealIP::get_real_ip( $remote_address, $x_forwarded_for_header ); - is($address,'1.1.1.1',"Trust proxy (2.2.2.2) using CIDR notation, so use the X-Forwarded-For header for the remote address"); + is( + $address, '1.1.1.1', + "Trust proxy (2.2.2.2) using CIDR notation, so use the X-Forwarded-For header for the remote address" + ); - $remote_address = "2.2.2.2"; + $remote_address = "2.2.2.2"; $x_forwarded_for_header = "1.1.1.1"; - t::lib::Mocks::mock_config('koha_trusted_proxies', '2.2.2.0:255.255.255.0'); + t::lib::Mocks::mock_config( 'koha_trusted_proxies', '2.2.2.0:255.255.255.0' ); $address = Koha::Middleware::RealIP::get_real_ip( $remote_address, $x_forwarded_for_header ); - is($address,'1.1.1.1',"Trust proxy (2.2.2.2) using an IP address and netmask separated by a colon, so use the X-Forwarded-For header for the remote address"); + is( + $address, '1.1.1.1', + "Trust proxy (2.2.2.2) using an IP address and netmask separated by a colon, so use the X-Forwarded-For header for the remote address" + ); }; subtest "Client IP is properly processed even if it is in koha_trusted_proxies" => sub { - $remote_address = "1.1.1.2"; + $remote_address = "1.1.1.2"; $x_forwarded_for_header = "1.1.1.1"; - t::lib::Mocks::mock_config('koha_trusted_proxies', '1.1.1.0/24'); + t::lib::Mocks::mock_config( 'koha_trusted_proxies', '1.1.1.0/24' ); $address = Koha::Middleware::RealIP::get_real_ip( $remote_address, $x_forwarded_for_header ); - is($address,'1.1.1.1',"The X-Forwarded-For value matches the koha_trusted_proxies, but there is no proxy specified"); + is( + $address, '1.1.1.1', + "The X-Forwarded-For value matches the koha_trusted_proxies, but there is no proxy specified" + ); done_testing(1); }; subtest "IPv6 support" => sub { - my ($remote_address,$x_forwarded_for_header,$address); + my ( $remote_address, $x_forwarded_for_header, $address ); require Net::Netmask; - if (Net::Netmask->VERSION < 1.9104){ + if ( Net::Netmask->VERSION < 1.9104 ) { $remote_address = "2001:db8:1234:5678:abcd:1234:abcd:1234"; $x_forwarded_for_header = "2.2.2.2"; t::lib::Mocks::mock_config( 'koha_trusted_proxies', '2001:db8:1234:5678::/64' ); warning_is { - $address = Koha::Middleware::RealIP::get_real_ip( $remote_address, - $x_forwarded_for_header ); + $address = Koha::Middleware::RealIP::get_real_ip( + $remote_address, + $x_forwarded_for_header + ); } "could not parse 2001:db8:1234:5678::/64", - "Warn on IPv6 koha_trusted_proxies"; + "Warn on IPv6 koha_trusted_proxies"; is( $address, '2001:db8:1234:5678:abcd:1234:abcd:1234', @@ -148,8 +173,11 @@ subtest "IPv6 support" => sub { $x_forwarded_for_header = "2.2.2.2"; t::lib::Mocks::mock_config( 'koha_trusted_proxies', '2001:db8:1234:5678::/64' ); - $address = Koha::Middleware::RealIP::get_real_ip( $remote_address,$x_forwarded_for_header ); - is($address,'2.2.2.2',"Trust proxy (2001:db8:1234:5678:abcd:1234:abcd:1234) using IPv6 CIDR notation, so use the X-Forwarded-For header for the remote address"); + $address = Koha::Middleware::RealIP::get_real_ip( $remote_address, $x_forwarded_for_header ); + is( + $address, '2.2.2.2', + "Trust proxy (2001:db8:1234:5678:abcd:1234:abcd:1234) using IPv6 CIDR notation, so use the X-Forwarded-For header for the remote address" + ); done_testing(1); } }; diff --git a/t/Koha/Object/Message.t b/t/Koha/Object/Message.t index 5a513753b2..82c68dd335 100755 --- a/t/Koha/Object/Message.t +++ b/t/Koha/Object/Message.t @@ -32,24 +32,23 @@ subtest 'new() tests' => sub { my $some_error = 'Some error'; - my $message = Koha::Object::Message->new({ message => $some_error }); - is( ref($message), 'Koha::Object::Message', 'Type is correct' ); - is( $message->message, $some_error, 'The message attribute has the right value' ); - is( $message->type, 'error', 'If omitted, the type is error' ); + my $message = Koha::Object::Message->new( { message => $some_error } ); + is( ref($message), 'Koha::Object::Message', 'Type is correct' ); + is( $message->message, $some_error, 'The message attribute has the right value' ); + is( $message->type, 'error', 'If omitted, the type is error' ); - $message = Koha::Object::Message->new({ message => $some_error, type => 'callback' }); - is( ref($message), 'Koha::Object::Message', 'Type is correct' ); - is( $message->message, $some_error, 'The message attribute has the right value' ); - is( $message->type, 'callback', 'type is correct' ); + $message = Koha::Object::Message->new( { message => $some_error, type => 'callback' } ); + is( ref($message), 'Koha::Object::Message', 'Type is correct' ); + is( $message->message, $some_error, 'The message attribute has the right value' ); + is( $message->type, 'callback', 'type is correct' ); - $message = Koha::Object::Message->new({ message => $some_error, payload => { some => 'structure' } }); - is( ref($message), 'Koha::Object::Message', 'Type is correct' ); - is( $message->message, $some_error, 'The message attribute has the right value' ); + $message = Koha::Object::Message->new( { message => $some_error, payload => { some => 'structure' } } ); + is( ref($message), 'Koha::Object::Message', 'Type is correct' ); + is( $message->message, $some_error, 'The message attribute has the right value' ); is_deeply( $message->payload, { some => 'structure' }, 'payload is correct' ); - throws_ok - { Koha::Object::Message->new({ blah => 'ohh' }); } - 'Koha::Exceptions::MissingParameter', + throws_ok { Koha::Object::Message->new( { blah => 'ohh' } ); } + 'Koha::Exceptions::MissingParameter', 'Exception thrown if required parameter missing'; like( "$@", qr/Mandatory parameter missing: 'message'/, 'Expected exception message' ); diff --git a/t/Koha/Plugins/Tab.t b/t/Koha/Plugins/Tab.t index 7502967499..bbb27b7bd9 100755 --- a/t/Koha/Plugins/Tab.t +++ b/t/Koha/Plugins/Tab.t @@ -27,7 +27,7 @@ subtest 'new() tests' => sub { throws_ok { Koha::Plugins::Tab->new( { title => 'A title' } ); } 'Koha::Exceptions::MissingParameter', - 'Exception is thrown on missing content'; + 'Exception is thrown on missing content'; like( "$@", @@ -37,7 +37,7 @@ subtest 'new() tests' => sub { throws_ok { Koha::Plugins::Tab->new( { content => 'Some content' } ); } 'Koha::Exceptions::MissingParameter', - 'Exception is thrown on missing title'; + 'Exception is thrown on missing title'; like( "$@", @@ -52,7 +52,7 @@ subtest 'new() tests' => sub { } ); - is( $tab->title, 'A title', 'title accessor is correct' ); + is( $tab->title, 'A title', 'title accessor is correct' ); is( $tab->content, 'Some content', 'content accessor is correct' ); my $id = 'calculated-id'; diff --git a/t/Koha/REST/Plugin/Query.t b/t/Koha/REST/Plugin/Query.t index ac5a803a9b..52e71362c5 100755 --- a/t/Koha/REST/Plugin/Query.t +++ b/t/Koha/REST/Plugin/Query.t @@ -36,8 +36,8 @@ get '/empty' => sub { }; get '/query' => sub { - my $c = shift; - my ( $filtered_params, $reserved_params ) = $c->extract_reserved_params($c->req->params->to_hash); + my $c = shift; + my ( $filtered_params, $reserved_params ) = $c->extract_reserved_params( $c->req->params->to_hash ); $c->render( json => { filtered_params => $filtered_params, @@ -48,23 +48,23 @@ get '/query' => sub { }; get '/query_full/:id/:subid' => sub { - my $c = shift; + my $c = shift; my $params = $c->req->params->to_hash; - $params->{id} = $c->stash->{id}; + $params->{id} = $c->stash->{id}; $params->{subid} = $c->stash->{subid}; my ( $filtered_params, $reserved_params, $path_params ) = $c->extract_reserved_params($params); $c->render( json => { filtered_params => $filtered_params, reserved_params => $reserved_params, - path_params => $path_params + path_params => $path_params }, status => 200 ); }; get '/dbic_merge_sorting' => sub { - my $c = shift; + my $c = shift; my $attributes = { a => 'a', b => 'b' }; $attributes = $c->dbic_merge_sorting( { @@ -76,7 +76,7 @@ get '/dbic_merge_sorting' => sub { }; get '/dbic_merge_sorting_single' => sub { - my $c = shift; + my $c = shift; my $attributes = { a => 'a', b => 'b' }; $attributes = $c->dbic_merge_sorting( { @@ -88,7 +88,7 @@ get '/dbic_merge_sorting_single' => sub { }; get '/dbic_merge_sorting_result_set' => sub { - my $c = shift; + my $c = shift; my $attributes = { a => 'a', b => 'b' }; my $result_set = Koha::Cities->new; $attributes = $c->dbic_merge_sorting( @@ -102,13 +102,13 @@ get '/dbic_merge_sorting_result_set' => sub { }; get '/dbic_merge_sorting_date' => sub { - my $c = shift; + my $c = shift; my $attributes = { a => 'a', b => 'b' }; my $result_set = Koha::Holds->new; $attributes = $c->dbic_merge_sorting( { attributes => $attributes, - params => { _match => 'exact', _order_by => [ '-hold_date' ] }, + params => { _match => 'exact', _order_by => ['-hold_date'] }, result_set => $result_set } ); @@ -116,91 +116,89 @@ get '/dbic_merge_sorting_date' => sub { }; get '/dbic_merge_prefetch' => sub { - my $c = shift; + my $c = shift; my $attributes = {}; my $result_set = Koha::Holds->new; - $c->stash('koha.embed', { - "item" => {}, - "biblio" => { - children => { - "orders" => {} - } - } - }); + $c->stash( + 'koha.embed', + { + "item" => {}, + "biblio" => { children => { "orders" => {} } } + } + ); - $c->dbic_merge_prefetch({ - attributes => $attributes, - result_set => $result_set - }); + $c->dbic_merge_prefetch( + { + attributes => $attributes, + result_set => $result_set + } + ); $c->render( json => $attributes, status => 200 ); }; get '/dbic_merge_prefetch_recursive' => sub { - my $c = shift; + my $c = shift; my $attributes = {}; my $result_set = Koha::Patron::Relationship->new; - $c->stash('koha.embed', { - "guarantee" => { - "children" => { - "article_requests" => {}, - "housebound_profile" => { - "children" => { - "housebound_visits" => {} + $c->stash( + 'koha.embed', + { + "guarantee" => { + "children" => { + "article_requests" => {}, + "housebound_profile" => { "children" => { "housebound_visits" => {} } }, + "housebound_role" => {} + } } - }, - "housebound_role" => {} } - } - }); + ); - $c->dbic_merge_prefetch({ - attributes => $attributes, - result_set => $result_set - }); + $c->dbic_merge_prefetch( + { + attributes => $attributes, + result_set => $result_set + } + ); $c->render( json => $attributes, status => 200 ); }; get '/dbic_merge_prefetch_count' => sub { - my $c = shift; + my $c = shift; my $attributes = {}; my $result_set = Koha::Patron::Relationship->new; - $c->stash('koha.embed', { - "guarantee_count" => { - "is_count" => 1 - } - }); + $c->stash( 'koha.embed', { "guarantee_count" => { "is_count" => 1 } } ); - $c->dbic_merge_prefetch({ - attributes => $attributes, - result_set => $result_set - }); + $c->dbic_merge_prefetch( + { + attributes => $attributes, + result_set => $result_set + } + ); $c->render( json => $attributes, status => 200 ); }; get '/merge_q_params' => sub { - my $c = shift; - my $filtered_params = {'biblio_id' => 1}; - my $result_set = Koha::Biblios->new; - $filtered_params = $c->merge_q_params($filtered_params, $c->req->json->{q}, $result_set); + my $c = shift; + my $filtered_params = { 'biblio_id' => 1 }; + my $result_set = Koha::Biblios->new; + $filtered_params = $c->merge_q_params( $filtered_params, $c->req->json->{q}, $result_set ); - $c->render( json => $filtered_params, status => 200 ); + $c->render( json => $filtered_params, status => 200 ); }; get '/build_query' => sub { my $c = shift; - my ( $filtered_params, $reserved_params ) = - $c->extract_reserved_params( $c->req->params->to_hash ); + my ( $filtered_params, $reserved_params ) = $c->extract_reserved_params( $c->req->params->to_hash ); my $query; try { $query = $c->build_query_params( $filtered_params, $reserved_params ); $c->render( json => { query => $query }, status => 200 ); - } - catch { + } catch { $c->render( - json => { exception_msg => $_->message, exception_type => ref($_) }, + json => { exception_msg => $_->message, exception_type => ref($_) }, status => 400 ); }; @@ -252,8 +250,7 @@ get '/stash_embed' => sub { embed => $embed } ); - } - catch { + } catch { $c->render( status => 400, json => { error => "$_" } @@ -277,8 +274,7 @@ get '/stash_embed_no_spec' => sub { embed => $embed } ); - } - catch { + } catch { $c->render( status => 400, json => { error => "$_" } @@ -383,28 +379,29 @@ subtest 'extract_reserved_params() tests' => sub { my $t = Test::Mojo->new; $t->get_ok('/query?_page=2&_per_page=3&firstname=Manuel&surname=Cohen%20Arazi')->status_is(200) - ->json_is( '/filtered_params' => - { firstname => 'Manuel', surname => 'Cohen Arazi' } ) - ->json_is( '/reserved_params' => { _page => 2, _per_page => 3 } ); + ->json_is( '/filtered_params' => { firstname => 'Manuel', surname => 'Cohen Arazi' } ) + ->json_is( '/reserved_params' => { _page => 2, _per_page => 3 } ); - $t->get_ok('/query_full/with/path?_match=exact&_order_by=blah&_page=2&_per_page=3&firstname=Manuel&surname=Cohen%20Arazi')->status_is(200) - ->json_is( + $t->get_ok( + '/query_full/with/path?_match=exact&_order_by=blah&_page=2&_per_page=3&firstname=Manuel&surname=Cohen%20Arazi') + ->status_is(200)->json_is( '/filtered_params' => { firstname => 'Manuel', surname => 'Cohen Arazi' - } ) - ->json_is( + } + )->json_is( '/reserved_params' => { _page => 2, _per_page => 3, _match => 'exact', _order_by => 'blah' - } ) - ->json_is( + } + )->json_is( '/path_params' => { - id => 'with', + id => 'with', subid => 'path' - } ); + } + ); }; @@ -414,43 +411,33 @@ subtest 'dbic_merge_sorting() tests' => sub { my $t = Test::Mojo->new; - $t->get_ok('/dbic_merge_sorting')->status_is(200) - ->json_is( '/a' => 'a', 'Existing values are kept (a)' ) - ->json_is( '/b' => 'b', 'Existing values are kept (b)' )->json_is( + $t->get_ok('/dbic_merge_sorting')->status_is(200)->json_is( '/a' => 'a', 'Existing values are kept (a)' ) + ->json_is( '/b' => 'b', 'Existing values are kept (b)' )->json_is( '/order_by' => [ 'uno', { -desc => 'dos' }, { -asc => 'tres' }, { -asc => 'cuatro' } ] - ); + ); $t->get_ok('/dbic_merge_sorting_result_set')->status_is(200) - ->json_is( '/a' => 'a', 'Existing values are kept (a)' ) - ->json_is( '/b' => 'b', 'Existing values are kept (b)' )->json_is( + ->json_is( '/a' => 'a', 'Existing values are kept (a)' ) + ->json_is( '/b' => 'b', 'Existing values are kept (b)' )->json_is( '/order_by' => [ 'city_name', { -desc => 'city_zipcode' }, { -asc => 'city_country' }, { -asc => 'city_state' } ] - ); + ); - $t->get_ok('/dbic_merge_sorting_date')->status_is(200) - ->json_is( '/a' => 'a', 'Existing values are kept (a)' ) - ->json_is( '/b' => 'b', 'Existing values are kept (b)' )->json_is( - '/order_by' => [ - { -desc => 'reservedate' } - ] - ); + $t->get_ok('/dbic_merge_sorting_date')->status_is(200)->json_is( '/a' => 'a', 'Existing values are kept (a)' ) + ->json_is( '/b' => 'b', 'Existing values are kept (b)' ) + ->json_is( '/order_by' => [ { -desc => 'reservedate' } ] ); - $t->get_ok('/dbic_merge_sorting_single')->status_is(200) - ->json_is( '/a' => 'a', 'Existing values are kept (a)' ) - ->json_is( '/b' => 'b', 'Existing values are kept (b)' )->json_is( - '/order_by' => [ - { '-desc' => 'uno' } - ] - ); + $t->get_ok('/dbic_merge_sorting_single')->status_is(200)->json_is( '/a' => 'a', 'Existing values are kept (a)' ) + ->json_is( '/b' => 'b', 'Existing values are kept (b)' )->json_is( '/order_by' => [ { '-desc' => 'uno' } ] ); }; subtest '/dbic_merge_prefetch' => sub { @@ -458,70 +445,58 @@ subtest '/dbic_merge_prefetch' => sub { my $t = Test::Mojo->new; - $t->get_ok('/dbic_merge_prefetch')->status_is(200) - ->json_is( '/prefetch/0' => { 'biblio' => 'orders' } ) - ->json_is( '/prefetch/1' => 'item' ); + $t->get_ok('/dbic_merge_prefetch')->status_is(200)->json_is( '/prefetch/0' => { 'biblio' => 'orders' } ) + ->json_is( '/prefetch/1' => 'item' ); - $t->get_ok('/dbic_merge_prefetch_recursive')->status_is(200) - ->json_is('/prefetch/0' => { - guarantee => [ - 'article_requests', - {housebound_profile => 'housebound_visits'}, - 'housebound_role' - ] - }); + $t->get_ok('/dbic_merge_prefetch_recursive')->status_is(200)->json_is( + '/prefetch/0' => { + guarantee => [ + 'article_requests', + { housebound_profile => 'housebound_visits' }, + 'housebound_role' + ] + } + ); - $t->get_ok('/dbic_merge_prefetch_count')->status_is(200) - ->json_is('/prefetch/0' => 'guarantee'); + $t->get_ok('/dbic_merge_prefetch_count')->status_is(200)->json_is( '/prefetch/0' => 'guarantee' ); }; subtest '/merge_q_params' => sub { - plan tests => 3; - my $t = Test::Mojo->new; + plan tests => 3; + my $t = Test::Mojo->new; - $t->get_ok('/merge_q_params' => json => { - q => { - "-not_bool" => "suggestions.suggester.patron_card_lost", - "-or" => [ - { - "creation_date" => { - "!=" => ["fff", "zzz", "xxx"] - } - }, - { "suggestions.suggester.housebound_profile.frequency" => "123" }, - { - "suggestions.suggester.library_id" => {"like" => "%CPL%"} - } - ] - } - })->status_is(200) - ->json_is( '/-and' => [ - { - "-not_bool" => "suggester.lost", - "-or" => [ - { - "datecreated" => { - "!=" => [ - "fff", - "zzz", - "xxx" + $t->get_ok( + '/merge_q_params' => json => { + q => { + "-not_bool" => "suggestions.suggester.patron_card_lost", + "-or" => [ + { "creation_date" => { "!=" => [ "fff", "zzz", "xxx" ] } }, + { "suggestions.suggester.housebound_profile.frequency" => "123" }, + { "suggestions.suggester.library_id" => { "like" => "%CPL%" } } ] - } - }, - { - "housebound_profile.frequency" => 123 - }, - { - "suggester.branchcode" => { - "like" => "\%CPL\%" - } } - ] - }, - { - "biblio_id" => 1 } - ]); + )->status_is(200)->json_is( + '/-and' => [ + { + "-not_bool" => "suggester.lost", + "-or" => [ + { + "datecreated" => { + "!=" => [ + "fff", + "zzz", + "xxx" + ] + } + }, + { "housebound_profile.frequency" => 123 }, + { "suggester.branchcode" => { "like" => "\%CPL\%" } } + ] + }, + { "biblio_id" => 1 } + ] + ); }; subtest '_build_query_params_from_api' => sub { @@ -531,33 +506,25 @@ subtest '_build_query_params_from_api' => sub { my $t = Test::Mojo->new; # _match => contains - $t->get_ok('/build_query?_match=contains&title=Ender&author=Orson') - ->status_is(200) - ->json_is( '/query' => - { author => { like => '%Orson%' }, title => { like => '%Ender%' } } ); + $t->get_ok('/build_query?_match=contains&title=Ender&author=Orson')->status_is(200) + ->json_is( '/query' => { author => { like => '%Orson%' }, title => { like => '%Ender%' } } ); # _match => starts_with - $t->get_ok('/build_query?_match=starts_with&title=Ender&author=Orson') - ->status_is(200) - ->json_is( '/query' => - { author => { like => 'Orson%' }, title => { like => 'Ender%' } } ); + $t->get_ok('/build_query?_match=starts_with&title=Ender&author=Orson')->status_is(200) + ->json_is( '/query' => { author => { like => 'Orson%' }, title => { like => 'Ender%' } } ); # _match => ends_with - $t->get_ok('/build_query?_match=ends_with&title=Ender&author=Orson') - ->status_is(200) - ->json_is( '/query' => - { author => { like => '%Orson' }, title => { like => '%Ender' } } ); + $t->get_ok('/build_query?_match=ends_with&title=Ender&author=Orson')->status_is(200) + ->json_is( '/query' => { author => { like => '%Orson' }, title => { like => '%Ender' } } ); # _match => exact - $t->get_ok('/build_query?_match=exact&title=Ender&author=Orson') - ->status_is(200) - ->json_is( '/query' => { author => 'Orson', title => 'Ender' } ); + $t->get_ok('/build_query?_match=exact&title=Ender&author=Orson')->status_is(200) + ->json_is( '/query' => { author => 'Orson', title => 'Ender' } ); # _match => blah - $t->get_ok('/build_query?_match=blah&title=Ender&author=Orson') - ->status_is(400) - ->json_is( '/exception_msg' => 'Invalid value for _match param (blah)' ) - ->json_is( '/exception_type' => 'Koha::Exceptions::WrongParameter' ); + $t->get_ok('/build_query?_match=blah&title=Ender&author=Orson')->status_is(400) + ->json_is( '/exception_msg' => 'Invalid value for _match param (blah)' ) + ->json_is( '/exception_type' => 'Koha::Exceptions::WrongParameter' ); }; @@ -568,42 +535,42 @@ subtest 'stash_embed() tests' => sub { my $t = Test::Mojo->new; $t->get_ok( '/stash_embed' => { 'x-koha-embed' => 'checkouts,checkouts.item' } ) - ->json_is( '/embed' => { checkouts => { children => { item => { } } } } ); + ->json_is( '/embed' => { checkouts => { children => { item => {} } } } ); $t->get_ok( '/stash_embed' => { 'x-koha-embed' => 'checkouts,checkouts.item,library' } ) - ->json_is( '/embed' => { checkouts => { children => { item => {} } }, library => {} } ); + ->json_is( '/embed' => { checkouts => { children => { item => {} } }, library => {} } ); $t->get_ok( '/stash_embed' => { 'x-koha-embed' => 'holds+count' } ) - ->json_is( '/embed' => { holds_count => { is_count => 1 } } ); + ->json_is( '/embed' => { holds_count => { is_count => 1 } } ); $t->get_ok( '/stash_embed' => { 'x-koha-embed' => 'holds:count' } ) - ->json_is( '/embed' => { holds_count => { is_count => 1 } } ); + ->json_is( '/embed' => { holds_count => { is_count => 1 } } ); - $t->get_ok( '/stash_embed' => { 'x-koha-embed' => 'checkouts,checkouts.item,patron' } ) - ->json_is( '/embed' => { + $t->get_ok( '/stash_embed' => { 'x-koha-embed' => 'checkouts,checkouts.item,patron' } )->json_is( + '/embed' => { checkouts => { children => { item => {} } }, patron => {} - }); + } + ); - $t->get_ok( '/stash_embed' => { 'x-koha-embed' => 'checkouts,checkouts.item+strings,patron+strings' } ) - ->json_is( '/embed' => { + $t->get_ok( '/stash_embed' => { 'x-koha-embed' => 'checkouts,checkouts.item+strings,patron+strings' } )->json_is( + '/embed' => { checkouts => { children => { item => { strings => 1 } } }, - patron => { strings => 1 } - }) - ->json_is( '/strings' => undef ); + patron => { strings => 1 } + } + )->json_is( '/strings' => undef ); - $t->get_ok( '/stash_embed' => { 'x-koha-embed' => 'checkouts+strings,checkouts.item,patron,+strings' } ) - ->json_is( '/embed' => { - checkouts => { children => { item => { } }, strings => 1 }, - patron => { } - }) - ->json_is( '/strings' => 1 ); + $t->get_ok( '/stash_embed' => { 'x-koha-embed' => 'checkouts+strings,checkouts.item,patron,+strings' } )->json_is( + '/embed' => { + checkouts => { children => { item => {} }, strings => 1 }, + patron => {} + } + )->json_is( '/strings' => 1 ); - $t->get_ok( '/stash_embed_no_spec' => { 'x-koha-embed' => 'checkouts,checkouts.item,patron' } ) - ->status_is(400) - ->json_is( '/error' => - qq{Exception 'Koha::Exceptions::BadParameter' thrown 'Embedding objects is not allowed on this endpoint.'\n} - ); + $t->get_ok( '/stash_embed_no_spec' => { 'x-koha-embed' => 'checkouts,checkouts.item,patron' } )->status_is(400) + ->json_is( '/error' => + qq{Exception 'Koha::Exceptions::BadParameter' thrown 'Embedding objects is not allowed on this endpoint.'\n} + ); }; subtest 'stash_overrides() tests' => sub { @@ -613,13 +580,11 @@ subtest 'stash_overrides() tests' => sub { my $t = Test::Mojo->new; $t->get_ok( '/stash_overrides' => { 'x-koha-override' => 'any,none,some_other,any,' } ) - ->json_is( { 'any' => 1, 'none' => 1, 'some_other' => 1 } ); # empty string and duplicates are skipped + ->json_is( { 'any' => 1, 'none' => 1, 'some_other' => 1 } ); # empty string and duplicates are skipped - $t->get_ok( '/stash_overrides' => { 'x-koha-override' => '' } ) - ->json_is( {} ); # empty string is skipped + $t->get_ok( '/stash_overrides' => { 'x-koha-override' => '' } )->json_is( {} ); # empty string is skipped - $t->get_ok( '/stash_overrides' => { } ) - ->json_is( {} ); # x-koha-ovverride not passed is skipped + $t->get_ok( '/stash_overrides' => {} )->json_is( {} ); # x-koha-ovverride not passed is skipped }; diff --git a/t/Koha/Result/Boolean.t b/t/Koha/Result/Boolean.t index 8a1a9c9429..96edfe2542 100755 --- a/t/Koha/Result/Boolean.t +++ b/t/Koha/Result/Boolean.t @@ -29,28 +29,44 @@ subtest 'new() tests' => sub { plan tests => 4; - ok( Koha::Result::Boolean->new, - 'Defaults to true if initialized without the parameter' ); - ok( Koha::Result::Boolean->new('Martin'), - 'Evals to true in boolean context if set an expression that evals to true' ); - ok( !Koha::Result::Boolean->new(0), - 'Evals to false in boolean context if set a false expression' ); - ok( !Koha::Result::Boolean->new(""), - 'Evals to false in boolean context if set a false expression' ); + ok( + Koha::Result::Boolean->new, + 'Defaults to true if initialized without the parameter' + ); + ok( + Koha::Result::Boolean->new('Martin'), + 'Evals to true in boolean context if set an expression that evals to true' + ); + ok( + !Koha::Result::Boolean->new(0), + 'Evals to false in boolean context if set a false expression' + ); + ok( + !Koha::Result::Boolean->new(""), + 'Evals to false in boolean context if set a false expression' + ); }; subtest '== context' => sub { plan tests => 4; - cmp_ok( Koha::Result::Boolean->new, '==', 1, - 'Defaults 1 if initialized without the parameter' ); - cmp_ok( Koha::Result::Boolean->new('Martin'), '==', 1, - 'Evals 1 if set an expression that evals to true' ); - cmp_ok( Koha::Result::Boolean->new(0), '==', 0, - 'Evals 0 if set a false expression' ); - cmp_ok( Koha::Result::Boolean->new(""), '==', 0, - 'Evals 0 if set a false expression' ); + cmp_ok( + Koha::Result::Boolean->new, '==', 1, + 'Defaults 1 if initialized without the parameter' + ); + cmp_ok( + Koha::Result::Boolean->new('Martin'), '==', 1, + 'Evals 1 if set an expression that evals to true' + ); + cmp_ok( + Koha::Result::Boolean->new(0), '==', 0, + 'Evals 0 if set a false expression' + ); + cmp_ok( + Koha::Result::Boolean->new(""), '==', 0, + 'Evals 0 if set a false expression' + ); }; }; @@ -60,14 +76,22 @@ subtest 'set_value() tests' => sub { my $bool = Koha::Result::Boolean->new; - ok( !$bool->set_value(), - 'Undef makes it eval to false' ); - ok( $bool->set_value('Martin'), - 'Evals to true in boolean context if set an expression that evals to true' ); - ok( !$bool->set_value(0), - 'Evals to false in boolean context if set a false expression' ); - ok( !$bool->set_value(""), - 'Evals to false in boolean context if set a false expression' ); + ok( + !$bool->set_value(), + 'Undef makes it eval to false' + ); + ok( + $bool->set_value('Martin'), + 'Evals to true in boolean context if set an expression that evals to true' + ); + ok( + !$bool->set_value(0), + 'Evals to false in boolean context if set a false expression' + ); + ok( + !$bool->set_value(""), + 'Evals to false in boolean context if set a false expression' + ); }; @@ -80,13 +104,13 @@ subtest 'messages() and add_message() tests' => sub { my @messages = @{ $bool->messages }; is( scalar @messages, 0, 'No messages' ); - $bool->add_message({ message => "message_1" }); - $bool->add_message({ message => "message_2" }); + $bool->add_message( { message => "message_1" } ); + $bool->add_message( { message => "message_2" } ); @messages = @{ $bool->messages }; - is( scalar @messages, 2, 'Messages are returned' ); - is( ref($messages[0]), 'Koha::Object::Message', 'Right type returned' ); - is( ref($messages[1]), 'Koha::Object::Message', 'Right type returned' ); - is( $messages[0]->message, 'message_1', 'Right message recorded' ); + is( scalar @messages, 2, 'Messages are returned' ); + is( ref( $messages[0] ), 'Koha::Object::Message', 'Right type returned' ); + is( ref( $messages[1] ), 'Koha::Object::Message', 'Right type returned' ); + is( $messages[0]->message, 'message_1', 'Right message recorded' ); }; diff --git a/t/Koha/Script.t b/t/Koha/Script.t index 527ff24ddd..eb5afe2353 100755 --- a/t/Koha/Script.t +++ b/t/Koha/Script.t @@ -62,7 +62,7 @@ subtest 'lock_exec() tests' => sub { exit; } - sleep 1; # Make sure we start after the fork + sleep 1; # Make sure we start after the fork my $command = dirname(__FILE__) . '/sleep.pl'; my $result = `$command 2>&1`; @@ -74,15 +74,14 @@ subtest 'lock_exec() tests' => sub { exit; } - sleep 1; # Make sure we start after the fork + sleep 1; # Make sure we start after the fork $command = dirname(__FILE__) . '/wait.pl'; $result = `$command 2>&1`; is( $result, 'YAY!', 'wait.pl successfully waits for the lock' ); - throws_ok - { Koha::Script->new({ lock_name => 'blah' }); } - 'Koha::Exceptions::MissingParameter', + throws_ok { Koha::Script->new( { lock_name => 'blah' } ); } + 'Koha::Exceptions::MissingParameter', 'Not passing the "script" parameter makes it raise an exception'; }; diff --git a/t/Koha/SearchEngine/Elasticsearch/QueryBuilder.t b/t/Koha/SearchEngine/Elasticsearch/QueryBuilder.t index b6b670d7d5..f851d9457a 100755 --- a/t/Koha/SearchEngine/Elasticsearch/QueryBuilder.t +++ b/t/Koha/SearchEngine/Elasticsearch/QueryBuilder.t @@ -25,18 +25,19 @@ use_ok('Koha::SearchEngine::Elasticsearch::QueryBuilder'); subtest 'query_regex_escape_options' => sub { plan tests => 12; - t::lib::Mocks::mock_preference('QueryRegexEscapeOptions', 'dont_escape'); + t::lib::Mocks::mock_preference( 'QueryRegexEscapeOptions', 'dont_escape' ); my $query_with_regexp = "query /with regexp/"; - my $processed_query = Koha::SearchEngine::Elasticsearch::QueryBuilder->_query_regex_escape_process($query_with_regexp); + my $processed_query = + Koha::SearchEngine::Elasticsearch::QueryBuilder->_query_regex_escape_process($query_with_regexp); is( $processed_query, $query_with_regexp, "Unescaped query regexp has not been escaped when escaping is disabled" ); - t::lib::Mocks::mock_preference('QueryRegexEscapeOptions', 'escape'); + t::lib::Mocks::mock_preference( 'QueryRegexEscapeOptions', 'escape' ); $processed_query = Koha::SearchEngine::Elasticsearch::QueryBuilder->_query_regex_escape_process($query_with_regexp); is( @@ -46,7 +47,8 @@ subtest 'query_regex_escape_options' => sub { ); my $query_with_escaped_regex = "query \\/with regexp\\/"; - $processed_query = Koha::SearchEngine::Elasticsearch::QueryBuilder->_query_regex_escape_process($query_with_escaped_regex); + $processed_query = + Koha::SearchEngine::Elasticsearch::QueryBuilder->_query_regex_escape_process($query_with_escaped_regex); is( $processed_query, $query_with_escaped_regex, @@ -54,7 +56,8 @@ subtest 'query_regex_escape_options' => sub { ); my $query_with_even_preceding_escapes_regex = "query \\\\/with regexp\\\\/"; - $processed_query = Koha::SearchEngine::Elasticsearch::QueryBuilder->_query_regex_escape_process($query_with_even_preceding_escapes_regex); + $processed_query = Koha::SearchEngine::Elasticsearch::QueryBuilder->_query_regex_escape_process( + $query_with_even_preceding_escapes_regex); is( $processed_query, "query \\\\\\/with regexp\\\\\\/", @@ -62,7 +65,8 @@ subtest 'query_regex_escape_options' => sub { ); my $query_with_odd_preceding_escapes_regex = 'query \\\\\\/with regexp\\\\\\/'; - $processed_query = Koha::SearchEngine::Elasticsearch::QueryBuilder->_query_regex_escape_process($query_with_odd_preceding_escapes_regex); + $processed_query = Koha::SearchEngine::Elasticsearch::QueryBuilder->_query_regex_escape_process( + $query_with_odd_preceding_escapes_regex); is( $processed_query, $query_with_odd_preceding_escapes_regex, @@ -70,14 +74,15 @@ subtest 'query_regex_escape_options' => sub { ); my $query_with_quoted_slash = "query with / and \"/ within quotes\""; - $processed_query = Koha::SearchEngine::Elasticsearch::QueryBuilder->_query_regex_escape_process($query_with_quoted_slash); + $processed_query = + Koha::SearchEngine::Elasticsearch::QueryBuilder->_query_regex_escape_process($query_with_quoted_slash); is( $processed_query, "query with \\/ and \"/ within quotes\"", "Unescaped slash outside of quotes has been escaped while unescaped slash within quotes is left as is when escaping is enabled." ); - t::lib::Mocks::mock_preference('QueryRegexEscapeOptions', 'unescape_escaped'); + t::lib::Mocks::mock_preference( 'QueryRegexEscapeOptions', 'unescape_escaped' ); $processed_query = Koha::SearchEngine::Elasticsearch::QueryBuilder->_query_regex_escape_process($query_with_regexp); is( @@ -86,21 +91,24 @@ subtest 'query_regex_escape_options' => sub { "Unescaped query regexp has been escaped when unescape escaping is enabled" ); - $processed_query = Koha::SearchEngine::Elasticsearch::QueryBuilder->_query_regex_escape_process($query_with_escaped_regex); + $processed_query = + Koha::SearchEngine::Elasticsearch::QueryBuilder->_query_regex_escape_process($query_with_escaped_regex); is( $processed_query, "query /with regexp/", "Escaped query regexp has been unescaped when unescape escaping is enabled" ); - $processed_query = Koha::SearchEngine::Elasticsearch::QueryBuilder->_query_regex_escape_process($query_with_even_preceding_escapes_regex); + $processed_query = Koha::SearchEngine::Elasticsearch::QueryBuilder->_query_regex_escape_process( + $query_with_even_preceding_escapes_regex); is( $processed_query, "query \\\\\\/with regexp\\\\\\/", "Query regexp with even preceding escapes, thus unescaped, has been escaped when unescape escaping is enabled" ); - $processed_query = Koha::SearchEngine::Elasticsearch::QueryBuilder->_query_regex_escape_process($query_with_odd_preceding_escapes_regex); + $processed_query = Koha::SearchEngine::Elasticsearch::QueryBuilder->_query_regex_escape_process( + $query_with_odd_preceding_escapes_regex); is( $processed_query, "query \\\\/with regexp\\\\/", @@ -108,7 +116,8 @@ subtest 'query_regex_escape_options' => sub { ); my $regexp_at_start_of_string_with_odd_preceding_escapes_regex = '\\\\\\/regexp\\\\\\/'; - $processed_query = Koha::SearchEngine::Elasticsearch::QueryBuilder->_query_regex_escape_process($regexp_at_start_of_string_with_odd_preceding_escapes_regex); + $processed_query = Koha::SearchEngine::Elasticsearch::QueryBuilder->_query_regex_escape_process( + $regexp_at_start_of_string_with_odd_preceding_escapes_regex); is( $processed_query, "\\\\/regexp\\\\/", @@ -116,7 +125,8 @@ subtest 'query_regex_escape_options' => sub { ); my $query_with_quoted_escaped_slash = "query with \\/ and \"\\/ within quotes\""; - $processed_query = Koha::SearchEngine::Elasticsearch::QueryBuilder->_query_regex_escape_process($query_with_quoted_escaped_slash); + $processed_query = + Koha::SearchEngine::Elasticsearch::QueryBuilder->_query_regex_escape_process($query_with_quoted_escaped_slash); is( $processed_query, "query with / and \"\\/ within quotes\"", @@ -129,27 +139,29 @@ subtest '_truncate_terms() tests' => sub { my $qb; ok( - $qb = Koha::SearchEngine::Elasticsearch::QueryBuilder->new({ 'index' => $Koha::SearchEngine::Elasticsearch::BIBLIOS_INDEX }), + $qb = Koha::SearchEngine::Elasticsearch::QueryBuilder->new( + { 'index' => $Koha::SearchEngine::Elasticsearch::BIBLIOS_INDEX } + ), 'Creating a new QueryBuilder object' ); my $res = $qb->_truncate_terms('donald'); - is_deeply($res, 'donald*', 'single search term returned correctly'); + is_deeply( $res, 'donald*', 'single search term returned correctly' ); $res = $qb->_truncate_terms('donald duck'); - is_deeply($res, 'donald* duck*', 'two search terms returned correctly'); + is_deeply( $res, 'donald* duck*', 'two search terms returned correctly' ); $res = $qb->_truncate_terms(' donald duck '); - is_deeply($res, 'donald* duck*', 'two search terms surrounded by spaces returned correctly'); + is_deeply( $res, 'donald* duck*', 'two search terms surrounded by spaces returned correctly' ); $res = $qb->_truncate_terms('"donald duck"'); - is_deeply($res, '"donald duck"', 'quoted search term returned correctly'); + is_deeply( $res, '"donald duck"', 'quoted search term returned correctly' ); $res = $qb->_truncate_terms('"donald, duck"'); - is_deeply($res, '"donald, duck"', 'quoted search term with comma returned correctly'); + is_deeply( $res, '"donald, duck"', 'quoted search term with comma returned correctly' ); $res = $qb->_truncate_terms(' "donald duck" '); - is_deeply($res, '"donald duck"', 'quoted search terms surrounded by spaces correctly'); + is_deeply( $res, '"donald duck"', 'quoted search terms surrounded by spaces correctly' ); }; subtest '_is_safe_to_auto_truncate() tests' => sub { @@ -187,33 +199,35 @@ subtest '_split_query() tests' => sub { my $qb; ok( - $qb = Koha::SearchEngine::Elasticsearch::QueryBuilder->new({ 'index' => $Koha::SearchEngine::Elasticsearch::BIBLIOS_INDEX }), + $qb = Koha::SearchEngine::Elasticsearch::QueryBuilder->new( + { 'index' => $Koha::SearchEngine::Elasticsearch::BIBLIOS_INDEX } + ), 'Creating a new QueryBuilder object' ); my @res = $qb->_split_query('donald'); my @exp = 'donald'; - is_deeply(\@res, \@exp, 'single search term returned correctly'); + is_deeply( \@res, \@exp, 'single search term returned correctly' ); @res = $qb->_split_query('donald duck'); - @exp = ('donald', 'duck'); - is_deeply(\@res, \@exp, 'two search terms returned correctly'); + @exp = ( 'donald', 'duck' ); + is_deeply( \@res, \@exp, 'two search terms returned correctly' ); @res = $qb->_split_query(' donald duck '); - @exp = ('donald', 'duck'); - is_deeply(\@res, \@exp, 'two search terms surrounded by spaces returned correctly'); + @exp = ( 'donald', 'duck' ); + is_deeply( \@res, \@exp, 'two search terms surrounded by spaces returned correctly' ); @res = $qb->_split_query('"donald duck"'); - @exp = ( '"donald duck"' ); - is_deeply(\@res, \@exp, 'quoted search term returned correctly'); + @exp = ('"donald duck"'); + is_deeply( \@res, \@exp, 'quoted search term returned correctly' ); @res = $qb->_split_query('"donald, duck"'); - @exp = ( '"donald, duck"' ); - is_deeply(\@res, \@exp, 'quoted search term with comma returned correctly'); + @exp = ('"donald, duck"'); + is_deeply( \@res, \@exp, 'quoted search term with comma returned correctly' ); @res = $qb->_split_query(' "donald duck" '); - @exp = ( '"donald duck"' ); - is_deeply(\@res, \@exp, 'quoted search terms surrounded by spaces correctly'); + @exp = ('"donald duck"'); + is_deeply( \@res, \@exp, 'quoted search terms surrounded by spaces correctly' ); }; subtest 'clean_search_term() tests' => sub { @@ -221,87 +235,100 @@ subtest 'clean_search_term() tests' => sub { my $qb; ok( - $qb = Koha::SearchEngine::Elasticsearch::QueryBuilder->new({ 'index' => $Koha::SearchEngine::Elasticsearch::BIBLIOS_INDEX }), + $qb = Koha::SearchEngine::Elasticsearch::QueryBuilder->new( + { 'index' => $Koha::SearchEngine::Elasticsearch::BIBLIOS_INDEX } + ), 'Creating a new QueryBuilder object' ); - t::lib::Mocks::mock_preference('QueryAutoTruncate', 0); + t::lib::Mocks::mock_preference( 'QueryAutoTruncate', 0 ); my $res = $qb->clean_search_term('an=123'); - is($res, 'koha-auth-number:123', 'equals sign replaced with colon'); + is( $res, 'koha-auth-number:123', 'equals sign replaced with colon' ); $res = $qb->clean_search_term('"balanced quotes"'); - is($res, '"balanced quotes"', 'balanced quotes returned correctly'); + is( $res, '"balanced quotes"', 'balanced quotes returned correctly' ); $res = $qb->clean_search_term('unbalanced quotes"'); - is($res, 'unbalanced quotes ', 'unbalanced quotes removed'); + is( $res, 'unbalanced quotes ', 'unbalanced quotes removed' ); $res = $qb->clean_search_term('"unbalanced "quotes"'); - is($res, ' unbalanced quotes ', 'unbalanced quotes removed'); + is( $res, ' unbalanced quotes ', 'unbalanced quotes removed' ); $res = $qb->clean_search_term(':test query'); - is($res, 'test query', 'remove colon at the start'); + is( $res, 'test query', 'remove colon at the start' ); $res = $qb->clean_search_term('test query\:'); - is($res, 'test query', 'remove colon at the end'); + is( $res, 'test query', 'remove colon at the end' ); $res = $qb->clean_search_term('test : query'); - is($res, 'test query', 'dangling colon removed'); + is( $res, 'test query', 'dangling colon removed' ); $res = $qb->clean_search_term('test :: query'); - is($res, 'test query', 'dangling double colon removed'); + is( $res, 'test query', 'dangling double colon removed' ); $res = $qb->clean_search_term('test "another : query"'); - is($res, 'test "another : query"', 'quoted dangling colon not removed'); + is( $res, 'test "another : query"', 'quoted dangling colon not removed' ); $res = $qb->clean_search_term('host-item:test:n'); - is($res, 'host-item:test\:n', 'screen colons properly'); + is( $res, 'host-item:test\:n', 'screen colons properly' ); $res = $qb->clean_search_term('host-item:test:n:test:and more'); - is($res, 'host-item:test\:n\:test\:and more', 'screen multiple colons properly'); + is( $res, 'host-item:test\:n\:test\:and more', 'screen multiple colons properly' ); $res = $qb->clean_search_term('host-item:te st:n'); - is($res, 'host-item:te st:n', 'leave colons as they are'); + is( $res, 'host-item:te st:n', 'leave colons as they are' ); $res = $qb->clean_search_term('test!'); - is($res, 'test', 'remove exclamation sign at the end of the line'); + is( $res, 'test', 'remove exclamation sign at the end of the line' ); $res = $qb->clean_search_term('test! and more'); - is($res, 'test and more', 'remove exclamation sign at with space after it'); + is( $res, 'test and more', 'remove exclamation sign at with space after it' ); $res = $qb->clean_search_term('test! and more (and more!)'); - is($res, 'test and more (and more)', 'remove exclamation sign followed by close parentheses'); + is( $res, 'test and more (and more)', 'remove exclamation sign followed by close parentheses' ); $res = $qb->clean_search_term('!test'); - is($res, '!test', 'exclamation sign left untouched'); + is( $res, '!test', 'exclamation sign left untouched' ); $res = $qb->clean_search_term('test [123 TO 345]'); - is($res, 'test [123 TO 345]', 'keep inculsive range untouched'); + is( $res, 'test [123 TO 345]', 'keep inculsive range untouched' ); $res = $qb->clean_search_term('test [test TO TEST} [and] {123 TO 456]'); - is($res, 'test [test TO TEST} \[and\] {123 TO 456]', 'keep exclusive range untouched'); + is( $res, 'test [test TO TEST} \[and\] {123 TO 456]', 'keep exclusive range untouched' ); $res = $qb->clean_search_term('test [test TO TEST} ["[and] {123 TO 456]" "[balanced]"]'); - is($res, 'test [test TO TEST} \["[and] {123 TO 456]" "[balanced]"\]', 'keep exclusive range untouched'); + is( $res, 'test [test TO TEST} \["[and] {123 TO 456]" "[balanced]"\]', 'keep exclusive range untouched' ); $res = $qb->clean_search_term('test[]test TO TEST] [ {123 to 345}}'); - is($res, 'test\[\]test TO TEST\] \[ \{123 to 345\}\}', 'screen all square and curly brackets'); + is( $res, 'test\[\]test TO TEST\] \[ \{123 to 345\}\}', 'screen all square and curly brackets' ); - t::lib::Mocks::mock_preference('QueryRegexEscapeOptions', 'escape'); + t::lib::Mocks::mock_preference( 'QueryRegexEscapeOptions', 'escape' ); $res = $qb->clean_search_term('test inside regexps /this [a-z]/ and \/not [a-z]\/ and that [a-z] [a TO z]'); - is($res, 'test inside regexps \/this \[a-z\]\/ and \/not \[a-z\]\/ and that \[a-z\] [a TO z]', 'behaviour with QueryRegexEscapeOptions set to "escape"'); + is( + $res, 'test inside regexps \/this \[a-z\]\/ and \/not \[a-z\]\/ and that \[a-z\] [a TO z]', + 'behaviour with QueryRegexEscapeOptions set to "escape"' + ); - t::lib::Mocks::mock_preference('QueryRegexEscapeOptions', 'dont_escape'); + t::lib::Mocks::mock_preference( 'QueryRegexEscapeOptions', 'dont_escape' ); - $res = $qb->clean_search_term('test inside regexps /this [a-z]/ /this2 [a-z]/ [but] /this3 [a-z]/ and \/not [a-z]\/ and that [a-z] [a TO z]'); - is($res, 'test inside regexps /this [a-z]/ /this2 [a-z]/ \[but\] /this3 [a-z]/ and \/not \[a-z\]\/ and that \[a-z\] [a TO z]', 'behaviour with QueryRegexEscapeOptions set to "dont_escape"'); + $res = $qb->clean_search_term( + 'test inside regexps /this [a-z]/ /this2 [a-z]/ [but] /this3 [a-z]/ and \/not [a-z]\/ and that [a-z] [a TO z]'); + is( + $res, + 'test inside regexps /this [a-z]/ /this2 [a-z]/ \[but\] /this3 [a-z]/ and \/not \[a-z\]\/ and that \[a-z\] [a TO z]', + 'behaviour with QueryRegexEscapeOptions set to "dont_escape"' + ); $res = $qb->clean_search_term('ti:test AND kw:test'); - is($res, 'title:test AND test', 'ti converted to title, kw converted to empty string, dangling colon removed with space preserved'); + is( + $res, 'title:test AND test', + 'ti converted to title, kw converted to empty string, dangling colon removed with space preserved' + ); $res = $qb->clean_search_term('kw:test'); - is($res, 'test', 'kw converted to empty string, dangling colon is removed'); + is( $res, 'test', 'kw converted to empty string, dangling colon is removed' ); }; subtest '_join_queries' => sub { @@ -315,22 +342,25 @@ subtest '_join_queries' => sub { my $query; $query = $qb->_join_queries('foo'); - is($query, 'foo', 'should work with a single param'); + is( $query, 'foo', 'should work with a single param' ); - $query = $qb->_join_queries(undef, '', 'foo', '', undef); - is($query, 'foo', 'should ignore undef or empty queries'); + $query = $qb->_join_queries( undef, '', 'foo', '', undef ); + is( $query, 'foo', 'should ignore undef or empty queries' ); - $query = $qb->_join_queries('foo', 'bar'); - is($query, '(foo) AND (bar)', 'should join queries with an AND'); + $query = $qb->_join_queries( 'foo', 'bar' ); + is( $query, '(foo) AND (bar)', 'should join queries with an AND' ); - $query = $qb->_join_queries('homebranch:foo', 'onloan:false'); - is($query, '(homebranch:foo) AND (onloan:false)', 'should also work when field is specified'); + $query = $qb->_join_queries( 'homebranch:foo', 'onloan:false' ); + is( $query, '(homebranch:foo) AND (onloan:false)', 'should also work when field is specified' ); - $query = $qb->_join_queries('homebranch:foo', 'mc-itype:BOOK', 'mc-itype:EBOOK'); - is($query, '(homebranch:foo) AND itype:(BOOK OR EBOOK)', 'should join with OR when using an "mc-" field'); + $query = $qb->_join_queries( 'homebranch:foo', 'mc-itype:BOOK', 'mc-itype:EBOOK' ); + is( $query, '(homebranch:foo) AND itype:(BOOK OR EBOOK)', 'should join with OR when using an "mc-" field' ); - $query = $qb->_join_queries('homebranch:foo', 'mc-itype:BOOK', 'mc-itype:EBOOK', 'mc-location:SHELF'); - is($query, '(homebranch:foo) AND itype:(BOOK OR EBOOK) AND location:(SHELF)', 'should join "mc-" parts with AND if not the same field'); + $query = $qb->_join_queries( 'homebranch:foo', 'mc-itype:BOOK', 'mc-itype:EBOOK', 'mc-location:SHELF' ); + is( + $query, '(homebranch:foo) AND itype:(BOOK OR EBOOK) AND location:(SHELF)', + 'should join "mc-" parts with AND if not the same field' + ); }; subtest '_create_query_string' => sub { @@ -369,5 +399,4 @@ subtest '_create_query_string' => sub { }; - 1; diff --git a/t/Koha/SearchEngine/Elasticsearch/Search.t b/t/Koha/SearchEngine/Elasticsearch/Search.t index 1ca6bd359e..daf20d628f 100755 --- a/t/Koha/SearchEngine/Elasticsearch/Search.t +++ b/t/Koha/SearchEngine/Elasticsearch/Search.t @@ -29,7 +29,7 @@ subtest 'search_auth_compat' => sub { plan tests => 7; t::lib::Mocks::mock_preference( 'QueryRegexEscapeOptions', 'dont_escape' ); - t::lib::Mocks::mock_preference( 'SearchEngine', 'Elasticsearch' ); + t::lib::Mocks::mock_preference( 'SearchEngine', 'Elasticsearch' ); my $search; ok( @@ -47,8 +47,8 @@ subtest 'search_auth_compat' => sub { ); my $search_query = $builder->build_authorities_query_compat( - ['mainmainentry'], ['and'], [''], ['contains'], - ['Donald - ^ \ ~ + Duck'], '', 'HeadingAsc' + ['mainmainentry'], ['and'], [''], ['contains'], + ['Donald - ^ \ ~ + Duck'], '', 'HeadingAsc' ); is( diff --git a/t/Koha/SearchEngine/Search.t b/t/Koha/SearchEngine/Search.t index cf34a6f55a..39ba02529f 100755 --- a/t/Koha/SearchEngine/Search.t +++ b/t/Koha/SearchEngine/Search.t @@ -34,9 +34,11 @@ subtest "pagination_bar tests" => sub { my @sort_by = ('relevance_dsc'); - my ( $PAGE_NUMBERS, $hits_to_paginate, $pages, $current_page_number, - $previous_page_offset, $next_page_offset, $last_page_offset ) - = Koha::SearchEngine::Search->pagination_bar( + my ( + $PAGE_NUMBERS, $hits_to_paginate, $pages, $current_page_number, + $previous_page_offset, $next_page_offset, $last_page_offset + ) + = Koha::SearchEngine::Search->pagination_bar( { hits => 500, max_result_window => 1000, @@ -44,25 +46,35 @@ subtest "pagination_bar tests" => sub { offset => 160, sort_by => \@sort_by } - ); - is( $hits_to_paginate, 500, - "We paginate all hits if less than max_result_window" ); + ); + is( + $hits_to_paginate, 500, + "We paginate all hits if less than max_result_window" + ); is( $pages, 25, "We have hits/hits_to_paginate pages" ); - is( $current_page_number, 9, - "We calculate current page by offset/results_per_page plus 1" ); - is( $previous_page_offset, 140, - "Previous page is current offset minus reults per page" ); - is( $next_page_offset, 180, - "Next page is current offset plus reults per page" ); - is( $last_page_offset, 480, - "Last page is pages minus 1 times reults per page" ); + is( + $current_page_number, 9, + "We calculate current page by offset/results_per_page plus 1" + ); + is( + $previous_page_offset, 140, + "Previous page is current offset minus reults per page" + ); + is( + $next_page_offset, 180, + "Next page is current offset plus reults per page" + ); + is( + $last_page_offset, 480, + "Last page is pages minus 1 times reults per page" + ); is( @$PAGE_NUMBERS, 10, "If on first ten pages we only show 10 pages" ); ( - $PAGE_NUMBERS, $hits_to_paginate, $pages, $current_page_number, + $PAGE_NUMBERS, $hits_to_paginate, $pages, $current_page_number, $previous_page_offset, $next_page_offset, $last_page_offset - ) - = Koha::SearchEngine::Search->pagination_bar( + ) + = Koha::SearchEngine::Search->pagination_bar( { hits => 500, max_result_window => 480, @@ -70,18 +82,28 @@ subtest "pagination_bar tests" => sub { offset => 240, sort_by => \@sort_by } - ); - is( $hits_to_paginate, 480, - "We paginate all hits if less than max_result_window" ); + ); + is( + $hits_to_paginate, 480, + "We paginate all hits if less than max_result_window" + ); is( $pages, 24, "We have hits/hits_to_paginate pages" ); - is( $current_page_number, 13, - "We calculate current page by offset/results_per_page plus 1" ); - is( $previous_page_offset, 220, - "Previous page is current offset minus reults per page" ); - is( $next_page_offset, 260, - "Next page is current offset plus reults per page" ); - is( $last_page_offset, 460, - "Last page is pages minus 1 times reults per page" ); + is( + $current_page_number, 13, + "We calculate current page by offset/results_per_page plus 1" + ); + is( + $previous_page_offset, 220, + "Previous page is current offset minus reults per page" + ); + is( + $next_page_offset, 260, + "Next page is current offset plus reults per page" + ); + is( + $last_page_offset, 460, + "Last page is pages minus 1 times reults per page" + ); is( @$PAGE_NUMBERS, 20, "If past first ten pages we show 20 pages" ); }; diff --git a/t/Koha/SearchEngine/Zebra/QueryBuilder.t b/t/Koha/SearchEngine/Zebra/QueryBuilder.t index 6dca03263d..3635e5987e 100755 --- a/t/Koha/SearchEngine/Zebra/QueryBuilder.t +++ b/t/Koha/SearchEngine/Zebra/QueryBuilder.t @@ -38,16 +38,14 @@ subtest 'build_authorities_query' => sub { authtypecode => '', orderby => 'HeadingAsc', }; - my $built_search = - Koha::SearchEngine::Zebra::QueryBuilder->build_authorities_query( @test_search ); + my $built_search = Koha::SearchEngine::Zebra::QueryBuilder->build_authorities_query(@test_search); is_deeply( $built_search, $expected_result, "We are simply hashifying our array of refs/values, should otherwise not be altered" ); $expected_result->{value} = ['"any"']; - $test_search[4] = ['"any"']; - $built_search = - Koha::SearchEngine::Zebra::QueryBuilder->build_authorities_query( @test_search ); + $test_search[4] = ['"any"']; + $built_search = Koha::SearchEngine::Zebra::QueryBuilder->build_authorities_query(@test_search); is_deeply( $built_search, $expected_result, "The same should hold true if the search contains double quotes which will be escaped during searching by search_auth_compat subroutine" @@ -59,22 +57,38 @@ subtest 'build_query_compat() tests' => sub { plan tests => 4; my $search = Test::MockModule->new('C4::Search'); - $search->mock( 'buildQuery', sub { return ( 'error', 'query', 'simple_query', 'query_cgi', 'query_desc', 'limit', 'limit_cgi', 'limit_desc', 'query_type' ) } ); + $search->mock( + 'buildQuery', + sub { + return ( + 'error', 'query', 'simple_query', 'query_cgi', 'query_desc', 'limit', 'limit_cgi', 'limit_desc', + 'query_type' + ); + } + ); my $qb = Koha::SearchEngine::Zebra::QueryBuilder->new(); my $query; ( undef, $query ) = $qb->build_query_compat( undef, undef, undef, undef, undef, undef, undef, { suppress => 1 } ); - is( $query, '(query) not Suppress=1', 'Suppress part of the query added correctly'); + is( $query, '(query) not Suppress=1', 'Suppress part of the query added correctly' ); ( undef, $query ) = $qb->build_query_compat( undef, undef, undef, undef, undef, undef, undef, { suppress => 0 } ); - is( $query, 'query', 'Suppress part of the query not added'); + is( $query, 'query', 'Suppress part of the query not added' ); - $search->mock( 'buildQuery', sub { return ( 'error', 'query', 'simple_query', 'query_cgi', 'query_desc', 'limit', 'limit_cgi', 'limit_desc', 'pqf' ) } ); + $search->mock( + 'buildQuery', + sub { + return ( + 'error', 'query', 'simple_query', 'query_cgi', 'query_desc', 'limit', 'limit_cgi', 'limit_desc', + 'pqf' + ); + } + ); ( undef, $query ) = $qb->build_query_compat( undef, undef, undef, undef, undef, undef, undef, { suppress => 1 } ); - is( $query, '@not query @attr 14=1 @attr 1=9011 1', 'Suppress part of the query added correctly (PQF)'); + is( $query, '@not query @attr 14=1 @attr 1=9011 1', 'Suppress part of the query added correctly (PQF)' ); ( undef, $query ) = $qb->build_query_compat( undef, undef, undef, undef, undef, undef, undef, { suppress => 0 } ); - is( $query, 'query', 'Suppress part of the query not added (PQF)'); + is( $query, 'query', 'Suppress part of the query not added (PQF)' ); }; subtest 'clean_search_term() tests' => sub { @@ -88,5 +102,5 @@ subtest 'clean_search_term() tests' => sub { ); my $res = $qb->clean_search_term('test "query":'); - is($res, 'test \"query\":', 'Double-quotes are escaped'); + is( $res, 'test \"query\":', 'Double-quotes are escaped' ); }; diff --git a/t/Koha/Util/MARC.t b/t/Koha/Util/MARC.t index 95e9c21397..5a349c9eb2 100755 --- a/t/Koha/Util/MARC.t +++ b/t/Koha/Util/MARC.t @@ -28,19 +28,19 @@ subtest 'set_marc_field' => sub { my $record = MARC::Record->new(); - Koha::Util::MARC::set_marc_field($record, '999$9', 'foobar'); + Koha::Util::MARC::set_marc_field( $record, '999$9', 'foobar' ); my @fields = $record->field('999'); - is(scalar @fields, 1, 'Created one field'); + is( scalar @fields, 1, 'Created one field' ); my @subfields = $fields[0]->subfield('9'); - is(scalar @subfields, 1, 'Created one subfield'); - is($subfields[0], 'foobar', 'Created subfield has correct value'); + is( scalar @subfields, 1, 'Created one subfield' ); + is( $subfields[0], 'foobar', 'Created subfield has correct value' ); - Koha::Util::MARC::set_marc_field($record, '999$9', 'foobaz'); + Koha::Util::MARC::set_marc_field( $record, '999$9', 'foobaz' ); @fields = $record->field('999'); - is(scalar @fields, 1, 'No additional field created'); + is( scalar @fields, 1, 'No additional field created' ); @subfields = $fields[0]->subfield('9'); - is(scalar @subfields, 1, 'No additional subfield created'); - is($subfields[0], 'foobaz', 'Subfield value has been changed'); + is( scalar @subfields, 1, 'No additional subfield created' ); + is( $subfields[0], 'foobaz', 'Subfield value has been changed' ); }; subtest 'find_marc_info, strip_orgcode, oclc_number' => sub { @@ -49,22 +49,44 @@ subtest 'find_marc_info, strip_orgcode, oclc_number' => sub { my $record = MARC::Record->new; $record->append_fields( MARC::Field->new( '003', 'some_data' ), - MARC::Field->new( '035', '', '', a => '(test)123', a => '(change)456' ), + MARC::Field->new( '035', '', '', a => '(test)123', a => '(change)456' ), MARC::Field->new( '035', '', '', a => '(test) 567', a => '(change) 567' ), ); - is( scalar Koha::Util::MARC::find_marc_info({ - record => $record, field => '003', - }), 'some_data', 'control field, scalar' ); - is( ( Koha::Util::MARC::find_marc_info({ - record => $record, field => '003', - }))[0], 'some_data', 'control field, list' ); + is( + scalar Koha::Util::MARC::find_marc_info( + { + record => $record, field => '003', + } + ), + 'some_data', + 'control field, scalar' + ); + is( + ( + Koha::Util::MARC::find_marc_info( + { + record => $record, field => '003', + } + ) + )[0], + 'some_data', + 'control field, list' + ); - is( scalar Koha::Util::MARC::find_marc_info({ - record => $record, field => '035', subfield => 'a', match => qr/56/, - }), '(change)456', '035a, match, scalar' ); - my @list = Koha::Util::MARC::find_marc_info({ - record => $record, field => '035', subfield => 'a', match => qr/c.*56/, - }); + is( + scalar Koha::Util::MARC::find_marc_info( + { + record => $record, field => '035', subfield => 'a', match => qr/56/, + } + ), + '(change)456', + '035a, match, scalar' + ); + my @list = Koha::Util::MARC::find_marc_info( + { + record => $record, field => '035', subfield => 'a', match => qr/c.*56/, + } + ); is_deeply( \@list, [ '(change)456', '(change) 567' ], '035a, match, list' ); @list = map { Koha::Util::MARC::strip_orgcode($_) } @list; diff --git a/t/Koha/Util/Navigation.t b/t/Koha/Util/Navigation.t index 9ff50ea238..1238c6958c 100755 --- a/t/Koha/Util/Navigation.t +++ b/t/Koha/Util/Navigation.t @@ -12,10 +12,10 @@ subtest 'Tests for local_referer' => sub { my ( $referer, $base ); my $cgi = Test::MockObject->new; $cgi->mock( 'referer', sub { $referer } ); - $cgi->mock( 'url', sub { $base } ); # base for [opac-]changelanguage + $cgi->mock( 'url', sub { $base } ); # base for [opac-]changelanguage # Start with filled OPACBaseIRL - t::lib::Mocks::mock_preference('OPACBaseURL', 'https://koha.nl' ); + t::lib::Mocks::mock_preference( 'OPACBaseURL', 'https://koha.nl' ); $referer = 'https://somewhere.com/myscript'; is( Koha::Util::Navigation::local_referer($cgi), '/', 'External referer' ); @@ -26,39 +26,48 @@ subtest 'Tests for local_referer' => sub { $referer = 'https://koha.nl/custom/stuff'; is( Koha::Util::Navigation::local_referer($cgi), '/', 'custom url' ); - t::lib::Mocks::mock_preference('OPACBaseURL', 'http://kohadev.myDNSname.org:8080'); + t::lib::Mocks::mock_preference( 'OPACBaseURL', 'http://kohadev.myDNSname.org:8080' ); $referer = "http://kohadev.mydnsname.org:8080$search"; - is( Koha::Util::Navigation::local_referer($cgi), $search, 'local_referer is comparing $OPACBaseURL case insensitive' ); + is( + Koha::Util::Navigation::local_referer($cgi), $search, + 'local_referer is comparing $OPACBaseURL case insensitive' + ); # trailing backslash - t::lib::Mocks::mock_preference('OPACBaseURL', 'http://koha.nl/' ); + t::lib::Mocks::mock_preference( 'OPACBaseURL', 'http://koha.nl/' ); $referer = "http://koha.nl$search"; is( Koha::Util::Navigation::local_referer($cgi), $search, 'opac-search, trailing backslash' ); # no OPACBaseURL - t::lib::Mocks::mock_preference('OPACBaseURL', ''); + t::lib::Mocks::mock_preference( 'OPACBaseURL', '' ); $referer = 'https://somewhere.com/myscript'; - $base = 'http://koha.nl'; + $base = 'http://koha.nl'; is( Koha::Util::Navigation::local_referer($cgi), '/', 'no opacbaseurl, external' ); $referer = "https://koha.nl$search"; - $base = 'https://koha.nl'; + $base = 'https://koha.nl'; is( Koha::Util::Navigation::local_referer($cgi), $search, 'no opacbaseurl, opac-search' ); $base = 'http://koha.nl'; is( Koha::Util::Navigation::local_referer($cgi), $search, 'no opacbaseurl, opac-search, protocol diff' ); # base contains https, referer http (this should be very unusual) # test parameters remove_language. staff - t::lib::Mocks::mock_preference('staffClientBaseURL', '' ); - $search = '/cgi-bin/koha/catalogue/search.pl?q=perl'; # staff + t::lib::Mocks::mock_preference( 'staffClientBaseURL', '' ); + $search = '/cgi-bin/koha/catalogue/search.pl?q=perl'; # staff $referer = "http://koha.nl:8080$search&language=zz-ZZ&debug=1"; - $base = 'https://koha.nl:8080'; - is( Koha::Util::Navigation::local_referer($cgi, { remove_language => 1, staff => 1 }), $search.'&debug=1', 'no baseurl, staff search, protocol diff (base https)' ); + $base = 'https://koha.nl:8080'; + is( + Koha::Util::Navigation::local_referer( $cgi, { remove_language => 1, staff => 1 } ), $search . '&debug=1', + 'no baseurl, staff search, protocol diff (base https)' + ); # custom script, test fallback parameter $referer = 'https://koha.nl/custom/stuff'; - $base = 'https://koha.nl'; - is( Koha::Util::Navigation::local_referer($cgi, { fallback => 'ZZZ' }), 'ZZZ', 'no opacbaseurl, custom url, test fallback' ); + $base = 'https://koha.nl'; + is( + Koha::Util::Navigation::local_referer( $cgi, { fallback => 'ZZZ' } ), 'ZZZ', + 'no opacbaseurl, custom url, test fallback' + ); $base = 'http://koha.nl'; is( Koha::Util::Navigation::local_referer($cgi), '/', 'no opacbaseurl, custom url, protocol diff' ); }; diff --git a/t/Koha/Util/Normalize.t b/t/Koha/Util/Normalize.t index 317ad8cbf8..1aeaf793d4 100755 --- a/t/Koha/Util/Normalize.t +++ b/t/Koha/Util/Normalize.t @@ -40,16 +40,17 @@ subtest 'pass undef' => sub { warning_is { lower_case() } undef, 'no warn from lower_case'; }; - subtest 'legacy_default() normalizer' => sub { plan tests => 1; my $string = ' .; kY[]:, (l)/E\'"'; - is( Koha::Util::Normalize::legacy_default( $string ), 'KY LE', + is( + Koha::Util::Normalize::legacy_default($string), 'KY LE', 'The \'legacy_default\' normalizer removes: .;:,][)(/\'" and shifts characters upper-case. - Also removes spaces from the beginning and ending, and replaces multiple spaces with a single one.' ); + Also removes spaces from the beginning and ending, and replaces multiple spaces with a single one.' + ); }; subtest 'remove_spaces() normalizer' => sub { @@ -58,8 +59,10 @@ subtest 'remove_spaces() normalizer' => sub { my $string = ' .; kY[]:, (l)/E\'"'; - is( Koha::Util::Normalize::remove_spaces( $string ), '.;kY[]:,(l)/E\'"', - 'The \'remove_spaces\' normalizer removes all spaces' ); + is( + Koha::Util::Normalize::remove_spaces($string), '.;kY[]:,(l)/E\'"', + 'The \'remove_spaces\' normalizer removes all spaces' + ); }; subtest 'upper_case() normalizer' => sub { @@ -68,8 +71,10 @@ subtest 'upper_case() normalizer' => sub { my $string = ' .; kY[]:, (l)/E\'"'; - is( Koha::Util::Normalize::upper_case( $string ), ' .; KY[]:, (L)/E\'"', - 'The \'upper_case\' normalizer only makes characters upper-case' ); + is( + Koha::Util::Normalize::upper_case($string), ' .; KY[]:, (L)/E\'"', + 'The \'upper_case\' normalizer only makes characters upper-case' + ); }; subtest 'lower_case() normalizer' => sub { @@ -78,7 +83,9 @@ subtest 'lower_case() normalizer' => sub { my $string = ' .; kY[]:, (l)/E\'"'; - is( Koha::Util::Normalize::lower_case( $string ), ' .; ky[]:, (l)/e\'"', - 'The \'lower_case\' normalizer only makes characters lower-case' ); + is( + Koha::Util::Normalize::lower_case($string), ' .; ky[]:, (l)/e\'"', + 'The \'lower_case\' normalizer only makes characters lower-case' + ); }; diff --git a/t/Koha/Z3950responder.t b/t/Koha/Z3950responder.t index 7f2219783b..0a94cc0c9d 100755 --- a/t/Koha/Z3950responder.t +++ b/t/Koha/Z3950responder.t @@ -7,8 +7,8 @@ BEGIN { use_ok('Koha::Z3950Responder'); } -my $zR = Koha::Z3950Responder->new({}); +my $zR = Koha::Z3950Responder->new( {} ); my $args = { PEER_NAME => 'PEER' }; $zR->init_handler($args); -is ( $args->{IMP_NAME}, 'Koha', 'Server returns basic info' ); +is( $args->{IMP_NAME}, 'Koha', 'Server returns basic info' ); diff --git a/t/Koha/sleep.pl b/t/Koha/sleep.pl index 072ec5b377..474fe470a2 100755 --- a/t/Koha/sleep.pl +++ b/t/Koha/sleep.pl @@ -5,7 +5,7 @@ use Modern::Perl; use Koha::Script; # # Lock execution -my $script = Koha::Script->new({ script => 'sleep.pl' }); +my $script = Koha::Script->new( { script => 'sleep.pl' } ); $script->lock_exec; diff --git a/t/Koha/wait.pl b/t/Koha/wait.pl index ebe873b0af..2c5f251d64 100755 --- a/t/Koha/wait.pl +++ b/t/Koha/wait.pl @@ -5,9 +5,9 @@ use Modern::Perl; use Koha::Script; # # Lock execution -my $script = Koha::Script->new({ script => 'sleep.pl' }); +my $script = Koha::Script->new( { script => 'sleep.pl' } ); -$script->lock_exec({ wait => 1 }); +$script->lock_exec( { wait => 1 } ); print STDOUT "YAY!"; diff --git a/t/Koha_MetadataRecord.t b/t/Koha_MetadataRecord.t index cb24fb8659..4ede2590b4 100755 --- a/t/Koha_MetadataRecord.t +++ b/t/Koha_MetadataRecord.t @@ -32,13 +32,13 @@ BEGIN { my $marcrecord = MARC::Record->new; $marcrecord->add_fields( - [ '001', '1234' ], - [ '150', ' ', ' ', a => 'Cooking' ], - [ '450', ' ', ' ', a => 'Cookery', z => 'Instructional manuals' ], - ); -my $record = Koha::MetadataRecord->new({ 'record' => $marcrecord, 'schema' => 'marc21' }); + [ '001', '1234' ], + [ '150', ' ', ' ', a => 'Cooking' ], + [ '450', ' ', ' ', a => 'Cookery', z => 'Instructional manuals' ], +); +my $record = Koha::MetadataRecord->new( { 'record' => $marcrecord, 'schema' => 'marc21' } ); -is(ref($record), 'Koha::MetadataRecord', 'Created valid Koha::MetadataRecord object'); +is( ref($record), 'Koha::MetadataRecord', 'Created valid Koha::MetadataRecord object' ); my $samplehash = [ { @@ -76,18 +76,17 @@ my $samplehash = [ my $hash = $record->createMergeHash(); my %fieldkeys; foreach my $field (@$hash) { - $fieldkeys{delete $field->{'key'}}++; - if (defined $field->{'subfield'}) { - foreach my $subfield (@{$field->{'subfield'}}) { - $fieldkeys{delete $subfield->{'subkey'}}++; + $fieldkeys{ delete $field->{'key'} }++; + if ( defined $field->{'subfield'} ) { + foreach my $subfield ( @{ $field->{'subfield'} } ) { + $fieldkeys{ delete $subfield->{'subkey'} }++; } } } -is_deeply($hash, $samplehash, 'Generated hash correctly'); +is_deeply( $hash, $samplehash, 'Generated hash correctly' ); my $dupkeys = grep { $_ > 1 } values %fieldkeys; -is($dupkeys, 0, 'No duplicate keys'); - +is( $dupkeys, 0, 'No duplicate keys' ); subtest "new() tests" => sub { @@ -97,49 +96,58 @@ subtest "new() tests" => sub { my $record = MARC::Record->new(); my $metadata_record; - warning_is { $metadata_record = Koha::MetadataRecord->new({ - record => $record }) } - { carped => 'No schema passed' }, + warning_is { + $metadata_record = Koha::MetadataRecord->new( { record => $record } ) + } + { carped => 'No schema passed' }, "Metadata schema is mandatory, raise a carped warning if omitted"; - is( $metadata_record, undef, "Metadata schema is mandatory, return undef if omitted"); + is( $metadata_record, undef, "Metadata schema is mandatory, return undef if omitted" ); - $metadata_record = Koha::MetadataRecord->new({ - record => $record, - schema => 'marc21' - }); + $metadata_record = Koha::MetadataRecord->new( + { + record => $record, + schema => 'marc21' + } + ); - is( ref($metadata_record), 'Koha::MetadataRecord', 'Type correct'); - is( ref($metadata_record->record), 'MARC::Record', 'Record type preserved'); - is( $metadata_record->schema, 'marc21', 'Metadata schema is set to marc21'); - is( $metadata_record->format, 'MARC', 'Serializacion format defaults to marc'); - is( $metadata_record->id, undef, 'id is optional, undef if unspecifid'); + is( ref($metadata_record), 'Koha::MetadataRecord', 'Type correct' ); + is( ref( $metadata_record->record ), 'MARC::Record', 'Record type preserved' ); + is( $metadata_record->schema, 'marc21', 'Metadata schema is set to marc21' ); + is( $metadata_record->format, 'MARC', 'Serializacion format defaults to marc' ); + is( $metadata_record->id, undef, 'id is optional, undef if unspecifid' ); # Test passed values, also no constraint on record type my $weird_record = {}; bless $weird_record, 'Weird::Class'; - $metadata_record = Koha::MetadataRecord->new({ - record => $weird_record, - schema => 'something', - format => 'else', - id => 'an id' - }); + $metadata_record = Koha::MetadataRecord->new( + { + record => $weird_record, + schema => 'something', + format => 'else', + id => 'an id' + } + ); - is( ref($metadata_record), 'Koha::MetadataRecord', 'Type correct'); - is( ref($metadata_record->record), 'Weird::Class', 'Record type preserved'); - is( $metadata_record->schema, 'something', 'Metadata schema correctly set'); - is( $metadata_record->format, 'else', 'Serializacion format correctly set'); - is( $metadata_record->id, 'an id', 'The id correctly set'); + is( ref($metadata_record), 'Koha::MetadataRecord', 'Type correct' ); + is( ref( $metadata_record->record ), 'Weird::Class', 'Record type preserved' ); + is( $metadata_record->schema, 'something', 'Metadata schema correctly set' ); + is( $metadata_record->format, 'else', 'Serializacion format correctly set' ); + is( $metadata_record->id, 'an id', 'The id correctly set' ); # Having a record object is mandatory - warning_is { $metadata_record = Koha::MetadataRecord->new({ - record => undef, - schema => 'something', - format => 'else', - id => 'an id' - }) } - { carped => 'No record passed' }, - 'Undefined record raises carped warning'; + warning_is { + $metadata_record = Koha::MetadataRecord->new( + { + record => undef, + schema => 'something', + format => 'else', + id => 'an id' + } + ) + } + { carped => 'No record passed' }, + 'Undefined record raises carped warning'; - is( $metadata_record, undef, 'record object mandatory') + is( $metadata_record, undef, 'record object mandatory' ); }; diff --git a/t/Koha_SearchEngine_Elasticsearch_Browse.t b/t/Koha_SearchEngine_Elasticsearch_Browse.t index 986c4ba658..0ed478e25e 100755 --- a/t/Koha_SearchEngine_Elasticsearch_Browse.t +++ b/t/Koha_SearchEngine_Elasticsearch_Browse.t @@ -24,45 +24,57 @@ use Test::More; use_ok('Koha::SearchEngine::Elasticsearch::Browse'); # testing browse itself not implemented as it'll require a running ES -can_ok('Koha::SearchEngine::Elasticsearch::Browse', - qw/ _build_query browse /); +can_ok( + 'Koha::SearchEngine::Elasticsearch::Browse', + qw/ _build_query browse / +); subtest "_build_query tests" => sub { plan tests => 2; - my $browse = Koha::SearchEngine::Elasticsearch::Browse->new({index=>'dummy'}); - my $q = $browse->_build_query('foo', 'title'); - is_deeply($q, { size => 1, - suggest => { - suggestions => { - text => 'foo', - completion => { - field => 'title__suggestion', - size => 500, - fuzzy => { - fuzziness => 1, + my $browse = Koha::SearchEngine::Elasticsearch::Browse->new( { index => 'dummy' } ); + my $q = $browse->_build_query( 'foo', 'title' ); + is_deeply( + $q, + { + size => 1, + suggest => { + suggestions => { + text => 'foo', + completion => { + field => 'title__suggestion', + size => 500, + fuzzy => { + fuzziness => 1, + } } } } - } - }, 'No fuzziness or size specified'); + }, + 'No fuzziness or size specified' + ); # Note that a fuzziness of 4 will get reduced to 2. - $q = $browse->_build_query('foo', 'title', { fuzziness => 4, count => 400 }); - is_deeply($q, { size => 1, - suggest => { - suggestions => { - text => 'foo', - completion => { - field => 'title__suggestion', - size => 400, - fuzzy => { - fuzziness => 2, + $q = $browse->_build_query( 'foo', 'title', { fuzziness => 4, count => 400 } ); + is_deeply( + $q, + { + size => 1, + suggest => { + suggestions => { + text => 'foo', + completion => { + field => 'title__suggestion', + size => 400, + fuzzy => { + fuzziness => 2, + } } } } - } - }, 'Fuzziness and size specified'); + }, + 'Fuzziness and size specified' + ); }; done_testing(); diff --git a/t/Koha_Template_Plugin_HtmlId.t b/t/Koha_Template_Plugin_HtmlId.t index 7e767a2cc9..552aa55964 100755 --- a/t/Koha_Template_Plugin_HtmlId.t +++ b/t/Koha_Template_Plugin_HtmlId.t @@ -19,7 +19,10 @@ use Modern::Perl; use Test::More tests => 2; -use_ok( 'Koha::Template::Plugin::HtmlId' ); +use_ok('Koha::Template::Plugin::HtmlId'); my $filter = Koha::Template::Plugin::HtmlId->new(); -is('Some_not-allowed_characters', $filter->filter('Some/;:not-allowed*$^characters'), 'Forbidden characters are replaced by _'); +is( + 'Some_not-allowed_characters', $filter->filter('Some/;:not-allowed*$^characters'), + 'Forbidden characters are replaced by _' +); diff --git a/t/Koha_Template_Plugin_Koha.t b/t/Koha_Template_Plugin_Koha.t index a8d66feb9d..285c37adca 100755 --- a/t/Koha_Template_Plugin_Koha.t +++ b/t/Koha_Template_Plugin_Koha.t @@ -24,7 +24,7 @@ use t::lib::Mocks; use String::Random; # Test the plugin is usable -use_ok( 'Koha::Template::Plugin::Koha' ); +use_ok('Koha::Template::Plugin::Koha'); ok( my $cache = Koha::Template::Plugin::Koha->new() ); subtest "Koha::Template::Plugin::Koha::Version tests" => sub { @@ -39,41 +39,52 @@ subtest "Koha::Template::Plugin::Koha::Version tests" => sub { # Mock Koha::version() my $koha = Test::MockModule->new('Koha'); - $koha->mock( 'version', sub { - return "$major.$minor.$maintenance.$development"; - }); + $koha->mock( + 'version', + sub { + return "$major.$minor.$maintenance.$development"; + } + ); my $rnd = String::Random->new; + # development version test $major = $rnd->randregex('\d'); $minor = $rnd->randregex('\d\d'); $maintenance = $rnd->randregex('\d\d'); $development = $rnd->randregex('\d\d\d'); my $version = "$major.$minor.$maintenance.$development"; - my $res = Koha::Template::Plugin::Koha::Version( $version ); - is_deeply( $res, { - major => $major, - minor => $minor, - release => $major . "." . $minor, - maintenance => $major . "." . $minor . "." . $maintenance, - development => $development - }, "Correct development version"); - + my $res = Koha::Template::Plugin::Koha::Version($version); + is_deeply( + $res, + { + major => $major, + minor => $minor, + release => $major . "." . $minor, + maintenance => $major . "." . $minor . "." . $maintenance, + development => $development + }, + "Correct development version" + ); # maintenance release test $major = $rnd->randregex('\d'); $minor = $rnd->randregex('\d\d'); $maintenance = $rnd->randregex('\d\d'); $development = "000"; - $version = "$major.$minor.$maintenance.$development"; - $res = Koha::Template::Plugin::Koha::Version( $version ); - is_deeply( $res, { - major => $major, - minor => $minor, - release => $major . "." . $minor, - maintenance => $major . "." . $minor . "." . $maintenance, - development => undef - }, "Correct maintenance version"); + $version = "$major.$minor.$maintenance.$development"; + $res = Koha::Template::Plugin::Koha::Version($version); + is_deeply( + $res, + { + major => $major, + minor => $minor, + release => $major . "." . $minor, + maintenance => $major . "." . $minor . "." . $maintenance, + development => undef + }, + "Correct maintenance version" + ); }; @@ -83,21 +94,21 @@ subtest "Koha::Template::Plugin::Koha::CSVDelimiter tests" => sub { my $plugin = Koha::Template::Plugin::Koha->new(); - t::lib::Mocks::mock_preference('CSVDelimiter', ''); - is($plugin->CSVDelimiter(), ',', "CSVDelimiter() returns comma when preference is empty string"); + t::lib::Mocks::mock_preference( 'CSVDelimiter', '' ); + is( $plugin->CSVDelimiter(), ',', "CSVDelimiter() returns comma when preference is empty string" ); - t::lib::Mocks::mock_preference('CSVDelimiter', undef); - is($plugin->CSVDelimiter(), ',', "CSVDelimiter() returns comma when preference is undefined"); + t::lib::Mocks::mock_preference( 'CSVDelimiter', undef ); + is( $plugin->CSVDelimiter(), ',', "CSVDelimiter() returns comma when preference is undefined" ); - t::lib::Mocks::mock_preference('CSVDelimiter', ';'); - is($plugin->CSVDelimiter(), ';', "CSVDelimiter() returns preference value when preference is not tabulation"); + t::lib::Mocks::mock_preference( 'CSVDelimiter', ';' ); + is( $plugin->CSVDelimiter(), ';', "CSVDelimiter() returns preference value when preference is not tabulation" ); - t::lib::Mocks::mock_preference('CSVDelimiter', 'tabulation'); - is($plugin->CSVDelimiter(), "\t", "CSVDelimiter() returns \\t when preference is tabulation"); + t::lib::Mocks::mock_preference( 'CSVDelimiter', 'tabulation' ); + is( $plugin->CSVDelimiter(), "\t", "CSVDelimiter() returns \\t when preference is tabulation" ); - t::lib::Mocks::mock_preference('CSVDelimiter', '#'); - is($plugin->CSVDelimiter(undef), '#', "CSVDelimiter(arg) returns preference value when arg is undefined"); - is($plugin->CSVDelimiter(''), '#', "CSVDelimiter(arg) returns preference value when arg is empty string"); - is($plugin->CSVDelimiter(','), ',', "CSVDelimiter(arg) returns arg value when arg is not tabulation"); - is($plugin->CSVDelimiter('tabulation'), "\t", "CSVDelimiter(arg) returns \\t value when arg is tabulation"); + t::lib::Mocks::mock_preference( 'CSVDelimiter', '#' ); + is( $plugin->CSVDelimiter(undef), '#', "CSVDelimiter(arg) returns preference value when arg is undefined" ); + is( $plugin->CSVDelimiter(''), '#', "CSVDelimiter(arg) returns preference value when arg is empty string" ); + is( $plugin->CSVDelimiter(','), ',', "CSVDelimiter(arg) returns arg value when arg is not tabulation" ); + is( $plugin->CSVDelimiter('tabulation'), "\t", "CSVDelimiter(arg) returns \\t value when arg is tabulation" ); }; diff --git a/t/Koha_Util_FrameworkPlugin.t b/t/Koha_Util_FrameworkPlugin.t index a30e3e79d5..2f604761af 100755 --- a/t/Koha_Util_FrameworkPlugin.t +++ b/t/Koha_Util_FrameworkPlugin.t @@ -6,11 +6,11 @@ use Test::More tests => 7; use_ok( 'Koha::Util::FrameworkPlugin', qw(wrapper date_entered) ); my $char; -is($char=wrapper(' '),'space',"Return space"); -is($char=wrapper(' '),'dblspace',"Return dblspace"); -is($char=wrapper('|'),'pipe',"Return pipe"); -is($char=wrapper('||'),'dblpipe',"Return dblpipe"); -is($char=wrapper('somethingelse'),'somethingelse',"Return somethingelse"); +is( $char = wrapper(' '), 'space', "Return space" ); +is( $char = wrapper(' '), 'dblspace', "Return dblspace" ); +is( $char = wrapper('|'), 'pipe', "Return pipe" ); +is( $char = wrapper('||'), 'dblpipe', "Return dblpipe" ); +is( $char = wrapper('somethingelse'), 'somethingelse', "Return somethingelse" ); -my $f008= date_entered(); +my $f008 = date_entered(); is( $f008 =~ /^\d{6}$/, 1, 'date_entered gives six digits' ); diff --git a/t/Koha_Util_MARC.t b/t/Koha_Util_MARC.t index e33867003c..2558a84414 100755 --- a/t/Koha_Util_MARC.t +++ b/t/Koha_Util_MARC.t @@ -27,16 +27,16 @@ use Test::More tests => 4; use MARC::Record; BEGIN { - use_ok('Koha::Util::MARC'); + use_ok('Koha::Util::MARC'); } my $marcrecord = MARC::Record->new; $marcrecord->add_fields( - [ '001', '1234' ], - [ '150', ' ', ' ', a => 'Cooking' ], - [ '450', ' ', ' ', a => 'Cookery', z => 'Instructional manuals' ], - ); + [ '001', '1234' ], + [ '150', ' ', ' ', a => 'Cooking' ], + [ '450', ' ', ' ', a => 'Cookery', z => 'Instructional manuals' ], +); my $samplehash = [ { 'value' => '1234', @@ -73,16 +73,19 @@ my $samplehash = [ my $hash = Koha::Util::MARC::createMergeHash($marcrecord); my %fieldkeys; foreach my $field (@$hash) { - $fieldkeys{delete $field->{'key'}}++; - if (defined $field->{'subfield'}) { - foreach my $subfield (@{$field->{'subfield'}}) { - $fieldkeys{delete $subfield->{'subkey'}}++; + $fieldkeys{ delete $field->{'key'} }++; + if ( defined $field->{'subfield'} ) { + foreach my $subfield ( @{ $field->{'subfield'} } ) { + $fieldkeys{ delete $subfield->{'subkey'} }++; } } } -is_deeply($hash, $samplehash, 'Generated hash correctly'); +is_deeply( $hash, $samplehash, 'Generated hash correctly' ); my $dupkeys = grep { $_ > 1 } values %fieldkeys; -is($dupkeys, 0, 'No duplicate keys'); +is( $dupkeys, 0, 'No duplicate keys' ); -is(Koha::Util::MARC::getAuthorityAuthorizedHeading($marcrecord, 'marc21'), 'Cooking', 'Routine for retrieving authorized heading works'); +is( + Koha::Util::MARC::getAuthorityAuthorizedHeading( $marcrecord, 'marc21' ), 'Cooking', + 'Routine for retrieving authorized heading works' +); diff --git a/t/Koha_XSLT_HTTPS.t b/t/Koha_XSLT_HTTPS.t index a5d1da4aaa..be7cd93d33 100755 --- a/t/Koha_XSLT_HTTPS.t +++ b/t/Koha_XSLT_HTTPS.t @@ -31,29 +31,29 @@ subtest 'load' => sub { # Mock the LWP stuff my $lwp_object = Test::MockObject->new; - my $response = Test::MockObject->new; + my $response = Test::MockObject->new; $response->mock( 'is_success', sub { return 0 } ); $lwp_object->mock( 'get', sub { return $response; } ); - my $lwp_mod = Test::MockModule->new( 'LWP::UserAgent' ); + my $lwp_mod = Test::MockModule->new('LWP::UserAgent'); $lwp_mod->mock( 'new', sub { return $lwp_object } ); # Trivial bad input throws_ok { Koha::XSLT::HTTPS->load; } 'Koha::Exceptions::XSLT::MissingFilename', 'No filename'; throws_ok { Koha::XSLT::HTTPS->load(q{}); } 'Koha::Exceptions::XSLT::MissingFilename', 'Empty filename'; my $result = Koha::XSLT::HTTPS->load('filename.xsl'); - is( ref($result), 'HASH', 'Should return hash' ); - is( exists $result->{location}, 1, 'Hash key location found' ); - is( $result->{location}, 'filename.xsl', 'Value for location key' ); + is( ref($result), 'HASH', 'Should return hash' ); + is( exists $result->{location}, 1, 'Hash key location found' ); + is( $result->{location}, 'filename.xsl', 'Value for location key' ); # Mock returns no success throws_ok { Koha::XSLT::HTTPS->load('https://myfavoritexsltsite.com/test1.xsl'); } - 'Koha::Exceptions::XSLT::FetchFailed', 'Fetch failed'; + 'Koha::Exceptions::XSLT::FetchFailed', 'Fetch failed'; # Mock returns 'code' - $response->mock( 'is_success', sub { return 1 } ); + $response->mock( 'is_success', sub { return 1 } ); $response->mock( 'decoded_content', sub { return 'supposed_xslt_code' } ); $result = Koha::XSLT::HTTPS->load('https://myfavoritexsltsite.com/test2.xsl'); - is( ref($result), 'HASH', 'Should return hash' ); - is( exists $result->{string}, 1, 'Hash key string found' ); - is( $result->{string}, 'supposed_xslt_code', 'Value for string key' ); -} + is( ref($result), 'HASH', 'Should return hash' ); + is( exists $result->{string}, 1, 'Hash key string found' ); + is( $result->{string}, 'supposed_xslt_code', 'Value for string key' ); + } diff --git a/t/Labels.t b/t/Labels.t index 69793618a7..1a5d8b53b1 100755 --- a/t/Labels.t +++ b/t/Labels.t @@ -24,32 +24,42 @@ use C4::ClassSplitRoutine::LCC qw( split_callnumber ); use Test::More tests => 11; BEGIN { - use_ok('C4::Labels::Label', qw( _get_text_fields _check_params _guide_box )); + use_ok( 'C4::Labels::Label', qw( _get_text_fields _check_params _guide_box ) ); } -my $format_string = "title, callnumber"; -my $parsed_fields = C4::Labels::Label::_get_text_fields($format_string); +my $format_string = "title, callnumber"; +my $parsed_fields = C4::Labels::Label::_get_text_fields($format_string); my $expected_fields = [ - { code => 'title', desc => 'title' }, - { code => 'itemcallnumber', desc => 'itemcallnumber' }, + { code => 'title', desc => 'title' }, + { code => 'itemcallnumber', desc => 'itemcallnumber' }, ]; -is_deeply($parsed_fields, $expected_fields, '"callnumber" in label layout alias for "itemcallnumber" per bug 5653'); +is_deeply( $parsed_fields, $expected_fields, '"callnumber" in label layout alias for "itemcallnumber" per bug 5653' ); -is(C4::Labels::Label::_check_params(),"0",'test checking parameters'); +is( C4::Labels::Label::_check_params(), "0", 'test checking parameters' ); -my ($llx,$lly,$width,$height) = ( 0, 0, 10, 10 ); -ok(!defined C4::Labels::Label::_guide_box(), - "Test guide box with undefined parameters returns undef"); -ok(!defined C4::Labels::Label::_guide_box(undef,$lly,$width,$height), - "Test guide box with undefined 'x' coordinate returns undef"); -ok(!defined C4::Labels::Label::_guide_box($llx,undef,$width,$height), - "Test guide box with undefined 'y' coordinate returns undef"); -ok(!defined C4::Labels::Label::_guide_box($llx,$lly,undef,$height), - "Test guide box with undefined 'width' returns undef"); -ok(!defined C4::Labels::Label::_guide_box($llx,$lly,$width,undef), - "Test guide box with undefined 'height' returns undef"); +my ( $llx, $lly, $width, $height ) = ( 0, 0, 10, 10 ); +ok( + !defined C4::Labels::Label::_guide_box(), + "Test guide box with undefined parameters returns undef" +); +ok( + !defined C4::Labels::Label::_guide_box( undef, $lly, $width, $height ), + "Test guide box with undefined 'x' coordinate returns undef" +); +ok( + !defined C4::Labels::Label::_guide_box( $llx, undef, $width, $height ), + "Test guide box with undefined 'y' coordinate returns undef" +); +ok( + !defined C4::Labels::Label::_guide_box( $llx, $lly, undef, $height ), + "Test guide box with undefined 'width' returns undef" +); +ok( + !defined C4::Labels::Label::_guide_box( $llx, $lly, $width, undef ), + "Test guide box with undefined 'height' returns undef" +); is( - C4::Labels::Label::_guide_box($llx, $lly, $width, $height), + C4::Labels::Label::_guide_box( $llx, $lly, $width, $height ), 'q 0.5 w 1.0 0.0 0.0 RG @@ -61,6 +71,6 @@ Q 'Return guide box if all four parameters are defined' ); -ok(C4::Labels::Label::_get_text_fields(), 'test getting textx fields'); +ok( C4::Labels::Label::_get_text_fields(), 'test getting textx fields' ); -is(C4::ClassSplitRoutine::LCC::split_callnumber(),"0", 'test when split LCC is null'); +is( C4::ClassSplitRoutine::LCC::split_callnumber(), "0", 'test when split LCC is null' ); diff --git a/t/Labels_split_Regex.t b/t/Labels_split_Regex.t index b69e03b725..688e18edbc 100755 --- a/t/Labels_split_Regex.t +++ b/t/Labels_split_Regex.t @@ -23,16 +23,16 @@ use C4::ClassSplitRoutine::RegEx qw( split_callnumber ); my $callnumbers = { '830 Han' => [qw{830 Han}], '159.9 (091) Gesh' => [qw{159.9 (091) Gesh}], - 'J 3 Kin =774' => ['J 3', 'Kin', '=774'], + 'J 3 Kin =774' => [ 'J 3', 'Kin', '=774' ], '830 Hil =774 4' => [qw{830 Hil =774 4}], '830 Las=20 4' => [qw{830 Las =20 4}], }; # Split on spaces and before = # If starts with J or K then do not split the first 2 groups -my @regexs = ('s/\s/\n/g', 's/(\s?=)/\n=/g', 's/^(J|K)\n/$1 /'); -foreach my $cn (sort keys %$callnumbers) { - my @parts = C4::ClassSplitRoutine::RegEx::split_callnumber($cn, \@regexs); - my @expected = @{$callnumbers->{$cn}}; - is_deeply(\@parts, \@expected); +my @regexs = ( 's/\s/\n/g', 's/(\s?=)/\n=/g', 's/^(J|K)\n/$1 /' ); +foreach my $cn ( sort keys %$callnumbers ) { + my @parts = C4::ClassSplitRoutine::RegEx::split_callnumber( $cn, \@regexs ); + my @expected = @{ $callnumbers->{$cn} }; + is_deeply( \@parts, \@expected ); } diff --git a/t/Labels_split_ccn.t b/t/Labels_split_ccn.t index c6db3c6681..3fe7f78168 100755 --- a/t/Labels_split_ccn.t +++ b/t/Labels_split_ccn.t @@ -24,21 +24,20 @@ use Test::More; BEGIN { our $ccns = {}; - if ($ARGV[0]) { + if ( $ARGV[0] ) { BAIL_OUT("USAGE: perl Labels_split_ccn.t 'BIO JP2 R5c.1' 'BIO,JP2,R5c.1'") unless $ARGV[1]; - $ccns = {$ARGV[0] => [split (/,/,$ARGV[1])],}; - } - else { + $ccns = { $ARGV[0] => [ split( /,/, $ARGV[1] ) ], }; + } else { $ccns = { - 'BIO JP2 R5c.1' => [qw(BIO JP2 R5 c.1)], - 'FIC GIR J5c.1' => [qw(FIC GIR J5 c.1)], - 'J DAR G7c.11' => [qw( J DAR G7 c.11)], - 'MP3-CD F PARKER' => [qw(MP3-CD F PARKER)], + 'BIO JP2 R5c.1' => [qw(BIO JP2 R5 c.1)], + 'FIC GIR J5c.1' => [qw(FIC GIR J5 c.1)], + 'J DAR G7c.11' => [qw( J DAR G7 c.11)], + 'MP3-CD F PARKER' => [qw(MP3-CD F PARKER)], }; } my $test_num = 1; - foreach (keys(%$ccns)) { - my $split_num = scalar(@{$ccns->{$_}}); + foreach ( keys(%$ccns) ) { + my $split_num = scalar( @{ $ccns->{$_} } ); $test_num += 2 * $split_num; $test_num += 4; } @@ -47,17 +46,17 @@ BEGIN { use vars qw($ccns); } -foreach my $ccn (sort keys %$ccns) { - my (@parts, @expected); - ok($ccn, "ddcn: $ccn"); - ok(@expected = @{$ccns->{$ccn}}, "split expected to produce " . scalar(@expected) . " pieces"); - ok(@parts = C4::ClassSplitRoutine::Generic::split_callnumber($ccn), "split LCC ($ccn)"); - ok(scalar(@expected) == scalar(@parts), sprintf("%d of %d pieces produced", scalar(@parts), scalar(@expected))); +foreach my $ccn ( sort keys %$ccns ) { + my ( @parts, @expected ); + ok( $ccn, "ddcn: $ccn" ); + ok( @expected = @{ $ccns->{$ccn} }, "split expected to produce " . scalar(@expected) . " pieces" ); + ok( @parts = C4::ClassSplitRoutine::Generic::split_callnumber($ccn), "split LCC ($ccn)" ); + ok( scalar(@expected) == scalar(@parts), sprintf( "%d of %d pieces produced", scalar(@parts), scalar(@expected) ) ); my $i = 0; foreach my $unit (@expected) { my $part; - ok($part = $parts[$i], "($ccn)[$i] populated: " . (defined($part) ? $part : 'UNDEF')); - ok((defined($part) and $part eq $unit), "($ccn)[$i] matches: $unit"); + ok( $part = $parts[$i], "($ccn)[$i] populated: " . ( defined($part) ? $part : 'UNDEF' ) ); + ok( ( defined($part) and $part eq $unit ), "($ccn)[$i] matches: $unit" ); $i++; } } diff --git a/t/Labels_split_ddcn.t b/t/Labels_split_ddcn.t index eaf92e8e9c..f7c5dff52c 100755 --- a/t/Labels_split_ddcn.t +++ b/t/Labels_split_ddcn.t @@ -24,11 +24,10 @@ use Test::More; BEGIN { our $ddcns = {}; - if ($ARGV[0]) { + if ( $ARGV[0] ) { BAIL_OUT("USAGE: perl Labels_split_ddcn.t '621.3828 J28l' '621.3828,J28l'") unless $ARGV[1]; - $ddcns = {$ARGV[0] => [split (/,/,$ARGV[1])],}; - } - else { + $ddcns = { $ARGV[0] => [ split( /,/, $ARGV[1] ) ], }; + } else { $ddcns = { 'R220.3 H2793Z H32 c.2' => [qw(R 220.3 H2793Z H32 c.2)], 'CD-ROM 787.87 EAS' => [qw(CD-ROM 787.87 EAS)], @@ -36,28 +35,28 @@ BEGIN { }; } my $test_num = 1; - foreach (keys(%$ddcns)) { - my $split_num = scalar(@{$ddcns->{$_}}); + foreach ( keys(%$ddcns) ) { + my $split_num = scalar( @{ $ddcns->{$_} } ); $test_num += 2 * $split_num; $test_num += 4; } plan tests => $test_num; - use_ok('C4::ClassSplitRoutine::Dewey', qw( split_callnumber )); + use_ok( 'C4::ClassSplitRoutine::Dewey', qw( split_callnumber ) ); use vars qw($ddcns); } -foreach my $ddcn (sort keys %$ddcns) { - my (@parts, @expected); - ok($ddcn, "ddcn: $ddcn"); - ok(@expected = @{$ddcns->{$ddcn}}, "split expected to produce " . scalar(@expected) . " pieces"); - ok(@parts = C4::ClassSplitRoutine::Dewey::split_callnumber($ddcn), "Dewey::split_callnumber($ddcn)"); +foreach my $ddcn ( sort keys %$ddcns ) { + my ( @parts, @expected ); + ok( $ddcn, "ddcn: $ddcn" ); + ok( @expected = @{ $ddcns->{$ddcn} }, "split expected to produce " . scalar(@expected) . " pieces" ); + ok( @parts = C4::ClassSplitRoutine::Dewey::split_callnumber($ddcn), "Dewey::split_callnumber($ddcn)" ); - ok(scalar(@expected) == scalar(@parts), sprintf("%d of %d pieces produced", scalar(@parts), scalar(@expected))); + ok( scalar(@expected) == scalar(@parts), sprintf( "%d of %d pieces produced", scalar(@parts), scalar(@expected) ) ); my $i = 0; foreach my $unit (@expected) { my $part; - ok($part = $parts[$i], "($ddcn)[$i] populated: " . (defined($part) ? $part : 'UNDEF')); - ok((defined($part) and $part eq $unit), "($ddcn)[$i] matches: $unit"); + ok( $part = $parts[$i], "($ddcn)[$i] populated: " . ( defined($part) ? $part : 'UNDEF' ) ); + ok( ( defined($part) and $part eq $unit ), "($ddcn)[$i] matches: $unit" ); $i++; } } diff --git a/t/Labels_split_lccn.t b/t/Labels_split_lccn.t index baca48c134..14332d0a40 100755 --- a/t/Labels_split_lccn.t +++ b/t/Labels_split_lccn.t @@ -25,11 +25,10 @@ use Test::More; BEGIN { our $lccns = {}; - if ($ARGV[0]) { + if ( $ARGV[0] ) { BAIL_OUT("USAGE: perl Labels_split_lccn.t 'HE 8700.7 .P6 T44 1983' 'HE,8700.7,.P6,T44,1983'") unless $ARGV[1]; - $lccns = {$ARGV[0] => [split (/,/,$ARGV[1])],}; - } - else { + $lccns = { $ARGV[0] => [ split( /,/, $ARGV[1] ) ], }; + } else { $lccns = { 'HE8700.7 .P6T44 1983' => [qw(HE 8700.7 .P6 T44 1983)], 'BS2545.E8 H39 1996' => [qw(BS 2545 .E8 H39 1996)], @@ -39,8 +38,8 @@ BEGIN { }; } my $test_num = 1; - foreach (keys(%$lccns)) { - my $split_num = scalar(@{$lccns->{$_}}); + foreach ( keys(%$lccns) ) { + my $split_num = scalar( @{ $lccns->{$_} } ); $test_num += 2 * $split_num; $test_num += 4; } @@ -49,17 +48,17 @@ BEGIN { use vars qw($lccns); } -foreach my $lccn (sort keys %$lccns) { - my (@parts, @expected); - ok($lccn, "lccn: $lccn"); - ok(@expected = @{$lccns->{$lccn}}, "split expected to produce " . scalar(@expected) . " pieces"); - ok(@parts = C4::ClassSplitRoutine::LCC::split_callnumber($lccn), "split LCC ($lccn)"); - ok(scalar(@expected) == scalar(@parts), sprintf("%d of %d pieces produced", scalar(@parts), scalar(@expected))); +foreach my $lccn ( sort keys %$lccns ) { + my ( @parts, @expected ); + ok( $lccn, "lccn: $lccn" ); + ok( @expected = @{ $lccns->{$lccn} }, "split expected to produce " . scalar(@expected) . " pieces" ); + ok( @parts = C4::ClassSplitRoutine::LCC::split_callnumber($lccn), "split LCC ($lccn)" ); + ok( scalar(@expected) == scalar(@parts), sprintf( "%d of %d pieces produced", scalar(@parts), scalar(@expected) ) ); my $i = 0; foreach my $unit (@expected) { my $part; - ok($part = $parts[$i], "($lccn)[$i] populated: " . (defined($part) ? $part : 'UNDEF')); - ok((defined($part) and $part eq $unit), "($lccn)[$i] matches: $unit"); + ok( $part = $parts[$i], "($lccn)[$i] populated: " . ( defined($part) ? $part : 'UNDEF' ) ); + ok( ( defined($part) and $part eq $unit ), "($lccn)[$i] matches: $unit" ); $i++; } } diff --git a/t/Languages.t b/t/Languages.t index 717e1f9615..f8b4defb8e 100755 --- a/t/Languages.t +++ b/t/Languages.t @@ -25,48 +25,48 @@ use Koha::Cache::Memory::Lite; use Koha::Language; BEGIN { - use_ok('C4::Languages', qw( getlanguage )); + use_ok( 'C4::Languages', qw( getlanguage ) ); } -my @languages = (); # stores the list of active languages - # for the syspref mock +my @languages = (); # stores the list of active languages + # for the syspref mock my $return_undef = 0; -my $module_context = Test::MockModule->new('C4::Context'); +my $module_context = Test::MockModule->new('C4::Context'); my $module_languages = Test::MockModule->new('C4::Languages'); $module_context->mock( preference => sub { - my ($self, $pref) = @_; + my ( $self, $pref ) = @_; if ($return_undef) { return; - } elsif ($pref eq 'language' || $pref eq 'OPACLanguages') { + } elsif ( $pref eq 'language' || $pref eq 'OPACLanguages' ) { return join ',', @languages; } else { return 'XXX'; } - }, + }, ); $module_languages->mock( _get_language_dirs => sub { - return @languages + return @languages; } ); delete $ENV{HTTP_ACCEPT_LANGUAGE}; my $query = CGI->new(); -@languages = ('de-DE', 'fr-FR'); -is(C4::Languages::getlanguage($query), 'de-DE', 'default to first language specified in syspref (bug 10560)'); +@languages = ( 'de-DE', 'fr-FR' ); +is( C4::Languages::getlanguage($query), 'de-DE', 'default to first language specified in syspref (bug 10560)' ); Koha::Cache::Memory::Lite->get_instance()->clear_from_cache('getlanguage'); @languages = (); -is(C4::Languages::getlanguage($query), 'en', 'default to English if no language specified in syspref (bug 10560)'); +is( C4::Languages::getlanguage($query), 'en', 'default to English if no language specified in syspref (bug 10560)' ); Koha::Cache::Memory::Lite->get_instance()->clear_from_cache('getlanguage'); $return_undef = 1; -is(C4::Languages::getlanguage($query), 'en', 'default to English if no database'); +is( C4::Languages::getlanguage($query), 'en', 'default to English if no database' ); subtest 'when interface is not intranet or opac' => sub { plan tests => 3; @@ -74,17 +74,17 @@ subtest 'when interface is not intranet or opac' => sub { my $cache = Koha::Cache::Memory::Lite->get_instance; C4::Context->interface('api'); - @languages = ('fr-FR', 'de-DE', 'en'); + @languages = ( 'fr-FR', 'de-DE', 'en' ); $ENV{HTTP_ACCEPT_LANGUAGE} = 'de-DE'; $cache->clear_from_cache('getlanguage'); - is(C4::Languages::getlanguage(), 'de-DE', 'Accept-Language HTTP header is respected'); + is( C4::Languages::getlanguage(), 'de-DE', 'Accept-Language HTTP header is respected' ); Koha::Language->set_requested_language('fr-FR'); $cache->clear_from_cache('getlanguage'); - is(C4::Languages::getlanguage(), 'fr-FR', 'but language requested through Koha::Language is preferred'); + is( C4::Languages::getlanguage(), 'fr-FR', 'but language requested through Koha::Language is preferred' ); @languages = (); $cache->clear_from_cache('getlanguage'); - is(C4::Languages::getlanguage(), 'en', 'fallback to english when no language is available'); + is( C4::Languages::getlanguage(), 'en', 'fallback to english when no language is available' ); }; diff --git a/t/Logger.t b/t/Logger.t index 4281c3b6ff..ce1b9dd23c 100755 --- a/t/Logger.t +++ b/t/Logger.t @@ -30,12 +30,13 @@ subtest 'Test01 -- Simple tests for Koha::Logger' => sub { plan tests => 13; my $ret; - t::lib::Mocks::mock_config('log4perl_conf', undef); + t::lib::Mocks::mock_config( 'log4perl_conf', undef ); throws_ok { Koha::Logger->get } qr/Configuration not defined/, 'Logger did not init correctly without config'; - my $log = mytempfile(); - my $config_file = mytempfile( <<"HERE" + my $log = mytempfile(); + my $config_file = mytempfile( + <<"HERE" log4perl.logger.intranet = WARN, INTRANET log4perl.appender.INTRANET=Log::Log4perl::Appender::File log4perl.appender.INTRANET.filename=$log @@ -45,11 +46,11 @@ log4perl.appender.INTRANET.layout.ConversionPattern=[%d] [%p] %m %l%n HERE ); - t::lib::Mocks::mock_config('log4perl_conf', $config_file); + t::lib::Mocks::mock_config( 'log4perl_conf', $config_file ); my $login = getlogin || getpwuid($<) || q{}; - SKIP: { +SKIP: { skip "Running as root user", 1 if $login eq 'root'; system("chmod 400 $log"); @@ -58,24 +59,24 @@ HERE } my $logger = Koha::Logger->get( { interface => 'intranet' } ); - is( exists $logger->{logger}, 1, 'Log4perl config found'); + is( exists $logger->{logger}, 1, 'Log4perl config found' ); is( $logger->warn('Message 1'), 1, '->warn returned a value' ); warning_is { $ret = $logger->catastrophe } - "ERROR: Unsupported method catastrophe", - "Undefined method raises warning"; - is( $ret, undef, "'catastrophe' method undefined"); + "ERROR: Unsupported method catastrophe", + "Undefined method raises warning"; + is( $ret, undef, "'catastrophe' method undefined" ); Koha::Logger->put_mdc( 'foo', 'bar' ); - is( Koha::Logger->get_mdc( 'foo' ), 'bar', "MDC value via put_mdc is correct" ); + is( Koha::Logger->get_mdc('foo'), 'bar', "MDC value via put_mdc is correct" ); Koha::Logger->put_mdc( 'foo', undef ); - is( Koha::Logger->get_mdc( 'foo' ), undef, "Updated MDC value to undefined via put_mdc is correct" ); + is( Koha::Logger->get_mdc('foo'), undef, "Updated MDC value to undefined via put_mdc is correct" ); Koha::Logger->put_mdc( 'foo', 'baz' ); - is( Koha::Logger->get_mdc( 'foo' ), 'baz', "Updated MDC value via put_mdc is correct" ); + is( Koha::Logger->get_mdc('foo'), 'baz', "Updated MDC value via put_mdc is correct" ); Koha::Logger->clear_mdc(); - is( Koha::Logger->get_mdc( 'foo' ), undef, "MDC value was cleared by clear_mdc" ); + is( Koha::Logger->get_mdc('foo'), undef, "MDC value was cleared by clear_mdc" ); is( Koha::Logger->get( { interface => 'cli', category => 'Test.Category' } )->category(), "cli.Test.Category", @@ -95,7 +96,7 @@ HERE sub mytempfile { my ( $fh, $fn ) = tempfile( SUFFIX => '.logger.test', UNLINK => 1 ); - print $fh $_[0]//''; + print $fh $_[0] // ''; close $fh; return $fn; } diff --git a/t/Makefile.t b/t/Makefile.t index a0cdeab5cc..4a4814de6b 100755 --- a/t/Makefile.t +++ b/t/Makefile.t @@ -41,11 +41,11 @@ my @ignored = qw( ); my @not_mapped; -for my $file (@files ) { +for my $file (@files) { chomp $file; - unless ( grep {/$file/} @MakeFile or grep {/$file/} @ignored ) { + unless ( grep { /$file/ } @MakeFile or grep { /$file/ } @ignored ) { push @not_mapped, $file; } } -is( @not_mapped, 0, 'All directories should be mapped' . (@not_mapped ? ': ' . join ',', @not_mapped : '' ) ); +is( @not_mapped, 0, 'All directories should be mapped' . ( @not_mapped ? ': ' . join ',', @not_mapped : '' ) ); diff --git a/t/Members_Messaging.t b/t/Members_Messaging.t index 93950084c1..112ecf21ba 100755 --- a/t/Members_Messaging.t +++ b/t/Members_Messaging.t @@ -1,6 +1,6 @@ #!/usr/bin/perl # -# This Koha test module is a stub! +# This Koha test module is a stub! # Add more tests here!!! use strict; @@ -9,6 +9,6 @@ use warnings; use Test::More tests => 1; BEGIN { - use_ok('C4::Members::Messaging'); + use_ok('C4::Members::Messaging'); } diff --git a/t/Number/Price.t b/t/Number/Price.t index d881750c17..2bb929f5ce 100755 --- a/t/Number/Price.t +++ b/t/Number/Price.t @@ -16,141 +16,176 @@ $budget_module->mock( 'get_active', sub { return $currency; } ); use_ok('Koha::Number::Price'); my $orig_locale = setlocale(LC_NUMERIC); -my $format = { - p_cs_precedes => 1, # Force to place the symbol at the beginning +my $format = { + p_cs_precedes => 1, # Force to place the symbol at the beginning }; -is( Koha::Number::Price->new->format( $format ), '0.00', 'There is no currency defined yet, do not explode!' ); +is( Koha::Number::Price->new->format($format), '0.00', 'There is no currency defined yet, do not explode!' ); t::lib::Mocks::mock_preference( 'CurrencyFormat', 'US' ); -$currency = Koha::Acquisition::Currency->new({ - currency => 'USD', - symbol => '$', - rate => 1, - active => 1, - p_sep_by_space => 0, # Force to not add a space between the symbol and the number. This is the default behaviour -}); +$currency = Koha::Acquisition::Currency->new( + { + currency => 'USD', + symbol => '$', + rate => 1, + active => 1, + p_sep_by_space => 0, # Force to not add a space between the symbol and the number. This is the default behaviour + } +); -is( Koha::Number::Price->new->format( $format ), '0.00', 'US: format 0' ); -is( Koha::Number::Price->new(3)->format( $format ), '3.00', 'US: format 3' ); -is( Koha::Number::Price->new(1234567890)->format( $format ), - '1,234,567,890.00', 'US: format 1234567890' ); - -is( Koha::Number::Price->new(100000000000000)->format, '100000000000000', 'Numbers too big are not formatted'); -is( Koha::Number::Price->new(-100000000000000)->format, '-100000000000000', 'Negative numbers too big are not formatted'); - -is( Koha::Number::Price->new->format( { %$format, with_symbol => 1 } ), - '$0.00', 'US: format 0 with symbol' ); -is( Koha::Number::Price->new(3)->format( { %$format, with_symbol => 1 } ), - '$3.00', 'US: format 3 with symbol' ); +is( Koha::Number::Price->new->format($format), '0.00', 'US: format 0' ); +is( Koha::Number::Price->new(3)->format($format), '3.00', 'US: format 3' ); is( - Koha::Number::Price->new(1234567890) - ->format( { %$format, with_symbol => 1 }, 'US: format 1234567890 with symbol' ), + Koha::Number::Price->new(1234567890)->format($format), + '1,234,567,890.00', 'US: format 1234567890' +); + +is( Koha::Number::Price->new(100000000000000)->format, '100000000000000', 'Numbers too big are not formatted' ); +is( + Koha::Number::Price->new(-100000000000000)->format, '-100000000000000', + 'Negative numbers too big are not formatted' +); + +is( + Koha::Number::Price->new->format( { %$format, with_symbol => 1 } ), + '$0.00', 'US: format 0 with symbol' +); +is( + Koha::Number::Price->new(3)->format( { %$format, with_symbol => 1 } ), + '$3.00', 'US: format 3 with symbol' +); +is( + Koha::Number::Price->new(1234567890)->format( { %$format, with_symbol => 1 }, 'US: format 1234567890 with symbol' ), '$1,234,567,890.00' ); $currency->p_sep_by_space(1); -is( Koha::Number::Price->new(3)->format( { %$format, with_symbol => 1 } ), - '$ 3.00', 'US: format 3 with symbol and a space' ); +is( + Koha::Number::Price->new(3)->format( { %$format, with_symbol => 1 } ), + '$ 3.00', 'US: format 3 with symbol and a space' +); is( Koha::Number::Price->new->unformat, '0', 'US: unformat 0' ); is( Koha::Number::Price->new(3)->unformat, '3', 'US: unformat 3' ); -is( Koha::Number::Price->new(1234567890)->unformat, - '1234567890', 'US: unformat 1234567890' ); +is( + Koha::Number::Price->new(1234567890)->unformat, + '1234567890', 'US: unformat 1234567890' +); SKIP: { # Bug 18900 - Check params are not from system environement - setlocale(LC_NUMERIC, "fr_FR.UTF-8"); + setlocale( LC_NUMERIC, "fr_FR.UTF-8" ); my $current_locale = setlocale(LC_NUMERIC); skip "fr_FR.UTF-8 locale required for tests and missing", 2 unless $current_locale eq 'fr_FR.UTF-8'; - is( Koha::Number::Price->new(12345678.9)->format( { %$format, with_symbol => 1 } ), - '$ 12,345,678.90', 'US: format 12,345,678.90 with symbol' ); - is( Koha::Number::Price->new('12,345,678.90')->unformat, - '12345678.9', 'US: unformat 12345678.9' ); - setlocale(LC_NUMERIC, $orig_locale); + is( + Koha::Number::Price->new(12345678.9)->format( { %$format, with_symbol => 1 } ), + '$ 12,345,678.90', 'US: format 12,345,678.90 with symbol' + ); + is( + Koha::Number::Price->new('12,345,678.90')->unformat, + '12345678.9', 'US: unformat 12345678.9' + ); + setlocale( LC_NUMERIC, $orig_locale ); } t::lib::Mocks::mock_preference( 'CurrencyFormat', 'FR' ); -$currency = Koha::Acquisition::Currency->new({ - currency => 'EUR', - symbol => '€', - rate => 1, - active => 1, -}); +$currency = Koha::Acquisition::Currency->new( + { + currency => 'EUR', + symbol => '€', + rate => 1, + active => 1, + } +); # Actually,the price formating for France is 3,00€ # How put the symbol at the end with Number::Format? -is( Koha::Number::Price->new->format( $format ), '0,00', 'FR: format 0' ); -is( Koha::Number::Price->new(3)->format( $format ), '3,00', 'FR: format 3' ); +is( Koha::Number::Price->new->format($format), '0,00', 'FR: format 0' ); +is( Koha::Number::Price->new(3)->format($format), '3,00', 'FR: format 3' ); is( - Koha::Number::Price->new(1234567890)->format( $format ), + Koha::Number::Price->new(1234567890)->format($format), '1 234 567 890,00', 'FR: format 1234567890' ); -is( Koha::Number::Price->new->format( { %$format, with_symbol => 1 } ), - '€0,00', 'FR: format 0 with symbol' ); -is( Koha::Number::Price->new(3)->format( { %$format, with_symbol => 1 } ), - '€3,00', 'FR: format 3 with symbol' ); is( - Koha::Number::Price->new(1234567890) - ->format( { %$format, with_symbol => 1 }, 'FR: format 123567890 with symbol' ), + Koha::Number::Price->new->format( { %$format, with_symbol => 1 } ), + '€0,00', 'FR: format 0 with symbol' +); +is( + Koha::Number::Price->new(3)->format( { %$format, with_symbol => 1 } ), + '€3,00', 'FR: format 3 with symbol' +); +is( + Koha::Number::Price->new(1234567890)->format( { %$format, with_symbol => 1 }, 'FR: format 123567890 with symbol' ), '€1 234 567 890,00' ); is( Koha::Number::Price->new->unformat, '0', 'FR: unformat 0' ); is( Koha::Number::Price->new(3)->unformat, '3', 'FR: unformat 3' ); -is( Koha::Number::Price->new(1234567890)->unformat, - '1234567890', 'FR: unformat 1234567890' ); +is( + Koha::Number::Price->new(1234567890)->unformat, + '1234567890', 'FR: unformat 1234567890' +); # Price formatting for Switzerland: 1'234'567.89 t::lib::Mocks::mock_preference( 'CurrencyFormat', 'CH' ); -$currency = Koha::Acquisition::Currency->new({ - currency => 'nnn', - symbol => 'CHF', - rate => 1, - active => 1, -}); +$currency = Koha::Acquisition::Currency->new( + { + currency => 'nnn', + symbol => 'CHF', + rate => 1, + active => 1, + } +); -is( Koha::Number::Price->new->format( $format ), '0.00', 'CH: format 0' ); -is( Koha::Number::Price->new(3)->format( $format ), '3.00', 'CH: format 3' ); +is( Koha::Number::Price->new->format($format), '0.00', 'CH: format 0' ); +is( Koha::Number::Price->new(3)->format($format), '3.00', 'CH: format 3' ); is( - Koha::Number::Price->new(1234567890)->format( $format ), + Koha::Number::Price->new(1234567890)->format($format), '1\'234\'567\'890.00', 'CHF: format 1234567890' ); -is( Koha::Number::Price->new->format( { %$format, with_symbol => 1 } ), - 'CHF0.00', 'CH: format 0 with symbol' ); -is( Koha::Number::Price->new(3)->format( { %$format, with_symbol => 1 } ), - 'CHF3.00', 'CH: format 3 with symbol' ); is( - Koha::Number::Price->new(1234567890) - ->format( { %$format, with_symbol => 1 }, 'CH: format 123567890 with symbol' ), + Koha::Number::Price->new->format( { %$format, with_symbol => 1 } ), + 'CHF0.00', 'CH: format 0 with symbol' +); +is( + Koha::Number::Price->new(3)->format( { %$format, with_symbol => 1 } ), + 'CHF3.00', 'CH: format 3 with symbol' +); +is( + Koha::Number::Price->new(1234567890)->format( { %$format, with_symbol => 1 }, 'CH: format 123567890 with symbol' ), 'CHF1\'234\'567\'890.00' ); is( Koha::Number::Price->new->unformat, '0', 'CHF: unformat 0' ); is( Koha::Number::Price->new(3)->unformat, '3', 'CHF: unformat 3' ); -is( Koha::Number::Price->new(1234567890)->unformat, - '1234567890', 'CHF: unformat 1234567890' ); +is( + Koha::Number::Price->new(1234567890)->unformat, + '1234567890', 'CHF: unformat 1234567890' +); # Rounding is( Koha::Number::Price->new(17.955)->round, '17.96', 'Round 17.955' ); -subtest 'Changes for format' => sub { # See also bug 18736 +subtest 'Changes for format' => sub { # See also bug 18736 plan tests => 3; t::lib::Mocks::mock_preference( 'CurrencyFormat', 'US' ); is( Koha::Number::Price->new(-2.125)->format, "-2.13", "Check negative value" ); - my $large_number = 2**53; # MAX_INT - my $price = Koha::Number::Price->new($large_number); - is( $price->format, $price->value, 'Format '.$price->value.' returns value' ); - like( Koha::Number::Price->new( 2**53/100 )->format, - qr/\d\.\d{2}$/, 'This price still seems to be formatted' ); - # Note that the comparison with MAX_INT is already subject to rounding + my $large_number = 2**53; # MAX_INT + my $price = Koha::Number::Price->new($large_number); + is( $price->format, $price->value, 'Format ' . $price->value . ' returns value' ); + like( + Koha::Number::Price->new( 2**53 / 100 )->format, + qr/\d\.\d{2}$/, 'This price still seems to be formatted' + ); + + # Note that the comparison with MAX_INT is already subject to rounding }; subtest 'Changes for default currency symbol position' => sub { diff --git a/t/OpenLibrarySearch.t b/t/OpenLibrarySearch.t index b0865e618b..a9cfc5458a 100755 --- a/t/OpenLibrarySearch.t +++ b/t/OpenLibrarySearch.t @@ -21,7 +21,7 @@ use Modern::Perl; use Test::More tests => 1; use LWP::Simple; use JSON; -my $content = get("https://openlibrary.org/search.json?q=9780201038095"); +my $content = get("https://openlibrary.org/search.json?q=9780201038095"); SKIP: { skip "json has not been retrieved from openlibrary.org", 1 unless defined $content; diff --git a/t/Output.t b/t/Output.t index 55ca2dc436..88af19c0c8 100755 --- a/t/Output.t +++ b/t/Output.t @@ -22,14 +22,14 @@ use Test::Warn; use Test::MockModule; use File::Temp qw/tempfile/; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Auth qw( get_template_and_user ); use t::lib::Mocks; BEGIN { - use_ok('C4::Output', qw( output_html_with_http_headers output_and_exit_if_error parametrized_url )); + use_ok( 'C4::Output', qw( output_html_with_http_headers output_and_exit_if_error parametrized_url ) ); } our $output_module = Test::MockModule->new('C4::Output'); @@ -43,26 +43,28 @@ my $output = 'foobarbaz'; my $stdout; open STDOUT, '>', \$stdout; output_html_with_http_headers $query, $cookie, $output, undef, { force_no_caching => 1 }; - like($stdout, qr/Cache-control: no-cache, no-store, max-age=0/, 'force_no_caching sets Cache-control as desired'); - like($stdout, qr/Expires: /, 'force_no_caching sets an Expires header'); + like( $stdout, qr/Cache-control: no-cache, no-store, max-age=0/, 'force_no_caching sets Cache-control as desired' ); + like( $stdout, qr/Expires: /, 'force_no_caching sets an Expires header' ); $stdout = ''; close STDOUT; open STDOUT, '>', \$stdout; output_html_with_http_headers $query, $cookie, $output, undef, undef; - like($stdout, qr/Cache-control: no-cache[^,]/, 'not using force_no_caching sets Cache-control as desired'); - unlike($stdout, qr/Expires: /, 'force_no_caching does not set an Expires header'); + like( $stdout, qr/Cache-control: no-cache[^,]/, 'not using force_no_caching sets Cache-control as desired' ); + unlike( $stdout, qr/Expires: /, 'force_no_caching does not set an Expires header' ); } subtest 'parametrized_url' => sub { plan tests => 2; - my $url = 'https://somesite.com/search?q={TITLE}&author={AUTHOR}{SUFFIX}'; + my $url = 'https://somesite.com/search?q={TITLE}&author={AUTHOR}{SUFFIX}'; my $subs = { TITLE => '_title_', AUTHOR => undef, ISBN => '123456789' }; my $res; warning_is { $res = C4::Output::parametrized_url( $url, $subs ) } - q{}, 'No warning expected on undefined author'; - is( $res, 'https://somesite.com/search?q=_title_&author=', - 'Title replaced, author empty and SUFFIX removed' ); + q{}, 'No warning expected on undefined author'; + is( + $res, 'https://somesite.com/search?q=_title_&author=', + 'Title replaced, author empty and SUFFIX removed' + ); }; subtest 'output_with_http_headers() tests' => sub { @@ -77,27 +79,30 @@ subtest 'output_with_http_headers() tests' => sub { my $output = 'foobarbaz'; open STDOUT, '>', \$stdout; - t::lib::Mocks::mock_preference('AccessControlAllowOrigin',''); + t::lib::Mocks::mock_preference( 'AccessControlAllowOrigin', '' ); output_html_with_http_headers $query, $cookie, $output, undef; - unlike($stdout, qr/Access-control-allow-origin/, 'No header set if no value on syspref'); + unlike( $stdout, qr/Access-control-allow-origin/, 'No header set if no value on syspref' ); close STDOUT; open STDOUT, '>', \$stdout; - t::lib::Mocks::mock_preference('AccessControlAllowOrigin',undef); + t::lib::Mocks::mock_preference( 'AccessControlAllowOrigin', undef ); output_html_with_http_headers $query, $cookie, $output, undef; - unlike($stdout, qr/Access-control-allow-origin/, 'No header set if no value on syspref'); + unlike( $stdout, qr/Access-control-allow-origin/, 'No header set if no value on syspref' ); close STDOUT; open STDOUT, '>', \$stdout; - t::lib::Mocks::mock_preference('AccessControlAllowOrigin','*'); + t::lib::Mocks::mock_preference( 'AccessControlAllowOrigin', '*' ); output_html_with_http_headers $query, $cookie, $output, undef; - like($stdout, qr/Access-control-allow-origin: \*/, 'Header set to *'); + like( $stdout, qr/Access-control-allow-origin: \*/, 'Header set to *' ); close STDOUT; open STDOUT, '>', \$stdout; - t::lib::Mocks::mock_preference('AccessControlAllowOrigin','https://koha-community.org'); + t::lib::Mocks::mock_preference( 'AccessControlAllowOrigin', 'https://koha-community.org' ); output_html_with_http_headers $query, $cookie, $output, undef; - like($stdout, qr/Access-control-allow-origin: https:\/\/koha-community\.org/, 'Header set to https://koha-community.org'); + like( + $stdout, qr/Access-control-allow-origin: https:\/\/koha-community\.org/, + 'Header set to https://koha-community.org' + ); close STDOUT; }; @@ -112,13 +117,13 @@ subtest 'output_and_exit_if_error() tests' => sub { } ); - t::lib::Mocks::mock_config( 'pluginsdir', [ C4::Context::temporary_directory ] ); + t::lib::Mocks::mock_config( 'pluginsdir', [C4::Context::temporary_directory] ); my ( $fh, $fn ) = tempfile( SUFFIX => '.tt', UNLINK => 1, DIR => C4::Context::temporary_directory ); print $fh qq|[% blocking_error %]|; close $fh; my $query = CGI->new(); - $query->param('csrf_token',''); + $query->param( 'csrf_token', '' ); my ( $template, $loggedinuser, $cookies ) = get_template_and_user( { template_name => $fn, @@ -127,6 +132,7 @@ subtest 'output_and_exit_if_error() tests' => sub { authnotrequired => 1, } ); + # Next call triggers test in the mocked sub - output_and_exit_if_error($query, $cookie, $template, { check => 'csrf_token' }); + output_and_exit_if_error( $query, $cookie, $template, { check => 'csrf_token' } ); }; diff --git a/t/Output_JSONStream.t b/t/Output_JSONStream.t index bf7b1842c1..88d27891e9 100755 --- a/t/Output_JSONStream.t +++ b/t/Output_JSONStream.t @@ -1,6 +1,6 @@ #!/usr/bin/perl # -# This Koha test module is a stub! +# This Koha test module is a stub! # Add more tests here!!! use strict; @@ -9,24 +9,24 @@ use warnings; use Test::More tests => 10; BEGIN { - use_ok('C4::Output::JSONStream'); + use_ok('C4::Output::JSONStream'); } my $json = C4::Output::JSONStream->new; -is($json->output,'{}',"Making sure JSON output is blank just after its created."); +is( $json->output, '{}', "Making sure JSON output is blank just after its created." ); $json->param( issues => [ 'yes!', 'please', 'no' ] ); -is($json->output,'{"issues":["yes!","please","no"]}',"Making sure JSON output has added what we told it to."); +is( $json->output, '{"issues":["yes!","please","no"]}', "Making sure JSON output has added what we told it to." ); $json->param( stuff => ['realia'] ); -like($json->output,'/"stuff":\["realia"\]/',"Making sure JSON output has added more params correctly."); -like($json->output,'/"issues":\["yes!","please","no"\]/',"Making sure existing elements remain in JSON output"); -$json->param( stuff => ['fun','love'] ); -like($json->output,'/"stuff":\["fun","love"\]/',"Making sure JSON output can overwrite params."); -like($json->output,'/"issues":\["yes!","please","no"\]/',"Making non overwitten elements remain in JSON output"); +like( $json->output, '/"stuff":\["realia"\]/', "Making sure JSON output has added more params correctly." ); +like( $json->output, '/"issues":\["yes!","please","no"\]/', "Making sure existing elements remain in JSON output" ); +$json->param( stuff => [ 'fun', 'love' ] ); +like( $json->output, '/"stuff":\["fun","love"\]/', "Making sure JSON output can overwrite params." ); +like( $json->output, '/"issues":\["yes!","please","no"\]/', "Making non overwitten elements remain in JSON output" ); -eval{$json->param( die )}; -ok($@,'Dies'); +eval { $json->param(die) }; +ok( $@, 'Dies' ); -eval{$json->param( die => ['yes','sure','now'])}; -ok(!$@,'Does not die.'); -eval{$json->param( die => ['yes','sure','now'], die2 =>)}; -ok($@,'Dies.'); +eval { $json->param( die => [ 'yes', 'sure', 'now' ] ) }; +ok( !$@, 'Does not die.' ); +eval { $json->param( die => [ 'yes', 'sure', 'now' ], die2 => ) }; +ok( $@, 'Dies.' ); diff --git a/t/Patroncards.t b/t/Patroncards.t index 60a7237fd8..ac89c8f7d9 100755 --- a/t/Patroncards.t +++ b/t/Patroncards.t @@ -1,6 +1,6 @@ #!/usr/bin/perl # -# This Koha test module is a stub! +# This Koha test module is a stub! # Add more tests here!!! use strict; @@ -9,6 +9,6 @@ use warnings; use Test::More tests => 1; BEGIN { - use_ok('C4::Patroncards'); + use_ok('C4::Patroncards'); } diff --git a/t/Patroncards_Batch.t b/t/Patroncards_Batch.t index a0743ff8d9..fe052e0931 100755 --- a/t/Patroncards_Batch.t +++ b/t/Patroncards_Batch.t @@ -1,6 +1,6 @@ #!/usr/bin/perl # -# This Koha test module is a stub! +# This Koha test module is a stub! # Add more tests here!!! use strict; @@ -9,6 +9,6 @@ use warnings; use Test::More tests => 1; BEGIN { - use_ok('C4::Patroncards::Batch'); + use_ok('C4::Patroncards::Batch'); } diff --git a/t/Patroncards_Lib.t b/t/Patroncards_Lib.t index 88154a6425..1730ac78bf 100755 --- a/t/Patroncards_Lib.t +++ b/t/Patroncards_Lib.t @@ -1,6 +1,6 @@ #!/usr/bin/perl # -# This Koha test module is a stub! +# This Koha test module is a stub! # Add more tests here!!! use strict; @@ -9,6 +9,6 @@ use warnings; use Test::More tests => 1; BEGIN { - use_ok('C4::Patroncards::Lib'); + use_ok('C4::Patroncards::Lib'); } diff --git a/t/Patroncards_Patroncard.t b/t/Patroncards_Patroncard.t index 8868350fb1..2dd35e73a0 100755 --- a/t/Patroncards_Patroncard.t +++ b/t/Patroncards_Patroncard.t @@ -1,6 +1,6 @@ #!/usr/bin/perl # -# This Koha test module is a stub! +# This Koha test module is a stub! # Add more tests here!!! use strict; @@ -9,6 +9,6 @@ use warnings; use Test::More tests => 1; BEGIN { - use_ok('C4::Patroncards::Patroncard'); + use_ok('C4::Patroncards::Patroncard'); } diff --git a/t/Patroncards_Profile.t b/t/Patroncards_Profile.t index 78cb6cfa7c..2a5d8aa817 100755 --- a/t/Patroncards_Profile.t +++ b/t/Patroncards_Profile.t @@ -1,6 +1,6 @@ #!/usr/bin/perl # -# This Koha test module is a stub! +# This Koha test module is a stub! # Add more tests here!!! use strict; @@ -9,6 +9,6 @@ use warnings; use Test::More tests => 1; BEGIN { - use_ok('C4::Patroncards::Profile'); + use_ok('C4::Patroncards::Profile'); } diff --git a/t/Patroncards_Template.t b/t/Patroncards_Template.t index a781e0c3cc..8c5f89669a 100755 --- a/t/Patroncards_Template.t +++ b/t/Patroncards_Template.t @@ -1,6 +1,6 @@ #!/usr/bin/perl # -# This Koha test module is a stub! +# This Koha test module is a stub! # Add more tests here!!! use strict; @@ -9,6 +9,6 @@ use warnings; use Test::More tests => 1; BEGIN { - use_ok('C4::Patroncards::Template'); + use_ok('C4::Patroncards::Template'); } diff --git a/t/RecordProcessor.t b/t/RecordProcessor.t index eef01d42cd..89a3e31909 100755 --- a/t/RecordProcessor.t +++ b/t/RecordProcessor.t @@ -57,28 +57,38 @@ foreach my $filter (@installed_filters) { } my $marc_filters = grep { /MARC/sm } @available_filters; -is( scalar Koha::RecordProcessor::AvailableFilters('MARC'), - $marc_filters, 'Retrieved list of MARC filters' ); +is( + scalar Koha::RecordProcessor::AvailableFilters('MARC'), + $marc_filters, 'Retrieved list of MARC filters' +); my $processor = - Koha::RecordProcessor->new( { filters => ('ABCD::EFGH::IJKL') } ); + Koha::RecordProcessor->new( { filters => ('ABCD::EFGH::IJKL') } ); -is( ref($processor), 'Koha::RecordProcessor', - 'Created record processor with invalid filter' ); +is( + ref($processor), 'Koha::RecordProcessor', + 'Created record processor with invalid filter' +); -is( $processor->process($marc_record), - $marc_record, 'Process record with empty processor' ); +is( + $processor->process($marc_record), + $marc_record, 'Process record with empty processor' +); $processor = Koha::RecordProcessor->new( { filters => ('Null') } ); -is( ref( $processor->filters->[0] ), +is( + ref( $processor->filters->[0] ), 'Koha::Filter::MARC::Null', - 'Created record processor with implicitly scoped Null filter' ); + 'Created record processor with implicitly scoped Null filter' +); $processor = - Koha::RecordProcessor->new( { filters => ('Koha::Filter::MARC::Null') } ); -is( ref( $processor->filters->[0] ), + Koha::RecordProcessor->new( { filters => ('Koha::Filter::MARC::Null') } ); +is( + ref( $processor->filters->[0] ), 'Koha::Filter::MARC::Null', - 'Created record processor with explicitly scoped Null filter' ); + 'Created record processor with explicitly scoped Null filter' +); is( $processor->process($marc_record), $marc_record, 'Process record' ); @@ -90,7 +100,7 @@ is( $processor->process(), $marc_record, 'Filter bound record' ); my $destroy_test = eval { $processor = - Koha::RecordProcessor->new( { filters => ('Koha::Filter::MARC::Null') } ); + Koha::RecordProcessor->new( { filters => ('Koha::Filter::MARC::Null') } ); undef $processor; return 1; }; @@ -105,23 +115,26 @@ subtest 'new() tests' => sub { # Create a processor with a valid filter $record_processor = Koha::RecordProcessor->new( { filters => 'Null' } ); - is( ref($record_processor), 'Koha::RecordProcessor', 'Processor created' ); - is( scalar @{ $record_processor->filters }, 1, 'One filter initialized' ); - is( ref( $record_processor->filters->[0] ), - 'Koha::Filter::MARC::Null', 'Correct filter initialized' ); + is( ref($record_processor), 'Koha::RecordProcessor', 'Processor created' ); + is( scalar @{ $record_processor->filters }, 1, 'One filter initialized' ); + is( + ref( $record_processor->filters->[0] ), + 'Koha::Filter::MARC::Null', 'Correct filter initialized' + ); # Create a processor with an invalid filter $record_processor = Koha::RecordProcessor->new( { filters => 'Dummy' } ); - is( ref($record_processor), 'Koha::RecordProcessor', 'Processor created' ); - is( scalar @{ $record_processor->filters }, 0, 'No filter initialized' ); - is( ref( $record_processor->filters->[0] ), - q{}, 'Make sure no filter initialized' ); + is( ref($record_processor), 'Koha::RecordProcessor', 'Processor created' ); + is( scalar @{ $record_processor->filters }, 0, 'No filter initialized' ); + is( + ref( $record_processor->filters->[0] ), + q{}, 'Make sure no filter initialized' + ); # Create a processor with two valid filters - $record_processor = Koha::RecordProcessor->new( - { filters => [ 'Null', 'EmbedSeeFromHeadings' ] } ); - is( ref($record_processor), 'Koha::RecordProcessor', 'Processor created' ); - is( scalar @{ $record_processor->filters }, 2, 'Two filters initialized' ); + $record_processor = Koha::RecordProcessor->new( { filters => [ 'Null', 'EmbedSeeFromHeadings' ] } ); + is( ref($record_processor), 'Koha::RecordProcessor', 'Processor created' ); + is( scalar @{ $record_processor->filters }, 2, 'Two filters initialized' ); is( ref( $record_processor->filters->[0] ), 'Koha::Filter::MARC::Null', @@ -140,10 +153,12 @@ subtest 'new() tests' => sub { options => { 'test' => 'true' } }; $record_processor = Koha::RecordProcessor->new($parameters); - is( ref($record_processor), 'Koha::RecordProcessor', 'Processor created' ); - is( scalar @{ $record_processor->filters }, 1, 'Invalid filter skipped' ); - is( ref( $record_processor->filters->[0] ), - 'Koha::Filter::MARC::Null', 'Correct filter initialized' ); + is( ref($record_processor), 'Koha::RecordProcessor', 'Processor created' ); + is( scalar @{ $record_processor->filters }, 1, 'Invalid filter skipped' ); + is( + ref( $record_processor->filters->[0] ), + 'Koha::Filter::MARC::Null', 'Correct filter initialized' + ); my $filter_params = $record_processor->filters->[0]->params; is_deeply( $filter_params, $parameters, 'Initialization parameters' ); @@ -156,17 +171,15 @@ subtest 'options() tests' => sub { # Create a processor with some options my $record_processor = Koha::RecordProcessor->new( { - filters => ['EmbedSeeFromHeadings','Null'], - options => { - dummy => 'something' - } + filters => [ 'EmbedSeeFromHeadings', 'Null' ], + options => { dummy => 'something' } } ); my $filter = $record_processor->filters->[0]; is( - ref( $filter ), + ref($filter), 'Koha::Filter::MARC::EmbedSeeFromHeadings', 'Correct second filter initialized' ); @@ -178,11 +191,7 @@ subtest 'options() tests' => sub { ); # Update the chosen options - my $ret = $record_processor->options( - { - dummy => 'something else' - } - ); + my $ret = $record_processor->options( { dummy => 'something else' } ); is( ref($ret), 'Koha::RecordProcessor', 'The setter return the object for chaining calls' ); is_deeply( $record_processor->options, { dummy => 'something else' }, 'The getter works as expected' ); @@ -191,7 +200,7 @@ subtest 'options() tests' => sub { $filter = $record_processor->filters->[0]; is( - ref( $filter ), + ref($filter), 'Koha::Filter::MARC::EmbedSeeFromHeadings', 'Correct second filter initialized' ); diff --git a/t/Ris.t b/t/Ris.t index c11b1f59b5..91bfb23879 100755 --- a/t/Ris.t +++ b/t/Ris.t @@ -1,6 +1,6 @@ #!/usr/bin/perl # -# This Koha test module is a stub! +# This Koha test module is a stub! # Add more tests here!!! use Modern::Perl; @@ -11,9 +11,9 @@ use Test::More tests => 4; BEGIN { use_ok('C4::Ris'); } -t::lib::Mocks::mock_preference('marcflavour', 'MARC21'); -is(C4::Ris::print_typetag(),undef,'test printing typetag'); +t::lib::Mocks::mock_preference( 'marcflavour', 'MARC21' ); +is( C4::Ris::print_typetag(), undef, 'test printing typetag' ); -is(C4::Ris::print_title(),undef, 'test printing title when print_title is nil'); +is( C4::Ris::print_title(), undef, 'test printing title when print_title is nil' ); -is(C4::Ris::print_stitle(),undef, 'test printing info from series title field when its nil'); +is( C4::Ris::print_stitle(), undef, 'test printing info from series title field when its nil' ); diff --git a/t/SIP/Sip.t b/t/SIP/Sip.t index 1dc7ed1684..8130d2fa07 100755 --- a/t/SIP/Sip.t +++ b/t/SIP/Sip.t @@ -21,37 +21,37 @@ use Test::More tests => 9; use Test::Warn; BEGIN { - use_ok('C4::SIP::Sip', qw( timestamp )); + use_ok( 'C4::SIP::Sip', qw( timestamp ) ); } my $date_time = C4::SIP::Sip::timestamp(); -like( $date_time, qr/^\d{8} \d{6}$/, 'Timestamp format no param'); +like( $date_time, qr/^\d{8} \d{6}$/, 'Timestamp format no param' ); my $t = time(); $date_time = C4::SIP::Sip::timestamp($t); -like( $date_time, qr/^\d{8} \d{6}$/, 'Timestamp format secs'); +like( $date_time, qr/^\d{8} \d{6}$/, 'Timestamp format secs' ); $date_time = C4::SIP::Sip::timestamp('2011-01-12'); -ok( $date_time eq '20110112 235900', 'Timestamp iso date string'); +ok( $date_time eq '20110112 235900', 'Timestamp iso date string' ); -my $myChecksum = C4::SIP::Sip::Checksum::checksum("12345"); -my $checker = 65281; +my $myChecksum = C4::SIP::Sip::Checksum::checksum("12345"); +my $checker = 65281; my $stringChecksum = C4::SIP::Sip::Checksum::checksum("teststring"); -my $stringChecker = 64425; +my $stringChecker = 64425; -is( $myChecksum, $checker, "Checksum: $myChecksum matches expected output"); -is( $stringChecksum, $stringChecker, "Checksum: $stringChecksum matches expected output"); +is( $myChecksum, $checker, "Checksum: $myChecksum matches expected output" ); +is( $stringChecksum, $stringChecker, "Checksum: $stringChecksum matches expected output" ); -my $testdata = "abcdAZ"; +my $testdata = "abcdAZ"; my $something = C4::SIP::Sip::Checksum::checksum($testdata); -$something = sprintf("%4X", $something); -ok( C4::SIP::Sip::Checksum::verify_cksum($testdata.$something), "Checksum: $something is valid."); +$something = sprintf( "%4X", $something ); +ok( C4::SIP::Sip::Checksum::verify_cksum( $testdata . $something ), "Checksum: $something is valid." ); my $invalidTest; warning_is { $invalidTest = C4::SIP::Sip::Checksum::verify_cksum("1234567") } - 'verify_cksum: no sum detected', - 'verify_cksum prints the expected warning for an invalid checksum'; -is($invalidTest, 0, "Checksum: 1234567 is invalid as expected"); +'verify_cksum: no sum detected', + 'verify_cksum prints the expected warning for an invalid checksum'; +is( $invalidTest, 0, "Checksum: 1234567 is invalid as expected" ); diff --git a/t/Scheduler.t b/t/Scheduler.t index 520b6b326f..1b861357a0 100755 --- a/t/Scheduler.t +++ b/t/Scheduler.t @@ -1,6 +1,6 @@ #!/usr/bin/perl # -# This Koha test module is a stub! +# This Koha test module is a stub! # Add more tests here!!! use strict; @@ -9,11 +9,11 @@ use warnings; use Test::More tests => 6; BEGIN { - use_ok('C4::Scheduler', qw( get_jobs get_at_jobs get_at_job add_at_job remove_at_job )); + use_ok( 'C4::Scheduler', qw( get_jobs get_at_jobs get_at_job add_at_job remove_at_job ) ); } -ok(C4::Scheduler::get_jobs(), "testing get_jobs with no arguments"); -ok(C4::Scheduler::get_at_jobs(), "testing get_at_jobs with no arguments"); -is(C4::Scheduler::get_at_job(), "0", "testing get_at_job returns '0' when given no arguments"); -is(C4::Scheduler::add_at_job(), "", "testing add_at_job with no arguments"); -is(C4::Scheduler::remove_at_job(), undef , "testing remove_at_job returns undef when given no arguments"); +ok( C4::Scheduler::get_jobs(), "testing get_jobs with no arguments" ); +ok( C4::Scheduler::get_at_jobs(), "testing get_at_jobs with no arguments" ); +is( C4::Scheduler::get_at_job(), "0", "testing get_at_job returns '0' when given no arguments" ); +is( C4::Scheduler::add_at_job(), "", "testing add_at_job with no arguments" ); +is( C4::Scheduler::remove_at_job(), undef, "testing remove_at_job returns undef when given no arguments" ); diff --git a/t/Scrubber.t b/t/Scrubber.t index e04fd2e0d9..7ce4759724 100755 --- a/t/Scrubber.t +++ b/t/Scrubber.t @@ -13,17 +13,17 @@ BEGIN { } sub pretty_line { - my $max = 54; - (@_) or return "#" x $max . "\n"; - my $phrase = " " . shift() . " "; - my $half = "#" x (($max - length($phrase))/2); - return $half . $phrase . $half . "\n"; + my $max = 54; + (@_) or return "#" x $max . "\n"; + my $phrase = " " . shift() . " "; + my $half = "#" x ( ( $max - length($phrase) ) / 2 ); + return $half . $phrase . $half . "\n"; } -my ($scrubber,$html,$result,@types,$collapse); +my ( $scrubber, $html, $result, @types, $collapse ); $collapse = 1; -@types = qw(default comment tag staff); -$html = q| +@types = qw(default comment tag staff); +$html = q|
            @@ -45,38 +45,38 @@ $html = q| At the end here, I actually have some regular text. |; -ok($scrubber = C4::Scrubber->new(), "Constructor: C4::Scrubber->new()"); +ok( $scrubber = C4::Scrubber->new(), "Constructor: C4::Scrubber->new()" ); -isa_ok($scrubber, 'HTML::Scrubber', 'Constructor returns HTML::Scrubber object'); +isa_ok( $scrubber, 'HTML::Scrubber', 'Constructor returns HTML::Scrubber object' ); warning_like { $scrubber->default() } '', "\$scrubber->default ran without fault."; warning_like { $scrubber->comment() } '', "\$scrubber->comment ran without fault."; warning_like { $scrubber->process() } '', "\$scrubber->process ran without fault."; -ok($result = $scrubber->scrub($html), "Getting scrubbed text (type: [default])"); +ok( $result = $scrubber->scrub($html), "Getting scrubbed text (type: [default])" ); -foreach(@types) { - ok($scrubber = C4::Scrubber->new($_), "testing Constructor: C4::Scrubber->new($_)"); +foreach (@types) { + ok( $scrubber = C4::Scrubber->new($_), "testing Constructor: C4::Scrubber->new($_)" ); - warning_like { $scrubber->default() } '', "\$scrubber->default ran without fault."; - warning_like { $scrubber->comment() } '', "\$scrubber->comment ran without fault."; - warning_like { $scrubber->process() } '', "\$scrubber->process ran without fault."; + warning_like { $scrubber->default() } '', "\$scrubber->default ran without fault."; + warning_like { $scrubber->comment() } '', "\$scrubber->comment ran without fault."; + warning_like { $scrubber->process() } '', "\$scrubber->process ran without fault."; - ok($result = $scrubber->scrub($html), "Getting scrubbed text (type: $_)"); + ok( $result = $scrubber->scrub($html), "Getting scrubbed text (type: $_)" ); } #Test for invalid new entry -eval{ - C4::Scrubber->new(""); - fail("test should fail on entry of ''"); +eval { + C4::Scrubber->new(""); + fail("test should fail on entry of ''"); }; if ($@) { pass("Test should have failed on entry of '' (empty string) and it did. YAY!"); } -eval{ - C4::Scrubber->new("Client"); - fail("test should fail on entry of 'Client'"); +eval { + C4::Scrubber->new("Client"); + fail("test should fail on entry of 'Client'"); }; if ($@) { pass("Test should have failed on entry of 'Client' and it did. YAY!"); diff --git a/t/Search.t b/t/Search.t index e32fc85595..048a5ac0a9 100755 --- a/t/Search.t +++ b/t/Search.t @@ -28,7 +28,8 @@ subtest "_build_initial_query tests" => sub { plan tests => 20; - my ($query,$query_cgi,$query_desc,$previous_operand); + my ( $query, $query_cgi, $query_desc, $previous_operand ); + # all params have values my $params = { query => "query", @@ -43,16 +44,23 @@ subtest "_build_initial_query tests" => sub { previous_operand => "previous_operand" }; - ($query,$query_cgi,$query_desc,$previous_operand) = - C4::Search::_build_initial_query($params); - is( $query, "query operator parsed_operand", - "\$query built correctly"); - is( $query_cgi, "query_cgi&op=operator&idx=index&q=original_operand", - "\$query_cgi built correctly"); - is( $query_desc, "query_desc operator index_plus original_operand", - "\$query_desc build correctly"); - is( $previous_operand, "previous_operand", - "\$query build correctly"); + ( $query, $query_cgi, $query_desc, $previous_operand ) = C4::Search::_build_initial_query($params); + is( + $query, "query operator parsed_operand", + "\$query built correctly" + ); + is( + $query_cgi, "query_cgi&op=operator&idx=index&q=original_operand", + "\$query_cgi built correctly" + ); + is( + $query_desc, "query_desc operator index_plus original_operand", + "\$query_desc build correctly" + ); + is( + $previous_operand, "previous_operand", + "\$query build correctly" + ); # no operator $params = { @@ -68,16 +76,23 @@ subtest "_build_initial_query tests" => sub { previous_operand => "previous_operand" }; - ($query,$query_cgi,$query_desc,$previous_operand) = - C4::Search::_build_initial_query($params); - is( $query, "query AND parsed_operand", - "\$query built correctly (no operator)"); - is( $query_cgi, "query_cgi&op=AND&idx=index&q=original_operand", - "\$query_cgi built correctly (no operator)"); - is( $query_desc, "query_desc AND index_plus original_operand", - "\$query_desc build correctly (no operator)"); - is( $previous_operand, "previous_operand", - "\$query build correctly (no operator)"); + ( $query, $query_cgi, $query_desc, $previous_operand ) = C4::Search::_build_initial_query($params); + is( + $query, "query AND parsed_operand", + "\$query built correctly (no operator)" + ); + is( + $query_cgi, "query_cgi&op=AND&idx=index&q=original_operand", + "\$query_cgi built correctly (no operator)" + ); + is( + $query_desc, "query_desc AND index_plus original_operand", + "\$query_desc build correctly (no operator)" + ); + is( + $previous_operand, "previous_operand", + "\$query build correctly (no operator)" + ); # no previous operand $params = { @@ -93,16 +108,23 @@ subtest "_build_initial_query tests" => sub { previous_operand => undef }; - ($query,$query_cgi,$query_desc,$previous_operand) = - C4::Search::_build_initial_query($params); - is( $query, "query parsed_operand", - "\$query built correctly (no previous operand)"); - is( $query_cgi, "query_cgi&idx=index&q=original_operand", - "\$query_cgi built correctly (no previous operand)"); - is( $query_desc, "query_desc index_plus original_operand", - "\$query_desc build correctly (no previous operand)"); - is( $previous_operand, 1, - "\$query build correctly (no previous operand)"); + ( $query, $query_cgi, $query_desc, $previous_operand ) = C4::Search::_build_initial_query($params); + is( + $query, "query parsed_operand", + "\$query built correctly (no previous operand)" + ); + is( + $query_cgi, "query_cgi&idx=index&q=original_operand", + "\$query_cgi built correctly (no previous operand)" + ); + is( + $query_desc, "query_desc index_plus original_operand", + "\$query_desc build correctly (no previous operand)" + ); + is( + $previous_operand, 1, + "\$query build correctly (no previous operand)" + ); # no index passed $params = { @@ -118,16 +140,23 @@ subtest "_build_initial_query tests" => sub { previous_operand => "previous_operand" }; - ($query,$query_cgi,$query_desc,$previous_operand) = - C4::Search::_build_initial_query($params); - is( $query, "query operator parsed_operand", - "\$query built correctly (no index passed)"); - is( $query_cgi, "query_cgi&op=operator&q=original_operand", - "\$query_cgi built correctly (no index passed)"); - is( $query_desc, "query_desc operator index_plus original_operand", - "\$query_desc build correctly (no index passed)"); - is( $previous_operand, "previous_operand", - "\$query build correctly (no index passed)"); + ( $query, $query_cgi, $query_desc, $previous_operand ) = C4::Search::_build_initial_query($params); + is( + $query, "query operator parsed_operand", + "\$query built correctly (no index passed)" + ); + is( + $query_cgi, "query_cgi&op=operator&q=original_operand", + "\$query_cgi built correctly (no index passed)" + ); + is( + $query_desc, "query_desc operator index_plus original_operand", + "\$query_desc build correctly (no index passed)" + ); + is( + $previous_operand, "previous_operand", + "\$query build correctly (no index passed)" + ); # no index_plus passed $params = { @@ -143,16 +172,23 @@ subtest "_build_initial_query tests" => sub { previous_operand => "previous_operand" }; - ($query,$query_cgi,$query_desc,$previous_operand) = - C4::Search::_build_initial_query($params); - is( $query, "query operator parsed_operand", - "\$query built correctly (no index_plus passed)"); - is( $query_cgi, "query_cgi&op=operator&idx=index&q=original_operand", - "\$query_cgi built correctly (no index_plus passed)"); - is( $query_desc, "query_desc operator original_operand", - "\$query_desc build correctly (no index_plus passed)"); - is( $previous_operand, "previous_operand", - "\$query build correctly (no index_plus passed)"); + ( $query, $query_cgi, $query_desc, $previous_operand ) = C4::Search::_build_initial_query($params); + is( + $query, "query operator parsed_operand", + "\$query built correctly (no index_plus passed)" + ); + is( + $query_cgi, "query_cgi&op=operator&idx=index&q=original_operand", + "\$query_cgi built correctly (no index_plus passed)" + ); + is( + $query_desc, "query_desc operator original_operand", + "\$query_desc build correctly (no index_plus passed)" + ); + is( + $previous_operand, "previous_operand", + "\$query build correctly (no index_plus passed)" + ); }; @@ -160,15 +196,17 @@ subtest "searchResults PassItemMarcToXSLT test" => sub { plan tests => 2; - t::lib::Mocks::mock_preference('OPACXSLTResultsDisplay','default'); - t::lib::Mocks::mock_preference('marcflavour','MARC21'); + t::lib::Mocks::mock_preference( 'OPACXSLTResultsDisplay', 'default' ); + t::lib::Mocks::mock_preference( 'marcflavour', 'MARC21' ); my $mock_xslt = Test::MockModule->new("C4::Search"); - $mock_xslt->mock( XSLTParse4Display => sub { - my $params = shift; - my $record = $params->{record}; - warn $record->field('952') ? "Item here" : "No item"; - return; - }); + $mock_xslt->mock( + XSLTParse4Display => sub { + my $params = shift; + my $record = $params->{record}; + warn $record->field('952') ? "Item here" : "No item"; + return; + } + ); my $xml_record = q{ sub { }; - t::lib::Mocks::mock_preference('PassItemMarcToXSLT','1'); + t::lib::Mocks::mock_preference( 'PassItemMarcToXSLT', '1' ); # The routine uses a count of items in DB to determine if record should be hidden. # Our item is not in the DB, so we avoid hiding the record which would # mean we don't call XSLTParse4Display. # Also ensure item is not hidden - t::lib::Mocks::mock_preference('OpacHiddenItems',''); - t::lib::Mocks::mock_preference('OpacHiddenItemsHidesRecord','0'); + t::lib::Mocks::mock_preference( 'OpacHiddenItems', '' ); + t::lib::Mocks::mock_preference( 'OpacHiddenItemsHidesRecord', '0' ); - warnings_like { C4::Search::searchResults({ interface => "opac" },"test",1,1,0,0,[ $xml_record ] ,undef) } - [qr/Item here/], + warnings_like { C4::Search::searchResults( { interface => "opac" }, "test", 1, 1, 0, 0, [$xml_record], undef ) } + [qr/Item here/], "Item field returned from default XSLT if pref set"; - t::lib::Mocks::mock_preference('PassItemMarcToXSLT','0'); + t::lib::Mocks::mock_preference( 'PassItemMarcToXSLT', '0' ); - warnings_like { C4::Search::searchResults({ interface => "opac" },"test",1,1,0,0,[ $xml_record ] ,undef) } - [qr/No item/], + warnings_like { C4::Search::searchResults( { interface => "opac" }, "test", 1, 1, 0, 0, [$xml_record], undef ) } + [qr/No item/], "Item field returned from default XSLT if pref set"; -} + } diff --git a/t/Search/History.t b/t/Search/History.t index 0b3715c13c..594d05d6bc 100755 --- a/t/Search/History.t +++ b/t/Search/History.t @@ -7,15 +7,15 @@ use URI::Escape; use JSON qw( decode_json ); use_ok('Koha::DateUtils'); -use_ok('C4::Search::History', qw( get get_from_session set_to_session delete )); -use_ok('C4::Auth', qw/get_session/ ); +use_ok( 'C4::Search::History', qw( get get_from_session set_to_session delete ) ); +use_ok( 'C4::Auth', qw/get_session/ ); # Test session my $expected_recent_searches = [ { - 'time' => 1374978877, - 'query_cgi' => 'idx=&q=history&branch_group_limit=', - 'total' => 2, + 'time' => 1374978877, + 'query_cgi' => 'idx=&q=history&branch_group_limit=', + 'total' => 2, 'query_desc' => 'kw,wrdl: history, ' } ]; @@ -23,18 +23,18 @@ my $expected_recent_searches = [ # Create new session and put its id into CGISESSID cookie my $session = C4::Auth::get_session(""); $session->flush; -my $input = CookieSimulator->new({CGISESSID => $session->id}); +my $input = CookieSimulator->new( { CGISESSID => $session->id } ); -my @recent_searches = C4::Search::History::get_from_session({ cgi => $input }); -is_deeply(\@recent_searches, [], 'at start, there is no recent searches'); +my @recent_searches = C4::Search::History::get_from_session( { cgi => $input } ); +is_deeply( \@recent_searches, [], 'at start, there is no recent searches' ); -C4::Search::History::set_to_session({ cgi => $input, search_history => $expected_recent_searches }); -@recent_searches = C4::Search::History::get_from_session({ cgi => $input }); -is_deeply(\@recent_searches, $expected_recent_searches, 'recent searches set and retrieved successfully'); +C4::Search::History::set_to_session( { cgi => $input, search_history => $expected_recent_searches } ); +@recent_searches = C4::Search::History::get_from_session( { cgi => $input } ); +is_deeply( \@recent_searches, $expected_recent_searches, 'recent searches set and retrieved successfully' ); -C4::Search::History::set_to_session({ cgi => $input, search_history => [] }); -@recent_searches = C4::Search::History::get_from_session({ cgi => $input }); -is_deeply(\@recent_searches, [], 'recent searches emptied successfully'); +C4::Search::History::set_to_session( { cgi => $input, search_history => [] } ); +@recent_searches = C4::Search::History::get_from_session( { cgi => $input } ); +is_deeply( \@recent_searches, [], 'recent searches emptied successfully' ); # Delete session $session->delete; @@ -43,13 +43,13 @@ $session->flush; package CookieSimulator; sub new { - my ($class, $hashref) = @_; + my ( $class, $hashref ) = @_; my $val = $hashref; return bless $val, $class; } sub cookie { - my ($self, $name) = @_; + my ( $self, $name ) = @_; return $self->{$name}; } diff --git a/t/Search/buildQuery.t b/t/Search/buildQuery.t index d03b2cf8b0..8aa1d9ae3a 100755 --- a/t/Search/buildQuery.t +++ b/t/Search/buildQuery.t @@ -58,37 +58,38 @@ sub _get_ccl_properties { subtest "test weighted autotruncated" => sub { plan tests => 13; - t::lib::Mocks::mock_preference('QueryWeightFields', '1'); - t::lib::Mocks::mock_preference('QueryAutoTruncate', '1'); + t::lib::Mocks::mock_preference( 'QueryWeightFields', '1' ); + t::lib::Mocks::mock_preference( 'QueryAutoTruncate', '1' ); - my $config = _get_ccl_properties(); + my $config = _get_ccl_properties(); my $operators = [""]; - my $operands = ["test"]; - my $indexes = [""]; - my $limits = [""]; - my $sort_by = [""]; - my ($scan,$lang); + my $operands = ["test"]; + my $indexes = [""]; + my $limits = [""]; + my $sort_by = [""]; + my ( $scan, $lang ); - my ($error,$query,$simple_query,$query_cgi,$query_desc,$limit,$limit_cgi,$limit_desc,$query_type) = - C4::Search::buildQuery($operators,$operands,$indexes,$limits,$sort_by,$scan,$lang); - is($error,undef,"Error is correct"); - is($query,'(rk=(kw,wrdl,rtrn=test )) ','Query is correct with auto truncation'); - is($simple_query,'test',"Simple query is correct"); - is($query_cgi,'idx=kw&q=test','Query cgi is correct'); - is($query_desc,'kw,wrdl: test','Query desc is correct'); - is($limit,'',"Limit is correct"); - is($limit_cgi,'',"Limit cgi is correct"); - is($limit_desc,'',"Limit desc is correct"); - is($query_type,undef,"Query type is correct"); + my ( $error, $query, $simple_query, $query_cgi, $query_desc, $limit, $limit_cgi, $limit_desc, $query_type ) = + C4::Search::buildQuery( $operators, $operands, $indexes, $limits, $sort_by, $scan, $lang ); + is( $error, undef, "Error is correct" ); + is( $query, '(rk=(kw,wrdl,rtrn=test )) ', 'Query is correct with auto truncation' ); + is( $simple_query, 'test', "Simple query is correct" ); + is( $query_cgi, 'idx=kw&q=test', 'Query cgi is correct' ); + is( $query_desc, 'kw,wrdl: test', 'Query desc is correct' ); + is( $limit, '', "Limit is correct" ); + is( $limit_cgi, '', "Limit cgi is correct" ); + is( $limit_desc, '', "Limit desc is correct" ); + is( $query_type, undef, "Query type is correct" ); my $q = Net::Z3950::ZOOM::query_create(); - my ($ccl_errcode, $ccl_errstr, $ccl_errpos) = (0,"",0); - my $res = Net::Z3950::ZOOM::query_ccl2rpn($q, $query, $config, + my ( $ccl_errcode, $ccl_errstr, $ccl_errpos ) = ( 0, "", 0 ); + my $res = Net::Z3950::ZOOM::query_ccl2rpn( + $q, $query, $config, $ccl_errcode, $ccl_errstr, $ccl_errpos ); - is($res,0,"created CCL2RPN query"); - is($ccl_errcode,0); - is($ccl_errstr,""); - is($ccl_errpos,0); + is( $res, 0, "created CCL2RPN query" ); + is( $ccl_errcode, 0 ); + is( $ccl_errstr, "" ); + is( $ccl_errpos, 0 ); Net::Z3950::ZOOM::query_destroy($q); }; @@ -96,258 +97,281 @@ subtest "test weighted autotruncated" => sub { subtest "test* weighted autotruncated" => sub { plan tests => 13; - t::lib::Mocks::mock_preference('QueryWeightFields', '1'); - t::lib::Mocks::mock_preference('QueryAutoTruncate', '1'); + t::lib::Mocks::mock_preference( 'QueryWeightFields', '1' ); + t::lib::Mocks::mock_preference( 'QueryAutoTruncate', '1' ); - my $config = _get_ccl_properties(); + my $config = _get_ccl_properties(); my $operators = [""]; - my $operands = ["test*"]; - my $indexes = [""]; - my $limits = [""]; - my $sort_by = [""]; - my ($scan,$lang); + my $operands = ["test*"]; + my $indexes = [""]; + my $limits = [""]; + my $sort_by = [""]; + my ( $scan, $lang ); - my ($error,$query,$simple_query,$query_cgi,$query_desc,$limit,$limit_cgi,$limit_desc,$query_type) = - C4::Search::buildQuery($operators,$operands,$indexes,$limits,$sort_by,$scan,$lang); - is($error,undef,"Error is correct"); - is($query,'(rk=(kw,wrdl,rtrn=test )) ','Query is correct with manual truncation'); - is($simple_query,'test*',"Simple query is correct"); - is($query_cgi,'idx=kw&q=test%2A','Query cgi is correct'); - is($query_desc,'kw,wrdl: test*','Query desc is correct'); - is($limit,'',"Limit is correct"); - is($limit_cgi,'',"Limit cgi is correct"); - is($limit_desc,'',"Limit desc is correct"); - is($query_type,undef,"Query type is correct"); + my ( $error, $query, $simple_query, $query_cgi, $query_desc, $limit, $limit_cgi, $limit_desc, $query_type ) = + C4::Search::buildQuery( $operators, $operands, $indexes, $limits, $sort_by, $scan, $lang ); + is( $error, undef, "Error is correct" ); + is( $query, '(rk=(kw,wrdl,rtrn=test )) ', 'Query is correct with manual truncation' ); + is( $simple_query, 'test*', "Simple query is correct" ); + is( $query_cgi, 'idx=kw&q=test%2A', 'Query cgi is correct' ); + is( $query_desc, 'kw,wrdl: test*', 'Query desc is correct' ); + is( $limit, '', "Limit is correct" ); + is( $limit_cgi, '', "Limit cgi is correct" ); + is( $limit_desc, '', "Limit desc is correct" ); + is( $query_type, undef, "Query type is correct" ); my $q = Net::Z3950::ZOOM::query_create(); - my ($ccl_errcode, $ccl_errstr, $ccl_errpos) = (0,"",0); - my $res = Net::Z3950::ZOOM::query_ccl2rpn($q, $query, $config, + my ( $ccl_errcode, $ccl_errstr, $ccl_errpos ) = ( 0, "", 0 ); + my $res = Net::Z3950::ZOOM::query_ccl2rpn( + $q, $query, $config, $ccl_errcode, $ccl_errstr, $ccl_errpos ); - is($res,0,"created CCL2RPN query"); - is($ccl_errcode,0); - is($ccl_errstr,""); - is($ccl_errpos,0); + is( $res, 0, "created CCL2RPN query" ); + is( $ccl_errcode, 0 ); + is( $ccl_errstr, "" ); + is( $ccl_errpos, 0 ); Net::Z3950::ZOOM::query_destroy($q); }; subtest "test weighted not-autotruncated" => sub { plan tests => 13; - t::lib::Mocks::mock_preference('QueryWeightFields', '1'); - t::lib::Mocks::mock_preference('QueryAutoTruncate', '0'); - t::lib::Mocks::mock_preference('QueryFuzzy', '1'); + t::lib::Mocks::mock_preference( 'QueryWeightFields', '1' ); + t::lib::Mocks::mock_preference( 'QueryAutoTruncate', '0' ); + t::lib::Mocks::mock_preference( 'QueryFuzzy', '1' ); - my $config = _get_ccl_properties(); + my $config = _get_ccl_properties(); my $operators = [""]; - my $operands = ["test"]; - my $indexes = [""]; - my $limits = [""]; - my $sort_by = [""]; - my ($scan,$lang); + my $operands = ["test"]; + my $indexes = [""]; + my $limits = [""]; + my $sort_by = [""]; + my ( $scan, $lang ); - my ($error,$query,$simple_query,$query_cgi,$query_desc,$limit,$limit_cgi,$limit_desc,$query_type) = - C4::Search::buildQuery($operators,$operands,$indexes,$limits,$sort_by,$scan,$lang); - is($error,undef,"Error is correct"); - is($query,'(rk=(Title-cover,ext,r1="test" or ti,ext,r2="test" or Title-cover,phr,r3="test" or ti,wrdl,r4="test" or wrdl,fuzzy,r8="test" or wrdl,right-Truncation,r9="test" or wrdl,r9="test")) ','Query is correct with weighted fields'); - is($simple_query,'test',"Simple query is correct"); - is($query_cgi,'idx=kw&q=test','Query cgi is correct'); - is($query_desc,'kw,wrdl: test','Query desc is correct'); - is($limit,'',"Limit is correct"); - is($limit_cgi,'',"Limit cgi is correct"); - is($limit_desc,'',"Limit desc is correct"); - is($query_type,undef,"Query type is correct"); + my ( $error, $query, $simple_query, $query_cgi, $query_desc, $limit, $limit_cgi, $limit_desc, $query_type ) = + C4::Search::buildQuery( $operators, $operands, $indexes, $limits, $sort_by, $scan, $lang ); + is( $error, undef, "Error is correct" ); + is( + $query, + '(rk=(Title-cover,ext,r1="test" or ti,ext,r2="test" or Title-cover,phr,r3="test" or ti,wrdl,r4="test" or wrdl,fuzzy,r8="test" or wrdl,right-Truncation,r9="test" or wrdl,r9="test")) ', + 'Query is correct with weighted fields' + ); + is( $simple_query, 'test', "Simple query is correct" ); + is( $query_cgi, 'idx=kw&q=test', 'Query cgi is correct' ); + is( $query_desc, 'kw,wrdl: test', 'Query desc is correct' ); + is( $limit, '', "Limit is correct" ); + is( $limit_cgi, '', "Limit cgi is correct" ); + is( $limit_desc, '', "Limit desc is correct" ); + is( $query_type, undef, "Query type is correct" ); my $q = Net::Z3950::ZOOM::query_create(); - my ($ccl_errcode, $ccl_errstr, $ccl_errpos) = (0,"",0); - my $res = Net::Z3950::ZOOM::query_ccl2rpn($q, $query, $config, + my ( $ccl_errcode, $ccl_errstr, $ccl_errpos ) = ( 0, "", 0 ); + my $res = Net::Z3950::ZOOM::query_ccl2rpn( + $q, $query, $config, $ccl_errcode, $ccl_errstr, $ccl_errpos ); - is($res,0,"created CCL2RPN query"); - is($ccl_errcode,0); - is($ccl_errstr,""); - is($ccl_errpos,0); + is( $res, 0, "created CCL2RPN query" ); + is( $ccl_errcode, 0 ); + is( $ccl_errstr, "" ); + is( $ccl_errpos, 0 ); Net::Z3950::ZOOM::query_destroy($q); }; - subtest "test ccode:REF weighted autotruncated" => sub { plan tests => 13; - t::lib::Mocks::mock_preference('QueryWeightFields', '1'); - t::lib::Mocks::mock_preference('QueryAutoTruncate', '1'); + t::lib::Mocks::mock_preference( 'QueryWeightFields', '1' ); + t::lib::Mocks::mock_preference( 'QueryAutoTruncate', '1' ); - my $config = _get_ccl_properties(); + my $config = _get_ccl_properties(); my $operators = [""]; - my $operands = ["test"]; - my $indexes = [""]; - my $limits = ["ccode:REF"]; - my $sort_by = [""]; - my ($scan,$lang); + my $operands = ["test"]; + my $indexes = [""]; + my $limits = ["ccode:REF"]; + my $sort_by = [""]; + my ( $scan, $lang ); - my ($error,$query,$simple_query,$query_cgi,$query_desc,$limit,$limit_cgi,$limit_desc,$query_type) = - C4::Search::buildQuery($operators,$operands,$indexes,$limits,$sort_by,$scan,$lang); - is($error,undef,"Error is correct"); - is($query,'(rk=(kw,wrdl,rtrn=test )) and ccode=REF','Query is correct with auto truncation and limits'); - is($simple_query,'test',"Simple query is correct"); - is($query_cgi,'idx=kw&q=test','Query cgi is correct'); - is($query_desc,'kw,wrdl: test','Query desc is correct'); - is($limit,'and ccode=REF',"Limit is correct"); - is($limit_cgi,'&limit=ccode%3AREF',"Limit cgi is correct"); - is($limit_desc,'ccode:REF',"Limit desc is correct"); - is($query_type,undef,"Query type is correct"); + my ( $error, $query, $simple_query, $query_cgi, $query_desc, $limit, $limit_cgi, $limit_desc, $query_type ) = + C4::Search::buildQuery( $operators, $operands, $indexes, $limits, $sort_by, $scan, $lang ); + is( $error, undef, "Error is correct" ); + is( $query, '(rk=(kw,wrdl,rtrn=test )) and ccode=REF', 'Query is correct with auto truncation and limits' ); + is( $simple_query, 'test', "Simple query is correct" ); + is( $query_cgi, 'idx=kw&q=test', 'Query cgi is correct' ); + is( $query_desc, 'kw,wrdl: test', 'Query desc is correct' ); + is( $limit, 'and ccode=REF', "Limit is correct" ); + is( $limit_cgi, '&limit=ccode%3AREF', "Limit cgi is correct" ); + is( $limit_desc, 'ccode:REF', "Limit desc is correct" ); + is( $query_type, undef, "Query type is correct" ); my $q = Net::Z3950::ZOOM::query_create(); - my ($ccl_errcode, $ccl_errstr, $ccl_errpos) = (0,"",0); - my $res = Net::Z3950::ZOOM::query_ccl2rpn($q, $query, $config, + my ( $ccl_errcode, $ccl_errstr, $ccl_errpos ) = ( 0, "", 0 ); + my $res = Net::Z3950::ZOOM::query_ccl2rpn( + $q, $query, $config, $ccl_errcode, $ccl_errstr, $ccl_errpos ); - is($res,0,"created CCL2RPN query"); - is($ccl_errcode,0); - is($ccl_errstr,""); - is($ccl_errpos,0); + is( $res, 0, "created CCL2RPN query" ); + is( $ccl_errcode, 0 ); + is( $ccl_errstr, "" ); + is( $ccl_errpos, 0 ); Net::Z3950::ZOOM::query_destroy($q); }; subtest "test ccode:REF weighted not-autotruncated" => sub { plan tests => 13; - t::lib::Mocks::mock_preference('QueryWeightFields', '1'); - t::lib::Mocks::mock_preference('QueryAutoTruncate', '0'); + t::lib::Mocks::mock_preference( 'QueryWeightFields', '1' ); + t::lib::Mocks::mock_preference( 'QueryAutoTruncate', '0' ); - my $config = _get_ccl_properties(); + my $config = _get_ccl_properties(); my $operators = [""]; - my $operands = ["test"]; - my $indexes = [""]; - my $limits = ["ccode:REF"]; - my $sort_by = [""]; - my ($scan,$lang); + my $operands = ["test"]; + my $indexes = [""]; + my $limits = ["ccode:REF"]; + my $sort_by = [""]; + my ( $scan, $lang ); - my ($error,$query,$simple_query,$query_cgi,$query_desc,$limit,$limit_cgi,$limit_desc,$query_type) = - C4::Search::buildQuery($operators,$operands,$indexes,$limits,$sort_by,$scan,$lang); - is($error,undef,"Error is correct"); - is($query,'(rk=(Title-cover,ext,r1="test" or ti,ext,r2="test" or Title-cover,phr,r3="test" or ti,wrdl,r4="test" or wrdl,fuzzy,r8="test" or wrdl,right-Truncation,r9="test" or wrdl,r9="test")) and ccode=REF','Query is correct with weighted fields and limits'); - is($simple_query,'test',"Simple query is correct"); - is($query_cgi,'idx=kw&q=test','Query cgi is correct'); - is($query_desc,'kw,wrdl: test','Query desc is correct'); - is($limit,'and ccode=REF',"Limit is correct"); - is($limit_cgi,'&limit=ccode%3AREF',"Limit cgi is correct"); - is($limit_desc,'ccode:REF',"Limit desc is correct"); - is($query_type,undef,"Query type is correct"); + my ( $error, $query, $simple_query, $query_cgi, $query_desc, $limit, $limit_cgi, $limit_desc, $query_type ) = + C4::Search::buildQuery( $operators, $operands, $indexes, $limits, $sort_by, $scan, $lang ); + is( $error, undef, "Error is correct" ); + is( + $query, + '(rk=(Title-cover,ext,r1="test" or ti,ext,r2="test" or Title-cover,phr,r3="test" or ti,wrdl,r4="test" or wrdl,fuzzy,r8="test" or wrdl,right-Truncation,r9="test" or wrdl,r9="test")) and ccode=REF', + 'Query is correct with weighted fields and limits' + ); + is( $simple_query, 'test', "Simple query is correct" ); + is( $query_cgi, 'idx=kw&q=test', 'Query cgi is correct' ); + is( $query_desc, 'kw,wrdl: test', 'Query desc is correct' ); + is( $limit, 'and ccode=REF', "Limit is correct" ); + is( $limit_cgi, '&limit=ccode%3AREF', "Limit cgi is correct" ); + is( $limit_desc, 'ccode:REF', "Limit desc is correct" ); + is( $query_type, undef, "Query type is correct" ); my $q = Net::Z3950::ZOOM::query_create(); - my ($ccl_errcode, $ccl_errstr, $ccl_errpos) = (0,"",0); - my $res = Net::Z3950::ZOOM::query_ccl2rpn($q, $query, $config, + my ( $ccl_errcode, $ccl_errstr, $ccl_errpos ) = ( 0, "", 0 ); + my $res = Net::Z3950::ZOOM::query_ccl2rpn( + $q, $query, $config, $ccl_errcode, $ccl_errstr, $ccl_errpos ); - is($res,0,"created CCL2RPN query"); - is($ccl_errcode,0); - is($ccl_errstr,""); - is($ccl_errpos,0); + is( $res, 0, "created CCL2RPN query" ); + is( $ccl_errcode, 0 ); + is( $ccl_errstr, "" ); + is( $ccl_errpos, 0 ); Net::Z3950::ZOOM::query_destroy($q); }; subtest "kw:one and title:two ccode:REF weighted autotruncated" => sub { plan tests => 13; - t::lib::Mocks::mock_preference('QueryWeightFields', '1'); - t::lib::Mocks::mock_preference('QueryAutoTruncate', '1'); + t::lib::Mocks::mock_preference( 'QueryWeightFields', '1' ); + t::lib::Mocks::mock_preference( 'QueryAutoTruncate', '1' ); - my $config = _get_ccl_properties(); + my $config = _get_ccl_properties(); my $operators = ["and"]; - my $operands = ["one","two"]; - my $indexes = ["kw","title"]; - my $limits = ["ccode:REF"]; - my $sort_by = [""]; - my ($scan,$lang); + my $operands = [ "one", "two" ]; + my $indexes = [ "kw", "title" ]; + my $limits = ["ccode:REF"]; + my $sort_by = [""]; + my ( $scan, $lang ); - my ($error,$query,$simple_query,$query_cgi,$query_desc,$limit,$limit_cgi,$limit_desc,$query_type) = - C4::Search::buildQuery($operators,$operands,$indexes,$limits,$sort_by,$scan,$lang); - is($error,undef,"Error is correct"); - is($query,'(rk=(kw,wrdl,rtrn=one )) and (rk=(title,wrdl,rtrn=two )) and ccode=REF','Query is correct with auto truncation, limits, and using indexes and operators'); - is($simple_query,'one',"Simple query is correct?"); - is($query_cgi,'idx=kw&q=one&op=and&idx=title&q=two','Query cgi is correct'); - is($query_desc,'kw,wrdl: one and title,wrdl: two','Query desc is correct'); - is($limit,'and ccode=REF',"Limit is correct"); - is($limit_cgi,'&limit=ccode%3AREF',"Limit cgi is correct"); - is($limit_desc,'ccode:REF',"Limit desc is correct"); - is($query_type,undef,"Query type is correct"); + my ( $error, $query, $simple_query, $query_cgi, $query_desc, $limit, $limit_cgi, $limit_desc, $query_type ) = + C4::Search::buildQuery( $operators, $operands, $indexes, $limits, $sort_by, $scan, $lang ); + is( $error, undef, "Error is correct" ); + is( + $query, '(rk=(kw,wrdl,rtrn=one )) and (rk=(title,wrdl,rtrn=two )) and ccode=REF', + 'Query is correct with auto truncation, limits, and using indexes and operators' + ); + is( $simple_query, 'one', "Simple query is correct?" ); + is( $query_cgi, 'idx=kw&q=one&op=and&idx=title&q=two', 'Query cgi is correct' ); + is( $query_desc, 'kw,wrdl: one and title,wrdl: two', 'Query desc is correct' ); + is( $limit, 'and ccode=REF', "Limit is correct" ); + is( $limit_cgi, '&limit=ccode%3AREF', "Limit cgi is correct" ); + is( $limit_desc, 'ccode:REF', "Limit desc is correct" ); + is( $query_type, undef, "Query type is correct" ); my $q = Net::Z3950::ZOOM::query_create(); - my ($ccl_errcode, $ccl_errstr, $ccl_errpos) = (0,"",0); - my $res = Net::Z3950::ZOOM::query_ccl2rpn($q, $query, $config, + my ( $ccl_errcode, $ccl_errstr, $ccl_errpos ) = ( 0, "", 0 ); + my $res = Net::Z3950::ZOOM::query_ccl2rpn( + $q, $query, $config, $ccl_errcode, $ccl_errstr, $ccl_errpos ); - is($res,0,"created CCL2RPN query"); - is($ccl_errcode,0); - is($ccl_errstr,""); - is($ccl_errpos,0); + is( $res, 0, "created CCL2RPN query" ); + is( $ccl_errcode, 0 ); + is( $ccl_errstr, "" ); + is( $ccl_errpos, 0 ); Net::Z3950::ZOOM::query_destroy($q); }; subtest "one and two weighted autotruncated" => sub { plan tests => 13; - t::lib::Mocks::mock_preference('QueryWeightFields', '1'); - t::lib::Mocks::mock_preference('QueryAutoTruncate', '1'); + t::lib::Mocks::mock_preference( 'QueryWeightFields', '1' ); + t::lib::Mocks::mock_preference( 'QueryAutoTruncate', '1' ); - my $config = _get_ccl_properties(); + my $config = _get_ccl_properties(); my $operators = [""]; - my $operands = ["one and two"]; - my $indexes = [""]; - my $limits = [""]; - my $sort_by = [""]; - my ($scan,$lang); + my $operands = ["one and two"]; + my $indexes = [""]; + my $limits = [""]; + my $sort_by = [""]; + my ( $scan, $lang ); - my ($error,$query,$simple_query,$query_cgi,$query_desc,$limit,$limit_cgi,$limit_desc,$query_type) = - C4::Search::buildQuery($operators,$operands,$indexes,$limits,$sort_by,$scan,$lang); - is($error,undef,"Error is correct"); - is($query,'(rk=(kw,wrdl,rtrn=one and two )) ','Query is correct with auto truncation and unstructured query'); - is($simple_query,'one and two',"Simple query is correct"); - is($query_cgi,'idx=kw&q=one%20and%20two','Query cgi is correct'); - is($query_desc,'kw,wrdl: one and two','Query desc is correct'); - is($limit,'',"Limit is correct"); - is($limit_cgi,'',"Limit cgi is correct"); - is($limit_desc,'',"Limit desc is correct"); - is($query_type,undef,"Query type is correct"); + my ( $error, $query, $simple_query, $query_cgi, $query_desc, $limit, $limit_cgi, $limit_desc, $query_type ) = + C4::Search::buildQuery( $operators, $operands, $indexes, $limits, $sort_by, $scan, $lang ); + is( $error, undef, "Error is correct" ); + is( $query, '(rk=(kw,wrdl,rtrn=one and two )) ', 'Query is correct with auto truncation and unstructured query' ); + is( $simple_query, 'one and two', "Simple query is correct" ); + is( $query_cgi, 'idx=kw&q=one%20and%20two', 'Query cgi is correct' ); + is( $query_desc, 'kw,wrdl: one and two', 'Query desc is correct' ); + is( $limit, '', "Limit is correct" ); + is( $limit_cgi, '', "Limit cgi is correct" ); + is( $limit_desc, '', "Limit desc is correct" ); + is( $query_type, undef, "Query type is correct" ); my $q = Net::Z3950::ZOOM::query_create(); - my ($ccl_errcode, $ccl_errstr, $ccl_errpos) = (0,"",0); - my $res = Net::Z3950::ZOOM::query_ccl2rpn($q, $query, $config, + my ( $ccl_errcode, $ccl_errstr, $ccl_errpos ) = ( 0, "", 0 ); + my $res = Net::Z3950::ZOOM::query_ccl2rpn( + $q, $query, $config, $ccl_errcode, $ccl_errstr, $ccl_errpos ); - is($res,0,"created CCL2RPN query"); - is($ccl_errcode,0); - is($ccl_errstr,""); - is($ccl_errpos,0); + is( $res, 0, "created CCL2RPN query" ); + is( $ccl_errcode, 0 ); + is( $ccl_errstr, "" ); + is( $ccl_errpos, 0 ); Net::Z3950::ZOOM::query_destroy($q); }; subtest "test with ISBN variations" => sub { plan tests => 12; - my $config = _get_ccl_properties(); + my $config = _get_ccl_properties(); my $operators = [""]; - my $operands = ["1565926994"]; - my $indexes = ["nb"]; - my $limits = [""]; - my $sort_by = [""]; - my ($scan,$lang); + my $operands = ["1565926994"]; + my $indexes = ["nb"]; + my $limits = [""]; + my $sort_by = [""]; + my ( $scan, $lang ); foreach my $sample ( { state => 0, query => 'nb=(rk=(1565926994)) ' }, - { state => 1, query => 'kw,wrdl=(rk=((nb=1-56592-699-4 OR nb=1-56592-699-4 OR nb=978-1-56592-699-8 OR nb=1565926994 OR nb=9781565926998))) ' }) + { + state => 1, + query => + 'kw,wrdl=(rk=((nb=1-56592-699-4 OR nb=1-56592-699-4 OR nb=978-1-56592-699-8 OR nb=1565926994 OR nb=9781565926998))) ' + } + ) { - t::lib::Mocks::mock_preference('SearchWithISBNVariations', $sample->{state}); + t::lib::Mocks::mock_preference( 'SearchWithISBNVariations', $sample->{state} ); + # Test with disabled variatioms - my ($error,$query,$simple_query,$query_cgi,$query_desc,$limit,$limit_cgi,$limit_desc,$query_type) = - C4::Search::buildQuery($operators,$operands,$indexes,$limits,$sort_by,$scan,$lang); - say 'Q: > ', $query; - is($error,undef,"Error is correct"); - is($query,$sample->{query},'Search ISBN when variations is '.$sample->{state}); + my ( $error, $query, $simple_query, $query_cgi, $query_desc, $limit, $limit_cgi, $limit_desc, $query_type ) = + C4::Search::buildQuery( $operators, $operands, $indexes, $limits, $sort_by, $scan, $lang ); + say 'Q: > ', $query; + is( $error, undef, "Error is correct" ); + is( $query, $sample->{query}, 'Search ISBN when variations is ' . $sample->{state} ); my $q = Net::Z3950::ZOOM::query_create(); - my ($ccl_errcode, $ccl_errstr, $ccl_errpos) = (0,"",0); - my $res = Net::Z3950::ZOOM::query_ccl2rpn($q, $query, $config, + my ( $ccl_errcode, $ccl_errstr, $ccl_errpos ) = ( 0, "", 0 ); + my $res = Net::Z3950::ZOOM::query_ccl2rpn( + $q, $query, $config, $ccl_errcode, $ccl_errstr, $ccl_errpos ); - is($res,0,"created CCL2RPN query"); - is($ccl_errcode,0); - is($ccl_errstr,""); - is($ccl_errpos,0); + is( $res, 0, "created CCL2RPN query" ); + is( $ccl_errcode, 0 ); + is( $ccl_errstr, "" ); + is( $ccl_errpos, 0 ); Net::Z3950::ZOOM::query_destroy($q); } @@ -356,34 +380,37 @@ subtest "test with ISBN variations" => sub { subtest "test with ISSN variations" => sub { plan tests => 12; - my $config = _get_ccl_properties(); + my $config = _get_ccl_properties(); my $operators = [""]; - my $operands = ["2434561X"]; - my $indexes = ["ns"]; - my $limits = [""]; - my $sort_by = [""]; - my ($scan,$lang); + my $operands = ["2434561X"]; + my $indexes = ["ns"]; + my $limits = [""]; + my $sort_by = [""]; + my ( $scan, $lang ); foreach my $sample ( { state => 0, query => 'ns=(rk=(2434561X)) ' }, - { state => 1, query => 'kw,wrdl=(rk=((ns=2434-561X OR ns=2434561X))) ' }) + { state => 1, query => 'kw,wrdl=(rk=((ns=2434-561X OR ns=2434561X))) ' } + ) { - t::lib::Mocks::mock_preference('SearchWithISSNVariations', $sample->{state}); + t::lib::Mocks::mock_preference( 'SearchWithISSNVariations', $sample->{state} ); + # Test with disabled variatioms - my ($error,$query,$simple_query,$query_cgi,$query_desc,$limit,$limit_cgi,$limit_desc,$query_type) = - C4::Search::buildQuery($operators,$operands,$indexes,$limits,$sort_by,$scan,$lang); - say 'Q: > ', $query; - is($error,undef,"Error is correct"); - is($query,$sample->{query},'Search ISSN when variations is '.$sample->{state}); + my ( $error, $query, $simple_query, $query_cgi, $query_desc, $limit, $limit_cgi, $limit_desc, $query_type ) = + C4::Search::buildQuery( $operators, $operands, $indexes, $limits, $sort_by, $scan, $lang ); + say 'Q: > ', $query; + is( $error, undef, "Error is correct" ); + is( $query, $sample->{query}, 'Search ISSN when variations is ' . $sample->{state} ); my $q = Net::Z3950::ZOOM::query_create(); - my ($ccl_errcode, $ccl_errstr, $ccl_errpos) = (0,"",0); - my $res = Net::Z3950::ZOOM::query_ccl2rpn($q, $query, $config, + my ( $ccl_errcode, $ccl_errstr, $ccl_errpos ) = ( 0, "", 0 ); + my $res = Net::Z3950::ZOOM::query_ccl2rpn( + $q, $query, $config, $ccl_errcode, $ccl_errstr, $ccl_errpos ); - is($res,0,"created CCL2RPN query"); - is($ccl_errcode,0); - is($ccl_errstr,""); - is($ccl_errpos,0); + is( $res, 0, "created CCL2RPN query" ); + is( $ccl_errcode, 0 ); + is( $ccl_errstr, "" ); + is( $ccl_errpos, 0 ); Net::Z3950::ZOOM::query_destroy($q); } diff --git a/t/Search_PazPar2.t b/t/Search_PazPar2.t index 62b622d97a..66a1fa6844 100755 --- a/t/Search_PazPar2.t +++ b/t/Search_PazPar2.t @@ -1,6 +1,6 @@ #!/usr/bin/perl # -# This Koha test module is a stub! +# This Koha test module is a stub! # Add more tests here!!! use Modern::Perl; @@ -9,39 +9,39 @@ use Test::More tests => 14; use Test::Warn; BEGIN { - use_ok('C4::Search::PazPar2'); + use_ok('C4::Search::PazPar2'); } my $obj = C4::Search::PazPar2->new(); -ok ($obj, "testing new works"); +ok( $obj, "testing new works" ); my $result; warning_like { $result = $obj->init(); } - qr/400 URL must be absolute at .*C4\/Search\/PazPar2.pm/, +qr/400 URL must be absolute at .*C4\/Search\/PazPar2.pm/, "Expected relative URL warning"; -is ($result, "1", "testing init returns '1' when given no arguments"); +is( $result, "1", "testing init returns '1' when given no arguments" ); warning_like { $result = $obj->search(); } - qr/400 URL must be absolute at .*C4\/Search\/PazPar2.pm/, +qr/400 URL must be absolute at .*C4\/Search\/PazPar2.pm/, "Expected relative URL warning"; -is ($result, "1", "testing search returns '1' when given no arguments"); +is( $result, "1", "testing search returns '1' when given no arguments" ); warning_like { $result = $obj->stat(); } - qr/400 URL must be absolute at .*C4\/Search\/PazPar2.pm/, +qr/400 URL must be absolute at .*C4\/Search\/PazPar2.pm/, "Expected relative URL warning"; -is ($result, undef, "testing stat returns undef when given no arguments"); +is( $result, undef, "testing stat returns undef when given no arguments" ); warning_like { $result = $obj->show(); } - qr/400 URL must be absolute at .*C4\/Search\/PazPar2.pm/, +qr/400 URL must be absolute at .*C4\/Search\/PazPar2.pm/, "Expected relative URL warning"; -is ($result, undef, "testing show returns undef when given no arguments"); +is( $result, undef, "testing show returns undef when given no arguments" ); warning_like { $result = $obj->record(); } - qr/400 URL must be absolute at .*C4\/Search\/PazPar2.pm/, +qr/400 URL must be absolute at .*C4\/Search\/PazPar2.pm/, "Expected relative URL warning"; -is ($result, undef, "testing record returns undef when given no arguments"); +is( $result, undef, "testing record returns undef when given no arguments" ); warning_like { $result = $obj->termlist(); } - qr/400 URL must be absolute at .*C4\/Search\/PazPar2.pm/, +qr/400 URL must be absolute at .*C4\/Search\/PazPar2.pm/, "Expected relative URL warning"; -is ($result, undef, "testing termlist returns undef when given no arguments"); +is( $result, undef, "testing termlist returns undef when given no arguments" ); diff --git a/t/Serials/GetNextSeq.t b/t/Serials/GetNextSeq.t index 63a7f3c73e..05526a59ad 100755 --- a/t/Serials/GetNextSeq.t +++ b/t/Serials/GetNextSeq.t @@ -6,254 +6,258 @@ use C4::Serials qw( GetNextSeq ); # TEST CASE 1 - 1 variable, from 1 to 4 my $subscription = { - lastvalue1 => 1, lastvalue2 => 1, lastvalue3 => 1, - innerloop1 => 0, innerloop2 => 0, innerloop3 => 0, + lastvalue1 => 1, lastvalue2 => 1, lastvalue3 => 1, + innerloop1 => 0, innerloop2 => 0, innerloop3 => 0, skip_serialseq => 0, - irregularity => '', - locale => 'en', + irregularity => '', + locale => 'en', }; my $pattern = { - add1 => 1, add2 => 0, add3 => 0, - every1 => 1, every2 => 0, every3 => 0, - whenmorethan1 => 4, whenmorethan2 => 0, whenmorethan3 => 0, - setto1 => 1, setto2 => 0, setto3 => 0, + add1 => 1, add2 => 0, add3 => 0, + every1 => 1, every2 => 0, every3 => 0, + whenmorethan1 => 4, whenmorethan2 => 0, whenmorethan3 => 0, + setto1 => 1, setto2 => 0, setto3 => 0, numberingmethod => 'X: {X}', - numbering1 => '', - numbering2 => '', - numbering3 => '', + numbering1 => '', + numbering2 => '', + numbering3 => '', }; -my $seq = _next_seq($subscription, $pattern); -is($seq, 'X: 2'); -$seq = _next_seq($subscription, $pattern); -is($seq, 'X: 3'); -$seq = _next_seq($subscription, $pattern); -is($seq, 'X: 4'); -$seq = _next_seq($subscription, $pattern); -is($seq, 'X: 1'); -$seq = _next_seq($subscription, $pattern); -is($seq, 'X: 2'); +my $seq = _next_seq( $subscription, $pattern ); +is( $seq, 'X: 2' ); +$seq = _next_seq( $subscription, $pattern ); +is( $seq, 'X: 3' ); +$seq = _next_seq( $subscription, $pattern ); +is( $seq, 'X: 4' ); +$seq = _next_seq( $subscription, $pattern ); +is( $seq, 'X: 1' ); +$seq = _next_seq( $subscription, $pattern ); +is( $seq, 'X: 2' ); # TEST CASE 2 - 1 variable, use 'dayname' numbering, from 1 to 7 $subscription = { - lastvalue1 => 1, lastvalue2 => 1, lastvalue3 => 1, - innerloop1 => 0, innerloop2 => 0, innerloop3 => 0, + lastvalue1 => 1, lastvalue2 => 1, lastvalue3 => 1, + innerloop1 => 0, innerloop2 => 0, innerloop3 => 0, skip_serialseq => 0, - irregularity => '', - locale => 'C', + irregularity => '', + locale => 'C', }; $pattern = { - add1 => 1, add2 => 1, add3 => 0, - every1 => 1, every2 => 1, every3 => 0, - whenmorethan1 => 7, whenmorethan2 => 7, whenmorethan3 => 0, - setto1 => 1, setto2 => 1, setto3 => 0, + add1 => 1, add2 => 1, add3 => 0, + every1 => 1, every2 => 1, every3 => 0, + whenmorethan1 => 7, whenmorethan2 => 7, whenmorethan3 => 0, + setto1 => 1, setto2 => 1, setto3 => 0, numberingmethod => 'dayname: {X} | dayabrv: {Y}', - numbering1 => 'dayname', - numbering2 => 'dayabrv', - numbering3 => '', + numbering1 => 'dayname', + numbering2 => 'dayabrv', + numbering3 => '', }; -$seq = _next_seq($subscription, $pattern); -is($seq, 'dayname: Tuesday | dayabrv: Tue'); -$seq = _next_seq($subscription, $pattern); -is($seq, 'dayname: Wednesday | dayabrv: Wed'); -$seq = _next_seq($subscription, $pattern); -is($seq, 'dayname: Thursday | dayabrv: Thu'); -$seq = _next_seq($subscription, $pattern); -is($seq, 'dayname: Friday | dayabrv: Fri'); -$seq = _next_seq($subscription, $pattern); -is($seq, 'dayname: Saturday | dayabrv: Sat'); -$seq = _next_seq($subscription, $pattern); -is($seq, 'dayname: Sunday | dayabrv: Sun'); -$seq = _next_seq($subscription, $pattern); -is($seq, 'dayname: Monday | dayabrv: Mon'); +$seq = _next_seq( $subscription, $pattern ); +is( $seq, 'dayname: Tuesday | dayabrv: Tue' ); +$seq = _next_seq( $subscription, $pattern ); +is( $seq, 'dayname: Wednesday | dayabrv: Wed' ); +$seq = _next_seq( $subscription, $pattern ); +is( $seq, 'dayname: Thursday | dayabrv: Thu' ); +$seq = _next_seq( $subscription, $pattern ); +is( $seq, 'dayname: Friday | dayabrv: Fri' ); +$seq = _next_seq( $subscription, $pattern ); +is( $seq, 'dayname: Saturday | dayabrv: Sat' ); +$seq = _next_seq( $subscription, $pattern ); +is( $seq, 'dayname: Sunday | dayabrv: Sun' ); +$seq = _next_seq( $subscription, $pattern ); +is( $seq, 'dayname: Monday | dayabrv: Mon' ); # TEST CASE 3 - 1 variable, use 'monthname' numbering, from 0 to 11 by step of 2 $subscription = { - lastvalue1 => 0, lastvalue2 => 0, lastvalue3 => 0, - innerloop1 => 0, innerloop2 => 0, innerloop3 => 0, + lastvalue1 => 0, lastvalue2 => 0, lastvalue3 => 0, + innerloop1 => 0, innerloop2 => 0, innerloop3 => 0, skip_serialseq => 0, - irregularity => '', - locale => 'C', # locale set to 'C' to ensure we'll have english strings + irregularity => '', + locale => 'C', # locale set to 'C' to ensure we'll have english strings }; $pattern = { - add1 => 2, add2 => 2, add3 => 0, - every1 => 1, every2 => 1, every3 => 0, - whenmorethan1 => 11, whenmorethan2 => 11, whenmorethan3 => 0, - setto1 => 0, setto2 => 0, setto3 => 0, + add1 => 2, add2 => 2, add3 => 0, + every1 => 1, every2 => 1, every3 => 0, + whenmorethan1 => 11, whenmorethan2 => 11, whenmorethan3 => 0, + setto1 => 0, setto2 => 0, setto3 => 0, numberingmethod => 'monthname: {X} | monthabrv: {Y}', - numbering1 => 'monthname', - numbering2 => 'monthabrv', - numbering3 => '', + numbering1 => 'monthname', + numbering2 => 'monthabrv', + numbering3 => '', }; -$seq = _next_seq($subscription, $pattern); -is($seq, 'monthname: March | monthabrv: Mar'); -$seq = _next_seq($subscription, $pattern); -is($seq, 'monthname: May | monthabrv: May'); -$seq = _next_seq($subscription, $pattern); -is($seq, 'monthname: July | monthabrv: Jul'); -$seq = _next_seq($subscription, $pattern); -is($seq, 'monthname: September | monthabrv: Sep'); -$seq = _next_seq($subscription, $pattern); -is($seq, 'monthname: November | monthabrv: Nov'); -$seq = _next_seq($subscription, $pattern); -is($seq, 'monthname: January | monthabrv: Jan'); -$seq = _next_seq($subscription, $pattern); -is($seq, 'monthname: March | monthabrv: Mar'); +$seq = _next_seq( $subscription, $pattern ); +is( $seq, 'monthname: March | monthabrv: Mar' ); +$seq = _next_seq( $subscription, $pattern ); +is( $seq, 'monthname: May | monthabrv: May' ); +$seq = _next_seq( $subscription, $pattern ); +is( $seq, 'monthname: July | monthabrv: Jul' ); +$seq = _next_seq( $subscription, $pattern ); +is( $seq, 'monthname: September | monthabrv: Sep' ); +$seq = _next_seq( $subscription, $pattern ); +is( $seq, 'monthname: November | monthabrv: Nov' ); +$seq = _next_seq( $subscription, $pattern ); +is( $seq, 'monthname: January | monthabrv: Jan' ); +$seq = _next_seq( $subscription, $pattern ); +is( $seq, 'monthname: March | monthabrv: Mar' ); # TEST CASE 4 - 1 variable, use 'season' numbering, from 0 to 3 # Months starts at 0, this implies subscription's lastvalue1 should be 0, # together with setto1 and whenmorethan1 should be 11 $subscription = { - lastvalue1 => 0, lastvalue2 => 0, lastvalue3 => 0, - innerloop1 => 0, innerloop2 => 0, innerloop3 => 0, + lastvalue1 => 0, lastvalue2 => 0, lastvalue3 => 0, + innerloop1 => 0, innerloop2 => 0, innerloop3 => 0, skip_serialseq => 0, - irregularity => '', - locale => 'C', # locale set to 'C' to ensure we'll have english strings + irregularity => '', + locale => 'C', # locale set to 'C' to ensure we'll have english strings }; $pattern = { - add1 => 1, add2 => 1, add3 => 0, - every1 => 1, every2 => 1, every3 => 0, - whenmorethan1 => 3, whenmorethan2 => 3, whenmorethan3 => 0, - setto1 => 0, setto2 => 0, setto3 => 0, + add1 => 1, add2 => 1, add3 => 0, + every1 => 1, every2 => 1, every3 => 0, + whenmorethan1 => 3, whenmorethan2 => 3, whenmorethan3 => 0, + setto1 => 0, setto2 => 0, setto3 => 0, numberingmethod => 'season: {X} | seasonabrv: {Y}', - numbering1 => 'season', - numbering2 => 'seasonabrv', - numbering3 => '', + numbering1 => 'season', + numbering2 => 'seasonabrv', + numbering3 => '', }; -$seq = _next_seq($subscription, $pattern); -is($seq, 'season: Summer | seasonabrv: Sum'); -$seq = _next_seq($subscription, $pattern); -is($seq, 'season: Fall | seasonabrv: Fal'); -$seq = _next_seq($subscription, $pattern); -is($seq, 'season: Winter | seasonabrv: Win'); -$seq = _next_seq($subscription, $pattern); -is($seq, 'season: Spring | seasonabrv: Spr'); -$seq = _next_seq($subscription, $pattern); -is($seq, 'season: Summer | seasonabrv: Sum'); +$seq = _next_seq( $subscription, $pattern ); +is( $seq, 'season: Summer | seasonabrv: Sum' ); +$seq = _next_seq( $subscription, $pattern ); +is( $seq, 'season: Fall | seasonabrv: Fal' ); +$seq = _next_seq( $subscription, $pattern ); +is( $seq, 'season: Winter | seasonabrv: Win' ); +$seq = _next_seq( $subscription, $pattern ); +is( $seq, 'season: Spring | seasonabrv: Spr' ); +$seq = _next_seq( $subscription, $pattern ); +is( $seq, 'season: Summer | seasonabrv: Sum' ); # TEST CASE 5 - 2 variables, from 1 to 12, and from 1 to 4 $subscription = { - lastvalue1 => 1, lastvalue2 => 1, lastvalue3 => 1, - innerloop1 => 0, innerloop2 => 0, innerloop3 => 0, + lastvalue1 => 1, lastvalue2 => 1, lastvalue3 => 1, + innerloop1 => 0, innerloop2 => 0, innerloop3 => 0, skip_serialseq => 0, - irregularity => '', - locale => 'C', # locale set to 'C' to ensure we'll have english strings + irregularity => '', + locale => 'C', # locale set to 'C' to ensure we'll have english strings }; $pattern = { - add1 => 1, add2 => 1, add3 => 0, - every1 => 1, every2 => 4, every3 => 0, - whenmorethan1 => 4, whenmorethan2 => 12, whenmorethan3 => 0, - setto1 => 1, setto2 => 1, setto3 => 0, + add1 => 1, add2 => 1, add3 => 0, + every1 => 1, every2 => 4, every3 => 0, + whenmorethan1 => 4, whenmorethan2 => 12, whenmorethan3 => 0, + setto1 => 1, setto2 => 1, setto3 => 0, numberingmethod => 'Y: {Y}, X: {X}', - numbering1 => '', - numbering2 => '', - numbering3 => '', + numbering1 => '', + numbering2 => '', + numbering3 => '', }; -$seq = _next_seq($subscription, $pattern); -is($seq, 'Y: 1, X: 2'); -$seq = _next_seq($subscription, $pattern); -is($seq, 'Y: 1, X: 3'); -$seq = _next_seq($subscription, $pattern); -is($seq, 'Y: 1, X: 4'); -$seq = _next_seq($subscription, $pattern); -is($seq, 'Y: 2, X: 1'); -$seq = _next_seq($subscription, $pattern); -is($seq, 'Y: 2, X: 2'); +$seq = _next_seq( $subscription, $pattern ); +is( $seq, 'Y: 1, X: 2' ); +$seq = _next_seq( $subscription, $pattern ); +is( $seq, 'Y: 1, X: 3' ); +$seq = _next_seq( $subscription, $pattern ); +is( $seq, 'Y: 1, X: 4' ); +$seq = _next_seq( $subscription, $pattern ); +is( $seq, 'Y: 2, X: 1' ); +$seq = _next_seq( $subscription, $pattern ); +is( $seq, 'Y: 2, X: 2' ); + # Back to the future -for (1..39) { - $seq = _next_seq($subscription, $pattern); +for ( 1 .. 39 ) { + $seq = _next_seq( $subscription, $pattern ); } -$seq = _next_seq($subscription, $pattern); -is($seq, 'Y: 12, X: 2'); -$seq = _next_seq($subscription, $pattern); -is($seq, 'Y: 12, X: 3'); -$seq = _next_seq($subscription, $pattern); -is($seq, 'Y: 12, X: 4'); -$seq = _next_seq($subscription, $pattern); -is($seq, 'Y: 1, X: 1'); +$seq = _next_seq( $subscription, $pattern ); +is( $seq, 'Y: 12, X: 2' ); +$seq = _next_seq( $subscription, $pattern ); +is( $seq, 'Y: 12, X: 3' ); +$seq = _next_seq( $subscription, $pattern ); +is( $seq, 'Y: 12, X: 4' ); +$seq = _next_seq( $subscription, $pattern ); +is( $seq, 'Y: 1, X: 1' ); # TEST CASE 6 - 3 variables, from 1 to 12, from 1 to 8, and from 1 to 4 $subscription = { - lastvalue1 => 1, lastvalue2 => 1, lastvalue3 => 1, - innerloop1 => 0, innerloop2 => 0, innerloop3 => 0, + lastvalue1 => 1, lastvalue2 => 1, lastvalue3 => 1, + innerloop1 => 0, innerloop2 => 0, innerloop3 => 0, skip_serialseq => 0, - irregularity => '', - locale => 'C', # locale set to 'C' to ensure we'll have english strings + irregularity => '', + locale => 'C', # locale set to 'C' to ensure we'll have english strings }; $pattern = { - add1 => 1, add2 => 1, add3 => 1, - every1 => 1, every2 => 4, every3 => 32, - whenmorethan1 => 4, whenmorethan2 => 8, whenmorethan3 => 12, - setto1 => 1, setto2 => 1, setto3 => 1, + add1 => 1, add2 => 1, add3 => 1, + every1 => 1, every2 => 4, every3 => 32, + whenmorethan1 => 4, whenmorethan2 => 8, whenmorethan3 => 12, + setto1 => 1, setto2 => 1, setto3 => 1, numberingmethod => 'Z: {Z}, Y: {Y}, X: {X}', - numbering1 => '', - numbering2 => '', - numbering3 => '', + numbering1 => '', + numbering2 => '', + numbering3 => '', }; -$seq = _next_seq($subscription, $pattern); -is($seq, 'Z: 1, Y: 1, X: 2'); -$seq = _next_seq($subscription, $pattern); -is($seq, 'Z: 1, Y: 1, X: 3'); -$seq = _next_seq($subscription, $pattern); -is($seq, 'Z: 1, Y: 1, X: 4'); -$seq = _next_seq($subscription, $pattern); -is($seq, 'Z: 1, Y: 2, X: 1'); -for (1..24) { - $seq = _next_seq($subscription, $pattern); +$seq = _next_seq( $subscription, $pattern ); +is( $seq, 'Z: 1, Y: 1, X: 2' ); +$seq = _next_seq( $subscription, $pattern ); +is( $seq, 'Z: 1, Y: 1, X: 3' ); +$seq = _next_seq( $subscription, $pattern ); +is( $seq, 'Z: 1, Y: 1, X: 4' ); +$seq = _next_seq( $subscription, $pattern ); +is( $seq, 'Z: 1, Y: 2, X: 1' ); + +for ( 1 .. 24 ) { + $seq = _next_seq( $subscription, $pattern ); } -$seq = _next_seq($subscription, $pattern); -is($seq, 'Z: 1, Y: 8, X: 2'); -$seq = _next_seq($subscription, $pattern); -is($seq, 'Z: 1, Y: 8, X: 3'); -$seq = _next_seq($subscription, $pattern); -is($seq, 'Z: 1, Y: 8, X: 4'); -$seq = _next_seq($subscription, $pattern); -is($seq, 'Z: 2, Y: 1, X: 1'); -for (1..350) { - $seq = _next_seq($subscription, $pattern); +$seq = _next_seq( $subscription, $pattern ); +is( $seq, 'Z: 1, Y: 8, X: 2' ); +$seq = _next_seq( $subscription, $pattern ); +is( $seq, 'Z: 1, Y: 8, X: 3' ); +$seq = _next_seq( $subscription, $pattern ); +is( $seq, 'Z: 1, Y: 8, X: 4' ); +$seq = _next_seq( $subscription, $pattern ); +is( $seq, 'Z: 2, Y: 1, X: 1' ); + +for ( 1 .. 350 ) { + $seq = _next_seq( $subscription, $pattern ); } -$seq = _next_seq($subscription, $pattern); -is($seq, 'Z: 12, Y: 8, X: 4'); -$seq = _next_seq($subscription, $pattern); -is($seq, 'Z: 1, Y: 1, X: 1'); +$seq = _next_seq( $subscription, $pattern ); +is( $seq, 'Z: 12, Y: 8, X: 4' ); +$seq = _next_seq( $subscription, $pattern ); +is( $seq, 'Z: 1, Y: 1, X: 1' ); # TEST CASE 7 . Specify how many issues to count forward, 1 variable, from 1 to 4 $subscription = { - lastvalue1 => 1, lastvalue2 => 1, lastvalue3 => 1, - innerloop1 => 0, innerloop2 => 0, innerloop3 => 0, + lastvalue1 => 1, lastvalue2 => 1, lastvalue3 => 1, + innerloop1 => 0, innerloop2 => 0, innerloop3 => 0, skip_serialseq => 0, - irregularity => '', - locale => 'en', + irregularity => '', + locale => 'en', }; $pattern = { - add1 => 1, add2 => 0, add3 => 0, - every1 => 1, every2 => 0, every3 => 0, - whenmorethan1 => 4, whenmorethan2 => 0, whenmorethan3 => 0, - setto1 => 1, setto2 => 0, setto3 => 0, + add1 => 1, add2 => 0, add3 => 0, + every1 => 1, every2 => 0, every3 => 0, + whenmorethan1 => 4, whenmorethan2 => 0, whenmorethan3 => 0, + setto1 => 1, setto2 => 0, setto3 => 0, numberingmethod => 'X: {X}', - numbering1 => '', - numbering2 => '', - numbering3 => '', + numbering1 => '', + numbering2 => '', + numbering3 => '', }; -$seq = _next_seq($subscription, $pattern, 1); -is($seq, 'X: 2'); -$seq = _next_seq($subscription, $pattern, 2); -is($seq, 'X: 4'); -$seq = _next_seq($subscription, $pattern, 2); -is($seq, 'X: 2'); +$seq = _next_seq( $subscription, $pattern, 1 ); +is( $seq, 'X: 2' ); +$seq = _next_seq( $subscription, $pattern, 2 ); +is( $seq, 'X: 4' ); +$seq = _next_seq( $subscription, $pattern, 2 ); +is( $seq, 'X: 2' ); sub _next_seq { - my ($subscription, $pattern, $count_forward) = @_; + my ( $subscription, $pattern, $count_forward ) = @_; my $seq; - ($seq, $subscription->{lastvalue1}, $subscription->{lastvalue2}, + ( + $seq, $subscription->{lastvalue1}, $subscription->{lastvalue2}, $subscription->{lastvalue3}, $subscription->{innerloop1}, - $subscription->{innerloop2}, $subscription->{innerloop3}) = - GetNextSeq($subscription, $pattern, undef, undef, $count_forward); + $subscription->{innerloop2}, $subscription->{innerloop3} + ) = GetNextSeq( $subscription, $pattern, undef, undef, $count_forward ); return $seq; } diff --git a/t/Serials/ModSerialStatus.t b/t/Serials/ModSerialStatus.t index 480b84f4c1..ee5f40b731 100755 --- a/t/Serials/ModSerialStatus.t +++ b/t/Serials/ModSerialStatus.t @@ -28,11 +28,11 @@ use C4::Serials; # Testing C4::Serials::_handle_seqno my $list = '2017 (No. 8); 2017 (No. 9); 2017 (No. 10)'; -is( C4::Serials::_handle_seqno( '2017 (No. 8)', $list ), $list, 'Not added 8' ); -is( C4::Serials::_handle_seqno( '2017 (No. 9)', $list ), $list, 'Not added 9' ); -is( C4::Serials::_handle_seqno( '2017 (No. 10)', $list ), $list, 'Not added 10' ); -is( C4::Serials::_handle_seqno( '2017 (No. 11)', $list ), $list.'; 2017 (No. 11)', 'Added 11' ); -is( C4::Serials::_handle_seqno( '2017 (No. 7)', $list, 'REMOVE'), $list, 'Not removed 7' ); -is( C4::Serials::_handle_seqno( '2017 (No. 10)', $list, 'REMOVE') !~ /\(10\)/, 1, 'Removed 10' ); -is( C4::Serials::_handle_seqno( '2017 (No. 8)', $list, 'CHECK'), 1, 'Found 8' ); -is( C4::Serials::_handle_seqno( '2017 (No. 11)', $list, 'CHECK'), q{}, 'Not found 11' ); +is( C4::Serials::_handle_seqno( '2017 (No. 8)', $list ), $list, 'Not added 8' ); +is( C4::Serials::_handle_seqno( '2017 (No. 9)', $list ), $list, 'Not added 9' ); +is( C4::Serials::_handle_seqno( '2017 (No. 10)', $list ), $list, 'Not added 10' ); +is( C4::Serials::_handle_seqno( '2017 (No. 11)', $list ), $list . '; 2017 (No. 11)', 'Added 11' ); +is( C4::Serials::_handle_seqno( '2017 (No. 7)', $list, 'REMOVE' ), $list, 'Not removed 7' ); +is( C4::Serials::_handle_seqno( '2017 (No. 10)', $list, 'REMOVE' ) !~ /\(10\)/, 1, 'Removed 10' ); +is( C4::Serials::_handle_seqno( '2017 (No. 8)', $list, 'CHECK' ), 1, 'Found 8' ); +is( C4::Serials::_handle_seqno( '2017 (No. 11)', $list, 'CHECK' ), q{}, 'Not found 11' ); diff --git a/t/SimpleMARC.t b/t/SimpleMARC.t index 597ec8c412..589f948cab 100755 --- a/t/SimpleMARC.t +++ b/t/SimpleMARC.t @@ -77,7 +77,7 @@ subtest 'field_exists' => sub { # read_field subtest 'read_field' => sub { - plan tests => 2; + plan tests => 2; subtest 'read subfield' => sub { plan tests => 6; my $record = new_record; @@ -93,8 +93,7 @@ subtest 'read_field' => sub { ) ); - my @fields_650a = - read_field( { record => $record, field => '650', subfield => 'a' } ); + my @fields_650a = read_field( { record => $record, field => '650', subfield => 'a' } ); is_deeply( $fields_650a[0], 'Computer programming.', 'first 650$a' ); is_deeply( $fields_650a[1], 'Computer algorithms.', 'second 650$a' ); is_deeply( @@ -190,29 +189,21 @@ subtest 'read_field' => sub { 'Get the all subfield values for the first field 650' ); is_deeply( - [ - read_field( - { record => $record, field => '650', field_numbers => [2] } - ) - ], + [ read_field( { record => $record, field => '650', field_numbers => [2] } ) ], [ 'Computer algorithms.', '463' ], 'Get the all subfield values for the second field 650' ); is_deeply( - [ - read_field( - { record => $record, field => '650', field_numbers => [3] } - ) - ], + [ read_field( { record => $record, field => '650', field_numbers => [3] } ) ], [], -'Get the all subfield values for the third field 650 which does not exist' + 'Get the all subfield values for the third field 650 which does not exist' ); }; }; # update_field subtest 'update_field' => sub { - plan tests => 1; + plan tests => 1; subtest 'update subfield' => sub { plan tests => 6; my $record = new_record; @@ -226,11 +217,7 @@ subtest 'update_field' => sub { } ); is_deeply( - [ - read_field( - { record => $record, field => '952', subfield => 'p' } - ) - ], + [ read_field( { record => $record, field => '952', subfield => 'p' } ) ], ['3010023918'], 'update existing subfield 952$p' ); @@ -252,18 +239,12 @@ subtest 'update_field' => sub { } ); is_deeply( - [ - read_field( - { record => $record, field => '952', subfield => 'p' } - ) - ], + [ read_field( { record => $record, field => '952', subfield => 'p' } ) ], ['3010023918'], 'create subfield 952$p' ); is_deeply( - read_field( - { record => $record, field => '952', subfield => 'y' } - ), + read_field( { record => $record, field => '952', subfield => 'y' } ), 'BK', 'create subfield 952$k on existing 952 field' ); @@ -284,8 +265,7 @@ subtest 'update_field' => sub { values => ['3010023919'] } ); - my @fields_952p = - read_field( { record => $record, field => '952', subfield => 'p' } ); + my @fields_952p = read_field( { record => $record, field => '952', subfield => 'p' } ); is_deeply( \@fields_952p, [ '3010023919', '3010023919' ], @@ -300,8 +280,7 @@ subtest 'update_field' => sub { values => [ '3010023917', '3010023918' ] } ); - @fields_952p = - read_field( { record => $record, field => '952', subfield => 'p' } ); + @fields_952p = read_field( { record => $record, field => '952', subfield => 'p' } ); is_deeply( \@fields_952p, [ '3010023917', '3010023918' ], @@ -313,11 +292,10 @@ subtest 'update_field' => sub { record => $record, field => '952', subfield => '0', - values => [ '654321' ] + values => ['654321'] } ); - my @fields_9520 = - read_field( { record => $record, field => '952', subfield => '0' } ); + my @fields_9520 = read_field( { record => $record, field => '952', subfield => '0' } ); is_deeply( \@fields_9520, [ '654321', '654321' ], @@ -329,7 +307,7 @@ subtest 'update_field' => sub { # copy_field - subfield subtest 'copy_field' => sub { - plan tests => 2; + plan tests => 2; subtest 'copy subfield' => sub { plan tests => 21; my $record = new_record; @@ -350,28 +328,18 @@ subtest 'copy_field' => sub { } ); is_deeply( - [ - read_field( - { record => $record, field => '245', subfield => 'a' } - ) - ], + [ read_field( { record => $record, field => '245', subfield => 'a' } ) ], ['The art of computer programming'], 'After copy 245$a still exists' ); is_deeply( - [ - read_field( - { record => $record, field => '246', subfield => 'a' } - ) - ], + [ read_field( { record => $record, field => '246', subfield => 'a' } ) ], ['The art of computer programming'], '246$a is a new field' ); delete_field( { record => $record, field => '246' } ); is_deeply( - field_exists( - { record => $record, field => '246', subfield => 'a' } - ), + field_exists( { record => $record, field => '246', subfield => 'a' } ), [], '246$a does not exist anymore' ); @@ -385,8 +353,7 @@ subtest 'copy_field' => sub { to_subfield => 'a' } ); - my @fields_651a = - read_field( { record => $record, field => '651', subfield => 'a' } ); + my @fields_651a = read_field( { record => $record, field => '651', subfield => 'a' } ); is_deeply( \@fields_651a, [ 'Computer algorithms.', 'Computer programming.' ], @@ -405,11 +372,7 @@ subtest 'copy_field' => sub { } ); is_deeply( - [ - read_field( - { record => $record, field => '651', subfield => 'a' } - ) - ], + [ read_field( { record => $record, field => '651', subfield => 'a' } ) ], ['Computer programming.'], 'Copy first field 650$a' ); @@ -426,12 +389,8 @@ subtest 'copy_field' => sub { } ); is_deeply( - [ - read_field( - { record => $record, field => '651', subfield => 'a' } - ) - ], - ['Computer programming.', 'Computer algorithms.'], + [ read_field( { record => $record, field => '651', subfield => 'a' } ) ], + [ 'Computer programming.', 'Computer algorithms.' ], 'Copy second field 650$a' ); delete_field( { record => $record, field => '651' } ); @@ -443,11 +402,10 @@ subtest 'copy_field' => sub { from_subfield => 'a', to_field => '651', to_subfield => 'a', - regex => { search => 'Computer', replace => 'The art of' } + regex => { search => 'Computer', replace => 'The art of' } } ); - @fields_651a = - read_field( { record => $record, field => '651', subfield => 'a' } ); + @fields_651a = read_field( { record => $record, field => '651', subfield => 'a' } ); is_deeply( \@fields_651a, [ 'The art of algorithms.', 'The art of programming.' ], @@ -462,11 +420,10 @@ subtest 'copy_field' => sub { from_subfield => 'a', to_field => '651', to_subfield => 'a', - regex => { search => 'Computer', replace => 'The mistake of' } + regex => { search => 'Computer', replace => 'The mistake of' } } ); - @fields_651a = - read_field( { record => $record, field => '651', subfield => 'a' } ); + @fields_651a = read_field( { record => $record, field => '651', subfield => 'a' } ); is_deeply( \@fields_651a, [ 'The mistake of algorithms.', 'The mistake of programming.' ], @@ -481,11 +438,10 @@ subtest 'copy_field' => sub { from_subfield => 'a', to_field => '651', to_subfield => 'a', - regex => { search => 'Computer', replace => 'The art of' } + regex => { search => 'Computer', replace => 'The art of' } } ); - @fields_651a = - read_field( { record => $record, field => '651', subfield => 'a' } ); + @fields_651a = read_field( { record => $record, field => '651', subfield => 'a' } ); is_deeply( \@fields_651a, [ 'The art of algorithms.', 'The art of programming.', ], @@ -500,12 +456,11 @@ subtest 'copy_field' => sub { from_subfield => 'a', to_field => '651', to_subfield => 'a', - regex => { search => 'Computer', replace => 'The art of' }, + regex => { search => 'Computer', replace => 'The art of' }, field_numbers => [1] } ); - @fields_651a = - read_field( { record => $record, field => '651', subfield => 'a' } ); + @fields_651a = read_field( { record => $record, field => '651', subfield => 'a' } ); is_deeply( \@fields_651a, [ 'The art of programming.', ], @@ -532,8 +487,7 @@ subtest 'copy_field' => sub { regex => { search => 'o', replace => 'foo' } } ); - my @fields_652a = - read_field( { record => $record, field => '652', subfield => 'a' } ); + my @fields_652a = read_field( { record => $record, field => '652', subfield => 'a' } ); is_deeply( \@fields_652a, [ 'Cfoomputer algorithms.', 'Cfoomputer programming.' ], @@ -547,11 +501,10 @@ subtest 'copy_field' => sub { from_subfield => 'a', to_field => '653', to_subfield => 'a', - regex => { search => 'o', replace => 'foo', modifiers => 'g' } + regex => { search => 'o', replace => 'foo', modifiers => 'g' } } ); - my @fields_653a = - read_field( { record => $record, field => '653', subfield => 'a' } ); + my @fields_653a = read_field( { record => $record, field => '653', subfield => 'a' } ); is_deeply( \@fields_653a, [ 'Cfoomputer algfoorithms.', 'Cfoomputer prfoogramming.' ], @@ -565,11 +518,10 @@ subtest 'copy_field' => sub { from_subfield => 'a', to_field => '654', to_subfield => 'a', - regex => { search => 'O', replace => 'foo', modifiers => 'i' } + regex => { search => 'O', replace => 'foo', modifiers => 'i' } } ); - my @fields_654a = - read_field( { record => $record, field => '654', subfield => 'a' } ); + my @fields_654a = read_field( { record => $record, field => '654', subfield => 'a' } ); is_deeply( \@fields_654a, [ 'Cfoomputer algorithms.', 'Cfoomputer programming.' ], @@ -583,11 +535,10 @@ subtest 'copy_field' => sub { from_subfield => 'a', to_field => '655', to_subfield => 'a', - regex => { search => 'O', replace => 'foo', modifiers => 'gi' } + regex => { search => 'O', replace => 'foo', modifiers => 'gi' } } ); - my @fields_655a = - read_field( { record => $record, field => '655', subfield => 'a' } ); + my @fields_655a = read_field( { record => $record, field => '655', subfield => 'a' } ); is_deeply( \@fields_655a, [ 'Cfoomputer algfoorithms.', 'Cfoomputer prfoogramming.' ], @@ -612,8 +563,8 @@ subtest 'copy_field' => sub { to_subfield => 'd' } ); - my @fields_952d = - read_field( { record => $record, field => '952', subfield => 'd' } ); + my @fields_952d = read_field( { record => $record, field => '952', subfield => 'd' } ); + # FIXME We need a new action "duplicate" if we don't want to modify the original field is_deeply( \@fields_952d, @@ -630,10 +581,11 @@ subtest 'copy_field' => sub { to_subfield => '9' } ); - my @fields_9999 = - read_field( { record => $record, field => '999', subfield => '9' } ); - is_deeply( \@fields_9999, [], - 'copy a nonexistent subfield does not create a new one' ); + my @fields_9999 = read_field( { record => $record, field => '999', subfield => '9' } ); + is_deeply( + \@fields_9999, [], + 'copy a nonexistent subfield does not create a new one' + ); $record = new_record; copy_field( @@ -647,12 +599,8 @@ subtest 'copy_field' => sub { } ); is_deeply( - [ - read_field( - { record => $record, field => '245', subfield => 'a' } - ) - ], - ['The art of computer programming', 'BEGIN The art of computer programming'], + [ read_field( { record => $record, field => '245', subfield => 'a' } ) ], + [ 'The art of computer programming', 'BEGIN The art of computer programming' ], 'Update a subfield: add a string at the beginning' ); @@ -668,12 +616,8 @@ subtest 'copy_field' => sub { } ); is_deeply( - [ - read_field( - { record => $record, field => '245', subfield => 'a' } - ) - ], - ['The art of computer programming', 'The art of computer programming END'], + [ read_field( { record => $record, field => '245', subfield => 'a' } ) ], + [ 'The art of computer programming', 'The art of computer programming END' ], 'Update a subfield: add a string at the end' ); @@ -689,12 +633,8 @@ subtest 'copy_field' => sub { } ); is_deeply( - [ - read_field( - { record => $record, field => '245', subfield => 'a' } - ) - ], - ['The art of computer programming', 'The smart art of computer programming'], + [ read_field( { record => $record, field => '245', subfield => 'a' } ) ], + [ 'The art of computer programming', 'The smart art of computer programming' ], 'Update a subfield: use capture groups' ); @@ -710,11 +650,7 @@ subtest 'copy_field' => sub { ); is_deeply( - [ - read_field( - { record => $record, field => '650' } - ) - ], + [ read_field( { record => $record, field => '650' } ) ], [ 'Computer programming.', '462', 'Donald E. Knuth.' ], 'Copy a subfield to an existent field but inexistent subfield' ); @@ -731,11 +667,7 @@ subtest 'copy_field' => sub { ); is_deeply( - [ - read_field( - { record => $record, field => '650' } - ) - ], + [ read_field( { record => $record, field => '650' } ) ], [ 'Computer programming.', '462', 'Donald E. Knuth.' ], 'Copy a subfield to an existent field / subfield' ); @@ -753,42 +685,25 @@ subtest 'copy_field' => sub { ); #- copy all fields - copy_field( - { record => $record, from_field => '952', to_field => '953' } ); + copy_field( { record => $record, from_field => '952', to_field => '953' } ); my @fields_952 = read_field( { record => $record, field => '952' } ); is_deeply( - [ - read_field( - { record => $record, field => '952', field_numbers => [1] } - ) - ], + [ read_field( { record => $record, field => '952', field_numbers => [1] } ) ], [ '3010023917', 'BK', 'GEN', '2001-06-25' ], "copy all: original first field still exists" ); is_deeply( - [ - read_field( - { record => $record, field => '952', field_numbers => [2] } - ) - ], + [ read_field( { record => $record, field => '952', field_numbers => [2] } ) ], [ '3010023918', 'CD' ], "copy all: original second field still exists" ); is_deeply( - [ - read_field( - { record => $record, field => '953', field_numbers => [1] } - ) - ], + [ read_field( { record => $record, field => '953', field_numbers => [1] } ) ], [ '3010023917', 'BK', 'GEN', '2001-06-25' ], "copy all: first original fields has been copied" ); is_deeply( - [ - read_field( - { record => $record, field => '953', field_numbers => [2] } - ) - ], + [ read_field( { record => $record, field => '953', field_numbers => [2] } ) ], [ '3010023918', 'CD' ], "copy all: second original fields has been copied" ); @@ -803,20 +718,12 @@ subtest 'copy_field' => sub { } ); is_deeply( - [ - read_field( - { record => $record, field => '953', field_numbers => [1] } - ) - ], + [ read_field( { record => $record, field => '953', field_numbers => [1] } ) ], [ '3010023917', 'BK', 'GEN', '2001-06-25' ], "copy first: first original fields has been copied" ); is_deeply( - [ - read_field( - { record => $record, field => '953', field_numbers => [2] } - ) - ], + [ read_field( { record => $record, field => '953', field_numbers => [2] } ) ], [ '3010023918', 'CD' ], "copy first: second original fields has been copied" ); @@ -845,38 +752,22 @@ subtest 'copy_field' => sub { } ); is_deeply( - [ - read_field( - { record => $record, field => '952', field_numbers => [1] } - ) - ], + [ read_field( { record => $record, field => '952', field_numbers => [1] } ) ], [ '3010023917', 'BK', 'GEN', '2001-06-25' ], "copy all with regex: original first field still exists" ); is_deeply( - [ - read_field( - { record => $record, field => '952', field_numbers => [2] } - ) - ], + [ read_field( { record => $record, field => '952', field_numbers => [2] } ) ], [ '3010023918', 'CD' ], "copy all with regex: original second field still exists" ); is_deeply( - [ - read_field( - { record => $record, field => '953', field_numbers => [1] } - ) - ], + [ read_field( { record => $record, field => '953', field_numbers => [1] } ) ], [ '4242423917', 'BK', 'GEN', '2001-06-25' ], "copy all with regex: first original fields has been copied" ); is_deeply( - [ - read_field( - { record => $record, field => '953', field_numbers => [2] } - ) - ], + [ read_field( { record => $record, field => '953', field_numbers => [2] } ) ], [ '4242423918', 'CD' ], "copy all with regex: second original fields has been copied" ); @@ -887,35 +778,28 @@ subtest 'copy_field' => sub { to_field => '999', } ); - my @fields_9999 = - read_field( { record => $record, field => '999', subfield => '9' } ); - is_deeply( \@fields_9999, [], - 'copy a nonexistent field does not create a new one' ); + my @fields_9999 = read_field( { record => $record, field => '999', subfield => '9' } ); + is_deeply( + \@fields_9999, [], + 'copy a nonexistent field does not create a new one' + ); $record = new_record; copy_field( { - record => $record, - from_field => 245, - to_field => 650, + record => $record, + from_field => 245, + to_field => 650, } ); is_deeply( - [ - read_field( - { record => $record, field => '650', field_numbers => [2] } - ) - ], + [ read_field( { record => $record, field => '650', field_numbers => [2] } ) ], [ 'Computer programming.', '462' ], 'Copy a field to existent fields should create a new field' ); is_deeply( - [ - read_field( - { record => $record, field => '650', field_numbers => [1] } - ) - ], + [ read_field( { record => $record, field => '650', field_numbers => [1] } ) ], [ 'The art of computer programming', 'Donald E. Knuth.' ], 'Copy a field to existent fields should create a new field, the original one should not have been updated' ); @@ -924,7 +808,7 @@ subtest 'copy_field' => sub { # copy_and_replace_field - subfield subtest 'copy_and_replace_field' => sub { - plan tests => 3; + plan tests => 3; subtest 'copy and replace subfield' => sub { plan tests => 20; my $record = new_record; @@ -945,20 +829,12 @@ subtest 'copy_and_replace_field' => sub { } ); is_deeply( - [ - read_field( - { record => $record, field => '245', subfield => 'a' } - ) - ], + [ read_field( { record => $record, field => '245', subfield => 'a' } ) ], ['The art of computer programming'], 'Copy and replace should not have modify original subfield 245$a (same as copy)' ); is_deeply( - [ - read_field( - { record => $record, field => '246', subfield => 'a' } - ) - ], + [ read_field( { record => $record, field => '246', subfield => 'a' } ) ], ['The art of computer programming'], 'Copy and replace should create a new 246$a (same as copy)' ); @@ -980,8 +856,7 @@ subtest 'copy_and_replace_field' => sub { to_subfield => 'a' } ); - my @fields_651a = - read_field( { record => $record, field => '651', subfield => 'a' } ); + my @fields_651a = read_field( { record => $record, field => '651', subfield => 'a' } ); is_deeply( \@fields_651a, [ 'Computer algorithms.', 'Computer programming.' ], @@ -1000,11 +875,7 @@ subtest 'copy_and_replace_field' => sub { } ); is_deeply( - [ - read_field( - { record => $record, field => '651', subfield => 'a' } - ) - ], + [ read_field( { record => $record, field => '651', subfield => 'a' } ) ], ['Computer programming.'], 'Copy and replace first field 650$a should only copy the 1st (same as copy)' ); @@ -1020,11 +891,7 @@ subtest 'copy_and_replace_field' => sub { } ); is_deeply( - [ - read_field( - { record => $record, field => '651', subfield => 'a' } - ) - ], + [ read_field( { record => $record, field => '651', subfield => 'a' } ) ], ['Computer algorithms.'], 'Copy and replace second field 650$a should erase 651$a' ); @@ -1037,11 +904,10 @@ subtest 'copy_and_replace_field' => sub { from_subfield => 'a', to_field => '651', to_subfield => 'a', - regex => { search => 'Computer', replace => 'The art of' } + regex => { search => 'Computer', replace => 'The art of' } } ); - @fields_651a = - read_field( { record => $record, field => '651', subfield => 'a' } ); + @fields_651a = read_field( { record => $record, field => '651', subfield => 'a' } ); is_deeply( \@fields_651a, [ 'The art of algorithms.', 'The art of programming.' ], @@ -1056,11 +922,10 @@ subtest 'copy_and_replace_field' => sub { from_subfield => 'a', to_field => '651', to_subfield => 'a', - regex => { search => 'Computer', replace => 'The mistake of' } + regex => { search => 'Computer', replace => 'The mistake of' } } ); - @fields_651a = - read_field( { record => $record, field => '651', subfield => 'a' } ); + @fields_651a = read_field( { record => $record, field => '651', subfield => 'a' } ); is_deeply( \@fields_651a, [ 'The mistake of algorithms.', 'The mistake of programming.' ], @@ -1075,11 +940,10 @@ subtest 'copy_and_replace_field' => sub { from_subfield => 'a', to_field => '651', to_subfield => 'a', - regex => { search => 'Computer', replace => 'The art of' } + regex => { search => 'Computer', replace => 'The art of' } } ); - @fields_651a = - read_field( { record => $record, field => '651', subfield => 'a' } ); + @fields_651a = read_field( { record => $record, field => '651', subfield => 'a' } ); is_deeply( \@fields_651a, [ 'The art of algorithms.', 'The art of programming.', ], @@ -1094,12 +958,11 @@ subtest 'copy_and_replace_field' => sub { from_subfield => 'a', to_field => '651', to_subfield => 'a', - regex => { search => 'Computer', replace => 'The art of' }, + regex => { search => 'Computer', replace => 'The art of' }, field_numbers => [1] } ); - @fields_651a = - read_field( { record => $record, field => '651', subfield => 'a' } ); + @fields_651a = read_field( { record => $record, field => '651', subfield => 'a' } ); is_deeply( \@fields_651a, [ 'The art of programming.', ], @@ -1126,8 +989,7 @@ subtest 'copy_and_replace_field' => sub { regex => { search => 'o', replace => 'foo' } } ); - my @fields_652a = - read_field( { record => $record, field => '652', subfield => 'a' } ); + my @fields_652a = read_field( { record => $record, field => '652', subfield => 'a' } ); is_deeply( \@fields_652a, [ 'Cfoomputer algorithms.', 'Cfoomputer programming.' ], @@ -1141,11 +1003,10 @@ subtest 'copy_and_replace_field' => sub { from_subfield => 'a', to_field => '653', to_subfield => 'a', - regex => { search => 'o', replace => 'foo', modifiers => 'g' } + regex => { search => 'o', replace => 'foo', modifiers => 'g' } } ); - my @fields_653a = - read_field( { record => $record, field => '653', subfield => 'a' } ); + my @fields_653a = read_field( { record => $record, field => '653', subfield => 'a' } ); is_deeply( \@fields_653a, [ 'Cfoomputer algfoorithms.', 'Cfoomputer prfoogramming.' ], @@ -1159,11 +1020,10 @@ subtest 'copy_and_replace_field' => sub { from_subfield => 'a', to_field => '654', to_subfield => 'a', - regex => { search => 'O', replace => 'foo', modifiers => 'i' } + regex => { search => 'O', replace => 'foo', modifiers => 'i' } } ); - my @fields_654a = - read_field( { record => $record, field => '654', subfield => 'a' } ); + my @fields_654a = read_field( { record => $record, field => '654', subfield => 'a' } ); is_deeply( \@fields_654a, [ 'Cfoomputer algorithms.', 'Cfoomputer programming.' ], @@ -1177,11 +1037,10 @@ subtest 'copy_and_replace_field' => sub { from_subfield => 'a', to_field => '655', to_subfield => 'a', - regex => { search => 'O', replace => 'foo', modifiers => 'gi' } + regex => { search => 'O', replace => 'foo', modifiers => 'gi' } } ); - my @fields_655a = - read_field( { record => $record, field => '655', subfield => 'a' } ); + my @fields_655a = read_field( { record => $record, field => '655', subfield => 'a' } ); is_deeply( \@fields_655a, [ 'Cfoomputer algfoorithms.', 'Cfoomputer prfoogramming.' ], @@ -1206,8 +1065,7 @@ subtest 'copy_and_replace_field' => sub { to_subfield => 'd' } ); - my @fields_952d = - read_field( { record => $record, field => '952', subfield => 'd' } ); + my @fields_952d = read_field( { record => $record, field => '952', subfield => 'd' } ); is_deeply( \@fields_952d, [ '2001-06-25', '2001-06-25' ], @@ -1223,10 +1081,11 @@ subtest 'copy_and_replace_field' => sub { to_subfield => '9' } ); - my @fields_9999 = - read_field( { record => $record, field => '999', subfield => '9' } ); - is_deeply( \@fields_9999, [], - 'copy and replace a nonexistent subfield does not create a new one (same as copy)' ); + my @fields_9999 = read_field( { record => $record, field => '999', subfield => '9' } ); + is_deeply( + \@fields_9999, [], + 'copy and replace a nonexistent subfield does not create a new one (same as copy)' + ); $record = new_record; copy_and_replace_field( @@ -1239,13 +1098,10 @@ subtest 'copy_and_replace_field' => sub { regex => { search => '^', replace => 'BEGIN ' } } ); + # This is the same as update the subfield is_deeply( - [ - read_field( - { record => $record, field => '245', subfield => 'a' } - ) - ], + [ read_field( { record => $record, field => '245', subfield => 'a' } ) ], ['BEGIN The art of computer programming'], 'Copy and replace - Update a subfield: add a string at the beginning' ); @@ -1261,13 +1117,10 @@ subtest 'copy_and_replace_field' => sub { regex => { search => '$', replace => ' END' } } ); + # This is the same as update the subfield is_deeply( - [ - read_field( - { record => $record, field => '245', subfield => 'a' } - ) - ], + [ read_field( { record => $record, field => '245', subfield => 'a' } ) ], ['The art of computer programming END'], 'Copy and replace - Update a subfield: add a string at the end' ); @@ -1283,13 +1136,10 @@ subtest 'copy_and_replace_field' => sub { regex => { search => '(art)', replace => 'sm$1 $1' } } ); + # This is the same as update the subfield is_deeply( - [ - read_field( - { record => $record, field => '245', subfield => 'a' } - ) - ], + [ read_field( { record => $record, field => '245', subfield => 'a' } ) ], ['The smart art of computer programming'], 'Copy and replace - Update a subfield: use capture groups' ); @@ -1306,11 +1156,7 @@ subtest 'copy_and_replace_field' => sub { ); is_deeply( - [ - read_field( - { record => $record, field => '650' } - ) - ], + [ read_field( { record => $record, field => '650' } ) ], [ 'Computer programming.', '462', 'Donald E. Knuth.' ], 'Copy and replace a subfield to an existent field but inexistent subfield (same as copy)' ); @@ -1327,11 +1173,7 @@ subtest 'copy_and_replace_field' => sub { ); is_deeply( - [ - read_field( - { record => $record, field => '650' } - ) - ], + [ read_field( { record => $record, field => '650' } ) ], [ 'Computer programming.', 'Donald E. Knuth.' ], 'Copy and replace a subfield to an existent field / subfield, the origin subfield is replaced' ); @@ -1349,42 +1191,25 @@ subtest 'copy_and_replace_field' => sub { ); #- copy all fields - copy_and_replace_field( - { record => $record, from_field => '952', to_field => '953' } ); + copy_and_replace_field( { record => $record, from_field => '952', to_field => '953' } ); my @fields_952 = read_field( { record => $record, field => '952' } ); is_deeply( - [ - read_field( - { record => $record, field => '952', field_numbers => [1] } - ) - ], + [ read_field( { record => $record, field => '952', field_numbers => [1] } ) ], [ '3010023917', 'BK', 'GEN', '2001-06-25' ], "copy all: original first field still exists (same as copy)" ); is_deeply( - [ - read_field( - { record => $record, field => '952', field_numbers => [2] } - ) - ], + [ read_field( { record => $record, field => '952', field_numbers => [2] } ) ], [ '3010023918', 'CD' ], "copy all: original second field still exists (same as copy)" ); is_deeply( - [ - read_field( - { record => $record, field => '953', field_numbers => [1] } - ) - ], + [ read_field( { record => $record, field => '953', field_numbers => [1] } ) ], [ '3010023917', 'BK', 'GEN', '2001-06-25' ], "copy all: first original fields has been copied (same as copy)" ); is_deeply( - [ - read_field( - { record => $record, field => '953', field_numbers => [2] } - ) - ], + [ read_field( { record => $record, field => '953', field_numbers => [2] } ) ], [ '3010023918', 'CD' ], "copy all: second original fields has been copied (same as copy)" ); @@ -1399,20 +1224,12 @@ subtest 'copy_and_replace_field' => sub { } ); is_deeply( - [ - read_field( - { record => $record, field => '953', field_numbers => [1] } - ) - ], + [ read_field( { record => $record, field => '953', field_numbers => [1] } ) ], [ '3010023917', 'BK', 'GEN', '2001-06-25' ], "copy and replace first: first original fields has been copied (same as copy)" ); is_deeply( - [ - read_field( - { record => $record, field => '953', field_numbers => [2] } - ) - ], + [ read_field( { record => $record, field => '953', field_numbers => [2] } ) ], [ '3010023918', 'CD' ], "copy and replace first: second original fields has been copied (same as copy)" ); @@ -1441,38 +1258,22 @@ subtest 'copy_and_replace_field' => sub { } ); is_deeply( - [ - read_field( - { record => $record, field => '952', field_numbers => [1] } - ) - ], + [ read_field( { record => $record, field => '952', field_numbers => [1] } ) ], [ '3010023917', 'BK', 'GEN', '2001-06-25' ], "copy and replace all with regex: original first field still exists (same as copy)" ); is_deeply( - [ - read_field( - { record => $record, field => '952', field_numbers => [2] } - ) - ], + [ read_field( { record => $record, field => '952', field_numbers => [2] } ) ], [ '3010023918', 'CD' ], "copy and replace all with regex: original second field still exists (same as copy)" ); is_deeply( - [ - read_field( - { record => $record, field => '953', field_numbers => [1] } - ) - ], + [ read_field( { record => $record, field => '953', field_numbers => [1] } ) ], [ '4242423917', 'BK', 'GEN', '2001-06-25' ], "copy and replace all with regex: first original fields has been copied (same as copy)" ); is_deeply( - [ - read_field( - { record => $record, field => '953', field_numbers => [2] } - ) - ], + [ read_field( { record => $record, field => '953', field_numbers => [2] } ) ], [ '4242423918', 'CD' ], "copy and replace all with regex: second original fields has been copied (same as copy)" ); @@ -1483,35 +1284,28 @@ subtest 'copy_and_replace_field' => sub { to_field => '999', } ); - my @fields_9999 = - read_field( { record => $record, field => '999', subfield => '9' } ); - is_deeply( \@fields_9999, [], - 'copy and replace a nonexistent field does not create a new one (same as copy)' ); + my @fields_9999 = read_field( { record => $record, field => '999', subfield => '9' } ); + is_deeply( + \@fields_9999, [], + 'copy and replace a nonexistent field does not create a new one (same as copy)' + ); $record = new_record; copy_and_replace_field( { - record => $record, - from_field => 245, - to_field => 650, + record => $record, + from_field => 245, + to_field => 650, } ); is_deeply( - [ - read_field( - { record => $record, field => '650', field_numbers => [1] } - ) - ], + [ read_field( { record => $record, field => '650', field_numbers => [1] } ) ], [ 'The art of computer programming', 'Donald E. Knuth.' ], 'Copy and replace to an existent field should erase the original field' ); is_deeply( - [ - read_field( - { record => $record, field => '650', field_numbers => [2] } - ) - ], + [ read_field( { record => $record, field => '650', field_numbers => [2] } ) ], [], 'Copy and replace to an existent field should not create a new field' ); @@ -1537,7 +1331,7 @@ subtest 'copy_and_replace_field' => sub { # move_field - subfields subtest 'move_field' => sub { - plan tests => 2; + plan tests => 2; subtest 'move subfield' => sub { plan tests => 7; my $record = new_record; @@ -1558,10 +1352,8 @@ subtest 'move_field' => sub { to_subfield => 'c' } ); - @fields_952c = - read_field( { record => $record, field => '952', subfield => 'c' } ); - @fields_954c = - read_field( { record => $record, field => '954', subfield => 'c' } ); + @fields_952c = read_field( { record => $record, field => '952', subfield => 'c' } ); + @fields_954c = read_field( { record => $record, field => '954', subfield => 'c' } ); is_deeply( \@fields_952c, [], 'The 952$c has moved' ); is_deeply( \@fields_954c, ['GEN'], 'Now 954$c exists' ); @@ -1575,10 +1367,8 @@ subtest 'move_field' => sub { field_numbers => [1] } ); # Move the first field - my @fields_952p = - read_field( { record => $record, field => '952', subfield => 'p' } ); - @fields_954p = - read_field( { record => $record, field => '954', subfield => 'p' } ); + my @fields_952p = read_field( { record => $record, field => '952', subfield => 'p' } ); + @fields_954p = read_field( { record => $record, field => '954', subfield => 'p' } ); is_deeply( \@fields_952p, ['3010023917'], 'One of 952$p has moved' ); is_deeply( \@fields_954p, ['3010023917'], 'Now 954$p exists' ); @@ -1600,10 +1390,8 @@ subtest 'move_field' => sub { to_subfield => 'p' } ); # Move all field - @fields_952p = - read_field( { record => $record, field => '952', subfield => 'p' } ); - @fields_954p = - read_field( { record => $record, field => '954', subfield => 'p' } ); + @fields_952p = read_field( { record => $record, field => '952', subfield => 'p' } ); + @fields_954p = read_field( { record => $record, field => '954', subfield => 'p' } ); is_deeply( \@fields_952p, [], 'All 952$p have moved' ); is_deeply( \@fields_954p, @@ -1620,10 +1408,11 @@ subtest 'move_field' => sub { to_subfield => '9' } ); - my @fields_9999 = - read_field( { record => $record, field => '999', subfield => '9' } ); - is_deeply( \@fields_9999, [], - 'move a nonexistent subfield does not create a new one' ); + my @fields_9999 = read_field( { record => $record, field => '999', subfield => '9' } ); + is_deeply( + \@fields_9999, [], + 'move a nonexistent subfield does not create a new one' + ); }; subtest 'move field' => sub { @@ -1640,25 +1429,18 @@ subtest 'move_field' => sub { ); #- Move all fields - move_field( - { record => $record, from_field => '952', to_field => '953' } ); - is_deeply( [ read_field( { record => $record, field => '952' } ) ], - [], "original fields don't exist" ); + move_field( { record => $record, from_field => '952', to_field => '953' } ); is_deeply( - [ - read_field( - { record => $record, field => '953', field_numbers => [1] } - ) - ], + [ read_field( { record => $record, field => '952' } ) ], + [], "original fields don't exist" + ); + is_deeply( + [ read_field( { record => $record, field => '953', field_numbers => [1] } ) ], [ '3010023917', 'BK', 'GEN', '2001-06-25' ], "first original fields has been copied" ); is_deeply( - [ - read_field( - { record => $record, field => '953', field_numbers => [2] } - ) - ], + [ read_field( { record => $record, field => '953', field_numbers => [2] } ) ], [ '3010023917', 'BK' ], "second original fields has been copied" ); @@ -1701,23 +1483,17 @@ subtest 'move_field' => sub { regex => { search => 'BK', replace => 'DVD' } } ); - is_deeply( [ read_field( { record => $record, field => '952' } ) ], - [], "use a regex, original fields don't exist" ); is_deeply( - [ - read_field( - { record => $record, field => '953', field_numbers => [1] } - ) - ], + [ read_field( { record => $record, field => '952' } ) ], + [], "use a regex, original fields don't exist" + ); + is_deeply( + [ read_field( { record => $record, field => '953', field_numbers => [1] } ) ], [ '3010023917', 'DVD', 'GEN', '2001-06-25' ], "use a regex, first original fields has been copied" ); is_deeply( - [ - read_field( - { record => $record, field => '953', field_numbers => [2] } - ) - ], + [ read_field( { record => $record, field => '953', field_numbers => [2] } ) ], [ '3010023917', 'DVD' ], "use a regex, second original fields has been copied" ); @@ -1729,17 +1505,18 @@ subtest 'move_field' => sub { to_field => '999', } ); - my @fields_9999 = - read_field( { record => $record, field => '999', subfield => '9' } ); - is_deeply( \@fields_9999, [], - 'move a nonexistent field does not create a new one' ); + my @fields_9999 = read_field( { record => $record, field => '999', subfield => '9' } ); + is_deeply( + \@fields_9999, [], + 'move a nonexistent field does not create a new one' + ); }; }; # delete_field subtest 'delete_field' => sub { - plan tests => 2; + plan tests => 2; subtest 'delete subfield' => sub { plan tests => 3; my $record = new_record; @@ -1759,8 +1536,7 @@ subtest 'delete_field' => sub { field_numbers => [1] } ); - my @fields_952p = - read_field( { record => $record, field => '952', subfield => 'p' } ); + my @fields_952p = read_field( { record => $record, field => '952', subfield => 'p' } ); is_deeply( \@fields_952p, ['3010023917'], 'Delete first 952$p' ); $record = new_record; @@ -1772,8 +1548,7 @@ subtest 'delete_field' => sub { ), ); delete_field( { record => $record, field => '952', subfield => 'p' } ); - @fields_952p = - read_field( { record => $record, field => '952', subfield => 'p' } ); + @fields_952p = read_field( { record => $record, field => '952', subfield => 'p' } ); is_deeply( \@fields_952p, [], 'Delete all 952$p' ); $record = new_record; @@ -1815,41 +1590,49 @@ subtest 'field_equals' => sub { my $record = new_record; subtest 'standard MARC fields' => sub { plan tests => 2; - my $match = Koha::SimpleMARC::field_equals({ - record => $record, - value => 'Donald', - field => '100', + my $match = Koha::SimpleMARC::field_equals( + { + record => $record, + value => 'Donald', + field => '100', subfield => 'a', - }); + } + ); is_deeply( $match, [], '100$a not equal to "Donald"' ); - $match = Koha::SimpleMARC::field_equals({ - record => $record, - value => 'Donald', - field => '100', + $match = Koha::SimpleMARC::field_equals( + { + record => $record, + value => 'Donald', + field => '100', subfield => 'a', is_regex => 1, - }); - is_deeply( $match, [1], 'first 100$a matches "Donald"'); + } + ); + is_deeply( $match, [1], 'first 100$a matches "Donald"' ); }; subtest 'control fields' => sub { plan tests => 2; - my $match = Koha::SimpleMARC::field_equals({ - record => $record, - value => 'eng', - field => '008', + my $match = Koha::SimpleMARC::field_equals( + { + record => $record, + value => 'eng', + field => '008', subfield => '', - }); + } + ); is_deeply( $match, [], '008 control field not equal to "eng"' ); - $match = Koha::SimpleMARC::field_equals({ - record => $record, - value => 'eng', - field => '008', + $match = Koha::SimpleMARC::field_equals( + { + record => $record, + value => 'eng', + field => '008', subfield => '', is_regex => 1, - }); + } + ); is_deeply( $match, [1], 'first 008 control field matches "eng"' ); }; }; diff --git a/t/SuggestionEngine.t b/t/SuggestionEngine.t index c8c981fa60..f729cd17e6 100755 --- a/t/SuggestionEngine.t +++ b/t/SuggestionEngine.t @@ -7,40 +7,49 @@ use File::Spec; use Test::More; BEGIN { - use_ok('Koha::SuggestionEngine'); + use_ok('Koha::SuggestionEngine'); } my $plugindir = File::Spec->rel2abs('Koha/SuggestionEngine/Plugin'); -opendir(my $dh, $plugindir); -my @installed_plugins = map { my $p = $_; ( $p =~ /\.pm$/ && -f "$plugindir/$p" && $p =~ s/\.pm$// ) ? "Koha::SuggestionEngine::Plugin::$p" : () } readdir($dh); +opendir( my $dh, $plugindir ); +my @installed_plugins = map { + my $p = $_; + ( $p =~ /\.pm$/ && -f "$plugindir/$p" && $p =~ s/\.pm$// ) ? "Koha::SuggestionEngine::Plugin::$p" : () +} readdir($dh); my @available_plugins = Koha::SuggestionEngine::AvailablePlugins(); foreach my $plugin (@installed_plugins) { - ok(grep($plugin, @available_plugins), "Found plugin $plugin"); + ok( grep( $plugin, @available_plugins ), "Found plugin $plugin" ); } -my $suggestor = Koha::SuggestionEngine->new( { plugins => [ 'ABCD::EFGH::IJKL' ] } ); +my $suggestor = Koha::SuggestionEngine->new( { plugins => ['ABCD::EFGH::IJKL'] } ); -is(ref($suggestor), 'Koha::SuggestionEngine', 'Created suggestion engine with invalid plugin'); -is(scalar @{ $suggestor->get_suggestions({ 'search' => 'books' }) }, 0 , 'Request suggestions with empty suggestor'); +is( ref($suggestor), 'Koha::SuggestionEngine', 'Created suggestion engine with invalid plugin' ); +is( scalar @{ $suggestor->get_suggestions( { 'search' => 'books' } ) }, 0, 'Request suggestions with empty suggestor' ); -$suggestor = Koha::SuggestionEngine->new( { plugins => [ 'Null' ] } ); -is(ref($suggestor->plugins->[0]), 'Koha::SuggestionEngine::Plugin::Null', 'Created record suggestor with implicitly scoped Null filter'); +$suggestor = Koha::SuggestionEngine->new( { plugins => ['Null'] } ); +is( + ref( $suggestor->plugins->[0] ), 'Koha::SuggestionEngine::Plugin::Null', + 'Created record suggestor with implicitly scoped Null filter' +); -$suggestor = Koha::SuggestionEngine->new( { plugins => [ 'Koha::SuggestionEngine::Plugin::Null' ] } ); -is(ref($suggestor->plugins->[0]), 'Koha::SuggestionEngine::Plugin::Null', 'Created record suggestor with explicitly scoped Null filter'); +$suggestor = Koha::SuggestionEngine->new( { plugins => ['Koha::SuggestionEngine::Plugin::Null'] } ); +is( + ref( $suggestor->plugins->[0] ), 'Koha::SuggestionEngine::Plugin::Null', + 'Created record suggestor with explicitly scoped Null filter' +); -my $suggestions = $suggestor->get_suggestions({ 'search' => 'books' }); +my $suggestions = $suggestor->get_suggestions( { 'search' => 'books' } ); -is_deeply($suggestions->[0], { 'search' => 'book', label => 'Book!', relevance => 1 }, "Good suggestion"); +is_deeply( $suggestions->[0], { 'search' => 'book', label => 'Book!', relevance => 1 }, "Good suggestion" ); -$suggestions = $suggestor->get_suggestions({ 'search' => 'silliness' }); +$suggestions = $suggestor->get_suggestions( { 'search' => 'silliness' } ); eval { - $suggestor = Koha::SuggestionEngine->new( { plugins => [ 'Koha::SuggestionEngine::Plugin::Null' ] } ); + $suggestor = Koha::SuggestionEngine->new( { plugins => ['Koha::SuggestionEngine::Plugin::Null'] } ); undef $suggestor; }; -ok(!$@, 'Destroyed suggestor successfully'); +ok( !$@, 'Destroyed suggestor successfully' ); done_testing(); diff --git a/t/SuggestionEngine_AuthorityFile.t b/t/SuggestionEngine_AuthorityFile.t index 7790722f3f..ed26cc6409 100755 --- a/t/SuggestionEngine_AuthorityFile.t +++ b/t/SuggestionEngine_AuthorityFile.t @@ -26,25 +26,35 @@ use Test::MockModule; use Koha::SuggestionEngine; my $module = Test::MockModule->new('C4::AuthoritiesMarc'); -$module->mock('SearchAuthorities', sub { - return [ { 'authid' => '1234', - 'reported_tag' => undef, - 'even' => 0, - 'summary' => { - 'authorized' => [ { 'heading' => 'Cooking' } ], - 'otherscript' => [], - 'seefrom' => [ 'Cookery' ], - 'notes' => [ 'Your quintessential poor heading selection' ], - 'seealso' => [] - }, - 'used' => 1, - 'authtype' => 'Topical Term' - } ], 1 -}); +$module->mock( + 'SearchAuthorities', + sub { + return [ + { + 'authid' => '1234', + 'reported_tag' => undef, + 'even' => 0, + 'summary' => { + 'authorized' => [ { 'heading' => 'Cooking' } ], + 'otherscript' => [], + 'seefrom' => ['Cookery'], + 'notes' => ['Your quintessential poor heading selection'], + 'seealso' => [] + }, + 'used' => 1, + 'authtype' => 'Topical Term' + } + ], + 1; + } +); -my $suggestor = Koha::SuggestionEngine->new( { plugins => [ 'AuthorityFile' ] } ); -is(ref($suggestor), 'Koha::SuggestionEngine', 'Created suggestion engine'); +my $suggestor = Koha::SuggestionEngine->new( { plugins => ['AuthorityFile'] } ); +is( ref($suggestor), 'Koha::SuggestionEngine', 'Created suggestion engine' ); -my $result = $suggestor->get_suggestions({search => 'Cookery'}); +my $result = $suggestor->get_suggestions( { search => 'Cookery' } ); -is_deeply($result, [ { 'search' => 'an:1234', 'relevance' => 1, 'label' => 'Cooking' } ], "Suggested correct alternative to 'Cookery'"); +is_deeply( + $result, [ { 'search' => 'an:1234', 'relevance' => 1, 'label' => 'Cooking' } ], + "Suggested correct alternative to 'Cookery'" +); diff --git a/t/Test/Dates.t b/t/Test/Dates.t index 4857e278c5..690c683c01 100755 --- a/t/Test/Dates.t +++ b/t/Test/Dates.t @@ -15,15 +15,19 @@ is( t::lib::Dates::compare( $date_1, $date_2 ), -1, '2017 is before 2018 (string is( t::lib::Dates::compare( $date_2, $date_1 ), 1, '2018 is after 2017 (strings comparison)' ); my $dt_3 = $dt_1->clone->subtract( seconds => 5 ); -is( t::lib::Dates::compare( $dt_1, $dt_3 ), - 0, 'If there is less than 1min, the dates are considered identicals' ); -is( t::lib::Dates::compare( $dt_3, $dt_1 ), - 0, 'If there is less than 1min, the dates are considered identicals' ); +is( + t::lib::Dates::compare( $dt_1, $dt_3 ), + 0, 'If there is less than 1min, the dates are considered identicals' +); +is( + t::lib::Dates::compare( $dt_3, $dt_1 ), + 0, 'If there is less than 1min, the dates are considered identicals' +); -$dt_1 = DateTime->new(year => 2001, month => 1, day => 1, hour => 0, minute => 0, second => 0, time_zone => '+0000'); -$dt_3 = DateTime->new(year => 2001, month => 1, day => 1, hour => 4, minute => 0, second => 0, time_zone => '+0400'); +$dt_1 = DateTime->new( year => 2001, month => 1, day => 1, hour => 0, minute => 0, second => 0, time_zone => '+0000' ); +$dt_3 = DateTime->new( year => 2001, month => 1, day => 1, hour => 4, minute => 0, second => 0, time_zone => '+0400' ); is( t::lib::Dates::compare( $dt_1, $dt_3 ), 0, 'Different timezone but same date/time' ); -$dt_1 = DateTime->new(year => 2001, month => 1, day => 1, hour => 0, minute => 0, second => 0, time_zone => '+0000'); -$dt_3 = DateTime->new(year => 2001, month => 1, day => 1, hour => 0, minute => 0, second => 0, time_zone => '+0400'); +$dt_1 = DateTime->new( year => 2001, month => 1, day => 1, hour => 0, minute => 0, second => 0, time_zone => '+0000' ); +$dt_3 = DateTime->new( year => 2001, month => 1, day => 1, hour => 0, minute => 0, second => 0, time_zone => '+0400' ); is( t::lib::Dates::compare( $dt_1, $dt_3 ), 1, 'Different timezone and different date/time' ); diff --git a/t/TmplToken.t b/t/TmplToken.t index a52f3c5e6f..465edacdef 100755 --- a/t/TmplToken.t +++ b/t/TmplToken.t @@ -1,6 +1,6 @@ #!/usr/bin/perl # -# This Koha test module is a stub! +# This Koha test module is a stub! # Add more tests here!!! use strict; @@ -8,38 +8,37 @@ use warnings; use Test::More tests => 19; BEGIN { - use_ok('C4::TmplToken'); + use_ok('C4::TmplToken'); } -ok (my $token = C4::TmplToken->new('test',C4::TmplTokenType::TEXT,10,'/tmp/translate.txt'), "Create new"); -ok ($token->string eq 'test', "String works"); -ok ($token->type == C4::TmplTokenType::TEXT, "Token works"); -ok ($token->line_number == 10, "Line number works"); -ok ($token->pathname eq '/tmp/translate.txt', "Path works"); +ok( my $token = C4::TmplToken->new( 'test', C4::TmplTokenType::TEXT, 10, '/tmp/translate.txt' ), "Create new" ); +ok( $token->string eq 'test', "String works" ); +ok( $token->type == C4::TmplTokenType::TEXT, "Token works" ); +ok( $token->line_number == 10, "Line number works" ); +ok( $token->pathname eq '/tmp/translate.txt', "Path works" ); +ok( $token->text_p, "text_p works" ); -ok ($token->text_p, "text_p works"); +is( $token->children(), undef, "testing children returns undef when given argument" ); -is($token-> children(), undef, "testing children returns undef when given argument"); +ok( $token->set_children(), "testing set_children with no arguments" ); -ok($token-> set_children(), "testing set_children with no arguments"); +is( $token->parameters_and_fields(), "0", "testing Parameters and fields returns 0 when given argument" ); -is($token-> parameters_and_fields(), "0", "testing Parameters and fields returns 0 when given argument"); +is( $token->anchors(), "0", "testing anchors returns 0 when given argument" ); -is($token-> anchors(), "0", "testing anchors returns 0 when given argument"); +is( $token->form(), undef, "testing form returns undef when given argument" ); -is($token-> form(),undef, "testing form returns undef when given argument"); +ok( $token->set_form(), "testing set_form with no arguments" ); -ok($token-> set_form(), "testing set_form with no arguments"); +is( $token->js_data(), undef, "testing form returns undef when given argument" ); -is($token-> js_data(),undef, "testing form returns undef when given argument"); +ok( $token->set_js_data(), "testing set_js_data with no arguments" ); -ok($token-> set_js_data(), "testing set_js_data with no arguments"); +is( $token->tag_p(), "", "testing tag_p returns '' when given argument" ); -is($token-> tag_p(),"", "testing tag_p returns '' when given argument"); +is( $token->cdata_p(), "", "testing cdata_p returns '' when given argument" ); -is($token-> cdata_p(),"", "testing cdata_p returns '' when given argument"); +is( $token->text_parametrized_p(), "", "testing text_parametrized returns '' when given argument" ); -is($token-> text_parametrized_p(),"", "testing text_parametrized returns '' when given argument"); - -is($token-> directive_p(),"", "testing directive_p returns '' when given argument"); +is( $token->directive_p(), "", "testing directive_p returns '' when given argument" ); diff --git a/t/Token.t b/t/Token.t index 794bb3d69a..55247b68bb 100755 --- a/t/Token.t +++ b/t/Token.t @@ -27,80 +27,96 @@ use Time::HiRes qw|usleep|; use C4::Context; use Koha::Token; -C4::Context->set_userenv(0,42,0,'firstname','surname', 'CPL', 'Library 1', 0, ''); +C4::Context->set_userenv( 0, 42, 0, 'firstname', 'surname', 'CPL', 'Library 1', 0, '' ); my $tokenizer = Koha::Token->new; is( length( $tokenizer->generate ), 1, "Generate without parameters" ); -my $token = $tokenizer->generate({ length => 20 }); +my $token = $tokenizer->generate( { length => 20 } ); is( length($token), 20, "Token $token has 20 chars" ); -my $id = $tokenizer->generate({ length => 8 }); -my $csrftoken = $tokenizer->generate_csrf({ session_id => $id }); +my $id = $tokenizer->generate( { length => 8 } ); +my $csrftoken = $tokenizer->generate_csrf( { session_id => $id } ); isnt( length($csrftoken), 0, "Token $csrftoken should not be empty" ); is( $tokenizer->check, undef, "Check without any parameters" ); -my $result = $tokenizer->check_csrf({ - session_id => $id, token => $csrftoken, -}); +my $result = $tokenizer->check_csrf( + { + session_id => $id, token => $csrftoken, + } +); is( $result, 1, "CSRF token verified" ); -$result = $tokenizer->check({ - type => 'CSRF', id => $id, token => $token, -}); +$result = $tokenizer->check( + { + type => 'CSRF', id => $id, token => $token, + } +); isnt( $result, 1, "This token is no CSRF token" ); # Test MaxAge parameter -my $age = 1; # 1 second -$result = $tokenizer->check_csrf({ - session_id => $id, token => $csrftoken, MaxAge => $age, -}); +my $age = 1; # 1 second +$result = $tokenizer->check_csrf( + { + session_id => $id, token => $csrftoken, MaxAge => $age, + } +); is( $result, 1, "CSRF token still valid within one second" ); -usleep $age * 1000000 * 2; # micro (millionth) seconds + 100% -$result = $tokenizer->check_csrf({ - session_id => $id, token => $csrftoken, MaxAge => $age, -}); +usleep $age * 1000000 * 2; # micro (millionth) seconds + 100% +$result = $tokenizer->check_csrf( + { + session_id => $id, token => $csrftoken, MaxAge => $age, + } +); isnt( $result, 1, "CSRF token expired after one second" ); subtest 'Same logged in user with another session (cookie CGISESSID)' => sub { plan tests => 2; - C4::Context->set_userenv(0,42,0,'firstname','surname', 'CPL', 'Library 1', 0, ''); - $csrftoken = $tokenizer->generate_csrf({ session_id => $id }); - $result = $tokenizer->check_csrf({ - session_id => $id, token => $csrftoken, - }); + C4::Context->set_userenv( 0, 42, 0, 'firstname', 'surname', 'CPL', 'Library 1', 0, '' ); + $csrftoken = $tokenizer->generate_csrf( { session_id => $id } ); + $result = $tokenizer->check_csrf( + { + session_id => $id, token => $csrftoken, + } + ); is( $result, 1, "CSRF token verified" ); + # Get another session id - $id = $tokenizer->generate({ length => 8 }); - $result = $tokenizer->check_csrf({ - session_id => $id, token => $csrftoken, - }); + $id = $tokenizer->generate( { length => 8 } ); + $result = $tokenizer->check_csrf( + { + session_id => $id, token => $csrftoken, + } + ); is( $result, '', "CSRF token is not verified if another session is used" ); }; subtest 'Pattern parameter' => sub { plan tests => 5; - my $id = $tokenizer->generate({ pattern => '\d\d', length => 8 }); + my $id = $tokenizer->generate( { pattern => '\d\d', length => 8 } ); is( length($id), 2, 'Pattern overrides length' ); ok( $id =~ /\d{2}/, 'Two digits found' ); - $id = $tokenizer->generate({ pattern => '[A-Z]{10}' }); + $id = $tokenizer->generate( { pattern => '[A-Z]{10}' } ); is( length($id), 10, 'Check length again' ); ok( $id !~ /[^A-Z]/, 'Only uppercase letters' ); - throws_ok( sub { $tokenizer->generate({ pattern => 'abc{d,e}', }) }, 'Koha::Exceptions::Token::BadPattern', 'Exception should be thrown when wrong pattern is used'); + throws_ok( + sub { $tokenizer->generate( { pattern => 'abc{d,e}', } ) }, 'Koha::Exceptions::Token::BadPattern', + 'Exception should be thrown when wrong pattern is used' + ); }; subtest 'JWT' => sub { plan tests => 3; - my $id = 42; - my $jwt = $tokenizer->generate_jwt({ id => $id }); + my $id = 42; + my $jwt = $tokenizer->generate_jwt( { id => $id } ); - my $is_valid = $tokenizer->check_jwt({ id => $id, token => $jwt }); + my $is_valid = $tokenizer->check_jwt( { id => $id, token => $jwt } ); is( $is_valid, 1, 'valid token should return 1' ); - $is_valid = $tokenizer->check_jwt({ id => 24, token => $jwt }); + $is_valid = $tokenizer->check_jwt( { id => 24, token => $jwt } ); isnt( $is_valid, 1, 'invalid token should not return 1' ); - my $retrieved_id = $tokenizer->decode_jwt({ token => $jwt }); + my $retrieved_id = $tokenizer->decode_jwt( { token => $jwt } ); is( $retrieved_id, $id, 'id stored in jwt should be correct' ); }; @@ -108,16 +124,16 @@ subtest 'testing _add_default_csrf_params with/without userenv (bug 27849)' => s plan tests => 8; # Current userenv: userid == 42 - my $result = Koha::Token::_add_default_csrf_params({ session_id => '567' }); - is( $result->{session_id}, 567, 'Check session id' ); - is( $result->{id}, 'anonymous_567', 'Check userid' ); + my $result = Koha::Token::_add_default_csrf_params( { session_id => '567' } ); + is( $result->{session_id}, 567, 'Check session id' ); + is( $result->{id}, 'anonymous_567', 'Check userid' ); # Clear userenv C4::Context->unset_userenv(); is( C4::Context::userenv, undef, 'No userenv anymore' ); - $result = Koha::Token::_add_default_csrf_params({}); # pass no session_id - is( $result->{session_id}, Koha::Token::DEFA_SESSION_ID, 'Check session id' ); - is( $result->{id}, Koha::Token::DEFA_SESSION_USERID. '_'. $result->{session_id}, 'Check userid' ); + $result = Koha::Token::_add_default_csrf_params( {} ); # pass no session_id + is( $result->{session_id}, Koha::Token::DEFA_SESSION_ID, 'Check session id' ); + is( $result->{id}, Koha::Token::DEFA_SESSION_USERID . '_' . $result->{session_id}, 'Check userid' ); # Empty anonymous userenv (see C4::Auth::check_cookie_auth) C4::Context->set_userenv( undef, q{} ); diff --git a/t/cypress/plugins/index.js b/t/cypress/plugins/index.js index 76e6a4c249..837e6d747c 100644 --- a/t/cypress/plugins/index.js +++ b/t/cypress/plugins/index.js @@ -1,15 +1,15 @@ -const { startDevServer } = require('@cypress/webpack-dev-server') +const { startDevServer } = require("@cypress/webpack-dev-server"); const mysql = require("cypress-mysql"); const { buildSampleObject, buildSampleObjects } = require("./mockData.js"); module.exports = (on, config) => { - on('dev-server:start', options => - startDevServer({ - options, - }) - ) + on("dev-server:start", options => + startDevServer({ + options, + }) + ); mysql.configurePlugin(on); diff --git a/t/cypress/plugins/mockData.js b/t/cypress/plugins/mockData.js index 47a239a4d2..48219e6257 100644 --- a/t/cypress/plugins/mockData.js +++ b/t/cypress/plugins/mockData.js @@ -1,6 +1,6 @@ const { faker } = require("@faker-js/faker"); const { readYamlFile } = require("./../plugins/readYamlFile.js"); -const fs = require('fs'); +const fs = require("fs"); const generateMockData = (type, properties) => { if (Array.isArray(type)) { @@ -8,8 +8,13 @@ const generateMockData = (type, properties) => { } switch (type) { case "string": - if(properties?.maxLength){ - return faker.string.alpha({ length: { min: properties.minLength || 1, max: properties.maxLength } }) + if (properties?.maxLength) { + return faker.string.alpha({ + length: { + min: properties.minLength || 1, + max: properties.maxLength, + }, + }); } return faker.lorem.words(3); case "integer": diff --git a/t/cypress/support/e2e.js b/t/cypress/support/e2e.js index ddc6afb8fc..01e5c19bd7 100644 --- a/t/cypress/support/e2e.js +++ b/t/cypress/support/e2e.js @@ -25,25 +25,34 @@ // Cypress.Commands.overwrite('visit', (originalFn, url, options) => { ... }) function get_fallback_login_value(param) { + var env_var = param == "username" ? "KOHA_USER" : "KOHA_PASS"; - var env_var = param == 'username' ? 'KOHA_USER' : 'KOHA_PASS'; - - return typeof Cypress.env(env_var) === 'undefined' ? 'koha' : Cypress.env(env_var); + return typeof Cypress.env(env_var) === "undefined" + ? "koha" + : Cypress.env(env_var); } -Cypress.Commands.add('login', (username, password) => { - var user = typeof username === 'undefined' ? get_fallback_login_value('username') : username; - var pass = typeof password === 'undefined' ? get_fallback_login_value('password') : password; - cy.visit('/cgi-bin/koha/mainpage.pl?logout.x=1') - cy.get("#userid").type(user) - cy.get("#password").type(pass) - cy.get("#submit-button").click() -}) +Cypress.Commands.add("login", (username, password) => { + var user = + typeof username === "undefined" + ? get_fallback_login_value("username") + : username; + var pass = + typeof password === "undefined" + ? get_fallback_login_value("password") + : password; + cy.visit("/cgi-bin/koha/mainpage.pl?logout.x=1"); + cy.get("#userid").type(user); + cy.get("#password").type(pass); + cy.get("#submit-button").click(); +}); -Cypress.Commands.add('left_menu_active_item_is', (label) => { - cy.get("#navmenulist a.current:not(.disabled)").should('have.length',1).contains(label); -}) -const dayjs = require("dayjs") /* Cannot use our calendar JS code, it's in an include file (!) +Cypress.Commands.add("left_menu_active_item_is", label => { + cy.get("#navmenulist a.current:not(.disabled)") + .should("have.length", 1) + .contains(label); +}); +const dayjs = require("dayjs"); /* Cannot use our calendar JS code, it's in an include file (!) Also note that moment.js is deprecated */ const dates = { @@ -51,7 +60,7 @@ const dates = { today_us: dayjs().format("MM/DD/YYYY"), tomorrow_iso: dayjs().add(1, "day").format("YYYY-MM-DD"), tomorrow_us: dayjs().add(1, "day").format("MM/DD/YYYY"), -} +}; cy.get_license = () => { return { @@ -137,7 +146,7 @@ cy.get_license = () => { ], }, }; -} +}; cy.get_agreement = () => { let licenses = cy.get_licenses_to_relate(); @@ -273,9 +282,9 @@ cy.get_agreement = () => { value_str: "Afghanistan", }, ], - } + }, }; -} +}; cy.get_package = () => { return { @@ -356,7 +365,7 @@ cy.get_package = () => { }, resources_count: 0, }; -} +}; cy.get_ERM_av_cats_values = () => { return [ @@ -1242,7 +1251,7 @@ cy.get_ERM_av_cats_values = () => { is_system: true, }, ]; -} +}; cy.get_licenses_to_relate = () => { return [ @@ -1265,7 +1274,7 @@ cy.get_licenses_to_relate = () => { name: "third license name", }, ]; -} +}; cy.get_title = () => { return { @@ -1300,7 +1309,7 @@ cy.get_title = () => { package: { content_type: "", package_id: 1, - name: "first package name" + name: "first package name", }, package_id: 1, resource_id: 2, @@ -1308,503 +1317,501 @@ cy.get_title = () => { biblio_id: 439, title_id: 1, }, - title_id: 1 - } + title_id: 1, + }, ], title_id: 1, - title_url: "title url" - }; -} + title_url: "title url", + }; +}; cy.get_agreements_to_relate = () => { return [ { agreement_id: 2, description: "a second agreement", - name: "second agreement name" + name: "second agreement name", }, { agreement_id: 3, description: "a third agreement", - name: "third agreement name" + name: "third agreement name", }, { agreement_id: 4, description: "a fourth agreement", - name: "fourth agreement name" + name: "fourth agreement name", }, - ] -} + ]; +}; cy.get_vendors_to_relate = () => { return [ { - "id": 1, - "name": "My Vendor", - "aliases": [], + id: 1, + name: "My Vendor", + aliases: [], }, { - "id": 2, - "name": "My Vendor 2", - "aliases": [ - {"alias": "alias", alias_id: 1, vendor_id: 2} - ], - } - ] -} + id: 2, + name: "My Vendor 2", + aliases: [{ alias: "alias", alias_id: 1, vendor_id: 2 }], + }, + ]; +}; cy.get_counter_file = () => { return { - "date_uploaded": "2023-06-19T09:13:39+00:00", - "erm_counter_files_id": 1, - "file_content": "Report_Name,\"Journal Requests (Excluding OA_Gold)\"\r\nReport_ID,TR_J1\r\nRelease,5\r\nInstitution_Name,\"University Of West London\"\r\nInstitution_ID,\"Proprietary:Wiley:EAL00000122866; ISNI:0000000121857124\"\r\nMetric_Types,\"Total_Item_Requests; Unique_Item_Requests\"\r\nReport_Filters,\"Metric_Type:Total_Item_Requests|Unique_Item_Requests; Access_Type:Controlled; End_Date:2023-06-01; Begin_Date:2022-01-01; Data_Type:Journal; Access_Method:Regular\"\r\nReport_Attributes,\r\nExceptions,\"3031: Usage Not Ready for Requested Dates (Requested data between 2023-06-01 and 2023-06-01. However only data between 2018-11-01 and 2023-05-31 exists.)\"\r\nReporting_Period,\"Begin_Date=2022-01-01; End_Date=2023-06-01\"\r\nCreated,2023-06-19T02:13:31Z\r\nCreated_By,\"Atypon Systems LLC.\"\r\n\r\nTitle,Publisher,Publisher_ID,Platform,DOI,Proprietary_ID,Print_ISSN,Online_ISSN,URI,Metric_Type,Reporting_Period_Total,\"Jan 2022\",\"Feb 2022\",\"Mar 2022\",\"Apr 2022\",\"May 2022\",\"Jun 2022\",\"Jul 2022\",\"Aug 2022\",\"Sep 2022\",\"Oct 2022\",\"Nov 2022\",\"Dez 2022\",\"Jan 2023\",\"Feb 2023\",\"Mar 2023\",\"Apr 2023\",\"May 2023\",\"Jun 2023\"\r\n\"AEM Education and Training\",Wiley,0000000403801313,\"Wiley Online Library\",10.1002/(ISSN)2472-5390,Wiley:AET2,2472-5390,2472-5390,,Total_Item_Requests,16,1,3,0,1,3,1,0,2,1,0,0,1,0,3,0,0,0,0\r\n\"AEM Education and Training\",Wiley,0000000403801313,\"Wiley Online Library\",10.1002/(ISSN)2472-5390,Wiley:AET2,2472-5390,2472-5390,,Unique_Item_Requests,10,1,2,0,1,1,1,0,1,1,0,0,1,0,1,0,0,0,0\r\n\"AIChE Journal\",Wiley,0000000403801313,\"Wiley Online Library\",10.1002/(ISSN)1547-5905,Wiley:AIC,0001-1541,1547-5905,,Total_Item_Requests,4,1,0,0,0,0,1,0,0,0,0,1,1,0,0,0,0,0,0\r\n\"AIChE Journal\",Wiley,0000000403801313,\"Wiley Online Library\",10.1002/(ISSN)1547-5905,Wiley:AIC,0001-1541,1547-5905,,Unique_Item_Requests,4,1,0,0,0,0,1,0,0,0,0,1,1,0,0,0,0,0,0\r\n\"ANZ Journal of Surgery\",Wiley,0000000403801313,\"Wiley Online Library\",10.1111/(ISSN)1445-2197,Wiley:ANS,1445-1433,1445-2197,,Total_Item_Requests,103,11,2,20,14,8,2,9,1,0,5,6,0,2,4,6,5,8,0\r\n\"ANZ Journal of Surgery\",Wiley,0000000403801313,\"Wiley Online Library\",10.1111/(ISSN)1445-2197,Wiley:ANS,1445-1433,1445-2197,,Unique_Item_Requests,77,9,2,16,8,6,1,9,1,0,3,4,0,1,4,4,2,7,0\r\n\"AORN Journal\",Wiley,0000000403801313,\"Wiley Online Library\",10.1002/(ISSN)1878-0369,Wiley:AORN,0001-2092,1878-0369,,Total_Item_Requests,634,71,45,59,20,43,47,45,11,14,15,31,22,29,18,28,39,97,0\r\n\"AORN Journal\",Wiley,0000000403801313,\"Wiley Online Library\",10.1002/(ISSN)1878-0369,Wiley:AORN,0001-2092,1878-0369,,Unique_Item_Requests,436,53,27,27,15,34,30,30,6,11,13,22,17,23,16,26,26,60,0\r\nAPMIS,Wiley,0000000403801313,\"Wiley Online Library\",10.1111/(ISSN)1600-0463,Wiley:APM,0903-4641,1600-0463,,Total_Item_Requests,6,0,0,0,1,0,0,0,2,0,0,0,2,0,1,0,0,0,0\r\nAPMIS,Wiley,0000000403801313,\"Wiley Online Library\",10.1111/(ISSN)1600-0463,Wiley:APM,0903-4641,1600-0463,,Unique_Item_Requests,4,0,0,0,1,0,0,0,1,0,0,0,1,0,1,0,0,0,0\r\n\"AWWA Water Science\",Wiley,0000000403801313,\"Wiley Online Library\",10.1002/(ISSN)2577-8161,Wiley:AWS2,,2577-8161,,Total_Item_Requests,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0\r\n\"AWWA Water Science\",Wiley,0000000403801313,\"Wiley Online Library\",10.1002/(ISSN)2577-8161,Wiley:AWS2,,2577-8161,,Unique_Item_Requests,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0\r\nAbacus,Wiley,0000000403801313,\"Wiley Online Library\",10.1111/(ISSN)1467-6281,Wiley:ABAC,0001-3072,1467-6281,,Total_Item_Requests,51,3,0,7,0,2,0,1,0,0,0,11,6,0,3,17,1,0,0\r\nAbacus,Wiley,0000000403801313,\"Wiley Online Library\",10.1111/(ISSN)1467-6281,Wiley:ABAC,0001-3072,1467-6281,,Unique_Item_Requests,36,2,0,6,0,2,0,1,0,0,0,7,2,0,2,13,1,0,0\r\n\"Academic Emergency Medicine\",Wiley,0000000403801313,\"Wiley Online Library\",10.1111/(ISSN)1553-2712,Wiley:ACEM,1069-6563,1553-2712,,Total_Item_Requests,213,18,16,11,13,21,20,28,16,6,11,2,4,18,17,1,7,4,0\r\n\"Academic Emergency Medicine\",Wiley,0000000403801313,\"Wiley Online Library\",10.1111/(ISSN)1553-2712,Wiley:ACEM,1069-6563,1553-2712,,Unique_Item_Requests,159,15,11,10,10,15,13,23,12,6,7,2,2,10,12,1,7,3,0\r\n\"Accounting & Finance\",Wiley,0000000403801313,\"Wiley Online Library\",10.1111/(ISSN)1467-629X,Wiley:ACFI,0810-5391,1467-629X,,Total_Item_Requests,67,2,4,4,13,8,1,0,2,2,1,9,6,2,0,2,4,7,0\r\n\"Accounting & Finance\",Wiley,0000000403801313,\"Wiley Online Library\",10.1111/(ISSN)1467-629X,Wiley:ACFI,0810-5391,1467-629X,,Unique_Item_Requests,53,1,4,4,11,7,1,0,2,1,1,7,3,1,0,2,4,4,0\r\n\"Accounting Perspectives\",Wiley,0000000403801313,\"Wiley Online Library\",10.1111/(ISSN)1911-3838,Wiley:APR,1911-382X,1911-3838,,Total_Item_Requests,19,0,0,2,1,3,0,1,0,0,0,0,0,3,1,0,4,4,0\r\n\"Accounting Perspectives\",Wiley,0000000403801313,\"Wiley Online Library\",10.1111/(ISSN)1911-3838,Wiley:APR,1911-382X,1911-3838,,Unique_Item_Requests,14,0,0,1,1,1,0,1,0,0,0,0,0,2,1,0,4,3,0\r\n\"Acta Anaesthesiologica Scandinavica\",Wiley,0000000403801313,\"Wiley Online Library\",10.1111/(ISSN)1399-6576,Wiley:AAS,0001-5172,1399-6576,,Total_Item_Requests,181,29,20,19,5,15,4,19,6,5,6,4,0,3,29,1,12,4,0\r\n\"Acta Anaesthesiologica Scandinavica\",Wiley,0000000403801313,\"Wiley Online Library\",10.1111/(ISSN)1399-6576,Wiley:AAS,0001-5172,1399-6576,,Unique_Item_Requests,117,21,12,11,4,10,4,14,3,5,4,4,0,2,14,1,4,4,0\r\n\"Acta Neurologica Scandinavica\",Wiley,0000000403801313,\"Wiley Online Library\",10.1111/(ISSN)1600-0404,Wiley:ANE,0001-6314,1600-0404,,Total_Item_Requests,23,0,0,2,0,5,0,1,1,0,2,2,0,2,1,5,2,0,0\r\n\"Acta Neurologica Scandinavica\",Wiley,0000000403801313,\"Wiley Online Library\",10.1111/(ISSN)1600-0404,Wiley:ANE,0001-6314,1600-0404,,Unique_Item_Requests,21,0,0,2,0,4,0,1,1,0,1,2,0,2,1,5,2,0,0\r\n\"Acta Obstetricia et Gynecologica Scandinavica\",Wiley,0000000403801313,\"Wiley Online Library\",10.1111/(ISSN)1600-0412,Wiley:AOGS,0001-6349,1600-0412,,Total_Item_Requests,22,1,0,0,0,0,0,0,0,0,0,0,0,0,0,15,4,2,0\r\n\"Acta Obstetricia et Gynecologica Scandinavica\",Wiley,0000000403801313,\"Wiley Online Library\",10.1111/(ISSN)1600-0412,Wiley:AOGS,0001-6349,1600-0412,,Unique_Item_Requests,11,1,0,0,0,0,0,0,0,0,0,0,0,0,0,7,2,1,0\r\n\"Acta Ophthalmologica\",Wiley,0000000403801313,\"Wiley Online Library\",10.1111/(ISSN)1755-3768,Wiley:AOS,1755-375X,1755-3768,,Total_Item_Requests,2,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0\r\n\"Acta Ophthalmologica\",Wiley,0000000403801313,\"Wiley Online Library\",10.1111/(ISSN)1755-3768,Wiley:AOS,1755-375X,1755-3768,,Unique_Item_Requests,2,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0\r\n\"Acta Paediatrica\",Wiley,0000000403801313,\"Wiley Online Library\",10.1111/(ISSN)1651-2227,Wiley:APA,0803-5253,1651-2227,,Total_Item_Requests,229,23,26,14,12,8,45,22,6,10,8,3,9,7,8,11,9,8,0\r\n\"Acta Paediatrica\",Wiley,0000000403801313,\"Wiley Online Library\",10.1111/(ISSN)1651-2227,Wiley:APA,0803-5253,1651-2227,,Unique_Item_Requests,165,16,19,8,8,8,37,11,6,7,6,3,8,6,7,7,3,5,0\r\n\"Acta Physiologica\",Wiley,0000000403801313,\"Wiley Online Library\",10.1111/(ISSN)1748-1716,Wiley:APHA,1748-1708,1748-1716,,Total_Item_Requests,13,2,0,0,1,1,8,0,0,0,0,0,0,0,1,0,0,0,0\r\n\"Acta Physiologica\",Wiley,0000000403801313,\"Wiley Online Library\",10.1111/(ISSN)1748-1716,Wiley:APHA,1748-1708,1748-1716,,Unique_Item_Requests,12,2,0,0,1,1,7,0,0,0,0,0,0,0,1,0,0,0,0\r\n\"Acta Psychiatrica Scandinavica\",Wiley,0000000403801313,\"Wiley Online Library\",10.1111/(ISSN)1600-0447,Wiley:ACPS,0001-690X,1600-0447,,Total_Item_Requests,226,5,9,28,28,15,18,4,1,2,4,13,14,24,8,20,21,12,0\r\n\"Acta Psychiatrica Scandinavica\",Wiley,0000000403801313,\"Wiley Online Library\",10.1111/(ISSN)1600-0447,Wiley:ACPS,0001-690X,1600-0447,,Unique_Item_Requests,178,4,5,19,23,10,17,3,1,1,4,13,10,19,6,18,14,11,0\r\n", - "filename": "PTFS Journals_TR_J1", - "type": "TR_J1", - "usage_data_provider_id": 1, - "counter_logs": [ - { - "borrowernumber": null, - "counter_files_id": 2, - "erm_counter_log_id": 2, - "filename": "PTFS Journals_TR_J1", - "importdate": "2023-06-19T09:40:46+00:00", - "logdetails": null, - "patron": { - "cardnumber": "42", - "category_id": "S", - "check_previous_checkout": "inherit", - "date_enrolled": "2024-04-18", - "expiry_date": "2032-07-18", - "incorrect_address": false, - "lang": "default", - "library_id": "CPL", - "login_attempts": 0, - "patron_card_lost": false, - "patron_id": 51, - "privacy": 1, - "privacy_guarantor_checkouts": 0, - "privacy_guarantor_fines": false, - "protected": false, - "restricted": false, - "surname": "koha", - "updated_on": "2024-04-18T09:42:59+00:00", - "userid": "koha", - }, - } - ] - } - -} + date_uploaded: "2023-06-19T09:13:39+00:00", + erm_counter_files_id: 1, + file_content: + 'Report_Name,"Journal Requests (Excluding OA_Gold)"\r\nReport_ID,TR_J1\r\nRelease,5\r\nInstitution_Name,"University Of West London"\r\nInstitution_ID,"Proprietary:Wiley:EAL00000122866; ISNI:0000000121857124"\r\nMetric_Types,"Total_Item_Requests; Unique_Item_Requests"\r\nReport_Filters,"Metric_Type:Total_Item_Requests|Unique_Item_Requests; Access_Type:Controlled; End_Date:2023-06-01; Begin_Date:2022-01-01; Data_Type:Journal; Access_Method:Regular"\r\nReport_Attributes,\r\nExceptions,"3031: Usage Not Ready for Requested Dates (Requested data between 2023-06-01 and 2023-06-01. However only data between 2018-11-01 and 2023-05-31 exists.)"\r\nReporting_Period,"Begin_Date=2022-01-01; End_Date=2023-06-01"\r\nCreated,2023-06-19T02:13:31Z\r\nCreated_By,"Atypon Systems LLC."\r\n\r\nTitle,Publisher,Publisher_ID,Platform,DOI,Proprietary_ID,Print_ISSN,Online_ISSN,URI,Metric_Type,Reporting_Period_Total,"Jan 2022","Feb 2022","Mar 2022","Apr 2022","May 2022","Jun 2022","Jul 2022","Aug 2022","Sep 2022","Oct 2022","Nov 2022","Dez 2022","Jan 2023","Feb 2023","Mar 2023","Apr 2023","May 2023","Jun 2023"\r\n"AEM Education and Training",Wiley,0000000403801313,"Wiley Online Library",10.1002/(ISSN)2472-5390,Wiley:AET2,2472-5390,2472-5390,,Total_Item_Requests,16,1,3,0,1,3,1,0,2,1,0,0,1,0,3,0,0,0,0\r\n"AEM Education and Training",Wiley,0000000403801313,"Wiley Online Library",10.1002/(ISSN)2472-5390,Wiley:AET2,2472-5390,2472-5390,,Unique_Item_Requests,10,1,2,0,1,1,1,0,1,1,0,0,1,0,1,0,0,0,0\r\n"AIChE Journal",Wiley,0000000403801313,"Wiley Online Library",10.1002/(ISSN)1547-5905,Wiley:AIC,0001-1541,1547-5905,,Total_Item_Requests,4,1,0,0,0,0,1,0,0,0,0,1,1,0,0,0,0,0,0\r\n"AIChE Journal",Wiley,0000000403801313,"Wiley Online Library",10.1002/(ISSN)1547-5905,Wiley:AIC,0001-1541,1547-5905,,Unique_Item_Requests,4,1,0,0,0,0,1,0,0,0,0,1,1,0,0,0,0,0,0\r\n"ANZ Journal of Surgery",Wiley,0000000403801313,"Wiley Online Library",10.1111/(ISSN)1445-2197,Wiley:ANS,1445-1433,1445-2197,,Total_Item_Requests,103,11,2,20,14,8,2,9,1,0,5,6,0,2,4,6,5,8,0\r\n"ANZ Journal of Surgery",Wiley,0000000403801313,"Wiley Online Library",10.1111/(ISSN)1445-2197,Wiley:ANS,1445-1433,1445-2197,,Unique_Item_Requests,77,9,2,16,8,6,1,9,1,0,3,4,0,1,4,4,2,7,0\r\n"AORN Journal",Wiley,0000000403801313,"Wiley Online Library",10.1002/(ISSN)1878-0369,Wiley:AORN,0001-2092,1878-0369,,Total_Item_Requests,634,71,45,59,20,43,47,45,11,14,15,31,22,29,18,28,39,97,0\r\n"AORN Journal",Wiley,0000000403801313,"Wiley Online Library",10.1002/(ISSN)1878-0369,Wiley:AORN,0001-2092,1878-0369,,Unique_Item_Requests,436,53,27,27,15,34,30,30,6,11,13,22,17,23,16,26,26,60,0\r\nAPMIS,Wiley,0000000403801313,"Wiley Online Library",10.1111/(ISSN)1600-0463,Wiley:APM,0903-4641,1600-0463,,Total_Item_Requests,6,0,0,0,1,0,0,0,2,0,0,0,2,0,1,0,0,0,0\r\nAPMIS,Wiley,0000000403801313,"Wiley Online Library",10.1111/(ISSN)1600-0463,Wiley:APM,0903-4641,1600-0463,,Unique_Item_Requests,4,0,0,0,1,0,0,0,1,0,0,0,1,0,1,0,0,0,0\r\n"AWWA Water Science",Wiley,0000000403801313,"Wiley Online Library",10.1002/(ISSN)2577-8161,Wiley:AWS2,,2577-8161,,Total_Item_Requests,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0\r\n"AWWA Water Science",Wiley,0000000403801313,"Wiley Online Library",10.1002/(ISSN)2577-8161,Wiley:AWS2,,2577-8161,,Unique_Item_Requests,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0\r\nAbacus,Wiley,0000000403801313,"Wiley Online Library",10.1111/(ISSN)1467-6281,Wiley:ABAC,0001-3072,1467-6281,,Total_Item_Requests,51,3,0,7,0,2,0,1,0,0,0,11,6,0,3,17,1,0,0\r\nAbacus,Wiley,0000000403801313,"Wiley Online Library",10.1111/(ISSN)1467-6281,Wiley:ABAC,0001-3072,1467-6281,,Unique_Item_Requests,36,2,0,6,0,2,0,1,0,0,0,7,2,0,2,13,1,0,0\r\n"Academic Emergency Medicine",Wiley,0000000403801313,"Wiley Online Library",10.1111/(ISSN)1553-2712,Wiley:ACEM,1069-6563,1553-2712,,Total_Item_Requests,213,18,16,11,13,21,20,28,16,6,11,2,4,18,17,1,7,4,0\r\n"Academic Emergency Medicine",Wiley,0000000403801313,"Wiley Online Library",10.1111/(ISSN)1553-2712,Wiley:ACEM,1069-6563,1553-2712,,Unique_Item_Requests,159,15,11,10,10,15,13,23,12,6,7,2,2,10,12,1,7,3,0\r\n"Accounting & Finance",Wiley,0000000403801313,"Wiley Online Library",10.1111/(ISSN)1467-629X,Wiley:ACFI,0810-5391,1467-629X,,Total_Item_Requests,67,2,4,4,13,8,1,0,2,2,1,9,6,2,0,2,4,7,0\r\n"Accounting & Finance",Wiley,0000000403801313,"Wiley Online Library",10.1111/(ISSN)1467-629X,Wiley:ACFI,0810-5391,1467-629X,,Unique_Item_Requests,53,1,4,4,11,7,1,0,2,1,1,7,3,1,0,2,4,4,0\r\n"Accounting Perspectives",Wiley,0000000403801313,"Wiley Online Library",10.1111/(ISSN)1911-3838,Wiley:APR,1911-382X,1911-3838,,Total_Item_Requests,19,0,0,2,1,3,0,1,0,0,0,0,0,3,1,0,4,4,0\r\n"Accounting Perspectives",Wiley,0000000403801313,"Wiley Online Library",10.1111/(ISSN)1911-3838,Wiley:APR,1911-382X,1911-3838,,Unique_Item_Requests,14,0,0,1,1,1,0,1,0,0,0,0,0,2,1,0,4,3,0\r\n"Acta Anaesthesiologica Scandinavica",Wiley,0000000403801313,"Wiley Online Library",10.1111/(ISSN)1399-6576,Wiley:AAS,0001-5172,1399-6576,,Total_Item_Requests,181,29,20,19,5,15,4,19,6,5,6,4,0,3,29,1,12,4,0\r\n"Acta Anaesthesiologica Scandinavica",Wiley,0000000403801313,"Wiley Online Library",10.1111/(ISSN)1399-6576,Wiley:AAS,0001-5172,1399-6576,,Unique_Item_Requests,117,21,12,11,4,10,4,14,3,5,4,4,0,2,14,1,4,4,0\r\n"Acta Neurologica Scandinavica",Wiley,0000000403801313,"Wiley Online Library",10.1111/(ISSN)1600-0404,Wiley:ANE,0001-6314,1600-0404,,Total_Item_Requests,23,0,0,2,0,5,0,1,1,0,2,2,0,2,1,5,2,0,0\r\n"Acta Neurologica Scandinavica",Wiley,0000000403801313,"Wiley Online Library",10.1111/(ISSN)1600-0404,Wiley:ANE,0001-6314,1600-0404,,Unique_Item_Requests,21,0,0,2,0,4,0,1,1,0,1,2,0,2,1,5,2,0,0\r\n"Acta Obstetricia et Gynecologica Scandinavica",Wiley,0000000403801313,"Wiley Online Library",10.1111/(ISSN)1600-0412,Wiley:AOGS,0001-6349,1600-0412,,Total_Item_Requests,22,1,0,0,0,0,0,0,0,0,0,0,0,0,0,15,4,2,0\r\n"Acta Obstetricia et Gynecologica Scandinavica",Wiley,0000000403801313,"Wiley Online Library",10.1111/(ISSN)1600-0412,Wiley:AOGS,0001-6349,1600-0412,,Unique_Item_Requests,11,1,0,0,0,0,0,0,0,0,0,0,0,0,0,7,2,1,0\r\n"Acta Ophthalmologica",Wiley,0000000403801313,"Wiley Online Library",10.1111/(ISSN)1755-3768,Wiley:AOS,1755-375X,1755-3768,,Total_Item_Requests,2,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0\r\n"Acta Ophthalmologica",Wiley,0000000403801313,"Wiley Online Library",10.1111/(ISSN)1755-3768,Wiley:AOS,1755-375X,1755-3768,,Unique_Item_Requests,2,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0\r\n"Acta Paediatrica",Wiley,0000000403801313,"Wiley Online Library",10.1111/(ISSN)1651-2227,Wiley:APA,0803-5253,1651-2227,,Total_Item_Requests,229,23,26,14,12,8,45,22,6,10,8,3,9,7,8,11,9,8,0\r\n"Acta Paediatrica",Wiley,0000000403801313,"Wiley Online Library",10.1111/(ISSN)1651-2227,Wiley:APA,0803-5253,1651-2227,,Unique_Item_Requests,165,16,19,8,8,8,37,11,6,7,6,3,8,6,7,7,3,5,0\r\n"Acta Physiologica",Wiley,0000000403801313,"Wiley Online Library",10.1111/(ISSN)1748-1716,Wiley:APHA,1748-1708,1748-1716,,Total_Item_Requests,13,2,0,0,1,1,8,0,0,0,0,0,0,0,1,0,0,0,0\r\n"Acta Physiologica",Wiley,0000000403801313,"Wiley Online Library",10.1111/(ISSN)1748-1716,Wiley:APHA,1748-1708,1748-1716,,Unique_Item_Requests,12,2,0,0,1,1,7,0,0,0,0,0,0,0,1,0,0,0,0\r\n"Acta Psychiatrica Scandinavica",Wiley,0000000403801313,"Wiley Online Library",10.1111/(ISSN)1600-0447,Wiley:ACPS,0001-690X,1600-0447,,Total_Item_Requests,226,5,9,28,28,15,18,4,1,2,4,13,14,24,8,20,21,12,0\r\n"Acta Psychiatrica Scandinavica",Wiley,0000000403801313,"Wiley Online Library",10.1111/(ISSN)1600-0447,Wiley:ACPS,0001-690X,1600-0447,,Unique_Item_Requests,178,4,5,19,23,10,17,3,1,1,4,13,10,19,6,18,14,11,0\r\n', + filename: "PTFS Journals_TR_J1", + type: "TR_J1", + usage_data_provider_id: 1, + counter_logs: [ + { + borrowernumber: null, + counter_files_id: 2, + erm_counter_log_id: 2, + filename: "PTFS Journals_TR_J1", + importdate: "2023-06-19T09:40:46+00:00", + logdetails: null, + patron: { + cardnumber: "42", + category_id: "S", + check_previous_checkout: "inherit", + date_enrolled: "2024-04-18", + expiry_date: "2032-07-18", + incorrect_address: false, + lang: "default", + library_id: "CPL", + login_attempts: 0, + patron_card_lost: false, + patron_id: 51, + privacy: 1, + privacy_guarantor_checkouts: 0, + privacy_guarantor_fines: false, + protected: false, + restricted: false, + surname: "koha", + updated_on: "2024-04-18T09:42:59+00:00", + userid: "koha", + }, + }, + ], + }; +}; cy.get_usage_data_provider = () => { - return { - "active": 1, - "aggregator": "test_aggregator", - "api_key": '12345', - "begin_date": dates['today_iso'], - "customer_id": "12345", - "description": "A data provider for cypress testing", - "end_date": dates['tomorrow_iso'], - "erm_usage_data_provider_id": 1, - "method": "test", - "name": "Wiley Online Library", - "report_release": "test_report_release", - "report_types": "TR_J1;", - "requestor_email": "test_requestor_email", - "requestor_id": "12345", - "requestor_name": "test_requestor_name", - "service_type": "test_service_type", - "service_url": "www.url.com", - "counter_files": [ + return { + active: 1, + aggregator: "test_aggregator", + api_key: "12345", + begin_date: dates["today_iso"], + customer_id: "12345", + description: "A data provider for cypress testing", + end_date: dates["tomorrow_iso"], + erm_usage_data_provider_id: 1, + method: "test", + name: "Wiley Online Library", + report_release: "test_report_release", + report_types: "TR_J1;", + requestor_email: "test_requestor_email", + requestor_id: "12345", + requestor_name: "test_requestor_name", + service_type: "test_service_type", + service_url: "www.url.com", + counter_files: [ { - "type": "TR_J1", - "date_uploaded": dates['today_iso'] + type: "TR_J1", + date_uploaded: dates["today_iso"], }, { - "type": "TR_J1", - "date_uploaded": dates['tomorrow_iso'] + type: "TR_J1", + date_uploaded: dates["tomorrow_iso"], }, - ], - "earliest_title": "2023-01-01", - "latest_title": "2023-01-01", - "earliest_item": "", - "latest_item": "", - "earliest_platform": "2023-01-01", - "latest_platform": "2023-01-01", - "earliest_database": "", - "latest_database": "", - "last_run": "2023-10-01" - } -} + earliest_title: "2023-01-01", + latest_title: "2023-01-01", + earliest_item: "", + latest_item: "", + earliest_platform: "2023-01-01", + latest_platform: "2023-01-01", + earliest_database: "", + latest_database: "", + last_run: "2023-10-01", + }; +}; cy.get_usage_title = () => { return [ { - "online_issn": "2472-5390", - "print_issn": "2472-5390", - "publisher": "Wiley", - "publisher_id": "0000000403801313", - "title": "AEM Education and Training", - "title_doi": "10.1002/(ISSN)2472-5390", - "title_id": 1338, - "title_uri": "", - "usage_data_provider_id": 5 - } - ] -} + online_issn: "2472-5390", + print_issn: "2472-5390", + publisher: "Wiley", + publisher_id: "0000000403801313", + title: "AEM Education and Training", + title_doi: "10.1002/(ISSN)2472-5390", + title_id: 1338, + title_uri: "", + usage_data_provider_id: 5, + }, + ]; +}; cy.get_default_report = () => { const params = { - "url": "/api/v1/erm/usage_titles/monthly_report?q=[{\"erm_usage_muses.year\":2022,\"erm_usage_muses.report_type\":\"TR_J1\",\"erm_usage_muses.month\":[1,2,3,4,5,6,7,8,9,10,11,12],\"erm_usage_muses.metric_type\":[\"Total_Item_Requests\",\"Unique_Item_Requests\"]},{\"erm_usage_muses.year\":2023,\"erm_usage_muses.report_type\":\"TR_J1\",\"erm_usage_muses.month\":[1,2,3,4,5,6,7,8,9,10,11,12],\"erm_usage_muses.metric_type\":[\"Total_Item_Requests\",\"Unique_Item_Requests\"]}]", - "columns": [1], - "queryObject": { - "data_display": "monthly", - "report_type": "TR_J1", - "metric_types": [ - "Total_Item_Requests", - "Unique_Item_Requests" - ], - "usage_data_providers": null, - "titles": null, - "start_month": null, - "start_year": "2022", - "end_month": null, - "end_year": "2023" + url: '/api/v1/erm/usage_titles/monthly_report?q=[{"erm_usage_muses.year":2022,"erm_usage_muses.report_type":"TR_J1","erm_usage_muses.month":[1,2,3,4,5,6,7,8,9,10,11,12],"erm_usage_muses.metric_type":["Total_Item_Requests","Unique_Item_Requests"]},{"erm_usage_muses.year":2023,"erm_usage_muses.report_type":"TR_J1","erm_usage_muses.month":[1,2,3,4,5,6,7,8,9,10,11,12],"erm_usage_muses.metric_type":["Total_Item_Requests","Unique_Item_Requests"]}]', + columns: [1], + queryObject: { + data_display: "monthly", + report_type: "TR_J1", + metric_types: ["Total_Item_Requests", "Unique_Item_Requests"], + usage_data_providers: null, + titles: null, + start_month: null, + start_year: "2022", + end_month: null, + end_year: "2023", }, - "yearly_filter": true, - "type": "monthly", - "tp_columns": { - "2022": [ + yearly_filter: true, + type: "monthly", + tp_columns: { + 2022: [ { - "short": "Jan", - "description": "January", - "value": 1, - "active": true + short: "Jan", + description: "January", + value: 1, + active: true, }, { - "short": "Feb", - "description": "February", - "value": 2, - "active": true + short: "Feb", + description: "February", + value: 2, + active: true, }, { - "short": "Mar", - "description": "March", - "value": 3, - "active": true + short: "Mar", + description: "March", + value: 3, + active: true, }, { - "short": "Apr", - "description": "April", - "value": 4, - "active": true + short: "Apr", + description: "April", + value: 4, + active: true, }, { - "short": "May", - "description": "May", - "value": 5, - "active": true + short: "May", + description: "May", + value: 5, + active: true, }, { - "short": "Jun", - "description": "June", - "value": 6, - "active": true + short: "Jun", + description: "June", + value: 6, + active: true, }, { - "short": "Jul", - "description": "July", - "value": 7, - "active": true + short: "Jul", + description: "July", + value: 7, + active: true, }, { - "short": "Aug", - "description": "August", - "value": 8, - "active": true + short: "Aug", + description: "August", + value: 8, + active: true, }, { - "short": "Sep", - "description": "September", - "value": 9, - "active": true + short: "Sep", + description: "September", + value: 9, + active: true, }, { - "short": "Oct", - "description": "October", - "value": 10, - "active": true + short: "Oct", + description: "October", + value: 10, + active: true, }, { - "short": "Nov", - "description": "November", - "value": 11, - "active": true + short: "Nov", + description: "November", + value: 11, + active: true, }, { - "short": "Dec", - "description": "December", - "value": 12, - "active": true - } + short: "Dec", + description: "December", + value: 12, + active: true, + }, ], - "2023": [ + 2023: [ { - "short": "Jan", - "description": "January", - "value": 1, - "active": true + short: "Jan", + description: "January", + value: 1, + active: true, }, { - "short": "Feb", - "description": "February", - "value": 2, - "active": true + short: "Feb", + description: "February", + value: 2, + active: true, }, { - "short": "Mar", - "description": "March", - "value": 3, - "active": true + short: "Mar", + description: "March", + value: 3, + active: true, }, { - "short": "Apr", - "description": "April", - "value": 4, - "active": true + short: "Apr", + description: "April", + value: 4, + active: true, }, { - "short": "May", - "description": "May", - "value": 5, - "active": true + short: "May", + description: "May", + value: 5, + active: true, }, { - "short": "Jun", - "description": "June", - "value": 6, - "active": true + short: "Jun", + description: "June", + value: 6, + active: true, }, { - "short": "Jul", - "description": "July", - "value": 7, - "active": true + short: "Jul", + description: "July", + value: 7, + active: true, }, { - "short": "Aug", - "description": "August", - "value": 8, - "active": true + short: "Aug", + description: "August", + value: 8, + active: true, }, { - "short": "Sep", - "description": "September", - "value": 9, - "active": true + short: "Sep", + description: "September", + value: 9, + active: true, }, { - "short": "Oct", - "description": "October", - "value": 10, - "active": true + short: "Oct", + description: "October", + value: 10, + active: true, }, { - "short": "Nov", - "description": "November", - "value": 11, - "active": true + short: "Nov", + description: "November", + value: 11, + active: true, }, { - "short": "Dec", - "description": "December", - "value": 12, - "active": true - } - ] - } - } + short: "Dec", + description: "December", + value: 12, + active: true, + }, + ], + }, + }; return { - "erm_default_usage_report_id": 1, - "report_name": "Cypress report", - "report_url_params": JSON.stringify(params) - } -} + erm_default_usage_report_id: 1, + report_name: "Cypress report", + report_url_params: JSON.stringify(params), + }; +}; cy.get_multiple_providers = () => { return [ { - "active": 1, - "aggregator": "test_aggregator", - "api_key": '12345', - "customer_id": "12345", - "description": "A data provider for cypress testing", - "erm_usage_data_provider_id": 1, - "method": "test", - "name": "Cypress test provider", - "report_release": "test_report_release", - "report_types": "TR_J1;", - "requestor_email": "test_requestor_email", - "requestor_id": "12345", - "requestor_name": "test_requestor_name", - "service_type": "test_service_type", - "service_url": "www.url.com", + active: 1, + aggregator: "test_aggregator", + api_key: "12345", + customer_id: "12345", + description: "A data provider for cypress testing", + erm_usage_data_provider_id: 1, + method: "test", + name: "Cypress test provider", + report_release: "test_report_release", + report_types: "TR_J1;", + requestor_email: "test_requestor_email", + requestor_id: "12345", + requestor_name: "test_requestor_name", + service_type: "test_service_type", + service_url: "www.url.com", }, { - "active": 1, - "aggregator": "test_aggregator", - "api_key": '12345', - "begin_date": dates['today_iso'], - "customer_id": "12345", - "description": "A second provider for reports testing", - "end_date": dates['tomorrow_iso'], - "erm_usage_data_provider_id": 2, - "method": "test", - "name": "Second test provider", - "report_release": "test_report_release", - "report_types": "TR_J1;TR_J2;TR_J3", - "requestor_email": "test_requestor_email", - "requestor_id": "12345", - "requestor_name": "test_requestor_name", - "service_type": "test_service_type", - "service_url": "www.url.com", + active: 1, + aggregator: "test_aggregator", + api_key: "12345", + begin_date: dates["today_iso"], + customer_id: "12345", + description: "A second provider for reports testing", + end_date: dates["tomorrow_iso"], + erm_usage_data_provider_id: 2, + method: "test", + name: "Second test provider", + report_release: "test_report_release", + report_types: "TR_J1;TR_J2;TR_J3", + requestor_email: "test_requestor_email", + requestor_id: "12345", + requestor_name: "test_requestor_name", + service_type: "test_service_type", + service_url: "www.url.com", }, - ] -} + ]; +}; cy.getCounterRegistryProvider = () => { return [ { - "abbrev": "Wiley", - "address": "John Wiley & Sons, Inc.\t\nCorporate Headquarters\tSuite 300\n111 River Street\t\nHoboken, NJ 07030-5774\nUSA", - "address_country": { - "code": "US", - "name": "United States of America" + abbrev: "Wiley", + address: + "John Wiley & Sons, Inc.\t\nCorporate Headquarters\tSuite 300\n111 River Street\t\nHoboken, NJ 07030-5774\nUSA", + address_country: { + code: "US", + name: "United States of America", }, - "contact": { - "email": "eal@wiley.com", - "form_url": "", - "person": "", - "phone": "" + contact: { + email: "eal@wiley.com", + form_url: "", + person: "", + phone: "", }, - "content_provider_name": "John Wiley & Sons", - "host_types": [ + content_provider_name: "John Wiley & Sons", + host_types: [ { - "name": "Aggregated_Full_Content" - } + name: "Aggregated_Full_Content", + }, ], - "id": "60c7aa79-272d-4610-8ad5-c399bd938c8e", - "name": "Wiley Online Library", - "reports": [ + id: "60c7aa79-272d-4610-8ad5-c399bd938c8e", + name: "Wiley Online Library", + reports: [ { - "counter_release": "5", - "report_id": "TR_J4", - "report_name": "Title Report - Journal Report 4" + counter_release: "5", + report_id: "TR_J4", + report_name: "Title Report - Journal Report 4", }, { - "counter_release": "5", - "report_id": "DR_D2", - "report_name": "Database Report - Report 2" + counter_release: "5", + report_id: "DR_D2", + report_name: "Database Report - Report 2", }, { - "counter_release": "5", - "report_id": "TR_J3", - "report_name": "Title Report - Journal Report 3" + counter_release: "5", + report_id: "TR_J3", + report_name: "Title Report - Journal Report 3", }, { - "counter_release": "5", - "report_id": "DR_D1", - "report_name": "Database Report - Report 1" + counter_release: "5", + report_id: "DR_D1", + report_name: "Database Report - Report 1", }, { - "counter_release": "5", - "report_id": "TR_J2", - "report_name": "Title Report - Journal Report 2" + counter_release: "5", + report_id: "TR_J2", + report_name: "Title Report - Journal Report 2", }, { - "counter_release": "5", - "report_id": "PR", - "report_name": "Platform Master Report" + counter_release: "5", + report_id: "PR", + report_name: "Platform Master Report", }, { - "counter_release": "5", - "report_id": "TR_B2", - "report_name": "Title Report - Book Report 2" + counter_release: "5", + report_id: "TR_B2", + report_name: "Title Report - Book Report 2", }, { - "counter_release": "5", - "report_id": "TR_B3", - "report_name": "Title Report - Book Report 3" + counter_release: "5", + report_id: "TR_B3", + report_name: "Title Report - Book Report 3", }, { - "counter_release": "5", - "report_id": "TR", - "report_name": "Title Master Report" + counter_release: "5", + report_id: "TR", + report_name: "Title Master Report", }, { - "counter_release": "5", - "report_id": "TR_B1", - "report_name": "Title Report - Book Report 1" + counter_release: "5", + report_id: "TR_B1", + report_name: "Title Report - Book Report 1", }, { - "counter_release": "5", - "report_id": "PR_P1", - "report_name": "Platform Report - Report 1" + counter_release: "5", + report_id: "PR_P1", + report_name: "Platform Report - Report 1", }, { - "counter_release": "5", - "report_id": "TR_J1", - "report_name": "Title Report - Journal Report 1" + counter_release: "5", + report_id: "TR_J1", + report_name: "Title Report - Journal Report 1", }, { - "counter_release": "5", - "report_id": "DR", - "report_name": "Database Master Report" - } + counter_release: "5", + report_id: "DR", + report_name: "Database Master Report", + }, ], - "sushi_services": [ + sushi_services: [ { - "counter_release": "5", - "url": "https:\/\/registry.projectcounter.org\/api\/v1\/sushi-service\/101d3199-5878-4421-b9c2-88826bee3ad6\/" - } + counter_release: "5", + url: "https:\/\/registry.projectcounter.org\/api\/v1\/sushi-service\/101d3199-5878-4421-b9c2-88826bee3ad6\/", + }, ], - "website": "https:\/\/onlinelibrary.wiley.com\/" - } - ] -} + website: "https:\/\/onlinelibrary.wiley.com\/", + }, + ]; +}; cy.getSushiService = () => { return { - "api_key_info": "", - "api_key_required": false, - "contact": { - "email": "eal@wiley.com", - "form_url": "", - "person": "", - "phone": "" + api_key_info: "", + api_key_required: false, + contact: { + email: "eal@wiley.com", + form_url: "", + person: "", + phone: "", }, - "counter_release": "5", - "credentials_auto_expire": false, - "credentials_auto_expire_info": "", - "customer_id_info": "EAL0000123 (EAL followed by 7 to 11 digits)", - "customizations_in_place": true, - "customizations_info": "Consortia reporting extension", - "data_host": "https:\/\/registry.projectcounter.org\/api\/v1\/usage-data-host\/761269a2-27ed-44ce-8a8f-cca4f198c23f\/", - "id": "101d3199-5878-4421-b9c2-88826bee3ad6", - "ip_address_authorization": false, - "ip_address_authorization_info": "", - "notification_count": 0, - "notifications_url": "https:\/\/registry.projectcounter.org\/api\/v1\/sushi-service\/101d3199-5878-4421-b9c2-88826bee3ad6\/notification\/", - "platform_attr_required": false, - "platform_specific_info": "", - "request_volume_limits_applied": false, - "request_volume_limits_info": "", - "requestor_id_info": "EAL0000123 (EAL followed by 7 to 11 digits)*\r\n(Only required for those operating outside of their approved institutional IP range).", - "requestor_id_required": true, - "url": "https:\/\/onlinelibrary.wiley.com\/reports\/" - } -} + counter_release: "5", + credentials_auto_expire: false, + credentials_auto_expire_info: "", + customer_id_info: "EAL0000123 (EAL followed by 7 to 11 digits)", + customizations_in_place: true, + customizations_info: "Consortia reporting extension", + data_host: + "https:\/\/registry.projectcounter.org\/api\/v1\/usage-data-host\/761269a2-27ed-44ce-8a8f-cca4f198c23f\/", + id: "101d3199-5878-4421-b9c2-88826bee3ad6", + ip_address_authorization: false, + ip_address_authorization_info: "", + notification_count: 0, + notifications_url: + "https:\/\/registry.projectcounter.org\/api\/v1\/sushi-service\/101d3199-5878-4421-b9c2-88826bee3ad6\/notification\/", + platform_attr_required: false, + platform_specific_info: "", + request_volume_limits_applied: false, + request_volume_limits_info: "", + requestor_id_info: + "EAL0000123 (EAL followed by 7 to 11 digits)*\r\n(Only required for those operating outside of their approved institutional IP range).", + requestor_id_required: true, + url: "https:\/\/onlinelibrary.wiley.com\/reports\/", + }; +}; -const mysql = require('cypress-mysql'); +const mysql = require("cypress-mysql"); mysql.addCommands(); diff --git a/t/db_dependent/00-strict.t b/t/db_dependent/00-strict.t index 41515a9451..66a3e8694f 100755 --- a/t/db_dependent/00-strict.t +++ b/t/db_dependent/00-strict.t @@ -37,19 +37,19 @@ $Test::Strict::TEST_STRICT = 0; my $ncpu; if ( $ENV{KOHA_PROVE_CPUS} ) { - $ncpu = $ENV{KOHA_PROVE_CPUS} ; # set number of cpus to use + $ncpu = $ENV{KOHA_PROVE_CPUS}; # set number of cpus to use } else { $ncpu = Sys::CPU::cpu_count(); } -my $pm = Parallel::ForkManager->new($ncpu); +my $pm = Parallel::ForkManager->new($ncpu); foreach my $d (@dirs) { - $pm->start and next; # do the fork + $pm->start and next; # do the fork all_perl_files_ok($d); - $pm->finish; # do the exit in the child process + $pm->finish; # do the exit in the child process } $pm->wait_all_children; diff --git a/t/db_dependent/Accounts.t b/t/db_dependent/Accounts.t index f749706a6c..79bc918614 100755 --- a/t/db_dependent/Accounts.t +++ b/t/db_dependent/Accounts.t @@ -37,19 +37,20 @@ use Koha::DateUtils qw( dt_from_string ); use C4::Circulation qw( MarkIssueReturned ); BEGIN { - use_ok('C4::Accounts', qw( chargelostitem purge_zero_balance_fees )); + use_ok( 'C4::Accounts', qw( chargelostitem purge_zero_balance_fees ) ); use_ok('Koha::Object'); use_ok('Koha::Patron'); use_ok('Data::Dumper'); } -can_ok( 'C4::Accounts', +can_ok( + 'C4::Accounts', qw( chargelostitem purge_zero_balance_fees ) ); -my $schema = Koha::Database->new->schema; +my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; my $dbh = C4::Context->dbh; @@ -59,13 +60,16 @@ my $library = $builder->build( { source => 'Branch' } ); my $branchcode = $library->{branchcode}; my $context = Test::MockModule->new('C4::Context'); -$context->mock( 'userenv', sub { - return { - flags => 1, - id => 'my_userid', - branch => $branchcode, - }; -}); +$context->mock( + 'userenv', + sub { + return { + flags => 1, + id => 'my_userid', + branch => $branchcode, + }; + } +); $context->mock( 'interface', sub { return "commandline" } ); my $userenv_branchcode = $branchcode; @@ -92,22 +96,67 @@ my $sth = $dbh->prepare( my $days = 5; my @test_data = ( - { amount => 0 , days_ago => 0 , description =>'purge_zero_balance_fees should not delete 0 balance fees with date today' , delete => 0, credit_type => undef, debit_type => 'OVERDUE' } , - { amount => 0 , days_ago => $days - 1 , description =>'purge_zero_balance_fees should not delete 0 balance fees with date before threshold day' , delete => 0, credit_type => undef, debit_type => 'OVERDUE' } , - { amount => 0 , days_ago => $days , description =>'purge_zero_balance_fees should not delete 0 balance fees with date on threshold day' , delete => 0, credit_type => undef, debit_type => 'OVERDUE' } , - { amount => 0 , days_ago => $days + 1 , description =>'purge_zero_balance_fees should delete 0 balance fees with date after threshold day' , delete => 1, credit_type => undef, debit_type => 'OVERDUE' } , - { amount => undef , days_ago => $days + 1 , description =>'purge_zero_balance_fees should delete NULL balance fees with date after threshold day' , delete => 1, credit_type => undef, debit_type => 'OVERDUE' } , - { amount => 5 , days_ago => $days - 1 , description =>'purge_zero_balance_fees should not delete fees with positive amout owed before threshold day' , delete => 0, credit_type => undef, debit_type => 'OVERDUE' } , - { amount => 5 , days_ago => $days , description =>'purge_zero_balance_fees should not delete fees with positive amout owed on threshold day' , delete => 0, credit_type => undef, debit_type => 'OVERDUE' } , - { amount => 5 , days_ago => $days + 1 , description =>'purge_zero_balance_fees should not delete fees with positive amout owed after threshold day' , delete => 0, credit_type => undef, debit_type => 'OVERDUE' } , - { amount => -5 , days_ago => $days - 1 , description =>'purge_zero_balance_fees should not delete fees with negative amout owed before threshold day' , delete => 0, credit_type => 'PAYMENT', debit_type => undef } , - { amount => -5 , days_ago => $days , description =>'purge_zero_balance_fees should not delete fees with negative amout owed on threshold day' , delete => 0, credit_type => 'PAYMENT', debit_type => undef } , - { amount => -5 , days_ago => $days + 1 , description =>'purge_zero_balance_fees should not delete fees with negative amout owed after threshold day' , delete => 0, credit_type => 'PAYMENT', debit_type => undef } + { + amount => 0, days_ago => 0, + description => 'purge_zero_balance_fees should not delete 0 balance fees with date today', delete => 0, + credit_type => undef, debit_type => 'OVERDUE' + }, + { + amount => 0, days_ago => $days - 1, + description => 'purge_zero_balance_fees should not delete 0 balance fees with date before threshold day', + delete => 0, credit_type => undef, debit_type => 'OVERDUE' + }, + { + amount => 0, days_ago => $days, + description => 'purge_zero_balance_fees should not delete 0 balance fees with date on threshold day', + delete => 0, credit_type => undef, debit_type => 'OVERDUE' + }, + { + amount => 0, days_ago => $days + 1, + description => 'purge_zero_balance_fees should delete 0 balance fees with date after threshold day', + delete => 1, credit_type => undef, debit_type => 'OVERDUE' + }, + { + amount => undef, days_ago => $days + 1, + description => 'purge_zero_balance_fees should delete NULL balance fees with date after threshold day', + delete => 1, credit_type => undef, debit_type => 'OVERDUE' + }, + { + amount => 5, days_ago => $days - 1, + description => 'purge_zero_balance_fees should not delete fees with positive amout owed before threshold day', + delete => 0, credit_type => undef, debit_type => 'OVERDUE' + }, + { + amount => 5, days_ago => $days, + description => 'purge_zero_balance_fees should not delete fees with positive amout owed on threshold day', + delete => 0, credit_type => undef, debit_type => 'OVERDUE' + }, + { + amount => 5, days_ago => $days + 1, + description => 'purge_zero_balance_fees should not delete fees with positive amout owed after threshold day', + delete => 0, credit_type => undef, debit_type => 'OVERDUE' + }, + { + amount => -5, days_ago => $days - 1, + description => 'purge_zero_balance_fees should not delete fees with negative amout owed before threshold day', + delete => 0, credit_type => 'PAYMENT', debit_type => undef + }, + { + amount => -5, days_ago => $days, + description => 'purge_zero_balance_fees should not delete fees with negative amout owed on threshold day', + delete => 0, credit_type => 'PAYMENT', debit_type => undef + }, + { + amount => -5, days_ago => $days + 1, + description => 'purge_zero_balance_fees should not delete fees with negative amout owed after threshold day', + delete => 0, credit_type => 'PAYMENT', debit_type => undef + } ); -my $categorycode = $builder->build({ source => 'Category' })->{categorycode}; -my $borrower = Koha::Patron->new( { firstname => 'Test', surname => 'Patron', categorycode => $categorycode, branchcode => $branchcode } )->store(); +my $categorycode = $builder->build( { source => 'Category' } )->{categorycode}; +my $borrower = Koha::Patron->new( + { firstname => 'Test', surname => 'Patron', categorycode => $categorycode, branchcode => $branchcode } )->store(); -for my $data ( @test_data ) { +for my $data (@test_data) { $sth->execute( $borrower->borrowernumber, $data->{amount}, @@ -119,25 +168,25 @@ for my $data ( @test_data ) { ); } -purge_zero_balance_fees( $days ); +purge_zero_balance_fees($days); $sth = $dbh->prepare( - "select count(*) = 0 as deleted + "select count(*) = 0 as deleted from accountlines where description = ?" - ); +); # sub is_delete_correct { my $should_delete = shift; - my $description = shift; - $sth->execute( $description ); + my $description = shift; + $sth->execute($description); my $test = $sth->fetchrow_hashref(); - is( $test->{deleted}, $should_delete, $description ) + is( $test->{deleted}, $should_delete, $description ); } -for my $data (@test_data) { - is_delete_correct( $data->{delete}, $data->{description}); +for my $data (@test_data) { + is_delete_correct( $data->{delete}, $data->{description} ); } $dbh->do(q|DELETE FROM accountlines|); @@ -147,97 +196,99 @@ subtest "Koha::Account::pay - always AutoReconcile + notes tests" => sub { plan tests => 17; # Create a borrower - my $categorycode = $builder->build({ source => 'Category' })->{ categorycode }; - my $branchcode = $builder->build({ source => 'Branch' })->{ branchcode }; + my $categorycode = $builder->build( { source => 'Category' } )->{categorycode}; + my $branchcode = $builder->build( { source => 'Branch' } )->{branchcode}; - my $borrower = Koha::Patron->new( { - cardnumber => '1234567890', - surname => 'McFly', - firstname => 'Marty', - } ); - $borrower->categorycode( $categorycode ); - $borrower->branchcode( $branchcode ); + my $borrower = Koha::Patron->new( + { + cardnumber => '1234567890', + surname => 'McFly', + firstname => 'Marty', + } + ); + $borrower->categorycode($categorycode); + $borrower->branchcode($branchcode); $borrower->store; - my $account = Koha::Account->new({ patron_id => $borrower->id }); + my $account = Koha::Account->new( { patron_id => $borrower->id } ); - my $line1 = $account->add_debit({ type => 'ACCOUNT', amount => 100, interface => 'commandline' }); - my $line2 = $account->add_debit({ type => 'ACCOUNT', amount => 200, interface => 'commandline' }); + my $line1 = $account->add_debit( { type => 'ACCOUNT', amount => 100, interface => 'commandline' } ); + my $line2 = $account->add_debit( { type => 'ACCOUNT', amount => 200, interface => 'commandline' } ); $sth = $dbh->prepare("SELECT count(*) FROM accountlines"); $sth->execute; my $count = $sth->fetchrow_array; - is($count, 2, 'There is 2 lines as expected'); + is( $count, 2, 'There is 2 lines as expected' ); # There is $100 in the account $sth = $dbh->prepare("SELECT amountoutstanding FROM accountlines WHERE borrowernumber=?"); my $outstanding_debt = $account->outstanding_debits->total_outstanding; - is($outstanding_debt, 300, 'The account has $300 outstanding debt as expected' ); + is( $outstanding_debt, 300, 'The account has $300 outstanding debt as expected' ); my $outstanding_credit = $account->outstanding_credits->total_outstanding; - is($outstanding_credit, 0, 'The account has $0 outstanding credit as expected' ); + is( $outstanding_credit, 0, 'The account has $0 outstanding credit as expected' ); # We make a $20 payment my $borrowernumber = $borrower->borrowernumber; - my $data = '20.00'; - my $payment_note = '$20.00 payment note'; + my $data = '20.00'; + my $payment_note = '$20.00 payment note'; my $id = $account->pay( { amount => $data, note => $payment_note, payment_type => "TEST_TYPE" } )->{payment_id}; - my $accountline = Koha::Account::Lines->find( $id ); + my $accountline = Koha::Account::Lines->find($id); is( $accountline->payment_type, "TEST_TYPE", "Payment type passed into pay is set in account line correctly" ); # There is now $280 in the account $outstanding_debt = $account->outstanding_debits->total_outstanding; - is($outstanding_debt, 280, 'The account has $280 outstanding debt as expected' ); + is( $outstanding_debt, 280, 'The account has $280 outstanding debt as expected' ); $outstanding_credit = $account->outstanding_credits->total_outstanding; - is($outstanding_credit, 0, 'The account has $0 outstanding credit as expected' ); + is( $outstanding_credit, 0, 'The account has $0 outstanding credit as expected' ); # Is the payment note well registered - is($accountline->note,'$20.00 payment note', '$20.00 payment note is registered'); + is( $accountline->note, '$20.00 payment note', '$20.00 payment note is registered' ); # We attempt to make a -$30 payment (a NEGATIVE payment) - $data = '-30.00'; + $data = '-30.00'; $payment_note = '-$30.00 payment note'; throws_ok { $account->pay( { amount => $data, note => $payment_note } ) } 'Koha::Exceptions::Account::AmountNotPositive', - 'Croaked on call to pay with negative amount'; + 'Croaked on call to pay with negative amount'; #We make a $150 payment ( > 1stLine ) - $data = '150.00'; + $data = '150.00'; $payment_note = '$150.00 payment note'; - $id = $account->pay( { amount => $data, note => $payment_note } )->{payment_id}; + $id = $account->pay( { amount => $data, note => $payment_note } )->{payment_id}; # There is now $130 in the account $outstanding_debt = $account->outstanding_debits->total_outstanding; - is($outstanding_debt, 130, 'The account has $130 outstanding debt as expected' ); + is( $outstanding_debt, 130, 'The account has $130 outstanding debt as expected' ); $outstanding_credit = $account->outstanding_credits->total_outstanding; - is($outstanding_credit, 0, 'The account has $0 outstanding credit as expected' ); + is( $outstanding_credit, 0, 'The account has $0 outstanding credit as expected' ); # Is the payment note well registered - $accountline = Koha::Account::Lines->find( $id ); - is($accountline->note,'$150.00 payment note', '$150.00 payment note is registered'); + $accountline = Koha::Account::Lines->find($id); + is( $accountline->note, '$150.00 payment note', '$150.00 payment note is registered' ); #We make a $200 payment ( > amountleft ) - $data = '200.00'; + $data = '200.00'; $payment_note = '$200.00 payment note'; - $id = $account->pay( { amount => $data, note => $payment_note } )->{payment_id}; + $id = $account->pay( { amount => $data, note => $payment_note } )->{payment_id}; # There is now -$70 in the account $outstanding_debt = $account->outstanding_debits->total_outstanding; - is($outstanding_debt, 0, 'The account has $0 outstanding debt as expected' ); + is( $outstanding_debt, 0, 'The account has $0 outstanding debt as expected' ); $outstanding_credit = $account->outstanding_credits->total_outstanding; - is($outstanding_credit, -70, 'The account has -$70 outstanding credit as expected' ); + is( $outstanding_credit, -70, 'The account has -$70 outstanding credit as expected' ); # Is the payment note well registered - $accountline = Koha::Account::Lines->find( $id ); - is($accountline->note,'$200.00 payment note', '$200.00 payment note is registered'); + $accountline = Koha::Account::Lines->find($id); + is( $accountline->note, '$200.00 payment note', '$200.00 payment note is registered' ); - my $line3 = $account->add_debit({ type => 'ACCOUNT', amount => 42, interface => 'commandline' }); - $id = $account->pay( { lines => [$line3], amount => 42 } )->{payment_id}; - $accountline = Koha::Account::Lines->find( $id ); - is( $accountline->amount()+0, -42, "Payment paid the specified fine" ); + my $line3 = $account->add_debit( { type => 'ACCOUNT', amount => 42, interface => 'commandline' } ); + $id = $account->pay( { lines => [$line3], amount => 42 } )->{payment_id}; + $accountline = Koha::Account::Lines->find($id); + is( $accountline->amount() + 0, -42, "Payment paid the specified fine" ); $line3 = Koha::Account::Lines->find( $line3->id ); - is( $line3->amountoutstanding+0, 0, "Specified fine is paid" ); - is( $accountline->branchcode, undef, 'branchcode passed, then undef' ); + is( $line3->amountoutstanding + 0, 0, "Specified fine is paid" ); + is( $accountline->branchcode, undef, 'branchcode passed, then undef' ); }; subtest "Koha::Account::pay particular line tests" => sub { @@ -245,30 +296,32 @@ subtest "Koha::Account::pay particular line tests" => sub { plan tests => 5; # Create a borrower - my $categorycode = $builder->build({ source => 'Category' })->{ categorycode }; - my $branchcode = $builder->build({ source => 'Branch' })->{ branchcode }; + my $categorycode = $builder->build( { source => 'Category' } )->{categorycode}; + my $branchcode = $builder->build( { source => 'Branch' } )->{branchcode}; - my $borrower = Koha::Patron->new( { - cardnumber => 'kylemhall', - surname => 'Hall', - firstname => 'Kyle', - } ); - $borrower->categorycode( $categorycode ); - $borrower->branchcode( $branchcode ); + my $borrower = Koha::Patron->new( + { + cardnumber => 'kylemhall', + surname => 'Hall', + firstname => 'Kyle', + } + ); + $borrower->categorycode($categorycode); + $borrower->branchcode($branchcode); $borrower->store; - my $account = Koha::Account->new({ patron_id => $borrower->id }); + my $account = Koha::Account->new( { patron_id => $borrower->id } ); - my $line1 = $account->add_debit({ type => 'ACCOUNT', amount => 1, interface => 'commandline' }); - my $line2 = $account->add_debit({ type => 'ACCOUNT', amount => 2, interface => 'commandline' }); - my $line3 = $account->add_debit({ type => 'ACCOUNT', amount => 3, interface => 'commandline' }); - my $line4 = $account->add_debit({ type => 'ACCOUNT', amount => 4, interface => 'commandline' }); + my $line1 = $account->add_debit( { type => 'ACCOUNT', amount => 1, interface => 'commandline' } ); + my $line2 = $account->add_debit( { type => 'ACCOUNT', amount => 2, interface => 'commandline' } ); + my $line3 = $account->add_debit( { type => 'ACCOUNT', amount => 3, interface => 'commandline' } ); + my $line4 = $account->add_debit( { type => 'ACCOUNT', amount => 4, interface => 'commandline' } ); is( $account->balance(), 10, "Account balance is 10" ); $account->pay( { - lines => [$line2, $line3, $line4], + lines => [ $line2, $line3, $line4 ], amount => 4, } ); @@ -276,13 +329,16 @@ subtest "Koha::Account::pay particular line tests" => sub { $_->_result->discard_changes foreach ( $line1, $line2, $line3, $line4 ); # Line1 is not paid at all, as it was not passed in the lines param - is( $line1->amountoutstanding+0, 1, "Line 1 was not paid" ); + is( $line1->amountoutstanding + 0, 1, "Line 1 was not paid" ); + # Line2 was paid in full, as it was the first in the lines list - is( $line2->amountoutstanding+0, 0, "Line 2 was paid in full" ); + is( $line2->amountoutstanding + 0, 0, "Line 2 was paid in full" ); + # Line3 was paid partially, as the remaining balance did not cover it entirely - is( $line3->amountoutstanding+0, 1, "Line 3 was paid to 1.00" ); + is( $line3->amountoutstanding + 0, 1, "Line 3 was paid to 1.00" ); + # Line4 was not paid at all, as the payment was all used up by that point - is( $line4->amountoutstanding+0, 4, "Line 4 was not paid" ); + is( $line4->amountoutstanding + 0, 4, "Line 4 was not paid" ); }; subtest "Koha::Account::pay writeoff tests" => sub { @@ -290,21 +346,23 @@ subtest "Koha::Account::pay writeoff tests" => sub { plan tests => 5; # Create a borrower - my $categorycode = $builder->build({ source => 'Category' })->{ categorycode }; - my $branchcode = $builder->build({ source => 'Branch' })->{ branchcode }; + my $categorycode = $builder->build( { source => 'Category' } )->{categorycode}; + my $branchcode = $builder->build( { source => 'Branch' } )->{branchcode}; - my $borrower = Koha::Patron->new( { - cardnumber => 'chelseahall', - surname => 'Hall', - firstname => 'Chelsea', - } ); - $borrower->categorycode( $categorycode ); - $borrower->branchcode( $branchcode ); + my $borrower = Koha::Patron->new( + { + cardnumber => 'chelseahall', + surname => 'Hall', + firstname => 'Chelsea', + } + ); + $borrower->categorycode($categorycode); + $borrower->branchcode($branchcode); $borrower->store; - my $account = Koha::Account->new({ patron_id => $borrower->id }); + my $account = Koha::Account->new( { patron_id => $borrower->id } ); - my $line = $account->add_debit({ type => 'ACCOUNT', amount => 42, interface => 'commandline' }); + my $line = $account->add_debit( { type => 'ACCOUNT', amount => 42, interface => 'commandline' } ); is( $account->balance(), 42, "Account balance is 42" ); @@ -318,13 +376,13 @@ subtest "Koha::Account::pay writeoff tests" => sub { $line->_result->discard_changes(); - is( $line->amountoutstanding+0, 0, "Line was written off" ); + is( $line->amountoutstanding + 0, 0, "Line was written off" ); - my $writeoff = Koha::Account::Lines->find( $id ); + my $writeoff = Koha::Account::Lines->find($id); is( $writeoff->credit_type_code, 'WRITEOFF', 'Type is correct for WRITEOFF' ); - is( $writeoff->description, '', 'Description is correct' ); - is( $writeoff->amount+0, -42, 'Amount is correct' ); + is( $writeoff->description, '', 'Description is correct' ); + is( $writeoff->amount + 0, -42, 'Amount is correct' ); }; subtest "More Koha::Account::pay tests" => sub { @@ -332,16 +390,20 @@ subtest "More Koha::Account::pay tests" => sub { plan tests => 12; # Create a borrower - my $category = $builder->build({ source => 'Category' })->{ categorycode }; - my $branch = $builder->build({ source => 'Branch' })->{ branchcode }; + my $category = $builder->build( { source => 'Category' } )->{categorycode}; + my $branch = $builder->build( { source => 'Branch' } )->{branchcode}; $branchcode = $branch; - my $borrowernumber = $builder->build({ - source => 'Borrower', - value => { categorycode => $category, - branchcode => $branch } - })->{ borrowernumber }; + my $borrowernumber = $builder->build( + { + source => 'Borrower', + value => { + categorycode => $category, + branchcode => $branch + } + } + )->{borrowernumber}; - my $amount = 100; + my $amount = 100; my $accountline = $builder->build( { source => 'Accountline', @@ -354,14 +416,13 @@ subtest "More Koha::Account::pay tests" => sub { } ); - my $rs = $schema->resultset('Accountline')->search({ - borrowernumber => $borrowernumber - }); + my $rs = $schema->resultset('Accountline')->search( { borrowernumber => $borrowernumber } ); is( $rs->count(), 1, 'Accountline created' ); my $account = Koha::Account->new( { patron_id => $borrowernumber } ); - my $line = Koha::Account::Lines->find( $accountline->{ accountlines_id } ); + my $line = Koha::Account::Lines->find( $accountline->{accountlines_id} ); + # make the full payment my $payment = $account->pay( { @@ -372,30 +433,33 @@ subtest "More Koha::Account::pay tests" => sub { } ); - my $offsets = Koha::Account::Offsets->search({ credit_id => $payment->{payment_id} }); - is( $offsets->count, 2, 'Two offsets recorded'); + my $offsets = Koha::Account::Offsets->search( { credit_id => $payment->{payment_id} } ); + is( $offsets->count, 2, 'Two offsets recorded' ); my $offset = $offsets->next; - is( $offset->type(), 'CREATE', 'First offset type is CREATE' ); - is( $offset->amount+0, 100, 'First offset amount is 100.00' ); + is( $offset->type(), 'CREATE', 'First offset type is CREATE' ); + is( $offset->amount + 0, 100, 'First offset amount is 100.00' ); $offset = $offsets->next; - is( $offset->type(), 'APPLY', 'Second offset type is APPLY' ); - is( $offset->amount+0, -100, 'Second offset amount is -100.00' ); - is( $offset->debit_id, $accountline->{accountlines_id}, 'Second offset is against the right accountline'); + is( $offset->type(), 'APPLY', 'Second offset type is APPLY' ); + is( $offset->amount + 0, -100, 'Second offset amount is -100.00' ); + is( $offset->debit_id, $accountline->{accountlines_id}, 'Second offset is against the right accountline' ); - my $stat = $schema->resultset('Statistic')->search({ - branch => $branch, - type => 'PAYMENT' - }, { order_by => { -desc => 'datetime' } })->next(); + my $stat = $schema->resultset('Statistic')->search( + { + branch => $branch, + type => 'PAYMENT' + }, + { order_by => { -desc => 'datetime' } } + )->next(); ok( defined $stat, "There's a payment log that matches the branch" ); - SKIP: { +SKIP: { skip "No statistic logged", 4 unless defined $stat; - is( $stat->type, 'payment', "Correct statistic type" ); - is( $stat->branch, $branch, "Correct branch logged to statistics" ); + is( $stat->type, 'payment', "Correct statistic type" ); + is( $stat->branch, $branch, "Correct branch logged to statistics" ); is( $stat->borrowernumber, $borrowernumber, "Correct borrowernumber logged to statistics" ); - is( $stat->value+0, -$amount, "Correct amount logged to statistics" ); + is( $stat->value + 0, -$amount, "Correct amount logged to statistics" ); } }; @@ -404,18 +468,22 @@ subtest "Even more Koha::Account::pay tests" => sub { plan tests => 12; # Create a borrower - my $category = $builder->build({ source => 'Category' })->{ categorycode }; - my $branch = $builder->build({ source => 'Branch' })->{ branchcode }; + my $category = $builder->build( { source => 'Category' } )->{categorycode}; + my $branch = $builder->build( { source => 'Branch' } )->{branchcode}; $branchcode = $branch; - my $borrowernumber = $builder->build({ - source => 'Borrower', - value => { categorycode => $category, - branchcode => $branch } - })->{ borrowernumber }; + my $borrowernumber = $builder->build( + { + source => 'Borrower', + value => { + categorycode => $category, + branchcode => $branch + } + } + )->{borrowernumber}; - my $amount = 100; + my $amount = 100; my $partialamount = 60; - my $accountline = $builder->build( + my $accountline = $builder->build( { source => 'Accountline', value => { @@ -427,14 +495,13 @@ subtest "Even more Koha::Account::pay tests" => sub { } ); - my $rs = $schema->resultset('Accountline')->search({ - borrowernumber => $borrowernumber - }); + my $rs = $schema->resultset('Accountline')->search( { borrowernumber => $borrowernumber } ); is( $rs->count(), 1, 'Accountline created' ); my $account = Koha::Account->new( { patron_id => $borrowernumber } ); - my $line = Koha::Account::Lines->find( $accountline->{ accountlines_id } ); + my $line = Koha::Account::Lines->find( $accountline->{accountlines_id} ); + # make the full payment my $payment = $account->pay( { @@ -445,37 +512,40 @@ subtest "Even more Koha::Account::pay tests" => sub { } ); - my $offsets = Koha::Account::Offsets->search({ credit_id => $payment->{payment_id} }); - is( $offsets->count, 2, 'Two offsets recorded'); + my $offsets = Koha::Account::Offsets->search( { credit_id => $payment->{payment_id} } ); + is( $offsets->count, 2, 'Two offsets recorded' ); my $offset = $offsets->next; - is( $offset->type(), 'CREATE', 'First offset type is CREATE' ); - is( $offset->amount+0, 60, 'First offset amount is 60.00' ); + is( $offset->type(), 'CREATE', 'First offset type is CREATE' ); + is( $offset->amount + 0, 60, 'First offset amount is 60.00' ); $offset = $offsets->next; - is( $offset->type(), 'APPLY', 'Second offset type is APPLY' ); - is( $offset->amount+0, -60, 'Second offset amount is -60.00' ); - is( $offset->debit_id, $accountline->{accountlines_id}, 'Second offset is against the right accountline'); + is( $offset->type(), 'APPLY', 'Second offset type is APPLY' ); + is( $offset->amount + 0, -60, 'Second offset amount is -60.00' ); + is( $offset->debit_id, $accountline->{accountlines_id}, 'Second offset is against the right accountline' ); - my $stat = $schema->resultset('Statistic')->search({ - branch => $branch, - type => 'PAYMENT' - }, { order_by => { -desc => 'datetime' } })->next(); + my $stat = $schema->resultset('Statistic')->search( + { + branch => $branch, + type => 'PAYMENT' + }, + { order_by => { -desc => 'datetime' } } + )->next(); ok( defined $stat, "There's a payment log that matches the branch" ); - SKIP: { +SKIP: { skip "No statistic logged", 4 unless defined $stat; - is( $stat->type, 'payment', "Correct statistic type" ); - is( $stat->branch, $branch, "Correct branch logged to statistics" ); + is( $stat->type, 'payment', "Correct statistic type" ); + is( $stat->branch, $branch, "Correct branch logged to statistics" ); is( $stat->borrowernumber, $borrowernumber, "Correct borrowernumber logged to statistics" ); - is( $stat->value+0, -$partialamount, "Correct amount logged to statistics" ); + is( $stat->value + 0, -$partialamount, "Correct amount logged to statistics" ); } }; subtest 'balance' => sub { plan tests => 2; - my $patron = $builder->build({source => 'Borrower'}); + my $patron = $builder->build( { source => 'Borrower' } ); $patron = Koha::Patrons->find( $patron->{borrowernumber} ); my $account = $patron->account; is( $account->balance, 0, 'balance should return 0 if the patron does not have fines' ); @@ -504,7 +574,7 @@ subtest 'balance' => sub { ); my $balance = $patron->account->balance; - is( int($balance), 29, 'balance should return the correct value'); + is( int($balance), 29, 'balance should return the correct value' ); $patron->delete; }; @@ -512,10 +582,10 @@ subtest 'balance' => sub { subtest "C4::Accounts::chargelostitem tests" => sub { plan tests => 3; - my $branch = $builder->build( { source => 'Branch' } ); + my $branch = $builder->build( { source => 'Branch' } ); my $branchcode = $branch->{branchcode}; - my $staff = $builder->build( { source => 'Borrower' } ); + my $staff = $builder->build( { source => 'Borrower' } ); my $staff_id = $staff->{borrowernumber}; my $module = Test::MockModule->new('C4::Context'); @@ -530,41 +600,71 @@ subtest "C4::Accounts::chargelostitem tests" => sub { } ); - my $itype_no_replace_no_fee = $builder->build({ source => 'Itemtype', value => { - rentalcharge => 0, - defaultreplacecost => undef, - processfee => undef, - }}); - my $itype_replace_no_fee = $builder->build({ source => 'Itemtype', value => { - rentalcharge => 0, - defaultreplacecost => 16.32, - processfee => undef, - }}); - my $itype_no_replace_fee = $builder->build({ source => 'Itemtype', value => { - rentalcharge => 0, - defaultreplacecost => undef, - processfee => 8.16, - }}); - my $itype_replace_fee = $builder->build({ source => 'Itemtype', value => { - rentalcharge => 0, - defaultreplacecost => 4.08, - processfee => 2.04, - }}); - my $cli_borrowernumber = $builder->build({ source => 'Borrower' })->{'borrowernumber'}; - my $cli_itemnumber1 = $builder->build_sample_item({ itype => $itype_no_replace_no_fee->{itemtype} })->itemnumber; - my $cli_itemnumber2 = $builder->build_sample_item({ itype => $itype_replace_no_fee->{itemtype} })->itemnumber; - my $cli_itemnumber3 = $builder->build_sample_item({ itype => $itype_no_replace_fee->{itemtype} })->itemnumber; - my $cli_itemnumber4 = $builder->build_sample_item({ itype => $itype_replace_fee->{itemtype} })->itemnumber; - my $cli_itemnumber5 = $builder->build_sample_item({ itype => $itype_replace_fee->{itemtype} })->itemnumber; - my $cli_bundle1 = $builder->build_sample_item({ itype => $itype_no_replace_no_fee->{itemtype} })->itemnumber; + my $itype_no_replace_no_fee = $builder->build( + { + source => 'Itemtype', + value => { + rentalcharge => 0, + defaultreplacecost => undef, + processfee => undef, + } + } + ); + my $itype_replace_no_fee = $builder->build( + { + source => 'Itemtype', + value => { + rentalcharge => 0, + defaultreplacecost => 16.32, + processfee => undef, + } + } + ); + my $itype_no_replace_fee = $builder->build( + { + source => 'Itemtype', + value => { + rentalcharge => 0, + defaultreplacecost => undef, + processfee => 8.16, + } + } + ); + my $itype_replace_fee = $builder->build( + { + source => 'Itemtype', + value => { + rentalcharge => 0, + defaultreplacecost => 4.08, + processfee => 2.04, + } + } + ); + my $cli_borrowernumber = $builder->build( { source => 'Borrower' } )->{'borrowernumber'}; + my $cli_itemnumber1 = $builder->build_sample_item( { itype => $itype_no_replace_no_fee->{itemtype} } )->itemnumber; + my $cli_itemnumber2 = $builder->build_sample_item( { itype => $itype_replace_no_fee->{itemtype} } )->itemnumber; + my $cli_itemnumber3 = $builder->build_sample_item( { itype => $itype_no_replace_fee->{itemtype} } )->itemnumber; + my $cli_itemnumber4 = $builder->build_sample_item( { itype => $itype_replace_fee->{itemtype} } )->itemnumber; + my $cli_itemnumber5 = $builder->build_sample_item( { itype => $itype_replace_fee->{itemtype} } )->itemnumber; + my $cli_bundle1 = $builder->build_sample_item( { itype => $itype_no_replace_no_fee->{itemtype} } )->itemnumber; $schema->resultset('ItemBundle')->create( { host => $cli_bundle1, item => $cli_itemnumber5 } ); - my $cli_issue_id_1 = $builder->build({ source => 'Issue', value => { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber1 } })->{issue_id}; - my $cli_issue_id_2 = $builder->build({ source => 'Issue', value => { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber2 } })->{issue_id}; - my $cli_issue_id_3 = $builder->build({ source => 'Issue', value => { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber3 } })->{issue_id}; - my $cli_issue_id_4 = $builder->build({ source => 'Issue', value => { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4 } })->{issue_id}; - my $cli_issue_id_4X = undef; - my $cli_bundle_issue = $builder->build({ source => 'Issue', value => { borrowernumber => $cli_borrowernumber, itemnumber => $cli_bundle1 } })->{issue_id}; + my $cli_issue_id_1 = $builder->build( + { source => 'Issue', value => { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber1 } } ) + ->{issue_id}; + my $cli_issue_id_2 = $builder->build( + { source => 'Issue', value => { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber2 } } ) + ->{issue_id}; + my $cli_issue_id_3 = $builder->build( + { source => 'Issue', value => { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber3 } } ) + ->{issue_id}; + my $cli_issue_id_4 = $builder->build( + { source => 'Issue', value => { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4 } } ) + ->{issue_id}; + my $cli_issue_id_4X = undef; + my $cli_bundle_issue = $builder->build( + { source => 'Issue', value => { borrowernumber => $cli_borrowernumber, itemnumber => $cli_bundle1 } } ) + ->{issue_id}; my $lostfine; my $procfee; @@ -572,140 +672,208 @@ subtest "C4::Accounts::chargelostitem tests" => sub { subtest "fee application tests" => sub { plan tests => 48; - t::lib::Mocks::mock_preference('item-level_itypes', '1'); - t::lib::Mocks::mock_preference('useDefaultReplacementCost', '0'); + t::lib::Mocks::mock_preference( 'item-level_itypes', '1' ); + t::lib::Mocks::mock_preference( 'useDefaultReplacementCost', '0' ); - C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber1, 0, "Perdedor"); - $lostfine = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber1, debit_type_code => 'LOST' }); - $procfee = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber1, debit_type_code => 'PROCESSING' }); - ok( !$lostfine, "No lost fine if no replacementcost or default when pref off"); - ok( !$procfee, "No processing fee if no processing fee"); - C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber1, 6.12, "Perdedor"); - $lostfine = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber1, debit_type_code => 'LOST' }); - $procfee = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber1, debit_type_code => 'PROCESSING' }); - ok( $lostfine->amount == 6.12, "Lost fine equals replacementcost when pref off and no default set"); - ok( !$procfee, "No processing fee if no processing fee"); + C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber1, 0, "Perdedor" ); + $lostfine = Koha::Account::Lines->find( + { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber1, debit_type_code => 'LOST' } ); + $procfee = Koha::Account::Lines->find( + { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber1, debit_type_code => 'PROCESSING' } + ); + ok( !$lostfine, "No lost fine if no replacementcost or default when pref off" ); + ok( !$procfee, "No processing fee if no processing fee" ); + C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber1, 6.12, "Perdedor" ); + $lostfine = Koha::Account::Lines->find( + { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber1, debit_type_code => 'LOST' } ); + $procfee = Koha::Account::Lines->find( + { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber1, debit_type_code => 'PROCESSING' } + ); + ok( $lostfine->amount == 6.12, "Lost fine equals replacementcost when pref off and no default set" ); + ok( !$procfee, "No processing fee if no processing fee" ); $lostfine->delete(); - C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber2, 0, "Perdedor"); - $lostfine = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber2, debit_type_code => 'LOST' }); - $procfee = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber2, debit_type_code => 'PROCESSING' }); - ok( !$lostfine, "No lost fine if no replacementcost but default set when pref off"); - ok( !$procfee, "No processing fee if no processing fee"); - C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber2, 6.12, "Perdedor"); - $lostfine = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber2, debit_type_code => 'LOST' }); - $procfee = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber2, debit_type_code => 'PROCESSING' }); - ok( $lostfine->amount == 6.12 , "Lost fine equals replacementcost when pref off and default set"); - ok( !$procfee, "No processing fee if no processing fee"); + C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber2, 0, "Perdedor" ); + $lostfine = Koha::Account::Lines->find( + { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber2, debit_type_code => 'LOST' } ); + $procfee = Koha::Account::Lines->find( + { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber2, debit_type_code => 'PROCESSING' } + ); + ok( !$lostfine, "No lost fine if no replacementcost but default set when pref off" ); + ok( !$procfee, "No processing fee if no processing fee" ); + C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber2, 6.12, "Perdedor" ); + $lostfine = Koha::Account::Lines->find( + { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber2, debit_type_code => 'LOST' } ); + $procfee = Koha::Account::Lines->find( + { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber2, debit_type_code => 'PROCESSING' } + ); + ok( $lostfine->amount == 6.12, "Lost fine equals replacementcost when pref off and default set" ); + ok( !$procfee, "No processing fee if no processing fee" ); $lostfine->delete(); - C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber3, 0, "Perdedor"); - $lostfine = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber3, debit_type_code => 'LOST' }); - $procfee = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber3, debit_type_code => 'PROCESSING' }); - ok( !$lostfine, "No lost fine if no replacementcost and no default set when pref off"); - ok( $procfee->amount == 8.16, "Processing fee if processing fee"); + C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber3, 0, "Perdedor" ); + $lostfine = Koha::Account::Lines->find( + { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber3, debit_type_code => 'LOST' } ); + $procfee = Koha::Account::Lines->find( + { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber3, debit_type_code => 'PROCESSING' } + ); + ok( !$lostfine, "No lost fine if no replacementcost and no default set when pref off" ); + ok( $procfee->amount == 8.16, "Processing fee if processing fee" ); is( $procfee->issue_id, $cli_issue_id_3, "Processing fee issue id is correct" ); $procfee->delete(); - C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber3, 6.12, "Perdedor"); - $lostfine = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber3, debit_type_code => 'LOST' }); - $procfee = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber3, debit_type_code => 'PROCESSING' }); - ok( $lostfine->amount == 6.12 , "Lost fine equals replacementcost when pref off and no default set"); - ok( $procfee->amount == 8.16, "Processing fee if processing fee"); + C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber3, 6.12, "Perdedor" ); + $lostfine = Koha::Account::Lines->find( + { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber3, debit_type_code => 'LOST' } ); + $procfee = Koha::Account::Lines->find( + { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber3, debit_type_code => 'PROCESSING' } + ); + ok( $lostfine->amount == 6.12, "Lost fine equals replacementcost when pref off and no default set" ); + ok( $procfee->amount == 8.16, "Processing fee if processing fee" ); is( $procfee->issue_id, $cli_issue_id_3, "Processing fee issue id is correct" ); $lostfine->delete(); $procfee->delete(); - C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber4, 0, "Perdedor"); - $lostfine = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'LOST' }); - $procfee = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'PROCESSING' }); - ok( !$lostfine, "No lost fine if no replacementcost but default set when pref off"); - ok( $procfee->amount == 2.04, "Processing fee if processing fee"); + C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber4, 0, "Perdedor" ); + $lostfine = Koha::Account::Lines->find( + { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'LOST' } ); + $procfee = Koha::Account::Lines->find( + { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'PROCESSING' } + ); + ok( !$lostfine, "No lost fine if no replacementcost but default set when pref off" ); + ok( $procfee->amount == 2.04, "Processing fee if processing fee" ); is( $procfee->issue_id, $cli_issue_id_4, "Processing fee issue id is correct" ); $procfee->delete(); - C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber4, 6.12, "Perdedor"); - $lostfine = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'LOST' }); - $procfee = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'PROCESSING' }); - ok( $lostfine->amount == 6.12 , "Lost fine equals replacementcost when pref off and default set"); - ok( $procfee->amount == 2.04, "Processing fee if processing fee"); + C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber4, 6.12, "Perdedor" ); + $lostfine = Koha::Account::Lines->find( + { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'LOST' } ); + $procfee = Koha::Account::Lines->find( + { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'PROCESSING' } + ); + ok( $lostfine->amount == 6.12, "Lost fine equals replacementcost when pref off and default set" ); + ok( $procfee->amount == 2.04, "Processing fee if processing fee" ); is( $procfee->issue_id, $cli_issue_id_4, "Processing fee issue id is correct" ); $lostfine->delete(); $procfee->delete(); - t::lib::Mocks::mock_preference('useDefaultReplacementCost', '1'); + t::lib::Mocks::mock_preference( 'useDefaultReplacementCost', '1' ); - C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber1, 0, "Perdedor"); - $lostfine = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber1, debit_type_code => 'LOST' }); - $procfee = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber1, debit_type_code => 'PROCESSING' }); - ok( !$lostfine, "No lost fine if no replacementcost or default when pref on"); - ok( !$procfee, "No processing fee if no processing fee"); - C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber1, 6.12, "Perdedor"); - $lostfine = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber1, debit_type_code => 'LOST' }); - $procfee = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber1, debit_type_code => 'PROCESSING' }); - is( $lostfine->amount, "6.120000", "Lost fine equals replacementcost when pref on and no default set"); - ok( !$procfee, "No processing fee if no processing fee"); + C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber1, 0, "Perdedor" ); + $lostfine = Koha::Account::Lines->find( + { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber1, debit_type_code => 'LOST' } ); + $procfee = Koha::Account::Lines->find( + { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber1, debit_type_code => 'PROCESSING' } + ); + ok( !$lostfine, "No lost fine if no replacementcost or default when pref on" ); + ok( !$procfee, "No processing fee if no processing fee" ); + C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber1, 6.12, "Perdedor" ); + $lostfine = Koha::Account::Lines->find( + { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber1, debit_type_code => 'LOST' } ); + $procfee = Koha::Account::Lines->find( + { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber1, debit_type_code => 'PROCESSING' } + ); + is( $lostfine->amount, "6.120000", "Lost fine equals replacementcost when pref on and no default set" ); + ok( !$procfee, "No processing fee if no processing fee" ); - C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber2, 0, "Perdedor"); - $lostfine = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber2, debit_type_code => 'LOST' }); - $procfee = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber2, debit_type_code => 'PROCESSING' }); - is( $lostfine->amount(), "16.320000", "Lost fine is default if no replacementcost but default set when pref on"); - ok( !$procfee, "No processing fee if no processing fee"); + C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber2, 0, "Perdedor" ); + $lostfine = Koha::Account::Lines->find( + { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber2, debit_type_code => 'LOST' } ); + $procfee = Koha::Account::Lines->find( + { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber2, debit_type_code => 'PROCESSING' } + ); + is( + $lostfine->amount(), "16.320000", + "Lost fine is default if no replacementcost but default set when pref on" + ); + ok( !$procfee, "No processing fee if no processing fee" ); $lostfine->delete(); - C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber2, 6.12, "Perdedor"); - $lostfine = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber2, debit_type_code => 'LOST' }); - $procfee = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber2, debit_type_code => 'PROCESSING' }); - is( $lostfine->amount, "6.120000" , "Lost fine equals replacementcost when pref on and default set"); - ok( !$procfee, "No processing fee if no processing fee"); + C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber2, 6.12, "Perdedor" ); + $lostfine = Koha::Account::Lines->find( + { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber2, debit_type_code => 'LOST' } ); + $procfee = Koha::Account::Lines->find( + { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber2, debit_type_code => 'PROCESSING' } + ); + is( $lostfine->amount, "6.120000", "Lost fine equals replacementcost when pref on and default set" ); + ok( !$procfee, "No processing fee if no processing fee" ); - C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber3, 0, "Perdedor"); - $lostfine = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber3, debit_type_code => 'LOST' }); - $procfee = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber3, debit_type_code => 'PROCESSING' }); - ok( !$lostfine, "No lost fine if no replacementcost and default not set when pref on"); - is( $procfee->amount, "8.160000", "Processing fee if processing fee"); + C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber3, 0, "Perdedor" ); + $lostfine = Koha::Account::Lines->find( + { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber3, debit_type_code => 'LOST' } ); + $procfee = Koha::Account::Lines->find( + { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber3, debit_type_code => 'PROCESSING' } + ); + ok( !$lostfine, "No lost fine if no replacementcost and default not set when pref on" ); + is( $procfee->amount, "8.160000", "Processing fee if processing fee" ); is( $procfee->issue_id, $cli_issue_id_3, "Processing fee issue id is correct" ); $procfee->delete(); - C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber3, 6.12, "Perdedor"); - $lostfine = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber3, debit_type_code => 'LOST' }); - $procfee = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber3, debit_type_code => 'PROCESSING' }); - is( $lostfine->amount, "6.120000", "Lost fine equals replacementcost when pref on and no default set"); - is( $procfee->amount, "8.160000", "Processing fee if processing fee"); + C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber3, 6.12, "Perdedor" ); + $lostfine = Koha::Account::Lines->find( + { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber3, debit_type_code => 'LOST' } ); + $procfee = Koha::Account::Lines->find( + { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber3, debit_type_code => 'PROCESSING' } + ); + is( $lostfine->amount, "6.120000", "Lost fine equals replacementcost when pref on and no default set" ); + is( $procfee->amount, "8.160000", "Processing fee if processing fee" ); is( $procfee->issue_id, $cli_issue_id_3, "Processing fee issue id is correct" ); - C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber4, 0, "Perdedor"); - $lostfine = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'LOST' }); - $procfee = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'PROCESSING' }); - is( $lostfine->amount, "4.080000", "Lost fine is default if no replacementcost but default set when pref on"); - is( $procfee->amount, "2.040000", "Processing fee if processing fee"); + C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber4, 0, "Perdedor" ); + $lostfine = Koha::Account::Lines->find( + { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'LOST' } ); + $procfee = Koha::Account::Lines->find( + { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'PROCESSING' } + ); + is( $lostfine->amount, "4.080000", "Lost fine is default if no replacementcost but default set when pref on" ); + is( $procfee->amount, "2.040000", "Processing fee if processing fee" ); is( $procfee->issue_id, $cli_issue_id_4, "Processing fee issue id is correct" ); $lostfine->delete(); $procfee->delete(); - C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber4, 6.12, "Perdedor"); - $lostfine = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'LOST' }); - $procfee = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'PROCESSING' }); - is( $lostfine->amount, "6.120000", "Lost fine equals replacementcost when pref on and default set"); - is( $procfee->amount, "2.040000", "Processing fee if processing fee"); + C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber4, 6.12, "Perdedor" ); + $lostfine = Koha::Account::Lines->find( + { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'LOST' } ); + $procfee = Koha::Account::Lines->find( + { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'PROCESSING' } + ); + is( $lostfine->amount, "6.120000", "Lost fine equals replacementcost when pref on and default set" ); + is( $procfee->amount, "2.040000", "Processing fee if processing fee" ); is( $procfee->issue_id, $cli_issue_id_4, "Processing fee issue id is correct" ); - C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber4, 6.12, "Perdedor"); - my $lostfines = Koha::Account::Lines->search({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'LOST' }); - my $procfees = Koha::Account::Lines->search({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'PROCESSING' }); - ok( $lostfines->count == 1 , "Lost fine cannot be double charged for the same issue_id"); - ok( $procfees->count == 1, "Processing fee cannot be double charged for the same issue_id"); - MarkIssueReturned($cli_borrowernumber, $cli_itemnumber4); - $cli_issue_id_4X = $builder->build({ source => 'Issue', value => { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4 } })->{issue_id}; - C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber4, 6.12, "Perdedor"); - $lostfines = Koha::Account::Lines->search({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'LOST' }); - $procfees = Koha::Account::Lines->search({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'PROCESSING' }); - ok( $lostfines->count == 2 , "Lost fine can be charged twice for the same item if they are distinct issue_id's"); - ok( $procfees->count == 2, "Processing fee can be charged twice for the same item if they are distinct issue_id's"); + C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber4, 6.12, "Perdedor" ); + my $lostfines = Koha::Account::Lines->search( + { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'LOST' } ); + my $procfees = Koha::Account::Lines->search( + { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'PROCESSING' } + ); + ok( $lostfines->count == 1, "Lost fine cannot be double charged for the same issue_id" ); + ok( $procfees->count == 1, "Processing fee cannot be double charged for the same issue_id" ); + MarkIssueReturned( $cli_borrowernumber, $cli_itemnumber4 ); + $cli_issue_id_4X = $builder->build( + { source => 'Issue', value => { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4 } } ) + ->{issue_id}; + C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber4, 6.12, "Perdedor" ); + $lostfines = Koha::Account::Lines->search( + { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'LOST' } ); + $procfees = Koha::Account::Lines->search( + { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'PROCESSING' } + ); + ok( + $lostfines->count == 2, + "Lost fine can be charged twice for the same item if they are distinct issue_id's" + ); + ok( + $procfees->count == 2, + "Processing fee can be charged twice for the same item if they are distinct issue_id's" + ); $lostfines->delete(); $procfees->delete(); - C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber5, 6.12, "Bundle"); - $lostfine = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber5, debit_type_code => 'LOST' }); - $procfee = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber5, debit_type_code => 'PROCESSING' }); - is( $lostfine->amount, "6.120000", "Lost fine equals replacementcost when pref on and default set (Bundle)"); - is( $procfee->amount, "2.040000", "Processing fee if processing fee (Bundle)"); - is( $lostfine->issue_id, $cli_bundle_issue, "Lost fine issue id matched to bundle issue"); - is( $procfee->issue_id, $cli_bundle_issue, "Processing fee issue id matched to bundle issue"); + C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber5, 6.12, "Bundle" ); + $lostfine = Koha::Account::Lines->find( + { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber5, debit_type_code => 'LOST' } ); + $procfee = Koha::Account::Lines->find( + { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber5, debit_type_code => 'PROCESSING' } + ); + is( $lostfine->amount, "6.120000", "Lost fine equals replacementcost when pref on and default set (Bundle)" ); + is( $procfee->amount, "2.040000", "Processing fee if processing fee (Bundle)" ); + is( $lostfine->issue_id, $cli_bundle_issue, "Lost fine issue id matched to bundle issue" ); + is( $procfee->issue_id, $cli_bundle_issue, "Processing fee issue id matched to bundle issue" ); $lostfine->delete(); $procfee->delete(); }; @@ -713,26 +881,32 @@ subtest "C4::Accounts::chargelostitem tests" => sub { subtest "basic fields tests" => sub { plan tests => 12; - t::lib::Mocks::mock_preference('ProcessingFeeNote', 'Test Note'); - C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber4, '1.99', "Perdedor"); + t::lib::Mocks::mock_preference( 'ProcessingFeeNote', 'Test Note' ); + C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber4, '1.99', "Perdedor" ); # Lost Item Fee - $lostfine = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'LOST' }); - ok($lostfine, "Lost fine created"); - is($lostfine->manager_id, $staff_id, "Lost fine manager_id set correctly"); - is($lostfine->issue_id, $cli_issue_id_4X, "Lost fine issue_id set correctly"); - is($lostfine->description, "Perdedor", "Lost fine issue_id set correctly"); - is($lostfine->note, '', "Lost fine does not contain a note"); - is($lostfine->branchcode, $branchcode, "Lost fine branchcode set correctly"); + $lostfine = Koha::Account::Lines->find( + { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'LOST' } ); + ok( $lostfine, "Lost fine created" ); + is( $lostfine->manager_id, $staff_id, "Lost fine manager_id set correctly" ); + is( $lostfine->issue_id, $cli_issue_id_4X, "Lost fine issue_id set correctly" ); + is( $lostfine->description, "Perdedor", "Lost fine issue_id set correctly" ); + is( $lostfine->note, '', "Lost fine does not contain a note" ); + is( $lostfine->branchcode, $branchcode, "Lost fine branchcode set correctly" ); # Processing Fee - $procfee = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'PROCESSING' }); - ok($procfee, "Processing fee created"); - is($procfee->manager_id, $staff_id, "Processing fee manager_id set correctly"); - is($procfee->issue_id, $cli_issue_id_4X, "Processing fee issue_id set correctly"); - is($procfee->description, "Perdedor", "Processing fee issue_id set correctly"); - is($procfee->note, C4::Context->preference("ProcessingFeeNote"), "Processing fee contains note matching ProcessingFeeNote"); - is($procfee->branchcode, $branchcode, "Processing fee branchcode set correctly"); + $procfee = Koha::Account::Lines->find( + { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'PROCESSING' } + ); + ok( $procfee, "Processing fee created" ); + is( $procfee->manager_id, $staff_id, "Processing fee manager_id set correctly" ); + is( $procfee->issue_id, $cli_issue_id_4X, "Processing fee issue_id set correctly" ); + is( $procfee->description, "Perdedor", "Processing fee issue_id set correctly" ); + is( + $procfee->note, C4::Context->preference("ProcessingFeeNote"), + "Processing fee contains note matching ProcessingFeeNote" + ); + is( $procfee->branchcode, $branchcode, "Processing fee branchcode set correctly" ); $lostfine->delete(); $procfee->delete(); }; @@ -743,17 +917,23 @@ subtest "C4::Accounts::chargelostitem tests" => sub { my $action_logs = $schema->resultset('ActionLog')->search()->count; t::lib::Mocks::mock_preference( 'FinesLog', 0 ); - C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber4, 0, "Perdedor"); - $lostfine = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'LOST' }); - $procfee = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'PROCESSING' }); + C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber4, 0, "Perdedor" ); + $lostfine = Koha::Account::Lines->find( + { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'LOST' } ); + $procfee = Koha::Account::Lines->find( + { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'PROCESSING' } + ); is( $schema->resultset('ActionLog')->count(), $action_logs + 0, 'No logs were added' ); $lostfine->delete(); $procfee->delete(); t::lib::Mocks::mock_preference( 'FinesLog', 1 ); - C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber4, 0, "Perdedor"); - $lostfine = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'LOST' }); - $procfee = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'PROCESSING' }); + C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber4, 0, "Perdedor" ); + $lostfine = Koha::Account::Lines->find( + { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'LOST' } ); + $procfee = Koha::Account::Lines->find( + { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'PROCESSING' } + ); is( $schema->resultset('ActionLog')->count(), $action_logs + 2, 'Logs were added' ); $lostfine->delete(); $procfee->delete(); @@ -766,13 +946,13 @@ subtest "C4::Accounts::chargelostitem tests" => sub { subtest "Koha::Account::non_issues_charges tests" => sub { plan tests => 6; - my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $account = $patron->account; my $res = 3; my $rent = 5; my $manual = 7; - my $print = 4; + my $print = 4; $account->add_debit( { description => 'a Res fee', @@ -813,15 +993,17 @@ subtest "Koha::Account::non_issues_charges tests" => sub { $res + $rent + $manual, 'Total charges should be Res + Rent + Manual' ); - is( $non_issues_charges, 15, - 'All types should count towards the non issue charge' ); + is( + $non_issues_charges, 15, + 'All types should count towards the non issue charge' + ); is( $other_charges, 0, 'There shouldn\'t be any non-included charges' ); Koha::Account::DebitTypes->find_or_create( { - code => 'Print', - description => 'Charge for using the printer', - is_system => 0, + code => 'Print', + description => 'Charge for using the printer', + is_system => 0, restricts_checkouts => 0 } )->store; @@ -842,8 +1024,10 @@ subtest "Koha::Account::non_issues_charges tests" => sub { $res + $rent + $manual + $print, 'Total charges should be Res + Rent + Manual + Print' ); - is( $new_non_issues_charges, 15, - 'All types except Print should count towards the non issue charge' ); + is( + $new_non_issues_charges, 15, + 'All types except Print should count towards the non issue charge' + ); is( $new_other_charges, 4, 'There should be non-included charges for Print' ); }; @@ -889,12 +1073,12 @@ subtest "Koha::Account::non_issues_charges tests" => sub { amount => 0 } )->store(); - purge_zero_balance_fees( 1 ); - my $debit_2 = Koha::Account::Lines->find( $debit->id ); + purge_zero_balance_fees(1); + my $debit_2 = Koha::Account::Lines->find( $debit->id ); my $credit_2 = Koha::Account::Lines->find( $credit->id ); - ok( $debit_2, 'Debit was correctly not deleted when credit has balance' ); + ok( $debit_2, 'Debit was correctly not deleted when credit has balance' ); ok( $credit_2, 'Credit was correctly not deleted when credit has balance' ); - is( Koha::Account::Lines->count({ borrowernumber => $patron->id }), 2, "The 2 account lines still exists" ); + is( Koha::Account::Lines->count( { borrowernumber => $patron->id } ), 2, "The 2 account lines still exists" ); $debit = Koha::Account::Line->new( { @@ -922,13 +1106,16 @@ subtest "Koha::Account::non_issues_charges tests" => sub { amount => 0 } )->store(); - purge_zero_balance_fees( 1 ); - $debit_2 = $credit_2 = undef; - $debit_2 = Koha::Account::Lines->find( $debit->id ); + purge_zero_balance_fees(1); + $debit_2 = $credit_2 = undef; + $debit_2 = Koha::Account::Lines->find( $debit->id ); $credit_2 = Koha::Account::Lines->find( $credit->id ); - ok( $debit_2, 'Debit was correctly not deleted when debit has balance' ); + ok( $debit_2, 'Debit was correctly not deleted when debit has balance' ); ok( $credit_2, 'Credit was correctly not deleted when debit has balance' ); - is( Koha::Account::Lines->count({ borrowernumber => $patron->id }), 2 + 2, "The 2 + 2 account lines still exists" ); + is( + Koha::Account::Lines->count( { borrowernumber => $patron->id } ), 2 + 2, + "The 2 + 2 account lines still exists" + ); $debit = Koha::Account::Line->new( { @@ -956,33 +1143,37 @@ subtest "Koha::Account::non_issues_charges tests" => sub { amount => 0 } )->store(); - purge_zero_balance_fees( 1 ); - $debit_2 = Koha::Account::Lines->find( $debit->id ); + purge_zero_balance_fees(1); + $debit_2 = Koha::Account::Lines->find( $debit->id ); $credit_2 = Koha::Account::Lines->find( $credit->id ); - ok( !$debit_2, 'Debit was correctly deleted' ); + ok( !$debit_2, 'Debit was correctly deleted' ); ok( !$credit_2, 'Credit was correctly deleted' ); - is( Koha::Account::Lines->count({ borrowernumber => $patron->id }), 2 + 2, "The 2 + 2 account lines still exists, the last 2 have been deleted ok" ); + is( + Koha::Account::Lines->count( { borrowernumber => $patron->id } ), 2 + 2, + "The 2 + 2 account lines still exists, the last 2 have been deleted ok" + ); }; - subtest "Koha::Account::Offset credit & debit tests" => sub { plan tests => 4; # Create a borrower - my $categorycode = $builder->build({ source => 'Category' })->{ categorycode }; - my $branchcode = $builder->build({ source => 'Branch' })->{ branchcode }; + my $categorycode = $builder->build( { source => 'Category' } )->{categorycode}; + my $branchcode = $builder->build( { source => 'Branch' } )->{branchcode}; - my $borrower = Koha::Patron->new( { - cardnumber => 'kyliehall', - surname => 'Hall', - firstname => 'Kylie', - } ); - $borrower->categorycode( $categorycode ); - $borrower->branchcode( $branchcode ); + my $borrower = Koha::Patron->new( + { + cardnumber => 'kyliehall', + surname => 'Hall', + firstname => 'Kylie', + } + ); + $borrower->categorycode($categorycode); + $borrower->branchcode($branchcode); $borrower->store; - my $account = Koha::Account->new({ patron_id => $borrower->id }); + my $account = Koha::Account->new( { patron_id => $borrower->id } ); my $line1 = Koha::Account::Line->new( { @@ -1005,15 +1196,15 @@ subtest "Koha::Account::Offset credit & debit tests" => sub { my $id = $account->pay( { - lines => [$line1, $line2], + lines => [ $line1, $line2 ], amount => 30, } )->{payment_id}; # Test debit and credit methods for Koha::Account::Offset my $account_offset = Koha::Account::Offsets->find( { credit_id => $id, debit_id => $line1->id } ); - is( $account_offset->debit->id, $line1->id, "Koha::Account::Offset->debit gets correct accountline" ); - is( $account_offset->credit->id, $id, "Koha::Account::Offset->credit gets correct accountline" ); + is( $account_offset->debit->id, $line1->id, "Koha::Account::Offset->debit gets correct accountline" ); + is( $account_offset->credit->id, $id, "Koha::Account::Offset->credit gets correct accountline" ); $account_offset = Koha::Account::Offset->new( { @@ -1024,7 +1215,7 @@ subtest "Koha::Account::Offset credit & debit tests" => sub { } )->store(); - is( $account_offset->debit, undef, "Koha::Account::Offset->debit returns undef if no associated debit" ); + is( $account_offset->debit, undef, "Koha::Account::Offset->debit returns undef if no associated debit" ); is( $account_offset->credit, undef, "Koha::Account::Offset->credit returns undef if no associated credit" ); }; @@ -1033,18 +1224,22 @@ subtest "Payment notice tests" => sub { plan tests => 8; Koha::Notice::Messages->delete(); - # Create a patron - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); - my $manager = $builder->build_object({ class => "Koha::Patrons" }); + # Create a patron + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + + my $manager = $builder->build_object( { class => "Koha::Patrons" } ); my $context = Test::MockModule->new('C4::Context'); - $context->mock( 'userenv', sub { - return { - number => $manager->borrowernumber, - branch => $manager->branchcode, - }; - }); - my $account = Koha::Account->new({ patron_id => $patron->borrowernumber }); + $context->mock( + 'userenv', + sub { + return { + number => $manager->borrowernumber, + branch => $manager->branchcode, + }; + } + ); + my $account = Koha::Account->new( { patron_id => $patron->borrowernumber } ); my $line = Koha::Account::Line->new( { @@ -1056,34 +1251,44 @@ subtest "Payment notice tests" => sub { )->store(); my $letter = Koha::Notice::Templates->find( { code => 'ACCOUNT_PAYMENT' } ); - $letter->content('[%- USE Price -%]A payment of [% credit.amount * -1 | $Price %] has been applied to your account. Your [% branch.branchcode %]'); + $letter->content( + '[%- USE Price -%]A payment of [% credit.amount * -1 | $Price %] has been applied to your account. Your [% branch.branchcode %]' + ); $letter->store(); - t::lib::Mocks::mock_preference('UseEmailReceipts', '0'); + t::lib::Mocks::mock_preference( 'UseEmailReceipts', '0' ); my $id = $account->pay( { amount => 1 } )->{payment_id}; is( Koha::Notice::Messages->search()->count(), 0, 'Notice for payment not sent if UseEmailReceipts is disabled' ); $id = $account->pay( { amount => 1, type => 'WRITEOFF' } )->{payment_id}; is( Koha::Notice::Messages->search()->count(), 0, 'Notice for writeoff not sent if UseEmailReceipts is disabled' ); - t::lib::Mocks::mock_preference('UseEmailReceipts', '1'); + t::lib::Mocks::mock_preference( 'UseEmailReceipts', '1' ); $id = $account->pay( { amount => 12, library_id => $branchcode } )->{payment_id}; my $notice = Koha::Notice::Messages->search()->next(); - is( $notice->subject, 'Account payment', 'Notice subject is correct for payment' ); + is( $notice->subject, 'Account payment', 'Notice subject is correct for payment' ); is( $notice->letter_code, 'ACCOUNT_PAYMENT', 'Notice letter code is correct for payment' ); - is( $notice->content, "A payment of 12.00 has been applied to your account. Your $branchcode", 'Notice content is correct for payment' ); + is( + $notice->content, "A payment of 12.00 has been applied to your account. Your $branchcode", + 'Notice content is correct for payment' + ); $notice->delete(); $letter = Koha::Notice::Templates->find( { code => 'ACCOUNT_WRITEOFF' } ); - $letter->content('[%- USE Price -%]A writeoff of [% credit.amount * -1 | $Price %] has been applied to your account. Your [% branch.branchcode %]'); + $letter->content( + '[%- USE Price -%]A writeoff of [% credit.amount * -1 | $Price %] has been applied to your account. Your [% branch.branchcode %]' + ); $letter->store(); - $id = $account->pay( { amount => 13, type => 'WRITEOFF', library_id => $branchcode } )->{payment_id}; + $id = $account->pay( { amount => 13, type => 'WRITEOFF', library_id => $branchcode } )->{payment_id}; $notice = Koha::Notice::Messages->search()->next(); - is( $notice->subject, 'Account writeoff', 'Notice subject is correct for payment' ); + is( $notice->subject, 'Account writeoff', 'Notice subject is correct for payment' ); is( $notice->letter_code, 'ACCOUNT_WRITEOFF', 'Notice letter code is correct for writeoff' ); - is( $notice->content, "A writeoff of 13.00 has been applied to your account. Your $branchcode", 'Notice content is correct for writeoff' ); + is( + $notice->content, "A writeoff of 13.00 has been applied to your account. Your $branchcode", + 'Notice content is correct for writeoff' + ); }; 1; diff --git a/t/db_dependent/Acquisition.t b/t/db_dependent/Acquisition.t index 931fc9a991..d8b8f9768c 100755 --- a/t/db_dependent/Acquisition.t +++ b/t/db_dependent/Acquisition.t @@ -28,9 +28,15 @@ use Koha::Acquisition::Basket; use MARC::File::XML ( BinaryEncoding => 'utf8', RecordFormat => 'MARC21' ); BEGIN { - use_ok('C4::Acquisition', qw( NewBasket GetBasket AddInvoice GetInvoice GetInvoices ModReceiveOrder SearchOrders GetOrder GetHistory ModOrder get_rounding_sql get_rounded_price ReopenBasket ModBasket ModBasketHeader ModBasketUsers )); - use_ok('C4::Biblio', qw( AddBiblio GetMarcSubfieldStructure )); - use_ok('C4::Budgets', qw( AddBudgetPeriod AddBudget GetBudget GetBudgetByOrderNumber GetBudgetsReport GetBudgets GetBudgetReport )); + use_ok( + 'C4::Acquisition', + qw( NewBasket GetBasket AddInvoice GetInvoice GetInvoices ModReceiveOrder SearchOrders GetOrder GetHistory ModOrder get_rounding_sql get_rounded_price ReopenBasket ModBasket ModBasketHeader ModBasketUsers ) + ); + use_ok( 'C4::Biblio', qw( AddBiblio GetMarcSubfieldStructure ) ); + use_ok( + 'C4::Budgets', + qw( AddBudgetPeriod AddBudget GetBudget GetBudgetByOrderNumber GetBudgetsReport GetBudgets GetBudgetReport ) + ); use_ok('Koha::Acquisition::Orders'); use_ok('Koha::Acquisition::Booksellers'); use_ok('t::lib::TestBuilder'); @@ -63,23 +69,21 @@ sub _check_fields_of_order { my $test_nbr_fields = scalar( keys %$order_to_check ); foreach my $field (@$exp_fields) { push @test_missing_fields, $field - unless exists( $order_to_check->{$field} ); + unless exists( $order_to_check->{$field} ); } foreach my $field ( keys %$order_to_check ) { push @test_extra_fields, $field - unless grep ( /^$field$/, @$exp_fields ); + unless grep ( /^$field$/, @$exp_fields ); } foreach my $field ( keys %{ $original_order_content->{str} } ) { push @test_different_fields, $field - unless ( !exists $order_to_check->{$field} ) - or ( $original_order_content->{str}->{$field} eq - $order_to_check->{$field} ); + unless ( !exists $order_to_check->{$field} ) + or ( $original_order_content->{str}->{$field} eq $order_to_check->{$field} ); } foreach my $field ( keys %{ $original_order_content->{num} } ) { push @test_different_fields, $field - unless ( !exists $order_to_check->{$field} ) - or ( $original_order_content->{num}->{$field} == - $order_to_check->{$field} ); + unless ( !exists $order_to_check->{$field} ) + or ( $original_order_content->{num}->{$field} == $order_to_check->{$field} ); } return ( \@test_missing_fields, \@test_extra_fields, @@ -98,14 +102,15 @@ sub _check_fields_of_orders { my @test_nbr_fields = (); foreach my $order_to_check (@$orders_to_check) { my $original_order_content = - ( grep { $_->{str}->{ordernumber} eq $order_to_check->{ordernumber} } - @$original_orders_content )[0]; + ( grep { $_->{str}->{ordernumber} eq $order_to_check->{ordernumber} } @$original_orders_content )[0]; my ( $t_missing_fields, $t_extra_fields, $t_different_fields, $t_nbr_fields - ) - = _check_fields_of_order( $exp_fields, $original_order_content, - $order_to_check ); + ) + = _check_fields_of_order( + $exp_fields, $original_order_content, + $order_to_check + ); push @test_missing_fields, @$t_missing_fields; push @test_extra_fields, @$t_extra_fields; push @test_different_fields, @$t_different_fields; @@ -114,14 +119,13 @@ sub _check_fields_of_orders { @test_missing_fields = keys %{ { map { $_ => 1 } @test_missing_fields } }; @test_extra_fields = keys %{ { map { $_ => 1 } @test_extra_fields } }; @test_different_fields = - keys %{ { map { $_ => 1 } @test_different_fields } }; + keys %{ { map { $_ => 1 } @test_different_fields } }; return ( \@test_missing_fields, \@test_extra_fields, \@test_different_fields, \@test_nbr_fields ); } - my $schema = Koha::Database->new()->schema(); $schema->storage->txn_begin(); @@ -139,9 +143,11 @@ my $bookseller = Koha::Acquisition::Bookseller->new( )->store; my $booksellerid = $bookseller->id; -my $booksellerinfo = Koha::Acquisition::Booksellers->find( $booksellerid ); -is( $booksellerinfo->deliverytime, - 5, 'set deliverytime when creating vendor (Bug 10556)' ); +my $booksellerinfo = Koha::Acquisition::Booksellers->find($booksellerid); +is( + $booksellerinfo->deliverytime, + 5, 'set deliverytime when creating vendor (Bug 10556)' +); my ( $basket, $basketno ); ok( @@ -150,17 +156,18 @@ ok( ); ok( $basket = GetBasket($basketno), "GetBasket($basketno) returns $basket" ); -my $bpid=AddBudgetPeriod({ - budget_period_startdate => '2008-01-01' - , budget_period_enddate => '2008-12-31' - , budget_period_active => 1 - , budget_period_description => "MAPERI" -}); +my $bpid = AddBudgetPeriod( + { + budget_period_startdate => '2008-01-01', budget_period_enddate => '2008-12-31' + , budget_period_active => 1 + , budget_period_description => "MAPERI" + } +); my $budgetid = C4::Budgets::AddBudget( { - budget_code => "budget_code_test_1", - budget_name => "budget_name_test_1", + budget_code => "budget_code_test_1", + budget_name => "budget_name_test_1", budget_period_id => $bpid, } ); @@ -173,21 +180,19 @@ my ( $biblionumber3, $biblioitemnumber3 ) = AddBiblio( MARC::Record->new, '' ); my ( $biblionumber4, $biblioitemnumber4 ) = AddBiblio( MARC::Record->new, '' ); my ( $biblionumber5, $biblioitemnumber5 ) = AddBiblio( MARC::Record->new, '' ); - - # Prepare 6 orders, and make distinction beween fields to be tested with eq and with == # Ex : a price of 50.1 will be stored internally as 5.100000 my @order_content = ( { str => { - basketno => $basketno, - biblionumber => $biblionumber1, - budget_id => $budget->{budget_id}, - uncertainprice => 0, + basketno => $basketno, + biblionumber => $biblionumber1, + budget_id => $budget->{budget_id}, + uncertainprice => 0, order_internalnote => "internal note foo", order_vendornote => "vendor note bar", - ordernumber => '', + ordernumber => '', }, num => { quantity => 24, @@ -207,10 +212,10 @@ my @order_content = ( }, { str => { - basketno => $basketno, - biblionumber => $biblionumber2, - budget_id => $budget->{budget_id}, - uncertainprice => 0, + basketno => $basketno, + biblionumber => $biblionumber2, + budget_id => $budget->{budget_id}, + uncertainprice => 0, order_internalnote => "internal note foo", order_vendornote => "vendor note bar" }, @@ -226,9 +231,9 @@ my @order_content = ( }, { str => { - basketno => $basketno, - biblionumber => $biblionumber3, - budget_id => $budget->{budget_id}, + basketno => $basketno, + biblionumber => $biblionumber3, + budget_id => $budget->{budget_id}, order_internalnote => "internal note", order_vendornote => "vendor note" }, @@ -245,9 +250,9 @@ my @order_content = ( }, { str => { - basketno => $basketno, - biblionumber => $biblionumber4, - budget_id => $budget->{budget_id}, + basketno => $basketno, + biblionumber => $biblionumber4, + budget_id => $budget->{budget_id}, order_internalnote => "internal note bar", order_vendornote => "vendor note foo" }, @@ -264,9 +269,9 @@ my @order_content = ( }, { str => { - basketno => $basketno, - biblionumber => $biblionumber5, - budget_id => $budget->{budget_id}, + basketno => $basketno, + biblionumber => $biblionumber5, + budget_id => $budget->{budget_id}, order_internalnote => "internal note", order_vendornote => "vendor note" }, @@ -287,14 +292,14 @@ my @order_content = ( for ( 0 .. 5 ) { my %ocontent; @ocontent{ keys %{ $order_content[$_]->{num} } } = - values %{ $order_content[$_]->{num} }; + values %{ $order_content[$_]->{num} }; @ocontent{ keys %{ $order_content[$_]->{str} } } = - values %{ $order_content[$_]->{str} }; + values %{ $order_content[$_]->{str} }; $ordernumbers[$_] = Koha::Acquisition::Order->new( \%ocontent )->store->ordernumber; $order_content[$_]->{str}->{ordernumber} = $ordernumbers[$_]; } -Koha::Acquisition::Orders->find($ordernumbers[3])->cancel; +Koha::Acquisition::Orders->find( $ordernumbers[3] )->cancel; my $invoiceid = AddInvoice( invoicenumber => 'invoice', @@ -302,23 +307,23 @@ my $invoiceid = AddInvoice( unknown => "unknown" ); -my $invoice = GetInvoice( $invoiceid ); +my $invoice = GetInvoice($invoiceid); my $reception_date = output_pref( { - dt => dt_from_string->add( days => 1 ), - dateformat => 'iso', - dateonly => 1, + dt => dt_from_string->add( days => 1 ), + dateformat => 'iso', + dateonly => 1, } ); -my ($datereceived, $new_ordernumber) = ModReceiveOrder( +my ( $datereceived, $new_ordernumber ) = ModReceiveOrder( { - biblionumber => $biblionumber4, - order => Koha::Acquisition::Orders->find( $ordernumbers[4] )->unblessed, - quantityreceived => 1, - invoice => $invoice, - budget_id => $order_content[4]->{str}->{budget_id}, - datereceived => $reception_date, + biblionumber => $biblionumber4, + order => Koha::Acquisition::Orders->find( $ordernumbers[4] )->unblessed, + quantityreceived => 1, + invoice => $invoice, + budget_id => $order_content[4]->{str}->{budget_id}, + datereceived => $reception_date, } ); @@ -334,84 +339,103 @@ is( 'ModReceiveOrder sets the passed date' ); -my $search_orders = SearchOrders({ - booksellerid => $booksellerid, - basketno => $basketno -}); +my $search_orders = SearchOrders( + { + booksellerid => $booksellerid, + basketno => $basketno + } +); isa_ok( $search_orders, 'ARRAY' ); ok( - ( - ( scalar @$search_orders == 5 ) - and !grep ( $_->{ordernumber} eq $ordernumbers[3], @$search_orders ) - ), + ( ( scalar @$search_orders == 5 ) and !grep ( $_->{ordernumber} eq $ordernumbers[3], @$search_orders ) ), "SearchOrders only gets non-cancelled orders" ); -$search_orders = SearchOrders({ - booksellerid => $booksellerid, - basketno => $basketno, - pending => 1 -}); +$search_orders = SearchOrders( + { + booksellerid => $booksellerid, + basketno => $basketno, + pending => 1 + } +); ok( ( ( scalar @$search_orders == 4 ) and !grep ( ( - ( $_->{ordernumber} eq $ordernumbers[3] ) - or ( $_->{ordernumber} eq $ordernumbers[4] ) + ( $_->{ordernumber} eq $ordernumbers[3] ) + or ( $_->{ordernumber} eq $ordernumbers[4] ) ), @$search_orders ) ), "SearchOrders with pending params gets only pending orders (bug 10723)" ); -$search_orders = SearchOrders({ - booksellerid => $booksellerid, - basketno => $basketno, - pending => 1, - ordered => 1, -}); -is( scalar (@$search_orders), 0, "SearchOrders with pending and ordered params gets only pending ordered orders (bug 11170)" ); +$search_orders = SearchOrders( + { + booksellerid => $booksellerid, + basketno => $basketno, + pending => 1, + ordered => 1, + } +); +is( + scalar(@$search_orders), 0, + "SearchOrders with pending and ordered params gets only pending ordered orders (bug 11170)" +); -$search_orders = SearchOrders({ - ordernumber => $ordernumbers[4] -}); -is( scalar (@$search_orders), 1, "SearchOrders takes into account the ordernumber filter" ); +$search_orders = SearchOrders( { ordernumber => $ordernumbers[4] } ); +is( scalar(@$search_orders), 1, "SearchOrders takes into account the ordernumber filter" ); -$search_orders = SearchOrders({ - biblionumber => $biblionumber4 -}); -is( scalar (@$search_orders), 1, "SearchOrders takes into account the biblionumber filter" ); +$search_orders = SearchOrders( { biblionumber => $biblionumber4 } ); +is( scalar(@$search_orders), 1, "SearchOrders takes into account the biblionumber filter" ); -$search_orders = SearchOrders({ - biblionumber => $biblionumber4, - pending => 1 -}); -is( scalar (@$search_orders), 0, "SearchOrders takes into account the biblionumber and pending filters" ); +$search_orders = SearchOrders( + { + biblionumber => $biblionumber4, + pending => 1 + } +); +is( scalar(@$search_orders), 0, "SearchOrders takes into account the biblionumber and pending filters" ); # # Test GetBudgetByOrderNumber # -ok( GetBudgetByOrderNumber( $ordernumbers[0] )->{'budget_id'} eq $budgetid, - "GetBudgetByOrderNumber returns expected budget" ); +ok( + GetBudgetByOrderNumber( $ordernumbers[0] )->{'budget_id'} eq $budgetid, + "GetBudgetByOrderNumber returns expected budget" +); -my $lateorders = Koha::Acquisition::Orders->filter_by_lates({ delay => 0 }); -is( $lateorders->search({ 'me.basketno' => $basketno })->count, - 0, "GetLateOrders does not get orders from opened baskets" ); +my $lateorders = Koha::Acquisition::Orders->filter_by_lates( { delay => 0 } ); +is( + $lateorders->search( { 'me.basketno' => $basketno } )->count, + 0, "GetLateOrders does not get orders from opened baskets" +); Koha::Acquisition::Baskets->find($basketno)->close; -$lateorders = Koha::Acquisition::Orders->filter_by_lates({ delay => 0 }); -isnt( $lateorders->search({ 'me.basketno' => $basketno })->count, - 0, "GetLateOrders gets orders from closed baskets" ); -is( $lateorders->search({ ordernumber => $ordernumbers[3] })->count, 0, - "GetLateOrders does not get cancelled orders" ); -is( $lateorders->search({ ordernumber => $ordernumbers[4] })->count, 0, - "GetLateOrders does not get received orders" ); +$lateorders = Koha::Acquisition::Orders->filter_by_lates( { delay => 0 } ); +isnt( + $lateorders->search( { 'me.basketno' => $basketno } )->count, + 0, "GetLateOrders gets orders from closed baskets" +); +is( + $lateorders->search( { ordernumber => $ordernumbers[3] } )->count, 0, + "GetLateOrders does not get cancelled orders" +); +is( + $lateorders->search( { ordernumber => $ordernumbers[4] } )->count, 0, + "GetLateOrders does not get received orders" +); -$search_orders = SearchOrders({ - booksellerid => $booksellerid, - basketno => $basketno, - pending => 1, - ordered => 1, -}); -is( scalar (@$search_orders), 4, "SearchOrders with pending and ordered params gets only pending ordered orders. After closing the basket, orders are marked as 'ordered' (bug 11170)" ); +$search_orders = SearchOrders( + { + booksellerid => $booksellerid, + basketno => $basketno, + pending => 1, + ordered => 1, + } +); +is( + scalar(@$search_orders), 4, + "SearchOrders with pending and ordered params gets only pending ordered orders. After closing the basket, orders are marked as 'ordered' (bug 11170)" +); # # Test AddClaim @@ -420,7 +444,7 @@ is( scalar (@$search_orders), 4, "SearchOrders with pending and ordered params g my $order = $lateorders->next; $order->claim(); is( - output_pref({ str => $order->claimed_date, dateformat => 'iso', dateonly => 1 }), + output_pref( { str => $order->claimed_date, dateformat => 'iso', dateonly => 1 } ), strftime( "%Y-%m-%d", localtime(time) ), "Koha::Acquisition::Order->claim: Check claimed_date" ); @@ -436,13 +460,19 @@ $order2->{order_internalnote} = "my notes"; } ); $order2 = GetOrder( $ordernumbers[1] ); -is( $order2->{'quantityreceived'}, - 0, 'Splitting up order did not receive any on original order' ); +is( + $order2->{'quantityreceived'}, + 0, 'Splitting up order did not receive any on original order' +); is( $order2->{'quantity'}, 40, '40 items on original order' ); -is( $order2->{'budget_id'}, $budgetid, - 'Budget on original order is unchanged' ); -is( $order2->{order_internalnote}, "my notes", - 'ModReceiveOrder and GetOrder deal with internal notes' ); +is( + $order2->{'budget_id'}, $budgetid, + 'Budget on original order is unchanged' +); +is( + $order2->{order_internalnote}, "my notes", + 'ModReceiveOrder and GetOrder deal with internal notes' +); my $order1 = GetOrder( $ordernumbers[0] ); is( $order1->{order_internalnote}, @@ -452,30 +482,35 @@ is( my $neworder = GetOrder($new_ordernumber); is( $neworder->{'quantity'}, 2, '2 items on new order' ); -is( $neworder->{'quantityreceived'}, - 2, 'Splitting up order received items on new order' ); +is( + $neworder->{'quantityreceived'}, + 2, 'Splitting up order received items on new order' +); is( $neworder->{'budget_id'}, $budgetid, 'Budget on new order is unchanged' ); -is( $neworder->{ordernumber}, $new_ordernumber, 'Split: test ordernumber' ); +is( $neworder->{ordernumber}, $new_ordernumber, 'Split: test ordernumber' ); is( $neworder->{parent_ordernumber}, $ordernumbers[1], 'Split: test parent_ordernumber' ); my $orders = GetHistory( ordernumber => $ordernumbers[1] ); -is( scalar( @$orders ), 1, 'GetHistory with a given ordernumber returns 1 order' ); +is( scalar(@$orders), 1, 'GetHistory with a given ordernumber returns 1 order' ); $orders = GetHistory( ordernumber => $ordernumbers[1], search_children_too => 1 ); -is( scalar( @$orders ), 2, 'GetHistory with a given ordernumber and search_children_too set returns 2 orders' ); -$orders = GetHistory( ordernumbers => [$ordernumbers[1]] ); -is( scalar( @$orders ), 1, 'GetHistory with a given ordernumbers returns 1 order' ); +is( scalar(@$orders), 2, 'GetHistory with a given ordernumber and search_children_too set returns 2 orders' ); +$orders = GetHistory( ordernumbers => [ $ordernumbers[1] ] ); +is( scalar(@$orders), 1, 'GetHistory with a given ordernumbers returns 1 order' ); $orders = GetHistory( ordernumbers => \@ordernumbers ); -is( scalar( @$orders ), scalar( @ordernumbers ) - 1, 'GetHistory with a list of ordernumbers returns N-1 orders (was has been deleted [3])' ); +is( + scalar(@$orders), scalar(@ordernumbers) - 1, + 'GetHistory with a list of ordernumbers returns N-1 orders (was has been deleted [3])' +); $orders = GetHistory( internalnote => 'internal note foo' ); -is( scalar( @$orders ), 2, 'GetHistory returns correctly a search for internalnote' ); +is( scalar(@$orders), 2, 'GetHistory returns correctly a search for internalnote' ); $orders = GetHistory( vendornote => 'vendor note bar' ); -is( scalar( @$orders ), 2, 'GetHistory returns correctly a search for vendornote' ); +is( scalar(@$orders), 2, 'GetHistory returns correctly a search for vendornote' ); $orders = GetHistory( internalnote => 'internal note bar' ); -is( scalar( @$orders ), 1, 'GetHistory returns correctly a search for internalnote' ); +is( scalar(@$orders), 1, 'GetHistory returns correctly a search for internalnote' ); $orders = GetHistory( vendornote => 'vendor note foo' ); -is( scalar( @$orders ), 1, 'GetHistory returns correctly a search for vendornote' ); +is( scalar(@$orders), 1, 'GetHistory returns correctly a search for vendornote' ); my $budget2 = $builder->build_object( { @@ -501,18 +536,26 @@ $order3->{order_internalnote} = "my other notes"; ); $order3 = GetOrder( $ordernumbers[2] ); -is( $order3->{'quantityreceived'}, - 0, 'Splitting up order did not receive any on original order' ); +is( + $order3->{'quantityreceived'}, + 0, 'Splitting up order did not receive any on original order' +); is( $order3->{'quantity'}, 2, '2 items on original order' ); -is( $order3->{'budget_id'}, $budgetid, - 'Budget on original order is unchanged' ); -is( $order3->{order_internalnote}, "my other notes", - 'ModReceiveOrder and GetOrder deal with notes' ); +is( + $order3->{'budget_id'}, $budgetid, + 'Budget on original order is unchanged' +); +is( + $order3->{order_internalnote}, "my other notes", + 'ModReceiveOrder and GetOrder deal with notes' +); $neworder = GetOrder($new_ordernumber); is( $neworder->{'quantity'}, 2, '2 items on new order' ); -is( $neworder->{'quantityreceived'}, - 2, 'Splitting up order received items on new order' ); +is( + $neworder->{'quantityreceived'}, + 2, 'Splitting up order received items on new order' +); is( $neworder->{'budget_id'}, $budgetid2, 'Budget on new order is changed' ); $order3 = Koha::Acquisition::Orders->find( $ordernumbers[2] )->unblessed; @@ -528,32 +571,35 @@ $order3->{order_internalnote} = "my third notes"; ); $order3 = GetOrder( $ordernumbers[2] ); -is( $order3->{'quantityreceived'}, 2, 'Order not split up' ); -is( $order3->{'quantity'}, 2, '2 items on order' ); -is( $order3->{'budget_id'}, $budgetid2, 'Budget has changed' ); +is( $order3->{'quantityreceived'}, 2, 'Order not split up' ); +is( $order3->{'quantity'}, 2, '2 items on order' ); +is( $order3->{'budget_id'}, $budgetid2, 'Budget has changed' ); is( $order3->{order_internalnote}, "my third notes", 'ModReceiveOrder and GetOrder deal with notes' ); my $nonexistent_order = GetOrder(); is( $nonexistent_order, undef, 'GetOrder returns undef if no ordernumber is given' ); -$nonexistent_order = GetOrder( 424242424242 ); +$nonexistent_order = GetOrder(424242424242); is( $nonexistent_order, undef, 'GetOrder returns undef if a nonexistent ordernumber is given' ); subtest 'ModOrder' => sub { plan tests => 1; ModOrder( { ordernumber => $order1->{ordernumber}, unitprice => 42 } ); my $order = GetOrder( $order1->{ordernumber} ); - is( int($order->{unitprice}), 42, 'ModOrder should work even if biblionumber if not passed'); + is( int( $order->{unitprice} ), 42, 'ModOrder should work even if biblionumber if not passed' ); }; # Budget reports my $all_count = scalar GetBudgetsReport(); -ok($all_count >= 1, "GetBudgetReport OK"); +ok( $all_count >= 1, "GetBudgetReport OK" ); my $active_count = scalar GetBudgetsReport(1); -ok($active_count >= 1 , "GetBudgetsReport(1) OK"); +ok( $active_count >= 1, "GetBudgetsReport(1) OK" ); -is($all_count, scalar GetBudgetsReport(), "GetBudgetReport returns inactive budget period acquisitions."); -ok($active_count >= scalar GetBudgetsReport(1), "GetBudgetReport doesn't return inactive budget period acquisitions."); +is( $all_count, scalar GetBudgetsReport(), "GetBudgetReport returns inactive budget period acquisitions." ); +ok( + $active_count >= scalar GetBudgetsReport(1), + "GetBudgetReport doesn't return inactive budget period acquisitions." +); # "Flavoured" tests (tests that required a run for each marc flavour) # Tests should be added to the run_flavoured_tests sub below @@ -563,27 +609,28 @@ $biblio_module->mock( sub { my ($self) = shift; - my ( $title_field, $title_subfield ) = get_title_field(); - my ( $isbn_field, $isbn_subfield ) = get_isbn_field(); - my ( $issn_field, $issn_subfield ) = get_issn_field(); - my ( $biblionumber_field, $biblionumber_subfield ) = ( '999', 'c' ); + my ( $title_field, $title_subfield ) = get_title_field(); + my ( $isbn_field, $isbn_subfield ) = get_isbn_field(); + my ( $issn_field, $issn_subfield ) = get_issn_field(); + my ( $biblionumber_field, $biblionumber_subfield ) = ( '999', 'c' ); my ( $biblioitemnumber_field, $biblioitemnumber_subfield ) = ( '999', '9' ); - my ( $itemnumber_field, $itemnumber_subfield ) = get_itemnumber_field(); + my ( $itemnumber_field, $itemnumber_subfield ) = get_itemnumber_field(); return { - 'biblio.title' => [ { tagfield => $title_field, tagsubfield => $title_subfield } ], - 'biblio.biblionumber' => [ { tagfield => $biblionumber_field, tagsubfield => $biblionumber_subfield } ], - 'biblioitems.isbn' => [ { tagfield => $isbn_field, tagsubfield => $isbn_subfield } ], - 'biblioitems.issn' => [ { tagfield => $issn_field, tagsubfield => $issn_subfield } ], - 'biblioitems.biblioitemnumber' => [ { tagfield => $biblioitemnumber_field, tagsubfield => $biblioitemnumber_subfield } ], - 'items.itemnumber' => [ { tagfield => $itemnumber_subfield, tagsubfield => $itemnumber_subfield } ], + 'biblio.title' => [ { tagfield => $title_field, tagsubfield => $title_subfield } ], + 'biblio.biblionumber' => [ { tagfield => $biblionumber_field, tagsubfield => $biblionumber_subfield } ], + 'biblioitems.isbn' => [ { tagfield => $isbn_field, tagsubfield => $isbn_subfield } ], + 'biblioitems.issn' => [ { tagfield => $issn_field, tagsubfield => $issn_subfield } ], + 'biblioitems.biblioitemnumber' => + [ { tagfield => $biblioitemnumber_field, tagsubfield => $biblioitemnumber_subfield } ], + 'items.itemnumber' => [ { tagfield => $itemnumber_subfield, tagsubfield => $itemnumber_subfield } ], }; - } + } ); sub run_flavoured_tests { my $marcflavour = shift; - t::lib::Mocks::mock_preference('marcflavour', $marcflavour); + t::lib::Mocks::mock_preference( 'marcflavour', $marcflavour ); # # Test SearchWithISBNVariations syspref @@ -593,27 +640,29 @@ sub run_flavoured_tests { my ( $biblionumber6, $biblioitemnumber6 ) = AddBiblio( $marc_record, '' ); # Create order - my $ordernumber = Koha::Acquisition::Order->new( { - basketno => $basketno, - biblionumber => $biblionumber6, - budget_id => $budget->{budget_id}, + my $ordernumber = Koha::Acquisition::Order->new( + { + basketno => $basketno, + biblionumber => $biblionumber6, + budget_id => $budget->{budget_id}, order_internalnote => "internal note", order_vendornote => "vendor note", - quantity => 1, - ecost => 10, - rrp => 10, - listprice => 10, - ecost => 10, - rrp => 10, - discount => 0, - uncertainprice => 0, - } )->store->ordernumber; + quantity => 1, + ecost => 10, + rrp => 10, + listprice => 10, + ecost => 10, + rrp => 10, + discount => 0, + uncertainprice => 0, + } + )->store->ordernumber; - t::lib::Mocks::mock_preference('SearchWithISBNVariations', 0); + t::lib::Mocks::mock_preference( 'SearchWithISBNVariations', 0 ); $orders = GetHistory( isbn => '0136019706' ); is( scalar(@$orders), 0, "GetHistory searches correctly by ISBN" ); - t::lib::Mocks::mock_preference('SearchWithISBNVariations', 1); + t::lib::Mocks::mock_preference( 'SearchWithISBNVariations', 1 ); $orders = GetHistory( isbn => '0136019706' ); is( scalar(@$orders), 1, "GetHistory searches correctly by ISBN" ); @@ -627,27 +676,29 @@ sub run_flavoured_tests { is( scalar(@$orders_issn), 0, "Precheck that ISSN shouldn't be in database" ); # Create order - my $ordernumber_issn = Koha::Acquisition::Order->new( { - basketno => $basketno, - biblionumber => $biblionumber6_issn, - budget_id => $budget->{budget_id}, + my $ordernumber_issn = Koha::Acquisition::Order->new( + { + basketno => $basketno, + biblionumber => $biblionumber6_issn, + budget_id => $budget->{budget_id}, order_internalnote => "internal note", order_vendornote => "vendor note", - quantity => 1, - ecost => 10, - rrp => 10, - listprice => 10, - ecost => 10, - rrp => 10, - discount => 0, - uncertainprice => 0, - } )->store->ordernumber; + quantity => 1, + ecost => 10, + rrp => 10, + listprice => 10, + ecost => 10, + rrp => 10, + discount => 0, + uncertainprice => 0, + } + )->store->ordernumber; - t::lib::Mocks::mock_preference('SearchWithISSNVariations', 0); + t::lib::Mocks::mock_preference( 'SearchWithISSNVariations', 0 ); $orders_issn = GetHistory( issn => '2434-561X' ); is( scalar(@$orders_issn), 0, "GetHistory searches correctly by ISSN" ); - t::lib::Mocks::mock_preference('SearchWithISSNVariations', 1); + t::lib::Mocks::mock_preference( 'SearchWithISSNVariations', 1 ); $orders_issn = GetHistory( issn => '2434-561X' ); is( scalar(@$orders_issn), 1, "GetHistory searches correctly by ISSN" ); @@ -713,64 +764,82 @@ sub create_issn_field { subtest 'ModReceiveOrder replacementprice tests' => sub { plan tests => 2; + #Let's build an order, we need a couple things though - my $order_biblio = $builder->build_sample_biblio; - my $order_basket = $builder->build({ source => 'Aqbasket', value => { is_standing => 0 } }); - my $order_invoice = $builder->build({ source => 'Aqinvoice'}); - my $order_currency = $builder->build({ source => 'Currency', value => { active => 1, archived => 0, symbol => 'F', rate => 2, isocode => undef, currency => 'FOO' } }); - my $order_vendor = $builder->build({ source => 'Aqbookseller',value => { listincgst => 0, listprice => $order_currency->{currency}, invoiceprice => $order_currency->{currency} } }); - my $orderinfo ={ - basketno => $order_basket->{basketno}, - rrp => 19.99, - replacementprice => undef, - quantity => 1, - quantityreceived => 0, - datereceived => undef, + my $order_biblio = $builder->build_sample_biblio; + my $order_basket = $builder->build( { source => 'Aqbasket', value => { is_standing => 0 } } ); + my $order_invoice = $builder->build( { source => 'Aqinvoice' } ); + my $order_currency = $builder->build( + { + source => 'Currency', + value => { active => 1, archived => 0, symbol => 'F', rate => 2, isocode => undef, currency => 'FOO' } + } + ); + my $order_vendor = $builder->build( + { + source => 'Aqbookseller', + value => { + listincgst => 0, listprice => $order_currency->{currency}, invoiceprice => $order_currency->{currency} + } + } + ); + my $orderinfo = { + basketno => $order_basket->{basketno}, + rrp => 19.99, + replacementprice => undef, + quantity => 1, + quantityreceived => 0, + datereceived => undef, datecancellationprinted => undef, }; - my $receive_order = $builder->build({ source => 'Aqorder', value => $orderinfo }); - (undef, my $received_ordernumber) = ModReceiveOrder({ - biblionumber => $order_biblio->biblionumber, - order => $receive_order, - invoice => $order_invoice, + my $receive_order = $builder->build( { source => 'Aqorder', value => $orderinfo } ); + ( undef, my $received_ordernumber ) = ModReceiveOrder( + { + biblionumber => $order_biblio->biblionumber, + order => $receive_order, + invoice => $order_invoice, quantityreceived => $receive_order->{quantity}, - budget_id => $order->{budget_id}, - }); + budget_id => $order->{budget_id}, + } + ); my $received_order = GetOrder($received_ordernumber); - is ($received_order->{replacementprice},undef,"No price set if none passed in"); + is( $received_order->{replacementprice}, undef, "No price set if none passed in" ); $orderinfo->{replacementprice} = 16.12; - $receive_order = $builder->build({ source => 'Aqorder', value => $orderinfo }); - (undef, $received_ordernumber) = ModReceiveOrder({ - biblionumber => $order_biblio->biblionumber, - order => $receive_order, - invoice => $order_invoice, + $receive_order = $builder->build( { source => 'Aqorder', value => $orderinfo } ); + ( undef, $received_ordernumber ) = ModReceiveOrder( + { + biblionumber => $order_biblio->biblionumber, + order => $receive_order, + invoice => $order_invoice, quantityreceived => $receive_order->{quantity}, - budget_id => $order->{budget_id}, - }); + budget_id => $order->{budget_id}, + } + ); $received_order = GetOrder($received_ordernumber); - is ($received_order->{replacementprice},'16.120000',"Replacement price set if none passed in"); + is( $received_order->{replacementprice}, '16.120000', "Replacement price set if none passed in" ); }; subtest 'ModReceiveOrder and subscription' => sub { plan tests => 2; - my $first_note = 'first note'; - my $second_note = 'second note'; + my $first_note = 'first note'; + my $second_note = 'second note'; my $subscription = $builder->build_object( { class => 'Koha::Subscriptions' } ); - my $order = $builder->build_object( + my $order = $builder->build_object( { class => 'Koha::Acquisition::Orders', value => { - subscriptionid => $subscription->subscriptionid, - order_internalnote => $first_note, - quantity => 5, - quantityreceived => 0, - ecost_tax_excluded => 42, + subscriptionid => $subscription->subscriptionid, + order_internalnote => $first_note, + quantity => 5, + quantityreceived => 0, + ecost_tax_excluded => 42, unitprice_tax_excluded => 42, } } ); my $order_info = $order->unblessed; + # We do not want the note from the original note to be modified # Keeping it will permit to display it for future receptions $order_info->{order_internalnote} = $second_note; @@ -784,8 +853,10 @@ subtest 'ModReceiveOrder and subscription' => sub { } ); my $received_order = Koha::Acquisition::Orders->find($received_ordernumber); - is( $received_order->order_internalnote, - $second_note, "No price set if none passed in" ); + is( + $received_order->order_internalnote, + $second_note, "No price set if none passed in" + ); is( $order->get_from_storage->order_internalnote, $first_note ); }; @@ -819,22 +890,29 @@ subtest 'ModReceiveOrder invoice_unitprice and invoice_currency' => sub { { biblionumber => $order->biblionumber, order => $order_info, - quantityreceived => 1, # We receive only 1 + quantityreceived => 1, # We receive only 1 budget_id => $order->budget_id, } ); my $active_currency = Koha::Acquisition::Currencies->get_active; - my $received_order = - Koha::Acquisition::Orders->find($received_ordernumber); - is( $received_order->invoice_unitprice, - $order->unitprice, 'no price should be stored if none passed' ); - is( $received_order->invoice_currency, - $active_currency->currency, 'no currency should be stored if none passed' ); + my $received_order = Koha::Acquisition::Orders->find($received_ordernumber); + is( + $received_order->invoice_unitprice, + $order->unitprice, 'no price should be stored if none passed' + ); + is( + $received_order->invoice_currency, + $active_currency->currency, 'no currency should be stored if none passed' + ); $order = $order->get_from_storage; - is( $order->invoice_unitprice, $order->unitprice, - 'no price should be stored if none passed' ); - is( $order->invoice_currency, $active_currency->currency, - 'no currency should be stored if none passed' ); + is( + $order->invoice_unitprice, $order->unitprice, + 'no price should be stored if none passed' + ); + is( + $order->invoice_currency, $active_currency->currency, + 'no currency should be stored if none passed' + ); }; subtest 'with invoice_unitprice' => sub { plan tests => 4; @@ -863,17 +941,24 @@ subtest 'ModReceiveOrder invoice_unitprice and invoice_currency' => sub { budget_id => $order->budget_id, } ); - my $received_order = - Koha::Acquisition::Orders->find($received_ordernumber); - is( $received_order->invoice_unitprice + 0, - 37, 'price should be stored in new order' ); - is( $received_order->invoice_currency, - 'GBP', 'currency should be stored in new order' ); + my $received_order = Koha::Acquisition::Orders->find($received_ordernumber); + is( + $received_order->invoice_unitprice + 0, + 37, 'price should be stored in new order' + ); + is( + $received_order->invoice_currency, + 'GBP', 'currency should be stored in new order' + ); $order = $order->get_from_storage; - is( $order->invoice_unitprice + 0, - 37, 'price should be stored in existing order' ); - is( $order->invoice_currency, 'GBP', - 'currency should be stored in existing order' ); + is( + $order->invoice_unitprice + 0, + 37, 'price should be stored in existing order' + ); + is( + $order->invoice_currency, 'GBP', + 'currency should be stored in existing order' + ); }; }; @@ -883,7 +968,7 @@ subtest 'ModReceiveOrder invoice_unitprice and invoice_currency' => sub { subtest 'no invoice_unitprice' => sub { plan tests => 4; - my $order = $builder->build_object( + my $order = $builder->build_object( { class => 'Koha::Acquisition::Orders', value => { @@ -902,24 +987,31 @@ subtest 'ModReceiveOrder invoice_unitprice and invoice_currency' => sub { }; my ( undef, $received_ordernumber ) = ModReceiveOrder( { - biblionumber => $order->biblionumber, - order => $order_info, - quantityreceived => 5, # We receive them all! + biblionumber => $order->biblionumber, + order => $order_info, + quantityreceived => 5, # We receive them all! budget_id => $order->budget_id, } ); my $active_currency = Koha::Acquisition::Currencies->get_active; - my $received_order = - Koha::Acquisition::Orders->find($received_ordernumber); - is( $received_order->invoice_unitprice, - $order->unitprice, 'no price should be stored if none passed' ); - is( $received_order->invoice_currency, - $active_currency->currency, 'no currency should be stored if none passed' ); + my $received_order = Koha::Acquisition::Orders->find($received_ordernumber); + is( + $received_order->invoice_unitprice, + $order->unitprice, 'no price should be stored if none passed' + ); + is( + $received_order->invoice_currency, + $active_currency->currency, 'no currency should be stored if none passed' + ); $order = $order->get_from_storage; - is( $order->invoice_unitprice, $order->unitprice, - 'no price should be stored if none passed' ); - is( $order->invoice_currency, $active_currency->currency, - 'no currency should be stored if none passed' ); + is( + $order->invoice_unitprice, $order->unitprice, + 'no price should be stored if none passed' + ); + is( + $order->invoice_currency, $active_currency->currency, + 'no currency should be stored if none passed' + ); }; @@ -950,17 +1042,24 @@ subtest 'ModReceiveOrder invoice_unitprice and invoice_currency' => sub { budget_id => $order->budget_id, } ); - my $received_order = - Koha::Acquisition::Orders->find($received_ordernumber); - is( $received_order->invoice_unitprice + 0, - 37, 'price should be stored in new order' ); - is( $received_order->invoice_currency, - 'GBP', 'currency should be stored in new order' ); + my $received_order = Koha::Acquisition::Orders->find($received_ordernumber); + is( + $received_order->invoice_unitprice + 0, + 37, 'price should be stored in new order' + ); + is( + $received_order->invoice_currency, + 'GBP', 'currency should be stored in new order' + ); $order = $order->get_from_storage; - is( $order->invoice_unitprice + 0, - 37, 'price should be stored in existing order' ); - is( $order->invoice_currency, 'GBP', - 'currency should be stored in existing order' ); + is( + $order->invoice_unitprice + 0, + 37, 'price should be stored in existing order' + ); + is( + $order->invoice_currency, 'GBP', + 'currency should be stored in existing order' + ); }; }; @@ -1009,36 +1108,50 @@ subtest 'GetHistory status search' => sub { subtest 'GetHistory with additional fields' => sub { plan tests => 3; - my $order_basket = $builder->build({ source => 'Aqbasket', value => { is_standing => 0 } }); - my $orderinfo ={ - basketno => $order_basket->{basketno}, - rrp => 19.99, - replacementprice => undef, - quantity => 1, - quantityreceived => 0, - datereceived => undef, + my $order_basket = $builder->build( { source => 'Aqbasket', value => { is_standing => 0 } } ); + my $orderinfo = { + basketno => $order_basket->{basketno}, + rrp => 19.99, + replacementprice => undef, + quantity => 1, + quantityreceived => 0, + datereceived => undef, datecancellationprinted => undef, }; - my $order = $builder->build({ source => 'Aqorder', value => $orderinfo }); - my $history = GetHistory(ordernumber => $order->{ordernumber}); - is( scalar( @$history ), 1, 'GetHistory returns the one order'); + my $order = $builder->build( { source => 'Aqorder', value => $orderinfo } ); + my $history = GetHistory( ordernumber => $order->{ordernumber} ); + is( scalar(@$history), 1, 'GetHistory returns the one order' ); - my $additional_field = $builder->build({source => 'AdditionalField', value => { - tablename => 'aqbasket', - name => 'snakeoil', - authorised_value_category => "", + my $additional_field = $builder->build( + { + source => 'AdditionalField', + value => { + tablename => 'aqbasket', + name => 'snakeoil', + authorised_value_category => "", + } } - }); - $history = GetHistory( ordernumber => $order->{ordernumber}, additional_fields => [{ id => $additional_field->{id}, value=>'delicious'}]); - is( scalar ( @$history ), 0, 'GetHistory returns no order for an unused additional field'); - my $basket = Koha::Acquisition::Baskets->find({ basketno => $order_basket->{basketno} }); - $basket->set_additional_fields([{ - id => $additional_field->{id}, - value => 'delicious', - }]); + ); + $history = GetHistory( + ordernumber => $order->{ordernumber}, + additional_fields => [ { id => $additional_field->{id}, value => 'delicious' } ] + ); + is( scalar(@$history), 0, 'GetHistory returns no order for an unused additional field' ); + my $basket = Koha::Acquisition::Baskets->find( { basketno => $order_basket->{basketno} } ); + $basket->set_additional_fields( + [ + { + id => $additional_field->{id}, + value => 'delicious', + } + ] + ); - $history = GetHistory( ordernumber => $order->{ordernumber}, additional_fields => [{ id => $additional_field->{id}, value=>'delicious'}]); - is( scalar( @$history ), 1, 'GetHistory returns the order when additional field is set'); + $history = GetHistory( + ordernumber => $order->{ordernumber}, + additional_fields => [ { id => $additional_field->{id}, value => 'delicious' } ] + ); + is( scalar(@$history), 1, 'GetHistory returns the order when additional field is set' ); }; subtest 'Tests for get_rounding_sql' => sub { @@ -1076,10 +1189,10 @@ subtest 'Test for get_rounded_price' => sub { my $rounded_result2 = C4::Acquisition::get_rounded_price($up_price); my $rounded_result3 = C4::Acquisition::get_rounded_price($down_price); - is( $not_rounded_result1, $exact_price, "Price ($exact_price) was correctly not rounded ($not_rounded_result1)" ); - is( $not_rounded_result2, $up_price, "Price ($up_price) was correctly not rounded ($not_rounded_result2)" ); - is( $not_rounded_result3, $down_price, "Price ($down_price) was correctly not rounded ($not_rounded_result3)" ); - is( $rounded_result1, $exact_price, "Price ($exact_price) was correctly rounded ($rounded_result1)" ); + is( $not_rounded_result1, $exact_price, "Price ($exact_price) was correctly not rounded ($not_rounded_result1)" ); + is( $not_rounded_result2, $up_price, "Price ($up_price) was correctly not rounded ($not_rounded_result2)" ); + is( $not_rounded_result3, $down_price, "Price ($down_price) was correctly not rounded ($not_rounded_result3)" ); + is( $rounded_result1, $exact_price, "Price ($exact_price) was correctly rounded ($rounded_result1)" ); is( $rounded_result2, $round_up_price, "Price ($up_price) was correctly rounded ($rounded_result2)" ); is( $rounded_result3, $round_down_price, "Price ($down_price) was correctly rounded ($rounded_result3)" ); @@ -1089,34 +1202,34 @@ subtest 'GetHistory - managing library' => sub { plan tests => 1; - my $orders = GetHistory(managing_library => 'CPL'); + my $orders = GetHistory( managing_library => 'CPL' ); - my $order_basket1 = $builder->build({ source => 'Aqbasket', value => { branch => 'CPL' } }); - my $orderinfo1 ={ - basketno => $order_basket1->{basketno}, - rrp => 19.99, - replacementprice => undef, - quantity => 1, - quantityreceived => 0, - datereceived => undef, + my $order_basket1 = $builder->build( { source => 'Aqbasket', value => { branch => 'CPL' } } ); + my $orderinfo1 = { + basketno => $order_basket1->{basketno}, + rrp => 19.99, + replacementprice => undef, + quantity => 1, + quantityreceived => 0, + datereceived => undef, datecancellationprinted => undef, }; - my $order1 = $builder->build({ source => 'Aqorder', value => $orderinfo1 }); + my $order1 = $builder->build( { source => 'Aqorder', value => $orderinfo1 } ); - my $order_basket2 = $builder->build({ source => 'Aqbasket', value => { branch => 'LIB' } }); - my $orderinfo2 ={ - basketno => $order_basket2->{basketno}, - rrp => 19.99, - replacementprice => undef, - quantity => 1, - quantityreceived => 0, - datereceived => undef, + my $order_basket2 = $builder->build( { source => 'Aqbasket', value => { branch => 'LIB' } } ); + my $orderinfo2 = { + basketno => $order_basket2->{basketno}, + rrp => 19.99, + replacementprice => undef, + quantity => 1, + quantityreceived => 0, + datereceived => undef, datecancellationprinted => undef, }; - my $order2 = $builder->build({ source => 'Aqorder', value => $orderinfo2 }); + my $order2 = $builder->build( { source => 'Aqorder', value => $orderinfo2 } ); - my $history = GetHistory(managing_library => 'CPL'); - is( scalar( @$history), scalar ( @$orders ) +1, "GetHistory returns number of orders"); + my $history = GetHistory( managing_library => 'CPL' ); + is( scalar(@$history), scalar(@$orders) + 1, "GetHistory returns number of orders" ); }; @@ -1127,7 +1240,7 @@ subtest 'GetHistory - is_standing' => sub { my $orders = GetHistory( is_standing => '1' ); my $order_basket1 = $builder->build( { source => 'Aqbasket', value => { is_standing => 0 } } ); - my $orderinfo1 = { + my $orderinfo1 = { basketno => $order_basket1->{basketno}, rrp => 19.99, replacementprice => undef, @@ -1139,7 +1252,7 @@ subtest 'GetHistory - is_standing' => sub { my $order1 = $builder->build( { source => 'Aqorder', value => $orderinfo1 } ); my $order_basket2 = $builder->build( { source => 'Aqbasket', value => { is_standing => 1 } } ); - my $orderinfo2 = { + my $orderinfo2 = { basketno => $order_basket2->{basketno}, rrp => 19.99, replacementprice => undef, @@ -1163,37 +1276,48 @@ subtest 'Acquisition logging' => sub { plan tests => 5; - t::lib::Mocks::mock_preference('AcquisitionLog', 1); + t::lib::Mocks::mock_preference( 'AcquisitionLog', 1 ); Koha::ActionLogs->delete; my $basketno = NewBasket( $booksellerid, 1 ); - my @create_logs = Koha::ActionLogs->search({ module =>'ACQUISITIONS', action => 'ADD_BASKET', object => $basketno })->as_list; - is (scalar @create_logs, 1, 'Basket creation is logged'); + my @create_logs = + Koha::ActionLogs->search( { module => 'ACQUISITIONS', action => 'ADD_BASKET', object => $basketno } )->as_list; + is( scalar @create_logs, 1, 'Basket creation is logged' ); Koha::ActionLogs->delete; C4::Acquisition::ReopenBasket($basketno); - my @reopen_logs = Koha::ActionLogs->search({ module =>'ACQUISITIONS', action => 'REOPEN_BASKET', object => $basketno })->as_list; - is (scalar @reopen_logs, 1, 'Basket reopen is logged'); + my @reopen_logs = + Koha::ActionLogs->search( { module => 'ACQUISITIONS', action => 'REOPEN_BASKET', object => $basketno } ) + ->as_list; + is( scalar @reopen_logs, 1, 'Basket reopen is logged' ); Koha::ActionLogs->delete; - C4::Acquisition::ModBasket({ - basketno => $basketno, - booksellerid => $booksellerid - }); - my @mod_logs = Koha::ActionLogs->search({ module =>'ACQUISITIONS', action => 'MODIFY_BASKET', object => $basketno })->as_list; - is (scalar @mod_logs, 1, 'Basket modify is logged'); + C4::Acquisition::ModBasket( + { + basketno => $basketno, + booksellerid => $booksellerid + } + ); + my @mod_logs = + Koha::ActionLogs->search( { module => 'ACQUISITIONS', action => 'MODIFY_BASKET', object => $basketno } ) + ->as_list; + is( scalar @mod_logs, 1, 'Basket modify is logged' ); Koha::ActionLogs->delete; - C4::Acquisition::ModBasketHeader($basketno,"Test","","","",$booksellerid); - my @mod_header_logs = Koha::ActionLogs->search({ module =>'ACQUISITIONS', action => 'MODIFY_BASKET_HEADER', object => $basketno })->as_list; - is (scalar @mod_header_logs, 1, 'Basket header modify is logged'); + C4::Acquisition::ModBasketHeader( $basketno, "Test", "", "", "", $booksellerid ); + my @mod_header_logs = + Koha::ActionLogs->search( { module => 'ACQUISITIONS', action => 'MODIFY_BASKET_HEADER', object => $basketno } ) + ->as_list; + is( scalar @mod_header_logs, 1, 'Basket header modify is logged' ); Koha::ActionLogs->delete; - C4::Acquisition::ModBasketUsers($basketno,(1)); - my @mod_users_logs = Koha::ActionLogs->search({ module =>'ACQUISITIONS', action => 'MODIFY_BASKET_USERS', object => $basketno })->as_list; - is (scalar @mod_users_logs, 1, 'Basket users modify is logged'); + C4::Acquisition::ModBasketUsers( $basketno, (1) ); + my @mod_users_logs = + Koha::ActionLogs->search( { module => 'ACQUISITIONS', action => 'MODIFY_BASKET_USERS', object => $basketno } ) + ->as_list; + is( scalar @mod_users_logs, 1, 'Basket users modify is logged' ); - t::lib::Mocks::mock_preference('AcquisitionLog', 0); + t::lib::Mocks::mock_preference( 'AcquisitionLog', 0 ); }; $schema->storage->txn_rollback(); @@ -1206,29 +1330,25 @@ subtest 'GetInvoices() tests with additional fields' => sub { my $invoice_1 = $builder->build_object( { - class => 'Koha::Acquisition::Invoices', - value => { - invoicenumber => 'whataretheodds1' - } + class => 'Koha::Acquisition::Invoices', + value => { invoicenumber => 'whataretheodds1' } } ); my $invoice_2 = $builder->build_object( { - class => 'Koha::Acquisition::Invoices', - value => { - invoicenumber => 'whataretheodds2' - } + class => 'Koha::Acquisition::Invoices', + value => { invoicenumber => 'whataretheodds2' } } ); - my $invoices = [ GetInvoices( invoicenumber => 'whataretheodds' ) ]; - is( scalar @{$invoices}, 2, 'Two invoices retrieved' ); + is( scalar @{$invoices}, 2, 'Two invoices retrieved' ); is( $invoices->[0]->{invoiceid}, $invoice_1->id ); is( $invoices->[1]->{invoiceid}, $invoice_2->id ); my $additional_field_1 = $builder->build_object( - { class => 'Koha::AdditionalFields', + { + class => 'Koha::AdditionalFields', value => { tablename => 'aqinvoices', authorised_value_category => "", @@ -1237,7 +1357,8 @@ subtest 'GetInvoices() tests with additional fields' => sub { ); my $additional_field_2 = $builder->build_object( - { class => 'Koha::AdditionalFields', + { + class => 'Koha::AdditionalFields', value => { tablename => 'aqinvoices', authorised_value_category => "", @@ -1245,21 +1366,25 @@ subtest 'GetInvoices() tests with additional fields' => sub { } ); - $invoice_1->set_additional_fields([ { id => $additional_field_1->id, value => 'Ya-Hey' } ]); - $invoice_2->set_additional_fields([ { id => $additional_field_2->id, value => "Hey ho let's go" } ]); + $invoice_1->set_additional_fields( [ { id => $additional_field_1->id, value => 'Ya-Hey' } ] ); + $invoice_2->set_additional_fields( [ { id => $additional_field_2->id, value => "Hey ho let's go" } ] ); - $invoices = [ GetInvoices( - invoicenumber => 'whataretheodds', - additional_fields => [{ id => $additional_field_1->id, value => 'Ya-Hey' }] - )]; - is( scalar @{$invoices}, 1, 'One invoice retrieved' ); + $invoices = [ + GetInvoices( + invoicenumber => 'whataretheodds', + additional_fields => [ { id => $additional_field_1->id, value => 'Ya-Hey' } ] + ) + ]; + is( scalar @{$invoices}, 1, 'One invoice retrieved' ); is( $invoices->[0]->{invoiceid}, $invoice_1->id, 'Ya-Hey' ); - $invoices = [ GetInvoices( - invoicenumber => 'whataretheodds', - additional_fields => [{ id => $additional_field_2->id, value => "Hey ho let's go" }] - )]; - is( scalar @{$invoices}, 1, 'One invoice retrieved' ); + $invoices = [ + GetInvoices( + invoicenumber => 'whataretheodds', + additional_fields => [ { id => $additional_field_2->id, value => "Hey ho let's go" } ] + ) + ]; + is( scalar @{$invoices}, 1, 'One invoice retrieved' ); is( $invoices->[0]->{invoiceid}, $invoice_2->id, "Hey ho let's go" ); $schema->storage->txn_rollback; diff --git a/t/db_dependent/Acquisition/CancelReceipt.t b/t/db_dependent/Acquisition/CancelReceipt.t index 6e25ed8edb..78dcf4af71 100755 --- a/t/db_dependent/Acquisition/CancelReceipt.t +++ b/t/db_dependent/Acquisition/CancelReceipt.t @@ -22,7 +22,7 @@ use t::lib::TestBuilder; use C4::Context; use C4::Acquisition qw( NewBasket ModReceiveOrder CancelReceipt ); -use C4::Biblio qw( AddBiblio ); +use C4::Biblio qw( AddBiblio ); use C4::Items; use C4::Budgets qw( AddBudget GetBudget ); use t::lib::Mocks; @@ -37,22 +37,20 @@ use MARC::Record; my $schema = Koha::Database->new()->schema(); $schema->storage->txn_begin(); -my $builder = t::lib::TestBuilder->new; -my $itemtype = $builder->build({ source => 'Itemtype' })->{ itemtype }; +my $builder = t::lib::TestBuilder->new; +my $itemtype = $builder->build( { source => 'Itemtype' } )->{itemtype}; my $bookseller = Koha::Acquisition::Bookseller->new( { - name => "my vendor 1", + name => "my vendor 1", address1 => "bookseller's address", - phone => "0123456", - active => 1 + phone => "0123456", + active => 1 } )->store; -t::lib::Mocks::mock_preference('AcqCreateItem', 'receiving'); +t::lib::Mocks::mock_preference( 'AcqCreateItem', 'receiving' ); -my $basketno1 = C4::Acquisition::NewBasket( - $bookseller->id -); +my $basketno1 = C4::Acquisition::NewBasket( $bookseller->id ); my $budget_period_id = C4::Budgets::AddBudgetPeriod( { @@ -71,17 +69,17 @@ my $budgetid = C4::Budgets::AddBudget( } ); -my $budget = C4::Budgets::GetBudget( $budgetid ); +my $budget = C4::Budgets::GetBudget($budgetid); -my ($biblionumber, $biblioitemnumber) = AddBiblio(MARC::Record->new, ''); -my $itemnumber = Koha::Item->new({ itype => $itemtype, biblionumber => $biblionumber })->store->itemnumber; +my ( $biblionumber, $biblioitemnumber ) = AddBiblio( MARC::Record->new, '' ); +my $itemnumber = Koha::Item->new( { itype => $itemtype, biblionumber => $biblionumber } )->store->itemnumber; my $order = Koha::Acquisition::Order->new( { - basketno => $basketno1, - quantity => 2, + basketno => $basketno1, + quantity => 2, biblionumber => $biblionumber, - budget_id => $budget->{budget_id}, + budget_id => $budget->{budget_id}, } )->store; my $ordernumber = $order->ordernumber; @@ -94,33 +92,34 @@ ModReceiveOrder( } ); -$order->add_item( $itemnumber ); +$order->add_item($itemnumber); CancelReceipt($ordernumber); -is($order->items->count, 0, "Create items on receiving: 0 item exist after cancelling a receipt"); +is( $order->items->count, 0, "Create items on receiving: 0 item exist after cancelling a receipt" ); -my $itemnumber1 = Koha::Item->new({ itype => $itemtype, biblionumber => $biblionumber })->store->itemnumber; -my $itemnumber2 = Koha::Item->new({ itype => $itemtype, biblionumber => $biblionumber })->store->itemnumber; +my $itemnumber1 = Koha::Item->new( { itype => $itemtype, biblionumber => $biblionumber } )->store->itemnumber; +my $itemnumber2 = Koha::Item->new( { itype => $itemtype, biblionumber => $biblionumber } )->store->itemnumber; -t::lib::Mocks::mock_preference('AcqCreateItem', 'ordering'); -t::lib::Mocks::mock_preference('AcqItemSetSubfieldsWhenReceiptIsCancelled', '7=9'); # notforloan is mapped with 952$7 +t::lib::Mocks::mock_preference( 'AcqCreateItem', 'ordering' ); +t::lib::Mocks::mock_preference( 'AcqItemSetSubfieldsWhenReceiptIsCancelled', '7=9' ); # notforloan is mapped with 952$7 $order = Koha::Acquisition::Order->new( { - basketno => $basketno1, - quantity => 2, + basketno => $basketno1, + quantity => 2, biblionumber => $biblionumber, - budget_id => $budget->{budget_id}, + budget_id => $budget->{budget_id}, } )->store; $ordernumber = $order->ordernumber; -is( $order->parent_ordernumber, $order->ordernumber, +is( + $order->parent_ordernumber, $order->ordernumber, "Insert an order should set parent_order=ordernumber, if no parent_ordernumber given" ); -$order->add_item( $itemnumber1 ); -$order->add_item( $itemnumber2 ); +$order->add_item($itemnumber1); +$order->add_item($itemnumber2); is( $order->items->count, @@ -133,17 +132,22 @@ my ( undef, $new_ordernumber ) = ModReceiveOrder( biblionumber => $biblionumber, order => $order->unblessed, quantityreceived => 1, - received_items => [ $itemnumber1 ], + received_items => [$itemnumber1], } ); -my $new_order = Koha::Acquisition::Orders->find( $new_ordernumber ); +my $new_order = Koha::Acquisition::Orders->find($new_ordernumber); -is( $new_order->ordernumber, $new_ordernumber, - "ModReceiveOrder should return a correct ordernumber" ); -isnt( $new_ordernumber, $ordernumber, - "ModReceiveOrder should return a different ordernumber" ); -is( $new_order->parent_ordernumber, $ordernumber, +is( + $new_order->ordernumber, $new_ordernumber, + "ModReceiveOrder should return a correct ordernumber" +); +isnt( + $new_ordernumber, $ordernumber, + "ModReceiveOrder should return a different ordernumber" +); +is( + $new_order->parent_ordernumber, $ordernumber, "The new order created by ModReceiveOrder should be linked to the parent order" ); @@ -171,10 +175,10 @@ is( "Create items on ordering: items are not deleted after cancelling a receipt" ); -my $item1 = Koha::Items->find( $itemnumber1 ); +my $item1 = Koha::Items->find($itemnumber1); is( $item1->notforloan, 9, "The notforloan value has been updated with '9'" ); -my $item2 = Koha::Items->find( $itemnumber2 ); +my $item2 = Koha::Items->find($itemnumber2); is( $item2->notforloan, 0, "The notforloan value has been updated with '0'" ); $schema->storage->txn_rollback(); diff --git a/t/db_dependent/Acquisition/FillWithDefaultValues.t b/t/db_dependent/Acquisition/FillWithDefaultValues.t index 96969e0c7f..fc19aefce6 100755 --- a/t/db_dependent/Acquisition/FillWithDefaultValues.t +++ b/t/db_dependent/Acquisition/FillWithDefaultValues.t @@ -31,7 +31,7 @@ $biblio_module->mock( repeatable => 0, tab => 0, lib => 'a lib', - }, + }, # default for a nonexisting field '099' => { @@ -97,24 +97,25 @@ is_deeply( ); # Test controlfield default -$record->field('008')->update( undef ); +$record->field('008')->update(undef); C4::Acquisition::FillWithDefaultValues($record); is( $record->field('008')->data, $default_x, 'Controlfield got default' ); -is( $record->subfield('942','d'), '942d_val', 'Check 942d' ); +is( $record->subfield( '942', 'd' ), '942d_val', 'Check 942d' ); # Now test only_mandatory parameter $record->delete_fields( $record->field('245') ); $record->delete_fields( $record->field('942') ); -$record->append_fields( MARC::Field->new('942','','','f'=>'f val') ); +$record->append_fields( MARC::Field->new( '942', '', '', 'f' => 'f val' ) ); + # We deleted 245 and replaced 942. If we only apply mandatories, we should get # back 245c again and 942c but not 942d. 942f should be left alone. -C4::Acquisition::FillWithDefaultValues($record, { only_mandatory => 1 }); +C4::Acquisition::FillWithDefaultValues( $record, { only_mandatory => 1 } ); @fields_245 = $record->field(245); is( scalar @fields_245, 1, 'Only one 245 expected' ); -is( $record->subfield('245','c'), $default_author, '245c restored' ); -is( $record->subfield('942','c'), 'BK', '942c also restored' ); -is( $record->subfield('942','d'), undef, '942d should not be there' ); -is( $record->subfield('942','f'), 'f val', '942f untouched' ); +is( $record->subfield( '245', 'c' ), $default_author, '245c restored' ); +is( $record->subfield( '942', 'c' ), 'BK', '942c also restored' ); +is( $record->subfield( '942', 'd' ), undef, '942d should not be there' ); +is( $record->subfield( '942', 'f' ), 'f val', '942f untouched' ); $schema->storage->txn_rollback; diff --git a/t/db_dependent/Acquisition/GetBasketAsCSV.t b/t/db_dependent/Acquisition/GetBasketAsCSV.t index 37b01e79e6..45c9c7b950 100755 --- a/t/db_dependent/Acquisition/GetBasketAsCSV.t +++ b/t/db_dependent/Acquisition/GetBasketAsCSV.t @@ -7,7 +7,7 @@ use CGI; use Test::More tests => 5; use C4::Acquisition qw( NewBasket GetBasket GetBasketAsCSV ); -use C4::Biblio qw( AddBiblio ); +use C4::Biblio qw( AddBiblio ); use Koha::Database; use Koha::CsvProfiles; use Koha::Acquisition::Orders; @@ -21,12 +21,14 @@ $schema->storage->txn_begin(); my $query = CGI->new(); -my $vendor = Koha::Acquisition::Bookseller->new({ - name => 'my vendor', - address1 => 'vendor address', - active => 1, - deliverytime => 5, -})->store; +my $vendor = Koha::Acquisition::Bookseller->new( + { + name => 'my vendor', + address1 => 'vendor address', + active => 1, + deliverytime => 5, + } +)->store; my $budget_period_id = C4::Budgets::AddBudgetPeriod( { @@ -44,47 +46,55 @@ my $budget_id = C4::Budgets::AddBudget( budget_period_id => $budget_period_id, } ); -my $budget = C4::Budgets::GetBudget( $budget_id ); +my $budget = C4::Budgets::GetBudget($budget_id); -my $csv_profile = Koha::CsvProfile->new({ - profile => 'my user profile', - type => 'export_basket', - csv_separator => ',', - content => 'autor=biblio.author|title=biblio.title|quantity=aqorders.quantity', - description => 'csv profile', -})->store; +my $csv_profile = Koha::CsvProfile->new( + { + profile => 'my user profile', + type => 'export_basket', + csv_separator => ',', + content => 'autor=biblio.author|title=biblio.title|quantity=aqorders.quantity', + description => 'csv profile', + } +)->store; -my $csv_profile2 = Koha::CsvProfile->new({ - profile => 'my user profile', - type => 'export_basket', - csv_separator => ',', - content => 'biblio.author | title = biblio.title|quantity=aqorders.quantity', - description => 'csv profile 2', -})->store; +my $csv_profile2 = Koha::CsvProfile->new( + { + profile => 'my user profile', + type => 'export_basket', + csv_separator => ',', + content => 'biblio.author | title = biblio.title|quantity=aqorders.quantity', + description => 'csv profile 2', + } +)->store; my $basketno; -$basketno = NewBasket($vendor->id, 1); +$basketno = NewBasket( $vendor->id, 1 ); my $biblio = MARC::Record->new(); $biblio->append_fields( MARC::Field->new( '100', ' ', ' ', a => 'King, Stephen' ), MARC::Field->new( '245', ' ', ' ', a => 'Test Record' ), ); -my ($biblionumber, $biblioitemnumber) = AddBiblio($biblio, ''); +my ( $biblionumber, $biblioitemnumber ) = AddBiblio( $biblio, '' ); -my $order = Koha::Acquisition::Order->new({ - basketno => $basketno, - quantity => 3, - biblionumber => $biblionumber, - budget_id => $budget_id, - entrydate => '2016-01-02', -})->store; +my $order = Koha::Acquisition::Order->new( + { + basketno => $basketno, + quantity => 3, + biblionumber => $biblionumber, + budget_id => $budget_id, + entrydate => '2016-01-02', + } +)->store; # Use user CSV profile -my $basket_csv1 = C4::Acquisition::GetBasketAsCSV($basketno, $query, $csv_profile->export_format_id); -is($basket_csv1, 'autor,title,quantity +my $basket_csv1 = C4::Acquisition::GetBasketAsCSV( $basketno, $query, $csv_profile->export_format_id ); +is( + $basket_csv1, 'autor,title,quantity "King, Stephen","Test Record",3 -', 'CSV should be generated with user profile'); +', 'CSV should be generated with user profile' +); # Use default template t::lib::Mocks::mock_preference( 'CSVDelimiter', ',' ); @@ -96,16 +106,21 @@ is( ', 'CSV should be generated with default template' ); -my $basket_csv3 = C4::Acquisition::GetBasketAsCSV($basketno, $query, $csv_profile2->export_format_id); -is($basket_csv3, 'biblio.author,title,quantity +my $basket_csv3 = C4::Acquisition::GetBasketAsCSV( $basketno, $query, $csv_profile2->export_format_id ); +is( + $basket_csv3, 'biblio.author,title,quantity "King, Stephen","Test Record",3 -', 'CSV should be generated with user profile which does not have all headers defined'); +', 'CSV should be generated with user profile which does not have all headers defined' +); try { - my $basket_csv4 = C4::Acquisition::GetBasketAsCSV($basketno, $query, 'non_existant_profile_id'); + my $basket_csv4 = C4::Acquisition::GetBasketAsCSV( $basketno, $query, 'non_existant_profile_id' ); fail("It is not possible to export basket using non-existant profile"); } catch { - ok($_->isa("Koha::Exceptions::ObjectNotFound"), "Using non-existant profile should throw ObjectNotFound exception"); + ok( + $_->isa("Koha::Exceptions::ObjectNotFound"), + "Using non-existant profile should throw ObjectNotFound exception" + ); }; Koha::Biblios->find($biblionumber)->delete; diff --git a/t/db_dependent/Acquisition/GetBasketGroupAsCSV.t b/t/db_dependent/Acquisition/GetBasketGroupAsCSV.t index ce9a90a26b..5715183ecf 100755 --- a/t/db_dependent/Acquisition/GetBasketGroupAsCSV.t +++ b/t/db_dependent/Acquisition/GetBasketGroupAsCSV.t @@ -7,7 +7,7 @@ use CGI; use Test::More tests => 2; use C4::Acquisition qw( NewBasket NewBasketgroup GetBasketGroupAsCSV ); -use C4::Biblio qw( AddBiblio ); +use C4::Biblio qw( AddBiblio ); use Koha::Database; use Koha::CsvProfiles; use Koha::Acquisition::Orders; @@ -21,12 +21,14 @@ $schema->storage->txn_begin(); my $query = CGI->new(); -my $vendor = Koha::Acquisition::Bookseller->new({ - name => 'my vendor', - address1 => 'vendor address', - active => 1, - deliverytime => 5, -})->store; +my $vendor = Koha::Acquisition::Bookseller->new( + { + name => 'my vendor', + address1 => 'vendor address', + active => 1, + deliverytime => 5, + } +)->store; my $budget_period_id = C4::Budgets::AddBudgetPeriod( { @@ -44,14 +46,14 @@ my $budget_id = C4::Budgets::AddBudget( budget_period_id => $budget_period_id, } ); -my $budget = C4::Budgets::GetBudget( $budget_id ); +my $budget = C4::Budgets::GetBudget($budget_id); -my $basketno = C4::Acquisition::NewBasket($vendor->id, 1); +my $basketno = C4::Acquisition::NewBasket( $vendor->id, 1 ); my $basketgroupid = C4::Acquisition::NewBasketgroup( { - booksellerid => $vendor->id, - basketlist => [ $basketno ], + booksellerid => $vendor->id, + basketlist => [$basketno], } ); @@ -60,17 +62,19 @@ $biblio->append_fields( MARC::Field->new( '100', ' ', ' ', a => 'King, Stephen' ), MARC::Field->new( '245', ' ', ' ', a => 'Test Record' ), ); -my ($biblionumber, $biblioitemnumber) = AddBiblio($biblio, ''); +my ( $biblionumber, $biblioitemnumber ) = AddBiblio( $biblio, '' ); -my $order = Koha::Acquisition::Order->new({ - basketno => $basketno, - quantity => 3, - biblionumber => $biblionumber, - budget_id => $budget_id, - entrydate => '2016-01-02', -})->store; +my $order = Koha::Acquisition::Order->new( + { + basketno => $basketno, + quantity => 3, + biblionumber => $biblionumber, + budget_id => $budget_id, + entrydate => '2016-01-02', + } +)->store; -t::lib::Mocks::mock_preference('CSVDelimiter', ','); +t::lib::Mocks::mock_preference( 'CSVDelimiter', ',' ); my $basketgroup_csv1 = C4::Acquisition::GetBasketGroupAsCSV( $basketgroupid, $query ); is( diff --git a/t/db_dependent/Acquisition/GetBasketsInfosByBookseller.t b/t/db_dependent/Acquisition/GetBasketsInfosByBookseller.t index b978cd76ce..852f8407f9 100755 --- a/t/db_dependent/Acquisition/GetBasketsInfosByBookseller.t +++ b/t/db_dependent/Acquisition/GetBasketsInfosByBookseller.t @@ -4,8 +4,9 @@ use Modern::Perl; use Test::More tests => 43; use Data::Dumper; -use C4::Acquisition qw( NewBasket GetBasket GetBasketsInfosByBookseller ReopenBasket AddInvoice GetInvoice ModReceiveOrder ); -use C4::Biblio qw( AddBiblio ); +use C4::Acquisition + qw( NewBasket GetBasket GetBasketsInfosByBookseller ReopenBasket AddInvoice GetInvoice ModReceiveOrder ); +use C4::Biblio qw( AddBiblio ); use C4::Budgets qw( AddBudget GetBudget ); use C4::Context; use Koha::Database; @@ -16,17 +17,17 @@ $schema->storage->txn_begin(); my $supplier = Koha::Acquisition::Bookseller->new( { - name => 'my vendor', - address1 => 'bookseller\'s address', - phone => '0123456', - active => 1, + name => 'my vendor', + address1 => 'bookseller\'s address', + phone => '0123456', + active => 1, deliverytime => 5, } )->store; my $supplierid = $supplier->id; my $basketno; -ok($basketno = NewBasket($supplierid, 1), 'NewBasket( $supplierid , 1 ) returns $basketno'); +ok( $basketno = NewBasket( $supplierid, 1 ), 'NewBasket( $supplierid , 1 ) returns $basketno' ); my $budget_period_id = C4::Budgets::AddBudgetPeriod( { @@ -44,143 +45,145 @@ my $budgetid = C4::Budgets::AddBudget( budget_period_id => $budget_period_id, } ); -my $budget = C4::Budgets::GetBudget( $budgetid ); +my $budget = C4::Budgets::GetBudget($budgetid); -my ($biblionumber1, $biblioitemnumber1) = AddBiblio(MARC::Record->new, ''); -my ($biblionumber2, $biblioitemnumber2) = AddBiblio(MARC::Record->new, ''); -my ($biblionumber3, $biblioitemnumber3) = AddBiblio(MARC::Record->new, ''); +my ( $biblionumber1, $biblioitemnumber1 ) = AddBiblio( MARC::Record->new, '' ); +my ( $biblionumber2, $biblioitemnumber2 ) = AddBiblio( MARC::Record->new, '' ); +my ( $biblionumber3, $biblioitemnumber3 ) = AddBiblio( MARC::Record->new, '' ); my $order1 = Koha::Acquisition::Order->new( { - basketno => $basketno, - quantity => 2, + basketno => $basketno, + quantity => 2, biblionumber => $biblionumber1, - budget_id => $budget->{budget_id}, + budget_id => $budget->{budget_id}, } )->store; my $ordernumber1 = $order1->ordernumber; my $order2 = Koha::Acquisition::Order->new( { - basketno => $basketno, - quantity => 4, + basketno => $basketno, + quantity => 4, biblionumber => $biblionumber2, - budget_id => $budget->{budget_id}, + budget_id => $budget->{budget_id}, } )->store; my $ordernumber2 = $order2->ordernumber; -my $baskets = C4::Acquisition::GetBasketsInfosByBookseller( $supplierid ); +my $baskets = C4::Acquisition::GetBasketsInfosByBookseller($supplierid); is( scalar(@$baskets), 1, 'Start: 1 basket' ); my $basket = $baskets->[0]; -is( $basket->{total_items}, 6, 'Start with 6 items' ); -is( $basket->{total_biblios}, 2, 'Start with 2 biblios' ); -is( $basket->{total_items_cancelled}, 0, 'Start with 0 item cancelled' ); -is( $basket->{expected_items}, 6, 'Start with 6 items expected' ); +is( $basket->{total_items}, 6, 'Start with 6 items' ); +is( $basket->{total_biblios}, 2, 'Start with 2 biblios' ); +is( $basket->{total_items_cancelled}, 0, 'Start with 0 item cancelled' ); +is( $basket->{expected_items}, 6, 'Start with 6 items expected' ); is( $basket->{total_biblios_cancelled}, 0, 'Start with 0 biblio cancelled' ); $order1->uncertainprice(1)->store; -$baskets = C4::Acquisition::GetBasketsInfosByBookseller( $supplierid ); -$basket = $baskets->[0]; -is( $basket->{uncertainprices}, 1, "Uncertain prcies returns number of uncertain items"); +$baskets = C4::Acquisition::GetBasketsInfosByBookseller($supplierid); +$basket = $baskets->[0]; +is( $basket->{uncertainprices}, 1, "Uncertain prcies returns number of uncertain items" ); $order2->uncertainprice(1)->store; -$baskets = C4::Acquisition::GetBasketsInfosByBookseller( $supplierid ); -$basket = $baskets->[0]; -is( $basket->{uncertainprices}, 2, "Uncertain prcies returns number of uncertain items"); +$baskets = C4::Acquisition::GetBasketsInfosByBookseller($supplierid); +$basket = $baskets->[0]; +is( $basket->{uncertainprices}, 2, "Uncertain prcies returns number of uncertain items" ); $order1->uncertainprice(0)->store; $order2->uncertainprice(0)->store; -$baskets = C4::Acquisition::GetBasketsInfosByBookseller( $supplierid ); -$basket = $baskets->[0]; -is( $basket->{uncertainprices}, 0, "Uncertain prcies returns number of uncertain items"); +$baskets = C4::Acquisition::GetBasketsInfosByBookseller($supplierid); +$basket = $baskets->[0]; +is( $basket->{uncertainprices}, 0, "Uncertain prcies returns number of uncertain items" ); Koha::Acquisition::Orders->find($ordernumber2)->cancel; -$baskets = C4::Acquisition::GetBasketsInfosByBookseller( $supplierid ); +$baskets = C4::Acquisition::GetBasketsInfosByBookseller($supplierid); is( scalar(@$baskets), 1, 'Order2 deleted, still 1 basket' ); $basket = $baskets->[0]; -is( $basket->{total_items}, 6, 'Order2 deleted, still 6 items' ); -is( $basket->{total_biblios}, 2, 'Order2 deleted, still 2 biblios' ); -is( $basket->{total_items_cancelled}, 4, 'Order2 deleted, 4 items cancelled' ); -is( $basket->{expected_items}, 2, 'Order2 deleted, now 2 items are expected' ); +is( $basket->{total_items}, 6, 'Order2 deleted, still 6 items' ); +is( $basket->{total_biblios}, 2, 'Order2 deleted, still 2 biblios' ); +is( $basket->{total_items_cancelled}, 4, 'Order2 deleted, 4 items cancelled' ); +is( $basket->{expected_items}, 2, 'Order2 deleted, now 2 items are expected' ); is( $basket->{total_biblios_cancelled}, 1, 'Order2 deleted, 1 biblios cancelled' ); Koha::Acquisition::Orders->find($ordernumber1)->cancel; -$baskets = C4::Acquisition::GetBasketsInfosByBookseller( $supplierid ); +$baskets = C4::Acquisition::GetBasketsInfosByBookseller($supplierid); is( scalar(@$baskets), 1, 'Both orders deleted, still 1 basket' ); $basket = $baskets->[0]; -is( $basket->{total_items}, 6, 'Both orders deleted, still 6 items' ); -is( $basket->{total_biblios}, 2, 'Both orders deleted, still 2 biblios' ); -is( $basket->{total_items_cancelled}, 6, 'Both orders deleted, 6 items cancelled' ); -is( $basket->{expected_items}, 0, 'Both orders delete, now 0 items are expected' ); +is( $basket->{total_items}, 6, 'Both orders deleted, still 6 items' ); +is( $basket->{total_biblios}, 2, 'Both orders deleted, still 2 biblios' ); +is( $basket->{total_items_cancelled}, 6, 'Both orders deleted, 6 items cancelled' ); +is( $basket->{expected_items}, 0, 'Both orders delete, now 0 items are expected' ); is( $basket->{total_biblios_cancelled}, 2, 'Both orders deleted, 2 biblios cancelled' ); -Koha::Acquisition::Baskets->find( $basketno )->close; -$baskets = C4::Acquisition::GetBasketsInfosByBookseller( $supplierid ); +Koha::Acquisition::Baskets->find($basketno)->close; +$baskets = C4::Acquisition::GetBasketsInfosByBookseller($supplierid); is( scalar(@$baskets), 0, 'Basket is closed, 0 basket opened' ); $baskets = C4::Acquisition::GetBasketsInfosByBookseller( $supplierid, 1 ); -is( scalar(@$baskets), 1, 'Basket is closed, test allbasket parameter'); +is( scalar(@$baskets), 1, 'Basket is closed, test allbasket parameter' ); -C4::Acquisition::ReopenBasket( $basketno ); +C4::Acquisition::ReopenBasket($basketno); my $order3 = Koha::Acquisition::Order->new( { - basketno => $basketno, - quantity => 4, + basketno => $basketno, + quantity => 4, biblionumber => $biblionumber3, - budget_id => $budget->{budget_id}, + budget_id => $budget->{budget_id}, } )->store; my $ordernumber3 = $order3->ordernumber; -Koha::Acquisition::Baskets->find( $basketno )->close; -$baskets = C4::Acquisition::GetBasketsInfosByBookseller( $supplierid ); +Koha::Acquisition::Baskets->find($basketno)->close; +$baskets = C4::Acquisition::GetBasketsInfosByBookseller($supplierid); is( scalar(@$baskets), 1, 'Basket is closed and has items to receive' ); $basket = $baskets->[0]; -is( $basket->{total_items}, 10, '2 orders deleted, 1 order pending, 10 items total' ); -is( $basket->{total_biblios}, 3, '2 orders deleted, 1 order pending, 3 biblios total' ); -is( $basket->{total_items_cancelled}, 6, '2 orders deleted, 1 order pending, still 6 items cancelled' ); -is( $basket->{expected_items}, 4, '2 orders delete, 1 order pending, 4 items are expected' ); -is( $basket->{total_biblios_cancelled}, 2, '2 orders deleted, 1 order pending, still 2 biblios cancelled' ); +is( $basket->{total_items}, 10, '2 orders deleted, 1 order pending, 10 items total' ); +is( $basket->{total_biblios}, 3, '2 orders deleted, 1 order pending, 3 biblios total' ); +is( $basket->{total_items_cancelled}, 6, '2 orders deleted, 1 order pending, still 6 items cancelled' ); +is( $basket->{expected_items}, 4, '2 orders delete, 1 order pending, 4 items are expected' ); +is( $basket->{total_biblios_cancelled}, 2, '2 orders deleted, 1 order pending, still 2 biblios cancelled' ); -my $invoiceid1 = C4::Acquisition::AddInvoice(invoicenumber => 'invoice1', booksellerid => $supplierid, unknown => "unknown"); -my $invoice1 = C4::Acquisition::GetInvoice( $invoiceid1 ); +my $invoiceid1 = + C4::Acquisition::AddInvoice( invoicenumber => 'invoice1', booksellerid => $supplierid, unknown => "unknown" ); +my $invoice1 = C4::Acquisition::GetInvoice($invoiceid1); my ( $date_received, $ordernumber4 ) = C4::Acquisition::ModReceiveOrder( { - biblionumber => $biblionumber3, - order => $order3->unblessed, - quantityreceived => 2, - budget_id => $budget->{budget_id}, - invoice => $invoice1, + biblionumber => $biblionumber3, + order => $order3->unblessed, + quantityreceived => 2, + budget_id => $budget->{budget_id}, + invoice => $invoice1, } ); -$baskets = C4::Acquisition::GetBasketsInfosByBookseller( $supplierid ); +$baskets = C4::Acquisition::GetBasketsInfosByBookseller($supplierid); is( scalar(@$baskets), 1, 'Basket is closed and still has items to receive' ); $basket = $baskets->[0]; -is( $basket->{total_items}, 10, '2 orders deleted, 1 order pending, 10 items total' ); -is( $basket->{total_biblios}, 3, '2 orders deleted, 1 order pending, 3 biblios total' ); -is( $basket->{total_items_cancelled}, 6, '2 orders deleted, 1 order pending, still 6 items cancelled' ); -is( $basket->{expected_items}, 2, '2 orders delete, 1 order pending, 2 items are expected' ); -is( $basket->{total_biblios_cancelled}, 2, '2 orders deleted, 1 order pending, still 2 biblios cancelled' ); +is( $basket->{total_items}, 10, '2 orders deleted, 1 order pending, 10 items total' ); +is( $basket->{total_biblios}, 3, '2 orders deleted, 1 order pending, 3 biblios total' ); +is( $basket->{total_items_cancelled}, 6, '2 orders deleted, 1 order pending, still 6 items cancelled' ); +is( $basket->{expected_items}, 2, '2 orders delete, 1 order pending, 2 items are expected' ); +is( $basket->{total_biblios_cancelled}, 2, '2 orders deleted, 1 order pending, still 2 biblios cancelled' ); -my $invoiceid2 = C4::Acquisition::AddInvoice(invoicenumber => 'invoice1', booksellerid => $supplierid, unknown => "unknown"); -my $invoice2 = C4::Acquisition::GetInvoice( $invoiceid2 ); +my $invoiceid2 = + C4::Acquisition::AddInvoice( invoicenumber => 'invoice1', booksellerid => $supplierid, unknown => "unknown" ); +my $invoice2 = C4::Acquisition::GetInvoice($invoiceid2); my ( $date_received2, $ordernumber5 ) = C4::Acquisition::ModReceiveOrder( { - biblionumber => $biblionumber3, - order => $order3->get_from_storage->unblessed, - quantityreceived => 2, - budget_id => $budget->{budget_id}, - invoice => $invoice2, + biblionumber => $biblionumber3, + order => $order3->get_from_storage->unblessed, + quantityreceived => 2, + budget_id => $budget->{budget_id}, + invoice => $invoice2, } ); $baskets = C4::Acquisition::GetBasketsInfosByBookseller( $supplierid, 1 ); -is( scalar(@$baskets), 1, 'Basket is closed and has no items to receive, test allbasket parameter'); +is( scalar(@$baskets), 1, 'Basket is closed and has no items to receive, test allbasket parameter' ); $basket = $baskets->[0]; -is( $basket->{total_items}, 10, 'Basket is closed and has no items to receive, still 10 items total' ); -is( $basket->{total_biblios}, 3, 'Basket is closed and has no items to receive, still 3 biblios total' ); -is( $basket->{total_items_cancelled}, 6, 'Basket is closed and has no items to receive, still 6 items cancelled' ); -is( $basket->{expected_items}, 0, 'Basket is closed and has no items to receive, 0 items are expected' ); -is( $basket->{total_biblios_cancelled}, 2, 'Basket is closed and has no items to receive, still 2 biblios cancelled' ); +is( $basket->{total_items}, 10, 'Basket is closed and has no items to receive, still 10 items total' ); +is( $basket->{total_biblios}, 3, 'Basket is closed and has no items to receive, still 3 biblios total' ); +is( $basket->{total_items_cancelled}, 6, 'Basket is closed and has no items to receive, still 6 items cancelled' ); +is( $basket->{expected_items}, 0, 'Basket is closed and has no items to receive, 0 items are expected' ); +is( $basket->{total_biblios_cancelled}, 2, 'Basket is closed and has no items to receive, still 2 biblios cancelled' ); -$baskets = C4::Acquisition::GetBasketsInfosByBookseller( $supplierid ); +$baskets = C4::Acquisition::GetBasketsInfosByBookseller($supplierid); is( scalar(@$baskets), 0, 'Basket is closed and has no items to receive' ); $schema->storage->txn_rollback(); diff --git a/t/db_dependent/Acquisition/GetOrdersByBiblionumber.t b/t/db_dependent/Acquisition/GetOrdersByBiblionumber.t index b16c307d27..56803ce889 100755 --- a/t/db_dependent/Acquisition/GetOrdersByBiblionumber.t +++ b/t/db_dependent/Acquisition/GetOrdersByBiblionumber.t @@ -4,8 +4,8 @@ use Modern::Perl; use Test::More; use C4::Acquisition qw( NewBasket GetOrders GetOrdersByBiblionumber GetOrder ); -use C4::Biblio qw( AddBiblio ); -use C4::Budgets qw( AddBudget GetBudget ); +use C4::Biblio qw( AddBiblio ); +use C4::Budgets qw( AddBudget GetBudget ); use Koha::Database; use Koha::Acquisition::Orders; @@ -17,16 +17,14 @@ $schema->storage->txn_begin(); my $bookseller = Koha::Acquisition::Bookseller->new( { - name => "my vendor", + name => "my vendor", address1 => "bookseller's address", - phone => "0123456", - active => 1 + phone => "0123456", + active => 1 } )->store; -my $basketno = C4::Acquisition::NewBasket( - $bookseller->id -); +my $basketno = C4::Acquisition::NewBasket( $bookseller->id ); my $budget_period_id = C4::Budgets::AddBudgetPeriod( { @@ -45,48 +43,48 @@ my $budgetid = C4::Budgets::AddBudget( } ); -my $budget = C4::Budgets::GetBudget( $budgetid ); +my $budget = C4::Budgets::GetBudget($budgetid); -my ($biblionumber1, $biblioitemnumber1) = AddBiblio(MARC::Record->new, ''); -my ($biblionumber2, $biblioitemnumber2) = AddBiblio(MARC::Record->new, ''); +my ( $biblionumber1, $biblioitemnumber1 ) = AddBiblio( MARC::Record->new, '' ); +my ( $biblionumber2, $biblioitemnumber2 ) = AddBiblio( MARC::Record->new, '' ); my $order1 = Koha::Acquisition::Order->new( { - basketno => $basketno, - quantity => 24, + basketno => $basketno, + quantity => 24, biblionumber => $biblionumber1, - budget_id => $budget->{budget_id}, + budget_id => $budget->{budget_id}, } )->store; my $ordernumber1 = $order1->ordernumber; my $order2 = Koha::Acquisition::Order->new( { - basketno => $basketno, - quantity => 42, + basketno => $basketno, + quantity => 42, biblionumber => $biblionumber2, - budget_id => $budget->{budget_id}, + budget_id => $budget->{budget_id}, } )->store; my $ordernumber2 = $order2->ordernumber; my $order3 = Koha::Acquisition::Order->new( { - basketno => $basketno, - quantity => 4, + basketno => $basketno, + quantity => 4, biblionumber => $biblionumber2, - budget_id => $budget->{budget_id}, + budget_id => $budget->{budget_id}, } )->store; my $ordernumber3 = $order3->ordernumber; my @orders = GetOrdersByBiblionumber(); -is(scalar(@orders), 0, 'GetOrdersByBiblionumber : no argument, return undef'); +is( scalar(@orders), 0, 'GetOrdersByBiblionumber : no argument, return undef' ); -@orders = GetOrdersByBiblionumber( $biblionumber1 ); -is(scalar(@orders), 1, '1 order on biblionumber 1'); +@orders = GetOrdersByBiblionumber($biblionumber1); +is( scalar(@orders), 1, '1 order on biblionumber 1' ); -@orders = GetOrdersByBiblionumber( $biblionumber2 ); -is(scalar(@orders), 2, '2 orders on biblionumber 2'); +@orders = GetOrdersByBiblionumber($biblionumber2); +is( scalar(@orders), 2, '2 orders on biblionumber 2' ); #End transaction $schema->storage->txn_rollback(); diff --git a/t/db_dependent/Acquisition/Invoices.t b/t/db_dependent/Acquisition/Invoices.t index 337bd94883..c82e168202 100755 --- a/t/db_dependent/Acquisition/Invoices.t +++ b/t/db_dependent/Acquisition/Invoices.t @@ -11,7 +11,10 @@ use Koha::Database; use Test::More tests => 29; BEGIN { - use_ok('C4::Acquisition', qw( NewBasket GetBasket AddInvoice GetInvoice ModReceiveOrder GetInvoiceDetails GetInvoices ModInvoice CloseInvoice ReopenInvoice MergeInvoices DelInvoice )); + use_ok( + 'C4::Acquisition', + qw( NewBasket GetBasket AddInvoice GetInvoice ModReceiveOrder GetInvoiceDetails GetInvoices ModInvoice CloseInvoice ReopenInvoice MergeInvoices DelInvoice ) + ); } my $schema = Koha::Database->new()->schema(); @@ -22,17 +25,17 @@ $dbh->do(q{DELETE FROM aqinvoices}); my $bookseller = Koha::Acquisition::Bookseller->new( { - name => "my vendor", + name => "my vendor", address1 => "bookseller's address", - phone => "0123456", - active => 1 + phone => "0123456", + active => 1 } )->store; my $booksellerid = $bookseller->id; -my $booksellerinfo = Koha::Acquisition::Booksellers->find( $booksellerid ); -my $basketno = NewBasket($booksellerid, 1); -my $basket = GetBasket($basketno); +my $booksellerinfo = Koha::Acquisition::Booksellers->find($booksellerid); +my $basketno = NewBasket( $booksellerid, 1 ); +my $basket = GetBasket($basketno); my $budget_period_id = C4::Budgets::AddBudgetPeriod( { @@ -50,55 +53,56 @@ my $budgetid = C4::Budgets::AddBudget( budget_period_id => $budget_period_id, } ); -my $budget = C4::Budgets::GetBudget( $budgetid ); +my $budget = C4::Budgets::GetBudget($budgetid); my $bibrec1 = MARC::Record->new(); $bibrec1->append_fields( - MARC::Field->new('020', '', '', 'a' => '1234567890'), - MARC::Field->new('100', '', '', 'a' => 'Shakespeare, Billy'), - MARC::Field->new('245', '', '', 'a' => 'Bug 8854'), - MARC::Field->new('260', '', '', 'b' => 'Scholastic Publishing', c => 'c2012'), + MARC::Field->new( '020', '', '', 'a' => '1234567890' ), + MARC::Field->new( '100', '', '', 'a' => 'Shakespeare, Billy' ), + MARC::Field->new( '245', '', '', 'a' => 'Bug 8854' ), + MARC::Field->new( '260', '', '', 'b' => 'Scholastic Publishing', c => 'c2012' ), ); -my ($biblionumber1, $biblioitemnumber1) = AddBiblio($bibrec1, ''); -my ($biblionumber2, $biblioitemnumber2) = AddBiblio(MARC::Record->new, ''); -my ($biblionumber3, $biblioitemnumber3) = AddBiblio(MARC::Record->new, ''); +my ( $biblionumber1, $biblioitemnumber1 ) = AddBiblio( $bibrec1, '' ); +my ( $biblionumber2, $biblioitemnumber2 ) = AddBiblio( MARC::Record->new, '' ); +my ( $biblionumber3, $biblioitemnumber3 ) = AddBiblio( MARC::Record->new, '' ); my $order1 = Koha::Acquisition::Order->new( { - basketno => $basketno, - quantity => 2, + basketno => $basketno, + quantity => 2, biblionumber => $biblionumber1, - budget_id => $budget->{budget_id}, + budget_id => $budget->{budget_id}, } )->store; my $ordernumber1 = $order1->ordernumber; my $order2 = Koha::Acquisition::Order->new( { - basketno => $basketno, - quantity => 1, + basketno => $basketno, + quantity => 1, biblionumber => $biblionumber2, - budget_id => $budget->{budget_id}, + budget_id => $budget->{budget_id}, } )->store; my $ordernumber2 = $order2->ordernumber; my $order3 = Koha::Acquisition::Order->new( { - basketno => $basketno, - quantity => 1, + basketno => $basketno, + quantity => 1, biblionumber => $biblionumber3, - budget_id => $budget->{budget_id}, - ecost => 42, - rrp => 42, + budget_id => $budget->{budget_id}, + ecost => 42, + rrp => 42, } )->store; my $ordernumber3 = $order3->ordernumber; -my $invoiceid1 = AddInvoice(invoicenumber => 'invoice1', booksellerid => $booksellerid, unknown => "unknown"); -my $invoiceid2 = AddInvoice(invoicenumber => 'invoice2', booksellerid => $booksellerid, unknown => "unknown", - shipmentdate => '2012-12-24', - ); +my $invoiceid1 = AddInvoice( invoicenumber => 'invoice1', booksellerid => $booksellerid, unknown => "unknown" ); +my $invoiceid2 = AddInvoice( + invoicenumber => 'invoice2', booksellerid => $booksellerid, unknown => "unknown", + shipmentdate => '2012-12-24', +); my $invoiceid_closed = AddInvoice( invoicenumber => 'invoice_close', booksellerid => $booksellerid, @@ -107,8 +111,8 @@ my $invoiceid_closed = AddInvoice( closedate => '2024-12-13', ); -my $invoice1 = GetInvoice( $invoiceid1 ); -my $invoice2 = GetInvoice( $invoiceid2 ); +my $invoice1 = GetInvoice($invoiceid1); +my $invoice2 = GetInvoice($invoiceid2); my ( $datereceived, $new_ordernumber ) = ModReceiveOrder( { @@ -141,33 +145,36 @@ my ( $datereceived, $new_ordernumber ) = ModReceiveOrder( $invoice1 = GetInvoiceDetails($invoiceid1); $invoice2 = GetInvoiceDetails($invoiceid2); -is(scalar @{$invoice1->{'orders'}}, 1, 'Invoice1 has only one order'); -is(scalar @{$invoice2->{'orders'}}, 2, 'Invoice2 has only two orders'); +is( scalar @{ $invoice1->{'orders'} }, 1, 'Invoice1 has only one order' ); +is( scalar @{ $invoice2->{'orders'} }, 2, 'Invoice2 has only two orders' ); my $orders = $invoice1->{orders}; -ok( exists( @$orders[0]->{basketgroupid} ), "GetInvoiceDetails: The basketgroupid key exists" ); +ok( exists( @$orders[0]->{basketgroupid} ), "GetInvoiceDetails: The basketgroupid key exists" ); ok( exists( @$orders[0]->{basketgroupname} ), "GetInvoiceDetails: The basketgroupname key exists" ); my @invoices = GetInvoices(); -cmp_ok(scalar @invoices, '>=', 2, 'GetInvoices returns at least two invoices'); +cmp_ok( scalar @invoices, '>=', 2, 'GetInvoices returns at least two invoices' ); -@invoices = GetInvoices(invoicenumber => 'invoice2'); -cmp_ok(scalar @invoices, '>=', 1, 'GetInvoices returns at least one invoice when a specific invoice is requested'); +@invoices = GetInvoices( invoicenumber => 'invoice2' ); +cmp_ok( scalar @invoices, '>=', 1, 'GetInvoices returns at least one invoice when a specific invoice is requested' ); -@invoices = GetInvoices(shipmentdateto => '2012-12-24', shipmentdatefrom => '2012-12-24'); -is($invoices[0]->{invoicenumber}, 'invoice2', 'GetInvoices() to search by shipmentdate works (bug 8854)'); -@invoices = GetInvoices(title => 'Bug'); -is($invoices[0]->{invoicenumber}, 'invoice1', 'GetInvoices() to search by title works (bug 8854)'); -@invoices = GetInvoices(author => 'Billy'); -is($invoices[0]->{invoicenumber}, 'invoice1', 'GetInvoices() to search by author works (bug 8854)'); -@invoices = GetInvoices(publisher => 'Scholastic'); -is($invoices[0]->{invoicenumber}, 'invoice1', 'GetInvoices() to search by publisher works (bug 8854)'); -@invoices = GetInvoices(publicationyear => '2012'); -is($invoices[0]->{invoicenumber}, 'invoice1', 'GetInvoices() to search by publication/copyright year works (bug 8854)'); -@invoices = GetInvoices(isbneanissn => '1234567890'); -is($invoices[0]->{invoicenumber}, 'invoice1', 'GetInvoices() to search by ISBN works (bug 8854)'); -@invoices = GetInvoices(isbneanissn => '123456789'); -is($invoices[0]->{invoicenumber}, 'invoice1', 'GetInvoices() to search by partial ISBN works (bug 8854)'); +@invoices = GetInvoices( shipmentdateto => '2012-12-24', shipmentdatefrom => '2012-12-24' ); +is( $invoices[0]->{invoicenumber}, 'invoice2', 'GetInvoices() to search by shipmentdate works (bug 8854)' ); +@invoices = GetInvoices( title => 'Bug' ); +is( $invoices[0]->{invoicenumber}, 'invoice1', 'GetInvoices() to search by title works (bug 8854)' ); +@invoices = GetInvoices( author => 'Billy' ); +is( $invoices[0]->{invoicenumber}, 'invoice1', 'GetInvoices() to search by author works (bug 8854)' ); +@invoices = GetInvoices( publisher => 'Scholastic' ); +is( $invoices[0]->{invoicenumber}, 'invoice1', 'GetInvoices() to search by publisher works (bug 8854)' ); +@invoices = GetInvoices( publicationyear => '2012' ); +is( + $invoices[0]->{invoicenumber}, 'invoice1', + 'GetInvoices() to search by publication/copyright year works (bug 8854)' +); +@invoices = GetInvoices( isbneanissn => '1234567890' ); +is( $invoices[0]->{invoicenumber}, 'invoice1', 'GetInvoices() to search by ISBN works (bug 8854)' ); +@invoices = GetInvoices( isbneanissn => '123456789' ); +is( $invoices[0]->{invoicenumber}, 'invoice1', 'GetInvoices() to search by partial ISBN works (bug 8854)' ); @invoices = GetInvoices( booksellerid => $booksellerid, closedate => undef ); is( scalar @invoices, 2, 'GetInvoices() to search by only open invoices' ); @@ -179,40 +186,41 @@ is( scalar @invoices, 1, 'GetInvoices() to filter by is( $invoices[0]->{invoicenumber}, 'invoice_close', 'GetInvoices() to filter by closedate' ); my $invoicesummary1 = GetInvoice($invoiceid1); -is($invoicesummary1->{'invoicenumber'}, 'invoice1', 'GetInvoice retrieves correct invoice'); -is($invoicesummary1->{'invoicenumber'}, $invoice1->{'invoicenumber'}, 'GetInvoice and GetInvoiceDetails retrieve same information'); +is( $invoicesummary1->{'invoicenumber'}, 'invoice1', 'GetInvoice retrieves correct invoice' ); +is( + $invoicesummary1->{'invoicenumber'}, $invoice1->{'invoicenumber'}, + 'GetInvoice and GetInvoiceDetails retrieve same information' +); -ModInvoice(invoiceid => $invoiceid1, invoicenumber => 'invoice11'); +ModInvoice( invoiceid => $invoiceid1, invoicenumber => 'invoice11' ); $invoice1 = GetInvoiceDetails($invoiceid1); -is($invoice1->{'invoicenumber'}, 'invoice11', 'ModInvoice changed invoice number'); +is( $invoice1->{'invoicenumber'}, 'invoice11', 'ModInvoice changed invoice number' ); -is($invoice1->{'closedate'}, undef, 'Invoice is not closed before CloseInvoice call'); +is( $invoice1->{'closedate'}, undef, 'Invoice is not closed before CloseInvoice call' ); CloseInvoice($invoiceid1); $invoice1 = GetInvoiceDetails($invoiceid1); -isnt($invoice1->{'closedate'}, undef, 'Invoice is closed after CloseInvoice call'); +isnt( $invoice1->{'closedate'}, undef, 'Invoice is closed after CloseInvoice call' ); ReopenInvoice($invoiceid1); $invoice1 = GetInvoiceDetails($invoiceid1); -is($invoice1->{'closedate'}, undef, 'Invoice is open after ReopenInvoice call'); +is( $invoice1->{'closedate'}, undef, 'Invoice is open after ReopenInvoice call' ); - -MergeInvoices($invoiceid1, [ $invoiceid2 ]); +MergeInvoices( $invoiceid1, [$invoiceid2] ); my $mergedinvoice = GetInvoiceDetails($invoiceid1); -is(scalar @{$mergedinvoice->{'orders'}}, 3, 'Merged invoice has three orders'); +is( scalar @{ $mergedinvoice->{'orders'} }, 3, 'Merged invoice has three orders' ); -my $invoiceid3 = AddInvoice(invoicenumber => 'invoice3', booksellerid => $booksellerid, unknown => "unknown"); +my $invoiceid3 = AddInvoice( invoicenumber => 'invoice3', booksellerid => $booksellerid, unknown => "unknown" ); my $invoicecount = GetInvoices(); DelInvoice($invoiceid3); @invoices = GetInvoices(); -is(scalar @invoices, $invoicecount - 1, 'DelInvoice deletes invoice'); -is(GetInvoice($invoiceid3), undef, 'DelInvoice deleted correct invoice'); +is( scalar @invoices, $invoicecount - 1, 'DelInvoice deletes invoice' ); +is( GetInvoice($invoiceid3), undef, 'DelInvoice deleted correct invoice' ); -my @invoices_linked_to_subscriptions = map{ - $_->{is_linked_to_subscriptions} - ? $_ - : () -} @invoices; -is_deeply( \@invoices_linked_to_subscriptions, [], "GetInvoices return linked_to_subscriptions: there is no invoices linked to subscriptions yet" ); +my @invoices_linked_to_subscriptions = map { $_->{is_linked_to_subscriptions} ? $_ : () } @invoices; +is_deeply( + \@invoices_linked_to_subscriptions, [], + "GetInvoices return linked_to_subscriptions: there is no invoices linked to subscriptions yet" +); END { $dbh and $schema->storage->txn_rollback(); diff --git a/t/db_dependent/Acquisition/NewOrder.t b/t/db_dependent/Acquisition/NewOrder.t index d853cb1f91..ab5f55095d 100755 --- a/t/db_dependent/Acquisition/NewOrder.t +++ b/t/db_dependent/Acquisition/NewOrder.t @@ -4,8 +4,8 @@ use Modern::Perl; use Test::More tests => 8; use C4::Acquisition qw( NewBasket ); -use C4::Biblio qw( AddBiblio ); -use C4::Budgets qw( AddBudget GetBudget ); +use C4::Biblio qw( AddBiblio ); +use C4::Budgets qw( AddBudget GetBudget ); use MARC::Record; use Koha::Database; use Koha::DateUtils qw( dt_from_string output_pref ); @@ -17,22 +17,20 @@ use t::lib::Mocks; my $schema = Koha::Database->new()->schema(); $schema->storage->txn_begin(); -my $builder = t::lib::TestBuilder->new; -my $logged_in_user = $builder->build_object({ class => 'Koha::Patrons' }); -t::lib::Mocks::mock_userenv({ patron => $logged_in_user }); +my $builder = t::lib::TestBuilder->new; +my $logged_in_user = $builder->build_object( { class => 'Koha::Patrons' } ); +t::lib::Mocks::mock_userenv( { patron => $logged_in_user } ); my $bookseller = Koha::Acquisition::Bookseller->new( { - name => "my vendor", + name => "my vendor", address1 => "bookseller's address", - phone => "0123456", - active => 1 + phone => "0123456", + active => 1 } )->store; -my $basketno = C4::Acquisition::NewBasket( - $bookseller->id -); +my $basketno = C4::Acquisition::NewBasket( $bookseller->id ); my $budget_period_id = C4::Budgets::AddBudgetPeriod( { @@ -51,18 +49,17 @@ my $budgetid = C4::Budgets::AddBudget( } ); -my $budget = C4::Budgets::GetBudget( $budgetid ); - -my ($biblionumber1, $biblioitemnumber1) = AddBiblio(MARC::Record->new, ''); -my ($biblionumber2, $biblioitemnumber2) = AddBiblio(MARC::Record->new, ''); +my $budget = C4::Budgets::GetBudget($budgetid); +my ( $biblionumber1, $biblioitemnumber1 ) = AddBiblio( MARC::Record->new, '' ); +my ( $biblionumber2, $biblioitemnumber2 ) = AddBiblio( MARC::Record->new, '' ); # returns undef and croaks if basketno, quantity, biblionumber or budget_id is missing -my $order = eval { Koha::Acquisition::Order->new->store }; +my $order = eval { Koha::Acquisition::Order->new->store }; my $return_error = $@; ok( - ( ! defined $order ) - && ( defined $return_error ), + ( !defined $order ) + && ( defined $return_error ), "Inserting an order with no params returns undef and croaks" ); @@ -76,30 +73,34 @@ my @mandatoryparams_keys = keys %$mandatoryparams; foreach my $mandatoryparams_key (@mandatoryparams_keys) { my %test_missing_mandatoryparams = %$mandatoryparams; delete $test_missing_mandatoryparams{$mandatoryparams_key}; - $order = eval { - Koha::Acquisition::Order->new( \%test_missing_mandatoryparams )->store; - }; + $order = eval { Koha::Acquisition::Order->new( \%test_missing_mandatoryparams )->store; }; $return_error = $@; my $expected_error = "Cannot insert order: Mandatory parameter $mandatoryparams_key is missing"; ok( - ( !( defined $order ) ) - && ( index( $return_error, $expected_error ) >= 0 ), -"Inserting an order with no $mandatoryparams_key returns undef and croaks with expected error message" + ( !( defined $order ) ) + && ( index( $return_error, $expected_error ) >= 0 ), + "Inserting an order with no $mandatoryparams_key returns undef and croaks with expected error message" ); } $order = Koha::Acquisition::Order->new( { - basketno => $basketno, - quantity => 24, + basketno => $basketno, + quantity => 24, biblionumber => $biblionumber1, - budget_id => $budget->{budget_id}, + budget_id => $budget->{budget_id}, } )->store; my $ordernumber = $order->ordernumber; -$order = Koha::Acquisition::Orders->find( $ordernumber ); +$order = Koha::Acquisition::Orders->find($ordernumber); is( $order->quantityreceived, 0, 'Koha::Acquisition::Order->insert set quantityreceivedto 0 if undef is given' ); -is( $order->entrydate, output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 }), 'Koha::Acquisition::Order->store set entrydate to today' ); -is( $order->created_by, $logged_in_user->borrowernumber, 'Koha::Acquisition::Order->store set created_by to logged in user if not given' ); +is( + $order->entrydate, output_pref( { dt => dt_from_string, dateformat => 'iso', dateonly => 1 } ), + 'Koha::Acquisition::Order->store set entrydate to today' +); +is( + $order->created_by, $logged_in_user->borrowernumber, + 'Koha::Acquisition::Order->store set created_by to logged in user if not given' +); $schema->storage->txn_rollback(); diff --git a/t/db_dependent/Acquisition/OrderFromSubscription.t b/t/db_dependent/Acquisition/OrderFromSubscription.t index d9db71c180..d601163b72 100755 --- a/t/db_dependent/Acquisition/OrderFromSubscription.t +++ b/t/db_dependent/Acquisition/OrderFromSubscription.t @@ -4,10 +4,10 @@ use Test::More tests => 12; use t::lib::TestBuilder; -use_ok('C4::Acquisition', qw( NewBasket AddInvoice GetInvoice ModReceiveOrder GetInvoices )); -use_ok('C4::Biblio', qw( AddBiblio )); -use_ok('C4::Budgets', qw( AddBudgetPeriod AddBudget )); -use_ok('C4::Serials', qw( NewSubscription GetSubscription subscriptionCurrentlyOnOrder )); +use_ok( 'C4::Acquisition', qw( NewBasket AddInvoice GetInvoice ModReceiveOrder GetInvoices ) ); +use_ok( 'C4::Biblio', qw( AddBiblio ) ); +use_ok( 'C4::Budgets', qw( AddBudgetPeriod AddBudget ) ); +use_ok( 'C4::Serials', qw( NewSubscription GetSubscription subscriptionCurrentlyOnOrder ) ); use Koha::Acquisition::Orders; use Koha::Database; @@ -16,76 +16,84 @@ use Koha::Database; my $schema = Koha::Database->new()->schema(); $schema->storage->txn_begin(); my $builder = t::lib::TestBuilder->new; -my $dbh = C4::Context->dbh; +my $dbh = C4::Context->dbh; -my $curcode = $builder->build({ source => 'Currency' })->{currencycode}; +my $curcode = $builder->build( { source => 'Currency' } )->{currencycode}; my $bookseller = Koha::Acquisition::Bookseller->new( { - name => "my vendor", + name => "my vendor", address1 => "bookseller's address", - phone => "0123456", - active => 1 + phone => "0123456", + active => 1 } )->store; -my ($biblionumber, $biblioitemnumber) = AddBiblio(MARC::Record->new, ''); -my $bpid = AddBudgetPeriod({ - budget_period_startdate => '2015-01-01', - budget_period_enddate => '2015-12-31', - budget_period_description => "budget desc" -}); +my ( $biblionumber, $biblioitemnumber ) = AddBiblio( MARC::Record->new, '' ); +my $bpid = AddBudgetPeriod( + { + budget_period_startdate => '2015-01-01', + budget_period_enddate => '2015-12-31', + budget_period_description => "budget desc" + } +); -my $budget_id = AddBudget({ - budget_code => "ABCD", - budget_amount => "123.132", - budget_name => "Périodiques", - budget_notes => "This is a note", - budget_period_id => $bpid -}); +my $budget_id = AddBudget( + { + budget_code => "ABCD", + budget_amount => "123.132", + budget_name => "Périodiques", + budget_notes => "This is a note", + budget_period_id => $bpid + } +); my $subscriptionid = NewSubscription( - undef, "", undef, undef, $budget_id, $biblionumber, - '2013-01-01',undef, undef, undef, undef, - undef, undef, undef, undef, undef, undef, - 1, "notes",undef, '2013-01-01', undef, undef, - undef, undef, 0, "intnotes", 0, - undef, undef, 0, undef, '2013-12-31', 0 + undef, "", undef, undef, $budget_id, $biblionumber, + '2013-01-01', undef, undef, undef, undef, + undef, undef, undef, undef, undef, undef, + 1, "notes", undef, '2013-01-01', undef, undef, + undef, undef, 0, "intnotes", 0, + undef, undef, 0, undef, '2013-12-31', 0 ); die unless $subscriptionid; my $basketno; -ok($basketno = NewBasket($bookseller->id, 1), "NewBasket( " . $bookseller->id . ", 1 ) returns $basketno"); +ok( $basketno = NewBasket( $bookseller->id, 1 ), "NewBasket( " . $bookseller->id . ", 1 ) returns $basketno" ); -my $cost = 42.00; -my $subscription = GetSubscription( $subscriptionid ); +my $cost = 42.00; +my $subscription = GetSubscription($subscriptionid); -my $order = Koha::Acquisition::Order->new({ - biblionumber => $subscription->{biblionumber}, - entrydate => '2013-01-01', - quantity => 1, - currency => $curcode, - listprice => $cost, - basketno => $basketno, - rrp => $cost, - ecost => $cost, - orderstatus => 'new', - subscriptionid => $subscription->{subscriptionid}, - budget_id => $budget_id, -})->store; +my $order = Koha::Acquisition::Order->new( + { + biblionumber => $subscription->{biblionumber}, + entrydate => '2013-01-01', + quantity => 1, + currency => $curcode, + listprice => $cost, + basketno => $basketno, + rrp => $cost, + ecost => $cost, + orderstatus => 'new', + subscriptionid => $subscription->{subscriptionid}, + budget_id => $budget_id, + } +)->store; my $ordernumber = $order->ordernumber; my $is_currently_on_order = subscriptionCurrentlyOnOrder( $subscription->{subscriptionid} ); -is ( $is_currently_on_order, 1, "The subscription is currently on order"); +is( $is_currently_on_order, 1, "The subscription is currently on order" ); -$order = Koha::Acquisition::Orders->search({ subscriptionid => $subscription->{subscriptionid}, datereceived => undef })->next->unblessed; -is ( $order->{subscriptionid}, $subscription->{subscriptionid}, "test subscriptionid for the last order not received"); -ok( $order->{ecost} == $cost, "test cost for the last order not received"); +$order = + Koha::Acquisition::Orders->search( { subscriptionid => $subscription->{subscriptionid}, datereceived => undef } ) + ->next->unblessed; +is( $order->{subscriptionid}, $subscription->{subscriptionid}, "test subscriptionid for the last order not received" ); +ok( $order->{ecost} == $cost, "test cost for the last order not received" ); $dbh->do(q{DELETE FROM aqinvoices}); -my $invoiceid = AddInvoice(invoicenumber => 'invoice1', booksellerid => $bookseller->id, unknown => "unknown"); +my $invoiceid = AddInvoice( invoicenumber => 'invoice1', booksellerid => $bookseller->id, unknown => "unknown" ); -my $invoice = GetInvoice( $invoiceid ); +my $invoice = GetInvoice($invoiceid); $invoice->{datereceived} = '2013-01-02'; my ( $datereceived, $new_ordernumber ) = ModReceiveOrder( @@ -103,20 +111,22 @@ $order = Koha::Acquisition::Orders->search( subscriptionid => $subscriptionid, datereceived => { '!=' => undef } }, - { - order_by => [ { -desc => 'datereceived' }, { -desc => 'ordernumber' } ] - } + { order_by => [ { -desc => 'datereceived' }, { -desc => 'ordernumber' } ] } )->next->unblessed; -is ( $order->{subscriptionid}, $subscription->{subscriptionid}, "test subscriptionid for the last order received"); -ok( $order->{ecost} == $cost, "test cost for the last order received"); +is( $order->{subscriptionid}, $subscription->{subscriptionid}, "test subscriptionid for the last order received" ); +ok( $order->{ecost} == $cost, "test cost for the last order received" ); -$order = Koha::Acquisition::Orders->search({ subscriptionid => $subscription->{subscriptionid}, datereceived => undef }); -is ( $order->count, 0, "test no not received order for a received order"); +$order = + Koha::Acquisition::Orders->search( { subscriptionid => $subscription->{subscriptionid}, datereceived => undef } ); +is( $order->count, 0, "test no not received order for a received order" ); -my @invoices = GetInvoices(); +my @invoices = GetInvoices(); my @invoices_linked_to_subscriptions = grep { $_->{is_linked_to_subscriptions} } @invoices; -is(scalar(@invoices_linked_to_subscriptions), 1, 'GetInvoices() can identify invoices that are linked to a subscription'); +is( + scalar(@invoices_linked_to_subscriptions), 1, + 'GetInvoices() can identify invoices that are linked to a subscription' +); # Cleanup $schema->storage->txn_rollback(); diff --git a/t/db_dependent/Acquisition/OrderUsers.t b/t/db_dependent/Acquisition/OrderUsers.t index 540be8460d..cd408003cf 100755 --- a/t/db_dependent/Acquisition/OrderUsers.t +++ b/t/db_dependent/Acquisition/OrderUsers.t @@ -2,8 +2,8 @@ use Modern::Perl; use Test::More tests => 3; use C4::Acquisition qw( NewBasket AddInvoice ModOrder ModOrderUsers GetOrder GetOrderUsers ModReceiveOrder ); -use C4::Biblio qw( AddBiblio ); -use C4::Letters qw( GetQueuedMessages ); +use C4::Biblio qw( AddBiblio ); +use C4::Letters qw( GetQueuedMessages ); use Koha::Database; use Koha::Acquisition::Booksellers; use Koha::Acquisition::Orders; @@ -15,19 +15,21 @@ my $schema = Koha::Database->schema; $schema->storage->txn_begin; my $builder = t::lib::TestBuilder->new; -my $library = $builder->build({ - source => "Branch", -}); -my $patron_category = $builder->build({ source => 'Category' }); -my $currency = $builder->build({ source => 'Currency' }); +my $library = $builder->build( + { + source => "Branch", + } +); +my $patron_category = $builder->build( { source => 'Category' } ); +my $currency = $builder->build( { source => 'Currency' } ); # Creating some orders my $bookseller = Koha::Acquisition::Bookseller->new( { - name => "my vendor", - address1 => "bookseller's address", - phone => "0123456", - active => 1, + name => "my vendor", + address1 => "bookseller's address", + phone => "0123456", + active => 1, } )->store; @@ -75,52 +77,57 @@ my $invoiceid = AddInvoice( unknown => "unknown" ); -my $borrowernumber = Koha::Patron->new({ - cardnumber => 'TESTCARD', - firstname => 'TESTFN', - surname => 'TESTSN', - categorycode => $patron_category->{categorycode}, - branchcode => $library->{branchcode}, - dateofbirth => '', - dateexpiry => '9999-12-31', - userid => 'TESTUSERID' -})->store->borrowernumber; +my $borrowernumber = Koha::Patron->new( + { + cardnumber => 'TESTCARD', + firstname => 'TESTFN', + surname => 'TESTSN', + categorycode => $patron_category->{categorycode}, + branchcode => $library->{branchcode}, + dateofbirth => '', + dateexpiry => '9999-12-31', + userid => 'TESTUSERID' + } +)->store->borrowernumber; C4::Acquisition::ModOrderUsers( $ordernumber, $borrowernumber ); -my $is_added = grep { /^$borrowernumber$/ } C4::Acquisition::GetOrderUsers( $ordernumber ); +my $is_added = grep { /^$borrowernumber$/ } C4::Acquisition::GetOrderUsers($ordernumber); is( $is_added, 1, 'ModOrderUsers should link patrons to an order' ); -$order = Koha::Acquisition::Orders->find( $ordernumber ); +$order = Koha::Acquisition::Orders->find($ordernumber); ModReceiveOrder( { - biblionumber => $biblionumber, - order => $order->unblessed, - quantityreceived => 1, - cost => 10, - ecost => 10, - invoiceid => $invoiceid, - rrp => 10, - budget_id => $budgetid, + biblionumber => $biblionumber, + order => $order->unblessed, + quantityreceived => 1, + cost => 10, + ecost => 10, + invoiceid => $invoiceid, + rrp => 10, + budget_id => $budgetid, } ); -my $messages = C4::Letters::GetQueuedMessages({ borrowernumber => $borrowernumber }); -is( scalar( @$messages ), 0, 'The letter has not been sent to message queue on receiving the order, the order is not entire received'); +my $messages = C4::Letters::GetQueuedMessages( { borrowernumber => $borrowernumber } ); +is( + scalar(@$messages), 0, + 'The letter has not been sent to message queue on receiving the order, the order is not entire received' +); -$order = Koha::Acquisition::Orders->find( $ordernumber ); +$order = Koha::Acquisition::Orders->find($ordernumber); ModReceiveOrder( { - biblionumber => $biblionumber, - order => $order->unblessed, - quantityreceived => 1, - cost => 10, - ecost => 10, - invoiceid => $invoiceid, - rrp => 10, - budget_id => $budgetid, + biblionumber => $biblionumber, + order => $order->unblessed, + quantityreceived => 1, + cost => 10, + ecost => 10, + invoiceid => $invoiceid, + rrp => 10, + budget_id => $budgetid, } ); -$messages = C4::Letters::GetQueuedMessages({ borrowernumber => $borrowernumber }); -is( scalar( @$messages ), 1, 'The letter has been sent to message queue on receiving the order'); +$messages = C4::Letters::GetQueuedMessages( { borrowernumber => $borrowernumber } ); +is( scalar(@$messages), 1, 'The letter has been sent to message queue on receiving the order' ); diff --git a/t/db_dependent/Acquisition/StandingOrders.t b/t/db_dependent/Acquisition/StandingOrders.t index ecf7cd1e5c..48ab35a611 100755 --- a/t/db_dependent/Acquisition/StandingOrders.t +++ b/t/db_dependent/Acquisition/StandingOrders.t @@ -5,7 +5,7 @@ use Modern::Perl; use Test::More tests => 14; use C4::Context; use C4::Acquisition qw( NewBasket GetBasket SearchOrders AddInvoice ModReceiveOrder CancelReceipt ); -use C4::Biblio qw( AddBiblio ); +use C4::Biblio qw( AddBiblio ); use C4::Items; use C4::Budgets; use Koha::Acquisition::Orders; @@ -18,36 +18,36 @@ my $builder = t::lib::TestBuilder->new; # Set up configuration data -my $branch = $builder->build( { source => 'Branch' } ); -my $bookseller = $builder->build( { source => 'Aqbookseller' } ); -my $budget = $builder->build( { source => 'Aqbudget' } ); +my $branch = $builder->build( { source => 'Branch' } ); +my $bookseller = $builder->build( { source => 'Aqbookseller' } ); +my $budget = $builder->build( { source => 'Aqbudget' } ); my $staffmember = $builder->build( { source => 'Borrower' } ); -my $curcode = $builder->build( { source => 'Currency' })->{currencycode}; +my $curcode = $builder->build( { source => 'Currency' } )->{currencycode}; # Create baskets and orders my $basketno = NewBasket( $bookseller->{id}, $staffmember->{borrowernumber}, - 'Standing order basket', # basketname - '', # basketnote - '', # basketbooksellernote - undef, # basketcontractnumber - $branch->{branchcode}, # deliveryplace - $branch->{branchcode}, # billingplace - 1 # is_standing + 'Standing order basket', # basketname + '', # basketnote + '', # basketbooksellernote + undef, # basketcontractnumber + $branch->{branchcode}, # deliveryplace + $branch->{branchcode}, # billingplace + 1 # is_standing ); my $nonstandingbasketno = NewBasket( $bookseller->{id}, $staffmember->{borrowernumber}, - 'Non-standing order basket', # basketname - '', # basketnote - '', # basketbooksellernote - undef, # basketcontractnumber - $branch->{branchcode}, # deliveryplace - $branch->{branchcode}, # billingplace - 0 # is_standing + 'Non-standing order basket', # basketname + '', # basketnote + '', # basketbooksellernote + undef, # basketcontractnumber + $branch->{branchcode}, # deliveryplace + $branch->{branchcode}, # billingplace + 0 # is_standing ); my $basket = GetBasket($basketno); @@ -56,35 +56,36 @@ is( $basket->{is_standing}, 1, 'basket correctly created as standing order baske my ( $biblionumber, $biblioitemnumber ) = C4::Biblio::AddBiblio( MARC::Record->new, '' ); - my $ordernumber = Koha::Acquisition::Order->new( { - basketno => $basketno, - biblionumber => $biblionumber, - budget_id => $budget->{budget_id}, - currency => $curcode, - quantity => 0, - rrp => 42, - rrp_tax_included => 42, - rrp_tax_excluded => 42, - ecost => 22, - ecost_tax_included => 22, - ecost_tax_excluded => 22, - unitprice => 12, - unitprice_tax_included => 12, - unitprice_tax_excluded => 12, - tax_rate_on_ordering => 0, - tax_rate_on_receiving => 0, + basketno => $basketno, + biblionumber => $biblionumber, + budget_id => $budget->{budget_id}, + currency => $curcode, + quantity => 0, + rrp => 42, + rrp_tax_included => 42, + rrp_tax_excluded => 42, + ecost => 22, + ecost_tax_included => 22, + ecost_tax_excluded => 22, + unitprice => 12, + unitprice_tax_included => 12, + unitprice_tax_excluded => 12, + tax_rate_on_ordering => 0, + tax_rate_on_receiving => 0, } )->store->ordernumber; isnt( $ordernumber, undef, 'standing order successfully created' ); -my $search_orders = SearchOrders( { - basketno => $basketno, - pending => 1, - ordered => 1, -} ); +my $search_orders = SearchOrders( + { + basketno => $basketno, + pending => 1, + ordered => 1, + } +); ok( scalar @$search_orders == 1 && $search_orders->[0]->{ordernumber} == $ordernumber, @@ -97,7 +98,7 @@ my $invoiceid = AddInvoice( unknown => "unknown" ); -my $order = Koha::Acquisition::Orders->find( $ordernumber ); +my $order = Koha::Acquisition::Orders->find($ordernumber); my ( $datereceived, $new_ordernumber ) = ModReceiveOrder( { @@ -111,29 +112,30 @@ my ( $datereceived, $new_ordernumber ) = ModReceiveOrder( isnt( $ordernumber, $new_ordernumber, "standing order split on receive" ); #order has been updated, refetch -$order = Koha::Acquisition::Orders->find( $ordernumber ); -my $neworder = Koha::Acquisition::Orders->find( $new_ordernumber ); +$order = Koha::Acquisition::Orders->find($ordernumber); +my $neworder = Koha::Acquisition::Orders->find($new_ordernumber); -is( $order->orderstatus, 'partial', 'original order set to partially received' ); -is( $order->quantity, 1, 'original order quantity unchanged' ); -is( $order->quantityreceived, 0, 'original order has no received items' ); +is( $order->orderstatus, 'partial', 'original order set to partially received' ); +is( $order->quantity, 1, 'original order quantity unchanged' ); +is( $order->quantityreceived, 0, 'original order has no received items' ); isnt( $order->unitprice, 12, 'original order does not get cost' ); -is( $neworder->orderstatus, 'complete', 'new order set to complete' ); -is( $neworder->quantityreceived, 2, 'new order has received items' ); +is( $neworder->orderstatus, 'complete', 'new order set to complete' ); +is( $neworder->quantityreceived, 2, 'new order has received items' ); cmp_ok( $neworder->unitprice, '==', 12, 'new order does get cost' ); -$search_orders = SearchOrders( { - basketno => $basketno, - pending => 1, - ordered => 1, -} ); +$search_orders = SearchOrders( + { + basketno => $basketno, + pending => 1, + ordered => 1, + } +); -is( scalar @$search_orders, 1, 'only one pending order after receive' ); +is( scalar @$search_orders, 1, 'only one pending order after receive' ); is( $search_orders->[0]->{ordernumber}, $ordernumber, 'original order is only pending order' ); CancelReceipt($new_ordernumber); -$order = Koha::Acquisition::Orders->find( $ordernumber ); -is( $order->quantity, 1, 'CancelReceipt should not have increased the quantity if order is standing'); - +$order = Koha::Acquisition::Orders->find($ordernumber); +is( $order->quantity, 1, 'CancelReceipt should not have increased the quantity if order is standing' ); $schema->storage->txn_rollback(); diff --git a/t/db_dependent/Acquisition/TransferOrder.t b/t/db_dependent/Acquisition/TransferOrder.t index 1cf443dd6d..459674c72e 100755 --- a/t/db_dependent/Acquisition/TransferOrder.t +++ b/t/db_dependent/Acquisition/TransferOrder.t @@ -23,29 +23,25 @@ my $builder = t::lib::TestBuilder->new; my $bookseller1 = Koha::Acquisition::Bookseller->new( { - name => "my vendor 1", + name => "my vendor 1", address1 => "bookseller's address", - phone => "0123456", - active => 1 + phone => "0123456", + active => 1 } )->store; -my $basketno1 = C4::Acquisition::NewBasket( - $bookseller1->id -); +my $basketno1 = C4::Acquisition::NewBasket( $bookseller1->id ); my $bookseller2 = Koha::Acquisition::Bookseller->new( { - name => "my vendor 2", + name => "my vendor 2", address1 => "bookseller's address", - phone => "0123456", - active => 1 + phone => "0123456", + active => 1 } )->store; -my $basketno2 = C4::Acquisition::NewBasket( - $bookseller2->id -); +my $basketno2 = C4::Acquisition::NewBasket( $bookseller2->id ); my $budget_period_id = C4::Budgets::AddBudgetPeriod( { @@ -64,62 +60,70 @@ my $budgetid = C4::Budgets::AddBudget( } ); -my $budget = C4::Budgets::GetBudget( $budgetid ); +my $budget = C4::Budgets::GetBudget($budgetid); -my $biblio = $builder->build_sample_biblio(); -my $item_1 = $builder->build_sample_item({ biblionumber => $biblio->biblionumber }); +my $biblio = $builder->build_sample_biblio(); +my $item_1 = $builder->build_sample_item( { biblionumber => $biblio->biblionumber } ); my $biblionumber = $biblio->biblionumber; my $order = Koha::Acquisition::Order->new( { - basketno => $basketno1, - quantity => 2, + basketno => $basketno1, + quantity => 2, biblionumber => $biblionumber, - budget_id => $budget->{budget_id}, + budget_id => $budget->{budget_id}, } )->store; my $ordernumber = $order->ordernumber; $order->add_item( $item_1->itemnumber ); # Begin tests -is(scalar GetOrders($basketno1), 1, "1 order in basket1"); +is( scalar GetOrders($basketno1), 1, "1 order in basket1" ); ($order) = GetOrders($basketno1); -$order = Koha::Acquisition::Orders->find($order->{ordernumber}); -is($order->items->count, 1, "1 item in basket1's order"); -is(scalar GetOrders($basketno2), 0, "0 order in basket2"); +$order = Koha::Acquisition::Orders->find( $order->{ordernumber} ); +is( $order->items->count, 1, "1 item in basket1's order" ); +is( scalar GetOrders($basketno2), 0, "0 order in basket2" ); # Transfering order to basket2 -my $newordernumber = TransferOrder($ordernumber, $basketno2); -is(scalar GetOrders($basketno1), 0, "0 order in basket1"); -is(scalar GetOrders($basketno2), 1, "1 order in basket2"); +my $newordernumber = TransferOrder( $ordernumber, $basketno2 ); +is( scalar GetOrders($basketno1), 0, "0 order in basket1" ); +is( scalar GetOrders($basketno2), 1, "1 order in basket2" ); # Determine if the transfer marked things cancelled properly. -is($order->orderstatus,'new','Before the transfer, the order status should be new'); -$order = Koha::Acquisition::Orders->find($order->ordernumber); -is($order->orderstatus,'cancelled','After the transfer, the order status should be set to cancelled'); +is( $order->orderstatus, 'new', 'Before the transfer, the order status should be new' ); +$order = Koha::Acquisition::Orders->find( $order->ordernumber ); +is( $order->orderstatus, 'cancelled', 'After the transfer, the order status should be set to cancelled' ); ($order) = GetOrders($basketno2); -$order = Koha::Acquisition::Orders->find($order->{ordernumber}); -is($order->items->count, 1, "1 item in basket2's order"); +$order = Koha::Acquisition::Orders->find( $order->{ordernumber} ); +is( $order->items->count, 1, "1 item in basket2's order" ); # Bug 11552 -my $orders = SearchOrders({ ordernumber => $newordernumber }); -is ( scalar( @$orders ), 1, 'SearchOrders returns 1 order with newordernumber' ); -$orders = SearchOrders({ ordernumber => $ordernumber }); -is ( scalar( @$orders ), 1, 'SearchOrders returns 1 order with [old]ordernumber' ); -is ( $orders->[0]->{ordernumber}, $newordernumber, 'SearchOrders returns newordernumber if [old]ordernumber is given' ); +my $orders = SearchOrders( { ordernumber => $newordernumber } ); +is( scalar(@$orders), 1, 'SearchOrders returns 1 order with newordernumber' ); +$orders = SearchOrders( { ordernumber => $ordernumber } ); +is( scalar(@$orders), 1, 'SearchOrders returns 1 order with [old]ordernumber' ); +is( $orders->[0]->{ordernumber}, $newordernumber, 'SearchOrders returns newordernumber if [old]ordernumber is given' ); -my $neworder = Koha::Acquisition::Orders->find( $newordernumber )->unblessed; +my $neworder = Koha::Acquisition::Orders->find($newordernumber)->unblessed; -ModReceiveOrder({ - biblionumber => $biblionumber, - order => $neworder, - quantityreceived => 2, -}); -CancelReceipt( $newordernumber ); -$order = GetOrder( $newordernumber ); -is ( $order->{ordernumber}, $newordernumber, 'Regression test Bug 11549: After a transfer, receive and cancel the receive should be possible.' ); -is ( $order->{basketno}, $basketno2, 'Regression test Bug 11549: The order still exist in the basket where the transfer has been done.'); +ModReceiveOrder( + { + biblionumber => $biblionumber, + order => $neworder, + quantityreceived => 2, + } +); +CancelReceipt($newordernumber); +$order = GetOrder($newordernumber); +is( + $order->{ordernumber}, $newordernumber, + 'Regression test Bug 11549: After a transfer, receive and cancel the receive should be possible.' +); +is( + $order->{basketno}, $basketno2, + 'Regression test Bug 11549: The order still exist in the basket where the transfer has been done.' +); subtest 'TransferOrder should copy additional fields' => sub { plan tests => 2; @@ -127,33 +131,36 @@ subtest 'TransferOrder should copy additional fields' => sub { my $field = Koha::AdditionalField->new( { tablename => 'aqorders', - name => random_string('c' x 100), + name => random_string( 'c' x 100 ), } ); $field->store()->discard_changes(); my $order = Koha::Acquisition::Order->new( { - basketno => $basketno1, - quantity => 2, + basketno => $basketno1, + quantity => 2, biblionumber => $biblionumber, - budget_id => $budget->{budget_id}, + budget_id => $budget->{budget_id}, } )->store; $order->set_additional_fields( [ { - id => $field->id, + id => $field->id, value => 'additional field value', }, ] ); - my $newordernumber = TransferOrder($order->ordernumber, $basketno2); - my $neworder = Koha::Acquisition::Orders->find($newordernumber); - my $field_values = $neworder->additional_field_values()->as_list; + my $newordernumber = TransferOrder( $order->ordernumber, $basketno2 ); + my $neworder = Koha::Acquisition::Orders->find($newordernumber); + my $field_values = $neworder->additional_field_values()->as_list; - is(scalar @$field_values, 1, 'transfered order has one additional field value'); - is($field_values->[0]->value, 'additional field value', 'transfered order additional field has the correct value'); + is( scalar @$field_values, 1, 'transfered order has one additional field value' ); + is( + $field_values->[0]->value, 'additional field value', + 'transfered order additional field has the correct value' + ); }; $schema->storage->txn_rollback(); diff --git a/t/db_dependent/Acquisition/close_reopen_basket.t b/t/db_dependent/Acquisition/close_reopen_basket.t index 47aa681fac..bef18fc53a 100755 --- a/t/db_dependent/Acquisition/close_reopen_basket.t +++ b/t/db_dependent/Acquisition/close_reopen_basket.t @@ -4,8 +4,8 @@ use Modern::Perl; use Test::More tests => 14; use C4::Acquisition qw( NewBasket GetBiblioCountByBasketno GetOrders GetOrder ReopenBasket ); -use C4::Biblio qw( AddBiblio ); -use C4::Budgets qw( AddBudget GetBudget ); +use C4::Biblio qw( AddBiblio ); +use C4::Budgets qw( AddBudget GetBudget ); use C4::Context; use Koha::Database; use Koha::Acquisition::Booksellers; @@ -17,22 +17,22 @@ $schema->storage->txn_begin(); my $dbh = C4::Context->dbh; -$dbh->do(q{ +$dbh->do( + q{ DELETE FROM aqorders; -}); +} +); my $bookseller = Koha::Acquisition::Bookseller->new( { - name => "my vendor", + name => "my vendor", address1 => "bookseller's address", - phone => "0123456", - active => 1 + phone => "0123456", + active => 1 } )->store; -my $basketno = C4::Acquisition::NewBasket( - $bookseller->id -); +my $basketno = C4::Acquisition::NewBasket( $bookseller->id ); my $budget_period_id = C4::Budgets::AddBudgetPeriod( { @@ -51,63 +51,69 @@ my $budgetid = C4::Budgets::AddBudget( } ); -my $budget = C4::Budgets::GetBudget( $budgetid ); +my $budget = C4::Budgets::GetBudget($budgetid); -my ($biblionumber1, $biblioitemnumber1) = AddBiblio(MARC::Record->new, ''); -my ($biblionumber2, $biblioitemnumber2) = AddBiblio(MARC::Record->new, ''); +my ( $biblionumber1, $biblioitemnumber1 ) = AddBiblio( MARC::Record->new, '' ); +my ( $biblionumber2, $biblioitemnumber2 ) = AddBiblio( MARC::Record->new, '' ); my $order1 = Koha::Acquisition::Order->new( { - basketno => $basketno, - quantity => 24, + basketno => $basketno, + quantity => 24, biblionumber => $biblionumber1, - budget_id => $budget->{budget_id}, + budget_id => $budget->{budget_id}, } )->store; my $ordernumber1 = $order1->ordernumber; my $order2 = Koha::Acquisition::Order->new( { - basketno => $basketno, - quantity => 42, + basketno => $basketno, + quantity => 42, biblionumber => $biblionumber2, - budget_id => $budget->{budget_id}, + budget_id => $budget->{budget_id}, } )->store; my $ordernumber2 = $order2->ordernumber; -my $nb_biblio = C4::Acquisition::GetBiblioCountByBasketno( $basketno ); -is ( $nb_biblio, 2, "There are 2 biblio for this basket" ); -my @orders = C4::Acquisition::GetOrders( $basketno ); -is( scalar(@orders), 2, "2 orders are created" ); -is ( scalar( map { $_->{orderstatus} eq 'new' ? 1 : () } @orders ), 2, "2 orders are new before closing the basket" ); +my $nb_biblio = C4::Acquisition::GetBiblioCountByBasketno($basketno); +is( $nb_biblio, 2, "There are 2 biblio for this basket" ); +my @orders = C4::Acquisition::GetOrders($basketno); +is( scalar(@orders), 2, "2 orders are created" ); +is( scalar( map { $_->{orderstatus} eq 'new' ? 1 : () } @orders ), 2, "2 orders are new before closing the basket" ); -Koha::Acquisition::Baskets->find( $basketno )->close; -@orders = C4::Acquisition::GetOrders( $basketno ); -is ( scalar( map { $_->{orderstatus} eq 'ordered' ? 1 : () } @orders ), 2, "2 orders are ordered, the basket is closed" ); +Koha::Acquisition::Baskets->find($basketno)->close; +@orders = C4::Acquisition::GetOrders($basketno); +is( + scalar( map { $_->{orderstatus} eq 'ordered' ? 1 : () } @orders ), 2, + "2 orders are ordered, the basket is closed" +); -C4::Acquisition::ReopenBasket( $basketno ); -@orders = C4::Acquisition::GetOrders( $basketno ); -is ( scalar( map { $_->{orderstatus} eq 'ordered' ? 1 : () } @orders ), 0, "No order is ordered, the basket is reopened" ); -is ( scalar( map { $_->{orderstatus} eq 'new' ? 1 : () } @orders ), 2, "2 orders are new, the basket is reopened" ); +C4::Acquisition::ReopenBasket($basketno); +@orders = C4::Acquisition::GetOrders($basketno); +is( + scalar( map { $_->{orderstatus} eq 'ordered' ? 1 : () } @orders ), 0, + "No order is ordered, the basket is reopened" +); +is( scalar( map { $_->{orderstatus} eq 'new' ? 1 : () } @orders ), 2, "2 orders are new, the basket is reopened" ); Koha::Acquisition::Orders->find($ordernumber1)->cancel; -my ( $order ) = C4::Acquisition::GetOrders( $basketno, {cancelled => 1} ); +my ($order) = C4::Acquisition::GetOrders( $basketno, { cancelled => 1 } ); is( $order->{ordernumber}, $ordernumber1, 'The order returned by GetOrders should have been the right one' ); -is( $order->{orderstatus}, 'cancelled', 'cancelling the order should have set status to cancelled' ); +is( $order->{orderstatus}, 'cancelled', 'cancelling the order should have set status to cancelled' ); -Koha::Acquisition::Baskets->find( $basketno )->close; -( $order ) = C4::Acquisition::GetOrders( $basketno, {cancelled => 1} ); +Koha::Acquisition::Baskets->find($basketno)->close; +($order) = C4::Acquisition::GetOrders( $basketno, { cancelled => 1 } ); is( $order->{ordernumber}, $ordernumber1, 'The order returned by GetOrders should have been the right one' ); is( $order->{orderstatus}, 'cancelled', '$basket->close should not reset the status to ordered for cancelled orders' ); -C4::Acquisition::ReopenBasket( $basketno ); -( $order ) = C4::Acquisition::GetOrders( $basketno, {cancelled => 1} ); +C4::Acquisition::ReopenBasket($basketno); +($order) = C4::Acquisition::GetOrders( $basketno, { cancelled => 1 } ); is( $order->{ordernumber}, $ordernumber1, 'The expected order is cancelled, the basket is reopened' ); -is( $order->{orderstatus}, 'cancelled', 'ReopenBasket should not reset the status for cancelled orders' ); +is( $order->{orderstatus}, 'cancelled', 'ReopenBasket should not reset the status for cancelled orders' ); -( $order ) = C4::Acquisition::GetOrders( $basketno, { cancelled => 0 } ); -is ( $order->{ordernumber}, $ordernumber2, "The expect order is not cancelled, the basket is reopened" ); -is ( $order->{orderstatus}, 'new', 'The expected order is new, the basket is reopened' ); +($order) = C4::Acquisition::GetOrders( $basketno, { cancelled => 0 } ); +is( $order->{ordernumber}, $ordernumber2, "The expect order is not cancelled, the basket is reopened" ); +is( $order->{orderstatus}, 'new', 'The expected order is new, the basket is reopened' ); $schema->storage->txn_rollback(); diff --git a/t/db_dependent/Acquisition/populate_order_with_prices.t b/t/db_dependent/Acquisition/populate_order_with_prices.t index 3bf9fa32f4..a4eac542f9 100755 --- a/t/db_dependent/Acquisition/populate_order_with_prices.t +++ b/t/db_dependent/Acquisition/populate_order_with_prices.t @@ -40,133 +40,252 @@ my $bookseller_exc_tax = Koha::Acquisition::Bookseller->new( my $basket_exc_tax = Koha::Acquisition::Basket->new( { - basketname => 'Basket tax excluded', + basketname => 'Basket tax excluded', booksellerid => $bookseller_exc_tax->id, } )->store; -my $order_exc_tax = Koha::Acquisition::Order->new({ - tax_rate_on_ordering => .1965, - tax_rate_on_receiving => .1965, - discount => .42, - rrp => 16.99, - unitprice => "0.00", - quantity => 8, - basketno => $basket_exc_tax->basketno, -}); +my $order_exc_tax = Koha::Acquisition::Order->new( + { + tax_rate_on_ordering => .1965, + tax_rate_on_receiving => .1965, + discount => .42, + rrp => 16.99, + unitprice => "0.00", + quantity => 8, + basketno => $basket_exc_tax->basketno, + } +); #Vendor prices exclude tax, no rounding, ordering -t::lib::Mocks::mock_preference('OrderPriceRounding', ''); +t::lib::Mocks::mock_preference( 'OrderPriceRounding', '' ); $order_exc_tax->populate_with_prices_for_ordering(); -is( $order_exc_tax->rrp_tax_excluded+0 ,16.99 ,"Ordering tax excluded, no round: rrp tax excluded is rrp"); -is( $order_exc_tax->rrp_tax_included+0 ,20.328535 ,"Ordering tax excluded, no round: rrp tax included is rr tax excluded * (1 + tax rate on ordering)"); -is( $order_exc_tax->ecost_tax_excluded+0 ,9.8542 ,"Ordering tax excluded, no round: ecost tax excluded is rrp * ( 1 - discount )"); -is( $order_exc_tax->ecost_tax_included+0 ,11.7905503 ,"Ordering tax excluded, no round: ecost tax included is ecost tax excluded * (1 + tax rate on ordering)"); -is( $order_exc_tax->tax_value_on_ordering+0 ,15.4908024 ,"Ordering tax excluded, no round: tax value on ordering is quantity * ecost_tax_excluded * tax rate on ordering if no unitprice"); +is( $order_exc_tax->rrp_tax_excluded + 0, 16.99, "Ordering tax excluded, no round: rrp tax excluded is rrp" ); +is( + $order_exc_tax->rrp_tax_included + 0, 20.328535, + "Ordering tax excluded, no round: rrp tax included is rr tax excluded * (1 + tax rate on ordering)" +); +is( + $order_exc_tax->ecost_tax_excluded + 0, 9.8542, + "Ordering tax excluded, no round: ecost tax excluded is rrp * ( 1 - discount )" +); +is( + $order_exc_tax->ecost_tax_included + 0, 11.7905503, + "Ordering tax excluded, no round: ecost tax included is ecost tax excluded * (1 + tax rate on ordering)" +); +is( + $order_exc_tax->tax_value_on_ordering + 0, 15.4908024, + "Ordering tax excluded, no round: tax value on ordering is quantity * ecost_tax_excluded * tax rate on ordering if no unitprice" +); $order_exc_tax->unitprice(9.85); $order_exc_tax->populate_with_prices_for_ordering(); -is( $order_exc_tax->unitprice_tax_excluded+0 ,9.85 ,"Ordering tax excluded, no round: rrp tax excluded is rrp"); -is( $order_exc_tax->unitprice_tax_included+0 ,11.785525 ,"Ordering tax excluded, no round: rrp tax included is rr tax excluded * (1 + tax rate on ordering)"); -is( $order_exc_tax->tax_value_on_ordering+0 ,15.4842 ,"Ordering tax excluded, no round: tax value on ordering is quantity * unitprice_tax_excluded * tax rate on ordering if unitprice"); +is( $order_exc_tax->unitprice_tax_excluded + 0, 9.85, "Ordering tax excluded, no round: rrp tax excluded is rrp" ); +is( + $order_exc_tax->unitprice_tax_included + 0, 11.785525, + "Ordering tax excluded, no round: rrp tax included is rr tax excluded * (1 + tax rate on ordering)" +); +is( + $order_exc_tax->tax_value_on_ordering + 0, 15.4842, + "Ordering tax excluded, no round: tax value on ordering is quantity * unitprice_tax_excluded * tax rate on ordering if unitprice" +); #Vendor prices exclude tax, no rounding, receiving $order_exc_tax->populate_with_prices_for_receiving(); -is( $order_exc_tax->unitprice+0 ,9.8542 ,"Receiving tax excluded, no round, rounded ecost tax excluded = rounded unitprice : unitprice is ecost tax excluded"); -is( $order_exc_tax->unitprice_tax_excluded+0 ,9.8542 ,"Receiving tax excluded, no round, rounded ecost tax excluded = rounded unitprice : unitprice tax excluded is ecost tax excluded"); -is( $order_exc_tax->unitprice_tax_included+0 ,11.7905503 ,"Receiving tax excluded, no round: unitprice tax included is unitprice tax excluded * (1 + tax rate on ordering)"); -is( $order_exc_tax->tax_value_on_receiving+0 ,15.4908024 ,"Receiving tax excluded, no round: tax value on receiving is quantity * unitprice_tax_excluded * tax rate on receiving"); - +is( + $order_exc_tax->unitprice + 0, 9.8542, + "Receiving tax excluded, no round, rounded ecost tax excluded = rounded unitprice : unitprice is ecost tax excluded" +); +is( + $order_exc_tax->unitprice_tax_excluded + 0, 9.8542, + "Receiving tax excluded, no round, rounded ecost tax excluded = rounded unitprice : unitprice tax excluded is ecost tax excluded" +); +is( + $order_exc_tax->unitprice_tax_included + 0, 11.7905503, + "Receiving tax excluded, no round: unitprice tax included is unitprice tax excluded * (1 + tax rate on ordering)" +); +is( + $order_exc_tax->tax_value_on_receiving + 0, 15.4908024, + "Receiving tax excluded, no round: tax value on receiving is quantity * unitprice_tax_excluded * tax rate on receiving" +); $order_exc_tax->unitprice(9.85); + #populate order with prices updates the passed in order hashref #we need to reset after additional tests and changes #Vendor prices exclude tax, rounding to nearest cent, ordering -t::lib::Mocks::mock_preference('OrderPriceRounding', 'nearest_cent'); +t::lib::Mocks::mock_preference( 'OrderPriceRounding', 'nearest_cent' ); $order_exc_tax->populate_with_prices_for_ordering(); -is( $order_exc_tax->unitprice_tax_excluded+0 ,9.85 ,"Ordering tax excluded, round: unitprice tax excluded is unitprice"); -is( $order_exc_tax->unitprice_tax_included+0 ,11.785525 ,"Ordering tax excluded, round: unitprice tax included is unitprice tax excluded * (1 + tax rate on ordering)"); -is( $order_exc_tax->rrp_tax_excluded+0 ,16.99 ,"Ordering tax excluded, round: rrp tax excluded is rrp"); -is( $order_exc_tax->rrp_tax_included+0 ,20.328535 ,"Ordering tax excluded, round: rrp tax included is rr tax excluded * (1 + tax rate on ordering)"); -is( $order_exc_tax->ecost_tax_excluded+0 ,9.8542 ,"Ordering tax excluded, round: ecost tax excluded is rrp * ( 1 - discount )"); -is( $order_exc_tax->ecost_tax_included+0 ,11.7905503 ,"Ordering tax excluded, round: ecost tax included is ecost tax excluded * (1 + tax rate on ordering)"); -is( $order_exc_tax->tax_value_on_ordering+0 ,15.4842 ,"Ordering tax excluded, round: tax value on ordering is quantity * ecost_tax_excluded * tax rate on ordering"); +is( + $order_exc_tax->unitprice_tax_excluded + 0, 9.85, + "Ordering tax excluded, round: unitprice tax excluded is unitprice" +); +is( + $order_exc_tax->unitprice_tax_included + 0, 11.785525, + "Ordering tax excluded, round: unitprice tax included is unitprice tax excluded * (1 + tax rate on ordering)" +); +is( $order_exc_tax->rrp_tax_excluded + 0, 16.99, "Ordering tax excluded, round: rrp tax excluded is rrp" ); +is( + $order_exc_tax->rrp_tax_included + 0, 20.328535, + "Ordering tax excluded, round: rrp tax included is rr tax excluded * (1 + tax rate on ordering)" +); +is( + $order_exc_tax->ecost_tax_excluded + 0, 9.8542, + "Ordering tax excluded, round: ecost tax excluded is rrp * ( 1 - discount )" +); +is( + $order_exc_tax->ecost_tax_included + 0, 11.7905503, + "Ordering tax excluded, round: ecost tax included is ecost tax excluded * (1 + tax rate on ordering)" +); +is( + $order_exc_tax->tax_value_on_ordering + 0, 15.4842, + "Ordering tax excluded, round: tax value on ordering is quantity * ecost_tax_excluded * tax rate on ordering" +); #Vendor prices exclude tax, no rounding, receiving $order_exc_tax->populate_with_prices_for_receiving(); -is( $order_exc_tax->unitprice_tax_excluded+0 ,9.8542 ,"Receiving tax excluded, round, rounded ecost tax excluded = rounded unitprice : unitprice tax excluded is ecost tax excluded"); -is( $order_exc_tax->unitprice_tax_included+0 ,11.7905503 ,"Receiving tax excluded, round: unitprice tax included is unitprice tax excluded * (1 + tax rate on ordering)"); -is( $order_exc_tax->tax_value_on_receiving+0 ,15.4842 ,"Receiving tax excluded, round: tax value on receiving is quantity * unitprice_tax_excluded * tax rate on receiving"); - +is( + $order_exc_tax->unitprice_tax_excluded + 0, 9.8542, + "Receiving tax excluded, round, rounded ecost tax excluded = rounded unitprice : unitprice tax excluded is ecost tax excluded" +); +is( + $order_exc_tax->unitprice_tax_included + 0, 11.7905503, + "Receiving tax excluded, round: unitprice tax included is unitprice tax excluded * (1 + tax rate on ordering)" +); +is( + $order_exc_tax->tax_value_on_receiving + 0, 15.4842, + "Receiving tax excluded, round: tax value on receiving is quantity * unitprice_tax_excluded * tax rate on receiving" +); my $basket_inc_tax = Koha::Acquisition::Basket->new( { - basketname => 'Basket tax included', + basketname => 'Basket tax included', booksellerid => $bookseller_inc_tax->id, } )->store; -my $order_inc_tax = Koha::Acquisition::Order->new({ - tax_rate_on_ordering => .1965, - tax_rate_on_receiving => .1965, - discount => .42, - rrp => 20.33, - unitprice => 0.00, - quantity => 8, - basketno => $basket_inc_tax->basketno, -}); +my $order_inc_tax = Koha::Acquisition::Order->new( + { + tax_rate_on_ordering => .1965, + tax_rate_on_receiving => .1965, + discount => .42, + rrp => 20.33, + unitprice => 0.00, + quantity => 8, + basketno => $basket_inc_tax->basketno, + } +); #Vendor prices include tax, no rounding, ordering -t::lib::Mocks::mock_preference('OrderPriceRounding', ''); +t::lib::Mocks::mock_preference( 'OrderPriceRounding', '' ); $order_inc_tax->populate_with_prices_for_ordering(); -is( $order_inc_tax->rrp_tax_included+0 ,20.33 ,"Ordering tax included, no round: rrp tax included is rrp"); -is( $order_inc_tax->rrp_tax_excluded+0 ,16.9912244045132 ,"Ordering tax included, no round: rrp tax excluded is rrp tax included / (1 + tax rate on ordering)"); -is( $order_inc_tax->ecost_tax_included+0 ,11.7914 ,"Ordering tax included, no round: ecost tax included is rrp tax included * (1 - discount)"); -is( $order_inc_tax->ecost_tax_excluded+0 ,9.85491015461764 ,"Ordering tax included, no round: ecost tax excluded is rrp tax excluded * ( 1 - discount )"); -is( $order_inc_tax->tax_value_on_ordering+0 ,15.4919187630589 ,"Ordering tax included, no round: tax value on ordering is ( ecost tax included - ecost tax excluded ) * quantity if no unitprice"); +is( $order_inc_tax->rrp_tax_included + 0, 20.33, "Ordering tax included, no round: rrp tax included is rrp" ); +is( + $order_inc_tax->rrp_tax_excluded + 0, 16.9912244045132, + "Ordering tax included, no round: rrp tax excluded is rrp tax included / (1 + tax rate on ordering)" +); +is( + $order_inc_tax->ecost_tax_included + 0, 11.7914, + "Ordering tax included, no round: ecost tax included is rrp tax included * (1 - discount)" +); +is( + $order_inc_tax->ecost_tax_excluded + 0, 9.85491015461764, + "Ordering tax included, no round: ecost tax excluded is rrp tax excluded * ( 1 - discount )" +); +is( + $order_inc_tax->tax_value_on_ordering + 0, 15.4919187630589, + "Ordering tax included, no round: tax value on ordering is ( ecost tax included - ecost tax excluded ) * quantity if no unitprice" +); $order_inc_tax->unitprice(11.79); $order_inc_tax->populate_with_prices_for_ordering(); -is( $order_inc_tax->unitprice_tax_included+0 ,11.79 ,"Ordering tax included, no round: unitprice tax included is unitprice"); -is( $order_inc_tax->unitprice_tax_excluded+0 ,9.85374007521939 ,"Ordering tax included, no round: unitprice tax excluded is unitprice tax included / (1 + tax_rate_on_ordering "); -is( $order_inc_tax->tax_value_on_ordering+0 ,15.4900793982449 ,"Ordering tax included, no round: tax value on ordering is ( unitprice tax included - unitprice tax excluded ) * quantity if unitprice"); +is( + $order_inc_tax->unitprice_tax_included + 0, 11.79, + "Ordering tax included, no round: unitprice tax included is unitprice" +); +is( + $order_inc_tax->unitprice_tax_excluded + 0, 9.85374007521939, + "Ordering tax included, no round: unitprice tax excluded is unitprice tax included / (1 + tax_rate_on_ordering " +); +is( + $order_inc_tax->tax_value_on_ordering + 0, 15.4900793982449, + "Ordering tax included, no round: tax value on ordering is ( unitprice tax included - unitprice tax excluded ) * quantity if unitprice" +); #Vendor prices include tax, no rounding, receiving $order_inc_tax->populate_with_prices_for_receiving(); -is( $order_inc_tax->unitprice+0 ,11.7914 ,"Receiving tax included, no round, rounded ecost tax excluded = rounded unitprice : unitprice is ecost tax excluded"); -is( $order_inc_tax->unitprice_tax_included+0 ,11.7914 ,"Receiving tax included, no round: unitprice tax included is unitprice"); -is( $order_inc_tax->unitprice_tax_excluded+0 ,9.85491015461764 ,"Receiving tax included, no round: unitprice tax excluded is unitprice tax included / (1 + tax rate on receiving)"); -is( $order_inc_tax->tax_value_on_receiving+0 ,15.4919187630589 ,"Receiving tax included, no round: tax value on receiving is quantity * unitprice_tax_excluded * tax rate on receiving"); +is( + $order_inc_tax->unitprice + 0, 11.7914, + "Receiving tax included, no round, rounded ecost tax excluded = rounded unitprice : unitprice is ecost tax excluded" +); +is( + $order_inc_tax->unitprice_tax_included + 0, 11.7914, + "Receiving tax included, no round: unitprice tax included is unitprice" +); +is( + $order_inc_tax->unitprice_tax_excluded + 0, 9.85491015461764, + "Receiving tax included, no round: unitprice tax excluded is unitprice tax included / (1 + tax rate on receiving)" +); +is( + $order_inc_tax->tax_value_on_receiving + 0, 15.4919187630589, + "Receiving tax included, no round: tax value on receiving is quantity * unitprice_tax_excluded * tax rate on receiving" +); #Vendor prices include tax, rounding to nearest cent, ordering -t::lib::Mocks::mock_preference('OrderPriceRounding', 'nearest_cent'); +t::lib::Mocks::mock_preference( 'OrderPriceRounding', 'nearest_cent' ); $order_inc_tax->unitprice(11.79); $order_inc_tax->populate_with_prices_for_ordering(); -is( $order_inc_tax->unitprice_tax_included+0 ,11.79 ,"Ordering tax included, round: unitprice tax included is unitprice"); -is( $order_inc_tax->unitprice_tax_excluded+0,9.85374007521939 ,"Ordering tax included, round: unitprice tax excluded is unitprice tax included / (1 + tax_rate_on_ordering "); -is( $order_inc_tax->rrp_tax_included+0 ,20.33 ,"Ordering tax included, round: rrp tax included is rrp"); -is( $order_inc_tax->rrp_tax_excluded+0 ,16.9912244045132 ,"Ordering tax included, round: rrp tax excluded is rounded rrp tax included * (1 + tax rate on ordering)"); -is( $order_inc_tax->ecost_tax_included+0 ,11.7914 ,"Ordering tax included, round: ecost tax included is rounded rrp * ( 1 - discount )"); -is( $order_inc_tax->ecost_tax_excluded+0 ,9.85491015461764 ,"Ordering tax included, round: ecost tax excluded is rounded ecost tax excluded * (1 - discount)"); -is( $order_inc_tax->tax_value_on_ordering+0 ,15.52 ,"Ordering tax included, round: tax value on ordering is (ecost_tax_included - ecost_tax_excluded) * quantity"); +is( + $order_inc_tax->unitprice_tax_included + 0, 11.79, + "Ordering tax included, round: unitprice tax included is unitprice" +); +is( + $order_inc_tax->unitprice_tax_excluded + 0, 9.85374007521939, + "Ordering tax included, round: unitprice tax excluded is unitprice tax included / (1 + tax_rate_on_ordering " +); +is( $order_inc_tax->rrp_tax_included + 0, 20.33, "Ordering tax included, round: rrp tax included is rrp" ); +is( + $order_inc_tax->rrp_tax_excluded + 0, 16.9912244045132, + "Ordering tax included, round: rrp tax excluded is rounded rrp tax included * (1 + tax rate on ordering)" +); +is( + $order_inc_tax->ecost_tax_included + 0, 11.7914, + "Ordering tax included, round: ecost tax included is rounded rrp * ( 1 - discount )" +); +is( + $order_inc_tax->ecost_tax_excluded + 0, 9.85491015461764, + "Ordering tax included, round: ecost tax excluded is rounded ecost tax excluded * (1 - discount)" +); +is( + $order_inc_tax->tax_value_on_ordering + 0, 15.52, + "Ordering tax included, round: tax value on ordering is (ecost_tax_included - ecost_tax_excluded) * quantity" +); #Vendor prices include tax, no rounding, receiving $order_inc_tax->populate_with_prices_for_receiving(); -is( $order_inc_tax->unitprice_tax_included+0 ,11.7914 ,"Receiving tax included, round: rounded ecost tax included = rounded unitprice : unitprice tax excluded is ecost tax included"); -is( $order_inc_tax->unitprice_tax_excluded+0 ,9.85491015461764 ,"Receiving tax included, round: unitprice tax excluded is unitprice tax included / (1 + tax rate on ordering)"); -is( $order_inc_tax->tax_value_on_receiving+0 ,15.4842 ,"Receiving tax included, round: tax value on receiving is quantity * (rounded unitprice_tax_excluded) * tax rate on receiving"); - +is( + $order_inc_tax->unitprice_tax_included + 0, 11.7914, + "Receiving tax included, round: rounded ecost tax included = rounded unitprice : unitprice tax excluded is ecost tax included" +); +is( + $order_inc_tax->unitprice_tax_excluded + 0, 9.85491015461764, + "Receiving tax included, round: unitprice tax excluded is unitprice tax included / (1 + tax rate on ordering)" +); +is( + $order_inc_tax->tax_value_on_receiving + 0, 15.4842, + "Receiving tax included, round: tax value on receiving is quantity * (rounded unitprice_tax_excluded) * tax rate on receiving" +); $schema->storage->txn_rollback(); diff --git a/t/db_dependent/Amazon.t b/t/db_dependent/Amazon.t index 871808415d..751429dae9 100755 --- a/t/db_dependent/Amazon.t +++ b/t/db_dependent/Amazon.t @@ -1,6 +1,6 @@ #!/usr/bin/perl # -# This Koha test module is a stub! +# This Koha test module is a stub! # Add more tests here!!! use strict; @@ -11,40 +11,40 @@ use t::lib::Mocks; use C4::Context; BEGIN { - use_ok('C4::External::Amazon', qw( get_amazon_tld )); + use_ok( 'C4::External::Amazon', qw( get_amazon_tld ) ); } my $context = C4::Context->new(); my $locale = $context->preference('AmazonLocale'); -t::lib::Mocks::mock_preference('AmazonLocale','CA'); +t::lib::Mocks::mock_preference( 'AmazonLocale', 'CA' ); $context->clear_syspref_cache(); -is(get_amazon_tld,'.ca','Changes locale to CA and tests get_amazon_tld'); +is( get_amazon_tld, '.ca', 'Changes locale to CA and tests get_amazon_tld' ); -t::lib::Mocks::mock_preference('AmazonLocale','DE'); +t::lib::Mocks::mock_preference( 'AmazonLocale', 'DE' ); $context->clear_syspref_cache(); -is(get_amazon_tld,'.de','Changes locale to DE and tests get_amazon_tld'); +is( get_amazon_tld, '.de', 'Changes locale to DE and tests get_amazon_tld' ); -t::lib::Mocks::mock_preference('AmazonLocale','FR'); +t::lib::Mocks::mock_preference( 'AmazonLocale', 'FR' ); $context->clear_syspref_cache(); -is(get_amazon_tld,'.fr','Changes locale to FR and tests get_amazon_tld'); +is( get_amazon_tld, '.fr', 'Changes locale to FR and tests get_amazon_tld' ); -t::lib::Mocks::mock_preference('AmazonLocale','JP'); +t::lib::Mocks::mock_preference( 'AmazonLocale', 'JP' ); $context->clear_syspref_cache(); -is(get_amazon_tld,'.jp','Changes locale to JP and tests get_amazon_tld'); +is( get_amazon_tld, '.jp', 'Changes locale to JP and tests get_amazon_tld' ); -t::lib::Mocks::mock_preference('AmazonLocale','UK'); +t::lib::Mocks::mock_preference( 'AmazonLocale', 'UK' ); $context->clear_syspref_cache(); -is(get_amazon_tld,'.co.uk','Changes locale to UK and tests get_amazon_tld'); +is( get_amazon_tld, '.co.uk', 'Changes locale to UK and tests get_amazon_tld' ); -t::lib::Mocks::mock_preference('AmazonLocale','US'); +t::lib::Mocks::mock_preference( 'AmazonLocale', 'US' ); $context->clear_syspref_cache(); -is(get_amazon_tld,'.com','Changes locale to US and tests get_amazon_tld'); +is( get_amazon_tld, '.com', 'Changes locale to US and tests get_amazon_tld' ); -t::lib::Mocks::mock_preference('AmazonLocale','NZ'); +t::lib::Mocks::mock_preference( 'AmazonLocale', 'NZ' ); $context->clear_syspref_cache(); -is(get_amazon_tld,'.com','Changes locale to one not in the array and tests get_amazon_tld'); +is( get_amazon_tld, '.com', 'Changes locale to one not in the array and tests get_amazon_tld' ); -t::lib::Mocks::mock_preference('AmazonLocale',$locale); +t::lib::Mocks::mock_preference( 'AmazonLocale', $locale ); $context->clear_syspref_cache(); diff --git a/t/db_dependent/ArticleRequests.t b/t/db_dependent/ArticleRequests.t index 289015b431..f4abe2c8af 100755 --- a/t/db_dependent/ArticleRequests.t +++ b/t/db_dependent/ArticleRequests.t @@ -50,26 +50,28 @@ my $dbh = C4::Context->dbh; $dbh->do("DELETE FROM circulation_rules"); -my $item = $builder->build_sample_item; +my $item = $builder->build_sample_item; my $biblio = $item->biblio; -my $branch = $builder->build({ source => 'Branch' }); -my $category = $builder->build({ source => 'Category' }); -my $patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { - categorycode => $category->{categorycode}, - branchcode => $branch->{branchcode}, - flags => 1,# superlibrarian - }, -}); +my $branch = $builder->build( { source => 'Branch' } ); +my $category = $builder->build( { source => 'Category' } ); +my $patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { + categorycode => $category->{categorycode}, + branchcode => $branch->{branchcode}, + flags => 1, # superlibrarian + }, + } +); ok( $patron->id, 'Koha::Patron created' ); -my $patron_2 = $builder->build_object({ class => 'Koha::Patrons', value => { flags => 0 } }); +my $patron_2 = $builder->build_object( { class => 'Koha::Patrons', value => { flags => 0 } } ); # store Koha::Notice::Messages->delete; my $article_request_title = 'an article request title'; -my $article_request = Koha::ArticleRequest->new( +my $article_request = Koha::ArticleRequest->new( { borrowernumber => $patron->id, biblionumber => $item->biblionumber, @@ -79,9 +81,13 @@ my $article_request = Koha::ArticleRequest->new( )->request(); my $notify_message = Koha::Notice::Messages->search->next; -is( $notify_message->letter_code, "AR_".Koha::ArticleRequest::Status::Requested); +is( $notify_message->letter_code, "AR_" . Koha::ArticleRequest::Status::Requested ); + # Default AR_PROCESSING template content "Title: <>" -like( $notify_message->content, qr{Title: $article_request_title}, 'Values from article_requests table must be fetched for the notification' ); +like( + $notify_message->content, qr{Title: $article_request_title}, + 'Values from article_requests table must be fetched for the notification' +); $article_request = Koha::ArticleRequests->find( $article_request->id ); ok( $article_request->id, 'Koha::ArticleRequest created' ); @@ -93,7 +99,7 @@ isnt( $article_request->updated_on, undef, 'New article request has updated_on d Koha::Notice::Messages->delete; $article_request->process(); $notify_message = Koha::Notice::Messages->search->next; -is( $notify_message->letter_code, "AR_".Koha::ArticleRequest::Status::Processing); +is( $notify_message->letter_code, "AR_" . Koha::ArticleRequest::Status::Processing ); is( $article_request->status, Koha::ArticleRequest::Status::Processing, '$ar->process() changes status to Processing' ); isnt( $article_request->updated_on, undef, 'Updated article request has an updated_on date set' ); @@ -121,7 +127,7 @@ my $rule = Koha::CirculationRules->set_rule( ); ok( $biblio->can_article_request($patron), 'Record is requestable with rule type yes' ); is( $biblio->article_request_type($patron), 'yes', 'Biblio article request type is yes' ); -ok( $item->can_article_request($patron), 'Item is requestable with rule type yes' ); +ok( $item->can_article_request($patron), 'Item is requestable with rule type yes' ); is( $item->article_request_type($patron), 'yes', 'Item article request type is yes' ); $rule->delete(); @@ -136,7 +142,7 @@ $rule = Koha::CirculationRules->set_rule( ); ok( $biblio->can_article_request($patron), 'Record is requestable with rule type bib_only' ); is( $biblio->article_request_type($patron), 'bib_only', 'Biblio article request type is bib_only' ); -ok( !$item->can_article_request($patron), 'Item is not requestable with rule type bib_only' ); +ok( !$item->can_article_request($patron), 'Item is not requestable with rule type bib_only' ); is( $item->article_request_type($patron), 'bib_only', 'Item article request type is bib_only' ); $rule->delete(); @@ -151,7 +157,7 @@ $rule = Koha::CirculationRules->set_rule( ); ok( $biblio->can_article_request($patron), 'Record is requestable with rule type item_only' ); is( $biblio->article_request_type($patron), 'item_only', 'Biblio article request type is item_only' ); -ok( $item->can_article_request($patron), 'Item is not requestable with rule type item_only' ); +ok( $item->can_article_request($patron), 'Item is not requestable with rule type item_only' ); is( $item->article_request_type($patron), 'item_only', 'Item article request type is item_only' ); $rule->delete(); @@ -166,7 +172,7 @@ $rule = Koha::CirculationRules->set_rule( ); ok( !$biblio->can_article_request($patron), 'Record is requestable with rule type no' ); is( $biblio->article_request_type($patron), 'no', 'Biblio article request type is no' ); -ok( !$item->can_article_request($patron), 'Item is not requestable with rule type no' ); +ok( !$item->can_article_request($patron), 'Item is not requestable with rule type no' ); is( $item->article_request_type($patron), 'no', 'Item article request type is no' ); $rule->delete(); @@ -176,35 +182,47 @@ subtest 'search_limited' => sub { my $group_1 = Koha::Library::Group->new( { title => 'TEST Group 1', ft_hide_patron_info => 1 } )->store; my $group_2 = Koha::Library::Group->new( { title => 'TEST Group 2', ft_hide_patron_info => 1 } )->store; - Koha::Library::Group->new({ parent_id => $group_1->id, branchcode => $patron->branchcode })->store(); - Koha::Library::Group->new({ parent_id => $group_2->id, branchcode => $patron_2->branchcode })->store(); - t::lib::Mocks::mock_userenv( { patron => $patron } ); # Is superlibrarian - is( Koha::ArticleRequests->search_limited->count, $nb_article_requests, 'Koha::ArticleRequests->search_limited should return all article requests for superlibrarian' ); - t::lib::Mocks::mock_userenv( { patron => $patron_2 } ); # Is restricted - is( Koha::ArticleRequests->search_limited->count, 0, 'Koha::ArticleRequests->search_limited should not return all article requests for restricted patron' ); + Koha::Library::Group->new( { parent_id => $group_1->id, branchcode => $patron->branchcode } )->store(); + Koha::Library::Group->new( { parent_id => $group_2->id, branchcode => $patron_2->branchcode } )->store(); + t::lib::Mocks::mock_userenv( { patron => $patron } ); # Is superlibrarian + is( + Koha::ArticleRequests->search_limited->count, $nb_article_requests, + 'Koha::ArticleRequests->search_limited should return all article requests for superlibrarian' + ); + t::lib::Mocks::mock_userenv( { patron => $patron_2 } ); # Is restricted + is( + Koha::ArticleRequests->search_limited->count, 0, + 'Koha::ArticleRequests->search_limited should not return all article requests for restricted patron' + ); }; subtest 'may_article_request' => sub { plan tests => 4; # mocking - t::lib::Mocks::mock_preference('ArticleRequests', 1); - t::lib::Mocks::mock_preference('ArticleRequestsLinkControl', 'calc'); - $cache->set_in_cache( Koha::CirculationRules::GUESSED_ITEMTYPES_KEY, { - '*' => { 'CR' => 1 }, - 'S' => { '*' => 1 }, - 'PT' => { 'BK' => 1 }, - }); + t::lib::Mocks::mock_preference( 'ArticleRequests', 1 ); + t::lib::Mocks::mock_preference( 'ArticleRequestsLinkControl', 'calc' ); + $cache->set_in_cache( + Koha::CirculationRules::GUESSED_ITEMTYPES_KEY, + { + '*' => { 'CR' => 1 }, + 'S' => { '*' => 1 }, + 'PT' => { 'BK' => 1 }, + } + ); - my $itemtype = Koha::ItemTypes->find('CR') // Koha::ItemType->new({ itemtype => 'CR' })->store; + my $itemtype = Koha::ItemTypes->find('CR') // Koha::ItemType->new( { itemtype => 'CR' } )->store; is( $itemtype->may_article_request, 1, 'SER/* should be true' ); - is( $itemtype->may_article_request({ categorycode => 'S' }), 1, 'SER/S should be true' ); - is( $itemtype->may_article_request({ categorycode => 'PT' }), '', 'SER/PT should be false' ); - t::lib::Mocks::mock_preference('ArticleRequestsLinkControl', 'always'); - is( $itemtype->may_article_request({ categorycode => 'PT' }), '1', 'Result should be true when LinkControl is set to always' ); + is( $itemtype->may_article_request( { categorycode => 'S' } ), 1, 'SER/S should be true' ); + is( $itemtype->may_article_request( { categorycode => 'PT' } ), '', 'SER/PT should be false' ); + t::lib::Mocks::mock_preference( 'ArticleRequestsLinkControl', 'always' ); + is( + $itemtype->may_article_request( { categorycode => 'PT' } ), '1', + 'Result should be true when LinkControl is set to always' + ); # Cleanup - $cache->clear_from_cache( Koha::CirculationRules::GUESSED_ITEMTYPES_KEY ); + $cache->clear_from_cache(Koha::CirculationRules::GUESSED_ITEMTYPES_KEY); }; $schema->storage->txn_rollback(); diff --git a/t/db_dependent/AudioAlerts.t b/t/db_dependent/AudioAlerts.t index 5b616e5008..6bb694c0d9 100755 --- a/t/db_dependent/AudioAlerts.t +++ b/t/db_dependent/AudioAlerts.t @@ -95,6 +95,7 @@ is( $c->precedence, 3, "Alert C has a precedence of 3" ); ## Test searching, should be ordered by precedence by default # Test searching, default search should be ordered by precedence $a->move('bottom'); + # Changed precedence order from database insert order # Insert order was a, b, c. Precedence order is now b, c, a. ( $b, $c, $a ) = Koha::AudioAlerts->search->as_list; @@ -110,11 +111,11 @@ is( $a->precedence, 3, "Alert A has a precedence of 3" ); ## Test fix precedences, should remove gaps in precedences # Testing precedence fixing. Should remove gaps from precedence list. -$a->precedence( 0 )->store(); -$b->precedence( 50 )->store(); -$c->precedence( 100 )->store(); -is( $a->precedence, 0, "Alert A has a precedence of 0" ); -is( $b->precedence, 50, "Alert B has a precedence of 50" ); +$a->precedence(0)->store(); +$b->precedence(50)->store(); +$c->precedence(100)->store(); +is( $a->precedence, 0, "Alert A has a precedence of 0" ); +is( $b->precedence, 50, "Alert B has a precedence of 50" ); is( $c->precedence, 100, "Alert C has a precedence of 100" ); # Running fix_precedences() @@ -126,5 +127,4 @@ is( $a->precedence, 1, "Alert A has a precedence of 1" ); is( $b->precedence, 2, "Alert B has a precedence of 2" ); is( $c->precedence, 3, "Alert C has a precedence of 3" ); - $schema->storage->txn_rollback(); diff --git a/t/db_dependent/Auth.t b/t/db_dependent/Auth.t index 28c1300de8..7ad430c0b3 100755 --- a/t/db_dependent/Auth.t +++ b/t/db_dependent/Auth.t @@ -32,8 +32,8 @@ my $builder = t::lib::TestBuilder->new; # FIXME: SessionStorage defaults to mysql, but it seems to break transaction # handling -t::lib::Mocks::mock_preference( 'SessionStorage', 'tmp' ); -t::lib::Mocks::mock_preference( 'PrivacyPolicyConsent', '' ); # Disabled +t::lib::Mocks::mock_preference( 'SessionStorage', 'tmp' ); +t::lib::Mocks::mock_preference( 'PrivacyPolicyConsent', '' ); # Disabled # To silence useless warnings $ENV{REMOTE_ADDR} = '127.0.0.1'; @@ -44,7 +44,7 @@ subtest 'checkauth() tests' => sub { plan tests => 11; - my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => undef } }); + my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { flags => undef } } ); # Mock a CGI object with real userid param my $cgi = Test::MockObject->new(); @@ -55,7 +55,7 @@ subtest 'checkauth() tests' => sub { if ( $var eq 'userid' ) { return $patron->userid; } } ); - $cgi->mock( 'cookie', sub { return; } ); + $cgi->mock( 'cookie', sub { return; } ); $cgi->mock( 'request_method', sub { return 'POST' } ); my $authnotrequired = 1; @@ -63,31 +63,33 @@ subtest 'checkauth() tests' => sub { is( $userid, undef, 'checkauth() returns undef for userid if no logged in user (Bug 18275)' ); - my $db_user_id = C4::Context->config('user'); + my $db_user_id = C4::Context->config('user'); my $db_user_pass = C4::Context->config('pass'); $cgi = Test::MockObject->new(); $cgi->mock( 'cookie', sub { return; } ); - $cgi->mock( 'param', sub { + $cgi->mock( + 'param', + sub { my ( $self, $param ) = @_; - if ( $param eq 'login_userid' ) { return $db_user_id; } + if ( $param eq 'login_userid' ) { return $db_user_id; } elsif ( $param eq 'login_password' ) { return $db_user_pass; } - else { return; } - }); + else { return; } + } + ); $cgi->mock( 'request_method', sub { return 'POST' } ); ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, $authnotrequired ); - is ( $userid, undef, 'If DB user is used, it should not be logged in' ); + is( $userid, undef, 'If DB user is used, it should not be logged in' ); my $is_allowed = C4::Auth::haspermission( $db_user_id, { can_do => 'everything' } ); # FIXME This belongs to t/db_dependent/Auth/haspermission.t but we do not want to c/p the pervious mock statements - ok( !$is_allowed, 'DB user should not have any permissions'); + ok( !$is_allowed, 'DB user should not have any permissions' ); subtest 'Prevent authentication when sending credential via GET' => sub { plan tests => 2; - my $patron = $builder->build_object( - { class => 'Koha::Patrons', value => { flags => 1 } } ); + my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { flags => 1 } } ); my $password = set_weak_password($patron); $cgi = Test::MockObject->new(); $cgi->mock( 'cookie', sub { return; } ); @@ -97,7 +99,7 @@ subtest 'checkauth() tests' => sub { my ( $self, $param ) = @_; if ( $param eq 'login_userid' ) { return $patron->userid; } elsif ( $param eq 'login_password' ) { return $password; } - else { return; } + else { return; } } ); @@ -126,7 +128,7 @@ subtest 'checkauth() tests' => sub { my ( $self, $param ) = @_; if ( $param eq 'login_userid' ) { return $patron->userid; } elsif ( $param eq 'login_password' ) { return $password; } - else { return; } + else { return; } } ); @@ -171,16 +173,18 @@ subtest 'checkauth() tests' => sub { my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $password = set_weak_password($patron); - $patron->password_expiration_date( dt_from_string->subtract(days => 1) )->store; + $patron->password_expiration_date( dt_from_string->subtract( days => 1 ) )->store; my $cgi_mock = Test::MockModule->new('CGI'); $cgi_mock->mock( 'request_method', sub { return 'POST' } ); - my $cgi = CGI->new; + my $cgi = CGI->new; + # Simulating the login form submission $cgi->param( 'login_userid', $patron->userid ); $cgi->param( 'login_password', $password ); - my ( $userid, $cookie, $sessionID, $flags, $template ) = C4::Auth::checkauth( $cgi, 0, { catalogue => 1 }, 'intranet', undef, undef, { do_not_print => 1 } ); + my ( $userid, $cookie, $sessionID, $flags, $template ) = + C4::Auth::checkauth( $cgi, 0, { catalogue => 1 }, 'intranet', undef, undef, { do_not_print => 1 } ); is( $template->{VARS}->{password_has_expired}, 1 ); }; @@ -209,8 +213,8 @@ subtest 'checkauth() tests' => sub { $mock2->mock( 'cookie', sub { return $sessionID; } ); # oversimplified.. my $cgi = CGI->new; - $cgi->param( -name => 'login_userid', -value => 'Bond' ); - $cgi->param( -name => 'login_password', -value => 'James Bond' ); + $cgi->param( -name => 'login_userid', -value => 'Bond' ); + $cgi->param( -name => 'login_password', -value => 'James Bond' ); $cgi->param( -name => 'koha_login_context', -value => 1 ); my ( $userid, $cookie, $flags, $template ); ( $userid, $cookie, $sessionID, $flags, $template ) = @@ -221,31 +225,35 @@ subtest 'checkauth() tests' => sub { subtest 'While still logged in, relogin with another user' => sub { plan tests => 5; - my $patron = $builder->build_object({ class => 'Koha::Patrons', value => {} }); - my $patron2 = $builder->build_object({ class => 'Koha::Patrons', value => {} }); + my $patron = $builder->build_object( { class => 'Koha::Patrons', value => {} } ); + my $patron2 = $builder->build_object( { class => 'Koha::Patrons', value => {} } ); + # Create 'former' session my $session = C4::Auth::get_session(); - $session->param( 'number', $patron->id ); - $session->param( 'id', $patron->userid ); - $session->param( 'ip', '1.2.3.4' ); - $session->param( 'lasttime', time() ); - $session->param( 'interface', 'opac' ); + $session->param( 'number', $patron->id ); + $session->param( 'id', $patron->userid ); + $session->param( 'ip', '1.2.3.4' ); + $session->param( 'lasttime', time() ); + $session->param( 'interface', 'opac' ); $session->flush; my $previous_sessionID = $session->id; - my ( $return ) = C4::Auth::check_cookie_auth( $previous_sessionID, undef, { skip_version_check => 1, remote_addr => '1.2.3.4' } ); + my ($return) = C4::Auth::check_cookie_auth( + $previous_sessionID, undef, + { skip_version_check => 1, remote_addr => '1.2.3.4' } + ); is( $return, 'ok', 'Former session in shape now' ); my $mock1 = Test::MockModule->new('C4::Auth'); - $mock1->mock( 'safe_exit', sub {} ); + $mock1->mock( 'safe_exit', sub { } ); my $mock2 = Test::MockModule->new('CGI'); $mock2->mock( 'request_method', 'POST' ); - $mock2->mock( 'cookie', sub { return $previous_sessionID; } ); # oversimplified.. - my $cgi = CGI->new; + $mock2->mock( 'cookie', sub { return $previous_sessionID; } ); # oversimplified.. + my $cgi = CGI->new; my $password = 'Incr3d1blyZtr@ng93$'; - $patron2->set_password({ password => $password }); - $cgi->param( -name => 'login_userid', -value => $patron2->userid ); - $cgi->param( -name => 'login_password', -value => $password ); + $patron2->set_password( { password => $password } ); + $cgi->param( -name => 'login_userid', -value => $patron2->userid ); + $cgi->param( -name => 'login_password', -value => $password ); $cgi->param( -name => 'koha_login_context', -value => 1 ); my ( $userid, $cookie, $sessionID, $flags, $template ) = C4::Auth::checkauth( $cgi, 0, {}, 'opac', undef, undef, { do_not_print => 1 } ); @@ -255,13 +263,13 @@ subtest 'checkauth() tests' => sub { # Similar situation: Relogin with former session of $patron, new user $patron2 has no permissions $patron2->flags(undef)->store; - $session->param( 'number', $patron->id ); - $session->param( 'id', $patron->userid ); - $session->param( 'interface', 'intranet' ); + $session->param( 'number', $patron->id ); + $session->param( 'id', $patron->userid ); + $session->param( 'interface', 'intranet' ); $session->flush; $previous_sessionID = $session->id; - $cgi->param( -name => 'login_userid', -value => $patron2->userid ); - $cgi->param( -name => 'login_password', -value => $password ); + $cgi->param( -name => 'login_userid', -value => $patron2->userid ); + $cgi->param( -name => 'login_password', -value => $password ); $cgi->param( -name => 'koha_login_context', -value => 1 ); ( $userid, $cookie, $sessionID, $flags, $template ) = C4::Auth::checkauth( $cgi, 0, { catalogue => 1 }, 'intranet', undef, undef, { do_not_print => 1 } ); @@ -273,8 +281,7 @@ subtest 'checkauth() tests' => sub { t::lib::Mocks::mock_preference( 'AutoLocation', 0 ); - my $patron = $builder->build_object( - { class => 'Koha::Patrons', value => { flags => 1 } } ); + my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { flags => 1 } } ); my $password = 'password'; $patron->set_password( { password => $password } ); $cgi = Test::MockObject->new(); @@ -285,18 +292,18 @@ subtest 'checkauth() tests' => sub { 'param', sub { my ( $self, $param ) = @_; - if ( $param eq 'login_userid' ) { return $patron->userid; } - elsif ( $param eq 'login_password' ) { return $password; } - elsif ( $param eq 'otp_token' ) { return $otp_token; } - elsif ( $param eq 'logout.x' ) { return $logout; } - else { return; } + if ( $param eq 'login_userid' ) { return $patron->userid; } + elsif ( $param eq 'login_password' ) { return $password; } + elsif ( $param eq 'otp_token' ) { return $otp_token; } + elsif ( $param eq 'logout.x' ) { return $logout; } + else { return; } } ); $cgi->mock( 'request_method', sub { return 'POST' } ); - $cgi->mock( 'cookie', sub { return $sessionID } ); + $cgi->mock( 'cookie', sub { return $sessionID } ); - my $two_factor_auth = Test::MockModule->new( 'Koha::Auth::TwoFactorAuth' ); - $two_factor_auth->mock( 'verify', sub {$verified} ); + my $two_factor_auth = Test::MockModule->new('Koha::Auth::TwoFactorAuth'); + $two_factor_auth->mock( 'verify', sub { $verified } ); my ( $userid, $cookie, $flags ); ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' ); @@ -312,22 +319,22 @@ subtest 'checkauth() tests' => sub { t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 'disabled' ); $patron->auth_method('password')->store; ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' ); - is( $userid, $patron->userid, 'Succesful login' ); - is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'Second auth not required' ); + is( $userid, $patron->userid, 'Succesful login' ); + is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'Second auth not required' ); logout($cgi); $patron->auth_method('two-factor')->store; ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' ); - is( $userid, $patron->userid, 'Succesful login' ); - is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'Second auth not required' ); + is( $userid, $patron->userid, 'Succesful login' ); + is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'Second auth not required' ); logout($cgi); t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 'enabled' ); - t::lib::Mocks::mock_config('encryption_key', '1234tH1s=t&st'); + t::lib::Mocks::mock_config( 'encryption_key', '1234tH1s=t&st' ); $patron->auth_method('password')->store; ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' ); - is( $userid, $patron->userid, 'Succesful login' ); - is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'Second auth not required' ); + is( $userid, $patron->userid, 'Succesful login' ); + is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'Second auth not required' ); logout($cgi); $patron->encode_secret('one_secret'); @@ -340,54 +347,59 @@ subtest 'checkauth() tests' => sub { # Wrong OTP token $otp_token = "wrong"; - $verified = 0; + $verified = 0; $patron->auth_method('two-factor')->store; ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' ); is( $userid, $patron->userid, 'Succesful login' ); - is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), 1, 'Second auth still required after wrong OTP token' ); + is( + C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), 1, + 'Second auth still required after wrong OTP token' + ); $otp_token = "good"; - $verified = 1; + $verified = 1; ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' ); is( $userid, $patron->userid, 'Succesful login' ); - is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), 0, 'Second auth no longer required if OTP token has been verified' ); + is( + C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), 0, + 'Second auth no longer required if OTP token has been verified' + ); logout($cgi); t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 'enforced' ); $patron->auth_method('password')->store; ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' ); - is( $userid, $patron->userid, 'Succesful login' ); - is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA-setup'), 1, 'Setup 2FA required' ); + is( $userid, $patron->userid, 'Succesful login' ); + is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA-setup'), 1, 'Setup 2FA required' ); logout($cgi); ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'opac' ); - is( $userid, $patron->userid, 'Succesful login at the OPAC' ); + is( $userid, $patron->userid, 'Succesful login at the OPAC' ); is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'No second auth required at the OPAC' ); # t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 'disabled' ); $session = C4::Auth::get_session($sessionID); - $session->param('waiting-for-2FA', 1); + $session->param( 'waiting-for-2FA', 1 ); $session->flush; - my ($auth_status, undef ) = C4::Auth::check_cookie_auth($sessionID, undef ); + my ( $auth_status, undef ) = C4::Auth::check_cookie_auth( $sessionID, undef ); is( $auth_status, 'ok', 'User authenticated, pref was disabled, access OK' ); - $session->param('waiting-for-2FA', 0); - $session->param('waiting-for-2FA-setup', 1); + $session->param( 'waiting-for-2FA', 0 ); + $session->param( 'waiting-for-2FA-setup', 1 ); $session->flush; - ($auth_status, undef ) = C4::Auth::check_cookie_auth($sessionID, undef ); + ( $auth_status, undef ) = C4::Auth::check_cookie_auth( $sessionID, undef ); is( $auth_status, 'ok', 'User waiting for 2FA setup, pref was disabled, access OK' ); }; subtest 'loggedinlibrary permission tests' => sub { plan tests => 3; - my $staff_user = $builder->build_object( - { class => 'Koha::Patrons', value => { flags => 536870916 } } ); + my $staff_user = $builder->build_object( { class => 'Koha::Patrons', value => { flags => 536870916 } } ); - my $branch = $builder->build_object({ class => 'Koha::Libraries' }); + my $branch = $builder->build_object( { class => 'Koha::Libraries' } ); my $password = set_weak_password($staff_user); - my $cgi = Test::MockObject->new(); + my $cgi = Test::MockObject->new(); $cgi->mock( 'cookie', sub { return; } ); $cgi->mock( 'param', @@ -395,25 +407,34 @@ subtest 'checkauth() tests' => sub { my ( $self, $param ) = @_; if ( $param eq 'login_userid' ) { return $staff_user->userid; } elsif ( $param eq 'login_password' ) { return $password; } - elsif ( $param eq 'branch' ) { return $branch->branchcode; } - else { return; } + elsif ( $param eq 'branch' ) { return $branch->branchcode; } + else { return; } } ); $cgi->mock( 'request_method', sub { return 'POST' } ); my ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired' ); my $sesh = C4::Auth::get_session($sessionID); - is( $sesh->param('branch'), $branch->branchcode, "If user has permission, they should be able to choose a branch" ); + is( + $sesh->param('branch'), $branch->branchcode, + "If user has permission, they should be able to choose a branch" + ); $staff_user->flags(4)->store->discard_changes; ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired' ); $sesh = C4::Auth::get_session($sessionID); - is( $sesh->param('branch'), $staff_user->branchcode, "If user has not permission, they should not be able to choose a branch" ); + is( + $sesh->param('branch'), $staff_user->branchcode, + "If user has not permission, they should not be able to choose a branch" + ); $staff_user->flags(1)->store->discard_changes; ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired' ); $sesh = C4::Auth::get_session($sessionID); - is( $sesh->param('branch'), $branch->branchcode, "If user is superlibrarian, they should be able to choose a branch" ); + is( + $sesh->param('branch'), $branch->branchcode, + "If user is superlibrarian, they should be able to choose a branch" + ); }; }; @@ -430,20 +451,23 @@ subtest 'no_set_userenv parameter tests' => sub { ok( checkpw( $patron->userid, $password, undef, undef, 1 ), 'checkpw returns true' ); C4::Context->unset_userenv; is( C4::Context->userenv, undef, 'Userenv should be undef as required' ); - C4::Context->set_userenv(0,0,0,'firstname','surname', $library->branchcode, 'Library 1', 0, '', ''); + C4::Context->set_userenv( 0, 0, 0, 'firstname', 'surname', $library->branchcode, 'Library 1', 0, '', '' ); is( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv gives correct branch' ); ok( checkpw( $patron->userid, $password, undef, undef, 1 ), 'checkpw returns true' ); is( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv branch is preserved if no_set_userenv is true' ); ok( checkpw( $patron->userid, $password, undef, undef, 0 ), 'checkpw still returns true' ); - isnt( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv branch is overwritten if no_set_userenv is false' ); + isnt( + C4::Context->userenv->{branch}, $library->branchcode, + 'Userenv branch is overwritten if no_set_userenv is false' + ); }; subtest 'checkpw lockout tests' => sub { plan tests => 5; - my $library = $builder->build_object( { class => 'Koha::Libraries' } ); - my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $password = set_weak_password($patron); t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 1 ); @@ -452,7 +476,7 @@ subtest 'checkpw lockout tests' => sub { ( $checkpw, undef, undef ) = checkpw( $patron->userid, "wrong_password", undef, undef, 1 ); is( $checkpw, 0, 'checkpw returns false when given wrong password' ); $patron = $patron->get_from_storage; - is( $patron->account_locked, 1, "Account is locked from failed login"); + is( $patron->account_locked, 1, "Account is locked from failed login" ); ( $checkpw, undef, undef ) = checkpw( $patron->userid, $password, undef, undef, 1 ); is( $checkpw, undef, 'checkpw returns undef with right password when account locked' ); ( $checkpw, undef, undef ) = checkpw( $patron->cardnumber, $password, undef, undef, 1 ); @@ -462,52 +486,55 @@ subtest 'checkpw lockout tests' => sub { # get_template_and_user tests -subtest 'get_template_and_user' => sub { # Tests for the language URL parameter +subtest 'get_template_and_user' => sub { # Tests for the language URL parameter sub MockedCheckauth { - my ($query,$authnotrequired,$flagsrequired,$type) = @_; + my ( $query, $authnotrequired, $flagsrequired, $type ) = @_; + # return vars - my $userid = 'cobain'; + my $userid = 'cobain'; my $sessionID = 234; + # we don't need to bother about permissions for this test my $flags = { - superlibrarian => 1, acquisition => 0, - borrowers => 0, - catalogue => 1, circulate => 0, - coursereserves => 0, editauthorities => 0, - editcatalogue => 0, - parameters => 0, permissions => 0, - plugins => 0, reports => 0, - reserveforothers => 0, serials => 0, - staffaccess => 0, tools => 0, - updatecharges => 0 + superlibrarian => 1, acquisition => 0, + borrowers => 0, + catalogue => 1, circulate => 0, + coursereserves => 0, editauthorities => 0, + editcatalogue => 0, + parameters => 0, permissions => 0, + plugins => 0, reports => 0, + reserveforothers => 0, serials => 0, + staffaccess => 0, tools => 0, + updatecharges => 0 }; my $session_cookie = $query->cookie( - -name => 'CGISESSID', + -name => 'CGISESSID', -value => 'nirvana', -HttpOnly => 1 ); - return ( $userid, [ $session_cookie ], $sessionID, $flags ); + return ( $userid, [$session_cookie], $sessionID, $flags ); } # Mock checkauth, build the scenario - my $auth = Test::MockModule->new( 'C4::Auth' ); + my $auth = Test::MockModule->new('C4::Auth'); $auth->mock( 'checkauth', \&MockedCheckauth ); # Make sure 'EnableOpacSearchHistory' is set - t::lib::Mocks::mock_preference('EnableOpacSearchHistory',1); + t::lib::Mocks::mock_preference( 'EnableOpacSearchHistory', 1 ); + # Enable es-ES for the OPAC and staff interfaces - t::lib::Mocks::mock_preference('OPACLanguages','en,es-ES'); - t::lib::Mocks::mock_preference('language','en,es-ES'); + t::lib::Mocks::mock_preference( 'OPACLanguages', 'en,es-ES' ); + t::lib::Mocks::mock_preference( 'language', 'en,es-ES' ); # we need a session cookie $ENV{"SERVER_PORT"} = 80; $ENV{"HTTP_COOKIE"} = 'CGISESSID=nirvana'; my $query = CGI->new; - $query->param('language','es-ES'); + $query->param( 'language', 'es-ES' ); my ( $template, $loggedinuser, $cookies ) = get_template_and_user( { @@ -520,11 +547,13 @@ subtest 'get_template_and_user' => sub { # Tests for the language URL paramete } ); - ok ( ( all { ref($_) eq 'CGI::Cookie' } @$cookies ), - 'BZ9735: the cookies array is flat' ); + ok( + ( all { ref($_) eq 'CGI::Cookie' } @$cookies ), + 'BZ9735: the cookies array is flat' + ); # new query, with non-existent language (we only have en and es-ES) - $query->param('language','tomas'); + $query->param( 'language', 'tomas' ); ( $template, $loggedinuser, $cookies ) = get_template_and_user( { @@ -537,20 +566,25 @@ subtest 'get_template_and_user' => sub { # Tests for the language URL paramete } ); - ok( ( none { $_->name eq 'KohaOpacLanguage' and $_->value eq 'tomas' } @$cookies ), - 'BZ9735: invalid language, it is not set'); + ok( + ( none { $_->name eq 'KohaOpacLanguage' and $_->value eq 'tomas' } @$cookies ), + 'BZ9735: invalid language, it is not set' + ); - ok( ( any { $_->name eq 'KohaOpacLanguage' and $_->value eq 'en' } @$cookies ), - 'BZ9735: invalid language, then default to en'); + ok( + ( any { $_->name eq 'KohaOpacLanguage' and $_->value eq 'en' } @$cookies ), + 'BZ9735: invalid language, then default to en' + ); for my $template_name ( qw( - ../../../../../../../../../../../../../../../etc/passwd - test/../../../../../../../../../../../../../../etc/passwd - /etc/passwd - test/does_not_finished_by_tt_t + ../../../../../../../../../../../../../../../etc/passwd + test/../../../../../../../../../../../../../../etc/passwd + /etc/passwd + test/does_not_finished_by_tt_t ) - ) { + ) + { eval { ( $template, $loggedinuser, $cookies ) = get_template_and_user( { @@ -562,7 +596,7 @@ subtest 'get_template_and_user' => sub { # Tests for the language URL paramete } ); }; - like ( $@, qr(bad template path), "The file $template_name should not be accessible" ); + like( $@, qr(bad template path), "The file $template_name should not be accessible" ); } ( $template, $loggedinuser, $cookies ) = get_template_and_user( { @@ -574,35 +608,35 @@ subtest 'get_template_and_user' => sub { # Tests for the language URL paramete } ); my $file_exists = ( -f $template->{filename} ) ? 1 : 0; - is ( $file_exists, 1, 'The file errors/errorpage.tt should be accessible (contains integers)' ); + is( $file_exists, 1, 'The file errors/errorpage.tt should be accessible (contains integers)' ); # Regression test for env opac search limit override - $ENV{"OPAC_SEARCH_LIMIT"} = "branch:CPL"; + $ENV{"OPAC_SEARCH_LIMIT"} = "branch:CPL"; $ENV{"OPAC_LIMIT_OVERRIDE"} = 1; - ( $template, $loggedinuser, $cookies) = get_template_and_user( + ( $template, $loggedinuser, $cookies ) = get_template_and_user( { - template_name => 'opac-main.tt', - query => $query, - type => 'opac', + template_name => 'opac-main.tt', + query => $query, + type => 'opac', authnotrequired => 1, } ); - is($template->{VARS}->{'opac_name'}, "CPL", "Opac name was set correctly"); - is($template->{VARS}->{'opac_search_limit'}, "branch:CPL", "Search limit was set correctly"); + is( $template->{VARS}->{'opac_name'}, "CPL", "Opac name was set correctly" ); + is( $template->{VARS}->{'opac_search_limit'}, "branch:CPL", "Search limit was set correctly" ); $ENV{"OPAC_SEARCH_LIMIT"} = "branch:multibranch-19"; - ( $template, $loggedinuser, $cookies) = get_template_and_user( + ( $template, $loggedinuser, $cookies ) = get_template_and_user( { - template_name => 'opac-main.tt', - query => $query, - type => 'opac', + template_name => 'opac-main.tt', + query => $query, + type => 'opac', authnotrequired => 1, } ); - is($template->{VARS}->{'opac_name'}, "multibranch-19", "Opac name was set correctly"); - is($template->{VARS}->{'opac_search_limit'}, "branch:multibranch-19", "Search limit was set correctly"); + is( $template->{VARS}->{'opac_name'}, "multibranch-19", "Opac name was set correctly" ); + is( $template->{VARS}->{'opac_search_limit'}, "branch:multibranch-19", "Search limit was set correctly" ); delete $ENV{"HTTP_COOKIE"}; }; @@ -612,66 +646,71 @@ my $input = CGI->new(); my ( $template1, $borrowernumber, $cookie ); ( $template1, $borrowernumber, $cookie ) = get_template_and_user( { - template_name => "opac-detail.tt", - type => "opac", - query => $input, + template_name => "opac-detail.tt", + type => "opac", + query => $input, authnotrequired => 1, } ); -ok( ( any { 'OPACBaseURL' eq $_ } keys %{$template1->{VARS}} ), - 'OPACBaseURL is in OPAC template' ); +ok( + ( any { 'OPACBaseURL' eq $_ } keys %{ $template1->{VARS} } ), + 'OPACBaseURL is in OPAC template' +); -my ( $template2 ); +my ($template2); ( $template2, $borrowernumber, $cookie ) = get_template_and_user( { - template_name => "catalogue/detail.tt", - type => "intranet", - query => $input, + template_name => "catalogue/detail.tt", + type => "intranet", + query => $input, authnotrequired => 1, } ); -ok( ( any { 'OPACBaseURL' eq $_ } keys %{$template2->{VARS}} ), - 'OPACBaseURL is in Staff template' ); +ok( + ( any { 'OPACBaseURL' eq $_ } keys %{ $template2->{VARS} } ), + 'OPACBaseURL is in Staff template' +); my $hash1 = hash_password('password'); my $hash2 = hash_password('password'); -ok(C4::Auth::checkpw_hash('password', $hash1), 'password validates with first hash'); -ok(C4::Auth::checkpw_hash('password', $hash2), 'password validates with second hash'); +ok( C4::Auth::checkpw_hash( 'password', $hash1 ), 'password validates with first hash' ); +ok( C4::Auth::checkpw_hash( 'password', $hash2 ), 'password validates with second hash' ); subtest 'Check value of login_attempts in checkpw' => sub { plan tests => 11; - t::lib::Mocks::mock_preference('FailedLoginAttempts', 3); + t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 3 ); # Only interested here in regular login $C4::Auth::cas = 0; $C4::Auth::ldap = 0; - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); $patron->login_attempts(2); - $patron->password('123')->store; # yes, deliberately not hashed + $patron->password('123')->store; # yes, deliberately not hashed is( $patron->account_locked, 0, 'Patron not locked' ); my @test = checkpw( $patron->userid, '123', undef, 'opac', 1 ); - # Note: 123 will not be hashed to 123 ! + + # Note: 123 will not be hashed to 123 ! is( $test[0], 0, 'checkpw should have failed' ); - $patron->discard_changes; # refresh + $patron->discard_changes; # refresh is( $patron->login_attempts, 3, 'Login attempts increased' ); is( $patron->account_locked, 1, 'Check locked status' ); # And another try to go over the limit: different return value! @test = checkpw( $patron->userid, '123', undef, 'opac', 1 ); is( @test, 0, 'checkpw failed again and returns nothing now' ); - $patron->discard_changes; # refresh + $patron->discard_changes; # refresh is( $patron->login_attempts, 3, 'Login attempts not increased anymore' ); # Administrative lockout cannot be undone? # Pass the right password now (or: add a nice mock). - my $auth = Test::MockModule->new( 'C4::Auth' ); - $auth->mock( 'checkpw_hash', sub { return 1; } ); # not for production :) + my $auth = Test::MockModule->new('C4::Auth'); + $auth->mock( 'checkpw_hash', sub { return 1; } ); # not for production :) $patron->login_attempts(0)->store; @test = checkpw( $patron->userid, '123', undef, 'opac', 1 ); is( $test[0], 1, 'Build confidence in the mock' ); @@ -679,18 +718,18 @@ subtest 'Check value of login_attempts in checkpw' => sub { is( $patron->account_locked, 1, 'Check administrative lockout' ); @test = checkpw( $patron->userid, '123', undef, 'opac', 1 ); is( @test, 0, 'checkpw gave red' ); - $patron->discard_changes; # refresh + $patron->discard_changes; # refresh is( $patron->login_attempts, -1, 'Still locked out' ); - t::lib::Mocks::mock_preference('FailedLoginAttempts', ''); # disable + t::lib::Mocks::mock_preference( 'FailedLoginAttempts', '' ); # disable is( $patron->account_locked, 1, 'Check administrative lockout without pref' ); }; subtest 'Check value of login_attempts in checkpw' => sub { plan tests => 3; - t::lib::Mocks::mock_preference('FailedLoginAttempts', 3); - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); - $patron->set_password({ password => '123', skip_validation => 1 }); + t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 3 ); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + $patron->set_password( { password => '123', skip_validation => 1 } ); my @test = checkpw( $patron->userid, '123', undef, 'opac', 1 ); is( $test[0], 1, 'Patron authenticated correctly' ); @@ -709,31 +748,30 @@ subtest '_timeout_syspref' => sub { plan tests => 6; - t::lib::Mocks::mock_preference('timeout', "100"); + t::lib::Mocks::mock_preference( 'timeout', "100" ); is( C4::Auth::_timeout_syspref, 100, ); - t::lib::Mocks::mock_preference('timeout', "2d"); - is( C4::Auth::_timeout_syspref, 2*86400, ); + t::lib::Mocks::mock_preference( 'timeout', "2d" ); + is( C4::Auth::_timeout_syspref, 2 * 86400, ); - t::lib::Mocks::mock_preference('timeout', "2D"); - is( C4::Auth::_timeout_syspref, 2*86400, ); + t::lib::Mocks::mock_preference( 'timeout', "2D" ); + is( C4::Auth::_timeout_syspref, 2 * 86400, ); - t::lib::Mocks::mock_preference('timeout', "10h"); - is( C4::Auth::_timeout_syspref, 10*3600, ); + t::lib::Mocks::mock_preference( 'timeout', "10h" ); + is( C4::Auth::_timeout_syspref, 10 * 3600, ); - t::lib::Mocks::mock_preference('timeout', "10x"); - warning_is - { is( C4::Auth::_timeout_syspref, 600, ); } - "The value of the system preference 'timeout' is not correct, defaulting to 600", + t::lib::Mocks::mock_preference( 'timeout', "10x" ); + warning_is { is( C4::Auth::_timeout_syspref, 600, ); } + "The value of the system preference 'timeout' is not correct, defaulting to 600", 'Bad values throw a warning and fallback to 600'; }; subtest 'check_cookie_auth' => sub { plan tests => 4; - t::lib::Mocks::mock_preference('timeout', "1d"); # back to default + t::lib::Mocks::mock_preference( 'timeout', "1d" ); # back to default - my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => 1 } }); + my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { flags => 1 } } ); # Mock a CGI object with real userid param my $cgi = Test::MockObject->new(); @@ -744,8 +782,8 @@ subtest 'check_cookie_auth' => sub { if ( $var eq 'userid' ) { return $patron->userid; } } ); - $cgi->mock('multi_param', sub {return q{}} ); - $cgi->mock( 'cookie', sub { return; } ); + $cgi->mock( 'multi_param', sub { return q{} } ); + $cgi->mock( 'cookie', sub { return; } ); $cgi->mock( 'request_method', sub { return 'POST' } ); $ENV{REMOTE_ADDR} = '127.0.0.1'; @@ -753,15 +791,27 @@ subtest 'check_cookie_auth' => sub { # Setting authnotrequired=1 or we wont' hit the return but the end of the sub that prints headers my ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 1 ); - my ($auth_status, $session) = C4::Auth::check_cookie_auth($sessionID); - isnt( $auth_status, 'ok', 'check_cookie_auth should not return ok if the user has not been authenticated before if no permissions needed' ); - is( $auth_status, 'anon', 'check_cookie_auth should return anon if the user has not been authenticated before and no permissions needed' ); + my ( $auth_status, $session ) = C4::Auth::check_cookie_auth($sessionID); + isnt( + $auth_status, 'ok', + 'check_cookie_auth should not return ok if the user has not been authenticated before if no permissions needed' + ); + is( + $auth_status, 'anon', + 'check_cookie_auth should return anon if the user has not been authenticated before and no permissions needed' + ); ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 1 ); - ($auth_status, $session) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1}); - isnt( $auth_status, 'ok', 'check_cookie_auth should not return ok if the user has not been authenticated before and permissions needed' ); - is( $auth_status, 'anon', 'check_cookie_auth should return anon if the user has not been authenticated before and permissions needed' ); + ( $auth_status, $session ) = C4::Auth::check_cookie_auth( $sessionID, { catalogue => 1 } ); + isnt( + $auth_status, 'ok', + 'check_cookie_auth should not return ok if the user has not been authenticated before and permissions needed' + ); + is( + $auth_status, 'anon', + 'check_cookie_auth should return anon if the user has not been authenticated before and permissions needed' + ); #FIXME We should have a test to cover 'failed' status when a user has logged in, but doesn't have permission }; @@ -770,7 +820,7 @@ subtest 'checkauth & check_cookie_auth' => sub { plan tests => 33; # flags = 4 => { catalogue => 1 } - my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => 4 } }); + my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { flags => 4 } } ); my $password = set_weak_password($patron); my $cgi_mock = Test::MockModule->new('CGI'); @@ -778,7 +828,8 @@ subtest 'checkauth & check_cookie_auth' => sub { my $cgi = CGI->new; - my $auth = Test::MockModule->new( 'C4::Auth' ); + my $auth = Test::MockModule->new('C4::Auth'); + # Tests will fail if we hit safe_exit $auth->mock( 'safe_exit', sub { return } ); @@ -788,7 +839,7 @@ subtest 'checkauth & check_cookie_auth' => sub { local *STDOUT; my $stdout; open STDOUT, '>', \$stdout; - C4::Auth::checkauth($cgi, 0, {catalogue => 1}); + C4::Auth::checkauth( $cgi, 0, { catalogue => 1 } ); like( $stdout, qr{\s*Log in to your account} ); $sessionID = ( $stdout =~ m{Set-Cookie: CGISESSID=((\d|\w)+);} ) ? $1 : undef; ok($sessionID); @@ -798,64 +849,66 @@ subtest 'checkauth & check_cookie_auth' => sub { my $first_sessionID = $sessionID; $ENV{"HTTP_COOKIE"} = "CGISESSID=$sessionID"; + # Not authenticated yet, the login form is displayed my $template; - ( $userid, $cookie, $sessionID, $flags, $template ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1}, 'intranet', undef, undef, { do_not_print => 1 } ); + ( $userid, $cookie, $sessionID, $flags, $template ) = + C4::Auth::checkauth( $cgi, 0, { catalogue => 1 }, 'intranet', undef, undef, { do_not_print => 1 } ); is( $template->{VARS}->{loginprompt}, 1, ); # Sending undefined fails obviously - my ( $auth_status, $session ) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1} ); + my ( $auth_status, $session ) = C4::Auth::check_cookie_auth( $sessionID, { catalogue => 1 } ); is( $auth_status, 'failed' ); - is( $session, undef ); + is( $session, undef ); # Simulating the login form submission - $cgi->param('login_userid', $patron->userid); - $cgi->param('login_password', $password); + $cgi->param( 'login_userid', $patron->userid ); + $cgi->param( 'login_password', $password ); # Logged in! - ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1}); + ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 0, { catalogue => 1 } ); is( $sessionID, $first_sessionID ); - is( $userid, $patron->userid ); + is( $userid, $patron->userid ); - ( $auth_status, $session ) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1}); + ( $auth_status, $session ) = C4::Auth::check_cookie_auth( $sessionID, { catalogue => 1 } ); is( $auth_status, 'ok' ); is( $session->id, $first_sessionID ); - my $patron_to_delete = $builder->build_object({ class => 'Koha::Patrons' }); - my $fresh_userid = $patron_to_delete->userid; + my $patron_to_delete = $builder->build_object( { class => 'Koha::Patrons' } ); + my $fresh_userid = $patron_to_delete->userid; $patron_to_delete->delete; - my $old_userid = $patron->userid; + my $old_userid = $patron->userid; # change the current session user's userid - $patron->userid( $fresh_userid )->store; - ( $auth_status, $session ) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1}); + $patron->userid($fresh_userid)->store; + ( $auth_status, $session ) = C4::Auth::check_cookie_auth( $sessionID, { catalogue => 1 } ); is( $auth_status, 'expired' ); - is( $session, undef ); + is( $session, undef ); # restore userid and generate a new session $patron->userid($old_userid)->store; - ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1}); + ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 0, { catalogue => 1 } ); is( $sessionID, $first_sessionID ); - is( $userid, $patron->userid ); + is( $userid, $patron->userid ); # Logging out! - $cgi->param('logout.x', 1); + $cgi->param( 'logout.x', 1 ); $cgi->delete( 'login_userid', 'login_password' ); ( $userid, $cookie, $sessionID, $flags, $template ) = C4::Auth::checkauth( $cgi, 0, { catalogue => 1 }, 'intranet', undef, undef, { do_not_print => 1 } ); is( $sessionID, undef ); is( $ENV{"HTTP_COOKIE"}, "CGISESSID=$first_sessionID", 'HTTP_COOKIE not unset' ); - ( $auth_status, $session) = C4::Auth::check_cookie_auth( $first_sessionID, {catalogue => 1} ); - is( $auth_status, "expired"); - is( $session, undef ); + ( $auth_status, $session ) = C4::Auth::check_cookie_auth( $first_sessionID, { catalogue => 1 } ); + is( $auth_status, "expired" ); + is( $session, undef ); { # Trying to access without sessionID $cgi = CGI->new; - ( $auth_status, $session) = C4::Auth::check_cookie_auth(undef, {catalogue => 1}); + ( $auth_status, $session ) = C4::Auth::check_cookie_auth( undef, { catalogue => 1 } ); is( $auth_status, 'failed' ); - is( $session, undef ); + is( $session, undef ); # This will fail on permissions undef $ENV{"HTTP_COOKIE"}; @@ -863,19 +916,19 @@ subtest 'checkauth & check_cookie_auth' => sub { local *STDOUT; my $stdout; open STDOUT, '>', \$stdout; - ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1} ); + ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 0, { catalogue => 1 } ); close STDOUT; } - is( $userid, undef ); + is( $userid, undef ); is( $sessionID, undef ); } { # First logging in $cgi = CGI->new; - $cgi->param('login_userid', $patron->userid); - $cgi->param('login_password', $password); - ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1}); + $cgi->param( 'login_userid', $patron->userid ); + $cgi->param( 'login_password', $password ); + ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 0, { catalogue => 1 } ); is( $userid, $patron->userid ); $first_sessionID = $sessionID; @@ -885,17 +938,17 @@ subtest 'checkauth & check_cookie_auth' => sub { local *STDOUT; my $stdout; open STDOUT, '>', \$stdout; - ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {borrowers => 1} ); + ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 0, { borrowers => 1 } ); close STDOUT; } - is( $userid, undef ); + is( $userid, undef ); is( $sessionID, undef ); # When calling check_cookie_auth, the session will be deleted - ( $auth_status, $session) = C4::Auth::check_cookie_auth( $first_sessionID, { borrowers => 1 } ); + ( $auth_status, $session ) = C4::Auth::check_cookie_auth( $first_sessionID, { borrowers => 1 } ); is( $auth_status, "failed" ); - is( $session, undef ); - ( $auth_status, $session) = C4::Auth::check_cookie_auth( $first_sessionID, { borrowers => 1 } ); + is( $session, undef ); + ( $auth_status, $session ) = C4::Auth::check_cookie_auth( $first_sessionID, { borrowers => 1 } ); is( $auth_status, 'expired', 'Session no longer exists' ); # NOTE: It is not what the UI is doing. @@ -905,19 +958,21 @@ subtest 'checkauth & check_cookie_auth' => sub { # Try reusing the deleted session: since it does not exist, we should get a new one now when passing correct permissions $cgi->cookie( -name => 'CGISESSID', value => $first_sessionID ); - ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1}); + ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 0, { catalogue => 1 } ); is( $userid, $patron->userid ); - isnt( $sessionID, undef, 'Check if we have a sessionID' ); + isnt( $sessionID, undef, 'Check if we have a sessionID' ); isnt( $sessionID, $first_sessionID, 'New value expected' ); - ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID, {catalogue => 1} ); + ( $auth_status, $session ) = C4::Auth::check_cookie_auth( $sessionID, { catalogue => 1 } ); is( $auth_status, "ok" ); is( $session->id, $sessionID, 'Same session' ); + # Two additional tests on userenv is( C4::Context->userenv->{id}, $userid, 'Check userid in userenv' ); } }; subtest 'Userenv clearing in check_cookie_auth' => sub { + # Note: We did already test userenv for a logged-in user in previous subtest plan tests => 8; @@ -926,48 +981,48 @@ subtest 'Userenv clearing in check_cookie_auth' => sub { # Create a new anonymous session by passing a fake session ID $cgi->cookie( -name => 'CGISESSID', -value => 'fake_sessionID' ); - my ($userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 1); - my ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID ); - is( $auth_status, 'anon', 'Should be anonymous' ); - is( defined C4::Context->userenv, 1, 'There should be a userenv' ); - is( C4::Context->userenv->{id}, q{}, 'userid should be empty string' ); + my ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 1 ); + my ( $auth_status, $session ) = C4::Auth::check_cookie_auth($sessionID); + is( $auth_status, 'anon', 'Should be anonymous' ); + is( defined C4::Context->userenv, 1, 'There should be a userenv' ); + is( C4::Context->userenv->{id}, q{}, 'userid should be empty string' ); # Make the session expire now, check_cookie_auth will delete it - $session->param('lasttime', time() - 1200 ); + $session->param( 'lasttime', time() - 1200 ); $session->flush; - ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID ); - is( $auth_status, 'expired', 'Should be expired' ); - is( C4::Context->userenv, undef, 'Environment should be cleared too' ); + ( $auth_status, $session ) = C4::Auth::check_cookie_auth($sessionID); + is( $auth_status, 'expired', 'Should be expired' ); + is( C4::Context->userenv, undef, 'Environment should be cleared too' ); # Show that we clear the userenv again: set up env and check deleted session - C4::Context->set_userenv; # empty + C4::Context->set_userenv; # empty is( defined C4::Context->userenv, 1, 'There should be an empty userenv again' ); - ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID ); - is( $auth_status, 'expired', 'Should be expired already' ); - is( C4::Context->userenv, undef, 'Environment should be cleared again' ); + ( $auth_status, $session ) = C4::Auth::check_cookie_auth($sessionID); + is( $auth_status, 'expired', 'Should be expired already' ); + is( C4::Context->userenv, undef, 'Environment should be cleared again' ); }; subtest 'create_basic_session tests' => sub { plan tests => 13; - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); - my $session = C4::Auth::create_basic_session({ patron => $patron, interface => 'opac' }); + my $session = C4::Auth::create_basic_session( { patron => $patron, interface => 'opac' } ); - isnt($session->id, undef, 'A new sessionID was created'); - is( $session->param('number'), $patron->borrowernumber, 'Session parameter number matches' ); - is( $session->param('id'), $patron->userid, 'Session parameter id matches' ); - is( $session->param('cardnumber'), $patron->cardnumber, 'Session parameter cardnumber matches' ); - is( $session->param('firstname'), $patron->firstname, 'Session parameter firstname matches' ); - is( $session->param('surname'), $patron->surname, 'Session parameter surname matches' ); - is( $session->param('branch'), $patron->branchcode, 'Session parameter branch matches' ); - is( $session->param('branchname'), $patron->library->branchname, 'Session parameter branchname matches' ); - is( $session->param('flags'), $patron->flags, 'Session parameter flags matches' ); - is( $session->param('emailaddress'), $patron->email, 'Session parameter emailaddress matches' ); - is( $session->param('ip'), $session->remote_addr(), 'Session parameter ip matches' ); - is( $session->param('interface'), 'opac', 'Session parameter interface matches' ); + isnt( $session->id, undef, 'A new sessionID was created' ); + is( $session->param('number'), $patron->borrowernumber, 'Session parameter number matches' ); + is( $session->param('id'), $patron->userid, 'Session parameter id matches' ); + is( $session->param('cardnumber'), $patron->cardnumber, 'Session parameter cardnumber matches' ); + is( $session->param('firstname'), $patron->firstname, 'Session parameter firstname matches' ); + is( $session->param('surname'), $patron->surname, 'Session parameter surname matches' ); + is( $session->param('branch'), $patron->branchcode, 'Session parameter branch matches' ); + is( $session->param('branchname'), $patron->library->branchname, 'Session parameter branchname matches' ); + is( $session->param('flags'), $patron->flags, 'Session parameter flags matches' ); + is( $session->param('emailaddress'), $patron->email, 'Session parameter emailaddress matches' ); + is( $session->param('ip'), $session->remote_addr(), 'Session parameter ip matches' ); + is( $session->param('interface'), 'opac', 'Session parameter interface matches' ); - $session = C4::Auth::create_basic_session({ patron => $patron, interface => 'staff' }); + $session = C4::Auth::create_basic_session( { patron => $patron, interface => 'staff' } ); is( $session->param('interface'), 'intranet', 'Staff interface gets converted to intranet' ); }; @@ -976,21 +1031,24 @@ subtest 'check_cookie_auth overwriting interface already set' => sub { t::lib::Mocks::mock_preference( 'SessionRestrictionByIP', 0 ); - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $session = C4::Auth::get_session(); - $session->param( 'number', $patron->id ); - $session->param( 'id', $patron->userid ); - $session->param( 'ip', '1.2.3.4' ); - $session->param( 'lasttime', time() ); - $session->param( 'interface', 'opac' ); + $session->param( 'number', $patron->id ); + $session->param( 'id', $patron->userid ); + $session->param( 'ip', '1.2.3.4' ); + $session->param( 'lasttime', time() ); + $session->param( 'interface', 'opac' ); $session->flush; C4::Context->interface('intranet'); C4::Auth::check_cookie_auth( $session->id ); is( C4::Context->interface, 'intranet', 'check_cookie_auth did not overwrite' ); - delete $C4::Context::context->{interface}; # clear context interface + delete $C4::Context::context->{interface}; # clear context interface C4::Auth::check_cookie_auth( $session->id ); - is( C4::Context->interface, 'opac', 'check_cookie_auth used interface from session when context interface was empty' ); + is( + C4::Context->interface, 'opac', + 'check_cookie_auth used interface from session when context interface was empty' + ); t::lib::Mocks::mock_preference( 'SessionRestrictionByIP', 1 ); }; @@ -1521,7 +1579,6 @@ subtest 'AutoSelfCheckAllowed' => sub { t::lib::Mocks::mock_preference( 'AutoSelfCheckID', '' ); t::lib::Mocks::mock_preference( 'AutoSelfCheckPass', '' ); - # Credential prefs are empty, cannot access sco { # checkauth will redirect and safe_exit if not authenticated and not authorized diff --git a/t/db_dependent/Auth/haspermission.t b/t/db_dependent/Auth/haspermission.t index 6cbb044561..2305573910 100755 --- a/t/db_dependent/Auth/haspermission.t +++ b/t/db_dependent/Auth/haspermission.t @@ -55,7 +55,7 @@ my $borr3 = $builder->build( source => 'Borrower', value => { surname => 'Bor2', - flags => 2**13, # top level tools + flags => 2**13, # top level tools }, } ); @@ -85,7 +85,7 @@ subtest 'undef top level tests' => sub { plan tests => 1; my $pass = haspermission( $borr2->{userid} ); - ok($pass, "let through undef privs"); + ok( $pass, "let through undef privs" ); #throws_ok { my $r = haspermission( $borr1->{userid} ); } #'Koha::Exceptions::WrongParameter', @@ -115,7 +115,7 @@ subtest 'hashref top level AND tests' => sub { # Check top level permission for superlibrarian my $r = - haspermission( $borr1->{userid}, { circulate => 1 } ); + haspermission( $borr1->{userid}, { circulate => 1 } ); is( ref($r), 'HASH', 'Superlibrarian/circulate' ); # Check specific top level permission(s) for borr2 @@ -145,8 +145,10 @@ subtest 'hashref top level AND tests' => sub { is( ref($r), 'HASH', 'Superlibrarian/tools edit_additional_contents' ); $r = haspermission( $borr2->{userid}, { acquisition => 'budget_manage' } ); is( ref($r), 'HASH', 'Borrower2/acq budget_manage' ); - $r = haspermission( $borr2->{userid}, - { acquisition => 'budget_manage', tools => 'edit_additional_contents' } ); + $r = haspermission( + $borr2->{userid}, + { acquisition => 'budget_manage', tools => 'edit_additional_contents' } + ); is( $r, 0, 'Borrower2 (/acquisition|budget_manage AND /tools|edit_additional_contents) should fail' ); $r = haspermission( $borr2->{userid}, @@ -172,8 +174,8 @@ subtest 'hashref top level AND tests' => sub { $borr2->{userid}, { tools => { - 'upload_local_cover_images' => 1, - 'edit_additional_contents' => 1 + 'upload_local_cover_images' => 1, + 'edit_additional_contents' => 1 }, } ); @@ -181,7 +183,7 @@ subtest 'hashref top level AND tests' => sub { $r = haspermission( $borr2->{userid}, { - tools => [ 'upload_local_cover_images', 'edit_additional_contents'], + tools => [ 'upload_local_cover_images', 'edit_additional_contents' ], } ); is( ref($r), 'HASH', 'Borrower2 (/tools|upload_local_cover_image OR /tools|edit_additional_contents) granular' ); @@ -193,19 +195,19 @@ subtest 'arrayref top level OR tests' => sub { # Check top level permission for superlibrarian my $r = - haspermission( $borr1->{userid}, [ 'circulate', 'editcatalogue' ] ); + haspermission( $borr1->{userid}, [ 'circulate', 'editcatalogue' ] ); is( ref($r), 'HASH', 'Superlibrarian/circulate' ); # Check specific top level permission(s) for borr2 $r = haspermission( $borr2->{userid}, [ 'circulate', 'updatecharges' ] ); is( ref($r), 'HASH', 'Borrower2/circulate OR Borrower2/updatecharges' ); - $r = haspermission( $borr2->{userid}, ['updatecharges', 'serials' ] ); + $r = haspermission( $borr2->{userid}, [ 'updatecharges', 'serials' ] ); is( $r, 0, 'Borrower2/updatecharges OR Borrower2/serials should fail' ); # Check granular permission with 1: means all subpermissions - $r = haspermission( $borr1->{userid}, [ 'tools' ] ); + $r = haspermission( $borr1->{userid}, ['tools'] ); is( ref($r), 'HASH', 'Superlibrarian/tools granular all' ); - $r = haspermission( $borr2->{userid}, [ 'tools' ] ); + $r = haspermission( $borr2->{userid}, ['tools'] ); is( $r, 0, 'Borrower2/tools granular all should fail' ); # Check granular permission with *: means at least one subpermission @@ -222,10 +224,12 @@ subtest 'arrayref top level OR tests' => sub { $r = haspermission( $borr1->{userid}, [ { tools => 'edit_additional_contents' } ] ); is( ref($r), 'HASH', 'Superlibrarian/tools edit_additional_contents' ); $r = - haspermission( $borr2->{userid}, [ { acquisition => 'budget_manage' } ] ); + haspermission( $borr2->{userid}, [ { acquisition => 'budget_manage' } ] ); is( ref($r), 'HASH', 'Borrower2/acq budget_manage' ); - $r = haspermission( $borr2->{userid}, - [ { acquisition => 'budget_manage'}, { tools => 'edit_additional_contents' } ] ); + $r = haspermission( + $borr2->{userid}, + [ { acquisition => 'budget_manage' }, { tools => 'edit_additional_contents' } ] + ); is( ref($r), 'HASH', 'Borrower2/two granular OR should pass' ); $r = haspermission( $borr2->{userid}, diff --git a/t/db_dependent/AuthUtils.t b/t/db_dependent/AuthUtils.t index fa5bc76038..b587ac28a0 100755 --- a/t/db_dependent/AuthUtils.t +++ b/t/db_dependent/AuthUtils.t @@ -50,8 +50,7 @@ my $category3 = $builder->build_object( my $category4 = $builder->build_object( { class => 'Koha::Patron::Categories', - value => - { min_password_length => undef, require_strong_password => undef } + value => { min_password_length => undef, require_strong_password => undef } } ); @@ -72,54 +71,45 @@ subtest 'is_password_valid for category' => sub { t::lib::Mocks::mock_preference( 'minPasswordLength', 3 ); #Category 1 - override=>1, length=>15, strong=>1 - ( $is_valid, $error ) = - Koha::AuthUtils::is_password_valid( $p_5l_strong, $category1 ); + ( $is_valid, $error ) = Koha::AuthUtils::is_password_valid( $p_5l_strong, $category1 ); is( $is_valid, 0, 'min password length for this category is 15' ); is( $error, 'too_short', 'min password length for this category is 15' ); - ( $is_valid, $error ) = - Koha::AuthUtils::is_password_valid( $p_15l_weak, $category1 ); + ( $is_valid, $error ) = Koha::AuthUtils::is_password_valid( $p_15l_weak, $category1 ); is( $is_valid, 0, 'password should be strong for this category' ); is( $error, 'too_weak', 'password should be strong for this category' ); - ( $is_valid, $error ) = - Koha::AuthUtils::is_password_valid( $p_15l_strong, $category1 ); + ( $is_valid, $error ) = Koha::AuthUtils::is_password_valid( $p_15l_strong, $category1 ); is( $is_valid, 1, 'password should be ok for this category' ); #Category 2 - override=>1, length=>5, strong=>0 - ( $is_valid, $error ) = - Koha::AuthUtils::is_password_valid( $p_3l_strong, $category2 ); + ( $is_valid, $error ) = Koha::AuthUtils::is_password_valid( $p_3l_strong, $category2 ); is( $is_valid, 0, 'min password length for this category is 5' ); is( $error, 'too_short', 'min password length for this category is 5' ); - ( $is_valid, $error ) = - Koha::AuthUtils::is_password_valid( $p_5l_weak, $category2 ); + ( $is_valid, $error ) = Koha::AuthUtils::is_password_valid( $p_5l_weak, $category2 ); is( $is_valid, 1, 'password should be ok for this category' ); #Category 3 - override=>0, length=>20, strong=>0 - ( $is_valid, $error ) = - Koha::AuthUtils::is_password_valid( $p_3l_weak, $category3 ); + ( $is_valid, $error ) = Koha::AuthUtils::is_password_valid( $p_3l_weak, $category3 ); is( $is_valid, 0, 'password should be strong' ); is( $error, 'too_weak', 'password should be strong' ); - ( $is_valid, $error ) = - Koha::AuthUtils::is_password_valid( $p_3l_strong, $category3 ); + ( $is_valid, $error ) = Koha::AuthUtils::is_password_valid( $p_3l_strong, $category3 ); is( $is_valid, 1, 'password should be ok' ); #Category 4 - default settings - override=>undef, length=>undef, strong=>undef - ( $is_valid, $error ) = - Koha::AuthUtils::is_password_valid( $p_3l_weak, $category4 ); + ( $is_valid, $error ) = Koha::AuthUtils::is_password_valid( $p_3l_weak, $category4 ); is( $is_valid, 1, 'password should be ok' ); t::lib::Mocks::mock_preference( 'minPasswordLength', 0 ); - ( $is_valid, $error ) = - Koha::AuthUtils::is_password_valid( $p_2l, $category4 ); + ( $is_valid, $error ) = Koha::AuthUtils::is_password_valid( $p_2l, $category4 ); is( $is_valid, 0, '3 is absolute minimum password' ); is( $error, 'too_short', '3 is absolute minimum password' ); throws_ok { Koha::AuthUtils::is_password_valid($p_2l); } 'Koha::Exceptions::Password::NoCategoryProvided', - 'Category should always be provided'; + 'Category should always be provided'; }; @@ -133,31 +123,27 @@ subtest 'generate_password for category' => sub { #Category 4 my $password = Koha::AuthUtils::generate_password($category4); - ( $is_valid, $error ) = - Koha::AuthUtils::is_password_valid( $password, $category4 ); + ( $is_valid, $error ) = Koha::AuthUtils::is_password_valid( $password, $category4 ); is( $is_valid, 1, 'password should be ok' ); #Category 3 $password = Koha::AuthUtils::generate_password($category3); - ( $is_valid, $error ) = - Koha::AuthUtils::is_password_valid( $password, $category3 ); + ( $is_valid, $error ) = Koha::AuthUtils::is_password_valid( $password, $category3 ); is( $is_valid, 1, 'password should be ok' ); #Category 2 $password = Koha::AuthUtils::generate_password($category2); - ( $is_valid, $error ) = - Koha::AuthUtils::is_password_valid( $password, $category2 ); + ( $is_valid, $error ) = Koha::AuthUtils::is_password_valid( $password, $category2 ); is( $is_valid, 1, 'password should be ok' ); #Category 1 $password = Koha::AuthUtils::generate_password($category1); - ( $is_valid, $error ) = - Koha::AuthUtils::is_password_valid( $password, $category1 ); + ( $is_valid, $error ) = Koha::AuthUtils::is_password_valid( $password, $category1 ); is( $is_valid, 1, 'password should be ok' ); throws_ok { Koha::AuthUtils::generate_password(); } 'Koha::Exceptions::Password::NoCategoryProvided', - 'Category should always be provided'; + 'Category should always be provided'; }; diff --git a/t/db_dependent/Auth_with_cas.t b/t/db_dependent/Auth_with_cas.t index be33224325..d223e5d4c4 100755 --- a/t/db_dependent/Auth_with_cas.t +++ b/t/db_dependent/Auth_with_cas.t @@ -28,43 +28,50 @@ use C4::Context; use Koha::Database; BEGIN { - use_ok('C4::Auth_with_cas', qw( check_api_auth_cas checkpw_cas login_cas logout_cas login_cas_url )); - can_ok('C4::Auth_with_cas', qw/ + use_ok( 'C4::Auth_with_cas', qw( check_api_auth_cas checkpw_cas login_cas logout_cas login_cas_url ) ); + can_ok( + 'C4::Auth_with_cas', qw/ check_api_auth_cas checkpw_cas login_cas logout_cas login_cas_url - /); + / + ); } my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; C4::Context->disable_syspref_cache(); -t::lib::Mocks::mock_preference('OPACBaseURL','http://localhost'); -t::lib::Mocks::mock_preference('staffClientBaseURL','http://localhost:8080'); +t::lib::Mocks::mock_preference( 'OPACBaseURL', 'http://localhost' ); +t::lib::Mocks::mock_preference( 'staffClientBaseURL', 'http://localhost:8080' ); -my $opac_base_url = C4::Context->preference('OpacBaseURL'); +my $opac_base_url = C4::Context->preference('OpacBaseURL'); my $staff_base_url = C4::Context->preference('staffClientBaseURL'); -my $query_string = 'ticket=foo&bar=baz'; +my $query_string = 'ticket=foo&bar=baz'; $ENV{QUERY_STRING} = $query_string; -$ENV{SCRIPT_NAME} = '/cgi-bin/koha/opac-user.pl'; +$ENV{SCRIPT_NAME} = '/cgi-bin/koha/opac-user.pl'; my $cgi = CGI->new($query_string); $cgi->delete('ticket'); # _url_with_get_params tests -is(C4::Auth_with_cas::_url_with_get_params($cgi, 'opac'), +is( + C4::Auth_with_cas::_url_with_get_params( $cgi, 'opac' ), "$opac_base_url/cgi-bin/koha/opac-user.pl?bar=baz", - "_url_with_get_params should return URL without deleted parameters (Bug 12398)"); + "_url_with_get_params should return URL without deleted parameters (Bug 12398)" +); $ENV{SCRIPT_NAME} = '/cgi-bin/koha/circ/circulation-home.pl'; + # intranet url test -is(C4::Auth_with_cas::_url_with_get_params($cgi, 'intranet'), +is( + C4::Auth_with_cas::_url_with_get_params( $cgi, 'intranet' ), "$staff_base_url/cgi-bin/koha/circ/circulation-home.pl?bar=baz", - "Intranet URL should be returned when using intranet login (Bug 13507)"); + "Intranet URL should be returned when using intranet login (Bug 13507)" +); subtest 'logout_cas() tests' => sub { @@ -73,12 +80,16 @@ subtest 'logout_cas() tests' => sub { my $cas_url = "https://mycasserver.url"; my $auth_with_cas_mock = Test::MockModule->new('C4::Auth_with_cas'); - $auth_with_cas_mock->mock( '_get_cas_and_service', sub - { + $auth_with_cas_mock->mock( + '_get_cas_and_service', + sub { my $cas = Test::MockObject->new(); - $cas->mock( 'logout_url', sub { - return "$cas_url/logout/?url=https://mykoha.url"; - }); + $cas->mock( + 'logout_url', + sub { + return "$cas_url/logout/?url=https://mykoha.url"; + } + ); return ( $cas, "$cas_url?logout.x=1" ); } ); @@ -88,18 +99,21 @@ subtest 'logout_cas() tests' => sub { # Yeah, this gets funky my $cgi_mock = Test::MockModule->new('CGI'); - $cgi_mock->mock( 'redirect', sub { - my ( $self, $url ) = @_; - return $url; - }); + $cgi_mock->mock( + 'redirect', + sub { + my ( $self, $url ) = @_; + return $url; + } + ); # Test CAS 2.0 behavior - $cas_version = 2; + $cas_version = 2; $expected_logout_url = "$cas_url/logout/?url=https://mykoha.url"; my $redirect_output = ''; close(STDOUT); - open(STDOUT, ">", \$redirect_output) or die "Error opening STDOUT"; + open( STDOUT, ">", \$redirect_output ) or die "Error opening STDOUT"; t::lib::Mocks::mock_preference( 'casServerVersion', $cas_version ); C4::Auth_with_cas::logout_cas( CGI->new, 'anything' ); @@ -109,9 +123,9 @@ subtest 'logout_cas() tests' => sub { # Test CAS 3.0 behavior $redirect_output = ''; close(STDOUT); - open(STDOUT, ">", \$redirect_output) or die "Error opening STDOUT"; + open( STDOUT, ">", \$redirect_output ) or die "Error opening STDOUT"; - $cas_version = 3; + $cas_version = 3; $expected_logout_url = "$cas_url/logout/?service=https://mykoha.url"; t::lib::Mocks::mock_preference( 'casServerVersion', $cas_version ); diff --git a/t/db_dependent/Auth_with_ldap.t b/t/db_dependent/Auth_with_ldap.t index 6c35aa5e5f..3b88d0e7a1 100755 --- a/t/db_dependent/Auth_with_ldap.t +++ b/t/db_dependent/Auth_with_ldap.t @@ -64,7 +64,7 @@ my $desired_admin_bind_result = 'error'; my $desired_search_result = 'error'; my $desired_count_result = 1; my $desired_bind_result = 'error'; -my $remaining_entry = 1; +my $remaining_entry = 1; my $ret; # Mock the context module @@ -81,8 +81,8 @@ $net_ldap->mock( # We were asked to fail the LDAP conexion return; - } - else { + } else { + # Return a mocked Net::LDAP object (Test::MockObject) return mock_net_ldap(); } @@ -94,17 +94,13 @@ my $branchcode = $builder->build( { source => 'Branch' } )->{branchcode}; my $attr_type = $builder->build( { source => 'BorrowerAttributeType', - value => { - category_code => $categorycode - } + value => { category_code => $categorycode } } ); -my $attr_type2 = $builder->build( +my $attr_type2 = $builder->build( { source => 'BorrowerAttributeType', - value => { - category_code => $categorycode - } + value => { category_code => $categorycode } } ); @@ -130,14 +126,14 @@ $builder->build( } ); -my $patron = Koha::Patrons->find($borrower->{borrowernumber}); +my $patron = Koha::Patrons->find( $borrower->{borrowernumber} ); # C4::Auth_with_ldap needs several stuff set first ^^^ -use_ok('C4::Auth_with_ldap', qw( checkpw_ldap )); +use_ok( 'C4::Auth_with_ldap', qw( checkpw_ldap ) ); can_ok( 'C4::Auth_with_ldap', qw/ - checkpw_ldap - search_method / + checkpw_ldap + search_method / ); subtest 'checkpw_ldap tests' => sub { @@ -147,11 +143,10 @@ subtest 'checkpw_ldap tests' => sub { ## Connection fail tests $desired_connection_result = 'error'; warning_is { - $ret = - C4::Auth_with_ldap::checkpw_ldap( 'hola', password => 'hey' ); + $ret = C4::Auth_with_ldap::checkpw_ldap( 'hola', password => 'hey' ); } 'LDAP connexion failed', - 'checkpw_ldap prints correct warning if LDAP conexion fails'; + 'checkpw_ldap prints correct warning if LDAP conexion fails'; is( $ret, 0, 'checkpw_ldap returns 0 if LDAP conexion fails' ); ## Connection success tests @@ -165,37 +160,41 @@ subtest 'checkpw_ldap tests' => sub { $desired_authentication_result = 'success'; $anonymous_bind = 1; - $desired_admin_bind_result = 'error'; + $desired_admin_bind_result = 'error'; $desired_search_result = 'error'; reload_ldap_module(); warning_like { - $ret = C4::Auth_with_ldap::checkpw_ldap( 'hola', - password => 'hey' ); + $ret = C4::Auth_with_ldap::checkpw_ldap( + 'hola', + password => 'hey' + ); } qr/Anonymous LDAP bind failed: LDAP error #1: error_name/, - 'checkpw_ldap prints correct warning if LDAP anonymous bind fails'; + 'checkpw_ldap prints correct warning if LDAP anonymous bind fails'; is( $ret, 0, 'checkpw_ldap returns 0 if LDAP anonymous bind fails' ); $anonymous_bind = 0; - $user = undef; - $pass = undef; + $user = undef; + $pass = undef; reload_ldap_module(); warning_like { - $ret = C4::Auth_with_ldap::checkpw_ldap( 'hola', - password => 'hey' ); + $ret = C4::Auth_with_ldap::checkpw_ldap( + 'hola', + password => 'hey' + ); } qr/LDAP bind failed as kohauser hola: LDAP error #1: error_name/, - 'checkpw_ldap prints correct warning if LDAP bind_by_auth fails'; + 'checkpw_ldap prints correct warning if LDAP bind_by_auth fails'; is( $ret, 0, 'checkpw_ldap returns 0 if LDAP bind_by_auth fails' ); $desired_authentication_result = 'success'; $anonymous_bind = 1; - $desired_admin_bind_result = 'success'; + $desired_admin_bind_result = 'success'; $desired_search_result = 'success'; $desired_count_result = 1; - $desired_bind_result = 'success'; + $desired_bind_result = 'success'; $update = 1; reload_ldap_module(); @@ -210,15 +209,13 @@ subtest 'checkpw_ldap tests' => sub { $auth->mock( 'ldap_entry_2_hash', sub { - return ( - $attr_type2->{code}, 'BAR' - ); + return ( $attr_type2->{code}, 'BAR' ); } ); C4::Auth_with_ldap::checkpw_ldap( 'hola', password => 'hey' ); ok( - Koha::Patrons->find($borrower->{borrowernumber})->extended_attributes->count, + Koha::Patrons->find( $borrower->{borrowernumber} )->extended_attributes->count, 'Extended attributes are not deleted' ); @@ -264,10 +261,11 @@ subtest 'checkpw_ldap tests' => sub { is( $patrons->count, 1, 'New patron added with "replicate"' ); $patron = $patrons->next; - my $queued_notices = Koha::Notice::Messages->search( - { borrowernumber => $patron->borrowernumber } ); - is( $queued_notices->count, 1, - "One notice queued when `welcome` is set" ); + my $queued_notices = Koha::Notice::Messages->search( { borrowernumber => $patron->borrowernumber } ); + is( + $queued_notices->count, 1, + "One notice queued when `welcome` is set" + ); my $THE_notice = $queued_notices->next; is( $THE_notice->status, 'failed', "The notice was sent immediately" ); @@ -288,6 +286,7 @@ subtest 'checkpw_ldap tests' => sub { $patron_replicated_from_auth->delete; $auth->unmock('ldap_entry_2_hash'); + # end replicate testing $desired_count_result = 0; @@ -295,31 +294,39 @@ subtest 'checkpw_ldap tests' => sub { reload_ldap_module(); warning_like { - $ret = C4::Auth_with_ldap::checkpw_ldap( 'hola', - password => 'hey' ); + $ret = C4::Auth_with_ldap::checkpw_ldap( + 'hola', + password => 'hey' + ); } qr/LDAP bind failed as kohauser hola: LDAP error #1: error_name/, - 'checkpw_ldap prints correct warning if LDAP bind fails'; - is( $ret, -1, - 'checkpw_ldap returns -1 LDAP bind fails for user (Bug 8148)' ); + 'checkpw_ldap prints correct warning if LDAP bind fails'; + is( + $ret, -1, + 'checkpw_ldap returns -1 LDAP bind fails for user (Bug 8148)' + ); # regression tests for bug 12831 $desired_authentication_result = 'error'; $anonymous_bind = 0; - $desired_admin_bind_result = 'error'; + $desired_admin_bind_result = 'error'; $desired_search_result = 'success'; $desired_count_result = 0; # user auth problem - $desired_bind_result = 'error'; + $desired_bind_result = 'error'; reload_ldap_module(); warning_like { - $ret = C4::Auth_with_ldap::checkpw_ldap( 'hola', - password => 'hey' ); + $ret = C4::Auth_with_ldap::checkpw_ldap( + 'hola', + password => 'hey' + ); } qr/LDAP bind failed as kohauser hola: LDAP error #1: error_name/, - 'checkpw_ldap prints correct warning if LDAP bind fails'; - is( $ret, 0, - 'checkpw_ldap returns 0 LDAP bind fails for user (Bug 12831)' ); + 'checkpw_ldap prints correct warning if LDAP bind fails'; + is( + $ret, 0, + 'checkpw_ldap returns 0 LDAP bind fails for user (Bug 12831)' + ); }; @@ -338,53 +345,61 @@ subtest 'checkpw_ldap tests' => sub { reload_ldap_module(); warning_like { - $ret = C4::Auth_with_ldap::checkpw_ldap( 'hola', - password => 'hey' ); + $ret = C4::Auth_with_ldap::checkpw_ldap( + 'hola', + password => 'hey' + ); } -qr/LDAP bind failed as ldapuser cn=Manager,dc=metavore,dc=com: LDAP error #1: error_name/, - 'checkpw_ldap prints correct warning if LDAP bind fails'; + qr/LDAP bind failed as ldapuser cn=Manager,dc=metavore,dc=com: LDAP error #1: error_name/, + 'checkpw_ldap prints correct warning if LDAP bind fails'; is( $ret, 0, 'checkpw_ldap returns 0 if bind fails' ); $anonymous_bind = 1; $desired_admin_bind_result = 'success'; - $desired_bind_result = 'error'; - $desired_search_result = 'success'; - $desired_count_result = 1; + $desired_bind_result = 'error'; + $desired_search_result = 'success'; + $desired_count_result = 1; reload_ldap_module(); warning_like { - $ret = C4::Auth_with_ldap::checkpw_ldap( 'hola', - password => 'hey' ); + $ret = C4::Auth_with_ldap::checkpw_ldap( + 'hola', + password => 'hey' + ); } -qr/LDAP Auth rejected : invalid password for user 'hola'./, - 'checkpw_ldap prints correct warning if LDAP bind fails'; + qr/LDAP Auth rejected : invalid password for user 'hola'./, + 'checkpw_ldap prints correct warning if LDAP bind fails'; is( $ret, -1, 'checkpw_ldap returns -1 if bind fails (Bug 8148)' ); # Non-anonymous bind $anonymous_bind = 0; $desired_admin_bind_result = 'error'; - $desired_bind_result = 'error'; + $desired_bind_result = 'error'; reload_ldap_module(); warning_like { - $ret = C4::Auth_with_ldap::checkpw_ldap( 'hola', - password => 'hey' ); + $ret = C4::Auth_with_ldap::checkpw_ldap( + 'hola', + password => 'hey' + ); } -qr/LDAP bind failed as ldapuser cn=Manager,dc=metavore,dc=com: LDAP error #1: error_name/, - 'checkpw_ldap prints correct warning if LDAP bind fails'; + qr/LDAP bind failed as ldapuser cn=Manager,dc=metavore,dc=com: LDAP error #1: error_name/, + 'checkpw_ldap prints correct warning if LDAP bind fails'; is( $ret, 0, 'checkpw_ldap returns 0 if bind fails' ); $anonymous_bind = 0; $desired_admin_bind_result = 'success'; - $desired_bind_result = 'error'; + $desired_bind_result = 'error'; reload_ldap_module(); warning_like { - $ret = C4::Auth_with_ldap::checkpw_ldap( 'hola', - password => 'hey' ); + $ret = C4::Auth_with_ldap::checkpw_ldap( + 'hola', + password => 'hey' + ); } -qr/LDAP Auth rejected : invalid password for user 'hola'./, - 'checkpw_ldap prints correct warning if LDAP bind fails'; + qr/LDAP Auth rejected : invalid password for user 'hola'./, + 'checkpw_ldap prints correct warning if LDAP bind fails'; is( $ret, -1, 'checkpw_ldap returns -1 if bind fails (Bug 8148)' ); }; @@ -492,20 +507,23 @@ subtest 'search_method tests' => sub { my $ldap = mock_net_ldap(); # Null params tests - is( C4::Auth_with_ldap::search_method( $ldap, undef ), - undef, 'search_method returns undef on undefined userid' ); - is( C4::Auth_with_ldap::search_method( undef, 'undef' ), - undef, 'search_method returns undef on undefined ldap object' ); + is( + C4::Auth_with_ldap::search_method( $ldap, undef ), + undef, 'search_method returns undef on undefined userid' + ); + is( + C4::Auth_with_ldap::search_method( undef, 'undef' ), + undef, 'search_method returns undef on undefined ldap object' + ); # search ->code and !->code $desired_search_result = 'error'; reload_ldap_module(); - my $eval_retval = - eval { $ret = C4::Auth_with_ldap::search_method( $ldap, 'undef' ); }; + my $eval_retval = eval { $ret = C4::Auth_with_ldap::search_method( $ldap, 'undef' ); }; like( $@, qr/LDAP search failed to return object : 1/, -'search_method prints correct warning when db->search returns error code' + 'search_method prints correct warning when db->search returns error code' ); }; @@ -557,7 +575,7 @@ sub mockedC4Config { return $class->{$param}; } - return C4::Context::_common_config($param, 'config'); + return C4::Context::_common_config( $param, 'config' ); } # Function that mocks the call to Net::LDAP @@ -565,22 +583,24 @@ sub mock_net_ldap { my $mocked_ldap = Test::MockObject->new(); - $mocked_ldap->mock( 'bind', sub { - if (is_admin_bind(@_)) { - return mock_net_ldap_message( - ($desired_admin_bind_result eq 'error' ) ? 1 : 0, # code - ($desired_admin_bind_result eq 'error' ) ? 1 : 0, # error - ($desired_admin_bind_result eq 'error' ) ? 'error_name' : 0, # error_name - ($desired_admin_bind_result eq 'error' ) ? 'error_text' : 0 # error_text - ); - } - else { - if ( $desired_bind_result eq 'error' ) { - return mock_net_ldap_message(1,1,'error_name','error_text'); + $mocked_ldap->mock( + 'bind', + sub { + if ( is_admin_bind(@_) ) { + return mock_net_ldap_message( + ( $desired_admin_bind_result eq 'error' ) ? 1 : 0, # code + ( $desired_admin_bind_result eq 'error' ) ? 1 : 0, # error + ( $desired_admin_bind_result eq 'error' ) ? 'error_name' : 0, # error_name + ( $desired_admin_bind_result eq 'error' ) ? 'error_text' : 0 # error_text + ); + } else { + if ( $desired_bind_result eq 'error' ) { + return mock_net_ldap_message( 1, 1, 'error_name', 'error_text' ); + } + return mock_net_ldap_message( 0, 0, '', '' ); } - return mock_net_ldap_message(0,0,'',''); } - }); + ); $mocked_ldap->mock( 'search', @@ -596,7 +616,8 @@ sub mock_net_ldap { code => ( $desired_search_result eq 'error' ) ? 1 : 0, # 0 == success - error => ( $desired_search_result eq 'error' ) ? 1 + error => ( $desired_search_result eq 'error' ) + ? 1 : 0, error_text => ( $desired_search_result eq 'error' ) ? 'error_text' @@ -625,18 +646,21 @@ sub mock_net_ldap_search { my $shift_entry = $parameters->{shift_entry}; my $mocked_search = Test::MockObject->new(); - $mocked_search->mock( 'count', sub { return $count; } ); - $mocked_search->mock( 'code', sub { return $code; } ); - $mocked_search->mock( 'error', sub { return $error; } ); - $mocked_search->mock( 'error_name', sub { return $error_name; } ); - $mocked_search->mock( 'error_text', sub { return $error_text; } ); - $mocked_search->mock( 'shift_entry', sub { - if ($remaining_entry) { - $remaining_entry--; - return $shift_entry; + $mocked_search->mock( 'count', sub { return $count; } ); + $mocked_search->mock( 'code', sub { return $code; } ); + $mocked_search->mock( 'error', sub { return $error; } ); + $mocked_search->mock( 'error_name', sub { return $error_name; } ); + $mocked_search->mock( 'error_text', sub { return $error_text; } ); + $mocked_search->mock( + 'shift_entry', + sub { + if ($remaining_entry) { + $remaining_entry--; + return $shift_entry; + } + return ''; } - return ''; - }); + ); return $mocked_search; } @@ -676,7 +700,7 @@ sub reload_ldap_module { sub is_admin_bind { my @args = @_; - if ($#args <= 1 || $args[1] eq 'cn=Manager,dc=metavore,dc=com') { + if ( $#args <= 1 || $args[1] eq 'cn=Manager,dc=metavore,dc=com' ) { return 1; } diff --git a/t/db_dependent/Auth_with_shibboleth.t b/t/db_dependent/Auth_with_shibboleth.t index d7f498ed39..db6ce0b1cb 100755 --- a/t/db_dependent/Auth_with_shibboleth.t +++ b/t/db_dependent/Auth_with_shibboleth.t @@ -23,7 +23,7 @@ use utf8; use Test::More tests => 6; use Test::MockModule; use Test::Warn; -use CGI qw(-utf8 ); +use CGI qw(-utf8 ); use File::Temp qw(tempdir); use t::lib::Mocks; @@ -45,42 +45,52 @@ BEGIN { my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; my $builder = t::lib::TestBuilder->new; -my $logger = t::lib::Mocks::Logger->new(); +my $logger = t::lib::Mocks::Logger->new(); # Mock variables my $shibboleth; -change_config({}); +change_config( {} ); my $interface = 'opac'; # Mock few preferences -t::lib::Mocks::mock_preference('OPACBaseURL', 'testopac.com' ); -t::lib::Mocks::mock_preference('StaffClientBaseURL', 'teststaff.com' ); -t::lib::Mocks::mock_preference( 'EmailFieldPrimary', '' ); +t::lib::Mocks::mock_preference( 'OPACBaseURL', 'testopac.com' ); +t::lib::Mocks::mock_preference( 'StaffClientBaseURL', 'teststaff.com' ); +t::lib::Mocks::mock_preference( 'EmailFieldPrimary', '' ); t::lib::Mocks::mock_preference( 'EmailFieldPrecedence', 'emailpro' ); # Mock Context: config, tz and interface my $context = Test::MockModule->new('C4::Context'); -$context->mock( 'config', sub { return $shibboleth; } ); # easier than caching by Mocks::mock_config -$context->mock( 'timezone', sub { return 'local'; } ); +$context->mock( 'config', sub { return $shibboleth; } ); # easier than caching by Mocks::mock_config +$context->mock( 'timezone', sub { return 'local'; } ); $context->mock( 'interface', sub { return $interface; } ); # Mock Letters: GetPreparedLetter, EnqueueLetter and SendQueuedMessages # We want to test the params my $mocked_letters = Test::MockModule->new('C4::Letters'); -$mocked_letters->mock( 'GetPreparedLetter', sub { - warn "GetPreparedLetter called"; - return 1; -}); -$mocked_letters->mock( 'EnqueueLetter', sub { - warn "EnqueueLetter called"; - # return a 'message_id' - return 42; -}); -$mocked_letters->mock( 'SendQueuedMessages', sub { - my $params = shift; - warn "SendQueuedMessages called with message_id: $params->{message_id}"; - return 1; -}); +$mocked_letters->mock( + 'GetPreparedLetter', + sub { + warn "GetPreparedLetter called"; + return 1; + } +); +$mocked_letters->mock( + 'EnqueueLetter', + sub { + warn "EnqueueLetter called"; + + # return a 'message_id' + return 42; + } +); +$mocked_letters->mock( + 'SendQueuedMessages', + sub { + my $params = shift; + warn "SendQueuedMessages called with message_id: $params->{message_id}"; + return 1; + } +); # Start testing ---------------------------------------------------------------- @@ -95,26 +105,26 @@ subtest "shib_ok tests" => sub { delete $shibboleth->{matchpoint}; warnings_are { $result = shib_ok() } [ { carped => 'shibboleth matchpoint not defined' }, ], - "undefined matchpoint = fatal config, warning given"; + "undefined matchpoint = fatal config, warning given"; is( $result, '0', "bad config" ); - change_config({ matchpoint => 'email' }); + change_config( { matchpoint => 'email' } ); warnings_are { $result = shib_ok() } [ { carped => 'shibboleth matchpoint not mapped' }, ], - "unmapped matchpoint = fatal config, warning given"; + "unmapped matchpoint = fatal config, warning given"; is( $result, '0', "bad config" ); # add test for undefined shibboleth block $logger->clear; - change_config({}); + change_config( {} ); }; subtest "login_shib_url tests" => sub { plan tests => 2; - my $string = 'language=en-GB¶m="heh❤"'; - my $query_string = Encode::encode('UTF-8', $string); - my $query_string_uri_escaped = URI::Escape::uri_escape_utf8('?'.$string); + my $string = 'language=en-GB¶m="heh❤"'; + my $query_string = Encode::encode( 'UTF-8', $string ); + my $query_string_uri_escaped = URI::Escape::uri_escape_utf8( '?' . $string ); local $ENV{REQUEST_METHOD} = 'GET'; local $ENV{QUERY_STRING} = $query_string; @@ -123,9 +133,9 @@ subtest "login_shib_url tests" => sub { is( login_shib_url($query), 'https://testopac.com' - . '/Shibboleth.sso/Login?target=' - . 'https://testopac.com/cgi-bin/koha/opac-user.pl' - . $query_string_uri_escaped, + . '/Shibboleth.sso/Login?target=' + . 'https://testopac.com/cgi-bin/koha/opac-user.pl' + . $query_string_uri_escaped, "login shib url" ); @@ -133,7 +143,7 @@ subtest "login_shib_url tests" => sub { local $ENV{REQUEST_METHOD} = 'POST'; local $ENV{CONTENT_LENGTH} = length($post_params); - my $dir = tempdir( CLEANUP => 1 ); + my $dir = tempdir( CLEANUP => 1 ); my $infile = "$dir/in.txt"; open my $fh_write, '>', $infile or die "Could not open '$infile' $!"; print $fh_write $post_params; @@ -144,9 +154,7 @@ subtest "login_shib_url tests" => sub { $query = CGI->new($fh_read); is( login_shib_url($query), - 'https://testopac.com' - . '/Shibboleth.sso/Login?target=' - . 'https://testopac.com/cgi-bin/koha/opac-user.pl', + 'https://testopac.com' . '/Shibboleth.sso/Login?target=' . 'https://testopac.com/cgi-bin/koha/opac-user.pl', "login shib url" ); @@ -157,9 +165,8 @@ subtest "get_login_shib tests" => sub { plan tests => 3; my $login = get_login_shib(); - $logger->debug_is("koha borrower field to match: userid", "borrower match field debug info") - ->debug_is("shibboleth attribute to match: uid", "shib match attribute debug info") - ->clear(); + $logger->debug_is( "koha borrower field to match: userid", "borrower match field debug info" ) + ->debug_is( "shibboleth attribute to match: uid", "shib match attribute debug info" )->clear(); is( $login, "test1234", "good config, attribute value returned" ); }; @@ -169,13 +176,24 @@ subtest "checkpw_shib tests" => sub { # Test borrower data my $test_borrowers = [ - { cardnumber => 'testcardnumber', userid => 'test1234', surname => 'renvoize', address => 'myaddress', city => 'johnston', email => undef }, - { cardnumber => 'testcardnumber1', userid => 'test12345', surname => 'clamp1', address => 'myaddress', city => 'quechee', email => 'kid@clamp.io' }, - { cardnumber => 'testcardnumber2', userid => 'test123456', surname => 'clamp2', address => 'myaddress', city => 'quechee', email => 'kid@clamp.io' }, + { + cardnumber => 'testcardnumber', userid => 'test1234', surname => 'renvoize', address => 'myaddress', + city => 'johnston', email => undef + }, + { + cardnumber => 'testcardnumber1', userid => 'test12345', surname => 'clamp1', address => 'myaddress', + city => 'quechee', email => 'kid@clamp.io' + }, + { + cardnumber => 'testcardnumber2', userid => 'test123456', surname => 'clamp2', address => 'myaddress', + city => 'quechee', email => 'kid@clamp.io' + }, ]; - my $category = $builder->build_object({ class => 'Koha::Patron::Categories', value => { default_privacy => 'never' }}); - $builder->build_object({ class => 'Koha::Patrons', value => { %$_, categorycode => $category->categorycode }}) for @$test_borrowers; - my $library = $builder->build_object({ class => 'Koha::Libraries' }); + my $category = + $builder->build_object( { class => 'Koha::Patron::Categories', value => { default_privacy => 'never' } } ); + $builder->build_object( { class => 'Koha::Patrons', value => { %$_, categorycode => $category->categorycode } } ) + for @$test_borrowers; + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); # good user my $shib_login = "test1234"; @@ -186,9 +204,8 @@ subtest "checkpw_shib tests" => sub { is( $retuserid, "test1234", "expected userid returned" ); is( ref($retpatron), 'Koha::Patron', "expected Koha::Patron object returned" ); - $logger->debug_is("koha borrower field to match: userid", "borrower match field debug info") - ->debug_is("shibboleth attribute to match: uid", "shib match attribute debug info") - ->clear(); + $logger->debug_is( "koha borrower field to match: userid", "borrower match field debug info" ) + ->debug_is( "shibboleth attribute to match: uid", "shib match attribute debug info" )->clear(); # bad user $shib_login = 'martin'; @@ -197,34 +214,33 @@ subtest "checkpw_shib tests" => sub { is( $retcard, undef ); is( $retuserid, undef ); is( $retpatron, undef ); - $logger->debug_is("koha borrower field to match: userid", "borrower match field debug info") - ->debug_is("shibboleth attribute to match: uid", "shib match attribute debug info") - ->clear(); + $logger->debug_is( "koha borrower field to match: userid", "borrower match field debug info" ) + ->debug_is( "shibboleth attribute to match: uid", "shib match attribute debug info" )->clear(); # duplicated matchpoint - change_config({ matchpoint => 'email', mapping => { email => { is => 'email' }} }); + change_config( { matchpoint => 'email', mapping => { email => { is => 'email' } } } ); $shib_login = 'kid@clamp.io'; ( $retval, $retcard, $retuserid, $retpatron ) = checkpw_shib($shib_login); is( $retval, 0, "user not authenticated if duplicated matchpoint" ); is( $retcard, undef ); is( $retuserid, undef ); is( $retpatron, undef ); - $logger->debug_is("koha borrower field to match: email", "borrower match field debug info") - ->debug_is("shibboleth attribute to match: email", "shib match attribute debug info") - ->clear(); + $logger->debug_is( "koha borrower field to match: email", "borrower match field debug info" ) + ->debug_is( "shibboleth attribute to match: email", "shib match attribute debug info" )->clear(); ( $retval, $retcard, $retuserid, $retpatron ) = checkpw_shib($shib_login); is( $retval, 0 ); is( $retcard, undef ); is( $retuserid, undef ); is( $retpatron, undef ); - $logger->debug_is("koha borrower field to match: email", "borrower match field debug info") - ->debug_is("shibboleth attribute to match: email", "shib match attribute debug info") - ->warn_is('There are several users with email of kid@clamp.io, matchpoints must be unique', "duplicated matchpoint warned with debug") - ->clear(); + $logger->debug_is( "koha borrower field to match: email", "borrower match field debug info" ) + ->debug_is( "shibboleth attribute to match: email", "shib match attribute debug info" )->warn_is( + 'There are several users with email of kid@clamp.io, matchpoints must be unique', + "duplicated matchpoint warned with debug" + )->clear(); # autocreate user (welcome) - change_config({ autocreate => 1, welcome => 1 }); + change_config( { autocreate => 1, welcome => 1 } ); $shib_login = 'test4321'; $ENV{'uid'} = 'test4321'; $ENV{'sn'} = "pika"; @@ -233,7 +249,7 @@ subtest "checkpw_shib tests" => sub { $ENV{'add'} = 'Address'; $ENV{'city'} = 'City'; $ENV{'emailpro'} = 'me@myemail.com'; - $ENV{branchcode} = $library->branchcode; # needed since T::D::C does no longer hides the FK constraint + $ENV{branchcode} = $library->branchcode; # needed since T::D::C does no longer hides the FK constraint warnings_are { ( $retval, $retcard, $retuserid, $retpatron ) = checkpw_shib($shib_login); @@ -243,20 +259,21 @@ subtest "checkpw_shib tests" => sub { 'EnqueueLetter called', 'SendQueuedMessages called with message_id: 42' ], - "WELCOME notice Prepared, Enqueued and Send"; + "WELCOME notice Prepared, Enqueued and Send"; is( $retval, "1", "user authenticated" ); is( $retuserid, "test4321", "expected userid returned" ); is( ref($retpatron), 'Koha::Patron', "expected Koha::Patron object returned" ); - $logger->debug_is("koha borrower field to match: userid", "borrower match field debug info") - ->debug_is("shibboleth attribute to match: uid", "shib match attribute debug info") - ->clear(); + $logger->debug_is( "koha borrower field to match: userid", "borrower match field debug info" ) + ->debug_is( "shibboleth attribute to match: uid", "shib match attribute debug info" )->clear(); - ok my $new_user = $schema->resultset('Borrower') - ->search( { 'userid' => 'test4321' }, { rows => 1 } ), "new user found"; + ok my $new_user = $schema->resultset('Borrower')->search( { 'userid' => 'test4321' }, { rows => 1 } ), + "new user found"; my $rec = $new_user->next; - is_deeply( [ map { $rec->$_ } qw/surname dateexpiry address city/ ], + is_deeply( + [ map { $rec->$_ } qw/surname dateexpiry address city/ ], [qw/pika 2017-01-01 Address City/], - 'Found $new_user surname' ); + 'Found $new_user surname' + ); # sync user $shibboleth->{sync} = 1; @@ -265,18 +282,19 @@ subtest "checkpw_shib tests" => sub { is( $retval, 1, "user authenticated" ); is( $retuserid, $shib_login, "expected userid returned" ); is( ref($retpatron), 'Koha::Patron', "expected Koha::Patron object returned" ); - $logger->debug_is("koha borrower field to match: userid", "borrower match field debug info") - ->debug_is("shibboleth attribute to match: uid", "shib match attribute debug info") - ->clear(); + $logger->debug_is( "koha borrower field to match: userid", "borrower match field debug info" ) + ->debug_is( "shibboleth attribute to match: uid", "shib match attribute debug info" )->clear(); - ok my $sync_user = $schema->resultset('Borrower') - ->search( { 'userid' => 'test4321' }, { rows => 1 } ), "sync user found"; + ok my $sync_user = $schema->resultset('Borrower')->search( { 'userid' => 'test4321' }, { rows => 1 } ), + "sync user found"; $rec = $sync_user->next; - is_deeply( [ map { $rec->$_ } qw/surname dateexpiry address city/ ], + is_deeply( + [ map { $rec->$_ } qw/surname dateexpiry address city/ ], [qw/pika 2017-01-01 Address AnotherCity/], - 'Found $sync_user synced city' ); - change_config({ sync => 0 }); + 'Found $sync_user synced city' + ); + change_config( { sync => 0 } ); # good user $shib_login = "test1234"; @@ -285,9 +303,8 @@ subtest "checkpw_shib tests" => sub { is( $retcard, "testcardnumber", "expected cardnumber returned" ); is( $retuserid, "test1234", "expected userid returned" ); is( ref($retpatron), 'Koha::Patron', "expected Koha::Patron object returned" ); - $logger->debug_is("koha borrower field to match: userid", "borrower match field debug info") - ->debug_is("shibboleth attribute to match: uid", "shib match attribute debug info") - ->clear(); + $logger->debug_is( "koha borrower field to match: userid", "borrower match field debug info" ) + ->debug_is( "shibboleth attribute to match: uid", "shib match attribute debug info" )->clear(); # bad user $shib_login = "martin"; @@ -296,7 +313,10 @@ subtest "checkpw_shib tests" => sub { is( $retcard, undef ); is( $retuserid, undef ); is( $retpatron, undef ); - $logger->info_is("No users with userid of martin found and autocreate is disabled", "Missing matchpoint warned to info"); + $logger->info_is( + "No users with userid of martin found and autocreate is disabled", + "Missing matchpoint warned to info" + ); # autocreate user from checkpw change_config( { autocreate => 1, welcome => 1 } ); @@ -324,56 +344,73 @@ subtest "checkpw_shib tests" => sub { subtest 'get_uri' => sub { plan tests => 13; + # Tests for OPAC - t::lib::Mocks::mock_preference('OPACBaseURL', 'testopac.com' ); - is( C4::Auth_with_shibboleth::_get_uri(), - "https://testopac.com", "https opac uri returned" ); + t::lib::Mocks::mock_preference( 'OPACBaseURL', 'testopac.com' ); + is( + C4::Auth_with_shibboleth::_get_uri(), + "https://testopac.com", "https opac uri returned" + ); $logger->clear; - t::lib::Mocks::mock_preference('OPACBaseURL', 'http://testopac.com' ); + t::lib::Mocks::mock_preference( 'OPACBaseURL', 'http://testopac.com' ); my $result = C4::Auth_with_shibboleth::_get_uri(); is( $result, "https://testopac.com", "https opac uri returned" ); - $logger->warn_is("Shibboleth requires OPACBaseURL/staffClientBaseURL to use the https protocol!", "Improper protocol logged to warn") - ->clear(); + $logger->warn_is( + "Shibboleth requires OPACBaseURL/staffClientBaseURL to use the https protocol!", + "Improper protocol logged to warn" + )->clear(); - t::lib::Mocks::mock_preference('OPACBaseURL', 'https://testopac.com' ); - is( C4::Auth_with_shibboleth::_get_uri(), - "https://testopac.com", "https opac uri returned" ); + t::lib::Mocks::mock_preference( 'OPACBaseURL', 'https://testopac.com' ); + is( + C4::Auth_with_shibboleth::_get_uri(), + "https://testopac.com", "https opac uri returned" + ); $logger->clear(); - t::lib::Mocks::mock_preference('OPACBaseURL', undef ); + t::lib::Mocks::mock_preference( 'OPACBaseURL', undef ); $result = C4::Auth_with_shibboleth::_get_uri(); is( $result, "https://", "https $interface uri returned" ); - $logger->warn_is("Syspref staffClientBaseURL or OPACBaseURL not set!", "undefined OPACBaseURL - received expected warning") - ->clear(); + $logger->warn_is( + "Syspref staffClientBaseURL or OPACBaseURL not set!", + "undefined OPACBaseURL - received expected warning" + )->clear(); # Tests for staff client $interface = 'intranet'; - t::lib::Mocks::mock_preference('StaffClientBaseURL', 'teststaff.com' ); - is( C4::Auth_with_shibboleth::_get_uri(), - "https://teststaff.com", "https $interface uri returned" ); + t::lib::Mocks::mock_preference( 'StaffClientBaseURL', 'teststaff.com' ); + is( + C4::Auth_with_shibboleth::_get_uri(), + "https://teststaff.com", "https $interface uri returned" + ); $logger->clear; - t::lib::Mocks::mock_preference('StaffClientBaseURL', 'http://teststaff.com' ); + t::lib::Mocks::mock_preference( 'StaffClientBaseURL', 'http://teststaff.com' ); $result = C4::Auth_with_shibboleth::_get_uri(); is( $result, "https://teststaff.com", "https $interface uri returned" ); - $logger->warn_is("Shibboleth requires OPACBaseURL/staffClientBaseURL to use the https protocol!", 'check protocol warn') - ->clear; + $logger->warn_is( + "Shibboleth requires OPACBaseURL/staffClientBaseURL to use the https protocol!", + 'check protocol warn' + )->clear; - t::lib::Mocks::mock_preference('StaffClientBaseURL', 'https://teststaff.com' ); - is( C4::Auth_with_shibboleth::_get_uri(), - "https://teststaff.com", "https $interface uri returned" ); + t::lib::Mocks::mock_preference( 'StaffClientBaseURL', 'https://teststaff.com' ); + is( + C4::Auth_with_shibboleth::_get_uri(), + "https://teststaff.com", "https $interface uri returned" + ); is( $logger->count(), 0, 'No logging' ); - t::lib::Mocks::mock_preference('StaffClientBaseURL', undef ); + t::lib::Mocks::mock_preference( 'StaffClientBaseURL', undef ); $result = C4::Auth_with_shibboleth::_get_uri(); is( $result, "https://", "https $interface uri returned" ); - $logger->warn_is("Syspref staffClientBaseURL or OPACBaseURL not set!", "undefined staffClientBaseURL - received expected warning") - ->clear; + $logger->warn_is( + "Syspref staffClientBaseURL or OPACBaseURL not set!", + "undefined staffClientBaseURL - received expected warning" + )->clear; }; $schema->storage->txn_rollback; @@ -392,13 +429,13 @@ sub change_config { 'emailpro' => { 'is' => 'emailpro' }, 'branchcode' => { 'is' => 'branchcode' }, ); - if( exists $params->{mapping} ) { - $mapping{$_} = $params->{mapping}->{$_} for keys %{$params->{mapping}}; + if ( exists $params->{mapping} ) { + $mapping{$_} = $params->{mapping}->{$_} for keys %{ $params->{mapping} }; } $shibboleth = { autocreate => $params->{autocreate} // 0, - welcome => $params->{welcome} // 0, - sync => $params->{sync} // 0, + welcome => $params->{welcome} // 0, + sync => $params->{sync} // 0, matchpoint => $params->{matchpoint} // 'userid', mapping => \%mapping, }; diff --git a/t/db_dependent/AuthorisedValues.t b/t/db_dependent/AuthorisedValues.t index 02fcbc5ac8..cf07bfc001 100755 --- a/t/db_dependent/AuthorisedValues.t +++ b/t/db_dependent/AuthorisedValues.t @@ -15,16 +15,16 @@ use Koha::AuthorisedValueCategories; use Koha::Exceptions; use Koha::MarcSubfieldStructures; -my $schema = Koha::Database->new->schema; +my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; my $builder = t::lib::TestBuilder->new; my @existing_categories = Koha::AuthorisedValues->new->categories; # insert -Koha::AuthorisedValueCategory->new({ category_name => 'av_for_testing', is_system => 1 })->store; -Koha::AuthorisedValueCategory->new({ category_name => 'aaav_for_testing' })->store; -Koha::AuthorisedValueCategory->new({ category_name => 'restricted_for_testing' })->store; +Koha::AuthorisedValueCategory->new( { category_name => 'av_for_testing', is_system => 1 } )->store; +Koha::AuthorisedValueCategory->new( { category_name => 'aaav_for_testing' } )->store; +Koha::AuthorisedValueCategory->new( { category_name => 'restricted_for_testing' } )->store; my $av1 = Koha::AuthorisedValue->new( { category => 'av_for_testing', @@ -67,7 +67,7 @@ my $av4 = Koha::AuthorisedValue->new( my $av_empty_string = Koha::AuthorisedValue->new( { category => 'restricted_for_testing', - authorised_value => undef, # Should have been defaulted to "" + authorised_value => undef, # Should have been defaulted to "" lib => 'display value undef', lib_opac => 'opac display value undef', } @@ -86,11 +86,10 @@ ok( $av2->id(), 'AV 2 is inserted' ); ok( $av3->id(), 'AV 3 is inserted' ); ok( $av4->id(), 'AV 4 is inserted' ); -{ # delete is_system AV categories +{ # delete is_system AV categories try { Koha::AuthorisedValueCategories->find('av_for_testing')->delete - } - catch { + } catch { ok( $_->isa('Koha::Exceptions::CannotDeleteDefault'), 'A system AV category cannot be deleted' @@ -99,8 +98,7 @@ ok( $av4->id(), 'AV 4 is inserted' ); try { Koha::AuthorisedValueCategories->search->delete - } - catch { + } catch { ok( $_->isa('Koha::Exceptions::CannotDeleteDefault'), 'system AV categories cannot be deleted' @@ -113,32 +111,41 @@ $av3->lib_opac(''); is( $av3->opac_description, 'display value 3', 'Got correction opac description if lib_opac is *not* set' ); my @authorised_values = - Koha::AuthorisedValues->new()->search( { category => 'av_for_testing' } )->as_list; + Koha::AuthorisedValues->new()->search( { category => 'av_for_testing' } )->as_list; is( @authorised_values, 3, "Get correct number of values" ); -my $branchcode1 = $builder->build({ source => 'Branch' })->{branchcode}; -my $branchcode2 = $builder->build({ source => 'Branch' })->{branchcode}; +my $branchcode1 = $builder->build( { source => 'Branch' } )->{branchcode}; +my $branchcode2 = $builder->build( { source => 'Branch' } )->{branchcode}; -$av1->add_library_limit( $branchcode1 ); +$av1->add_library_limit($branchcode1); -@authorised_values = Koha::AuthorisedValues->search_with_library_limits( { category => 'av_for_testing' }, {}, $branchcode1 )->as_list; -is( @authorised_values, 3, "Search including value with a branch limit ( branch can use the limited value ) gives correct number of results" ); +@authorised_values = + Koha::AuthorisedValues->search_with_library_limits( { category => 'av_for_testing' }, {}, $branchcode1 )->as_list; +is( + @authorised_values, 3, + "Search including value with a branch limit ( branch can use the limited value ) gives correct number of results" +); -@authorised_values = Koha::AuthorisedValues->search_with_library_limits( { category => 'av_for_testing' }, {}, $branchcode2 )->as_list; -is( @authorised_values, 2, "Search including value with a branch limit ( branch *cannot* use the limited value ) gives correct number of results" ); +@authorised_values = + Koha::AuthorisedValues->search_with_library_limits( { category => 'av_for_testing' }, {}, $branchcode2 )->as_list; +is( + @authorised_values, 2, + "Search including value with a branch limit ( branch *cannot* use the limited value ) gives correct number of results" +); -$av1->del_library_limit( $branchcode1 ); -@authorised_values = Koha::AuthorisedValues->search_with_library_limits( { category => 'av_for_testing' }, {}, $branchcode2 )->as_list; +$av1->del_library_limit($branchcode1); +@authorised_values = + Koha::AuthorisedValues->search_with_library_limits( { category => 'av_for_testing' }, {}, $branchcode2 )->as_list; is( @authorised_values, 3, "Branch limitation deleted successfully" ); -$av1->add_library_limit( $branchcode1 ); +$av1->add_library_limit($branchcode1); $av1->library_limits( [ $branchcode1, $branchcode2 ] ); my $limits = $av1->library_limits->as_list; is( @$limits, 2, 'library_limits functions correctly both as setter and getter' ); my @categories = Koha::AuthorisedValues->new->categories; -is( @categories, @existing_categories+3, 'There should have 3 categories inserted' ); +is( @categories, @existing_categories + 3, 'There should have 3 categories inserted' ); is_deeply( \@categories, [ sort { uc $a cmp uc $b } @categories ], @@ -163,10 +170,30 @@ subtest 'search_by_*_field + find_by_koha_field + get_description + authorised_v Koha::AuthorisedValueCategory->new( { category_name => 'TEST' } )->store; Koha::AuthorisedValueCategory->new( { category_name => 'CONTROL_TEST' } )->store; Koha::AuthorisedValueCategory->new( { category_name => 'ANOTHER_4_TESTS' } )->store; - Koha::MarcSubfieldStructure->new( { tagfield => 952, tagsubfield => 'c', frameworkcode => '', authorised_value => 'TEST', kohafield => 'items.location' } )->store; - Koha::MarcSubfieldStructure->new( { tagfield => 952, tagsubfield => 'c', frameworkcode => 'ACQ', authorised_value => 'TEST', kohafield => 'items.location' } )->store; - Koha::MarcSubfieldStructure->new( { tagfield => 952, tagsubfield => 'd', frameworkcode => '', authorised_value => 'ANOTHER_4_TESTS', kohafield => 'items.another_field' } )->store; - Koha::MarcSubfieldStructure->new( { tagfield => 952, tagsubfield => '5', frameworkcode => '', authorised_value => 'restricted_for_testing', kohafield => 'items.restricted' } )->store; + Koha::MarcSubfieldStructure->new( + { + tagfield => 952, tagsubfield => 'c', frameworkcode => '', authorised_value => 'TEST', + kohafield => 'items.location' + } + )->store; + Koha::MarcSubfieldStructure->new( + { + tagfield => 952, tagsubfield => 'c', frameworkcode => 'ACQ', authorised_value => 'TEST', + kohafield => 'items.location' + } + )->store; + Koha::MarcSubfieldStructure->new( + { + tagfield => 952, tagsubfield => 'd', frameworkcode => '', authorised_value => 'ANOTHER_4_TESTS', + kohafield => 'items.another_field' + } + )->store; + Koha::MarcSubfieldStructure->new( + { + tagfield => 952, tagsubfield => '5', frameworkcode => '', authorised_value => 'restricted_for_testing', + kohafield => 'items.restricted' + } + )->store; Koha::MarcSubfieldStructure->new( { tagfield => '003', frameworkcode => '', authorised_value => 'CONTROL_TEST', } ) ->store; Koha::AuthorisedValue->new( { category => 'TEST', authorised_value => 'location_1', lib => 'location_1' } )->store; @@ -182,18 +209,18 @@ subtest 'search_by_*_field + find_by_koha_field + get_description + authorised_v plan tests => 4; my $avs; $avs = Koha::AuthorisedValues->search_by_marc_field(); - is ( $avs, undef ); - $avs = Koha::AuthorisedValues->search_by_marc_field({ frameworkcode => '' }); - is ( $avs, undef ); - $avs = Koha::AuthorisedValues->search_by_marc_field({ tagfield => 952, tagsubfield => 'c'}); - is( $avs->count, 3, 'default fk'); + is( $avs, undef ); + $avs = Koha::AuthorisedValues->search_by_marc_field( { frameworkcode => '' } ); + is( $avs, undef ); + $avs = Koha::AuthorisedValues->search_by_marc_field( { tagfield => 952, tagsubfield => 'c' } ); + is( $avs->count, 3, 'default fk' ); is( $avs->next->authorised_value, 'location_1', ); }; subtest 'search_by_koha_field' => sub { plan tests => 3; my $avs; $avs = Koha::AuthorisedValues->search_by_koha_field(); - is ( $avs, undef ); + is( $avs, undef ); $avs = Koha::AuthorisedValues->search_by_koha_field( { kohafield => 'items.location' } ); is( $avs->count, 3, ); is( $avs->next->authorised_value, 'location_1', ); @@ -201,15 +228,19 @@ subtest 'search_by_*_field + find_by_koha_field + get_description + authorised_v }; subtest 'find_by_koha_field' => sub { plan tests => 3; + # Test authorised_value = 0 my $av; $av = Koha::AuthorisedValues->find_by_koha_field( { kohafield => 'items.restricted', authorised_value => 0 } ); is( $av->lib, $av_0->lib, ); + # Test authorised_value = "" $av = Koha::AuthorisedValues->find_by_koha_field( { kohafield => 'items.restricted', authorised_value => '' } ); is( $av->lib, $av_empty_string->lib, ); + # Test authorised_value = undef => we do not want to retrieve anything - $av = Koha::AuthorisedValues->find_by_koha_field( { kohafield => 'items.restricted', authorised_value => undef } ); + $av = Koha::AuthorisedValues->find_by_koha_field( + { kohafield => 'items.restricted', authorised_value => undef } ); is( $av, undef, ); }; subtest 'get_description_by_koha_field' => sub { @@ -219,7 +250,8 @@ subtest 'search_by_*_field + find_by_koha_field + get_description + authorised_v # Test authorised_value = 0 $descriptions = Koha::AuthorisedValues->get_description_by_koha_field( { kohafield => 'items.restricted', authorised_value => 0 } ); - is_deeply( $descriptions, + is_deeply( + $descriptions, { lib => $av_0->lib, opac_description => $av_0->lib_opac }, ); @@ -237,16 +269,17 @@ subtest 'search_by_*_field + find_by_koha_field + get_description + authorised_v # Test authorised_value = undef => we do not want to retrieve anything $descriptions = Koha::AuthorisedValues->get_description_by_koha_field( { kohafield => 'items.restricted', authorised_value => undef } ); - is_deeply( $descriptions, {}, ) ; # This could be arguable, we could return undef instead + is_deeply( $descriptions, {}, ); # This could be arguable, we could return undef instead # No authorised_value $descriptions = Koha::AuthorisedValues->get_description_by_koha_field( { kohafield => 'items.restricted', authorised_value => "does not exist" } ); - is_deeply( $descriptions, {}, ) ; # This could be arguable, we could return undef instead + is_deeply( $descriptions, {}, ); # This could be arguable, we could return undef instead }; subtest 'get_descriptions_by_koha_field' => sub { plan tests => 1; - my @descriptions = Koha::AuthorisedValues->get_descriptions_by_koha_field( { kohafield => 'items.restricted' } ); + my @descriptions = + Koha::AuthorisedValues->get_descriptions_by_koha_field( { kohafield => 'items.restricted' } ); is_deeply( \@descriptions, [ @@ -307,13 +340,10 @@ subtest 'search_by_*_field + find_by_koha_field + get_description + authorised_v $schema->storage->txn_begin; - my $authorised_value_category = - $builder->build_object( + my $authorised_value_category = $builder->build_object( { class => 'Koha::AuthorisedValueCategories', - value => { - category_name => 'test_avs' - } + value => { category_name => 'test_avs' } } ); diff --git a/t/db_dependent/AuthoritiesMarc.t b/t/db_dependent/AuthoritiesMarc.t index 55435d281b..600a0b6e28 100755 --- a/t/db_dependent/AuthoritiesMarc.t +++ b/t/db_dependent/AuthoritiesMarc.t @@ -1,6 +1,6 @@ #!/usr/bin/perl # -# This Koha test module is a stub! +# This Koha test module is a stub! # Add more tests here!!! use Modern::Perl; @@ -17,18 +17,27 @@ use Koha::Database; use Koha::Authority::Types; BEGIN { - use_ok('C4::AuthoritiesMarc', qw( GetHeaderAuthority AddAuthority AddAuthorityTrees GetAuthority BuildAuthHierarchies GenerateHierarchy BuildSummary DelAuthority CompareFieldWithAuthority ModAuthority merge )); + use_ok( + 'C4::AuthoritiesMarc', + qw( GetHeaderAuthority AddAuthority AddAuthorityTrees GetAuthority BuildAuthHierarchies GenerateHierarchy BuildSummary DelAuthority CompareFieldWithAuthority ModAuthority merge ) + ); } # We are now going to be testing the authorities hierarchy code, and # therefore need to pretend that we have consistent data in our database my $module = Test::MockModule->new('C4::AuthoritiesMarc'); -$module->mock('GetHeaderAuthority', sub { - return {'authtrees' => ''}; -}); -$module->mock('AddAuthorityTrees', sub { - return; -}); +$module->mock( + 'GetHeaderAuthority', + sub { + return { 'authtrees' => '' }; + } +); +$module->mock( + 'AddAuthorityTrees', + sub { + return; + } +); $module->mock( 'GetAuthority', sub { @@ -71,69 +80,86 @@ $module->mock( } ); - -my $schema = Koha::Database->new->schema; +my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; -my $dbh = C4::Context->dbh; +my $dbh = C4::Context->dbh; my $builder = t::lib::TestBuilder->new; -t::lib::Mocks::mock_preference('marcflavour', 'MARC21'); +t::lib::Mocks::mock_preference( 'marcflavour', 'MARC21' ); # Authority type GEOGR_NAME is hardcoded here -if( ! Koha::Authority::Types->find('GEOGR_NAME') ) { - $builder->build({ source => 'AuthType', value => { authtypecode => 'GEOGR_NAME' }}); -}; +if ( !Koha::Authority::Types->find('GEOGR_NAME') ) { + $builder->build( { source => 'AuthType', value => { authtypecode => 'GEOGR_NAME' } } ); +} -is(BuildAuthHierarchies(3, 1), '1,2,3', "Built linked authtrees hierarchy string"); +is( BuildAuthHierarchies( 3, 1 ), '1,2,3', "Built linked authtrees hierarchy string" ); -my $expectedhierarchy = [ [ { - 'authid' => '1', - 'value' => 'United States', - 'class' => 'child0', - 'children' => [ { - 'authid' => '2', - 'value' => 'New York (State)', - 'class' => 'child1', - 'children' => [ { - 'authid' => '3', - 'current_value' => 1, - 'value' => 'New York (City)', - 'class' => 'child2', - 'children' => [], - 'parents' => [ { - 'authid' => '2', - 'value' => 'New York (State)' - } ] - } ], - 'parents' => [ { - 'authid' => '1', - 'value' => 'United States' - } ] - } ], - 'parents' => [] -} ] ]; +my $expectedhierarchy = [ + [ + { + 'authid' => '1', + 'value' => 'United States', + 'class' => 'child0', + 'children' => [ + { + 'authid' => '2', + 'value' => 'New York (State)', + 'class' => 'child1', + 'children' => [ + { + 'authid' => '3', + 'current_value' => 1, + 'value' => 'New York (City)', + 'class' => 'child2', + 'children' => [], + 'parents' => [ + { + 'authid' => '2', + 'value' => 'New York (State)' + } + ] + } + ], + 'parents' => [ + { + 'authid' => '1', + 'value' => 'United States' + } + ] + } + ], + 'parents' => [] + } + ] +]; -is_deeply(GenerateHierarchy(3), $expectedhierarchy, "Generated hierarchy data structure for linked hierarchy"); +is_deeply( GenerateHierarchy(3), $expectedhierarchy, "Generated hierarchy data structure for linked hierarchy" ); -is(BuildAuthHierarchies(4, 1), '4', "Built unlinked authtrees hierarchy string"); -$expectedhierarchy = [ [ { - 'authid' => '4', - 'current_value' => 1, - 'value' => 'New York (City)', - 'class' => 'child0', - 'children' => [], - 'parents' => [] -} ] ]; -is_deeply(GenerateHierarchy(4), $expectedhierarchy, "Generated hierarchy data structure for unlinked hierarchy"); +is( BuildAuthHierarchies( 4, 1 ), '4', "Built unlinked authtrees hierarchy string" ); +$expectedhierarchy = [ + [ + { + 'authid' => '4', + 'current_value' => 1, + 'value' => 'New York (City)', + 'class' => 'child0', + 'children' => [], + 'parents' => [] + } + ] +]; +is_deeply( GenerateHierarchy(4), $expectedhierarchy, "Generated hierarchy data structure for unlinked hierarchy" ); # set up auth_types for next tests $dbh->do('DELETE FROM auth_types'); -$dbh->do(q{ +$dbh->do( + q{ INSERT INTO auth_types (authtypecode, authtypetext, auth_tag_to_report, summary) VALUES ('GEOGR_NAME', 'Geographic Name', '151', 'Geographic Name') -}); +} +); -t::lib::Mocks::mock_preference('marcflavour', 'MARC21'); +t::lib::Mocks::mock_preference( 'marcflavour', 'MARC21' ); my $expected_marc21_summary = { 'authorized' => [ { @@ -181,17 +207,17 @@ is_deeply( ); my $marc21_subdiv = MARC::Record->new(); -$marc21_subdiv->add_fields( - [ '181', ' ', ' ', x => 'Political aspects' ] -); -warning_is { BuildSummary($marc21_subdiv, 99999, 'GEN_SUBDIV') } [], +$marc21_subdiv->add_fields( [ '181', ' ', ' ', x => 'Political aspects' ] ); +warning_is { BuildSummary( $marc21_subdiv, 99999, 'GEN_SUBDIV' ) } [], 'BuildSummary does not generate warning if main heading subfield not present'; -t::lib::Mocks::mock_preference('marcflavour', 'UNIMARC'); -$dbh->do(q{ +t::lib::Mocks::mock_preference( 'marcflavour', 'UNIMARC' ); +$dbh->do( + q{ INSERT INTO auth_types (authtypecode, authtypetext, auth_tag_to_report, summary) VALUES ('NP', 'Auteur', '200', '[200a][, 200b][ 200d][ ; 200c][ (200f)]') -}); +} +); $dbh->do( q{ INSERT INTO marc_subfield_structure (frameworkcode,authtypecode,tagfield) @@ -201,9 +227,9 @@ $dbh->do( my $unimarc_name_auth = MARC::Record->new(); $unimarc_name_auth->add_fields( - ['100', ' ', ' ', a => '20121025 frey50 '], - ['200', ' ', ' ', a => 'Fossey', b => 'Brigitte' ], - ['152', ' ', ' ', a => 'NP'], + [ '100', ' ', ' ', a => '20121025 frey50 ' ], + [ '200', ' ', ' ', a => 'Fossey', b => 'Brigitte' ], + [ '152', ' ', ' ', a => 'NP' ], ); my $expected_unimarc_name_summary = { 'authorized' => [ @@ -226,7 +252,7 @@ my $expected_unimarc_name_summary = { }; is_deeply( - BuildSummary($unimarc_name_auth, 99999, 'NP'), + BuildSummary( $unimarc_name_auth, 99999, 'NP' ), $expected_unimarc_name_summary, 'test BuildSummary for UNIMARC' ); @@ -282,21 +308,27 @@ subtest 'AddAuthority should create heading field with display form' => sub { subtest 'CompareFieldWithAuthority tests' => sub { plan tests => 3; - t::lib::Mocks::mock_preference('marcflavour', 'MARC21'); + t::lib::Mocks::mock_preference( 'marcflavour', 'MARC21' ); - $builder->build({ source => 'AuthType', value => { authtypecode => 'PERSO_NAME' }}); + $builder->build( { source => 'AuthType', value => { authtypecode => 'PERSO_NAME' } } ); - my $field = MARC::Field->new('100', 0, 0, a => 'Lastname, Firstname', b => 'b', c => 'c'); + my $field = MARC::Field->new( '100', 0, 0, a => 'Lastname, Firstname', b => 'b', c => 'c' ); - ok(C4::AuthoritiesMarc::CompareFieldWithAuthority({'field' => $field, 'authid' => 5}), 'Authority matches'); + ok( C4::AuthoritiesMarc::CompareFieldWithAuthority( { 'field' => $field, 'authid' => 5 } ), 'Authority matches' ); - $field->add_subfields(i => 'X'); + $field->add_subfields( i => 'X' ); - ok(C4::AuthoritiesMarc::CompareFieldWithAuthority({'field' => $field, 'authid' => 5}), 'Compare ignores unlisted subfields'); + ok( + C4::AuthoritiesMarc::CompareFieldWithAuthority( { 'field' => $field, 'authid' => 5 } ), + 'Compare ignores unlisted subfields' + ); - $field->add_subfields(d => 'd'); + $field->add_subfields( d => 'd' ); - ok(!C4::AuthoritiesMarc::CompareFieldWithAuthority({'field' => $field, 'authid' => 5}), 'Authority does not match'); + ok( + !C4::AuthoritiesMarc::CompareFieldWithAuthority( { 'field' => $field, 'authid' => 5 } ), + 'Authority does not match' + ); }; $schema->storage->txn_rollback; @@ -310,25 +342,23 @@ subtest 'ModAuthority() tests' => sub { $schema->storage->txn_begin; my $auth_type = 'GEOGR_NAME'; - my $record = MARC::Record->new; + my $record = MARC::Record->new; $record->add_fields( - [ '001', '1' ], - [ '151', ' ', ' ', a => 'United States' ] - ); -; + [ '001', '1' ], + [ '151', ' ', ' ', a => 'United States' ] + ); + my $auth_id = AddAuthority( $record, undef, $auth_type ); my $mocked_authorities_marc = Test::MockModule->new('C4::AuthoritiesMarc'); $mocked_authorities_marc->mock( 'merge', sub { warn 'merge called'; } ); - warning_is - { ModAuthority( $auth_id, $record, $auth_type ); } - 'merge called', + warning_is { ModAuthority( $auth_id, $record, $auth_type ); } + 'merge called', 'No param, merge called'; - warning_is - { ModAuthority( $auth_id, $record, $auth_type, { skip_merge => 1 } ); } - undef, + warning_is { ModAuthority( $auth_id, $record, $auth_type, { skip_merge => 1 } ); } + undef, 'skip_merge passed, merge not called'; $schema->storage->txn_rollback; @@ -341,27 +371,25 @@ subtest 'DelAuthority() tests' => sub { $schema->storage->txn_begin; my $auth_type = 'GEOGR_NAME'; - my $record = MARC::Record->new; + my $record = MARC::Record->new; $record->add_fields( - [ '001', '1' ], - [ '151', ' ', ' ', a => 'United States' ] - ); -; + [ '001', '1' ], + [ '151', ' ', ' ', a => 'United States' ] + ); + my $auth_id = AddAuthority( $record, undef, $auth_type ); my $mocked_authorities_marc = Test::MockModule->new('C4::AuthoritiesMarc'); $mocked_authorities_marc->mock( 'merge', sub { warn 'merge called'; } ); - warning_is - { DelAuthority({ authid => $auth_id }); } - 'merge called', + warning_is { DelAuthority( { authid => $auth_id } ); } + 'merge called', 'No param, merge called'; $auth_id = AddAuthority( $record, undef, $auth_type ); - warning_is - { DelAuthority({ authid => $auth_id, skip_merge => 1 }); } - undef, + warning_is { DelAuthority( { authid => $auth_id, skip_merge => 1 } ); } + undef, 'skip_merge passed, merge not called'; $schema->storage->txn_rollback; diff --git a/t/db_dependent/AuthoritiesMarc/MARC21.t b/t/db_dependent/AuthoritiesMarc/MARC21.t index d8ccde0d3f..d658b97645 100755 --- a/t/db_dependent/AuthoritiesMarc/MARC21.t +++ b/t/db_dependent/AuthoritiesMarc/MARC21.t @@ -16,12 +16,12 @@ BEGIN { use_ok('C4::AuthoritiesMarc::MARC21'); } -my $schema = Koha::Database->new->schema; +my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; -my $dbh = C4::Context->dbh; +my $dbh = C4::Context->dbh; my $builder = t::lib::TestBuilder->new; -t::lib::Mocks::mock_preference('marcflavour', 'MARC21'); +t::lib::Mocks::mock_preference( 'marcflavour', 'MARC21' ); subtest 'CompareFieldWithAuthority tests' => sub { plan tests => 3; @@ -29,63 +29,78 @@ subtest 'CompareFieldWithAuthority tests' => sub { # We are now going to be testing the authorities hierarchy code, and # therefore need to pretend that we have consistent data in our database my $module = Test::MockModule->new('C4::AuthoritiesMarc'); - $module->mock('GetHeaderAuthority', sub { - return {'authtrees' => ''}; - }); - $module->mock('AddAuthorityTrees', sub { - return; - }); - $module->mock('GetAuthority', sub { - my ($authid) = @_; - my $record = MARC::Record->new(); - if ($authid eq '1') { - $record->add_fields( - [ '001', '1' ], - [ '151', ' ', ' ', a => 'United States' ] - ); - } elsif ($authid eq '2') { - $record->add_fields( - [ '001', '2' ], - [ '151', ' ', ' ', a => 'New York (State)' ], - [ '551', ' ', ' ', a => 'United States', w => 'g', 9 => '1' ] - ); - } elsif ($authid eq '3') { - $record->add_fields( - [ '001', '3' ], - [ '151', ' ', ' ', a => 'New York (City)' ], - [ '551', ' ', ' ', a => 'New York (State)', w => 'g', 9 => '2' ] - ); - } elsif ($authid eq '4') { - $record->add_fields( - [ '001', '4' ], - [ '151', ' ', ' ', a => 'New York (City)' ], - [ '551', ' ', ' ', a => 'New York (State)', w => 'g' ] - ); - } elsif ($authid eq '5') { - $record->add_fields( - [ '001', '5' ], - [ '100', ' ', ' ', a => 'Lastname, Firstname', b => 'b', c => 'c', i => 'i' ] - ); - } else { - undef $record; + $module->mock( + 'GetHeaderAuthority', + sub { + return { 'authtrees' => '' }; } - return $record; - }); + ); + $module->mock( + 'AddAuthorityTrees', + sub { + return; + } + ); + $module->mock( + 'GetAuthority', + sub { + my ($authid) = @_; + my $record = MARC::Record->new(); + if ( $authid eq '1' ) { + $record->add_fields( + [ '001', '1' ], + [ '151', ' ', ' ', a => 'United States' ] + ); + } elsif ( $authid eq '2' ) { + $record->add_fields( + [ '001', '2' ], + [ '151', ' ', ' ', a => 'New York (State)' ], + [ '551', ' ', ' ', a => 'United States', w => 'g', 9 => '1' ] + ); + } elsif ( $authid eq '3' ) { + $record->add_fields( + [ '001', '3' ], + [ '151', ' ', ' ', a => 'New York (City)' ], + [ '551', ' ', ' ', a => 'New York (State)', w => 'g', 9 => '2' ] + ); + } elsif ( $authid eq '4' ) { + $record->add_fields( + [ '001', '4' ], + [ '151', ' ', ' ', a => 'New York (City)' ], + [ '551', ' ', ' ', a => 'New York (State)', w => 'g' ] + ); + } elsif ( $authid eq '5' ) { + $record->add_fields( + [ '001', '5' ], + [ '100', ' ', ' ', a => 'Lastname, Firstname', b => 'b', c => 'c', i => 'i' ] + ); + } else { + undef $record; + } + return $record; + } + ); $dbh->do('DELETE FROM auth_types'); - $builder->build({ source => 'AuthType', value => { authtypecode => 'PERSO_NAME' }}); + $builder->build( { source => 'AuthType', value => { authtypecode => 'PERSO_NAME' } } ); - my $field = MARC::Field->new('100', 0, 0, a => 'Lastname, Firstname', b => 'b', c => 'c'); + my $field = MARC::Field->new( '100', 0, 0, a => 'Lastname, Firstname', b => 'b', c => 'c' ); - ok(C4::AuthoritiesMarc::CompareFieldWithAuthority({'field' => $field, 'authid' => 5}), 'Authority matches'); + ok( C4::AuthoritiesMarc::CompareFieldWithAuthority( { 'field' => $field, 'authid' => 5 } ), 'Authority matches' ); - $field->add_subfields(i => 'X'); + $field->add_subfields( i => 'X' ); - ok(C4::AuthoritiesMarc::CompareFieldWithAuthority({'field' => $field, 'authid' => 5}), 'Compare ignores unlisted subfields'); + ok( + C4::AuthoritiesMarc::CompareFieldWithAuthority( { 'field' => $field, 'authid' => 5 } ), + 'Compare ignores unlisted subfields' + ); - $field->add_subfields(d => 'd'); + $field->add_subfields( d => 'd' ); - ok(!C4::AuthoritiesMarc::CompareFieldWithAuthority({'field' => $field, 'authid' => 5}), 'Authority does not match'); + ok( + !C4::AuthoritiesMarc::CompareFieldWithAuthority( { 'field' => $field, 'authid' => 5 } ), + 'Authority does not match' + ); }; $schema->storage->txn_rollback; diff --git a/t/db_dependent/AuthoritiesMarc_GetTagsLabels.t b/t/db_dependent/AuthoritiesMarc_GetTagsLabels.t index f5d98e3542..2ddbda4536 100755 --- a/t/db_dependent/AuthoritiesMarc_GetTagsLabels.t +++ b/t/db_dependent/AuthoritiesMarc_GetTagsLabels.t @@ -28,7 +28,7 @@ use C4::AuthoritiesMarc qw( GetTagsLabels ); use Koha::Authority::Types; use Koha::Database; -my $schema = Koha::Database->new->schema; +my $schema = Koha::Database->new->schema; our $builder = t::lib::TestBuilder->new; $schema->storage->txn_begin; @@ -42,18 +42,24 @@ subtest 'GetTagsLabels' => sub { is( $tagslib, undef, 'Nothing in table' ); # Add one tag (and auth type), test librarian flag - my $tag = $builder->build_object({ class => 'Koha::Authority::Tags', value => { authtypecode => 'XX1', tagfield => '177' } }); + my $tag = $builder->build_object( + { class => 'Koha::Authority::Tags', value => { authtypecode => 'XX1', tagfield => '177' } } ); $tagslib = GetTagsLabels( 1, $tag->authtypecode ); - is( ref($tagslib), 'HASH', 'Should be a hash' ); - is( scalar keys %$tagslib, 1, 'Only one entry' ); - is( ref( $tagslib->{177} ), 'HASH' , 'Should be a hash' ); + is( ref($tagslib), 'HASH', 'Should be a hash' ); + is( scalar keys %$tagslib, 1, 'Only one entry' ); + is( ref( $tagslib->{177} ), 'HASH', 'Should be a hash' ); is( $tagslib->{177}->{lib}, $tag->liblibrarian, 'passed librarian flag' ); # Add subfield, test opac flag - my $sub = $builder->build_object({ class => 'Koha::Authority::Subfields', value => { authtypecode => 'XX1', tagfield => '177', tagsubfield => 'a' } }); + my $sub = $builder->build_object( + { + class => 'Koha::Authority::Subfields', + value => { authtypecode => 'XX1', tagfield => '177', tagsubfield => 'a' } + } + ); $tagslib = GetTagsLabels( 0, $tag->authtypecode ); - is( $tagslib->{177}->{lib}, $tag->libopac, 'passed opac flag' ); - is( ref( $tagslib->{177}->{a} ), 'HASH' , 'Should be a hash' ); + is( $tagslib->{177}->{lib}, $tag->libopac, 'passed opac flag' ); + is( ref( $tagslib->{177}->{a} ), 'HASH', 'Should be a hash' ); is( $tagslib->{177}->{a}->{lib}, $sub->libopac, 'opac lib in subfield' ); }; diff --git a/t/db_dependent/Authority/Merge.t b/t/db_dependent/Authority/Merge.t index 2336cf999c..c46ad51e9c 100755 --- a/t/db_dependent/Authority/Merge.t +++ b/t/db_dependent/Authority/Merge.t @@ -22,7 +22,7 @@ use Koha::Biblios; use Koha::Database; BEGIN { - use_ok('C4::AuthoritiesMarc', qw( merge AddAuthority DelAuthority ModAuthority )); + use_ok( 'C4::AuthoritiesMarc', qw( merge AddAuthority DelAuthority ModAuthority ) ); } # FIXME These tests fail if you pass this variable because we don't scaffold the authority types for UNIMARC @@ -33,7 +33,7 @@ GetOptions( 'flavour:s' => \$marcflavour ); $marcflavour //= 'MARC21'; t::lib::Mocks::mock_preference( 'marcflavour', $marcflavour ) if $marcflavour; -my $schema = Koha::Database->new->schema; +my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; my $heading_module = Test::MockModule->new('C4::Heading::MARC21'); @@ -60,102 +60,117 @@ subtest 'Test postponed merge feature' => sub { plan tests => 6; # Set limit to zero, and call merge a few times - t::lib::Mocks::mock_preference('AuthorityMergeLimit', 0); - my $auth1 = t::lib::TestBuilder->new->build({ source => 'AuthHeader' }); - my $cnt = Koha::Authority::MergeRequests->count; - merge({ mergefrom => '0' }); + t::lib::Mocks::mock_preference( 'AuthorityMergeLimit', 0 ); + my $auth1 = t::lib::TestBuilder->new->build( { source => 'AuthHeader' } ); + my $cnt = Koha::Authority::MergeRequests->count; + merge( { mergefrom => '0' } ); is( Koha::Authority::MergeRequests->count, $cnt, 'No merge request added as expected' ); - merge({ mergefrom => $auth1->{authid} }); + merge( { mergefrom => $auth1->{authid} } ); is( Koha::Authority::MergeRequests->count, $cnt, 'No merge request added since we have zero hits' ); - @linkedrecords = ( 1, 2 ); # these biblionumbers do not matter - merge({ mergefrom => $auth1->{authid} }); + @linkedrecords = ( 1, 2 ); # these biblionumbers do not matter + merge( { mergefrom => $auth1->{authid} } ); is( Koha::Authority::MergeRequests->count, $cnt + 1, 'Merge request added as expected' ); # Set limit to two (starting with two records) - t::lib::Mocks::mock_preference('AuthorityMergeLimit', 2); - merge({ mergefrom => $auth1->{authid} }); + t::lib::Mocks::mock_preference( 'AuthorityMergeLimit', 2 ); + merge( { mergefrom => $auth1->{authid} } ); is( Koha::Authority::MergeRequests->count, $cnt + 1, 'No merge request added as we do not exceed the limit' ); - @linkedrecords = ( 1, 2, 3 ); # these biblionumbers do not matter - merge({ mergefrom => $auth1->{authid} }); + @linkedrecords = ( 1, 2, 3 ); # these biblionumbers do not matter + merge( { mergefrom => $auth1->{authid} } ); is( Koha::Authority::MergeRequests->count, $cnt + 2, 'Merge request added as we do exceed the limit again' ); + # Now override - merge({ mergefrom => $auth1->{authid}, override_limit => 1 }); + merge( { mergefrom => $auth1->{authid}, override_limit => 1 } ); is( Koha::Authority::MergeRequests->count, $cnt + 2, 'No merge request added as we did override' ); # Set merge limit high enough for the other subtests - t::lib::Mocks::mock_preference('AuthorityMergeLimit', 1000); + t::lib::Mocks::mock_preference( 'AuthorityMergeLimit', 1000 ); }; subtest 'Test merge A1 to A2 (within same authtype)' => sub { -# Tests originate from bug 11700 + + # Tests originate from bug 11700 plan tests => 9; # Start in loose mode, although it actually does not matter here - t::lib::Mocks::mock_preference('AuthorityMergeMode', 'loose'); + t::lib::Mocks::mock_preference( 'AuthorityMergeMode', 'loose' ); # Add two authority records my $auth1 = MARC::Record->new; - $auth1->append_fields( MARC::Field->new( '109', '0', '0', 'a' => 'George Orwell' )); + $auth1->append_fields( MARC::Field->new( '109', '0', '0', 'a' => 'George Orwell' ) ); my $authid1 = AddAuthority( $auth1, undef, $authtype1 ); - my $auth2 = MARC::Record->new; - $auth2->append_fields( MARC::Field->new( '109', '0', '0', 'a' => 'G. Orwell' )); + my $auth2 = MARC::Record->new; + $auth2->append_fields( MARC::Field->new( '109', '0', '0', 'a' => 'G. Orwell' ) ); my $authid2 = AddAuthority( $auth2, undef, $authtype1 ); # Add two biblio records my $biblio1 = MARC::Record->new; - $biblio1->append_fields( MARC::Field->new( '609', '0', '0', '9' => $authid1, 'a' => 'George Orwell' )); - my ( $biblionumber1 ) = AddBiblio($biblio1, ''); + $biblio1->append_fields( MARC::Field->new( '609', '0', '0', '9' => $authid1, 'a' => 'George Orwell' ) ); + my ($biblionumber1) = AddBiblio( $biblio1, '' ); my $biblio2 = MARC::Record->new; - $biblio2->append_fields( MARC::Field->new( '609', '0', '0', '9' => $authid2, 'a' => 'G. Orwell' )); - my ( $biblionumber2 ) = AddBiblio($biblio2, ''); + $biblio2->append_fields( MARC::Field->new( '609', '0', '0', '9' => $authid2, 'a' => 'G. Orwell' ) ); + my ($biblionumber2) = AddBiblio( $biblio2, '' ); # Time to merge @linkedrecords = ( $biblionumber1, $biblionumber2 ); - my $rv = C4::AuthoritiesMarc::merge({ mergefrom => $authid2, MARCfrom => $auth2, mergeto => $authid1, MARCto => $auth1 }); + my $rv = C4::AuthoritiesMarc::merge( + { mergefrom => $authid2, MARCfrom => $auth2, mergeto => $authid1, MARCto => $auth1 } ); is( $rv, 1, 'We expect one biblio record (out of two) to be updated' ); # Check the results my $newbiblio1 = Koha::Biblios->find($biblionumber1)->metadata->record; compare_fields( $biblio1, $newbiblio1, {}, 'count' ); compare_fields( $biblio1, $newbiblio1, {}, 'order' ); - is( $newbiblio1->subfield('609', '9'), $authid1, 'Check biblio1 609$9' ); - is( $newbiblio1->subfield('609', 'a'), 'George Orwell', - 'Check biblio1 609$a' ); + is( $newbiblio1->subfield( '609', '9' ), $authid1, 'Check biblio1 609$9' ); + is( + $newbiblio1->subfield( '609', 'a' ), 'George Orwell', + 'Check biblio1 609$a' + ); my $newbiblio2 = Koha::Biblios->find($biblionumber2)->metadata->record; compare_fields( $biblio2, $newbiblio2, {}, 'count' ); compare_fields( $biblio2, $newbiblio2, {}, 'order' ); - is( $newbiblio2->subfield('609', '9'), $authid1, 'Check biblio2 609$9' ); - is( $newbiblio2->subfield('609', 'a'), 'George Orwell', - 'Check biblio2 609$a' ); + is( $newbiblio2->subfield( '609', '9' ), $authid1, 'Check biblio2 609$9' ); + is( + $newbiblio2->subfield( '609', 'a' ), 'George Orwell', + 'Check biblio2 609$a' + ); }; subtest 'Test merge A1 to modified A1, test strict mode' => sub { -# Tests originate from bug 11700 + + # Tests originate from bug 11700 plan tests => 12; # Simulate modifying an authority from auth1old to auth1new my $auth1old = MARC::Record->new; - $auth1old->append_fields( MARC::Field->new( '109', '0', '0', 'a' => 'Bruce Wayne' )); + $auth1old->append_fields( MARC::Field->new( '109', '0', '0', 'a' => 'Bruce Wayne' ) ); my $auth1new = $auth1old->clone; $auth1new->field('109')->update( a => 'Batman' ); my $authid1 = AddAuthority( $auth1new, undef, $authtype1 ); # Add two biblio records my $MARC1 = MARC::Record->new; - $MARC1->append_fields( MARC::Field->new( '109', '', '', 'a' => 'Bruce Wayne', 'b' => '2014', '9' => $authid1 )); - $MARC1->append_fields( MARC::Field->new( '245', '', '', 'a' => 'From the depths' )); - $MARC1->append_fields( MARC::Field->new( '609', '', '', 'a' => 'Bruce Lee', 'b' => 'Should be cleared too', '9' => $authid1 )); - $MARC1->append_fields( MARC::Field->new( '609', '', '', 'a' => 'Bruce Lee', 'c' => 'This is a duplicate to be removed in strict mode', '9' => $authid1 )); + $MARC1->append_fields( MARC::Field->new( '109', '', '', 'a' => 'Bruce Wayne', 'b' => '2014', '9' => $authid1 ) ); + $MARC1->append_fields( MARC::Field->new( '245', '', '', 'a' => 'From the depths' ) ); + $MARC1->append_fields( + MARC::Field->new( '609', '', '', 'a' => 'Bruce Lee', 'b' => 'Should be cleared too', '9' => $authid1 ) ); + $MARC1->append_fields( + MARC::Field->new( + '609', '', '', 'a' => 'Bruce Lee', 'c' => 'This is a duplicate to be removed in strict mode', + '9' => $authid1 + ) + ); my $MARC2 = MARC::Record->new; - $MARC2->append_fields( MARC::Field->new( '109', '', '', 'a' => 'Batman', '9' => $authid1 )); - $MARC2->append_fields( MARC::Field->new( '245', '', '', 'a' => 'All the way to heaven' )); - my ( $biblionumber1 ) = AddBiblio( $MARC1, ''); - my ( $biblionumber2 ) = AddBiblio( $MARC2, ''); + $MARC2->append_fields( MARC::Field->new( '109', '', '', 'a' => 'Batman', '9' => $authid1 ) ); + $MARC2->append_fields( MARC::Field->new( '245', '', '', 'a' => 'All the way to heaven' ) ); + my ($biblionumber1) = AddBiblio( $MARC1, '' ); + my ($biblionumber2) = AddBiblio( $MARC2, '' ); # Time to merge in loose mode first @linkedrecords = ( $biblionumber1, $biblionumber2 ); - t::lib::Mocks::mock_preference('AuthorityMergeMode', 'loose'); - my $rv = C4::AuthoritiesMarc::merge({ mergefrom => $authid1, MARCfrom => $auth1old, mergeto => $authid1, MARCto => $auth1new }); + t::lib::Mocks::mock_preference( 'AuthorityMergeMode', 'loose' ); + my $rv = C4::AuthoritiesMarc::merge( + { mergefrom => $authid1, MARCfrom => $auth1old, mergeto => $authid1, MARCto => $auth1new } ); is( $rv, 2, 'Both records are updated now' ); #Check the results @@ -167,41 +182,50 @@ subtest 'Test merge A1 to modified A1, test strict mode' => sub { compare_fields( $MARC2, $biblio2, {}, 'count' ); compare_fields( $MARC2, $biblio2, {}, 'order' ); is( $auth1new->field(109)->subfield('a'), $biblio2->field(109)->subfield('a'), 'Record2 values updated correctly' ); + # This is only true in loose mode: - is( $biblio1->field(109)->subfield('b'), $MARC1->field(109)->subfield('b'), 'Subfield not overwritten in loose mode'); + is( + $biblio1->field(109)->subfield('b'), $MARC1->field(109)->subfield('b'), + 'Subfield not overwritten in loose mode' + ); # Merge again in strict mode - t::lib::Mocks::mock_preference('AuthorityMergeMode', 'strict'); + t::lib::Mocks::mock_preference( 'AuthorityMergeMode', 'strict' ); ModBiblio( $MARC1, $biblionumber1, '' ); - @linkedrecords = ( $biblionumber1 ); - $rv = C4::AuthoritiesMarc::merge({ mergefrom => $authid1, MARCfrom => $auth1old, mergeto => $authid1, MARCto => $auth1new }); + @linkedrecords = ($biblionumber1); + $rv = C4::AuthoritiesMarc::merge( + { mergefrom => $authid1, MARCfrom => $auth1old, mergeto => $authid1, MARCto => $auth1new } ); $biblio1 = Koha::Biblios->find($biblionumber1)->metadata->record; is( $biblio1->field(109)->subfield('b'), undef, 'Subfield overwritten in strict mode' ); compare_fields( $MARC1, $biblio1, { 609 => 1 }, 'count' ); my @old609 = $MARC1->field('609'); my @new609 = $biblio1->field('609'); is( scalar @new609, @old609 - 1, 'strict mode should remove a duplicate 609' ); - is( $biblio1->field(609)->subfields, - scalar($auth1new->field('109')->subfields) + 1, - 'Check number of subfields in strict mode for the remaining 609' ); - # Note: the +1 comes from the added subfield $9 in the biblio + is( + $biblio1->field(609)->subfields, + scalar( $auth1new->field('109')->subfields ) + 1, + 'Check number of subfields in strict mode for the remaining 609' + ); + + # Note: the +1 comes from the added subfield $9 in the biblio }; subtest 'Test merge A1 to B1 (changing authtype)' => sub { -# Tests were aimed for bug 9988, moved to 17909 in adjusted form -# Would not encourage this type of merge, but we should test what we offer + + # Tests were aimed for bug 9988, moved to 17909 in adjusted form + # Would not encourage this type of merge, but we should test what we offer plan tests => 13; # Get back to loose mode now - t::lib::Mocks::mock_preference('AuthorityMergeMode', 'loose'); + t::lib::Mocks::mock_preference( 'AuthorityMergeMode', 'loose' ); # create two auth recs of different type my $auth1 = MARC::Record->new; - $auth1->append_fields( MARC::Field->new( '109', '0', '0', 'a' => 'George Orwell', b => 'bb' )); + $auth1->append_fields( MARC::Field->new( '109', '0', '0', 'a' => 'George Orwell', b => 'bb' ) ); my $authid1 = AddAuthority( $auth1, undef, $authtype1 ); - my $auth2 = MARC::Record->new; - $auth2->append_fields( MARC::Field->new( '112', '0', '0', 'a' => 'Batman', c => 'cc' )); - my $authid2 = AddAuthority($auth2, undef, $authtype2 ); + my $auth2 = MARC::Record->new; + $auth2->append_fields( MARC::Field->new( '112', '0', '0', 'a' => 'Batman', c => 'cc' ) ); + my $authid2 = AddAuthority( $auth2, undef, $authtype2 ); # create a biblio with one 109 and two 609s to be touched # seems exceptional see bug 13760 comment10 @@ -215,68 +239,92 @@ subtest 'Test merge A1 to B1 (changing authtype)' => sub { MARC::Field->new( '611', '', '', a => 'Added for testing order' ), MARC::Field->new( '612', '', '', a => 'unrelated', 9 => 'other' ), ); - my ( $biblionumber ) = C4::Biblio::AddBiblio( $marc, '' ); + my ($biblionumber) = C4::Biblio::AddBiblio( $marc, '' ); my $oldbiblio = Koha::Biblios->find($biblionumber)->metadata->record; # Time to merge - @linkedrecords = ( $biblionumber ); - my $retval = C4::AuthoritiesMarc::merge({ mergefrom => $authid1, MARCfrom => $auth1, mergeto => $authid2, MARCto => $auth2 }); + @linkedrecords = ($biblionumber); + my $retval = C4::AuthoritiesMarc::merge( + { mergefrom => $authid1, MARCfrom => $auth1, mergeto => $authid2, MARCto => $auth2 } ); is( $retval, 1, 'We touched only one biblio' ); # Get new marc record for compares my $newbiblio = Koha::Biblios->find($biblionumber)->metadata->record; compare_fields( $oldbiblio, $newbiblio, {}, 'count' ); + # Exclude 109/609 and 112/612 in comparing order my $excl = { '109' => 1, '112' => 1, '609' => 1, '612' => 1 }; compare_fields( $oldbiblio, $newbiblio, $excl, 'order' ); + # Check position of 612s in the new record my $full_order = join q/,/, map { $_->tag } $newbiblio->fields; is( $full_order =~ /611(,612){3}/, 1, 'Check position of all 612s' ); # Check some fields - is( $newbiblio->field('003')->data, + is( + $newbiblio->field('003')->data, $oldbiblio->field('003')->data, - 'Check contents of a control field not expected to be touched' ); - is( $newbiblio->subfield( '245', 'a' ), + 'Check contents of a control field not expected to be touched' + ); + is( + $newbiblio->subfield( '245', 'a' ), $oldbiblio->subfield( '245', 'a' ), - 'Check contents of a data field not expected to be touched' ); - is( $newbiblio->subfield( '112', 'a' ), - $auth2->subfield( '112', 'a' ), 'Check modified 112a' ); - is( $newbiblio->subfield( '112', 'c' ), - $auth2->subfield( '112', 'c' ), 'Check new 112c' ); + 'Check contents of a data field not expected to be touched' + ); + is( + $newbiblio->subfield( '112', 'a' ), + $auth2->subfield( '112', 'a' ), 'Check modified 112a' + ); + is( + $newbiblio->subfield( '112', 'c' ), + $auth2->subfield( '112', 'c' ), 'Check new 112c' + ); # Check 112b; this subfield was cleared when moving from 109 to 112 # Note that this fix only applies to the current loose mode only - is( $newbiblio->subfield( '112', 'b' ), undef, - 'Merge respects a cleared subfield in loose mode' ); + is( + $newbiblio->subfield( '112', 'b' ), undef, + 'Merge respects a cleared subfield in loose mode' + ); # Check the original 612 - is( ( $newbiblio->field('612') )[0]->subfield( 'a' ), - $oldbiblio->subfield( '612', 'a' ), 'Check untouched 612a' ); + is( + ( $newbiblio->field('612') )[0]->subfield('a'), + $oldbiblio->subfield( '612', 'a' ), 'Check untouched 612a' + ); + # Check second 612 - is( ( $newbiblio->field('612') )[1]->subfield( 'a' ), - $auth2->subfield( '112', 'a' ), 'Check second touched 612a' ); + is( + ( $newbiblio->field('612') )[1]->subfield('a'), + $auth2->subfield( '112', 'a' ), 'Check second touched 612a' + ); + # Check second new 612ax (in LOOSE mode) - is( ( $newbiblio->field('612') )[2]->subfield( 'a' ), - $auth2->subfield( '112', 'a' ), 'Check touched 612a' ); - is( ( $newbiblio->field('612') )[2]->subfield( 'x' ), + is( + ( $newbiblio->field('612') )[2]->subfield('a'), + $auth2->subfield( '112', 'a' ), 'Check touched 612a' + ); + is( + ( $newbiblio->field('612') )[2]->subfield('x'), ( $oldbiblio->field('609') )[1]->subfield('x'), - 'Check 612x' ); + 'Check 612x' + ); }; subtest 'Test update A with modified heading tag (changing authtype)' => sub { -# Bug 19693 -# This would happen rarely when updating authorities from authority file -# when the tag of a heading field is being changed (and thus also -# the authtype) + + # Bug 19693 + # This would happen rarely when updating authorities from authority file + # when the tag of a heading field is being changed (and thus also + # the authtype) plan tests => 13; # Get back to loose mode now - t::lib::Mocks::mock_preference('AuthorityMergeMode', 'loose'); + t::lib::Mocks::mock_preference( 'AuthorityMergeMode', 'loose' ); # create an auth rec my $auth1 = MARC::Record->new; - $auth1->append_fields( MARC::Field->new( '109', '0', '0', 'a' => 'George Orwell', b => 'bb' )); + $auth1->append_fields( MARC::Field->new( '109', '0', '0', 'a' => 'George Orwell', b => 'bb' ) ); my $authid1 = AddAuthority( $auth1, undef, $authtype1 ); # create a biblio with one 109 and two 609s to be touched @@ -291,14 +339,15 @@ subtest 'Test update A with modified heading tag (changing authtype)' => sub { MARC::Field->new( '611', '', '', a => 'Added for testing order' ), MARC::Field->new( '612', '', '', a => 'unrelated', 9 => 'other' ), ); - my ( $biblionumber ) = C4::Biblio::AddBiblio( $marc, '' ); + my ($biblionumber) = C4::Biblio::AddBiblio( $marc, '' ); my $oldbiblio = Koha::Biblios->find($biblionumber)->metadata->record; # Time to merge - @linkedrecords = ( $biblionumber ); + @linkedrecords = ($biblionumber); my $auth2 = MARC::Record->new; - $auth2->append_fields( MARC::Field->new( '112', '0', '0', 'a' => 'Batman', c => 'cc' )); - my $authid2 = ModAuthority($authid1, $auth2, $authtype2 ); + $auth2->append_fields( MARC::Field->new( '112', '0', '0', 'a' => 'Batman', c => 'cc' ) ); + my $authid2 = ModAuthority( $authid1, $auth2, $authtype2 ); + # inside ModAuthority the following is executed: # merge({ mergefrom => $authid1, MARCfrom => $auth1, mergeto => $authid1, MARCto => $auth2 }); is( $authid2, $authid1, 'authid after ModAuthority OK' ); @@ -306,42 +355,64 @@ subtest 'Test update A with modified heading tag (changing authtype)' => sub { # Get new marc record for compares my $newbiblio = Koha::Biblios->find($biblionumber)->metadata->record; compare_fields( $oldbiblio, $newbiblio, {}, 'count' ); + # Exclude 109/609 and 112/612 in comparing order my $excl = { '109' => 1, '112' => 1, '609' => 1, '612' => 1 }; compare_fields( $oldbiblio, $newbiblio, $excl, 'order' ); + # Check position of 612s in the new record my $full_order = join q/,/, map { $_->tag } $newbiblio->fields; is( $full_order =~ /611(,612){3}/, 1, 'Check position of all 612s' ); # Check some fields - is( $newbiblio->field('003')->data, + is( + $newbiblio->field('003')->data, $oldbiblio->field('003')->data, - 'Check contents of a control field not expected to be touched' ); - is( $newbiblio->subfield( '245', 'a' ), + 'Check contents of a control field not expected to be touched' + ); + is( + $newbiblio->subfield( '245', 'a' ), $oldbiblio->subfield( '245', 'a' ), - 'Check contents of a data field not expected to be touched' ); - is( $newbiblio->subfield( '112', 'a' ), - $auth2->subfield( '112', 'a' ), 'Check modified 112a' ); - is( $newbiblio->subfield( '112', 'c' ), - $auth2->subfield( '112', 'c' ), 'Check new 112c' ); + 'Check contents of a data field not expected to be touched' + ); + is( + $newbiblio->subfield( '112', 'a' ), + $auth2->subfield( '112', 'a' ), 'Check modified 112a' + ); + is( + $newbiblio->subfield( '112', 'c' ), + $auth2->subfield( '112', 'c' ), 'Check new 112c' + ); # Check 112b; this subfield was cleared when moving from 109 to 112 # Note that this fix only applies to the current loose mode only - is( $newbiblio->subfield( '112', 'b' ), undef, - 'Merge respects a cleared subfield in loose mode' ); + is( + $newbiblio->subfield( '112', 'b' ), undef, + 'Merge respects a cleared subfield in loose mode' + ); # Check the original 612 - is( ( $newbiblio->field('612') )[0]->subfield( 'a' ), - $oldbiblio->subfield( '612', 'a' ), 'Check untouched 612a' ); + is( + ( $newbiblio->field('612') )[0]->subfield('a'), + $oldbiblio->subfield( '612', 'a' ), 'Check untouched 612a' + ); + # Check second 612 - is( ( $newbiblio->field('612') )[1]->subfield( 'a' ), - $auth2->subfield( '112', 'a' ), 'Check second touched 612a' ); + is( + ( $newbiblio->field('612') )[1]->subfield('a'), + $auth2->subfield( '112', 'a' ), 'Check second touched 612a' + ); + # Check second new 612ax (in LOOSE mode) - is( ( $newbiblio->field('612') )[2]->subfield( 'a' ), - $auth2->subfield( '112', 'a' ), 'Check touched 612a' ); - is( ( $newbiblio->field('612') )[2]->subfield( 'x' ), + is( + ( $newbiblio->field('612') )[2]->subfield('a'), + $auth2->subfield( '112', 'a' ), 'Check touched 612a' + ); + is( + ( $newbiblio->field('612') )[2]->subfield('x'), ( $oldbiblio->field('609') )[1]->subfield('x'), - 'Check 612x' ); + 'Check 612x' + ); }; subtest 'Merging authorities should handle deletes (BZ 18070)' => sub { @@ -349,16 +420,16 @@ subtest 'Merging authorities should handle deletes (BZ 18070)' => sub { # Add authority and linked biblio, delete authority my $auth1 = MARC::Record->new; - $auth1->append_fields( MARC::Field->new( '109', '', '', 'a' => 'DEL')); + $auth1->append_fields( MARC::Field->new( '109', '', '', 'a' => 'DEL' ) ); my $authid1 = AddAuthority( $auth1, undef, $authtype1 ); - my $bib1 = MARC::Record->new; + my $bib1 = MARC::Record->new; $bib1->append_fields( MARC::Field->new( '245', '', '', a => 'test DEL' ), MARC::Field->new( '609', '', '', a => 'DEL', 9 => "$authid1" ), ); - my ( $biblionumber ) = C4::Biblio::AddBiblio( $bib1, '' ); - @linkedrecords = ( $biblionumber ); - DelAuthority({ authid => $authid1 }); # this triggers a merge call + my ($biblionumber) = C4::Biblio::AddBiblio( $bib1, '' ); + @linkedrecords = ($biblionumber); + DelAuthority( { authid => $authid1 } ); # this triggers a merge call # See what happened in the biblio record my $marc1 = Koha::Biblios->find($biblionumber)->metadata->record; @@ -367,12 +438,13 @@ subtest 'Merging authorities should handle deletes (BZ 18070)' => sub { # Now we simulate the delete as done in the cron job # First, restore auth1 and add 609 back in bib1 $auth1 = MARC::Record->new; - $auth1->append_fields( MARC::Field->new( '109', '', '', 'a' => 'DEL')); + $auth1->append_fields( MARC::Field->new( '109', '', '', 'a' => 'DEL' ) ); $authid1 = AddAuthority( $auth1, undef, $authtype1 ); $marc1->append_fields( MARC::Field->new( '609', '', '', a => 'DEL', 9 => "$authid1" ), ); ModBiblio( $marc1, $biblionumber, '' ); + # Instead of going through DelAuthority, we manually delete the auth # record and call merge afterwards. # This mimics deleting an authority and calling merge later in the @@ -381,7 +453,8 @@ subtest 'Merging authorities should handle deletes (BZ 18070)' => sub { C4::Context->dbh->do( "DELETE FROM auth_header WHERE authid=?", undef, $authid1 ); @linkedrecords = (); $mocks->{auth_mod}->unmock_all; - merge({ mergefrom => $authid1, biblionumbers => [ $biblionumber ] }); + merge( { mergefrom => $authid1, biblionumbers => [$biblionumber] } ); + # Final check $marc1 = Koha::Biblios->find($biblionumber)->metadata->record; is( $marc1->field('609'), undef, 'Merge removed the 609 again even after deleting the authority record' ); @@ -391,29 +464,34 @@ subtest "Test some specific postponed merge issues" => sub { plan tests => 6; my $authmarc = MARC::Record->new; - $authmarc->append_fields( MARC::Field->new( '109', '', '', 'a' => 'aa', b => 'bb' )); + $authmarc->append_fields( MARC::Field->new( '109', '', '', 'a' => 'aa', b => 'bb' ) ); my $oldauthmarc = MARC::Record->new; - $oldauthmarc->append_fields( MARC::Field->new( '112', '', '', c => 'cc' )); - my $id = AddAuthority( $authmarc, undef, $authtype1 ); + $oldauthmarc->append_fields( MARC::Field->new( '112', '', '', c => 'cc' ) ); + my $id = AddAuthority( $authmarc, undef, $authtype1 ); my $biblio = MARC::Record->new; $biblio->append_fields( MARC::Field->new( '109', '', '', a => 'a1', 9 => $id ), - MARC::Field->new( '612', '', '', a => 'a2', c => 'cc', 9 => $id+1 ), - MARC::Field->new( '612', '', '', a => 'a3', 9 => $id+2 ), + MARC::Field->new( '612', '', '', a => 'a2', c => 'cc', 9 => $id + 1 ), + MARC::Field->new( '612', '', '', a => 'a3', 9 => $id + 2 ), ); - my ( $biblionumber ) = C4::Biblio::AddBiblio( $biblio, '' ); + my ($biblionumber) = C4::Biblio::AddBiblio( $biblio, '' ); # Merge A to B postponed, A is deleted (simulated by id+1) # This proves the !authtypefrom condition in sub merge # Additionally, we test clearing subfield - merge({ mergefrom => $id + 1, MARCfrom => $oldauthmarc, mergeto => $id, MARCto => $authmarc, biblionumbers => [ $biblionumber ] }); + merge( + { + mergefrom => $id + 1, MARCfrom => $oldauthmarc, mergeto => $id, MARCto => $authmarc, + biblionumbers => [$biblionumber] + } + ); $biblio = Koha::Biblios->find($biblionumber)->metadata->record; - is( $biblio->subfield('609', '9'), $id, '612 moved to 609' ); - is( $biblio->subfield('609', 'c'), undef, '609c cleared correctly' ); + is( $biblio->subfield( '609', '9' ), $id, '612 moved to 609' ); + is( $biblio->subfield( '609', 'c' ), undef, '609c cleared correctly' ); # Merge A to B postponed, delete B immediately (hits B < hits A) # This proves the !@record_to test in sub merge - merge({ mergefrom => $id + 2, mergeto => $id + 1, MARCto => undef, biblionumbers => [ $biblionumber ] }); + merge( { mergefrom => $id + 2, mergeto => $id + 1, MARCto => undef, biblionumbers => [$biblionumber] } ); $biblio = Koha::Biblios->find($biblionumber)->metadata->record; is( $biblio->field('612'), undef, 'Last 612 must be gone' ); @@ -422,23 +500,27 @@ subtest "Test some specific postponed merge issues" => sub { # Suppose: Merge A to B postponed, and delete A would merge rightaway. # (You would need some special race condition with merge.pl to do so.) # The modify merge would be useless after that. - @linkedrecords = ( $biblionumber ); + @linkedrecords = ($biblionumber); my $restored_mocks = set_mocks(); - DelAuthority({ authid => $id, skip_merge => 1 }); # delete A + DelAuthority( { authid => $id, skip_merge => 1 } ); # delete A $restored_mocks->{auth_mod}->unmock_all; $biblio = Koha::Biblios->find($biblionumber)->metadata->record; - is( $biblio->subfield('109', '9'), $id, 'If the 109 is no longer present, another modify merge would not bring it back' ); + is( + $biblio->subfield( '109', '9' ), $id, + 'If the 109 is no longer present, another modify merge would not bring it back' + ); # Bug 22437 now removes older postponed A->A merges in DelAuthority $id = AddAuthority( $authmarc, undef, $authtype1 ); - my $merge = Koha::Authority::MergeRequest->new({ authid => $id })->store; - DelAuthority({ authid => $id, skip_merge => 1 }); + my $merge = Koha::Authority::MergeRequest->new( { authid => $id } )->store; + DelAuthority( { authid => $id, skip_merge => 1 } ); $merge->discard_changes; is( $merge->in_storage, 0, 'Older merge should be removed' ); + # And even if we don't pass skip_merge - $id = AddAuthority( $authmarc, undef, $authtype1 ); - $merge = Koha::Authority::MergeRequest->new({ authid => $id })->store; - DelAuthority({ authid => $id }); + $id = AddAuthority( $authmarc, undef, $authtype1 ); + $merge = Koha::Authority::MergeRequest->new( { authid => $id } )->store; + DelAuthority( { authid => $id } ); $merge->discard_changes; is( $merge->in_storage, 0, 'Older merge should be removed again' ); }; @@ -451,11 +533,11 @@ subtest "Graceful resolution of missing reporting tag" => sub { # in order to allow a future merge to restore data. # Accomplish the above by clearing reporting tag in $authtype2 - my $fw2 = Koha::Authority::Types->find( $authtype2 ); + my $fw2 = Koha::Authority::Types->find($authtype2); $fw2->auth_tag_to_report('')->store; my $authmarc = MARC::Record->new; - $authmarc->append_fields( MARC::Field->new( '109', '', '', 'a' => 'aa', b => 'bb' )); + $authmarc->append_fields( MARC::Field->new( '109', '', '', 'a' => 'aa', b => 'bb' ) ); my $id1 = AddAuthority( $authmarc, undef, $authtype1 ); my $id2 = AddAuthority( $authmarc, undef, $authtype2 ); @@ -463,13 +545,18 @@ subtest "Graceful resolution of missing reporting tag" => sub { $biblio->append_fields( MARC::Field->new( '609', '', '', a => 'aa', 9 => $id1 ), ); - my ( $biblionumber ) = C4::Biblio::AddBiblio( $biblio, '' ); + my ($biblionumber) = C4::Biblio::AddBiblio( $biblio, '' ); # Merge - merge({ mergefrom => $id1, MARCfrom => $authmarc, mergeto => $id2, MARCto => $authmarc, biblionumbers => [ $biblionumber ] }); + merge( + { + mergefrom => $id1, MARCfrom => $authmarc, mergeto => $id2, MARCto => $authmarc, + biblionumbers => [$biblionumber] + } + ); $biblio = Koha::Biblios->find($biblionumber)->metadata->record; - is( $biblio->subfield('612', '9'), $id2, 'id2 saved in $9' ); - is( $biblio->subfield('612', 'a'), ' ', 'Kept an empty $a too' ); + is( $biblio->subfield( '612', '9' ), $id2, 'id2 saved in $9' ); + is( $biblio->subfield( '612', 'a' ), ' ', 'Kept an empty $a too' ); $fw2->auth_tag_to_report('112')->store; }; @@ -478,21 +565,28 @@ subtest 'merge should not reorder too much' => sub { plan tests => 2; # Back to loose mode - t::lib::Mocks::mock_preference('AuthorityMergeMode', 'loose'); + t::lib::Mocks::mock_preference( 'AuthorityMergeMode', 'loose' ); my $authmarc = MARC::Record->new; - $authmarc->append_fields( MARC::Field->new( '109', '', '', 'a' => 'aa', b => 'bb' )); - my $id = AddAuthority( $authmarc, undef, $authtype1 ); + $authmarc->append_fields( MARC::Field->new( '109', '', '', 'a' => 'aa', b => 'bb' ) ); + my $id = AddAuthority( $authmarc, undef, $authtype1 ); my $biblio = MARC::Record->new; $biblio->append_fields( - MARC::Field->new( '109', '', '', 9 => $id, i => 'in front', a => 'aa', c => 'after controlled block' ), # this field shows the old situation when $9 is the first subfield - MARC::Field->new( '609', '', '', i => 'in front', a => 'aa', c => 'after controlled block', 9 => $id ), # here $9 is already the last one + MARC::Field->new( '109', '', '', 9 => $id, i => 'in front', a => 'aa', c => 'after controlled block' ) + , # this field shows the old situation when $9 is the first subfield + MARC::Field->new( '609', '', '', i => 'in front', a => 'aa', c => 'after controlled block', 9 => $id ) + , # here $9 is already the last one ); - my ( $biblionumber ) = C4::Biblio::AddBiblio( $biblio, '' ); + my ($biblionumber) = C4::Biblio::AddBiblio( $biblio, '' ); # Merge 109 and 609 and check order of subfields - merge({ mergefrom => $id, MARCfrom => $authmarc, mergeto => $id, MARCto => $authmarc, biblionumbers => [ $biblionumber ] }); - my $biblio2 = Koha::Biblios->find($biblionumber)->metadata->record; + merge( + { + mergefrom => $id, MARCfrom => $authmarc, mergeto => $id, MARCto => $authmarc, + biblionumbers => [$biblionumber] + } + ); + my $biblio2 = Koha::Biblios->find($biblionumber)->metadata->record; my $subfields = [ map { $_->[0] } $biblio2->field('109')->subfields ]; is_deeply( $subfields, [ 'i', 'a', 'b', 'c', '9' ], 'Merge only moved $9' ); $subfields = [ map { $_->[0] } $biblio2->field('609')->subfields ]; @@ -505,34 +599,44 @@ subtest 'Test how merge handles controlled indicators' => sub { # Note: See more detailed tests in t/Koha/Authority/ControlledIndicators.t # Testing MARC21 because thesaurus code makes it more interesting - t::lib::Mocks::mock_preference( 'marcflavour', 'MARC21' ); - t::lib::Mocks::mock_preference('AuthorityControlledIndicators', q|marc21,*,ind1:auth1,ind2:thesaurus|); + t::lib::Mocks::mock_preference( 'marcflavour', 'MARC21' ); + t::lib::Mocks::mock_preference( 'AuthorityControlledIndicators', q|marc21,*,ind1:auth1,ind2:thesaurus| ); my $authmarc = MARC::Record->new; $authmarc->append_fields( - MARC::Field->new( '008', (' 'x11).'r' ), # thesaurus code + MARC::Field->new( '008', ( ' ' x 11 ) . 'r' ), # thesaurus code MARC::Field->new( '109', '7', '', 'a' => 'a' ), ); - my $id = AddAuthority( $authmarc, undef, $authtype1 ); + my $id = AddAuthority( $authmarc, undef, $authtype1 ); my $biblio = MARC::Record->new; $biblio->append_fields( MARC::Field->new( '609', '8', '4', a => 'a', 2 => '2', 9 => $id ), ); - my ( $biblionumber ) = C4::Biblio::AddBiblio( $biblio, '' ); + my ($biblionumber) = C4::Biblio::AddBiblio( $biblio, '' ); # Merge and check indicators and $2 - merge({ mergefrom => $id, MARCfrom => $authmarc, mergeto => $id, MARCto => $authmarc, biblionumbers => [ $biblionumber ] }); + merge( + { + mergefrom => $id, MARCfrom => $authmarc, mergeto => $id, MARCto => $authmarc, + biblionumbers => [$biblionumber] + } + ); my $biblio2 = Koha::Biblios->find($biblionumber)->metadata->record; - is( $biblio2->field('609')->indicator(1), '7', 'Indicator1 OK' ); - is( $biblio2->field('609')->indicator(2), '7', 'Indicator2 OK' ); - is( $biblio2->subfield('609', '2'), 'aat', 'Subfield $2 OK' ); + is( $biblio2->field('609')->indicator(1), '7', 'Indicator1 OK' ); + is( $biblio2->field('609')->indicator(2), '7', 'Indicator2 OK' ); + is( $biblio2->subfield( '609', '2' ), 'aat', 'Subfield $2 OK' ); # Test $2 removal now - $authmarc->field('008')->update( (' 'x11).'a' ); # LOC, no $2 needed - AddAuthority( $authmarc, $id, $authtype1 ); # modify - merge({ mergefrom => $id, MARCfrom => $authmarc, mergeto => $id, MARCto => $authmarc, biblionumbers => [ $biblionumber ] }); + $authmarc->field('008')->update( ( ' ' x 11 ) . 'a' ); # LOC, no $2 needed + AddAuthority( $authmarc, $id, $authtype1 ); # modify + merge( + { + mergefrom => $id, MARCfrom => $authmarc, mergeto => $id, MARCto => $authmarc, + biblionumbers => [$biblionumber] + } + ); $biblio2 = Koha::Biblios->find($biblionumber)->metadata->record; - is( $biblio2->subfield('609', '2'), undef, 'No subfield $2 left' ); + is( $biblio2->subfield( '609', '2' ), undef, 'No subfield $2 left' ); }; subtest "Test bibs not auto linked when merging" => sub { @@ -573,17 +677,24 @@ subtest "Test bibs not auto linked when merging" => sub { }; sub set_mocks { + # After we removed the Zebra code from merge, we only need to mock # get_usage_count and linked_biblionumbers here. my $mocks; - $mocks->{auth_mod} = Test::MockModule->new( 'Koha::Authorities' ); - $mocks->{auth_mod}->mock( 'get_usage_count', sub { - return scalar @linkedrecords; - }); - $mocks->{auth_mod}->mock( 'linked_biblionumbers', sub { - return @linkedrecords; - }); + $mocks->{auth_mod} = Test::MockModule->new('Koha::Authorities'); + $mocks->{auth_mod}->mock( + 'get_usage_count', + sub { + return scalar @linkedrecords; + } + ); + $mocks->{auth_mod}->mock( + 'linked_biblionumbers', + sub { + return @linkedrecords; + } + ); return $mocks; } @@ -591,79 +702,92 @@ sub modify_framework { my $builder = t::lib::TestBuilder->new; # create two auth types - my $authtype1 = $builder->build({ - source => 'AuthType', - value => { - auth_tag_to_report => '109', - }, - }); - my $authtype2 = $builder->build({ - source => 'AuthType', - value => { - auth_tag_to_report => '112', - }, - }); + my $authtype1 = $builder->build( + { + source => 'AuthType', + value => { + auth_tag_to_report => '109', + }, + } + ); + my $authtype2 = $builder->build( + { + source => 'AuthType', + value => { + auth_tag_to_report => '112', + }, + } + ); # Link 109/609 to the first authtype - $builder->build({ - source => 'MarcSubfieldStructure', - value => { - tagfield => '109', - tagsubfield => 'a', - authtypecode => $authtype1->{authtypecode}, - frameworkcode => '', - }, - }); - $builder->build({ - source => 'MarcSubfieldStructure', - value => { - tagfield => '609', - tagsubfield => 'a', - authtypecode => $authtype1->{authtypecode}, - frameworkcode => '', - }, - }); + $builder->build( + { + source => 'MarcSubfieldStructure', + value => { + tagfield => '109', + tagsubfield => 'a', + authtypecode => $authtype1->{authtypecode}, + frameworkcode => '', + }, + } + ); + $builder->build( + { + source => 'MarcSubfieldStructure', + value => { + tagfield => '609', + tagsubfield => 'a', + authtypecode => $authtype1->{authtypecode}, + frameworkcode => '', + }, + } + ); # Link 112/612 to the second authtype - $builder->build({ - source => 'MarcSubfieldStructure', - value => { - tagfield => '112', - tagsubfield => 'a', - authtypecode => $authtype2->{authtypecode}, - frameworkcode => '', - }, - }); - $builder->build({ - source => 'MarcSubfieldStructure', - value => { - tagfield => '612', - tagsubfield => 'a', - authtypecode => $authtype2->{authtypecode}, - frameworkcode => '', - }, - }); + $builder->build( + { + source => 'MarcSubfieldStructure', + value => { + tagfield => '112', + tagsubfield => 'a', + authtypecode => $authtype2->{authtypecode}, + frameworkcode => '', + }, + } + ); + $builder->build( + { + source => 'MarcSubfieldStructure', + value => { + tagfield => '612', + tagsubfield => 'a', + authtypecode => $authtype2->{authtypecode}, + frameworkcode => '', + }, + } + ); return ( $authtype1->{authtypecode}, $authtype2->{authtypecode} ); } -sub compare_fields { # mode parameter: order or count +sub compare_fields { # mode parameter: order or count my ( $oldmarc, $newmarc, $exclude, $mode ) = @_; $exclude //= {}; - if( C4::Context->preference('marcflavour') eq 'UNIMARC' ) { + if ( C4::Context->preference('marcflavour') eq 'UNIMARC' ) { + # By default exclude field 100 from comparison in UNIMARC. # Will have been added by ModBiblio in merge. $exclude->{100} = 1; - } else { #MARC21 + } else { #MARC21 $exclude->{'005'} = 1; } - my @oldfields = map { $exclude->{$_->tag} ? () : $_->tag } $oldmarc->fields; - my @newfields = map { $exclude->{$_->tag} ? () : $_->tag } $newmarc->fields; + my @oldfields = map { $exclude->{ $_->tag } ? () : $_->tag } $oldmarc->fields; + my @newfields = map { $exclude->{ $_->tag } ? () : $_->tag } $newmarc->fields; - if( $mode eq 'count' ) { + if ( $mode eq 'count' ) { my $t; is( scalar @newfields, $t = @oldfields, "Number of fields still equal to $t" ); - } elsif( $mode eq 'order' ) { + } elsif ( $mode eq 'order' ) { is( ( join q/,/, @newfields ), ( join q/,/, @oldfields ), 'Order of fields unchanged' ); } } diff --git a/t/db_dependent/Authority/MergeRequests.t b/t/db_dependent/Authority/MergeRequests.t index bba791992a..55fac79f51 100755 --- a/t/db_dependent/Authority/MergeRequests.t +++ b/t/db_dependent/Authority/MergeRequests.t @@ -8,7 +8,7 @@ use Koha::Authority::MergeRequests; use Koha::Database; use Koha::DateUtils qw/dt_from_string/; -my $schema = Koha::Database->new->schema; +my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; subtest "Tests for cron_cleanup" => sub { @@ -16,28 +16,32 @@ subtest "Tests for cron_cleanup" => sub { my $dt = dt_from_string; $dt->subtract( hours => 2 ); - my $req1 = Koha::Authority::MergeRequest->new({ - authid => 1, - done => 2, - timestamp => $dt, - })->store; + my $req1 = Koha::Authority::MergeRequest->new( + { + authid => 1, + done => 2, + timestamp => $dt, + } + )->store; $dt->subtract( days => 30 ); - my $req2 = Koha::Authority::MergeRequest->new({ - authid => 2, - done => 1, - timestamp => $dt, - })->store; + my $req2 = Koha::Authority::MergeRequest->new( + { + authid => 2, + done => 1, + timestamp => $dt, + } + )->store; # Now test two cleanup calls # First call should only remove req2; second call should reset req1 - Koha::Authority::MergeRequests->cron_cleanup({ reset_hours => 3 }); - $req1->discard_changes; # requery + Koha::Authority::MergeRequests->cron_cleanup( { reset_hours => 3 } ); + $req1->discard_changes; # requery is( $req1->done, 2, 'My request was not touched' ); - $req2->discard_changes; # requery + $req2->discard_changes; # requery is( $req2->in_storage, 0, 'Second request removed' ); - Koha::Authority::MergeRequests->cron_cleanup({ reset_hours => 1 }); - $req1->discard_changes; # requery + Koha::Authority::MergeRequests->cron_cleanup( { reset_hours => 1 } ); + $req1->discard_changes; # requery is( $req1->done, 0, 'Yes, we got a reset' ); }; diff --git a/t/db_dependent/Authority/Subfields.t b/t/db_dependent/Authority/Subfields.t index dc5e53a1c3..e760cbb399 100755 --- a/t/db_dependent/Authority/Subfields.t +++ b/t/db_dependent/Authority/Subfields.t @@ -30,18 +30,21 @@ $schema->storage->txn_begin; subtest "Some supertrivial tests for Subfield" => sub { plan tests => 3; - my $authtype = t::lib::TestBuilder->new->build({ - source => 'AuthType' - }); - my $cnt = Koha::Authority::Subfields->count; - my $rec = Koha::Authority::Subfield->new({ - authtypecode => $authtype->{authtypecode}, - tagfield => '100', - tagsubfield => 'a', - })->store; + my $authtype = t::lib::TestBuilder->new->build( { source => 'AuthType' } ); + my $cnt = Koha::Authority::Subfields->count; + my $rec = Koha::Authority::Subfield->new( + { + authtypecode => $authtype->{authtypecode}, + tagfield => '100', + tagsubfield => 'a', + } + )->store; is( Koha::Authority::Subfields->count, $cnt + 1, 'One record added' ); - $rec->update({ liblibrarian => 'intelligent text' }); - is( Koha::Authority::Subfields->find( $authtype->{authtypecode}, '100', 'a' )->liblibrarian, 'intelligent text', 'Found record' ); + $rec->update( { liblibrarian => 'intelligent text' } ); + is( + Koha::Authority::Subfields->find( $authtype->{authtypecode}, '100', 'a' )->liblibrarian, 'intelligent text', + 'Found record' + ); $rec->delete; is( Koha::Authority::Subfields->count, $cnt, 'One record deleted' ); }; diff --git a/t/db_dependent/Authority/Tags.t b/t/db_dependent/Authority/Tags.t index 4111f7ab8a..a30d23e528 100755 --- a/t/db_dependent/Authority/Tags.t +++ b/t/db_dependent/Authority/Tags.t @@ -30,17 +30,20 @@ $schema->storage->txn_begin; subtest "Some supertrivial tests for Tag" => sub { plan tests => 3; - my $authtype = t::lib::TestBuilder->new->build({ - source => 'AuthType' - }); - my $cnt = Koha::Authority::Tags->count; - my $rec = Koha::Authority::Tag->new({ - authtypecode => $authtype->{authtypecode}, - tagfield => '100', - })->store; + my $authtype = t::lib::TestBuilder->new->build( { source => 'AuthType' } ); + my $cnt = Koha::Authority::Tags->count; + my $rec = Koha::Authority::Tag->new( + { + authtypecode => $authtype->{authtypecode}, + tagfield => '100', + } + )->store; is( Koha::Authority::Tags->count, $cnt + 1, 'One record added' ); - $rec->update({ liblibrarian => 'another intelligent idea' }); - is( Koha::Authority::Tags->find( $authtype->{authtypecode}, '100' )->liblibrarian, 'another intelligent idea', 'Found record' ); + $rec->update( { liblibrarian => 'another intelligent idea' } ); + is( + Koha::Authority::Tags->find( $authtype->{authtypecode}, '100' )->liblibrarian, 'another intelligent idea', + 'Found record' + ); $rec->delete; is( Koha::Authority::Tags->count, $cnt, 'One record deleted' ); }; diff --git a/t/db_dependent/Barcodes.t b/t/db_dependent/Barcodes.t index 0232a4a9c9..847b95b9b4 100755 --- a/t/db_dependent/Barcodes.t +++ b/t/db_dependent/Barcodes.t @@ -29,34 +29,32 @@ $| = 1; BEGIN { use FindBin; use lib $FindBin::Bin; - use_ok('C4::Barcodes', qw( value initial max db_max next_value next previous serial autoBarcode is_max )); + use_ok( 'C4::Barcodes', qw( value initial max db_max next_value next previous serial autoBarcode is_max ) ); } my $builder = t::lib::TestBuilder->new; -my $schema = Koha::Database->new->schema; +my $schema = Koha::Database->new->schema; subtest 'Test generation of annual barcodes from DB values' => sub { plan tests => 4; $schema->storage->txn_begin; - $builder->schema->resultset( 'Issue' )->delete_all; - $builder->schema->resultset( 'Item' )->delete_all; + $builder->schema->resultset('Issue')->delete_all; + $builder->schema->resultset('Item')->delete_all; my $barcodeobj; - warning_like { $barcodeobj = C4::Barcodes->new('annual'); } [ qr/No max barcode (.*) found\. Using initial value\./ ], "(annual) Expected complaint regarding no max barcode found"; + warning_like { $barcodeobj = C4::Barcodes->new('annual'); } + [qr/No max barcode (.*) found\. Using initial value\./], + "(annual) Expected complaint regarding no max barcode found"; my $barcodevalue = $barcodeobj->value(); - my $item_1 = $builder->build_sample_item( - { - barcode => $barcodevalue - } - ); + my $item_1 = $builder->build_sample_item( { barcode => $barcodevalue } ); - is($barcodevalue,$barcodeobj->db_max(), "(annual) First barcode saved to db is equal to db_max" ); + is( $barcodevalue, $barcodeobj->db_max(), "(annual) First barcode saved to db is equal to db_max" ); #This is just setting the value ahead an arbitrary amount before adding a second barcode to db $barcodevalue = $barcodeobj->next_value(); @@ -65,16 +63,18 @@ subtest 'Test generation of annual barcodes from DB values' => sub { $barcodevalue = $barcodeobj->next_value($barcodevalue); $barcodevalue = $barcodeobj->next_value($barcodevalue); - my $item_2 = $builder->build_sample_item( - { - barcode => $barcodevalue - } - ); + my $item_2 = $builder->build_sample_item( { barcode => $barcodevalue } ); $barcodeobj = C4::Barcodes->new('annual'); - is($barcodevalue,$barcodeobj->db_max(), '(annual) db_max should equal the greatest barcode in the db when more than 1 present'); - ok($barcodeobj->value() gt $barcodevalue, '(annual) new barcode object should be created with value greater and last value inserted into db'); + is( + $barcodevalue, $barcodeobj->db_max(), + '(annual) db_max should equal the greatest barcode in the db when more than 1 present' + ); + ok( + $barcodeobj->value() gt $barcodevalue, + '(annual) new barcode object should be created with value greater and last value inserted into db' + ); $schema->storage->txn_rollback; }; @@ -84,32 +84,29 @@ subtest 'Test generation of hbyymmincr barcodes from DB values' => sub { plan tests => 5; $schema->storage->txn_begin; - $builder->schema->resultset( 'Issue' )->delete_all; - $builder->schema->resultset( 'Item' )->delete_all; + $builder->schema->resultset('Issue')->delete_all; + $builder->schema->resultset('Item')->delete_all; - my $branchcode_1 = "LETTERS"; #NOTE: This barcode type supports only letters in the branchcode + my $branchcode_1 = "LETTERS"; #NOTE: This barcode type supports only letters in the branchcode my $barcodeobj; warnings_are { $barcodeobj = C4::Barcodes->new('hbyymmincr'); } - [ "HBYYMM Barcode created with no branchcode, default is blank", - "No existing hbyymmincr barcodes found. Reverting to initial value.", - "HBYYMM Barcode was not passed a branch, default is blank"] - , "(hbyymmincr) Expected complaint regarding no max barcode found"; + [ + "HBYYMM Barcode created with no branchcode, default is blank", + "No existing hbyymmincr barcodes found. Reverting to initial value.", + "HBYYMM Barcode was not passed a branch, default is blank" + ], + "(hbyymmincr) Expected complaint regarding no max barcode found"; - - warning_like { $barcodeobj = C4::Barcodes->new('hbyymmincr',$branchcode_1); } - [ qr/No existing hbyymmincr barcodes found\. Reverting to initial value\./], + warning_like { $barcodeobj = C4::Barcodes->new( 'hbyymmincr', $branchcode_1 ); } + [qr/No existing hbyymmincr barcodes found\. Reverting to initial value\./], "(hbyymmincr) Expected complaint regarding no max barcode found"; my $barcodevalue = $barcodeobj->value(); - my $item_1 = $builder->build_sample_item( - { - barcode => $barcodevalue - } - ); + my $item_1 = $builder->build_sample_item( { barcode => $barcodevalue } ); - is($barcodevalue,$barcodeobj->db_max(), "(hbyymmincr) First barcode saved to db is equal to db_max" ); + is( $barcodevalue, $barcodeobj->db_max(), "(hbyymmincr) First barcode saved to db is equal to db_max" ); #This is just setting the value ahead an arbitrary amount before adding a second barcode to db $barcodevalue = $barcodeobj->next_value(); @@ -118,16 +115,18 @@ subtest 'Test generation of hbyymmincr barcodes from DB values' => sub { $barcodevalue = $barcodeobj->next_value($barcodevalue); $barcodevalue = $barcodeobj->next_value($barcodevalue); - my $item_2 = $builder->build_sample_item( - { - barcode => $barcodevalue - } + my $item_2 = $builder->build_sample_item( { barcode => $barcodevalue } ); + + $barcodeobj = C4::Barcodes->new( 'hbyymmincr', $branchcode_1 ); + + is( + $barcodevalue, $barcodeobj->db_max(), + '(hbyymmincr) db_max should equal the greatest barcode in the db when more than 1 present' + ); + ok( + $barcodeobj->value() gt $barcodevalue, + '(hbyymmincr) new barcode object should be created with value greater and last value inserted into db' ); - - $barcodeobj = C4::Barcodes->new('hbyymmincr',$branchcode_1); - - is($barcodevalue,$barcodeobj->db_max(), '(hbyymmincr) db_max should equal the greatest barcode in the db when more than 1 present'); - ok($barcodeobj->value() gt $barcodevalue, '(hbyymmincr) new barcode object should be created with value greater and last value inserted into db'); $schema->storage->txn_rollback; }; @@ -153,102 +152,103 @@ subtest 'Test generation of incremental barcodes from DB values' => sub { $schema->storage->txn_begin; -$builder->schema->resultset( 'Issue' )->delete_all; -$builder->schema->resultset( 'Item' )->delete_all; +$builder->schema->resultset('Issue')->delete_all; +$builder->schema->resultset('Item')->delete_all; my %thash = ( incremental => [], - annual => [], - hbyymmincr => ['MAIN'], - EAN13 => ['0000000695152','892685001928'], + annual => [], + hbyymmincr => ['MAIN'], + EAN13 => [ '0000000695152', '892685001928' ], ); -my ($obj1,$obj2,$format,$value,$initial,$serial,$next,$previous,$temp); +my ( $obj1, $obj2, $format, $value, $initial, $serial, $next, $previous, $temp ); my @formats = sort keys %thash; foreach (@formats) { my $pre = sprintf '(%-12s)', $_; - if ($_ eq 'EAN13') { + if ( $_ eq 'EAN13' ) { warning_like { $obj1 = C4::Barcodes->new($_); } - [ qr/not valid EAN-13 barcode/ ], - "$pre Expected complaint regarding $_ not being a valid EAN-13 barcode"; - } - elsif ($_ eq 'annual') { + [qr/not valid EAN-13 barcode/], + "$pre Expected complaint regarding $_ not being a valid EAN-13 barcode"; + } elsif ( $_ eq 'annual' ) { warning_like { $obj1 = C4::Barcodes->new($_); } - [ qr/No max barcode (.*) found\. Using initial value\./ ], - "$pre Expected complaint regarding no max barcode found"; - } - elsif ($_ eq 'hbyymmincr') { + [qr/No max barcode (.*) found\. Using initial value\./], + "$pre Expected complaint regarding no max barcode found"; + } elsif ( $_ eq 'hbyymmincr' ) { warnings_are { $obj1 = C4::Barcodes->new($_); } - [ "HBYYMM Barcode created with no branchcode, default is blank", - "No existing hbyymmincr barcodes found. Reverting to initial value.", - "HBYYMM Barcode was not passed a branch, default is blank"] - , "$pre Expected complaint regarding no max barcode found"; - } - elsif ($_ eq 'incremental') { + [ + "HBYYMM Barcode created with no branchcode, default is blank", + "No existing hbyymmincr barcodes found. Reverting to initial value.", + "HBYYMM Barcode was not passed a branch, default is blank" + ], + "$pre Expected complaint regarding no max barcode found"; + } elsif ( $_ eq 'incremental' ) { $obj1 = C4::Barcodes->new($_); - } - else { + } else { die "This should not happen! ($_)\n"; } - ok($obj1, "$pre Barcode Creation : new($_)"); - SKIP: { + ok( $obj1, "$pre Barcode Creation : new($_)" ); +SKIP: { skip "No Object Returned by new($_)", 17 unless $obj1; - ok($_ eq ($format = $obj1->autoBarcode()), "$pre autoBarcode() : " . ($format || 'FAILED') ); - if ($_ eq 'hbyymmincr') { - warning_like { $initial= $obj1->initial(); } - [ qr/HBYYMM Barcode was not passed a branch, default is blank/ ] - ,"$pre Expected complaint regarding no branch passed when getting initial\n $pre initial() : " . $initial ; + ok( $_ eq ( $format = $obj1->autoBarcode() ), "$pre autoBarcode() : " . ( $format || 'FAILED' ) ); + if ( $_ eq 'hbyymmincr' ) { + warning_like { $initial = $obj1->initial(); } + [qr/HBYYMM Barcode was not passed a branch, default is blank/], + "$pre Expected complaint regarding no branch passed when getting initial\n $pre initial() : " + . $initial; warnings_are { $temp = $obj1->db_max(); } - [ "No existing hbyymmincr barcodes found. Reverting to initial value.", - "HBYYMM Barcode was not passed a branch, default is blank"] - ,"$pre Expected complaint regarding no hbyymmincr barcodes found"; - } - else { - ok($initial= $obj1->initial(), "$pre initial() : " . ($initial|| 'FAILED') ); + [ + "No existing hbyymmincr barcodes found. Reverting to initial value.", + "HBYYMM Barcode was not passed a branch, default is blank" + ], + "$pre Expected complaint regarding no hbyymmincr barcodes found"; + } else { + ok( $initial = $obj1->initial(), "$pre initial() : " . ( $initial || 'FAILED' ) ); $temp = $obj1->db_max(); } - ok($temp = $obj1->max(), "$pre max() : " . ($temp || 'FAILED') ); - ok($value = $obj1->value(), "$pre value() : " . ($value || 'FAILED') ); - ok($serial = $obj1->serial(), "$pre serial() : " . ($serial || 'FAILED') ); - ok($temp = $obj1->is_max(), "$pre obj1->is_max() [obj1 should currently be max]"); - if ($_ eq 'hbyymmincr') { - warning_like { $obj2 = $obj1->new(); } - [ qr/HBYYMM Barcode created with no branchcode, default is blank/ ] - ,"$pre Expected complaint regarding no branch passed when getting initial\n $pre Barcode Creation : obj2 = obj1->new()" ; + ok( $temp = $obj1->max(), "$pre max() : " . ( $temp || 'FAILED' ) ); + ok( $value = $obj1->value(), "$pre value() : " . ( $value || 'FAILED' ) ); + ok( $serial = $obj1->serial(), "$pre serial() : " . ( $serial || 'FAILED' ) ); + ok( $temp = $obj1->is_max(), "$pre obj1->is_max() [obj1 should currently be max]" ); + if ( $_ eq 'hbyymmincr' ) { + warning_like { $obj2 = $obj1->new(); } + [qr/HBYYMM Barcode created with no branchcode, default is blank/], + "$pre Expected complaint regarding no branch passed when getting initial\n $pre Barcode Creation : obj2 = obj1->new()"; } else { - ok($obj2 = $obj1->new(), "$pre Barcode Creation : obj2 = obj1->new()"); + ok( $obj2 = $obj1->new(), "$pre Barcode Creation : obj2 = obj1->new()" ); } - ok(not($obj1->is_max()), "$pre obj1->is_max() [obj1 should no longer be max]"); - ok( $obj2->is_max(), "$pre obj2->is_max() [obj2 should currently be max]"); - ok($obj2->serial == $obj1->serial + 1, "$pre obj2->serial() : " . ($obj2->serial || 'FAILED')); - ok($previous = $obj2->previous(), "$pre obj2->previous() : " . ($previous || 'FAILED')); - ok($next = $obj1->next(), "$pre obj1->next() : " . ($next || 'FAILED')); - ok($next->previous()->value() eq $obj1->value(), "$pre Roundtrip, value : " . ($obj1->value || 'FAILED')); - ok($previous->next()->value() eq $obj2->value(), "$pre Roundtrip, value : " . ($obj2->value || 'FAILED')); + ok( not( $obj1->is_max() ), "$pre obj1->is_max() [obj1 should no longer be max]" ); + ok( $obj2->is_max(), "$pre obj2->is_max() [obj2 should currently be max]" ); + ok( $obj2->serial == $obj1->serial + 1, "$pre obj2->serial() : " . ( $obj2->serial || 'FAILED' ) ); + ok( $previous = $obj2->previous(), "$pre obj2->previous() : " . ( $previous || 'FAILED' ) ); + ok( $next = $obj1->next(), "$pre obj1->next() : " . ( $next || 'FAILED' ) ); + ok( $next->previous()->value() eq $obj1->value(), "$pre Roundtrip, value : " . ( $obj1->value || 'FAILED' ) ); + ok( $previous->next()->value() eq $obj2->value(), "$pre Roundtrip, value : " . ( $obj2->value || 'FAILED' ) ); } } foreach my $format (@formats) { my $pre = sprintf '(%-12s)', $format; - foreach my $testval (@{$thash{ $format }}) { - if ($format eq 'hbyymmincr') { - warning_like { $obj1 = C4::Barcodes->new($format,$testval); } - [ qr/No existing hbyymmincr barcodes found\. Reverting to initial value\./ ], - "$pre Expected complaint regarding no hbyymmincr barcodes found"; - ok($obj1, "$pre Barcode Creation : new('$format','$testval')"); + foreach my $testval ( @{ $thash{$format} } ) { + if ( $format eq 'hbyymmincr' ) { + warning_like { $obj1 = C4::Barcodes->new( $format, $testval ); } + [qr/No existing hbyymmincr barcodes found\. Reverting to initial value\./], + "$pre Expected complaint regarding no hbyymmincr barcodes found"; + ok( $obj1, "$pre Barcode Creation : new('$format','$testval')" ); $obj2 = $obj1->new(); my $branch; - ok($branch = $obj1->branch(), "$pre branch() : " . ($branch || 'FAILED') ); - ok($branch eq $obj2->branch(), "$pre branch extended to derived object : " . ($obj2->branch || 'FAILED')); - } - elsif ($format eq 'EAN13') { - warning_like { $obj1 = C4::Barcodes->new($format,$testval) } - [ qr/not valid EAN-13 barcode/ ], - "$pre Expected complaint regarding $testval not being a valid EAN-13 barcode"; - ok($obj1, "$pre Barcode Creation : new('$format','$testval')"); - } - else { - ok($obj1 = C4::Barcodes->new($format,$testval), "$pre Barcode Creation : new('$format','$testval')"); + ok( $branch = $obj1->branch(), "$pre branch() : " . ( $branch || 'FAILED' ) ); + ok( + $branch eq $obj2->branch(), + "$pre branch extended to derived object : " . ( $obj2->branch || 'FAILED' ) + ); + } elsif ( $format eq 'EAN13' ) { + warning_like { $obj1 = C4::Barcodes->new( $format, $testval ) } + [qr/not valid EAN-13 barcode/], + "$pre Expected complaint regarding $testval not being a valid EAN-13 barcode"; + ok( $obj1, "$pre Barcode Creation : new('$format','$testval')" ); + } else { + ok( $obj1 = C4::Barcodes->new( $format, $testval ), "$pre Barcode Creation : new('$format','$testval')" ); } } } diff --git a/t/db_dependent/Barcodes_ValueBuilder.t b/t/db_dependent/Barcodes_ValueBuilder.t index 84fcce1983..b4eb059c2c 100755 --- a/t/db_dependent/Barcodes_ValueBuilder.t +++ b/t/db_dependent/Barcodes_ValueBuilder.t @@ -23,10 +23,10 @@ use t::lib::TestBuilder; use Koha::Database; BEGIN { - use_ok('C4::Barcodes::ValueBuilder', qw( get_barcode )); -}; + use_ok( 'C4::Barcodes::ValueBuilder', qw( get_barcode ) ); +} -my $schema = Koha::Database->new->schema; +my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; my $builder = t::lib::TestBuilder->new; @@ -34,55 +34,35 @@ my $builder = t::lib::TestBuilder->new; my $dbh = C4::Context->dbh; $dbh->do(q|DELETE FROM issues|); $dbh->do(q|DELETE FROM items|); -my $item_1 = $builder->build_sample_item( - { - barcode => '33333074344563' - } -); -my $item_2 = $builder->build_sample_item( - { - barcode => 'hb12070890' - } -); -my $item_3 = $builder->build_sample_item( - { - barcode => '201200345' - } -); -my $item_4 = $builder->build_sample_item( - { - barcode => '2012-0034' - } -); +my $item_1 = $builder->build_sample_item( { barcode => '33333074344563' } ); +my $item_2 = $builder->build_sample_item( { barcode => 'hb12070890' } ); +my $item_3 = $builder->build_sample_item( { barcode => '201200345' } ); +my $item_4 = $builder->build_sample_item( { barcode => '2012-0034' } ); my %args = ( - year => '2012', - mon => '07', - day => '30', - tag => '952', - subfield => 'p', + year => '2012', + mon => '07', + day => '30', + tag => '952', + subfield => 'p', ); -my ($nextnum, $scr) = C4::Barcodes::ValueBuilder::incremental::get_barcode(\%args); -is($nextnum, 33333074344564, 'incremental barcode'); -is($scr, undef, 'incremental javascript'); +my ( $nextnum, $scr ) = C4::Barcodes::ValueBuilder::incremental::get_barcode( \%args ); +is( $nextnum, 33333074344564, 'incremental barcode' ); +is( $scr, undef, 'incremental javascript' ); -($nextnum, $scr) = C4::Barcodes::ValueBuilder::hbyymmincr::get_barcode(\%args); -is($nextnum, '12070891', 'hbyymmincr barcode'); -ok(length($scr) > 0, 'hbyymmincr javascript'); +( $nextnum, $scr ) = C4::Barcodes::ValueBuilder::hbyymmincr::get_barcode( \%args ); +is( $nextnum, '12070891', 'hbyymmincr barcode' ); +ok( length($scr) > 0, 'hbyymmincr javascript' ); -($nextnum, $scr) = C4::Barcodes::ValueBuilder::annual::get_barcode(\%args); -is($nextnum, '2012-0035', 'annual barcode'); -is($scr, undef, 'annual javascript'); +( $nextnum, $scr ) = C4::Barcodes::ValueBuilder::annual::get_barcode( \%args ); +is( $nextnum, '2012-0035', 'annual barcode' ); +is( $scr, undef, 'annual javascript' ); $dbh->do(q|DELETE FROM items|); -my $item_5 = $builder->build_sample_item( - { - barcode => '978e0143019375' - } -); -($nextnum, $scr) = C4::Barcodes::ValueBuilder::incremental::get_barcode(\%args); -is($nextnum, '979', 'incremental barcode'); -is($scr, undef, 'incremental javascript'); +my $item_5 = $builder->build_sample_item( { barcode => '978e0143019375' } ); +( $nextnum, $scr ) = C4::Barcodes::ValueBuilder::incremental::get_barcode( \%args ); +is( $nextnum, '979', 'incremental barcode' ); +is( $scr, undef, 'incremental javascript' ); $schema->storage->txn_rollback; diff --git a/t/db_dependent/Biblio.t b/t/db_dependent/Biblio.t index d208d20f62..79109d708a 100755 --- a/t/db_dependent/Biblio.t +++ b/t/db_dependent/Biblio.t @@ -35,13 +35,16 @@ use Koha::MarcSubfieldStructures; use C4::Linker::Default qw( get_link ); BEGIN { - use_ok('C4::Biblio', qw( AddBiblio GetMarcFromKohaField BiblioAutoLink GetMarcSubfieldStructure GetMarcSubfieldStructureFromKohaField LinkBibHeadingsToAuthorities GetBiblioData ModBiblio GetMarcISSN GetMarcISBN GetMarcPrice GetFrameworkCode GetMarcUrls IsMarcStructureInternal GetMarcStructure GetXmlBiblio DelBiblio )); + use_ok( + 'C4::Biblio', + qw( AddBiblio GetMarcFromKohaField BiblioAutoLink GetMarcSubfieldStructure GetMarcSubfieldStructureFromKohaField LinkBibHeadingsToAuthorities GetBiblioData ModBiblio GetMarcISSN GetMarcISBN GetMarcPrice GetFrameworkCode GetMarcUrls IsMarcStructureInternal GetMarcStructure GetXmlBiblio DelBiblio ) + ); } my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; my $dbh = C4::Context->dbh; -Koha::Caches->get_instance->clear_from_cache( "MarcSubfieldStructure-" ); +Koha::Caches->get_instance->clear_from_cache("MarcSubfieldStructure-"); my $builder = t::lib::TestBuilder->new; @@ -52,53 +55,69 @@ subtest 'AddBiblio' => sub { t::lib::Mocks::mock_preference( 'marcflavour', $marcflavour ); my ( $f, $sf ) = GetMarcFromKohaField('biblioitems.cn_item'); - my $cn_item_field = MARC::Field->new( $f, ' ', ' ', - $sf => 'Thisisgoingtobetoomanycharactersforthe.cn_item.field' ); + my $cn_item_field = MARC::Field->new( + $f, ' ', ' ', + $sf => 'Thisisgoingtobetoomanycharactersforthe.cn_item.field' + ); my $record = MARC::Record->new(); $record->append_fields($cn_item_field); my $nb_biblios = Koha::Biblios->count; my ( $biblionumber, $biblioitemnumber ); warnings_like { ( $biblionumber, $biblioitemnumber ) = C4::Biblio::AddBiblio( $record, '' ) } - [ qr/Data too long for column 'cn_item'/, qr/Data too long for column 'cn_item'/ ], + [ qr/Data too long for column 'cn_item'/, qr/Data too long for column 'cn_item'/ ], "expected warnings when adding too long cn_item"; - is( $biblionumber, undef, - 'AddBiblio returns undef for biblionumber if something went wrong' ); - is( $biblioitemnumber, undef, + is( + $biblionumber, undef, + 'AddBiblio returns undef for biblionumber if something went wrong' + ); + is( + $biblioitemnumber, undef, 'AddBiblio returns undef for biblioitemnumber if something went wrong' ); - is( Koha::Biblios->count, $nb_biblios, - 'No biblio should have been added if something went wrong' ); + is( + Koha::Biblios->count, $nb_biblios, + 'No biblio should have been added if something went wrong' + ); ( $f, $sf ) = GetMarcFromKohaField('biblioitems.lccn'); - my $lccn_field = MARC::Field->new( $f, ' ', ' ', - $sf => 'ThisisNOTgoingtobetoomanycharactersfortheLCCNfield' ); + my $lccn_field = MARC::Field->new( + $f, ' ', ' ', + $sf => 'ThisisNOTgoingtobetoomanycharactersfortheLCCNfield' + ); $record = MARC::Record->new(); $record->append_fields($lccn_field); warnings_like { ( $biblionumber, $biblioitemnumber ) = C4::Biblio::AddBiblio( $record, '' ) } - [], + [], "No warning expected when adding a long LCCN"; - isnt( $biblionumber, undef, - 'AddBiblio returns the biblionumber' ); - isnt( $biblioitemnumber, undef, + isnt( + $biblionumber, undef, + 'AddBiblio returns the biblionumber' + ); + isnt( + $biblioitemnumber, undef, 'AddBiblio returns the biblioitemnumber' ); - is( Koha::Biblios->count, $nb_biblios + 1, - 'The biblio should have been added if nothing went wrong' ); + is( + Koha::Biblios->count, $nb_biblios + 1, + 'The biblio should have been added if nothing went wrong' + ); - t::lib::Mocks::mock_preference( 'AutoLinkBiblios', $marcflavour ); + t::lib::Mocks::mock_preference( 'AutoLinkBiblios', $marcflavour ); t::lib::Mocks::mock_preference( 'AutoCreateAuthorities', $marcflavour ); - t::lib::Mocks::mock_preference( 'autoControlNumber', "OFF" ); + t::lib::Mocks::mock_preference( 'autoControlNumber', "OFF" ); my $mock_biblio = Test::MockModule->new("C4::Biblio"); - $mock_biblio->mock( BiblioAutoLink => sub { - my $record = shift; - my $frameworkcode = shift; - warn "My biblionumber is ".$record->subfield('999','c')." and my frameworkcode is $frameworkcode"; - }); + $mock_biblio->mock( + BiblioAutoLink => sub { + my $record = shift; + my $frameworkcode = shift; + warn "My biblionumber is " . $record->subfield( '999', 'c' ) . " and my frameworkcode is $frameworkcode"; + } + ); warning_like { $builder->build_sample_biblio(); } - qr/My biblionumber is \d+ and my frameworkcode is /, "The biblionumber is correctly passed to BiblioAutoLink"; + qr/My biblionumber is \d+ and my frameworkcode is /, "The biblionumber is correctly passed to BiblioAutoLink"; $mock_biblio->unmock('BiblioAutoLink'); subtest 'record_source_id param tests' => sub { @@ -126,9 +145,10 @@ subtest 'GetMarcSubfieldStructureFromKohaField' => sub { plan tests => 27; # Add second mapping for copyrightdate - Koha::MarcSubfieldStructures->search({ frameworkcode => '', tagfield => '264', tagsubfield => 'c' })->delete; - Koha::MarcSubfieldStructure->new({ frameworkcode => '', tagfield => '264', tagsubfield => 'c', kohafield => "biblio.copyrightdate" })->store; - Koha::Caches->get_instance->clear_from_cache( "MarcSubfieldStructure-" ); + Koha::MarcSubfieldStructures->search( { frameworkcode => '', tagfield => '264', tagsubfield => 'c' } )->delete; + Koha::MarcSubfieldStructure->new( + { frameworkcode => '', tagfield => '264', tagsubfield => 'c', kohafield => "biblio.copyrightdate" } )->store; + Koha::Caches->get_instance->clear_from_cache("MarcSubfieldStructure-"); my @columns = qw( tagfield tagsubfield liblibrarian libopac repeatable mandatory kohafield tab @@ -140,7 +160,7 @@ subtest 'GetMarcSubfieldStructureFromKohaField' => sub { my $marc_subfield_structure = GetMarcSubfieldStructureFromKohaField('biblio.biblionumber'); is( ref $marc_subfield_structure, "ARRAY", "Result is an arrayref" ); - is( @$marc_subfield_structure, 1, 'Expecting one hit only' ); + is( @$marc_subfield_structure, 1, 'Expecting one hit only' ); foreach my $col (@columns) { ok( exists $marc_subfield_structure->[0]->{$col}, "Hashref contains key '$col'" ); } @@ -152,7 +172,7 @@ subtest 'GetMarcSubfieldStructureFromKohaField' => sub { is( ref $marc_subfield_structure, "ARRAY", "Result is again an arrayref" ); is( @$marc_subfield_structure, 2, 'We expect two hits' ); ok( exists $marc_subfield_structure->[0]->{tagsubfield}, 'Testing a random column for existence in 1st hash' ); - ok( exists $marc_subfield_structure->[1]->{hidden}, 'Testing a random column for existence in 2nd hash' ); + ok( exists $marc_subfield_structure->[1]->{hidden}, 'Testing a random column for existence in 2nd hash' ); # foo.bar does not exist so this should return [] $marc_subfield_structure = GetMarcSubfieldStructureFromKohaField('foo.bar'); @@ -164,22 +184,35 @@ subtest "GetMarcSubfieldStructure" => sub { plan tests => 5; # Add multiple Koha to Marc mappings - Koha::MarcSubfieldStructures->search({ frameworkcode => '', tagfield => '399', tagsubfield => [ 'a', 'b' ] })->delete; - Koha::MarcSubfieldStructure->new({ frameworkcode => '', tagfield => '399', tagsubfield => 'a', kohafield => "mytable.nicepages" })->store; - Koha::MarcSubfieldStructure->new({ frameworkcode => '', tagfield => '399', tagsubfield => 'b', kohafield => "mytable.nicepages" })->store; - Koha::Caches->get_instance->clear_from_cache( "MarcSubfieldStructure-" ); + Koha::MarcSubfieldStructures->search( { frameworkcode => '', tagfield => '399', tagsubfield => [ 'a', 'b' ] } ) + ->delete; + Koha::MarcSubfieldStructure->new( + { frameworkcode => '', tagfield => '399', tagsubfield => 'a', kohafield => "mytable.nicepages" } )->store; + Koha::MarcSubfieldStructure->new( + { frameworkcode => '', tagfield => '399', tagsubfield => 'b', kohafield => "mytable.nicepages" } )->store; + Koha::Caches->get_instance->clear_from_cache("MarcSubfieldStructure-"); my $structure = C4::Biblio::GetMarcSubfieldStructure(''); - is( @{ $structure->{"mytable.nicepages"} }, 2, - 'GetMarcSubfieldStructure should return two entries for nicepages' ); - is( $structure->{"mytable.nicepages"}->[0]->{tagfield}, '399', - 'Check tagfield for first entry' ); - is( $structure->{"mytable.nicepages"}->[0]->{tagsubfield}, 'a', - 'Check tagsubfield for first entry' ); - is( $structure->{"mytable.nicepages"}->[1]->{tagfield}, '399', - 'Check tagfield for second entry' ); - is( $structure->{"mytable.nicepages"}->[1]->{tagsubfield}, 'b', - 'Check tagsubfield for second entry' ); + is( + @{ $structure->{"mytable.nicepages"} }, 2, + 'GetMarcSubfieldStructure should return two entries for nicepages' + ); + is( + $structure->{"mytable.nicepages"}->[0]->{tagfield}, '399', + 'Check tagfield for first entry' + ); + is( + $structure->{"mytable.nicepages"}->[0]->{tagsubfield}, 'a', + 'Check tagsubfield for first entry' + ); + is( + $structure->{"mytable.nicepages"}->[1]->{tagfield}, '399', + 'Check tagfield for second entry' + ); + is( + $structure->{"mytable.nicepages"}->[1]->{tagsubfield}, 'b', + 'Check tagsubfield for second entry' + ); }; subtest "GetMarcFromKohaField" => sub { @@ -190,49 +223,54 @@ subtest "GetMarcFromKohaField" => sub { # Check call in list context for multiple mappings my @retval = C4::Biblio::GetMarcFromKohaField('mytable.nicepages'); - is( @retval, 4, 'Should return two tags and subfields' ); + is( @retval, 4, 'Should return two tags and subfields' ); is( $retval[0], '399', 'Check first tag' ); - is( $retval[1], 'a', 'Check first subfield' ); + is( $retval[1], 'a', 'Check first subfield' ); is( $retval[2], '399', 'Check second tag' ); - is( $retval[3], 'b', 'Check second subfield' ); + is( $retval[3], 'b', 'Check second subfield' ); # Check same call in scalar context - is( C4::Biblio::GetMarcFromKohaField('mytable.nicepages'), 4, - 'GetMarcFromKohaField returns list count in scalar context' ); + is( + C4::Biblio::GetMarcFromKohaField('mytable.nicepages'), 4, + 'GetMarcFromKohaField returns list count in scalar context' + ); # Check for warning about obsoleted framework parameter - warning_like - { @retval = C4::Biblio::GetMarcFromKohaField( 'mytable.nicepages', 1 ) } - qr/obsoleted for long/, + warning_like { @retval = C4::Biblio::GetMarcFromKohaField( 'mytable.nicepages', 1 ) } + qr/obsoleted for long/, 'Found warning about obsoleted parameter'; }; subtest "Authority creation with default linker" => sub { plan tests => 4; + # Automatic authority creation - t::lib::Mocks::mock_preference('LinkerModule', 'Default'); - t::lib::Mocks::mock_preference('AutoLinkBiblios', 1); - t::lib::Mocks::mock_preference('AutoCreateAuthorities', 1); - t::lib::Mocks::mock_preference('marcflavour', 'MARC21'); - my $linker = C4::Linker::Default->new({}); - my $authorities_mod = Test::MockModule->new( 'C4::Heading' ); + t::lib::Mocks::mock_preference( 'LinkerModule', 'Default' ); + t::lib::Mocks::mock_preference( 'AutoLinkBiblios', 1 ); + t::lib::Mocks::mock_preference( 'AutoCreateAuthorities', 1 ); + t::lib::Mocks::mock_preference( 'marcflavour', 'MARC21' ); + my $linker = C4::Linker::Default->new( {} ); + my $authorities_mod = Test::MockModule->new('C4::Heading'); $authorities_mod->mock( 'authorities', sub { - my $results = [{ authid => 'original' },{ authid => 'duplicate' }]; + my $results = [ { authid => 'original' }, { authid => 'duplicate' } ]; return $results; } ); my $marc_record = MARC::Record->new(); - my $field = MARC::Field->new(655, ' ', ' ','a' => 'Magical realism'); - $marc_record->append_fields( $field ); - my ($num_changed,$results) = LinkBibHeadingsToAuthorities($linker, $marc_record, "",undef); - is( $num_changed, 0, "We shouldn't link or create a new record"); - ok( !defined $results->{added}, "If we have multiple matches, we shouldn't create a new record"); + my $field = MARC::Field->new( 655, ' ', ' ', 'a' => 'Magical realism' ); + $marc_record->append_fields($field); + my ( $num_changed, $results ) = LinkBibHeadingsToAuthorities( $linker, $marc_record, "", undef ); + is( $num_changed, 0, "We shouldn't link or create a new record" ); + ok( !defined $results->{added}, "If we have multiple matches, we shouldn't create a new record" ); - ($num_changed,$results) = LinkBibHeadingsToAuthorities($linker, $marc_record, "",undef); - is( $num_changed, 0, "We shouldn't link or create a new record using cached result"); - ok( !defined $results->{added}, "If we have multiple matches, we shouldn't create a new record on second instance"); + ( $num_changed, $results ) = LinkBibHeadingsToAuthorities( $linker, $marc_record, "", undef ); + is( $num_changed, 0, "We shouldn't link or create a new record using cached result" ); + ok( + !defined $results->{added}, + "If we have multiple matches, we shouldn't create a new record on second instance" + ); }; subtest "Test caching of authority types in LinkBibHeadingsToAuthorities" => sub { @@ -280,8 +318,6 @@ subtest "Test caching of authority types in LinkBibHeadingsToAuthorities" => sub }; - - # Mocking variables my $biblio_module = Test::MockModule->new('C4::Biblio'); $biblio_module->mock( @@ -289,30 +325,31 @@ $biblio_module->mock( sub { my ($self) = shift; - my ( $title_field, $title_subfield ) = get_title_field(); - my ( $subtitle_field, $subtitle_subfield ) = get_subtitle_field(); - my ( $medium_field, $medium_subfield ) = get_medium_field(); - my ( $part_number_field, $part_number_subfield ) = get_part_number_field(); - my ( $part_name_field, $part_name_subfield ) = get_part_name_field(); - my ( $isbn_field, $isbn_subfield ) = get_isbn_field(); - my ( $issn_field, $issn_subfield ) = get_issn_field(); - my ( $biblionumber_field, $biblionumber_subfield ) = ( '999', 'c' ); + my ( $title_field, $title_subfield ) = get_title_field(); + my ( $subtitle_field, $subtitle_subfield ) = get_subtitle_field(); + my ( $medium_field, $medium_subfield ) = get_medium_field(); + my ( $part_number_field, $part_number_subfield ) = get_part_number_field(); + my ( $part_name_field, $part_name_subfield ) = get_part_name_field(); + my ( $isbn_field, $isbn_subfield ) = get_isbn_field(); + my ( $issn_field, $issn_subfield ) = get_issn_field(); + my ( $biblionumber_field, $biblionumber_subfield ) = ( '999', 'c' ); my ( $biblioitemnumber_field, $biblioitemnumber_subfield ) = ( '999', '9' ); - my ( $itemnumber_field, $itemnumber_subfield ) = get_itemnumber_field(); + my ( $itemnumber_field, $itemnumber_subfield ) = get_itemnumber_field(); return { - 'biblio.title' => [ { tagfield => $title_field, tagsubfield => $title_subfield } ], - 'biblio.subtitle' => [ { tagfield => $subtitle_field, tagsubfield => $subtitle_subfield } ], - 'biblio.medium' => [ { tagfield => $medium_field, tagsubfield => $medium_subfield } ], - 'biblio.part_number' => [ { tagfield => $part_number_field, tagsubfield => $part_number_subfield } ], - 'biblio.part_name' => [ { tagfield => $part_name_field, tagsubfield => $part_name_subfield } ], - 'biblio.biblionumber' => [ { tagfield => $biblionumber_field, tagsubfield => $biblionumber_subfield } ], - 'biblioitems.isbn' => [ { tagfield => $isbn_field, tagsubfield => $isbn_subfield } ], - 'biblioitems.issn' => [ { tagfield => $issn_field, tagsubfield => $issn_subfield } ], - 'biblioitems.biblioitemnumber' => [ { tagfield => $biblioitemnumber_field, tagsubfield => $biblioitemnumber_subfield } ], - 'items.itemnumber' => [ { tagfield => $itemnumber_subfield, tagsubfield => $itemnumber_subfield } ], + 'biblio.title' => [ { tagfield => $title_field, tagsubfield => $title_subfield } ], + 'biblio.subtitle' => [ { tagfield => $subtitle_field, tagsubfield => $subtitle_subfield } ], + 'biblio.medium' => [ { tagfield => $medium_field, tagsubfield => $medium_subfield } ], + 'biblio.part_number' => [ { tagfield => $part_number_field, tagsubfield => $part_number_subfield } ], + 'biblio.part_name' => [ { tagfield => $part_name_field, tagsubfield => $part_name_subfield } ], + 'biblio.biblionumber' => [ { tagfield => $biblionumber_field, tagsubfield => $biblionumber_subfield } ], + 'biblioitems.isbn' => [ { tagfield => $isbn_field, tagsubfield => $isbn_subfield } ], + 'biblioitems.issn' => [ { tagfield => $issn_field, tagsubfield => $issn_subfield } ], + 'biblioitems.biblioitemnumber' => + [ { tagfield => $biblioitemnumber_field, tagsubfield => $biblioitemnumber_subfield } ], + 'items.itemnumber' => [ { tagfield => $itemnumber_subfield, tagsubfield => $itemnumber_subfield } ], }; - } + } ); my $currency = Test::MockModule->new('Koha::Acquisition::Currencies'); @@ -320,7 +357,8 @@ $currency->mock( 'get_active', sub { return Koha::Acquisition::Currency->new( - { symbol => '$', + { + symbol => '$', isocode => 'USD', currency => 'USD', active => 1, @@ -333,33 +371,38 @@ sub run_tests { Koha::Cache::Memory::Lite->flush(); #Clear cache like we have a new request my $marcflavour = shift; - t::lib::Mocks::mock_preference('marcflavour', $marcflavour); + t::lib::Mocks::mock_preference( 'marcflavour', $marcflavour ); + # Authority tests don't interact well with Elasticsearch at the moment due to the fact that there's currently no way to # roll back ES index changes. - t::lib::Mocks::mock_preference('SearchEngine', 'Zebra'); - t::lib::Mocks::mock_preference('autoControlNumber', 'OFF'); + t::lib::Mocks::mock_preference( 'SearchEngine', 'Zebra' ); + t::lib::Mocks::mock_preference( 'autoControlNumber', 'OFF' ); t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 0 ); - my $isbn = '0590353403'; - my $title = 'Foundation'; - my $subtitle1 = 'Research'; - my $subtitle2 = 'Conclusions'; - my $medium = 'Medium'; + my $isbn = '0590353403'; + my $title = 'Foundation'; + my $subtitle1 = 'Research'; + my $subtitle2 = 'Conclusions'; + my $medium = 'Medium'; my $part_number = '123'; - my $part_name = 'First years'; + my $part_name = 'First years'; # Generate a record with just the ISBN my $marc_record = MARC::Record->new; $marc_record->append_fields( create_isbn_field( $isbn, $marcflavour ) ); # Add the record to the DB - my( $biblionumber, $biblioitemnumber ) = AddBiblio( $marc_record, '' ); - my $data = GetBiblioData( $biblionumber ); - is( $data->{ isbn }, $isbn, - '(GetBiblioData) ISBN correctly retireved.'); - is( $data->{ title }, undef, - '(GetBiblioData) Title field is empty in fresh biblio.'); + my ( $biblionumber, $biblioitemnumber ) = AddBiblio( $marc_record, '' ); + my $data = GetBiblioData($biblionumber); + is( + $data->{isbn}, $isbn, + '(GetBiblioData) ISBN correctly retireved.' + ); + is( + $data->{title}, undef, + '(GetBiblioData) Title field is empty in fresh biblio.' + ); my $biblio = Koha::Biblios->find($biblionumber); @@ -369,90 +412,110 @@ sub run_tests { # Add title my $field = create_title_field( $title, $marcflavour ); - $marc_record->append_fields( $field ); - ModBiblio( $marc_record, $biblionumber ,'' ); - $data = GetBiblioData( $biblionumber ); - is( $data->{ title }, $title, - 'ModBiblio correctly added the title field, and GetBiblioData.'); - is( $data->{ isbn }, $isbn, '(ModBiblio) ISBN is still there after ModBiblio.'); + $marc_record->append_fields($field); + ModBiblio( $marc_record, $biblionumber, '' ); + $data = GetBiblioData($biblionumber); + is( + $data->{title}, $title, + 'ModBiblio correctly added the title field, and GetBiblioData.' + ); + is( $data->{isbn}, $isbn, '(ModBiblio) ISBN is still there after ModBiblio.' ); $marc = $biblio->get_from_storage->metadata->record; my ( $title_field, $title_subfield ) = get_title_field(); is( $marc->subfield( $title_field, $title_subfield ), $title, ); # Add other fields - $marc_record->append_fields( create_field( $subtitle1, $marcflavour, get_subtitle_field() ) ); - $marc_record->append_fields( create_field( $subtitle2, $marcflavour, get_subtitle_field() ) ); - $marc_record->append_fields( create_field( $medium, $marcflavour, get_medium_field() ) ); + $marc_record->append_fields( create_field( $subtitle1, $marcflavour, get_subtitle_field() ) ); + $marc_record->append_fields( create_field( $subtitle2, $marcflavour, get_subtitle_field() ) ); + $marc_record->append_fields( create_field( $medium, $marcflavour, get_medium_field() ) ); $marc_record->append_fields( create_field( $part_number, $marcflavour, get_part_number_field() ) ); - $marc_record->append_fields( create_field( $part_name, $marcflavour, get_part_name_field() ) ); + $marc_record->append_fields( create_field( $part_name, $marcflavour, get_part_name_field() ) ); - ModBiblio( $marc_record, $biblionumber ,'' ); - $data = GetBiblioData( $biblionumber ); - is( $data->{ title }, $title, '(ModBiblio) still there after adding other fields.' ); - is( $data->{ isbn }, $isbn, '(ModBiblio) ISBN is still there after adding other fields.' ); + ModBiblio( $marc_record, $biblionumber, '' ); + $data = GetBiblioData($biblionumber); + is( $data->{title}, $title, '(ModBiblio) still there after adding other fields.' ); + is( $data->{isbn}, $isbn, '(ModBiblio) ISBN is still there after adding other fields.' ); - is( $data->{ subtitle }, "$subtitle1 | $subtitle2", '(ModBiblio) subtitles correctly added and returned in GetBiblioData.' ); - is( $data->{ medium }, $medium, '(ModBiblio) medium correctly added and returned in GetBiblioData.' ); - is( $data->{ part_number }, $part_number, '(ModBiblio) part_number correctly added and returned in GetBiblioData.' ); - is( $data->{ part_name }, $part_name, '(ModBiblio) part_name correctly added and returned in GetBiblioData.' ); + is( + $data->{subtitle}, "$subtitle1 | $subtitle2", + '(ModBiblio) subtitles correctly added and returned in GetBiblioData.' + ); + is( $data->{medium}, $medium, '(ModBiblio) medium correctly added and returned in GetBiblioData.' ); + is( $data->{part_number}, $part_number, '(ModBiblio) part_number correctly added and returned in GetBiblioData.' ); + is( $data->{part_name}, $part_name, '(ModBiblio) part_name correctly added and returned in GetBiblioData.' ); - my $biblioitem = Koha::Biblioitems->find( $biblioitemnumber ); - is( $biblioitem->_result->biblio->title, $title, # Should be $biblioitem->biblio instead, but not needed elsewhere for now - 'Do not know if this makes sense - compare result of previous two GetBiblioData tests.'); - is( $biblioitem->isbn, $isbn, - 'Second test checking it returns the correct isbn.'); + my $biblioitem = Koha::Biblioitems->find($biblioitemnumber); + is( + $biblioitem->_result->biblio->title, + $title, # Should be $biblioitem->biblio instead, but not needed elsewhere for now + 'Do not know if this makes sense - compare result of previous two GetBiblioData tests.' + ); + is( + $biblioitem->isbn, $isbn, + 'Second test checking it returns the correct isbn.' + ); my $success = 0; $field = MARC::Field->new( - 655, ' ', ' ', - 'a' => 'Auction catalogs', - '9' => '1' - ); + 655, ' ', ' ', + 'a' => 'Auction catalogs', + '9' => '1' + ); eval { $marc_record->append_fields($field); - $success = ModBiblio($marc_record,$biblionumber,''); + $success = ModBiblio( $marc_record, $biblionumber, '' ); } or do { diag($@); $success = 0; }; - ok($success, "ModBiblio handles authority-linked 655"); + ok( $success, "ModBiblio handles authority-linked 655" ); eval { $field->delete_subfields('a'); $marc_record->append_fields($field); - $success = ModBiblio($marc_record,$biblionumber,''); + $success = ModBiblio( $marc_record, $biblionumber, '' ); } or do { diag($@); $success = 0; }; - ok($success, "ModBiblio handles 655 with authority link but no heading"); + ok( $success, "ModBiblio handles 655 with authority link but no heading" ); eval { $field->delete_subfields('9'); $marc_record->append_fields($field); - $success = ModBiblio($marc_record,$biblionumber,''); + $success = ModBiblio( $marc_record, $biblionumber, '' ); } or do { diag($@); $success = 0; }; - ok($success, "ModBiblio handles 655 with no subfields"); + ok( $success, "ModBiblio handles 655 with no subfields" ); ## Testing GetMarcISSN my $issns; $issns = GetMarcISSN( $marc_record, $marcflavour ); - is( $issns->[0], undef, - 'GetMarcISSN handles records without the ISSN field (list is empty)' ); - is( scalar @$issns, 0, - 'GetMarcISSN handles records without the ISSN field (count is 0)' ); + is( + $issns->[0], undef, + 'GetMarcISSN handles records without the ISSN field (list is empty)' + ); + is( + scalar @$issns, 0, + 'GetMarcISSN handles records without the ISSN field (count is 0)' + ); + # Add an ISSN field my $issn = '1234-1234'; $field = create_issn_field( $issn, $marcflavour ); $marc_record->append_fields($field); $issns = GetMarcISSN( $marc_record, $marcflavour ); - is( $issns->[0], $issn, - 'GetMarcISSN handles records with a single ISSN field (first element is correct)' ); - is( scalar @$issns, 1, - 'GetMARCISSN handles records with a single ISSN field (count is 1)'); + is( + $issns->[0], $issn, + 'GetMarcISSN handles records with a single ISSN field (first element is correct)' + ); + is( + scalar @$issns, 1, + 'GetMARCISSN handles records with a single ISSN field (count is 1)' + ); + # Add multiple ISSN field my @more_issns = qw/1111-1111 2222-2222 3333-3333/; foreach (@more_issns) { @@ -460,26 +523,31 @@ sub run_tests { $marc_record->append_fields($field); } $issns = GetMarcISSN( $marc_record, $marcflavour ); - is( scalar @$issns, 4, - 'GetMARCISSN handles records with multiple ISSN fields (count correct)'); + is( + scalar @$issns, 4, + 'GetMARCISSN handles records with multiple ISSN fields (count correct)' + ); + # Create an empty ISSN $field = create_issn_field( "", $marcflavour ); $marc_record->append_fields($field); $issns = GetMarcISSN( $marc_record, $marcflavour ); - is( scalar @$issns, 4, - 'GetMARCISSN skips empty ISSN fields (Bug 12674)'); + is( + scalar @$issns, 4, + 'GetMARCISSN skips empty ISSN fields (Bug 12674)' + ); ## Testing GetMarcISBN my $record_for_isbn = MARC::Record->new(); - my $isbns = GetMarcISBN( $record_for_isbn, $marcflavour ); - is( scalar @$isbns, 0, '(GetMarcISBN) The record contains no ISBN'); + my $isbns = GetMarcISBN( $record_for_isbn, $marcflavour ); + is( scalar @$isbns, 0, '(GetMarcISBN) The record contains no ISBN' ); # We add one ISBN $isbn_field = create_isbn_field( $isbn, $marcflavour ); - $record_for_isbn->append_fields( $isbn_field ); + $record_for_isbn->append_fields($isbn_field); $isbns = GetMarcISBN( $record_for_isbn, $marcflavour ); - is( scalar @$isbns, 1, '(GetMarcISBN) The record contains one ISBN'); - is( $isbns->[0], $isbn, '(GetMarcISBN) The record contains our ISBN'); + is( scalar @$isbns, 1, '(GetMarcISBN) The record contains one ISBN' ); + is( $isbns->[0], $isbn, '(GetMarcISBN) The record contains our ISBN' ); # We add 3 more ISBNs $record_for_isbn = MARC::Record->new(); @@ -489,17 +557,21 @@ sub run_tests { $record_for_isbn->append_fields($field); } $isbns = GetMarcISBN( $record_for_isbn, $marcflavour ); - is( scalar @$isbns, 4, '(GetMarcISBN) The record contains 4 ISBNs'); - for my $i (0 .. $#more_isbns) { - is( $isbns->[$i], $more_isbns[$i], - "(GetMarcISBN) Correctly retrieves ISBN #". ($i + 1)); + is( scalar @$isbns, 4, '(GetMarcISBN) The record contains 4 ISBNs' ); + for my $i ( 0 .. $#more_isbns ) { + is( + $isbns->[$i], $more_isbns[$i], + "(GetMarcISBN) Correctly retrieves ISBN #" . ( $i + 1 ) + ); } - is( GetMarcPrice( $record_for_isbn, $marcflavour ), 100, - "GetMarcPrice returns the correct value"); + is( + GetMarcPrice( $record_for_isbn, $marcflavour ), 100, + "GetMarcPrice returns the correct value" + ); my $frameworkcode = GetFrameworkCode($biblionumber); my $updatedrecord = $biblio->metadata->record; - my ( $biblioitem_tag, $biblioitem_subfield ) = GetMarcFromKohaField( "biblioitems.biblioitemnumber" ); + my ( $biblioitem_tag, $biblioitem_subfield ) = GetMarcFromKohaField("biblioitems.biblioitemnumber"); die qq{No biblioitemnumber tag for framework "$frameworkcode"} unless $biblioitem_tag; my $biblioitemnumbertotest; if ( $biblioitem_tag < 10 ) { @@ -516,13 +588,15 @@ sub run_tests { my $marcurl = GetMarcUrls( $marc_record, $marcflavour ); is( @$marcurl, 2, 'GetMarcUrls returns two URLs' ); like( $marcurl->[0]->{MARCURL}, qr/^https/, 'GetMarcUrls did not stumble over a preceding space' ); - ok( $marcflavour ne 'MARC21' || $marcurl->[1]->{MARCURL} =~ /^http:\/\//, - "GetMarcUrls prefixed a $marcflavour URL with http://" ); + ok( + $marcflavour ne 'MARC21' || $marcurl->[1]->{MARCURL} =~ /^http:\/\//, + "GetMarcUrls prefixed a $marcflavour URL with http://" + ); # Automatic authority creation - t::lib::Mocks::mock_preference('AutoLinkBiblios', 1); - t::lib::Mocks::mock_preference('AutoCreateAuthorities', 1); - my $authorities_mod = Test::MockModule->new( 'C4::Heading' ); + t::lib::Mocks::mock_preference( 'AutoLinkBiblios', 1 ); + t::lib::Mocks::mock_preference( 'AutoCreateAuthorities', 1 ); + my $authorities_mod = Test::MockModule->new('C4::Heading'); $authorities_mod->mock( 'authorities', sub { @@ -531,41 +605,40 @@ sub run_tests { } ); $success = 0; - $field = create_author_field('Author Name'); + $field = create_author_field('Author Name'); eval { $marc_record->append_fields($field); - $success = ModBiblio($marc_record,$biblionumber,''); + $success = ModBiblio( $marc_record, $biblionumber, '' ); } or do { diag($@); $success = 0; }; - ok($success, "ModBiblio handles authority addition for author"); + ok( $success, "ModBiblio handles authority addition for author" ); - my ($author_field, $author_subfield, $author_relator_subfield) = get_author_field(); + my ( $author_field, $author_subfield, $author_relator_subfield ) = get_author_field(); $field = $marc_record->field($author_field); - ok($field->subfield($author_subfield), "ModBiblio keeps $author_field$author_subfield intact"); + ok( $field->subfield($author_subfield), "ModBiblio keeps $author_field$author_subfield intact" ); my $authid = $field->subfield('9'); - ok($authid, 'ModBiblio adds authority id'); + ok( $authid, 'ModBiblio adds authority id' ); - use_ok('C4::AuthoritiesMarc', qw( GetAuthority )); + use_ok( 'C4::AuthoritiesMarc', qw( GetAuthority ) ); my $auth_record = C4::AuthoritiesMarc::GetAuthority($authid); - ok($auth_record, 'Authority record successfully retrieved'); + ok( $auth_record, 'Authority record successfully retrieved' ); - - my ($auth_author_field, $auth_author_subfield) = get_auth_author_field(); + my ( $auth_author_field, $auth_author_subfield ) = get_auth_author_field(); $field = $auth_record->field($auth_author_field); - ok($field, "Authority record contains field $auth_author_field"); + ok( $field, "Authority record contains field $auth_author_field" ); is( $field->subfield($auth_author_subfield), 'Author Name', 'Authority $auth_author_field$auth_author_subfield contains author name' ); - is($field->subfield($author_relator_subfield), undef, 'Authority does not contain relator subfield'); + is( $field->subfield($author_relator_subfield), undef, 'Authority does not contain relator subfield' ); # Reset settings - t::lib::Mocks::mock_preference('AutoLinkBiblios', 0); - t::lib::Mocks::mock_preference('AutoCreateAuthorities', 0); + t::lib::Mocks::mock_preference( 'AutoLinkBiblios', 0 ); + t::lib::Mocks::mock_preference( 'AutoCreateAuthorities', 0 ); Koha::Cache::Memory::Lite->flush(); # Since we may have changed flavours } @@ -657,12 +730,12 @@ sub create_issn_field { } sub create_author_field { - my ( $author ) = @_; + my ($author) = @_; my ( $author_field, $author_subfield, $author_relator_subfield ) = get_author_field(); my $field = MARC::Field->new( $author_field, '', '', - $author_subfield => $author, + $author_subfield => $author, $author_relator_subfield => 'aut' ); @@ -698,17 +771,17 @@ subtest 'IsMarcStructureInternal' => sub { for my $tag ( sort keys %$tagslib ) { next unless $tag; for my $subfield ( sort keys %{ $tagslib->{$tag} } ) { - push @internals, $subfield if IsMarcStructureInternal($tagslib->{$tag}{$subfield}); + push @internals, $subfield if IsMarcStructureInternal( $tagslib->{$tag}{$subfield} ); } } @internals = uniq @internals; - is( scalar(@internals), 7, 'expect 7 internals'); - is( grep( /^lib$/, @internals ), 1, 'check lib' ); - is( grep( /^tab$/, @internals ), 1, 'check tab' ); - is( grep( /^mandatory$/, @internals ), 1, 'check mandatory' ); - is( grep( /^repeatable$/, @internals ), 1, 'check repeatable' ); - is( grep( /^important$/, @internals ), 1, 'check important' ); - is( grep( /^a$/, @internals ), 0, 'no subfield a' ); + is( scalar(@internals), 7, 'expect 7 internals' ); + is( grep( /^lib$/, @internals ), 1, 'check lib' ); + is( grep( /^tab$/, @internals ), 1, 'check tab' ); + is( grep( /^mandatory$/, @internals ), 1, 'check mandatory' ); + is( grep( /^repeatable$/, @internals ), 1, 'check repeatable' ); + is( grep( /^important$/, @internals ), 1, 'check important' ); + is( grep( /^a$/, @internals ), 0, 'no subfield a' ); is( grep( /^ind1_defaultvalue$/, @internals ), 1, 'check indicator 1 default value' ); is( grep( /^ind2_defaultvalue$/, @internals ), 1, 'check indicator 2 default value' ); }; @@ -718,12 +791,16 @@ subtest 'deletedbiblio_metadata' => sub { t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 0 ); - my ($biblionumber, $biblioitemnumber) = AddBiblio(MARC::Record->new, ''); - my $biblio_metadata = C4::Biblio::GetXmlBiblio( $biblionumber ); - C4::Biblio::DelBiblio( $biblionumber ); - my ( $moved ) = $dbh->selectrow_array(q|SELECT biblionumber FROM deletedbiblio WHERE biblionumber=?|, undef, $biblionumber); + my ( $biblionumber, $biblioitemnumber ) = AddBiblio( MARC::Record->new, '' ); + my $biblio_metadata = C4::Biblio::GetXmlBiblio($biblionumber); + C4::Biblio::DelBiblio($biblionumber); + my ($moved) = + $dbh->selectrow_array( q|SELECT biblionumber FROM deletedbiblio WHERE biblionumber=?|, undef, $biblionumber ); is( $moved, $biblionumber, 'Found in deletedbiblio' ); - ( $moved ) = $dbh->selectrow_array(q|SELECT biblionumber FROM deletedbiblio_metadata WHERE biblionumber=?|, undef, $biblionumber); + ($moved) = $dbh->selectrow_array( + q|SELECT biblionumber FROM deletedbiblio_metadata WHERE biblionumber=?|, undef, + $biblionumber + ); is( $moved, $biblionumber, 'Found in deletedbiblio_metadata' ); }; @@ -764,12 +841,13 @@ subtest 'DelBiblio' => sub { ); }; - my ($biblionumber, $biblioitemnumber) = C4::Biblio::AddBiblio(MARC::Record->new, ''); - my $deleted = C4::Biblio::DelBiblio( $biblionumber ); - is( $deleted, undef, 'DelBiblio returns undef is the biblio has been deleted correctly - Must be 1 instead'); # FIXME We should return 1 instead! + my ( $biblionumber, $biblioitemnumber ) = C4::Biblio::AddBiblio( MARC::Record->new, '' ); + my $deleted = C4::Biblio::DelBiblio($biblionumber); + is( $deleted, undef, 'DelBiblio returns undef is the biblio has been deleted correctly - Must be 1 instead' ) + ; # FIXME We should return 1 instead! - $deleted = C4::Biblio::DelBiblio( $biblionumber ); - is( $deleted, undef, 'DelBiblo should return undef is the record did not exist'); + $deleted = C4::Biblio::DelBiblio($biblionumber); + is( $deleted, undef, 'DelBiblo should return undef is the record did not exist' ); my $biblio = $builder->build_sample_biblio; my $subscription = $builder->build_object( @@ -803,121 +881,135 @@ subtest 'DelBiblio' => sub { biblionumber => $biblio->biblionumber, basketno => $order_basket->{basketno}, }; - my $order = $builder->build_object( - { class => 'Koha::Acquisition::Orders', value => $orderinfo } ); + my $order = $builder->build_object( { class => 'Koha::Acquisition::Orders', value => $orderinfo } ); # Add some ILL requests - my $ill_req_1 = $builder->build_object({ class => 'Koha::ILL::Requests', value => { biblio_id => $biblio->id, deleted_biblio_id => undef } }); - my $ill_req_2 = $builder->build_object({ class => 'Koha::ILL::Requests', value => { biblio_id => $biblio->id, deleted_biblio_id => undef } }); + my $ill_req_1 = $builder->build_object( + { class => 'Koha::ILL::Requests', value => { biblio_id => $biblio->id, deleted_biblio_id => undef } } ); + my $ill_req_2 = $builder->build_object( + { class => 'Koha::ILL::Requests', value => { biblio_id => $biblio->id, deleted_biblio_id => undef } } ); - C4::Biblio::DelBiblio($biblio->biblionumber); # Or $biblio->delete - is( $subscription->get_from_storage, undef, 'subscription should be deleted on biblio deletion' ); - is( $serial->get_from_storage, undef, 'serial should be deleted on biblio deletion' ); + C4::Biblio::DelBiblio( $biblio->biblionumber ); # Or $biblio->delete + is( $subscription->get_from_storage, undef, 'subscription should be deleted on biblio deletion' ); + is( $serial->get_from_storage, undef, 'serial should be deleted on biblio deletion' ); is( $subscription_history->get_from_storage, undef, 'subscription history should be deleted on biblio deletion' ); - is( $order->get_from_storage->deleted_biblionumber, $biblio->biblionumber, 'biblionumber of order has been moved to deleted_biblionumber column' ); + is( + $order->get_from_storage->deleted_biblionumber, $biblio->biblionumber, + 'biblionumber of order has been moved to deleted_biblionumber column' + ); $ill_req_1 = $ill_req_1->get_from_storage; $ill_req_2 = $ill_req_2->get_from_storage; - is( $ill_req_1->biblio_id, undef, 'biblio_id cleared on biblio deletion' ); + is( $ill_req_1->biblio_id, undef, 'biblio_id cleared on biblio deletion' ); is( $ill_req_1->deleted_biblio_id, $biblio->id, 'biblio_id is kept on the deleted_biblio_id column' ); - is( $ill_req_2->biblio_id, undef, 'biblio_id cleared on biblio deletion' ); + is( $ill_req_2->biblio_id, undef, 'biblio_id cleared on biblio deletion' ); is( $ill_req_2->deleted_biblio_id, $biblio->id, 'biblio_id is kept on the deleted_biblio_id column' ); }; subtest 'MarcFieldForCreatorAndModifier' => sub { plan tests => 8; - t::lib::Mocks::mock_preference('MarcFieldForCreatorId', '998$a'); - t::lib::Mocks::mock_preference('MarcFieldForCreatorName', '998$b'); - t::lib::Mocks::mock_preference('MarcFieldForModifierId', '998$c'); - t::lib::Mocks::mock_preference('MarcFieldForModifierName', '998$d'); + t::lib::Mocks::mock_preference( 'MarcFieldForCreatorId', '998$a' ); + t::lib::Mocks::mock_preference( 'MarcFieldForCreatorName', '998$b' ); + t::lib::Mocks::mock_preference( 'MarcFieldForModifierId', '998$c' ); + t::lib::Mocks::mock_preference( 'MarcFieldForModifierName', '998$d' ); my $c4_context = Test::MockModule->new('C4::Context'); - $c4_context->mock('userenv', sub { return { number => 123, firstname => 'John', surname => 'Doe'}; }); + $c4_context->mock( 'userenv', sub { return { number => 123, firstname => 'John', surname => 'Doe' }; } ); my $record = MARC::Record->new(); - my ($biblionumber) = C4::Biblio::AddBiblio($record, ''); + my ($biblionumber) = C4::Biblio::AddBiblio( $record, '' ); my $biblio = Koha::Biblios->find($biblionumber); $record = $biblio->metadata->record; - is($record->subfield('998', 'a'), 123, '998$a = 123'); - is($record->subfield('998', 'b'), 'John Doe', '998$b = John Doe'); - is($record->subfield('998', 'c'), 123, '998$c = 123'); - is($record->subfield('998', 'd'), 'John Doe', '998$d = John Doe'); + is( $record->subfield( '998', 'a' ), 123, '998$a = 123' ); + is( $record->subfield( '998', 'b' ), 'John Doe', '998$b = John Doe' ); + is( $record->subfield( '998', 'c' ), 123, '998$c = 123' ); + is( $record->subfield( '998', 'd' ), 'John Doe', '998$d = John Doe' ); - $c4_context->mock('userenv', sub { return { number => 321, firstname => 'Jane', surname => 'Doe'}; }); - C4::Biblio::ModBiblio($record, $biblionumber, ''); + $c4_context->mock( 'userenv', sub { return { number => 321, firstname => 'Jane', surname => 'Doe' }; } ); + C4::Biblio::ModBiblio( $record, $biblionumber, '' ); $record = $biblio->get_from_storage->metadata->record; - is($record->subfield('998', 'a'), 123, '998$a = 123'); - is($record->subfield('998', 'b'), 'John Doe', '998$b = John Doe'); - is($record->subfield('998', 'c'), 321, '998$c = 321'); - is($record->subfield('998', 'd'), 'Jane Doe', '998$d = Jane Doe'); + is( $record->subfield( '998', 'a' ), 123, '998$a = 123' ); + is( $record->subfield( '998', 'b' ), 'John Doe', '998$b = John Doe' ); + is( $record->subfield( '998', 'c' ), 321, '998$c = 321' ); + is( $record->subfield( '998', 'd' ), 'Jane Doe', '998$d = Jane Doe' ); }; subtest 'ModBiblio called from linker test' => sub { plan tests => 2; my $called = 0; - t::lib::Mocks::mock_preference('AutoLinkBiblios', 1); - my $biblio_mod = Test::MockModule->new( 'C4::Biblio' ); - $biblio_mod->mock( 'LinkBibHeadingsToAuthorities', sub { - $called = 1; - }); + t::lib::Mocks::mock_preference( 'AutoLinkBiblios', 1 ); + my $biblio_mod = Test::MockModule->new('C4::Biblio'); + $biblio_mod->mock( + 'LinkBibHeadingsToAuthorities', + sub { + $called = 1; + } + ); my $record = MARC::Record->new(); - my ($biblionumber) = C4::Biblio::AddBiblio($record,''); - C4::Biblio::ModBiblio($record,$biblionumber,''); - is($called,1,"We called to link bibs because not from linker"); + my ($biblionumber) = C4::Biblio::AddBiblio( $record, '' ); + C4::Biblio::ModBiblio( $record, $biblionumber, '' ); + is( $called, 1, "We called to link bibs because not from linker" ); $called = 0; - C4::Biblio::ModBiblio($record,$biblionumber,'',{ disable_autolink => 1 }); - is($called,0,"We didn't call to link bibs because from linker"); + C4::Biblio::ModBiblio( $record, $biblionumber, '', { disable_autolink => 1 } ); + is( $called, 0, "We didn't call to link bibs because from linker" ); }; subtest "LinkBibHeadingsToAuthorities tests" => sub { plan tests => 5; # Set up mocks to return more than 1 match - my $biblio_mod = Test::MockModule->new( 'C4::Linker::Default' ); - $biblio_mod->mock( 'get_link', sub { - return (undef, undef, 2); - }); + my $biblio_mod = Test::MockModule->new('C4::Linker::Default'); + $biblio_mod->mock( + 'get_link', + sub { + return ( undef, undef, 2 ); + } + ); + # UNIMARC return values should be consistent with MARC21 # testing with MARC21 should be sufficient for now - t::lib::Mocks::mock_preference('marcflavour', 'MARC21'); - t::lib::Mocks::mock_preference('AutoCreateAuthorities', '0'); + t::lib::Mocks::mock_preference( 'marcflavour', 'MARC21' ); + t::lib::Mocks::mock_preference( 'AutoCreateAuthorities', '0' ); my $linker = C4::Linker::Default->new(); my $biblio = $builder->build_sample_biblio(); my $record = $biblio->metadata->record; # Generate a field, no current link - my $field = MARC::Field->new('650','','','a' => 'Duplicated' ); + my $field = MARC::Field->new( '650', '', '', 'a' => 'Duplicated' ); $record->append_fields($field); my ( $num_headings_changed, $results ) = LinkBibHeadingsToAuthorities( $linker, $record, "", undef, 650, 1 ); is( $num_headings_changed, 0, 'We did not make any changes because we found 2' ); - is_deeply( $results->{unlinked}, - {"Duplicated" => 1 }, + is_deeply( + $results->{unlinked}, + { "Duplicated" => 1 }, "The heading was not linked" ); - is_deeply( $results->{details}[0], + is_deeply( + $results->{details}[0], { - tag => 650, - authid => undef, - status => 'MULTIPLE_MATCH', - auth_type => 'TOPIC_TERM', + tag => 650, + authid => undef, + status => 'MULTIPLE_MATCH', + auth_type => 'TOPIC_TERM', tag_to_report => 150 }, "The heading was not linked" ); - t::lib::Mocks::mock_preference('AutoCreateAuthorities', '1'); + t::lib::Mocks::mock_preference( 'AutoCreateAuthorities', '1' ); ( $num_headings_changed, $results ) = LinkBibHeadingsToAuthorities( $linker, $record, "", undef, 650, 1 ); is( $num_headings_changed, 0, 'We did not make any changes because we found 2' ); - is_deeply( $results->{details}[0], + is_deeply( + $results->{details}[0], { - tag => 650, - authid => undef, - status => 'MULTIPLE_MATCH', - auth_type => 'TOPIC_TERM', + tag => 650, + authid => undef, + status => 'MULTIPLE_MATCH', + auth_type => 'TOPIC_TERM', tag_to_report => 150 }, "When AutoCreateAuthorities is enabled, multiple results are reported" @@ -929,82 +1021,98 @@ subtest "LinkBibHeadingsToAuthorities record generation tests" => sub { plan tests => 12; # Set up mocks to ensure authorities are generated - my $biblio_mod = Test::MockModule->new( 'C4::Linker::Default' ); - $biblio_mod->mock( 'get_link', sub { - return (undef,undef,0); - }); + my $biblio_mod = Test::MockModule->new('C4::Linker::Default'); + $biblio_mod->mock( + 'get_link', + sub { + return ( undef, undef, 0 ); + } + ); + # UNIMARC valid headings are built from the marc_subfield_structure for bibs and # include all subfields as valid, testing with MARC21 should be sufficient for now - t::lib::Mocks::mock_preference('marcflavour', 'MARC21'); - t::lib::Mocks::mock_preference('AutoCreateAuthorities', '1'); + t::lib::Mocks::mock_preference( 'marcflavour', 'MARC21' ); + t::lib::Mocks::mock_preference( 'AutoCreateAuthorities', '1' ); my $linker = C4::Linker::Default->new(); my $biblio = $builder->build_sample_biblio(); my $record = $biblio->metadata->record; # Generate a record including all valid subfields and an invalid one 'e' - my $field = MARC::Field->new('650','','','a' => 'Beach city', 'b' => 'Weirdness', 'v' => 'Fiction', 'x' => 'Books', 'y' => '21st Century', 'z' => 'Fish Stew Pizza', 'e' => 'Depicted'); + my $field = MARC::Field->new( + '650', '', '', 'a' => 'Beach city', 'b' => 'Weirdness', 'v' => 'Fiction', 'x' => 'Books', + 'y' => '21st Century', 'z' => 'Fish Stew Pizza', 'e' => 'Depicted' + ); $record->append_fields($field); - my ( $num_headings_changed, $results ) = LinkBibHeadingsToAuthorities($linker, $record, "",undef,650); + my ( $num_headings_changed, $results ) = LinkBibHeadingsToAuthorities( $linker, $record, "", undef, 650 ); is( $num_headings_changed, 1, 'We changed the one we passed' ); - is_deeply( $results->{added}, - {"Beach city Weirdness--Fiction--Books--21st Century--Fish Stew Pizza" => 1 }, + is_deeply( + $results->{added}, + { "Beach city Weirdness--Fiction--Books--21st Century--Fish Stew Pizza" => 1 }, "We added an authority record for the heading" ); # Now we check the authority record itself - my $authority = GetAuthority( $record->subfield('650','9') ); - is( $authority->field('150')->as_string(), + my $authority = GetAuthority( $record->subfield( '650', '9' ) ); + is( + $authority->field('150')->as_string(), "Beach city Weirdness Fiction Books 21st Century Fish Stew Pizza", "The generated record contains the correct subfields" ); #Add test for this case using verbose $record->field('650')->delete_subfield('9'); - ( $num_headings_changed, $results ) = LinkBibHeadingsToAuthorities($linker, $record, "",undef, 650, 1); - is( $num_headings_changed, 1, 'We changed the one we passed' ); - is( $results->{details}->[0]->{status}, 'CREATED', "We added an authority record for the heading using verbose"); + ( $num_headings_changed, $results ) = LinkBibHeadingsToAuthorities( $linker, $record, "", undef, 650, 1 ); + is( $num_headings_changed, 1, 'We changed the one we passed' ); + is( $results->{details}->[0]->{status}, 'CREATED', "We added an authority record for the heading using verbose" ); # Now we check the authority record itself - $authority = GetAuthority($results->{details}->[0]->{authid}); + $authority = GetAuthority( $results->{details}->[0]->{authid} ); - is( $authority->field('150')->as_string(), - "Beach city Weirdness Fiction Books 21st Century Fish Stew Pizza", - "The generated record contains the correct subfields when using verbose" + is( + $authority->field('150')->as_string(), + "Beach city Weirdness Fiction Books 21st Century Fish Stew Pizza", + "The generated record contains the correct subfields when using verbose" ); # Example series link with volume and punctuation - $field = MARC::Field->new('800','','','a' => 'Tolkien, J. R. R.', 'q' => '(John Ronald Reuel),', 'd' => '1892-1973.', 't' => 'Lord of the rings ;', 'v' => '1'); + $field = MARC::Field->new( + '800', '', '', 'a' => 'Tolkien, J. R. R.', 'q' => '(John Ronald Reuel),', + 'd' => '1892-1973.', 't' => 'Lord of the rings ;', 'v' => '1' + ); $record->append_fields($field); - ( $num_headings_changed, $results ) = LinkBibHeadingsToAuthorities($linker, $record, "",undef, 800); + ( $num_headings_changed, $results ) = LinkBibHeadingsToAuthorities( $linker, $record, "", undef, 800 ); is( $num_headings_changed, 1, 'We changed the one we passed' ); - is_deeply( $results->{added}, - {"Tolkien, J. R. R. (John Ronald Reuel), 1892-1973. Lord of the rings ;" => 1 }, + is_deeply( + $results->{added}, + { "Tolkien, J. R. R. (John Ronald Reuel), 1892-1973. Lord of the rings ;" => 1 }, "We added an authority record for the heading" ); # Now we check the authority record itself - $authority = GetAuthority( $record->subfield('800','9') ); - is( $authority->field('100')->as_string(), + $authority = GetAuthority( $record->subfield( '800', '9' ) ); + is( + $authority->field('100')->as_string(), "Tolkien, J. R. R. (John Ronald Reuel), 1892-1973. Lord of the rings", "The generated record contains the correct subfields" ); # The same example With verbose $record->field('800')->delete_subfield('9'); - ( $num_headings_changed, $results ) = LinkBibHeadingsToAuthorities($linker, $record, "",undef, 800, 1); - is( $num_headings_changed, 1, 'We changed the one we passed' ); - is( $results->{details}->[0]->{status}, 'CREATED', "We added an authority record for the heading using verbose"); + ( $num_headings_changed, $results ) = LinkBibHeadingsToAuthorities( $linker, $record, "", undef, 800, 1 ); + is( $num_headings_changed, 1, 'We changed the one we passed' ); + is( $results->{details}->[0]->{status}, 'CREATED', "We added an authority record for the heading using verbose" ); # Now we check the authority record itself - $authority = GetAuthority($results->{details}->[0]->{authid}); - is( $authority->field('100')->as_string(), - "Tolkien, J. R. R. (John Ronald Reuel), 1892-1973. Lord of the rings", - "The generated record contains the correct subfields" + $authority = GetAuthority( $results->{details}->[0]->{authid} ); + is( + $authority->field('100')->as_string(), + "Tolkien, J. R. R. (John Ronald Reuel), 1892-1973. Lord of the rings", + "The generated record contains the correct subfields" ); }; @@ -1012,26 +1120,29 @@ subtest 'autoControlNumber tests' => sub { plan tests => 3; - t::lib::Mocks::mock_preference('autoControlNumber', 'OFF'); + t::lib::Mocks::mock_preference( 'autoControlNumber', 'OFF' ); - my $record = MARC::Record->new(); - my ($biblio_id) = C4::Biblio::AddBiblio($record, ''); - my $biblio = Koha::Biblios->find($biblio_id); + my $record = MARC::Record->new(); + my ($biblio_id) = C4::Biblio::AddBiblio( $record, '' ); + my $biblio = Koha::Biblios->find($biblio_id); $record = $biblio->metadata->record; - is($record->field('001'), undef, '001 not set when pref is off'); + is( $record->field('001'), undef, '001 not set when pref is off' ); - t::lib::Mocks::mock_preference('autoControlNumber', 'biblionumber'); - C4::Biblio::ModBiblio($record, $biblio_id, "", { skip_record_index => 1, disable_autolink => 1 }); + t::lib::Mocks::mock_preference( 'autoControlNumber', 'biblionumber' ); + C4::Biblio::ModBiblio( $record, $biblio_id, "", { skip_record_index => 1, disable_autolink => 1 } ); $biblio->discard_changes; $record = $biblio->metadata->record; - is($record->field('001')->as_string(), $biblio_id, '001 set to biblionumber when pref set and field is blank'); + is( $record->field('001')->as_string(), $biblio_id, '001 set to biblionumber when pref set and field is blank' ); $record->field('001')->update('Not biblionumber'); - C4::Biblio::ModBiblio($record, $biblio_id, "", { skip_record_index => 1, disable_autolink => 1 }); + C4::Biblio::ModBiblio( $record, $biblio_id, "", { skip_record_index => 1, disable_autolink => 1 } ); $biblio->discard_changes; $record = $biblio->metadata->record; - is($record->field('001')->as_string(), 'Not biblionumber', '001 not set to biblionumber when pref set and field exists'); + is( + $record->field('001')->as_string(), 'Not biblionumber', + '001 not set to biblionumber when pref set and field exists' + ); }; @@ -1045,8 +1156,10 @@ subtest 'record test' => sub { my $biblio = Koha::Biblios->find($biblionumber); - is( $biblio->record->as_formatted, - $biblio->metadata->record->as_formatted ); + is( + $biblio->record->as_formatted, + $biblio->metadata->record->as_formatted + ); }; subtest 'record_schema test' => sub { @@ -1059,30 +1172,37 @@ subtest 'record_schema test' => sub { my $biblio = Koha::Biblios->find($biblionumber); - is( $biblio->record_schema, - $biblio->metadata->schema ); + is( + $biblio->record_schema, + $biblio->metadata->schema + ); }; - subtest 'GetFrameworkCode' => sub { plan tests => 4; - my $biblio = $builder->build_sample_biblio({ frameworkcode => 'OBP' }); + my $biblio = $builder->build_sample_biblio( { frameworkcode => 'OBP' } ); - is(GetFrameworkCode($biblio->biblionumber), 'OBP', 'GetFrameworkCode returns correct frameworkcode'); + is( GetFrameworkCode( $biblio->biblionumber ), 'OBP', 'GetFrameworkCode returns correct frameworkcode' ); - my $cache = Koha::Cache::Memory::Lite->get_instance(); - my $cache_key = "FrameworkCode-" . $biblio->biblionumber; + my $cache = Koha::Cache::Memory::Lite->get_instance(); + my $cache_key = "FrameworkCode-" . $biblio->biblionumber; my $frameworkcode = $cache->get_from_cache($cache_key); - is($frameworkcode, 'OBP', 'Cache has been set in GetFrameworkCode'); + is( $frameworkcode, 'OBP', 'Cache has been set in GetFrameworkCode' ); # Set new value directly in cache to make sure it's actually being used - $cache->set_in_cache($cache_key, 'OD'); - is(GetFrameworkCode($biblio->biblionumber), 'OD', 'GetFrameworkCode returns correct frameworkcode, using cache'); + $cache->set_in_cache( $cache_key, 'OD' ); + is( + GetFrameworkCode( $biblio->biblionumber ), 'OD', + 'GetFrameworkCode returns correct frameworkcode, using cache' + ); # Test cache invalidation - ModBiblio($biblio->metadata->record, $biblio->biblionumber, 'OGR'); - is(GetFrameworkCode($biblio->biblionumber), 'OGR', 'GetFrameworkCode returns correct frameworkcode after setting a new one though ModBiblio'); + ModBiblio( $biblio->metadata->record, $biblio->biblionumber, 'OGR' ); + is( + GetFrameworkCode( $biblio->biblionumber ), 'OGR', + 'GetFrameworkCode returns correct frameworkcode after setting a new one though ModBiblio' + ); }; @@ -1259,5 +1379,5 @@ subtest 'AddBiblio/ModBiblio calling ModBiblioMarc for field 005' => sub { }; # Cleanup -Koha::Caches->get_instance->clear_from_cache( "MarcSubfieldStructure-" ); +Koha::Caches->get_instance->clear_from_cache("MarcSubfieldStructure-"); $schema->storage->txn_rollback; diff --git a/t/db_dependent/Biblio/Isbd.t b/t/db_dependent/Biblio/Isbd.t index dc992b284a..bc11dad07a 100755 --- a/t/db_dependent/Biblio/Isbd.t +++ b/t/db_dependent/Biblio/Isbd.t @@ -25,27 +25,27 @@ use t::lib::Mocks qw( mock_preference ); use Koha::Database; BEGIN { - use_ok('C4::Biblio', qw( GetISBDView )); + use_ok( 'C4::Biblio', qw( GetISBDView ) ); } -my $schema = Koha::Database->new->schema; +my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; -my $template = '#200|<h2>Title : |{200a}{ by 200f}|</h2>'; +my $template = '#200|<h2>Title : |{200a}{ by 200f}|</h2>'; my $opac_template = '#200|<h2>Title : |{200a}{ (200f)}|</h2>'; -t::lib::Mocks::mock_preference('isbd', $template); -t::lib::Mocks::mock_preference('opacisbd', $opac_template); +t::lib::Mocks::mock_preference( 'isbd', $template ); +t::lib::Mocks::mock_preference( 'opacisbd', $opac_template ); my $record = MARC::Record->new(); $record->append_fields( - MARC::Field->new('200', '', '', 'a' => 'Mountains'), - MARC::Field->new('200', '', '', 'f' => 'Keith Lye'), + MARC::Field->new( '200', '', '', 'a' => 'Mountains' ), + MARC::Field->new( '200', '', '', 'f' => 'Keith Lye' ), ); -my $isbd = GetISBDView({ record => $record }); -is($isbd, '<h2>Title : Mountains by Keith Lye</h2>', 'ISBD is correct'); +my $isbd = GetISBDView( { record => $record } ); +is( $isbd, '<h2>Title : Mountains by Keith Lye</h2>', 'ISBD is correct' ); -my $opacisbd = GetISBDView({ record => $record, template => 'opac' }); -is($opacisbd, '<h2>Title : Mountains (Keith Lye)</h2>', 'OPAC ISBD is correct'); +my $opacisbd = GetISBDView( { record => $record, template => 'opac' } ); +is( $opacisbd, '<h2>Title : Mountains (Keith Lye)</h2>', 'OPAC ISBD is correct' ); $schema->storage->txn_rollback; diff --git a/t/db_dependent/Biblio/MarcOverlayRules.t b/t/db_dependent/Biblio/MarcOverlayRules.t index c97815494d..7becb4e39c 100755 --- a/t/db_dependent/Biblio/MarcOverlayRules.t +++ b/t/db_dependent/Biblio/MarcOverlayRules.t @@ -36,44 +36,45 @@ use t::lib::Mocks; my $schema = Koha::Database->schema; $schema->storage->txn_begin; -t::lib::Mocks::mock_preference('MARCOverlayRules', '1'); +t::lib::Mocks::mock_preference( 'MARCOverlayRules', '1' ); Koha::MarcOverlayRules->search->delete; sub build_record { - my ( $fields ) = @_; + my ($fields) = @_; my $record = MARC::Record->new; my @marc_fields; - for my $f ( @$fields ) { + for my $f (@$fields) { my $tag = $f->[0]; my @subfields; - for my $i ( 1 .. (scalar(@$f) / 2) ) { - my $ii = floor($i*2); - push @subfields, $f->[$ii - 1], $f->[$ii]; + for my $i ( 1 .. ( scalar(@$f) / 2 ) ) { + my $ii = floor( $i * 2 ); + push @subfields, $f->[ $ii - 1 ], $f->[$ii]; } - push @marc_fields, MARC::Field->new($tag, '','', @subfields); + push @marc_fields, MARC::Field->new( $tag, '', '', @subfields ); } $record->append_fields(@marc_fields); return $record; } - # Create a record -my $orig_record = build_record([ - [ '250', 'a', '250 bottles of beer on the wall' ], - [ '250', 'a', '256 bottles of beer on the wall' ], - [ '500', 'a', 'One bottle of beer in the fridge' ], -]); +my $orig_record = build_record( + [ + [ '250', 'a', '250 bottles of beer on the wall' ], + [ '250', 'a', '256 bottles of beer on the wall' ], + [ '500', 'a', 'One bottle of beer in the fridge' ], + ] +); my $incoming_record = build_record( [ - [ '250', 'a', '256 bottles of beer on the wall' ], # Unchanged - [ '250', 'a', '251 bottles of beer on the wall' ], # Appended - # ['250', 'a', '250 bottles of beer on the wall'], # Removed - # ['500', 'a', 'One bottle of beer in the fridge'], # Deleted - [ '501', 'a', 'One cold bottle of beer in the fridge' ], # Added - [ '501', 'a', 'Two cold bottles of beer in the fridge' ], # Added + [ '250', 'a', '256 bottles of beer on the wall' ], # Unchanged + [ '250', 'a', '251 bottles of beer on the wall' ], # Appended + # ['250', 'a', '250 bottles of beer on the wall'], # Removed + # ['500', 'a', 'One bottle of beer in the fridge'], # Deleted + [ '501', 'a', 'One cold bottle of beer in the fridge' ], # Added + [ '501', 'a', 'Two cold bottles of beer in the fridge' ], # Added ] ); @@ -81,7 +82,7 @@ my $incoming_record = build_record( subtest 'No rule defined' => sub { plan tests => 1; - my $merged_record = Koha::MarcOverlayRules->merge_records($orig_record, $incoming_record, { 'source' => 'test' }); + my $merged_record = Koha::MarcOverlayRules->merge_records( $orig_record, $incoming_record, { 'source' => 'test' } ); is( $merged_record->as_formatted, @@ -91,20 +92,22 @@ subtest 'No rule defined' => sub { }; -my $rule = Koha::MarcOverlayRules->find_or_create({ - tag => '*', - module => 'source', - filter => '*', - add => 0, - append => 0, - remove => 0, - delete => 0 -}); +my $rule = Koha::MarcOverlayRules->find_or_create( + { + tag => '*', + module => 'source', + filter => '*', + add => 0, + append => 0, + remove => 0, + delete => 0 + } +); subtest 'Record fields has been protected when matched merge all rule operations are set to "0"' => sub { plan tests => 1; - my $merged_record = Koha::MarcOverlayRules->merge_records($orig_record, $incoming_record, { 'source' => 'test' }); + my $merged_record = Koha::MarcOverlayRules->merge_records( $orig_record, $incoming_record, { 'source' => 'test' } ); is( $merged_record->as_formatted, @@ -119,22 +122,24 @@ subtest '"Add new" - Only new fields has been added when add = 1, append = 0, re $rule->set( { - 'add' => 1, + 'add' => 1, 'append' => 0, 'remove' => 0, 'delete' => 0, } )->store(); - my $merged_record = Koha::MarcOverlayRules->merge_records($orig_record, $incoming_record, { 'source' => 'test' }); + my $merged_record = Koha::MarcOverlayRules->merge_records( $orig_record, $incoming_record, { 'source' => 'test' } ); - my $expected_record = build_record([ - [ '250', 'a', '250 bottles of beer on the wall' ], # original - [ '250', 'a', '256 bottles of beer on the wall' ], # original - [ '500', 'a', 'One bottle of beer in the fridge' ], # original - [ '501', 'a', 'One cold bottle of beer in the fridge' ], # incoming - [ '501', 'a', 'Two cold bottles of beer in the fridge' ], # incoming - ]); + my $expected_record = build_record( + [ + [ '250', 'a', '250 bottles of beer on the wall' ], # original + [ '250', 'a', '256 bottles of beer on the wall' ], # original + [ '500', 'a', 'One bottle of beer in the fridge' ], # original + [ '501', 'a', 'One cold bottle of beer in the fridge' ], # incoming + [ '501', 'a', 'Two cold bottles of beer in the fridge' ], # incoming + ] + ); is( $merged_record->as_formatted, $expected_record->as_formatted, @@ -148,23 +153,25 @@ subtest 'Only appended fields has been added when add = 0, append = 1, remove = $rule->set( { - 'add' => 0, + 'add' => 0, 'append' => 1, 'remove' => 0, 'delete' => 0, } )->store; - my $merged_record = Koha::MarcOverlayRules->merge_records($orig_record, $incoming_record, { 'source' => 'test' }); + my $merged_record = Koha::MarcOverlayRules->merge_records( $orig_record, $incoming_record, { 'source' => 'test' } ); - my $expected_record = build_record([ - [ '250', 'a', '250 bottles of beer on the wall' ], # original - [ '250', 'a', '256 bottles of beer on the wall' ], # original - # "251" field has been appended - [ '250', 'a', '251 bottles of beer on the wall' ], # incoming - # "500" field has retained its original value - [ '500', 'a', 'One bottle of beer in the fridge' ], # original - ]); + my $expected_record = build_record( + [ + [ '250', 'a', '250 bottles of beer on the wall' ], # original + [ '250', 'a', '256 bottles of beer on the wall' ], # original + # "251" field has been appended + [ '250', 'a', '251 bottles of beer on the wall' ], # incoming + # "500" field has retained its original value + [ '500', 'a', 'One bottle of beer in the fridge' ], # original + ] + ); is( $merged_record->as_formatted, @@ -179,26 +186,28 @@ subtest '"Add and append" - add = 1, append = 1, remove = 0, delete = 0' => sub $rule->set( { - 'add' => 1, + 'add' => 1, 'append' => 1, 'remove' => 0, 'delete' => 0, } )->store; - my $expected_record = build_record([ - [ '250', 'a', '250 bottles of beer on the wall' ], # original - [ '250', 'a', '256 bottles of beer on the wall' ], # original - # "251" field has been appended - [ '250', 'a', '251 bottles of beer on the wall' ], # incoming - # "500" field has retained its original value - [ '500', 'a', 'One bottle of beer in the fridge' ], # original - # "501" fields have been added - [ '501', 'a', 'One cold bottle of beer in the fridge' ], # incoming - [ '501', 'a', 'Two cold bottles of beer in the fridge' ], # incoming - ]); + my $expected_record = build_record( + [ + [ '250', 'a', '250 bottles of beer on the wall' ], # original + [ '250', 'a', '256 bottles of beer on the wall' ], # original + # "251" field has been appended + [ '250', 'a', '251 bottles of beer on the wall' ], # incoming + # "500" field has retained its original value + [ '500', 'a', 'One bottle of beer in the fridge' ], # original + # "501" fields have been added + [ '501', 'a', 'One cold bottle of beer in the fridge' ], # incoming + [ '501', 'a', 'Two cold bottles of beer in the fridge' ], # incoming + ] + ); - my $merged_record = Koha::MarcOverlayRules->merge_records($orig_record, $incoming_record, { 'source' => 'test' }); + my $merged_record = Koha::MarcOverlayRules->merge_records( $orig_record, $incoming_record, { 'source' => 'test' } ); is( $merged_record->as_formatted, @@ -213,7 +222,7 @@ subtest 'Record fields has been only removed when add = 0, append = 0, remove = $rule->set( { - 'add' => 0, + 'add' => 0, 'append' => 0, 'remove' => 1, 'delete' => 0, @@ -221,14 +230,16 @@ subtest 'Record fields has been only removed when add = 0, append = 0, remove = )->store; # Warning - not obvious as the 500 is untouched - my $expected_record = build_record([ + my $expected_record = build_record( + [ # "250" field has been removed - [ '250', 'a', '256 bottles of beer on the wall' ], # original and incoming - # "500" field has retained its original value - [ '500', 'a', 'One bottle of beer in the fridge' ], # original - ]); + [ '250', 'a', '256 bottles of beer on the wall' ], # original and incoming + # "500" field has retained its original value + [ '500', 'a', 'One bottle of beer in the fridge' ], # original + ] + ); - my $merged_record = Koha::MarcOverlayRules->merge_records($orig_record, $incoming_record, { 'source' => 'test' }); + my $merged_record = Koha::MarcOverlayRules->merge_records( $orig_record, $incoming_record, { 'source' => 'test' } ); is( $merged_record->as_formatted, @@ -243,24 +254,26 @@ subtest 'Record fields has been added and removed when add = 1, append = 0, remo $rule->set( { - 'add' => 1, + 'add' => 1, 'append' => 0, 'remove' => 1, 'delete' => 0, } )->store(); - my $expected_record = build_record([ + my $expected_record = build_record( + [ # "250" field has been removed - [ '250', 'a', '256 bottles of beer on the wall' ], # original and incoming - # "500" field has retained its original value - [ '500', 'a', 'One bottle of beer in the fridge' ], # original - # "501" fields have been added - [ '501', 'a', 'One cold bottle of beer in the fridge' ], # incoming - [ '501', 'a', 'Two cold bottles of beer in the fridge' ], # incoming - ]); + [ '250', 'a', '256 bottles of beer on the wall' ], # original and incoming + # "500" field has retained its original value + [ '500', 'a', 'One bottle of beer in the fridge' ], # original + # "501" fields have been added + [ '501', 'a', 'One cold bottle of beer in the fridge' ], # incoming + [ '501', 'a', 'Two cold bottles of beer in the fridge' ], # incoming + ] + ); - my $merged_record = Koha::MarcOverlayRules->merge_records($orig_record, $incoming_record, { 'source' => 'test' }); + my $merged_record = Koha::MarcOverlayRules->merge_records( $orig_record, $incoming_record, { 'source' => 'test' } ); is( $merged_record->as_formatted, @@ -275,22 +288,24 @@ subtest 'Record fields has been appended and removed when add = 0, append = 1, r $rule->set( { - 'add' => 0, + 'add' => 0, 'append' => 1, 'remove' => 1, 'delete' => 0, } )->store(); - my $expected_record = build_record([ + my $expected_record = build_record( + [ # "250" field has been appended and removed - [ '250', 'a', '256 bottles of beer on the wall' ], # incoming - [ '250', 'a', '251 bottles of beer on the wall' ], # incoming - # "500" field has retained its original value - [ '500', 'a', 'One bottle of beer in the fridge' ], # original - ]); + [ '250', 'a', '256 bottles of beer on the wall' ], # incoming + [ '250', 'a', '251 bottles of beer on the wall' ], # incoming + # "500" field has retained its original value + [ '500', 'a', 'One bottle of beer in the fridge' ], # original + ] + ); - my $merged_record = Koha::MarcOverlayRules->merge_records($orig_record, $incoming_record, { 'source' => 'test' }); + my $merged_record = Koha::MarcOverlayRules->merge_records( $orig_record, $incoming_record, { 'source' => 'test' } ); is( $merged_record->as_formatted, @@ -305,25 +320,27 @@ subtest 'Record fields has been added, appended and removed when add = 0, append $rule->set( { - 'add' => 1, + 'add' => 1, 'append' => 1, 'remove' => 1, 'delete' => 0, } )->store(); - my $expected_record = build_record([ + my $expected_record = build_record( + [ # "250" field has been appended and removed - [ '250', 'a', '256 bottles of beer on the wall' ], # incoming - [ '250', 'a', '251 bottles of beer on the wall' ], # incoming - # "500" field has retained its original value - [ '500', 'a', 'One bottle of beer in the fridge' ], # original - # "501" fields have been added - [ '501', 'a', 'One cold bottle of beer in the fridge' ], # incoming - [ '501', 'a', 'Two cold bottles of beer in the fridge' ], # incoming - ]); + [ '250', 'a', '256 bottles of beer on the wall' ], # incoming + [ '250', 'a', '251 bottles of beer on the wall' ], # incoming + # "500" field has retained its original value + [ '500', 'a', 'One bottle of beer in the fridge' ], # original + # "501" fields have been added + [ '501', 'a', 'One cold bottle of beer in the fridge' ], # incoming + [ '501', 'a', 'Two cold bottles of beer in the fridge' ], # incoming + ] + ); - my $merged_record = Koha::MarcOverlayRules->merge_records($orig_record, $incoming_record, { 'source' => 'test' }); + my $merged_record = Koha::MarcOverlayRules->merge_records( $orig_record, $incoming_record, { 'source' => 'test' } ); is( $merged_record->as_formatted, @@ -338,7 +355,7 @@ subtest 'Record fields has been deleted when add = 0, append = 0, remove = 0, de $rule->set( { - 'add' => 0, + 'add' => 0, 'append' => 0, 'remove' => 0, 'delete' => 1, @@ -348,13 +365,15 @@ subtest 'Record fields has been deleted when add = 0, append = 0, remove = 0, de # FIXME the tooltip for delete is saying # "If the original record has fields matching the rule tag, but no fields with this are found in the incoming record" # But it does not seem to do that - my $expected_record = build_record([ + my $expected_record = build_record( + [ # "250" fields have retained their original value - [ '250', 'a', '250 bottles of beer on the wall' ], # original - [ '250', 'a', '256 bottles of beer on the wall' ], # original - ]); + [ '250', 'a', '250 bottles of beer on the wall' ], # original + [ '250', 'a', '256 bottles of beer on the wall' ], # original + ] + ); - my $merged_record = Koha::MarcOverlayRules->merge_records($orig_record, $incoming_record, { 'source' => 'test' }); + my $merged_record = Koha::MarcOverlayRules->merge_records( $orig_record, $incoming_record, { 'source' => 'test' } ); is( $merged_record->as_formatted, @@ -369,7 +388,7 @@ subtest 'Record fields has been added and deleted when add = 1, append = 0, remo $rule->set( { - 'add' => 1, + 'add' => 1, 'append' => 0, 'remove' => 0, 'delete' => 1, @@ -377,17 +396,19 @@ subtest 'Record fields has been added and deleted when add = 1, append = 0, remo )->store(); # Warning - is there a use case in real-life for this combinaison? - my $expected_record = build_record([ + my $expected_record = build_record( + [ # "250" field have retained their original value - [ '250', 'a', '250 bottles of beer on the wall' ], # original - [ '250', 'a', '256 bottles of beer on the wall' ], # original - # "500" field has been removed - # "501" fields have been added - [ '501', 'a', 'One cold bottle of beer in the fridge' ], # incoming - [ '501', 'a', 'Two cold bottles of beer in the fridge' ], # incoming - ]); + [ '250', 'a', '250 bottles of beer on the wall' ], # original + [ '250', 'a', '256 bottles of beer on the wall' ], # original + # "500" field has been removed + # "501" fields have been added + [ '501', 'a', 'One cold bottle of beer in the fridge' ], # incoming + [ '501', 'a', 'Two cold bottles of beer in the fridge' ], # incoming + ] + ); - my $merged_record = Koha::MarcOverlayRules->merge_records($orig_record, $incoming_record, { 'source' => 'test' }); + my $merged_record = Koha::MarcOverlayRules->merge_records( $orig_record, $incoming_record, { 'source' => 'test' } ); is( $merged_record->as_formatted, @@ -402,22 +423,24 @@ subtest 'Record fields has been appended and deleted when add = 0, append = 1, r $rule->set( { - 'add' => 0, + 'add' => 0, 'append' => 1, 'remove' => 0, 'delete' => 1, } )->store(); - my $expected_record = build_record([ + my $expected_record = build_record( + [ # "250" field has been appended - [ '250', 'a', '250 bottles of beer on the wall' ], # original - [ '250', 'a', '256 bottles of beer on the wall' ], # original and incoming - [ '250', 'a', '251 bottles of beer on the wall' ], # incoming - # "500" field has been removed - ]); + [ '250', 'a', '250 bottles of beer on the wall' ], # original + [ '250', 'a', '256 bottles of beer on the wall' ], # original and incoming + [ '250', 'a', '251 bottles of beer on the wall' ], # incoming + # "500" field has been removed + ] + ); - my $merged_record = Koha::MarcOverlayRules->merge_records($orig_record, $incoming_record, { 'source' => 'test' }); + my $merged_record = Koha::MarcOverlayRules->merge_records( $orig_record, $incoming_record, { 'source' => 'test' } ); is( $merged_record->as_formatted, @@ -432,25 +455,27 @@ subtest 'Record fields has been added, appended and deleted when add = 1, append $rule->set( { - 'add' => 1, + 'add' => 1, 'append' => 1, 'remove' => 0, 'delete' => 1, } )->store(); - my $expected_record = build_record([ + my $expected_record = build_record( + [ # "250" field has been appended - [ '250', 'a', '250 bottles of beer on the wall' ], # original - [ '250', 'a', '256 bottles of beer on the wall' ], # original and incoming - [ '250', 'a', '251 bottles of beer on the wall' ], # incoming - # "500" field has been removed - # "501" fields have been added - [ '501', 'a', 'One cold bottle of beer in the fridge' ], # incoming - [ '501', 'a', 'Two cold bottles of beer in the fridge' ], # incoming - ]); + [ '250', 'a', '250 bottles of beer on the wall' ], # original + [ '250', 'a', '256 bottles of beer on the wall' ], # original and incoming + [ '250', 'a', '251 bottles of beer on the wall' ], # incoming + # "500" field has been removed + # "501" fields have been added + [ '501', 'a', 'One cold bottle of beer in the fridge' ], # incoming + [ '501', 'a', 'Two cold bottles of beer in the fridge' ], # incoming + ] + ); - my $merged_record = Koha::MarcOverlayRules->merge_records($orig_record, $incoming_record, { 'source' => 'test' }); + my $merged_record = Koha::MarcOverlayRules->merge_records( $orig_record, $incoming_record, { 'source' => 'test' } ); is( $merged_record->as_formatted, @@ -465,20 +490,22 @@ subtest 'Record fields has been removed and deleted when add = 0, append = 0, re $rule->set( { - 'add' => 0, + 'add' => 0, 'append' => 0, 'remove' => 1, 'delete' => 1, } )->store(); - my $expected_record = build_record([ + my $expected_record = build_record( + [ # "250" field has been removed - [ '250', 'a', '256 bottles of beer on the wall' ], # original and incoming - # "500" field has been removed - ]); + [ '250', 'a', '256 bottles of beer on the wall' ], # original and incoming + # "500" field has been removed + ] + ); - my $merged_record = Koha::MarcOverlayRules->merge_records($orig_record, $incoming_record, { 'source' => 'test' }); + my $merged_record = Koha::MarcOverlayRules->merge_records( $orig_record, $incoming_record, { 'source' => 'test' } ); is( $merged_record->as_formatted, @@ -493,23 +520,25 @@ subtest 'Record fields has been added, removed and deleted when add = 1, append $rule->set( { - 'add' => 1, + 'add' => 1, 'append' => 0, 'remove' => 1, 'delete' => 1, } )->store(); - my $expected_record = build_record([ + my $expected_record = build_record( + [ # "250" field has been appended - [ '250', 'a', '256 bottles of beer on the wall' ], # original and incoming - # "500" field has been removed - # "501" fields have been added - [ '501', 'a', 'One cold bottle of beer in the fridge' ], # incoming - [ '501', 'a', 'Two cold bottles of beer in the fridge' ], # incoming - ]); + [ '250', 'a', '256 bottles of beer on the wall' ], # original and incoming + # "500" field has been removed + # "501" fields have been added + [ '501', 'a', 'One cold bottle of beer in the fridge' ], # incoming + [ '501', 'a', 'Two cold bottles of beer in the fridge' ], # incoming + ] + ); - my $merged_record = Koha::MarcOverlayRules->merge_records($orig_record, $incoming_record, { 'source' => 'test' }); + my $merged_record = Koha::MarcOverlayRules->merge_records( $orig_record, $incoming_record, { 'source' => 'test' } ); is( $merged_record->as_formatted, @@ -524,21 +553,23 @@ subtest 'Record fields has been appended, removed and deleted when add = 0, appe $rule->set( { - 'add' => 0, + 'add' => 0, 'append' => 1, 'remove' => 1, 'delete' => 1, } )->store(); - my $expected_record = build_record([ + my $expected_record = build_record( + [ # "250" field has been appended and removed - [ '250', 'a', '256 bottles of beer on the wall' ], # incoming - [ '250', 'a', '251 bottles of beer on the wall' ], # incoming - # "500" field has been removed - ]); + [ '250', 'a', '256 bottles of beer on the wall' ], # incoming + [ '250', 'a', '251 bottles of beer on the wall' ], # incoming + # "500" field has been removed + ] + ); - my $merged_record = Koha::MarcOverlayRules->merge_records($orig_record, $incoming_record, { 'source' => 'test' }); + my $merged_record = Koha::MarcOverlayRules->merge_records( $orig_record, $incoming_record, { 'source' => 'test' } ); is( $merged_record->as_formatted, @@ -553,14 +584,14 @@ subtest 'Record fields has been overwritten when add = 1, append = 1, remove = 1 $rule->set( { - 'add' => 1, + 'add' => 1, 'append' => 1, 'remove' => 1, 'delete' => 1, } )->store(); - my $merged_record = Koha::MarcOverlayRules->merge_records($orig_record, $incoming_record, { 'source' => 'test' }); + my $merged_record = Koha::MarcOverlayRules->merge_records( $orig_record, $incoming_record, { 'source' => 'test' } ); is( $merged_record->as_formatted, @@ -575,7 +606,7 @@ subtest 'subfields order' => sub { $rule->set( { - 'add' => 0, + 'add' => 0, 'append' => 0, 'remove' => 0, 'delete' => 0, @@ -590,7 +621,7 @@ subtest 'subfields order' => sub { ] ); - my $merged_record = Koha::MarcOverlayRules->merge_records($orig_record, $incoming_record, { 'source' => 'test' }); + my $merged_record = Koha::MarcOverlayRules->merge_records( $orig_record, $incoming_record, { 'source' => 'test' } ); is( $merged_record->as_formatted, @@ -600,14 +631,14 @@ subtest 'subfields order' => sub { $rule->set( { - 'add' => 1, + 'add' => 1, 'append' => 1, 'remove' => 1, 'delete' => 1, } )->store(); - $merged_record = Koha::MarcOverlayRules->merge_records($orig_record, $incoming_record, { 'source' => 'test' }); + $merged_record = Koha::MarcOverlayRules->merge_records( $orig_record, $incoming_record, { 'source' => 'test' } ); is( $merged_record->as_formatted, @@ -620,31 +651,37 @@ subtest 'subfields order' => sub { # Test rule tag specificity # Protect field 500 with more specific tag value -my $skip_all_rule = Koha::MarcOverlayRules->find_or_create({ - tag => '500', - module => 'source', - filter => '*', - add => 0, - append => 0, - remove => 0, - delete => 0 -}); +my $skip_all_rule = Koha::MarcOverlayRules->find_or_create( + { + tag => '500', + module => 'source', + filter => '*', + add => 0, + append => 0, + remove => 0, + delete => 0 + } +); -subtest '"500" field has been protected when rule matching on tag "500" is add = 0, append = 0, remove = 0, delete = 0' => sub { +subtest + '"500" field has been protected when rule matching on tag "500" is add = 0, append = 0, remove = 0, delete = 0' => + sub { plan tests => 1; - my $expected_record = build_record([ + my $expected_record = build_record( + [ # "250" field has been appended - [ '250', 'a', '256 bottles of beer on the wall' ], # incoming - [ '250', 'a', '251 bottles of beer on the wall' ], # incoming - # "500" field has retained its original value - [ '500', 'a', 'One bottle of beer in the fridge' ], # original - # "501" fields have been added - [ '501', 'a', 'One cold bottle of beer in the fridge' ], # incoming - [ '501', 'a', 'Two cold bottles of beer in the fridge' ], # incoming - ]); + [ '250', 'a', '256 bottles of beer on the wall' ], # incoming + [ '250', 'a', '251 bottles of beer on the wall' ], # incoming + # "500" field has retained its original value + [ '500', 'a', 'One bottle of beer in the fridge' ], # original + # "501" fields have been added + [ '501', 'a', 'One cold bottle of beer in the fridge' ], # incoming + [ '501', 'a', 'Two cold bottles of beer in the fridge' ], # incoming + ] + ); - my $merged_record = Koha::MarcOverlayRules->merge_records($orig_record, $incoming_record, { 'source' => 'test' }); + my $merged_record = Koha::MarcOverlayRules->merge_records( $orig_record, $incoming_record, { 'source' => 'test' } ); is( $merged_record->as_formatted, @@ -652,10 +689,12 @@ subtest '"500" field has been protected when rule matching on tag "500" is add = 'All fields are erased by incoming record but 500 is protected' ); -}; + }; # Test regexp matching -subtest '"5XX" fields has been protected when rule matching on regexp "5\d{2}" is add = 0, append = 0, remove = 0, delete = 0' => sub { +subtest + '"5XX" fields has been protected when rule matching on regexp "5\d{2}" is add = 0, append = 0, remove = 0, delete = 0' + => sub { plan tests => 1; $skip_all_rule->set( @@ -664,15 +703,17 @@ subtest '"5XX" fields has been protected when rule matching on regexp "5\d{2}" i } )->store; - my $expected_record = build_record([ + my $expected_record = build_record( + [ # "250" field has been appended - [ '250', 'a', '256 bottles of beer on the wall' ], # incoming - [ '250', 'a', '251 bottles of beer on the wall' ], # incoming - # "500" field has retained its original value - [ '500', 'a', 'One bottle of beer in the fridge' ], # original - ]); + [ '250', 'a', '256 bottles of beer on the wall' ], # incoming + [ '250', 'a', '251 bottles of beer on the wall' ], # incoming + # "500" field has retained its original value + [ '500', 'a', 'One bottle of beer in the fridge' ], # original + ] + ); - my $merged_record = Koha::MarcOverlayRules->merge_records($orig_record, $incoming_record, { 'source' => 'test' }); + my $merged_record = Koha::MarcOverlayRules->merge_records( $orig_record, $incoming_record, { 'source' => 'test' } ); is( $merged_record->as_formatted, @@ -680,7 +721,7 @@ subtest '"5XX" fields has been protected when rule matching on regexp "5\d{2}" i 'Fields are erased by incoming record but 500 is protected and 501 is not added' ); -}; + }; $skip_all_rule->delete(); @@ -933,73 +974,76 @@ subtest 'Module filter precedence tests' => sub { subtest 'An exception is thrown when append = 1, remove = 0 is set for control field rule' => sub { plan tests => 2; my $exception = try { - Koha::MarcOverlayRules->validate({ - 'tag' => '008', - 'append' => 1, - 'remove' => 0, - }); - } - catch { + Koha::MarcOverlayRules->validate( + { + 'tag' => '008', + 'append' => 1, + 'remove' => 0, + } + ); + } catch { return $_; }; - ok(defined $exception, "Exception was caught"); - ok($exception->isa('Koha::Exceptions::MarcOverlayRule::InvalidControlFieldActions'), "Exception is of correct class"); + ok( defined $exception, "Exception was caught" ); + ok( + $exception->isa('Koha::Exceptions::MarcOverlayRule::InvalidControlFieldActions'), + "Exception is of correct class" + ); }; subtest 'An exception is thrown when rule tag is set to invalid regexp' => sub { plan tests => 2; my $exception = try { - Koha::MarcOverlayRules->validate({ - 'tag' => '**' - }); - } - catch { + Koha::MarcOverlayRules->validate( { 'tag' => '**' } ); + } catch { return $_; }; - ok(defined $exception, "Exception was caught"); - ok($exception->isa('Koha::Exceptions::MarcOverlayRule::InvalidTagRegExp'), "Exception is of correct class"); + ok( defined $exception, "Exception was caught" ); + ok( $exception->isa('Koha::Exceptions::MarcOverlayRule::InvalidTagRegExp'), "Exception is of correct class" ); }; - subtest 'context option in ModBiblio is handled correctly' => sub { plan tests => 2; $rule->set( { - tag => '250', - module => 'source', - filter => '*', - 'add' => 0, + tag => '250', + module => 'source', + filter => '*', + 'add' => 0, 'append' => 0, 'remove' => 0, 'delete' => 0, } )->store(); - my ($biblionumber, $biblioitemnumber) = AddBiblio($orig_record, ''); + my ( $biblionumber, $biblioitemnumber ) = AddBiblio( $orig_record, '' ); # Since marc merc rules are not run on save, only update # saved record should be identical to orig_record - my $biblio = Koha::Biblios->find($biblionumber); + my $biblio = Koha::Biblios->find($biblionumber); my $saved_record = $biblio->metadata->record; my @all_fields = $saved_record->fields(); + # Koha also adds 999c field, therefore 4 not 3 - my $expected_record = build_record([ + my $expected_record = build_record( + [ # "250" field has been appended [ '250', 'a', '250 bottles of beer on the wall' ], # original [ '250', 'a', '256 bottles of beer on the wall' ], # original [ '500', 'a', 'One bottle of beer in the fridge' ], # original [ '999', 'c', $biblionumber, 'd', $biblioitemnumber ], # created by AddBiblio - ]); + ] + ); # Remove timestamp from saved record when comparing $saved_record->delete_fields( $saved_record->field('005') ); # Make sure leader is equal after AddBiblio - $expected_record->leader($saved_record->leader()); + $expected_record->leader( $saved_record->leader() ); is( $saved_record->as_formatted, @@ -1007,29 +1051,32 @@ subtest 'context option in ModBiblio is handled correctly' => sub { ); $saved_record->append_fields( - MARC::Field->new('250', '', '', 'a' => '251 bottles of beer on the wall'), # Appended - MARC::Field->new('500', '', '', 'a' => 'One cold bottle of beer in the fridge'), # Appended + MARC::Field->new( '250', '', '', 'a' => '251 bottles of beer on the wall' ), # Appended + MARC::Field->new( '500', '', '', 'a' => 'One cold bottle of beer in the fridge' ), # Appended ); - ModBiblio($saved_record, $biblionumber, '', { overlay_context => { 'source' => 'test' } }); + ModBiblio( $saved_record, $biblionumber, '', { overlay_context => { 'source' => 'test' } } ); my $updated_record = $biblio->get_from_storage->metadata->record; - $expected_record = build_record([ + $expected_record = build_record( + [ # "250" field has been protected [ '250', 'a', '250 bottles of beer on the wall' ], [ '250', 'a', '256 bottles of beer on the wall' ], [ '500', 'a', 'One bottle of beer in the fridge' ], + # "500" field has been appended [ '500', 'a', 'One cold bottle of beer in the fridge' ], [ '999', 'c', $biblionumber, 'd', $biblioitemnumber ], # created by AddBiblio - ]); + ] + ); # Remove timestamp from saved record when comparing $updated_record->delete_fields( $updated_record->field('005') ); # Make sure leader is equal after ModBiblio - $expected_record->leader($updated_record->leader()); + $expected_record->leader( $updated_record->leader() ); is( $updated_record->as_formatted, diff --git a/t/db_dependent/Biblio/ModBiblioMarc.t b/t/db_dependent/Biblio/ModBiblioMarc.t index a1fb6cf596..00799add0f 100755 --- a/t/db_dependent/Biblio/ModBiblioMarc.t +++ b/t/db_dependent/Biblio/ModBiblioMarc.t @@ -42,18 +42,18 @@ subtest "Check MARC field length calculation" => sub { MARC::Field->new( '100', '', '', a => 'My title' ), ); - is( $record->leader, ' 'x24, 'No leader lengths' ); + is( $record->leader, ' ' x 24, 'No leader lengths' ); C4::Biblio::ModBiblioMarc( $record, $biblio->biblionumber ); my $savedrec = $biblio->metadata->record; - like( substr($savedrec->leader,0,5), qr/^\d{5}$/, 'Record length found' ); - like( substr($savedrec->leader,12,5), qr/^\d{5}$/, 'Base address found' ); + like( substr( $savedrec->leader, 0, 5 ), qr/^\d{5}$/, 'Record length found' ); + like( substr( $savedrec->leader, 12, 5 ), qr/^\d{5}$/, 'Base address found' ); }; subtest "StripWhitespaceChars tests" => sub { plan tests => 4; - t::lib::Mocks::mock_preference('marcflavour', 'MARC21'); - t::lib::Mocks::mock_preference('StripWhitespaceChars', 0); + t::lib::Mocks::mock_preference( 'marcflavour', 'MARC21' ); + t::lib::Mocks::mock_preference( 'StripWhitespaceChars', 0 ); my $biblio = t::lib::TestBuilder->new->build_sample_biblio; my $record = MARC::Record->new; @@ -67,15 +67,18 @@ subtest "StripWhitespaceChars tests" => sub { C4::Biblio::ModBiblioMarc( $record, $biblio->biblionumber ); $biblio = Koha::Biblios->find( $biblio->biblionumber ); - my $savedrec = $biblio->metadata->record; + my $savedrec = $biblio->metadata->record; my $savedtitle = $savedrec->title; - is( $savedtitle, " My\ntitle\n", "Title still has whitespace characters because StripWhitespaceChars is disabled" ); + is( + $savedtitle, " My\ntitle\n", + "Title still has whitespace characters because StripWhitespaceChars is disabled" + ); - t::lib::Mocks::mock_preference('StripWhitespaceChars', 1); + t::lib::Mocks::mock_preference( 'StripWhitespaceChars', 1 ); C4::Biblio::ModBiblioMarc( $record, $biblio->biblionumber ); $biblio = Koha::Biblios->find( $biblio->biblionumber ); - my $amendedrec = $biblio->metadata->record; + my $amendedrec = $biblio->metadata->record; my $amendedtitle = $amendedrec->title; is( $amendedtitle, "My title", "Whitespace characters removed from title because StripWhitespaceChars is enabled" ); diff --git a/t/db_dependent/Biblio/TransformHtmlToMarc.t b/t/db_dependent/Biblio/TransformHtmlToMarc.t index 0d54748031..4b5cb7e6d3 100755 --- a/t/db_dependent/Biblio/TransformHtmlToMarc.t +++ b/t/db_dependent/Biblio/TransformHtmlToMarc.t @@ -11,66 +11,76 @@ use Koha::MarcSubfieldStructures; use C4::Biblio qw( GetMarcFromKohaField TransformHtmlToMarc ); our ( $biblionumbertagfield, $biblionumbertagsubfield ); -my $schema = Koha::Database->new->schema; +my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; # Move field for biblionumber to imaginary 399 -Koha::MarcSubfieldStructures->search({ frameworkcode => '', kohafield => 'biblio.biblionumber' })->delete; -Koha::MarcSubfieldStructures->search({ frameworkcode => '', tagfield => '399', tagsubfield => 'a' })->delete; -Koha::MarcSubfieldStructure->new({ frameworkcode => '', tagfield => '399', tagsubfield => 'a', kohafield => "biblio.biblionumber" })->store; -Koha::Caches->get_instance->clear_from_cache( "MarcSubfieldStructure-" ); -( $biblionumbertagfield, $biblionumbertagsubfield ) = C4::Biblio::GetMarcFromKohaField( "biblio.biblionumber" ); +Koha::MarcSubfieldStructures->search( { frameworkcode => '', kohafield => 'biblio.biblionumber' } )->delete; +Koha::MarcSubfieldStructures->search( { frameworkcode => '', tagfield => '399', tagsubfield => 'a' } )->delete; +Koha::MarcSubfieldStructure->new( + { frameworkcode => '', tagfield => '399', tagsubfield => 'a', kohafield => "biblio.biblionumber" } )->store; +Koha::Caches->get_instance->clear_from_cache("MarcSubfieldStructure-"); +( $biblionumbertagfield, $biblionumbertagsubfield ) = C4::Biblio::GetMarcFromKohaField("biblio.biblionumber"); subtest 'Biblio record' => sub { plan tests => 20; my $leader = '00203nam a2200097 4500'; my $input = CGI->new; - $input->param( -name => 'biblionumber', -value => '42' ); - $input->param( -name => 'tag_000_indicator1_570367553534', -value => '' ); - $input->param( -name => 'tag_000_indicator2_570367553534', -value => '' ); - $input->param( -name => 'tag_000_code_00_570367_810561', -value => '' ); - $input->param( -name => 'tag_000_subfield_00_570367_810561', -value => $leader ); - $input->param( -name => 'tag_010_indicator1_493056', -value => '' ); - $input->param( -name => 'tag_010_indicator2_493056', -value => '' ); - $input->param( -name => 'tag_010_code_a_493056_296409', -value => 'a' ); - $input->param( -name => 'tag_010_subfield_a_493056_296409', -value => Encode::encode( 'utf-8', "first isbn é" ) ); - $input->param( -name => 'tag_010_indicator1_49305613979', -value => '' ); - $input->param( -name => 'tag_010_indicator2_49305613979', -value => '' ); - $input->param( -name => 'tag_010_code_a_493056_29640913979', -value => 'a' ); - $input->param( -name => 'tag_010_subfield_a_493056_29640913979', -value => Encode::encode( 'utf-8', "second isbn à" ) ); # 2 010 fields - $input->param( -name => 'tag_100_indicator1_588794844868', -value => '' ); - $input->param( -name => 'tag_100_indicator2_588794844868', -value => '' ); - $input->param( -name => 'tag_100_code_a_588794_15537', -value => 'a' ); - $input->param( -name => 'tag_100_subfield_a_588794_15537', -value => '20160112d u||y0frey5050 ba' ); - $input->param( -name => 'tag_200_indicator1_593269251146', -value => '' ); - $input->param( -name => 'tag_200_indicator2_593269251146', -value => '' ); - $input->param( -name => 'tag_200_code_a_593269_944056', -value => 'a' ); - $input->param( -name => 'tag_200_subfield_a_593269_944056', -value => 'first title' ); # 2 200$a in the same field - $input->param( -name => 'tag_200_code_a_593269_94405618065', -value => 'a' ); - $input->param( -name => 'tag_200_subfield_a_593269_94405618065', -value => 'second title' ); - $input->param( -name => 'tag_200_code_b_593269_250538', -value => 'b' ); - $input->param( -name => 'tag_200_subfield_b_593269_250538', -value => 'DVD' ); - $input->param( -name => 'tag_200_code_f_593269_445603', -value => 'f' ); - $input->param( -name => 'tag_200_subfield_f_593269_445603', -value => 'author' ); - $input->param( -name => 'tag_200_code_h_593269_616594', -value => 'h' ); # Empty field - $input->param( -name => 'tag_200_subfield_h_593269_616594', -value => '' ); + $input->param( -name => 'biblionumber', -value => '42' ); + $input->param( -name => 'tag_000_indicator1_570367553534', -value => '' ); + $input->param( -name => 'tag_000_indicator2_570367553534', -value => '' ); + $input->param( -name => 'tag_000_code_00_570367_810561', -value => '' ); + $input->param( -name => 'tag_000_subfield_00_570367_810561', -value => $leader ); + $input->param( -name => 'tag_010_indicator1_493056', -value => '' ); + $input->param( -name => 'tag_010_indicator2_493056', -value => '' ); + $input->param( -name => 'tag_010_code_a_493056_296409', -value => 'a' ); + $input->param( -name => 'tag_010_subfield_a_493056_296409', -value => Encode::encode( 'utf-8', "first isbn é" ) ); + $input->param( -name => 'tag_010_indicator1_49305613979', -value => '' ); + $input->param( -name => 'tag_010_indicator2_49305613979', -value => '' ); + $input->param( -name => 'tag_010_code_a_493056_29640913979', -value => 'a' ); + $input->param( + -name => 'tag_010_subfield_a_493056_29640913979', + -value => Encode::encode( 'utf-8', "second isbn à" ) + ); # 2 010 fields + $input->param( -name => 'tag_100_indicator1_588794844868', -value => '' ); + $input->param( -name => 'tag_100_indicator2_588794844868', -value => '' ); + $input->param( -name => 'tag_100_code_a_588794_15537', -value => 'a' ); + $input->param( -name => 'tag_100_subfield_a_588794_15537', -value => '20160112d u||y0frey5050 ba' ); + $input->param( -name => 'tag_200_indicator1_593269251146', -value => '' ); + $input->param( -name => 'tag_200_indicator2_593269251146', -value => '' ); + $input->param( -name => 'tag_200_code_a_593269_944056', -value => 'a' ); + $input->param( -name => 'tag_200_subfield_a_593269_944056', -value => 'first title' ); # 2 200$a in the same field + $input->param( -name => 'tag_200_code_a_593269_94405618065', -value => 'a' ); + $input->param( -name => 'tag_200_subfield_a_593269_94405618065', -value => 'second title' ); + $input->param( -name => 'tag_200_code_b_593269_250538', -value => 'b' ); + $input->param( -name => 'tag_200_subfield_b_593269_250538', -value => 'DVD' ); + $input->param( -name => 'tag_200_code_f_593269_445603', -value => 'f' ); + $input->param( -name => 'tag_200_subfield_f_593269_445603', -value => 'author' ); + $input->param( -name => 'tag_200_code_h_593269_616594', -value => 'h' ); # Empty field + $input->param( -name => 'tag_200_subfield_h_593269_616594', -value => '' ); # Add a field 390 before our 399 $input->param( -name => "tag_390_indicator1_123", -value => "" ); $input->param( -name => "tag_390_indicator2_123", -value => "" ); - $input->param( -name => "tag_390_code_a_123", -value => 'a' ); + $input->param( -name => "tag_390_code_a_123", -value => 'a' ); $input->param( -name => "tag_390_subfield_a_123", -value => '390a' ); # Our imaginary biblionumber field in 399 $input->param( -name => "tag_${biblionumbertagfield}_indicator1_588794844868", -value => "" ); $input->param( -name => "tag_${biblionumbertagfield}_indicator2_588794844868", -value => "" ); - $input->param( -name => "tag_${biblionumbertagfield}_code_${biblionumbertagsubfield}_588794_784323", -value => $biblionumbertagsubfield ); - $input->param( -name => "tag_${biblionumbertagfield}_subfield_${biblionumbertagsubfield}_588794_784323", -value => $biblionumbertagfield ); + $input->param( + -name => "tag_${biblionumbertagfield}_code_${biblionumbertagsubfield}_588794_784323", + -value => $biblionumbertagsubfield + ); + $input->param( + -name => "tag_${biblionumbertagfield}_subfield_${biblionumbertagsubfield}_588794_784323", + -value => $biblionumbertagfield + ); # A field (490) after 399 $input->param( -name => "tag_490_indicator1_1123", -value => "" ); $input->param( -name => "tag_490_indicator2_1123", -value => "" ); - $input->param( -name => "tag_490_code_b_1123", -value => 'b' ); + $input->param( -name => "tag_490_code_b_1123", -value => 'b' ); $input->param( -name => "tag_490_subfield_b_1123", -value => '490b' ); # A field (900) after 490 @@ -79,11 +89,12 @@ subtest 'Biblio record' => sub { $input->param( -name => "tag_900_code_a_1123", -value => 'a' ); $input->param( -name => "tag_900_subfield_a_1123", -value => "This string has bad \x{1B}characters in it" ); - my $record = C4::Biblio::TransformHtmlToMarc($input, 1); + my $record = C4::Biblio::TransformHtmlToMarc( $input, 1 ); my @all_fields = $record->fields; is( @all_fields, 8, 'The record should have been created with 8 fields' ); - # biblionumber + 2x010 + 100 + 200 + 390 + 490 + + # biblionumber + 2x010 + 100 + 200 + 390 + 490 my @fields_010 = $record->field('010'); is( @fields_010, 2, 'The record should have been created with 2 010' ); my @fields_100 = $record->field('100'); @@ -96,7 +107,10 @@ subtest 'Biblio record' => sub { my @subfields_200_a = $record->subfield( 200, 'a' ); is( @subfields_200_a, 2, 'The record should have been created with 2 200$a' ); - is_deeply( \@subfields_200_a, [ 'first title', 'second title' ], 'The 2 titles should have been kept in the correct order' ); + is_deeply( + \@subfields_200_a, [ 'first title', 'second title' ], + 'The 2 titles should have been kept in the correct order' + ); my @fields_900 = $record->field('900'); is( @fields_900, 1, 'The record should have been created with 1 900' ); @@ -111,13 +125,13 @@ subtest 'Biblio record' => sub { is( $record->leader, $leader, 'The leader should have been kept' ); # Check the order of some fields - is( $all_fields[0]->tag, '010', 'First field expected 010' ); - is( $all_fields[1]->tag, '010', 'Second field also 010' ); - is( $all_fields[2]->tag, '100', 'Third field is 100' ); - is( $all_fields[3]->tag, '200', 'Fourth field is 200' ); - is( $all_fields[4]->tag, '390', 'Fifth field is 390' ); - is( $all_fields[5]->subfield('a'), 42, 'Sixth field contains bibnumber' ); - is( $all_fields[6]->tag, '490', 'Last field is 490' ); + is( $all_fields[0]->tag, '010', 'First field expected 010' ); + is( $all_fields[1]->tag, '010', 'Second field also 010' ); + is( $all_fields[2]->tag, '100', 'Third field is 100' ); + is( $all_fields[3]->tag, '200', 'Fourth field is 200' ); + is( $all_fields[4]->tag, '390', 'Fifth field is 390' ); + is( $all_fields[5]->subfield('a'), 42, 'Sixth field contains bibnumber' ); + is( $all_fields[6]->tag, '490', 'Last field is 490' ); my $new_record = eval { MARC::Record::new_from_xml( $record->as_xml(), 'UTF-8' ); }; my $record_error = $@; @@ -129,22 +143,28 @@ subtest 'Add authority record' => sub { plan tests => 1; my $input = CGI->new; - $input->param( -name => 'tag_200_indicator1_906288', -value => '' ); - $input->param( -name => 'tag_200_indicator2_906288', -value => '' ); - $input->param( -name => 'tag_200_code_a_906288_722171', -value => 'a' ); - $input->param( -name => 'tag_200_subfield_a_906288_722171', -value => 'a 200$a' ); - $input->param( -name => 'tag_200_code_b_906288_611549', -value => 'b' ); - $input->param( -name => 'tag_200_subfield_b_906288_611549', -value => 'a 200$b' ); - $input->param( -name => "tag_${biblionumbertagfield}_indicator1_198510", -value => "" ); - $input->param( -name => "tag_${biblionumbertagfield}_indicator2_198510", -value => "" ); - $input->param( -name => "tag_${biblionumbertagfield}_code_${biblionumbertagsubfield}_198510_886205", -value => $biblionumbertagsubfield ); - $input->param( -name => "tag_${biblionumbertagfield}_subfield_${biblionumbertagsubfield}_198510_886205", -value => "a biblionumber which is not a biblionumber" ); + $input->param( -name => 'tag_200_indicator1_906288', -value => '' ); + $input->param( -name => 'tag_200_indicator2_906288', -value => '' ); + $input->param( -name => 'tag_200_code_a_906288_722171', -value => 'a' ); + $input->param( -name => 'tag_200_subfield_a_906288_722171', -value => 'a 200$a' ); + $input->param( -name => 'tag_200_code_b_906288_611549', -value => 'b' ); + $input->param( -name => 'tag_200_subfield_b_906288_611549', -value => 'a 200$b' ); + $input->param( -name => "tag_${biblionumbertagfield}_indicator1_198510", -value => "" ); + $input->param( -name => "tag_${biblionumbertagfield}_indicator2_198510", -value => "" ); + $input->param( + -name => "tag_${biblionumbertagfield}_code_${biblionumbertagsubfield}_198510_886205", + -value => $biblionumbertagsubfield + ); + $input->param( + -name => "tag_${biblionumbertagfield}_subfield_${biblionumbertagsubfield}_198510_886205", + -value => "a biblionumber which is not a biblionumber" + ); - my $record = C4::Biblio::TransformHtmlToMarc($input, 0); + my $record = C4::Biblio::TransformHtmlToMarc( $input, 0 ); my @subfields_biblionumber = $record->subfield( $biblionumbertagfield, $biblionumbertagsubfield ); is( @subfields_biblionumber, 1, 'The record should contain the field which are mapped to biblio.biblionumber' ); }; -Koha::Caches->get_instance->clear_from_cache( "MarcSubfieldStructure-" ); +Koha::Caches->get_instance->clear_from_cache("MarcSubfieldStructure-"); $schema->storage->txn_rollback; diff --git a/t/db_dependent/Biblio/TransformKohaToMarc.t b/t/db_dependent/Biblio/TransformKohaToMarc.t index d2efaa6aa9..d3fd9f9d24 100755 --- a/t/db_dependent/Biblio/TransformKohaToMarc.t +++ b/t/db_dependent/Biblio/TransformKohaToMarc.t @@ -10,34 +10,44 @@ use Koha::Caches; use Koha::MarcSubfieldStructures; use C4::Biblio qw( TransformKohaToMarc ); -my $schema = Koha::Database->new->schema; +my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; our $builder = t::lib::TestBuilder->new; # Create/overwrite some Koha to MARC mappings in default framework -Koha::MarcSubfieldStructures->search({ frameworkcode => '', tagfield => '300', tagsubfield => 'a' })->delete; -Koha::MarcSubfieldStructure->new({ frameworkcode => '', tagfield => '300', tagsubfield => 'a', kohafield => "mytable.nicepages" })->store; -Koha::MarcSubfieldStructures->search({ frameworkcode => '', tagfield => '300', tagsubfield => 'b' })->delete; -Koha::MarcSubfieldStructure->new({ frameworkcode => '', tagfield => '300', tagsubfield => 'b', kohafield => "mytable2.goodillustrations", repeatable => 1 })->store; -Koha::Caches->get_instance->clear_from_cache( "MarcSubfieldStructure-" ); +Koha::MarcSubfieldStructures->search( { frameworkcode => '', tagfield => '300', tagsubfield => 'a' } )->delete; +Koha::MarcSubfieldStructure->new( + { frameworkcode => '', tagfield => '300', tagsubfield => 'a', kohafield => "mytable.nicepages" } )->store; +Koha::MarcSubfieldStructures->search( { frameworkcode => '', tagfield => '300', tagsubfield => 'b' } )->delete; +Koha::MarcSubfieldStructure->new( + { + frameworkcode => '', tagfield => '300', tagsubfield => 'b', kohafield => "mytable2.goodillustrations", + repeatable => 1 + } +)->store; +Koha::Caches->get_instance->clear_from_cache("MarcSubfieldStructure-"); -my $record = C4::Biblio::TransformKohaToMarc({ - "mytable2.goodillustrations" => "Other physical details", # 300$b - "mytable.nicepages" => "Extent", # 300$a -}); +my $record = C4::Biblio::TransformKohaToMarc( + { + "mytable2.goodillustrations" => "Other physical details", # 300$b + "mytable.nicepages" => "Extent", # 300$a + } +); my @subfields = $record->field('300')->subfields(); -is_deeply( \@subfields, [ - [ +is_deeply( + \@subfields, + [ + [ 'a', 'Extent' - ], - [ + ], + [ 'b', 'Other physical details' - ], ], -'TransformKohaToMarc should return sorted subfields (regression test for bug 12343)' ); - + ], + 'TransformKohaToMarc should return sorted subfields (regression test for bug 12343)' +); # Now test multiple mappings per kohafield too subtest "Multiple Koha to MARC mappings (BZ 10306)" => sub { @@ -45,73 +55,94 @@ subtest "Multiple Koha to MARC mappings (BZ 10306)" => sub { # Add 260d mapping so that 300a and 260d both map to mytable.nicepages # Add 260e to test not-repeatable behavior - Koha::MarcSubfieldStructures->search({ frameworkcode => '', tagfield => '260' })->delete; - Koha::MarcSubfieldStructure->new({ frameworkcode => '', tagfield => '260', tagsubfield => 'd', kohafield => "mytable.nicepages" })->store; - Koha::MarcSubfieldStructure->new({ frameworkcode => '', tagfield => '260', tagsubfield => 'e', kohafield => "mytable.unrepeatable", repeatable => 0 })->store; - Koha::Caches->get_instance->clear_from_cache( "MarcSubfieldStructure-" ); + Koha::MarcSubfieldStructures->search( { frameworkcode => '', tagfield => '260' } )->delete; + Koha::MarcSubfieldStructure->new( + { frameworkcode => '', tagfield => '260', tagsubfield => 'd', kohafield => "mytable.nicepages" } )->store; + Koha::MarcSubfieldStructure->new( + { + frameworkcode => '', tagfield => '260', tagsubfield => 'e', kohafield => "mytable.unrepeatable", + repeatable => 0 + } + )->store; + Koha::Caches->get_instance->clear_from_cache("MarcSubfieldStructure-"); # Include two values in goodillustrations too: should result in two # subfields. But unrepeatable should result in one field. - my $record = C4::Biblio::TransformKohaToMarc({ - "mytable2.goodillustrations" => "good | better", - "mytable.nicepages" => "nice", - "mytable.unrepeatable" => "A | B", - }); - is( $record->subfield('260','d'), "nice", "Check 260d" ); - is( $record->subfield('260','e'), "A | B", "Check 260e" ); - is( $record->subfield('300','a'), "nice", "Check 300a" ); - is( $record->subfield('300','b'), "good", "Check first 300b" ); - is( ($record->field('300')->subfield('b'))[1], "better", - "Check second 300b" ); + my $record = C4::Biblio::TransformKohaToMarc( + { + "mytable2.goodillustrations" => "good | better", + "mytable.nicepages" => "nice", + "mytable.unrepeatable" => "A | B", + } + ); + is( $record->subfield( '260', 'd' ), "nice", "Check 260d" ); + is( $record->subfield( '260', 'e' ), "A | B", "Check 260e" ); + is( $record->subfield( '300', 'a' ), "nice", "Check 300a" ); + is( $record->subfield( '300', 'b' ), "good", "Check first 300b" ); + is( + ( $record->field('300')->subfield('b') )[1], "better", + "Check second 300b" + ); }; subtest "Working with control fields" => sub { plan tests => 1; # Map a controlfield to 'fullcontrol' - Koha::MarcSubfieldStructures->search({ frameworkcode => '', tagfield => '001', tagsubfield => '@' })->delete; - Koha::MarcSubfieldStructure->new({ frameworkcode => '', tagfield => '001', tagsubfield => '@', kohafield => "fullcontrol" })->store; - Koha::Caches->get_instance->clear_from_cache( "MarcSubfieldStructure-" ); + Koha::MarcSubfieldStructures->search( { frameworkcode => '', tagfield => '001', tagsubfield => '@' } )->delete; + Koha::MarcSubfieldStructure->new( + { frameworkcode => '', tagfield => '001', tagsubfield => '@', kohafield => "fullcontrol" } )->store; + Koha::Caches->get_instance->clear_from_cache("MarcSubfieldStructure-"); - my @cols = ( notexist => 'i am not here', fullcontrol => 'all' ); - my $record = C4::Biblio::TransformKohaToMarc( { @cols } ); + my @cols = ( notexist => 'i am not here', fullcontrol => 'all' ); + my $record = C4::Biblio::TransformKohaToMarc( {@cols} ); is( $record->field('001')->data, 'all', 'Verify field 001' ); }; subtest "Add tests for _check_split" => sub { plan tests => 8; - Koha::MarcSubfieldStructures->search({ frameworkcode => '', tagfield => '952', tagsubfield => 'a' })->delete; - Koha::MarcSubfieldStructure->new({ frameworkcode => '', tagfield => '952', tagsubfield => 'a', kohafield => 'items.fld1' })->store; - Koha::MarcSubfieldStructures->search({ frameworkcode => '', tagfield => '952', tagsubfield => 'b' })->delete; - Koha::MarcSubfieldStructure->new({ frameworkcode => '', tagfield => '952', tagsubfield => 'b', kohafield => 'items.fld1' })->store; - Koha::Caches->get_instance->clear_from_cache( "MarcSubfieldStructure-" ); + Koha::MarcSubfieldStructures->search( { frameworkcode => '', tagfield => '952', tagsubfield => 'a' } )->delete; + Koha::MarcSubfieldStructure->new( + { frameworkcode => '', tagfield => '952', tagsubfield => 'a', kohafield => 'items.fld1' } )->store; + Koha::MarcSubfieldStructures->search( { frameworkcode => '', tagfield => '952', tagsubfield => 'b' } )->delete; + Koha::MarcSubfieldStructure->new( + { frameworkcode => '', tagfield => '952', tagsubfield => 'b', kohafield => 'items.fld1' } )->store; + Koha::Caches->get_instance->clear_from_cache("MarcSubfieldStructure-"); + # add 952a repeatable in another framework - my $fw = $builder->build({ source => 'BiblioFramework' })->{frameworkcode}; - Koha::MarcSubfieldStructure->new({ frameworkcode => $fw, tagfield => '952', tagsubfield => 'a', repeatable => 1, kohafield => 'items.fld1' })->store; + my $fw = $builder->build( { source => 'BiblioFramework' } )->{frameworkcode}; + Koha::MarcSubfieldStructure->new( + { frameworkcode => $fw, tagfield => '952', tagsubfield => 'a', repeatable => 1, kohafield => 'items.fld1' } ) + ->store; # Test single value in fld1 - my @cols = ( 'items.fld1' => '01' ); - my $record = C4::Biblio::TransformKohaToMarc( { @cols }, { no_split => 1 } ); + my @cols = ( 'items.fld1' => '01' ); + my $record = C4::Biblio::TransformKohaToMarc( {@cols}, { no_split => 1 } ); is( $record->subfield( '952', 'a' ), '01', 'Check single in 952a' ); is( $record->subfield( '952', 'b' ), '01', 'Check single in 952b' ); # Test glued (composite) value in fld1 with no_split parameter - @cols = ( 'items.fld1' => '01 | 02' ); - $record = C4::Biblio::TransformKohaToMarc( { @cols }, { no_split => 1 } ); + @cols = ( 'items.fld1' => '01 | 02' ); + $record = C4::Biblio::TransformKohaToMarc( {@cols}, { no_split => 1 } ); is( $record->subfield( '952', 'a' ), '01 | 02', 'Check composite in 952a' ); is( $record->subfield( '952', 'b' ), '01 | 02', 'Check composite in 952b' ); + # Test without no_split (subfield is not repeatable) - $record = C4::Biblio::TransformKohaToMarc( { @cols } ); + $record = C4::Biblio::TransformKohaToMarc( {@cols} ); is( $record->subfield( '952', 'a' ), '01 | 02', 'Check composite in 952a' ); + # Test with other framework (repeatable) - Koha::Caches->get_instance->clear_from_cache( "MarcSubfieldStructure-". $fw ); - $record = C4::Biblio::TransformKohaToMarc( { @cols }, { framework => $fw } ); - is( ($record->subfield( '952', 'a' ))[0], '01', "Framework $fw first 952a" ); - is( ($record->subfield( '952', 'a' ))[1], '02', "Framework $fw second 952a" ); - is( ref(Koha::Caches->get_instance->get_from_cache( "MarcSubfieldStructure-". $fw )), 'HASH', 'We did hit the cache' ); + Koha::Caches->get_instance->clear_from_cache( "MarcSubfieldStructure-" . $fw ); + $record = C4::Biblio::TransformKohaToMarc( {@cols}, { framework => $fw } ); + is( ( $record->subfield( '952', 'a' ) )[0], '01', "Framework $fw first 952a" ); + is( ( $record->subfield( '952', 'a' ) )[1], '02', "Framework $fw second 952a" ); + is( + ref( Koha::Caches->get_instance->get_from_cache( "MarcSubfieldStructure-" . $fw ) ), 'HASH', + 'We did hit the cache' + ); }; # Cleanup -Koha::Caches->get_instance->clear_from_cache( "MarcSubfieldStructure-" ); +Koha::Caches->get_instance->clear_from_cache("MarcSubfieldStructure-"); $schema->storage->txn_rollback; diff --git a/t/db_dependent/Biblio/TransformMarcToKoha.t b/t/db_dependent/Biblio/TransformMarcToKoha.t index ab16f52d30..b85dd1525d 100755 --- a/t/db_dependent/Biblio/TransformMarcToKoha.t +++ b/t/db_dependent/Biblio/TransformMarcToKoha.t @@ -30,37 +30,45 @@ use Koha::Caches; use Koha::MarcSubfieldStructures; use C4::Biblio qw( TransformMarcToKoha ); -my $schema = Koha::Database->new->schema; +my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; # Create a few mappings # Note: TransformMarcToKoha wants a table name (biblio, biblioitems or items) -Koha::MarcSubfieldStructures->search({ frameworkcode => '', tagfield => [ '300', '500' ] })->delete; -Koha::MarcSubfieldStructure->new({ frameworkcode => '', tagfield => '300', tagsubfield => 'a', kohafield => 'biblio.field1' })->store; -Koha::MarcSubfieldStructure->new({ frameworkcode => '', tagfield => '300', tagsubfield => 'b', kohafield => 'biblio.field2' })->store; -Koha::MarcSubfieldStructure->new({ frameworkcode => '', tagfield => '500', tagsubfield => 'a', kohafield => 'biblio.field3' })->store; -Koha::Caches->get_instance->clear_from_cache( "MarcSubfieldStructure-" ); +Koha::MarcSubfieldStructures->search( { frameworkcode => '', tagfield => [ '300', '500' ] } )->delete; +Koha::MarcSubfieldStructure->new( + { frameworkcode => '', tagfield => '300', tagsubfield => 'a', kohafield => 'biblio.field1' } )->store; +Koha::MarcSubfieldStructure->new( + { frameworkcode => '', tagfield => '300', tagsubfield => 'b', kohafield => 'biblio.field2' } )->store; +Koha::MarcSubfieldStructure->new( + { frameworkcode => '', tagfield => '500', tagsubfield => 'a', kohafield => 'biblio.field3' } )->store; +Koha::Caches->get_instance->clear_from_cache("MarcSubfieldStructure-"); subtest 'Test a few mappings' => sub { plan tests => 6; my $marc = MARC::Record->new; $marc->append_fields( - MARC::Field->new( '300', '', '', a => 'a1', b => 'b1' ), - MARC::Field->new( '300', '', '', a => 'a2', b => 'b2' ), + MARC::Field->new( '300', '', '', a => 'a1', b => 'b1' ), + MARC::Field->new( '300', '', '', a => 'a2', b => 'b2' ), MARC::Field->new( '500', '', '', a => 'note1', a => 'note2' ), ); - my $result = C4::Biblio::TransformMarcToKoha({ record => $marc }); - # Note: TransformMarcToKoha stripped the table prefix biblio. - is( keys %{$result}, 3, 'Found all three mappings' ); - is( $result->{field1}, 'a1 | a2', 'Check field1 results' ); - is( $result->{field2}, 'b1 | b2', 'Check field2 results' ); + my $result = C4::Biblio::TransformMarcToKoha( { record => $marc } ); + + # Note: TransformMarcToKoha stripped the table prefix biblio. + is( keys %{$result}, 3, 'Found all three mappings' ); + is( $result->{field1}, 'a1 | a2', 'Check field1 results' ); + is( $result->{field2}, 'b1 | b2', 'Check field2 results' ); is( $result->{field3}, 'note1 | note2', 'Check field3 results' ); - is_deeply( C4::Biblio::TransformMarcToKoha({ record => $marc, kohafields => ['biblio.field1'] }), - {field1 => 'a1 | a2'}, 'TransformMarcToKoha returns biblio.field1 if kohafields specified'); - is_deeply( C4::Biblio::TransformMarcToKoha({ record => $marc, kohafields => ['field4'] }), - {} , 'TransformMarcToKoha returns empty hashref on unknown kohafields' ); + is_deeply( + C4::Biblio::TransformMarcToKoha( { record => $marc, kohafields => ['biblio.field1'] } ), + { field1 => 'a1 | a2' }, 'TransformMarcToKoha returns biblio.field1 if kohafields specified' + ); + is_deeply( + C4::Biblio::TransformMarcToKoha( { record => $marc, kohafields => ['field4'] } ), + {}, 'TransformMarcToKoha returns empty hashref on unknown kohafields' + ); }; @@ -68,74 +76,83 @@ subtest 'Multiple mappings for one kohafield' => sub { plan tests => 4; # Add another mapping to field1 - Koha::MarcSubfieldStructures->search({ frameworkcode => '', tagfield => '510' })->delete; - Koha::MarcSubfieldStructure->new({ frameworkcode => '', tagfield => '510', tagsubfield => 'a', kohafield => 'biblio.field1' })->store; - Koha::Caches->get_instance->clear_from_cache( "MarcSubfieldStructure-" ); + Koha::MarcSubfieldStructures->search( { frameworkcode => '', tagfield => '510' } )->delete; + Koha::MarcSubfieldStructure->new( + { frameworkcode => '', tagfield => '510', tagsubfield => 'a', kohafield => 'biblio.field1' } )->store; + Koha::Caches->get_instance->clear_from_cache("MarcSubfieldStructure-"); my $marc = MARC::Record->new; $marc->append_fields( MARC::Field->new( '300', '', '', a => '3a' ) ); - my $result = C4::Biblio::TransformMarcToKoha({ record => $marc }); + my $result = C4::Biblio::TransformMarcToKoha( { record => $marc } ); is_deeply( $result, { field1 => '3a' }, 'Simple start' ); $marc->append_fields( MARC::Field->new( '510', '', '', a => '' ) ); - $result = C4::Biblio::TransformMarcToKoha({ record => $marc }); + $result = C4::Biblio::TransformMarcToKoha( { record => $marc } ); is_deeply( $result, { field1 => '3a' }, 'An empty 510a makes no difference' ); $marc->append_fields( MARC::Field->new( '510', '', '', a => '51' ) ); - $result = C4::Biblio::TransformMarcToKoha({ record => $marc }); + $result = C4::Biblio::TransformMarcToKoha( { record => $marc } ); is_deeply( $result, { field1 => '3a | 51' }, 'Got 300a and 510a' ); - is_deeply( C4::Biblio::TransformMarcToKoha({ kohafields => ['biblio.field1'], record => $marc }), - { 'field1' => '3a | 51'}, 'TransformMarcToKoha returns biblio.field1 when kohafields specified' ); + is_deeply( + C4::Biblio::TransformMarcToKoha( { kohafields => ['biblio.field1'], record => $marc } ), + { 'field1' => '3a | 51' }, 'TransformMarcToKoha returns biblio.field1 when kohafields specified' + ); }; subtest 'Testing _adjust_pubyear' => sub { plan tests => 18; - is( C4::Biblio::_adjust_pubyear('2004 c2000 2007'), 2000, 'First cYEAR' ); - is( C4::Biblio::_adjust_pubyear('2004 2000 2007'), 2004, 'First year' ); - is( C4::Biblio::_adjust_pubyear('18xx 1900'), 1900, '1900 has priority over 18xx' ); - is( C4::Biblio::_adjust_pubyear('18xx'), 1800, '18xx on its own' ); - is( C4::Biblio::_adjust_pubyear('197X'), 1970, '197X on its own' ); - is( C4::Biblio::_adjust_pubyear('1...'), 1000, '1... on its own' ); - is( C4::Biblio::_adjust_pubyear('12?? 13xx'), 1200, '12?? first' ); - is( C4::Biblio::_adjust_pubyear('12? 1x'), 1200, '12? first' ); - is( C4::Biblio::_adjust_pubyear('198-'), 1980, '198-' ); - is( C4::Biblio::_adjust_pubyear('19--'), 1900, '19--' ); - is( C4::Biblio::_adjust_pubyear('19-'), 1900, '19-' ); - is( C4::Biblio::_adjust_pubyear('1-'), 1000, '1-' ); - is( C4::Biblio::_adjust_pubyear('2xxx'), 2000, '2xxx' ); - is( C4::Biblio::_adjust_pubyear('2xx'), 2000, '2xx' ); - is( C4::Biblio::_adjust_pubyear('2x'), 2000, '2x' ); - is( C4::Biblio::_adjust_pubyear('198-?'), 1980, '198-?' ); - is( C4::Biblio::_adjust_pubyear('1981-'), 1981, 'Date range returns first date' ); - is( C4::Biblio::_adjust_pubyear('broken'), undef, 'Non-matching data' ); + is( C4::Biblio::_adjust_pubyear('2004 c2000 2007'), 2000, 'First cYEAR' ); + is( C4::Biblio::_adjust_pubyear('2004 2000 2007'), 2004, 'First year' ); + is( C4::Biblio::_adjust_pubyear('18xx 1900'), 1900, '1900 has priority over 18xx' ); + is( C4::Biblio::_adjust_pubyear('18xx'), 1800, '18xx on its own' ); + is( C4::Biblio::_adjust_pubyear('197X'), 1970, '197X on its own' ); + is( C4::Biblio::_adjust_pubyear('1...'), 1000, '1... on its own' ); + is( C4::Biblio::_adjust_pubyear('12?? 13xx'), 1200, '12?? first' ); + is( C4::Biblio::_adjust_pubyear('12? 1x'), 1200, '12? first' ); + is( C4::Biblio::_adjust_pubyear('198-'), 1980, '198-' ); + is( C4::Biblio::_adjust_pubyear('19--'), 1900, '19--' ); + is( C4::Biblio::_adjust_pubyear('19-'), 1900, '19-' ); + is( C4::Biblio::_adjust_pubyear('1-'), 1000, '1-' ); + is( C4::Biblio::_adjust_pubyear('2xxx'), 2000, '2xxx' ); + is( C4::Biblio::_adjust_pubyear('2xx'), 2000, '2xx' ); + is( C4::Biblio::_adjust_pubyear('2x'), 2000, '2x' ); + is( C4::Biblio::_adjust_pubyear('198-?'), 1980, '198-?' ); + is( C4::Biblio::_adjust_pubyear('1981-'), 1981, 'Date range returns first date' ); + is( C4::Biblio::_adjust_pubyear('broken'), undef, 'Non-matching data' ); }; subtest 'Test repeatable subfields' => sub { plan tests => 5; # Make 510x repeatable and 510y not - Koha::MarcSubfieldStructures->search({ frameworkcode => '', tagfield => '510' })->delete; - Koha::MarcSubfieldStructure->new({ frameworkcode => '', tagfield => '510', tagsubfield => 'x', kohafield => 'items.test', repeatable => 1 })->store; - Koha::MarcSubfieldStructure->new({ frameworkcode => '', tagfield => '510', tagsubfield => 'y', kohafield => 'items.norepeat', repeatable => 0 })->store; - Koha::Caches->get_instance->clear_from_cache( "MarcSubfieldStructure-" ); - + Koha::MarcSubfieldStructures->search( { frameworkcode => '', tagfield => '510' } )->delete; + Koha::MarcSubfieldStructure->new( + { frameworkcode => '', tagfield => '510', tagsubfield => 'x', kohafield => 'items.test', repeatable => 1 } ) + ->store; + Koha::MarcSubfieldStructure->new( + { frameworkcode => '', tagfield => '510', tagsubfield => 'y', kohafield => 'items.norepeat', repeatable => 0 } ) + ->store; + Koha::Caches->get_instance->clear_from_cache("MarcSubfieldStructure-"); my $marc = MARC::Record->new; - $marc->append_fields( MARC::Field->new( '510', '', '', x => '1', x => '2', y => '3 | 4', y => '5' ) ); # actually, we should only have one $y (BZ 24652) - my $result = C4::Biblio::TransformMarcToKoha({ record => $marc }); - is( $result->{test}, '1 | 2', 'Check 510x for two values' ); + $marc->append_fields( MARC::Field->new( '510', '', '', x => '1', x => '2', y => '3 | 4', y => '5' ) ) + ; # actually, we should only have one $y (BZ 24652) + my $result = C4::Biblio::TransformMarcToKoha( { record => $marc } ); + is( $result->{test}, '1 | 2', 'Check 510x for two values' ); is( $result->{norepeat}, '3 | 4 | 5', 'Check 510y too' ); - Koha::MarcSubfieldStructure->new({ frameworkcode => '', tagfield => '510', tagsubfield => 'a', kohafield => 'biblio.field1' })->store; - Koha::Caches->get_instance->clear_from_cache( "MarcSubfieldStructure-" ); - $marc->append_fields( MARC::Field->new( '510', '', '', a => '1' ) ); # actually, we should only have one $y (BZ 24652) + Koha::MarcSubfieldStructure->new( + { frameworkcode => '', tagfield => '510', tagsubfield => 'a', kohafield => 'biblio.field1' } )->store; + Koha::Caches->get_instance->clear_from_cache("MarcSubfieldStructure-"); + $marc->append_fields( MARC::Field->new( '510', '', '', a => '1' ) ) + ; # actually, we should only have one $y (BZ 24652) - $result = C4::Biblio::TransformMarcToKoha({ record => $marc, limit_table => 'no_items' }); - is( $result->{test}, undef, 'Item field not returned when "no_items" passed' ); + $result = C4::Biblio::TransformMarcToKoha( { record => $marc, limit_table => 'no_items' } ); + is( $result->{test}, undef, 'Item field not returned when "no_items" passed' ); is( $result->{norepeat}, undef, 'Item field not returned when "no_items" passed' ); - is( $result->{field1}, 1, 'Biblio field returned when "no_items" passed' ); + is( $result->{field1}, 1, 'Biblio field returned when "no_items" passed' ); }; # Cleanup -Koha::Caches->get_instance->clear_from_cache( "MarcSubfieldStructure-" ); +Koha::Caches->get_instance->clear_from_cache("MarcSubfieldStructure-"); $schema->storage->txn_rollback; diff --git a/t/db_dependent/Biblio_holdsqueue.t b/t/db_dependent/Biblio_holdsqueue.t index 4c687a69ba..dc8824c6e8 100755 --- a/t/db_dependent/Biblio_holdsqueue.t +++ b/t/db_dependent/Biblio_holdsqueue.t @@ -25,7 +25,7 @@ use t::lib::TestBuilder; use Koha::Database; -my $schema = Koha::Database->new->schema; +my $schema = Koha::Database->new->schema; my $builder = t::lib::TestBuilder->new; subtest 'ModBiblio() + holds_queue update tests' => sub { @@ -39,22 +39,25 @@ subtest 'ModBiblio() + holds_queue update tests' => sub { t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 1 ); my $mock = Test::MockModule->new('Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue'); - $mock->mock( 'enqueue', sub { - my ( $self, $args ) = @_; - my ($package, $filename, $line) = caller; - is_deeply( - $args->{biblio_ids}, - [ $biblio->id ], - 'ModBiblio triggers a holds queue update for the related biblio' - ); - } ); + $mock->mock( + 'enqueue', + sub { + my ( $self, $args ) = @_; + my ( $package, $filename, $line ) = caller; + is_deeply( + $args->{biblio_ids}, + [ $biblio->id ], + 'ModBiblio triggers a holds queue update for the related biblio' + ); + } + ); # add a hold $builder->build_object( { class => 'Koha::Holds', value => { - biblionumber => $biblio->id, + biblionumber => $biblio->id, } } ); @@ -99,21 +102,24 @@ subtest 'DelBiblio + holds_queue update tests' => sub { my $biblio = $builder->build_sample_biblio; my $mock = Test::MockModule->new('Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue'); - $mock->mock( 'enqueue', sub { - my ( $self, $args ) = @_; - is_deeply( - $args->{biblio_ids}, - [ $biblio->id ], - 'DelBiblio triggers a holds queue update for the related biblio' - ); - } ); + $mock->mock( + 'enqueue', + sub { + my ( $self, $args ) = @_; + is_deeply( + $args->{biblio_ids}, + [ $biblio->id ], + 'DelBiblio triggers a holds queue update for the related biblio' + ); + } + ); # add a hold $builder->build_object( { class => 'Koha::Holds', value => { - biblionumber => $biblio->id, + biblionumber => $biblio->id, } } ); diff --git a/t/db_dependent/Breeding.t b/t/db_dependent/Breeding.t index c88763076b..531f1c233f 100755 --- a/t/db_dependent/Breeding.t +++ b/t/db_dependent/Breeding.t @@ -35,7 +35,7 @@ use C4::Breeding; use Koha::Database; use Koha::XSLT::Base; -my $schema = Koha::Database->new->schema; +my $schema = Koha::Database->new->schema; my $builder = t::lib::TestBuilder->new; $schema->storage->txn_begin; @@ -44,16 +44,19 @@ subtest '_build_query' => sub { plan tests => 14; test_build_translate_query(); }; + #Group 2: testing _create_connection (part of Z3950Search) subtest '_create_connection' => sub { plan tests => 5; test_create_connection(); }; + #Group 3: testing _do_xslt_proc (part of Z3950Search) subtest '_do_xslt_proc' => sub { plan tests => 6; test_do_xslt(); }; + #Group 4: testing _add_custom_field_rowdata (part of Z3950Search) subtest '_add_custom_field_rowdata' => sub { plan tests => 5; @@ -63,33 +66,42 @@ subtest '_add_custom_field_rowdata' => sub { subtest BreedingSearch => sub { plan tests => 5; - my $import_biblio_1 = $builder->build({ source => 'ImportBiblio', value => { - title => 'Unique title the first adventure', - author => 'Firstnamey Surnamey', - isbn => '1407239961' + my $import_biblio_1 = $builder->build( + { + source => 'ImportBiblio', + value => { + title => 'Unique title the first adventure', + author => 'Firstnamey Surnamey', + isbn => '1407239961' + } } - }); - my $import_biblio_2 = $builder->build({ source => 'ImportBiblio', value => { - title => 'Unique title the adventure continues', - author => 'Firstnamey Surnamey', - isbn => '9798200834976' + ); + my $import_biblio_2 = $builder->build( + { + source => 'ImportBiblio', + value => { + title => 'Unique title the adventure continues', + author => 'Firstnamey Surnamey', + isbn => '9798200834976' + } } - }); + ); - my ($count, @results) = C4::Breeding::BreedingSearch("Firstnamey Surnamey"); - is( $count, 2, "Author search returns two results"); + my ( $count, @results ) = C4::Breeding::BreedingSearch("Firstnamey Surnamey"); + is( $count, 2, "Author search returns two results" ); - ($count, @results) = C4::Breeding::BreedingSearch("first adventure"); - is( $count, 1, "Title search returns one result"); + ( $count, @results ) = C4::Breeding::BreedingSearch("first adventure"); + is( $count, 1, "Title search returns one result" ); - ($count, @results) = C4::Breeding::BreedingSearch("adventure continues"); - is( $count, 1, "Title search returns one result"); + ( $count, @results ) = C4::Breeding::BreedingSearch("adventure continues"); + is( $count, 1, "Title search returns one result" ); - ($count, @results) = C4::Breeding::BreedingSearch("9781407239965"); - is( $count, 1, "ISBN search matches normalized DB value"); + ( $count, @results ) = C4::Breeding::BreedingSearch("9781407239965"); + is( $count, 1, "ISBN search matches normalized DB value" ); + + ( $count, @results ) = C4::Breeding::BreedingSearch("9798200834976"); + is( $count, 1, "ISBN search for 13 digit ISBN matches 13 digit ISBN in database" ); - ($count, @results) = C4::Breeding::BreedingSearch("9798200834976"); - is( $count, 1, "ISBN search for 13 digit ISBN matches 13 digit ISBN in database"); # FIXME - Import doesn't currently store these, but this proves the search works }; @@ -99,140 +111,166 @@ $schema->storage->txn_rollback; sub test_build_translate_query { my $str; + #First pass no parameters - my @queries= C4::Breeding::_bib_build_query( {} ); - is( defined $queries[0] && $queries[0] eq '' && defined $queries[1] && - $queries[1] eq '', 1, '_bib_build_query gets no parameters'); + my @queries = C4::Breeding::_bib_build_query( {} ); + is( + defined $queries[0] && $queries[0] eq '' && defined $queries[1] && $queries[1] eq '', 1, + '_bib_build_query gets no parameters' + ); #We now pass one parameter - my $pars1= { isbn => '234567' }; - @queries= C4::Breeding::_bib_build_query( $pars1 ); + my $pars1 = { isbn => '234567' }; + @queries = C4::Breeding::_bib_build_query($pars1); + #Passed only one par: zquery should start with @attr 1=\d+ - is( $queries[0] =~ /^\@attr 1=\d+/, 1, 'Z39.50 query with one parameter'); - $str=$pars1->{isbn}; + is( $queries[0] =~ /^\@attr 1=\d+/, 1, 'Z39.50 query with one parameter' ); + $str = $pars1->{isbn}; + #Find back ISBN? - is( $queries[0] =~ /$str/, 1, 'First Z39.50 query contains ISBN'); + is( $queries[0] =~ /$str/, 1, 'First Z39.50 query contains ISBN' ); + #SRU query should contain translation for ISBN - my $server= { sru_fields => 'isbn=ie-es-bee-en,srchany=overal' }; - my $squery= C4::Breeding::_translate_query( $server, $queries[1] ); - is( $squery =~ /ie-es-bee-en/, 1, 'SRU query has translated ISBN index'); + my $server = { sru_fields => 'isbn=ie-es-bee-en,srchany=overal' }; + my $squery = C4::Breeding::_translate_query( $server, $queries[1] ); + is( $squery =~ /ie-es-bee-en/, 1, 'SRU query has translated ISBN index' ); + #Another try with fallback to any - $server= { sru_fields => 'srchany=overal' }; - $squery= C4::Breeding::_translate_query( $server, $queries[1] ); - is( $squery =~ /overal/, 1, 'SRU query fallback to translated any'); + $server = { sru_fields => 'srchany=overal' }; + $squery = C4::Breeding::_translate_query( $server, $queries[1] ); + is( $squery =~ /overal/, 1, 'SRU query fallback to translated any' ); + #Another try even without any - $server= { sru_fields => 'this,is,bad,input' }; - $squery= C4::Breeding::_translate_query( $server, $queries[1] ); - is( $squery =~ /$str/ && $squery !~ /=/, 1, 'SRU query without indexes'); + $server = { sru_fields => 'this,is,bad,input' }; + $squery = C4::Breeding::_translate_query( $server, $queries[1] ); + is( $squery =~ /$str/ && $squery !~ /=/, 1, 'SRU query without indexes' ); #We now pass two parameters - my $pars2= { isbn => '123456', title => 'You should read this.' }; - @queries= C4::Breeding::_bib_build_query( $pars2 ); + my $pars2 = { isbn => '123456', title => 'You should read this.' }; + @queries = C4::Breeding::_bib_build_query($pars2); + #The Z39.50 query should start with @and (we passed two pars) - is( $queries[0] =~ /^\@and/, 1, 'Second Z39.50 query starts with @and'); + is( $queries[0] =~ /^\@and/, 1, 'Second Z39.50 query starts with @and' ); + #We should also find two @attr 1=\d+ - my @matches= $queries[0] =~ /\@attr 1=\d+/g; - is( @matches == 2, 1, 'Second Z39.50 query includes two @attr 1='); + my @matches = $queries[0] =~ /\@attr 1=\d+/g; + is( @matches == 2, 1, 'Second Z39.50 query includes two @attr 1=' ); + #We should find text of both parameters in the query - $str= $pars2->{isbn}; - is( $queries[0] =~ /\"$str\"/, 1, - 'Second query contains ISBN enclosed by double quotes'); - $str= $pars2->{title}; - is( $queries[0] =~ /\"$str\"/, 1, - 'Second query contains title enclosed by double quotes'); + $str = $pars2->{isbn}; + is( + $queries[0] =~ /\"$str\"/, 1, + 'Second query contains ISBN enclosed by double quotes' + ); + $str = $pars2->{title}; + is( + $queries[0] =~ /\"$str\"/, 1, + 'Second query contains title enclosed by double quotes' + ); #SRU revisited - $server= { sru_fields => 'isbn=nb,title=dc.title,srchany=overal' }; - $squery= C4::Breeding::_translate_query( $server, $queries[1] ); - is ( $squery =~ /dc.title/ && $squery =~ / and / && - $squery =~ /nb=/, 1, 'SRU query with two parameters'); + $server = { sru_fields => 'isbn=nb,title=dc.title,srchany=overal' }; + $squery = C4::Breeding::_translate_query( $server, $queries[1] ); + is( $squery =~ /dc.title/ && $squery =~ / and / && $squery =~ /nb=/, 1, 'SRU query with two parameters' ); #We now pass a third wrong parameter (should not make a difference) - my $pars3= { isbn => '123456', title => 'You should read this.', xyz => 1 }; - my @queries2= C4::Breeding::_bib_build_query( $pars3 ); - is( $queries[0] eq $queries2[0] && $queries[1] eq $queries2[1], 1, - 'Third query makes no difference'); + my $pars3 = { isbn => '123456', title => 'You should read this.', xyz => 1 }; + my @queries2 = C4::Breeding::_bib_build_query($pars3); + is( + $queries[0] eq $queries2[0] && $queries[1] eq $queries2[1], 1, + 'Third query makes no difference' + ); # Check that indexes with equal signs are ok $server = { sru_fields => 'subjectsubdiv=aut.type=ram_pe and aut.accesspoint' }; my $pars4 = { subjectsubdiv => 'mysubjectsubdiv' }; - @queries = C4::Breeding::_auth_build_query( $pars4 ); + @queries = C4::Breeding::_auth_build_query($pars4); my $zquery = C4::Breeding::_translate_query( $server, $queries[1] ); - is ( $zquery, 'aut.type=ram_pe and aut.accesspoint="mysubjectsubdiv"', 'SRU query with equal sign in index'); + is( $zquery, 'aut.type=ram_pe and aut.accesspoint="mysubjectsubdiv"', 'SRU query with equal sign in index' ); # Check that indexes with double-quotes are ok $server = { sru_fields => 'subject=(aut.type any "geo ram_nc ram_ge ram_pe ram_co") and aut.accesspoint' }; my $pars5 = { subject => 'mysubject' }; - @queries = C4::Breeding::_auth_build_query( $pars5 ); - $zquery = C4::Breeding::_translate_query( $server, $queries[1] ); - is ( $zquery, '(aut.type any "geo ram_nc ram_ge ram_pe ram_co") and aut.accesspoint="mysubject"', 'SRU query with double quotes in index'); + @queries = C4::Breeding::_auth_build_query($pars5); + $zquery = C4::Breeding::_translate_query( $server, $queries[1] ); + is( + $zquery, '(aut.type any "geo ram_nc ram_ge ram_pe ram_co") and aut.accesspoint="mysubject"', + 'SRU query with double quotes in index' + ); } sub test_create_connection { + #TODO This is just a *simple* start my $str; - my $server= { servertype => 'zed', db => 'MyDatabase', - host => 'really-not-a-domain-i-hope.nl', port => 80, + my $server = { + servertype => 'zed', db => 'MyDatabase', + host => 'really-not-a-domain-i-hope.nl', port => 80, }; - my $obj= C4::Breeding::_create_connection( $server ); + my $obj = C4::Breeding::_create_connection($server); #We should get back an object, even if it did not connect - is( ref $obj eq 'ZOOM::Connection', 1, 'Got back a ZOOM connection'); + is( ref $obj eq 'ZOOM::Connection', 1, 'Got back a ZOOM connection' ); #Remember: it is async - my $i= ZOOM::event( [ $obj ] ); - if( $i == 1 ) { + my $i = ZOOM::event( [$obj] ); + if ( $i == 1 ) { + #We could examine ZOOM::event_str( $obj->last_event ) #For now we are satisfied with an error message #Probably: Connect failed - is( ($obj->errmsg//'') ne '', 1, 'Connection failed as expected'); + is( ( $obj->errmsg // '' ) ne '', 1, 'Connection failed as expected' ); } else { ok( 1, 'No ZOOM event found: skipped errmsg' ); } #Checking the databaseName for Z39.50 server - $str=$obj->option('databaseName')//''; - is( $str eq $server->{db}, 1, 'Check ZOOM option for database'); + $str = $obj->option('databaseName') // ''; + is( $str eq $server->{db}, 1, 'Check ZOOM option for database' ); #Another test for SRU $obj->destroy(); - $server->{ servertype } = 'sru'; - $server->{ sru_options } = 'just_testing=fun'; - $obj= C4::Breeding::_create_connection( $server ); + $server->{servertype} = 'sru'; + $server->{sru_options} = 'just_testing=fun'; + $obj = C4::Breeding::_create_connection($server); + #In this case we expect no databaseName, but we expect just_testing - $str=$obj->option('databaseName'); - is( $str, undef, 'No databaseName for SRU connection'); - $str=$obj->option('just_testing')//''; - is( $str eq 'fun', 1, 'Additional ZOOM option for SRU found'); + $str = $obj->option('databaseName'); + is( $str, undef, 'No databaseName for SRU connection' ); + $str = $obj->option('just_testing') // ''; + is( $str eq 'fun', 1, 'Additional ZOOM option for SRU found' ); $obj->destroy(); } sub test_do_xslt { my $biblio = MARC::Record->new(); $biblio->append_fields( - MARC::Field->new('100', ' ', ' ', a => 'John Writer'), - MARC::Field->new('245', ' ', ' ', a => 'Just a title'), + MARC::Field->new( '100', ' ', ' ', a => 'John Writer' ), + MARC::Field->new( '245', ' ', ' ', a => 'Just a title' ), ); - my $file= xsl_file(); - my $server= { add_xslt => $file }; - my $engine=Koha::XSLT::Base->new; + my $file = xsl_file(); + my $server = { add_xslt => $file }; + my $engine = Koha::XSLT::Base->new; #ready for the main test my @res = C4::Breeding::_do_xslt_proc( $biblio, $server, $engine ); - is( $res[1], undef, 'No error returned' ); - is( ref $res[0], 'MARC::Record', 'Got back MARC record'); - is( $res[0]->subfield('990','a'), 'I saw you', 'Found 990a in the record'); + is( $res[1], undef, 'No error returned' ); + is( ref $res[0], 'MARC::Record', 'Got back MARC record' ); + is( $res[0]->subfield( '990', 'a' ), 'I saw you', 'Found 990a in the record' ); #forcing an error on the xslt side $server->{add_xslt} = 'notafile.xsl'; @res = C4::Breeding::_do_xslt_proc( $biblio, $server, $engine ); is( $res[1], Koha::XSLT::Base::XSLTH_ERR_2, 'Error code found' ); + #We still expect the original record back is( ref $res[0], 'MARC::Record', 'Still got back MARC record' ); - is ( $res[0]->subfield('245','a'), 'Just a title', - 'At least the title is the same :)' ); + is( + $res[0]->subfield( '245', 'a' ), 'Just a title', + 'At least the title is the same :)' + ); } sub test_add_custom_field_rowdata { @@ -270,7 +308,8 @@ sub test_add_custom_field_rowdata { } sub xsl_file { - return mytempfile( q{<xsl:stylesheet version="1.0" + return mytempfile( + q{<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:marc="http://www.loc.gov/MARC21/slim" > @@ -293,12 +332,13 @@ sub xsl_file { <xsl:apply-templates/> </xsl:copy> </xsl:template> -</xsl:stylesheet>} ); +</xsl:stylesheet>} + ); } sub mytempfile { my ( $fh, $fn ) = tempfile( SUFFIX => '.xsl', UNLINK => 1 ); - print $fh $_[0]//''; + print $fh $_[0] // ''; close $fh; return $fn; } diff --git a/t/db_dependent/Breeding_Auth.t b/t/db_dependent/Breeding_Auth.t index b019bb127d..c40e551d7f 100755 --- a/t/db_dependent/Breeding_Auth.t +++ b/t/db_dependent/Breeding_Auth.t @@ -123,8 +123,8 @@ subtest 'Z3950SearchAuth' => sub { { source => 'Z3950server', value => { - recordtype => 'authority', servertype => 'zed', host => 'marc8test', servername => 'MARC8 server', - syntax => 'USMARC', encoding => 'MARC-8', attributes => undef + recordtype => 'authority', servertype => 'zed', host => 'marc8test', servername => 'MARC8 server', + syntax => 'USMARC', encoding => 'MARC-8', attributes => undef }, } ); @@ -161,7 +161,7 @@ subtest 'Z3950SearchAuth' => sub { init_mock_data( { result_counts => [1], results => [ $marc8_record->as_usmarc ] } ); C4::Breeding::Z3950SearchAuth( { srchany => 'a', id => [ $marc8_server->{id} ] }, $template ); $output = $mock_data->{template_params}; - is( @{ $output->{breeding_loop} }, 1, 'One result in breedingloop' ); + is( @{ $output->{breeding_loop} }, 1, 'One result in breedingloop' ); is( $output->{breeding_loop}->[0]->{heading}, 'Cooper, Susan', 'Check heading' ); my $import_record = Koha::Import::Records->find( $output->{breeding_loop}->[0]->{breedingid} ); ok( $import_record, 'import record found' ); diff --git a/t/db_dependent/Budgets.t b/t/db_dependent/Budgets.t index 418c66bc59..b68fc16496 100755 --- a/t/db_dependent/Budgets.t +++ b/t/db_dependent/Budgets.t @@ -4,10 +4,13 @@ use Test::More tests => 156; use JSON; BEGIN { - use_ok('C4::Budgets', qw( AddBudgetPeriod AddBudget GetBudgetPeriods GetBudgetPeriod GetBudget ModBudgetPeriod ModBudget DelBudgetPeriod DelBudget GetBudgets GetBudgetName GetBudgetByCode GetBudgetHierarchy GetBudgetHierarchySpent GetBudgetSpent GetBudgetOrdered CloneBudgetPeriod GetBudgetsByActivity MoveOrders GetBudgetByOrderNumber SetOwnerToFundHierarchy GetBudgetAuthCats GetBudgetsPlanCell )); + use_ok( + 'C4::Budgets', + qw( AddBudgetPeriod AddBudget GetBudgetPeriods GetBudgetPeriod GetBudget ModBudgetPeriod ModBudget DelBudgetPeriod DelBudget GetBudgets GetBudgetName GetBudgetByCode GetBudgetHierarchy GetBudgetHierarchySpent GetBudgetSpent GetBudgetOrdered CloneBudgetPeriod GetBudgetsByActivity MoveOrders GetBudgetByOrderNumber SetOwnerToFundHierarchy GetBudgetAuthCats GetBudgetsPlanCell ) + ); } use C4::Context; -use C4::Biblio qw( AddBiblio ); +use C4::Biblio qw( AddBiblio ); use C4::Acquisition qw( NewBasket AddInvoice GetInvoice ModReceiveOrder ); use Koha::ActionLogs; @@ -23,30 +26,32 @@ use t::lib::Mocks; use Koha::DateUtils; use t::lib::Mocks; -t::lib::Mocks::mock_preference('OrderPriceRounding',''); -t::lib::Mocks::mock_preference('AcquisitionLog','1'); +t::lib::Mocks::mock_preference( 'OrderPriceRounding', '' ); +t::lib::Mocks::mock_preference( 'AcquisitionLog', '1' ); -my $schema = Koha::Database->new->schema; +my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; my $builder = t::lib::TestBuilder->new; -my $dbh = C4::Context->dbh; +my $dbh = C4::Context->dbh; $dbh->do(q|DELETE FROM vendor_edi_accounts|); $dbh->do(q|DELETE FROM aqbudgetperiods|); $dbh->do(q|DELETE FROM aqbudgets|); -my $library = $builder->build({ - source => 'Branch', -}); +my $library = $builder->build( + { + source => 'Branch', + } +); -my $patron = $builder->build_object({ class => 'Koha::Patrons' }); +my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); $patron->store; t::lib::Mocks::mock_userenv( { - flags => 1, - userid => $patron->userid, + flags => 1, + userid => $patron->userid, borrowernumber => $patron->borrowernumber, - branch => $library->{branchcode}, + branch => $library->{branchcode}, } ); @@ -54,15 +59,19 @@ t::lib::Mocks::mock_userenv( # Budget Periods : # -is( AddBudgetPeriod(), undef, 'AddBugetPeriod without argument returns undef' ); -is( AddBudgetPeriod( { } ), undef, 'AddBugetPeriod with an empty argument returns undef' ); -my $bpid = AddBudgetPeriod({ - budget_period_startdate => '2008-01-01', -}); +is( AddBudgetPeriod(), undef, 'AddBugetPeriod without argument returns undef' ); +is( AddBudgetPeriod( {} ), undef, 'AddBugetPeriod with an empty argument returns undef' ); +my $bpid = AddBudgetPeriod( + { + budget_period_startdate => '2008-01-01', + } +); is( $bpid, undef, 'AddBugetPeriod without end date returns undef' ); -$bpid = AddBudgetPeriod({ - budget_period_enddate => '2008-12-31', -}); +$bpid = AddBudgetPeriod( + { + budget_period_enddate => '2008-12-31', + } +); is( $bpid, undef, 'AddBugetPeriod without start date returns undef' ); my $budgetperiods = GetBudgetPeriods(); is( @$budgetperiods, 0, 'GetBudgetPeriods returns the correct number of budget periods' ); @@ -72,15 +81,27 @@ my $my_budgetperiod = { budget_period_enddate => '2008-12-31', budget_period_description => 'MAPERI', budget_period_active => 0, - budget_period_id => '', # Bug 21604 + budget_period_id => '', # Bug 21604 }; $bpid = AddBudgetPeriod($my_budgetperiod); isnt( $bpid, undef, 'AddBugetPeriod does not returns undef' ); my $budgetperiod = GetBudgetPeriod($bpid); -is( $budgetperiod->{budget_period_startdate}, $my_budgetperiod->{budget_period_startdate}, 'AddBudgetPeriod stores the start date correctly' ); -is( $budgetperiod->{budget_period_enddate}, $my_budgetperiod->{budget_period_enddate}, 'AddBudgetPeriod stores the end date correctly' ); -is( $budgetperiod->{budget_period_description}, $my_budgetperiod->{budget_period_description}, 'AddBudgetPeriod stores the description correctly' ); -is( $budgetperiod->{budget_period_active}, $my_budgetperiod->{budget_period_active}, 'AddBudgetPeriod stores active correctly' ); +is( + $budgetperiod->{budget_period_startdate}, $my_budgetperiod->{budget_period_startdate}, + 'AddBudgetPeriod stores the start date correctly' +); +is( + $budgetperiod->{budget_period_enddate}, $my_budgetperiod->{budget_period_enddate}, + 'AddBudgetPeriod stores the end date correctly' +); +is( + $budgetperiod->{budget_period_description}, $my_budgetperiod->{budget_period_description}, + 'AddBudgetPeriod stores the description correctly' +); +is( + $budgetperiod->{budget_period_active}, $my_budgetperiod->{budget_period_active}, + 'AddBudgetPeriod stores active correctly' +); $my_budgetperiod = { budget_period_startdate => '2009-01-01', @@ -95,18 +116,45 @@ $my_budgetperiod->{budget_period_id} = $bpid; $mod_status = ModBudgetPeriod($my_budgetperiod); is( $mod_status, 1, 'ModBudgetPeriod returnis true' ); $budgetperiod = GetBudgetPeriod($bpid); -is( $budgetperiod->{budget_period_startdate}, $my_budgetperiod->{budget_period_startdate}, 'ModBudgetPeriod updates the start date correctly' ); -is( $budgetperiod->{budget_period_enddate}, $my_budgetperiod->{budget_period_enddate}, 'ModBudgetPeriod updates the end date correctly' ); -is( $budgetperiod->{budget_period_description}, $my_budgetperiod->{budget_period_description}, 'ModBudgetPeriod updates the description correctly' ); -is( $budgetperiod->{budget_period_active}, $my_budgetperiod->{budget_period_active}, 'ModBudgetPeriod upates active correctly' ); +is( + $budgetperiod->{budget_period_startdate}, $my_budgetperiod->{budget_period_startdate}, + 'ModBudgetPeriod updates the start date correctly' +); +is( + $budgetperiod->{budget_period_enddate}, $my_budgetperiod->{budget_period_enddate}, + 'ModBudgetPeriod updates the end date correctly' +); +is( + $budgetperiod->{budget_period_description}, $my_budgetperiod->{budget_period_description}, + 'ModBudgetPeriod updates the description correctly' +); +is( + $budgetperiod->{budget_period_active}, $my_budgetperiod->{budget_period_active}, + 'ModBudgetPeriod upates active correctly' +); $budgetperiods = GetBudgetPeriods(); is( @$budgetperiods, 1, 'GetBudgetPeriods returns the correct number of budget periods' ); -is( $budgetperiods->[0]->{budget_period_id}, $my_budgetperiod->{budget_period_id}, 'GetBudgetPeriods returns the id correctly' ); -is( $budgetperiods->[0]->{budget_period_startdate}, $my_budgetperiod->{budget_period_startdate}, 'GetBudgetPeriods returns the start date correctly' ); -is( $budgetperiods->[0]->{budget_period_enddate}, $my_budgetperiod->{budget_period_enddate}, 'GetBudgetPeriods returns the end date correctly' ); -is( $budgetperiods->[0]->{budget_period_description}, $my_budgetperiod->{budget_period_description}, 'GetBudgetPeriods returns the description correctly' ); -is( $budgetperiods->[0]->{budget_period_active}, $my_budgetperiod->{budget_period_active}, 'GetBudgetPeriods returns active correctly' ); +is( + $budgetperiods->[0]->{budget_period_id}, $my_budgetperiod->{budget_period_id}, + 'GetBudgetPeriods returns the id correctly' +); +is( + $budgetperiods->[0]->{budget_period_startdate}, $my_budgetperiod->{budget_period_startdate}, + 'GetBudgetPeriods returns the start date correctly' +); +is( + $budgetperiods->[0]->{budget_period_enddate}, $my_budgetperiod->{budget_period_enddate}, + 'GetBudgetPeriods returns the end date correctly' +); +is( + $budgetperiods->[0]->{budget_period_description}, $my_budgetperiod->{budget_period_description}, + 'GetBudgetPeriods returns the description correctly' +); +is( + $budgetperiods->[0]->{budget_period_active}, $my_budgetperiod->{budget_period_active}, + 'GetBudgetPeriods returns active correctly' +); is( DelBudgetPeriod($bpid), 1, 'DelBudgetPeriod returns true' ); $budgetperiods = GetBudgetPeriods(); @@ -128,7 +176,7 @@ is( AddBudget(), undef, 'AddBuget without argument returns undef' ); my $budgets = GetBudgets(); is( @$budgets, 0, 'GetBudgets returns the correct number of budgets' ); -$bpid = AddBudgetPeriod($my_budgetperiod); #this is an active budget +$bpid = AddBudgetPeriod($my_budgetperiod); #this is an active budget my $my_budget = { budget_code => 'ABCD', @@ -137,18 +185,19 @@ my $my_budget = { budget_name => 'Periodiques', budget_notes => 'This is a note', budget_period_id => $bpid, - budget_encumb => '456', # Bug 21604 + budget_encumb => '456', # Bug 21604 }; my $budget_id = AddBudget($my_budget); isnt( $budget_id, undef, 'AddBudget does not returns undef' ); my $budget = GetBudget($budget_id); -is( $budget->{budget_code}, $my_budget->{budget_code}, 'AddBudget stores the budget code correctly' ); -is( $budget->{budget_amount}, $my_budget->{budget_amount}, 'AddBudget stores the budget amount correctly' ); -is( $budget->{budget_name}, $my_budget->{budget_name}, 'AddBudget stores the budget name correctly' ); -is( $budget->{budget_notes}, $my_budget->{budget_notes}, 'AddBudget stores the budget notes correctly' ); +is( $budget->{budget_code}, $my_budget->{budget_code}, 'AddBudget stores the budget code correctly' ); +is( $budget->{budget_amount}, $my_budget->{budget_amount}, 'AddBudget stores the budget amount correctly' ); +is( $budget->{budget_name}, $my_budget->{budget_name}, 'AddBudget stores the budget name correctly' ); +is( $budget->{budget_notes}, $my_budget->{budget_notes}, 'AddBudget stores the budget notes correctly' ); is( $budget->{budget_period_id}, $my_budget->{budget_period_id}, 'AddBudget stores the budget period id correctly' ); -my @create_logs = Koha::ActionLogs->find({ module =>'ACQUISITIONS', action => 'CREATE_FUND', object => $budget->{budget_id} }); +my @create_logs = + Koha::ActionLogs->find( { module => 'ACQUISITIONS', action => 'CREATE_FUND', object => $budget->{budget_id} } ); my $expected_create_payload = { budget_amount => $my_budget->{budget_amount}, @@ -156,9 +205,12 @@ my $expected_create_payload = { budget_encumb => $my_budget->{budget_encumb}, }; -my $actual_create_payload = from_json($create_logs[0]->info); +my $actual_create_payload = from_json( $create_logs[0]->info ); -is_deeply ($actual_create_payload, $expected_create_payload, 'ModBudget logs a budget creation with the correct payload'); +is_deeply( + $actual_create_payload, $expected_create_payload, + 'ModBudget logs a budget creation with the correct payload' +); my $before = $budget; @@ -178,13 +230,14 @@ $my_budget->{budget_id} = $budget_id; $mod_status = ModBudget($my_budget); is( $mod_status, 1, 'ModBudget returns true' ); $budget = GetBudget($budget_id); -is( $budget->{budget_code}, $my_budget->{budget_code}, 'ModBudget updates the budget code correctly' ); -is( $budget->{budget_amount}, $my_budget->{budget_amount}, 'ModBudget updates the budget amount correctly' ); -is( $budget->{budget_name}, $my_budget->{budget_name}, 'ModBudget updates the budget name correctly' ); -is( $budget->{budget_notes}, $my_budget->{budget_notes}, 'ModBudget updates the budget notes correctly' ); +is( $budget->{budget_code}, $my_budget->{budget_code}, 'ModBudget updates the budget code correctly' ); +is( $budget->{budget_amount}, $my_budget->{budget_amount}, 'ModBudget updates the budget amount correctly' ); +is( $budget->{budget_name}, $my_budget->{budget_name}, 'ModBudget updates the budget name correctly' ); +is( $budget->{budget_notes}, $my_budget->{budget_notes}, 'ModBudget updates the budget notes correctly' ); is( $budget->{budget_period_id}, $my_budget->{budget_period_id}, 'ModBudget updates the budget period id correctly' ); -my @mod_logs = Koha::ActionLogs->find({ module =>'ACQUISITIONS', action => 'MODIFY_FUND', object => $budget->{budget_id} }); +my @mod_logs = + Koha::ActionLogs->find( { module => 'ACQUISITIONS', action => 'MODIFY_FUND', object => $budget->{budget_id} } ); my $expected_mod_payload = { budget_amount_new => $my_budget->{budget_amount}, budget_encumb_new => $my_budget->{budget_encumb}, @@ -192,38 +245,43 @@ my $expected_mod_payload = { budget_amount_old => $before->{budget_amount}, budget_encumb_old => $before->{budget_encumb}, budget_expend_old => $before->{budget_expend}, - budget_amount_change => 0 - ($before->{budget_amount} - $my_budget->{budget_amount}) + budget_amount_change => 0 - ( $before->{budget_amount} - $my_budget->{budget_amount} ) }; -my $actual_mod_payload = from_json($mod_logs[0]->info); -is_deeply ($actual_mod_payload, $expected_mod_payload, 'ModBudget logs a budget modification with the correct payload'); +my $actual_mod_payload = from_json( $mod_logs[0]->info ); +is_deeply( + $actual_mod_payload, $expected_mod_payload, + 'ModBudget logs a budget modification with the correct payload' +); $budgets = GetBudgets(); -is( @$budgets, 1, 'GetBudgets returns the correct number of budgets' ); -is( $budgets->[0]->{budget_id}, $my_budget->{budget_id}, 'GetBudgets returns the budget id correctly' ); -is( $budgets->[0]->{budget_code}, $my_budget->{budget_code}, 'GetBudgets returns the budget code correctly' ); +is( @$budgets, 1, 'GetBudgets returns the correct number of budgets' ); +is( $budgets->[0]->{budget_id}, $my_budget->{budget_id}, 'GetBudgets returns the budget id correctly' ); +is( $budgets->[0]->{budget_code}, $my_budget->{budget_code}, 'GetBudgets returns the budget code correctly' ); is( $budgets->[0]->{budget_amount}, $my_budget->{budget_amount}, 'GetBudgets returns the budget amount correctly' ); -is( $budgets->[0]->{budget_name}, $my_budget->{budget_name}, 'GetBudgets returns the budget name correctly' ); -is( $budgets->[0]->{budget_notes}, $my_budget->{budget_notes}, 'GetBudgets returns the budget notes correctly' ); -is( $budgets->[0]->{budget_period_id}, $my_budget->{budget_period_id}, 'GetBudgets returns the budget period id correctly' ); +is( $budgets->[0]->{budget_name}, $my_budget->{budget_name}, 'GetBudgets returns the budget name correctly' ); +is( $budgets->[0]->{budget_notes}, $my_budget->{budget_notes}, 'GetBudgets returns the budget notes correctly' ); +is( + $budgets->[0]->{budget_period_id}, $my_budget->{budget_period_id}, + 'GetBudgets returns the budget period id correctly' +); -$budgets = GetBudgets( {budget_period_id => $bpid} ); +$budgets = GetBudgets( { budget_period_id => $bpid } ); is( @$budgets, 1, 'GetBudgets With Filter OK' ); -$budgets = GetBudgets( {budget_period_id => $bpid}, {-asc => "budget_name"} ); +$budgets = GetBudgets( { budget_period_id => $bpid }, { -asc => "budget_name" } ); is( @$budgets, 1, 'GetBudgets With Order OK' ); -$budgets = GetBudgets( {budget_period_id => GetBudgetPeriod($bpid)->{budget_period_id}}, {-asc => "budget_name"} ); -is( @$budgets, 1, 'GetBudgets With Order Getting Active budgetPeriod OK'); +$budgets = GetBudgets( { budget_period_id => GetBudgetPeriod($bpid)->{budget_period_id} }, { -asc => "budget_name" } ); +is( @$budgets, 1, 'GetBudgets With Order Getting Active budgetPeriod OK' ); +my $budget_name = GetBudgetName($budget_id); +is( $budget_name, $my_budget->{budget_name}, "Test the GetBudgetName routine" ); -my $budget_name = GetBudgetName( $budget_id ); -is($budget_name, $my_budget->{budget_name}, "Test the GetBudgetName routine"); - -my $my_inactive_budgetperiod = { #let's add an inactive +my $my_inactive_budgetperiod = { #let's add an inactive budget_period_startdate => '2010-01-01', budget_period_enddate => '2010-12-31', budget_period_description => 'MODIF_MAPERI', budget_period_active => 0, }; -my $bpid_i = AddBudgetPeriod($my_inactive_budgetperiod); #this is an inactive budget +my $bpid_i = AddBudgetPeriod($my_inactive_budgetperiod); #this is an inactive budget my $my_budget_inactive = { budget_code => 'EFG', @@ -234,38 +292,41 @@ my $my_budget_inactive = { }; my $budget_id_inactive = AddBudget($my_budget_inactive); -my $budget_code = $my_budget->{budget_code}; -my $budget_by_code = GetBudgetByCode( $budget_code ); -is($budget_by_code->{budget_id}, $budget_id, "GetBudgetByCode, check id"); #this should match the active budget, not the inactive -is($budget_by_code->{budget_notes}, $my_budget->{budget_notes}, "GetBudgetByCode, check notes"); +my $budget_code = $my_budget->{budget_code}; +my $budget_by_code = GetBudgetByCode($budget_code); +is( $budget_by_code->{budget_id}, $budget_id, "GetBudgetByCode, check id" ) + ; #this should match the active budget, not the inactive +is( $budget_by_code->{budget_notes}, $my_budget->{budget_notes}, "GetBudgetByCode, check notes" ); -my $second_budget_id = AddBudget({ - budget_code => "ZZZZ", - budget_amount => "500.00", - budget_name => "Art", - budget_notes => "This is a note", - budget_period_id => $bpid, -}); +my $second_budget_id = AddBudget( + { + budget_code => "ZZZZ", + budget_amount => "500.00", + budget_name => "Art", + budget_notes => "This is a note", + budget_period_id => $bpid, + } +); isnt( $second_budget_id, undef, 'AddBudget does not returns undef' ); -$budgets = GetBudgets( {budget_period_id => $bpid} ); +$budgets = GetBudgets( { budget_period_id => $bpid } ); ok( $budgets->[0]->{budget_name} lt $budgets->[1]->{budget_name}, 'default sort order for GetBudgets is by name' ); is( DelBudget($budget_id), 1, 'DelBudget returns true' ); $budgets = GetBudgets(); is( @$budgets, 2, 'GetBudgets returns the correct number of budget periods' ); -my @delete_logs = Koha::ActionLogs->find({ module =>'ACQUISITIONS', action => 'DELETE_FUND', object => $budget_id }); +my @delete_logs = Koha::ActionLogs->find( { module => 'ACQUISITIONS', action => 'DELETE_FUND', object => $budget_id } ); -is (scalar @delete_logs, 1, 'DelBudget logs a budget deletion'); +is( scalar @delete_logs, 1, 'DelBudget logs a budget deletion' ); # GetBudgetHierarchySpent and GetBudgetHierarchyOrdered my $budget_period_total = 10_000; -my $budget_1_total = 1_000; -my $budget_11_total = 100; -my $budget_111_total = 50; -my $budget_12_total = 100; -my $budget_2_total = 2_000; +my $budget_1_total = 1_000; +my $budget_11_total = 100; +my $budget_111_total = 50; +my $budget_12_total = 100; +my $budget_2_total = 2_000; my $budget_period_id = AddBudgetPeriod( { @@ -343,34 +404,33 @@ my $bookseller = Koha::Acquisition::Bookseller->new( my $booksellerid = $bookseller->id; my $basketno = C4::Acquisition::NewBasket( $booksellerid, 1 ); -my ( $biblionumber, $biblioitemnumber ) = - C4::Biblio::AddBiblio( MARC::Record->new, '' ); +my ( $biblionumber, $biblioitemnumber ) = C4::Biblio::AddBiblio( MARC::Record->new, '' ); my @order_infos = ( { - budget_id => $budget_id1, - pending_quantity => 1, - spent_quantity => 0, + budget_id => $budget_id1, + pending_quantity => 1, + spent_quantity => 0, }, { - budget_id => $budget_id2, - pending_quantity => 2, - spent_quantity => 1, + budget_id => $budget_id2, + pending_quantity => 2, + spent_quantity => 1, }, { - budget_id => $budget_id11, - pending_quantity => 3, - spent_quantity => 4, + budget_id => $budget_id11, + pending_quantity => 3, + spent_quantity => 4, }, { - budget_id => $budget_id12, - pending_quantity => 4, - spent_quantity => 3, + budget_id => $budget_id12, + pending_quantity => 4, + spent_quantity => 3, }, { - budget_id => $budget_id111, - pending_quantity => 2, - spent_quantity => 1, + budget_id => $budget_id111, + pending_quantity => 2, + spent_quantity => 1, }, # No order for budget_21 @@ -378,10 +438,11 @@ my @order_infos = ( ); my %budgets; -my $invoiceid = AddInvoice(invoicenumber => 'invoice_test_clone', booksellerid => $booksellerid, unknown => "unknown"); -my $invoice = GetInvoice( $invoiceid ); -my $item_price = 10; -my $item_quantity = 2; +my $invoiceid = + AddInvoice( invoicenumber => 'invoice_test_clone', booksellerid => $booksellerid, unknown => "unknown" ); +my $invoice = GetInvoice($invoiceid); +my $item_price = 10; +my $item_quantity = 2; my $number_of_orders_to_move = 0; for my $infos (@order_infos) { for ( 1 .. $infos->{pending_quantity} ) { @@ -402,7 +463,7 @@ for my $infos (@order_infos) { } )->store; my $ordernumber = $order->ordernumber; - push @{ $budgets{$infos->{budget_id}} }, $ordernumber; + push @{ $budgets{ $infos->{budget_id} } }, $ordernumber; $number_of_orders_to_move++; } for ( 1 .. $infos->{spent_quantity} ) { @@ -423,24 +484,26 @@ for my $infos (@order_infos) { } )->store; my $ordernumber = $order->ordernumber; - ModReceiveOrder({ - biblionumber => $biblionumber, - order => $order->unblessed, - budget_id => $infos->{budget_id}, - quantityreceived => $item_quantity, - invoice => $invoice, - received_items => [], - } ); + ModReceiveOrder( + { + biblionumber => $biblionumber, + order => $order->unblessed, + budget_id => $infos->{budget_id}, + quantityreceived => $item_quantity, + invoice => $invoice, + received_items => [], + } + ); } } -t::lib::Mocks::mock_preference('CalculateFundValuesIncludingTax', '1'); -is( GetBudgetHierarchySpent( $budget_id1 ), 160, "total spent for budget1 is 160" ); -is( GetBudgetHierarchySpent( $budget_id11 ), 100, "total spent for budget11 is 100" ); -is( GetBudgetHierarchySpent( $budget_id111 ), 20, "total spent for budget111 is 20" ); +t::lib::Mocks::mock_preference( 'CalculateFundValuesIncludingTax', '1' ); +is( GetBudgetHierarchySpent($budget_id1), 160, "total spent for budget1 is 160" ); +is( GetBudgetHierarchySpent($budget_id11), 100, "total spent for budget11 is 100" ); +is( GetBudgetHierarchySpent($budget_id111), 20, "total spent for budget111 is 20" ); # GetBudgetSpent and GetBudgetOrdered my $budget_period_amount = 100; -my $budget_amount = 50; +my $budget_amount = 50; $budget = AddBudgetPeriod( { @@ -454,11 +517,11 @@ $budget = AddBudgetPeriod( my $fund = AddBudget( { - budget_code => 'Test fund', - budget_name => 'Test fund', - budget_period_id => $budget, - budget_parent_id => undef, - budget_amount => $budget_amount, + budget_code => 'Test fund', + budget_name => 'Test fund', + budget_period_id => $budget, + budget_parent_id => undef, + budget_amount => $budget_amount, } ); @@ -479,72 +542,77 @@ my ( $biblio, $biblioitem ) = C4::Biblio::AddBiblio( MARC::Record->new, '' ); my @orders = ( { - budget_id => $fund, + budget_id => $fund, pending_quantity => 1, - spent_quantity => 0, + spent_quantity => 0, }, ); -my $invoiceident = AddInvoice( invoicenumber => 'invoice_test_clone', booksellerid => $vendorid, shipmentdate => '2017-08-22', shipmentcost => 6, shipmentcost_budgetid => $fund ); -my $test_invoice = GetInvoice( $invoiceident ); +my $invoiceident = AddInvoice( + invoicenumber => 'invoice_test_clone', booksellerid => $vendorid, shipmentdate => '2017-08-22', + shipmentcost => 6, shipmentcost_budgetid => $fund +); +my $test_invoice = GetInvoice($invoiceident); my $individual_item_price = 10; my $order = Koha::Acquisition::Order->new( - { - basketno => $basketnumber, - biblionumber => $biblio, - budget_id => $fund, - order_internalnote => "internalnote", - order_vendornote => "vendor note", - quantity => 2, - cost_tax_included => $individual_item_price, - rrp_tax_included => $individual_item_price, - listprice => $individual_item_price, - ecost_tax_included => $individual_item_price, - discount => 0, - uncertainprice => 0, - } + { + basketno => $basketnumber, + biblionumber => $biblio, + budget_id => $fund, + order_internalnote => "internalnote", + order_vendornote => "vendor note", + quantity => 2, + cost_tax_included => $individual_item_price, + rrp_tax_included => $individual_item_price, + listprice => $individual_item_price, + ecost_tax_included => $individual_item_price, + discount => 0, + uncertainprice => 0, + } )->store; -ModReceiveOrder({ - bibionumber => $biblio, - order => $order->unblessed, - budget_id => $fund, - quantityreceived => 2, - invoice => $test_invoice, - received_items => [], -} ); -t::lib::Mocks::mock_preference('OrderPriceRounding',''); - -is ( GetBudgetSpent( $fund ), 6, "total shipping cost is 6"); -is ( GetBudgetOrdered( $fund ), '20', "total ordered price is 20"); +ModReceiveOrder( + { + bibionumber => $biblio, + order => $order->unblessed, + budget_id => $fund, + quantityreceived => 2, + invoice => $test_invoice, + received_items => [], + } +); +t::lib::Mocks::mock_preference( 'OrderPriceRounding', '' ); +is( GetBudgetSpent($fund), 6, "total shipping cost is 6" ); +is( GetBudgetOrdered($fund), '20', "total ordered price is 20" ); # CloneBudgetPeriod # Let's make sure our timestamp is old -my @orig_funds = Koha::Acquisition::Funds->search({ budget_period_id => $budget_period_id })->as_list; -foreach my $fund (@orig_funds){ +my @orig_funds = Koha::Acquisition::Funds->search( { budget_period_id => $budget_period_id } )->as_list; +foreach my $fund (@orig_funds) { $fund->timestamp('1999-12-31 23:59:59')->store; } my $budget_period_id_cloned = C4::Budgets::CloneBudgetPeriod( { - budget_period_id => $budget_period_id, - budget_period_startdate => '2014-01-01', - budget_period_enddate => '2014-12-31', + budget_period_id => $budget_period_id, + budget_period_startdate => '2014-01-01', + budget_period_enddate => '2014-12-31', budget_period_description => 'Budget Period Cloned', } ); my $budget_period_cloned = C4::Budgets::GetBudgetPeriod($budget_period_id_cloned); -is($budget_period_cloned->{budget_period_description}, 'Budget Period Cloned', 'Cloned budget\'s description is updated.'); - -my $budget_cloned = C4::Budgets::GetBudgets({ budget_period_id => $budget_period_id_cloned }); -my $budget_time = $budget_cloned->[0]->{timestamp}; - -isnt($budget_time, '1999-12-31 23:59:59', "New budget has an updated timestamp"); +is( + $budget_period_cloned->{budget_period_description}, 'Budget Period Cloned', + 'Cloned budget\'s description is updated.' +); +my $budget_cloned = C4::Budgets::GetBudgets( { budget_period_id => $budget_period_id_cloned } ); +my $budget_time = $budget_cloned->[0]->{timestamp}; +isnt( $budget_time, '1999-12-31 23:59:59', "New budget has an updated timestamp" ); my $budget_hierarchy = GetBudgetHierarchy($budget_period_id); my $budget_hierarchy_cloned = GetBudgetHierarchy($budget_period_id_cloned); @@ -562,7 +630,8 @@ is_deeply( # CloneBudgetPeriod with param mark_original_budget_as_inactive my $budget_period = C4::Budgets::GetBudgetPeriod($budget_period_id); -is( $budget_period->{budget_period_active}, 1, +is( + $budget_period->{budget_period_active}, 1, 'CloneBudgetPeriod does not mark as inactive the budgetperiod if not needed' ); @@ -571,8 +640,10 @@ my $number_of_budgets_not_reset = 0; for my $budget (@$budget_hierarchy_cloned) { $number_of_budgets_not_reset++ if $budget->{budget_amount} > 0; } -is( $number_of_budgets_not_reset, 5, - 'CloneBudgetPeriod does not reset budgets (funds) if not needed' ); +is( + $number_of_budgets_not_reset, 5, + 'CloneBudgetPeriod does not reset budgets (funds) if not needed' +); $budget_period_id_cloned = C4::Budgets::CloneBudgetPeriod( { @@ -583,29 +654,66 @@ $budget_period_id_cloned = C4::Budgets::CloneBudgetPeriod( } ); -$budget_hierarchy = GetBudgetHierarchy($budget_period_id); -is( $budget_hierarchy->[0]->{children}->[0]->{budget_name}, 'budget_11', 'GetBudgetHierarchy should return budgets ordered by name, first child is budget_11' ); -is( $budget_hierarchy->[0]->{children}->[1]->{budget_name}, 'budget_12', 'GetBudgetHierarchy should return budgets ordered by name, second child is budget_12' ); -is($budget_hierarchy->[0]->{budget_name},'budget_1','GetBudgetHierarchy should return budgets ordered by name, first budget is budget_1'); -is($budget_hierarchy->[0]->{budget_level},'0','budget_level of budget (budget_1) should be 0'); -is($budget_hierarchy->[0]->{children}->[0]->{budget_level},'1','budget_level of first fund(budget_11) should be 1'); -is($budget_hierarchy->[0]->{children}->[1]->{budget_level},'1','budget_level of second fund(budget_12) should be 1'); -is($budget_hierarchy->[0]->{children}->[0]->{children}->[0]->{budget_level},'2','budget_level of child fund budget_11 should be 2'); +$budget_hierarchy = GetBudgetHierarchy($budget_period_id); +is( + $budget_hierarchy->[0]->{children}->[0]->{budget_name}, 'budget_11', + 'GetBudgetHierarchy should return budgets ordered by name, first child is budget_11' +); +is( + $budget_hierarchy->[0]->{children}->[1]->{budget_name}, 'budget_12', + 'GetBudgetHierarchy should return budgets ordered by name, second child is budget_12' +); +is( + $budget_hierarchy->[0]->{budget_name}, 'budget_1', + 'GetBudgetHierarchy should return budgets ordered by name, first budget is budget_1' +); +is( $budget_hierarchy->[0]->{budget_level}, '0', 'budget_level of budget (budget_1) should be 0' ); +is( + $budget_hierarchy->[0]->{children}->[0]->{budget_level}, '1', + 'budget_level of first fund(budget_11) should be 1' +); +is( + $budget_hierarchy->[0]->{children}->[1]->{budget_level}, '1', + 'budget_level of second fund(budget_12) should be 1' +); +is( + $budget_hierarchy->[0]->{children}->[0]->{children}->[0]->{budget_level}, '2', + 'budget_level of child fund budget_11 should be 2' +); #Test skiptotals -$budget_hierarchy = GetBudgetHierarchy($budget_period_id, undef, undef, 1); -is( $budget_hierarchy->[0]->{children}->[0]->{budget_name}, 'budget_11', 'GetBudgetHierarchy skiptotals should return budgets ordered by name, first child is budget_11' ); -is( $budget_hierarchy->[0]->{children}->[1]->{budget_name}, 'budget_12', 'GetBudgetHierarchy skiptotals should return budgets ordered by name, second child is budget_12' ); -is($budget_hierarchy->[0]->{budget_name},'budget_1','GetBudgetHierarchy skiptotals should return budgets ordered by name, first budget is budget_1'); -is($budget_hierarchy->[0]->{budget_level},'0','skiptotals: budget_level of budget (budget_1) should be 0'); -is($budget_hierarchy->[0]->{children}->[0]->{budget_level},'1','skiptotals: budget_level of first fund(budget_11) should be 1'); -is($budget_hierarchy->[0]->{children}->[1]->{budget_level},'1','skiptotals: budget_level of second fund(budget_12) should be 1'); -is($budget_hierarchy->[0]->{children}->[0]->{children}->[0]->{budget_level},'2','skiptotals: budget_level of child fund budget_11 should be 2'); +$budget_hierarchy = GetBudgetHierarchy( $budget_period_id, undef, undef, 1 ); +is( + $budget_hierarchy->[0]->{children}->[0]->{budget_name}, 'budget_11', + 'GetBudgetHierarchy skiptotals should return budgets ordered by name, first child is budget_11' +); +is( + $budget_hierarchy->[0]->{children}->[1]->{budget_name}, 'budget_12', + 'GetBudgetHierarchy skiptotals should return budgets ordered by name, second child is budget_12' +); +is( + $budget_hierarchy->[0]->{budget_name}, 'budget_1', + 'GetBudgetHierarchy skiptotals should return budgets ordered by name, first budget is budget_1' +); +is( $budget_hierarchy->[0]->{budget_level}, '0', 'skiptotals: budget_level of budget (budget_1) should be 0' ); +is( + $budget_hierarchy->[0]->{children}->[0]->{budget_level}, '1', + 'skiptotals: budget_level of first fund(budget_11) should be 1' +); +is( + $budget_hierarchy->[0]->{children}->[1]->{budget_level}, '1', + 'skiptotals: budget_level of second fund(budget_12) should be 1' +); +is( + $budget_hierarchy->[0]->{children}->[0]->{children}->[0]->{budget_level}, '2', + 'skiptotals: budget_level of child fund budget_11 should be 2' +); $budget_hierarchy = GetBudgetHierarchy($budget_period_id); $budget_hierarchy_cloned = GetBudgetHierarchy($budget_period_id_cloned); -is( scalar(@$budget_hierarchy_cloned), scalar(@$budget_hierarchy), -'CloneBudgetPeriod (with inactive param) clones the same number of budgets (funds)' +is( + scalar(@$budget_hierarchy_cloned), scalar(@$budget_hierarchy), + 'CloneBudgetPeriod (with inactive param) clones the same number of budgets (funds)' ); is_deeply( _get_dependencies($budget_hierarchy), @@ -613,7 +721,8 @@ is_deeply( 'CloneBudgetPeriod (with inactive param) keeps the same dependencies order' ); $budget_period = C4::Budgets::GetBudgetPeriod($budget_period_id); -is( $budget_period->{budget_period_active}, 0, +is( + $budget_period->{budget_period_active}, 0, 'CloneBudgetPeriod (with inactive param) marks as inactive the budgetperiod' ); @@ -623,7 +732,7 @@ $budget_period_id_cloned = C4::Budgets::CloneBudgetPeriod( budget_period_id => $budget_period_id, budget_period_startdate => '2014-01-01', budget_period_enddate => '2014-12-31', - reset_all_budgets => 1, + reset_all_budgets => 1, } ); @@ -632,72 +741,93 @@ $number_of_budgets_not_reset = 0; for my $budget (@$budget_hierarchy_cloned) { $number_of_budgets_not_reset++ if $budget->{budget_amount} > 0; } -is( $number_of_budgets_not_reset, 0, - 'CloneBudgetPeriod has reset all budgets (funds)' ); +is( + $number_of_budgets_not_reset, 0, + 'CloneBudgetPeriod has reset all budgets (funds)' +); #GetBudgetsByActivity -my $result=C4::Budgets::GetBudgetsByActivity(1); -isnt( $result, undef ,'GetBudgetsByActivity return correct value with parameter 1'); -$result=C4::Budgets::GetBudgetsByActivity(0); - isnt( $result, undef ,'GetBudgetsByActivity return correct value with parameter 0'); -$result=C4::Budgets::GetBudgetsByActivity(); - is( $result, 0 , 'GetBudgetsByActivity return 0 with none parameter or other 0 or 1' ); +my $result = C4::Budgets::GetBudgetsByActivity(1); +isnt( $result, undef, 'GetBudgetsByActivity return correct value with parameter 1' ); +$result = C4::Budgets::GetBudgetsByActivity(0); +isnt( $result, undef, 'GetBudgetsByActivity return correct value with parameter 0' ); +$result = C4::Budgets::GetBudgetsByActivity(); +is( $result, 0, 'GetBudgetsByActivity return 0 with none parameter or other 0 or 1' ); DelBudget($budget_id); DelBudgetPeriod($bpid); # CloneBudgetPeriod with param amount_change_* $budget_period_id_cloned = C4::Budgets::CloneBudgetPeriod( { - budget_period_id => $budget_period_id, - budget_period_startdate => '2014-01-01', - budget_period_enddate => '2014-12-31', - amount_change_percentage => 16, + budget_period_id => $budget_period_id, + budget_period_startdate => '2014-01-01', + budget_period_enddate => '2014-12-31', + amount_change_percentage => 16, amount_change_round_increment => 5, } ); $budget_period_cloned = C4::Budgets::GetBudgetPeriod($budget_period_id_cloned); -cmp_ok($budget_period_cloned->{budget_period_total}, '==', 11600, "CloneBudgetPeriod changed correctly budget amount"); -$budget_hierarchy_cloned = GetBudgetHierarchy($budget_period_id_cloned); -cmp_ok($budget_hierarchy_cloned->[0]->{budget_amount}, '==', 1160, "CloneBudgetPeriod changed correctly funds amounts"); -cmp_ok($budget_hierarchy_cloned->[1]->{budget_amount}, '==', 115, "CloneBudgetPeriod changed correctly funds amounts"); -cmp_ok($budget_hierarchy_cloned->[2]->{budget_amount}, '==', 55, "CloneBudgetPeriod changed correctly funds amounts"); -cmp_ok($budget_hierarchy_cloned->[3]->{budget_amount}, '==', 115, "CloneBudgetPeriod changed correctly funds amounts"); -cmp_ok($budget_hierarchy_cloned->[4]->{budget_amount}, '==', 2320, "CloneBudgetPeriod changed correctly funds amounts"); -cmp_ok($budget_hierarchy_cloned->[5]->{budget_amount}, '==', 0, "CloneBudgetPeriod changed correctly funds amounts"); +cmp_ok( + $budget_period_cloned->{budget_period_total}, '==', 11600, + "CloneBudgetPeriod changed correctly budget amount" +); +$budget_hierarchy_cloned = GetBudgetHierarchy($budget_period_id_cloned); +cmp_ok( + $budget_hierarchy_cloned->[0]->{budget_amount}, '==', 1160, + "CloneBudgetPeriod changed correctly funds amounts" +); +cmp_ok( + $budget_hierarchy_cloned->[1]->{budget_amount}, '==', 115, + "CloneBudgetPeriod changed correctly funds amounts" +); +cmp_ok( $budget_hierarchy_cloned->[2]->{budget_amount}, '==', 55, "CloneBudgetPeriod changed correctly funds amounts" ); +cmp_ok( + $budget_hierarchy_cloned->[3]->{budget_amount}, '==', 115, + "CloneBudgetPeriod changed correctly funds amounts" +); +cmp_ok( + $budget_hierarchy_cloned->[4]->{budget_amount}, '==', 2320, + "CloneBudgetPeriod changed correctly funds amounts" +); +cmp_ok( $budget_hierarchy_cloned->[5]->{budget_amount}, '==', 0, "CloneBudgetPeriod changed correctly funds amounts" ); $budget_period_id_cloned = C4::Budgets::CloneBudgetPeriod( { - budget_period_id => $budget_period_id, - budget_period_startdate => '2014-01-01', - budget_period_enddate => '2014-12-31', - amount_change_percentage => 16, + budget_period_id => $budget_period_id, + budget_period_startdate => '2014-01-01', + budget_period_enddate => '2014-12-31', + amount_change_percentage => 16, amount_change_round_increment => 5, - reset_all_budgets => 1, + reset_all_budgets => 1, } ); -$budget_hierarchy_cloned = GetBudgetHierarchy($budget_period_id_cloned); -cmp_ok($budget_hierarchy_cloned->[0]->{budget_amount}, '==', 0, "CloneBudgetPeriod reset all fund amounts"); +$budget_hierarchy_cloned = GetBudgetHierarchy($budget_period_id_cloned); +cmp_ok( $budget_hierarchy_cloned->[0]->{budget_amount}, '==', 0, "CloneBudgetPeriod reset all fund amounts" ); # MoveOrders my $number_orders_moved = C4::Budgets::MoveOrders(); is( $number_orders_moved, undef, 'MoveOrders return undef if no arg passed' ); -$number_orders_moved = - C4::Budgets::MoveOrders( { from_budget_period_id => $budget_period_id } ); -is( $number_orders_moved, undef, - 'MoveOrders return undef if only 1 arg passed' ); -$number_orders_moved = - C4::Budgets::MoveOrders( { to_budget_period_id => $budget_period_id } ); -is( $number_orders_moved, undef, - 'MoveOrders return undef if only 1 arg passed' ); +$number_orders_moved = C4::Budgets::MoveOrders( { from_budget_period_id => $budget_period_id } ); +is( + $number_orders_moved, undef, + 'MoveOrders return undef if only 1 arg passed' +); +$number_orders_moved = C4::Budgets::MoveOrders( { to_budget_period_id => $budget_period_id } ); +is( + $number_orders_moved, undef, + 'MoveOrders return undef if only 1 arg passed' +); $number_orders_moved = C4::Budgets::MoveOrders( { from_budget_period_id => $budget_period_id, to_budget_period_id => $budget_period_id } ); -is( $number_orders_moved, undef, - 'MoveOrders return undef if 2 budget period id are the same' ); +is( + $number_orders_moved, undef, + 'MoveOrders return undef if 2 budget period id are the same' +); $budget_period_id_cloned = C4::Budgets::CloneBudgetPeriod( { @@ -714,16 +844,14 @@ my $report = C4::Budgets::MoveOrders( move_remaining_unspent => 1, } ); -is( scalar( @$report ), 6 , "MoveOrders has processed 6 funds" ); +is( scalar(@$report), 6, "MoveOrders has processed 6 funds" ); my $number_of_orders_moved = 0; $number_of_orders_moved += scalar( @{ $_->{orders_moved} } ) for @$report; is( $number_of_orders_moved, $number_of_orders_to_move, "MoveOrders has moved $number_of_orders_to_move orders" ); -my @new_budget_ids = map { $_->{budget_id} } - @{ C4::Budgets::GetBudgetHierarchy($budget_period_id_cloned) }; -my @old_budget_ids = map { $_->{budget_id} } - @{ C4::Budgets::GetBudgetHierarchy($budget_period_id) }; +my @new_budget_ids = map { $_->{budget_id} } @{ C4::Budgets::GetBudgetHierarchy($budget_period_id_cloned) }; +my @old_budget_ids = map { $_->{budget_id} } @{ C4::Budgets::GetBudgetHierarchy($budget_period_id) }; for my $budget_id ( keys %budgets ) { for my $ordernumber ( @{ $budgets{$budget_id} } ) { my $budget = GetBudgetByOrderNumber($ordernumber); @@ -734,102 +862,135 @@ for my $budget_id ( keys %budgets ) { } } - # MoveOrders with param move_remaining_unspent my @new_budgets = @{ C4::Budgets::GetBudgetHierarchy($budget_period_id_cloned) }; my @old_budgets = @{ C4::Budgets::GetBudgetHierarchy($budget_period_id) }; -for my $new_budget ( @new_budgets ) { - my ( $old_budget ) = map { $_->{budget_code} eq $new_budget->{budget_code} ? $_ : () } @old_budgets; +for my $new_budget (@new_budgets) { + my ($old_budget) = map { $_->{budget_code} eq $new_budget->{budget_code} ? $_ : () } @old_budgets; my $new_budget_amount_should_be = $old_budget->{budget_amount} * 2 - $old_budget->{total_spent}; - is( $new_budget->{budget_amount} + 0, $new_budget_amount_should_be, "MoveOrders updated the budget amount with the previous unspent budget (for budget $new_budget->{budget_code})" ); + is( + $new_budget->{budget_amount} + 0, $new_budget_amount_should_be, + "MoveOrders updated the budget amount with the previous unspent budget (for budget $new_budget->{budget_code})" + ); } # Test SetOwnerToFundHierarchy -my $patron_category = $builder->build({ source => 'Category' }); -my $branchcode = $library->{branchcode}; -my $john_doe = Koha::Patron->new({ - cardnumber => '123456', - firstname => 'John', - surname => 'Doe', - categorycode => $patron_category->{categorycode}, - branchcode => $branchcode, - dateofbirth => '', - dateexpiry => '9999-12-31', - userid => 'john.doe' -})->store->borrowernumber; +my $patron_category = $builder->build( { source => 'Category' } ); +my $branchcode = $library->{branchcode}; +my $john_doe = Koha::Patron->new( + { + cardnumber => '123456', + firstname => 'John', + surname => 'Doe', + categorycode => $patron_category->{categorycode}, + branchcode => $branchcode, + dateofbirth => '', + dateexpiry => '9999-12-31', + userid => 'john.doe' + } +)->store->borrowernumber; C4::Budgets::SetOwnerToFundHierarchy( $budget_id1, $john_doe ); -is( C4::Budgets::GetBudget($budget_id1)->{budget_owner_id}, - $john_doe, "SetOwnerToFundHierarchy should have set John Doe for budget 1 ($budget_id1)" ); -is( C4::Budgets::GetBudget($budget_id11)->{budget_owner_id}, - $john_doe, "SetOwnerToFundHierarchy should have set John Doe for budget 11 ($budget_id11)" ); -is( C4::Budgets::GetBudget($budget_id111)->{budget_owner_id}, - $john_doe, "SetOwnerToFundHierarchy should have set John Doe for budget 111 ($budget_id111)" ); -is( C4::Budgets::GetBudget($budget_id12)->{budget_owner_id}, - $john_doe, "SetOwnerToFundHierarchy should have set John Doe for budget 12 ($budget_id12 )" ); -is( C4::Budgets::GetBudget($budget_id2)->{budget_owner_id}, - undef, "SetOwnerToFundHierarchy should not have set an owner for budget 2 ($budget_id2)" ); -is( C4::Budgets::GetBudget($budget_id21)->{budget_owner_id}, - undef, "SetOwnerToFundHierarchy should not have set an owner for budget 21 ($budget_id21)" ); +is( + C4::Budgets::GetBudget($budget_id1)->{budget_owner_id}, + $john_doe, "SetOwnerToFundHierarchy should have set John Doe for budget 1 ($budget_id1)" +); +is( + C4::Budgets::GetBudget($budget_id11)->{budget_owner_id}, + $john_doe, "SetOwnerToFundHierarchy should have set John Doe for budget 11 ($budget_id11)" +); +is( + C4::Budgets::GetBudget($budget_id111)->{budget_owner_id}, + $john_doe, "SetOwnerToFundHierarchy should have set John Doe for budget 111 ($budget_id111)" +); +is( + C4::Budgets::GetBudget($budget_id12)->{budget_owner_id}, + $john_doe, "SetOwnerToFundHierarchy should have set John Doe for budget 12 ($budget_id12 )" +); +is( + C4::Budgets::GetBudget($budget_id2)->{budget_owner_id}, + undef, "SetOwnerToFundHierarchy should not have set an owner for budget 2 ($budget_id2)" +); +is( + C4::Budgets::GetBudget($budget_id21)->{budget_owner_id}, + undef, "SetOwnerToFundHierarchy should not have set an owner for budget 21 ($budget_id21)" +); -my $jane_doe = Koha::Patron->new({ - cardnumber => '789012', - firstname => 'Jane', - surname => 'Doe', - categorycode => $patron_category->{categorycode}, - branchcode => $branchcode, - dateofbirth => '', - dateexpiry => '9999-12-31', - userid => 'jane.doe' -})->store->borrowernumber; +my $jane_doe = Koha::Patron->new( + { + cardnumber => '789012', + firstname => 'Jane', + surname => 'Doe', + categorycode => $patron_category->{categorycode}, + branchcode => $branchcode, + dateofbirth => '', + dateexpiry => '9999-12-31', + userid => 'jane.doe' + } +)->store->borrowernumber; C4::Budgets::SetOwnerToFundHierarchy( $budget_id11, $jane_doe ); -is( C4::Budgets::GetBudget($budget_id1)->{budget_owner_id}, - $john_doe, "SetOwnerToFundHierarchy should have set John Doe $john_doe for budget 1 ($budget_id1)" ); -is( C4::Budgets::GetBudget($budget_id11)->{budget_owner_id}, - $jane_doe, "SetOwnerToFundHierarchy should have set John Doe $jane_doe for budget 11 ($budget_id11)" ); -is( C4::Budgets::GetBudget($budget_id111)->{budget_owner_id}, - $jane_doe, "SetOwnerToFundHierarchy should have set John Doe $jane_doe for budget 111 ($budget_id111)" ); -is( C4::Budgets::GetBudget($budget_id12)->{budget_owner_id}, - $john_doe, "SetOwnerToFundHierarchy should have set John Doe $john_doe for budget 12 ($budget_id12 )" ); -is( C4::Budgets::GetBudget($budget_id2)->{budget_owner_id}, - undef, "SetOwnerToFundHierarchy should have set John Doe $john_doe for budget 2 ($budget_id2)" ); -is( C4::Budgets::GetBudget($budget_id21)->{budget_owner_id}, - undef, "SetOwnerToFundHierarchy should have set John Doe $john_doe for budget 21 ($budget_id21)" ); +is( + C4::Budgets::GetBudget($budget_id1)->{budget_owner_id}, + $john_doe, "SetOwnerToFundHierarchy should have set John Doe $john_doe for budget 1 ($budget_id1)" +); +is( + C4::Budgets::GetBudget($budget_id11)->{budget_owner_id}, + $jane_doe, "SetOwnerToFundHierarchy should have set John Doe $jane_doe for budget 11 ($budget_id11)" +); +is( + C4::Budgets::GetBudget($budget_id111)->{budget_owner_id}, + $jane_doe, "SetOwnerToFundHierarchy should have set John Doe $jane_doe for budget 111 ($budget_id111)" +); +is( + C4::Budgets::GetBudget($budget_id12)->{budget_owner_id}, + $john_doe, "SetOwnerToFundHierarchy should have set John Doe $john_doe for budget 12 ($budget_id12 )" +); +is( + C4::Budgets::GetBudget($budget_id2)->{budget_owner_id}, + undef, "SetOwnerToFundHierarchy should have set John Doe $john_doe for budget 2 ($budget_id2)" +); +is( + C4::Budgets::GetBudget($budget_id21)->{budget_owner_id}, + undef, "SetOwnerToFundHierarchy should have set John Doe $john_doe for budget 21 ($budget_id21)" +); # Test GetBudgetAuthCats -my $budgetPeriodId = AddBudgetPeriod({ - budget_period_startdate => '2008-01-01', - budget_period_enddate => '2008-12-31', - budget_period_description => 'just another budget', - budget_period_active => 0, -}); +my $budgetPeriodId = AddBudgetPeriod( + { + budget_period_startdate => '2008-01-01', + budget_period_enddate => '2008-12-31', + budget_period_description => 'just another budget', + budget_period_active => 0, + } +); $budgets = GetBudgets(); my $i = 0; -for my $budget ( @$budgets ) -{ - $budget->{sort1_authcat} = "sort1_authcat_$i"; - $budget->{sort2_authcat} = "sort2_authcat_$i"; +for my $budget (@$budgets) { + $budget->{sort1_authcat} = "sort1_authcat_$i"; + $budget->{sort2_authcat} = "sort2_authcat_$i"; $budget->{budget_period_id} = $budgetPeriodId; - ModBudget( $budget ); + ModBudget($budget); $i++; } my $authCat = GetBudgetAuthCats($budgetPeriodId); -is( scalar @{$authCat}, $i * 2, "GetBudgetAuthCats returns only non-empty sorting categories (no empty authCat in db)" ); +is( + scalar @{$authCat}, $i * 2, + "GetBudgetAuthCats returns only non-empty sorting categories (no empty authCat in db)" +); $i = 0; -for my $budget ( @$budgets ) -{ - $budget->{sort1_authcat} = "sort_authcat_$i"; - $budget->{sort2_authcat} = "sort_authcat_$i"; +for my $budget (@$budgets) { + $budget->{sort1_authcat} = "sort_authcat_$i"; + $budget->{sort2_authcat} = "sort_authcat_$i"; $budget->{budget_period_id} = $budgetPeriodId; - ModBudget( $budget ); + ModBudget($budget); $i++; } @@ -837,26 +998,27 @@ $authCat = GetBudgetAuthCats($budgetPeriodId); is( scalar @$authCat, scalar @$budgets, "GetBudgetAuthCats returns distinct authCat" ); $i = 0; -for my $budget ( @$budgets ) -{ - $budget->{sort1_authcat} = "sort1_authcat_$i"; - $budget->{sort2_authcat} = ""; +for my $budget (@$budgets) { + $budget->{sort1_authcat} = "sort1_authcat_$i"; + $budget->{sort2_authcat} = ""; $budget->{budget_period_id} = $budgetPeriodId; - ModBudget( $budget ); + ModBudget($budget); $i++; } $authCat = GetBudgetAuthCats($budgetPeriodId); -is( scalar @{$authCat}, $i, "GetBudgetAuthCats returns only non-empty sorting categories (empty sort2_authcat on all records)" ); +is( + scalar @{$authCat}, $i, + "GetBudgetAuthCats returns only non-empty sorting categories (empty sort2_authcat on all records)" +); $i = 0; -for my $budget ( @$budgets ) -{ - $budget->{sort1_authcat} = ""; - $budget->{sort2_authcat} = ""; +for my $budget (@$budgets) { + $budget->{sort1_authcat} = ""; + $budget->{sort2_authcat} = ""; $budget->{budget_period_id} = $budgetPeriodId; - ModBudget( $budget ); + ModBudget($budget); $i++; } @@ -869,174 +1031,244 @@ is( scalar @{$authCat}, 0, "GetBudgetAuthCats returns only non-empty sorting cat subtest 'GetBudgetSpent and GetBudgetOrdered and GetBudgetHierarchy shipping and adjustments' => sub { plan tests => 26; - my $budget_period = $builder->build({ - source => 'Aqbudgetperiod', - value => { - budget_period_active => 1, - budget_period_total => 10000, + my $budget_period = $builder->build( + { + source => 'Aqbudgetperiod', + value => { + budget_period_active => 1, + budget_period_total => 10000, + } } - }); - my $budget = $builder->build({ - source => 'Aqbudget', - value => { - budget_amount => 1000, - budget_encumb => undef, - budget_expend => undef, - budget_period_id => $budget_period->{budget_period_id}, - budget_parent_id => undef, + ); + my $budget = $builder->build( + { + source => 'Aqbudget', + value => { + budget_amount => 1000, + budget_encumb => undef, + budget_expend => undef, + budget_period_id => $budget_period->{budget_period_id}, + budget_parent_id => undef, + } } - }); - my $invoice = $builder->build({ - source => 'Aqinvoice', - value => { - closedate => undef, + ); + my $invoice = $builder->build( + { + source => 'Aqinvoice', + value => { + closedate => undef, + } } - }); + ); my $spent = GetBudgetSpent( $budget->{budget_id} ); my $ordered = GetBudgetOrdered( $budget->{budget_id} ); - my $hierarchy = GetBudgetHierarchy($budget_period->{budget_period_id} ); + my $hierarchy = GetBudgetHierarchy( $budget_period->{budget_period_id} ); - is( $spent, 0, "New budget, no orders/invoices, should be nothing spent"); - is( $ordered, 0, "New budget, no orders/invoices, should be nothing ordered"); - is( @$hierarchy[0]->{total_spent},0,"New budgets, no orders/invoices, budget hierarchy shows 0 spent"); - is( @$hierarchy[0]->{total_ordered},0,"New budgets, no orders/invoices, budget hierarchy shows 0 ordered"); + is( $spent, 0, "New budget, no orders/invoices, should be nothing spent" ); + is( $ordered, 0, "New budget, no orders/invoices, should be nothing ordered" ); + is( @$hierarchy[0]->{total_spent}, 0, "New budgets, no orders/invoices, budget hierarchy shows 0 spent" ); + is( @$hierarchy[0]->{total_ordered}, 0, "New budgets, no orders/invoices, budget hierarchy shows 0 ordered" ); - my $inv_adj_1 = $builder->build({ - source => 'AqinvoiceAdjustment', - value => { - invoiceid => $invoice->{invoiceid}, - adjustment => 3, - encumber_open => 0, - budget_id => $budget->{budget_id}, + my $inv_adj_1 = $builder->build( + { + source => 'AqinvoiceAdjustment', + value => { + invoiceid => $invoice->{invoiceid}, + adjustment => 3, + encumber_open => 0, + budget_id => $budget->{budget_id}, + } } - }); + ); - $spent = GetBudgetSpent( $budget->{budget_id} ); + $spent = GetBudgetSpent( $budget->{budget_id} ); + $ordered = GetBudgetOrdered( $budget->{budget_id} ); + $hierarchy = GetBudgetHierarchy( $budget_period->{budget_period_id} ); + is( $spent, 0, "After adding invoice adjustment on open invoice, should be nothing spent" ); + is( $ordered, 0, "After adding invoice adjustment on open invoice not encumbered, should be nothing ordered" ); + is( + @$hierarchy[0]->{total_spent}, 0, + "After adding invoice adjustment on open invoice, budget hierarchy shows 0 spent" + ); + is( + @$hierarchy[0]->{total_ordered}, 0, + "After adding invoice adjustment on open invoice, budget hierarchy shows 0 ordered" + ); + + my $inv_adj_2 = $builder->build( + { + source => 'AqinvoiceAdjustment', + value => { + invoiceid => $invoice->{invoiceid}, + adjustment => 3, + encumber_open => 1, + budget_id => $budget->{budget_id}, + } + } + ); + + $spent = GetBudgetSpent( $budget->{budget_id} ); + $ordered = GetBudgetOrdered( $budget->{budget_id} ); + $hierarchy = GetBudgetHierarchy( $budget_period->{budget_period_id} ); + is( $spent, 0, "After adding invoice adjustment on open invoice, should be nothing spent" ); + is( $ordered, 3, "After adding invoice adjustment on open invoice encumbered, should be 3 ordered" ); + is( + @$hierarchy[0]->{total_spent}, 0, + "After adding invoice adjustment on open invoice encumbered, budget hierarchy shows 0 spent" + ); + is( + @$hierarchy[0]->{total_ordered}, 3, + "After adding invoice adjustment on open invoice encumbered, budget hierarchy shows 3 ordered" + ); + + my $invoice_2 = $builder->build( + { + source => 'Aqinvoice', + value => { + closedate => '2017-07-01', + } + } + ); + my $inv_adj_3 = $builder->build( + { + source => 'AqinvoiceAdjustment', + value => { + invoiceid => $invoice_2->{invoiceid}, + adjustment => 3, + encumber_open => 0, + budget_id => $budget->{budget_id}, + } + } + ); + my $inv_adj_4 = $builder->build( + { + source => 'AqinvoiceAdjustment', + value => { + invoiceid => $invoice_2->{invoiceid}, + adjustment => 3, + encumber_open => 1, + budget_id => $budget->{budget_id}, + } + } + ); + + $spent = GetBudgetSpent( $budget->{budget_id} ); + $ordered = GetBudgetOrdered( $budget->{budget_id} ); + $hierarchy = GetBudgetHierarchy( $budget_period->{budget_period_id} ); + is( + $spent, 6, + "After adding invoice adjustment on closed invoice, should be 6 spent, encumber has no affect once closed" + ); + is( $ordered, 3, "After adding invoice adjustment on closed invoice, should still be 3 ordered" ); + is( + @$hierarchy[0]->{total_spent}, 6, + "After adding invoice adjustment on closed invoice, budget hierarchy shows 6 spent" + ); + is( + @$hierarchy[0]->{total_ordered}, 3, + "After adding invoice adjustment on closed invoice, budget hierarchy still shows 3 ordered" + ); + + my $budget0 = $builder->build( + { + source => 'Aqbudget', + value => { + budget_amount => 1000, + budget_encumb => undef, + budget_expend => undef, + budget_period_id => $budget_period->{budget_period_id}, + budget_parent_id => $budget->{budget_id}, + } + } + ); + my $inv_adj_5 = $builder->build( + { + source => 'AqinvoiceAdjustment', + value => { + invoiceid => $invoice->{invoiceid}, + adjustment => 3, + encumber_open => 1, + budget_id => $budget0->{budget_id}, + } + } + ); + my $inv_adj_6 = $builder->build( + { + source => 'AqinvoiceAdjustment', + value => { + invoiceid => $invoice_2->{invoiceid}, + adjustment => 3, + encumber_open => 1, + budget_id => $budget0->{budget_id}, + } + } + ); + + $spent = GetBudgetSpent( $budget->{budget_id} ); + $ordered = GetBudgetOrdered( $budget->{budget_id} ); + $hierarchy = GetBudgetHierarchy( $budget_period->{budget_period_id} ); + is( $spent, 6, "After adding invoice adjustment on a child budget should be 6 spent/budget unaffected" ); + is( $ordered, 3, "After adding invoice adjustment on a child budget, should still be 3 ordered/budget unaffected" ); + is( + @$hierarchy[0]->{total_spent}, 9, + "After adding invoice adjustment on child budget, budget hierarchy shows 9 spent" + ); + is( + @$hierarchy[0]->{total_ordered}, 6, + "After adding invoice adjustment on child budget, budget hierarchy shows 6 ordered" + ); + + my $invoice_3 = $builder->build( + { + source => 'Aqinvoice', + value => { + closedate => '2017-07-01', + shipmentcost_budgetid => $budget0->{budget_id}, + shipmentcost => 1.25 + } + } + ); + my $invoice_4 = $builder->build( + { + source => 'Aqinvoice', + value => { + closedate => undef, + shipmentcost_budgetid => $budget0->{budget_id}, + shipmentcost => 1.75 + } + } + ); + + $spent = GetBudgetSpent( $budget->{budget_id} ); $ordered = GetBudgetOrdered( $budget->{budget_id} ); - $hierarchy = GetBudgetHierarchy($budget_period->{budget_period_id} ); - is( $spent, 0, "After adding invoice adjustment on open invoice, should be nothing spent"); - is( $ordered, 0, "After adding invoice adjustment on open invoice not encumbered, should be nothing ordered"); - is( @$hierarchy[0]->{total_spent},0,"After adding invoice adjustment on open invoice, budget hierarchy shows 0 spent"); - is( @$hierarchy[0]->{total_ordered},0,"After adding invoice adjustment on open invoice, budget hierarchy shows 0 ordered"); - - my $inv_adj_2 = $builder->build({ - source => 'AqinvoiceAdjustment', - value => { - invoiceid => $invoice->{invoiceid}, - adjustment => 3, - encumber_open => 1, - budget_id => $budget->{budget_id}, - } - }); - - $spent = GetBudgetSpent( $budget->{budget_id} ); - $ordered = GetBudgetOrdered( $budget->{budget_id} ); - $hierarchy = GetBudgetHierarchy($budget_period->{budget_period_id} ); - is( $spent, 0, "After adding invoice adjustment on open invoice, should be nothing spent"); - is( $ordered, 3, "After adding invoice adjustment on open invoice encumbered, should be 3 ordered"); - is( @$hierarchy[0]->{total_spent},0,"After adding invoice adjustment on open invoice encumbered, budget hierarchy shows 0 spent"); - is( @$hierarchy[0]->{total_ordered},3,"After adding invoice adjustment on open invoice encumbered, budget hierarchy shows 3 ordered"); - - my $invoice_2 = $builder->build({ - source => 'Aqinvoice', - value => { - closedate => '2017-07-01', - } - }); - my $inv_adj_3 = $builder->build({ - source => 'AqinvoiceAdjustment', - value => { - invoiceid => $invoice_2->{invoiceid}, - adjustment => 3, - encumber_open => 0, - budget_id => $budget->{budget_id}, - } - }); - my $inv_adj_4 = $builder->build({ - source => 'AqinvoiceAdjustment', - value => { - invoiceid => $invoice_2->{invoiceid}, - adjustment => 3, - encumber_open => 1, - budget_id => $budget->{budget_id}, - } - }); - - $spent = GetBudgetSpent( $budget->{budget_id} ); - $ordered = GetBudgetOrdered( $budget->{budget_id} ); - $hierarchy = GetBudgetHierarchy($budget_period->{budget_period_id} ); - is( $spent, 6, "After adding invoice adjustment on closed invoice, should be 6 spent, encumber has no affect once closed"); - is( $ordered, 3, "After adding invoice adjustment on closed invoice, should still be 3 ordered"); - is( @$hierarchy[0]->{total_spent},6,"After adding invoice adjustment on closed invoice, budget hierarchy shows 6 spent"); - is( @$hierarchy[0]->{total_ordered},3,"After adding invoice adjustment on closed invoice, budget hierarchy still shows 3 ordered"); - - my $budget0 = $builder->build({ - source => 'Aqbudget', - value => { - budget_amount => 1000, - budget_encumb => undef, - budget_expend => undef, - budget_period_id => $budget_period->{budget_period_id}, - budget_parent_id => $budget->{budget_id}, - } - }); - my $inv_adj_5 = $builder->build({ - source => 'AqinvoiceAdjustment', - value => { - invoiceid => $invoice->{invoiceid}, - adjustment => 3, - encumber_open => 1, - budget_id => $budget0->{budget_id}, - } - }); - my $inv_adj_6 = $builder->build({ - source => 'AqinvoiceAdjustment', - value => { - invoiceid => $invoice_2->{invoiceid}, - adjustment => 3, - encumber_open => 1, - budget_id => $budget0->{budget_id}, - } - }); - - $spent = GetBudgetSpent( $budget->{budget_id} ); - $ordered = GetBudgetOrdered( $budget->{budget_id} ); - $hierarchy = GetBudgetHierarchy($budget_period->{budget_period_id} ); - is( $spent, 6, "After adding invoice adjustment on a child budget should be 6 spent/budget unaffected"); - is( $ordered, 3, "After adding invoice adjustment on a child budget, should still be 3 ordered/budget unaffected"); - is( @$hierarchy[0]->{total_spent},9,"After adding invoice adjustment on child budget, budget hierarchy shows 9 spent"); - is( @$hierarchy[0]->{total_ordered},6,"After adding invoice adjustment on child budget, budget hierarchy shows 6 ordered"); - - my $invoice_3 = $builder->build({ - source => 'Aqinvoice', - value => { - closedate => '2017-07-01', - shipmentcost_budgetid => $budget0->{budget_id}, - shipmentcost => 1.25 - } - }); - my $invoice_4 = $builder->build({ - source => 'Aqinvoice', - value => { - closedate => undef, - shipmentcost_budgetid => $budget0->{budget_id}, - shipmentcost => 1.75 - } - }); - - $spent = GetBudgetSpent( $budget->{budget_id} ); - $ordered = GetBudgetOrdered( $budget->{budget_id} ); - is( $spent, 6, "After adding invoice shipment cost on open and closed invoice on child, neither are counted as spent from parent"); - is( $ordered, 3, "After adding invoice shipment cost on open and closed invoice, neither are counted as ordered from parent"); - $spent = GetBudgetSpent( $budget0->{budget_id} ); + is( + $spent, 6, + "After adding invoice shipment cost on open and closed invoice on child, neither are counted as spent from parent" + ); + is( + $ordered, 3, + "After adding invoice shipment cost on open and closed invoice, neither are counted as ordered from parent" + ); + $spent = GetBudgetSpent( $budget0->{budget_id} ); $ordered = GetBudgetOrdered( $budget0->{budget_id} ); - is( $spent, 6, "After adding invoice shipment cost on open and closed invoice on child, both are counted as spent from child"); - is( $ordered, 3, "After adding invoice shipment cost on open and closed invoice, neither are counted as ordered from child"); - $hierarchy = GetBudgetHierarchy($budget_period->{budget_period_id} ); - is( @$hierarchy[0]->{total_spent},12,"After adding shipmentcost on child, budget hierarchy shows 12 spent total"); - is( @$hierarchy[0]->{total_ordered},6,"After adding shipmentcost on child, budget hierarchy still shows 6 ordered total"); - + is( + $spent, 6, + "After adding invoice shipment cost on open and closed invoice on child, both are counted as spent from child" + ); + is( + $ordered, 3, + "After adding invoice shipment cost on open and closed invoice, neither are counted as ordered from child" + ); + $hierarchy = GetBudgetHierarchy( $budget_period->{budget_period_id} ); + is( + @$hierarchy[0]->{total_spent}, 12, + "After adding shipmentcost on child, budget hierarchy shows 12 spent total" + ); + is( + @$hierarchy[0]->{total_ordered}, 6, + "After adding shipmentcost on child, budget hierarchy still shows 6 ordered total" + ); }; @@ -1044,29 +1276,47 @@ subtest 'GetBudgetSpent GetBudgetOrdered GetBudgetsPlanCell tests' => sub { plan tests => 24; -#Let's build an order, we need a couple things though - t::lib::Mocks::mock_preference('OrderPriceRounding','nearest_cent'); + #Let's build an order, we need a couple things though + t::lib::Mocks::mock_preference( 'OrderPriceRounding', 'nearest_cent' ); my $item_1 = $builder->build_sample_item; - my $spent_basket = $builder->build({ source => 'Aqbasket', value => { is_standing => 0 } }); - my $spent_invoice = $builder->build({ source => 'Aqinvoice'}); - my $spent_currency = $builder->build({ source => 'Currency', value => { active => 1, archived => 0, symbol => 'F', rate => 2, isocode => undef, currency => 'FOO' } }); - my $spent_vendor = $builder->build({ source => 'Aqbookseller',value => { listincgst => 0, listprice => $spent_currency->{currency}, invoiceprice => $spent_currency->{currency} } }); - my $budget_authcat = $builder->build({ source => 'AuthorisedValueCategory', value => {} }); - my $spent_sort1 = $builder->build({ source => 'AuthorisedValue', value => { - category => $budget_authcat->{category_name}, - authorised_value => 'PICKLE', + my $spent_basket = $builder->build( { source => 'Aqbasket', value => { is_standing => 0 } } ); + my $spent_invoice = $builder->build( { source => 'Aqinvoice' } ); + my $spent_currency = $builder->build( + { + source => 'Currency', + value => { active => 1, archived => 0, symbol => 'F', rate => 2, isocode => undef, currency => 'FOO' } } - }); - my $spent_budget_period = $builder->build({ source => 'Aqbudgetperiod', value => { + ); + my $spent_vendor = $builder->build( + { + source => 'Aqbookseller', + value => { + listincgst => 0, listprice => $spent_currency->{currency}, invoiceprice => $spent_currency->{currency} + } } - }); - my $spent_budget = $builder->build({ source => 'Aqbudget', value => { - sort1_authcat => $budget_authcat->{category_name}, - budget_period_id => $spent_budget_period->{budget_period_id}, - budget_parent_id => undef, + ); + my $budget_authcat = $builder->build( { source => 'AuthorisedValueCategory', value => {} } ); + my $spent_sort1 = $builder->build( + { + source => 'AuthorisedValue', + value => { + category => $budget_authcat->{category_name}, + authorised_value => 'PICKLE', + } } - }); + ); + my $spent_budget_period = $builder->build( { source => 'Aqbudgetperiod', value => {} } ); + my $spent_budget = $builder->build( + { + source => 'Aqbudget', + value => { + sort1_authcat => $budget_authcat->{category_name}, + budget_period_id => $spent_budget_period->{budget_period_id}, + budget_parent_id => undef, + } + } + ); my $spent_orderinfo = { basketno => $spent_basket->{basketno}, booksellerid => $spent_vendor->{id}, @@ -1087,66 +1337,80 @@ subtest 'GetBudgetSpent GetBudgetOrdered GetBudgetsPlanCell tests' => sub { sort1 => $spent_sort1->{authorised_value}, }; -#Okay we have basically what the user would enter, now we do some maths + #Okay we have basically what the user would enter, now we do some maths my $spent_order_obj = Koha::Acquisition::Order->new($spent_orderinfo); $spent_order_obj->populate_with_prices_for_ordering(); $spent_orderinfo = $spent_order_obj->unblessed(); -#And let's place the order - my $spent_order = $builder->build({ source => 'Aqorder', value => $spent_orderinfo }); - t::lib::Mocks::mock_preference('OrderPriceRounding',''); + #And let's place the order + my $spent_order = $builder->build( { source => 'Aqorder', value => $spent_orderinfo } ); + t::lib::Mocks::mock_preference( 'OrderPriceRounding', '' ); my $spent_ordered = GetBudgetOrdered( $spent_order->{budget_id} ); - is($spent_orderinfo->{ecost_tax_excluded}, 9.854200,'We store extra precision in price calculation'); - is( Koha::Number::Price->new($spent_orderinfo->{ecost_tax_excluded})->format(), 9.85,'But the price as formatted is two digits'); - is($spent_ordered,'78.8336',"We expect the ordered amount to be equal to the estimated price times quantity with full precision"); + is( $spent_orderinfo->{ecost_tax_excluded}, 9.854200, 'We store extra precision in price calculation' ); + is( + Koha::Number::Price->new( $spent_orderinfo->{ecost_tax_excluded} )->format(), 9.85, + 'But the price as formatted is two digits' + ); + is( + $spent_ordered, '78.8336', + "We expect the ordered amount to be equal to the estimated price times quantity with full precision" + ); - t::lib::Mocks::mock_preference('OrderPriceRounding','nearest_cent'); + t::lib::Mocks::mock_preference( 'OrderPriceRounding', 'nearest_cent' ); $spent_ordered = GetBudgetOrdered( $spent_order->{budget_id} ); - is($spent_ordered,'78.8',"We expect the ordered amount to be equal to the estimated price rounded times quantity"); + is( + $spent_ordered, '78.8', + "We expect the ordered amount to be equal to the estimated price rounded times quantity" + ); #Test GetBudgetHierarchy for rounding - t::lib::Mocks::mock_preference('OrderPriceRounding',''); - my $gbh = GetBudgetHierarchy($spent_budget->{budget_period_id}); - is ( @$gbh[0]->{budget_spent}+0, 0, "We expect this to be an exact order cost * quantity"); - is ( @$gbh[0]->{budget_ordered}+0, 78.8336, "We expect this to be an exact order cost * quantity"); - t::lib::Mocks::mock_preference('OrderPriceRounding','nearest_cent'); - $gbh = GetBudgetHierarchy($spent_budget->{budget_period_id}); - is ( @$gbh[0]->{budget_spent}+0, 0, "We expect this to be an rounded order cost * quantity"); - is ( @$gbh[0]->{budget_ordered}+0, 78.8, "We expect this to be an exact order cost * quantity"); + t::lib::Mocks::mock_preference( 'OrderPriceRounding', '' ); + my $gbh = GetBudgetHierarchy( $spent_budget->{budget_period_id} ); + is( @$gbh[0]->{budget_spent} + 0, 0, "We expect this to be an exact order cost * quantity" ); + is( @$gbh[0]->{budget_ordered} + 0, 78.8336, "We expect this to be an exact order cost * quantity" ); + t::lib::Mocks::mock_preference( 'OrderPriceRounding', 'nearest_cent' ); + $gbh = GetBudgetHierarchy( $spent_budget->{budget_period_id} ); + is( @$gbh[0]->{budget_spent} + 0, 0, "We expect this to be an rounded order cost * quantity" ); + is( @$gbh[0]->{budget_ordered} + 0, 78.8, "We expect this to be an exact order cost * quantity" ); -#Let's test some budget planning -#Regression tests for bug 18736 + #Let's test some budget planning + #Regression tests for bug 18736 #We need an item to test by BRANCHES - my $order_item_1 = $builder->build({ source => 'AqordersItem', value => { ordernumber => $spent_order->{ordernumber}, itemnumber => $item_1->itemnumber } }); + my $order_item_1 = $builder->build( + { + source => 'AqordersItem', + value => { ordernumber => $spent_order->{ordernumber}, itemnumber => $item_1->itemnumber } + } + ); my $spent_fund = Koha::Acquisition::Funds->find( $spent_order->{budget_id} ); - my $cell = { - authcat => 'MONTHS', - cell_authvalue => $spent_order->{entrydate}, #normally this is just the year/month but full won't hurt us here - budget_id => $spent_order->{budget_id}, + my $cell = { + authcat => 'MONTHS', + cell_authvalue => $spent_order->{entrydate}, #normally this is just the year/month but full won't hurt us here + budget_id => $spent_order->{budget_id}, budget_period_id => $spent_fund->budget_period_id, - sort1_authcat => $spent_order->{sort1_authcat}, - sort2_authcat => $spent_order->{sort1_authcat}, + sort1_authcat => $spent_order->{sort1_authcat}, + sort2_authcat => $spent_order->{sort1_authcat}, }; my $test_values = { 'MONTHS' => { - authvalue => $spent_order->{entrydate}, + authvalue => $spent_order->{entrydate}, expected_rounded => 9.85, expected_exact => 9.8542, }, 'BRANCHES' => { - authvalue => $item_1->homebranch, + authvalue => $item_1->homebranch, expected_rounded => 9.85, expected_exact => 9.8542, }, 'ITEMTYPES' => { - authvalue => $item_1->biblioitem->itemtype, + authvalue => $item_1->biblioitem->itemtype, expected_rounded => 78.80, expected_exact => 78.8336, }, 'ELSE' => { - authvalue => $spent_sort1->{authorised_value}, + authvalue => $spent_sort1->{authorised_value}, expected_rounded => 78.8, expected_exact => 78.8336, }, @@ -1157,57 +1421,67 @@ subtest 'GetBudgetSpent GetBudgetOrdered GetBudgetsPlanCell tests' => sub { my $authvalue = $test_val->{authvalue}; my $expected_rounded = $test_val->{expected_rounded}; my $expected_exact = $test_val->{expected_exact}; - $cell->{authcat} = $authcat; + $cell->{authcat} = $authcat; $cell->{authvalue} = $authvalue; - t::lib::Mocks::mock_preference('OrderPriceRounding',''); - my ( $actual ) = GetBudgetsPlanCell( $cell, undef, $spent_budget); #we are only testing the actual for now - is ( $actual+0, $expected_exact, "We expect this to be an exact order cost ($authcat)"); #really we should expect cost*quantity but we don't - t::lib::Mocks::mock_preference('OrderPriceRounding','nearest_cent'); - ( $actual ) = GetBudgetsPlanCell( $cell, undef, $spent_budget); #we are only testing the actual for now - is ( $actual+0, $expected_rounded, "We expect this to be a rounded order cost ($authcat)"); #really we should expect cost*quantity but we don't + t::lib::Mocks::mock_preference( 'OrderPriceRounding', '' ); + my ($actual) = GetBudgetsPlanCell( $cell, undef, $spent_budget ); #we are only testing the actual for now + is( $actual + 0, $expected_exact, "We expect this to be an exact order cost ($authcat)" ) + ; #really we should expect cost*quantity but we don't + t::lib::Mocks::mock_preference( 'OrderPriceRounding', 'nearest_cent' ); + ($actual) = GetBudgetsPlanCell( $cell, undef, $spent_budget ); #we are only testing the actual for now + is( $actual + 0, $expected_rounded, "We expect this to be a rounded order cost ($authcat)" ) + ; #really we should expect cost*quantity but we don't } -#Okay, now we can receive the order, giving the price as the user would + #Okay, now we can receive the order, giving the price as the user would - $spent_orderinfo->{unitprice} = 9.85; #we are paying what we expected + $spent_orderinfo->{unitprice} = 9.85; #we are paying what we expected -#Do our maths + #Do our maths $spent_order_obj = Koha::Acquisition::Order->new($spent_orderinfo); $spent_order_obj->populate_with_prices_for_receiving(); $spent_orderinfo = $spent_order_obj->unblessed(); - my $received_order = $builder->build({ source => 'Aqorder', value => $spent_orderinfo }); + my $received_order = $builder->build( { source => 'Aqorder', value => $spent_orderinfo } ); -#And receive a copy of the order so we have both spent and ordered values + #And receive a copy of the order so we have both spent and ordered values - ModReceiveOrder({ - biblionumber => $spent_order->{biblionumber}, - order => $received_order, - invoice => $spent_invoice, + ModReceiveOrder( + { + biblionumber => $spent_order->{biblionumber}, + order => $received_order, + invoice => $spent_invoice, quantityreceived => $spent_order->{quantity}, - budget_id => $spent_order->{budget_id}, - received_items => [], - }); + budget_id => $spent_order->{budget_id}, + received_items => [], + } + ); - t::lib::Mocks::mock_preference('OrderPriceRounding',''); + t::lib::Mocks::mock_preference( 'OrderPriceRounding', '' ); my $spent_spent = GetBudgetSpent( $spent_order->{budget_id} ); - is($spent_orderinfo->{unitprice_tax_excluded}, 9.854200,'We store extra precision in price calculation'); - is( Koha::Number::Price->new($spent_orderinfo->{unitprice_tax_excluded})->format(), 9.85,'But the price as formatted is two digits'); - is($spent_spent,'78.8336',"We expect the spent amount to be equal to the estimated price times quantity with full precision"); + is( $spent_orderinfo->{unitprice_tax_excluded}, 9.854200, 'We store extra precision in price calculation' ); + is( + Koha::Number::Price->new( $spent_orderinfo->{unitprice_tax_excluded} )->format(), 9.85, + 'But the price as formatted is two digits' + ); + is( + $spent_spent, '78.8336', + "We expect the spent amount to be equal to the estimated price times quantity with full precision" + ); - t::lib::Mocks::mock_preference('OrderPriceRounding','nearest_cent'); + t::lib::Mocks::mock_preference( 'OrderPriceRounding', 'nearest_cent' ); $spent_spent = GetBudgetSpent( $spent_order->{budget_id} ); - is($spent_spent,'78.8',"We expect the spent amount to be equal to the estimated price rounded times quantity"); + is( $spent_spent, '78.8', "We expect the spent amount to be equal to the estimated price rounded times quantity" ); #Test GetBudgetHierarchy for rounding - t::lib::Mocks::mock_preference('OrderPriceRounding',''); - $gbh = GetBudgetHierarchy($spent_budget->{budget_period_id}); - is ( @$gbh[0]->{budget_spent}, 78.8336, "We expect this to be an exact order cost * quantity"); - is ( @$gbh[0]->{budget_ordered}, 78.8336, "We expect this to be an exact order cost * quantity"); - t::lib::Mocks::mock_preference('OrderPriceRounding','nearest_cent'); - $gbh = GetBudgetHierarchy($spent_budget->{budget_period_id}); - is ( @$gbh[0]->{budget_spent}+0, 78.8, "We expect this to be a rounded order cost * quantity"); - is ( @$gbh[0]->{budget_ordered}, 78.8, "We expect this to be a rounded order cost * quantity"); + t::lib::Mocks::mock_preference( 'OrderPriceRounding', '' ); + $gbh = GetBudgetHierarchy( $spent_budget->{budget_period_id} ); + is( @$gbh[0]->{budget_spent}, 78.8336, "We expect this to be an exact order cost * quantity" ); + is( @$gbh[0]->{budget_ordered}, 78.8336, "We expect this to be an exact order cost * quantity" ); + t::lib::Mocks::mock_preference( 'OrderPriceRounding', 'nearest_cent' ); + $gbh = GetBudgetHierarchy( $spent_budget->{budget_period_id} ); + is( @$gbh[0]->{budget_spent} + 0, 78.8, "We expect this to be a rounded order cost * quantity" ); + is( @$gbh[0]->{budget_ordered}, 78.8, "We expect this to be a rounded order cost * quantity" ); $schema->storage->txn_rollback; }; @@ -1337,37 +1611,56 @@ subtest 'FieldsForCalculatingFundValues with a vendor NOT including tax in their }; # Bug 31631 -subtest 'FieldsForCalculatingFundValues with a vendor that IS including tax in their list and invoice prices tests' => sub { +subtest 'FieldsForCalculatingFundValues with a vendor that IS including tax in their list and invoice prices tests' => + sub { plan tests => 10; $schema->storage->txn_begin; # Test FieldsForCalculatingFundValues() - t::lib::Mocks::mock_preference('CalculateFundValuesIncludingTax', '1'); + t::lib::Mocks::mock_preference( 'CalculateFundValuesIncludingTax', '1' ); my ( $unitprice_field, $ecost_field ) = C4::Budgets->FieldsForCalculatingFundValues(); - is ( $unitprice_field, 'unitprice_tax_included', "We expect this to be unitprice_tax_included" ); - is ( $ecost_field, 'ecost_tax_included', "We expect this to be ecost_tax_included" ); - t::lib::Mocks::mock_preference('CalculateFundValuesIncludingTax', '0'); + is( $unitprice_field, 'unitprice_tax_included', "We expect this to be unitprice_tax_included" ); + is( $ecost_field, 'ecost_tax_included', "We expect this to be ecost_tax_included" ); + t::lib::Mocks::mock_preference( 'CalculateFundValuesIncludingTax', '0' ); ( $unitprice_field, $ecost_field ) = C4::Budgets->FieldsForCalculatingFundValues(); - is ( $unitprice_field, 'unitprice_tax_excluded', "We expect this to be unitprice_tax_excluded" ); - is ( $ecost_field, 'ecost_tax_excluded', "We expect this to be ecost_tax_excluded" ); + is( $unitprice_field, 'unitprice_tax_excluded', "We expect this to be unitprice_tax_excluded" ); + is( $ecost_field, 'ecost_tax_excluded', "We expect this to be ecost_tax_excluded" ); # Test GetBudgetOrdered() # ----------------------- # Build an order - t::lib::Mocks::mock_preference('OrderPriceRounding','nearest_cent'); - my $item_1 = $builder->build_sample_item; - my $invoice = $builder->build({ source => 'Aqinvoice'}); - my $currency = $builder->build({ source => 'Currency', value => { active => 1, archived => 0, symbol => 'F', rate => 2, isocode => undef, currency => 'BOO' } }); - my $vendor = $builder->build({ source => 'Aqbookseller',value => { listincgst => 1, invoiceincgst => 1, listprice => $currency->{currency}, invoiceprice => $currency->{currency} } }); - my $basket = $builder->build({ source => 'Aqbasket', value => { is_standing => 0, booksellerid => $vendor->{id} } }); - my $budget_period = $builder->build({ source => 'Aqbudgetperiod' }); - my $budget = $builder->build({ source => 'Aqbudget', value => { - budget_period_id => $budget_period->{budget_period_id}, - budget_parent_id => undef, + t::lib::Mocks::mock_preference( 'OrderPriceRounding', 'nearest_cent' ); + my $item_1 = $builder->build_sample_item; + my $invoice = $builder->build( { source => 'Aqinvoice' } ); + my $currency = $builder->build( + { + source => 'Currency', + value => { active => 1, archived => 0, symbol => 'F', rate => 2, isocode => undef, currency => 'BOO' } } - }); + ); + my $vendor = $builder->build( + { + source => 'Aqbookseller', + value => { + listincgst => 1, invoiceincgst => 1, listprice => $currency->{currency}, + invoiceprice => $currency->{currency} + } + } + ); + my $basket = + $builder->build( { source => 'Aqbasket', value => { is_standing => 0, booksellerid => $vendor->{id} } } ); + my $budget_period = $builder->build( { source => 'Aqbudgetperiod' } ); + my $budget = $builder->build( + { + source => 'Aqbudget', + value => { + budget_period_id => $budget_period->{budget_period_id}, + budget_parent_id => undef, + } + } + ); my $orderdata = { basketno => $basket->{basketno}, booksellerid => $vendor->{id}, @@ -1393,52 +1686,54 @@ subtest 'FieldsForCalculatingFundValues with a vendor that IS including tax in t $orderdata = $order->unblessed(); # Place the order - $order = $builder->build({ source => 'Aqorder', value => $orderdata }); + $order = $builder->build( { source => 'Aqorder', value => $orderdata } ); # Check order values with different CalculateFundValuesIncludingTax options - t::lib::Mocks::mock_preference('CalculateFundValuesIncludingTax', '0'); + t::lib::Mocks::mock_preference( 'CalculateFundValuesIncludingTax', '0' ); my $budget_ordered = GetBudgetOrdered( $order->{budget_id} ); - is ( $budget_ordered, 8.7, "We expect this to be the tax exclusive value" ); - t::lib::Mocks::mock_preference('CalculateFundValuesIncludingTax', '1'); + is( $budget_ordered, 8.7, "We expect this to be the tax exclusive value" ); + t::lib::Mocks::mock_preference( 'CalculateFundValuesIncludingTax', '1' ); $budget_ordered = GetBudgetOrdered( $order->{budget_id} ); - is ( $budget_ordered, 10, "We expect this to be the tax inclusive value" ); + is( $budget_ordered, 10, "We expect this to be the tax inclusive value" ); # Test GetBudgetSpent() and GetBudgetHierarchy() # ----------------------------------------------- # Receive the order - $orderdata->{unitprice} = 10; #we are paying what we expected + $orderdata->{unitprice} = 10; #we are paying what we expected # Do some maths $order = Koha::Acquisition::Order->new($orderdata); $order->populate_with_prices_for_receiving(); $orderdata = $order->unblessed(); - my $received_order = $builder->build({ source => 'Aqorder', value => $orderdata }); + my $received_order = $builder->build( { source => 'Aqorder', value => $orderdata } ); # Receive a copy of the order - ModReceiveOrder({ - biblionumber => $orderdata->{biblionumber}, - order => $received_order, - invoice => $invoice, + ModReceiveOrder( + { + biblionumber => $orderdata->{biblionumber}, + order => $received_order, + invoice => $invoice, quantityreceived => 1, - budget_id => $orderdata->{budget_id}, - received_items => [], - }); + budget_id => $orderdata->{budget_id}, + received_items => [], + } + ); - t::lib::Mocks::mock_preference('CalculateFundValuesIncludingTax', '0'); + t::lib::Mocks::mock_preference( 'CalculateFundValuesIncludingTax', '0' ); my $spent_amount = GetBudgetSpent( $orderdata->{budget_id} ); - is ( $spent_amount, 8.7, "We expect this to be the tax exclusive value" ); - my $gbh = GetBudgetHierarchy($budget->{budget_period_id}); - is ( @$gbh[0]->{budget_spent}, 8.7, "We expect this value to be the tax exclusive value"); + is( $spent_amount, 8.7, "We expect this to be the tax exclusive value" ); + my $gbh = GetBudgetHierarchy( $budget->{budget_period_id} ); + is( @$gbh[0]->{budget_spent}, 8.7, "We expect this value to be the tax exclusive value" ); - t::lib::Mocks::mock_preference('CalculateFundValuesIncludingTax', '1'); + t::lib::Mocks::mock_preference( 'CalculateFundValuesIncludingTax', '1' ); $spent_amount = GetBudgetSpent( $orderdata->{budget_id} ); - is ( $spent_amount, 10, "We expect this to be the tax inclusive value" ); - $gbh = GetBudgetHierarchy($budget->{budget_period_id}); - is ( @$gbh[0]->{budget_spent}, 10, "We expect this value to be the tax inclusive value"); + is( $spent_amount, 10, "We expect this to be the tax inclusive value" ); + $gbh = GetBudgetHierarchy( $budget->{budget_period_id} ); + is( @$gbh[0]->{budget_spent}, 10, "We expect this value to be the tax inclusive value" ); $schema->storage->txn_rollback; -}; + }; sub _get_dependencies { my ($budget_hierarchy) = @_; @@ -1448,11 +1743,11 @@ sub _get_dependencies { my @sorted = sort @{ $budget->{child} }; for my $child_id (@sorted) { push @{ $graph->{ $budget->{budget_name} }{children} }, - _get_budgetname_by_id( $budget_hierarchy, $child_id ); + _get_budgetname_by_id( $budget_hierarchy, $child_id ); } } push @{ $graph->{ $budget->{budget_name} }{parents} }, - $budget->{parent_id}; + $budget->{parent_id}; } return $graph; } @@ -1460,7 +1755,6 @@ sub _get_dependencies { sub _get_budgetname_by_id { my ( $budgets, $budget_id ) = @_; my ($budget_name) = - map { ( $_->{budget_id} eq $budget_id ) ? $_->{budget_name} : () } - @$budgets; + map { ( $_->{budget_id} eq $budget_id ) ? $_->{budget_name} : () } @$budgets; return $budget_name; } diff --git a/t/db_dependent/Budgets/CloneBudgetHierarchy.t b/t/db_dependent/Budgets/CloneBudgetHierarchy.t index be221dcb00..570d63bcf4 100755 --- a/t/db_dependent/Budgets/CloneBudgetHierarchy.t +++ b/t/db_dependent/Budgets/CloneBudgetHierarchy.t @@ -14,7 +14,7 @@ use t::lib::TestBuilder; plan tests => 1; -my $schema = Koha::Database->schema; +my $schema = Koha::Database->schema; my $builder = t::lib::TestBuilder->new; subtest 'CloneBudgetHierarchy should clone budget users too' => sub { @@ -22,10 +22,10 @@ subtest 'CloneBudgetHierarchy should clone budget users too' => sub { $schema->txn_begin; my $aqbudgetperiod_rs = $schema->resultset('Aqbudgetperiod'); - my $budget_1 = Koha::Acquisition::Budget->new( + my $budget_1 = Koha::Acquisition::Budget->new( { budget_period_startdate => '2000-01-01', - budget_period_enddate => '2999-12-31', + budget_period_enddate => '2999-12-31', } )->store; @@ -35,28 +35,31 @@ subtest 'CloneBudgetHierarchy should clone budget users too' => sub { } )->store; - my $patron_1 = $builder->build_object({ class => 'Koha::Patrons' }); - my $patron_2 = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron_1 = $builder->build_object( { class => 'Koha::Patrons' } ); + my $patron_2 = $builder->build_object( { class => 'Koha::Patrons' } ); - C4::Budgets::ModBudgetUsers($budget_1_fund_1->id, $patron_1->id, $patron_2->id); + C4::Budgets::ModBudgetUsers( $budget_1_fund_1->id, $patron_1->id, $patron_2->id ); my $budget_2 = Koha::Acquisition::Budget->new( { budget_period_startdate => '2000-01-01', - budget_period_enddate => '2999-12-31', + budget_period_enddate => '2999-12-31', } )->store; CloneBudgetHierarchy( { - budgets => C4::Budgets::GetBudgetHierarchy($budget_1->id), + budgets => C4::Budgets::GetBudgetHierarchy( $budget_1->id ), new_budget_period_id => $budget_2->id, } ); - my @funds = Koha::Acquisition::Funds->search({ budget_period_id => $budget_2->id })->as_list; - my @borrowernumbers = C4::Budgets::GetBudgetUsers($funds[0]->id); - is_deeply(\@borrowernumbers, [$patron_1->id, $patron_2->id], 'cloned budget has the same users as the original'); + my @funds = Koha::Acquisition::Funds->search( { budget_period_id => $budget_2->id } )->as_list; + my @borrowernumbers = C4::Budgets::GetBudgetUsers( $funds[0]->id ); + is_deeply( + \@borrowernumbers, [ $patron_1->id, $patron_2->id ], + 'cloned budget has the same users as the original' + ); $schema->txn_rollback; }; diff --git a/t/db_dependent/Cache.t b/t/db_dependent/Cache.t index e47393f22c..1e313366b1 100755 --- a/t/db_dependent/Cache.t +++ b/t/db_dependent/Cache.t @@ -33,15 +33,17 @@ BEGIN { SKIP: { # Set a special namespace for testing, to avoid breaking # if test is run with a different user than Apache's. - $ENV{ MEMCACHED_NAMESPACE } = 'unit_tests'; + $ENV{MEMCACHED_NAMESPACE} = 'unit_tests'; my $cache = Koha::Caches->get_instance(); skip "Cache not enabled", 36 - unless ( $cache->is_cache_active() && defined $cache ); + unless ( $cache->is_cache_active() && defined $cache ); # test fetching an item that isnt in the cache - is( $cache->get_from_cache("not in here"), - undef, "fetching item NOT in cache" ); + is( + $cache->get_from_cache("not in here"), + undef, "fetching item NOT in cache" + ); # set_in_cache should not warn my $warn; @@ -54,17 +56,18 @@ SKIP: { } # test expiry time in cache - $cache->set_in_cache( "timeout", "I AM DATA", { expiry => 1 } ); # expiry time of 1 second + $cache->set_in_cache( "timeout", "I AM DATA", { expiry => 1 } ); # expiry time of 1 second sleep 2; $cache->flush_L1_cache(); - is( $cache->get_from_cache("timeout"), - undef, "fetching expired item from cache" ); + is( + $cache->get_from_cache("timeout"), + undef, "fetching expired item from cache" + ); # test fetching a valid, non expired, item from cache - $cache->set_in_cache( "clear_me", "I AM MORE DATA", { expiry => 1000 } ) - ; # overly large expiry time, clear below + $cache->set_in_cache( "clear_me", "I AM MORE DATA", { expiry => 1000 } ); # overly large expiry time, clear below $cache->set_in_cache( "dont_clear_me", "I AM MORE DATA22", { expiry => 1000 } ) - ; # overly large expiry time, clear below + ; # overly large expiry time, clear below is( $cache->get_from_cache("clear_me"), "I AM MORE DATA", @@ -73,8 +76,10 @@ SKIP: { # test clearing from cache $cache->clear_from_cache("clear_me"); - is( $cache->get_from_cache("clear_me"), - undef, "fetching cleared item from cache" ); + is( + $cache->get_from_cache("clear_me"), + undef, "fetching cleared item from cache" + ); is( $cache->get_from_cache("dont_clear_me"), "I AM MORE DATA22", @@ -84,10 +89,14 @@ SKIP: { #test flushing from cache $cache->set_in_cache( "flush_me", "testing 1 data" ); $cache->flush_all; - is( $cache->get_from_cache("flush_me"), - undef, "fetching flushed item from cache" ); - is( $cache->get_from_cache("dont_clear_me"), - undef, "fetching flushed item from cache" ); + is( + $cache->get_from_cache("flush_me"), + undef, "fetching flushed item from cache" + ); + is( + $cache->get_from_cache("dont_clear_me"), + undef, "fetching flushed item from cache" + ); my $constructorcount = 0; my $myscalar = $cache->create_scalar( @@ -112,112 +121,132 @@ SKIP: { is( $constructorcount, 2, 'Constructor not called after storing value' ); undef $myscalar; - is( $cache->get_from_cache("myscalar"), - undef, 'Item removed from cache on destruction' ); + is( + $cache->get_from_cache("myscalar"), + undef, 'Item removed from cache on destruction' + ); my %hash = ( 'key' => 'value' ); - my $myhash = $cache->create_hash( + my $myhash = $cache->create_hash( { 'key' => 'myhash', 'timeout' => 1, 'allowupdate' => 1, 'unset' => 1, - 'constructor' => sub { return { %hash }; }, + 'constructor' => sub { return {%hash}; }, } ); - ok(defined $myhash, 'Created tied hash'); + ok( defined $myhash, 'Created tied hash' ); - is($myhash->{'key'}, 'value', 'Found expected value in hash'); - ok(exists $myhash->{'key'}, 'Exists works'); + is( $myhash->{'key'}, 'value', 'Found expected value in hash' ); + ok( exists $myhash->{'key'}, 'Exists works' ); $myhash->{'key2'} = 'surprise'; - is($myhash->{'key2'}, 'surprise', 'Setting hash member worked'); + is( $myhash->{'key2'}, 'surprise', 'Setting hash member worked' ); $hash{'key2'} = 'nosurprise'; sleep 2; $cache->flush_L1_cache(); - is($myhash->{'key2'}, 'nosurprise', 'Cache change caught'); - + is( $myhash->{'key2'}, 'nosurprise', 'Cache change caught' ); my $foundkeys = 0; - foreach my $key (keys %{$myhash}) { + foreach my $key ( keys %{$myhash} ) { $foundkeys++; } - is($foundkeys, 2, 'Found expected 2 keys when iterating through hash'); + is( $foundkeys, 2, 'Found expected 2 keys when iterating through hash' ); - isnt(scalar %{$myhash}, undef, 'scalar knows the hash is not empty'); + isnt( scalar %{$myhash}, undef, 'scalar knows the hash is not empty' ); $hash{'anotherkey'} = 'anothervalue'; sleep 2; $cache->flush_L1_cache(); - ok(exists $myhash->{'anotherkey'}, 'Cache reset properly'); + ok( exists $myhash->{'anotherkey'}, 'Cache reset properly' ); delete $hash{'anotherkey'}; delete $myhash->{'anotherkey'}; - ok(!exists $myhash->{'anotherkey'}, 'Key successfully deleted'); + ok( !exists $myhash->{'anotherkey'}, 'Key successfully deleted' ); undef %hash; %{$myhash} = (); - is(scalar %{$myhash}, 0, 'hash cleared'); + is( scalar %{$myhash}, 0, 'hash cleared' ); $hash{'key'} = 'value'; - is($myhash->{'key'}, 'value', 'retrieved value after clearing cache'); + is( $myhash->{'key'}, 'value', 'retrieved value after clearing cache' ); # UTF8 testing my $utf8_str = "A Møøse once bit my sister"; - $cache->set_in_cache('utf8_1', $utf8_str); - is($cache->get_from_cache('utf8_1'), $utf8_str, 'Simple 8-bit UTF8 correctly retrieved'); - $utf8_str = "\x{20ac}"; # € - $cache->set_in_cache('utf8_1', $utf8_str); + $cache->set_in_cache( 'utf8_1', $utf8_str ); + is( $cache->get_from_cache('utf8_1'), $utf8_str, 'Simple 8-bit UTF8 correctly retrieved' ); + $utf8_str = "\x{20ac}"; # € + $cache->set_in_cache( 'utf8_1', $utf8_str ); my $utf8_res = $cache->get_from_cache('utf8_1'); + # This'll ensure that we're getting a unicode string back, rather than # a couple of bytes. - is(length($utf8_res), 1, 'UTF8 string length correct'); + is( length($utf8_res), 1, 'UTF8 string length correct' ); + # ...and that it's really the character we intend - is(ord($utf8_res), 8364, 'UTF8 string value correct'); + is( ord($utf8_res), 8364, 'UTF8 string value correct' ); # Make sure the item will be deep copied # Scalar my $item = "just a simple scalar"; - $cache->set_in_cache('test_deep_copy', $item); + $cache->set_in_cache( 'test_deep_copy', $item ); my $item_from_cache = $cache->get_from_cache('test_deep_copy'); $item_from_cache = "a modified scalar"; - is( $cache->get_from_cache('test_deep_copy'), 'just a simple scalar', 'A scalar will not be modified in the cache if get from the cache' ); + is( + $cache->get_from_cache('test_deep_copy'), 'just a simple scalar', + 'A scalar will not be modified in the cache if get from the cache' + ); + # Array my @item = qw( an array ref ); - $cache->set_in_cache('test_deep_copy_array', \@item); - $item_from_cache = $cache->get_from_cache('test_deep_copy_array'); + $cache->set_in_cache( 'test_deep_copy_array', \@item ); + $item_from_cache = $cache->get_from_cache('test_deep_copy_array'); @$item_from_cache = qw( another array ref ); - is_deeply( $cache->get_from_cache('test_deep_copy_array'), [ qw ( an array ref ) ], 'An array will be deep copied'); + is_deeply( $cache->get_from_cache('test_deep_copy_array'), [qw ( an array ref )], 'An array will be deep copied' ); $cache->flush_L1_cache(); - $item_from_cache = $cache->get_from_cache('test_deep_copy_array'); + $item_from_cache = $cache->get_from_cache('test_deep_copy_array'); @$item_from_cache = qw( another array ref ); - is_deeply( $cache->get_from_cache('test_deep_copy_array'), [ qw ( an array ref ) ], 'An array will be deep copied even it is the first fetch from L2'); + is_deeply( + $cache->get_from_cache('test_deep_copy_array'), [qw ( an array ref )], + 'An array will be deep copied even it is the first fetch from L2' + ); - $item_from_cache = $cache->get_from_cache('test_deep_copy_array', { unsafe => 1 }); + $item_from_cache = $cache->get_from_cache( 'test_deep_copy_array', { unsafe => 1 } ); @$item_from_cache = qw( another array ref ); - is_deeply( $cache->get_from_cache('test_deep_copy_array', { unsafe => 1 }), [ qw ( another array ref ) ], 'An array will not be deep copied if the unsafe flag is set'); + is_deeply( + $cache->get_from_cache( 'test_deep_copy_array', { unsafe => 1 } ), [qw ( another array ref )], + 'An array will not be deep copied if the unsafe flag is set' + ); + # Hash my %item = ( a => 'hashref' ); - $cache->set_in_cache('test_deep_copy_hash', \%item); - $item_from_cache = $cache->get_from_cache('test_deep_copy_hash'); + $cache->set_in_cache( 'test_deep_copy_hash', \%item ); + $item_from_cache = $cache->get_from_cache('test_deep_copy_hash'); %$item_from_cache = ( another => 'hashref' ); - is_deeply( $cache->get_from_cache('test_deep_copy_hash'), { a => 'hashref' }, 'A hash will be deep copied'); + is_deeply( $cache->get_from_cache('test_deep_copy_hash'), { a => 'hashref' }, 'A hash will be deep copied' ); %item = ( a_modified => 'hashref' ); - is_deeply( $cache->get_from_cache('test_deep_copy_hash'), { a => 'hashref' }, 'A hash will be deep copied when set in cache'); + is_deeply( + $cache->get_from_cache('test_deep_copy_hash'), { a => 'hashref' }, + 'A hash will be deep copied when set in cache' + ); %item = ( a => 'hashref' ); - $cache->set_in_cache('test_deep_copy_hash', \%item); - $item_from_cache = $cache->get_from_cache('test_deep_copy_hash', { unsafe => 1 }); + $cache->set_in_cache( 'test_deep_copy_hash', \%item ); + $item_from_cache = $cache->get_from_cache( 'test_deep_copy_hash', { unsafe => 1 } ); %$item_from_cache = ( another => 'hashref' ); - is_deeply( $cache->get_from_cache('test_deep_copy_hash', { unsafe => 1 }), { another => 'hashref' }, 'A hash will not be deep copied if the unsafe flag is set'); + is_deeply( + $cache->get_from_cache( 'test_deep_copy_hash', { unsafe => 1 } ), { another => 'hashref' }, + 'A hash will not be deep copied if the unsafe flag is set' + ); } subtest 'Koha::Cache::Memory::Lite' => sub { @@ -225,13 +254,15 @@ subtest 'Koha::Cache::Memory::Lite' => sub { my $memory_cache = Koha::Cache::Memory::Lite->get_instance(); # test fetching an item that isnt in the cache - is( $memory_cache->get_from_cache("not in here"), - undef, "fetching item NOT in cache" ); + is( + $memory_cache->get_from_cache("not in here"), + undef, "fetching item NOT in cache" + ); # test fetching a valid item from cache - $memory_cache->set_in_cache( "clear_me", "I AM MORE DATA" ); + $memory_cache->set_in_cache( "clear_me", "I AM MORE DATA" ); $memory_cache->set_in_cache( "dont_clear_me", "I AM MORE DATA22" ); - ; # overly large expiry time, clear below + ; # overly large expiry time, clear below is( $memory_cache->get_from_cache("clear_me"), "I AM MORE DATA", @@ -240,8 +271,10 @@ subtest 'Koha::Cache::Memory::Lite' => sub { # test clearing from cache $memory_cache->clear_from_cache("clear_me"); - is( $memory_cache->get_from_cache("clear_me"), - undef, "fetching cleared item from cache" ); + is( + $memory_cache->get_from_cache("clear_me"), + undef, "fetching cleared item from cache" + ); is( $memory_cache->get_from_cache("dont_clear_me"), "I AM MORE DATA22", @@ -251,20 +284,24 @@ subtest 'Koha::Cache::Memory::Lite' => sub { #test flushing from cache $memory_cache->set_in_cache( "flush_me", "testing 1 data" ); $memory_cache->flush; - is( $memory_cache->get_from_cache("flush_me"), - undef, "fetching flushed item from cache" ); - is( $memory_cache->get_from_cache("dont_clear_me"), - undef, "fetching flushed item from cache" ); + is( + $memory_cache->get_from_cache("flush_me"), + undef, "fetching flushed item from cache" + ); + is( + $memory_cache->get_from_cache("dont_clear_me"), + undef, "fetching flushed item from cache" + ); }; subtest 'Koha::Caches' => sub { plan tests => 8; my $default_cache = Koha::Caches->get_instance(); my $another_cache = Koha::Caches->get_instance('another_cache'); - $default_cache->set_in_cache('key_a', 'value_a'); - $default_cache->set_in_cache('key_b', 'value_b'); - $another_cache->set_in_cache('key_a', 'another_value_a'); - $another_cache->set_in_cache('key_b', 'another_value_b'); + $default_cache->set_in_cache( 'key_a', 'value_a' ); + $default_cache->set_in_cache( 'key_b', 'value_b' ); + $another_cache->set_in_cache( 'key_a', 'another_value_a' ); + $another_cache->set_in_cache( 'key_b', 'another_value_b' ); is( $default_cache->get_from_cache('key_a'), 'value_a' ); is( $another_cache->get_from_cache('key_a'), 'another_value_a' ); is( $default_cache->get_from_cache('key_b'), 'value_b' ); @@ -278,11 +315,11 @@ subtest 'Koha::Caches' => sub { }; END { - SKIP: { - $ENV{ MEMCACHED_NAMESPACE } = 'unit_tests'; +SKIP: { + $ENV{MEMCACHED_NAMESPACE} = 'unit_tests'; my $cache = Koha::Caches->get_instance(); skip "Cache not enabled", 1 - unless ( $cache->is_cache_active() ); + unless ( $cache->is_cache_active() ); is( $destructorcount, 1, 'Destructor run exactly once' ); } } diff --git a/t/db_dependent/Calendar.t b/t/db_dependent/Calendar.t index 40b99bc795..90dc45bbe2 100755 --- a/t/db_dependent/Calendar.t +++ b/t/db_dependent/Calendar.t @@ -53,12 +53,12 @@ subtest 'Original tests from t' => sub { } ); - my $mpl = $builder->build_object( { class => 'Koha::Libraries' } )->branchcode; - my $cpl = $builder->build_object( { class => 'Koha::Libraries' } )->branchcode; + my $mpl = $builder->build_object( { class => 'Koha::Libraries' } )->branchcode; + my $cpl = $builder->build_object( { class => 'Koha::Libraries' } )->branchcode; my $rows = [ # add weekly holidays { branchcode => $mpl, weekday => 0 }, # sundays { branchcode => $mpl, weekday => 6 }, # saturdays - { branchcode => $mpl, day => 1, month => 1 }, # new year's day + { branchcode => $mpl, day => 1, month => 1 }, # new year's day { branchcode => $mpl, day => 25, month => 12 }, # chrismas ]; $schema->resultset('RepeatableHoliday')->delete_all; diff --git a/t/db_dependent/Charset.t b/t/db_dependent/Charset.t index 420b38641e..c1a0236fdd 100755 --- a/t/db_dependent/Charset.t +++ b/t/db_dependent/Charset.t @@ -14,38 +14,42 @@ my $dbh = C4::Context->dbh; my $frameworkcode = q||; -$dbh->do(q| +$dbh->do( + q| DELETE FROM marc_subfield_structure WHERE kohafield='biblioitems.url' -|); -$dbh->do(qq| +| +); +$dbh->do( + qq| INSERT INTO marc_subfield_structure(frameworkcode,kohafield,tagfield,tagsubfield) VALUES ('$frameworkcode', 'biblioitems.url', '856', 'u') -|); -my ( $url_field, $url_subfield ) = C4::Biblio::GetMarcFromKohaField( 'biblioitems.url' ); +| +); +my ( $url_field, $url_subfield ) = C4::Biblio::GetMarcFromKohaField('biblioitems.url'); -my $title = q|My title & a word & another word|; -my $url = q|http://www.example.org/index.pl?arg1=val1&arg2=val2|; +my $title = q|My title & a word & another word|; +my $url = q|http://www.example.org/index.pl?arg1=val1&arg2=val2|; my $record = MARC::Record->new(); $record->append_fields( - MARC::Field->new('100', ' ', ' ', a => 'my author'), - MARC::Field->new('245', ' ', ' ', a => $title), - MARC::Field->new($url_field, ' ', ' ', $url_subfield => $url ), + MARC::Field->new( '100', ' ', ' ', a => 'my author' ), + MARC::Field->new( '245', ' ', ' ', a => $title ), + MARC::Field->new( $url_field, ' ', ' ', $url_subfield => $url ), ); -my ($biblionumber, $biblioitemnumber) = AddBiblio($record, $frameworkcode); +my ( $biblionumber, $biblioitemnumber ) = AddBiblio( $record, $frameworkcode ); my ( $sanitized_record, $has_been_modified ) = C4::Charset::SanitizeRecord( $record, $biblionumber ); is( $has_been_modified, 0, 'SanitizeRecord: the record has not been modified' ); -is( $url, $sanitized_record->subfield($url_field, $url_subfield), 'SanitizeRecord: the url has not been modified'); +is( $url, $sanitized_record->subfield( $url_field, $url_subfield ), 'SanitizeRecord: the url has not been modified' ); -$title = q|My title &amp;amp; a word &amp; another word|; +$title = q|My title &amp;amp; a word &amp; another word|; $record = MARC::Record->new(); $record->append_fields( - MARC::Field->new('100', ' ', ' ', a => 'my author'), - MARC::Field->new('245', ' ', ' ', a => $title), - MARC::Field->new($url_field, ' ', ' ', $url_subfield => $url ), + MARC::Field->new( '100', ' ', ' ', a => 'my author' ), + MARC::Field->new( '245', ' ', ' ', a => $title ), + MARC::Field->new( $url_field, ' ', ' ', $url_subfield => $url ), ); -($biblionumber, $biblioitemnumber) = AddBiblio($record, $frameworkcode); +( $biblionumber, $biblioitemnumber ) = AddBiblio( $record, $frameworkcode ); ( $sanitized_record, $has_been_modified ) = C4::Charset::SanitizeRecord( $record, $biblionumber ); -is( $has_been_modified, 1, 'SanitizeRecord: the record has been modified' ); -is( $url, $sanitized_record->subfield($url_field, $url_subfield), 'SanitizeRecord: the url has not been modified'); +is( $has_been_modified, 1, 'SanitizeRecord: the record has been modified' ); +is( $url, $sanitized_record->subfield( $url_field, $url_subfield ), 'SanitizeRecord: the url has not been modified' ); diff --git a/t/db_dependent/Circulation.t b/t/db_dependent/Circulation.t index ce38277610..d3e7dea4f6 100755 --- a/t/db_dependent/Circulation.t +++ b/t/db_dependent/Circulation.t @@ -33,14 +33,15 @@ use t::lib::TestBuilder; use C4::Accounts; use C4::Calendar qw( new insert_single_holiday insert_week_day_holiday delete_holiday ); -use C4::Circulation qw( AddIssue AddReturn CanBookBeRenewed GetIssuingCharges AddRenewal GetSoonestRenewDate GetLatestAutoRenewDate LostItem GetUpcomingDueIssues CanBookBeIssued AddIssuingCharge MarkIssueReturned ProcessOfflinePayment transferbook ); +use C4::Circulation + qw( AddIssue AddReturn CanBookBeRenewed GetIssuingCharges AddRenewal GetSoonestRenewDate GetLatestAutoRenewDate LostItem GetUpcomingDueIssues CanBookBeIssued AddIssuingCharge MarkIssueReturned ProcessOfflinePayment transferbook ); use C4::Biblio; use C4::Items qw( ModItemTransfer ); use C4::Log; -use C4::Reserves qw( AddReserve ModReserve ModReserveCancelAll ModReserveAffect CheckReserves ); -use C4::Overdues qw( CalcFine UpdateFine get_chargeable_units ); +use C4::Reserves qw( AddReserve ModReserve ModReserveCancelAll ModReserveAffect CheckReserves ); +use C4::Overdues qw( CalcFine UpdateFine get_chargeable_units ); use C4::Members::Messaging qw( SetMessagingPreference ); -use Koha::DateUtils qw( dt_from_string output_pref ); +use Koha::DateUtils qw( dt_from_string output_pref ); use Koha::Database; use Koha::Bookings; use Koha::Items; @@ -58,28 +59,29 @@ use Koha::Notice::Messages; use Koha::Cache::Memory::Lite; my $builder = t::lib::TestBuilder->new; + sub set_userenv { - my ( $library ) = @_; - my $staff = $builder->build_object({ class => "Koha::Patrons" }); - t::lib::Mocks::mock_userenv({ patron => $staff, branchcode => $library->{branchcode} }); + my ($library) = @_; + my $staff = $builder->build_object( { class => "Koha::Patrons" } ); + t::lib::Mocks::mock_userenv( { patron => $staff, branchcode => $library->{branchcode} } ); } sub str { my ( $error, $question, $alert ) = @_; my $s; - $s = %$error ? ' (error: ' . join( ' ', keys %$error ) . ')' : ''; + $s = %$error ? ' (error: ' . join( ' ', keys %$error ) . ')' : ''; $s .= %$question ? ' (question: ' . join( ' ', keys %$question ) . ')' : ''; - $s .= %$alert ? ' (alert: ' . join( ' ', keys %$alert ) . ')' : ''; + $s .= %$alert ? ' (alert: ' . join( ' ', keys %$alert ) . ')' : ''; return $s; } sub test_debarment_on_checkout { - my ($params) = @_; - my $item = $params->{item}; - my $library = $params->{library}; - my $patron = $params->{patron}; - my $due_date = $params->{due_date} || dt_from_string; - my $return_date = $params->{return_date} || dt_from_string; + my ($params) = @_; + my $item = $params->{item}; + my $library = $params->{library}; + my $patron = $params->{patron}; + my $due_date = $params->{due_date} || dt_from_string; + my $return_date = $params->{return_date} || dt_from_string; my $expected_expiration_date = $params->{expiration_date}; $expected_expiration_date = output_pref( @@ -95,16 +97,17 @@ sub test_debarment_on_checkout { my ( undef, $message ) = AddReturn( $item->barcode, $library->{branchcode}, undef, $return_date ); is( $message->{WasReturned} && exists $message->{Debarred}, 1, 'AddReturn must have debarred the patron' ) - or diag('AddReturn returned message ' . Dumper $message ); - my $suspensions = $patron->restrictions->search({ type => 'SUSPENSION' } ); + or diag( 'AddReturn returned message ' . Dumper $message ); + my $suspensions = $patron->restrictions->search( { type => 'SUSPENSION' } ); is( $suspensions->count, 1, 'Test at line ' . $line_number ); my $THE_suspension = $suspensions->next; - is( $THE_suspension->expiration, - $expected_expiration_date, 'Test at line ' . $line_number ); - Koha::Patron::Debarments::DelUniqueDebarment( - { borrowernumber => $patron->borrowernumber, type => 'SUSPENSION' } ); -}; + is( + $THE_suspension->expiration, + $expected_expiration_date, 'Test at line ' . $line_number + ); + Koha::Patron::Debarments::DelUniqueDebarment( { borrowernumber => $patron->borrowernumber, type => 'SUSPENSION' } ); +} my $schema = Koha::Database->schema; $schema->storage->txn_begin; @@ -129,16 +132,20 @@ $dbh->do('DELETE FROM issues'); $dbh->do('DELETE FROM borrowers'); # Disable recording of the staff who checked out an item until we're ready for it -t::lib::Mocks::mock_preference('RecordStaffUserOnCheckout', 0); +t::lib::Mocks::mock_preference( 'RecordStaffUserOnCheckout', 0 ); my $module = Test::MockModule->new('C4::Context'); -my $library = $builder->build({ - source => 'Branch', -}); -my $library2 = $builder->build({ - source => 'Branch', -}); +my $library = $builder->build( + { + source => 'Branch', + } +); +my $library2 = $builder->build( + { + source => 'Branch', + } +); my $itemtype = $builder->build( { source => 'Itemtype', @@ -162,53 +169,57 @@ my $patron_category = $builder->build( } ); -my $CircControl = C4::Context->preference('CircControl'); +my $CircControl = C4::Context->preference('CircControl'); my $HomeOrHoldingBranch = C4::Context->preference('HomeOrHoldingBranch'); -my $item = $builder->build_object({ - class => 'Koha::Items', - value => { - homebranch => $library2->{branchcode}, - holdingbranch => $library2->{branchcode} +my $item = $builder->build_object( + { + class => 'Koha::Items', + value => { + homebranch => $library2->{branchcode}, + holdingbranch => $library2->{branchcode} + } } -}); +); -my $borrower = $builder->build_object({ - class => 'Koha::Patrons', - value => { branchcode => $library2->{branchcode} } -}); +my $borrower = $builder->build_object( + { + class => 'Koha::Patrons', + value => { branchcode => $library2->{branchcode} } + } +); -t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0); +t::lib::Mocks::mock_preference( 'AutoReturnCheckedOutItems', 0 ); # No userenv, PickupLibrary -t::lib::Mocks::mock_preference('IndependentBranches', '0'); -t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary'); +t::lib::Mocks::mock_preference( 'IndependentBranches', '0' ); +t::lib::Mocks::mock_preference( 'CircControl', 'PickupLibrary' ); is( C4::Context->preference('CircControl'), 'PickupLibrary', 'CircControl changed to PickupLibrary' ); is( - C4::Circulation::_GetCircControlBranch($item, $borrower), + C4::Circulation::_GetCircControlBranch( $item, $borrower ), $item->get_column($HomeOrHoldingBranch), '_GetCircControlBranch returned item branch (no userenv defined)' ); # No userenv, PatronLibrary -t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary'); +t::lib::Mocks::mock_preference( 'CircControl', 'PatronLibrary' ); is( C4::Context->preference('CircControl'), 'PatronLibrary', 'CircControl changed to PatronLibrary' ); is( - C4::Circulation::_GetCircControlBranch($item, $borrower), + C4::Circulation::_GetCircControlBranch( $item, $borrower ), $borrower->branchcode, '_GetCircControlBranch returned borrower branch' ); # No userenv, ItemHomeLibrary -t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary'); +t::lib::Mocks::mock_preference( 'CircControl', 'ItemHomeLibrary' ); is( C4::Context->preference('CircControl'), 'ItemHomeLibrary', @@ -216,55 +227,55 @@ is( ); is( $item->get_column($HomeOrHoldingBranch), - C4::Circulation::_GetCircControlBranch($item, $borrower), + C4::Circulation::_GetCircControlBranch( $item, $borrower ), '_GetCircControlBranch returned item branch' ); # Now, set a userenv -t::lib::Mocks::mock_userenv({ branchcode => $library2->{branchcode} }); -is(C4::Context->userenv->{branch}, $library2->{branchcode}, 'userenv set'); +t::lib::Mocks::mock_userenv( { branchcode => $library2->{branchcode} } ); +is( C4::Context->userenv->{branch}, $library2->{branchcode}, 'userenv set' ); # Userenv set, PickupLibrary -t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary'); +t::lib::Mocks::mock_preference( 'CircControl', 'PickupLibrary' ); is( C4::Context->preference('CircControl'), 'PickupLibrary', 'CircControl changed to PickupLibrary' ); is( - C4::Circulation::_GetCircControlBranch($item, $borrower), + C4::Circulation::_GetCircControlBranch( $item, $borrower ), $library2->{branchcode}, '_GetCircControlBranch returned current branch' ); # Userenv set, PatronLibrary -t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary'); +t::lib::Mocks::mock_preference( 'CircControl', 'PatronLibrary' ); is( C4::Context->preference('CircControl'), 'PatronLibrary', 'CircControl changed to PatronLibrary' ); is( - C4::Circulation::_GetCircControlBranch($item, $borrower), + C4::Circulation::_GetCircControlBranch( $item, $borrower ), $borrower->branchcode, '_GetCircControlBranch returned borrower branch' ); # Userenv set, ItemHomeLibrary -t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary'); +t::lib::Mocks::mock_preference( 'CircControl', 'ItemHomeLibrary' ); is( C4::Context->preference('CircControl'), 'ItemHomeLibrary', 'CircControl changed to ItemHomeLibrary' ); is( - C4::Circulation::_GetCircControlBranch($item, $borrower), + C4::Circulation::_GetCircControlBranch( $item, $borrower ), $item->get_column($HomeOrHoldingBranch), '_GetCircControlBranch returned item branch' ); # Reset initial configuration -t::lib::Mocks::mock_preference('CircControl', $CircControl); +t::lib::Mocks::mock_preference( 'CircControl', $CircControl ); is( C4::Context->preference('CircControl'), $CircControl, @@ -342,16 +353,16 @@ subtest "CanBookBeRenewed AllowRenewalIfOtherItemsAvailable multiple borrowers a #Can only reserve from home branch Koha::CirculationRules->set_rule( { - branchcode => undef, - itemtype => undef, - rule_name => 'holdallowed', - rule_value => 1 + branchcode => undef, + itemtype => undef, + rule_name => 'holdallowed', + rule_value => 1 } ); Koha::CirculationRules->set_rule( { branchcode => undef, - categorycode => undef, + categorycode => undef, itemtype => undef, rule_name => 'onshelfholds', rule_value => 1 @@ -359,28 +370,34 @@ subtest "CanBookBeRenewed AllowRenewalIfOtherItemsAvailable multiple borrowers a ); # Patrons from three different branches - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); - my $patron_hold_1 = $builder->build_object({ class => 'Koha::Patrons' }); - my $patron_hold_2 = $builder->build_object({ class => 'Koha::Patrons' }); - my $biblio = $builder->build_sample_biblio(); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + my $patron_hold_1 = $builder->build_object( { class => 'Koha::Patrons' } ); + my $patron_hold_2 = $builder->build_object( { class => 'Koha::Patrons' } ); + my $biblio = $builder->build_sample_biblio(); # Item at each patron branch - my $item_1 = $builder->build_sample_item({ - biblionumber => $biblio->biblionumber, - homebranch => $patron->branchcode - }); - my $item_2 = $builder->build_sample_item({ - biblionumber => $biblio->biblionumber, - homebranch => $patron_hold_2->branchcode - }); - my $item_3 = $builder->build_sample_item({ - biblionumber => $biblio->biblionumber, - homebranch => $patron_hold_1->branchcode - }); + my $item_1 = $builder->build_sample_item( + { + biblionumber => $biblio->biblionumber, + homebranch => $patron->branchcode + } + ); + my $item_2 = $builder->build_sample_item( + { + biblionumber => $biblio->biblionumber, + homebranch => $patron_hold_2->branchcode + } + ); + my $item_3 = $builder->build_sample_item( + { + biblionumber => $biblio->biblionumber, + homebranch => $patron_hold_1->branchcode + } + ); - my $issue = AddIssue( $patron, $item_1->barcode); + my $issue = AddIssue( $patron, $item_1->barcode ); my $datedue = dt_from_string( $issue->date_due() ); - is (defined $issue->date_due(), 1, "Item 1 checked out, due date: " . $issue->date_due() ); + is( defined $issue->date_due(), 1, "Item 1 checked out, due date: " . $issue->date_due() ); # Biblio-level holds my $reserve_1 = AddReserve( @@ -407,31 +424,31 @@ subtest "CanBookBeRenewed AllowRenewalIfOtherItemsAvailable multiple borrowers a found => undef, } ); - t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 0 ); + t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 ); - my ( $renewokay, $error ) = CanBookBeRenewed($patron, $issue); - is( $renewokay, 0, 'Cannot renew, reserved'); - is( $error, 'on_reserve', 'Cannot renew, reserved (returned error is on_reserve)'); + my ( $renewokay, $error ) = CanBookBeRenewed( $patron, $issue ); + is( $renewokay, 0, 'Cannot renew, reserved' ); + is( $error, 'on_reserve', 'Cannot renew, reserved (returned error is on_reserve)' ); - t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 1 ); + t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 ); - ( $renewokay, $error ) = CanBookBeRenewed($patron, $issue); - is( $renewokay, 1, 'Can renew, two items available for two holds'); - is( $error, undef, 'Can renew, each reserve has an item'); + ( $renewokay, $error ) = CanBookBeRenewed( $patron, $issue ); + is( $renewokay, 1, 'Can renew, two items available for two holds' ); + is( $error, undef, 'Can renew, each reserve has an item' ); # Item level hold - my $hold = Koha::Holds->find( $reserve_1 ); + my $hold = Koha::Holds->find($reserve_1); $hold->itemnumber( $item_1->itemnumber )->store; - ( $renewokay, $error ) = CanBookBeRenewed($patron, $issue); - is( $renewokay, 0, 'Cannot renew when there is an item specific hold'); - is( $error, 'on_reserve', 'Cannot renew, only this item can fill the reserve'); + ( $renewokay, $error ) = CanBookBeRenewed( $patron, $issue ); + is( $renewokay, 0, 'Cannot renew when there is an item specific hold' ); + is( $error, 'on_reserve', 'Cannot renew, only this item can fill the reserve' ); }; subtest "GetIssuingCharges tests" => sub { plan tests => 4; - my $branch_discount = $builder->build_object({ class => 'Koha::Libraries' }); - my $branch_no_discount = $builder->build_object({ class => 'Koha::Libraries' }); + my $branch_discount = $builder->build_object( { class => 'Koha::Libraries' } ); + my $branch_no_discount = $builder->build_object( { class => 'Koha::Libraries' } ); Koha::CirculationRules->set_rule( { categorycode => undef, @@ -441,35 +458,37 @@ subtest "GetIssuingCharges tests" => sub { rule_value => 15 } ); - my $itype_charge = $builder->build_object({ - class => 'Koha::ItemTypes', - value => { - rentalcharge => 10 + my $itype_charge = $builder->build_object( + { + class => 'Koha::ItemTypes', + value => { rentalcharge => 10 } } - }); - my $itype_no_charge = $builder->build_object({ - class => 'Koha::ItemTypes', - value => { - rentalcharge => 0 + ); + my $itype_no_charge = $builder->build_object( + { + class => 'Koha::ItemTypes', + value => { rentalcharge => 0 } } - }); - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); - my $item_1 = $builder->build_sample_item({ itype => $itype_charge->itemtype }); - my $item_2 = $builder->build_sample_item({ itype => $itype_no_charge->itemtype }); + ); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + my $item_1 = $builder->build_sample_item( { itype => $itype_charge->itemtype } ); + my $item_2 = $builder->build_sample_item( { itype => $itype_no_charge->itemtype } ); - t::lib::Mocks::mock_userenv({ branchcode => $branch_no_discount->branchcode }); - # For now the sub always uses the env branch, this should follow CircControl instead - my ($charge, $itemtype) = GetIssuingCharges( $item_1->itemnumber, $patron->borrowernumber); - is( $charge + 0, 10.00, "Charge fetched correctly when no discount exists"); - ($charge, $itemtype) = GetIssuingCharges( $item_2->itemnumber, $patron->borrowernumber); - is( $charge + 0, 0.00, "Charge fetched correctly when no discount exists and no charge"); + t::lib::Mocks::mock_userenv( { branchcode => $branch_no_discount->branchcode } ); - t::lib::Mocks::mock_userenv({ branchcode => $branch_discount->branchcode }); # For now the sub always uses the env branch, this should follow CircControl instead - ($charge, $itemtype) = GetIssuingCharges( $item_1->itemnumber, $patron->borrowernumber); - is( $charge + 0, 8.50, "Charge fetched correctly when discount exists"); - ($charge, $itemtype) = GetIssuingCharges( $item_2->itemnumber, $patron->borrowernumber); - is( $charge + 0, 0.00, "Charge fetched correctly when discount exists and no charge"); + my ( $charge, $itemtype ) = GetIssuingCharges( $item_1->itemnumber, $patron->borrowernumber ); + is( $charge + 0, 10.00, "Charge fetched correctly when no discount exists" ); + ( $charge, $itemtype ) = GetIssuingCharges( $item_2->itemnumber, $patron->borrowernumber ); + is( $charge + 0, 0.00, "Charge fetched correctly when no discount exists and no charge" ); + + t::lib::Mocks::mock_userenv( { branchcode => $branch_discount->branchcode } ); + + # For now the sub always uses the env branch, this should follow CircControl instead + ( $charge, $itemtype ) = GetIssuingCharges( $item_1->itemnumber, $patron->borrowernumber ); + is( $charge + 0, 8.50, "Charge fetched correctly when discount exists" ); + ( $charge, $itemtype ) = GetIssuingCharges( $item_2->itemnumber, $patron->borrowernumber ); + is( $charge + 0, 0.00, "Charge fetched correctly when discount exists and no charge" ); }; @@ -477,7 +496,8 @@ my ( $reused_itemnumber_1, $reused_itemnumber_2 ); subtest "CanBookBeRenewed tests" => sub { plan tests => 114; - C4::Context->set_preference('ItemsDeniedRenewal',''); + C4::Context->set_preference( 'ItemsDeniedRenewal', '' ); + # Generate test biblio my $biblio = $builder->build_sample_biblio(); @@ -518,10 +538,10 @@ subtest "CanBookBeRenewed tests" => sub { { class => 'Koha::Patrons', value => { - firstname => 'John', - surname => 'Renewal', - categorycode => $patron_category->{categorycode}, - branchcode => $branch, + firstname => 'John', + surname => 'Renewal', + categorycode => $patron_category->{categorycode}, + branchcode => $branch, autorenew_checkouts => 1, } } @@ -532,10 +552,10 @@ subtest "CanBookBeRenewed tests" => sub { { class => 'Koha::Patrons', value => { - firstname => 'Katrin', - surname => 'Reservation', + firstname => 'Katrin', + surname => 'Reservation', categorycode => $patron_category->{categorycode}, - branchcode => $branch, + branchcode => $branch, } } )->store->borrowernumber; @@ -544,10 +564,10 @@ subtest "CanBookBeRenewed tests" => sub { { class => 'Koha::Patrons', value => { - firstname => 'Kyle', - surname => 'Reservation', + firstname => 'Kyle', + surname => 'Reservation', categorycode => $patron_category->{categorycode}, - branchcode => $branch, + branchcode => $branch, } } )->store->borrowernumber; @@ -556,11 +576,11 @@ subtest "CanBookBeRenewed tests" => sub { { class => 'Koha::Patrons', value => { - firstname => 'Alice', - surname => 'Reservation', + firstname => 'Alice', + surname => 'Reservation', categorycode => $patron_category->{categorycode}, - debarred => '3228-01-01', - branchcode => $branch, + debarred => '3228-01-01', + branchcode => $branch, } } )->store; @@ -569,37 +589,39 @@ subtest "CanBookBeRenewed tests" => sub { { class => 'Koha::Patrons', value => { - firstname => 'Ça', - surname => 'Glisse', - categorycode => $patron_category->{categorycode}, - branchcode => $branch, - dateexpiry => dt_from_string->subtract( months => 1 ), + firstname => 'Ça', + surname => 'Glisse', + categorycode => $patron_category->{categorycode}, + branchcode => $branch, + dateexpiry => dt_from_string->subtract( months => 1 ), autorenew_checkouts => 1, } } ); - my $bibitems = ''; - my $priority = '1'; - my $resdate = undef; - my $expdate = undef; - my $notes = ''; - my $checkitem = undef; - my $found = undef; + my $bibitems = ''; + my $priority = '1'; + my $resdate = undef; + my $expdate = undef; + my $notes = ''; + my $checkitem = undef; + my $found = undef; - my $issue_1 = AddIssue( $renewing_borrower_obj, $item_1->barcode); + my $issue_1 = AddIssue( $renewing_borrower_obj, $item_1->barcode ); my $datedue = dt_from_string( $issue_1->date_due() ); - is (defined $issue_1->date_due(), 1, "Item 1 checked out, due date: " . $issue_1->date_due() ); + is( defined $issue_1->date_due(), 1, "Item 1 checked out, due date: " . $issue_1->date_due() ); - my $issue_2 = AddIssue( $renewing_borrower_obj, $item_2->barcode); - is (defined $issue_2, 1, "Item 2 checked out, due date: " . $issue_2->date_due()); + my $issue_2 = AddIssue( $renewing_borrower_obj, $item_2->barcode ); + is( defined $issue_2, 1, "Item 2 checked out, due date: " . $issue_2->date_due() ); my $borrowing_borrowernumber = Koha::Checkouts->find( { itemnumber => $item_1->itemnumber } )->borrowernumber; - is ($borrowing_borrowernumber, $renewing_borrowernumber, "Item checked out to ".$renewing_borrower_obj->firstname." ".$renewing_borrower_obj->surname); - - my ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_1, 1); - is( $renewokay, 1, 'Can renew, no holds for this title or item'); + is( + $borrowing_borrowernumber, $renewing_borrowernumber, + "Item checked out to " . $renewing_borrower_obj->firstname . " " . $renewing_borrower_obj->surname + ); + my ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $issue_1, 1 ); + is( $renewokay, 1, 'Can renew, no holds for this title or item' ); # Biblio-level hold, renewal test AddReserve( @@ -635,12 +657,17 @@ subtest "CanBookBeRenewed tests" => sub { rule_value => '5', } ); - t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 1 ); - ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_1); - is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds'); - ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_2); - is( $renewokay, 1, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds'); - + t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 ); + ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $issue_1 ); + is( + $renewokay, 1, + 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds' + ); + ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $issue_2 ); + is( + $renewokay, 1, + 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds' + ); # Second biblio-level hold my $reserve_id = AddReserve( @@ -656,8 +683,8 @@ subtest "CanBookBeRenewed tests" => sub { found => $found, } ); - ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_1); - is( $renewokay, 0, 'Renewal not possible when single patron\'s holds exceed the number of available items'); + ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $issue_1 ); + is( $renewokay, 0, 'Renewal not possible when single patron\'s holds exceed the number of available items' ); Koha::Holds->find($reserve_id)->delete; # Now let's add an item level hold, we should no longer be able to renew the item @@ -671,8 +698,8 @@ subtest "CanBookBeRenewed tests" => sub { reservedate => '1999-01-01', } ); - ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_1); - is( $renewokay, 0, 'Bug 13919 - Renewal possible with item level hold on item'); + ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $issue_1 ); + is( $renewokay, 0, 'Bug 13919 - Renewal possible with item level hold on item' ); $hold->delete(); # Now let's add a waiting hold on the 3rd item, it's no longer available tp check out by just anyone, so we should no longer @@ -687,29 +714,37 @@ subtest "CanBookBeRenewed tests" => sub { found => 'W' } ); - ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_1); - is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds'); - ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_2); - is( $renewokay, 0, 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds'); - t::lib::Mocks::mock_preference('AllowRenewalIfOtherItemsAvailable', 0 ); + ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $issue_1 ); + is( + $renewokay, 0, + 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds' + ); + ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $issue_2 ); + is( + $renewokay, 0, + 'Bug 11634 - Allow renewal of item with unfilled holds if other available items can fill those holds' + ); + t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 ); - ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_1); - is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved'); - is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)'); + ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $issue_1 ); + is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved' ); + is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)' ); - ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_2); - is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved'); - is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)'); + ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $issue_2 ); + is( $renewokay, 0, '(Bug 10663) Cannot renew, reserved' ); + is( $error, 'on_reserve', '(Bug 10663) Cannot renew, reserved (returned error is on_reserve)' ); - my $reserveid = Koha::Holds->search({ biblionumber => $biblio->biblionumber, borrowernumber => $reserving_borrowernumber })->next->reserve_id; - my $reserving_borrower = Koha::Patrons->find( $reserving_borrowernumber ); - AddIssue($reserving_borrower, $item_3->barcode); + my $reserveid = + Koha::Holds->search( { biblionumber => $biblio->biblionumber, borrowernumber => $reserving_borrowernumber } ) + ->next->reserve_id; + my $reserving_borrower = Koha::Patrons->find($reserving_borrowernumber); + AddIssue( $reserving_borrower, $item_3->barcode ); my $reserve = $dbh->selectrow_hashref( 'SELECT * FROM old_reserves WHERE reserve_id = ?', { Slice => {} }, $reserveid ); - is($reserve->{found}, 'F', 'hold marked completed when checking out item that fills it'); + is( $reserve->{found}, 'F', 'hold marked completed when checking out item that fills it' ); # Item-level hold, renewal test AddReserve( @@ -726,18 +761,18 @@ subtest "CanBookBeRenewed tests" => sub { } ); - ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_1, 1); - is( $renewokay, 0, '(Bug 10663) Cannot renew, item reserved'); - is( $error, 'on_reserve', '(Bug 10663) Cannot renew, item reserved (returned error is on_reserve)'); + ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $issue_1, 1 ); + is( $renewokay, 0, '(Bug 10663) Cannot renew, item reserved' ); + is( $error, 'on_reserve', '(Bug 10663) Cannot renew, item reserved (returned error is on_reserve)' ); - ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_2, 1); - is( $renewokay, 1, 'Can renew item 2, item-level hold is on item 1'); + ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $issue_2, 1 ); + is( $renewokay, 1, 'Can renew item 2, item-level hold is on item 1' ); # Items can't fill hold for reasons $issue_1->item->notforloan(1)->store; - ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_1, 1); - is( $renewokay, 0, 'Cannot renew, item is marked not for loan, but an item specific hold always blocks'); - $item_1->set({notforloan => 0, itype => $itemtype })->store; + ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $issue_1, 1 ); + is( $renewokay, 0, 'Cannot renew, item is marked not for loan, but an item specific hold always blocks' ); + $item_1->set( { notforloan => 0, itype => $itemtype } )->store; # FIXME: Add more for itemtype not for loan etc. @@ -750,15 +785,15 @@ subtest "CanBookBeRenewed tests" => sub { itype => $itemtype, } ); - my $issue_5 = AddIssue($restricted_borrower_obj, $item_5->barcode); - is (defined $issue_5, 1, "Item with date due checked out, due date: ". $issue_5->date_due); + my $issue_5 = AddIssue( $restricted_borrower_obj, $item_5->barcode ); + is( defined $issue_5, 1, "Item with date due checked out, due date: " . $issue_5->date_due ); - t::lib::Mocks::mock_preference('RestrictionBlockRenewing','1'); - ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_2); - is( $renewokay, 1, '(Bug 8236), Can renew, user is not restricted'); - ( $renewokay, $error ) = CanBookBeRenewed($restricted_borrower_obj, $issue_5); - is( $renewokay, 0, '(Bug 8236), Cannot renew, user is restricted'); - is( $error, 'restriction', "Correct error returned"); + t::lib::Mocks::mock_preference( 'RestrictionBlockRenewing', '1' ); + ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $issue_2 ); + is( $renewokay, 1, '(Bug 8236), Can renew, user is not restricted' ); + ( $renewokay, $error ) = CanBookBeRenewed( $restricted_borrower_obj, $issue_5 ); + is( $renewokay, 0, '(Bug 8236), Cannot renew, user is restricted' ); + is( $error, 'restriction', "Correct error returned" ); # Users cannot renew an overdue item my $item_6 = $builder->build_sample_item( @@ -779,39 +814,39 @@ subtest "CanBookBeRenewed tests" => sub { } ); - my $issue_6 = AddIssue( $renewing_borrower_obj, $item_6->barcode); - is (defined $issue_6, 1, "Item 2 checked out, due date: ".$issue_6->date_due); + my $issue_6 = AddIssue( $renewing_borrower_obj, $item_6->barcode ); + is( defined $issue_6, 1, "Item 2 checked out, due date: " . $issue_6->date_due ); - my $now = dt_from_string(); - my $five_weeks = DateTime::Duration->new(weeks => 5); + my $now = dt_from_string(); + my $five_weeks = DateTime::Duration->new( weeks => 5 ); my $five_weeks_ago = $now - $five_weeks; - t::lib::Mocks::mock_preference('finesMode', 'production'); + t::lib::Mocks::mock_preference( 'finesMode', 'production' ); - my $issue_7 = AddIssue($renewing_borrower_obj, $item_7->barcode, $five_weeks_ago); - is (defined $issue_7, 1, "Item with passed date due checked out, due date: " . $issue_7->date_due); + my $issue_7 = AddIssue( $renewing_borrower_obj, $item_7->barcode, $five_weeks_ago ); + is( defined $issue_7, 1, "Item with passed date due checked out, due date: " . $issue_7->date_due ); - t::lib::Mocks::mock_preference('OverduesBlockRenewing','allow'); - ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_6); - is( $renewokay, 1, '(Bug 8236), Can renew, this item is not overdue'); - ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_7); - is( $renewokay, 1, '(Bug 8236), Can renew, this item is overdue but not pref does not block'); + t::lib::Mocks::mock_preference( 'OverduesBlockRenewing', 'allow' ); + ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $issue_6 ); + is( $renewokay, 1, '(Bug 8236), Can renew, this item is not overdue' ); + ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $issue_7 ); + is( $renewokay, 1, '(Bug 8236), Can renew, this item is overdue but not pref does not block' ); - t::lib::Mocks::mock_preference('OverduesBlockRenewing','block'); - ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_6); - is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is not overdue but patron has overdues'); - is( $error, 'overdue', "Correct error returned"); - ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_7); - is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is overdue so patron has overdues'); - is( $error, 'overdue', "Correct error returned"); + t::lib::Mocks::mock_preference( 'OverduesBlockRenewing', 'block' ); + ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $issue_6 ); + is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is not overdue but patron has overdues' ); + is( $error, 'overdue', "Correct error returned" ); + ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $issue_7 ); + is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is overdue so patron has overdues' ); + is( $error, 'overdue', "Correct error returned" ); - t::lib::Mocks::mock_preference('OverduesBlockRenewing','blockitem'); - ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_6); - is( $renewokay, 1, '(Bug 8236), Can renew, this item is not overdue'); - ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_7); - is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is overdue'); - is( $error, 'overdue', "Correct error returned"); + t::lib::Mocks::mock_preference( 'OverduesBlockRenewing', 'blockitem' ); + ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $issue_6 ); + is( $renewokay, 1, '(Bug 8236), Can renew, this item is not overdue' ); + ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $issue_7 ); + is( $renewokay, 0, '(Bug 8236), Cannot renew, this item is overdue' ); + is( $error, 'overdue', "Correct error returned" ); - my ( $fine ) = CalcFine( $item_7->unblessed, $renewing_borrower_obj->categorycode, $branch, $five_weeks_ago, $now ); + my ($fine) = CalcFine( $item_7->unblessed, $renewing_borrower_obj->categorycode, $branch, $five_weeks_ago, $now ); C4::Overdues::UpdateFine( { issue_id => $issue_7->id(), @@ -823,29 +858,29 @@ subtest "CanBookBeRenewed tests" => sub { ); # Make sure fine calculation isn't skipped when adding renewal - t::lib::Mocks::mock_preference('CalculateFinesOnReturn', 1); + t::lib::Mocks::mock_preference( 'CalculateFinesOnReturn', 1 ); # Calculate new due-date based on the present date not to incur # multiple fees - t::lib::Mocks::mock_preference('RenewalPeriodBase', 'now'); + t::lib::Mocks::mock_preference( 'RenewalPeriodBase', 'now' ); - my $staff = $builder->build_object({ class => "Koha::Patrons" }); - t::lib::Mocks::mock_userenv({ patron => $staff }); + my $staff = $builder->build_object( { class => "Koha::Patrons" } ); + t::lib::Mocks::mock_userenv( { patron => $staff } ); - t::lib::Mocks::mock_preference('RenewalLog', 0); - my $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } ); + t::lib::Mocks::mock_preference( 'RenewalLog', 0 ); + my $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } ); my %params_renewal = ( timestamp => { -like => $date . "%" }, - module => "CIRCULATION", - action => "RENEWAL", + module => "CIRCULATION", + action => "RENEWAL", ); my %params_issue = ( timestamp => { -like => $date . "%" }, - module => "CIRCULATION", - action => "ISSUE" + module => "CIRCULATION", + action => "ISSUE" ); my $old_log_size = Koha::ActionLogs->count( \%params_renewal ); - my $dt = dt_from_string(); + my $dt = dt_from_string(); Time::Fake->offset( $dt->epoch ); my $datedue1 = AddRenewal( { @@ -855,12 +890,12 @@ subtest "CanBookBeRenewed tests" => sub { } ); my $new_log_size = Koha::ActionLogs->count( \%params_renewal ); - is ($new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog'); - isnt (DateTime->compare($datedue1, $dt), 0, "AddRenewal returned a good duedate"); + is( $new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog' ); + isnt( DateTime->compare( $datedue1, $dt ), 0, "AddRenewal returned a good duedate" ); Time::Fake->reset; - t::lib::Mocks::mock_preference('RenewalLog', 1); - $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } ); + t::lib::Mocks::mock_preference( 'RenewalLog', 1 ); + $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } ); $old_log_size = Koha::ActionLogs->count( \%params_renewal ); AddRenewal( { @@ -870,10 +905,11 @@ subtest "CanBookBeRenewed tests" => sub { } ); $new_log_size = Koha::ActionLogs->count( \%params_renewal ); - is ($new_log_size, $old_log_size + 1, 'renew log successfully added'); + is( $new_log_size, $old_log_size + 1, 'renew log successfully added' ); - my $fines = Koha::Account::Lines->search( { borrowernumber => $renewing_borrower_obj->borrowernumber, itemnumber => $item_7->itemnumber } ); - is( $fines->count, 1, 'AddRenewal left fine' ); + my $fines = Koha::Account::Lines->search( + { borrowernumber => $renewing_borrower_obj->borrowernumber, itemnumber => $item_7->itemnumber } ); + is( $fines->count, 1, 'AddRenewal left fine' ); is( $fines->next->status, 'RENEWED', 'Fine on renewed item is closed out properly' ); $fines->delete(); @@ -882,18 +918,20 @@ subtest "CanBookBeRenewed tests" => sub { AddIssue( $renewing_borrower_obj, $item_7->barcode, - Koha::DateUtils::output_pref({str=>$issue_6->date_due, dateformat =>'iso'}), + Koha::DateUtils::output_pref( { str => $issue_6->date_due, dateformat => 'iso' } ), 0, $date, 0, undef - ); # TODO: Already issued??? + ); # TODO: Already issued??? $new_log_size = Koha::ActionLogs->count( \%params_renewal ); - is ($new_log_size, $old_renew_log_size + 1, 'renew log successfully added when renewed via issuing'); + is( $new_log_size, $old_renew_log_size + 1, 'renew log successfully added when renewed via issuing' ); $new_log_size = Koha::ActionLogs->count( \%params_issue ); - is ($new_log_size, $old_issue_log_size, 'renew not logged as issue when renewed via issuing'); + is( $new_log_size, $old_issue_log_size, 'renew not logged as issue when renewed via issuing' ); - $hold = Koha::Holds->search({ biblionumber => $biblio->biblionumber, borrowernumber => $reserving_borrowernumber })->next; + $hold = + Koha::Holds->search( { biblionumber => $biblio->biblionumber, borrowernumber => $reserving_borrowernumber } ) + ->next; $hold->cancel; # Bug 14101 @@ -941,32 +979,34 @@ subtest "CanBookBeRenewed tests" => sub { } ); ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $auto_renew_issue ); - is( $renewokay, 0, 'Still should not be able to renew' ); - is( $error, 'on_reserve', 'returned code is on_reserve, reserve checked when not checking for cron' ); + is( $renewokay, 0, 'Still should not be able to renew' ); + is( $error, 'on_reserve', 'returned code is on_reserve, reserve checked when not checking for cron' ); ( $renewokay, $error, $info ) = CanBookBeRenewed( $renewing_borrower_obj, $auto_renew_issue, undef, 1 ); - is( $renewokay, 0, 'Still should not be able to renew' ); - is( $error, 'auto_too_soon', 'returned code is auto_too_soon, reserve not checked when checking for cron' ); - is( $info->{soonest_renew_date}, dt_from_string($auto_renew_issue->date_due), "Due date is returned as earliest renewal date when error is 'auto_too_soon'" ); + is( $renewokay, 0, 'Still should not be able to renew' ); + is( $error, 'auto_too_soon', 'returned code is auto_too_soon, reserve not checked when checking for cron' ); + is( + $info->{soonest_renew_date}, dt_from_string( $auto_renew_issue->date_due ), + "Due date is returned as earliest renewal date when error is 'auto_too_soon'" + ); ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $auto_renew_issue, 1 ); - is( $renewokay, 0, 'Still should not be able to renew' ); - is( $error, 'on_reserve', 'returned code is on_reserve, auto_too_soon limit is overridden' ); + is( $renewokay, 0, 'Still should not be able to renew' ); + is( $error, 'on_reserve', 'returned code is on_reserve, auto_too_soon limit is overridden' ); ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $auto_renew_issue, 1, 1 ); - is( $renewokay, 0, 'Still should not be able to renew' ); - is( $error, 'on_reserve', 'returned code is on_reserve, auto_too_soon limit is overridden' ); + is( $renewokay, 0, 'Still should not be able to renew' ); + is( $error, 'on_reserve', 'returned code is on_reserve, auto_too_soon limit is overridden' ); $dbh->do('UPDATE circulation_rules SET rule_value = 0 where rule_name = "norenewalbefore"'); Koha::Cache::Memory::Lite->flush(); ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $auto_renew_issue, 1 ); - is( $renewokay, 0, 'Still should not be able to renew' ); - is( $error, 'on_reserve', 'returned code is on_reserve, auto_renew only happens if not on reserve' ); - ModReserveCancelAll($item_4->itemnumber, $reserving_borrowernumber); + is( $renewokay, 0, 'Still should not be able to renew' ); + is( $error, 'on_reserve', 'returned code is on_reserve, auto_renew only happens if not on reserve' ); + ModReserveCancelAll( $item_4->itemnumber, $reserving_borrowernumber ); - $renewing_borrower_obj = Koha::Patrons->find($renewing_borrower_obj->borrowernumber); + $renewing_borrower_obj = Koha::Patrons->find( $renewing_borrower_obj->borrowernumber ); $renewing_borrower_obj->autorenew_checkouts(0)->store; ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $auto_renew_issue ); is( $renewokay, 1, 'No renewal before is undef, but patron opted out of auto_renewal' ); $renewing_borrower_obj->autorenew_checkouts(1)->store; - # Bug 7413 # Test premature manual renewal Koha::CirculationRules->set_rule( @@ -979,10 +1019,13 @@ subtest "CanBookBeRenewed tests" => sub { } ); - ( $renewokay, $error, $info ) = CanBookBeRenewed($renewing_borrower_obj, $issue_1); - is( $renewokay, 0, 'Bug 7413: Cannot renew, renewal is premature'); - is( $error, 'too_soon', 'Bug 7413: Cannot renew, renewal is premature (returned code is too_soon)'); - is( $info->{soonest_renew_date}, dt_from_string($issue_1->date_due)->subtract( days => 7 ), "Soonest renew date returned when error is 'too_soon'"); + ( $renewokay, $error, $info ) = CanBookBeRenewed( $renewing_borrower_obj, $issue_1 ); + is( $renewokay, 0, 'Bug 7413: Cannot renew, renewal is premature' ); + is( $error, 'too_soon', 'Bug 7413: Cannot renew, renewal is premature (returned code is too_soon)' ); + is( + $info->{soonest_renew_date}, dt_from_string( $issue_1->date_due )->subtract( days => 7 ), + "Soonest renew date returned when error is 'too_soon'" + ); # Bug 25393 # Test premature automatic renewal @@ -996,10 +1039,10 @@ subtest "CanBookBeRenewed tests" => sub { } ); - ( $renewokay, $error, $info ) = - CanBookBeRenewed( $renewing_borrower_obj, $auto_renew_issue ); + ( $renewokay, $error, $info ) = CanBookBeRenewed( $renewing_borrower_obj, $auto_renew_issue ); is( $renewokay, 0, 'Bug 25393: Cannot renew, renewal is premature' ); - is( $error, 'too_soon', + is( + $error, 'too_soon', 'Bug 25393: Cannot renew, renewal is premature (returned code is too_soon)' ); is( @@ -1015,49 +1058,61 @@ subtest "CanBookBeRenewed tests" => sub { ); $renewing_borrower_obj->autorenew_checkouts(0)->store; ( $renewokay, $error, $info ) = CanBookBeRenewed( $renewing_borrower_obj, $auto_renew_issue ); - is( $renewokay, 0, 'No renewal before is 7, patron opted out of auto_renewal still cannot renew early' ); - is( $error, 'too_soon', 'Error is too_soon, no auto' ); - is( $info->{soonest_renew_date}, dt_from_string($auto_renew_issue->date_due)->subtract( days => 7 ), "Soonest renew date returned when error is 'too_soon'"); + is( $renewokay, 0, 'No renewal before is 7, patron opted out of auto_renewal still cannot renew early' ); + is( $error, 'too_soon', 'Error is too_soon, no auto' ); + is( + $info->{soonest_renew_date}, dt_from_string( $auto_renew_issue->date_due )->subtract( days => 7 ), + "Soonest renew date returned when error is 'too_soon'" + ); $renewing_borrower_obj->autorenew_checkouts(1)->store; # Change policy so that loans can only be renewed exactly on due date (0 days prior to due date) # and test automatic renewal again $dbh->do(q{UPDATE circulation_rules SET rule_value = '0' WHERE rule_name = 'norenewalbefore'}); Koha::Cache::Memory::Lite->flush(); - ( $renewokay, $error, $info ) = - CanBookBeRenewed( $renewing_borrower_obj, $auto_renew_issue ); + ( $renewokay, $error, $info ) = CanBookBeRenewed( $renewing_borrower_obj, $auto_renew_issue ); is( $renewokay, 0, 'Bug 25393: Cannot manual renew, renewal is too soon' ); - is( $error, 'too_soon', + is( + $error, 'too_soon', 'Bug 25393: Cannot manual renew, renewal is too soon, even though it\'s also scheduled for auto renewal' ); - is( $info->{soonest_renew_date}, dt_from_string($auto_renew_issue->date_due), "Soonest renew date returned when error is 'auto_too_soon'"); + is( + $info->{soonest_renew_date}, dt_from_string( $auto_renew_issue->date_due ), + "Soonest renew date returned when error is 'auto_too_soon'" + ); # Now we test for noautorenewalbefore if cron $dbh->do(q{UPDATE circulation_rules SET rule_value = '0' WHERE rule_name = 'noautorenewalbefore'}); Koha::Cache::Memory::Lite->flush(); - ( $renewokay, $error, $info ) = - CanBookBeRenewed( $renewing_borrower_obj, $auto_renew_issue, undef, 1 ); + ( $renewokay, $error, $info ) = CanBookBeRenewed( $renewing_borrower_obj, $auto_renew_issue, undef, 1 ); is( $renewokay, 0, 'Bug 25393: Cannot auto renew, renewal is too soon' ); - is( $error, 'auto_too_soon', + is( + $error, 'auto_too_soon', 'Bug 25393: Cannot auto renew, auto renewal is too soon' ); - is( $info->{soonest_renew_date}, dt_from_string($auto_renew_issue->date_due), "Soonest renew date returned when error is 'auto_too_soon'"); + is( + $info->{soonest_renew_date}, dt_from_string( $auto_renew_issue->date_due ), + "Soonest renew date returned when error is 'auto_too_soon'" + ); $renewing_borrower_obj->autorenew_checkouts(0)->store; ( $renewokay, $error, $info ) = CanBookBeRenewed( $renewing_borrower_obj, $auto_renew_issue ); - is( $renewokay, 0, 'No renewal before is 0, patron opted out of auto_renewal still cannot renew early' ); - is( $error, 'too_soon', 'Error is too_soon, no auto' ); - is( $info->{soonest_renew_date}, dt_from_string($auto_renew_issue->date_due), "Soonest renew date returned when error is 'auto_too_soon'"); + is( $renewokay, 0, 'No renewal before is 0, patron opted out of auto_renewal still cannot renew early' ); + is( $error, 'too_soon', 'Error is too_soon, no auto' ); + is( + $info->{soonest_renew_date}, dt_from_string( $auto_renew_issue->date_due ), + "Soonest renew date returned when error is 'auto_too_soon'" + ); $renewing_borrower_obj->autorenew_checkouts(1)->store; # Change policy so that loans can be renewed 99 days prior to the due date # and test automatic renewal again $dbh->do(q{UPDATE circulation_rules SET rule_value = '99' WHERE rule_name = 'norenewalbefore'}); Koha::Cache::Memory::Lite->flush(); - ( $renewokay, $error ) = - CanBookBeRenewed( $renewing_borrower_obj, $auto_renew_issue ); + ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $auto_renew_issue ); is( $renewokay, 1, 'Bug 25393: Can do a manual renew, even if renewal is automatic and premature' ); - is( $error, 'auto_renew', + is( + $error, 'auto_renew', 'Bug 14101: Cannot renew, renewal is automatic (returned code is auto_renew)' ); @@ -1065,8 +1120,8 @@ subtest "CanBookBeRenewed tests" => sub { $dbh->do(q{UPDATE circulation_rules SET rule_value = '99' WHERE rule_name = 'noautorenewalbefore'}); Koha::Cache::Memory::Lite->flush(); ( $renewokay, $error, $info ) = CanBookBeRenewed( $renewing_borrower_obj, $auto_renew_issue, undef, 1 ); - is( $renewokay, 1, 'Bug 25393: Can auto renew' ); - is( $error, 'auto_renew', 'Bug 25393: Can auto renew' ); + is( $renewokay, 1, 'Bug 25393: Can auto renew' ); + is( $error, 'auto_renew', 'Bug 25393: Can auto renew' ); is( $info->{soonest_renew_date}, undef, "soonest_renew_date is not returned because this issue can be renewed" ); $renewing_borrower_obj->autorenew_checkouts(0)->store; @@ -1074,7 +1129,6 @@ subtest "CanBookBeRenewed tests" => sub { is( $renewokay, 1, 'No renewal before is 99, patron opted out of auto_renewal so can renew' ); $renewing_borrower_obj->autorenew_checkouts(1)->store; - # Bug 31427 # Ensure autorenewal errors always take highest precedence subtest "auto_renewal errors first" => sub { @@ -1128,7 +1182,10 @@ subtest "CanBookBeRenewed tests" => sub { my $ten_days_before = dt_from_string->add( days => -10 ); my $ten_days_ahead = dt_from_string->add( days => 10 ); - my $issue = AddIssue( $renewing_borrower_obj, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } ); + my $issue = AddIssue( + $renewing_borrower_obj, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, + undef, { auto_renew => 1 } + ); Koha::CirculationRules->set_rules( { @@ -1141,10 +1198,9 @@ subtest "CanBookBeRenewed tests" => sub { } } ); - ( $renewokay, $error ) = - CanBookBeRenewed( $renewing_borrower_obj, $issue ); - is( $renewokay, 0, 'Do not renew, renewal is automatic' ); - is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' ); + ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $issue ); + is( $renewokay, 0, 'Do not renew, renewal is automatic' ); + is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' ); Koha::CirculationRules->set_rules( { @@ -1157,10 +1213,12 @@ subtest "CanBookBeRenewed tests" => sub { } } ); - ( $renewokay, $error ) = - CanBookBeRenewed( $renewing_borrower_obj, $issue ); + ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $issue ); is( $renewokay, 0, 'Do not renew, renewal is automatic' ); - is( $error, 'auto_too_late', 'Cannot auto renew, too late - no_auto_renewal_after is inclusive(returned code is auto_too_late)' ); + is( + $error, 'auto_too_late', + 'Cannot auto renew, too late - no_auto_renewal_after is inclusive(returned code is auto_too_late)' + ); Koha::CirculationRules->set_rules( { @@ -1173,10 +1231,12 @@ subtest "CanBookBeRenewed tests" => sub { } } ); - ( $renewokay, $error ) = - CanBookBeRenewed( $renewing_borrower_obj, $issue ); + ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $issue ); is( $renewokay, 0, 'Do not renew, too_soon' ); - is( $error, 'too_soon', 'Cannot renew, too_soon - no_auto_renewal_after is defined(returned code is too_soon)' ); + is( + $error, 'too_soon', + 'Cannot renew, too_soon - no_auto_renewal_after is defined(returned code is too_soon)' + ); # Now check for cron Koha::CirculationRules->set_rules( @@ -1208,8 +1268,7 @@ subtest "CanBookBeRenewed tests" => sub { } } ); - ( $renewokay, $error ) = - CanBookBeRenewed( $renewing_borrower_obj, $issue ); + ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $issue ); is( $renewokay, 1, 'Renew, even if renewal is automatic' ); is( $error, 'auto_renew', 'Cannot renew, renew is automatic' ); @@ -1219,16 +1278,15 @@ subtest "CanBookBeRenewed tests" => sub { branchcode => undef, itemtype => undef, rules => { - norenewalbefore => '10', - no_auto_renewal_after => undef, + norenewalbefore => '10', + no_auto_renewal_after => undef, no_auto_renewal_after_hard_limit => dt_from_string->add( days => -1 ), } } ); - ( $renewokay, $error ) = - CanBookBeRenewed( $renewing_borrower_obj, $issue ); - is( $renewokay, 0, 'Do not renew, renewal is automatic' ); - is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' ); + ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $issue ); + is( $renewokay, 0, 'Do not renew, renewal is automatic' ); + is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' ); Koha::CirculationRules->set_rules( { @@ -1236,16 +1294,15 @@ subtest "CanBookBeRenewed tests" => sub { branchcode => undef, itemtype => undef, rules => { - norenewalbefore => '7', - no_auto_renewal_after => '15', + norenewalbefore => '7', + no_auto_renewal_after => '15', no_auto_renewal_after_hard_limit => dt_from_string->add( days => -1 ), } } ); - ( $renewokay, $error ) = - CanBookBeRenewed( $renewing_borrower_obj, $issue ); - is( $renewokay, 0, 'Do not renew, renewal is automatic' ); - is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' ); + ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $issue ); + is( $renewokay, 0, 'Do not renew, renewal is automatic' ); + is( $error, 'auto_too_late', 'Cannot renew, too late(returned code is auto_too_late)' ); Koha::CirculationRules->set_rules( { @@ -1253,16 +1310,15 @@ subtest "CanBookBeRenewed tests" => sub { branchcode => undef, itemtype => undef, rules => { - norenewalbefore => '10', - no_auto_renewal_after => undef, + norenewalbefore => '10', + no_auto_renewal_after => undef, no_auto_renewal_after_hard_limit => dt_from_string->add( days => 1 ), } } ); - ( $renewokay, $error ) = - CanBookBeRenewed( $renewing_borrower_obj, $issue ); - is( $renewokay, 1, 'Renew, even if renewal is automatic' ); - is( $error, 'auto_renew', 'Cannot renew, renew is automatic' ); + ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $issue ); + is( $renewokay, 1, 'Renew, even if renewal is automatic' ); + is( $error, 'auto_renew', 'Cannot renew, renew is automatic' ); }; subtest "auto_too_much_oweing | OPACFineNoRenewalsBlockAutoRenew & OPACFineNoRenewalsIncludeCredit" => sub { @@ -1275,8 +1331,11 @@ subtest "CanBookBeRenewed tests" => sub { ); my $ten_days_before = dt_from_string->add( days => -10 ); - my $ten_days_ahead = dt_from_string->add( days => 10 ); - my $issue = AddIssue( $renewing_borrower_obj, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } ); + my $ten_days_ahead = dt_from_string->add( days => 10 ); + my $issue = AddIssue( + $renewing_borrower_obj, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, + undef, { auto_renew => 1 } + ); Koha::CirculationRules->set_rules( { @@ -1289,11 +1348,11 @@ subtest "CanBookBeRenewed tests" => sub { } } ); - C4::Context->set_preference('OPACFineNoRenewalsBlockAutoRenew','1'); - C4::Context->set_preference('OPACFineNoRenewals','10'); - C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','1'); + C4::Context->set_preference( 'OPACFineNoRenewalsBlockAutoRenew', '1' ); + C4::Context->set_preference( 'OPACFineNoRenewals', '10' ); + C4::Context->set_preference( 'OPACFineNoRenewalsIncludeCredit', '1' ); my $fines_amount = 5; - my $account = Koha::Account->new({patron_id => $renewing_borrowernumber}); + my $account = Koha::Account->new( { patron_id => $renewing_borrowernumber } ); $account->add_debit( { amount => $fines_amount, @@ -1303,10 +1362,9 @@ subtest "CanBookBeRenewed tests" => sub { description => "Some fines" } )->status('RETURNED')->store; - ( $renewokay, $error ) = - CanBookBeRenewed( $renewing_borrower_obj, $issue ); - is( $renewokay, 1, 'Renew, even if renewal is automatic' ); - is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 5' ); + ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $issue ); + is( $renewokay, 1, 'Renew, even if renewal is automatic' ); + is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 5' ); $account->add_debit( { @@ -1317,10 +1375,9 @@ subtest "CanBookBeRenewed tests" => sub { description => "Some fines" } )->status('RETURNED')->store; - ( $renewokay, $error ) = - CanBookBeRenewed( $renewing_borrower_obj, $issue ); - is( $renewokay, 1, 'Renew, even if renewal is automatic' ); - is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 10' ); + ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $issue ); + is( $renewokay, 1, 'Renew, even if renewal is automatic' ); + is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, patron has 10' ); $account->add_debit( { @@ -1331,10 +1388,9 @@ subtest "CanBookBeRenewed tests" => sub { description => "Some fines" } )->status('RETURNED')->store; - ( $renewokay, $error ) = - CanBookBeRenewed( $renewing_borrower_obj, $issue ); - is( $renewokay, 0, 'Do not renew, renewal is automatic' ); - is( $error, 'auto_too_much_oweing', 'Cannot auto renew, OPACFineNoRenewals=10, patron has 15' ); + ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $issue ); + is( $renewokay, 0, 'Do not renew, renewal is automatic' ); + is( $error, 'auto_too_much_oweing', 'Cannot auto renew, OPACFineNoRenewals=10, patron has 15' ); $account->add_credit( { @@ -1344,19 +1400,23 @@ subtest "CanBookBeRenewed tests" => sub { description => "Some payment" } )->store; - ( $renewokay, $error ) = - CanBookBeRenewed( $renewing_borrower_obj, $issue ); + ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $issue ); is( $renewokay, 1, 'Renew, even if renewal is automatic' ); - is( $error, 'auto_renew', 'Can auto renew, OPACFineNoRenewals=10, OPACFineNoRenewalsIncludeCredit=1, patron has 15 debt, 5 credit' ); + is( + $error, 'auto_renew', + 'Can auto renew, OPACFineNoRenewals=10, OPACFineNoRenewalsIncludeCredit=1, patron has 15 debt, 5 credit' + ); - C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','0'); - ( $renewokay, $error ) = - CanBookBeRenewed( $renewing_borrower_obj, $issue ); + C4::Context->set_preference( 'OPACFineNoRenewalsIncludeCredit', '0' ); + ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $issue ); is( $renewokay, 0, 'Do not renew, renewal is automatic' ); - is( $error, 'auto_too_much_oweing', 'Cannot auto renew, OPACFineNoRenewals=10, OPACFineNoRenewalsIncludeCredit=1, patron has 15 debt, 5 credit' ); + is( + $error, 'auto_too_much_oweing', + 'Cannot auto renew, OPACFineNoRenewals=10, OPACFineNoRenewalsIncludeCredit=1, patron has 15 debt, 5 credit' + ); - $dbh->do('DELETE FROM accountlines WHERE borrowernumber=?', undef, $renewing_borrowernumber); - C4::Context->set_preference('OPACFineNoRenewalsIncludeCredit','1'); + $dbh->do( 'DELETE FROM accountlines WHERE borrowernumber=?', undef, $renewing_borrowernumber ); + C4::Context->set_preference( 'OPACFineNoRenewalsIncludeCredit', '1' ); }; subtest "auto_account_expired | BlockExpiredPatronOpacActions" => sub { @@ -1381,36 +1441,44 @@ subtest "CanBookBeRenewed tests" => sub { ); my $ten_days_before = dt_from_string->add( days => -10 ); - my $ten_days_ahead = dt_from_string->add( days => 10 ); + my $ten_days_ahead = dt_from_string->add( days => 10 ); # Patron is expired and BlockExpiredPatronOpacActions='' # => auto renew is allowed - t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', ''); - my $issue = AddIssue( $expired_borrower_obj, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } ); - ( $renewokay, $error ) = - CanBookBeRenewed( $expired_borrower_obj, $issue ); - is( $renewokay, 1, 'Renew, even if renewal is automatic' ); - is( $error, 'auto_renew', 'Can auto renew, patron is expired but BlockExpiredPatronOpacActions=\'\'' ); + t::lib::Mocks::mock_preference( 'BlockExpiredPatronOpacActions', '' ); + my $issue = AddIssue( + $expired_borrower_obj, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, + undef, { auto_renew => 1 } + ); + ( $renewokay, $error ) = CanBookBeRenewed( $expired_borrower_obj, $issue ); + is( $renewokay, 1, 'Renew, even if renewal is automatic' ); + is( $error, 'auto_renew', 'Can auto renew, patron is expired but BlockExpiredPatronOpacActions=\'\'' ); Koha::Checkouts->find( $issue->issue_id )->delete; - # Patron is expired and BlockExpiredPatronOpacActions='renew' # => auto renew is not allowed - t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 'renew'); - $issue = AddIssue( $expired_borrower_obj, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } ); - ( $renewokay, $error ) = - CanBookBeRenewed( $expired_borrower_obj, $issue ); + t::lib::Mocks::mock_preference( 'BlockExpiredPatronOpacActions', 'renew' ); + $issue = AddIssue( + $expired_borrower_obj, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, + undef, { auto_renew => 1 } + ); + ( $renewokay, $error ) = CanBookBeRenewed( $expired_borrower_obj, $issue ); is( $renewokay, 0, 'Do not renew, renewal is automatic' ); - is( $error, 'auto_account_expired', 'Can not auto renew, lockExpiredPatronOpacActions=1 and patron is expired' ); + is( + $error, 'auto_account_expired', + 'Can not auto renew, lockExpiredPatronOpacActions=1 and patron is expired' + ); $issue->delete; # Patron is not expired and BlockExpiredPatronOpacActions=1 # => auto renew is allowed - t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 'renew'); - $issue = AddIssue( $renewing_borrower_obj, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } ); - ( $renewokay, $error ) = - CanBookBeRenewed( $renewing_borrower_obj, $issue ); - is( $renewokay, 1, 'Renew, even if renewal is automatic' ); + t::lib::Mocks::mock_preference( 'BlockExpiredPatronOpacActions', 'renew' ); + $issue = AddIssue( + $renewing_borrower_obj, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, + undef, { auto_renew => 1 } + ); + ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $issue ); + is( $renewokay, 1, 'Renew, even if renewal is automatic' ); is( $error, 'auto_renew', 'Can auto renew, BlockExpiredPatronOpacActions=\'renew\' but patron is not expired' ); $issue->delete; }; @@ -1426,21 +1494,27 @@ subtest "CanBookBeRenewed tests" => sub { my $ten_days_before = dt_from_string->add( days => -10 ); my $ten_days_ahead = dt_from_string->add( days => 10 ); - my $issue = AddIssue( $renewing_borrower_obj, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, undef, { auto_renew => 1 } ); + my $issue = AddIssue( + $renewing_borrower_obj, $item_to_auto_renew->barcode, $ten_days_ahead, undef, $ten_days_before, + undef, { auto_renew => 1 } + ); Koha::CirculationRules->set_rules( { categorycode => undef, branchcode => undef, itemtype => undef, rules => { - norenewalbefore => '7', - no_auto_renewal_after => '', + norenewalbefore => '7', + no_auto_renewal_after => '', no_auto_renewal_after_hard_limit => undef, } } ); my $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrower_obj, $issue ); - is( $latest_auto_renew_date, undef, 'GetLatestAutoRenewDate should return undef if no_auto_renewal_after or no_auto_renewal_after_hard_limit are not defined' ); + is( + $latest_auto_renew_date, undef, + 'GetLatestAutoRenewDate should return undef if no_auto_renewal_after or no_auto_renewal_after_hard_limit are not defined' + ); my $five_days_before = dt_from_string->add( days => -5 ); Koha::CirculationRules->set_rules( { @@ -1448,21 +1522,23 @@ subtest "CanBookBeRenewed tests" => sub { branchcode => undef, itemtype => undef, rules => { - norenewalbefore => '10', - no_auto_renewal_after => '5', + norenewalbefore => '10', + no_auto_renewal_after => '5', no_auto_renewal_after_hard_limit => undef, } } ); $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrower_obj,, $issue ); - is( $latest_auto_renew_date->truncate( to => 'minute' ), + is( + $latest_auto_renew_date->truncate( to => 'minute' ), $five_days_before->truncate( to => 'minute' ), 'GetLatestAutoRenewDate should return -5 days if no_auto_renewal_after = 5 and date_due is 10 days before' ); my $five_days_ahead = dt_from_string->add( days => 5 ); $dbh->do(q{UPDATE circulation_rules SET rule_value = '10' WHERE rule_name = 'norenewalbefore'}); $dbh->do(q{UPDATE circulation_rules SET rule_value = '15' WHERE rule_name = 'no_auto_renewal_after'}); - $dbh->do(q{UPDATE circulation_rules SET rule_value = NULL WHERE rule_name = 'no_auto_renewal_after_hard_limit'}); + $dbh->do( + q{UPDATE circulation_rules SET rule_value = NULL WHERE rule_name = 'no_auto_renewal_after_hard_limit'}); Koha::Cache::Memory::Lite->flush(); Koha::CirculationRules->set_rules( { @@ -1470,14 +1546,15 @@ subtest "CanBookBeRenewed tests" => sub { branchcode => undef, itemtype => undef, rules => { - norenewalbefore => '10', - no_auto_renewal_after => '15', + norenewalbefore => '10', + no_auto_renewal_after => '15', no_auto_renewal_after_hard_limit => undef, } } ); $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrower_obj, $issue ); - is( $latest_auto_renew_date->truncate( to => 'minute' ), + is( + $latest_auto_renew_date->truncate( to => 'minute' ), $five_days_ahead->truncate( to => 'minute' ), 'GetLatestAutoRenewDate should return +5 days if no_auto_renewal_after = 15 and date_due is 10 days before' ); @@ -1488,14 +1565,15 @@ subtest "CanBookBeRenewed tests" => sub { branchcode => undef, itemtype => undef, rules => { - norenewalbefore => '10', - no_auto_renewal_after => '', + norenewalbefore => '10', + no_auto_renewal_after => '', no_auto_renewal_after_hard_limit => dt_from_string->add( days => 2 ), } } ); $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrower_obj, $issue ); - is( $latest_auto_renew_date->truncate( to => 'day' ), + is( + $latest_auto_renew_date->truncate( to => 'day' ), $two_days_ahead->truncate( to => 'day' ), 'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is defined and not no_auto_renewal_after' ); @@ -1505,14 +1583,15 @@ subtest "CanBookBeRenewed tests" => sub { branchcode => undef, itemtype => undef, rules => { - norenewalbefore => '10', - no_auto_renewal_after => '15', + norenewalbefore => '10', + no_auto_renewal_after => '15', no_auto_renewal_after_hard_limit => dt_from_string->add( days => 2 ), } } ); $latest_auto_renew_date = GetLatestAutoRenewDate( $renewing_borrower_obj, $issue ); - is( $latest_auto_renew_date->truncate( to => 'day' ), + is( + $latest_auto_renew_date->truncate( to => 'day' ), $two_days_ahead->truncate( to => 'day' ), 'GetLatestAutoRenewDate should return +2 days if no_auto_renewal_after_hard_limit is < no_auto_renewal_after' ); @@ -1597,9 +1676,9 @@ subtest "CanBookBeRenewed tests" => sub { } ); - ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_1); - is( $renewokay, 0, 'Cannot renew, 0 renewals allowed'); - is( $error, 'too_many', 'Cannot renew, 0 renewals allowed (returned code is too_many)'); + ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $issue_1 ); + is( $renewokay, 0, 'Cannot renew, 0 renewals allowed' ); + is( $error, 'too_many', 'Cannot renew, 0 renewals allowed (returned code is too_many)' ); # Too many unseen renewals Koha::CirculationRules->set_rules( @@ -1609,17 +1688,17 @@ subtest "CanBookBeRenewed tests" => sub { itemtype => undef, rules => { unseen_renewals_allowed => 2, - renewalsallowed => 10, + renewalsallowed => 10, } } ); - t::lib::Mocks::mock_preference('UnseenRenewals', 1); + t::lib::Mocks::mock_preference( 'UnseenRenewals', 1 ); $issue_1->unseen_renewals(2)->store; - ( $renewokay, $error ) = CanBookBeRenewed($renewing_borrower_obj, $issue_1); - is( $renewokay, 0, 'Cannot renew, 0 unseen renewals allowed'); - is( $error, 'too_unseen', 'Cannot renew, returned code is too_unseen'); + ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $issue_1 ); + is( $renewokay, 0, 'Cannot renew, 0 unseen renewals allowed' ); + is( $error, 'too_unseen', 'Cannot renew, returned code is too_unseen' ); Koha::CirculationRules->set_rules( { categorycode => undef, @@ -1631,11 +1710,11 @@ subtest "CanBookBeRenewed tests" => sub { } } ); - t::lib::Mocks::mock_preference('UnseenRenewals', 0); + t::lib::Mocks::mock_preference( 'UnseenRenewals', 0 ); # Test WhenLostForgiveFine and WhenLostChargeReplacementFee - t::lib::Mocks::mock_preference('WhenLostForgiveFine','1'); - t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1'); + t::lib::Mocks::mock_preference( 'WhenLostForgiveFine', '1' ); + t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', '1' ); C4::Overdues::UpdateFine( { @@ -1648,29 +1727,29 @@ subtest "CanBookBeRenewed tests" => sub { } ); - my $line = Koha::Account::Lines->search({ borrowernumber => $renewing_borrower_obj->borrowernumber })->next(); - is( $line->debit_type_code, 'OVERDUE', 'Account line type is OVERDUE' ); - is( $line->status, 'UNRETURNED', 'Account line status is UNRETURNED' ); - is( $line->amountoutstanding+0, 15, 'Account line amount outstanding is 15.00' ); - is( $line->amount+0, 15, 'Account line amount is 15.00' ); - is( $line->issue_id, $issue_1->id, 'Account line issue id matches' ); + my $line = Koha::Account::Lines->search( { borrowernumber => $renewing_borrower_obj->borrowernumber } )->next(); + is( $line->debit_type_code, 'OVERDUE', 'Account line type is OVERDUE' ); + is( $line->status, 'UNRETURNED', 'Account line status is UNRETURNED' ); + is( $line->amountoutstanding + 0, 15, 'Account line amount outstanding is 15.00' ); + is( $line->amount + 0, 15, 'Account line amount is 15.00' ); + is( $line->issue_id, $issue_1->id, 'Account line issue id matches' ); - my $offset = Koha::Account::Offsets->search({ debit_id => $line->id })->next(); - is( $offset->type, 'CREATE', 'Account offset type is CREATE' ); - is( $offset->amount+0, 15, 'Account offset amount is 15.00' ); + my $offset = Koha::Account::Offsets->search( { debit_id => $line->id } )->next(); + is( $offset->type, 'CREATE', 'Account offset type is CREATE' ); + is( $offset->amount + 0, 15, 'Account offset amount is 15.00' ); - t::lib::Mocks::mock_preference('WhenLostForgiveFine','0'); - t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','0'); + t::lib::Mocks::mock_preference( 'WhenLostForgiveFine', '0' ); + t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', '0' ); LostItem( $item_1->itemnumber, 'test', 1 ); - $line = Koha::Account::Lines->find($line->id); + $line = Koha::Account::Lines->find( $line->id ); is( $line->debit_type_code, 'OVERDUE', 'Account type remains as OVERDUE' ); isnt( $line->status, 'UNRETURNED', 'Account status correctly changed from UNRETURNED to RETURNED' ); - my $item = Koha::Items->find($item_1->itemnumber); + my $item = Koha::Items->find( $item_1->itemnumber ); ok( !$item->onloan(), "Lost item marked as returned has false onloan value" ); - my $checkout = Koha::Checkouts->find({ itemnumber => $item_1->itemnumber }); + my $checkout = Koha::Checkouts->find( { itemnumber => $item_1->itemnumber } ); is( $checkout, undef, 'LostItem called with forced return has checked in the item' ); my $total_due = $dbh->selectrow_array( @@ -1678,7 +1757,10 @@ subtest "CanBookBeRenewed tests" => sub { undef, $renewing_borrower_obj->borrowernumber ); - is( $total_due+0, 15, 'Borrower only charged replacement fee with both WhenLostForgiveFine and WhenLostChargeReplacementFee enabled' ); + is( + $total_due + 0, 15, + 'Borrower only charged replacement fee with both WhenLostForgiveFine and WhenLostChargeReplacementFee enabled' + ); C4::Context->dbh->do("DELETE FROM accountlines"); @@ -1695,101 +1777,119 @@ subtest "CanBookBeRenewed tests" => sub { LostItem( $item_2->itemnumber, 'test', 0 ); - my $item2 = Koha::Items->find($item_2->itemnumber); + my $item2 = Koha::Items->find( $item_2->itemnumber ); ok( $item2->onloan(), "Lost item *not* marked as returned has true onloan value" ); - ok( Koha::Checkouts->find({ itemnumber => $item_2->itemnumber }), 'LostItem called without forced return has checked in the item' ); + ok( + Koha::Checkouts->find( { itemnumber => $item_2->itemnumber } ), + 'LostItem called without forced return has checked in the item' + ); $total_due = $dbh->selectrow_array( 'SELECT SUM( amountoutstanding ) FROM accountlines WHERE borrowernumber = ?', undef, $renewing_borrower_obj->borrowernumber ); - ok( $total_due == 15, 'Borrower only charged fine with both WhenLostForgiveFine and WhenLostChargeReplacementFee disabled' ); + ok( + $total_due == 15, + 'Borrower only charged fine with both WhenLostForgiveFine and WhenLostChargeReplacementFee disabled' + ); my $future = dt_from_string(); $future->add( days => 7 ); - my $units = C4::Overdues::get_chargeable_units('days', $future, $now, $library2->{branchcode}); + my $units = C4::Overdues::get_chargeable_units( 'days', $future, $now, $library2->{branchcode} ); ok( $units == 0, '_get_chargeable_units returns 0 for items not past due date (Bug 12596)' ); - my $manager = $builder->build_object({ class => "Koha::Patrons" }); - t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode }); - t::lib::Mocks::mock_preference('WhenLostChargeReplacementFee','1'); + my $manager = $builder->build_object( { class => "Koha::Patrons" } ); + t::lib::Mocks::mock_userenv( { patron => $manager, branchcode => $manager->branchcode } ); + t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', '1' ); $checkout = Koha::Checkouts->find( { itemnumber => $item_3->itemnumber } ); LostItem( $item_3->itemnumber, 'test', 0 ); my $accountline = Koha::Account::Lines->find( { itemnumber => $item_3->itemnumber } ); is( $accountline->issue_id, $checkout->id, "Issue id added for lost replacement fee charge" ); is( $accountline->description, - sprintf( "%s %s %s", + sprintf( + "%s %s %s", $item_3->biblio->title || '', $item_3->barcode || '', - $item_3->itemcallnumber || '' ), + $item_3->itemcallnumber || '' + ), "Account line description must not contain 'Lost Items ', but be title, barcode, itemcallnumber" ); # Recalls - t::lib::Mocks::mock_preference('UseRecalls', 1); - Koha::CirculationRules->set_rules({ - categorycode => undef, - branchcode => undef, - itemtype => undef, - rules => { - recalls_allowed => 10, - renewalsallowed => 5, - }, - }); - my $recall_borrower = $builder->build_object({ class => 'Koha::Patrons' }); - my $recall_biblio = $builder->build_sample_biblio(); - my $recall_item1 = $builder->build_sample_item({ biblionumber => $recall_biblio->biblionumber }); - my $recall_item2 = $builder->build_sample_item({ biblionumber => $recall_biblio->biblionumber }); + t::lib::Mocks::mock_preference( 'UseRecalls', 1 ); + Koha::CirculationRules->set_rules( + { + categorycode => undef, + branchcode => undef, + itemtype => undef, + rules => { + recalls_allowed => 10, + renewalsallowed => 5, + }, + } + ); + my $recall_borrower = $builder->build_object( { class => 'Koha::Patrons' } ); + my $recall_biblio = $builder->build_sample_biblio(); + my $recall_item1 = $builder->build_sample_item( { biblionumber => $recall_biblio->biblionumber } ); + my $recall_item2 = $builder->build_sample_item( { biblionumber => $recall_biblio->biblionumber } ); my $recall_issue = AddIssue( $renewing_borrower_obj, $recall_item1->barcode ); # item-level and this item: renewal not allowed - my $recall = Koha::Recall->new({ - biblio_id => $recall_item1->biblionumber, - item_id => $recall_item1->itemnumber, - patron_id => $recall_borrower->borrowernumber, - pickup_library_id => $recall_borrower->branchcode, - item_level => 1, - })->store; + my $recall = Koha::Recall->new( + { + biblio_id => $recall_item1->biblionumber, + item_id => $recall_item1->itemnumber, + patron_id => $recall_borrower->borrowernumber, + pickup_library_id => $recall_borrower->branchcode, + item_level => 1, + } + )->store; ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $recall_issue ); is( $error, 'recalled', 'Cannot renew item that has been recalled' ); $recall->set_cancelled; # biblio-level requested recall: renewal not allowed - $recall = Koha::Recall->new({ - biblio_id => $recall_item1->biblionumber, - item_id => undef, - patron_id => $recall_borrower->borrowernumber, - pickup_library_id => $recall_borrower->branchcode, - item_level => 0, - })->store; + $recall = Koha::Recall->new( + { + biblio_id => $recall_item1->biblionumber, + item_id => undef, + patron_id => $recall_borrower->borrowernumber, + pickup_library_id => $recall_borrower->branchcode, + item_level => 0, + } + )->store; ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $recall_issue ); is( $error, 'recalled', 'Cannot renew item if biblio is recalled and has no item allocated' ); $recall->set_cancelled; # item-level and not this item: renewal allowed - $recall = Koha::Recall->new({ - biblio_id => $recall_item2->biblionumber, - item_id => $recall_item2->itemnumber, - patron_id => $recall_borrower->borrowernumber, - pickup_library_id => $recall_borrower->branchcode, - item_level => 1, - })->store; + $recall = Koha::Recall->new( + { + biblio_id => $recall_item2->biblionumber, + item_id => $recall_item2->itemnumber, + patron_id => $recall_borrower->borrowernumber, + pickup_library_id => $recall_borrower->branchcode, + item_level => 1, + } + )->store; ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $recall_issue ); is( $renewokay, 1, 'Can renew item if item-level recall on biblio is not on this item' ); $recall->set_cancelled; # biblio-level waiting recall: renewal allowed - $recall = Koha::Recall->new({ - biblio_id => $recall_item1->biblionumber, - item_id => undef, - patron_id => $recall_borrower->borrowernumber, - pickup_library_id => $recall_borrower->branchcode, - item_level => 0, - })->store; - $recall->set_waiting({ item => $recall_item1 }); + $recall = Koha::Recall->new( + { + biblio_id => $recall_item1->biblionumber, + item_id => undef, + patron_id => $recall_borrower->borrowernumber, + pickup_library_id => $recall_borrower->branchcode, + item_level => 0, + } + )->store; + $recall->set_waiting( { item => $recall_item1 } ); ( $renewokay, $error ) = CanBookBeRenewed( $renewing_borrower_obj, $recall_issue ); is( $renewokay, 1, 'Can renew item if biblio-level recall has already been allocated an item' ); $recall->set_cancelled; @@ -1836,7 +1936,7 @@ subtest "CanBookBeRenewed | bookings" => sub { subtest "GetUpcomingDueIssues" => sub { plan tests => 12; - my $branch = $library2->{branchcode}; + my $branch = $library2->{branchcode}; #Create another record my $biblio2 = $builder->build_sample_biblio(); @@ -1846,49 +1946,50 @@ subtest "GetUpcomingDueIssues" => sub { my $item_2 = Koha::Items->find($reused_itemnumber_2); my $item_3 = $builder->build_sample_item( { - biblionumber => $biblio2->biblionumber, - library => $branch, - itype => $itemtype, + biblionumber => $biblio2->biblionumber, + library => $branch, + itype => $itemtype, } ); - # Create a borrower my %a_borrower_data = ( - firstname => 'Fridolyn', - surname => 'SOMERS', + firstname => 'Fridolyn', + surname => 'SOMERS', categorycode => $patron_category->{categorycode}, - branchcode => $branch, + branchcode => $branch, ); - my $a_borrower_borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber; - my $a_borrower = Koha::Patrons->find( $a_borrower_borrowernumber ); + my $a_borrower_borrowernumber = Koha::Patron->new( \%a_borrower_data )->store->borrowernumber; + my $a_borrower = Koha::Patrons->find($a_borrower_borrowernumber); - my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 ); - my $two_days_ahead = DateTime->today(time_zone => C4::Context->tz())->add( days => 2 ); - my $today = DateTime->today(time_zone => C4::Context->tz()); + my $yesterday = DateTime->today( time_zone => C4::Context->tz() )->add( days => -1 ); + my $two_days_ahead = DateTime->today( time_zone => C4::Context->tz() )->add( days => 2 ); + my $today = DateTime->today( time_zone => C4::Context->tz() ); - my $issue = AddIssue( $a_borrower, $item_1->barcode, $yesterday ); - my $datedue = dt_from_string( $issue->date_due() ); - my $issue_2 = AddIssue( $a_borrower, $item_2->barcode, $two_days_ahead ); + my $issue = AddIssue( $a_borrower, $item_1->barcode, $yesterday ); + my $datedue = dt_from_string( $issue->date_due() ); + my $issue_2 = AddIssue( $a_borrower, $item_2->barcode, $two_days_ahead ); my $datedue2 = dt_from_string( $issue->date_due() ); my $upcoming_dues; # GetUpcomingDueIssues tests - for my $i(0..1) { + for my $i ( 0 .. 1 ) { $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } ); - is ( scalar( @$upcoming_dues ), 0, "No items due in less than one day ($i days in advance)" ); + is( scalar(@$upcoming_dues), 0, "No items due in less than one day ($i days in advance)" ); } #days_in_advance needs to be inclusive, so 1 matches items due tomorrow, 0 items due today etc. $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } ); - is ( scalar ( @$upcoming_dues), 1, "Only one item due in 2 days or less" ); + is( scalar(@$upcoming_dues), 1, "Only one item due in 2 days or less" ); - for my $i(3..5) { + for my $i ( 3 .. 5 ) { $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => $i } ); - is ( scalar( @$upcoming_dues ), 1, - "Bug 9362: Only one item due in more than 2 days ($i days in advance)" ); + is( + scalar(@$upcoming_dues), 1, + "Bug 9362: Only one item due in more than 2 days ($i days in advance)" + ); } # Bug 11218 - Due notices not generated - GetUpcomingDueIssues needs to select due today items as well @@ -1896,51 +1997,51 @@ subtest "GetUpcomingDueIssues" => sub { my $issue3 = AddIssue( $a_borrower, $item_3->barcode, $today ); $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => -1 } ); - is ( scalar ( @$upcoming_dues), 0, "Overdues can not be selected" ); + is( scalar(@$upcoming_dues), 0, "Overdues can not be selected" ); $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 0 } ); - is ( scalar ( @$upcoming_dues), 1, "1 item is due today" ); + is( scalar(@$upcoming_dues), 1, "1 item is due today" ); $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 1 } ); - is ( scalar ( @$upcoming_dues), 1, "1 item is due today, none tomorrow" ); + is( scalar(@$upcoming_dues), 1, "1 item is due today, none tomorrow" ); - $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } ); - is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" ); + $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 2 } ); + is( scalar(@$upcoming_dues), 2, "2 items are due withing 2 days" ); $upcoming_dues = C4::Circulation::GetUpcomingDueIssues( { days_in_advance => 3 } ); - is ( scalar ( @$upcoming_dues), 2, "2 items are due withing 2 days" ); + is( scalar(@$upcoming_dues), 2, "2 items are due withing 2 days" ); $upcoming_dues = C4::Circulation::GetUpcomingDueIssues(); - is ( scalar ( @$upcoming_dues), 2, "days_in_advance is 7 in GetUpcomingDueIssues if not provided" ); + is( scalar(@$upcoming_dues), 2, "days_in_advance is 7 in GetUpcomingDueIssues if not provided" ); }; subtest "Bug 13841 - Do not create new 0 amount fines" => sub { - my $branch = $library2->{branchcode}; + my $branch = $library2->{branchcode}; my $biblio = $builder->build_sample_biblio(); #Create third item my $item = $builder->build_sample_item( { - biblionumber => $biblio->biblionumber, - library => $branch, - itype => $itemtype, + biblionumber => $biblio->biblionumber, + library => $branch, + itype => $itemtype, } ); # Create a borrower my %a_borrower_data = ( - firstname => 'Kyle', - surname => 'Hall', + firstname => 'Kyle', + surname => 'Hall', categorycode => $patron_category->{categorycode}, - branchcode => $branch, + branchcode => $branch, ); - my $borrowernumber = Koha::Patron->new(\%a_borrower_data)->store->borrowernumber; + my $borrowernumber = Koha::Patron->new( \%a_borrower_data )->store->borrowernumber; - my $borrower = Koha::Patrons->find( $borrowernumber ); - my $issue = AddIssue( $borrower, $item->barcode ); + my $borrower = Koha::Patrons->find($borrowernumber); + my $issue = AddIssue( $borrower, $item->barcode ); UpdateFine( { issue_id => $issue->id(), @@ -1951,10 +2052,13 @@ subtest "Bug 13841 - Do not create new 0 amount fines" => sub { } ); - my $hr = $dbh->selectrow_hashref(q{SELECT COUNT(*) AS count FROM accountlines WHERE borrowernumber = ? AND itemnumber = ?}, undef, $borrowernumber, $item->itemnumber ); + my $hr = $dbh->selectrow_hashref( + q{SELECT COUNT(*) AS count FROM accountlines WHERE borrowernumber = ? AND itemnumber = ?}, undef, + $borrowernumber, $item->itemnumber + ); my $count = $hr->{count}; - is ( $count, 0, "Calling UpdateFine on non-existant fine with an amount of 0 does not result in an empty fine" ); + is( $count, 0, "Calling UpdateFine on non-existant fine with an amount of 0 does not result in an empty fine" ); }; subtest "AllowRenewalIfOtherItemsAvailable tests" => sub { @@ -1962,15 +2066,15 @@ subtest "AllowRenewalIfOtherItemsAvailable tests" => sub { my $biblio = $builder->build_sample_biblio(); my $item_1 = $builder->build_sample_item( { - biblionumber => $biblio->biblionumber, - library => $library2->{branchcode}, + biblionumber => $biblio->biblionumber, + library => $library2->{branchcode}, } ); - my $item_2= $builder->build_sample_item( + my $item_2 = $builder->build_sample_item( { - biblionumber => $biblio->biblionumber, - library => $library2->{branchcode}, - itype => $item_1->effective_itemtype, + biblionumber => $biblio->biblionumber, + library => $library2->{branchcode}, + itype => $item_1->effective_itemtype, } ); @@ -1980,17 +2084,17 @@ subtest "AllowRenewalIfOtherItemsAvailable tests" => sub { itemtype => $item_1->effective_itemtype, branchcode => undef, rules => { - reservesallowed => 25, + reservesallowed => 25, holds_per_record => 25, - issuelength => 14, - lengthunit => 'days', - renewalsallowed => 1, - renewalperiod => 7, - norenewalbefore => undef, - auto_renew => 0, - fine => .10, - chargeperiod => 1, - maxissueqty => 20 + issuelength => 14, + lengthunit => 'days', + renewalsallowed => 1, + renewalperiod => 7, + norenewalbefore => undef, + auto_renew => 0, + fine => .10, + chargeperiod => 1, + maxissueqty => 20 } } ); @@ -2069,11 +2173,17 @@ subtest "AllowRenewalIfOtherItemsAvailable tests" => sub { ); t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 ); ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue ); - is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfholds are disabled' ); + is( + $renewokay, 0, + 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfholds are disabled' + ); t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 ); ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue ); - is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is enabled and onshelfholds is disabled' ); + is( + $renewokay, 0, + 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is enabled and onshelfholds is disabled' + ); Koha::CirculationRules->set_rules( { @@ -2087,11 +2197,17 @@ subtest "AllowRenewalIfOtherItemsAvailable tests" => sub { ); t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 0 ); ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue ); - is( $renewokay, 0, 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is disabled and onshelfhold is enabled' ); + is( + $renewokay, 0, + 'Bug 14337 - Verify the borrower cannot renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is disabled and onshelfhold is enabled' + ); t::lib::Mocks::mock_preference( 'AllowRenewalIfOtherItemsAvailable', 1 ); ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue ); - is( $renewokay, 1, 'Bug 14337 - Verify the borrower can renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfhold are enabled' ); + is( + $renewokay, 1, + 'Bug 14337 - Verify the borrower can renew with a hold on the record if AllowRenewalIfOtherItemsAvailable and onshelfhold are enabled' + ); AddReserve( { @@ -2103,18 +2219,24 @@ subtest "AllowRenewalIfOtherItemsAvailable tests" => sub { ); ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue ); - is( $renewokay, 0, 'Verify the borrower cannot renew with 2 holds on the record if AllowRenewalIfOtherItemsAvailable and onshelfhold are enabled and one other item on record' ); + is( + $renewokay, 0, + 'Verify the borrower cannot renew with 2 holds on the record if AllowRenewalIfOtherItemsAvailable and onshelfhold are enabled and one other item on record' + ); - my $item_3= $builder->build_sample_item( + my $item_3 = $builder->build_sample_item( { - biblionumber => $biblio->biblionumber, - library => $library2->{branchcode}, - itype => $item_1->effective_itemtype, + biblionumber => $biblio->biblionumber, + library => $library2->{branchcode}, + itype => $item_1->effective_itemtype, } ); ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue ); - is( $renewokay, 1, 'Verify the borrower cannot renew with 2 holds on the record if AllowRenewalIfOtherItemsAvailable and onshelfhold are enabled and two other items on record' ); + is( + $renewokay, 1, + 'Verify the borrower cannot renew with 2 holds on the record if AllowRenewalIfOtherItemsAvailable and onshelfhold are enabled and two other items on record' + ); Koha::CirculationRules->set_rules( { @@ -2128,7 +2250,10 @@ subtest "AllowRenewalIfOtherItemsAvailable tests" => sub { ); ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue ); - is( $renewokay, 0, 'Verify the borrower cannot renew with 2 holds on the record, but only one of those holds can be filled when AllowRenewalIfOtherItemsAvailable and onshelfhold are enabled and two other items on record' ); + is( + $renewokay, 0, + 'Verify the borrower cannot renew with 2 holds on the record, but only one of those holds can be filled when AllowRenewalIfOtherItemsAvailable and onshelfhold are enabled and two other items on record' + ); Koha::CirculationRules->set_rules( { @@ -2145,28 +2270,35 @@ subtest "AllowRenewalIfOtherItemsAvailable tests" => sub { $item_2->notforloan(-1)->store; ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue ); - is( $renewokay, 0, 'Bug 14337 - Verify the borrower can not renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is enabled but the only available item is notforloan' ); + is( + $renewokay, 0, + 'Bug 14337 - Verify the borrower can not renew with a hold on the record if AllowRenewalIfOtherItemsAvailable is enabled but the only available item is notforloan' + ); my $mock_circ = Test::MockModule->new("C4::Circulation"); - $mock_circ->mock( CanItemBeReserved => sub { - warn "Checked"; - return { status => 'no' } - } ); + $mock_circ->mock( + CanItemBeReserved => sub { + warn "Checked"; + return { status => 'no' }; + } + ); $item_2->notforloan(0)->store; $item_3->delete(); + # Two items total, one item available, one issued, two holds on record - warnings_are{ - ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue ); - } [], "CanItemBeReserved not called when there are more possible holds than available items"; + warnings_are { + ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue ); + } + [], "CanItemBeReserved not called when there are more possible holds than available items"; is( $renewokay, 0, 'Borrower cannot renew when there are more holds than available items' ); $item_3 = $builder->build_sample_item( { - biblionumber => $biblio->biblionumber, - library => $library2->{branchcode}, - itype => $item_1->effective_itemtype, + biblionumber => $biblio->biblionumber, + library => $library2->{branchcode}, + itype => $item_1->effective_itemtype, } ); @@ -2181,25 +2313,27 @@ subtest "AllowRenewalIfOtherItemsAvailable tests" => sub { } ); - warnings_are{ - ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue ); - } ["Checked","Checked"], "CanItemBeReserved only called once per available item if it returns a negative result for all items for a borrower"; + warnings_are { + ( $renewokay, $error ) = CanBookBeRenewed( $borrower1, $issue ); + } + [ "Checked", "Checked" ], + "CanItemBeReserved only called once per available item if it returns a negative result for all items for a borrower"; is( $renewokay, 0, 'Borrower cannot renew when there are more holds than available items' ); }; { # Don't allow renewing onsite checkout - my $branch = $library->{branchcode}; + my $branch = $library->{branchcode}; #Create another record my $biblio = $builder->build_sample_biblio(); my $item = $builder->build_sample_item( { - biblionumber => $biblio->biblionumber, - library => $branch, - itype => $itemtype, + biblionumber => $biblio->biblionumber, + library => $branch, + itype => $itemtype, } ); @@ -2207,33 +2341,38 @@ subtest "AllowRenewalIfOtherItemsAvailable tests" => sub { { class => 'Koha::Patrons', value => { - firstname => 'fn', - surname => 'dn', + firstname => 'fn', + surname => 'dn', categorycode => $patron_category->{categorycode}, - branchcode => $branch, + branchcode => $branch, } } ); my $issue = AddIssue( $borrower, $item->barcode, undef, undef, undef, undef, { onsite_checkout => 1 } ); my ( $renewed, $error ) = CanBookBeRenewed( $borrower, $issue ); - is( $renewed, 0, 'CanBookBeRenewed should not allow to renew on-site checkout' ); + is( $renewed, 0, 'CanBookBeRenewed should not allow to renew on-site checkout' ); is( $error, 'onsite_checkout', 'A correct error code should be returned by CanBookBeRenewed for on-site checkout' ); } { - my $library = $builder->build({ source => 'Branch' }); + my $library = $builder->build( { source => 'Branch' } ); my $biblio = $builder->build_sample_biblio(); my $item = $builder->build_sample_item( { - biblionumber => $biblio->biblionumber, - library => $library->{branchcode}, - itype => $itemtype, + biblionumber => $biblio->biblionumber, + library => $library->{branchcode}, + itype => $itemtype, + } + ); + my $patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { branchcode => $library->{branchcode}, categorycode => $patron_category->{categorycode} } } ); - my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { branchcode => $library->{branchcode}, categorycode => $patron_category->{categorycode} } } ); my $issue = AddIssue( $patron, $item->barcode ); UpdateFine( @@ -2254,7 +2393,10 @@ subtest "AllowRenewalIfOtherItemsAvailable tests" => sub { type => q{} } ); - is( Koha::Account::Lines->search({ issue_id => $issue->id })->count, 1, 'UpdateFine should not create a new accountline when updating an existing fine'); + is( + Koha::Account::Lines->search( { issue_id => $issue->id } )->count, 1, + 'UpdateFine should not create a new accountline when updating an existing fine' + ); } subtest 'CanBookBeIssued & AllowReturnToBranch' => sub { @@ -2263,8 +2405,10 @@ subtest 'CanBookBeIssued & AllowReturnToBranch' => sub { my $homebranch = $builder->build( { source => 'Branch' } ); my $holdingbranch = $builder->build( { source => 'Branch' } ); my $otherbranch = $builder->build( { source => 'Branch' } ); - my $patron_1 = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } ); - my $patron_2 = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } ); + my $patron_1 = $builder->build_object( + { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } ); + my $patron_2 = $builder->build_object( + { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } ); my $item = $builder->build_sample_item( { @@ -2312,16 +2456,25 @@ subtest 'CanBookBeIssued & AllowReturnToBranch' => sub { ## Can be issued from homebranch set_userenv($homebranch); ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode ); - is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) ); + is( + keys(%$error) + keys(%$alerts), 0, + 'There should not be any errors or alerts (impossible)' . str( $error, $question, $alerts ) + ); is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' ); ## Can be issued from holdingbranch set_userenv($holdingbranch); ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode ); - is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) ); + is( + keys(%$error) + keys(%$alerts), 0, + 'There should not be any errors or alerts (impossible)' . str( $error, $question, $alerts ) + ); is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' ); ## Can be issued from another branch ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode ); - is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) ); + is( + keys(%$error) + keys(%$alerts), 0, + 'There should not be any errors or alerts (impossible)' . str( $error, $question, $alerts ) + ); is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' ); # AllowReturnToBranch == holdingbranch @@ -2329,19 +2482,28 @@ subtest 'CanBookBeIssued & AllowReturnToBranch' => sub { ## Cannot be issued from homebranch set_userenv($homebranch); ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode ); - is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) ); - is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' ); + is( + keys(%$question) + keys(%$alerts), 0, + 'There should not be any errors or alerts (impossible)' . str( $error, $question, $alerts ) + ); + is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' ); is( $error->{branch_to_return}, $holdingbranch->{branchcode}, 'branch_to_return matched holdingbranch' ); ## Can be issued from holdinbranch set_userenv($holdingbranch); ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode ); - is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) ); + is( + keys(%$error) + keys(%$alerts), 0, + 'There should not be any errors or alerts (impossible)' . str( $error, $question, $alerts ) + ); is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' ); ## Cannot be issued from another branch set_userenv($otherbranch); ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode ); - is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) ); - is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' ); + is( + keys(%$question) + keys(%$alerts), 0, + 'There should not be any errors or alerts (impossible)' . str( $error, $question, $alerts ) + ); + is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' ); is( $error->{branch_to_return}, $holdingbranch->{branchcode}, 'branch_to_return matches holdingbranch' ); # AllowReturnToBranch == homebranch @@ -2349,19 +2511,28 @@ subtest 'CanBookBeIssued & AllowReturnToBranch' => sub { ## Can be issued from holdinbranch set_userenv($homebranch); ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode ); - is( keys(%$error) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) ); + is( + keys(%$error) + keys(%$alerts), 0, + 'There should not be any errors or alerts (impossible)' . str( $error, $question, $alerts ) + ); is( exists $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER must be set' ); ## Cannot be issued from holdinbranch set_userenv($holdingbranch); ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode ); - is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) ); - is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' ); + is( + keys(%$question) + keys(%$alerts), 0, + 'There should not be any errors or alerts (impossible)' . str( $error, $question, $alerts ) + ); + is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' ); is( $error->{branch_to_return}, $homebranch->{branchcode}, 'branch_to_return matches homebranch' ); ## Cannot be issued from holdinbranch set_userenv($otherbranch); ( $error, $question, $alerts ) = CanBookBeIssued( $patron_2, $item->barcode ); - is( keys(%$question) + keys(%$alerts), 0, 'There should not be any errors or alerts (impossible)' . str($error, $question, $alerts) ); - is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' ); + is( + keys(%$question) + keys(%$alerts), 0, + 'There should not be any errors or alerts (impossible)' . str( $error, $question, $alerts ) + ); + is( exists $error->{RETURN_IMPOSSIBLE}, 1, 'RETURN_IMPOSSIBLE must be set' ); is( $error->{branch_to_return}, $homebranch->{branchcode}, 'branch_to_return matches homebranch' ); # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch'); @@ -2374,16 +2545,19 @@ subtest 'AddIssue & AllowReturnToBranch' => sub { my $holdingbranch = $builder->build( { source => 'Branch' } ); my $otherbranch = $builder->build( { source => 'Branch' } ); - my $patron_1 = $builder->build_object({ - class => 'Koha::Patrons', - value => { categorycode => $patron_category->{categorycode} } - }); - - my $patron_2 = $builder->build_object({ - class => 'Koha::Patrons', - value => { categorycode => $patron_category->{categorycode} } - }); + my $patron_1 = $builder->build_object( + { + class => 'Koha::Patrons', + value => { categorycode => $patron_category->{categorycode} } + } + ); + my $patron_2 = $builder->build_object( + { + class => 'Koha::Patrons', + value => { categorycode => $patron_category->{categorycode} } + } + ); my $item = $builder->build_sample_item( { @@ -2395,7 +2569,7 @@ subtest 'AddIssue & AllowReturnToBranch' => sub { set_userenv($holdingbranch); my $ref_issue = 'Koha::Checkout'; - my $issue = AddIssue( $patron_1, $item->barcode ); + my $issue = AddIssue( $patron_1, $item->barcode ); my ( $error, $question, $alerts ); @@ -2403,65 +2577,100 @@ subtest 'AddIssue & AllowReturnToBranch' => sub { t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' ); ## Can be issued from homebranch set_userenv($homebranch); - is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from homebranch'); - set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue + is( + ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, + 'AllowReturnToBranch - anywhere | Can be issued from homebranch' + ); + set_userenv($holdingbranch); + AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue ## Can be issued from holdinbranch set_userenv($holdingbranch); - is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from holdingbranch'); - set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue + is( + ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, + 'AllowReturnToBranch - anywhere | Can be issued from holdingbranch' + ); + set_userenv($holdingbranch); + AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue ## Can be issued from another branch set_userenv($otherbranch); - is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - anywhere | Can be issued from otherbranch'); - set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue + is( + ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, + 'AllowReturnToBranch - anywhere | Can be issued from otherbranch' + ); + set_userenv($holdingbranch); + AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue # AllowReturnToBranch == holdinbranch t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' ); ## Cannot be issued from homebranch set_userenv($homebranch); - is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - holdingbranch | Cannot be issued from homebranch'); + is( + ref( AddIssue( $patron_2, $item->barcode ) ), '', + 'AllowReturnToBranch - holdingbranch | Cannot be issued from homebranch' + ); ## Can be issued from holdingbranch set_userenv($holdingbranch); - is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - holdingbranch | Can be issued from holdingbranch'); - set_userenv($holdingbranch); AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue + is( + ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, + 'AllowReturnToBranch - holdingbranch | Can be issued from holdingbranch' + ); + set_userenv($holdingbranch); + AddIssue( $patron_1, $item->barcode ); # Reinsert the original issue ## Cannot be issued from another branch set_userenv($otherbranch); - is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - holdingbranch | Cannot be issued from otherbranch'); + is( + ref( AddIssue( $patron_2, $item->barcode ) ), '', + 'AllowReturnToBranch - holdingbranch | Cannot be issued from otherbranch' + ); # AllowReturnToBranch == homebranch t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' ); ## Can be issued from homebranch set_userenv($homebranch); - is ( ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, 'AllowReturnToBranch - homebranch | Can be issued from homebranch' ); - AddIssue( $patron_1, $item->barcode ); # Re-issue to patron 1 + is( + ref( AddIssue( $patron_2, $item->barcode ) ), $ref_issue, + 'AllowReturnToBranch - homebranch | Can be issued from homebranch' + ); + AddIssue( $patron_1, $item->barcode ); # Re-issue to patron 1 ## Cannot be issued from holdinbranch set_userenv($holdingbranch); - is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - homebranch | Cannot be issued from holdingbranch' ); + is( + ref( AddIssue( $patron_2, $item->barcode ) ), '', + 'AllowReturnToBranch - homebranch | Cannot be issued from holdingbranch' + ); ## Cannot be issued from another branch set_userenv($otherbranch); - is ( ref( AddIssue( $patron_2, $item->barcode ) ), '', 'AllowReturnToBranch - homebranch | Cannot be issued from otherbranch' ); + is( + ref( AddIssue( $patron_2, $item->barcode ) ), '', + 'AllowReturnToBranch - homebranch | Cannot be issued from otherbranch' + ); + # TODO t::lib::Mocks::mock_preference('AllowReturnToBranch', 'homeorholdingbranch'); }; subtest 'AddIssue | recalls' => sub { plan tests => 3; - t::lib::Mocks::mock_preference("UseRecalls", 1); - t::lib::Mocks::mock_preference("item-level_itypes", 1); - my $patron1 = $builder->build_object({ class => 'Koha::Patrons' }); - my $patron2 = $builder->build_object({ class => 'Koha::Patrons' }); - my $item = $builder->build_sample_item; - Koha::CirculationRules->set_rules({ - branchcode => undef, - itemtype => undef, - categorycode => undef, - rules => { - recalls_allowed => 10, - }, - }); + t::lib::Mocks::mock_preference( "UseRecalls", 1 ); + t::lib::Mocks::mock_preference( "item-level_itypes", 1 ); + my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } ); + my $patron2 = $builder->build_object( { class => 'Koha::Patrons' } ); + my $item = $builder->build_sample_item; + Koha::CirculationRules->set_rules( + { + branchcode => undef, + itemtype => undef, + categorycode => undef, + rules => { + recalls_allowed => 10, + }, + } + ); # checking out item that they have recalled my $recall1 = Koha::Recall->new( - { patron_id => $patron1->borrowernumber, + { + patron_id => $patron1->borrowernumber, biblio_id => $item->biblionumber, item_id => $item->itemnumber, item_level => 1, @@ -2475,21 +2684,26 @@ subtest 'AddIssue | recalls' => sub { # this item is has a recall request. cancel recall my $recall2 = Koha::Recall->new( - { patron_id => $patron2->borrowernumber, + { + patron_id => $patron2->borrowernumber, biblio_id => $item->biblionumber, item_id => $item->itemnumber, item_level => 1, pickup_library_id => $patron2->branchcode, } )->store; - AddIssue( $patron1, $item->barcode, undef, undef, undef, undef, { recall_id => $recall2->id, cancel_recall => 'cancel' } ); + AddIssue( + $patron1, $item->barcode, undef, undef, undef, undef, + { recall_id => $recall2->id, cancel_recall => 'cancel' } + ); $recall2 = Koha::Recalls->find( $recall2->id ); is( $recall2->cancelled, 1, 'Recall was cancelled when patron checked out item' ); AddReturn( $item->barcode, $item->homebranch ); # this item is waiting to fulfill a recall. revert recall my $recall3 = Koha::Recall->new( - { patron_id => $patron2->borrowernumber, + { + patron_id => $patron2->borrowernumber, biblio_id => $item->biblionumber, item_id => $item->itemnumber, item_level => 1, @@ -2497,7 +2711,10 @@ subtest 'AddIssue | recalls' => sub { } )->store; $recall3->set_waiting; - AddIssue( $patron1, $item->barcode, undef, undef, undef, undef, { recall_id => $recall3->id, cancel_recall => 'revert' } ); + AddIssue( + $patron1, $item->barcode, undef, undef, undef, undef, + { recall_id => $recall3->id, cancel_recall => 'revert' } + ); $recall3 = Koha::Recalls->find( $recall3->id ); is( $recall3->requested, 1, 'Recall was reverted from waiting when patron checked out item' ); AddReturn( $item->barcode, $item->homebranch ); @@ -2508,43 +2725,48 @@ subtest 'AddIssue & illrequests.due_date' => sub { t::lib::Mocks::mock_preference( 'ILLModule', 1 ); my $library = $builder->build( { source => 'Branch' } ); - my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); - my $item = $builder->build_sample_item(); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + my $item = $builder->build_sample_item(); set_userenv($library); - my $custom_date_due = '4999-12-18 12:34:56'; + my $custom_date_due = '4999-12-18 12:34:56'; my $expected_date_due = '4999-12-18 23:59:00'; - my $illrequest = Koha::ILL::Request->new({ - borrowernumber => $patron->borrowernumber, - biblio_id => $item->biblionumber, - branchcode => $library->{'branchcode'}, - due_date => $custom_date_due, - })->store; + my $illrequest = Koha::ILL::Request->new( + { + borrowernumber => $patron->borrowernumber, + biblio_id => $item->biblionumber, + branchcode => $library->{'branchcode'}, + due_date => $custom_date_due, + } + )->store; my $issue = AddIssue( $patron, $item->barcode ); - is( $issue->date_due, $expected_date_due, 'Custom illrequest date due has been set for this issue'); + is( $issue->date_due, $expected_date_due, 'Custom illrequest date due has been set for this issue' ); - $patron = $builder->build_object( { class => 'Koha::Patrons' } ); - $item = $builder->build_sample_item(); - $custom_date_due = '4999-12-19'; + $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + $item = $builder->build_sample_item(); + $custom_date_due = '4999-12-19'; $expected_date_due = '4999-12-19 23:59:00'; - $illrequest = Koha::ILL::Request->new({ - borrowernumber => $patron->borrowernumber, - biblio_id => $item->biblionumber, - branchcode => $library->{'branchcode'}, - due_date => $custom_date_due, - })->store; + $illrequest = Koha::ILL::Request->new( + { + borrowernumber => $patron->borrowernumber, + biblio_id => $item->biblionumber, + branchcode => $library->{'branchcode'}, + due_date => $custom_date_due, + } + )->store; $issue = AddIssue( $patron, $item->barcode ); - is( $issue->date_due, $expected_date_due, 'Custom illrequest date due has been set for this issue'); + is( $issue->date_due, $expected_date_due, 'Custom illrequest date due has been set for this issue' ); }; subtest 'CanBookBeIssued + Koha::Patron->is_debarred|has_overdues' => sub { plan tests => 8; my $library = $builder->build( { source => 'Branch' } ); - my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } ); + my $patron = $builder->build_object( + { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } ); my $item_1 = $builder->build_sample_item( { library => $library->{branchcode}, @@ -2579,29 +2801,38 @@ subtest 'CanBookBeIssued + Koha::Patron->is_debarred|has_overdues' => sub { # Patron cannot issue item_1, they have overdues my $yesterday = DateTime->today( time_zone => C4::Context->tz() )->add( days => -1 ); - my $issue = AddIssue( $patron, $item_1->barcode, $yesterday ); # Add an overdue + my $issue = AddIssue( $patron, $item_1->barcode, $yesterday ); # Add an overdue t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'confirmation' ); ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode ); - is( keys(%$error) + keys(%$alerts), 0, 'No key for error and alert' . str($error, $question, $alerts) ); - is( $question->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=confirmation, USERBLOCKEDOVERDUE should be set for question' ); + is( keys(%$error) + keys(%$alerts), 0, 'No key for error and alert' . str( $error, $question, $alerts ) ); + is( + $question->{USERBLOCKEDOVERDUE}, 1, + 'OverduesBlockCirc=confirmation, USERBLOCKEDOVERDUE should be set for question' + ); t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'block' ); ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode ); - is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) ); + is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str( $error, $question, $alerts ) ); is( $error->{USERBLOCKEDOVERDUE}, 1, 'OverduesBlockCirc=block, USERBLOCKEDOVERDUE should be set for error' ); # Patron cannot issue item_1, they are debarred my $tomorrow = DateTime->today( time_zone => C4::Context->tz() )->add( days => 1 ); Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber, expiration => $tomorrow } ); ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode ); - is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) ); - is( $error->{USERBLOCKEDWITHENDDATE}, output_pref( { dt => $tomorrow, dateformat => 'sql', dateonly => 1 } ), 'USERBLOCKEDWITHENDDATE should be tomorrow' ); + is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str( $error, $question, $alerts ) ); + is( + $error->{USERBLOCKEDWITHENDDATE}, output_pref( { dt => $tomorrow, dateformat => 'sql', dateonly => 1 } ), + 'USERBLOCKEDWITHENDDATE should be tomorrow' + ); Koha::Patron::Debarments::AddDebarment( { borrowernumber => $patron->borrowernumber } ); ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode ); - is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str($error, $question, $alerts) ); - is( $error->{USERBLOCKEDNOENDDATE}, '9999-12-31', 'USERBLOCKEDNOENDDATE should be 9999-12-31 for unlimited debarments' ); + is( keys(%$question) + keys(%$alerts), 0, 'No key for question and alert ' . str( $error, $question, $alerts ) ); + is( + $error->{USERBLOCKEDNOENDDATE}, '9999-12-31', + 'USERBLOCKEDNOENDDATE should be 9999-12-31 for unlimited debarments' + ); }; subtest 'Statistic patrons "X"' => sub { @@ -2695,7 +2926,6 @@ subtest 'Statistic patrons "X"' => sub { # TODO There are other tests to provide here }; - subtest "Bug 27753 - Add AutoClaimReturnStatusOnCheckin" => sub { plan tests => 8; @@ -2751,7 +2981,10 @@ subtest "Bug 27753 - Add AutoClaimReturnStatusOnCheckin" => sub { "AddReturn returns message 'ClaimAutoResolved' containing the ReturnClaim object" ); $claim->discard_changes; - is( $claim->resolved_by, $librarian->borrowernumber, "Claim marked as resolved by librarian calling AddReturn when AutoClaimReturnStatusOnCheckin set" ); + is( + $claim->resolved_by, $librarian->borrowernumber, + "Claim marked as resolved by librarian calling AddReturn when AutoClaimReturnStatusOnCheckin set" + ); is( $claim->resolution, 'RETURNED_ON_CLAIM', "Claim resolution set to match AutoClaimReturnStatusOnCheckin value" ); $item->discard_changes; is( $item->itemlost, 1, "Item lost status follows BlockReturnOfLostItems when feature is enabled" ); @@ -2782,40 +3015,40 @@ subtest 'MultipleReserves' => sub { } ); - my $bibitems = ''; - my $priority = '1'; - my $resdate = undef; - my $expdate = undef; - my $notes = ''; - my $checkitem = undef; - my $found = undef; + my $bibitems = ''; + my $priority = '1'; + my $resdate = undef; + my $expdate = undef; + my $notes = ''; + my $checkitem = undef; + my $found = undef; # Renewing borrower my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { - firstname => 'John', - surname => 'Renewal', + firstname => 'John', + surname => 'Renewal', categorycode => $patron_category->{categorycode}, - branchcode => $branch, + branchcode => $branch, } } ); - my $issue = AddIssue( $patron, $item_1->barcode); + my $issue = AddIssue( $patron, $item_1->barcode ); my $datedue = dt_from_string( $issue->date_due() ); - is (defined $issue->date_due(), 1, "item 1 checked out"); - my $borrowing_borrowernumber = Koha::Checkouts->find({ itemnumber => $item_1->itemnumber })->borrowernumber; + is( defined $issue->date_due(), 1, "item 1 checked out" ); + my $borrowing_borrowernumber = Koha::Checkouts->find( { itemnumber => $item_1->itemnumber } )->borrowernumber; my $reserving_borrowernumber1 = $builder->build_object( { class => 'Koha::Patrons', value => { - firstname => 'Katrin', - surname => 'Reservation', + firstname => 'Katrin', + surname => 'Reservation', categorycode => $patron_category->{categorycode}, - branchcode => $branch, + branchcode => $branch, } } )->borrowernumber; @@ -2838,10 +3071,10 @@ subtest 'MultipleReserves' => sub { { class => 'Koha::Patrons', value => { - firstname => 'Kirk', - surname => 'Reservation', + firstname => 'Kirk', + surname => 'Reservation', categorycode => $patron_category->{categorycode}, - branchcode => $branch, + branchcode => $branch, } } )->borrowernumber; @@ -2861,8 +3094,8 @@ subtest 'MultipleReserves' => sub { ); { - my ( $renewokay, $error ) = CanBookBeRenewed($patron, $issue, 1); - is($renewokay, 0, 'Bug 17941 - should cover the case where 2 books are both reserved, so failing'); + my ( $renewokay, $error ) = CanBookBeRenewed( $patron, $issue, 1 ); + is( $renewokay, 0, 'Bug 17941 - should cover the case where 2 books are both reserved, so failing' ); } my $item_3 = $builder->build_sample_item( @@ -2875,8 +3108,11 @@ subtest 'MultipleReserves' => sub { ); { - my ( $renewokay, $error ) = CanBookBeRenewed($patron, $issue, 1); - is($renewokay, 1, 'Bug 17941 - should cover the case where 2 books are reserved, but a third one is available'); + my ( $renewokay, $error ) = CanBookBeRenewed( $patron, $issue, 1 ); + is( + $renewokay, 1, + 'Bug 17941 - should cover the case where 2 books are reserved, but a third one is available' + ); } }; @@ -2884,7 +3120,8 @@ subtest 'CanBookBeIssued + AllowMultipleIssuesOnABiblio' => sub { plan tests => 5; my $library = $builder->build( { source => 'Branch' } ); - my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } ); + my $patron = $builder->build_object( + { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } ); my $biblionumber = $builder->build_sample_biblio( { @@ -2928,39 +3165,42 @@ subtest 'CanBookBeIssued + AllowMultipleIssuesOnABiblio' => sub { my ( $error, $question, $alerts ); my $issue = AddIssue( $patron, $item_1->barcode, dt_from_string->add( days => 1 ) ); - t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0); + t::lib::Mocks::mock_preference( 'AllowMultipleIssuesOnABiblio', 0 ); ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode ); cmp_deeply( { error => $error, alerts => $alerts }, - { error => {}, alerts => {} }, + { error => {}, alerts => {} }, 'No error or alert should be raised' ); - is( $question->{BIBLIO_ALREADY_ISSUED}, 1, 'BIBLIO_ALREADY_ISSUED question flag should be set if AllowMultipleIssuesOnABiblio=0 and issue already exists' ); + is( + $question->{BIBLIO_ALREADY_ISSUED}, 1, + 'BIBLIO_ALREADY_ISSUED question flag should be set if AllowMultipleIssuesOnABiblio=0 and issue already exists' + ); - t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1); + t::lib::Mocks::mock_preference( 'AllowMultipleIssuesOnABiblio', 1 ); ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode ); cmp_deeply( { error => $error, question => $question, alerts => $alerts }, - { error => {}, question => {}, alerts => {} }, + { error => {}, question => {}, alerts => {} }, 'No BIBLIO_ALREADY_ISSUED flag should be set if AllowMultipleIssuesOnABiblio=1' ); # Add a subscription - Koha::Subscription->new({ biblionumber => $biblionumber })->store; + Koha::Subscription->new( { biblionumber => $biblionumber } )->store; - t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 0); + t::lib::Mocks::mock_preference( 'AllowMultipleIssuesOnABiblio', 0 ); ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode ); cmp_deeply( { error => $error, question => $question, alerts => $alerts }, - { error => {}, question => {}, alerts => {} }, + { error => {}, question => {}, alerts => {} }, 'No BIBLIO_ALREADY_ISSUED flag should be set if it is a subscription' ); - t::lib::Mocks::mock_preference('AllowMultipleIssuesOnABiblio', 1); + t::lib::Mocks::mock_preference( 'AllowMultipleIssuesOnABiblio', 1 ); ( $error, $question, $alerts ) = CanBookBeIssued( $patron, $item_2->barcode ); cmp_deeply( { error => $error, question => $question, alerts => $alerts }, - { error => {}, question => {}, alerts => {} }, + { error => {}, question => {}, alerts => {} }, 'No BIBLIO_ALREADY_ISSUED flag should be set if it is a subscription' ); }; @@ -2969,7 +3209,8 @@ subtest 'AddReturn + CumulativeRestrictionPeriods' => sub { plan tests => 8; my $library = $builder->build( { source => 'Branch' } ); - my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } ); + my $patron = $builder->build_object( + { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } ); # Add 2 items my $biblionumber = $builder->build_sample_biblio( @@ -3007,12 +3248,11 @@ subtest 'AddReturn + CumulativeRestrictionPeriods' => sub { ); # Patron cannot issue item_1, they have overdues - my $now = dt_from_string; + my $now = dt_from_string; my $five_days_ago = $now->clone->subtract( days => 5 ); my $ten_days_ago = $now->clone->subtract( days => 10 ); AddIssue( $patron, $item_1->barcode, $five_days_ago ); # Add an overdue - AddIssue( $patron, $item_2->barcode, $ten_days_ago ) - ; # Add another overdue + AddIssue( $patron, $item_2->barcode, $ten_days_ago ); # Add another overdue t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '0' ); AddReturn( $item_1->barcode, $library->{branchcode}, undef, $now ); @@ -3045,13 +3285,11 @@ subtest 'AddReturn + CumulativeRestrictionPeriods' => sub { ); is( $THE_suspension->expiration, $expected_expiration, "Suspension expiration date updated" ); - Koha::Patron::Debarments::DelUniqueDebarment( - { borrowernumber => $patron->borrowernumber, type => 'SUSPENSION' } ); + Koha::Patron::Debarments::DelUniqueDebarment( { borrowernumber => $patron->borrowernumber, type => 'SUSPENSION' } ); t::lib::Mocks::mock_preference( 'CumulativeRestrictionPeriods', '1' ); AddIssue( $patron, $item_1->barcode, $five_days_ago ); # Add an overdue - AddIssue( $patron, $item_2->barcode, $ten_days_ago ) - ; # Add another overdue + AddIssue( $patron, $item_2->barcode, $ten_days_ago ); # Add another overdue AddReturn( $item_1->barcode, $library->{branchcode}, undef, $now ); $suspensions = $patron->restrictions->search( { type => 'SUSPENSION' } ); is( $suspensions->count, 1, "Only one suspension" ); @@ -3073,7 +3311,7 @@ subtest 'AddReturn + CumulativeRestrictionPeriods' => sub { $expected_expiration = output_pref( { - dt => $now->clone->add( days => ( 5 - 1 ) * 2 + ( 10 - 1 ) * 2 ), + dt => $now->clone->add( days => ( 5 - 1 ) * 2 + ( 10 - 1 ) * 2 ), dateformat => 'sql', dateonly => 1 } @@ -3085,7 +3323,8 @@ subtest 'AddReturn + suspension_chargeperiod' => sub { plan tests => 29; my $library = $builder->build( { source => 'Branch' } ); - my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } ); + my $patron = $builder->build_object( + { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } ); my $biblionumber = $builder->build_sample_biblio( { @@ -3107,17 +3346,18 @@ subtest 'AddReturn + suspension_chargeperiod' => sub { itemtype => '*', branchcode => '*', rules => { - issuelength => 1, - firstremind => 0, # 0 day of grace - finedays => 2, # 2 days of fine per day of overdue + issuelength => 1, + firstremind => 0, # 0 day of grace + finedays => 2, # 2 days of fine per day of overdue suspension_chargeperiod => 1, lengthunit => 'days', } } ); - my $now = dt_from_string; + my $now = dt_from_string; my $five_days_ago = $now->clone->subtract( days => 5 ); + # We want to charge 2 days every day, without grace # With 5 days of overdue: 5 * Z my $expected_expiration = $now->clone->add( days => ( 5 * 2 ) / 1 ); @@ -3139,30 +3379,32 @@ subtest 'AddReturn + suspension_chargeperiod' => sub { itemtype => '*', branchcode => '*', rules => { - issuelength => 1, - firstremind => undef, # 0 day of grace - finedays => 2, # 2 days of fine per day of overdue + issuelength => 1, + firstremind => undef, # 0 day of grace + finedays => 2, # 2 days of fine per day of overdue suspension_chargeperiod => 1, lengthunit => 'days', } } ); { - my $now = dt_from_string; - my $five_days_ago = $now->clone->subtract( days => 5 ); - # We want to charge 2 days every day, without grace - # With 5 days of overdue: 5 * Z - my $expected_expiration = $now->clone->add( days => ( 5 * 2 ) / 1 ); - test_debarment_on_checkout( - { - item => $item_1, - library => $library, - patron => $patron, - due_date => $five_days_ago, - expiration_date => $expected_expiration, - } - ); + my $now = dt_from_string; + my $five_days_ago = $now->clone->subtract( days => 5 ); + + # We want to charge 2 days every day, without grace + # With 5 days of overdue: 5 * Z + my $expected_expiration = $now->clone->add( days => ( 5 * 2 ) / 1 ); + test_debarment_on_checkout( + { + item => $item_1, + library => $library, + patron => $patron, + due_date => $five_days_ago, + expiration_date => $expected_expiration, + } + ); } + # We want to charge 2 days every 2 days, without grace # With 5 days of overdue: (5 * 2) / 2 Koha::CirculationRules->set_rule( @@ -3224,19 +3466,20 @@ subtest 'AddReturn + suspension_chargeperiod' => sub { } } ); - t::lib::Mocks::mock_preference('finesCalendar', 'noFinesWhenClosed'); - t::lib::Mocks::mock_preference('SuspensionsCalendar', 'noSuspensionsWhenClosed'); + t::lib::Mocks::mock_preference( 'finesCalendar', 'noFinesWhenClosed' ); + t::lib::Mocks::mock_preference( 'SuspensionsCalendar', 'noSuspensionsWhenClosed' ); # Adding a holiday 2 days ago - my $calendar = C4::Calendar->new(branchcode => $library->{branchcode}); + my $calendar = C4::Calendar->new( branchcode => $library->{branchcode} ); my $two_days_ago = $now->clone->subtract( days => 2 ); $calendar->insert_single_holiday( - day => $two_days_ago->day, - month => $two_days_ago->month, - year => $two_days_ago->year, - title => 'holidayTest-2d', - description => 'holidayDesc 2 days ago' + day => $two_days_ago->day, + month => $two_days_ago->month, + year => $two_days_ago->year, + title => 'holidayTest-2d', + description => 'holidayDesc 2 days ago' ); + # With 5 days of overdue, only 4 (x finedays=2) days must charged (one was an holiday) $expected_expiration = $now->clone->add( days => floor( ( ( 5 - 0 - 1 ) / 1 ) * 2 ) ); test_debarment_on_checkout( @@ -3252,11 +3495,11 @@ subtest 'AddReturn + suspension_chargeperiod' => sub { # Adding a holiday 2 days ahead, with finesCalendar=noFinesWhenClosed it should be skipped my $two_days_ahead = $now->clone->add( days => 2 ); $calendar->insert_single_holiday( - day => $two_days_ahead->day, - month => $two_days_ahead->month, - year => $two_days_ahead->year, - title => 'holidayTest+2d', - description => 'holidayDesc 2 days ahead' + day => $two_days_ahead->day, + month => $two_days_ahead->month, + year => $two_days_ahead->year, + title => 'holidayTest+2d', + description => 'holidayDesc 2 days ahead' ); # Same as above, but we should skip D+2 @@ -3274,12 +3517,13 @@ subtest 'AddReturn + suspension_chargeperiod' => sub { # Adding another holiday, day of expiration date my $expected_expiration_dt = dt_from_string($expected_expiration); $calendar->insert_single_holiday( - day => $expected_expiration_dt->day, - month => $expected_expiration_dt->month, - year => $expected_expiration_dt->year, - title => 'holidayTest_exp', - description => 'holidayDesc on expiration date' + day => $expected_expiration_dt->day, + month => $expected_expiration_dt->month, + year => $expected_expiration_dt->year, + title => 'holidayTest_exp', + description => 'holidayDesc on expiration date' ); + # Expiration date will be the day after test_debarment_on_checkout( { @@ -3296,8 +3540,8 @@ subtest 'AddReturn + suspension_chargeperiod' => sub { item => $item_1, library => $library, patron => $patron, - return_date => $now->clone->add(days => 5), - expiration_date => $now->clone->add(days => 5 + (5 * 2 - 1) ), + return_date => $now->clone->add( days => 5 ), + expiration_date => $now->clone->add( days => 5 + ( 5 * 2 - 1 ) ), } ); @@ -3306,9 +3550,9 @@ subtest 'AddReturn + suspension_chargeperiod' => sub { item => $item_1, library => $library, patron => $patron, - due_date => $now->clone->add(days => 1), - return_date => $now->clone->add(days => 5), - expiration_date => $now->clone->add(days => 5 + (4 * 2 - 1) ), + due_date => $now->clone->add( days => 1 ), + return_date => $now->clone->add( days => 5 ), + expiration_date => $now->clone->add( days => 5 + ( 4 * 2 - 1 ) ), } ); @@ -3318,10 +3562,10 @@ subtest 'AddReturn + suspension_chargeperiod' => sub { categorycode => undef, itemtype => undef, branchcode => undef, - rules => { + rules => { finedays => 0, lengthunit => 'days', - } + } } ); @@ -3335,7 +3579,10 @@ subtest 'AddReturn + suspension_chargeperiod' => sub { AddIssue( $patron, $item_1->barcode, $now->clone->subtract( days => 1 ) ); my ( undef, $message ) = AddReturn( $item_1->barcode, $library->{branchcode}, undef, $now ); - is( $message->{WasReturned} && exists $message->{ForeverDebarred}, 1, 'Forever debarred message for Addreturn when overdue'); + is( + $message->{WasReturned} && exists $message->{ForeverDebarred}, 1, + 'Forever debarred message for Addreturn when overdue' + ); Koha::Patron::Debarments::DelUniqueDebarment( { @@ -3352,8 +3599,11 @@ subtest 'AddReturn + suspension_chargeperiod' => sub { ); AddIssue( $patron, $item_1->barcode, $now->clone->subtract( days => 1 ) ); - (undef, $message) = AddReturn( $item_1->barcode, $library->{branchcode}, undef, $now ); - is( $message->{WasReturned} && exists $message->{PrevDebarred}, 1, 'Previously debarred message for Addreturn when overdue'); + ( undef, $message ) = AddReturn( $item_1->barcode, $library->{branchcode}, undef, $now ); + is( + $message->{WasReturned} && exists $message->{PrevDebarred}, 1, + 'Previously debarred message for Addreturn when overdue' + ); }; subtest 'CanBookBeIssued + AutoReturnCheckedOutItems' => sub { @@ -3379,36 +3629,44 @@ subtest 'CanBookBeIssued + AutoReturnCheckedOutItems' => sub { } ); - t::lib::Mocks::mock_userenv({ branchcode => $library->branchcode }); + t::lib::Mocks::mock_userenv( { branchcode => $library->branchcode } ); my $item = $builder->build_sample_item( { - library => $library->branchcode, + library => $library->branchcode, } ); my ( $error, $question, $alerts ); my $issue = AddIssue( $patron1, $item->barcode ); - t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0); + t::lib::Mocks::mock_preference( 'AutoReturnCheckedOutItems', 0 ); ( $error, $question, $alerts ) = CanBookBeIssued( $patron2, $item->barcode ); - is( $question->{ISSUED_TO_ANOTHER}, 1, 'ISSUED_TO_ANOTHER question flag should be set if AutoReturnCheckedOutItems is disabled and item is checked out to another' ); + is( + $question->{ISSUED_TO_ANOTHER}, 1, + 'ISSUED_TO_ANOTHER question flag should be set if AutoReturnCheckedOutItems is disabled and item is checked out to another' + ); - t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 1); + t::lib::Mocks::mock_preference( 'AutoReturnCheckedOutItems', 1 ); ( $error, $question, $alerts ) = CanBookBeIssued( $patron2, $item->barcode ); - is( $alerts->{RETURNED_FROM_ANOTHER}->{patron}->borrowernumber, $patron1->borrowernumber, 'RETURNED_FROM_ANOTHER alert flag should be set if AutoReturnCheckedOutItems is enabled and item is checked out to another' ); + is( + $alerts->{RETURNED_FROM_ANOTHER}->{patron}->borrowernumber, $patron1->borrowernumber, + 'RETURNED_FROM_ANOTHER alert flag should be set if AutoReturnCheckedOutItems is enabled and item is checked out to another' + ); - t::lib::Mocks::mock_preference('AutoReturnCheckedOutItems', 0); + t::lib::Mocks::mock_preference( 'AutoReturnCheckedOutItems', 0 ); }; - subtest 'AddReturn | is_overdue' => sub { plan tests => 9; - t::lib::Mocks::mock_preference('MarkLostItemsAsReturned', 'batchmod|moredetail|cronjob|additem|pendingreserves|onpayment'); - t::lib::Mocks::mock_preference('CalculateFinesOnReturn', 1); - t::lib::Mocks::mock_preference('finesMode', 'production'); - t::lib::Mocks::mock_preference('MaxFine', '100'); + t::lib::Mocks::mock_preference( + 'MarkLostItemsAsReturned', + 'batchmod|moredetail|cronjob|additem|pendingreserves|onpayment' + ); + t::lib::Mocks::mock_preference( 'CalculateFinesOnReturn', 1 ); + t::lib::Mocks::mock_preference( 'finesMode', 'production' ); + t::lib::Mocks::mock_preference( 'MaxFine', '100' ); my $library = $builder->build( { source => 'Branch' } ); my $patron = $builder->build_object( @@ -3418,11 +3676,11 @@ subtest 'AddReturn | is_overdue' => sub { } ); my $manager = $builder->build_object( { class => "Koha::Patrons" } ); - t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode }); + t::lib::Mocks::mock_userenv( { patron => $manager, branchcode => $manager->branchcode } ); my $item = $builder->build_sample_item( { - library => $library->{branchcode}, + library => $library->{branchcode}, replacementprice => 7 } ); @@ -3442,35 +3700,35 @@ subtest 'AddReturn | is_overdue' => sub { } ); - my $now = dt_from_string; + my $now = dt_from_string; my $one_day_ago = $now->clone->subtract( days => 1 ); my $two_days_ago = $now->clone->subtract( days => 2 ); my $five_days_ago = $now->clone->subtract( days => 5 ); my $ten_days_ago = $now->clone->subtract( days => 10 ); # No return date specified, today will be used => 10 days overdue charged - AddIssue( $patron, $item->barcode, $ten_days_ago ); # date due was 10d ago + AddIssue( $patron, $item->barcode, $ten_days_ago ); # date due was 10d ago AddReturn( $item->barcode, $library->{branchcode} ); - is( int($patron->account->balance()), 10, 'Patron should have a charge of 10 (10 days x 1)' ); - Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete; + is( int( $patron->account->balance() ), 10, 'Patron should have a charge of 10 (10 days x 1)' ); + Koha::Account::Lines->search( { borrowernumber => $patron->borrowernumber } )->delete; # specify return date 5 days before => no overdue charged - AddIssue( $patron, $item->barcode, $five_days_ago ); # date due was 5d ago + AddIssue( $patron, $item->barcode, $five_days_ago ); # date due was 5d ago AddReturn( $item->barcode, $library->{branchcode}, undef, $ten_days_ago ); - is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' ); - Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete; + is( int( $patron->account->balance() ), 0, 'AddReturn: pass return_date => no overdue' ); + Koha::Account::Lines->search( { borrowernumber => $patron->borrowernumber } )->delete; # specify return date 5 days later => 5 days overdue charged - AddIssue( $patron, $item->barcode, $ten_days_ago ); # date due was 10d ago + AddIssue( $patron, $item->barcode, $ten_days_ago ); # date due was 10d ago AddReturn( $item->barcode, $library->{branchcode}, undef, $five_days_ago ); - is( int($patron->account->balance()), 5, 'AddReturn: pass return_date => overdue' ); - Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete; + is( int( $patron->account->balance() ), 5, 'AddReturn: pass return_date => overdue' ); + Koha::Account::Lines->search( { borrowernumber => $patron->borrowernumber } )->delete; # specify return date 5 days later, specify exemptfine => no overdue charge - AddIssue( $patron, $item->barcode, $ten_days_ago ); # date due was 10d ago + AddIssue( $patron, $item->barcode, $ten_days_ago ); # date due was 10d ago AddReturn( $item->barcode, $library->{branchcode}, 1, $five_days_ago ); - is( int($patron->account->balance()), 0, 'AddReturn: pass return_date => no overdue' ); - Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete; + is( int( $patron->account->balance() ), 0, 'AddReturn: pass return_date => no overdue' ); + Koha::Account::Lines->search( { borrowernumber => $patron->borrowernumber } )->delete; subtest 'bug 22877 | Lost item return' => sub { @@ -3479,9 +3737,10 @@ subtest 'AddReturn | is_overdue' => sub { my $issue = AddIssue( $patron, $item->barcode, $ten_days_ago ); # date due was 10d ago # Fake fines cronjob on this checkout - my ($fine) = - CalcFine( $item, $patron->categorycode, $library->{branchcode}, - $ten_days_ago, $now ); + my ($fine) = CalcFine( + $item, $patron->categorycode, $library->{branchcode}, + $ten_days_ago, $now + ); UpdateFine( { issue_id => $issue->issue_id, @@ -3491,35 +3750,42 @@ subtest 'AddReturn | is_overdue' => sub { due => output_pref($ten_days_ago) } ); - is( int( $patron->account->balance() ), - 10, "Overdue fine of 10 days overdue" ); + is( + int( $patron->account->balance() ), + 10, "Overdue fine of 10 days overdue" + ); # Fake longoverdue with charge and not marking returned LostItem( $item->itemnumber, 'cronjob', 0 ); - is( int( $patron->account->balance() ), - 17, "Lost fine of 7 plus 10 days overdue" ); + is( + int( $patron->account->balance() ), + 17, "Lost fine of 7 plus 10 days overdue" + ); # Now we return it today AddReturn( $item->barcode, $library->{branchcode} ); - is( int( $patron->account->balance() ), - 17, "Should have a single 10 days overdue fine and lost charge" ); + is( + int( $patron->account->balance() ), + 17, "Should have a single 10 days overdue fine and lost charge" + ); # Cleanup - Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete; + Koha::Account::Lines->search( { borrowernumber => $patron->borrowernumber } )->delete; }; subtest 'bug 8338 | backdated return resulting in zero amount fine' => sub { plan tests => 17; - t::lib::Mocks::mock_preference('CalculateFinesOnBackdate', 1); + t::lib::Mocks::mock_preference( 'CalculateFinesOnBackdate', 1 ); my $issue = AddIssue( $patron, $item->barcode, $one_day_ago ); # date due was 1d ago # Fake fines cronjob on this checkout - my ($fine) = - CalcFine( $item, $patron->categorycode, $library->{branchcode}, - $one_day_ago, $now ); + my ($fine) = CalcFine( + $item, $patron->categorycode, $library->{branchcode}, + $one_day_ago, $now + ); UpdateFine( { issue_id => $issue->issue_id, @@ -3529,22 +3795,27 @@ subtest 'AddReturn | is_overdue' => sub { due => output_pref($one_day_ago) } ); - is( int( $patron->account->balance() ), - 1, "Overdue fine of 1 day overdue" ); + is( + int( $patron->account->balance() ), + 1, "Overdue fine of 1 day overdue" + ); # Backdated return (dropbox mode example - charge should be removed) AddReturn( $item->barcode, $library->{branchcode}, 1, $one_day_ago ); - is( int( $patron->account->balance() ), - 0, "Overdue fine should be annulled" ); - my $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber }); - is( $lines->count, 0, "Overdue fine accountline has been removed"); + is( + int( $patron->account->balance() ), + 0, "Overdue fine should be annulled" + ); + my $lines = Koha::Account::Lines->search( { borrowernumber => $patron->borrowernumber } ); + is( $lines->count, 0, "Overdue fine accountline has been removed" ); $issue = AddIssue( $patron, $item->barcode, $two_days_ago ); # date due was 2d ago # Fake fines cronjob on this checkout - ($fine) = - CalcFine( $item, $patron->categorycode, $library->{branchcode}, - $two_days_ago, $now ); + ($fine) = CalcFine( + $item, $patron->categorycode, $library->{branchcode}, + $two_days_ago, $now + ); UpdateFine( { issue_id => $issue->issue_id, @@ -3554,12 +3825,14 @@ subtest 'AddReturn | is_overdue' => sub { due => output_pref($one_day_ago) } ); - is( int( $patron->account->balance() ), - 2, "Overdue fine of 2 days overdue" ); + is( + int( $patron->account->balance() ), + 2, "Overdue fine of 2 days overdue" + ); # Payment made against fine - $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber }); - my $debit = $lines->next; + $lines = Koha::Account::Lines->search( { borrowernumber => $patron->borrowernumber } ); + my $debit = $lines->next; my $credit = $patron->account->add_credit( { amount => 2, @@ -3569,48 +3842,56 @@ subtest 'AddReturn | is_overdue' => sub { ); $credit->apply( { debits => [$debit] } ); - is( int( $patron->account->balance() ), - 0, "Overdue fine should be paid off" ); - $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber }); - is ( $lines->count, 2, "Overdue (debit) and Payment (credit) present"); + is( + int( $patron->account->balance() ), + 0, "Overdue fine should be paid off" + ); + $lines = Koha::Account::Lines->search( { borrowernumber => $patron->borrowernumber } ); + is( $lines->count, 2, "Overdue (debit) and Payment (credit) present" ); my $line = $lines->next; - is( $line->amount+0, 2, "Overdue fine amount remains as 2 days"); - is( $line->amountoutstanding+0, 0, "Overdue fine amountoutstanding reduced to 0"); + is( $line->amount + 0, 2, "Overdue fine amount remains as 2 days" ); + is( $line->amountoutstanding + 0, 0, "Overdue fine amountoutstanding reduced to 0" ); # Backdated return (dropbox mode example - charge should be removed) AddReturn( $item->barcode, $library->{branchcode}, undef, $one_day_ago ); - is( int( $patron->account->balance() ), - -1, "Refund credit has been applied" ); - $lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber }, { order_by => { '-asc' => 'accountlines_id' }}); - is( $lines->count, 3, "Overdue (debit), Payment (credit) and Refund (credit) are all present"); + is( + int( $patron->account->balance() ), + -1, "Refund credit has been applied" + ); + $lines = Koha::Account::Lines->search( + { borrowernumber => $patron->borrowernumber }, + { order_by => { '-asc' => 'accountlines_id' } } + ); + is( $lines->count, 3, "Overdue (debit), Payment (credit) and Refund (credit) are all present" ); $line = $lines->next; - is($line->amount+0,1, "Overdue fine amount has been reduced to 1"); - is($line->amountoutstanding+0,0, "Overdue fine amount outstanding remains at 0"); - is($line->status,'RETURNED', "Overdue fine is fixed"); + is( $line->amount + 0, 1, "Overdue fine amount has been reduced to 1" ); + is( $line->amountoutstanding + 0, 0, "Overdue fine amount outstanding remains at 0" ); + is( $line->status, 'RETURNED', "Overdue fine is fixed" ); $line = $lines->next; - is($line->amount+0,-2, "Original payment amount remains as 2"); - is($line->amountoutstanding+0,0, "Original payment remains applied"); + is( $line->amount + 0, -2, "Original payment amount remains as 2" ); + is( $line->amountoutstanding + 0, 0, "Original payment remains applied" ); $line = $lines->next; - is($line->amount+0,-1, "Refund amount correctly set to 1"); - is($line->amountoutstanding+0,-1, "Refund amount outstanding unspent"); + is( $line->amount + 0, -1, "Refund amount correctly set to 1" ); + is( $line->amountoutstanding + 0, -1, "Refund amount outstanding unspent" ); # Cleanup - Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete; + Koha::Account::Lines->search( { borrowernumber => $patron->borrowernumber } )->delete; }; subtest 'bug 25417 | backdated return + exemptfine' => sub { plan tests => 2; - t::lib::Mocks::mock_preference('CalculateFinesOnBackdate', 1); + t::lib::Mocks::mock_preference( 'CalculateFinesOnBackdate', 1 ); my $issue = AddIssue( $patron, $item->barcode, $one_day_ago ); # date due was 1d ago # Fake fines cronjob on this checkout - my ($fine) = - CalcFine( $item, $patron->categorycode, $library->{branchcode}, - $one_day_ago, $now ); + my ($fine) = CalcFine( + $item, $patron->categorycode, $library->{branchcode}, + $one_day_ago, $now + ); UpdateFine( { issue_id => $issue->issue_id, @@ -3620,16 +3901,20 @@ subtest 'AddReturn | is_overdue' => sub { due => output_pref($one_day_ago) } ); - is( int( $patron->account->balance() ), - 1, "Overdue fine of 1 day overdue" ); + is( + int( $patron->account->balance() ), + 1, "Overdue fine of 1 day overdue" + ); # Backdated return (dropbox mode example - charge should no longer exist) AddReturn( $item->barcode, $library->{branchcode}, 1, $one_day_ago ); - is( int( $patron->account->balance() ), - 0, "Overdue fine should be annulled" ); + is( + int( $patron->account->balance() ), + 0, "Overdue fine should be annulled" + ); # Cleanup - Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber })->delete; + Koha::Account::Lines->search( { borrowernumber => $patron->borrowernumber } )->delete; }; subtest 'bug 24075 | backdated return with return datetime matching due datetime' => sub { @@ -3638,7 +3923,7 @@ subtest 'AddReturn | is_overdue' => sub { t::lib::Mocks::mock_preference( 'CalculateFinesOnBackdate', 1 ); my $due_date = dt_from_string; - my $issue = AddIssue( $patron, $item->barcode, $due_date ); + my $issue = AddIssue( $patron, $item->barcode, $due_date ); # Add fine UpdateFine( @@ -3650,16 +3935,18 @@ subtest 'AddReturn | is_overdue' => sub { due => output_pref($due_date) } ); - is( $patron->account->balance(), - 0.25, 'Overdue fine of $0.25 recorded' ); + is( + $patron->account->balance(), + 0.25, 'Overdue fine of $0.25 recorded' + ); # Backdate return to exact due date and time - my ( undef, $message ) = - AddReturn( $item->barcode, $library->{branchcode}, - undef, $due_date ); + my ( undef, $message ) = AddReturn( + $item->barcode, $library->{branchcode}, + undef, $due_date + ); - my $accountline = - Koha::Account::Lines->find( { issue_id => $issue->id } ); + my $accountline = Koha::Account::Lines->find( { issue_id => $issue->id } ); ok( !$accountline, 'accountline removed as expected' ); # Re-issue @@ -3675,8 +3962,10 @@ subtest 'AddReturn | is_overdue' => sub { due => output_pref($due_date) } ); - is( $patron->account->balance(), - 0.25, 'Overdue fine of $0.25 recorded' ); + is( + $patron->account->balance(), + 0.25, 'Overdue fine of $0.25 recorded' + ); # Partial pay accruing fine my $lines = Koha::Account::Lines->search( @@ -3698,9 +3987,10 @@ subtest 'AddReturn | is_overdue' => sub { is( $patron->account->balance(), .05, 'Overdue fine reduced to $0.05' ); # Backdate return to exact due date and time - ( undef, $message ) = - AddReturn( $item->barcode, $library->{branchcode}, - undef, $due_date ); + ( undef, $message ) = AddReturn( + $item->barcode, $library->{branchcode}, + undef, $due_date + ); $lines = Koha::Account::Lines->search( { @@ -3709,24 +3999,27 @@ subtest 'AddReturn | is_overdue' => sub { } ); $accountline = $lines->next; - is( $accountline->amountoutstanding + 0, - 0, 'Partially paid fee amount outstanding was reduced to 0' ); - is( $accountline->amount + 0, - 0, 'Partially paid fee amount was reduced to 0' ); + is( + $accountline->amountoutstanding + 0, + 0, 'Partially paid fee amount outstanding was reduced to 0' + ); + is( + $accountline->amount + 0, + 0, 'Partially paid fee amount was reduced to 0' + ); is( $patron->account->balance(), -0.20, 'Patron refund recorded' ); # Cleanup - Koha::Account::Lines->search( - { borrowernumber => $patron->borrowernumber } )->delete; + Koha::Account::Lines->search( { borrowernumber => $patron->borrowernumber } )->delete; }; subtest 'enh 23091 | Lost item return policies' => sub { plan tests => 5; - my $manager = $builder->build_object({ class => "Koha::Patrons" }); + my $manager = $builder->build_object( { class => "Koha::Patrons" } ); my $branchcode_false = - $builder->build( { source => 'Branch' } )->{branchcode}; + $builder->build( { source => 'Branch' } )->{branchcode}; my $specific_rule_false = $builder->build( { source => 'CirculationRule', @@ -3740,7 +4033,7 @@ subtest 'AddReturn | is_overdue' => sub { } ); my $branchcode_refund = - $builder->build( { source => 'Branch' } )->{branchcode}; + $builder->build( { source => 'Branch' } )->{branchcode}; my $specific_rule_refund = $builder->build( { source => 'CirculationRule', @@ -3754,7 +4047,7 @@ subtest 'AddReturn | is_overdue' => sub { } ); my $branchcode_restore = - $builder->build( { source => 'Branch' } )->{branchcode}; + $builder->build( { source => 'Branch' } )->{branchcode}; my $specific_rule_restore = $builder->build( { source => 'CirculationRule', @@ -3768,7 +4061,7 @@ subtest 'AddReturn | is_overdue' => sub { } ); my $branchcode_charge = - $builder->build( { source => 'Branch' } )->{branchcode}; + $builder->build( { source => 'Branch' } )->{branchcode}; my $specific_rule_charge = $builder->build( { source => 'CirculationRule', @@ -3783,7 +4076,7 @@ subtest 'AddReturn | is_overdue' => sub { ); my $branchcode_refund_unpaid = - $builder->build( { source => 'Branch' } )->{branchcode}; + $builder->build( { source => 'Branch' } )->{branchcode}; my $specific_rule_refund_unpaid = $builder->build( { source => 'CirculationRule', @@ -3798,25 +4091,25 @@ subtest 'AddReturn | is_overdue' => sub { ); my $replacement_amount = 99.00; - t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' ); + t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' ); t::lib::Mocks::mock_preference( 'WhenLostChargeReplacementFee', 1 ); t::lib::Mocks::mock_preference( 'WhenLostForgiveFine', 0 ); t::lib::Mocks::mock_preference( 'BlockReturnOfLostItems', 0 ); - t::lib::Mocks::mock_preference( 'RefundLostOnReturnControl', - 'CheckinLibrary' ); - t::lib::Mocks::mock_preference( 'NoRefundOnLostReturnedItemsAge', - undef ); + t::lib::Mocks::mock_preference( + 'RefundLostOnReturnControl', + 'CheckinLibrary' + ); + t::lib::Mocks::mock_preference( + 'NoRefundOnLostReturnedItemsAge', + undef + ); subtest 'lostreturn | refund_unpaid' => sub { plan tests => 21; - t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_refund_unpaid }); + t::lib::Mocks::mock_userenv( { patron => $manager, branchcode => $branchcode_refund_unpaid } ); - my $item = $builder->build_sample_item( - { - replacementprice => $replacement_amount - } - ); + my $item = $builder->build_sample_item( { replacementprice => $replacement_amount } ); # Issue the item my $issue = C4::Circulation::AddIssue( $patron, $item->barcode ); @@ -3834,16 +4127,20 @@ subtest 'AddReturn | is_overdue' => sub { ); is( $lost_fee_lines->count, 1, 'Lost item fee produced' ); my $lost_fee_line = $lost_fee_lines->next; - is( int($lost_fee_line->amount), - $replacement_amount, 'The right LOST amount is generated' ); - is( int($lost_fee_line->amountoutstanding), + is( + int( $lost_fee_line->amount ), + $replacement_amount, 'The right LOST amount is generated' + ); + is( + int( $lost_fee_line->amountoutstanding ), $replacement_amount, - 'The right LOST amountoutstanding is generated' ); + 'The right LOST amountoutstanding is generated' + ); is( $lost_fee_line->status, undef, 'The LOST status was not set' ); is( - int($patron->account->balance), - $replacement_amount , + int( $patron->account->balance ), + $replacement_amount, "Account balance equals the replacement amount after being charged lost fee when no payments has been made" ); @@ -3852,21 +4149,17 @@ subtest 'AddReturn | is_overdue' => sub { $lost_fee_line->discard_changes; - is( int($lost_fee_line->amount), $replacement_amount, 'The LOST amount is left intact' ); - is( int($lost_fee_line->amountoutstanding) , 0, 'The LOST amountoutstanding is zero' ); - is( $lost_fee_line->status, 'FOUND', 'The FOUND status was set' ); + is( int( $lost_fee_line->amount ), $replacement_amount, 'The LOST amount is left intact' ); + is( int( $lost_fee_line->amountoutstanding ), 0, 'The LOST amountoutstanding is zero' ); + is( $lost_fee_line->status, 'FOUND', 'The FOUND status was set' ); is( - int($patron->account->balance), + int( $patron->account->balance ), 0, 'Account balance should be zero after returning item with lost fee when no payments has been made' ); # Create a second item - $item = $builder->build_sample_item( - { - replacementprice => $replacement_amount - } - ); + $item = $builder->build_sample_item( { replacementprice => $replacement_amount } ); # Issue the item $issue = C4::Circulation::AddIssue( $patron, $item->barcode ); @@ -3886,47 +4179,49 @@ subtest 'AddReturn | is_overdue' => sub { $lost_fee_line = $lost_fee_lines->next; # Make partial payment - $patron->account->payin_amount({ - type => 'PAYMENT', - interface => 'intranet', - payment_type => 'CASH', - user_id => $patron->borrowernumber, - amount => 39.00, - debits => [$lost_fee_line] - }); + $patron->account->payin_amount( + { + type => 'PAYMENT', + interface => 'intranet', + payment_type => 'CASH', + user_id => $patron->borrowernumber, + amount => 39.00, + debits => [$lost_fee_line] + } + ); $lost_fee_line->discard_changes; - is( int($lost_fee_line->amountoutstanding), + is( + int( $lost_fee_line->amountoutstanding ), 60, 'The LOST amountoutstanding is the expected amount after partial payment of lost fee' ); is( - int($patron->account->balance), + int( $patron->account->balance ), 60, 'Account balance is the expected amount after partial payment of lost fee' ); - # Return lost item with partial payment having been made + # Return lost item with partial payment having been made ( $returned, $message ) = AddReturn( $item->barcode, $branchcode_refund_unpaid ); $lost_fee_line->discard_changes; - is( int($lost_fee_line->amountoutstanding) , 0, 'The LOST amountoutstanding is zero after returning lost item with partial payment' ); + is( + int( $lost_fee_line->amountoutstanding ), 0, + 'The LOST amountoutstanding is zero after returning lost item with partial payment' + ); is( $lost_fee_line->status, 'FOUND', 'The FOUND status was set for lost item with partial payment' ); is( - int($patron->account->balance), + int( $patron->account->balance ), 0, 'Account balance should be zero after returning item with lost fee when partial payment has been made' ); # Create a third item - $item = $builder->build_sample_item( - { - replacementprice => $replacement_amount - } - ); + $item = $builder->build_sample_item( { replacementprice => $replacement_amount } ); # Issue the item $issue = C4::Circulation::AddIssue( $patron, $item->barcode ); @@ -3946,37 +4241,43 @@ subtest 'AddReturn | is_overdue' => sub { $lost_fee_line = $lost_fee_lines->next; # Make full payment - $patron->account->payin_amount({ - type => 'PAYMENT', - interface => 'intranet', - payment_type => 'CASH', - user_id => $patron->borrowernumber, - amount => $replacement_amount, - debits => [$lost_fee_line] - }); + $patron->account->payin_amount( + { + type => 'PAYMENT', + interface => 'intranet', + payment_type => 'CASH', + user_id => $patron->borrowernumber, + amount => $replacement_amount, + debits => [$lost_fee_line] + } + ); $lost_fee_line->discard_changes; - is( int($lost_fee_line->amountoutstanding), + is( + int( $lost_fee_line->amountoutstanding ), 0, 'The LOST amountoutstanding is the expected amount after partial payment of lost fee' ); is( - int($patron->account->balance), + int( $patron->account->balance ), 0, 'Account balance is the expected amount after partial payment of lost fee' ); - # Return lost item with partial payment having been made + # Return lost item with partial payment having been made ( $returned, $message ) = AddReturn( $item->barcode, $branchcode_refund_unpaid ); $lost_fee_line->discard_changes; - is( int($lost_fee_line->amountoutstanding) , 0, 'The LOST amountoutstanding is zero after returning lost item with full payment' ); + is( + int( $lost_fee_line->amountoutstanding ), 0, + 'The LOST amountoutstanding is zero after returning lost item with full payment' + ); is( $lost_fee_line->status, 'FOUND', 'The FOUND status was set for lost item with partial payment' ); is( - int($patron->account->balance), + int( $patron->account->balance ), 0, 'Account balance should be zero after returning item with lost fee when full payment has been made' ); @@ -3985,21 +4286,18 @@ subtest 'AddReturn | is_overdue' => sub { subtest 'lostreturn | false' => sub { plan tests => 12; - t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_false }); + t::lib::Mocks::mock_userenv( { patron => $manager, branchcode => $branchcode_false } ); - my $item = $builder->build_sample_item( - { - replacementprice => $replacement_amount - } - ); + my $item = $builder->build_sample_item( { replacementprice => $replacement_amount } ); # Issue the item my $issue = C4::Circulation::AddIssue( $patron, $item->barcode, $ten_days_ago ); # Fake fines cronjob on this checkout - my ($fine) = - CalcFine( $item, $patron->categorycode, $library->{branchcode}, - $ten_days_ago, $now ); + my ($fine) = CalcFine( + $item, $patron->categorycode, $library->{branchcode}, + $ten_days_ago, $now + ); UpdateFine( { issue_id => $issue->issue_id, @@ -4018,11 +4316,15 @@ subtest 'AddReturn | is_overdue' => sub { ); is( $overdue_fees->count, 1, 'Overdue item fee produced' ); my $overdue_fee = $overdue_fees->next; - is( $overdue_fee->amount + 0, - 10, 'The right OVERDUE amount is generated' ); - is( $overdue_fee->amountoutstanding + 0, + is( + $overdue_fee->amount + 0, + 10, 'The right OVERDUE amount is generated' + ); + is( + $overdue_fee->amountoutstanding + 0, 10, - 'The right OVERDUE amountoutstanding is generated' ); + 'The right OVERDUE amountoutstanding is generated' + ); # Simulate item marked as lost $item->itemlost(3)->store; @@ -4037,30 +4339,42 @@ subtest 'AddReturn | is_overdue' => sub { ); is( $lost_fee_lines->count, 1, 'Lost item fee produced' ); my $lost_fee_line = $lost_fee_lines->next; - is( $lost_fee_line->amount + 0, - $replacement_amount, 'The right LOST amount is generated' ); - is( $lost_fee_line->amountoutstanding + 0, + is( + $lost_fee_line->amount + 0, + $replacement_amount, 'The right LOST amount is generated' + ); + is( + $lost_fee_line->amountoutstanding + 0, $replacement_amount, - 'The right LOST amountoutstanding is generated' ); + 'The right LOST amountoutstanding is generated' + ); is( $lost_fee_line->status, undef, 'The LOST status was not set' ); # Return lost item - my ( $returned, $message ) = - AddReturn( $item->barcode, $branchcode_false, undef, $five_days_ago ); + my ( $returned, $message ) = AddReturn( $item->barcode, $branchcode_false, undef, $five_days_ago ); $overdue_fee->discard_changes; - is( $overdue_fee->amount + 0, - 10, 'The OVERDUE amount is left intact' ); - is( $overdue_fee->amountoutstanding + 0, + is( + $overdue_fee->amount + 0, + 10, 'The OVERDUE amount is left intact' + ); + is( + $overdue_fee->amountoutstanding + 0, 10, - 'The OVERDUE amountoutstanding is left intact' ); + 'The OVERDUE amountoutstanding is left intact' + ); $lost_fee_line->discard_changes; - is( $lost_fee_line->amount + 0, - $replacement_amount, 'The LOST amount is left intact' ); - is( $lost_fee_line->amountoutstanding + 0, + is( + $lost_fee_line->amount + 0, + $replacement_amount, 'The LOST amount is left intact' + ); + is( + $lost_fee_line->amountoutstanding + 0, $replacement_amount, - 'The LOST amountoutstanding is left intact' ); + 'The LOST amountoutstanding is left intact' + ); + # FIXME: Should we set the LOST fee status to 'FOUND' regardless of whether we're refunding or not? is( $lost_fee_line->status, undef, 'The LOST status was not set' ); }; @@ -4068,21 +4382,18 @@ subtest 'AddReturn | is_overdue' => sub { subtest 'lostreturn | refund' => sub { plan tests => 12; - t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_refund }); + t::lib::Mocks::mock_userenv( { patron => $manager, branchcode => $branchcode_refund } ); - my $item = $builder->build_sample_item( - { - replacementprice => $replacement_amount - } - ); + my $item = $builder->build_sample_item( { replacementprice => $replacement_amount } ); # Issue the item my $issue = C4::Circulation::AddIssue( $patron, $item->barcode, $ten_days_ago ); # Fake fines cronjob on this checkout - my ($fine) = - CalcFine( $item, $patron->categorycode, $library->{branchcode}, - $ten_days_ago, $now ); + my ($fine) = CalcFine( + $item, $patron->categorycode, $library->{branchcode}, + $ten_days_ago, $now + ); UpdateFine( { issue_id => $issue->issue_id, @@ -4101,11 +4412,15 @@ subtest 'AddReturn | is_overdue' => sub { ); is( $overdue_fees->count, 1, 'Overdue item fee produced' ); my $overdue_fee = $overdue_fees->next; - is( $overdue_fee->amount + 0, - 10, 'The right OVERDUE amount is generated' ); - is( $overdue_fee->amountoutstanding + 0, + is( + $overdue_fee->amount + 0, + 10, 'The right OVERDUE amount is generated' + ); + is( + $overdue_fee->amountoutstanding + 0, 10, - 'The right OVERDUE amountoutstanding is generated' ); + 'The right OVERDUE amountoutstanding is generated' + ); # Simulate item marked as lost $item->itemlost(3)->store; @@ -4120,51 +4435,59 @@ subtest 'AddReturn | is_overdue' => sub { ); is( $lost_fee_lines->count, 1, 'Lost item fee produced' ); my $lost_fee_line = $lost_fee_lines->next; - is( $lost_fee_line->amount + 0, - $replacement_amount, 'The right LOST amount is generated' ); - is( $lost_fee_line->amountoutstanding + 0, + is( + $lost_fee_line->amount + 0, + $replacement_amount, 'The right LOST amount is generated' + ); + is( + $lost_fee_line->amountoutstanding + 0, $replacement_amount, - 'The right LOST amountoutstanding is generated' ); + 'The right LOST amountoutstanding is generated' + ); is( $lost_fee_line->status, undef, 'The LOST status was not set' ); # Return the lost item - my ( undef, $message ) = - AddReturn( $item->barcode, $branchcode_refund, undef, $five_days_ago ); + my ( undef, $message ) = AddReturn( $item->barcode, $branchcode_refund, undef, $five_days_ago ); $overdue_fee->discard_changes; - is( $overdue_fee->amount + 0, - 10, 'The OVERDUE amount is left intact' ); - is( $overdue_fee->amountoutstanding + 0, + is( + $overdue_fee->amount + 0, + 10, 'The OVERDUE amount is left intact' + ); + is( + $overdue_fee->amountoutstanding + 0, 10, - 'The OVERDUE amountoutstanding is left intact' ); + 'The OVERDUE amountoutstanding is left intact' + ); $lost_fee_line->discard_changes; - is( $lost_fee_line->amount + 0, - $replacement_amount, 'The LOST amount is left intact' ); - is( $lost_fee_line->amountoutstanding + 0, + is( + $lost_fee_line->amount + 0, + $replacement_amount, 'The LOST amount is left intact' + ); + is( + $lost_fee_line->amountoutstanding + 0, 0, - 'The LOST amountoutstanding is refunded' ); + 'The LOST amountoutstanding is refunded' + ); is( $lost_fee_line->status, 'FOUND', 'The LOST status was set to FOUND' ); }; subtest 'lostreturn | restore' => sub { plan tests => 13; - t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_restore }); + t::lib::Mocks::mock_userenv( { patron => $manager, branchcode => $branchcode_restore } ); - my $item = $builder->build_sample_item( - { - replacementprice => $replacement_amount - } - ); + my $item = $builder->build_sample_item( { replacementprice => $replacement_amount } ); # Issue the item - my $issue = C4::Circulation::AddIssue( $patron, $item->barcode , $ten_days_ago); + my $issue = C4::Circulation::AddIssue( $patron, $item->barcode, $ten_days_ago ); # Fake fines cronjob on this checkout - my ($fine) = - CalcFine( $item, $patron->categorycode, $library->{branchcode}, - $ten_days_ago, $now ); + my ($fine) = CalcFine( + $item, $patron->categorycode, $library->{branchcode}, + $ten_days_ago, $now + ); UpdateFine( { issue_id => $issue->issue_id, @@ -4183,11 +4506,15 @@ subtest 'AddReturn | is_overdue' => sub { ); is( $overdue_fees->count, 1, 'Overdue item fee produced' ); my $overdue_fee = $overdue_fees->next; - is( $overdue_fee->amount + 0, - 10, 'The right OVERDUE amount is generated' ); - is( $overdue_fee->amountoutstanding + 0, + is( + $overdue_fee->amount + 0, + 10, 'The right OVERDUE amount is generated' + ); + is( + $overdue_fee->amountoutstanding + 0, 10, - 'The right OVERDUE amountoutstanding is generated' ); + 'The right OVERDUE amountoutstanding is generated' + ); # Simulate item marked as lost $item->itemlost(3)->store; @@ -4202,11 +4529,15 @@ subtest 'AddReturn | is_overdue' => sub { ); is( $lost_fee_lines->count, 1, 'Lost item fee produced' ); my $lost_fee_line = $lost_fee_lines->next; - is( $lost_fee_line->amount + 0, - $replacement_amount, 'The right LOST amount is generated' ); - is( $lost_fee_line->amountoutstanding + 0, + is( + $lost_fee_line->amount + 0, + $replacement_amount, 'The right LOST amount is generated' + ); + is( + $lost_fee_line->amountoutstanding + 0, $replacement_amount, - 'The right LOST amountoutstanding is generated' ); + 'The right LOST amountoutstanding is generated' + ); is( $lost_fee_line->status, undef, 'The LOST status was not set' ); # Simulate refunding overdue fees upon marking item as lost @@ -4222,46 +4553,50 @@ subtest 'AddReturn | is_overdue' => sub { ); $overdue_forgive->apply( { debits => [$overdue_fee] } ); $overdue_fee->discard_changes; - is($overdue_fee->amountoutstanding + 0, 0, 'Overdue fee forgiven'); + is( $overdue_fee->amountoutstanding + 0, 0, 'Overdue fee forgiven' ); # Do nothing - my ( undef, $message ) = - AddReturn( $item->barcode, $branchcode_restore, undef, $five_days_ago ); + my ( undef, $message ) = AddReturn( $item->barcode, $branchcode_restore, undef, $five_days_ago ); $overdue_fee->discard_changes; - is( $overdue_fee->amount + 0, - 10, 'The OVERDUE amount is left intact' ); - is( $overdue_fee->amountoutstanding + 0, + is( + $overdue_fee->amount + 0, + 10, 'The OVERDUE amount is left intact' + ); + is( + $overdue_fee->amountoutstanding + 0, 10, - 'The OVERDUE amountoutstanding is restored' ); + 'The OVERDUE amountoutstanding is restored' + ); $lost_fee_line->discard_changes; - is( $lost_fee_line->amount + 0, - $replacement_amount, 'The LOST amount is left intact' ); - is( $lost_fee_line->amountoutstanding + 0, + is( + $lost_fee_line->amount + 0, + $replacement_amount, 'The LOST amount is left intact' + ); + is( + $lost_fee_line->amountoutstanding + 0, 0, - 'The LOST amountoutstanding is refunded' ); + 'The LOST amountoutstanding is refunded' + ); is( $lost_fee_line->status, 'FOUND', 'The LOST status was set to FOUND' ); }; subtest 'lostreturn | charge' => sub { plan tests => 16; - t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $branchcode_charge }); + t::lib::Mocks::mock_userenv( { patron => $manager, branchcode => $branchcode_charge } ); - my $item = $builder->build_sample_item( - { - replacementprice => $replacement_amount - } - ); + my $item = $builder->build_sample_item( { replacementprice => $replacement_amount } ); # Issue the item my $issue = C4::Circulation::AddIssue( $patron, $item->barcode, $ten_days_ago ); # Fake fines cronjob on this checkout - my ($fine) = - CalcFine( $item, $patron->categorycode, $library->{branchcode}, - $ten_days_ago, $now ); + my ($fine) = CalcFine( + $item, $patron->categorycode, $library->{branchcode}, + $ten_days_ago, $now + ); UpdateFine( { issue_id => $issue->issue_id, @@ -4280,11 +4615,15 @@ subtest 'AddReturn | is_overdue' => sub { ); is( $overdue_fees->count, 1, 'Overdue item fee produced' ); my $overdue_fee = $overdue_fees->next; - is( $overdue_fee->amount + 0, - 10, 'The right OVERDUE amount is generated' ); - is( $overdue_fee->amountoutstanding + 0, + is( + $overdue_fee->amount + 0, + 10, 'The right OVERDUE amount is generated' + ); + is( + $overdue_fee->amountoutstanding + 0, 10, - 'The right OVERDUE amountoutstanding is generated' ); + 'The right OVERDUE amountoutstanding is generated' + ); # Simulate item marked as lost $item->itemlost(3)->store; @@ -4299,11 +4638,15 @@ subtest 'AddReturn | is_overdue' => sub { ); is( $lost_fee_lines->count, 1, 'Lost item fee produced' ); my $lost_fee_line = $lost_fee_lines->next; - is( $lost_fee_line->amount + 0, - $replacement_amount, 'The right LOST amount is generated' ); - is( $lost_fee_line->amountoutstanding + 0, + is( + $lost_fee_line->amount + 0, + $replacement_amount, 'The right LOST amount is generated' + ); + is( + $lost_fee_line->amountoutstanding + 0, $replacement_amount, - 'The right LOST amountoutstanding is generated' ); + 'The right LOST amountoutstanding is generated' + ); is( $lost_fee_line->status, undef, 'The LOST status was not set' ); # Simulate refunding overdue fees upon marking item as lost @@ -4319,18 +4662,21 @@ subtest 'AddReturn | is_overdue' => sub { ); $overdue_forgive->apply( { debits => [$overdue_fee] } ); $overdue_fee->discard_changes; - is($overdue_fee->amountoutstanding + 0, 0, 'Overdue fee forgiven'); + is( $overdue_fee->amountoutstanding + 0, 0, 'Overdue fee forgiven' ); # Do nothing - my ( undef, $message ) = - AddReturn( $item->barcode, $branchcode_charge, undef, $five_days_ago ); + my ( undef, $message ) = AddReturn( $item->barcode, $branchcode_charge, undef, $five_days_ago ); $lost_fee_line->discard_changes; - is( $lost_fee_line->amount + 0, - $replacement_amount, 'The LOST amount is left intact' ); - is( $lost_fee_line->amountoutstanding + 0, + is( + $lost_fee_line->amount + 0, + $replacement_amount, 'The LOST amount is left intact' + ); + is( + $lost_fee_line->amountoutstanding + 0, 0, - 'The LOST amountoutstanding is refunded' ); + 'The LOST amountoutstanding is refunded' + ); is( $lost_fee_line->status, 'FOUND', 'The LOST status was set to FOUND' ); $overdue_fees = Koha::Account::Lines->search( @@ -4339,23 +4685,29 @@ subtest 'AddReturn | is_overdue' => sub { itemnumber => $item->itemnumber, debit_type_code => 'OVERDUE' }, - { - order_by => { '-asc' => 'accountlines_id'} - } + { order_by => { '-asc' => 'accountlines_id' } } ); is( $overdue_fees->count, 2, 'A second OVERDUE fee has been added' ); $overdue_fee = $overdue_fees->next; - is( $overdue_fee->amount + 0, - 10, 'The original OVERDUE amount is left intact' ); - is( $overdue_fee->amountoutstanding + 0, + is( + $overdue_fee->amount + 0, + 10, 'The original OVERDUE amount is left intact' + ); + is( + $overdue_fee->amountoutstanding + 0, 0, - 'The original OVERDUE amountoutstanding is left as forgiven' ); + 'The original OVERDUE amountoutstanding is left as forgiven' + ); $overdue_fee = $overdue_fees->next; - is( $overdue_fee->amount + 0, - 5, 'The new OVERDUE amount is correct for the backdated return' ); - is( $overdue_fee->amountoutstanding + 0, + is( + $overdue_fee->amount + 0, + 5, 'The new OVERDUE amount is correct for the backdated return' + ); + is( + $overdue_fee->amountoutstanding + 0, 5, - 'The new OVERDUE amountoutstanding is correct for the backdated return' ); + 'The new OVERDUE amountoutstanding is correct for the backdated return' + ); }; }; }; @@ -4363,12 +4715,12 @@ subtest 'AddReturn | is_overdue' => sub { subtest '_FixOverduesOnReturn' => sub { plan tests => 14; - my $manager = $builder->build_object({ class => "Koha::Patrons" }); - t::lib::Mocks::mock_userenv({ patron => $manager, branchcode => $manager->branchcode }); + my $manager = $builder->build_object( { class => "Koha::Patrons" } ); + t::lib::Mocks::mock_userenv( { patron => $manager, branchcode => $manager->branchcode } ); - my $biblio = $builder->build_sample_biblio({ author => 'Hall, Kylie' }); + my $biblio = $builder->build_sample_biblio( { author => 'Hall, Kylie' } ); - my $branchcode = $library2->{branchcode}; + my $branchcode = $library2->{branchcode}; my $item = $builder->build_sample_item( { @@ -4384,13 +4736,13 @@ subtest '_FixOverduesOnReturn' => sub { ## Start with basic call, should just close out the open fine my $accountline = Koha::Account::Line->new( { - borrowernumber => $patron->{borrowernumber}, - debit_type_code => 'OVERDUE', - status => 'UNRETURNED', - itemnumber => $item->itemnumber, - amount => 99.00, + borrowernumber => $patron->{borrowernumber}, + debit_type_code => 'OVERDUE', + status => 'UNRETURNED', + itemnumber => $item->itemnumber, + amount => 99.00, amountoutstanding => 99.00, - interface => 'test', + interface => 'test', } )->store(); @@ -4398,15 +4750,18 @@ subtest '_FixOverduesOnReturn' => sub { $accountline->_result()->discard_changes(); - is( $accountline->amountoutstanding+0, 99, 'Fine has the same amount outstanding as previously' ); - isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )'); - is( $accountline->status, 'RETURNED', 'Passed status has been used to set as RETURNED )'); + is( $accountline->amountoutstanding + 0, 99, 'Fine has the same amount outstanding as previously' ); + isnt( + $accountline->status, 'UNRETURNED', + 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )' + ); + is( $accountline->status, 'RETURNED', 'Passed status has been used to set as RETURNED )' ); ## Run again, with exemptfine enabled $accountline->set( { - debit_type_code => 'OVERDUE', - status => 'UNRETURNED', + debit_type_code => 'OVERDUE', + status => 'UNRETURNED', amountoutstanding => 99.00, } )->store(); @@ -4414,23 +4769,29 @@ subtest '_FixOverduesOnReturn' => sub { C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, 1, 'RETURNED' ); $accountline->_result()->discard_changes(); - my $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id, type => 'APPLY' })->next(); + my $offset = Koha::Account::Offsets->search( { debit_id => $accountline->id, type => 'APPLY' } )->next(); is( $accountline->amountoutstanding + 0, 0, 'Fine amountoutstanding has been reduced to 0' ); - isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )'); - is( $accountline->status, 'RETURNED', 'Open fine ( account type OVERDUE ) has been set to returned ( status RETURNED )'); - is( ref $offset, "Koha::Account::Offset", "Found matching offset for fine reduction via forgiveness" ); - is( $offset->amount + 0, -99, "Amount of offset is correct" ); + isnt( + $accountline->status, 'UNRETURNED', + 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )' + ); + is( + $accountline->status, 'RETURNED', + 'Open fine ( account type OVERDUE ) has been set to returned ( status RETURNED )' + ); + is( ref $offset, "Koha::Account::Offset", "Found matching offset for fine reduction via forgiveness" ); + is( $offset->amount + 0, -99, "Amount of offset is correct" ); my $credit = $offset->credit; - is( ref $credit, "Koha::Account::Line", "Found matching credit for fine forgiveness" ); - is( $credit->amount + 0, -99, "Credit amount is set correctly" ); - is( $credit->amountoutstanding + 0, 0, "Credit amountoutstanding is correctly set to 0" ); + is( ref $credit, "Koha::Account::Line", "Found matching credit for fine forgiveness" ); + is( $credit->amount + 0, -99, "Credit amount is set correctly" ); + is( $credit->amountoutstanding + 0, 0, "Credit amountoutstanding is correctly set to 0" ); # Bug 25417 - Only forgive fines where there is an amount outstanding to forgive $accountline->set( { - debit_type_code => 'OVERDUE', - status => 'UNRETURNED', + debit_type_code => 'OVERDUE', + status => 'UNRETURNED', amountoutstanding => 0.00, } )->store(); @@ -4439,27 +4800,40 @@ subtest '_FixOverduesOnReturn' => sub { C4::Circulation::_FixOverduesOnReturn( $patron->{borrowernumber}, $item->itemnumber, 1, 'RETURNED' ); $accountline->_result()->discard_changes(); - $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id, type => 'CREATE' })->next(); + $offset = Koha::Account::Offsets->search( { debit_id => $accountline->id, type => 'CREATE' } )->next(); is( $offset, undef, "No offset created when trying to forgive fine with no outstanding balance" ); - isnt( $accountline->status, 'UNRETURNED', 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )'); - is( $accountline->status, 'RETURNED', 'Passed status has been used to set as RETURNED )'); + isnt( + $accountline->status, 'UNRETURNED', + 'Open fine ( account type OVERDUE ) has been closed out ( status not UNRETURNED )' + ); + is( $accountline->status, 'RETURNED', 'Passed status has been used to set as RETURNED )' ); }; subtest 'Set waiting flag' => sub { plan tests => 11; my $library_1 = $builder->build( { source => 'Branch' } ); - my $patron_1 = $builder->build( { source => 'Borrower', value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } } ); - my $library_2 = $builder->build( { source => 'Branch' } ); - my $patron_2 = $builder->build( { source => 'Borrower', value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } ); - - my $item = $builder->build_sample_item( + my $patron_1 = $builder->build( { - library => $library_1->{branchcode}, + source => 'Borrower', + value => { branchcode => $library_1->{branchcode}, categorycode => $patron_category->{categorycode} } + } + ); + my $library_2 = $builder->build( { source => 'Branch' } ); + my $patron_2 = $builder->build( + { + source => 'Borrower', + value => { branchcode => $library_2->{branchcode}, categorycode => $patron_category->{categorycode} } } ); - set_userenv( $library_2 ); + my $item = $builder->build_sample_item( + { + library => $library_1->{branchcode}, + } + ); + + set_userenv($library_2); my $reserve_id = AddReserve( { branchcode => $library_2->{branchcode}, @@ -4470,44 +4844,45 @@ subtest 'Set waiting flag' => sub { } ); - set_userenv( $library_1 ); + set_userenv($library_1); my $do_transfer = 1; my ( $res, $rr ) = AddReturn( $item->barcode, $library_1->{branchcode} ); ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id ); - my $hold = Koha::Holds->find( $reserve_id ); + my $hold = Koha::Holds->find($reserve_id); is( $hold->found, 'T', 'Hold is in transit' ); - my ( $status ) = CheckReserves($item); - is( $status, 'Transferred', 'Hold is not waiting yet'); + my ($status) = CheckReserves($item); + is( $status, 'Transferred', 'Hold is not waiting yet' ); - set_userenv( $library_2 ); + set_userenv($library_2); $do_transfer = 0; AddReturn( $item->barcode, $library_2->{branchcode} ); ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id ); - $hold = Koha::Holds->find( $reserve_id ); + $hold = Koha::Holds->find($reserve_id); is( $hold->found, 'W', 'Hold is waiting' ); - ( $status ) = CheckReserves($item); - is( $status, 'Waiting', 'Now the hold is waiting'); + ($status) = CheckReserves($item); + is( $status, 'Waiting', 'Now the hold is waiting' ); #Bug 21944 - Waiting transfer checked in at branch other than pickup location - set_userenv( $library_1 ); - (undef, my $messages, undef, undef ) = AddReturn ( $item->barcode, $library_1->{branchcode} ); - $hold = Koha::Holds->find( $reserve_id ); - is( $hold->found, undef, 'Hold is no longer marked waiting' ); - is( $hold->priority, 1, "Hold is now priority one again"); - is( $hold->waitingdate, undef, "Hold no longer has a waiting date"); - is( $hold->itemnumber, $item->itemnumber, "Hold has retained its' itemnumber"); - is( $messages->{ResFound}->{ResFound}, "Reserved", "Hold is still returned"); - is( $messages->{ResFound}->{found}, undef, "Hold is no longer marked found in return message"); - is( $messages->{ResFound}->{priority}, 1, "Hold is priority 1 in return message"); + set_userenv($library_1); + ( undef, my $messages, undef, undef ) = AddReturn( $item->barcode, $library_1->{branchcode} ); + $hold = Koha::Holds->find($reserve_id); + is( $hold->found, undef, 'Hold is no longer marked waiting' ); + is( $hold->priority, 1, "Hold is now priority one again" ); + is( $hold->waitingdate, undef, "Hold no longer has a waiting date" ); + is( $hold->itemnumber, $item->itemnumber, "Hold has retained its' itemnumber" ); + is( $messages->{ResFound}->{ResFound}, "Reserved", "Hold is still returned" ); + is( $messages->{ResFound}->{found}, undef, "Hold is no longer marked found in return message" ); + is( $messages->{ResFound}->{priority}, 1, "Hold is priority 1 in return message" ); }; subtest 'Cancel transfers on lost items' => sub { plan tests => 6; - my $library_to = $builder->build_object( { class => 'Koha::Libraries' } ); - my $item = $builder->build_sample_item(); + my $library_to = $builder->build_object( { class => 'Koha::Libraries' } ); + my $item = $builder->build_sample_item(); my $holdingbranch = $item->holdingbranch; + # Historic transfer (datearrived is defined) my $old_transfer = $builder->build_object( { @@ -4524,6 +4899,7 @@ subtest 'Cancel transfers on lost items' => sub { } } ); + # Queued transfer (datesent is undefined) my $transfer_1 = $builder->build_object( { @@ -4540,6 +4916,7 @@ subtest 'Cancel transfers on lost items' => sub { } } ); + # In transit transfer (datesent is defined, datearrived and datecancelled are both undefined) my $transfer_2 = $builder->build_object( { @@ -4562,15 +4939,15 @@ subtest 'Cancel transfers on lost items' => sub { LostItem( $item->itemnumber, 'test', 1 ); $transfer_1->discard_changes; - isnt($transfer_1->datecancelled, undef, "Queud transfer was cancelled upon item lost"); - is($transfer_1->cancellation_reason, 'ItemLost', "Cancellation reason was set to 'ItemLost'"); + isnt( $transfer_1->datecancelled, undef, "Queud transfer was cancelled upon item lost" ); + is( $transfer_1->cancellation_reason, 'ItemLost', "Cancellation reason was set to 'ItemLost'" ); $transfer_2->discard_changes; - isnt($transfer_2->datecancelled, undef, "Active transfer was cancelled upon item lost"); - is($transfer_2->cancellation_reason, 'ItemLost', "Cancellation reason was set to 'ItemLost'"); + isnt( $transfer_2->datecancelled, undef, "Active transfer was cancelled upon item lost" ); + is( $transfer_2->cancellation_reason, 'ItemLost', "Cancellation reason was set to 'ItemLost'" ); $old_transfer->discard_changes; - is($old_transfer->datecancelled, undef, "Old transfers are unaffected"); + is( $old_transfer->datecancelled, undef, "Old transfers are unaffected" ); $item->discard_changes; - is($item->holdingbranch, $holdingbranch, "Items holding branch remains unchanged"); + is( $item->holdingbranch, $holdingbranch, "Items holding branch remains unchanged" ); }; subtest 'CanBookBeIssued | is_overdue' => sub { @@ -4597,30 +4974,35 @@ subtest 'CanBookBeIssued | is_overdue' => sub { } ); - my $now = dt_from_string()->truncate( to => 'day' ); + my $now = dt_from_string()->truncate( to => 'day' ); my $five_days_go = $now->clone->add( days => 5 ); - my $ten_days_go = $now->clone->add( days => 10); - my $library = $builder->build( { source => 'Branch' } ); - my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } ); + my $ten_days_go = $now->clone->add( days => 10 ); + my $library = $builder->build( { source => 'Branch' } ); + my $patron = $builder->build_object( + { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } ); my $item = $builder->build_sample_item( { - library => $library->{branchcode}, + library => $library->{branchcode}, } ); - my $issue = AddIssue( $patron, $item->barcode, $five_days_go ); # date due was 10d ago + my $issue = AddIssue( $patron, $item->barcode, $five_days_go ); # date due was 10d ago my $actualissue = Koha::Checkouts->find( { itemnumber => $item->itemnumber } ); - is( output_pref({ str => $actualissue->date_due, dateonly => 1}), output_pref({ str => $five_days_go, dateonly => 1}), "First issue works"); - my ($issuingimpossible, $needsconfirmation) = CanBookBeIssued($patron, $item->barcode, $ten_days_go, undef, undef, undef); - is( $needsconfirmation->{RENEW_ISSUE}, 1, "This is a renewal"); - is( $needsconfirmation->{TOO_MANY}, undef, "Not too many, is a renewal"); + is( + output_pref( { str => $actualissue->date_due, dateonly => 1 } ), + output_pref( { str => $five_days_go, dateonly => 1 } ), "First issue works" + ); + my ( $issuingimpossible, $needsconfirmation ) = + CanBookBeIssued( $patron, $item->barcode, $ten_days_go, undef, undef, undef ); + is( $needsconfirmation->{RENEW_ISSUE}, 1, "This is a renewal" ); + is( $needsconfirmation->{TOO_MANY}, undef, "Not too many, is a renewal" ); }; subtest 'ItemsDeniedRenewal rules are checked' => sub { plan tests => 4; - my $idr_lib = $builder->build_object({ class => 'Koha::Libraries'}); + my $idr_lib = $builder->build_object( { class => 'Koha::Libraries' } ); Koha::CirculationRules->set_rules( { categorycode => '*', @@ -4640,17 +5022,23 @@ subtest 'ItemsDeniedRenewal rules are checked' => sub { } ); - my $allow_book = $builder->build_sample_item({ - homebranch => $idr_lib->branchcode, - holdingbranch => $idr_lib->branchcode, - }); - - my $idr_borrower = $builder->build_object({ class => 'Koha::Patrons', value=> { - branchcode => $idr_lib->branchcode, + my $allow_book = $builder->build_sample_item( + { + homebranch => $idr_lib->branchcode, + holdingbranch => $idr_lib->branchcode, } - }); + ); + + my $idr_borrower = $builder->build_object( + { + class => 'Koha::Patrons', + value => { + branchcode => $idr_lib->branchcode, + } + } + ); my $future = dt_from_string->add( days => 1 ); - my $issue = $builder->build_object( + my $issue = $builder->build_object( { class => 'Koha::Checkouts', value => { @@ -4669,33 +5057,35 @@ subtest 'ItemsDeniedRenewal rules are checked' => sub { $mock_item_class->mock( 'is_denied_renewal', sub { return 1; } ); my ( $mayrenew, $error ) = CanBookBeRenewed( $idr_borrower, $issue ); - is( $mayrenew, 0, 'Renewal blocked when $item->is_denied_renewal returns true' ); - is( $error, 'item_denied_renewal', 'Renewal blocked when $item->is_denied_renewal returns true' ); + is( $mayrenew, 0, 'Renewal blocked when $item->is_denied_renewal returns true' ); + is( $error, 'item_denied_renewal', 'Renewal blocked when $item->is_denied_renewal returns true' ); - $mock_item_class->unmock( 'is_denied_renewal' ); + $mock_item_class->unmock('is_denied_renewal'); $mock_item_class->mock( 'is_denied_renewal', sub { return 0; } ); ( $mayrenew, $error ) = CanBookBeRenewed( $idr_borrower, $issue ); - is( $mayrenew, 1, 'Renewal allowed when $item->is_denied_renewal returns false' ); - is( $error, undef, 'Renewal allowed when $item->is_denied_renewal returns false' ); + is( $mayrenew, 1, 'Renewal allowed when $item->is_denied_renewal returns false' ); + is( $error, undef, 'Renewal allowed when $item->is_denied_renewal returns false' ); - $mock_item_class->unmock( 'is_denied_renewal' ); + $mock_item_class->unmock('is_denied_renewal'); }; subtest 'CanBookBeIssued | item-level_itypes=biblio' => sub { plan tests => 2; - t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio + t::lib::Mocks::mock_preference( 'item-level_itypes', 0 ); # biblio my $library = $builder->build( { source => 'Branch' } ); - my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } ); + my $patron = $builder->build_object( + { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } ); my $item = $builder->build_sample_item( { - library => $library->{branchcode}, + library => $library->{branchcode}, } ); - my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef ); + my ( $issuingimpossible, $needsconfirmation ) = + CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef ); is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' ); is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' ); }; @@ -4703,10 +5093,11 @@ subtest 'CanBookBeIssued | item-level_itypes=biblio' => sub { subtest 'CanBookBeIssued | notforloan' => sub { plan tests => 2; - t::lib::Mocks::mock_preference('AllowNotForLoanOverride', 0); + t::lib::Mocks::mock_preference( 'AllowNotForLoanOverride', 0 ); my $library = $builder->build( { source => 'Branch' } ); - my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } ); + my $patron = $builder->build_object( + { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } } ); my $itemtype = $builder->build( { @@ -4716,27 +5107,28 @@ subtest 'CanBookBeIssued | notforloan' => sub { ); my $item = $builder->build_sample_item( { - library => $library->{branchcode}, - itype => $itemtype->{itemtype}, + library => $library->{branchcode}, + itype => $itemtype->{itemtype}, } ); - $item->biblioitem->itemtype($itemtype->{itemtype})->store; + $item->biblioitem->itemtype( $itemtype->{itemtype} )->store; my ( $issuingimpossible, $needsconfirmation ); - subtest 'item-level_itypes = 1' => sub { plan tests => 6; - t::lib::Mocks::mock_preference('item-level_itypes', 1); # item - # Is for loan at item type and item level - ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef ); + t::lib::Mocks::mock_preference( 'item-level_itypes', 1 ); # item + # Is for loan at item type and item level + ( $issuingimpossible, $needsconfirmation ) = + CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef ); is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' ); is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' ); # not for loan at item type level Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store; - ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef ); + ( $issuingimpossible, $needsconfirmation ) = + CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef ); is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' ); is_deeply( $issuingimpossible, @@ -4746,8 +5138,9 @@ subtest 'CanBookBeIssued | notforloan' => sub { # not for loan at item level Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(0)->store; - $item->notforloan( 1 )->store; - ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef ); + $item->notforloan(1)->store; + ( $issuingimpossible, $needsconfirmation ) = + CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef ); is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' ); is_deeply( $issuingimpossible, @@ -4759,7 +5152,7 @@ subtest 'CanBookBeIssued | notforloan' => sub { subtest 'item-level_itypes = 0' => sub { plan tests => 6; - t::lib::Mocks::mock_preference('item-level_itypes', 0); # biblio + t::lib::Mocks::mock_preference( 'item-level_itypes', 0 ); # biblio # We set another itemtype for biblioitem my $itemtype = $builder->build( @@ -4771,14 +5164,16 @@ subtest 'CanBookBeIssued | notforloan' => sub { # for loan at item type and item level $item->notforloan(0)->store; - $item->biblioitem->itemtype($itemtype->{itemtype})->store; - ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef ); + $item->biblioitem->itemtype( $itemtype->{itemtype} )->store; + ( $issuingimpossible, $needsconfirmation ) = + CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef ); is_deeply( $needsconfirmation, {}, 'Item can be issued to this patron' ); is_deeply( $issuingimpossible, {}, 'Item can be issued to this patron' ); # not for loan at item type level Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(1)->store; - ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef ); + ( $issuingimpossible, $needsconfirmation ) = + CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef ); is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' ); is_deeply( $issuingimpossible, @@ -4788,8 +5183,9 @@ subtest 'CanBookBeIssued | notforloan' => sub { # not for loan at item level Koha::ItemTypes->find( $itemtype->{itemtype} )->notforloan(0)->store; - $item->notforloan( 1 )->store; - ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef ); + $item->notforloan(1)->store; + ( $issuingimpossible, $needsconfirmation ) = + CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, undef ); is_deeply( $needsconfirmation, {}, 'No confirmation needed, AllowNotForLoanOverride=0' ); is_deeply( $issuingimpossible, @@ -4804,23 +5200,26 @@ subtest 'CanBookBeIssued | notforloan' => sub { subtest 'CanBookBeIssued | recalls' => sub { plan tests => 3; - t::lib::Mocks::mock_preference("UseRecalls", 1); - t::lib::Mocks::mock_preference("item-level_itypes", 1); - my $patron1 = $builder->build_object({ class => 'Koha::Patrons' }); - my $patron2 = $builder->build_object({ class => 'Koha::Patrons' }); - my $item = $builder->build_sample_item; - Koha::CirculationRules->set_rules({ - branchcode => undef, - itemtype => undef, - categorycode => undef, - rules => { - recalls_allowed => 10, - }, - }); + t::lib::Mocks::mock_preference( "UseRecalls", 1 ); + t::lib::Mocks::mock_preference( "item-level_itypes", 1 ); + my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } ); + my $patron2 = $builder->build_object( { class => 'Koha::Patrons' } ); + my $item = $builder->build_sample_item; + Koha::CirculationRules->set_rules( + { + branchcode => undef, + itemtype => undef, + categorycode => undef, + rules => { + recalls_allowed => 10, + }, + } + ); # item-level recall my $recall = Koha::Recall->new( - { patron_id => $patron1->borrowernumber, + { + patron_id => $patron1->borrowernumber, biblio_id => $item->biblionumber, item_id => $item->itemnumber, item_level => 1, @@ -4828,14 +5227,19 @@ subtest 'CanBookBeIssued | recalls' => sub { } )->store; - my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron2, $item->barcode, undef, undef, undef, undef ); - is( $needsconfirmation->{RECALLED}->id, $recall->id, "Another patron has placed an item-level recall on this item" ); + my ( $issuingimpossible, $needsconfirmation ) = + CanBookBeIssued( $patron2, $item->barcode, undef, undef, undef, undef ); + is( + $needsconfirmation->{RECALLED}->id, $recall->id, + "Another patron has placed an item-level recall on this item" + ); $recall->set_cancelled; # biblio-level recall $recall = Koha::Recall->new( - { patron_id => $patron1->borrowernumber, + { + patron_id => $patron1->borrowernumber, biblio_id => $item->biblionumber, item_id => undef, item_level => 0, @@ -4843,14 +5247,19 @@ subtest 'CanBookBeIssued | recalls' => sub { } )->store; - ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron2, $item->barcode, undef, undef, undef, undef ); - is( $needsconfirmation->{RECALLED}->id, $recall->id, "Another patron has placed a biblio-level recall and this item is eligible to fill it" ); + ( $issuingimpossible, $needsconfirmation ) = + CanBookBeIssued( $patron2, $item->barcode, undef, undef, undef, undef ); + is( + $needsconfirmation->{RECALLED}->id, $recall->id, + "Another patron has placed a biblio-level recall and this item is eligible to fill it" + ); $recall->set_cancelled; # biblio-level recall $recall = Koha::Recall->new( - { patron_id => $patron1->borrowernumber, + { + patron_id => $patron1->borrowernumber, biblio_id => $item->biblionumber, item_id => undef, item_level => 0, @@ -4949,31 +5358,34 @@ subtest 'AddReturn should clear items.onloan for unissued items' => sub { ); AddReturn( $item->barcode, $item->homebranch ); - $item->discard_changes; # refresh + $item->discard_changes; # refresh is( $item->onloan, undef, 'AddReturn did clear items.onloan' ); }; subtest 'AddReturn | recalls' => sub { plan tests => 3; - t::lib::Mocks::mock_preference("UseRecalls", 1); - t::lib::Mocks::mock_preference("item-level_itypes", 1); - my $patron1 = $builder->build_object({ class => 'Koha::Patrons' }); - my $patron2 = $builder->build_object({ class => 'Koha::Patrons' }); - my $item1 = $builder->build_sample_item; - Koha::CirculationRules->set_rules({ - branchcode => undef, - itemtype => undef, - categorycode => undef, - rules => { - recalls_allowed => 10, - }, - }); + t::lib::Mocks::mock_preference( "UseRecalls", 1 ); + t::lib::Mocks::mock_preference( "item-level_itypes", 1 ); + my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } ); + my $patron2 = $builder->build_object( { class => 'Koha::Patrons' } ); + my $item1 = $builder->build_sample_item; + Koha::CirculationRules->set_rules( + { + branchcode => undef, + itemtype => undef, + categorycode => undef, + rules => { + recalls_allowed => 10, + }, + } + ); # this item can fill a recall with pickup at this branch AddIssue( $patron1, $item1->barcode ); my $recall1 = Koha::Recall->new( - { patron_id => $patron2->borrowernumber, + { + patron_id => $patron2->borrowernumber, biblio_id => $item1->biblionumber, item_id => $item1->itemnumber, item_level => 1, @@ -4987,7 +5399,8 @@ subtest 'AddReturn | recalls' => sub { # this item can fill a recall but needs transfer AddIssue( $patron1, $item1->barcode ); $recall1 = Koha::Recall->new( - { patron_id => $patron2->borrowernumber, + { + patron_id => $patron2->borrowernumber, biblio_id => $item1->biblionumber, item_id => $item1->itemnumber, item_level => 1, @@ -5001,7 +5414,8 @@ subtest 'AddReturn | recalls' => sub { # this item is already in transit, do not ask to transfer AddIssue( $patron1, $item1->barcode ); $recall1 = Koha::Recall->new( - { patron_id => $patron2->borrowernumber, + { + patron_id => $patron2->borrowernumber, biblio_id => $item1->biblionumber, item_id => $item1->itemnumber, item_level => 1, @@ -5020,15 +5434,17 @@ subtest 'AddReturn | bundles' => sub { my $schema = Koha::Database->schema; $schema->storage->txn_begin; - my $patron1 = $builder->build_object({ class => 'Koha::Patrons' }); - my $host_item1 = $builder->build_sample_item; + my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } ); + my $host_item1 = $builder->build_sample_item; my $bundle_item1 = $builder->build_sample_item; - $schema->resultset('ItemBundle') - ->create( - { host => $host_item1->itemnumber, item => $bundle_item1->itemnumber } ); + $schema->resultset('ItemBundle')->create( { host => $host_item1->itemnumber, item => $bundle_item1->itemnumber } ); - my ( $doreturn, $messages, $iteminfo, $borrowerinfo ) = AddReturn( $bundle_item1->barcode, $bundle_item1->homebranch ); - is($messages->{InBundle}->id, $host_item1->id, 'AddReturn returns InBundle host item when item is part of a bundle'); + my ( $doreturn, $messages, $iteminfo, $borrowerinfo ) = + AddReturn( $bundle_item1->barcode, $bundle_item1->homebranch ); + is( + $messages->{InBundle}->id, $host_item1->id, + 'AddReturn returns InBundle host item when item is part of a bundle' + ); $schema->storage->txn_rollback; }; @@ -5037,13 +5453,12 @@ subtest 'AddRenewal and AddIssuingCharge tests' => sub { plan tests => 13; - - t::lib::Mocks::mock_preference('item-level_itypes', 1); + t::lib::Mocks::mock_preference( 'item-level_itypes', 1 ); my $issuing_charges = 15; - my $title = 'A title'; - my $author = 'Author, An'; - my $barcode = 'WHATARETHEODDS'; + my $title = 'A title'; + my $author = 'Author, An'; + my $barcode = 'WHATARETHEODDS'; my $circ = Test::MockModule->new('C4::Circulation'); $circ->mock( @@ -5053,14 +5468,16 @@ subtest 'AddRenewal and AddIssuingCharge tests' => sub { } ); - my $library = $builder->build_object({ class => 'Koha::Libraries' }); - my $itemtype = $builder->build_object({ class => 'Koha::ItemTypes', value => { rentalcharge_daily => 0.00 }}); - my $patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { branchcode => $library->id } - }); + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); + my $itemtype = $builder->build_object( { class => 'Koha::ItemTypes', value => { rentalcharge_daily => 0.00 } } ); + my $patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { branchcode => $library->id } + } + ); - my $biblio = $builder->build_sample_biblio({ title=> $title, author => $author }); + my $biblio = $builder->build_sample_biblio( { title => $title, author => $author } ); my $item_id = Koha::Item->new( { biblionumber => $biblio->biblionumber, @@ -5071,7 +5488,7 @@ subtest 'AddRenewal and AddIssuingCharge tests' => sub { itype => $itemtype->id }, )->store->itemnumber; - my $item = Koha::Items->find( $item_id ); + my $item = Koha::Items->find($item_id); my $context = Test::MockModule->new('C4::Context'); $context->mock( userenv => { branch => $library->id } ); @@ -5088,16 +5505,17 @@ subtest 'AddRenewal and AddIssuingCharge tests' => sub { lastreneweddate => { break => "the_renewal" } } ); - } 'Koha::Exceptions::Checkout::FailedRenewal', 'Exception is thrown when renewal update to issues fails'; + } + 'Koha::Exceptions::Checkout::FailedRenewal', 'Exception is thrown when renewal update to issues fails'; t::lib::Mocks::mock_preference( 'RenewalLog', 0 ); - my $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } ); + my $date = output_pref( { dt => dt_from_string(), dateonly => 1, dateformat => 'iso' } ); my %params_renewal = ( timestamp => { -like => $date . "%" }, - module => "CIRCULATION", - action => "RENEWAL", + module => "CIRCULATION", + action => "RENEWAL", ); - my $old_log_size = Koha::ActionLogs->count( \%params_renewal );; + my $old_log_size = Koha::ActionLogs->count( \%params_renewal ); AddRenewal( { borrowernumber => $patron->id, @@ -5109,36 +5527,49 @@ subtest 'AddRenewal and AddIssuingCharge tests' => sub { is( $new_log_size, $old_log_size, 'renew log not added because of the syspref RenewalLog' ); my $checkouts = $patron->checkouts; - # The following will fail if run on 00:00:00 - unlike ( $checkouts->next->lastreneweddate, qr/00:00:00/, 'AddRenewal should set the renewal date with the time part'); - my $lines = Koha::Account::Lines->search({ - borrowernumber => $patron->id, - itemnumber => $item->id - }); + # The following will fail if run on 00:00:00 + unlike( + $checkouts->next->lastreneweddate, qr/00:00:00/, + 'AddRenewal should set the renewal date with the time part' + ); + + my $lines = Koha::Account::Lines->search( + { + borrowernumber => $patron->id, + itemnumber => $item->id + } + ); is( $lines->count, 2 ); my $line = $lines->next; - is( $line->debit_type_code, 'RENT', 'The issue of item with issuing charge generates an accountline of the correct type' ); + is( + $line->debit_type_code, 'RENT', + 'The issue of item with issuing charge generates an accountline of the correct type' + ); is( $line->branchcode, $library->id, 'AddIssuingCharge correctly sets branchcode' ); - is( $line->description, '', 'AddIssue does not set a hardcoded description for the accountline' ); + is( $line->description, '', 'AddIssue does not set a hardcoded description for the accountline' ); $line = $lines->next; - is( $line->debit_type_code, 'RENT_RENEW', 'The renewal of item with issuing charge generates an accountline of the correct type' ); + is( + $line->debit_type_code, 'RENT_RENEW', + 'The renewal of item with issuing charge generates an accountline of the correct type' + ); is( $line->branchcode, $library->id, 'AddRenewal correctly sets branchcode' ); - is( $line->description, '', 'AddRenewal does not set a hardcoded description for the accountline' ); + is( $line->description, '', 'AddRenewal does not set a hardcoded description for the accountline' ); t::lib::Mocks::mock_preference( 'RenewalLog', 1 ); $context = Test::MockModule->new('C4::Context'); - $context->mock( userenv => { branch => undef, interface => 'CRON'} ); #Test statistical logging of renewal via cron (atuo_renew) + $context->mock( userenv => { branch => undef, interface => 'CRON' } ) + ; #Test statistical logging of renewal via cron (atuo_renew) my $now = dt_from_string; - $date = output_pref( { dt => $now, dateonly => 1, dateformat => 'iso' } ); + $date = output_pref( { dt => $now, dateonly => 1, dateformat => 'iso' } ); $old_log_size = Koha::ActionLogs->count( \%params_renewal ); my $sth = $dbh->prepare("SELECT COUNT(*) FROM statistics WHERE itemnumber = ? AND branch = ?"); - $sth->execute($item->id, $library->id); + $sth->execute( $item->id, $library->id ); my ($old_stats_size) = $sth->fetchrow_array; AddRenewal( { @@ -5148,9 +5579,9 @@ subtest 'AddRenewal and AddIssuingCharge tests' => sub { } ); $new_log_size = Koha::ActionLogs->count( \%params_renewal ); - $sth->execute($item->id, $library->id); + $sth->execute( $item->id, $library->id ); my ($new_stats_size) = $sth->fetchrow_array; - is( $new_log_size, $old_log_size + 1, 'renew log successfully added' ); + is( $new_log_size, $old_log_size + 1, 'renew log successfully added' ); is( $new_stats_size, $old_stats_size + 1, 'renew statistic successfully added with passed branch' ); AddReturn( $item->id, $library->id, undef, $date ); @@ -5163,10 +5594,12 @@ subtest 'AddRenewal and AddIssuingCharge tests' => sub { skipfinecalc => 1 } ); - my $lines_skipped = Koha::Account::Lines->search({ - borrowernumber => $patron->id, - itemnumber => $item->id - }); + my $lines_skipped = Koha::Account::Lines->search( + { + borrowernumber => $patron->id, + itemnumber => $item->id + } + ); is( $lines_skipped->count, 5, 'Passing skipfinecalc causes fine calculation on renewal to be skipped' ); }; @@ -5174,11 +5607,13 @@ subtest 'AddRenewal and AddIssuingCharge tests' => sub { subtest 'AddRenewal() adds to renewals' => sub { plan tests => 5; - my $library = $builder->build_object({ class => 'Koha::Libraries' }); - my $patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { branchcode => $library->id } - }); + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); + my $patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { branchcode => $library->id } + } + ); my $item = $builder->build_sample_item(); @@ -5186,7 +5621,7 @@ subtest 'AddRenewal() adds to renewals' => sub { # Check the item out my $issue = AddIssue( $patron, $item->barcode ); - is(ref($issue), 'Koha::Checkout', 'Issue added'); + is( ref($issue), 'Koha::Checkout', 'Issue added' ); # Renew item my $duedate = AddRenewal( @@ -5200,31 +5635,31 @@ subtest 'AddRenewal() adds to renewals' => sub { ok( $duedate, "Renewal added" ); - my $renewals = Koha::Checkouts::Renewals->search({ checkout_id => $issue->issue_id }); - is($renewals->count, 1, 'One renewal added'); + my $renewals = Koha::Checkouts::Renewals->search( { checkout_id => $issue->issue_id } ); + is( $renewals->count, 1, 'One renewal added' ); my $THE_renewal = $renewals->next; - is( $THE_renewal->renewer_id, C4::Context->userenv->{'number'}, 'Renewer recorded from context' ); - is( $THE_renewal->renewal_type, 'Automatic', 'AddRenewal "automatic" parameter sets renewal type to "Automatic"'); + is( $THE_renewal->renewer_id, C4::Context->userenv->{'number'}, 'Renewer recorded from context' ); + is( $THE_renewal->renewal_type, 'Automatic', 'AddRenewal "automatic" parameter sets renewal type to "Automatic"' ); }; subtest 'ProcessOfflinePayment() tests' => sub { plan tests => 4; - my $amount = 123; - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); - my $library = $builder->build_object({ class => 'Koha::Libraries' }); - my $result = C4::Circulation::ProcessOfflinePayment({ cardnumber => $patron->cardnumber, amount => $amount, branchcode => $library->id }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); + my $result = C4::Circulation::ProcessOfflinePayment( + { cardnumber => $patron->cardnumber, amount => $amount, branchcode => $library->id } ); is( $result, 'Success.', 'The right string is returned' ); my $lines = $patron->account->lines; - is( $lines->count, 1, 'line created correctly'); + is( $lines->count, 1, 'line created correctly' ); my $line = $lines->next; - is( $line->amount+0, $amount * -1, 'amount picked from params' ); + is( $line->amount + 0, $amount * -1, 'amount picked from params' ); is( $line->branchcode, $library->id, 'branchcode set correctly' ); }; @@ -5252,23 +5687,23 @@ subtest 'Incremented fee tests' => sub { { class => 'Koha::ItemTypes', value => { - notforloan => 0, - rentalcharge => 0, - rentalcharge_daily => 1, - rentalcharge_daily_calendar => 0 + notforloan => 0, + rentalcharge => 0, + rentalcharge_daily => 1, + rentalcharge_daily_calendar => 0 } } )->store; my $item = $builder->build_sample_item( { - library => $library->id, - itype => $itemtype->id, + library => $library->id, + itype => $itemtype->id, } ); - is( $itemtype->rentalcharge_daily + 0,1, 'Daily rental charge stored and retreived correctly' ); - is( $item->effective_itemtype, $itemtype->id, "Itemtype set correctly for item" ); + is( $itemtype->rentalcharge_daily + 0, 1, 'Daily rental charge stored and retreived correctly' ); + is( $item->effective_itemtype, $itemtype->id, "Itemtype set correctly for item" ); my $now = dt_from_string; my $dt_from = $now->clone; @@ -5276,8 +5711,7 @@ subtest 'Incremented fee tests' => sub { my $dt_to_renew = $now->clone->add( days => 13 ); # Daily Tests - my $issue = - AddIssue( $patron, $item->barcode, $dt_to, undef, $dt_from ); + my $issue = AddIssue( $patron, $item->barcode, $dt_to, undef, $dt_from ); my $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } ); is( $accountline->amount + 0, @@ -5305,8 +5739,7 @@ subtest 'Incremented fee tests' => sub { t::lib::Mocks::mock_preference( 'finesCalendar', 'noFinesWhenClosed' ); $itemtype->rentalcharge_daily_calendar(1)->store(); - $issue = - AddIssue( $patron, $item->barcode, $dt_to, undef, $dt_from ); + $issue = AddIssue( $patron, $item->barcode, $dt_to, undef, $dt_from ); $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } ); is( $accountline->amount + 0, @@ -5333,19 +5766,19 @@ subtest 'Incremented fee tests' => sub { $issue->delete(); my $calendar = C4::Calendar->new( branchcode => $library->id ); + # DateTime 1..7 (Mon..Sun), C4::Calender 0..6 (Sun..Sat) my $closed_day = - ( $dt_from->day_of_week == 6 ) ? 0 - : ( $dt_from->day_of_week == 7 ) ? 1 - : $dt_from->day_of_week + 1; - my $closed_day_name = $dt_from->clone->add(days => 1)->day_name; + ( $dt_from->day_of_week == 6 ) ? 0 + : ( $dt_from->day_of_week == 7 ) ? 1 + : $dt_from->day_of_week + 1; + my $closed_day_name = $dt_from->clone->add( days => 1 )->day_name; $calendar->insert_week_day_holiday( weekday => $closed_day, title => 'Test holiday', description => 'Test holiday' ); - $issue = - AddIssue( $patron, $item->barcode, $dt_to, undef, $dt_from ); + $issue = AddIssue( $patron, $item->barcode, $dt_to, undef, $dt_from ); $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } ); is( $accountline->amount + 0, @@ -5373,10 +5806,8 @@ subtest 'Incremented fee tests' => sub { $itemtype->rentalcharge(2)->store; is( $itemtype->rentalcharge + 0, 2, 'Rental charge updated and retreived correctly' ); - $issue = - AddIssue( $patron, $item->barcode, $dt_to, undef, $dt_from ); - my $accountlines = - Koha::Account::Lines->search( { itemnumber => $item->id } ); + $issue = AddIssue( $patron, $item->barcode, $dt_to, undef, $dt_from ); + my $accountlines = Koha::Account::Lines->search( { itemnumber => $item->id } ); is( $accountlines->count, '2', "Fixed charge and accrued charge recorded distinctly" ); $accountlines->delete(); AddRenewal( @@ -5413,8 +5844,7 @@ subtest 'Incremented fee tests' => sub { $dt_to_renew = $now->clone->add( hours => 312 ); $itemtype->rentalcharge_hourly_calendar(0)->store(); - $issue = - AddIssue( $patron, $item->barcode, $dt_to, undef, $dt_from ); + $issue = AddIssue( $patron, $item->barcode, $dt_to, undef, $dt_from ); $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } ); is( $accountline->amount + 0, @@ -5441,8 +5871,7 @@ subtest 'Incremented fee tests' => sub { $issue->delete(); $itemtype->rentalcharge_hourly_calendar(1)->store(); - $issue = - AddIssue( $patron, $item->barcode, $dt_to, undef, $dt_from ); + $issue = AddIssue( $patron, $item->barcode, $dt_to, undef, $dt_from ); $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } ); is( $accountline->amount + 0, @@ -5469,8 +5898,7 @@ subtest 'Incremented fee tests' => sub { $issue->delete(); $calendar->delete_holiday( weekday => $closed_day ); - $issue = - AddIssue( $patron, $item->barcode, $dt_to, undef, $dt_from ); + $issue = AddIssue( $patron, $item->barcode, $dt_to, undef, $dt_from ); $accountline = Koha::Account::Lines->find( { itemnumber => $item->id } ); is( $accountline->amount + 0, @@ -5501,12 +5929,11 @@ subtest 'Incremented fee tests' => sub { subtest 'CanBookBeIssued & RentalFeesCheckoutConfirmation' => sub { plan tests => 2; - t::lib::Mocks::mock_preference('RentalFeesCheckoutConfirmation', 1); - t::lib::Mocks::mock_preference('item-level_itypes', 1); + t::lib::Mocks::mock_preference( 'RentalFeesCheckoutConfirmation', 1 ); + t::lib::Mocks::mock_preference( 'item-level_itypes', 1 ); - my $library = - $builder->build_object( { class => 'Koha::Libraries' } )->store; - my $patron = $builder->build_object( + my $library = $builder->build_object( { class => 'Koha::Libraries' } )->store; + my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } @@ -5536,22 +5963,27 @@ subtest 'CanBookBeIssued & RentalFeesCheckoutConfirmation' => sub { my ( $issuingimpossible, $needsconfirmation ); my $dt_from = dt_from_string(); - my $dt_due = $dt_from->clone->add( days => 3 ); + my $dt_due = $dt_from->clone->add( days => 3 ); $itemtype->rentalcharge(1)->store; - ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef ); + ( $issuingimpossible, $needsconfirmation ) = + CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef ); is_deeply( $needsconfirmation, { RENTALCHARGE => '1.00' }, 'Item needs rentalcharge confirmation to be issued' ); $itemtype->rentalcharge('0')->store; $itemtype->rentalcharge_daily(1)->store; - ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef ); - is_deeply( $needsconfirmation, { RENTALCHARGE => '3' }, 'Item needs rentalcharge confirmation to be issued, increment' ); + ( $issuingimpossible, $needsconfirmation ) = + CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef ); + is_deeply( + $needsconfirmation, { RENTALCHARGE => '3' }, + 'Item needs rentalcharge confirmation to be issued, increment' + ); $itemtype->rentalcharge_daily('0')->store; }; subtest 'CanBookBeIssued & CircConfirmItemParts' => sub { plan tests => 1; - t::lib::Mocks::mock_preference('CircConfirmItemParts', 1); + t::lib::Mocks::mock_preference( 'CircConfirmItemParts', 1 ); my $patron = $builder->build_object( { @@ -5568,17 +6000,21 @@ subtest 'CanBookBeIssued & CircConfirmItemParts' => sub { my $dt_due = dt_from_string->add( days => 3 ); - my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef ); - is_deeply( $needsconfirmation, { ADDITIONAL_MATERIALS => 'includes DVD' }, 'Item needs confirmation of additional parts' ); + my ( $issuingimpossible, $needsconfirmation ) = + CanBookBeIssued( $patron, $item->barcode, $dt_due, undef, undef, undef ); + is_deeply( + $needsconfirmation, { ADDITIONAL_MATERIALS => 'includes DVD' }, + 'Item needs confirmation of additional parts' + ); }; subtest 'Do not return on renewal (LOST charge)' => sub { plan tests => 1; - t::lib::Mocks::mock_preference('MarkLostItemsAsReturned', 'onpayment'); + t::lib::Mocks::mock_preference( 'MarkLostItemsAsReturned', 'onpayment' ); my $library = $builder->build_object( { class => "Koha::Libraries" } ); my $manager = $builder->build_object( { class => "Koha::Patrons" } ); - t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode }); + t::lib::Mocks::mock_userenv( { patron => $manager, branchcode => $manager->branchcode } ); my $biblio = $builder->build_sample_biblio; @@ -5609,7 +6045,8 @@ subtest 'Do not return on renewal (LOST charge)' => sub { # AddRenewal doesn't call _FixAccountForLostAndFound AddIssue( $patron, $item->barcode ); - is( $patron->checkouts->count, 1, + is( + $patron->checkouts->count, 1, 'Renewal should not return the item even if a LOST payment has been made earlier' ); }; @@ -5844,47 +6281,57 @@ subtest 'Update lost item to authorized value on write-off of balance' => sub { subtest 'Filling a hold should cancel existing transfer' => sub { plan tests => 4; - t::lib::Mocks::mock_preference('AutomaticItemReturn', 1); + t::lib::Mocks::mock_preference( 'AutomaticItemReturn', 1 ); my $libraryA = $builder->build_object( { class => 'Koha::Libraries' } ); my $libraryB = $builder->build_object( { class => 'Koha::Libraries' } ); - my $patron = $builder->build_object( + my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode}, - branchcode => $libraryA->branchcode, + branchcode => $libraryA->branchcode, } } ); - my $item = $builder->build_sample_item({ - homebranch => $libraryB->branchcode, - }); + my $item = $builder->build_sample_item( + { + homebranch => $libraryB->branchcode, + } + ); my ( undef, $message ) = AddReturn( $item->barcode, $libraryA->branchcode, undef, undef ); - is( Koha::Item::Transfers->search({ itemnumber => $item->itemnumber, datearrived => undef })->count, 1, "We generate a transfer on checkin"); - AddReserve({ - branchcode => $libraryA->branchcode, - borrowernumber => $patron->borrowernumber, - biblionumber => $item->biblionumber, - itemnumber => $item->itemnumber - }); - my $reserves = Koha::Holds->search({ itemnumber => $item->itemnumber }); - is( $reserves->count, 1, "Reserve is placed"); + is( + Koha::Item::Transfers->search( { itemnumber => $item->itemnumber, datearrived => undef } )->count, 1, + "We generate a transfer on checkin" + ); + AddReserve( + { + branchcode => $libraryA->branchcode, + borrowernumber => $patron->borrowernumber, + biblionumber => $item->biblionumber, + itemnumber => $item->itemnumber + } + ); + my $reserves = Koha::Holds->search( { itemnumber => $item->itemnumber } ); + is( $reserves->count, 1, "Reserve is placed" ); ( undef, $message ) = AddReturn( $item->barcode, $libraryA->branchcode, undef, undef ); my $reserve = $reserves->next; ModReserveAffect( $item->itemnumber, $patron->borrowernumber, 0, $reserve->reserve_id ); $reserve->discard_changes; ok( $reserve->found eq 'W', "Reserve is marked waiting" ); - is( Koha::Item::Transfers->search({ itemnumber => $item->itemnumber, datearrived => undef })->count, 0, "No outstanding transfers when hold is waiting"); + is( + Koha::Item::Transfers->search( { itemnumber => $item->itemnumber, datearrived => undef } )->count, 0, + "No outstanding transfers when hold is waiting" + ); }; subtest 'Tests for NoRefundOnLostReturnedItemsAge with AddReturn' => sub { plan tests => 4; - t::lib::Mocks::mock_preference('BlockReturnOfLostItems', 0); + t::lib::Mocks::mock_preference( 'BlockReturnOfLostItems', 0 ); my $library = $builder->build_object( { class => 'Koha::Libraries' } ); my $patron = $builder->build_object( { @@ -5943,7 +6390,7 @@ subtest 'Tests for NoRefundOnLostReturnedItemsAge with AddReturn' => sub { my $issue = AddIssue( $patron, $item->barcode ); LostItem( $item->itemnumber, 'cli', 0 ); $item->_result->itemlost(1); - $item->_result->itemlost_on( $lost_on ); + $item->_result->itemlost_on($lost_on); $item->_result->update(); my $a = Koha::Account::Lines->search( @@ -5978,7 +6425,7 @@ subtest 'Tests for NoRefundOnLostReturnedItemsAge with AddReturn' => sub { my $issue = AddIssue( $patron, $item->barcode ); LostItem( $item->itemnumber, 'cli', 0 ); $item->_result->itemlost(1); - $item->_result->itemlost_on( $lost_on ); + $item->_result->itemlost_on($lost_on); $item->_result->update(); my $a = Koha::Account::Lines->search( @@ -6013,7 +6460,7 @@ subtest 'Tests for NoRefundOnLostReturnedItemsAge with AddReturn' => sub { my $issue = AddIssue( $patron, $item->barcode ); LostItem( $item->itemnumber, 'cli', 0 ); $item->_result->itemlost(1); - $item->_result->itemlost_on( $lost_on ); + $item->_result->itemlost_on($lost_on); $item->_result->update(); my $a = Koha::Account::Lines->search( @@ -6048,7 +6495,7 @@ subtest 'Tests for NoRefundOnLostReturnedItemsAge with AddReturn' => sub { my $issue = AddIssue( $patron, $item->barcode ); LostItem( $item->itemnumber, 'cli', 0 ); $item->_result->itemlost(1); - $item->_result->itemlost_on( $lost_on ); + $item->_result->itemlost_on($lost_on); $item->_result->update(); my $a = Koha::Account::Lines->search( @@ -6071,7 +6518,7 @@ subtest 'Tests for NoRefundOnLostReturnedItemsAge with AddIssue' => sub { plan tests => 4; - t::lib::Mocks::mock_preference('BlockReturnOfLostItems', 0); + t::lib::Mocks::mock_preference( 'BlockReturnOfLostItems', 0 ); my $library = $builder->build_object( { class => 'Koha::Libraries' } ); my $patron = $builder->build_object( { @@ -6079,7 +6526,7 @@ subtest 'Tests for NoRefundOnLostReturnedItemsAge with AddIssue' => sub { value => { categorycode => $patron_category->{categorycode} } } ); - my $patron2 = $builder->build_object( + my $patron2 = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } @@ -6136,7 +6583,7 @@ subtest 'Tests for NoRefundOnLostReturnedItemsAge with AddIssue' => sub { my $issue = AddIssue( $patron, $item->barcode ); LostItem( $item->itemnumber, 'cli', 0 ); $item->_result->itemlost(1); - $item->_result->itemlost_on( $lost_on ); + $item->_result->itemlost_on($lost_on); $item->_result->update(); my $a = Koha::Account::Lines->search( @@ -6148,7 +6595,7 @@ subtest 'Tests for NoRefundOnLostReturnedItemsAge with AddIssue' => sub { ok( $a, "Found accountline for lost fee" ); is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" ); $issue = AddIssue( $patron2, $item->barcode ); - $a = $a->get_from_storage; + $a = $a->get_from_storage; is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" ); $a->delete; $issue->delete; @@ -6172,7 +6619,7 @@ subtest 'Tests for NoRefundOnLostReturnedItemsAge with AddIssue' => sub { my $issue = AddIssue( $patron, $item->barcode ); LostItem( $item->itemnumber, 'cli', 0 ); $item->_result->itemlost(1); - $item->_result->itemlost_on( $lost_on ); + $item->_result->itemlost_on($lost_on); $item->_result->update(); my $a = Koha::Account::Lines->search( @@ -6184,7 +6631,7 @@ subtest 'Tests for NoRefundOnLostReturnedItemsAge with AddIssue' => sub { ok( $a, "Found accountline for lost fee" ); is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" ); $issue = AddIssue( $patron2, $item->barcode ); - $a = $a->get_from_storage; + $a = $a->get_from_storage; is( $a->amountoutstanding + 0, 0, "Lost fee was refunded" ); $a->delete; }; @@ -6207,7 +6654,7 @@ subtest 'Tests for NoRefundOnLostReturnedItemsAge with AddIssue' => sub { my $issue = AddIssue( $patron, $item->barcode ); LostItem( $item->itemnumber, 'cli', 0 ); $item->_result->itemlost(1); - $item->_result->itemlost_on( $lost_on ); + $item->_result->itemlost_on($lost_on); $item->_result->update(); my $a = Koha::Account::Lines->search( @@ -6219,7 +6666,7 @@ subtest 'Tests for NoRefundOnLostReturnedItemsAge with AddIssue' => sub { ok( $a, "Found accountline for lost fee" ); is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" ); $issue = AddIssue( $patron2, $item->barcode ); - $a = $a->get_from_storage; + $a = $a->get_from_storage; is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" ); $a->delete; }; @@ -6242,7 +6689,7 @@ subtest 'Tests for NoRefundOnLostReturnedItemsAge with AddIssue' => sub { my $issue = AddIssue( $patron, $item->barcode ); LostItem( $item->itemnumber, 'cli', 0 ); $item->_result->itemlost(1); - $item->_result->itemlost_on( $lost_on ); + $item->_result->itemlost_on($lost_on); $item->_result->update(); my $a = Koha::Account::Lines->search( @@ -6255,7 +6702,7 @@ subtest 'Tests for NoRefundOnLostReturnedItemsAge with AddIssue' => sub { ok( $a, "Found accountline for lost fee" ); is( $a->amountoutstanding + 0, 42, "Lost fee charged correctly" ); $issue = AddIssue( $patron2, $item->barcode ); - $a = $a->get_from_storage; + $a = $a->get_from_storage; is( $a->amountoutstanding + 0, 42, "Lost fee was not refunded" ); $a->delete; }; @@ -6264,29 +6711,27 @@ subtest 'Tests for NoRefundOnLostReturnedItemsAge with AddIssue' => sub { subtest 'transferbook tests' => sub { plan tests => 9; - throws_ok - { C4::Circulation::transferbook({}); } + throws_ok { C4::Circulation::transferbook( {} ); } 'Koha::Exceptions::MissingParameter', - 'Koha::Patron->store raises an exception on missing params'; + 'Koha::Patron->store raises an exception on missing params'; - throws_ok - { C4::Circulation::transferbook({to_branch=>'anything'}); } + throws_ok { C4::Circulation::transferbook( { to_branch => 'anything' } ); } 'Koha::Exceptions::MissingParameter', - 'Koha::Patron->store raises an exception on missing params'; + 'Koha::Patron->store raises an exception on missing params'; - throws_ok - { C4::Circulation::transferbook({from_branch=>'anything'}); } + throws_ok { C4::Circulation::transferbook( { from_branch => 'anything' } ); } 'Koha::Exceptions::MissingParameter', - 'Koha::Patron->store raises an exception on missing params'; + 'Koha::Patron->store raises an exception on missing params'; - my ($doreturn,$messages) = C4::Circulation::transferbook({to_branch=>'there',from_branch=>'here'}); - is( $doreturn, 0, "No return without barcode"); - ok( exists $messages->{BadBarcode}, "We get a BadBarcode message if no barcode passed"); + my ( $doreturn, $messages ) = C4::Circulation::transferbook( { to_branch => 'there', from_branch => 'here' } ); + is( $doreturn, 0, "No return without barcode" ); + ok( exists $messages->{BadBarcode}, "We get a BadBarcode message if no barcode passed" ); is( $messages->{BadBarcode}, undef, "No barcode passed means undef BadBarcode" ); - ($doreturn,$messages) = C4::Circulation::transferbook({to_branch=>'there',from_branch=>'here',barcode=>'BadBarcode'}); - is( $doreturn, 0, "No return without barcode"); - ok( exists $messages->{BadBarcode}, "We get a BadBarcode message if no barcode passed"); + ( $doreturn, $messages ) = + C4::Circulation::transferbook( { to_branch => 'there', from_branch => 'here', barcode => 'BadBarcode' } ); + is( $doreturn, 0, "No return without barcode" ); + ok( exists $messages->{BadBarcode}, "We get a BadBarcode message if no barcode passed" ); is( $messages->{BadBarcode}, 'BadBarcode', "No barcode passed means undef BadBarcode" ); }; @@ -6295,14 +6740,14 @@ subtest 'Checkout should correctly terminate a transfer' => sub { plan tests => 7; my $library_1 = $builder->build_object( { class => 'Koha::Libraries' } ); - my $patron_1 = $builder->build_object( + my $patron_1 = $builder->build_object( { class => 'Koha::Patrons', value => { branchcode => $library_1->branchcode } } ); my $library_2 = $builder->build_object( { class => 'Koha::Libraries' } ); - my $patron_2 = $builder->build_object( + my $patron_2 = $builder->build_object( { class => 'Koha::Patrons', value => { branchcode => $library_2->branchcode } @@ -6327,8 +6772,10 @@ subtest 'Checkout should correctly terminate a transfer' => sub { ); my $do_transfer = 1; - ModItemTransfer( $item->itemnumber, $library_1->branchcode, - $library_2->branchcode, 'Reserve' ); + ModItemTransfer( + $item->itemnumber, $library_1->branchcode, + $library_2->branchcode, 'Reserve' + ); ModReserveAffect( $item->itemnumber, undef, $do_transfer, $reserve_id ); my $hold = Koha::Holds->find($reserve_id); is( $hold->found, 'T', 'Hold is in transit' ); @@ -6346,13 +6793,13 @@ subtest 'Checkout should correctly terminate a transfer' => sub { is( $hold->priority, 1, ); }; -subtest 'AddIssue records staff who checked out item if appropriate' => sub { +subtest 'AddIssue records staff who checked out item if appropriate' => sub { plan tests => 2; $module->mock( 'userenv', sub { { branch => $library->{id} } } ); my $library = $builder->build_object( { class => 'Koha::Libraries' } ); - my $patron = $builder->build_object( + my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $patron_category->{categorycode} } @@ -6364,17 +6811,9 @@ subtest 'AddIssue records staff who checked out item if appropriate' => sub { value => { categorycode => $patron_category->{categorycode} } } ); - my $item_1 = $builder->build_sample_item( - { - library => $library->{branchcode} - } - ); + my $item_1 = $builder->build_sample_item( { library => $library->{branchcode} } ); - my $item_2 = $builder->build_sample_item( - { - library => $library->branchcode - } - ); + my $item_2 = $builder->build_sample_item( { library => $library->branchcode } ); $module->mock( 'userenv', sub { { branch => $library->id, number => $issuer->borrowernumber } } ); @@ -6383,21 +6822,26 @@ subtest 'AddIssue records staff who checked out item if appropriate' => sub { my $issue_1 = AddIssue( $patron, $item_1->barcode, $dt_to, undef, $dt_from ); - is( $issue_1->issuer, undef, "Staff who checked out the item not recorded when RecordStaffUserOnCheckout turned off" ); + is( + $issue_1->issuer, undef, + "Staff who checked out the item not recorded when RecordStaffUserOnCheckout turned off" + ); - t::lib::Mocks::mock_preference('RecordStaffUserOnCheckout', 1); + t::lib::Mocks::mock_preference( 'RecordStaffUserOnCheckout', 1 ); - my $issue_2 = - AddIssue( $patron, $item_2->barcode, $dt_to, undef, $dt_from ); + my $issue_2 = AddIssue( $patron, $item_2->barcode, $dt_to, undef, $dt_from ); - is( $issue_2->issuer->borrowernumber, $issuer->borrowernumber, "Staff who checked out the item recorded when RecordStaffUserOnCheckout turned on" ); + is( + $issue_2->issuer->borrowernumber, $issuer->borrowernumber, + "Staff who checked out the item recorded when RecordStaffUserOnCheckout turned on" + ); }; subtest "Item's onloan value should be set if checked out item is checked out to a different patron" => sub { plan tests => 2; my $library_1 = $builder->build_object( { class => 'Koha::Libraries' } ); - my $patron_1 = $builder->build_object( + my $patron_1 = $builder->build_object( { class => 'Koha::Patrons', value => { branchcode => $library_1->branchcode } @@ -6431,55 +6875,77 @@ subtest "SendCirculationAlert" => sub { $ENV{KOHA_TESTING} = 1; # Setup branch, borrowr, and notice - my $library = $builder->build_object({ class => 'Koha::Libraries' }); - set_userenv( $library->unblessed); - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); - C4::Members::Messaging::SetMessagingPreference({ - borrowernumber => $patron->id, - message_transport_types => ['sms'], - message_attribute_id => 5 - }); - my $item = $builder->build_sample_item(); - my $checkin_notice = $builder->build_object({ - class => 'Koha::Notice::Templates', - value =>{ - module => 'circulation', - code => 'CHECKIN', - branchcode => $library->branchcode, - name => 'Test Checkin', - is_html => 0, - content => "Checkins:\n----\n[% biblio.title %]-[% old_checkout.issue_id %]\n----Thank you.", - message_transport_type => 'sms', - lang => 'default' + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); + set_userenv( $library->unblessed ); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + C4::Members::Messaging::SetMessagingPreference( + { + borrowernumber => $patron->id, + message_transport_types => ['sms'], + message_attribute_id => 5 } - })->store; + ); + my $item = $builder->build_sample_item(); + my $checkin_notice = $builder->build_object( + { + class => 'Koha::Notice::Templates', + value => { + module => 'circulation', + code => 'CHECKIN', + branchcode => $library->branchcode, + name => 'Test Checkin', + is_html => 0, + content => "Checkins:\n----\n[% biblio.title %]-[% old_checkout.issue_id %]\n----Thank you.", + message_transport_type => 'sms', + lang => 'default' + } + } + )->store; # Checkout an item, mark it returned, generate a notice - my $issue_1 = AddIssue( $patron, $item->barcode); - MarkIssueReturned( $patron->borrowernumber, $item->itemnumber, undef, 0, { skip_record_index => 1} ); - C4::Circulation::SendCirculationAlert({ - type => 'CHECKIN', - item => $item->unblessed, - borrower => $patron->unblessed, - branch => $library->branchcode, - issue => $issue_1 - }); - my $notice = Koha::Notice::Messages->find({ borrowernumber => $patron->id, letter_code => 'CHECKIN' }); - is($notice->content,"Checkins:\n".$item->biblio->title."-".$issue_1->id."\nThank you.", 'Letter generated with expected output on first checkin' ); - is($notice->to_address, $patron->smsalertnumber, "Letter has the correct to_address set to smsalertnumber for SMS type notices"); + my $issue_1 = AddIssue( $patron, $item->barcode ); + MarkIssueReturned( $patron->borrowernumber, $item->itemnumber, undef, 0, { skip_record_index => 1 } ); + C4::Circulation::SendCirculationAlert( + { + type => 'CHECKIN', + item => $item->unblessed, + borrower => $patron->unblessed, + branch => $library->branchcode, + issue => $issue_1 + } + ); + my $notice = Koha::Notice::Messages->find( { borrowernumber => $patron->id, letter_code => 'CHECKIN' } ); + is( + $notice->content, "Checkins:\n" . $item->biblio->title . "-" . $issue_1->id . "\nThank you.", + 'Letter generated with expected output on first checkin' + ); + is( + $notice->to_address, $patron->smsalertnumber, + "Letter has the correct to_address set to smsalertnumber for SMS type notices" + ); # Checkout an item, mark it returned, generate a notice - my $issue_2 = AddIssue( $patron, $item->barcode); - MarkIssueReturned( $patron->borrowernumber, $item->itemnumber, undef, 0, { skip_record_index => 1} ); - C4::Circulation::SendCirculationAlert({ - type => 'CHECKIN', - item => $item->unblessed, - borrower => $patron->unblessed, - branch => $library->branchcode, - issue => $issue_2 - }); + my $issue_2 = AddIssue( $patron, $item->barcode ); + MarkIssueReturned( $patron->borrowernumber, $item->itemnumber, undef, 0, { skip_record_index => 1 } ); + C4::Circulation::SendCirculationAlert( + { + type => 'CHECKIN', + item => $item->unblessed, + borrower => $patron->unblessed, + branch => $library->branchcode, + issue => $issue_2 + } + ); $notice->discard_changes(); - is($notice->content,"Checkins:\n".$item->biblio->title."-".$issue_1->id."\n".$item->biblio->title."-".$issue_2->id."\nThank you.", 'Letter appended with expected output on second checkin' ); + is( + $notice->content, + "Checkins:\n" + . $item->biblio->title . "-" + . $issue_1->id . "\n" + . $item->biblio->title . "-" + . $issue_2->id + . "\nThank you.", 'Letter appended with expected output on second checkin' + ); }; @@ -6502,8 +6968,8 @@ subtest "GetSoonestRenewDate tests" => sub { } } ); - my $item = $builder->build_sample_item(); - my $issue = AddIssue( $patron, $item->barcode); + my $item = $builder->build_sample_item(); + my $issue = AddIssue( $patron, $item->barcode ); my $datedue = dt_from_string( $issue->date_due() ); # Bug 14395 @@ -6524,7 +6990,6 @@ subtest "GetSoonestRenewDate tests" => sub { 'Bug 14395: Renewals permitted 7 days before due date, as expected' ); - Koha::CirculationRules->set_rule( { categorycode => undef, @@ -6577,55 +7042,64 @@ subtest "GetSoonestRenewDate tests" => sub { subtest "CanBookBeIssued + needsconfirmation message" => sub { plan tests => 4; - my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $library = $builder->build_object( { class => 'Koha::Libraries' } ); - my $biblio = $builder->build_object({ class => 'Koha::Biblios' }); - my $biblioitem = $builder->build_object({ class => 'Koha::Biblioitems', value => { biblionumber => $biblio->biblionumber }}); - my $item = $builder->build_object({ class => 'Koha::Items' , value => { itype => $itemtype, biblionumber => $biblio->biblionumber }}); + my $biblio = $builder->build_object( { class => 'Koha::Biblios' } ); + my $biblioitem = + $builder->build_object( { class => 'Koha::Biblioitems', value => { biblionumber => $biblio->biblionumber } } ); + my $item = $builder->build_object( + { class => 'Koha::Items', value => { itype => $itemtype, biblionumber => $biblio->biblionumber } } ); - my $hold = $builder->build_object({ class => 'Koha::Holds', value => { - biblionumber => $item->biblionumber, - branchcode => $library->branchcode, - itemnumber => undef, - itemtype => undef, - priority => 1, - found => undef, - suspend => 0, - item_group_id => undef - }}); + my $hold = $builder->build_object( + { + class => 'Koha::Holds', + value => { + biblionumber => $item->biblionumber, + branchcode => $library->branchcode, + itemnumber => undef, + itemtype => undef, + priority => 1, + found => undef, + suspend => 0, + item_group_id => undef + } + } + ); my ( $error, $needsconfirmation, $alerts, $messages ); ( $error, $needsconfirmation, $alerts, $messages ) = CanBookBeIssued( $patron, $item->barcode ); - is($needsconfirmation->{resbranchcode}, $hold->branchcode, "Branchcodes match when hold exists."); + is( $needsconfirmation->{resbranchcode}, $hold->branchcode, "Branchcodes match when hold exists." ); $hold->priority(0)->store(); $hold->found("W")->store(); ( $error, $needsconfirmation, $alerts, $messages ) = CanBookBeIssued( $patron, $item->barcode ); - is($needsconfirmation->{resbranchcode}, $hold->branchcode, "Branchcodes match when hold is waiting."); + is( $needsconfirmation->{resbranchcode}, $hold->branchcode, "Branchcodes match when hold is waiting." ); $hold->found("T")->store(); ( $error, $needsconfirmation, $alerts, $messages ) = CanBookBeIssued( $patron, $item->barcode ); - is($needsconfirmation->{resbranchcode}, $hold->branchcode, "Branchcodes match when hold is being transferred."); + is( $needsconfirmation->{resbranchcode}, $hold->branchcode, "Branchcodes match when hold is being transferred." ); $hold->found("P")->store(); ( $error, $needsconfirmation, $alerts, $messages ) = CanBookBeIssued( $patron, $item->barcode ); - is($needsconfirmation->{resbranchcode}, $hold->branchcode, "Branchcodes match when hold is being processed."); + is( $needsconfirmation->{resbranchcode}, $hold->branchcode, "Branchcodes match when hold is being processed." ); }; subtest 'Tests for BlockReturnOfWithdrawnItems' => sub { plan tests => 1; - t::lib::Mocks::mock_preference('BlockReturnOfWithdrawnItems', 1); - t::lib::Mocks::mock_preference('RecordLocalUseOnReturn', 0); + t::lib::Mocks::mock_preference( 'BlockReturnOfWithdrawnItems', 1 ); + t::lib::Mocks::mock_preference( 'RecordLocalUseOnReturn', 0 ); my $item = $builder->build_sample_item(); $item->withdrawn(1)->itemlost(1)->store; my @return = AddReturn( $item->barcode, $item->homebranch, 0, undef ); is_deeply( \@return, - [ 0, { NotIssued => $item->barcode, withdrawn => 1 }, undef, {} ], "Item returned as withdrawn, no other messages"); + [ 0, { NotIssued => $item->barcode, withdrawn => 1 }, undef, {} ], + "Item returned as withdrawn, no other messages" + ); }; subtest 'Tests for transfer not in transit' => sub { @@ -6924,7 +7398,6 @@ subtest 'NoRefundOnLostFinesPaidAge' => sub { ); }; - $schema->storage->txn_rollback; C4::Context->clear_syspref_cache(); $branches = Koha::Libraries->search(); diff --git a/t/db_dependent/Circulation/Branch.t b/t/db_dependent/Circulation/Branch.t index 80a8cc6142..09c7e53990 100755 --- a/t/db_dependent/Circulation/Branch.t +++ b/t/db_dependent/Circulation/Branch.t @@ -18,8 +18,8 @@ use Modern::Perl; use C4::Circulation qw( AddIssue AddReturn GetBranchBorrowerCircRule GetBranchItemRule ); -use C4::Items qw( ModItemTransfer ); -use C4::Biblio qw( AddBiblio ); +use C4::Items qw( ModItemTransfer ); +use C4::Biblio qw( AddBiblio ); use C4::Context; use Koha::CirculationRules; @@ -30,14 +30,15 @@ use t::lib::Mocks; use t::lib::TestBuilder; BEGIN { - use_ok('C4::Circulation', qw( AddIssue AddReturn GetBranchBorrowerCircRule GetBranchItemRule )); + use_ok( 'C4::Circulation', qw( AddIssue AddReturn GetBranchBorrowerCircRule GetBranchItemRule ) ); } -can_ok( 'C4::Circulation', qw( - AddIssue - AddReturn - GetBranchBorrowerCircRule - GetBranchItemRule +can_ok( + 'C4::Circulation', qw( + AddIssue + AddReturn + GetBranchBorrowerCircRule + GetBranchItemRule ) ); @@ -59,42 +60,49 @@ $dbh->do(q|DELETE FROM circulation_rules|); my $builder = t::lib::TestBuilder->new(); # Add branch -my $samplebranch1 = $builder->build({ source => 'Branch' }); -my $samplebranch2 = $builder->build({ source => 'Branch' }); +my $samplebranch1 = $builder->build( { source => 'Branch' } ); +my $samplebranch2 = $builder->build( { source => 'Branch' } ); + # Add itemtypes -my $no_circ_itemtype = $builder->build({ - source => 'Itemtype', - value => { - rentalcharge => '0', - notforloan => 0 +my $no_circ_itemtype = $builder->build( + { + source => 'Itemtype', + value => { + rentalcharge => '0', + notforloan => 0 + } } -}); -my $sampleitemtype1 = $builder->build({ - source => 'Itemtype', - value => { - rentalcharge => '10.0', - notforloan => 1 +); +my $sampleitemtype1 = $builder->build( + { + source => 'Itemtype', + value => { + rentalcharge => '10.0', + notforloan => 1 + } } -}); -my $sampleitemtype2 = $builder->build({ - source => 'Itemtype', - value => { - rentalcharge => '5.0', - notforloan => 0 +); +my $sampleitemtype2 = $builder->build( + { + source => 'Itemtype', + value => { + rentalcharge => '5.0', + notforloan => 0 + } } -}); +); + # Add Category -my $samplecat = $builder->build({ - source => 'Category', - value => { - hidelostitems => 0 +my $samplecat = $builder->build( + { + source => 'Category', + value => { hidelostitems => 0 } } -}); +); #Add biblio and item my $record = MARC::Record->new(); -$record->append_fields( - MARC::Field->new( '952', '0', '0', a => $samplebranch1->{branchcode} ) ); +$record->append_fields( MARC::Field->new( '952', '0', '0', a => $samplebranch1->{branchcode} ) ); my ( $biblionumber, $biblioitemnumber ) = C4::Biblio::AddBiblio( $record, '' ); # item 1 has home branch and holding branch samplebranch1 @@ -105,7 +113,7 @@ my $item_id1 = Koha::Item->new( itemcallnumber => 'callnumber1', homebranch => $samplebranch1->{branchcode}, holdingbranch => $samplebranch1->{branchcode}, - itype => $no_circ_itemtype->{ itemtype } + itype => $no_circ_itemtype->{itemtype} } )->store->itemnumber; @@ -117,7 +125,7 @@ my $item_id2 = Koha::Item->new( itemcallnumber => 'callnumber2', homebranch => $samplebranch2->{branchcode}, holdingbranch => $samplebranch1->{branchcode}, - itype => $no_circ_itemtype->{ itemtype } + itype => $no_circ_itemtype->{itemtype} }, )->store->itemnumber; @@ -134,17 +142,19 @@ my $item_id3 = Koha::Item->new( )->store->itemnumber; #Add borrower -my $borrower_id1 = Koha::Patron->new({ - firstname => 'firstname1', - surname => 'surname1 ', - categorycode => $samplecat->{categorycode}, - branchcode => $samplebranch1->{branchcode}, -})->store->borrowernumber; +my $borrower_id1 = Koha::Patron->new( + { + firstname => 'firstname1', + surname => 'surname1 ', + categorycode => $samplecat->{categorycode}, + branchcode => $samplebranch1->{branchcode}, + } +)->store->borrowernumber; is_deeply( GetBranchBorrowerCircRule(), { patron_maxissueqty => undef, patron_maxonsiteissueqty => undef }, -"Without parameter, GetBranchBorrower returns undef (unilimited) for patron_maxissueqty and patron_maxonsiteissueqty if no rules defined" + "Without parameter, GetBranchBorrower returns undef (unilimited) for patron_maxissueqty and patron_maxonsiteissueqty if no rules defined" ); Koha::CirculationRules->set_rules( @@ -158,7 +168,6 @@ Koha::CirculationRules->set_rules( } ); - Koha::CirculationRules->set_rules( { branchcode => $samplebranch2->{branchcode}, @@ -171,11 +180,11 @@ Koha::CirculationRules->set_rules( ); Koha::CirculationRules->set_rules( { - branchcode => $samplebranch2->{branchcode}, - itemtype => undef, - rules => { - holdallowed => 'from_home_library', - returnbranch => 'holdingbranch', + branchcode => $samplebranch2->{branchcode}, + itemtype => undef, + rules => { + holdallowed => 'from_home_library', + returnbranch => 'holdingbranch', } } ); @@ -192,42 +201,42 @@ Koha::CirculationRules->set_rules( ); Koha::CirculationRules->set_rules( { - branchcode => undef, - itemtype => undef, - rules => { - holdallowed => 'from_local_hold_group', - returnbranch => 'homebranch', + branchcode => undef, + itemtype => undef, + rules => { + holdallowed => 'from_local_hold_group', + returnbranch => 'homebranch', } } ); Koha::CirculationRules->set_rules( { - branchcode => $samplebranch1->{branchcode}, - itemtype => $sampleitemtype1->{itemtype}, - rules => { - holdallowed => 'invalid_value', - returnbranch => 'homebranch', + branchcode => $samplebranch1->{branchcode}, + itemtype => $sampleitemtype1->{itemtype}, + rules => { + holdallowed => 'invalid_value', + returnbranch => 'homebranch', } } ); Koha::CirculationRules->set_rules( { - branchcode => $samplebranch2->{branchcode}, - itemtype => $sampleitemtype1->{itemtype}, - rules => { - holdallowed => 'invalid_value', - returnbranch => 'holdingbranch', + branchcode => $samplebranch2->{branchcode}, + itemtype => $sampleitemtype1->{itemtype}, + rules => { + holdallowed => 'invalid_value', + returnbranch => 'holdingbranch', } } ); Koha::CirculationRules->set_rules( { - branchcode => $samplebranch2->{branchcode}, - itemtype => $sampleitemtype2->{itemtype}, - rules => { - holdallowed => 'invalid_value', - returnbranch => 'noreturn', + branchcode => $samplebranch2->{branchcode}, + itemtype => $sampleitemtype2->{itemtype}, + rules => { + holdallowed => 'invalid_value', + returnbranch => 'noreturn', } } ); @@ -236,12 +245,12 @@ Koha::CirculationRules->set_rules( is_deeply( GetBranchBorrowerCircRule(), { patron_maxissueqty => 4, patron_maxonsiteissueqty => 5 }, -"Without parameter, GetBranchBorrower returns the patron_maxissueqty and patron_maxonsiteissueqty of default_circ_rules" + "Without parameter, GetBranchBorrower returns the patron_maxissueqty and patron_maxonsiteissueqty of default_circ_rules" ); is_deeply( GetBranchBorrowerCircRule( $samplebranch2->{branchcode} ), { patron_maxissueqty => 3, patron_maxonsiteissueqty => 2 }, -"Without only the branchcode specified, GetBranchBorrower returns the patron_maxissueqty and patron_maxonsiteissueqty corresponding" + "Without only the branchcode specified, GetBranchBorrower returns the patron_maxissueqty and patron_maxonsiteissueqty corresponding" ); is_deeply( GetBranchBorrowerCircRule( @@ -254,7 +263,7 @@ is_deeply( is_deeply( GetBranchBorrowerCircRule( -1, -1 ), { patron_maxissueqty => 4, patron_maxonsiteissueqty => 5 }, -"GetBranchBorrower with wrong parameters returns the patron_maxissueqty and patron_maxonsiteissueqty of default_circ_rules" + "GetBranchBorrower with wrong parameters returns the patron_maxissueqty and patron_maxonsiteissueqty of default_circ_rules" ); #Test GetBranchItemRule @@ -270,12 +279,12 @@ is_deeply( is_deeply( GetBranchItemRule(), { holdallowed => 'from_local_hold_group', @lazy_any }, -"Without parameters GetBranchItemRule returns the values in default_circ_rules" + "Without parameters GetBranchItemRule returns the values in default_circ_rules" ); is_deeply( GetBranchItemRule( $samplebranch2->{branchcode} ), { holdallowed => 'from_home_library', @lazy_any }, -"With only a branchcode GetBranchItemRule returns values in default_branch_circ_rules" + "With only a branchcode GetBranchItemRule returns values in default_branch_circ_rules" ); is_deeply( GetBranchItemRule( -1, -1 ), @@ -284,51 +293,68 @@ is_deeply( ); # Test return policies -t::lib::Mocks::mock_preference('AutomaticItemReturn','0'); +t::lib::Mocks::mock_preference( 'AutomaticItemReturn', '0' ); # item1 returned at branch2 should trigger transfer to homebranch -$query = -"INSERT INTO issues (borrowernumber,itemnumber,branchcode) VALUES( ?,?,? )"; +$query = "INSERT INTO issues (borrowernumber,itemnumber,branchcode) VALUES( ?,?,? )"; $dbh->do( $query, {}, $borrower_id1, $item_id1, $samplebranch1->{branchcode} ); t::lib::Mocks::mock_preference( 'CataloguingLog', 1 ); t::lib::Mocks::mock_userenv( { branchcode => $samplebranch2->{branchcode} } ); -my $log_count_before = $schema->resultset('ActionLog')->search({module => 'CATALOGUING'})->count(); -my ($doreturn, $messages, $iteminformation, $borrower) = AddReturn('barcode_1', - $samplebranch2->{branchcode}); -is( $messages->{NeedsTransfer}, $samplebranch1->{branchcode}, "AddReturn respects default return policy - return to homebranch" ); -my $log_count_after = $schema->resultset('ActionLog')->search({module => 'CATALOGUING'})->count(); -is($log_count_before, $log_count_after, "Update to holdingbranch is not logged"); +my $log_count_before = $schema->resultset('ActionLog')->search( { module => 'CATALOGUING' } )->count(); +my ( $doreturn, $messages, $iteminformation, $borrower ) = AddReturn( + 'barcode_1', + $samplebranch2->{branchcode} +); +is( + $messages->{NeedsTransfer}, $samplebranch1->{branchcode}, + "AddReturn respects default return policy - return to homebranch" +); +my $log_count_after = $schema->resultset('ActionLog')->search( { module => 'CATALOGUING' } )->count(); +is( $log_count_before, $log_count_after, "Update to holdingbranch is not logged" ); # item2 returned at branch2 should trigger transfer to holding branch -$query = -"INSERT INTO issues (borrowernumber,itemnumber,branchcode) VALUES( ?,?,? )"; +$query = "INSERT INTO issues (borrowernumber,itemnumber,branchcode) VALUES( ?,?,? )"; $dbh->do( $query, {}, $borrower_id1, $item_id2, $samplebranch2->{branchcode} ); -($doreturn, $messages, $iteminformation, $borrower) = AddReturn('barcode_2', - $samplebranch2->{branchcode}); -is( $messages->{NeedsTransfer}, $samplebranch1->{branchcode}, "AddReturn respects branch return policy - item2->homebranch policy = 'holdingbranch'" ); +( $doreturn, $messages, $iteminformation, $borrower ) = AddReturn( + 'barcode_2', + $samplebranch2->{branchcode} +); +is( + $messages->{NeedsTransfer}, $samplebranch1->{branchcode}, + "AddReturn respects branch return policy - item2->homebranch policy = 'holdingbranch'" +); # Generate the transfer from above -ModItemTransfer($item_id2, $samplebranch2->{branchcode}, $samplebranch1->{branchcode}, "ReturnToHolding"); +ModItemTransfer( $item_id2, $samplebranch2->{branchcode}, $samplebranch1->{branchcode}, "ReturnToHolding" ); + # Fulfill it -($doreturn, $messages, $iteminformation, $borrower) = AddReturn('barcode_2',$samplebranch1->{branchcode}); -is( $messages->{NeedsTransfer}, undef, "AddReturn does not generate a new transfer for return policy when resolving an existing non-Reserve transfer" ); +( $doreturn, $messages, $iteminformation, $borrower ) = AddReturn( 'barcode_2', $samplebranch1->{branchcode} ); +is( + $messages->{NeedsTransfer}, undef, + "AddReturn does not generate a new transfer for return policy when resolving an existing non-Reserve transfer" +); # Generate a hold caused transfer which doesn't have a hold i.e. is the hold is cancelled -ModItemTransfer($item_id2, $samplebranch2->{branchcode}, $samplebranch1->{branchcode}, "Reserve"); +ModItemTransfer( $item_id2, $samplebranch2->{branchcode}, $samplebranch1->{branchcode}, "Reserve" ); + # Fulfill it -($doreturn, $messages, $iteminformation, $borrower) = AddReturn('barcode_2',$samplebranch1->{branchcode}); -is( $messages->{NeedsTransfer}, $samplebranch2->{branchcode}, "AddReturn generates a new transfer for hold transfer if the hold was cancelled" ); +( $doreturn, $messages, $iteminformation, $borrower ) = AddReturn( 'barcode_2', $samplebranch1->{branchcode} ); +is( + $messages->{NeedsTransfer}, $samplebranch2->{branchcode}, + "AddReturn generates a new transfer for hold transfer if the hold was cancelled" +); # item3 should not trigger transfer - floating collection -$query = -"INSERT INTO issues (borrowernumber,itemnumber,branchcode) VALUES( ?,?,? )"; +$query = "INSERT INTO issues (borrowernumber,itemnumber,branchcode) VALUES( ?,?,? )"; $dbh->do( $query, {}, $borrower_id1, $item_id3, $samplebranch1->{branchcode} ); t::lib::Mocks::mock_preference( 'item-level_itypes', 1 ); -($doreturn, $messages, $iteminformation, $borrower) = AddReturn('barcode_3', - $samplebranch1->{branchcode}); -is($messages->{NeedsTransfer},undef,"AddReturn respects branch item return policy - noreturn"); +( $doreturn, $messages, $iteminformation, $borrower ) = AddReturn( + 'barcode_3', + $samplebranch1->{branchcode} +); +is( $messages->{NeedsTransfer}, undef, "AddReturn respects branch item return policy - noreturn" ); t::lib::Mocks::mock_preference( 'item-level_itypes', 0 ); $schema->storage->txn_rollback; @@ -353,7 +379,7 @@ subtest "GetBranchItemRule() tests" => sub { ); my $biblio = $builder->build_sample_biblio; - my $item = Koha::Item->new( + my $item = Koha::Item->new( { biblionumber => $biblio->id, homebranch => $homebranch, @@ -364,28 +390,28 @@ subtest "GetBranchItemRule() tests" => sub { Koha::CirculationRules->set_rule( { - branchcode => $homebranch, - itemtype => undef, - rule_name => 'returnbranch', - rule_value => 'homebranch', + branchcode => $homebranch, + itemtype => undef, + rule_name => 'returnbranch', + rule_value => 'homebranch', } ); Koha::CirculationRules->set_rule( { - branchcode => $holdingbranch, - itemtype => undef, - rule_name => 'returnbranch', - rule_value => 'holdingbranch', + branchcode => $holdingbranch, + itemtype => undef, + rule_name => 'returnbranch', + rule_value => 'holdingbranch', } ); Koha::CirculationRules->set_rule( { - branchcode => $checkinbranch, - itemtype => undef, - rule_name => 'returnbranch', - rule_value => 'noreturn', + branchcode => $checkinbranch, + itemtype => undef, + rule_name => 'returnbranch', + rule_value => 'noreturn', } ); diff --git a/t/db_dependent/Circulation/CalcDateDue.t b/t/db_dependent/Circulation/CalcDateDue.t index f4c232b9dd..1f2fa7842d 100755 --- a/t/db_dependent/Circulation/CalcDateDue.t +++ b/t/db_dependent/Circulation/CalcDateDue.t @@ -13,30 +13,31 @@ use Koha::DateUtils qw( dt_from_string ); use Koha::Library::Hours; use Koha::CirculationRules; -use_ok('C4::Circulation', qw( CalcDateDue )); +use_ok( 'C4::Circulation', qw( CalcDateDue ) ); my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; my $builder = t::lib::TestBuilder->new; t::lib::Mocks::mock_preference( 'ConsiderLibraryHoursInCirculation', 'ignore' ); -my $library = $builder->build_object({ class => 'Koha::Libraries' })->store; +my $library = $builder->build_object( { class => 'Koha::Libraries' } )->store; my $dateexpiry = '2013-01-01'; -my $patron_category = $builder->build_object({ class => 'Koha::Patron::Categories', value => { category_type => 'B' } })->store; +my $patron_category = + $builder->build_object( { class => 'Koha::Patron::Categories', value => { category_type => 'B' } } )->store; my $borrower = $builder->build_object( { - class => 'Koha::Patrons', - value => { + class => 'Koha::Patrons', + value => { categorycode => $patron_category->categorycode, - dateexpiry => $dateexpiry, + dateexpiry => $dateexpiry, } } )->store; -my $itemtype = $builder->build_object({ class => 'Koha::ItemTypes' })->store->itemtype; -my $issuelength = 10; +my $itemtype = $builder->build_object( { class => 'Koha::ItemTypes' } )->store->itemtype; +my $issuelength = 10; my $renewalperiod = 5; -my $lengthunit = 'days'; +my $lengthunit = 'days'; Koha::CirculationRules->search()->delete(); Koha::CirculationRules->set_rules( @@ -53,8 +54,8 @@ Koha::CirculationRules->set_rules( ); #Set syspref ReturnBeforeExpiry = 1 and useDaysMode = 'Days' -t::lib::Mocks::mock_preference('ReturnBeforeExpiry', 1); -t::lib::Mocks::mock_preference('useDaysMode', 'Days'); +t::lib::Mocks::mock_preference( 'ReturnBeforeExpiry', 1 ); +t::lib::Mocks::mock_preference( 'useDaysMode', 'Days' ); my $branchcode = $library->branchcode; @@ -62,57 +63,53 @@ my $cache = Koha::Caches->get_instance(); my $key = $branchcode . "_holidays"; $cache->clear_from_cache($key); -my $start_date = DateTime->new({year => 2013, month => 2, day => 9}); -my $date = C4::Circulation::CalcDateDue( $start_date, $itemtype, $branchcode, $borrower ); -is($date, $dateexpiry . 'T23:59:00', 'date expiry'); +my $start_date = DateTime->new( { year => 2013, month => 2, day => 9 } ); +my $date = C4::Circulation::CalcDateDue( $start_date, $itemtype, $branchcode, $borrower ); +is( $date, $dateexpiry . 'T23:59:00', 'date expiry' ); $date = C4::Circulation::CalcDateDue( $start_date, $itemtype, $branchcode, $borrower, 1 ); - #Set syspref ReturnBeforeExpiry = 1 and useDaysMode != 'Days' -t::lib::Mocks::mock_preference('ReturnBeforeExpiry', 1); -t::lib::Mocks::mock_preference('useDaysMode', 'noDays'); +t::lib::Mocks::mock_preference( 'ReturnBeforeExpiry', 1 ); +t::lib::Mocks::mock_preference( 'useDaysMode', 'noDays' ); -$start_date = DateTime->new({year => 2013, month => 2, day => 9}); -$date = C4::Circulation::CalcDateDue( $start_date, $itemtype, $branchcode, $borrower ); -is($date, $dateexpiry . 'T23:59:00', 'date expiry with useDaysMode to noDays'); +$start_date = DateTime->new( { year => 2013, month => 2, day => 9 } ); +$date = C4::Circulation::CalcDateDue( $start_date, $itemtype, $branchcode, $borrower ); +is( $date, $dateexpiry . 'T23:59:00', 'date expiry with useDaysMode to noDays' ); # Let's add a special holiday on 2013-01-01. With ReturnBeforeExpiry and # useDaysMode different from 'Days', return should forward the dateexpiry. -my $calendar = C4::Calendar->new(branchcode => $branchcode); +my $calendar = C4::Calendar->new( branchcode => $branchcode ); $calendar->insert_single_holiday( - day => 1, - month => 1, - year => 2013, - title =>'holidayTest', - description => 'holidayDesc' + day => 1, + month => 1, + year => 2013, + title => 'holidayTest', + description => 'holidayDesc' ); $date = C4::Circulation::CalcDateDue( $start_date, $itemtype, $branchcode, $borrower ); -is($date, '2012-12-31T23:59:00', 'date expiry should be 2013-01-01 -1 day'); +is( $date, '2012-12-31T23:59:00', 'date expiry should be 2013-01-01 -1 day' ); $calendar->insert_single_holiday( - day => 31, - month => 12, - year => 2012, - title =>'holidayTest', - description => 'holidayDesc' + day => 31, + month => 12, + year => 2012, + title => 'holidayTest', + description => 'holidayDesc' ); $date = C4::Circulation::CalcDateDue( $start_date, $itemtype, $branchcode, $borrower ); -is($date, '2012-12-30T23:59:00', 'date expiry should be 2013-01-01 -2 day'); - +is( $date, '2012-12-30T23:59:00', 'date expiry should be 2013-01-01 -2 day' ); $date = C4::Circulation::CalcDateDue( $start_date, $itemtype, $branchcode, $borrower, 1 ); - #Set syspref ReturnBeforeExpiry = 0 and useDaysMode = 'Days' -t::lib::Mocks::mock_preference('ReturnBeforeExpiry', 0); -t::lib::Mocks::mock_preference('useDaysMode', 'Days'); +t::lib::Mocks::mock_preference( 'ReturnBeforeExpiry', 0 ); +t::lib::Mocks::mock_preference( 'useDaysMode', 'Days' ); -$start_date = DateTime->new({year => 2013, month => 2, day => 9}); -$date = C4::Circulation::CalcDateDue( $start_date, $itemtype, $branchcode, $borrower ); -is($date, '2013-02-' . (9 + $issuelength) . 'T23:59:00', "date expiry ( 9 + $issuelength )"); +$start_date = DateTime->new( { year => 2013, month => 2, day => 9 } ); +$date = C4::Circulation::CalcDateDue( $start_date, $itemtype, $branchcode, $borrower ); +is( $date, '2013-02-' . ( 9 + $issuelength ) . 'T23:59:00', "date expiry ( 9 + $issuelength )" ); $date = C4::Circulation::CalcDateDue( $start_date, $itemtype, $branchcode, $borrower, 1 ); -is($date, '2013-02-' . (9 + $renewalperiod) . 'T23:59:00', "date expiry ( 9 + $renewalperiod )"); - +is( $date, '2013-02-' . ( 9 + $renewalperiod ) . 'T23:59:00', "date expiry ( 9 + $renewalperiod )" ); # Now we want to test the Dayweek useDaysMode option # For this we need a loan period that is a mutiple of 7 days @@ -120,59 +117,74 @@ is($date, '2013-02-' . (9 + $renewalperiod) . 'T23:59:00', "date expiry ( 9 + $r # right thing in that case, it should act as though useDaysMode is set to # Datedue #Set syspref ReturnBeforeExpiry = 0 and useDaysMode = 'Dayweek' -t::lib::Mocks::mock_preference('ReturnBeforeExpiry', 0); -t::lib::Mocks::mock_preference('useDaysMode', 'Dayweek'); +t::lib::Mocks::mock_preference( 'ReturnBeforeExpiry', 0 ); +t::lib::Mocks::mock_preference( 'useDaysMode', 'Dayweek' ); # No closed day interfering, so we should get the regular due date $date = C4::Circulation::CalcDateDue( $start_date, $itemtype, $branchcode, $borrower ); -is($date, '2013-02-' . (9 + $issuelength) . 'T23:59:00', "useDaysMode = Dayweek, no closed days, issue date expiry ( start + $issuelength )"); +is( + $date, '2013-02-' . ( 9 + $issuelength ) . 'T23:59:00', + "useDaysMode = Dayweek, no closed days, issue date expiry ( start + $issuelength )" +); $date = C4::Circulation::CalcDateDue( $start_date, $itemtype, $branchcode, $borrower, 1 ); -is($date, '2013-02-' . (9 + $renewalperiod) . 'T23:59:00', "useDaysMode = Dayweek, no closed days, renewal date expiry ( start + $renewalperiod )"); +is( + $date, '2013-02-' . ( 9 + $renewalperiod ) . 'T23:59:00', + "useDaysMode = Dayweek, no closed days, renewal date expiry ( start + $renewalperiod )" +); # Now let's add a closed day on the expected renewal date, it should # roll forward as per Datedue (i.e. one day at a time) # For issues... $calendar->insert_single_holiday( - day => 9 + $issuelength, - month => 2, - year => 2013, - title =>'DayweekTest1', - description => 'DayweekTest1' + day => 9 + $issuelength, + month => 2, + year => 2013, + title => 'DayweekTest1', + description => 'DayweekTest1' ); $date = C4::Circulation::CalcDateDue( $start_date, $itemtype, $branchcode, $borrower ); -is($date, '2013-02-' . (9 + $issuelength + 1) . 'T23:59:00', "useDaysMode = Dayweek, closed on due date, 10 day loan (should not trigger 7 day roll forward), issue date expiry ( start + $issuelength + 1 )"); +is( + $date, '2013-02-' . ( 9 + $issuelength + 1 ) . 'T23:59:00', + "useDaysMode = Dayweek, closed on due date, 10 day loan (should not trigger 7 day roll forward), issue date expiry ( start + $issuelength + 1 )" +); + # Remove the holiday we just created $calendar->delete_holiday( - day => 9 + $issuelength, - month => 2, - year => 2013 + day => 9 + $issuelength, + month => 2, + year => 2013 ); # ...and for renewals... $calendar->insert_single_holiday( - day => 9 + $renewalperiod, - month => 2, - year => 2013, - title =>'DayweekTest2', - description => 'DayweekTest2' + day => 9 + $renewalperiod, + month => 2, + year => 2013, + title => 'DayweekTest2', + description => 'DayweekTest2' ); $date = C4::Circulation::CalcDateDue( $start_date, $itemtype, $branchcode, $borrower, 1 ); -is($date, '2013-02-' . (9 + $renewalperiod + 1) . 'T23:59:00', "useDaysMode = Dayweek, closed on due date, 5 day renewal (should not trigger 7 day roll forward), renewal date expiry ( start + $renewalperiod + 1 )"); +is( + $date, '2013-02-' . ( 9 + $renewalperiod + 1 ) . 'T23:59:00', + "useDaysMode = Dayweek, closed on due date, 5 day renewal (should not trigger 7 day roll forward), renewal date expiry ( start + $renewalperiod + 1 )" +); + # Remove the holiday we just created $calendar->delete_holiday( - day => 9 + $renewalperiod, - month => 2, - year => 2013, + day => 9 + $renewalperiod, + month => 2, + year => 2013, ); # Now we test it does the right thing if the loan and renewal periods # are a multiple of 7 days -my $dayweek_issuelength = 14; +my $dayweek_issuelength = 14; my $dayweek_renewalperiod = 7; -my $dayweek_lengthunit = 'days'; +my $dayweek_lengthunit = 'days'; -$patron_category = $builder->build_object({ class => 'Koha::Patron::Categories', value => { category_type => 'K' } })->store; +$patron_category = + $builder->build_object( { class => 'Koha::Patron::Categories', value => { category_type => 'K' } } )->store; Koha::CirculationRules->set_rules( { @@ -189,137 +201,162 @@ Koha::CirculationRules->set_rules( my $dayweek_borrower = $builder->build_object( { - class => 'Koha::Patrons', - value => { + class => 'Koha::Patrons', + value => { categorycode => $patron_category->categorycode, - dateexpiry => $dateexpiry, + dateexpiry => $dateexpiry, } } ); # For issues... -$start_date = DateTime->new({year => 2013, month => 2, day => 9}); +$start_date = DateTime->new( { year => 2013, month => 2, day => 9 } ); $calendar->insert_single_holiday( - day => 9 + $dayweek_issuelength, - month => 2, - year => 2013, - title =>'DayweekTest3', - description => 'DayweekTest3' + day => 9 + $dayweek_issuelength, + month => 2, + year => 2013, + title => 'DayweekTest3', + description => 'DayweekTest3' ); $date = C4::Circulation::CalcDateDue( $start_date, $itemtype, $branchcode, $dayweek_borrower ); -my $issue_should_add = $dayweek_issuelength + 7; +my $issue_should_add = $dayweek_issuelength + 7; my $dayweek_issue_expected = $start_date->add( days => $issue_should_add ); -is($date, $dayweek_issue_expected->strftime('%F') . 'T23:59:00', "useDaysMode = Dayweek, closed on due date, 14 day loan (should trigger 7 day roll forward), issue date expiry ( start + $issue_should_add )"); +is( + $date, $dayweek_issue_expected->strftime('%F') . 'T23:59:00', + "useDaysMode = Dayweek, closed on due date, 14 day loan (should trigger 7 day roll forward), issue date expiry ( start + $issue_should_add )" +); + # Remove the holiday we just created $calendar->delete_holiday( - day => 9 + $dayweek_issuelength, - month => 2, - year => 2013, + day => 9 + $dayweek_issuelength, + month => 2, + year => 2013, ); # ...and for renewals... -$start_date = DateTime->new({year => 2013, month => 2, day => 9}); +$start_date = DateTime->new( { year => 2013, month => 2, day => 9 } ); $calendar->insert_single_holiday( - day => 9 + $dayweek_renewalperiod, - month => 2, - year => 2013, - title => 'DayweekTest4', - description => 'DayweekTest4' + day => 9 + $dayweek_renewalperiod, + month => 2, + year => 2013, + title => 'DayweekTest4', + description => 'DayweekTest4' ); $date = C4::Circulation::CalcDateDue( $start_date, $itemtype, $branchcode, $dayweek_borrower, 1 ); -my $renewal_should_add = $dayweek_renewalperiod + 7; +my $renewal_should_add = $dayweek_renewalperiod + 7; my $dayweek_renewal_expected = $start_date->add( days => $renewal_should_add ); -is($date, $dayweek_renewal_expected->strftime('%F') . 'T23:59:00', "useDaysMode = Dayweek, closed on due date, 7 day renewal (should trigger 7 day roll forward), renewal date expiry ( start + $renewal_should_add )"); +is( + $date, $dayweek_renewal_expected->strftime('%F') . 'T23:59:00', + "useDaysMode = Dayweek, closed on due date, 7 day renewal (should trigger 7 day roll forward), renewal date expiry ( start + $renewal_should_add )" +); + # Remove the holiday we just created $calendar->delete_holiday( - day => 9 + $dayweek_renewalperiod, - month => 2, - year => 2013, + day => 9 + $dayweek_renewalperiod, + month => 2, + year => 2013, ); # Now test it continues to roll forward by 7 days until it finds # an open day, so we create a 3 week period of closed Saturdays -$start_date = DateTime->new({year => 2013, month => 2, day => 9}); -my $expected_rolled_date = DateTime->new({year => 2013, month => 3, day => 9}); +$start_date = DateTime->new( { year => 2013, month => 2, day => 9 } ); +my $expected_rolled_date = DateTime->new( { year => 2013, month => 3, day => 9 } ); my $holiday = $start_date->clone(); -$holiday->add(days => 7); +$holiday->add( days => 7 ); $calendar->insert_single_holiday( - day => $holiday->day, - month => $holiday->month, - year => 2013, - title =>'DayweekTest5', - description => 'DayweekTest5' + day => $holiday->day, + month => $holiday->month, + year => 2013, + title => 'DayweekTest5', + description => 'DayweekTest5' ); -$holiday->add(days => 7); +$holiday->add( days => 7 ); $calendar->insert_single_holiday( - day => $holiday->day, - month => $holiday->month, - year => 2013, - title =>'DayweekTest6', - description => 'DayweekTest6' + day => $holiday->day, + month => $holiday->month, + year => 2013, + title => 'DayweekTest6', + description => 'DayweekTest6' ); -$holiday->add(days => 7); +$holiday->add( days => 7 ); $calendar->insert_single_holiday( - day => $holiday->day, - month => $holiday->month, - year => 2013, - title =>'DayweekTest7', - description => 'DayweekTest7' + day => $holiday->day, + month => $holiday->month, + year => 2013, + title => 'DayweekTest7', + description => 'DayweekTest7' ); + # For issues... -$date = C4::Circulation::CalcDateDue( $start_date, $itemtype, $branchcode, $dayweek_borrower ); +$date = C4::Circulation::CalcDateDue( $start_date, $itemtype, $branchcode, $dayweek_borrower ); $dayweek_issue_expected = $start_date->add( days => $issue_should_add ); -is($date, $expected_rolled_date->strftime('%F') . 'T23:59:00', "useDaysMode = Dayweek, closed on due date and two subequent due dates, 14 day loan (should trigger 2 x 7 day roll forward), issue date expiry ( start + 28 )"); +is( + $date, $expected_rolled_date->strftime('%F') . 'T23:59:00', + "useDaysMode = Dayweek, closed on due date and two subequent due dates, 14 day loan (should trigger 2 x 7 day roll forward), issue date expiry ( start + 28 )" +); + # ...and for renewals... -$start_date = DateTime->new({year => 2013, month => 2, day => 9}); -$date = C4::Circulation::CalcDateDue( $start_date, $itemtype, $branchcode, $dayweek_borrower, 1 ); +$start_date = DateTime->new( { year => 2013, month => 2, day => 9 } ); +$date = C4::Circulation::CalcDateDue( $start_date, $itemtype, $branchcode, $dayweek_borrower, 1 ); $dayweek_issue_expected = $start_date->add( days => $renewal_should_add ); -is($date, $expected_rolled_date->strftime('%F') . 'T23:59:00', "useDaysMode = Dayweek, closed on due date and three subsequent due dates, 7 day renewal (should trigger 3 x 7 day roll forward), issue date expiry ( start + 28 )"); +is( + $date, $expected_rolled_date->strftime('%F') . 'T23:59:00', + "useDaysMode = Dayweek, closed on due date and three subsequent due dates, 7 day renewal (should trigger 3 x 7 day roll forward), issue date expiry ( start + 28 )" +); + # Remove the holidays we just created -$start_date = DateTime->new({year => 2013, month => 2, day => 9}); +$start_date = DateTime->new( { year => 2013, month => 2, day => 9 } ); my $del_holiday = $start_date->clone(); -$del_holiday->add(days => 7); +$del_holiday->add( days => 7 ); $calendar->delete_holiday( - day => $del_holiday->day, - month => $del_holiday->month, - year => 2013 + day => $del_holiday->day, + month => $del_holiday->month, + year => 2013 ); -$del_holiday->add(days => 7); +$del_holiday->add( days => 7 ); $calendar->delete_holiday( - day => $del_holiday->day, - month => $del_holiday->month, - year => 2013 + day => $del_holiday->day, + month => $del_holiday->month, + year => 2013 ); -$del_holiday->add(days => 7); +$del_holiday->add( days => 7 ); $calendar->delete_holiday( - day => $del_holiday->day, - month => $del_holiday->month, - year => 2013 + day => $del_holiday->day, + month => $del_holiday->month, + year => 2013 ); # Now test that useDaysMode "Dayweek" doesn't try to roll forward onto # a permanently closed day and instead rolls forward just one day -$start_date = DateTime->new({year => 2013, month => 2, day => 9}); +$start_date = DateTime->new( { year => 2013, month => 2, day => 9 } ); + # Our tests are concerned with Saturdays, so let's close on Saturdays $calendar->insert_week_day_holiday( - weekday => 6, - title => "Saturday closure", + weekday => 6, + title => "Saturday closure", description => "Closed on Saturdays" ); + # For issues... -$date = C4::Circulation::CalcDateDue( $start_date, $itemtype, $branchcode, $dayweek_borrower ); +$date = C4::Circulation::CalcDateDue( $start_date, $itemtype, $branchcode, $dayweek_borrower ); $dayweek_issue_expected = $start_date->add( days => $dayweek_issuelength + 1 ); -is($date, $dayweek_issue_expected->strftime('%F') . 'T23:59:00', "useDaysMode = Dayweek, due on Saturday, closed on Saturdays, 14 day loan (should trigger 1 day roll forward), issue date expiry ( start + 15 )"); -# ...and for renewals... -$start_date = DateTime->new({year => 2013, month => 2, day => 9}); -$date = C4::Circulation::CalcDateDue( $start_date, $itemtype, $branchcode, $dayweek_borrower, 1 ); -$dayweek_renewal_expected = $start_date->add( days => $dayweek_renewalperiod + 1 ); -is($date, $dayweek_renewal_expected->strftime('%F') . 'T23:59:00', "useDaysMode = Dayweek, due on Saturday, closed on Saturdays, 7 day renewal (should trigger 1 day roll forward), issue date expiry ( start + 8 )"); -# Remove the holiday we just created -$calendar->delete_holiday( - weekday => 6 +is( + $date, $dayweek_issue_expected->strftime('%F') . 'T23:59:00', + "useDaysMode = Dayweek, due on Saturday, closed on Saturdays, 14 day loan (should trigger 1 day roll forward), issue date expiry ( start + 15 )" ); +# ...and for renewals... +$start_date = DateTime->new( { year => 2013, month => 2, day => 9 } ); +$date = C4::Circulation::CalcDateDue( $start_date, $itemtype, $branchcode, $dayweek_borrower, 1 ); +$dayweek_renewal_expected = $start_date->add( days => $dayweek_renewalperiod + 1 ); +is( + $date, $dayweek_renewal_expected->strftime('%F') . 'T23:59:00', + "useDaysMode = Dayweek, due on Saturday, closed on Saturdays, 7 day renewal (should trigger 1 day roll forward), issue date expiry ( start + 8 )" +); + +# Remove the holiday we just created +$calendar->delete_holiday( weekday => 6 ); + # Renewal period of 0 is valid Koha::CirculationRules->search()->delete(); Koha::CirculationRules->set_rules( diff --git a/t/db_dependent/Circulation/CalcFine.t b/t/db_dependent/Circulation/CalcFine.t index d372d17339..5a7b9d98e7 100755 --- a/t/db_dependent/Circulation/CalcFine.t +++ b/t/db_dependent/Circulation/CalcFine.t @@ -19,7 +19,7 @@ $schema->storage->txn_begin; our $dbh = C4::Context->dbh; $dbh->do(q|DELETE FROM issues|); -t::lib::Mocks::mock_preference('item-level_itypes', '1'); +t::lib::Mocks::mock_preference( 'item-level_itypes', '1' ); my $builder = t::lib::TestBuilder->new(); @@ -48,7 +48,7 @@ my $patron = $builder->build( my $itemtype = $builder->build( { source => 'Itemtype', - value => { + value => { defaultreplacecost => 6, }, } @@ -83,15 +83,15 @@ subtest 'Test basic functionality' => sub { ); my $start_dt = DateTime->new( - year => 2000, - month => 1, - day => 1, + year => 2000, + month => 1, + day => 1, ); my $end_dt = DateTime->new( - year => 2000, - month => 1, - day => 30, + year => 2000, + month => 1, + day => 30, ); my ($amount) = CalcFine( $item->unblessed, $patron->{categorycode}, $branch->{branchcode}, $start_dt, $end_dt ); @@ -179,7 +179,6 @@ subtest 'Overdue fines cap should be disabled when value is 0.00' => sub { teardown(); }; - subtest 'Test with fine amount empty' => sub { plan tests => 1; @@ -201,19 +200,19 @@ subtest 'Test with fine amount empty' => sub { ); my $start_dt = DateTime->new( - year => 2000, - month => 1, - day => 1, + year => 2000, + month => 1, + day => 1, ); my $end_dt = DateTime->new( - year => 2000, - month => 1, - day => 30, + year => 2000, + month => 1, + day => 30, ); warning_is { - my ($amount) = CalcFine( $item->unblessed, $patron->{categorycode}, $branch->{branchcode}, $start_dt, $end_dt ); + my ($amount) = CalcFine( $item->unblessed, $patron->{categorycode}, $branch->{branchcode}, $start_dt, $end_dt ); } undef, "No warning when fine amount is ''"; @@ -223,7 +222,7 @@ subtest 'Test with fine amount empty' => sub { subtest 'Test cap_fine_to_replacement_price' => sub { plan tests => 2; - t::lib::Mocks::mock_preference('useDefaultReplacementCost', '1'); + t::lib::Mocks::mock_preference( 'useDefaultReplacementCost', '1' ); Koha::CirculationRules->set_rules( { branchcode => undef, @@ -242,15 +241,15 @@ subtest 'Test cap_fine_to_replacement_price' => sub { ); my $start_dt = DateTime->new( - year => 2000, - month => 1, - day => 1, + year => 2000, + month => 1, + day => 1, ); my $end_dt = DateTime->new( - year => 2000, - month => 1, - day => 30, + year => 2000, + month => 1, + day => 30, ); my $item = $builder->build_sample_item( @@ -276,7 +275,7 @@ subtest 'Test cap_fine_to_replacement_price' => sub { subtest 'Test cap_fine_to_replacement_pricew with overduefinescap' => sub { plan tests => 2; - t::lib::Mocks::mock_preference('useDefaultReplacementCost', '1'); + t::lib::Mocks::mock_preference( 'useDefaultReplacementCost', '1' ); Koha::CirculationRules->set_rules( { branchcode => undef, @@ -295,23 +294,34 @@ subtest 'Test cap_fine_to_replacement_pricew with overduefinescap' => sub { ); my $start_dt = DateTime->new( - year => 2000, - month => 1, - day => 1, + year => 2000, + month => 1, + day => 1, ); my $end_dt = DateTime->new( - year => 2000, - month => 1, - day => 30, + year => 2000, + month => 1, + day => 30, ); my ($amount) = CalcFine( $item->unblessed, $patron->{categorycode}, $branch->{branchcode}, $start_dt, $end_dt ); - is( int($amount), 3, 'Got the lesser of overduefinescap and replacement price where overduefinescap < replacement price' ); + is( + int($amount), 3, + 'Got the lesser of overduefinescap and replacement price where overduefinescap < replacement price' + ); - Koha::CirculationRules->set_rule({ rule_name => 'overduefinescap', rule_value => 6, branchcode => undef, categorycode => undef, itemtype => undef }); + Koha::CirculationRules->set_rule( + { + rule_name => 'overduefinescap', rule_value => 6, branchcode => undef, categorycode => undef, + itemtype => undef + } + ); ($amount) = CalcFine( $item->unblessed, $patron->{categorycode}, $branch->{branchcode}, $start_dt, $end_dt ); - is( int($amount), 5, 'Get the lesser of overduefinescap and replacement price where overduefinescap > replacement price' ); + is( + int($amount), 5, + 'Get the lesser of overduefinescap and replacement price where overduefinescap > replacement price' + ); teardown(); }; @@ -325,37 +335,39 @@ subtest 'Recall overdue fines' => sub { categorycode => undef, itemtype => undef, rules => { - fine => '1.00', - lengthunit => 'days', - finedays => 0, - firstremind => 0, - chargeperiod => 1, - recall_overdue_fine => '5.00', + fine => '1.00', + lengthunit => 'days', + finedays => 0, + firstremind => 0, + chargeperiod => 1, + recall_overdue_fine => '5.00', }, } ); my $start_dt = DateTime->new( - year => 2000, - month => 1, - day => 1, + year => 2000, + month => 1, + day => 1, ); my $end_dt = DateTime->new( - year => 2000, - month => 1, - day => 6, + year => 2000, + month => 1, + day => 6, ); - my $recall = Koha::Recall->new({ - patron_id => $patron->{borrowernumber}, - created_date => dt_from_string, - biblio_id => $item->biblionumber, - pickup_library_id => $branch->{branchcode}, - item_id => $item->itemnumber, - expiration_date => undef, - item_level => 1 - })->store; + my $recall = Koha::Recall->new( + { + patron_id => $patron->{borrowernumber}, + created_date => dt_from_string, + biblio_id => $item->biblionumber, + pickup_library_id => $branch->{branchcode}, + item_id => $item->itemnumber, + expiration_date => undef, + item_level => 1 + } + )->store; $recall->set_overdue; my ($amount) = CalcFine( $item->unblessed, $patron->{categorycode}, $branch->{branchcode}, $start_dt, $end_dt ); @@ -365,7 +377,6 @@ subtest 'Recall overdue fines' => sub { ($amount) = CalcFine( $item->unblessed, $patron->{categorycode}, $branch->{branchcode}, $start_dt, $end_dt ); is( int($amount), 5, 'With no recall, use normal fine amount' ); - teardown(); }; diff --git a/t/db_dependent/Circulation/CheckIfIssuedToPatron.t b/t/db_dependent/Circulation/CheckIfIssuedToPatron.t index 9add304139..3aa02e9168 100755 --- a/t/db_dependent/Circulation/CheckIfIssuedToPatron.t +++ b/t/db_dependent/Circulation/CheckIfIssuedToPatron.t @@ -42,7 +42,6 @@ $dbh->do(q|DELETE FROM biblio|); $dbh->do(q|DELETE FROM items|); $dbh->do(q|DELETE FROM categories|); - ## Create sample data # Add a branch my $branchcode = $builder->build( { source => 'Branch' } )->{branchcode}; @@ -59,19 +58,19 @@ my %item_info = ( itype => $itemtype ); -my ($biblionumber1) = AddBiblio(MARC::Record->new, ''); +my ($biblionumber1) = AddBiblio( MARC::Record->new, '' ); my $barcode1 = '0101'; -Koha::Item->new({ barcode => $barcode1, %item_info, biblionumber => $biblionumber1 })->store; -my ($biblionumber2) = AddBiblio(MARC::Record->new, ''); +Koha::Item->new( { barcode => $barcode1, %item_info, biblionumber => $biblionumber1 } )->store; +my ($biblionumber2) = AddBiblio( MARC::Record->new, '' ); my $barcode2 = '0202'; -Koha::Item->new({ barcode => $barcode2, %item_info, biblionumber => $biblionumber2 })->store; +Koha::Item->new( { barcode => $barcode2, %item_info, biblionumber => $biblionumber2 } )->store; my $patron1 = $builder->build_object( { class => 'Koha::Patrons', value => { categorycode => $categorycode, - branchcode => $branchcode + branchcode => $branchcode } } ); @@ -80,7 +79,7 @@ my $patron2 = $builder->build_object( class => 'Koha::Patrons', value => { categorycode => $categorycode, - branchcode => $branchcode + branchcode => $branchcode } } ); @@ -89,52 +88,51 @@ my $borrowernumber1 = $patron1->borrowernumber; my $borrowernumber2 = $patron2->borrowernumber; my $module = Test::MockModule->new('C4::Context'); -$module->mock('userenv', sub { { branch => $branchcode } }); - +$module->mock( 'userenv', sub { { branch => $branchcode } } ); my $check_if_issued = C4::Circulation::CheckIfIssuedToPatron(); is( $check_if_issued, undef, 'CheckIfIssuedToPatron without argument returns undef' ); -$check_if_issued = C4::Circulation::CheckIfIssuedToPatron(undef, $biblionumber1); +$check_if_issued = C4::Circulation::CheckIfIssuedToPatron( undef, $biblionumber1 ); is( $check_if_issued, undef, 'CheckIfIssuedToPatron without the borrower number returns undef' ); -$check_if_issued = C4::Circulation::CheckIfIssuedToPatron($borrowernumber1, undef); +$check_if_issued = C4::Circulation::CheckIfIssuedToPatron( $borrowernumber1, undef ); is( $check_if_issued, undef, 'CheckIfIssuedToPatron without the biblio number returns undef' ); -$check_if_issued = C4::Circulation::CheckIfIssuedToPatron($borrowernumber1, $biblionumber1); +$check_if_issued = C4::Circulation::CheckIfIssuedToPatron( $borrowernumber1, $biblionumber1 ); is( $check_if_issued, undef, 'CheckIfIssuedToPatron returns unef' ); -$check_if_issued = C4::Circulation::CheckIfIssuedToPatron($borrowernumber1, $biblionumber2); +$check_if_issued = C4::Circulation::CheckIfIssuedToPatron( $borrowernumber1, $biblionumber2 ); is( $check_if_issued, undef, 'CheckIfIssuedToPatron returns undef' ); -$check_if_issued = C4::Circulation::CheckIfIssuedToPatron($borrowernumber2, $biblionumber1); +$check_if_issued = C4::Circulation::CheckIfIssuedToPatron( $borrowernumber2, $biblionumber1 ); is( $check_if_issued, undef, 'CheckIfIssuedToPatron returns undef' ); -$check_if_issued = C4::Circulation::CheckIfIssuedToPatron($borrowernumber2, $biblionumber2); +$check_if_issued = C4::Circulation::CheckIfIssuedToPatron( $borrowernumber2, $biblionumber2 ); is( $check_if_issued, undef, 'CheckIfIssuedToPatron returns undef' ); -AddIssue($patron1, '0101'); +AddIssue( $patron1, '0101' ); $check_if_issued = C4::Circulation::CheckIfIssuedToPatron(); is( $check_if_issued, undef, 'CheckIfIssuedToPatron without argument returns undef' ); -$check_if_issued = C4::Circulation::CheckIfIssuedToPatron(undef, $biblionumber1); +$check_if_issued = C4::Circulation::CheckIfIssuedToPatron( undef, $biblionumber1 ); is( $check_if_issued, undef, 'CheckIfIssuedToPatron without the borrower number returns undef' ); -$check_if_issued = C4::Circulation::CheckIfIssuedToPatron($borrowernumber1, undef); +$check_if_issued = C4::Circulation::CheckIfIssuedToPatron( $borrowernumber1, undef ); is( $check_if_issued, undef, 'CheckIfIssuedToPatron without the biblio number returns undef' ); -$check_if_issued = C4::Circulation::CheckIfIssuedToPatron($borrowernumber1, $biblionumber1); +$check_if_issued = C4::Circulation::CheckIfIssuedToPatron( $borrowernumber1, $biblionumber1 ); is( $check_if_issued, 1, 'CheckIfIssuedToPatron returns true' ); -$check_if_issued = C4::Circulation::CheckIfIssuedToPatron($borrowernumber1, $biblionumber2); +$check_if_issued = C4::Circulation::CheckIfIssuedToPatron( $borrowernumber1, $biblionumber2 ); is( $check_if_issued, undef, 'CheckIfIssuedToPatron returns undef' ); -$check_if_issued = C4::Circulation::CheckIfIssuedToPatron($borrowernumber2, $biblionumber1); +$check_if_issued = C4::Circulation::CheckIfIssuedToPatron( $borrowernumber2, $biblionumber1 ); is( $check_if_issued, undef, 'CheckIfIssuedToPatron returns undef' ); -$check_if_issued = C4::Circulation::CheckIfIssuedToPatron($borrowernumber2, $biblionumber2); +$check_if_issued = C4::Circulation::CheckIfIssuedToPatron( $borrowernumber2, $biblionumber2 ); is( $check_if_issued, undef, 'CheckIfIssuedToPatron returns undef' ); -AddIssue($patron2, '0202'); +AddIssue( $patron2, '0202' ); $check_if_issued = C4::Circulation::CheckIfIssuedToPatron(); is( $check_if_issued, undef, 'CheckIfIssuedToPatron without argument returns undef' ); -$check_if_issued = C4::Circulation::CheckIfIssuedToPatron(undef, $biblionumber1); +$check_if_issued = C4::Circulation::CheckIfIssuedToPatron( undef, $biblionumber1 ); is( $check_if_issued, undef, 'CheckIfIssuedToPatron without the borrower number returns undef' ); -$check_if_issued = C4::Circulation::CheckIfIssuedToPatron($borrowernumber1, undef); +$check_if_issued = C4::Circulation::CheckIfIssuedToPatron( $borrowernumber1, undef ); is( $check_if_issued, undef, 'CheckIfIssuedToPatron without the biblio number returns undef' ); -$check_if_issued = C4::Circulation::CheckIfIssuedToPatron($borrowernumber1, $biblionumber1); +$check_if_issued = C4::Circulation::CheckIfIssuedToPatron( $borrowernumber1, $biblionumber1 ); is( $check_if_issued, 1, 'CheckIfIssuedToPatron returns true' ); -$check_if_issued = C4::Circulation::CheckIfIssuedToPatron($borrowernumber1, $biblionumber2); +$check_if_issued = C4::Circulation::CheckIfIssuedToPatron( $borrowernumber1, $biblionumber2 ); is( $check_if_issued, undef, 'CheckIfIssuedToPatron returns undef' ); -$check_if_issued = C4::Circulation::CheckIfIssuedToPatron($borrowernumber2, $biblionumber1); +$check_if_issued = C4::Circulation::CheckIfIssuedToPatron( $borrowernumber2, $biblionumber1 ); is( $check_if_issued, undef, 'CheckIfIssuedToPatron returns undef' ); -$check_if_issued = C4::Circulation::CheckIfIssuedToPatron($borrowernumber2, $biblionumber2); +$check_if_issued = C4::Circulation::CheckIfIssuedToPatron( $borrowernumber2, $biblionumber2 ); is( $check_if_issued, 1, 'CheckIfIssuedToPatron returns true' ); diff --git a/t/db_dependent/Circulation/CheckValidBarcode.t b/t/db_dependent/Circulation/CheckValidBarcode.t index 0e159b60ac..3eb235c5df 100755 --- a/t/db_dependent/Circulation/CheckValidBarcode.t +++ b/t/db_dependent/Circulation/CheckValidBarcode.t @@ -20,14 +20,13 @@ use Modern::Perl; use Test::More tests => 10; use C4::Circulation qw( CheckValidBarcode ); -use C4::Biblio qw( AddBiblio ); +use C4::Biblio qw( AddBiblio ); use C4::Items; use Koha::Database; use Koha::Library; - BEGIN { - use_ok('C4::Circulation', qw( CheckValidBarcode )); + use_ok( 'C4::Circulation', qw( CheckValidBarcode ) ); } my $schema = Koha::Database->new->schema; @@ -41,15 +40,14 @@ $dbh->do(q|DELETE FROM branches|); $dbh->do(q|DELETE FROM biblio|); $dbh->do(q|DELETE FROM categories|); - my $branchcode = 'B'; -Koha::Library->new({ branchcode => $branchcode, branchname => 'Branch' })->store; +Koha::Library->new( { branchcode => $branchcode, branchname => 'Branch' } )->store; my $categorycode = 'C'; -$dbh->do("INSERT INTO categories(categorycode) VALUES(?)", undef, $categorycode); +$dbh->do( "INSERT INTO categories(categorycode) VALUES(?)", undef, $categorycode ); my %item_branch_infos = ( - homebranch => $branchcode, + homebranch => $branchcode, holdingbranch => $branchcode, ); @@ -66,11 +64,11 @@ is( $check_valid_barcode, 0, 'CheckValidBarcode with an invalid barcode returns $check_valid_barcode = C4::Circulation::CheckValidBarcode($barcode3); is( $check_valid_barcode, 0, 'CheckValidBarcode with an invalid barcode returns true' ); -my ($biblionumber1) = AddBiblio(MARC::Record->new, ''); -Koha::Item->new({ barcode => $barcode1, %item_branch_infos, biblionumber => $biblionumber1})->store; -Koha::Item->new({ barcode => $barcode2, %item_branch_infos, biblionumber => $biblionumber1})->store; -my ($biblionumber2) = AddBiblio(MARC::Record->new, ''); -Koha::Item->new({ barcode => $barcode3, %item_branch_infos, biblionumber =>$biblionumber2})->store; +my ($biblionumber1) = AddBiblio( MARC::Record->new, '' ); +Koha::Item->new( { barcode => $barcode1, %item_branch_infos, biblionumber => $biblionumber1 } )->store; +Koha::Item->new( { barcode => $barcode2, %item_branch_infos, biblionumber => $biblionumber1 } )->store; +my ($biblionumber2) = AddBiblio( MARC::Record->new, '' ); +Koha::Item->new( { barcode => $barcode3, %item_branch_infos, biblionumber => $biblionumber2 } )->store; $check_valid_barcode = C4::Circulation::CheckValidBarcode(); is( $check_valid_barcode, 0, 'CheckValidBarcode without barcode returns false' ); diff --git a/t/db_dependent/Circulation/GetHardDueDate.t b/t/db_dependent/Circulation/GetHardDueDate.t index 227bde390c..502a8ed287 100755 --- a/t/db_dependent/Circulation/GetHardDueDate.t +++ b/t/db_dependent/Circulation/GetHardDueDate.t @@ -13,14 +13,14 @@ use t::lib::TestBuilder; use Test::More tests => 9; BEGIN { - use_ok('C4::Circulation', qw( GetHardDueDate GetLoanLength )); + use_ok( 'C4::Circulation', qw( GetHardDueDate GetLoanLength ) ); } can_ok( 'C4::Circulation', qw( - GetHardDueDate - GetLoanLength - ) + GetHardDueDate + GetLoanLength + ) ); my $schema = Koha::Database->new->schema; @@ -86,7 +86,7 @@ my $samplecat = { category_type => 'A', }; my $query = -"INSERT INTO categories (categorycode,description,enrolmentperiod,enrolmentperioddate,dateofbirthrequired,enrolmentfee,overduenoticerequired ,reservefee ,hidelostitems ,category_type) VALUES( ?,?,?,?,?,?,?,?,?,?)"; + "INSERT INTO categories (categorycode,description,enrolmentperiod,enrolmentperioddate,dateofbirthrequired,enrolmentfee,overduenoticerequired ,reservefee ,hidelostitems ,category_type) VALUES( ?,?,?,?,?,?,?,?,?,?)"; $dbh->do( $query, {}, $samplecat->{categorycode}, $samplecat->{description}, @@ -96,16 +96,16 @@ $dbh->do( $samplecat->{hidelostitems}, $samplecat->{category_type} ); -my $builder = t::lib::TestBuilder->new; -my $sampleitemtype1 = $builder->build({ source => 'Itemtype' })->{itemtype}; -my $sampleitemtype2 = $builder->build({ source => 'Itemtype' })->{itemtype}; +my $builder = t::lib::TestBuilder->new; +my $sampleitemtype1 = $builder->build( { source => 'Itemtype' } )->{itemtype}; +my $sampleitemtype2 = $builder->build( { source => 'Itemtype' } )->{itemtype}; #Begin Tests my $default = { - issuelength => 0, + issuelength => 0, renewalperiod => 0, - lengthunit => 'days' + lengthunit => 'days' }; #Test get_effective_rules @@ -201,9 +201,9 @@ my $sampleissuingrule3 = { } }; -Koha::CirculationRules->set_rules( $sampleissuingrule1 ); -Koha::CirculationRules->set_rules( $sampleissuingrule2 ); -Koha::CirculationRules->set_rules( $sampleissuingrule3 ); +Koha::CirculationRules->set_rules($sampleissuingrule1); +Koha::CirculationRules->set_rules($sampleissuingrule2); +Koha::CirculationRules->set_rules($sampleissuingrule3); #Test GetLoanLength is_deeply( @@ -246,8 +246,10 @@ is_deeply( ); #Test GetHardDueDate -my @hardduedate = C4::Circulation::GetHardDueDate( $samplecat->{categorycode}, - $sampleitemtype1, $samplebranch1->{branchcode} ); +my @hardduedate = C4::Circulation::GetHardDueDate( + $samplecat->{categorycode}, + $sampleitemtype1, $samplebranch1->{branchcode} +); is_deeply( \@hardduedate, [ diff --git a/t/db_dependent/Circulation/GetPendingOnSiteCheckouts.t b/t/db_dependent/Circulation/GetPendingOnSiteCheckouts.t index 01d60d9790..6a9e92bd14 100755 --- a/t/db_dependent/Circulation/GetPendingOnSiteCheckouts.t +++ b/t/db_dependent/Circulation/GetPendingOnSiteCheckouts.t @@ -22,7 +22,7 @@ use Test::MockModule; use t::lib::TestBuilder; use C4::Circulation qw( AddIssue GetPendingOnSiteCheckouts ); -use C4::Biblio qw( AddBiblio ); +use C4::Biblio qw( AddBiblio ); use C4::Items; use C4::Members; @@ -36,12 +36,12 @@ my $schema = Koha::Database->schema; $schema->storage->txn_begin; my $builder = t::lib::TestBuilder->new; -my $dbh = C4::Context->dbh; +my $dbh = C4::Context->dbh; $dbh->do(q|DELETE FROM issues|); -my $branchcode = $builder->build({ source => 'Branch' })->{ branchcode }; -my $itemtype = $builder->build({ source => 'Itemtype' })->{ itemtype }; +my $branchcode = $builder->build( { source => 'Branch' } )->{branchcode}; +my $itemtype = $builder->build( { source => 'Itemtype' } )->{itemtype}; my %item_infos = ( homebranch => $branchcode, @@ -49,31 +49,36 @@ my %item_infos = ( itype => $itemtype ); -my ($biblionumber1) = AddBiblio(MARC::Record->new, ''); -my $itemnumber1 = Koha::Item->new({ barcode => '0101', %item_infos, biblionumber => $biblionumber1})->store->itemnumber; -my $itemnumber2 = Koha::Item->new({ barcode => '0102', %item_infos, biblionumber => $biblionumber1})->store->itemnumber; +my ($biblionumber1) = AddBiblio( MARC::Record->new, '' ); +my $itemnumber1 = + Koha::Item->new( { barcode => '0101', %item_infos, biblionumber => $biblionumber1 } )->store->itemnumber; +my $itemnumber2 = + Koha::Item->new( { barcode => '0102', %item_infos, biblionumber => $biblionumber1 } )->store->itemnumber; -my ($biblionumber2) = AddBiblio(MARC::Record->new, ''); -my $itemnumber3 = Koha::Item->new({ barcode => '0203', %item_infos, biblionumber => $biblionumber2})->store->itemnumber; +my ($biblionumber2) = AddBiblio( MARC::Record->new, '' ); +my $itemnumber3 = + Koha::Item->new( { barcode => '0203', %item_infos, biblionumber => $biblionumber2 } )->store->itemnumber; -my $categorycode = $builder->build({ source => 'Category' })->{ categorycode }; -my $patron = $builder->build_object( - { class => 'Koha::Patrons', - value => { categorycode => $categorycode, branchcode => $branchcode } +my $categorycode = $builder->build( { source => 'Category' } )->{categorycode}; +my $patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { categorycode => $categorycode, branchcode => $branchcode } } ); # Need to mock userenv for AddIssue my $module = Test::MockModule->new('C4::Context'); -$module->mock('userenv', sub { { branch => $branchcode } }); -AddIssue($patron, '0101'); -AddIssue($patron, '0203'); +$module->mock( 'userenv', sub { { branch => $branchcode } } ); +AddIssue( $patron, '0101' ); +AddIssue( $patron, '0203' ); # Begin tests... my $onsite_checkouts = GetPendingOnSiteCheckouts; is( scalar @$onsite_checkouts, 0, "No pending on-site checkouts" ); -my $itemnumber4 = Koha::Item->new({ barcode => '0104', %item_infos, biblionumber => $biblionumber1})->store->itemnumber; +my $itemnumber4 = + Koha::Item->new( { barcode => '0104', %item_infos, biblionumber => $biblionumber1 } )->store->itemnumber; AddIssue( $patron, '0104', undef, undef, undef, undef, { onsite_checkout => 1 } ); $onsite_checkouts = GetPendingOnSiteCheckouts; is( scalar @$onsite_checkouts, 1, "There is 1 pending on-site checkout" ); diff --git a/t/db_dependent/Circulation/GetTopIssues.t b/t/db_dependent/Circulation/GetTopIssues.t index 3130faeff0..96a5f83750 100755 --- a/t/db_dependent/Circulation/GetTopIssues.t +++ b/t/db_dependent/Circulation/GetTopIssues.t @@ -24,7 +24,7 @@ use t::lib::TestBuilder; use C4::Context; use C4::Circulation qw( AddIssue GetTopIssues ); -use C4::Biblio qw( GetMarcFromKohaField AddBiblio ); +use C4::Biblio qw( GetMarcFromKohaField AddBiblio ); use C4::Items; use Koha::Database; @@ -37,77 +37,88 @@ my $builder = t::lib::TestBuilder->new(); # Start transaction $schema->storage->txn_begin(); -my $itemtype = $builder->build({ source => 'Itemtype' })->{ itemtype }; -my $category = $builder->build({ source => 'Category' })->{ categorycode }; -my $branch_1 = $builder->build({ source => 'Branch' }); -my $branch_2 = $builder->build({ source => 'Branch' }); +my $itemtype = $builder->build( { source => 'Itemtype' } )->{itemtype}; +my $category = $builder->build( { source => 'Category' } )->{categorycode}; +my $branch_1 = $builder->build( { source => 'Branch' } ); +my $branch_2 = $builder->build( { source => 'Branch' } ); my $c4_context = Test::MockModule->new('C4::Context'); -$c4_context->mock('userenv', sub { - { branch => $branch_1->{ branchcode } } -}); -t::lib::Mocks::mock_preference('item-level_itypes', '0'); +$c4_context->mock( + 'userenv', + sub { + { branch => $branch_1->{branchcode} } + } +); +t::lib::Mocks::mock_preference( 'item-level_itypes', '0' ); -my $biblionumber = create_biblio('Test 1', $itemtype); -Koha::Item->new({ - biblionumber => $biblionumber, - barcode => 'GTI_BARCODE_001', - homebranch => $branch_1->{ branchcode }, - ccode => 'GTI_CCODE', -})->store; +my $biblionumber = create_biblio( 'Test 1', $itemtype ); +Koha::Item->new( + { + biblionumber => $biblionumber, + barcode => 'GTI_BARCODE_001', + homebranch => $branch_1->{branchcode}, + ccode => 'GTI_CCODE', + } +)->store; -$biblionumber = create_biblio('Test 2', $itemtype); -Koha::Item->new({ - biblionumber => $biblionumber, - barcode => 'GTI_BARCODE_002', - homebranch => $branch_2->{ branchcode }, -})->store; +$biblionumber = create_biblio( 'Test 2', $itemtype ); +Koha::Item->new( + { + biblionumber => $biblionumber, + barcode => 'GTI_BARCODE_002', + homebranch => $branch_2->{branchcode}, + } +)->store; -my $borrowernumber = Koha::Patron->new({ - userid => 'gti.test', - categorycode => $category, - branchcode => $branch_1->{ branchcode } -})->store->borrowernumber; -my $borrower = Koha::Patrons->find( $borrowernumber ); +my $borrowernumber = Koha::Patron->new( + { + userid => 'gti.test', + categorycode => $category, + branchcode => $branch_1->{branchcode} + } +)->store->borrowernumber; +my $borrower = Koha::Patrons->find($borrowernumber); -AddIssue($borrower, 'GTI_BARCODE_001'); -AddIssue($borrower, 'GTI_BARCODE_002'); +AddIssue( $borrower, 'GTI_BARCODE_001' ); +AddIssue( $borrower, 'GTI_BARCODE_002' ); # # Start of tests # -my @issues = GetTopIssues({count => 10, itemtype => $itemtype}); -is(scalar @issues, 2); -is($issues[0]->{title}, 'Test 1'); -is($issues[1]->{title}, 'Test 2'); +my @issues = GetTopIssues( { count => 10, itemtype => $itemtype } ); +is( scalar @issues, 2 ); +is( $issues[0]->{title}, 'Test 1' ); +is( $issues[1]->{title}, 'Test 2' ); -@issues = GetTopIssues({count => 1, itemtype => $itemtype}); -is(scalar @issues, 1); -is($issues[0]->{title}, 'Test 1'); +@issues = GetTopIssues( { count => 1, itemtype => $itemtype } ); +is( scalar @issues, 1 ); +is( $issues[0]->{title}, 'Test 1' ); -@issues = GetTopIssues({count => 10, branch => $branch_2->{ branchcode }}); -is(scalar @issues, 1); -is($issues[0]->{title}, 'Test 2'); +@issues = GetTopIssues( { count => 10, branch => $branch_2->{branchcode} } ); +is( scalar @issues, 1 ); +is( $issues[0]->{title}, 'Test 2' ); -@issues = GetTopIssues({count => 10, ccode => 'GTI_CCODE'}); -is(scalar @issues, 1); -is($issues[0]->{title}, 'Test 1'); +@issues = GetTopIssues( { count => 10, ccode => 'GTI_CCODE' } ); +is( scalar @issues, 1 ); +is( $issues[0]->{title}, 'Test 1' ); -@issues = GetTopIssues({count => 10, itemtype => $itemtype, newness => 1}); -is(scalar @issues, 2); -is($issues[0]->{title}, 'Test 1'); -is($issues[1]->{title}, 'Test 2'); +@issues = GetTopIssues( { count => 10, itemtype => $itemtype, newness => 1 } ); +is( scalar @issues, 2 ); +is( $issues[0]->{title}, 'Test 1' ); +is( $issues[1]->{title}, 'Test 2' ); -$dbh->do(q{ +$dbh->do( + q{ UPDATE biblio SET datecreated = DATE_SUB(datecreated, INTERVAL 2 DAY) WHERE biblionumber = ? -}, undef, $biblionumber); +}, undef, $biblionumber +); -@issues = GetTopIssues({count => 10, itemtype => $itemtype, newness => 1}); -is(scalar @issues, 1); -is($issues[0]->{title}, 'Test 1'); +@issues = GetTopIssues( { count => 10, itemtype => $itemtype, newness => 1 } ); +is( scalar @issues, 1 ); +is( $issues[0]->{title}, 'Test 1' ); # # End of tests @@ -116,18 +127,18 @@ is($issues[0]->{title}, 'Test 1'); $schema->storage->txn_rollback(); sub create_biblio { - my ($title, $itemtype) = @_; + my ( $title, $itemtype ) = @_; - my ($title_tag, $title_subfield) = GetMarcFromKohaField( 'biblio.title' ); - my ($it_tag, $it_subfield) = GetMarcFromKohaField( 'biblioitems.itemtype' ); + my ( $title_tag, $title_subfield ) = GetMarcFromKohaField('biblio.title'); + my ( $it_tag, $it_subfield ) = GetMarcFromKohaField('biblioitems.itemtype'); my $record = MARC::Record->new(); $record->append_fields( - MARC::Field->new($title_tag, ' ', ' ', $title_subfield => $title), - MARC::Field->new($it_tag, ' ', ' ', $it_subfield => $itemtype), + MARC::Field->new( $title_tag, ' ', ' ', $title_subfield => $title ), + MARC::Field->new( $it_tag, ' ', ' ', $it_subfield => $itemtype ), ); - my ($biblionumber) = AddBiblio($record, ''); + my ($biblionumber) = AddBiblio( $record, '' ); return $biblionumber; } diff --git a/t/db_dependent/Circulation/IsItemIssued.t b/t/db_dependent/Circulation/IsItemIssued.t index 5cfae54e70..57016c5158 100755 --- a/t/db_dependent/Circulation/IsItemIssued.t +++ b/t/db_dependent/Circulation/IsItemIssued.t @@ -36,47 +36,48 @@ my $schema = Koha::Database->schema; $schema->storage->txn_begin; my $builder = t::lib::TestBuilder->new; -my $library = $builder->build({ source => 'Branch' }); -my $itemtype = $builder->build({ source => 'Itemtype' })->{itemtype}; -my $patron_category = $builder->build({ source => 'Category' }); +my $library = $builder->build( { source => 'Branch' } ); +my $itemtype = $builder->build( { source => 'Itemtype' } )->{itemtype}; +my $patron_category = $builder->build( { source => 'Category' } ); -t::lib::Mocks::mock_userenv({ branchcode => $library->{branchcode} }); - -my $borrower = Koha::Patron->new({ - firstname => 'my firstname', - surname => 'my surname', - categorycode => $patron_category->{categorycode}, - branchcode => $library->{branchcode}, -})->store; +t::lib::Mocks::mock_userenv( { branchcode => $library->{branchcode} } ); +my $borrower = Koha::Patron->new( + { + firstname => 'my firstname', + surname => 'my surname', + categorycode => $patron_category->{categorycode}, + branchcode => $library->{branchcode}, + } +)->store; my $record = MARC::Record->new(); my ( $biblionumber, $biblioitemnumber ) = AddBiblio( $record, '' ); my $item = $builder->build_sample_item( { - biblionumber => $biblionumber, - library => $library->{branchcode}, - itype => $itemtype + biblionumber => $biblionumber, + library => $library->{branchcode}, + itype => $itemtype } ); -is ( IsItemIssued( $item->itemnumber ), 0, "item is not on loan at first" ); +is( IsItemIssued( $item->itemnumber ), 0, "item is not on loan at first" ); -AddIssue($borrower, $item->barcode); -is ( IsItemIssued( $item->itemnumber ), 1, "item is now on loan" ); +AddIssue( $borrower, $item->barcode ); +is( IsItemIssued( $item->itemnumber ), 1, "item is now on loan" ); is( - @{$item->safe_delete->messages}[0]->message, + @{ $item->safe_delete->messages }[0]->message, 'book_on_loan', 'item that is on loan cannot be deleted', ); -AddReturn($item->barcode, $library->{branchcode}); -is ( IsItemIssued( $item->itemnumber ), 0, "item has been returned" ); +AddReturn( $item->barcode, $library->{branchcode} ); +is( IsItemIssued( $item->itemnumber ), 0, "item has been returned" ); -$item->discard_changes; # FIXME We should not need that - # If we do not, $self->checkout in safe_to_delete will not know the item has been checked out +$item->discard_changes; # FIXME We should not need that + # If we do not, $self->checkout in safe_to_delete will not know the item has been checked out ok( $item->safe_delete, 'item that is not on loan can be deleted', diff --git a/t/db_dependent/Circulation/MarkIssueReturned.t b/t/db_dependent/Circulation/MarkIssueReturned.t index 7f76a40a61..7918a97187 100755 --- a/t/db_dependent/Circulation/MarkIssueReturned.t +++ b/t/db_dependent/Circulation/MarkIssueReturned.t @@ -32,7 +32,7 @@ use Koha::Old::Checkouts; use Koha::Patrons; use Koha::Patron::Debarments qw( AddUniqueDebarment ); -my $schema = Koha::Database->schema; +my $schema = Koha::Database->schema; my $builder = t::lib::TestBuilder->new; subtest 'Failure tests' => sub { @@ -41,10 +41,12 @@ subtest 'Failure tests' => sub { $schema->storage->txn_begin; - my $category = $builder->build_object( { class => 'Koha::Patron::Categories', value => { category_type => 'P', enrolmentfee => 0 } } ); - my $library = $builder->build_object( { class => 'Koha::Libraries' } ); - my $patron = $builder->build_object( - { class => 'Koha::Patrons', + my $category = $builder->build_object( + { class => 'Koha::Patron::Categories', value => { category_type => 'P', enrolmentfee => 0 } } ); + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); + my $patron = $builder->build_object( + { + class => 'Koha::Patrons', value => { branchcode => $library->branchcode, categorycode => $category->categorycode } } ); @@ -57,9 +59,10 @@ subtest 'Failure tests' => sub { t::lib::Mocks::mock_userenv( { branchcode => $library->branchcode } ); my ( $issue_id, $issue ); + # The next call will return undef for invalid item number eval { $issue_id = C4::Circulation::MarkIssueReturned( $patron->borrowernumber, 'invalid_itemnumber', undef, 0 ) }; - is( $@, '', 'No die triggered by invalid itemnumber' ); + is( $@, '', 'No die triggered by invalid itemnumber' ); is( $issue_id, undef, 'No issue_id returned' ); # In the next call we return the item and try it another time @@ -67,10 +70,9 @@ subtest 'Failure tests' => sub { eval { $issue_id = C4::Circulation::MarkIssueReturned( $patron->borrowernumber, $item->itemnumber, undef, 0 ) }; is( $issue_id, $issue->issue_id, "Item has been returned (issue $issue_id)" ); eval { $issue_id = C4::Circulation::MarkIssueReturned( $patron->borrowernumber, $item->itemnumber, undef, 0 ) }; - is( $@, '', 'No crash on returning item twice' ); + is( $@, '', 'No crash on returning item twice' ); is( $issue_id, undef, 'Cannot return an item twice' ); - $schema->storage->txn_rollback; }; @@ -80,10 +82,12 @@ subtest 'Anonymous patron tests' => sub { $schema->storage->txn_begin; - my $category = $builder->build_object( { class => 'Koha::Patron::Categories', value => { category_type => 'P', enrolmentfee => 0 } } ); - my $library = $builder->build_object( { class => 'Koha::Libraries' } ); - my $patron = $builder->build_object( - { class => 'Koha::Patrons', + my $category = $builder->build_object( + { class => 'Koha::Patron::Categories', value => { category_type => 'P', enrolmentfee => 0 } } ); + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); + my $patron = $builder->build_object( + { + class => 'Koha::Patrons', value => { branchcode => $library->branchcode, categorycode => $category->categorycode } } ); @@ -100,27 +104,28 @@ subtest 'Anonymous patron tests' => sub { my $issue = C4::Circulation::AddIssue( $patron, $item->barcode ); - throws_ok - { C4::Circulation::MarkIssueReturned( $patron->borrowernumber, $item->itemnumber, undef, 2 ); } - 'Koha::Exceptions::SysPref::NotSet', + throws_ok { C4::Circulation::MarkIssueReturned( $patron->borrowernumber, $item->itemnumber, undef, 2 ); } + 'Koha::Exceptions::SysPref::NotSet', 'AnonymousPatron not set causes an exception'; is( $@->syspref, 'AnonymousPatron', 'AnonymousPatron is not set - Fatal error on anonymization' ); Koha::Checkouts->find( $issue->issue_id )->delete; # Create a valid anonymous user - my $anonymous = $builder->build_object({ - class => 'Koha::Patrons', - value => { - categorycode => $category->categorycode, - branchcode => $library->branchcode + my $anonymous = $builder->build_object( + { + class => 'Koha::Patrons', + value => { + categorycode => $category->categorycode, + branchcode => $library->branchcode + } } - }); - t::lib::Mocks::mock_preference('AnonymousPatron', $anonymous->borrowernumber); + ); + t::lib::Mocks::mock_preference( 'AnonymousPatron', $anonymous->borrowernumber ); $issue = C4::Circulation::AddIssue( $patron, $item->barcode ); eval { C4::Circulation::MarkIssueReturned( $patron->borrowernumber, $item->itemnumber, undef, 2 ) }; - is ( $@, q||, 'AnonymousPatron is set correctly - no error expected'); + is( $@, q||, 'AnonymousPatron is set correctly - no error expected' ); $schema->storage->txn_rollback; }; @@ -131,10 +136,12 @@ subtest 'Manually pass a return date' => sub { $schema->storage->txn_begin; - my $category = $builder->build_object( { class => 'Koha::Patron::Categories', value => { category_type => 'P', enrolmentfee => 0 } } ); + my $category = $builder->build_object( + { class => 'Koha::Patron::Categories', value => { category_type => 'P', enrolmentfee => 0 } } ); my $library = $builder->build_object( { class => 'Koha::Libraries' } ); my $patron = $builder->build_object( - { class => 'Koha::Patrons', + { + class => 'Koha::Patrons', value => { branchcode => $library->branchcode, categorycode => $category->categorycode } } ); @@ -144,15 +151,15 @@ subtest 'Manually pass a return date' => sub { } ); - t::lib::Mocks::mock_userenv({ branchcode => $library->branchcode }); + t::lib::Mocks::mock_userenv( { branchcode => $library->branchcode } ); my ( $issue, $issue_id ); - $issue = C4::Circulation::AddIssue( $patron, $item->barcode ); + $issue = C4::Circulation::AddIssue( $patron, $item->barcode ); $issue_id = C4::Circulation::MarkIssueReturned( $patron->borrowernumber, $item->itemnumber, '2018-12-25', 0 ); is( $issue_id, $issue->issue_id, "Item has been returned" ); - my $old_checkout = Koha::Old::Checkouts->find( $issue_id ); + my $old_checkout = Koha::Old::Checkouts->find($issue_id); is( $old_checkout->returndate, '2018-12-25 00:00:00', 'Manually passed date stored correctly' ); $issue = C4::Circulation::AddIssue( $patron, $item->barcode ); @@ -162,9 +169,10 @@ subtest 'Manually pass a return date' => sub { # DBD::mysql::st execute failed: Incorrect datetime value: 'bad_date' for column 'returndate' local *STDERR; open STDERR, '>', '/dev/null'; - throws_ok - { $issue_id = C4::Circulation::MarkIssueReturned( $patron->borrowernumber, $item->itemnumber, 'bad_date', 0 ); } - 'Koha::Exceptions::Object::BadValue', + throws_ok { + $issue_id = C4::Circulation::MarkIssueReturned( $patron->borrowernumber, $item->itemnumber, 'bad_date', 0 ); + } + 'Koha::Exceptions::Object::BadValue', 'An exception is thrown on bad date'; close STDERR; } @@ -204,12 +212,9 @@ subtest 'AutoRemoveOverduesRestrictions' => sub { my $item_2 = $builder->build_sample_item; my $item_3 = $builder->build_sample_item; my $nine_days_ago = dt_from_string->subtract( days => 9 ); - my $checkout_1 = - AddIssue( $patron, $item_1->barcode, $nine_days_ago ); # overdue, but would not trigger debarment - my $checkout_2 = - AddIssue( $patron, $item_2->barcode, $nine_days_ago ); # overdue, but would not trigger debarment - my $checkout_3 = AddIssue( $patron, $item_3->barcode ); # not overdue - + my $checkout_1 = AddIssue( $patron, $item_1->barcode, $nine_days_ago ); # overdue, but would not trigger debarment + my $checkout_2 = AddIssue( $patron, $item_2->barcode, $nine_days_ago ); # overdue, but would not trigger debarment + my $checkout_3 = AddIssue( $patron, $item_3->barcode ); # not overdue Koha::Patron::Debarments::AddUniqueDebarment( { @@ -234,9 +239,8 @@ subtest 'AutoRemoveOverduesRestrictions' => sub { my $ten_days_ago = dt_from_string->subtract( days => 10 ); - $checkout_1 = AddIssue( $patron, $item_1->barcode, $ten_days_ago ); # overdue and would trigger debarment - $checkout_2 = - AddIssue( $patron, $item_2->barcode, $nine_days_ago ); # overdue, but would not trigger debarment + $checkout_1 = AddIssue( $patron, $item_1->barcode, $ten_days_ago ); # overdue and would trigger debarment + $checkout_2 = AddIssue( $patron, $item_2->barcode, $nine_days_ago ); # overdue, but would not trigger debarment Koha::Patron::Debarments::AddUniqueDebarment( { @@ -254,7 +258,7 @@ subtest 'AutoRemoveOverduesRestrictions' => sub { 'OVERDUES debarment is removed if remaining items would not result in patron debarment' ); - $checkout_1 = AddIssue( $patron, $item_1->barcode, $ten_days_ago ); # overdue and would trigger debarment + $checkout_1 = AddIssue( $patron, $item_1->barcode, $ten_days_ago ); # overdue and would trigger debarment Koha::Patron::Debarments::AddUniqueDebarment( { @@ -310,10 +314,12 @@ subtest 'Pass checkin_library to old_issues' => sub { $schema->storage->txn_begin; - my $category = $builder->build_object( { class => 'Koha::Patron::Categories', value => { category_type => 'P', enrolmentfee => 0 } } ); - my $library = $builder->build_object( { class => 'Koha::Libraries' } ); - my $patron = $builder->build_object( - { class => 'Koha::Patrons', + my $category = $builder->build_object( + { class => 'Koha::Patron::Categories', value => { category_type => 'P', enrolmentfee => 0 } } ); + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); + my $patron = $builder->build_object( + { + class => 'Koha::Patrons', value => { branchcode => $library->branchcode, categorycode => $category->categorycode } } ); @@ -325,12 +331,12 @@ subtest 'Pass checkin_library to old_issues' => sub { t::lib::Mocks::mock_userenv( { branchcode => $library->branchcode } ); - my $issue = C4::Circulation::AddIssue( $patron, $item->barcode ); + my $issue = C4::Circulation::AddIssue( $patron, $item->barcode ); my $issue_id = C4::Circulation::MarkIssueReturned( $patron->borrowernumber, $item->itemnumber ); is( $issue_id, $issue->issue_id, 'Item has been returned' ); - my $old_issue = Koha::Old::Checkouts->find( $issue_id ); + my $old_issue = Koha::Old::Checkouts->find($issue_id); is( $old_issue->checkin_library, $library->branchcode, 'Return branch is passed correctly' ); - $schema->storage->txn_rollback + $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/Circulation/NoIssuesChargeGuarantees.t b/t/db_dependent/Circulation/NoIssuesChargeGuarantees.t index f3d51fc91f..fb9c0a070d 100755 --- a/t/db_dependent/Circulation/NoIssuesChargeGuarantees.t +++ b/t/db_dependent/Circulation/NoIssuesChargeGuarantees.t @@ -74,13 +74,13 @@ my $r = $builder->build_object( ); t::lib::Mocks::mock_preference( 'NoIssuesChargeGuarantees', '5.00' ); -t::lib::Mocks::mock_preference( 'AllowFineOverride', '' ); +t::lib::Mocks::mock_preference( 'AllowFineOverride', '' ); my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode ); is( $issuingimpossible->{DEBT_GUARANTEES}, undef, "Patron can check out item" ); my $account = Koha::Account->new( { patron_id => $guarantee->id } ); -$account->add_debit({ amount => 10.00, type => 'LOST', interface => 'test' }); +$account->add_debit( { amount => 10.00, type => 'LOST', interface => 'test' } ); ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode ); is( $issuingimpossible->{DEBT_GUARANTEES} + 0, '10.00' + 0, "Patron cannot check out item due to debt for guarantee" ); @@ -91,13 +91,13 @@ is( "Patron can check out item as the patron category limit is now higher than 10" ); -my $accountline = Koha::Account::Lines->search({ borrowernumber => $guarantee->id })->next(); -is( $accountline->amountoutstanding+0, 10, "Found 10.00 amount outstanding" ); -is( $accountline->debit_type_code, "LOST", "Debit type is LOST" ); +my $accountline = Koha::Account::Lines->search( { borrowernumber => $guarantee->id } )->next(); +is( $accountline->amountoutstanding + 0, 10, "Found 10.00 amount outstanding" ); +is( $accountline->debit_type_code, "LOST", "Debit type is LOST" ); -my $offset = Koha::Account::Offsets->search({ debit_id => $accountline->id })->next(); -is( $offset->type, 'CREATE', 'Got CREATE offset type' ); -is( $offset->amount+0, 10, 'Got amount of $10.00' ); +my $offset = Koha::Account::Offsets->search( { debit_id => $accountline->id } )->next(); +is( $offset->type, 'CREATE', 'Got CREATE offset type' ); +is( $offset->amount + 0, 10, 'Got amount of $10.00' ); $schema->storage->txn_rollback; diff --git a/t/db_dependent/Circulation/OfflineCirculation.t b/t/db_dependent/Circulation/OfflineCirculation.t index 9aec60fb19..b20c0840a1 100755 --- a/t/db_dependent/Circulation/OfflineCirculation.t +++ b/t/db_dependent/Circulation/OfflineCirculation.t @@ -24,10 +24,10 @@ use Test::Warn; use t::lib::Mocks; use t::lib::TestBuilder; -use C4::Biblio qw( AddBiblio ); +use C4::Biblio qw( AddBiblio ); use C4::Circulation qw( AddOfflineOperation ProcessOfflineOperation GetOfflineOperation ProcessOfflineIssue ); use C4::Context; -use C4::Reserves qw( AddReserve ); +use C4::Reserves qw( AddReserve ); use Koha::DateUtils qw( dt_from_string ); use MARC::Record; diff --git a/t/db_dependent/Circulation/OfflineOperation.t b/t/db_dependent/Circulation/OfflineOperation.t index 867ce700a1..ba903477ca 100755 --- a/t/db_dependent/Circulation/OfflineOperation.t +++ b/t/db_dependent/Circulation/OfflineOperation.t @@ -10,16 +10,19 @@ use Koha::Library; use Test::More tests => 7; BEGIN { - use_ok('C4::Circulation', qw( AddOfflineOperation GetOfflineOperation GetOfflineOperations DeleteOfflineOperation )); + use_ok( + 'C4::Circulation', + qw( AddOfflineOperation GetOfflineOperation GetOfflineOperations DeleteOfflineOperation ) + ); } can_ok( 'C4::Circulation', qw( - AddOfflineOperation - GetOfflineOperation - GetOfflineOperations - DeleteOfflineOperation - ) + AddOfflineOperation + GetOfflineOperation + GetOfflineOperations + DeleteOfflineOperation + ) ); my $schema = Koha::Database->new->schema; @@ -58,13 +61,12 @@ my $now = dt_from_string->truncate( to => 'minute' ); is( AddOfflineOperation( 'User1', $samplebranch1->{branchcode}, - $now, 'Action1', 'CODE', 'Cardnumber1', 10 + $now, 'Action1', 'CODE', 'Cardnumber1', 10 ), 'Added.', "OfflineOperation has been added" ); -my $offline_id = - $dbh->last_insert_id( undef, undef, 'pending_offline_operations', undef ); +my $offline_id = $dbh->last_insert_id( undef, undef, 'pending_offline_operations', undef ); #Test GetOfflineOperations is_deeply( @@ -73,27 +75,34 @@ is_deeply( operationid => $offline_id, userid => 'User1', branchcode => $samplebranch1->{branchcode}, + # FIXME sounds like we need a 'timestamp' dateformat - timestamp => output_pref({ dt => $now, dateformat => 'iso', dateonly => 0 }) . ':00', - action => 'Action1', - barcode => 'CODE', - cardnumber => 'Cardnumber1', - amount => '10.000000' + timestamp => output_pref( { dt => $now, dateformat => 'iso', dateonly => 0 } ) . ':00', + action => 'Action1', + barcode => 'CODE', + cardnumber => 'Cardnumber1', + amount => '10.000000' }, "GetOffline returns offlineoperation's informations" ); -is( GetOfflineOperation(), undef, - 'GetOfflineOperation without parameters returns undef' ); -is( GetOfflineOperation(-1), undef, - 'GetOfflineOperation with wrong parameters returns undef' ); +is( + GetOfflineOperation(), undef, + 'GetOfflineOperation without parameters returns undef' +); +is( + GetOfflineOperation(-1), undef, + 'GetOfflineOperation with wrong parameters returns undef' +); #Test GetOfflineOperations #TODO later: test GetOfflineOperations # Actually we cannot mock C4::Context->userenv in unit tests #Test DeleteOfflineOperation -is( DeleteOfflineOperation($offline_id), - 'Deleted.', 'Offlineoperation has been deleted' ); +is( + DeleteOfflineOperation($offline_id), + 'Deleted.', 'Offlineoperation has been deleted' +); #is (DeleteOfflineOperation(), undef, 'DeleteOfflineOperation without id returns undef'); #is (DeleteOfflineOperation(-1),undef, 'DeleteOfflineOperation with a wrong id returns undef');#FIXME diff --git a/t/db_dependent/Circulation/ReturnClaims.t b/t/db_dependent/Circulation/ReturnClaims.t index e1b4409f6e..96c2a05e96 100755 --- a/t/db_dependent/Circulation/ReturnClaims.t +++ b/t/db_dependent/Circulation/ReturnClaims.t @@ -61,9 +61,9 @@ $branch = $builder->build( { source => 'Branch' } )->{branchcode}; subtest 'Test Koha::Checkout::claim_returned, do not mark as returned' => sub { plan tests => 7; - t::lib::Mocks::mock_preference( 'ClaimReturnedLostValue', 1 ); + t::lib::Mocks::mock_preference( 'ClaimReturnedLostValue', 1 ); t::lib::Mocks::mock_preference( 'MarkLostItemsAsReturned', q{} ); - my $item = $builder->build_sample_item; + my $item = $builder->build_sample_item; my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $checkout = AddIssue( $patron, $item->barcode ); @@ -74,22 +74,22 @@ subtest 'Test Koha::Checkout::claim_returned, do not mark as returned' => sub { } ); - is( $claim->issue_id, $checkout->id, "Claim issue id matches" ); - is( $claim->itemnumber, $item->id, "Claim itemnumber matches" ); - is( $claim->borrowernumber, $patron->id, "Claim borrowernumber matches" ); - is( $claim->notes, "Test note", "Claim notes match" ); - is( $claim->created_by, $patron->id, "Claim created_by matches" ); + is( $claim->issue_id, $checkout->id, "Claim issue id matches" ); + is( $claim->itemnumber, $item->id, "Claim itemnumber matches" ); + is( $claim->borrowernumber, $patron->id, "Claim borrowernumber matches" ); + is( $claim->notes, "Test note", "Claim notes match" ); + is( $claim->created_by, $patron->id, "Claim created_by matches" ); ok( $claim->created_on, "Claim created_on is set" ); my $checkout2 = Koha::Checkouts->find( $checkout->id ); - is( $checkout2->id, $checkout->id, "Item is still checked out to patron") + is( $checkout2->id, $checkout->id, "Item is still checked out to patron" ); }; subtest 'Test Koha::Patronn::return_claims' => sub { plan tests => 7; t::lib::Mocks::mock_preference( 'ClaimReturnedLostValue', 1 ); - my $item = $builder->build_sample_item; + my $item = $builder->build_sample_item; my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $checkout = AddIssue( $patron, $item->barcode ); @@ -106,18 +106,18 @@ subtest 'Test Koha::Patronn::return_claims' => sub { my $claim = $claims->next; - is( $claim->issue_id, $checkout->id, "Claim issue id matches" ); - is( $claim->itemnumber, $item->id, "Claim itemnumber matches" ); - is( $claim->borrowernumber, $patron->id, "Claim borrowernumber matches" ); - is( $claim->notes, "Test note", "Claim notes match" ); - is( $claim->created_by, $patron->id, "Claim created_by matches" ); + is( $claim->issue_id, $checkout->id, "Claim issue id matches" ); + is( $claim->itemnumber, $item->id, "Claim itemnumber matches" ); + is( $claim->borrowernumber, $patron->id, "Claim borrowernumber matches" ); + is( $claim->notes, "Test note", "Claim notes match" ); + is( $claim->created_by, $patron->id, "Claim created_by matches" ); ok( $claim->created_on, "Claim created_on is set" ); }; subtest 'Test Koha::Checkout::claim_returned, mark as returned' => sub { plan tests => 8; - t::lib::Mocks::mock_preference( 'ClaimReturnedLostValue', 1 ); + t::lib::Mocks::mock_preference( 'ClaimReturnedLostValue', 1 ); t::lib::Mocks::mock_preference( 'MarkLostItemsAsReturned', q{claim_returned} ); my $item = $builder->build_sample_item; my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); @@ -130,17 +130,17 @@ subtest 'Test Koha::Checkout::claim_returned, mark as returned' => sub { } ); - is( $claim->issue_id, $checkout->id, "Claim issue id matches" ); - is( $claim->itemnumber, $item->id, "Claim itemnumber matches" ); - is( $claim->borrowernumber, $patron->id, "Claim borrowernumber matches" ); - is( $claim->notes, "Test note", "Claim notes match" ); - is( $claim->created_by, $patron->id, "Claim created_by matches" ); + is( $claim->issue_id, $checkout->id, "Claim issue id matches" ); + is( $claim->itemnumber, $item->id, "Claim itemnumber matches" ); + is( $claim->borrowernumber, $patron->id, "Claim borrowernumber matches" ); + is( $claim->notes, "Test note", "Claim notes match" ); + is( $claim->created_by, $patron->id, "Claim created_by matches" ); ok( $claim->created_on, "Claim created_on is set" ); my $checkout2 = Koha::Checkouts->find( $checkout->id ); - is( $checkout2, undef, "Checkout is not longer in the issues table"); + is( $checkout2, undef, "Checkout is not longer in the issues table" ); $checkout2 = Koha::Old::Checkouts->find( $checkout->id ); - is( $checkout2->id, $checkout->id, "Checkout was found in the old_issues table"); + is( $checkout2->id, $checkout->id, "Checkout was found in the old_issues table" ); }; subtest 'Test Koha::Checkout::claim_returned, should refund a previous lost fee if refund_lost_fee is set' => sub { diff --git a/t/db_dependent/Circulation/Returns.t b/t/db_dependent/Circulation/Returns.t index e11fe4d001..4382ff69a0 100755 --- a/t/db_dependent/Circulation/Returns.t +++ b/t/db_dependent/Circulation/Returns.t @@ -76,33 +76,39 @@ subtest "AddReturn logging on statistics table (item-level_itypes=1)" => sub { t::lib::Mocks::mock_preference( "item-level_itypes", 1 ); # Make sure logging is enabled - t::lib::Mocks::mock_preference( "IssueLog", 1 ); + t::lib::Mocks::mock_preference( "IssueLog", 1 ); t::lib::Mocks::mock_preference( "ReturnLog", 1 ); # Create an itemtype for biblio-level item type - my $blevel_itemtype = $builder->build({ source => 'Itemtype' })->{ itemtype }; + my $blevel_itemtype = $builder->build( { source => 'Itemtype' } )->{itemtype}; + # Create an itemtype for item-level item type - my $ilevel_itemtype = $builder->build({ source => 'Itemtype' })->{ itemtype }; + my $ilevel_itemtype = $builder->build( { source => 'Itemtype' } )->{itemtype}; + # Create a branch - $branch = $builder->build({ source => 'Branch' })->{ branchcode }; + $branch = $builder->build( { source => 'Branch' } )->{branchcode}; + # Create a borrower - my $patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { branchcode => $branch } - }); + my $patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { branchcode => $branch } + } + ); + # Look for the defined MARC field for biblio-level itemtype - my $rs = $schema->resultset('MarcSubfieldStructure')->search({ - frameworkcode => '', - kohafield => 'biblioitems.itemtype' - }); + my $rs = $schema->resultset('MarcSubfieldStructure')->search( + { + frameworkcode => '', + kohafield => 'biblioitems.itemtype' + } + ); my $tagfield = $rs->first->tagfield; my $tagsubfield = $rs->first->tagsubfield; # Create a biblio record with biblio-level itemtype my $record = MARC::Record->new(); - $record->append_fields( - MARC::Field->new($tagfield,'','', $tagsubfield => $blevel_itemtype ) - ); + $record->append_fields( MARC::Field->new( $tagfield, '', '', $tagsubfield => $blevel_itemtype ) ); my ( $biblionumber, $biblioitemnumber ) = AddBiblio( $record, '' ); my $item_with_itemtype = $builder->build_sample_item( { @@ -116,34 +122,48 @@ subtest "AddReturn logging on statistics table (item-level_itypes=1)" => sub { biblionumber => $biblionumber, library => $branch, } - )->_result->update({ itype => undef }); + )->_result->update( { itype => undef } ); AddIssue( $patron, $item_with_itemtype->barcode ); AddReturn( $item_with_itemtype->barcode, $branch ); + # Test item-level itemtype was recorded on the 'statistics' table - my $stat = $schema->resultset('Statistic')->search({ - branch => $branch, - type => 'return', - itemnumber => $item_with_itemtype->itemnumber - }, { order_by => { -asc => 'datetime' } })->next(); + my $stat = $schema->resultset('Statistic')->search( + { + branch => $branch, + type => 'return', + itemnumber => $item_with_itemtype->itemnumber + }, + { order_by => { -asc => 'datetime' } } + )->next(); - is( $stat->itemtype, $ilevel_itemtype, - "item-level itype recorded on statistics for return"); + is( + $stat->itemtype, $ilevel_itemtype, + "item-level itype recorded on statistics for return" + ); warning_like { AddIssue( $patron, $item_without_itemtype->barcode ) } - [qr/^item-level_itypes set but no itemtype set for item/, - qr/^item-level_itypes set but no itemtype set for item/, - qr/^item-level_itypes set but no itemtype set for item/], - 'Item without itemtype set raises warning on AddIssue'; + [ + qr/^item-level_itypes set but no itemtype set for item/, + qr/^item-level_itypes set but no itemtype set for item/, + qr/^item-level_itypes set but no itemtype set for item/ + ], + 'Item without itemtype set raises warning on AddIssue'; AddReturn( $item_without_itemtype->barcode, $branch ); - # Test biblio-level itemtype was recorded on the 'statistics' table - $stat = $schema->resultset('Statistic')->search({ - branch => $branch, - type => 'return', - itemnumber => $item_without_itemtype->itemnumber - }, { order_by => { -asc => 'datetime' } })->next(); - is( $stat->itemtype, $blevel_itemtype, - "biblio-level itype recorded on statistics for return as a fallback for null item-level itype"); + # Test biblio-level itemtype was recorded on the 'statistics' table + $stat = $schema->resultset('Statistic')->search( + { + branch => $branch, + type => 'return', + itemnumber => $item_without_itemtype->itemnumber + }, + { order_by => { -asc => 'datetime' } } + )->next(); + + is( + $stat->itemtype, $blevel_itemtype, + "biblio-level itype recorded on statistics for return as a fallback for null item-level itype" + ); }; @@ -152,36 +172,42 @@ subtest "AddReturn logging on statistics table (item-level_itypes=0)" => sub { plan tests => 2; # Make sure logging is enabled - t::lib::Mocks::mock_preference( "IssueLog", 1 ); + t::lib::Mocks::mock_preference( "IssueLog", 1 ); t::lib::Mocks::mock_preference( "ReturnLog", 1 ); # Set biblio level item types t::lib::Mocks::mock_preference( "item-level_itypes", 0 ); # Create an itemtype for biblio-level item type - my $blevel_itemtype = $builder->build({ source => 'Itemtype' })->{ itemtype }; + my $blevel_itemtype = $builder->build( { source => 'Itemtype' } )->{itemtype}; + # Create an itemtype for item-level item type - my $ilevel_itemtype = $builder->build({ source => 'Itemtype' })->{ itemtype }; + my $ilevel_itemtype = $builder->build( { source => 'Itemtype' } )->{itemtype}; + # Create a branch - $branch = $builder->build({ source => 'Branch' })->{ branchcode }; + $branch = $builder->build( { source => 'Branch' } )->{branchcode}; + # Create a borrower - my $patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { branchcode => $branch } - })->{ borrowernumber }; + my $patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { branchcode => $branch } + } + )->{borrowernumber}; + # Look for the defined MARC field for biblio-level itemtype - my $rs = $schema->resultset('MarcSubfieldStructure')->search({ - frameworkcode => '', - kohafield => 'biblioitems.itemtype' - }); + my $rs = $schema->resultset('MarcSubfieldStructure')->search( + { + frameworkcode => '', + kohafield => 'biblioitems.itemtype' + } + ); my $tagfield = $rs->first->tagfield; my $tagsubfield = $rs->first->tagsubfield; # Create a biblio record with biblio-level itemtype my $record = MARC::Record->new(); - $record->append_fields( - MARC::Field->new($tagfield,'','', $tagsubfield => $blevel_itemtype ) - ); + $record->append_fields( MARC::Field->new( $tagfield, '', '', $tagsubfield => $blevel_itemtype ) ); my ( $biblionumber, $biblioitemnumber ) = AddBiblio( $record, '' ); my $item_with_itemtype = $builder->build_sample_item( { @@ -200,35 +226,47 @@ subtest "AddReturn logging on statistics table (item-level_itypes=0)" => sub { AddIssue( $patron, $item_with_itemtype->barcode ); AddReturn( $item_with_itemtype->barcode, $branch ); - # Test item-level itemtype was recorded on the 'statistics' table - my $stat = $schema->resultset('Statistic')->search({ - branch => $branch, - type => 'return', - itemnumber => $item_with_itemtype->itemnumber - }, { order_by => { -asc => 'datetime' } })->next(); - is( $stat->itemtype, $blevel_itemtype, - "biblio-level itype recorded on statistics for return"); + # Test item-level itemtype was recorded on the 'statistics' table + my $stat = $schema->resultset('Statistic')->search( + { + branch => $branch, + type => 'return', + itemnumber => $item_with_itemtype->itemnumber + }, + { order_by => { -asc => 'datetime' } } + )->next(); + + is( + $stat->itemtype, $blevel_itemtype, + "biblio-level itype recorded on statistics for return" + ); AddIssue( $patron, $item_without_itemtype->barcode ); AddReturn( $item_without_itemtype->barcode, $branch ); - # Test biblio-level itemtype was recorded on the 'statistics' table - $stat = $schema->resultset('Statistic')->search({ - branch => $branch, - type => 'return', - itemnumber => $item_without_itemtype->itemnumber - }, { order_by => { -asc => 'datetime' } })->next(); - is( $stat->itemtype, $blevel_itemtype, - "biblio-level itype recorded on statistics for return"); + # Test biblio-level itemtype was recorded on the 'statistics' table + $stat = $schema->resultset('Statistic')->search( + { + branch => $branch, + type => 'return', + itemnumber => $item_without_itemtype->itemnumber + }, + { order_by => { -asc => 'datetime' } } + )->next(); + + is( + $stat->itemtype, $blevel_itemtype, + "biblio-level itype recorded on statistics for return" + ); }; subtest 'Handle ids duplication' => sub { plan tests => 8; - t::lib::Mocks::mock_preference( 'item-level_itypes', 1 ); + t::lib::Mocks::mock_preference( 'item-level_itypes', 1 ); t::lib::Mocks::mock_preference( 'CalculateFinesOnReturn', 1 ); - t::lib::Mocks::mock_preference( 'finesMode', 'production' ); + t::lib::Mocks::mock_preference( 'finesMode', 'production' ); Koha::CirculationRules->set_rules( { categorycode => undef, @@ -243,102 +281,105 @@ subtest 'Handle ids duplication' => sub { ); my $itemtype = $builder->build( { source => 'Itemtype', value => { rentalcharge => 5 } } ); - my $item = $builder->build_sample_item( + my $item = $builder->build_sample_item( { itype => $itemtype->{itemtype}, } ); - my $patron = $builder->build_object( - { class => 'Koha::Patrons'} - ); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $original_checkout = AddIssue( $patron, $item->barcode, dt_from_string->subtract( days => 50 ) ); - my $issue_id = $original_checkout->issue_id; - my $account_lines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber, issue_id => $issue_id }); - is( $account_lines->count, 1, '1 account line should exist for this issue_id' ); + my $issue_id = $original_checkout->issue_id; + my $account_lines = + Koha::Account::Lines->search( { borrowernumber => $patron->borrowernumber, issue_id => $issue_id } ); + is( $account_lines->count, 1, '1 account line should exist for this issue_id' ); is( $account_lines->next->debit_type_code, 'RENT', 'patron has been charged the rentalcharge' ); $account_lines->delete; # Create an existing entry in old_issue - $builder->build({ source => 'OldIssue', value => { issue_id => $issue_id } }); + $builder->build( { source => 'OldIssue', value => { issue_id => $issue_id } } ); - my $old_checkout = Koha::Old::Checkouts->find( $issue_id ); + my $old_checkout = Koha::Old::Checkouts->find($issue_id); - my ($doreturn, $messages, $new_checkout, $borrower); + my ( $doreturn, $messages, $new_checkout, $borrower ); warning_like { ( $doreturn, $messages, $new_checkout, $borrower ) = - AddReturn( $item->barcode, undef, undef, undef, dt_from_string ); + AddReturn( $item->barcode, undef, undef, undef, dt_from_string ); } [ qr{.*DBD::mysql::st execute failed: Duplicate entry.*}, { carped => qr{The checkin for the following issue failed.*Duplicate ID.*} } ], - 'DBD should have raised an error about dup primary key'; + 'DBD should have raised an error about dup primary key'; - is( $doreturn, 0, 'Return should not have been done' ); - is( $messages->{WasReturned}, 0, 'messages should have the WasReturned flag set to 0' ); + is( $doreturn, 0, 'Return should not have been done' ); + is( $messages->{WasReturned}, 0, 'messages should have the WasReturned flag set to 0' ); is( $messages->{DataCorrupted}, 1, 'messages should have the DataCorrupted flag set to 1' ); - $account_lines = Koha::Account::Lines->search({ borrowernumber => $borrower->{borrowernumber}, issue_id => $issue_id }); - is( $account_lines->count, 0, 'No account lines should exist for this issue_id, patron should not have been charged' ); + $account_lines = + Koha::Account::Lines->search( { borrowernumber => $borrower->{borrowernumber}, issue_id => $issue_id } ); + is( + $account_lines->count, 0, + 'No account lines should exist for this issue_id, patron should not have been charged' + ); - is( Koha::Checkouts->find( $issue_id )->issue_id, $issue_id, 'The issues entry should not have been removed' ); + is( Koha::Checkouts->find($issue_id)->issue_id, $issue_id, 'The issues entry should not have been removed' ); }; subtest 'BlockReturnOfLostItems' => sub { plan tests => 5; - my $item = $builder->build_sample_item; - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $item = $builder->build_sample_item; + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $checkout = AddIssue( $patron, $item->barcode ); # Mark the item as lost $item->itemlost(1)->store; - t::lib::Mocks::mock_preference('BlockReturnOfLostItems', 1); - my ( $doreturn, $messages, $issue ) = AddReturn($item->barcode); - is( $doreturn, 0, "With BlockReturnOfLostItems, a checkin of a lost item should be blocked"); - is( $messages->{WasLost}, 1, "... and the WasLost flag should be set"); + t::lib::Mocks::mock_preference( 'BlockReturnOfLostItems', 1 ); + my ( $doreturn, $messages, $issue ) = AddReturn( $item->barcode ); + is( $doreturn, 0, "With BlockReturnOfLostItems, a checkin of a lost item should be blocked" ); + is( $messages->{WasLost}, 1, "... and the WasLost flag should be set" ); is( $messages->{NeedsTransfer}, undef, "... and no transfer should be triggered" ); $item->discard_changes; is( $item->itemlost, 1, "Item remains lost" ); - t::lib::Mocks::mock_preference('BlockReturnOfLostItems', 0); - ( $doreturn, $messages, $issue ) = AddReturn($item->barcode); - is( $doreturn, 1, "Without BlockReturnOfLostItems, a checkin of a lost item should not be blocked"); + t::lib::Mocks::mock_preference( 'BlockReturnOfLostItems', 0 ); + ( $doreturn, $messages, $issue ) = AddReturn( $item->barcode ); + is( $doreturn, 1, "Without BlockReturnOfLostItems, a checkin of a lost item should not be blocked" ); }; subtest 'Checkin of an item claimed as returned should generate a message' => sub { plan tests => 1; - t::lib::Mocks::mock_preference('ClaimReturnedLostValue', 1); - my $item = $builder->build_sample_item; - my $patron = $builder->build_object({class => 'Koha::Patrons'}); + t::lib::Mocks::mock_preference( 'ClaimReturnedLostValue', 1 ); + my $item = $builder->build_sample_item; + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $checkout = AddIssue( $patron, $item->barcode ); - $checkout->claim_returned({ created_by => $patron->id }); + $checkout->claim_returned( { created_by => $patron->id } ); - my ( $doreturn, $messages, $issue ) = AddReturn($item->barcode); + my ( $doreturn, $messages, $issue ) = AddReturn( $item->barcode ); ok( $messages->{ReturnClaims}, "ReturnClaims is in messages for return of a claimed as returned itm" ); }; subtest 'BranchTransferLimitsType' => sub { plan tests => 2; - t::lib::Mocks::mock_preference('AutomaticItemReturn', 0); - t::lib::Mocks::mock_preference('UseBranchTransferLimits', 1); - t::lib::Mocks::mock_preference('BranchTransferLimitsType', 'ccode'); + t::lib::Mocks::mock_preference( 'AutomaticItemReturn', 0 ); + t::lib::Mocks::mock_preference( 'UseBranchTransferLimits', 1 ); + t::lib::Mocks::mock_preference( 'BranchTransferLimitsType', 'ccode' ); - my $item = $builder->build_sample_item; - my $patron = $builder->build_object({class => 'Koha::Patrons'}); + my $item = $builder->build_sample_item; + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $checkout = AddIssue( $patron, $item->barcode ); - my ( $doreturn, $messages, $issue ) = AddReturn($item->barcode); - is( $doreturn, 1, 'AddReturn should have checkin the item if BranchTransferLimitsType=ccode'); + my ( $doreturn, $messages, $issue ) = AddReturn( $item->barcode ); + is( $doreturn, 1, 'AddReturn should have checkin the item if BranchTransferLimitsType=ccode' ); - t::lib::Mocks::mock_preference('BranchTransferLimitsType', 'itemtype'); + t::lib::Mocks::mock_preference( 'BranchTransferLimitsType', 'itemtype' ); $checkout = AddIssue( $patron, $item->barcode ); - ( $doreturn, $messages, $issue ) = AddReturn($item->barcode); - is( $doreturn, 1, 'AddReturn should have checkin the item if BranchTransferLimitsType=itemtype'); + ( $doreturn, $messages, $issue ) = AddReturn( $item->barcode ); + is( $doreturn, 1, 'AddReturn should have checkin the item if BranchTransferLimitsType=itemtype' ); }; subtest 'Backdated returns should reduce fine if needed' => sub { @@ -347,30 +388,32 @@ subtest 'Backdated returns should reduce fine if needed' => sub { t::lib::Mocks::mock_preference( "CalculateFinesOnReturn", 0 ); t::lib::Mocks::mock_preference( "CalculateFinesOnBackdate", 1 ); - my $biblio = $builder->build_object( { class => 'Koha::Biblios' } ); - my $item = $builder->build_sample_item; - my $patron = $builder->build_object({class => 'Koha::Patrons'}); + my $biblio = $builder->build_object( { class => 'Koha::Biblios' } ); + my $item = $builder->build_sample_item; + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $checkout = AddIssue( $patron, $item->barcode ); - my $fine = Koha::Account::Line->new({ - issue_id => $checkout->id, - borrowernumber => $patron->id, - itemnumber => $item->id, - date => dt_from_string(), - amount => 100, - amountoutstanding => 100, - debit_type_code => 'OVERDUE', - status => 'UNRETURNED', - timestamp => dt_from_string(), - manager_id => undef, - interface => 'cli', - branchcode => $patron->branchcode, - })->store(); + my $fine = Koha::Account::Line->new( + { + issue_id => $checkout->id, + borrowernumber => $patron->id, + itemnumber => $item->id, + date => dt_from_string(), + amount => 100, + amountoutstanding => 100, + debit_type_code => 'OVERDUE', + status => 'UNRETURNED', + timestamp => dt_from_string(), + manager_id => undef, + interface => 'cli', + branchcode => $patron->branchcode, + } + )->store(); my $account = $patron->account; - is( $account->balance+0, 100, "Account balance before return is 100"); + is( $account->balance + 0, 100, "Account balance before return is 100" ); - my ( $doreturn, $messages, $issue ) = AddReturn($item->barcode, undef, undef, dt_from_string('1999-01-01') ); - is( $account->balance+0, 0, "Account balance after return is 0"); + my ( $doreturn, $messages, $issue ) = AddReturn( $item->barcode, undef, undef, dt_from_string('1999-01-01') ); + is( $account->balance + 0, 0, "Account balance after return is 0" ); $fine = $fine->get_from_storage; is( $fine, undef, "Fine was removed correctly with a backdated return" ); diff --git a/t/db_dependent/Circulation/StoreLastBorrower.t b/t/db_dependent/Circulation/StoreLastBorrower.t index c4c7f37a22..8c81503765 100755 --- a/t/db_dependent/Circulation/StoreLastBorrower.t +++ b/t/db_dependent/Circulation/StoreLastBorrower.t @@ -28,7 +28,7 @@ use Koha::Items; use t::lib::Mocks; use t::lib::TestBuilder; -my $schema = Koha::Database->new->schema; +my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; my $builder = t::lib::TestBuilder->new; @@ -64,9 +64,10 @@ subtest 'Test StoreLastBorrower' => sub { my $patron_object = $item->last_returned_by(); is( $patron_object, undef, 'Koha::Item::last_returned_by returned undef' ); - my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->barcode, $patron->{branchcode}, undef, dt_from_string('2010-10-10') ); + my ( $returned, undef, undef ) = + C4::Circulation::AddReturn( $item->barcode, $patron->{branchcode}, undef, dt_from_string('2010-10-10') ); - $item = $item->get_from_storage; + $item = $item->get_from_storage; $patron_object = $item->last_returned_by(); is( ref($patron_object), 'Koha::Patron', 'Koha::Item::last_returned_by returned Koha::Patron' ); @@ -87,9 +88,10 @@ subtest 'Test StoreLastBorrower' => sub { } ); - ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->barcode, $patron->{branchcode}, undef, dt_from_string('2010-10-10') ); + ( $returned, undef, undef ) = + C4::Circulation::AddReturn( $item->barcode, $patron->{branchcode}, undef, dt_from_string('2010-10-10') ); - $item = $item->get_from_storage; + $item = $item->get_from_storage; $patron_object = $item->last_returned_by(); is( $patron_object->id, $patron->{borrowernumber}, 'Second patron to return item replaces the first' ); @@ -101,15 +103,20 @@ subtest 'Test StoreLastBorrower' => sub { ); $patron_object = Koha::Patrons->find( $patron->{borrowernumber} ); - $item->last_returned_by($patron_object->borrowernumber); + $item->last_returned_by( $patron_object->borrowernumber ); $item = $item->get_from_storage; my $patron_object2 = $item->last_returned_by(); - is( $patron_object->id, $patron_object2->id, - 'Calling last_returned_by with Borrower object sets last_returned_by to that borrower' ); + is( + $patron_object->id, $patron_object2->id, + 'Calling last_returned_by with Borrower object sets last_returned_by to that borrower' + ); $patron_object->delete; $item = $item->get_from_storage; - is( $item->last_returned_by, undef, 'last_returned_by should return undef if the last patron to return the item has been deleted' ); + is( + $item->last_returned_by, undef, + 'last_returned_by should return undef if the last patron to return the item has been deleted' + ); t::lib::Mocks::mock_preference( 'StoreLastBorrower', '0' ); $patron = $builder->build( @@ -128,7 +135,8 @@ subtest 'Test StoreLastBorrower' => sub { }, } ); - ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->barcode, $patron->{branchcode}, undef, dt_from_string('2010-10-10') ); + ( $returned, undef, undef ) = + C4::Circulation::AddReturn( $item->barcode, $patron->{branchcode}, undef, dt_from_string('2010-10-10') ); $item = $item->get_from_storage; is( $item->last_returned_by, undef, 'Last patron to return item should not be stored if StoreLastBorrower if off' ); diff --git a/t/db_dependent/Circulation/SwitchOnSiteCheckouts.t b/t/db_dependent/Circulation/SwitchOnSiteCheckouts.t index e0aafb3868..ccc400684f 100755 --- a/t/db_dependent/Circulation/SwitchOnSiteCheckouts.t +++ b/t/db_dependent/Circulation/SwitchOnSiteCheckouts.t @@ -42,19 +42,24 @@ $dbh->do(q|DELETE FROM circulation_rules|); my $builder = t::lib::TestBuilder->new(); -my $branch = $builder->build({ - source => 'Branch', -}); +my $branch = $builder->build( + { + source => 'Branch', + } +); -my $patron_category = $builder->build({ source => 'Category', value => { categorycode => 'NOT_X', category_type => 'P', enrolmentfee => 0 } }); -my $patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { - branchcode => $branch->{branchcode}, - debarred => undef, - categorycode => $patron_category->{categorycode}, - }, -}); +my $patron_category = $builder->build( + { source => 'Category', value => { categorycode => 'NOT_X', category_type => 'P', enrolmentfee => 0 } } ); +my $patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { + branchcode => $branch->{branchcode}, + debarred => undef, + categorycode => $patron_category->{categorycode}, + }, + } +); my $item = $builder->build_sample_item( { @@ -69,40 +74,46 @@ Koha::CirculationRules->set_rules( categorycode => undef, itemtype => undef, rules => { - maxissueqty => 2, - maxonsiteissueqty => 1, - lengthunit => 'days', - issuelength => 5, + maxissueqty => 2, + maxonsiteissueqty => 1, + lengthunit => 'days', + issuelength => 5, hardduedate => undef, hardduedatecompare => 0, } } ); -t::lib::Mocks::mock_userenv({ patron => $patron }); +t::lib::Mocks::mock_userenv( { patron => $patron } ); -t::lib::Mocks::mock_preference('AllowTooManyOverride', 0); +t::lib::Mocks::mock_preference( 'AllowTooManyOverride', 0 ); # Add onsite checkout -C4::Circulation::AddIssue( $patron, $item->barcode, dt_from_string, undef, dt_from_string, undef, { onsite_checkout => 1 } ); +C4::Circulation::AddIssue( + $patron, $item->barcode, dt_from_string, undef, dt_from_string, undef, + { onsite_checkout => 1 } +); my ( $impossible, $messages ); -t::lib::Mocks::mock_preference('SwitchOnSiteCheckouts', 0); +t::lib::Mocks::mock_preference( 'SwitchOnSiteCheckouts', 0 ); ( $impossible, undef, undef, $messages ) = C4::Circulation::CanBookBeIssued( $patron, $item->barcode ); is( $impossible->{NO_RENEWAL_FOR_ONSITE_CHECKOUTS}, 1, 'Do not renew on-site checkouts' ); -t::lib::Mocks::mock_preference('SwitchOnSiteCheckouts', 1); +t::lib::Mocks::mock_preference( 'SwitchOnSiteCheckouts', 1 ); ( $impossible, undef, undef, $messages ) = C4::Circulation::CanBookBeIssued( $patron, $item->barcode ); -is( $messages->{ONSITE_CHECKOUT_WILL_BE_SWITCHED}, 1, 'If SwitchOnSiteCheckouts, switch the on-site checkout' ); -is( exists $impossible->{TOO_MANY}, '', 'If SwitchOnSiteCheckouts, switch the on-site checkout' ); +is( $messages->{ONSITE_CHECKOUT_WILL_BE_SWITCHED}, 1, 'If SwitchOnSiteCheckouts, switch the on-site checkout' ); +is( exists $impossible->{TOO_MANY}, '', 'If SwitchOnSiteCheckouts, switch the on-site checkout' ); C4::Circulation::AddIssue( $patron, $item->barcode, undef, undef, undef, undef, { switch_onsite_checkout => 1 } ); my $issue = Koha::Checkouts->find( { itemnumber => $item->itemnumber } ); is( $issue->onsite_checkout, 0, 'The issue should have been switched to a regular checkout' ); my $five_days_after = dt_from_string->add( days => 5 )->set( hour => 23, minute => 59, second => 0 ); -is( dt_from_string($issue->date_due, 'sql'), $five_days_after, 'The date_due should have been set depending on the circ rules when the on-site checkout has been switched' ); +is( + dt_from_string( $issue->date_due, 'sql' ), $five_days_after, + 'The date_due should have been set depending on the circ rules when the on-site checkout has been switched' +); # Specific case -t::lib::Mocks::mock_preference('ConsiderOnSiteCheckoutsAsNormalCheckouts', 1); +t::lib::Mocks::mock_preference( 'ConsiderOnSiteCheckoutsAsNormalCheckouts', 1 ); my $another_item = $builder->build_sample_item( { biblionumber => $item->biblionumber, @@ -110,10 +121,13 @@ my $another_item = $builder->build_sample_item( } ); -C4::Circulation::AddIssue( $patron, $another_item->barcode, dt_from_string, undef, dt_from_string, undef, { onsite_checkout => 1 } ); +C4::Circulation::AddIssue( + $patron, $another_item->barcode, dt_from_string, undef, dt_from_string, undef, + { onsite_checkout => 1 } +); ( $impossible, undef, undef, $messages ) = C4::Circulation::CanBookBeIssued( $patron, $another_item->barcode ); -is( $messages->{ONSITE_CHECKOUT_WILL_BE_SWITCHED}, 1, 'Specific case 1 - Switch is allowed' ); -is( exists $impossible->{TOO_MANY}, '', 'Specific case 1 - Switch is allowed' ); +is( $messages->{ONSITE_CHECKOUT_WILL_BE_SWITCHED}, 1, 'Specific case 1 - Switch is allowed' ); +is( exists $impossible->{TOO_MANY}, '', 'Specific case 1 - Switch is allowed' ); my $yet_another_item = $builder->build_sample_item( { @@ -138,8 +152,8 @@ Koha::CirculationRules->set_rules( } ); ( $impossible, undef, undef, $messages ) = C4::Circulation::CanBookBeIssued( $patron, $another_item->barcode ); -is( $messages->{ONSITE_CHECKOUT_WILL_BE_SWITCHED}, 1, 'Specific case 2 - Switch is allowed' ); -is( exists $impossible->{TOO_MANY}, '', 'Specific case 2 - Switch is allowed' ); +is( $messages->{ONSITE_CHECKOUT_WILL_BE_SWITCHED}, 1, 'Specific case 2 - Switch is allowed' ); +is( exists $impossible->{TOO_MANY}, '', 'Specific case 2 - Switch is allowed' ); $schema->storage->txn_rollback; diff --git a/t/db_dependent/Circulation/TooMany.t b/t/db_dependent/Circulation/TooMany.t index b760cb4136..17980bb7ce 100755 --- a/t/db_dependent/Circulation/TooMany.t +++ b/t/db_dependent/Circulation/TooMany.t @@ -39,6 +39,7 @@ our $dbh = C4::Context->dbh; $dbh->do(q|DELETE FROM issues|); $dbh->do(q|DELETE FROM items|); $dbh->do(q|DELETE FROM borrowers|); + #$dbh->do(q|DELETE FROM branches|); $dbh->do(q|DELETE FROM categories|); $dbh->do(q|DELETE FROM accountlines|); @@ -47,36 +48,46 @@ $dbh->do(q|DELETE FROM itemtypes|); Koha::CirculationRules->search()->delete(); my $builder = t::lib::TestBuilder->new(); -t::lib::Mocks::mock_preference('item-level_itypes', 1); # Assuming the item type is defined at item level +t::lib::Mocks::mock_preference( 'item-level_itypes', 1 ); # Assuming the item type is defined at item level -my $branch = $builder->build({ - source => 'Branch', -}); +my $branch = $builder->build( + { + source => 'Branch', + } +); -my $branch2 = $builder->build({ - source => 'Branch', -}); +my $branch2 = $builder->build( + { + source => 'Branch', + } +); -my $category = $builder->build({ - source => 'Category', -}); +my $category = $builder->build( + { + source => 'Category', + } +); -my $patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { - categorycode => $category->{categorycode}, - branchcode => $branch->{branchcode}, - }, -}); +my $patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { + categorycode => $category->{categorycode}, + branchcode => $branch->{branchcode}, + }, + } +); -my $biblio = $builder->build_sample_biblio({ branchcode => $branch->{branchcode} }); -my $item = $builder->build_sample_item({ - biblionumber => $biblio->biblionumber, - homebranch => $branch->{branchcode}, - holdingbranch => $branch->{branchcode}, -}); +my $biblio = $builder->build_sample_biblio( { branchcode => $branch->{branchcode} } ); +my $item = $builder->build_sample_item( + { + biblionumber => $biblio->biblionumber, + homebranch => $branch->{branchcode}, + holdingbranch => $branch->{branchcode}, + } +); -t::lib::Mocks::mock_userenv( { patron => $patron }); +t::lib::Mocks::mock_userenv( { patron => $patron } ); # TooMany return ($current_loan_count, $max_loans_allowed) or undef # CO = Checkout @@ -109,7 +120,7 @@ subtest '1 Issuingrule exist 0 0: no issue allowed' => sub { } }, ); - t::lib::Mocks::mock_preference('ConsiderOnSiteCheckoutsAsNormalCheckouts', 0); + t::lib::Mocks::mock_preference( 'ConsiderOnSiteCheckoutsAsNormalCheckouts', 0 ); my $data = C4::Circulation::TooMany( $patron, $item ); my $rule = delete $data->{circulation_rule}; @@ -117,46 +128,46 @@ subtest '1 Issuingrule exist 0 0: no issue allowed' => sub { is_deeply( $data, { - reason => 'TOO_MANY_CHECKOUTS', - count => 0, + reason => 'TOO_MANY_CHECKOUTS', + count => 0, max_allowed => 0, }, 'CO should not be allowed if ConsiderOnSiteCheckoutsAsNormalCheckouts == 0' ); $data = C4::Circulation::TooMany( $patron, $item, { onsite_checkout => 1 } ), - $rule = delete $data->{circulation_rule}; + $rule = delete $data->{circulation_rule}; is( ref $rule, 'Koha::CirculationRule', 'Circulation rule was returned' ); is_deeply( $data, { - reason => 'TOO_MANY_ONSITE_CHECKOUTS', - count => 0, + reason => 'TOO_MANY_ONSITE_CHECKOUTS', + count => 0, max_allowed => 0, }, 'OSCO should not be allowed if ConsiderOnSiteCheckoutsAsNormalCheckouts == 0' ); - t::lib::Mocks::mock_preference('ConsiderOnSiteCheckoutsAsNormalCheckouts', 1); + t::lib::Mocks::mock_preference( 'ConsiderOnSiteCheckoutsAsNormalCheckouts', 1 ); $data = C4::Circulation::TooMany( $patron, $item ); $rule = delete $data->{circulation_rule}; is( ref $rule, 'Koha::CirculationRule', 'Circulation rule was returned' ); is_deeply( $data, { - reason => 'TOO_MANY_CHECKOUTS', - count => 0, + reason => 'TOO_MANY_CHECKOUTS', + count => 0, max_allowed => 0, }, 'CO should not be allowed if ConsiderOnSiteCheckoutsAsNormalCheckouts == 1' ); $data = C4::Circulation::TooMany( $patron, $item, { onsite_checkout => 1 } ), - $rule = delete $data->{circulation_rule}; + $rule = delete $data->{circulation_rule}; is( ref $rule, 'Koha::CirculationRule', 'Circulation rule was returned' ); is_deeply( $data, { - reason => 'TOO_MANY_ONSITE_CHECKOUTS', - count => 0, + reason => 'TOO_MANY_ONSITE_CHECKOUTS', + count => 0, max_allowed => 0, }, 'OSCO should not be allowed if ConsiderOnSiteCheckoutsAsNormalCheckouts == 1' @@ -181,15 +192,15 @@ subtest '1 Issuingrule exist with onsiteissueqty=unlimited' => sub { ); my $issue = C4::Circulation::AddIssue( $patron, $item->barcode, dt_from_string() ); - t::lib::Mocks::mock_preference('ConsiderOnSiteCheckoutsAsNormalCheckouts', 0); + t::lib::Mocks::mock_preference( 'ConsiderOnSiteCheckoutsAsNormalCheckouts', 0 ); my $data = C4::Circulation::TooMany( $patron, $item ); my $rule = delete $data->{circulation_rule}; is( ref $rule, 'Koha::CirculationRule', 'Circulation rule was returned' ); is_deeply( $data, { - reason => 'TOO_MANY_CHECKOUTS', - count => 1, + reason => 'TOO_MANY_CHECKOUTS', + count => 1, max_allowed => 1, }, 'CO should not be allowed if ConsiderOnSiteCheckoutsAsNormalCheckouts == 0' @@ -203,7 +214,7 @@ subtest '1 Issuingrule exist with onsiteissueqty=unlimited' => sub { 'OSCO should be allowed if ConsiderOnSiteCheckoutsAsNormalCheckouts == 0' ); - t::lib::Mocks::mock_preference('ConsiderOnSiteCheckoutsAsNormalCheckouts', 1); + t::lib::Mocks::mock_preference( 'ConsiderOnSiteCheckoutsAsNormalCheckouts', 1 ); $data = C4::Circulation::TooMany( $patron, $item ); $rule = delete $data->{circulation_rule}; is( ref $rule, 'Koha::CirculationRule', 'Circulation rule was returned' ); @@ -222,8 +233,8 @@ subtest '1 Issuingrule exist with onsiteissueqty=unlimited' => sub { is_deeply( $data, { - reason => 'TOO_MANY_CHECKOUTS', - count => 1, + reason => 'TOO_MANY_CHECKOUTS', + count => 1, max_allowed => 1, }, 'OSCO should not be allowed if ConsiderOnSiteCheckoutsAsNormalCheckouts == 1' @@ -232,7 +243,6 @@ subtest '1 Issuingrule exist with onsiteissueqty=unlimited' => sub { teardown(); }; - subtest '1 Issuingrule exist 1 1: issue is allowed' => sub { plan tests => 4; Koha::CirculationRules->set_rules( @@ -246,7 +256,7 @@ subtest '1 Issuingrule exist 1 1: issue is allowed' => sub { } } ); - t::lib::Mocks::mock_preference('ConsiderOnSiteCheckoutsAsNormalCheckouts', 0); + t::lib::Mocks::mock_preference( 'ConsiderOnSiteCheckoutsAsNormalCheckouts', 0 ); is( C4::Circulation::TooMany( $patron, $item ), undef, @@ -258,7 +268,7 @@ subtest '1 Issuingrule exist 1 1: issue is allowed' => sub { 'OSCO should be allowed if ConsiderOnSiteCheckoutsAsNormalCheckouts == 0' ); - t::lib::Mocks::mock_preference('ConsiderOnSiteCheckoutsAsNormalCheckouts', 1); + t::lib::Mocks::mock_preference( 'ConsiderOnSiteCheckoutsAsNormalCheckouts', 1 ); is( C4::Circulation::TooMany( $patron, $item ), undef, @@ -312,15 +322,15 @@ subtest '1 Issuingrule exist: 1 CO allowed, 1 OSCO allowed. Do a CO' => sub { 'OSCO should be allowed if ConsiderOnSiteCheckoutsAsNormalCheckouts == 0' ); - t::lib::Mocks::mock_preference('ConsiderOnSiteCheckoutsAsNormalCheckouts', 1); + t::lib::Mocks::mock_preference( 'ConsiderOnSiteCheckoutsAsNormalCheckouts', 1 ); $data = C4::Circulation::TooMany( $patron, $item ); $rule = delete $data->{circulation_rule}; is( ref $rule, 'Koha::CirculationRule', 'Circulation rule was returned' ); is_deeply( $data, { - reason => 'TOO_MANY_CHECKOUTS', - count => 1, + reason => 'TOO_MANY_CHECKOUTS', + count => 1, max_allowed => 1, }, 'CO should not be allowed if ConsiderOnSiteCheckoutsAsNormalCheckouts == 1' @@ -331,8 +341,8 @@ subtest '1 Issuingrule exist: 1 CO allowed, 1 OSCO allowed. Do a CO' => sub { is_deeply( $data, { - reason => 'TOO_MANY_CHECKOUTS', - count => 1, + reason => 'TOO_MANY_CHECKOUTS', + count => 1, max_allowed => 1, }, 'OSCO should not be allowed if ConsiderOnSiteCheckoutsAsNormalCheckouts == 1' @@ -355,7 +365,10 @@ subtest '1 Issuingrule exist: 1 CO allowed, 1 OSCO allowed, Do a OSCO' => sub { } ); - my $issue = C4::Circulation::AddIssue( $patron, $item->barcode, dt_from_string(), undef, undef, undef, { onsite_checkout => 1 } ); + my $issue = C4::Circulation::AddIssue( + $patron, $item->barcode, dt_from_string(), undef, undef, undef, + { onsite_checkout => 1 } + ); like( $issue->issue_id, qr|^\d+$|, 'The issue should have been inserted' ); t::lib::Mocks::mock_preference( 'ConsiderOnSiteCheckoutsAsNormalCheckouts', 0 ); @@ -396,8 +409,8 @@ subtest '1 Issuingrule exist: 1 CO allowed, 1 OSCO allowed, Do a OSCO' => sub { is_deeply( $data, { - reason => 'TOO_MANY_ONSITE_CHECKOUTS', - count => 1, + reason => 'TOO_MANY_ONSITE_CHECKOUTS', + count => 1, max_allowed => 1, }, 'OSCO should not be allowed if ConsiderOnSiteCheckoutsAsNormalCheckouts == 1' @@ -407,6 +420,7 @@ subtest '1 Issuingrule exist: 1 CO allowed, 1 OSCO allowed, Do a OSCO' => sub { }; subtest '1 BranchBorrowerCircRule exist: 1 CO allowed, 1 OSCO allowed' => sub { + # Note: the same test coul be done for # DefaultBorrowerCircRule, DefaultBranchCircRule, DefaultBranchItemRule ans DefaultCircRule.pm @@ -426,21 +440,21 @@ subtest '1 BranchBorrowerCircRule exist: 1 CO allowed, 1 OSCO allowed' => sub { my $issue = C4::Circulation::AddIssue( $patron, $item->barcode, dt_from_string(), undef, undef, undef ); like( $issue->issue_id, qr|^\d+$|, 'The issue should have been inserted' ); - t::lib::Mocks::mock_preference('ConsiderOnSiteCheckoutsAsNormalCheckouts', 0); + t::lib::Mocks::mock_preference( 'ConsiderOnSiteCheckoutsAsNormalCheckouts', 0 ); my $data = C4::Circulation::TooMany( $patron, $item ); my $rule = delete $data->{circulation_rule}; is( ref $rule, 'Koha::CirculationRule', 'Circulation rule was returned' ); is_deeply( $data, { - reason => 'TOO_MANY_CHECKOUTS', - count => 1, + reason => 'TOO_MANY_CHECKOUTS', + count => 1, max_allowed => 1, }, 'CO should be allowed if ConsiderOnSiteCheckoutsAsNormalCheckouts == 0' ); $data = C4::Circulation::TooMany( $patron, $item, { onsite_checkout => 1 } ), - $rule = delete $data->{circulation_rule}; + $rule = delete $data->{circulation_rule}; is( ref $rule, '', 'No circulation rule was returned' ); is_deeply( $data, @@ -448,27 +462,27 @@ subtest '1 BranchBorrowerCircRule exist: 1 CO allowed, 1 OSCO allowed' => sub { 'OSCO should not be allowed if ConsiderOnSiteCheckoutsAsNormalCheckouts == 0' ); - t::lib::Mocks::mock_preference('ConsiderOnSiteCheckoutsAsNormalCheckouts', 1); + t::lib::Mocks::mock_preference( 'ConsiderOnSiteCheckoutsAsNormalCheckouts', 1 ); $data = C4::Circulation::TooMany( $patron, $item ); $rule = delete $data->{circulation_rule}; is( ref $rule, 'Koha::CirculationRule', 'Circulation rule was returned' ); is_deeply( $data, { - reason => 'TOO_MANY_CHECKOUTS', - count => 1, + reason => 'TOO_MANY_CHECKOUTS', + count => 1, max_allowed => 1, }, 'CO should not be allowed if ConsiderOnSiteCheckoutsAsNormalCheckouts == 1' ); $data = C4::Circulation::TooMany( $patron, $item, { onsite_checkout => 1 } ), - $rule = delete $data->{circulation_rule}; + $rule = delete $data->{circulation_rule}; is( ref $rule, 'Koha::CirculationRule', 'Circulation rule was returned' ); is_deeply( $data, { - reason => 'TOO_MANY_CHECKOUTS', - count => 1, + reason => 'TOO_MANY_CHECKOUTS', + count => 1, max_allowed => 1, }, 'OSCO should not be allowed if ConsiderOnSiteCheckoutsAsNormalCheckouts == 1' @@ -487,10 +501,13 @@ subtest '1 BranchBorrowerCircRule exist: 1 CO allowed, 1 OSCO allowed' => sub { } ); - $issue = C4::Circulation::AddIssue( $patron, $item->barcode, dt_from_string(), undef, undef, undef, { onsite_checkout => 1 } ); + $issue = C4::Circulation::AddIssue( + $patron, $item->barcode, dt_from_string(), undef, undef, undef, + { onsite_checkout => 1 } + ); like( $issue->issue_id, qr|^\d+$|, 'The issue should have been inserted' ); - t::lib::Mocks::mock_preference('ConsiderOnSiteCheckoutsAsNormalCheckouts', 0); + t::lib::Mocks::mock_preference( 'ConsiderOnSiteCheckoutsAsNormalCheckouts', 0 ); $data = C4::Circulation::TooMany( $patron, $item ); $rule = delete $data->{circulation_rule}; is( ref $rule, '', 'No circulation rule was returned' ); @@ -500,39 +517,39 @@ subtest '1 BranchBorrowerCircRule exist: 1 CO allowed, 1 OSCO allowed' => sub { 'CO should be allowed if ConsiderOnSiteCheckoutsAsNormalCheckouts == 0' ); $data = C4::Circulation::TooMany( $patron, $item, { onsite_checkout => 1 } ), - $rule = delete $data->{circulation_rule}; + $rule = delete $data->{circulation_rule}; is( ref $rule, 'Koha::CirculationRule', 'Circulation rule was returned' ); is_deeply( $data, { - reason => 'TOO_MANY_ONSITE_CHECKOUTS', - count => 1, + reason => 'TOO_MANY_ONSITE_CHECKOUTS', + count => 1, max_allowed => 1, }, 'OSCO should not be allowed if ConsiderOnSiteCheckoutsAsNormalCheckouts == 0' ); - t::lib::Mocks::mock_preference('ConsiderOnSiteCheckoutsAsNormalCheckouts', 1); + t::lib::Mocks::mock_preference( 'ConsiderOnSiteCheckoutsAsNormalCheckouts', 1 ); $data = C4::Circulation::TooMany( $patron, $item ); $rule = delete $data->{circulation_rule}; is( ref $rule, 'Koha::CirculationRule', 'Circulation rule was returned' ); is_deeply( $data, { - reason => 'TOO_MANY_CHECKOUTS', - count => 1, + reason => 'TOO_MANY_CHECKOUTS', + count => 1, max_allowed => 1, }, 'CO should not be allowed if ConsiderOnSiteCheckoutsAsNormalCheckouts == 1' ); $data = C4::Circulation::TooMany( $patron, $item, { onsite_checkout => 1 } ), - $rule = delete $data->{circulation_rule}; + $rule = delete $data->{circulation_rule}; is( ref $rule, 'Koha::CirculationRule', 'Circulation rule was returned' ); is_deeply( $data, { - reason => 'TOO_MANY_ONSITE_CHECKOUTS', - count => 1, + reason => 'TOO_MANY_ONSITE_CHECKOUTS', + count => 1, max_allowed => 1, }, 'OSCO should not be allowed if ConsiderOnSiteCheckoutsAsNormalCheckouts == 1' @@ -544,25 +561,29 @@ subtest '1 BranchBorrowerCircRule exist: 1 CO allowed, 1 OSCO allowed' => sub { subtest 'General vs specific rules limit quantity correctly' => sub { plan tests => 18; - t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary'); - my $branch = $builder->build({source => 'Branch',}); - my $category = $builder->build({source => 'Category',}); - my $itemtype = $builder->build({ - source => 'Itemtype', - value => { - rentalcharge => 0, - rentalcharge_daily => 0, - rentalcharge_hourly => 0, - notforloan => 0, + t::lib::Mocks::mock_preference( 'CircControl', 'ItemHomeLibrary' ); + my $branch = $builder->build( { source => 'Branch', } ); + my $category = $builder->build( { source => 'Category', } ); + my $itemtype = $builder->build( + { + source => 'Itemtype', + value => { + rentalcharge => 0, + rentalcharge_daily => 0, + rentalcharge_hourly => 0, + notforloan => 0, + } } - }); - my $patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { - categorycode => $category->{categorycode}, - branchcode => $branch->{branchcode}, + ); + my $patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { + categorycode => $category->{categorycode}, + branchcode => $branch->{branchcode}, + } } - }); + ); # Set up an issuing rule Koha::CirculationRules->set_rules( @@ -605,18 +626,18 @@ subtest 'General vs specific rules limit quantity correctly' => sub { ); # Create an item - my $issue_item = $builder->build_sample_item({ - itype => $itemtype->{itemtype} - }); - my $branch_item = $builder->build_sample_item({ - itype => $itemtype->{itemtype}, - homebranch => $branch->{branchcode}, - holdingbranch => $branch->{branchcode} - }); + my $issue_item = $builder->build_sample_item( { itype => $itemtype->{itemtype} } ); + my $branch_item = $builder->build_sample_item( + { + itype => $itemtype->{itemtype}, + homebranch => $branch->{branchcode}, + holdingbranch => $branch->{branchcode} + } + ); - - t::lib::Mocks::mock_userenv({ branchcode => $branch->{branchcode} }); + t::lib::Mocks::mock_userenv( { branchcode => $branch->{branchcode} } ); my $issue = C4::Circulation::AddIssue( $patron, $issue_item->barcode, dt_from_string() ); + # We checkout one item my $data = C4::Circulation::TooMany( $patron, $branch_item ); my $rule = delete $data->{circulation_rule}; @@ -624,17 +645,18 @@ subtest 'General vs specific rules limit quantity correctly' => sub { is_deeply( $data, { - reason => 'TOO_MANY_CHECKOUTS', - count => 1, + reason => 'TOO_MANY_CHECKOUTS', + count => 1, max_allowed => 1, }, 'We are only allowed one, and we have one (itemtype on item)' ); # Check itemtype on biblio level - t::lib::Mocks::mock_preference('item-level_itypes', 0); - $issue_item->biblio->biblioitem->itemtype($itemtype->{itemtype})->store; - $branch_item->biblio->biblioitem->itemtype($itemtype->{itemtype})->store; + t::lib::Mocks::mock_preference( 'item-level_itypes', 0 ); + $issue_item->biblio->biblioitem->itemtype( $itemtype->{itemtype} )->store; + $branch_item->biblio->biblioitem->itemtype( $itemtype->{itemtype} )->store; + # We checkout one item $data = C4::Circulation::TooMany( $patron, $branch_item ); $rule = delete $data->{circulation_rule}; @@ -642,13 +664,13 @@ subtest 'General vs specific rules limit quantity correctly' => sub { is_deeply( $data, { - reason => 'TOO_MANY_CHECKOUTS', - count => 1, + reason => 'TOO_MANY_CHECKOUTS', + count => 1, max_allowed => 1, }, 'We are only allowed one, and we have one (itemtype on biblioitem)' ); - t::lib::Mocks::mock_preference('item-level_itypes', 1); + t::lib::Mocks::mock_preference( 'item-level_itypes', 1 ); # Set a branch specific rule Koha::CirculationRules->set_rules( @@ -663,7 +685,7 @@ subtest 'General vs specific rules limit quantity correctly' => sub { } ); - t::lib::Mocks::mock_preference('HomeOrHoldingBranch', 'homebranch'); + t::lib::Mocks::mock_preference( 'HomeOrHoldingBranch', 'homebranch' ); is( C4::Circulation::TooMany( $patron, $branch_item ), @@ -672,99 +694,105 @@ subtest 'General vs specific rules limit quantity correctly' => sub { ); # If circcontrol is PatronLibrary we count all the patron's loan, regardless of branch - t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary'); + t::lib::Mocks::mock_preference( 'CircControl', 'PatronLibrary' ); $data = C4::Circulation::TooMany( $patron, $branch_item ); $rule = delete $data->{circulation_rule}; is( ref $rule, 'Koha::CirculationRule', 'Circulation rule was returned' ); is_deeply( $data, { - reason => 'TOO_MANY_CHECKOUTS', - count => 1, + reason => 'TOO_MANY_CHECKOUTS', + count => 1, max_allowed => 1, }, 'We are allowed one from the branch specifically, but have one' ); - t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary'); + t::lib::Mocks::mock_preference( 'CircControl', 'ItemHomeLibrary' ); $issue = C4::Circulation::AddIssue( $patron, $branch_item->barcode, dt_from_string() ); + # We issue that one # And make another - my $branch_item_2 = $builder->build_sample_item({ - itype => $itemtype->{itemtype}, - homebranch => $branch->{branchcode}, - holdingbranch => $branch->{branchcode} - }); + my $branch_item_2 = $builder->build_sample_item( + { + itype => $itemtype->{itemtype}, + homebranch => $branch->{branchcode}, + holdingbranch => $branch->{branchcode} + } + ); $data = C4::Circulation::TooMany( $patron, $branch_item_2 ); $rule = delete $data->{circulation_rule}; is( ref $rule, 'Koha::CirculationRule', 'Circulation rule was returned' ); is_deeply( $data, { - reason => 'TOO_MANY_CHECKOUTS', - count => 1, + reason => 'TOO_MANY_CHECKOUTS', + count => 1, max_allowed => 1, }, 'We are only allowed one from that branch, and have one' ); # Now we make anothe from a different branch - my $item_2 = $builder->build_sample_item({ - itype => $itemtype->{itemtype}, - }); + my $item_2 = $builder->build_sample_item( + { + itype => $itemtype->{itemtype}, + } + ); $data = C4::Circulation::TooMany( $patron, $item_2 ); $rule = delete $data->{circulation_rule}; is( ref $rule, 'Koha::CirculationRule', 'Circulation rule was returned' ); is_deeply( $data, { - reason => 'TOO_MANY_CHECKOUTS', - count => 2, + reason => 'TOO_MANY_CHECKOUTS', + count => 2, max_allowed => 1, }, 'We are only allowed one for general rule, and have two' ); - t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary'); + t::lib::Mocks::mock_preference( 'CircControl', 'PatronLibrary' ); $data = C4::Circulation::TooMany( $patron, $item_2 ); $rule = delete $data->{circulation_rule}; is( ref $rule, 'Koha::CirculationRule', 'Circulation rule was returned' ); is_deeply( $data, { - reason => 'TOO_MANY_CHECKOUTS', - count => 2, + reason => 'TOO_MANY_CHECKOUTS', + count => 2, max_allowed => 1, }, 'We are only allowed one for general rule, and have two' ); - t::lib::Mocks::mock_preference('CircControl', 'PickupLibrary'); + t::lib::Mocks::mock_preference( 'CircControl', 'PickupLibrary' ); $data = C4::Circulation::TooMany( $patron, $item_2 ); $rule = delete $data->{circulation_rule}; is( ref $rule, 'Koha::CirculationRule', 'Circulation rule was returned' ); is_deeply( $data, { - reason => 'TOO_MANY_CHECKOUTS', - count => 2, + reason => 'TOO_MANY_CHECKOUTS', + count => 2, max_allowed => 1, }, 'We are only allowed one for general rule, and have checked out two at this branch' ); - t::lib::Mocks::mock_userenv({ branchcode => $branch2->{branchcode} }); + t::lib::Mocks::mock_userenv( { branchcode => $branch2->{branchcode} } ); $data = C4::Circulation::TooMany( $patron, $item_2 ); $rule = delete $data->{circulation_rule}; is( ref $rule, 'Koha::CirculationRule', 'Circulation rule was returned' ); is_deeply( $data, { - reason => 'TOO_MANY_CHECKOUTS', - count => 2, + reason => 'TOO_MANY_CHECKOUTS', + count => 2, max_allowed => 1, }, 'We are only allowed one for general rule, and have two total (no rule for specific branch)' ); + # Set a branch specific rule for new branch Koha::CirculationRules->set_rules( { @@ -809,7 +837,7 @@ subtest 'empty string means unlimited' => sub { C4::Circulation::TooMany( $patron, $item, { onsite_checkout => 1 } ), undef, 'maxonsiteissueqty="" should mean unlimited' - ); + ); }; subtest 'itemtype group tests' => sub { @@ -825,8 +853,8 @@ subtest 'itemtype group tests' => sub { maxissueqty => '5', maxonsiteissueqty => '', issuelength => 1, - firstremind => 1, # 1 day of grace - finedays => 2, # 2 days of fine per day of overdue + firstremind => 1, # 1 day of grace + finedays => 2, # 2 days of fine per day of overdue lengthunit => 'days', } }, @@ -874,7 +902,7 @@ subtest 'itemtype group tests' => sub { my $patron = $builder->build_object( { class => 'Koha::Patrons', - value => { + value => { categorycode => $category->{categorycode}, branchcode => $branch->{branchcode}, }, @@ -898,7 +926,7 @@ subtest 'itemtype group tests' => sub { my $all_iq_rule = $builder->build_object( { class => 'Koha::CirculationRules', - value => { + value => { branchcode => $branch->{branchcode}, categorycode => $category->{categorycode}, itemtype => undef, @@ -907,8 +935,10 @@ subtest 'itemtype group tests' => sub { } } ); - is( C4::Circulation::TooMany( $patron, $item ), - undef, 'Checkout allowed, using all rule of 1' ); + is( + C4::Circulation::TooMany( $patron, $item ), + undef, 'Checkout allowed, using all rule of 1' + ); #Checkout an item my $issue = C4::Circulation::AddIssue( $patron, $checkout_item->barcode, dt_from_string() ); @@ -1006,12 +1036,13 @@ subtest 'itemtype group tests' => sub { } ); - is( C4::Circulation::TooMany( $patron, $item_1 ), - undef, 'Checkout allowed' ); + is( + C4::Circulation::TooMany( $patron, $item_1 ), + undef, 'Checkout allowed' + ); #checkout an item - $issue = - C4::Circulation::AddIssue( $patron, $item_1->barcode, dt_from_string() ); + $issue = C4::Circulation::AddIssue( $patron, $item_1->barcode, dt_from_string() ); like( $issue->issue_id, qr|^\d+$|, 'the issue should have been inserted' ); #patron has 1 checkout of childitype1 and 1 checkout of childitype2 @@ -1026,7 +1057,7 @@ subtest 'itemtype group tests' => sub { count => 2, max_allowed => 2, }, -'Checkout not allowed, using parent type rule of 2, checkout of sibling itemtype counted' + 'Checkout not allowed, using parent type rule of 2, checkout of sibling itemtype counted' ); my $parent_item = $builder->build_sample_item( @@ -1047,15 +1078,16 @@ subtest 'itemtype group tests' => sub { count => 2, max_allowed => 2, }, -'Checkout not allowed, using parent type rule of 2, checkout of child itemtypes counted' + 'Checkout not allowed, using parent type rule of 2, checkout of child itemtypes counted' ); #increase parent type to greater than specific $parent_iq_rule->rule_value(4)->store(); - - is( C4::Circulation::TooMany( $patron, $item_1 ), - undef, 'Checkout allowed, using specific type rule of 3' ); + is( + C4::Circulation::TooMany( $patron, $item_1 ), + undef, 'Checkout allowed, using specific type rule of 3' + ); my $item_2 = $builder->build_sample_item( { @@ -1066,9 +1098,10 @@ subtest 'itemtype group tests' => sub { ); #checkout an item - $issue = - C4::Circulation::AddIssue( $patron, $item_2->barcode, dt_from_string(), - undef, undef, undef ); + $issue = C4::Circulation::AddIssue( + $patron, $item_2->barcode, dt_from_string(), + undef, undef, undef + ); like( $issue->issue_id, qr|^\d+$|, 'the issue should have been inserted' ); #patron has 1 checkout of childitype1 and 2 of childitype2 @@ -1076,10 +1109,10 @@ subtest 'itemtype group tests' => sub { is( C4::Circulation::TooMany( $patron, $item_2 ), undef, -'Checkout allowed, using specific type rule of 3, checkout of sibling itemtype not counted' + 'Checkout allowed, using specific type rule of 3, checkout of sibling itemtype not counted' ); - $child1_iq_rule->rule_value(2)->store(); #Allow 2 checkouts for child type 1 + $child1_iq_rule->rule_value(2)->store(); #Allow 2 checkouts for child type 1 my $item_3 = $builder->build_sample_item( { @@ -1097,9 +1130,10 @@ subtest 'itemtype group tests' => sub { ); #checkout an item - $issue = - C4::Circulation::AddIssue( $patron, $item_4->barcode, dt_from_string(), - undef, undef, undef ); + $issue = C4::Circulation::AddIssue( + $patron, $item_4->barcode, dt_from_string(), + undef, undef, undef + ); like( $issue->issue_id, qr|^\d+$|, 'the issue should have been inserted' ); #patron has 1 checkout of childitype 1 and 3 of childitype2 @@ -1114,7 +1148,7 @@ subtest 'itemtype group tests' => sub { max_allowed => 4, count => 4, }, -'Checkout not allowed, using specific type rule of 2, checkout of sibling itemtype not counted, but parent rule (4) prevents another' + 'Checkout not allowed, using specific type rule of 2, checkout of sibling itemtype not counted, but parent rule (4) prevents another' ); teardown(); @@ -1138,7 +1172,7 @@ subtest 'HomeOrHoldingBranch is used' => sub { categorycode => undef, itemtype => undef, rules => { - maxissueqty => 0, + maxissueqty => 0, } } ); @@ -1149,15 +1183,15 @@ subtest 'HomeOrHoldingBranch is used' => sub { categorycode => undef, itemtype => undef, rules => { - maxissueqty => 1, + maxissueqty => 1, } } ); - t::lib::Mocks::mock_userenv({ branchcode => $branch2->{branchcode} }); + t::lib::Mocks::mock_userenv( { branchcode => $branch2->{branchcode} } ); my $issue = C4::Circulation::AddIssue( $patron, $item_1->barcode, dt_from_string() ); - t::lib::Mocks::mock_preference('HomeOrHoldingBranch', 'homebranch'); + t::lib::Mocks::mock_preference( 'HomeOrHoldingBranch', 'homebranch' ); my $data = C4::Circulation::TooMany( $patron, $item_1 ); my $rule = delete $data->{circulation_rule}; @@ -1172,7 +1206,7 @@ subtest 'HomeOrHoldingBranch is used' => sub { 'We are allowed zero issues from the homebranch specifically' ); - t::lib::Mocks::mock_preference('HomeOrHoldingBranch', 'holdingbranch'); + t::lib::Mocks::mock_preference( 'HomeOrHoldingBranch', 'holdingbranch' ); $data = C4::Circulation::TooMany( $patron, $item_1 ); $rule = delete $data->{circulation_rule}; diff --git a/t/db_dependent/Circulation/_CalculateAndUpdateFine.t b/t/db_dependent/Circulation/_CalculateAndUpdateFine.t index 701e3bfb56..b1f18cbce0 100755 --- a/t/db_dependent/Circulation/_CalculateAndUpdateFine.t +++ b/t/db_dependent/Circulation/_CalculateAndUpdateFine.t @@ -30,39 +30,48 @@ use C4::Circulation; use t::lib::TestBuilder; use t::lib::Mocks; - my $schema = Koha::Database->schema; $schema->storage->txn_begin; my $builder = t::lib::TestBuilder->new(); -my $branch = $builder->build({ - source => 'Branch', -}); +my $branch = $builder->build( + { + source => 'Branch', + } +); -my $branch2 = $builder->build({ - source => 'Branch', -}); +my $branch2 = $builder->build( + { + source => 'Branch', + } +); -my $category = $builder->build({ - source => 'Category', -}); +my $category = $builder->build( + { + source => 'Category', + } +); -my $patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { - categorycode => $category->{categorycode}, - branchcode => $branch->{branchcode}, - }, -}); +my $patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { + categorycode => $category->{categorycode}, + branchcode => $branch->{branchcode}, + }, + } +); -my $biblio = $builder->build_sample_biblio({ branchcode => $branch->{branchcode} }); +my $biblio = $builder->build_sample_biblio( { branchcode => $branch->{branchcode} } ); -my $item = $builder->build_sample_item({ - biblionumber => $biblio->biblionumber, - homebranch => $branch->{branchcode}, - holdingbranch => $branch2->{branchcode}, -}); +my $item = $builder->build_sample_item( + { + biblionumber => $biblio->biblionumber, + homebranch => $branch->{branchcode}, + holdingbranch => $branch2->{branchcode}, + } +); Koha::CirculationRules->search()->delete(); @@ -76,10 +85,10 @@ subtest 'HomeOrHoldingBranch is used' => sub { categorycode => undef, branchcode => $branch->{branchcode}, rules => { - fine => '1.00', - lengthunit => 'days', - finedays => 0, - chargeperiod => 1, + fine => '1.00', + lengthunit => 'days', + finedays => 0, + chargeperiod => 1, } } ); @@ -91,46 +100,46 @@ subtest 'HomeOrHoldingBranch is used' => sub { categorycode => undef, branchcode => $branch2->{branchcode}, rules => { - fine => '0.00', - lengthunit => 'days', - finedays => 0, - chargeperiod => 1, + fine => '0.00', + lengthunit => 'days', + finedays => 0, + chargeperiod => 1, } } ); - t::lib::Mocks::mock_preference('finesMode', 'production'); - t::lib::Mocks::mock_preference('CircControl', 'ItemHomeLibrary'); - t::lib::Mocks::mock_preference('HomeOrHoldingBranch', 'holdingbranch'); - t::lib::Mocks::mock_userenv({ branchcode => $branch->{branchcode} }); + t::lib::Mocks::mock_preference( 'finesMode', 'production' ); + t::lib::Mocks::mock_preference( 'CircControl', 'ItemHomeLibrary' ); + t::lib::Mocks::mock_preference( 'HomeOrHoldingBranch', 'holdingbranch' ); + t::lib::Mocks::mock_userenv( { branchcode => $branch->{branchcode} } ); my $issue = C4::Circulation::AddIssue( $patron, $item->barcode, dt_from_string() ); # Returning loan 1 day after due date my $return_date = dt_from_string()->add( days => 1 )->set( hour => 23, minute => 59, second => 0 ); C4::Circulation::_CalculateAndUpdateFine( - { - borrower => $patron->unblessed, - issue => $issue, - item => $item->unblessed, + { + borrower => $patron->unblessed, + issue => $issue, + item => $item->unblessed, return_date => $return_date, } ); - my $fines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber }); - is($fines->total_outstanding, 0, "Fine is not accrued for holdingbranch"); + my $fines = Koha::Account::Lines->search( { borrowernumber => $patron->borrowernumber } ); + is( $fines->total_outstanding, 0, "Fine is not accrued for holdingbranch" ); - t::lib::Mocks::mock_preference('HomeOrHoldingBranch', 'homebranch'); + t::lib::Mocks::mock_preference( 'HomeOrHoldingBranch', 'homebranch' ); C4::Circulation::_CalculateAndUpdateFine( { - borrower => $patron->unblessed, - issue => $issue, - item => $item->unblessed, + borrower => $patron->unblessed, + issue => $issue, + item => $item->unblessed, return_date => $return_date, } ); - $fines = Koha::Account::Lines->search({ borrowernumber => $patron->borrowernumber }); - is($fines->total_outstanding, 1, "Fine is accrued for homebranch"); + $fines = Koha::Account::Lines->search( { borrowernumber => $patron->borrowernumber } ); + is( $fines->total_outstanding, 1, "Fine is accrued for homebranch" ); }; diff --git a/t/db_dependent/Circulation/dateexpiry.t b/t/db_dependent/Circulation/dateexpiry.t index f992219687..8a1e5c8976 100755 --- a/t/db_dependent/Circulation/dateexpiry.t +++ b/t/db_dependent/Circulation/dateexpiry.t @@ -27,12 +27,12 @@ use Koha::Database; use t::lib::TestBuilder; use t::lib::Mocks qw( mock_preference ); -my $schema = Koha::Database->new->schema; +my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; my $builder = t::lib::TestBuilder->new(); -my $patron_category = $builder->build({ source => 'Category', value => { category_type => 'P', enrolmentfee => 0 } }); +my $patron_category = $builder->build( { source => 'Category', value => { category_type => 'P', enrolmentfee => 0 } } ); subtest 'Tests for CanBookBeIssued related to dateexpiry' => sub { plan tests => 4; @@ -44,11 +44,12 @@ subtest 'Tests for CalcDateDue related to dateexpiry' => sub { }; sub can_book_be_issued { - my $item = $builder->build_sample_item; - my $patron = $builder->build_object( - { class => 'Koha::Patrons', - value => { - dateexpiry => '9999-12-31', + my $item = $builder->build_sample_item; + my $patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { + dateexpiry => '9999-12-31', categorycode => $patron_category->{categorycode}, } } @@ -57,32 +58,43 @@ sub can_book_be_issued { my ( $issuingimpossible, $needsconfirmation ) = C4::Circulation::CanBookBeIssued( $patron, $item->barcode ); $duration = gettimeofday() - $duration; cmp_ok $duration, '<', 1, "CanBookBeIssued should not be take more than 1s if the patron is expired"; - is( not( exists $issuingimpossible->{EXPIRED} ), 1, 'The patron should not be considered as expired if dateexpiry is 9999-*' ); + is( + not( exists $issuingimpossible->{EXPIRED} ), 1, + 'The patron should not be considered as expired if dateexpiry is 9999-*' + ); $item = $builder->build_sample_item; $patron = $builder->build_object( - { class => 'Koha::Patrons', - value => { - dateexpiry => undef, + { + class => 'Koha::Patrons', + value => { + dateexpiry => undef, categorycode => $patron_category->{categorycode}, } } ); ( $issuingimpossible, $needsconfirmation ) = C4::Circulation::CanBookBeIssued( $patron, $item->barcode ); - is( not( exists $issuingimpossible->{EXPIRED} ), 1, 'The patron should not be considered as expired if dateexpiry is not set' ); + is( + not( exists $issuingimpossible->{EXPIRED} ), 1, + 'The patron should not be considered as expired if dateexpiry is not set' + ); my $tomorrow = dt_from_string->add_duration( DateTime::Duration->new( days => 1 ) ); $item = $builder->build_sample_item; $patron = $builder->build_object( - { class => 'Koha::Patrons', - value => { - dateexpiry => output_pref( { dt => $tomorrow, dateonly => 1, dateformat => 'sql' } ), + { + class => 'Koha::Patrons', + value => { + dateexpiry => output_pref( { dt => $tomorrow, dateonly => 1, dateformat => 'sql' } ), categorycode => $patron_category->{categorycode}, }, } ); ( $issuingimpossible, $needsconfirmation ) = C4::Circulation::CanBookBeIssued( $patron, $item->barcode ); - is( not( exists $issuingimpossible->{EXPIRED} ), 1, 'The patron should not be considered as expired if dateexpiry is tomorrow' ); + is( + not( exists $issuingimpossible->{EXPIRED} ), 1, + 'The patron should not be considered as expired if dateexpiry is tomorrow' + ); } @@ -93,8 +105,8 @@ sub calc_date_due { my $patron = $builder->build_object( { - class => 'Koha::Patrons', - value => { + class => 'Koha::Patrons', + value => { categorycode => $patron_category->{categorycode}, } } @@ -113,10 +125,13 @@ sub calc_date_due { my $d2 = output_pref( { dt => $today, dateonly => 1, dateformat => 'sql' } ); $patron->dateexpiry($d2)->store; $d = C4::Circulation::CalcDateDue( $today, $item->effective_itemtype, $branch->{branchcode}, $patron ); - is( ref $d eq "DateTime" && DateTime->compare( $d->truncate( to => 'day' ), $today->truncate( to => 'day' ) ) == 0, 1, "CalcDateDue with expiry today" ); + is( + ref $d eq "DateTime" && DateTime->compare( $d->truncate( to => 'day' ), $today->truncate( to => 'day' ) ) == 0, + 1, "CalcDateDue with expiry today" + ); # third test expiry date tomorrow - my $dur = DateTime::Duration->new( days => 1 ); + my $dur = DateTime::Duration->new( days => 1 ); my $tomorrow = $today->clone->add_duration($dur); $d2 = output_pref( { dt => $tomorrow, dateonly => 1, dateformat => 'sql' } ); $patron->dateexpiry($d2)->store; @@ -128,7 +143,10 @@ sub calc_date_due { my $t1 = time; $d = C4::Circulation::CalcDateDue( $today, $item->effective_itemtype, $branch->{branchcode}, $patron ); my $t2 = time; - is( ref $d eq "DateTime" && $t2 - $t1 < 1, 1, "CalcDateDue with expiry in year 9876 in " . sprintf( "%6.4f", $t2 - $t1 ) . " seconds." ); + is( + ref $d eq "DateTime" && $t2 - $t1 < 1, 1, + "CalcDateDue with expiry in year 9876 in " . sprintf( "%6.4f", $t2 - $t1 ) . " seconds." + ); } $schema->storage->txn_rollback; diff --git a/t/db_dependent/Circulation/issue.t b/t/db_dependent/Circulation/issue.t index 8b91a27a88..2b00d54a33 100755 --- a/t/db_dependent/Circulation/issue.t +++ b/t/db_dependent/Circulation/issue.t @@ -24,7 +24,8 @@ use t::lib::Mocks; use t::lib::TestBuilder; use C4::Biblio qw( AddBiblio ); -use C4::Circulation qw( AddIssue AddIssuingCharge AddRenewal AddReturn GetIssuingCharges GetRenewCount GetUpcomingDueIssues ); +use C4::Circulation + qw( AddIssue AddIssuingCharge AddRenewal AddReturn GetIssuingCharges GetRenewCount GetUpcomingDueIssues ); use C4::Context; use C4::Items; use C4::Reserves qw( AddReserve ); @@ -45,13 +46,13 @@ BEGIN { can_ok( 'C4::Circulation', qw(AddIssue - AddIssuingCharge - AddRenewal - AddReturn - GetIssuingCharges - GetRenewCount - GetUpcomingDueIssues - ) + AddIssuingCharge + AddRenewal + AddReturn + GetIssuingCharges + GetRenewCount + GetUpcomingDueIssues + ) ); #Start transaction @@ -84,13 +85,15 @@ my $itemtype2 = $builder->build( value => { notforloan => 0 } } )->{itemtype}; -my $branchcode_1 = $builder->build({ source => 'Branch' })->{branchcode}; -my $branchcode_2 = $builder->build({ source => 'Branch' })->{branchcode}; -my $branchcode_3 = $builder->build({ source => 'Branch' })->{branchcode}; -my $categorycode = $builder->build({ +my $branchcode_1 = $builder->build( { source => 'Branch' } )->{branchcode}; +my $branchcode_2 = $builder->build( { source => 'Branch' } )->{branchcode}; +my $branchcode_3 = $builder->build( { source => 'Branch' } )->{branchcode}; +my $categorycode = $builder->build( + { source => 'Category', - value => { enrolmentfee => undef } - })->{categorycode}; + value => { enrolmentfee => undef } + } +)->{categorycode}; # A default issuingrule should always be present Koha::CirculationRules->set_rules( @@ -110,7 +113,8 @@ Koha::CirculationRules->set_rules( # Add Dates my $dt_today = dt_from_string; my $today = output_pref( - { dt => $dt_today, + { + dt => $dt_today, dateformat => 'iso', timeformat => '24hr', dateonly => 1 @@ -118,10 +122,11 @@ my $today = output_pref( ); my $dt_today2 = dt_from_string; -my $dur10 = DateTime::Duration->new( days => -10 ); +my $dur10 = DateTime::Duration->new( days => -10 ); $dt_today2->add_duration($dur10); my $daysago10 = output_pref( - { dt => $dt_today2, + { + dt => $dt_today2, dateformat => 'iso', timeformat => '24hr', dateonly => 1 @@ -129,22 +134,24 @@ my $daysago10 = output_pref( ); # Add biblio and item -my $record = MARC::Record->new(); +my $record = MARC::Record->new(); my $record2 = MARC::Record->new(); $record->append_fields( MARC::Field->new( '942', '0', '0', c => $itemtype ), - MARC::Field->new( '952', '0', '0', a => $branchcode_1 ) ); + MARC::Field->new( '952', '0', '0', a => $branchcode_1 ) +); $record2->append_fields( MARC::Field->new( '942', '0', '0', c => $itemtype2 ), - MARC::Field->new( '952', '0', '0', a => $branchcode_1 ) ); + MARC::Field->new( '952', '0', '0', a => $branchcode_1 ) +); -my ( $biblionumber, $biblioitemnumber ) = C4::Biblio::AddBiblio( $record, '' ); +my ( $biblionumber, $biblioitemnumber ) = C4::Biblio::AddBiblio( $record, '' ); my ( $biblionumber2, $biblioitemnumber2 ) = C4::Biblio::AddBiblio( $record2, '' ); my $barcode_1 = 'barcode_1'; my $barcode_2 = 'barcode_2'; -my $item_id1 = Koha::Item->new( +my $item_id1 = Koha::Item->new( { biblionumber => $biblionumber, barcode => $barcode_1, @@ -167,34 +174,40 @@ my $item_id2 = Koha::Item->new( )->store->itemnumber; #Add borrower -my $borrower_id1 = Koha::Patron->new({ - firstname => 'firstname1', - surname => 'surname1 ', - categorycode => $categorycode, - branchcode => $branchcode_1 -})->store->borrowernumber; -my $patron_1 = Koha::Patrons->find( $borrower_id1 ); -my $borrower_id2 = Koha::Patron->new({ - firstname => 'firstname2', - surname => 'surname2 ', - categorycode => $categorycode, - branchcode => $branchcode_2, -})->store->borrowernumber; -my $patron_2 = Koha::Patrons->find( $borrower_id2 ); +my $borrower_id1 = Koha::Patron->new( + { + firstname => 'firstname1', + surname => 'surname1 ', + categorycode => $categorycode, + branchcode => $branchcode_1 + } +)->store->borrowernumber; +my $patron_1 = Koha::Patrons->find($borrower_id1); +my $borrower_id2 = Koha::Patron->new( + { + firstname => 'firstname2', + surname => 'surname2 ', + categorycode => $categorycode, + branchcode => $branchcode_2, + } +)->store->borrowernumber; +my $patron_2 = Koha::Patrons->find($borrower_id2); -t::lib::Mocks::mock_userenv({ patron => $patron_1 }); +t::lib::Mocks::mock_userenv( { patron => $patron_1 } ); #Begin Tests #Test AddIssue my $query = " SELECT count(*) FROM issues"; -my $sth = $dbh->prepare($query); +my $sth = $dbh->prepare($query); $sth->execute; my $countissue = $sth->fetchrow_array; -is ($countissue ,0, "there is no issue"); +is( $countissue, 0, "there is no issue" ); my $issue1 = C4::Circulation::AddIssue( $patron_1, $barcode_1, $daysago10, 0, $today, '' ); -is( ref $issue1, 'Koha::Checkout', - 'AddIssue returns a Koha::Checkout object' ); +is( + ref $issue1, 'Koha::Checkout', + 'AddIssue returns a Koha::Checkout object' +); my $datedue1 = dt_from_string( $issue1->date_due() ); like( $datedue1, @@ -208,32 +221,32 @@ is( $issue2, undef, "AddIssue returns undef if no datedue is specified" ); $sth->execute; $countissue = $sth->fetchrow_array; -is ($countissue,1,"1 issues have been added"); +is( $countissue, 1, "1 issues have been added" ); #Test AddIssuingCharge $query = " SELECT count(*) FROM accountlines"; -$sth = $dbh->prepare($query); +$sth = $dbh->prepare($query); $sth->execute; my $countaccount = $sth->fetchrow_array; -is ($countaccount,0,"0 accountline exists"); -my $checkout = Koha::Checkouts->find( $issue_id1 ); -my $charge = C4::Circulation::AddIssuingCharge( $checkout, 10, 'RENT' ); -is( ref( $charge ), 'Koha::Account::Line', "An issuing charge has been added" ); -is( $charge->issue_id, $issue_id1, 'Issue id is set correctly for issuing charge' ); +is( $countaccount, 0, "0 accountline exists" ); +my $checkout = Koha::Checkouts->find($issue_id1); +my $charge = C4::Circulation::AddIssuingCharge( $checkout, 10, 'RENT' ); +is( ref($charge), 'Koha::Account::Line', "An issuing charge has been added" ); +is( $charge->issue_id, $issue_id1, 'Issue id is set correctly for issuing charge' ); my $offset = Koha::Account::Offsets->find( { debit_id => $charge->id } ); -is( $offset->credit_id, undef, 'Offset was created'); +is( $offset->credit_id, undef, 'Offset was created' ); $sth->execute; $countaccount = $sth->fetchrow_array; -is ($countaccount,1,"1 accountline has been added"); +is( $countaccount, 1, "1 accountline has been added" ); # Test AddRenewal -my $se = Test::MockModule->new( 'C4::Context' ); -$se->mock( 'interface', sub {return 'intranet'}); +my $se = Test::MockModule->new('C4::Context'); +$se->mock( 'interface', sub { return 'intranet' } ); # Let's renew this one at a different library for statistical purposes to test Bug 17781 # Mocking userenv with a different branchcode -t::lib::Mocks::mock_userenv({ patron => $patron_2, branchcode => $branchcode_3 }); +t::lib::Mocks::mock_userenv( { patron => $patron_2, branchcode => $branchcode_3 } ); my $datedue3 = AddRenewal( { @@ -246,7 +259,7 @@ my $datedue3 = AddRenewal( ); # Restoring the userenv with the original branchcode -t::lib::Mocks::mock_userenv({ patron => $patron_1}); +t::lib::Mocks::mock_userenv( { patron => $patron_1 } ); like( $datedue3, @@ -254,14 +267,17 @@ like( "AddRenewal returns a date" ); -my $stat = $dbh->selectrow_hashref("SELECT * FROM statistics WHERE type = 'renew' AND borrowernumber = ? AND itemnumber = ? AND branch = ?", undef, $borrower_id1, $item_id1, $branchcode_3 ); +my $stat = $dbh->selectrow_hashref( + "SELECT * FROM statistics WHERE type = 'renew' AND borrowernumber = ? AND itemnumber = ? AND branch = ?", undef, + $borrower_id1, $item_id1, $branchcode_3 +); ok( $stat, "Bug 17781 - 'Improper branchcode set during renewal' still fixed" ); subtest 'Show that AddRenewal respects OpacRenewalBranch and interface' => sub { plan tests => 10; - my $item_library = $builder->build_object( { class => 'Koha::Libraries' } ); - my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + my $item_library = $builder->build_object( { class => 'Koha::Libraries' } ); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $logged_in_user = $builder->build_object( { class => 'Koha::Patrons' } ); t::lib::Mocks::mock_userenv( { patron => $logged_in_user } ); @@ -280,10 +296,8 @@ subtest 'Show that AddRenewal respects OpacRenewalBranch and interface' => sub { { $se->mock( 'interface', sub { return 'opac' } ); - my $item = $builder->build_sample_item( - { library => $item_library->branchcode, itype => $itemtype } ); - my $opac_renew_issue = - C4::Circulation::AddIssue( $patron, $item->barcode ); + my $item = $builder->build_sample_item( { library => $item_library->branchcode, itype => $itemtype } ); + my $opac_renew_issue = C4::Circulation::AddIssue( $patron, $item->barcode ); AddRenewal( { @@ -295,9 +309,9 @@ subtest 'Show that AddRenewal respects OpacRenewalBranch and interface' => sub { } ); - my $stat = Koha::Statistics->search( - { itemnumber => $item->itemnumber, type => 'renew' } )->next; - is( $stat->branch, $expected_branchcode, + my $stat = Koha::Statistics->search( { itemnumber => $item->itemnumber, type => 'renew' } )->next; + is( + $stat->branch, $expected_branchcode, "->renewal_branchcode is respected for OpacRenewalBranch = $syspref" ); } @@ -305,10 +319,8 @@ subtest 'Show that AddRenewal respects OpacRenewalBranch and interface' => sub { { $se->mock( 'interface', sub { return 'intranet' } ); - my $item = $builder->build_sample_item( - { library => $item_library->branchcode, itype => $itemtype } ); - my $opac_renew_issue = - C4::Circulation::AddIssue( $patron, $item->barcode ); + my $item = $builder->build_sample_item( { library => $item_library->branchcode, itype => $itemtype } ); + my $opac_renew_issue = C4::Circulation::AddIssue( $patron, $item->barcode ); AddRenewal( { @@ -320,33 +332,34 @@ subtest 'Show that AddRenewal respects OpacRenewalBranch and interface' => sub { } ); - my $stat = Koha::Statistics->search( - { itemnumber => $item->itemnumber, type => 'renew' } )->next; - is( $stat->branch, $logged_in_user->branchcode, + my $stat = Koha::Statistics->search( { itemnumber => $item->itemnumber, type => 'renew' } )->next; + is( + $stat->branch, $logged_in_user->branchcode, "->renewal_branchcode is always logged in branch for intranet" ); } } }; - my @renewcount; + #Test GetRenewCount my $issue3 = C4::Circulation::AddIssue( $patron_1, $barcode_1 ); + #Without anything in DB @renewcount = C4::Circulation::GetRenewCount(); is_deeply( \@renewcount, - [ 0, 0, 0, 0, 0, 0 ], # FIXME Need to be fixed, see FIXME in GetRenewCount + [ 0, 0, 0, 0, 0, 0 ], # FIXME Need to be fixed, see FIXME in GetRenewCount "Without issuing rules and without parameter, GetRenewCount returns renewcount = 0, renewsallowed = undef, renewsleft = 0" ); @renewcount = C4::Circulation::GetRenewCount(-1); is_deeply( \@renewcount, - [ 0, 0, 0, 0, 0, 0 ], # FIXME Need to be fixed + [ 0, 0, 0, 0, 0, 0 ], # FIXME Need to be fixed "Without issuing rules and without wrong parameter, GetRenewCount returns renewcount = 0, renewsallowed = undef, renewsleft = 0" ); -@renewcount = C4::Circulation::GetRenewCount($borrower_id1, $item_id1); +@renewcount = C4::Circulation::GetRenewCount( $borrower_id1, $item_id1 ); is_deeply( \@renewcount, [ 2, 0, 0, 0, 0, 0 ], @@ -366,7 +379,7 @@ is_deeply( [ 0, 0, 0, 0, 0, 0 ], "With issuing rules (renewal disallowed) and without wrong parameter, GetRenewCount returns renewcount = 0, renewsallowed = 0, renewsleft = 0" ); -@renewcount = C4::Circulation::GetRenewCount($borrower_id1, $item_id1); +@renewcount = C4::Circulation::GetRenewCount( $borrower_id1, $item_id1 ); is_deeply( \@renewcount, [ 2, 0, 0, 0, 0, 0 ], @@ -384,7 +397,7 @@ Koha::CirculationRules->set_rules( } } ); -@renewcount = C4::Circulation::GetRenewCount($borrower_id1, $item_id1); +@renewcount = C4::Circulation::GetRenewCount( $borrower_id1, $item_id1 ); is_deeply( \@renewcount, [ 2, 3, 1, 0, 0, 0 ], @@ -400,7 +413,7 @@ AddRenewal( lastreneweddate => $daysago10 } ); -@renewcount = C4::Circulation::GetRenewCount($borrower_id1, $item_id1); +@renewcount = C4::Circulation::GetRenewCount( $borrower_id1, $item_id1 ); is_deeply( \@renewcount, [ 3, 3, 0, 0, 0, 0 ], @@ -409,34 +422,38 @@ is_deeply( $dbh->do("DELETE FROM old_issues"); AddReturn($barcode_1); -my $return = $dbh->selectrow_hashref("SELECT DATE(returndate) AS return_date, CURRENT_DATE() AS today FROM old_issues LIMIT 1" ); +my $return = + $dbh->selectrow_hashref("SELECT DATE(returndate) AS return_date, CURRENT_DATE() AS today FROM old_issues LIMIT 1"); ok( $return->{return_date} eq $return->{today}, "Item returned with no return date specified has todays date" ); $dbh->do("DELETE FROM old_issues"); C4::Circulation::AddIssue( $patron_1, $barcode_1, $daysago10, 0, $today ); -AddReturn($barcode_1, undef, undef, dt_from_string('2014-04-01 23:42')); -$return = $dbh->selectrow_hashref("SELECT * FROM old_issues LIMIT 1" ); -ok( $return->{returndate} eq '2014-04-01 23:42:00', "Item returned with a return date of '2014-04-01 23:42' has that return date" ); +AddReturn( $barcode_1, undef, undef, dt_from_string('2014-04-01 23:42') ); +$return = $dbh->selectrow_hashref("SELECT * FROM old_issues LIMIT 1"); +ok( + $return->{returndate} eq '2014-04-01 23:42:00', + "Item returned with a return date of '2014-04-01 23:42' has that return date" +); my $itemnumber = Koha::Item->new( { - biblionumber => $biblionumber, - barcode => 'barcode_3', - itemcallnumber => 'callnumber3', - homebranch => $branchcode_1, - holdingbranch => $branchcode_1, - notforloan => 1, - itype => $itemtype, + biblionumber => $biblionumber, + barcode => 'barcode_3', + itemcallnumber => 'callnumber3', + homebranch => $branchcode_1, + holdingbranch => $branchcode_1, + notforloan => 1, + itype => $itemtype, biblioitemnumber => $biblioitemnumber }, )->store->itemnumber; t::lib::Mocks::mock_preference( 'UpdateNotForLoanStatusOnCheckin', q{} ); -t::lib::Mocks::mock_preference( 'CataloguingLog', 1 ); -my $log_count_before = $schema->resultset('ActionLog')->search({module => 'CATALOGUING'})->count(); +t::lib::Mocks::mock_preference( 'CataloguingLog', 1 ); +my $log_count_before = $schema->resultset('ActionLog')->search( { module => 'CATALOGUING' } )->count(); AddReturn( 'barcode_3', $branchcode_1 ); -my $item = Koha::Items->find( $itemnumber ); +my $item = Koha::Items->find($itemnumber); ok( $item->notforloan eq 1, 'UpdateNotForLoanStatusOnCheckin does not modify value when not enabled' ); my $updatenotforloanstatusoncheckin = " @@ -448,21 +465,27 @@ $itemtype:\n "; t::lib::Mocks::mock_preference( 'UpdateNotForLoanStatusOnCheckin', $updatenotforloanstatusoncheckin ); AddReturn( 'barcode_3', $branchcode_1 ); -$item = Koha::Items->find( $itemnumber ); +$item = Koha::Items->find($itemnumber); ok( $item->notforloan eq 9, q{UpdateNotForLoanStatusOnCheckin prioritises item type specific rule over _ALL_ rules} ); -my $log_count_after = $schema->resultset('ActionLog')->search({module => 'CATALOGUING'})->count(); -is($log_count_before, $log_count_after, "Change from UpdateNotForLoanStatusOnCheckin is not logged"); +my $log_count_after = $schema->resultset('ActionLog')->search( { module => 'CATALOGUING' } )->count(); +is( $log_count_before, $log_count_after, "Change from UpdateNotForLoanStatusOnCheckin is not logged" ); AddReturn( 'barcode_3', $branchcode_1 ); -$item = Koha::Items->find( $itemnumber ); -ok( $item->notforloan eq 9, q{UpdateNotForLoanStatusOnCheckin uses item type specific rules even if they do not target the returned items' notforloan value} ); +$item = Koha::Items->find($itemnumber); +ok( + $item->notforloan eq 9, + q{UpdateNotForLoanStatusOnCheckin uses item type specific rules even if they do not target the returned items' notforloan value} +); # Change the returning item to an item type without a rule -Koha::Items->find( $itemnumber )->itype( $itemtype2 )->store; -Koha::Items->find( $itemnumber )->notforloan( 1 )->store; +Koha::Items->find($itemnumber)->itype($itemtype2)->store; +Koha::Items->find($itemnumber)->notforloan(1)->store; AddReturn( 'barcode_3', $branchcode_1 ); -$item = Koha::Items->find( $itemnumber ); -ok( $item->notforloan eq 0, q{UpdateNotForLoanStatusOnCheckin _ALL_ rules are applied if there are no specific item type rule matching the returned item} ); +$item = Koha::Items->find($itemnumber); +ok( + $item->notforloan eq 0, + q{UpdateNotForLoanStatusOnCheckin _ALL_ rules are applied if there are no specific item type rule matching the returned item} +); t::lib::Mocks::mock_preference( 'UpdateNotForLoanStatusOnCheckin', q{_ALL_: @@ -477,9 +500,8 @@ is( q{UpdateNotForLoanStatusOnCheckin does not update notforloan value from 1 for _ALL_ with setting "1: ONLYMESSAGE"} ); - t::lib::Mocks::mock_preference( - 'UpdateNotForLoanStatusOnCheckin', "$itemtype:\n + 'UpdateNotForLoanStatusOnCheckin', "$itemtype:\n 1: ONLYMESSAGE " ); @@ -506,52 +528,87 @@ t::lib::Mocks::mock_preference( 'UpdateItemLocationOnCheckout', q{} ); t::lib::Mocks::mock_preference( 'UpdateItemLocationOnCheckin', q{} ); AddReturn( 'barcode_4', $branchcode_1 ); -my $item2 = Koha::Items->find( $itemnumber2 ); +my $item2 = Koha::Items->find($itemnumber2); ok( $item2->location eq 'FIC', 'UpdateItemLocationOnCheckin does not modify value when not enabled' ); t::lib::Mocks::mock_preference( 'UpdateItemLocationOnCheckin', 'FIC: GEN' ); -$log_count_before = $schema->resultset('ActionLog')->search({module => 'CATALOGUING'})->count(); +$log_count_before = $schema->resultset('ActionLog')->search( { module => 'CATALOGUING' } )->count(); AddReturn( 'barcode_4', $branchcode_1 ); -$item2 = Koha::Items->find( $itemnumber2 ); -is( $item2->location, 'GEN', q{UpdateItemLocationOnCheckin updates location value from 'FIC' to 'GEN' with setting "FIC: GEN"} ); -is( $item2->permanent_location, 'GEN', q{UpdateItemLocationOnCheckin updates permanent_location value from 'FIC' to 'GEN' with setting "FIC: GEN"} ); -$log_count_after = $schema->resultset('ActionLog')->search({module => 'CATALOGUING'})->count(); -is($log_count_before, $log_count_after, "Change from UpdateNotForLoanStatusOnCheckin is not logged"); +$item2 = Koha::Items->find($itemnumber2); +is( + $item2->location, 'GEN', + q{UpdateItemLocationOnCheckin updates location value from 'FIC' to 'GEN' with setting "FIC: GEN"} +); +is( + $item2->permanent_location, 'GEN', + q{UpdateItemLocationOnCheckin updates permanent_location value from 'FIC' to 'GEN' with setting "FIC: GEN"} +); +$log_count_after = $schema->resultset('ActionLog')->search( { module => 'CATALOGUING' } )->count(); +is( $log_count_before, $log_count_after, "Change from UpdateNotForLoanStatusOnCheckin is not logged" ); AddReturn( 'barcode_4', $branchcode_1 ); -$item2 = Koha::Items->find( $itemnumber2 ); -ok( $item2->location eq 'GEN', q{UpdateItemLocationOnCheckin does not update location value from 'GEN' with setting "FIC: GEN"} ); +$item2 = Koha::Items->find($itemnumber2); +ok( + $item2->location eq 'GEN', + q{UpdateItemLocationOnCheckin does not update location value from 'GEN' with setting "FIC: GEN"} +); t::lib::Mocks::mock_preference( 'UpdateItemLocationOnCheckin', '_ALL_: CART' ); AddReturn( 'barcode_4', $branchcode_1 ); -$item2 = Koha::Items->find( $itemnumber2 ); -ok( $item2->location eq 'CART', q{UpdateItemLocationOnCheckin updates location value from 'GEN' with setting "_ALL_: CART"} ); -Koha::Item::Transfer->new({ - itemnumber => $itemnumber2, - frombranch => $branchcode_2, - tobranch => $branchcode_1, - datesent => '2020-01-01' -})->store; +$item2 = Koha::Items->find($itemnumber2); +ok( + $item2->location eq 'CART', + q{UpdateItemLocationOnCheckin updates location value from 'GEN' with setting "_ALL_: CART"} +); +Koha::Item::Transfer->new( + { + itemnumber => $itemnumber2, + frombranch => $branchcode_2, + tobranch => $branchcode_1, + datesent => '2020-01-01' + } +)->store; AddReturn( 'barcode_4', $branchcode_1 ); -$item2 = Koha::Items->find( $itemnumber2 ); -ok( $item2->location eq 'CART', q{UpdateItemLocationOnCheckin updates location value from 'GEN' with setting "_ALL_: CART" when transfer filled} ); +$item2 = Koha::Items->find($itemnumber2); +ok( + $item2->location eq 'CART', + q{UpdateItemLocationOnCheckin updates location value from 'GEN' with setting "_ALL_: CART" when transfer filled} +); -ok( $item2->permanent_location eq 'GEN', q{UpdateItemLocationOnCheckin does not update permanent_location value from 'GEN' with setting "_ALL_: CART"} ); -AddIssue( $patron_1, 'barcode_4', $daysago10,0, $today, '' ); -$item2 = Koha::Items->find( $itemnumber2 ); +ok( + $item2->permanent_location eq 'GEN', + q{UpdateItemLocationOnCheckin does not update permanent_location value from 'GEN' with setting "_ALL_: CART"} +); +AddIssue( $patron_1, 'barcode_4', $daysago10, 0, $today, '' ); +$item2 = Koha::Items->find($itemnumber2); ok( $item2->location eq 'GEN', q{Location updates from 'CART' to permanent location on issue} ); t::lib::Mocks::mock_preference( 'UpdateItemLocationOnCheckin', "GEN: _BLANK_\n_BLANK_: PROC\nPROC: _PERM_" ); AddReturn( 'barcode_4', $branchcode_1 ); -$item2 = Koha::Items->find( $itemnumber2 ); -ok( $item2->location eq '', q{UpdateItemLocationOnCheckin updates location value from 'GEN' to '' with setting "GEN: _BLANK_"} ); +$item2 = Koha::Items->find($itemnumber2); +ok( + $item2->location eq '', + q{UpdateItemLocationOnCheckin updates location value from 'GEN' to '' with setting "GEN: _BLANK_"} +); AddReturn( 'barcode_4', $branchcode_1 ); -$item2 = Koha::Items->find( $itemnumber2 ); -ok( $item2->location eq 'PROC' , q{UpdateItemLocationOnCheckin updates location value from '' to 'PROC' with setting "_BLANK_: PROC"} ); -ok( $item2->permanent_location eq '' , q{UpdateItemLocationOnCheckin does not update permanent_location value from '' to 'PROC' with setting "_BLANK_: PROC"} ); +$item2 = Koha::Items->find($itemnumber2); +ok( + $item2->location eq 'PROC', + q{UpdateItemLocationOnCheckin updates location value from '' to 'PROC' with setting "_BLANK_: PROC"} +); +ok( + $item2->permanent_location eq '', + q{UpdateItemLocationOnCheckin does not update permanent_location value from '' to 'PROC' with setting "_BLANK_: PROC"} +); AddReturn( 'barcode_4', $branchcode_1 ); -$item2 = Koha::Items->find( $itemnumber2 ); -ok( $item2->location eq '' , q{UpdateItemLocationOnCheckin updates location value from 'PROC' to '' with setting "PROC: _PERM_" } ); -ok( $item2->permanent_location eq '' , q{UpdateItemLocationOnCheckin does not update permanent_location from '' with setting "PROC: _PERM_" } ); +$item2 = Koha::Items->find($itemnumber2); +ok( + $item2->location eq '', + q{UpdateItemLocationOnCheckin updates location value from 'PROC' to '' with setting "PROC: _PERM_" } +); +ok( + $item2->permanent_location eq '', + q{UpdateItemLocationOnCheckin does not update permanent_location from '' with setting "PROC: _PERM_" } +); # Bug 28472 my $itemnumber3 = Koha::Item->new( @@ -568,13 +625,14 @@ my $itemnumber3 = Koha::Item->new( t::lib::Mocks::mock_preference( 'UpdateItemLocationOnCheckin', '_ALL_: CART' ); AddReturn( 'barcode_5', $branchcode_1 ); -my $item3 = Koha::Items->find( $itemnumber3 ); -is( $item3->location, 'CART', q{UpdateItemLocationOnCheckin updates location value from NULL (i.e. the item has no shelving location set) to 'CART' with setting "_ALL_: CART"} ); - - +my $item3 = Koha::Items->find($itemnumber3); +is( + $item3->location, 'CART', + q{UpdateItemLocationOnCheckin updates location value from NULL (i.e. the item has no shelving location set) to 'CART' with setting "_ALL_: CART"} +); # Bug 14640 - Cancel the hold on checking out if asked -Koha::Items->find({ barcode => $barcode_1 })->notforloan('0')->store; +Koha::Items->find( { barcode => $barcode_1 } )->notforloan('0')->store; my $reserve_id = AddReserve( { branchcode => $branchcode_1, @@ -587,11 +645,12 @@ my $reserve_id = AddReserve( ); ok( $reserve_id, 'The reserve should have been inserted' ); AddIssue( $patron_2, $barcode_1, dt_from_string, 'cancel' ); -my $hold = Koha::Holds->find( $reserve_id ); +my $hold = Koha::Holds->find($reserve_id); is( $hold, undef, 'The reserve should have been correctly cancelled' ); # Unseen rewnewals -t::lib::Mocks::mock_preference('UnseenRenewals', 1); +t::lib::Mocks::mock_preference( 'UnseenRenewals', 1 ); + # Add a default circ rule: 3 unseen renewals allowed Koha::CirculationRules->set_rules( { @@ -599,7 +658,7 @@ Koha::CirculationRules->set_rules( itemtype => undef, branchcode => undef, rules => { - renewalsallowed => 10, + renewalsallowed => 10, unseen_renewals_allowed => 3 } } @@ -607,12 +666,11 @@ Koha::CirculationRules->set_rules( my $unseen_library = $builder->build_object( { class => 'Koha::Libraries' } ); my $unseen_patron = $builder->build_object( { class => 'Koha::Patrons' } ); -my $unseen_item = $builder->build_sample_item( - { library => $unseen_library->branchcode, itype => $itemtype } ); -my $unseen_issue = C4::Circulation::AddIssue( $unseen_patron, $unseen_item->barcode ); +my $unseen_item = $builder->build_sample_item( { library => $unseen_library->branchcode, itype => $itemtype } ); +my $unseen_issue = C4::Circulation::AddIssue( $unseen_patron, $unseen_item->barcode ); # Does an unseen renewal increment the issue's count -my ( $unseen_before ) = ( C4::Circulation::GetRenewCount( $unseen_patron->borrowernumber, $unseen_item->itemnumber ) )[3]; +my ($unseen_before) = ( C4::Circulation::GetRenewCount( $unseen_patron->borrowernumber, $unseen_item->itemnumber ) )[3]; AddRenewal( { borrowernumber => $unseen_patron->borrowernumber, @@ -621,7 +679,7 @@ AddRenewal( seen => 0 } ); -my ( $unseen_after ) = ( C4::Circulation::GetRenewCount( $unseen_patron->borrowernumber, $unseen_item->itemnumber ) )[3]; +my ($unseen_after) = ( C4::Circulation::GetRenewCount( $unseen_patron->borrowernumber, $unseen_item->itemnumber ) )[3]; is( $unseen_after, $unseen_before + 1, 'unseen_renewals increments' ); # Does a seen renewal reset the unseen count @@ -633,7 +691,7 @@ AddRenewal( seen => 1 } ); -my ( $unseen_reset ) = ( C4::Circulation::GetRenewCount( $unseen_patron->borrowernumber, $unseen_item->itemnumber ) )[3]; +my ($unseen_reset) = ( C4::Circulation::GetRenewCount( $unseen_patron->borrowernumber, $unseen_item->itemnumber ) )[3]; is( $unseen_reset, 0, 'seen renewal resets the unseen count' ); my $itemnumber4 = Koha::Item->new( @@ -651,19 +709,25 @@ my $itemnumber4 = Koha::Item->new( t::lib::Mocks::mock_preference( 'UpdateNotForLoanStatusOnCheckout', q{} ); AddIssue( $patron_2, 'barcode_6', dt_from_string ); -$item = Koha::Items->find( $itemnumber4 ); +$item = Koha::Items->find($itemnumber4); ok( $item->notforloan eq -1, 'UpdateNotForLoanStatusOnCheckout does not modify value when not enabled' ); t::lib::Mocks::mock_preference( 'UpdateNotForLoanStatusOnCheckout', '-1: 0' ); AddReturn( 'barcode_6', $branchcode_1 ); my $test = AddIssue( $patron_2, 'barcode_6', dt_from_string ); -$item = Koha::Items->find( $itemnumber4 ); -ok( $item->notforloan eq 0, q{UpdateNotForLoanStatusOnCheckout updates notforloan value from -1 to 0 with setting "-1: 0"} ); +$item = Koha::Items->find($itemnumber4); +ok( + $item->notforloan eq 0, + q{UpdateNotForLoanStatusOnCheckout updates notforloan value from -1 to 0 with setting "-1: 0"} +); AddIssue( $patron_2, 'barcode_6', dt_from_string ); AddReturn( 'barcode_6', $branchcode_1 ); -$item = Koha::Items->find( $itemnumber4 ); -ok( $item->notforloan eq 0, q{UpdateNotForLoanStatusOnCheckout does not update notforloan value from 0 with setting "-1: 0"} ); +$item = Koha::Items->find($itemnumber4); +ok( + $item->notforloan eq 0, + q{UpdateNotForLoanStatusOnCheckout does not update notforloan value from 0 with setting "-1: 0"} +); # Bug 21159 - Update item shelving location on checkout my $itemnumber5 = Koha::Item->new( diff --git a/t/db_dependent/Circulation/maxsuspensiondays.t b/t/db_dependent/Circulation/maxsuspensiondays.t index 614a32303a..f8c8b61f2a 100755 --- a/t/db_dependent/Circulation/maxsuspensiondays.t +++ b/t/db_dependent/Circulation/maxsuspensiondays.t @@ -6,9 +6,9 @@ use MARC::Field; use C4::Context; use C4::Circulation qw( AddIssue AddReturn ); -use C4::Biblio qw( AddBiblio ); +use C4::Biblio qw( AddBiblio ); use Koha::Database; -use Koha::DateUtils qw( dt_from_string output_pref ); +use Koha::DateUtils qw( dt_from_string output_pref ); use Koha::Patron::Debarments qw( DelDebarment ); use Koha::Patrons; @@ -18,13 +18,13 @@ use t::lib::Mocks; my $schema = Koha::Database->schema; $schema->storage->txn_begin; my $builder = t::lib::TestBuilder->new; -my $dbh = C4::Context->dbh; +my $dbh = C4::Context->dbh; -my $branchcode = $builder->build({ source => 'Branch' })->{branchcode}; -my $itemtype = $builder->build({ source => 'Itemtype' })->{itemtype}; -my $patron_category = $builder->build({ source => 'Category' }); +my $branchcode = $builder->build( { source => 'Branch' } )->{branchcode}; +my $itemtype = $builder->build( { source => 'Itemtype' } )->{itemtype}; +my $patron_category = $builder->build( { source => 'Category' } ); -t::lib::Mocks::mock_userenv({ branchcode => $branchcode }); +t::lib::Mocks::mock_userenv( { branchcode => $branchcode } ); # Test without maxsuspensiondays set Koha::CirculationRules->search->delete; @@ -34,52 +34,56 @@ Koha::CirculationRules->set_rules( itemtype => undef, branchcode => undef, rules => { - firstremind => 0, - finedays => 2, - lengthunit => 'days', + firstremind => 0, + finedays => 2, + lengthunit => 'days', suspension_chargeperiod => 1, } } ); -my $patron = Koha::Patron->new({ - firstname => 'my firstname', - surname => 'my surname', - categorycode => $patron_category->{categorycode}, - branchcode => $branchcode, -})->store; +my $patron = Koha::Patron->new( + { + firstname => 'my firstname', + surname => 'my surname', + categorycode => $patron_category->{categorycode}, + branchcode => $branchcode, + } +)->store; my $record = MARC::Record->new(); $record->append_fields( - MARC::Field->new('100', ' ', ' ', a => 'My author'), - MARC::Field->new('245', ' ', ' ', a => 'My title'), + MARC::Field->new( '100', ' ', ' ', a => 'My author' ), + MARC::Field->new( '245', ' ', ' ', a => 'My title' ), ); my $barcode = 'bc_maxsuspensiondays'; -my ($biblionumber, $biblioitemnumber) = AddBiblio($record, ''); -my $itemnumber = Koha::Item->new({ - biblionumber => $biblionumber, - homebranch => $branchcode, +my ( $biblionumber, $biblioitemnumber ) = AddBiblio( $record, '' ); +my $itemnumber = Koha::Item->new( + { + biblionumber => $biblionumber, + homebranch => $branchcode, holdingbranch => $branchcode, - barcode => $barcode, - itype => $itemtype - })->store->itemnumber; + barcode => $barcode, + itype => $itemtype + } +)->store->itemnumber; # clear any holidays to avoid throwing off the suspension day # calculations $dbh->do('DELETE FROM special_holidays'); $dbh->do('DELETE FROM repeatable_holidays'); -my $daysago20 = dt_from_string->add_duration(DateTime::Duration->new(days => -20)); -my $daysafter40 = dt_from_string->add_duration(DateTime::Duration->new(days => 40)); +my $daysago20 = dt_from_string->add_duration( DateTime::Duration->new( days => -20 ) ); +my $daysafter40 = dt_from_string->add_duration( DateTime::Duration->new( days => 40 ) ); AddIssue( $patron, $barcode, $daysago20 ); AddReturn( $barcode, $branchcode ); -my $debarments = $patron->restrictions; +my $debarments = $patron->restrictions; my $THE_debarment = $debarments->next; is( $THE_debarment->expiration, - output_pref({ dt => $daysafter40, dateformat => 'iso', dateonly => 1 }), + output_pref( { dt => $daysafter40, dateformat => 'iso', dateonly => 1 } ), 'calculate suspension with no maximum set' ); DelDebarment( $THE_debarment->borrower_debarment_id ); @@ -96,14 +100,14 @@ Koha::CirculationRules->set_rules( } ); -my $daysafter10 = dt_from_string->add_duration(DateTime::Duration->new(days => 10)); +my $daysafter10 = dt_from_string->add_duration( DateTime::Duration->new( days => 10 ) ); AddIssue( $patron, $barcode, $daysago20 ); AddReturn( $barcode, $branchcode ); -$debarments = $patron->restrictions; +$debarments = $patron->restrictions; $THE_debarment = $debarments->next; is( $THE_debarment->expiration, - output_pref({ dt => $daysafter10, dateformat => 'iso', dateonly => 1 }), + output_pref( { dt => $daysafter10, dateformat => 'iso', dateonly => 1 } ), 'calculate suspension with a maximum set' ); DelDebarment( $THE_debarment->borrower_debarment_id ); @@ -115,22 +119,24 @@ subtest "suspension_chargeperiod" => sub { itemtype => undef, branchcode => undef, rules => { - firstremind => 0, - finedays => 7, - lengthunit => 'days', + firstremind => 0, + finedays => 7, + lengthunit => 'days', suspension_chargeperiod => 15, - maxsuspensiondays => 333, + maxsuspensiondays => 333, } } ); - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); - my $item = $builder->build_sample_item; + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + my $item = $builder->build_sample_item; - my $last_year = dt_from_string->clone->subtract( years => 1 ); - my $today = dt_from_string; + my $last_year = dt_from_string->clone->subtract( years => 1 ); + my $today = dt_from_string; my $new_debar_dt = C4::Circulation::_calculate_new_debar_dt( $patron, $item, $last_year, $today ); - is( $new_debar_dt->truncate( to => 'day' ), - $today->clone->add( days => 365 / 15 * 7 )->truncate( to => 'day' ) ); + is( + $new_debar_dt->truncate( to => 'day' ), + $today->clone->add( days => 365 / 15 * 7 )->truncate( to => 'day' ) + ); }; @@ -141,22 +147,24 @@ subtest "maxsuspensiondays" => sub { itemtype => undef, branchcode => undef, rules => { - firstremind => 0, - finedays => 15, - lengthunit => 'days', + firstremind => 0, + finedays => 15, + lengthunit => 'days', suspension_chargeperiod => 7, - maxsuspensiondays => 333, + maxsuspensiondays => 333, } } ); - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); - my $item = $builder->build_sample_item; + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + my $item = $builder->build_sample_item; - my $last_year = dt_from_string->clone->subtract( years => 1 ); - my $today = dt_from_string; + my $last_year = dt_from_string->clone->subtract( years => 1 ); + my $today = dt_from_string; my $new_debar_dt = C4::Circulation::_calculate_new_debar_dt( $patron, $item, $last_year, $today ); - is( $new_debar_dt->truncate( to => 'day' ), - $today->clone->add( days => 333 )->truncate( to => 'day' ) ); + is( + $new_debar_dt->truncate( to => 'day' ), + $today->clone->add( days => 333 )->truncate( to => 'day' ) + ); }; $schema->storage->txn_rollback; diff --git a/t/db_dependent/Circulation/transferbook.t b/t/db_dependent/Circulation/transferbook.t index 78ca0b34c8..ad447dc0a6 100755 --- a/t/db_dependent/Circulation/transferbook.t +++ b/t/db_dependent/Circulation/transferbook.t @@ -22,12 +22,12 @@ use t::lib::TestBuilder; use t::lib::Mocks; use C4::Circulation qw( transferbook AddIssue ); -use C4::Reserves qw( AddReserve ); +use C4::Reserves qw( AddReserve ); use Koha::DateUtils qw( dt_from_string ); use Koha::Item::Transfers; my $builder = t::lib::TestBuilder->new; -my $schema = Koha::Database->new->schema; +my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; @@ -42,13 +42,14 @@ subtest 'transfer a non-existant item' => sub { $item->delete; my $trigger = "Manual"; - my ( $dotransfer, $messages ) = - C4::Circulation::transferbook({ - from_branch => $item->homebranch, - to_branch => $library->{branchcode}, - barcode => $badbc, - trigger => $trigger - }); + my ( $dotransfer, $messages ) = C4::Circulation::transferbook( + { + from_branch => $item->homebranch, + to_branch => $library->{branchcode}, + barcode => $badbc, + trigger => $trigger + } + ); is( $dotransfer, 0, "Can't transfer a bad barcode" ); is_deeply( $messages, @@ -79,12 +80,14 @@ subtest 'field population tests' => sub { ); my $trigger = "Manual"; - my ($dotransfer, $messages ) = transferbook({ - from_branch => $item->homebranch, - to_branch => $library2->branchcode, - barcode => $item->barcode, - trigger => $trigger - }); + my ( $dotransfer, $messages ) = transferbook( + { + from_branch => $item->homebranch, + to_branch => $library2->branchcode, + barcode => $item->barcode, + trigger => $trigger + } + ); is( $dotransfer, 1, 'Transfer succeeded' ); is_deeply( $messages, @@ -92,13 +95,13 @@ subtest 'field population tests' => sub { "WasTransfered was set correctly" ); - my $transfers = Koha::Item::Transfers->search({ itemnumber => $item->itemnumber, datearrived => undef }); - is( $transfers->count, 1, 'One transfer created'); + my $transfers = Koha::Item::Transfers->search( { itemnumber => $item->itemnumber, datearrived => undef } ); + is( $transfers->count, 1, 'One transfer created' ); my $transfer = $transfers->next; - is ($transfer->frombranch, $library->branchcode, 'frombranch set correctly'); - is ($transfer->tobranch, $library2->branchcode, 'tobranch set correctly'); - is ($transfer->reason, $trigger, 'reason set if passed'); + is( $transfer->frombranch, $library->branchcode, 'frombranch set correctly' ); + is( $transfer->tobranch, $library2->branchcode, 'tobranch set correctly' ); + is( $transfer->reason, $trigger, 'reason set if passed' ); }; #FIXME:'UseBranchTransferLimits tests missing @@ -116,20 +119,22 @@ subtest 'transfer already at destination' => sub { } ); - my $itemtype = $builder->build_object({ class => 'Koha::ItemTypes' })->store->itemtype; - my $item = $builder->build_sample_item( + my $itemtype = $builder->build_object( { class => 'Koha::ItemTypes' } )->store->itemtype; + my $item = $builder->build_sample_item( { library => $library->branchcode, - itype => $itemtype + itype => $itemtype } ); - my ($dotransfer, $messages ) = transferbook({ - from_branch => $item->homebranch, - to_branch => $library->branchcode, - barcode => $item->barcode, - trigger => "Manual" - }); + my ( $dotransfer, $messages ) = transferbook( + { + from_branch => $item->homebranch, + to_branch => $library->branchcode, + barcode => $item->barcode, + trigger => "Manual" + } + ); is( $dotransfer, 0, 'Transfer of item failed when destination equals holding branch' ); is_deeply( $messages, @@ -140,27 +145,32 @@ subtest 'transfer already at destination' => sub { # We are making sure there is no regression, feel free to change the behavior if needed. # * Contrary to the POD, if ignore_reserves is not passed (or is false), any item reserve # found will override all other measures that may prevent transfer and force a transfer. - AddReserve({ - branchcode => $item->homebranch, - borrowernumber => $patron->borrowernumber, - biblionumber => $item->biblionumber, - itemnumber => $item->itemnumber, - }); + AddReserve( + { + branchcode => $item->homebranch, + borrowernumber => $patron->borrowernumber, + biblionumber => $item->biblionumber, + itemnumber => $item->itemnumber, + } + ); - ($dotransfer, $messages ) = transferbook({ - from_branch => $item->homebranch, - to_branch => $library->branchcode, - barcode => $item->barcode, - trigger => "Manual" - }); - is( $dotransfer, 0, 'Transfer of reserved item doesn\'t succeed without ignore_reserves' ); - is( $messages->{ResFound}->{ResFound}, 'Reserved', "We found the reserve"); - is( $messages->{ResFound}->{itemnumber}, $item->itemnumber, "We got the reserve info"); + ( $dotransfer, $messages ) = transferbook( + { + from_branch => $item->homebranch, + to_branch => $library->branchcode, + barcode => $item->barcode, + trigger => "Manual" + } + ); + is( $dotransfer, 0, 'Transfer of reserved item doesn\'t succeed without ignore_reserves' ); + is( $messages->{ResFound}->{ResFound}, 'Reserved', "We found the reserve" ); + is( $messages->{ResFound}->{itemnumber}, $item->itemnumber, "We got the reserve info" ); # recalls - t::lib::Mocks::mock_preference('UseRecalls', 1); + t::lib::Mocks::mock_preference( 'UseRecalls', 1 ); my $recall = Koha::Recall->new( - { biblio_id => $item->biblionumber, + { + biblio_id => $item->biblionumber, item_id => $item->itemnumber, item_level => 1, patron_id => $patron->borrowernumber, @@ -168,13 +178,15 @@ subtest 'transfer already at destination' => sub { } )->store; ( $recall, $dotransfer, $messages ) = $recall->start_transfer; - is( $dotransfer, 0, 'Do not transfer recalled item, it has already arrived' ); - is( $messages->{RecallPlacedAtHoldingBranch}, 1, "We found the recall"); + is( $dotransfer, 0, 'Do not transfer recalled item, it has already arrived' ); + is( $messages->{RecallPlacedAtHoldingBranch}, 1, "We found the recall" ); - $itemtype = $builder->build_object({ class => 'Koha::ItemTypes' })->store->itemtype; - my $item2 = $builder->build_object({ class => 'Koha::Items', value => { itype => $itemtype } }); # this item will have a different holding branch to the pickup branch + $itemtype = $builder->build_object( { class => 'Koha::ItemTypes' } )->store->itemtype; + my $item2 = $builder->build_object( { class => 'Koha::Items', value => { itype => $itemtype } } ) + ; # this item will have a different holding branch to the pickup branch $recall = Koha::Recall->new( - { biblio_id => $item2->biblionumber, + { + biblio_id => $item2->biblionumber, item_id => $item2->itemnumber, item_level => 1, patron_id => $patron->borrowernumber, @@ -182,8 +194,8 @@ subtest 'transfer already at destination' => sub { } )->store; ( $recall, $dotransfer, $messages ) = $recall->start_transfer; - is( $dotransfer, 1, 'Transfer of recalled item succeeded' ); - is( $messages->{RecallFound}->id, $recall->id, "We found the recall"); + is( $dotransfer, 1, 'Transfer of recalled item succeeded' ); + is( $messages->{RecallFound}->id, $recall->id, "We found the recall" ); }; subtest 'transfer an issued item' => sub { @@ -199,11 +211,11 @@ subtest 'transfer an issued item' => sub { } ); - my $itemtype = $builder->build_object({ class => 'Koha::ItemTypes' })->store->itemtype; - my $item = $builder->build_sample_item( + my $itemtype = $builder->build_object( { class => 'Koha::ItemTypes' } )->store->itemtype; + my $item = $builder->build_sample_item( { library => $library->branchcode, - itype => $itemtype + itype => $itemtype } ); @@ -213,13 +225,18 @@ subtest 'transfer an issued item' => sub { # We are making sure there is no regression, feel free to change the behavior if needed. # * WasReturned does not seem like a variable that should contain a borrowernumber # * Should we return even if the transfer did not happen? (same branches) - my ($dotransfer, $messages) = transferbook({ - from_branch => $item->homebranch, - to_branch => $library->branchcode, - barcode => $item->barcode, - trigger => "Manual" - }); - is( $messages->{WasReturned}, $patron->borrowernumber, 'transferbook should have return a WasReturned flag is the item was issued before the transferbook call'); + my ( $dotransfer, $messages ) = transferbook( + { + from_branch => $item->homebranch, + to_branch => $library->branchcode, + barcode => $item->barcode, + trigger => "Manual" + } + ); + is( + $messages->{WasReturned}, $patron->borrowernumber, + 'transferbook should have return a WasReturned flag is the item was issued before the transferbook call' + ); # Reset issue $issue = AddIssue( $patron, $item->barcode, $dt_to ); @@ -227,28 +244,32 @@ subtest 'transfer an issued item' => sub { # We are making sure there is no regression, feel free to change the behavior if needed. # * Contrary to the POD, if ignore_reserves is not passed (or is false), any item reserve # found will override all other measures that may prevent transfer and force a transfer. - AddReserve({ - branchcode => $item->homebranch, - borrowernumber => $patron->borrowernumber, - biblionumber => $item->biblionumber, - itemnumber => $item->itemnumber, - }); + AddReserve( + { + branchcode => $item->homebranch, + borrowernumber => $patron->borrowernumber, + biblionumber => $item->biblionumber, + itemnumber => $item->itemnumber, + } + ); - ($dotransfer, $messages ) = transferbook({ - from_branch => $item->homebranch, - to_branch => $library->branchcode, - barcode => $item->barcode, - trigger => "Manual" - }); - is( $dotransfer, 0, 'Transfer of reserved item doesn\'t succeed without ignore_reserves' ); - is( $messages->{ResFound}->{ResFound}, 'Reserved', "We found the reserve"); - is( $messages->{ResFound}->{itemnumber}, $item->itemnumber, "We got the reserve info"); - is( $messages->{WasReturned}, $patron->borrowernumber, "We got the return info"); + ( $dotransfer, $messages ) = transferbook( + { + from_branch => $item->homebranch, + to_branch => $library->branchcode, + barcode => $item->barcode, + trigger => "Manual" + } + ); + is( $dotransfer, 0, 'Transfer of reserved item doesn\'t succeed without ignore_reserves' ); + is( $messages->{ResFound}->{ResFound}, 'Reserved', "We found the reserve" ); + is( $messages->{ResFound}->{itemnumber}, $item->itemnumber, "We got the reserve info" ); + is( $messages->{WasReturned}, $patron->borrowernumber, "We got the return info" ); }; subtest 'ignore_reserves flag' => sub { plan tests => 9; - my $library = $builder->build_object( { class => 'Koha::Libraries' } )->store; + my $library = $builder->build_object( { class => 'Koha::Libraries' } )->store; my $library2 = $builder->build_object( { class => 'Koha::Libraries' } )->store; t::lib::Mocks::mock_userenv( { branchcode => $library->branchcode } ); @@ -265,75 +286,93 @@ subtest 'ignore_reserves flag' => sub { } ); - AddReserve({ - branchcode => $item->homebranch, - borrowernumber => $patron->borrowernumber, - biblionumber => $item->biblionumber, - itemnumber => $item->itemnumber, - }); + AddReserve( + { + branchcode => $item->homebranch, + borrowernumber => $patron->borrowernumber, + biblionumber => $item->biblionumber, + itemnumber => $item->itemnumber, + } + ); # We are making sure there is no regression, feel free to change the behavior if needed. # * Contrary to the POD, if ignore_reserves is not passed (or is false), any item reserve # found will override all other measures that may prevent transfer and force a transfer. - my ($dotransfer, $messages ) = transferbook({ - from_branch => $item->homebranch, - to_branch => $library2->branchcode, - barcode => $item->barcode, - trigger => "Manual" - }); - is( $dotransfer, 0, 'Transfer of reserved item doesn\'t succeed without ignore_reserves' ); - is( $messages->{ResFound}->{ResFound}, 'Reserved', "We found the reserve"); - is( $messages->{ResFound}->{itemnumber}, $item->itemnumber, "We got the reserve info"); + my ( $dotransfer, $messages ) = transferbook( + { + from_branch => $item->homebranch, + to_branch => $library2->branchcode, + barcode => $item->barcode, + trigger => "Manual" + } + ); + is( $dotransfer, 0, 'Transfer of reserved item doesn\'t succeed without ignore_reserves' ); + is( $messages->{ResFound}->{ResFound}, 'Reserved', "We found the reserve" ); + is( $messages->{ResFound}->{itemnumber}, $item->itemnumber, "We got the reserve info" ); my $ignore_reserves = 0; - ($dotransfer, $messages ) = transferbook({ - from_branch => $item->homebranch, - to_branch => $library2->branchcode, - barcode => $item->barcode, - ignore_reserves => $ignore_reserves, - trigger => "Manual" - }); - is( $dotransfer, 0, 'Transfer of reserved item doesn\'t succeed without ignore_reserves' ); - is( $messages->{ResFound}->{ResFound}, 'Reserved', "We found the reserve"); - is( $messages->{ResFound}->{itemnumber}, $item->itemnumber, "We got the reserve info"); + ( $dotransfer, $messages ) = transferbook( + { + from_branch => $item->homebranch, + to_branch => $library2->branchcode, + barcode => $item->barcode, + ignore_reserves => $ignore_reserves, + trigger => "Manual" + } + ); + is( $dotransfer, 0, 'Transfer of reserved item doesn\'t succeed without ignore_reserves' ); + is( $messages->{ResFound}->{ResFound}, 'Reserved', "We found the reserve" ); + is( $messages->{ResFound}->{itemnumber}, $item->itemnumber, "We got the reserve info" ); $ignore_reserves = 1; - ($dotransfer, $messages ) = transferbook({ - from_branch => $item->homebranch, - to_branch => $library2->branchcode, - barcode => $item->barcode, - ignore_reserves => $ignore_reserves, - trigger => "Manual" - }); - is( $dotransfer, 1, 'Transfer of reserved item succeed with ignore reserves: true' ); - is( $messages->{ResFound}->{ResFound}, 'Reserved', "We found the reserve"); - is( $messages->{ResFound}->{itemnumber}, $item->itemnumber, "We got the reserve info"); + ( $dotransfer, $messages ) = transferbook( + { + from_branch => $item->homebranch, + to_branch => $library2->branchcode, + barcode => $item->barcode, + ignore_reserves => $ignore_reserves, + trigger => "Manual" + } + ); + is( $dotransfer, 1, 'Transfer of reserved item succeed with ignore reserves: true' ); + is( $messages->{ResFound}->{ResFound}, 'Reserved', "We found the reserve" ); + is( $messages->{ResFound}->{itemnumber}, $item->itemnumber, "We got the reserve info" ); }; subtest 'transferbook test from branch' => sub { plan tests => 5; my $library = $builder->build_object( { class => 'Koha::Libraries' } ); - my $item = $builder->build_sample_item(); - ok( $item->holdingbranch ne $library->branchcode && $item->homebranch ne $library->branchcode, "Item is not held or owned by library"); - C4::Circulation::transferbook({ - from_branch => $library->branchcode, - to_branch => $item->homebranch, - barcode => $item->barcode, - trigger => "Manual" - }); + my $item = $builder->build_sample_item(); + ok( + $item->holdingbranch ne $library->branchcode && $item->homebranch ne $library->branchcode, + "Item is not held or owned by library" + ); + C4::Circulation::transferbook( + { + from_branch => $library->branchcode, + to_branch => $item->homebranch, + barcode => $item->barcode, + trigger => "Manual" + } + ); my $transfer = $item->get_transfer; - is( $transfer->frombranch, $library->branchcode, 'The transfer is initiated from the specified branch, not the items home or holdingbranch'); - is( $transfer->tobranch, $item->homebranch, 'The transfer is initiated to the specified branch'); - C4::Circulation::transferbook({ - from_branch => $item->homebranch, - to_branch => $library->branchcode, - barcode => $item->barcode, - trigger => "Manual" - }); + is( + $transfer->frombranch, $library->branchcode, + 'The transfer is initiated from the specified branch, not the items home or holdingbranch' + ); + is( $transfer->tobranch, $item->homebranch, 'The transfer is initiated to the specified branch' ); + C4::Circulation::transferbook( + { + from_branch => $item->homebranch, + to_branch => $library->branchcode, + barcode => $item->barcode, + trigger => "Manual" + } + ); $transfer = $item->get_transfer; - is( $transfer->frombranch, $item->homebranch, 'The transfer is initiated from the specified branch'); - is( $transfer->tobranch, $library->branchcode, 'The transfer is initiated to the specified branch'); + is( $transfer->frombranch, $item->homebranch, 'The transfer is initiated from the specified branch' ); + is( $transfer->tobranch, $library->branchcode, 'The transfer is initiated to the specified branch' ); }; $schema->storage->txn_rollback; diff --git a/t/db_dependent/Circulation/transfers.t b/t/db_dependent/Circulation/transfers.t index ca6c37daa4..458f0b28fb 100755 --- a/t/db_dependent/Circulation/transfers.t +++ b/t/db_dependent/Circulation/transfers.t @@ -18,8 +18,8 @@ use Modern::Perl; use C4::Context; use C4::Circulation qw( CreateBranchTransferLimit DeleteBranchTransferLimits GetTransfersFromTo TransferSlip ); -use C4::Biblio qw( AddBiblio ); -use C4::Items qw( ModItemTransfer ); +use C4::Biblio qw( AddBiblio ); +use C4::Items qw( ModItemTransfer ); use Koha::Database; use Koha::DateUtils qw( dt_from_string ); use DateTime::Duration; @@ -31,15 +31,18 @@ use Test::More tests => 19; use Test::Deep; BEGIN { - use_ok('C4::Circulation', qw( CreateBranchTransferLimit DeleteBranchTransferLimits GetTransfersFromTo TransferSlip )); + use_ok( + 'C4::Circulation', + qw( CreateBranchTransferLimit DeleteBranchTransferLimits GetTransfersFromTo TransferSlip ) + ); } can_ok( 'C4::Circulation', qw( - CreateBranchTransferLimit - DeleteBranchTransferLimits - GetTransfersFromTo - ) + CreateBranchTransferLimit + DeleteBranchTransferLimits + GetTransfersFromTo + ) ); my $schema = Koha::Database->schema; @@ -58,13 +61,13 @@ $dbh->do(q|DELETE FROM branchtransfers|); # Add branches my $branchcode_1 = $builder->build( { source => 'Branch', } )->{branchcode}; my $branchcode_2 = $builder->build( { source => 'Branch', } )->{branchcode}; + # Add itemtype my $itemtype = $builder->build( { source => 'Itemtype' } )->{itemtype}; #Add biblio and items my $record = MARC::Record->new(); -$record->append_fields( - MARC::Field->new( '952', '0', '0', a => $branchcode_1 ) ); +$record->append_fields( MARC::Field->new( '952', '0', '0', a => $branchcode_1 ) ); my ( $biblionumber, $biblioitemnumber ) = C4::Biblio::AddBiblio( $record, '', ); my $item_id1 = Koha::Item->new( @@ -117,8 +120,8 @@ ModItemTransfer( $trigger ); -my $item_obj = Koha::Items->find({ itemnumber => $item_id1 }); -is( $item_obj->holdingbranch, $branchcode_1, "Item should be held at branch that initiates transfer"); +my $item_obj = Koha::Items->find( { itemnumber => $item_id1 } ); +is( $item_obj->holdingbranch, $branchcode_1, "Item should be held at branch that initiates transfer" ); ModItemTransfer( $item_id2, @@ -134,8 +137,8 @@ ModItemTransfer( $branchcode_2, $trigger ); -my $transfer_requested = Koha::Item::Transfers->search( { itemnumber => $item_id3 }, { rows => 1 })->single; -$transfer_requested->set({ daterequested => dt_from_string, datesent => undef })->store; +my $transfer_requested = Koha::Item::Transfers->search( { itemnumber => $item_id3 }, { rows => 1 } )->single; +$transfer_requested->set( { daterequested => dt_from_string, datesent => undef } )->store; # Add a "cancelled" transfer for tests ModItemTransfer( @@ -144,8 +147,9 @@ ModItemTransfer( $branchcode_2, $trigger ); -my $transfer_cancelled = Koha::Item::Transfers->search( { itemnumber => $item_id4 }, { rows => 1 })->single; -$transfer_cancelled->set( { daterequested => dt_from_string, datesent => undef, datecancelled => dt_from_string } )->store; +my $transfer_cancelled = Koha::Item::Transfers->search( { itemnumber => $item_id4 }, { rows => 1 } )->single; +$transfer_cancelled->set( { daterequested => dt_from_string, datesent => undef, datecancelled => dt_from_string } ) + ->store; #Begin Tests #Test CreateBranchTransferLimit @@ -157,19 +161,28 @@ is( 1, "A Branch TransferLimit has been added" ); -is(CreateBranchTransferLimit(),undef, - "Without parameters CreateBranchTransferLimit returns undef"); -is(CreateBranchTransferLimit($branchcode_2),undef, - "With only tobranch CreateBranchTransferLimit returns undef"); -is(CreateBranchTransferLimit(undef,$branchcode_2),undef, - "With only frombranch CreateBranchTransferLimit returns undef"); +is( + CreateBranchTransferLimit(), undef, + "Without parameters CreateBranchTransferLimit returns undef" +); +is( + CreateBranchTransferLimit($branchcode_2), undef, + "With only tobranch CreateBranchTransferLimit returns undef" +); +is( + CreateBranchTransferLimit( undef, $branchcode_2 ), undef, + "With only frombranch CreateBranchTransferLimit returns undef" +); + #FIXME: Currently, we can add a transferlimit even to nonexistent branches because in the database, #branch_transfer_limits.toBranch and branch_transfer_limits.fromBranch aren't foreign keys #is(CreateBranchTransferLimit(-1,-1,'CODE'),0,"With wrong CreateBranchTransferLimit returns 0 - No transfertlimit added"); #Test GetTransfersFromTo -my @transferfrom1to2 = GetTransfersFromTo( $branchcode_1, - $branchcode_2 ); +my @transferfrom1to2 = GetTransfersFromTo( + $branchcode_1, + $branchcode_2 +); cmp_deeply( \@transferfrom1to2, [ @@ -189,34 +202,47 @@ cmp_deeply( "Item1 and Item2 has been transferred from branch1 to branch2" ); my @transferto = GetTransfersFromTo( undef, $branchcode_2 ); -is_deeply( \@transferto, [], - "GetTransfersfromTo without frombranch returns an empty array" ); -my @transferfrom = GetTransfersFromTo( $branchcode_1 ); -is_deeply( \@transferfrom, [], - "GetTransfersfromTo without tobranch returns an empty array" ); +is_deeply( + \@transferto, [], + "GetTransfersfromTo without frombranch returns an empty array" +); +my @transferfrom = GetTransfersFromTo($branchcode_1); +is_deeply( + \@transferfrom, [], + "GetTransfersfromTo without tobranch returns an empty array" +); @transferfrom = GetTransfersFromTo(); -is_deeply( \@transferfrom, [], - "GetTransfersfromTo without params returns an empty array" ); +is_deeply( + \@transferfrom, [], + "GetTransfersfromTo without params returns an empty array" +); #Test DeleteBranchTransferLimits is( - C4::Circulation::DeleteBranchTransferLimits( $branchcode_1 ), + C4::Circulation::DeleteBranchTransferLimits($branchcode_1), 1, "A Branch TransferLimit has been deleted" ); -is(C4::Circulation::DeleteBranchTransferLimits(),undef,"Without parameters DeleteBranchTransferLimit returns undef"); -is(C4::Circulation::DeleteBranchTransferLimits('B'),'0E0',"With a wrong id DeleteBranchTransferLimit returns 0E0"); +is( + C4::Circulation::DeleteBranchTransferLimits(), undef, + "Without parameters DeleteBranchTransferLimit returns undef" +); +is( C4::Circulation::DeleteBranchTransferLimits('B'), '0E0', "With a wrong id DeleteBranchTransferLimit returns 0E0" ); #Test TransferSlip -is( C4::Circulation::TransferSlip($branchcode_1, undef, 5, $branchcode_2), - undef, "No tranferslip if invalid or undef itemnumber or barcode" ); -is( C4::Circulation::TransferSlip($branchcode_1, $item_id1, 1, $branchcode_2)->{'code'}, - 'TRANSFERSLIP', "Get a transferslip on valid itemnumber and/or barcode" ); +is( + C4::Circulation::TransferSlip( $branchcode_1, undef, 5, $branchcode_2 ), + undef, "No tranferslip if invalid or undef itemnumber or barcode" +); +is( + C4::Circulation::TransferSlip( $branchcode_1, $item_id1, 1, $branchcode_2 )->{'code'}, + 'TRANSFERSLIP', "Get a transferslip on valid itemnumber and/or barcode" +); cmp_deeply( - C4::Circulation::TransferSlip($branchcode_1, $item_id1, undef, $branchcode_2), - C4::Circulation::TransferSlip($branchcode_1, undef, 1, $branchcode_2), + C4::Circulation::TransferSlip( $branchcode_1, $item_id1, undef, $branchcode_2 ), + C4::Circulation::TransferSlip( $branchcode_1, undef, 1, $branchcode_2 ), "Barcode and itemnumber for same item both generate same TransferSlip" - ); +); $dbh->do("DELETE FROM branchtransfers"); ModItemTransfer( diff --git a/t/db_dependent/Circulation_holdsqueue.t b/t/db_dependent/Circulation_holdsqueue.t index 44dcc00d5a..5674fa11aa 100755 --- a/t/db_dependent/Circulation_holdsqueue.t +++ b/t/db_dependent/Circulation_holdsqueue.t @@ -36,26 +36,29 @@ subtest 'AddIssue() and AddReturn() real-time holds queue tests' => sub { $schema->storage->txn_begin; - my $library = $builder->build_object({ class => 'Koha::Libraries' }); - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); - my $item = $builder->build_sample_item({ library => $library->id }); + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + my $item = $builder->build_sample_item( { library => $library->id } ); - t::lib::Mocks::mock_userenv({ branchcode => $library->id }); + t::lib::Mocks::mock_userenv( { branchcode => $library->id } ); t::lib::Mocks::mock_preference( 'UpdateTotalIssuesOnCirc', 1 ); - t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 1 ); + t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 1 ); my $action; my $mock = Test::MockModule->new('Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue'); - $mock->mock( 'enqueue', sub { - my ( $self, $args ) = @_; - my ($package, $filename, $line) = caller; - is_deeply( - $args->{biblio_ids}, - [ $item->biblionumber ], - "$action triggers a holds queue update for the related biblio from $package at line $line" - ); - } ); + $mock->mock( + 'enqueue', + sub { + my ( $self, $args ) = @_; + my ( $package, $filename, $line ) = caller; + is_deeply( + $args->{biblio_ids}, + [ $item->biblionumber ], + "$action triggers a holds queue update for the related biblio from $package at line $line" + ); + } + ); $action = 'AddIssue'; AddIssue( $patron, $item->barcode, ); diff --git a/t/db_dependent/Clubs.t b/t/db_dependent/Clubs.t index 853c988f8a..8cb3b07b03 100755 --- a/t/db_dependent/Clubs.t +++ b/t/db_dependent/Clubs.t @@ -78,8 +78,10 @@ my $club_template_field_1 = Koha::Club::Template::Field->new( name => 'Test Club Template Field 1', } )->store(); -is( ref($club_template_field_1), - 'Koha::Club::Template::Field', 'Club template field 1 created' ); +is( + ref($club_template_field_1), + 'Koha::Club::Template::Field', 'Club template field 1 created' +); my $club_template_field_2 = Koha::Club::Template::Field->new( { @@ -87,41 +89,45 @@ my $club_template_field_2 = Koha::Club::Template::Field->new( name => 'Test Club Template Field 2', } )->store(); -is( ref($club_template_field_2), - 'Koha::Club::Template::Field', 'Club template field 2 created' ); +is( + ref($club_template_field_2), + 'Koha::Club::Template::Field', 'Club template field 2 created' +); -is( $club_template->club_template_fields->count, - 2, 'Club template has two fields' ); +is( + $club_template->club_template_fields->count, + 2, 'Club template has two fields' +); ## Add some template enrollment fields -my $club_template_enrollment_field_1 = - Koha::Club::Template::EnrollmentField->new( +my $club_template_enrollment_field_1 = Koha::Club::Template::EnrollmentField->new( { club_template_id => $club_template->id, name => 'Test Club Template EnrollmentField 1', } - )->store(); +)->store(); is( ref($club_template_enrollment_field_1), 'Koha::Club::Template::EnrollmentField', 'Club template field 1 created' ); -my $club_template_enrollment_field_2 = - Koha::Club::Template::EnrollmentField->new( +my $club_template_enrollment_field_2 = Koha::Club::Template::EnrollmentField->new( { club_template_id => $club_template->id, name => 'Test Club Template EnrollmentField 2', } - )->store(); +)->store(); is( ref($club_template_enrollment_field_2), 'Koha::Club::Template::EnrollmentField', 'Club template field 2 created' ); -is( $club_template->club_template_enrollment_fields->count, - 2, 'Club template has two enrollment fields' ); +is( + $club_template->club_template_enrollment_fields->count, + 2, 'Club template has two enrollment fields' +); ## Create a club based on this template Koha::Club->new( @@ -173,14 +179,20 @@ is( ); is( ref($club), 'Koha::Club', 'Club created' ); -is( $club->club_template->id, - $club_template->id, 'Club is using correct template' ); -is( $club->branch->id, $branchcode, 'Club is using correct branch' ); -is( $club->club_fields->count, 2, 'Club has correct number of fields' ); -is( Koha::Clubs->get_enrollable( { borrower => $patron } )->count, - 1, 'Koha::Clubs->get_enrollable returns 1 enrollable club for patron' ); -is( $patron->get_enrollable_clubs->count, - 1, 'There is 1 enrollable club for patron' ); +is( + $club->club_template->id, + $club_template->id, 'Club is using correct template' +); +is( $club->branch->id, $branchcode, 'Club is using correct branch' ); +is( $club->club_fields->count, 2, 'Club has correct number of fields' ); +is( + Koha::Clubs->get_enrollable( { borrower => $patron } )->count, + 1, 'Koha::Clubs->get_enrollable returns 1 enrollable club for patron' +); +is( + $patron->get_enrollable_clubs->count, + 1, 'There is 1 enrollable club for patron' +); ## Create an enrollment for this club my $club_enrollment = Koha::Club::Enrollment->new( @@ -190,15 +202,16 @@ my $club_enrollment = Koha::Club::Enrollment->new( branchcode => $branchcode, } )->store(); -is( ref($club_enrollment), 'Koha::Club::Enrollment', - 'Club enrollment created' ); +is( + ref($club_enrollment), 'Koha::Club::Enrollment', + 'Club enrollment created' +); my $club_enrollment_field_1 = Koha::Club::Enrollment::Field->new( { - club_enrollment_id => $club_enrollment->id, - club_template_enrollment_field_id => - $club_template_enrollment_field_1->id, - value => 'TEST', + club_enrollment_id => $club_enrollment->id, + club_template_enrollment_field_id => $club_template_enrollment_field_1->id, + value => 'TEST', } )->store(); is( @@ -209,10 +222,9 @@ is( my $club_enrollment_field_2 = Koha::Club::Enrollment::Field->new( { - club_enrollment_id => $club_enrollment->id, - club_template_enrollment_field_id => - $club_template_enrollment_field_2->id, - value => 'TEST', + club_enrollment_id => $club_enrollment->id, + club_template_enrollment_field_id => $club_template_enrollment_field_2->id, + value => 'TEST', } )->store(); is( @@ -222,12 +234,18 @@ is( ); is( $club_enrollment->club->id, $club->id, 'Got correct club for enrollment' ); -is( Koha::Clubs->get_enrollable( { borrower => $patron } )->count, - 0, 'Koha::Clubs->get_enrollable returns 0 enrollable clubs for patron' ); -is( $patron->get_club_enrollments->count, - 1, 'Got 1 club enrollment for patron' ); -is( $patron->get_enrollable_clubs->count, - 0, 'No more enrollable clubs for patron' ); +is( + Koha::Clubs->get_enrollable( { borrower => $patron } )->count, + 0, 'Koha::Clubs->get_enrollable returns 0 enrollable clubs for patron' +); +is( + $patron->get_club_enrollments->count, + 1, 'Got 1 club enrollment for patron' +); +is( + $patron->get_enrollable_clubs->count, + 0, 'No more enrollable clubs for patron' +); is( $club->club_enrollments->count, 1, 'There is 1 enrollment for club' ); $schema->storage->txn_rollback(); @@ -238,7 +256,7 @@ subtest 'filter_out_empty' => sub { $schema->storage->txn_begin(); - my $club_template = $builder->build_object({ class => 'Koha::Club::Templates' }); + my $club_template = $builder->build_object( { class => 'Koha::Club::Templates' } ); # club_1 has 2 patrons my $club_1 = $builder->build_object( @@ -264,8 +282,8 @@ subtest 'filter_out_empty' => sub { } ); - my $patron_1 = $builder->build_object({ class => 'Koha::Patrons' }); - my $patron_2 = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron_1 = $builder->build_object( { class => 'Koha::Patrons' } ); + my $patron_2 = $builder->build_object( { class => 'Koha::Patrons' } ); my $enrollment_1_1 = Koha::Club::Enrollment->new( { @@ -289,17 +307,16 @@ subtest 'filter_out_empty' => sub { } )->store(); - $enrollment_2_1->cancel; - my $clubs = Koha::Clubs->search({ club_template_id => $club_template->id }); + my $clubs = Koha::Clubs->search( { club_template_id => $club_template->id } ); is( $clubs->count, 3, 'Base resultset has all the clubs' ); my $filtered_out_rs = $clubs->filter_out_empty; - is( $filtered_out_rs->count, 1, 'Only one club has patron enrolled' ); - is( $filtered_out_rs->next->id, $club_1->id, 'Correct club is considered non-empty'); + is( $filtered_out_rs->count, 1, 'Only one club has patron enrolled' ); + is( $filtered_out_rs->next->id, $club_1->id, 'Correct club is considered non-empty' ); $schema->storage->txn_rollback(); -} + } diff --git a/t/db_dependent/Context.t b/t/db_dependent/Context.t index 67587b4798..e6b9296e29 100755 --- a/t/db_dependent/Context.t +++ b/t/db_dependent/Context.t @@ -27,6 +27,7 @@ $schema = Koha::Database->new->schema; subtest 'Environment' => sub { plan tests => 2; + # First we need to check your environmental variables my $ret; for (qw(KOHA_CONF PERL5LIB)) { @@ -39,31 +40,31 @@ subtest 'Tests with preferences' => sub { $schema->storage->txn_begin; my $dbh; - ok($dbh = C4::Context->dbh(), 'Getting dbh from C4::Context'); + ok( $dbh = C4::Context->dbh(), 'Getting dbh from C4::Context' ); - C4::Context->set_preference('OPACBaseURL','junk'); + C4::Context->set_preference( 'OPACBaseURL', 'junk' ); C4::Context->clear_syspref_cache(); my $OPACBaseURL = C4::Context->preference('OPACBaseURL'); - is($OPACBaseURL,'http://junk','OPACBaseURL saved with http:// when missing it'); + is( $OPACBaseURL, 'http://junk', 'OPACBaseURL saved with http:// when missing it' ); - C4::Context->set_preference('OPACBaseURL','https://junk'); + C4::Context->set_preference( 'OPACBaseURL', 'https://junk' ); C4::Context->clear_syspref_cache(); $OPACBaseURL = C4::Context->preference('OPACBaseURL'); - is($OPACBaseURL,'https://junk','OPACBaseURL saved with https:// as specified'); + is( $OPACBaseURL, 'https://junk', 'OPACBaseURL saved with https:// as specified' ); - C4::Context->set_preference('OPACBaseURL','http://junk2'); + C4::Context->set_preference( 'OPACBaseURL', 'http://junk2' ); C4::Context->clear_syspref_cache(); $OPACBaseURL = C4::Context->preference('OPACBaseURL'); - is($OPACBaseURL,'http://junk2','OPACBaseURL saved with http:// as specified'); + is( $OPACBaseURL, 'http://junk2', 'OPACBaseURL saved with http:// as specified' ); - C4::Context->set_preference('OPACBaseURL', ''); + C4::Context->set_preference( 'OPACBaseURL', '' ); $OPACBaseURL = C4::Context->preference('OPACBaseURL'); - is($OPACBaseURL,'','OPACBaseURL saved empty as specified'); + is( $OPACBaseURL, '', 'OPACBaseURL saved empty as specified' ); - C4::Context->set_preference('SillyPreference','random'); + C4::Context->set_preference( 'SillyPreference', 'random' ); C4::Context->clear_syspref_cache(); my $SillyPeference = C4::Context->preference('SillyPreference'); - is($SillyPeference,'random','SillyPreference saved as specified'); + is( $SillyPeference, 'random', 'SillyPreference saved as specified' ); C4::Context->clear_syspref_cache(); C4::Context->enable_syspref_cache(); @@ -71,50 +72,71 @@ subtest 'Tests with preferences' => sub { $schema->storage->debug(1); my $trace_read; open my $trace, '>', \$trace_read or die "Can't open variable: $!"; - $schema->storage->debugfh( $trace ); + $schema->storage->debugfh($trace); - C4::Context->set_preference('SillyPreference', 'thing1'); + C4::Context->set_preference( 'SillyPreference', 'thing1' ); my $silly_preference = Koha::Config::SysPrefs->find('SillyPreference'); is( $silly_preference->variable, 'SillyPreference', 'set_preference should have kept the case sensitivity' ); my $pref = C4::Context->preference("SillyPreference"); - is(C4::Context->preference("SillyPreference"), 'thing1', "Retrieved syspref (value='thing1') successfully with default behavior"); - ok( $trace_read, 'Retrieved syspref from database'); + is( + C4::Context->preference("SillyPreference"), 'thing1', + "Retrieved syspref (value='thing1') successfully with default behavior" + ); + ok( $trace_read, 'Retrieved syspref from database' ); $trace_read = q{}; - is(C4::Context->preference("SillyPreference"), 'thing1', "Retrieved syspref (value='thing1') successfully with default behavior"); - is( $trace_read , q{}, 'Did not retrieve syspref from database'); + is( + C4::Context->preference("SillyPreference"), 'thing1', + "Retrieved syspref (value='thing1') successfully with default behavior" + ); + is( $trace_read, q{}, 'Did not retrieve syspref from database' ); $trace_read = q{}; C4::Context->disable_syspref_cache(); $silly_preference->set( { value => 'thing2' } )->store(); - is(C4::Context->preference("SillyPreference"), 'thing2', "Retrieved syspref (value='thing2') successfully with disabled cache"); - ok($trace_read, 'Retrieved syspref from database'); + is( + C4::Context->preference("SillyPreference"), 'thing2', + "Retrieved syspref (value='thing2') successfully with disabled cache" + ); + ok( $trace_read, 'Retrieved syspref from database' ); $trace_read = q{}; $silly_preference->set( { value => 'thing3' } )->store(); - is(C4::Context->preference("SillyPreference"), 'thing3', "Retrieved syspref (value='thing3') successfully with disabled cache"); - ok($trace_read, 'Retrieved syspref from database'); + is( + C4::Context->preference("SillyPreference"), 'thing3', + "Retrieved syspref (value='thing3') successfully with disabled cache" + ); + ok( $trace_read, 'Retrieved syspref from database' ); $trace_read = q{}; C4::Context->enable_syspref_cache(); - is(C4::Context->preference("SillyPreference"), 'thing3', "Retrieved syspref (value='thing3') successfully from cache"); - isnt( $trace_read, q{}, 'The pref should be retrieved from the database if the cache has been enabled'); + is( + C4::Context->preference("SillyPreference"), 'thing3', + "Retrieved syspref (value='thing3') successfully from cache" + ); + isnt( $trace_read, q{}, 'The pref should be retrieved from the database if the cache has been enabled' ); $trace_read = q{}; $silly_preference->set( { value => 'thing4' } )->store(); C4::Context->clear_syspref_cache(); - is(C4::Context->preference("SillyPreference"), 'thing4', "Retrieved syspref (value='thing4') successfully after clearing cache"); - ok($trace_read, 'Retrieved syspref from database'); + is( + C4::Context->preference("SillyPreference"), 'thing4', + "Retrieved syspref (value='thing4') successfully after clearing cache" + ); + ok( $trace_read, 'Retrieved syspref from database' ); $trace_read = q{}; - is(C4::Context->preference("SillyPreference"), 'thing4', "Retrieved syspref (value='thing4') successfully from cache"); - is( $trace_read, q{}, 'Did not retrieve syspref from database'); + is( + C4::Context->preference("SillyPreference"), 'thing4', + "Retrieved syspref (value='thing4') successfully from cache" + ); + is( $trace_read, q{}, 'Did not retrieve syspref from database' ); $trace_read = q{}; $silly_preference->delete(); # AutoEmailNewUser should be a YesNo pref - C4::Context->set_preference('AutoEmailNewUser', ''); + C4::Context->set_preference( 'AutoEmailNewUser', '' ); my $yesno_pref = Koha::Config::SysPrefs->find('AutoEmailNewUser'); is( $yesno_pref->value(), 0, 'set_preference should have set the value to 0, instead of an empty string' ); @@ -123,49 +145,52 @@ subtest 'Tests with preferences' => sub { subtest 'Check context hash keys' => sub { my $koha; - ok($koha = C4::Context->new, 'C4::Context->new'); - my @keys = keys %$koha; + ok( $koha = C4::Context->new, 'C4::Context->new' ); + my @keys = keys %$koha; my $width = 0; ok( @keys, 'Expecting entries in context hash' ); - if( @keys ) { - $width = (sort {$a <=> $b} map {length} @keys)[-1]; + if (@keys) { + $width = ( sort { $a <=> $b } map { length } @keys )[-1]; } - foreach (sort @keys) { - ok(exists $koha->{$_}, - '$koha->{' . sprintf('%' . $width . 's', $_) . '} exists ' - . ((defined $koha->{$_}) ? "and is defined." : "but is not defined.") + foreach ( sort @keys ) { + ok( + exists $koha->{$_}, + '$koha->{' + . sprintf( '%' . $width . 's', $_ ) + . '} exists ' + . ( ( defined $koha->{$_} ) ? "and is defined." : "but is not defined." ) ); } my $config; - ok($config = $koha->{config}, 'Getting $koha->{config} '); + ok( $config = $koha->{config}, 'Getting $koha->{config} ' ); done_testing(); }; subtest 'Zconn' => sub { plan tests => 2; - my $oConnection = C4::Context->Zconn('biblioserver', 0); - isnt($oConnection->option('async'), 1, "ZOOM connection is synchronous"); - $oConnection = C4::Context->Zconn('biblioserver', 1); - is($oConnection->option('async'), 1, "ZOOM connection is asynchronous"); + my $oConnection = C4::Context->Zconn( 'biblioserver', 0 ); + isnt( $oConnection->option('async'), 1, "ZOOM connection is synchronous" ); + $oConnection = C4::Context->Zconn( 'biblioserver', 1 ); + is( $oConnection->option('async'), 1, "ZOOM connection is asynchronous" ); }; subtest 'get_versions' => sub { plan tests => 2; my $dbh = C4::Context->dbh; - my $mod = Test::MockModule->new( 'C4::Context' ); + my $mod = Test::MockModule->new('C4::Context'); my $no_dbh; $mod->mock( 'dbh', sub { return $no_dbh ? undef : $dbh; } ); my $client = `mysql -V`; my $server = ( C4::Context->dbh->selectrow_array("SHOW VARIABLES LIKE 'version'") )[1]; my $server_version; - if( $server =~ /(\d+(\.\d+)+)/ ) { + if ( $server =~ /(\d+(\.\d+)+)/ ) { $server_version = $1; $server_version =~ s/\./\\./g; } my $v; - like( $v = { C4::Context::get_versions }->{mysqlVersion}, qr/$server_version/, "Server version $v found" ); + like( $v = {C4::Context::get_versions}->{mysqlVersion}, qr/$server_version/, "Server version $v found" ); $no_dbh = 1; - is( $v = { C4::Context::get_versions }->{mysqlVersion}, $client, "Client version $v found" ); + is( $v = {C4::Context::get_versions}->{mysqlVersion}, $client, "Client version $v found" ); }; diff --git a/t/db_dependent/Contract.t b/t/db_dependent/Contract.t index e1af15b19c..5010da6e55 100755 --- a/t/db_dependent/Contract.t +++ b/t/db_dependent/Contract.t @@ -29,7 +29,7 @@ use DateTime::Duration; use Test::More tests => 43; BEGIN { - use_ok('C4::Contract', qw( GetContracts GetContract AddContract ModContract DelContract )); + use_ok( 'C4::Contract', qw( GetContracts GetContract AddContract ModContract DelContract ) ); } my $schema = Koha::Database->new->schema; @@ -40,11 +40,10 @@ $dbh->do(q|DELETE FROM aqbasket|); $dbh->do(q|DELETE FROM aqcontract|); $dbh->do(q|DELETE FROM aqbooksellers|); - -my $bookseller1 = Koha::Acquisition::Bookseller->new( { name => 'My first bookseller' } )->store; +my $bookseller1 = Koha::Acquisition::Bookseller->new( { name => 'My first bookseller' } )->store; my $bookseller_id1 = $bookseller1->id; isnt( $bookseller_id1, undef, 'AddBookseller does not return undef' ); -my $bookseller2 = Koha::Acquisition::Bookseller->new( { name => 'My second bookseller' } )->store; +my $bookseller2 = Koha::Acquisition::Bookseller->new( { name => 'My second bookseller' } )->store; my $bookseller_id2 = $bookseller2->id; isnt( $bookseller_id2, undef, 'AddBookseller does not return undef' ); my $contracts = GetContracts(); @@ -52,7 +51,6 @@ is( @$contracts, 0, 'GetContracts returns the correct number of contracts' ); my $contract = GetContract(); is( $contract, undef, 'GetContract without argument returns undef' ); - my $my_contract1 = { contractstartdate => '2014-06-01', contractenddate => '2014-06-30', @@ -71,13 +69,22 @@ is( @$contracts, 1, 'AddContract adds a contract' ); $contract = GetContract(); is( $contract, undef, 'GetContract without argument returns undef' ); $contract = GetContract( { contractnumber => $my_contract_id1 } ); -is( $contract->{contractstartdate}, $my_contract1->{contractstartdate}, 'AddContract stores the contract start date correctly.' ); -is( $contract->{contractenddate}, $my_contract1->{contractenddate}, 'AddContract stores the contract end date correctly.' ); +is( + $contract->{contractstartdate}, $my_contract1->{contractstartdate}, + 'AddContract stores the contract start date correctly.' +); +is( + $contract->{contractenddate}, $my_contract1->{contractenddate}, + 'AddContract stores the contract end date correctly.' +); is( $contract->{contractname}, $my_contract1->{contractname}, 'AddContract stores the contract name correctly.' ); -is( $contract->{contractdescription}, $my_contract1->{contractdescription}, 'AddContract stores the contract description correctly.' ); +is( + $contract->{contractdescription}, $my_contract1->{contractdescription}, + 'AddContract stores the contract description correctly.' +); is( $contract->{booksellerid}, $my_contract1->{booksellerid}, 'AddContract stores the bookseller id correctly.' ); -my $now = dt_from_string; +my $now = dt_from_string; my $three_more_days = $now + DateTime::Duration->new( days => 3 ); $my_contract1 = { @@ -96,13 +103,21 @@ is( $mod_status, 1, 'ModContract returns true' ); $contracts = GetContracts(); is( @$contracts, 1, 'ModContract does not modify the number of contracts' ); $contract = GetContract( { contractnumber => $my_contract_id1 } ); -is( $contract->{contractstartdate}, $my_contract1->{contractstartdate}, 'ModContract updates the contract start date correctly.' ); -is( $contract->{contractenddate}, $my_contract1->{contractenddate}, 'ModContract updates the contract end date correctly.' ); +is( + $contract->{contractstartdate}, $my_contract1->{contractstartdate}, + 'ModContract updates the contract start date correctly.' +); +is( + $contract->{contractenddate}, $my_contract1->{contractenddate}, + 'ModContract updates the contract end date correctly.' +); is( $contract->{contractname}, $my_contract1->{contractname}, 'ModContract updates the contract name correctly.' ); -is( $contract->{contractdescription}, $my_contract1->{contractdescription}, 'ModContract updates the contract description correctly.' ); +is( + $contract->{contractdescription}, $my_contract1->{contractdescription}, + 'ModContract updates the contract description correctly.' +); is( $contract->{booksellerid}, $my_contract1->{booksellerid}, 'ModContract updates the bookseller id correctly.' ); - my $my_contract2 = { contractstartdate => '2013-08-05', contractenddate => '2013-09-25', @@ -113,9 +128,7 @@ my $my_contract2 = { my $my_contract_id2 = AddContract($my_contract2); $contracts = GetContracts( { booksellerid => $bookseller_id1 } ); is( @$contracts, 1, 'GetContracts returns the correct number of contracts' ); -$contracts = GetContracts({ - activeonly => 1 -}); +$contracts = GetContracts( { activeonly => 1 } ); is( @$contracts, 1, 'GetContracts with active only returns only current contracts' ); $contracts = GetContracts( { booksellerid => $bookseller_id2 } ); is( @$contracts, 1, 'GetContracts returns the correct number of contracts' ); @@ -123,24 +136,53 @@ $contracts = GetContracts(); is( @$contracts, 2, 'GetContracts returns the correct number of contracts' ); is( $contracts->[0]->{contractnumber}, $my_contract_id1, 'GetContracts returns the contract number correctly' ); -is( $contracts->[0]->{contractstartdate}, $my_contract1->{contractstartdate}, 'GetContracts returns the contract start date correctly.' ); -is( $contracts->[0]->{contractenddate}, $my_contract1->{contractenddate}, 'GetContracts returns the contract end date correctly.' ); -is( $contracts->[0]->{contractname}, $my_contract1->{contractname}, 'GetContracts returns the contract name correctly.' ); -is( $contracts->[0]->{contractdescription}, $my_contract1->{contractdescription}, 'GetContracts returns the contract description correctly.' ); -is( $contracts->[0]->{booksellerid}, $my_contract1->{booksellerid}, 'GetContracts returns the bookseller id correctly.' ); +is( + $contracts->[0]->{contractstartdate}, $my_contract1->{contractstartdate}, + 'GetContracts returns the contract start date correctly.' +); +is( + $contracts->[0]->{contractenddate}, $my_contract1->{contractenddate}, + 'GetContracts returns the contract end date correctly.' +); +is( + $contracts->[0]->{contractname}, $my_contract1->{contractname}, + 'GetContracts returns the contract name correctly.' +); +is( + $contracts->[0]->{contractdescription}, $my_contract1->{contractdescription}, + 'GetContracts returns the contract description correctly.' +); +is( + $contracts->[0]->{booksellerid}, $my_contract1->{booksellerid}, + 'GetContracts returns the bookseller id correctly.' +); is( $contracts->[1]->{contractnumber}, $my_contract_id2, 'GetContracts returns the contract number correctly' ); -is( $contracts->[1]->{contractstartdate}, $my_contract2->{contractstartdate}, 'GetContracts returns the contract start date correctly.' ); -is( $contracts->[1]->{contractenddate}, $my_contract2->{contractenddate}, 'GetContracts returns the contract end date correctly.' ); -is( $contracts->[1]->{contractname}, $my_contract2->{contractname}, 'GetContracts returns the contract name correctly.' ); -is( $contracts->[1]->{contractdescription}, $my_contract2->{contractdescription}, 'GetContracts returns the contract description correctly.' ); -is( $contracts->[1]->{booksellerid}, $my_contract2->{booksellerid}, 'GetContracts returns the bookseller id correctly.' ); - +is( + $contracts->[1]->{contractstartdate}, $my_contract2->{contractstartdate}, + 'GetContracts returns the contract start date correctly.' +); +is( + $contracts->[1]->{contractenddate}, $my_contract2->{contractenddate}, + 'GetContracts returns the contract end date correctly.' +); +is( + $contracts->[1]->{contractname}, $my_contract2->{contractname}, + 'GetContracts returns the contract name correctly.' +); +is( + $contracts->[1]->{contractdescription}, $my_contract2->{contractdescription}, + 'GetContracts returns the contract description correctly.' +); +is( + $contracts->[1]->{booksellerid}, $my_contract2->{booksellerid}, + 'GetContracts returns the bookseller id correctly.' +); my $del_status = DelContract(); is( $del_status, undef, 'DelContract without contract number returns undef' ); -$del_status = DelContract( { contractnumber => $my_contract_id1 } ); +$del_status = DelContract( { contractnumber => $my_contract_id1 } ); is( $del_status, 1, 'DelContract returns true' ); $contracts = GetContracts(); is( @$contracts, 1, 'DelContract deletes a contract' ); diff --git a/t/db_dependent/CourseReserves.t b/t/db_dependent/CourseReserves.t index 06af1b5a50..3c9a882f55 100755 --- a/t/db_dependent/CourseReserves.t +++ b/t/db_dependent/CourseReserves.t @@ -23,8 +23,11 @@ use Koha::Database; use t::lib::TestBuilder; BEGIN { - use_ok('C4::Biblio', qw( AddBiblio )); - use_ok('C4::CourseReserves', qw( GetCourse ModCourse GetCourses DelCourse GetCourseInstructors ModCourseInstructors GetCourseItem ModCourseItem GetCourseReserve ModCourseReserve GetCourseReserves DelCourseReserve SearchCourses GetItemCourseReservesInfo )); + use_ok( 'C4::Biblio', qw( AddBiblio ) ); + use_ok( + 'C4::CourseReserves', + qw( GetCourse ModCourse GetCourses DelCourse GetCourseInstructors ModCourseInstructors GetCourseItem ModCourseItem GetCourseReserve ModCourseReserve GetCourseReserves DelCourseReserve SearchCourses GetItemCourseReservesInfo ) + ); use_ok('C4::Context'); use_ok('MARC::Field'); use_ok('MARC::Record'); @@ -35,17 +38,17 @@ $schema->storage->txn_begin; my $builder = t::lib::TestBuilder->new; my $branchcode = $builder->build( { source => 'Branch' } )->{branchcode}; -my $itemtype = $builder->build( { source => 'Itemtype', value => { notforloan => 0 } } )->{itemtype}; +my $itemtype = $builder->build( { source => 'Itemtype', value => { notforloan => 0 } } )->{itemtype}; # Create 10 sample borrowers my @borrowers = (); -foreach (1..10) { - push @borrowers, $builder->build({ source => 'Borrower' }); +foreach ( 1 .. 10 ) { + push @borrowers, $builder->build( { source => 'Borrower' } ); } # Create the a record with an item my $record = MARC::Record->new; -my ( $biblionumber, $biblioitemnumber ) = C4::Biblio::AddBiblio($record, ''); +my ( $biblionumber, $biblioitemnumber ) = C4::Biblio::AddBiblio( $record, '' ); my $itemnumber = Koha::Item->new( { biblionumber => $biblionumber, @@ -66,26 +69,35 @@ ok( $course_id, "ModCourse created course successfully" ); $course_id = ModCourse( course_id => $course_id, staff_note => "Test staff note 2", - enabled => 'no', + enabled => 'no', ); my $course = GetCourse($course_id); -ok( $course->{'course_name'} eq "Test Course", "GetCourse returned correct course" ); -ok( $course->{'staff_note'} eq "Test staff note 2", "ModCourse updated course succesfully" ); +ok( $course->{'course_name'} eq "Test Course", "GetCourse returned correct course" ); +ok( $course->{'staff_note'} eq "Test staff note 2", "ModCourse updated course succesfully" ); is( $course->{'enabled'}, 'no', "Test Course is disabled" ); my $courses = GetCourses(); is( ref($courses), 'ARRAY', "GetCourses returns an array" ); -my @match = map {$_->{course_name} eq 'Test Course'} @$courses; +my @match = map { $_->{course_name} eq 'Test Course' } @$courses; ok( scalar(@match) > 0, "GetCourses returns valid array of course data" ); -ModCourseInstructors( mode => 'add', course_id => $course_id, borrowernumbers => [ $borrowers[0]->{'borrowernumber'} ] ); +ModCourseInstructors( + mode => 'add', course_id => $course_id, + borrowernumbers => [ $borrowers[0]->{'borrowernumber'} ] +); $course = GetCourse($course_id); -ok( $course->{'instructors'}->[0]->{'borrowernumber'} == $borrowers[0]->{'borrowernumber'}, "ModCourseInstructors added instructors correctly" ); +ok( + $course->{'instructors'}->[0]->{'borrowernumber'} == $borrowers[0]->{'borrowernumber'}, + "ModCourseInstructors added instructors correctly" +); my $course_instructors = GetCourseInstructors($course_id); -ok( $course_instructors->[0]->{'borrowernumber'} eq $borrowers[0]->{'borrowernumber'}, "GetCourseInstructors returns valid data" ); +ok( + $course_instructors->[0]->{'borrowernumber'} eq $borrowers[0]->{'borrowernumber'}, + "GetCourseInstructors returns valid data" +); my $ci_id = ModCourseItem( 'itemnumber' => $itemnumber ); ok( $ci_id, "ModCourseItem returned valid data" ); @@ -104,7 +116,7 @@ ok( $course_reserves->[0]->{'ci_id'} eq $ci_id, "GetCourseReserves returns valid ## Check for regression of Bug 15530 $course_id = ModCourse( - course_id => $course_id, + course_id => $course_id, enabled => 'yes', ); $course = GetCourse($course_id); @@ -115,7 +127,7 @@ my $disabled_course_id = ModCourse( course_name => "Disabled Course", enabled => 'no', ); -my $disabled_course = GetCourse( $disabled_course_id ); +my $disabled_course = GetCourse($disabled_course_id); is( $disabled_course->{'enabled'}, 'no', "Disabled Course is disabled" ); my $cr_id2 = ModCourseReserve( 'course_id' => $disabled_course_id, 'ci_id' => $ci_id ); $course_item = GetCourseItem( 'ci_id' => $ci_id ); @@ -133,7 +145,7 @@ DelCourse($course_id); $course = GetCourse($course_id); ok( !defined( $course->{'course_id'} ), "DelCourse deleted course successfully" ); -$courses = SearchCourses(); # FIXME Lack of tests for SearchCourses +$courses = SearchCourses(); # FIXME Lack of tests for SearchCourses is( ref($courses), 'ARRAY', 'SearchCourses should not crash and return an arrayref' ); $schema->storage->txn_rollback; diff --git a/t/db_dependent/CourseReserves/CourseItems.t b/t/db_dependent/CourseReserves/CourseItems.t index 6e419cdb25..432c859ade 100755 --- a/t/db_dependent/CourseReserves/CourseItems.t +++ b/t/db_dependent/CourseReserves/CourseItems.t @@ -19,7 +19,8 @@ use Modern::Perl; use t::lib::Mocks; use t::lib::TestBuilder; -use C4::CourseReserves qw( ModCourse ModCourseItem ModCourseReserve GetCourse GetCourseItem DelCourse DelCourseReserve ); +use C4::CourseReserves + qw( ModCourse ModCourseItem ModCourseReserve GetCourse GetCourseItem DelCourse DelCourseReserve ); use C4::Context; use Koha::Items; @@ -29,13 +30,13 @@ BEGIN { require_ok('C4::CourseReserves'); } -my $schema = Koha::Database->new->schema; +my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; my $builder = t::lib::TestBuilder->new(); create_dependent_objects(); -my ($biblionumber, $itemnumber) = create_bib_and_item(); +my ( $biblionumber, $itemnumber ) = create_bib_and_item(); my $ci_id = ModCourseItem( itemnumber => $itemnumber, @@ -51,12 +52,14 @@ my $ci_id = ModCourseItem( location => 'TH', ); -my $course = $builder->build({ - source => 'CourseReserve', - value => { - ci_id => $ci_id, +my $course = $builder->build( + { + source => 'CourseReserve', + value => { + ci_id => $ci_id, + } } -}); +); my $cr_id = ModCourseReserve( course_id => $course->{course_id}, @@ -66,18 +69,18 @@ my $cr_id = ModCourseReserve( ); my $course_item = GetCourseItem( ci_id => $ci_id ); -is($course_item->{itype_storage}, 'CD_foo', 'Course item itype storage should be CD_foo'); -is($course_item->{ccode_storage}, 'CD', 'Course item ccode storage should be CD'); -is($course_item->{homebranch_storage}, 'B1', 'Course item holding branch storage should be B1'); -is($course_item->{holdingbranch_storage}, 'B1', 'Course item holding branch storage should be B1'); -is($course_item->{location_storage}, 'HR', 'Course item location storage should be HR'); +is( $course_item->{itype_storage}, 'CD_foo', 'Course item itype storage should be CD_foo' ); +is( $course_item->{ccode_storage}, 'CD', 'Course item ccode storage should be CD' ); +is( $course_item->{homebranch_storage}, 'B1', 'Course item holding branch storage should be B1' ); +is( $course_item->{holdingbranch_storage}, 'B1', 'Course item holding branch storage should be B1' ); +is( $course_item->{location_storage}, 'HR', 'Course item location storage should be HR' ); my $item = Koha::Items->find($itemnumber); -is($item->effective_itemtype, 'BK_foo', 'Item type in course should be BK_foo'); -is($item->ccode, 'BOOK', 'Item ccode in course should be BOOK'); -is($item->homebranch, 'B2', 'Item home branch in course should be B2'); -is($item->holdingbranch, 'B2', 'Item holding branch in course should be B2'); -is($item->location, 'TH', 'Item location in course should be TH'); +is( $item->effective_itemtype, 'BK_foo', 'Item type in course should be BK_foo' ); +is( $item->ccode, 'BOOK', 'Item ccode in course should be BOOK' ); +is( $item->homebranch, 'B2', 'Item home branch in course should be B2' ); +is( $item->holdingbranch, 'B2', 'Item holding branch in course should be B2' ); +is( $item->location, 'TH', 'Item location in course should be TH' ); ModCourseItem( itemnumber => $itemnumber, @@ -101,32 +104,32 @@ ModCourseReserve( ); $course_item = GetCourseItem( ci_id => $ci_id ); -is($course_item->{itype_storage}, 'CD_foo', 'Course item itype storage should be CD_foo'); -is($course_item->{ccode_storage}, 'CD', 'Course item ccode storage should be CD'); -is($course_item->{homebranch_storage}, 'B1', 'Course item home branch storage should be B1'); -is($course_item->{holdingbranch_storage}, 'B1', 'Course item holding branch storage should be B1'); -is($course_item->{location_storage}, 'HR', 'Course item location storage should be HR'); +is( $course_item->{itype_storage}, 'CD_foo', 'Course item itype storage should be CD_foo' ); +is( $course_item->{ccode_storage}, 'CD', 'Course item ccode storage should be CD' ); +is( $course_item->{homebranch_storage}, 'B1', 'Course item home branch storage should be B1' ); +is( $course_item->{holdingbranch_storage}, 'B1', 'Course item holding branch storage should be B1' ); +is( $course_item->{location_storage}, 'HR', 'Course item location storage should be HR' ); $item = Koha::Items->find($itemnumber); -is($item->effective_itemtype, 'BK_foo', 'Item type in course should be BK_foo'); -is($item->ccode, 'DVD', 'Item ccode in course should be DVD'); -is($item->homebranch, 'B3', 'Item home branch in course should be B3'); -is($item->holdingbranch, 'B3', 'Item holding branch in course should be B3'); -is($item->location, 'TH', 'Item location in course should be TH'); +is( $item->effective_itemtype, 'BK_foo', 'Item type in course should be BK_foo' ); +is( $item->ccode, 'DVD', 'Item ccode in course should be DVD' ); +is( $item->homebranch, 'B3', 'Item home branch in course should be B3' ); +is( $item->holdingbranch, 'B3', 'Item holding branch in course should be B3' ); +is( $item->location, 'TH', 'Item location in course should be TH' ); DelCourseReserve( cr_id => $cr_id ); $item = Koha::Items->find($itemnumber); -is($item->effective_itemtype, 'CD_foo', 'Item type removed from course should be set back to CD_foo'); -is($item->ccode, 'CD', 'Item ccode removed from course should be set back to CD'); -is($item->homebranch, 'B1', 'Item home branch removed from course should be set back B1'); -is($item->holdingbranch, 'B1', 'Item holding branch removed from course should be set back B1'); -is($item->location, 'HR', 'Item location removed from course should be TH'); +is( $item->effective_itemtype, 'CD_foo', 'Item type removed from course should be set back to CD_foo' ); +is( $item->ccode, 'CD', 'Item ccode removed from course should be set back to CD' ); +is( $item->homebranch, 'B1', 'Item home branch removed from course should be set back B1' ); +is( $item->holdingbranch, 'B1', 'Item holding branch removed from course should be set back B1' ); +is( $item->location, 'HR', 'Item location removed from course should be TH' ); # Test the specific case described on bug #10382. $item->ccode('')->store; $item = Koha::Items->find($itemnumber); -is($item->ccode, '', 'Item ccode should be empty'); +is( $item->ccode, '', 'Item ccode should be empty' ); my $ci_id2 = ModCourseItem( itemnumber => $itemnumber, @@ -150,10 +153,10 @@ my $cr_id2 = ModCourseReserve( ); $item = Koha::Items->find($itemnumber); -is($item->ccode, 'BOOK', 'Item ccode should be BOOK'); +is( $item->ccode, 'BOOK', 'Item ccode should be BOOK' ); my $course_item2 = GetCourseItem( ci_id => $ci_id2 ); -is($course_item2->{ccode_storage}, '', 'Course item ccode storage should be empty'); +is( $course_item2->{ccode_storage}, '', 'Course item ccode storage should be empty' ); ModCourseItem( itemnumber => $itemnumber, @@ -177,7 +180,7 @@ ModCourseReserve( ); $item = Koha::Items->find($itemnumber); -is($item->ccode, 'DVD', 'Item ccode should be DVD'); +is( $item->ccode, 'DVD', 'Item ccode should be DVD' ); ModCourseItem( itemnumber => $itemnumber, @@ -192,19 +195,19 @@ ModCourseItem( location => 'TH', ); $item = Koha::Items->find($itemnumber); -is($item->ccode, 'BOOK', 'Item ccode should be BOOK'); +is( $item->ccode, 'BOOK', 'Item ccode should be BOOK' ); $course_item2 = GetCourseItem( ci_id => $ci_id2 ); -is($course_item2->{ccode_storage}, '', 'Course item ccode storage should be empty'); +is( $course_item2->{ccode_storage}, '', 'Course item ccode storage should be empty' ); DelCourseReserve( cr_id => $cr_id2 ); $item = Koha::Items->find($itemnumber); -is($item->ccode, '', 'Item ccode should be set back to empty'); +is( $item->ccode, '', 'Item ccode should be set back to empty' ); subtest 'Ensure modifying fields on existing course items updates the item and course item' => sub { plan tests => 60; - my ($biblionumber, $itemnumber) = create_bib_and_item(); + my ( $biblionumber, $itemnumber ) = create_bib_and_item(); my $ci_id = ModCourseItem( itemnumber => $itemnumber, itype_enabled => 0, @@ -214,12 +217,14 @@ subtest 'Ensure modifying fields on existing course items updates the item and c location_enabled => 0, ); - my $course = $builder->build({ - source => 'CourseReserve', - value => { - ci_id => $ci_id, + my $course = $builder->build( + { + source => 'CourseReserve', + value => { + ci_id => $ci_id, + } } - }); + ); my $cr_id = ModCourseReserve( course_id => $course->{course_id}, @@ -229,30 +234,30 @@ subtest 'Ensure modifying fields on existing course items updates the item and c ); my $course_item = GetCourseItem( ci_id => $ci_id ); - is($course_item->{itype_storage}, undef, 'Course item itype storage should be undef'); - is($course_item->{ccode_storage}, undef, 'Course item ccode storage should be undef'); - is($course_item->{homebranch_storage}, undef, 'Course item holding branch storage should be undef'); - is($course_item->{holdingbranch_storage}, undef, 'Course item holding branch storage should be undef'); - is($course_item->{location_storage}, undef, 'Course item location storage should be undef'); + is( $course_item->{itype_storage}, undef, 'Course item itype storage should be undef' ); + is( $course_item->{ccode_storage}, undef, 'Course item ccode storage should be undef' ); + is( $course_item->{homebranch_storage}, undef, 'Course item holding branch storage should be undef' ); + is( $course_item->{holdingbranch_storage}, undef, 'Course item holding branch storage should be undef' ); + is( $course_item->{location_storage}, undef, 'Course item location storage should be undef' ); - is($course_item->{itype}, undef, 'Course item itype should be undef'); - is($course_item->{ccode}, undef, 'Course item ccode should be undef'); - is($course_item->{homebranch}, undef, 'Course item holding branch should be undef'); - is($course_item->{holdingbranch}, undef, 'Course item holding branch should be undef'); - is($course_item->{location}, undef, 'Course item location should be undef'); + is( $course_item->{itype}, undef, 'Course item itype should be undef' ); + is( $course_item->{ccode}, undef, 'Course item ccode should be undef' ); + is( $course_item->{homebranch}, undef, 'Course item holding branch should be undef' ); + is( $course_item->{holdingbranch}, undef, 'Course item holding branch should be undef' ); + is( $course_item->{location}, undef, 'Course item location should be undef' ); - is($course_item->{itype_enabled}, 0, 'Course item itype enabled should be 0'); - is($course_item->{ccode_enabled}, 0, 'Course item ccode enabled should be 0'); - is($course_item->{homebranch_enabled}, 0, 'Course item holding branch enabled should be 0'); - is($course_item->{holdingbranch_enabled}, 0, 'Course item holding branch enabled should be 0'); - is($course_item->{location_enabled}, 0, 'Course item location enabled should be 0'); + is( $course_item->{itype_enabled}, 0, 'Course item itype enabled should be 0' ); + is( $course_item->{ccode_enabled}, 0, 'Course item ccode enabled should be 0' ); + is( $course_item->{homebranch_enabled}, 0, 'Course item holding branch enabled should be 0' ); + is( $course_item->{holdingbranch_enabled}, 0, 'Course item holding branch enabled should be 0' ); + is( $course_item->{location_enabled}, 0, 'Course item location enabled should be 0' ); my $item = Koha::Items->find($itemnumber); - is($item->effective_itemtype, 'CD_foo', 'Item type in course should be CD_foo'); - is($item->ccode, 'CD', 'Item ccode in course should be CD'); - is($item->homebranch, 'B1', 'Item home branch in course should be B1'); - is($item->holdingbranch, 'B1', 'Item holding branch in course should be B1'); - is($item->location, 'HR', 'Item location in course should be HR'); + is( $item->effective_itemtype, 'CD_foo', 'Item type in course should be CD_foo' ); + is( $item->ccode, 'CD', 'Item ccode in course should be CD' ); + is( $item->homebranch, 'B1', 'Item home branch in course should be B1' ); + is( $item->holdingbranch, 'B1', 'Item holding branch in course should be B1' ); + is( $item->location, 'HR', 'Item location in course should be HR' ); ModCourseItem( itemnumber => $itemnumber, @@ -269,30 +274,30 @@ subtest 'Ensure modifying fields on existing course items updates the item and c ); $course_item = GetCourseItem( ci_id => $ci_id ); - is($course_item->{itype_storage}, 'CD_foo', 'Course item itype storage should be CD_foo'); - is($course_item->{ccode_storage}, 'CD', 'Course item ccode storage should be CD'); - is($course_item->{homebranch_storage}, 'B1', 'Course item holding branch storage should be B1'); - is($course_item->{holdingbranch_storage}, 'B1', 'Course item holding branch storage should be B1'); - is($course_item->{location_storage}, 'HR', 'Course item location storage should be HR'); + is( $course_item->{itype_storage}, 'CD_foo', 'Course item itype storage should be CD_foo' ); + is( $course_item->{ccode_storage}, 'CD', 'Course item ccode storage should be CD' ); + is( $course_item->{homebranch_storage}, 'B1', 'Course item holding branch storage should be B1' ); + is( $course_item->{holdingbranch_storage}, 'B1', 'Course item holding branch storage should be B1' ); + is( $course_item->{location_storage}, 'HR', 'Course item location storage should be HR' ); - is($course_item->{itype}, 'BK_foo', 'Course item itype should be BK_foo'); - is($course_item->{ccode}, 'BOOK', 'Course item ccode should be BOOK'); - is($course_item->{homebranch}, 'B2', 'Course item holding branch should be B2'); - is($course_item->{holdingbranch}, 'B2', 'Course item holding branch should be B2'); - is($course_item->{location}, 'TH', 'Course item location should be TH'); + is( $course_item->{itype}, 'BK_foo', 'Course item itype should be BK_foo' ); + is( $course_item->{ccode}, 'BOOK', 'Course item ccode should be BOOK' ); + is( $course_item->{homebranch}, 'B2', 'Course item holding branch should be B2' ); + is( $course_item->{holdingbranch}, 'B2', 'Course item holding branch should be B2' ); + is( $course_item->{location}, 'TH', 'Course item location should be TH' ); - is($course_item->{itype_enabled}, 1, 'Course item itype enabled should be 1'); - is($course_item->{ccode_enabled}, 1, 'Course item ccode enabled should be 1'); - is($course_item->{homebranch_enabled}, 1, 'Course item holding branch enabled should be 1'); - is($course_item->{holdingbranch_enabled}, 1, 'Course item holding branch enabled should be 1'); - is($course_item->{location_enabled}, 1, 'Course item location enabled should be 1'); + is( $course_item->{itype_enabled}, 1, 'Course item itype enabled should be 1' ); + is( $course_item->{ccode_enabled}, 1, 'Course item ccode enabled should be 1' ); + is( $course_item->{homebranch_enabled}, 1, 'Course item holding branch enabled should be 1' ); + is( $course_item->{holdingbranch_enabled}, 1, 'Course item holding branch enabled should be 1' ); + is( $course_item->{location_enabled}, 1, 'Course item location enabled should be 1' ); $item = Koha::Items->find($itemnumber); - is($item->effective_itemtype, 'BK_foo', 'Item type in course should be BK_foo'); - is($item->ccode, 'BOOK', 'Item ccode in course should be BOOK'); - is($item->homebranch, 'B2', 'Item home branch in course should be B2'); - is($item->holdingbranch, 'B2', 'Item holding branch in course should be B2'); - is($item->location, 'TH', 'Item location in course should be TH'); + is( $item->effective_itemtype, 'BK_foo', 'Item type in course should be BK_foo' ); + is( $item->ccode, 'BOOK', 'Item ccode in course should be BOOK' ); + is( $item->homebranch, 'B2', 'Item home branch in course should be B2' ); + is( $item->holdingbranch, 'B2', 'Item holding branch in course should be B2' ); + is( $item->location, 'TH', 'Item location in course should be TH' ); # Test removing fields from an active course item ModCourseItem( @@ -305,37 +310,38 @@ subtest 'Ensure modifying fields on existing course items updates the item and c ); $course_item = GetCourseItem( ci_id => $ci_id ); - is($course_item->{itype_storage}, undef, 'Course item itype storage should be undef'); - is($course_item->{ccode_storage}, undef, 'Course item ccode storage should be undef'); - is($course_item->{homebranch_storage}, undef, 'Course item holding branch storage should be undef'); - is($course_item->{holdingbranch_storage}, undef, 'Course item holding branch storage should be undef'); - is($course_item->{location_storage}, undef, 'Course item location storage should be undef'); + is( $course_item->{itype_storage}, undef, 'Course item itype storage should be undef' ); + is( $course_item->{ccode_storage}, undef, 'Course item ccode storage should be undef' ); + is( $course_item->{homebranch_storage}, undef, 'Course item holding branch storage should be undef' ); + is( $course_item->{holdingbranch_storage}, undef, 'Course item holding branch storage should be undef' ); + is( $course_item->{location_storage}, undef, 'Course item location storage should be undef' ); - is($course_item->{itype}, undef, 'Course item itype should be undef'); - is($course_item->{ccode}, undef, 'Course item ccode should be undef'); - is($course_item->{homebranch}, undef, 'Course item holding branch should be undef'); - is($course_item->{holdingbranch}, undef, 'Course item holding branch should be undef'); - is($course_item->{location}, undef, 'Course item location should be undef'); + is( $course_item->{itype}, undef, 'Course item itype should be undef' ); + is( $course_item->{ccode}, undef, 'Course item ccode should be undef' ); + is( $course_item->{homebranch}, undef, 'Course item holding branch should be undef' ); + is( $course_item->{holdingbranch}, undef, 'Course item holding branch should be undef' ); + is( $course_item->{location}, undef, 'Course item location should be undef' ); - is($course_item->{itype_enabled}, 0, 'Course item itype enabled should be 0'); - is($course_item->{ccode_enabled}, 0, 'Course item ccode enabled should be 0'); - is($course_item->{homebranch_enabled}, 0, 'Course item holding branch enabled should be 0'); - is($course_item->{holdingbranch_enabled}, 0, 'Course item holding branch enabled should be 0'); - is($course_item->{location_enabled}, 0, 'Course item location enabled should be 0'); + is( $course_item->{itype_enabled}, 0, 'Course item itype enabled should be 0' ); + is( $course_item->{ccode_enabled}, 0, 'Course item ccode enabled should be 0' ); + is( $course_item->{homebranch_enabled}, 0, 'Course item holding branch enabled should be 0' ); + is( $course_item->{holdingbranch_enabled}, 0, 'Course item holding branch enabled should be 0' ); + is( $course_item->{location_enabled}, 0, 'Course item location enabled should be 0' ); $item = Koha::Items->find($itemnumber); - is($item->effective_itemtype, 'CD_foo', 'Item type in course should be CD_foo'); - is($item->ccode, 'CD', 'Item ccode in course should be CD'); - is($item->homebranch, 'B1', 'Item home branch in course should be B1'); - is($item->holdingbranch, 'B1', 'Item holding branch in course should be B1'); - is($item->location, 'HR', 'Item location in course should be HR'); + is( $item->effective_itemtype, 'CD_foo', 'Item type in course should be CD_foo' ); + is( $item->ccode, 'CD', 'Item ccode in course should be CD' ); + is( $item->homebranch, 'B1', 'Item home branch in course should be B1' ); + is( $item->holdingbranch, 'B1', 'Item holding branch in course should be B1' ); + is( $item->location, 'HR', 'Item location in course should be HR' ); }; subtest 'Ensure item info is preserved' => sub { plan tests => 8; - my $course = $builder->build({ source => 'Course' }); - my $item = $builder->build_sample_item({ ccode=>"grasshopper", location=>"transylvania"}); + my $course = $builder->build( { source => 'Course' } ); + my $item = $builder->build_sample_item( { ccode => "grasshopper", location => "transylvania" } ); + #Add course item but change nothing my $course_item_id = ModCourseItem( itemnumber => $item->itemnumber, @@ -344,6 +350,7 @@ subtest 'Ensure item info is preserved' => sub { holdingbranch => '', location => '', ); + #Add course reserve my $course_reserve_id = ModCourseReserve( course_id => $course->{course_id}, @@ -351,16 +358,30 @@ subtest 'Ensure item info is preserved' => sub { staff_note => '', public_note => '', ); + #Remove course reservei DelCourseReserve( cr_id => $course_reserve_id ); my $item_after = Koha::Items->find( $item->itemnumber ); - is( $item->effective_itemtype, $item_after->itype, "Itemtype is unchanged after adding to and removing from course reserves for inactive course"); - is( $item->location, $item_after->location, "Location is unchanged after adding to and removing from course reserves for inactive course"); - is( $item->holdingbranch, $item_after->holdingbranch, "Holdingbranch is unchanged after adding to and removing from course reserves for inactive course"); - is( $item->ccode, $item_after->ccode, "Collection is unchanged after adding to and removing from course reserves for inactive course"); + is( + $item->effective_itemtype, $item_after->itype, + "Itemtype is unchanged after adding to and removing from course reserves for inactive course" + ); + is( + $item->location, $item_after->location, + "Location is unchanged after adding to and removing from course reserves for inactive course" + ); + is( + $item->holdingbranch, $item_after->holdingbranch, + "Holdingbranch is unchanged after adding to and removing from course reserves for inactive course" + ); + is( + $item->ccode, $item_after->ccode, + "Collection is unchanged after adding to and removing from course reserves for inactive course" + ); + + $course = $builder->build( { source => 'Course' } ); + $item = $builder->build_sample_item( { ccode => "grasshopper", location => "transylvania" } ); - $course = $builder->build({ source => 'Course' }); - $item = $builder->build_sample_item({ ccode=>"grasshopper", location=>"transylvania"}); #Add course item but change nothing $course_item_id = ModCourseItem( itemnumber => $item->itemnumber, @@ -369,6 +390,7 @@ subtest 'Ensure item info is preserved' => sub { holdingbranch => '', location => '', ); + #Add course reserve $course_reserve_id = ModCourseReserve( course_id => $course->{course_id}, @@ -376,20 +398,34 @@ subtest 'Ensure item info is preserved' => sub { staff_note => '', public_note => '', ); + #Remove course reserve DelCourseReserve( cr_id => $course_reserve_id ); $item_after = Koha::Items->find( $item->itemnumber ); - is( $item->effective_itemtype, $item_after->itype, "Itemtype is unchanged after adding to and removing from course reserves for inactive course"); - is( $item->location, $item_after->location, "Location is unchanged after adding to and removing from course reserves for inactive course"); - is( $item->holdingbranch, $item_after->holdingbranch, "Holdingbranch is unchanged after adding to and removing from course reserves for inactive course"); - is( $item->ccode, $item_after->ccode, "Collection is unchanged after adding to and removing from course reserves for inactive course"); + is( + $item->effective_itemtype, $item_after->itype, + "Itemtype is unchanged after adding to and removing from course reserves for inactive course" + ); + is( + $item->location, $item_after->location, + "Location is unchanged after adding to and removing from course reserves for inactive course" + ); + is( + $item->holdingbranch, $item_after->holdingbranch, + "Holdingbranch is unchanged after adding to and removing from course reserves for inactive course" + ); + is( + $item->ccode, $item_after->ccode, + "Collection is unchanged after adding to and removing from course reserves for inactive course" + ); }; subtest 'biblio added to course without items' => sub { plan tests => 1; - my $course = $builder->build({ source => 'Course' }); + my $course = $builder->build( { source => 'Course' } ); + #Add course item but change nothing my $course_item_id = ModCourseItem( itemnumber => undef, @@ -399,6 +435,7 @@ subtest 'biblio added to course without items' => sub { holdingbranch => '', location => '', ); + #Add course reserve my $course_reserve_id = ModCourseReserve( course_id => $course->{course_id}, @@ -411,95 +448,113 @@ subtest 'biblio added to course without items' => sub { is( $course_item->{itemnumber}, undef, "Course reserve with no item correctly added" ); }; - - $schema->storage->txn_rollback; sub create_dependent_objects { - $builder->build({ - source => 'Itemtype', - value => { - itemtype => 'CD_foo', - description => 'Compact Disk' + $builder->build( + { + source => 'Itemtype', + value => { + itemtype => 'CD_foo', + description => 'Compact Disk' + } } - }); + ); - $builder->build({ - source => 'Itemtype', - value => { - itemtype => 'BK_foo', - description => 'Book' + $builder->build( + { + source => 'Itemtype', + value => { + itemtype => 'BK_foo', + description => 'Book' + } } - }); + ); - $builder->build({ - source => 'Branch', - value => { - branchcode => 'B1', - branchname => 'Branch 1' + $builder->build( + { + source => 'Branch', + value => { + branchcode => 'B1', + branchname => 'Branch 1' + } } - }); + ); - $builder->build({ - source => 'Branch', - value => { - branchcode => 'B2', - branchname => 'Branch 2' + $builder->build( + { + source => 'Branch', + value => { + branchcode => 'B2', + branchname => 'Branch 2' + } } - }); + ); - $builder->build({ - source => 'Branch', - value => { - branchcode => 'B3', - branchname => 'Branch 3' + $builder->build( + { + source => 'Branch', + value => { + branchcode => 'B3', + branchname => 'Branch 3' + } } - }); + ); - $builder->build({ - source => 'AuthorisedValue', - value => { - category => 'CCODE', - authorised_value => 'BOOK', - lib => 'Book' + $builder->build( + { + source => 'AuthorisedValue', + value => { + category => 'CCODE', + authorised_value => 'BOOK', + lib => 'Book' + } } - }); + ); - $builder->build({ - source => 'AuthorisedValue', - value => { - category => 'CCODE', - authorised_value => 'DVD', - lib => 'Book' + $builder->build( + { + source => 'AuthorisedValue', + value => { + category => 'CCODE', + authorised_value => 'DVD', + lib => 'Book' + } } - }); + ); - $builder->build({ - source => 'AuthorisedValue', - value => { - category => 'CCODE', - authorised_value => 'CD', - lib => 'Compact Disk' + $builder->build( + { + source => 'AuthorisedValue', + value => { + category => 'CCODE', + authorised_value => 'CD', + lib => 'Compact Disk' + } } - }); + ); - $builder->build({ - source => 'AuthorisedValue', - value => { - category => 'LOC', - authorised_value => 'HR', - lib => 'Here' + $builder->build( + { + source => 'AuthorisedValue', + value => { + category => 'LOC', + authorised_value => 'HR', + lib => 'Here' + } } - }); + ); - $builder->build({ - source => 'AuthorisedValue', - value => { - category => 'LOC', - authorised_value => 'TH', - lib => 'There' + $builder->build( + { + source => 'AuthorisedValue', + value => { + category => 'LOC', + authorised_value => 'TH', + lib => 'There' + } } - }); + ); } sub create_bib_and_item { @@ -511,5 +566,5 @@ sub create_bib_and_item { library => 'B1', } ); - return ($item->biblionumber, $item->itemnumber); + return ( $item->biblionumber, $item->itemnumber ); } diff --git a/t/db_dependent/Creators/Lib.t b/t/db_dependent/Creators/Lib.t index 5b314bcd68..c98088d928 100755 --- a/t/db_dependent/Creators/Lib.t +++ b/t/db_dependent/Creators/Lib.t @@ -26,7 +26,10 @@ use Koha::Database; use Test::Warn; BEGIN { - use_ok('C4::Creators::Lib', qw( get_all_templates get_all_layouts get_all_profiles get_all_image_names get_batch_summary get_label_summary get_card_summary get_barcode_types get_label_types get_font_types get_text_justification_types get_output_formats get_table_names get_unit_values html_table )); + use_ok( + 'C4::Creators::Lib', + qw( get_all_templates get_all_layouts get_all_profiles get_all_image_names get_batch_summary get_label_summary get_card_summary get_barcode_types get_label_types get_font_types get_text_justification_types get_output_formats get_table_names get_unit_values html_table ) + ); use_ok('C4::Biblio'); use_ok('C4::Context'); use_ok('Koha::Patron'); @@ -35,21 +38,21 @@ BEGIN { can_ok( 'C4::Creators::Lib', qw( - get_all_templates - get_all_layouts - get_all_profiles - get_all_image_names - get_batch_summary - get_label_summary - get_card_summary - get_barcode_types - get_label_types - get_font_types - get_text_justification_types - get_output_formats - get_table_names - get_unit_values - html_table ) + get_all_templates + get_all_layouts + get_all_profiles + get_all_image_names + get_batch_summary + get_label_summary + get_card_summary + get_barcode_types + get_label_types + get_font_types + get_text_justification_types + get_output_formats + get_table_names + get_unit_values + html_table ) ); my $schema = Koha::Database->schema; @@ -71,15 +74,21 @@ $dbh->do('DELETE FROM biblioitems'); # Inserted data ########################################################### -my $library1 = $builder->build({ - source => 'Branch', -}); -my $library2 = $builder->build({ - source => 'Branch', -}); -my $library3 = $builder->build({ - source => 'Branch', -}); +my $library1 = $builder->build( + { + source => 'Branch', + } +); +my $library2 = $builder->build( + { + source => 'Branch', + } +); +my $library3 = $builder->build( + { + source => 'Branch', + } +); # ---------- Some Templates -------------------- my $query = ' @@ -110,7 +119,10 @@ $query = ' creator) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)'; $insert_sth = $dbh->prepare($query); -$insert_sth->execute( 'COOP2OF5', 1, 'BAR1', 'NAME1', 1, 'TR', 11, 'POINT', 1, 'L', 'barcode', 'layout_xml1', 'Labels' ); +$insert_sth->execute( + 'COOP2OF5', 1, 'BAR1', 'NAME1', 1, 'TR', 11, 'POINT', 1, 'L', 'barcode', 'layout_xml1', + 'Labels' +); $insert_sth->execute( 'EAN13', 2, 'BAR2', 'NAME2', 2, 'TR', 12, 'POINT', 2, 'L', 'barcode', 'layout_xml2', 'Labels' ); @@ -258,7 +270,7 @@ $insert_sth->execute( 12, $item_number3, $borrowernumber3, $library3->{branchcod $dbi_st->mock( 'errstr', sub { return 'something went wrong'; } ); my $templates; warning_is { $templates = get_all_templates() } 'Database returned the following error: something went wrong', - 'get_all_templates() raises warning if something went wrong with the sql request execution'; + 'get_all_templates() raises warning if something went wrong with the sql request execution'; is( $templates, -1, '$templates return -1' ); } @@ -314,7 +326,7 @@ is( $templates->[1]->{units}, 'POINT', 'units is good is( $templates->[1]->{creator}, 'Labels', 'creator is good' ); # With field_list params -------------- -$templates = get_all_templates( {fields=> [qw(units cols rows)] } ); +$templates = get_all_templates( { fields => [qw(units cols rows)] } ); $query = ' SELECT count(*) @@ -337,12 +349,12 @@ isnt( exists $templates->[0]->{top_text_margin}, 2, 'top_text_margin isnt( exists $templates->[0]->{left_text_margin}, 3, 'left_text_margin is good' ); isnt( exists $templates->[0]->{top_margin}, 1, 'top_margin is good' ); isnt( exists $templates->[0]->{left_margin}, 4, 'left_margin is good' ); -is ( $templates->[0]->{cols}, 9, 'cols is good' ); -is ( $templates->[0]->{rows}, 6, 'rows is good' ); -isnt( exists $templates->[0]->{col_gap}, 0.1, 'col_gap is good' ); -isnt( exists $templates->[0]->{row_gap}, 0.2, 'row_gap is good' ); -is ( $templates->[0]->{units}, 'POINT', 'units is good' ); -isnt( exists $templates->[0]->{creator}, 'Labels', 'creator is good' ); +is( $templates->[0]->{cols}, 9, 'cols is good' ); +is( $templates->[0]->{rows}, 6, 'rows is good' ); +isnt( exists $templates->[0]->{col_gap}, 0.1, 'col_gap is good' ); +isnt( exists $templates->[0]->{row_gap}, 0.2, 'row_gap is good' ); +is( $templates->[0]->{units}, 'POINT', 'units is good' ); +isnt( exists $templates->[0]->{creator}, 'Labels', 'creator is good' ); isa_ok( $templates->[1], 'HASH', '$templates->[1] is a HASH' ); isnt( exists $templates->[1]->{profile_id}, 2, 'profile_id is good' ); @@ -356,15 +368,15 @@ isnt( exists $templates->[1]->{top_text_margin}, 3, 'top_text_margin isnt( exists $templates->[1]->{left_text_margin}, 4, 'left_text_margin is good' ); isnt( exists $templates->[1]->{top_margin}, 2, 'top_margin is good' ); isnt( exists $templates->[1]->{left_margin}, 5, 'left_margin is good' ); -is ( $templates->[1]->{cols}, 10, 'cols is good' ); -is ( $templates->[1]->{rows}, 7, 'rows is good' ); -isnt( exists $templates->[1]->{col_gap}, 0.2, 'col_gap is good' ); -isnt( exists $templates->[1]->{row_gap}, 0.3, 'row_gap is good' ); -is ( $templates->[1]->{units}, 'POINT', 'units is good' ); -isnt( exists $templates->[1]->{creator}, 'Labels', 'creator is good' ); +is( $templates->[1]->{cols}, 10, 'cols is good' ); +is( $templates->[1]->{rows}, 7, 'rows is good' ); +isnt( exists $templates->[1]->{col_gap}, 0.2, 'col_gap is good' ); +isnt( exists $templates->[1]->{row_gap}, 0.3, 'row_gap is good' ); +is( $templates->[1]->{units}, 'POINT', 'units is good' ); +isnt( exists $templates->[1]->{creator}, 'Labels', 'creator is good' ); # With filters params ------------------ -$templates = get_all_templates( { filters => { rows => 7} } ); +$templates = get_all_templates( { filters => { rows => 7 } } ); $query = ' SELECT count(*) @@ -395,8 +407,9 @@ is( $templates->[0]->{row_gap}, 0.3, 'row_gap is good is( $templates->[0]->{units}, 'POINT', 'units is good' ); is( $templates->[0]->{creator}, 'Labels', 'creator is good' ); -$templates = get_all_templates( { filters => { rows => [-42, 7]} } ); +$templates = get_all_templates( { filters => { rows => [ -42, 7 ] } } ); is( @$templates, $count, 'There is 1 template matching' ); + # With orderby param ------------------ $templates = get_all_templates( { orderby => '`rows` DESC' } ); @@ -455,7 +468,7 @@ is( $templates->[1]->{creator}, 'Labels', 'creator is good $dbi_st->mock( 'errstr', sub { return 'something went wrong'; } ); my $layouts; warning_is { $layouts = get_all_layouts() } 'Database returned the following error: something went wrong', - 'get_all_layouts() raises warning if something went wrong with the sql request execution'; + 'get_all_layouts() raises warning if something went wrong with the sql request execution'; is( $layouts, -1, '$layouts return -1' ); } @@ -503,7 +516,7 @@ is( $layouts->[1]->{layout_xml}, 'layout_xml2', 'layout_xml is good' ); is( $layouts->[1]->{creator}, 'Labels', 'creator is good' ); # With field_list params -------------- -$layouts = get_all_layouts( { fields => [qw(barcode_type layout_name font)] }); +$layouts = get_all_layouts( { fields => [qw(barcode_type layout_name font)] } ); $query = ' SELECT count(*) @@ -515,12 +528,12 @@ is( @$layouts, $count, 'There are 2 layouts matching' ); isa_ok( $layouts, 'ARRAY', '$layouts is an ARRAY' ); isa_ok( $layouts->[0], 'HASH', '$layouts->[0] is a HASH' ); -is ( $layouts->[0]->{barcode_type}, 'COOP2OF5', 'barcode_type is good' ); -isnt( exists $layouts->[0]->{start_label}, 1, 'start_label is good' ); -isnt( exists $layouts->[0]->{printing_type}, 'BAR1', 'printing_type is good' ); -is ( $layouts->[0]->{layout_name}, 'NAME1', 'layout_name is good' ); -isnt( exists $layouts->[0]->{guidebox}, 1, 'guidebox is good' ); -is ( $layouts->[0]->{font}, 'TR', 'font is good' ); +is( $layouts->[0]->{barcode_type}, 'COOP2OF5', 'barcode_type is good' ); +isnt( exists $layouts->[0]->{start_label}, 1, 'start_label is good' ); +isnt( exists $layouts->[0]->{printing_type}, 'BAR1', 'printing_type is good' ); +is( $layouts->[0]->{layout_name}, 'NAME1', 'layout_name is good' ); +isnt( exists $layouts->[0]->{guidebox}, 1, 'guidebox is good' ); +is( $layouts->[0]->{font}, 'TR', 'font is good' ); isnt( exists $layouts->[0]->{font_size}, 11, 'font_size is good' ); isnt( exists $layouts->[0]->{units}, 'POINT', 'units is good' ); isnt( exists $layouts->[0]->{callnum_split}, 1, 'callnum_split is good' ); @@ -530,15 +543,15 @@ isnt( exists $layouts->[0]->{layout_xml}, 'layout_xml1', 'layout_xml is g isnt( exists $layouts->[0]->{creator}, 'Labels', 'creator is good' ); isa_ok( $layouts->[1], 'HASH', '$layouts->[1] is a HASH' ); -is ( $layouts->[1]->{barcode_type}, 'EAN13', 'barcode_type is good' ); -isnt( exists $layouts->[1]->{start_label}, 2, 'start_label is good' ); -isnt( exists $layouts->[1]->{printing_type}, 'BAR2', 'printing_type is good' ); -is ( $layouts->[1]->{layout_name}, 'NAME2', 'layout_name is good' ); -isnt( exists $layouts->[1]->{guidebox}, 2, 'guidebox is good' ); -is ( $layouts->[1]->{font}, 'TR', 'font is good' ); -isnt( exists $layouts->[1]->{font_size}, 12, 'font_size is good' ); +is( $layouts->[1]->{barcode_type}, 'EAN13', 'barcode_type is good' ); +isnt( exists $layouts->[1]->{start_label}, 2, 'start_label is good' ); +isnt( exists $layouts->[1]->{printing_type}, 'BAR2', 'printing_type is good' ); +is( $layouts->[1]->{layout_name}, 'NAME2', 'layout_name is good' ); +isnt( exists $layouts->[1]->{guidebox}, 2, 'guidebox is good' ); +is( $layouts->[1]->{font}, 'TR', 'font is good' ); +isnt( exists $layouts->[1]->{font_size}, 12, 'font_size is good' ); isnt( exists $layouts->[1]->{units}, 'POINT', 'units is good' ); -isnt( exists $layouts->[1]->{callnum_split}, 2, 'callnum_split is good' ); +isnt( exists $layouts->[1]->{callnum_split}, 2, 'callnum_split is good' ); isnt( exists $layouts->[1]->{text_justify}, 'L', 'text_justify is good' ); isnt( exists $layouts->[1]->{format_string}, 'barcode', 'format_string is good' ); isnt( exists $layouts->[1]->{layout_xml}, 'layout_xml2', 'layout_xml is good' ); @@ -622,7 +635,7 @@ is( $layouts->[1]->{creator}, 'Labels', 'creator is good' ); $dbi_st->mock( 'errstr', sub { return 'something went wrong'; } ); my $profiles; warning_is { $profiles = get_all_profiles() } 'Database returned the following error: something went wrong', - 'get_all_profiles() raises warning if something went wrong with the sql request execution'; + 'get_all_profiles() raises warning if something went wrong with the sql request execution'; is( $profiles, -1, '$profiles return -1' ); } @@ -662,7 +675,7 @@ is( $profiles->[1]->{units}, 'POINT', 'units is good' ); is( $profiles->[1]->{creator}, 'Labels', 'creator is good' ); # With field_list params -------------- -$profiles = get_all_profiles( { fields => [qw(printer_name template_id)] }); +$profiles = get_all_profiles( { fields => [qw(printer_name template_id)] } ); $query = ' SELECT count(*) @@ -674,26 +687,26 @@ is( @$profiles, $count, 'There are 2 profiles matching' ); isa_ok( $profiles, 'ARRAY', '$profiles is an ARRAY' ); isa_ok( $profiles->[0], 'HASH', '$profiles->[0] is a HASH' ); -is ( $profiles->[0]->{printer_name}, 'Layout1 Name', 'printer_name is good' ); -is ( $profiles->[0]->{template_id}, 1234, 'template_id is good' ); -isnt( exists $profiles->[0]->{paper_bin}, 'Bypass', 'paper_bin is good' ); -isnt( exists $profiles->[0]->{offset_horz}, 0.1, 'offset_horz is good' ); -isnt( exists $profiles->[0]->{offset_vert}, 0.2, 'offset_vert is good' ); -isnt( exists $profiles->[0]->{creep_horz}, 0.3, 'creep_horz is good' ); -isnt( exists $profiles->[0]->{creep_vert}, 0.4, 'creep_vert is good' ); -isnt( exists $profiles->[0]->{units}, 'POINT', 'units is good' ); -isnt( exists $profiles->[0]->{creator}, 'Labels', 'creator is good' ); +is( $profiles->[0]->{printer_name}, 'Layout1 Name', 'printer_name is good' ); +is( $profiles->[0]->{template_id}, 1234, 'template_id is good' ); +isnt( exists $profiles->[0]->{paper_bin}, 'Bypass', 'paper_bin is good' ); +isnt( exists $profiles->[0]->{offset_horz}, 0.1, 'offset_horz is good' ); +isnt( exists $profiles->[0]->{offset_vert}, 0.2, 'offset_vert is good' ); +isnt( exists $profiles->[0]->{creep_horz}, 0.3, 'creep_horz is good' ); +isnt( exists $profiles->[0]->{creep_vert}, 0.4, 'creep_vert is good' ); +isnt( exists $profiles->[0]->{units}, 'POINT', 'units is good' ); +isnt( exists $profiles->[0]->{creator}, 'Labels', 'creator is good' ); isa_ok( $profiles->[1], 'HASH', '$profiles->[1] is a HASH' ); -is ( $profiles->[1]->{printer_name}, 'Layout2 Name', 'printer_name is good' ); -is ( $profiles->[1]->{template_id}, 1235, 'template_id is good' ); -isnt( exists $profiles->[1]->{paper_bin}, 'Bypass', 'paper_bin is good' ); -isnt( exists $profiles->[1]->{offset_horz}, 0.2, 'offset_horz is good' ); -isnt( exists $profiles->[1]->{offset_vert}, 0.3, 'offset_vert is good' ); -isnt( exists $profiles->[1]->{creep_horz}, 0.4, 'creep_horz is good' ); -isnt( exists $profiles->[1]->{creep_vert}, 0.5, 'creep_vert is good' ); -isnt( exists $profiles->[1]->{units}, 'POINT', 'units is good' ); -isnt( exists $profiles->[1]->{creator}, 'Labels', 'creator is good' ); +is( $profiles->[1]->{printer_name}, 'Layout2 Name', 'printer_name is good' ); +is( $profiles->[1]->{template_id}, 1235, 'template_id is good' ); +isnt( exists $profiles->[1]->{paper_bin}, 'Bypass', 'paper_bin is good' ); +isnt( exists $profiles->[1]->{offset_horz}, 0.2, 'offset_horz is good' ); +isnt( exists $profiles->[1]->{offset_vert}, 0.3, 'offset_vert is good' ); +isnt( exists $profiles->[1]->{creep_horz}, 0.4, 'creep_horz is good' ); +isnt( exists $profiles->[1]->{creep_vert}, 0.5, 'creep_vert is good' ); +isnt( exists $profiles->[1]->{units}, 'POINT', 'units is good' ); +isnt( exists $profiles->[1]->{creator}, 'Labels', 'creator is good' ); # With filters params ------------------ $profiles = get_all_profiles( { filters => { template_id => 1235 } } ); @@ -709,15 +722,15 @@ is( @$profiles, $count, 'There is 1 profile matching' ); isa_ok( $profiles, 'ARRAY', '$profiles is an ARRAY' ); isa_ok( $profiles->[0], 'HASH', '$profiles->[0] is a HASH' ); -is ( $profiles->[0]->{printer_name}, 'Layout2 Name', 'printer_name is good' ); -is ( $profiles->[0]->{template_id}, 1235, 'template_id is good' ); -isnt( exists $profiles->[0]->{paper_bin}, 'Bypass', 'paper_bin is good' ); -isnt( exists $profiles->[0]->{offset_horz}, 0.2, 'offset_horz is good' ); -isnt( exists $profiles->[0]->{offset_vert}, 0.3, 'offset_vert is good' ); -isnt( exists $profiles->[0]->{creep_horz}, 0.4, 'creep_horz is good' ); -isnt( exists $profiles->[0]->{creep_vert}, 0.5, 'creep_vert is good' ); -isnt( exists $profiles->[0]->{units}, 'POINT', 'units is good' ); -isnt( exists $profiles->[0]->{creator}, 'Labels', 'creator is good' ); +is( $profiles->[0]->{printer_name}, 'Layout2 Name', 'printer_name is good' ); +is( $profiles->[0]->{template_id}, 1235, 'template_id is good' ); +isnt( exists $profiles->[0]->{paper_bin}, 'Bypass', 'paper_bin is good' ); +isnt( exists $profiles->[0]->{offset_horz}, 0.2, 'offset_horz is good' ); +isnt( exists $profiles->[0]->{offset_vert}, 0.3, 'offset_vert is good' ); +isnt( exists $profiles->[0]->{creep_horz}, 0.4, 'creep_horz is good' ); +isnt( exists $profiles->[0]->{creep_vert}, 0.5, 'creep_vert is good' ); +isnt( exists $profiles->[0]->{units}, 'POINT', 'units is good' ); +isnt( exists $profiles->[0]->{creator}, 'Labels', 'creator is good' ); # ---------- Testing get_all_image_names ------------------ @@ -728,7 +741,7 @@ isnt( exists $profiles->[0]->{creator}, 'Labels', 'creator is $dbi_st->mock( 'errstr', sub { return 'something went wrong'; } ); my $images; warning_is { $images = get_all_image_names() } 'Database returned the following error: something went wrong', - 'get_all_image_names() raises warning if something went wrong with the sql request execution'; + 'get_all_image_names() raises warning if something went wrong with the sql request execution'; is( $images, -1, '$images return -1' ); } @@ -763,8 +776,9 @@ is( $images->[1]->{type}, $images->[1]->{name}, 'type is good' ); $dbi_st->mock( 'err', sub { return 1; } ); $dbi_st->mock( 'errstr', sub { return 'something went wrong'; } ); my $batches; - warning_is { $batches = get_batch_summary() } 'Database returned the following error on attempted SELECT: something went wrong', - 'get_batch_summary() raises warning if something went wrong with the sql request execution'; + warning_is { $batches = get_batch_summary() } + 'Database returned the following error on attempted SELECT: something went wrong', + 'get_batch_summary() raises warning if something went wrong with the sql request execution'; is( $batches, -1, '$batches return -1' ); } @@ -830,8 +844,9 @@ is( $batches->[0]->{_item_count}, $nb, 'item_number is good for this batch_id' ) my $labels; my @items = [ { item_number => $item_number1 } ]; - warning_is { $labels = get_label_summary( items => @items ) } 'Database returned the following error on attempted SELECT: something went wrong', - 'get_label_summary() raises warning if something went wrong with the sql request execution'; + warning_is { $labels = get_label_summary( items => @items ) } + 'Database returned the following error on attempted SELECT: something went wrong', + 'get_label_summary() raises warning if something went wrong with the sql request execution'; is( $labels, -1, '$labels return -1' ); } @@ -856,16 +871,20 @@ $query = ' FROM biblioitems WHERE biblioitemnumber = ? '; -my ( $bi_biblionumber1, $bi_biblioitemnumber1, $bi_itemtype1 ) = $dbh->selectrow_array( $query, {}, $biblioitemnumber1 ); -my ( $bi_biblionumber2, $bi_biblioitemnumber2, $bi_itemtype2 ) = $dbh->selectrow_array( $query, {}, $biblioitemnumber2 ); +my ( $bi_biblionumber1, $bi_biblioitemnumber1, $bi_itemtype1 ) = + $dbh->selectrow_array( $query, {}, $biblioitemnumber1 ); +my ( $bi_biblionumber2, $bi_biblioitemnumber2, $bi_itemtype2 ) = + $dbh->selectrow_array( $query, {}, $biblioitemnumber2 ); $query = ' SELECT biblionumber, biblioitemnumber, itemnumber, barcode, itype FROM items WHERE itemnumber = ? '; -my ( $i_biblionumber1, $i_biblioitemnumber1, $i_itemnumber1, $i_barcode1, $i_itype1 ) = $dbh->selectrow_array( $query, {}, $item_number1 ); -my ( $i_biblionumber2, $i_biblioitemnumber2, $i_itemnumber2, $i_barcode2, $i_itype2 ) = $dbh->selectrow_array( $query, {}, $item_number2 ); +my ( $i_biblionumber1, $i_biblioitemnumber1, $i_itemnumber1, $i_barcode1, $i_itype1 ) = + $dbh->selectrow_array( $query, {}, $item_number1 ); +my ( $i_biblionumber2, $i_biblioitemnumber2, $i_itemnumber2, $i_barcode2, $i_itype2 ) = + $dbh->selectrow_array( $query, {}, $item_number2 ); $query = ' SELECT label_id, batch_id, item_number @@ -884,7 +903,8 @@ is( $i_biblioitemnumber2, $bi_biblioitemnumber2, 'ITEMS.biblioitemnumber == is( $bi_biblionumber2, $b_biblionumber2, 'BIBLIOITEMS.biblionumber == BIBLIO.biblionumber' ); my @items = [ - { item_number => $item_number1, + { + item_number => $item_number1, label_id => $c_label_id1, } ]; @@ -898,7 +918,8 @@ my $record_author = $b_author1; my $record_title = $b_title1; $record_author =~ s/[^\.|\w]$//; $record_title =~ s/\W*$//; -$record_title = '<a href="/cgi-bin/koha/catalogue/detail.pl?biblionumber=' . $b_biblionumber1 . '"> ' . $b_title1 . '</a>'; +$record_title = + '<a href="/cgi-bin/koha/catalogue/detail.pl?biblionumber=' . $b_biblionumber1 . '"> ' . $b_title1 . '</a>'; my $summary1 = $record_title . " | " . ( $b_author1 ? $b_author1 : 'N/A' ); my $itemtypes_pref = C4::Context->preference("item-level_itypes"); my $record_itemtype = $itemtypes_pref ? $i_itype1 : $bi_itemtype1; @@ -914,7 +935,8 @@ is( $labels->[0]->{_label_id}, $c_label_id1, '_label_id # record without author @items = [ - { item_number => $item_number2, + { + item_number => $item_number2, label_id => $c_label_id2, } ]; @@ -927,10 +949,11 @@ isa_ok( $labels->[0], 'HASH', '$labels->[0] is an hash' ); $record_author = $b_author2; $record_title = $b_title2; $record_author =~ s/[^\.|\w]$// if $b_author2; -$record_title =~ s/\W*$//; -$record_title = '<a href="/cgi-bin/koha/catalogue/detail.pl?biblionumber=' . $b_biblionumber2 . '"> ' . $b_title2 . '</a>'; +$record_title =~ s/\W*$//; +$record_title = + '<a href="/cgi-bin/koha/catalogue/detail.pl?biblionumber=' . $b_biblionumber2 . '"> ' . $b_title2 . '</a>'; my $summary2 = $record_title . " | " . ( $b_author2 ? $b_author2 : 'N/A' ); -$itemtypes_pref = C4::Context->preference("item-level_itypes"); +$itemtypes_pref = C4::Context->preference("item-level_itypes"); $record_itemtype = $itemtypes_pref ? $i_itype2 : $bi_itemtype2; is( $labels->[0]->{_label_number}, 1, '_label_number is good' ); @@ -948,7 +971,8 @@ is( $labels->[0]->{_label_id}, $c_label_id2, '_label_id my $h = C4::Context->preference("item-level_itypes"); my @items = [ - { item_number => $item_number1, + { + item_number => $item_number1, label_id => $c_label_id1, } ]; @@ -962,7 +986,8 @@ is( $labels->[0]->{_label_id}, $c_label_id2, '_label_id my $record_title = $b_title1; $record_author =~ s/[^\.|\w]$//; $record_title =~ s/\W*$//; - $record_title = '<a href="/cgi-bin/koha/catalogue/detail.pl?biblionumber=' . $b_biblionumber1 . '"> ' . $b_title1 . '</a>'; + $record_title = + '<a href="/cgi-bin/koha/catalogue/detail.pl?biblionumber=' . $b_biblionumber1 . '"> ' . $b_title1 . '</a>'; my $summary1 = $record_title . " | " . ( $b_author1 ? $b_author1 : 'N/A' ); my $itemtypes_pref = C4::Context->preference("item-level_itypes"); my $record_itemtype = $itemtypes_pref ? $i_itype1 : $bi_itemtype1; @@ -987,8 +1012,9 @@ is( $labels->[0]->{_label_id}, $c_label_id2, '_label_id my $cards; my @items = [ { item_number => $item_number1 } ]; - warning_is { $cards = get_card_summary( items => @items ) } 'Database returned the following error on attempted SELECT: something went wrong', - 'get_card_summary() raises warning if something went wrong with the sql request execution'; + warning_is { $cards = get_card_summary( items => @items ) } + 'Database returned the following error on attempted SELECT: something went wrong', + 'get_card_summary() raises warning if something went wrong with the sql request execution'; is( $cards, -1, '$cards return -1' ); } @@ -1008,7 +1034,8 @@ $query = ' my ( $b_surname1, $b_firstname1, $b_cardnumber1 ) = $dbh->selectrow_array( $query, {}, $borrowernumber1 ); @items = [ - { item_number => $item_number1, + { + item_number => $item_number1, label_id => $c_label_id1, borrower_number => $borrowernumber1, } @@ -1032,43 +1059,62 @@ is( @$barcode_types, 6, 'There are 6 barcodes types' ); isa_ok( $barcode_types, 'ARRAY', '$barcode_types is an ARRAY' ); isa_ok( $barcode_types->[0], 'HASH', '$barcode_types->[0] is a HASH' ); -is( $barcode_types->[0]->{type}, 'CODE39', 'type is good' ); -is( $barcode_types->[0]->{name}, 'Code 39', 'name is good' ); -is( $barcode_types->[0]->{desc}, 'Translates the characters 0-9, A-Z, \'-\', \'*\', \'+\', \'$\', \'%\', \'/\', \'.\' and \' \' to a barcode pattern.', 'desc is good' ); -is( $barcode_types->[0]->{selected}, 0, 'selected is good' ); +is( $barcode_types->[0]->{type}, 'CODE39', 'type is good' ); +is( $barcode_types->[0]->{name}, 'Code 39', 'name is good' ); +is( + $barcode_types->[0]->{desc}, + 'Translates the characters 0-9, A-Z, \'-\', \'*\', \'+\', \'$\', \'%\', \'/\', \'.\' and \' \' to a barcode pattern.', + 'desc is good' +); +is( $barcode_types->[0]->{selected}, 0, 'selected is good' ); isa_ok( $barcode_types->[1], 'HASH', '$barcode_types->[1] is a HASH' ); is( $barcode_types->[1]->{type}, 'CODE39MOD', 'type is good' ); is( $barcode_types->[1]->{name}, 'Code 39 + Modulo43', 'name is good' ); -is( $barcode_types->[1]->{desc}, +is( + $barcode_types->[1]->{desc}, 'Translates the characters 0-9, A-Z, \'-\', \'*\', \'+\', \'$\', \'%\', \'/\', \'.\' and \' \' to a barcode pattern. Encodes Mod 43 checksum.', 'desc is good' ); is( $barcode_types->[1]->{selected}, 0, 'selected is good' ); isa_ok( $barcode_types->[2], 'HASH', '$barcode_types->[2] is a HASH' ); -is( $barcode_types->[2]->{type}, 'CODE39MOD10', 'type is good' ); -is( $barcode_types->[2]->{name}, 'Code 39 + Modulo10', 'name is good' ); -is( $barcode_types->[2]->{desc}, 'Translates the characters 0-9, A-Z, \'-\', \'*\', \'+\', \'$\', \'%\', \'/\', \'.\' and \' \' to a barcode pattern. Encodes Mod 10 checksum.', 'desc is good'); -is( $barcode_types->[2]->{selected}, 0, 'selected is good' ); +is( $barcode_types->[2]->{type}, 'CODE39MOD10', 'type is good' ); +is( $barcode_types->[2]->{name}, 'Code 39 + Modulo10', 'name is good' ); +is( + $barcode_types->[2]->{desc}, + 'Translates the characters 0-9, A-Z, \'-\', \'*\', \'+\', \'$\', \'%\', \'/\', \'.\' and \' \' to a barcode pattern. Encodes Mod 10 checksum.', + 'desc is good' +); +is( $barcode_types->[2]->{selected}, 0, 'selected is good' ); isa_ok( $barcode_types->[3], 'HASH', '$barcode_types->[3] is a HASH' ); -is( $barcode_types->[3]->{type}, 'COOP2OF5', 'type is good' ); -is( $barcode_types->[3]->{name}, 'COOP2of5', 'name is good' ); -is( $barcode_types->[3]->{desc}, 'Creates COOP2of5 barcodes from a string consisting of the numeric characters 0-9', 'desc is good' ); -is( $barcode_types->[3]->{selected}, 0, 'selected is good' ); +is( $barcode_types->[3]->{type}, 'COOP2OF5', 'type is good' ); +is( $barcode_types->[3]->{name}, 'COOP2of5', 'name is good' ); +is( + $barcode_types->[3]->{desc}, 'Creates COOP2of5 barcodes from a string consisting of the numeric characters 0-9', + 'desc is good' +); +is( $barcode_types->[3]->{selected}, 0, 'selected is good' ); isa_ok( $barcode_types->[4], 'HASH', '$barcode_types->[4] is a HASH' ); -is( $barcode_types->[4]->{type}, 'EAN13', 'type is good' ); -is( $barcode_types->[4]->{name}, 'EAN13', 'name is good' ); -is( $barcode_types->[4]->{desc}, 'Creates EAN13 barcodes from a string of 12 or 13 digits. The check number (the 13:th digit) is calculated if not supplied.', 'desc is good' ); -is( $barcode_types->[4]->{selected}, 0, 'selected is good' ); +is( $barcode_types->[4]->{type}, 'EAN13', 'type is good' ); +is( $barcode_types->[4]->{name}, 'EAN13', 'name is good' ); +is( + $barcode_types->[4]->{desc}, + 'Creates EAN13 barcodes from a string of 12 or 13 digits. The check number (the 13:th digit) is calculated if not supplied.', + 'desc is good' +); +is( $barcode_types->[4]->{selected}, 0, 'selected is good' ); isa_ok( $barcode_types->[5], 'HASH', '$barcode_types->[5] is a HASH' ); -is( $barcode_types->[5]->{type}, 'INDUSTRIAL2OF5', 'type is good' ); -is( $barcode_types->[5]->{name}, 'Industrial2of5', 'name is good' ); -is( $barcode_types->[5]->{desc}, 'Creates Industrial2of5 barcodes from a string consisting of the numeric characters 0-9', 'desc is good' ); -is( $barcode_types->[5]->{selected}, 0, 'selected is good' ); +is( $barcode_types->[5]->{type}, 'INDUSTRIAL2OF5', 'type is good' ); +is( $barcode_types->[5]->{name}, 'Industrial2of5', 'name is good' ); +is( + $barcode_types->[5]->{desc}, + 'Creates Industrial2of5 barcodes from a string consisting of the numeric characters 0-9', 'desc is good' +); +is( $barcode_types->[5]->{selected}, 0, 'selected is good' ); # ---------- Testing get_label_types ---------------------- my $label_types = get_label_types(); @@ -1095,10 +1141,13 @@ is( $label_types->[2]->{desc}, 'Bibliographic data proceeds barcode.', 'desc is( $label_types->[2]->{selected}, 0, 'selected is good' ); isa_ok( $label_types->[3], 'HASH', '$label_types->[3] is a HASH' ); -is( $label_types->[3]->{type}, 'ALT', 'type is good' ); -is( $label_types->[3]->{name}, 'Alternating', 'name is good' ); -is( $label_types->[3]->{desc}, 'Barcode and bibliographic data are printed on alternating labels.', 'desc is good' ); -is( $label_types->[3]->{selected}, 0, 'selected is good' ); +is( $label_types->[3]->{type}, 'ALT', 'type is good' ); +is( $label_types->[3]->{name}, 'Alternating', 'name is good' ); +is( + $label_types->[3]->{desc}, 'Barcode and bibliographic data are printed on alternating labels.', + 'desc is good' +); +is( $label_types->[3]->{selected}, 0, 'selected is good' ); isa_ok( $label_types->[4], 'HASH', '$label_types->[4] is a HASH' ); is( $label_types->[4]->{type}, 'BAR', 'type is good' ); @@ -1110,7 +1159,6 @@ $label_types->[0]->{selected} = 1; $label_types = get_label_types(); is( $label_types->[0]->{selected}, 0, 'get_label_types must returned a new structure (copied)' ); - # ---------- Testing get_font_types ----------------------- my $font_types = get_font_types(); @@ -1118,59 +1166,59 @@ is( @$font_types, 12, 'There are 12 font types' ); isa_ok( $font_types, 'ARRAY', '$font_types is an ARRAY' ); isa_ok( $font_types->[0], 'HASH', '$font_types->[0] is a HASH' ); -is( $font_types->[0]->{type}, 'TR', 'type is good' ); -is( $font_types->[0]->{name}, 'Times-Roman', 'name is good' ); -is( $font_types->[0]->{selected}, 0, 'selected is good' ); +is( $font_types->[0]->{type}, 'TR', 'type is good' ); +is( $font_types->[0]->{name}, 'Times-Roman', 'name is good' ); +is( $font_types->[0]->{selected}, 0, 'selected is good' ); isa_ok( $font_types->[1], 'HASH', '$font_types->[1] is a HASH' ); -is( $font_types->[1]->{type}, 'TB', 'type is good' ); -is( $font_types->[1]->{name}, 'Times-Bold', 'name is good' ); -is( $font_types->[1]->{selected}, 0, 'selected is good' ); +is( $font_types->[1]->{type}, 'TB', 'type is good' ); +is( $font_types->[1]->{name}, 'Times-Bold', 'name is good' ); +is( $font_types->[1]->{selected}, 0, 'selected is good' ); isa_ok( $font_types->[2], 'HASH', '$font_types->[2] is a HASH' ); -is( $font_types->[2]->{type}, 'TI', 'type is good' ); -is( $font_types->[2]->{name}, 'Times-Italic', 'name is good' ); -is( $font_types->[2]->{selected}, 0, 'selected is good' ); +is( $font_types->[2]->{type}, 'TI', 'type is good' ); +is( $font_types->[2]->{name}, 'Times-Italic', 'name is good' ); +is( $font_types->[2]->{selected}, 0, 'selected is good' ); isa_ok( $font_types->[3], 'HASH', '$font_types->[3] is a HASH' ); -is( $font_types->[3]->{type}, 'TBI', 'type is good' ); -is( $font_types->[3]->{name}, 'Times-Bold-Italic', 'name is good' ); -is( $font_types->[3]->{selected}, 0, 'selected is good' ); +is( $font_types->[3]->{type}, 'TBI', 'type is good' ); +is( $font_types->[3]->{name}, 'Times-Bold-Italic', 'name is good' ); +is( $font_types->[3]->{selected}, 0, 'selected is good' ); isa_ok( $font_types->[4], 'HASH', '$font_types->[4] is a HASH' ); -is( $font_types->[4]->{type}, 'C', 'type is good' ); -is( $font_types->[4]->{name}, 'Courier', 'name is good' ); -is( $font_types->[4]->{selected}, 0, 'selected is good' ); +is( $font_types->[4]->{type}, 'C', 'type is good' ); +is( $font_types->[4]->{name}, 'Courier', 'name is good' ); +is( $font_types->[4]->{selected}, 0, 'selected is good' ); isa_ok( $font_types->[5], 'HASH', '$font_types->[5] is a HASH' ); -is( $font_types->[5]->{type}, 'CB', 'type is good' ); -is( $font_types->[5]->{name}, 'Courier-Bold', 'name is good' ); -is( $font_types->[5]->{selected}, 0, 'selected is good' ); +is( $font_types->[5]->{type}, 'CB', 'type is good' ); +is( $font_types->[5]->{name}, 'Courier-Bold', 'name is good' ); +is( $font_types->[5]->{selected}, 0, 'selected is good' ); isa_ok( $font_types->[6], 'HASH', '$font_types->[6] is a HASH' ); -is( $font_types->[6]->{type}, 'CO', 'type is good' ); -is( $font_types->[6]->{name}, 'Courier-Oblique', 'name is good' ); -is( $font_types->[6]->{selected}, 0, 'selected is good' ); +is( $font_types->[6]->{type}, 'CO', 'type is good' ); +is( $font_types->[6]->{name}, 'Courier-Oblique', 'name is good' ); +is( $font_types->[6]->{selected}, 0, 'selected is good' ); isa_ok( $font_types->[7], 'HASH', '$font_types->[7] is a HASH' ); -is( $font_types->[7]->{type}, 'CBO', 'type is good' ); -is( $font_types->[7]->{name}, 'Courier-Bold-Oblique', 'name is good' ); -is( $font_types->[7]->{selected}, 0, 'selected is good' ); +is( $font_types->[7]->{type}, 'CBO', 'type is good' ); +is( $font_types->[7]->{name}, 'Courier-Bold-Oblique', 'name is good' ); +is( $font_types->[7]->{selected}, 0, 'selected is good' ); isa_ok( $font_types->[8], 'HASH', '$font_types->[8] is a HASH' ); -is( $font_types->[8]->{type}, 'H', 'type is good' ); -is( $font_types->[8]->{name}, 'Helvetica', 'name is good' ); -is( $font_types->[8]->{selected}, 0, 'selected is good' ); +is( $font_types->[8]->{type}, 'H', 'type is good' ); +is( $font_types->[8]->{name}, 'Helvetica', 'name is good' ); +is( $font_types->[8]->{selected}, 0, 'selected is good' ); isa_ok( $font_types->[9], 'HASH', '$font_types->[9] is a HASH' ); -is( $font_types->[9]->{type}, 'HO', 'type is good' ); -is( $font_types->[9]->{name}, 'Helvetica-Oblique', 'name is good' ); -is( $font_types->[9]->{selected}, 0, 'selected is good' ); +is( $font_types->[9]->{type}, 'HO', 'type is good' ); +is( $font_types->[9]->{name}, 'Helvetica-Oblique', 'name is good' ); +is( $font_types->[9]->{selected}, 0, 'selected is good' ); isa_ok( $font_types->[10], 'HASH', '$font_types->[10] is a HASH' ); -is( $font_types->[10]->{type}, 'HB', 'type is good' ); -is( $font_types->[10]->{name}, 'Helvetica-Bold', 'name is good' ); -is( $font_types->[10]->{selected}, 0, 'selected is good' ); +is( $font_types->[10]->{type}, 'HB', 'type is good' ); +is( $font_types->[10]->{name}, 'Helvetica-Bold', 'name is good' ); +is( $font_types->[10]->{selected}, 0, 'selected is good' ); isa_ok( $font_types->[11], 'HASH', '$font_types->[11] is a HASH' ); is( $font_types->[11]->{type}, 'HBO', 'type is good' ); @@ -1184,19 +1232,19 @@ is( @$text_justification_types, 3, 'There are 3 text justification types' ); isa_ok( $text_justification_types, 'ARRAY', '$text_justification_types is an ARRAY' ); isa_ok( $text_justification_types->[0], 'HASH', '$font_types->[0] is a HASH' ); -is( $text_justification_types->[0]->{type}, 'L', 'type is good' ); -is( $text_justification_types->[0]->{name}, 'Left', 'name is good' ); -is( $text_justification_types->[0]->{selected}, 0, 'selected is good' ); +is( $text_justification_types->[0]->{type}, 'L', 'type is good' ); +is( $text_justification_types->[0]->{name}, 'Left', 'name is good' ); +is( $text_justification_types->[0]->{selected}, 0, 'selected is good' ); isa_ok( $text_justification_types->[1], 'HASH', '$font_types->[1] is a HASH' ); -is( $text_justification_types->[1]->{type}, 'C', 'type is good' ); -is( $text_justification_types->[1]->{name}, 'Center', 'name is good' ); -is( $text_justification_types->[1]->{selected}, 0, 'selected is good' ); +is( $text_justification_types->[1]->{type}, 'C', 'type is good' ); +is( $text_justification_types->[1]->{name}, 'Center', 'name is good' ); +is( $text_justification_types->[1]->{selected}, 0, 'selected is good' ); isa_ok( $text_justification_types->[2], 'HASH', '$font_types->[2] is a HASH' ); -is( $text_justification_types->[2]->{type}, 'R', 'type is good' ); -is( $text_justification_types->[2]->{name}, 'Right', 'name is good' ); -is( $text_justification_types->[2]->{selected}, 0, 'selected is good' ); +is( $text_justification_types->[2]->{type}, 'R', 'type is good' ); +is( $text_justification_types->[2]->{name}, 'Right', 'name is good' ); +is( $text_justification_types->[2]->{selected}, 0, 'selected is good' ); # ---------- Testing get_unit_values ---------------------- my $unit_values = get_unit_values(); @@ -1205,34 +1253,34 @@ is( @$unit_values, 5, 'There are 5 unit values' ); isa_ok( $unit_values, 'ARRAY', '$unit_values is an ARRAY' ); isa_ok( $unit_values->[0], 'HASH', '$unit_values->[0] is a HASH' ); -is( $unit_values->[0]->{type}, 'POINT', 'type is good' ); -is( $unit_values->[0]->{desc}, 'PostScript Points', 'desc is good' ); -is( $unit_values->[0]->{value}, 1, 'value is good' ); -is( $unit_values->[0]->{selected}, 0, 'selected is good' ); +is( $unit_values->[0]->{type}, 'POINT', 'type is good' ); +is( $unit_values->[0]->{desc}, 'PostScript Points', 'desc is good' ); +is( $unit_values->[0]->{value}, 1, 'value is good' ); +is( $unit_values->[0]->{selected}, 0, 'selected is good' ); isa_ok( $unit_values->[1], 'HASH', '$unit_values->[1] is a HASH' ); -is( $unit_values->[1]->{type}, 'AGATE', 'type is good' ); -is( $unit_values->[1]->{desc}, 'Adobe Agates', 'desc is good' ); -is( $unit_values->[1]->{value}, 5.1428571, 'value is good' ); -is( $unit_values->[1]->{selected}, 0, 'selected is good' ); +is( $unit_values->[1]->{type}, 'AGATE', 'type is good' ); +is( $unit_values->[1]->{desc}, 'Adobe Agates', 'desc is good' ); +is( $unit_values->[1]->{value}, 5.1428571, 'value is good' ); +is( $unit_values->[1]->{selected}, 0, 'selected is good' ); isa_ok( $unit_values->[2], 'HASH', '$unit_values->[2] is a HASH' ); -is( $unit_values->[2]->{type}, 'INCH', 'type is good' ); -is( $unit_values->[2]->{desc}, 'US Inches', 'desc is good' ); -is( $unit_values->[2]->{value}, 72, 'value is good' ); -is( $unit_values->[2]->{selected}, 0, 'selected is good' ); +is( $unit_values->[2]->{type}, 'INCH', 'type is good' ); +is( $unit_values->[2]->{desc}, 'US Inches', 'desc is good' ); +is( $unit_values->[2]->{value}, 72, 'value is good' ); +is( $unit_values->[2]->{selected}, 0, 'selected is good' ); isa_ok( $unit_values->[3], 'HASH', '$unit_values->[3] is a HASH' ); -is( $unit_values->[3]->{type}, 'MM', 'type is good' ); -is( $unit_values->[3]->{desc}, 'SI Millimeters', 'desc is good' ); -is( $unit_values->[3]->{value}, 2.83464567, 'value is good' ); -is( $unit_values->[3]->{selected}, 0, 'selected is good' ); +is( $unit_values->[3]->{type}, 'MM', 'type is good' ); +is( $unit_values->[3]->{desc}, 'SI Millimeters', 'desc is good' ); +is( $unit_values->[3]->{value}, 2.83464567, 'value is good' ); +is( $unit_values->[3]->{selected}, 0, 'selected is good' ); isa_ok( $unit_values->[4], 'HASH', '$unit_values->[4] is a HASH' ); -is( $unit_values->[4]->{type}, 'CM', 'type is good' ); -is( $unit_values->[4]->{desc}, 'SI Centimeters', 'desc is good' ); -is( $unit_values->[4]->{value}, 28.3464567, 'value is good' ); -is( $unit_values->[4]->{selected}, 0, 'selected is good' ); +is( $unit_values->[4]->{type}, 'CM', 'type is good' ); +is( $unit_values->[4]->{desc}, 'SI Centimeters', 'desc is good' ); +is( $unit_values->[4]->{value}, 28.3464567, 'value is good' ); +is( $unit_values->[4]->{selected}, 0, 'selected is good' ); # ---------- Testing get_output_formats ------------------- my $output_formats = get_output_formats(); @@ -1281,12 +1329,13 @@ my $display_columns = [ #without $data param ------------------ my $db_rows = []; -my $table = html_table( $display_columns, $db_rows ); +my $table = html_table( $display_columns, $db_rows ); is( $table, undef, 'No need to generate a table if there is not data to display' ); #with $data param --------------------- $db_rows = [ - { _label_number => 1, + { + _label_number => 1, _summary => $summary1, _item_type => 'Book', _barcode => $barcode1, @@ -1304,40 +1353,40 @@ isa_ok( $table->[0]->{header_fields}, 'ARRAY', '$table->[0]->{header_fields} is is( scalar( @{ $table->[0]->{header_fields} } ), 6, 'There are 7 header_fields' ); my $field_value = $display_columns->[0]->{_label_number}->{label}; -is( $table->[0]->{header_fields}->[0]->{hidden}, 0, '[Label Number] hidden field is good' ); -is( $table->[0]->{header_fields}->[0]->{select_field}, 0, '[Label Number] select_field field is good' ); -is( $table->[0]->{header_fields}->[0]->{field_name}, '_label_number', '[Label Number] field_name field is good' ); -is( $table->[0]->{header_fields}->[0]->{field_label}, $field_value, '[Label Number] field_label field is good' ); +is( $table->[0]->{header_fields}->[0]->{hidden}, 0, '[Label Number] hidden field is good' ); +is( $table->[0]->{header_fields}->[0]->{select_field}, 0, '[Label Number] select_field field is good' ); +is( $table->[0]->{header_fields}->[0]->{field_name}, '_label_number', '[Label Number] field_name field is good' ); +is( $table->[0]->{header_fields}->[0]->{field_label}, $field_value, '[Label Number] field_label field is good' ); $field_value = $display_columns->[1]->{_summary}->{label}; -is( $table->[0]->{header_fields}->[1]->{hidden}, 0, '[Summary] hidden field is good' ); -is( $table->[0]->{header_fields}->[1]->{select_field}, 0, '[Summary] select_field field is good' ); -is( $table->[0]->{header_fields}->[1]->{field_name}, '_summary', '[Summary] field_name field is good' ); -is( $table->[0]->{header_fields}->[1]->{field_label}, $field_value, '[Summary] field_label field is good' ); +is( $table->[0]->{header_fields}->[1]->{hidden}, 0, '[Summary] hidden field is good' ); +is( $table->[0]->{header_fields}->[1]->{select_field}, 0, '[Summary] select_field field is good' ); +is( $table->[0]->{header_fields}->[1]->{field_name}, '_summary', '[Summary] field_name field is good' ); +is( $table->[0]->{header_fields}->[1]->{field_label}, $field_value, '[Summary] field_label field is good' ); $field_value = $display_columns->[2]->{_item_type}->{label}; -is( $table->[0]->{header_fields}->[2]->{hidden}, 0, '[Item Type] hidden field is good' ); -is( $table->[0]->{header_fields}->[2]->{select_field}, 0, '[Item Type] select_field field is good' ); -is( $table->[0]->{header_fields}->[2]->{field_name}, '_item_type', '[Item Type] field_name field is good' ); -is( $table->[0]->{header_fields}->[2]->{field_label}, $field_value, '[Item Type] field_label field is good' ); +is( $table->[0]->{header_fields}->[2]->{hidden}, 0, '[Item Type] hidden field is good' ); +is( $table->[0]->{header_fields}->[2]->{select_field}, 0, '[Item Type] select_field field is good' ); +is( $table->[0]->{header_fields}->[2]->{field_name}, '_item_type', '[Item Type] field_name field is good' ); +is( $table->[0]->{header_fields}->[2]->{field_label}, $field_value, '[Item Type] field_label field is good' ); $field_value = $display_columns->[3]->{_barcode}->{label}; -is( $table->[0]->{header_fields}->[3]->{hidden}, 0, '[Barcode] hidden field is good' ); -is( $table->[0]->{header_fields}->[3]->{select_field}, 0, '[Barcode] select_field field is good' ); -is( $table->[0]->{header_fields}->[3]->{field_name}, '_barcode', '[Barcode] field_name field is good' ); -is( $table->[0]->{header_fields}->[3]->{field_label}, $field_value, '[Barcode] field_label field is good' ); +is( $table->[0]->{header_fields}->[3]->{hidden}, 0, '[Barcode] hidden field is good' ); +is( $table->[0]->{header_fields}->[3]->{select_field}, 0, '[Barcode] select_field field is good' ); +is( $table->[0]->{header_fields}->[3]->{field_name}, '_barcode', '[Barcode] field_name field is good' ); +is( $table->[0]->{header_fields}->[3]->{field_label}, $field_value, '[Barcode] field_label field is good' ); $field_value = $display_columns->[4]->{_template_code}->{label}; -is( $table->[0]->{header_fields}->[4]->{hidden}, 0, '[Template Code] hidden field is good' ); -is( $table->[0]->{header_fields}->[4]->{select_field}, 0, '[Template Code] select_field field is good' ); -is( $table->[0]->{header_fields}->[4]->{field_name}, '_template_code', '[Template Code] field_name field is good' ); -is( $table->[0]->{header_fields}->[4]->{field_label}, $field_value, '[Template Code] field_label field is good' ); +is( $table->[0]->{header_fields}->[4]->{hidden}, 0, '[Template Code] hidden field is good' ); +is( $table->[0]->{header_fields}->[4]->{select_field}, 0, '[Template Code] select_field field is good' ); +is( $table->[0]->{header_fields}->[4]->{field_name}, '_template_code', '[Template Code] field_name field is good' ); +is( $table->[0]->{header_fields}->[4]->{field_label}, $field_value, '[Template Code] field_label field is good' ); $field_value = $display_columns->[5]->{select}->{label}; -is( $table->[0]->{header_fields}->[5]->{hidden}, 0, '[Select] hidden field is good' ); -is( $table->[0]->{header_fields}->[5]->{select_field}, 0, '[Select] select_field field is good' ); -is( $table->[0]->{header_fields}->[5]->{field_name}, 'select', '[Select] field_name field is good' ); -is( $table->[0]->{header_fields}->[5]->{field_label}, $field_value, '[Select] field_label field is good' ); +is( $table->[0]->{header_fields}->[5]->{hidden}, 0, '[Select] hidden field is good' ); +is( $table->[0]->{header_fields}->[5]->{select_field}, 0, '[Select] select_field field is good' ); +is( $table->[0]->{header_fields}->[5]->{field_name}, 'select', '[Select] field_name field is good' ); +is( $table->[0]->{header_fields}->[5]->{field_label}, $field_value, '[Select] field_label field is good' ); #POPULATE TABLE isa_ok( $table->[1]->{text_fields}, 'ARRAY', '$table->[0]->{text_fields} is an ARRAY' ); @@ -1347,38 +1396,38 @@ is( scalar( @{ $table->[1]->{text_fields} } ), 6, 'There are 6 text_fields' ); my $link_field = $display_columns->[0]->{_label_number}->{link_field}; my $field_name = "$table->[0]->{header_fields}->[0]->{field_name}_tbl"; $field_value = $db_rows->[0]->{_label_number}; -is( $table->[1]->{text_fields}->[0]->{hidden}, 0, '[Label Number] hidden field is good' ); -is( $table->[1]->{text_fields}->[0]->{link_field}, $link_field, '[Label Number] link_field field is good' ); -is( $table->[1]->{text_fields}->[0]->{select_field}, 0, '[Label Number] select_field field is good' ); -is( $table->[1]->{text_fields}->[0]->{field_name}, $field_name, '[Label Number] field_name field is good' ); -is( $table->[1]->{text_fields}->[0]->{field_value}, $field_value, '[Label Number] field_value field is good' ); +is( $table->[1]->{text_fields}->[0]->{hidden}, 0, '[Label Number] hidden field is good' ); +is( $table->[1]->{text_fields}->[0]->{link_field}, $link_field, '[Label Number] link_field field is good' ); +is( $table->[1]->{text_fields}->[0]->{select_field}, 0, '[Label Number] select_field field is good' ); +is( $table->[1]->{text_fields}->[0]->{field_name}, $field_name, '[Label Number] field_name field is good' ); +is( $table->[1]->{text_fields}->[0]->{field_value}, $field_value, '[Label Number] field_value field is good' ); $link_field = $display_columns->[1]->{_summary}->{link_field}; $field_value = $db_rows->[0]->{_summary}; $field_name = "$table->[0]->{header_fields}->[1]->{field_name}_tbl"; -is( $table->[1]->{text_fields}->[1]->{hidden}, 0, '[Summary] hidden field is good' ); -is( $table->[1]->{text_fields}->[1]->{link_field}, $link_field, '[Summary] link_field field is good' ); -is( $table->[1]->{text_fields}->[1]->{select_field}, 0, '[Summary] select_field field is good' ); -is( $table->[1]->{text_fields}->[1]->{field_name}, $field_name, '[Summary] field_name field is good' ); -is( $table->[1]->{text_fields}->[1]->{field_value}, $field_value, '[Summary] field_value field is good' ); +is( $table->[1]->{text_fields}->[1]->{hidden}, 0, '[Summary] hidden field is good' ); +is( $table->[1]->{text_fields}->[1]->{link_field}, $link_field, '[Summary] link_field field is good' ); +is( $table->[1]->{text_fields}->[1]->{select_field}, 0, '[Summary] select_field field is good' ); +is( $table->[1]->{text_fields}->[1]->{field_name}, $field_name, '[Summary] field_name field is good' ); +is( $table->[1]->{text_fields}->[1]->{field_value}, $field_value, '[Summary] field_value field is good' ); $link_field = $display_columns->[2]->{_item_type}->{link_field}; $field_name = "$table->[0]->{header_fields}->[2]->{field_name}_tbl"; $field_value = $db_rows->[0]->{_item_type}; -is( $table->[1]->{text_fields}->[2]->{hidden}, 0, '[Item Type] hidden field is good' ); -is( $table->[1]->{text_fields}->[2]->{link_field}, $link_field, '[Item Type] link_field field is good' ); -is( $table->[1]->{text_fields}->[2]->{select_field}, 0, '[Item Type] select_field field is good' ); -is( $table->[1]->{text_fields}->[2]->{field_name}, $field_name, '[Item Type] field_name field is good' ); -is( $table->[1]->{text_fields}->[2]->{field_value}, $field_value, '[Item Type] field_value field is good' ); +is( $table->[1]->{text_fields}->[2]->{hidden}, 0, '[Item Type] hidden field is good' ); +is( $table->[1]->{text_fields}->[2]->{link_field}, $link_field, '[Item Type] link_field field is good' ); +is( $table->[1]->{text_fields}->[2]->{select_field}, 0, '[Item Type] select_field field is good' ); +is( $table->[1]->{text_fields}->[2]->{field_name}, $field_name, '[Item Type] field_name field is good' ); +is( $table->[1]->{text_fields}->[2]->{field_value}, $field_value, '[Item Type] field_value field is good' ); $link_field = $display_columns->[3]->{_barcode}->{link_field}; $field_name = "$table->[0]->{header_fields}->[3]->{field_name}_tbl"; $field_value = $db_rows->[0]->{_barcode}; -is( $table->[1]->{text_fields}->[3]->{hidden}, 0, '[Barcode] hidden field is good' ); -is( $table->[1]->{text_fields}->[3]->{link_field}, $link_field, '[Barcode] link_field field is good' ); -is( $table->[1]->{text_fields}->[3]->{select_field}, 0, '[Barcode] select_field field is good' ); -is( $table->[1]->{text_fields}->[3]->{field_name}, $field_name, '[Barcode] field_name field is good' ); -is( $table->[1]->{text_fields}->[3]->{field_value}, $field_value, '[Barcode] field_value field is good' ); +is( $table->[1]->{text_fields}->[3]->{hidden}, 0, '[Barcode] hidden field is good' ); +is( $table->[1]->{text_fields}->[3]->{link_field}, $link_field, '[Barcode] link_field field is good' ); +is( $table->[1]->{text_fields}->[3]->{select_field}, 0, '[Barcode] select_field field is good' ); +is( $table->[1]->{text_fields}->[3]->{field_name}, $field_name, '[Barcode] field_name field is good' ); +is( $table->[1]->{text_fields}->[3]->{field_value}, $field_value, '[Barcode] field_value field is good' ); #test : elsif ($table_column =~ m/^_((.*)_(.*$))/) $link_field = $display_columns->[4]->{_template_code}->{link_field}; @@ -1391,10 +1440,10 @@ is( $table->[1]->{text_fields}->[4]->{field_value}, $template_code1, '[Template #test : elsif ($table_column eq 'select') $field_value = $db_rows->[0]->{_label_id}; -is( $table->[1]->{text_fields}->[5]->{hidden}, 0, '[Select] hidden field is good' ); -is( $table->[1]->{text_fields}->[5]->{select_field}, 1, '[Select] select_field field is good' ); -is( $table->[1]->{text_fields}->[5]->{field_name}, 'select', '[Select] field_name field is good' ); -is( $table->[1]->{text_fields}->[5]->{field_value}, $field_value, '[Select] field_value field is good' ); +is( $table->[1]->{text_fields}->[5]->{hidden}, 0, '[Select] hidden field is good' ); +is( $table->[1]->{text_fields}->[5]->{select_field}, 1, '[Select] select_field field is good' ); +is( $table->[1]->{text_fields}->[5]->{field_name}, 'select', '[Select] field_name field is good' ); +is( $table->[1]->{text_fields}->[5]->{field_value}, $field_value, '[Select] field_value field is good' ); # ---------- Testing _SELECT --------------------------- # Mocking $sth->err and $sth->errstr @@ -1403,8 +1452,9 @@ is( $table->[1]->{text_fields}->[5]->{field_value}, $field_value, '[Select] $dbi_st->mock( 'err', sub { return 1; } ); $dbi_st->mock( 'errstr', sub { return 'something went wrong'; } ); my $records; - warning_is { $records = C4::Creators::Lib::_SELECT( '*', 'borrowers', "borrowernumber = $borrowernumber1" ) } 'Database returned the following error: something went wrong', - '_SELECT raises warning if something went wrong with the sql request execution'; + warning_is { $records = C4::Creators::Lib::_SELECT( '*', 'borrowers', "borrowernumber = $borrowernumber1" ) } + 'Database returned the following error: something went wrong', + '_SELECT raises warning if something went wrong with the sql request execution'; is( $records, 1, '$record return 1' ); } @@ -1437,7 +1487,10 @@ is( $records->[2]->{branchcode}, $branchcode, 'branchcode is good' ); is( $records->[2]->{categorycode}, $categorycode, 'categorycode is good' ); #with $params[2] ---------------------- -$records = C4::Creators::Lib::_SELECT( 'surname, firstname, cardnumber, branchcode, categorycode', 'borrowers', "borrowernumber = $borrowernumber1" ); +$records = C4::Creators::Lib::_SELECT( + 'surname, firstname, cardnumber, branchcode, categorycode', 'borrowers', + "borrowernumber = $borrowernumber1" +); is( @$records, 1, 'There is 1 borrower where borrowernumber = $borrowernumber1' ); isa_ok( $records, 'ARRAY', '$records is an ARRAY' ); @@ -1451,11 +1504,17 @@ is( $records->[0]->{categorycode}, $categorycode, 'categorycode is good' ); subtest '_add_backtics' => sub { plan tests => 7; - my @a = ( 'rows', 'rows ', ' rows ', 'table.rows,field2', 'table.field1, table.field_2_a', 'table1.*, *', 'COUNT(id) AS mycount, count(*) as mycount2' ); - my @a_exp = ( '`rows`', '`rows` ', ' `rows` ', '`table`.`rows`,`field2`', '`table`.`field1`, `table`.`field_2_a`', '`table1`.*, *', 'COUNT(`id`) AS `mycount`, COUNT(*) AS `mycount2`' ); # expected results + my @a = ( + 'rows', 'rows ', ' rows ', 'table.rows,field2', 'table.field1, table.field_2_a', 'table1.*, *', + 'COUNT(id) AS mycount, count(*) as mycount2' + ); + my @a_exp = ( + '`rows`', '`rows` ', ' `rows` ', '`table`.`rows`,`field2`', '`table`.`field1`, `table`.`field_2_a`', + '`table1`.*, *', 'COUNT(`id`) AS `mycount`, COUNT(*) AS `mycount2`' + ); # expected results my @b = C4::Creators::Lib::_add_backtics(@a); - while( my $f = shift @a_exp ) { - is( shift @b, $f, (shift @a). ' became '. $f ); + while ( my $f = shift @a_exp ) { + is( shift @b, $f, ( shift @a ) . ' became ' . $f ); } }; diff --git a/t/db_dependent/DecreaseLoanHighHolds.t b/t/db_dependent/DecreaseLoanHighHolds.t index 2d42d28b9b..925cf493b9 100755 --- a/t/db_dependent/DecreaseLoanHighHolds.t +++ b/t/db_dependent/DecreaseLoanHighHolds.t @@ -32,8 +32,8 @@ use t::lib::Mocks; use Test::More tests => 26; -my $dbh = C4::Context->dbh; -my $schema = Koha::Database->new()->schema(); +my $dbh = C4::Context->dbh; +my $schema = Koha::Database->new()->schema(); my $builder = t::lib::TestBuilder->new; $schema->storage->txn_begin(); @@ -46,26 +46,30 @@ my $library = $builder->build( { source => 'Branch' } ); my $category = $builder->build( { source => 'Category' } ); my $itemtype = $builder->build( { source => 'Itemtype' } )->{itemtype}; -t::lib::Mocks::mock_userenv({ branchcode => $library->{branchcode} }); +t::lib::Mocks::mock_userenv( { branchcode => $library->{branchcode} } ); is( C4::Context->userenv->{branch}, $library->{branchcode}, 'userenv set' ); -my $patron_category = $builder->build({ - source => 'Category', - value => { - category_type => 'P', - enrolmentfee => 0 +my $patron_category = $builder->build( + { + source => 'Category', + value => { + category_type => 'P', + enrolmentfee => 0 + } } -}); +); my @patrons; for my $i ( 1 .. 20 ) { - my $patron = Koha::Patron->new({ - firstname => 'Kyle', - surname => 'Hall', - categorycode => $category->{categorycode}, - branchcode => $library->{branchcode}, - categorycode => $patron_category->{categorycode}, - })->store(); + my $patron = Koha::Patron->new( + { + firstname => 'Kyle', + surname => 'Hall', + categorycode => $category->{categorycode}, + branchcode => $library->{branchcode}, + categorycode => $patron_category->{categorycode}, + } + )->store(); push( @patrons, $patron ); } @@ -76,8 +80,8 @@ my @items; for my $i ( 1 .. 10 ) { my $item = $builder->build_sample_item( { - biblionumber => $biblio->id(), - itype => $itemtype + biblionumber => $biblio->id(), + itype => $itemtype } ); push( @items, $item ); @@ -97,7 +101,8 @@ for my $i ( 0 .. 5 ) { my $item = shift(@items); my $patron = shift(@patrons); -my $patron_hold = Koha::Holds->find({ borrowernumber => $patron->borrowernumber, biblionumber => $item->biblionumber }); +my $patron_hold = + Koha::Holds->find( { borrowernumber => $patron->borrowernumber, biblionumber => $item->biblionumber } ); Koha::CirculationRules->set_rules( { @@ -105,10 +110,10 @@ Koha::CirculationRules->set_rules( categorycode => undef, itemtype => $item->itype, rules => { - issuelength => '14', - lengthunit => 'days', - reservesallowed => '99', - holds_per_record => '99', + issuelength => '14', + lengthunit => 'days', + reservesallowed => '99', + holds_per_record => '99', decreaseloanholds => 0, } } @@ -133,13 +138,13 @@ is( $data->{outstanding}, 5, "Should have 5 outstanding holds" ); is( $data->{duration}, 0, "Should have duration of 0 because of specific circulation rules" ); is( ref( $data->{due_date} ), 'DateTime', "due_date should be a DateTime object" ); -t::lib::Mocks::mock_preference( 'decreaseLoanHighHoldsValue', 5 ); +t::lib::Mocks::mock_preference( 'decreaseLoanHighHoldsValue', 5 ); $data = C4::Circulation::checkHighHolds( $item, $patron ); -is( $data->{exceeded}, 0, "Static mode should not exceed threshold when it equals outstanding holds" ); -is( $data->{outstanding}, 5, "Should have 5 outstanding holds" ); -is( $data->{duration}, 0, "Should have duration of 0 because decrease not calculated" ); -is( $data->{due_date}, undef, "duedate undefined as not decreasing loan period" ); -t::lib::Mocks::mock_preference( 'decreaseLoanHighHoldsValue', 1 ); +is( $data->{exceeded}, 0, "Static mode should not exceed threshold when it equals outstanding holds" ); +is( $data->{outstanding}, 5, "Should have 5 outstanding holds" ); +is( $data->{duration}, 0, "Should have duration of 0 because decrease not calculated" ); +is( $data->{due_date}, undef, "duedate undefined as not decreasing loan period" ); +t::lib::Mocks::mock_preference( 'decreaseLoanHighHoldsValue', 1 ); Koha::CirculationRules->set_rules( { @@ -147,28 +152,30 @@ Koha::CirculationRules->set_rules( categorycode => undef, itemtype => $item->itype, rules => { - issuelength => '14', - lengthunit => 'days', - reservesallowed => '99', - holds_per_record => '99', + issuelength => '14', + lengthunit => 'days', + reservesallowed => '99', + holds_per_record => '99', decreaseloanholds => undef, } } ); $data = C4::Circulation::checkHighHolds( $item, $patron ); -is( $data->{duration}, 1, "Should have a duration of 1 because no specific circulation rules so defaults to system preference" ); +is( + $data->{duration}, 1, + "Should have a duration of 1 because no specific circulation rules so defaults to system preference" +); my $duedate = $data->{due_date}; -is($duedate->hour, $orig_due->hour, 'New due hour is equal to original due hour.'); -is($duedate->min, $orig_due->min, 'New due minute is equal to original due minute.'); -is($duedate->sec, 0, 'New due date second is zero.'); +is( $duedate->hour, $orig_due->hour, 'New due hour is equal to original due hour.' ); +is( $duedate->min, $orig_due->min, 'New due minute is equal to original due minute.' ); +is( $duedate->sec, 0, 'New due date second is zero.' ); t::lib::Mocks::mock_preference( 'decreaseLoanHighHoldsControl', 'dynamic' ); $data = C4::Circulation::checkHighHolds( $item, $patron ); is( $data->{exceeded}, 0, "Should not exceed threshold" ); - # Place 7 more holds - patrons 5,6,7,8,9,10,11 for my $i ( 5 .. 11 ) { my $patron = $patrons[$i]; @@ -185,7 +192,7 @@ for my $i ( 5 .. 11 ) { # 12 holds, threshold is 1 over 10 holdable items = 11 $data = C4::Circulation::checkHighHolds( $item, $patron ); -is( $data->{exceeded}, 1, "Should exceed threshold of 1" ); +is( $data->{exceeded}, 1, "Should exceed threshold of 1" ); is( $data->{outstanding}, 12, "Should exceed threshold of 1" ); # 12 holds, threshold is 2 over 10 holdable items = 12 (equal is okay) @@ -226,17 +233,19 @@ $data = C4::Circulation::checkHighHolds( $item, $patron ); is( $data->{exceeded}, 1, "Should exceed threshold with one withdrawn item" ); $patron_hold->found('F')->store; + # 11 holds, threshold is 2 over 9 holdable items = 11 $data = C4::Circulation::checkHighHolds( $item, $patron ); is( $data->{exceeded}, 1, "Should exceed threshold with one withdrawn item" ); $patron_hold->found(undef)->store; -t::lib::Mocks::mock_preference('CircControl', 'PatronLibrary'); +t::lib::Mocks::mock_preference( 'CircControl', 'PatronLibrary' ); my ( undef, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode ); ok( $needsconfirmation->{HIGHHOLDS}, "High holds checkout needs confirmation" ); -( undef, $needsconfirmation ) = CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, { override_high_holds => 1 } ); +( undef, $needsconfirmation ) = + CanBookBeIssued( $patron, $item->barcode, undef, undef, undef, { override_high_holds => 1 } ); ok( !$needsconfirmation->{HIGHHOLDS}, "High holds checkout does not need confirmation" ); Koha::CirculationRules->set_rule( @@ -252,30 +261,31 @@ Koha::CirculationRules->set_rule( $data = C4::Circulation::checkHighHolds( $item, $patron ); is( $data->{duration}, 2, "Circulation rules override system preferences" ); - subtest "Test patron's own holds do not count towards HighHolds count" => sub { plan tests => 2; - my $item = $builder->build_sample_item(); - my $item2 = $builder->build_sample_item({ biblionumber => $item->biblionumber }); - my $item3 = $builder->build_sample_item({ biblionumber => $item->biblionumber }); + my $item = $builder->build_sample_item(); + my $item2 = $builder->build_sample_item( { biblionumber => $item->biblionumber } ); + my $item3 = $builder->build_sample_item( { biblionumber => $item->biblionumber } ); - my $patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { - branchcode => $item->homebranch + my $patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { branchcode => $item->homebranch } } - }); - my $hold = $builder->build_object({ - class => 'Koha::Holds', - value => { - biblionumber => $item->biblionumber, - borrowernumber => $patron->id, - suspend => 0, - found => undef + ); + my $hold = $builder->build_object( + { + class => 'Koha::Holds', + value => { + biblionumber => $item->biblionumber, + borrowernumber => $patron->id, + suspend => 0, + found => undef + } } - }); + ); Koha::CirculationRules->set_rules( { @@ -283,9 +293,9 @@ subtest "Test patron's own holds do not count towards HighHolds count" => sub { categorycode => undef, itemtype => $item->itype, rules => { - issuelength => '14', - lengthunit => 'days', - reservesallowed => '99', + issuelength => '14', + lengthunit => 'days', + reservesallowed => '99', holds_per_record => '1', } } @@ -297,12 +307,13 @@ subtest "Test patron's own holds do not count towards HighHolds count" => sub { t::lib::Mocks::mock_preference( 'decreaseLoanHighHoldsControl', 'static' ); t::lib::Mocks::mock_preference( 'decreaseLoanHighHoldsIgnoreStatuses', 'damaged,itemlost,notforloan,withdrawn' ); - my $data = C4::Circulation::checkHighHolds( $item , $patron ); - ok( !$data->{exceeded}, "Patron's hold on the record does not limit their own circulation if static decrease"); - t::lib::Mocks::mock_preference( 'decreaseLoanHighHoldsControl', 'dynamic' ); + my $data = C4::Circulation::checkHighHolds( $item, $patron ); + ok( !$data->{exceeded}, "Patron's hold on the record does not limit their own circulation if static decrease" ); + t::lib::Mocks::mock_preference( 'decreaseLoanHighHoldsControl', 'dynamic' ); + # 3 items on record, patron has 1 hold $data = C4::Circulation::checkHighHolds( $item, $patron ); - ok( !$data->{exceeded}, "Patron's hold on the record does not limit their own circulation if dynamic decrease"); + ok( !$data->{exceeded}, "Patron's hold on the record does not limit their own circulation if dynamic decrease" ); }; diff --git a/t/db_dependent/Exporter/Record.t b/t/db_dependent/Exporter/Record.t index 68fa733f7d..ac506e4eff 100755 --- a/t/db_dependent/Exporter/Record.t +++ b/t/db_dependent/Exporter/Record.t @@ -40,44 +40,46 @@ use t::lib::TestBuilder; my $builder = t::lib::TestBuilder->new; -my $schema = Koha::Database->new->schema; +my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; my $dbh = C4::Context->dbh; my $biblio_1_title = 'Silence in the library'; my $biblio_2_title = 'The art of computer programming ກ ຂ ຄ ງ ຈ ຊ ຍ é'; -my $biblio_1 = $builder->build_sample_biblio( +my $biblio_1 = $builder->build_sample_biblio( { - title => $biblio_1_title, + title => $biblio_1_title, author => 'Moffat, Steven', } ); my $biblionumber_1 = $biblio_1->biblionumber; -my $biblio_2 = $builder->build_sample_biblio( +my $biblio_2 = $builder->build_sample_biblio( { - title => $biblio_2_title, + title => $biblio_2_title, author => 'Knuth, Donald Ervin', } ); my $biblionumber_2 = $biblio_2->biblionumber; my $marcflavour = C4::Context->preference('marcflavour'); -my ($title_field_tag, $item_field_tag, $barcode_subfield_code, $homebranch_subfield_code); -if ($marcflavour eq 'UNIMARC') { - $title_field_tag = '200'; - $item_field_tag = '995'; - $barcode_subfield_code = 'f'; +my ( $title_field_tag, $item_field_tag, $barcode_subfield_code, $homebranch_subfield_code ); +if ( $marcflavour eq 'UNIMARC' ) { + $title_field_tag = '200'; + $item_field_tag = '995'; + $barcode_subfield_code = 'f'; $homebranch_subfield_code = 'b'; } else { - $title_field_tag = '245'; - $item_field_tag = '952'; - $barcode_subfield_code = 'p'; + $title_field_tag = '245'; + $item_field_tag = '952'; + $barcode_subfield_code = 'p'; $homebranch_subfield_code = 'a'; } my $bad_biblio = Koha::Biblio->new()->store(); -Koha::Biblio::Metadata->new( { biblionumber => $bad_biblio->id, format => 'marcxml', metadata => 'something wrong', schema => $marcflavour } )->store(); +Koha::Biblio::Metadata->new( + { biblionumber => $bad_biblio->id, format => 'marcxml', metadata => 'something wrong', schema => $marcflavour } ) + ->store(); my $bad_biblionumber = $bad_biblio->id; my $item_1_1 = $builder->build_sample_item( @@ -95,24 +97,30 @@ my $item_2_1 = $builder->build_sample_item( biblionumber => $biblionumber_2, } )->unblessed; -my $bad_item = $builder->build({ # Cannot call build_sample_item, we want inconsistent data on purpose - source => 'Item', - value => { - biblionumber => $bad_biblionumber, +my $bad_item = $builder->build( + { # Cannot call build_sample_item, we want inconsistent data on purpose + source => 'Item', + value => { + biblionumber => $bad_biblionumber, + } } -}); +); subtest 'export csv' => sub { plan tests => 3; my $csv_content = "Title=$title_field_tag\$a|Barcode=$item_field_tag\$$barcode_subfield_code"; - $dbh->do(q|INSERT INTO export_format(profile, description, content, csv_separator, field_separator, subfield_separator, encoding, type) VALUES (?, ?, ?, ?, ?, ?, ?, ?)|, {}, "TEST_PROFILE_Records.t", "my useless desc", $csv_content, '|', ';', ',', 'utf8', 'marc'); - my $csv_profile_id = $dbh->last_insert_id( undef, undef, 'export_format', undef ); + $dbh->do( + q|INSERT INTO export_format(profile, description, content, csv_separator, field_separator, subfield_separator, encoding, type) VALUES (?, ?, ?, ?, ?, ?, ?, ?)|, + {}, "TEST_PROFILE_Records.t", "my useless desc", $csv_content, '|', ';', ',', 'utf8', 'marc' + ); + my $csv_profile_id = $dbh->last_insert_id( undef, undef, 'export_format', undef ); my $generated_csv_file = '/tmp/test_export_1.csv'; # Get all item infos warning_like { Koha::Exporter::Record::export( - { record_type => 'bibs', + { + record_type => 'bibs', record_ids => [ $biblionumber_1, $bad_biblionumber, $biblionumber_2 ], format => 'csv', csv_profile_id => $csv_profile_id, @@ -126,18 +134,19 @@ Title|Barcode "$biblio_1_title"|$item_1_1->{barcode},$item_1_2->{barcode} "$biblio_2_title"|$item_2_1->{barcode} EOF - my $generated_csv_content = read_file( $generated_csv_file ); + my $generated_csv_content = read_file($generated_csv_file); is( $generated_csv_content, $expected_csv, "Export CSV: All item's infos should have been retrieved" ); $generated_csv_file = '/tmp/test_export.csv'; + # Get only 1 item info Koha::Exporter::Record::export( { - record_type => 'bibs', - record_ids => [ $biblionumber_1, $biblionumber_2 ], - itemnumbers => [ $item_1_1->{itemnumber}, $item_2_1->{itemnumber} ], - format => 'csv', - csv_profile_id => $csv_profile_id, + record_type => 'bibs', + record_ids => [ $biblionumber_1, $biblionumber_2 ], + itemnumbers => [ $item_1_1->{itemnumber}, $item_2_1->{itemnumber} ], + format => 'csv', + csv_profile_id => $csv_profile_id, output_filepath => $generated_csv_file, } ); @@ -146,7 +155,7 @@ Title|Barcode "$biblio_1_title"|$item_1_1->{barcode} "$biblio_2_title"|$item_2_1->{barcode} EOF - $generated_csv_content = read_file( $generated_csv_file ); + $generated_csv_content = read_file($generated_csv_file); is( $generated_csv_content, $expected_csv, "Export CSV: Only 1 item info should have been retrieved" ); }; @@ -155,7 +164,8 @@ subtest 'export xml' => sub { my $generated_xml_file = '/tmp/test_export.xml'; warning_like { Koha::Exporter::Record::export( - { record_type => 'bibs', + { + record_type => 'bibs', record_ids => [ $biblionumber_1, $bad_biblionumber, $biblionumber_2 ], format => 'xml', output_filepath => $generated_xml_file, @@ -164,31 +174,34 @@ subtest 'export xml' => sub { } qr|.*Start tag expected.*|, "Export xml with wrong marcxml should raise a warning"; - my $generated_xml_content = read_file( $generated_xml_file ); + my $generated_xml_content = read_file($generated_xml_file); $MARC::File::XML::_load_args{BinaryEncoding} = 'utf-8'; open my $fh, '<', $generated_xml_file; my $records = MARC::Batch->new( 'XML', $fh ); my @records; + # The following statement produces # Use of uninitialized value in concatenation (.) or string at /usr/share/perl5/MARC/File/XML.pm line 398, <$fh> chunk 5. # Why? while ( my $record = $records->next ) { push @records, $record; } - is( scalar( @records ), 2, 'Export XML: 2 records should have been exported' ); + is( scalar(@records), 2, 'Export XML: 2 records should have been exported' ); my $second_record = $records[1]; - my $title = $second_record->subfield($title_field_tag, 'a'); - $title = Encode::encode('UTF-8', $title); + my $title = $second_record->subfield( $title_field_tag, 'a' ); + $title = Encode::encode( 'UTF-8', $title ); is( $title, $biblio_2_title, 'Export XML: The title is correctly encoded' ); }; subtest 'export iso2709' => sub { plan tests => 3; my $generated_mrc_file = '/tmp/test_export.mrc'; + # Get all item infos warning_like { Koha::Exporter::Record::export( - { record_type => 'bibs', + { + record_type => 'bibs', record_ids => [ $biblionumber_1, $bad_biblionumber, $biblionumber_2 ], format => 'iso2709', output_filepath => $generated_mrc_file, @@ -197,27 +210,30 @@ subtest 'export iso2709' => sub { } qr|.*Start tag expected.*|, "Export iso2709 with wrong marcxml should raise a warning"; - my $records = MARC::File::USMARC->in( $generated_mrc_file ); + my $records = MARC::File::USMARC->in($generated_mrc_file); my @records; while ( my $record = $records->next ) { push @records, $record; } - is( scalar( @records ), 2, 'Export ISO2709: 2 records should have been exported' ); + is( scalar(@records), 2, 'Export ISO2709: 2 records should have been exported' ); my $second_record = $records[1]; - my $title = $second_record->subfield($title_field_tag, 'a'); - $title = Encode::encode('UTF-8', $title); + my $title = $second_record->subfield( $title_field_tag, 'a' ); + $title = Encode::encode( 'UTF-8', $title ); is( $title, $biblio_2_title, 'Export ISO2709: The title is correctly encoded' ); }; subtest 'export without record_type' => sub { plan tests => 1; - my $rv = Koha::Exporter::Record::export({ - record_ids => [ $biblionumber_1, $biblionumber_2 ], - format => 'iso2709', + my $rv = Koha::Exporter::Record::export( + { + record_ids => [ $biblionumber_1, $biblionumber_2 ], + format => 'iso2709', output_filepath => 'does_not_matter_here', - }); + } + ); is( $rv, undef, 'export returns undef' ); + #Depending on your logger config, you might have a warn in your logs }; @@ -226,13 +242,13 @@ subtest '_get_biblio_for_export' => sub { my $biblio = $builder->build_sample_biblio( { - title => 'The 13 Clocks', + title => 'The 13 Clocks', author => 'Thurber, James', } ); - my $biblionumber = $biblio->biblionumber; - my $branch_a = $builder->build({source => 'Branch',}); - my $branch_b = $builder->build({source => 'Branch',}); + my $biblionumber = $biblio->biblionumber; + my $branch_a = $builder->build( { source => 'Branch', } ); + my $branch_b = $builder->build( { source => 'Branch', } ); my $item_branch_a = $builder->build_sample_item( { biblionumber => $biblionumber, @@ -279,17 +295,17 @@ subtest '_get_biblio_for_export' => sub { } ); @items = $record->field($item_field_tag); - is( scalar @items, 0, "We should not have any items if we don't request items and pass a branch"); + is( scalar @items, 0, "We should not have any items if we don't request items and pass a branch" ); $record = Koha::Exporter::Record::_get_biblio_for_export( { biblionumber => $biblionumber, export_items => 1, - itemnumbers => [$item_branch_a->itemnumber], + itemnumbers => [ $item_branch_a->itemnumber ], } ); @items = $record->field($item_field_tag); - is( scalar @items, 1, "We should have only items requested if we pass itemnumbers"); + is( scalar @items, 1, "We should have only items requested if we pass itemnumbers" ); }; @@ -298,7 +314,7 @@ subtest '_get_record_for_export MARC field conditions' => sub { my $biblio = $builder->build_sample_biblio( { - title => 'The 13 Clocks', + title => 'The 13 Clocks', author => 'Thurber, James', } ); @@ -308,114 +324,112 @@ subtest '_get_record_for_export MARC field conditions' => sub { MARC::Field->new( '035', ' ', ' ', a => '(TEST)123' ), MARC::Field->new( '035', ' ', ' ', a => '(TEST)1234' ), ); - $biblio->metadata->metadata($record->as_xml)->store; + $biblio->metadata->metadata( $record->as_xml )->store; my $biblionumber = $biblio->biblionumber; $record = Koha::Exporter::Record::_get_record_for_export( { - record_id => $biblionumber, - record_conditions => [['080', 'a', '=', '12345']], - record_type => 'bibs', + record_id => $biblionumber, + record_conditions => [ [ '080', 'a', '=', '12345' ] ], + record_type => 'bibs', } ); ok( $record, "Record condition \"080a=12345\" should match" ); $record = Koha::Exporter::Record::_get_record_for_export( { - record_id => $biblionumber, - record_conditions => [['080', 'a', '!=', '12345']], - record_type => 'bibs', + record_id => $biblionumber, + record_conditions => [ [ '080', 'a', '!=', '12345' ] ], + record_type => 'bibs', } ); is( $record, undef, "Record condition \"080a!=12345\" should not match" ); $record = Koha::Exporter::Record::_get_record_for_export( { - record_id => $biblionumber, - record_conditions => [['080', 'a', '>', '1234']], - record_type => 'bibs', + record_id => $biblionumber, + record_conditions => [ [ '080', 'a', '>', '1234' ] ], + record_type => 'bibs', } ); ok( $record, "Record condition \"080a>1234\" should match" ); $record = Koha::Exporter::Record::_get_record_for_export( { - record_id => $biblionumber, - record_conditions => [['080', 'a', '<', '123456']], - record_type => 'bibs', + record_id => $biblionumber, + record_conditions => [ [ '080', 'a', '<', '123456' ] ], + record_type => 'bibs', } ); ok( $record, "Record condition \"080a<123456\" should match" ); $record = Koha::Exporter::Record::_get_record_for_export( { - record_id => $biblionumber, - record_conditions => [['080', 'a', '>', '123456']], - record_type => 'bibs', + record_id => $biblionumber, + record_conditions => [ [ '080', 'a', '>', '123456' ] ], + record_type => 'bibs', } ); is( $record, undef, "Record condition \"080a>123456\" should not match" ); - ## Multiple subfields $record = Koha::Exporter::Record::_get_record_for_export( { - record_id => $biblionumber, - record_conditions => [['035', 'a', '!=', 'TEST(12345)']], - record_type => 'bibs', + record_id => $biblionumber, + record_conditions => [ [ '035', 'a', '!=', 'TEST(12345)' ] ], + record_type => 'bibs', } ); ok( $record, "Record condition \"035a!=TEST(12345)\" should match" ); $record = Koha::Exporter::Record::_get_record_for_export( { - record_id => $biblionumber, - record_conditions => [['035', 'a', '=', 'TEST(1234)']], - record_type => 'bibs', + record_id => $biblionumber, + record_conditions => [ [ '035', 'a', '=', 'TEST(1234)' ] ], + record_type => 'bibs', } ); - is( $record, undef, "Record condition \"035a=TEST(1234)\" should not match" ); # Since matching all subfields required - + is( $record, undef, "Record condition \"035a=TEST(1234)\" should not match" ) + ; # Since matching all subfields required ## Multiple conditions $record = Koha::Exporter::Record::_get_record_for_export( { - record_id => $biblionumber, - record_conditions => [['035', 'a', '!=', 'TEST(12345)'], ['080', 'a', '>', '1234']], - record_type => 'bibs', + record_id => $biblionumber, + record_conditions => [ [ '035', 'a', '!=', 'TEST(12345)' ], [ '080', 'a', '>', '1234' ] ], + record_type => 'bibs', } ); ok( $record, "Record condition \"035a!=TEST(12345),080a>1234\" should match" ); $record = Koha::Exporter::Record::_get_record_for_export( { - record_id => $biblionumber, - record_conditions => [['035', 'a', '!=', 'TEST(12345)'], ['080', 'a', '<', '1234']], - record_type => 'bibs', + record_id => $biblionumber, + record_conditions => [ [ '035', 'a', '!=', 'TEST(12345)' ], [ '080', 'a', '<', '1234' ] ], + record_type => 'bibs', } ); is( $record, undef, "Record condition \"035a!=TEST(12345),080a<1234\" should not match" ); - ## exists/not_exists $record = Koha::Exporter::Record::_get_record_for_export( { - record_id => $biblionumber, - record_conditions => [['035', 'a', '?']], - record_type => 'bibs', + record_id => $biblionumber, + record_conditions => [ [ '035', 'a', '?' ] ], + record_type => 'bibs', } ); ok( $record, "Record condition \"exists(035a)\" should match" ); $record = Koha::Exporter::Record::_get_record_for_export( { - record_id => $biblionumber, - record_conditions => [['035', 'a', '!?']], - record_type => 'bibs', - record_type => 'bibs', + record_id => $biblionumber, + record_conditions => [ [ '035', 'a', '!?' ] ], + record_type => 'bibs', + record_type => 'bibs', } ); is( $record, undef, "Record condition \"not_exists(035a)\" should not match" ); diff --git a/t/db_dependent/Filter_MARC_ViewPolicy.t b/t/db_dependent/Filter_MARC_ViewPolicy.t index 1b03f807ac..78dd77f77e 100755 --- a/t/db_dependent/Filter_MARC_ViewPolicy.t +++ b/t/db_dependent/Filter_MARC_ViewPolicy.t @@ -49,16 +49,14 @@ sub run_hiding_tests { # TODO: -8 is Flagged, which doesn't seem used. # -9 and +9 are supposedly valid future values # according to older documentation in 3.10.x - my @valid_hidden_values = - ( -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8 ); + my @valid_hidden_values = ( -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8 ); my $hidden = { 'opac' => [ -8, 1, 2, 3, 4, 5, 6, 7, 8 ], 'intranet' => [ -8, -7, -4, -3, -2, 2, 3, 5, 8 ] }; - my ( $isbn_field, $isbn_subfield ) = - GetMarcFromKohaField( 'biblioitems.isbn' ); + my ( $isbn_field, $isbn_subfield ) = GetMarcFromKohaField('biblioitems.isbn'); my $update_sql = q{UPDATE marc_subfield_structure SET hidden=? }; my $sth = $dbh->prepare($update_sql); foreach my $hidden_value (@valid_hidden_values) { @@ -93,49 +91,59 @@ sub run_hiding_tests { if ( any { $_ == $hidden_value } @{ $hidden->{$interface} } ) { # Subfield and controlfield are set to be hidden - is( $filtered_record->field($isbn_field), + is( + $filtered_record->field($isbn_field), undef, - "Data field has been deleted because of hidden=$hidden_value" ); - isnt( $unfiltered_record->field($isbn_field), undef, -"Data field has been deleted in the original record because of hidden=$hidden_value" + "Data field has been deleted because of hidden=$hidden_value" + ); + isnt( + $unfiltered_record->field($isbn_field), undef, + "Data field has been deleted in the original record because of hidden=$hidden_value" ); # Control fields have a different behaviour in code - is( $filtered_record->field('008'), undef, + is( + $filtered_record->field('008'), undef, "Control field has been deleted because of hidden=$hidden_value" ); - isnt( $unfiltered_record->field('008'), undef, -"Control field has been deleted in the original record because of hidden=$hidden_value" + isnt( + $unfiltered_record->field('008'), undef, + "Control field has been deleted in the original record because of hidden=$hidden_value" ); ok( $filtered_record && $unfiltered_record, 'Records exist' ); - } - else { - isnt( $filtered_record->field($isbn_field), undef, + } else { + isnt( + $filtered_record->field($isbn_field), undef, "Data field hasn't been deleted because of hidden=$hidden_value" ); - isnt( $unfiltered_record->field($isbn_field), undef, -"Data field hasn't been deleted in the original record because of hidden=$hidden_value" + isnt( + $unfiltered_record->field($isbn_field), undef, + "Data field hasn't been deleted in the original record because of hidden=$hidden_value" ); # Control fields have a different behaviour in code - isnt( $filtered_record->field('008'), undef, -"Control field hasn't been deleted because of hidden=$hidden_value" + isnt( + $filtered_record->field('008'), undef, + "Control field hasn't been deleted because of hidden=$hidden_value" ); - isnt( $unfiltered_record->field('008'), undef, -"Control field hasn't been deleted in the original record because of hidden=$hidden_value" + isnt( + $unfiltered_record->field('008'), undef, + "Control field hasn't been deleted in the original record because of hidden=$hidden_value" ); # force all the hidden values the same, so filtered and unfiltered # records should be identical. - is_deeply( $filtered_record, $unfiltered_record, - 'Records are the same' ); + is_deeply( + $filtered_record, $unfiltered_record, + 'Records are the same' + ); } } - $sth->execute(-1); # -1 is visible in opac and intranet. + $sth->execute(-1); # -1 is visible in opac and intranet. my $cache = Koha::Caches->get_instance(); $cache->flush_all(); # easy way to ensure DB is queried again. @@ -146,9 +154,9 @@ sub run_hiding_tests { interface => $interface } ); - my @hiddenfields = grep { $shouldhidemarc->{$_}==1 } keys %{$shouldhidemarc}; + my @hiddenfields = grep { $shouldhidemarc->{$_} == 1 } keys %{$shouldhidemarc}; - $sth->execute(8); # 8 is invisible in opac and intranet. + $sth->execute(8); # 8 is invisible in opac and intranet. $cache->flush_all(); # easy way to ensure DB is queried again. @@ -158,26 +166,24 @@ sub run_hiding_tests { interface => $interface } ); - my @keyvalues = keys %{$shouldhidemarc}; - my @visiblefields = grep { $shouldhidemarc->{$_}==1 } @keyvalues; + my @keyvalues = keys %{$shouldhidemarc}; + my @visiblefields = grep { $shouldhidemarc->{$_} == 1 } @keyvalues; - is(scalar @hiddenfields,0,'Should Hide MARC - Full Visibility'); - is_deeply(\@visiblefields,\@keyvalues,'Should Hide MARC - No Visibility'); + is( scalar @hiddenfields, 0, 'Should Hide MARC - Full Visibility' ); + is_deeply( \@visiblefields, \@keyvalues, 'Should Hide MARC - No Visibility' ); return; } sub create_marc_record { - my ( $title_field, $title_subfield ) = - GetMarcFromKohaField( 'biblio.title' ); - my ( $isbn_field, $isbn_subfield ) = - GetMarcFromKohaField( 'biblioitems.isbn' ); + my ( $title_field, $title_subfield ) = GetMarcFromKohaField('biblio.title'); + my ( $isbn_field, $isbn_subfield ) = GetMarcFromKohaField('biblioitems.isbn'); my $isbn = '0590353403'; my $title = 'Foundation'; my $marc_record = MARC::Record->new; my @fields = ( - MARC::Field->new( '003', 'AR-CdUBM' ), - MARC::Field->new( '008', '######suuuu####ag_||||__||||_0||_|_uuu|d' ), + MARC::Field->new( '003', 'AR-CdUBM' ), + MARC::Field->new( '008', '######suuuu####ag_||||__||||_0||_|_uuu|d' ), MARC::Field->new( $isbn_field, q{}, q{}, $isbn_subfield => $isbn ), MARC::Field->new( $title_field, q{}, q{}, $title_subfield => $title ), ); @@ -206,4 +212,4 @@ subtest 'Koha::Filter::MARC::ViewPolicy intranet tests' => sub { }; my $cache = Koha::Caches->get_instance(); -$cache->flush_all(); # Clear cache for the other tests +$cache->flush_all(); # Clear cache for the other tests diff --git a/t/db_dependent/Fines.t b/t/db_dependent/Fines.t index b604a3374a..67360f92e2 100755 --- a/t/db_dependent/Fines.t +++ b/t/db_dependent/Fines.t @@ -34,13 +34,13 @@ my $issuingrule = Koha::CirculationRules->set_rules( ok( $issuingrule, 'Issuing rule created' ); my $period_start = dt_from_string('2000-01-01'); -my $period_end = dt_from_string('2000-01-05'); +my $period_end = dt_from_string('2000-01-05'); -my ( $fine ) = CalcFine( {}, q{}, q{}, $period_start, $period_end ); +my ($fine) = CalcFine( {}, q{}, q{}, $period_start, $period_end ); is( $fine, 0, '4 days overdue, charge period 7 days, charge at end of interval gives fine of $0' ); $period_end = dt_from_string('2000-01-10'); -( $fine ) = CalcFine( {}, q{}, q{}, $period_start, $period_end ); +($fine) = CalcFine( {}, q{}, q{}, $period_start, $period_end ); is( $fine, 1, '9 days overdue, charge period 7 days, charge at end of interval gives fine of $1' ); # Test charging fine at the *beginning* of each charge period @@ -56,9 +56,9 @@ $issuingrule = Koha::CirculationRules->set_rules( ); $period_end = dt_from_string('2000-01-05'); -( $fine ) = CalcFine( {}, q{}, q{}, $period_start, $period_end ); +($fine) = CalcFine( {}, q{}, q{}, $period_start, $period_end ); is( $fine, 1, '4 days overdue, charge period 7 days, charge at start of interval gives fine of $1' ); $period_end = dt_from_string('2000-01-10'); -( $fine ) = CalcFine( {}, q{}, q{}, $period_start, $period_end ); +($fine) = CalcFine( {}, q{}, q{}, $period_start, $period_end ); is( $fine, 2, '9 days overdue, charge period 7 days, charge at start of interval gives fine of $2' ); diff --git a/t/db_dependent/FrameworkPlugin.t b/t/db_dependent/FrameworkPlugin.t index 731f97df6d..9207ea2761 100755 --- a/t/db_dependent/FrameworkPlugin.t +++ b/t/db_dependent/FrameworkPlugin.t @@ -10,21 +10,21 @@ use Test::Warn; use t::lib::Mocks; use t::lib::TestBuilder; -use C4::Auth qw( checkauth ); +use C4::Auth qw( checkauth ); use C4::Output qw( output_html_with_http_headers ); use Koha::Database; use Koha::FrameworkPlugin; use Koha::Util::FrameworkPlugin qw( biblio_008 ); our @includes; -GetOptions( 'include=s{,}' => \@includes ); #not used by default ! +GetOptions( 'include=s{,}' => \@includes ); #not used by default ! # Because of CGI::Session being buggy (see bug 17427) and a use of get_session somewhere here t::lib::Mocks::mock_preference( 'SessionStorage', 'tmp' ); -my $schema = Koha::Database->new->schema; +my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; -our $dbh = C4::Context->dbh; +our $dbh = C4::Context->dbh; our $builder = t::lib::TestBuilder->new; subtest 'Test01 -- Simple tests for new and name' => sub { @@ -48,18 +48,18 @@ subtest 'Test05 -- tests with build and launch for default plugins' => sub { subtest 'Test06 -- test biblio_008' => sub { plan tests => 5; - t::lib::Mocks::mock_preference('DefaultCountryField008', 'nl' ); # deliberately shorter than 3 pos - t::lib::Mocks::mock_preference('DefaultLanguageField008', 'dutch' ); # deliberately too long + t::lib::Mocks::mock_preference( 'DefaultCountryField008', 'nl' ); # deliberately shorter than 3 pos + t::lib::Mocks::mock_preference( 'DefaultLanguageField008', 'dutch' ); # deliberately too long my $field = biblio_008(); is( length($field), 40, 'Check length' ); - is( substr($field, 15, 3), 'nl ', 'Check country right padded' ); - is( substr($field, 35, 3), 'dut', 'Check language' ); - t::lib::Mocks::mock_preference('DefaultCountryField008', '' ); + is( substr( $field, 15, 3 ), 'nl ', 'Check country right padded' ); + is( substr( $field, 35, 3 ), 'dut', 'Check language' ); + t::lib::Mocks::mock_preference( 'DefaultCountryField008', '' ); $field = biblio_008(); - is( substr($field, 15, 3), '|||', 'Check country fallback for empty string' ); - t::lib::Mocks::mock_preference('DefaultCountryField008', undef ); + is( substr( $field, 15, 3 ), '|||', 'Check country fallback for empty string' ); + t::lib::Mocks::mock_preference( 'DefaultCountryField008', undef ); $field = biblio_008(); - is( substr($field, 15, 3), '|||', 'Check country fallback for undefined' ); + is( substr( $field, 15, 3 ), '|||', 'Check country fallback for undefined' ); }; subtest 'Test07 -- validate input' => sub { @@ -78,167 +78,186 @@ subtest 'Test07 -- validate input' => sub { $schema->storage->txn_rollback; sub test01 { + #empty plugin - my $plugin= Koha::FrameworkPlugin->new; + my $plugin = Koha::FrameworkPlugin->new; is( ref($plugin), 'Koha::FrameworkPlugin', 'Got an object' ); - isnt( $plugin->errstr, undef, 'We should have an error for missing name'); - is( $plugin->build, undef, 'Build returns undef'); + isnt( $plugin->errstr, undef, 'We should have an error for missing name' ); + is( $plugin->build, undef, 'Build returns undef' ); #tests for name and path, with/without hashref - $plugin= Koha::FrameworkPlugin->new( { name => 'marc21_leader.pl' } ); + $plugin = Koha::FrameworkPlugin->new( { name => 'marc21_leader.pl' } ); is( $plugin->name, 'marc21_leader.pl', 'Check name without path in hash' ); - $plugin= Koha::FrameworkPlugin->new( 'marc21_leader.pl' ); + $plugin = Koha::FrameworkPlugin->new('marc21_leader.pl'); is( $plugin->name, 'marc21_leader.pl', 'Check name without path' ); - $plugin= Koha::FrameworkPlugin->new( 'cataloguing/value_builder/marc21_leader.pl' ); + $plugin = Koha::FrameworkPlugin->new('cataloguing/value_builder/marc21_leader.pl'); is( $plugin->name, 'marc21_leader.pl', 'Check name with path' ); - $plugin= Koha::FrameworkPlugin->new({ path => 'cataloguing/value_builder', name => 'marc21_leader.pl' }); + $plugin = Koha::FrameworkPlugin->new( { path => 'cataloguing/value_builder', name => 'marc21_leader.pl' } ); is( $plugin->name, 'marc21_leader.pl', 'Check name and path in hash' ); } sub test02 { + # first test an old style item plugin - my $old = old01(); # plugin filename + my $old = old01(); # plugin filename my $path; - if( $old =~ /^(.*)\/([^\/]+)$/ ) { # extract path + if ( $old =~ /^(.*)\/([^\/]+)$/ ) { # extract path $path = $1; - $old = $2; + $old = $2; } - my $plugin= Koha::FrameworkPlugin->new({ - name => $old, path => $path, item_style => 1, - }); - my $pars= { id => '234567' }; + my $plugin = Koha::FrameworkPlugin->new( + { + name => $old, path => $path, item_style => 1, + } + ); + my $pars = { id => '234567' }; is( $plugin->build($pars), 1, 'Build oldstyler successful' ); - is( length($plugin->javascript)>0 && !$plugin->noclick, 1, - 'Checked javascript and noclick' ); + is( + length( $plugin->javascript ) > 0 && !$plugin->noclick, 1, + 'Checked javascript and noclick' + ); # now test marc21_leader - $plugin= Koha::FrameworkPlugin->new( { name => 'marc21_leader.pl' } ); - $pars= { dbh => $dbh, id => '123456' }; + $plugin = Koha::FrameworkPlugin->new( { name => 'marc21_leader.pl' } ); + $pars = { dbh => $dbh, id => '123456' }; is( $plugin->build($pars), 1, 'Build marc21_leader successful' ); - is( $plugin->javascript =~ /<script.*function.*\<\/script\>/s, 1, - 'Javascript looks ok' ); - is( $plugin->noclick, '', 'marc21_leader should have a popup'); + is( + $plugin->javascript =~ /<script.*function.*\<\/script\>/s, 1, + 'Javascript looks ok' + ); + is( $plugin->noclick, '', 'marc21_leader should have a popup' ); } sub test03 { + #file not found - my $plugin= Koha::FrameworkPlugin->new('file_does_not_exist'); + my $plugin = Koha::FrameworkPlugin->new('file_does_not_exist'); $plugin->build; - is( $plugin->errstr =~ /not found/i, 1, 'File not found-message'); + is( $plugin->errstr =~ /not found/i, 1, 'File not found-message' ); #three bad ones: no perl, syntax error, bad return value foreach my $f ( bad01(), bad02(), bad03() ) { next if !$f; - $plugin= Koha::FrameworkPlugin->new( $f ); - $plugin->build({ id => '998877' }); - is( defined($plugin->errstr), 1, - "Saw: ". ( $plugin->errstr//'no error??' )); + $plugin = Koha::FrameworkPlugin->new($f); + $plugin->build( { id => '998877' } ); + is( + defined( $plugin->errstr ), 1, + "Saw: " . ( $plugin->errstr // 'no error??' ) + ); } done_testing(); } sub test04 { + #two simple new style plugins - my $plugin= Koha::FrameworkPlugin->new( good01() ); - my $pars= { id => 'example_345' }; - is( $plugin->build($pars), 1, 'Build 1 ok'); + my $plugin = Koha::FrameworkPlugin->new( good01() ); + my $pars = { id => 'example_345' }; + is( $plugin->build($pars), 1, 'Build 1 ok' ); isnt( $plugin->javascript, '', 'Checked javascript property' ); - $plugin= Koha::FrameworkPlugin->new( ugly01() ); - $pars= { id => 'example_456' }; - is( $plugin->build($pars), 1, 'Build 2 ok'); - is( $plugin->build($pars), 1, 'Second build 2 ok'); + $plugin = Koha::FrameworkPlugin->new( ugly01() ); + $pars = { id => 'example_456' }; + is( $plugin->build($pars), 1, 'Build 2 ok' ); + is( $plugin->build($pars), 1, 'Second build 2 ok' ); is( $plugin->launch($pars), 'abc', 'Launcher returned something' ); - #note: normally you will not call build and launch like that + + #note: normally you will not call build and launch like that } sub test05 { - my ( $incl ) = @_; + my ($incl) = @_; + #mock to simulate some authorization and eliminate lots of output my $launched = 0; my $mContext = Test::MockModule->new('C4::Context'); - my $mAuth = Test::MockModule->new('C4::Auth'); - my $mOutput = Test::MockModule->new('C4::Output'); + my $mAuth = Test::MockModule->new('C4::Auth'); + my $mOutput = Test::MockModule->new('C4::Output'); $mContext->mock( 'userenv', \&mock_userenv ); - $mAuth->mock( 'checkauth', sub { return ( 1, undef, 1, all_perms() ); } ); + $mAuth->mock( 'checkauth', sub { return ( 1, undef, 1, all_perms() ); } ); $mAuth->mock( 'check_cookie_auth', sub { return ('ok') } ); - $mOutput->mock('output_html_with_http_headers', sub { ++$launched; } ); + $mOutput->mock( 'output_html_with_http_headers', sub { ++$launched; } ); - my $cgi=CGI->new; - my ( $plugins, $min ) = selected_plugins( $incl ); + my $cgi = CGI->new; + my ( $plugins, $min ) = selected_plugins($incl); # test building them my $objs; - foreach my $f ( @$plugins ) { - $objs->{$f} = Koha::FrameworkPlugin->new( $f ); - my $pars= { dbh => $dbh, id => $f }; - is( $objs->{$f}->build($pars), 1, "Builded ".$objs->{$f}->name ); + foreach my $f (@$plugins) { + $objs->{$f} = Koha::FrameworkPlugin->new($f); + my $pars = { dbh => $dbh, id => $f }; + is( $objs->{$f}->build($pars), 1, "Builded " . $objs->{$f}->name ); } # test launching them (but we cannot verify returned results here) undef $objs; - foreach my $f ( @$plugins ) { - $objs->{$f} = Koha::FrameworkPlugin->new( $f ); - my $pars= { dbh => $dbh, id => $f }; - $objs->{$f}->launch({ cgi => $cgi }); - # may generate some uninitialized warnings for missing params - is( $objs->{$f}->errstr, undef, "Launched ".$objs->{$f}->name ); + foreach my $f (@$plugins) { + $objs->{$f} = Koha::FrameworkPlugin->new($f); + my $pars = { dbh => $dbh, id => $f }; + $objs->{$f}->launch( { cgi => $cgi } ); + + # may generate some uninitialized warnings for missing params + is( $objs->{$f}->errstr, undef, "Launched " . $objs->{$f}->name ); } - is( $launched >= $min, 1, - "$launched of ". scalar @$plugins.' plugins generated output '); + is( + $launched >= $min, 1, + "$launched of " . scalar @$plugins . ' plugins generated output ' + ); done_testing(); } sub selected_plugins { - my ( $incl ) = @_; + my ($incl) = @_; + #if you use includes, FIRST assure yourself that you do not #include any destructive perl scripts! You know what you are doing.. - my ( @fi, $min); - if( $incl && @$incl ) { - @fi = @$incl; - $min = 0; #not sure how many will output - } else { # some default MARC, UNIMARC and item plugins + my ( @fi, $min ); + if ( $incl && @$incl ) { + @fi = @$incl; + $min = 0; #not sure how many will output + } else { # some default MARC, UNIMARC and item plugins @fi = qw| barcode.pl dateaccessioned.pl marc21_orgcode.pl -marc21_field_005.pl marc21_field_006.pl marc21_field_007.pl marc21_field_008.pl -marc21_field_008_authorities.pl marc21_leader.pl marc21_leader_authorities.pl -unimarc_leader.pl unimarc_field_100.pl unimarc_field_105.pl -unimarc_field_106.pl unimarc_field_110.pl unimarc_field_120.pl -unimarc_field_130.pl unimarc_field_140.pl unimarc_field_225a.pl -unimarc_field_4XX.pl |; - $min = 16; # the first four generate no output + marc21_field_005.pl marc21_field_006.pl marc21_field_007.pl marc21_field_008.pl + marc21_field_008_authorities.pl marc21_leader.pl marc21_leader_authorities.pl + unimarc_leader.pl unimarc_field_100.pl unimarc_field_105.pl + unimarc_field_106.pl unimarc_field_110.pl unimarc_field_120.pl + unimarc_field_130.pl unimarc_field_140.pl unimarc_field_225a.pl + unimarc_field_4XX.pl |; + $min = 16; # the first four generate no output } - @fi = grep - { !/ajax|callnumber(-KU)?\.pl|labs_theses/ } # skip these + @fi = grep { !/ajax|callnumber(-KU)?\.pl|labs_theses/ } # skip these @fi; - return ( \@fi, $min); + return ( \@fi, $min ); } sub mock_userenv { - my $branch = $builder->build({ source => 'Branch' }); + my $branch = $builder->build( { source => 'Branch' } ); return { branch => $branch->{branchcode}, flags => 1, id => 1 }; } sub all_perms { - my $p = $dbh->selectcol_arrayref("SELECT flag FROM userflags"); - my $rv= {}; - foreach my $module ( @$p ) { - $rv->{ $module } = 1; + my $p = $dbh->selectcol_arrayref("SELECT flag FROM userflags"); + my $rv = {}; + foreach my $module (@$p) { + $rv->{$module} = 1; } return $rv; } sub mytempfile { my ( $fh, $fn ) = tempfile( SUFFIX => '.plugin', UNLINK => 1 ); - print $fh $_[0]//''; + print $fh $_[0] // ''; close $fh; return $fn; } sub old01 { -# simple old style item plugin: note that Focus has two pars -# includes a typical empty Clic function and plugin subroutine - return mytempfile( <<'HERE' + + # simple old style item plugin: note that Focus has two pars + # includes a typical empty Clic function and plugin subroutine + return mytempfile( + <<'HERE' sub plugin_javascript { my ($dbh,$record,$tagslib,$field_number) = @_; my $function_name = $field_number; @@ -263,8 +282,9 @@ HERE ); } -sub good01 { #very simple new style plugin, no launcher - return mytempfile( <<'HERE' +sub good01 { #very simple new style plugin, no launcher + return mytempfile( + <<'HERE' my $builder = sub { my $params = shift; return qq| @@ -281,12 +301,13 @@ HERE ); } -sub bad01 { # this is no plugin - return mytempfile( 'Just nonsense' ); +sub bad01 { # this is no plugin + return mytempfile('Just nonsense'); } -sub bad02 { # common syntax error: you forgot the semicolon of sub1 declare - return mytempfile( <<'HERE' +sub bad02 { # common syntax error: you forgot the semicolon of sub1 declare + return mytempfile( + <<'HERE' my $sub1= sub { my $params = shift; return qq|<script type="text/javascript">function Change$params->{id}(event) { alert("Changed"); }</script>|; @@ -296,8 +317,9 @@ HERE ); } -sub bad03 { # badscript tag should trigger an error - return mytempfile( <<'HERE' +sub bad03 { # badscript tag should trigger an error + return mytempfile( + <<'HERE' my $sub1= sub { my $params = shift; return qq|<badscript type="text/javascript">function Click$params->{id} (event) { alert("Hi there"); return false; }</badscript>|; @@ -307,8 +329,9 @@ HERE ); } -sub ugly01 { #works, but not very readable.. - return mytempfile( <<'HERE' +sub ugly01 { #works, but not very readable.. + return mytempfile( + <<'HERE' return {builder=>sub{return qq|<script type="text/javascript">function Blur$_[0]->{id}(event){alert('Bye');}</script>|;},launcher=>sub{'abc'}}; HERE ); diff --git a/t/db_dependent/Heading.t b/t/db_dependent/Heading.t index 80ce96b842..5b4ecbdbe4 100755 --- a/t/db_dependent/Heading.t +++ b/t/db_dependent/Heading.t @@ -24,174 +24,198 @@ use t::lib::Mocks; use Test::MockModule; BEGIN { - use_ok('C4::Heading', qw( field valid_heading_subfield )); + use_ok( 'C4::Heading', qw( field valid_heading_subfield ) ); } subtest "MARC21 tests" => sub { plan tests => 8; - t::lib::Mocks::mock_preference('marcflavour', 'MARC21'); + t::lib::Mocks::mock_preference( 'marcflavour', 'MARC21' ); - ok(C4::Heading::valid_heading_subfield('100', 'a'), '100a valid for bib'); - ok(!C4::Heading::valid_heading_subfield('100', 'e'), '100e not valid for bib'); + ok( C4::Heading::valid_heading_subfield( '100', 'a' ), '100a valid for bib' ); + ok( !C4::Heading::valid_heading_subfield( '100', 'e' ), '100e not valid for bib' ); - ok(C4::Heading::valid_heading_subfield('100', 'a', 1), '100a valid for authority'); + ok( C4::Heading::valid_heading_subfield( '100', 'a', 1 ), '100a valid for authority' ); - ok(C4::Heading::valid_heading_subfield('110', 'a'), '110a valid for bib'); - ok(!C4::Heading::valid_heading_subfield('110', 'e'), '110e not valid for bib'); + ok( C4::Heading::valid_heading_subfield( '110', 'a' ), '110a valid for bib' ); + ok( !C4::Heading::valid_heading_subfield( '110', 'e' ), '110e not valid for bib' ); - ok(C4::Heading::valid_heading_subfield('600', 'a'), '600a valid for bib'); - ok(!C4::Heading::valid_heading_subfield('600', 'e'), '600e not valid for bib'); + ok( C4::Heading::valid_heading_subfield( '600', 'a' ), '600a valid for bib' ); + ok( !C4::Heading::valid_heading_subfield( '600', 'e' ), '600e not valid for bib' ); - ok(!C4::Heading::valid_heading_subfield('012', 'a'), '012a invalid field for bib'); + ok( !C4::Heading::valid_heading_subfield( '012', 'a' ), '012a invalid field for bib' ); }; subtest "UNIMARC tests" => sub { plan tests => 7; - t::lib::Mocks::mock_preference('marcflavour', 'UNIMARC'); + t::lib::Mocks::mock_preference( 'marcflavour', 'UNIMARC' ); - ok(C4::Heading::valid_heading_subfield('100', 'a'), '100a valid for bib'); - ok(!C4::Heading::valid_heading_subfield('100', 'i'), '100i not valid fir bib'); + ok( C4::Heading::valid_heading_subfield( '100', 'a' ), '100a valid for bib' ); + ok( !C4::Heading::valid_heading_subfield( '100', 'i' ), '100i not valid fir bib' ); - ok(C4::Heading::valid_heading_subfield('110', 'a'), '110a valid for bib'); - ok(!C4::Heading::valid_heading_subfield('110', 'i'), '110i not valid for bib'); + ok( C4::Heading::valid_heading_subfield( '110', 'a' ), '110a valid for bib' ); + ok( !C4::Heading::valid_heading_subfield( '110', 'i' ), '110i not valid for bib' ); - ok(C4::Heading::valid_heading_subfield('600', 'a'), '600a valid for bib'); - ok(!C4::Heading::valid_heading_subfield('600', 'i'), '600i not valid for bib'); + ok( C4::Heading::valid_heading_subfield( '600', 'a' ), '600a valid for bib' ); + ok( !C4::Heading::valid_heading_subfield( '600', 'i' ), '600i not valid for bib' ); - ok(!C4::Heading::valid_heading_subfield('012', 'a'), '012a invalid field for bib'); + ok( !C4::Heading::valid_heading_subfield( '012', 'a' ), '012a invalid field for bib' ); }; subtest "_search tests" => sub { plan tests => 10; - t::lib::Mocks::mock_preference('marcflavour', 'MARC21'); - t::lib::Mocks::mock_preference('SearchEngine', 'Elasticsearch'); + t::lib::Mocks::mock_preference( 'marcflavour', 'MARC21' ); + t::lib::Mocks::mock_preference( 'SearchEngine', 'Elasticsearch' ); + # NOTE: We are testing solely against ES here to make the assumptions simpler while testing # C4/Headings code specifically. The actual query building and searching code should # be covered in other test files my $search = Test::MockModule->new('Koha::SearchEngine::Elasticsearch::Search'); - $search->mock('search_auth_compat', sub { - my $self = shift; - my $search_query = shift; - return ($search_query, 1 ); - }); + $search->mock( + 'search_auth_compat', + sub { + my $self = shift; + my $search_query = shift; + return ( $search_query, 1 ); + } + ); - t::lib::Mocks::mock_preference('LinkerConsiderThesaurus', '0'); + t::lib::Mocks::mock_preference( 'LinkerConsiderThesaurus', '0' ); - my $field = MARC::Field->new( '650', ' ', '0', a => 'Uncles', x => 'Fiction' ); - my $heading = C4::Heading->new_from_field($field); - my ($search_query) = $heading->_search( 'match-heading' ); - my $terms = $search_query->{query}->{bool}->{must}; + my $field = MARC::Field->new( '650', ' ', '0', a => 'Uncles', x => 'Fiction' ); + my $heading = C4::Heading->new_from_field($field); + my ($search_query) = $heading->_search('match-heading'); + my $terms = $search_query->{query}->{bool}->{must}; my $expected_terms = [ { term => { 'match-heading.ci_raw' => 'Uncles generalsubdiv Fiction' } }, ]; - is_deeply( $terms, $expected_terms, "Search formed only using heading content, not thesaurus, when LinkerConsiderThesaurus disabled"); + is_deeply( + $terms, $expected_terms, + "Search formed only using heading content, not thesaurus, when LinkerConsiderThesaurus disabled" + ); + t::lib::Mocks::mock_preference( 'LinkerConsiderThesaurus', '1' ); - t::lib::Mocks::mock_preference('LinkerConsiderThesaurus', '1'); - - $field = MARC::Field->new( '650', ' ', '0', a => 'Uncles', x => 'Fiction' ); + $field = MARC::Field->new( '650', ' ', '0', a => 'Uncles', x => 'Fiction' ); $heading = C4::Heading->new_from_field($field); - ($search_query) = $heading->_search( 'match-heading' ); - $terms = $search_query->{query}->{bool}->{must}; + ($search_query) = $heading->_search('match-heading'); + $terms = $search_query->{query}->{bool}->{must}; $expected_terms = [ - { term => { 'match-heading.ci_raw' => 'Uncles generalsubdiv Fiction' } }, + { term => { 'match-heading.ci_raw' => 'Uncles generalsubdiv Fiction' } }, { term => { 'subject-heading-thesaurus.ci_raw' => 'a' } }, ]; - is_deeply( $terms, $expected_terms, "Search formed as expected for a subject with second indicator 0"); + is_deeply( $terms, $expected_terms, "Search formed as expected for a subject with second indicator 0" ); - $field = MARC::Field->new( '650', ' ', '3', a => 'Uncles', x => 'Fiction' ); + $field = MARC::Field->new( '650', ' ', '3', a => 'Uncles', x => 'Fiction' ); $heading = C4::Heading->new_from_field($field); - ($search_query) = $heading->_search( 'match-heading' ); - $terms = $search_query->{query}->{bool}->{must}; + ($search_query) = $heading->_search('match-heading'); + $terms = $search_query->{query}->{bool}->{must}; $expected_terms = [ - { term => { 'match-heading.ci_raw' => 'Uncles generalsubdiv Fiction' } }, + { term => { 'match-heading.ci_raw' => 'Uncles generalsubdiv Fiction' } }, { term => { 'subject-heading-thesaurus.ci_raw' => 'd' } }, ]; - is_deeply( $terms, $expected_terms, "Search formed as expected with second indicator 3"); + is_deeply( $terms, $expected_terms, "Search formed as expected with second indicator 3" ); - $field = MARC::Field->new( '650', ' ', '7', a => 'Uncles', x => 'Fiction', 2 => 'special_sauce' ); + $field = MARC::Field->new( '650', ' ', '7', a => 'Uncles', x => 'Fiction', 2 => 'special_sauce' ); $heading = C4::Heading->new_from_field($field); - ($search_query) = $heading->_search( 'match-heading' ); - $terms = $search_query->{query}->{bool}->{must}; + ($search_query) = $heading->_search('match-heading'); + $terms = $search_query->{query}->{bool}->{must}; $expected_terms = [ - { term => { 'match-heading.ci_raw' => 'Uncles generalsubdiv Fiction' } }, + { term => { 'match-heading.ci_raw' => 'Uncles generalsubdiv Fiction' } }, { term => { 'subject-heading-thesaurus.ci_raw' => 'special_sauce' } }, ]; - is_deeply( $terms, $expected_terms, "Search formed as expected with second indicator 7 and subfield 2"); + is_deeply( $terms, $expected_terms, "Search formed as expected with second indicator 7 and subfield 2" ); - $field = MARC::Field->new( '650', ' ', '4', a => 'Uncles', x => 'Fiction' ); + $field = MARC::Field->new( '650', ' ', '4', a => 'Uncles', x => 'Fiction' ); $heading = C4::Heading->new_from_field($field); - ($search_query) = $heading->_search( 'match-heading' ); - $terms = $search_query->{query}->{bool}->{must}; + ($search_query) = $heading->_search('match-heading'); + $terms = $search_query->{query}->{bool}->{must}; $expected_terms = [ - { term => { 'match-heading.ci_raw' => 'Uncles generalsubdiv Fiction' } }, + { term => { 'match-heading.ci_raw' => 'Uncles generalsubdiv Fiction' } }, { term => { 'subject-heading-thesaurus.ci_raw' => '|' } }, ]; - is_deeply( $terms, $expected_terms, "Search looks for thesaurus '|' when second indicator 4"); + is_deeply( $terms, $expected_terms, "Search looks for thesaurus '|' when second indicator 4" ); - $field = MARC::Field->new( '100', ' ', '', a => 'Yankovic, Al', d => '1959-,' ); + $field = MARC::Field->new( '100', ' ', '', a => 'Yankovic, Al', d => '1959-,' ); $heading = C4::Heading->new_from_field($field); - ($search_query) = $heading->_search( 'match-heading' ); - $terms = $search_query->{query}->{bool}->{must}; + ($search_query) = $heading->_search('match-heading'); + $terms = $search_query->{query}->{bool}->{must}; $expected_terms = [ { term => { 'match-heading.ci_raw' => 'Yankovic, Al 1959' } }, ]; - is_deeply( $terms, $expected_terms, "Search formed as expected for a non-subject field with single punctuation mark"); + is_deeply( + $terms, $expected_terms, + "Search formed as expected for a non-subject field with single punctuation mark" + ); - $field = MARC::Field->new( '100', ' ', '', a => 'Yankovic, Al', d => '1959-,', e => '[author]' ); + $field = MARC::Field->new( '100', ' ', '', a => 'Yankovic, Al', d => '1959-,', e => '[author]' ); $heading = C4::Heading->new_from_field($field); - ($search_query) = $heading->_search( 'match-heading' ); - $terms = $search_query->{query}->{bool}->{must}; + ($search_query) = $heading->_search('match-heading'); + $terms = $search_query->{query}->{bool}->{must}; $expected_terms = [ { term => { 'match-heading.ci_raw' => 'Yankovic, Al 1959' } }, ]; - is_deeply( $terms, $expected_terms, "Search formed as expected for a non-subject field with double punctuation, hyphen+comma"); + is_deeply( + $terms, $expected_terms, + "Search formed as expected for a non-subject field with double punctuation, hyphen+comma" + ); - $field = MARC::Field->new( '100', ' ', '', a => 'Tolkien, J.R.R.,', e => '[author]' ); + $field = MARC::Field->new( '100', ' ', '', a => 'Tolkien, J.R.R.,', e => '[author]' ); $heading = C4::Heading->new_from_field($field); - ($search_query) = $heading->_search( 'match-heading' ); - $terms = $search_query->{query}->{bool}->{must}; + ($search_query) = $heading->_search('match-heading'); + $terms = $search_query->{query}->{bool}->{must}; $expected_terms = [ { term => { 'match-heading.ci_raw' => 'Tolkien, J.R.R' } }, ]; - is_deeply( $terms, $expected_terms, "Search formed as expected for a non-subject field with double punctuation, period+comma "); + is_deeply( + $terms, $expected_terms, + "Search formed as expected for a non-subject field with double punctuation, period+comma " + ); - $search->mock('search_auth_compat', sub { - my $self = shift; - my $search_query = shift; - if( - scalar @{$search_query->{query}->{bool}->{must}} == 2 && - $search_query->{query}->{bool}->{must}[1]->{term}->{'subject-heading-thesaurus.ci_raw'} eq 'special_sauce' - ){ - return; + $search->mock( + 'search_auth_compat', + sub { + my $self = shift; + my $search_query = shift; + if ( scalar @{ $search_query->{query}->{bool}->{must} } == 2 + && $search_query->{query}->{bool}->{must}[1]->{term}->{'subject-heading-thesaurus.ci_raw'} eq + 'special_sauce' ) + { + return; + } + return ( $search_query, 1 ); } - return ($search_query, 1); - }); + ); # Special case where thesaurus defined in subfield 2 should also match record with no thesaurus - $field = MARC::Field->new( '650', ' ', '7', a => 'Uncles', x => 'Fiction', 2 => 'special_sauce' ); + $field = MARC::Field->new( '650', ' ', '7', a => 'Uncles', x => 'Fiction', 2 => 'special_sauce' ); $heading = C4::Heading->new_from_field($field); - ($search_query) = $heading->_search( 'match-heading' ); - $terms = $search_query->{query}->{bool}->{must}; + ($search_query) = $heading->_search('match-heading'); + $terms = $search_query->{query}->{bool}->{must}; $expected_terms = [ - { term => { 'match-heading.ci_raw' => 'Uncles generalsubdiv Fiction' } }, + { term => { 'match-heading.ci_raw' => 'Uncles generalsubdiv Fiction' } }, { term => { 'subject-heading-thesaurus.ci_raw' => 'z' } }, ]; - is_deeply( $terms, $expected_terms, "When thesaurus in subfield 2, and nothing is found, we should search again for notdefined (008_11 = z) "); + is_deeply( + $terms, $expected_terms, + "When thesaurus in subfield 2, and nothing is found, we should search again for notdefined (008_11 = z) " + ); - t::lib::Mocks::mock_preference('LinkerConsiderThesaurus', '0'); + t::lib::Mocks::mock_preference( 'LinkerConsiderThesaurus', '0' ); $search_query = undef; - ($search_query) = $heading->_search( 'match-heading' ); - $terms = $search_query->{query}->{bool}->{must}; + ($search_query) = $heading->_search('match-heading'); + $terms = $search_query->{query}->{bool}->{must}; $expected_terms = [ { term => { 'match-heading.ci_raw' => 'Uncles generalsubdiv Fiction' } }, ]; - is_deeply( $terms, $expected_terms, "When thesaurus in subfield 2, and nothing is found, we don't search again if LinkerConsiderThesaurusDisabled"); + is_deeply( + $terms, $expected_terms, + "When thesaurus in subfield 2, and nothing is found, we don't search again if LinkerConsiderThesaurusDisabled" + ); }; diff --git a/t/db_dependent/Heading_MARC21.t b/t/db_dependent/Heading_MARC21.t index 9f94cf2234..ade6e83a48 100755 --- a/t/db_dependent/Heading_MARC21.t +++ b/t/db_dependent/Heading_MARC21.t @@ -1,6 +1,6 @@ #!/usr/bin/perl # -# This Koha test module is a stub! +# This Koha test module is a stub! # Add more tests here!!! use strict; @@ -10,27 +10,27 @@ use Test::More tests => 10; use C4::Context; BEGIN { - use_ok('C4::Heading', qw( field new_from_field display_form search_form )); + use_ok( 'C4::Heading', qw( field new_from_field display_form search_form ) ); } SKIP: { skip "MARC21 heading tests not applicable to UNIMARC", 2 if C4::Context->preference('marcflavour') eq 'UNIMARC'; - my $field = MARC::Field->new( '650', ' ', '2', a => 'Uncles', x => 'Fiction' ); + my $field = MARC::Field->new( '650', ' ', '2', a => 'Uncles', x => 'Fiction' ); my $heading = C4::Heading->new_from_field($field); - is($heading->display_form(), 'Uncles--Fiction', 'Display form generation'); - is($heading->search_form(), 'Uncles generalsubdiv Fiction', 'Search form generation'); - is($heading->{thesaurus}, 'mesh', 'Thesaurus generation'); + is( $heading->display_form(), 'Uncles--Fiction', 'Display form generation' ); + is( $heading->search_form(), 'Uncles generalsubdiv Fiction', 'Search form generation' ); + is( $heading->{thesaurus}, 'mesh', 'Thesaurus generation' ); - $field = MARC::Field->new( '830', ' ', '4', a => 'The dark is rising ;', v => '3' ); + $field = MARC::Field->new( '830', ' ', '4', a => 'The dark is rising ;', v => '3' ); $heading = C4::Heading->new_from_field($field); - is($heading->display_form(), 'The dark is rising ;', 'Display form generation'); - is($heading->search_form(), 'The dark is rising', 'Search form generation'); - ok( !defined $heading->{thesaurus}, 'Thesaurus is not generated outside of 6XX fields'); + is( $heading->display_form(), 'The dark is rising ;', 'Display form generation' ); + is( $heading->search_form(), 'The dark is rising', 'Search form generation' ); + ok( !defined $heading->{thesaurus}, 'Thesaurus is not generated outside of 6XX fields' ); - $field = MARC::Field->new( '100', '1', '', a => 'Yankovic, Al', d => '1959-' ); + $field = MARC::Field->new( '100', '1', '', a => 'Yankovic, Al', d => '1959-' ); $heading = C4::Heading->new_from_field($field); - is($heading->display_form(), 'Yankovic, Al 1959-', 'Display form generation'); - is($heading->search_form(), 'Yankovic, Al 1959', 'Search form generation'); - ok( !defined $heading->{thesaurus}, 'Thesaurus is not generated outside of 6XX fields'); + is( $heading->display_form(), 'Yankovic, Al 1959-', 'Display form generation' ); + is( $heading->search_form(), 'Yankovic, Al 1959', 'Search form generation' ); + ok( !defined $heading->{thesaurus}, 'Thesaurus is not generated outside of 6XX fields' ); } diff --git a/t/db_dependent/Hold.t b/t/db_dependent/Hold.t index 15c61a31fa..cb517426ba 100755 --- a/t/db_dependent/Hold.t +++ b/t/db_dependent/Hold.t @@ -41,10 +41,10 @@ $schema->storage->txn_begin(); # add two branches and a borrower my $builder = t::lib::TestBuilder->new; my @branches; -foreach( 1..2 ) { - push @branches, $builder->build({ source => 'Branch' }); +foreach ( 1 .. 2 ) { + push @branches, $builder->build( { source => 'Branch' } ); } -my $borrower = $builder->build({ source => 'Borrower' }); +my $borrower = $builder->build( { source => 'Borrower' } ); my $biblio = MARC::Record->new(); my $title = 'Silence in the library'; @@ -78,10 +78,17 @@ my $hold = Koha::Hold->new( $hold->store(); my $b1_cal = C4::Calendar->new( branchcode => $branches[1]->{branchcode} ); -$b1_cal->insert_single_holiday( day => 2, month => 1, year => 2017, title => "Morty Day", description => "Rick" ); #Add a holiday +$b1_cal->insert_single_holiday( day => 2, month => 1, year => 2017, title => "Morty Day", description => "Rick" ) + ; #Add a holiday my $today = dt_from_string; -is( $hold->age(), $today->delta_days( dt_from_string( '2017-01-01' ) )->in_units( 'days') , "Age of hold is days from reservedate to now if calendar ignored"); -is( $hold->age(1), $today->delta_days( dt_from_string( '2017-01-01' ) )->in_units( 'days' ) - 1 , "Age of hold is days from reservedate to now minus 1 if calendar used"); +is( + $hold->age(), $today->delta_days( dt_from_string('2017-01-01') )->in_units('days'), + "Age of hold is days from reservedate to now if calendar ignored" +); +is( + $hold->age(1), $today->delta_days( dt_from_string('2017-01-01') )->in_units('days') - 1, + "Age of hold is days from reservedate to now minus 1 if calendar used" +); is( $hold->suspend, 0, "Hold is not suspended" ); $hold->suspend_hold(); @@ -89,15 +96,15 @@ is( $hold->suspend, 1, "Hold is suspended" ); $hold->resume(); is( $hold->suspend, 0, "Hold is not suspended" ); my $dt = dt_from_string(); -$hold->suspend_hold( $dt ); +$hold->suspend_hold($dt); $dt->truncate( to => 'day' ); -is( $hold->suspend, 1, "Hold is suspended" ); +is( $hold->suspend, 1, "Hold is suspended" ); is( $hold->suspend_until, "$dt", "Hold is suspended with a date, truncation takes place automatically" ); $hold->suspend_hold; -is( $hold->suspend, 1, "Hold is suspended" ); +is( $hold->suspend, 1, "Hold is suspended" ); is( $hold->suspend_until, undef, "Hold is suspended without a date" ); $hold->resume(); -is( $hold->suspend, 0, "Hold is not suspended" ); +is( $hold->suspend, 0, "Hold is not suspended" ); is( $hold->suspend_until, undef, "Hold no longer has suspend_until date" ); $item = $hold->item(); @@ -109,17 +116,17 @@ is( $hold_borrower->borrowernumber(), $borrower->{borrowernumber}, 'Hold borrowe t::lib::Mocks::mock_preference( 'ReservesMaxPickUpDelay', '5' ); $hold->found('T'); isnt( $hold->is_waiting, 1, 'The hold is not waiting (T)' ); -is( $hold->is_found, 1, 'The hold is found'); +is( $hold->is_found, 1, 'The hold is found' ); is( $hold->is_in_transit, 1, 'The hold is in transit' ); $hold->found('P'); -is( $hold->is_found, 1, 'The hold is found'); +is( $hold->is_found, 1, 'The hold is found' ); is( $hold->is_in_processing, 1, 'The hold is in processing' ); $hold->found(q{}); isnt( $hold->is_waiting, 1, 'The hold is not waiting (W)' ); is( $hold->is_found, 0, 'The hold is not found' ); -ok( !$hold->is_in_transit, 'The hold is not in transit' ); +ok( !$hold->is_in_transit, 'The hold is not in transit' ); ok( !$hold->is_in_processing, 'The hold is not in processing' ); # Test method is_cancelable_from_opac @@ -138,9 +145,15 @@ ok( !$hold->is_at_destination(), "Unfound hold cannot be at destination" ); $hold->found('T'); ok( !$hold->is_at_destination(), "In transit hold cannot be at destination" ); $hold->found('W'); -ok( !$hold->is_at_destination(), "Waiting hold where hold branchcode is not the same as the item's holdingbranch is not at destination" ); +ok( + !$hold->is_at_destination(), + "Waiting hold where hold branchcode is not the same as the item's holdingbranch is not at destination" +); $item->holdingbranch( $branches[1]->{branchcode} ); -ok( $hold->is_at_destination(), "Waiting hold where hold branchcode is the same as the item's holdingbranch is at destination" ); +ok( + $hold->is_at_destination(), + "Waiting hold where hold branchcode is the same as the item's holdingbranch is at destination" +); $schema->storage->txn_rollback(); @@ -158,8 +171,10 @@ subtest "store() tests" => sub { # Test setting expiration date t::lib::Mocks::mock_preference( 'DefaultHoldExpirationdate', 1 ); t::lib::Mocks::mock_preference( 'DefaultHoldExpirationdatePeriod', 2 ); - t::lib::Mocks::mock_preference( 'DefaultHoldExpirationdateUnitOfTime', - 'years' ); + t::lib::Mocks::mock_preference( + 'DefaultHoldExpirationdateUnitOfTime', + 'years' + ); my $hold = Koha::Hold->new( { @@ -174,13 +189,13 @@ subtest "store() tests" => sub { )->store; $hold->discard_changes; - my $expected_date = - dt_from_string( $hold->reservedate )->add( years => 2 ); - is( $hold->expirationdate, - $expected_date->ymd, 'Default expiration date for new hold is correctly set.' ); + my $expected_date = dt_from_string( $hold->reservedate )->add( years => 2 ); + is( + $hold->expirationdate, + $expected_date->ymd, 'Default expiration date for new hold is correctly set.' + ); - my $passed_date = - dt_from_string( $hold->reservedate )->add( months => 2 ); + my $passed_date = dt_from_string( $hold->reservedate )->add( months => 2 ); $hold = Koha::Hold->new( { biblionumber => $biblio->biblionumber, @@ -195,21 +210,27 @@ subtest "store() tests" => sub { )->store; $hold->discard_changes; - is( $hold->expirationdate, - $passed_date->ymd, 'Passed expiration date for new hold is correctly set.' ); + is( + $hold->expirationdate, + $passed_date->ymd, 'Passed expiration date for new hold is correctly set.' + ); $passed_date->add( months => 1 ); - $hold->expirationdate($passed_date->ymd)->store(); + $hold->expirationdate( $passed_date->ymd )->store(); $hold->discard_changes; - is( $hold->expirationdate, - $passed_date->ymd, 'Passed expiration date when updating hold is correctly set.' ); + is( + $hold->expirationdate, + $passed_date->ymd, 'Passed expiration date when updating hold is correctly set.' + ); - $hold->reservedate($passed_date->ymd)->store(); + $hold->reservedate( $passed_date->ymd )->store(); $hold->discard_changes; - is( $hold->expirationdate, - $passed_date->add( years => 2 )->ymd, 'Default expiration date correctly set on reservedate update.' ); + is( + $hold->expirationdate, + $passed_date->add( years => 2 )->ymd, 'Default expiration date correctly set on reservedate update.' + ); $hold->set( { @@ -219,8 +240,11 @@ subtest "store() tests" => sub { )->store(); $hold->discard_changes; - is( $hold->expirationdate, - $passed_date->ymd, 'Passed expiration date when updating hold correctly set (Passing both reservedate and expirationdate.' ); + is( + $hold->expirationdate, + $passed_date->ymd, + 'Passed expiration date when updating hold correctly set (Passing both reservedate and expirationdate.' + ); $passed_date = dt_from_string('2023-06-20'); $hold->set( @@ -276,15 +300,15 @@ subtest "set_waiting() tests" => sub { $schema->storage->txn_begin(); - my $hold = $builder->build_object({ class => 'Koha::Holds' }); + my $hold = $builder->build_object( { class => 'Koha::Holds' } ); $hold->waitingdate('2021-01-01'); $hold->set_waiting(); - is($hold->waitingdate, '2021-01-01', "Setting waiting when already waiting should not update waitingdate"); + is( $hold->waitingdate, '2021-01-01', "Setting waiting when already waiting should not update waitingdate" ); $hold->waitingdate(undef)->store; $hold->set_waiting(); - isnt($hold->waitingdate, undef, "Setting waiting when not waiting already should update waitingdate"); + isnt( $hold->waitingdate, undef, "Setting waiting when not waiting already should update waitingdate" ); $schema->storage->txn_rollback(); }; @@ -298,35 +322,45 @@ subtest "delete() tests" => sub { # Disable logging t::lib::Mocks::mock_preference( 'HoldsLog', 0 ); - my $hold = $builder->build({ source => 'Reserve' }); + my $hold = $builder->build( { source => 'Reserve' } ); - my $hold_object = Koha::Holds->find( $hold->{ reserve_id } ); - my $deleted = $hold_object->delete; - is( ref($deleted), 'Koha::Hold', 'Koha::Hold->delete should return the Koha::Hold object if the hold has been correctly deleted' ); - is( Koha::Holds->search({ reserve_id => $hold->{ reserve_id } })->count, 0, - "Koha::Hold->delete should have deleted the hold" ); + my $hold_object = Koha::Holds->find( $hold->{reserve_id} ); + my $deleted = $hold_object->delete; + is( + ref($deleted), 'Koha::Hold', + 'Koha::Hold->delete should return the Koha::Hold object if the hold has been correctly deleted' + ); + is( + Koha::Holds->search( { reserve_id => $hold->{reserve_id} } )->count, 0, + "Koha::Hold->delete should have deleted the hold" + ); - my $number_of_logs = $schema->resultset('ActionLog')->search( - { module => 'HOLDS', action => 'DELETE', object => $hold->{ reserve_id } } )->count; + my $number_of_logs = $schema->resultset('ActionLog') + ->search( { module => 'HOLDS', action => 'DELETE', object => $hold->{reserve_id} } )->count; is( $number_of_logs, 0, 'With HoldsLogs, Koha::Hold->delete shouldn\'t have been logged' ); # Enable logging t::lib::Mocks::mock_preference( 'HoldsLog', 1 ); - $hold = $builder->build({ source => 'Reserve' }); + $hold = $builder->build( { source => 'Reserve' } ); - $hold_object = Koha::Holds->find( $hold->{ reserve_id } ); - $deleted = $hold_object->delete; - is( ref($deleted), 'Koha::Hold', 'Koha::Hold->delete should return a Koha::Hold object if the hold has been correctly deleted' ); - is( Koha::Holds->search({ reserve_id => $hold->{ reserve_id } })->count, 0, - "Koha::Hold->delete should have deleted the hold" ); + $hold_object = Koha::Holds->find( $hold->{reserve_id} ); + $deleted = $hold_object->delete; + is( + ref($deleted), 'Koha::Hold', + 'Koha::Hold->delete should return a Koha::Hold object if the hold has been correctly deleted' + ); + is( + Koha::Holds->search( { reserve_id => $hold->{reserve_id} } )->count, 0, + "Koha::Hold->delete should have deleted the hold" + ); - $number_of_logs = $schema->resultset('ActionLog')->search( - { module => 'HOLDS', action => 'DELETE', object => $hold->{ reserve_id } } )->count; + $number_of_logs = $schema->resultset('ActionLog') + ->search( { module => 'HOLDS', action => 'DELETE', object => $hold->{reserve_id} } )->count; is( $number_of_logs, 1, 'With HoldsLogs, Koha::Hold->delete should have been logged' ); $schema->storage->txn_rollback(); - }; +}; subtest 'suspend() tests' => sub { @@ -338,15 +372,16 @@ subtest 'suspend() tests' => sub { t::lib::Mocks::mock_preference( 'HoldsLog', 0 ); my $hold = $builder->build_object( - { class => 'Koha::Holds', + { + class => 'Koha::Holds', value => { found => undef, suspend => 0, suspend_until => undef, waitingdate => undef } } ); ok( !$hold->is_suspended, 'Hold is not suspended' ); my $suspended = $hold->suspend_hold; - is( ref($suspended) , 'Koha::Hold', 'suspend returns the Koha::Hold object' ); - is( $suspended->id, $hold->id, 'suspend returns the same object' ); + is( ref($suspended), 'Koha::Hold', 'suspend returns the Koha::Hold object' ); + is( $suspended->id, $hold->id, 'suspend returns the same object' ); ok( $suspended->is_suspended, 'The hold is suspended' ); is( $suspended->suspend_until, undef, 'It is an indefinite suspension' ); @@ -356,9 +391,9 @@ subtest 'suspend() tests' => sub { # create a DT my $date = dt_from_string()->add( days => 1 ); - $suspended = $hold->suspend_hold( $date ); - is( ref($suspended) , 'Koha::Hold', 'suspend returns the Koha::Hold object' ); - is( $suspended->id, $hold->id, 'suspend returns the same object' ); + $suspended = $hold->suspend_hold($date); + is( ref($suspended), 'Koha::Hold', 'suspend returns the Koha::Hold object' ); + is( $suspended->id, $hold->id, 'suspend returns the same object' ); ok( $suspended->is_suspended, 'The hold is suspended' ); is( $suspended->suspend_until, $date->truncate( to => 'day' ), 'It is an indefinite suspension' ); @@ -368,27 +403,24 @@ subtest 'suspend() tests' => sub { # set hold found=W $hold->set_waiting; - throws_ok - { $hold->suspend_hold; } - 'Koha::Exceptions::Hold::CannotSuspendFound', + throws_ok { $hold->suspend_hold; } + 'Koha::Exceptions::Hold::CannotSuspendFound', 'Exception is thrown when a found hold is tried to suspend'; is( $@->status, 'W', 'Exception gets the \'status\' parameter set correctly' ); # set hold found=T $hold->set_transfer; - throws_ok - { $hold->suspend_hold; } - 'Koha::Exceptions::Hold::CannotSuspendFound', + throws_ok { $hold->suspend_hold; } + 'Koha::Exceptions::Hold::CannotSuspendFound', 'Exception is thrown when a found hold is tried to suspend'; is( $@->status, 'T', 'Exception gets the \'status\' parameter set correctly' ); # set hold found=T $hold->set_processing(); - throws_ok - { $hold->suspend_hold; } - 'Koha::Exceptions::Hold::CannotSuspendFound', + throws_ok { $hold->suspend_hold; } + 'Koha::Exceptions::Hold::CannotSuspendFound', 'Exception is thrown when a found hold is tried to suspend'; is( $@->status, 'P', 'Exception gets the \'status\' parameter set correctly' ); @@ -398,34 +430,38 @@ subtest 'suspend() tests' => sub { # bad data case $hold->found('X'); - throws_ok - { $hold->suspend_hold } - 'Koha::Exceptions::Hold::CannotSuspendFound', + throws_ok { $hold->suspend_hold } + 'Koha::Exceptions::Hold::CannotSuspendFound', 'Exception is thrown when a found hold is tried to suspend'; - is( $@->error, 'Unhandled data exception on found hold (id=' - . $hold->id - . ', found=' - . $hold->found - . ')' , 'Exception gets the \'status\' parameter set correctly' ); + is( + $@->error, 'Unhandled data exception on found hold (id=' + . $hold->id + . ', found=' + . $hold->found + . ')', 'Exception gets the \'status\' parameter set correctly' + ); - $holds_module->unmock( 'is_found' ); + $holds_module->unmock('is_found'); # Enable logging t::lib::Mocks::mock_preference( 'HoldsLog', 1 ); - my $logs_count = $schema->resultset('ActionLog')->search( - { module => 'HOLDS', action => 'SUSPEND', object => $hold->id } )->count; + my $logs_count = + $schema->resultset('ActionLog')->search( { module => 'HOLDS', action => 'SUSPEND', object => $hold->id } ) + ->count; $hold = $builder->build_object( - { class => 'Koha::Holds', + { + class => 'Koha::Holds', value => { suspend => 0, suspend_until => undef, waitingdate => undef, found => undef } } ); $hold->suspend_hold; - my $new_logs_count = $schema->resultset('ActionLog')->search( - { module => 'HOLDS', action => 'SUSPEND', object => $hold->id } )->count; + my $new_logs_count = + $schema->resultset('ActionLog')->search( { module => 'HOLDS', action => 'SUSPEND', object => $hold->id } ) + ->count; is( $new_logs_count, $logs_count + 1, 'If logging is enabled, suspending a hold gets logged' ); diff --git a/t/db_dependent/Holds.t b/t/db_dependent/Holds.t index b899c10ad1..b4c98d9393 100755 --- a/t/db_dependent/Holds.t +++ b/t/db_dependent/Holds.t @@ -15,14 +15,15 @@ use MARC::Record; use C4::Biblio; use C4::Calendar; use C4::Items; -use C4::Reserves qw( AddReserve CalculatePriority ModReserve AutoUnsuspendReserves SuspendAll ModReserveMinusPriority AlterPriority CanItemBeReserved CheckReserves MoveReserve ); +use C4::Reserves + qw( AddReserve CalculatePriority ModReserve AutoUnsuspendReserves SuspendAll ModReserveMinusPriority AlterPriority CanItemBeReserved CheckReserves MoveReserve ); use C4::Circulation qw( CanBookBeRenewed ); use Koha::Biblios; use Koha::CirculationRules; use Koha::Database; use Koha::DateUtils qw( dt_from_string output_pref ); -use Koha::Holds qw( search ); +use Koha::Holds qw( search ); use Koha::Checkout; use Koha::Item::Transfer::Limits; use Koha::Items; @@ -37,17 +38,17 @@ BEGIN { use lib $FindBin::Bin; } -my $schema = Koha::Database->new->schema; +my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; my $builder = t::lib::TestBuilder->new(); my $dbh = C4::Context->dbh; # Create two random branches -my $branch_1 = $builder->build({ source => 'Branch' })->{ branchcode }; -my $branch_2 = $builder->build({ source => 'Branch' })->{ branchcode }; +my $branch_1 = $builder->build( { source => 'Branch' } )->{branchcode}; +my $branch_2 = $builder->build( { source => 'Branch' } )->{branchcode}; -my $category = $builder->build({ source => 'Category' }); +my $category = $builder->build( { source => 'Category' } ); my $borrowers_count = 5; @@ -61,28 +62,30 @@ $insert_sth->execute('DUMMY'); $insert_sth->execute('ONLY1'); # Setup Test------------------------ -my $biblio = $builder->build_sample_biblio({ itemtype => 'DUMMY' }); +my $biblio = $builder->build_sample_biblio( { itemtype => 'DUMMY' } ); # Create item instance for testing. -my $item = $builder->build_sample_item({ library => $branch_1, biblionumber => $biblio->biblionumber }); +my $item = $builder->build_sample_item( { library => $branch_1, biblionumber => $biblio->biblionumber } ); my $itemnumber = $item->itemnumber; # Create some borrowers my @borrowernumbers; my @patrons; -foreach (1..$borrowers_count) { - my $patron = Koha::Patron->new({ - firstname => 'my firstname', - surname => 'my surname ' . $_, - categorycode => $category->{categorycode}, - branchcode => $branch_1, - })->store; - push @patrons, $patron; +foreach ( 1 .. $borrowers_count ) { + my $patron = Koha::Patron->new( + { + firstname => 'my firstname', + surname => 'my surname ' . $_, + categorycode => $category->{categorycode}, + branchcode => $branch_1, + } + )->store; + push @patrons, $patron; push @borrowernumbers, $patron->borrowernumber; } # Create five item level holds -foreach my $borrowernumber ( @borrowernumbers ) { +foreach my $borrowernumber (@borrowernumbers) { AddReserve( { branchcode => $branch_1, @@ -95,25 +98,28 @@ foreach my $borrowernumber ( @borrowernumbers ) { } my $holds = $biblio->holds; -is( $holds->count, $borrowers_count, 'Test GetReserves()' ); -is( $holds->next->priority, 1, "Reserve 1 has a priority of 1" ); -is( $holds->next->priority, 2, "Reserve 2 has a priority of 2" ); -is( $holds->next->priority, 3, "Reserve 3 has a priority of 3" ); -is( $holds->next->priority, 4, "Reserve 4 has a priority of 4" ); -is( $holds->next->priority, 5, "Reserve 5 has a priority of 5" ); +is( $holds->count, $borrowers_count, 'Test GetReserves()' ); +is( $holds->next->priority, 1, "Reserve 1 has a priority of 1" ); +is( $holds->next->priority, 2, "Reserve 2 has a priority of 2" ); +is( $holds->next->priority, 3, "Reserve 3 has a priority of 3" ); +is( $holds->next->priority, 4, "Reserve 4 has a priority of 4" ); +is( $holds->next->priority, 5, "Reserve 5 has a priority of 5" ); $holds = $item->current_holds; -my $first_hold = $holds->next; -my $reservedate = $first_hold->reservedate; +my $first_hold = $holds->next; +my $reservedate = $first_hold->reservedate; my $borrowernumber = $first_hold->borrowernumber; -my $branch_1code = $first_hold->branchcode; -my $reserve_id = $first_hold->reserve_id; -is( $reservedate, output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 }), "holds_placed_today should return a valid reserve date"); -is( $borrowernumber, $borrowernumbers[0], "holds_placed_today should return a valid borrowernumber"); -is( $branch_1code, $branch_1, "holds_placed_today should return a valid branchcode"); -ok($reserve_id, "Test holds_placed_today()"); +my $branch_1code = $first_hold->branchcode; +my $reserve_id = $first_hold->reserve_id; +is( + $reservedate, output_pref( { dt => dt_from_string, dateformat => 'iso', dateonly => 1 } ), + "holds_placed_today should return a valid reserve date" +); +is( $borrowernumber, $borrowernumbers[0], "holds_placed_today should return a valid borrowernumber" ); +is( $branch_1code, $branch_1, "holds_placed_today should return a valid branchcode" ); +ok( $reserve_id, "Test holds_placed_today()" ); -my $hold = Koha::Holds->find( $reserve_id ); +my $hold = Koha::Holds->find($reserve_id); ok( $hold, "Koha::Holds found the hold" ); my $hold_biblio = $hold->biblio(); ok( $hold_biblio, "Got biblio using biblio() method" ); @@ -122,106 +128,108 @@ ok( $hold_item, "Got item using item() method" ); my $hold_branch = $hold->branch(); ok( $hold_branch, "Got branch using branch() method" ); my $hold_found = $hold->found(); -$hold->set({ found => 'W'})->store(); -is( Koha::Holds->waiting()->count(), 1, "Koha::Holds->waiting returns waiting holds" ); +$hold->set( { found => 'W' } )->store(); +is( Koha::Holds->waiting()->count(), 1, "Koha::Holds->waiting returns waiting holds" ); is( Koha::Holds->unfilled()->count(), 4, "Koha::Holds->unfilled returns unfilled holds" ); my $patron = Koha::Patrons->find( $borrowernumbers[0] ); $holds = $patron->holds; -is( $holds->next->borrowernumber, $borrowernumbers[0], "Test Koha::Patron->holds"); +is( $holds->next->borrowernumber, $borrowernumbers[0], "Test Koha::Patron->holds" ); - -$holds = $item->current_holds; -$first_hold = $holds->next; +$holds = $item->current_holds; +$first_hold = $holds->next; $borrowernumber = $first_hold->borrowernumber; -$branch_1code = $first_hold->branchcode; -$reserve_id = $first_hold->reserve_id; +$branch_1code = $first_hold->branchcode; +$reserve_id = $first_hold->reserve_id; -ModReserve({ - reserve_id => $reserve_id, - rank => '4', - branchcode => $branch_1, - itemnumber => $itemnumber, - suspend_until => output_pref( { dt => dt_from_string( "2013-01-01", "iso" ), dateonly => 1 } ), -}); +ModReserve( + { + reserve_id => $reserve_id, + rank => '4', + branchcode => $branch_1, + itemnumber => $itemnumber, + suspend_until => output_pref( { dt => dt_from_string( "2013-01-01", "iso" ), dateonly => 1 } ), + } +); -$hold = Koha::Holds->find( $reserve_id ); +$hold = Koha::Holds->find($reserve_id); ok( $hold->priority eq '4', "Test ModReserve, priority changed correctly" ); -ok( $hold->suspend, "Test ModReserve, suspend hold" ); +ok( $hold->suspend, "Test ModReserve, suspend hold" ); is( $hold->suspend_until, '2013-01-01 00:00:00', "Test ModReserve, suspend until date" ); -ModReserve({ # call without reserve_id - rank => '3', - branchcode => $branch_1, - biblionumber => $biblio->biblionumber, - itemnumber => $itemnumber, - borrowernumber => $borrowernumber, -}); -$hold = Koha::Holds->find( $reserve_id ); +ModReserve( + { # call without reserve_id + rank => '3', + branchcode => $branch_1, + biblionumber => $biblio->biblionumber, + itemnumber => $itemnumber, + borrowernumber => $borrowernumber, + } +); +$hold = Koha::Holds->find($reserve_id); ok( $hold->priority eq '3', "Test ModReserve, priority changed correctly" ); AutoUnsuspendReserves(); -$hold = Koha::Holds->find( $reserve_id ); -ok( ! $hold->suspend, "Test AutoUnsuspendReserves()" ); +$hold = Koha::Holds->find($reserve_id); +ok( !$hold->suspend, "Test AutoUnsuspendReserves()" ); SuspendAll( borrowernumber => $borrowernumber, biblionumber => $biblio->biblionumber, - suspend => 1, - suspend_until => '2012-01-01', + suspend => 1, + suspend_until => '2012-01-01', ); -$hold = Koha::Holds->find( $reserve_id ); -is( $hold->suspend, 1, "Test SuspendAll()" ); +$hold = Koha::Holds->find($reserve_id); +is( $hold->suspend, 1, "Test SuspendAll()" ); is( $hold->suspend_until, '2012-01-01 00:00:00', "Test SuspendAll(), with date" ); SuspendAll( borrowernumber => $borrowernumber, biblionumber => $biblio->biblionumber, - suspend => 0, + suspend => 0, ); -$hold = Koha::Holds->find( $reserve_id ); -is( $hold->suspend, 0, "Test resuming with SuspendAll()" ); +$hold = Koha::Holds->find($reserve_id); +is( $hold->suspend, 0, "Test resuming with SuspendAll()" ); is( $hold->suspend_until, undef, "Test resuming with SuspendAll(), should have no suspend until date" ); # Add a new hold for the borrower whose hold we canceled earlier, this time at the bib level - AddReserve( - { - branchcode => $branch_1, - borrowernumber => $borrowernumbers[0], - biblionumber => $biblio->biblionumber, - } - ); +AddReserve( + { + branchcode => $branch_1, + borrowernumber => $borrowernumbers[0], + biblionumber => $biblio->biblionumber, + } +); -$patron = Koha::Patrons->find( $borrowernumber ); -$holds = $patron->holds; -my $reserveid = Koha::Holds->search({ biblionumber => $biblio->biblionumber, borrowernumber => $borrowernumbers[0] })->next->reserve_id; +$patron = Koha::Patrons->find($borrowernumber); +$holds = $patron->holds; +my $reserveid = Koha::Holds->search( { biblionumber => $biblio->biblionumber, borrowernumber => $borrowernumbers[0] } ) + ->next->reserve_id; ModReserveMinusPriority( $itemnumber, $reserveid ); $holds = $patron->holds; -is( $holds->search({ itemnumber => $itemnumber })->count, 1, "Test ModReserveMinusPriority()" ); +is( $holds->search( { itemnumber => $itemnumber } )->count, 1, "Test ModReserveMinusPriority()" ); $holds = $biblio->holds; -$hold = $holds->next; +$hold = $holds->next; AlterPriority( 'top', $hold->reserve_id, undef, 2, 1, 6 ); -$hold = Koha::Holds->find( $reserveid ); +$hold = Koha::Holds->find($reserveid); is( $hold->priority, '1', "Test AlterPriority(), move to top" ); AlterPriority( 'down', $hold->reserve_id, undef, 2, 1, 6 ); -$hold = Koha::Holds->find( $reserveid ); +$hold = Koha::Holds->find($reserveid); is( $hold->priority, '2', "Test AlterPriority(), move down" ); AlterPriority( 'up', $hold->reserve_id, 1, 3, 1, 6 ); -$hold = Koha::Holds->find( $reserveid ); +$hold = Koha::Holds->find($reserveid); is( $hold->priority, '1', "Test AlterPriority(), move up" ); AlterPriority( 'bottom', $hold->reserve_id, undef, 2, 1, 6 ); -$hold = Koha::Holds->find( $reserveid ); +$hold = Koha::Holds->find($reserveid); is( $hold->priority, '6', "Test AlterPriority(), move to bottom" ); - $hold->delete; -throws_ok - { C4::Reserves::ModReserve({ reserve_id => $hold->reserve_id }) } - 'Koha::Exceptions::ObjectNotFound', +throws_ok { C4::Reserves::ModReserve( { reserve_id => $hold->reserve_id } ) } +'Koha::Exceptions::ObjectNotFound', 'No hold with id ' . $hold->reserve_id; # Regression test for bug 2394 @@ -235,8 +243,9 @@ throws_ok # Note that canreservefromotherbranches has no effect if # IndependentBranches is OFF. -my $foreign_biblio = $builder->build_sample_biblio({ itemtype => 'DUMMY' }); -my $foreign_item = $builder->build_sample_item({ library => $branch_2, biblionumber => $foreign_biblio->biblionumber }); +my $foreign_biblio = $builder->build_sample_biblio( { itemtype => 'DUMMY' } ); +my $foreign_item = + $builder->build_sample_item( { library => $branch_2, biblionumber => $foreign_biblio->biblionumber } ); Koha::CirculationRules->set_rules( { categorycode => undef, @@ -261,36 +270,37 @@ Koha::CirculationRules->set_rules( ); # make sure some basic sysprefs are set -t::lib::Mocks::mock_preference('ReservesControlBranch', 'ItemHomeLibrary'); -t::lib::Mocks::mock_preference('item-level_itypes', 1); +t::lib::Mocks::mock_preference( 'ReservesControlBranch', 'ItemHomeLibrary' ); +t::lib::Mocks::mock_preference( 'item-level_itypes', 1 ); # if IndependentBranches is OFF, a $branch_1 patron can reserve an $branch_2 item -t::lib::Mocks::mock_preference('IndependentBranches', 0); +t::lib::Mocks::mock_preference( 'IndependentBranches', 0 ); is( - CanItemBeReserved($patrons[0], $foreign_item)->{status}, 'OK', + CanItemBeReserved( $patrons[0], $foreign_item )->{status}, 'OK', '$branch_1 patron allowed to reserve $branch_2 item with IndependentBranches OFF (bug 2394)' ); # if IndependentBranches is OFF, a $branch_1 patron cannot reserve an $branch_2 item -t::lib::Mocks::mock_preference('IndependentBranches', 1); -t::lib::Mocks::mock_preference('canreservefromotherbranches', 0); +t::lib::Mocks::mock_preference( 'IndependentBranches', 1 ); +t::lib::Mocks::mock_preference( 'canreservefromotherbranches', 0 ); ok( - CanItemBeReserved($patrons[0], $foreign_item)->{status} eq 'cannotReserveFromOtherBranches', + CanItemBeReserved( $patrons[0], $foreign_item )->{status} eq 'cannotReserveFromOtherBranches', '$branch_1 patron NOT allowed to reserve $branch_2 item with IndependentBranches ON ... (bug 2394)' ); # ... unless canreservefromotherbranches is ON -t::lib::Mocks::mock_preference('canreservefromotherbranches', 1); +t::lib::Mocks::mock_preference( 'canreservefromotherbranches', 1 ); ok( - CanItemBeReserved($patrons[0], $foreign_item)->{status} eq 'OK', + CanItemBeReserved( $patrons[0], $foreign_item )->{status} eq 'OK', '... unless canreservefromotherbranches is ON (bug 2394)' ); { # Regression test for bug 11336 # Test if ModReserve correctly recalculate the priorities - $biblio = $builder->build_sample_biblio({ itemtype => 'DUMMY' }); - $itemnumber = $builder->build_sample_item({ library => $branch_1, biblionumber => $biblio->biblionumber })->itemnumber; + $biblio = $builder->build_sample_biblio( { itemtype => 'DUMMY' } ); + $itemnumber = + $builder->build_sample_item( { library => $branch_1, biblionumber => $biblio->biblionumber } )->itemnumber; my $reserveid1 = AddReserve( { branchcode => $branch_1, @@ -300,7 +310,8 @@ ok( } ); - $itemnumber = $builder->build_sample_item({ library => $branch_1, biblionumber => $biblio->biblionumber })->itemnumber; + $itemnumber = + $builder->build_sample_item( { library => $branch_1, biblionumber => $biblio->biblionumber } )->itemnumber; my $reserveid2 = AddReserve( { branchcode => $branch_1, @@ -310,7 +321,8 @@ ok( } ); - $itemnumber = $builder->build_sample_item({ library => $branch_1, biblionumber => $biblio->biblionumber })->itemnumber; + $itemnumber = + $builder->build_sample_item( { library => $branch_1, biblionumber => $biblio->biblionumber } )->itemnumber; my $reserveid3 = AddReserve( { branchcode => $branch_1, @@ -320,18 +332,27 @@ ok( } ); - my $hhh = Koha::Holds->search({ biblionumber => $biblio->biblionumber }); - my $hold3 = Koha::Holds->find( $reserveid3 ); + my $hhh = Koha::Holds->search( { biblionumber => $biblio->biblionumber } ); + my $hold3 = Koha::Holds->find($reserveid3); is( $hold3->priority, 3, "The 3rd hold should have a priority set to 3" ); - ModReserve({ reserve_id => $reserveid1, rank => 'del' }); - ModReserve({ reserve_id => $reserveid2, rank => 'del' }); - is( $hold3->discard_changes->priority, 1, "After ModReserve, the 3rd reserve becomes the first on the waiting list" ); + ModReserve( { reserve_id => $reserveid1, rank => 'del' } ); + ModReserve( { reserve_id => $reserveid2, rank => 'del' } ); + is( + $hold3->discard_changes->priority, 1, + "After ModReserve, the 3rd reserve becomes the first on the waiting list" + ); } -my $damaged_item = Koha::Items->find($itemnumber)->damaged(1)->store; # FIXME The $itemnumber is a bit confusing here +my $damaged_item = Koha::Items->find($itemnumber)->damaged(1)->store; # FIXME The $itemnumber is a bit confusing here t::lib::Mocks::mock_preference( 'AllowHoldsOnDamagedItems', 1 ); -is( CanItemBeReserved( $patrons[0], $damaged_item)->{status}, 'OK', "Patron can reserve damaged item with AllowHoldsOnDamagedItems enabled" ); -ok( defined( ( CheckReserves($damaged_item) )[1] ), "Hold can be trapped for damaged item with AllowHoldsOnDamagedItems enabled" ); +is( + CanItemBeReserved( $patrons[0], $damaged_item )->{status}, 'OK', + "Patron can reserve damaged item with AllowHoldsOnDamagedItems enabled" +); +ok( + defined( ( CheckReserves($damaged_item) )[1] ), + "Hold can be trapped for damaged item with AllowHoldsOnDamagedItems enabled" +); $hold = Koha::Hold->new( { @@ -341,20 +362,31 @@ $hold = Koha::Hold->new( branchcode => $branch_1, } )->store(); -is( CanItemBeReserved( $patrons[0], $damaged_item )->{status}, +is( + CanItemBeReserved( $patrons[0], $damaged_item )->{status}, 'itemAlreadyOnHold', - "Patron cannot place a second item level hold for a given item" ); + "Patron cannot place a second item level hold for a given item" +); $hold->delete(); t::lib::Mocks::mock_preference( 'AllowHoldsOnDamagedItems', 0 ); -ok( CanItemBeReserved( $patrons[0], $damaged_item)->{status} eq 'damaged', "Patron cannot reserve damaged item with AllowHoldsOnDamagedItems disabled" ); -ok( !defined( ( CheckReserves($damaged_item) )[1] ), "Hold cannot be trapped for damaged item with AllowHoldsOnDamagedItems disabled" ); +ok( + CanItemBeReserved( $patrons[0], $damaged_item )->{status} eq 'damaged', + "Patron cannot reserve damaged item with AllowHoldsOnDamagedItems disabled" +); +ok( + !defined( ( CheckReserves($damaged_item) )[1] ), + "Hold cannot be trapped for damaged item with AllowHoldsOnDamagedItems disabled" +); # Items that are not for loan, but holdable should not be trapped until they are available for loan t::lib::Mocks::mock_preference( 'TrapHoldsOnOrder', 0 ); my $nfl_item = Koha::Items->find($itemnumber)->damaged(0)->notforloan(-1)->store; -Koha::Holds->search({ biblionumber => $biblio->id })->delete(); -is( CanItemBeReserved( $patrons[0], $nfl_item)->{status}, 'OK', "Patron can place hold on item that is not for loan but holdable ( notforloan < 0 )" ); +Koha::Holds->search( { biblionumber => $biblio->id } )->delete(); +is( + CanItemBeReserved( $patrons[0], $nfl_item )->{status}, 'OK', + "Patron can place hold on item that is not for loan but holdable ( notforloan < 0 )" +); $hold = Koha::Hold->new( { borrowernumber => $borrowernumbers[0], @@ -366,32 +398,45 @@ $hold = Koha::Hold->new( branchcode => $branch_1, } )->store(); -ok( !defined( ( CheckReserves($nfl_item) )[1] ), "Hold cannot be trapped for item that is not for loan but holdable ( notforloan < 0 )" ); +ok( + !defined( ( CheckReserves($nfl_item) )[1] ), + "Hold cannot be trapped for item that is not for loan but holdable ( notforloan < 0 )" +); t::lib::Mocks::mock_preference( 'TrapHoldsOnOrder', 1 ); -ok( defined( ( CheckReserves($nfl_item) )[1] ), "Hold is trapped for item that is not for loan but holdable ( notforloan < 0 )" ); +ok( + defined( ( CheckReserves($nfl_item) )[1] ), + "Hold is trapped for item that is not for loan but holdable ( notforloan < 0 )" +); t::lib::Mocks::mock_preference( 'SkipHoldTrapOnNotForLoanValue', '-1' ); -ok( !defined( ( CheckReserves($nfl_item) )[1] ), "Hold cannot be trapped for item with notforloan value matching SkipHoldTrapOnNotForLoanValue" ); +ok( + !defined( ( CheckReserves($nfl_item) )[1] ), + "Hold cannot be trapped for item with notforloan value matching SkipHoldTrapOnNotForLoanValue" +); t::lib::Mocks::mock_preference( 'SkipHoldTrapOnNotForLoanValue', '-1|1' ); -ok( !defined( ( CheckReserves($nfl_item) )[1] ), "Hold cannot be trapped for item with notforloan value matching SkipHoldTrapOnNotForLoanValue" ); +ok( + !defined( ( CheckReserves($nfl_item) )[1] ), + "Hold cannot be trapped for item with notforloan value matching SkipHoldTrapOnNotForLoanValue" +); t::lib::Mocks::mock_preference( 'SkipHoldTrapOnNotForLoanValue', '' ); my $item_group_1 = Koha::Biblio::ItemGroup->new( { biblio_id => $biblio->id } )->store(); my $item_group_2 = Koha::Biblio::ItemGroup->new( { biblio_id => $biblio->id } )->store(); -$item_group_1->add_item({ item_id => $itemnumber }); +$item_group_1->add_item( { item_id => $itemnumber } ); $hold->item_group_id( $item_group_2->id )->update; ok( !defined( ( CheckReserves($nfl_item) )[1] ), "Hold cannot be trapped for item with non-matching item group" ); is( - CanItemBeReserved( $patrons[0], $nfl_item)->{status}, 'itemAlreadyOnHold', + CanItemBeReserved( $patrons[0], $nfl_item )->{status}, 'itemAlreadyOnHold', "cannot request item that you have already reservedd" ); is( - CanItemBeReserved( $patrons[0], $item, undef, { ignore_hold_counts => 1 })->{status}, 'OK', + CanItemBeReserved( $patrons[0], $item, undef, { ignore_hold_counts => 1 } )->{status}, 'OK', "can request item if we are not checking holds counts, but only if policy allows or forbids it" ); $hold->delete(); # Regression test for bug 9532 -$biblio = $builder->build_sample_biblio({ itemtype => 'CANNOT' }); -$item = $builder->build_sample_item({ library => $branch_1, itype => 'CANNOT', biblionumber => $biblio->biblionumber}); +$biblio = $builder->build_sample_biblio( { itemtype => 'CANNOT' } ); +$item = + $builder->build_sample_item( { library => $branch_1, itype => 'CANNOT', biblionumber => $biblio->biblionumber } ); AddReserve( { branchcode => $branch_1, @@ -401,20 +446,20 @@ AddReserve( } ); is( - CanItemBeReserved( $patrons[0], $item)->{status}, 'noReservesAllowed', + CanItemBeReserved( $patrons[0], $item )->{status}, 'noReservesAllowed', "cannot request item if policy that matches on item-level item type forbids it" ); is( - CanItemBeReserved( $patrons[0], $item, undef, { ignore_hold_counts => 1 })->{status}, 'noReservesAllowed', + CanItemBeReserved( $patrons[0], $item, undef, { ignore_hold_counts => 1 } )->{status}, 'noReservesAllowed', "cannot request item if policy that matches on item-level item type forbids it even if ignoring counts" ); subtest 'CanItemBeReserved' => sub { plan tests => 2; - my $itemtype_can = $builder->build({source => "Itemtype"})->{itemtype}; - my $itemtype_cant = $builder->build({source => "Itemtype"})->{itemtype}; - my $itemtype_cant_record = $builder->build({source => "Itemtype"})->{itemtype}; + my $itemtype_can = $builder->build( { source => "Itemtype" } )->{itemtype}; + my $itemtype_cant = $builder->build( { source => "Itemtype" } )->{itemtype}; + my $itemtype_cant_record = $builder->build( { source => "Itemtype" } )->{itemtype}; Koha::CirculationRules->set_rules( { @@ -454,8 +499,8 @@ subtest 'CanItemBeReserved' => sub { { branchcode => $branch_1, itemtype => $itemtype_cant, - rules => { - holdallowed => 0, + rules => { + holdallowed => 0, returnbranch => 'homebranch', } } @@ -464,8 +509,8 @@ subtest 'CanItemBeReserved' => sub { { branchcode => $branch_1, itemtype => $itemtype_can, - rules => { - holdallowed => 1, + rules => { + holdallowed => 1, returnbranch => 'homebranch', } } @@ -474,38 +519,64 @@ subtest 'CanItemBeReserved' => sub { subtest 'noReservesAllowed' => sub { plan tests => 5; - my $biblionumber_cannot = $builder->build_sample_biblio({ itemtype => $itemtype_cant })->biblionumber; - my $biblionumber_can = $builder->build_sample_biblio({ itemtype => $itemtype_can })->biblionumber; - my $biblionumber_record_cannot = $builder->build_sample_biblio({ itemtype => $itemtype_cant_record })->biblionumber; + my $biblionumber_cannot = $builder->build_sample_biblio( { itemtype => $itemtype_cant } )->biblionumber; + my $biblionumber_can = $builder->build_sample_biblio( { itemtype => $itemtype_can } )->biblionumber; + my $biblionumber_record_cannot = + $builder->build_sample_biblio( { itemtype => $itemtype_cant_record } )->biblionumber; - my $item_1_can = $builder->build_sample_item({ homebranch => $branch_1, holdingbranch => $branch_1, itype => $itemtype_can, biblionumber => $biblionumber_cannot }); - my $item_1_cannot = $builder->build_sample_item({ homebranch => $branch_1, holdingbranch => $branch_1, itype => $itemtype_cant, biblionumber => $biblionumber_cannot }); - my $item_2_can = $builder->build_sample_item({ homebranch => $branch_1, holdingbranch => $branch_1, itype => $itemtype_can, biblionumber => $biblionumber_can }); - my $item_2_cannot = $builder->build_sample_item({ homebranch => $branch_1, holdingbranch => $branch_1, itype => $itemtype_cant, biblionumber => $biblionumber_can }); - my $item_3_cannot = $builder->build_sample_item({ homebranch => $branch_1, holdingbranch => $branch_1, itype => $itemtype_cant_record, biblionumber => $biblionumber_record_cannot }); + my $item_1_can = $builder->build_sample_item( + { + homebranch => $branch_1, holdingbranch => $branch_1, itype => $itemtype_can, + biblionumber => $biblionumber_cannot + } + ); + my $item_1_cannot = $builder->build_sample_item( + { + homebranch => $branch_1, holdingbranch => $branch_1, itype => $itemtype_cant, + biblionumber => $biblionumber_cannot + } + ); + my $item_2_can = $builder->build_sample_item( + { + homebranch => $branch_1, holdingbranch => $branch_1, itype => $itemtype_can, + biblionumber => $biblionumber_can + } + ); + my $item_2_cannot = $builder->build_sample_item( + { + homebranch => $branch_1, holdingbranch => $branch_1, itype => $itemtype_cant, + biblionumber => $biblionumber_can + } + ); + my $item_3_cannot = $builder->build_sample_item( + { + homebranch => $branch_1, holdingbranch => $branch_1, itype => $itemtype_cant_record, + biblionumber => $biblionumber_record_cannot + } + ); - Koha::Holds->search({borrowernumber => $borrowernumbers[0]})->delete; + Koha::Holds->search( { borrowernumber => $borrowernumbers[0] } )->delete; - t::lib::Mocks::mock_preference('item-level_itypes', 1); + t::lib::Mocks::mock_preference( 'item-level_itypes', 1 ); is( - CanItemBeReserved( $patrons[0], $item_2_cannot)->{status}, 'noReservesAllowed', + CanItemBeReserved( $patrons[0], $item_2_cannot )->{status}, 'noReservesAllowed', "With item level set, rule from item must be picked (CANNOT)" ); is( - CanItemBeReserved( $patrons[0], $item_1_can)->{status}, 'OK', + CanItemBeReserved( $patrons[0], $item_1_can )->{status}, 'OK', "With item level set, rule from item must be picked (CAN)" ); - t::lib::Mocks::mock_preference('item-level_itypes', 0); + t::lib::Mocks::mock_preference( 'item-level_itypes', 0 ); is( - CanItemBeReserved( $patrons[0], $item_1_can)->{status}, 'noReservesAllowed', + CanItemBeReserved( $patrons[0], $item_1_can )->{status}, 'noReservesAllowed', "With biblio level set, rule from biblio must be picked (CANNOT)" ); is( - CanItemBeReserved( $patrons[0], $item_2_cannot)->{status}, 'OK', + CanItemBeReserved( $patrons[0], $item_2_cannot )->{status}, 'OK', "With biblio level set, rule from biblio must be picked (CAN)" ); is( - CanItemBeReserved( $patrons[0], $item_3_cannot)->{status}, 'noReservesAllowed', + CanItemBeReserved( $patrons[0], $item_3_cannot )->{status}, 'noReservesAllowed', "When no holds allowed and no holds per record allowed should return noReservesAllowed" ); }; @@ -513,38 +584,63 @@ subtest 'CanItemBeReserved' => sub { subtest 'tooManyHoldsForThisRecord + tooManyReserves + itemAlreadyOnHold' => sub { plan tests => 7; - my $biblionumber_1 = $builder->build_sample_biblio({ itemtype => $itemtype_can })->biblionumber; - my $item_11 = $builder->build_sample_item({ homebranch => $branch_1, holdingbranch => $branch_1, itype => $itemtype_can, biblionumber => $biblionumber_1 }); - my $item_12 = $builder->build_sample_item({ homebranch => $branch_1, holdingbranch => $branch_1, itype => $itemtype_can, biblionumber => $biblionumber_1 }); - my $biblionumber_2 = $builder->build_sample_biblio({ itemtype => $itemtype_can })->biblionumber; - my $item_21 = $builder->build_sample_item({ homebranch => $branch_1, holdingbranch => $branch_1, itype => $itemtype_can, biblionumber => $biblionumber_2 }); - my $item_22 = $builder->build_sample_item({ homebranch => $branch_1, holdingbranch => $branch_1, itype => $itemtype_can, biblionumber => $biblionumber_2 }); + my $biblionumber_1 = $builder->build_sample_biblio( { itemtype => $itemtype_can } )->biblionumber; + my $item_11 = $builder->build_sample_item( + { + homebranch => $branch_1, holdingbranch => $branch_1, itype => $itemtype_can, + biblionumber => $biblionumber_1 + } + ); + my $item_12 = $builder->build_sample_item( + { + homebranch => $branch_1, holdingbranch => $branch_1, itype => $itemtype_can, + biblionumber => $biblionumber_1 + } + ); + my $biblionumber_2 = $builder->build_sample_biblio( { itemtype => $itemtype_can } )->biblionumber; + my $item_21 = $builder->build_sample_item( + { + homebranch => $branch_1, holdingbranch => $branch_1, itype => $itemtype_can, + biblionumber => $biblionumber_2 + } + ); + my $item_22 = $builder->build_sample_item( + { + homebranch => $branch_1, holdingbranch => $branch_1, itype => $itemtype_can, + biblionumber => $biblionumber_2 + } + ); - Koha::Holds->search({borrowernumber => $borrowernumbers[0]})->delete; + Koha::Holds->search( { borrowernumber => $borrowernumbers[0] } )->delete; # Biblio-level hold - AddReserve({ - branchcode => $branch_1, - borrowernumber => $borrowernumbers[0], - biblionumber => $biblionumber_1, - }); - for my $item_level ( 0..1 ) { - t::lib::Mocks::mock_preference('item-level_itypes', $item_level); + AddReserve( + { + branchcode => $branch_1, + borrowernumber => $borrowernumbers[0], + biblionumber => $biblionumber_1, + } + ); + for my $item_level ( 0 .. 1 ) { + t::lib::Mocks::mock_preference( 'item-level_itypes', $item_level ); is( # FIXME This is not really correct, but CanItemBeReserved does not check if biblio-level holds already exist - CanItemBeReserved( $patrons[0], $item_11)->{status}, 'OK', + CanItemBeReserved( $patrons[0], $item_11 )->{status}, 'OK', "A biblio-level hold already exists - another hold can be placed on a specific item item" ); } - Koha::Holds->search({borrowernumber => $borrowernumbers[0]})->delete; + Koha::Holds->search( { borrowernumber => $borrowernumbers[0] } )->delete; + # Item-level hold - AddReserve({ - branchcode => $branch_1, - borrowernumber => $borrowernumbers[0], - biblionumber => $biblionumber_1, - itemnumber => $item_11->itemnumber, - }); + AddReserve( + { + branchcode => $branch_1, + borrowernumber => $borrowernumbers[0], + biblionumber => $biblionumber_1, + itemnumber => $item_11->itemnumber, + } + ); $dbh->do('DELETE FROM circulation_rules'); Koha::CirculationRules->set_rules( @@ -559,7 +655,7 @@ subtest 'CanItemBeReserved' => sub { } ); is( - CanItemBeReserved( $patrons[0], $item_12)->{status}, 'tooManyHoldsForThisRecord', + CanItemBeReserved( $patrons[0], $item_12 )->{status}, 'tooManyHoldsForThisRecord', "A item-level hold already exists and holds_per_record=1, another hold cannot be placed on this record" ); Koha::CirculationRules->set_rules( @@ -574,7 +670,7 @@ subtest 'CanItemBeReserved' => sub { } ); is( - CanItemBeReserved( $patrons[0], $item_12)->{status}, 'tooManyHoldsForThisRecord', + CanItemBeReserved( $patrons[0], $item_12 )->{status}, 'tooManyHoldsForThisRecord', "A item-level hold already exists and holds_per_record=1 - tooManyHoldsForThisRecord has priority over tooManyReserves" ); Koha::CirculationRules->set_rules( @@ -589,16 +685,18 @@ subtest 'CanItemBeReserved' => sub { } ); is( - CanItemBeReserved( $patrons[0], $item_12)->{status}, 'OK', + CanItemBeReserved( $patrons[0], $item_12 )->{status}, 'OK', "A item-level hold already exists but holds_per_record=2- another item-level hold can be placed on this record" ); - AddReserve({ - branchcode => $branch_1, - borrowernumber => $borrowernumbers[0], - biblionumber => $biblionumber_2, - itemnumber => $item_21->itemnumber - }); + AddReserve( + { + branchcode => $branch_1, + borrowernumber => $borrowernumbers[0], + biblionumber => $biblionumber_2, + itemnumber => $item_21->itemnumber + } + ); Koha::CirculationRules->set_rules( { categorycode => undef, @@ -611,17 +709,16 @@ subtest 'CanItemBeReserved' => sub { } ); is( - CanItemBeReserved( $patrons[0], $item_21)->{status}, 'itemAlreadyOnHold', + CanItemBeReserved( $patrons[0], $item_21 )->{status}, 'itemAlreadyOnHold', "A item-level holds already exists on this item, itemAlreadyOnHold should be raised" ); is( - CanItemBeReserved( $patrons[0], $item_22)->{status}, 'tooManyReserves', + CanItemBeReserved( $patrons[0], $item_22 )->{status}, 'tooManyReserves', "This patron has already placed reservesallowed holds, tooManyReserves should be raised" ); }; }; - # Test branch item rules $dbh->do('DELETE FROM circulation_rules'); @@ -640,8 +737,8 @@ Koha::CirculationRules->set_rules( { branchcode => $branch_1, itemtype => 'CANNOT', - rules => { - holdallowed => 'not_allowed', + rules => { + holdallowed => 'not_allowed', returnbranch => 'homebranch', } } @@ -650,30 +747,41 @@ Koha::CirculationRules->set_rules( { branchcode => $branch_1, itemtype => 'CAN', - rules => { - holdallowed => 'from_home_library', + rules => { + holdallowed => 'from_home_library', returnbranch => 'homebranch', } } ); -$biblio = $builder->build_sample_biblio({ itemtype => 'CANNOT' }); -my $branch_rule_item = $builder->build_sample_item({ library => $branch_1, itype => 'CANNOT', biblionumber => $biblio->biblionumber}); -is(CanItemBeReserved($patrons[0], $branch_rule_item)->{status}, 'notReservable', - "CanItemBeReserved should return 'notReservable'"); +$biblio = $builder->build_sample_biblio( { itemtype => 'CANNOT' } ); +my $branch_rule_item = + $builder->build_sample_item( { library => $branch_1, itype => 'CANNOT', biblionumber => $biblio->biblionumber } ); +is( + CanItemBeReserved( $patrons[0], $branch_rule_item )->{status}, 'notReservable', + "CanItemBeReserved should return 'notReservable'" +); t::lib::Mocks::mock_preference( 'ReservesControlBranch', 'PatronLibrary' ); -$branch_rule_item = $builder->build_sample_item({ library => $branch_2, itype => 'CAN', biblionumber => $biblio->biblionumber}); -is(CanItemBeReserved($patrons[0], $branch_rule_item)->{status}, +$branch_rule_item = + $builder->build_sample_item( { library => $branch_2, itype => 'CAN', biblionumber => $biblio->biblionumber } ); +is( + CanItemBeReserved( $patrons[0], $branch_rule_item )->{status}, 'cannotReserveFromOtherBranches', - "CanItemBeReserved should use PatronLibrary rule when ReservesControlBranch set to 'PatronLibrary'"); + "CanItemBeReserved should use PatronLibrary rule when ReservesControlBranch set to 'PatronLibrary'" +); t::lib::Mocks::mock_preference( 'ReservesControlBranch', 'ItemHomeLibrary' ); -is(CanItemBeReserved($patrons[0], $branch_rule_item)->{status}, +is( + CanItemBeReserved( $patrons[0], $branch_rule_item )->{status}, 'OK', - "CanItemBeReserved should use item home library rule when ReservesControlBranch set to 'ItemsHomeLibrary'"); + "CanItemBeReserved should use item home library rule when ReservesControlBranch set to 'ItemsHomeLibrary'" +); -$branch_rule_item = $builder->build_sample_item({ library => $branch_1, itype => 'CAN', biblionumber => $biblio->biblionumber}); -is(CanItemBeReserved($patrons[0], $branch_rule_item)->{status}, 'OK', - "CanItemBeReserved should return 'OK'"); +$branch_rule_item = + $builder->build_sample_item( { library => $branch_1, itype => 'CAN', biblionumber => $biblio->biblionumber } ); +is( + CanItemBeReserved( $patrons[0], $branch_rule_item )->{status}, 'OK', + "CanItemBeReserved should return 'OK'" +); # Bug 12632 t::lib::Mocks::mock_preference( 'item-level_itypes', 1 ); @@ -684,8 +792,8 @@ $dbh->do('DELETE FROM issues'); $dbh->do('DELETE FROM items'); $dbh->do('DELETE FROM biblio'); -$biblio = $builder->build_sample_biblio({ itemtype => 'ONLY1' }); -my $limit_count_item = $builder->build_sample_item({ library => $branch_1, biblionumber => $biblio->biblionumber}); +$biblio = $builder->build_sample_biblio( { itemtype => 'ONLY1' } ); +my $limit_count_item = $builder->build_sample_item( { library => $branch_1, biblionumber => $biblio->biblionumber } ); Koha::CirculationRules->set_rules( { @@ -698,8 +806,10 @@ Koha::CirculationRules->set_rules( } } ); -is( CanItemBeReserved( $patrons[0], $limit_count_item )->{status}, - 'OK', 'Patron can reserve item with hold limit of 1, no holds placed' ); +is( + CanItemBeReserved( $patrons[0], $limit_count_item )->{status}, + 'OK', 'Patron can reserve item with hold limit of 1, no holds placed' +); my $res_id = AddReserve( { @@ -710,15 +820,22 @@ my $res_id = AddReserve( } ); -is( CanItemBeReserved( $patrons[0], $limit_count_item )->{status}, - 'tooManyReserves', 'Patron cannot reserve item with hold limit of 1, 1 bib level hold placed' ); -is( CanItemBeReserved( $patrons[0], $limit_count_item, undef, { ignore_hold_counts => 1 } )->{status}, - 'OK', 'Patron can reserve item if checking policy but not counts' ); +is( + CanItemBeReserved( $patrons[0], $limit_count_item )->{status}, + 'tooManyReserves', 'Patron cannot reserve item with hold limit of 1, 1 bib level hold placed' +); +is( + CanItemBeReserved( $patrons[0], $limit_count_item, undef, { ignore_hold_counts => 1 } )->{status}, + 'OK', 'Patron can reserve item if checking policy but not counts' +); - #results should be the same for both ReservesControlBranch settings +#results should be the same for both ReservesControlBranch settings t::lib::Mocks::mock_preference( 'ReservesControlBranch', 'ItemHomeLibrary' ); -is( CanItemBeReserved( $patrons[0], $limit_count_item )->{status}, - 'tooManyReserves', 'Patron cannot reserve item with hold limit of 1, 1 bib level hold placed' ); +is( + CanItemBeReserved( $patrons[0], $limit_count_item )->{status}, + 'tooManyReserves', 'Patron cannot reserve item with hold limit of 1, 1 bib level hold placed' +); + #reset for further tests t::lib::Mocks::mock_preference( 'ReservesControlBranch', 'PatronLibrary' ); @@ -728,7 +845,7 @@ subtest 'Test max_holds per library/patron category' => sub { $dbh->do('DELETE FROM reserves'); $biblio = $builder->build_sample_biblio; - my $max_holds_item = $builder->build_sample_item({ library => $branch_1, biblionumber => $biblio->biblionumber}); + my $max_holds_item = $builder->build_sample_item( { library => $branch_1, biblionumber => $biblio->biblionumber } ); Koha::CirculationRules->set_rules( { categorycode => undef, @@ -753,7 +870,7 @@ subtest 'Test max_holds per library/patron category' => sub { } my $count = - Koha::Holds->search( { borrowernumber => $borrowernumbers[0] } )->count(); + Koha::Holds->search( { borrowernumber => $borrowernumbers[0] } )->count(); is( $count, 3, 'Patron now has 3 holds' ); my $ret = CanItemBeReserved( $patrons[0], $max_holds_item ); @@ -804,8 +921,9 @@ subtest 'Test max_holds per library/patron category' => sub { subtest 'Pickup location availability tests' => sub { plan tests => 4; - $biblio = $builder->build_sample_biblio({ itemtype => 'ONLY1' }); - my $pickup_item = $builder->build_sample_item({ library => $branch_1, biblionumber => $biblio->biblionumber}); + $biblio = $builder->build_sample_biblio( { itemtype => 'ONLY1' } ); + my $pickup_item = $builder->build_sample_item( { library => $branch_1, biblionumber => $biblio->biblionumber } ); + #Add a default rule to allow some holds Koha::CirculationRules->set_rules( @@ -819,32 +937,42 @@ subtest 'Pickup location availability tests' => sub { } } ); - my $branch_to = $builder->build({ source => 'Branch' })->{ branchcode }; - my $library = Koha::Libraries->find($branch_to); + my $branch_to = $builder->build( { source => 'Branch' } )->{branchcode}; + my $library = Koha::Libraries->find($branch_to); $library->pickup_location('1')->store; - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); - t::lib::Mocks::mock_preference('UseBranchTransferLimits', 1); - t::lib::Mocks::mock_preference('BranchTransferLimitsType', 'itemtype'); + t::lib::Mocks::mock_preference( 'UseBranchTransferLimits', 1 ); + t::lib::Mocks::mock_preference( 'BranchTransferLimitsType', 'itemtype' ); $library->pickup_location('1')->store; - is(CanItemBeReserved($patron, $pickup_item, $branch_to)->{status}, - 'OK', 'Library is a pickup location'); + is( + CanItemBeReserved( $patron, $pickup_item, $branch_to )->{status}, + 'OK', 'Library is a pickup location' + ); - my $limit = Koha::Item::Transfer::Limit->new({ - fromBranch => $pickup_item->holdingbranch, - toBranch => $branch_to, - itemtype => $pickup_item->effective_itemtype, - })->store; - is(CanItemBeReserved($patron, $pickup_item, $branch_to)->{status}, - 'cannotBeTransferred', 'Item cannot be transferred'); + my $limit = Koha::Item::Transfer::Limit->new( + { + fromBranch => $pickup_item->holdingbranch, + toBranch => $branch_to, + itemtype => $pickup_item->effective_itemtype, + } + )->store; + is( + CanItemBeReserved( $patron, $pickup_item, $branch_to )->{status}, + 'cannotBeTransferred', 'Item cannot be transferred' + ); $limit->delete; $library->pickup_location('0')->store; - is(CanItemBeReserved($patron, $pickup_item, $branch_to)->{status}, - 'libraryNotPickupLocation', 'Library is not a pickup location'); - is(CanItemBeReserved($patron, $pickup_item, 'nonexistent')->{status}, - 'libraryNotFound', 'Cannot set unknown library as pickup location'); + is( + CanItemBeReserved( $patron, $pickup_item, $branch_to )->{status}, + 'libraryNotPickupLocation', 'Library is not a pickup location' + ); + is( + CanItemBeReserved( $patron, $pickup_item, 'nonexistent' )->{status}, + 'libraryNotFound', 'Cannot set unknown library as pickup location' + ); }; $schema->storage->txn_rollback; @@ -860,12 +988,15 @@ subtest 'CanItemBeReserved / holds_per_day tests' => sub { my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); # Create 3 biblios with items - my $biblio_1 = $builder->build_sample_biblio({ itemtype => $itemtype->itemtype }); - my $item_1 = $builder->build_sample_item({ library => $library->branchcode, biblionumber => $biblio_1->biblionumber}); - my $biblio_2 = $builder->build_sample_biblio({ itemtype => $itemtype->itemtype }); - my $item_2 = $builder->build_sample_item({ library => $library->branchcode, biblionumber => $biblio_2->biblionumber}); - my $biblio_3 = $builder->build_sample_biblio({ itemtype => $itemtype->itemtype }); - my $item_3 = $builder->build_sample_item({ library => $library->branchcode, biblionumber => $biblio_3->biblionumber}); + my $biblio_1 = $builder->build_sample_biblio( { itemtype => $itemtype->itemtype } ); + my $item_1 = + $builder->build_sample_item( { library => $library->branchcode, biblionumber => $biblio_1->biblionumber } ); + my $biblio_2 = $builder->build_sample_biblio( { itemtype => $itemtype->itemtype } ); + my $item_2 = + $builder->build_sample_item( { library => $library->branchcode, biblionumber => $biblio_2->biblionumber } ); + my $biblio_3 = $builder->build_sample_biblio( { itemtype => $itemtype->itemtype } ); + my $item_3 = + $builder->build_sample_item( { library => $library->branchcode, biblionumber => $biblio_3->biblionumber } ); Koha::CirculationRules->set_rules( { @@ -908,8 +1039,8 @@ subtest 'CanItemBeReserved / holds_per_day tests' => sub { categorycode => '*', branchcode => '*', itemtype => $itemtype->itemtype, - rule_name => 'reservesallowed', - rule_value => 3, + rule_name => 'reservesallowed', + rule_value => 3, } ); @@ -952,12 +1083,11 @@ subtest 'CanItemBeReserved / holds_per_day tests' => sub { categorycode => '*', branchcode => '*', itemtype => $itemtype->itemtype, - rule_name => 'holds_per_day', - rule_value => 0, + rule_name => 'holds_per_day', + rule_value => 0, } ); - # Delete existing holds Koha::Holds->search->delete; is_deeply( @@ -972,8 +1102,8 @@ subtest 'CanItemBeReserved / holds_per_day tests' => sub { categorycode => '*', branchcode => '*', itemtype => $itemtype->itemtype, - rule_name => 'holds_per_day', - rule_value => undef, + rule_name => 'holds_per_day', + rule_value => undef, } ); @@ -1018,8 +1148,9 @@ subtest 'CanItemBeReserved / holds_per_day tests' => sub { { status => 'tooManyReserves', limit => 3 }, 'Unlimited daily holds, but reached reservesallowed' ); + #results should be the same for both ReservesControlBranch settings - t::lib::Mocks::mock_preference('ReservesControlBranch', 'ItemHomeLibrary'); + t::lib::Mocks::mock_preference( 'ReservesControlBranch', 'ItemHomeLibrary' ); is_deeply( CanItemBeReserved( $patron, $item_3 ), { status => 'tooManyReserves', limit => 3 }, @@ -1049,28 +1180,41 @@ subtest 'CanItemBeReserved / branch_not_in_hold_group' => sub { my $itemtype2 = $builder->build_object( { class => 'Koha::ItemTypes' } ); # Create libraries - my $library1 = $builder->build_object( { class => 'Koha::Libraries' } ); - my $library2 = $builder->build_object( { class => 'Koha::Libraries' } ); - my $library3 = $builder->build_object( { class => 'Koha::Libraries' } ); + my $library1 = $builder->build_object( { class => 'Koha::Libraries' } ); + my $library2 = $builder->build_object( { class => 'Koha::Libraries' } ); + my $library3 = $builder->build_object( { class => 'Koha::Libraries' } ); # Create library groups hierarchy - my $rootgroup = $builder->build_object( { class => 'Koha::Library::Groups', value => {ft_local_hold_group => 1} } ); - my $group1 = $builder->build_object( { class => 'Koha::Library::Groups', value => {parent_id => $rootgroup->id, branchcode => $library1->branchcode}} ); - my $group2 = $builder->build_object( { class => 'Koha::Library::Groups', value => {parent_id => $rootgroup->id, branchcode => $library2->branchcode} } ); + my $rootgroup = + $builder->build_object( { class => 'Koha::Library::Groups', value => { ft_local_hold_group => 1 } } ); + my $group1 = $builder->build_object( + { + class => 'Koha::Library::Groups', + value => { parent_id => $rootgroup->id, branchcode => $library1->branchcode } + } + ); + my $group2 = $builder->build_object( + { + class => 'Koha::Library::Groups', + value => { parent_id => $rootgroup->id, branchcode => $library2->branchcode } + } + ); # Create 2 patrons - my $patron1 = $builder->build_object( { class => 'Koha::Patrons', value => {branchcode => $library1->branchcode} } ); - my $patron3 = $builder->build_object( { class => 'Koha::Patrons', value => {branchcode => $library3->branchcode} } ); + my $patron1 = + $builder->build_object( { class => 'Koha::Patrons', value => { branchcode => $library1->branchcode } } ); + my $patron3 = + $builder->build_object( { class => 'Koha::Patrons', value => { branchcode => $library3->branchcode } } ); # Create 3 biblios with items - my $biblio_1 = $builder->build_sample_biblio({ itemtype => $itemtype1->itemtype }); + my $biblio_1 = $builder->build_sample_biblio( { itemtype => $itemtype1->itemtype } ); my $item_1 = $builder->build_sample_item( { biblionumber => $biblio_1->biblionumber, library => $library1->branchcode } ); - my $biblio_2 = $builder->build_sample_biblio({ itemtype => $itemtype2->itemtype }); + my $biblio_2 = $builder->build_sample_biblio( { itemtype => $itemtype2->itemtype } ); my $item_2 = $builder->build_sample_item( { biblionumber => $biblio_2->biblionumber, @@ -1078,8 +1222,8 @@ subtest 'CanItemBeReserved / branch_not_in_hold_group' => sub { } ); my $itemnumber_2 = $item_2->itemnumber; - my $biblio_3 = $builder->build_sample_biblio({ itemtype => $itemtype1->itemtype }); - my $item_3 = $builder->build_sample_item( + my $biblio_3 = $builder->build_sample_biblio( { itemtype => $itemtype1->itemtype } ); + my $item_3 = $builder->build_sample_item( { biblionumber => $biblio_3->biblionumber, library => $library1->branchcode @@ -1098,10 +1242,10 @@ subtest 'CanItemBeReserved / branch_not_in_hold_group' => sub { { branchcode => undef, itemtype => undef, - rules => { - holdallowed => 'from_local_hold_group', + rules => { + holdallowed => 'from_local_hold_group', hold_fulfillment_policy => 'any', - returnbranch => 'any' + returnbranch => 'any' } } ); @@ -1125,10 +1269,10 @@ subtest 'CanItemBeReserved / branch_not_in_hold_group' => sub { { branchcode => $library2->branchcode, itemtype => undef, - rules => { - holdallowed => 'from_any_library', + rules => { + holdallowed => 'from_any_library', hold_fulfillment_policy => 'any', - returnbranch => 'any' + returnbranch => 'any' } } ); @@ -1145,10 +1289,10 @@ subtest 'CanItemBeReserved / branch_not_in_hold_group' => sub { { branchcode => $library2->branchcode, itemtype => undef, - rules => { - holdallowed => 'from_local_hold_group', + rules => { + holdallowed => 'from_local_hold_group', hold_fulfillment_policy => 'any', - returnbranch => 'any' + returnbranch => 'any' } } ); @@ -1165,10 +1309,10 @@ subtest 'CanItemBeReserved / branch_not_in_hold_group' => sub { { branchcode => $library2->branchcode, itemtype => $itemtype2->itemtype, - rules => { - holdallowed => 'from_any_library', + rules => { + holdallowed => 'from_any_library', hold_fulfillment_policy => 'any', - returnbranch => 'any' + returnbranch => 'any' } } ); @@ -1185,10 +1329,10 @@ subtest 'CanItemBeReserved / branch_not_in_hold_group' => sub { { branchcode => $library2->branchcode, itemtype => $itemtype2->itemtype, - rules => { - holdallowed => 'from_local_hold_group', + rules => { + holdallowed => 'from_local_hold_group', hold_fulfillment_policy => 'any', - returnbranch => 'any' + returnbranch => 'any' } } ); @@ -1205,10 +1349,10 @@ subtest 'CanItemBeReserved / branch_not_in_hold_group' => sub { { branchcode => $library2->branchcode, itemtype => $itemtype2->itemtype, - rules => { - holdallowed => 'from_any_library', + rules => { + holdallowed => 'from_any_library', hold_fulfillment_policy => 'any', - returnbranch => 'any' + returnbranch => 'any' } } ); @@ -1225,10 +1369,10 @@ subtest 'CanItemBeReserved / branch_not_in_hold_group' => sub { { branchcode => $library2->branchcode, itemtype => $itemtype2->itemtype, - rules => { - holdallowed => 'from_local_hold_group', + rules => { + holdallowed => 'from_local_hold_group', hold_fulfillment_policy => 'any', - returnbranch => 'any' + returnbranch => 'any' } } ); @@ -1263,28 +1407,41 @@ subtest 'CanItemBeReserved / pickup_not_in_hold_group' => sub { my $itemtype2 = $builder->build_object( { class => 'Koha::ItemTypes' } ); # Create libraries - my $library1 = $builder->build_object( { class => 'Koha::Libraries', value => {pickup_location => 1} } ); - my $library2 = $builder->build_object( { class => 'Koha::Libraries', value => {pickup_location => 1} } ); - my $library3 = $builder->build_object( { class => 'Koha::Libraries', value => {pickup_location => 1} } ); + my $library1 = $builder->build_object( { class => 'Koha::Libraries', value => { pickup_location => 1 } } ); + my $library2 = $builder->build_object( { class => 'Koha::Libraries', value => { pickup_location => 1 } } ); + my $library3 = $builder->build_object( { class => 'Koha::Libraries', value => { pickup_location => 1 } } ); # Create library groups hierarchy - my $rootgroup = $builder->build_object( { class => 'Koha::Library::Groups', value => {ft_local_hold_group => 1} } ); - my $group1 = $builder->build_object( { class => 'Koha::Library::Groups', value => {parent_id => $rootgroup->id, branchcode => $library1->branchcode}} ); - my $group2 = $builder->build_object( { class => 'Koha::Library::Groups', value => {parent_id => $rootgroup->id, branchcode => $library2->branchcode} } ); + my $rootgroup = + $builder->build_object( { class => 'Koha::Library::Groups', value => { ft_local_hold_group => 1 } } ); + my $group1 = $builder->build_object( + { + class => 'Koha::Library::Groups', + value => { parent_id => $rootgroup->id, branchcode => $library1->branchcode } + } + ); + my $group2 = $builder->build_object( + { + class => 'Koha::Library::Groups', + value => { parent_id => $rootgroup->id, branchcode => $library2->branchcode } + } + ); # Create 2 patrons - my $patron1 = $builder->build_object( { class => 'Koha::Patrons', value => {branchcode => $library1->branchcode} } ); - my $patron3 = $builder->build_object( { class => 'Koha::Patrons', value => {branchcode => $library3->branchcode} } ); + my $patron1 = + $builder->build_object( { class => 'Koha::Patrons', value => { branchcode => $library1->branchcode } } ); + my $patron3 = + $builder->build_object( { class => 'Koha::Patrons', value => { branchcode => $library3->branchcode } } ); # Create 3 biblios with items - my $biblio_1 = $builder->build_sample_biblio({ itemtype => $itemtype1->itemtype }); + my $biblio_1 = $builder->build_sample_biblio( { itemtype => $itemtype1->itemtype } ); my $item_1 = $builder->build_sample_item( { biblionumber => $biblio_1->biblionumber, library => $library1->branchcode } ); - my $biblio_2 = $builder->build_sample_biblio({ itemtype => $itemtype2->itemtype }); + my $biblio_2 = $builder->build_sample_biblio( { itemtype => $itemtype2->itemtype } ); my $item_2 = $builder->build_sample_item( { biblionumber => $biblio_2->biblionumber, @@ -1292,8 +1449,8 @@ subtest 'CanItemBeReserved / pickup_not_in_hold_group' => sub { } ); my $itemnumber_2 = $item_2->itemnumber; - my $biblio_3 = $builder->build_sample_biblio({ itemtype => $itemtype1->itemtype }); - my $item_3 = $builder->build_sample_item( + my $biblio_3 = $builder->build_sample_biblio( { itemtype => $itemtype1->itemtype } ); + my $item_3 = $builder->build_sample_item( { biblionumber => $biblio_3->biblionumber, library => $library1->branchcode @@ -1312,10 +1469,10 @@ subtest 'CanItemBeReserved / pickup_not_in_hold_group' => sub { { branchcode => undef, itemtype => undef, - rules => { - holdallowed => 'from_any_library', + rules => { + holdallowed => 'from_any_library', hold_fulfillment_policy => 'holdgroup', - returnbranch => 'any' + returnbranch => 'any' } } ); @@ -1339,10 +1496,10 @@ subtest 'CanItemBeReserved / pickup_not_in_hold_group' => sub { { branchcode => $library2->branchcode, itemtype => undef, - rules => { - holdallowed => 'from_any_library', + rules => { + holdallowed => 'from_any_library', hold_fulfillment_policy => 'any', - returnbranch => 'any' + returnbranch => 'any' } } ); @@ -1359,10 +1516,10 @@ subtest 'CanItemBeReserved / pickup_not_in_hold_group' => sub { { branchcode => $library2->branchcode, itemtype => undef, - rules => { - holdallowed => 'from_any_library', + rules => { + holdallowed => 'from_any_library', hold_fulfillment_policy => 'holdgroup', - returnbranch => 'any' + returnbranch => 'any' } } ); @@ -1379,10 +1536,10 @@ subtest 'CanItemBeReserved / pickup_not_in_hold_group' => sub { { branchcode => $library2->branchcode, itemtype => $itemtype2->itemtype, - rules => { - holdallowed => 'from_any_library', + rules => { + holdallowed => 'from_any_library', hold_fulfillment_policy => 'any', - returnbranch => 'any' + returnbranch => 'any' } } ); @@ -1399,10 +1556,10 @@ subtest 'CanItemBeReserved / pickup_not_in_hold_group' => sub { { branchcode => $library2->branchcode, itemtype => $itemtype2->itemtype, - rules => { - holdallowed => 'from_any_library', + rules => { + holdallowed => 'from_any_library', hold_fulfillment_policy => 'holdgroup', - returnbranch => 'any' + returnbranch => 'any' } } ); @@ -1419,10 +1576,10 @@ subtest 'CanItemBeReserved / pickup_not_in_hold_group' => sub { { branchcode => $library2->branchcode, itemtype => $itemtype2->itemtype, - rules => { - holdallowed => 'from_any_library', + rules => { + holdallowed => 'from_any_library', hold_fulfillment_policy => 'any', - returnbranch => 'any' + returnbranch => 'any' } } ); @@ -1439,10 +1596,10 @@ subtest 'CanItemBeReserved / pickup_not_in_hold_group' => sub { { branchcode => $library2->branchcode, itemtype => $itemtype2->itemtype, - rules => { - holdallowed => 'from_any_library', + rules => { + holdallowed => 'from_any_library', hold_fulfillment_policy => 'holdgroup', - returnbranch => 'any' + returnbranch => 'any' } } ); @@ -1508,8 +1665,7 @@ subtest 'non priority holds' => sub { } ); - my ( $ok, $err ) = - CanBookBeRenewed( $patron1, $issue ); + my ( $ok, $err ) = CanBookBeRenewed( $patron1, $issue ); ok( !$ok, 'Cannot renew' ); is( $err, 'on_reserve', 'Item is on hold' ); @@ -1517,8 +1673,7 @@ subtest 'non priority holds' => sub { my $hold = Koha::Holds->find($hid); $hold->non_priority(1)->store; - ( $ok, $err ) = - CanBookBeRenewed( $patron1, $issue ); + ( $ok, $err ) = CanBookBeRenewed( $patron1, $issue ); ok( $ok, 'Can renew' ); is( $err, undef, 'Item is on non priority hold' ); @@ -1541,8 +1696,7 @@ subtest 'non priority holds' => sub { } ); - ( $ok, $err ) = - CanBookBeRenewed( $patron1, $issue ); + ( $ok, $err ) = CanBookBeRenewed( $patron1, $issue ); ok( !$ok, 'Cannot renew' ); is( $err, 'on_reserve', 'Item is on hold' ); @@ -1556,24 +1710,30 @@ subtest 'CanItemBeReserved / recall' => sub { $schema->storage->txn_begin; my $itemtype1 = $builder->build_object( { class => 'Koha::ItemTypes' } ); - my $library1 = $builder->build_object( { class => 'Koha::Libraries', value => {pickup_location => 1} } ); - my $patron1 = $builder->build_object( { class => 'Koha::Patrons', value => {branchcode => $library1->branchcode} } ); - my $biblio1 = $builder->build_sample_biblio({ itemtype => $itemtype1->itemtype }); + my $library1 = $builder->build_object( { class => 'Koha::Libraries', value => { pickup_location => 1 } } ); + my $patron1 = + $builder->build_object( { class => 'Koha::Patrons', value => { branchcode => $library1->branchcode } } ); + my $biblio1 = $builder->build_sample_biblio( { itemtype => $itemtype1->itemtype } ); my $item1 = $builder->build_sample_item( { biblionumber => $biblio1->biblionumber, library => $library1->branchcode } ); - Koha::Recall->new({ - patron_id => $patron1->borrowernumber, - biblio_id => $biblio1->biblionumber, - pickup_library_id => $library1->branchcode, - item_id => $item1->itemnumber, - created_date => '2020-05-04 10:10:10', - item_level => 1, - })->store; - is( CanItemBeReserved( $patron1, $item1, $library1->branchcode )->{status}, 'recall', "Can't reserve an item that they have already recalled" ); + Koha::Recall->new( + { + patron_id => $patron1->borrowernumber, + biblio_id => $biblio1->biblionumber, + pickup_library_id => $library1->branchcode, + item_id => $item1->itemnumber, + created_date => '2020-05-04 10:10:10', + item_level => 1, + } + )->store; + is( + CanItemBeReserved( $patron1, $item1, $library1->branchcode )->{status}, 'recall', + "Can't reserve an item that they have already recalled" + ); $schema->storage->txn_rollback; }; @@ -1582,30 +1742,38 @@ subtest 'CanItemBeReserved rule precedence tests' => sub { plan tests => 3; - t::lib::Mocks::mock_preference('ReservesControlBranch', 'ItemHomeLibrary'); + t::lib::Mocks::mock_preference( 'ReservesControlBranch', 'ItemHomeLibrary' ); $schema->storage->txn_begin; - my $library = $builder->build_object( { class => 'Koha::Libraries', value => { - pickup_location => 1, - }}); - my $item = $builder->build_sample_item({ - homebranch => $library->branchcode, - holdingbranch => $library->branchcode - }); - my $item2 = $builder->build_sample_item({ - homebranch => $library->branchcode, - holdingbranch => $library->branchcode, - itype => $item->itype - }); - my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { - branchcode => $library->branchcode - }}); + my $library = $builder->build_object( + { + class => 'Koha::Libraries', + value => { + pickup_location => 1, + } + } + ); + my $item = $builder->build_sample_item( + { + homebranch => $library->branchcode, + holdingbranch => $library->branchcode + } + ); + my $item2 = $builder->build_sample_item( + { + homebranch => $library->branchcode, + holdingbranch => $library->branchcode, + itype => $item->itype + } + ); + my $patron = + $builder->build_object( { class => 'Koha::Patrons', value => { branchcode => $library->branchcode } } ); Koha::CirculationRules->set_rules( { branchcode => undef, categorycode => $patron->categorycode, itemtype => $item->itype, rules => { - reservesallowed => 1, + reservesallowed => 1, } } ); @@ -1614,14 +1782,19 @@ subtest 'CanItemBeReserved rule precedence tests' => sub { { status => 'OK' }, 'Patron of specified category can place 1 hold on specified itemtype' ); - my $hold = $builder->build_object({ class => 'Koha::Holds', value => { - biblionumber => $item2->biblionumber, - itemnumber => $item2->itemnumber, - found => undef, - priority => 1, - branchcode => $library->branchcode, - borrowernumber => $patron->borrowernumber, - }}); + my $hold = $builder->build_object( + { + class => 'Koha::Holds', + value => { + biblionumber => $item2->biblionumber, + itemnumber => $item2->itemnumber, + found => undef, + priority => 1, + branchcode => $library->branchcode, + borrowernumber => $patron->borrowernumber, + } + } + ); is_deeply( CanItemBeReserved( $patron, $item, $library->branchcode ), { status => 'tooManyReserves', limit => 1 }, @@ -1633,7 +1806,7 @@ subtest 'CanItemBeReserved rule precedence tests' => sub { categorycode => undef, itemtype => undef, rules => { - reservesallowed => 2, + reservesallowed => 2, } } ); @@ -1652,12 +1825,11 @@ subtest 'ModReserve can only update expirationdate for found holds' => sub { $schema->storage->txn_begin; - my $category = $builder->build({ source => 'Category' }); - my $branch = $builder->build({ source => 'Branch' })->{ branchcode }; - my $biblio = $builder->build_sample_biblio( { itemtype => 'DUMMY' } ); - my $itemnumber = $builder->build_sample_item( - { library => $branch, biblionumber => $biblio->biblionumber } ) - ->itemnumber; + my $category = $builder->build( { source => 'Category' } ); + my $branch = $builder->build( { source => 'Branch' } )->{branchcode}; + my $biblio = $builder->build_sample_biblio( { itemtype => 'DUMMY' } ); + my $itemnumber = + $builder->build_sample_item( { library => $branch, biblionumber => $biblio->biblionumber } )->itemnumber; my $borrowernumber = Koha::Patron->new( { @@ -1673,9 +1845,8 @@ subtest 'ModReserve can only update expirationdate for found holds' => sub { branchcode => $branch, borrowernumber => $borrowernumber, biblionumber => $biblio->biblionumber, - priority => - C4::Reserves::CalculatePriority( $biblio->biblionumber ), - itemnumber => $itemnumber, + priority => C4::Reserves::CalculatePriority( $biblio->biblionumber ), + itemnumber => $itemnumber, } ); @@ -1694,8 +1865,10 @@ subtest 'ModReserve can only update expirationdate for found holds' => sub { $hold = Koha::Holds->find($reserve_id); - is( $hold->expirationdate, '1981-06-10', - 'Found hold expiration date updated correctly' ); + is( + $hold->expirationdate, '1981-06-10', + 'Found hold expiration date updated correctly' + ); is( $hold->priority, '0', 'Found hold priority was not updated' ); $schema->storage->txn_rollback; @@ -1709,26 +1882,37 @@ subtest 'Koha::Holds->get_items_that_can_fill returns items with datecancelled o # biblio item with date arrived and date cancelled my $biblio1 = $builder->build_sample_biblio(); - my $item1 = $builder->build_sample_item({ biblionumber => $biblio1->biblionumber }); + my $item1 = $builder->build_sample_item( { biblionumber => $biblio1->biblionumber } ); - my $transfer1 = $builder->build_object({ class => "Koha::Item::Transfers", value => { - datecancelled => '2022-06-12', - itemnumber => $item1->itemnumber - }}); + my $transfer1 = $builder->build_object( + { + class => "Koha::Item::Transfers", + value => { + datecancelled => '2022-06-12', + itemnumber => $item1->itemnumber + } + } + ); - my $hold1 = $builder->build_object({ class => 'Koha::Holds', value => { - biblionumber => $biblio1->biblionumber, - itemnumber => undef, - itemtype => undef, - found => undef - }}); + my $hold1 = $builder->build_object( + { + class => 'Koha::Holds', + value => { + biblionumber => $biblio1->biblionumber, + itemnumber => undef, + itemtype => undef, + found => undef + } + } + ); # biblio item with date arrived and NO date cancelled my $biblio2 = $builder->build_sample_biblio(); - my $item2 = $builder->build_sample_item({ biblionumber => $biblio2->biblionumber }); + my $item2 = $builder->build_sample_item( { biblionumber => $biblio2->biblionumber } ); my $transfer2 = $builder->build_object( - { class => "Koha::Item::Transfers", + { + class => "Koha::Item::Transfers", value => { datearrived => dt_from_string, datecancelled => undef, @@ -1737,67 +1921,112 @@ subtest 'Koha::Holds->get_items_that_can_fill returns items with datecancelled o } ); - my $hold2 = $builder->build_object({ class => 'Koha::Holds', value => { - biblionumber => $biblio2->biblionumber, - itemnumber => undef, - itemtype => undef, - found => undef - }}); + my $hold2 = $builder->build_object( + { + class => 'Koha::Holds', + value => { + biblionumber => $biblio2->biblionumber, + itemnumber => undef, + itemtype => undef, + found => undef + } + } + ); # biblio item with NO date arrived and date cancelled my $biblio3 = $builder->build_sample_biblio(); - my $item3 = $builder->build_sample_item({ biblionumber => $biblio3->biblionumber }); + my $item3 = $builder->build_sample_item( { biblionumber => $biblio3->biblionumber } ); - my $transfer3 = $builder->build_object({ class => "Koha::Item::Transfers", value => { - datecancelled => '2022-06-12', - itemnumber => $item3->itemnumber, - datearrived => undef - }}); - - my $hold3 = $builder->build_object({ class => 'Koha::Holds', value => { - biblionumber => $biblio3->biblionumber, - itemnumber => undef, - itemtype => undef, - found => undef - }}); + my $transfer3 = $builder->build_object( + { + class => "Koha::Item::Transfers", + value => { + datecancelled => '2022-06-12', + itemnumber => $item3->itemnumber, + datearrived => undef + } + } + ); + my $hold3 = $builder->build_object( + { + class => 'Koha::Holds', + value => { + biblionumber => $biblio3->biblionumber, + itemnumber => undef, + itemtype => undef, + found => undef + } + } + ); # biblio item with NO date arrived and NO date cancelled my $biblio4 = $builder->build_sample_biblio(); - my $item4 = $builder->build_sample_item({ biblionumber => $biblio4->biblionumber }); + my $item4 = $builder->build_sample_item( { biblionumber => $biblio4->biblionumber } ); - my $transfer4 = $builder->build_object({ class => "Koha::Item::Transfers", value => { - datecancelled => undef, - itemnumber => $item4->itemnumber, - datearrived => undef - }}); + my $transfer4 = $builder->build_object( + { + class => "Koha::Item::Transfers", + value => { + datecancelled => undef, + itemnumber => $item4->itemnumber, + datearrived => undef + } + } + ); - my $hold4 = $builder->build_object({ class => 'Koha::Holds', value => { - biblionumber => $biblio4->biblionumber, - itemnumber => undef, - itemtype => undef, - found => undef - }}); + my $hold4 = $builder->build_object( + { + class => 'Koha::Holds', + value => { + biblionumber => $biblio4->biblionumber, + itemnumber => undef, + itemtype => undef, + found => undef + } + } + ); # create the holds which get_items_that_can_fill will be ran on - my $holds1 = Koha::Holds->search({reserve_id => $hold1->id}); - my $holds2 = Koha::Holds->search({reserve_id => $hold2->id}); - my $holds3 = Koha::Holds->search({reserve_id => $hold3->id}); - my $holds4 = Koha::Holds->search({reserve_id => $hold4->id}); + my $holds1 = Koha::Holds->search( { reserve_id => $hold1->id } ); + my $holds2 = Koha::Holds->search( { reserve_id => $hold2->id } ); + my $holds3 = Koha::Holds->search( { reserve_id => $hold3->id } ); + my $holds4 = Koha::Holds->search( { reserve_id => $hold4->id } ); my $items_that_can_fill1 = $holds1->get_items_that_can_fill; my $items_that_can_fill2 = $holds2->get_items_that_can_fill; my $items_that_can_fill3 = $holds3->get_items_that_can_fill; my $items_that_can_fill4 = $holds4->get_items_that_can_fill; - is($items_that_can_fill1->next->id, $item1->id, "Koha::Holds->get_items_that_can_fill returns item with defined datearrived and datecancelled"); - is($items_that_can_fill1->count, 1, "Koha::Holds->get_items_that_can_fill returns 1 item with correct parameters"); - is($items_that_can_fill2->next->id, $item2->id, "Koha::Holds->get_items_that_can_fill returns item with defined datearrived and undefined datecancelled"); - is($items_that_can_fill2->count, 1, "Koha::Holds->get_items_that_can_fill returns 1 item with correct parameters"); - is($items_that_can_fill3->next->id, $item3->id, "Koha::Holds->get_items_that_can_fill returns item with undefined datearrived and defined datecancelled"); - is($items_that_can_fill3->count, 1, "Koha::Holds->get_items_that_can_fill returns 1 item with correct parameters"); - is($items_that_can_fill4->next, undef, "Koha::Holds->get_items_that_can_fill doesn't return item with undefined datearrived and undefined datecancelled"); - is($items_that_can_fill4->count, 0, "Koha::Holds->get_items_that_can_fill returns 0 item"); + is( + $items_that_can_fill1->next->id, $item1->id, + "Koha::Holds->get_items_that_can_fill returns item with defined datearrived and datecancelled" + ); + is( + $items_that_can_fill1->count, 1, + "Koha::Holds->get_items_that_can_fill returns 1 item with correct parameters" + ); + is( + $items_that_can_fill2->next->id, $item2->id, + "Koha::Holds->get_items_that_can_fill returns item with defined datearrived and undefined datecancelled" + ); + is( + $items_that_can_fill2->count, 1, + "Koha::Holds->get_items_that_can_fill returns 1 item with correct parameters" + ); + is( + $items_that_can_fill3->next->id, $item3->id, + "Koha::Holds->get_items_that_can_fill returns item with undefined datearrived and defined datecancelled" + ); + is( + $items_that_can_fill3->count, 1, + "Koha::Holds->get_items_that_can_fill returns 1 item with correct parameters" + ); + is( + $items_that_can_fill4->next, undef, + "Koha::Holds->get_items_that_can_fill doesn't return item with undefined datearrived and undefined datecancelled" + ); + is( $items_that_can_fill4->count, 0, "Koha::Holds->get_items_that_can_fill returns 0 item" ); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/Holds/ExpireReservesAutoFill.t b/t/db_dependent/Holds/ExpireReservesAutoFill.t index 31d595a421..1a7f43491a 100755 --- a/t/db_dependent/Holds/ExpireReservesAutoFill.t +++ b/t/db_dependent/Holds/ExpireReservesAutoFill.t @@ -29,30 +29,33 @@ my $builder = t::lib::TestBuilder->new(); my $dbh = C4::Context->dbh; # Create two random branches -my $branch_1 = $builder->build_object({ - class => 'Koha::Libraries', - value => { - branchemail => 'branch1@e.mail', - branchreplyto => 'branch1@reply.to' +my $branch_1 = $builder->build_object( + { + class => 'Koha::Libraries', + value => { + branchemail => 'branch1@e.mail', + branchreplyto => 'branch1@reply.to' + } } -}); +); my $library_1 = $branch_1->branchcode; -my $branch_2 = $builder->build_object({ - class => 'Koha::Libraries', - value => { - branchemail => 'branch2@e.mail', - branchreplyto => 'branch2@reply.to' +my $branch_2 = $builder->build_object( + { + class => 'Koha::Libraries', + value => { + branchemail => 'branch2@e.mail', + branchreplyto => 'branch2@reply.to' + } } -}); +); my $library_2 = $branch_2->branchcode; - subtest 'Test automatically canceled expired waiting holds to fill the next hold, without a transfer' => sub { plan tests => 12; - my $item = $builder->build_sample_item({ library => $library_1 }); + my $item = $builder->build_sample_item( { library => $library_1 } ); my $biblionumber = $item->biblionumber; - my $itemnumber = $item->itemnumber; + my $itemnumber = $item->itemnumber; my $patron_1 = $builder->build( { source => 'Borrower' } ); my $patron_2 = $builder->build( { source => 'Borrower' } ); @@ -106,10 +109,12 @@ subtest 'Test automatically canceled expired waiting holds to fill the next hold t::lib::Mocks::mock_preference( 'ReservesMaxPickUpDelay', 1 ); t::lib::Mocks::mock_preference( 'ExpireReservesOnHolidays', 1 ); t::lib::Mocks::mock_preference( 'ExpireReservesAutoFill', 1 ); - t::lib::Mocks::mock_preference( 'ExpireReservesAutoFillEmail', - 'kyle@example.com' ); + t::lib::Mocks::mock_preference( + 'ExpireReservesAutoFillEmail', + 'kyle@example.com' + ); - $hold_1->cancel({ autofill => 1 }); + $hold_1->cancel( { autofill => 1 } ); my $holds = Koha::Holds->search( { biblionumber => $biblionumber }, { order_by => 'priority' } ); $hold_2 = $holds->next; @@ -119,40 +124,44 @@ subtest 'Test automatically canceled expired waiting holds to fill the next hold is( $hold_2->priority, 0, 'Next hold in line now has priority of 0' ); is( $hold_2->found, 'W', 'Next hold in line is now set to waiting' ); - my $messages = Koha::Notice::Messages->search({ - letter_code => 'HOLD_CHANGED', - borrowernumber => $patron_2->{borrowernumber} - } ); + my $messages = Koha::Notice::Messages->search( + { + letter_code => 'HOLD_CHANGED', + borrowernumber => $patron_2->{borrowernumber} + } + ); is( $messages->count, 1, 'Found message in the message queue with borrower 2 as the object' ); my $message = $messages->next; - is( $message->to_address, 'kyle@example.com', 'Message sent to correct email address' ); - is( $message->from_address, $branch_1->branchemail, "Message is sent from library's email"); + is( $message->to_address, 'kyle@example.com', 'Message sent to correct email address' ); + is( $message->from_address, $branch_1->branchemail, "Message is sent from library's email" ); - $hold_2->cancel({ autofill => 1 }); + $hold_2->cancel( { autofill => 1 } ); - $holds = Koha::Holds->search( { biblionumber => $biblionumber }, { order_by => 'priority' } ); + $holds = Koha::Holds->search( { biblionumber => $biblionumber }, { order_by => 'priority' } ); $hold_3 = $holds->next; is( $holds->count, 1, 'Found 1 hold' ); is( $hold_3->priority, 0, 'Next hold in line now has priority of 0' ); is( $hold_3->found, 'W', 'Next hold in line is now set to waiting' ); - $messages = Koha::Notice::Messages->search({ - letter_code => 'HOLD_CHANGED', - borrowernumber => $patron_3->{borrowernumber} - }); + $messages = Koha::Notice::Messages->search( + { + letter_code => 'HOLD_CHANGED', + borrowernumber => $patron_3->{borrowernumber} + } + ); is( $messages->count, 1, 'Found message with borrower 3 as the object' ); $message = $messages->next; - is( $message->to_address, 'kyle@example.com', 'Message sent to correct email address' ); - is( $message->from_address, $branch_1->branchemail, "Message is sent from library's email"); + is( $message->to_address, 'kyle@example.com', 'Message sent to correct email address' ); + is( $message->from_address, $branch_1->branchemail, "Message is sent from library's email" ); }; subtest 'Test automatically canceled expired waiting holds to fill the next hold, with a transfer' => sub { plan tests => 7; - my $item = $builder->build_sample_item({ library => $library_1 }); + my $item = $builder->build_sample_item( { library => $library_1 } ); my $biblionumber = $item->biblionumber; - my $itemnumber = $item->itemnumber; + my $itemnumber = $item->itemnumber; my $patron_1 = $builder->build( { source => 'Borrower' } ); my $patron_2 = $builder->build( { source => 'Borrower' } ); @@ -193,28 +202,34 @@ subtest 'Test automatically canceled expired waiting holds to fill the next hold t::lib::Mocks::mock_preference( 'ReservesMaxPickUpDelay', 1 ); t::lib::Mocks::mock_preference( 'ExpireReservesOnHolidays', 1 ); t::lib::Mocks::mock_preference( 'ExpireReservesAutoFill', 1 ); - t::lib::Mocks::mock_preference( 'ExpireReservesAutoFillEmail', '' ); + t::lib::Mocks::mock_preference( 'ExpireReservesAutoFillEmail', '' ); - $hold_1->cancel({ autofill => 1 }); + $hold_1->cancel( { autofill => 1 } ); my @holds = Koha::Holds->search( { biblionumber => $biblionumber }, { order_by => 'priority' } )->as_list; $hold_2 = $holds[0]; - is( @holds, 1, 'Found 1 hold' ); - is( $hold_2->priority, 0, 'Next hold in line now has priority of 0' ); - is( $hold_2->found, 'T', 'Next hold in line is now set to in transit' ); + is( @holds, 1, 'Found 1 hold' ); + is( $hold_2->priority, 0, 'Next hold in line now has priority of 0' ); + is( $hold_2->found, 'T', 'Next hold in line is now set to in transit' ); is( $hold_2->branchcode, $library_2, "Next hold in line has correct branchcode" ); - my $messages = Koha::Notice::Messages->search({ - letter_code => 'HOLD_CHANGED', - borrowernumber => $patron_2->{borrowernumber} - }); + my $messages = Koha::Notice::Messages->search( + { + letter_code => 'HOLD_CHANGED', + borrowernumber => $patron_2->{borrowernumber} + } + ); is( $messages->count, 1, 'Message is generated in the message queue when generating transfer' ); my $message = $messages->next; + # Is the below correct? Email of changed hold is sent to the receiving library # how does the sending library know to remove book from the holds shelf? - is( $message->to_address, $branch_2->branchreplyto, "Message is sent to the incoming email of the library with the next hold"); - is( $message->from_address, $branch_2->branchemail, "Message is sent from library's email"); + is( + $message->to_address, $branch_2->branchreplyto, + "Message is sent to the incoming email of the library with the next hold" + ); + is( $message->from_address, $branch_2->branchemail, "Message is sent from library's email" ); }; $schema->storage->txn_rollback; diff --git a/t/db_dependent/Holds/HoldFulfillmentPolicy.t b/t/db_dependent/Holds/HoldFulfillmentPolicy.t index 5fadfb0cfe..bc6ef88148 100755 --- a/t/db_dependent/Holds/HoldFulfillmentPolicy.t +++ b/t/db_dependent/Holds/HoldFulfillmentPolicy.t @@ -12,7 +12,7 @@ use t::lib::Mocks; use Koha::Holds; BEGIN { - use_ok('C4::Reserves', qw( AddReserve CheckReserves )); + use_ok( 'C4::Reserves', qw( AddReserve CheckReserves ) ); } my $schema = Koha::Database->schema; @@ -21,61 +21,71 @@ my $dbh = C4::Context->dbh; my $builder = t::lib::TestBuilder->new; -my $library1 = $builder->build({ - source => 'Branch', -}); -my $library2 = $builder->build({ - source => 'Branch', -}); -my $library3 = $builder->build({ - source => 'Branch', -}); +my $library1 = $builder->build( + { + source => 'Branch', + } +); +my $library2 = $builder->build( + { + source => 'Branch', + } +); +my $library3 = $builder->build( + { + source => 'Branch', + } +); my $itemtype = $builder->build_sample_item->itype; my $bib_title = "Test Title"; -my $borrower = $builder->build({ - source => 'Borrower', - value => { - branchcode => $library1->{branchcode}, +my $borrower = $builder->build( + { + source => 'Borrower', + value => { + branchcode => $library1->{branchcode}, + } } -}); +); # Test hold_fulfillment_policy my $borrowernumber = $borrower->{borrowernumber}; -my $library_A = $library1->{branchcode}; -my $library_B = $library2->{branchcode}; -my $library_C = $library3->{branchcode}; +my $library_A = $library1->{branchcode}; +my $library_B = $library2->{branchcode}; +my $library_C = $library3->{branchcode}; $dbh->do("DELETE FROM transport_cost"); $dbh->do("DELETE FROM tmp_holdsqueue"); $dbh->do("DELETE FROM hold_fill_targets"); $dbh->do("DELETE FROM circulation_rules"); -$dbh->do("INSERT INTO biblio (frameworkcode, author, title, datecreated) VALUES ('', 'Koha test', '$bib_title', '2011-02-01')"); +$dbh->do( + "INSERT INTO biblio (frameworkcode, author, title, datecreated) VALUES ('', 'Koha test', '$bib_title', '2011-02-01')" +); my $biblionumber = $dbh->selectrow_array("SELECT biblionumber FROM biblio WHERE title = '$bib_title'") - or BAIL_OUT("Cannot find newly created biblio record"); + or BAIL_OUT("Cannot find newly created biblio record"); $dbh->do("INSERT INTO biblioitems (biblionumber, itemtype) VALUES ($biblionumber, '$itemtype')"); my $biblioitemnumber = - $dbh->selectrow_array("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = $biblionumber") - or BAIL_OUT("Cannot find newly created biblioitems record"); + $dbh->selectrow_array("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = $biblionumber") + or BAIL_OUT("Cannot find newly created biblioitems record"); -$dbh->do(" +$dbh->do( " INSERT INTO items (biblionumber, biblioitemnumber, homebranch, holdingbranch, notforloan, damaged, itemlost, withdrawn, onloan, itype) VALUES ($biblionumber, $biblioitemnumber, '$library_A', '$library_B', 0, 0, 0, 0, NULL, '$itemtype') -"); +" ); -my $item = Koha::Items->find({ biblionumber => $biblionumber }); +my $item = Koha::Items->find( { biblionumber => $biblionumber } ); # With hold_fulfillment_policy = homebranch, hold should only be picked up if pickup branch = homebranch $dbh->do("DELETE FROM circulation_rules"); Koha::CirculationRules->set_rules( { - branchcode => undef, - itemtype => undef, - rules => { + branchcode => undef, + itemtype => undef, + rules => { holdallowed => 'from_any_library', hold_fulfillment_policy => 'homebranch', } @@ -91,9 +101,9 @@ my $reserve_id = AddReserve( priority => 1, } ); -my ( $status ) = CheckReserves($item); +my ($status) = CheckReserves($item); is( $status, 'Reserved', "Hold where pickup branch matches home branch targeted" ); -Koha::Holds->find( $reserve_id )->cancel; +Koha::Holds->find($reserve_id)->cancel; # Holding branch matches pickup branch $reserve_id = AddReserve( @@ -104,9 +114,9 @@ $reserve_id = AddReserve( priority => 1, } ); -( $status ) = CheckReserves($item); -is($status, q{}, "Hold where pickup ne home, pickup eq home not targeted" ); -Koha::Holds->find( $reserve_id )->cancel; +($status) = CheckReserves($item); +is( $status, q{}, "Hold where pickup ne home, pickup eq home not targeted" ); +Koha::Holds->find($reserve_id)->cancel; # Neither branch matches pickup branch $reserve_id = AddReserve( @@ -117,17 +127,17 @@ $reserve_id = AddReserve( priority => 1, } ); -( $status ) = CheckReserves($item); +($status) = CheckReserves($item); is( $status, q{}, "Hold where pickup ne home, pickup ne holding not targeted" ); -Koha::Holds->find( $reserve_id )->cancel; +Koha::Holds->find($reserve_id)->cancel; # With hold_fulfillment_policy = holdingbranch, hold should only be picked up if pickup branch = holdingbranch $dbh->do("DELETE FROM circulation_rules"); Koha::CirculationRules->set_rules( { - branchcode => undef, - itemtype => undef, - rules => { + branchcode => undef, + itemtype => undef, + rules => { holdallowed => 'from_any_library', hold_fulfillment_policy => 'holdingbranch', } @@ -143,9 +153,9 @@ $reserve_id = AddReserve( priority => 1, } ); -( $status ) = CheckReserves($item); +($status) = CheckReserves($item); is( $status, q{}, "Hold where pickup eq home, pickup ne holding not targeted" ); -Koha::Holds->find( $reserve_id )->cancel; +Koha::Holds->find($reserve_id)->cancel; # Holding branch matches pickup branch $reserve_id = AddReserve( @@ -156,9 +166,9 @@ $reserve_id = AddReserve( priority => 1, } ); -( $status ) = CheckReserves($item); +($status) = CheckReserves($item); is( $status, 'Reserved', "Hold where pickup ne home, pickup eq holding targeted" ); -Koha::Holds->find( $reserve_id )->cancel; +Koha::Holds->find($reserve_id)->cancel; # Neither branch matches pickup branch $reserve_id = AddReserve( @@ -169,17 +179,17 @@ $reserve_id = AddReserve( priority => 1, } ); -( $status ) = CheckReserves($item); +($status) = CheckReserves($item); is( $status, q{}, "Hold where pickup ne home, pickup ne holding not targeted" ); -Koha::Holds->find( $reserve_id )->cancel; +Koha::Holds->find($reserve_id)->cancel; # With hold_fulfillment_policy = any, hold should be pikcup up reguardless of matching home or holding branch $dbh->do("DELETE FROM circulation_rules"); Koha::CirculationRules->set_rules( { - branchcode => undef, - itemtype => undef, - rules => { + branchcode => undef, + itemtype => undef, + rules => { holdallowed => 'from_any_library', hold_fulfillment_policy => 'any', } @@ -195,9 +205,9 @@ $reserve_id = AddReserve( priority => 1, } ); -( $status ) = CheckReserves($item); +($status) = CheckReserves($item); is( $status, 'Reserved', "Hold where pickup eq home, pickup ne holding targeted" ); -Koha::Holds->find( $reserve_id )->cancel; +Koha::Holds->find($reserve_id)->cancel; # Holding branch matches pickup branch $reserve_id = AddReserve( @@ -208,9 +218,9 @@ $reserve_id = AddReserve( priority => 1, } ); -( $status ) = CheckReserves($item); +($status) = CheckReserves($item); is( $status, 'Reserved', "Hold where pickup ne home, pickup eq holding targeted" ); -Koha::Holds->find( $reserve_id )->cancel; +Koha::Holds->find($reserve_id)->cancel; # Neither branch matches pickup branch $reserve_id = AddReserve( @@ -221,9 +231,9 @@ $reserve_id = AddReserve( priority => 1, } ); -( $status ) = CheckReserves($item); +($status) = CheckReserves($item); is( $status, 'Reserved', "Hold where pickup ne home, pickup ne holding targeted" ); -Koha::Holds->find( $reserve_id )->cancel; +Koha::Holds->find($reserve_id)->cancel; # Test enforement of branch transfer limits t::lib::Mocks::mock_preference( 'UseBranchTransferLimits', '1' ); @@ -245,5 +255,5 @@ $reserve_id = AddReserve( } ); ($status) = CheckReserves($item); -is( $status, '', "No hold where branch transfer is not allowed" ); +is( $status, '', "No hold where branch transfer is not allowed" ); Koha::Holds->find($reserve_id)->cancel; diff --git a/t/db_dependent/Holds/HoldItemtypeLimit.t b/t/db_dependent/Holds/HoldItemtypeLimit.t index 2b5bdc141a..c2337d3b14 100755 --- a/t/db_dependent/Holds/HoldItemtypeLimit.t +++ b/t/db_dependent/Holds/HoldItemtypeLimit.t @@ -14,7 +14,7 @@ use Koha::Holds; BEGIN { use FindBin; use lib $FindBin::Bin; - use_ok('C4::Reserves', qw( AddReserve CheckReserves )); + use_ok( 'C4::Reserves', qw( AddReserve CheckReserves ) ); } my $schema = Koha::Database->schema; @@ -23,40 +23,42 @@ my $dbh = C4::Context->dbh; my $builder = t::lib::TestBuilder->new; -my $library = $builder->build({ - source => 'Branch', -}); +my $library = $builder->build( + { + source => 'Branch', + } +); my $bib_title = "Test Title"; - -my $borrower = $builder->build({ - source => 'Borrower', - value => { - branchcode => $library->{branchcode}, +my $borrower = $builder->build( + { + source => 'Borrower', + value => { + branchcode => $library->{branchcode}, + } } -}); +); -my $itemtype1 = $builder->build({ - source => 'Itemtype', - value => { - notforloan => 0 +my $itemtype1 = $builder->build( + { + source => 'Itemtype', + value => { notforloan => 0 } } -}); +); -my $itemtype2 = $builder->build({ - source => 'Itemtype', - value => { - notforloan => 0 +my $itemtype2 = $builder->build( + { + source => 'Itemtype', + value => { notforloan => 0 } } -}); - +); # Test hold_fulfillment_policy my $right_itemtype = $itemtype1->{itemtype}; my $wrong_itemtype = $itemtype2->{itemtype}; my $borrowernumber = $borrower->{borrowernumber}; -my $branchcode = $library->{branchcode}; +my $branchcode = $library->{branchcode}; $dbh->do("DELETE FROM reserves"); $dbh->do("DELETE FROM issues"); $dbh->do("DELETE FROM items"); @@ -66,30 +68,32 @@ $dbh->do("DELETE FROM transport_cost"); $dbh->do("DELETE FROM tmp_holdsqueue"); $dbh->do("DELETE FROM hold_fill_targets"); -$dbh->do("INSERT INTO biblio (frameworkcode, author, title, datecreated) VALUES ('', 'Koha test', '$bib_title', '2011-02-01')"); +$dbh->do( + "INSERT INTO biblio (frameworkcode, author, title, datecreated) VALUES ('', 'Koha test', '$bib_title', '2011-02-01')" +); my $biblionumber = $dbh->selectrow_array("SELECT biblionumber FROM biblio WHERE title = '$bib_title'") - or BAIL_OUT("Cannot find newly created biblio record"); + or BAIL_OUT("Cannot find newly created biblio record"); $dbh->do("INSERT INTO biblioitems (biblionumber, itemtype) VALUES ($biblionumber, '$right_itemtype')"); my $biblioitemnumber = - $dbh->selectrow_array("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = $biblionumber") - or BAIL_OUT("Cannot find newly created biblioitems record"); + $dbh->selectrow_array("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = $biblionumber") + or BAIL_OUT("Cannot find newly created biblioitems record"); -$dbh->do(" +$dbh->do( " INSERT INTO items (biblionumber, biblioitemnumber, homebranch, holdingbranch, notforloan, damaged, itemlost, withdrawn, onloan, itype) VALUES ($biblionumber, $biblioitemnumber, '$branchcode', '$branchcode', 0, 0, 0, 0, NULL, '$right_itemtype') -"); +" ); -my $item = Koha::Items->find({ biblionumber => $biblionumber }); +my $item = Koha::Items->find( { biblionumber => $biblionumber } ); $dbh->do("DELETE FROM circulation_rules"); Koha::CirculationRules->set_rules( { - itemtype => undef, - branchcode => undef, - rules => { + itemtype => undef, + branchcode => undef, + rules => { holdallowed => 2, hold_fulfillment_policy => 'any', } @@ -106,9 +110,9 @@ my $reserve_id = AddReserve( itemtype => $right_itemtype, } ); -my ( $status ) = CheckReserves($item); +my ($status) = CheckReserves($item); is( $status, 'Reserved', "Hold where itemtype matches item's itemtype targed" ); -Koha::Holds->find( $reserve_id )->cancel; +Koha::Holds->find($reserve_id)->cancel; # Itemtypes don't match $reserve_id = AddReserve( @@ -121,9 +125,9 @@ $reserve_id = AddReserve( } ); -( $status ) = CheckReserves($item); -is($status, q{}, "Hold where itemtype does not match item's itemtype not targeted" ); -Koha::Holds->find( $reserve_id )->cancel; +($status) = CheckReserves($item); +is( $status, q{}, "Hold where itemtype does not match item's itemtype not targeted" ); +Koha::Holds->find($reserve_id)->cancel; # No itemtype set $reserve_id = AddReserve( @@ -134,9 +138,9 @@ $reserve_id = AddReserve( priority => 1, } ); -( $status ) = CheckReserves($item); +($status) = CheckReserves($item); is( $status, 'Reserved', "Item targeted with no hold itemtype set" ); -Koha::Holds->find( $reserve_id )->cancel; +Koha::Holds->find($reserve_id)->cancel; # Cleanup $schema->storage->txn_rollback; diff --git a/t/db_dependent/Holds/LocalHoldsPriority.t b/t/db_dependent/Holds/LocalHoldsPriority.t index 7638130e20..45677a1e51 100755 --- a/t/db_dependent/Holds/LocalHoldsPriority.t +++ b/t/db_dependent/Holds/LocalHoldsPriority.t @@ -19,7 +19,7 @@ use t::lib::TestBuilder; BEGIN { use FindBin; use lib $FindBin::Bin; - use_ok('C4::Reserves', qw( AddReserve CheckReserves )); + use_ok( 'C4::Reserves', qw( AddReserve CheckReserves ) ); } my $schema = Koha::Database->schema; @@ -27,10 +27,10 @@ $schema->storage->txn_begin; my $builder = t::lib::TestBuilder->new; -my $library1 = $builder->build({ source => 'Branch', }); -my $library2 = $builder->build({ source => 'Branch', }); -my $library3 = $builder->build({ source => 'Branch', }); -my $library4 = $builder->build({ source => 'Branch', }); +my $library1 = $builder->build( { source => 'Branch', } ); +my $library2 = $builder->build( { source => 'Branch', } ); +my $library3 = $builder->build( { source => 'Branch', } ); +my $library4 = $builder->build( { source => 'Branch', } ); my $itemtype = $builder->build( { source => 'Itemtype', @@ -38,32 +38,36 @@ my $itemtype = $builder->build( } )->{itemtype}; - - my $borrowers_count = 5; my $biblio = $builder->build_sample_biblio(); -my $item = Koha::Item->new( +my $item = Koha::Item->new( { - biblionumber => $biblio->biblionumber, - homebranch => $library4->{branchcode}, - holdingbranch => $library3->{branchcode}, - itype => $itemtype, + biblionumber => $biblio->biblionumber, + homebranch => $library4->{branchcode}, + holdingbranch => $library3->{branchcode}, + itype => $itemtype, exclude_from_local_holds_priority => 0, }, )->store->get_from_storage; -my @branchcodes = ( $library1->{branchcode}, $library2->{branchcode}, $library3->{branchcode}, $library4->{branchcode}, $library3->{branchcode}, $library4->{branchcode} ); -my $patron_category = $builder->build({ source => 'Category', value => {exclude_from_local_holds_priority => 0} }); +my @branchcodes = ( + $library1->{branchcode}, $library2->{branchcode}, $library3->{branchcode}, $library4->{branchcode}, + $library3->{branchcode}, $library4->{branchcode} +); +my $patron_category = $builder->build( { source => 'Category', value => { exclude_from_local_holds_priority => 0 } } ); + # Create some borrowers my @borrowernumbers; -foreach ( 0 .. $borrowers_count-1 ) { - my $borrowernumber = Koha::Patron->new({ - firstname => 'my firstname', - surname => 'my surname ' . $_, - categorycode => $patron_category->{categorycode}, - branchcode => $branchcodes[$_], - })->store->borrowernumber; +foreach ( 0 .. $borrowers_count - 1 ) { + my $borrowernumber = Koha::Patron->new( + { + firstname => 'my firstname', + surname => 'my surname ' . $_, + categorycode => $patron_category->{categorycode}, + branchcode => $branchcodes[$_], + } + )->store->borrowernumber; push @borrowernumbers, $borrowernumber; } @@ -82,32 +86,32 @@ foreach my $borrowernumber (@borrowernumbers) { $i++; } -my ($status, $reserve, $all_reserves); +my ( $status, $reserve, $all_reserves ); t::lib::Mocks::mock_preference( 'LocalHoldsPriority', 0 ); -($status, $reserve, $all_reserves) = CheckReserves($item); +( $status, $reserve, $all_reserves ) = CheckReserves($item); ok( $reserve->{borrowernumber} eq $borrowernumbers[0], "Received expected results with LocalHoldsPriority disabled" ); t::lib::Mocks::mock_preference( 'LocalHoldsPriority', 1 ); t::lib::Mocks::mock_preference( 'LocalHoldsPriorityPatronControl', 'PickupLibrary' ); -t::lib::Mocks::mock_preference( 'LocalHoldsPriorityItemControl', 'homebranch' ); -($status, $reserve, $all_reserves) = CheckReserves($item); +t::lib::Mocks::mock_preference( 'LocalHoldsPriorityItemControl', 'homebranch' ); +( $status, $reserve, $all_reserves ) = CheckReserves($item); ok( $reserve->{borrowernumber} eq $borrowernumbers[2], "Received expected results with PickupLibrary/homebranch" ); t::lib::Mocks::mock_preference( 'LocalHoldsPriorityPatronControl', 'PickupLibrary' ); -t::lib::Mocks::mock_preference( 'LocalHoldsPriorityItemControl', 'holdingbranch' ); -($status, $reserve, $all_reserves) = CheckReserves($item); +t::lib::Mocks::mock_preference( 'LocalHoldsPriorityItemControl', 'holdingbranch' ); +( $status, $reserve, $all_reserves ) = CheckReserves($item); ok( $reserve->{borrowernumber} eq $borrowernumbers[1], "Received expected results with PickupLibrary/holdingbranch" ); t::lib::Mocks::mock_preference( 'LocalHoldsPriorityPatronControl', 'HomeLibrary' ); -t::lib::Mocks::mock_preference( 'LocalHoldsPriorityItemControl', 'holdingbranch' ); -($status, $reserve, $all_reserves) = CheckReserves($item); +t::lib::Mocks::mock_preference( 'LocalHoldsPriorityItemControl', 'holdingbranch' ); +( $status, $reserve, $all_reserves ) = CheckReserves($item); ok( $reserve->{borrowernumber} eq $borrowernumbers[2], "Received expected results with HomeLibrary/holdingbranch" ); t::lib::Mocks::mock_preference( 'LocalHoldsPriorityPatronControl', 'HomeLibrary' ); -t::lib::Mocks::mock_preference( 'LocalHoldsPriorityItemControl', 'homebranch' ); -($status, $reserve, $all_reserves) = CheckReserves($item); +t::lib::Mocks::mock_preference( 'LocalHoldsPriorityItemControl', 'homebranch' ); +( $status, $reserve, $all_reserves ) = CheckReserves($item); ok( $reserve->{borrowernumber} eq $borrowernumbers[3], "Received expected results with HomeLibrary/homebranch" ); $schema->storage->txn_rollback; @@ -117,23 +121,47 @@ subtest "exclude from local holds" => sub { $schema->storage->txn_begin; - t::lib::Mocks::mock_preference( 'LocalHoldsPriority', 1 ); + t::lib::Mocks::mock_preference( 'LocalHoldsPriority', 1 ); t::lib::Mocks::mock_preference( 'LocalHoldsPriorityPatronControl', 'HomeLibrary' ); - t::lib::Mocks::mock_preference( 'LocalHoldsPriorityItemControl', 'homebranch' ); + t::lib::Mocks::mock_preference( 'LocalHoldsPriorityItemControl', 'homebranch' ); - my $category_ex = $builder->build_object({ class => 'Koha::Patron::Categories', value => {exclude_from_local_holds_priority => 1} }); - my $category_nex = $builder->build_object({ class => 'Koha::Patron::Categories', value => {exclude_from_local_holds_priority => 0} }); + my $category_ex = $builder->build_object( + { class => 'Koha::Patron::Categories', value => { exclude_from_local_holds_priority => 1 } } ); + my $category_nex = $builder->build_object( + { class => 'Koha::Patron::Categories', value => { exclude_from_local_holds_priority => 0 } } ); - my $lib1 = $builder->build_object({ class => 'Koha::Libraries' }); - my $lib2 = $builder->build_object({ class => 'Koha::Libraries' }); + my $lib1 = $builder->build_object( { class => 'Koha::Libraries' } ); + my $lib2 = $builder->build_object( { class => 'Koha::Libraries' } ); - my $item1 = $builder->build_sample_item({exclude_from_local_holds_priority => 0, homebranch => $lib1->branchcode}); - my $item2 = $builder->build_sample_item({exclude_from_local_holds_priority => 1, homebranch => $lib1->branchcode}); + my $item1 = + $builder->build_sample_item( { exclude_from_local_holds_priority => 0, homebranch => $lib1->branchcode } ); + my $item2 = + $builder->build_sample_item( { exclude_from_local_holds_priority => 1, homebranch => $lib1->branchcode } ); - my $patron_ex_l2 = $builder->build_object({ class => 'Koha::Patrons', value => {branchcode => $lib2->branchcode, categorycode => $category_ex->categorycode}}); - my $patron_ex_l1 = $builder->build_object({ class => 'Koha::Patrons', value => {branchcode => $lib1->branchcode, categorycode => $category_ex->categorycode}}); - my $patron_nex_l2 = $builder->build_object({ class => 'Koha::Patrons', value => {branchcode => $lib2->branchcode, categorycode => $category_nex->categorycode}}); - my $patron_nex_l1 = $builder->build_object({ class => 'Koha::Patrons', value => {branchcode => $lib1->branchcode, categorycode => $category_nex->categorycode}}); + my $patron_ex_l2 = $builder->build_object( + { + class => 'Koha::Patrons', + value => { branchcode => $lib2->branchcode, categorycode => $category_ex->categorycode } + } + ); + my $patron_ex_l1 = $builder->build_object( + { + class => 'Koha::Patrons', + value => { branchcode => $lib1->branchcode, categorycode => $category_ex->categorycode } + } + ); + my $patron_nex_l2 = $builder->build_object( + { + class => 'Koha::Patrons', + value => { branchcode => $lib2->branchcode, categorycode => $category_nex->categorycode } + } + ); + my $patron_nex_l1 = $builder->build_object( + { + class => 'Koha::Patrons', + value => { branchcode => $lib1->branchcode, categorycode => $category_nex->categorycode } + } + ); AddReserve( { @@ -160,9 +188,12 @@ subtest "exclude from local holds" => sub { } ); - my ($status, $reserve, $all_reserves); - ($status, $reserve, $all_reserves) = CheckReserves($item1); - is($reserve->{borrowernumber}, $patron_nex_l1->borrowernumber, "Patron not excluded with local holds priorities is next checkout"); + my ( $status, $reserve, $all_reserves ); + ( $status, $reserve, $all_reserves ) = CheckReserves($item1); + is( + $reserve->{borrowernumber}, $patron_nex_l1->borrowernumber, + "Patron not excluded with local holds priorities is next checkout" + ); Koha::Holds->delete; @@ -183,8 +214,8 @@ subtest "exclude from local holds" => sub { } ); - ($status, $reserve, $all_reserves) = CheckReserves($item1); - is($reserve->{borrowernumber}, $patron_nex_l2->borrowernumber, "Local patron is excluded from priority"); + ( $status, $reserve, $all_reserves ) = CheckReserves($item1); + is( $reserve->{borrowernumber}, $patron_nex_l2->borrowernumber, "Local patron is excluded from priority" ); Koha::Holds->delete; @@ -205,8 +236,11 @@ subtest "exclude from local holds" => sub { } ); - ($status, $reserve, $all_reserves) = CheckReserves($item2); - is($reserve->{borrowernumber}, $patron_nex_l2->borrowernumber, "Patron from other library is next checkout because item is excluded"); + ( $status, $reserve, $all_reserves ) = CheckReserves($item2); + is( + $reserve->{borrowernumber}, $patron_nex_l2->borrowernumber, + "Patron from other library is next checkout because item is excluded" + ); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/Holds/RevertWaitingStatus.t b/t/db_dependent/Holds/RevertWaitingStatus.t index 069c7537c1..a26fa5fb0c 100755 --- a/t/db_dependent/Holds/RevertWaitingStatus.t +++ b/t/db_dependent/Holds/RevertWaitingStatus.t @@ -32,21 +32,21 @@ use t::lib::Mocks; my $schema = Koha::Database->schema; $schema->storage->txn_begin; my $builder = t::lib::TestBuilder->new; -my $dbh = C4::Context->dbh; +my $dbh = C4::Context->dbh; $dbh->do("DELETE FROM reserves"); $dbh->do("DELETE FROM old_reserves"); my $branchcode = $builder->build( { source => 'Branch' } )->{branchcode}; -my $itemtype = $builder->build( { source => 'Itemtype', value => { notforloan => 0 } } )->{itemtype}; +my $itemtype = $builder->build( { source => 'Itemtype', value => { notforloan => 0 } } )->{itemtype}; -t::lib::Mocks::mock_userenv({ flags => 1, userid => '1', branchcode => $branchcode }); +t::lib::Mocks::mock_userenv( { flags => 1, userid => '1', branchcode => $branchcode } ); my $borrowers_count = 3; -my $biblio = $builder->build_sample_biblio(); +my $biblio = $builder->build_sample_biblio(); my $item_barcode = 'my_barcode'; -my $itemnumber = Koha::Item->new( +my $itemnumber = Koha::Item->new( { biblionumber => $biblio->biblionumber, homebranch => $branchcode, @@ -57,15 +57,17 @@ my $itemnumber = Koha::Item->new( )->store->itemnumber; # Create some borrowers -my $patron_category = $builder->build({ source => 'Category' }); +my $patron_category = $builder->build( { source => 'Category' } ); my @borrowernumbers; foreach my $i ( 1 .. $borrowers_count ) { - my $borrowernumber = Koha::Patron->new({ - firstname => 'my firstname', - surname => 'my surname ' . $i, - categorycode => $patron_category->{categorycode}, - branchcode => $branchcode, - })->store->borrowernumber; + my $borrowernumber = Koha::Patron->new( + { + firstname => 'my firstname', + surname => 'my surname ' . $i, + categorycode => $patron_category->{categorycode}, + branchcode => $branchcode, + } + )->store->borrowernumber; push @borrowernumbers, $borrowernumber; } @@ -84,8 +86,7 @@ ModReserveAffect( $itemnumber, $borrowernumbers[0] ); my $patron = Koha::Patrons->find( $borrowernumbers[1] ); C4::Circulation::AddIssue( $patron, $item_barcode, undef, 'revert' ); -my $priorities = $dbh->selectall_arrayref( - "SELECT priority FROM reserves ORDER BY priority ASC"); +my $priorities = $dbh->selectall_arrayref("SELECT priority FROM reserves ORDER BY priority ASC"); ok( scalar @$priorities == 2, 'Only 2 holds remain in the reserves table' ); ok( $priorities->[0]->[0] == 1, 'First hold has a priority of 1' ); ok( $priorities->[1]->[0] == 2, 'Second hold has a priority of 2' ); diff --git a/t/db_dependent/Holds/WaitingReserves.t b/t/db_dependent/Holds/WaitingReserves.t index b39ee11ce1..ddadaa157e 100755 --- a/t/db_dependent/Holds/WaitingReserves.t +++ b/t/db_dependent/Holds/WaitingReserves.t @@ -2,7 +2,7 @@ use Modern::Perl; -use C4::Reserves qw( ModReserve ModReserveAffect ); +use C4::Reserves qw( ModReserve ModReserveAffect ); use Koha::DateUtils qw( dt_from_string ); use t::lib::Mocks; @@ -10,9 +10,9 @@ use t::lib::TestBuilder; use Test::More tests => 13; -use_ok('C4::Reserves', qw( ModReserve ModReserveAffect )); +use_ok( 'C4::Reserves', qw( ModReserve ModReserveAffect ) ); -my $schema = Koha::Database->new->schema; +my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; my $dbh = C4::Context->dbh; @@ -23,41 +23,51 @@ $dbh->do("DELETE FROM reserves"); my $builder = t::lib::TestBuilder->new(); # Category, branch and patrons -$builder->build({ - source => 'Category', - value => { - categorycode => 'XYZ1', - }, -}); -$builder->build({ - source => 'Branch', - value => { - branchcode => 'LIB1', - }, -}); +$builder->build( + { + source => 'Category', + value => { + categorycode => 'XYZ1', + }, + } +); +$builder->build( + { + source => 'Branch', + value => { + branchcode => 'LIB1', + }, + } +); -$builder->build({ - source => 'Branch', - value => { - branchcode => 'LIB2', - }, -}); +$builder->build( + { + source => 'Branch', + value => { + branchcode => 'LIB2', + }, + } +); -my $patron1 = $builder->build({ - source => 'Borrower', - value => { - categorycode => 'XYZ1', - branchcode => 'LIB1', - }, -}); +my $patron1 = $builder->build( + { + source => 'Borrower', + value => { + categorycode => 'XYZ1', + branchcode => 'LIB1', + }, + } +); -my $patron2 = $builder->build({ - source => 'Borrower', - value => { - categorycode => 'XYZ1', - branchcode => 'LIB2', - }, -}); +my $patron2 = $builder->build( + { + source => 'Borrower', + value => { + categorycode => 'XYZ1', + branchcode => 'LIB2', + }, + } +); my $biblio = $builder->build_sample_biblio; my $biblio2 = $builder->build_sample_biblio; @@ -87,129 +97,141 @@ Koha::CirculationRules->set_rules( my $today = dt_from_string(); my $reserve1_reservedate = $today->clone; -$reserve1_reservedate->subtract(days => 20); +$reserve1_reservedate->subtract( days => 20 ); my $reserve1_expirationdate = $today->clone; -$reserve1_expirationdate->add(days => 6); +$reserve1_expirationdate->add( days => 6 ); -my $reserve1 = $builder->build({ - source => 'Reserve', - value => { - borrowernumber => $patron1->{borrowernumber}, - reservedate => $reserve1_reservedate->ymd, - patron_expiration_date => undef, - biblionumber => $biblio->biblionumber, - branchcode => 'LIB1', - priority => 1, - found => '', - }, -}); +my $reserve1 = $builder->build( + { + source => 'Reserve', + value => { + borrowernumber => $patron1->{borrowernumber}, + reservedate => $reserve1_reservedate->ymd, + patron_expiration_date => undef, + biblionumber => $biblio->biblionumber, + branchcode => 'LIB1', + priority => 1, + found => '', + }, + } +); -t::lib::Mocks::mock_preference('ExpireReservesMaxPickUpDelay', 1); -t::lib::Mocks::mock_preference('ReservesMaxPickUpDelay', 6); +t::lib::Mocks::mock_preference( 'ExpireReservesMaxPickUpDelay', 1 ); +t::lib::Mocks::mock_preference( 'ReservesMaxPickUpDelay', 6 ); -ModReserveAffect( $item1->itemnumber, $patron1->{borrowernumber}); -my $r = Koha::Holds->find($reserve1->{reserve_id}); +ModReserveAffect( $item1->itemnumber, $patron1->{borrowernumber} ); +my $r = Koha::Holds->find( $reserve1->{reserve_id} ); -is($r->waitingdate, $today->ymd, 'Waiting date should be set to today' ); -is($r->expirationdate, $reserve1_expirationdate->ymd, 'Expiration date should be set to today + 6' ); -is($r->found, 'W', 'Reserve status is now "waiting"' ); -is($r->priority, 0, 'Priority should be 0' ); -is($r->itemnumber, $item1->itemnumber, 'Item number should be set correctly' ); +is( $r->waitingdate, $today->ymd, 'Waiting date should be set to today' ); +is( $r->expirationdate, $reserve1_expirationdate->ymd, 'Expiration date should be set to today + 6' ); +is( $r->found, 'W', 'Reserve status is now "waiting"' ); +is( $r->priority, 0, 'Priority should be 0' ); +is( $r->itemnumber, $item1->itemnumber, 'Item number should be set correctly' ); -my $reserve2 = $builder->build({ - source => 'Reserve', - value => { - borrowernumber => $patron2->{borrowernumber}, - reservedate => $reserve1_reservedate->ymd, - patron_expiration_date => undef, - biblionumber => $biblio2->biblionumber, - branchcode => 'LIB1', - priority => 1, - found => '', - }, -}); +my $reserve2 = $builder->build( + { + source => 'Reserve', + value => { + borrowernumber => $patron2->{borrowernumber}, + reservedate => $reserve1_reservedate->ymd, + patron_expiration_date => undef, + biblionumber => $biblio2->biblionumber, + branchcode => 'LIB1', + priority => 1, + found => '', + }, + } +); -ModReserveAffect( $item2->itemnumber, $patron2->{borrowernumber}, 1); -my $r2 = Koha::Holds->find($reserve2->{reserve_id}); +ModReserveAffect( $item2->itemnumber, $patron2->{borrowernumber}, 1 ); +my $r2 = Koha::Holds->find( $reserve2->{reserve_id} ); -is($r2->found, 'T', '2nd reserve - Reserve status is now "To transfer"' ); -is($r2->priority, 0, '2nd reserve - Priority should be 0' ); -is($r2->itemnumber, $item2->itemnumber, '2nd reserve - Item number should be set correctly' ); +is( $r2->found, 'T', '2nd reserve - Reserve status is now "To transfer"' ); +is( $r2->priority, 0, '2nd reserve - Priority should be 0' ); +is( $r2->itemnumber, $item2->itemnumber, '2nd reserve - Item number should be set correctly' ); -my $reserve3 = $builder->build({ - source => 'Reserve', - value => { - borrowernumber => $patron2->{borrowernumber}, - reservedate => $reserve1_reservedate->ymd, - patron_expiration_date => undef, - biblionumber => $biblio3->biblionumber, - branchcode => 'LIB1', - priority => 1, - found => '', - }, -}); +my $reserve3 = $builder->build( + { + source => 'Reserve', + value => { + borrowernumber => $patron2->{borrowernumber}, + reservedate => $reserve1_reservedate->ymd, + patron_expiration_date => undef, + biblionumber => $biblio3->biblionumber, + branchcode => 'LIB1', + priority => 1, + found => '', + }, + } +); my $special_holiday1_dt = $today->clone; -$special_holiday1_dt->add(days => 2); +$special_holiday1_dt->add( days => 2 ); -my $holiday = $builder->build({ - source => 'SpecialHoliday', - value => { - branchcode => 'LIB1', - day => $special_holiday1_dt->day, - month => $special_holiday1_dt->month, - year => $special_holiday1_dt->year, - title => 'My special holiday', - isexception => 0 - }, -}); +my $holiday = $builder->build( + { + source => 'SpecialHoliday', + value => { + branchcode => 'LIB1', + day => $special_holiday1_dt->day, + month => $special_holiday1_dt->month, + year => $special_holiday1_dt->year, + title => 'My special holiday', + isexception => 0 + }, + } +); my $special_holiday2_dt = $today->clone; -$special_holiday2_dt->add(days => 4); +$special_holiday2_dt->add( days => 4 ); -my $holiday2 = $builder->build({ - source => 'SpecialHoliday', - value => { - branchcode => 'LIB1', - day => $special_holiday2_dt->day, - month => $special_holiday2_dt->month, - year => $special_holiday2_dt->year, - title => 'My special holiday 2', - isexception => 0 - }, -}); +my $holiday2 = $builder->build( + { + source => 'SpecialHoliday', + value => { + branchcode => 'LIB1', + day => $special_holiday2_dt->day, + month => $special_holiday2_dt->month, + year => $special_holiday2_dt->year, + title => 'My special holiday 2', + isexception => 0 + }, + } +); Koha::Caches->get_instance->flush_all; -t::lib::Mocks::mock_preference('ExcludeHolidaysFromMaxPickUpDelay', 1); -ModReserveAffect( $item3->itemnumber, $patron2->{borrowernumber}); +t::lib::Mocks::mock_preference( 'ExcludeHolidaysFromMaxPickUpDelay', 1 ); +ModReserveAffect( $item3->itemnumber, $patron2->{borrowernumber} ); # Add 6 days of pickup delay + 1 day of holiday. my $expected_expiration = $today->clone; -$expected_expiration->add(days => 8); +$expected_expiration->add( days => 8 ); -my $r3 = Koha::Holds->find($reserve3->{reserve_id}); -is($r3->expirationdate, $expected_expiration->ymd, 'Expiration date should be set to today + 7' ); +my $r3 = Koha::Holds->find( $reserve3->{reserve_id} ); +is( $r3->expirationdate, $expected_expiration->ymd, 'Expiration date should be set to today + 7' ); my $reserve4_reservedate = $today->clone; -my $requested_expiredate = $today->clone()->add(days => 6); +my $requested_expiredate = $today->clone()->add( days => 6 ); -my $reserve4 = $builder->build({ - source => 'Reserve', - value => { - borrowernumber => $patron2->{borrowernumber}, - reservedate => $reserve4_reservedate->ymd, - patron_expiration_date => $requested_expiredate->ymd, - biblionumber => $biblio4->biblionumber, - branchcode => 'LIB1', - priority => 1, - found => '', - }, -}); +my $reserve4 = $builder->build( + { + source => 'Reserve', + value => { + borrowernumber => $patron2->{borrowernumber}, + reservedate => $reserve4_reservedate->ymd, + patron_expiration_date => $requested_expiredate->ymd, + biblionumber => $biblio4->biblionumber, + branchcode => 'LIB1', + priority => 1, + found => '', + }, + } +); -t::lib::Mocks::mock_preference('ReservesMaxPickUpDelay', 10); -ModReserveAffect( $item4->itemnumber, $patron2->{borrowernumber}, 0, $reserve4->{reserve_id}); +t::lib::Mocks::mock_preference( 'ReservesMaxPickUpDelay', 10 ); +ModReserveAffect( $item4->itemnumber, $patron2->{borrowernumber}, 0, $reserve4->{reserve_id} ); my $r4 = Koha::Holds->find( $reserve4->{reserve_id} ); is( $r4->expirationdate, $requested_expiredate->ymd, 'Requested expiration date should be kept' ); diff --git a/t/db_dependent/HoldsQueue.t b/t/db_dependent/HoldsQueue.t index 11bcad4156..73594fdfa7 100755 --- a/t/db_dependent/HoldsQueue.t +++ b/t/db_dependent/HoldsQueue.t @@ -27,8 +27,11 @@ use t::lib::Mocks; BEGIN { use FindBin; use lib $FindBin::Bin; - use_ok('C4::Reserves', qw( AddReserve ModReserve ModReserveAffect )); - use_ok('C4::HoldsQueue', qw( TransportCostMatrix GetHoldsQueueItems CreateQueue UpdateTransportCostMatrix GetPendingHoldRequestsForBib )); + use_ok( 'C4::Reserves', qw( AddReserve ModReserve ModReserveAffect ) ); + use_ok( + 'C4::HoldsQueue', + qw( TransportCostMatrix GetHoldsQueueItems CreateQueue UpdateTransportCostMatrix GetPendingHoldRequestsForBib ) + ); } my $schema = Koha::Database->schema; @@ -41,79 +44,99 @@ my $builder = t::lib::TestBuilder->new; t::lib::Mocks::mock_preference( 'UseBranchTransferLimits', '0' ); t::lib::Mocks::mock_preference( 'BranchTransferLimitsType', 'itemtype' ); -my $library1 = $builder->build({ - source => 'Branch', -}); -my $library2 = $builder->build({ - source => 'Branch', -}); -my $library3 = $builder->build({ - source => 'Branch', -}); +my $library1 = $builder->build( + { + source => 'Branch', + } +); +my $library2 = $builder->build( + { + source => 'Branch', + } +); +my $library3 = $builder->build( + { + source => 'Branch', + } +); my $TITLE = "Test Holds Queue XXX"; -my $borrower = $builder->build({ - source => 'Borrower', - value => { - branchcode => $library1->{branchcode}, +my $borrower = $builder->build( + { + source => 'Borrower', + value => { + branchcode => $library1->{branchcode}, + } } -}); +); my $borrowernumber = $borrower->{borrowernumber}; + # Set special (for this test) branches -my $borrower_branchcode = $borrower->{branchcode}; -my @branchcodes = ( $library1->{branchcode}, $library2->{branchcode}, $library3->{branchcode} ); -my @other_branches = ( $library2->{branchcode}, $library3->{branchcode} ); +my $borrower_branchcode = $borrower->{branchcode}; +my @branchcodes = ( $library1->{branchcode}, $library2->{branchcode}, $library3->{branchcode} ); +my @other_branches = ( $library2->{branchcode}, $library3->{branchcode} ); my $least_cost_branch_code = pop @other_branches; -my $itemtype = $builder->build({ source => 'Itemtype', value => { notforloan => 0 } })->{itemtype}; +my $itemtype = $builder->build( { source => 'Itemtype', value => { notforloan => 0 } } )->{itemtype}; #Set up the stage # Sysprefs and cost matrix -t::lib::Mocks::mock_preference('HoldsQueueSkipClosed', 0); -t::lib::Mocks::mock_preference('LocalHoldsPriority', 0); -$dbh->do("UPDATE systempreferences SET value = ? WHERE variable = 'StaticHoldsQueueWeight'", undef, - join( ',', @other_branches, $borrower_branchcode, $least_cost_branch_code)); +t::lib::Mocks::mock_preference( 'HoldsQueueSkipClosed', 0 ); +t::lib::Mocks::mock_preference( 'LocalHoldsPriority', 0 ); +$dbh->do( + "UPDATE systempreferences SET value = ? WHERE variable = 'StaticHoldsQueueWeight'", undef, + join( ',', @other_branches, $borrower_branchcode, $least_cost_branch_code ) +); $dbh->do("UPDATE systempreferences SET value = '0' WHERE variable = 'RandomizeHoldsQueueWeight'"); $dbh->do("DELETE FROM transport_cost"); -my $transport_cost_insert_sth = $dbh->prepare("insert into transport_cost (frombranch, tobranch, cost) values (?, ?, ?)"); +my $transport_cost_insert_sth = + $dbh->prepare("insert into transport_cost (frombranch, tobranch, cost) values (?, ?, ?)"); + # Favour $least_cost_branch_code -$transport_cost_insert_sth->execute($borrower_branchcode, $least_cost_branch_code, 0.2); -$transport_cost_insert_sth->execute($least_cost_branch_code, $borrower_branchcode, 0.2); +$transport_cost_insert_sth->execute( $borrower_branchcode, $least_cost_branch_code, 0.2 ); +$transport_cost_insert_sth->execute( $least_cost_branch_code, $borrower_branchcode, 0.2 ); my @b = @other_branches; while ( my $b1 = shift @b ) { - foreach my $b2 ($borrower_branchcode, $least_cost_branch_code, @b) { - $transport_cost_insert_sth->execute($b1, $b2, 0.5); - $transport_cost_insert_sth->execute($b2, $b1, 0.5); + foreach my $b2 ( $borrower_branchcode, $least_cost_branch_code, @b ) { + $transport_cost_insert_sth->execute( $b1, $b2, 0.5 ); + $transport_cost_insert_sth->execute( $b2, $b1, 0.5 ); } } - # Loanable items - all possible combinations of homebranch and holdingbranch -$dbh->do("INSERT INTO biblio (frameworkcode, author, title, datecreated) - VALUES ('SER', 'Koha test', '$TITLE', '2011-02-01')"); +$dbh->do( + "INSERT INTO biblio (frameworkcode, author, title, datecreated) + VALUES ('SER', 'Koha test', '$TITLE', '2011-02-01')" +); my $biblionumber = $dbh->selectrow_array("SELECT biblionumber FROM biblio WHERE title = '$TITLE'") - or BAIL_OUT("Cannot find newly created biblio record"); -$dbh->do("INSERT INTO biblioitems (biblionumber, itemtype) - VALUES ($biblionumber, '$itemtype')"); -my $biblioitemnumber = $dbh->selectrow_array("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = $biblionumber") - or BAIL_OUT("Cannot find newly created biblioitems record"); + or BAIL_OUT("Cannot find newly created biblio record"); +$dbh->do( + "INSERT INTO biblioitems (biblionumber, itemtype) + VALUES ($biblionumber, '$itemtype')" +); +my $biblioitemnumber = + $dbh->selectrow_array("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = $biblionumber") + or BAIL_OUT("Cannot find newly created biblioitems record"); -my $items_insert_sth = $dbh->prepare("INSERT INTO items (biblionumber, biblioitemnumber, barcode, homebranch, holdingbranch, notforloan, damaged, itemlost, withdrawn, onloan, itype) - VALUES ($biblionumber, $biblioitemnumber, ?, ?, ?, 0, 0, 0, 0, NULL, '$itemtype')"); # CURRENT_DATE - 3)"); -my $first_barcode = int(rand(1000000000000)); # XXX -my $barcode = $first_barcode; +my $items_insert_sth = $dbh->prepare( + "INSERT INTO items (biblionumber, biblioitemnumber, barcode, homebranch, holdingbranch, notforloan, damaged, itemlost, withdrawn, onloan, itype) + VALUES ($biblionumber, $biblioitemnumber, ?, ?, ?, 0, 0, 0, 0, NULL, '$itemtype')" +); # CURRENT_DATE - 3)"); +my $first_barcode = int( rand(1000000000000) ); # XXX +my $barcode = $first_barcode; foreach ( $borrower_branchcode, $least_cost_branch_code, @other_branches ) { - $items_insert_sth->execute($barcode++, $borrower_branchcode, $_); - $items_insert_sth->execute($barcode++, $_, $_); - $items_insert_sth->execute($barcode++, $_, $borrower_branchcode); + $items_insert_sth->execute( $barcode++, $borrower_branchcode, $_ ); + $items_insert_sth->execute( $barcode++, $_, $_ ); + $items_insert_sth->execute( $barcode++, $_, $borrower_branchcode ); } # Remove existing reserves, makes debugging easier $dbh->do("DELETE FROM reserves"); my $bibitems = undef; my $priority = 1; + # Make a reserve AddReserve( { @@ -123,52 +146,66 @@ AddReserve( priority => $priority, } ); + # $resdate, $expdate, $notes, $title, $checkitem, $found $dbh->do("UPDATE reserves SET reservedate = DATE_SUB( reservedate, INTERVAL 1 DAY )"); # Tests -my $use_cost_matrix_sth = $dbh->prepare("UPDATE systempreferences SET value = ? WHERE variable = 'UseTransportCostMatrix'"); -my $test_sth = $dbh->prepare("SELECT * FROM hold_fill_targets +my $use_cost_matrix_sth = + $dbh->prepare("UPDATE systempreferences SET value = ? WHERE variable = 'UseTransportCostMatrix'"); +my $test_sth = $dbh->prepare( + "SELECT * FROM hold_fill_targets JOIN tmp_holdsqueue USING (borrowernumber, biblionumber, itemnumber) JOIN items USING (itemnumber) - WHERE borrowernumber = $borrowernumber"); + WHERE borrowernumber = $borrowernumber" +); # We have a book available homed in borrower branch, no point fiddling with AutomaticItemReturn -t::lib::Mocks::mock_preference('AutomaticItemReturn', 0); -test_queue ('take from homebranch', 0, $borrower_branchcode, $borrower_branchcode); -test_queue ('take from homebranch', 1, $borrower_branchcode, $borrower_branchcode); +t::lib::Mocks::mock_preference( 'AutomaticItemReturn', 0 ); +test_queue( 'take from homebranch', 0, $borrower_branchcode, $borrower_branchcode ); +test_queue( 'take from homebranch', 1, $borrower_branchcode, $borrower_branchcode ); $dbh->do("DELETE FROM tmp_holdsqueue"); $dbh->do("DELETE FROM hold_fill_targets"); -$dbh->do("DELETE FROM issues WHERE itemnumber IN (SELECT itemnumber FROM items WHERE homebranch = '$borrower_branchcode' AND holdingbranch = '$borrower_branchcode')"); +$dbh->do( + "DELETE FROM issues WHERE itemnumber IN (SELECT itemnumber FROM items WHERE homebranch = '$borrower_branchcode' AND holdingbranch = '$borrower_branchcode')" +); $dbh->do("DELETE FROM items WHERE homebranch = '$borrower_branchcode' AND holdingbranch = '$borrower_branchcode'"); + # test_queue will flush -t::lib::Mocks::mock_preference('AutomaticItemReturn', 1); +t::lib::Mocks::mock_preference( 'AutomaticItemReturn', 1 ); + # Not sure how to make this test more difficult - holding branch does not matter $dbh->do("DELETE FROM tmp_holdsqueue"); $dbh->do("DELETE FROM hold_fill_targets"); -$dbh->do("DELETE FROM issues WHERE itemnumber IN (SELECT itemnumber FROM items WHERE homebranch = '$borrower_branchcode')"); +$dbh->do( + "DELETE FROM issues WHERE itemnumber IN (SELECT itemnumber FROM items WHERE homebranch = '$borrower_branchcode')"); $dbh->do("DELETE FROM items WHERE homebranch = '$borrower_branchcode'"); -t::lib::Mocks::mock_preference('AutomaticItemReturn', 0); +t::lib::Mocks::mock_preference( 'AutomaticItemReturn', 0 ); + # We have a book available held in borrower branch -test_queue ('take from holdingbranch', 0, $borrower_branchcode, $borrower_branchcode); -test_queue ('take from holdingbranch', 1, $borrower_branchcode, $borrower_branchcode); +test_queue( 'take from holdingbranch', 0, $borrower_branchcode, $borrower_branchcode ); +test_queue( 'take from holdingbranch', 1, $borrower_branchcode, $borrower_branchcode ); $dbh->do("DELETE FROM tmp_holdsqueue"); $dbh->do("DELETE FROM hold_fill_targets"); -$dbh->do("DELETE FROM issues WHERE itemnumber IN (SELECT itemnumber FROM items WHERE holdingbranch = '$borrower_branchcode')"); +$dbh->do( + "DELETE FROM issues WHERE itemnumber IN (SELECT itemnumber FROM items WHERE holdingbranch = '$borrower_branchcode')" +); $dbh->do("DELETE FROM items WHERE holdingbranch = '$borrower_branchcode'"); + # No book available in borrower branch, pick according to the rules # Frst branch from StaticHoldsQueueWeight -test_queue ('take from lowest cost branch', 0, $borrower_branchcode, $other_branches[0]); -test_queue ('take from lowest cost branch', 1, $borrower_branchcode, $least_cost_branch_code); -my $queue = C4::HoldsQueue::GetHoldsQueueItems({ branchlimit => $least_cost_branch_code}) || []; +test_queue( 'take from lowest cost branch', 0, $borrower_branchcode, $other_branches[0] ); +test_queue( 'take from lowest cost branch', 1, $borrower_branchcode, $least_cost_branch_code ); +my $queue = C4::HoldsQueue::GetHoldsQueueItems( { branchlimit => $least_cost_branch_code } ) || []; my $queue_item = $queue->next; -ok( $queue_item - && $queue_item->pickbranch eq $borrower_branchcode - && $queue_item->item->holdingbranch eq $least_cost_branch_code, "GetHoldsQueueItems" ) - or diag( "Expected item for pick $borrower_branchcode, hold $least_cost_branch_code, got ".Dumper($queue_item->unblessed) ); +ok( $queue_item + && $queue_item->pickbranch eq $borrower_branchcode + && $queue_item->item->holdingbranch eq $least_cost_branch_code, "GetHoldsQueueItems" ) + or diag( "Expected item for pick $borrower_branchcode, hold $least_cost_branch_code, got " + . Dumper( $queue_item->unblessed ) ); ok( $queue_item->item->effective_itemtype, 'item type included in queued items list (bug 5825)' ); ok( @@ -187,46 +224,59 @@ $schema->txn_begin; # Clear out existing rules relating to holdallowed $dbh->do("DELETE FROM circulation_rules"); -t::lib::Mocks::mock_preference('UseTransportCostMatrix', 0); +t::lib::Mocks::mock_preference( 'UseTransportCostMatrix', 0 ); -$itemtype = $builder->build({ source => 'Itemtype', value => { notforloan => 0 } })->{itemtype}; +$itemtype = $builder->build( { source => 'Itemtype', value => { notforloan => 0 } } )->{itemtype}; -$library1 = $builder->build({ - source => 'Branch', -}); -$library2 = $builder->build({ - source => 'Branch', -}); -$library3 = $builder->build({ - source => 'Branch', -}); +$library1 = $builder->build( + { + source => 'Branch', + } +); +$library2 = $builder->build( + { + source => 'Branch', + } +); +$library3 = $builder->build( + { + source => 'Branch', + } +); @branchcodes = ( $library1->{branchcode}, $library2->{branchcode}, $library3->{branchcode} ); -my $category = $builder->build({ source => 'Category', value => {exclude_from_local_holds_priority => 0} } ); +my $category = $builder->build( { source => 'Category', value => { exclude_from_local_holds_priority => 0 } } ); -my $borrower1 = $builder->build({ - source => 'Borrower', - value => { - branchcode => $branchcodes[0], - categorycode => $category->{categorycode}, - }, -}); -my $borrower2 = $builder->build({ - source => 'Borrower', - value => { - branchcode => $branchcodes[1], - categorycode => $category->{categorycode}, - }, -}); -my $borrower3 = $builder->build({ - source => 'Borrower', - value => { - branchcode => $branchcodes[2], - categorycode => $category->{categorycode}, - }, -}); +my $borrower1 = $builder->build( + { + source => 'Borrower', + value => { + branchcode => $branchcodes[0], + categorycode => $category->{categorycode}, + }, + } +); +my $borrower2 = $builder->build( + { + source => 'Borrower', + value => { + branchcode => $branchcodes[1], + categorycode => $category->{categorycode}, + }, + } +); +my $borrower3 = $builder->build( + { + source => 'Borrower', + value => { + branchcode => $branchcodes[2], + categorycode => $category->{categorycode}, + }, + } +); -$dbh->do(qq{ +$dbh->do( + qq{ INSERT INTO biblio ( frameworkcode, author, @@ -238,11 +288,13 @@ $dbh->do(qq{ '$TITLE', '2011-02-01' ) -}); +} +); $biblionumber = $dbh->selectrow_array("SELECT biblionumber FROM biblio WHERE title = '$TITLE'") - or BAIL_OUT("Cannot find newly created biblio record"); + or BAIL_OUT("Cannot find newly created biblio record"); -$dbh->do(qq{ +$dbh->do( + qq{ INSERT INTO biblioitems ( biblionumber, itemtype @@ -250,11 +302,13 @@ $dbh->do(qq{ $biblionumber, '$itemtype' ) -}); +} +); $biblioitemnumber = $dbh->selectrow_array("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = $biblionumber") - or BAIL_OUT("Cannot find newly created biblioitems record"); + or BAIL_OUT("Cannot find newly created biblioitems record"); -$items_insert_sth = $dbh->prepare(qq{ +$items_insert_sth = $dbh->prepare( + qq{ INSERT INTO items ( biblionumber, biblioitemnumber, @@ -282,7 +336,9 @@ $items_insert_sth = $dbh->prepare(qq{ '$itemtype', 0 ) -}); +} +); + # Create 3 items from 2 branches ( branches are for borrowers 1 and 2 respectively ) $barcode = int( rand(1000000000000) ); $items_insert_sth->execute( $barcode + 0, $branchcodes[0], $branchcodes[0] ); @@ -290,7 +346,8 @@ $items_insert_sth->execute( $barcode + 1, $branchcodes[1], $branchcodes[1] ); $items_insert_sth->execute( $barcode + 2, $branchcodes[1], $branchcodes[1] ); $dbh->do("DELETE FROM reserves"); -my $sth = $dbh->prepare(q{ +my $sth = $dbh->prepare( + q{ INSERT INTO reserves ( borrowernumber, biblionumber, @@ -298,7 +355,8 @@ my $sth = $dbh->prepare(q{ priority, reservedate ) VALUES ( ?,?,?,?, CURRENT_DATE() ) -}); +} +); $sth->execute( $borrower1->{borrowernumber}, $biblionumber, $branchcodes[0], 1 ); $sth->execute( $borrower2->{borrowernumber}, $biblionumber, $branchcodes[0], 2 ); $sth->execute( $borrower3->{borrowernumber}, $biblionumber, $branchcodes[0], 3 ); @@ -308,24 +366,30 @@ my $holds_queue; $dbh->do("DELETE FROM circulation_rules"); Koha::CirculationRules->set_rule( { - rule_name => 'holdallowed', - rule_value => 'from_home_library', - branchcode => undef, - itemtype => undef, + rule_name => 'holdallowed', + rule_value => 'from_home_library', + branchcode => undef, + itemtype => undef, } ); C4::HoldsQueue::CreateQueue(); -$holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} }); +$holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } ); is( @$holds_queue, 2, "Holds queue filling correct number for default holds policy 'from home library'" ); -is( $holds_queue->[0]->{cardnumber}, $borrower1->{cardnumber}, "Holds queue filling 1st correct hold for default holds policy 'from home library'"); -is( $holds_queue->[1]->{cardnumber}, $borrower2->{cardnumber}, "Holds queue filling 2nd correct hold for default holds policy 'from home library'"); +is( + $holds_queue->[0]->{cardnumber}, $borrower1->{cardnumber}, + "Holds queue filling 1st correct hold for default holds policy 'from home library'" +); +is( + $holds_queue->[1]->{cardnumber}, $borrower2->{cardnumber}, + "Holds queue filling 2nd correct hold for default holds policy 'from home library'" +); # Test skipping hold picks for closed libraries. # At this point in the test, we have 2 rows in the holds queue # 1 of which is coming from MPL. Let's enable HoldsQueueSkipClosed # and make today a holiday for MPL. When we run it again we should only # have 1 row in the holds queue -t::lib::Mocks::mock_preference('HoldsQueueSkipClosed', 1); +t::lib::Mocks::mock_preference( 'HoldsQueueSkipClosed', 1 ); my $today = dt_from_string(); C4::Calendar->new( branchcode => $branchcodes[0] )->insert_single_holiday( day => $today->day(), @@ -334,25 +398,29 @@ C4::Calendar->new( branchcode => $branchcodes[0] )->insert_single_holiday( title => "$today", description => "$today", ); + # If the test below is removed, aother tests using the holiday will fail. For some reason if we call is_holiday now # the holiday will get set in cache correctly, but not if we let C4::HoldsQueue call is_holiday instead. -is( Koha::Calendar->new( branchcode => $branchcodes[0] )->is_holiday( $today ), 1, 'Is today a holiday for pickup branch' ); +is( + Koha::Calendar->new( branchcode => $branchcodes[0] )->is_holiday($today), 1, + 'Is today a holiday for pickup branch' +); C4::HoldsQueue::CreateQueue(); -$holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} }); -is( scalar( @$holds_queue ), 1, "Holds not filled with items from closed libraries" ); -t::lib::Mocks::mock_preference('HoldsQueueSkipClosed', 0); +$holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } ); +is( scalar(@$holds_queue), 1, "Holds not filled with items from closed libraries" ); +t::lib::Mocks::mock_preference( 'HoldsQueueSkipClosed', 0 ); $dbh->do("DELETE FROM circulation_rules"); Koha::CirculationRules->set_rule( { - rule_name => 'holdallowed', - rule_value => 'from_any_library', - branchcode => undef, - itemtype => undef, + rule_name => 'holdallowed', + rule_value => 'from_any_library', + branchcode => undef, + itemtype => undef, } ); C4::HoldsQueue::CreateQueue(); -$holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} }); +$holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } ); is( @$holds_queue, 3, "Holds queue filling correct number for holds for default holds policy 'from any library'" ); # Test skipping hold picks for closed libraries without transport cost matrix @@ -362,27 +430,27 @@ is( @$holds_queue, 3, "Holds queue filling correct number for holds for default # When we run it again we should only have 2 rows in the holds queue t::lib::Mocks::mock_preference( 'HoldsQueueSkipClosed', 1 ); C4::HoldsQueue::CreateQueue(); -$holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} }); -is( scalar( @$holds_queue ), 2, "Holds not filled with items from closed libraries" ); +$holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } ); +is( scalar(@$holds_queue), 2, "Holds not filled with items from closed libraries" ); t::lib::Mocks::mock_preference( 'HoldsQueueSkipClosed', 0 ); ## Test LocalHoldsPriority -t::lib::Mocks::mock_preference('LocalHoldsPriority', 1); +t::lib::Mocks::mock_preference( 'LocalHoldsPriority', 1 ); $dbh->do("DELETE FROM circulation_rules"); Koha::CirculationRules->set_rule( { - rule_name => 'holdallowed', - rule_value => 'from_any_library', - branchcode => undef, - itemtype => undef, + rule_name => 'holdallowed', + rule_value => 'from_any_library', + branchcode => undef, + itemtype => undef, } ); $dbh->do("DELETE FROM issues"); # Test homebranch = patron branch -t::lib::Mocks::mock_preference('LocalHoldsPriorityPatronControl', 'HomeLibrary'); -t::lib::Mocks::mock_preference('LocalHoldsPriorityItemControl', 'homebranch'); +t::lib::Mocks::mock_preference( 'LocalHoldsPriorityPatronControl', 'HomeLibrary' ); +t::lib::Mocks::mock_preference( 'LocalHoldsPriorityItemControl', 'homebranch' ); C4::Context->clear_syspref_cache(); $dbh->do("DELETE FROM reserves"); $sth->execute( $borrower1->{borrowernumber}, $biblionumber, $branchcodes[0], 1 ); @@ -390,23 +458,28 @@ $sth->execute( $borrower2->{borrowernumber}, $biblionumber, $branchcodes[0], 2 ) $sth->execute( $borrower3->{borrowernumber}, $biblionumber, $branchcodes[0], 3 ); $dbh->do("DELETE FROM items"); + # barcode, homebranch, holdingbranch, itemtype $items_insert_sth->execute( $barcode + 4, $branchcodes[2], $branchcodes[0] ); C4::HoldsQueue::CreateQueue(); -$holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} }); -is( $holds_queue->[0]->{cardnumber}, $borrower3->{cardnumber}, "Holds queue giving priority to patron who's home library matches item's home library"); +$holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } ); +is( + $holds_queue->[0]->{cardnumber}, $borrower3->{cardnumber}, + "Holds queue giving priority to patron who's home library matches item's home library" +); ### Test branch transfer limits ### -t::lib::Mocks::mock_preference('LocalHoldsPriorityPatronControl', 'HomeLibrary'); -t::lib::Mocks::mock_preference('LocalHoldsPriorityItemControl', 'holdingbranch'); -t::lib::Mocks::mock_preference( 'UseBranchTransferLimits', '1' ); +t::lib::Mocks::mock_preference( 'LocalHoldsPriorityPatronControl', 'HomeLibrary' ); +t::lib::Mocks::mock_preference( 'LocalHoldsPriorityItemControl', 'holdingbranch' ); +t::lib::Mocks::mock_preference( 'UseBranchTransferLimits', '1' ); C4::Context->clear_syspref_cache(); $dbh->do("DELETE FROM reserves"); $sth->execute( $borrower1->{borrowernumber}, $biblionumber, $branchcodes[0], 1 ); $sth->execute( $borrower2->{borrowernumber}, $biblionumber, $branchcodes[1], 2 ); $dbh->do("DELETE FROM items"); + # barcode, homebranch, holdingbranch, itemtype $items_insert_sth->execute( $barcode, $branchcodes[2], $branchcodes[2] ); my $item = Koha::Items->find( { barcode => $barcode } ); @@ -420,8 +493,11 @@ my $limit1 = Koha::Item::Transfer::Limit->new( )->store(); C4::HoldsQueue::CreateQueue(); -$holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} }); -is( $holds_queue->[0]->{cardnumber}, $borrower2->{cardnumber}, "Holds queue skips hold transfer that would violate branch transfer limits"); +$holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } ); +is( + $holds_queue->[0]->{cardnumber}, $borrower2->{cardnumber}, + "Holds queue skips hold transfer that would violate branch transfer limits" +); my $limit2 = Koha::Item::Transfer::Limit->new( { @@ -432,8 +508,11 @@ my $limit2 = Koha::Item::Transfer::Limit->new( )->store(); C4::HoldsQueue::CreateQueue(); -$holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} }); -is( $holds_queue->[0]->{cardnumber}, undef, "Holds queue doesn't fill hold where all available items would violate branch transfer limits"); +$holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } ); +is( + $holds_queue->[0]->{cardnumber}, undef, + "Holds queue doesn't fill hold where all available items would violate branch transfer limits" +); $limit1->delete(); $limit2->delete(); @@ -441,8 +520,8 @@ t::lib::Mocks::mock_preference( 'UseBranchTransferLimits', '0' ); ### END Test branch transfer limits ### # Test holdingbranch = patron branch -t::lib::Mocks::mock_preference('LocalHoldsPriorityPatronControl', 'HomeLibrary'); -t::lib::Mocks::mock_preference('LocalHoldsPriorityItemControl', 'holdingbranch'); +t::lib::Mocks::mock_preference( 'LocalHoldsPriorityPatronControl', 'HomeLibrary' ); +t::lib::Mocks::mock_preference( 'LocalHoldsPriorityItemControl', 'holdingbranch' ); C4::Context->clear_syspref_cache(); $dbh->do("DELETE FROM reserves"); $sth->execute( $borrower1->{borrowernumber}, $biblionumber, $branchcodes[0], 1 ); @@ -450,16 +529,20 @@ $sth->execute( $borrower2->{borrowernumber}, $biblionumber, $branchcodes[0], 2 ) $sth->execute( $borrower3->{borrowernumber}, $biblionumber, $branchcodes[0], 3 ); $dbh->do("DELETE FROM items"); + # barcode, homebranch, holdingbranch, itemtype $items_insert_sth->execute( $barcode + 4, $branchcodes[0], $branchcodes[2] ); C4::HoldsQueue::CreateQueue(); -$holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} }); -is( $holds_queue->[0]->{cardnumber}, $borrower3->{cardnumber}, "Holds queue giving priority to patron who's home library matches item's holding library"); +$holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } ); +is( + $holds_queue->[0]->{cardnumber}, $borrower3->{cardnumber}, + "Holds queue giving priority to patron who's home library matches item's holding library" +); # Test holdingbranch = pickup branch -t::lib::Mocks::mock_preference('LocalHoldsPriorityPatronControl', 'PickupLibrary'); -t::lib::Mocks::mock_preference('LocalHoldsPriorityItemControl', 'holdingbranch'); +t::lib::Mocks::mock_preference( 'LocalHoldsPriorityPatronControl', 'PickupLibrary' ); +t::lib::Mocks::mock_preference( 'LocalHoldsPriorityItemControl', 'holdingbranch' ); C4::Context->clear_syspref_cache(); $dbh->do("DELETE FROM reserves"); $sth->execute( $borrower1->{borrowernumber}, $biblionumber, $branchcodes[0], 1 ); @@ -467,16 +550,20 @@ $sth->execute( $borrower2->{borrowernumber}, $biblionumber, $branchcodes[0], 2 ) $sth->execute( $borrower3->{borrowernumber}, $biblionumber, $branchcodes[2], 3 ); $dbh->do("DELETE FROM items"); + # barcode, homebranch, holdingbranch, itemtype $items_insert_sth->execute( $barcode + 4, $branchcodes[0], $branchcodes[2] ); C4::HoldsQueue::CreateQueue(); -$holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} }); -is( $holds_queue->[0]->{cardnumber}, $borrower3->{cardnumber}, "Holds queue giving priority to patron who's home library matches item's holding library"); +$holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } ); +is( + $holds_queue->[0]->{cardnumber}, $borrower3->{cardnumber}, + "Holds queue giving priority to patron who's home library matches item's holding library" +); # Test homebranch = pickup branch -t::lib::Mocks::mock_preference('LocalHoldsPriorityPatronControl', 'PickupLibrary'); -t::lib::Mocks::mock_preference('LocalHoldsPriorityItemControl', 'homebranch'); +t::lib::Mocks::mock_preference( 'LocalHoldsPriorityPatronControl', 'PickupLibrary' ); +t::lib::Mocks::mock_preference( 'LocalHoldsPriorityItemControl', 'homebranch' ); C4::Context->clear_syspref_cache(); $dbh->do("DELETE FROM reserves"); $sth->execute( $borrower1->{borrowernumber}, $biblionumber, $branchcodes[0], 1 ); @@ -484,19 +571,22 @@ $sth->execute( $borrower2->{borrowernumber}, $biblionumber, $branchcodes[0], 2 ) $sth->execute( $borrower3->{borrowernumber}, $biblionumber, $branchcodes[2], 3 ); $dbh->do("DELETE FROM items"); + # barcode, homebranch, holdingbranch, itemtype $items_insert_sth->execute( $barcode + 4, $branchcodes[2], $branchcodes[0] ); C4::HoldsQueue::CreateQueue(); -$holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} }); -is( $holds_queue->[0]->{cardnumber}, $borrower3->{cardnumber}, "Holds queue giving priority to patron who's home library matches item's holding library"); +$holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } ); +is( + $holds_queue->[0]->{cardnumber}, $borrower3->{cardnumber}, + "Holds queue giving priority to patron who's home library matches item's holding library" +); -t::lib::Mocks::mock_preference('LocalHoldsPriority', 0); +t::lib::Mocks::mock_preference( 'LocalHoldsPriority', 0 ); ## End testing of LocalHoldsPriority - # Bug 14297 -$itemtype = $builder->build({ source => 'Itemtype', value => { notforloan => 0 } })->{itemtype}; +$itemtype = $builder->build( { source => 'Itemtype', value => { notforloan => 0 } } )->{itemtype}; $borrowernumber = $borrower3->{borrowernumber}; my $library_A = $library1->{branchcode}; my $library_B = $library2->{branchcode}; @@ -510,43 +600,44 @@ $dbh->do("DELETE FROM transport_cost"); $dbh->do("DELETE FROM tmp_holdsqueue"); $dbh->do("DELETE FROM hold_fill_targets"); -$dbh->do(" +$dbh->do( " INSERT INTO biblio (frameworkcode, author, title, datecreated) VALUES ('', 'Koha test', '$TITLE', '2011-02-01') -"); +" ); $biblionumber = $dbh->selectrow_array("SELECT biblionumber FROM biblio WHERE title = '$TITLE'") - or BAIL_OUT("Cannot find newly created biblio record"); + or BAIL_OUT("Cannot find newly created biblio record"); $dbh->do("INSERT INTO biblioitems (biblionumber, itemtype) VALUES ($biblionumber, '$itemtype')"); -$biblioitemnumber = - $dbh->selectrow_array("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = $biblionumber") - or BAIL_OUT("Cannot find newly created biblioitems record"); +$biblioitemnumber = $dbh->selectrow_array("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = $biblionumber") + or BAIL_OUT("Cannot find newly created biblioitems record"); -$dbh->do(" +$dbh->do( " INSERT INTO items (biblionumber, biblioitemnumber, homebranch, holdingbranch, notforloan, damaged, itemlost, withdrawn, onloan, itype, exclude_from_local_holds_priority) VALUES ($biblionumber, $biblioitemnumber, '$library_A', '$library_A', 0, 0, 0, 0, NULL, '$itemtype', 0) -"); +" ); -$dbh->do(" +$dbh->do( " INSERT INTO items (biblionumber, biblioitemnumber, homebranch, holdingbranch, notforloan, damaged, itemlost, withdrawn, onloan, itype, exclude_from_local_holds_priority) VALUES ($biblionumber, $biblioitemnumber, '$library_B', '$library_B', 0, 0, 0, 0, NULL, '$itemtype', 0) -"); +" ); Koha::CirculationRules->set_rules( { - branchcode => $library_A, - itemtype => $itemtype, - rules => { + branchcode => $library_A, + itemtype => $itemtype, + rules => { holdallowed => 'from_any_library', returnbranch => 'homebranch', } } ); -$dbh->do( "UPDATE systempreferences SET value = ? WHERE variable = 'StaticHoldsQueueWeight'", - undef, join( ',', $library_B, $library_A, $library_C ) ); -$dbh->do( "UPDATE systempreferences SET value = 0 WHERE variable = 'RandomizeHoldsQueueWeight'" ); +$dbh->do( + "UPDATE systempreferences SET value = ? WHERE variable = 'StaticHoldsQueueWeight'", + undef, join( ',', $library_B, $library_A, $library_C ) +); +$dbh->do("UPDATE systempreferences SET value = 0 WHERE variable = 'RandomizeHoldsQueueWeight'"); my $reserve_id = AddReserve( { @@ -557,15 +648,19 @@ my $reserve_id = AddReserve( } ); C4::HoldsQueue::CreateQueue(); -$holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} }); -is( @$holds_queue, 1, "Bug 14297 - Holds Queue building ignoring holds where pickup & home branch don't match and item is not from le"); +$holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } ); +is( + @$holds_queue, 1, + "Bug 14297 - Holds Queue building ignoring holds where pickup & home branch don't match and item is not from le" +); + # End Bug 14297 # Bug 15062 -$itemtype = $builder->build({ source => 'Itemtype', value => { notforloan => 0 } })->{itemtype}; +$itemtype = $builder->build( { source => 'Itemtype', value => { notforloan => 0 } } )->{itemtype}; $borrowernumber = $borrower2->{borrowernumber}; -$library_A = $library1->{branchcode}; -$library_B = $library2->{branchcode}; +$library_A = $library1->{branchcode}; +$library_B = $library2->{branchcode}; $dbh->do("DELETE FROM reserves"); $dbh->do("DELETE FROM issues"); $dbh->do("DELETE FROM items"); @@ -575,29 +670,28 @@ $dbh->do("DELETE FROM transport_cost"); $dbh->do("DELETE FROM tmp_holdsqueue"); $dbh->do("DELETE FROM hold_fill_targets"); -t::lib::Mocks::mock_preference("UseTransportCostMatrix",1); +t::lib::Mocks::mock_preference( "UseTransportCostMatrix", 1 ); my $tc_rs = $schema->resultset('TransportCost'); -$tc_rs->create({ frombranch => $library_A, tobranch => $library_B, cost => 0, disable_transfer => 1 }); -$tc_rs->create({ frombranch => $library_B, tobranch => $library_A, cost => 0, disable_transfer => 1 }); +$tc_rs->create( { frombranch => $library_A, tobranch => $library_B, cost => 0, disable_transfer => 1 } ); +$tc_rs->create( { frombranch => $library_B, tobranch => $library_A, cost => 0, disable_transfer => 1 } ); -$dbh->do(" +$dbh->do( " INSERT INTO biblio (frameworkcode, author, title, datecreated) VALUES ('', 'Koha test', '$TITLE', '2011-02-01') -"); +" ); $biblionumber = $dbh->selectrow_array("SELECT biblionumber FROM biblio WHERE title = '$TITLE'") - or BAIL_OUT("Cannot find newly created biblio record"); + or BAIL_OUT("Cannot find newly created biblio record"); $dbh->do("INSERT INTO biblioitems (biblionumber, itemtype) VALUES ($biblionumber, '$itemtype')"); -$biblioitemnumber = - $dbh->selectrow_array("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = $biblionumber") - or BAIL_OUT("Cannot find newly created biblioitems record"); +$biblioitemnumber = $dbh->selectrow_array("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = $biblionumber") + or BAIL_OUT("Cannot find newly created biblioitems record"); -$dbh->do(" +$dbh->do( " INSERT INTO items (biblionumber, biblioitemnumber, homebranch, holdingbranch, notforloan, damaged, itemlost, withdrawn, onloan, itype, exclude_from_local_holds_priority) VALUES ($biblionumber, $biblioitemnumber, '$library_A', '$library_A', 0, 0, 0, 0, NULL, '$itemtype', 0) -"); +" ); $reserve_id = AddReserve( { @@ -609,16 +703,20 @@ $reserve_id = AddReserve( ); C4::HoldsQueue::CreateQueue(); -$holds_queue = $dbh->selectall_arrayref("SELECT * FROM tmp_holdsqueue", { Slice => {} }); -is( @$holds_queue, 0, "Bug 15062 - Holds queue with Transport Cost Matrix will transfer item even if transfers disabled"); +$holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } ); +is( + @$holds_queue, 0, + "Bug 15062 - Holds queue with Transport Cost Matrix will transfer item even if transfers disabled" +); + # End Bug 15062 # Test hold_fulfillment_policy t::lib::Mocks::mock_preference( "UseTransportCostMatrix", 0 ); $borrowernumber = $borrower3->{borrowernumber}; -$library_A = $library1->{branchcode}; -$library_B = $library2->{branchcode}; -$library_C = $library3->{branchcode}; +$library_A = $library1->{branchcode}; +$library_B = $library2->{branchcode}; +$library_C = $library3->{branchcode}; $dbh->do("DELETE FROM reserves"); $dbh->do("DELETE FROM issues"); $dbh->do("DELETE FROM items"); @@ -628,29 +726,29 @@ $dbh->do("DELETE FROM transport_cost"); $dbh->do("DELETE FROM tmp_holdsqueue"); $dbh->do("DELETE FROM hold_fill_targets"); -$dbh->do("INSERT INTO biblio (frameworkcode, author, title, datecreated) VALUES ('', 'Koha test', '$TITLE', '2011-02-01')"); +$dbh->do( + "INSERT INTO biblio (frameworkcode, author, title, datecreated) VALUES ('', 'Koha test', '$TITLE', '2011-02-01')"); $biblionumber = $dbh->selectrow_array("SELECT biblionumber FROM biblio WHERE title = '$TITLE'") - or BAIL_OUT("Cannot find newly created biblio record"); + or BAIL_OUT("Cannot find newly created biblio record"); $dbh->do("INSERT INTO biblioitems (biblionumber, itemtype) VALUES ($biblionumber, '$itemtype')"); -$biblioitemnumber = - $dbh->selectrow_array("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = $biblionumber") - or BAIL_OUT("Cannot find newly created biblioitems record"); +$biblioitemnumber = $dbh->selectrow_array("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = $biblionumber") + or BAIL_OUT("Cannot find newly created biblioitems record"); -$dbh->do(" +$dbh->do( " INSERT INTO items (biblionumber, biblioitemnumber, homebranch, holdingbranch, notforloan, damaged, itemlost, withdrawn, onloan, itype, exclude_from_local_holds_priority) VALUES ($biblionumber, $biblioitemnumber, '$library_A', '$library_B', 0, 0, 0, 0, NULL, '$itemtype', 0) -"); +" ); # With hold_fulfillment_policy = homebranch, hold should only be picked up if pickup branch = homebranch $dbh->do("DELETE FROM circulation_rules"); Koha::CirculationRules->set_rules( { - branchcode => undef, - itemtype => undef, - rules => { + branchcode => undef, + itemtype => undef, + rules => { holdallowed => 'from_any_library', hold_fulfillment_policy => 'homebranch', } @@ -672,7 +770,7 @@ $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice is( @$holds_queue, 1, "Hold where pickup branch matches home branch targeted" ); my $target_rs = $schema->resultset('HoldFillTarget'); is( $target_rs->next->reserve_id, $reserve_id, "Reserve id correctly set in hold fill target for title level hold" ); -Koha::Holds->find( $reserve_id )->cancel; +Koha::Holds->find($reserve_id)->cancel; # Holding branch matches pickup branch $reserve_id = AddReserve( @@ -684,11 +782,10 @@ $reserve_id = AddReserve( } ); - C4::HoldsQueue::CreateQueue(); $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } ); is( @$holds_queue, 0, "Hold where pickup ne home, pickup eq home not targeted" ); -Koha::Holds->find( $reserve_id )->cancel; +Koha::Holds->find($reserve_id)->cancel; # Neither branch matches pickup branch $reserve_id = AddReserve( @@ -703,15 +800,15 @@ $reserve_id = AddReserve( C4::HoldsQueue::CreateQueue(); $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } ); is( @$holds_queue, 0, "Hold where pickup ne home, pickup ne holding not targeted" ); -Koha::Holds->find( $reserve_id )->cancel; +Koha::Holds->find($reserve_id)->cancel; # With hold_fulfillment_policy = holdingbranch, hold should only be picked up if pickup branch = holdingbranch $dbh->do("DELETE FROM circulation_rules"); Koha::CirculationRules->set_rules( { - branchcode => undef, - itemtype => undef, - rules => { + branchcode => undef, + itemtype => undef, + rules => { holdallowed => 'from_any_library', hold_fulfillment_policy => 'holdingbranch', } @@ -731,7 +828,7 @@ $reserve_id = AddReserve( C4::HoldsQueue::CreateQueue(); $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } ); is( @$holds_queue, 0, "Hold where pickup eq home, pickup ne holding not targeted" ); -Koha::Holds->find( $reserve_id )->cancel; +Koha::Holds->find($reserve_id)->cancel; # Holding branch matches pickup branch $reserve_id = AddReserve( @@ -746,7 +843,7 @@ $reserve_id = AddReserve( C4::HoldsQueue::CreateQueue(); $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } ); is( @$holds_queue, 1, "Hold where pickup ne home, pickup eq holding targeted" ); -Koha::Holds->find( $reserve_id )->cancel; +Koha::Holds->find($reserve_id)->cancel; # Neither branch matches pickup branch $reserve_id = AddReserve( @@ -761,15 +858,15 @@ $reserve_id = AddReserve( C4::HoldsQueue::CreateQueue(); $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } ); is( @$holds_queue, 0, "Hold where pickup ne home, pickup ne holding not targeted" ); -Koha::Holds->find( $reserve_id )->cancel; +Koha::Holds->find($reserve_id)->cancel; # With hold_fulfillment_policy = any, hold should be pikcup up reguardless of matching home or holding branch $dbh->do("DELETE FROM circulation_rules"); Koha::CirculationRules->set_rules( { - branchcode => undef, - itemtype => undef, - rules => { + branchcode => undef, + itemtype => undef, + rules => { holdallowed => 'from_any_library', hold_fulfillment_policy => 'any', } @@ -789,7 +886,7 @@ $reserve_id = AddReserve( C4::HoldsQueue::CreateQueue(); $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } ); is( @$holds_queue, 1, "Hold where pickup eq home, pickup ne holding targeted" ); -Koha::Holds->find( $reserve_id )->cancel; +Koha::Holds->find($reserve_id)->cancel; # Holding branch matches pickup branch $reserve_id = AddReserve( @@ -804,7 +901,7 @@ $reserve_id = AddReserve( C4::HoldsQueue::CreateQueue(); $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } ); is( @$holds_queue, 1, "Hold where pickup ne home, pickup eq holding targeted" ); -Koha::Holds->find( $reserve_id )->cancel; +Koha::Holds->find($reserve_id)->cancel; # Neither branch matches pickup branch $reserve_id = AddReserve( @@ -819,14 +916,14 @@ $reserve_id = AddReserve( C4::HoldsQueue::CreateQueue(); $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } ); is( @$holds_queue, 1, "Hold where pickup ne home, pickup ne holding targeted" ); -Koha::Holds->find( $reserve_id )->cancel; +Koha::Holds->find($reserve_id)->cancel; # End testing hold_fulfillment_policy # Test hold itemtype limit t::lib::Mocks::mock_preference( "UseTransportCostMatrix", 0 ); -my $wrong_itemtype = $builder->build({ source => 'Itemtype', value => { notforloan => 0 } })->{itemtype}; -my $right_itemtype = $builder->build({ source => 'Itemtype', value => { notforloan => 0 } })->{itemtype}; +my $wrong_itemtype = $builder->build( { source => 'Itemtype', value => { notforloan => 0 } } )->{itemtype}; +my $right_itemtype = $builder->build( { source => 'Itemtype', value => { notforloan => 0 } } )->{itemtype}; $borrowernumber = $borrower3->{borrowernumber}; my $branchcode = $library1->{branchcode}; $dbh->do("DELETE FROM reserves"); @@ -838,29 +935,29 @@ $dbh->do("DELETE FROM transport_cost"); $dbh->do("DELETE FROM tmp_holdsqueue"); $dbh->do("DELETE FROM hold_fill_targets"); -$dbh->do("INSERT INTO biblio (frameworkcode, author, title, datecreated) VALUES ('', 'Koha test', '$TITLE', '2011-02-01')"); +$dbh->do( + "INSERT INTO biblio (frameworkcode, author, title, datecreated) VALUES ('', 'Koha test', '$TITLE', '2011-02-01')"); $biblionumber = $dbh->selectrow_array("SELECT biblionumber FROM biblio WHERE title = '$TITLE'") - or BAIL_OUT("Cannot find newly created biblio record"); + or BAIL_OUT("Cannot find newly created biblio record"); $dbh->do("INSERT INTO biblioitems (biblionumber, itemtype) VALUES ($biblionumber, '$itemtype')"); -$biblioitemnumber = - $dbh->selectrow_array("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = $biblionumber") - or BAIL_OUT("Cannot find newly created biblioitems record"); +$biblioitemnumber = $dbh->selectrow_array("SELECT biblioitemnumber FROM biblioitems WHERE biblionumber = $biblionumber") + or BAIL_OUT("Cannot find newly created biblioitems record"); -$dbh->do(" +$dbh->do( " INSERT INTO items (biblionumber, biblioitemnumber, homebranch, holdingbranch, notforloan, damaged, itemlost, withdrawn, onloan, itype, exclude_from_local_holds_priority) VALUES ($biblionumber, $biblioitemnumber, '$library_A', '$library_B', 0, 0, 0, 0, NULL, '$right_itemtype', 0) -"); +" ); # With hold_fulfillment_policy = homebranch, hold should only be picked up if pickup branch = homebranch $dbh->do("DELETE FROM circulation_rules"); Koha::CirculationRules->set_rules( { - branchcode => undef, - itemtype => undef, - rules => { + branchcode => undef, + itemtype => undef, + rules => { holdallowed => 'from_any_library', hold_fulfillment_policy => 'any', } @@ -881,7 +978,7 @@ $reserve_id = AddReserve( C4::HoldsQueue::CreateQueue(); $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } ); is( @$holds_queue, 0, "Item with incorrect itemtype not targeted" ); -Koha::Holds->find( $reserve_id )->cancel; +Koha::Holds->find($reserve_id)->cancel; # Holding branch matches pickup branch $reserve_id = AddReserve( @@ -897,7 +994,7 @@ $reserve_id = AddReserve( C4::HoldsQueue::CreateQueue(); $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } ); is( @$holds_queue, 1, "Item with matching itemtype is targeted" ); -Koha::Holds->find( $reserve_id )->cancel; +Koha::Holds->find($reserve_id)->cancel; # Neither branch matches pickup branch $reserve_id = AddReserve( @@ -912,26 +1009,26 @@ $reserve_id = AddReserve( C4::HoldsQueue::CreateQueue(); $holds_queue = $dbh->selectall_arrayref( "SELECT * FROM tmp_holdsqueue", { Slice => {} } ); is( @$holds_queue, 1, "Item targeted when hold itemtype is not set" ); -Koha::Holds->find( $reserve_id )->cancel; +Koha::Holds->find($reserve_id)->cancel; # End testing hold itemtype limit - subtest "Test Local Holds Priority - Bib level" => sub { plan tests => 3; Koha::Biblios->delete(); - t::lib::Mocks::mock_preference( 'LocalHoldsPriority', 1 ); + t::lib::Mocks::mock_preference( 'LocalHoldsPriority', 1 ); t::lib::Mocks::mock_preference( 'LocalHoldsPriorityPatronControl', 'PickupLibrary' ); - t::lib::Mocks::mock_preference( 'LocalHoldsPriorityItemControl', 'homebranch' ); - my $branch = $builder->build_object( { class => 'Koha::Libraries' } ); - my $branch2 = $builder->build_object( { class => 'Koha::Libraries' } ); - my $category = $builder->build_object( { class => 'Koha::Patron::Categories', value => {exclude_from_local_holds_priority => 0} }); + t::lib::Mocks::mock_preference( 'LocalHoldsPriorityItemControl', 'homebranch' ); + my $branch = $builder->build_object( { class => 'Koha::Libraries' } ); + my $branch2 = $builder->build_object( { class => 'Koha::Libraries' } ); + my $category = $builder->build_object( + { class => 'Koha::Patron::Categories', value => { exclude_from_local_holds_priority => 0 } } ); my $local_patron = $builder->build_object( { class => "Koha::Patrons", value => { - branchcode => $branch->branchcode, + branchcode => $branch->branchcode, categorycode => $category->categorycode } } @@ -940,7 +1037,7 @@ subtest "Test Local Holds Priority - Bib level" => sub { { class => "Koha::Patrons", value => { - branchcode => $branch2->branchcode, + branchcode => $branch2->branchcode, categorycode => $category->categorycode } } @@ -948,8 +1045,8 @@ subtest "Test Local Holds Priority - Bib level" => sub { my $biblio = $builder->build_sample_biblio(); my $item = $builder->build_sample_item( { - biblionumber => $biblio->biblionumber, - library => $branch->branchcode, + biblionumber => $biblio->biblionumber, + library => $branch->branchcode, exclude_from_local_holds_priority => 0, } ); @@ -973,10 +1070,12 @@ subtest "Test Local Holds Priority - Bib level" => sub { C4::HoldsQueue::CreateQueue(); - my $queue_rs = $schema->resultset('TmpHoldsqueue'); + my $queue_rs = $schema->resultset('TmpHoldsqueue'); my $target_rs = $schema->resultset('HoldFillTarget'); - is( $queue_rs->count(), 1, - "Hold queue contains one hold" ); + is( + $queue_rs->count(), 1, + "Hold queue contains one hold" + ); is( $queue_rs->next->borrowernumber->borrowernumber, $local_patron->borrowernumber, @@ -989,17 +1088,18 @@ subtest "Test Local Holds Priority - Item level" => sub { plan tests => 2; Koha::Biblios->delete(); - t::lib::Mocks::mock_preference( 'LocalHoldsPriority', 1 ); + t::lib::Mocks::mock_preference( 'LocalHoldsPriority', 1 ); t::lib::Mocks::mock_preference( 'LocalHoldsPriorityPatronControl', 'PickupLibrary' ); - t::lib::Mocks::mock_preference( 'LocalHoldsPriorityItemControl', 'homebranch' ); - my $branch = $builder->build_object( { class => 'Koha::Libraries' } ); - my $branch2 = $builder->build_object( { class => 'Koha::Libraries' } ); - my $category = $builder->build_object( { class => 'Koha::Patron::Categories', value => {exclude_from_local_holds_priority => 0} }); + t::lib::Mocks::mock_preference( 'LocalHoldsPriorityItemControl', 'homebranch' ); + my $branch = $builder->build_object( { class => 'Koha::Libraries' } ); + my $branch2 = $builder->build_object( { class => 'Koha::Libraries' } ); + my $category = $builder->build_object( + { class => 'Koha::Patron::Categories', value => { exclude_from_local_holds_priority => 0 } } ); my $local_patron = $builder->build_object( { class => "Koha::Patrons", value => { - branchcode => $branch->branchcode, + branchcode => $branch->branchcode, categorycode => $category->categorycode } } @@ -1008,7 +1108,7 @@ subtest "Test Local Holds Priority - Item level" => sub { { class => "Koha::Patrons", value => { - branchcode => $branch2->branchcode, + branchcode => $branch2->branchcode, categorycode => $category->categorycode } } @@ -1016,8 +1116,8 @@ subtest "Test Local Holds Priority - Item level" => sub { my $biblio = $builder->build_sample_biblio(); my $item = $builder->build_sample_item( { - biblionumber => $biblio->biblionumber, - library => $branch->branchcode, + biblionumber => $biblio->biblionumber, + library => $branch->branchcode, exclude_from_local_holds_priority => 0, } ); @@ -1044,9 +1144,11 @@ subtest "Test Local Holds Priority - Item level" => sub { C4::HoldsQueue::CreateQueue(); my $queue_rs = $schema->resultset('TmpHoldsqueue'); - my $q = $queue_rs->next; - is( $queue_rs->count(), 1, - "Hold queue contains one hold" ); + my $q = $queue_rs->next; + is( + $queue_rs->count(), 1, + "Hold queue contains one hold" + ); is( $q->borrowernumber->borrowernumber, $local_patron->borrowernumber, @@ -1058,17 +1160,18 @@ subtest "Test Local Holds Priority - Item level hold over Record level hold (Bug plan tests => 2; Koha::Biblios->delete(); - t::lib::Mocks::mock_preference( 'LocalHoldsPriority', 1 ); + t::lib::Mocks::mock_preference( 'LocalHoldsPriority', 1 ); t::lib::Mocks::mock_preference( 'LocalHoldsPriorityPatronControl', 'PickupLibrary' ); - t::lib::Mocks::mock_preference( 'LocalHoldsPriorityItemControl', 'homebranch' ); - my $branch = $builder->build_object( { class => 'Koha::Libraries' } ); - my $branch2 = $builder->build_object( { class => 'Koha::Libraries' } ); - my $category = $builder->build_object( { class => 'Koha::Patron::Categories', value => {exclude_from_local_holds_priority => 0} }); + t::lib::Mocks::mock_preference( 'LocalHoldsPriorityItemControl', 'homebranch' ); + my $branch = $builder->build_object( { class => 'Koha::Libraries' } ); + my $branch2 = $builder->build_object( { class => 'Koha::Libraries' } ); + my $category = $builder->build_object( + { class => 'Koha::Patron::Categories', value => { exclude_from_local_holds_priority => 0 } } ); my $local_patron = $builder->build_object( { class => "Koha::Patrons", value => { - branchcode => $branch->branchcode, + branchcode => $branch->branchcode, categorycode => $category->categorycode, } } @@ -1077,7 +1180,7 @@ subtest "Test Local Holds Priority - Item level hold over Record level hold (Bug { class => "Koha::Patrons", value => { - branchcode => $branch2->branchcode, + branchcode => $branch2->branchcode, categorycode => $category->categorycode, } } @@ -1085,8 +1188,8 @@ subtest "Test Local Holds Priority - Item level hold over Record level hold (Bug my $biblio = $builder->build_sample_biblio(); my $item = $builder->build_sample_item( { - biblionumber => $biblio->biblionumber, - library => $branch->branchcode, + biblionumber => $biblio->biblionumber, + library => $branch->branchcode, exclude_from_local_holds_priority => 0, } ); @@ -1112,9 +1215,11 @@ subtest "Test Local Holds Priority - Item level hold over Record level hold (Bug C4::HoldsQueue::CreateQueue(); my $queue_rs = $schema->resultset('TmpHoldsqueue'); - my $q = $queue_rs->next; - is( $queue_rs->count(), 1, - "Hold queue contains one hold" ); + my $q = $queue_rs->next; + is( + $queue_rs->count(), 1, + "Hold queue contains one hold" + ); is( $q->borrowernumber->borrowernumber, $local_patron->borrowernumber, @@ -1126,17 +1231,18 @@ subtest "Test Local Holds Priority - Get correct item for item level hold" => su plan tests => 3; Koha::Biblios->delete(); - t::lib::Mocks::mock_preference( 'LocalHoldsPriority', 1 ); + t::lib::Mocks::mock_preference( 'LocalHoldsPriority', 1 ); t::lib::Mocks::mock_preference( 'LocalHoldsPriorityPatronControl', 'PickupLibrary' ); - t::lib::Mocks::mock_preference( 'LocalHoldsPriorityItemControl', 'homebranch' ); - my $branch = $builder->build_object( { class => 'Koha::Libraries' } ); - my $branch2 = $builder->build_object( { class => 'Koha::Libraries' } ); - my $category = $builder->build_object( { class => 'Koha::Patron::Categories', value => {exclude_from_local_holds_priority => 0} }); + t::lib::Mocks::mock_preference( 'LocalHoldsPriorityItemControl', 'homebranch' ); + my $branch = $builder->build_object( { class => 'Koha::Libraries' } ); + my $branch2 = $builder->build_object( { class => 'Koha::Libraries' } ); + my $category = $builder->build_object( + { class => 'Koha::Patron::Categories', value => { exclude_from_local_holds_priority => 0 } } ); my $local_patron = $builder->build_object( { class => "Koha::Patrons", value => { - branchcode => $branch->branchcode, + branchcode => $branch->branchcode, categorycode => $category->categorycode, } } @@ -1145,7 +1251,7 @@ subtest "Test Local Holds Priority - Get correct item for item level hold" => su { class => "Koha::Patrons", value => { - branchcode => $branch2->branchcode, + branchcode => $branch2->branchcode, categorycode => $category->categorycode, } } @@ -1154,44 +1260,44 @@ subtest "Test Local Holds Priority - Get correct item for item level hold" => su my $item1 = $builder->build_sample_item( { - biblionumber => $biblio->biblionumber, - library => $branch->branchcode, + biblionumber => $biblio->biblionumber, + library => $branch->branchcode, exclude_from_local_holds_priority => 0, } ); my $item2 = $builder->build_sample_item( { - biblionumber => $biblio->biblionumber, - library => $branch->branchcode, + biblionumber => $biblio->biblionumber, + library => $branch->branchcode, exclude_from_local_holds_priority => 0, } ); my $item3 = $builder->build_sample_item( { - biblionumber => $biblio->biblionumber, - library => $branch->branchcode, + biblionumber => $biblio->biblionumber, + library => $branch->branchcode, exclude_from_local_holds_priority => 0, } ); - my $reserve_id2 = - AddReserve( - { - branchcode => $item2->homebranch, - borrowernumber => $local_patron->borrowernumber, - biblionumber => $biblio->biblionumber, - priority => 2, - itemnumber => $item2->id, - } - ); - + my $reserve_id2 = AddReserve( + { + branchcode => $item2->homebranch, + borrowernumber => $local_patron->borrowernumber, + biblionumber => $biblio->biblionumber, + priority => 2, + itemnumber => $item2->id, + } + ); C4::HoldsQueue::CreateQueue(); my $queue_rs = $schema->resultset('TmpHoldsqueue'); - my $q = $queue_rs->next; - is( $queue_rs->count(), 1, - "Hold queue contains one hold" ); + my $q = $queue_rs->next; + is( + $queue_rs->count(), 1, + "Hold queue contains one hold" + ); is( $q->borrowernumber->borrowernumber, $local_patron->borrowernumber, @@ -1209,17 +1315,18 @@ subtest "Test Local Holds Priority - Ensure no duplicate requests in holds queue $dbh->do("DELETE FROM circulation_rules"); Koha::Biblios->delete(); - t::lib::Mocks::mock_preference( 'LocalHoldsPriority', 1 ); + t::lib::Mocks::mock_preference( 'LocalHoldsPriority', 1 ); t::lib::Mocks::mock_preference( 'LocalHoldsPriorityPatronControl', 'PickupLibrary' ); - t::lib::Mocks::mock_preference( 'LocalHoldsPriorityItemControl', 'homebranch' ); - my $branch = $builder->build_object( { class => 'Koha::Libraries' } ); - my $branch2 = $builder->build_object( { class => 'Koha::Libraries' } ); - my $category = $builder->build_object( { class => 'Koha::Patron::Categories', value => {exclude_from_local_holds_priority => 0} }); - my $patron = $builder->build_object( + t::lib::Mocks::mock_preference( 'LocalHoldsPriorityItemControl', 'homebranch' ); + my $branch = $builder->build_object( { class => 'Koha::Libraries' } ); + my $branch2 = $builder->build_object( { class => 'Koha::Libraries' } ); + my $category = $builder->build_object( + { class => 'Koha::Patron::Categories', value => { exclude_from_local_holds_priority => 0 } } ); + my $patron = $builder->build_object( { class => "Koha::Patrons", value => { - branchcode => $branch->branchcode, + branchcode => $branch->branchcode, categorycode => $category->categorycode, } } @@ -1227,23 +1334,23 @@ subtest "Test Local Holds Priority - Ensure no duplicate requests in holds queue my $biblio = $builder->build_sample_biblio(); my $item1 = $builder->build_sample_item( { - biblionumber => $biblio->biblionumber, - library => $branch->branchcode, + biblionumber => $biblio->biblionumber, + library => $branch->branchcode, exclude_from_local_holds_priority => 0, } ); my $item2 = $builder->build_sample_item( { - biblionumber => $biblio->biblionumber, - library => $branch->branchcode, + biblionumber => $biblio->biblionumber, + library => $branch->branchcode, exclude_from_local_holds_priority => 0, } ); my $item3 = $builder->build_sample_item( { - biblionumber => $biblio->biblionumber, - library => $branch->branchcode, + biblionumber => $biblio->biblionumber, + library => $branch->branchcode, exclude_from_local_holds_priority => 0, } ); @@ -1261,11 +1368,12 @@ subtest "Test Local Holds Priority - Ensure no duplicate requests in holds queue my $queue_rs = $schema->resultset('TmpHoldsqueue'); - is( $queue_rs->count(), 1, - "Hold queue contains one hold from chosen from three possible items" ); + is( + $queue_rs->count(), 1, + "Hold queue contains one hold from chosen from three possible items" + ); }; - subtest "Item level holds info is preserved (Bug 25738)" => sub { plan tests => 4; @@ -1275,13 +1383,14 @@ subtest "Item level holds info is preserved (Bug 25738)" => sub { $dbh->do("DELETE FROM reserves"); $dbh->do("DELETE FROM circulation_rules"); - my $library = $builder->build_object({ class => 'Koha::Libraries' }); - my $category = $builder->build_object( { class => 'Koha::Patron::Categories', value => {exclude_from_local_holds_priority => 0} }); + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); + my $category = $builder->build_object( + { class => 'Koha::Patron::Categories', value => { exclude_from_local_holds_priority => 0 } } ); my $patron_1 = $builder->build_object( { class => "Koha::Patrons", value => { - branchcode => $library->branchcode, + branchcode => $library->branchcode, categorycode => $category->categorycode } } @@ -1291,7 +1400,7 @@ subtest "Item level holds info is preserved (Bug 25738)" => sub { { class => "Koha::Patrons", value => { - branchcode => $library->branchcode, + branchcode => $library->branchcode, categorycode => $category->categorycode } } @@ -1300,15 +1409,15 @@ subtest "Item level holds info is preserved (Bug 25738)" => sub { my $biblio = $builder->build_sample_biblio(); my $item_1 = $builder->build_sample_item( { - biblionumber => $biblio->biblionumber, - library => $library->branchcode, + biblionumber => $biblio->biblionumber, + library => $library->branchcode, exclude_from_local_holds_priority => 0, } ); my $item_2 = $builder->build_sample_item( { - biblionumber => $biblio->biblionumber, - library => $library->branchcode, + biblionumber => $biblio->biblionumber, + library => $library->branchcode, exclude_from_local_holds_priority => 0, } ); @@ -1341,8 +1450,11 @@ subtest "Item level holds info is preserved (Bug 25738)" => sub { my $queue_line_1 = $queue_rs->next; is( $queue_line_1->item_level_request, 1, 'Request is correctly advertised as item-level' ); - my $target_rs = $schema->resultset('HoldFillTarget')->search({borrowernumber=>$patron_1->borrowernumber});; - is( $target_rs->next->reserve_id, $reserve_id_1, "Reserve id correctly set in hold fill target for item level hold" ); + my $target_rs = $schema->resultset('HoldFillTarget')->search( { borrowernumber => $patron_1->borrowernumber } ); + is( + $target_rs->next->reserve_id, $reserve_id_1, + "Reserve id correctly set in hold fill target for item level hold" + ); my $queue_line_2 = $queue_rs->next; is( $queue_line_2->item_level_request, 0, 'Request is correctly advertised as biblio-level' ); @@ -1352,10 +1464,14 @@ subtest "Item level holds info is preserved (Bug 25738)" => sub { subtest 'Trivial test for UpdateTransportCostMatrix' => sub { plan tests => 1; my $recs = [ - { frombranch => $library1->{branchcode}, tobranch => $library2->{branchcode}, cost => 1, disable_transfer => 0 }, - { frombranch => $library2->{branchcode}, tobranch => $library3->{branchcode}, cost => 0, disable_transfer => 1 }, + { + frombranch => $library1->{branchcode}, tobranch => $library2->{branchcode}, cost => 1, disable_transfer => 0 + }, + { + frombranch => $library2->{branchcode}, tobranch => $library3->{branchcode}, cost => 0, disable_transfer => 1 + }, ]; - C4::HoldsQueue::UpdateTransportCostMatrix( $recs ); + C4::HoldsQueue::UpdateTransportCostMatrix($recs); is( $schema->resultset('TransportCost')->count, 2, 'UpdateTransportCostMatrix added two records' ); }; @@ -1364,19 +1480,21 @@ subtest 'Excludes from local holds priority' => sub { Koha::Holds->delete; - t::lib::Mocks::mock_preference( 'LocalHoldsPriority', 1 ); + t::lib::Mocks::mock_preference( 'LocalHoldsPriority', 1 ); t::lib::Mocks::mock_preference( 'LocalHoldsPriorityPatronControl', 'PickupLibrary' ); - t::lib::Mocks::mock_preference( 'LocalHoldsPriorityItemControl', 'homebranch' ); + t::lib::Mocks::mock_preference( 'LocalHoldsPriorityItemControl', 'homebranch' ); - my $branch = $builder->build_object( { class => 'Koha::Libraries' } ); - my $branch2 = $builder->build_object( { class => 'Koha::Libraries' } ); - my $category = $builder->build_object( { class => 'Koha::Patron::Categories', value => {exclude_from_local_holds_priority => 0} }); - my $excluded_category = $builder->build_object( { class => 'Koha::Patron::Categories', value => {exclude_from_local_holds_priority => 1} }); + my $branch = $builder->build_object( { class => 'Koha::Libraries' } ); + my $branch2 = $builder->build_object( { class => 'Koha::Libraries' } ); + my $category = $builder->build_object( + { class => 'Koha::Patron::Categories', value => { exclude_from_local_holds_priority => 0 } } ); + my $excluded_category = $builder->build_object( + { class => 'Koha::Patron::Categories', value => { exclude_from_local_holds_priority => 1 } } ); my $local_patron_excluded = $builder->build_object( { class => "Koha::Patrons", value => { - branchcode => $branch->branchcode, + branchcode => $branch->branchcode, categorycode => $excluded_category->categorycode } } @@ -1386,7 +1504,7 @@ subtest 'Excludes from local holds priority' => sub { { class => "Koha::Patrons", value => { - branchcode => $branch->branchcode, + branchcode => $branch->branchcode, categorycode => $category->categorycode } } @@ -1396,15 +1514,15 @@ subtest 'Excludes from local holds priority' => sub { { class => "Koha::Patrons", value => { - branchcode => $branch2->branchcode, + branchcode => $branch2->branchcode, categorycode => $category->categorycode } } ); - my $item1 = $builder->build_sample_item( + my $item1 = $builder->build_sample_item( { - library => $branch->branchcode, + library => $branch->branchcode, exclude_from_local_holds_priority => 0, } ); @@ -1442,14 +1560,17 @@ subtest 'Excludes from local holds priority' => sub { C4::HoldsQueue::CreateQueue(); my $queue_rs = $schema->resultset('TmpHoldsqueue'); - my $next = $queue_rs->next; - is($queue_rs->count, 1, 'Only 1 patron queueud' ); - is($next->borrowernumber->borrowernumber, $local_patron_not_excluded->borrowernumber, 'Not excluded local patron is queued'); + my $next = $queue_rs->next; + is( $queue_rs->count, 1, 'Only 1 patron queueud' ); + is( + $next->borrowernumber->borrowernumber, $local_patron_not_excluded->borrowernumber, + 'Not excluded local patron is queued' + ); - my $item2 = $builder->build_sample_item( + my $item2 = $builder->build_sample_item( { - biblionumber => $item1->biblionumber, - library => $branch->branchcode, + biblionumber => $item1->biblionumber, + library => $branch->branchcode, exclude_from_local_holds_priority => 1, } ); @@ -1458,9 +1579,12 @@ subtest 'Excludes from local holds priority' => sub { $queue_rs = $schema->resultset('TmpHoldsqueue'); is( $queue_rs->count, 2, '2 patrons queued' ); $next = $queue_rs->next; - is($next->borrowernumber->borrowernumber, $local_patron_not_excluded->borrowernumber, 'Not excluded local patron is queued'); + is( + $next->borrowernumber->borrowernumber, $local_patron_not_excluded->borrowernumber, + 'Not excluded local patron is queued' + ); $next = $queue_rs->next; - is($next->borrowernumber->borrowernumber, $other_patron->borrowernumber, 'Other patron is queued'); + is( $next->borrowernumber->borrowernumber, $other_patron->borrowernumber, 'Other patron is queued' ); $item1->exclude_from_local_holds_priority(1)->store; @@ -1469,9 +1593,12 @@ subtest 'Excludes from local holds priority' => sub { $queue_rs = $schema->resultset('TmpHoldsqueue'); is( $queue_rs->count, 2, '2 patrons queued' ); $next = $queue_rs->next; - is($next->borrowernumber->borrowernumber, $other_patron->borrowernumber, 'Other patron is queued'); + is( $next->borrowernumber->borrowernumber, $other_patron->borrowernumber, 'Other patron is queued' ); $next = $queue_rs->next; - is($next->borrowernumber->borrowernumber, $local_patron_excluded->borrowernumber, 'Excluded local patron is queued'); + is( + $next->borrowernumber->borrowernumber, $local_patron_excluded->borrowernumber, + 'Excluded local patron is queued' + ); }; subtest "Test item group holds" => sub { @@ -1483,16 +1610,17 @@ subtest "Test item group holds" => sub { $dbh->do("DELETE FROM reserves"); $dbh->do("DELETE FROM circulation_rules"); - t::lib::Mocks::mock_preference('HoldsQueueSkipClosed', 0); - t::lib::Mocks::mock_preference('LocalHoldsPriority', 0); + t::lib::Mocks::mock_preference( 'HoldsQueueSkipClosed', 0 ); + t::lib::Mocks::mock_preference( 'LocalHoldsPriority', 0 ); - my $library = $builder->build_object({ class => 'Koha::Libraries' }); - my $category = $builder->build_object( { class => 'Koha::Patron::Categories', value => {exclude_from_local_holds_priority => 0} }); + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); + my $category = $builder->build_object( + { class => 'Koha::Patron::Categories', value => { exclude_from_local_holds_priority => 0 } } ); my $patron_1 = $builder->build_object( { class => "Koha::Patrons", value => { - branchcode => $library->branchcode, + branchcode => $library->branchcode, categorycode => $category->categorycode } } @@ -1502,7 +1630,7 @@ subtest "Test item group holds" => sub { { class => "Koha::Patrons", value => { - branchcode => $library->branchcode, + branchcode => $library->branchcode, categorycode => $category->categorycode } } @@ -1512,7 +1640,7 @@ subtest "Test item group holds" => sub { { class => "Koha::Patrons", value => { - branchcode => $library->branchcode, + branchcode => $library->branchcode, categorycode => $category->categorycode } } @@ -1522,7 +1650,7 @@ subtest "Test item group holds" => sub { { class => "Koha::Patrons", value => { - branchcode => $library->branchcode, + branchcode => $library->branchcode, categorycode => $category->categorycode } } @@ -1532,29 +1660,29 @@ subtest "Test item group holds" => sub { my $item_1 = $builder->build_sample_item( { - biblionumber => $biblio->biblionumber, - library => $library->branchcode, + biblionumber => $biblio->biblionumber, + library => $library->branchcode, exclude_from_local_holds_priority => 0, } ); my $item_2 = $builder->build_sample_item( { - biblionumber => $biblio->biblionumber, - library => $library->branchcode, + biblionumber => $biblio->biblionumber, + library => $library->branchcode, exclude_from_local_holds_priority => 0, } ); my $item_3 = $builder->build_sample_item( { - biblionumber => $biblio->biblionumber, - library => $library->branchcode, + biblionumber => $biblio->biblionumber, + library => $library->branchcode, exclude_from_local_holds_priority => 0, } ); my $item_4 = $builder->build_sample_item( { - biblionumber => $biblio->biblionumber, - library => $library->branchcode, + biblionumber => $biblio->biblionumber, + library => $library->branchcode, exclude_from_local_holds_priority => 0, } ); @@ -1562,8 +1690,8 @@ subtest "Test item group holds" => sub { my $item_group_1 = Koha::Biblio::ItemGroup->new( { biblio_id => $biblio->id } )->store(); my $item_group_2 = Koha::Biblio::ItemGroup->new( { biblio_id => $biblio->id } )->store(); - $item_group_1->add_item({ item_id => $item_1->id }); - $item_group_1->add_item({ item_id => $item_2->id }); + $item_group_1->add_item( { item_id => $item_1->id } ); + $item_group_1->add_item( { item_id => $item_2->id } ); # Add item-level hold for patron_1 my $reserve_id_1 = AddReserve( @@ -1614,13 +1742,22 @@ subtest "Test item group holds" => sub { is( $queue_rs->count(), 3, "Hold queue contains two holds" ); my $queue_line_1 = $queue_rs->next; - is( $queue_line_1->borrowernumber->id, $patron_1->id, "Correct Hold was filled for the correct patron, item group 1, priority 1" ); + is( + $queue_line_1->borrowernumber->id, $patron_1->id, + "Correct Hold was filled for the correct patron, item group 1, priority 1" + ); my $queue_line_2 = $queue_rs->next; - is( $queue_line_2->borrowernumber->id, $patron_3->id, "Correct Hold was filled for the correct patron, item group 1, priority 2" ); + is( + $queue_line_2->borrowernumber->id, $patron_3->id, + "Correct Hold was filled for the correct patron, item group 1, priority 2" + ); my $queue_line_3 = $queue_rs->next; - is( $queue_line_3->borrowernumber->id, $patron_4->id, "Correct Hold was filled for the correct patron, no item group" ); + is( + $queue_line_3->borrowernumber->id, $patron_4->id, + "Correct Hold was filled for the correct patron, no item group" + ); }; # Cleanup @@ -1629,24 +1766,25 @@ $schema->storage->txn_rollback; ### END Test holds queue builder does not violate holds policy ### sub test_queue { - my ($test_name, $use_cost_matrix, $pick_branch, $hold_branch) = @_; + my ( $test_name, $use_cost_matrix, $pick_branch, $hold_branch ) = @_; - $test_name = "$test_name (".($use_cost_matrix ? "" : "don't ")."use cost matrix)"; + $test_name = "$test_name (" . ( $use_cost_matrix ? "" : "don't " ) . "use cost matrix)"; $use_cost_matrix_sth->execute($use_cost_matrix); C4::Context->clear_syspref_cache(); C4::HoldsQueue::CreateQueue(); - my $results = $dbh->selectall_arrayref($test_sth, { Slice => {} }); # should be only one - my $r = $results->[0]; + my $results = $dbh->selectall_arrayref( $test_sth, { Slice => {} } ); # should be only one + my $r = $results->[0]; - my $ok = is( $r->{pickbranch}, $pick_branch, "$test_name pick up branch"); - $ok &&= is( $r->{holdingbranch}, $hold_branch, "$test_name holding branch") - if $hold_branch; + my $ok = is( $r->{pickbranch}, $pick_branch, "$test_name pick up branch" ); + $ok &&= is( $r->{holdingbranch}, $hold_branch, "$test_name holding branch" ) + if $hold_branch; - diag( "Wrong pick-up/hold for first target (pick_branch, hold_branch, reserves, hold_fill_targets, tmp_holdsqueue): " - . Dumper ($pick_branch, $hold_branch, map dump_records($_), qw(reserves hold_fill_targets tmp_holdsqueue)) ) - unless $ok; + diag( + "Wrong pick-up/hold for first target (pick_branch, hold_branch, reserves, hold_fill_targets, tmp_holdsqueue): " + . Dumper( $pick_branch, $hold_branch, map dump_records($_), qw(reserves hold_fill_targets tmp_holdsqueue) ) + ) unless $ok; # Test enforcement of branch transfer limit if ( $r->{pickbranch} ne $r->{holdingbranch} ) { @@ -1660,10 +1798,12 @@ sub test_queue { )->store(); C4::Context->clear_syspref_cache(); C4::HoldsQueue::CreateQueue(); - $results = $dbh->selectall_arrayref( $test_sth, { Slice => {} } ) - ; # should be only one + $results = $dbh->selectall_arrayref( $test_sth, { Slice => {} } ); # should be only one my $s = $results->[0]; - isnt( $r->{holdingbranch}, $s->{holdingbranch}, 'Hold is not trapped for pickup at a branch that cannot be transferred to'); + isnt( + $r->{holdingbranch}, $s->{holdingbranch}, + 'Hold is not trapped for pickup at a branch that cannot be transferred to' + ); $limit->delete(); t::lib::Mocks::mock_preference( 'UseBranchTransferLimits', '0' ); @@ -1679,15 +1819,16 @@ subtest "Test _checkHoldPolicy" => sub { $schema->storage->txn_begin; - my $library1 = $builder->build_object( { class => 'Koha::Libraries' } ); - my $library2 = $builder->build_object( { class => 'Koha::Libraries' } ); + my $library1 = $builder->build_object( { class => 'Koha::Libraries' } ); + my $library2 = $builder->build_object( { class => 'Koha::Libraries' } ); my $library_nongroup = $builder->build_object( { class => 'Koha::Libraries' } ); - my $category = $builder->build_object( { class => 'Koha::Patron::Categories', value => {exclude_from_local_holds_priority => 0} }); - my $patron = $builder->build_object( + my $category = $builder->build_object( + { class => 'Koha::Patron::Categories', value => { exclude_from_local_holds_priority => 0 } } ); + my $patron = $builder->build_object( { class => "Koha::Patrons", value => { - branchcode => $library1->branchcode, + branchcode => $library1->branchcode, categorycode => $category->categorycode, } } @@ -1695,8 +1836,8 @@ subtest "Test _checkHoldPolicy" => sub { my $biblio = $builder->build_sample_biblio(); my $item1 = $builder->build_sample_item( { - biblionumber => $biblio->biblionumber, - library => $library1->branchcode, + biblionumber => $biblio->biblionumber, + library => $library1->branchcode, exclude_from_local_holds_priority => 0, } ); @@ -1709,22 +1850,22 @@ subtest "Test _checkHoldPolicy" => sub { priority => 1 } ); - ok( $reserve_id, "Hold was created"); - my $requests = C4::HoldsQueue::GetPendingHoldRequestsForBib({ biblionumber => $biblio->biblionumber}); - is( @$requests, 1, "Got correct number of holds"); + ok( $reserve_id, "Hold was created" ); + my $requests = C4::HoldsQueue::GetPendingHoldRequestsForBib( { biblionumber => $biblio->biblionumber } ); + is( @$requests, 1, "Got correct number of holds" ); my $request = $requests->[0]; - is( $request->{biblionumber}, $biblio->id, "Hold has correct biblio"); - is( $request->{borrowernumber}, $patron->id, "Hold has correct borrower"); - is( $request->{borrowerbranch}, $patron->branchcode, "Hold has correct borrowerbranch"); + is( $request->{biblionumber}, $biblio->id, "Hold has correct biblio" ); + is( $request->{borrowernumber}, $patron->id, "Hold has correct borrower" ); + is( $request->{borrowerbranch}, $patron->branchcode, "Hold has correct borrowerbranch" ); - my $hold = Koha::Holds->find( $reserve_id ); + my $hold = Koha::Holds->find($reserve_id); ok( $hold, "Found hold" ); my $item = { - holdallowed => 'from_home_library', - homebranch => $request->{borrowerbranch}, # library1 - hold_fulfillment_policy => 'any' + holdallowed => 'from_home_library', + homebranch => $request->{borrowerbranch}, # library1 + hold_fulfillment_policy => 'any' }; # Base case should work @@ -1732,78 +1873,153 @@ subtest "Test _checkHoldPolicy" => sub { # Test holdallowed = 'not_allowed' $item->{holdallowed} = 'not_allowed'; - is( C4::HoldsQueue::_checkHoldPolicy( $item, $request ), 0, "_checkHoldPolicy returns false if holdallowed = not_allowed" ); + is( + C4::HoldsQueue::_checkHoldPolicy( $item, $request ), 0, + "_checkHoldPolicy returns false if holdallowed = not_allowed" + ); # Test holdallowed = 'from_home_library' $item->{holdallowed} = 'from_home_library'; - $item->{homebranch} = $library_nongroup->id; - is( C4::HoldsQueue::_checkHoldPolicy( $item, $request ), 0, "_checkHoldPolicy returns false if holdallowed = from_home_library and branches do not match" ); + $item->{homebranch} = $library_nongroup->id; + is( + C4::HoldsQueue::_checkHoldPolicy( $item, $request ), 0, + "_checkHoldPolicy returns false if holdallowed = from_home_library and branches do not match" + ); $item->{homebranch} = $request->{borrowerbranch}; - is( C4::HoldsQueue::_checkHoldPolicy( $item, $request ), 1, "_checkHoldPolicy returns true if holdallowed = from_home_library and branches do match" ); + is( + C4::HoldsQueue::_checkHoldPolicy( $item, $request ), 1, + "_checkHoldPolicy returns true if holdallowed = from_home_library and branches do match" + ); # Test holdallowed = 3 $item->{holdallowed} = 'from_local_hold_group'; - $item->{homebranch} = $library_nongroup->id; - is( C4::HoldsQueue::_checkHoldPolicy( $item, $request ), 0, "_checkHoldPolicy returns false if branchode doesn't match, holdallowed = from_local_hold_group and no group branches exist" ); + $item->{homebranch} = $library_nongroup->id; + is( + C4::HoldsQueue::_checkHoldPolicy( $item, $request ), 0, + "_checkHoldPolicy returns false if branchode doesn't match, holdallowed = from_local_hold_group and no group branches exist" + ); $item->{homebranch} = $request->{borrowerbranch}; - is( C4::HoldsQueue::_checkHoldPolicy( $item, $request ), 1, "_checkHoldPolicy returns true if branchode matches, holdallowed = from_local_hold_group and no group branches exist" ); + is( + C4::HoldsQueue::_checkHoldPolicy( $item, $request ), 1, + "_checkHoldPolicy returns true if branchode matches, holdallowed = from_local_hold_group and no group branches exist" + ); # Create library groups hierarchy - my $rootgroup = $builder->build_object( { class => 'Koha::Library::Groups', value => {ft_local_hold_group => 1} } ); - my $group1 = $builder->build_object( { class => 'Koha::Library::Groups', value => {parent_id => $rootgroup->id, branchcode => $library1->branchcode}} ); - my $group2 = $builder->build_object( { class => 'Koha::Library::Groups', value => {parent_id => $rootgroup->id, branchcode => $library2->branchcode}} ); + my $rootgroup = + $builder->build_object( { class => 'Koha::Library::Groups', value => { ft_local_hold_group => 1 } } ); + my $group1 = $builder->build_object( + { + class => 'Koha::Library::Groups', + value => { parent_id => $rootgroup->id, branchcode => $library1->branchcode } + } + ); + my $group2 = $builder->build_object( + { + class => 'Koha::Library::Groups', + value => { parent_id => $rootgroup->id, branchcode => $library2->branchcode } + } + ); - is( C4::HoldsQueue::_checkHoldPolicy( $item, $request ), 1, "_checkHoldPolicy returns true if holdallowed = from_local_hold_group and no group branches exist" ); + is( + C4::HoldsQueue::_checkHoldPolicy( $item, $request ), 1, + "_checkHoldPolicy returns true if holdallowed = from_local_hold_group and no group branches exist" + ); $group1->delete; # Test hold_fulfillment_policy = holdgroup $item->{hold_fulfillment_policy} = 'holdgroup'; - $item->{homebranch} = $library_nongroup->id; - is( C4::HoldsQueue::_checkHoldPolicy( $item, $request ), 0, "_checkHoldPolicy returns true if library is not part of hold group, branches don't match and hfp = holdgroup" ); + $item->{homebranch} = $library_nongroup->id; + is( + C4::HoldsQueue::_checkHoldPolicy( $item, $request ), 0, + "_checkHoldPolicy returns true if library is not part of hold group, branches don't match and hfp = holdgroup" + ); $item->{homebranch} = $request->{borrowerbranch}; - is( C4::HoldsQueue::_checkHoldPolicy( $item, $request ), 1, "_checkHoldPolicy returns true if library is not part of hold group, branches match and hfp = holdgroup" ); + is( + C4::HoldsQueue::_checkHoldPolicy( $item, $request ), 1, + "_checkHoldPolicy returns true if library is not part of hold group, branches match and hfp = holdgroup" + ); - $group1 = $builder->build_object( { class => 'Koha::Library::Groups', value => {parent_id => $rootgroup->id, branchcode => $library1->branchcode}} ); - is( C4::HoldsQueue::_checkHoldPolicy( $item, $request ), 1, "_checkHoldPolicy returns true if library is part of hold group with hfp = holdgroup" ); + $group1 = $builder->build_object( + { + class => 'Koha::Library::Groups', + value => { parent_id => $rootgroup->id, branchcode => $library1->branchcode } + } + ); + is( + C4::HoldsQueue::_checkHoldPolicy( $item, $request ), 1, + "_checkHoldPolicy returns true if library is part of hold group with hfp = holdgroup" + ); $item->{homebranch} = $library2->id; - is( C4::HoldsQueue::_checkHoldPolicy( $item, $request ), 1, "_checkHoldPolicy returns true if library is part of hold group with hfp = holdgroup" ); + is( + C4::HoldsQueue::_checkHoldPolicy( $item, $request ), 1, + "_checkHoldPolicy returns true if library is part of hold group with hfp = holdgroup" + ); $item->{homebranch} = $library1->id; $group1->delete; # Test hold_fulfillment_policy = homebranch $item->{hold_fulfillment_policy} = 'homebranch'; - $item->{homebranch} = $library_nongroup->id; - is( C4::HoldsQueue::_checkHoldPolicy( $item, $request ), 0, "_checkHoldPolicy returns false if hfp = homebranch and pickup branch != item homebranch" ); + $item->{homebranch} = $library_nongroup->id; + is( + C4::HoldsQueue::_checkHoldPolicy( $item, $request ), 0, + "_checkHoldPolicy returns false if hfp = homebranch and pickup branch != item homebranch" + ); $item->{homebranch} = $request->{borrowerbranch}; - is( C4::HoldsQueue::_checkHoldPolicy( $item, $request ), 1, "_checkHoldPolicy returns true if hfp = homebranch and pickup branch = item homebranch" ); + is( + C4::HoldsQueue::_checkHoldPolicy( $item, $request ), 1, + "_checkHoldPolicy returns true if hfp = homebranch and pickup branch = item homebranch" + ); # Test hold_fulfillment_policy = holdingbranch $item->{hold_fulfillment_policy} = 'holdingbranch'; - $item->{holdingbranch} = $library_nongroup->id; - is( C4::HoldsQueue::_checkHoldPolicy( $item, $request ), 0, "_checkHoldPolicy returns false if hfp = holdingbranch and pickup branch != item holdingbranch" ); + $item->{holdingbranch} = $library_nongroup->id; + is( + C4::HoldsQueue::_checkHoldPolicy( $item, $request ), 0, + "_checkHoldPolicy returns false if hfp = holdingbranch and pickup branch != item holdingbranch" + ); $item->{holdingbranch} = $request->{borrowerbranch}; - is( C4::HoldsQueue::_checkHoldPolicy( $item, $request ), 1, "_checkHoldPolicy returns true if hfp = holdingbranch and pickup branch = item holdingbranch" ); + is( + C4::HoldsQueue::_checkHoldPolicy( $item, $request ), 1, + "_checkHoldPolicy returns true if hfp = holdingbranch and pickup branch = item holdingbranch" + ); # Test hold_fulfillment_policy = patrongroup $item->{hold_fulfillment_policy} = 'patrongroup'; - $item->{borrowerbranch} = $library1->id; + $item->{borrowerbranch} = $library1->id; $item->{homebranch} = $library_nongroup->id; - is( C4::HoldsQueue::_checkHoldPolicy( $item, $request ), 0, "_checkHoldPolicy returns false if library is not part of hold group, branches don't match, hfp = patrongroup" ); + is( + C4::HoldsQueue::_checkHoldPolicy( $item, $request ), 0, + "_checkHoldPolicy returns false if library is not part of hold group, branches don't match, hfp = patrongroup" + ); $item->{homebranch} = $request->{borrowerbranch}; - is( C4::HoldsQueue::_checkHoldPolicy( $item, $request ), 1, "_checkHoldPolicy returns false if library is not part of hold group, branches match, hfp = patrongroup" ); + is( + C4::HoldsQueue::_checkHoldPolicy( $item, $request ), 1, + "_checkHoldPolicy returns false if library is not part of hold group, branches match, hfp = patrongroup" + ); - $group1 = $builder->build_object( { class => 'Koha::Library::Groups', value => {parent_id => $rootgroup->id, branchcode => $library1->branchcode}} ); - is( C4::HoldsQueue::_checkHoldPolicy( $item, $request ), 1, "_checkHoldPolicy returns true if library is part of hold group with hfp = holdgroup" ); + $group1 = $builder->build_object( + { + class => 'Koha::Library::Groups', + value => { parent_id => $rootgroup->id, branchcode => $library1->branchcode } + } + ); + is( + C4::HoldsQueue::_checkHoldPolicy( $item, $request ), 1, + "_checkHoldPolicy returns true if library is part of hold group with hfp = holdgroup" + ); $item->{borrowerbranch} = $library2->id; - is( C4::HoldsQueue::_checkHoldPolicy( $item, $request ), 1, "_checkHoldPolicy returns true if library is part of hold group with hfp = holdgroup" ); + is( + C4::HoldsQueue::_checkHoldPolicy( $item, $request ), 1, + "_checkHoldPolicy returns true if library is part of hold group with hfp = holdgroup" + ); $item->{borrowerbranch} = $library1->id; $schema->storage->txn_rollback; @@ -1811,7 +2027,10 @@ subtest "Test _checkHoldPolicy" => sub { sub dump_records { my ($tablename) = @_; - return $dbh->selectall_arrayref("SELECT * from $tablename where borrowernumber = ?", { Slice => {} }, $borrowernumber); + return $dbh->selectall_arrayref( + "SELECT * from $tablename where borrowernumber = ?", { Slice => {} }, + $borrowernumber + ); } subtest 'Remove holds on check-in match' => sub { @@ -1835,8 +2054,7 @@ subtest 'Remove holds on check-in match' => sub { } ); - my $item = $builder->build_sample_item( - { homebranch => $lib->branchcode, holdingbranch => $lib->branchcode } ); + my $item = $builder->build_sample_item( { homebranch => $lib->branchcode, holdingbranch => $lib->branchcode } ); t::lib::Mocks::mock_userenv( { branchcode => $lib->branchcode } ); @@ -1858,7 +2076,8 @@ subtest 'Remove holds on check-in match' => sub { C4::HoldsQueue::CreateQueue(); - my $sth = $dbh->prepare(q{ + my $sth = $dbh->prepare( + q{ SELECT COUNT(*) FROM tmp_holdsqueue q INNER JOIN hold_fill_targets t @@ -1868,22 +2087,27 @@ subtest 'Remove holds on check-in match' => sub { AND q.item_level_request = t.item_level_request AND q.holdingbranch = t.source_branchcode WHERE t.reserve_id = ? - }); - $sth->execute($hold->reserve_id); + } + ); + $sth->execute( $hold->reserve_id ); my ($count_1) = $sth->fetchrow_array; is( $count_1, 1, "Holds queue has one element" ); AddReturn( $item->barcode, $item->homebranch, undef, dt_from_string ); - ModReserveAffect( $item->itemnumber, $hold->borrowernumber, 0, - $hold->reserve_id ); + ModReserveAffect( + $item->itemnumber, $hold->borrowernumber, 0, + $hold->reserve_id + ); - $sth->execute($hold->reserve_id); + $sth->execute( $hold->reserve_id ); my ($count_2) = $sth->fetchrow_array; - is( $count_2, 0, - "Holds queue has no elements, even when queue was not rebuilt" ); + is( + $count_2, 0, + "Holds queue has no elements, even when queue was not rebuilt" + ); $schema->storage->txn_rollback; }; @@ -1896,17 +2120,13 @@ subtest "GetHoldsQueueItems" => sub { my $ccode = $builder->build_object( { class => 'Koha::AuthorisedValues', - value => { - category => 'CCODE' - } + value => { category => 'CCODE' } } ); my $location = $builder->build_object( { class => 'Koha::AuthorisedValues', - value => { - category => 'LOC' - } + value => { category => 'LOC' } } ); my $item_1 = $builder->build_sample_item(); @@ -1947,13 +2167,16 @@ subtest "GetHoldsQueueItems" => sub { is( $queue_items->count, $count + 3, 'Three items added to queue' ); $queue_items = GetHoldsQueueItems( { itemtypeslimit => $item_1->itype } ); - is( $queue_items->count, - 3, 'Three items of same itemtype found when itemtypeslimit passed' ); + is( + $queue_items->count, + 3, 'Three items of same itemtype found when itemtypeslimit passed' + ); - $queue_items = GetHoldsQueueItems( - { itemtypeslimit => $item_1->itype, ccodeslimit => $item_2->ccode } ); - is( $queue_items->count, - 2, 'Two items of same collection found when ccodeslimit passed' ); + $queue_items = GetHoldsQueueItems( { itemtypeslimit => $item_1->itype, ccodeslimit => $item_2->ccode } ); + is( + $queue_items->count, + 2, 'Two items of same collection found when ccodeslimit passed' + ); $queue_items = GetHoldsQueueItems( { @@ -1962,8 +2185,10 @@ subtest "GetHoldsQueueItems" => sub { locationslimit => $item_3->location } ); - is( scalar $queue_items->count, - 1, 'One item of shleving location found when locationslimit passed' ); + is( + scalar $queue_items->count, + 1, 'One item of shleving location found when locationslimit passed' + ); $schema->storage->txn_rollback; }; @@ -1974,34 +2199,34 @@ subtest "Test HoldsQueuePrioritizeBranch" => sub { $schema->storage->txn_begin; - t::lib::Mocks::mock_preference( 'LocalHoldsPriority', 0 ); + t::lib::Mocks::mock_preference( 'LocalHoldsPriority', 0 ); t::lib::Mocks::mock_preference( 'UseTransportCostMatrix', 0 ); - my $branch1 = $builder->build_object( { class => 'Koha::Libraries' } ); - my $branch2 = $builder->build_object( { class => 'Koha::Libraries' } ); - my $category = $builder->build_object( { class => 'Koha::Patron::Categories' }); - my $patron = $builder->build_object( + my $branch1 = $builder->build_object( { class => 'Koha::Libraries' } ); + my $branch2 = $builder->build_object( { class => 'Koha::Libraries' } ); + my $category = $builder->build_object( { class => 'Koha::Patron::Categories' } ); + my $patron = $builder->build_object( { class => "Koha::Patrons", value => { - branchcode => $branch1->branchcode, + branchcode => $branch1->branchcode, categorycode => $category->categorycode } } ); my $biblio = $builder->build_sample_biblio(); - my $item1 = $builder->build_sample_item( + my $item1 = $builder->build_sample_item( { - biblionumber => $biblio->biblionumber, - library => $branch1->branchcode, + biblionumber => $biblio->biblionumber, + library => $branch1->branchcode, } )->holdingbranch( $branch2->id )->store(); - my $item2 = $builder->build_sample_item( + my $item2 = $builder->build_sample_item( { - biblionumber => $biblio->biblionumber, - library => $branch1->branchcode, + biblionumber => $biblio->biblionumber, + library => $branch1->branchcode, } )->homebranch( $branch2->id )->store(); @@ -2018,7 +2243,7 @@ subtest "Test HoldsQueuePrioritizeBranch" => sub { C4::HoldsQueue::CreateQueue(); - my $queue_rs = $schema->resultset('TmpHoldsqueue')->search({ biblionumber => $biblio->biblionumber }); + my $queue_rs = $schema->resultset('TmpHoldsqueue')->search( { biblionumber => $biblio->biblionumber } ); is( $queue_rs->next->itemnumber->itemnumber, $item1->itemnumber, @@ -2029,7 +2254,7 @@ subtest "Test HoldsQueuePrioritizeBranch" => sub { C4::HoldsQueue::CreateQueue(); - $queue_rs = $schema->resultset('TmpHoldsqueue')->search({ biblionumber => $biblio->biblionumber }); + $queue_rs = $schema->resultset('TmpHoldsqueue')->search( { biblionumber => $biblio->biblionumber } ); is( $queue_rs->next->itemnumber->itemnumber, $item2->itemnumber, @@ -2040,7 +2265,7 @@ subtest "Test HoldsQueuePrioritizeBranch" => sub { C4::HoldsQueue::CreateQueue(); - $queue_rs = $schema->resultset('TmpHoldsqueue')->search({ biblionumber => $biblio->biblionumber }); + $queue_rs = $schema->resultset('TmpHoldsqueue')->search( { biblionumber => $biblio->biblionumber } ); is( $queue_rs->next->itemnumber->itemnumber, $item1->itemnumber, @@ -2051,7 +2276,7 @@ subtest "Test HoldsQueuePrioritizeBranch" => sub { C4::HoldsQueue::CreateQueue(); - $queue_rs = $schema->resultset('TmpHoldsqueue')->search({ biblionumber => $biblio->biblionumber }); + $queue_rs = $schema->resultset('TmpHoldsqueue')->search( { biblionumber => $biblio->biblionumber } ); is( $queue_rs->next->itemnumber->itemnumber, $item2->itemnumber, @@ -2067,28 +2292,46 @@ subtest "GetItemsAvailableToFillHoldsRequestsForBib" => sub { $schema->storage->txn_begin; my $item_1 = $builder->build_sample_item(); - my $item_2 = $builder->build_sample_item({ biblionumber => $item_1->biblionumber }); - my $item_3 = $builder->build_sample_item({ biblionumber => $item_1->biblionumber }); + my $item_2 = $builder->build_sample_item( { biblionumber => $item_1->biblionumber } ); + my $item_3 = $builder->build_sample_item( { biblionumber => $item_1->biblionumber } ); - my $transfer_1 = $builder->build_object({ class => 'Koha::Item::Transfers', value => { - itemnumber => $item_1->itemnumber, - datearrived => undef, - datecancelled => undef - }}); - my $transfer_2 = $builder->build_object({ class => 'Koha::Item::Transfers', value => { - itemnumber => $item_2->itemnumber, - datearrived => dt_from_string, - datecancelled => undef - }}); - my $transfer_3 = $builder->build_object({ class => 'Koha::Item::Transfers', value => { - itemnumber => $item_3->itemnumber, - datearrived => undef, - datecancelled => dt_from_string - }}); + my $transfer_1 = $builder->build_object( + { + class => 'Koha::Item::Transfers', + value => { + itemnumber => $item_1->itemnumber, + datearrived => undef, + datecancelled => undef + } + } + ); + my $transfer_2 = $builder->build_object( + { + class => 'Koha::Item::Transfers', + value => { + itemnumber => $item_2->itemnumber, + datearrived => dt_from_string, + datecancelled => undef + } + } + ); + my $transfer_3 = $builder->build_object( + { + class => 'Koha::Item::Transfers', + value => { + itemnumber => $item_3->itemnumber, + datearrived => undef, + datecancelled => dt_from_string + } + } + ); my $items = C4::HoldsQueue::GetItemsAvailableToFillHoldRequestsForBib( $item_1->biblionumber ); - is( scalar @$items, 2, "Two items without active transfers correctly retrieved"); - is_deeply( [$items->[0]->{itemnumber},$items->[1]->{itemnumber}],[$item_2->itemnumber,$item_3->itemnumber],"Correct two items retrieved"); + is( scalar @$items, 2, "Two items without active transfers correctly retrieved" ); + is_deeply( + [ $items->[0]->{itemnumber}, $items->[1]->{itemnumber} ], [ $item_2->itemnumber, $item_3->itemnumber ], + "Correct two items retrieved" + ); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/Holidays.t b/t/db_dependent/Holidays.t index db169e8e2a..c15ae674e9 100755 --- a/t/db_dependent/Holidays.t +++ b/t/db_dependent/Holidays.t @@ -30,11 +30,14 @@ use Koha::DateUtils qw( dt_from_string ); BEGIN { use_ok('Koha::Calendar'); - use_ok('C4::Calendar', qw( insert_exception_holiday insert_week_day_holiday insert_day_month_holiday insert_single_holiday copy_to_branch get_exception_holidays isHoliday )); + use_ok( + 'C4::Calendar', + qw( insert_exception_holiday insert_week_day_holiday insert_day_month_holiday insert_single_holiday copy_to_branch get_exception_holidays isHoliday ) + ); } -my $schema = Koha::Database->new->schema; -my $dbh = C4::Context->dbh; +my $schema = Koha::Database->new->schema; +my $dbh = C4::Context->dbh; my $builder = t::lib::TestBuilder->new; subtest 'is_holiday timezone tests' => sub { @@ -44,6 +47,7 @@ subtest 'is_holiday timezone tests' => sub { $schema->storage->txn_begin; $dbh->do("DELETE FROM special_holidays"); + # Clear cache Koha::Caches->get_instance->flush_all; @@ -53,7 +57,7 @@ subtest 'is_holiday timezone tests' => sub { use POSIX qw(tzset); tzset; - my $branch = $builder->build( { source => 'Branch' } )->{branchcode}; + my $branch = $builder->build( { source => 'Branch' } )->{branchcode}; my $calendar = Koha::Calendar->new( branchcode => $branch ); C4::Calendar->new( branchcode => $branch )->insert_exception_holiday( @@ -81,8 +85,8 @@ subtest 'is_holiday timezone tests' => sub { $schema->storage->txn_begin; # Create two fresh branches for the tests -my $branch_1 = $builder->build({ source => 'Branch' })->{ branchcode }; -my $branch_2 = $builder->build({ source => 'Branch' })->{ branchcode }; +my $branch_1 = $builder->build( { source => 'Branch' } )->{branchcode}; +my $branch_2 = $builder->build( { source => 'Branch' } )->{branchcode}; C4::Calendar->new( branchcode => $branch_1 )->insert_week_day_holiday( weekday => 0, @@ -108,7 +112,7 @@ C4::Calendar->new( branchcode => $branch_1 )->insert_day_month_holiday( ); my $koha_calendar = Koha::Calendar->new( branchcode => $branch_1 ); -my $c4_calendar = C4::Calendar->new( branchcode => $branch_1 ); +my $c4_calendar = C4::Calendar->new( branchcode => $branch_1 ); isa_ok( $koha_calendar, 'Koha::Calendar', 'Koha::Calendar class returned' ); isa_ok( $c4_calendar, 'C4::Calendar', 'C4::Calendar class returned' ); @@ -157,8 +161,8 @@ C4::Calendar->new( branchcode => $branch_2 )->insert_single_holiday( description => "$today", ); -is( Koha::Calendar->new( branchcode => $branch_2 )->is_holiday( $today ), 1, "Today is a holiday for $branch_2" ); -is( Koha::Calendar->new( branchcode => $branch_1 )->is_holiday( $today ), 0, "Today is not a holiday for $branch_1"); +is( Koha::Calendar->new( branchcode => $branch_2 )->is_holiday($today), 1, "Today is a holiday for $branch_2" ); +is( Koha::Calendar->new( branchcode => $branch_1 )->is_holiday($today), 0, "Today is not a holiday for $branch_1" ); $schema->storage->txn_rollback; @@ -168,9 +172,9 @@ subtest 'copy_to_branch' => sub { $schema->storage->txn_begin; - my $branch1 = $builder->build( { source => 'Branch' } )->{ branchcode }; + my $branch1 = $builder->build( { source => 'Branch' } )->{branchcode}; my $calendar1 = C4::Calendar->new( branchcode => $branch1 ); - my $sunday = dt_from_string("2020-03-15"); + my $sunday = dt_from_string("2020-03-15"); $calendar1->insert_week_day_holiday( weekday => 0, title => '', @@ -224,22 +228,31 @@ subtest 'copy_to_branch' => sub { my $branch2 = $builder->build( { source => 'Branch' } )->{branchcode}; - C4::Calendar->new( branchcode => $branch1 )->copy_to_branch( $branch2 ); + C4::Calendar->new( branchcode => $branch1 )->copy_to_branch($branch2); - my $calendar2 = C4::Calendar->new( branchcode => $branch2 ); + my $calendar2 = C4::Calendar->new( branchcode => $branch2 ); my $exceptions = $calendar2->get_exception_holidays; is( $calendar2->isHoliday( $sunday->day, $sunday->month, $sunday->year ), 1, "Weekday holiday copied to branch 2" ); - is( $calendar2->isHoliday( $day_month->day, $day_month->month, $day_month->year ), 1, "Day/month holiday copied to branch 2" ); - is( $calendar2->isHoliday( $future_date->day, $future_date->month, $future_date->year ), 1, "Single holiday copied to branch 2" ); - is( ( grep { $_->{date} eq "9999-12-30"} values %$exceptions ), 1, "Exception holiday copied to branch 2" ); - is( $calendar2->isHoliday( $past_date->day, $past_date->month, $past_date->year ), 0, "Don't copy past single holidays" ); - is( ( grep { $_->{date} eq "2020-03-09"} values %$exceptions ), 0, "Don't copy past exception holidays " ); + is( + $calendar2->isHoliday( $day_month->day, $day_month->month, $day_month->year ), 1, + "Day/month holiday copied to branch 2" + ); + is( + $calendar2->isHoliday( $future_date->day, $future_date->month, $future_date->year ), 1, + "Single holiday copied to branch 2" + ); + is( ( grep { $_->{date} eq "9999-12-30" } values %$exceptions ), 1, "Exception holiday copied to branch 2" ); + is( + $calendar2->isHoliday( $past_date->day, $past_date->month, $past_date->year ), 0, + "Don't copy past single holidays" + ); + is( ( grep { $_->{date} eq "2020-03-09" } values %$exceptions ), 0, "Don't copy past exception holidays " ); - C4::Calendar->new( branchcode => $branch1 )->copy_to_branch( $branch2 ); + C4::Calendar->new( branchcode => $branch1 )->copy_to_branch($branch2); #Select all rows with same values from database - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $get_repeatable_holidays = "SELECT a.* FROM repeatable_holidays a JOIN (SELECT branchcode, weekday, day, month, COUNT(*) FROM repeatable_holidays @@ -247,15 +260,15 @@ subtest 'copy_to_branch' => sub { ON a.branchcode = b.branchcode AND ( a.weekday = b.weekday OR (a.day = b.day AND a.month = b.month)) ORDER BY a.branchcode;"; - my $sth = $dbh->prepare($get_repeatable_holidays); + my $sth = $dbh->prepare($get_repeatable_holidays); $sth->execute; my @repeatable_holidays; - while(my $row = $sth->fetchrow_hashref){ - push @repeatable_holidays, $row + while ( my $row = $sth->fetchrow_hashref ) { + push @repeatable_holidays, $row; } - is( scalar(@repeatable_holidays), 0, "None of the repeatable holidays were doubled"); + is( scalar(@repeatable_holidays), 0, "None of the repeatable holidays were doubled" ); my $get_special_holidays = "SELECT a.* FROM special_holidays a JOIN (SELECT branchcode, day, month, year, isexception, COUNT(*) @@ -264,15 +277,15 @@ subtest 'copy_to_branch' => sub { ON a.branchcode = b.branchcode AND a.day = b.day AND a.month = b.month AND a.year = b.year AND a.isexception = b.isexception ORDER BY a.branchcode;"; - $sth = $dbh->prepare($get_special_holidays); + $sth = $dbh->prepare($get_special_holidays); $sth->execute; my @special_holidays; - while(my $row = $sth->fetchrow_hashref){ - push @special_holidays, $row + while ( my $row = $sth->fetchrow_hashref ) { + push @special_holidays, $row; } - is( scalar(@special_holidays), 0, "None of the special holidays were doubled"); + is( scalar(@special_holidays), 0, "None of the special holidays were doubled" ); $schema->storage->txn_rollback; diff --git a/t/db_dependent/ILSDI_Services.t b/t/db_dependent/ILSDI_Services.t index df7e65a374..6a420a383f 100755 --- a/t/db_dependent/ILSDI_Services.t +++ b/t/db_dependent/ILSDI_Services.t @@ -26,15 +26,18 @@ use t::lib::TestBuilder; use t::lib::Dates; use XML::LibXML; -use C4::Items qw( ModItemTransfer ); +use C4::Items qw( ModItemTransfer ); use C4::Circulation qw( AddIssue ); -use C4::Reserves qw (AddReserve ModReserve ModReserveAffect ModReserveStatus); +use C4::Reserves qw (AddReserve ModReserve ModReserveAffect ModReserveStatus); use Koha::AuthUtils; use Koha::DateUtils qw( dt_from_string ); BEGIN { - use_ok('C4::ILSDI::Services', qw( AuthenticatePatron GetPatronInfo LookupPatron HoldTitle HoldItem GetRecords RenewLoan GetAvailability )); + use_ok( + 'C4::ILSDI::Services', + qw( AuthenticatePatron GetPatronInfo LookupPatron HoldTitle HoldItem GetRecords RenewLoan GetAvailability ) + ); } my $schema = Koha::Database->schema; @@ -47,78 +50,81 @@ subtest 'AuthenticatePatron test' => sub { $schema->storage->txn_begin; - my $plain_password = 'tomasito'; - $builder->build({ - source => 'Borrower', - value => { - cardnumber => undef, + $builder->build( + { + source => 'Borrower', + value => { + cardnumber => undef, + } } - }); + ); - my $borrower = $builder->build({ - source => 'Borrower', - value => { - cardnumber => undef, - password => Koha::AuthUtils::hash_password( $plain_password ), - lastseen => "2001-01-01 12:34:56" + my $borrower = $builder->build( + { + source => 'Borrower', + value => { + cardnumber => undef, + password => Koha::AuthUtils::hash_password($plain_password), + lastseen => "2001-01-01 12:34:56" + } } - }); + ); my $query = CGI->new; - $query->param( 'username', $borrower->{userid}); - $query->param( 'password', $plain_password); + $query->param( 'username', $borrower->{userid} ); + $query->param( 'password', $plain_password ); t::lib::Mocks::mock_preference( 'TrackLastPatronActivityTriggers', '' ); - my $reply = C4::ILSDI::Services::AuthenticatePatron( $query ); - is( $reply->{id}, $borrower->{borrowernumber}, "userid and password - Patron authenticated" ); - is( $reply->{code}, undef, "Error code undef"); - my $seen_patron = Koha::Patrons->find({ borrowernumber => $reply->{id} }); - is( $seen_patron->lastseen(), '2001-01-01 12:34:56','Last seen not updated if not tracking patrons'); + my $reply = C4::ILSDI::Services::AuthenticatePatron($query); + is( $reply->{id}, $borrower->{borrowernumber}, "userid and password - Patron authenticated" ); + is( $reply->{code}, undef, "Error code undef" ); + my $seen_patron = Koha::Patrons->find( { borrowernumber => $reply->{id} } ); + is( $seen_patron->lastseen(), '2001-01-01 12:34:56', 'Last seen not updated if not tracking patrons' ); - $query->param('password','ilsdi-passworD'); - $reply = C4::ILSDI::Services::AuthenticatePatron( $query ); + $query->param( 'password', 'ilsdi-passworD' ); + $reply = C4::ILSDI::Services::AuthenticatePatron($query); is( $reply->{code}, 'PatronNotFound', "userid and wrong password - PatronNotFound" ); - is( $reply->{id}, undef, "id undef"); + is( $reply->{id}, undef, "id undef" ); $query->param( 'password', $plain_password ); $query->param( 'username', 'wrong-ilsdi-useriD' ); - $reply = C4::ILSDI::Services::AuthenticatePatron( $query ); + $reply = C4::ILSDI::Services::AuthenticatePatron($query); is( $reply->{code}, 'PatronNotFound', "non-existing userid - PatronNotFound" ); - is( $reply->{id}, undef, "id undef"); + is( $reply->{id}, undef, "id undef" ); t::lib::Mocks::mock_preference( 'TrackLastPatronActivityTriggers', 'connection' ); - $query->param( 'username', uc( $borrower->{userid} )); - $reply = C4::ILSDI::Services::AuthenticatePatron( $query ); + $query->param( 'username', uc( $borrower->{userid} ) ); + $reply = C4::ILSDI::Services::AuthenticatePatron($query); my $now = dt_from_string; - is( $reply->{id}, $borrower->{borrowernumber}, "userid is not case sensitive - Patron authenticated" ); - is( $reply->{code}, undef, "Error code undef"); - $seen_patron = Koha::Patrons->find({ borrowernumber => $reply->{id} }); - is( t::lib::Dates::compare( $seen_patron->lastseen, $now), 0, 'Last seen updated to today if tracking patrons' ); + is( $reply->{id}, $borrower->{borrowernumber}, "userid is not case sensitive - Patron authenticated" ); + is( $reply->{code}, undef, "Error code undef" ); + $seen_patron = Koha::Patrons->find( { borrowernumber => $reply->{id} } ); + is( t::lib::Dates::compare( $seen_patron->lastseen, $now ), 0, 'Last seen updated to today if tracking patrons' ); $query->param( 'username', $borrower->{cardnumber} ); - $reply = C4::ILSDI::Services::AuthenticatePatron( $query ); - is( $reply->{id}, $borrower->{borrowernumber}, "cardnumber and password - Patron authenticated" ); - is( $reply->{code}, undef, "Error code undef" ); + $reply = C4::ILSDI::Services::AuthenticatePatron($query); + is( $reply->{id}, $borrower->{borrowernumber}, "cardnumber and password - Patron authenticated" ); + is( $reply->{code}, undef, "Error code undef" ); $query->param( 'password', 'ilsdi-passworD' ); - $reply = C4::ILSDI::Services::AuthenticatePatron( $query ); + $reply = C4::ILSDI::Services::AuthenticatePatron($query); is( $reply->{code}, 'PatronNotFound', "cardnumber and wrong password - PatronNotFount" ); - is( $reply->{id}, undef, "id undef" ); + is( $reply->{id}, undef, "id undef" ); $query->param( 'username', 'randomcardnumber1234' ); $query->param( 'password', $plain_password ); $reply = C4::ILSDI::Services::AuthenticatePatron($query); is( $reply->{code}, 'PatronNotFound', "non-existing cardnumer/userid - PatronNotFound" ); - is( $reply->{id}, undef, "id undef"); + is( $reply->{id}, undef, "id undef" ); $query->param( 'username', $borrower->{userid} ); $query->param( 'password', $plain_password ); $seen_patron->password_expiration_date('2020-01-01')->store; $reply = C4::ILSDI::Services::AuthenticatePatron($query); is( $reply->{code}, 'PasswordExpired', "correct credentials, expired password not authenticated" ); - is( $reply->{id}, undef, "id undef"); + is( $reply->{id}, undef, "id undef" ); $schema->storage->txn_rollback; }; @@ -248,90 +254,104 @@ subtest 'GetPatronInfo/GetBorrowerAttributes test for extended patron attributes $schema->storage->txn_begin; - $schema->resultset( 'Issue' )->delete_all; - $schema->resultset( 'Borrower' )->delete_all; - $schema->resultset( 'BorrowerAttribute' )->delete_all; - $schema->resultset( 'BorrowerAttributeType' )->delete_all; - $schema->resultset( 'Category' )->delete_all; - $schema->resultset( 'Item' )->delete_all; # 'Branch' deps. on this - $schema->resultset( 'Club' )->delete_all; - $schema->resultset( 'Branch' )->delete_all; + $schema->resultset('Issue')->delete_all; + $schema->resultset('Borrower')->delete_all; + $schema->resultset('BorrowerAttribute')->delete_all; + $schema->resultset('BorrowerAttributeType')->delete_all; + $schema->resultset('Category')->delete_all; + $schema->resultset('Item')->delete_all; # 'Branch' deps. on this + $schema->resultset('Club')->delete_all; + $schema->resultset('Branch')->delete_all; # Configure Koha to enable ILS-DI server and extended attributes: - t::lib::Mocks::mock_preference( 'ILS-DI', 1 ); + t::lib::Mocks::mock_preference( 'ILS-DI', 1 ); t::lib::Mocks::mock_preference( 'ExtendedPatronAttributes', 1 ); # Set up a library/branch for our user to belong to: - my $lib = $builder->build( { - source => 'Branch', - value => { - branchcode => 'T_ILSDI', + my $lib = $builder->build( + { + source => 'Branch', + value => { + branchcode => 'T_ILSDI', + } } - } ); + ); # Create a new category for user to belong to: - my $cat = $builder->build( { - source => 'Category', - value => { - category_type => 'A', - BlockExpiredPatronOpacActions => 'follow_syspref_BlockExpiredPatronOpacActions', + my $cat = $builder->build( + { + source => 'Category', + value => { + category_type => 'A', + BlockExpiredPatronOpacActions => 'follow_syspref_BlockExpiredPatronOpacActions', + } } - } ); + ); # Create a new attribute type: - my $attr_type = $builder->build( { - source => 'BorrowerAttributeType', - value => { - code => 'HIDEME', - opac_display => 0, - authorised_value_category => '', - class => '', + my $attr_type = $builder->build( + { + source => 'BorrowerAttributeType', + value => { + code => 'HIDEME', + opac_display => 0, + authorised_value_category => '', + class => '', + } } - } ); - my $attr_type_visible = $builder->build( { - source => 'BorrowerAttributeType', - value => { - code => 'SHOWME', - opac_display => 1, - authorised_value_category => '', - class => '', + ); + my $attr_type_visible = $builder->build( + { + source => 'BorrowerAttributeType', + value => { + code => 'SHOWME', + opac_display => 1, + authorised_value_category => '', + class => '', + } } - } ); + ); # Create a new user: - my $brwr = $builder->build( { - source => 'Borrower', - value => { - categorycode => $cat->{'categorycode'}, - branchcode => $lib->{'branchcode'}, + my $brwr = $builder->build( + { + source => 'Borrower', + value => { + categorycode => $cat->{'categorycode'}, + branchcode => $lib->{'branchcode'}, + } } - } ); + ); # Authorised value: - my $auth = $builder->build( { - source => 'AuthorisedValue', - value => { - category => $cat->{'categorycode'} + my $auth = $builder->build( + { + source => 'AuthorisedValue', + value => { category => $cat->{'categorycode'} } } - } ); + ); # Set the new attribute for our user: - my $attr_hidden = $builder->build( { - source => 'BorrowerAttribute', - value => { - borrowernumber => $brwr->{'borrowernumber'}, - code => $attr_type->{'code'}, - attribute => '1337 hidden', + my $attr_hidden = $builder->build( + { + source => 'BorrowerAttribute', + value => { + borrowernumber => $brwr->{'borrowernumber'}, + code => $attr_type->{'code'}, + attribute => '1337 hidden', + } } - } ); - my $attr_shown = $builder->build( { - source => 'BorrowerAttribute', - value => { - borrowernumber => $brwr->{'borrowernumber'}, - code => $attr_type_visible->{'code'}, - attribute => '1337 shown', + ); + my $attr_shown = $builder->build( + { + source => 'BorrowerAttribute', + value => { + borrowernumber => $brwr->{'borrowernumber'}, + code => $attr_type_visible->{'code'}, + attribute => '1337 shown', + } } - } ); + ); my $fine = $builder->build( { @@ -346,12 +366,12 @@ subtest 'GetPatronInfo/GetBorrowerAttributes test for extended patron attributes # Prepare and send web request for IL-SDI server: my $query = CGI->new; - $query->param( 'service', 'GetPatronInfo' ); - $query->param( 'patron_id', $brwr->{'borrowernumber'} ); + $query->param( 'service', 'GetPatronInfo' ); + $query->param( 'patron_id', $brwr->{'borrowernumber'} ); $query->param( 'show_attributes', '1' ); - $query->param( 'show_fines', '1' ); + $query->param( 'show_fines', '1' ); - my $reply = C4::ILSDI::Services::GetPatronInfo( $query ); + my $reply = C4::ILSDI::Services::GetPatronInfo($query); # Build a structure for comparison: my $cmp = { @@ -362,10 +382,12 @@ subtest 'GetPatronInfo/GetBorrowerAttributes test for extended patron attributes %$attr_shown, }; - is( $reply->{'charges'}, '10.00', - 'The \'charges\' attribute should be correctly filled (bug 17836)' ); + is( + $reply->{'charges'}, '10.00', + 'The \'charges\' attribute should be correctly filled (bug 17836)' + ); - is( scalar( @{$reply->{fines}->{fine}}), 1, 'There should be only 1 account line'); + is( scalar( @{ $reply->{fines}->{fine} } ), 1, 'There should be only 1 account line' ); is( $reply->{fines}->{fine}->[0]->{accountlines_id}, $fine->{accountlines_id}, @@ -373,9 +395,9 @@ subtest 'GetPatronInfo/GetBorrowerAttributes test for extended patron attributes ); # Check results: - is_deeply( $reply->{'attributes'}, [ $cmp ], 'Test GetPatronInfo - show_attributes parameter' ); + is_deeply( $reply->{'attributes'}, [$cmp], 'Test GetPatronInfo - show_attributes parameter' ); - ok( exists $reply->{is_expired}, 'There should be the is_expired information'); + ok( exists $reply->{is_expired}, 'There should be the is_expired information' ); # Cleanup $schema->storage->txn_rollback; @@ -387,19 +409,21 @@ subtest 'LookupPatron test' => sub { $schema->storage->txn_begin; - $schema->resultset( 'Issue' )->delete_all; - $schema->resultset( 'Borrower' )->delete_all; - $schema->resultset( 'BorrowerAttribute' )->delete_all; - $schema->resultset( 'BorrowerAttributeType' )->delete_all; - $schema->resultset( 'Category' )->delete_all; - $schema->resultset( 'Item' )->delete_all; # 'Branch' deps. on this - $schema->resultset( 'Branch' )->delete_all; + $schema->resultset('Issue')->delete_all; + $schema->resultset('Borrower')->delete_all; + $schema->resultset('BorrowerAttribute')->delete_all; + $schema->resultset('BorrowerAttributeType')->delete_all; + $schema->resultset('Category')->delete_all; + $schema->resultset('Item')->delete_all; # 'Branch' deps. on this + $schema->resultset('Branch')->delete_all; - my $borrower = $builder->build({ - source => 'Borrower', - }); + my $borrower = $builder->build( + { + source => 'Borrower', + } + ); - my $query = CGI->new(); + my $query = CGI->new(); my $bad_result = C4::ILSDI::Services::LookupPatron($query); is( $bad_result->{message}, 'PatronNotFound', 'No parameters' ); @@ -424,10 +448,11 @@ subtest 'LookupPatron test' => sub { 'borrowernumber', 'surname', 'firstname' - ) { + ) + { $query->delete_all(); $query->param( 'id_type', $id_type ); - $query->param( 'id', $borrower->{$id_type} ); + $query->param( 'id', $borrower->{$id_type} ); my $result = C4::ILSDI::Services::LookupPatron($query); is( $result->{'id'}, $borrower->{borrowernumber}, "Checking $id_type" ); } @@ -446,40 +471,38 @@ subtest 'Holds test' => sub { my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); - my $item = $builder->build_sample_item( - { - damaged => 1 - } - ); + my $item = $builder->build_sample_item( { damaged => 1 } ); my $query = CGI->new; - $query->param( 'patron_id', $patron->borrowernumber); - $query->param( 'bib_id', $item->biblionumber); + $query->param( 'patron_id', $patron->borrowernumber ); + $query->param( 'bib_id', $item->biblionumber ); - my $reply = C4::ILSDI::Services::HoldTitle( $query ); + my $reply = C4::ILSDI::Services::HoldTitle($query); is( $reply->{code}, 'damaged', "Item damaged" ); $item->damaged(0)->store; - my $hold = $builder->build({ - source => 'Reserve', - value => { - borrowernumber => $patron->borrowernumber, - biblionumber => $item->biblionumber, - itemnumber => $item->itemnumber + my $hold = $builder->build( + { + source => 'Reserve', + value => { + borrowernumber => $patron->borrowernumber, + biblionumber => $item->biblionumber, + itemnumber => $item->itemnumber + } } - }); + ); - $reply = C4::ILSDI::Services::HoldTitle( $query ); + $reply = C4::ILSDI::Services::HoldTitle($query); is( $reply->{code}, 'itemAlreadyOnHold', "Item already on hold" ); my $biblio_with_no_item = $builder->build_sample_biblio; $query = CGI->new; - $query->param( 'patron_id', $patron->borrowernumber); - $query->param( 'bib_id', $biblio_with_no_item->biblionumber); + $query->param( 'patron_id', $patron->borrowernumber ); + $query->param( 'bib_id', $biblio_with_no_item->biblionumber ); - $reply = C4::ILSDI::Services::HoldTitle( $query ); + $reply = C4::ILSDI::Services::HoldTitle($query); is( $reply->{code}, 'NoItems', 'Biblio has no item' ); my $item2 = $builder->build_sample_item( @@ -500,11 +523,11 @@ subtest 'Holds test' => sub { ); $query = CGI->new; - $query->param( 'patron_id', $patron->borrowernumber); - $query->param( 'bib_id', $item2->biblionumber); - $query->param( 'item_id', $item2->itemnumber); + $query->param( 'patron_id', $patron->borrowernumber ); + $query->param( 'bib_id', $item2->biblionumber ); + $query->param( 'item_id', $item2->itemnumber ); - $reply = C4::ILSDI::Services::HoldItem( $query ); + $reply = C4::ILSDI::Services::HoldItem($query); is( $reply->{code}, 'tooManyReserves', "Too many reserves" ); Koha::CirculationRules->set_rule( @@ -518,11 +541,11 @@ subtest 'Holds test' => sub { ); $query = CGI->new; - $query->param( 'patron_id', $patron->borrowernumber); - $query->param( 'bib_id', $item2->biblionumber); - $query->param( 'item_id', $item2->itemnumber); + $query->param( 'patron_id', $patron->borrowernumber ); + $query->param( 'bib_id', $item2->biblionumber ); + $query->param( 'item_id', $item2->itemnumber ); - $reply = C4::ILSDI::Services::HoldItem( $query ); + $reply = C4::ILSDI::Services::HoldItem($query); is( $reply->{code}, 'noReservesAllowed', "No reserves allowed" ); my $origin_branch = $builder->build( @@ -536,17 +559,19 @@ subtest 'Holds test' => sub { # Adding a holdable item. my $item3 = $builder->build_sample_item( - { - barcode => '123456789', - library => $origin_branch->{branchcode} - }); + { + barcode => '123456789', + library => $origin_branch->{branchcode} + } + ); my $item4 = $builder->build_sample_item( { - biblionumber => $item3->biblionumber, - damaged => 1, - library => $origin_branch->{branchcode} - }); + biblionumber => $item3->biblionumber, + damaged => 1, + library => $origin_branch->{branchcode} + } + ); Koha::CirculationRules->set_rule( { @@ -559,60 +584,66 @@ subtest 'Holds test' => sub { ); $query = CGI->new; - $query->param( 'patron_id', $patron->borrowernumber); - $query->param( 'bib_id', $item4->biblionumber); - $query->param( 'item_id', $item4->itemnumber); + $query->param( 'patron_id', $patron->borrowernumber ); + $query->param( 'bib_id', $item4->biblionumber ); + $query->param( 'item_id', $item4->itemnumber ); - $reply = C4::ILSDI::Services::HoldItem( $query ); + $reply = C4::ILSDI::Services::HoldItem($query); is( $reply->{code}, 'damaged', "Item is damaged" ); my $module = Test::MockModule->new('C4::Context'); - $module->mock('userenv', sub { { patron => $patron->unblessed } }); - my $issue = C4::Circulation::AddIssue($patron, $item3->barcode); + $module->mock( 'userenv', sub { { patron => $patron->unblessed } } ); + my $issue = C4::Circulation::AddIssue( $patron, $item3->barcode ); t::lib::Mocks::mock_preference( 'AllowHoldsOnPatronsPossessions', '0' ); $query = CGI->new; - $query->param( 'patron_id', $patron->borrowernumber); - $query->param( 'bib_id', $item3->biblionumber); - $query->param( 'item_id', $item3->itemnumber); - $query->param( 'pickup_location', $origin_branch->{branchcode}); - $reply = C4::ILSDI::Services::HoldItem( $query ); + $query->param( 'patron_id', $patron->borrowernumber ); + $query->param( 'bib_id', $item3->biblionumber ); + $query->param( 'item_id', $item3->itemnumber ); + $query->param( 'pickup_location', $origin_branch->{branchcode} ); + $reply = C4::ILSDI::Services::HoldItem($query); - is( $reply->{code}, 'alreadypossession', "Patron has issued same book" ); - is( $reply->{pickup_location}, undef, "No reserve placed"); + is( $reply->{code}, 'alreadypossession', "Patron has issued same book" ); + is( $reply->{pickup_location}, undef, "No reserve placed" ); # Test Patron cannot reserve if expired and BlockExpiredPatronOpacActions - my $category = $builder->build({ - source => 'Category', - value => { BlockExpiredPatronOpacActions => 'follow_syspref_BlockExpiredPatronOpacActions' } - }); - - my $branch_1 = $builder->build({ source => 'Branch' })->{ branchcode }; - - my $expired_borrowernumber = Koha::Patron->new({ - firstname => 'Expired', - surname => 'Patron', - categorycode => $category->{categorycode}, - branchcode => $branch_1, - dateexpiry => '2000-01-01', - })->store->borrowernumber; - - t::lib::Mocks::mock_preference('BlockExpiredPatronOpacActions', 'hold,renew'); - - my $item5 = $builder->build({ - source => 'Item', - value => { - biblionumber => $biblio_with_no_item->biblionumber, - damaged => 0, + my $category = $builder->build( + { + source => 'Category', + value => { BlockExpiredPatronOpacActions => 'follow_syspref_BlockExpiredPatronOpacActions' } } - }); + ); + + my $branch_1 = $builder->build( { source => 'Branch' } )->{branchcode}; + + my $expired_borrowernumber = Koha::Patron->new( + { + firstname => 'Expired', + surname => 'Patron', + categorycode => $category->{categorycode}, + branchcode => $branch_1, + dateexpiry => '2000-01-01', + } + )->store->borrowernumber; + + t::lib::Mocks::mock_preference( 'BlockExpiredPatronOpacActions', 'hold,renew' ); + + my $item5 = $builder->build( + { + source => 'Item', + value => { + biblionumber => $biblio_with_no_item->biblionumber, + damaged => 0, + } + } + ); $query = CGI->new; - $query->param( 'patron_id', $expired_borrowernumber); - $query->param( 'bib_id', $biblio_with_no_item->biblionumber); - $query->param( 'item_id', $item5->{itemnumber}); + $query->param( 'patron_id', $expired_borrowernumber ); + $query->param( 'bib_id', $biblio_with_no_item->biblionumber ); + $query->param( 'item_id', $item5->{itemnumber} ); - $reply = C4::ILSDI::Services::HoldItem( $query ); + $reply = C4::ILSDI::Services::HoldItem($query); is( $reply->{code}, 'PatronExpired', "Patron is expired" ); $schema->storage->txn_rollback; @@ -625,12 +656,14 @@ subtest 'Holds test for branch transfer limits' => sub { $schema->storage->txn_begin; # Test enforement of branch transfer limits - t::lib::Mocks::mock_preference( 'UseBranchTransferLimits', '1' ); + t::lib::Mocks::mock_preference( 'UseBranchTransferLimits', '1' ); t::lib::Mocks::mock_preference( 'BranchTransferLimitsType', 'itemtype' ); - my $patron = $builder->build_object({ - class => 'Koha::Patrons', - }); + my $patron = $builder->build_object( + { + class => 'Koha::Patrons', + } + ); my $origin_branch = $builder->build( { @@ -665,36 +698,40 @@ subtest 'Holds test for branch transfer limits' => sub { } ); - my $limit = Koha::Item::Transfer::Limit->new({ - toBranch => $pickup_branch->{branchcode}, - fromBranch => $item->holdingbranch, - itemtype => $item->effective_itemtype, - })->store(); + my $limit = Koha::Item::Transfer::Limit->new( + { + toBranch => $pickup_branch->{branchcode}, + fromBranch => $item->holdingbranch, + itemtype => $item->effective_itemtype, + } + )->store(); my $query = CGI->new; $query->param( 'pickup_location', $pickup_branch->{branchcode} ); - $query->param( 'patron_id', $patron->borrowernumber); - $query->param( 'bib_id', $item->biblionumber); - $query->param( 'item_id', $item->itemnumber); + $query->param( 'patron_id', $patron->borrowernumber ); + $query->param( 'bib_id', $item->biblionumber ); + $query->param( 'item_id', $item->itemnumber ); - my $reply = C4::ILSDI::Services::HoldItem( $query ); + my $reply = C4::ILSDI::Services::HoldItem($query); is( $reply->{code}, 'cannotBeTransferred', "Item hold, Item cannot be transferred" ); - $reply = C4::ILSDI::Services::HoldTitle( $query ); + $reply = C4::ILSDI::Services::HoldTitle($query); is( $reply->{code}, 'cannotBeTransferred', "Record hold, Item cannot be transferred" ); t::lib::Mocks::mock_preference( 'UseBranchTransferLimits', '0' ); - $reply = C4::ILSDI::Services::HoldItem( $query ); + $reply = C4::ILSDI::Services::HoldItem($query); is( $reply->{code}, undef, "Item hold, Item can be transferred" ); - my $hold = Koha::Holds->search({ itemnumber => $item->itemnumber, borrowernumber => $patron->borrowernumber })->next; + my $hold = + Koha::Holds->search( { itemnumber => $item->itemnumber, borrowernumber => $patron->borrowernumber } )->next; is( $hold->branchcode, $pickup_branch->{branchcode}, 'The library id is correctly set' ); Koha::Holds->search()->delete(); - $reply = C4::ILSDI::Services::HoldTitle( $query ); + $reply = C4::ILSDI::Services::HoldTitle($query); is( $reply->{code}, undef, "Record hold, Item con be transferred" ); - $hold = Koha::Holds->search({ biblionumber => $item->biblionumber, borrowernumber => $patron->borrowernumber })->next; + $hold = + Koha::Holds->search( { biblionumber => $item->biblionumber, borrowernumber => $patron->borrowernumber } )->next; is( $hold->branchcode, $pickup_branch->{branchcode}, 'The library id is correctly set' ); $schema->storage->txn_rollback; @@ -708,18 +745,20 @@ subtest 'Holds test with start_date and end_date' => sub { my $pickup_library = $builder->build_object( { - class => 'Koha::Libraries', - value => { + class => 'Koha::Libraries', + value => { pickup_location => 1, } } ); - my $patron = $builder->build_object({ - class => 'Koha::Patrons', - }); + my $patron = $builder->build_object( + { + class => 'Koha::Patrons', + } + ); - my $item = $builder->build_sample_item({ library => $pickup_library->branchcode }); + my $item = $builder->build_sample_item( { library => $pickup_library->branchcode } ); Koha::CirculationRules->set_rule( { @@ -733,27 +772,27 @@ subtest 'Holds test with start_date and end_date' => sub { my $query = CGI->new; $query->param( 'pickup_location', $pickup_library->branchcode ); - $query->param( 'patron_id', $patron->borrowernumber); - $query->param( 'bib_id', $item->biblionumber); - $query->param( 'item_id', $item->itemnumber); - $query->param( 'start_date', '2020-03-20'); - $query->param( 'expiry_date', '2020-04-22'); + $query->param( 'patron_id', $patron->borrowernumber ); + $query->param( 'bib_id', $item->biblionumber ); + $query->param( 'item_id', $item->itemnumber ); + $query->param( 'start_date', '2020-03-20' ); + $query->param( 'expiry_date', '2020-04-22' ); - my $reply = C4::ILSDI::Services::HoldItem( $query ); - is ($reply->{pickup_location}, $pickup_library->branchname, "Item hold with date parameters was placed"); - my $hold = Koha::Holds->search({ biblionumber => $item->biblionumber})->next(); - is( $hold->biblionumber, $item->biblionumber, "correct biblionumber"); - is( $hold->reservedate, '2020-03-20', "Item hold has correct start date" ); - is( $hold->expirationdate, '2020-04-22', "Item hold has correct end date" ); + my $reply = C4::ILSDI::Services::HoldItem($query); + is( $reply->{pickup_location}, $pickup_library->branchname, "Item hold with date parameters was placed" ); + my $hold = Koha::Holds->search( { biblionumber => $item->biblionumber } )->next(); + is( $hold->biblionumber, $item->biblionumber, "correct biblionumber" ); + is( $hold->reservedate, '2020-03-20', "Item hold has correct start date" ); + is( $hold->expirationdate, '2020-04-22', "Item hold has correct end date" ); $hold->delete(); - $reply = C4::ILSDI::Services::HoldTitle( $query ); - is ($reply->{pickup_location}, $pickup_library->branchname, "Record hold with date parameters was placed"); - $hold = Koha::Holds->search({ biblionumber => $item->biblionumber})->next(); - is( $hold->biblionumber, $item->biblionumber, "correct biblionumber"); - is( $hold->reservedate, '2020-03-20', "Record hold has correct start date" ); - is( $hold->expirationdate, '2020-04-22', "Record hold has correct end date" ); + $reply = C4::ILSDI::Services::HoldTitle($query); + is( $reply->{pickup_location}, $pickup_library->branchname, "Record hold with date parameters was placed" ); + $hold = Koha::Holds->search( { biblionumber => $item->biblionumber } )->next(); + is( $hold->biblionumber, $item->biblionumber, "correct biblionumber" ); + is( $hold->reservedate, '2020-03-20', "Record hold has correct start date" ); + is( $hold->expirationdate, '2020-04-22', "Record hold has correct end date" ); $schema->storage->txn_rollback; }; @@ -766,12 +805,16 @@ subtest 'GetRecords' => sub { t::lib::Mocks::mock_preference( 'ILS-DI', 1 ); - my $branch1 = $builder->build({ - source => 'Branch', - }); - my $branch2 = $builder->build({ - source => 'Branch', - }); + my $branch1 = $builder->build( + { + source => 'Branch', + } + ); + my $branch2 = $builder->build( + { + source => 'Branch', + } + ); my $item = $builder->build_sample_item( { @@ -779,51 +822,59 @@ subtest 'GetRecords' => sub { } ); - my $patron = $builder->build({ - source => 'Borrower', - }); - - my $issue = $builder->build({ - source => 'Issue', - value => { - itemnumber => $item->itemnumber, + my $patron = $builder->build( + { + source => 'Borrower', } - }); + ); - my $hold = $builder->build({ - source => 'Reserve', - value => { - biblionumber => $item->biblionumber, + my $issue = $builder->build( + { + source => 'Issue', + value => { + itemnumber => $item->itemnumber, + } } - }); + ); - ModItemTransfer($item->itemnumber, $branch1->{branchcode}, $branch2->{branchcode}, 'Manual'); + my $hold = $builder->build( + { + source => 'Reserve', + value => { + biblionumber => $item->biblionumber, + } + } + ); + + ModItemTransfer( $item->itemnumber, $branch1->{branchcode}, $branch2->{branchcode}, 'Manual' ); my $cgi = CGI->new; - $cgi->param(service => 'GetRecords'); - $cgi->param(id => $item->biblionumber); + $cgi->param( service => 'GetRecords' ); + $cgi->param( id => $item->biblionumber ); my $reply = C4::ILSDI::Services::GetRecords($cgi); my $transfer = $item->get_transfer; my $expected = { - datesent => $transfer->datesent, + datesent => $transfer->datesent, frombranch => $transfer->frombranch, - tobranch => $transfer->tobranch, + tobranch => $transfer->tobranch, }; - is_deeply($reply->{record}->[0]->{items}->{item}->[0]->{transfer}, $expected, - 'GetRecords returns transfer informations'); + is_deeply( + $reply->{record}->[0]->{items}->{item}->[0]->{transfer}, $expected, + 'GetRecords returns transfer informations' + ); # Check informations exposed my $reply_issue = $reply->{record}->[0]->{issues}->{issue}->[0]; - is($reply_issue->{itemnumber}, $item->itemnumber, 'GetRecords has an issue tag'); - is($reply_issue->{borrowernumber}, undef, 'GetRecords does not expose borrowernumber in issue tag'); - is($reply_issue->{surname}, undef, 'GetRecords does not expose surname in issue tag'); - is($reply_issue->{firstname}, undef, 'GetRecords does not expose firstname in issue tag'); - is($reply_issue->{cardnumber}, undef, 'GetRecords does not expose cardnumber in issue tag'); + is( $reply_issue->{itemnumber}, $item->itemnumber, 'GetRecords has an issue tag' ); + is( $reply_issue->{borrowernumber}, undef, 'GetRecords does not expose borrowernumber in issue tag' ); + is( $reply_issue->{surname}, undef, 'GetRecords does not expose surname in issue tag' ); + is( $reply_issue->{firstname}, undef, 'GetRecords does not expose firstname in issue tag' ); + is( $reply_issue->{cardnumber}, undef, 'GetRecords does not expose cardnumber in issue tag' ); my $reply_reserve = $reply->{record}->[0]->{reserves}->{reserve}->[0]; - is($reply_reserve->{biblionumber}, $item->biblionumber, 'GetRecords has a reserve tag'); - is($reply_reserve->{borrowernumber}, undef, 'GetRecords does not expose borrowernumber in reserve tag'); + is( $reply_reserve->{biblionumber}, $item->biblionumber, 'GetRecords has a reserve tag' ); + is( $reply_reserve->{borrowernumber}, undef, 'GetRecords does not expose borrowernumber in reserve tag' ); # Check for hidelostitems sys pref t::lib::Mocks::mock_preference( 'hidelostitems', 1 ); @@ -873,16 +924,17 @@ subtest 'RenewHold' => sub { # The item is not checked out $checkout->delete; $reply = C4::ILSDI::Services::RenewLoan($cgi); - is( $reply, undef, 'If the item is not checked out, we should not explode.'); # FIXME We should return an error code instead + is( $reply, undef, 'If the item is not checked out, we should not explode.' ) + ; # FIXME We should return an error code instead # The item does not exist $item->delete; $reply = C4::ILSDI::Services::RenewLoan($cgi); - is( $reply->{code}, 'RecordNotFound', 'If the item does not exist, RecordNotFound should be returned'); + is( $reply->{code}, 'RecordNotFound', 'If the item does not exist, RecordNotFound should be returned' ); $patron->delete; $reply = C4::ILSDI::Services::RenewLoan($cgi); - is( $reply->{code}, 'PatronNotFound', 'If the patron does not exist, PatronNotFound should be returned'); + is( $reply->{code}, 'PatronNotFound', 'If the patron does not exist, PatronNotFound should be returned' ); $schema->storage->txn_rollback; }; @@ -894,54 +946,72 @@ subtest 'CancelHold' => sub { my $cgi = CGI->new; - my $library = $builder->build_object({ - class => 'Koha::Libraries', - }); + my $library = $builder->build_object( + { + class => 'Koha::Libraries', + } + ); - my $patron = $builder->build_object( { class => 'Koha::Patrons', - value => { - branchcode => $library->branchcode, - }, - } ); + my $patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { + branchcode => $library->branchcode, + }, + } + ); - my $patron2 = $builder->build_object( { class => 'Koha::Patrons', - value => { - branchcode => $library->branchcode, - }, - } ); + my $patron2 = $builder->build_object( + { + class => 'Koha::Patrons', + value => { + branchcode => $library->branchcode, + }, + } + ); - my $item = $builder->build_sample_item({ library => $library->branchcode }); + my $item = $builder->build_sample_item( { library => $library->branchcode } ); - my $reserve = C4::Reserves::AddReserve({branchcode => $library->branchcode, - borrowernumber => $patron->borrowernumber, - biblionumber => $item->biblionumber }); + my $reserve = C4::Reserves::AddReserve( + { + branchcode => $library->branchcode, + borrowernumber => $patron->borrowernumber, + biblionumber => $item->biblionumber + } + ); # Affecting the reserve sets it to a waiting state - C4::Reserves::ModReserveAffect( $item->itemnumber, - $patron->borrowernumber, - undef, - $reserve, - ); + C4::Reserves::ModReserveAffect( + $item->itemnumber, + $patron->borrowernumber, + undef, + $reserve, + ); $cgi->param( patron_id => $patron2->borrowernumber ); $cgi->param( item_id => $reserve ); - my $reply = C4::ILSDI::Services::CancelHold($cgi); - is( $reply->{code}, 'BorrowerCannotCancelHold', 'If the patron is wrong, BorrowerCannotCancelHold should be returned'); + is( + $reply->{code}, 'BorrowerCannotCancelHold', + 'If the patron is wrong, BorrowerCannotCancelHold should be returned' + ); $cgi->param( patron_id => $patron->borrowernumber ); $reply = C4::ILSDI::Services::CancelHold($cgi); - is( $reply->{code}, 'BorrowerCannotCancelHold', 'If reserve in a Waiting state, patron cannot cancel'); + is( $reply->{code}, 'BorrowerCannotCancelHold', 'If reserve in a Waiting state, patron cannot cancel' ); C4::Reserves::ModReserveStatus( $item->itemnumber, 'T' ); $reply = C4::ILSDI::Services::CancelHold($cgi); - is( $reply->{code}, 'BorrowerCannotCancelHold', 'If reserve in a Transfer state, patron cannot cancel'); + is( $reply->{code}, 'BorrowerCannotCancelHold', 'If reserve in a Transfer state, patron cannot cancel' ); - C4::Reserves::ModReserve( {rank => 1, reserve_id => $reserve, branchcode => $library->branchcode} ); + C4::Reserves::ModReserve( { rank => 1, reserve_id => $reserve, branchcode => $library->branchcode } ); $cgi->param( item_id => $reserve ); $reply = C4::ILSDI::Services::CancelHold($cgi); - is( $reply->{code}, 'Canceled', 'If the patron is fine and reserve not waiting, Canceled should be returned and reserve canceled'); + is( + $reply->{code}, 'Canceled', + 'If the patron is fine and reserve not waiting, Canceled should be returned and reserve canceled' + ); $schema->storage->txn_rollback; }; @@ -951,49 +1021,53 @@ subtest 'GetPatronInfo paginated loans' => sub { $schema->storage->txn_begin; - my $library = $builder->build_object({ - class => 'Koha::Libraries', - }); + my $library = $builder->build_object( + { + class => 'Koha::Libraries', + } + ); - my $item1 = $builder->build_sample_item({ library => $library->branchcode }); - my $item2 = $builder->build_sample_item({ library => $library->branchcode }); - my $item3 = $builder->build_sample_item({ library => $library->branchcode }); - my $patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { - branchcode => $library->branchcode, - }, - }); + my $item1 = $builder->build_sample_item( { library => $library->branchcode } ); + my $item2 = $builder->build_sample_item( { library => $library->branchcode } ); + my $item3 = $builder->build_sample_item( { library => $library->branchcode } ); + my $patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { + branchcode => $library->branchcode, + }, + } + ); my $module = Test::MockModule->new('C4::Context'); - $module->mock('userenv', sub { { branch => $library->branchcode } }); - my $date_due = Koha::DateUtils::dt_from_string()->add(weeks => 2); - my $issue1 = C4::Circulation::AddIssue($patron, $item1->barcode, $date_due); + $module->mock( 'userenv', sub { { branch => $library->branchcode } } ); + my $date_due = Koha::DateUtils::dt_from_string()->add( weeks => 2 ); + my $issue1 = C4::Circulation::AddIssue( $patron, $item1->barcode, $date_due ); my $date_due1 = Koha::DateUtils::dt_from_string( $issue1->date_due ); - my $issue2 = C4::Circulation::AddIssue($patron, $item2->barcode, $date_due); + my $issue2 = C4::Circulation::AddIssue( $patron, $item2->barcode, $date_due ); my $date_due2 = Koha::DateUtils::dt_from_string( $issue2->date_due ); - my $issue3 = C4::Circulation::AddIssue($patron, $item3->barcode, $date_due); + my $issue3 = C4::Circulation::AddIssue( $patron, $item3->barcode, $date_due ); my $date_due3 = Koha::DateUtils::dt_from_string( $issue3->date_due ); my $cgi = CGI->new; - $cgi->param( 'service', 'GetPatronInfo' ); - $cgi->param( 'patron_id', $patron->borrowernumber ); - $cgi->param( 'show_loans', '1' ); + $cgi->param( 'service', 'GetPatronInfo' ); + $cgi->param( 'patron_id', $patron->borrowernumber ); + $cgi->param( 'show_loans', '1' ); $cgi->param( 'loans_per_page', '2' ); - $cgi->param( 'loans_page', '1' ); + $cgi->param( 'loans_page', '1' ); my $reply = C4::ILSDI::Services::GetPatronInfo($cgi); - is($reply->{total_loans}, 3, 'total_loans == 3'); - is(scalar @{ $reply->{loans}->{loan} }, 2, 'GetPatronInfo returned only 2 loans'); - is($reply->{loans}->{loan}->[0]->{itemnumber}, $item3->itemnumber); - is($reply->{loans}->{loan}->[1]->{itemnumber}, $item2->itemnumber); + is( $reply->{total_loans}, 3, 'total_loans == 3' ); + is( scalar @{ $reply->{loans}->{loan} }, 2, 'GetPatronInfo returned only 2 loans' ); + is( $reply->{loans}->{loan}->[0]->{itemnumber}, $item3->itemnumber ); + is( $reply->{loans}->{loan}->[1]->{itemnumber}, $item2->itemnumber ); $cgi->param( 'loans_page', '2' ); $reply = C4::ILSDI::Services::GetPatronInfo($cgi); - is($reply->{total_loans}, 3, 'total_loans == 3'); - is(scalar @{ $reply->{loans}->{loan} }, 1, 'GetPatronInfo returned only 1 loan'); - is($reply->{loans}->{loan}->[0]->{itemnumber}, $item1->itemnumber); + is( $reply->{total_loans}, 3, 'total_loans == 3' ); + is( scalar @{ $reply->{loans}->{loan} }, 1, 'GetPatronInfo returned only 1 loan' ); + is( $reply->{loans}->{loan}->[0]->{itemnumber}, $item1->itemnumber ); $schema->storage->txn_rollback; }; @@ -1024,46 +1098,50 @@ subtest 'GetAvailability itemcallnumber' => sub { my $reply = C4::ILSDI::Services::GetAvailability($cgi); # Parse the output and get info - my $result_XML = XML::LibXML->load_xml( string => $reply ); - my $reply_callnumber = - $result_XML->findnodes('//dlf:itemcallnumber')->to_literal(); + my $result_XML = XML::LibXML->load_xml( string => $reply ); + my $reply_callnumber = $result_XML->findnodes('//dlf:itemcallnumber')->to_literal(); # Test the output - is( $reply_callnumber, $item1->itemcallnumber, - "GetAvailability item has an itemcallnumber tag" ); + is( + $reply_callnumber, $item1->itemcallnumber, + "GetAvailability item has an itemcallnumber tag" + ); $cgi = CGI->new; $cgi->param( service => 'GetAvailability' ); $cgi->param( id => $item2->itemnumber ); $cgi->param( id_type => 'item' ); - $reply = C4::ILSDI::Services::GetAvailability($cgi); - $result_XML = XML::LibXML->load_xml( string => $reply ); - $reply_callnumber = - $result_XML->findnodes('//dlf:itemcallnumber')->to_literal(); - is( $reply_callnumber, '', - "As expected, GetAvailability item has no itemcallnumber tag" ); + $reply = C4::ILSDI::Services::GetAvailability($cgi); + $result_XML = XML::LibXML->load_xml( string => $reply ); + $reply_callnumber = $result_XML->findnodes('//dlf:itemcallnumber')->to_literal(); + is( + $reply_callnumber, '', + "As expected, GetAvailability item has no itemcallnumber tag" + ); $cgi = CGI->new; $cgi->param( service => 'GetAvailability' ); $cgi->param( id => $item1->biblionumber ); $cgi->param( id_type => 'biblio' ); - $reply = C4::ILSDI::Services::GetAvailability($cgi); - $result_XML = XML::LibXML->load_xml( string => $reply ); - $reply_callnumber = - $result_XML->findnodes('//dlf:itemcallnumber')->to_literal(); - is( $reply_callnumber, $item1->itemcallnumber, - "GetAvailability biblio has an itemcallnumber tag" ); + $reply = C4::ILSDI::Services::GetAvailability($cgi); + $result_XML = XML::LibXML->load_xml( string => $reply ); + $reply_callnumber = $result_XML->findnodes('//dlf:itemcallnumber')->to_literal(); + is( + $reply_callnumber, $item1->itemcallnumber, + "GetAvailability biblio has an itemcallnumber tag" + ); $cgi = CGI->new; $cgi->param( service => 'GetAvailability' ); $cgi->param( id => $item2->biblionumber ); $cgi->param( id_type => 'biblio' ); - $reply = C4::ILSDI::Services::GetAvailability($cgi); - $result_XML = XML::LibXML->load_xml( string => $reply ); - $reply_callnumber = - $result_XML->findnodes('//dlf:itemcallnumber')->to_literal(); - is( $reply_callnumber, '', - "As expected, GetAvailability biblio has no itemcallnumber tag" ); + $reply = C4::ILSDI::Services::GetAvailability($cgi); + $result_XML = XML::LibXML->load_xml( string => $reply ); + $reply_callnumber = $result_XML->findnodes('//dlf:itemcallnumber')->to_literal(); + is( + $reply_callnumber, '', + "As expected, GetAvailability biblio has no itemcallnumber tag" + ); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/ImportBatch.t b/t/db_dependent/ImportBatch.t index c9ef54391a..4016d9686c 100755 --- a/t/db_dependent/ImportBatch.t +++ b/t/db_dependent/ImportBatch.t @@ -18,44 +18,47 @@ BEGIN { t::lib::Mocks::mock_config( 'pluginsdir', $path ); use_ok('Koha::Plugins'); - use_ok('C4::ImportBatch', qw( AddImportBatch GetImportBatch AddBiblioToBatch AddItemsToImportBiblio SetMatchedBiblionumber GetImportBiblios GetItemNumbersFromImportBatch CleanBatch DeleteBatch RecordsFromMarcPlugin BatchCommitRecords )); + use_ok( + 'C4::ImportBatch', + qw( AddImportBatch GetImportBatch AddBiblioToBatch AddItemsToImportBiblio SetMatchedBiblionumber GetImportBiblios GetItemNumbersFromImportBatch CleanBatch DeleteBatch RecordsFromMarcPlugin BatchCommitRecords ) + ); } # Start transaction -my $schema = Koha::Database->new->schema; +my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; my $builder = t::lib::TestBuilder->new; -my $dbh = C4::Context->dbh; +my $dbh = C4::Context->dbh; # clear $dbh->do('DELETE FROM import_batches'); my $sample_import_batch1 = { - matcher_id => 1, - template_id => 1, - branchcode => 'QRT', + matcher_id => 1, + template_id => 1, + branchcode => 'QRT', overlay_action => 'create_new', nomatch_action => 'create_new', - item_action => 'always_add', - import_status => 'staged', - batch_type => 'z3950', - file_name => 'test.mrc', - comments => 'test', - record_type => 'auth', + item_action => 'always_add', + import_status => 'staged', + batch_type => 'z3950', + file_name => 'test.mrc', + comments => 'test', + record_type => 'auth', }; my $sample_import_batch2 = { - matcher_id => 2, - template_id => 2, - branchcode => 'QRZ', + matcher_id => 2, + template_id => 2, + branchcode => 'QRZ', overlay_action => 'create_new', nomatch_action => 'create_new', - item_action => 'always_add', - import_status => 'staged', - batch_type => 'z3950', - file_name => 'test.mrc', - comments => 'test', - record_type => 'auth', + item_action => 'always_add', + import_status => 'staged', + batch_type => 'z3950', + file_name => 'test.mrc', + comments => 'test', + record_type => 'auth', }; my $id_import_batch1 = C4::ImportBatch::AddImportBatch($sample_import_batch1); @@ -65,7 +68,7 @@ like( $id_import_batch1, '/^\d+$/', "AddImportBatch for sample_import_batch1 ret like( $id_import_batch2, '/^\d+$/', "AddImportBatch for sample_import_batch2 return an id" ); #Test GetImportBatch -my $importbatch2 = C4::ImportBatch::GetImportBatch( $id_import_batch2 ); +my $importbatch2 = C4::ImportBatch::GetImportBatch($id_import_batch2); delete $importbatch2->{upload_timestamp}; delete $importbatch2->{import_batch_id}; delete $importbatch2->{num_records}; @@ -73,10 +76,12 @@ delete $importbatch2->{num_items}; delete $importbatch2->{profile_id}; delete $importbatch2->{profile}; -is_deeply( $importbatch2, $sample_import_batch2, - "GetImportBatch returns the right informations about $sample_import_batch2" ); +is_deeply( + $importbatch2, $sample_import_batch2, + "GetImportBatch returns the right informations about $sample_import_batch2" +); -my $importbatch1 = C4::ImportBatch::GetImportBatch( $id_import_batch1 ); +my $importbatch1 = C4::ImportBatch::GetImportBatch($id_import_batch1); delete $importbatch1->{upload_timestamp}; delete $importbatch1->{import_batch_id}; delete $importbatch1->{num_records}; @@ -84,16 +89,18 @@ delete $importbatch1->{num_items}; delete $importbatch1->{profile_id}; delete $importbatch1->{profile}; -is_deeply( $importbatch1, $sample_import_batch1, - "GetImportBatch returns the right informations about $sample_import_batch1" ); +is_deeply( + $importbatch1, $sample_import_batch1, + "GetImportBatch returns the right informations about $sample_import_batch1" +); -my $record = MARC::Record->new; +my $record = MARC::Record->new; my $original_record = MARC::Record->new; $record->leader('03174nam a2200445 a 4500'); $original_record->leader('03174nam a2200445 a 4500'); -my ($item_tag, $item_subfield) = C4::Biblio::GetMarcFromKohaField( 'items.itemnumber' ); +my ( $item_tag, $item_subfield ) = C4::Biblio::GetMarcFromKohaField('items.itemnumber'); my @fields; -if (C4::Context->preference('marcflavour') eq 'UNIMARC') { +if ( C4::Context->preference('marcflavour') eq 'UNIMARC' ) { @fields = ( MARC::Field->new( 100, ' ', ' ', @@ -159,68 +166,79 @@ $original_record->append_fields(@fields); my $import_record_id = AddBiblioToBatch( $id_import_batch1, 0, $record, 'utf8', 0 ); AddItemsToImportBiblio( $id_import_batch1, $import_record_id, $record, 0 ); -my $import_record = Koha::Import::Records->find($import_record_id); +my $import_record = Koha::Import::Records->find($import_record_id); my $record_from_import_biblio = $import_record->get_marc_record(); -$original_record->leader($record_from_import_biblio->leader()); -is_deeply( $record_from_import_biblio, $original_record, 'Koha::Import::Record::get_marc_record should return the record in original state' ); -my $utf8_field = $record_from_import_biblio->subfield($item_tag, 'e'); -is($utf8_field, 'my edition ❤'); +$original_record->leader( $record_from_import_biblio->leader() ); +is_deeply( + $record_from_import_biblio, $original_record, + 'Koha::Import::Record::get_marc_record should return the record in original state' +); +my $utf8_field = $record_from_import_biblio->subfield( $item_tag, 'e' ); +is( $utf8_field, 'my edition ❤' ); my $another_biblio = $builder->build_sample_biblio; C4::ImportBatch::SetMatchedBiblionumber( $import_record_id, $another_biblio->biblionumber ); -my $import_biblios = GetImportBiblios( $import_record_id ); -is( $import_biblios->[0]->{matched_biblionumber}, $another_biblio->biblionumber, 'SetMatchedBiblionumber should set the correct biblionumber' ); +my $import_biblios = GetImportBiblios($import_record_id); +is( + $import_biblios->[0]->{matched_biblionumber}, $another_biblio->biblionumber, + 'SetMatchedBiblionumber should set the correct biblionumber' +); # Add a few tests for GetItemNumbersFromImportBatch -my @a = GetItemNumbersFromImportBatch( $id_import_batch1 ); +my @a = GetItemNumbersFromImportBatch($id_import_batch1); is( @a, 0, 'No item numbers expected since we did not commit' ); my $itemno = $builder->build_sample_item->itemnumber; + # Link this item to the import item to fool GetItemNumbersFromImportBatch my $sql = "UPDATE import_items SET itemnumber=? WHERE import_record_id=?"; $dbh->do( $sql, undef, $itemno, $import_record_id ); -@a = GetItemNumbersFromImportBatch( $id_import_batch1 ); -is( @a, 2, 'Expecting two items now' ); +@a = GetItemNumbersFromImportBatch($id_import_batch1); +is( @a, 2, 'Expecting two items now' ); is( $a[0], $itemno, 'Check the first returned itemnumber' ); + # Now delete the item and check again $dbh->do( "DELETE FROM items WHERE itemnumber=?", undef, $itemno ); -@a = GetItemNumbersFromImportBatch( $id_import_batch1 ); +@a = GetItemNumbersFromImportBatch($id_import_batch1); is( @a, 0, 'No item numbers expected since we deleted the item' ); -$dbh->do( $sql, undef, undef, $import_record_id ); # remove link again +$dbh->do( $sql, undef, undef, $import_record_id ); # remove link again # fresh data my $sample_import_batch3 = { - matcher_id => 3, - template_id => 3, - branchcode => 'QRT', + matcher_id => 3, + template_id => 3, + branchcode => 'QRT', overlay_action => 'create_new', nomatch_action => 'create_new', - item_action => 'always_add', - import_status => 'staged', - batch_type => 'z3950', - file_name => 'test.mrc', - comments => 'test', - record_type => 'auth', + item_action => 'always_add', + import_status => 'staged', + batch_type => 'z3950', + file_name => 'test.mrc', + comments => 'test', + record_type => 'auth', }; my $id_import_batch3 = C4::ImportBatch::AddImportBatch($sample_import_batch3); # Test CleanBatch -C4::ImportBatch::CleanBatch( $id_import_batch3 ); -$import_record = get_import_record( $id_import_batch3 ); +C4::ImportBatch::CleanBatch($id_import_batch3); +$import_record = get_import_record($id_import_batch3); is( $import_record, "0E0", "Batch 3 has been cleaned" ); # Test DeleteBatch -C4::ImportBatch::DeleteBatch( $id_import_batch3 ); -my $import_batch = C4::ImportBatch::GetImportBatch( $id_import_batch3 ); -is( $import_batch, undef, "Batch 3 has been deleted"); +C4::ImportBatch::DeleteBatch($id_import_batch3); +my $import_batch = C4::ImportBatch::GetImportBatch($id_import_batch3); +is( $import_batch, undef, "Batch 3 has been deleted" ); subtest "_batchCommitItems" => sub { plan tests => 3; - my $exist_item = $builder->build_sample_item; - my $import_item = $builder->build_object({ class => 'Koha::Import::Record::Items', value => { - marcxml => q{<?xml version="1.0" encoding="UTF-8"?> + my $exist_item = $builder->build_sample_item; + my $import_item = $builder->build_object( + { + class => 'Koha::Import::Record::Items', + value => { + marcxml => q{<?xml version="1.0" encoding="UTF-8"?> <collection xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.loc.gov/MARC21/slim http://www.loc.gov/standards/marcxml/schema/MARC21slim.xsd" @@ -232,20 +250,25 @@ subtest "_batchCommitItems" => sub { <subfield code="a">CPL</subfield> <subfield code="b">CPL</subfield> <subfield code="c">GEN</subfield> - <subfield code="p">}.$exist_item->barcode.q{</subfield> + <subfield code="p">} . $exist_item->barcode . q{</subfield> <subfield code="y">BK</subfield> </datafield> </record> </collection> }, - }}); + } + } + ); my ( $num_items_added, $num_items_replaced, $num_items_errored ) = - C4::ImportBatch::_batchCommitItems( $import_item->import_record_id, 32, 'always_add',64 ); + C4::ImportBatch::_batchCommitItems( $import_item->import_record_id, 32, 'always_add', 64 ); is( $num_items_errored, 1, "Item with duplicate barcode fails when action always_add" ); $import_item->discard_changes(); - is( $import_item->status, 'error', "Import item marked as error when duplicate barcode and action always_add"); - is( $import_item->import_error, 'duplicate item barcode', 'Error correctly set when import item has duplicate barcode and action always_add' ); + is( $import_item->status, 'error', "Import item marked as error when duplicate barcode and action always_add" ); + is( + $import_item->import_error, 'duplicate item barcode', + 'Error correctly set when import item has duplicate barcode and action always_add' + ); }; subtest "RecordsFromMarcPlugin" => sub { @@ -253,7 +276,7 @@ subtest "RecordsFromMarcPlugin" => sub { # Create a test file my ( $fh, $name ) = tempfile(); - if (C4::Context->preference('marcflavour') eq 'UNIMARC') { + if ( C4::Context->preference('marcflavour') eq 'UNIMARC' ) { print $fh q{ 003 = NLAmRIJ 100,a = 20220520d u||y0frey50 ba @@ -282,21 +305,29 @@ subtest "RecordsFromMarcPlugin" => sub { my $plugins = Koha::Plugins->new; $plugins->InstallPlugins; - my ($plugin) = $plugins->GetPlugins({ all => 1, metadata => { name => 'MarcFieldValues' } }); + my ($plugin) = $plugins->GetPlugins( { all => 1, metadata => { name => 'MarcFieldValues' } } ); isnt( $plugin, undef, "Plugin found" ); my $records = C4::ImportBatch::RecordsFromMarcPlugin( $name, ref $plugin, 'UTF-8' ); - is( @$records, 2, 'Two results returned' ); + is( @$records, 2, 'Two results returned' ); is( ref $records->[0], 'MARC::Record', 'Returned MARC::Record object' ); - if (C4::Context->preference('marcflavour') eq 'UNIMARC') { - is( $records->[0]->subfield('200', 'a'), 'Silence in the library', - 'Checked one field in first record' ); - is( $records->[1]->subfield('700', 'a'), 'Another', - 'Checked one field in second record' ); + if ( C4::Context->preference('marcflavour') eq 'UNIMARC' ) { + is( + $records->[0]->subfield( '200', 'a' ), 'Silence in the library', + 'Checked one field in first record' + ); + is( + $records->[1]->subfield( '700', 'a' ), 'Another', + 'Checked one field in second record' + ); } else { - is( $records->[0]->subfield('245', 'a'), 'Silence in the library', - 'Checked one field in first record' ); - is( $records->[1]->subfield('100', 'a'), 'Another', - 'Checked one field in second record' ); + is( + $records->[0]->subfield( '245', 'a' ), 'Silence in the library', + 'Checked one field in first record' + ); + is( + $records->[1]->subfield( '100', 'a' ), 'Another', + 'Checked one field in second record' + ); } }; @@ -305,23 +336,33 @@ subtest "_get_commit_action" => sub { my $mock_import = Test::MockModule->new("C4::ImportBatch"); $mock_import->mock( GetBestRecordMatch => sub { return 5; } ); - foreach my $record_type ( ('biblio','authority') ){ - foreach my $match_action ( ('replace','create_new','ignore') ){ - foreach my $no_match_action ( ('create_new','ignore') ){ - my ($result, $match, $item_result) = - C4::ImportBatch::_get_commit_action($match_action, $no_match_action, 'always_add', 'auto_match', 42, $record_type); - is( $result, $match_action, "When match found amd chosen we return the match_action for $record_type records with match action $match_action and no match action $no_match_action"); + foreach my $record_type ( ( 'biblio', 'authority' ) ) { + foreach my $match_action ( ( 'replace', 'create_new', 'ignore' ) ) { + foreach my $no_match_action ( ( 'create_new', 'ignore' ) ) { + my ( $result, $match, $item_result ) = C4::ImportBatch::_get_commit_action( + $match_action, $no_match_action, 'always_add', 'auto_match', + 42, $record_type + ); + is( + $result, $match_action, + "When match found amd chosen we return the match_action for $record_type records with match action $match_action and no match action $no_match_action" + ); } } } $mock_import->mock( GetBestRecordMatch => sub { my $matches = undef; return $matches; } ); - foreach my $record_type ( ('biblio','authority') ){ - foreach my $match_action ( ('replace','create_new','ignore') ){ - foreach my $no_match_action ( ('create_new','ignore') ){ - my ($result, $match, $item_result) = - C4::ImportBatch::_get_commit_action($match_action, $no_match_action, 'always_add', 'auto_match', 42, $record_type); - is( $result, $no_match_action, "When no match found or chosen we return the match_action for $record_type records with match action $match_action and no match action $no_match_action"); + foreach my $record_type ( ( 'biblio', 'authority' ) ) { + foreach my $match_action ( ( 'replace', 'create_new', 'ignore' ) ) { + foreach my $no_match_action ( ( 'create_new', 'ignore' ) ) { + my ( $result, $match, $item_result ) = C4::ImportBatch::_get_commit_action( + $match_action, $no_match_action, 'always_add', 'auto_match', + 42, $record_type + ); + is( + $result, $no_match_action, + "When no match found or chosen we return the match_action for $record_type records with match action $match_action and no match action $no_match_action" + ); } } } @@ -332,30 +373,32 @@ subtest "BatchCommitRecords overlay into framework" => sub { plan tests => 1; t::lib::Mocks::mock_config( 'enable_plugins', 0 ); my $mock_import = Test::MockModule->new("C4::ImportBatch"); - my $biblio = $builder->build_sample_biblio; - $mock_import->mock( _get_commit_action => sub { return ('replace','ignore',$biblio->biblionumber); } ); + my $biblio = $builder->build_sample_biblio; + $mock_import->mock( _get_commit_action => sub { return ( 'replace', 'ignore', $biblio->biblionumber ); } ); my $import_batch = { - matcher_id => 2, - template_id => 2, - branchcode => 'QRZ', + matcher_id => 2, + template_id => 2, + branchcode => 'QRZ', overlay_action => 'replace', nomatch_action => 'ignore', - item_action => 'ignore', - import_status => 'staged', - batch_type => 'z3950', - file_name => 'test.mrc', - comments => 'test', - record_type => 'auth', + item_action => 'ignore', + import_status => 'staged', + batch_type => 'z3950', + file_name => 'test.mrc', + comments => 'test', + record_type => 'auth', }; - my $id_import_batch = C4::ImportBatch::AddImportBatch($import_batch); + my $id_import_batch = C4::ImportBatch::AddImportBatch($import_batch); my $import_record_id = AddBiblioToBatch( $id_import_batch, 0, $biblio->metadata->record, 'utf8', 0 ); - BatchCommitRecords({ - batch_id => $id_import_batch, - framework => "", - overlay_framework => "QQ", - }); + BatchCommitRecords( + { + batch_id => $id_import_batch, + framework => "", + overlay_framework => "QQ", + } + ); $biblio->discard_changes; is( $biblio->frameworkcode, "QQ", "Framework set on overlay" ); }; @@ -363,15 +406,18 @@ subtest "BatchCommitRecords overlay into framework" => sub { subtest "Do not adjust biblionumber when replacing items during import" => sub { plan tests => 7; - my $item1 = $builder->build_sample_item; - my $original_biblionumber = $item1->biblionumber; + my $item1 = $builder->build_sample_item; + my $original_biblionumber = $item1->biblionumber; my $original_biblioitemnumber = $item1->biblioitemnumber; - my $item2 = $builder->build_sample_item; + my $item2 = $builder->build_sample_item; - my $library = $builder->build_object({ class => 'Koha::Libraries' }); + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); - my $import_item = $builder->build_object({ class => 'Koha::Import::Record::Items', value => { - marcxml => qq{<?xml version="1.0" encoding="UTF-8"?> + my $import_item = $builder->build_object( + { + class => 'Koha::Import::Record::Items', + value => { + marcxml => qq{<?xml version="1.0" encoding="UTF-8"?> <collection xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.loc.gov/MARC21/slim http://www.loc.gov/standards/marcxml/schema/MARC21slim.xsd" @@ -389,9 +435,14 @@ subtest "Do not adjust biblionumber when replacing items during import" => sub { </record> </collection> }, - }}); + } + } + ); - isnt( $item1->homebranch, $library->branchcode, "Item's homebranch is currently not the same as our created branch's branchcode" ); + isnt( + $item1->homebranch, $library->branchcode, + "Item's homebranch is currently not the same as our created branch's branchcode" + ); my ( $num_items_added, $num_items_replaced, $num_items_errored ) = C4::ImportBatch::_batchCommitItems( $import_item->import_record_id, $item2->biblionumber, 'replace' ); @@ -400,17 +451,17 @@ subtest "Do not adjust biblionumber when replacing items during import" => sub { is( $num_items_errored, 0, 'Item was replaced' ); $import_item->discard_changes(); - is( $import_item->status, 'imported', 'Import was successful'); - is( $import_item->import_error, undef, 'No error was reported' ); + is( $import_item->status, 'imported', 'Import was successful' ); + is( $import_item->import_error, undef, 'No error was reported' ); - is( $item1->biblionumber, $original_biblionumber, "Item's biblionumber has not changed" ); + is( $item1->biblionumber, $original_biblionumber, "Item's biblionumber has not changed" ); is( $item1->biblioitemnumber, $original_biblioitemnumber, "Item's biblioitemnumber has not changed" ); - is( $item1->homebranch, $library->branchcode, "Item was overlaid successfully" ); + is( $item1->homebranch, $library->branchcode, "Item was overlaid successfully" ); }; sub get_import_record { my $id_import_batch = shift; - return $dbh->do('SELECT * FROM import_records WHERE import_batch_id = ?', undef, $id_import_batch); + return $dbh->do( 'SELECT * FROM import_records WHERE import_batch_id = ?', undef, $id_import_batch ); } $schema->storage->txn_rollback; diff --git a/t/db_dependent/ImportExportFramework.t b/t/db_dependent/ImportExportFramework.t index db88a7c72e..a521045969 100755 --- a/t/db_dependent/ImportExportFramework.t +++ b/t/db_dependent/ImportExportFramework.t @@ -87,27 +87,27 @@ sub run_biblio_tests { $schema->storage->txn_begin; my $data_filepath = dirname(__FILE__) . "/data/frameworks/biblio_framework.$format"; - my $fw_1 = $builder->build_object({ class => 'Koha::BiblioFrameworks' }); + my $fw_1 = $builder->build_object( { class => 'Koha::BiblioFrameworks' } ); my $result = C4::ImportExportFramework::ImportFramework( $data_filepath, $fw_1->id, 0, $type ); is( $result, 0, 'Import successful, no tags removed' ); - my $nb_tags = $schema->resultset('MarcTagStructure')->search({ frameworkcode => $fw_1->id })->count; + my $nb_tags = $schema->resultset('MarcTagStructure')->search( { frameworkcode => $fw_1->id } )->count; is( $nb_tags, 4, "4 tags should have been imported" ); - my $nb_subfields = Koha::MarcSubfieldStructures->search({ frameworkcode => $fw_1->id })->count; + my $nb_subfields = Koha::MarcSubfieldStructures->search( { frameworkcode => $fw_1->id } )->count; is( $nb_subfields, 12, "12 subfields should have been imported" ); # bad file tests - my $fw_2 = $builder->build_object({ class => 'Koha::BiblioFrameworks' }); + my $fw_2 = $builder->build_object( { class => 'Koha::BiblioFrameworks' } ); $result = C4::ImportExportFramework::ImportFramework( '', $fw_2->id, 0, $type ); is( $result, -1, 'Bad file makes it return -1' ); - $nb_tags = $schema->resultset('MarcTagStructure')->search({ frameworkcode => $fw_2->id })->count; + $nb_tags = $schema->resultset('MarcTagStructure')->search( { frameworkcode => $fw_2->id } )->count; is( $nb_tags, 0, "0 tags should have been imported" ); - $nb_subfields = Koha::MarcSubfieldStructures->search({ frameworkcode => $fw_2->id })->count; + $nb_subfields = Koha::MarcSubfieldStructures->search( { frameworkcode => $fw_2->id } )->count; is( $nb_subfields, 0, "0 subfields should have been imported" ); # framework overwrite @@ -116,45 +116,45 @@ sub run_biblio_tests { $result = C4::ImportExportFramework::ImportFramework( $data_filepath, $fw_1->id, 0, $type ); is( $result, 5, 'Smaller fw import successful, 4 tags removed' ); - $nb_tags = $schema->resultset('MarcTagStructure')->search({ frameworkcode => $fw_1->id })->count; + $nb_tags = $schema->resultset('MarcTagStructure')->search( { frameworkcode => $fw_1->id } )->count; is( $nb_tags, 3, "3 tags should have been imported" ); - $nb_subfields = Koha::MarcSubfieldStructures->search({ frameworkcode => $fw_1->id })->count; + $nb_subfields = Koha::MarcSubfieldStructures->search( { frameworkcode => $fw_1->id } )->count; is( $nb_subfields, 8, "8 subfields should have been imported" ); $schema->storage->txn_rollback; -}; +} sub run_csv_no_quoted { $schema->storage->txn_begin; my $data_filepath = dirname(__FILE__) . "/data/frameworks/biblio_framework_no_quoted.csv"; - my $fw_1 = $builder->build_object({ class => 'Koha::BiblioFrameworks' }); + my $fw_1 = $builder->build_object( { class => 'Koha::BiblioFrameworks' } ); my $result = C4::ImportExportFramework::ImportFramework( $data_filepath, $fw_1->id ); is( $result, 0, 'Import successful, no tags removed' ); - my $nb_tags = $schema->resultset('MarcTagStructure')->search({ frameworkcode => $fw_1->id })->count; + my $nb_tags = $schema->resultset('MarcTagStructure')->search( { frameworkcode => $fw_1->id } )->count; is( $nb_tags, 4, "4 tags should have been imported" ); - my $nb_subfields = Koha::MarcSubfieldStructures->search({ frameworkcode => $fw_1->id })->count; + my $nb_subfields = Koha::MarcSubfieldStructures->search( { frameworkcode => $fw_1->id } )->count; is( $nb_subfields, 12, "12 subfields should have been imported" ); # bad file tests - my $fw_2 = $builder->build_object({ class => 'Koha::BiblioFrameworks' }); + my $fw_2 = $builder->build_object( { class => 'Koha::BiblioFrameworks' } ); $result = C4::ImportExportFramework::ImportFramework( '', $fw_2->id ); is( $result, -1, 'Bad file makes it return -1' ); - $nb_tags = $schema->resultset('MarcTagStructure')->search({ frameworkcode => $fw_2->id })->count; + $nb_tags = $schema->resultset('MarcTagStructure')->search( { frameworkcode => $fw_2->id } )->count; is( $nb_tags, 0, "0 tags should have been imported" ); - $nb_subfields = Koha::MarcSubfieldStructures->search({ frameworkcode => $fw_2->id })->count; + $nb_subfields = Koha::MarcSubfieldStructures->search( { frameworkcode => $fw_2->id } )->count; is( $nb_subfields, 0, "0 subfields should have been imported" ); $schema->storage->txn_rollback; -}; +} sub run_ods_new { @@ -163,32 +163,31 @@ sub run_ods_new { $schema->storage->txn_begin; my $data_filepath = dirname(__FILE__) . "/data/frameworks/biblio_framework_new.ods"; - my $fw_1 = $builder->build_object({ class => 'Koha::BiblioFrameworks' }); + my $fw_1 = $builder->build_object( { class => 'Koha::BiblioFrameworks' } ); my $result = C4::ImportExportFramework::ImportFramework( $data_filepath, $fw_1->id ); is( $result, 0, 'Import successful, no tags removed' ); - my $nb_tags = $schema->resultset('MarcTagStructure')->search({ frameworkcode => $fw_1->id })->count; + my $nb_tags = $schema->resultset('MarcTagStructure')->search( { frameworkcode => $fw_1->id } )->count; is( $nb_tags, 5, "5 tags should have been imported" ); - my $nb_subfields = Koha::MarcSubfieldStructures->search({ frameworkcode => $fw_1->id })->count; + my $nb_subfields = Koha::MarcSubfieldStructures->search( { frameworkcode => $fw_1->id } )->count; is( $nb_subfields, 16, "16 subfields should have been imported" ); # bad file tests - my $fw_2 = $builder->build_object({ class => 'Koha::BiblioFrameworks' }); + my $fw_2 = $builder->build_object( { class => 'Koha::BiblioFrameworks' } ); $result = C4::ImportExportFramework::ImportFramework( '', $fw_2->id ); is( $result, -1, 'Bad file makes it return -1' ); - $nb_tags = $schema->resultset('MarcTagStructure')->search({ frameworkcode => $fw_2->id })->count; + $nb_tags = $schema->resultset('MarcTagStructure')->search( { frameworkcode => $fw_2->id } )->count; is( $nb_tags, 0, "0 tags should have been imported" ); - $nb_subfields = Koha::MarcSubfieldStructures->search({ frameworkcode => $fw_2->id })->count; + $nb_subfields = Koha::MarcSubfieldStructures->search( { frameworkcode => $fw_2->id } )->count; is( $nb_subfields, 0, "0 subfields should have been imported" ); - $schema->storage->txn_rollback; -}; +} sub run_auth_tests { @@ -198,27 +197,27 @@ sub run_auth_tests { $schema->storage->txn_begin; my $data_filepath = dirname(__FILE__) . "/data/frameworks/auth_type.$format"; - my $fw_1 = $builder->build_object({ class => 'Koha::Authority::Types' }); + my $fw_1 = $builder->build_object( { class => 'Koha::Authority::Types' } ); my $result = C4::ImportExportFramework::ImportFramework( $data_filepath, $fw_1->id, '', $type ); is( $result, 0, 'Import successful, no tags removed' ); - my $nb_tags = $schema->resultset('AuthTagStructure')->search({ authtypecode => $fw_1->id })->count; + my $nb_tags = $schema->resultset('AuthTagStructure')->search( { authtypecode => $fw_1->id } )->count; is( $nb_tags, 6, "6 tags should have been imported" ); - my $nb_subfields = Koha::Authority::Subfields->search({ authtypecode => $fw_1->id })->count; + my $nb_subfields = Koha::Authority::Subfields->search( { authtypecode => $fw_1->id } )->count; is( $nb_subfields, 8, "8 subfields should have been imported" ); # bad file tests - my $fw_2 = $builder->build_object({ class => 'Koha::Authority::Types' }); + my $fw_2 = $builder->build_object( { class => 'Koha::Authority::Types' } ); $result = C4::ImportExportFramework::ImportFramework( '', $fw_2->id, '', $type ); is( $result, -1, 'Bad file makes it return -1' ); - $nb_tags = $schema->resultset('AuthTagStructure')->search({ authtypecode => $fw_2->id })->count; + $nb_tags = $schema->resultset('AuthTagStructure')->search( { authtypecode => $fw_2->id } )->count; is( $nb_tags, 0, "0 tags should have been imported" ); - $nb_subfields = Koha::Authority::Subfields->search({ authtypecode => $fw_2->id })->count; + $nb_subfields = Koha::Authority::Subfields->search( { authtypecode => $fw_2->id } )->count; is( $nb_subfields, 0, "0 subfields should have been imported" ); # framework overwrite @@ -227,11 +226,11 @@ sub run_auth_tests { $result = C4::ImportExportFramework::ImportFramework( $data_filepath, $fw_1->id, '', $type ); is( $result, 8, 'Smaller fw import successful, 6 tags removed' ); - $nb_tags = $schema->resultset('AuthTagStructure')->search({ authtypecode => $fw_1->id })->count; + $nb_tags = $schema->resultset('AuthTagStructure')->search( { authtypecode => $fw_1->id } )->count; is( $nb_tags, 3, "3 tags should have been imported" ); - $nb_subfields = Koha::Authority::Subfields->search({ authtypecode => $fw_1->id })->count; + $nb_subfields = Koha::Authority::Subfields->search( { authtypecode => $fw_1->id } )->count; is( $nb_subfields, 3, "3 subfields should have been imported" ); $schema->storage->txn_rollback; -}; +} diff --git a/t/db_dependent/Installer.t b/t/db_dependent/Installer.t index 2e9c0e26c8..5570d008a3 100755 --- a/t/db_dependent/Installer.t +++ b/t/db_dependent/Installer.t @@ -29,11 +29,14 @@ use utf8; use Koha::Database; BEGIN { - use_ok('C4::Installer', qw( column_exists index_exists unique_key_exists foreign_key_exists primary_key_exists marc_framework_sql_list )); + use_ok( + 'C4::Installer', + qw( column_exists index_exists unique_key_exists foreign_key_exists primary_key_exists marc_framework_sql_list ) + ); } ok( my $installer = C4::Installer->new(), 'Testing NewInstaller' ); -is( ref $installer, 'C4::Installer', 'Testing class of object' ); +is( ref $installer, 'C4::Installer', 'Testing class of object' ); is( $installer->{'dbname'}, C4::Context->config('database'), 'Testing DbName' ); is( $installer->{'dbms'}, @@ -57,38 +60,41 @@ my $source = $schema->source('Borrower'); my @column_names = $source->columns(); my $column_name = $column_names[0]; -ok( column_exists( 'borrowers', $column_name ), 'Known column does exist' ); -ok( ! column_exists( 'borrowers', 'xxx'), 'Column xxx does not exist' ); +ok( column_exists( 'borrowers', $column_name ), 'Known column does exist' ); +ok( !column_exists( 'borrowers', 'xxx' ), 'Column xxx does not exist' ); { - ok( ! column_exists( 'this_table_will_never_exist', 'xxx'), 'Column xxx does not exist, the table does not exist' ); + ok( !column_exists( 'this_table_will_never_exist', 'xxx' ), 'Column xxx does not exist, the table does not exist' ); } my @constraint_names = $source->unique_constraint_names(); my $constraint_name = $constraint_names[0]; -ok( index_exists( 'borrowers', $constraint_name), 'Known contraint does exist' ); -ok( ! index_exists( 'borrowers', 'xxx'), 'Constraint xxx does not exist' ); +ok( index_exists( 'borrowers', $constraint_name ), 'Known contraint does exist' ); +ok( !index_exists( 'borrowers', 'xxx' ), 'Constraint xxx does not exist' ); -ok( foreign_key_exists( 'borrowers', 'borrowers_ibfk_1' ), 'FK borrowers_ibfk_1 exists' ); -ok( ! foreign_key_exists( 'borrowers', 'xxx' ), 'FK xxxx does not exist' ); +ok( foreign_key_exists( 'borrowers', 'borrowers_ibfk_1' ), 'FK borrowers_ibfk_1 exists' ); +ok( !foreign_key_exists( 'borrowers', 'xxx' ), 'FK xxxx does not exist' ); -ok( unique_key_exists( 'items', 'itembarcodeidx' ), 'UNIQUE KEY itembarcodeidx exists' ); -ok( ! unique_key_exists( 'borrowers', 'xxx' ), 'UNIQUE KEY xxxx does not exist' ); +ok( unique_key_exists( 'items', 'itembarcodeidx' ), 'UNIQUE KEY itembarcodeidx exists' ); +ok( !unique_key_exists( 'borrowers', 'xxx' ), 'UNIQUE KEY xxxx does not exist' ); -ok( primary_key_exists( 'borrowers' ), 'Borrowers does have a primary key on some column'); -ok( primary_key_exists( 'borrowers', 'borrowernumber'), 'Borrowers has primary key on borrowernumber'); -ok( ! primary_key_exists( 'borrowers', 'email'), 'Borrowers does not have a primary key on email'); +ok( primary_key_exists('borrowers'), 'Borrowers does have a primary key on some column' ); +ok( primary_key_exists( 'borrowers', 'borrowernumber' ), 'Borrowers has primary key on borrowernumber' ); +ok( !primary_key_exists( 'borrowers', 'email' ), 'Borrowers does not have a primary key on email' ); subtest 'marc_framework_sql_list' => sub { plan tests => 1; - my ($fh, $filepath) = tempfile( DIR => C4::Context->config("intranetdir") . "/installer/data/mysql/en/marcflavour/marc21/mandatory", SUFFIX => '.yml', UNLINK => 1 ); + my ( $fh, $filepath ) = tempfile( + DIR => C4::Context->config("intranetdir") . "/installer/data/mysql/en/marcflavour/marc21/mandatory", + SUFFIX => '.yml', UNLINK => 1 + ); print $fh Encode::encode_utf8("---\ndescription:\n - \"Standardowe typy haseł przedmiotowych MARC21\"\n"); close $fh; - my $yaml_files = $installer->marc_framework_sql_list('en', 'MARC21'); + my $yaml_files = $installer->marc_framework_sql_list( 'en', 'MARC21' ); my $description; - FILE: for my $file ( @$yaml_files ) { - for my $framework ( @{ $file->{frameworks}} ) { +FILE: for my $file (@$yaml_files) { + for my $framework ( @{ $file->{frameworks} } ) { if ( $framework->{fwkfile} eq $filepath ) { $description = $framework->{fwkdescription}->[0]; last FILE; diff --git a/t/db_dependent/Items.t b/t/db_dependent/Items.t index 1954162a0a..6f310a9fb7 100755 --- a/t/db_dependent/Items.t +++ b/t/db_dependent/Items.t @@ -21,7 +21,7 @@ use Data::Dumper; use MARC::Record; use C4::Items qw( ModItemTransfer SearchItems AddItemFromMarc ModItemFromMarc get_hostitemnumbers_of Item2Marc ModDateLastSeen CartToShelf CheckItemPreSave ); -use C4::Biblio qw( GetMarcFromKohaField AddBiblio ); +use C4::Biblio qw( GetMarcFromKohaField AddBiblio ); use C4::Circulation qw( AddIssue ); use Koha::BackgroundJobs; use Koha::Items; @@ -40,7 +40,7 @@ use Test::More tests => 14; use Test::Warn; -my $schema = Koha::Database->new->schema; +my $schema = Koha::Database->new->schema; my $location = 'My Location'; subtest 'General Add, Get and Del tests' => sub { @@ -50,15 +50,19 @@ subtest 'General Add, Get and Del tests' => sub { $schema->storage->txn_begin; my $builder = t::lib::TestBuilder->new; - my $library = $builder->build({ - source => 'Branch', - }); - my $itemtype = $builder->build({ - source => 'Itemtype', - }); + my $library = $builder->build( + { + source => 'Branch', + } + ); + my $itemtype = $builder->build( + { + source => 'Itemtype', + } + ); # Create a biblio instance for testing - t::lib::Mocks::mock_preference('marcflavour', 'MARC21'); + t::lib::Mocks::mock_preference( 'marcflavour', 'MARC21' ); my $biblio = $builder->build_sample_biblio(); # Add an item. @@ -71,60 +75,66 @@ subtest 'General Add, Get and Del tests' => sub { } ); my $itemnumber = $item->itemnumber; - cmp_ok($item->biblionumber, '==', $biblio->biblionumber, "New item is linked to correct biblionumber."); - cmp_ok($item->biblioitemnumber, '==', $biblio->biblioitem->biblioitemnumber, "New item is linked to correct biblioitemnumber."); + cmp_ok( $item->biblionumber, '==', $biblio->biblionumber, "New item is linked to correct biblionumber." ); + cmp_ok( + $item->biblioitemnumber, '==', $biblio->biblioitem->biblioitemnumber, + "New item is linked to correct biblioitemnumber." + ); # Get item. my $getitem = Koha::Items->find($itemnumber); - cmp_ok($getitem->itemnumber, '==', $itemnumber, "Retrieved item has correct itemnumber."); - cmp_ok($getitem->biblioitemnumber, '==', $item->biblioitemnumber, "Retrieved item has correct biblioitemnumber."); # We are not testing anything useful here - is( $getitem->location, $location, "The location should not have been modified" ); + cmp_ok( $getitem->itemnumber, '==', $itemnumber, "Retrieved item has correct itemnumber." ); + cmp_ok( $getitem->biblioitemnumber, '==', $item->biblioitemnumber, "Retrieved item has correct biblioitemnumber." ) + ; # We are not testing anything useful here + is( $getitem->location, $location, "The location should not have been modified" ); is( $getitem->permanent_location, $location, "The permanent_location should have been set to the location value" ); - # Do not modify anything, and do not explode! - $getitem->set({})->store; + $getitem->set( {} )->store; # Modify item; setting barcode. $getitem->barcode('987654321')->store; my $moditem = Koha::Items->find($itemnumber); - cmp_ok($moditem->barcode, '==', '987654321', 'Modified item barcode successfully to: '.$moditem->barcode . '.'); + cmp_ok( $moditem->barcode, '==', '987654321', 'Modified item barcode successfully to: ' . $moditem->barcode . '.' ); # Delete item. $moditem->delete; my $getdeleted = Koha::Items->find($itemnumber); - is($getdeleted, undef, "Item deleted as expected."); + is( $getdeleted, undef, "Item deleted as expected." ); $itemnumber = $builder->build_sample_item( { - biblionumber => $biblio->biblionumber, - library => $library->{branchcode}, - location => $location, + biblionumber => $biblio->biblionumber, + library => $library->{branchcode}, + location => $location, permanent_location => 'my permanent location', - itype => $itemtype->{itemtype} + itype => $itemtype->{itemtype} } )->itemnumber; $getitem = Koha::Items->find($itemnumber); - is( $getitem->location, $location, "The location should not have been modified" ); + is( $getitem->location, $location, "The location should not have been modified" ); is( $getitem->permanent_location, 'my permanent location', "The permanent_location should not have modified" ); my $new_location = "New location"; $getitem->location($new_location)->store; $getitem = Koha::Items->find($itemnumber); - is( $getitem->location, $new_location, "The location should have been set to correct location" ); + is( $getitem->location, $new_location, "The location should have been set to correct location" ); is( $getitem->permanent_location, $new_location, "The permanent_location should have been set to location" ); $getitem->location('CART')->store; $getitem = Koha::Items->find($itemnumber); - is( $getitem->location, 'CART', "The location should have been set to CART" ); + is( $getitem->location, 'CART', "The location should have been set to CART" ); is( $getitem->permanent_location, $new_location, "The permanent_location should not have been set to CART" ); - t::lib::Mocks::mock_preference('item-level_itypes', '1'); + t::lib::Mocks::mock_preference( 'item-level_itypes', '1' ); $getitem = Koha::Items->find($itemnumber); is( $getitem->effective_itemtype, $itemtype->{itemtype}, "Itemtype set correctly when using item-level_itypes" ); - t::lib::Mocks::mock_preference('item-level_itypes', '0'); + t::lib::Mocks::mock_preference( 'item-level_itypes', '0' ); $getitem = Koha::Items->find($itemnumber); - is( $getitem->effective_itemtype, $biblio->biblioitem->itemtype, "Itemtype set correctly when not using item-level_itypes" ); + is( + $getitem->effective_itemtype, $biblio->biblioitem->itemtype, + "Itemtype set correctly when not using item-level_itypes" + ); $schema->storage->txn_rollback; }; @@ -170,38 +180,40 @@ subtest 'ModItemTransfer tests' => sub { } ); - ModItemTransfer( $item->itemnumber, $library1->{branchcode}, - $library2->{branchcode}, 'Manual' ); - - my $transfers = Koha::Item::Transfers->search( - { - itemnumber => $item->itemnumber - } + ModItemTransfer( + $item->itemnumber, $library1->{branchcode}, + $library2->{branchcode}, 'Manual' ); + my $transfers = Koha::Item::Transfers->search( { itemnumber => $item->itemnumber } ); + is( $transfers->count, 1, "One transfer created with ModItemTransfer" ); $item->discard_changes; - is($item->holdingbranch, $library1->{branchcode}, "Items holding branch was updated to frombranch"); + is( $item->holdingbranch, $library1->{branchcode}, "Items holding branch was updated to frombranch" ); - ModItemTransfer( $item->itemnumber, $library2->{branchcode}, - $library1->{branchcode}, 'Manual' ); + ModItemTransfer( + $item->itemnumber, $library2->{branchcode}, + $library1->{branchcode}, 'Manual' + ); $transfers = Koha::Item::Transfers->search( { itemnumber => $item->itemnumber, }, { order_by => { '-asc' => 'branchtransfer_id' } } ); - is($transfers->count, 2, "Second transfer recorded on second call of ModItemTransfer"); + is( $transfers->count, 2, "Second transfer recorded on second call of ModItemTransfer" ); my $transfer1 = $transfers->next; my $transfer2 = $transfers->next; - isnt($transfer1->datecancelled, undef, "First transfer marked as cancelled by ModItemTransfer"); - like($transfer1->cancellation_reason,qr/^Manual/, "First transfer contains cancellation_reason 'Manual'"); - is($transfer2->datearrived, undef, "Second transfer is now the active transfer"); + isnt( $transfer1->datecancelled, undef, "First transfer marked as cancelled by ModItemTransfer" ); + like( $transfer1->cancellation_reason, qr/^Manual/, "First transfer contains cancellation_reason 'Manual'" ); + is( $transfer2->datearrived, undef, "Second transfer is now the active transfer" ); $item->discard_changes; - is($item->holdingbranch, $library2->{branchcode}, "Items holding branch was updated to frombranch"); + is( $item->holdingbranch, $library2->{branchcode}, "Items holding branch was updated to frombranch" ); # Check 'reason' is populated when passed - ModItemTransfer( $item->itemnumber, $library2->{branchcode}, - $library1->{branchcode}, "Manual" ); + ModItemTransfer( + $item->itemnumber, $library2->{branchcode}, + $library1->{branchcode}, "Manual" + ); $transfers = Koha::Item::Transfers->search( { itemnumber => $item->itemnumber, }, @@ -209,7 +221,7 @@ subtest 'ModItemTransfer tests' => sub { ); my $transfer3 = $transfers->next; - is($transfer3->reason, 'Manual', "Reason set via ModItemTransfer"); + is( $transfer3->reason, 'Manual', "Reason set via ModItemTransfer" ); # Ensure StockrotationAdvance transfers are not cancelled my $stock_transfer = $transfer3->reason('StockrotationAdvance')->store(); @@ -248,36 +260,48 @@ subtest q{Test Koha::Database->schema()->resultset('Item')->itemtype()} => sub { $schema->storage->txn_begin; - my $biblio = $schema->resultset('Biblio')->create({ - title => "Test title", - datecreated => dt_from_string, - biblioitems => [ { itemtype => 'BIB_LEVEL' } ], - }); + my $biblio = $schema->resultset('Biblio')->create( + { + title => "Test title", + datecreated => dt_from_string, + biblioitems => [ { itemtype => 'BIB_LEVEL' } ], + } + ); my $biblioitem = $biblio->biblioitems->first; - my $item = $schema->resultset('Item')->create({ - biblioitemnumber => $biblioitem->biblioitemnumber, - biblionumber => $biblio->biblionumber, - itype => "ITEM_LEVEL", - }); + my $item = $schema->resultset('Item')->create( + { + biblioitemnumber => $biblioitem->biblioitemnumber, + biblionumber => $biblio->biblionumber, + itype => "ITEM_LEVEL", + } + ); t::lib::Mocks::mock_preference( 'item-level_itypes', 0 ); - is( $item->effective_itemtype(), 'BIB_LEVEL', '$item->itemtype() returns biblioitem.itemtype when item-level_itypes is disabled' ); + is( + $item->effective_itemtype(), 'BIB_LEVEL', + '$item->itemtype() returns biblioitem.itemtype when item-level_itypes is disabled' + ); t::lib::Mocks::mock_preference( 'item-level_itypes', 1 ); - is( $item->effective_itemtype(), 'ITEM_LEVEL', '$item->itemtype() returns items.itype when item-level_itypes is enabled' ); + is( + $item->effective_itemtype(), 'ITEM_LEVEL', + '$item->itemtype() returns items.itype when item-level_itypes is enabled' + ); # If itemtype is not defined and item-level_level item types are set # fallback to biblio-level itemtype (Bug 14651) and warn - $item->itype( undef ); + $item->itype(undef); $item->update(); my $effective_itemtype; warning_is { $effective_itemtype = $item->effective_itemtype() } - "item-level_itypes set but no itemtype set for item (".$item->itemnumber.")", - '->effective_itemtype() raises a warning when falling back to bib-level'; + "item-level_itypes set but no itemtype set for item (" . $item->itemnumber . ")", + '->effective_itemtype() raises a warning when falling back to bib-level'; - ok( defined $effective_itemtype && - $effective_itemtype eq 'BIB_LEVEL', - '$item->effective_itemtype() falls back to biblioitems.itemtype when item-level_itypes is enabled but undef' ); + ok( + defined $effective_itemtype + && $effective_itemtype eq 'BIB_LEVEL', + '$item->effective_itemtype() falls back to biblioitems.itemtype when item-level_itypes is enabled but undef' + ); $schema->storage->txn_rollback; }; @@ -286,26 +310,32 @@ subtest 'SearchItems test' => sub { plan tests => 21; $schema->storage->txn_begin; - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $builder = t::lib::TestBuilder->new; - my $library1 = $builder->build({ - source => 'Branch', - }); - my $library2 = $builder->build({ - source => 'Branch', - }); - my $itemtype = $builder->build({ - source => 'Itemtype', - }); + my $library1 = $builder->build( + { + source => 'Branch', + } + ); + my $library2 = $builder->build( + { + source => 'Branch', + } + ); + my $itemtype = $builder->build( + { + source => 'Itemtype', + } + ); - t::lib::Mocks::mock_preference('marcflavour', 'MARC21'); + t::lib::Mocks::mock_preference( 'marcflavour', 'MARC21' ); my ($cpl_items_before) = SearchItems( { field => 'homebranch', query => $library1->{branchcode} } ); - my $biblio = $builder->build_sample_biblio({ title => 'Silence in the library' }); - $builder->build_sample_biblio({ title => 'Silence in the shadow' }); + my $biblio = $builder->build_sample_biblio( { title => 'Silence in the library' } ); + $builder->build_sample_biblio( { title => 'Silence in the shadow' } ); - my (undef, $initial_items_count) = SearchItems(undef, {rows => 1}); + my ( undef, $initial_items_count ) = SearchItems( undef, { rows => 1 } ); # Add two items my $item1 = $builder->build_sample_item( @@ -324,93 +354,99 @@ subtest 'SearchItems test' => sub { } )->itemnumber; - my ($items, $total_results); + my ( $items, $total_results ); - ($items, $total_results) = SearchItems(); + ( $items, $total_results ) = SearchItems(); - is($total_results, $initial_items_count + 2, "Created 2 new items"); - is(scalar @$items, $total_results, "SearchItems() returns all items"); + is( $total_results, $initial_items_count + 2, "Created 2 new items" ); + is( scalar @$items, $total_results, "SearchItems() returns all items" ); - ($items, $total_results) = SearchItems(undef, {rows => 1}); - is($total_results, $initial_items_count + 2); - is(scalar @$items, 1, "SearchItems(undef, {rows => 1}) returns only 1 item"); + ( $items, $total_results ) = SearchItems( undef, { rows => 1 } ); + is( $total_results, $initial_items_count + 2 ); + is( scalar @$items, 1, "SearchItems(undef, {rows => 1}) returns only 1 item" ); # Search all items where homebranch = 'CPL' my $filter = { - field => 'homebranch', - query => $library1->{branchcode}, + field => 'homebranch', + query => $library1->{branchcode}, operator => '=', }; - ($items, $total_results) = SearchItems($filter); - ok($total_results > 0, "There is at least one CPL item"); + ( $items, $total_results ) = SearchItems($filter); + ok( $total_results > 0, "There is at least one CPL item" ); my $all_items_are_CPL = 1; foreach my $item (@$items) { - if ($item->{homebranch} ne $library1->{branchcode}) { + if ( $item->{homebranch} ne $library1->{branchcode} ) { $all_items_are_CPL = 0; last; } } - ok($all_items_are_CPL, "All items returned by SearchItems are from CPL"); + ok( $all_items_are_CPL, "All items returned by SearchItems are from CPL" ); # Search all items where homebranch != 'CPL' $filter = { - field => 'homebranch', - query => $library1->{branchcode}, + field => 'homebranch', + query => $library1->{branchcode}, operator => '!=', }; - ($items, $total_results) = SearchItems($filter); - ok($total_results > 0, "There is at least one non-CPL item"); + ( $items, $total_results ) = SearchItems($filter); + ok( $total_results > 0, "There is at least one non-CPL item" ); my $all_items_are_not_CPL = 1; foreach my $item (@$items) { - if ($item->{homebranch} eq $library1->{branchcode}) { + if ( $item->{homebranch} eq $library1->{branchcode} ) { $all_items_are_not_CPL = 0; last; } } - ok($all_items_are_not_CPL, "All items returned by SearchItems are not from CPL"); + ok( $all_items_are_not_CPL, "All items returned by SearchItems are not from CPL" ); # Search all items where biblio title (245$a) is like 'Silence in the %' $filter = { - field => 'marc:245$a', - query => 'Silence in the %', + field => 'marc:245$a', + query => 'Silence in the %', operator => 'like', }; - ($items, $total_results) = SearchItems($filter); - ok($total_results >= 2, "There is at least 2 items with a biblio title like 'Silence in the %'"); + ( $items, $total_results ) = SearchItems($filter); + ok( $total_results >= 2, "There is at least 2 items with a biblio title like 'Silence in the %'" ); # Search all items where biblio title is 'Silence in the library' # and homebranch is 'CPL' $filter = { conjunction => 'AND', - filters => [ + filters => [ { - field => 'marc:245$a', - query => 'Silence in the %', + field => 'marc:245$a', + query => 'Silence in the %', operator => 'like', }, { - field => 'homebranch', - query => $library1->{branchcode}, + field => 'homebranch', + query => $library1->{branchcode}, operator => '=', }, ], }; - ($items, $total_results) = SearchItems($filter); + ( $items, $total_results ) = SearchItems($filter); my $found = 0; foreach my $item (@$items) { - if ($item->{itemnumber} == $item1_itemnumber) { + if ( $item->{itemnumber} == $item1_itemnumber ) { $found = 1; last; } } - ok($found, "item1 found"); + ok( $found, "item1 found" ); my $frameworkcode = q||; - my ($itemfield) = GetMarcFromKohaField( 'items.itemnumber' ); + my ($itemfield) = GetMarcFromKohaField('items.itemnumber'); # Create item subfield 'z' without link - $dbh->do('DELETE FROM marc_subfield_structure WHERE tagfield=? AND tagsubfield="z" AND frameworkcode=?', undef, $itemfield, $frameworkcode); - $dbh->do('INSERT INTO marc_subfield_structure (tagfield, tagsubfield, frameworkcode) VALUES (?, "z", ?)', undef, $itemfield, $frameworkcode); + $dbh->do( + 'DELETE FROM marc_subfield_structure WHERE tagfield=? AND tagsubfield="z" AND frameworkcode=?', undef, + $itemfield, $frameworkcode + ); + $dbh->do( + 'INSERT INTO marc_subfield_structure (tagfield, tagsubfield, frameworkcode) VALUES (?, "z", ?)', undef, + $itemfield, $frameworkcode + ); # Clear cache my $cache = Koha::Caches->get_instance(); @@ -426,60 +462,68 @@ subtest 'SearchItems test' => sub { 'y' => $itemtype->{itemtype} ) ); - my (undef, undef, $item3_itemnumber) = AddItemFromMarc($item3_record, - $biblio->biblionumber); + my ( undef, undef, $item3_itemnumber ) = AddItemFromMarc( + $item3_record, + $biblio->biblionumber + ); # Search item where item subfield z is "foobar" $filter = { - field => 'marc:' . $itemfield . '$z', - query => 'foobar', + field => 'marc:' . $itemfield . '$z', + query => 'foobar', operator => 'like', }; - ($items, $total_results) = SearchItems($filter); - ok(scalar @$items == 1, 'found 1 item with $z = "foobar"'); + ( $items, $total_results ) = SearchItems($filter); + ok( scalar @$items == 1, 'found 1 item with $z = "foobar"' ); # Link $z to items.itemnotes (and make sure there is no other subfields # linked to it) - $dbh->do('DELETE FROM marc_subfield_structure WHERE kohafield="items.itemnotes" AND frameworkcode=?', undef, $itemfield, $frameworkcode); - $dbh->do('UPDATE marc_subfield_structure SET kohafield="items.itemnotes" WHERE tagfield=? AND tagsubfield="z" AND frameworkcode=?', undef, $itemfield, $frameworkcode); + $dbh->do( + 'DELETE FROM marc_subfield_structure WHERE kohafield="items.itemnotes" AND frameworkcode=?', undef, + $itemfield, $frameworkcode + ); + $dbh->do( + 'UPDATE marc_subfield_structure SET kohafield="items.itemnotes" WHERE tagfield=? AND tagsubfield="z" AND frameworkcode=?', + undef, $itemfield, $frameworkcode + ); # Clear cache $cache->clear_from_cache("MarcStructure-0-$frameworkcode"); $cache->clear_from_cache("MarcStructure-1-$frameworkcode"); $cache->clear_from_cache("MarcSubfieldStructure-$frameworkcode"); - ModItemFromMarc($item3_record, $biblio->biblionumber, $item3_itemnumber); + ModItemFromMarc( $item3_record, $biblio->biblionumber, $item3_itemnumber ); # Make sure the link is used my $item3 = Koha::Items->find($item3_itemnumber); - is($item3->itemnotes, 'foobar', 'itemnotes eq "foobar"'); + is( $item3->itemnotes, 'foobar', 'itemnotes eq "foobar"' ); # Do the same search again. # This time it will search in items.itemnotes - ($items, $total_results) = SearchItems($filter); - is(scalar(@$items), 1, 'found 1 item with itemnotes = "foobar"'); + ( $items, $total_results ) = SearchItems($filter); + is( scalar(@$items), 1, 'found 1 item with itemnotes = "foobar"' ); my ($cpl_items_after) = SearchItems( { field => 'homebranch', query => $library1->{branchcode} } ); - is( ( scalar( @$cpl_items_after ) - scalar ( @$cpl_items_before ) ), 1, 'SearchItems should return something' ); + is( ( scalar(@$cpl_items_after) - scalar(@$cpl_items_before) ), 1, 'SearchItems should return something' ); # Issues count = 0 $filter = { conjunction => 'AND', - filters => [ + filters => [ { - field => 'issues', - query => 0, + field => 'issues', + query => 0, operator => '=', }, { - field => 'homebranch', - query => $library1->{branchcode}, + field => 'homebranch', + query => $library1->{branchcode}, operator => '=', }, ], }; - ($items, $total_results) = SearchItems($filter); - is($total_results, 1, "Search items.issues issues = 0 returns result (items.issues defaults to 0)"); + ( $items, $total_results ) = SearchItems($filter); + is( $total_results, 1, "Search items.issues issues = 0 returns result (items.issues defaults to 0)" ); # Is null $filter = { @@ -497,47 +541,48 @@ subtest 'SearchItems test' => sub { }, ], }; - ($items, $total_results) = SearchItems($filter); - is($total_results, 0, 'found no item with new_status=0 without ifnull'); + ( $items, $total_results ) = SearchItems($filter); + is( $total_results, 0, 'found no item with new_status=0 without ifnull' ); $filter->{filters}[0]->{ifnull} = 0; - ($items, $total_results) = SearchItems($filter); - is($total_results, 1, 'found all items of library1 with new_status=0 with ifnull = 0'); + ( $items, $total_results ) = SearchItems($filter); + is( $total_results, 1, 'found all items of library1 with new_status=0 with ifnull = 0' ); - t::lib::Mocks::mock_userenv({ branchcode => $item1->homebranch }); - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); + t::lib::Mocks::mock_userenv( { branchcode => $item1->homebranch } ); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); AddIssue( $patron, $item1->barcode ); + # Search item where item is checked out $filter = { conjunction => 'AND', - filters => [ + filters => [ { - field => 'onloan', - query => 'not null', + field => 'onloan', + query => 'not null', operator => 'is', }, { - field => 'homebranch', - query => $item1->homebranch, + field => 'homebranch', + query => $item1->homebranch, operator => '=', }, ], }; - ($items, $total_results) = SearchItems($filter); - ok(scalar @$items == 1, 'found 1 checked out item'); + ( $items, $total_results ) = SearchItems($filter); + ok( scalar @$items == 1, 'found 1 checked out item' ); # When sorting by descending availability, checked out item should show first my $params = { - sortby => 'availability', + sortby => 'availability', sortorder => 'DESC', }; $filter = { - field => 'homebranch', - query => $item1->homebranch, + field => 'homebranch', + query => $item1->homebranch, operator => '=', }; - ($items, $total_results) = SearchItems($filter,$params); - is($items->[0]->{barcode}, $item1->barcode, 'Items sorted as expected by availability'); + ( $items, $total_results ) = SearchItems( $filter, $params ); + is( $items->[0]->{barcode}, $item1->barcode, 'Items sorted as expected by availability' ); subtest 'Sort items by callnumber' => sub { plan tests => 2; @@ -574,11 +619,13 @@ subtest 'SearchItems test' => sub { plan tests => 4; my $marc_record = MARC::Record->new; + # Prepare ISBN for biblio: $marc_record->append_fields( MARC::Field->new( '020', '', '', 'a' => '9780136019701' ) ); + # Prepare ISSN for biblio: $marc_record->append_fields( MARC::Field->new( '022', '', '', 'a' => '2434561X' ) ); - my ( $isbnissn_biblionumber ) = AddBiblio( $marc_record, '' ); + my ($isbnissn_biblionumber) = AddBiblio( $marc_record, '' ); my $isbnissn_biblio = Koha::Biblios->find($isbnissn_biblionumber); my $item = $builder->build_sample_item( @@ -589,32 +636,32 @@ subtest 'SearchItems test' => sub { my $item_itemnumber = $item->itemnumber; my $filter_isbn = { - field => 'isbn', - query => '978013-6019701', + field => 'isbn', + query => '978013-6019701', operator => 'like', }; - t::lib::Mocks::mock_preference('SearchWithISBNVariations', 0); - ($items, $total_results) = SearchItems($filter_isbn); - is($total_results, 0, "Search items finds ISBN, no variations"); + t::lib::Mocks::mock_preference( 'SearchWithISBNVariations', 0 ); + ( $items, $total_results ) = SearchItems($filter_isbn); + is( $total_results, 0, "Search items finds ISBN, no variations" ); - t::lib::Mocks::mock_preference('SearchWithISBNVariations', 1); - ($items, $total_results) = SearchItems($filter_isbn); - is($total_results, 1, "Search items finds ISBN with variations"); + t::lib::Mocks::mock_preference( 'SearchWithISBNVariations', 1 ); + ( $items, $total_results ) = SearchItems($filter_isbn); + is( $total_results, 1, "Search items finds ISBN with variations" ); my $filter_issn = { - field => 'issn', - query => '2434-561X', + field => 'issn', + query => '2434-561X', operator => 'like', }; - t::lib::Mocks::mock_preference('SearchWithISSNVariations', 0); - ($items, $total_results) = SearchItems($filter_issn); - is($total_results, 0, "Search items finds ISSN, no variations"); + t::lib::Mocks::mock_preference( 'SearchWithISSNVariations', 0 ); + ( $items, $total_results ) = SearchItems($filter_issn); + is( $total_results, 0, "Search items finds ISSN, no variations" ); - t::lib::Mocks::mock_preference('SearchWithISSNVariations', 1); - ($items, $total_results) = SearchItems($filter_issn); - is($total_results, 1, "Search items finds ISSN with variations"); + t::lib::Mocks::mock_preference( 'SearchWithISSNVariations', 1 ); + ( $items, $total_results ) = SearchItems($filter_issn); + is( $total_results, 1, "Search items finds ISSN with variations" ); }; $schema->storage->txn_rollback; @@ -626,20 +673,26 @@ subtest 'Koha::Item(s) tests' => sub { $schema->storage->txn_begin(); - my $builder = t::lib::TestBuilder->new; - my $library1 = $builder->build({ - source => 'Branch', - }); - my $library2 = $builder->build({ - source => 'Branch', - }); - my $itemtype = $builder->build({ - source => 'Itemtype', - }); + my $builder = t::lib::TestBuilder->new; + my $library1 = $builder->build( + { + source => 'Branch', + } + ); + my $library2 = $builder->build( + { + source => 'Branch', + } + ); + my $itemtype = $builder->build( + { + source => 'Itemtype', + } + ); # Create a biblio and item for testing - t::lib::Mocks::mock_preference('marcflavour', 'MARC21'); - my $biblio = $builder->build_sample_biblio(); + t::lib::Mocks::mock_preference( 'marcflavour', 'MARC21' ); + my $biblio = $builder->build_sample_biblio(); my $itemnumber = $builder->build_sample_item( { biblionumber => $biblio->biblionumber, @@ -650,21 +703,21 @@ subtest 'Koha::Item(s) tests' => sub { )->itemnumber; # Get item. - my $item = Koha::Items->find( $itemnumber ); + my $item = Koha::Items->find($itemnumber); is( ref($item), 'Koha::Item', "Got Koha::Item" ); my $homebranch = $item->home_branch(); - is( ref($homebranch), 'Koha::Library', "Got Koha::Library from home_branch method" ); - is( $homebranch->branchcode(), $library1->{branchcode}, "Home branch code matches homebranch" ); - is( ref( $item->home_library ), 'Koha::Library', 'home_library returns a Koha::Library object' ); + is( ref($homebranch), 'Koha::Library', "Got Koha::Library from home_branch method" ); + is( $homebranch->branchcode(), $library1->{branchcode}, "Home branch code matches homebranch" ); + is( ref( $item->home_library ), 'Koha::Library', 'home_library returns a Koha::Library object' ); my $holdingbranch = $item->holding_branch(); - is( ref($holdingbranch), 'Koha::Library', "Got Koha::Library from holding_branch method" ); - is( $holdingbranch->branchcode(), $library2->{branchcode}, "Home branch code matches holdingbranch" ); - is( ref( $item->holding_library ), 'Koha::Library', 'holding_library returns a Koha::Library object' ); + is( ref($holdingbranch), 'Koha::Library', "Got Koha::Library from holding_branch method" ); + is( $holdingbranch->branchcode(), $library2->{branchcode}, "Home branch code matches holdingbranch" ); + is( ref( $item->holding_library ), 'Koha::Library', 'holding_library returns a Koha::Library object' ); $biblio = $item->biblio(); - is( ref($item->biblio), 'Koha::Biblio', "Got Koha::Biblio from biblio method" ); + is( ref( $item->biblio ), 'Koha::Biblio', "Got Koha::Biblio from biblio method" ); is( $item->biblio->title(), $biblio->title, 'Title matches biblio title' ); $schema->storage->txn_rollback; @@ -674,37 +727,37 @@ subtest 'get_hostitemnumbers_of' => sub { plan tests => 3; $schema->storage->txn_begin; - t::lib::Mocks::mock_preference('marcflavour', 'MARC21'); + t::lib::Mocks::mock_preference( 'marcflavour', 'MARC21' ); my $builder = t::lib::TestBuilder->new; # Host item field without 0 or 9 my $bib1 = MARC::Record->new(); $bib1->append_fields( - MARC::Field->new('100', ' ', ' ', a => 'Moffat, Steven'), - MARC::Field->new('245', ' ', ' ', a => 'Silence in the library'), - MARC::Field->new('773', ' ', ' ', b => 'b without 0 or 9'), + MARC::Field->new( '100', ' ', ' ', a => 'Moffat, Steven' ), + MARC::Field->new( '245', ' ', ' ', a => 'Silence in the library' ), + MARC::Field->new( '773', ' ', ' ', b => 'b without 0 or 9' ), ); - my ($biblionumber1, $bibitemnum1) = AddBiblio($bib1, ''); - my @itemnumbers1 = C4::Items::get_hostitemnumbers_of( $biblionumber1 ); - is( scalar @itemnumbers1, 0, '773 without 0 or 9'); + my ( $biblionumber1, $bibitemnum1 ) = AddBiblio( $bib1, '' ); + my @itemnumbers1 = C4::Items::get_hostitemnumbers_of($biblionumber1); + is( scalar @itemnumbers1, 0, '773 without 0 or 9' ); # Correct host item field, analytical records on - t::lib::Mocks::mock_preference('EasyAnalyticalRecords', 1); + t::lib::Mocks::mock_preference( 'EasyAnalyticalRecords', 1 ); my $hostitem = $builder->build_sample_item(); - my $bib2 = MARC::Record->new(); + my $bib2 = MARC::Record->new(); $bib2->append_fields( - MARC::Field->new('100', ' ', ' ', a => 'Moffat, Steven'), - MARC::Field->new('245', ' ', ' ', a => 'Silence in the library'), - MARC::Field->new('773', ' ', ' ', 0 => $hostitem->biblionumber , 9 => $hostitem->itemnumber, b => 'b' ), + MARC::Field->new( '100', ' ', ' ', a => 'Moffat, Steven' ), + MARC::Field->new( '245', ' ', ' ', a => 'Silence in the library' ), + MARC::Field->new( '773', ' ', ' ', 0 => $hostitem->biblionumber, 9 => $hostitem->itemnumber, b => 'b' ), ); - my ($biblionumber2, $bibitemnum2) = AddBiblio($bib2, ''); - my @itemnumbers2 = C4::Items::get_hostitemnumbers_of( $biblionumber2 ); - is( scalar @itemnumbers2, 1, '773 with 0 and 9, EasyAnalyticalRecords on'); + my ( $biblionumber2, $bibitemnum2 ) = AddBiblio( $bib2, '' ); + my @itemnumbers2 = C4::Items::get_hostitemnumbers_of($biblionumber2); + is( scalar @itemnumbers2, 1, '773 with 0 and 9, EasyAnalyticalRecords on' ); # Correct host item field, analytical records off - t::lib::Mocks::mock_preference('EasyAnalyticalRecords', 0); - @itemnumbers2 = C4::Items::get_hostitemnumbers_of( $biblionumber2 ); - is( scalar @itemnumbers2, 0, '773 with 0 and 9, EasyAnalyticalRecords off'); + t::lib::Mocks::mock_preference( 'EasyAnalyticalRecords', 0 ); + @itemnumbers2 = C4::Items::get_hostitemnumbers_of($biblionumber2); + is( scalar @itemnumbers2, 0, '773 with 0 and 9, EasyAnalyticalRecords off' ); $schema->storage->txn_rollback; }; @@ -713,20 +766,24 @@ subtest 'Test logging for ModItem' => sub { plan tests => 3; - t::lib::Mocks::mock_preference('CataloguingLog', 1); + t::lib::Mocks::mock_preference( 'CataloguingLog', 1 ); $schema->storage->txn_begin; my $builder = t::lib::TestBuilder->new; - my $library = $builder->build({ - source => 'Branch', - }); - my $itemtype = $builder->build({ - source => 'Itemtype', - }); + my $library = $builder->build( + { + source => 'Branch', + } + ); + my $itemtype = $builder->build( + { + source => 'Itemtype', + } + ); # Create a biblio instance for testing - t::lib::Mocks::mock_preference('marcflavour', 'MARC21'); + t::lib::Mocks::mock_preference( 'marcflavour', 'MARC21' ); my $biblio = $builder->build_sample_biblio(); # Add an item. @@ -741,12 +798,12 @@ subtest 'Test logging for ModItem' => sub { # False means no logging $schema->resultset('ActionLog')->search()->delete(); - $item->location($location)->store({ log_action => 0 }); + $item->location($location)->store( { log_action => 0 } ); is( $schema->resultset('ActionLog')->count(), 0, 'False value does not trigger logging' ); # True means logging $schema->resultset('ActionLog')->search()->delete(); - $item->location('new location')->store({ log_action => 1 }); + $item->location('new location')->store( { log_action => 1 } ); is( $schema->resultset('ActionLog')->count(), 1, 'True value does trigger logging' ); # Undefined defaults to true @@ -763,14 +820,16 @@ subtest 'Check stockrotationitem relationship' => sub { $schema->storage->txn_begin(); my $builder = t::lib::TestBuilder->new; - my $item = $builder->build_sample_item; + my $item = $builder->build_sample_item; - $builder->build({ - source => 'Stockrotationitem', - value => { itemnumber_id => $item->itemnumber } - }); + $builder->build( + { + source => 'Stockrotationitem', + value => { itemnumber_id => $item->itemnumber } + } + ); - my $sritem = Koha::Items->find($item->itemnumber)->stockrotationitem; + my $sritem = Koha::Items->find( $item->itemnumber )->stockrotationitem; isa_ok( $sritem, 'Koha::StockRotationItem', "Relationship works and correctly creates Koha::Object." ); $schema->storage->txn_rollback; @@ -782,37 +841,41 @@ subtest 'Check add_to_rota method' => sub { $schema->storage->txn_begin(); my $builder = t::lib::TestBuilder->new; - my $item = $builder->build_sample_item; - my $rota = $builder->build({ source => 'Stockrotationrota' }); - my $srrota = Koha::StockRotationRotas->find($rota->{rota_id}); + my $item = $builder->build_sample_item; + my $rota = $builder->build( { source => 'Stockrotationrota' } ); + my $srrota = Koha::StockRotationRotas->find( $rota->{rota_id} ); - $builder->build({ - source => 'Stockrotationstage', - value => { rota_id => $rota->{rota_id} }, - }); + $builder->build( + { + source => 'Stockrotationstage', + value => { rota_id => $rota->{rota_id} }, + } + ); - my $sritem = Koha::Items->find($item->itemnumber); - $sritem->add_to_rota($rota->{rota_id}); + my $sritem = Koha::Items->find( $item->itemnumber ); + $sritem->add_to_rota( $rota->{rota_id} ); is( - Koha::StockRotationItems->find($item->itemnumber)->stage_id, + Koha::StockRotationItems->find( $item->itemnumber )->stage_id, $srrota->stockrotationstages->next->stage_id, "Adding to a rota a new sritem item being assigned to its first stage." ); - my $newrota = $builder->build({ source => 'Stockrotationrota' }); + my $newrota = $builder->build( { source => 'Stockrotationrota' } ); - my $srnewrota = Koha::StockRotationRotas->find($newrota->{rota_id}); + my $srnewrota = Koha::StockRotationRotas->find( $newrota->{rota_id} ); - $builder->build({ - source => 'Stockrotationstage', - value => { rota_id => $newrota->{rota_id} }, - }); + $builder->build( + { + source => 'Stockrotationstage', + value => { rota_id => $newrota->{rota_id} }, + } + ); - $sritem->add_to_rota($newrota->{rota_id}); + $sritem->add_to_rota( $newrota->{rota_id} ); is( - Koha::StockRotationItems->find($item->itemnumber)->stage_id, + Koha::StockRotationItems->find( $item->itemnumber )->stage_id, $srnewrota->stockrotationstages->next->stage_id, "Moving an item results in that sritem being assigned to the new first stage." ); @@ -825,10 +888,10 @@ subtest 'Split subfields in Item2Marc (Bug 21774)' => sub { $schema->storage->txn_begin; my $builder = t::lib::TestBuilder->new; - my $item = $builder->build_sample_item({ ccode => 'A|B' }); + my $item = $builder->build_sample_item( { ccode => 'A|B' } ); - Koha::MarcSubfieldStructures->search({ tagfield => '952', tagsubfield => '8' })->delete; # theoretical precaution - Koha::MarcSubfieldStructures->search({ kohafield => 'items.ccode' })->delete; + Koha::MarcSubfieldStructures->search( { tagfield => '952', tagsubfield => '8' } )->delete; # theoretical precaution + Koha::MarcSubfieldStructures->search( { kohafield => 'items.ccode' } )->delete; my $mapping = Koha::MarcSubfieldStructure->new( { frameworkcode => q{}, @@ -838,12 +901,12 @@ subtest 'Split subfields in Item2Marc (Bug 21774)' => sub { repeatable => 1 } )->store; - Koha::Caches->get_instance->clear_from_cache( "MarcSubfieldStructure-" ); + Koha::Caches->get_instance->clear_from_cache("MarcSubfieldStructure-"); # Start testing my $marc = C4::Items::Item2Marc( $item->unblessed, $item->biblionumber ); my @subs = $marc->subfield( $mapping->tagfield, $mapping->tagsubfield ); - is( @subs, 2, 'Expect two subfields' ); + is( @subs, 2, 'Expect two subfields' ); is( $subs[0], 'A', 'First subfield matches' ); is( $subs[1], 'B', 'Second subfield matches' ); @@ -854,11 +917,11 @@ subtest 'ModItemFromMarc' => sub { plan tests => 8; $schema->storage->txn_begin; - my $builder = t::lib::TestBuilder->new; - my ($itemfield) = GetMarcFromKohaField( 'items.itemnumber' ); - my $itemtype = $builder->build_object({ class => 'Koha::ItemTypes' }); - my $biblio = $builder->build_sample_biblio; - my ( $lost_tag, $lost_sf ) = GetMarcFromKohaField( 'items.itemlost' ); + my $builder = t::lib::TestBuilder->new; + my ($itemfield) = GetMarcFromKohaField('items.itemnumber'); + my $itemtype = $builder->build_object( { class => 'Koha::ItemTypes' } ); + my $biblio = $builder->build_sample_biblio; + my ( $lost_tag, $lost_sf ) = GetMarcFromKohaField('items.itemlost'); my $item_record = MARC::Record->new; $item_record->append_fields( MARC::Field->new( @@ -870,11 +933,13 @@ subtest 'ModItemFromMarc' => sub { $lost_sf => '1', ), ); - my (undef, undef, $itemnumber) = AddItemFromMarc($item_record, - $biblio->biblionumber); + my ( undef, undef, $itemnumber ) = AddItemFromMarc( + $item_record, + $biblio->biblionumber + ); my $item = Koha::Items->find($itemnumber); - is( $item->itemlost, 1, 'itemlost picked from the item marc'); + is( $item->itemlost, 1, 'itemlost picked from the item marc' ); $item->new_status("this is something")->store; @@ -886,8 +951,8 @@ subtest 'ModItemFromMarc' => sub { ) ); - my $updated_item = ModItemFromMarc($updated_item_record, $biblio->biblionumber, $itemnumber); - is( $updated_item->{itemlost}, 0, 'itemlost should have been reset to the default value in DB' ); + my $updated_item = ModItemFromMarc( $updated_item_record, $biblio->biblionumber, $itemnumber ); + is( $updated_item->{itemlost}, 0, 'itemlost should have been reset to the default value in DB' ); is( $updated_item->{new_status}, "this is something", "Non mapped field has not been reset" ); is( Koha::Items->find($itemnumber)->new_status, "this is something" ); @@ -895,14 +960,14 @@ subtest 'ModItemFromMarc' => sub { plan tests => 3; my $item = $builder->build_sample_item; - $item->set({ cn_source => 'ddc', itemcallnumber => 'xxx' })->store; + $item->set( { cn_source => 'ddc', itemcallnumber => 'xxx' } )->store; is( $item->cn_sort, 'XXX', 'init values set are expected' ); my $marc = C4::Items::Item2Marc( $item->get_from_storage->unblessed, $item->biblionumber ); ModItemFromMarc( $marc, $item->biblionumber, $item->itemnumber ); is( $item->get_from_storage->cn_sort, 'XXX', 'cn_sort has not been updated' ); - $marc = C4::Items::Item2Marc( { %{$item->unblessed}, itemcallnumber => 'yyy' }, $item->biblionumber ); + $marc = C4::Items::Item2Marc( { %{ $item->unblessed }, itemcallnumber => 'yyy' }, $item->biblionumber ); ModItemFromMarc( $marc, $item->biblionumber, $item->itemnumber ); is( $item->get_from_storage->cn_sort, 'YYY', 'cn_sort has been updated' ); }; @@ -911,16 +976,16 @@ subtest 'ModItemFromMarc' => sub { plan tests => 3; my $item = $builder->build_sample_item; - $item->set({ onloan => '2022-03-19' })->store; + $item->set( { onloan => '2022-03-19' } )->store; is( $item->onloan, '2022-03-19', 'init values set are expected' ); my $marc = C4::Items::Item2Marc( $item->get_from_storage->unblessed, $item->biblionumber ); - my ( $MARCfield, $MARCsubfield ) = GetMarcFromKohaField( 'items.onloan' ); + my ( $MARCfield, $MARCsubfield ) = GetMarcFromKohaField('items.onloan'); $marc->field($MARCfield)->delete_subfield( code => $MARCsubfield ); ModItemFromMarc( $marc, $item->biblionumber, $item->itemnumber ); is( $item->get_from_storage->onloan, '2022-03-19', 'onloan has not been updated if not passed' ); - $marc = C4::Items::Item2Marc( { %{$item->unblessed}, onloan => '2022-03-26' }, $item->biblionumber ); + $marc = C4::Items::Item2Marc( { %{ $item->unblessed }, onloan => '2022-03-26' }, $item->biblionumber ); ModItemFromMarc( $marc, $item->biblionumber, $item->itemnumber ); is( $item->get_from_storage->onloan, '2022-03-26', 'onloan has been updated when passed in' ); }; @@ -929,16 +994,19 @@ subtest 'ModItemFromMarc' => sub { plan tests => 3; my $item = $builder->build_sample_item; - $item->set({ dateaccessioned => '2022-03-19' })->store->discard_changes; + $item->set( { dateaccessioned => '2022-03-19' } )->store->discard_changes; is( $item->dateaccessioned, '2022-03-19', 'init values set are expected' ); my $marc = C4::Items::Item2Marc( $item->get_from_storage->unblessed, $item->biblionumber ); - my ( $MARCfield, $MARCsubfield ) = GetMarcFromKohaField( 'items.dateaccessioned' ); + my ( $MARCfield, $MARCsubfield ) = GetMarcFromKohaField('items.dateaccessioned'); $marc->field($MARCfield)->delete_subfield( code => $MARCsubfield ); ModItemFromMarc( $marc, $item->biblionumber, $item->itemnumber ); - is( $item->get_from_storage->dateaccessioned, '2022-03-19', 'dateaccessioned has not been updated if not passed' ); + is( + $item->get_from_storage->dateaccessioned, '2022-03-19', + 'dateaccessioned has not been updated if not passed' + ); - $marc = C4::Items::Item2Marc( { %{$item->unblessed}, dateaccessioned => '2022-03-26' }, $item->biblionumber ); + $marc = C4::Items::Item2Marc( { %{ $item->unblessed }, dateaccessioned => '2022-03-26' }, $item->biblionumber ); ModItemFromMarc( $marc, $item->biblionumber, $item->itemnumber ); is( $item->get_from_storage->dateaccessioned, '2022-03-26', 'dateaccessioned has been updated when passed in' ); }; @@ -956,18 +1024,18 @@ subtest 'ModItemFromMarc' => sub { Koha::MarcSubfieldStructures->search( { frameworkcode => q{}, - tagfield => '952', - tagsubfield => 'C', + tagfield => '952', + tagsubfield => 'C', } )->delete; - Koha::Caches->get_instance->clear_from_cache( "MarcSubfieldStructure-" ); + Koha::Caches->get_instance->clear_from_cache("MarcSubfieldStructure-"); my $item = $builder->build_sample_item; # By default, setting location to something new should set permanent location to the same thing # with the usual exceptions - $item->set({ location => 'A', permanent_location => 'A' })->store; - is( $item->location, 'A', 'initial location set as expected' ); + $item->set( { location => 'A', permanent_location => 'A' } )->store; + is( $item->location, 'A', 'initial location set as expected' ); is( $item->permanent_location, 'A', 'initial permanent location set as expected' ); $item->location('B'); @@ -975,7 +1043,7 @@ subtest 'ModItemFromMarc' => sub { ModItemFromMarc( $marc, $item->biblionumber, $item->itemnumber ); $item = $item->get_from_storage; - is( $item->location, 'B', 'new location set as expected' ); + is( $item->location, 'B', 'new location set as expected' ); is( $item->permanent_location, 'B', 'new permanent location set as expected' ); # Added a marc mapping for permanent location, allows it to be edited independently @@ -990,7 +1058,7 @@ subtest 'ModItemFromMarc' => sub { hidden => 0, } )->store; - Koha::Caches->get_instance->clear_from_cache( "MarcSubfieldStructure-" ); + Koha::Caches->get_instance->clear_from_cache("MarcSubfieldStructure-"); # Now if we change location, and also pass in a permanent location # the permanent_location will not be overwritten by location @@ -998,21 +1066,23 @@ subtest 'ModItemFromMarc' => sub { $marc = C4::Items::Item2Marc( $item->unblessed, $item->biblionumber ); ModItemFromMarc( $marc, $item->biblionumber, $item->itemnumber ); $item = $item->get_from_storage; - is( $item->location, 'C', 'next new location set as expected' ); + is( $item->location, 'C', 'next new location set as expected' ); is( $item->permanent_location, 'B', 'permanent location remains unchanged as expected' ); $item->permanent_location(undef)->more_subfields_xml(undef)->store; + # Clear values from the DB $item = $item->get_from_storage; # Update the location $item->location('D'); $marc = C4::Items::Item2Marc( $item->unblessed, $item->biblionumber ); + # Remove the permanent_location field from the form $marc->field('952')->delete_subfield("C"); ModItemFromMarc( $marc, $item->biblionumber, $item->itemnumber ); $item = $item->get_from_storage; - is( $item->location, 'D', 'next new location set as expected' ); + is( $item->location, 'D', 'next new location set as expected' ); is( $item->permanent_location, 'D', 'permanent location is updated if not previously set and no value passed' ); # Clear values from the DB @@ -1026,12 +1096,12 @@ subtest 'ModItemFromMarc' => sub { $marc->field('952')->add_subfields( "C", "" ); ModItemFromMarc( $marc, $item->biblionumber, $item->itemnumber ); $item = $item->get_from_storage; - is( $item->location, 'E', 'next new location set as expected' ); + is( $item->location, 'E', 'next new location set as expected' ); is( $item->permanent_location, undef, 'permanent location is not updated if previously set as blank string' ); }; $schema->storage->txn_rollback; - Koha::Caches->get_instance->clear_from_cache( "MarcSubfieldStructure-" ); + Koha::Caches->get_instance->clear_from_cache("MarcSubfieldStructure-"); }; subtest 'ModDateLastSeen' => sub { @@ -1039,23 +1109,27 @@ subtest 'ModDateLastSeen' => sub { $schema->storage->txn_begin; my $builder = t::lib::TestBuilder->new; - my $item = $builder->build_sample_item; - t::lib::Mocks::mock_preference('CataloguingLog', '1'); - my $logs_before = Koha::ActionLogs->search({ module => 'CATALOGUING', action => 'MODIFY', object => $item->itemnumber })->count; - ModDateLastSeen($item->itemnumber); - my $logs_after = Koha::ActionLogs->search({ module => 'CATALOGUING', action => 'MODIFY', object => $item->itemnumber })->count; - is( $logs_after, $logs_before, "ModDateLastSeen doesn't log if item not lost"); - $item->itemlost(1)->store({ log_action => 0 }); - ModDateLastSeen($item->itemnumber, 1); + my $item = $builder->build_sample_item; + t::lib::Mocks::mock_preference( 'CataloguingLog', '1' ); + my $logs_before = + Koha::ActionLogs->search( { module => 'CATALOGUING', action => 'MODIFY', object => $item->itemnumber } )->count; + ModDateLastSeen( $item->itemnumber ); + my $logs_after = + Koha::ActionLogs->search( { module => 'CATALOGUING', action => 'MODIFY', object => $item->itemnumber } )->count; + is( $logs_after, $logs_before, "ModDateLastSeen doesn't log if item not lost" ); + $item->itemlost(1)->store( { log_action => 0 } ); + ModDateLastSeen( $item->itemnumber, 1 ); $item->discard_changes; - $logs_after = Koha::ActionLogs->search({ module => 'CATALOGUING', action => 'MODIFY', object => $item->itemnumber })->count; - is( $item->itemlost, 1, "Item left lost when parameter is passed"); - is( $logs_after, $logs_before, "ModDateLastSeen doesn't log if item not lost"); - ModDateLastSeen($item->itemnumber); + $logs_after = + Koha::ActionLogs->search( { module => 'CATALOGUING', action => 'MODIFY', object => $item->itemnumber } )->count; + is( $item->itemlost, 1, "Item left lost when parameter is passed" ); + is( $logs_after, $logs_before, "ModDateLastSeen doesn't log if item not lost" ); + ModDateLastSeen( $item->itemnumber ); $item->discard_changes; - $logs_after = Koha::ActionLogs->search({ module => 'CATALOGUING', action => 'MODIFY', object => $item->itemnumber })->count; - is( $item->itemlost, 0, "Item no longer lost when no parameter is passed"); - is( $logs_after, $logs_before + 1, "ModDateLastSeen logs if item was lost and now found"); + $logs_after = + Koha::ActionLogs->search( { module => 'CATALOGUING', action => 'MODIFY', object => $item->itemnumber } )->count; + is( $item->itemlost, 0, "Item no longer lost when no parameter is passed" ); + is( $logs_after, $logs_before + 1, "ModDateLastSeen logs if item was lost and now found" ); }; subtest 'CartToShelf test' => sub { diff --git a/t/db_dependent/Items/AutomaticItemModificationByAge.t b/t/db_dependent/Items/AutomaticItemModificationByAge.t index 74532194b0..3603c45fb0 100755 --- a/t/db_dependent/Items/AutomaticItemModificationByAge.t +++ b/t/db_dependent/Items/AutomaticItemModificationByAge.t @@ -7,7 +7,7 @@ use MARC::Field; use DateTime; use DateTime::Duration; -use C4::Items qw( GetMarcItem ToggleNewStatus ); +use C4::Items qw( GetMarcItem ToggleNewStatus ); use C4::Biblio qw( AddBiblio GetMarcFromKohaField ); use C4::Context; use Koha::DateUtils qw( dt_from_string ); @@ -22,21 +22,25 @@ my $dbh = C4::Context->dbh; my $builder = t::lib::TestBuilder->new; # create two branches -my $library = $builder->build( { source => 'Branch' })->{branchcode}; -my $library2 = $builder->build( { source => 'Branch' })->{branchcode}; +my $library = $builder->build( { source => 'Branch' } )->{branchcode}; +my $library2 = $builder->build( { source => 'Branch' } )->{branchcode}; -my $frameworkcode = ''; # Use Default for Koha to MARC mappings -$dbh->do(q| +my $frameworkcode = ''; # Use Default for Koha to MARC mappings +$dbh->do( + q| DELETE FROM marc_subfield_structure WHERE ( kohafield = 'items.new_status' OR kohafield = 'items.stocknumber' ) AND frameworkcode = ? -|, undef, $frameworkcode); +|, undef, $frameworkcode +); my $new_tagfield = 'i'; -$dbh->do(qq| +$dbh->do( + qq| INSERT INTO marc_subfield_structure(tagfield, tagsubfield, kohafield, frameworkcode) VALUES ( 952, ?, 'items.new_status', ? ) -|, undef, $new_tagfield, $frameworkcode); +|, undef, $new_tagfield, $frameworkcode +); # Clear cache my $cache = Koha::Caches->get_instance(); @@ -51,7 +55,7 @@ $record->append_fields( MARC::Field->new( '260', ' ', ' ', c => '1999' ), MARC::Field->new( '942', ' ', ' ', c => 'ITEMTYPE_T' ), ); -my ($biblionumber, undef) = C4::Biblio::AddBiblio($record, $frameworkcode); +my ( $biblionumber, undef ) = C4::Biblio::AddBiblio( $record, $frameworkcode ); my $item = $builder->build_sample_item( { @@ -62,11 +66,11 @@ my $item = $builder->build_sample_item( } ); my $itemnumber = $item->itemnumber; -is ( $item->new_status, 'new_value', q|AddItem insert the 'new_status' field| ); +is( $item->new_status, 'new_value', q|AddItem insert the 'new_status' field| ); -my ( $tagfield, undef ) = GetMarcFromKohaField( 'items.itemnumber' ); +my ( $tagfield, undef ) = GetMarcFromKohaField('items.itemnumber'); my $marc_item = C4::Items::GetMarcItem( $biblionumber, $itemnumber ); -is( $marc_item->subfield($tagfield, $new_tagfield), 'new_value', q|Koha mapping is correct|); +is( $marc_item->subfield( $tagfield, $new_tagfield ), 'new_value', q|Koha mapping is correct| ); # Update the items.new_status field if items.ccode eq 'FIC' => should be updated my @rules = ( @@ -81,7 +85,7 @@ my @rules = ( { field => 'items.new_status', value => 'updated_value', - }, + }, ], age => '0', }, @@ -89,10 +93,13 @@ my @rules = ( C4::Items::ToggleNewStatus( { rules => \@rules } ); -my $modified_item = Koha::Items->find( $itemnumber ); -is( $modified_item->new_status, 'updated_value', q|ToggleNewStatus: The new_status value is updated|); +my $modified_item = Koha::Items->find($itemnumber); +is( $modified_item->new_status, 'updated_value', q|ToggleNewStatus: The new_status value is updated| ); $marc_item = C4::Items::GetMarcItem( $biblionumber, $itemnumber ); -is( $marc_item->subfield($tagfield, $new_tagfield), 'updated_value', q|ToggleNewStatus: The new_status value is updated| ); +is( + $marc_item->subfield( $tagfield, $new_tagfield ), 'updated_value', + q|ToggleNewStatus: The new_status value is updated| +); # Update the items.new_status field if items.ccode eq 'DONT_EXIST' => should not be updated @rules = ( @@ -107,7 +114,7 @@ is( $marc_item->subfield($tagfield, $new_tagfield), 'updated_value', q|ToggleNew { field => 'items.new_status', value => 'new_updated_value', - }, + }, ], age => '0', }, @@ -115,10 +122,13 @@ is( $marc_item->subfield($tagfield, $new_tagfield), 'updated_value', q|ToggleNew C4::Items::ToggleNewStatus( { rules => \@rules } ); -$modified_item = Koha::Items->find( $itemnumber ); -is( $modified_item->new_status, 'updated_value', q|ToggleNewStatus: The new_status value is not updated|); +$modified_item = Koha::Items->find($itemnumber); +is( $modified_item->new_status, 'updated_value', q|ToggleNewStatus: The new_status value is not updated| ); $marc_item = C4::Items::GetMarcItem( $biblionumber, $itemnumber ); -is( $marc_item->subfield($tagfield, $new_tagfield), 'updated_value', q|ToggleNewStatus: The new_status value is not updated| ); +is( + $marc_item->subfield( $tagfield, $new_tagfield ), 'updated_value', + q|ToggleNewStatus: The new_status value is not updated| +); # Play with age my $dt_today = dt_from_string; @@ -138,32 +148,38 @@ $modified_item->dateaccessioned($days5ago)->store; { field => 'items.new_status', value => 'new_updated_value', - }, + }, ], - age => '10', # Confirm not defining agefield, will default to using items.dateaccessioned + age => '10', # Confirm not defining agefield, will default to using items.dateaccessioned }, ); C4::Items::ToggleNewStatus( { rules => \@rules } ); -$modified_item = Koha::Items->find( $itemnumber ); -is( $modified_item->new_status, 'updated_value', q|ToggleNewStatus: Age = 10 : The new_status value is not updated|); +$modified_item = Koha::Items->find($itemnumber); +is( $modified_item->new_status, 'updated_value', q|ToggleNewStatus: Age = 10 : The new_status value is not updated| ); $rules[0]->{age} = 5; $rules[0]->{substitutions}[0]{value} = 'new_updated_value5'; C4::Items::ToggleNewStatus( { rules => \@rules } ); -$modified_item = Koha::Items->find( $itemnumber ); -is( $modified_item->new_status, 'new_updated_value5', q|ToggleNewStatus: Age = 5 : The new_status value is updated|); +$modified_item = Koha::Items->find($itemnumber); +is( $modified_item->new_status, 'new_updated_value5', q|ToggleNewStatus: Age = 5 : The new_status value is updated| ); $rules[0]->{age} = ''; $rules[0]->{substitutions}[0]{value} = 'new_updated_value_empty_string'; C4::Items::ToggleNewStatus( { rules => \@rules } ); -$modified_item = Koha::Items->find( $itemnumber ); -is( $modified_item->new_status, 'new_updated_value_empty_string', q|ToggleNewStatus: Age = '' : The new_status value is updated|); +$modified_item = Koha::Items->find($itemnumber); +is( + $modified_item->new_status, 'new_updated_value_empty_string', + q|ToggleNewStatus: Age = '' : The new_status value is updated| +); $rules[0]->{age} = undef; $rules[0]->{substitutions}[0]{value} = 'new_updated_value_undef'; C4::Items::ToggleNewStatus( { rules => \@rules } ); -$modified_item = Koha::Items->find( $itemnumber ); -is( $modified_item->new_status, 'new_updated_value_undef', q|ToggleNewStatus: Age = undef : The new_status value is updated|); +$modified_item = Koha::Items->find($itemnumber); +is( + $modified_item->new_status, 'new_updated_value_undef', + q|ToggleNewStatus: Age = undef : The new_status value is updated| +); # Field deletion @rules = ( @@ -178,7 +194,7 @@ is( $modified_item->new_status, 'new_updated_value_undef', q|ToggleNewStatus: Ag { field => 'items.new_status', value => '', - }, + }, ], age => '0', }, @@ -186,10 +202,13 @@ is( $modified_item->new_status, 'new_updated_value_undef', q|ToggleNewStatus: Ag C4::Items::ToggleNewStatus( { rules => \@rules } ); -$modified_item = Koha::Items->find( $itemnumber ); -is( $modified_item->new_status, '', q|ToggleNewStatus: The new_status value is empty|); +$modified_item = Koha::Items->find($itemnumber); +is( $modified_item->new_status, '', q|ToggleNewStatus: The new_status value is empty| ); $marc_item = C4::Items::GetMarcItem( $biblionumber, $itemnumber ); -is( $marc_item->subfield($tagfield, $new_tagfield), undef, q|ToggleNewStatus: The new_status field is removed from the item marc| ); +is( + $marc_item->subfield( $tagfield, $new_tagfield ), undef, + q|ToggleNewStatus: The new_status field is removed from the item marc| +); # conditions multiple @rules = ( @@ -208,7 +227,7 @@ is( $marc_item->subfield($tagfield, $new_tagfield), undef, q|ToggleNewStatus: Th { field => 'items.new_status', value => 'new_value', - }, + }, ], age => '0', }, @@ -216,8 +235,11 @@ is( $marc_item->subfield($tagfield, $new_tagfield), undef, q|ToggleNewStatus: Th C4::Items::ToggleNewStatus( { rules => \@rules } ); -$modified_item = Koha::Items->find( $itemnumber ); -is( $modified_item->new_status, 'new_value', q|ToggleNewStatus: conditions multiple: all match, the new_status value is updated|); +$modified_item = Koha::Items->find($itemnumber); +is( + $modified_item->new_status, 'new_value', + q|ToggleNewStatus: conditions multiple: all match, the new_status value is updated| +); @rules = ( { @@ -235,7 +257,7 @@ is( $modified_item->new_status, 'new_value', q|ToggleNewStatus: conditions multi { field => 'items.new_status', value => 'new_updated_value', - }, + }, ], age => '0', }, @@ -243,8 +265,11 @@ is( $modified_item->new_status, 'new_value', q|ToggleNewStatus: conditions multi C4::Items::ToggleNewStatus( { rules => \@rules } ); -$modified_item = Koha::Items->find( $itemnumber ); -is( $modified_item->new_status, 'new_value', q|ToggleNewStatus: conditions multiple: at least 1 condition does not match, the new_status value is not updated|); +$modified_item = Koha::Items->find($itemnumber); +is( + $modified_item->new_status, 'new_value', + q|ToggleNewStatus: conditions multiple: at least 1 condition does not match, the new_status value is not updated| +); @rules = ( { @@ -262,7 +287,7 @@ is( $modified_item->new_status, 'new_value', q|ToggleNewStatus: conditions multi { field => 'items.new_status', value => 'new_updated_value', - }, + }, ], age => '0', }, @@ -270,8 +295,11 @@ is( $modified_item->new_status, 'new_value', q|ToggleNewStatus: conditions multi C4::Items::ToggleNewStatus( { rules => \@rules } ); -$modified_item = Koha::Items->find( $itemnumber ); -is( $modified_item->new_status, 'new_updated_value', q|ToggleNewStatus: conditions multiple: the 2 conditions match, the new_status value is updated|); +$modified_item = Koha::Items->find($itemnumber); +is( + $modified_item->new_status, 'new_updated_value', + q|ToggleNewStatus: conditions multiple: the 2 conditions match, the new_status value is updated| +); @rules = ( { @@ -286,7 +314,7 @@ is( $modified_item->new_status, 'new_updated_value', q|ToggleNewStatus: conditio { field => 'items.new_status', value => 'another_new_updated_value', - }, + }, ], age => '0', }, @@ -294,11 +322,11 @@ is( $modified_item->new_status, 'new_updated_value', q|ToggleNewStatus: conditio C4::Items::ToggleNewStatus( { rules => \@rules } ); -$modified_item = Koha::Items->find( $itemnumber ); -is( $modified_item->new_status, 'another_new_updated_value', q|ToggleNewStatus: conditions on biblioitems|); +$modified_item = Koha::Items->find($itemnumber); +is( $modified_item->new_status, 'another_new_updated_value', q|ToggleNewStatus: conditions on biblioitems| ); # Play with the 'Age field' -my $days2ago = $dt_today->add_duration( DateTime::Duration->new( days => -10 ) ); +my $days2ago = $dt_today->add_duration( DateTime::Duration->new( days => -10 ) ); my $days20ago = $dt_today->add_duration( DateTime::Duration->new( days => -20 ) ); $modified_item->datelastseen($days2ago)->store; $modified_item->dateaccessioned($days20ago)->store; @@ -316,20 +344,26 @@ $modified_item->dateaccessioned($days20ago)->store; { field => 'items.new_status', value => 'agefield_new_value', - }, + }, ], - age => '5', + age => '5', agefield => 'items.datelastseen' # Confirm defining agefield => 'items.datelastseen' will use items.datelastseen }, ); C4::Items::ToggleNewStatus( { rules => \@rules } ); -$modified_item = Koha::Items->find( $itemnumber ); -is( $modified_item->new_status, 'agefield_new_value', q|ToggleNewStatus: Age = 5, agefield = 'items.datelastseen' : The new_status value is not updated|); +$modified_item = Koha::Items->find($itemnumber); +is( + $modified_item->new_status, 'agefield_new_value', + q|ToggleNewStatus: Age = 5, agefield = 'items.datelastseen' : The new_status value is not updated| +); $rules[0]->{age} = 2; C4::Items::ToggleNewStatus( { rules => \@rules } ); -$modified_item = Koha::Items->find( $itemnumber ); -is( $modified_item->new_status, 'agefield_new_value', q|ToggleNewStatus: Age = 2, agefield = 'items.datelastseen' : The new_status value is updated|); +$modified_item = Koha::Items->find($itemnumber); +is( + $modified_item->new_status, 'agefield_new_value', + q|ToggleNewStatus: Age = 2, agefield = 'items.datelastseen' : The new_status value is updated| +); # Condition on biblio column @rules = ( @@ -353,14 +387,17 @@ is( $modified_item->new_status, 'agefield_new_value', q|ToggleNewStatus: Age = 2 C4::Items::ToggleNewStatus( { rules => \@rules } ); -$modified_item = Koha::Items->find( $itemnumber ); -is( $modified_item->new_status, 'new_updated_value_biblio', q|ToggleNewStatus: conditions on biblio|); +$modified_item = Koha::Items->find($itemnumber); +is( $modified_item->new_status, 'new_updated_value_biblio', q|ToggleNewStatus: conditions on biblio| ); # Run twice -t::lib::Mocks::mock_preference('CataloguingLog', 1); +t::lib::Mocks::mock_preference( 'CataloguingLog', 1 ); my $actions_nb = $schema->resultset('ActionLog')->count(); C4::Items::ToggleNewStatus( { rules => \@rules } ); -is( $schema->resultset('ActionLog')->count(), $actions_nb, q|ToggleNewStatus: no substitution does not generate action logs|); +is( + $schema->resultset('ActionLog')->count(), $actions_nb, + q|ToggleNewStatus: no substitution does not generate action logs| +); # Cleanup $cache = Koha::Caches->get_instance(); diff --git a/t/db_dependent/Items/GetItemsForInventory.t b/t/db_dependent/Items/GetItemsForInventory.t index b5c2b97bd2..d93bbdd46b 100755 --- a/t/db_dependent/Items/GetItemsForInventory.t +++ b/t/db_dependent/Items/GetItemsForInventory.t @@ -24,8 +24,8 @@ use t::lib::TestBuilder; use List::MoreUtils qw( any none ); -use C4::Biblio qw(AddBiblio); -use C4::Reserves qw( AddReserve ); +use C4::Biblio qw(AddBiblio); +use C4::Reserves qw( AddReserve ); use C4::ClassSource qw( GetClassSort ); use Koha::AuthorisedValues; use Koha::Biblios; @@ -34,12 +34,12 @@ use MARC::Record; BEGIN { use_ok('C4::Context'); - use_ok('C4::Items', qw( GetItemsForInventory )); + use_ok( 'C4::Items', qw( GetItemsForInventory ) ); use_ok('C4::Biblio'); use_ok('C4::Koha'); } -can_ok('C4::Items','GetItemsForInventory'); +can_ok( 'C4::Items', 'GetItemsForInventory' ); my $schema = Koha::Database->new->schema; my $builder = t::lib::TestBuilder->new; @@ -50,27 +50,24 @@ subtest 'Skip items with waiting holds' => sub { $schema->storage->txn_begin; - my $library = $builder->build_object( { class => 'Koha::Libraries' } ); - my $itemtype - = $builder->build_object( { class => 'Koha::ItemTypes', value => { rentalcharge => 0 } } ); - my $patron_1 = $builder->build_object( - { class => 'Koha::Patrons', value => { branchcode => $library->id } } ); - my $patron_2 = $builder->build_object( - { class => 'Koha::Patrons', value => { branchcode => $library->id } } ); - + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); + my $itemtype = $builder->build_object( { class => 'Koha::ItemTypes', value => { rentalcharge => 0 } } ); + my $patron_1 = $builder->build_object( { class => 'Koha::Patrons', value => { branchcode => $library->id } } ); + my $patron_2 = $builder->build_object( { class => 'Koha::Patrons', value => { branchcode => $library->id } } ); my $title_1 = 'Title 1, '; my $title_2 = 'Title 2, bizzarre one so doesn\'t already exist'; - my $biblio_1 = $builder->build_sample_biblio({ itemtype => $itemtype->itemtype, title => $title_1 }); - my $biblio_2 = $builder->build_sample_biblio({ itemtype => $itemtype->itemtype, title => $title_2 }); + my $biblio_1 = $builder->build_sample_biblio( { itemtype => $itemtype->itemtype, title => $title_1 } ); + my $biblio_2 = $builder->build_sample_biblio( { itemtype => $itemtype->itemtype, title => $title_2 } ); my ( $items_1, $first_items_count ) = GetItemsForInventory(); is( scalar @{$items_1}, $first_items_count, 'Results and count match' ); # Add two items, so we don't depend on existing data my $item_1 = $builder->build_object( - { class => 'Koha::Items', + { + class => 'Koha::Items', value => { biblionumber => $biblio_1->biblionumber, biblioitemnumber => $biblio_1->biblioitem->biblioitemnumber, @@ -83,7 +80,8 @@ subtest 'Skip items with waiting holds' => sub { ); my $item_2 = $builder->build_object( - { class => 'Koha::Items', + { + class => 'Koha::Items', value => { biblionumber => $biblio_2->biblionumber, biblioitemnumber => $biblio_2->biblioitem->biblioitemnumber, @@ -99,9 +97,9 @@ subtest 'Skip items with waiting holds' => sub { is( scalar @{$items_2}, $second_items_count, 'Results and count match' ); is( $first_items_count + 2, $second_items_count, 'Two items added, count makes sense' ); - my $real_itemtype_count = Koha::Items->search({ itype => $itemtype->itemtype })->count; - my $itype_str = "'" . $itemtype->itemtype . "'"; # manipulate string for db query - my ( $items_3, $itemtype_count ) = GetItemsForInventory({ itemtypes => [ $itype_str ] }); + my $real_itemtype_count = Koha::Items->search( { itype => $itemtype->itemtype } )->count; + my $itype_str = "'" . $itemtype->itemtype . "'"; # manipulate string for db query + my ( $items_3, $itemtype_count ) = GetItemsForInventory( { itemtypes => [$itype_str] } ); is( $itemtype_count, $real_itemtype_count, 'Itemtype filter gets correct number of inventory items' ); # Add 2 waiting holds @@ -136,11 +134,15 @@ subtest 'Skip items with waiting holds' => sub { my ( $new_items, $new_items_count ) = GetItemsForInventory( { ignore_waiting_holds => 1 } ); is( $new_items_count, $first_items_count + 1, 'Item on hold skipped, count makes sense' ); - ok( (any { $_->{title} eq $title_2 } @{$new_items}), - 'Item on hold skipped, the other one we added is present' ); - ok( (none { $_->{title} eq $title_1 } @{$new_items}), - 'Item on hold skipped, no one matches' ); - is( scalar(@$new_items), $new_items_count, 'total and number of items is the same'); + ok( + ( any { $_->{title} eq $title_2 } @{$new_items} ), + 'Item on hold skipped, the other one we added is present' + ); + ok( + ( none { $_->{title} eq $title_1 } @{$new_items} ), + 'Item on hold skipped, no one matches' + ); + is( scalar(@$new_items), $new_items_count, 'total and number of items is the same' ); $schema->storage->txn_rollback; }; @@ -151,38 +153,48 @@ subtest 'Use cn_sort rather than callnumber to determine correct location' => su my $builder = t::lib::TestBuilder->new; - my $class_rule = $builder->build({ - source => 'ClassSortRule', - value => { sort_routine => "LCC" } - }); - my $class_source = $builder->build({ - source => 'ClassSource', - value => { - class_sort_rule => $class_rule->{class_sort_rule}, + my $class_rule = $builder->build( + { + source => 'ClassSortRule', + value => { sort_routine => "LCC" } } - }); + ); + my $class_source = $builder->build( + { + source => 'ClassSource', + value => { + class_sort_rule => $class_rule->{class_sort_rule}, + } + } + ); #Find if we have any items in our test range before we start - my( undef, $pre_item_count) = GetItemsForInventory({ - maxlocation => 'GT100', - minlocation => 'GT90', - class_source => $class_source->{cn_source}, - }); + my ( undef, $pre_item_count ) = GetItemsForInventory( + { + maxlocation => 'GT100', + minlocation => 'GT90', + class_source => $class_source->{cn_source}, + } + ); - my $item_1 = $builder->build({ # Cannot call build_sample_item or cn_sort will be replaced by Koha::Item->store + my $item_1 = $builder->build( + { # Cannot call build_sample_item or cn_sort will be replaced by Koha::Item->store source => 'Item', value => { itemcallnumber => 'GT95', - cn_sort => GetClassSort($class_source->{cn_source},undef,'GT95'), + cn_sort => GetClassSort( $class_source->{cn_source}, undef, 'GT95' ), } - }); + } + ); - my( undef, $item_count) = GetItemsForInventory({ - maxlocation => 'GT100', - minlocation => 'GT90', - class_source => $class_source->{cn_source}, - }); - is($item_count,$pre_item_count + 1,"We should return GT95 as between GT90 and GT100"); + my ( undef, $item_count ) = GetItemsForInventory( + { + maxlocation => 'GT100', + minlocation => 'GT90', + class_source => $class_source->{cn_source}, + } + ); + is( $item_count, $pre_item_count + 1, "We should return GT95 as between GT90 and GT100" ); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/Koha.t b/t/db_dependent/Koha.t index f802b5d972..f010d00b13 100755 --- a/t/db_dependent/Koha.t +++ b/t/db_dependent/Koha.t @@ -24,29 +24,31 @@ BEGIN { ); } -my $schema = Koha::Database->new->schema; +my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; my $builder = t::lib::TestBuilder->new; -my $dbh = C4::Context->dbh; +my $dbh = C4::Context->dbh; -our $itype_1 = $builder->build({ source => 'Itemtype' }); +our $itype_1 = $builder->build( { source => 'Itemtype' } ); subtest 'Authorized Values Tests' => sub { plan tests => 4; my $data = { - category => 'CATEGORY', - authorised_value => 'AUTHORISED_VALUE', - lib => 'LIB', - lib_opac => 'LIBOPAC', - imageurl => 'IMAGEURL' + category => 'CATEGORY', + authorised_value => 'AUTHORISED_VALUE', + lib => 'LIB', + lib_opac => 'LIBOPAC', + imageurl => 'IMAGEURL' }; - my $avc = Koha::AuthorisedValueCategories->find($data->{category}); - Koha::AuthorisedValueCategory->new({ category_name => $data->{category} })->store unless $avc; -# Insert an entry into authorised_value table + my $avc = Koha::AuthorisedValueCategories->find( $data->{category} ); + Koha::AuthorisedValueCategory->new( { category_name => $data->{category} } )->store unless $avc; + + # Insert an entry into authorised_value table my $insert_success = Koha::AuthorisedValue->new( - { category => $data->{category}, + { + category => $data->{category}, authorised_value => $data->{authorised_value}, lib => $data->{lib}, lib_opac => $data->{lib_opac}, @@ -55,17 +57,21 @@ subtest 'Authorized Values Tests' => sub { )->store; ok( $insert_success, "Insert data in database" ); - -# Clean up - if($insert_success){ - my $query = "DELETE FROM authorised_values WHERE category=? AND authorised_value=? AND lib=? AND lib_opac=? AND imageurl=?;"; + # Clean up + if ($insert_success) { + my $query = + "DELETE FROM authorised_values WHERE category=? AND authorised_value=? AND lib=? AND lib_opac=? AND imageurl=?;"; my $sth = $dbh->prepare($query); - $sth->execute($data->{category}, $data->{authorised_value}, $data->{lib}, $data->{lib_opac}, $data->{imageurl}); + $sth->execute( + $data->{category}, $data->{authorised_value}, $data->{lib}, $data->{lib_opac}, + $data->{imageurl} + ); } - Koha::AuthorisedValueCategory->new({ category_name => 'BUG10656' })->store; + Koha::AuthorisedValueCategory->new( { category_name => 'BUG10656' } )->store; Koha::AuthorisedValue->new( - { category => 'BUG10656', + { + category => 'BUG10656', authorised_value => 'ZZZ', lib => 'Z_STAFF', lib_opac => 'A_PUBLIC', @@ -73,7 +79,8 @@ subtest 'Authorized Values Tests' => sub { } )->store; Koha::AuthorisedValue->new( - { category => 'BUG10656', + { + category => 'BUG10656', authorised_value => 'AAA', lib => 'A_STAFF', lib_opac => 'Z_PUBLIC', @@ -84,7 +91,8 @@ subtest 'Authorized Values Tests' => sub { # the next one sets lib_opac to NULL; in that case, the staff # display value is meant to be used. Koha::AuthorisedValue->new( - { category => 'BUG10656', + { + category => 'BUG10656', authorised_value => 'DDD', lib => 'D_STAFF', lib_opac => undef, @@ -97,59 +105,59 @@ subtest 'Authorized Values Tests' => sub { $authvals, [ { - id => ignore(), - category => 'BUG10656', + id => ignore(), + category => 'BUG10656', authorised_value => 'AAA', - lib => 'A_STAFF', - lib_opac => 'Z_PUBLIC', - imageurl => '', + lib => 'A_STAFF', + lib_opac => 'Z_PUBLIC', + imageurl => '', }, { - id => ignore(), - category => 'BUG10656', + id => ignore(), + category => 'BUG10656', authorised_value => 'DDD', - lib => 'D_STAFF', - lib_opac => undef, - imageurl => '', + lib => 'D_STAFF', + lib_opac => undef, + imageurl => '', }, { - id => ignore(), - category => 'BUG10656', + id => ignore(), + category => 'BUG10656', authorised_value => 'ZZZ', - lib => 'Z_STAFF', - lib_opac => 'A_PUBLIC', - imageurl => '', + lib => 'Z_STAFF', + lib_opac => 'A_PUBLIC', + imageurl => '', }, ], 'list of authorised values in staff mode sorted by staff label (bug 10656)' ); - $authvals = GetAuthorisedValues('BUG10656', 1); + $authvals = GetAuthorisedValues( 'BUG10656', 1 ); cmp_deeply( $authvals, [ { - id => ignore(), - category => 'BUG10656', + id => ignore(), + category => 'BUG10656', authorised_value => 'ZZZ', - lib => 'A_PUBLIC', - lib_opac => 'A_PUBLIC', - imageurl => '', + lib => 'A_PUBLIC', + lib_opac => 'A_PUBLIC', + imageurl => '', }, { - id => ignore(), - category => 'BUG10656', + id => ignore(), + category => 'BUG10656', authorised_value => 'DDD', - lib => 'D_STAFF', - lib_opac => undef, - imageurl => '', + lib => 'D_STAFF', + lib_opac => undef, + imageurl => '', }, { - id => ignore(), - category => 'BUG10656', + id => ignore(), + category => 'BUG10656', authorised_value => 'AAA', - lib => 'Z_PUBLIC', - lib_opac => 'Z_PUBLIC', - imageurl => '', + lib => 'Z_PUBLIC', + lib_opac => 'Z_PUBLIC', + imageurl => '', }, ], 'list of authorised values in OPAC mode sorted by OPAC label (bug 10656)' @@ -338,61 +346,68 @@ subtest 'GetItemTypesCategorized test' => sub { plan tests => 9; my $avc = Koha::AuthorisedValueCategories->find('ITEMTYPECAT'); - Koha::AuthorisedValueCategory->new({ category_name => 'ITEMTYPECAT' })->store unless $avc; + Koha::AuthorisedValueCategory->new( { category_name => 'ITEMTYPECAT' } )->store unless $avc; my $insertGroup = Koha::AuthorisedValue->new( - { category => 'ITEMTYPECAT', + { + category => 'ITEMTYPECAT', authorised_value => 'Qwertyware', lib => 'Keyboard software', lib_opac => 'Computer stuff', } )->store; - ok($insertGroup, "Create group Qwertyware"); + ok( $insertGroup, "Create group Qwertyware" ); - my $query = "INSERT into itemtypes (itemtype, description, searchcategory, hideinopac) values (?,?,?,?)"; + my $query = "INSERT into itemtypes (itemtype, description, searchcategory, hideinopac) values (?,?,?,?)"; my $insertSth = C4::Context->dbh->prepare($query); - $insertSth->execute('BKghjklo1', 'One type of book', '', 0); - $insertSth->execute('BKghjklo2', 'Another type of book', 'Qwertyware', 0); - $insertSth->execute('BKghjklo3', 'Yet another type of book', 'Qwertyware', 0); + $insertSth->execute( 'BKghjklo1', 'One type of book', '', 0 ); + $insertSth->execute( 'BKghjklo2', 'Another type of book', 'Qwertyware', 0 ); + $insertSth->execute( 'BKghjklo3', 'Yet another type of book', 'Qwertyware', 0 ); # Azertyware should not exist. - my @itemtypes = Koha::ItemTypes->search({ searchcategory => 'Azertyware' })->as_list; - is( @itemtypes, 0, 'Search item types by searchcategory: Invalid category returns nothing'); + my @itemtypes = Koha::ItemTypes->search( { searchcategory => 'Azertyware' } )->as_list; + is( @itemtypes, 0, 'Search item types by searchcategory: Invalid category returns nothing' ); - @itemtypes = Koha::ItemTypes->search({ searchcategory => 'Qwertyware' })->as_list; - my @got = map { $_->itemtype } @itemtypes; + @itemtypes = Koha::ItemTypes->search( { searchcategory => 'Qwertyware' } )->as_list; + my @got = map { $_->itemtype } @itemtypes; my @expected = ( 'BKghjklo2', 'BKghjklo3' ); - is_deeply(\@got,\@expected,'Search item types by searchcategory: valid category returns itemtypes'); + is_deeply( \@got, \@expected, 'Search item types by searchcategory: valid category returns itemtypes' ); # add more data since GetItemTypesCategorized's search is more subtle $insertGroup = Koha::AuthorisedValue->new( - { category => 'ITEMTYPECAT', + { + category => 'ITEMTYPECAT', authorised_value => 'Veryheavybook', lib => 'Weighty literature', } )->store; - $insertSth->execute('BKghjklo4', 'Another hidden book', 'Veryheavybook', 1); + $insertSth->execute( 'BKghjklo4', 'Another hidden book', 'Veryheavybook', 1 ); my $hrCat = GetItemTypesCategorized(); - ok(exists $hrCat->{Qwertyware}, 'GetItemTypesCategorized: fully visible category exists'); - ok($hrCat->{Veryheavybook} && - $hrCat->{Veryheavybook}->{hideinopac}==1, 'GetItemTypesCategorized: non-visible category hidden' ); + ok( exists $hrCat->{Qwertyware}, 'GetItemTypesCategorized: fully visible category exists' ); + ok( + $hrCat->{Veryheavybook} && $hrCat->{Veryheavybook}->{hideinopac} == 1, + 'GetItemTypesCategorized: non-visible category hidden' + ); - is( $hrCat->{Veryheavybook}->{description}, 'Weighty literature', 'A category with only lib description passes through'); - is( $hrCat->{Qwertyware}->{description}, 'Computer stuff', 'A category with lib_opac description uses that'); + is( + $hrCat->{Veryheavybook}->{description}, 'Weighty literature', + 'A category with only lib description passes through' + ); + is( $hrCat->{Qwertyware}->{description}, 'Computer stuff', 'A category with lib_opac description uses that' ); - $insertSth->execute('BKghjklo5', 'An hidden book', 'Qwertyware', 1); + $insertSth->execute( 'BKghjklo5', 'An hidden book', 'Qwertyware', 1 ); $hrCat = GetItemTypesCategorized(); - ok(exists $hrCat->{Qwertyware}, 'GetItemTypesCategorized: partially visible category exists'); + ok( exists $hrCat->{Qwertyware}, 'GetItemTypesCategorized: partially visible category exists' ); - my @only = ( 'BKghjklo1', 'BKghjklo2', 'BKghjklo3', 'BKghjklo4', 'BKghjklo5', 'Qwertyware', 'Veryheavybook' ); + my @only = ( 'BKghjklo1', 'BKghjklo2', 'BKghjklo3', 'BKghjklo4', 'BKghjklo5', 'Qwertyware', 'Veryheavybook' ); my @results = (); foreach my $key (@only) { push @results, $key if exists $hrCat->{$key}; } @expected = ( 'BKghjklo1', 'Qwertyware', 'Veryheavybook' ); - is_deeply(\@results,\@expected, 'GetItemTypesCategorized: grouped and ungrouped items returned as expected.'); + is_deeply( \@results, \@expected, 'GetItemTypesCategorized: grouped and ungrouped items returned as expected.' ); }; $schema->storage->txn_rollback; diff --git a/t/db_dependent/Koha/Account.t b/t/db_dependent/Koha/Account.t index 39a84a7eb2..37e9ebf9fc 100755 --- a/t/db_dependent/Koha/Account.t +++ b/t/db_dependent/Koha/Account.t @@ -34,7 +34,7 @@ use Koha::DateUtils qw( dt_from_string ); use t::lib::Mocks; use t::lib::TestBuilder; -my $schema = Koha::Database->new->schema; +my $schema = Koha::Database->new->schema; $schema->storage->dbh->{PrintError} = 0; my $builder = t::lib::TestBuilder->new; C4::Context->interface('commandline'); @@ -47,7 +47,7 @@ subtest 'new' => sub { throws_ok { Koha::Account->new(); } qr/No patron id passed in!/, 'Croaked on bad call to new'; - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $account = Koha::Account->new( { patron_id => $patron->borrowernumber } ); is( defined $account, 1, "Account is defined" ); @@ -60,21 +60,24 @@ subtest 'outstanding_debits() tests' => sub { $schema->storage->txn_begin; - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $account = $patron->account; my @generated_lines; - push @generated_lines, $account->add_debit({ amount => 1, interface => 'commandline', type => 'OVERDUE' }); - push @generated_lines, $account->add_debit({ amount => 2, interface => 'commandline', type => 'OVERDUE' }); - push @generated_lines, $account->add_debit({ amount => 3, interface => 'commandline', type => 'OVERDUE' }); - push @generated_lines, $account->add_debit({ amount => 4, interface => 'commandline', type => 'OVERDUE' }); + push @generated_lines, $account->add_debit( { amount => 1, interface => 'commandline', type => 'OVERDUE' } ); + push @generated_lines, $account->add_debit( { amount => 2, interface => 'commandline', type => 'OVERDUE' } ); + push @generated_lines, $account->add_debit( { amount => 3, interface => 'commandline', type => 'OVERDUE' } ); + push @generated_lines, $account->add_debit( { amount => 4, interface => 'commandline', type => 'OVERDUE' } ); - my $lines = $account->outstanding_debits(); + my $lines = $account->outstanding_debits(); - is( ref($lines), 'Koha::Account::Lines', 'Called in scalar context, outstanding_debits returns a Koha::Account::Lines object' ); + is( + ref($lines), 'Koha::Account::Lines', + 'Called in scalar context, outstanding_debits returns a Koha::Account::Lines object' + ); is( $lines->total_outstanding, 10, 'Outstandig debits total is correctly calculated' ); - my $patron_2 = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron_2 = $builder->build_object( { class => 'Koha::Patrons' } ); Koha::Account::Line->new( { borrowernumber => $patron_2->id, @@ -103,24 +106,24 @@ subtest 'outstanding_debits() tests' => sub { )->store; $lines = $patron_2->account->outstanding_debits(); is( $lines->total_outstanding, 3, "Total if some outstanding debits and some credits is only debits" ); - is( $lines->count, 1, "With 1 outstanding debits, we get back a Lines object with 1 lines" ); + is( $lines->count, 1, "With 1 outstanding debits, we get back a Lines object with 1 lines" ); my $the_line = Koha::Account::Lines->find( $just_one->id ); - is_deeply( $the_line->unblessed, $lines->next->unblessed, "We get back the one correct line"); + is_deeply( $the_line->unblessed, $lines->next->unblessed, "We get back the one correct line" ); - my $patron_3 = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron_3 = $builder->build_object( { class => 'Koha::Patrons' } ); my $account_3 = $patron_3->account; $account_3->add_credit( { amount => 2, interface => 'commandline' } ); $account_3->add_credit( { amount => 20, interface => 'commandline' } ); $account_3->add_credit( { amount => 200, interface => 'commandline' } ); $lines = $account_3->outstanding_debits(); is( $lines->total_outstanding, 0, "Total if no outstanding debits total is 0" ); - is( $lines->count, 0, "With 0 outstanding debits, we get back a Lines object with 0 lines" ); + is( $lines->count, 0, "With 0 outstanding debits, we get back a Lines object with 0 lines" ); - my $patron_4 = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron_4 = $builder->build_object( { class => 'Koha::Patrons' } ); my $account_4 = $patron_4->account; $lines = $account_4->outstanding_debits(); is( $lines->total_outstanding, 0, "Total if no outstanding debits is 0" ); - is( $lines->count, 0, "With no outstanding debits, we get back a Lines object with 0 lines" ); + is( $lines->count, 0, "With no outstanding debits, we get back a Lines object with 0 lines" ); # create a pathological credit with amountoutstanding > 0 (BZ 14591) Koha::Account::Line->new( @@ -144,25 +147,28 @@ subtest 'outstanding_credits() tests' => sub { $schema->storage->txn_begin; - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $account = $patron->account; my @generated_lines; - push @generated_lines, $account->add_credit({ amount => 1, interface => 'commandline' }); - push @generated_lines, $account->add_credit({ amount => 2, interface => 'commandline' }); - push @generated_lines, $account->add_credit({ amount => 3, interface => 'commandline' }); - push @generated_lines, $account->add_credit({ amount => 4, interface => 'commandline' }); + push @generated_lines, $account->add_credit( { amount => 1, interface => 'commandline' } ); + push @generated_lines, $account->add_credit( { amount => 2, interface => 'commandline' } ); + push @generated_lines, $account->add_credit( { amount => 3, interface => 'commandline' } ); + push @generated_lines, $account->add_credit( { amount => 4, interface => 'commandline' } ); - my $lines = $account->outstanding_credits(); + my $lines = $account->outstanding_credits(); - is( ref($lines), 'Koha::Account::Lines', 'Called in scalar context, outstanding_credits returns a Koha::Account::Lines object' ); + is( + ref($lines), 'Koha::Account::Lines', + 'Called in scalar context, outstanding_credits returns a Koha::Account::Lines object' + ); is( $lines->total_outstanding, -10, 'Outstandig credits total is correctly calculated' ); - my $patron_2 = $builder->build_object({ class => 'Koha::Patrons' }); - $account = $patron_2->account; - $lines = $account->outstanding_credits(); + my $patron_2 = $builder->build_object( { class => 'Koha::Patrons' } ); + $account = $patron_2->account; + $lines = $account->outstanding_credits(); is( $lines->total_outstanding, 0, "Total if no outstanding credits is 0" ); - is( $lines->count, 0, "With no outstanding credits, we get back a Lines object with 0 lines" ); + is( $lines->count, 0, "With no outstanding credits, we get back a Lines object with 0 lines" ); # create a pathological debit with amountoutstanding < 0 (BZ 14591) Koha::Account::Line->new( @@ -188,7 +194,7 @@ subtest 'add_credit() tests' => sub { # delete logs and statistics my $action_logs = $schema->resultset('ActionLog')->search()->count; - my $statistics = $schema->resultset('Statistic')->search()->count; + my $statistics = $schema->resultset('Statistic')->search()->count; my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $account = Koha::Account->new( { patron_id => $patron->borrowernumber } ); @@ -224,17 +230,18 @@ subtest 'add_credit() tests' => sub { } ); - is( $account->balance, -25, 'Patron has a balance of -25' ); + is( $account->balance, -25, 'Patron has a balance of -25' ); is( $schema->resultset('ActionLog')->count(), $action_logs + 0, 'No log was added' ); - is( $schema->resultset('Statistic')->count(), $statistics + 1, 'Action added to statistics' ); - is( $line_1->credit_type_code, 'PAYMENT', 'Account type is correctly set' ); + is( $schema->resultset('Statistic')->count(), $statistics + 1, 'Action added to statistics' ); + is( $line_1->credit_type_code, 'PAYMENT', 'Account type is correctly set' ); ok( $line_1->amount < 0, 'Credit amount is stored as a negative' ); # Enable logs t::lib::Mocks::mock_preference( 'FinesLog', 1 ); my $line_2 = $account->add_credit( - { amount => 37, + { + amount => 37, description => 'Payment of 37', library_id => $patron->branchcode, note => 'not really important', @@ -243,21 +250,21 @@ subtest 'add_credit() tests' => sub { } ); - is( $account->balance, -62, 'Patron has a balance of -25' ); + is( $account->balance, -62, 'Patron has a balance of -25' ); is( $schema->resultset('ActionLog')->count(), $action_logs + 1, 'Log was added' ); - is( $schema->resultset('Statistic')->count(), $statistics + 2, 'Action added to statistics' ); - is( $line_2->credit_type_code, 'PAYMENT', 'Account type is correctly set' ); + is( $schema->resultset('Statistic')->count(), $statistics + 2, 'Action added to statistics' ); + is( $line_2->credit_type_code, 'PAYMENT', 'Account type is correctly set' ); ok( $line_1->amount < 0, 'Credit amount is stored as a negative' ); # offsets have the credit_id set to accountlines_id, and debit_id is undef - my $offset_1 = Koha::Account::Offsets->search({ credit_id => $line_1->id })->next; - my $offset_2 = Koha::Account::Offsets->search({ credit_id => $line_2->id })->next; + my $offset_1 = Koha::Account::Offsets->search( { credit_id => $line_1->id } )->next; + my $offset_2 = Koha::Account::Offsets->search( { credit_id => $line_2->id } )->next; is( $offset_1->credit_id, $line_1->id, 'No debit_id is set for credits' ); - is( $offset_1->debit_id, undef, 'No debit_id is set for credits' ); + is( $offset_1->debit_id, undef, 'No debit_id is set for credits' ); ok( $offset_1->amount > 0, 'Credit creation offset is a positive' ); is( $offset_2->credit_id, $line_2->id, 'No debit_id is set for credits' ); - is( $offset_2->debit_id, undef, 'No debit_id is set for credits' ); + is( $offset_2->debit_id, undef, 'No debit_id is set for credits' ); ok( $offset_2->amount > 0, 'Credit creation offset is a positive' ); my $line_3 = $account->add_credit( @@ -272,7 +279,10 @@ subtest 'add_credit() tests' => sub { ); is( $schema->resultset('ActionLog')->count(), $action_logs + 2, 'Log was added' ); - is( $schema->resultset('Statistic')->count(), $statistics + 2, 'No action added to statistics, because of credit type' ); + is( + $schema->resultset('Statistic')->count(), $statistics + 2, + 'No action added to statistics, because of credit type' + ); # Enable cash registers t::lib::Mocks::mock_preference( 'UseCashRegisters', 1 ); @@ -289,7 +299,7 @@ subtest 'add_credit() tests' => sub { ); } 'Koha::Exceptions::Account::RegisterRequired', - 'Exception thrown for UseCashRegisters:1 + payment_type:CASH + cash_register:undef'; + 'Exception thrown for UseCashRegisters:1 + payment_type:CASH + cash_register:undef'; # Disable cash registers t::lib::Mocks::mock_preference( 'UseCashRegisters', 0 ); @@ -333,24 +343,25 @@ subtest 'add_debit() tests' => sub { my $action_logs = $schema->resultset('ActionLog')->search()->count; my $statistics = $schema->resultset('Statistic')->search()->count; - my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); - my $account = - Koha::Account->new( { patron_id => $patron->borrowernumber } ); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + my $account = Koha::Account->new( { patron_id => $patron->borrowernumber } ); is( $account->balance, 0, 'Patron has no balance' ); throws_ok { - $account->add_debit( - { - amount => -5, - description => 'amount validation failure', - library_id => $patron->branchcode, - note => 'this should fail anyway', - type => 'RENT', - user_id => $patron->id, - interface => 'commandline' - } - ); } 'Koha::Exceptions::Account::AmountNotPositive', 'Expected validation exception thrown (amount)'; + $account->add_debit( + { + amount => -5, + description => 'amount validation failure', + library_id => $patron->branchcode, + note => 'this should fail anyway', + type => 'RENT', + user_id => $patron->id, + interface => 'commandline' + } + ); + } + 'Koha::Exceptions::Account::AmountNotPositive', 'Expected validation exception thrown (amount)'; throws_ok { local *STDERR; @@ -369,19 +380,21 @@ subtest 'add_debit() tests' => sub { close STDERR; } 'Koha::Exceptions::Account::UnrecognisedType', - 'Expected validation exception thrown (type)'; + 'Expected validation exception thrown (type)'; throws_ok { - $account->add_debit( - { - amount => 25, - description => 'Rental charge of 25', - library_id => $patron->branchcode, - note => 'not really important', - type => 'RENT', - user_id => $patron->id - } - ); } 'Koha::Exceptions::MissingParameter', 'Exception thrown if interface parameter missing'; + $account->add_debit( + { + amount => 25, + description => 'Rental charge of 25', + library_id => $patron->branchcode, + note => 'not really important', + type => 'RENT', + user_id => $patron->id + } + ); + } + 'Koha::Exceptions::MissingParameter', 'Exception thrown if interface parameter missing'; # Disable logs t::lib::Mocks::mock_preference( 'FinesLog', 0 ); @@ -413,7 +426,7 @@ subtest 'add_debit() tests' => sub { # Enable logs t::lib::Mocks::mock_preference( 'FinesLog', 1 ); - my $line_2 = $account->add_debit( + my $line_2 = $account->add_debit( { amount => 37, description => 'Rental charge of 37', @@ -438,10 +451,8 @@ subtest 'add_debit() tests' => sub { ); # offsets have the debit_id set to accountlines_id, and credit_id is undef - my $offset_1 = - Koha::Account::Offsets->search( { debit_id => $line_1->id } )->next; - my $offset_2 = - Koha::Account::Offsets->search( { debit_id => $line_2->id } )->next; + my $offset_1 = Koha::Account::Offsets->search( { debit_id => $line_1->id } )->next; + my $offset_2 = Koha::Account::Offsets->search( { debit_id => $line_2->id } )->next; is( $offset_1->debit_id, $line_1->id, 'debit_id is set for debit 1' ); is( $offset_1->credit_id, undef, 'credit_id is not set for debit 1' ); @@ -457,27 +468,27 @@ subtest 'lines() tests' => sub { $schema->storage->txn_begin; - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $account = $patron->account; # Add Credits - $account->add_credit({ amount => 1, interface => 'commandline' }); - $account->add_credit({ amount => 2, interface => 'commandline' }); - $account->add_credit({ amount => 3, interface => 'commandline' }); - $account->add_credit({ amount => 4, interface => 'commandline' }); + $account->add_credit( { amount => 1, interface => 'commandline' } ); + $account->add_credit( { amount => 2, interface => 'commandline' } ); + $account->add_credit( { amount => 3, interface => 'commandline' } ); + $account->add_credit( { amount => 4, interface => 'commandline' } ); # Add Debits - $account->add_debit({ amount => 1, interface => 'commandline', type => 'OVERDUE' }); - $account->add_debit({ amount => 2, interface => 'commandline', type => 'OVERDUE' }); - $account->add_debit({ amount => 3, interface => 'commandline', type => 'OVERDUE' }); - $account->add_debit({ amount => 4, interface => 'commandline', type => 'OVERDUE' }); + $account->add_debit( { amount => 1, interface => 'commandline', type => 'OVERDUE' } ); + $account->add_debit( { amount => 2, interface => 'commandline', type => 'OVERDUE' } ); + $account->add_debit( { amount => 3, interface => 'commandline', type => 'OVERDUE' } ); + $account->add_debit( { amount => 4, interface => 'commandline', type => 'OVERDUE' } ); # Paid Off $account->add_credit( { amount => 1, interface => 'commandline' } ) ->apply( { debits => [ $account->outstanding_debits->as_list ] } ); my $lines = $account->lines; - is( $lines->_resultset->count, 9, "All accountlines (debits, credits and paid off) were fetched"); + is( $lines->_resultset->count, 9, "All accountlines (debits, credits and paid off) were fetched" ); $schema->storage->txn_rollback; }; @@ -492,21 +503,21 @@ subtest 'reconcile_balance' => sub { $schema->storage->txn_begin; - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $account = $patron->account; # Add Credits - $account->add_credit({ amount => 1, interface => 'commandline' }); - $account->add_credit({ amount => 2, interface => 'commandline' }); - $account->add_credit({ amount => 3, interface => 'commandline' }); - $account->add_credit({ amount => 4, interface => 'commandline' }); - $account->add_credit({ amount => 5, interface => 'commandline' }); + $account->add_credit( { amount => 1, interface => 'commandline' } ); + $account->add_credit( { amount => 2, interface => 'commandline' } ); + $account->add_credit( { amount => 3, interface => 'commandline' } ); + $account->add_credit( { amount => 4, interface => 'commandline' } ); + $account->add_credit( { amount => 5, interface => 'commandline' } ); # Add Debits - $account->add_debit({ amount => 1, interface => 'commandline', type => 'OVERDUE' }); - $account->add_debit({ amount => 2, interface => 'commandline', type => 'OVERDUE' }); - $account->add_debit({ amount => 3, interface => 'commandline', type => 'OVERDUE' }); - $account->add_debit({ amount => 4, interface => 'commandline', type => 'OVERDUE' }); + $account->add_debit( { amount => 1, interface => 'commandline', type => 'OVERDUE' } ); + $account->add_debit( { amount => 2, interface => 'commandline', type => 'OVERDUE' } ); + $account->add_debit( { amount => 3, interface => 'commandline', type => 'OVERDUE' } ); + $account->add_debit( { amount => 4, interface => 'commandline', type => 'OVERDUE' } ); # Paid Off Koha::Account::Line->new( @@ -528,14 +539,14 @@ subtest 'reconcile_balance' => sub { } )->store; - is( $account->balance(), -5, "Account balance is -5" ); - is( $account->outstanding_debits->total_outstanding, 10, 'Outstanding debits sum 10' ); + is( $account->balance(), -5, "Account balance is -5" ); + is( $account->outstanding_debits->total_outstanding, 10, 'Outstanding debits sum 10' ); is( $account->outstanding_credits->total_outstanding, -15, 'Outstanding credits sum -15' ); $account->reconcile_balance(); - is( $account->balance(), -5, "Account balance is -5" ); - is( $account->outstanding_debits->total_outstanding, 0, 'No outstanding debits' ); + is( $account->balance(), -5, "Account balance is -5" ); + is( $account->outstanding_debits->total_outstanding, 0, 'No outstanding debits' ); is( $account->outstanding_credits->total_outstanding, -5, 'Outstanding credits sum -5' ); $schema->storage->txn_rollback; @@ -547,20 +558,20 @@ subtest 'reconcile_balance' => sub { $schema->storage->txn_begin; - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $account = $patron->account; # Add Credits - $account->add_credit({ amount => 1, interface => 'commandline' }); - $account->add_credit({ amount => 2, interface => 'commandline' }); - $account->add_credit({ amount => 3, interface => 'commandline' }); - $account->add_credit({ amount => 4, interface => 'commandline' }); + $account->add_credit( { amount => 1, interface => 'commandline' } ); + $account->add_credit( { amount => 2, interface => 'commandline' } ); + $account->add_credit( { amount => 3, interface => 'commandline' } ); + $account->add_credit( { amount => 4, interface => 'commandline' } ); # Add Debits - $account->add_debit({ amount => 1, interface => 'commandline', type => 'OVERDUE' }); - $account->add_debit({ amount => 2, interface => 'commandline', type => 'OVERDUE' }); - $account->add_debit({ amount => 3, interface => 'commandline', type => 'OVERDUE' }); - $account->add_debit({ amount => 4, interface => 'commandline', type => 'OVERDUE' }); + $account->add_debit( { amount => 1, interface => 'commandline', type => 'OVERDUE' } ); + $account->add_debit( { amount => 2, interface => 'commandline', type => 'OVERDUE' } ); + $account->add_debit( { amount => 3, interface => 'commandline', type => 'OVERDUE' } ); + $account->add_debit( { amount => 4, interface => 'commandline', type => 'OVERDUE' } ); # Paid Off Koha::Account::Line->new( @@ -582,14 +593,14 @@ subtest 'reconcile_balance' => sub { } )->store; - is( $account->balance(), 0, "Account balance is 0" ); - is( $account->outstanding_debits->total_outstanding, 10, 'Outstanding debits sum 10' ); + is( $account->balance(), 0, "Account balance is 0" ); + is( $account->outstanding_debits->total_outstanding, 10, 'Outstanding debits sum 10' ); is( $account->outstanding_credits->total_outstanding, -10, 'Outstanding credits sum -10' ); $account->reconcile_balance(); - is( $account->balance(), 0, "Account balance is 0" ); - is( $account->outstanding_debits->total_outstanding, 0, 'No outstanding debits' ); + is( $account->balance(), 0, "Account balance is 0" ); + is( $account->outstanding_debits->total_outstanding, 0, 'No outstanding debits' ); is( $account->outstanding_credits->total_outstanding, 0, 'Outstanding credits sum 0' ); $schema->storage->txn_rollback; @@ -601,21 +612,21 @@ subtest 'reconcile_balance' => sub { $schema->storage->txn_begin; - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $account = $patron->account; # Add Credits - $account->add_credit({ amount => 1, interface => 'commandline' }); - $account->add_credit({ amount => 2, interface => 'commandline' }); - $account->add_credit({ amount => 3, interface => 'commandline' }); - $account->add_credit({ amount => 4, interface => 'commandline' }); + $account->add_credit( { amount => 1, interface => 'commandline' } ); + $account->add_credit( { amount => 2, interface => 'commandline' } ); + $account->add_credit( { amount => 3, interface => 'commandline' } ); + $account->add_credit( { amount => 4, interface => 'commandline' } ); # Add Debits - $account->add_debit({ amount => 1, interface => 'commandline', type => 'OVERDUE' }); - $account->add_debit({ amount => 2, interface => 'commandline', type => 'OVERDUE' }); - $account->add_debit({ amount => 3, interface => 'commandline', type => 'OVERDUE' }); - $account->add_debit({ amount => 4, interface => 'commandline', type => 'OVERDUE' }); - $account->add_debit({ amount => 5, interface => 'commandline', type => 'OVERDUE' }); + $account->add_debit( { amount => 1, interface => 'commandline', type => 'OVERDUE' } ); + $account->add_debit( { amount => 2, interface => 'commandline', type => 'OVERDUE' } ); + $account->add_debit( { amount => 3, interface => 'commandline', type => 'OVERDUE' } ); + $account->add_debit( { amount => 4, interface => 'commandline', type => 'OVERDUE' } ); + $account->add_debit( { amount => 5, interface => 'commandline', type => 'OVERDUE' } ); # Paid Off Koha::Account::Line->new( @@ -637,14 +648,14 @@ subtest 'reconcile_balance' => sub { } )->store; - is( $account->balance(), 5, "Account balance is 5" ); - is( $account->outstanding_debits->total_outstanding, 15, 'Outstanding debits sum 15' ); + is( $account->balance(), 5, "Account balance is 5" ); + is( $account->outstanding_debits->total_outstanding, 15, 'Outstanding debits sum 15' ); is( $account->outstanding_credits->total_outstanding, -10, 'Outstanding credits sum -10' ); $account->reconcile_balance(); - is( $account->balance(), 5, "Account balance is 5" ); - is( $account->outstanding_debits->total_outstanding, 5, 'Outstanding debits sum 5' ); + is( $account->balance(), 5, "Account balance is 5" ); + is( $account->outstanding_debits->total_outstanding, 5, 'Outstanding debits sum 5' ); is( $account->outstanding_credits->total_outstanding, 0, 'Outstanding credits sum 0' ); $schema->storage->txn_rollback; @@ -656,26 +667,26 @@ subtest 'reconcile_balance' => sub { $schema->storage->txn_begin; - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $account = $patron->account; # Add Credits - $account->add_credit({ amount => 1, interface => 'commandline' }); - $account->add_credit({ amount => 3, interface => 'commandline' }); + $account->add_credit( { amount => 1, interface => 'commandline' } ); + $account->add_credit( { amount => 3, interface => 'commandline' } ); # Add Debits - my $debit_1 = $account->add_debit({ amount => 1, interface => 'commandline', type => 'OVERDUE' }); - my $debit_2 = $account->add_debit({ amount => 2, interface => 'commandline', type => 'OVERDUE' }); - my $debit_3 = $account->add_debit({ amount => 3, interface => 'commandline', type => 'OVERDUE' }); + my $debit_1 = $account->add_debit( { amount => 1, interface => 'commandline', type => 'OVERDUE' } ); + my $debit_2 = $account->add_debit( { amount => 2, interface => 'commandline', type => 'OVERDUE' } ); + my $debit_3 = $account->add_debit( { amount => 3, interface => 'commandline', type => 'OVERDUE' } ); - is( $account->balance(), 2, "Account balance is 2" ); - is( $account->outstanding_debits->total_outstanding, 6, 'Outstanding debits sum 6' ); + is( $account->balance(), 2, "Account balance is 2" ); + is( $account->outstanding_debits->total_outstanding, 6, 'Outstanding debits sum 6' ); is( $account->outstanding_credits->total_outstanding, -4, 'Outstanding credits sum -4' ); $account->reconcile_balance(); - is( $account->balance(), 2, "Account balance is 2" ); - is( $account->outstanding_debits->total_outstanding, 2, 'Outstanding debits sum 2' ); + is( $account->balance(), 2, "Account balance is 2" ); + is( $account->outstanding_debits->total_outstanding, 2, 'Outstanding debits sum 2' ); is( $account->outstanding_credits->total_outstanding, 0, 'Outstanding credits sum 0' ); $debit_1->discard_changes; @@ -698,22 +709,21 @@ subtest 'pay() tests' => sub { # Disable renewing upon fine payment t::lib::Mocks::mock_preference( 'RenewAccruingItemWhenPaid', 0 ); - - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); - my $library = $builder->build_object({ class => 'Koha::Libraries' }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); my $account = $patron->account; t::lib::Mocks::mock_preference( 'RequirePaymentType', 1 ); throws_ok { $account->pay( { - amount => 5, - interface => 'intranet', + amount => 5, + interface => 'intranet', } ); } 'Koha::Exceptions::Account::PaymentTypeRequired', - 'Exception thrown for RequirePaymentType:1 + payment_type:undef'; + 'Exception thrown for RequirePaymentType:1 + payment_type:undef'; throws_ok { $account->pay( @@ -725,7 +735,7 @@ subtest 'pay() tests' => sub { ); } 'Koha::Exceptions::Account::InvalidPaymentType', - 'Exception thrown for InvalidPaymentType:1 + payment_type:FOOBAR'; + 'Exception thrown for InvalidPaymentType:1 + payment_type:FOOBAR'; my $writeoff_id = $account->pay( { @@ -741,15 +751,16 @@ subtest 'pay() tests' => sub { my $context = Test::MockModule->new('C4::Context'); $context->mock( 'userenv', { branch => $library->id } ); - my $credit_1_id = $account->pay({ amount => 200 })->{payment_id}; - my $credit_1 = Koha::Account::Lines->find( $credit_1_id ); + my $credit_1_id = $account->pay( { amount => 200 } )->{payment_id}; + my $credit_1 = Koha::Account::Lines->find($credit_1_id); is( $credit_1->branchcode, undef, 'No branchcode is set if library_id was not passed' ); - my $credit_2_id = $account->pay({ amount => 150, library_id => $library->id })->{payment_id}; - my $credit_2 = Koha::Account::Lines->find( $credit_2_id ); + my $credit_2_id = $account->pay( { amount => 150, library_id => $library->id } )->{payment_id}; + my $credit_2 = Koha::Account::Lines->find($credit_2_id); is( $credit_2->branchcode, $library->id, 'branchcode set because library_id was passed' ); + # Enable cash registers t::lib::Mocks::mock_preference( 'UseCashRegisters', 1 ); throws_ok { @@ -762,7 +773,7 @@ subtest 'pay() tests' => sub { ); } 'Koha::Exceptions::Account::RegisterRequired', - 'Exception thrown for UseCashRegisters:1 + payment_type:CASH + cash_register:undef'; + 'Exception thrown for UseCashRegisters:1 + payment_type:CASH + cash_register:undef'; # Disable cash registers t::lib::Mocks::mock_preference( 'UseCashRegisters', 0 ); @@ -771,14 +782,14 @@ subtest 'pay() tests' => sub { $context->mock( 'userenv', undef ); my $result = $account->pay( { - amount => 20, + amount => 20, payment_type => 'CASH', - interface => 'intranet' + interface => 'intranet' } ); - ok($result, "Koha::Account->pay functions without a userenv"); - my $payment = Koha::Account::Lines->find({accountlines_id => $result->{payment_id}}); - is($payment->manager_id, undef, "manager_id left undefined when no userenv found"); + ok( $result, "Koha::Account->pay functions without a userenv" ); + my $payment = Koha::Account::Lines->find( { accountlines_id => $result->{payment_id} } ); + is( $payment->manager_id, undef, "manager_id left undefined when no userenv found" ); subtest 'UseEmailReceipts tests' => sub { @@ -789,32 +800,40 @@ subtest 'pay() tests' => sub { my %params; my $mocked_letters = Test::MockModule->new('C4::Letters'); + # we want to test the params - $mocked_letters->mock( 'GetPreparedLetter', sub { - %params = @_; - return 1; - }); + $mocked_letters->mock( + 'GetPreparedLetter', + sub { + %params = @_; + return 1; + } + ); + # we don't care about EnqueueLetter for now - $mocked_letters->mock( 'EnqueueLetter', sub { - return 1; - }); + $mocked_letters->mock( + 'EnqueueLetter', + sub { + return 1; + } + ); $schema->storage->txn_begin; - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $account = $patron->account; my $debit_1 = $account->add_debit( { amount => 5, interface => 'commandline', type => 'OVERDUE' } ); - my $debit_2 = $account->add_debit( { amount => 10, interface => 'commandline', type => 'OVERDUE' } ); + my $debit_2 = $account->add_debit( { amount => 10, interface => 'commandline', type => 'OVERDUE' } ); - $account->pay({ amount => 6, lines => [ $debit_1, $debit_2 ] }); - my @offsets = @{$params{substitute}{offsets}}; + $account->pay( { amount => 6, lines => [ $debit_1, $debit_2 ] } ); + my @offsets = @{ $params{substitute}{offsets} }; - is( scalar @offsets, 2, 'Two offsets related to payment' ); - is( ref($offsets[0]), 'Koha::Account::Offset', 'Type is correct' ); - is( ref($offsets[1]), 'Koha::Account::Offset', 'Type is correct' ); - is( $offsets[0]->type, 'APPLY', 'Only APPLY offsets are passed to the notice' ); - is( $offsets[1]->type, 'APPLY', 'Only APPLY offsets are passed to the notice' ); + is( scalar @offsets, 2, 'Two offsets related to payment' ); + is( ref( $offsets[0] ), 'Koha::Account::Offset', 'Type is correct' ); + is( ref( $offsets[1] ), 'Koha::Account::Offset', 'Type is correct' ); + is( $offsets[0]->type, 'APPLY', 'Only APPLY offsets are passed to the notice' ); + is( $offsets[1]->type, 'APPLY', 'Only APPLY offsets are passed to the notice' ); $schema->storage->txn_rollback; }; @@ -836,8 +855,7 @@ subtest 'pay() handles lost items when paying a specific lost fee' => sub { $context->mock( 'userenv', { branch => $library->id } ); my $biblio = $builder->build_sample_biblio(); - my $item = - $builder->build_sample_item( { biblionumber => $biblio->biblionumber } ); + my $item = $builder->build_sample_item( { biblionumber => $biblio->biblionumber } ); my $checkout = Koha::Checkout->new( { @@ -853,13 +871,13 @@ subtest 'pay() handles lost items when paying a specific lost fee' => sub { my $accountline = Koha::Account::Line->new( { - issue_id => $checkout->id, - borrowernumber => $patron->id, - itemnumber => $item->id, - date => \'NOW()', - debit_type_code => 'LOST', - interface => 'cli', - amount => '1', + issue_id => $checkout->id, + borrowernumber => $patron->id, + itemnumber => $item->id, + date => \'NOW()', + debit_type_code => 'LOST', + interface => 'cli', + amount => '1', amountoutstanding => '1', } )->store(); @@ -873,7 +891,7 @@ subtest 'pay() handles lost items when paying a specific lost fee' => sub { ); $accountline = Koha::Account::Lines->find( $accountline->id ); - is( $accountline->amountoutstanding+0, .5, 'Account line was paid down by half' ); + is( $accountline->amountoutstanding + 0, .5, 'Account line was paid down by half' ); $checkout = Koha::Checkouts->find( $checkout->id ); ok( $checkout, 'Item still checked out to patron' ); @@ -887,7 +905,7 @@ subtest 'pay() handles lost items when paying a specific lost fee' => sub { ); $accountline = Koha::Account::Lines->find( $accountline->id ); - is( $accountline->amountoutstanding+0, 0, 'Account line was paid down by half' ); + is( $accountline->amountoutstanding + 0, 0, 'Account line was paid down by half' ); $checkout = Koha::Checkouts->find( $checkout->id ); ok( !$checkout, 'Item was removed from patron account' ); @@ -955,8 +973,7 @@ subtest 'pay() handles lost items when paying by amount ( not specifying the los $context->mock( 'userenv', { branch => $library->id } ); my $biblio = $builder->build_sample_biblio(); - my $item = - $builder->build_sample_item( { biblionumber => $biblio->biblionumber } ); + my $item = $builder->build_sample_item( { biblionumber => $biblio->biblionumber } ); my $checkout = Koha::Checkout->new( { @@ -972,13 +989,13 @@ subtest 'pay() handles lost items when paying by amount ( not specifying the los my $accountline = Koha::Account::Line->new( { - issue_id => $checkout->id, - borrowernumber => $patron->id, - itemnumber => $item->id, - date => \'NOW()', - debit_type_code => 'LOST', - interface => 'cli', - amount => '1', + issue_id => $checkout->id, + borrowernumber => $patron->id, + itemnumber => $item->id, + date => \'NOW()', + debit_type_code => 'LOST', + interface => 'cli', + amount => '1', amountoutstanding => '1', } )->store(); @@ -991,7 +1008,7 @@ subtest 'pay() handles lost items when paying by amount ( not specifying the los ); $accountline = Koha::Account::Lines->find( $accountline->id ); - is( $accountline->amountoutstanding+0, .5, 'Account line was paid down by half' ); + is( $accountline->amountoutstanding + 0, .5, 'Account line was paid down by half' ); $checkout = Koha::Checkouts->find( $checkout->id ); ok( $checkout, 'Item still checked out to patron' ); @@ -1004,7 +1021,7 @@ subtest 'pay() handles lost items when paying by amount ( not specifying the los ); $accountline = Koha::Account::Lines->find( $accountline->id ); - is( $accountline->amountoutstanding+0, 0, 'Account line was paid down by half' ); + is( $accountline->amountoutstanding + 0, 0, 'Account line was paid down by half' ); $checkout = Koha::Checkouts->find( $checkout->id ); ok( !$checkout, 'Item was removed from patron account' ); @@ -1026,14 +1043,13 @@ subtest 'pay() renews items when appropriate' => sub { $context->mock( 'userenv', { branch => $library->id } ); my $biblio = $builder->build_sample_biblio(); - my $item = - $builder->build_sample_item( { biblionumber => $biblio->biblionumber } ); + my $item = $builder->build_sample_item( { biblionumber => $biblio->biblionumber } ); - my $now = dt_from_string(); - my $seven_weeks = DateTime::Duration->new(weeks => 7); - my $five_weeks = DateTime::Duration->new(weeks => 5); + my $now = dt_from_string(); + my $seven_weeks = DateTime::Duration->new( weeks => 7 ); + my $five_weeks = DateTime::Duration->new( weeks => 5 ); my $seven_weeks_ago = $now - $seven_weeks; - my $five_weeks_ago = $now - $five_weeks; + my $five_weeks_ago = $now - $five_weeks; my $checkout = Koha::Checkout->new( { @@ -1047,14 +1063,14 @@ subtest 'pay() renews items when appropriate' => sub { my $accountline = Koha::Account::Line->new( { - issue_id => $checkout->id, - borrowernumber => $patron->id, - itemnumber => $item->id, - date => \'NOW()', - debit_type_code => 'OVERDUE', - status => 'UNRETURNED', - interface => 'cli', - amount => '1', + issue_id => $checkout->id, + borrowernumber => $patron->id, + itemnumber => $item->id, + date => \'NOW()', + debit_type_code => 'OVERDUE', + status => 'UNRETURNED', + interface => 'cli', + amount => '1', amountoutstanding => '1', } )->store(); @@ -1063,8 +1079,8 @@ subtest 'pay() renews items when appropriate' => sub { t::lib::Mocks::mock_preference( 'RenewAccruingItemWhenPaid', 1 ); my $called = 0; my $module = Test::MockModule->new('C4::Circulation'); - $module->mock('AddRenewal', sub { $called = 1; }); - $module->mock('CanBookBeRenewed', sub { return 1; }); + $module->mock( 'AddRenewal', sub { $called = 1; } ); + $module->mock( 'CanBookBeRenewed', sub { return 1; } ); my $result = $account->pay( { amount => '1', @@ -1073,21 +1089,21 @@ subtest 'pay() renews items when appropriate' => sub { ); is( $called, 1, 'RenewAccruingItemWhenPaid causes C4::Circulation::AddRenew to be called when appropriate' ); - is(ref($result->{renew_result}), 'ARRAY', "Pay result contains 'renew_result' ARRAY" ); - is( scalar @{$result->{renew_result}}, 1, "renew_result contains one renewal result" ); + is( ref( $result->{renew_result} ), 'ARRAY', "Pay result contains 'renew_result' ARRAY" ); + is( scalar @{ $result->{renew_result} }, 1, "renew_result contains one renewal result" ); is( $result->{renew_result}->[0]->{itemnumber}, $item->id, "renew_result contains itemnumber of renewed item" ); # Reset test by adding a new overdue Koha::Account::Line->new( { - issue_id => $checkout->id, - borrowernumber => $patron->id, - itemnumber => $item->id, - date => \'NOW()', - debit_type_code => 'OVERDUE', - status => 'UNRETURNED', - interface => 'cli', - amount => '1', + issue_id => $checkout->id, + borrowernumber => $patron->id, + itemnumber => $item->id, + date => \'NOW()', + debit_type_code => 'OVERDUE', + status => 'UNRETURNED', + interface => 'cli', + amount => '1', amountoutstanding => '1', } )->store(); @@ -1102,8 +1118,8 @@ subtest 'pay() renews items when appropriate' => sub { ); is( $called, 0, 'C4::Circulation::AddRenew NOT called when RenewAccruingItemWhenPaid disabled' ); - is(ref($result->{renew_result}), 'ARRAY', "Pay result contains 'renew_result' ARRAY" ); - is( scalar @{$result->{renew_result}}, 0, "renew_result contains no renewal results" ); + is( ref( $result->{renew_result} ), 'ARRAY', "Pay result contains 'renew_result' ARRAY" ); + is( scalar @{ $result->{renew_result} }, 0, "renew_result contains no renewal results" ); $schema->storage->txn_rollback; }; @@ -1122,8 +1138,7 @@ subtest 'Koha::Account::Line::apply() handles lost items' => sub { $context->mock( 'userenv', { branch => $library->id } ); my $biblio = $builder->build_sample_biblio(); - my $item = - $builder->build_sample_item( { biblionumber => $biblio->biblionumber } ); + my $item = $builder->build_sample_item( { biblionumber => $biblio->biblionumber } ); my $checkout = Koha::Checkout->new( { @@ -1143,7 +1158,7 @@ subtest 'Koha::Account::Line::apply() handles lost items' => sub { borrowernumber => $patron->id, itemnumber => $item->id, date => \'NOW()', - debit_type_code => 'LOST', + debit_type_code => 'LOST', interface => 'cli', amount => '1', amountoutstanding => '1', @@ -1161,10 +1176,10 @@ subtest 'Koha::Account::Line::apply() handles lost items' => sub { } )->store(); my $debits = $account->outstanding_debits; - $credit->apply({ debits => [ $debits->as_list ] }); + $credit->apply( { debits => [ $debits->as_list ] } ); $debit = Koha::Account::Lines->find( $debit->id ); - is( $debit->amountoutstanding+0, .5, 'Account line was paid down by half' ); + is( $debit->amountoutstanding + 0, .5, 'Account line was paid down by half' ); $checkout = Koha::Checkouts->find( $checkout->id ); ok( $checkout, 'Item still checked out to patron' ); @@ -1180,10 +1195,10 @@ subtest 'Koha::Account::Line::apply() handles lost items' => sub { } )->store(); $debits = $account->outstanding_debits; - $credit->apply({ debits => [ $debits->as_list ] }); + $credit->apply( { debits => [ $debits->as_list ] } ); $debit = Koha::Account::Lines->find( $debit->id ); - is( $debit->amountoutstanding+0, 0, 'Account line was paid down by half' ); + is( $debit->amountoutstanding + 0, 0, 'Account line was paid down by half' ); $checkout = Koha::Checkouts->find( $checkout->id ); ok( !$checkout, 'Item was removed from patron account' ); @@ -1206,49 +1221,59 @@ subtest 'Koha::Account::pay() generates credit number (Koha::Account::Line->stor my $context = Test::MockModule->new('C4::Context'); $context->mock( 'userenv', { branch => $library->id } ); - my $now = dt_from_string; - my $year = $now->year; + my $now = dt_from_string; + my $year = $now->year; my $month = $now->month; - my ($accountlines_id, $accountline); + my ( $accountlines_id, $accountline ); my $credit_type = Koha::Account::CreditTypes->find('PAYMENT'); $credit_type->credit_number_enabled(1); $credit_type->store(); - t::lib::Mocks::mock_preference('AutoCreditNumber', ''); - $accountlines_id = $account->pay({ amount => '1.00', library_id => $library->id })->{payment_id}; - $accountline = Koha::Account::Lines->find($accountlines_id); - is($accountline->credit_number, undef, 'No credit number is generated when syspref is off'); + t::lib::Mocks::mock_preference( 'AutoCreditNumber', '' ); + $accountlines_id = $account->pay( { amount => '1.00', library_id => $library->id } )->{payment_id}; + $accountline = Koha::Account::Lines->find($accountlines_id); + is( $accountline->credit_number, undef, 'No credit number is generated when syspref is off' ); - t::lib::Mocks::mock_preference('AutoCreditNumber', 'incremental'); - for my $i (1..11) { - $accountlines_id = $account->pay({ amount => '1.00', library_id => $library->id })->{payment_id}; - $accountline = Koha::Account::Lines->find($accountlines_id); - is($accountline->credit_number, $i, "Incremental format credit number added for payments: $i"); + t::lib::Mocks::mock_preference( 'AutoCreditNumber', 'incremental' ); + for my $i ( 1 .. 11 ) { + $accountlines_id = $account->pay( { amount => '1.00', library_id => $library->id } )->{payment_id}; + $accountline = Koha::Account::Lines->find($accountlines_id); + is( $accountline->credit_number, $i, "Incremental format credit number added for payments: $i" ); } - $accountlines_id = $account->pay({ type => 'WRITEOFF', amount => '1.00', library_id => $library->id })->{payment_id}; + $accountlines_id = + $account->pay( { type => 'WRITEOFF', amount => '1.00', library_id => $library->id } )->{payment_id}; $accountline = Koha::Account::Lines->find($accountlines_id); - is($accountline->credit_number, undef, "Incremental credit number not added for writeoff"); + is( $accountline->credit_number, undef, "Incremental credit number not added for writeoff" ); - t::lib::Mocks::mock_preference('AutoCreditNumber', 'annual'); - for my $i (1..11) { - $accountlines_id = $account->pay({ amount => '1.00', library_id => $library->id })->{payment_id}; - $accountline = Koha::Account::Lines->find($accountlines_id); - is($accountline->credit_number, sprintf('%s-%04d', $year, $i), "Annual format credit number added for payments: " . sprintf('%s-%04d', $year, $i)); + t::lib::Mocks::mock_preference( 'AutoCreditNumber', 'annual' ); + for my $i ( 1 .. 11 ) { + $accountlines_id = $account->pay( { amount => '1.00', library_id => $library->id } )->{payment_id}; + $accountline = Koha::Account::Lines->find($accountlines_id); + is( + $accountline->credit_number, sprintf( '%s-%04d', $year, $i ), + "Annual format credit number added for payments: " . sprintf( '%s-%04d', $year, $i ) + ); } - $accountlines_id = $account->pay({ type => 'WRITEOFF', amount => '1.00', library_id => $library->id })->{payment_id}; + $accountlines_id = + $account->pay( { type => 'WRITEOFF', amount => '1.00', library_id => $library->id } )->{payment_id}; $accountline = Koha::Account::Lines->find($accountlines_id); - is($accountline->credit_number, undef, "Annual format credit number not aded for writeoff"); + is( $accountline->credit_number, undef, "Annual format credit number not aded for writeoff" ); - t::lib::Mocks::mock_preference('AutoCreditNumber', 'branchyyyymmincr'); - for my $i (1..11) { - $accountlines_id = $account->pay({ amount => '1.00', library_id => $library->id })->{payment_id}; - $accountline = Koha::Account::Lines->find($accountlines_id); - is($accountline->credit_number, sprintf('%s%d%02d%04d', $library->id, $year, $month, $i), "branchyyyymmincr format credit number added for payment: " . sprintf('%s%d%02d%04d', $library->id, $year, $month, $i)); + t::lib::Mocks::mock_preference( 'AutoCreditNumber', 'branchyyyymmincr' ); + for my $i ( 1 .. 11 ) { + $accountlines_id = $account->pay( { amount => '1.00', library_id => $library->id } )->{payment_id}; + $accountline = Koha::Account::Lines->find($accountlines_id); + is( + $accountline->credit_number, sprintf( '%s%d%02d%04d', $library->id, $year, $month, $i ), + "branchyyyymmincr format credit number added for payment: " + . sprintf( '%s%d%02d%04d', $library->id, $year, $month, $i ) + ); } - $accountlines_id = $account->pay({ type => 'WRITEOFF', amount => '1.00', library_id => $library->id })->{payment_id}; + $accountlines_id = + $account->pay( { type => 'WRITEOFF', amount => '1.00', library_id => $library->id } )->{payment_id}; $accountline = Koha::Account::Lines->find($accountlines_id); - is($accountline->credit_number, undef, "branchyyyymmincr format credit number not added for writeoff"); + is( $accountline->credit_number, undef, "branchyyyymmincr format credit number not added for writeoff" ); throws_ok { Koha::Account::Line->new( @@ -1261,7 +1286,7 @@ subtest 'Koha::Account::pay() generates credit number (Koha::Account::Line->stor )->store; } 'Koha::Exceptions::Account', -"Exception thrown when AutoCreditNumber is enabled but credit_number is already defined"; + "Exception thrown when AutoCreditNumber is enabled but credit_number is already defined"; $schema->storage->txn_rollback; }; @@ -1275,13 +1300,11 @@ subtest 'Koha::Account::payout_amount() tests' => sub { my $action_logs = $schema->resultset('ActionLog')->search()->count; my $statistics = $schema->resultset('Statistic')->search()->count; - my $staff = $builder->build_object( { class => 'Koha::Patrons' } ); - my $library = $builder->build_object( { class => 'Koha::Libraries' } ); - my $register = - $builder->build_object( { class => 'Koha::Cash::Registers' } ); - my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); - my $account = - Koha::Account->new( { patron_id => $patron->borrowernumber } ); + my $staff = $builder->build_object( { class => 'Koha::Patrons' } ); + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); + my $register = $builder->build_object( { class => 'Koha::Cash::Registers' } ); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + my $account = Koha::Account->new( { patron_id => $patron->borrowernumber } ); is( $account->balance, 0, 'Test patron has no balance' ); @@ -1294,8 +1317,7 @@ subtest 'Koha::Account::payout_amount() tests' => sub { amount => -10, }; - my @required_fields = - ( 'interface', 'staff_id', 'branch', 'payout_type', 'amount' ); + my @required_fields = ( 'interface', 'staff_id', 'branch', 'payout_type', 'amount' ); for my $required_field (@required_fields) { my $this_payout = { %{$payout_params} }; delete $this_payout->{$required_field}; @@ -1304,21 +1326,21 @@ subtest 'Koha::Account::payout_amount() tests' => sub { $account->payout_amount($this_payout); } 'Koha::Exceptions::MissingParameter', - "Exception thrown if $required_field parameter missing"; + "Exception thrown if $required_field parameter missing"; } throws_ok { $account->payout_amount($payout_params); } 'Koha::Exceptions::Account::AmountNotPositive', - 'Expected validation exception thrown (amount not positive)'; + 'Expected validation exception thrown (amount not positive)'; $payout_params->{amount} = 10; throws_ok { $account->payout_amount($payout_params); } 'Koha::Exceptions::ParameterTooHigh', - 'Expected validation exception thrown (amount greater than outstanding)'; + 'Expected validation exception thrown (amount greater than outstanding)'; # Enable cash registers t::lib::Mocks::mock_preference( 'UseCashRegisters', 1 ); @@ -1326,7 +1348,7 @@ subtest 'Koha::Account::payout_amount() tests' => sub { $account->payout_amount($payout_params); } 'Koha::Exceptions::Account::RegisterRequired', -'Exception thrown for UseCashRegisters:1 + payout_type:CASH + cash_register:undef'; + 'Exception thrown for UseCashRegisters:1 + payout_type:CASH + cash_register:undef'; # Disable cash registers t::lib::Mocks::mock_preference( 'UseCashRegisters', 0 ); @@ -1336,60 +1358,63 @@ subtest 'Koha::Account::payout_amount() tests' => sub { my $credit_2 = $account->add_credit( { amount => 3, interface => 'commandline' } ); my $credit_3 = $account->add_credit( { amount => 5, interface => 'commandline' } ); my $credit_4 = $account->add_credit( { amount => 10, interface => 'commandline' } ); - my $credits = $account->outstanding_credits(); - is( $credits->count, 4, "Found 4 credits with outstanding amounts" ); + my $credits = $account->outstanding_credits(); + is( $credits->count, 4, "Found 4 credits with outstanding amounts" ); is( $credits->total_outstanding + 0, -20, "Total -20 outstanding credit" ); my $payout = $account->payout_amount($payout_params); - is(ref($payout), 'Koha::Account::Line', 'Return the Koha::Account::Line object for the payout'); - is($payout->amount + 0, 10, "Payout amount recorded correctly"); - is($payout->amountoutstanding + 0, 0, "Full amount was paid out"); + is( ref($payout), 'Koha::Account::Line', 'Return the Koha::Account::Line object for the payout' ); + is( $payout->amount + 0, 10, "Payout amount recorded correctly" ); + is( $payout->amountoutstanding + 0, 0, "Full amount was paid out" ); $credits = $account->outstanding_credits(); - is($credits->count, 1, "Payout was applied against oldest outstanding credits first"); - is($credits->total_outstanding + 0, -10, "Total of 10 outstanding credit remaining"); + is( $credits->count, 1, "Payout was applied against oldest outstanding credits first" ); + is( $credits->total_outstanding + 0, -10, "Total of 10 outstanding credit remaining" ); my $offsets = Koha::Account::Offsets->search( { debit_id => $payout->id } ); is( $offsets->count, 4, 'Four offsets generated' ); my $offset = $offsets->next; - is( $offset->type, 'CREATE', 'CREATE offset added for payout line' ); - is( $offset->amount * 1, 10, 'Correct offset amount recorded' ); + is( $offset->type, 'CREATE', 'CREATE offset added for payout line' ); + is( $offset->amount * 1, 10, 'Correct offset amount recorded' ); $offset = $offsets->next; - is( $offset->credit_id, $credit_1->id, "Offset added against credit_1"); - is( $offset->type, 'APPLY', "APPLY used for offset_type" ); - is( $offset->amount * 1, -2, 'Correct amount offset against credit_1' ); + is( $offset->credit_id, $credit_1->id, "Offset added against credit_1" ); + is( $offset->type, 'APPLY', "APPLY used for offset_type" ); + is( $offset->amount * 1, -2, 'Correct amount offset against credit_1' ); $offset = $offsets->next; - is( $offset->credit_id, $credit_2->id, "Offset added against credit_2"); - is( $offset->type, 'APPLY', "APPLY used for offset_type" ); - is( $offset->amount * 1, -3, 'Correct amount offset against credit_2' ); + is( $offset->credit_id, $credit_2->id, "Offset added against credit_2" ); + is( $offset->type, 'APPLY', "APPLY used for offset_type" ); + is( $offset->amount * 1, -3, 'Correct amount offset against credit_2' ); $offset = $offsets->next; - is( $offset->credit_id, $credit_3->id, "Offset added against credit_3"); - is( $offset->type, 'APPLY', "APPLY used for offset_type" ); - is( $offset->amount * 1, -5, 'Correct amount offset against credit_3' ); + is( $offset->credit_id, $credit_3->id, "Offset added against credit_3" ); + is( $offset->type, 'APPLY', "APPLY used for offset_type" ); + is( $offset->amount * 1, -5, 'Correct amount offset against credit_3' ); my $credit_5 = $account->add_credit( { amount => 5, interface => 'commandline' } ); $credits = $account->outstanding_credits(); - is($credits->count, 2, "New credit added"); - $payout_params->{amount} = 2.50; + is( $credits->count, 2, "New credit added" ); + $payout_params->{amount} = 2.50; $payout_params->{credits} = [$credit_5]; - $payout = $account->payout_amount($payout_params); + $payout = $account->payout_amount($payout_params); $credits = $account->outstanding_credits(); - is($credits->count, 2, "Second credit not fully paid off"); - is($credits->total_outstanding + 0, -12.50, "12.50 outstanding credit remaining"); + is( $credits->count, 2, "Second credit not fully paid off" ); + is( $credits->total_outstanding + 0, -12.50, "12.50 outstanding credit remaining" ); $credit_4->discard_changes; $credit_5->discard_changes; - is($credit_4->amountoutstanding + 0, -10, "Credit 4 unaffected when credit_5 was passed to payout_amount"); - is($credit_5->amountoutstanding + 0, -2.50, "Credit 5 correctly reduced when payout_amount called with credit_5 passed"); + is( $credit_4->amountoutstanding + 0, -10, "Credit 4 unaffected when credit_5 was passed to payout_amount" ); + is( + $credit_5->amountoutstanding + 0, -2.50, + "Credit 5 correctly reduced when payout_amount called with credit_5 passed" + ); $offsets = Koha::Account::Offsets->search( { debit_id => $payout->id } ); is( $offsets->count, 2, 'Two offsets generated' ); $offset = $offsets->next; - is( $offset->type, 'CREATE', 'CREATE offset added for payout line' ); - is( $offset->amount * 1, 2.50, 'Correct offset amount recorded' ); + is( $offset->type, 'CREATE', 'CREATE offset added for payout line' ); + is( $offset->amount * 1, 2.50, 'Correct offset amount recorded' ); $offset = $offsets->next; - is( $offset->credit_id, $credit_5->id, "Offset added against credit_5"); - is( $offset->type, 'APPLY', "APPLY used for offset_type" ); - is( $offset->amount * 1, -2.50, 'Correct amount offset against credit_5' ); + is( $offset->credit_id, $credit_5->id, "Offset added against credit_5" ); + is( $offset->type, 'APPLY', "APPLY used for offset_type" ); + is( $offset->amount * 1, -2.50, 'Correct amount offset against credit_5' ); $schema->storage->txn_rollback; }; @@ -1403,18 +1428,16 @@ subtest 'Koha::Account::payin_amount() tests' => sub { my $action_logs = $schema->resultset('ActionLog')->search()->count; my $statistics = $schema->resultset('Statistic')->search()->count; - my $staff = $builder->build_object( { class => 'Koha::Patrons' } ); - my $library = $builder->build_object( { class => 'Koha::Libraries' } ); - my $register = - $builder->build_object( { class => 'Koha::Cash::Registers' } ); - my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); - my $account = - Koha::Account->new( { patron_id => $patron->borrowernumber } ); + my $staff = $builder->build_object( { class => 'Koha::Patrons' } ); + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); + my $register = $builder->build_object( { class => 'Koha::Cash::Registers' } ); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + my $account = Koha::Account->new( { patron_id => $patron->borrowernumber } ); is( $account->balance, 0, 'Test patron has no balance' ); my $payin_params = { - type => 'PAYMENT', + type => 'PAYMENT', payment_type => 'CASH', branch => $library->id, register_id => $register->id, @@ -1423,8 +1446,7 @@ subtest 'Koha::Account::payin_amount() tests' => sub { amount => -10, }; - my @required_fields = - ( 'interface', 'amount', 'type' ); + my @required_fields = ( 'interface', 'amount', 'type' ); for my $required_field (@required_fields) { my $this_payin = { %{$payin_params} }; delete $this_payin->{$required_field}; @@ -1433,14 +1455,14 @@ subtest 'Koha::Account::payin_amount() tests' => sub { $account->payin_amount($this_payin); } 'Koha::Exceptions::MissingParameter', - "Exception thrown if $required_field parameter missing"; + "Exception thrown if $required_field parameter missing"; } throws_ok { $account->payin_amount($payin_params); } 'Koha::Exceptions::Account::AmountNotPositive', - 'Expected validation exception thrown (amount not positive)'; + 'Expected validation exception thrown (amount not positive)'; $payin_params->{amount} = 10; @@ -1450,7 +1472,7 @@ subtest 'Koha::Account::payin_amount() tests' => sub { $account->payin_amount($payin_params); } 'Koha::Exceptions::Account::RegisterRequired', -'Exception thrown for UseCashRegisters:1 + payment_type:CASH + cash_register:undef'; + 'Exception thrown for UseCashRegisters:1 + payment_type:CASH + cash_register:undef'; # Disable cash registers t::lib::Mocks::mock_preference( 'UseCashRegisters', 0 ); @@ -1463,60 +1485,63 @@ subtest 'Koha::Account::payin_amount() tests' => sub { my $debit_2 = $account->add_debit( { amount => 3, interface => 'commandline', type => 'OVERDUE' } ); my $debit_3 = $account->add_debit( { amount => 5, interface => 'commandline', type => 'OVERDUE' } ); my $debit_4 = $account->add_debit( { amount => 10, interface => 'commandline', type => 'OVERDUE' } ); - my $debits = $account->outstanding_debits(); - is( $debits->count, 4, "Found 4 debits with outstanding amounts" ); + my $debits = $account->outstanding_debits(); + is( $debits->count, 4, "Found 4 debits with outstanding amounts" ); is( $debits->total_outstanding + 0, 20, "Total 20 outstanding debit" ); my $payin = $account->payin_amount($payin_params); - is(ref($payin), 'Koha::Account::Line', 'Return the Koha::Account::Line object for the payin'); - is($payin->amount + 0, -10, "Payin amount recorded correctly"); - is($payin->amountoutstanding + 0, 0, "Full amount was used to pay debts"); + is( ref($payin), 'Koha::Account::Line', 'Return the Koha::Account::Line object for the payin' ); + is( $payin->amount + 0, -10, "Payin amount recorded correctly" ); + is( $payin->amountoutstanding + 0, 0, "Full amount was used to pay debts" ); $debits = $account->outstanding_debits(); - is($debits->count, 1, "Payin was applied against oldest outstanding debits first"); - is($debits->total_outstanding + 0, 10, "Total of 10 outstanding debit remaining"); + is( $debits->count, 1, "Payin was applied against oldest outstanding debits first" ); + is( $debits->total_outstanding + 0, 10, "Total of 10 outstanding debit remaining" ); my $offsets = Koha::Account::Offsets->search( { credit_id => $payin->id } ); is( $offsets->count, 4, 'Four offsets generated' ); my $offset = $offsets->next; - is( $offset->type, 'CREATE', 'CREATE offset added for payin line' ); - is( $offset->amount * 1, 10, 'Correct offset amount recorded' ); + is( $offset->type, 'CREATE', 'CREATE offset added for payin line' ); + is( $offset->amount * 1, 10, 'Correct offset amount recorded' ); $offset = $offsets->next; - is( $offset->debit_id, $debit_1->id, "Offset added against debit_1"); - is( $offset->type, 'APPLY', "APPLY used for offset_type" ); - is( $offset->amount * 1, -2, 'Correct amount offset against debit_1' ); + is( $offset->debit_id, $debit_1->id, "Offset added against debit_1" ); + is( $offset->type, 'APPLY', "APPLY used for offset_type" ); + is( $offset->amount * 1, -2, 'Correct amount offset against debit_1' ); $offset = $offsets->next; - is( $offset->debit_id, $debit_2->id, "Offset added against debit_2"); - is( $offset->type, 'APPLY', "APPLY used for offset_type" ); - is( $offset->amount * 1, -3, 'Correct amount offset against debit_2' ); + is( $offset->debit_id, $debit_2->id, "Offset added against debit_2" ); + is( $offset->type, 'APPLY', "APPLY used for offset_type" ); + is( $offset->amount * 1, -3, 'Correct amount offset against debit_2' ); $offset = $offsets->next; - is( $offset->debit_id, $debit_3->id, "Offset added against debit_3"); - is( $offset->type, 'APPLY', "APPLY used for offset_type" ); - is( $offset->amount * 1, -5, 'Correct amount offset against debit_3' ); + is( $offset->debit_id, $debit_3->id, "Offset added against debit_3" ); + is( $offset->type, 'APPLY', "APPLY used for offset_type" ); + is( $offset->amount * 1, -5, 'Correct amount offset against debit_3' ); my $debit_5 = $account->add_debit( { amount => 5, interface => 'commandline', type => 'OVERDUE' } ); $debits = $account->outstanding_debits(); - is($debits->count, 2, "New debit added"); + is( $debits->count, 2, "New debit added" ); $payin_params->{amount} = 2.50; $payin_params->{debits} = [$debit_5]; - $payin = $account->payin_amount($payin_params); + $payin = $account->payin_amount($payin_params); $debits = $account->outstanding_debits(); - is($debits->count, 2, "Second debit not fully paid off"); - is($debits->total_outstanding + 0, 12.50, "12.50 outstanding debit remaining"); + is( $debits->count, 2, "Second debit not fully paid off" ); + is( $debits->total_outstanding + 0, 12.50, "12.50 outstanding debit remaining" ); $debit_4->discard_changes; $debit_5->discard_changes; - is($debit_4->amountoutstanding + 0, 10, "Debit 4 unaffected when debit_5 was passed to payin_amount"); - is($debit_5->amountoutstanding + 0, 2.50, "Debit 5 correctly reduced when payin_amount called with debit_5 passed"); + is( $debit_4->amountoutstanding + 0, 10, "Debit 4 unaffected when debit_5 was passed to payin_amount" ); + is( + $debit_5->amountoutstanding + 0, 2.50, + "Debit 5 correctly reduced when payin_amount called with debit_5 passed" + ); $offsets = Koha::Account::Offsets->search( { credit_id => $payin->id } ); is( $offsets->count, 2, 'Two offsets generated' ); $offset = $offsets->next; - is( $offset->type, 'CREATE', 'CREATE offset added for payin line' ); - is( $offset->amount * 1, 2.50, 'Correct offset amount recorded' ); + is( $offset->type, 'CREATE', 'CREATE offset added for payin line' ); + is( $offset->amount * 1, 2.50, 'Correct offset amount recorded' ); $offset = $offsets->next; - is( $offset->debit_id, $debit_5->id, "Offset added against debit_5"); - is( $offset->type, 'APPLY', "APPLY used for offset_type" ); - is( $offset->amount * 1, -2.50, 'Correct amount offset against debit_5' ); + is( $offset->debit_id, $debit_5->id, "Offset added against debit_5" ); + is( $offset->type, 'APPLY', "APPLY used for offset_type" ); + is( $offset->amount * 1, -2.50, 'Correct amount offset against debit_5' ); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/Koha/Account/DebitType.t b/t/db_dependent/Koha/Account/DebitType.t index 34e8ceec89..c13d7586e7 100755 --- a/t/db_dependent/Koha/Account/DebitType.t +++ b/t/db_dependent/Koha/Account/DebitType.t @@ -57,27 +57,31 @@ is( '2 debit types added successfully' ); -my $retrieved_debit_type_1 = - Koha::Account::DebitTypes->find( $new_debit_type_1->code ); +my $retrieved_debit_type_1 = Koha::Account::DebitTypes->find( $new_debit_type_1->code ); is( $retrieved_debit_type_1->description, $new_debit_type_1->description, 'Find a debit type by code should return the correct one (non-system)' ); -ok( !$retrieved_debit_type_1->is_system, - 'Non-system debit type identified correctly by "is_system"' ); +ok( + !$retrieved_debit_type_1->is_system, + 'Non-system debit type identified correctly by "is_system"' +); my $retrieved_debit_type_system = Koha::Account::DebitTypes->find('OVERDUE'); -is( $retrieved_debit_type_system->code, +is( + $retrieved_debit_type_system->code, 'OVERDUE', - 'Find a debit type by code should return the correct one (system)' ); -ok( $retrieved_debit_type_system->is_system, - 'System debit type identified correctly by "is_system"' ); + 'Find a debit type by code should return the correct one (system)' +); +ok( + $retrieved_debit_type_system->is_system, + 'System debit type identified correctly by "is_system"' +); try { $retrieved_debit_type_system->delete; -} -catch { +} catch { ok( $_->isa('Koha::Exceptions::CannotDeleteDefault'), 'A system debit type cannot be deleted' diff --git a/t/db_dependent/Koha/Account/DebitTypes.t b/t/db_dependent/Koha/Account/DebitTypes.t index 0c4812d2bd..3f6148ee52 100755 --- a/t/db_dependent/Koha/Account/DebitTypes.t +++ b/t/db_dependent/Koha/Account/DebitTypes.t @@ -55,8 +55,7 @@ my $new_debit_type_2 = Koha::Account::DebitType->new( my $retrieved_debit_types_all = Koha::Account::DebitTypes->search(); try { $retrieved_debit_types_all->delete; -} -catch { +} catch { ok( $_->isa('Koha::Exceptions::CannotDeleteDefault'), 'A system debit type cannot be deleted via the set' @@ -68,14 +67,13 @@ is( 'System debit types cannot be deleted as a set' ); -my $retrieved_debit_types_limited = Koha::Account::DebitTypes->search( - { - code => { 'in' => [ $new_debit_type_1->code, $new_debit_type_2->code ] } - } -); +my $retrieved_debit_types_limited = + Koha::Account::DebitTypes->search( { code => { 'in' => [ $new_debit_type_1->code, $new_debit_type_2->code ] } } ); $retrieved_debit_types_limited->delete; -is( Koha::Account::DebitTypes->search->count, - $number_of_debit_types, 'Non-system debit types can be deleted as a set' ); +is( + Koha::Account::DebitTypes->search->count, + $number_of_debit_types, 'Non-system debit types can be deleted as a set' +); $schema->storage->txn_rollback; diff --git a/t/db_dependent/Koha/Account/Line.t b/t/db_dependent/Koha/Account/Line.t index 20c9e64afa..ad2e4911ab 100755 --- a/t/db_dependent/Koha/Account/Line.t +++ b/t/db_dependent/Koha/Account/Line.t @@ -35,7 +35,7 @@ use Koha::DateUtils qw( dt_from_string ); use t::lib::Mocks; use t::lib::TestBuilder; -my $schema = Koha::Database->new->schema; +my $schema = Koha::Database->new->schema; my $builder = t::lib::TestBuilder->new; subtest 'patron() tests' => sub { @@ -45,20 +45,24 @@ subtest 'patron() tests' => sub { $schema->storage->txn_begin; my $library = $builder->build( { source => 'Branch' } ); - my $patron = $builder->build( { source => 'Borrower' } ); + my $patron = $builder->build( { source => 'Borrower' } ); my $line = Koha::Account::Line->new( - { - borrowernumber => $patron->{borrowernumber}, - debit_type_code => "OVERDUE", - status => "RETURNED", - amount => 10, - interface => 'commandline', - })->store; + { + borrowernumber => $patron->{borrowernumber}, + debit_type_code => "OVERDUE", + status => "RETURNED", + amount => 10, + interface => 'commandline', + } + )->store; my $account_line_patron = $line->patron; - is( ref( $account_line_patron ), 'Koha::Patron', 'Koha::Account::Line->patron should return a Koha::Patron' ); - is( $line->borrowernumber, $account_line_patron->borrowernumber, 'Koha::Account::Line->patron should return the correct borrower' ); + is( ref($account_line_patron), 'Koha::Patron', 'Koha::Account::Line->patron should return a Koha::Patron' ); + is( + $line->borrowernumber, $account_line_patron->borrowernumber, + 'Koha::Account::Line->patron should return the correct borrower' + ); $line->borrowernumber(undef)->store; is( $line->patron, undef, 'Koha::Account::Line->patron should return undef if no patron linked' ); @@ -76,17 +80,21 @@ subtest 'manager() tests' => sub { my $manager = $builder->build( { source => 'Borrower' } ); my $line = Koha::Account::Line->new( - { - manager_id => $manager->{borrowernumber}, - debit_type_code => "OVERDUE", - status => "RETURNED", - amount => 10, - interface => 'commandline', - })->store; + { + manager_id => $manager->{borrowernumber}, + debit_type_code => "OVERDUE", + status => "RETURNED", + amount => 10, + interface => 'commandline', + } + )->store; my $account_line_manager = $line->manager; - is( ref( $account_line_manager ), 'Koha::Patron', 'Koha::Account::Line->manager should return a Koha::Patron' ); - is( $line->manager_id, $account_line_manager->borrowernumber, 'Koha::Account::Line->manager should return the correct staff' ); + is( ref($account_line_manager), 'Koha::Patron', 'Koha::Account::Line->manager should return a Koha::Patron' ); + is( + $line->manager_id, $account_line_manager->borrowernumber, + 'Koha::Account::Line->manager should return the correct staff' + ); $line->manager_id(undef)->store; is( $line->manager, undef, 'Koha::Account::Line->manager should return undef if no staff linked' ); @@ -101,8 +109,8 @@ subtest 'item() tests' => sub { $schema->storage->txn_begin; my $library = $builder->build( { source => 'Branch' } ); - my $patron = $builder->build( { source => 'Borrower' } ); - my $item = $builder->build_sample_item( + my $patron = $builder->build( { source => 'Borrower' } ); + my $item = $builder->build_sample_item( { library => $library->{branchcode}, barcode => 'some_barcode_12', @@ -111,17 +119,18 @@ subtest 'item() tests' => sub { ); my $line = Koha::Account::Line->new( - { - borrowernumber => $patron->{borrowernumber}, - itemnumber => $item->itemnumber, - debit_type_code => "OVERDUE", - status => "RETURNED", - amount => 10, - interface => 'commandline', - })->store; + { + borrowernumber => $patron->{borrowernumber}, + itemnumber => $item->itemnumber, + debit_type_code => "OVERDUE", + status => "RETURNED", + amount => 10, + interface => 'commandline', + } + )->store; my $account_line_item = $line->item; - is( ref( $account_line_item ), 'Koha::Item', 'Koha::Account::Line->item should return a Koha::Item' ); + is( ref($account_line_item), 'Koha::Item', 'Koha::Account::Line->item should return a Koha::Item' ); is( $line->itemnumber, $account_line_item->itemnumber, 'Koha::Account::Line->item should return the correct item' ); $line->itemnumber(undef)->store; @@ -151,9 +160,11 @@ subtest 'library() tests' => sub { )->store; my $account_line_library = $line->library; - is( ref($account_line_library), + is( + ref($account_line_library), 'Koha::Library', - 'Koha::Account::Line->library should return a Koha::Library' ); + 'Koha::Account::Line->library should return a Koha::Library' + ); is( $line->branchcode, $account_line_library->branchcode, @@ -165,8 +176,9 @@ subtest 'library() tests' => sub { my $found = Koha::Account::Lines->find( $line->accountlines_id ); ok( $found, "Koha::Account::Line not deleted when the linked library is deleted" ); - is( $found->library, undef, -'Koha::Account::Line->library should return undef if linked library has been deleted' + is( + $found->library, undef, + 'Koha::Account::Line->library should return undef if linked library has been deleted' ); $schema->storage->txn_rollback; @@ -178,25 +190,26 @@ subtest 'is_credit() and is_debit() tests' => sub { $schema->storage->txn_begin; - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $account = $patron->account; - my $credit = $account->add_credit({ amount => 100, user_id => $patron->id, interface => 'commandline' }); + my $credit = $account->add_credit( { amount => 100, user_id => $patron->id, interface => 'commandline' } ); ok( $credit->is_credit, 'is_credit detects credits' ); ok( !$credit->is_debit, 'is_debit detects credits' ); my $debit = Koha::Account::Line->new( - { - borrowernumber => $patron->id, - debit_type_code => "OVERDUE", - status => "RETURNED", - amount => 10, - interface => 'commandline', - })->store; + { + borrowernumber => $patron->id, + debit_type_code => "OVERDUE", + status => "RETURNED", + amount => 10, + interface => 'commandline', + } + )->store; ok( !$debit->is_credit, 'is_credit detects debits' ); - ok( $debit->is_debit, 'is_debit detects debits'); + ok( $debit->is_debit, 'is_debit detects debits' ); $schema->storage->txn_rollback; }; @@ -213,8 +226,9 @@ subtest 'apply() tests' => sub { my $credit = $account->add_credit( { amount => 100, user_id => $patron->id, interface => 'commandline' } ); my $debit_1 = Koha::Account::Line->new( - { borrowernumber => $patron->id, - debit_type_code => "OVERDUE", + { + borrowernumber => $patron->id, + debit_type_code => "OVERDUE", status => "RETURNED", amount => 10, amountoutstanding => 10, @@ -223,8 +237,9 @@ subtest 'apply() tests' => sub { )->store; my $debit_2 = Koha::Account::Line->new( - { borrowernumber => $patron->id, - debit_type_code => "OVERDUE", + { + borrowernumber => $patron->id, + debit_type_code => "OVERDUE", status => "RETURNED", amount => 100, amountoutstanding => 100, @@ -235,9 +250,9 @@ subtest 'apply() tests' => sub { $credit->discard_changes; $debit_1->discard_changes; - my $debits = Koha::Account::Lines->search({ accountlines_id => $debit_1->id }); + my $debits = Koha::Account::Lines->search( { accountlines_id => $debit_1->id } ); $credit = $credit->apply( { debits => [ $debits->as_list ] } ); - is( ref($credit), 'Koha::Account::Line', '->apply returns the updated Koha::Account::Line credit object'); + is( ref($credit), 'Koha::Account::Line', '->apply returns the updated Koha::Account::Line credit object' ); is( $credit->amountoutstanding * -1, 90, 'Remaining credit is correctly calculated' ); # re-read debit info @@ -247,10 +262,10 @@ subtest 'apply() tests' => sub { my $offsets = Koha::Account::Offsets->search( { credit_id => $credit->id, debit_id => $debit_1->id } ); is( $offsets->count, 1, 'Only one offset is generated' ); my $THE_offset = $offsets->next; - is( $THE_offset->amount * 1, -10, 'Amount was calculated correctly (less than the available credit)' ); - is( $THE_offset->type, 'APPLY', 'Passed type stored correctly' ); + is( $THE_offset->amount * 1, -10, 'Amount was calculated correctly (less than the available credit)' ); + is( $THE_offset->type, 'APPLY', 'Passed type stored correctly' ); - $debits = Koha::Account::Lines->search({ accountlines_id => $debit_2->id }); + $debits = Koha::Account::Lines->search( { accountlines_id => $debit_2->id } ); $credit = $credit->apply( { debits => [ $debits->as_list ] } ); is( $credit->amountoutstanding * 1, 0, 'No remaining credit' ); $debit_2->discard_changes; @@ -259,32 +274,30 @@ subtest 'apply() tests' => sub { $offsets = Koha::Account::Offsets->search( { credit_id => $credit->id, debit_id => $debit_2->id } ); is( $offsets->count, 1, 'Only one offset is generated' ); $THE_offset = $offsets->next; - is( $THE_offset->amount * 1, -90, 'Amount was calculated correctly (less than the available credit)' ); - is( $THE_offset->type, 'APPLY', 'Defaults to \'APPLY\' offset type' ); + is( $THE_offset->amount * 1, -90, 'Amount was calculated correctly (less than the available credit)' ); + is( $THE_offset->type, 'APPLY', 'Defaults to \'APPLY\' offset type' ); - $debits = Koha::Account::Lines->search({ accountlines_id => $debit_1->id }); - throws_ok - { $credit->apply({ debits => [ $debits->as_list ] }); } - 'Koha::Exceptions::Account::NoAvailableCredit', + $debits = Koha::Account::Lines->search( { accountlines_id => $debit_1->id } ); + throws_ok { $credit->apply( { debits => [ $debits->as_list ] } ); } + 'Koha::Exceptions::Account::NoAvailableCredit', '->apply() can only be used with outstanding credits'; - $debits = Koha::Account::Lines->search({ accountlines_id => $credit->id }); - throws_ok - { $debit_1->apply({ debits => [ $debits->as_list ] }); } - 'Koha::Exceptions::Account::IsNotCredit', + $debits = Koha::Account::Lines->search( { accountlines_id => $credit->id } ); + throws_ok { $debit_1->apply( { debits => [ $debits->as_list ] } ); } + 'Koha::Exceptions::Account::IsNotCredit', '->apply() can only be used with credits'; - $debits = Koha::Account::Lines->search({ accountlines_id => $credit->id }); - my $credit_3 = $account->add_credit({ amount => 1, interface => 'commandline' }); - throws_ok - { $credit_3->apply({ debits => [ $debits->as_list ] }); } - 'Koha::Exceptions::Account::IsNotDebit', + $debits = Koha::Account::Lines->search( { accountlines_id => $credit->id } ); + my $credit_3 = $account->add_credit( { amount => 1, interface => 'commandline' } ); + throws_ok { $credit_3->apply( { debits => [ $debits->as_list ] } ); } + 'Koha::Exceptions::Account::IsNotDebit', '->apply() can only be applied to credits'; - my $credit_2 = $account->add_credit({ amount => 20, interface => 'commandline' }); + my $credit_2 = $account->add_credit( { amount => 20, interface => 'commandline' } ); my $debit_3 = Koha::Account::Line->new( - { borrowernumber => $patron->id, - debit_type_code => "OVERDUE", + { + borrowernumber => $patron->id, + debit_type_code => "OVERDUE", status => "RETURNED", amount => 100, amountoutstanding => 100, @@ -292,34 +305,36 @@ subtest 'apply() tests' => sub { } )->store; - $debits = Koha::Account::Lines->search({ accountlines_id => { -in => [ $debit_1->id, $debit_2->id, $debit_3->id, $credit->id ] } }); + $debits = Koha::Account::Lines->search( + { accountlines_id => { -in => [ $debit_1->id, $debit_2->id, $debit_3->id, $credit->id ] } } ); throws_ok { - $credit_2->apply( { debits => [ $debits->as_list ] }); } - 'Koha::Exceptions::Account::IsNotDebit', + $credit_2->apply( { debits => [ $debits->as_list ] } ); + } + 'Koha::Exceptions::Account::IsNotDebit', '->apply() rolls back if any of the passed lines is not a debit'; - is( $debit_1->discard_changes->amountoutstanding * 1, 0, 'No changes to already cancelled debit' ); - is( $debit_2->discard_changes->amountoutstanding * 1, 10, 'Debit cancelled' ); - is( $debit_3->discard_changes->amountoutstanding * 1, 100, 'Outstanding amount correctly calculated' ); - is( $credit_2->discard_changes->amountoutstanding * -1, 20, 'No changes made' ); + is( $debit_1->discard_changes->amountoutstanding * 1, 0, 'No changes to already cancelled debit' ); + is( $debit_2->discard_changes->amountoutstanding * 1, 10, 'Debit cancelled' ); + is( $debit_3->discard_changes->amountoutstanding * 1, 100, 'Outstanding amount correctly calculated' ); + is( $credit_2->discard_changes->amountoutstanding * -1, 20, 'No changes made' ); - $debits = Koha::Account::Lines->search({ accountlines_id => { -in => [ $debit_1->id, $debit_2->id, $debit_3->id ] } }); + $debits = + Koha::Account::Lines->search( { accountlines_id => { -in => [ $debit_1->id, $debit_2->id, $debit_3->id ] } } ); $credit_2 = $credit_2->apply( { debits => [ $debits->as_list ] } ); - is( $debit_1->discard_changes->amountoutstanding * 1, 0, 'No changes to already cancelled debit' ); - is( $debit_2->discard_changes->amountoutstanding * 1, 0, 'Debit cancelled' ); + is( $debit_1->discard_changes->amountoutstanding * 1, 0, 'No changes to already cancelled debit' ); + is( $debit_2->discard_changes->amountoutstanding * 1, 0, 'Debit cancelled' ); is( $debit_3->discard_changes->amountoutstanding * 1, 90, 'Outstanding amount correctly calculated' ); - is( $credit_2->amountoutstanding * 1, 0, 'No remaining credit' ); + is( $credit_2->amountoutstanding * 1, 0, 'No remaining credit' ); - my $library = $builder->build_object( { class => 'Koha::Libraries' } ); - my $biblio = $builder->build_sample_biblio(); - my $item = - $builder->build_sample_item( { biblionumber => $biblio->biblionumber } ); - my $now = dt_from_string(); - my $seven_weeks = DateTime::Duration->new(weeks => 7); - my $five_weeks = DateTime::Duration->new(weeks => 5); + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); + my $biblio = $builder->build_sample_biblio(); + my $item = $builder->build_sample_item( { biblionumber => $biblio->biblionumber } ); + my $now = dt_from_string(); + my $seven_weeks = DateTime::Duration->new( weeks => 7 ); + my $five_weeks = DateTime::Duration->new( weeks => 5 ); my $seven_weeks_ago = $now - $seven_weeks; - my $five_weeks_ago = $now - $five_weeks; + my $five_weeks_ago = $now - $five_weeks; my $checkout = Koha::Checkout->new( { @@ -333,15 +348,15 @@ subtest 'apply() tests' => sub { my $accountline = Koha::Account::Line->new( { - issue_id => $checkout->id, - borrowernumber => $patron->id, - itemnumber => $item->id, - branchcode => $library->id, - date => \'NOW()', - debit_type_code => 'OVERDUE', - status => 'UNRETURNED', - interface => 'cli', - amount => '1', + issue_id => $checkout->id, + borrowernumber => $patron->id, + itemnumber => $item->id, + branchcode => $library->id, + date => \'NOW()', + debit_type_code => 'OVERDUE', + status => 'UNRETURNED', + interface => 'cli', + amount => '1', amountoutstanding => '1', } )->store(); @@ -353,8 +368,8 @@ subtest 'apply() tests' => sub { t::lib::Mocks::mock_preference( 'RenewAccruingItemWhenPaid', 1 ); my $called = 0; my $module = Test::MockModule->new('C4::Circulation'); - $module->mock('AddRenewal', sub { $called = 1; }); - $module->mock('CanBookBeRenewed', sub { return 1; }); + $module->mock( 'AddRenewal', sub { $called = 1; } ); + $module->mock( 'CanBookBeRenewed', sub { return 1; } ); my $credit_forgive = $account->add_credit( { amount => 1, @@ -363,42 +378,45 @@ subtest 'apply() tests' => sub { type => 'FORGIVEN' } ); - my $debits_renew = Koha::Account::Lines->search({ accountlines_id => $accountline->id })->as_list; + my $debits_renew = Koha::Account::Lines->search( { accountlines_id => $accountline->id } )->as_list; $credit_forgive = $credit_forgive->apply( { debits => $debits_renew } ); - is( $called, 0, 'C4::Circulation::AddRenew NOT called when RenewAccruingItemWhenPaid enabled but credit type is "FORGIVEN"' ); + is( + $called, 0, + 'C4::Circulation::AddRenew NOT called when RenewAccruingItemWhenPaid enabled but credit type is "FORGIVEN"' + ); $accountline = Koha::Account::Line->new( { - issue_id => $checkout->id, - borrowernumber => $patron->id, - itemnumber => $item->id, - branchcode => $library->id, - date => \'NOW()', - debit_type_code => 'OVERDUE', - status => 'UNRETURNED', - interface => 'cli', - amount => '1', + issue_id => $checkout->id, + borrowernumber => $patron->id, + itemnumber => $item->id, + branchcode => $library->id, + date => \'NOW()', + debit_type_code => 'OVERDUE', + status => 'UNRETURNED', + interface => 'cli', + amount => '1', amountoutstanding => '1', } )->store(); - my $credit_renew = $account->add_credit({ amount => 100, user_id => $patron->id, interface => 'commandline' }); - $debits_renew = Koha::Account::Lines->search({ accountlines_id => $accountline->id })->as_list; + my $credit_renew = $account->add_credit( { amount => 100, user_id => $patron->id, interface => 'commandline' } ); + $debits_renew = Koha::Account::Lines->search( { accountlines_id => $accountline->id } )->as_list; $credit_renew = $credit_renew->apply( { debits => $debits_renew } ); is( $called, 1, 'RenewAccruingItemWhenPaid causes C4::Circulation::AddRenew to be called when appropriate' ); - my @messages = @{$credit_renew->object_messages}; - is( $messages[0]->type, 'info', 'Info message added for renewal' ); - is( $messages[0]->message, 'renewal', 'Message is "renewal"' ); + my @messages = @{ $credit_renew->object_messages }; + is( $messages[0]->type, 'info', 'Info message added for renewal' ); + is( $messages[0]->message, 'renewal', 'Message is "renewal"' ); is( $messages[0]->payload->{itemnumber}, $item->id, 'itemnumber found in payload' ); - is( $messages[0]->payload->{due_date}, 1, 'due_date key in payload' ); - is( $messages[0]->payload->{success}, 1, "'success' key in payload" ); + is( $messages[0]->payload->{due_date}, 1, 'due_date key in payload' ); + is( $messages[0]->payload->{success}, 1, "'success' key in payload" ); - t::lib::Mocks::mock_preference( 'MarkLostItemsAsReturned', 'onpayment'); + t::lib::Mocks::mock_preference( 'MarkLostItemsAsReturned', 'onpayment' ); t::lib::Mocks::mock_userenv( { branchcode => $library->id } ); - my $loser = $builder->build_object( { class => 'Koha::Patrons' } ); + my $loser = $builder->build_object( { class => 'Koha::Patrons' } ); my $loser_account = $loser->account; - my $lost_item = $builder->build_sample_item(); + my $lost_item = $builder->build_sample_item(); my $lost_checkout = Koha::Checkout->new( { borrowernumber => $loser->id, @@ -412,37 +430,38 @@ subtest 'apply() tests' => sub { $lost_item->itemlost(1)->store; my $processing_fee = Koha::Account::Line->new( { - issue_id => $lost_checkout->id, - borrowernumber => $loser->id, - itemnumber => $lost_item->id, - branchcode => $library->id, - date => \'NOW()', - debit_type_code => 'PROCESSING', - status => undef, - interface => 'intranet', - amount => '15', + issue_id => $lost_checkout->id, + borrowernumber => $loser->id, + itemnumber => $lost_item->id, + branchcode => $library->id, + date => \'NOW()', + debit_type_code => 'PROCESSING', + status => undef, + interface => 'intranet', + amount => '15', amountoutstanding => '15', } )->store(); my $lost_fee = Koha::Account::Line->new( { - issue_id => $lost_checkout->id, - borrowernumber => $loser->id, - itemnumber => $lost_item->id, - branchcode => $library->id, - date => \'NOW()', - debit_type_code => 'LOST', - status => undef, - interface => 'intranet', - amount => '12.63', + issue_id => $lost_checkout->id, + borrowernumber => $loser->id, + itemnumber => $lost_item->id, + branchcode => $library->id, + date => \'NOW()', + debit_type_code => 'LOST', + status => undef, + interface => 'intranet', + amount => '12.63', amountoutstanding => '12.63', } )->store(); - my $pay_lost = $loser_account->add_credit({ amount => 27.630000, user_id => $loser->id, interface => 'intranet' }); + my $pay_lost = + $loser_account->add_credit( { amount => 27.630000, user_id => $loser->id, interface => 'intranet' } ); my $pay_lines = [ $processing_fee, $lost_fee ]; $pay_lost->apply( { debits => $pay_lines, offset_type => 'Credit applied' } ); - is( $loser->checkouts->next, undef, "Item has been returned"); + is( $loser->checkouts->next, undef, "Item has been returned" ); $schema->storage->txn_rollback; }; @@ -454,15 +473,15 @@ subtest 'Keep account info when related patron, staff, item, issue or cash_regis $schema->storage->txn_begin; my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); - my $staff = $builder->build_object( { class => 'Koha::Patrons' } ); - my $item = $builder->build_sample_item; - my $issue = $builder->build_object( + my $staff = $builder->build_object( { class => 'Koha::Patrons' } ); + my $item = $builder->build_sample_item; + my $issue = $builder->build_object( { class => 'Koha::Checkouts', value => { itemnumber => $item->itemnumber, borrowernumber => $patron->borrowernumber } } ); - my $register = $builder->build_object({ class => 'Koha::Cash::Registers' }); + my $register = $builder->build_object( { class => 'Koha::Cash::Registers' } ); my $line = Koha::Account::Line->new( { @@ -479,31 +498,31 @@ subtest 'Keep account info when related patron, staff, item, issue or cash_regis } )->store; - MarkIssueReturned($patron->borrowernumber, $item->itemnumber, undef, 0 ); + MarkIssueReturned( $patron->borrowernumber, $item->itemnumber, undef, 0 ); $line = $line->get_from_storage; - is( $line->issue_id, undef, "The account line should not be deleted when the related issue is archived"); - is( $line->old_issue_id, $issue->id, "The account line link to the archived issue"); + is( $line->issue_id, undef, "The account line should not be deleted when the related issue is archived" ); + is( $line->old_issue_id, $issue->id, "The account line link to the archived issue" ); - my $old_issue = Koha::Old::Checkouts->find($issue->id); + my $old_issue = Koha::Old::Checkouts->find( $issue->id ); $old_issue->delete; $line = $line->get_from_storage; - is( $line->old_issue_id, undef, "The account line should not be deleted when the related old_issue is delete"); + is( $line->old_issue_id, undef, "The account line should not be deleted when the related old_issue is delete" ); $item->delete; $line = $line->get_from_storage; - is( $line->itemnumber, undef, "The account line should not be deleted when the related item is delete"); + is( $line->itemnumber, undef, "The account line should not be deleted when the related item is delete" ); $staff->delete; $line = $line->get_from_storage; - is( $line->manager_id, undef, "The account line should not be deleted when the related staff is delete"); + is( $line->manager_id, undef, "The account line should not be deleted when the related staff is delete" ); $patron->delete; $line = $line->get_from_storage; - is( $line->borrowernumber, undef, "The account line should not be deleted when the related patron is delete"); + is( $line->borrowernumber, undef, "The account line should not be deleted when the related patron is delete" ); $register->delete; $line = $line->get_from_storage; - is( $line->register_id, undef, "The account line should not be deleted when the related cash register is delete"); + is( $line->register_id, undef, "The account line should not be deleted when the related cash register is delete" ); $schema->storage->txn_rollback; }; @@ -531,16 +550,17 @@ subtest 'Renewal related tests' => sub { ); my $line = Koha::Account::Line->new( - { - borrowernumber => $patron->borrowernumber, - manager_id => $staff->borrowernumber, - itemnumber => $item->itemnumber, - debit_type_code => "OVERDUE", - status => "UNRETURNED", - amountoutstanding => 0, - amount => 0, - interface => 'commandline', - })->store; + { + borrowernumber => $patron->borrowernumber, + manager_id => $staff->borrowernumber, + itemnumber => $item->itemnumber, + debit_type_code => "OVERDUE", + status => "UNRETURNED", + amountoutstanding => 0, + amount => 0, + interface => 'commandline', + } + )->store; is( $line->is_renewable, 1, "Item is returned as renewable when it meets the conditions" ); $line->amountoutstanding(5); @@ -552,15 +572,14 @@ subtest 'Renewal related tests' => sub { $line->status("RETURNED"); is( $line->is_renewable, 0, "Item is returned as unrenewable when it has the wrong account status" ); - t::lib::Mocks::mock_preference( 'RenewAccruingItemWhenPaid', 0 ); - is ($line->renew_item({ interface => 'intranet' }), undef, 'Attempt to renew fails when syspref is not set'); + is( $line->renew_item( { interface => 'intranet' } ), undef, 'Attempt to renew fails when syspref is not set' ); t::lib::Mocks::mock_preference( 'RenewAccruingItemWhenPaid', 1 ); - t::lib::Mocks::mock_preference( 'RenewAccruingItemInOpac', 0 ); - is ($line->renew_item({ interface => 'opac' }), undef, 'Attempt to renew fails when syspref is not set - OPAC'); + t::lib::Mocks::mock_preference( 'RenewAccruingItemInOpac', 0 ); + is( $line->renew_item( { interface => 'opac' } ), undef, 'Attempt to renew fails when syspref is not set - OPAC' ); t::lib::Mocks::mock_preference( 'RenewAccruingItemInOpac', 1 ); is_deeply( - $line->renew_item({ interface => 'intranet' }), + $line->renew_item( { interface => 'intranet' } ), { itemnumber => $item->itemnumber, error => 'too_many', @@ -582,9 +601,9 @@ subtest 'Renewal related tests' => sub { ); my $called = 0; my $module = Test::MockModule->new('C4::Circulation'); - $module->mock('CanBookBeRenewed', sub { return 1; }); + $module->mock( 'CanBookBeRenewed', sub { return 1; } ); $line->renew_item; - my $r = Koha::Checkouts::Renewals->find({ checkout_id => $issue->id }); + my $r = Koha::Checkouts::Renewals->find( { checkout_id => $issue->id } ); is( $r->seen, 0, "RenewAccruingItemWhenPaid triggers an unseen renewal" ); $schema->storage->txn_rollback; @@ -606,8 +625,9 @@ subtest 'adjust() tests' => sub { my $account = $patron->account; my $debit_1 = Koha::Account::Line->new( - { borrowernumber => $patron->id, - debit_type_code => "OVERDUE", + { + borrowernumber => $patron->id, + debit_type_code => "OVERDUE", status => "RETURNED", amount => 10, amountoutstanding => 10, @@ -616,8 +636,9 @@ subtest 'adjust() tests' => sub { )->store; my $debit_2 = Koha::Account::Line->new( - { borrowernumber => $patron->id, - debit_type_code => "OVERDUE", + { + borrowernumber => $patron->id, + debit_type_code => "OVERDUE", status => "UNRETURNED", amount => 100, amountoutstanding => 100, @@ -632,29 +653,29 @@ subtest 'adjust() tests' => sub { throws_ok { $debit_1->adjust( { amount => 50, type => 'overdue_update', interface => 'commandline' } ) } qr/Update type not allowed on this debit_type/, - 'Exception thrown for type conflict'; + 'Exception thrown for type conflict'; # Increment an unpaid fine $debit_2->adjust( { amount => 150, type => 'overdue_update', interface => 'commandline' } )->discard_changes; - is( $debit_2->amount * 1, 150, 'Fine amount was updated in full' ); + is( $debit_2->amount * 1, 150, 'Fine amount was updated in full' ); is( $debit_2->amountoutstanding * 1, 150, 'Fine amountoutstanding was update in full' ); isnt( $debit_2->date, undef, 'Date has been set' ); my $offsets = Koha::Account::Offsets->search( { debit_id => $debit_2->id } ); is( $offsets->count, 1, 'An offset is generated for the increment' ); my $THIS_offset = $offsets->next; - is( $THIS_offset->amount * 1, 50, 'Amount was calculated correctly (increment by 50)' ); - is( $THIS_offset->type, 'OVERDUE_INCREASE', 'Adjust type stored correctly' ); + is( $THIS_offset->amount * 1, 50, 'Amount was calculated correctly (increment by 50)' ); + is( $THIS_offset->type, 'OVERDUE_INCREASE', 'Adjust type stored correctly' ); is( $schema->resultset('ActionLog')->count(), $action_logs + 0, 'No log was added' ); # Update fine to partially paid - my $debits = Koha::Account::Lines->search({ accountlines_id => $debit_2->id }); + my $debits = Koha::Account::Lines->search( { accountlines_id => $debit_2->id } ); $credit->apply( { debits => [ $debits->as_list ] } ); $debit_2->discard_changes; - is( $debit_2->amount * 1, 150, 'Fine amount unaffected by partial payment' ); + is( $debit_2->amount * 1, 150, 'Fine amount unaffected by partial payment' ); is( $debit_2->amountoutstanding * 1, 110, 'Fine amountoutstanding updated by partial payment' ); # Enable logs @@ -663,42 +684,42 @@ subtest 'adjust() tests' => sub { # Increment the partially paid fine $debit_2->adjust( { amount => 160, type => 'overdue_update', interface => 'commandline' } )->discard_changes; - is( $debit_2->amount * 1, 160, 'Fine amount was updated in full' ); + is( $debit_2->amount * 1, 160, 'Fine amount was updated in full' ); is( $debit_2->amountoutstanding * 1, 120, 'Fine amountoutstanding was updated by difference' ); $offsets = Koha::Account::Offsets->search( { debit_id => $debit_2->id } ); is( $offsets->count, 3, 'An offset is generated for the increment' ); $THIS_offset = $offsets->last; - is( $THIS_offset->amount * 1, 10, 'Amount was calculated correctly (increment by 10)' ); - is( $THIS_offset->type, 'OVERDUE_INCREASE', 'Adjust type stored correctly' ); + is( $THIS_offset->amount * 1, 10, 'Amount was calculated correctly (increment by 10)' ); + is( $THIS_offset->type, 'OVERDUE_INCREASE', 'Adjust type stored correctly' ); is( $schema->resultset('ActionLog')->count(), $action_logs + 1, 'Log was added' ); # Decrement the partially paid fine, less than what was paid $debit_2->adjust( { amount => 50, type => 'overdue_update', interface => 'commandline' } )->discard_changes; - is( $debit_2->amount * 1, 50, 'Fine amount was updated in full' ); + is( $debit_2->amount * 1, 50, 'Fine amount was updated in full' ); is( $debit_2->amountoutstanding * 1, 10, 'Fine amountoutstanding was updated by difference' ); $offsets = Koha::Account::Offsets->search( { debit_id => $debit_2->id } ); is( $offsets->count, 4, 'An offset is generated for the decrement' ); $THIS_offset = $offsets->last; - is( $THIS_offset->amount * 1, -110, 'Amount was calculated correctly (decrement by 110)' ); - is( $THIS_offset->type, 'OVERDUE_DECREASE', 'Adjust type stored correctly' ); + is( $THIS_offset->amount * 1, -110, 'Amount was calculated correctly (decrement by 110)' ); + is( $THIS_offset->type, 'OVERDUE_DECREASE', 'Adjust type stored correctly' ); # Decrement the partially paid fine, more than what was paid $debit_2->adjust( { amount => 30, type => 'overdue_update', interface => 'commandline' } )->discard_changes; - is( $debit_2->amount * 1, 30, 'Fine amount was updated in full' ); - is( $debit_2->amountoutstanding * 1, 0, 'Fine amountoutstanding was zeroed (payment was 40)' ); + is( $debit_2->amount * 1, 30, 'Fine amount was updated in full' ); + is( $debit_2->amountoutstanding * 1, 0, 'Fine amountoutstanding was zeroed (payment was 40)' ); $offsets = Koha::Account::Offsets->search( { debit_id => $debit_2->id } ); is( $offsets->count, 5, 'An offset is generated for the decrement' ); $THIS_offset = $offsets->last; - is( $THIS_offset->amount * 1, -20, 'Amount was calculated correctly (decrement by 20)' ); - is( $THIS_offset->type, 'OVERDUE_DECREASE', 'Adjust type stored correctly' ); + is( $THIS_offset->amount * 1, -20, 'Amount was calculated correctly (decrement by 20)' ); + is( $THIS_offset->type, 'OVERDUE_DECREASE', 'Adjust type stored correctly' ); my $overpayment_refund = $account->lines->last; - is( $overpayment_refund->amount * 1, -10, 'A new credit has been added' ); + is( $overpayment_refund->amount * 1, -10, 'A new credit has been added' ); is( $overpayment_refund->credit_type_code, 'OVERPAYMENT', 'Credit generated with the expected credit_type_code' ); $schema->storage->txn_rollback; @@ -710,11 +731,11 @@ subtest 'checkout() tests' => sub { $schema->storage->txn_begin; my $library = $builder->build_object( { class => 'Koha::Libraries' } ); - my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); - my $item = $builder->build_sample_item; + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + my $item = $builder->build_sample_item; my $account = $patron->account; - t::lib::Mocks::mock_userenv({ branchcode => $library->branchcode }); + t::lib::Mocks::mock_userenv( { branchcode => $library->branchcode } ); my $checkout = AddIssue( $patron, $item->barcode ); my $line = $account->add_debit( @@ -731,29 +752,36 @@ subtest 'checkout() tests' => sub { my $line_checkout = $line->checkout; is( ref($line_checkout), 'Koha::Checkout', 'Result type is correct' ); - is( $line_checkout->issue_id, $checkout->issue_id, 'Koha::Account::Line->checkout should return the correct checkout'); + is( + $line_checkout->issue_id, $checkout->issue_id, + 'Koha::Account::Line->checkout should return the correct checkout' + ); # Prevent re-calculation of fines at check-in for the test; Since bug 8338 the recalculation would result in a '0' # fine which would subsequently be removed by _FixOverduesOnReturn t::lib::Mocks::mock_preference( 'finesMode', 'off' ); - my ( $returned, undef, $old_checkout) = C4::Circulation::AddReturn( $item->barcode, $library->branchcode ); + my ( $returned, undef, $old_checkout ) = C4::Circulation::AddReturn( $item->barcode, $library->branchcode ); is( $returned, 1, 'The item should have been returned' ); $line = $line->get_from_storage; my $old_line_checkout = $line->checkout; is( ref($old_line_checkout), 'Koha::Old::Checkout', 'Result type is correct' ); - is( $old_line_checkout->issue_id, $old_checkout->issue_id, 'Koha::Account::Line->checkout should return the correct old_checkout' ); + is( + $old_line_checkout->issue_id, $old_checkout->issue_id, + 'Koha::Account::Line->checkout should return the correct old_checkout' + ); $old_line_checkout->delete; - $line->discard_changes; #NOTE: discard_changes refreshes the whole resultset, get_from_storage only refreshes the unjoined row + $line->discard_changes + ; #NOTE: discard_changes refreshes the whole resultset, get_from_storage only refreshes the unjoined row is( $line->checkout, undef, 'Koha::Account::Line->checkout should return undef if no checkout linked' ); $line->old_issue_id(undef)->store; - $line->discard_changes; #NOTE: discard_changes refreshes the whole resultset, get_from_storage only refreshes the unjoined row + $line->discard_changes + ; #NOTE: discard_changes refreshes the whole resultset, get_from_storage only refreshes the unjoined row is( $line->checkout, undef, 'Koha::Account::Line->checkout should return undef if no checkout linked' ); - $schema->storage->txn_rollback; }; @@ -762,68 +790,73 @@ subtest 'credits() and debits() tests' => sub { $schema->storage->txn_begin; - my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $account = $patron->account; - my $debit1 = $account->add_debit({ - amount => 8, - interface => 'commandline', - type => 'ACCOUNT', - }); - my $debit2 = $account->add_debit({ - amount => 12, - interface => 'commandline', - type => 'ACCOUNT', - }); - my $credit1 = $account->add_credit({ - amount => 5, - interface => 'commandline', - type => 'CREDIT', - }); - my $credit2 = $account->add_credit({ - amount => 10, - interface => 'commandline', - type => 'CREDIT', - }); + my $debit1 = $account->add_debit( + { + amount => 8, + interface => 'commandline', + type => 'ACCOUNT', + } + ); + my $debit2 = $account->add_debit( + { + amount => 12, + interface => 'commandline', + type => 'ACCOUNT', + } + ); + my $credit1 = $account->add_credit( + { + amount => 5, + interface => 'commandline', + type => 'CREDIT', + } + ); + my $credit2 = $account->add_credit( + { + amount => 10, + interface => 'commandline', + type => 'CREDIT', + } + ); - $credit1->apply({ debits => [ $debit1 ] }); - $credit2->apply({ debits => [ $debit1, $debit2 ] }); + $credit1->apply( { debits => [$debit1] } ); + $credit2->apply( { debits => [ $debit1, $debit2 ] } ); my $credits = $debit1->credits; - is($credits->count, 2, '2 Credits applied to debit 1'); + is( $credits->count, 2, '2 Credits applied to debit 1' ); my $credit = $credits->next; - is($credit->amount + 0, -5, 'Correct first credit'); + is( $credit->amount + 0, -5, 'Correct first credit' ); $credit = $credits->next; - is($credit->amount + 0, -10, 'Correct second credit'); + is( $credit->amount + 0, -10, 'Correct second credit' ); $credits = $debit2->credits; - is($credits->count, 1, '1 Credits applied to debit 2'); + is( $credits->count, 1, '1 Credits applied to debit 2' ); $credit = $credits->next; - is($credit->amount + 0, -10, 'Correct first credit'); + is( $credit->amount + 0, -10, 'Correct first credit' ); my $debits = $credit1->debits; - is($debits->count, 1, 'Credit 1 applied to 1 debit'); + is( $debits->count, 1, 'Credit 1 applied to 1 debit' ); my $debit = $debits->next; - is($debit->amount + 0, 8, 'Correct first debit'); + is( $debit->amount + 0, 8, 'Correct first debit' ); $debits = $credit2->debits; - is($debits->count, 2, 'Credit 2 applied to 2 debits'); + is( $debits->count, 2, 'Credit 2 applied to 2 debits' ); $debit = $debits->next; - is($debit->amount + 0, 8, 'Correct first debit'); + is( $debit->amount + 0, 8, 'Correct first debit' ); $debit = $debits->next; - is($debit->amount + 0, 12, 'Correct second debit'); + is( $debit->amount + 0, 12, 'Correct second debit' ); - throws_ok - { $debit1->debits; } - 'Koha::Exceptions::Account::IsNotCredit', + throws_ok { $debit1->debits; } + 'Koha::Exceptions::Account::IsNotCredit', 'Exception is thrown when requesting debits linked to debit'; - throws_ok - { $credit1->credits; } - 'Koha::Exceptions::Account::IsNotDebit', + throws_ok { $credit1->credits; } + 'Koha::Exceptions::Account::IsNotDebit', 'Exception is thrown when requesting credits linked to credit'; - $schema->storage->txn_rollback; }; @@ -834,26 +867,26 @@ subtest "void() tests" => sub { $schema->storage->txn_begin; # Create a borrower - my $categorycode = $builder->build({ source => 'Category' })->{ categorycode }; - my $branchcode = $builder->build({ source => 'Branch' })->{ branchcode }; + my $categorycode = $builder->build( { source => 'Category' } )->{categorycode}; + my $branchcode = $builder->build( { source => 'Branch' } )->{branchcode}; - my $staff = $builder->build_object({ class => 'Koha::Patrons' }); - t::lib::Mocks::mock_userenv({ patron => $staff }); + my $staff = $builder->build_object( { class => 'Koha::Patrons' } ); + t::lib::Mocks::mock_userenv( { patron => $staff } ); my $borrower = $builder->build_object( { class => 'Koha::Patrons', value => { - cardnumber => 'dariahall', - surname => 'Hall', - firstname => 'Daria', + cardnumber => 'dariahall', + surname => 'Hall', + firstname => 'Daria', categorycode => $categorycode, - branchcode => $branchcode, + branchcode => $branchcode, } } ); - my $account = Koha::Account->new({ patron_id => $borrower->id }); + my $account = Koha::Account->new( { patron_id => $borrower->id } ); my $line1 = Koha::Account::Line->new( { @@ -874,68 +907,68 @@ subtest "void() tests" => sub { } )->store(); - is( $account->balance(), 30, "Account balance is 30" ); + is( $account->balance(), 30, "Account balance is 30" ); is( $line1->amountoutstanding, 10, 'First fee has amount outstanding of 10' ); is( $line2->amountoutstanding, 20, 'Second fee has amount outstanding of 20' ); my $id = $account->pay( { - lines => [$line1, $line2], + lines => [ $line1, $line2 ], amount => 30, } )->{payment_id}; - my $account_payment = Koha::Account::Lines->find( $id ); + my $account_payment = Koha::Account::Lines->find($id); is( $account->balance(), 0, "Account balance is 0" ); $line1->_result->discard_changes(); $line2->_result->discard_changes(); - is( $line1->amountoutstanding+0, 0, 'First fee has amount outstanding of 0' ); - is( $line2->amountoutstanding+0, 0, 'Second fee has amount outstanding of 0' ); + is( $line1->amountoutstanding + 0, 0, 'First fee has amount outstanding of 0' ); + is( $line2->amountoutstanding + 0, 0, 'Second fee has amount outstanding of 0' ); throws_ok { $line1->void( { interface => 'test' } ); } 'Koha::Exceptions::Account::IsNotCredit', - '->void() can only be used with credits'; + '->void() can only be used with credits'; throws_ok { $account_payment->void(); } 'Koha::Exceptions::MissingParameter', - "->void() requires the `interface` parameter is passed"; + "->void() requires the `interface` parameter is passed"; throws_ok { $account_payment->void( { interface => 'intranet' } ); } 'Koha::Exceptions::MissingParameter', - "->void() requires the `staff_id` parameter is passed when `interface` equals 'intranet'"; + "->void() requires the `staff_id` parameter is passed when `interface` equals 'intranet'"; throws_ok { $account_payment->void( { interface => 'intranet', staff_id => $borrower->borrowernumber } ); } 'Koha::Exceptions::MissingParameter', - "->void() requires the `branch` parameter is passed when `interface` equals 'intranet'"; + "->void() requires the `branch` parameter is passed when `interface` equals 'intranet'"; - my $void = $account_payment->void({ interface => 'test' }); + my $void = $account_payment->void( { interface => 'test' } ); - is( ref($void), 'Koha::Account::Line', 'Void returns the account line' ); - is( $void->debit_type_code, 'VOID', 'Void returns the VOID account line' ); - is( $void->manager_id, undef, 'Void proceeds without manager_id OK if interface is not "intranet"' ); - is( $void->branchcode, undef, 'Void proceeds without branchcode OK if interface is not "intranet"' ); - is( $account->balance(), 30, "Account balance is again 30" ); + is( ref($void), 'Koha::Account::Line', 'Void returns the account line' ); + is( $void->debit_type_code, 'VOID', 'Void returns the VOID account line' ); + is( $void->manager_id, undef, 'Void proceeds without manager_id OK if interface is not "intranet"' ); + is( $void->branchcode, undef, 'Void proceeds without branchcode OK if interface is not "intranet"' ); + is( $account->balance(), 30, "Account balance is again 30" ); $account_payment->_result->discard_changes(); $line1->_result->discard_changes(); $line2->_result->discard_changes(); - is( $account_payment->credit_type_code, 'PAYMENT', 'Voided payment credit_type_code is still PAYMENT' ); - is( $account_payment->status, 'VOID', 'Voided payment status is VOID' ); - is( $account_payment->amount+0, -30, 'Voided payment amount is still -30' ); - is( $account_payment->amountoutstanding+0, 0, 'Voided payment amount outstanding is 0' ); + is( $account_payment->credit_type_code, 'PAYMENT', 'Voided payment credit_type_code is still PAYMENT' ); + is( $account_payment->status, 'VOID', 'Voided payment status is VOID' ); + is( $account_payment->amount + 0, -30, 'Voided payment amount is still -30' ); + is( $account_payment->amountoutstanding + 0, 0, 'Voided payment amount outstanding is 0' ); - is( $line1->amountoutstanding+0, 10, 'First fee again has amount outstanding of 10' ); - is( $line2->amountoutstanding+0, 20, 'Second fee again has amount outstanding of 20' ); + is( $line1->amountoutstanding + 0, 10, 'First fee again has amount outstanding of 10' ); + is( $line2->amountoutstanding + 0, 20, 'Second fee again has amount outstanding of 20' ); my $credit2 = $account->add_credit( { interface => 'test', amount => 10 } ); $void = $credit2->void( @@ -945,8 +978,8 @@ subtest "void() tests" => sub { branch => $branchcode } ); - is( $void->manager_id, $borrower->borrowernumber, "->void stores the manager_id when it's passed"); - is( $void->branchcode, $branchcode, "->void stores the branchcode when it's passed"); + is( $void->manager_id, $borrower->borrowernumber, "->void stores the manager_id when it's passed" ); + is( $void->branchcode, $branchcode, "->void stores the branchcode when it's passed" ); $schema->storage->txn_rollback; }; @@ -959,7 +992,7 @@ subtest "payout() tests" => sub { # Create a borrower my $categorycode = - $builder->build( { source => 'Category' } )->{categorycode}; + $builder->build( { source => 'Category' } )->{categorycode}; my $branchcode = $builder->build( { source => 'Branch' } )->{branchcode}; my $borrower = Koha::Patron->new( @@ -1006,10 +1039,14 @@ subtest "payout() tests" => sub { )->store(); is( $account->balance(), -10, "Account balance is -10" ); - is( $debit1->amountoutstanding + 0, - 10, 'Overdue fee has an amount outstanding of 10' ); - is( $credit1->amountoutstanding + 0, - -20, 'Credit has an amount outstanding of -20' ); + is( + $debit1->amountoutstanding + 0, + 10, 'Overdue fee has an amount outstanding of 10' + ); + is( + $credit1->amountoutstanding + 0, + -20, 'Credit has an amount outstanding of -20' + ); my $pay_params = { interface => 'intranet', @@ -1021,10 +1058,9 @@ subtest "payout() tests" => sub { throws_ok { $debit1->payout($pay_params); } 'Koha::Exceptions::Account::IsNotCredit', - '->payout() can only be used with credits'; + '->payout() can only be used with credits'; - my @required = - ( 'interface', 'staff_id', 'branch', 'payout_type', 'amount' ); + my @required = ( 'interface', 'staff_id', 'branch', 'payout_type', 'amount' ); for my $required (@required) { my $params = {%$pay_params}; delete( $params->{$required} ); @@ -1032,7 +1068,7 @@ subtest "payout() tests" => sub { $credit1->payout($params); } 'Koha::Exceptions::MissingParameter', - "->payout() requires the `$required` parameter is passed"; + "->payout() requires the `$required` parameter is passed"; } throws_ok { @@ -1047,7 +1083,7 @@ subtest "payout() tests" => sub { ); } 'Koha::Exceptions::ParameterTooHigh', - '->payout() cannot pay out more than the amountoutstanding'; + '->payout() cannot pay out more than the amountoutstanding'; t::lib::Mocks::mock_preference( 'UseCashRegisters', 1 ); throws_ok { @@ -1062,7 +1098,7 @@ subtest "payout() tests" => sub { ); } 'Koha::Exceptions::Account::RegisterRequired', - '->payout() requires a cash_register if payout_type is `CASH`'; + '->payout() requires a cash_register if payout_type is `CASH`'; t::lib::Mocks::mock_preference( 'UseCashRegisters', 0 ); my $payout = $credit1->payout( @@ -1075,15 +1111,21 @@ subtest "payout() tests" => sub { } ); - is( ref($payout), 'Koha::Account::Line', - '->payout() returns a Koha::Account::Line' ); + is( + ref($payout), 'Koha::Account::Line', + '->payout() returns a Koha::Account::Line' + ); is( $payout->amount() + 0, 10, "Payout amount is 10" ); is( $payout->amountoutstanding() + 0, 0, "Payout amountoutstanding is 0" ); is( $account->balance() + 0, 0, "Account balance is 0" ); - is( $debit1->amountoutstanding + 0, - 10, 'Overdue fee still has an amount outstanding of 10' ); - is( $credit1->amountoutstanding + 0, - -10, 'Credit has an new amount outstanding of -10' ); + is( + $debit1->amountoutstanding + 0, + 10, 'Overdue fee still has an amount outstanding of 10' + ); + is( + $credit1->amountoutstanding + 0, + -10, 'Credit has an new amount outstanding of -10' + ); is( $credit1->status(), 'PAID', "Credit has a new status of PAID" ); $schema->storage->txn_rollback; @@ -1097,7 +1139,7 @@ subtest "reduce() tests" => sub { # Create a borrower my $categorycode = - $builder->build( { source => 'Category' } )->{categorycode}; + $builder->build( { source => 'Category' } )->{categorycode}; my $branchcode = $builder->build( { source => 'Branch' } )->{branchcode}; my $borrower = Koha::Patron->new( @@ -1144,10 +1186,14 @@ subtest "reduce() tests" => sub { )->store(); is( $account->balance(), 0, "Account balance is 0" ); - is( $debit1->amountoutstanding, - 20, 'Overdue fee has an amount outstanding of 20' ); - is( $credit1->amountoutstanding, - -20, 'Credit has an amount outstanding of -20' ); + is( + $debit1->amountoutstanding, + 20, 'Overdue fee has an amount outstanding of 20' + ); + is( + $credit1->amountoutstanding, + -20, 'Credit has an amount outstanding of -20' + ); my $reduce_params = { interface => 'commandline', @@ -1159,7 +1205,7 @@ subtest "reduce() tests" => sub { throws_ok { $credit1->reduce($reduce_params); } 'Koha::Exceptions::Account::IsNotDebit', - '->reduce() can only be used with debits'; + '->reduce() can only be used with debits'; my @required = ( 'interface', 'reduction_type', 'amount' ); for my $required (@required) { @@ -1169,7 +1215,7 @@ subtest "reduce() tests" => sub { $debit1->reduce($params); } 'Koha::Exceptions::MissingParameter', - "->reduce() requires the `$required` parameter is passed"; + "->reduce() requires the `$required` parameter is passed"; } $reduce_params->{interface} = 'intranet'; @@ -1181,7 +1227,7 @@ subtest "reduce() tests" => sub { $debit1->reduce($params); } 'Koha::Exceptions::MissingParameter', -"->reduce() requires the `$d` parameter is passed when interface is intranet"; + "->reduce() requires the `$d` parameter is passed when interface is intranet"; } throws_ok { @@ -1196,58 +1242,72 @@ subtest "reduce() tests" => sub { ); } 'Koha::Exceptions::ParameterTooHigh', - '->reduce() cannot reduce more than original amount'; + '->reduce() cannot reduce more than original amount'; # Partial Reduction # (Discount 5 on debt of 20) my $reduction = $debit1->reduce($reduce_params); - is( ref($reduction), 'Koha::Account::Line', - '->reduce() returns a Koha::Account::Line' ); + is( + ref($reduction), 'Koha::Account::Line', + '->reduce() returns a Koha::Account::Line' + ); is( $reduction->amount() * 1, -5, "Reduce amount is -5" ); - is( $reduction->amountoutstanding() * 1, - 0, "Reduce amountoutstanding is 0" ); - is( $debit1->amountoutstanding() * 1, - 15, "Debit amountoutstanding reduced by 5 to 15" ); - is( $debit1->status(), 'DISCOUNTED', "Debit status updated to DISCOUNTED"); - is( $account->balance() * 1, -5, "Account balance is -5" ); - is( $reduction->status(), 'APPLIED', "Reduction status is 'APPLIED'" ); + is( + $reduction->amountoutstanding() * 1, + 0, "Reduce amountoutstanding is 0" + ); + is( + $debit1->amountoutstanding() * 1, + 15, "Debit amountoutstanding reduced by 5 to 15" + ); + is( $debit1->status(), 'DISCOUNTED', "Debit status updated to DISCOUNTED" ); + is( $account->balance() * 1, -5, "Account balance is -5" ); + is( $reduction->status(), 'APPLIED', "Reduction status is 'APPLIED'" ); - my $offsets = Koha::Account::Offsets->search( - { credit_id => $reduction->id } ); + my $offsets = Koha::Account::Offsets->search( { credit_id => $reduction->id } ); is( $offsets->count, 2, 'Two offsets generated' ); my $THE_offset = $offsets->next; - is( $THE_offset->type, 'CREATE', 'CREATE offset added for discount line'); - is( $THE_offset->amount * 1, - -5, 'Correct offset amount recorded'); + is( $THE_offset->type, 'CREATE', 'CREATE offset added for discount line' ); + is( + $THE_offset->amount * 1, + -5, 'Correct offset amount recorded' + ); $THE_offset = $offsets->next; - is( $THE_offset->type, 'APPLY', "APPLY offset added for 'DISCOUNT'" ); - is( $THE_offset->amount * 1, -5, 'Correct amount offset against debt'); - is( $THE_offset->debit_id, $debit1->accountlines_id, 'APPLY offset recorded the correct debit_id'); + is( $THE_offset->type, 'APPLY', "APPLY offset added for 'DISCOUNT'" ); + is( $THE_offset->amount * 1, -5, 'Correct amount offset against debt' ); + is( $THE_offset->debit_id, $debit1->accountlines_id, 'APPLY offset recorded the correct debit_id' ); # Zero offset created when zero outstanding # (Refund another 5 on paid debt of 20) $credit1->apply( { debits => [$debit1] } ); - is( $debit1->amountoutstanding + 0, - 0, 'Debit1 amountoutstanding reduced to 0' ); + is( + $debit1->amountoutstanding + 0, + 0, 'Debit1 amountoutstanding reduced to 0' + ); $reduce_params->{reduction_type} = 'REFUND'; $reduction = $debit1->reduce($reduce_params); is( $reduction->amount() * 1, -5, "Reduce amount is -5" ); - is( $reduction->amountoutstanding() * 1, - -5, "Reduce amountoutstanding is -5" ); - is( $debit1->status(), 'REFUNDED', "Debit status updated to REFUNDED"); + is( + $reduction->amountoutstanding() * 1, + -5, "Reduce amountoutstanding is -5" + ); + is( $debit1->status(), 'REFUNDED', "Debit status updated to REFUNDED" ); - $offsets = Koha::Account::Offsets->search( - { credit_id => $reduction->id } ); + $offsets = Koha::Account::Offsets->search( { credit_id => $reduction->id } ); is( $offsets->count, 2, 'Two offsets generated' ); $THE_offset = $offsets->next; - is( $THE_offset->type, 'CREATE', 'CREATE offset added for refund line'); - is( $THE_offset->amount * 1, - -5, 'Correct offset amount recorded'); + is( $THE_offset->type, 'CREATE', 'CREATE offset added for refund line' ); + is( + $THE_offset->amount * 1, + -5, 'Correct offset amount recorded' + ); $THE_offset = $offsets->next; is( $THE_offset->type, 'APPLY', "APPLY offset added for 'REFUND'" ); - is( $THE_offset->amount * 1, - 0, 'Zero offset created for already paid off debit' ); + is( + $THE_offset->amount * 1, + 0, 'Zero offset created for already paid off debit' + ); # Compound reduction should not allow more than original amount # (Reduction of 5 + 5 + 20 > 20) @@ -1256,7 +1316,7 @@ subtest "reduce() tests" => sub { $debit1->reduce($reduce_params); } 'Koha::Exceptions::ParameterTooHigh', -'->reduce cannot reduce more than the original amount (combined reductions test)'; + '->reduce cannot reduce more than the original amount (combined reductions test)'; # Throw exception if attempting to reduce a payout my $payout = $reduction->payout( @@ -1272,7 +1332,7 @@ subtest "reduce() tests" => sub { $payout->reduce($reduce_params); } 'Koha::Exceptions::Account::IsNotDebit', - '->reduce() cannot be used on a payout debit'; + '->reduce() cannot be used on a payout debit'; # Throw exception if attempting to reduce a voided debt my $payment = Koha::Account::Line->new( @@ -1286,16 +1346,16 @@ subtest "reduce() tests" => sub { )->store(); my $void = $payment->void( { - interface => 'intranet', - staff_id => $staff->borrowernumber, - branch => $branchcode, + interface => 'intranet', + staff_id => $staff->borrowernumber, + branch => $branchcode, } ); throws_ok { $void->reduce($reduce_params); } 'Koha::Exceptions::Account::IsNotDebit', - '->reduce() cannot be used on a void debit'; + '->reduce() cannot be used on a void debit'; $schema->storage->txn_rollback; }; @@ -1305,11 +1365,12 @@ subtest "cancel() tests" => sub { $schema->storage->txn_begin; - my $library = $builder->build_object( { class => 'Koha::Libraries' }); - my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { branchcode => $library->branchcode } }); - my $staff = $builder->build_object({ class => 'Koha::Patrons', value => { branchcode => $library->branchcode } }); + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); + my $patron = + $builder->build_object( { class => 'Koha::Patrons', value => { branchcode => $library->branchcode } } ); + my $staff = $builder->build_object( { class => 'Koha::Patrons', value => { branchcode => $library->branchcode } } ); - t::lib::Mocks::mock_userenv({ patron => $patron }); + t::lib::Mocks::mock_userenv( { patron => $patron } ); my $account = Koha::Account->new( { patron_id => $patron->borrowernumber } ); @@ -1338,64 +1399,72 @@ subtest "cancel() tests" => sub { amount => 5, } ); - my $credit = Koha::Account::Lines->find({ accountlines_id => $ret->{payment_id} }); + my $credit = Koha::Account::Lines->find( { accountlines_id => $ret->{payment_id} } ); is( $account->balance(), 25, "Account balance is 25" ); - is( $debit1->amountoutstanding + 0, - 10, 'First fee has amount outstanding of 10' ); - is( $debit2->amountoutstanding + 0, - 15, 'Second fee has amount outstanding of 15' ); + is( + $debit1->amountoutstanding + 0, + 10, 'First fee has amount outstanding of 10' + ); + is( + $debit2->amountoutstanding + 0, + 15, 'Second fee has amount outstanding of 15' + ); throws_ok { - $credit->cancel( - { staff_id => $staff->borrowernumber, branch => $library->branchcode } ); + $credit->cancel( { staff_id => $staff->borrowernumber, branch => $library->branchcode } ); } 'Koha::Exceptions::Account::IsNotDebit', - '->cancel() can only be used with debits'; + '->cancel() can only be used with debits'; throws_ok { $debit1->reduce( { staff_id => $staff->borrowernumber } ); } 'Koha::Exceptions::MissingParameter', - "->cancel() requires the `branch` parameter is passed"; + "->cancel() requires the `branch` parameter is passed"; throws_ok { $debit1->reduce( { branch => $library->branchcode } ); } 'Koha::Exceptions::MissingParameter', - "->cancel() requires the `staff_id` parameter is passed"; + "->cancel() requires the `staff_id` parameter is passed"; throws_ok { - $debit2->cancel( - { staff_id => $staff->borrowernumber, branch => $library->branchcode } ); + $debit2->cancel( { staff_id => $staff->borrowernumber, branch => $library->branchcode } ); } 'Koha::Exceptions::Account', - '->cancel() can only be used with debits that have not been offset'; + '->cancel() can only be used with debits that have not been offset'; - my $cancellation = $debit1->cancel( - { staff_id => $staff->borrowernumber, branch => $library->branchcode } ); - is( ref($cancellation), 'Koha::Account::Line', - 'Cancel returns an account line' ); + my $cancellation = $debit1->cancel( { staff_id => $staff->borrowernumber, branch => $library->branchcode } ); + is( + ref($cancellation), 'Koha::Account::Line', + 'Cancel returns an account line' + ); is( $cancellation->amount() * 1, $debit1->amount * -1, "Cancellation amount is " . $debit1->amount ); - is( $cancellation->amountoutstanding() * 1, - 0, "Cancellation amountoutstanding is 0" ); - is( $debit1->amountoutstanding() * 1, - 0, "Debit amountoutstanding reduced to 0" ); - is( $debit1->status(), 'CANCELLED', "Debit status updated to CANCELLED" ); - is( $account->balance() * 1, 15, "Account balance is 15" ); + is( + $cancellation->amountoutstanding() * 1, + 0, "Cancellation amountoutstanding is 0" + ); + is( + $debit1->amountoutstanding() * 1, + 0, "Debit amountoutstanding reduced to 0" + ); + is( $debit1->status(), 'CANCELLED', "Debit status updated to CANCELLED" ); + is( $account->balance() * 1, 15, "Account balance is 15" ); - my $offsets = Koha::Account::Offsets->search( - { credit_id => $cancellation->id } ); + my $offsets = Koha::Account::Offsets->search( { credit_id => $cancellation->id } ); is( $offsets->count, 2, 'Two offsets are generated' ); my $THE_offset = $offsets->next; - is( $THE_offset->type, 'CREATE', 'CREATE offset added for cancel line'); - is( $THE_offset->amount * 1, -10, 'Correct offset amount recorded' ); + is( $THE_offset->type, 'CREATE', 'CREATE offset added for cancel line' ); + is( $THE_offset->amount * 1, -10, 'Correct offset amount recorded' ); $THE_offset = $offsets->next; is( $THE_offset->type, 'APPLY', "APPLY offset added" ); - is( $THE_offset->amount * 1, - -10, 'Correct amount was applied against debit' ); + is( + $THE_offset->amount * 1, + -10, 'Correct amount was applied against debit' + ); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/Koha/Account/Lines.t b/t/db_dependent/Koha/Account/Lines.t index 039fb809f0..8267874a85 100755 --- a/t/db_dependent/Koha/Account/Lines.t +++ b/t/db_dependent/Koha/Account/Lines.t @@ -32,7 +32,7 @@ use Koha::Account::Offsets; use t::lib::Mocks; use t::lib::TestBuilder; -my $schema = Koha::Database->new->schema; +my $schema = Koha::Database->new->schema; my $builder = t::lib::TestBuilder->new; subtest 'total_outstanding() tests' => sub { @@ -41,13 +41,14 @@ subtest 'total_outstanding() tests' => sub { $schema->storage->txn_begin; - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); - my $lines = Koha::Account::Lines->search({ borrowernumber => $patron->id }); + my $lines = Koha::Account::Lines->search( { borrowernumber => $patron->id } ); is( $lines->total_outstanding, 0, 'total_outstanding returns 0 if no lines (undef case)' ); my $debit_1 = Koha::Account::Line->new( - { borrowernumber => $patron->id, + { + borrowernumber => $patron->id, debit_type_code => "OVERDUE", status => "RETURNED", amount => 10, @@ -57,7 +58,8 @@ subtest 'total_outstanding() tests' => sub { )->store; my $debit_2 = Koha::Account::Line->new( - { borrowernumber => $patron->id, + { + borrowernumber => $patron->id, debit_type_code => "OVERDUE", status => "RETURNED", amount => 10, @@ -66,11 +68,12 @@ subtest 'total_outstanding() tests' => sub { } )->store; - $lines = Koha::Account::Lines->search({ borrowernumber => $patron->id }); + $lines = Koha::Account::Lines->search( { borrowernumber => $patron->id } ); is( $lines->total_outstanding, 20, 'total_outstanding sums correctly' ); my $credit_1 = Koha::Account::Line->new( - { borrowernumber => $patron->id, + { + borrowernumber => $patron->id, credit_type_code => "PAYMENT", amount => -10, amountoutstanding => -10, @@ -78,11 +81,12 @@ subtest 'total_outstanding() tests' => sub { } )->store; - $lines = Koha::Account::Lines->search({ borrowernumber => $patron->id }); + $lines = Koha::Account::Lines->search( { borrowernumber => $patron->id } ); is( $lines->total_outstanding, 10, 'total_outstanding sums correctly' ); my $credit_2 = Koha::Account::Line->new( - { borrowernumber => $patron->id, + { + borrowernumber => $patron->id, credit_type_code => "PAYMENT", amount => -10, amountoutstanding => -10, @@ -90,11 +94,12 @@ subtest 'total_outstanding() tests' => sub { } )->store; - $lines = Koha::Account::Lines->search({ borrowernumber => $patron->id }); + $lines = Koha::Account::Lines->search( { borrowernumber => $patron->id } ); is( $lines->total_outstanding, 0, 'total_outstanding sums correctly' ); my $credit_3 = Koha::Account::Line->new( - { borrowernumber => $patron->id, + { + borrowernumber => $patron->id, credit_type_code => "PAYMENT", amount => -100, amountoutstanding => -100, @@ -102,7 +107,7 @@ subtest 'total_outstanding() tests' => sub { } )->store; - $lines = Koha::Account::Lines->search({ borrowernumber => $patron->id }); + $lines = Koha::Account::Lines->search( { borrowernumber => $patron->id } ); is( $lines->total_outstanding, -100, 'total_outstanding sums correctly' ); $schema->storage->txn_rollback; @@ -114,13 +119,14 @@ subtest 'total() tests' => sub { $schema->storage->txn_begin; - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); - my $lines = Koha::Account::Lines->search({ borrowernumber => $patron->id }); + my $lines = Koha::Account::Lines->search( { borrowernumber => $patron->id } ); is( $lines->total, 0, 'total returns 0 if no lines (undef case)' ); my $debit_1 = Koha::Account::Line->new( - { borrowernumber => $patron->id, + { + borrowernumber => $patron->id, debit_type_code => "OVERDUE", status => "RETURNED", amount => 10, @@ -130,8 +136,9 @@ subtest 'total() tests' => sub { )->store; my $debit_2 = Koha::Account::Line->new( - { borrowernumber => $patron->id, - debit_type_code => "OVERDUE", + { + borrowernumber => $patron->id, + debit_type_code => "OVERDUE", status => "RETURNED", amount => 10, amountoutstanding => 10, @@ -139,11 +146,12 @@ subtest 'total() tests' => sub { } )->store; - $lines = Koha::Account::Lines->search({ borrowernumber => $patron->id }); + $lines = Koha::Account::Lines->search( { borrowernumber => $patron->id } ); is( $lines->total, 20, 'total sums correctly' ); my $credit_1 = Koha::Account::Line->new( - { borrowernumber => $patron->id, + { + borrowernumber => $patron->id, credit_type_code => "PAYMENT", amount => -10, amountoutstanding => -10, @@ -151,11 +159,12 @@ subtest 'total() tests' => sub { } )->store; - $lines = Koha::Account::Lines->search({ borrowernumber => $patron->id }); + $lines = Koha::Account::Lines->search( { borrowernumber => $patron->id } ); is( $lines->total, 10, 'total sums correctly' ); my $credit_2 = Koha::Account::Line->new( - { borrowernumber => $patron->id, + { + borrowernumber => $patron->id, credit_type_code => "PAYMENT", amount => -10, amountoutstanding => -10, @@ -163,11 +172,12 @@ subtest 'total() tests' => sub { } )->store; - $lines = Koha::Account::Lines->search({ borrowernumber => $patron->id }); + $lines = Koha::Account::Lines->search( { borrowernumber => $patron->id } ); is( $lines->total, 0, 'total sums correctly' ); my $credit_3 = Koha::Account::Line->new( - { borrowernumber => $patron->id, + { + borrowernumber => $patron->id, credit_type_code => "PAYMENT", amount => -100, amountoutstanding => -100, @@ -175,7 +185,7 @@ subtest 'total() tests' => sub { } )->store; - $lines = Koha::Account::Lines->search({ borrowernumber => $patron->id }); + $lines = Koha::Account::Lines->search( { borrowernumber => $patron->id } ); is( $lines->total, -100, 'total sums correctly' ); $schema->storage->txn_rollback; @@ -187,13 +197,14 @@ subtest 'credits_total() tests' => sub { $schema->storage->txn_begin; - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); - my $lines = Koha::Account::Lines->search({ borrowernumber => $patron->id }); + my $lines = Koha::Account::Lines->search( { borrowernumber => $patron->id } ); is( $lines->credits_total, 0, 'credits_total returns 0 if no lines (undef case)' ); my $debit_1 = Koha::Account::Line->new( - { borrowernumber => $patron->id, + { + borrowernumber => $patron->id, debit_type_code => "OVERDUE", status => "RETURNED", amount => 10, @@ -203,7 +214,8 @@ subtest 'credits_total() tests' => sub { )->store; my $debit_2 = Koha::Account::Line->new( - { borrowernumber => $patron->id, + { + borrowernumber => $patron->id, debit_type_code => "OVERDUE", status => "RETURNED", amount => 10, @@ -212,11 +224,12 @@ subtest 'credits_total() tests' => sub { } )->store; - $lines = Koha::Account::Lines->search({ borrowernumber => $patron->id }); + $lines = Koha::Account::Lines->search( { borrowernumber => $patron->id } ); is( $lines->credits_total, 0, 'credits_total sums correctly' ); my $credit_1 = Koha::Account::Line->new( - { borrowernumber => $patron->id, + { + borrowernumber => $patron->id, credit_type_code => "PAYMENT", amount => -10, amountoutstanding => -10, @@ -224,11 +237,12 @@ subtest 'credits_total() tests' => sub { } )->store; - $lines = Koha::Account::Lines->search({ borrowernumber => $patron->id }); + $lines = Koha::Account::Lines->search( { borrowernumber => $patron->id } ); is( $lines->credits_total, -10, 'credits_total sums correctly' ); my $credit_2 = Koha::Account::Line->new( - { borrowernumber => $patron->id, + { + borrowernumber => $patron->id, credit_type_code => "PAYMENT", amount => -10, amountoutstanding => -10, @@ -236,11 +250,12 @@ subtest 'credits_total() tests' => sub { } )->store; - $lines = Koha::Account::Lines->search({ borrowernumber => $patron->id }); + $lines = Koha::Account::Lines->search( { borrowernumber => $patron->id } ); is( $lines->credits_total, -20, 'credits_total sums correctly' ); my $credit_3 = Koha::Account::Line->new( - { borrowernumber => $patron->id, + { + borrowernumber => $patron->id, credit_type_code => "PAYMENT", amount => -100, amountoutstanding => -100, @@ -248,7 +263,7 @@ subtest 'credits_total() tests' => sub { } )->store; - $lines = Koha::Account::Lines->search({ borrowernumber => $patron->id }); + $lines = Koha::Account::Lines->search( { borrowernumber => $patron->id } ); is( $lines->credits_total, -120, 'credits_total sums correctly' ); $schema->storage->txn_rollback; @@ -260,13 +275,14 @@ subtest 'debits_total() tests' => sub { $schema->storage->txn_begin; - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); - my $lines = Koha::Account::Lines->search({ borrowernumber => $patron->id }); + my $lines = Koha::Account::Lines->search( { borrowernumber => $patron->id } ); is( $lines->debits_total, 0, 'debits_total returns 0 if no lines (undef case)' ); my $debit_1 = Koha::Account::Line->new( - { borrowernumber => $patron->id, + { + borrowernumber => $patron->id, debit_type_code => "OVERDUE", status => "RETURNED", amount => 10, @@ -276,7 +292,8 @@ subtest 'debits_total() tests' => sub { )->store; my $debit_2 = Koha::Account::Line->new( - { borrowernumber => $patron->id, + { + borrowernumber => $patron->id, debit_type_code => "OVERDUE", status => "RETURNED", amount => 10, @@ -285,11 +302,12 @@ subtest 'debits_total() tests' => sub { } )->store; - $lines = Koha::Account::Lines->search({ borrowernumber => $patron->id }); + $lines = Koha::Account::Lines->search( { borrowernumber => $patron->id } ); is( $lines->debits_total, 20, 'debits_total sums correctly' ); my $credit_1 = Koha::Account::Line->new( - { borrowernumber => $patron->id, + { + borrowernumber => $patron->id, credit_type_code => "PAYMENT", amount => -10, amountoutstanding => 0, @@ -297,11 +315,12 @@ subtest 'debits_total() tests' => sub { } )->store; - $lines = Koha::Account::Lines->search({ borrowernumber => $patron->id }); + $lines = Koha::Account::Lines->search( { borrowernumber => $patron->id } ); is( $lines->debits_total, 20, 'debits_total sums correctly' ); my $credit_2 = Koha::Account::Line->new( - { borrowernumber => $patron->id, + { + borrowernumber => $patron->id, credit_type_code => "PAYMENT", amount => -10, amountoutstanding => 0, @@ -309,11 +328,12 @@ subtest 'debits_total() tests' => sub { } )->store; - $lines = Koha::Account::Lines->search({ borrowernumber => $patron->id }); + $lines = Koha::Account::Lines->search( { borrowernumber => $patron->id } ); is( $lines->debits_total, 20, 'debits_total sums correctly' ); my $credit_3 = Koha::Account::Line->new( - { borrowernumber => $patron->id, + { + borrowernumber => $patron->id, credit_type_code => "PAYMENT", amount => -100, amountoutstanding => 0, @@ -321,7 +341,7 @@ subtest 'debits_total() tests' => sub { } )->store; - $lines = Koha::Account::Lines->search({ borrowernumber => $patron->id }); + $lines = Koha::Account::Lines->search( { borrowernumber => $patron->id } ); is( $lines->debits_total, 20, 'debits_total sums correctly' ); $schema->storage->txn_rollback; diff --git a/t/db_dependent/Koha/Account/Offsets.t b/t/db_dependent/Koha/Account/Offsets.t index 54365f92b0..dd851dd9a8 100755 --- a/t/db_dependent/Koha/Account/Offsets.t +++ b/t/db_dependent/Koha/Account/Offsets.t @@ -47,16 +47,16 @@ subtest 'total() tests' => sub { my $amount_4 = -300; my $amount_5 = 500; - my $offset_1 = Koha::Account::Offset->new( - { type => 'OVERDUE_INCREASE', amount => $amount_1, debit_id => $line->id } )->store; - my $offset_2 = Koha::Account::Offset->new( - { type => 'OVERDUE_INCREASE', amount => $amount_2, debit_id => $line->id } )->store; - my $offset_3 = Koha::Account::Offset->new( - { type => 'OVERDUE_DECREASE', amount => $amount_3, debit_id => $line->id } )->store; - my $offset_4 = Koha::Account::Offset->new( - { type => 'OVERDUE_DECREASE', amount => $amount_4, debit_id => $line->id } )->store; - my $offset_5 = Koha::Account::Offset->new( - { type => 'OVERDUE_INCREASE', amount => $amount_5, debit_id => $line->id } )->store; + my $offset_1 = + Koha::Account::Offset->new( { type => 'OVERDUE_INCREASE', amount => $amount_1, debit_id => $line->id } )->store; + my $offset_2 = + Koha::Account::Offset->new( { type => 'OVERDUE_INCREASE', amount => $amount_2, debit_id => $line->id } )->store; + my $offset_3 = + Koha::Account::Offset->new( { type => 'OVERDUE_DECREASE', amount => $amount_3, debit_id => $line->id } )->store; + my $offset_4 = + Koha::Account::Offset->new( { type => 'OVERDUE_DECREASE', amount => $amount_4, debit_id => $line->id } )->store; + my $offset_5 = + Koha::Account::Offset->new( { type => 'OVERDUE_INCREASE', amount => $amount_5, debit_id => $line->id } )->store; my $debits = Koha::Account::Offsets->search( { type => 'OVERDUE_INCREASE', debit_id => $line->id } ); is( $debits->total, $amount_1 + $amount_2 + $amount_5 ); @@ -82,7 +82,7 @@ subtest 'filter_by_non_reversible() and filter_by_reversible() tests' => sub { my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $account = $patron->account; - my $manual_fee = $account->add_debit({ amount => 11, interface => 'intranet', type => 'MANUAL' }); + my $manual_fee = $account->add_debit( { amount => 11, interface => 'intranet', type => 'MANUAL' } ); $account->pay( { amount => 1, type => 'WRITEOFF' } ); $account->pay( { amount => 2, type => 'DISCOUNT' } ); @@ -91,15 +91,24 @@ subtest 'filter_by_non_reversible() and filter_by_reversible() tests' => sub { $account->pay( { amount => 5, type => 'CREDIT' } ); # non-reversible offsets - is( $manual_fee->debit_offsets->filter_by_non_reversible->count, - 3, '3 non-reversible offsets' ); - is( $manual_fee->debit_offsets->filter_by_non_reversible->total, - -6, '-6 the total amount of the non-reversible offsets' ); + is( + $manual_fee->debit_offsets->filter_by_non_reversible->count, + 3, '3 non-reversible offsets' + ); + is( + $manual_fee->debit_offsets->filter_by_non_reversible->total, + -6, '-6 the total amount of the non-reversible offsets' + ); + # reversible offsets - is( $manual_fee->debit_offsets->filter_by_reversible->count, - 2, 'The right reversible offsets count' ); - is( $manual_fee->debit_offsets->filter_by_reversible->total, - -5, 'The right total amount of the reversible offsets' ); + is( + $manual_fee->debit_offsets->filter_by_reversible->count, + 2, 'The right reversible offsets count' + ); + is( + $manual_fee->debit_offsets->filter_by_reversible->total, + -5, 'The right total amount of the reversible offsets' + ); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/Koha/Acquisition/Basket.t b/t/db_dependent/Koha/Acquisition/Basket.t index c3dc128513..b7bca18e76 100755 --- a/t/db_dependent/Koha/Acquisition/Basket.t +++ b/t/db_dependent/Koha/Acquisition/Basket.t @@ -55,14 +55,18 @@ subtest 'create_items + effective_create_items tests' => sub { $basket->is_standing, $basket->create_items ); my $created_basket = Koha::Acquisition::Baskets->find($created_basketno); - is( $created_basket->basketno, $created_basketno, - "Basket created by NewBasket matches db basket" ); + is( + $created_basket->basketno, $created_basketno, + "Basket created by NewBasket matches db basket" + ); is( $basket->create_items, undef, "Create items value can be null" ); t::lib::Mocks::mock_preference( 'AcqCreateItem', 'cataloguing' ); - is( $basket->effective_create_items, + is( + $basket->effective_create_items, "cataloguing", - "We use AcqCreateItem if basket create items is not set" ); + "We use AcqCreateItem if basket create items is not set" + ); C4::Acquisition::ModBasketHeader( $basket->basketno, $basket->basketname, $basket->note, $basket->booksellernote, @@ -73,11 +77,15 @@ subtest 'create_items + effective_create_items tests' => sub { my $retrieved_basket = Koha::Acquisition::Baskets->find( $basket->basketno ); $basket->create_items("ordering"); is( $retrieved_basket->create_items, "ordering", "Should be able to set with ModBasketHeader" ); - is( $basket->create_items, "ordering", "Should be able to set with object methods" ); - is_deeply( $retrieved_basket->unblessed, - $basket->unblessed, "Correct basket found and updated" ); - is( $retrieved_basket->effective_create_items, - "ordering", "We use basket create items if it is set" ); + is( $basket->create_items, "ordering", "Should be able to set with object methods" ); + is_deeply( + $retrieved_basket->unblessed, + $basket->unblessed, "Correct basket found and updated" + ); + is( + $retrieved_basket->effective_create_items, + "ordering", "We use basket create items if it is set" + ); $schema->storage->txn_rollback; }; @@ -89,24 +97,29 @@ subtest 'basket_group' => sub { my $b = $builder->build_object( { class => 'Koha::Acquisition::Baskets', - value => { basketgroupid => undef }, # not linked to a basketgroupid + value => { basketgroupid => undef }, # not linked to a basketgroupid } ); my $basket = Koha::Acquisition::Baskets->find( $b->basketno ); - is( $basket->basket_group, undef, - '->basket_group should return undef if not linked to a basket group'); + is( + $basket->basket_group, undef, + '->basket_group should return undef if not linked to a basket group' + ); $b = $builder->build_object( { class => 'Koha::Acquisition::Baskets', + # Will be linked to a basket group by TestBuilder } ); $basket = Koha::Acquisition::Baskets->find( $b->basketno ); - is( ref( $basket->basket_group ), 'Koha::Acquisition::BasketGroup', - '->basket_group should return a Koha::Acquisition::BasketGroup object if linked to a basket group'); + is( + ref( $basket->basket_group ), 'Koha::Acquisition::BasketGroup', + '->basket_group should return a Koha::Acquisition::BasketGroup object if linked to a basket group' + ); $schema->storage->txn_rollback; }; @@ -126,11 +139,11 @@ subtest 'creator() tests' => sub { is( $basket->creator, undef, 'Undef is handled as expected' ); - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); $basket->authorisedby( $patron->borrowernumber )->store->discard_changes; my $creator = $basket->creator; - is( ref($creator), 'Koha::Patron', 'Return type is correct' ); + is( ref($creator), 'Koha::Patron', 'Return type is correct' ); is( $creator->borrowernumber, $patron->borrowernumber, 'Returned object is the right one' ); # Delete the patron @@ -147,27 +160,25 @@ subtest 'to_api() tests' => sub { $schema->storage->txn_begin; - my $vendor = $builder->build_object({ class => 'Koha::Acquisition::Booksellers' }); + my $vendor = $builder->build_object( { class => 'Koha::Acquisition::Booksellers' } ); my $basket = $builder->build_object( { class => 'Koha::Acquisition::Baskets', - value => { - closedate => undef - } + value => { closedate => undef } } ); my $closed = $basket->to_api->{closed}; ok( defined $closed, 'closed is defined' ); - ok( !$closed, 'closedate is undef, closed evaluates to false' ); + ok( !$closed, 'closedate is undef, closed evaluates to false' ); - $basket->closedate( dt_from_string )->store->discard_changes; + $basket->closedate(dt_from_string)->store->discard_changes; $closed = $basket->to_api->{closed}; ok( defined $closed, 'closed is defined' ); - ok( $closed, 'closedate is defined, closed evaluates to true' ); + ok( $closed, 'closedate is defined, closed evaluates to true' ); $basket->booksellerid( $vendor->id )->store->discard_changes; - my $basket_json = $basket->to_api({ embed => { bookseller => {} } }); + my $basket_json = $basket->to_api( { embed => { bookseller => {} } } ); ok( exists $basket_json->{bookseller} ); is_deeply( $basket_json->{bookseller}, $vendor->to_api ); @@ -182,7 +193,7 @@ subtest 'estimated_delivery_date' => sub { { class => 'Koha::Acquisition::Booksellers', value => { - deliverytime => undef, # Does not have a delivery time defined + deliverytime => undef, # Does not have a delivery time defined } } ); @@ -198,21 +209,26 @@ subtest 'estimated_delivery_date' => sub { ); my $now = dt_from_string; - is( $basket->estimated_delivery_date, - undef, 'return undef if closedate and deliverytime are not defined' ); + is( + $basket->estimated_delivery_date, + undef, 'return undef if closedate and deliverytime are not defined' + ); - $basket->closedate( $now->clone->subtract( days => 1 ) ) - ->store; #Closing the basket - is( $basket->estimated_delivery_date, - undef, 'return undef if deliverytime is not defined' ); + $basket->closedate( $now->clone->subtract( days => 1 ) )->store; #Closing the basket + is( + $basket->estimated_delivery_date, + undef, 'return undef if deliverytime is not defined' + ); - $basket->closedate(undef)->store; #Reopening - $bookseller->deliverytime(2)->store; # 2 delivery days - is( $basket->estimated_delivery_date, - undef, 'return undef if closedate is not defined (basket stil open)' ); + $basket->closedate(undef)->store; #Reopening + $bookseller->deliverytime(2)->store; # 2 delivery days + is( + $basket->estimated_delivery_date, + undef, 'return undef if closedate is not defined (basket stil open)' + ); - $bookseller->deliverytime(2)->store; # 2 delivery days - $basket->closedate( $now->clone->subtract( days => 1 ) )->store; #Closing the basket + $bookseller->deliverytime(2)->store; # 2 delivery days + $basket->closedate( $now->clone->subtract( days => 1 ) )->store; #Closing the basket is( $basket->get_from_storage->estimated_delivery_date, $now->clone->add( days => 1 )->truncate( to => 'day' ), @@ -226,17 +242,17 @@ subtest 'late_since_days' => sub { plan tests => 3; $schema->storage->txn_begin; - my $basket = $builder->build_object( + my $basket = $builder->build_object( { class => 'Koha::Acquisition::Baskets', } ); my $now = dt_from_string; - $basket->closedate(undef)->store; # Basket is open - is( $basket->late_since_days, undef, 'return undef if basket is still open'); + $basket->closedate(undef)->store; # Basket is open + is( $basket->late_since_days, undef, 'return undef if basket is still open' ); - $basket->closedate( $now )->store; #Closing the basket today + $basket->closedate($now)->store; #Closing the basket today is( $basket->late_since_days, 0, 'return 0 if basket has been closed on today' ); $basket->closedate( $now->clone->subtract( days => 2 ) )->store; @@ -258,13 +274,17 @@ subtest 'authorizer' => sub { my $basket_creator = $builder->build_object( { class => 'Koha::Patrons' } ); - is( $basket->authorizer, undef, - 'authorisedby is null, ->authorized should return undef' ); + is( + $basket->authorizer, undef, + 'authorisedby is null, ->authorized should return undef' + ); $basket->authorisedby( $basket_creator->borrowernumber )->store; - is( ref( $basket->authorizer ), - 'Koha::Patron', '->authorized should return a Koha::Patron object' ); + is( + ref( $basket->authorizer ), + 'Koha::Patron', '->authorized should return a Koha::Patron object' + ); is( $basket->authorizer->borrowernumber, $basket_creator->borrowernumber, @@ -280,25 +300,22 @@ subtest 'orders' => sub { $schema->storage->txn_begin; - my $basket = $builder->build_object( - { - class => 'Koha::Acquisition::Baskets' - } - ); + my $basket = $builder->build_object( { class => 'Koha::Acquisition::Baskets' } ); my $orders = $basket->orders; - is( ref($orders), 'Koha::Acquisition::Orders', 'Type is correct with no attached orders' ); - is( $orders->count, 0, 'No orders attached, count 0' ); + is( ref($orders), 'Koha::Acquisition::Orders', 'Type is correct with no attached orders' ); + is( $orders->count, 0, 'No orders attached, count 0' ); my @actual_orders; - for ( 1..3 ) { - push @actual_orders, $builder->build_object({ class => 'Koha::Acquisition::Orders', value => { basketno => $basket->id } }); + for ( 1 .. 3 ) { + push @actual_orders, + $builder->build_object( { class => 'Koha::Acquisition::Orders', value => { basketno => $basket->id } } ); } $orders = $basket->orders; - is( ref($orders), 'Koha::Acquisition::Orders', 'Type is correct with no attached orders' ); - is( $orders->count, 3, '3 orders attached, count 3' ); + is( ref($orders), 'Koha::Acquisition::Orders', 'Type is correct with no attached orders' ); + is( $orders->count, 3, '3 orders attached, count 3' ); $schema->storage->txn_rollback; }; @@ -309,14 +326,12 @@ subtest 'edi_order' => sub { $schema->storage->txn_begin; - my $basket = $builder->build_object( - { - class => 'Koha::Acquisition::Baskets' - } - ); + my $basket = $builder->build_object( { class => 'Koha::Acquisition::Baskets' } ); - is( $basket->edi_order, undef, - 'edi_order returns undefined if there are no edi_messages of type "ORDER" attached' ); + is( + $basket->edi_order, undef, + 'edi_order returns undefined if there are no edi_messages of type "ORDER" attached' + ); my $order_message_1 = $builder->build( { @@ -331,8 +346,10 @@ subtest 'edi_order' => sub { ); my $edi_message = $basket->edi_order; - is( ref($edi_message), 'Koha::Schema::Result::EdifactMessage', - 'edi_order returns an EdifactMessage if one is attached' ); + is( + ref($edi_message), 'Koha::Schema::Result::EdifactMessage', + 'edi_order returns an EdifactMessage if one is attached' + ); my $order_message_2 = $builder->build( { @@ -346,8 +363,10 @@ subtest 'edi_order' => sub { ); $edi_message = $basket->edi_order; - is( $edi_message->id, $order_message_2->{id}, - 'edi_order returns the most recently associated ORDERS EdifactMessage' ); + is( + $edi_message->id, $order_message_2->{id}, + 'edi_order returns the most recently associated ORDERS EdifactMessage' + ); $schema->storage->txn_rollback; }; @@ -361,23 +380,19 @@ subtest 'is_closed() tests' => sub { my $open_basket = $builder->build_object( { class => 'Koha::Acquisition::Baskets', - value => { - closedate => undef - } + value => { closedate => undef } } ); my $closed_basket = $builder->build_object( { class => 'Koha::Acquisition::Baskets', - value => { - closedate => \'NOW()' - } + value => { closedate => \'NOW()' } } ); ok( $closed_basket->is_closed, 'Closed basket is tested as closed' ); - ok( !$open_basket->is_closed, 'Open basket is tested as open' ); + ok( !$open_basket->is_closed, 'Open basket is tested as open' ); $schema->storage->txn_rollback; }; @@ -387,7 +402,7 @@ subtest 'close() tests' => sub { plan tests => 4; # Turn on acquisitions logging and ensure the logs are empty - t::lib::Mocks::mock_preference('AcquisitionLog', 1); + t::lib::Mocks::mock_preference( 'AcquisitionLog', 1 ); Koha::ActionLogs->delete; $schema->storage->txn_begin; @@ -396,13 +411,11 @@ subtest 'close() tests' => sub { my $basket = $builder->build_object( { class => 'Koha::Acquisition::Baskets', - value => { - closedate => undef - } + value => { closedate => undef } } ); - for my $status ( qw( new ordered partial complete cancelled ) ) { + for my $status (qw( new ordered partial complete cancelled )) { $builder->build_object( { class => 'Koha::Acquisition::Orders', @@ -417,16 +430,17 @@ subtest 'close() tests' => sub { $basket->close; ok( $basket->is_closed, 'Basket is closed' ); - my $ordered_orders = $basket->orders->search({ orderstatus => 'ordered' }); + my $ordered_orders = $basket->orders->search( { orderstatus => 'ordered' } ); is( $ordered_orders->count, 3, 'Only open orders have been marked as ordered' ); - throws_ok - { $basket->close; } - 'Koha::Exceptions::Acquisition::Basket::AlreadyClosed', + throws_ok { $basket->close; } + 'Koha::Exceptions::Acquisition::Basket::AlreadyClosed', 'Trying to close an already closed basket throws an exception'; - my @close_logs = Koha::ActionLogs->search({ module =>'ACQUISITIONS', action => 'CLOSE_BASKET', object => $basket->id })->as_list; - is (scalar @close_logs, 1, 'Basket closure is logged'); + my @close_logs = + Koha::ActionLogs->search( { module => 'ACQUISITIONS', action => 'CLOSE_BASKET', object => $basket->id } ) + ->as_list; + is( scalar @close_logs, 1, 'Basket closure is logged' ); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/Koha/Acquisition/Baskets.t b/t/db_dependent/Koha/Acquisition/Baskets.t index 45a9071def..a70cccfa88 100755 --- a/t/db_dependent/Koha/Acquisition/Baskets.t +++ b/t/db_dependent/Koha/Acquisition/Baskets.t @@ -31,32 +31,41 @@ use t::lib::TestBuilder; my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; -my $builder = t::lib::TestBuilder->new; +my $builder = t::lib::TestBuilder->new; my $num_of_baskets = Koha::Acquisition::Baskets->search->count; -my $bookseller = Koha::Acquisition::Bookseller->new({ - name => 'Bookseller1', -})->store; +my $bookseller = Koha::Acquisition::Bookseller->new( + { + name => 'Bookseller1', + } +)->store; -my $basket = Koha::Acquisition::Basket->new({ - basketname => 'Basket1', - booksellerid => $bookseller->id, - is_standing => 0, -})->store; +my $basket = Koha::Acquisition::Basket->new( + { + basketname => 'Basket1', + booksellerid => $bookseller->id, + is_standing => 0, + } +)->store; -my $basket2 = Koha::Acquisition::Basket->new({ - basketname => 'BasketToDelete', - booksellerid => $bookseller->id, - is_standing => 0, -})->store; +my $basket2 = Koha::Acquisition::Basket->new( + { + basketname => 'BasketToDelete', + booksellerid => $bookseller->id, + is_standing => 0, + } +)->store; -like( $basket->basketno, qr|^\d+$|, 'Adding a new basket should have set the basketno'); +like( $basket->basketno, qr|^\d+$|, 'Adding a new basket should have set the basketno' ); my $retrieved_basket = Koha::Acquisition::Baskets->find( $basket->basketno ); is( $retrieved_basket->basketname, $basket->basketname, 'Find a basket by id should return the correct basket' ); my $retrieved_bookseller = $retrieved_basket->bookseller; -is( $retrieved_bookseller->name, $bookseller->name, "Finding the bookseller of a basket by the basket's booksellerid should work as expected" ); +is( + $retrieved_bookseller->name, $bookseller->name, + "Finding the bookseller of a basket by the basket's booksellerid should work as expected" +); $basket2->delete; is( Koha::Acquisition::Baskets->search->count, $num_of_baskets + 1, 'Delete should have deleted the basket' ); diff --git a/t/db_dependent/Koha/Acquisition/Booksellers.t b/t/db_dependent/Koha/Acquisition/Booksellers.t index 604a40e79f..241663d3d3 100755 --- a/t/db_dependent/Koha/Acquisition/Booksellers.t +++ b/t/db_dependent/Koha/Acquisition/Booksellers.t @@ -22,9 +22,9 @@ use Test::More tests => 6; use t::lib::TestBuilder; use C4::Acquisition qw( NewBasket ); -use C4::Biblio qw( AddBiblio ); -use C4::Budgets qw( AddBudgetPeriod AddBudget ); -use C4::Serials qw( NewSubscription SearchSubscriptions ); +use C4::Biblio qw( AddBiblio ); +use C4::Budgets qw( AddBudgetPeriod AddBudget ); +use C4::Serials qw( NewSubscription SearchSubscriptions ); use Koha::Acquisition::Booksellers; use Koha::Database; @@ -39,7 +39,7 @@ subtest '->baskets() tests' => sub { $schema->storage->txn_begin(); - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $vendor = $builder->build_object( { class => 'Koha::Acquisition::Booksellers' } ); @@ -66,23 +66,23 @@ subtest '->subscriptions() tests' => sub { is( $vendor->subscriptions->count, 0, 'Vendor has no subscriptions' ); my $dt_today = dt_from_string; - my $today = output_pref( - { dt => $dt_today, dateformat => 'iso', timeformat => '24hr', dateonly => 1 } ); + my $today = output_pref( { dt => $dt_today, dateformat => 'iso', timeformat => '24hr', dateonly => 1 } ); my $dt_today1 = dt_from_string; - my $dur5 = DateTime::Duration->new( days => -5 ); + my $dur5 = DateTime::Duration->new( days => -5 ); $dt_today1->add_duration($dur5); - my $daysago5 = output_pref( - { dt => $dt_today1, dateformat => 'iso', timeformat => '24hr', dateonly => 1 } ); + my $daysago5 = output_pref( { dt => $dt_today1, dateformat => 'iso', timeformat => '24hr', dateonly => 1 } ); my $budgetperiod = C4::Budgets::AddBudgetPeriod( - { budget_period_startdate => $daysago5, + { + budget_period_startdate => $daysago5, budget_period_enddate => $today, budget_period_description => "budget desc" } ); my $id_budget = AddBudget( - { budget_code => "CODE", + { + budget_code => "CODE", budget_amount => "123.132", budget_name => "Budgetname", budget_notes => "This is a note", @@ -110,11 +110,13 @@ subtest '->subscriptions() tests' => sub { ); my @subscriptions = SearchSubscriptions( { biblionumber => $biblionumber } ); - is( $subscriptions[0]->{publicnotes}, + is( + $subscriptions[0]->{publicnotes}, 'subscription notes', 'subscription search results include public notes (bug 10689)' ); - is( $subscriptions[0]->{subtitle}, + is( + $subscriptions[0]->{subtitle}, 'A subtitle', 'subscription search results include subtitle (bug 30204)' ); @@ -135,7 +137,7 @@ subtest '->subscriptions() tests' => sub { $vendor = Koha::Acquisition::Booksellers->find( $vendor->id ); my $subscriptions = $vendor->subscriptions; is( $subscriptions->count, 2, 'Vendor has two subscriptions' ); - while (my $subscription = $subscriptions->next ) { + while ( my $subscription = $subscriptions->next ) { is( ref($subscription), 'Koha::Subscription', 'Type is correct' ); } @@ -154,12 +156,14 @@ subtest '->contacts() tests' => sub { # Add two contacts my $contact_1 = $builder->build_object( - { class => 'Koha::Acquisition::Bookseller::Contacts', + { + class => 'Koha::Acquisition::Bookseller::Contacts', value => { booksellerid => $vendor->id } } ); my $contact_2 = $builder->build_object( - { class => 'Koha::Acquisition::Bookseller::Contacts', + { + class => 'Koha::Acquisition::Bookseller::Contacts', value => { booksellerid => $vendor->id } } ); @@ -167,8 +171,8 @@ subtest '->contacts() tests' => sub { # Re-fetch vendor $vendor = Koha::Acquisition::Booksellers->find( $vendor->id ); my $contacts = $vendor->contacts; - is( $contacts->count, 2, 'Vendor has two contacts' ); - is( ref($contacts), 'Koha::Acquisition::Bookseller::Contacts', 'Type is correct' ); + is( $contacts->count, 2, 'Vendor has two contacts' ); + is( ref($contacts), 'Koha::Acquisition::Bookseller::Contacts', 'Type is correct' ); $schema->storage->txn_rollback(); }; @@ -207,8 +211,8 @@ subtest 'interfaces' => sub { $vendor = $vendor->get_from_storage; my $interfaces = $vendor->interfaces; - is( $interfaces->count, 2, '2 interfaces stored' ); - is( ref($interfaces), 'Koha::Acquisition::Bookseller::Interfaces', 'Type is correct' ); + is( $interfaces->count, 2, '2 interfaces stored' ); + is( ref($interfaces), 'Koha::Acquisition::Bookseller::Interfaces', 'Type is correct' ); $vendor->interfaces( [ { name => 'first interface', login => 'one_login', password => 'oneP@sswOrd' } ] ); $vendor = $vendor->get_from_storage; diff --git a/t/db_dependent/Koha/Acquisition/Budgets.t b/t/db_dependent/Koha/Acquisition/Budgets.t index e5aedefdad..7b46462978 100755 --- a/t/db_dependent/Koha/Acquisition/Budgets.t +++ b/t/db_dependent/Koha/Acquisition/Budgets.t @@ -30,22 +30,27 @@ use t::lib::TestBuilder; my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; -my $builder = t::lib::TestBuilder->new; -my $nb_of_budgets= Koha::Acquisition::Budgets->search->count; -my $now = dt_from_string; -my $new_budget = Koha::Acquisition::Budget->new({ - budget_period_startdate => $now, - budget_period_enddate => $now, - budget_period_active => 1, - budget_period_description => 'a new budget', - budget_period_total => 1000, -})->store; +my $builder = t::lib::TestBuilder->new; +my $nb_of_budgets = Koha::Acquisition::Budgets->search->count; +my $now = dt_from_string; +my $new_budget = Koha::Acquisition::Budget->new( + { + budget_period_startdate => $now, + budget_period_enddate => $now, + budget_period_active => 1, + budget_period_description => 'a new budget', + budget_period_total => 1000, + } +)->store; -like( $new_budget->budget_period_id, qr|^\d+$|, 'Adding a new budget should have set the budget_period_id'); +like( $new_budget->budget_period_id, qr|^\d+$|, 'Adding a new budget should have set the budget_period_id' ); is( Koha::Acquisition::Budgets->search->count, $nb_of_budgets + 1, 'The budget should have been added' ); -my $retrieved_budget = Koha::Acquisition::Budgets->find( $new_budget->budget_period_id); -is( $retrieved_budget->budget_period_description, $new_budget->budget_period_description, 'Find a budget by budget_period_id should return the correct budget' ); +my $retrieved_budget = Koha::Acquisition::Budgets->find( $new_budget->budget_period_id ); +is( + $retrieved_budget->budget_period_description, $new_budget->budget_period_description, + 'Find a budget by budget_period_id should return the correct budget' +); $retrieved_budget->delete; is( Koha::Acquisition::Budgets->search->count, $nb_of_budgets, 'Delete should have deleted the budget' ); diff --git a/t/db_dependent/Koha/Acquisition/Currencies.t b/t/db_dependent/Koha/Acquisition/Currencies.t index 0412160c42..93facad3d1 100755 --- a/t/db_dependent/Koha/Acquisition/Currencies.t +++ b/t/db_dependent/Koha/Acquisition/Currencies.t @@ -27,26 +27,30 @@ use t::lib::TestBuilder; my $schema = Koha::Database->schema; $schema->storage->txn_begin; -my $builder = t::lib::TestBuilder->new; +my $builder = t::lib::TestBuilder->new; my $nb_of_currencies = Koha::Acquisition::Currencies->search->count; -my $new_currency_1 = Koha::Acquisition::Currency->new({ - currency => 'my_cur_1', - symbol => 'symb1', - isocode => 'isoc1', - rate => 1, - active => 1, -})->store; +my $new_currency_1 = Koha::Acquisition::Currency->new( + { + currency => 'my_cur_1', + symbol => 'symb1', + isocode => 'isoc1', + rate => 1, + active => 1, + } +)->store; my $retrieved_currency_1 = Koha::Acquisition::Currencies->find( $new_currency_1->currency ); is( $retrieved_currency_1->active, 1, 'Active should have been set to 1' ); -my $new_currency_2 = Koha::Acquisition::Currency->new({ - currency => 'my_cur_2', - symbol => 'symb2', - isocode => 'isoc2', - rate => 2, - active => 1, -})->store; +my $new_currency_2 = Koha::Acquisition::Currency->new( + { + currency => 'my_cur_2', + symbol => 'symb2', + isocode => 'isoc2', + rate => 2, + active => 1, + } +)->store; is( Koha::Acquisition::Currencies->search->count, $nb_of_currencies + 2, 'The 2 currencies should have been added' ); my $retrieved_currency_2 = Koha::Acquisition::Currencies->find( $new_currency_2->currency ); @@ -57,10 +61,13 @@ $retrieved_currency_2 = Koha::Acquisition::Currencies->find( $new_currency_2->cu is( $retrieved_currency_2->active, 1, 'Editing the existing active currency should not remove its active flag' ); my $active_currency = Koha::Acquisition::Currencies->get_active; -is ( $active_currency->currency, $retrieved_currency_2->currency, 'The active currency should be the last one marked as active' ); +is( + $active_currency->currency, $retrieved_currency_2->currency, + 'The active currency should be the last one marked as active' +); -my $nb_of_active_currencies = Koha::Acquisition::Currencies->search({active => 1})->count; -is ( $nb_of_active_currencies, 1, 'Only 1 currency should be marked as active' ); +my $nb_of_active_currencies = Koha::Acquisition::Currencies->search( { active => 1 } )->count; +is( $nb_of_active_currencies, 1, 'Only 1 currency should be marked as active' ); $retrieved_currency_1->delete; is( Koha::Acquisition::Currencies->search->count, $nb_of_currencies + 1, 'Delete should have deleted the currency' ); diff --git a/t/db_dependent/Koha/Acquisition/Fund.t b/t/db_dependent/Koha/Acquisition/Fund.t index fc21d0b38f..ff1c6fe02b 100755 --- a/t/db_dependent/Koha/Acquisition/Fund.t +++ b/t/db_dependent/Koha/Acquisition/Fund.t @@ -35,10 +35,10 @@ subtest 'to_api() tests' => sub { $schema->storage->txn_begin; - my $fund = $builder->build_object({ class => 'Koha::Acquisition::Funds' }); + my $fund = $builder->build_object( { class => 'Koha::Acquisition::Funds' } ); my $fund_api = $fund->to_api(); - is( $fund->budget_id, $fund_api->{fund_id}, 'Mapping is correct for budget_id' ); + is( $fund->budget_id, $fund_api->{fund_id}, 'Mapping is correct for budget_id' ); is( $fund->budget_period_id, $fund_api->{budget_id}, 'Mapping is correct for budget_period_id' ); $schema->storage->txn_rollback; @@ -49,10 +49,11 @@ subtest 'budget ()' => sub { $schema->storage->txn_begin; - my $budget = $builder->build_object({ class => 'Koha::Acquisition::Budgets' }); - my $fund = $builder->build_object({ class => 'Koha::Acquisition::Funds', value => { budget_period_id => $budget->budget_period_id } }); + my $budget = $builder->build_object( { class => 'Koha::Acquisition::Budgets' } ); + my $fund = $builder->build_object( + { class => 'Koha::Acquisition::Funds', value => { budget_period_id => $budget->budget_period_id } } ); - is($budget->budget_period_id, $fund->budget->budget_period_id, 'Fund\'s budget retrieved correctly'); + is( $budget->budget_period_id, $fund->budget->budget_period_id, 'Fund\'s budget retrieved correctly' ); $schema->storage->txn_rollback; }; @@ -68,16 +69,18 @@ subtest 'budget' => sub { ); my $fund = Koha::Acquisition::Funds->find( $f->budget_id ); - is( ref( $fund->budget ), + is( + ref( $fund->budget ), 'Koha::Acquisition::Budget', - '->fund should return a Koha::Acquisition::Budget object' ); + '->fund should return a Koha::Acquisition::Budget object' + ); # Cannot set aqbudgets.budget_period_id as NULL warning_like { eval { $fund->budget_period_id(undef)->store } } qr{.*DBD::mysql::st execute failed: Column 'budget_period_id' cannot be null.*}, - 'DBD should have raised an error about budget_period_id that cannot be null'; + 'DBD should have raised an error about budget_period_id that cannot be null'; $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/Koha/Acquisition/Funds.t b/t/db_dependent/Koha/Acquisition/Funds.t index fc87ef7727..43e01562af 100755 --- a/t/db_dependent/Koha/Acquisition/Funds.t +++ b/t/db_dependent/Koha/Acquisition/Funds.t @@ -29,8 +29,8 @@ use t::lib::TestBuilder; my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; -my $builder = t::lib::TestBuilder->new; -my $nb_of_funds = Koha::Acquisition::Funds->search->count; +my $builder = t::lib::TestBuilder->new; +my $nb_of_funds = Koha::Acquisition::Funds->search->count; my $budget_period_id = C4::Budgets::AddBudgetPeriod( { budget_period_startdate => '2024-01-01', @@ -47,7 +47,7 @@ my $new_fund = Koha::Acquisition::Fund->new( } )->store; -like( $new_fund->budget_id, qr|^\d+$|, 'Adding a new fund should have set the budget_id'); +like( $new_fund->budget_id, qr|^\d+$|, 'Adding a new fund should have set the budget_id' ); is( Koha::Acquisition::Funds->search->count, $nb_of_funds + 1, 'The fund should have been added' ); my $retrieved_fund_1 = Koha::Acquisition::Funds->find( $new_fund->budget_id ); diff --git a/t/db_dependent/Koha/Acquisition/Invoice.t b/t/db_dependent/Koha/Acquisition/Invoice.t index e99f01f1c3..1875bd78c6 100755 --- a/t/db_dependent/Koha/Acquisition/Invoice.t +++ b/t/db_dependent/Koha/Acquisition/Invoice.t @@ -47,22 +47,20 @@ subtest 'to_api() tests' => sub { my $invoice = $builder->build_object( { class => 'Koha::Acquisition::Invoices', - value => { - closedate => undef - } + value => { closedate => undef } } ); my $closed = $invoice->to_api->{closed}; ok( defined $closed, 'closed is defined' ); - ok( !$closed, 'closedate is undef, closed evaluates to false' ); + ok( !$closed, 'closedate is undef, closed evaluates to false' ); - $invoice->closedate( dt_from_string )->store->discard_changes; + $invoice->closedate(dt_from_string)->store->discard_changes; $closed = $invoice->to_api->{closed}; ok( defined $closed, 'closed is defined' ); - ok( $closed, 'closedate is defined, closed evaluates to true' ); + ok( $closed, 'closedate is defined, closed evaluates to true' ); - my $invoice_json = $invoice->to_api({ embed => { algo => {} } }); + my $invoice_json = $invoice->to_api( { embed => { algo => {} } } ); ok( exists $invoice_json->{algo} ); is_deeply( $invoice_json->{algo}, 'algo' ); diff --git a/t/db_dependent/Koha/Acquisition/Invoice/Adjustments.t b/t/db_dependent/Koha/Acquisition/Invoice/Adjustments.t index 3419672b79..1a4b32ff1d 100755 --- a/t/db_dependent/Koha/Acquisition/Invoice/Adjustments.t +++ b/t/db_dependent/Koha/Acquisition/Invoice/Adjustments.t @@ -32,52 +32,74 @@ BEGIN { my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; -my $builder = t::lib::TestBuilder->new; +my $builder = t::lib::TestBuilder->new; my $nb_of_adjs = Koha::Acquisition::Invoice::Adjustments->search->count; -my $budget_id = $builder->build({source=>'Aqbudget'})->{budget_id}; -my $invoice_id = $builder->build({source=>'Aqinvoice'})->{invoiceid}; +my $budget_id = $builder->build( { source => 'Aqbudget' } )->{budget_id}; +my $invoice_id = $builder->build( { source => 'Aqinvoice' } )->{invoiceid}; -my $new_adj = Koha::Acquisition::Invoice::Adjustment->new({ - note => 'noted', - invoiceid => $invoice_id, - adjustment => '3', - reason => 'unreasonable', - budget_id => $budget_id, -})->store; +my $new_adj = Koha::Acquisition::Invoice::Adjustment->new( + { + note => 'noted', + invoiceid => $invoice_id, + adjustment => '3', + reason => 'unreasonable', + budget_id => $budget_id, + } +)->store; -like( $new_adj->adjustment_id, qr|^\d+$|, 'Adding a new adjustment should have set the adjustment_id'); +like( $new_adj->adjustment_id, qr|^\d+$|, 'Adding a new adjustment should have set the adjustment_id' ); -my $new_adj2 = Koha::Acquisition::Invoice::Adjustment->new({ - note => 'not noted', - invoiceid => $invoice_id, - adjustment => '-3', - reason => 'unreasonable', - budget_id => $budget_id, -})->store; +my $new_adj2 = Koha::Acquisition::Invoice::Adjustment->new( + { + note => 'not noted', + invoiceid => $invoice_id, + adjustment => '-3', + reason => 'unreasonable', + budget_id => $budget_id, + } +)->store; -ok( $new_adj->adjustment_id < $new_adj2->adjustment_id, 'Adding a new adjustment should increment'); -is( Koha::Acquisition::Invoice::Adjustments->search->count, $nb_of_adjs + 2, 'The 2 adjustments should have been added' ); +ok( $new_adj->adjustment_id < $new_adj2->adjustment_id, 'Adding a new adjustment should increment' ); +is( + Koha::Acquisition::Invoice::Adjustments->search->count, $nb_of_adjs + 2, + 'The 2 adjustments should have been added' +); my $retrieved_adj = Koha::Acquisition::Invoice::Adjustments->find( $new_adj->adjustment_id ); is( $retrieved_adj->reason, $new_adj->reason, 'Find an adjustment by id should return the correct adjustment' ); $retrieved_adj->delete; -is( Koha::Acquisition::Invoice::Adjustments->search->count, $nb_of_adjs + 1, 'Delete should have deleted the adjustment' ); +is( + Koha::Acquisition::Invoice::Adjustments->search->count, $nb_of_adjs + 1, + 'Delete should have deleted the adjustment' +); subtest 'invoice' => sub { plan tests => 2; my $invoice = $retrieved_adj->invoice; - is( ref( $invoice ), 'Koha::Acquisition::Invoice', 'Koha::Acquisition::Invoice::Adjustment->invoice should return a Koha::Acquisition::Invoice' ); - is( $invoice->invoiceid, $retrieved_adj->invoiceid, 'Koha::Acquisition::Invoice::Adjustment->invoice should return the correct invoice' ); + is( + ref($invoice), 'Koha::Acquisition::Invoice', + 'Koha::Acquisition::Invoice::Adjustment->invoice should return a Koha::Acquisition::Invoice' + ); + is( + $invoice->invoiceid, $retrieved_adj->invoiceid, + 'Koha::Acquisition::Invoice::Adjustment->invoice should return the correct invoice' + ); }; subtest 'fund' => sub { plan tests => 2; my $fund = $retrieved_adj->fund; - is( ref( $fund ), 'Koha::Acquisition::Fund', 'Koha::Acquisition::Invoice::Adjustment->fund should return a Koha::Acquisition::Fund' ); - is( $fund->budget_id, $retrieved_adj->budget_id, 'Koha::Acquisition::Invoice::Adjustment->fund should return the correct fund ' ); + is( + ref($fund), 'Koha::Acquisition::Fund', + 'Koha::Acquisition::Invoice::Adjustment->fund should return a Koha::Acquisition::Fund' + ); + is( + $fund->budget_id, $retrieved_adj->budget_id, + 'Koha::Acquisition::Invoice::Adjustment->fund should return the correct fund ' + ); }; $schema->storage->txn_rollback; diff --git a/t/db_dependent/Koha/Acquisition/Order.t b/t/db_dependent/Koha/Acquisition/Order.t index d74afa1ff5..0f7b7f21b5 100755 --- a/t/db_dependent/Koha/Acquisition/Order.t +++ b/t/db_dependent/Koha/Acquisition/Order.t @@ -41,12 +41,8 @@ subtest 'basket() tests' => sub { $schema->storage->txn_begin; - my $basket = $builder->build_object( - { - class => 'Koha::Acquisition::Baskets' - } - ); - my $order = $builder->build_object( + my $basket = $builder->build_object( { class => 'Koha::Acquisition::Baskets' } ); + my $order = $builder->build_object( { class => 'Koha::Acquisition::Orders', value => { basketno => $basket->basketno } @@ -54,10 +50,14 @@ subtest 'basket() tests' => sub { ); my $retrieved_basket = $order->basket; - is( ref($retrieved_basket), 'Koha::Acquisition::Basket', - 'Type is correct for ->basket' ); - is_deeply( $retrieved_basket->unblessed, - $basket->unblessed, "Correct basket found and updated" ); + is( + ref($retrieved_basket), 'Koha::Acquisition::Basket', + 'Type is correct for ->basket' + ); + is_deeply( + $retrieved_basket->unblessed, + $basket->unblessed, "Correct basket found and updated" + ); $schema->storage->txn_rollback; }; @@ -79,14 +79,14 @@ subtest 'biblio() tests' => sub { # Add and link a biblio to the order my $biblio = $builder->build_sample_biblio(); - $order->set({ biblionumber => $biblio->biblionumber })->store->discard_changes; + $order->set( { biblionumber => $biblio->biblionumber } )->store->discard_changes; my $THE_biblio = $order->biblio; - is( ref($THE_biblio), 'Koha::Biblio', 'Returns a Koha::Biblio object' ); + is( ref($THE_biblio), 'Koha::Biblio', 'Returns a Koha::Biblio object' ); is( $THE_biblio->biblionumber, $biblio->biblionumber, 'It is not cheating about the object' ); $order->biblio->delete; - $order = Koha::Acquisition::Orders->find($order->ordernumber); + $order = Koha::Acquisition::Orders->find( $order->ordernumber ); ok( $order, 'The order is not deleted if the biblio is deleted' ); is( $order->biblio, undef, 'order.biblio is correctly set to NULL when the biblio is deleted' ); @@ -97,11 +97,7 @@ subtest 'store' => sub { plan tests => 1; $schema->storage->txn_begin; - my $o = $builder->build_object( - { - class => 'Koha::Acquisition::Orders' - } - ); + my $o = $builder->build_object( { class => 'Koha::Acquisition::Orders' } ); subtest 'entrydate' => sub { plan tests => 2; @@ -146,9 +142,11 @@ subtest 'fund' => sub { ); my $order = Koha::Acquisition::Orders->find( $o->ordernumber ); - is( ref( $order->fund ), + is( + ref( $order->fund ), 'Koha::Acquisition::Fund', - '->fund should return a Koha::Acquisition::Fund object' ); + '->fund should return a Koha::Acquisition::Fund object' + ); $schema->storage->txn_rollback; }; @@ -159,13 +157,15 @@ subtest 'invoice' => sub { my $o = $builder->build_object( { class => 'Koha::Acquisition::Orders', - value => { cancellationreason => 'XXXXXXXX', invoiceid => undef }, # not received yet + value => { cancellationreason => 'XXXXXXXX', invoiceid => undef }, # not received yet } ); my $order = Koha::Acquisition::Orders->find( $o->ordernumber ); - is( $order->invoice, undef, - '->invoice should return undef if no invoice defined yet'); + is( + $order->invoice, undef, + '->invoice should return undef if no invoice defined yet' + ); my $invoice = $builder->build_object( { @@ -175,8 +175,10 @@ subtest 'invoice' => sub { $o->invoiceid( $invoice->invoiceid )->store; $order = Koha::Acquisition::Orders->find( $o->ordernumber ); - is( ref( $order->invoice ), 'Koha::Acquisition::Invoice', - '->invoice should return a Koha::Acquisition::Invoice object if an invoice is defined'); + is( + ref( $order->invoice ), 'Koha::Acquisition::Invoice', + '->invoice should return a Koha::Acquisition::Invoice object if an invoice is defined' + ); $schema->storage->txn_rollback; }; @@ -188,24 +190,29 @@ subtest 'subscription' => sub { my $o = $builder->build_object( { class => 'Koha::Acquisition::Orders', - value => { subscriptionid => undef }, # not linked to a subscription + value => { subscriptionid => undef }, # not linked to a subscription } ); my $order = Koha::Acquisition::Orders->find( $o->ordernumber ); - is( $order->subscription, undef, - '->subscription should return undef if not created from a subscription'); + is( + $order->subscription, undef, + '->subscription should return undef if not created from a subscription' + ); $o = $builder->build_object( { class => 'Koha::Acquisition::Orders', + # Will be linked to a subscription by TestBuilder } ); $order = Koha::Acquisition::Orders->find( $o->ordernumber ); - is( ref( $order->subscription ), 'Koha::Subscription', - '->subscription should return a Koha::Subscription object if created from a subscription'); + is( + ref( $order->subscription ), 'Koha::Subscription', + '->subscription should return a Koha::Subscription object if created from a subscription' + ); $schema->storage->txn_rollback; }; @@ -215,49 +222,49 @@ subtest 'duplicate_to | add_item' => sub { $schema->storage->txn_begin; - my $item = $builder->build_sample_item; + my $item = $builder->build_sample_item; my $order_no_sub = $builder->build_object( { class => 'Koha::Acquisition::Orders', - value => - { - biblionumber => $item->biblionumber, - subscriptionid => undef, # not linked to a subscription - } + value => { + biblionumber => $item->biblionumber, + subscriptionid => undef, # not linked to a subscription + } } ); - $order_no_sub->basket->create_items(undef)->store; # use syspref + $order_no_sub->basket->create_items(undef)->store; # use syspref $order_no_sub->add_item( $item->itemnumber ); $item = $builder->build_sample_item; my $order_from_sub = $builder->build_object( { class => 'Koha::Acquisition::Orders', - value => - { - biblionumber => $item->biblionumber, - # Will be linked to a subscription by TestBuilder - } + value => { + biblionumber => $item->biblionumber, + + # Will be linked to a subscription by TestBuilder + } } ); - $order_from_sub->basket->create_items(undef)->store; # use syspref + $order_from_sub->basket->create_items(undef)->store; # use syspref $order_from_sub->add_item( $item->itemnumber ); - my $basket_to = $builder->build_object( - { class => 'Koha::Acquisition::Baskets' }); + my $basket_to = $builder->build_object( { class => 'Koha::Acquisition::Baskets' } ); subtest 'Create item on receiving' => sub { plan tests => 2; - t::lib::Mocks::mock_preference('AcqCreateItem', 'receiving'); + t::lib::Mocks::mock_preference( 'AcqCreateItem', 'receiving' ); my $duplicated_order = $order_no_sub->duplicate_to($basket_to); - is( $duplicated_order->items->count, 0, + is( + $duplicated_order->items->count, 0, 'Items should not be copied if the original order did not create items on ordering' ); $duplicated_order = $order_from_sub->duplicate_to($basket_to); - is( $duplicated_order->items->count, 0, + is( + $duplicated_order->items->count, 0, 'Items should not be copied if the original order is created from a subscription' ); }; @@ -265,15 +272,17 @@ subtest 'duplicate_to | add_item' => sub { subtest 'Create item on ordering' => sub { plan tests => 2; - t::lib::Mocks::mock_preference('AcqCreateItem', 'ordering'); + t::lib::Mocks::mock_preference( 'AcqCreateItem', 'ordering' ); my $duplicated_order = $order_no_sub->duplicate_to($basket_to); - is( $duplicated_order->items->count, 1, + is( + $duplicated_order->items->count, 1, 'Items should be copied if items are created on ordering' ); $duplicated_order = $order_from_sub->duplicate_to($basket_to); - is( $duplicated_order->items->count, 0, + is( + $duplicated_order->items->count, 0, 'Items should never be copied if the original order is created from a subscription' ); }; @@ -282,7 +291,7 @@ subtest 'duplicate_to | add_item' => sub { plan tests => 1; my $duplicated_order = $order_no_sub->duplicate_to($basket_to); - is($duplicated_order->invoiceid, undef, "invoiceid should be set to null for a new duplicated order"); + is( $duplicated_order->invoiceid, undef, "invoiceid should be set to null for a new duplicated order" ); }; $schema->storage->txn_rollback; @@ -318,6 +327,7 @@ subtest 'current_item_level_holds() tests' => sub { itemnumber => $item_2->itemnumber, } ); + # Add a hold in the future C4::Reserves::AddReserve( { @@ -333,29 +343,27 @@ subtest 'current_item_level_holds() tests' => sub { my $order = $builder->build_object( { class => 'Koha::Acquisition::Orders', - value => { - biblionumber => undef - } + value => { biblionumber => undef } } ); my $holds = $order->current_item_level_holds; - is( ref($holds), 'Koha::Holds', 'Koha::Holds iterator returned if no linked biblio' ); - is( $holds->count, 0, 'Count is 0 if no linked biblio' ); + is( ref($holds), 'Koha::Holds', 'Koha::Holds iterator returned if no linked biblio' ); + is( $holds->count, 0, 'Count is 0 if no linked biblio' ); - $order->set({ biblionumber => $biblio->biblionumber })->store->discard_changes; + $order->set( { biblionumber => $biblio->biblionumber } )->store->discard_changes; $holds = $order->current_item_level_holds; - is( ref($holds), 'Koha::Holds', 'Koha::Holds iterator returned if no linked items' ); - is( $holds->count, 0, 'Count is 0 if no linked items' ); + is( ref($holds), 'Koha::Holds', 'Koha::Holds iterator returned if no linked items' ); + is( $holds->count, 0, 'Count is 0 if no linked items' ); $order->add_item( $item_2->itemnumber ); $order->add_item( $item_3->itemnumber ); $holds = $order->current_item_level_holds; - is( $holds->count, 1, 'Only current (not future) holds are returned'); + is( $holds->count, 1, 'Only current (not future) holds are returned' ); $schema->storage->txn_rollback; }; @@ -371,19 +379,19 @@ subtest 'claim*' => sub { ); my $now = dt_from_string; - is( $order->claims->count, 0, 'No claim yet, ->claims should return an empty set'); - is( $order->claims_count, 0, 'No claim yet, ->claims_count should return 0'); - is( $order->claimed_date, undef, 'No claim yet, ->claimed_date should return undef'); + is( $order->claims->count, 0, 'No claim yet, ->claims should return an empty set' ); + is( $order->claims_count, 0, 'No claim yet, ->claims_count should return 0' ); + is( $order->claimed_date, undef, 'No claim yet, ->claimed_date should return undef' ); my $claim_1 = $order->claim; my $claim_2 = $order->claim; - $claim_1->claimed_on($now->clone->subtract(days => 1))->store; + $claim_1->claimed_on( $now->clone->subtract( days => 1 ) )->store; $claim_2->claimed_on($now)->store; - is( $order->claims->count, 2, '->claims should return the correct number of claims'); - is( $order->claims_count, 2, '->claims_count should return the correct number of claims'); - is( dt_from_string($order->claimed_date), $now, '->claimed_date should return the date of the last claim'); + is( $order->claims->count, 2, '->claims should return the correct number of claims' ); + is( $order->claims_count, 2, '->claims_count should return the correct number of claims' ); + is( dt_from_string( $order->claimed_date ), $now, '->claimed_date should return the date of the last claim' ); $schema->storage->txn_rollback; }; @@ -538,27 +546,22 @@ subtest 'filter_by_late' => sub { $late_orders = $orders->filter_by_lates( { delay => 6 } ); is( $late_orders->count, 0 ); - $late_orders = $orders->filter_by_lates( - { estimated_from => $now->clone->subtract( days => 6 ) } ); + $late_orders = $orders->filter_by_lates( { estimated_from => $now->clone->subtract( days => 6 ) } ); is( $late_orders->count, 2 ); is( $late_orders->next->ordernumber, $order_3->ordernumber ); - $late_orders = $orders->filter_by_lates( - { estimated_from => $now->clone->subtract( days => 5 ) } ); + $late_orders = $orders->filter_by_lates( { estimated_from => $now->clone->subtract( days => 5 ) } ); is( $late_orders->count, 2 ); is( $late_orders->next->ordernumber, $order_3->ordernumber ); - $late_orders = $orders->filter_by_lates( - { estimated_from => $now->clone->subtract( days => 4 ) } ); + $late_orders = $orders->filter_by_lates( { estimated_from => $now->clone->subtract( days => 4 ) } ); is( $late_orders->count, 2 ); is( $late_orders->next->ordernumber, $order_3->ordernumber ); - $late_orders = $orders->filter_by_lates( - { estimated_from => $now->clone->subtract( days => 3 ) } ); + $late_orders = $orders->filter_by_lates( { estimated_from => $now->clone->subtract( days => 3 ) } ); is( $late_orders->count, 2 ); - $late_orders = $orders->filter_by_lates( - { estimated_from => $now->clone->subtract( days => 1 ) } ); + $late_orders = $orders->filter_by_lates( { estimated_from => $now->clone->subtract( days => 1 ) } ); is( $late_orders->count, 1 ); $late_orders = $orders->filter_by_lates( @@ -606,7 +609,7 @@ subtest 'filter_out_cancelled & filter_by_cancelled' => sub { plan tests => 2; $schema->storage->txn_begin; - my $now = dt_from_string; + my $now = dt_from_string; my $order_1 = $builder->build_object( { class => 'Koha::Acquisition::Orders', @@ -643,9 +646,8 @@ subtest 'filter_out_cancelled & filter_by_cancelled' => sub { } ); - is( $orders->filter_out_cancelled->count, 2); - is( $orders->filter_by_cancelled->count, 1); - + is( $orders->filter_out_cancelled->count, 2 ); + is( $orders->filter_by_cancelled->count, 1 ); $schema->storage->txn_rollback; }; @@ -655,12 +657,13 @@ subtest 'creator ()' => sub { $schema->storage->txn_begin; - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); - my $order = $builder->build_object({ class => 'Koha::Acquisition::Orders', value => { created_by => $patron->borrowernumber } }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + my $order = $builder->build_object( + { class => 'Koha::Acquisition::Orders', value => { created_by => $patron->borrowernumber } } ); my $creator = $order->creator; - is($creator->borrowernumber, $patron->borrowernumber, 'Patron is order creator'); + is( $creator->borrowernumber, $patron->borrowernumber, 'Patron is order creator' ); $creator->delete; @@ -707,21 +710,22 @@ subtest 'cancel() tests' => sub { value => { branchcode => $item->homebranch, flags => 1 } } ); - t::lib::Mocks::mock_userenv({ patron => $patron }); + t::lib::Mocks::mock_userenv( { patron => $patron } ); # Add a checkout so deleting the item fails because od 'book_on_loan' C4::Circulation::AddIssue( $patron, $item->barcode ); - my $result = $order->cancel({ reason => $reason }); + my $result = $order->cancel( { reason => $reason } ); + # refresh the order object $order->discard_changes; - is( $result, $order, 'self is returned' ); + is( $result, $order, 'self is returned' ); is( $order->orderstatus, 'cancelled', 'Order is not marked as cancelled' ); isnt( $order->datecancellationprinted, undef, 'datecancellationprinted is not undef' ); - is( $order->cancellationreason, $reason, 'cancellationreason is set' ); - is( ref(Koha::Items->find($item->id)), 'Koha::Item', 'The item is present' ); - is( ref(Koha::Biblios->find($biblio_id)), 'Koha::Biblio', 'The biblio is present' ); + is( $order->cancellationreason, $reason, 'cancellationreason is set' ); + is( ref( Koha::Items->find( $item->id ) ), 'Koha::Item', 'The item is present' ); + is( ref( Koha::Biblios->find($biblio_id) ), 'Koha::Biblio', 'The biblio is present' ); my @messages = @{ $order->object_messages }; is( $messages[0]->message, 'error_delitem', 'An error message is attached to the order' ); @@ -735,15 +739,14 @@ subtest 'cancel() tests' => sub { C4::Circulation::AddReturn( $item->barcode ); - $order = Koha::Acquisition::Orders->find($order->ordernumber); - $order->cancel({ reason => $reason }) - ->discard_changes; + $order = Koha::Acquisition::Orders->find( $order->ordernumber ); + $order->cancel( { reason => $reason } )->discard_changes; is( $order->orderstatus, 'cancelled', 'Order is marked as cancelled' ); isnt( $order->datecancellationprinted, undef, 'datecancellationprinted is set' ); - is( $order->cancellationreason, $reason, 'cancellationreason is undef' ); - is( Koha::Items->find($item->id), undef, 'The item is no longer present' ); - is( ref(Koha::Biblios->find($biblio_id)), 'Koha::Biblio', 'The biblio is present' ); + is( $order->cancellationreason, $reason, 'cancellationreason is undef' ); + is( Koha::Items->find( $item->id ), undef, 'The item is no longer present' ); + is( ref( Koha::Biblios->find($biblio_id) ), 'Koha::Biblio', 'The biblio is present' ); @messages = @{ $order->object_messages }; is( scalar @messages, 0, 'No messages' ); @@ -757,8 +760,8 @@ subtest 'cancel() tests' => sub { my $item_1 = $builder->build_sample_item; $biblio_id = $item_1->biblionumber; - my $item_2 = $builder->build_sample_item({ biblionumber => $biblio_id }); - $order = $builder->build_object( + my $item_2 = $builder->build_sample_item( { biblionumber => $biblio_id } ); + $order = $builder->build_object( { class => 'Koha::Acquisition::Orders', value => { @@ -771,15 +774,14 @@ subtest 'cancel() tests' => sub { ); $order->add_item( $item_1->id ); - $order->cancel({ reason => $reason, delete_biblio => 1 }) - ->discard_changes; + $order->cancel( { reason => $reason, delete_biblio => 1 } )->discard_changes; is( $order->orderstatus, 'cancelled', 'Order is marked as cancelled' ); isnt( $order->datecancellationprinted, undef, 'datecancellationprinted is set' ); - is( $order->cancellationreason, $reason, 'cancellationreason is undef' ); - is( Koha::Items->find($item_1->id), undef, 'The item is no longer present' ); - is( ref(Koha::Items->find($item_2->id)), 'Koha::Item', 'The item is still present' ); - is( ref(Koha::Biblios->find($biblio_id)), 'Koha::Biblio', 'The biblio is still present' ); + is( $order->cancellationreason, $reason, 'cancellationreason is undef' ); + is( Koha::Items->find( $item_1->id ), undef, 'The item is no longer present' ); + is( ref( Koha::Items->find( $item_2->id ) ), 'Koha::Item', 'The item is still present' ); + is( ref( Koha::Biblios->find($biblio_id) ), 'Koha::Biblio', 'The biblio is still present' ); @messages = @{ $order->object_messages }; is( $messages[0]->message, 'error_delbiblio_items', 'Cannot delete biblio and it gets notified' ); @@ -819,14 +821,13 @@ subtest 'cancel() tests' => sub { } ); - $order->cancel({ reason => $reason, delete_biblio => 1 }) - ->discard_changes; + $order->cancel( { reason => $reason, delete_biblio => 1 } )->discard_changes; is( $order->orderstatus, 'cancelled', 'Order is marked as cancelled' ); isnt( $order->datecancellationprinted, undef, 'datecancellationprinted is set' ); - is( $order->cancellationreason, $reason, 'cancellationreason is undef' ); - is( Koha::Items->find($item->id), undef, 'The item is no longer present' ); - is( ref(Koha::Biblios->find($biblio_id)), 'Koha::Biblio', 'The biblio is still present' ); + is( $order->cancellationreason, $reason, 'cancellationreason is undef' ); + is( Koha::Items->find( $item->id ), undef, 'The item is no longer present' ); + is( ref( Koha::Biblios->find($biblio_id) ), 'Koha::Biblio', 'The biblio is still present' ); @messages = @{ $order->object_messages }; is( $messages[0]->message, 'error_delbiblio_uncancelled_orders', 'Cannot delete biblio and it gets notified' ); @@ -863,14 +864,13 @@ subtest 'cancel() tests' => sub { } ); - $order->cancel({ reason => $reason, delete_biblio => 1 }) - ->discard_changes; + $order->cancel( { reason => $reason, delete_biblio => 1 } )->discard_changes; is( $order->orderstatus, 'cancelled', 'Order is marked as cancelled' ); isnt( $order->datecancellationprinted, undef, 'datecancellationprinted is set' ); - is( $order->cancellationreason, $reason, 'cancellationreason is undef' ); - is( Koha::Items->find($item->id), undef, 'The item is no longer present' ); - is( ref(Koha::Biblios->find($biblio_id)), 'Koha::Biblio', 'The biblio is still present' ); + is( $order->cancellationreason, $reason, 'cancellationreason is undef' ); + is( Koha::Items->find( $item->id ), undef, 'The item is no longer present' ); + is( ref( Koha::Biblios->find($biblio_id) ), 'Koha::Biblio', 'The biblio is still present' ); @messages = @{ $order->object_messages }; is( $messages[0]->message, 'error_delbiblio_subscriptions', 'Cannot delete biblio and it gets notified' ); @@ -896,14 +896,13 @@ subtest 'cancel() tests' => sub { ); $order->add_item( $item->id ); - $order->cancel({ reason => $reason, delete_biblio => 1 }) - ->discard_changes; + $order->cancel( { reason => $reason, delete_biblio => 1 } )->discard_changes; is( $order->orderstatus, 'cancelled', 'Order is not marked as cancelled' ); isnt( $order->datecancellationprinted, undef, 'datecancellationprinted is not undef' ); - is( $order->cancellationreason, $reason, 'cancellationreason is set' ); - is( Koha::Items->find($item->id), undef, 'The item is not present' ); - is( Koha::Biblios->find($biblio_id), undef, 'The biblio is not present' ); + is( $order->cancellationreason, $reason, 'cancellationreason is set' ); + is( Koha::Items->find( $item->id ), undef, 'The item is not present' ); + is( Koha::Biblios->find($biblio_id), undef, 'The biblio is not present' ); @messages = @{ $order->object_messages }; is( scalar @messages, 0, 'No errors' ); @@ -920,10 +919,10 @@ subtest 'cancel() tests' => sub { { class => 'Koha::Suggestions', value => { - biblionumber => $biblio_id, + biblionumber => $biblio_id, suggesteddate => dt_from_string, - STATUS => 'ORDERED', - archived => 0, + STATUS => 'ORDERED', + archived => 0, } } ); @@ -940,13 +939,12 @@ subtest 'cancel() tests' => sub { } ); - $order->cancel({ reason => $reason }) - ->discard_changes; + $order->cancel( { reason => $reason } )->discard_changes; $suggestion = Koha::Suggestions->find( $suggestion->id ); is( $order->orderstatus, 'cancelled', 'Order is marked as cancelled' ); - is( $suggestion->STATUS, 'ACCEPTED', 'Suggestion status is correctly reverted after order is cancelled' ); + is( $suggestion->STATUS, 'ACCEPTED', 'Suggestion status is correctly reverted after order is cancelled' ); # Scenario: # * order with two items attached @@ -958,9 +956,9 @@ subtest 'cancel() tests' => sub { # => biblio delete error notified # => item delete error notified - $item_1 = $builder->build_sample_item; - $item_2 = $builder->build_sample_item({ biblionumber => $item_1->biblionumber }); - my $item_3 = $builder->build_sample_item({ biblionumber => $item_1->biblionumber }); + $item_1 = $builder->build_sample_item; + $item_2 = $builder->build_sample_item( { biblionumber => $item_1->biblionumber } ); + my $item_3 = $builder->build_sample_item( { biblionumber => $item_1->biblionumber } ); $biblio_id = $item_1->biblionumber; $order = $builder->build_object( { @@ -989,37 +987,38 @@ subtest 'cancel() tests' => sub { } ); - $order->cancel({ reason => $reason, delete_biblio => 1 }) - ->discard_changes; + $order->cancel( { reason => $reason, delete_biblio => 1 } )->discard_changes; is( $order->orderstatus, 'cancelled', 'Order is marked as cancelled' ); isnt( $order->datecancellationprinted, undef, 'datecancellationprinted is set' ); - is( $order->cancellationreason, $reason, 'cancellationreason is undef' ); - is( Koha::Items->find($item_1->id), undef, 'The item is no longer present' ); - is( ref(Koha::Items->find($item_2->id)), 'Koha::Item', 'The on loan item is still present' ); - is( ref(Koha::Biblios->find($biblio_id)), 'Koha::Biblio', 'The biblio is still present' ); + is( $order->cancellationreason, $reason, 'cancellationreason is undef' ); + is( Koha::Items->find( $item_1->id ), undef, 'The item is no longer present' ); + is( ref( Koha::Items->find( $item_2->id ) ), 'Koha::Item', 'The on loan item is still present' ); + is( ref( Koha::Biblios->find($biblio_id) ), 'Koha::Biblio', 'The biblio is still present' ); @messages = @{ $order->object_messages }; - is( $messages[0]->message, 'error_delitem', 'Cannot delete on loan item' ); - is( $messages[0]->payload->{item}->id, $item_2->id, 'Cannot delete on loan item' ); - is( $messages[0]->payload->{reason}, 'book_on_loan', 'Item on loan notified' ); - is( $messages[1]->message, 'error_delitem', 'Cannot delete reserved and found item' ); - is( $messages[1]->payload->{item}->id, $item_3->id, 'Cannot delete reserved and found item' ); - is( $messages[1]->payload->{reason}, 'book_reserved', 'Item reserved notified' ); - is( $messages[2]->message, 'error_delbiblio_items', 'Cannot delete on loan item' ); - is( $messages[2]->payload->{biblio}->id, $biblio_id, 'The right biblio is attached' ); + is( $messages[0]->message, 'error_delitem', 'Cannot delete on loan item' ); + is( $messages[0]->payload->{item}->id, $item_2->id, 'Cannot delete on loan item' ); + is( $messages[0]->payload->{reason}, 'book_on_loan', 'Item on loan notified' ); + is( $messages[1]->message, 'error_delitem', 'Cannot delete reserved and found item' ); + is( $messages[1]->payload->{item}->id, $item_3->id, 'Cannot delete reserved and found item' ); + is( $messages[1]->payload->{reason}, 'book_reserved', 'Item reserved notified' ); + is( $messages[2]->message, 'error_delbiblio_items', 'Cannot delete on loan item' ); + is( $messages[2]->payload->{biblio}->id, $biblio_id, 'The right biblio is attached' ); # Call ->store with biblionumber NULL (as ->cancel does) - $item_1 = $builder->build_sample_item; + $item_1 = $builder->build_sample_item; $biblio_id = $item_1->biblionumber; - $order= $builder->build_object({ - class => 'Koha::Acquisition::Orders', - value => { - orderstatus => 'new', - biblionumber => $biblio_id, - datecancellationprinted => undef, - cancellationreason => undef, + $order = $builder->build_object( + { + class => 'Koha::Acquisition::Orders', + value => { + orderstatus => 'new', + biblionumber => $biblio_id, + datecancellationprinted => undef, + cancellationreason => undef, + } } - }); + ); my $columns = { biblionumber => undef, cancellationreason => $reason, @@ -1027,7 +1026,8 @@ subtest 'cancel() tests' => sub { orderstatus => 'cancelled', }; lives_ok { $order->set($columns)->store; } 'No croak on missing biblionumber when cancelling an order'; - throws_ok { $order->orderstatus('new')->store; } qr/Cannot insert order: Mandatory parameter biblionumber is missing/, 'Expected croak'; + throws_ok { $order->orderstatus('new')->store; } + qr/Cannot insert order: Mandatory parameter biblionumber is missing/, 'Expected croak'; # Try to cancel again, not overwriting cancellation date my $dt = dt_from_string->subtract( days => 1 ); diff --git a/t/db_dependent/Koha/Acquisition/Orders.t b/t/db_dependent/Koha/Acquisition/Orders.t index a8bca21a8f..707c8f5082 100755 --- a/t/db_dependent/Koha/Acquisition/Orders.t +++ b/t/db_dependent/Koha/Acquisition/Orders.t @@ -108,17 +108,15 @@ subtest 'filter_by_active() tests' => sub { $order_6->ordernumber, ] }, - { - order_by => 'ordernumber' - } + { order_by => 'ordernumber' } ); my $rs = $this_orders_rs->filter_by_active; - is( $rs->count, 3, 'Only new (basket is standing), ordered and partial orders are returned' ); - is( $rs->next->ordernumber, $order_3->ordernumber , 'Expected order in resultset' ); - is( $rs->next->ordernumber, $order_4->ordernumber , 'Expected order in resultset' ); - is( $rs->next->ordernumber, $order_5->ordernumber , 'Expected order in resultset' ); + is( $rs->count, 3, 'Only new (basket is standing), ordered and partial orders are returned' ); + is( $rs->next->ordernumber, $order_3->ordernumber, 'Expected order in resultset' ); + is( $rs->next->ordernumber, $order_4->ordernumber, 'Expected order in resultset' ); + is( $rs->next->ordernumber, $order_5->ordernumber, 'Expected order in resultset' ); # If we change quantities on order_5 (partial), we should no longer see it $order_5->quantityreceived(2)->store; @@ -133,9 +131,9 @@ subtest 'filter_by_id_including_transfers() tests' => sub { $schema->storage->txn_begin; - my $order_1 = $builder->build_object({ class => 'Koha::Acquisition::Orders' }); - my $order_2 = $builder->build_object({ class => 'Koha::Acquisition::Orders' }); - my $order_3 = $builder->build_object({ class => 'Koha::Acquisition::Orders' }); + my $order_1 = $builder->build_object( { class => 'Koha::Acquisition::Orders' } ); + my $order_2 = $builder->build_object( { class => 'Koha::Acquisition::Orders' } ); + my $order_3 = $builder->build_object( { class => 'Koha::Acquisition::Orders' } ); $builder->build( { @@ -148,20 +146,22 @@ subtest 'filter_by_id_including_transfers() tests' => sub { ); my $orders_rs = Koha::Acquisition::Orders->search; - my $count = $orders_rs->count; + my $count = $orders_rs->count; - throws_ok - { $orders_rs->filter_by_id_including_transfers() } - 'Koha::Exceptions::MissingParameter', + throws_ok { $orders_rs->filter_by_id_including_transfers() } + 'Koha::Exceptions::MissingParameter', 'Exception thrown correctly'; - $orders_rs = $orders_rs->filter_by_id_including_transfers({ ordernumber => $order_1->ordernumber }); + $orders_rs = $orders_rs->filter_by_id_including_transfers( { ordernumber => $order_1->ordernumber } ); - is_deeply( [ sort { $a <=> $b } $orders_rs->get_column('ordernumber') ], [$order_1->ordernumber, $order_2->ordernumber ], 'The 2 orders are returned' ); + is_deeply( + [ sort { $a <=> $b } $orders_rs->get_column('ordernumber') ], + [ $order_1->ordernumber, $order_2->ordernumber ], 'The 2 orders are returned' + ); - $orders_rs = $orders_rs->filter_by_id_including_transfers({ ordernumber => $order_2->ordernumber }); + $orders_rs = $orders_rs->filter_by_id_including_transfers( { ordernumber => $order_2->ordernumber } ); - is( $orders_rs->count, 1, 'Only one order related to the specified ordernumber' ); + is( $orders_rs->count, 1, 'Only one order related to the specified ordernumber' ); is( $orders_rs->next->ordernumber, $order_2->ordernumber, 'The right order is returned' ); $schema->storage->txn_rollback; diff --git a/t/db_dependent/Koha/ActionLogs.t b/t/db_dependent/Koha/ActionLogs.t index ede7e0cc5e..5131f76e63 100755 --- a/t/db_dependent/Koha/ActionLogs.t +++ b/t/db_dependent/Koha/ActionLogs.t @@ -27,7 +27,7 @@ use Koha::DateUtils qw( dt_from_string ); use t::lib::TestBuilder; BEGIN { - use_ok('Koha::ActionLogs'); + use_ok('Koha::ActionLogs'); } my $schema = Koha::Database->new->schema; @@ -39,21 +39,25 @@ subtest 'store() tests' => sub { $schema->storage->txn_begin; my $logs_count = Koha::ActionLogs->count; - my $log = Koha::ActionLog->new({ - module => 'CIRCULATION', - action => 'ISSUE', - interface => 'intranet', - })->store; + my $log = Koha::ActionLog->new( + { + module => 'CIRCULATION', + action => 'ISSUE', + interface => 'intranet', + } + )->store; $log->discard_changes; - is( ref($log), 'Koha::ActionLog', 'Log object creation success'); - is( Koha::ActionLogs->count, $logs_count + 1, 'Exactly one log was saved'); + is( ref($log), 'Koha::ActionLog', 'Log object creation success' ); + is( Koha::ActionLogs->count, $logs_count + 1, 'Exactly one log was saved' ); my $yesterday = dt_from_string->subtract( days => 1 ); $log->timestamp($yesterday)->store; $log->info("a new info")->store; # Must be 2 different store calls - is( dt_from_string( $log->get_from_storage->timestamp ), $yesterday, - 'timestamp column should not be updated to current_timestamp' ); + is( + dt_from_string( $log->get_from_storage->timestamp ), $yesterday, + 'timestamp column should not be updated to current_timestamp' + ); $schema->storage->txn_rollback; }; @@ -63,13 +67,18 @@ subtest 'search() tests' => sub { $schema->storage->txn_begin; - my $patron1 = $builder->build_object({ - class => 'Koha::Patrons', - }); + my $patron1 = $builder->build_object( + { + class => 'Koha::Patrons', + } + ); - logaction("MEMBERS", "MODIFY", $patron1->borrowernumber, "test"); + logaction( "MEMBERS", "MODIFY", $patron1->borrowernumber, "test" ); - is(Koha::ActionLogs->search({ object => $patron1->borrowernumber })->count, 1, 'search() return right number of action logs'); + is( + Koha::ActionLogs->search( { object => $patron1->borrowernumber } )->count, 1, + 'search() return right number of action logs' + ); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/Koha/AdditionalContents.t b/t/db_dependent/Koha/AdditionalContents.t index b2170126b6..6fc01677c0 100755 --- a/t/db_dependent/Koha/AdditionalContents.t +++ b/t/db_dependent/Koha/AdditionalContents.t @@ -28,7 +28,7 @@ use Koha::DateUtils qw( dt_from_string ); use t::lib::TestBuilder; -my $schema = Koha::Database->new->schema; +my $schema = Koha::Database->new->schema; my $builder = t::lib::TestBuilder->new; subtest 'Koha::AdditionalContents basic test' => sub { @@ -37,8 +37,8 @@ subtest 'Koha::AdditionalContents basic test' => sub { $schema->storage->txn_begin; - my $library = $builder->build({ source => 'Branch'}); - my $nb_of_news = Koha::AdditionalContents->search->count; + my $library = $builder->build( { source => 'Branch' } ); + my $nb_of_news = Koha::AdditionalContents->search->count; my $new_news_item_1 = Koha::AdditionalContent->new( { category => 'news', @@ -107,31 +107,37 @@ subtest '->is_expired' => sub { $schema->storage->txn_begin; - my $today = dt_from_string; + my $today = dt_from_string; my $yesterday = dt_from_string->add( days => -1 ); - my $tomorrow = dt_from_string->add( days => 1 ); - my $new_today = $builder->build_object({ - class => 'Koha::AdditionalContents', - value => { - expirationdate => $today, + my $tomorrow = dt_from_string->add( days => 1 ); + my $new_today = $builder->build_object( + { + class => 'Koha::AdditionalContents', + value => { + expirationdate => $today, + } } - }); - my $new_expired = $builder->build_object({ - class => 'Koha::AdditionalContents', - value => { - expirationdate => $yesterday, + ); + my $new_expired = $builder->build_object( + { + class => 'Koha::AdditionalContents', + value => { + expirationdate => $yesterday, + } } - }); - my $new_not_expired = $builder->build_object({ - class => 'Koha::AdditionalContents', - value => { - expirationdate => $tomorrow, + ); + my $new_not_expired = $builder->build_object( + { + class => 'Koha::AdditionalContents', + value => { + expirationdate => $tomorrow, + } } - }); + ); - ok($new_expired->is_expired, 'Expired new is expired'); - ok(!$new_not_expired->is_expired, 'Not expired new is not expired'); - ok(!$new_today->is_expired, 'Today expiration date means the new is not expired'); + ok( $new_expired->is_expired, 'Expired new is expired' ); + ok( !$new_not_expired->is_expired, 'Not expired new is not expired' ); + ok( !$new_today->is_expired, 'Today expiration date means the new is not expired' ); $schema->storage->txn_rollback; }; @@ -142,25 +148,25 @@ subtest '->library' => sub { $schema->storage->txn_begin; - my $library = $builder->build_object({ class => 'Koha::Libraries' }); + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); - my $new_with_library = $builder->build_object({ - class => 'Koha::AdditionalContents', - value => { - branchcode => $library->branchcode + my $new_with_library = $builder->build_object( + { + class => 'Koha::AdditionalContents', + value => { branchcode => $library->branchcode } } - }); - my $new_without_library = $builder->build_object({ - class => 'Koha::AdditionalContents', - value => { - branchcode => undef + ); + my $new_without_library = $builder->build_object( + { + class => 'Koha::AdditionalContents', + value => { branchcode => undef } } - }); + ); - ok($new_with_library->library, 'News item with library have library relation'); - is($new_with_library->library->branchcode, $library->branchcode, 'The library linked with new item is right'); + ok( $new_with_library->library, 'News item with library have library relation' ); + is( $new_with_library->library->branchcode, $library->branchcode, 'The library linked with new item is right' ); - ok(!$new_without_library->library, 'New item without library does not have library relation'); + ok( !$new_without_library->library, 'New item without library does not have library relation' ); $schema->storage->txn_rollback; }; @@ -170,15 +176,15 @@ subtest '->author' => sub { $schema->storage->txn_begin; - my $news_item = $builder->build_object({ class => 'Koha::AdditionalContents' }); - my $author = $news_item->author; + my $news_item = $builder->build_object( { class => 'Koha::AdditionalContents' } ); + my $author = $news_item->author; is( ref($author), 'Koha::Patron', 'Koha::AdditionalContent->author returns a Koha::Patron object' ); $author->delete; $news_item = Koha::AdditionalContents->find( $news_item->id ); - is( ref($news_item), 'Koha::AdditionalContent', 'News are not deleted alongwith the author' ); - is( $news_item->author, undef, '->author returns undef is the author has been deleted' ); + is( ref($news_item), 'Koha::AdditionalContent', 'News are not deleted alongwith the author' ); + is( $news_item->author, undef, '->author returns undef is the author has been deleted' ); $schema->storage->txn_rollback; }; @@ -191,97 +197,109 @@ subtest '->search_for_display' => sub { Koha::AdditionalContents->search->delete; - my $today = dt_from_string; + my $today = dt_from_string; my $yesterday = dt_from_string->add( days => -1 ); - my $tomorrow = dt_from_string->add( days => 1 ); - my $library1 = $builder->build_object({ class => 'Koha::Libraries' }); - my $library2 = $builder->build_object({ class => 'Koha::Libraries' }); + my $tomorrow = dt_from_string->add( days => 1 ); + my $library1 = $builder->build_object( { class => 'Koha::Libraries' } ); + my $library2 = $builder->build_object( { class => 'Koha::Libraries' } ); - my $new_expired = $builder->build_object({ - class => 'Koha::AdditionalContents', - value => { - expirationdate => $yesterday, - published_on => $today, - category => 'news', - location => 'staff_and_opac', - branchcode => undef, - number => 1, + my $new_expired = $builder->build_object( + { + class => 'Koha::AdditionalContents', + value => { + expirationdate => $yesterday, + published_on => $today, + category => 'news', + location => 'staff_and_opac', + branchcode => undef, + number => 1, + } } - }); + ); $new_expired->translated_contents( [ { lang => 'default', content => '' } ] ); - my $new_not_expired = $builder->build_object({ - class => 'Koha::AdditionalContents', - value => { - expirationdate => $tomorrow, - published_on => $today, - category => 'news', - location => 'staff_and_opac', - branchcode => undef, - number => 2, + my $new_not_expired = $builder->build_object( + { + class => 'Koha::AdditionalContents', + value => { + expirationdate => $tomorrow, + published_on => $today, + category => 'news', + location => 'staff_and_opac', + branchcode => undef, + number => 2, + } } - }); + ); $new_not_expired->translated_contents( [ { lang => 'default', content => '' } ] ); - my $new_not_active = $builder->build_object({ - class => 'Koha::AdditionalContents', - value => { - expirationdate => $tomorrow, - published_on => $tomorrow, - category => 'news', - location => 'staff_and_opac', - branchcode => undef, - number => 3, + my $new_not_active = $builder->build_object( + { + class => 'Koha::AdditionalContents', + value => { + expirationdate => $tomorrow, + published_on => $tomorrow, + category => 'news', + location => 'staff_and_opac', + branchcode => undef, + number => 3, + } } - }); + ); $new_not_active->translated_contents( [ { lang => 'default', content => '' } ] ); - my $new_slip= $builder->build_object({ - class => 'Koha::AdditionalContents', - value => { - expirationdate => $tomorrow, - published_on => $today, - category => 'news', - location => 'staff_only', - branchcode => $library1->branchcode, - number => 4, + my $new_slip = $builder->build_object( + { + class => 'Koha::AdditionalContents', + value => { + expirationdate => $tomorrow, + published_on => $today, + category => 'news', + location => 'staff_only', + branchcode => $library1->branchcode, + number => 4, + } } - }); + ); $new_slip->translated_contents( [ { lang => 'default', content => '' } ] ); - my $new_intra = $builder->build_object({ - class => 'Koha::AdditionalContents', - value => { - expirationdate => $tomorrow, - published_on => $today, - category => 'news', - location => 'staff_only', - branchcode => $library2->branchcode, - number => 5, + my $new_intra = $builder->build_object( + { + class => 'Koha::AdditionalContents', + value => { + expirationdate => $tomorrow, + published_on => $today, + category => 'news', + location => 'staff_only', + branchcode => $library2->branchcode, + number => 5, + } } - }); + ); $new_intra->translated_contents( [ { lang => 'default', content => '' } ] ); - my $new_intra2 = $builder->build_object({ - class => 'Koha::AdditionalContents', - value => { - expirationdate => $tomorrow, - published_on => $today, - category => 'news', - location => 'staff_only', - branchcode => undef, - number => 5, + my $new_intra2 = $builder->build_object( + { + class => 'Koha::AdditionalContents', + value => { + expirationdate => $tomorrow, + published_on => $today, + category => 'news', + location => 'staff_only', + branchcode => undef, + number => 5, + } } - }); + ); $new_intra2->translated_contents( [ { lang => 'default', content => '' } ] ); - my $news = Koha::AdditionalContents->search_for_display({ location => 'staff_only' }); - is($news->count, 1, "There is 1 news for all staff"); + my $news = Koha::AdditionalContents->search_for_display( { location => 'staff_only' } ); + is( $news->count, 1, "There is 1 news for all staff" ); $news = Koha::AdditionalContents->search_for_display( { location => 'staff_only', library_id => $library1->branchcode } ); is( $news->count, 2, "There are 2 news for staff at library1" ); - $news = Koha::AdditionalContents->search_for_display({ location => 'opac_only' }); - is($news->count, 0, "There are 0 news for OPAC only"); + $news = Koha::AdditionalContents->search_for_display( { location => 'opac_only' } ); + is( $news->count, 0, "There are 0 news for OPAC only" ); - $news = Koha::AdditionalContents->search_for_display({ location => 'staff_and_opac' }); - is($news->count, 1, "There is 1 news for all staff and all OPAC "); + $news = Koha::AdditionalContents->search_for_display( { location => 'staff_and_opac' } ); + is( $news->count, 1, "There is 1 news for all staff and all OPAC " ); # TODO We should add more tests here diff --git a/t/db_dependent/Koha/AdditionalField.t b/t/db_dependent/Koha/AdditionalField.t index b369dc7ce2..2c6955fca5 100755 --- a/t/db_dependent/Koha/AdditionalField.t +++ b/t/db_dependent/Koha/AdditionalField.t @@ -18,65 +18,71 @@ subtest 'effective_authorised_value_category' => sub { $schema->txn_begin; - my $av_category_name = random_string('C' x 32); - my $av_category = Koha::AuthorisedValueCategory->new({ category_name => $av_category_name }); + my $av_category_name = random_string( 'C' x 32 ); + my $av_category = Koha::AuthorisedValueCategory->new( { category_name => $av_category_name } ); $av_category->store()->discard_changes(); my $field = Koha::AdditionalField->new( { - tablename => random_string('c' x 100), - name => random_string('c' x 100), + tablename => random_string( 'c' x 100 ), + name => random_string( 'c' x 100 ), } ); $field->store()->discard_changes(); - is($field->effective_authorised_value_category, undef, 'no default category'); + is( $field->effective_authorised_value_category, undef, 'no default category' ); $field = Koha::AdditionalField->new( { - tablename => random_string('c' x 100), - name => random_string('c' x 100), + tablename => random_string( 'c' x 100 ), + name => random_string( 'c' x 100 ), authorised_value_category => $av_category_name, } ); $field->store()->discard_changes(); - is($field->effective_authorised_value_category, $av_category_name, 'returns authorised_value_category if set'); + is( $field->effective_authorised_value_category, $av_category_name, 'returns authorised_value_category if set' ); my $mss = Koha::MarcSubfieldStructure->new( { - frameworkcode => '', - tagfield => '999', - tagsubfield => 'Z', + frameworkcode => '', + tagfield => '999', + tagsubfield => 'Z', authorised_value => $av_category_name, } ); $mss->store(); $field = Koha::AdditionalField->new( { - tablename => random_string('c' x 100), - name => random_string('c' x 100), + tablename => random_string( 'c' x 100 ), + name => random_string( 'c' x 100 ), marcfield => '999$Z', } ); $field->store()->discard_changes(); - is($field->effective_authorised_value_category, $av_category_name, 'returns MARC subfield authorised value category if set'); + is( + $field->effective_authorised_value_category, $av_category_name, + 'returns MARC subfield authorised value category if set' + ); - my $av2_category_name = random_string('C' x 32); - my $av2_category = Koha::AuthorisedValueCategory->new({ category_name => $av2_category_name }); + my $av2_category_name = random_string( 'C' x 32 ); + my $av2_category = Koha::AuthorisedValueCategory->new( { category_name => $av2_category_name } ); $av2_category->store()->discard_changes(); $field = Koha::AdditionalField->new( { - tablename => random_string('c' x 100), - name => random_string('c' x 100), + tablename => random_string( 'c' x 100 ), + name => random_string( 'c' x 100 ), authorised_value_category => $av2_category_name, - marcfield => '999$Z', + marcfield => '999$Z', } ); $field->store()->discard_changes(); - is($field->effective_authorised_value_category, $av2_category_name, 'returns authorised_value_category if both authorised_value_category and marcfield are set'); + is( + $field->effective_authorised_value_category, $av2_category_name, + 'returns authorised_value_category if both authorised_value_category and marcfield are set' + ); $schema->txn_rollback; }; diff --git a/t/db_dependent/Koha/ApiKey.t b/t/db_dependent/Koha/ApiKey.t index d9f46fce88..85ce8280b3 100755 --- a/t/db_dependent/Koha/ApiKey.t +++ b/t/db_dependent/Koha/ApiKey.t @@ -41,7 +41,7 @@ subtest 'store() tests' => sub { Koha::ApiKeys->search->delete; - my $patron_1 = $builder->build_object( { class => 'Koha::Patrons' } ); + my $patron_1 = $builder->build_object( { class => 'Koha::Patrons' } ); my $description = 'Coral API key'; my $api_key = Koha::ApiKey->new( @@ -56,15 +56,18 @@ subtest 'store() tests' => sub { is( ref($api_key), 'Koha::ApiKey' ); is( $api_key->patron_id, $patron_1->id, 'FK is matched' ); - ok( defined $api_key->client_id + ok( + defined $api_key->client_id && $api_key->client_id ne '' && length( $api_key->client_id ) > 1, 'API client_id is generated' ); - ok( defined $api_key->secret + ok( + defined $api_key->secret && $api_key->secret ne '' && length( $api_key->secret ) > 1, - 'API secret is generated' ); + 'API secret is generated' + ); is( $api_key->description, $description, 'Description is correctly stored' ); is( $api_key->active, 1, 'Key is active by default' ); @@ -74,11 +77,11 @@ subtest 'store() tests' => sub { $api_key->discard_changes; is( $api_key->client_id, $original_api_key->{client_id}, '->store() preserves the client_id' ); - is( $api_key->secret, $original_api_key->{secret}, '->store() preserves the secret' ); + is( $api_key->secret, $original_api_key->{secret}, '->store() preserves the secret' ); is( $api_key->patron_id, $original_api_key->{patron_id}, '->store() preserves the patron_id' ); - is( $api_key->active, 0, '->store() preserves the active value' ); + is( $api_key->active, 0, '->store() preserves the active value' ); - $api_key->set({ client_id => 'NewID!' }); + $api_key->set( { client_id => 'NewID!' } ); throws_ok { $api_key->store @@ -89,24 +92,23 @@ subtest 'store() tests' => sub { is( $@->property, 'client_id', 'Correct attribute reported back' ); $api_key->discard_changes; + # set a writeable attribute - $api_key->set({ description => 'Hey' }); + $api_key->set( { description => 'Hey' } ); lives_ok { $api_key->store } 'Updating a writeable attribute works'; my $patron_to_delete = $builder->build_object( { class => 'Koha::Patrons' } ); - my $deleted_id = $patron_to_delete->id; + my $deleted_id = $patron_to_delete->id; $patron_to_delete->delete; { # hide useless warnings local *STDERR; open STDERR, '>', '/dev/null'; throws_ok { - Koha::ApiKey->new( - { patron_id => $deleted_id, description => 'a description' } ) - ->store + Koha::ApiKey->new( { patron_id => $deleted_id, description => 'a description' } )->store } 'Koha::Exceptions::Object::FKConstraint', - 'Invalid patron ID raises exception'; + 'Invalid patron ID raises exception'; close STDERR; } is( $@->message, 'Broken FK constraint', 'Exception message is correct' ); @@ -123,15 +125,16 @@ subtest 'validate_secret() tests' => sub { my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $api_key = Koha::ApiKey->new( - { patron_id => $patron->id, + { + patron_id => $patron->id, description => 'The description' } )->store; my $secret = $api_key->plain_text_secret; - is( $api_key->validate_secret( $secret ), 1, 'Valid secret returns true' ); - is( $api_key->validate_secret( 'Wrong secret' ), 0, 'Invalid secret returns false' ); + is( $api_key->validate_secret($secret), 1, 'Valid secret returns true' ); + is( $api_key->validate_secret('Wrong secret'), 0, 'Invalid secret returns false' ); $schema->storage->txn_rollback; }; @@ -142,13 +145,14 @@ subtest 'plain_text_secret() tests' => sub { $schema->storage->txn_begin; - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + # generate a fresh API key - my $api_key = Koha::ApiKey->new({ description => 'blah', patron_id => $patron->id })->store; + my $api_key = Koha::ApiKey->new( { description => 'blah', patron_id => $patron->id } )->store; my $plain_text_secret = $api_key->plain_text_secret; ok( defined $plain_text_secret, 'A fresh API key carries its plain text secret' ); - ok( $plain_text_secret ne q{}, 'Plain text secret is not an empty string' ); + ok( $plain_text_secret ne q{}, 'Plain text secret is not an empty string' ); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/Koha/ArticleRequest.t b/t/db_dependent/Koha/ArticleRequest.t index 2d6819e763..f2feb3b3b1 100755 --- a/t/db_dependent/Koha/ArticleRequest.t +++ b/t/db_dependent/Koha/ArticleRequest.t @@ -58,8 +58,8 @@ subtest 'request() tests' => sub { is( $ar->status, Koha::ArticleRequest::Status::Requested ); ok( defined $ar->created_on, 'created_on is set' ); - is( $ar->debit_id, undef, 'No fee linked' ); - is( $patron->account->balance, 0, 'No outstanding fees' ); + is( $ar->debit_id, undef, 'No fee linked' ); + is( $patron->account->balance, 0, 'No outstanding fees' ); $patron->discard_changes; is( $patron->lastseen, undef, 'Patron activity not tracked when article is not a valid trigger' ); @@ -95,7 +95,7 @@ subtest 'set_pending() tests' => sub { $schema->storage->txn_begin; - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $biblio = $builder->build_sample_biblio; my $ar_mock = Test::MockModule->new('Koha::ArticleRequest'); @@ -126,7 +126,8 @@ subtest 'process() tests' => sub { $ar_mock->mock( 'notify', sub { ok( 1, '->notify() called' ); } ); my $ar = $builder->build_object( - { class => 'Koha::ArticleRequests', + { + class => 'Koha::ArticleRequests', value => { status => Koha::ArticleRequest::Status::Requested } } ); @@ -148,7 +149,8 @@ subtest 'complete() tests' => sub { $ar_mock->mock( 'notify', sub { ok( 1, '->notify() called' ); } ); my $ar = $builder->build_object( - { class => 'Koha::ArticleRequests', + { + class => 'Koha::ArticleRequests', value => { status => Koha::ArticleRequest::Status::Requested } } ); @@ -171,7 +173,7 @@ subtest 'cancel() tests' => sub { my $patron_mock = Test::MockModule->new('Koha::Patron'); $patron_mock->mock( 'article_request_fee', sub { return $amount; } ); - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $item = $builder->build_sample_item; my $ar_mock = Test::MockModule->new('Koha::ArticleRequest'); @@ -193,17 +195,17 @@ subtest 'cancel() tests' => sub { is( $patron->account->balance, $amount, 'Outstanding fees with the right value' ); my $payed_amount = 5; - $patron->account->pay({ amount => $payed_amount, interface => 'intranet', lines => [ $ar->debit ] }); + $patron->account->pay( { amount => $payed_amount, interface => 'intranet', lines => [ $ar->debit ] } ); is( $patron->account->balance, $amount - $payed_amount, 'Outstanding fees with the right value' ); my $reason = "Hey, ho"; my $notes = "Let's go!"; - $ar->cancel({ cancellation_reason => $reason, notes => $notes })->discard_changes; + $ar->cancel( { cancellation_reason => $reason, notes => $notes } )->discard_changes; - is( $ar->status, Koha::ArticleRequest::Status::Canceled ); + is( $ar->status, Koha::ArticleRequest::Status::Canceled ); is( $ar->cancellation_reason, $reason, 'Cancellation reason stored correctly' ); - is( $ar->notes, $notes, 'Notes stored correctly' ); + is( $ar->notes, $notes, 'Notes stored correctly' ); is( $patron->account->balance, -$payed_amount, 'The patron has a credit balance' ); diff --git a/t/db_dependent/Koha/ArticleRequests.t b/t/db_dependent/Koha/ArticleRequests.t index 1b240b6524..2b02f24d17 100755 --- a/t/db_dependent/Koha/ArticleRequests.t +++ b/t/db_dependent/Koha/ArticleRequests.t @@ -39,7 +39,8 @@ subtest 'requested() tests' => sub { my $library_1 = $builder->build_object( { class => 'Koha::Libraries' } ); my $library_2 = $builder->build_object( { class => 'Koha::Libraries' } ); - my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { branchcode => $library_1->id, flags => 1 } } ); + my $patron = + $builder->build_object( { class => 'Koha::Patrons', value => { branchcode => $library_1->id, flags => 1 } } ); t::lib::Mocks::mock_userenv( { patron => $patron } ); # FIXME: we moved past this pattern. This method should be refactored @@ -50,25 +51,28 @@ subtest 'requested() tests' => sub { $ar_mock->mock( 'notify', sub { ok( 1, '->notify() called' ); } ); my $ar_1 = $builder->build_object( - { class => 'Koha::ArticleRequests', + { + class => 'Koha::ArticleRequests', value => { status => Koha::ArticleRequest::Status::Requested, branchcode => $library_1->id } } ); my $ar_2 = $builder->build_object( - { class => 'Koha::ArticleRequests', + { + class => 'Koha::ArticleRequests', value => { status => Koha::ArticleRequest::Status::Requested, branchcode => $library_2->id } } ); my $ar_3 = $builder->build_object( - { class => 'Koha::ArticleRequests', + { + class => 'Koha::ArticleRequests', value => { status => Koha::ArticleRequest::Status::Pending, branchcode => $library_2->id } } ); my $requested = Koha::ArticleRequests->requested; - is( $requested->count, 2, 'Two article requests with the REQUESTED status' ); + is( $requested->count, 2, 'Two article requests with the REQUESTED status' ); is( $requested->next->status, Koha::ArticleRequest::Status::Requested, 'Status is correct' ); is( $requested->next->status, Koha::ArticleRequest::Status::Requested, 'Status is correct' ); diff --git a/t/db_dependent/Koha/Auth/Client.t b/t/db_dependent/Koha/Auth/Client.t index b3aa115d13..bc2cbbbba3 100755 --- a/t/db_dependent/Koha/Auth/Client.t +++ b/t/db_dependent/Koha/Auth/Client.t @@ -25,7 +25,7 @@ use Test::MockModule; use Test::MockObject; use Test::Exception; -use JSON qw(encode_json); +use JSON qw(encode_json); use MIME::Base64 qw{ encode_base64url }; use Koha::Auth::Client; @@ -44,11 +44,16 @@ subtest 'get_user() tests' => sub { $schema->storage->txn_begin; - my $client = Koha::Auth::Client::OAuth->new; - my $provider = $builder->build_object( { class => 'Koha::Auth::Identity::Providers', value => { matchpoint => 'email' } } ); - my $domain = $builder->build_object( - { class => 'Koha::Auth::Identity::Provider::Domains', - value => { identity_provider_id => $provider->id, domain => '', update_on_auth => 0, allow_opac => 1, allow_staff => 0 } + my $client = Koha::Auth::Client::OAuth->new; + my $provider = + $builder->build_object( { class => 'Koha::Auth::Identity::Providers', value => { matchpoint => 'email' } } ); + my $domain = $builder->build_object( + { + class => 'Koha::Auth::Identity::Provider::Domains', + value => { + identity_provider_id => $provider->id, domain => '', update_on_auth => 0, allow_opac => 1, + allow_staff => 0 + } } ); my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { email => 'patron@test.com' } } ); @@ -59,18 +64,19 @@ subtest 'get_user() tests' => sub { }; $provider->set_mapping($mapping)->store; - my $id_token = 'header.' - . encode_base64url( + my $id_token = 'header.' . encode_base64url( encode_json( - { electronic_mail => 'patron@test.com', + { + electronic_mail => 'patron@test.com', given_name => 'test name' } ) - ) . '.footer'; + ) . '.footer'; my $data = { id_token => $id_token }; - my ( $resolved_patron, $mapped_data, $resolved_domain ) = $client->get_user( { provider => $provider->code, data => $data, interface => 'opac' } ); + my ( $resolved_patron, $mapped_data, $resolved_domain ) = + $client->get_user( { provider => $provider->code, data => $data, interface => 'opac' } ); is_deeply( $resolved_patron->to_api( { user => $patron } ), $patron->to_api( { user => $patron } ), 'Patron correctly retrieved' @@ -87,57 +93,103 @@ subtest 'get_valid_domain_config() tests' => sub { $schema->storage->txn_begin; - my $client = Koha::Auth::Client->new; - my $provider = $builder->build_object( { class => 'Koha::Auth::Identity::Providers', value => { matchpoint => 'email' } } ); - my $domain1 = $builder->build_object( - { class => 'Koha::Auth::Identity::Provider::Domains', value => { identity_provider_id => $provider->id, domain => '', allow_opac => 0, allow_staff => 0 } } ); + my $client = Koha::Auth::Client->new; + my $provider = + $builder->build_object( { class => 'Koha::Auth::Identity::Providers', value => { matchpoint => 'email' } } ); + my $domain1 = $builder->build_object( + { + class => 'Koha::Auth::Identity::Provider::Domains', + value => { identity_provider_id => $provider->id, domain => '', allow_opac => 0, allow_staff => 0 } + } + ); my $domain2 = $builder->build_object( - { class => 'Koha::Auth::Identity::Provider::Domains', value => { identity_provider_id => $provider->id, domain => '*library.com', allow_opac => 1, allow_staff => 0 } } ); + { + class => 'Koha::Auth::Identity::Provider::Domains', + value => + { identity_provider_id => $provider->id, domain => '*library.com', allow_opac => 1, allow_staff => 0 } + } + ); my $domain3 = $builder->build_object( - { class => 'Koha::Auth::Identity::Provider::Domains', value => { identity_provider_id => $provider->id, domain => '*.library.com', allow_opac => 1, allow_staff => 0 } } + { + class => 'Koha::Auth::Identity::Provider::Domains', + value => + { identity_provider_id => $provider->id, domain => '*.library.com', allow_opac => 1, allow_staff => 0 } + } ); my $domain4 = $builder->build_object( - { class => 'Koha::Auth::Identity::Provider::Domains', - value => { identity_provider_id => $provider->id, domain => 'student.library.com', allow_opac => 1, allow_staff => 0 } + { + class => 'Koha::Auth::Identity::Provider::Domains', + value => { + identity_provider_id => $provider->id, domain => 'student.library.com', allow_opac => 1, + allow_staff => 0 + } } ); my $domain5 = $builder->build_object( - { class => 'Koha::Auth::Identity::Provider::Domains', - value => { identity_provider_id => $provider->id, domain => 'staff.library.com', allow_opac => 1, allow_staff => 1 } + { + class => 'Koha::Auth::Identity::Provider::Domains', + value => { + identity_provider_id => $provider->id, domain => 'staff.library.com', allow_opac => 1, allow_staff => 1 + } } ); my $retrieved_domain; # Test @gmail.com - $retrieved_domain = $client->get_valid_domain_config( { provider => $provider, email => 'user@gmail.com', interface => 'opac' } ); + $retrieved_domain = + $client->get_valid_domain_config( { provider => $provider, email => 'user@gmail.com', interface => 'opac' } ); is( $retrieved_domain, undef, 'gmail user cannot enter opac' ); - $retrieved_domain = $client->get_valid_domain_config( { provider => $provider, email => 'user@gmail.com', interface => 'staff' } ); + $retrieved_domain = + $client->get_valid_domain_config( { provider => $provider, email => 'user@gmail.com', interface => 'staff' } ); is( $retrieved_domain, undef, 'gmail user cannot enter staff' ); # Test @otherlibrary.com - $retrieved_domain = $client->get_valid_domain_config( { provider => $provider, email => 'user@otherlibrary.com', interface => 'opac' } ); - is( $retrieved_domain->identity_provider_domain_id, $domain2->identity_provider_domain_id, 'otherlibaray user can enter opac with domain2' ); - $retrieved_domain = $client->get_valid_domain_config( { provider => $provider, email => 'user@otherlibrary.com', interface => 'staff' } ); + $retrieved_domain = $client->get_valid_domain_config( + { provider => $provider, email => 'user@otherlibrary.com', interface => 'opac' } ); + is( + $retrieved_domain->identity_provider_domain_id, $domain2->identity_provider_domain_id, + 'otherlibaray user can enter opac with domain2' + ); + $retrieved_domain = $client->get_valid_domain_config( + { provider => $provider, email => 'user@otherlibrary.com', interface => 'staff' } ); is( $retrieved_domain, undef, 'otherlibrary user cannot enter staff' ); # Test @provider.library.com - $retrieved_domain = $client->get_valid_domain_config( { provider => $provider, email => 'user@provider.library.com', interface => 'opac' } ); - is( $retrieved_domain->identity_provider_domain_id, $domain3->identity_provider_domain_id, 'provider.library user can enter opac with domain3' ); - $retrieved_domain = $client->get_valid_domain_config( { provider => $provider, email => 'user@provider.library.com', interface => 'staff' } ); + $retrieved_domain = $client->get_valid_domain_config( + { provider => $provider, email => 'user@provider.library.com', interface => 'opac' } ); + is( + $retrieved_domain->identity_provider_domain_id, $domain3->identity_provider_domain_id, + 'provider.library user can enter opac with domain3' + ); + $retrieved_domain = $client->get_valid_domain_config( + { provider => $provider, email => 'user@provider.library.com', interface => 'staff' } ); is( $retrieved_domain, undef, 'provider.library user cannot enter staff' ); # Test @student.library.com - $retrieved_domain = $client->get_valid_domain_config( { provider => $provider, email => 'user@student.library.com', interface => 'opac' } ); - is( $retrieved_domain->identity_provider_domain_id, $domain4->identity_provider_domain_id, 'student.library user can enter opac with domain4' ); - $retrieved_domain = $client->get_valid_domain_config( { provider => $provider, email => 'user@student.library.com', interface => 'staff' } ); + $retrieved_domain = $client->get_valid_domain_config( + { provider => $provider, email => 'user@student.library.com', interface => 'opac' } ); + is( + $retrieved_domain->identity_provider_domain_id, $domain4->identity_provider_domain_id, + 'student.library user can enter opac with domain4' + ); + $retrieved_domain = $client->get_valid_domain_config( + { provider => $provider, email => 'user@student.library.com', interface => 'staff' } ); is( $retrieved_domain, undef, 'student.library user cannot enter staff' ); # Test @staff.library.com - $retrieved_domain = $client->get_valid_domain_config( { provider => $provider, email => 'user@staff.library.com', interface => 'opac' } ); - is( $retrieved_domain->identity_provider_domain_id, $domain5->identity_provider_domain_id, 'staff.library user can enter opac with domain5' ); - $retrieved_domain = $client->get_valid_domain_config( { provider => $provider, email => 'user@staff.library.com', interface => 'staff' } ); - is( $retrieved_domain->identity_provider_domain_id, $domain5->identity_provider_domain_id, 'staff.library user can enter staff with domain5' ); + $retrieved_domain = $client->get_valid_domain_config( + { provider => $provider, email => 'user@staff.library.com', interface => 'opac' } ); + is( + $retrieved_domain->identity_provider_domain_id, $domain5->identity_provider_domain_id, + 'staff.library user can enter opac with domain5' + ); + $retrieved_domain = $client->get_valid_domain_config( + { provider => $provider, email => 'user@staff.library.com', interface => 'staff' } ); + is( + $retrieved_domain->identity_provider_domain_id, $domain5->identity_provider_domain_id, + 'staff.library user can enter staff with domain5' + ); $schema->storage->txn_rollback; }; @@ -146,16 +198,28 @@ subtest 'has_valid_domain_config() tests' => sub { plan tests => 2; $schema->storage->txn_begin; - my $client = Koha::Auth::Client->new; - my $provider = $builder->build_object( { class => 'Koha::Auth::Identity::Providers', value => { matchpoint => 'email' } } ); - my $domain1 = $builder->build_object( - { class => 'Koha::Auth::Identity::Provider::Domains', value => { identity_provider_id => $provider->id, domain => '', allow_opac => 1, allow_staff => 0 } } ); + my $client = Koha::Auth::Client->new; + my $provider = + $builder->build_object( { class => 'Koha::Auth::Identity::Providers', value => { matchpoint => 'email' } } ); + my $domain1 = $builder->build_object( + { + class => 'Koha::Auth::Identity::Provider::Domains', + value => { identity_provider_id => $provider->id, domain => '', allow_opac => 1, allow_staff => 0 } + } + ); # Test @gmail.com - my $retrieved_domain = $client->has_valid_domain_config( { provider => $provider, email => 'user@gmail.com', interface => 'opac' } ); - is( $retrieved_domain->identity_provider_domain_id, $domain1->identity_provider_domain_id, 'gmail user can enter opac with domain1' ); - throws_ok { $client->has_valid_domain_config( { provider => $provider, email => 'user@gmail.com', interface => 'staff' } ) } 'Koha::Exceptions::Auth::NoValidDomain', - 'gmail user cannot enter staff'; + my $retrieved_domain = + $client->has_valid_domain_config( { provider => $provider, email => 'user@gmail.com', interface => 'opac' } ); + is( + $retrieved_domain->identity_provider_domain_id, $domain1->identity_provider_domain_id, + 'gmail user can enter opac with domain1' + ); + throws_ok { + $client->has_valid_domain_config( { provider => $provider, email => 'user@gmail.com', interface => 'staff' } ) + } + 'Koha::Exceptions::Auth::NoValidDomain', + 'gmail user cannot enter staff'; $schema->storage->txn_rollback; }; @@ -171,21 +235,24 @@ subtest '_traverse_hash() tests' => sub { }; my $first_result = $client->_traverse_hash( - { base => $hash, + { + base => $hash, keys => 'a.hash.with' } ); is( $first_result, 'complicated structure', 'get the value within a hash structure' ); my $second_result = $client->_traverse_hash( - { base => $hash, + { + base => $hash, keys => 'an.array.0.inside' } ); is( $second_result, 'a hash', 'get the value of the first element of an array within a hash structure' ); my $third_result = $client->_traverse_hash( - { base => $hash, + { + base => $hash, keys => 'an.array.1.inside' } ); diff --git a/t/db_dependent/Koha/Auth/Identity/Provider.t b/t/db_dependent/Koha/Auth/Identity/Provider.t index afea2aed07..df96a54ea2 100755 --- a/t/db_dependent/Koha/Auth/Identity/Provider.t +++ b/t/db_dependent/Koha/Auth/Identity/Provider.t @@ -44,10 +44,12 @@ subtest 'domains() tests' => sub { my $domains = $provider->domains; is( ref($domains), 'Koha::Auth::Identity::Provider::Domains', 'Type is correct' ); - is( $domains->count, 0, 'No domains defined' ); + is( $domains->count, 0, 'No domains defined' ); - $builder->build_object( { class => 'Koha::Auth::Identity::Provider::Domains', value => { identity_provider_id => $provider->id } } ); - $builder->build_object( { class => 'Koha::Auth::Identity::Provider::Domains', value => { identity_provider_id => $provider->id } } ); + $builder->build_object( + { class => 'Koha::Auth::Identity::Provider::Domains', value => { identity_provider_id => $provider->id } } ); + $builder->build_object( + { class => 'Koha::Auth::Identity::Provider::Domains', value => { identity_provider_id => $provider->id } } ); is( $provider->domains->count, 2, 'The provider has 2 domains defined' ); @@ -83,7 +85,8 @@ subtest 'set_config() tests' => sub { plan tests => 4; - my $provider = $builder->build_object( { class => 'Koha::Auth::Identity::Providers', value => { protocol => 'OIDC' } } ); + my $provider = + $builder->build_object( { class => 'Koha::Auth::Identity::Providers', value => { protocol => 'OIDC' } } ); $provider = $provider->upgrade_class; my $config = { @@ -108,7 +111,8 @@ subtest 'set_config() tests' => sub { plan tests => 4; - my $provider = $builder->build_object( { class => 'Koha::Auth::Identity::Providers', value => { protocol => 'OAuth' } } ); + my $provider = + $builder->build_object( { class => 'Koha::Auth::Identity::Providers', value => { protocol => 'OAuth' } } ); $provider = $provider->upgrade_class; my $config = { @@ -134,7 +138,8 @@ subtest 'set_config() tests' => sub { plan tests => 2; - my $provider = $builder->build_object( { class => 'Koha::Auth::Identity::Providers', value => { protocol => 'CAS' } } ); + my $provider = + $builder->build_object( { class => 'Koha::Auth::Identity::Providers', value => { protocol => 'CAS' } } ); throws_ok { $provider->set_config() } 'Koha::Exception', 'Exception thrown on unsupported protocol'; @@ -187,7 +192,7 @@ subtest 'upgrade_class() tests' => sub { $schema->storage->txn_begin; my $mapping = Koha::Auth::Identity::Provider::protocol_to_class_mapping; - my @protocols = keys %{ $mapping }; + my @protocols = keys %{$mapping}; foreach my $protocol (@protocols) { @@ -199,16 +204,19 @@ subtest 'upgrade_class() tests' => sub { ); is( ref($provider), 'Koha::Auth::Identity::Provider', "Base class used for $protocol" ); + # upgrade $provider = $provider->upgrade_class; - is( ref($provider), $mapping->{$protocol}, "Class upgraded to " . $mapping->{$protocol} . "for protocol $protocol" ); + is( + ref($provider), $mapping->{$protocol}, + "Class upgraded to " . $mapping->{$protocol} . "for protocol $protocol" + ); } - my $provider = Koha::Auth::Identity::Provider->new({ protocol => 'Invalid' }); - throws_ok - { $provider->upgrade } - 'Koha::Exception', - 'Exception throw on invalid protocol'; + my $provider = Koha::Auth::Identity::Provider->new( { protocol => 'Invalid' } ); + throws_ok { $provider->upgrade } + 'Koha::Exception', + 'Exception throw on invalid protocol'; $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/Koha/Auth/TwoFactorAuth.t b/t/db_dependent/Koha/Auth/TwoFactorAuth.t index eb50a503f7..10e7e9af2c 100755 --- a/t/db_dependent/Koha/Auth/TwoFactorAuth.t +++ b/t/db_dependent/Koha/Auth/TwoFactorAuth.t @@ -14,47 +14,49 @@ use Koha::Exceptions; use Koha::Exceptions::Patron; use Koha::Notice::Messages; -our $schema = Koha::Database->new->schema; -our $builder = t::lib::TestBuilder->new; -our $mocked_stuffer = Test::MockModule->new('Email::Stuffer'); +our $schema = Koha::Database->new->schema; +our $builder = t::lib::TestBuilder->new; +our $mocked_stuffer = Test::MockModule->new('Email::Stuffer'); $mocked_stuffer->mock( 'send_or_die', sub { warn 'I do not send mails now'; } ); subtest 'new' => sub { plan tests => 10; $schema->storage->txn_begin; - t::lib::Mocks::mock_preference('TwoFactorAuthentication', 'enabled'); - t::lib::Mocks::mock_config('encryption_key', 'bad_example'); + t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 'enabled' ); + t::lib::Mocks::mock_config( 'encryption_key', 'bad_example' ); # Trivial test: no patron, no object throws_ok { Koha::Auth::TwoFactorAuth->new; } - 'Koha::Exceptions::MissingParameter', + 'Koha::Exceptions::MissingParameter', 'Croaked on missing patron'; - throws_ok { Koha::Auth::TwoFactorAuth->new({ patron => 'Henk', secret => q<> }) } - 'Koha::Exceptions::MissingParameter', + throws_ok { Koha::Auth::TwoFactorAuth->new( { patron => 'Henk', secret => q<> } ) } + 'Koha::Exceptions::MissingParameter', 'Croaked on missing patron object'; # Testing without secret - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); is( $patron->secret, undef, 'Secret still undefined' ); - throws_ok { Koha::Auth::TwoFactorAuth->new({ patron => $patron }) } - 'Koha::Exceptions::MissingParameter', 'Croaks on missing secret'; + throws_ok { Koha::Auth::TwoFactorAuth->new( { patron => $patron } ) } + 'Koha::Exceptions::MissingParameter', 'Croaks on missing secret'; + # Pass a wrong encoded secret - throws_ok { Koha::Auth::TwoFactorAuth->new({ patron => $patron, secret32 => '@' }) } - 'Koha::Exceptions::BadParameter', + throws_ok { Koha::Auth::TwoFactorAuth->new( { patron => $patron, secret32 => '@' } ) } + 'Koha::Exceptions::BadParameter', 'Croaked on wrong encoding'; # Test passing secret or secret32 (converted to base32) - $patron->encode_secret('nv4v65dpobpxgzldojsxiii'); # this is base32 already for 'my_top_secret!' - my $auth = Koha::Auth::TwoFactorAuth->new({ patron => $patron }); + $patron->encode_secret('nv4v65dpobpxgzldojsxiii'); # this is base32 already for 'my_top_secret!' + my $auth = Koha::Auth::TwoFactorAuth->new( { patron => $patron } ); is( $auth->secret32, $patron->decoded_secret, 'Base32 secret as expected' ); - $auth->code( $patron->decoded_secret ); # trigger conversion by passing base32 to code + $auth->code( $patron->decoded_secret ); # trigger conversion by passing base32 to code is( $auth->secret, 'my_top_secret!', 'Decoded secret fine too' ); + # The other way around - $auth = Koha::Auth::TwoFactorAuth->new({ patron => $patron, secret => 'my_top_secret!' }); + $auth = Koha::Auth::TwoFactorAuth->new( { patron => $patron, secret => 'my_top_secret!' } ); is( $auth->secret32, undef, 'GoogleAuth did not yet encode' ); - $auth->code; # this will trigger base32 encoding now - is( $auth->secret, 'my_top_secret!', 'Check secret' ); + $auth->code; # this will trigger base32 encoding now + is( $auth->secret, 'my_top_secret!', 'Check secret' ); is( $auth->secret32, 'nv4v65dpobpxgzldojsxiii', 'Check secret32' ); $schema->storage->txn_rollback; @@ -65,24 +67,24 @@ subtest 'qr_code' => sub { $schema->storage->txn_begin; - t::lib::Mocks::mock_preference('TwoFactorAuthentication', 'enabled'); - t::lib::Mocks::mock_config('encryption_key', 'bad_example'); - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); - $patron->encode_secret('you2wont2guess2it'); # this is base32 btw + t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 'enabled' ); + t::lib::Mocks::mock_config( 'encryption_key', 'bad_example' ); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + $patron->encode_secret('you2wont2guess2it'); # this is base32 btw $patron->auth_method('two-factor'); $patron->store; - my $auth = Koha::Auth::TwoFactorAuth->new({ patron => $patron }); + my $auth = Koha::Auth::TwoFactorAuth->new( { patron => $patron } ); my $img_data = $auth->qr_code; - is( substr($img_data, 0, 22), 'data:image/png;base64,', 'Checking prefix of dataurl' ); - like( substr($img_data, 22), qr/^[a-zA-Z0-9\/=+]+$/, 'Contains base64 chars' ); + is( substr( $img_data, 0, 22 ), 'data:image/png;base64,', 'Checking prefix of dataurl' ); + like( substr( $img_data, 22 ), qr/^[a-zA-Z0-9\/=+]+$/, 'Contains base64 chars' ); is( $auth->qr_code, $img_data, 'Repeated call' ); $auth->clear; # Changing the secret should generate different data, right? - $patron->encode_secret('no3really3not3cracked'); # base32 + $patron->encode_secret('no3really3not3cracked'); # base32 $patron->store; - $auth = Koha::Auth::TwoFactorAuth->new({ patron => $patron }); + $auth = Koha::Auth::TwoFactorAuth->new( { patron => $patron } ); my $img_data02 = $auth->qr_code; is( length($img_data02) > 22, 1, 'More characters than prefix' ); isnt( $img_data02, $img_data, 'Another secret, another image' ); diff --git a/t/db_dependent/Koha/Authorities.t b/t/db_dependent/Koha/Authorities.t index 6d0e1ffd74..e53ddf2d2f 100755 --- a/t/db_dependent/Koha/Authorities.t +++ b/t/db_dependent/Koha/Authorities.t @@ -46,19 +46,22 @@ $schema->storage->txn_begin; # Globals our $search_compat_pars; -our $builder = t::lib::TestBuilder->new; +our $builder = t::lib::TestBuilder->new; my $nb_of_authorities = Koha::Authorities->search->count; my $nb_of_authority_types = Koha::Authority::Types->search->count; my $new_authority_type_1 = Koha::Authority::Type->new( - { authtypecode => 'my_ac_1', + { + authtypecode => 'my_ac_1', authtypetext => 'my authority type text 1', auth_tag_to_report => '100', summary => 'my summary for authority 1', } )->store; -my $new_authority_1 = Koha::Authority->new( { authtypecode => $new_authority_type_1->authtypecode, marcxml => '' } )->store; -my $new_authority_2 = Koha::Authority->new( { authtypecode => $new_authority_type_1->authtypecode, marcxml => '' } )->store; +my $new_authority_1 = + Koha::Authority->new( { authtypecode => $new_authority_type_1->authtypecode, marcxml => '' } )->store; +my $new_authority_2 = + Koha::Authority->new( { authtypecode => $new_authority_type_1->authtypecode, marcxml => '' } )->store; is( Koha::Authority::Types->search->count, $nb_of_authority_types + 1, 'The authority type should have been added' ); is( Koha::Authorities->search->count, $nb_of_authorities + 2, 'The 2 authorities should have been added' ); @@ -74,21 +77,25 @@ subtest 'New merge request, method oldmarc' => sub { MARC::Field->new( '100', '', '', a => 'a', b => 'b_findme' ), MARC::Field->new( '200', '', '', a => 'aa' ), ); - my $req = Koha::Authority::MergeRequest->new({ - authid => $new_authority_2->authid, - reportxml => 'Should be discarded', - }); + my $req = Koha::Authority::MergeRequest->new( + { + authid => $new_authority_2->authid, + reportxml => 'Should be discarded', + } + ); is( $req->reportxml, undef, 'Reportxml is undef without oldrecord' ); - $req = Koha::Authority::MergeRequest->new({ - authid => $new_authority_2->authid, - oldrecord => $marc, - }); + $req = Koha::Authority::MergeRequest->new( + { + authid => $new_authority_2->authid, + oldrecord => $marc, + } + ); like( $req->reportxml, qr/b_findme/, 'Reportxml initialized' ); # Check if oldmarc is a MARC::Record and has one or two fields is( ref( $req->oldmarc ), 'MARC::Record', 'Check oldmarc method' ); - if( C4::Context->preference('marcflavour') eq 'UNIMARC' ) { + if ( C4::Context->preference('marcflavour') eq 'UNIMARC' ) { is( scalar $req->oldmarc->fields, 2, 'UNIMARC contains two fields' ); } else { is( scalar $req->oldmarc->fields, 1, 'MARC21 contains one field' ); @@ -104,20 +111,25 @@ subtest 'Testing reporting_tag_xml in MergeRequest' => sub { MARC::Field->new( '110', '', '', a => 'Best author' ), MARC::Field->new( '234', '', '', a => 'Just a field' ), ); - my $xml = Koha::Authority::MergeRequest->reporting_tag_xml({ - record => $record, tag => '100', - }); + my $xml = Koha::Authority::MergeRequest->reporting_tag_xml( + { + record => $record, tag => '100', + } + ); is( $xml, undef, 'Expected no result for wrong tag' ); - $xml = Koha::Authority::MergeRequest->reporting_tag_xml({ - record => $record, tag => '110', - }); + $xml = Koha::Authority::MergeRequest->reporting_tag_xml( + { + record => $record, tag => '110', + } + ); my $newrecord = MARC::Record->new_from_xml( $xml, 'UTF-8', - C4::Context->preference('marcflavour') eq 'UNIMARC' ? - 'UNIMARCAUTH' : - 'MARC21', + C4::Context->preference('marcflavour') eq 'UNIMARC' + ? 'UNIMARCAUTH' + : 'MARC21', ); - cmp_deeply( $record->field('110')->subfields, + cmp_deeply( + $record->field('110')->subfields, $newrecord->field('110')->subfields, 'Compare reporting tag in both records', ); @@ -131,36 +143,40 @@ subtest 'Trivial tests for get_usage_count and linked_biblionumbers' => sub { # So we're just testing the 'wrapper' here. my ( $mods, $koha_fields ); - t::lib::Mocks::mock_preference('SearchEngine', 'Zebra'); - $mods->{zebra} = Test::MockModule->new( 'Koha::SearchEngine::Zebra::Search' ); - $mods->{elastic} = Test::MockModule->new( 'Koha::SearchEngine::Elasticsearch::Search' ); - $mods->{biblio} = Test::MockModule->new( 'C4::Biblio' ); + t::lib::Mocks::mock_preference( 'SearchEngine', 'Zebra' ); + $mods->{zebra} = Test::MockModule->new('Koha::SearchEngine::Zebra::Search'); + $mods->{elastic} = Test::MockModule->new('Koha::SearchEngine::Elasticsearch::Search'); + $mods->{biblio} = Test::MockModule->new('C4::Biblio'); $mods->{zebra}->mock( 'simple_search_compat', \&simple_search_compat ); $mods->{elastic}->mock( 'simple_search_compat', \&simple_search_compat ); - $mods->{biblio}->mock( 'GetMarcFromKohaField', sub { return @$koha_fields; }); + $mods->{biblio}->mock( 'GetMarcFromKohaField', sub { return @$koha_fields; } ); - my $auth1 = $builder->build({ source => 'AuthHeader' }); + my $auth1 = $builder->build( { source => 'AuthHeader' } ); $auth1 = Koha::Authorities->find( $auth1->{authid} ); # Test error condition my $count; $search_compat_pars = [ 0, 'some_error' ]; warning_like { $count = $auth1->get_usage_count } - qr/some_error/, 'Catch warn of simple_search_compat'; + qr/some_error/, 'Catch warn of simple_search_compat'; is( $count, undef, 'Undef returned when error encountered' ); # Simple test with some results; one result discarded in the 2nd test - $search_compat_pars = [ 1 ]; - $koha_fields = [ '001', '' ]; - is( $auth1->get_usage_count, 3, 'Three results expected (Zebra)' ); - cmp_deeply( [ $auth1->linked_biblionumbers ], [ 1001, 3003 ], - 'linked_biblionumbers should ignore record without biblionumber' ); + $search_compat_pars = [1]; + $koha_fields = [ '001', '' ]; + is( $auth1->get_usage_count, 3, 'Three results expected (Zebra)' ); + cmp_deeply( + [ $auth1->linked_biblionumbers ], [ 1001, 3003 ], + 'linked_biblionumbers should ignore record without biblionumber' + ); # And a simple test with Elastic - t::lib::Mocks::mock_preference('SearchEngine', 'Elasticsearch'); - cmp_deeply( [ $auth1->linked_biblionumbers ], [ 2001 ], - 'linked_biblionumbers with Elasticsearch' ); - t::lib::Mocks::mock_preference('SearchEngine', 'Zebra'); + t::lib::Mocks::mock_preference( 'SearchEngine', 'Elasticsearch' ); + cmp_deeply( + [ $auth1->linked_biblionumbers ], [2001], + 'linked_biblionumbers with Elasticsearch' + ); + t::lib::Mocks::mock_preference( 'SearchEngine', 'Zebra' ); }; subtest 'Simple test for controlled_indicators' => sub { @@ -170,23 +186,25 @@ subtest 'Simple test for controlled_indicators' => sub { # Mock pref so that authority indicators are swapped for marc21/unimarc # The biblio tag is actually made irrelevant here - t::lib::Mocks::mock_preference('AuthorityControlledIndicators', q|marc21,*,ind1:auth2,ind2:auth1 -unimarc,*,ind1:auth2,ind2:auth1|); + t::lib::Mocks::mock_preference( + 'AuthorityControlledIndicators', q|marc21,*,ind1:auth2,ind2:auth1 +unimarc,*,ind1:auth2,ind2:auth1| + ); t::lib::Mocks::mock_preference( 'marcflavour', 'MARC21' ); my $record = MARC::Record->new; $record->append_fields( MARC::Field->new( '100', '1', '2', a => 'Name' ) ); - my $type = $builder->build({ source => 'AuthType', value => { auth_tag_to_report => '100'} }); + my $type = $builder->build( { source => 'AuthType', value => { auth_tag_to_report => '100' } } ); my $authid = C4::AuthoritiesMarc::AddAuthority( $record, undef, $type->{authtypecode} ); - my $auth = Koha::Authorities->find( $authid ); - is( $auth->controlled_indicators({ biblio_tag => '123' })->{ind1}, '2', 'MARC21: Swapped ind2' ); - is( $auth->controlled_indicators({ biblio_tag => '234' })->{ind2}, '1', 'MARC21: Swapped ind1' ); + my $auth = Koha::Authorities->find($authid); + is( $auth->controlled_indicators( { biblio_tag => '123' } )->{ind1}, '2', 'MARC21: Swapped ind2' ); + is( $auth->controlled_indicators( { biblio_tag => '234' } )->{ind2}, '1', 'MARC21: Swapped ind1' ); # try UNIMARC too t::lib::Mocks::mock_preference( 'marcflavour', 'UNIMARC' ); $record = MARC::Record->new; $record->append_fields( MARC::Field->new( '210', '1', '2', a => 'Name' ) ); - $type = $builder->build({ source => 'AuthType', value => { auth_tag_to_report => '210'} }); + $type = $builder->build( { source => 'AuthType', value => { auth_tag_to_report => '210' } } ); my $dbh = C4::Context->dbh; $dbh->do( "INSERT INTO marc_subfield_structure (tagfield,authtypecode,frameworkcode) VALUES ('210',?,'')", undef, @@ -194,16 +212,17 @@ unimarc,*,ind1:auth2,ind2:auth1|); ) or die $dbh->errstr; $authid = C4::AuthoritiesMarc::AddAuthority( $record, undef, $type->{authtypecode} ); - $auth = Koha::Authorities->find( $authid ); - is( $auth->controlled_indicators({ biblio_tag => '345' })->{ind1}, '2', 'UNIMARC: Swapped ind2' ); - is( $auth->controlled_indicators({ biblio_tag => '456' })->{ind2}, '1', 'UNIMARC: Swapped ind1' ); + $auth = Koha::Authorities->find($authid); + is( $auth->controlled_indicators( { biblio_tag => '345' } )->{ind1}, '2', 'UNIMARC: Swapped ind2' ); + is( $auth->controlled_indicators( { biblio_tag => '456' } )->{ind2}, '1', 'UNIMARC: Swapped ind1' ); }; sub simple_search_compat { - if( $search_compat_pars->[0] == 0 ) { + if ( $search_compat_pars->[0] == 0 ) { return ( $search_compat_pars->[1], [], 0 ); - } elsif( $search_compat_pars->[0] == 1 ) { - my $records = C4::Context->preference('SearchEngine') eq 'Zebra' + } elsif ( $search_compat_pars->[0] == 1 ) { + my $records = + C4::Context->preference('SearchEngine') eq 'Zebra' ? few_marcxml_records() : few_marc_records(); return ( undef, $records, scalar @$records ); @@ -212,7 +231,7 @@ sub simple_search_compat { sub few_marcxml_records { return [ -q|<?xml version="1.0" encoding="UTF-8"?> + q|<?xml version="1.0" encoding="UTF-8"?> <record xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.loc.gov/MARC21/slim" xsi:schemaLocation="http://www.loc.gov/MARC21/slim http://www.loc.gov/standards/marcxml/schema/MARC21slim.xsd"> <controlfield tag="001">1001</controlfield> <datafield tag="110" ind1=" " ind2=" "> @@ -220,7 +239,7 @@ q|<?xml version="1.0" encoding="UTF-8"?> <subfield code="a">My Corporation</subfield> </datafield> </record>|, -q|<?xml version="1.0" encoding="UTF-8"?> + q|<?xml version="1.0" encoding="UTF-8"?> <record xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.loc.gov/MARC21/slim" xsi:schemaLocation="http://www.loc.gov/MARC21/slim http://www.loc.gov/standards/marcxml/schema/MARC21slim.xsd"> <!-- No biblionumber here --> <datafield tag="610" ind1=" " ind2=" "> @@ -228,7 +247,7 @@ q|<?xml version="1.0" encoding="UTF-8"?> <subfield code="a">Another Corporation</subfield> </datafield> </record>|, -q|<?xml version="1.0" encoding="UTF-8"?> + q|<?xml version="1.0" encoding="UTF-8"?> <record xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.loc.gov/MARC21/slim" xsi:schemaLocation="http://www.loc.gov/MARC21/slim http://www.loc.gov/standards/marcxml/schema/MARC21slim.xsd"> <controlfield tag="001">3003</controlfield> <datafield tag="110" ind1=" " ind2=" "> @@ -245,13 +264,13 @@ sub few_marc_records { MARC::Field->new( '001', '2001' ), MARC::Field->new( '245', '', '', a => 'Title' ), ); - return [ $marc ]; + return [$marc]; } subtest 'get_identifiers_and_information' => sub { plan tests => 1; - t::lib::Mocks::mock_preference( 'marcflavour', 'MARC21' ); + t::lib::Mocks::mock_preference( 'marcflavour', 'MARC21' ); t::lib::Mocks::mock_preference( 'OPACAuthorIdentifiersAndInformation', 'identifiers' ); my $record = MARC::Record->new(); $record->add_fields( @@ -275,7 +294,7 @@ subtest 'get_identifiers_and_information' => sub { 6 => 'https://www.scopus.com/authid/detail.uri?authorId=01234567890' ], ); - my $authid = C4::AuthoritiesMarc::AddAuthority($record, undef, 'PERSO_NAME'); + my $authid = C4::AuthoritiesMarc::AddAuthority( $record, undef, 'PERSO_NAME' ); my $authority = Koha::Authorities->find($authid); is_deeply( $authority->get_identifiers_and_information, @@ -320,28 +339,28 @@ subtest 'record tests' => sub { 6 => 'https://www.scopus.com/authid/detail.uri?authorId=01234567890' ], ); - my $authid = C4::AuthoritiesMarc::AddAuthority($record, undef, 'PERSO_NAME'); - my $authority = Koha::Authorities->find($authid); + my $authid = C4::AuthoritiesMarc::AddAuthority( $record, undef, 'PERSO_NAME' ); + my $authority = Koha::Authorities->find($authid); my $authority_record = $authority->record; - is ($authority_record->field('100')->subfield('a'), 'Lastname, Firstname'); + is( $authority_record->field('100')->subfield('a'), 'Lastname, Firstname' ); my @fields_024 = $authority_record->field('024'); - is ($fields_024[0]->subfield('a'), '0000-0002-1234-5678'); - is ($fields_024[1]->subfield('a'), '01234567890'); + is( $fields_024[0]->subfield('a'), '0000-0002-1234-5678' ); + is( $fields_024[1]->subfield('a'), '01234567890' ); }; subtest 'record_schema tests' => sub { plan tests => 2; - my $authority = $builder->build_object({class => 'Koha::Authorities'}); + my $authority = $builder->build_object( { class => 'Koha::Authorities' } ); t::lib::Mocks::mock_preference( 'marcflavour', 'MARC21' ); - is($authority->record_schema, 'MARC21'); + is( $authority->record_schema, 'MARC21' ); t::lib::Mocks::mock_preference( 'marcflavour', 'UNIMARC' ); - is($authority->record_schema, 'UNIMARCAUTH'); + is( $authority->record_schema, 'UNIMARCAUTH' ); }; $schema->storage->txn_rollback; diff --git a/t/db_dependent/Koha/BackgroundJob.t b/t/db_dependent/Koha/BackgroundJob.t index 35f8fb4e7d..c70a69184c 100755 --- a/t/db_dependent/Koha/BackgroundJob.t +++ b/t/db_dependent/Koha/BackgroundJob.t @@ -44,13 +44,14 @@ subtest '_derived_class() tests' => sub { $schema->storage->txn_begin; my $job_object = Koha::BackgroundJob->new(); - my $mapping = $job_object->type_to_class_mapping; + my $mapping = $job_object->type_to_class_mapping; # pick the first my $type = ( keys %{$mapping} )[0]; my $job = $builder->build_object( - { class => 'Koha::BackgroundJobs', + { + class => 'Koha::BackgroundJobs', value => { type => $type, data => 'Foo' } } ); @@ -63,7 +64,10 @@ subtest '_derived_class() tests' => sub { $derived->data('Bar')->store->discard_changes; $job->discard_changes; - is_deeply( $job->unblessed, $derived->unblessed, '_derived_class object refers to the same DB object and can be manipulated as expected' ); + is_deeply( + $job->unblessed, $derived->unblessed, + '_derived_class object refers to the same DB object and can be manipulated as expected' + ); $schema->storage->txn_rollback; }; @@ -96,7 +100,7 @@ subtest 'enqueue() tests' => sub { is( $job->borrowernumber, undef, 'No userenv, borrowernumber undef' ); my $interface = C4::Context->interface; - my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); t::lib::Mocks::mock_userenv( { patron => $patron } ); my $job_context = { number => $patron->borrowernumber, @@ -119,9 +123,9 @@ subtest 'enqueue() tests' => sub { $job_id = Koha::BackgroundJob::BatchUpdateItem->new->enqueue( { record_ids => [ 1, 2, 3 ] } ); $job = Koha::BackgroundJobs->find($job_id)->_derived_class; - is( $job->size, 3, 'Three steps' ); - is( $job->status, 'new', 'Initial status set correctly' ); - is( $job->borrowernumber, $patron->id, 'Borrowernumber set from userenv' ); + is( $job->size, 3, 'Three steps' ); + is( $job->status, 'new', 'Initial status set correctly' ); + is( $job->borrowernumber, $patron->id, 'Borrowernumber set from userenv' ); is( $job->queue, 'long_tasks', 'BatchUpdateItem should use the long_tasks queue' ); is_deeply( $job->json->decode( $job->context ), $job_context, 'Context set from userenv + interface' ); @@ -139,7 +143,7 @@ subtest 'start(), step() and finish() tests' => sub { my $job = Koha::BackgroundJobs->find($job_id)->_derived_class; is( $job->started_on, undef, 'started_on not set yet' ); - is( $job->size, 2, 'Two steps' ); + is( $job->size, 2, 'Two steps' ); $job->start; @@ -151,9 +155,8 @@ subtest 'start(), step() and finish() tests' => sub { is( $job->progress, 1, 'First step' ); $job->step; is( $job->progress, 2, 'Second step' ); - throws_ok - { $job->step; } - 'Koha::Exceptions::BackgroundJob::StepOutOfBounds', + throws_ok { $job->step; } + 'Koha::Exceptions::BackgroundJob::StepOutOfBounds', 'Tried to make a forbidden extra step'; is( $job->progress, 2, 'progress remains unchanged' ); @@ -161,29 +164,27 @@ subtest 'start(), step() and finish() tests' => sub { my $data = { some => 'data' }; $job->status('cancelled')->store; - $job->finish( $data ); + $job->finish($data); is( $job->status, 'cancelled', "'finish' leaves 'cancelled' untouched" ); isnt( $job->ended_on, undef, 'ended_on set' ); is_deeply( $job->json->decode( $job->data ), $data ); $job->status('started')->store; - $job->finish( $data ); + $job->finish($data); is( $job->status, 'finished' ); isnt( $job->ended_on, undef, 'ended_on set' ); is_deeply( $job->json->decode( $job->data ), $data ); - throws_ok - { $job->start; } - 'Koha::Exceptions::BackgroundJob::InconsistentStatus', + throws_ok { $job->start; } + 'Koha::Exceptions::BackgroundJob::InconsistentStatus', 'Exception thrown trying to start a finished job'; is( $@->expected_status, 'new' ); - throws_ok - { $job->step; } - 'Koha::Exceptions::BackgroundJob::InconsistentStatus', + throws_ok { $job->step; } + 'Koha::Exceptions::BackgroundJob::InconsistentStatus', 'Exception thrown trying to start a finished job'; is( $@->expected_status, 'started' ); @@ -225,24 +226,24 @@ subtest 'process tests' => sub { } ); - my $job_id = t::lib::Koha::BackgroundJob::BatchTest->new->enqueue( - { size => 10, a => 'aaa', b => 'bbb' } ); + my $job_id = t::lib::Koha::BackgroundJob::BatchTest->new->enqueue( { size => 10, a => 'aaa', b => 'bbb' } ); my $job = Koha::BackgroundJobs->find($job_id); C4::Context->interface('opac'); C4::Context->unset_userenv; - is( C4::Context->userenv, undef, "Userenv unset prior to calling process"); - is( C4::Context->interface, 'opac', "Interface set to opac prior to calling process"); + is( C4::Context->userenv, undef, "Userenv unset prior to calling process" ); + is( C4::Context->interface, 'opac', "Interface set to opac prior to calling process" ); $job->process(); - is_deeply( C4::Context->userenv, $job_context, "Userenv set from job context on process" ); - is_deeply( C4::Context->interface, 'intranet', "Interface set from job context on process" ); + is_deeply( C4::Context->userenv, $job_context, "Userenv set from job context on process" ); + is_deeply( C4::Context->interface, 'intranet', "Interface set from job context on process" ); # Manually add a job (->new->store) without context - my $json = $job->json; # sorry, quickly borrowing your json object - my $data = $json->encode({ a => 'a', b => 'b' }); + my $json = $job->json; # sorry, quickly borrowing your json object + my $data = $json->encode( { a => 'a', b => 'b' } ); my $incomplete_job = t::lib::Koha::BackgroundJob::BatchTest->new( - { status => 'new', + { + status => 'new', size => 1, borrowernumber => $patron->borrowernumber, type => 'batch_test', @@ -262,38 +263,41 @@ subtest 'decoded_data() and set_encoded_data() tests' => sub { plan tests => 8; $schema->storage->txn_begin; - my $job = Koha::BackgroundJob::BatchUpdateItem->new->set_encoded_data( undef ); + my $job = Koha::BackgroundJob::BatchUpdateItem->new->set_encoded_data(undef); is( $job->decoded_data, undef, 'undef is undef' ); my $data = { some => 'data' }; - $job->set_encoded_data( $data ); + $job->set_encoded_data($data); - is_deeply( $job->json->decode($job->data), $data, 'decode what we sent' ); - is_deeply( $job->decoded_data, $data, 'check with decoded_data' ); + is_deeply( $job->json->decode( $job->data ), $data, 'decode what we sent' ); + is_deeply( $job->decoded_data, $data, 'check with decoded_data' ); # Let's get some Unicode stuff into the game $data = { favorite_Chinese => [ '葑', '癱' ], latin_dancing => [ '¢', '¥', 'á', 'û' ] }; - $job->set_encoded_data( $data )->store; + $job->set_encoded_data($data)->store; - $job->discard_changes; # refresh + $job->discard_changes; # refresh is_deeply( $job->decoded_data, $data, 'Deep compare with Unicode data' ); + # To convince you even more is( ord( $job->decoded_data->{favorite_Chinese}->[0] ), 33873, 'We still found Unicode \x8451' ); - is( ord( $job->decoded_data->{latin_dancing}->[0] ), 162, 'We still found the equivalent of Unicode \x00A2' ); + is( ord( $job->decoded_data->{latin_dancing}->[0] ), 162, 'We still found the equivalent of Unicode \x00A2' ); # Testing with sending encoded data (which we normally shouldn't do) my $utf8_data; foreach my $k ( 'favorite_Chinese', 'latin_dancing' ) { - foreach my $c ( @{$data->{$k}} ) { - push @{$utf8_data->{$k}}, Encode::encode('UTF-8', $c); + foreach my $c ( @{ $data->{$k} } ) { + push @{ $utf8_data->{$k} }, Encode::encode( 'UTF-8', $c ); } } - $job->set_encoded_data( $utf8_data )->store; - $job->discard_changes; # refresh + $job->set_encoded_data($utf8_data)->store; + $job->discard_changes; # refresh is_deeply( $job->decoded_data, $utf8_data, 'Deep compare with utf8_data' ); + # Need more evidence? - is( ord( $job->decoded_data->{favorite_Chinese}->[0] ), 232, 'We still found a UTF8 encoded byte' ); # ord does not need substr here + is( ord( $job->decoded_data->{favorite_Chinese}->[0] ), 232, 'We still found a UTF8 encoded byte' ) + ; # ord does not need substr here $schema->storage->txn_rollback; }; @@ -302,13 +306,13 @@ subtest 'decoded_data() and set_encoded_data() tests' => sub { plan tests => 2; $ENV{KOHA_STOMP_HOSTNAME} = "not_localhost"; - $ENV{KOHA_STOMP_PORT} = "99999"; + $ENV{KOHA_STOMP_PORT} = "99999"; - t::lib::Mocks::mock_preference('JobsNotificationMethod', 'STOMP'); + t::lib::Mocks::mock_preference( 'JobsNotificationMethod', 'STOMP' ); my $job = Koha::BackgroundJob->connect(); is( $job, undef, "Return undef if unable to connect when using stomp" ); - t::lib::Mocks::mock_preference('JobsNotificationMethod', 'polling'); + t::lib::Mocks::mock_preference( 'JobsNotificationMethod', 'polling' ); $job = Koha::BackgroundJob->connect(); is( $job, undef, "Return undef if using polling" ); -} + } diff --git a/t/db_dependent/Koha/BackgroundJob/BatchUpdateAuthority.t b/t/db_dependent/Koha/BackgroundJob/BatchUpdateAuthority.t index 9e9c223312..c4b045801c 100755 --- a/t/db_dependent/Koha/BackgroundJob/BatchUpdateAuthority.t +++ b/t/db_dependent/Koha/BackgroundJob/BatchUpdateAuthority.t @@ -45,7 +45,8 @@ subtest 'enqueue() tests' => sub { my $record_ids = [ 1, 2 ]; - $job_id = Koha::BackgroundJob::BatchUpdateAuthority->new->enqueue( { record_ids => $record_ids, mmtid => 'thing' } ); + $job_id = + Koha::BackgroundJob::BatchUpdateAuthority->new->enqueue( { record_ids => $record_ids, mmtid => 'thing' } ); my $job = Koha::BackgroundJobs->find($job_id)->_derived_class; is( $job->size, scalar @{$record_ids}, 'Size is correct' ); diff --git a/t/db_dependent/Koha/BackgroundJob/BatchUpdateBiblioHoldsQueue.t b/t/db_dependent/Koha/BackgroundJob/BatchUpdateBiblioHoldsQueue.t index f4f3f20440..fdb9587f37 100755 --- a/t/db_dependent/Koha/BackgroundJob/BatchUpdateBiblioHoldsQueue.t +++ b/t/db_dependent/Koha/BackgroundJob/BatchUpdateBiblioHoldsQueue.t @@ -45,9 +45,8 @@ subtest 'enqueue() tests' => sub { ); t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 1 ); - throws_ok - { Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue->new->enqueue() } - 'Koha::Exceptions::MissingParameter', + throws_ok { Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue->new->enqueue() } + 'Koha::Exceptions::MissingParameter', "Exception thrown if 'biblio_ids' param is missing"; like( "$@", qr/Missing biblio_ids parameter is mandatory/, 'Expected exception message' ); diff --git a/t/db_dependent/Koha/BackgroundJob/CreateEHoldingsFromBiblios.t b/t/db_dependent/Koha/BackgroundJob/CreateEHoldingsFromBiblios.t index aa829aa708..a35f0863f5 100755 --- a/t/db_dependent/Koha/BackgroundJob/CreateEHoldingsFromBiblios.t +++ b/t/db_dependent/Koha/BackgroundJob/CreateEHoldingsFromBiblios.t @@ -36,13 +36,11 @@ subtest 'enqueue' => sub { $schema->storage->txn_begin; # FIXME: Should be an exception - my $job_id = - Koha::BackgroundJob::CreateEHoldingsFromBiblios->new->enqueue(); + my $job_id = Koha::BackgroundJob::CreateEHoldingsFromBiblios->new->enqueue(); is( $job_id, undef, 'Nothing enqueued if missing params' ); # FIXME: Should be an exception - $job_id = Koha::BackgroundJob::CreateEHoldingsFromBiblios->new->enqueue( - { record_ids => undef } ); + $job_id = Koha::BackgroundJob::CreateEHoldingsFromBiblios->new->enqueue( { record_ids => undef } ); is( $job_id, undef, "Nothing enqueued if missing 'package_id' param" ); $schema->storage->txn_rollback; @@ -56,9 +54,8 @@ subtest 'process' => sub { $schema->storage->txn_begin; - my $biblio = $builder->build_sample_biblio; - my $package = - Koha::ERM::EHoldings::Package->new( { name => 'a package' } )->store; + my $biblio = $builder->build_sample_biblio; + my $package = Koha::ERM::EHoldings::Package->new( { name => 'a package' } )->store; my $job = Koha::BackgroundJob::CreateEHoldingsFromBiblios->new( { @@ -74,7 +71,7 @@ subtest 'process' => sub { }; my $json = $job->json->encode($data); $job->data($json)->store; - $package->delete; # Delete the package + $package->delete; # Delete the package $job->process($data); is( $job->report->{total_success}, 0 ); is_deeply( @@ -94,9 +91,8 @@ subtest 'process' => sub { $schema->storage->txn_begin; - my $biblio = $builder->build_sample_biblio; - my $package = - Koha::ERM::EHoldings::Package->new( { name => 'a package' } )->store; + my $biblio = $builder->build_sample_biblio; + my $package = Koha::ERM::EHoldings::Package->new( { name => 'a package' } )->store; my $job = Koha::BackgroundJob::CreateEHoldingsFromBiblios->new( { diff --git a/t/db_dependent/Koha/BackgroundJob/ImportKBARTFile.t b/t/db_dependent/Koha/BackgroundJob/ImportKBARTFile.t index e0abbb283a..8d3f9fa5b7 100755 --- a/t/db_dependent/Koha/BackgroundJob/ImportKBARTFile.t +++ b/t/db_dependent/Koha/BackgroundJob/ImportKBARTFile.t @@ -413,10 +413,10 @@ Nature Astronomy,,2397-3366,2017-01,1,1,,,,https://www.nature.com/natastron,,4bb $job3->messages, [ { - 'type' => 'error', - 'code' => 'no_title_found', - 'title_id' => '12345', - 'title' => '(Unknown)' + 'type' => 'error', + 'code' => 'no_title_found', + 'title_id' => '12345', + 'title' => '(Unknown)' }, { 'code' => 'title_already_exists', diff --git a/t/db_dependent/Koha/BackgroundJob/MARCImportCommitBatch.t b/t/db_dependent/Koha/BackgroundJob/MARCImportCommitBatch.t index 04651adc58..cf4aab5b96 100755 --- a/t/db_dependent/Koha/BackgroundJob/MARCImportCommitBatch.t +++ b/t/db_dependent/Koha/BackgroundJob/MARCImportCommitBatch.t @@ -35,10 +35,11 @@ subtest 'enqueue() tests' => sub { $schema->storage->txn_begin; - my $import_batch = $builder->build_object({ class => 'Koha::ImportBatches' }); + my $import_batch = $builder->build_object( { class => 'Koha::ImportBatches' } ); + # Add two records - $builder->build_object({ class => 'Koha::Import::Records', value => { import_batch_id => $import_batch->id } }); - $builder->build_object({ class => 'Koha::Import::Records', value => { import_batch_id => $import_batch->id } }); + $builder->build_object( { class => 'Koha::Import::Records', value => { import_batch_id => $import_batch->id } } ); + $builder->build_object( { class => 'Koha::Import::Records', value => { import_batch_id => $import_batch->id } } ); my $job_id = Koha::BackgroundJob::MARCImportCommitBatch->new->enqueue( { import_batch_id => $import_batch->id } ); my $job = Koha::BackgroundJobs->find($job_id)->_derived_class; diff --git a/t/db_dependent/Koha/BackgroundJob/MARCImportRevertBatch.t b/t/db_dependent/Koha/BackgroundJob/MARCImportRevertBatch.t index e77d2d4cae..72002d9897 100755 --- a/t/db_dependent/Koha/BackgroundJob/MARCImportRevertBatch.t +++ b/t/db_dependent/Koha/BackgroundJob/MARCImportRevertBatch.t @@ -35,10 +35,11 @@ subtest 'enqueue() tests' => sub { $schema->storage->txn_begin; - my $import_batch = $builder->build_object({ class => 'Koha::ImportBatches' }); + my $import_batch = $builder->build_object( { class => 'Koha::ImportBatches' } ); + # Add two records - $builder->build_object({ class => 'Koha::Import::Records', value => { import_batch_id => $import_batch->id } }); - $builder->build_object({ class => 'Koha::Import::Records', value => { import_batch_id => $import_batch->id } }); + $builder->build_object( { class => 'Koha::Import::Records', value => { import_batch_id => $import_batch->id } } ); + $builder->build_object( { class => 'Koha::Import::Records', value => { import_batch_id => $import_batch->id } } ); my $job_id = Koha::BackgroundJob::MARCImportRevertBatch->new->enqueue( { import_batch_id => $import_batch->id } ); my $job = Koha::BackgroundJobs->find($job_id)->_derived_class; diff --git a/t/db_dependent/Koha/BackgroundJob/StageMARCForImport.t b/t/db_dependent/Koha/BackgroundJob/StageMARCForImport.t index 1a8e0b495f..d8a1ca9c2d 100755 --- a/t/db_dependent/Koha/BackgroundJob/StageMARCForImport.t +++ b/t/db_dependent/Koha/BackgroundJob/StageMARCForImport.t @@ -35,7 +35,7 @@ subtest 'enqueue() tests' => sub { $schema->storage->txn_begin; - my $job_id = Koha::BackgroundJob::StageMARCForImport->new->enqueue({}); + my $job_id = Koha::BackgroundJob::StageMARCForImport->new->enqueue( {} ); my $job = Koha::BackgroundJobs->find($job_id)->_derived_class; is( $job->size, 0, 'Size is correct' ); diff --git a/t/db_dependent/Koha/BackgroundJob/UpdateElasticIndex.t b/t/db_dependent/Koha/BackgroundJob/UpdateElasticIndex.t index ccff377c04..2ebd32230d 100755 --- a/t/db_dependent/Koha/BackgroundJob/UpdateElasticIndex.t +++ b/t/db_dependent/Koha/BackgroundJob/UpdateElasticIndex.t @@ -45,11 +45,12 @@ subtest 'enqueue() tests' => sub { my $record_ids = [ 1, 2 ]; - $job_id = Koha::BackgroundJob::UpdateElasticIndex->new->enqueue( { record_ids => $record_ids, record_server => 'thing' } ); + $job_id = Koha::BackgroundJob::UpdateElasticIndex->new->enqueue( + { record_ids => $record_ids, record_server => 'thing' } ); my $job = Koha::BackgroundJobs->find($job_id)->_derived_class; - is( $job->size, 1, 'Size is correct' ); - is( $job->status, 'new', 'Initial status set correctly' ); + is( $job->size, 1, 'Size is correct' ); + is( $job->status, 'new', 'Initial status set correctly' ); is( $job->queue, 'elastic_index', 'BatchUpdateItem should use the default queue' ); $schema->storage->txn_rollback; diff --git a/t/db_dependent/Koha/BackgroundJobs.t b/t/db_dependent/Koha/BackgroundJobs.t index c8089d4488..521a0a2f8d 100755 --- a/t/db_dependent/Koha/BackgroundJobs.t +++ b/t/db_dependent/Koha/BackgroundJobs.t @@ -62,10 +62,14 @@ my $job_id = t::lib::Koha::BackgroundJob::BatchTest->new->enqueue( # Enqueuing a new job my $new_job = Koha::BackgroundJobs->find($job_id); ok( $new_job, 'New job correctly enqueued' ); -is_deeply( $new_job->json->decode( $new_job->data ), - $data, 'data retrieved and json encoded correctly' ); -is( t::lib::Dates::compare( $new_job->enqueued_on, dt_from_string ), - 0, 'enqueued_on correctly filled with now()' ); +is_deeply( + $new_job->json->decode( $new_job->data ), + $data, 'data retrieved and json encoded correctly' +); +is( + t::lib::Dates::compare( $new_job->enqueued_on, dt_from_string ), + 0, 'enqueued_on correctly filled with now()' +); is( $new_job->size, $job_size, 'job size retrieved correctly' ); is( $new_job->status, "new", 'job has not started yet, status is new' ); is( $new_job->type, "batch_test", 'job type retrieved from ->job_type' ); @@ -83,8 +87,8 @@ is( $new_job->status, "cancelled", "A cancelled job has not been processed" ); # Test new job to process $new_job->status('new')->store; $new_job = $new_job->process; -is( $new_job->status, "finished", 'job is new finished!' ); -is( scalar( @{ $new_job->messages } ), 10, '10 messages generated' ); +is( $new_job->status, "finished", 'job is new finished!' ); +is( scalar( @{ $new_job->messages } ), 10, '10 messages generated' ); is_deeply( $new_job->report, { total_records => 10, total_success => 10 }, @@ -101,24 +105,22 @@ subtest 'filter_by_current() tests' => sub { $schema->storage->txn_begin; - my $job_new = $builder->build_object( { class => 'Koha::BackgroundJobs', value => { status => 'new' } } ); - my $job_cancelled = $builder->build_object( { class => 'Koha::BackgroundJobs', value => { status => 'cancelled' } } ); - my $job_failed = $builder->build_object( { class => 'Koha::BackgroundJobs', value => { status => 'failed' } } ); - my $job_finished = $builder->build_object( { class => 'Koha::BackgroundJobs', value => { status => 'finished' } } ); + my $job_new = $builder->build_object( { class => 'Koha::BackgroundJobs', value => { status => 'new' } } ); + my $job_cancelled = + $builder->build_object( { class => 'Koha::BackgroundJobs', value => { status => 'cancelled' } } ); + my $job_failed = $builder->build_object( { class => 'Koha::BackgroundJobs', value => { status => 'failed' } } ); + my $job_finished = $builder->build_object( { class => 'Koha::BackgroundJobs', value => { status => 'finished' } } ); my $rs = Koha::BackgroundJobs->search( - { - id => [ $job_new->id, $job_cancelled->id, $job_failed->id, $job_finished->id ] - } - ); + { id => [ $job_new->id, $job_cancelled->id, $job_failed->id, $job_finished->id ] } ); is( $rs->count, 4, '4 jobs in resultset' ); - ok( any {$_->status eq 'new'} @{$rs->as_list}, "There is a 'new' job" ); + ok( any { $_->status eq 'new' } @{ $rs->as_list }, "There is a 'new' job" ); $rs = $rs->filter_by_current; - is( $rs->count, 1, 'Only 1 job in filtered resultset' ); - is( $rs->next->status, 'new', "The only job in resultset is 'new'" ); + is( $rs->count, 1, 'Only 1 job in filtered resultset' ); + is( $rs->next->status, 'new', "The only job in resultset is 'new'" ); $schema->storage->txn_rollback; }; @@ -129,9 +131,11 @@ subtest 'search_limited' => sub { $schema->storage->txn_begin; my $patron1 = $builder->build_object( { class => 'Koha::Patrons', value => { flags => 0 } } ); my $patron2 = $builder->build_object( { class => 'Koha::Patrons', value => { flags => 0 } } ); - my $job1 = $builder->build_object( { class => 'Koha::BackgroundJobs', value => { borrowernumber => $patron1->id } } ); + my $job1 = + $builder->build_object( { class => 'Koha::BackgroundJobs', value => { borrowernumber => $patron1->id } } ); - my $cnt = Koha::BackgroundJobs->search({ borrowernumber => undef })->count; # expected to be zero, but theoretically possible + my $cnt = Koha::BackgroundJobs->search( { borrowernumber => undef } ) + ->count; # expected to be zero, but theoretically possible C4::Context->set_userenv( undef, q{} ); is( Koha::BackgroundJobs->search_limited->count, $cnt, 'No jobs found without userenv' ); diff --git a/t/db_dependent/Koha/BackgroundJobs/BatchDeleteBiblio.t b/t/db_dependent/Koha/BackgroundJobs/BatchDeleteBiblio.t index fa1a332fb4..02bf645391 100755 --- a/t/db_dependent/Koha/BackgroundJobs/BatchDeleteBiblio.t +++ b/t/db_dependent/Koha/BackgroundJobs/BatchDeleteBiblio.t @@ -31,7 +31,7 @@ use Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue; use t::lib::Mocks; use t::lib::TestBuilder; -my $schema = Koha::Database->new->schema; +my $schema = Koha::Database->new->schema; my $builder = t::lib::TestBuilder->new; subtest "process() tests" => sub { @@ -40,13 +40,13 @@ subtest "process() tests" => sub { $schema->storage->txn_begin; - t::lib::Mocks::mock_preference('SearchEngine', 'Elasticsearch'); + t::lib::Mocks::mock_preference( 'SearchEngine', 'Elasticsearch' ); my $biblio = $builder->build_sample_biblio; - my $item_1 = $builder->build_sample_item({ biblionumber => $biblio->id }); - my $item_2 = $builder->build_sample_item({ biblionumber => $biblio->id }); + my $item_1 = $builder->build_sample_item( { biblionumber => $biblio->id } ); + my $item_2 = $builder->build_sample_item( { biblionumber => $biblio->id } ); - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); AddReserve( { borrowernumber => $patron->id, @@ -59,16 +59,22 @@ subtest "process() tests" => sub { my $update_biblio_counter = 0; my $mock_holds_queue_job = Test::MockModule->new('Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue'); - $mock_holds_queue_job->mock( 'enqueue', sub { - $update_biblio_counter++; - }); + $mock_holds_queue_job->mock( + 'enqueue', + sub { + $update_biblio_counter++; + } + ); my $index_biblio_counter = 0; my $mock_index = Test::MockModule->new("Koha::SearchEngine::Elasticsearch::Indexer"); - $mock_index->mock( 'index_records', sub { - $index_biblio_counter++; - }); + $mock_index->mock( + 'index_records', + sub { + $index_biblio_counter++; + } + ); my $job = Koha::BackgroundJob::BatchDeleteBiblio->new( { @@ -77,7 +83,7 @@ subtest "process() tests" => sub { borrowernumber => undef, type => 'batch_biblio_record_deletion', data => encode_json { - record_ids => [ $biblio->id ], + record_ids => [ $biblio->id ], } } ); @@ -104,7 +110,7 @@ subtest "process() tests" => sub { borrowernumber => undef, type => 'batch_biblio_record_deletion', data => encode_json { - record_ids => [ $biblio->id ], + record_ids => [ $biblio->id ], } } ); diff --git a/t/db_dependent/Koha/BackgroundJobs/BatchDeleteItem.t b/t/db_dependent/Koha/BackgroundJobs/BatchDeleteItem.t index ee40088c8c..6f02ac7a14 100755 --- a/t/db_dependent/Koha/BackgroundJobs/BatchDeleteItem.t +++ b/t/db_dependent/Koha/BackgroundJobs/BatchDeleteItem.t @@ -28,7 +28,7 @@ use Koha::BackgroundJob::BatchDeleteItem; use t::lib::Mocks; use t::lib::TestBuilder; -my $schema = Koha::Database->new->schema; +my $schema = Koha::Database->new->schema; my $builder = t::lib::TestBuilder->new; subtest "process() tests" => sub { @@ -38,15 +38,18 @@ subtest "process() tests" => sub { $schema->storage->txn_begin; my $biblio = $builder->build_sample_biblio; - my $item_1 = $builder->build_sample_item({ biblionumber => $biblio->id }); - my $item_2 = $builder->build_sample_item({ biblionumber => $biblio->id }); + my $item_1 = $builder->build_sample_item( { biblionumber => $biblio->id } ); + my $item_2 = $builder->build_sample_item( { biblionumber => $biblio->id } ); my $counter = 0; my $mock_holds_queue_job = Test::MockModule->new('Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue'); - $mock_holds_queue_job->mock( 'enqueue', sub { - $counter++; - }); + $mock_holds_queue_job->mock( + 'enqueue', + sub { + $counter++; + } + ); t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 1 ); @@ -75,7 +78,7 @@ subtest "process() tests" => sub { t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 0 ); $biblio = $builder->build_sample_biblio; - my $item = $builder->build_sample_item({ biblionumber => $biblio->id }); + my $item = $builder->build_sample_item( { biblionumber => $biblio->id } ); $job = Koha::BackgroundJob::BatchDeleteItem->new( { diff --git a/t/db_dependent/Koha/BackgroundJobs/BatchUpdateBiblio.t b/t/db_dependent/Koha/BackgroundJobs/BatchUpdateBiblio.t index aa9b0e49d5..66a5c0cbec 100755 --- a/t/db_dependent/Koha/BackgroundJobs/BatchUpdateBiblio.t +++ b/t/db_dependent/Koha/BackgroundJobs/BatchUpdateBiblio.t @@ -38,8 +38,10 @@ subtest "Exceptions must be stringified" => sub { $schema->storage->txn_begin; my $C4_biblio_module = Test::MockModule->new('C4::Biblio'); - $C4_biblio_module->mock( 'ModBiblio', - sub { Koha::Exception->throw("It didn't work"); } ); + $C4_biblio_module->mock( + 'ModBiblio', + sub { Koha::Exception->throw("It didn't work"); } + ); my $biblio = $builder->build_sample_biblio; my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); @@ -51,11 +53,10 @@ subtest "Exceptions must be stringified" => sub { type => 'batch_biblio_record_modification', } ); - my $data = $job->json->encode({ record_ids => [ $biblio->biblionumber ] }); - $job->data( $data )->store; + my $data = $job->json->encode( { record_ids => [ $biblio->biblionumber ] } ); + $job->data($data)->store; $job = Koha::BackgroundJobs->find( $job->id ); - $job->process( - { job_id => $job->id, record_ids => [ $biblio->biblionumber ] } ); + $job->process( { job_id => $job->id, record_ids => [ $biblio->biblionumber ] } ); $data = $job->json->decode( $job->get_from_storage->data ); is_deeply( diff --git a/t/db_dependent/Koha/BackgroundJobs/StageMARCForImport.t b/t/db_dependent/Koha/BackgroundJobs/StageMARCForImport.t index 7818807830..78342ab414 100755 --- a/t/db_dependent/Koha/BackgroundJobs/StageMARCForImport.t +++ b/t/db_dependent/Koha/BackgroundJobs/StageMARCForImport.t @@ -67,7 +67,7 @@ subtest 'StageMARCForImport' => sub { } ); - my $report = decode_json($job->get_from_storage->data)->{report}; + my $report = decode_json( $job->get_from_storage->data )->{report}; is( $report->{num_items}, 138 ); is( $report->{staged}, 178 ); is( $report->{total}, 179 ); diff --git a/t/db_dependent/Koha/Biblio.t b/t/db_dependent/Koha/Biblio.t index aa753903c0..9d697b7850 100755 --- a/t/db_dependent/Koha/Biblio.t +++ b/t/db_dependent/Koha/Biblio.t @@ -21,9 +21,9 @@ use Test::More tests => 39; use Test::Exception; use Test::Warn; -use C4::Biblio qw( AddBiblio ModBiblio ModBiblioMarc ); +use C4::Biblio qw( AddBiblio ModBiblio ModBiblioMarc ); use C4::Circulation qw( AddIssue AddReturn ); -use C4::Reserves qw( AddReserve ); +use C4::Reserves qw( AddReserve ); use Koha::Database; use Koha::DateUtils qw( dt_from_string ); @@ -59,11 +59,11 @@ subtest 'metadata() tests' => sub { my $title = 'Oranges and Peaches'; my $record = MARC::Record->new(); - my $field = MARC::Field->new('245','','','a' => $title); - $record->append_fields( $field ); - my ($biblionumber) = C4::Biblio::AddBiblio($record, ''); + my $field = MARC::Field->new( '245', '', '', 'a' => $title ); + $record->append_fields($field); + my ($biblionumber) = C4::Biblio::AddBiblio( $record, '' ); - my $biblio = Koha::Biblios->find( $biblionumber ); + my $biblio = Koha::Biblios->find($biblionumber); is( ref $biblio, 'Koha::Biblio', 'Found a Koha::Biblio object' ); my $metadata = $biblio->metadata; @@ -84,39 +84,39 @@ subtest 'hidden_in_opac() tests' => sub { $schema->storage->txn_begin; my $biblio = $builder->build_sample_biblio(); - my $rules = { withdrawn => [ 2 ] }; + my $rules = { withdrawn => [2] }; t::lib::Mocks::mock_preference( 'OpacHiddenItemsHidesRecord', 0 ); ok( - !$biblio->hidden_in_opac({ rules => $rules }), + !$biblio->hidden_in_opac( { rules => $rules } ), 'Biblio not hidden if there is no item attached (!OpacHiddenItemsHidesRecord)' ); t::lib::Mocks::mock_preference( 'OpacHiddenItemsHidesRecord', 1 ); ok( - !$biblio->hidden_in_opac({ rules => $rules }), + !$biblio->hidden_in_opac( { rules => $rules } ), 'Biblio not hidden if there is no item attached (OpacHiddenItemsHidesRecord)' ); - my $item_1 = $builder->build_sample_item({ biblionumber => $biblio->biblionumber }); - my $item_2 = $builder->build_sample_item({ biblionumber => $biblio->biblionumber }); + my $item_1 = $builder->build_sample_item( { biblionumber => $biblio->biblionumber } ); + my $item_2 = $builder->build_sample_item( { biblionumber => $biblio->biblionumber } ); - $item_1->withdrawn( 1 )->store->discard_changes; - $item_2->withdrawn( 1 )->store->discard_changes; + $item_1->withdrawn(1)->store->discard_changes; + $item_2->withdrawn(1)->store->discard_changes; - ok( !$biblio->hidden_in_opac({ rules => $rules }), 'Biblio not hidden' ); + ok( !$biblio->hidden_in_opac( { rules => $rules } ), 'Biblio not hidden' ); - $item_2->withdrawn( 2 )->store->discard_changes; - $biblio->discard_changes; # refresh + $item_2->withdrawn(2)->store->discard_changes; + $biblio->discard_changes; # refresh - ok( !$biblio->hidden_in_opac({ rules => $rules }), 'Biblio not hidden' ); + ok( !$biblio->hidden_in_opac( { rules => $rules } ), 'Biblio not hidden' ); - $item_1->withdrawn( 2 )->store->discard_changes; - $biblio->discard_changes; # refresh + $item_1->withdrawn(2)->store->discard_changes; + $biblio->discard_changes; # refresh - ok( $biblio->hidden_in_opac({ rules => $rules }), 'Biblio hidden' ); + ok( $biblio->hidden_in_opac( { rules => $rules } ), 'Biblio hidden' ); t::lib::Mocks::mock_preference( 'OpacHiddenItemsHidesRecord', 0 ); ok( @@ -124,7 +124,6 @@ subtest 'hidden_in_opac() tests' => sub { 'Biblio hidden (!OpacHiddenItemsHidesRecord)' ); - $schema->storage->txn_rollback; }; @@ -138,12 +137,12 @@ subtest 'items() tests' => sub { is( $biblio->items->count, 0, 'No items, count is 0' ); - my $item_1 = $builder->build_sample_item({ biblionumber => $biblio->biblionumber }); - my $item_2 = $builder->build_sample_item({ biblionumber => $biblio->biblionumber }); + my $item_1 = $builder->build_sample_item( { biblionumber => $biblio->biblionumber } ); + my $item_2 = $builder->build_sample_item( { biblionumber => $biblio->biblionumber } ); my $items = $biblio->items; - is( ref($items), 'Koha::Items', 'Returns a Koha::Items resultset' ); - is( $items->count, 2, 'Two items in resultset' ); + is( ref($items), 'Koha::Items', 'Returns a Koha::Items resultset' ); + is( $items->count, 2, 'Two items in resultset' ); $schema->storage->txn_rollback; @@ -180,10 +179,12 @@ subtest 'get_coins and get_openurl' => sub { $schema->storage->txn_begin; my $builder = t::lib::TestBuilder->new; - my $biblio = $builder->build_sample_biblio({ - title => 'Title 1', + my $biblio = $builder->build_sample_biblio( + { + title => 'Title 1', author => 'Author 1' - }); + } + ); is( $biblio->get_coins, 'ctx_ver=Z39.88-2004&rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook&rft.genre=book&rft.btitle=Title%201&rft.au=Author%201', @@ -191,8 +192,11 @@ subtest 'get_coins and get_openurl' => sub { ); my $record = MARC::Record->new(); - $record->append_fields( MARC::Field->new('100','','','a' => 'Author 2'), MARC::Field->new('880','','','a' => 'Something') ); - my ( $biblionumber ) = C4::Biblio::AddBiblio($record, ''); + $record->append_fields( + MARC::Field->new( '100', '', '', 'a' => 'Author 2' ), + MARC::Field->new( '880', '', '', 'a' => 'Something' ) + ); + my ($biblionumber) = C4::Biblio::AddBiblio( $record, '' ); my $biblio_no_title = Koha::Biblios->find($biblionumber); is( $biblio_no_title->get_coins, @@ -200,14 +204,14 @@ subtest 'get_coins and get_openurl' => sub { 'GetCOinsBiblio returned right metadata if biblio does not have a title' ); - t::lib::Mocks::mock_preference("OpenURLResolverURL", "https://koha.example.com/"); + t::lib::Mocks::mock_preference( "OpenURLResolverURL", "https://koha.example.com/" ); is( $biblio->get_openurl, 'https://koha.example.com/?ctx_ver=Z39.88-2004&rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook&rft.genre=book&rft.btitle=Title%201&rft.au=Author%201', 'Koha::Biblio->get_openurl returned right URL' ); - t::lib::Mocks::mock_preference("OpenURLResolverURL", "https://koha.example.com/?client_id=ci1"); + t::lib::Mocks::mock_preference( "OpenURLResolverURL", "https://koha.example.com/?client_id=ci1" ); is( $biblio->get_openurl, 'https://koha.example.com/?client_id=ci1&ctx_ver=Z39.88-2004&rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook&rft.genre=book&rft.btitle=Title%201&rft.au=Author%201', @@ -225,16 +229,16 @@ subtest 'is_serial() tests' => sub { my $biblio = $builder->build_sample_biblio(); - $biblio->serial( 1 )->store->discard_changes; + $biblio->serial(1)->store->discard_changes; ok( $biblio->is_serial, 'Bibliographic record is serial' ); - $biblio->serial( 0 )->store->discard_changes; + $biblio->serial(0)->store->discard_changes; ok( !$biblio->is_serial, 'Bibliographic record is not serial' ); my $record = $biblio->metadata->record; $record->leader('00142nas a22 7a 4500'); - ModBiblio($record, $biblio->biblionumber ); - $biblio = Koha::Biblios->find($biblio->biblionumber); + ModBiblio( $record, $biblio->biblionumber ); + $biblio = Koha::Biblios->find( $biblio->biblionumber ); ok( $biblio->is_serial, 'Bibliographic record is serial' ); @@ -263,25 +267,34 @@ subtest 'pickup_locations() tests' => sub { my $root2 = $builder->build_object( { class => 'Koha::Library::Groups', value => { ft_local_hold_group => 1 } } ); my $root3 = $builder->build_object( { class => 'Koha::Library::Groups', value => { ft_local_hold_group => 1 } } ); - my $library1 = $builder->build_object( { class => 'Koha::Libraries', value => { pickup_location => 1, branchname => 'zzz' } } ); - my $library2 = $builder->build_object( { class => 'Koha::Libraries', value => { pickup_location => 1, branchname => 'AAA' } } ); - my $library3 = $builder->build_object( { class => 'Koha::Libraries', value => { pickup_location => 0, branchname => 'FFF' } } ); - my $library4 = $builder->build_object( { class => 'Koha::Libraries', value => { pickup_location => 1, branchname => 'CCC' } } ); - my $library5 = $builder->build_object( { class => 'Koha::Libraries', value => { pickup_location => 1, branchname => 'eee' } } ); - my $library6 = $builder->build_object( { class => 'Koha::Libraries', value => { pickup_location => 1, branchname => 'BBB' } } ); - my $library7 = $builder->build_object( { class => 'Koha::Libraries', value => { pickup_location => 1, branchname => 'DDD' } } ); - my $library8 = $builder->build_object( { class => 'Koha::Libraries', value => { pickup_location => 0, branchname => 'GGG' } } ); + my $library1 = $builder->build_object( + { class => 'Koha::Libraries', value => { pickup_location => 1, branchname => 'zzz' } } ); + my $library2 = $builder->build_object( + { class => 'Koha::Libraries', value => { pickup_location => 1, branchname => 'AAA' } } ); + my $library3 = $builder->build_object( + { class => 'Koha::Libraries', value => { pickup_location => 0, branchname => 'FFF' } } ); + my $library4 = $builder->build_object( + { class => 'Koha::Libraries', value => { pickup_location => 1, branchname => 'CCC' } } ); + my $library5 = $builder->build_object( + { class => 'Koha::Libraries', value => { pickup_location => 1, branchname => 'eee' } } ); + my $library6 = $builder->build_object( + { class => 'Koha::Libraries', value => { pickup_location => 1, branchname => 'BBB' } } ); + my $library7 = $builder->build_object( + { class => 'Koha::Libraries', value => { pickup_location => 1, branchname => 'DDD' } } ); + my $library8 = $builder->build_object( + { class => 'Koha::Libraries', value => { pickup_location => 0, branchname => 'GGG' } } ); - our @branchcodes = map { $_->branchcode } ($library1, $library2, $library3, $library4, $library5, $library6, $library7, $library8); + our @branchcodes = map { $_->branchcode } + ( $library1, $library2, $library3, $library4, $library5, $library6, $library7, $library8 ); Koha::CirculationRules->set_rules( { branchcode => $library1->branchcode, itemtype => undef, - rules => { - holdallowed => 'from_home_library', + rules => { + holdallowed => 'from_home_library', hold_fulfillment_policy => 'any', - returnbranch => 'any' + returnbranch => 'any' } } ); @@ -290,10 +303,10 @@ subtest 'pickup_locations() tests' => sub { { branchcode => $library2->branchcode, itemtype => undef, - rules => { - holdallowed => 'from_local_hold_group', + rules => { + holdallowed => 'from_local_hold_group', hold_fulfillment_policy => 'holdgroup', - returnbranch => 'any' + returnbranch => 'any' } } ); @@ -302,10 +315,10 @@ subtest 'pickup_locations() tests' => sub { { branchcode => $library3->branchcode, itemtype => undef, - rules => { - holdallowed => 'from_local_hold_group', + rules => { + holdallowed => 'from_local_hold_group', hold_fulfillment_policy => 'patrongroup', - returnbranch => 'any' + returnbranch => 'any' } } ); @@ -314,10 +327,10 @@ subtest 'pickup_locations() tests' => sub { { branchcode => $library4->branchcode, itemtype => undef, - rules => { - holdallowed => 'from_any_library', + rules => { + holdallowed => 'from_any_library', hold_fulfillment_policy => 'holdingbranch', - returnbranch => 'any' + returnbranch => 'any' } } ); @@ -326,10 +339,10 @@ subtest 'pickup_locations() tests' => sub { { branchcode => $library5->branchcode, itemtype => undef, - rules => { - holdallowed => 'from_any_library', + rules => { + holdallowed => 'from_any_library', hold_fulfillment_policy => 'homebranch', - returnbranch => 'any' + returnbranch => 'any' } } ); @@ -338,10 +351,10 @@ subtest 'pickup_locations() tests' => sub { { branchcode => $library6->branchcode, itemtype => undef, - rules => { - holdallowed => 'from_home_library', + rules => { + holdallowed => 'from_home_library', hold_fulfillment_policy => 'holdgroup', - returnbranch => 'any' + returnbranch => 'any' } } ); @@ -350,96 +363,124 @@ subtest 'pickup_locations() tests' => sub { { branchcode => $library7->branchcode, itemtype => undef, - rules => { - holdallowed => 'from_local_hold_group', + rules => { + holdallowed => 'from_local_hold_group', hold_fulfillment_policy => 'holdingbranch', - returnbranch => 'any' + returnbranch => 'any' } } ); - Koha::CirculationRules->set_rules( { branchcode => $library8->branchcode, itemtype => undef, - rules => { - holdallowed => 'from_any_library', + rules => { + holdallowed => 'from_any_library', hold_fulfillment_policy => 'patrongroup', - returnbranch => 'any' + returnbranch => 'any' } } ); - my $group1_1 = $builder->build_object( { class => 'Koha::Library::Groups', value => { parent_id => $root1->id, branchcode => $library1->branchcode } } ); - my $group1_2 = $builder->build_object( { class => 'Koha::Library::Groups', value => { parent_id => $root1->id, branchcode => $library2->branchcode } } ); + my $group1_1 = $builder->build_object( + { class => 'Koha::Library::Groups', value => { parent_id => $root1->id, branchcode => $library1->branchcode } } + ); + my $group1_2 = $builder->build_object( + { class => 'Koha::Library::Groups', value => { parent_id => $root1->id, branchcode => $library2->branchcode } } + ); - my $group2_3 = $builder->build_object( { class => 'Koha::Library::Groups', value => { parent_id => $root2->id, branchcode => $library3->branchcode } } ); - my $group2_4 = $builder->build_object( { class => 'Koha::Library::Groups', value => { parent_id => $root2->id, branchcode => $library4->branchcode } } ); + my $group2_3 = $builder->build_object( + { class => 'Koha::Library::Groups', value => { parent_id => $root2->id, branchcode => $library3->branchcode } } + ); + my $group2_4 = $builder->build_object( + { class => 'Koha::Library::Groups', value => { parent_id => $root2->id, branchcode => $library4->branchcode } } + ); - my $group3_5 = $builder->build_object( { class => 'Koha::Library::Groups', value => { parent_id => $root3->id, branchcode => $library5->branchcode } } ); - my $group3_6 = $builder->build_object( { class => 'Koha::Library::Groups', value => { parent_id => $root3->id, branchcode => $library6->branchcode } } ); - my $group3_7 = $builder->build_object( { class => 'Koha::Library::Groups', value => { parent_id => $root3->id, branchcode => $library7->branchcode } } ); - my $group3_8 = $builder->build_object( { class => 'Koha::Library::Groups', value => { parent_id => $root3->id, branchcode => $library8->branchcode } } ); + my $group3_5 = $builder->build_object( + { class => 'Koha::Library::Groups', value => { parent_id => $root3->id, branchcode => $library5->branchcode } } + ); + my $group3_6 = $builder->build_object( + { class => 'Koha::Library::Groups', value => { parent_id => $root3->id, branchcode => $library6->branchcode } } + ); + my $group3_7 = $builder->build_object( + { class => 'Koha::Library::Groups', value => { parent_id => $root3->id, branchcode => $library7->branchcode } } + ); + my $group3_8 = $builder->build_object( + { class => 'Koha::Library::Groups', value => { parent_id => $root3->id, branchcode => $library8->branchcode } } + ); - my $biblio1 = $builder->build_sample_biblio({ title => '1' }); - my $biblio2 = $builder->build_sample_biblio({ title => '2' }); + my $biblio1 = $builder->build_sample_biblio( { title => '1' } ); + my $biblio2 = $builder->build_sample_biblio( { title => '2' } ); - throws_ok - { $biblio1->pickup_locations } - 'Koha::Exceptions::MissingParameter', - 'Exception thrown on missing parameter'; + throws_ok { $biblio1->pickup_locations } + 'Koha::Exceptions::MissingParameter', + 'Exception thrown on missing parameter'; is( $@->parameter, 'patron', 'Exception param correctly set' ); - my $item1_1 = $builder->build_sample_item({ - biblionumber => $biblio1->biblionumber, - homebranch => $library1->branchcode, - holdingbranch => $library2->branchcode, - })->store; + my $item1_1 = $builder->build_sample_item( + { + biblionumber => $biblio1->biblionumber, + homebranch => $library1->branchcode, + holdingbranch => $library2->branchcode, + } + )->store; - my $item1_3 = $builder->build_sample_item({ - biblionumber => $biblio1->biblionumber, - homebranch => $library3->branchcode, - holdingbranch => $library4->branchcode, - })->store; + my $item1_3 = $builder->build_sample_item( + { + biblionumber => $biblio1->biblionumber, + homebranch => $library3->branchcode, + holdingbranch => $library4->branchcode, + } + )->store; - my $item1_7 = $builder->build_sample_item({ - biblionumber => $biblio1->biblionumber, - homebranch => $library7->branchcode, - holdingbranch => $library4->branchcode, - })->store; + my $item1_7 = $builder->build_sample_item( + { + biblionumber => $biblio1->biblionumber, + homebranch => $library7->branchcode, + holdingbranch => $library4->branchcode, + } + )->store; - my $item2_2 = $builder->build_sample_item({ - biblionumber => $biblio2->biblionumber, - homebranch => $library2->branchcode, - holdingbranch => $library1->branchcode, - })->store; + my $item2_2 = $builder->build_sample_item( + { + biblionumber => $biblio2->biblionumber, + homebranch => $library2->branchcode, + holdingbranch => $library1->branchcode, + } + )->store; - my $item2_4 = $builder->build_sample_item({ - biblionumber => $biblio2->biblionumber, - homebranch => $library4->branchcode, - holdingbranch => $library3->branchcode, - })->store; + my $item2_4 = $builder->build_sample_item( + { + biblionumber => $biblio2->biblionumber, + homebranch => $library4->branchcode, + holdingbranch => $library3->branchcode, + } + )->store; - my $item2_6 = $builder->build_sample_item({ - biblionumber => $biblio2->biblionumber, - homebranch => $library6->branchcode, - holdingbranch => $library4->branchcode, - })->store; + my $item2_6 = $builder->build_sample_item( + { + biblionumber => $biblio2->biblionumber, + homebranch => $library6->branchcode, + holdingbranch => $library4->branchcode, + } + )->store; - my $patron1 = $builder->build_object( { class => 'Koha::Patrons', value => { firstname=>'1', branchcode => $library1->branchcode } } ); - my $patron8 = $builder->build_object( { class => 'Koha::Patrons', value => { firstname=>'8', branchcode => $library8->branchcode } } ); + my $patron1 = $builder->build_object( + { class => 'Koha::Patrons', value => { firstname => '1', branchcode => $library1->branchcode } } ); + my $patron8 = $builder->build_object( + { class => 'Koha::Patrons', value => { firstname => '8', branchcode => $library8->branchcode } } ); my $results = { "ItemHomeLibrary-1-1" => 6, "ItemHomeLibrary-1-8" => 1, "ItemHomeLibrary-2-1" => 2, "ItemHomeLibrary-2-8" => 0, - "PatronLibrary-1-1" => 6, - "PatronLibrary-1-8" => 3, - "PatronLibrary-2-1" => 0, - "PatronLibrary-2-8" => 3, + "PatronLibrary-1-1" => 6, + "PatronLibrary-1-8" => 3, + "PatronLibrary-2-1" => 0, + "PatronLibrary-2-8" => 3, }; my $items_results = { @@ -516,19 +557,19 @@ subtest 'pickup_locations() tests' => sub { ); } - foreach my $cbranch ('ItemHomeLibrary','PatronLibrary') { + foreach my $cbranch ( 'ItemHomeLibrary', 'PatronLibrary' ) { my $cache = Koha::Cache::Memory::Lite->get_instance(); - $cache->flush(); # needed since we change ReservesControlBranch - foreach my $biblio ($biblio1, $biblio2) { - foreach my $patron ($patron1, $patron8) { - _doTest($cbranch, $biblio, $patron, $results, $items_results); + $cache->flush(); # needed since we change ReservesControlBranch + foreach my $biblio ( $biblio1, $biblio2 ) { + foreach my $patron ( $patron1, $patron8 ) { + _doTest( $cbranch, $biblio, $patron, $results, $items_results ); } } } - my @pl_names = map { $_->branchname } $biblio1->pickup_locations( { patron => $patron1 } )->as_list; - my $pl_ori_str = join('|', @pl_names); - my $pl_sorted_str = join('|', sort { lc($a) cmp lc($b) } @pl_names); + my @pl_names = map { $_->branchname } $biblio1->pickup_locations( { patron => $patron1 } )->as_list; + my $pl_ori_str = join( '|', @pl_names ); + my $pl_sorted_str = join( '|', sort { lc($a) cmp lc($b) } @pl_names ); ok( $pl_ori_str eq $pl_sorted_str, 'Libraries must be sorted by name' @@ -541,18 +582,18 @@ subtest 'to_api() tests' => sub { $schema->storage->txn_begin; my $biblio = $builder->build_sample_biblio(); - my $item = $builder->build_sample_item({ biblionumber => $biblio->biblionumber }); + my $item = $builder->build_sample_item( { biblionumber => $biblio->biblionumber } ); my $biblioitem_api = $biblio->biblioitem->to_api; my $biblio_api = $biblio->to_api; - plan tests => (scalar keys %{ $biblioitem_api }) + 1; + plan tests => ( scalar keys %{$biblioitem_api} ) + 1; - foreach my $key ( keys %{ $biblioitem_api } ) { + foreach my $key ( keys %{$biblioitem_api} ) { is( $biblio_api->{$key}, $biblioitem_api->{$key}, "$key is added to the biblio object" ); } - $biblio_api = $biblio->to_api({ embed => { items => {} } }); + $biblio_api = $biblio->to_api( { embed => { items => {} } } ); is_deeply( $biblio_api->{items}, [ $item->to_api ], 'Item correctly embedded' ); $schema->storage->txn_rollback; @@ -774,9 +815,9 @@ subtest 'suggestions() tests' => sub { $schema->storage->txn_begin; - my $biblio = $builder->build_sample_biblio(); + my $biblio = $builder->build_sample_biblio(); - is( ref($biblio->suggestions), 'Koha::Suggestions', 'Return type is correct' ); + is( ref( $biblio->suggestions ), 'Koha::Suggestions', 'Return type is correct' ); is_deeply( $biblio->suggestions->unblessed, @@ -808,10 +849,10 @@ subtest 'get_marc_components() tests' => sub { $schema->storage->txn_begin; - my ($host_bibnum) = C4::Biblio::AddBiblio(host_record(), ''); + my ($host_bibnum) = C4::Biblio::AddBiblio( host_record(), '' ); my $host_biblio = Koha::Biblios->find($host_bibnum); t::lib::Mocks::mock_preference( 'SearchEngine', 'Zebra' ); - my $search_mod = Test::MockModule->new( 'Koha::SearchEngine::Zebra::Search' ); + my $search_mod = Test::MockModule->new('Koha::SearchEngine::Zebra::Search'); $search_mod->mock( 'search_compat', \&search_component_record2 ); my $components = $host_biblio->get_marc_components; @@ -823,7 +864,7 @@ subtest 'get_marc_components() tests' => sub { '->get_marc_components returns an empty ARRAY' ); - $search_mod->unmock( 'search_compat'); + $search_mod->unmock('search_compat'); $search_mod->mock( 'search_compat', \&search_component_record1 ); my $component_record = component_record1()->as_xml(); @@ -832,13 +873,14 @@ subtest 'get_marc_components() tests' => sub { [$component_record], '->get_marc_components returns the related component part record' ); - $search_mod->unmock( 'search_compat'); + $search_mod->unmock('search_compat'); - $search_mod->mock( 'search_compat', + $search_mod->mock( + 'search_compat', sub { Koha::Exception->throw("error searching analytics") } ); warning_like { $components = $host_biblio->get_marc_components } - qr{Warning from search_compat: .* 'error searching analytics'}; + qr{Warning from search_compat: .* 'error searching analytics'}; is_deeply( $host_biblio->object_messages, @@ -850,7 +892,7 @@ subtest 'get_marc_components() tests' => sub { } ] ); - $search_mod->unmock( 'search_compat'); + $search_mod->unmock('search_compat'); $schema->storage->txn_rollback; }; @@ -860,41 +902,48 @@ subtest 'get_components_query' => sub { $schema->storage->txn_begin; - my $biblio = $builder->build_sample_biblio(); + my $biblio = $builder->build_sample_biblio(); my $biblionumber = $biblio->biblionumber; - my $record = $biblio->metadata->record; + my $record = $biblio->metadata->record; - foreach my $engine ('Zebra','Elasticsearch'){ + foreach my $engine ( 'Zebra', 'Elasticsearch' ) { t::lib::Mocks::mock_preference( 'SearchEngine', $engine ); - t::lib::Mocks::mock_preference( 'UseControlNumber', '0' ); + t::lib::Mocks::mock_preference( 'UseControlNumber', '0' ); t::lib::Mocks::mock_preference( 'ComponentSortField', 'author' ); t::lib::Mocks::mock_preference( 'ComponentSortOrder', 'za' ); my ( $comp_query, $comp_query_str, $comp_sort ) = $biblio->get_components_query; - is($comp_query_str, 'Host-item:("Some boring read")', "$engine: UseControlNumber disabled"); - is($comp_sort, "author_za", "$engine: UseControlNumber disabled sort is correct"); + is( $comp_query_str, 'Host-item:("Some boring read")', "$engine: UseControlNumber disabled" ); + is( $comp_sort, "author_za", "$engine: UseControlNumber disabled sort is correct" ); - t::lib::Mocks::mock_preference( 'UseControlNumber', '1' ); + t::lib::Mocks::mock_preference( 'UseControlNumber', '1' ); t::lib::Mocks::mock_preference( 'ComponentSortOrder', 'az' ); - my $marc_001_field = MARC::Field->new('001', $biblionumber); + my $marc_001_field = MARC::Field->new( '001', $biblionumber ); $record->append_fields($marc_001_field); C4::Biblio::ModBiblio( $record, $biblio->biblionumber ); - $biblio = Koha::Biblios->find( $biblio->biblionumber); + $biblio = Koha::Biblios->find( $biblio->biblionumber ); ( $comp_query, $comp_query_str, $comp_sort ) = $biblio->get_components_query; - is($comp_query_str, "(rcn:\"$biblionumber\" AND (bib-level:a OR bib-level:b))", "$engine: UseControlNumber enabled without MarcOrgCode"); - is($comp_sort, "author_az", "$engine: UseControlNumber enabled without MarcOrgCode sort is correct"); + is( + $comp_query_str, "(rcn:\"$biblionumber\" AND (bib-level:a OR bib-level:b))", + "$engine: UseControlNumber enabled without MarcOrgCode" + ); + is( $comp_sort, "author_az", "$engine: UseControlNumber enabled without MarcOrgCode sort is correct" ); - my $marc_003_field = MARC::Field->new('003', 'OSt'); + my $marc_003_field = MARC::Field->new( '003', 'OSt' ); $record->append_fields($marc_003_field); C4::Biblio::ModBiblio( $record, $biblio->biblionumber ); - $biblio = Koha::Biblios->find( $biblio->biblionumber); + $biblio = Koha::Biblios->find( $biblio->biblionumber ); t::lib::Mocks::mock_preference( 'ComponentSortField', 'title' ); t::lib::Mocks::mock_preference( 'ComponentSortOrder', 'asc' ); ( $comp_query, $comp_query_str, $comp_sort ) = $biblio->get_components_query; - is($comp_query_str, "(((rcn:\"$biblionumber\" AND cni:\"OSt\") OR rcn:\"OSt $biblionumber\") AND (bib-level:a OR bib-level:b))", "$engine: UseControlNumber enabled with MarcOrgCode"); - is($comp_sort, "title_asc", "$engine: UseControlNumber enabled with MarcOrgCode sort if correct"); + is( + $comp_query_str, + "(((rcn:\"$biblionumber\" AND cni:\"OSt\") OR rcn:\"OSt $biblionumber\") AND (bib-level:a OR bib-level:b))", + "$engine: UseControlNumber enabled with MarcOrgCode" + ); + is( $comp_sort, "title_asc", "$engine: UseControlNumber enabled with MarcOrgCode sort if correct" ); $record->delete_field($marc_003_field); } @@ -931,7 +980,6 @@ subtest 'get_volumes_query' => sub { C4::Biblio::ModBiblio( $record, $biblio->biblionumber ); $biblio = Koha::Biblios->find( $biblio->biblionumber ); - is( $biblio->get_volumes_query, "(rcn:$biblionumber NOT (bib-level:a OR bib-level:b))", "UseControlNumber enabled without MarcOrgCode" @@ -1090,7 +1138,7 @@ subtest '->orders, ->uncancelled_orders and ->acq_status tests' => sub { ); # Add a couple orders - foreach (1..2) { + foreach ( 1 .. 2 ) { $builder->build_object( { class => 'Koha::Acquisition::Orders', @@ -1141,13 +1189,13 @@ subtest 'tickets() tests' => sub { $schema->storage->txn_begin; - my $biblio = $builder->build_sample_biblio(); + my $biblio = $builder->build_sample_biblio(); my $tickets = $biblio->tickets; - is( ref($tickets), 'Koha::Tickets', 'Koha::Biblio->tickets should return a Koha::Tickets object' ); + is( ref($tickets), 'Koha::Tickets', 'Koha::Biblio->tickets should return a Koha::Tickets object' ); is( $tickets->count, 0, 'Koha::Biblio->tickets should return a count of 0 when there are no related tickets' ); # Add two tickets - foreach (1..2) { + foreach ( 1 .. 2 ) { $builder->build_object( { class => 'Koha::Tickets', @@ -1157,8 +1205,8 @@ subtest 'tickets() tests' => sub { } $tickets = $biblio->tickets; - is( ref($tickets), 'Koha::Tickets', 'Koha::Biblio->tickets should return a Koha::Tickets object' ); - is( $tickets->count, 2, 'Koha::Biblio->tickets should return the correct number of tickets' ); + is( ref($tickets), 'Koha::Tickets', 'Koha::Biblio->tickets should return a Koha::Tickets object' ); + is( $tickets->count, 2, 'Koha::Biblio->tickets should return the correct number of tickets' ); $schema->storage->txn_rollback; }; @@ -1207,13 +1255,14 @@ subtest 'subscriptions() tests' => sub { my $biblio = $builder->build_sample_biblio; my $subscriptions = $biblio->subscriptions; - is( ref($subscriptions), 'Koha::Subscriptions', + is( + ref($subscriptions), 'Koha::Subscriptions', 'Koha::Biblio->subscriptions should return a Koha::Subscriptions object' ); - is( $subscriptions->count, 0, 'Koha::Biblio->subscriptions should return the correct number of subscriptions'); + is( $subscriptions->count, 0, 'Koha::Biblio->subscriptions should return the correct number of subscriptions' ); # Add two subscriptions - foreach (1..2) { + foreach ( 1 .. 2 ) { $builder->build_object( { class => 'Koha::Subscriptions', @@ -1223,10 +1272,11 @@ subtest 'subscriptions() tests' => sub { } $subscriptions = $biblio->subscriptions; - is( ref($subscriptions), 'Koha::Subscriptions', + is( + ref($subscriptions), 'Koha::Subscriptions', 'Koha::Biblio->subscriptions should return a Koha::Subscriptions object' ); - is( $subscriptions->count, 2, 'Koha::Biblio->subscriptions should return the correct number of subscriptions'); + is( $subscriptions->count, 2, 'Koha::Biblio->subscriptions should return the correct number of subscriptions' ); $schema->storage->txn_rollback; }; @@ -1284,20 +1334,22 @@ subtest 'get_marc_notes() MARC21 tests' => sub { my $biblio = $builder->build_sample_biblio; my $record = $biblio->metadata->record; $record->append_fields( - MARC::Field->new( '500', '', '', a => 'Note1' ), - MARC::Field->new( '505', '', '', a => 'Note2', u => 'http://someserver.com' ), - MARC::Field->new( '520', '', '', a => 'Note3 skipped' ), + MARC::Field->new( '500', '', '', a => 'Note1' ), + MARC::Field->new( '505', '', '', a => 'Note2', u => 'http://someserver.com' ), + MARC::Field->new( '520', '', '', a => 'Note3 skipped' ), MARC::Field->new( '541', '0', '', a => 'Note4 skipped on opac' ), - MARC::Field->new( '544', '', '', a => 'Note5' ), - MARC::Field->new( '590', '', '', a => $av->authorised_value ), - MARC::Field->new( '545', '', '', a => 'Invisible on OPAC' ), + MARC::Field->new( '544', '', '', a => 'Note5' ), + MARC::Field->new( '590', '', '', a => $av->authorised_value ), + MARC::Field->new( '545', '', '', a => 'Invisible on OPAC' ), ); - my $mss = Koha::MarcSubfieldStructures->find({tagfield => "590", tagsubfield => "a", frameworkcode => $biblio->frameworkcode }); - $mss->update({ authorised_value => $av->category }); + my $mss = Koha::MarcSubfieldStructures->find( + { tagfield => "590", tagsubfield => "a", frameworkcode => $biblio->frameworkcode } ); + $mss->update( { authorised_value => $av->category } ); - $mss = Koha::MarcSubfieldStructures->find({tagfield => "545", tagsubfield => "a", frameworkcode => $biblio->frameworkcode }); - $mss->update({ hidden => 1 }); + $mss = Koha::MarcSubfieldStructures->find( + { tagfield => "545", tagsubfield => "a", frameworkcode => $biblio->frameworkcode } ); + $mss->update( { hidden => 1 } ); my $cache = Koha::Caches->get_instance; $cache->clear_from_cache("MarcStructure-0-"); @@ -1306,23 +1358,29 @@ subtest 'get_marc_notes() MARC21 tests' => sub { $cache->clear_from_cache("MarcCodedFields-"); C4::Biblio::ModBiblio( $record, $biblio->biblionumber ); - $biblio = Koha::Biblios->find( $biblio->biblionumber); + $biblio = Koha::Biblios->find( $biblio->biblionumber ); my $notes = $biblio->get_marc_notes; - is( $notes->[0]->{marcnote}, 'Note1', 'First note' ); - is( $notes->[1]->{marcnote}, 'Note2', 'Second note' ); + is( $notes->[0]->{marcnote}, 'Note1', 'First note' ); + is( $notes->[1]->{marcnote}, 'Note2', 'Second note' ); is( $notes->[2]->{marcnote}, 'http://someserver.com', 'URL separated' ); - is( $notes->[3]->{marcnote}, 'Note4 skipped on opac',"Note shows if not opac (Hidden by Indicator)" ); - is( $notes->[4]->{marcnote}, 'Note5', 'Fifth note' ); - is( $notes->[5]->{marcnote}, $av->lib, 'Authorised value is correctly parsed to show description rather than code' ); + is( $notes->[3]->{marcnote}, 'Note4 skipped on opac', "Note shows if not opac (Hidden by Indicator)" ); + is( $notes->[4]->{marcnote}, 'Note5', 'Fifth note' ); + is( + $notes->[5]->{marcnote}, $av->lib, + 'Authorised value is correctly parsed to show description rather than code' + ); is( $notes->[6]->{marcnote}, 'Invisible on OPAC', 'Note shows if not opac (Hidden by framework)' ); - is( @$notes, 7, 'No more notes' ); - $notes = $biblio->get_marc_notes({ opac => 1 }); - is( $notes->[0]->{marcnote}, 'Note1', 'First note' ); - is( $notes->[1]->{marcnote}, 'Note2', 'Second note' ); + is( @$notes, 7, 'No more notes' ); + $notes = $biblio->get_marc_notes( { opac => 1 } ); + is( $notes->[0]->{marcnote}, 'Note1', 'First note' ); + is( $notes->[1]->{marcnote}, 'Note2', 'Second note' ); is( $notes->[2]->{marcnote}, 'http://someserver.com', 'URL separated' ); - is( $notes->[3]->{marcnote}, 'Note5', 'Fifth note shows after fourth skipped' ); - is( $notes->[4]->{marcnote}, $av->lib_opac, 'Authorised value is correctly parsed for OPAC to show description rather than code' ); + is( $notes->[3]->{marcnote}, 'Note5', 'Fifth note shows after fourth skipped' ); + is( + $notes->[4]->{marcnote}, $av->lib_opac, + 'Authorised value is correctly parsed for OPAC to show description rather than code' + ); is( @$notes, 5, 'No more notes' ); $cache->clear_from_cache("MarcStructure-0-"); @@ -1349,11 +1407,11 @@ subtest 'get_marc_notes() UNIMARC tests' => sub { MARC::Field->new( '310', '', '', a => 'Note3 skipped' ), ); C4::Biblio::ModBiblio( $record, $biblio->biblionumber ); - $biblio = Koha::Biblios->find( $biblio->biblionumber); - my $notes = $biblio->get_marc_notes({ marcflavour => 'UNIMARC' }); + $biblio = Koha::Biblios->find( $biblio->biblionumber ); + my $notes = $biblio->get_marc_notes( { marcflavour => 'UNIMARC' } ); is( $notes->[0]->{marcnote}, 'Note1', 'First note' ); is( $notes->[1]->{marcnote}, 'Note2', 'Second note' ); - is( @$notes, 2, 'No more notes' ); + is( @$notes, 2, 'No more notes' ); t::lib::Mocks::mock_preference( 'marcflavour', 'MARC21' ); $schema->storage->txn_rollback; @@ -1371,8 +1429,7 @@ subtest 'host_items() tests' => sub { is( ref($host_items), 'Koha::Items' ); is( $host_items->count, 0 ); - my $item_1 = - $builder->build_sample_item( { biblionumber => $biblio->biblionumber } ); + my $item_1 = $builder->build_sample_item( { biblionumber => $biblio->biblionumber } ); my $host_item_1 = $builder->build_sample_item; my $host_item_2 = $builder->build_sample_item; @@ -1385,11 +1442,13 @@ subtest 'host_items() tests' => sub { ), ); C4::Biblio::ModBiblio( $record, $biblio->biblionumber ); - $biblio = $biblio->get_from_storage; + $biblio = $biblio->get_from_storage; $host_items = $biblio->host_items; is( $host_items->count, 2 ); - is_deeply( [ $host_items->get_column('itemnumber') ], - [ $host_item_1->itemnumber, $host_item_2->itemnumber ] ); + is_deeply( + [ $host_items->get_column('itemnumber') ], + [ $host_item_1->itemnumber, $host_item_2->itemnumber ] + ); my $transfer = $builder->build_object( { @@ -1423,13 +1482,15 @@ subtest 'host_items() tests' => sub { t::lib::Mocks::mock_preference( 'EasyAnalyticalRecords', 1 ); my $items = $biblio->items; - is( $items->count, 1, "Without host_items param we only get the items on the biblio"); + is( $items->count, 1, "Without host_items param we only get the items on the biblio" ); - $items = $biblio->items({ host_items => 1 }); - is( $items->count, 3, "With param host_items we get the biblio items plus analytics"); - is( ref($items), 'Koha::Items', "We correctly get an Items object"); - is_deeply( [ $items->get_column('itemnumber') ], - [ $item_1->itemnumber, $host_item_1->itemnumber, $host_item_2->itemnumber ] ); + $items = $biblio->items( { host_items => 1 } ); + is( $items->count, 3, "With param host_items we get the biblio items plus analytics" ); + is( ref($items), 'Koha::Items', "We correctly get an Items object" ); + is_deeply( + [ $items->get_column('itemnumber') ], + [ $item_1->itemnumber, $host_item_1->itemnumber, $host_item_2->itemnumber ] + ); t::lib::Mocks::mock_preference( 'EasyAnalyticalRecords', 0 ); @@ -1453,8 +1514,10 @@ subtest 'article_requests() tests' => sub { my $biblio = $item->biblio; my $article_requests = $biblio->article_requests; - is( ref($article_requests), 'Koha::ArticleRequests', - 'In scalar context, type is correct' ); + is( + ref($article_requests), 'Koha::ArticleRequests', + 'In scalar context, type is correct' + ); is( $article_requests->count, 0, 'No article requests' ); foreach my $i ( 0 .. 3 ) { @@ -1483,15 +1546,15 @@ subtest 'current_checkouts() and old_checkouts() tests' => sub { $schema->storage->txn_begin; - my $library = $builder->build_object({ class => 'Koha::Libraries' }); + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); - my $patron_1 = $builder->build_object({ class => 'Koha::Patrons' }); - my $patron_2 = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron_1 = $builder->build_object( { class => 'Koha::Patrons' } ); + my $patron_2 = $builder->build_object( { class => 'Koha::Patrons' } ); my $item_1 = $builder->build_sample_item; - my $item_2 = $builder->build_sample_item({ biblionumber => $item_1->biblionumber }); + my $item_2 = $builder->build_sample_item( { biblionumber => $item_1->biblionumber } ); - t::lib::Mocks::mock_userenv({ branchcode => $library->id }); + t::lib::Mocks::mock_userenv( { branchcode => $library->id } ); AddIssue( $patron_1, $item_1->barcode ); AddIssue( $patron_1, $item_2->barcode ); @@ -1499,15 +1562,15 @@ subtest 'current_checkouts() and old_checkouts() tests' => sub { AddReturn( $item_1->barcode ); AddIssue( $patron_2, $item_1->barcode ); - my $biblio = $item_1->biblio; + my $biblio = $item_1->biblio; my $current_checkouts = $biblio->current_checkouts; - my $old_checkouts = $biblio->old_checkouts; + my $old_checkouts = $biblio->old_checkouts; - is( ref($current_checkouts), 'Koha::Checkouts', 'Type is correct' ); - is( ref($old_checkouts), 'Koha::Old::Checkouts', 'Type is correct' ); + is( ref($current_checkouts), 'Koha::Checkouts', 'Type is correct' ); + is( ref($old_checkouts), 'Koha::Old::Checkouts', 'Type is correct' ); is( $current_checkouts->count, 2, 'Count is correct for current checkouts' ); - is( $old_checkouts->count, 1, 'Count is correct for old checkouts' ); + is( $old_checkouts->count, 1, 'Count is correct for old checkouts' ); $schema->storage->txn_rollback; }; @@ -1518,21 +1581,21 @@ subtest 'get_marc_contributors() tests' => sub { $schema->storage->txn_begin; - my $biblio = $builder->build_sample_biblio({ author => 'Main author' }); + my $biblio = $builder->build_sample_biblio( { author => 'Main author' } ); my $record = $biblio->metadata->record; # add author information - my $field = MARC::Field->new('700','1','','a' => 'Jefferson, Thomas'); + my $field = MARC::Field->new( '700', '1', '', 'a' => 'Jefferson, Thomas' ); $record->append_fields($field); - $field = MARC::Field->new('701','1','','d' => 'Secondary author 2'); + $field = MARC::Field->new( '701', '1', '', 'd' => 'Secondary author 2' ); $record->append_fields($field); # get record C4::Biblio::ModBiblio( $record, $biblio->biblionumber ); $biblio = Koha::Biblios->find( $biblio->biblionumber ); - is( @{$biblio->get_marc_authors}, 3, 'get_marc_authors retrieves correct number of author subfields' ); - is( @{$biblio->get_marc_contributors}, 2, 'get_marc_contributors retrieves correct number of author subfields' ); + is( @{ $biblio->get_marc_authors }, 3, 'get_marc_authors retrieves correct number of author subfields' ); + is( @{ $biblio->get_marc_contributors }, 2, 'get_marc_contributors retrieves correct number of author subfields' ); $schema->storage->txn_rollback; }; @@ -1542,17 +1605,26 @@ subtest 'Recalls tests' => sub { $schema->storage->txn_begin; - my $item1 = $builder->build_sample_item; - my $biblio = $item1->biblio; + my $item1 = $builder->build_sample_item; + my $biblio = $item1->biblio; my $branchcode = $item1->holdingbranch; - my $patron1 = $builder->build_object({ class => 'Koha::Patrons', value => { branchcode => $branchcode } }); - my $patron2 = $builder->build_object({ class => 'Koha::Patrons', value => { branchcode => $branchcode } }); - my $patron3 = $builder->build_object({ class => 'Koha::Patrons', value => { branchcode => $branchcode } }); - my $item2 = $builder->build_object({ class => 'Koha::Items', value => { holdingbranch => $branchcode, homebranch => $branchcode, biblionumber => $biblio->biblionumber, itype => $item1->effective_itemtype } }); - t::lib::Mocks::mock_userenv({ patron => $patron1 }); + my $patron1 = $builder->build_object( { class => 'Koha::Patrons', value => { branchcode => $branchcode } } ); + my $patron2 = $builder->build_object( { class => 'Koha::Patrons', value => { branchcode => $branchcode } } ); + my $patron3 = $builder->build_object( { class => 'Koha::Patrons', value => { branchcode => $branchcode } } ); + my $item2 = $builder->build_object( + { + class => 'Koha::Items', + value => { + holdingbranch => $branchcode, homebranch => $branchcode, biblionumber => $biblio->biblionumber, + itype => $item1->effective_itemtype + } + } + ); + t::lib::Mocks::mock_userenv( { patron => $patron1 } ); my $recall1 = Koha::Recall->new( - { patron_id => $patron1->borrowernumber, + { + patron_id => $patron1->borrowernumber, created_date => \'NOW()', biblio_id => $biblio->biblionumber, pickup_library_id => $branchcode, @@ -1562,7 +1634,8 @@ subtest 'Recalls tests' => sub { } )->store; my $recall2 = Koha::Recall->new( - { patron_id => $patron2->borrowernumber, + { + patron_id => $patron2->borrowernumber, created_date => \'NOW()', biblio_id => $biblio->biblionumber, pickup_library_id => $branchcode, @@ -1572,7 +1645,8 @@ subtest 'Recalls tests' => sub { } )->store; my $recall3 = Koha::Recall->new( - { patron_id => $patron3->borrowernumber, + { + patron_id => $patron3->borrowernumber, created_date => \'NOW()', biblio_id => $biblio->biblionumber, pickup_library_id => $branchcode, @@ -1586,70 +1660,88 @@ subtest 'Recalls tests' => sub { is( $recalls->count, 3, 'Correctly get number of recalls for biblio' ); $recall1->set_cancelled; - $recall2->set_expired({ interface => 'COMMANDLINE' }); + $recall2->set_expired( { interface => 'COMMANDLINE' } ); - is( $recalls->count, 3, 'Correctly get number of recalls for biblio' ); + is( $recalls->count, 3, 'Correctly get number of recalls for biblio' ); is( $recalls->filter_by_current->count, 1, 'Correctly get number of active recalls for biblio' ); - t::lib::Mocks::mock_preference('UseRecalls', 0); - is( $biblio->can_be_recalled({ patron => $patron1 }), 0, "Can't recall with UseRecalls disabled" ); + t::lib::Mocks::mock_preference( 'UseRecalls', 0 ); + is( $biblio->can_be_recalled( { patron => $patron1 } ), 0, "Can't recall with UseRecalls disabled" ); - t::lib::Mocks::mock_preference("UseRecalls", 1); - $item1->update({ notforloan => 1 }); - is( $biblio->can_be_recalled({ patron => $patron1 }), 0, "Can't recall with no available items" ); + t::lib::Mocks::mock_preference( "UseRecalls", 1 ); + $item1->update( { notforloan => 1 } ); + is( $biblio->can_be_recalled( { patron => $patron1 } ), 0, "Can't recall with no available items" ); - $item1->update({ notforloan => 0 }); - Koha::CirculationRules->set_rules({ - branchcode => $branchcode, - categorycode => $patron1->categorycode, - itemtype => $item1->effective_itemtype, - rules => { - recalls_allowed => 0, - recalls_per_record => 1, - on_shelf_recalls => 'all', - }, - }); - is( $biblio->can_be_recalled({ patron => $patron1 }), 0, "Can't recall if recalls_allowed = 0" ); + $item1->update( { notforloan => 0 } ); + Koha::CirculationRules->set_rules( + { + branchcode => $branchcode, + categorycode => $patron1->categorycode, + itemtype => $item1->effective_itemtype, + rules => { + recalls_allowed => 0, + recalls_per_record => 1, + on_shelf_recalls => 'all', + }, + } + ); + is( $biblio->can_be_recalled( { patron => $patron1 } ), 0, "Can't recall if recalls_allowed = 0" ); - Koha::CirculationRules->set_rules({ - branchcode => $branchcode, - categorycode => $patron1->categorycode, - itemtype => $item1->effective_itemtype, - rules => { - recalls_allowed => 1, - recalls_per_record => 1, - on_shelf_recalls => 'all', - }, - }); - is( $biblio->can_be_recalled({ patron => $patron1 }), 0, "Can't recall if patron has more existing recall(s) than recalls_allowed" ); - is( $biblio->can_be_recalled({ patron => $patron1 }), 0, "Can't recall if patron has more existing recall(s) than recalls_per_record" ); + Koha::CirculationRules->set_rules( + { + branchcode => $branchcode, + categorycode => $patron1->categorycode, + itemtype => $item1->effective_itemtype, + rules => { + recalls_allowed => 1, + recalls_per_record => 1, + on_shelf_recalls => 'all', + }, + } + ); + is( + $biblio->can_be_recalled( { patron => $patron1 } ), 0, + "Can't recall if patron has more existing recall(s) than recalls_allowed" + ); + is( + $biblio->can_be_recalled( { patron => $patron1 } ), 0, + "Can't recall if patron has more existing recall(s) than recalls_per_record" + ); $recall1->set_cancelled; C4::Circulation::AddIssue( $patron1, $item2->barcode ); - is( $biblio->can_be_recalled({ patron => $patron1 }), 0, "Can't recall if patron has already checked out an item attached to this biblio" ); + is( + $biblio->can_be_recalled( { patron => $patron1 } ), 0, + "Can't recall if patron has already checked out an item attached to this biblio" + ); - is( $biblio->can_be_recalled({ patron => $patron1 }), 0, "Can't recall if on_shelf_recalls = all and items are still available" ); + is( + $biblio->can_be_recalled( { patron => $patron1 } ), 0, + "Can't recall if on_shelf_recalls = all and items are still available" + ); - Koha::CirculationRules->set_rules({ - branchcode => $branchcode, - categorycode => $patron1->categorycode, - itemtype => $item1->effective_itemtype, - rules => { - recalls_allowed => 1, - recalls_per_record => 1, - on_shelf_recalls => 'any', - }, - }); + Koha::CirculationRules->set_rules( + { + branchcode => $branchcode, + categorycode => $patron1->categorycode, + itemtype => $item1->effective_itemtype, + rules => { + recalls_allowed => 1, + recalls_per_record => 1, + on_shelf_recalls => 'any', + }, + } + ); C4::Circulation::AddReturn( $item2->barcode, $branchcode ); - is( $biblio->can_be_recalled({ patron => $patron1 }), 0, "Can't recall if no items are checked out" ); + is( $biblio->can_be_recalled( { patron => $patron1 } ), 0, "Can't recall if no items are checked out" ); $recall2->set_cancelled; C4::Circulation::AddIssue( $patron2, $item2->barcode ); C4::Circulation::AddIssue( $patron2, $item1->barcode ); - is( $biblio->can_be_recalled({ patron => $patron1 }), 2, "Can recall two items" ); + is( $biblio->can_be_recalled( { patron => $patron1 } ), 2, "Can recall two items" ); - $item1->update({ withdrawn => 1 }); - is( $biblio->can_be_recalled({ patron => $patron1 }), 1, "Can recall one item" ); + $item1->update( { withdrawn => 1 } ); + is( $biblio->can_be_recalled( { patron => $patron1 } ), 1, "Can recall one item" ); $schema->storage->txn_rollback; }; @@ -1666,7 +1758,7 @@ subtest 'ill_requests() tests' => sub { is( ref($rs), 'Koha::ILL::Requests' ); is( $rs->count, 0, 'No linked requests' ); - foreach ( 1..10 ) { + foreach ( 1 .. 10 ) { $builder->build_object( { class => 'Koha::ILL::Requests', @@ -1689,20 +1781,20 @@ subtest 'item_groups() tests' => sub { my $biblio = $builder->build_sample_biblio(); my @item_groups = $biblio->item_groups->as_list; - is( scalar(@item_groups), 0, 'Got zero item groups'); + is( scalar(@item_groups), 0, 'Got zero item groups' ); my $item_group_1 = Koha::Biblio::ItemGroup->new( { biblio_id => $biblio->id } )->store(); @item_groups = $biblio->item_groups->as_list; - is( scalar(@item_groups), 1, 'Got one item group'); - is( $item_groups[0]->id, $item_group_1->id, 'Got correct item group'); + is( scalar(@item_groups), 1, 'Got one item group' ); + is( $item_groups[0]->id, $item_group_1->id, 'Got correct item group' ); my $item_group_2 = Koha::Biblio::ItemGroup->new( { biblio_id => $biblio->id } )->store(); @item_groups = $biblio->item_groups->as_list; - is( scalar(@item_groups), 2, 'Got two item groups'); - is( $item_groups[0]->id, $item_group_1->id, 'Got correct item group 1'); - is( $item_groups[1]->id, $item_group_2->id, 'Got correct item group 2'); + is( scalar(@item_groups), 2, 'Got two item groups' ); + is( $item_groups[0]->id, $item_group_1->id, 'Got correct item group 1' ); + is( $item_groups[1]->id, $item_group_2->id, 'Got correct item group 2' ); $schema->storage->txn_rollback; }; @@ -1760,6 +1852,7 @@ subtest 'normalized_oclc() tests' => sub { subtest 'ratings' => sub { plan tests => 1; + # See t/db_dependent/Koha/Ratings.t ok(1); }; @@ -1880,6 +1973,7 @@ sub component_record1 { ); return $marc; } + sub search_component_record1 { my @results = ( component_record1()->as_xml() ); return ( undef, { biblioserver => { RECORDS => \@results, hits => 1 } }, 1 ); diff --git a/t/db_dependent/Koha/Biblio/ItemGroups.t b/t/db_dependent/Koha/Biblio/ItemGroups.t index f0d8accf14..13e2558baf 100755 --- a/t/db_dependent/Koha/Biblio/ItemGroups.t +++ b/t/db_dependent/Koha/Biblio/ItemGroups.t @@ -32,7 +32,7 @@ BEGIN { my $schema = Koha::Database->new->schema; my $builder = t::lib::TestBuilder->new; -t::lib::Mocks::mock_preference('EnableItemGroups', 1); +t::lib::Mocks::mock_preference( 'EnableItemGroups', 1 ); subtest 'add_item() and items() tests' => sub { @@ -41,18 +41,18 @@ subtest 'add_item() and items() tests' => sub { $schema->storage->txn_begin; my $biblio = $builder->build_sample_biblio(); - my $item_1 = $builder->build_sample_item({ biblionumber => $biblio->biblionumber }); - my $item_2 = $builder->build_sample_item({ biblionumber => $biblio->biblionumber }); + my $item_1 = $builder->build_sample_item( { biblionumber => $biblio->biblionumber } ); + my $item_2 = $builder->build_sample_item( { biblionumber => $biblio->biblionumber } ); my $item_group = Koha::Biblio::ItemGroup->new( { biblio_id => $biblio->id } )->store(); my $items = $item_group->items; - is( $items->count, 0, 'Item group has no items'); + is( $items->count, 0, 'Item group has no items' ); - $item_group->add_item({ item_id => $item_1->id }); + $item_group->add_item( { item_id => $item_1->id } ); my @items = $item_group->items->as_list(); - is( scalar(@items), 1, 'Item group has one item'); - is( $items[0]->id, $item_1->id, 'Item 1 is correct' ); + is( scalar(@items), 1, 'Item group has one item' ); + is( $items[0]->id, $item_1->id, 'Item 1 is correct' ); is( ref( $items[0]->item_group ), 'Koha::Biblio::ItemGroup', '->item_group should return a Koha::Biblio::ItemGroup object' @@ -62,22 +62,22 @@ subtest 'add_item() and items() tests' => sub { '->item_group should return the correct item group' ); - $item_group->add_item({ item_id => $item_2->id }); + $item_group->add_item( { item_id => $item_2->id } ); @items = $item_group->items->as_list(); - is( scalar(@items), 2, 'Item group has two items'); - is( $items[0]->id, $item_1->id, 'Item 1 is correct' ); - is( $items[1]->id, $item_2->id, 'Item 2 is correct' ); + is( scalar(@items), 2, 'Item group has two items' ); + is( $items[0]->id, $item_1->id, 'Item 1 is correct' ); + is( $items[1]->id, $item_2->id, 'Item 2 is correct' ); # Remove an item $item_1->delete; @items = $item_group->items->as_list(); - is( scalar(@items), 1, 'Item group now has only one item'); - is( $items[0]->id, $item_2->id, 'Item 2 is correct' ); + is( scalar(@items), 1, 'Item group now has only one item' ); + is( $items[0]->id, $item_2->id, 'Item 2 is correct' ); # Remove last item $item_2->delete; @items = $item_group->items->as_list(); - is( scalar(@items), 0, "Item group now has no items"); + is( scalar(@items), 0, "Item group now has no items" ); $item_group = Koha::Biblio::ItemGroups->find( $item_group->id ); is( $item_group, undef, 'ItemGroup is deleted when last item is deleted' ); diff --git a/t/db_dependent/Koha/Biblio/Metadata.t b/t/db_dependent/Koha/Biblio/Metadata.t index 67a09b40ce..0947b0c846 100755 --- a/t/db_dependent/Koha/Biblio/Metadata.t +++ b/t/db_dependent/Koha/Biblio/Metadata.t @@ -74,19 +74,23 @@ subtest 'record() tests' => sub { is( scalar @fields_952, 0, 'Item fields stripped out then calling $metadata->record' ); is( ref $record2, 'MARC::Record', 'Method record() returned a MARC::Record object' ); - is( $record2->field('245')->subfield("a"), - $title, 'Title in 245$a matches title from original record object' ); + is( + $record2->field('245')->subfield("a"), + $title, 'Title in 245$a matches title from original record object' + ); my $bad_data = $builder->build_object( - { class => 'Koha::Biblio::Metadatas', + { + class => 'Koha::Biblio::Metadatas', value => { format => 'marcxml', schema => 'MARC21', metadata => 'this_is_not_marcxml' } } ); - warning_like - { throws_ok { $bad_data->record; } - 'Koha::Exceptions::Metadata::Invalid', 'Exception thrown on bad record'; } - qr/parser error : Start tag expected, '<' not found/, + warning_like { + throws_ok { $bad_data->record; } + 'Koha::Exceptions::Metadata::Invalid', 'Exception thrown on bad record'; + } + qr/parser error : Start tag expected, '<' not found/, 'Warning thrown excplicitly'; my $exception = $@; @@ -95,7 +99,8 @@ subtest 'record() tests' => sub { is( $exception->schema, 'MARC21', 'schema passed correctly to exception' ); my $bad_format = $builder->build_object( - { class => 'Koha::Biblio::Metadatas', + { + class => 'Koha::Biblio::Metadatas', value => { format => 'mij', schema => 'MARC21', metadata => 'something' } } ); @@ -103,7 +108,8 @@ subtest 'record() tests' => sub { throws_ok { $bad_format->record; } 'Koha::Exceptions::Metadata', 'Exception thrown on unhandled format'; - is( "$@", + is( + "$@", 'Koha::Biblio::Metadata->record called on unhandled format: mij', 'Exception message built correctly' ); @@ -171,18 +177,24 @@ subtest '_embed_items' => sub { $schema->storage->txn_begin(); - my $builder = t::lib::TestBuilder->new; - my $library1 = $builder->build({ - source => 'Branch', - }); - my $library2 = $builder->build({ - source => 'Branch', - }); - my $itemtype = $builder->build({ - source => 'Itemtype', - }); + my $builder = t::lib::TestBuilder->new; + my $library1 = $builder->build( + { + source => 'Branch', + } + ); + my $library2 = $builder->build( + { + source => 'Branch', + } + ); + my $itemtype = $builder->build( + { + source => 'Itemtype', + } + ); - my $biblio = $builder->build_sample_biblio(); + my $biblio = $builder->build_sample_biblio(); my $item_infos = [ { homebranch => $library1->{branchcode}, holdingbranch => $library1->{branchcode} }, { homebranch => $library1->{branchcode}, holdingbranch => $library1->{branchcode} }, @@ -195,7 +207,7 @@ subtest '_embed_items' => sub { ]; my $number_of_items = scalar @$item_infos; my $number_of_items_with_homebranch_is_CPL = - grep { $_->{homebranch} eq $library1->{branchcode} } @$item_infos; + grep { $_->{homebranch} eq $library1->{branchcode} } @$item_infos; my @itemnumbers; for my $item_info (@$item_infos) { @@ -216,10 +228,9 @@ subtest '_embed_items' => sub { throws_ok { Koha::Biblio::Metadata->record() } 'Koha::Exceptions::Metadata', -'Koha::Biblio::Metadata->record must be called on an instantiated object or like a class method with a record passed in parameter'; + 'Koha::Biblio::Metadata->record must be called on an instantiated object or like a class method with a record passed in parameter'; - my ($itemfield) = - C4::Biblio::GetMarcFromKohaField( 'items.itemnumber' ); + my ($itemfield) = C4::Biblio::GetMarcFromKohaField('items.itemnumber'); my $record = $biblio->metadata->record; Koha::Biblio::Metadata->record( { @@ -231,44 +242,46 @@ subtest '_embed_items' => sub { my @items = $record->field($itemfield); is( scalar @items, $number_of_items, 'Should return all items' ); - my $marc_with_items = $biblio->metadata->record({ embed_items => 1 }); - is_deeply( $record, $marc_with_items, 'A direct call to GetMarcBiblio with items matches'); + my $marc_with_items = $biblio->metadata->record( { embed_items => 1 } ); + is_deeply( $record, $marc_with_items, 'A direct call to GetMarcBiblio with items matches' ); - $record = $biblio->metadata->record({ embed_items => 1, itemnumbers => [ $itemnumbers[1], $itemnumbers[3] ] }); - @items = $record->field($itemfield); + $record = $biblio->metadata->record( { embed_items => 1, itemnumbers => [ $itemnumbers[1], $itemnumbers[3] ] } ); + @items = $record->field($itemfield); is( scalar @items, 2, 'Should return all items present in the list' ); - $record = $biblio->metadata->record({ embed_items => 1, opac => 1 }); - @items = $record->field($itemfield); + $record = $biblio->metadata->record( { embed_items => 1, opac => 1 } ); + @items = $record->field($itemfield); is( scalar @items, $number_of_items, 'Should return all items for opac' ); my $opachiddenitems = " homebranch: ['$library1->{branchcode}']"; t::lib::Mocks::mock_preference( 'OpacHiddenItems', $opachiddenitems ); - $record = $biblio->metadata->record({ embed_items => 1 }); - @items = $record->field($itemfield); - is( scalar @items, + $record = $biblio->metadata->record( { embed_items => 1 } ); + @items = $record->field($itemfield); + is( + scalar @items, $number_of_items, - 'Even with OpacHiddenItems set, all items should have been embedded' ); + 'Even with OpacHiddenItems set, all items should have been embedded' + ); - $record = $biblio->metadata->record({ embed_items => 1, opac => 1 }); - @items = $record->field($itemfield); + $record = $biblio->metadata->record( { embed_items => 1, opac => 1 } ); + @items = $record->field($itemfield); is( scalar @items, $number_of_items - $number_of_items_with_homebranch_is_CPL, -'For OPAC, the pref OpacHiddenItems should have been take into account. Only items with homebranch ne CPL should have been embedded' + 'For OPAC, the pref OpacHiddenItems should have been take into account. Only items with homebranch ne CPL should have been embedded' ); $opachiddenitems = " homebranch: ['$library1->{branchcode}', '$library2->{branchcode}']"; t::lib::Mocks::mock_preference( 'OpacHiddenItems', $opachiddenitems ); - $record = $biblio->metadata->record({ embed_items => 1, opac => 1 }); - @items = $record->field($itemfield); + $record = $biblio->metadata->record( { embed_items => 1, opac => 1 } ); + @items = $record->field($itemfield); is( scalar @items, 0, -'For OPAC, If all items are hidden, no item should have been embedded' + 'For OPAC, If all items are hidden, no item should have been embedded' ); # Check position of 952 in response of embed_items marc @@ -282,7 +295,7 @@ subtest '_embed_items' => sub { my $field_list = join ',', map { $_->tag } $record->fields; ok( $field_list =~ /951,953/, "951 and 953 in $field_list" ); $biblio->discard_changes; - $record = $biblio->metadata->record({ embed_items => 1 }); + $record = $biblio->metadata->record( { embed_items => 1 } ); $field_list = join ',', map { $_->tag } $record->fields; ok( $field_list =~ /951,(952,)+953/, "951-952s-953 in $field_list" ); diff --git a/t/db_dependent/Koha/Biblio/host_record.t b/t/db_dependent/Koha/Biblio/host_record.t index c5c5827ad1..577f551404 100755 --- a/t/db_dependent/Koha/Biblio/host_record.t +++ b/t/db_dependent/Koha/Biblio/host_record.t @@ -30,7 +30,6 @@ use Koha::Database; use Koha::Biblios; use C4::Biblio; - my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; our $builder = t::lib::TestBuilder->new; @@ -41,21 +40,21 @@ subtest 'get_marc_host' => sub { t::lib::Mocks::mock_preference( 'marcflavour', 'MARC21' ); t::lib::Mocks::mock_preference( 'MARCOrgCode', 'xyz' ); - my $bib1 = $builder->build_object({ class => 'Koha::Biblios' }); - my $bib2 = $builder->build_object({ class => 'Koha::Biblios' }); - my $item1 = $builder->build_object({ class => 'Koha::Items', value => { biblionumber => $bib2->biblionumber } }); - my $marc = MARC::Record->new; + my $bib1 = $builder->build_object( { class => 'Koha::Biblios' } ); + my $bib2 = $builder->build_object( { class => 'Koha::Biblios' } ); + my $item1 = $builder->build_object( { class => 'Koha::Items', value => { biblionumber => $bib2->biblionumber } } ); + my $marc = MARC::Record->new; my $results = []; # Lets mock! Simulate search engine response and biblio metadata call. my $metadata = Test::MockObject->new; $metadata->mock( 'record', sub { return $marc; } ); - my $meta_mod = Test::MockModule->new( 'Koha::Biblio' ); + my $meta_mod = Test::MockModule->new('Koha::Biblio'); $meta_mod->mock( 'metadata', sub { return $metadata; } ); my $engine = Test::MockObject->new; $engine->mock( 'simple_search_compat', sub { return ( undef, $results, scalar @$results ); } ); $engine->mock( 'extract_biblionumber', sub { return $results->[0]; } ); - my $search_mod = Test::MockModule->new( 'Koha::SearchEngine::Search' ); + my $search_mod = Test::MockModule->new('Koha::SearchEngine::Search'); $search_mod->mock( 'new', sub { return $engine; } ); # Case 1: Search engine does not return any results on controlnumber @@ -66,15 +65,16 @@ subtest 'get_marc_host' => sub { is( $bib1->get_marc_host, undef, '773 looks fine, but no search results' ); # Case 2: Search engine returns (at maximum) one result - $results = [ $bib1->biblionumber ]; # will be found because 773w is in shape + $results = [ $bib1->biblionumber ]; # will be found because 773w is in shape my $host = $bib1->get_marc_host; - is( ref( $host ), 'Koha::Biblio', 'Correct object returned' ); + is( ref($host), 'Koha::Biblio', 'Correct object returned' ); is( $host->biblionumber, $bib1->biblionumber, 'Check biblionumber' ); - $marc->field('773')->update( w => '(xyz) bad data' ); # causes no results + $marc->field('773')->update( w => '(xyz) bad data' ); # causes no results $host = $bib1->get_marc_host; is( $bib1->get_marc_host, undef, 'No results for bad 773' ); t::lib::Mocks::mock_preference( 'EasyAnalyticalRecords', 1 ); + # no $w $marc->field('773')->update( t => 'title' ); $marc->field('773')->delete_subfield( code => 'w' ); @@ -90,7 +90,7 @@ subtest 'get_marc_host' => sub { $marc->field('773')->delete_subfield( code => '9' ); my ( $relatedparts, $info ); ( $host, $relatedparts, $info ) = $bib1->get_marc_host; - is( $host, undef, 'No Koha Biblio object returned with no $w' ); + is( $host, undef, 'No Koha Biblio object returned with no $w' ); is( $info, "title, relpart", '773$atg returned when no $w' ); my $host_only = $bib1->get_marc_host_only; @@ -98,23 +98,26 @@ subtest 'get_marc_host' => sub { my $relatedparts_only = $bib1->get_marc_relatedparts_only; is_deeply( $relatedparts_only, $relatedparts, "Related parts only retrieved successfully" ); my $hostinfo_only = $bib1->get_marc_hostinfo_only; - is_deeply( $hostinfo_only, $info, "Host info only retrieved successfully"); + is_deeply( $hostinfo_only, $info, "Host info only retrieved successfully" ); - $marc->field('773')->delete_subfield( code => 't' ); # restore + $marc->field('773')->delete_subfield( code => 't' ); # restore # Add second 773 $marc->append_fields( MARC::Field->new( '773', '', '', g => 'relpart2', w => '234' ) ); $host = $bib1->get_marc_host; is( $host->biblionumber, $bib1->biblionumber, 'Result triggered by second 773' ); + # Replace orgcode - ($marc->field('773'))[1]->update( w => '(abc)345' ); + ( $marc->field('773') )[1]->update( w => '(abc)345' ); is( $bib1->get_marc_host, undef, 'No results for two 773s' ); + # Test no_items flag - ($marc->field('773'))[1]->update( w => '234' ); # restore - $host = $bib1->get_marc_host({ no_items => 1 }); + ( $marc->field('773') )[1]->update( w => '234' ); # restore + $host = $bib1->get_marc_host( { no_items => 1 } ); is( $host->biblionumber, $bib1->biblionumber, 'Record found with no_items' ); - $builder->build({ source => 'Item', value => { biblionumber => $bib1->biblionumber } }); - is( $bib1->get_marc_host({ no_items => 1 }), undef, 'Record not found with no_items flag after adding one item' ); + $builder->build( { source => 'Item', value => { biblionumber => $bib1->biblionumber } } ); + is( $bib1->get_marc_host( { no_items => 1 } ), undef, 'Record not found with no_items flag after adding one item' ); + # Test list context my @temp = $bib1->get_marc_host; is( $temp[1], 'relpart2', 'Return $g in list context' ); diff --git a/t/db_dependent/Koha/BiblioFrameworks.t b/t/db_dependent/Koha/BiblioFrameworks.t index d2e31d9149..e92e23db9b 100755 --- a/t/db_dependent/Koha/BiblioFrameworks.t +++ b/t/db_dependent/Koha/BiblioFrameworks.t @@ -26,19 +26,26 @@ my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; my $nb_of_frameworks = Koha::BiblioFrameworks->search->count; -my $new_framework_1 = Koha::BiblioFramework->new({ - frameworkcode => 'mfw1', - frameworktext => 'my_frameworktext_for_fw_1', -})->store; -my $new_framework_2 = Koha::BiblioFramework->new({ - frameworkcode => 'mfw2', - frameworktext => 'my_frameworktext_for_fw_2', -})->store; +my $new_framework_1 = Koha::BiblioFramework->new( + { + frameworkcode => 'mfw1', + frameworktext => 'my_frameworktext_for_fw_1', + } +)->store; +my $new_framework_2 = Koha::BiblioFramework->new( + { + frameworkcode => 'mfw2', + frameworktext => 'my_frameworktext_for_fw_2', + } +)->store; is( Koha::BiblioFrameworks->search->count, $nb_of_frameworks + 2, 'The 2 biblio frameworks should have been added' ); my $retrieved_framework_1 = Koha::BiblioFrameworks->find( $new_framework_1->frameworkcode ); -is( $retrieved_framework_1->frameworktext, $new_framework_1->frameworktext, 'Find a biblio framework by frameworkcode should return the correct framework' ); +is( + $retrieved_framework_1->frameworktext, $new_framework_1->frameworktext, + 'Find a biblio framework by frameworkcode should return the correct framework' +); $retrieved_framework_1->delete; is( Koha::BiblioFrameworks->search->count, $nb_of_frameworks + 1, 'Delete should have deleted the biblio framework' ); diff --git a/t/db_dependent/Koha/Biblios.t b/t/db_dependent/Koha/Biblios.t index fde249ffe5..eb9a12fffb 100755 --- a/t/db_dependent/Koha/Biblios.t +++ b/t/db_dependent/Koha/Biblios.t @@ -28,7 +28,7 @@ use MARC::Field; use Mojo::JSON qw(encode_json); use C4::Items; -use C4::Biblio qw( AddBiblio ModBiblio GetMarcFromKohaField ); +use C4::Biblio qw( AddBiblio ModBiblio GetMarcFromKohaField ); use C4::Reserves qw( AddReserve ); use Koha::DateUtils qw( dt_from_string output_pref ); @@ -41,27 +41,21 @@ use t::lib::Mocks; my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; -my $dbh = C4::Context->dbh; +my $dbh = C4::Context->dbh; my $builder = t::lib::TestBuilder->new; -my $patron = $builder->build( { source => 'Borrower' } ); +my $patron = $builder->build( { source => 'Borrower' } ); $patron = Koha::Patrons->find( $patron->{borrowernumber} ); my $biblio = Koha::Biblio->new()->store(); -my $biblioitem = $schema->resultset('Biblioitem')->new( - { - biblionumber => $biblio->id - } -)->insert(); +my $biblioitem = $schema->resultset('Biblioitem')->new( { biblionumber => $biblio->id } )->insert(); subtest 'store' => sub { plan tests => 1; is( Koha::Biblios->find( $biblio->biblionumber )->datecreated, - output_pref( - { dt => dt_from_string, dateformat => 'iso', dateonly => 1 } - ), + output_pref( { dt => dt_from_string, dateformat => 'iso', dateonly => 1 } ), "datecreated must be set to today if not passed to the constructor" ); }; @@ -76,8 +70,8 @@ subtest 'holds + current_holds' => sub { } ); my $holds = $biblio->holds; - is( ref($holds), 'Koha::Holds', '->holds should return a Koha::Holds object' ); - is( $holds->count, 1, '->holds should only return 1 hold' ); + is( ref($holds), 'Koha::Holds', '->holds should return a Koha::Holds object' ); + is( $holds->count, 1, '->holds should only return 1 hold' ); is( $holds->next->borrowernumber, $patron->borrowernumber, '->holds should return the correct hold' ); $holds->delete; @@ -100,82 +94,106 @@ subtest 'holds + current_holds' => sub { subtest 'waiting_or_in_transit' => sub { plan tests => 4; - my $item = $builder->build_sample_item; - my $reserve = $builder->build({ - source => 'Reserve', - value => { - biblionumber => $item->biblionumber, - found => undef + my $item = $builder->build_sample_item; + my $reserve = $builder->build( + { + source => 'Reserve', + value => { + biblionumber => $item->biblionumber, + found => undef + } } - }); + ); - $reserve = Koha::Holds->find($reserve->{reserve_id}); - $biblio = $item->biblio; + $reserve = Koha::Holds->find( $reserve->{reserve_id} ); + $biblio = $item->biblio; - is($biblio->has_items_waiting_or_intransit, 0, 'Item is neither waiting nor in transit'); + is( $biblio->has_items_waiting_or_intransit, 0, 'Item is neither waiting nor in transit' ); $reserve->found('W')->store; - is($biblio->has_items_waiting_or_intransit, 1, 'Item is waiting'); + is( $biblio->has_items_waiting_or_intransit, 1, 'Item is waiting' ); $reserve->found('T')->store; - is($biblio->has_items_waiting_or_intransit, 1, 'Item is in transit'); + is( $biblio->has_items_waiting_or_intransit, 1, 'Item is in transit' ); - my $transfer = $builder->build({ - source => 'Branchtransfer', - value => { - itemnumber => $item->itemnumber, - datearrived => undef, - datecancelled => undef, + my $transfer = $builder->build( + { + source => 'Branchtransfer', + value => { + itemnumber => $item->itemnumber, + datearrived => undef, + datecancelled => undef, + } } - }); - my $t = Koha::Database->new()->schema()->resultset( 'Branchtransfer' )->find($transfer->{branchtransfer_id}); + ); + my $t = Koha::Database->new()->schema()->resultset('Branchtransfer')->find( $transfer->{branchtransfer_id} ); $reserve->found(undef)->store; - is($biblio->has_items_waiting_or_intransit, 1, 'Item has transfer'); + is( $biblio->has_items_waiting_or_intransit, 1, 'Item has transfer' ); }; subtest 'can_be_transferred' => sub { plan tests => 8; - t::lib::Mocks::mock_preference('UseBranchTransferLimits', 1); - t::lib::Mocks::mock_preference('BranchTransferLimitsType', 'itemtype'); + t::lib::Mocks::mock_preference( 'UseBranchTransferLimits', 1 ); + t::lib::Mocks::mock_preference( 'BranchTransferLimitsType', 'itemtype' ); my $library1 = $builder->build_object( { class => 'Koha::Libraries' } ); my $library2 = $builder->build_object( { class => 'Koha::Libraries' } ); my $library3 = $builder->build_object( { class => 'Koha::Libraries' } ); - my $biblio = $builder->build_sample_biblio({ itemtype => 'ONLY1' }); - my $item = $builder->build_sample_item( + my $biblio = $builder->build_sample_biblio( { itemtype => 'ONLY1' } ); + my $item = $builder->build_sample_item( { biblionumber => $biblio->biblionumber, library => $library1->branchcode } ); - is(Koha::Item::Transfer::Limits->search({ - fromBranch => $library1->branchcode, - toBranch => $library2->branchcode, - })->count, 0, 'There are no transfer limits between libraries.'); - ok($biblio->can_be_transferred({ to => $library2 }), - 'Some items of this biblio can be transferred between libraries.'); + is( + Koha::Item::Transfer::Limits->search( + { + fromBranch => $library1->branchcode, + toBranch => $library2->branchcode, + } + )->count, + 0, + 'There are no transfer limits between libraries.' + ); + ok( + $biblio->can_be_transferred( { to => $library2 } ), + 'Some items of this biblio can be transferred between libraries.' + ); - my $limit = Koha::Item::Transfer::Limit->new({ - fromBranch => $library1->branchcode, - toBranch => $library2->branchcode, - itemtype => $item->effective_itemtype, - })->store; - is(Koha::Item::Transfer::Limits->search({ - fromBranch => $library1->branchcode, - toBranch => $library2->branchcode, - })->count, 1, 'Given we have added a transfer limit that applies for all ' - .'of this biblio\s items,'); - is($biblio->can_be_transferred({ to => $library2 }), 0, - 'None of the items of biblio can no longer be transferred between ' - .'libraries.'); - is($biblio->can_be_transferred({ to => $library2, from => $library1 }), 0, - 'We get the same result also if we pass the from-library parameter.'); - $item->holdingbranch($library2->branchcode)->store; - is($biblio->can_be_transferred({ to => $library2 }), 1, 'Given one of the ' - .'items is already located at to-library, then the transfer is possible.'); - $item->holdingbranch($library1->branchcode)->store; + my $limit = Koha::Item::Transfer::Limit->new( + { + fromBranch => $library1->branchcode, + toBranch => $library2->branchcode, + itemtype => $item->effective_itemtype, + } + )->store; + is( + Koha::Item::Transfer::Limits->search( + { + fromBranch => $library1->branchcode, + toBranch => $library2->branchcode, + } + )->count, + 1, + 'Given we have added a transfer limit that applies for all ' . 'of this biblio\s items,' + ); + is( + $biblio->can_be_transferred( { to => $library2 } ), 0, + 'None of the items of biblio can no longer be transferred between ' . 'libraries.' + ); + is( + $biblio->can_be_transferred( { to => $library2, from => $library1 } ), 0, + 'We get the same result also if we pass the from-library parameter.' + ); + $item->holdingbranch( $library2->branchcode )->store; + is( + $biblio->can_be_transferred( { to => $library2 } ), 1, + 'Given one of the ' . 'items is already located at to-library, then the transfer is possible.' + ); + $item->holdingbranch( $library1->branchcode )->store; my $item2 = $builder->build_sample_item( { @@ -184,13 +202,19 @@ subtest 'can_be_transferred' => sub { holdingbranch => $library3->branchcode, } ); - is($biblio->can_be_transferred({ to => $library2 }), 1, 'Given we added ' - .'another item that should have no transfer limits applying on, then ' - .'the transfer is possible.'); - $item2->holdingbranch($library1->branchcode)->store; - is($biblio->can_be_transferred({ to => $library2 }), 0, 'Given all of items' - .' of the biblio are from same, transfer limited library, then transfer' - .' is not possible.'); + is( + $biblio->can_be_transferred( { to => $library2 } ), 1, + 'Given we added ' + . 'another item that should have no transfer limits applying on, then ' + . 'the transfer is possible.' + ); + $item2->holdingbranch( $library1->branchcode )->store; + is( + $biblio->can_be_transferred( { to => $library2 } ), 0, + 'Given all of items' + . ' of the biblio are from same, transfer limited library, then transfer' + . ' is not possible.' + ); }; subtest 'custom_cover_image_url' => sub { @@ -198,13 +222,13 @@ subtest 'custom_cover_image_url' => sub { t::lib::Mocks::mock_preference( 'CustomCoverImagesURL', 'https://my_url/{isbn}_{issn}.png' ); - my $isbn = '0553573403 | 9780553573404 (pbk.).png'; - my $issn = 'my_issn'; - my $cf_value = 'from_control_field'; - my $biblio = $builder->build_sample_biblio; + my $isbn = '0553573403 | 9780553573404 (pbk.).png'; + my $issn = 'my_issn'; + my $cf_value = 'from_control_field'; + my $biblio = $builder->build_sample_biblio; my $marc_record = $biblio->metadata->record; - my ( $isbn_tag, $isbn_subfield ) = GetMarcFromKohaField( 'biblioitems.isbn' ); - my ( $issn_tag, $issn_subfield ) = GetMarcFromKohaField( 'biblioitems.issn' ); + my ( $isbn_tag, $isbn_subfield ) = GetMarcFromKohaField('biblioitems.isbn'); + my ( $issn_tag, $issn_subfield ) = GetMarcFromKohaField('biblioitems.issn'); $marc_record->append_fields( MARC::Field->new( $isbn_tag, '', '', $isbn_subfield => $isbn ), MARC::Field->new( $issn_tag, '', '', $issn_subfield => $issn ), @@ -225,11 +249,14 @@ subtest 'custom_cover_image_url' => sub { is( $biblio->custom_cover_image_url, "https://my_url/$normalized_isbn.png" ); $biblio->biblioitem->isbn('')->store; - is( $biblio->custom_cover_image_url, undef, "Don't generate the url if the biblio does not have the value needed to generate it" ); + is( + $biblio->custom_cover_image_url, undef, + "Don't generate the url if the biblio does not have the value needed to generate it" + ); t::lib::Mocks::mock_preference( 'CustomCoverImagesURL', 'https://my_url/{001}.png' ); is( $biblio->custom_cover_image_url, undef, 'Record does not have 001' ); - $marc_record->append_fields(MARC::Field->new('001', $cf_value)); + $marc_record->append_fields( MARC::Field->new( '001', $cf_value ) ); C4::Biblio::ModBiblio( $marc_record, $biblio->biblionumber ); $biblio = Koha::Biblios->find( $biblio->biblionumber ); is( $biblio->get_from_storage->custom_cover_image_url, "https://my_url/$cf_value.png", 'URL generated using 001' ); @@ -244,14 +271,14 @@ subtest 'pickup_locations() tests' => sub { $schema->storage->txn_begin; # Build 8 libraries - my $l_1 = $builder->build_object({ class => 'Koha::Libraries', value => { pickup_location => 1 } }); - my $l_2 = $builder->build_object({ class => 'Koha::Libraries', value => { pickup_location => 1 } }); - my $l_3 = $builder->build_object({ class => 'Koha::Libraries', value => { pickup_location => 1 } }); - my $l_4 = $builder->build_object({ class => 'Koha::Libraries', value => { pickup_location => 1 } }); - my $l_5 = $builder->build_object({ class => 'Koha::Libraries', value => { pickup_location => 1 } }); - my $l_6 = $builder->build_object({ class => 'Koha::Libraries', value => { pickup_location => 1 } }); - my $l_7 = $builder->build_object({ class => 'Koha::Libraries', value => { pickup_location => 1 } }); - my $l_8 = $builder->build_object({ class => 'Koha::Libraries', value => { pickup_location => 1 } }); + my $l_1 = $builder->build_object( { class => 'Koha::Libraries', value => { pickup_location => 1 } } ); + my $l_2 = $builder->build_object( { class => 'Koha::Libraries', value => { pickup_location => 1 } } ); + my $l_3 = $builder->build_object( { class => 'Koha::Libraries', value => { pickup_location => 1 } } ); + my $l_4 = $builder->build_object( { class => 'Koha::Libraries', value => { pickup_location => 1 } } ); + my $l_5 = $builder->build_object( { class => 'Koha::Libraries', value => { pickup_location => 1 } } ); + my $l_6 = $builder->build_object( { class => 'Koha::Libraries', value => { pickup_location => 1 } } ); + my $l_7 = $builder->build_object( { class => 'Koha::Libraries', value => { pickup_location => 1 } } ); + my $l_8 = $builder->build_object( { class => 'Koha::Libraries', value => { pickup_location => 1 } } ); # Mock Koha::Item->pickup_locations so we have control on the output # The $switch variable controls the output. @@ -278,23 +305,18 @@ subtest 'pickup_locations() tests' => sub { my $biblio_2 = $builder->build_sample_biblio; # Two items each - my $item_1_1 = $builder->build_sample_item({ biblionumber => $biblio_1->biblionumber }); - my $item_1_2 = $builder->build_sample_item({ biblionumber => $biblio_1->biblionumber }); - my $item_2_1 = $builder->build_sample_item({ biblionumber => $biblio_2->biblionumber }); - my $item_2_2 = $builder->build_sample_item({ biblionumber => $biblio_2->biblionumber }); + my $item_1_1 = $builder->build_sample_item( { biblionumber => $biblio_1->biblionumber } ); + my $item_1_2 = $builder->build_sample_item( { biblionumber => $biblio_1->biblionumber } ); + my $item_2_1 = $builder->build_sample_item( { biblionumber => $biblio_2->biblionumber } ); + my $item_2_2 = $builder->build_sample_item( { biblionumber => $biblio_2->biblionumber } ); - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); - my $biblios = Koha::Biblios->search( - { - biblionumber => [ $biblio_1->biblionumber, $biblio_2->biblionumber ] - } - ); + my $biblios = Koha::Biblios->search( { biblionumber => [ $biblio_1->biblionumber, $biblio_2->biblionumber ] } ); - throws_ok - { $biblios->pickup_locations } - 'Koha::Exceptions::MissingParameter', - 'Exception thrown on missing parameter'; + throws_ok { $biblios->pickup_locations } + 'Koha::Exceptions::MissingParameter', + 'Exception thrown on missing parameter'; is( $@->parameter, 'patron', 'Exception param correctly set' ); @@ -311,9 +333,8 @@ subtest 'pickup_locations() tests' => sub { )->_resultset->get_column('branchcode')->all ]; - my $pickup_locations_ids = [ - $biblios->pickup_locations({ patron => $patron })->_resultset->get_column('branchcode')->all - ]; + my $pickup_locations_ids = + [ $biblios->pickup_locations( { patron => $patron } )->_resultset->get_column('branchcode')->all ]; is_deeply( $library_ids, diff --git a/t/db_dependent/Koha/Cash/Register.t b/t/db_dependent/Koha/Cash/Register.t index 479d22326f..aeef2556c9 100755 --- a/t/db_dependent/Koha/Cash/Register.t +++ b/t/db_dependent/Koha/Cash/Register.t @@ -35,7 +35,7 @@ subtest 'library' => sub { $schema->storage->txn_begin; - my $library = $builder->build_object( { class => 'Koha::Libraries' } ); + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); my $register = $builder->build_object( { class => 'Koha::Cash::Registers', @@ -43,13 +43,17 @@ subtest 'library' => sub { } ); - is( ref( $register->library ), + is( + ref( $register->library ), 'Koha::Library', - 'Koha::Cash::Register->library should return a Koha::Library' ); + 'Koha::Cash::Register->library should return a Koha::Library' + ); - is( $register->library->id, + is( + $register->library->id, $library->id, - 'Koha::Cash::Register->library returns the correct Koha::Library' ); + 'Koha::Cash::Register->library returns the correct Koha::Library' + ); $schema->storage->txn_rollback; }; @@ -59,15 +63,16 @@ subtest 'accountlines' => sub { $schema->storage->txn_begin; - my $register = - $builder->build_object( { class => 'Koha::Cash::Registers' } ); + my $register = $builder->build_object( { class => 'Koha::Cash::Registers' } ); my $accountlines = $register->accountlines; - is( ref($accountlines), 'Koha::Account::Lines', -'Koha::Cash::Register->accountlines should always return a Koha::Account::Lines set' + is( + ref($accountlines), 'Koha::Account::Lines', + 'Koha::Cash::Register->accountlines should always return a Koha::Account::Lines set' ); - is( $accountlines->count, 0, -'Koha::Cash::Register->accountlines should always return the correct number of accountlines' + is( + $accountlines->count, 0, + 'Koha::Cash::Register->accountlines should always return the correct number of accountlines' ); my $accountline1 = $builder->build_object( @@ -84,16 +89,19 @@ subtest 'accountlines' => sub { ); $accountlines = $register->accountlines; - is( ref($accountlines), 'Koha::Account::Lines', -'Koha::Cash::Register->accountlines should return a set of Koha::Account::Lines' + is( + ref($accountlines), 'Koha::Account::Lines', + 'Koha::Cash::Register->accountlines should return a set of Koha::Account::Lines' ); - is( $accountlines->count, 2, -'Koha::Cash::Register->accountlines should return the correct number of accountlines' + is( + $accountlines->count, 2, + 'Koha::Cash::Register->accountlines should return the correct number of accountlines' ); $accountline1->delete; - is( $register->accountlines->next->id, $accountline2->id, -'Koha::Cash::Register->accountlines should return the correct acocuntlines' + is( + $register->accountlines->next->id, $accountline2->id, + 'Koha::Cash::Register->accountlines should return the correct acocuntlines' ); $schema->storage->txn_rollback; @@ -103,7 +111,7 @@ subtest 'branch_default' => sub { plan tests => 3; $schema->storage->txn_begin; - my $library = $builder->build_object( { class => 'Koha::Libraries' } ); + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); my $register1 = $builder->build_object( { class => 'Koha::Cash::Registers', @@ -121,13 +129,15 @@ subtest 'branch_default' => sub { plan tests => 2; $register1->name('Test till 1'); - ok( $register1->store(), - "Store works as expected when branch_default is not changed" ); + ok( + $register1->store(), + "Store works as expected when branch_default is not changed" + ); $register1->branch_default(0); throws_ok { $register1->store(); } 'Koha::Exceptions::Object::ReadOnlyProperty', - 'Exception thrown if direct update to branch_default is attempted'; + 'Exception thrown if direct update to branch_default is attempted'; }; @@ -159,18 +169,15 @@ subtest 'cashup' => sub { $schema->storage->txn_begin; - my $register = - $builder->build_object( { class => 'Koha::Cash::Registers' } ); - my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + my $register = $builder->build_object( { class => 'Koha::Cash::Registers' } ); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $cashup1; subtest 'add_cashup' => sub { plan tests => 6; ok( - $cashup1 = $register->add_cashup( - { manager_id => $patron->id, amount => '12.00' } - ), + $cashup1 = $register->add_cashup( { manager_id => $patron->id, amount => '12.00' } ), 'call successfull' ); @@ -179,21 +186,28 @@ subtest 'cashup' => sub { 'Koha::Cash::Register::Cashup', 'return is Koha::Cash::Register::Cashup' ); - is( $cashup1->code, 'CASHUP', - 'CASHUP code set in Koha::Cash::Register::Cashup' ); - is( $cashup1->manager_id, $patron->id, - 'manager_id set correctly in Koha::Cash::Register::Cashup' ); - is( $cashup1->amount, '12.000000', - 'amount set correctly in Koha::Cash::Register::Cashup' ); - isnt( $cashup1->timestamp, undef, - 'timestamp set in Koha::Cash::Register::Cashup' ); + is( + $cashup1->code, 'CASHUP', + 'CASHUP code set in Koha::Cash::Register::Cashup' + ); + is( + $cashup1->manager_id, $patron->id, + 'manager_id set correctly in Koha::Cash::Register::Cashup' + ); + is( + $cashup1->amount, '12.000000', + 'amount set correctly in Koha::Cash::Register::Cashup' + ); + isnt( + $cashup1->timestamp, undef, + 'timestamp set in Koha::Cash::Register::Cashup' + ); }; subtest 'last_cashup' => sub { plan tests => 3; - my $cashup2 = - $register->add_cashup( { manager_id => $patron->id, amount => '6.00' } ); + my $cashup2 = $register->add_cashup( { manager_id => $patron->id, amount => '6.00' } ); my $last_cashup = $register->last_cashup; is( @@ -201,8 +215,10 @@ subtest 'cashup' => sub { 'Koha::Cash::Register::Cashup', 'A cashup was returned when one existed' ); - is( $last_cashup->id, $cashup2->id, - 'The most recent cashup was returned' ); + is( + $last_cashup->id, $cashup2->id, + 'The most recent cashup was returned' + ); $cashup1->delete; $cashup2->delete; $last_cashup = $register->last_cashup; @@ -213,22 +229,25 @@ subtest 'cashup' => sub { plan tests => 4; my $cashups = $register->cashups; - is( ref($cashups), 'Koha::Cash::Register::Cashups', -'Koha::Cash::Register->cashups should always return a Koha::Cash::Register::Cashups set' + is( + ref($cashups), 'Koha::Cash::Register::Cashups', + 'Koha::Cash::Register->cashups should always return a Koha::Cash::Register::Cashups set' ); - is( $cashups->count, 0, -'Koha::Cash::Register->cashups should always return the correct number of cashups' + is( + $cashups->count, 0, + 'Koha::Cash::Register->cashups should always return the correct number of cashups' ); - my $cashup3 = - $register->add_cashup( { manager_id => $patron->id, amount => '6.00' } ); + my $cashup3 = $register->add_cashup( { manager_id => $patron->id, amount => '6.00' } ); $cashups = $register->cashups; - is( ref($cashups), 'Koha::Cash::Register::Cashups', -'Koha::Cash::Register->cashups should return a Koha::Cash::Register::Cashups set' + is( + ref($cashups), 'Koha::Cash::Register::Cashups', + 'Koha::Cash::Register->cashups should return a Koha::Cash::Register::Cashups set' ); - is( $cashups->count, 1, -'Koha::Cash::Register->cashups should return the correct number of cashups' + is( + $cashups->count, 1, + 'Koha::Cash::Register->cashups should return the correct number of cashups' ); $cashup3->delete; @@ -238,11 +257,13 @@ subtest 'cashup' => sub { plan tests => 6; my $accountlines = $register->outstanding_accountlines; - is( ref($accountlines), 'Koha::Account::Lines', -'Koha::Cash::Register->outstanding_accountlines should always return a Koha::Account::Lines set' + is( + ref($accountlines), 'Koha::Account::Lines', + 'Koha::Cash::Register->outstanding_accountlines should always return a Koha::Account::Lines set' ); - is( $accountlines->count, 0, -'Koha::Cash::Register->outstanding_accountlines should always return the correct number of accountlines' + is( + $accountlines->count, 0, + 'Koha::Cash::Register->outstanding_accountlines should always return the correct number of accountlines' ); my $accountline1 = $builder->build_object( @@ -254,15 +275,14 @@ subtest 'cashup' => sub { my $accountline2 = $builder->build_object( { class => 'Koha::Account::Lines', - value => { register_id => $register->id, date => \'NOW() - INTERVAL 5 MINUTE'}, + value => { register_id => $register->id, date => \'NOW() - INTERVAL 5 MINUTE' }, } ); $accountlines = $register->outstanding_accountlines; is( $accountlines->count, 2, 'No cashup, all accountlines returned' ); - my $cashup3 = - $register->add_cashup( { manager_id => $patron->id, amount => '2.50' } ); + my $cashup3 = $register->add_cashup( { manager_id => $patron->id, amount => '2.50' } ); $accountlines = $register->outstanding_accountlines; is( $accountlines->count, 0, 'Cashup added, no accountlines returned' ); @@ -276,13 +296,17 @@ subtest 'cashup' => sub { # Fake the cashup timestamp to make sure it's before the accountline we just added, # we can't trust that these two actions are more than a second apart in a test - $cashup3->timestamp(\'NOW() - INTERVAL 2 MINUTE')->store; + $cashup3->timestamp( \'NOW() - INTERVAL 2 MINUTE' )->store; $accountlines = $register->outstanding_accountlines; - is( $accountlines->count, 1, - 'Accountline added, one accountline returned' ); - is( $accountlines->next->id, - $accountline3->id, 'Correct accountline returned' ); + is( + $accountlines->count, 1, + 'Accountline added, one accountline returned' + ); + is( + $accountlines->next->id, + $accountline3->id, 'Correct accountline returned' + ); }; $schema->storage->txn_rollback; diff --git a/t/db_dependent/Koha/Cash/Register/Action.t b/t/db_dependent/Koha/Cash/Register/Action.t index 233c1a7590..b348bed6f9 100755 --- a/t/db_dependent/Koha/Cash/Register/Action.t +++ b/t/db_dependent/Koha/Cash/Register/Action.t @@ -33,19 +33,22 @@ subtest 'manager' => sub { $schema->storage->txn_begin; my $manager = $builder->build_object( { class => 'Koha::Patrons' } ); - my $action = $builder->build_object( + my $action = $builder->build_object( { class => 'Koha::Cash::Register::Actions', value => { manager_id => $manager->borrowernumber }, } ); - is( ref( $action->manager ), + is( + ref( $action->manager ), 'Koha::Patron', - 'Koha::Cash::Register::Action->manager should return a Koha::Patron' ); + 'Koha::Cash::Register::Action->manager should return a Koha::Patron' + ); - is( $action->manager->id, $manager->id, -'Koha::Cash::Registeri::Action->manager returns the correct Koha::Patron' + is( + $action->manager->id, $manager->id, + 'Koha::Cash::Registeri::Action->manager returns the correct Koha::Patron' ); $schema->storage->txn_rollback; @@ -57,9 +60,8 @@ subtest 'register' => sub { $schema->storage->txn_begin; - my $register = - $builder->build_object( { class => 'Koha::Cash::Registers' } ); - my $action = $builder->build_object( + my $register = $builder->build_object( { class => 'Koha::Cash::Registers' } ); + my $action = $builder->build_object( { class => 'Koha::Cash::Register::Actions', value => { register_id => $register->id }, @@ -69,11 +71,12 @@ subtest 'register' => sub { is( ref( $action->register ), 'Koha::Cash::Register', -'Koha::Cash::Register::Action->register should return a Koha::Cash::Register' + 'Koha::Cash::Register::Action->register should return a Koha::Cash::Register' ); - is( $action->register->id, $register->id, -'Koha::Cash::Register::Action->register returns the correct Koha::Cash::Register' + is( + $action->register->id, $register->id, + 'Koha::Cash::Register::Action->register returns the correct Koha::Cash::Register' ); $schema->storage->txn_rollback; diff --git a/t/db_dependent/Koha/Cash/Register/Cashup.t b/t/db_dependent/Koha/Cash/Register/Cashup.t index df373c3d87..97a8151df7 100755 --- a/t/db_dependent/Koha/Cash/Register/Cashup.t +++ b/t/db_dependent/Koha/Cash/Register/Cashup.t @@ -33,18 +33,21 @@ subtest 'manager' => sub { $schema->storage->txn_begin; my $manager = $builder->build_object( { class => 'Koha::Patrons' } ); - my $cashup = $builder->build_object( + my $cashup = $builder->build_object( { class => 'Koha::Cash::Register::Cashups', value => { manager_id => $manager->borrowernumber }, } ); - is( ref( $cashup->manager ), + is( + ref( $cashup->manager ), 'Koha::Patron', - 'Koha::Cash::Register::Cashup->manager should return a Koha::Patron' ); + 'Koha::Cash::Register::Cashup->manager should return a Koha::Patron' + ); - is( $cashup->manager->id, $manager->id, + is( + $cashup->manager->id, $manager->id, 'Koha::Cash::Register::Cashup->manager returns the correct Koha::Patron' ); @@ -57,9 +60,8 @@ subtest 'register' => sub { $schema->storage->txn_begin; - my $register = - $builder->build_object( { class => 'Koha::Cash::Registers' } ); - my $cashup = $builder->build_object( + my $register = $builder->build_object( { class => 'Koha::Cash::Registers' } ); + my $cashup = $builder->build_object( { class => 'Koha::Cash::Register::Cashups', value => { register_id => $register->id }, @@ -69,11 +71,12 @@ subtest 'register' => sub { is( ref( $cashup->register ), 'Koha::Cash::Register', -'Koha::Cash::Register::Cashup->register should return a Koha::Cash::Register' + 'Koha::Cash::Register::Cashup->register should return a Koha::Cash::Register' ); - is( $cashup->register->id, $register->id, -'Koha::Cash::Register::Cashup->register returns the correct Koha::Cash::Register' + is( + $cashup->register->id, $register->id, + 'Koha::Cash::Register::Cashup->register returns the correct Koha::Cash::Register' ); $schema->storage->txn_rollback; @@ -85,12 +88,11 @@ subtest 'summary' => sub { $schema->storage->txn_begin; - my $register = - $builder->build_object( { class => 'Koha::Cash::Registers' } ); - my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); - my $manager = $builder->build_object( { class => 'Koha::Patrons' } ); - my $account = $patron->account; - my $expected_total = 0; + my $register = $builder->build_object( { class => 'Koha::Cash::Registers' } ); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + my $manager = $builder->build_object( { class => 'Koha::Patrons' } ); + my $account = $patron->account; + my $expected_total = 0; my $expected_income_total = 0; my $expected_income_grouped = []; my $expected_payout_total = 0; @@ -120,11 +122,11 @@ subtest 'summary' => sub { # Overdue of 1.0 fully paid unshift @{$expected_income_grouped}, - { + { debit_type_code => 'OVERDUE', total => '1', debit_type => { description => 'Overdue fine' } - }; + }; # Transaction 2 (Account (1.00) + Lost (0.50) + Payment (-1.50)) my $account1 = $account->add_debit( @@ -157,19 +159,19 @@ subtest 'summary' => sub { # Lost charge of 0.5 fully paid unshift @{$expected_income_grouped}, - { + { debit_type_code => 'LOST', total => '0.5', debit_type => { description => 'Lost item' } - }; + }; # Account fee of 1.0 fully paid unshift @{$expected_income_grouped}, - { + { debit_type_code => 'ACCOUNT', total => '1', debit_type => { description => 'Account creation fee' } - }; + }; # Transaction 3 (Refund (-0.50) + Payout (0.50)) $lost1->discard_changes; @@ -197,46 +199,41 @@ subtest 'summary' => sub { # Lost fee of 0.50 fully refunded unshift @{$expected_payout_grouped}, - { - 'total' => '0.5', - 'credit_type' => { - 'description' => 'Refund' - }, + { + 'total' => '0.5', + 'credit_type' => { 'description' => 'Refund' }, 'credit_type_code' => 'REFUND', - 'related_debit' => { + 'related_debit' => { 'debit_type_code' => 'LOST', - 'debit_type' => { - 'description' => 'Lost item' - } + 'debit_type' => { 'description' => 'Lost item' } } - }; + }; $expected_total += $expected_income_total; $expected_total -= $expected_payout_total; # Cashup 1 - my $cashup1 = - $register->add_cashup( { manager_id => $manager->id, amount => '2.00' } ); + my $cashup1 = $register->add_cashup( { manager_id => $manager->id, amount => '2.00' } ); my $summary = $cashup1->summary; - is( $summary->{from_date}, undef, "from_date is undefined if there is only one recorded" ); - is( $summary->{to_date}, $cashup1->timestamp, "to_date equals cashup timestamp" ); - is( ref( $summary->{income_grouped} ), 'ARRAY', "income_grouped contains an arrayref" ); - is( scalar @{ $summary->{income_grouped} }, 3, "income_grouped contains 3 transactions" ); + is( $summary->{from_date}, undef, "from_date is undefined if there is only one recorded" ); + is( $summary->{to_date}, $cashup1->timestamp, "to_date equals cashup timestamp" ); + is( ref( $summary->{income_grouped} ), 'ARRAY', "income_grouped contains an arrayref" ); + is( scalar @{ $summary->{income_grouped} }, 3, "income_grouped contains 3 transactions" ); is_deeply( $summary->{income_grouped}, $expected_income_grouped, "income_grouped arrayref is correct" ); is( $summary->{income_total}, $expected_income_total, "income_total is correct" ); - is( ref( $summary->{payout_grouped} ), 'ARRAY', "payout_grouped contains an arrayref" ); - is( scalar @{ $summary->{payout_grouped} }, 1, "payout_grouped contains 1 transaction" ); + is( ref( $summary->{payout_grouped} ), 'ARRAY', "payout_grouped contains an arrayref" ); + is( scalar @{ $summary->{payout_grouped} }, 1, "payout_grouped contains 1 transaction" ); is_deeply( $summary->{payout_grouped}, $expected_payout_grouped, "payout_grouped arrayref is correct" ); is( $summary->{payout_total}, $expected_payout_total, "payout_total is correct" ); - is( $summary->{total}, $expected_total,"total equals expected_total" ); + is( $summary->{total}, $expected_total, "total equals expected_total" ); # Backdate cashup1 so we can add a new cashup to check 'previous' $cashup1->timestamp( \'NOW() - INTERVAL 12 MINUTE' )->store(); $cashup1->discard_changes; - $expected_total = 0; + $expected_total = 0; $expected_income_total = 0; $expected_income_grouped = []; $expected_payout_total = 0; @@ -265,35 +262,37 @@ subtest 'summary' => sub { $expected_income_total += '2.00'; unshift @{$expected_income_grouped}, - { + { debit_type_code => 'OVERDUE', total => '-2.000000' * -1, debit_type => { 'description' => 'Overdue fine' } - }; + }; $expected_total += $expected_income_total; $expected_total -= $expected_payout_total; # Cashup 2 - my $cashup2 = - $register->add_cashup( { manager_id => $manager->id, amount => '2.00' } ); + my $cashup2 = $register->add_cashup( { manager_id => $manager->id, amount => '2.00' } ); $summary = $cashup2->summary; is( $summary->{from_date}, $cashup1->timestamp, "from_date returns the timestamp of the previous cashup cashup" ); - is( $summary->{to_date}, $cashup2->timestamp, "to_date equals cashup timestamp" ); - is( ref( $summary->{income_grouped} ), 'ARRAY', "income_grouped contains Koha::Account::Lines" ); - is( scalar @{ $summary->{income_grouped} }, 1, "income_grouped contains 1 transaction" ); - is_deeply( $summary->{income_grouped}, $expected_income_grouped, "income_grouped arrayref is correct for partial payment" ); - is( ref( $summary->{payout_grouped} ), 'ARRAY', "payout_grouped contains Koha::Account::Lines" ); - is( scalar @{ $summary->{payout_grouped} }, 0, "payout_grouped contains 0 transactions" ); + is( $summary->{to_date}, $cashup2->timestamp, "to_date equals cashup timestamp" ); + is( ref( $summary->{income_grouped} ), 'ARRAY', "income_grouped contains Koha::Account::Lines" ); + is( scalar @{ $summary->{income_grouped} }, 1, "income_grouped contains 1 transaction" ); + is_deeply( + $summary->{income_grouped}, $expected_income_grouped, + "income_grouped arrayref is correct for partial payment" + ); + is( ref( $summary->{payout_grouped} ), 'ARRAY', "payout_grouped contains Koha::Account::Lines" ); + is( scalar @{ $summary->{payout_grouped} }, 0, "payout_grouped contains 0 transactions" ); is_deeply( $summary->{payout_grouped}, $expected_payout_grouped, "payout_grouped arrayref is correct" ); is( $summary->{total}, $expected_total, "total equals expected_total" ); # Backdate cashup2 so we can add a new cashup to check $cashup2->timestamp( \'NOW() - INTERVAL 6 MINUTE' )->store(); $cashup2->discard_changes; - $expected_total = 0; + $expected_total = 0; $expected_income_total = 0; $expected_income_grouped = []; $expected_payout_total = 0; @@ -325,36 +324,34 @@ subtest 'summary' => sub { # Account fee of 1.00 fully refunded (Across cashup boundary) unshift @{$expected_payout_grouped}, - { - 'total' => '1', - 'credit_type' => { - 'description' => 'Refund' - }, + { + 'total' => '1', + 'credit_type' => { 'description' => 'Refund' }, 'credit_type_code' => 'REFUND', - 'related_debit' => { + 'related_debit' => { 'debit_type_code' => 'ACCOUNT', - 'debit_type' => { - 'description' => 'Account creation fee' - } + 'debit_type' => { 'description' => 'Account creation fee' } } - }; + }; $expected_total += $expected_income_total; $expected_total -= $expected_payout_total; # Cashup 3 - my $cashup3 = - $register->add_cashup( { manager_id => $manager->id, amount => '2.00' } ); + my $cashup3 = $register->add_cashup( { manager_id => $manager->id, amount => '2.00' } ); $summary = $cashup3->summary; is( $summary->{from_date}, $cashup2->timestamp, "from_date returns the timestamp of the previous cashup cashup" ); - is( $summary->{to_date}, $cashup3->timestamp, "to_date equals cashup timestamp" ); - is( ref( $summary->{income_grouped} ), 'ARRAY', "income_grouped contains Koha::Account::Lines" ); - is( scalar @{ $summary->{income_grouped} }, 0, "income_grouped contains 1 transaction" ); - is_deeply( $summary->{income_grouped}, $expected_income_grouped, "income_grouped arrayref is correct for partial payment" ); - is( ref( $summary->{payout_grouped} ), 'ARRAY', "payout_grouped contains Koha::Account::Lines" ); - is( scalar @{ $summary->{payout_grouped} }, 1, "payout_grouped contains 0 transactions" ); + is( $summary->{to_date}, $cashup3->timestamp, "to_date equals cashup timestamp" ); + is( ref( $summary->{income_grouped} ), 'ARRAY', "income_grouped contains Koha::Account::Lines" ); + is( scalar @{ $summary->{income_grouped} }, 0, "income_grouped contains 1 transaction" ); + is_deeply( + $summary->{income_grouped}, $expected_income_grouped, + "income_grouped arrayref is correct for partial payment" + ); + is( ref( $summary->{payout_grouped} ), 'ARRAY', "payout_grouped contains Koha::Account::Lines" ); + is( scalar @{ $summary->{payout_grouped} }, 1, "payout_grouped contains 0 transactions" ); is_deeply( $summary->{payout_grouped}, $expected_payout_grouped, "payout_grouped arrayref is correct" ); is( $summary->{total}, $expected_total, "total equals expected_total" ); diff --git a/t/db_dependent/Koha/Cash/Register/Cashups.t b/t/db_dependent/Koha/Cash/Register/Cashups.t index 7f009a528d..6845930d3d 100755 --- a/t/db_dependent/Koha/Cash/Register/Cashups.t +++ b/t/db_dependent/Koha/Cash/Register/Cashups.t @@ -32,10 +32,9 @@ subtest 'search' => sub { $schema->storage->txn_begin; - my $manager = $builder->build_object( { class => 'Koha::Patrons' } ); - my $register = - $builder->build_object( { class => 'Koha::Cash::Registers' } ); - my $cashup1 = $builder->build_object( + my $manager = $builder->build_object( { class => 'Koha::Patrons' } ); + my $register = $builder->build_object( { class => 'Koha::Cash::Registers' } ); + my $cashup1 = $builder->build_object( { class => 'Koha::Cash::Register::Actions', value => { diff --git a/t/db_dependent/Koha/Charges/Fees.t b/t/db_dependent/Koha/Charges/Fees.t index 2f2af9d876..acf429885a 100755 --- a/t/db_dependent/Koha/Charges/Fees.t +++ b/t/db_dependent/Koha/Charges/Fees.t @@ -28,7 +28,7 @@ use t::lib::TestBuilder; use t::lib::Dates; use Time::Fake; -use C4::Calendar qw( new insert_week_day_holiday delete_holiday ); +use C4::Calendar qw( new insert_week_day_holiday delete_holiday ); use Koha::DateUtils qw(dt_from_string); BEGIN { @@ -69,7 +69,7 @@ my $itemtype = $builder->build_object( rentalcharge => '0.00', processfee => '0.00', defaultreplacecost => '0.00', - }, + }, } ); my $item = $builder->build_object( @@ -97,7 +97,7 @@ my $now = dt_from_string()->set_time_zone('floating'); Time::Fake->offset( $now->epoch ); my $dt_from = $now->clone->subtract( days => 2 ); -my $dt_to = $now->clone->add( days => 4 ); +my $dt_to = $now->clone->add( days => 4 ); subtest 'new' => sub { plan tests => 9; @@ -110,7 +110,7 @@ subtest 'new' => sub { item => $item, to_date => $dt_to, } - ) + ) } 'Koha::Exceptions::MissingParameter', 'MissingParameter thrown for patron'; throws_ok { @@ -120,7 +120,7 @@ subtest 'new' => sub { item => $item, to_date => $dt_to, } - ) + ) } 'Koha::Exceptions::MissingParameter', 'MissingParameter thrown for library'; throws_ok { @@ -130,7 +130,7 @@ subtest 'new' => sub { library => $library, to_date => $dt_to, } - ) + ) } 'Koha::Exceptions::MissingParameter', 'MissingParameter thrown for item'; throws_ok { @@ -140,7 +140,7 @@ subtest 'new' => sub { library => $library, item => $item, } - ) + ) } 'Koha::Exceptions::MissingParameter', 'MissingParameter thrown for to_date'; @@ -153,7 +153,7 @@ subtest 'new' => sub { item => $item, to_date => $dt_to, } - ) + ) } 'dies for bad patron'; dies_ok { @@ -164,7 +164,7 @@ subtest 'new' => sub { item => $item, to_date => $dt_to, } - ) + ) } 'dies for bad library'; dies_ok { @@ -175,7 +175,7 @@ subtest 'new' => sub { item => '12345', to_date => $dt_to, } - ) + ) } 'dies for bad item'; dies_ok { @@ -186,7 +186,7 @@ subtest 'new' => sub { item => $item, to_date => 12345 } - ) + ) } 'dies for bad to_date'; @@ -199,8 +199,10 @@ subtest 'new' => sub { to_date => $dt_to, } ); - is( t::lib::Dates::compare($fees->from_date, dt_from_string()), 0, - 'from_date default set correctly to today' ); + is( + t::lib::Dates::compare( $fees->from_date, dt_from_string() ), 0, + 'from_date default set correctly to today' + ); }; subtest 'patron accessor' => sub { @@ -220,9 +222,8 @@ subtest 'patron accessor' => sub { 'patron accessor returns a Koha::Patron' ); warning_is { $fees->patron('12345') } - { carped => -"Setting 'patron' to something other than a Koha::Patron is not supported!" - }, "Warning thrown when attempting to set patron to string"; + { carped => "Setting 'patron' to something other than a Koha::Patron is not supported!" }, + "Warning thrown when attempting to set patron to string"; }; @@ -243,9 +244,8 @@ subtest 'library accessor' => sub { 'library accessor returns a Koha::Library' ); warning_is { $fees->library('12345') } - { carped => -"Setting 'library' to something other than a Koha::Library is not supported!" - }, "Warning thrown when attempting to set library to string"; + { carped => "Setting 'library' to something other than a Koha::Library is not supported!" }, + "Warning thrown when attempting to set library to string"; }; subtest 'item accessor' => sub { @@ -262,9 +262,8 @@ subtest 'item accessor' => sub { ok( $fees->item->isa('Koha::Item'), 'item accessor returns a Koha::Item' ); warning_is { $fees->item('12345') } - { carped => -"Setting 'item' to something other than a Koha::Item is not supported!" - }, "Warning thrown when attempting to set item to string"; + { carped => "Setting 'item' to something other than a Koha::Item is not supported!" }, + "Warning thrown when attempting to set item to string"; }; subtest 'to_date accessor' => sub { @@ -279,12 +278,13 @@ subtest 'to_date accessor' => sub { } ); - ok( $fees->to_date->isa('DateTime'), - 'to_date accessor returns a DateTime' ); + ok( + $fees->to_date->isa('DateTime'), + 'to_date accessor returns a DateTime' + ); warning_is { $fees->to_date(12345) } - { carped => -"Setting 'to_date' to something other than a DateTime is not supported!" - }, "Warning thrown when attempting to set to_date to integer"; + { carped => "Setting 'to_date' to something other than a DateTime is not supported!" }, + "Warning thrown when attempting to set to_date to integer"; }; subtest 'from_date accessor' => sub { @@ -304,9 +304,8 @@ subtest 'from_date accessor' => sub { 'from_date accessor returns a DateTime' ); warning_is { $fees->from_date(12345) } - { carped => -"Setting 'from_date' to something other than a DateTime is not supported!" - }, "Warning thrown when attempting to set from_date to integer"; + { carped => "Setting 'from_date' to something other than a DateTime is not supported!" }, + "Warning thrown when attempting to set from_date to integer"; }; subtest 'accumulate_rentalcharge tests' => sub { @@ -323,11 +322,12 @@ subtest 'accumulate_rentalcharge tests' => sub { ); # Daily tests - Koha::CirculationRules->set_rules({ + Koha::CirculationRules->set_rules( + { categorycode => $patron->categorycode, itemtype => $itemtype->id, branchcode => $library->id, - rules => { + rules => { lengthunit => 'days', } } @@ -335,34 +335,40 @@ subtest 'accumulate_rentalcharge tests' => sub { $itemtype->rentalcharge_daily(1.00); $itemtype->store(); - is( $itemtype->rentalcharge_daily, - 1.00, 'Daily return charge stored correctly' ); + is( + $itemtype->rentalcharge_daily, + 1.00, 'Daily return charge stored correctly' + ); t::lib::Mocks::mock_preference( 'finesCalendar', 'ignoreCalendar' ); my $charge = $fees->accumulate_rentalcharge(); - is( $charge, 6.00, -'Daily rental charge calculated correctly with finesCalendar = ignoreCalendar' + is( + $charge, 6.00, + 'Daily rental charge calculated correctly with finesCalendar = ignoreCalendar' ); t::lib::Mocks::mock_preference( 'finesCalendar', 'noFinesWhenClosed' ); $charge = $fees->accumulate_rentalcharge(); - is( $charge, 6.00, -'Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed' + is( + $charge, 6.00, + 'Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed' ); $itemtype->rentalcharge_daily_calendar(0)->store(); $charge = $fees->accumulate_rentalcharge(); - is( $charge, 6.00, -'Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed and rentalcharge_daily_calendar = 0' + is( + $charge, 6.00, + 'Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed and rentalcharge_daily_calendar = 0' ); $itemtype->rentalcharge_daily_calendar(1)->store(); my $calendar = C4::Calendar->new( branchcode => $library->id ); + # DateTime 1..7 (Mon..Sun), C4::Calender 0..6 (Sun..Sat) my $closed_day = - ( $dt_from->day_of_week == 6 ) ? 0 - : ( $dt_from->day_of_week == 7 ) ? 1 - : $dt_from->day_of_week + 1; + ( $dt_from->day_of_week == 6 ) ? 0 + : ( $dt_from->day_of_week == 7 ) ? 1 + : $dt_from->day_of_week + 1; $calendar->insert_week_day_holiday( weekday => $closed_day, title => 'Test holiday', @@ -379,16 +385,18 @@ subtest 'accumulate_rentalcharge tests' => sub { 6 => 'Saturday' }; my $dayname = $day_names->{$closed_day}; - is( $charge, 5.00, -"Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed and closed $dayname" + is( + $charge, 5.00, + "Daily rental charge calculated correctly with finesCalendar = noFinesWhenClosed and closed $dayname" ); # Hourly tests - Koha::CirculationRules->set_rules({ + Koha::CirculationRules->set_rules( + { categorycode => $patron->categorycode, itemtype => $itemtype->id, branchcode => $library->id, - rules => { + rules => { lengthunit => 'hours', } } @@ -398,8 +406,8 @@ subtest 'accumulate_rentalcharge tests' => sub { $itemtype->rentalcharge_hourly("0.25"); $itemtype->store(); - $dt_to = $dt_from->clone->add( hours => 96 ); - $fees = Koha::Charges::Fees->new( + $dt_to = $dt_from->clone->add( hours => 96 ); + $fees = Koha::Charges::Fees->new( { patron => $patron, library => $library, @@ -415,20 +423,25 @@ subtest 'accumulate_rentalcharge tests' => sub { $itemtype->rentalcharge_hourly_calendar(1)->store(); $charge = $fees->accumulate_rentalcharge(); - is( $charge, 18.00, -"Hourly rental charge calculated correctly with finesCalendar = noFinesWhenClosed and closed $dayname (96h - 24h * 0.25u)" + is( + $charge, 18.00, + "Hourly rental charge calculated correctly with finesCalendar = noFinesWhenClosed and closed $dayname (96h - 24h * 0.25u)" ); $itemtype->rentalcharge_hourly_calendar(0)->store(); $charge = $fees->accumulate_rentalcharge(); - is( $charge, 24.00, -"Hourly rental charge calculated correctly with finesCalendar = noFinesWhenClosed and closed $dayname (96h - 24h * 0.25u) and rentalcharge_hourly_calendar = 0" + is( + $charge, 24.00, + "Hourly rental charge calculated correctly with finesCalendar = noFinesWhenClosed and closed $dayname (96h - 24h * 0.25u) and rentalcharge_hourly_calendar = 0" ); $itemtype->rentalcharge_hourly_calendar(1)->store(); $calendar->delete_holiday( weekday => $closed_day ); $charge = $fees->accumulate_rentalcharge(); - is( $charge, 24.00, 'Hourly rental charge calculated correctly with finesCalendar = noFinesWhenClosed (96h - 0h * 0.25u)' ); + is( + $charge, 24.00, + 'Hourly rental charge calculated correctly with finesCalendar = noFinesWhenClosed (96h - 0h * 0.25u)' + ); }; $schema->storage->txn_rollback; diff --git a/t/db_dependent/Koha/Charges/Sales.t b/t/db_dependent/Koha/Charges/Sales.t index 1a7aa9f43b..105c43cb45 100755 --- a/t/db_dependent/Koha/Charges/Sales.t +++ b/t/db_dependent/Koha/Charges/Sales.t @@ -42,23 +42,21 @@ subtest 'new' => sub { throws_ok { Koha::Charges::Sales->new( { staff_id => 1 } ) } 'Koha::Exceptions::MissingParameter', - 'Exception thrown if cash_register parameter missing'; + 'Exception thrown if cash_register parameter missing'; throws_ok { Koha::Charges::Sales->new( { cash_register => 1 } ) } 'Koha::Exceptions::MissingParameter', - 'Exception thrown if staff_id parameter missing'; + 'Exception thrown if staff_id parameter missing'; throws_ok { Koha::Charges::Sales->new( { staff_id => 1, cash_register => 1 } ) } qr/Koha::Cash::Register/, - 'Exception thrown if cash_register is not a Koha::Cash::Register'; + 'Exception thrown if cash_register is not a Koha::Cash::Register'; - my $cash_register = - $builder->build_object( { class => 'Koha::Cash::Registers' } ); + my $cash_register = $builder->build_object( { class => 'Koha::Cash::Registers' } ); - my $sale = Koha::Charges::Sales->new( - { staff_id => 1, cash_register => $cash_register } ); + my $sale = Koha::Charges::Sales->new( { staff_id => 1, cash_register => $cash_register } ); ok( $sale->isa('Koha::Charges::Sales'), 'New returns a Koha::Charges::Sales object' @@ -72,8 +70,8 @@ subtest 'payment_type (_get_valid_payments) tests' => sub { $schema->storage->txn_begin; - my $library1 = $builder->build_object( { class => 'Koha::Libraries' } ); - my $library2 = $builder->build_object( { class => 'Koha::Libraries' } ); + my $library1 = $builder->build_object( { class => 'Koha::Libraries' } ); + my $library2 = $builder->build_object( { class => 'Koha::Libraries' } ); my $cash_register = $builder->build_object( { class => 'Koha::Cash::Registers', @@ -81,14 +79,13 @@ subtest 'payment_type (_get_valid_payments) tests' => sub { } ); - my $sale = Koha::Charges::Sales->new( - { staff_id => 1, cash_register => $cash_register } ); + my $sale = Koha::Charges::Sales->new( { staff_id => 1, cash_register => $cash_register } ); is( $sale->payment_type, undef, "payment_type does not have a default" ); throws_ok { $sale->payment_type('BOBBYRANDOM') } 'Koha::Exceptions::Account::UnrecognisedType', - "Exception thrown if passed a payment type that doesn't exist"; + "Exception thrown if passed a payment type that doesn't exist"; my $av = Koha::AuthorisedValue->new( { @@ -102,15 +99,17 @@ subtest 'payment_type (_get_valid_payments) tests' => sub { throws_ok { $sale->payment_type('BOBBYRANDOM') } 'Koha::Exceptions::Account::UnrecognisedType', -'Exception thrown if passed payment type that is not valid for the cash registers branch'; + 'Exception thrown if passed payment type that is not valid for the cash registers branch'; $av->replace_library_limits(); - $sale->{valid_payments} = undef; # Flush object cache for 'valid_payments' + $sale->{valid_payments} = undef; # Flush object cache for 'valid_payments' my $pt = $sale->payment_type('BOBBYRANDOM'); is( $pt, 'BOBBYRANDOM', 'Payment type set successfully' ); - is( $sale->payment_type, 'BOBBYRANDOM', - 'Getter returns the current payment_type' ); + is( + $sale->payment_type, 'BOBBYRANDOM', + 'Getter returns the current payment_type' + ); $schema->storage->txn_rollback; }; @@ -120,8 +119,8 @@ subtest 'add_item (_get_valid_items) tests' => sub { $schema->storage->txn_begin; - my $staff = $builder->build_object( { class => 'Koha::Patrons' } ); - my $library1 = $builder->build_object( { class => 'Koha::Libraries' } ); + my $staff = $builder->build_object( { class => 'Koha::Patrons' } ); + my $library1 = $builder->build_object( { class => 'Koha::Libraries' } ); my $cash_register = $builder->build_object( { class => 'Koha::Cash::Registers', @@ -129,16 +128,14 @@ subtest 'add_item (_get_valid_items) tests' => sub { } ); - my $sale = Koha::Charges::Sales->new( - { staff_id => $staff->borrowernumber, cash_register => $cash_register } - ); + my $sale = Koha::Charges::Sales->new( { staff_id => $staff->borrowernumber, cash_register => $cash_register } ); throws_ok { $sale->add_item( { price => 1.00, quantity => 1 } ) } 'Koha::Exceptions::MissingParameter', - 'Exception thrown if `code` parameter is missing'; + 'Exception thrown if `code` parameter is missing'; my $library2 = $builder->build_object( { class => 'Koha::Libraries' } ); - my $dt = Koha::Account::DebitType->new( + my $dt = Koha::Account::DebitType->new( { code => 'BOBBYRANDOM', description => 'Test bobbyrandom', @@ -148,7 +145,7 @@ subtest 'add_item (_get_valid_items) tests' => sub { throws_ok { $sale->add_item( { code => 'BOBBYRANDOM' } ) } 'Koha::Exceptions::Account::UnrecognisedType', -'Exception thrown if passed an item code that is not valid for the cash registers branch'; + 'Exception thrown if passed an item code that is not valid for the cash registers branch'; $dt->replace_library_limits(); $sale->{valid_items} = undef; # Flush object cache for 'valid_items' @@ -157,20 +154,16 @@ subtest 'add_item (_get_valid_items) tests' => sub { $sale->add_item( { code => 'BOBBYRANDOM', quantity => 1 } ) } 'Koha::Exceptions::MissingParameter', - 'Exception thrown if `price` parameter is missing'; + 'Exception thrown if `price` parameter is missing'; throws_ok { $sale->add_item( { code => 'BOBBYRANDOM', price => 1.00 } ) } 'Koha::Exceptions::MissingParameter', - 'Exception thrown if `quantity` parameter is missing'; + 'Exception thrown if `quantity` parameter is missing'; is( - ref( - $sale->add_item( - { code => 'BOBBYRANDOM', price => 1.00, quantity => 1 } - ) - ), + ref( $sale->add_item( { code => 'BOBBYRANDOM', price => 1.00, quantity => 1 } ) ), 'Koha::Charges::Sales', 'Original object returned succesfully' ); @@ -185,8 +178,8 @@ subtest 'purchase tests' => sub { $schema->storage->txn_begin; - my $staff = $builder->build_object( { class => 'Koha::Patrons' } ); - my $library = $builder->build_object( { class => 'Koha::Libraries' } ); + my $staff = $builder->build_object( { class => 'Koha::Patrons' } ); + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); my $cash_register = $builder->build_object( { class => 'Koha::Cash::Registers', @@ -207,22 +200,20 @@ subtest 'purchase tests' => sub { } )->store; - my $sale = Koha::Charges::Sales->new( - { staff_id => $staff->borrowernumber, cash_register => $cash_register } - ); + my $sale = Koha::Charges::Sales->new( { staff_id => $staff->borrowernumber, cash_register => $cash_register } ); throws_ok { $sale->purchase() } 'Koha::Exceptions::MissingParameter', - 'Exception thrown if `payment_type` is neither set nor passed'; + 'Exception thrown if `payment_type` is neither set nor passed'; $sale->payment_type('CASH'); # Set payment_type throws_ok { $sale->purchase() } 'Koha::Exceptions::NoChanges', - 'Exception thrown if `add_item` is not called before `purchase`'; + 'Exception thrown if `add_item` is not called before `purchase`'; $sale->add_item( { code => 'COPYRANDOM', price => 1.00, quantity => 1 } ); $sale->add_item( { code => 'CARDRANDOM', price => 2.00, quantity => 2 } ); @@ -230,23 +221,25 @@ subtest 'purchase tests' => sub { $sale->{payment_type} = undef; # Flush payment_type cache in object my $credit; - ok( $credit = $sale->purchase( { payment_type => 'CASH' } ), - "No exception when payment_type passed" ); + ok( + $credit = $sale->purchase( { payment_type => 'CASH' } ), + "No exception when payment_type passed" + ); - is(ref($credit), 'Koha::Account::Line', "Koha::Account::Line returned"); - ok($credit->is_credit, "return is a credit for payment"); - is($credit->credit_type_code, 'PURCHASE', "credit_type_code set correctly to 'PURCHASE' for payment"); - is($credit->amount * 1, -5, "amount is calculated correctly for payment"); - is($credit->amountoutstanding * 1, 0, "amountoutstanding is set to zero for payment"); - is($credit->manager_id, $staff->borrowernumber, "manager_id set correctionly for payment"); - is($credit->register_id, $cash_register->id, "register_id set correctly for payment"); - is($credit->payment_type, 'CASH', "payment_type set correctly for payment"); + is( ref($credit), 'Koha::Account::Line', "Koha::Account::Line returned" ); + ok( $credit->is_credit, "return is a credit for payment" ); + is( $credit->credit_type_code, 'PURCHASE', "credit_type_code set correctly to 'PURCHASE' for payment" ); + is( $credit->amount * 1, -5, "amount is calculated correctly for payment" ); + is( $credit->amountoutstanding * 1, 0, "amountoutstanding is set to zero for payment" ); + is( $credit->manager_id, $staff->borrowernumber, "manager_id set correctionly for payment" ); + is( $credit->register_id, $cash_register->id, "register_id set correctly for payment" ); + is( $credit->payment_type, 'CASH', "payment_type set correctly for payment" ); - my $offsets = Koha::Account::Offsets->search({credit_id => $credit->accountlines_id}); - is($offsets->count, 3, "One offset was added for each item added"); # 2 items + 1 purchase + my $offsets = Koha::Account::Offsets->search( { credit_id => $credit->accountlines_id } ); + is( $offsets->count, 3, "One offset was added for each item added" ); # 2 items + 1 purchase -#ensure relevant fields are set -#ensure register_id is only ever set with a corresponding payment_type having been set + #ensure relevant fields are set + #ensure register_id is only ever set with a corresponding payment_type having been set $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/Koha/Checkout.t b/t/db_dependent/Koha/Checkout.t index cb27ff90c4..4693863adf 100755 --- a/t/db_dependent/Koha/Checkout.t +++ b/t/db_dependent/Koha/Checkout.t @@ -69,13 +69,17 @@ subtest 'overdue_fines' => sub { )->store(); my $overdue_fines = $checkout->overdue_fines; - is( ref($overdue_fines), 'Koha::Account::Lines', - 'Koha::Checkout->overdue_fines should return a Koha::Account::Lines' ); - is( $overdue_fines->count, 1, "Koha::Checkout->overdue_fines returns only overdue fines"); + is( + ref($overdue_fines), 'Koha::Account::Lines', + 'Koha::Checkout->overdue_fines should return a Koha::Account::Lines' + ); + is( $overdue_fines->count, 1, "Koha::Checkout->overdue_fines returns only overdue fines" ); my $overdue = $overdue_fines->next; - is( ref($overdue), 'Koha::Account::Line', - 'next returns a Koha::Account::Line' ); + is( + ref($overdue), 'Koha::Account::Line', + 'next returns a Koha::Account::Line' + ); is( $overdueline->id, @@ -92,17 +96,15 @@ subtest 'library() tests' => sub { $schema->storage->txn_begin; - my $library = $builder->build_object({ class => 'Koha::Libraries' }); + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); my $checkout = $builder->build_object( { class => 'Koha::Checkouts', - value => { - branchcode => $library->branchcode - } + value => { branchcode => $library->branchcode } } ); - is( ref($checkout->library), 'Koha::Library', 'Object type is correct' ); + is( ref( $checkout->library ), 'Koha::Library', 'Object type is correct' ); is( $checkout->library->branchcode, $library->branchcode, 'Right library linked' ); $schema->storage->txn_rollback; @@ -113,11 +115,7 @@ subtest 'renewals() tests' => sub { plan tests => 2; $schema->storage->txn_begin; - my $checkout = $builder->build_object( - { - class => 'Koha::Checkouts' - } - ); + my $checkout = $builder->build_object( { class => 'Koha::Checkouts' } ); my $renewal1 = $builder->build_object( { class => 'Koha::Checkouts::Renewals', @@ -131,8 +129,8 @@ subtest 'renewals() tests' => sub { } ); - is( ref($checkout->renewals), 'Koha::Checkouts::Renewals', 'Object set type is correct' ); - is( $checkout->renewals->count, 2, "Count of renewals is correct" ); + is( ref( $checkout->renewals ), 'Koha::Checkouts::Renewals', 'Object set type is correct' ); + is( $checkout->renewals->count, 2, "Count of renewals is correct" ); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/Koha/Checkouts.t b/t/db_dependent/Koha/Checkouts.t index deb166fdba..844880d777 100755 --- a/t/db_dependent/Koha/Checkouts.t +++ b/t/db_dependent/Koha/Checkouts.t @@ -24,7 +24,7 @@ use Test::MockModule; use Test::Warn; use C4::Circulation qw( MarkIssueReturned AddReturn ); -use C4::Reserves qw( AddReserve ); +use C4::Reserves qw( AddReserve ); use Koha::Checkouts; use Koha::Database; use Koha::DateUtils qw( dt_from_string ); @@ -36,11 +36,9 @@ use t::lib::Mocks; my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; -my $builder = t::lib::TestBuilder->new; -my $library = $builder->build( { source => 'Branch' } ); -my $patron = $builder->build( - { source => 'Borrower', value => { branchcode => $library->{branchcode} } } -); +my $builder = t::lib::TestBuilder->new; +my $library = $builder->build( { source => 'Branch' } ); +my $patron = $builder->build( { source => 'Borrower', value => { branchcode => $library->{branchcode} } } ); my $item_1 = $builder->build_sample_item; my $item_2 = $builder->build_sample_item; my $nb_of_checkouts = Koha::Checkouts->search->count; @@ -59,8 +57,10 @@ my $new_checkout_2 = Koha::Checkout->new( } )->store; -like( $new_checkout_1->issue_id, qr|^\d+$|, - 'Adding a new checkout should have set the issue_id' ); +like( + $new_checkout_1->issue_id, qr|^\d+$|, + 'Adding a new checkout should have set the issue_id' +); is( Koha::Checkouts->search->count, $nb_of_checkouts + 2, @@ -82,36 +82,50 @@ subtest 'is_overdue' => sub { my $tomorrow = dt_from_string->add( days => 1 ); $retrieved_checkout_1->date_due($ten_days_ago)->store; - is( $retrieved_checkout_1->is_overdue, - 1, 'The item should have been returned 10 days ago' ); + is( + $retrieved_checkout_1->is_overdue, + 1, 'The item should have been returned 10 days ago' + ); $retrieved_checkout_1->date_due($ten_days_later)->store; is( $retrieved_checkout_1->is_overdue, 0, 'The item is due in 10 days' ); $retrieved_checkout_1->date_due($tomorrow)->store; - is( $retrieved_checkout_1->is_overdue($ten_days_later), - 1, 'The item should have been returned yesterday' ); + is( + $retrieved_checkout_1->is_overdue($ten_days_later), + 1, 'The item should have been returned yesterday' + ); $retrieved_checkout_1->date_due($yesterday)->store; - is( $retrieved_checkout_1->is_overdue($ten_days_ago), - 0, 'Ten days ago the item due yesterday was not late' ); + is( + $retrieved_checkout_1->is_overdue($ten_days_ago), + 0, 'Ten days ago the item due yesterday was not late' + ); $retrieved_checkout_1->date_due($tomorrow)->store; - is( $retrieved_checkout_1->is_overdue($ten_days_later), - 1, 'In Ten days, the item due tomorrow will be late' ); + is( + $retrieved_checkout_1->is_overdue($ten_days_later), + 1, 'In Ten days, the item due tomorrow will be late' + ); $retrieved_checkout_1->date_due($yesterday)->store; - is( $retrieved_checkout_1->is_overdue($ten_days_ago), - 0, 'In Ten days, the item due yesterday will still be late' ); + is( + $retrieved_checkout_1->is_overdue($ten_days_ago), + 0, 'In Ten days, the item due yesterday will still be late' + ); }; subtest 'item' => sub { plan tests => 2; my $item = $retrieved_checkout_1->item; - is( ref($item), 'Koha::Item', - 'Koha::Checkout->item should return a Koha::Item' ); - is( $item->itemnumber, $item_1->itemnumber, - 'Koha::Checkout->item should return the correct item' ); + is( + ref($item), 'Koha::Item', + 'Koha::Checkout->item should return a Koha::Item' + ); + is( + $item->itemnumber, $item_1->itemnumber, + 'Koha::Checkout->item should return the correct item' + ); }; subtest 'account_lines' => sub { @@ -133,12 +147,16 @@ subtest 'account_lines' => sub { )->store(); my $account_lines = $retrieved_checkout_1->account_lines; - is( ref($account_lines), 'Koha::Account::Lines', - 'Koha::Checkout->account_lines should return a Koha::Account::Lines' ); + is( + ref($account_lines), 'Koha::Account::Lines', + 'Koha::Checkout->account_lines should return a Koha::Account::Lines' + ); my $line = $account_lines->next; - is( ref($line), 'Koha::Account::Line', - 'next returns a Koha::Account::Line' ); + is( + ref($line), 'Koha::Account::Line', + 'next returns a Koha::Account::Line' + ); is( $accountline->id, @@ -168,19 +186,26 @@ subtest 'patron' => sub { t::lib::Mocks::mock_userenv( { branchcode => $library->{branchcode} } ); my $p = $checkout->patron; - is( ref($p), 'Koha::Patron', - 'Koha::Checkout->patron should return a Koha::Patron' ); - is( $p->borrowernumber, $patron->borrowernumber, - 'Koha::Checkout->patron should return the correct patron' ); + is( + ref($p), 'Koha::Patron', + 'Koha::Checkout->patron should return a Koha::Patron' + ); + is( + $p->borrowernumber, $patron->borrowernumber, + 'Koha::Checkout->patron should return the correct patron' + ); # Testing Koha::Old::Checkout->patron now my $issue_id = $checkout->issue_id; - C4::Circulation::MarkIssueReturned( $p->borrowernumber, - $checkout->itemnumber ); + C4::Circulation::MarkIssueReturned( + $p->borrowernumber, + $checkout->itemnumber + ); $p->delete; my $old_issue = Koha::Old::Checkouts->find($issue_id); - is( $old_issue->patron, undef, -'Koha::Checkout->patron should return undef if the patron record has been deleted' + is( + $old_issue->patron, undef, + 'Koha::Checkout->patron should return undef if the patron record has been deleted' ); }; @@ -217,19 +242,26 @@ subtest 'issuer' => sub { )->store; my $i = $checkout->issuer; - is( ref($i), 'Koha::Patron', - 'Koha::Checkout->issuer should return a Koha::Patron' ); - is( $i->borrowernumber, $issuer->borrowernumber, - 'Koha::Checkout->issuer should return the correct patron' ); + is( + ref($i), 'Koha::Patron', + 'Koha::Checkout->issuer should return a Koha::Patron' + ); + is( + $i->borrowernumber, $issuer->borrowernumber, + 'Koha::Checkout->issuer should return the correct patron' + ); # Testing Koha::Old::Checkout->patron now my $issue_id = $checkout->issue_id; - C4::Circulation::MarkIssueReturned( $patron->borrowernumber, - $checkout->itemnumber ); + C4::Circulation::MarkIssueReturned( + $patron->borrowernumber, + $checkout->itemnumber + ); $i->delete; my $old_issue = Koha::Old::Checkouts->find($issue_id); - is( $old_issue->issuer_id, undef, -'Koha::Checkout->issuer_id should return undef if the patron record has been deleted' + is( + $old_issue->issuer_id, undef, + 'Koha::Checkout->issuer_id should return undef if the patron record has been deleted' ); }; @@ -255,11 +287,12 @@ subtest 'Koha::Old::Checkouts->filter_by_todays_checkins' => sub { ); my @checkouts; + # Create 7 checkouts for ( 0 .. 6 ) { my $item = $builder->build_sample_item; push @checkouts, - Koha::Checkout->new( + Koha::Checkout->new( { borrowernumber => $patron->borrowernumber, itemnumber => $item->itemnumber, @@ -274,16 +307,17 @@ subtest 'Koha::Old::Checkouts->filter_by_todays_checkins' => sub { my $checkout = $checkouts[$i]; C4::Circulation::AddReturn( $checkout->item->barcode, $library->{branchcode}, - undef, $not_today->set_hour( int( rand(24) ) ) + undef, $not_today->set_hour( int( rand(24) ) ) ); } + # Checkin 4 today my $today = dt_from_string; for my $i ( 3 .. 6 ) { my $checkout = $checkouts[$i]; C4::Circulation::AddReturn( $checkout->item->barcode, $library->{branchcode}, - undef, $today->set_hour( int( rand(24) ) ) + undef, $today->set_hour( int( rand(24) ) ) ); } @@ -308,18 +342,10 @@ subtest 'automatic_checkin' => sub { my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); - my $due_ac_item = - $builder->build_sample_item( - { homebranch => $patron->branchcode, itemlost => 0 } ); - my $ac_item = - $builder->build_sample_item( - { homebranch => $patron->branchcode, itemlost => 0 } ); - my $odue_ac_item = - $builder->build_sample_item( - { homebranch => $patron->branchcode, itemlost => 0 } ); - my $normal_item = - $builder->build_sample_item( - { homebranch => $patron->branchcode, itemlost => 0 } ); + my $due_ac_item = $builder->build_sample_item( { homebranch => $patron->branchcode, itemlost => 0 } ); + my $ac_item = $builder->build_sample_item( { homebranch => $patron->branchcode, itemlost => 0 } ); + my $odue_ac_item = $builder->build_sample_item( { homebranch => $patron->branchcode, itemlost => 0 } ); + my $normal_item = $builder->build_sample_item( { homebranch => $patron->branchcode, itemlost => 0 } ); $due_ac_item->itemtype->automatic_checkin(1)->store; $odue_ac_item->itemtype->automatic_checkin(1)->store; @@ -371,12 +397,16 @@ subtest 'automatic_checkin' => sub { )->store; my $searched = Koha::Checkouts->find( $checkout_ni->issue_id ); - is( $searched->issue_id, $checkout_ni->issue_id, - 'checkout for normal_item exists' ); + is( + $searched->issue_id, $checkout_ni->issue_id, + 'checkout for normal_item exists' + ); $searched = Koha::Checkouts->find( $checkout_aci->issue_id ); - is( $searched->issue_id, $checkout_aci->issue_id, - 'checkout for ac_item exists' ); + is( + $searched->issue_id, $checkout_aci->issue_id, + 'checkout for ac_item exists' + ); $searched = Koha::Checkouts->find( $checkout_due_aci->issue_id ); is( @@ -395,12 +425,16 @@ subtest 'automatic_checkin' => sub { Koha::Checkouts->automatic_checkin; $searched = Koha::Checkouts->find( $checkout_ni->issue_id ); - is( $searched->issue_id, $checkout_ni->issue_id, - 'checkout for normal_item still exists' ); + is( + $searched->issue_id, $checkout_ni->issue_id, + 'checkout for normal_item still exists' + ); $searched = Koha::Checkouts->find( $checkout_aci->issue_id ); - is( $searched->issue_id, $checkout_aci->issue_id, - 'checkout for ac_item still exists' ); + is( + $searched->issue_id, $checkout_aci->issue_id, + 'checkout for ac_item still exists' + ); $searched = Koha::Checkouts->find( $checkout_due_aci->issue_id ); is( $searched, undef, 'checkout for due_ac_item doesn\'t exist anymore' ); @@ -409,8 +443,10 @@ subtest 'automatic_checkin' => sub { is( $searched, undef, 'checkout for odue_ac_item doesn\'t exist anymore' ); $searched = Koha::Old::Checkouts->find( $checkout_odue_aci->issue_id ); - is( dt_from_string($searched->returndate), $yesterday, 'old checkout for odue_ac_item has the right return date' ); - + is( + dt_from_string( $searched->returndate ), $yesterday, + 'old checkout for odue_ac_item has the right return date' + ); subtest 'automatic_checkin AutomaticCheckinAutoFill tests' => sub { diff --git a/t/db_dependent/Koha/Checkouts/Renewal.t b/t/db_dependent/Koha/Checkouts/Renewal.t index 9e1a42a3dc..c28833ff79 100755 --- a/t/db_dependent/Koha/Checkouts/Renewal.t +++ b/t/db_dependent/Koha/Checkouts/Renewal.t @@ -66,7 +66,7 @@ subtest "store() tests" => sub { Koha::Checkouts::Renewal->new( { interface => 'intranet' } )->store() } 'Koha::Exceptions::Object::FKConstraint', - 'Exception thrown if no checkout_id is passed on creation'; + 'Exception thrown if no checkout_id is passed on creation'; my $renewal = Koha::Checkouts::Renewal->new( { @@ -78,8 +78,7 @@ subtest "store() tests" => sub { is( ref($renewal), 'Koha::Checkouts::Renewal', 'Object type is correct' ); is( - Koha::Checkouts::Renewals->search( { checkout_id => $checkout->id } ) - ->count, + Koha::Checkouts::Renewals->search( { checkout_id => $checkout->id } )->count, 1, 'Renewal stored on the DB' ); @@ -88,9 +87,8 @@ subtest "store() tests" => sub { local *STDERR; open STDERR, '>', '/dev/null'; - my $another_checkout = - $builder->build_object( { class => 'Koha::Checkouts' } ); - my $checkout_id = $another_checkout->id; + my $another_checkout = $builder->build_object( { class => 'Koha::Checkouts' } ); + my $checkout_id = $another_checkout->id; $another_checkout->delete; my $THE_renewal; @@ -104,7 +102,7 @@ subtest "store() tests" => sub { )->store; } 'Koha::Exceptions::Object::FKConstraint', - 'An exception is thrown on invalid checkout_id'; + 'An exception is thrown on invalid checkout_id'; close STDERR; is( $@->broken_fk, 'checkout_id', 'Exception field is correct' ); @@ -142,19 +140,23 @@ subtest 'renewer() tests' => sub { )->store; my $renewal_renewer_patron = $renewal->renewer; - is( ref($renewal_renewer_patron), + is( + ref($renewal_renewer_patron), 'Koha::Patron', - 'Koha::Checkouts::Renewal->renewer should return a Koha::Patron' ); - is( $renewal->renewer_id, $renewal_renewer_patron->borrowernumber, + 'Koha::Checkouts::Renewal->renewer should return a Koha::Patron' + ); + is( + $renewal->renewer_id, $renewal_renewer_patron->borrowernumber, 'Koha::Checkouts::Renewal->renewer should return the correct borrower' ); my $checkout_id = $checkout->id; $librarian->delete; - my $renewals = - Koha::Checkouts::Renewals->search( { checkout_id => $checkout_id } ); - is( $renewals->count, 1, - 'Koha::Checkouts::Renewal is not deleted on librarian deletion' ); + my $renewals = Koha::Checkouts::Renewals->search( { checkout_id => $checkout_id } ); + is( + $renewals->count, 1, + 'Koha::Checkouts::Renewal is not deleted on librarian deletion' + ); $schema->storage->txn_rollback; }; @@ -188,23 +190,28 @@ subtest 'checkout() tests' => sub { )->store; my $renewal_checkout = $renewal->checkout; - is( ref($renewal_checkout), 'Koha::Checkout', - 'Koha::Checkouts::Renewal->checkout should return a Koha::Checkout' ); - is( $renewal->checkout_id, $renewal_checkout->id, + is( + ref($renewal_checkout), 'Koha::Checkout', + 'Koha::Checkouts::Renewal->checkout should return a Koha::Checkout' + ); + is( + $renewal->checkout_id, $renewal_checkout->id, 'Koha::Checkouts::Renewal->checkout should return the correct checkout' ); my $issue_id = $checkout->issue_id; $checkout->delete; - my $renewals = - Koha::Checkouts::Renewals->search( { checkout_id => $issue_id } ); - is( $renewals->count, 1, - 'Koha::Checkouts::Renewal remains on checkout deletion' ); + my $renewals = Koha::Checkouts::Renewals->search( { checkout_id => $issue_id } ); + is( + $renewals->count, 1, + 'Koha::Checkouts::Renewal remains on checkout deletion' + ); $renewal->discard_changes; - is( $renewal->checkout, undef, -'Koha::Checkouts::Renewal->checkout should return undef if checkout has been deleted' + is( + $renewal->checkout, undef, + 'Koha::Checkouts::Renewal->checkout should return undef if checkout has been deleted' ); $schema->storage->txn_rollback; @@ -239,26 +246,30 @@ subtest 'old_checkout() tests' => sub { )->store; my $renewal_old_checkout = $renewal->old_checkout; - is( ref($renewal_old_checkout), 'Koha::Old::Checkout', -'Koha::Checkouts::Renewal->old_checkout should return a Koha::Old::Checkout' + is( + ref($renewal_old_checkout), 'Koha::Old::Checkout', + 'Koha::Checkouts::Renewal->old_checkout should return a Koha::Old::Checkout' ); - is( $renewal->checkout_id, $renewal_old_checkout->id, -'Koha::Checkouts::Renewal->old_checkout should return the correct old checkout' + is( + $renewal->checkout_id, $renewal_old_checkout->id, + 'Koha::Checkouts::Renewal->old_checkout should return the correct old checkout' ); my $issue_id = $old_checkout->issue_id; $old_checkout->delete; - my $renewals = - Koha::Checkouts::Renewals->search( { checkout_id => $issue_id } ); - is( $renewals->count, 1, - 'Koha::Checkouts::Renewal remains on old_checkout deletion' ); + my $renewals = Koha::Checkouts::Renewals->search( { checkout_id => $issue_id } ); + is( + $renewals->count, 1, + 'Koha::Checkouts::Renewal remains on old_checkout deletion' + ); # FIXME: Should we actually set null on OldCheckout deletion? $renewal->discard_changes; - is( $renewal->old_checkout, undef, -'Koha::Checkouts::Renewal->old_checkout should return undef if old_checkout has been deleted' + is( + $renewal->old_checkout, undef, + 'Koha::Checkouts::Renewal->old_checkout should return undef if old_checkout has been deleted' ); $schema->storage->txn_rollback; diff --git a/t/db_dependent/Koha/Checkouts/ReturnClaim.t b/t/db_dependent/Koha/Checkouts/ReturnClaim.t index 5d5ebda400..62571c3588 100755 --- a/t/db_dependent/Koha/Checkouts/ReturnClaim.t +++ b/t/db_dependent/Koha/Checkouts/ReturnClaim.t @@ -35,8 +35,8 @@ subtest "store() tests" => sub { $schema->storage->txn_begin; - my $librarian = $builder->build_object({ class => 'Koha::Patrons' }); - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $librarian = $builder->build_object( { class => 'Koha::Patrons' } ); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $item = $builder->build_sample_item; my $checkout = $builder->build_object( @@ -50,16 +50,17 @@ subtest "store() tests" => sub { } ); - throws_ok - { Koha::Checkouts::ReturnClaim->new( + throws_ok { + Koha::Checkouts::ReturnClaim->new( { issue_id => $checkout->id, itemnumber => $checkout->itemnumber, borrowernumber => $checkout->borrowernumber, notes => 'Some notes' } - )->store } - 'Koha::Exceptions::Checkouts::ReturnClaims::NoCreatedBy', + )->store + } + 'Koha::Exceptions::Checkouts::ReturnClaims::NoCreatedBy', 'Exception thrown if no created_by passed on creation'; my $old_checkout = $builder->build_object( @@ -89,12 +90,12 @@ subtest "store() tests" => sub { is( $nullable_created_by->created_by, undef, 'Deletion was deleted' ); ok( $nullable_created_by->in_storage, 'In storage' ); is( - ref($nullable_created_by->notes('Some other note')->store), + ref( $nullable_created_by->notes('Some other note')->store ), 'Koha::Checkouts::ReturnClaim', 'Subsequent store succeeds after created_by has been unset' ); - is( Koha::Checkouts::ReturnClaims->search({ issue_id => $checkout->id })->count, 0, 'No claims stored' ); + is( Koha::Checkouts::ReturnClaims->search( { issue_id => $checkout->id } )->count, 0, 'No claims stored' ); my $claim = Koha::Checkouts::ReturnClaim->new( { @@ -106,8 +107,8 @@ subtest "store() tests" => sub { } )->store; - is( ref($claim), 'Koha::Checkouts::ReturnClaim', 'Object type is correct' ); - is( Koha::Checkouts::ReturnClaims->search( { issue_id => $checkout->id } )->count, 1, 'Claim stored on the DB'); + is( ref($claim), 'Koha::Checkouts::ReturnClaim', 'Object type is correct' ); + is( Koha::Checkouts::ReturnClaims->search( { issue_id => $checkout->id } )->count, 1, 'Claim stored on the DB' ); $schema->storage->txn_rollback; }; @@ -119,9 +120,9 @@ subtest "resolve() tests" => sub { $schema->storage->txn_begin; my $itemlost = 1; - my $librarian = $builder->build_object({ class => 'Koha::Patrons' }); - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); - my $item = $builder->build_sample_item({ itemlost => $itemlost }); + my $librarian = $builder->build_object( { class => 'Koha::Patrons' } ); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + my $item = $builder->build_sample_item( { itemlost => $itemlost } ); my $checkout = $builder->build_object( { @@ -144,27 +145,24 @@ subtest "resolve() tests" => sub { } )->store; - throws_ok - { $claim->resolve({ resolution => 1 }); } - 'Koha::Exceptions::MissingParameter', + throws_ok { $claim->resolve( { resolution => 1 } ); } + 'Koha::Exceptions::MissingParameter', "Not passing 'resolved_by' makes it throw an exception"; - throws_ok - { $claim->resolve({ resolved_by => 1 }); } - 'Koha::Exceptions::MissingParameter', + throws_ok { $claim->resolve( { resolved_by => 1 } ); } + 'Koha::Exceptions::MissingParameter', "Not passing 'resolution' makes it throw an exception"; - my $deleted_patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $deleted_patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $deleted_patron_id = $deleted_patron->id; $deleted_patron->delete; - { # hide useless warnings + { # hide useless warnings local *STDERR; open STDERR, '>', '/dev/null'; - throws_ok - { $claim->resolve({ resolution => "X", resolved_by => $deleted_patron_id }) } - 'Koha::Exceptions::Object::FKConstraint', + throws_ok { $claim->resolve( { resolution => "X", resolved_by => $deleted_patron_id } ) } + 'Koha::Exceptions::Object::FKConstraint', "Exception thrown on invalid resolver"; close STDERR; @@ -181,7 +179,10 @@ subtest "resolve() tests" => sub { } )->discard_changes; - is( output_pref( { str => $claim->resolved_on } ), output_pref( { dt => $tomorrow } ), 'resolved_on set to the passed param' ); + is( + output_pref( { str => $claim->resolved_on } ), output_pref( { dt => $tomorrow } ), + 'resolved_on set to the passed param' + ); is( $claim->updated_by, $librarian->id, 'updated_by set to the passed resolved_by' ); # Make sure $item is refreshed @@ -222,7 +223,10 @@ subtest "resolve() tests" => sub { } )->discard_changes; - is( output_pref( { str => $claim->resolved_on } ), output_pref( { dt => $tomorrow } ), 'resolved_on set to the passed param' ); + is( + output_pref( { str => $claim->resolved_on } ), output_pref( { dt => $tomorrow } ), + 'resolved_on set to the passed param' + ); is( $claim->updated_by, $librarian->id, 'updated_by set to the passed resolved_by' ); # Make sure $item is refreshed @@ -274,10 +278,10 @@ subtest 'item() tests' => sub { $schema->storage->txn_begin; - my $librarian = $builder->build_object({ class => 'Koha::Patrons' }); - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $librarian = $builder->build_object( { class => 'Koha::Patrons' } ); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $item = $builder->build_sample_item; - my $checkout = $builder->build_object( + my $checkout = $builder->build_object( { class => 'Koha::Checkouts', value => { @@ -299,14 +303,17 @@ subtest 'item() tests' => sub { )->store; my $return_claim_item = $claim->item; - is( ref( $return_claim_item ), 'Koha::Item', 'Koha::Checkouts::ReturnClaim->item should return a Koha::Item' ); - is( $claim->itemnumber, $return_claim_item->itemnumber, 'Koha::Checkouts::ReturnClaim->item should return the correct item' ); + is( ref($return_claim_item), 'Koha::Item', 'Koha::Checkouts::ReturnClaim->item should return a Koha::Item' ); + is( + $claim->itemnumber, $return_claim_item->itemnumber, + 'Koha::Checkouts::ReturnClaim->item should return the correct item' + ); my $itemnumber = $item->itemnumber; - $checkout->delete; # Required to allow deletion of item + $checkout->delete; # Required to allow deletion of item $item->delete; - my $claims = Koha::Checkouts::ReturnClaims->search({ itemnumber => $itemnumber }); + my $claims = Koha::Checkouts::ReturnClaims->search( { itemnumber => $itemnumber } ); is( $claims->count, 0, 'Koha::Checkouts::ReturnClaim is deleted on item deletion' ); $schema->storage->txn_rollback; @@ -318,10 +325,10 @@ subtest 'patron() tests' => sub { $schema->storage->txn_begin; - my $librarian = $builder->build_object({ class => 'Koha::Patrons' }); - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $librarian = $builder->build_object( { class => 'Koha::Patrons' } ); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $item = $builder->build_sample_item; - my $checkout = $builder->build_object( + my $checkout = $builder->build_object( { class => 'Koha::Checkouts', value => { @@ -343,14 +350,20 @@ subtest 'patron() tests' => sub { )->store; my $return_claim_patron = $claim->patron; - is( ref( $return_claim_patron ), 'Koha::Patron', 'Koha::Checkouts::ReturnClaim->patron should return a Koha::Patron' ); - is( $claim->borrowernumber, $return_claim_patron->borrowernumber, 'Koha::Checkouts::ReturnClaim->patron should return the correct borrower' ); + is( + ref($return_claim_patron), 'Koha::Patron', + 'Koha::Checkouts::ReturnClaim->patron should return a Koha::Patron' + ); + is( + $claim->borrowernumber, $return_claim_patron->borrowernumber, + 'Koha::Checkouts::ReturnClaim->patron should return the correct borrower' + ); my $borrowernumber = $patron->borrowernumber; - $checkout->delete; # Required to allow deletion of patron + $checkout->delete; # Required to allow deletion of patron $patron->delete; - my $claims = Koha::Checkouts::ReturnClaims->search({ borrowernumber => $borrowernumber }); + my $claims = Koha::Checkouts::ReturnClaims->search( { borrowernumber => $borrowernumber } ); is( $claims->count, 0, 'Koha::Checkouts::ReturnClaim is deleted on borrower deletion' ); $schema->storage->txn_rollback; @@ -362,9 +375,9 @@ subtest 'old_checkout() tests' => sub { $schema->storage->txn_begin; - my $librarian = $builder->build_object({ class => 'Koha::Patrons' }); - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); - my $item = $builder->build_sample_item; + my $librarian = $builder->build_object( { class => 'Koha::Patrons' } ); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + my $item = $builder->build_sample_item; my $old_checkout = $builder->build_object( { class => 'Koha::Old::Checkouts', @@ -387,18 +400,28 @@ subtest 'old_checkout() tests' => sub { )->store; my $return_claim_old_checkout = $claim->old_checkout; - is( ref( $return_claim_old_checkout ), 'Koha::Old::Checkout', 'Koha::Checkouts::ReturnClaim->old_checkout should return a Koha::Old::Checkout' ); - is( $claim->issue_id, $return_claim_old_checkout->issue_id, 'Koha::Checkouts::ReturnClaim->old_checkout should return the correct borrower' ); + is( + ref($return_claim_old_checkout), 'Koha::Old::Checkout', + 'Koha::Checkouts::ReturnClaim->old_checkout should return a Koha::Old::Checkout' + ); + is( + $claim->issue_id, $return_claim_old_checkout->issue_id, + 'Koha::Checkouts::ReturnClaim->old_checkout should return the correct borrower' + ); my $issue_id = $old_checkout->issue_id; $old_checkout->delete; - my $claims = Koha::Checkouts::ReturnClaims->search({ issue_id => $issue_id }); + my $claims = Koha::Checkouts::ReturnClaims->search( { issue_id => $issue_id } ); is( $claims->count, 1, 'Koha::Checkouts::ReturnClaim remains on old_checkout deletion' ); + # FIXME: Should we actually set null on OldCheckout deletion? $claim->issue_id(undef)->store; - is( $claim->old_checkout, undef, 'Koha::Checkouts::ReturnClaim->old_checkout should return undef if no old_checkout linked' ); + is( + $claim->old_checkout, undef, + 'Koha::Checkouts::ReturnClaim->old_checkout should return undef if no old_checkout linked' + ); $schema->storage->txn_rollback; }; @@ -409,10 +432,10 @@ subtest 'checkout() tests' => sub { $schema->storage->txn_begin; - my $librarian = $builder->build_object({ class => 'Koha::Patrons' }); - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $librarian = $builder->build_object( { class => 'Koha::Patrons' } ); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $item = $builder->build_sample_item; - my $checkout = $builder->build_object( + my $checkout = $builder->build_object( { class => 'Koha::Checkouts', value => { @@ -434,13 +457,19 @@ subtest 'checkout() tests' => sub { )->store; my $return_claim_checkout = $claim->checkout; - is( ref( $return_claim_checkout ), 'Koha::Checkout', 'Koha::Checkouts::ReturnClaim->checkout should return a Koha::Checkout' ); - is( $claim->issue_id, $return_claim_checkout->issue_id, 'Koha::Checkouts::ReturnClaim->checkout should return the correct borrower' ); + is( + ref($return_claim_checkout), 'Koha::Checkout', + 'Koha::Checkouts::ReturnClaim->checkout should return a Koha::Checkout' + ); + is( + $claim->issue_id, $return_claim_checkout->issue_id, + 'Koha::Checkouts::ReturnClaim->checkout should return the correct borrower' + ); my $issue_id = $checkout->issue_id; $checkout->delete; - my $claims = Koha::Checkouts::ReturnClaims->search({ issue_id => $issue_id }); + my $claims = Koha::Checkouts::ReturnClaims->search( { issue_id => $issue_id } ); is( $claims->count, 1, 'Koha::Checkouts::ReturnClaim remains on checkout deletion' ); $claim->issue_id(undef)->store; diff --git a/t/db_dependent/Koha/CirculationRules.t b/t/db_dependent/Koha/CirculationRules.t index 928fe6104b..dbac7133e3 100755 --- a/t/db_dependent/Koha/CirculationRules.t +++ b/t/db_dependent/Koha/CirculationRules.t @@ -31,7 +31,7 @@ use t::lib::Mocks; use t::lib::TestBuilder; use Koha::Cache::Memory::Lite; -my $schema = Koha::Database->new->schema; +my $schema = Koha::Database->new->schema; my $builder = t::lib::TestBuilder->new; subtest 'get_effective_issuing_rule' => sub { @@ -39,9 +39,9 @@ subtest 'get_effective_issuing_rule' => sub { $schema->storage->txn_begin; - my $categorycode = $builder->build({ source => 'Category' })->{'categorycode'}; - my $itemtype = $builder->build({ source => 'Itemtype' })->{'itemtype'}; - my $branchcode = $builder->build({ source => 'Branch' })->{'branchcode'}; + my $categorycode = $builder->build( { source => 'Category' } )->{'categorycode'}; + my $itemtype = $builder->build( { source => 'Itemtype' } )->{'itemtype'}; + my $branchcode = $builder->build( { source => 'Branch' } )->{'branchcode'}; subtest 'Call with undefined values' => sub { plan tests => 5; @@ -49,19 +49,22 @@ subtest 'get_effective_issuing_rule' => sub { my $rule; Koha::CirculationRules->delete; - is(Koha::CirculationRules->search->count, 0, 'There are no issuing rules.'); - # undef, undef, undef => 1 - $rule = Koha::CirculationRules->get_effective_rule({ - branchcode => undef, - categorycode => undef, - itemtype => undef, - rule_name => 'fine', - rule_value => 1, - }); - is($rule, undef, 'When I attempt to get effective issuing rule by' - .' providing undefined values, then undef is returned.'); + is( Koha::CirculationRules->search->count, 0, 'There are no issuing rules.' ); - # undef, undef, undef => 2 + # undef, undef, undef => 1 + $rule = Koha::CirculationRules->get_effective_rule( + { + branchcode => undef, + categorycode => undef, + itemtype => undef, + rule_name => 'fine', + rule_value => 1, + } + ); + is( $rule, undef, 'When I attempt to get effective issuing rule by' + . ' providing undefined values, then undef is returned.' ); + + # undef, undef, undef => 2 ok( Koha::CirculationRule->new( { @@ -71,15 +74,17 @@ subtest 'get_effective_issuing_rule' => sub { rule_name => 'fine', rule_value => 2, } - )->store, - 'Given I added an issuing rule branchcode => undef,' - .' categorycode => undef, itemtype => undef,'); - $rule = Koha::CirculationRules->get_effective_rule({ - branchcode => undef, - categorycode => undef, - itemtype => undef, - rule_name => 'fine', - }); + )->store, + 'Given I added an issuing rule branchcode => undef,' . ' categorycode => undef, itemtype => undef,' + ); + $rule = Koha::CirculationRules->get_effective_rule( + { + branchcode => undef, + categorycode => undef, + itemtype => undef, + rule_name => 'fine', + } + ); _is_row_match( $rule, { @@ -90,62 +95,94 @@ subtest 'get_effective_issuing_rule' => sub { rule_value => 2, }, 'When I attempt to get effective' - .' issuing rule by providing undefined values, then the above one is' - .' returned.' + . ' issuing rule by providing undefined values, then the above one is' + . ' returned.' ); }; subtest 'Performance' => sub { plan tests => 4; - my $worst_case = timethis(500, - sub { Koha::CirculationRules->get_effective_rule({ - branchcode => 'nonexistent', - categorycode => 'nonexistent', - itemtype => 'nonexistent', - rule_name => 'nonexistent', - }); + my $worst_case = timethis( + 500, + sub { + Koha::CirculationRules->get_effective_rule( + { + branchcode => 'nonexistent', + categorycode => 'nonexistent', + itemtype => 'nonexistent', + rule_name => 'nonexistent', } ); - my $mid_case = timethis(500, - sub { Koha::CirculationRules->get_effective_rule({ - branchcode => $branchcode, - categorycode => 'nonexistent', - itemtype => 'nonexistent', - rule_name => 'nonexistent', - }); + } + ); + my $mid_case = timethis( + 500, + sub { + Koha::CirculationRules->get_effective_rule( + { + branchcode => $branchcode, + categorycode => 'nonexistent', + itemtype => 'nonexistent', + rule_name => 'nonexistent', } ); - my $sec_best_case = timethis(500, - sub { Koha::CirculationRules->get_effective_rule({ - branchcode => $branchcode, - categorycode => $categorycode, - itemtype => 'nonexistent', - rule_name => 'nonexistent', - }); + } + ); + my $sec_best_case = timethis( + 500, + sub { + Koha::CirculationRules->get_effective_rule( + { + branchcode => $branchcode, + categorycode => $categorycode, + itemtype => 'nonexistent', + rule_name => 'nonexistent', } ); - my $best_case = timethis(500, - sub { Koha::CirculationRules->get_effective_rule({ - branchcode => $branchcode, - categorycode => $categorycode, - itemtype => $itemtype, - rule_name => 'nonexistent', - }); + } + ); + my $best_case = timethis( + 500, + sub { + Koha::CirculationRules->get_effective_rule( + { + branchcode => $branchcode, + categorycode => $categorycode, + itemtype => $itemtype, + rule_name => 'nonexistent', } ); - ok($worst_case, 'In worst case, get_effective_issuing_rule finds matching' - .' rule '.sprintf('%.2f', $worst_case->iters/$worst_case->cpu_a) - .' times per second.'); - ok($mid_case, 'In mid case, get_effective_issuing_rule finds matching' - .' rule '.sprintf('%.2f', $mid_case->iters/$mid_case->cpu_a) - .' times per second.'); - ok($sec_best_case, 'In second best case, get_effective_issuing_rule finds matching' - .' rule '.sprintf('%.2f', $sec_best_case->iters/$sec_best_case->cpu_a) - .' times per second.'); - ok($best_case, 'In best case, get_effective_issuing_rule finds matching' - .' rule '.sprintf('%.2f', $best_case->iters/$best_case->cpu_a) - .' times per second.'); + } + ); + ok( + $worst_case, + 'In worst case, get_effective_issuing_rule finds matching' + . ' rule ' + . sprintf( '%.2f', $worst_case->iters / $worst_case->cpu_a ) + . ' times per second.' + ); + ok( + $mid_case, + 'In mid case, get_effective_issuing_rule finds matching' + . ' rule ' + . sprintf( '%.2f', $mid_case->iters / $mid_case->cpu_a ) + . ' times per second.' + ); + ok( + $sec_best_case, + 'In second best case, get_effective_issuing_rule finds matching' + . ' rule ' + . sprintf( '%.2f', $sec_best_case->iters / $sec_best_case->cpu_a ) + . ' times per second.' + ); + ok( + $best_case, + 'In best case, get_effective_issuing_rule finds matching' + . ' rule ' + . sprintf( '%.2f', $best_case->iters / $best_case->cpu_a ) + . ' times per second.' + ); }; $schema->storage->txn_rollback; @@ -157,58 +194,83 @@ subtest 'set_rule' => sub { $schema->storage->txn_begin; - my $branchcode = $builder->build({ source => 'Branch' })->{'branchcode'}; - my $categorycode = $builder->build({ source => 'Category' })->{'categorycode'}; - my $itemtype = $builder->build({ source => 'Itemtype' })->{'itemtype'}; + my $branchcode = $builder->build( { source => 'Branch' } )->{'branchcode'}; + my $categorycode = $builder->build( { source => 'Category' } )->{'categorycode'}; + my $itemtype = $builder->build( { source => 'Itemtype' } )->{'itemtype'}; subtest 'Correct call' => sub { plan tests => 5; Koha::CirculationRules->delete; - lives_ok( sub { - Koha::CirculationRules->set_rule( { - branchcode => $branchcode, - rule_name => 'lostreturn', - rule_value => '', - } ); - }, 'setting lostreturn with branch' ); + lives_ok( + sub { + Koha::CirculationRules->set_rule( + { + branchcode => $branchcode, + rule_name => 'lostreturn', + rule_value => '', + } + ); + }, + 'setting lostreturn with branch' + ); - lives_ok( sub { - Koha::CirculationRules->set_rule( { - branchcode => $branchcode, - rule_name => 'processingreturn', - rule_value => '', - } ); - }, 'setting processingreturn with branch' ); + lives_ok( + sub { + Koha::CirculationRules->set_rule( + { + branchcode => $branchcode, + rule_name => 'processingreturn', + rule_value => '', + } + ); + }, + 'setting processingreturn with branch' + ); - lives_ok( sub { - Koha::CirculationRules->set_rule( { - branchcode => $branchcode, - categorycode => $categorycode, - rule_name => 'patron_maxissueqty', - rule_value => '', - } ); - }, 'setting patron_maxissueqty with branch/category succeeds' ); + lives_ok( + sub { + Koha::CirculationRules->set_rule( + { + branchcode => $branchcode, + categorycode => $categorycode, + rule_name => 'patron_maxissueqty', + rule_value => '', + } + ); + }, + 'setting patron_maxissueqty with branch/category succeeds' + ); - lives_ok( sub { - Koha::CirculationRules->set_rule( { - branchcode => $branchcode, - itemtype => $itemtype, - rule_name => 'holdallowed', - rule_value => '', - } ); - }, 'setting holdallowed with branch/itemtype succeeds' ); + lives_ok( + sub { + Koha::CirculationRules->set_rule( + { + branchcode => $branchcode, + itemtype => $itemtype, + rule_name => 'holdallowed', + rule_value => '', + } + ); + }, + 'setting holdallowed with branch/itemtype succeeds' + ); - lives_ok( sub { - Koha::CirculationRules->set_rule( { - branchcode => $branchcode, - categorycode => $categorycode, - itemtype => $itemtype, - rule_name => 'article_requests', - rule_value => '', - } ); - }, 'setting fine with branch/category/itemtype succeeds' ); + lives_ok( + sub { + Koha::CirculationRules->set_rule( + { + branchcode => $branchcode, + categorycode => $categorycode, + itemtype => $itemtype, + rule_name => 'article_requests', + rule_value => '', + } + ); + }, + 'setting fine with branch/category/itemtype succeeds' + ); }; subtest 'Call with missing params' => sub { @@ -216,44 +278,74 @@ subtest 'set_rule' => sub { Koha::CirculationRules->delete; - throws_ok( sub { - Koha::CirculationRules->set_rule( { - rule_name => 'lostreturn', - rule_value => '', - } ); - }, qr/branchcode/, 'setting lostreturn without branch fails' ); + throws_ok( + sub { + Koha::CirculationRules->set_rule( + { + rule_name => 'lostreturn', + rule_value => '', + } + ); + }, + qr/branchcode/, + 'setting lostreturn without branch fails' + ); - throws_ok( sub { - Koha::CirculationRules->set_rule( { - rule_name => 'processingreturn', - rule_value => '', - } ); - }, qr/branchcode/, 'setting processingreturn without branch fails' ); + throws_ok( + sub { + Koha::CirculationRules->set_rule( + { + rule_name => 'processingreturn', + rule_value => '', + } + ); + }, + qr/branchcode/, + 'setting processingreturn without branch fails' + ); - throws_ok( sub { - Koha::CirculationRules->set_rule( { - branchcode => $branchcode, - rule_name => 'patron_maxissueqty', - rule_value => '', - } ); - }, qr/categorycode/, 'setting patron_maxissueqty without categorycode fails' ); + throws_ok( + sub { + Koha::CirculationRules->set_rule( + { + branchcode => $branchcode, + rule_name => 'patron_maxissueqty', + rule_value => '', + } + ); + }, + qr/categorycode/, + 'setting patron_maxissueqty without categorycode fails' + ); - throws_ok( sub { - Koha::CirculationRules->set_rule( { - branchcode => $branchcode, - rule_name => 'holdallowed', - rule_value => '', - } ); - }, qr/itemtype/, 'setting holdallowed without itemtype fails' ); + throws_ok( + sub { + Koha::CirculationRules->set_rule( + { + branchcode => $branchcode, + rule_name => 'holdallowed', + rule_value => '', + } + ); + }, + qr/itemtype/, + 'setting holdallowed without itemtype fails' + ); - throws_ok( sub { - Koha::CirculationRules->set_rule( { - branchcode => $branchcode, - categorycode => $categorycode, - rule_name => 'fine', - rule_value => '', - } ); - }, qr/itemtype/, 'setting fine without itemtype fails' ); + throws_ok( + sub { + Koha::CirculationRules->set_rule( + { + branchcode => $branchcode, + categorycode => $categorycode, + rule_name => 'fine', + rule_value => '', + } + ); + }, + qr/itemtype/, + 'setting fine without itemtype fails' + ); }; subtest 'Call with extra params' => sub { @@ -261,43 +353,67 @@ subtest 'set_rule' => sub { Koha::CirculationRules->delete; - throws_ok( sub { - Koha::CirculationRules->set_rule( { - branchcode => $branchcode, - categorycode => $categorycode, - rule_name => 'lostreturn', - rule_value => '', - } ); - }, qr/categorycode/, 'setting lostreturn with categorycode fails' ); + throws_ok( + sub { + Koha::CirculationRules->set_rule( + { + branchcode => $branchcode, + categorycode => $categorycode, + rule_name => 'lostreturn', + rule_value => '', + } + ); + }, + qr/categorycode/, + 'setting lostreturn with categorycode fails' + ); - throws_ok( sub { - Koha::CirculationRules->set_rule( { - branchcode => $branchcode, - categorycode => $categorycode, - rule_name => 'processingreturn', - rule_value => '', - } ); - }, qr/categorycode/, 'setting processingreturn with categorycode fails' ); + throws_ok( + sub { + Koha::CirculationRules->set_rule( + { + branchcode => $branchcode, + categorycode => $categorycode, + rule_name => 'processingreturn', + rule_value => '', + } + ); + }, + qr/categorycode/, + 'setting processingreturn with categorycode fails' + ); - throws_ok( sub { - Koha::CirculationRules->set_rule( { - branchcode => $branchcode, - categorycode => $categorycode, - itemtype => $itemtype, - rule_name => 'patron_maxissueqty', - rule_value => '', - } ); - }, qr/itemtype/, 'setting patron_maxissueqty with itemtype fails' ); + throws_ok( + sub { + Koha::CirculationRules->set_rule( + { + branchcode => $branchcode, + categorycode => $categorycode, + itemtype => $itemtype, + rule_name => 'patron_maxissueqty', + rule_value => '', + } + ); + }, + qr/itemtype/, + 'setting patron_maxissueqty with itemtype fails' + ); - throws_ok( sub { - Koha::CirculationRules->set_rule( { - branchcode => $branchcode, - rule_name => 'holdallowed', - categorycode => $categorycode, - itemtype => $itemtype, - rule_value => '', - } ); - }, qr/categorycode/, 'setting holdallowed with categorycode fails' ); + throws_ok( + sub { + Koha::CirculationRules->set_rule( + { + branchcode => $branchcode, + rule_name => 'holdallowed', + categorycode => $categorycode, + itemtype => $itemtype, + rule_value => '', + } + ); + }, + qr/categorycode/, + 'setting holdallowed with categorycode fails' + ); }; subtest 'Call with badly formatted params' => sub { @@ -332,45 +448,53 @@ subtest 'clone' => sub { $schema->storage->txn_begin; - my $branchcode = $builder->build({ source => 'Branch' })->{'branchcode'}; - my $categorycode = $builder->build({ source => 'Category' })->{'categorycode'}; - my $itemtype = $builder->build({ source => 'Itemtype' })->{'itemtype'}; + my $branchcode = $builder->build( { source => 'Branch' } )->{'branchcode'}; + my $categorycode = $builder->build( { source => 'Category' } )->{'categorycode'}; + my $itemtype = $builder->build( { source => 'Itemtype' } )->{'itemtype'}; subtest 'Clone multiple rules' => sub { plan tests => 4; Koha::CirculationRules->delete; - Koha::CirculationRule->new({ - branchcode => undef, - categorycode => $categorycode, - itemtype => $itemtype, - rule_name => 'fine', - rule_value => 5, - })->store; + Koha::CirculationRule->new( + { + branchcode => undef, + categorycode => $categorycode, + itemtype => $itemtype, + rule_name => 'fine', + rule_value => 5, + } + )->store; - Koha::CirculationRule->new({ - branchcode => undef, - categorycode => $categorycode, - itemtype => $itemtype, - rule_name => 'lengthunit', - rule_value => 'days', - })->store; + Koha::CirculationRule->new( + { + branchcode => undef, + categorycode => $categorycode, + itemtype => $itemtype, + rule_name => 'lengthunit', + rule_value => 'days', + } + )->store; - Koha::CirculationRules->search({ branchcode => undef })->clone($branchcode); + Koha::CirculationRules->search( { branchcode => undef } )->clone($branchcode); - my $rule_fine = Koha::CirculationRules->get_effective_rule({ - branchcode => $branchcode, - categorycode => $categorycode, - itemtype => $itemtype, - rule_name => 'fine', - }); - my $rule_lengthunit = Koha::CirculationRules->get_effective_rule({ - branchcode => $branchcode, - categorycode => $categorycode, - itemtype => $itemtype, - rule_name => 'lengthunit', - }); + my $rule_fine = Koha::CirculationRules->get_effective_rule( + { + branchcode => $branchcode, + categorycode => $categorycode, + itemtype => $itemtype, + rule_name => 'fine', + } + ); + my $rule_lengthunit = Koha::CirculationRules->get_effective_rule( + { + branchcode => $branchcode, + categorycode => $categorycode, + itemtype => $itemtype, + rule_name => 'lengthunit', + } + ); _is_row_match( $rule_fine, @@ -381,8 +505,7 @@ subtest 'clone' => sub { rule_name => 'fine', rule_value => 5, }, - 'When I attempt to get cloned fine rule,' - .' then the above one is returned.' + 'When I attempt to get cloned fine rule,' . ' then the above one is returned.' ); _is_row_match( $rule_lengthunit, @@ -393,8 +516,7 @@ subtest 'clone' => sub { rule_name => 'lengthunit', rule_value => 'days', }, - 'When I attempt to get cloned lengthunit rule,' - .' then the above one is returned.' + 'When I attempt to get cloned lengthunit rule,' . ' then the above one is returned.' ); }; @@ -404,23 +526,27 @@ subtest 'clone' => sub { Koha::CirculationRules->delete; - Koha::CirculationRule->new({ - branchcode => undef, - categorycode => $categorycode, - itemtype => $itemtype, - rule_name => 'fine', - rule_value => 5, - })->store; + Koha::CirculationRule->new( + { + branchcode => undef, + categorycode => $categorycode, + itemtype => $itemtype, + rule_name => 'fine', + rule_value => 5, + } + )->store; - my $rule = Koha::CirculationRules->search({ branchcode => undef })->next; + my $rule = Koha::CirculationRules->search( { branchcode => undef } )->next; $rule->clone($branchcode); - my $cloned_rule = Koha::CirculationRules->get_effective_rule({ - branchcode => $branchcode, - categorycode => $categorycode, - itemtype => $itemtype, - rule_name => 'fine', - }); + my $cloned_rule = Koha::CirculationRules->get_effective_rule( + { + branchcode => $branchcode, + categorycode => $categorycode, + itemtype => $itemtype, + rule_name => 'fine', + } + ); _is_row_match( $cloned_rule, @@ -431,8 +557,7 @@ subtest 'clone' => sub { rule_name => 'fine', rule_value => '5', }, - 'When I attempt to get cloned fine rule,' - .' then the above one is returned.' + 'When I attempt to get cloned fine rule,' . ' then the above one is returned.' ); }; @@ -445,11 +570,11 @@ subtest 'set_rule + get_effective_rule' => sub { $schema->storage->txn_begin; - my $categorycode = $builder->build_object( { class => 'Koha::Patron::Categories' } )->categorycode; - my $itemtype = $builder->build_object( { class => 'Koha::ItemTypes' } )->itemtype; - my $branchcode = $builder->build_object( { class => 'Koha::Libraries' } )->branchcode; - my $branchcode_2 = $builder->build_object( { class => 'Koha::Libraries' } )->branchcode; - my $rule_name = 'maxissueqty'; + my $categorycode = $builder->build_object( { class => 'Koha::Patron::Categories' } )->categorycode; + my $itemtype = $builder->build_object( { class => 'Koha::ItemTypes' } )->itemtype; + my $branchcode = $builder->build_object( { class => 'Koha::Libraries' } )->branchcode; + my $branchcode_2 = $builder->build_object( { class => 'Koha::Libraries' } )->branchcode; + my $rule_name = 'maxissueqty'; my $default_rule_value = 1; my $rule; @@ -457,7 +582,7 @@ subtest 'set_rule + get_effective_rule' => sub { throws_ok { Koha::CirculationRules->get_effective_rule } 'Koha::Exceptions::MissingParameter', - "Exception should be raised if get_effective_rule is called without rule_name parameter"; + "Exception should be raised if get_effective_rule is called without rule_name parameter"; $rule = Koha::CirculationRules->get_effective_rule( { @@ -507,18 +632,20 @@ subtest 'set_rule + get_effective_rule' => sub { rule_name => $rule_name, } ); - is( $rule->rule_value, 1, - 'Default rule is returned if there is no rule for this branchcode' ); + is( + $rule->rule_value, 1, + 'Default rule is returned if there is no rule for this branchcode' + ); subtest 'test rules that cannot be blank' => sub { plan tests => 3; - foreach my $no_blank_rule ( ('holdallowed','hold_fulfillment_policy','returnbranch') ){ + foreach my $no_blank_rule ( ( 'holdallowed', 'hold_fulfillment_policy', 'returnbranch' ) ) { Koha::CirculationRules->set_rule( { - branchcode => $branchcode, - itemtype => '*', - rule_name => $no_blank_rule, - rule_value => '', + branchcode => $branchcode, + itemtype => '*', + rule_name => $no_blank_rule, + rule_value => '', } ); @@ -592,16 +719,17 @@ subtest 'set_rule + get_effective_rule' => sub { $scope_output .= " $key" if $test->{$key} ne '*'; } - is( $rule->rule_value, $rule_value, - 'Explicitly scoped' - . ( $scope_output ? $scope_output : ' nothing' ) ); + is( + $rule->rule_value, $rule_value, + 'Explicitly scoped' . ( $scope_output ? $scope_output : ' nothing' ) + ); } }; - my $our_branch_rules = Koha::CirculationRules->search({branchcode => $branchcode}); - is( $our_branch_rules->count, 5, "We added 9 rules"); + my $our_branch_rules = Koha::CirculationRules->search( { branchcode => $branchcode } ); + is( $our_branch_rules->count, 5, "We added 9 rules" ); $our_branch_rules->delete; - is( $our_branch_rules->count, 0, "We deleted 9 rules"); + is( $our_branch_rules->count, 0, "We deleted 9 rules" ); $schema->storage->txn_rollback; }; @@ -615,8 +743,9 @@ subtest 'get_onshelfholds_policy() tests' => sub { my $item = $builder->build_sample_item(); my $circ_rules = Koha::CirculationRules->new; + # Cleanup - $circ_rules->search({ rule_name => 'onshelfholds' })->delete; + $circ_rules->search( { rule_name => 'onshelfholds' } )->delete; $circ_rules->set_rule( { @@ -628,10 +757,14 @@ subtest 'get_onshelfholds_policy() tests' => sub { } ); - is( $circ_rules->get_onshelfholds_policy({ item => $item }), 1, 'If rule_value is set on a matching rule, return it' ); + is( + $circ_rules->get_onshelfholds_policy( { item => $item } ), 1, + 'If rule_value is set on a matching rule, return it' + ); + # Delete the rule (i.e. get_effective_rule returns undef) $circ_rules->delete; - is( $circ_rules->get_onshelfholds_policy({ item => $item }), 0, 'If no matching rule, fallback to 0' ); + is( $circ_rules->get_onshelfholds_policy( { item => $item } ), 0, 'If no matching rule, fallback to 0' ); $schema->storage->txn_rollback; }; @@ -644,8 +777,7 @@ subtest 'get_effective_daysmode' => sub { my $item_1 = $builder->build_sample_item(); my $item_2 = $builder->build_sample_item(); - my $circ_rules = - Koha::CirculationRules->search( { rule_name => 'daysmode' } )->delete; + my $circ_rules = Koha::CirculationRules->search( { rule_name => 'daysmode' } )->delete; # Default value 'Datedue' at pref level t::lib::Mocks::mock_preference( 'useDaysMode', 'Datedue' ); @@ -734,7 +866,7 @@ subtest 'get_effective_expire_reserves_charge' => sub { $schema->storage->txn_begin; - Koha::CirculationRules->search({ rule_name => 'expire_reserves_charge' })->delete; + Koha::CirculationRules->search( { rule_name => 'expire_reserves_charge' } )->delete; t::lib::Mocks::mock_preference( 'ExpireReservesMaxPickUpDelayCharge', 10 ); @@ -852,7 +984,7 @@ subtest 'get_lostreturn_policy() tests' => sub { } } ); - my $branchcode = $builder->build( { source => 'Branch' } )->{branchcode}; + my $branchcode = $builder->build( { source => 'Branch' } )->{branchcode}; my $specific_lost_rule_false = $builder->build( { source => 'CirculationRule', @@ -877,7 +1009,7 @@ subtest 'get_lostreturn_policy() tests' => sub { } } ); - my $branchcode2 = $builder->build( { source => 'Branch' } )->{branchcode}; + my $branchcode2 = $builder->build( { source => 'Branch' } )->{branchcode}; my $specific_lost_rule_refund = $builder->build( { source => 'CirculationRule', @@ -902,7 +1034,7 @@ subtest 'get_lostreturn_policy() tests' => sub { } } ); - my $branchcode3 = $builder->build( { source => 'Branch' } )->{branchcode}; + my $branchcode3 = $builder->build( { source => 'Branch' } )->{branchcode}; my $specific_lost_rule_restore = $builder->build( { source => 'CirculationRule', @@ -938,68 +1070,80 @@ subtest 'get_lostreturn_policy() tests' => sub { } ); my $params = { - return_branch => $specific_lost_rule_refund->{ branchcode }, + return_branch => $specific_lost_rule_refund->{branchcode}, item => $item }; # Specific rules t::lib::Mocks::mock_preference( 'RefundLostOnReturnControl', 'CheckinLibrary' ); - is_deeply( Koha::CirculationRules->get_lostreturn_policy( $params ), - { lostreturn => 'refund', processingreturn => 'refund' },'Specific rule for checkin branch is applied (refund)'); + is_deeply( + Koha::CirculationRules->get_lostreturn_policy($params), + { lostreturn => 'refund', processingreturn => 'refund' }, 'Specific rule for checkin branch is applied (refund)' + ); t::lib::Mocks::mock_preference( 'RefundLostOnReturnControl', 'ItemHomeBranch' ); - is_deeply( Koha::CirculationRules->get_lostreturn_policy( $params ), - { lostreturn => 'restore', processingreturn => 'restore' },'Specific rule for home branch is applied (restore)'); + is_deeply( + Koha::CirculationRules->get_lostreturn_policy($params), + { lostreturn => 'restore', processingreturn => 'restore' }, 'Specific rule for home branch is applied (restore)' + ); t::lib::Mocks::mock_preference( 'RefundLostOnReturnControl', 'ItemHoldingBranch' ); - is_deeply( Koha::CirculationRules->get_lostreturn_policy( $params ), - { lostreturn => 0, processingreturn => 0 },'Specific rule for holding branch is applied (false)'); + is_deeply( + Koha::CirculationRules->get_lostreturn_policy($params), + { lostreturn => 0, processingreturn => 0 }, 'Specific rule for holding branch is applied (false)' + ); # Default rule check t::lib::Mocks::mock_preference( 'RefundLostOnReturnControl', 'CheckinLibrary' ); $params->{return_branch} = $branch_without_rule; - is_deeply( Koha::CirculationRules->get_lostreturn_policy( $params ), - { lostreturn => 'charge', processingreturn => 'charge' },'No rule for branch, global rule applied (charge)'); + is_deeply( + Koha::CirculationRules->get_lostreturn_policy($params), + { lostreturn => 'charge', processingreturn => 'charge' }, 'No rule for branch, global rule applied (charge)' + ); # Change the default value just to try - Koha::CirculationRules->search({ branchcode => undef, rule_name => 'lostreturn' })->next->rule_value(0)->store; - Koha::CirculationRules->search({ branchcode => undef, rule_name => 'processingreturn' })->next->rule_value(0)->store; + Koha::CirculationRules->search( { branchcode => undef, rule_name => 'lostreturn' } )->next->rule_value(0)->store; + Koha::CirculationRules->search( { branchcode => undef, rule_name => 'processingreturn' } )->next->rule_value(0) + ->store; my $memory_cache = Koha::Cache::Memory::Lite->get_instance; $memory_cache->flush(); - is_deeply( Koha::CirculationRules->get_lostreturn_policy( $params ), - { lostreturn => 0, processingreturn => 0 },'No rule for branch, global rule applied (false)'); + is_deeply( + Koha::CirculationRules->get_lostreturn_policy($params), + { lostreturn => 0, processingreturn => 0 }, 'No rule for branch, global rule applied (false)' + ); # No default rule defined check - Koha::CirculationRules - ->search( - { - branchcode => undef, - categorycode => undef, - itemtype => undef, - rule_name => 'lostreturn' - } - ) - ->next - ->delete; + Koha::CirculationRules->search( + { + branchcode => undef, + categorycode => undef, + itemtype => undef, + rule_name => 'lostreturn' + } + )->next->delete; + # No default rule defined check - Koha::CirculationRules - ->search( - { - branchcode => undef, - categorycode => undef, - itemtype => undef, - rule_name => 'processingreturn' - } - ) - ->next - ->delete; - is_deeply( Koha::CirculationRules->get_lostreturn_policy( $params ), - { lostreturn => 'refund', processingreturn => 'refund' },'No rule for branch, no default rule, fallback default (refund)'); + Koha::CirculationRules->search( + { + branchcode => undef, + categorycode => undef, + itemtype => undef, + rule_name => 'processingreturn' + } + )->next->delete; + is_deeply( + Koha::CirculationRules->get_lostreturn_policy($params), + { lostreturn => 'refund', processingreturn => 'refund' }, + 'No rule for branch, no default rule, fallback default (refund)' + ); # Fallback to ItemHoldBranch if CheckinLibrary is undefined $params->{return_branch} = undef; - is_deeply( Koha::CirculationRules->get_lostreturn_policy( $params ), - { lostreturn => 'restore', processingreturn => 'restore' },'return_branch undefined, fallback to ItemHomeBranch rule (restore)'); + is_deeply( + Koha::CirculationRules->get_lostreturn_policy($params), + { lostreturn => 'restore', processingreturn => 'restore' }, + 'return_branch undefined, fallback to ItemHomeBranch rule (restore)' + ); $schema->storage->txn_rollback; }; @@ -1007,9 +1151,9 @@ subtest 'get_lostreturn_policy() tests' => sub { sub _is_row_match { my ( $rule, $expected, $message ) = @_; - ok( $rule, $message ) ? - cmp_methods( $rule, [ %$expected ], $message ) : - fail( $message ); + ok( $rule, $message ) + ? cmp_methods( $rule, [%$expected], $message ) + : fail($message); } sub _prepare_tests_for_rule_scope_combinations { @@ -1041,14 +1185,16 @@ sub _prepare_tests_for_rule_scope_combinations { # equal to Koha/CirculationRules.pm "order_by" of C<get_effective_rule> sub. # Let's explicitly define the order and fail test if we are missing a scope: my $order = [ 'branchcode', 'categorycode', 'itemtype' ]; - is( join(", ", sort keys %$scope), - join(", ", sort @$order), 'Missing a scope!' ) if keys %$scope ne scalar @$order; + is( + join( ", ", sort keys %$scope ), + join( ", ", sort @$order ), 'Missing a scope!' + ) if keys %$scope ne scalar @$order; my @tests = (); foreach my $value ( glob( "{0,1}" x keys %$scope || 1 ) ) { - my $test = { %$scope }; - for ( my $i=0; $i < keys %$scope; $i++ ) { - $test->{$order->[$i]} = '*' unless substr( $value, $i, 1 ); + my $test = {%$scope}; + for ( my $i = 0 ; $i < keys %$scope ; $i++ ) { + $test->{ $order->[$i] } = '*' unless substr( $value, $i, 1 ); } push @tests, $test; } diff --git a/t/db_dependent/Koha/CirculationRules/guess_article_requestable_itemtypes.t b/t/db_dependent/Koha/CirculationRules/guess_article_requestable_itemtypes.t index f5c0f8aa9b..a1a0295099 100755 --- a/t/db_dependent/Koha/CirculationRules/guess_article_requestable_itemtypes.t +++ b/t/db_dependent/Koha/CirculationRules/guess_article_requestable_itemtypes.t @@ -12,21 +12,21 @@ use Koha::Caches; my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; our $builder = t::lib::TestBuilder->new; -our $cache = Koha::Caches->get_instance; +our $cache = Koha::Caches->get_instance; subtest 'guess_article_requestable_itemtypes' => sub { plan tests => 13; - t::lib::Mocks::mock_preference('ArticleRequests', 1); - t::lib::Mocks::mock_preference('ArticleRequestsLinkControl', 'calc'); - $cache->clear_from_cache( Koha::CirculationRules::GUESSED_ITEMTYPES_KEY ); + t::lib::Mocks::mock_preference( 'ArticleRequests', 1 ); + t::lib::Mocks::mock_preference( 'ArticleRequestsLinkControl', 'calc' ); + $cache->clear_from_cache(Koha::CirculationRules::GUESSED_ITEMTYPES_KEY); Koha::CirculationRules->delete; - my $library = $builder->build_object({ class => 'Koha::Libraries' }); - my $itype1 = $builder->build_object({ class => 'Koha::ItemTypes' }); - my $itype2 = $builder->build_object({ class => 'Koha::ItemTypes' }); - my $catg1 = $builder->build_object({ class => 'Koha::Patron::Categories' }); - my $catg2 = $builder->build_object({ class => 'Koha::Patron::Categories' }); - my $rule1 = Koha::CirculationRules->set_rule( + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); + my $itype1 = $builder->build_object( { class => 'Koha::ItemTypes' } ); + my $itype2 = $builder->build_object( { class => 'Koha::ItemTypes' } ); + my $catg1 = $builder->build_object( { class => 'Koha::Patron::Categories' } ); + my $catg2 = $builder->build_object( { class => 'Koha::Patron::Categories' } ); + my $rule1 = Koha::CirculationRules->set_rule( { branchcode => $library->branchcode, categorycode => undef, @@ -46,32 +46,32 @@ subtest 'guess_article_requestable_itemtypes' => sub { ); my $res = Koha::CirculationRules->guess_article_requestable_itemtypes; - is( $res->{'*'}, undef, 'Item type * seems not permitted' ); - is( $res->{$itype1->itemtype}, 1, 'Item type 1 seems permitted' ); - is( $res->{$itype2->itemtype}, 1, 'Item type 2 seems permitted' ); - $res = Koha::CirculationRules->guess_article_requestable_itemtypes({ categorycode => $catg2->categorycode }); - is( $res->{'*'}, undef, 'Item type * seems not permitted' ); - is( $res->{$itype1->itemtype}, 1, 'Item type 1 seems permitted' ); - is( $res->{$itype2->itemtype}, undef, 'Item type 2 seems not permitted' ); + is( $res->{'*'}, undef, 'Item type * seems not permitted' ); + is( $res->{ $itype1->itemtype }, 1, 'Item type 1 seems permitted' ); + is( $res->{ $itype2->itemtype }, 1, 'Item type 2 seems permitted' ); + $res = Koha::CirculationRules->guess_article_requestable_itemtypes( { categorycode => $catg2->categorycode } ); + is( $res->{'*'}, undef, 'Item type * seems not permitted' ); + is( $res->{ $itype1->itemtype }, 1, 'Item type 1 seems permitted' ); + is( $res->{ $itype2->itemtype }, undef, 'Item type 2 seems not permitted' ); # Change the rules $rule2->itemtype(undef)->store; - $cache->clear_from_cache( Koha::CirculationRules::GUESSED_ITEMTYPES_KEY ); + $cache->clear_from_cache(Koha::CirculationRules::GUESSED_ITEMTYPES_KEY); $res = Koha::CirculationRules->guess_article_requestable_itemtypes; - is( $res->{'*'}, 1, 'Item type * seems permitted' ); - is( $res->{$itype1->itemtype}, 1, 'Item type 1 seems permitted' ); - is( $res->{$itype2->itemtype}, undef, 'Item type 2 seems not permitted' ); - $res = Koha::CirculationRules->guess_article_requestable_itemtypes({ categorycode => $catg2->categorycode }); - is( $res->{'*'}, undef, 'Item type * seems not permitted' ); - is( $res->{$itype1->itemtype}, 1, 'Item type 1 seems permitted' ); - is( $res->{$itype2->itemtype}, undef, 'Item type 2 seems not permitted' ); + is( $res->{'*'}, 1, 'Item type * seems permitted' ); + is( $res->{ $itype1->itemtype }, 1, 'Item type 1 seems permitted' ); + is( $res->{ $itype2->itemtype }, undef, 'Item type 2 seems not permitted' ); + $res = Koha::CirculationRules->guess_article_requestable_itemtypes( { categorycode => $catg2->categorycode } ); + is( $res->{'*'}, undef, 'Item type * seems not permitted' ); + is( $res->{ $itype1->itemtype }, 1, 'Item type 1 seems permitted' ); + is( $res->{ $itype2->itemtype }, undef, 'Item type 2 seems not permitted' ); # Finally test the overriding pref - t::lib::Mocks::mock_preference('ArticleRequestsLinkControl', 'always'); - $res = Koha::CirculationRules->guess_article_requestable_itemtypes({}); + t::lib::Mocks::mock_preference( 'ArticleRequestsLinkControl', 'always' ); + $res = Koha::CirculationRules->guess_article_requestable_itemtypes( {} ); is( $res->{'*'}, 1, 'Override algorithm with pref setting' ); - $cache->clear_from_cache( Koha::CirculationRules::GUESSED_ITEMTYPES_KEY ); + $cache->clear_from_cache(Koha::CirculationRules::GUESSED_ITEMTYPES_KEY); }; $schema->storage->txn_rollback; diff --git a/t/db_dependent/Koha/Cities.t b/t/db_dependent/Koha/Cities.t index acf44b3a04..388d086c97 100755 --- a/t/db_dependent/Koha/Cities.t +++ b/t/db_dependent/Koha/Cities.t @@ -30,22 +30,26 @@ use t::lib::TestBuilder; my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; -my $builder = t::lib::TestBuilder->new; +my $builder = t::lib::TestBuilder->new; my $nb_of_cities = Koha::Cities->search->count; -my $new_city_1 = Koha::City->new({ - city_name => 'my_city_name_for_test_1', - city_state => 'my_city_state_for_test_1', - city_zipcode => 'my_zipcode_4_test_1', - city_country => 'my_city_country_for_test_1', -})->store; -my $new_city_2 = Koha::City->new({ - city_name => 'my_city_name_for_test_2', - city_state => 'my_city_state_for_test_2', - city_zipcode => 'my_zipcode_4_test_2', - city_country => 'my_city_country_for_test_2', -})->store; +my $new_city_1 = Koha::City->new( + { + city_name => 'my_city_name_for_test_1', + city_state => 'my_city_state_for_test_1', + city_zipcode => 'my_zipcode_4_test_1', + city_country => 'my_city_country_for_test_1', + } +)->store; +my $new_city_2 = Koha::City->new( + { + city_name => 'my_city_name_for_test_2', + city_state => 'my_city_state_for_test_2', + city_zipcode => 'my_zipcode_4_test_2', + city_country => 'my_city_country_for_test_2', + } +)->store; -like( $new_city_1->cityid, qr|^\d+$|, 'Adding a new city should have set the cityid'); +like( $new_city_1->cityid, qr|^\d+$|, 'Adding a new city should have set the cityid' ); is( Koha::Cities->search->count, $nb_of_cities + 2, 'The 2 cities should have been added' ); my $retrieved_city_1 = Koha::Cities->find( $new_city_1->cityid ); diff --git a/t/db_dependent/Koha/ClassSortRules.t b/t/db_dependent/Koha/ClassSortRules.t index e83d93ba59..96bc5bfd3d 100755 --- a/t/db_dependent/Koha/ClassSortRules.t +++ b/t/db_dependent/Koha/ClassSortRules.t @@ -30,24 +30,34 @@ use t::lib::TestBuilder; my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; -my $builder = t::lib::TestBuilder->new; +my $builder = t::lib::TestBuilder->new; my $nb_of_class_sort_rules = Koha::ClassSortRules->search->count; -my $new_cs_1 = Koha::ClassSortRule->new({ - class_sort_rule => 'sort_rule1', - description => 'a_sort_test_1', - sort_routine => 'lcc', -})->store; -my $new_cs_2 = Koha::ClassSortRule->new({ - class_sort_rule => 'sort_rule2', - description => 'a_sort_test_2', - sort_routine => 'dewey', -})->store; +my $new_cs_1 = Koha::ClassSortRule->new( + { + class_sort_rule => 'sort_rule1', + description => 'a_sort_test_1', + sort_routine => 'lcc', + } +)->store; +my $new_cs_2 = Koha::ClassSortRule->new( + { + class_sort_rule => 'sort_rule2', + description => 'a_sort_test_2', + sort_routine => 'dewey', + } +)->store; -is( $new_cs_1->class_sort_rule, 'sort_rule1', 'Adding a new classification sort should have set the class_sort_rule'); -is( Koha::ClassSortRules->search->count, $nb_of_class_sort_rules + 2, 'The 2 classification sorters should have been added' ); +is( $new_cs_1->class_sort_rule, 'sort_rule1', 'Adding a new classification sort should have set the class_sort_rule' ); +is( + Koha::ClassSortRules->search->count, $nb_of_class_sort_rules + 2, + 'The 2 classification sorters should have been added' +); my $retrieved_cs_1 = Koha::ClassSortRules->find( $new_cs_1->class_sort_rule ); -is( $retrieved_cs_1->description, $new_cs_1->description, 'Find a sorter by class_sort_rule should return the correct source' ); +is( + $retrieved_cs_1->description, $new_cs_1->description, + 'Find a sorter by class_sort_rule should return the correct source' +); $retrieved_cs_1->delete; is( Koha::ClassSortRules->search->count, $nb_of_class_sort_rules + 1, 'Delete should have deleted the sort' ); diff --git a/t/db_dependent/Koha/ClassSources.t b/t/db_dependent/Koha/ClassSources.t index c1772b1654..213bf334f5 100755 --- a/t/db_dependent/Koha/ClassSources.t +++ b/t/db_dependent/Koha/ClassSources.t @@ -30,31 +30,38 @@ use t::lib::TestBuilder; my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; -my $builder = t::lib::TestBuilder->new; -my $class_sort_1 = $builder->build({ source=>'ClassSortRule' }); -my $class_sort_2 = $builder->build({ source=>'ClassSortRule' }); -my $class_split = $builder->build({ source=>'ClassSplitRule' }); +my $builder = t::lib::TestBuilder->new; +my $class_sort_1 = $builder->build( { source => 'ClassSortRule' } ); +my $class_sort_2 = $builder->build( { source => 'ClassSortRule' } ); +my $class_split = $builder->build( { source => 'ClassSplitRule' } ); my $nb_of_class_sources = Koha::ClassSources->search->count; -my $new_cs_1 = Koha::ClassSource->new({ - cn_source => 'source_1', - description => 'a_test_1', - used => '1', - class_sort_rule => $class_sort_1->{class_sort_rule},#'sort_rule_1', - class_split_rule => $class_split->{class_split_rule}, -})->store; -my $new_cs_2 = Koha::ClassSource->new({ - cn_source => 'source_2', - description => 'a_test_2', - used => '0', - class_sort_rule => $class_sort_2->{class_sort_rule},#'sort_rule_1', - class_split_rule => $class_split->{class_split_rule}, -})->store; +my $new_cs_1 = Koha::ClassSource->new( + { + cn_source => 'source_1', + description => 'a_test_1', + used => '1', + class_sort_rule => $class_sort_1->{class_sort_rule}, #'sort_rule_1', + class_split_rule => $class_split->{class_split_rule}, + } +)->store; +my $new_cs_2 = Koha::ClassSource->new( + { + cn_source => 'source_2', + description => 'a_test_2', + used => '0', + class_sort_rule => $class_sort_2->{class_sort_rule}, #'sort_rule_1', + class_split_rule => $class_split->{class_split_rule}, + } +)->store; -is( $new_cs_1->cn_source, 'source_1', 'Adding a new classification should have set the cn_source'); +is( $new_cs_1->cn_source, 'source_1', 'Adding a new classification should have set the cn_source' ); is( Koha::ClassSources->search->count, $nb_of_class_sources + 2, 'The 2 classifcations should have been added' ); my $retrieved_cs_1 = Koha::ClassSources->find( $new_cs_1->cn_source ); -is( $retrieved_cs_1->description, $new_cs_1->description, 'Find a source by cn_source should return the correct source' ); +is( + $retrieved_cs_1->description, $new_cs_1->description, + 'Find a source by cn_source should return the correct source' +); $retrieved_cs_1->delete; is( Koha::ClassSources->search->count, $nb_of_class_sources + 1, 'Delete should have deleted the classification' ); diff --git a/t/db_dependent/Koha/ClassSplitRules.t b/t/db_dependent/Koha/ClassSplitRules.t index 2224dcc17e..a5e7b329c7 100755 --- a/t/db_dependent/Koha/ClassSplitRules.t +++ b/t/db_dependent/Koha/ClassSplitRules.t @@ -31,22 +31,22 @@ subtest 'store + regexs' => sub { plan tests => 2; $schema->storage->txn_begin; - my @regexs = ('s/\s/\n/g', 's/(\s?=)/\n=/g', 's/^(J|K)\n/$1 /'); - my $rule = Koha::ClassSplitRule->new( + my @regexs = ( 's/\s/\n/g', 's/(\s?=)/\n=/g', 's/^(J|K)\n/$1 /' ); + my $rule = Koha::ClassSplitRule->new( { class_split_rule => 'split_rule', - description => 'a_split_test_1', - split_routine => 'regex', + description => 'a_split_test_1', + split_routine => 'regex', } )->store; $rule = Koha::ClassSplitRules->find("split_rule"); - is_deeply($rule->regexs, [], '->regexs return an empty array when no regex is defined'); + is_deeply( $rule->regexs, [], '->regexs return an empty array when no regex is defined' ); - $rule->regexs(\@regexs)->store; + $rule->regexs( \@regexs )->store; $rule = Koha::ClassSplitRules->find("split_rule"); - is_deeply($rule->regexs, \@regexs, '->new and ->regexs correctly serialized/deserialized the regexs'); + is_deeply( $rule->regexs, \@regexs, '->new and ->regexs correctly serialized/deserialized the regexs' ); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/Koha/Club/Enrollment.t b/t/db_dependent/Koha/Club/Enrollment.t index 528be79151..d7d85b13d0 100755 --- a/t/db_dependent/Koha/Club/Enrollment.t +++ b/t/db_dependent/Koha/Club/Enrollment.t @@ -29,20 +29,21 @@ use Koha::DateUtils qw(dt_from_string); use t::lib::TestBuilder; my $builder = t::lib::TestBuilder->new; -my $schema = Koha::Database->new->schema; +my $schema = Koha::Database->new->schema; subtest 'is_canceled' => sub { plan tests => 2; $schema->storage->txn_begin; - my $enrollment = $builder->build_object({ class => 'Koha::Club::Enrollments', value => { date_canceled => undef } }); + my $enrollment = + $builder->build_object( { class => 'Koha::Club::Enrollments', value => { date_canceled => undef } } ); - ok(!$enrollment->is_canceled, 'Enrollment should not be canceled'); + ok( !$enrollment->is_canceled, 'Enrollment should not be canceled' ); - $enrollment->date_canceled(dt_from_string+"")->store; + $enrollment->date_canceled( dt_from_string + "" )->store; - ok($enrollment->is_canceled, 'Enrollment should be canceled'); + ok( $enrollment->is_canceled, 'Enrollment should be canceled' ); $schema->storage->txn_rollback; -} + } diff --git a/t/db_dependent/Koha/Club/Hold.t b/t/db_dependent/Koha/Club/Hold.t index d705f1d807..fb2f4a7030 100755 --- a/t/db_dependent/Koha/Club/Hold.t +++ b/t/db_dependent/Koha/Club/Hold.t @@ -28,12 +28,12 @@ use Koha::Club::Hold::PatronHolds; use Koha::Holds; use Koha::Database; use Koha::DateUtils qw(dt_from_string); -use Scalar::Util qw(blessed); +use Scalar::Util qw(blessed); use t::lib::TestBuilder; my $builder = t::lib::TestBuilder->new; -my $schema = Koha::Database->new->schema; +my $schema = Koha::Database->new->schema; subtest 'add' => sub { @@ -41,32 +41,24 @@ subtest 'add' => sub { $schema->storage->txn_begin; - my $club = $builder->build_object({ class => 'Koha::Clubs' }); - my $library = $builder->build_object({ class => 'Koha::Libraries', value => { pickup_location => 1 } }); - my $item1 = $builder->build_sample_item({ library => $library->branchcode }); - my $item2 = $builder->build_sample_item({ library => $library->branchcode }); + my $club = $builder->build_object( { class => 'Koha::Clubs' } ); + my $library = $builder->build_object( { class => 'Koha::Libraries', value => { pickup_location => 1 } } ); + my $item1 = $builder->build_sample_item( { library => $library->branchcode } ); + my $item2 = $builder->build_sample_item( { library => $library->branchcode } ); throws_ok { - Koha::Club::Hold::add( - { - club_id => $club->id - } - ); + Koha::Club::Hold::add( { club_id => $club->id } ); } 'Koha::Exceptions::MissingParameter', - 'Exception thrown when biblio_id is passed'; + 'Exception thrown when biblio_id is passed'; like( "$@", qr/The biblio_id parameter is mandatory/ ); throws_ok { - Koha::Club::Hold::add( - { - biblio_id => $item1->biblionumber - } - ); + Koha::Club::Hold::add( { biblio_id => $item1->biblionumber } ); } 'Koha::Exceptions::MissingParameter', - 'Exception thrown when club_id is passed'; + 'Exception thrown when club_id is passed'; like( "$@", qr/The club_id parameter is mandatory/ ); @@ -80,7 +72,7 @@ subtest 'add' => sub { ); } 'Koha::Exceptions::ClubHold::NoPatrons', - 'Exception thrown when no patron is enrolled in club'; + 'Exception thrown when no patron is enrolled in club'; my $patron = $builder->build_object( { @@ -107,7 +99,7 @@ subtest 'add' => sub { } ); - is(blessed($club_hold), 'Koha::Club::Hold', 'add returns a Koha::Club::Hold'); + is( blessed($club_hold), 'Koha::Club::Hold', 'add returns a Koha::Club::Hold' ); $e->date_canceled(dt_from_string)->store; @@ -121,17 +113,17 @@ subtest 'add' => sub { ); } 'Koha::Exceptions::ClubHold::NoPatrons', - 'Exception thrown when no patron is enrolled in club'; + 'Exception thrown when no patron is enrolled in club'; - my $patron_holds = Koha::Club::Hold::PatronHolds->search({ club_hold_id => $club_hold->id }); + my $patron_holds = Koha::Club::Hold::PatronHolds->search( { club_hold_id => $club_hold->id } ); - ok($patron_holds->count, "There must be at least one patron_hold"); + ok( $patron_holds->count, "There must be at least one patron_hold" ); my $patron_hold = $patron_holds->next; - my $hold = Koha::Holds->find($patron_hold->hold_id); + my $hold = Koha::Holds->find( $patron_hold->hold_id ); - is($patron_hold->patron_id, $hold->borrowernumber, 'Patron must be the same'); + is( $patron_hold->patron_id, $hold->borrowernumber, 'Patron must be the same' ); $schema->storage->txn_rollback; -} + } diff --git a/t/db_dependent/Koha/Config/SysPrefs.t b/t/db_dependent/Koha/Config/SysPrefs.t index 0f540edd30..c005989bb7 100755 --- a/t/db_dependent/Koha/Config/SysPrefs.t +++ b/t/db_dependent/Koha/Config/SysPrefs.t @@ -30,13 +30,15 @@ $schema->storage->txn_begin; my $builder = t::lib::TestBuilder->new; my $nb_of_prefs = Koha::Config::SysPrefs->search->count; -my $new_pref = Koha::Config::SysPref->new({ - variable => 'ShouldNotBeDone', - value => 'but a good test?', - options => undef, - explanation => 'just for CRUD sake', - type => 'Free' -})->store; +my $new_pref = Koha::Config::SysPref->new( + { + variable => 'ShouldNotBeDone', + value => 'but a good test?', + options => undef, + explanation => 'just for CRUD sake', + type => 'Free' + } +)->store; is( Koha::Config::SysPrefs->search->count, $nb_of_prefs + 1, 'The 1 pref should have been added' ); my $retrieved_pref = Koha::Config::SysPrefs->find('ShouldNotBeDone'); diff --git a/t/db_dependent/Koha/CoverImages.t b/t/db_dependent/Koha/CoverImages.t index ff4c12ed54..953947e62d 100755 --- a/t/db_dependent/Koha/CoverImages.t +++ b/t/db_dependent/Koha/CoverImages.t @@ -40,15 +40,16 @@ my $item = $builder->build_sample_item; is( $biblio->cover_images->count, 0, 'No cover images yet' ); my $no_image = Koha::CoverImages->no_image; -is( ref($no_image), 'Koha::CoverImage', - 'no_image returns a Koha::CoverImage object' ); +is( + ref($no_image), 'Koha::CoverImage', + 'no_image returns a Koha::CoverImage object' +); is( $no_image->mimetype, 'image/gif', 'no_image is a gif image' ); ok( $no_image->imagefile, 'no_image has imagefile set' ); ok( $no_image->thumbnail, 'no_image has thumbnail set' ); -my $logo_filepath = - "$Bin/../../../koha-tmpl/intranet-tmpl/prog/img/koha-logo.png"; -my $image = Koha::CoverImage->new( +my $logo_filepath = "$Bin/../../../koha-tmpl/intranet-tmpl/prog/img/koha-logo.png"; +my $image = Koha::CoverImage->new( { biblionumber => $biblio->biblionumber, src_image => GD::Image->new($logo_filepath) @@ -59,8 +60,10 @@ is( $biblio->cover_images->count, 1, 'There is one cover image' ); my $cover_image = $biblio->cover_images->next; ok( $cover_image->imagefile, 'image is stored in imagefile' ); ok( $cover_image->thumbnail, 'thumbnail has been generated' ); -is( $cover_image->mimetype, 'image/png', - 'mimetype has been correctly guessed' ); +is( + $cover_image->mimetype, 'image/png', + 'mimetype has been correctly guessed' +); $image = Koha::CoverImage->new( { @@ -77,9 +80,11 @@ $image = Koha::CoverImage->new( src_image => GD::Image->new($logo_filepath) } )->store; -is( ref( $item->cover_images->next ), +is( + ref( $item->cover_images->next ), 'Koha::CoverImage', - 'Koha::Item->cover_images returns a rs of Koha::CoverImage object' ); + 'Koha::Item->cover_images returns a rs of Koha::CoverImage object' +); Koha::CoverImage->new( { @@ -89,6 +94,6 @@ Koha::CoverImage->new( } )->store; is( $biblio->cover_images->count, 3, ); -is( $item->cover_images->count, 2, ); +is( $item->cover_images->count, 2, ); $schema->storage->txn_rollback; diff --git a/t/db_dependent/Koha/CsvProfiles.t b/t/db_dependent/Koha/CsvProfiles.t index d823f40404..e7c71c48d0 100755 --- a/t/db_dependent/Koha/CsvProfiles.t +++ b/t/db_dependent/Koha/CsvProfiles.t @@ -30,27 +30,37 @@ use t::lib::TestBuilder; my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; -my $builder = t::lib::TestBuilder->new; +my $builder = t::lib::TestBuilder->new; my $nb_of_csv_profiles = Koha::CsvProfiles->search->count; -my $new_csv_profile_1 = Koha::CsvProfile->new({ - profile => 'my_csv_profile_name_for_test_1', - description => 'my_csv_profile_description_for_test_1', - type => 'sql', - used_for => 'late_issues', - content => 'a content', -})->store; -my $new_csv_profile_2 = Koha::CsvProfile->new({ - profile => 'my_csv_profile_name_for_test_2', - description => 'my_csv_profile_description_for_test_2', - type => 'marc', - content => 'another content', -})->store; +my $new_csv_profile_1 = Koha::CsvProfile->new( + { + profile => 'my_csv_profile_name_for_test_1', + description => 'my_csv_profile_description_for_test_1', + type => 'sql', + used_for => 'late_issues', + content => 'a content', + } +)->store; +my $new_csv_profile_2 = Koha::CsvProfile->new( + { + profile => 'my_csv_profile_name_for_test_2', + description => 'my_csv_profile_description_for_test_2', + type => 'marc', + content => 'another content', + } +)->store; -like( $new_csv_profile_1->export_format_id, qr|^\d+$|, 'Adding a new csv_profile should have set the export_format_id'); +like( + $new_csv_profile_1->export_format_id, qr|^\d+$|, + 'Adding a new csv_profile should have set the export_format_id' +); is( Koha::CsvProfiles->search->count, $nb_of_csv_profiles + 2, 'The 2 csv profiles should have been added' ); my $retrieved_csv_profile_1 = Koha::CsvProfiles->find( $new_csv_profile_1->export_format_id ); -is( $retrieved_csv_profile_1->profile, $new_csv_profile_1->profile, 'Find a csv_profile by id should return the correct csv_profile' ); +is( + $retrieved_csv_profile_1->profile, $new_csv_profile_1->profile, + 'Find a csv_profile by id should return the correct csv_profile' +); $retrieved_csv_profile_1->delete; is( Koha::CsvProfiles->search->count, $nb_of_csv_profiles + 1, 'Delete should have deleted the csv_profile' ); diff --git a/t/db_dependent/Koha/CurbsidePickups.t b/t/db_dependent/Koha/CurbsidePickups.t index 3b98bef472..2717520c04 100755 --- a/t/db_dependent/Koha/CurbsidePickups.t +++ b/t/db_dependent/Koha/CurbsidePickups.t @@ -53,22 +53,22 @@ my $patron = $builder->build_object( my $policy = Koha::CurbsidePickupPolicy->new( { - branchcode => $library->branchcode, - enabled => 1, + branchcode => $library->branchcode, + enabled => 1, enable_waiting_holds_only => 0, - pickup_interval => 15, - patrons_per_interval => 2, - patron_scheduled_pickup => 1 + pickup_interval => 15, + patrons_per_interval => 2, + patron_scheduled_pickup => 1 } )->store; my $policy_disabled = Koha::CurbsidePickupPolicy->new( { - branchcode => $library_disabled->branchcode, - enabled => 0, + branchcode => $library_disabled->branchcode, + enabled => 0, enable_waiting_holds_only => 0, - pickup_interval => 30, - patrons_per_interval => 2, - patron_scheduled_pickup => 1 + pickup_interval => 30, + patrons_per_interval => 2, + patron_scheduled_pickup => 1 } )->store; @@ -81,32 +81,30 @@ subtest 'Create a pickup' => sub { plan tests => 10; # Day and datetime are ok - my $next_monday = - $today->clone->add( days => ( 1 - $today->day_of_week ) % 7 ); + my $next_monday = $today->clone->add( days => ( 1 - $today->day_of_week ) % 7 ); my $schedule_dt = - $next_monday->set_hour(15)->set_minute(00)->set_second(00); - my $params = - { - branchcode => $library->branchcode, - borrowernumber => $patron->borrowernumber, - scheduled_pickup_datetime => $schedule_dt, - notes => 'just a note' - }; + $next_monday->set_hour(15)->set_minute(00)->set_second(00); + my $params = { + branchcode => $library->branchcode, + borrowernumber => $patron->borrowernumber, + scheduled_pickup_datetime => $schedule_dt, + notes => 'just a note' + }; throws_ok { - Koha::CurbsidePickup->new({%$params, branchcode => $library_disabled->branchcode})->store; + Koha::CurbsidePickup->new( { %$params, branchcode => $library_disabled->branchcode } )->store; } 'Koha::Exceptions::CurbsidePickup::NotEnabled', - 'Cannot create pickup if the policy does not allow it'; + 'Cannot create pickup if the policy does not allow it'; - $policy->enabled(1)->store; + $policy->enabled(1)->store; - $policy->enable_waiting_holds_only(1)->store; + $policy->enable_waiting_holds_only(1)->store; throws_ok { Koha::CurbsidePickup->new($params)->store; } 'Koha::Exceptions::CurbsidePickup::NoWaitingHolds', - 'Cannot create pickup for a patron without waiting hold if flag is set'; + 'Cannot create pickup for a patron without waiting hold if flag is set'; $policy->enable_waiting_holds_only(0)->store; my $cp = Koha::CurbsidePickup->new($params)->store; @@ -117,7 +115,7 @@ subtest 'Create a pickup' => sub { Koha::CurbsidePickup->new($params)->store } 'Koha::Exceptions::CurbsidePickup::TooManyPickups', - 'Cannot create 2 pickups for the same patron'; + 'Cannot create 2 pickups for the same patron'; $cp->delete; @@ -127,30 +125,29 @@ subtest 'Create a pickup' => sub { $cp->delete; # Day is not ok - my $next_tuesday = - $today->clone->add( days => ( 2 - $today->day_of_week ) % 7 ); + my $next_tuesday = $today->clone->add( days => ( 2 - $today->day_of_week ) % 7 ); $schedule_dt = $next_tuesday->set_hour(15)->set_minute(00)->set_second(00); throws_ok { - Koha::CurbsidePickup->new({%$params, scheduled_pickup_datetime => $schedule_dt})->store; + Koha::CurbsidePickup->new( { %$params, scheduled_pickup_datetime => $schedule_dt } )->store; } 'Koha::Exceptions::CurbsidePickup::NoMatchingSlots', - 'Cannot create a pickup on a day without opening slots defined'; + 'Cannot create a pickup on a day without opening slots defined'; # Day ok but datetime not ok $schedule_dt = $next_monday->set_hour(19)->set_minute(00)->set_second(00); throws_ok { - Koha::CurbsidePickup->new({%$params, scheduled_pickup_datetime => $schedule_dt})->store; + Koha::CurbsidePickup->new( { %$params, scheduled_pickup_datetime => $schedule_dt } )->store; } 'Koha::Exceptions::CurbsidePickup::NoMatchingSlots', - 'Cannot create a pickup on a time without opening slots defined'; + 'Cannot create a pickup on a time without opening slots defined'; # Day ok, datetime inside the opening slot, but wrong (15:07 for instance) $schedule_dt = $next_monday->set_hour(15)->set_minute(7)->set_second(0); throws_ok { - Koha::CurbsidePickup->new({%$params, scheduled_pickup_datetime => $schedule_dt})->store; + Koha::CurbsidePickup->new( { %$params, scheduled_pickup_datetime => $schedule_dt } )->store; } 'Koha::Exceptions::CurbsidePickup::NoMatchingSlots', -'Cannot create a pickup on a time that is not matching the start of an interval'; + 'Cannot create a pickup on a time that is not matching the start of an interval'; # Day is a holiday Koha::Caches->get_instance->flush_all; @@ -161,10 +158,10 @@ subtest 'Create a pickup' => sub { ); my $calendar = Koha::Calendar->new( branchcode => $library->branchcode ); throws_ok { - Koha::CurbsidePickup->new({%$params, scheduled_pickup_datetime => $schedule_dt})->store; + Koha::CurbsidePickup->new( { %$params, scheduled_pickup_datetime => $schedule_dt } )->store; } 'Koha::Exceptions::CurbsidePickup::LibraryIsClosed', - 'Cannot create a pickup on a holiday'; + 'Cannot create a pickup on a holiday'; C4::Context->dbh->do(q{DELETE FROM repeatable_holidays}); Koha::Caches->get_instance->flush_all; @@ -173,13 +170,11 @@ subtest 'Create a pickup' => sub { subtest 'workflow' => sub { plan tests => 11; - my $pickups = - Koha::CurbsidePickups->search( { branchcode => $library->branchcode } ); + my $pickups = Koha::CurbsidePickups->search( { branchcode => $library->branchcode } ); - my $next_monday = - $today->clone->add( days => ( 1 - $today->day_of_week ) % 7 ); + my $next_monday = $today->clone->add( days => ( 1 - $today->day_of_week ) % 7 ); my $schedule_dt = - $next_monday->set_hour(15)->set_minute(00)->set_second(00); + $next_monday->set_hour(15)->set_minute(00)->set_second(00); my $cp = Koha::CurbsidePickup->new( { branchcode => $library->branchcode, @@ -188,11 +183,11 @@ subtest 'workflow' => sub { notes => 'just a note' } )->store; - is( $cp->status, 'to-be-staged' ); + is( $cp->status, 'to-be-staged' ); is( $pickups->filter_by_to_be_staged->count, 1 ); $cp->mark_as_staged; - is( $cp->status, 'staged-and-ready' ); + is( $cp->status, 'staged-and-ready' ); is( $pickups->filter_by_staged_and_ready->count, 1 ); $cp->mark_as_unstaged; @@ -201,15 +196,15 @@ subtest 'workflow' => sub { $cp->mark_as_staged; $cp->mark_patron_has_arrived; - is( $cp->status, 'patron-is-outside' ); + is( $cp->status, 'patron-is-outside' ); is( $pickups->filter_by_patron_outside->count, 1 ); $cp->mark_as_delivered; - is( $cp->status, 'delivered' ); + is( $cp->status, 'delivered' ); is( $pickups->filter_by_delivered->count, 1 ); is( $pickups->filter_by_scheduled_today->count, 1 ); - $cp->scheduled_pickup_datetime($today->clone->subtract(days => 1))->store; + $cp->scheduled_pickup_datetime( $today->clone->subtract( days => 1 ) )->store; is( $pickups->filter_by_scheduled_today->count, 0 ); $cp->delete; @@ -218,7 +213,7 @@ subtest 'workflow' => sub { subtest 'mark_as_delivered' => sub { plan tests => 3; - my $item = $builder->build_sample_item({ library => $library->branchcode }); + my $item = $builder->build_sample_item( { library => $library->branchcode } ); my $reserve_id = C4::Reserves::AddReserve( { branchcode => $library->branchcode, @@ -231,10 +226,9 @@ subtest 'mark_as_delivered' => sub { my $hold = Koha::Holds->find($reserve_id); $hold->set_waiting; - my $next_monday = - $today->clone->add( days => ( 1 - $today->day_of_week ) % 7 ); + my $next_monday = $today->clone->add( days => ( 1 - $today->day_of_week ) % 7 ); my $schedule_dt = - $next_monday->set_hour(15)->set_minute(00)->set_second(00); + $next_monday->set_hour(15)->set_minute(00)->set_second(00); my $cp = Koha::CurbsidePickup->new( { branchcode => $library->branchcode, @@ -246,10 +240,10 @@ subtest 'mark_as_delivered' => sub { $cp->mark_as_delivered; $cp->discard_changes; - is( t::lib::Dates::compare( $cp->arrival_datetime, dt_from_string), 0, 'Arrival time has been set to now' ); + is( t::lib::Dates::compare( $cp->arrival_datetime, dt_from_string ), 0, 'Arrival time has been set to now' ); is( $hold->get_from_storage, undef, 'Hold has been filled' ); - my $checkout = Koha::Checkouts->find({ itemnumber => $item->itemnumber }); + my $checkout = Koha::Checkouts->find( { itemnumber => $item->itemnumber } ); is( $checkout->borrowernumber, $patron->borrowernumber, 'Item has correctly been checked out' ); $cp->delete; @@ -258,8 +252,7 @@ subtest 'mark_as_delivered' => sub { subtest 'notify_new_pickup' => sub { plan tests => 2; - my $item = - $builder->build_sample_item( { library => $library->branchcode } ); + my $item = $builder->build_sample_item( { library => $library->branchcode } ); my $reserve_id = C4::Reserves::AddReserve( { branchcode => $library->branchcode, @@ -272,10 +265,9 @@ subtest 'notify_new_pickup' => sub { my $hold = Koha::Holds->find($reserve_id); $hold->set_waiting; - my $next_monday = - $today->clone->add( days => ( 1 - $today->day_of_week ) % 7 ); + my $next_monday = $today->clone->add( days => ( 1 - $today->day_of_week ) % 7 ); my $schedule_dt = - $next_monday->set_hour(15)->set_minute(00)->set_second(00); + $next_monday->set_hour(15)->set_minute(00)->set_second(00); my $cp = Koha::CurbsidePickup->new( { branchcode => $library->branchcode, @@ -287,11 +279,11 @@ subtest 'notify_new_pickup' => sub { $patron->set( { email => 'test@example.org' } )->store; my $dbh = C4::Context->dbh; - $dbh->do( q|INSERT INTO borrower_message_preferences( borrowernumber, message_attribute_id ) VALUES ( ?, ?)|, + $dbh->do( + q|INSERT INTO borrower_message_preferences( borrowernumber, message_attribute_id ) VALUES ( ?, ?)|, undef, $patron->borrowernumber, 4 ); - my $borrower_message_preference_id = - $dbh->last_insert_id( undef, undef, "borrower_message_preferences", undef ); + my $borrower_message_preference_id = $dbh->last_insert_id( undef, undef, "borrower_message_preferences", undef ); $dbh->do( q|INSERT INTO borrower_message_transport_preferences( borrower_message_preference_id, message_transport_type) VALUES ( ?, ? )|, undef, $borrower_message_preference_id, 'email' @@ -299,16 +291,17 @@ subtest 'notify_new_pickup' => sub { $cp->notify_new_pickup; - my $messages = C4::Letters::GetQueuedMessages( - { borrowernumber => $patron->borrowernumber } ); + my $messages = C4::Letters::GetQueuedMessages( { borrowernumber => $patron->borrowernumber } ); is( $messages->[0]->{subject}, - sprintf ("You have scheduled a curbside pickup for %s", $library->branchname), + sprintf( "You have scheduled a curbside pickup for %s", $library->branchname ), "Notice correctly generated" ); my $biblio_title = $item->biblio->title; - like( $messages->[0]->{content}, - qr{$biblio_title}, "Content contains the list of waiting holds" ); + like( + $messages->[0]->{content}, + qr{$biblio_title}, "Content contains the list of waiting holds" + ); }; $schema->storage->txn_rollback; diff --git a/t/db_dependent/Koha/Database.t b/t/db_dependent/Koha/Database.t index 3543992e71..aca225f411 100755 --- a/t/db_dependent/Koha/Database.t +++ b/t/db_dependent/Koha/Database.t @@ -20,7 +20,7 @@ use Test::More tests => 4; use C4::Context; use t::lib::Mocks; -my $dbh = C4::Context->dbh; +my $dbh = C4::Context->dbh; my $sql_mode = $dbh->selectrow_array(q|SELECT @@SQL_MODE|); like( $sql_mode, qr{STRICT_TRANS_TABLES}, 'Strict SQL modes must be turned on for tests' ); @@ -29,10 +29,10 @@ is( $dbh->{RaiseError}, 1, 'RaiseError must be turned on for tests' ); subtest 'db_scheme2dbi' => sub { plan tests => 4; - is(Koha::Database::db_scheme2dbi('mysql'), 'mysql', 'ask for mysql, get mysql'); - is(Koha::Database::db_scheme2dbi('Pg'), 'Pg', 'ask for Pg, get Pg'); - is(Koha::Database::db_scheme2dbi('xxx'), 'mysql', 'ask for unsupported DBMS, get mysql'); - is(Koha::Database::db_scheme2dbi(), 'mysql', 'ask for nothing, get mysql'); + is( Koha::Database::db_scheme2dbi('mysql'), 'mysql', 'ask for mysql, get mysql' ); + is( Koha::Database::db_scheme2dbi('Pg'), 'Pg', 'ask for Pg, get Pg' ); + is( Koha::Database::db_scheme2dbi('xxx'), 'mysql', 'ask for unsupported DBMS, get mysql' ); + is( Koha::Database::db_scheme2dbi(), 'mysql', 'ask for nothing, get mysql' ); }; subtest 'generate_dsn' => sub { diff --git a/t/db_dependent/Koha/Database/Commenter.t b/t/db_dependent/Koha/Database/Commenter.t index 25bbeda010..de9161e2e1 100755 --- a/t/db_dependent/Koha/Database/Commenter.t +++ b/t/db_dependent/Koha/Database/Commenter.t @@ -10,28 +10,30 @@ use Koha::Database; use Koha::Database::Commenter; our $schema = Koha::Database->new->schema; -our $dbh = C4::Context->dbh; +our $dbh = C4::Context->dbh; our $mgr; subtest '->new, dry_run' => sub { plan tests => 9; - $schema->storage->txn_begin; # just cosmetic, no changes expected in a dry run + $schema->storage->txn_begin; # just cosmetic, no changes expected in a dry run # Two exceptions on dbh parameter throws_ok { Koha::Database::Commenter->new } 'Koha::Exceptions::MissingParameter', 'No dbh'; - throws_ok { Koha::Database::Commenter->new({ dbh => 'dbh' }) } 'Koha::Exceptions::WrongParameter', 'dbh no string'; + throws_ok { Koha::Database::Commenter->new( { dbh => 'dbh' } ) } 'Koha::Exceptions::WrongParameter', + 'dbh no string'; # Another exception: delete schema file and reset should raise exception my $filename = create_schema_file(); - $mgr = Koha::Database::Commenter->new({ dbh => $dbh, schema_file => $filename }); + $mgr = Koha::Database::Commenter->new( { dbh => $dbh, schema_file => $filename } ); unlink $filename; - throws_ok { $mgr->reset_to_schema({ dry_run => 1, table => 'biblio' }) } 'Koha::Exceptions::FileNotFound', 'Schema deleted'; + throws_ok { $mgr->reset_to_schema( { dry_run => 1, table => 'biblio' } ) } 'Koha::Exceptions::FileNotFound', + 'Schema deleted'; # Check case of columns from information_schema (MySQL8 defaults to uppercase) - my $columns = $mgr->_fetch_stored_comments({ table => 'article_requests' }); - ok( exists $columns->[0]->{table_name}, 'Check table_name column' ); - ok( exists $columns->[0]->{column_name}, 'Check column_name column' ); + my $columns = $mgr->_fetch_stored_comments( { table => 'article_requests' } ); + ok( exists $columns->[0]->{table_name}, 'Check table_name column' ); + ok( exists $columns->[0]->{column_name}, 'Check column_name column' ); ok( exists $columns->[0]->{column_comment}, 'Check column_comment column' ); # Clear comments for article_requests in dry run mode @@ -47,39 +49,45 @@ subtest '->new, dry_run' => sub { # Reset in dry run mode, first fix schema file again # Our fake schema contains only one column for article_requests now. $filename = create_schema_file(); - $mgr = Koha::Database::Commenter->new({ dbh => $dbh, schema_file => $filename }); + $mgr = Koha::Database::Commenter->new( { dbh => $dbh, schema_file => $filename } ); $messages = []; $mgr->reset_to_schema( { table => 'article_requests', dry_run => 1 }, $messages ); + # We expect an ALTER clearing toc_request first, followed by an ALTER adding comment. # Note: This is based on the fair assumption that toc_request had a comment! This test could fail if it had not. - like( join("\n", @$messages), qr/ALTER.*toc_request.*DEFAULT 0;(.*\n)+ALTER.*toc_request.*COMMENT.*$/m, 'Reset for one-columned article_requests' ); + like( + join( "\n", @$messages ), qr/ALTER.*toc_request.*DEFAULT 0;(.*\n)+ALTER.*toc_request.*COMMENT.*$/m, + 'Reset for one-columned article_requests' + ); $schema->storage->txn_rollback; }; subtest '->clear, ->reset, ->renumber' => sub { plan tests => 6; + #$schema->storage->txn_begin; # commented: DDL statements implicitly commit; we are testing only 1 new table here btw create_test_table1($dbh); - $mgr->clear({ table => 'database_commenter_1' }); - my $info = $mgr->_columns_info( 'database_commenter_1' ); - is( $info->{sometext}->{Comment}, q{}, 'Found no comment for sometext' ); + $mgr->clear( { table => 'database_commenter_1' } ); + my $info = $mgr->_columns_info('database_commenter_1'); + is( $info->{sometext}->{Comment}, q{}, 'Found no comment for sometext' ); is( $info->{anotherint}->{Comment}, q{}, 'Found no comment for anotherint' ); # Created temporary file serves as schema/kohastructure.sql now - $mgr->reset_to_schema({ table => 'database_commenter_1' }); - $info = $mgr->_columns_info( 'database_commenter_1' ); - is( $info->{sometext}->{Comment}, 'some nice quote\'s', 'Found comment for sometext' ); - is( $info->{anotherint}->{Comment}, 'my int', 'Found comment for anotherint' ); + $mgr->reset_to_schema( { table => 'database_commenter_1' } ); + $info = $mgr->_columns_info('database_commenter_1'); + is( $info->{sometext}->{Comment}, 'some nice quote\'s', 'Found comment for sometext' ); + is( $info->{anotherint}->{Comment}, 'my int', 'Found comment for anotherint' ); # Renumber follows alphabetical order - $mgr->renumber({ table => 'database_commenter_1' }); - $info = $mgr->_columns_info( 'database_commenter_1' ); + $mgr->renumber( { table => 'database_commenter_1' } ); + $info = $mgr->_columns_info('database_commenter_1'); is( $info->{anotherint}->{Comment}, 'Column_1', 'Found Column_1' ); is( $info->{timestamp2}->{Comment}, 'Column_5', 'Found Column_5' ); eval { $dbh->do('DROP TABLE database_commenter_1') }; + #$schema->storage->txn_rollback; # commented: DDL statements implicitly commit }; @@ -87,7 +95,7 @@ sub create_schema_file { my ( $fh, $filename ) = File::Temp::tempfile(); print $fh schema_table1(); print $fh "\n"; - print $fh schema_table2(); # fragment of Koha table + print $fh schema_table2(); # fragment of Koha table close $fh; return $filename; } @@ -102,13 +110,13 @@ sub schema_table1 { PRIMARY KEY (id) );|; } -sub schema_table2 { # only a fragment +sub schema_table2 { # only a fragment return q|CREATE TABLE article_requests ( `toc_request` tinyint(4) NOT NULL DEFAULT 0 COMMENT 'borrower requested table of contents')|; } sub create_test_table1 { - my ( $dbh ) = @_; + my ($dbh) = @_; eval { $dbh->do('DROP TABLE database_commenter_1') }; $dbh->do( schema_table1() ); } diff --git a/t/db_dependent/Koha/Desks.t b/t/db_dependent/Koha/Desks.t index 89814456ff..cf673517ea 100755 --- a/t/db_dependent/Koha/Desks.t +++ b/t/db_dependent/Koha/Desks.t @@ -33,22 +33,26 @@ my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; # Add CPL if missing. -if (not defined Koha::Libraries->find('CPL')) { - Koha::Library->new({ branchcode => 'CPL', branchname => 'Centerville' })->store; +if ( not defined Koha::Libraries->find('CPL') ) { + Koha::Library->new( { branchcode => 'CPL', branchname => 'Centerville' } )->store; } -my $builder = t::lib::TestBuilder->new; +my $builder = t::lib::TestBuilder->new; my $nb_of_desks = Koha::Desks->search->count; -my $new_desk_1 = Koha::Desk->new({ - desk_name => 'my_desk_name_for_test_1', - branchcode => 'CPL', -})->store; -my $new_desk_2 = Koha::Desk->new({ - desk_name => 'my_desk_name_for_test_2', - branchcode => 'CPL', -})->store; +my $new_desk_1 = Koha::Desk->new( + { + desk_name => 'my_desk_name_for_test_1', + branchcode => 'CPL', + } +)->store; +my $new_desk_2 = Koha::Desk->new( + { + desk_name => 'my_desk_name_for_test_2', + branchcode => 'CPL', + } +)->store; -like( $new_desk_1->desk_id, qr|^\d+$|, 'Adding a new desk should have set the desk_id'); +like( $new_desk_1->desk_id, qr|^\d+$|, 'Adding a new desk should have set the desk_id' ); is( Koha::Desks->search->count, $nb_of_desks + 2, 'The 2 desks should have been added' ); my $retrieved_desk_1 = Koha::Desks->find( $new_desk_1->desk_id ); diff --git a/t/db_dependent/Koha/ERM/Agreements.t b/t/db_dependent/Koha/ERM/Agreements.t index 6cbf8cac4d..a4a4fdddd9 100755 --- a/t/db_dependent/Koha/ERM/Agreements.t +++ b/t/db_dependent/Koha/ERM/Agreements.t @@ -34,15 +34,14 @@ subtest 'periods' => sub { $schema->storage->txn_begin; - my $agreement = - $builder->build_object( { class => 'Koha::ERM::Agreements' } ); + my $agreement = $builder->build_object( { class => 'Koha::ERM::Agreements' } ); is( $agreement->periods->count, 0, "no period yet" ); my $today = dt_from_string; my $periods = [ { started_on => $today->ymd, - ended_on => $today->clone->add( days => 1 )->ymd, + ended_on => $today->clone->add( days => 1 )->ymd, cancellation_deadline => $today->clone->add( years => 1 )->ymd, notes => 'just some notes' }, @@ -59,8 +58,7 @@ subtest 'periods' => sub { my $retrieved_periods = $agreement->periods; is( ref($retrieved_periods), 'Koha::ERM::Agreement::Periods' ); $retrieved_periods = - [ map { delete $_->{agreement_id}; delete $_->{agreement_period_id}; $_ } - @{ $retrieved_periods->unblessed } ]; + [ map { delete $_->{agreement_id}; delete $_->{agreement_period_id}; $_ } @{ $retrieved_periods->unblessed } ]; is_deeply( $retrieved_periods, $periods ); $agreement->periods( [] ); is( $agreement->periods->count, 0 ); @@ -74,8 +72,7 @@ subtest 'user_role' => sub { $schema->storage->txn_begin; - my $agreement = - $builder->build_object( { class => 'Koha::ERM::Agreements' } ); + my $agreement = $builder->build_object( { class => 'Koha::ERM::Agreements' } ); is( $agreement->user_roles->count, 0, "no user yet" ); my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); @@ -94,9 +91,9 @@ subtest 'user_role' => sub { my $user_roles = [ { - user_id => $patron->borrowernumber, + user_id => $patron->borrowernumber, license_id => undef, - role => $role + role => $role } ]; $agreement->user_roles($user_roles); @@ -104,8 +101,7 @@ subtest 'user_role' => sub { my $retrieved_user_roles = $agreement->user_roles; is( ref($retrieved_user_roles), 'Koha::ERM::UserRoles' ); $retrieved_user_roles = - [ map { delete $_->{agreement_id}; delete $_->{user_role_id}; $_ } - @{ $retrieved_user_roles->unblessed } ]; + [ map { delete $_->{agreement_id}; delete $_->{user_role_id}; $_ } @{ $retrieved_user_roles->unblessed } ]; is_deeply( $retrieved_user_roles, $user_roles ); $agreement->user_roles( [] ); is( $agreement->user_roles->count, 0 ); diff --git a/t/db_dependent/Koha/ERM/EUsage/UsageDataProvider.t b/t/db_dependent/Koha/ERM/EUsage/UsageDataProvider.t index 941bfe351d..874141f081 100755 --- a/t/db_dependent/Koha/ERM/EUsage/UsageDataProvider.t +++ b/t/db_dependent/Koha/ERM/EUsage/UsageDataProvider.t @@ -45,8 +45,8 @@ subtest '_build_url_query' => sub { { class => 'Koha::ERM::EUsage::UsageDataProviders', value => { - service_url => $service_url, api_key => $api_key, requestor_id => $requestor_id, - customer_id => $customer_id, name => $name, service_platform => undef + service_url => $service_url, api_key => $api_key, requestor_id => $requestor_id, + customer_id => $customer_id, name => $name, service_platform => undef } } ); @@ -78,8 +78,8 @@ subtest '_build_url_query' => sub { { class => 'Koha::ERM::EUsage::UsageDataProviders', value => { - service_url => $service_url, api_key => $api_key, requestor_id => $requestor_id, - customer_id => $customer_id, name => $name, service_platform => $test_platform + service_url => $service_url, api_key => $api_key, requestor_id => $requestor_id, + customer_id => $customer_id, name => $name, service_platform => $test_platform } } ); diff --git a/t/db_dependent/Koha/Edifact/Order.t b/t/db_dependent/Koha/Edifact/Order.t index 3630a8172d..23c990ad0b 100755 --- a/t/db_dependent/Koha/Edifact/Order.t +++ b/t/db_dependent/Koha/Edifact/Order.t @@ -35,7 +35,7 @@ subtest 'beggining_of_message tests' => sub { $schema->storage->txn_begin; - my $basketno = sprintf '%011d', '123456'; + my $basketno = sprintf '%011d', '123456'; my $edi_vendor = $builder->build( { source => 'VendorEdiAccount', @@ -44,28 +44,29 @@ subtest 'beggining_of_message tests' => sub { } } ); - my $dbic_edi_vendor = $schema->resultset('VendorEdiAccount')->find($edi_vendor->{id}); + my $dbic_edi_vendor = $schema->resultset('VendorEdiAccount')->find( $edi_vendor->{id} ); - my $bgm = Koha::Edifact::Order::beginning_of_message($basketno, $dbic_edi_vendor->standard, 1); - is( $bgm, qq{BGM+220+$basketno+9'}, "When vendor is set to EDItEUR standard we use 220 in BGM segment"); + my $bgm = Koha::Edifact::Order::beginning_of_message( $basketno, $dbic_edi_vendor->standard, 1 ); + is( $bgm, qq{BGM+220+$basketno+9'}, "When vendor is set to EDItEUR standard we use 220 in BGM segment" ); - $dbic_edi_vendor->update({ standard => 'BIC'}); - $bgm = Koha::Edifact::Order::beginning_of_message($basketno, $dbic_edi_vendor->standard, 1); - is( $bgm, qq{BGM+22V+$basketno+9'}, "When vendor is set to BiC standard we use 22V in BGM segment"); + $dbic_edi_vendor->update( { standard => 'BIC' } ); + $bgm = Koha::Edifact::Order::beginning_of_message( $basketno, $dbic_edi_vendor->standard, 1 ); + is( $bgm, qq{BGM+22V+$basketno+9'}, "When vendor is set to BiC standard we use 22V in BGM segment" ); $schema->storage->txn_rollback; }; subtest 'order_line() tests' => sub { + # TODO: Split up order_line() to smaller methods in order # to allow better testing plan tests => 27; $schema->storage->txn_begin; - my $biblio = $builder->build_sample_biblio(); + my $biblio = $builder->build_sample_biblio(); my $biblioitem = $biblio->biblioitem; - $biblioitem->update({ isbn => '979-8572072303' }); + $biblioitem->update( { isbn => '979-8572072303' } ); my $biblioitem_itype = $biblioitem->itemtype; my $item1 = $builder->build_sample_item( @@ -77,8 +78,8 @@ subtest 'order_line() tests' => sub { } ); my $item1_homebranch = $item1->homebranch; - my $item1_itype = $item1->effective_itemtype; - my $item2 = $builder->build_sample_item( + my $item1_itype = $item1->effective_itemtype; + my $item2 = $builder->build_sample_item( { biblionumber => $biblio->biblionumber, location => 'PROCESSING', @@ -87,29 +88,29 @@ subtest 'order_line() tests' => sub { } ); my $item2_homebranch = $item2->homebranch; - my $item2_itype = $item2->effective_itemtype; + my $item2_itype = $item2->effective_itemtype; - my $ean = $builder->build( { source => 'EdifactEan' } ); - my $dbic_ean = $schema->resultset('EdifactEan')->find($ean->{ee_id}); - my $order = $builder->build_object( + my $ean = $builder->build( { source => 'EdifactEan' } ); + my $dbic_ean = $schema->resultset('EdifactEan')->find( $ean->{ee_id} ); + my $order = $builder->build_object( { class => 'Koha::Acquisition::Orders', value => { - biblionumber => $biblio->biblionumber, - quantity => 2, - line_item_id => 'EDILINEID1', + biblionumber => $biblio->biblionumber, + quantity => 2, + line_item_id => 'EDILINEID1', order_vendornote => 'A not so pretty note', - listprice => '1.50' + listprice => '1.50' } } ); - my $ordernumber = $order->ordernumber; - my $supplier_qualifier = $order->suppliers_reference_qualifier; + my $ordernumber = $order->ordernumber; + my $supplier_qualifier = $order->suppliers_reference_qualifier; my $supplier_ordernumber = $order->suppliers_reference_number; - my $budgetcode = $order->fund->budget_code; - my $deliveryplace = $order->basket->deliveryplace; - $order->add_item($item1->itemnumber); - $order->add_item($item2->itemnumber); + my $budgetcode = $order->fund->budget_code; + my $deliveryplace = $order->basket->deliveryplace; + $order->add_item( $item1->itemnumber ); + $order->add_item( $item2->itemnumber ); my $vendor = $builder->build( { @@ -119,10 +120,9 @@ subtest 'order_line() tests' => sub { } } ); - my $dbic_vendor = $schema->resultset('VendorEdiAccount')->find($vendor->{id}); + my $dbic_vendor = $schema->resultset('VendorEdiAccount')->find( $vendor->{id} ); - my @orders = $schema->resultset('Aqorder') - ->search( { basketno => $order->basket->basketno } )->all; + my @orders = $schema->resultset('Aqorder')->search( { basketno => $order->basket->basketno } )->all; my $edi_order = Koha::Edifact::Order->new( { @@ -138,77 +138,77 @@ subtest 'order_line() tests' => sub { t::lib::Mocks::mock_preference( 'EdifactLSQ', 'location' ); $order->basket->create_items('ordering')->store; - is( $edi_order->order_line( 1, $orders[0] ), - undef, 'order_line run for message formed with effective_create_items = "ordering"' ); + is( + $edi_order->order_line( 1, $orders[0] ), + undef, 'order_line run for message formed with effective_create_items = "ordering"' + ); my $segs = $edi_order->{segs}; - is( $segs->[0], 'LIN+1++EDILINEID1:EN\'', 'LIN segment added containing order->line_item_id' ); - is( $segs->[1], 'PIA+5+8572072303:IB\'', 'PIA segment added with example biblioitem->isbn13' ); + is( $segs->[0], 'LIN+1++EDILINEID1:EN\'', 'LIN segment added containing order->line_item_id' ); + is( $segs->[1], 'PIA+5+8572072303:IB\'', 'PIA segment added with example biblioitem->isbn13' ); is( $segs->[2], 'IMD+L+009+:::Some boring author\'', 'IMD segment added containing demo data author' ); - is( $segs->[3], 'IMD+L+050+:::Some boring read\'', 'IMD segment added containing demo data title' ); - is( $segs->[4], 'QTY+21:2\'', 'QTY segment added containing the number of items expected' ); + is( $segs->[3], 'IMD+L+050+:::Some boring read\'', 'IMD segment added containing demo data title' ); + is( $segs->[4], 'QTY+21:2\'', 'QTY segment added containing the number of items expected' ); is( $segs->[5], 'GIR+001' - . "+$budgetcode:LFN" - . "+$item1_homebranch:LLO" - . "+$item1_itype:LST" - . "+PROCESSING:LSQ" - . "+000.101:LSM" - . "'", + . "+$budgetcode:LFN" + . "+$item1_homebranch:LLO" + . "+$item1_itype:LST" + . "+PROCESSING:LSQ" + . "+000.101:LSM" . "'", 'GIR segment added for first item and contains item record data' ); is( $segs->[6], 'GIR+002' - . "+$budgetcode:LFN" - . "+$item2_homebranch:LLO" - . "+$item2_itype:LST" - . "+PROCESSING:LSQ" - . "+000.102:LSM" - . "'", + . "+$budgetcode:LFN" + . "+$item2_homebranch:LLO" + . "+$item2_itype:LST" + . "+PROCESSING:LSQ" + . "+000.102:LSM" . "'", 'GIR segment added for second item and contains item record data' ); is( $segs->[7], 'FTX+LIN+++A not so pretty note\'', 'FTX segment added containing data from vendor_note' ); - is( $segs->[8], 'PRI+AAE:1.50:CA\'', 'PRI segment added containing data orderline listprice' ); - is( $segs->[9], "RFF+LI:$ordernumber'", 'RFF segment added containing koha orderline id' ); - is( $segs->[10], "RFF+$supplier_qualifier:$supplier_ordernumber'", 'RFF segment added containing supplier orderline id' ); + is( $segs->[8], 'PRI+AAE:1.50:CA\'', 'PRI segment added containing data orderline listprice' ); + is( $segs->[9], "RFF+LI:$ordernumber'", 'RFF segment added containing koha orderline id' ); + is( + $segs->[10], "RFF+$supplier_qualifier:$supplier_ordernumber'", + 'RFF segment added containing supplier orderline id' + ); # Reset segments for effective_create_items = 'receiving' $edi_order->{segs} = []; $order->basket->create_items('receiving')->store; - is( $edi_order->order_line( 1, $orders[0] ), - undef, 'order_line run for message formed with effective_create_items = "receiving"' ); + is( + $edi_order->order_line( 1, $orders[0] ), + undef, 'order_line run for message formed with effective_create_items = "receiving"' + ); $segs = $edi_order->{segs}; - is( $segs->[0], 'LIN+1++EDILINEID1:EN\'', 'LIN segment added containing order->line_item_id' ); - is( $segs->[1], 'PIA+5+8572072303:IB\'', 'PIA segment added with example biblioitem->isbn13' ); + is( $segs->[0], 'LIN+1++EDILINEID1:EN\'', 'LIN segment added containing order->line_item_id' ); + is( $segs->[1], 'PIA+5+8572072303:IB\'', 'PIA segment added with example biblioitem->isbn13' ); is( $segs->[2], 'IMD+L+009+:::Some boring author\'', 'IMD segment added containing demo data author' ); - is( $segs->[3], 'IMD+L+050+:::Some boring read\'', 'IMD segment added containing demo data title' ); - is( $segs->[4], 'QTY+21:2\'', 'QTY segment added containing the number of items expected' ); + is( $segs->[3], 'IMD+L+050+:::Some boring read\'', 'IMD segment added containing demo data title' ); + is( $segs->[4], 'QTY+21:2\'', 'QTY segment added containing the number of items expected' ); is( $segs->[5], - 'GIR+001' - . "+$budgetcode:LFN" - . "+$deliveryplace:LLO" - . "+$biblioitem_itype:LST" - . "'", + 'GIR+001' . "+$budgetcode:LFN" . "+$deliveryplace:LLO" . "+$biblioitem_itype:LST" . "'", 'GIR segment added for first item and contains biblioitem data' ); is( $segs->[6], - 'GIR+002' - . "+$budgetcode:LFN" - . "+$deliveryplace:LLO" - . "+$biblioitem_itype:LST" - . "'", + 'GIR+002' . "+$budgetcode:LFN" . "+$deliveryplace:LLO" . "+$biblioitem_itype:LST" . "'", 'GIR segment added for second item and contains biblioitem data' ); is( $segs->[7], 'FTX+LIN+++A not so pretty note\'', 'FTX segment added containing data from vendor_note' ); - is( $segs->[8], 'PRI+AAE:1.50:CA\'', 'PRI segment added containing data orderline listprice' ); - is( $segs->[9], "RFF+LI:$ordernumber'", 'RFF segment added containing koha orderline id' ); - is( $segs->[10], "RFF+$supplier_qualifier:$supplier_ordernumber'", 'RFF segment added containing supplier orderline id' ); + is( $segs->[8], 'PRI+AAE:1.50:CA\'', 'PRI segment added containing data orderline listprice' ); + is( $segs->[9], "RFF+LI:$ordernumber'", 'RFF segment added containing koha orderline id' ); + is( + $segs->[10], "RFF+$supplier_qualifier:$supplier_ordernumber'", + 'RFF segment added containing supplier orderline id' + ); # Reset segments for testing EdifactLSQ preference $edi_order->{segs} = []; @@ -217,30 +217,30 @@ subtest 'order_line() tests' => sub { t::lib::Mocks::mock_preference( 'EdifactLSQ', 'ccode' ); $order->basket->create_items('ordering')->store; - is( $edi_order->order_line( 1, $orders[0] ), - undef, 'order_line run for message formed with EdifactLSQ = "ccode"' ); + is( + $edi_order->order_line( 1, $orders[0] ), + undef, 'order_line run for message formed with EdifactLSQ = "ccode"' + ); $segs = $edi_order->{segs}; is( $segs->[5], 'GIR+001' - . "+$budgetcode:LFN" - . "+$item1_homebranch:LLO" - . "+$item1_itype:LST" - . "+COLLECTION:LSQ" - . "+000.101:LSM" - . "'", + . "+$budgetcode:LFN" + . "+$item1_homebranch:LLO" + . "+$item1_itype:LST" + . "+COLLECTION:LSQ" + . "+000.101:LSM" . "'", 'GIR segment added for first item and contains item ccode data' ); is( $segs->[6], 'GIR+002' - . "+$budgetcode:LFN" - . "+$item2_homebranch:LLO" - . "+$item2_itype:LST" - . "+COLLECTION:LSQ" - . "+000.102:LSM" - . "'", + . "+$budgetcode:LFN" + . "+$item2_homebranch:LLO" + . "+$item2_itype:LST" + . "+COLLECTION:LSQ" + . "+000.102:LSM" . "'", 'GIR segment added for second item and contains item ccode data' ); @@ -252,9 +252,8 @@ subtest 'filename() tests' => sub { $schema->storage->txn_begin; - my $ean = $builder->build( { source => 'EdifactEan' } ); - my $order = - $builder->build_object( { class => 'Koha::Acquisition::Orders' } ); + my $ean = $builder->build( { source => 'EdifactEan' } ); + my $order = $builder->build_object( { class => 'Koha::Acquisition::Orders' } ); my $vendor = $builder->build( { source => 'VendorEdiAccount', @@ -262,8 +261,7 @@ subtest 'filename() tests' => sub { } ); - my @orders = $schema->resultset('Aqorder') - ->search( { basketno => $order->basket->basketno } )->all; + my @orders = $schema->resultset('Aqorder')->search( { basketno => $order->basket->basketno } )->all; my $edi_order = Koha::Edifact::Order->new( { @@ -274,8 +272,10 @@ subtest 'filename() tests' => sub { ); my $expected_filename = 'ordr' . $order->basket->basketno . '.CEP'; - is( $edi_order->filename, $expected_filename, - 'Filename is formed from the basket number' ); + is( + $edi_order->filename, $expected_filename, + 'Filename is formed from the basket number' + ); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/Koha/Encryption.t b/t/db_dependent/Koha/Encryption.t index cc133c79c0..eee199404e 100755 --- a/t/db_dependent/Koha/Encryption.t +++ b/t/db_dependent/Koha/Encryption.t @@ -5,14 +5,14 @@ use Test::Exception; use t::lib::Mocks; use Koha::Encryption; -t::lib::Mocks::mock_config('encryption_key', 'my secret passphrase'); +t::lib::Mocks::mock_config( 'encryption_key', 'my secret passphrase' ); my $string = 'a string to encrypt'; -my $crypt = Koha::Encryption->new; +my $crypt = Koha::Encryption->new; my $encrypted_string = $crypt->encrypt_hex($string); is( $crypt->decrypt_hex($encrypted_string), $string, 'Decrypted to original text' ); # Check if exception raised when key is empty or missing -t::lib::Mocks::mock_config('encryption_key', ''); +t::lib::Mocks::mock_config( 'encryption_key', '' ); throws_ok { $crypt = Koha::Encryption->new } 'Koha::Exceptions::MissingParameter', 'Exception raised'; diff --git a/t/db_dependent/Koha/Filter/EmbedItems.t b/t/db_dependent/Koha/Filter/EmbedItems.t index 524bfb5f34..179a437049 100755 --- a/t/db_dependent/Koha/Filter/EmbedItems.t +++ b/t/db_dependent/Koha/Filter/EmbedItems.t @@ -38,10 +38,10 @@ subtest 'EmbedItems tests' => sub { # Add a biblio my $biblio = $builder->build_sample_biblio; foreach ( 1 .. 10 ) { - $builder->build_sample_item({ biblionumber => $biblio->biblionumber }); + $builder->build_sample_item( { biblionumber => $biblio->biblionumber } ); } - my $mss = C4::Biblio::GetMarcSubfieldStructure( '', { unsafe => 0 } ); + my $mss = C4::Biblio::GetMarcSubfieldStructure( '', { unsafe => 0 } ); my $item_tag = $mss->{'items.itemnumber'}[0]->{tagfield}; $biblio->discard_changes; @@ -50,16 +50,14 @@ subtest 'EmbedItems tests' => sub { my $processor = Koha::RecordProcessor->new( { - schema => 'MARC', + schema => 'MARC', filters => ('EmbedItems'), - options => { - items => \@items - } + options => { items => \@items } } ); is( ref($processor), 'Koha::RecordProcessor', 'Created record processor' ); - my $result = $processor->process( $record ); + my $result = $processor->process($record); is( ref($result), 'MARC::Record', 'It returns a reference to a MARC::Record object' ); my @item_fields = $record->field($item_tag); diff --git a/t/db_dependent/Koha/Filter/EmbedItemsAvailability.t b/t/db_dependent/Koha/Filter/EmbedItemsAvailability.t index ef1249eec6..c66e4e400f 100755 --- a/t/db_dependent/Koha/Filter/EmbedItemsAvailability.t +++ b/t/db_dependent/Koha/Filter/EmbedItemsAvailability.t @@ -40,27 +40,28 @@ subtest 'EmbedItemsAvailability tests' => sub { $schema->storage->txn_begin(); my $biblio = Test::MockModule->new('C4::Biblio'); - $biblio->mock( 'GetMarcFromKohaField', sub { - my ( $kohafield ) = @_; - if ( $kohafield eq 'biblio.biblionumber' ) { - if ( C4::Context->preference('marcflavour') eq 'UNIMARC' ) { - return ( '001', '@' ); - } - else { - return ( '999', 'c' ); + $biblio->mock( + 'GetMarcFromKohaField', + sub { + my ($kohafield) = @_; + if ( $kohafield eq 'biblio.biblionumber' ) { + if ( C4::Context->preference('marcflavour') eq 'UNIMARC' ) { + return ( '001', '@' ); + } else { + return ( '999', 'c' ); + } + } else { + my $func_ref = $biblio->original('GetMarcFromKohaField'); + &$func_ref($kohafield); } } - else { - my $func_ref = $biblio->original( 'GetMarcFromKohaField' ); - &$func_ref( $kohafield ); - } - }); + ); # MARC21 tests t::lib::Mocks::mock_preference( 'marcflavour', 'MARC21' ); # Create a dummy record - my ( $biblionumber, $biblioitemnumber ) = AddBiblio(MARC::Record->new(), ''); + my ( $biblionumber, $biblioitemnumber ) = AddBiblio( MARC::Record->new(), '' ); # Add some items with different onloan values $builder->build_sample_item( @@ -86,11 +87,12 @@ subtest 'EmbedItemsAvailability tests' => sub { is( ref($processor), 'Koha::RecordProcessor', 'Created record processor' ); my $biblio_object = Koha::Biblios->find($biblionumber); - my $record = $biblio_object->metadata->record; + my $record = $biblio_object->metadata->record; ok( !defined $record->field('999')->subfield('x'), q{The record doesn't originally contain 999$x} ); + # Apply filter $processor->process($record); - is($record->field('999')->subfield('x'), 1, 'There is only one item with undef onloan'); + is( $record->field('999')->subfield('x'), 1, 'There is only one item with undef onloan' ); $schema->storage->txn_rollback(); @@ -100,7 +102,7 @@ subtest 'EmbedItemsAvailability tests' => sub { $schema->storage->txn_begin(); # Create a dummy record - ( $biblionumber, $biblioitemnumber ) = AddBiblio(MARC::Record->new(), ''); + ( $biblionumber, $biblioitemnumber ) = AddBiblio( MARC::Record->new(), '' ); # Add some items with different onloan values $builder->build_sample_item( @@ -126,11 +128,12 @@ subtest 'EmbedItemsAvailability tests' => sub { is( ref($processor), 'Koha::RecordProcessor', 'Created record processor' ); $biblio_object = Koha::Biblios->find($biblionumber); - $record = $biblio_object->metadata->record; - ok( !defined $record->subfield('999', 'x'), q{The record doesn't originally contain 999$x} ); + $record = $biblio_object->metadata->record; + ok( !defined $record->subfield( '999', 'x' ), q{The record doesn't originally contain 999$x} ); + # Apply filter $processor->process($record); - is($record->subfield('999', 'x'), 1, 'There is only one item with undef onloan'); + is( $record->subfield( '999', 'x' ), 1, 'There is only one item with undef onloan' ); $schema->storage->txn_rollback(); }; diff --git a/t/db_dependent/Koha/Filter/ExpandCodedFields.t b/t/db_dependent/Koha/Filter/ExpandCodedFields.t index ac33dc9a14..b0a623dfc2 100755 --- a/t/db_dependent/Koha/Filter/ExpandCodedFields.t +++ b/t/db_dependent/Koha/Filter/ExpandCodedFields.t @@ -61,19 +61,21 @@ subtest 'ExpandCodedFields tests' => sub { MARC::Field->new( '590', '', '', a => $av->authorised_value ), ); - my $mss = Koha::MarcSubfieldStructures->find({tagfield => "590", tagsubfield => "a", frameworkcode => $biblio->frameworkcode }); + my $mss = Koha::MarcSubfieldStructures->find( + { tagfield => "590", tagsubfield => "a", frameworkcode => $biblio->frameworkcode } ); $mss->update( { authorised_value => $av->category } ); my $cache = Koha::Caches->get_instance; $cache->clear_from_cache("MarcCodedFields-"); + # Clear GetAuthorisedValueDesc-generated cache $cache->clear_from_cache("libraries:name"); $cache->clear_from_cache("itemtype:description:en"); $cache->clear_from_cache("cn_sources:description"); - $cache->clear_from_cache("AV_descriptions:" . $av->category); + $cache->clear_from_cache( "AV_descriptions:" . $av->category ); C4::Biblio::ModBiblio( $record, $biblio->biblionumber ); - $biblio = Koha::Biblios->find( $biblio->biblionumber); + $biblio = Koha::Biblios->find( $biblio->biblionumber ); $record = $biblio->metadata->record; # Embed an item to test for branchcode and itemtype expansions @@ -86,11 +88,16 @@ subtest 'ExpandCodedFields tests' => sub { ), ); - is( $record->field('590')->subfield('a'), $av->authorised_value, 'Record prior to filtering contains AV Code' ); is( $record->field('942')->subfield('n'), 1, 'Record suppression is numeric prior to filtering' ); - is( $record->field('952')->subfield('a'), $homebranch->branchcode, 'Record prior to filtering contains homebranch branchcode' ); - is( $record->field('952')->subfield('b'), $holdingbranch->branchcode, 'Record prior to filtering contains holdingbranch branchcode' ); + is( + $record->field('952')->subfield('a'), $homebranch->branchcode, + 'Record prior to filtering contains homebranch branchcode' + ); + is( + $record->field('952')->subfield('b'), $holdingbranch->branchcode, + 'Record prior to filtering contains holdingbranch branchcode' + ); is( $record->field('952')->subfield('y'), $itemtype->itemtype, 'Record prior to filtering contains itemtype code' ); my $processor = Koha::RecordProcessor->new( @@ -101,13 +108,22 @@ subtest 'ExpandCodedFields tests' => sub { ); is( ref($processor), 'Koha::RecordProcessor', 'Created record processor with ExpandCodedFields filter' ); - my $result = $processor->process( $record ); + my $result = $processor->process($record); is( ref($result), 'MARC::Record', 'It returns a reference to a MARC::Record object' ); - is( $result->field('590')->subfield('a'), $av->lib_opac, 'Returned record contains AV OPAC description (interface defaults to opac)' ); - is( $record->field('590')->subfield('a'), $av->lib_opac, 'Original record now contains AV OPAC description (interface defaults to opac)' ); + is( + $result->field('590')->subfield('a'), $av->lib_opac, + 'Returned record contains AV OPAC description (interface defaults to opac)' + ); + is( + $record->field('590')->subfield('a'), $av->lib_opac, + 'Original record now contains AV OPAC description (interface defaults to opac)' + ); is( $record->field('942')->subfield('n'), 1, 'Record suppression is still numeric after filtering' ); is( $record->field('952')->subfield('a'), $homebranch->branchname, 'Record now contains homebranch branchname' ); - is( $record->field('952')->subfield('b'), $holdingbranch->branchname, 'Record now contains holdingbranch branchname' ); + is( + $record->field('952')->subfield('b'), $holdingbranch->branchname, + 'Record now contains holdingbranch branchname' + ); is( $record->field('952')->subfield('y'), $itemtype->description, 'Record now contains itemtype description' ); # reset record for next test @@ -115,9 +131,12 @@ subtest 'ExpandCodedFields tests' => sub { is( $record->field('590')->subfield('a'), $av->authorised_value, 'Record reset contains AV Code' ); # set interface - $processor->options({ interface => 'intranet' }); - $result = $processor->process( $record ); - is( $record->field('590')->subfield('a'), $av->lib, 'Original record now contains AV description (interface set to intranet)' ); + $processor->options( { interface => 'intranet' } ); + $result = $processor->process($record); + is( + $record->field('590')->subfield('a'), $av->lib, + 'Original record now contains AV description (interface set to intranet)' + ); is( $record->field('942')->subfield('n'), 1, 'Item suppression field remains numeric after filtering' ); $schema->storage->txn_rollback(); diff --git a/t/db_dependent/Koha/Hold.t b/t/db_dependent/Koha/Hold.t index e8d1dc5155..527b6988f7 100755 --- a/t/db_dependent/Koha/Hold.t +++ b/t/db_dependent/Koha/Hold.t @@ -55,14 +55,14 @@ subtest 'store() tests' => sub { )->store } 'Koha::Exceptions::Hold::MissingPickupLocation', - 'Exception thrown because branchcode was not passed'; + 'Exception thrown because branchcode was not passed'; my $hold = $builder->build_object( { class => 'Koha::Holds' } ); throws_ok { $hold->branchcode(undef)->store; } 'Koha::Exceptions::Hold::MissingPickupLocation', - 'Exception thrown if one tries to set branchcode to null'; + 'Exception thrown if one tries to set branchcode to null'; $schema->storage->txn_rollback; }; @@ -144,35 +144,41 @@ subtest 'fill() tests' => sub { t::lib::Mocks::mock_preference( 'HoldFeeMode', 'any_time_is_collected' ); t::lib::Mocks::mock_preference( 'HoldsLog', 1 ); - t::lib::Mocks::mock_userenv( - { patron => $manager, branchcode => $manager->branchcode } ); + t::lib::Mocks::mock_userenv( { patron => $manager, branchcode => $manager->branchcode } ); my $interface = 'api'; C4::Context->interface($interface); my $hold_timestamp = $hold->timestamp; - my $ret = $hold->fill; + my $ret = $hold->fill; is( ref($ret), 'Koha::Hold', '->fill returns the object type' ); - is( $ret->id, $hold->id, '->fill returns the object' ); + is( $ret->id, $hold->id, '->fill returns the object' ); - is( Koha::Holds->find($hold->id), undef, 'Hold no longer current' ); + is( Koha::Holds->find( $hold->id ), undef, 'Hold no longer current' ); my $old_hold = Koha::Old::Holds->find( $hold->id ); - is( $old_hold->id, $hold->id, 'reserve_id retained' ); - is( $old_hold->priority, 0, 'priority set to 0' ); + is( $old_hold->id, $hold->id, 'reserve_id retained' ); + is( $old_hold->priority, 0, 'priority set to 0' ); isnt( $old_hold->timestamp, $hold_timestamp, 'timestamp updated' ); is( $old_hold->found, 'F', 'found set to F' ); subtest 'item_id parameter' => sub { plan tests => 1; - $category->reservefee(0)->store; # do not disturb later accounts - $hold = $builder->build_object({ class => 'Koha::Holds', value => { biblionumber => $biblio->id, borrowernumber => $patron->id, itemnumber => undef, priority => 1 } }); + $category->reservefee(0)->store; # do not disturb later accounts + $hold = $builder->build_object( + { + class => 'Koha::Holds', + value => + { biblionumber => $biblio->id, borrowernumber => $patron->id, itemnumber => undef, priority => 1 } + } + ); + # Simulating checkout without confirming hold - $hold->fill({ item_id => $item->id }); - $old_hold = Koha::Old::Holds->find($hold->id); + $hold->fill( { item_id => $item->id } ); + $old_hold = Koha::Old::Holds->find( $hold->id ); is( $old_hold->itemnumber, $item->itemnumber, 'The itemnumber has been saved in old_reserves by fill' ); $old_hold->delete; - $category->reservefee($fee)->store; # restore + $category->reservefee($fee)->store; # restore }; subtest 'fee applied tests' => sub { @@ -187,18 +193,30 @@ subtest 'fill() tests' => sub { my $fee_debit = $debits->next; is( $fee_debit->amount * 1, $fee, 'Fee amount stored correctly' ); - is( $fee_debit->description, $title, - 'Fee description stored correctly' ); - is( $fee_debit->manager_id, $manager->id, - 'Fee manager_id stored correctly' ); - is( $fee_debit->branchcode, $manager->branchcode, - 'Fee branchcode stored correctly' ); - is( $fee_debit->interface, $interface, - 'Fee interface stored correctly' ); - is( $fee_debit->debit_type_code, - 'RESERVE', 'Fee debit_type_code stored correctly' ); - is( $fee_debit->itemnumber, $item->id, - 'Fee itemnumber stored correctly' ); + is( + $fee_debit->description, $title, + 'Fee description stored correctly' + ); + is( + $fee_debit->manager_id, $manager->id, + 'Fee manager_id stored correctly' + ); + is( + $fee_debit->branchcode, $manager->branchcode, + 'Fee branchcode stored correctly' + ); + is( + $fee_debit->interface, $interface, + 'Fee interface stored correctly' + ); + is( + $fee_debit->debit_type_code, + 'RESERVE', 'Fee debit_type_code stored correctly' + ); + is( + $fee_debit->itemnumber, $item->id, + 'Fee itemnumber stored correctly' + ); }; my $logs = Koha::ActionLogs->search( @@ -213,8 +231,9 @@ subtest 'fill() tests' => sub { # Set HoldFeeMode to something other than any_time_is_collected t::lib::Mocks::mock_preference( 'HoldFeeMode', 'not_always' ); + # Disable logging - t::lib::Mocks::mock_preference( 'HoldsLog', 0 ); + t::lib::Mocks::mock_preference( 'HoldsLog', 0 ); $hold = $builder->build_object( { @@ -253,6 +272,7 @@ subtest 'fill() tests' => sub { # reduce the tests noise t::lib::Mocks::mock_preference( 'HoldsLog', 0 ); t::lib::Mocks::mock_preference( 'HoldFeeMode', 'not_always' ); + # unset AnonymousPatron t::lib::Mocks::mock_preference( 'AnonymousPatron', undef ); @@ -265,8 +285,10 @@ subtest 'fill() tests' => sub { } ); $hold->fill(); - is( Koha::Old::Holds->find( $hold->id )->borrowernumber, - $patron->borrowernumber, 'Patron link is kept' ); + is( + Koha::Old::Holds->find( $hold->id )->borrowernumber, + $patron->borrowernumber, 'Patron link is kept' + ); # 1 == "default", meaning it is not protected from removal $patron->privacy(1)->store; @@ -277,11 +299,14 @@ subtest 'fill() tests' => sub { } ); $hold->fill(); - is( Koha::Old::Holds->find( $hold->id )->borrowernumber, - $patron->borrowernumber, 'Patron link is kept' ); + is( + Koha::Old::Holds->find( $hold->id )->borrowernumber, + $patron->borrowernumber, 'Patron link is kept' + ); - my $anonymous_patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $anonymous_patron = $builder->build_object( { class => 'Koha::Patrons' } ); t::lib::Mocks::mock_preference( 'AnonymousPatron', $anonymous_patron->id ); + # We need anonymous patron set to change patron privacy to never # (2 == delete immediately) # then we can undef for further tests @@ -294,12 +319,11 @@ subtest 'fill() tests' => sub { } ); - throws_ok - { $hold->fill(); } - 'Koha::Exception', + throws_ok { $hold->fill(); } + 'Koha::Exception', 'AnonymousPatron not set, exception thrown'; - $hold->discard_changes; # refresh from DB + $hold->discard_changes; # refresh from DB ok( !$hold->is_found, 'Hold is not filled' ); @@ -326,14 +350,17 @@ subtest 'fill() tests' => sub { my $biblio = $builder->build_sample_biblio; my $mock = Test::MockModule->new('Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue'); - $mock->mock( 'enqueue', sub { - my ( $self, $args ) = @_; - is_deeply( - $args->{biblio_ids}, - [ $biblio->id ], - '->fill triggers a holds queue update for the related biblio' - ); - } ); + $mock->mock( + 'enqueue', + sub { + my ( $self, $args ) = @_; + is_deeply( + $args->{biblio_ids}, + [ $biblio->id ], + '->fill triggers a holds queue update for the related biblio' + ); + } + ); t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 1 ); @@ -341,18 +368,19 @@ subtest 'fill() tests' => sub { { class => 'Koha::Holds', value => { - biblionumber => $biblio->id, + biblionumber => $biblio->id, } } )->fill; t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 0 ); + # this call shouldn't add a new test $builder->build_object( { class => 'Koha::Holds', value => { - biblionumber => $biblio->id, + biblionumber => $biblio->id, } } )->fill; @@ -367,19 +395,17 @@ subtest 'patron() tests' => sub { $schema->storage->txn_begin; - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $hold = $builder->build_object( { class => 'Koha::Holds', - value => { - borrowernumber => $patron->borrowernumber - } + value => { borrowernumber => $patron->borrowernumber } } ); my $hold_patron = $hold->patron; is( ref($hold_patron), 'Koha::Patron', 'Right type' ); - is( $hold_patron->id, $patron->id, 'Right object' ); + is( $hold_patron->id, $patron->id, 'Right object' ); $schema->storage->txn_rollback; }; @@ -393,21 +419,28 @@ subtest 'set_pickup_location() tests' => sub { my $mock_biblio = Test::MockModule->new('Koha::Biblio'); my $mock_item = Test::MockModule->new('Koha::Item'); - my $library_1 = $builder->build_object({ class => 'Koha::Libraries' }); - my $library_2 = $builder->build_object({ class => 'Koha::Libraries' }); - my $library_3 = $builder->build_object({ class => 'Koha::Libraries' }); + my $library_1 = $builder->build_object( { class => 'Koha::Libraries' } ); + my $library_2 = $builder->build_object( { class => 'Koha::Libraries' } ); + my $library_3 = $builder->build_object( { class => 'Koha::Libraries' } ); # let's control what Koha::Biblio->pickup_locations returns, for testing - $mock_biblio->mock( 'pickup_locations', sub { - return Koha::Libraries->search( { branchcode => [ $library_2->branchcode, $library_3->branchcode ] } ); - }); + $mock_biblio->mock( + 'pickup_locations', + sub { + return Koha::Libraries->search( { branchcode => [ $library_2->branchcode, $library_3->branchcode ] } ); + } + ); + # let's mock what Koha::Item->pickup_locations returns, for testing - $mock_item->mock( 'pickup_locations', sub { - return Koha::Libraries->search( { branchcode => [ $library_2->branchcode, $library_3->branchcode ] } ); - }); + $mock_item->mock( + 'pickup_locations', + sub { + return Koha::Libraries->search( { branchcode => [ $library_2->branchcode, $library_3->branchcode ] } ); + } + ); my $biblio = $builder->build_sample_biblio; - my $item = $builder->build_sample_item({ biblionumber => $biblio->biblionumber }); + my $item = $builder->build_sample_item( { biblionumber => $biblio->biblionumber } ); # Test biblio-level holds my $biblio_hold = $builder->build_object( @@ -421,15 +454,14 @@ subtest 'set_pickup_location() tests' => sub { } ); - throws_ok - { $biblio_hold->set_pickup_location({ library_id => $library_1->branchcode }); } - 'Koha::Exceptions::Hold::InvalidPickupLocation', + throws_ok { $biblio_hold->set_pickup_location( { library_id => $library_1->branchcode } ); } + 'Koha::Exceptions::Hold::InvalidPickupLocation', 'Exception thrown on invalid pickup location'; $biblio_hold->discard_changes; is( $biblio_hold->branchcode, $library_3->branchcode, 'branchcode remains untouched' ); - my $ret = $biblio_hold->set_pickup_location({ library_id => $library_2->id }); + my $ret = $biblio_hold->set_pickup_location( { library_id => $library_2->id } ); is( ref($ret), 'Koha::Hold', 'self is returned' ); $biblio_hold->discard_changes; @@ -447,27 +479,25 @@ subtest 'set_pickup_location() tests' => sub { } ); - throws_ok - { $item_hold->set_pickup_location({ library_id => $library_1->branchcode }); } - 'Koha::Exceptions::Hold::InvalidPickupLocation', + throws_ok { $item_hold->set_pickup_location( { library_id => $library_1->branchcode } ); } + 'Koha::Exceptions::Hold::InvalidPickupLocation', 'Exception thrown on invalid pickup location'; $item_hold->discard_changes; is( $item_hold->branchcode, $library_3->branchcode, 'branchcode remains untouched' ); - $item_hold->set_pickup_location({ library_id => $library_1->branchcode, force => 1 }); + $item_hold->set_pickup_location( { library_id => $library_1->branchcode, force => 1 } ); $item_hold->discard_changes; is( $item_hold->branchcode, $library_1->branchcode, 'branchcode changed because of \'force\'' ); - $ret = $item_hold->set_pickup_location({ library_id => $library_2->id }); + $ret = $item_hold->set_pickup_location( { library_id => $library_2->id } ); is( ref($ret), 'Koha::Hold', 'self is returned' ); $item_hold->discard_changes; is( $item_hold->branchcode, $library_2->id, 'Pickup location changed correctly' ); - throws_ok - { $item_hold->set_pickup_location({ library_id => undef }); } - 'Koha::Exceptions::MissingParameter', + throws_ok { $item_hold->set_pickup_location( { library_id => undef } ); } + 'Koha::Exceptions::MissingParameter', 'Exception thrown if missing parameter'; like( "$@", qr/The library_id parameter is mandatory/, 'Exception message is clear' ); @@ -484,21 +514,28 @@ subtest 'is_pickup_location_valid() tests' => sub { my $mock_biblio = Test::MockModule->new('Koha::Biblio'); my $mock_item = Test::MockModule->new('Koha::Item'); - my $library_1 = $builder->build_object({ class => 'Koha::Libraries' }); - my $library_2 = $builder->build_object({ class => 'Koha::Libraries' }); - my $library_3 = $builder->build_object({ class => 'Koha::Libraries' }); + my $library_1 = $builder->build_object( { class => 'Koha::Libraries' } ); + my $library_2 = $builder->build_object( { class => 'Koha::Libraries' } ); + my $library_3 = $builder->build_object( { class => 'Koha::Libraries' } ); # let's control what Koha::Biblio->pickup_locations returns, for testing - $mock_biblio->mock( 'pickup_locations', sub { - return Koha::Libraries->search( { branchcode => [ $library_2->branchcode, $library_3->branchcode ] } ); - }); + $mock_biblio->mock( + 'pickup_locations', + sub { + return Koha::Libraries->search( { branchcode => [ $library_2->branchcode, $library_3->branchcode ] } ); + } + ); + # let's mock what Koha::Item->pickup_locations returns, for testing - $mock_item->mock( 'pickup_locations', sub { - return Koha::Libraries->search( { branchcode => [ $library_2->branchcode, $library_3->branchcode ] } ); - }); + $mock_item->mock( + 'pickup_locations', + sub { + return Koha::Libraries->search( { branchcode => [ $library_2->branchcode, $library_3->branchcode ] } ); + } + ); my $biblio = $builder->build_sample_biblio; - my $item = $builder->build_sample_item({ biblionumber => $biblio->biblionumber }); + my $item = $builder->build_sample_item( { biblionumber => $biblio->biblionumber } ); # Test biblio-level holds my $biblio_hold = $builder->build_object( @@ -512,8 +549,11 @@ subtest 'is_pickup_location_valid() tests' => sub { } ); - ok( !$biblio_hold->is_pickup_location_valid({ library_id => $library_1->branchcode }), 'Pickup location invalid'); - ok( $biblio_hold->is_pickup_location_valid({ library_id => $library_2->id }), 'Pickup location valid'); + ok( + !$biblio_hold->is_pickup_location_valid( { library_id => $library_1->branchcode } ), + 'Pickup location invalid' + ); + ok( $biblio_hold->is_pickup_location_valid( { library_id => $library_2->id } ), 'Pickup location valid' ); # Test item-level holds my $item_hold = $builder->build_object( @@ -527,8 +567,8 @@ subtest 'is_pickup_location_valid() tests' => sub { } ); - ok( !$item_hold->is_pickup_location_valid({ library_id => $library_1->branchcode }), 'Pickup location invalid'); - ok( $item_hold->is_pickup_location_valid({ library_id => $library_2->id }), 'Pickup location valid' ); + ok( !$item_hold->is_pickup_location_valid( { library_id => $library_1->branchcode } ), 'Pickup location invalid' ); + ok( $item_hold->is_pickup_location_valid( { library_id => $library_2->id } ), 'Pickup location valid' ); subtest 'pickup_locations() returning ->empty' => sub { @@ -536,7 +576,7 @@ subtest 'is_pickup_location_valid() tests' => sub { $schema->storage->txn_begin; - my $library = $builder->build_object({ class => 'Koha::Libraries' }); + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); my $mock_item = Test::MockModule->new('Koha::Item'); $mock_item->mock( 'pickup_locations', sub { return Koha::Libraries->new->empty; } ); @@ -558,7 +598,10 @@ subtest 'is_pickup_location_valid() tests' => sub { } ); - ok( !$biblio_hold->is_pickup_location_valid({ library_id => $library->branchcode }), 'Pickup location invalid'); + ok( + !$biblio_hold->is_pickup_location_valid( { library_id => $library->branchcode } ), + 'Pickup location invalid' + ); # Test item-level holds my $item_hold = $builder->build_object( @@ -571,7 +614,10 @@ subtest 'is_pickup_location_valid() tests' => sub { } ); - ok( !$item_hold->is_pickup_location_valid({ library_id => $library->branchcode }), 'Pickup location invalid'); + ok( + !$item_hold->is_pickup_location_valid( { library_id => $library->branchcode } ), + 'Pickup location invalid' + ); $schema->storage->txn_rollback; }; @@ -589,8 +635,10 @@ subtest 'cancel() tests' => sub { # reduce the tests noise t::lib::Mocks::mock_preference( 'HoldsLog', 0 ); - t::lib::Mocks::mock_preference( 'ExpireReservesMaxPickUpDelayCharge', - undef ); + t::lib::Mocks::mock_preference( + 'ExpireReservesMaxPickUpDelayCharge', + undef + ); t::lib::Mocks::mock_preference( 'AnonymousPatron', undef ); @@ -603,8 +651,10 @@ subtest 'cancel() tests' => sub { } ); $hold->cancel(); - is( Koha::Old::Holds->find( $hold->id )->borrowernumber, - $patron->borrowernumber, 'Patron link is kept' ); + is( + Koha::Old::Holds->find( $hold->id )->borrowernumber, + $patron->borrowernumber, 'Patron link is kept' + ); # 1 == "default", meaning it is not protected from removal $patron->privacy(1)->store; @@ -615,11 +665,14 @@ subtest 'cancel() tests' => sub { } ); $hold->cancel(); - is( Koha::Old::Holds->find( $hold->id )->borrowernumber, - $patron->borrowernumber, 'Patron link is kept' ); + is( + Koha::Old::Holds->find( $hold->id )->borrowernumber, + $patron->borrowernumber, 'Patron link is kept' + ); - my $anonymous_patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $anonymous_patron = $builder->build_object( { class => 'Koha::Patrons' } ); t::lib::Mocks::mock_preference( 'AnonymousPatron', $anonymous_patron->id ); + # We need anonymous patron set to change patron privacy to never # (2 == delete immediately) # then we can undef for further tests @@ -631,9 +684,8 @@ subtest 'cancel() tests' => sub { value => { borrowernumber => $patron->id, found => undef } } ); - throws_ok - { $hold->cancel(); } - 'Koha::Exception', + throws_ok { $hold->cancel(); } + 'Koha::Exception', 'AnonymousPatron not set, exception thrown'; $hold->discard_changes; @@ -664,20 +716,23 @@ subtest 'cancel() tests' => sub { t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 1 ); my $mock = Test::MockModule->new('Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue'); - $mock->mock( 'enqueue', sub { - my ( $self, $args ) = @_; - is_deeply( - $args->{biblio_ids}, - [ $biblio->id ], - '->cancel triggers a holds queue update for the related biblio' - ); - } ); + $mock->mock( + 'enqueue', + sub { + my ( $self, $args ) = @_; + is_deeply( + $args->{biblio_ids}, + [ $biblio->id ], + '->cancel triggers a holds queue update for the related biblio' + ); + } + ); $builder->build_object( { class => 'Koha::Holds', value => { - biblionumber => $biblio->id, + biblionumber => $biblio->id, } } )->cancel; @@ -687,10 +742,10 @@ subtest 'cancel() tests' => sub { { class => 'Koha::Holds', value => { - biblionumber => $biblio->id, + biblionumber => $biblio->id, } } - )->cancel({ skip_holds_queue => 1 }); + )->cancel( { skip_holds_queue => 1 } ); t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 0 ); @@ -698,10 +753,10 @@ subtest 'cancel() tests' => sub { { class => 'Koha::Holds', value => { - biblionumber => $biblio->id, + biblionumber => $biblio->id, } } - )->cancel({ skip_holds_queue => 0 }); + )->cancel( { skip_holds_queue => 0 } ); }; $schema->storage->txn_rollback; @@ -719,14 +774,17 @@ subtest 'suspend_hold() and resume() tests' => sub { t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 1 ); my $mock = Test::MockModule->new('Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue'); - $mock->mock( 'enqueue', sub { - my ( $self, $args ) = @_; - is_deeply( - $args->{biblio_ids}, - [ $biblio->id ], - "->$action triggers a holds queue update for the related biblio" - ); - } ); + $mock->mock( + 'enqueue', + sub { + my ( $self, $args ) = @_; + is_deeply( + $args->{biblio_ids}, + [ $biblio->id ], + "->$action triggers a holds queue update for the related biblio" + ); + } + ); my $hold = $builder->build_object( { @@ -787,15 +845,11 @@ subtest 'cancellation_requestable_from_opac() tests' => sub { $schema->storage->txn_begin; - my $category = - $builder->build_object( { class => 'Koha::Patron::Categories' } ); - my $item_home_library = - $builder->build_object( { class => 'Koha::Libraries' } ); - my $patron_home_library = - $builder->build_object( { class => 'Koha::Libraries' } ); + my $category = $builder->build_object( { class => 'Koha::Patron::Categories' } ); + my $item_home_library = $builder->build_object( { class => 'Koha::Libraries' } ); + my $patron_home_library = $builder->build_object( { class => 'Koha::Libraries' } ); - my $item = - $builder->build_sample_item( { library => $item_home_library->id } ); + my $item = $builder->build_sample_item( { library => $item_home_library->id } ); my $patron = $builder->build_object( { class => 'Koha::Patrons', @@ -820,7 +874,7 @@ subtest 'cancellation_requestable_from_opac() tests' => sub { throws_ok { $hold->cancellation_requestable_from_opac; } 'Koha::Exceptions::InvalidStatus', - 'Exception thrown because hold is not waiting'; + 'Exception thrown because hold is not waiting'; is( $@->invalid_status, 'hold_not_waiting' ); @@ -837,7 +891,7 @@ subtest 'cancellation_requestable_from_opac() tests' => sub { throws_ok { $hold->cancellation_requestable_from_opac; } 'Koha::Exceptions::InvalidStatus', - 'Exception thrown because waiting hold has no item linked'; + 'Exception thrown because waiting hold has no item linked'; is( $@->invalid_status, 'no_item_linked' ); }; @@ -864,8 +918,10 @@ subtest 'cancellation_requestable_from_opac() tests' => sub { } ); - t::lib::Mocks::mock_preference( 'ReservesControlBranch', - 'ItemHomeLibrary' ); + t::lib::Mocks::mock_preference( + 'ReservesControlBranch', + 'ItemHomeLibrary' + ); Koha::CirculationRules->set_rule( { @@ -933,7 +989,8 @@ subtest 'can_update_pickup_location_opac() tests' => sub { $schema->storage->txn_begin; my $hold = $builder->build_object( - { class => 'Koha::Holds', + { + class => 'Koha::Holds', value => { found => undef, suspend => 0, suspend_until => undef, waitingdate => undef } } ); @@ -951,24 +1008,36 @@ subtest 'can_update_pickup_location_opac() tests' => sub { $hold->found(undef); my $dt = dt_from_string(); - $hold->suspend_hold( $dt ); + $hold->suspend_hold($dt); is( $hold->can_update_pickup_location_opac, 0, "Suspended hold pickup can't be changed (No change allowed)" ); $hold->resume(); t::lib::Mocks::mock_preference( 'OPACAllowUserToChangeBranch', 'pending,intransit,suspended' ); $hold->found(undef); - is( $hold->can_update_pickup_location_opac, 1, "Pending hold pickup can be changed (pending,intransit,suspended allowed)" ); + is( + $hold->can_update_pickup_location_opac, 1, + "Pending hold pickup can be changed (pending,intransit,suspended allowed)" + ); $hold->found('T'); - is( $hold->can_update_pickup_location_opac, 1, "In transit hold pickup can be changed (pending,intransit,suspended allowed)" ); + is( + $hold->can_update_pickup_location_opac, 1, + "In transit hold pickup can be changed (pending,intransit,suspended allowed)" + ); $hold->found('W'); - is( $hold->can_update_pickup_location_opac, 0, "Waiting hold pickup can't be changed (pending,intransit,suspended allowed)" ); + is( + $hold->can_update_pickup_location_opac, 0, + "Waiting hold pickup can't be changed (pending,intransit,suspended allowed)" + ); $hold->found(undef); $dt = dt_from_string(); - $hold->suspend_hold( $dt ); - is( $hold->can_update_pickup_location_opac, 1, "Suspended hold pickup can be changed (pending,intransit,suspended allowed)" ); + $hold->suspend_hold($dt); + is( + $hold->can_update_pickup_location_opac, 1, + "Suspended hold pickup can be changed (pending,intransit,suspended allowed)" + ); $schema->storage->txn_rollback; }; @@ -998,7 +1067,7 @@ subtest 'Koha::Hold::item_group tests' => sub { my $biblio = $builder->build_sample_biblio(); my $item_group = - Koha::Biblio::ItemGroup->new( { biblio_id => $biblio->id } )->store(); + Koha::Biblio::ItemGroup->new( { biblio_id => $biblio->id } )->store(); my $hold = $builder->build_object( { diff --git a/t/db_dependent/Koha/Holds.t b/t/db_dependent/Koha/Holds.t index 4310370f28..2f560980d9 100755 --- a/t/db_dependent/Koha/Holds.t +++ b/t/db_dependent/Koha/Holds.t @@ -23,7 +23,7 @@ use Test::More tests => 12; use Test::Warn; use C4::Circulation qw( AddIssue ); -use C4::Reserves qw( AddReserve CheckReserves ModReserve ModReserveCancelAll ); +use C4::Reserves qw( AddReserve CheckReserves ModReserve ModReserveCancelAll ); use Koha::AuthorisedValueCategory; use Koha::Biblio::ItemGroups; use Koha::Database; @@ -42,8 +42,8 @@ my $builder = t::lib::TestBuilder->new; subtest 'DB constraints' => sub { plan tests => 1; - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); - my $item = $builder->build_sample_item; + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + my $item = $builder->build_sample_item; my $hold_info = { branchcode => $patron->branchcode, borrowernumber => $patron->borrowernumber, @@ -54,13 +54,13 @@ subtest 'DB constraints' => sub { }; my $reserve_id = C4::Reserves::AddReserve($hold_info); - my $hold = Koha::Holds->find( $reserve_id ); + my $hold = Koha::Holds->find($reserve_id); warning_like { eval { $hold->priority(undef)->store } } qr{.*DBD::mysql::st execute failed: Column 'priority' cannot be null.*}, - 'DBD should have raised an error about priority that cannot be null'; + 'DBD should have raised an error about priority that cannot be null'; }; subtest 'cancel' => sub { @@ -75,9 +75,9 @@ subtest 'cancel' => sub { holdingbranch => $library->branchcode, itype => $itemtype->itemtype, }; - my $item = $builder->build_object( { class => 'Koha::Items', value => $item_info } ); - my $manager = $builder->build_object({ class => "Koha::Patrons" }); - t::lib::Mocks::mock_userenv({ patron => $manager,branchcode => $manager->branchcode }); + my $item = $builder->build_object( { class => 'Koha::Items', value => $item_info } ); + my $manager = $builder->build_object( { class => "Koha::Patrons" } ); + t::lib::Mocks::mock_userenv( { patron => $manager, branchcode => $manager->branchcode } ); my ( @patrons, @holds ); for my $i ( 0 .. 2 ) { @@ -104,28 +104,36 @@ subtest 'cancel' => sub { } # There are 3 holds on this records - my $nb_of_holds = - Koha::Holds->search( { biblionumber => $item->biblionumber } )->count; - is( $nb_of_holds, 3, - 'There should have 3 holds placed on this biblio record' ); + my $nb_of_holds = Koha::Holds->search( { biblionumber => $item->biblionumber } )->count; + is( + $nb_of_holds, 3, + 'There should have 3 holds placed on this biblio record' + ); my $first_hold = $holds[0]; my $second_hold = $holds[1]; my $third_hold = $holds[2]; - is( ref($second_hold), 'Koha::Hold', - 'We should play with Koha::Hold objects' ); - is( $second_hold->priority, 2, - 'Second hold should have a priority set to 3' ); + is( + ref($second_hold), 'Koha::Hold', + 'We should play with Koha::Hold objects' + ); + is( + $second_hold->priority, 2, + 'Second hold should have a priority set to 3' + ); # Remove the second hold, only 2 should still exist in DB and priorities must have been updated my $is_cancelled = $second_hold->cancel; - is( ref($is_cancelled), 'Koha::Hold', - 'Koha::Hold->cancel should return the Koha::Hold (?)' ) - ; # This is can reconsidered - is( $second_hold->in_storage, 0, - 'The hold has been cancelled and does not longer exist in DB' ); - $nb_of_holds = - Koha::Holds->search( { biblionumber => $item->biblionumber } )->count; - is( $nb_of_holds, 2, + is( + ref($is_cancelled), 'Koha::Hold', + 'Koha::Hold->cancel should return the Koha::Hold (?)' + ); # This is can reconsidered + is( + $second_hold->in_storage, 0, + 'The hold has been cancelled and does not longer exist in DB' + ); + $nb_of_holds = Koha::Holds->search( { biblionumber => $item->biblionumber } )->count; + is( + $nb_of_holds, 2, 'a hold has been cancelled, there should have only 2 holds placed on this biblio record' ); @@ -141,7 +149,8 @@ subtest 'cancel' => sub { my $bib_title = "Test Title"; - my $borrower = $builder->build_object({ class => "Koha::Patrons", value => { branchcode => $library1->branchcode } }); + my $borrower = + $builder->build_object( { class => "Koha::Patrons", value => { branchcode => $library1->branchcode } } ); my $itemtype1 = $builder->build_object( { class => 'Koha::ItemTypes', value => {} } ); my $itemtype2 = $builder->build_object( { class => 'Koha::ItemTypes', value => {} } ); @@ -152,57 +161,65 @@ subtest 'cancel' => sub { my $library_A_code = $library1->branchcode; - my $biblio = $builder->build_sample_biblio({itemtype => $itemtype1->itemtype}); + my $biblio = $builder->build_sample_biblio( { itemtype => $itemtype1->itemtype } ); my $biblionumber = $biblio->biblionumber; - my $item1 = $builder->build_sample_item({ - biblionumber => $biblionumber, - itype => $itemtype1->itemtype, - homebranch => $library_A_code, - holdingbranch => $library_A_code - }); - my $item2 = $builder->build_sample_item({ - biblionumber => $biblionumber, - itype => $itemtype2->itemtype, - homebranch => $library_A_code, - holdingbranch => $library_A_code - }); - my $item3 = $builder->build_sample_item({ - biblionumber => $biblionumber, - itype => $itemtype3->itemtype, - homebranch => $library_A_code, - holdingbranch => $library_A_code - }); + my $item1 = $builder->build_sample_item( + { + biblionumber => $biblionumber, + itype => $itemtype1->itemtype, + homebranch => $library_A_code, + holdingbranch => $library_A_code + } + ); + my $item2 = $builder->build_sample_item( + { + biblionumber => $biblionumber, + itype => $itemtype2->itemtype, + homebranch => $library_A_code, + holdingbranch => $library_A_code + } + ); + my $item3 = $builder->build_sample_item( + { + biblionumber => $biblionumber, + itype => $itemtype3->itemtype, + homebranch => $library_A_code, + holdingbranch => $library_A_code + } + ); my $library_B_code = $library2->branchcode; - my $biblio2 = $builder->build_sample_biblio({itemtype => $itemtype4->itemtype}); + my $biblio2 = $builder->build_sample_biblio( { itemtype => $itemtype4->itemtype } ); my $biblionumber2 = $biblio2->biblionumber; - my $item4 = $builder->build_sample_item({ - biblionumber => $biblionumber2, - itype => $itemtype4->itemtype, - homebranch => $library_B_code, - holdingbranch => $library_B_code - }); + my $item4 = $builder->build_sample_item( + { + biblionumber => $biblionumber2, + itype => $itemtype4->itemtype, + homebranch => $library_B_code, + holdingbranch => $library_B_code + } + ); my $library_C_code = $library3->branchcode; - my $biblio3 = $builder->build_sample_biblio({itemtype => $itemtype4->itemtype}); + my $biblio3 = $builder->build_sample_biblio( { itemtype => $itemtype4->itemtype } ); my $biblionumber3 = $biblio3->biblionumber; - my $item5 = $builder->build_sample_item({ - biblionumber => $biblionumber3, - itype => $itemtype4->itemtype, - homebranch => $library_C_code, - holdingbranch => $library_C_code - }); + my $item5 = $builder->build_sample_item( + { + biblionumber => $biblionumber3, + itype => $itemtype4->itemtype, + homebranch => $library_C_code, + holdingbranch => $library_C_code + } + ); Koha::CirculationRules->set_rules( { itemtype => undef, categorycode => undef, branchcode => undef, - rules => { - expire_reserves_charge => undef - } + rules => { expire_reserves_charge => undef } } ); Koha::CirculationRules->set_rules( @@ -210,9 +227,7 @@ subtest 'cancel' => sub { itemtype => $itemtype1->itemtype, categorycode => undef, branchcode => undef, - rules => { - expire_reserves_charge => '111' - } + rules => { expire_reserves_charge => '111' } } ); Koha::CirculationRules->set_rules( @@ -220,9 +235,7 @@ subtest 'cancel' => sub { itemtype => $itemtype2->itemtype, categorycode => undef, branchcode => undef, - rules => { - expire_reserves_charge => undef - } + rules => { expire_reserves_charge => undef } } ); Koha::CirculationRules->set_rules( @@ -230,9 +243,7 @@ subtest 'cancel' => sub { itemtype => undef, categorycode => undef, branchcode => $library_B_code, - rules => { - expire_reserves_charge => '444' - } + rules => { expire_reserves_charge => '444' } } ); Koha::CirculationRules->set_rules( @@ -240,13 +251,11 @@ subtest 'cancel' => sub { itemtype => undef, categorycode => undef, branchcode => $library_C_code, - rules => { - expire_reserves_charge => '0' - } + rules => { expire_reserves_charge => '0' } } ); - t::lib::Mocks::mock_preference('ReservesControlBranch', 'ItemHomeLibrary'); + t::lib::Mocks::mock_preference( 'ReservesControlBranch', 'ItemHomeLibrary' ); my $reserve_id; my $account; @@ -256,157 +265,166 @@ subtest 'cancel' => sub { # TEST: Hold itemtype1 item $reserve_id = AddReserve( { - branchcode => $library_A_code, - borrowernumber => $borrowernumber, - biblionumber => $biblionumber, - priority => 1, - itemnumber => $item1->itemnumber, + branchcode => $library_A_code, + borrowernumber => $borrowernumber, + biblionumber => $biblionumber, + priority => 1, + itemnumber => $item1->itemnumber, } ); - $account = Koha::Account->new({ patron_id => $borrowernumber }); + $account = Koha::Account->new( { patron_id => $borrowernumber } ); - ( $status ) = CheckReserves($item1); + ($status) = CheckReserves($item1); is( $status, 'Reserved', "Hold for the itemtype1 created" ); $start_balance = $account->balance(); - Koha::Holds->find( $reserve_id )->cancel({ charge_cancel_fee => 1 }); + Koha::Holds->find($reserve_id)->cancel( { charge_cancel_fee => 1 } ); - ( $status ) = CheckReserves($item1); + ($status) = CheckReserves($item1); is( $status, '', "Hold for the itemtype1 cancelled" ); is( $account->balance() - $start_balance, 111, "Used circulation rule for itemtype1" ); # TEST: circulation rule for itemtype2 has 'expire_reserves_charge' set undef, so it should use ExpireReservesMaxPickUpDelayCharge preference - t::lib::Mocks::mock_preference('ExpireReservesMaxPickUpDelayCharge', 222); + t::lib::Mocks::mock_preference( 'ExpireReservesMaxPickUpDelayCharge', 222 ); $reserve_id = AddReserve( { - branchcode => $library_A_code, - borrowernumber => $borrowernumber, - biblionumber => $biblionumber, - priority => 1, - itemnumber => $item2->itemnumber, + branchcode => $library_A_code, + borrowernumber => $borrowernumber, + biblionumber => $biblionumber, + priority => 1, + itemnumber => $item2->itemnumber, } ); - $account = Koha::Account->new({ patron_id => $borrowernumber }); + $account = Koha::Account->new( { patron_id => $borrowernumber } ); - ( $status ) = CheckReserves($item2); + ($status) = CheckReserves($item2); is( $status, 'Reserved', "Hold for the itemtype2 created" ); $start_balance = $account->balance(); - Koha::Holds->find( $reserve_id )->cancel({ charge_cancel_fee => 1 }); + Koha::Holds->find($reserve_id)->cancel( { charge_cancel_fee => 1 } ); - ( $status ) = CheckReserves($item2); + ($status) = CheckReserves($item2); is( $status, '', "Hold for the itemtype2 cancelled" ); - is( $account->balance() - $start_balance, 222, "Used ExpireReservesMaxPickUpDelayCharge preference as expire_reserves_charge set to undef" ); + is( + $account->balance() - $start_balance, 222, + "Used ExpireReservesMaxPickUpDelayCharge preference as expire_reserves_charge set to undef" + ); # TEST: no circulation rules for itemtype3, it should use ExpireReservesMaxPickUpDelayCharge preference - t::lib::Mocks::mock_preference('ExpireReservesMaxPickUpDelayCharge', 333); + t::lib::Mocks::mock_preference( 'ExpireReservesMaxPickUpDelayCharge', 333 ); $reserve_id = AddReserve( { - branchcode => $library_A_code, - borrowernumber => $borrowernumber, - biblionumber => $biblionumber, - priority => 1, - itemnumber => $item3->itemnumber, + branchcode => $library_A_code, + borrowernumber => $borrowernumber, + biblionumber => $biblionumber, + priority => 1, + itemnumber => $item3->itemnumber, } ); - $account = Koha::Account->new({ patron_id => $borrowernumber }); + $account = Koha::Account->new( { patron_id => $borrowernumber } ); - ( $status ) = CheckReserves($item3); + ($status) = CheckReserves($item3); is( $status, 'Reserved', "Hold for the itemtype3 created" ); $start_balance = $account->balance(); - Koha::Holds->find( $reserve_id )->cancel({ charge_cancel_fee => 1 }); + Koha::Holds->find($reserve_id)->cancel( { charge_cancel_fee => 1 } ); - ( $status ) = CheckReserves($item3); + ($status) = CheckReserves($item3); is( $status, '', "Hold for the itemtype3 cancelled" ); - is( $account->balance() - $start_balance, 333, "Used ExpireReservesMaxPickUpDelayCharge preference as there's no circulation rules for itemtype3" ); + is( + $account->balance() - $start_balance, 333, + "Used ExpireReservesMaxPickUpDelayCharge preference as there's no circulation rules for itemtype3" + ); # TEST: circulation rule for itemtype4 with library_B_code - t::lib::Mocks::mock_preference('ExpireReservesMaxPickUpDelayCharge', 555); + t::lib::Mocks::mock_preference( 'ExpireReservesMaxPickUpDelayCharge', 555 ); $reserve_id = AddReserve( { - branchcode => $library_B_code, - borrowernumber => $borrowernumber, - biblionumber => $biblionumber2, - priority => 1, - itemnumber => $item4->itemnumber, + branchcode => $library_B_code, + borrowernumber => $borrowernumber, + biblionumber => $biblionumber2, + priority => 1, + itemnumber => $item4->itemnumber, } ); - $account = Koha::Account->new({ patron_id => $borrowernumber }); + $account = Koha::Account->new( { patron_id => $borrowernumber } ); - ( $status ) = CheckReserves($item4); + ($status) = CheckReserves($item4); is( $status, 'Reserved', "Hold for the itemtype4 created" ); $start_balance = $account->balance(); - Koha::Holds->find( $reserve_id )->cancel({ charge_cancel_fee => 1 }); + Koha::Holds->find($reserve_id)->cancel( { charge_cancel_fee => 1 } ); - ( $status ) = CheckReserves($item4); + ($status) = CheckReserves($item4); is( $status, '', "Hold for the itemtype4 cancelled" ); is( $account->balance() - $start_balance, 444, "Used circulation rule for itemtype4 with library_B_code" ); # TEST: circulation rule for library_C_code that has expire_reserves_charge = 0 - t::lib::Mocks::mock_preference('ExpireReservesMaxPickUpDelayCharge', 777); + t::lib::Mocks::mock_preference( 'ExpireReservesMaxPickUpDelayCharge', 777 ); $reserve_id = AddReserve( { - branchcode => $library_C_code, - borrowernumber => $borrowernumber, - biblionumber => $biblionumber3, - priority => 1, - itemnumber => $item5->itemnumber, + branchcode => $library_C_code, + borrowernumber => $borrowernumber, + biblionumber => $biblionumber3, + priority => 1, + itemnumber => $item5->itemnumber, } ); - $account = Koha::Account->new({ patron_id => $borrowernumber }); + $account = Koha::Account->new( { patron_id => $borrowernumber } ); - ( $status ) = CheckReserves($item5); + ($status) = CheckReserves($item5); is( $status, 'Reserved', "Hold for the itemtype5 created" ); $start_balance = $account->balance(); - Koha::Holds->find( $reserve_id )->cancel({ charge_cancel_fee => 1 }); + Koha::Holds->find($reserve_id)->cancel( { charge_cancel_fee => 1 } ); - ( $status ) = CheckReserves($item5); + ($status) = CheckReserves($item5); is( $status, '', "Hold for the itemtype5 cancelled" ); - is( $account->balance() - $start_balance, 0, "Used circulation rule for itemtype4 with library_C_code even though it's 0" ); + is( + $account->balance() - $start_balance, 0, + "Used circulation rule for itemtype4 with library_C_code even though it's 0" + ); # TEST: charge_cancel_fee is 0 $reserve_id = AddReserve( { - branchcode => $library_B_code, - borrowernumber => $borrowernumber, - biblionumber => $biblionumber2, - priority => 1, - itemnumber => $item4->itemnumber, + branchcode => $library_B_code, + borrowernumber => $borrowernumber, + biblionumber => $biblionumber2, + priority => 1, + itemnumber => $item4->itemnumber, } ); - $account = Koha::Account->new({ patron_id => $borrowernumber }); + $account = Koha::Account->new( { patron_id => $borrowernumber } ); - ( $status ) = CheckReserves($item4); + ($status) = CheckReserves($item4); is( $status, 'Reserved', "Hold for the itemtype4 created" ); $start_balance = $account->balance(); - Koha::Holds->find( $reserve_id )->cancel({ charge_cancel_fee => 0 }); + Koha::Holds->find($reserve_id)->cancel( { charge_cancel_fee => 0 } ); - ( $status ) = CheckReserves($item4); + ($status) = CheckReserves($item4); is( $status, '', "Hold for the itemtype4 cancelled" ); is( $account->balance() - $start_balance, 0, "Patron not charged when charge_cancel_fee is 0" ); @@ -414,7 +432,7 @@ subtest 'cancel' => sub { subtest 'waiting hold' => sub { plan tests => 1; - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $reserve_id = C4::Reserves::AddReserve( { branchcode => $library->branchcode, @@ -426,14 +444,14 @@ subtest 'cancel' => sub { found => 'W', } ); - Koha::Holds->find( $reserve_id )->cancel; - my $hold_old = Koha::Old::Holds->find( $reserve_id ); + Koha::Holds->find($reserve_id)->cancel; + my $hold_old = Koha::Old::Holds->find($reserve_id); is( $hold_old->found, 'W', 'The found column should have been kept and a hold is cancelled' ); }; subtest 'HoldsLog' => sub { plan tests => 2; - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $hold_info = { branchcode => $library->branchcode, borrowernumber => $patron->borrowernumber, @@ -443,16 +461,20 @@ subtest 'cancel' => sub { itemnumber => $item->itemnumber, }; - t::lib::Mocks::mock_preference('HoldsLog', 0); + t::lib::Mocks::mock_preference( 'HoldsLog', 0 ); my $reserve_id = C4::Reserves::AddReserve($hold_info); - Koha::Holds->find( $reserve_id )->cancel; - my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'HOLDS', action => 'CANCEL', object => $reserve_id } )->count; + Koha::Holds->find($reserve_id)->cancel; + my $number_of_logs = + $schema->resultset('ActionLog')->search( { module => 'HOLDS', action => 'CANCEL', object => $reserve_id } ) + ->count; is( $number_of_logs, 0, 'Without HoldsLog, Koha::Hold->cancel should not have logged' ); - t::lib::Mocks::mock_preference('HoldsLog', 1); + t::lib::Mocks::mock_preference( 'HoldsLog', 1 ); $reserve_id = C4::Reserves::AddReserve($hold_info); - Koha::Holds->find( $reserve_id )->cancel; - $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'HOLDS', action => 'CANCEL', object => $reserve_id } )->count; + Koha::Holds->find($reserve_id)->cancel; + $number_of_logs = + $schema->resultset('ActionLog')->search( { module => 'HOLDS', action => 'CANCEL', object => $reserve_id } ) + ->count; is( $number_of_logs, 1, 'With HoldsLog, Koha::Hold->cancel should have logged' ); }; @@ -479,7 +501,7 @@ subtest 'cancel' => sub { itemnumber => $item->itemnumber, }; - t::lib::Mocks::mock_preference( 'ExpireReservesMaxPickUpDelayCharge',42 ); + t::lib::Mocks::mock_preference( 'ExpireReservesMaxPickUpDelayCharge', 42 ); my $reserve_id = C4::Reserves::AddReserve($hold_info); my $hold = Koha::Holds->find($reserve_id); @@ -490,12 +512,13 @@ subtest 'cancel' => sub { eval { $hold->cancel( { charge_cancel_fee => 1 } ) }; } qr{.*DBD::mysql::st execute failed: Duplicate entry.*}, - 'DBD should have raised an error about dup primary key'; + 'DBD should have raised an error about dup primary key'; $hold = Koha::Holds->find($reserve_id); is( ref($hold), 'Koha::Hold', 'The hold should not have been deleted' ); - is( $patron->account->balance, 0, -'If the hold has not been cancelled, the patron should not have been charged' + is( + $patron->account->balance, 0, + 'If the hold has not been cancelled, the patron should not have been charged' ); }; @@ -504,7 +527,7 @@ subtest 'cancel' => sub { subtest 'cancel with reason' => sub { plan tests => 7; my $library = $builder->build_object( { class => 'Koha::Libraries' } ); - my $item = $builder->build_sample_item({ library => $library->branchcode }); + my $item = $builder->build_sample_item( { library => $library->branchcode } ); my $manager = $builder->build_object( { class => "Koha::Patrons" } ); t::lib::Mocks::mock_userenv( { patron => $manager, branchcode => $manager->branchcode } ); @@ -527,32 +550,35 @@ subtest 'cancel with reason' => sub { my $hold = Koha::Holds->find($reserve_id); - ok($reserve_id, "Hold created"); - ok($hold, "Hold found"); + ok( $reserve_id, "Hold created" ); + ok( $hold, "Hold found" ); - my $av = Koha::AuthorisedValue->new( { category => 'HOLD_CANCELLATION', authorised_value => 'TEST_REASON' } )->store; - Koha::Notice::Templates->search({ code => 'HOLD_CANCELLATION'})->delete(); - my $notice = Koha::Notice::Template->new({ - name => 'Hold cancellation', - module => 'reserves', - code => 'HOLD_CANCELLATION', - title => 'Hold cancelled', - content => 'Your hold was cancelled.', - message_transport_type => 'email', - branchcode => q{}, - })->store(); + my $av = + Koha::AuthorisedValue->new( { category => 'HOLD_CANCELLATION', authorised_value => 'TEST_REASON' } )->store; + Koha::Notice::Templates->search( { code => 'HOLD_CANCELLATION' } )->delete(); + my $notice = Koha::Notice::Template->new( + { + name => 'Hold cancellation', + module => 'reserves', + code => 'HOLD_CANCELLATION', + title => 'Hold cancelled', + content => 'Your hold was cancelled.', + message_transport_type => 'email', + branchcode => q{}, + } + )->store(); - $hold->cancel({cancellation_reason => 'TEST_REASON'}); + $hold->cancel( { cancellation_reason => 'TEST_REASON' } ); $hold = Koha::Holds->find($reserve_id); - is( $hold, undef, 'Hold is not in the reserves table'); + is( $hold, undef, 'Hold is not in the reserves table' ); $hold = Koha::Old::Holds->find($reserve_id); - ok( $hold, 'Hold was found in the old reserves table'); + ok( $hold, 'Hold was found in the old reserves table' ); - my $message = Koha::Notice::Messages->find({ borrowernumber => $patron->id, letter_code => 'HOLD_CANCELLATION'}); - ok( $message, 'Found hold cancellation message'); - is( $message->subject, 'Hold cancelled', 'Message has correct title' ); - is( $message->content, 'Your hold was cancelled.', 'Message has correct content'); + my $message = Koha::Notice::Messages->find( { borrowernumber => $patron->id, letter_code => 'HOLD_CANCELLATION' } ); + ok( $message, 'Found hold cancellation message' ); + is( $message->subject, 'Hold cancelled', 'Message has correct title' ); + is( $message->content, 'Your hold was cancelled.', 'Message has correct content' ); $notice->delete; $av->delete; @@ -562,7 +588,7 @@ subtest 'cancel with reason' => sub { subtest 'cancel all with reason' => sub { plan tests => 7; my $library = $builder->build_object( { class => 'Koha::Libraries' } ); - my $item = $builder->build_sample_item({ library => $library->branchcode }); + my $item = $builder->build_sample_item( { library => $library->branchcode } ); my $manager = $builder->build_object( { class => "Koha::Patrons" } ); t::lib::Mocks::mock_userenv( { patron => $manager, branchcode => $manager->branchcode } ); @@ -585,32 +611,35 @@ subtest 'cancel all with reason' => sub { my $hold = Koha::Holds->find($reserve_id); - ok($reserve_id, "Hold created"); - ok($hold, "Hold found"); + ok( $reserve_id, "Hold created" ); + ok( $hold, "Hold found" ); - my $av = Koha::AuthorisedValue->new( { category => 'HOLD_CANCELLATION', authorised_value => 'TEST_REASON' } )->store; - Koha::Notice::Templates->search({ code => 'HOLD_CANCELLATION'})->delete(); - my $notice = Koha::Notice::Template->new({ - name => 'Hold cancellation', - module => 'reserves', - code => 'HOLD_CANCELLATION', - title => 'Hold cancelled', - content => 'Your hold was cancelled.', - message_transport_type => 'email', - branchcode => q{}, - })->store(); + my $av = + Koha::AuthorisedValue->new( { category => 'HOLD_CANCELLATION', authorised_value => 'TEST_REASON' } )->store; + Koha::Notice::Templates->search( { code => 'HOLD_CANCELLATION' } )->delete(); + my $notice = Koha::Notice::Template->new( + { + name => 'Hold cancellation', + module => 'reserves', + code => 'HOLD_CANCELLATION', + title => 'Hold cancelled', + content => 'Your hold was cancelled.', + message_transport_type => 'email', + branchcode => q{}, + } + )->store(); - ModReserveCancelAll($item->id, $patron->id, 'TEST_REASON'); + ModReserveCancelAll( $item->id, $patron->id, 'TEST_REASON' ); $hold = Koha::Holds->find($reserve_id); - is( $hold, undef, 'Hold is not in the reserves table'); + is( $hold, undef, 'Hold is not in the reserves table' ); $hold = Koha::Old::Holds->find($reserve_id); - ok( $hold, 'Hold was found in the old reserves table'); + ok( $hold, 'Hold was found in the old reserves table' ); - my $message = Koha::Notice::Messages->find({ borrowernumber => $patron->id, letter_code => 'HOLD_CANCELLATION'}); - ok( $message, 'Found hold cancellation message'); - is( $message->subject, 'Hold cancelled', 'Message has correct title' ); - is( $message->content, 'Your hold was cancelled.', 'Message has correct content'); + my $message = Koha::Notice::Messages->find( { borrowernumber => $patron->id, letter_code => 'HOLD_CANCELLATION' } ); + ok( $message, 'Found hold cancellation message' ); + is( $message->subject, 'Hold cancelled', 'Message has correct title' ); + is( $message->content, 'Your hold was cancelled.', 'Message has correct content' ); $av->delete; $message->delete; @@ -738,12 +767,14 @@ subtest 'Desks' => sub { plan tests => 5; my $library = $builder->build_object( { class => 'Koha::Libraries' } ); - my $desk = Koha::Desk->new({ - desk_name => 'my_desk_name_for_test', - branchcode => $library->branchcode , - })->store; - ok($desk, "Desk created"); - my $item = $builder->build_sample_item({ library => $library->branchcode }); + my $desk = Koha::Desk->new( + { + desk_name => 'my_desk_name_for_test', + branchcode => $library->branchcode, + } + )->store; + ok( $desk, "Desk created" ); + my $item = $builder->build_sample_item( { library => $library->branchcode } ); my $manager = $builder->build_object( { class => "Koha::Patrons" } ); t::lib::Mocks::mock_userenv( { patron => $manager, branchcode => $manager->branchcode } ); @@ -752,7 +783,7 @@ subtest 'Desks' => sub { class => 'Koha::Patrons', value => { branchcode => $library->branchcode, } } - ); + ); my $reserve_id = C4::Reserves::AddReserve( { @@ -766,11 +797,11 @@ subtest 'Desks' => sub { my $hold = Koha::Holds->find($reserve_id); - ok($reserve_id, "Hold created"); - ok($hold, "Hold found"); - $hold->set_waiting($desk->desk_id); - is($hold->found, 'W', 'Hold is waiting with correct status set'); - is($hold->desk_id, $desk->desk_id, 'Hold is attach to its desk'); + ok( $reserve_id, "Hold created" ); + ok( $hold, "Hold found" ); + $hold->set_waiting( $desk->desk_id ); + is( $hold->found, 'W', 'Hold is waiting with correct status set' ); + is( $hold->desk_id, $desk->desk_id, 'Hold is attach to its desk' ); }; @@ -784,19 +815,20 @@ subtest 'get_items_that_can_fill' => sub { } )->delete; - my $biblio = $builder->build_sample_biblio; - my $itype_1 = $builder->build_object({ class => 'Koha::ItemTypes' }); # For 1, 2, 3, 4 - my $itype_2 = $builder->build_object({ class => 'Koha::ItemTypes' }); - my $item_1 = $builder->build_sample_item( { biblionumber => $biblio->biblionumber, itype => $itype_1->itemtype } ); - # waiting + my $biblio = $builder->build_sample_biblio; + my $itype_1 = $builder->build_object( { class => 'Koha::ItemTypes' } ); # For 1, 2, 3, 4 + my $itype_2 = $builder->build_object( { class => 'Koha::ItemTypes' } ); + my $item_1 = $builder->build_sample_item( { biblionumber => $biblio->biblionumber, itype => $itype_1->itemtype } ); + + # waiting my $item_2 = $builder->build_sample_item( { biblionumber => $biblio->biblionumber, itype => $itype_1->itemtype } ); - my $item_3 = $builder->build_sample_item( { biblionumber => $biblio->biblionumber, itype => $itype_1->itemtype } ) - ; # onloan + my $item_3 = + $builder->build_sample_item( { biblionumber => $biblio->biblionumber, itype => $itype_1->itemtype } ); # onloan my $item_4 = $builder->build_sample_item( { biblionumber => $biblio->biblionumber, itype => $itype_1->itemtype } ) - ; # in transfer + ; # in transfer my $item_5 = $builder->build_sample_item( { biblionumber => $biblio->biblionumber, itype => $itype_2->itemtype } ); - my $lost = $builder->build_sample_item( { biblionumber => $biblio->biblionumber, itemlost => 1 } ); - my $withdrawn = $builder->build_sample_item( { biblionumber => $biblio->biblionumber, withdrawn => 1 } ); + my $lost = $builder->build_sample_item( { biblionumber => $biblio->biblionumber, itemlost => 1 } ); + my $withdrawn = $builder->build_sample_item( { biblionumber => $biblio->biblionumber, withdrawn => 1 } ); my $notforloan = $builder->build_sample_item( { biblionumber => $biblio->biblionumber, notforloan => -1 } ); my $patron_1 = $builder->build_object( { class => 'Koha::Patrons' } ); @@ -817,9 +849,12 @@ subtest 'get_items_that_can_fill' => sub { } ); - my $holds = Koha::Holds->search({ reserve_id => $reserve_id_1 }); + my $holds = Koha::Holds->search( { reserve_id => $reserve_id_1 } ); my $items = $holds->get_items_that_can_fill; - is_deeply( [ map { $_->itemnumber } $items->as_list ], [ $item_1->itemnumber ], 'Item level hold can only be filled by the specific item'); + is_deeply( + [ map { $_->itemnumber } $items->as_list ], [ $item_1->itemnumber ], + 'Item level hold can only be filled by the specific item' + ); my $reserve_id_2 = C4::Reserves::AddReserve( { @@ -868,14 +903,13 @@ subtest 'get_items_that_can_fill' => sub { )->store; $holds = Koha::Holds->search( - { - reserve_id => [ $reserve_id_1, $reserve_id_2, $waiting_reserve_id, $notforloan_reserve_id, ] - } - ); + { reserve_id => [ $reserve_id_1, $reserve_id_2, $waiting_reserve_id, $notforloan_reserve_id, ] } ); $items = $holds->get_items_that_can_fill; - is_deeply( [ map { $_->itemnumber } $items->as_list ], - [ $item_2->itemnumber, $item_5->itemnumber ], 'Only item 2 and 5 are available for filling the hold' ); + is_deeply( + [ map { $_->itemnumber } $items->as_list ], + [ $item_2->itemnumber, $item_5->itemnumber ], 'Only item 2 and 5 are available for filling the hold' + ); # Marking item_5 is no hold allowed Koha::CirculationRule->new( @@ -886,26 +920,26 @@ subtest 'get_items_that_can_fill' => sub { } )->store; $items = $holds->get_items_that_can_fill; - is_deeply( [ map { $_->itemnumber } $items->as_list ], - [ $item_2->itemnumber ], 'Only item 2 is available for filling the hold' ); - + is_deeply( + [ map { $_->itemnumber } $items->as_list ], + [ $item_2->itemnumber ], 'Only item 2 is available for filling the hold' + ); my $noloan_itype = $builder->build_object( { class => 'Koha::ItemTypes', value => { notforloan => 1 } } ); t::lib::Mocks::mock_preference( 'item-level_itypes', 0 ); - Koha::Holds->find( $waiting_reserve_id )->delete; - $holds = Koha::Holds->search( - { - reserve_id => [ $reserve_id_1, $reserve_id_2 ] - } - ); + Koha::Holds->find($waiting_reserve_id)->delete; + $holds = Koha::Holds->search( { reserve_id => [ $reserve_id_1, $reserve_id_2 ] } ); $items = $holds->get_items_that_can_fill; - is_deeply( [ sort { $a <=> $b } map { $_->itemnumber } $items->as_list ], - [ $item_1->itemnumber, $item_2->itemnumber, $item_5->itemnumber ], 'Items 1, 2, and 5 are available for filling the holds' ); + is_deeply( + [ sort { $a <=> $b } map { $_->itemnumber } $items->as_list ], + [ $item_1->itemnumber, $item_2->itemnumber, $item_5->itemnumber ], + 'Items 1, 2, and 5 are available for filling the holds' + ); my $no_holds = Koha::Holds->new->empty(); my $no_items = $no_holds->get_items_that_can_fill(); - is( ref $no_items, "Koha::Items", "Routine returns a Koha::Items object"); - is( $no_items->count, 0, "Object is empty when called on no holds"); + is( ref $no_items, "Koha::Items", "Routine returns a Koha::Items object" ); + is( $no_items->count, 0, "Object is empty when called on no holds" ); }; @@ -913,11 +947,9 @@ subtest 'set_waiting+patron_expiration_date' => sub { plan tests => 2; my $library = $builder->build_object( { class => 'Koha::Libraries' } ); - my $item = - $builder->build_sample_item( { library => $library->branchcode } ); + my $item = $builder->build_sample_item( { library => $library->branchcode } ); my $manager = $builder->build_object( { class => "Koha::Patrons" } ); - t::lib::Mocks::mock_userenv( - { patron => $manager, branchcode => $manager->branchcode } ); + t::lib::Mocks::mock_userenv( { patron => $manager, branchcode => $manager->branchcode } ); my $patron = $builder->build_object( { @@ -959,9 +991,7 @@ subtest 'set_waiting+patron_expiration_date' => sub { is( $hold->expirationdate, $patron_expiration_date ); is( $hold->patron_expiration_date, $patron_expiration_date ); - C4::Reserves::RevertWaitingStatus( - { itemnumber => $item->itemnumber } - ); + C4::Reserves::RevertWaitingStatus( { itemnumber => $item->itemnumber } ); $hold = $hold->get_from_storage; is( $hold->expirationdate, $patron_expiration_date ); @@ -971,7 +1001,7 @@ subtest 'set_waiting+patron_expiration_date' => sub { subtest 'patron_expiration_date > expiration_date' => sub { plan tests => 6; t::lib::Mocks::mock_preference( 'ReservesMaxPickUpDelay', 5 ); - my $new_expiration_date = dt_from_string->add( days => 5 )->ymd; + my $new_expiration_date = dt_from_string->add( days => 5 )->ymd; my $patron_expiration_date = dt_from_string->add( days => 6 )->ymd; my $reserve_id = C4::Reserves::AddReserve( { @@ -1002,9 +1032,7 @@ subtest 'set_waiting+patron_expiration_date' => sub { is( $hold->expirationdate, $new_expiration_date ); is( $hold->patron_expiration_date, $patron_expiration_date ); - C4::Reserves::RevertWaitingStatus( - { itemnumber => $item->itemnumber } - ); + C4::Reserves::RevertWaitingStatus( { itemnumber => $item->itemnumber } ); $hold = $hold->get_from_storage; is( $hold->expirationdate, $patron_expiration_date ); @@ -1015,8 +1043,8 @@ subtest 'set_waiting+patron_expiration_date' => sub { subtest 'Test Koha::Hold::item_group' => sub { plan tests => 1; my $library = $builder->build_object( { class => 'Koha::Libraries' } ); - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); - my $item = $builder->build_sample_item; + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + my $item = $builder->build_sample_item; my $item_group = $builder->build_object( { class => 'Koha::Biblio::ItemGroups', @@ -1024,20 +1052,21 @@ subtest 'Test Koha::Hold::item_group' => sub { ); my $reserve_id = AddReserve( { - branchcode => $library->branchcode, - borrowernumber => $patron->borrowernumber, - biblionumber => $item->biblionumber, - itemnumber => $item->itemnumber, - item_group_id => $item_group->id, + branchcode => $library->branchcode, + borrowernumber => $patron->borrowernumber, + biblionumber => $item->biblionumber, + itemnumber => $item->itemnumber, + item_group_id => $item_group->id, } ); my $hold = Koha::Holds->find($reserve_id); - is( $hold->item_group_id, $item_group->id, - 'Koha::Hold::item_group returns the correct item_group' ); + is( + $hold->item_group_id, $item_group->id, + 'Koha::Hold::item_group returns the correct item_group' + ); }; - $schema->storage->txn_rollback; subtest 'filter_by_found() tests' => sub { @@ -1053,7 +1082,7 @@ subtest 'filter_by_found() tests' => sub { my $holds = Koha::Holds->search( { reserve_id => [ $unfilled->id, $processing->id, $in_transit->id, $waiting->id ] }, - { order_by => ['reserve_id'] } + { order_by => ['reserve_id'] } ); is( $holds->count, 4, 'Resultset count is correct' ); @@ -1063,9 +1092,8 @@ subtest 'filter_by_found() tests' => sub { is( $found_holds->count, 3, 'Resultset count is correct' ); ok( $found_holds->next->is_in_processing, 'Status is correct (P)' ); - ok( $found_holds->next->is_in_transit, 'Status is correct (T)' ); - ok( $found_holds->next->is_waiting, 'Status is correct (W)' ); - + ok( $found_holds->next->is_in_transit, 'Status is correct (T)' ); + ok( $found_holds->next->is_waiting, 'Status is correct (W)' ); $schema->storage->txn_rollback; }; @@ -1116,8 +1144,7 @@ subtest 'filter_by_has_cancellation_requests() and filter_out_has_cancellation_r } ); - my $rs = Koha::Holds->search( - { reserve_id => [ $hold_1->id, $hold_2->id, $hold_3->id ] } ); + my $rs = Koha::Holds->search( { reserve_id => [ $hold_1->id, $hold_2->id, $hold_3->id ] } ); is( $rs->count, 3 ); @@ -1169,7 +1196,7 @@ subtest 'processing() tests' => sub { } ); - my $holds = Koha::Holds->search({ reserve_id => [ $hold_1->id, $hold_2->id, $hold_3->id ] }); + my $holds = Koha::Holds->search( { reserve_id => [ $hold_1->id, $hold_2->id, $hold_3->id ] } ); is( $holds->count, 3, 'Resultset contains 3 holds' ); my $processing = $holds->processing; diff --git a/t/db_dependent/Koha/ILL/Request/Config.t b/t/db_dependent/Koha/ILL/Request/Config.t index 2d4b60f260..f7fa7616e5 100755 --- a/t/db_dependent/Koha/ILL/Request/Config.t +++ b/t/db_dependent/Koha/ILL/Request/Config.t @@ -25,13 +25,13 @@ use Test::Exception; use Test::More tests => 6; -my $schema = Koha::Database->new->schema; +my $schema = Koha::Database->new->schema; my $builder = t::lib::TestBuilder->new; use_ok('Koha::ILL::Request::Config'); my $base_limits = { - branch => { CPL => { count => 1, method => 'annual' } }, - brw_cat => { A => { count => -1, method => 'active' } }, + branch => { CPL => { count => 1, method => 'annual' } }, + brw_cat => { A => { count => -1, method => 'active' } }, default => { count => 10, method => 'annual' }, }; @@ -43,49 +43,61 @@ subtest 'Basics' => sub { $schema->storage->txn_begin; - t::lib::Mocks::mock_config("interlibrary_loans", {}); - t::lib::Mocks::mock_preference('ILLPartnerCode', undef); + t::lib::Mocks::mock_config( "interlibrary_loans", {} ); + t::lib::Mocks::mock_preference( 'ILLPartnerCode', undef ); my $config = Koha::ILL::Request::Config->new; - isa_ok($config, "Koha::ILL::Request::Config", - "Correctly create and load a config object."); + isa_ok( + $config, "Koha::ILL::Request::Config", + "Correctly create and load a config object." + ); # backend: - is($config->backend, undef, "backend: Undefined backend is undefined."); - is($config->backend("Mock"), "Mock", "backend: setter works."); - is($config->backend, "Mock", "backend: setter is persistent."); + is( $config->backend, undef, "backend: Undefined backend is undefined." ); + is( $config->backend("Mock"), "Mock", "backend: setter works." ); + is( $config->backend, "Mock", "backend: setter is persistent." ); # backend_dir: - is($config->backend_dir, undef, "backend_dir: Undefined backend_dir is undefined."); - is($config->backend_dir("/tmp/"), "/tmp/", "backend_dir: setter works."); - is($config->backend_dir, "/tmp/", "backend_dir: setter is persistent."); + is( $config->backend_dir, undef, "backend_dir: Undefined backend_dir is undefined." ); + is( $config->backend_dir("/tmp/"), "/tmp/", "backend_dir: setter works." ); + is( $config->backend_dir, "/tmp/", "backend_dir: setter is persistent." ); # partner_code: - is($config->partner_code, 'IL', "partner_code: Undefined partner_code fallback to 'IL'."); - is($config->partner_code("ILTST"), "ILTST", "partner_code: setter works."); - is($config->partner_code, "ILTST", "partner_code: setter is persistent."); + is( $config->partner_code, 'IL', "partner_code: Undefined partner_code fallback to 'IL'." ); + is( $config->partner_code("ILTST"), "ILTST", "partner_code: setter works." ); + is( $config->partner_code, "ILTST", "partner_code: setter is persistent." ); # limits: - is_deeply($config->limits, {}, "limits: Undefined limits is empty hash."); - is_deeply($config->limits($base_limits), $base_limits, "limits: setter works."); - is_deeply($config->limits, $base_limits, "limits: setter is persistent."); + is_deeply( $config->limits, {}, "limits: Undefined limits is empty hash." ); + is_deeply( $config->limits($base_limits), $base_limits, "limits: setter works." ); + is_deeply( $config->limits, $base_limits, "limits: setter is persistent." ); # censorship: - is_deeply($config->censorship, { censor_notes_staff => 0, censor_reply_date => 0 }, - "censorship: Undefined censorship is default values."); - is_deeply($config->censorship($base_censorship), $base_censorship, "censorship: setter works."); - is_deeply($config->censorship, $base_censorship, "censorship: setter is persistent."); + is_deeply( + $config->censorship, { censor_notes_staff => 0, censor_reply_date => 0 }, + "censorship: Undefined censorship is default values." + ); + is_deeply( $config->censorship($base_censorship), $base_censorship, "censorship: setter works." ); + is_deeply( $config->censorship, $base_censorship, "censorship: setter is persistent." ); # getLimitRules - dies_ok( sub { $config->getLimitRules("FOO") }, "getLimitRules: die if not correct type."); - is_deeply($config->getLimitRules("brw_cat"), { - A => { count => -1, method => 'active' }, - default => { count => 10, method => 'annual' }, - }, "getLimitRules: fetch brw_cat limits."); - is_deeply($config->getLimitRules("branch"), { - CPL => { count => 1, method => 'annual' }, - default => { count => 10, method => 'annual' }, - }, "getLimitRules: fetch brw_cat limits."); + dies_ok( sub { $config->getLimitRules("FOO") }, "getLimitRules: die if not correct type." ); + is_deeply( + $config->getLimitRules("brw_cat"), + { + A => { count => -1, method => 'active' }, + default => { count => 10, method => 'annual' }, + }, + "getLimitRules: fetch brw_cat limits." + ); + is_deeply( + $config->getLimitRules("branch"), + { + CPL => { count => 1, method => 'annual' }, + default => { count => 10, method => 'annual' }, + }, + "getLimitRules: fetch brw_cat limits." + ); $schema->storage->txn_rollback; }; @@ -101,80 +113,99 @@ subtest '_load_unit_config' => sub { my $config = Koha::ILL::Request::Config->new; dies_ok( - sub { Koha::ILL::Request::Config::_load_unit_config({ - id => 'durineadu', type => 'baz' - }) }, + sub { + Koha::ILL::Request::Config::_load_unit_config( { id => 'durineadu', type => 'baz' } ); + }, "_load_unit_config: die if ID is not default, and type is not branch or brw_cat." ); is_deeply( - Koha::ILL::Request::Config::_load_unit_config({ - unit => {}, id => 'default', config => {}, test => 1 - }), {}, "_load_unit_config: invocation without id returns unmodified config." + Koha::ILL::Request::Config::_load_unit_config( { unit => {}, id => 'default', config => {}, test => 1 } ), {}, + "_load_unit_config: invocation without id returns unmodified config." ); is_deeply( - Koha::ILL::Request::Config::_load_unit_config({ - unit => { api_key => 'foo', api_auth => 'bar' }, - id => "CPL", type => 'branch', config => {} - }), + Koha::ILL::Request::Config::_load_unit_config( + { + unit => { api_key => 'foo', api_auth => 'bar' }, + id => "CPL", type => 'branch', config => {} + } + ), { credentials => { api_keys => { CPL => { api_key => 'foo', api_auth => 'bar' } } } }, "_load_unit_config: add auth values." ); # Populate request_limits is_deeply( - Koha::ILL::Request::Config::_load_unit_config({ - unit => { request_limit => [ 'heelo', 1234 ] }, - id => "CPL", type => 'branch', config => {} - }), {}, "_load_unit_config: invalid request_limit structure." + Koha::ILL::Request::Config::_load_unit_config( + { + unit => { request_limit => [ 'heelo', 1234 ] }, + id => "CPL", type => 'branch', config => {} + } + ), + {}, + "_load_unit_config: invalid request_limit structure." ); is_deeply( - Koha::ILL::Request::Config::_load_unit_config({ - unit => { request_limit => { method => 'eudiren', count => '-5465' } }, - id => "CPL", type => 'branch', config => {} - }), {}, "_load_unit_config: invalid method & count." + Koha::ILL::Request::Config::_load_unit_config( + { + unit => { request_limit => { method => 'eudiren', count => '-5465' } }, + id => "CPL", type => 'branch', config => {} + } + ), + {}, + "_load_unit_config: invalid method & count." ); is_deeply( - Koha::ILL::Request::Config::_load_unit_config({ - unit => { request_limit => { method => 'annual', count => 6 } }, - id => "default", config => {} - }), + Koha::ILL::Request::Config::_load_unit_config( + { + unit => { request_limit => { method => 'annual', count => 6 } }, + id => "default", config => {} + } + ), { limits => { default => { method => 'annual', count => 6 } } }, "_load_unit_config: correct default request_limits." ); # Populate prefix is_deeply( - Koha::ILL::Request::Config::_load_unit_config({ - unit => { prefix => 'Foo-ill' }, - id => "default", config => {} - }), + Koha::ILL::Request::Config::_load_unit_config( + { + unit => { prefix => 'Foo-ill' }, + id => "default", config => {} + } + ), { prefixes => { default => 'Foo-ill' } }, "_load_unit_config: correct default prefix." ); is_deeply( - Koha::ILL::Request::Config::_load_unit_config({ - unit => { prefix => 'Foo-ill' }, - id => "A", config => {}, type => 'brw_cat' - }), + Koha::ILL::Request::Config::_load_unit_config( + { + unit => { prefix => 'Foo-ill' }, + id => "A", config => {}, type => 'brw_cat' + } + ), { prefixes => { brw_cat => { A => 'Foo-ill' } } }, "_load_unit_config: correct brw_cat prefix." ); # Populate digital_recipient is_deeply( - Koha::ILL::Request::Config::_load_unit_config({ - unit => { digital_recipient => 'borrower' }, - id => "default", config => {} - }), + Koha::ILL::Request::Config::_load_unit_config( + { + unit => { digital_recipient => 'borrower' }, + id => "default", config => {} + } + ), { digital_recipients => { default => 'borrower' } }, "_load_unit_config: correct default digital_recipient." ); is_deeply( - Koha::ILL::Request::Config::_load_unit_config({ - unit => { digital_recipient => 'branch' }, - id => "A", config => {}, type => 'brw_cat' - }), + Koha::ILL::Request::Config::_load_unit_config( + { + unit => { digital_recipient => 'branch' }, + id => "A", config => {}, type => 'brw_cat' + } + ), { digital_recipients => { brw_cat => { A => 'branch' } } }, "_load_unit_config: correct brw_cat digital_recipient." ); @@ -199,16 +230,16 @@ subtest '_load_configuration' => sub { $schema->storage->txn_begin; my $config = Koha::ILL::Request::Config->new; - t::lib::Mocks::mock_preference('ILLPartnerCode', 'IL'); + t::lib::Mocks::mock_preference( 'ILLPartnerCode', 'IL' ); # Return basic configuration is_deeply( Koha::ILL::Request::Config::_load_configuration( {}, 0 ), { - backend_directory => undef, - censorship => { + backend_directory => undef, + censorship => { censor_notes_staff => 0, - censor_reply_date => 0, + censor_reply_date => 0, }, limits => {}, digital_recipients => {}, @@ -223,10 +254,10 @@ subtest '_load_configuration' => sub { is_deeply( Koha::ILL::Request::Config::_load_configuration( { backend_directory => '/tmp/' }, 0 ), { - backend_directory => '/tmp/', - censorship => { + backend_directory => '/tmp/', + censorship => { censor_notes_staff => 0, - censor_reply_date => 0, + censor_reply_date => 0, }, limits => {}, digital_recipients => {}, @@ -240,19 +271,19 @@ subtest '_load_configuration' => sub { # Map over branch configs my $xml_config = { backend_directory => '/tmp/', - branch => [ - { code => '1', request_limit => { method => 'annual', count => 1 } }, - { code => '2', prefix => '2-prefix' }, + branch => [ + { code => '1', request_limit => { method => 'annual', count => 1 } }, + { code => '2', prefix => '2-prefix' }, { code => '3', digital_recipient => 'branch' } ] }; is_deeply( Koha::ILL::Request::Config::_load_configuration( $xml_config, 0 ), { - backend_directory => '/tmp/', - censorship => { + backend_directory => '/tmp/', + censorship => { censor_notes_staff => 0, - censor_reply_date => 0, + censor_reply_date => 0, }, limits => { branch => { 1 => { method => 'annual', count => 1 } } }, digital_recipients => { branch => { 3 => 'branch' } }, @@ -262,23 +293,24 @@ subtest '_load_configuration' => sub { }, "load_configuration: multi branch config parsed correctly." ); + # Single branch config $xml_config = { backend_directory => '/tmp/', - branch => { - code => '1', - request_limit => { method => 'annual', count => 1 }, - prefix => '2-prefix', + branch => { + code => '1', + request_limit => { method => 'annual', count => 1 }, + prefix => '2-prefix', digital_recipient => 'branch', } }; is_deeply( Koha::ILL::Request::Config::_load_configuration( $xml_config, 0 ), { - backend_directory => '/tmp/', - censorship => { + backend_directory => '/tmp/', + censorship => { censor_notes_staff => 0, - censor_reply_date => 0, + censor_reply_date => 0, }, limits => { branch => { 1 => { method => 'annual', count => 1 } } }, digital_recipients => { branch => { 1 => 'branch' } }, @@ -293,18 +325,18 @@ subtest '_load_configuration' => sub { $xml_config = { backend_directory => '/tmp/', borrower_category => [ - { code => 'A', request_limit => { method => 'annual', count => 1 } }, - { code => 'B', prefix => '2-prefix' }, + { code => 'A', request_limit => { method => 'annual', count => 1 } }, + { code => 'B', prefix => '2-prefix' }, { code => 'C', digital_recipient => 'branch' } ] }; is_deeply( Koha::ILL::Request::Config::_load_configuration( $xml_config, 0 ), { - backend_directory => '/tmp/', - censorship => { + backend_directory => '/tmp/', + censorship => { censor_notes_staff => 0, - censor_reply_date => 0, + censor_reply_date => 0, }, limits => { brw_cat => { A => { method => 'annual', count => 1 } } }, digital_recipients => { brw_cat => { C => 'branch' } }, @@ -314,23 +346,24 @@ subtest '_load_configuration' => sub { }, "load_configuration: multi borrower_category config parsed correctly." ); + # Single borrower_category config $xml_config = { backend_directory => '/tmp/', borrower_category => { - code => '1', - request_limit => { method => 'annual', count => 1 }, - prefix => '2-prefix', + code => '1', + request_limit => { method => 'annual', count => 1 }, + prefix => '2-prefix', digital_recipient => 'branch', } }; is_deeply( Koha::ILL::Request::Config::_load_configuration( $xml_config, 0 ), { - backend_directory => '/tmp/', - censorship => { + backend_directory => '/tmp/', + censorship => { censor_notes_staff => 0, - censor_reply_date => 0, + censor_reply_date => 0, }, limits => { brw_cat => { 1 => { method => 'annual', count => 1 } } }, digital_recipients => { brw_cat => { 1 => 'branch' } }, @@ -344,17 +377,17 @@ subtest '_load_configuration' => sub { # Default Configuration $xml_config = { backend_directory => '/tmp/', - request_limit => { method => 'annual', count => 1 }, - prefix => '2-prefix', + request_limit => { method => 'annual', count => 1 }, + prefix => '2-prefix', digital_recipient => 'branch', }; is_deeply( Koha::ILL::Request::Config::_load_configuration( $xml_config, 0 ), { - backend_directory => '/tmp/', - censorship => { + backend_directory => '/tmp/', + censorship => { censor_notes_staff => 0, - censor_reply_date => 0, + censor_reply_date => 0, }, limits => { default => { method => 'annual', count => 1 } }, digital_recipients => { default => 'branch' }, @@ -367,17 +400,17 @@ subtest '_load_configuration' => sub { # Censorship $xml_config = { - backend_directory => '/tmp/', + backend_directory => '/tmp/', staff_request_comments => 'hide', - reply_date => 'hide' + reply_date => 'hide' }; is_deeply( Koha::ILL::Request::Config::_load_configuration( $xml_config, 0 ), { - backend_directory => '/tmp/', - censorship => { + backend_directory => '/tmp/', + censorship => { censor_notes_staff => 1, - censor_reply_date => 1, + censor_reply_date => 1, }, limits => {}, digital_recipients => {}, @@ -428,61 +461,76 @@ subtest '_load_configuration' => sub { $schema->storage->txn_rollback; }; - subtest 'Final tests' => sub { plan tests => 9; $schema->storage->txn_begin; - t::lib::Mocks::mock_config("interlibrary_loans", {}); + t::lib::Mocks::mock_config( "interlibrary_loans", {} ); my $config = Koha::ILL::Request::Config->new; # getPrefixes (error & undef): - is($config->getPrefixes(), undef, - "getPrefixes: Undefined branch prefix is undefined."); + is( + $config->getPrefixes(), undef, + "getPrefixes: Undefined branch prefix is undefined." + ); - is($config->has_branch(), undef, "Config does not have branch when no config loaded"); + is( $config->has_branch(), undef, "Config does not have branch when no config loaded" ); # getDigitalRecipients (error & undef): - dies_ok( sub { $config->getDigitalRecipients("FOO") }, - "getDigitalRecipients: die if not correct type."); - is_deeply($config->getDigitalRecipients("brw_cat"), { default => undef}, - "getDigitalRecipients: Undefined brw_cat dig rec is undefined."); - is_deeply($config->getDigitalRecipients("branch"), { default => undef}, - "getDigitalRecipients: Undefined branch dig rec is undefined."); + dies_ok( + sub { $config->getDigitalRecipients("FOO") }, + "getDigitalRecipients: die if not correct type." + ); + is_deeply( + $config->getDigitalRecipients("brw_cat"), { default => undef }, + "getDigitalRecipients: Undefined brw_cat dig rec is undefined." + ); + is_deeply( + $config->getDigitalRecipients("branch"), { default => undef }, + "getDigitalRecipients: Undefined branch dig rec is undefined." + ); - $config->{configuration} = Koha::ILL::Request::Config::_load_configuration({ + $config->{configuration} = Koha::ILL::Request::Config::_load_configuration( + { backend_directory => '/tmp/', - prefix => 'DEFAULT-prefix', + prefix => 'DEFAULT-prefix', digital_recipient => 'branch', borrower_category => [ - { code => 'B', prefix => '2-prefix' }, + { code => 'B', prefix => '2-prefix' }, { code => 'C', digital_recipient => 'branch' } ], branch => [ - { code => '1', prefix => 'T-prefix' }, + { code => '1', prefix => 'T-prefix' }, { code => '2', digital_recipient => 'borrower' } ] - }, 0 + }, + 0 ); # getPrefixes (values): - is_deeply($config->getPrefixes(), - { '1' => 'T-prefix' }, - "getPrefixes: return configuration branch prefixes."); + is_deeply( + $config->getPrefixes(), + { '1' => 'T-prefix' }, + "getPrefixes: return configuration branch prefixes." + ); # getDigitalRecipients (values): - is_deeply($config->getDigitalRecipients("brw_cat"), - { C => 'branch', default => 'branch' }, - "getDigitalRecipients: return brw_cat digital_recipients."); - is_deeply($config->getDigitalRecipients("branch"), - { 2 => 'borrower', default => 'branch' }, - "getDigitalRecipients: return branch digital_recipients."); + is_deeply( + $config->getDigitalRecipients("brw_cat"), + { C => 'branch', default => 'branch' }, + "getDigitalRecipients: return brw_cat digital_recipients." + ); + is_deeply( + $config->getDigitalRecipients("branch"), + { 2 => 'borrower', default => 'branch' }, + "getDigitalRecipients: return branch digital_recipients." + ); # has_branch test - ok($config->has_branch(), "has_branch returns true if branch defined in configuration"); + ok( $config->has_branch(), "has_branch returns true if branch defined in configuration" ); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/Koha/ILL/Request/Logger.t b/t/db_dependent/Koha/ILL/Request/Logger.t index 8fc5e7fb8f..ad2df153fa 100755 --- a/t/db_dependent/Koha/ILL/Request/Logger.t +++ b/t/db_dependent/Koha/ILL/Request/Logger.t @@ -29,10 +29,12 @@ my $schema = Koha::Database->new->schema; # Mock the modules we use my $c4_log = Test::MockModule->new('C4::Log'); -$c4_log->mock('logaction', sub { 1 }); +$c4_log->mock( 'logaction', sub { 1 } ); my $c4_tpl = Test::MockModule->new('C4::Templates'); -$c4_tpl->mock('_get_template_file', - sub { return ('htdocs', 'theme', 'lang', 'base/'); }); +$c4_tpl->mock( + '_get_template_file', + sub { return ( 'htdocs', 'theme', 'lang', 'base/' ); } +); use_ok('Koha::ILL::Request::Logger'); @@ -47,48 +49,61 @@ subtest 'Basics' => sub { # new() # ok( defined($logger), 'new() returned something' ); - ok( $logger->isa('Koha::ILL::Request::Logger'), - 'new() returns the correct object' ); + ok( + $logger->isa('Koha::ILL::Request::Logger'), + 'new() returns the correct object' + ); # This is an incomplete data hashref, we use it to # test validation of the data before logging my $log_obj = { - modulename => 'modulename', - actionname => 'actionname', - infos => 'infos' + modulename => 'modulename', + actionname => 'actionname', + infos => 'infos' }; # log_something() # # Do we only log when the pref is set (currently unset) - is($logger->log_something(), '', - 'logaction() not being called without pref being set'); + is( + $logger->log_something(), '', + 'logaction() not being called without pref being set' + ); # Set the pref t::lib::Mocks::mock_preference( 'IllLog', 1 ); + # We should not log without all the required data, we are still # using the incomplete hashref - is($logger->log_something(), '', - 'logaction() being called when data is incomplete'); + is( + $logger->log_something(), '', + 'logaction() being called when data is incomplete' + ); # Fix the data hashref, then test that logging occurs $log_obj->{objectnumber} = 'objectnumber'; - is($logger->log_something($log_obj), 1, - 'logaction() being called when pref is set and data is complete'); + is( + $logger->log_something($log_obj), 1, + 'logaction() being called when pref is set and data is complete' + ); # log_maybe() # - is($logger->log_maybe({}, {}), '', - 'log_maybe() does not log with incomplete data'); + is( + $logger->log_maybe( {}, {} ), '', + 'log_maybe() does not log with incomplete data' + ); # get_log_template() # is( - $logger->get_log_template({ - request => {}, - origin => 'core', - action => 'STATUS_CHANGE' - }), + $logger->get_log_template( + { + request => {}, + origin => 'core', + action => 'STATUS_CHANGE' + } + ), 'base/status_change.tt', 'get_log_template() fetches correct core template' ); diff --git a/t/db_dependent/Koha/ILL/Request/SupplierUpdate.t b/t/db_dependent/Koha/ILL/Request/SupplierUpdate.t index 00dcfe3fc3..b90dc8abb6 100755 --- a/t/db_dependent/Koha/ILL/Request/SupplierUpdate.t +++ b/t/db_dependent/Koha/ILL/Request/SupplierUpdate.t @@ -37,28 +37,33 @@ isa_ok( $update, 'Koha::ILL::Request::SupplierUpdate' ); my $processor = Test::MockObject->new; $processor->set_isa('Koha::ILL::Request::Processor'); $processor->{name} = 'Test processor'; -$processor->mock('run', sub { - my ( $self, $update, $options, $result ) = @_; - push @{$result->{success}}, 'Hello'; -}); +$processor->mock( + 'run', + sub { + my ( $self, $update, $options, $result ) = @_; + push @{ $result->{success} }, 'Hello'; + } +); # attach_processor $update->attach_processor($processor); is( - scalar @{$update->{processors}}, + scalar @{ $update->{processors} }, 1, 'attach_processors works' ); # run_processors is_deeply( - $update->run_processors({}), - [{ - name => 'Test processor', - result => { - success => ['Hello'], - error => [] + $update->run_processors( {} ), + [ + { + name => 'Test processor', + result => { + success => ['Hello'], + error => [] + } } - }], + ], 'run_processors calls attached processors' ); diff --git a/t/db_dependent/Koha/ILL/Request/SupplierUpdateProcessor.t b/t/db_dependent/Koha/ILL/Request/SupplierUpdateProcessor.t index d4110f30bd..7ea29f277e 100755 --- a/t/db_dependent/Koha/ILL/Request/SupplierUpdateProcessor.t +++ b/t/db_dependent/Koha/ILL/Request/SupplierUpdateProcessor.t @@ -34,4 +34,5 @@ isa_ok( $processor, 'Koha::ILL::Request::SupplierUpdateProcessor' ); warning_like { $processor->run() -} qr/run should only be invoked by a subclass/, 'Invoking base class "run" warns'; +} +qr/run should only be invoked by a subclass/, 'Invoking base class "run" warns'; diff --git a/t/db_dependent/Koha/ILL/Request/Workflow/Availability.t b/t/db_dependent/Koha/ILL/Request/Workflow/Availability.t index d80dca387a..24312257bf 100755 --- a/t/db_dependent/Koha/ILL/Request/Workflow/Availability.t +++ b/t/db_dependent/Koha/ILL/Request/Workflow/Availability.t @@ -47,14 +47,13 @@ foreach my $key ( keys %{$metadata} ) { $sorted->{$key} = $metadata->{$key}; } -my $availability = - Koha::ILL::Request::Workflow::Availability->new( $sorted, 'staff' ); +my $availability = Koha::ILL::Request::Workflow::Availability->new( $sorted, 'staff' ); isa_ok( $availability, 'Koha::ILL::Request::Workflow::Availability' ); is( $availability->prep_metadata($sorted), -'eyJhdXRob3IiOiJUaGlzIGlzIGFuIGF1dGhvciIsInRpdGxlIjoiVGhpcyBpcyBhIHRpdGxlIn0%3D%0A', + 'eyJhdXRob3IiOiJUaGlzIGlzIGFuIGF1dGhvciIsInRpdGxlIjoiVGhpcyBpcyBhIHRpdGxlIn0%3D%0A', 'prep_metadata works' ); @@ -77,15 +76,16 @@ $backend->mock( 'status_graph', sub { }, ); # Mock Koha::ILL::Request::load_backend (to load Mocked Backend) my $illreqmodule = Test::MockModule->new('Koha::ILL::Request'); -$illreqmodule->mock( 'load_backend', - sub { my $self = shift; $self->{_my_backend} = $backend; return $self } ); +$illreqmodule->mock( + 'load_backend', + sub { my $self = shift; $self->{_my_backend} = $backend; return $self } +); # Mock ILLModuleDisclaimerByType with valid YAML t::lib::Mocks::mock_preference( 'ILLCheckAvailability', 1 ); # Mock not empty availability services -my $availability_module = - Test::MockModule->new('Koha::ILL::Request::Workflow::Availability'); +my $availability_module = Test::MockModule->new('Koha::ILL::Request::Workflow::Availability'); $availability_module->mock( 'get_services', [ { name => 'service' } ] ); my $req_1 = $builder->build_object( @@ -97,13 +97,17 @@ my $req_1 = $builder->build_object( my $request = $req_1->load_backend('Mock'); -is( $availability->show_availability($request), - 1, 'able to show availability search' ); +is( + $availability->show_availability($request), + 1, 'able to show availability search' +); # Mock empty availability services $availability_module->mock( 'get_services', [] ); -is( $availability->show_availability($request), - 0, 'unable to show type disclaimer form' ); +is( + $availability->show_availability($request), + 0, 'unable to show type disclaimer form' +); -$schema->storage->txn_rollback; \ No newline at end of file +$schema->storage->txn_rollback; diff --git a/t/db_dependent/Koha/ILL/Request/Workflow/TypeDisclaimer.t b/t/db_dependent/Koha/ILL/Request/Workflow/TypeDisclaimer.t index b910f2c9da..f69d34b5a4 100755 --- a/t/db_dependent/Koha/ILL/Request/Workflow/TypeDisclaimer.t +++ b/t/db_dependent/Koha/ILL/Request/Workflow/TypeDisclaimer.t @@ -48,14 +48,13 @@ foreach my $key ( keys %{$metadata} ) { $sorted->{$key} = $metadata->{$key}; } -my $type_disclaimer = - Koha::ILL::Request::Workflow::TypeDisclaimer->new( $sorted, 'staff' ); +my $type_disclaimer = Koha::ILL::Request::Workflow::TypeDisclaimer->new( $sorted, 'staff' ); isa_ok( $type_disclaimer, 'Koha::ILL::Request::Workflow::TypeDisclaimer' ); is( $type_disclaimer->prep_metadata($sorted), -'eyJhdXRob3IiOiJUaGlzIGlzIGFuIGF1dGhvciIsInRpdGxlIjoiVGhpcyBpcyBhIHRpdGxlIiwi%0AdHlwZSI6ImpvdXJuYWwifQ%3D%3D%0A', + 'eyJhdXRob3IiOiJUaGlzIGlzIGFuIGF1dGhvciIsInRpdGxlIjoiVGhpcyBpcyBhIHRpdGxlIiwi%0AdHlwZSI6ImpvdXJuYWwifQ%3D%3D%0A', 'prep_metadata works' ); @@ -78,8 +77,10 @@ $backend->mock( 'status_graph', sub { }, ); # Mock Koha::ILL::Request::load_backend (to load Mocked Backend) my $illreqmodule = Test::MockModule->new('Koha::ILL::Request'); -$illreqmodule->mock( 'load_backend', - sub { my $self = shift; $self->{_my_backend} = $backend; return $self } ); +$illreqmodule->mock( + 'load_backend', + sub { my $self = shift; $self->{_my_backend} = $backend; return $self } +); # Mock ILLModuleDisclaimerByType with valid YAML t::lib::Mocks::mock_preference( @@ -104,15 +105,18 @@ my $req_1 = $builder->build_object( my $request = $req_1->load_backend('Mock'); -is( $type_disclaimer->show_type_disclaimer($request), - 1, 'able to show type disclaimer form' ); +is( + $type_disclaimer->show_type_disclaimer($request), + 1, 'able to show type disclaimer form' +); # Mock ILLModuleDisclaimerByType with invalid YAML -my $type_disclaimer_module = - Test::MockModule->new('Koha::ILL::Request::Workflow::TypeDisclaimer'); +my $type_disclaimer_module = Test::MockModule->new('Koha::ILL::Request::Workflow::TypeDisclaimer'); $type_disclaimer_module->mock( '_get_type_disclaimer_sys_pref', {} ); -is( $type_disclaimer->show_type_disclaimer($request), - 0, 'not able to show type disclaimer form' ); +is( + $type_disclaimer->show_type_disclaimer($request), + 0, 'not able to show type disclaimer form' +); $schema->storage->txn_rollback; diff --git a/t/db_dependent/Koha/ILL/Requests.t b/t/db_dependent/Koha/ILL/Requests.t index c4a536f01a..c5ba6262cb 100755 --- a/t/db_dependent/Koha/ILL/Requests.t +++ b/t/db_dependent/Koha/ILL/Requests.t @@ -43,7 +43,7 @@ use Test::Warn; use Test::More tests => 16; -my $schema = Koha::Database->new->schema; +my $schema = Koha::Database->new->schema; my $builder = t::lib::TestBuilder->new; use_ok('Koha::ILL::Request'); use_ok('Koha::ILL::Requests'); @@ -55,72 +55,122 @@ subtest 'Basic object tests' => sub { $schema->storage->txn_begin; Koha::ILL::Requests->search->delete; - my $illrq = $builder->build({ source => 'Illrequest' }); - my $illrq_obj = Koha::ILL::Requests->find($illrq->{illrequest_id}); + my $illrq = $builder->build( { source => 'Illrequest' } ); + my $illrq_obj = Koha::ILL::Requests->find( $illrq->{illrequest_id} ); - isa_ok($illrq_obj, 'Koha::ILL::Request', - "Correctly create and load an illrequest object."); - isa_ok($illrq_obj->_config, 'Koha::ILL::Request::Config', - "Created a config object as part of Illrequest creation."); + isa_ok( + $illrq_obj, 'Koha::ILL::Request', + "Correctly create and load an illrequest object." + ); + isa_ok( + $illrq_obj->_config, 'Koha::ILL::Request::Config', + "Created a config object as part of Illrequest creation." + ); - is($illrq_obj->illrequest_id, $illrq->{illrequest_id}, - "Illrequest_id getter works."); - is($illrq_obj->borrowernumber, $illrq->{borrowernumber}, - "Borrowernumber getter works."); - is($illrq_obj->biblio_id, $illrq->{biblio_id}, - "Biblio_Id getter works."); - is($illrq_obj->branchcode, $illrq->{branchcode}, - "Branchcode getter works."); - is($illrq_obj->status, $illrq->{status}, - "Status getter works."); - is($illrq_obj->placed, $illrq->{placed}, - "Placed getter works."); - is($illrq_obj->replied, $illrq->{replied}, - "Replied getter works."); - is($illrq_obj->updated, $illrq->{updated}, - "Updated getter works."); - is($illrq_obj->completed, $illrq->{completed}, - "Completed getter works."); - is($illrq_obj->medium, $illrq->{medium}, - "Medium getter works."); - is($illrq_obj->accessurl, $illrq->{accessurl}, - "Accessurl getter works."); - is($illrq_obj->cost, $illrq->{cost}, - "Cost getter works."); - is($illrq_obj->price_paid, $illrq->{price_paid}, - "Price_paid getter works."); - is($illrq_obj->notesopac, $illrq->{notesopac}, - "Notesopac getter works."); - is($illrq_obj->notesstaff, $illrq->{notesstaff}, - "Notesstaff getter works."); - is($illrq_obj->orderid, $illrq->{orderid}, - "Orderid getter works."); - is($illrq_obj->backend, $illrq->{backend}, - "Backend getter works."); + is( + $illrq_obj->illrequest_id, $illrq->{illrequest_id}, + "Illrequest_id getter works." + ); + is( + $illrq_obj->borrowernumber, $illrq->{borrowernumber}, + "Borrowernumber getter works." + ); + is( + $illrq_obj->biblio_id, $illrq->{biblio_id}, + "Biblio_Id getter works." + ); + is( + $illrq_obj->branchcode, $illrq->{branchcode}, + "Branchcode getter works." + ); + is( + $illrq_obj->status, $illrq->{status}, + "Status getter works." + ); + is( + $illrq_obj->placed, $illrq->{placed}, + "Placed getter works." + ); + is( + $illrq_obj->replied, $illrq->{replied}, + "Replied getter works." + ); + is( + $illrq_obj->updated, $illrq->{updated}, + "Updated getter works." + ); + is( + $illrq_obj->completed, $illrq->{completed}, + "Completed getter works." + ); + is( + $illrq_obj->medium, $illrq->{medium}, + "Medium getter works." + ); + is( + $illrq_obj->accessurl, $illrq->{accessurl}, + "Accessurl getter works." + ); + is( + $illrq_obj->cost, $illrq->{cost}, + "Cost getter works." + ); + is( + $illrq_obj->price_paid, $illrq->{price_paid}, + "Price_paid getter works." + ); + is( + $illrq_obj->notesopac, $illrq->{notesopac}, + "Notesopac getter works." + ); + is( + $illrq_obj->notesstaff, $illrq->{notesstaff}, + "Notesstaff getter works." + ); + is( + $illrq_obj->orderid, $illrq->{orderid}, + "Orderid getter works." + ); + is( + $illrq_obj->backend, $illrq->{backend}, + "Backend getter works." + ); - is($illrq_obj->get_type, undef, - 'get_type() returns undef if no type is set'); - $builder->build({ - source => 'Illrequestattribute', - value => { - illrequest_id => $illrq_obj->illrequest_id, - type => 'type', - value => 'book' + is( + $illrq_obj->get_type, undef, + 'get_type() returns undef if no type is set' + ); + $builder->build( + { + source => 'Illrequestattribute', + value => { + illrequest_id => $illrq_obj->illrequest_id, + type => 'type', + value => 'book' + } } - }); - is($illrq_obj->get_type, 'book', - 'get_type() returns correct type if set'); + ); + is( + $illrq_obj->get_type, 'book', + 'get_type() returns correct type if set' + ); - isnt($illrq_obj->status, 'COMP', - "ILL is not currently marked complete."); + isnt( + $illrq_obj->status, 'COMP', + "ILL is not currently marked complete." + ); $illrq_obj->mark_completed; - is($illrq_obj->status, 'COMP', - "ILL is now marked complete."); + is( + $illrq_obj->status, 'COMP', + "ILL is now marked complete." + ); $illrq_obj->delete; - is(Koha::ILL::Requests->search->count, 0, - "No illrequest found after delete."); + is( + Koha::ILL::Requests->search->count, 0, + "No illrequest found after delete." + ); $schema->storage->txn_rollback; }; @@ -132,56 +182,74 @@ subtest 'store borrowernumber change also updates holds' => sub { Koha::ILL::Requests->search->delete; - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); - my $other_patron = $builder->build_object({ class => 'Koha::Patrons' }); - my $biblio = $builder->build_object({ class => 'Koha::Biblios' }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + my $other_patron = $builder->build_object( { class => 'Koha::Patrons' } ); + my $biblio = $builder->build_object( { class => 'Koha::Biblios' } ); - my $request = $builder->build_object({ - class => 'Koha::ILL::Requests', - value => { - borrowernumber => $patron->borrowernumber, - biblio_id => $biblio->biblionumber, + my $request = $builder->build_object( + { + class => 'Koha::ILL::Requests', + value => { + borrowernumber => $patron->borrowernumber, + biblio_id => $biblio->biblionumber, + } } - }); - $builder->build({ - source => 'Reserve', - value => { - borrowernumber => $patron->borrowernumber, - biblionumber => $request->biblio_id + ); + $builder->build( + { + source => 'Reserve', + value => { + borrowernumber => $patron->borrowernumber, + biblionumber => $request->biblio_id + } } - }); + ); - my $hold = Koha::Holds->find({ - biblionumber => $request->biblio_id, - borrowernumber => $request->borrowernumber, - }); + my $hold = Koha::Holds->find( + { + biblionumber => $request->biblio_id, + borrowernumber => $request->borrowernumber, + } + ); - is( $hold->borrowernumber, $request->borrowernumber, - 'before change, original borrowernumber found' ); + is( + $hold->borrowernumber, $request->borrowernumber, + 'before change, original borrowernumber found' + ); $request->borrowernumber( $other_patron->borrowernumber )->store; # reload changes $hold->discard_changes; - is( $hold->borrowernumber, $other_patron->borrowernumber, - 'after change, changed borrowernumber found in holds' ); + is( + $hold->borrowernumber, $other_patron->borrowernumber, + 'after change, changed borrowernumber found in holds' + ); - is( $request->borrowernumber, $other_patron->borrowernumber, - 'after change, changed borrowernumber found in illrequests' ); + is( + $request->borrowernumber, $other_patron->borrowernumber, + 'after change, changed borrowernumber found in illrequests' + ); - my $new_request = Koha::ILL::Request->new({ - biblio_id => $biblio->biblionumber, - branchcode => $patron->branchcode, - })->borrowernumber( $patron->borrowernumber )->store; + my $new_request = Koha::ILL::Request->new( + { + biblio_id => $biblio->biblionumber, + branchcode => $patron->branchcode, + } + )->borrowernumber( $patron->borrowernumber )->store; - is( $new_request->borrowernumber, $patron->borrowernumber, - 'Koha::ILL::Request->new()->store() works as expected'); + is( + $new_request->borrowernumber, $patron->borrowernumber, + 'Koha::ILL::Request->new()->store() works as expected' + ); - my $new_holds_found = Koha::Holds->search({ - biblionumber => $new_request->biblio_id, - borrowernumber => $new_request->borrowernumber, - })->count; + my $new_holds_found = Koha::Holds->search( + { + biblionumber => $new_request->biblio_id, + borrowernumber => $new_request->borrowernumber, + } + )->count; is( $new_holds_found, 0, 'no holds found with new()->store()' ); @@ -197,7 +265,8 @@ subtest 'Working with related objects' => sub { my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $illrq = $builder->build_object( - { class => 'Koha::ILL::Requests', + { + class => 'Koha::ILL::Requests', value => { borrowernumber => $patron->id, biblio_id => undef } } ); @@ -205,30 +274,36 @@ subtest 'Working with related objects' => sub { isa_ok( $illrq->patron, 'Koha::Patron', "OK accessing related patron." ); $builder->build( - { source => 'Illrequestattribute', + { + source => 'Illrequestattribute', value => { illrequest_id => $illrq->illrequest_id, type => 'X' } } ); $builder->build( - { source => 'Illrequestattribute', + { + source => 'Illrequestattribute', value => { illrequest_id => $illrq->illrequest_id, type => 'Y' } } ); $builder->build( - { source => 'Illrequestattribute', + { + source => 'Illrequestattribute', value => { illrequest_id => $illrq->illrequest_id, type => 'Z' } } ); my $rs = Koha::ILL::Request::Attributes->search( { illrequest_id => $illrq->id } ); - is( $illrq->extended_attributes->count, - $rs->count, "Fetching expected number of Illrequestattributes for our request." ); + is( + $illrq->extended_attributes->count, + $rs->count, "Fetching expected number of Illrequestattributes for our request." + ); is( $illrq->biblio, undef, "->biblio returns undef if no biblio" ); my $biblio = $builder->build_object( { class => 'Koha::Biblios' } ); my $req_bib = $builder->build_object( - { class => 'Koha::ILL::Requests', + { + class => 'Koha::ILL::Requests', value => { biblio_id => $biblio->biblionumber } } ); @@ -248,54 +323,59 @@ subtest 'Status Graph tests' => sub { $schema->storage->txn_begin; - my $illrq = $builder->build({source => 'Illrequest'}); - my $illrq_obj = Koha::ILL::Requests->find($ illrq->{illrequest_id}) ; + my $illrq = $builder->build( { source => 'Illrequest' } ); + my $illrq_obj = Koha::ILL::Requests->find( $illrq->{illrequest_id} ); # _core_status_graph tests: it's just a constant, so here we just make # sure it returns a hashref. - is(ref $illrq_obj->_core_status_graph, "HASH", - "_core_status_graph returns a hash."); + is( + ref $illrq_obj->_core_status_graph, "HASH", + "_core_status_graph returns a hash." + ); # _status_graph_union: let's try different merge operations. # Identity operation is_deeply( - $illrq_obj->_status_graph_union($illrq_obj->_core_status_graph, {}), + $illrq_obj->_status_graph_union( $illrq_obj->_core_status_graph, {} ), $illrq_obj->_core_status_graph, "core_status_graph + null = core_status_graph" ); # Simple addition is_deeply( - $illrq_obj->_status_graph_union({}, $illrq_obj->_core_status_graph), + $illrq_obj->_status_graph_union( {}, $illrq_obj->_core_status_graph ), $illrq_obj->_core_status_graph, "null + core_status_graph = core_status_graph" ); # Correct merge behaviour is_deeply( - $illrq_obj->_status_graph_union({ - REQ => { - prev_actions => [ ], - id => 'REQ', - next_actions => [ ], + $illrq_obj->_status_graph_union( + { + REQ => { + prev_actions => [], + id => 'REQ', + next_actions => [], + }, }, - }, { - QER => { - prev_actions => [ 'REQ' ], - id => 'QER', - next_actions => [ 'REQ' ], - }, - }), + { + QER => { + prev_actions => ['REQ'], + id => 'QER', + next_actions => ['REQ'], + }, + } + ), { REQ => { - prev_actions => [ 'QER' ], - id => 'REQ', - next_actions => [ 'QER' ], + prev_actions => ['QER'], + id => 'REQ', + next_actions => ['QER'], }, QER => { - prev_actions => [ 'REQ' ], - id => 'QER', - next_actions => [ 'REQ' ], + prev_actions => ['REQ'], + id => 'QER', + next_actions => ['REQ'], }, }, "REQ atom + linking QER = cyclical status graph" @@ -305,120 +385,123 @@ subtest 'Status Graph tests' => sub { # protect us against regressions related to bug 22280. my $new_node = { TEST => { - prev_actions => [ ], - id => 'TEST', - next_actions => [ ], + prev_actions => [], + id => 'TEST', + next_actions => [], }, }; + # Add the new node to the core_status_grpah - my $new_graph = $illrq_obj->_status_graph_union( $new_node, $illrq_obj->_core_status_graph); + my $new_graph = $illrq_obj->_status_graph_union( $new_node, $illrq_obj->_core_status_graph ); + # Compare the updated graph to the expected graph # The structure we compare against here is just a copy of the structure found # in Koha::ILL::Request::_core_status_graph() + the new node we created above - cmp_deeply( $new_graph, + cmp_deeply( + $new_graph, { - TEST => { - prev_actions => [ ], - id => 'TEST', - next_actions => [ ], + TEST => { + prev_actions => [], + id => 'TEST', + next_actions => [], + }, + NEW => { + prev_actions => [], # Actions containing buttons + # leading to this status + id => 'NEW', # ID of this status + name => 'New request', # UI name of this status + ui_method_name => 'New request', # UI name of method leading + # to this status + method => 'create', # method to this status + next_actions => [ 'REQ', 'GENREQ', 'KILL' ], # buttons to add to all + # requests with this status + ui_method_icon => 'fa-plus', # UI Style class + }, + REQ => { + prev_actions => [ 'NEW', 'REQREV', 'QUEUED', 'CANCREQ' ], + id => 'REQ', + name => 'Requested', + ui_method_name => 'Confirm request', + method => 'confirm', + next_actions => [ 'REQREV', 'COMP', 'CHK' ], + ui_method_icon => 'fa-check', + }, + GENREQ => { + prev_actions => [ 'NEW', 'REQREV' ], + id => 'GENREQ', + name => 'Requested from partners', + ui_method_name => 'Place request with partners', + method => 'generic_confirm', + next_actions => [ 'COMP', 'CHK', 'REQREV' ], + ui_method_icon => 'fa-paper-plane', + }, + REQREV => { + prev_actions => [ 'REQ', 'GENREQ' ], + id => 'REQREV', + name => 'Request reverted', + ui_method_name => 'Revert request', + method => 'cancel', + next_actions => [ 'REQ', 'GENREQ', 'KILL' ], + ui_method_icon => 'fa-times', + }, + QUEUED => { + prev_actions => [], + id => 'QUEUED', + name => 'Queued request', + ui_method_name => 0, + method => 0, + next_actions => [ 'REQ', 'KILL' ], + ui_method_icon => 0, + }, + CANCREQ => { + prev_actions => ['NEW'], + id => 'CANCREQ', + name => 'Cancellation requested', + ui_method_name => 0, + method => 0, + next_actions => [ 'KILL', 'REQ' ], + ui_method_icon => 0, + }, + COMP => { + prev_actions => ['REQ'], + id => 'COMP', + name => 'Completed', + ui_method_name => 'Mark completed', + method => 'mark_completed', + next_actions => ['CHK'], + ui_method_icon => 'fa-check', + }, + KILL => { + prev_actions => [ 'QUEUED', 'REQREV', 'NEW', 'CANCREQ' ], + id => 'KILL', + name => 0, + ui_method_name => 'Delete request', + method => 'delete', + next_actions => [], + ui_method_icon => 'fa-trash', + }, + CHK => { + prev_actions => [ 'REQ', 'GENREQ', 'COMP' ], + id => 'CHK', + name => 'Checked out', + ui_method_name => 'Check out', + needs_prefs => ['CirculateILL'], + needs_perms => ['user_circulate_circulate_remaining_permissions'], + needs_all => ignore(), + method => 'check_out', + next_actions => [], + ui_method_icon => 'fa-upload', + }, + RET => { + prev_actions => ['CHK'], + id => 'RET', + name => 'Returned to library', + ui_method_name => 'Check in', + method => 'check_in', + next_actions => ['COMP'], + ui_method_icon => 'fa-download', + } }, - NEW => { - prev_actions => [ ], # Actions containing buttons - # leading to this status - id => 'NEW', # ID of this status - name => 'New request', # UI name of this status - ui_method_name => 'New request', # UI name of method leading - # to this status - method => 'create', # method to this status - next_actions => [ 'REQ', 'GENREQ', 'KILL' ], # buttons to add to all - # requests with this status - ui_method_icon => 'fa-plus', # UI Style class - }, - REQ => { - prev_actions => [ 'NEW', 'REQREV', 'QUEUED', 'CANCREQ' ], - id => 'REQ', - name => 'Requested', - ui_method_name => 'Confirm request', - method => 'confirm', - next_actions => [ 'REQREV', 'COMP', 'CHK' ], - ui_method_icon => 'fa-check', - }, - GENREQ => { - prev_actions => [ 'NEW', 'REQREV' ], - id => 'GENREQ', - name => 'Requested from partners', - ui_method_name => 'Place request with partners', - method => 'generic_confirm', - next_actions => [ 'COMP', 'CHK', 'REQREV' ], - ui_method_icon => 'fa-paper-plane', - }, - REQREV => { - prev_actions => [ 'REQ', 'GENREQ' ], - id => 'REQREV', - name => 'Request reverted', - ui_method_name => 'Revert request', - method => 'cancel', - next_actions => [ 'REQ', 'GENREQ', 'KILL' ], - ui_method_icon => 'fa-times', - }, - QUEUED => { - prev_actions => [ ], - id => 'QUEUED', - name => 'Queued request', - ui_method_name => 0, - method => 0, - next_actions => [ 'REQ', 'KILL' ], - ui_method_icon => 0, - }, - CANCREQ => { - prev_actions => [ 'NEW' ], - id => 'CANCREQ', - name => 'Cancellation requested', - ui_method_name => 0, - method => 0, - next_actions => [ 'KILL', 'REQ' ], - ui_method_icon => 0, - }, - COMP => { - prev_actions => [ 'REQ' ], - id => 'COMP', - name => 'Completed', - ui_method_name => 'Mark completed', - method => 'mark_completed', - next_actions => [ 'CHK' ], - ui_method_icon => 'fa-check', - }, - KILL => { - prev_actions => [ 'QUEUED', 'REQREV', 'NEW', 'CANCREQ' ], - id => 'KILL', - name => 0, - ui_method_name => 'Delete request', - method => 'delete', - next_actions => [ ], - ui_method_icon => 'fa-trash', - }, - CHK => { - prev_actions => [ 'REQ', 'GENREQ', 'COMP' ], - id => 'CHK', - name => 'Checked out', - ui_method_name => 'Check out', - needs_prefs => [ 'CirculateILL' ], - needs_perms => [ 'user_circulate_circulate_remaining_permissions' ], - needs_all => ignore(), - method => 'check_out', - next_actions => [ ], - ui_method_icon => 'fa-upload', - }, - RET => { - prev_actions => [ 'CHK' ], - id => 'RET', - name => 'Returned to library', - ui_method_name => 'Check in', - method => 'check_in', - next_actions => [ 'COMP' ], - ui_method_icon => 'fa-download', - } - }, "new node + core_status_graph = bigger status graph" ) || diag explain $new_graph; @@ -434,110 +517,113 @@ subtest 'Status Graph tests' => sub { ui_method_icon => 'fa-check', } }; + # Add the dupe node to the core_status_grpah - my $dupe_graph = $illrq_obj->_status_graph_union( $illrq_obj->_core_status_graph, $dupe_node); + my $dupe_graph = $illrq_obj->_status_graph_union( $illrq_obj->_core_status_graph, $dupe_node ); + # Compare the updated graph to the expected graph # The structure we compare against here is just a copy of the structure found # in Koha::ILL::Request::_core_status_graph() + the new node we created above - cmp_deeply( $dupe_graph, + cmp_deeply( + $dupe_graph, { - NEW => { - prev_actions => [ ], # Actions containing buttons - # leading to this status - id => 'NEW', # ID of this status - name => 'New request', # UI name of this status - ui_method_name => 'New request', # UI name of method leading - # to this status - method => 'create', # method to this status - next_actions => [ 'REQ', 'GENREQ', 'KILL' ], # buttons to add to all - # requests with this status - ui_method_icon => 'fa-plus', # UI Style class + NEW => { + prev_actions => [], # Actions containing buttons + # leading to this status + id => 'NEW', # ID of this status + name => 'New request', # UI name of this status + ui_method_name => 'New request', # UI name of method leading + # to this status + method => 'create', # method to this status + next_actions => [ 'REQ', 'GENREQ', 'KILL' ], # buttons to add to all + # requests with this status + ui_method_icon => 'fa-plus', # UI Style class + }, + REQ => { + prev_actions => [ 'NEW', 'REQREV', 'QUEUED', 'CANCREQ' ], + id => 'REQ', + name => 'Requested', + ui_method_name => 'Confirm request dupe', + method => 'confirm', + next_actions => [ 'REQREV', 'COMP', 'CHK' ], + ui_method_icon => 'fa-check', + }, + GENREQ => { + prev_actions => [ 'NEW', 'REQREV' ], + id => 'GENREQ', + name => 'Requested from partners', + ui_method_name => 'Place request with partners', + method => 'generic_confirm', + next_actions => [ 'COMP', 'CHK', 'REQREV' ], + ui_method_icon => 'fa-paper-plane', + }, + REQREV => { + prev_actions => [ 'REQ', 'GENREQ' ], + id => 'REQREV', + name => 'Request reverted', + ui_method_name => 'Revert request', + method => 'cancel', + next_actions => [ 'REQ', 'GENREQ', 'KILL' ], + ui_method_icon => 'fa-times', + }, + QUEUED => { + prev_actions => [], + id => 'QUEUED', + name => 'Queued request', + ui_method_name => 0, + method => 0, + next_actions => [ 'REQ', 'KILL' ], + ui_method_icon => 0, + }, + CANCREQ => { + prev_actions => ['NEW'], + id => 'CANCREQ', + name => 'Cancellation requested', + ui_method_name => 0, + method => 0, + next_actions => [ 'KILL', 'REQ' ], + ui_method_icon => 0, + }, + COMP => { + prev_actions => ['REQ'], + id => 'COMP', + name => 'Completed', + ui_method_name => 'Mark completed', + method => 'mark_completed', + next_actions => ['CHK'], + ui_method_icon => 'fa-check', + }, + KILL => { + prev_actions => [ 'QUEUED', 'REQREV', 'NEW', 'CANCREQ' ], + id => 'KILL', + name => 0, + ui_method_name => 'Delete request', + method => 'delete', + next_actions => [], + ui_method_icon => 'fa-trash', + }, + CHK => { + prev_actions => [ 'REQ', 'GENREQ', 'COMP' ], + id => 'CHK', + name => 'Checked out', + ui_method_name => 'Check out', + needs_prefs => ['CirculateILL'], + needs_perms => ['user_circulate_circulate_remaining_permissions'], + needs_all => ignore(), + method => 'check_out', + next_actions => [], + ui_method_icon => 'fa-upload', + }, + RET => { + prev_actions => ['CHK'], + id => 'RET', + name => 'Returned to library', + ui_method_name => 'Check in', + method => 'check_in', + next_actions => ['COMP'], + ui_method_icon => 'fa-download', + } }, - REQ => { - prev_actions => [ 'NEW', 'REQREV', 'QUEUED', 'CANCREQ' ], - id => 'REQ', - name => 'Requested', - ui_method_name => 'Confirm request dupe', - method => 'confirm', - next_actions => [ 'REQREV', 'COMP', 'CHK' ], - ui_method_icon => 'fa-check', - }, - GENREQ => { - prev_actions => [ 'NEW', 'REQREV' ], - id => 'GENREQ', - name => 'Requested from partners', - ui_method_name => 'Place request with partners', - method => 'generic_confirm', - next_actions => [ 'COMP', 'CHK', 'REQREV' ], - ui_method_icon => 'fa-paper-plane', - }, - REQREV => { - prev_actions => [ 'REQ', 'GENREQ' ], - id => 'REQREV', - name => 'Request reverted', - ui_method_name => 'Revert request', - method => 'cancel', - next_actions => [ 'REQ', 'GENREQ', 'KILL' ], - ui_method_icon => 'fa-times', - }, - QUEUED => { - prev_actions => [ ], - id => 'QUEUED', - name => 'Queued request', - ui_method_name => 0, - method => 0, - next_actions => [ 'REQ', 'KILL' ], - ui_method_icon => 0, - }, - CANCREQ => { - prev_actions => [ 'NEW' ], - id => 'CANCREQ', - name => 'Cancellation requested', - ui_method_name => 0, - method => 0, - next_actions => [ 'KILL', 'REQ' ], - ui_method_icon => 0, - }, - COMP => { - prev_actions => [ 'REQ' ], - id => 'COMP', - name => 'Completed', - ui_method_name => 'Mark completed', - method => 'mark_completed', - next_actions => [ 'CHK' ], - ui_method_icon => 'fa-check', - }, - KILL => { - prev_actions => [ 'QUEUED', 'REQREV', 'NEW', 'CANCREQ' ], - id => 'KILL', - name => 0, - ui_method_name => 'Delete request', - method => 'delete', - next_actions => [ ], - ui_method_icon => 'fa-trash', - }, - CHK => { - prev_actions => [ 'REQ', 'GENREQ', 'COMP' ], - id => 'CHK', - name => 'Checked out', - ui_method_name => 'Check out', - needs_prefs => [ 'CirculateILL' ], - needs_perms => [ 'user_circulate_circulate_remaining_permissions' ], - needs_all => ignore(), - method => 'check_out', - next_actions => [ ], - ui_method_icon => 'fa-upload', - }, - RET => { - prev_actions => [ 'CHK' ], - id => 'RET', - name => 'Returned to library', - ui_method_name => 'Check in', - method => 'check_in', - next_actions => [ 'COMP' ], - ui_method_icon => 'fa-download', - } - }, "new node + core_status_graph = bigger status graph" ) || diag explain $dupe_graph; @@ -554,20 +640,24 @@ subtest 'Backend testing (mocks)' => sub { # the Dummy plugin installed. load_backend & available_backends don't # currently have tests as a result. - t::lib::Mocks->mock_config('interlibrary_loans', { backend_dir => 'a_dir' } ); + t::lib::Mocks->mock_config( 'interlibrary_loans', { backend_dir => 'a_dir' } ); my $backend = Test::MockObject->new; $backend->set_isa('Koha::Illbackends::Mock'); - $backend->set_always('name', 'Mock'); + $backend->set_always( 'name', 'Mock' ); - my $patron = $builder->build({ source => 'Borrower' }); - my $illrq = $builder->build_object({ - class => 'Koha::ILL::Requests', - }); + my $patron = $builder->build( { source => 'Borrower' } ); + my $illrq = $builder->build_object( + { + class => 'Koha::ILL::Requests', + } + ); $illrq->_backend($backend); - isa_ok($illrq->_backend, 'Koha::Illbackends::Mock', - "OK accessing mocked backend."); + isa_ok( + $illrq->_backend, 'Koha::Illbackends::Mock', + "OK accessing mocked backend." + ); # _backend_capability tests: # We need to test whether this optional feature of a mocked backend @@ -577,17 +667,23 @@ subtest 'Backend testing (mocks)' => sub { # capability exists. This method can be used to implement custom backend # functionality, such as unmediated in the BLDSS backend (also see # bugzilla 18837). - $backend->set_always('capabilities', undef); - is($illrq->_backend_capability('Test'), 0, - "0 returned on Mock not implementing capabilities."); + $backend->set_always( 'capabilities', undef ); + is( + $illrq->_backend_capability('Test'), 0, + "0 returned on Mock not implementing capabilities." + ); - $backend->set_always('capabilities', 0); - is($illrq->_backend_capability('Test'), 0, - "0 returned on Mock not implementing Test capability."); + $backend->set_always( 'capabilities', 0 ); + is( + $illrq->_backend_capability('Test'), 0, + "0 returned on Mock not implementing Test capability." + ); - $backend->set_always('capabilities', sub { return 'bar'; } ); - is($illrq->_backend_capability('Test'), 'bar', - "'bar' returned on Mock implementing Test capability."); + $backend->set_always( 'capabilities', sub { return 'bar'; } ); + is( + $illrq->_backend_capability('Test'), 'bar', + "'bar' returned on Mock implementing Test capability." + ); # metadata test: we need to be sure that we return the arbitrary values # from the backend. @@ -596,16 +692,16 @@ subtest 'Backend testing (mocks)' => sub { sub { my ( $self, $rq ) = @_; return { - ID => $rq->illrequest_id, + ID => $rq->illrequest_id, Title => $rq->patron->borrowernumber - } + }; } ); is_deeply( $illrq->metadata, { - ID => $illrq->illrequest_id, + ID => $illrq->illrequest_id, Title => $illrq->patron->borrowernumber }, "Test metadata." @@ -614,80 +710,102 @@ subtest 'Backend testing (mocks)' => sub { # capabilities: # No backend graph extension - $backend->set_always('status_graph', {}); - is_deeply($illrq->capabilities('COMP'), - { - prev_actions => [ 'REQ' ], - id => 'COMP', - name => 'Completed', - ui_method_name => 'Mark completed', - method => 'mark_completed', - next_actions => [ 'CHK' ], - ui_method_icon => 'fa-check', - }, - "Dummy status graph for COMP."); - is($illrq->capabilities('UNKNOWN'), undef, - "Dummy status graph for UNKNOWN."); - is_deeply($illrq->capabilities(), - $illrq->_core_status_graph, - "Dummy full status graph."); + $backend->set_always( 'status_graph', {} ); + is_deeply( + $illrq->capabilities('COMP'), + { + prev_actions => ['REQ'], + id => 'COMP', + name => 'Completed', + ui_method_name => 'Mark completed', + method => 'mark_completed', + next_actions => ['CHK'], + ui_method_icon => 'fa-check', + }, + "Dummy status graph for COMP." + ); + is( + $illrq->capabilities('UNKNOWN'), undef, + "Dummy status graph for UNKNOWN." + ); + is_deeply( + $illrq->capabilities(), + $illrq->_core_status_graph, + "Dummy full status graph." + ); + # Simple backend graph extension - $backend->set_always('status_graph', - { - QER => { - prev_actions => [ 'REQ' ], - id => 'QER', - next_actions => [ 'REQ' ], - }, - }); - is_deeply($illrq->capabilities('QER'), - { - prev_actions => [ 'REQ' ], - id => 'QER', - next_actions => [ 'REQ' ], - }, - "Simple status graph for QER."); - is($illrq->capabilities('UNKNOWN'), undef, - "Simple status graph for UNKNOWN."); - is_deeply($illrq->capabilities(), - $illrq->_status_graph_union( - $illrq->_core_status_graph, - { - QER => { - prev_actions => [ 'REQ' ], - id => 'QER', - next_actions => [ 'REQ' ], - }, - } - ), - "Simple full status graph."); + $backend->set_always( + 'status_graph', + { + QER => { + prev_actions => ['REQ'], + id => 'QER', + next_actions => ['REQ'], + }, + } + ); + is_deeply( + $illrq->capabilities('QER'), + { + prev_actions => ['REQ'], + id => 'QER', + next_actions => ['REQ'], + }, + "Simple status graph for QER." + ); + is( + $illrq->capabilities('UNKNOWN'), undef, + "Simple status graph for UNKNOWN." + ); + is_deeply( + $illrq->capabilities(), + $illrq->_status_graph_union( + $illrq->_core_status_graph, + { + QER => { + prev_actions => ['REQ'], + id => 'QER', + next_actions => ['REQ'], + }, + } + ), + "Simple full status graph." + ); # custom_capability: # No backend graph extension - $backend->set_always('status_graph', {}); - is($illrq->custom_capability('unknown', {}), 0, - "Unknown candidate."); + $backend->set_always( 'status_graph', {} ); + is( + $illrq->custom_capability( 'unknown', {} ), 0, + "Unknown candidate." + ); # Simple backend graph extension - $backend->set_always('status_graph', - { - ID => { - prev_actions => [ 'REQ' ], - id => 'ID', - method => 'identity', - next_actions => [ 'REQ' ], - }, - }); - $backend->mock('identity', - sub { my ( $self, $params ) = @_; return $params->{other}; }); - is($illrq->custom_capability('identity', { test => 1, method => 'blah' })->{test}, 1, - "Resolve identity custom_capability"); + $backend->set_always( + 'status_graph', + { + ID => { + prev_actions => ['REQ'], + id => 'ID', + method => 'identity', + next_actions => ['REQ'], + }, + } + ); + $backend->mock( + 'identity', + sub { my ( $self, $params ) = @_; return $params->{other}; } + ); + is( + $illrq->custom_capability( 'identity', { test => 1, method => 'blah' } )->{test}, 1, + "Resolve identity custom_capability" + ); $schema->storage->txn_rollback; }; - subtest 'Backend core methods' => sub { plan tests => 20; @@ -697,86 +815,102 @@ subtest 'Backend core methods' => sub { # Build infrastructure my $backend = Test::MockObject->new; $backend->set_isa('Koha::Illbackends::Mock'); - $backend->set_always('name', 'Mock'); - $backend->mock('capabilities', sub { return 'Mock'; }); + $backend->set_always( 'name', 'Mock' ); + $backend->mock( 'capabilities', sub { return 'Mock'; } ); my $config = Test::MockObject->new; - $config->set_always('backend_dir', "/tmp"); - $config->set_always('getLimitRules', - { default => { count => 0, method => 'active' } }); + $config->set_always( 'backend_dir', "/tmp" ); + $config->set_always( + 'getLimitRules', + { default => { count => 0, method => 'active' } } + ); - my $illrq = $builder->build_object({ - class => 'Koha::ILL::Requests', - value => { backend => undef } - }); + my $illrq = $builder->build_object( + { + class => 'Koha::ILL::Requests', + value => { backend => undef } + } + ); $illrq->_config($config); # Test error conditions (no backend) throws_ok { $illrq->load_backend; } - 'Koha::Exceptions::Ill::InvalidBackendId', + 'Koha::Exceptions::Ill::InvalidBackendId', 'Exception raised correctly'; throws_ok { $illrq->load_backend(''); } - 'Koha::Exceptions::Ill::InvalidBackendId', + 'Koha::Exceptions::Ill::InvalidBackendId', 'Exception raised correctly'; # Now load the mocked backend $illrq->_backend($backend); # expand_template: - is_deeply($illrq->expand_template({ test => 1, method => "bar" }), - { - test => 1, - method => "bar", - template => "/tmp/Mock/intra-includes/bar.inc", - opac_template => "/tmp/Mock/opac-includes/bar.inc", - }, - "expand_template"); + is_deeply( + $illrq->expand_template( { test => 1, method => "bar" } ), + { + test => 1, + method => "bar", + template => "/tmp/Mock/intra-includes/bar.inc", + opac_template => "/tmp/Mock/opac-includes/bar.inc", + }, + "expand_template" + ); # backend_create # we are testing simple cases. - $backend->set_series('create', - { stage => 'bar', method => 'create' }, - { stage => 'commit', method => 'create' }, - { stage => 'commit', method => 'create' }, - { stage => 'commit', method => 'create' }, - { stage => 'commit', method => 'create' }); + $backend->set_series( + 'create', + { stage => 'bar', method => 'create' }, + { stage => 'commit', method => 'create' }, + { stage => 'commit', method => 'create' }, + { stage => 'commit', method => 'create' }, + { stage => 'commit', method => 'create' } + ); + # Test non-commit - is_deeply($illrq->backend_create({test => 1}), - { - stage => 'bar', method => 'create', - template => "/tmp/Mock/intra-includes/create.inc", - opac_template => "/tmp/Mock/opac-includes/create.inc", - }, - "Backend create: arbitrary stage."); + is_deeply( + $illrq->backend_create( { test => 1 } ), + { + stage => 'bar', method => 'create', + template => "/tmp/Mock/intra-includes/create.inc", + opac_template => "/tmp/Mock/opac-includes/create.inc", + }, + "Backend create: arbitrary stage." + ); + # Test commit - is_deeply($illrq->backend_create({test => 1}), - { - stage => 'commit', method => 'create', permitted => 0, - template => "/tmp/Mock/intra-includes/create.inc", - opac_template => "/tmp/Mock/opac-includes/create.inc", - }, - "Backend create: arbitrary stage, not permitted."); - is($illrq->status, "QUEUED", "Backend create: queued if restricted."); - $config->set_always('getLimitRules', {}); + is_deeply( + $illrq->backend_create( { test => 1 } ), + { + stage => 'commit', method => 'create', permitted => 0, + template => "/tmp/Mock/intra-includes/create.inc", + opac_template => "/tmp/Mock/opac-includes/create.inc", + }, + "Backend create: arbitrary stage, not permitted." + ); + is( $illrq->status, "QUEUED", "Backend create: queued if restricted." ); + $config->set_always( 'getLimitRules', {} ); $illrq->status('NEW'); - is_deeply($illrq->backend_create({test => 1}), - { - stage => 'commit', method => 'create', permitted => 1, - template => "/tmp/Mock/intra-includes/create.inc", - opac_template => "/tmp/Mock/opac-includes/create.inc", - }, - "Backend create: arbitrary stage, permitted."); - is($illrq->status, "NEW", "Backend create: not-queued."); + is_deeply( + $illrq->backend_create( { test => 1 } ), + { + stage => 'commit', method => 'create', permitted => 1, + template => "/tmp/Mock/intra-includes/create.inc", + opac_template => "/tmp/Mock/opac-includes/create.inc", + }, + "Backend create: arbitrary stage, permitted." + ); + is( $illrq->status, "NEW", "Backend create: not-queued." ); # Test that enabling the unmediated workflow causes the backend's # 'unmediated_ill' method to be called - t::lib::Mocks::mock_preference('ILLModuleUnmediated', '1'); + t::lib::Mocks::mock_preference( 'ILLModuleUnmediated', '1' ); $backend->mock( 'capabilities', sub { - my ($self, $name) = @_; - if ($name eq 'unmediated_ill') { + my ( $self, $name ) = @_; + if ( $name eq 'unmediated_ill' ) { return sub { return { unmediated_ill => 1 }; }; @@ -785,10 +919,10 @@ subtest 'Backend core methods' => sub { ); $illrq->status('NEW'); is_deeply( - $illrq->backend_create({test => 1}), + $illrq->backend_create( { test => 1 } ), { - 'opac_template' => '/tmp/Mock/opac-includes/.inc', - 'template' => '/tmp/Mock/intra-includes/.inc', + 'opac_template' => '/tmp/Mock/opac-includes/.inc', + 'template' => '/tmp/Mock/intra-includes/.inc', 'unmediated_ill' => 1 }, "Backend create: commit stage, permitted, ILLModuleUnmediated enabled." @@ -796,62 +930,72 @@ subtest 'Backend core methods' => sub { # Test that disabling the unmediated workflow causes the backend's # 'unmediated_ill' method to be NOT called - t::lib::Mocks::mock_preference('ILLModuleUnmediated', '0'); + t::lib::Mocks::mock_preference( 'ILLModuleUnmediated', '0' ); $illrq->status('NEW'); is_deeply( - $illrq->backend_create({test => 1}), + $illrq->backend_create( { test => 1 } ), { - stage => 'commit', method => 'create', permitted => 1, - template => "/tmp/Mock/intra-includes/create.inc", + stage => 'commit', method => 'create', permitted => 1, + template => "/tmp/Mock/intra-includes/create.inc", opac_template => "/tmp/Mock/opac-includes/create.inc", }, "Backend create: commit stage, permitted, ILLModuleUnmediated disabled." ); # backend_renew - $backend->set_series('renew', { stage => 'bar', method => 'renew' }); - is_deeply($illrq->backend_renew({test => 1}), - { - stage => 'bar', method => 'renew', - template => "/tmp/Mock/intra-includes/renew.inc", - opac_template => "/tmp/Mock/opac-includes/renew.inc", - }, - "Backend renew: arbitrary stage."); + $backend->set_series( 'renew', { stage => 'bar', method => 'renew' } ); + is_deeply( + $illrq->backend_renew( { test => 1 } ), + { + stage => 'bar', method => 'renew', + template => "/tmp/Mock/intra-includes/renew.inc", + opac_template => "/tmp/Mock/opac-includes/renew.inc", + }, + "Backend renew: arbitrary stage." + ); # backend_cancel - $backend->set_series('cancel', { stage => 'bar', method => 'cancel' }); - is_deeply($illrq->backend_cancel({test => 1}), - { - stage => 'bar', method => 'cancel', - template => "/tmp/Mock/intra-includes/cancel.inc", - opac_template => "/tmp/Mock/opac-includes/cancel.inc", - }, - "Backend cancel: arbitrary stage."); + $backend->set_series( 'cancel', { stage => 'bar', method => 'cancel' } ); + is_deeply( + $illrq->backend_cancel( { test => 1 } ), + { + stage => 'bar', method => 'cancel', + template => "/tmp/Mock/intra-includes/cancel.inc", + opac_template => "/tmp/Mock/opac-includes/cancel.inc", + }, + "Backend cancel: arbitrary stage." + ); # backend_illview - $backend->set_series('illview', { stage => '', method => 'illview' }); - is_deeply($illrq->backend_illview({test => 1}), 0, - "Backend illview optional method."); + $backend->set_series( 'illview', { stage => '', method => 'illview' } ); + is_deeply( + $illrq->backend_illview( { test => 1 } ), 0, + "Backend illview optional method." + ); # backend_update_status - $backend->set_series('update_status', { stage => 'bar', method => 'update_status' }); - is_deeply($illrq->backend_update_status({test => 1}), - { - stage => 'bar', method => 'update_status', - template => "/tmp/Mock/intra-includes/update_status.inc", - opac_template => "/tmp/Mock/opac-includes/update_status.inc", - }, - "Backend update_status: arbitrary stage."); + $backend->set_series( 'update_status', { stage => 'bar', method => 'update_status' } ); + is_deeply( + $illrq->backend_update_status( { test => 1 } ), + { + stage => 'bar', method => 'update_status', + template => "/tmp/Mock/intra-includes/update_status.inc", + opac_template => "/tmp/Mock/opac-includes/update_status.inc", + }, + "Backend update_status: arbitrary stage." + ); # backend_confirm - $backend->set_series('confirm', { stage => 'bar', method => 'confirm' }); - is_deeply($illrq->backend_confirm({test => 1}), - { - stage => 'bar', method => 'confirm', - template => "/tmp/Mock/intra-includes/confirm.inc", - opac_template => "/tmp/Mock/opac-includes/confirm.inc", - }, - "Backend confirm: arbitrary stage."); + $backend->set_series( 'confirm', { stage => 'bar', method => 'confirm' } ); + is_deeply( + $illrq->backend_confirm( { test => 1 } ), + { + stage => 'bar', method => 'confirm', + template => "/tmp/Mock/intra-includes/confirm.inc", + opac_template => "/tmp/Mock/opac-includes/confirm.inc", + }, + "Backend confirm: arbitrary stage." + ); # backend_get_update $backend->mock( @@ -861,47 +1005,64 @@ subtest 'Backend core methods' => sub { return $options; } ); - $backend->mock('capabilities', sub { return sub { return 1; } }); - is_deeply($illrq->backend_get_update({}), 1, - "Backend get_update method."); - - $config->set_always('partner_code', "ILLTSTLIB"); - $backend->set_always('metadata', { Test => "Foobar" }); - my $illbrn = $builder->build({ - source => 'Branch', - value => { branchemail => "", branchreplyto => "" } - }); - my $partner1 = $builder->build({ - source => 'Borrower', - value => { categorycode => "ILLTSTLIB" }, - }); - my $partner2 = $builder->build({ - source => 'Borrower', - value => { categorycode => "ILLTSTLIB" }, - }); - my $gen_conf = $illrq->generic_confirm({ - current_branchcode => $illbrn->{branchcode} - }); - isnt(index($gen_conf->{value}->{draft}->{body}, $backend->metadata->{Test}), -1, - "Generic confirm: draft contains metadata." + $backend->mock( + 'capabilities', + sub { + return sub { return 1; } + } ); - is($gen_conf->{value}->{partners}->next->borrowernumber, $partner1->{borrowernumber}, - "Generic cofnirm: partner 1 is correct." - ); - is($gen_conf->{value}->{partners}->next->borrowernumber, $partner2->{borrowernumber}, - "Generic confirm: partner 2 is correct." + is_deeply( + $illrq->backend_get_update( {} ), 1, + "Backend get_update method." ); - dies_ok { $illrq->generic_confirm({ - current_branchcode => $illbrn->{branchcode}, - stage => 'draft' - }) } - "Generic confirm: missing to dies OK."; + $config->set_always( 'partner_code', "ILLTSTLIB" ); + $backend->set_always( 'metadata', { Test => "Foobar" } ); + my $illbrn = $builder->build( + { + source => 'Branch', + value => { branchemail => "", branchreplyto => "" } + } + ); + my $partner1 = $builder->build( + { + source => 'Borrower', + value => { categorycode => "ILLTSTLIB" }, + } + ); + my $partner2 = $builder->build( + { + source => 'Borrower', + value => { categorycode => "ILLTSTLIB" }, + } + ); + my $gen_conf = $illrq->generic_confirm( { current_branchcode => $illbrn->{branchcode} } ); + isnt( + index( $gen_conf->{value}->{draft}->{body}, $backend->metadata->{Test} ), -1, + "Generic confirm: draft contains metadata." + ); + is( + $gen_conf->{value}->{partners}->next->borrowernumber, $partner1->{borrowernumber}, + "Generic cofnirm: partner 1 is correct." + ); + is( + $gen_conf->{value}->{partners}->next->borrowernumber, $partner2->{borrowernumber}, + "Generic confirm: partner 2 is correct." + ); + + dies_ok { + $illrq->generic_confirm( + { + current_branchcode => $illbrn->{branchcode}, + stage => 'draft' + } + ) + } + "Generic confirm: missing to dies OK."; $schema->storage->txn_rollback; }; - subtest 'Helpers' => sub { plan tests => 25; @@ -911,55 +1072,65 @@ subtest 'Helpers' => sub { # Build infrastructure my $backend = Test::MockObject->new; $backend->set_isa('Koha::Illbackends::Mock'); - $backend->set_always('name', 'Mock'); + $backend->set_always( 'name', 'Mock' ); $backend->mock( 'metadata', sub { my ( $self, $rq ) = @_; return { - title => 'mytitle', + title => 'mytitle', author => 'myauthor' - } + }; } ); my $config = Test::MockObject->new; - $config->set_always('backend_dir', "/tmp"); + $config->set_always( 'backend_dir', "/tmp" ); - my $patron = $builder->build({ - source => 'Borrower', - value => { categorycode => "A" } - }); - # Create a mocked branch with no email addressed defined - my $illbrn = $builder->build({ - source => 'Branch', - value => { - branchcode => 'HDE', - branchemail => "", - branchillemail => "", - branchreplyto => "" + my $patron = $builder->build( + { + source => 'Borrower', + value => { categorycode => "A" } } - }); - my $illrq = $builder->build({ - source => 'Illrequest', - value => { branchcode => "HDE", borrowernumber => $patron->{borrowernumber} } - }); - my $illrq_obj = Koha::ILL::Requests->find($illrq->{illrequest_id}); + ); + + # Create a mocked branch with no email addressed defined + my $illbrn = $builder->build( + { + source => 'Branch', + value => { + branchcode => 'HDE', + branchemail => "", + branchillemail => "", + branchreplyto => "" + } + } + ); + my $illrq = $builder->build( + { + source => 'Illrequest', + value => { branchcode => "HDE", borrowernumber => $patron->{borrowernumber} } + } + ); + my $illrq_obj = Koha::ILL::Requests->find( $illrq->{illrequest_id} ); $illrq_obj->_config($config); $illrq_obj->_backend($backend); #attach_processors - my $type = 'test_type_1'; - my $name = 'test_name_1'; + my $type = 'test_type_1'; + my $name = 'test_name_1'; my $update = Test::MockObject->new; $update->set_isa('Koha::ILL::Request::SupplierUpdate'); $update->{source_type} = $type; $update->{source_name} = $name; - $update->{processors} = []; - $update->mock('attach_processor', sub { - my ( $self, $to_attach ) = @_; - push @{$self->{processors}}, $to_attach; - }); + $update->{processors} = []; + $update->mock( + 'attach_processor', + sub { + my ( $self, $to_attach ) = @_; + push @{ $self->{processors} }, $to_attach; + } + ); my $processor = Test::MockObject->new; $processor->{target_source_type} = $type; $processor->{target_source_name} = $name; @@ -967,82 +1138,103 @@ subtest 'Helpers' => sub { $illrq_obj->push_processor($processor); $illrq_obj->attach_processors($update); is_deeply( - scalar @{$update->{processors}}, + scalar @{ $update->{processors} }, 1, 'attaching processors as appropriate works' ); # getPrefix - $config->set_series('getPrefixes', - { HDE => "TEST", TSL => "BAR", default => "DEFAULT" }, - { A => "ATEST", C => "CBAR", default => "DEFAULT" }); - is($illrq_obj->getPrefix({ brw_cat => "UNKNOWN", branch => "HDE" }), "TEST", - "getPrefix: branch"); - $config->set_series('getPrefixes', - { HDE => "TEST", TSL => "BAR", default => "DEFAULT" }, - { A => "ATEST", C => "CBAR", default => "DEFAULT" }); - is($illrq_obj->getPrefix({ branch => "UNKNOWN" }), "", - "getPrefix: default"); - $config->set_always('getPrefixes', {}); - is($illrq_obj->getPrefix({ branch => "UNKNOWN" }), "", - "getPrefix: the empty prefix"); + $config->set_series( + 'getPrefixes', + { HDE => "TEST", TSL => "BAR", default => "DEFAULT" }, + { A => "ATEST", C => "CBAR", default => "DEFAULT" } + ); + is( + $illrq_obj->getPrefix( { brw_cat => "UNKNOWN", branch => "HDE" } ), "TEST", + "getPrefix: branch" + ); + $config->set_series( + 'getPrefixes', + { HDE => "TEST", TSL => "BAR", default => "DEFAULT" }, + { A => "ATEST", C => "CBAR", default => "DEFAULT" } + ); + is( + $illrq_obj->getPrefix( { branch => "UNKNOWN" } ), "", + "getPrefix: default" + ); + $config->set_always( 'getPrefixes', {} ); + is( + $illrq_obj->getPrefix( { branch => "UNKNOWN" } ), "", + "getPrefix: the empty prefix" + ); # id_prefix - $config->set_series('getPrefixes', - { HDE => "TEST", TSL => "BAR", default => "DEFAULT" }, - { AB => "ATEST", CD => "CBAR", default => "DEFAULT" }); - is($illrq_obj->id_prefix, "TEST-", "id_prefix: branch"); - $config->set_series('getPrefixes', - { HDET => "TEST", TSLT => "BAR", default => "DEFAULT" }, - { AB => "ATEST", CD => "CBAR", default => "DEFAULT" }); - is($illrq_obj->id_prefix, "", "id_prefix: default"); + $config->set_series( + 'getPrefixes', + { HDE => "TEST", TSL => "BAR", default => "DEFAULT" }, + { AB => "ATEST", CD => "CBAR", default => "DEFAULT" } + ); + is( $illrq_obj->id_prefix, "TEST-", "id_prefix: branch" ); + $config->set_series( + 'getPrefixes', + { HDET => "TEST", TSLT => "BAR", default => "DEFAULT" }, + { AB => "ATEST", CD => "CBAR", default => "DEFAULT" } + ); + is( $illrq_obj->id_prefix, "", "id_prefix: default" ); # requires_moderation $illrq_obj->status('NEW')->store; - is($illrq_obj->requires_moderation, undef, "requires_moderation: No."); + is( $illrq_obj->requires_moderation, undef, "requires_moderation: No." ); $illrq_obj->status('CANCREQ')->store; - is($illrq_obj->requires_moderation, 'CANCREQ', "requires_moderation: Yes."); + is( $illrq_obj->requires_moderation, 'CANCREQ', "requires_moderation: Yes." ); #send_patron_notice - my $attr = Koha::Patron::MessagePreference::Attributes->find({ message_name => 'Ill_ready' }); - C4::Members::Messaging::SetMessagingPreference({ - borrowernumber => $patron->{borrowernumber}, - message_attribute_id => $attr->message_attribute_id, - message_transport_types => ['email'] - }); + my $attr = Koha::Patron::MessagePreference::Attributes->find( { message_name => 'Ill_ready' } ); + C4::Members::Messaging::SetMessagingPreference( + { + borrowernumber => $patron->{borrowernumber}, + message_attribute_id => $attr->message_attribute_id, + message_transport_types => ['email'] + } + ); my $return_patron = $illrq_obj->send_patron_notice('ILL_PICKUP_READY'); - my $notice = $schema->resultset('MessageQueue')->search({ - letter_code => 'ILL_PICKUP_READY', + my $notice = $schema->resultset('MessageQueue')->search( + { + letter_code => 'ILL_PICKUP_READY', message_transport_type => 'email', - borrowernumber => $illrq_obj->borrowernumber - })->next()->letter_code; + borrowernumber => $illrq_obj->borrowernumber + } + )->next()->letter_code; is_deeply( $return_patron, { result => { success => ['email'], fail => [] } }, "Correct return when notice created" ); - is($notice, 'ILL_PICKUP_READY' ,"Notice is correctly created"); + is( $notice, 'ILL_PICKUP_READY', "Notice is correctly created" ); # ill update notice, passes additional text parameter - my $attr_update = Koha::Patron::MessagePreference::Attributes->find({ message_name => 'Ill_update' }); - C4::Members::Messaging::SetMessagingPreference({ - borrowernumber => $patron->{borrowernumber}, - message_attribute_id => $attr_update->message_attribute_id, - message_transport_types => ['email'] - }); - my $return_patron_update = $illrq_obj->send_patron_notice('ILL_REQUEST_UPDATE', 'Some additional text'); - my $notice_update = $schema->resultset('MessageQueue')->search({ - letter_code => 'ILL_REQUEST_UPDATE', + my $attr_update = Koha::Patron::MessagePreference::Attributes->find( { message_name => 'Ill_update' } ); + C4::Members::Messaging::SetMessagingPreference( + { + borrowernumber => $patron->{borrowernumber}, + message_attribute_id => $attr_update->message_attribute_id, + message_transport_types => ['email'] + } + ); + my $return_patron_update = $illrq_obj->send_patron_notice( 'ILL_REQUEST_UPDATE', 'Some additional text' ); + my $notice_update = $schema->resultset('MessageQueue')->search( + { + letter_code => 'ILL_REQUEST_UPDATE', message_transport_type => 'email', - borrowernumber => $illrq_obj->borrowernumber - })->next()->letter_code; + borrowernumber => $illrq_obj->borrowernumber + } + )->next()->letter_code; is_deeply( $return_patron_update, { result => { success => ['email'], fail => [] } }, "Correct return when notice created" ); - is($notice_update, 'ILL_REQUEST_UPDATE' ,"Notice is correctly created"); - + is( $notice_update, 'ILL_REQUEST_UPDATE', "Notice is correctly created" ); my $return_patron_fail = $illrq_obj->send_patron_notice(); is_deeply( @@ -1053,33 +1245,26 @@ subtest 'Helpers' => sub { #send_staff_notice # Specify that no staff notices should be send - t::lib::Mocks::mock_preference('ILLSendStaffNotices', ''); - my $return_staff_cancel_fail = - $illrq_obj->send_staff_notice('ILL_REQUEST_CANCEL'); + t::lib::Mocks::mock_preference( 'ILLSendStaffNotices', '' ); + my $return_staff_cancel_fail = $illrq_obj->send_staff_notice('ILL_REQUEST_CANCEL'); is_deeply( $return_staff_cancel_fail, { error => 'notice_not_enabled' }, "Does not send notices that are not enabled" ); - my $queue = $schema->resultset('MessageQueue')->search({ - letter_code => 'ILL_REQUEST_CANCEL' - }); - is($queue->count, 0, "Notice is not queued"); + my $queue = $schema->resultset('MessageQueue')->search( { letter_code => 'ILL_REQUEST_CANCEL' } ); + is( $queue->count, 0, "Notice is not queued" ); # Specify that the cancel notice can be sent - t::lib::Mocks::mock_preference('ILLSendStaffNotices', 'ILL_REQUEST_CANCEL'); - my $return_staff_cancel = $illrq_obj->send_staff_notice( - 'ILL_REQUEST_CANCEL' - ); + t::lib::Mocks::mock_preference( 'ILLSendStaffNotices', 'ILL_REQUEST_CANCEL' ); + my $return_staff_cancel = $illrq_obj->send_staff_notice('ILL_REQUEST_CANCEL'); is_deeply( $return_staff_cancel, { success => 'notice_queued' }, "Correct return when staff notice created" ); - $queue = $schema->resultset('MessageQueue')->search({ - letter_code => 'ILL_REQUEST_CANCEL' - }); - is($queue->count, 1, "Notice queued as expected"); + $queue = $schema->resultset('MessageQueue')->search( { letter_code => 'ILL_REQUEST_CANCEL' } ); + is( $queue->count, 1, "Notice queued as expected" ); my $return_staff_fail = $illrq_obj->send_staff_notice(); is_deeply( @@ -1087,15 +1272,15 @@ subtest 'Helpers' => sub { { error => 'notice_no_type' }, "Correct error when missing type" ); - $queue = $schema->resultset('MessageQueue')->search({ - letter_code => 'ILL_REQUEST_CANCEL' - }); - is($queue->count, 1, "Notice is not queued"); + $queue = $schema->resultset('MessageQueue')->search( { letter_code => 'ILL_REQUEST_CANCEL' } ); + is( $queue->count, 1, "Notice is not queued" ); - my $attribute = $builder->build({ - source => 'Illrequestattribute', - value => { illrequest_id => $illrq_obj->illrequest_id, type => 'pages', value => '42' } - }); + my $attribute = $builder->build( + { + source => 'Illrequestattribute', + value => { illrequest_id => $illrq_obj->illrequest_id, type => 'pages', value => '42' } + } + ); my $ILL_REQUEST_CANCEL_content = q{The patron for interlibrary loans request [% illrequest.illrequest_id %], with the following details, has requested cancellation of this ILL request: @@ -1105,16 +1290,20 @@ subtest 'Helpers' => sub { Attribute: Pages=[% illrequestattributes.pages %] }; my $dbh = C4::Context->dbh; - $dbh->do(q{UPDATE letter + $dbh->do( + q{UPDATE letter SET content=? WHERE code="ILL_REQUEST_CANCEL" - }, undef, $ILL_REQUEST_CANCEL_content); + }, undef, $ILL_REQUEST_CANCEL_content + ); #get_notice - my $not = $illrq_obj->get_notice({ - notice_code => 'ILL_REQUEST_CANCEL', - transport => 'email' - }); + my $not = $illrq_obj->get_notice( + { + notice_code => 'ILL_REQUEST_CANCEL', + transport => 'email' + } + ); # We test the properties of the hashref separately because the random # hash ordering of the metadata means we can't test the entire thing @@ -1138,7 +1327,10 @@ Attribute: Pages=[% illrequestattributes.pages %] $not->{content} =~ s/\s//g; is( - $not->{content},"Thepatronforinterlibraryloansrequest" . $illrq_obj->id . ",withthefollowingdetails,hasrequestedcancellationofthisILLrequest:-author:myauthor-title:mytitleAttribute:Pages=42", + $not->{content}, + "Thepatronforinterlibraryloansrequest" + . $illrq_obj->id + . ",withthefollowingdetails,hasrequestedcancellationofthisILLrequest:-author:myauthor-title:mytitleAttribute:Pages=42", 'Correct content returned from get_notice with metadata correctly ordered' ); @@ -1152,7 +1344,6 @@ Attribute: Pages=[% illrequestattributes.pages %] $schema->storage->txn_rollback; }; - subtest 'Censorship' => sub { plan tests => 2; @@ -1162,27 +1353,33 @@ subtest 'Censorship' => sub { # Build infrastructure my $backend = Test::MockObject->new; $backend->set_isa('Koha::Illbackends::Mock'); - $backend->set_always('name', 'Mock'); + $backend->set_always( 'name', 'Mock' ); my $config = Test::MockObject->new; - $config->set_always('backend_dir', "/tmp"); + $config->set_always( 'backend_dir', "/tmp" ); - my $illrq = $builder->build({source => 'Illrequest'}); - my $illrq_obj = Koha::ILL::Requests->find($illrq->{illrequest_id}); + my $illrq = $builder->build( { source => 'Illrequest' } ); + my $illrq_obj = Koha::ILL::Requests->find( $illrq->{illrequest_id} ); $illrq_obj->_config($config); $illrq_obj->_backend($backend); - $config->set_always('censorship', { censor_notes_staff => 1, censor_reply_date => 0 }); + $config->set_always( 'censorship', { censor_notes_staff => 1, censor_reply_date => 0 } ); - my $censor_out = $illrq_obj->_censor({ foo => 'bar', baz => 564 }); - is_deeply($censor_out, { foo => 'bar', baz => 564, display_reply_date => 1 }, - "_censor: not OPAC, reply_date = 1"); + my $censor_out = $illrq_obj->_censor( { foo => 'bar', baz => 564 } ); + is_deeply( + $censor_out, { foo => 'bar', baz => 564, display_reply_date => 1 }, + "_censor: not OPAC, reply_date = 1" + ); - $censor_out = $illrq_obj->_censor({ foo => 'bar', baz => 564, opac => 1 }); - is_deeply($censor_out, { - foo => 'bar', baz => 564, censor_notes_staff => 1, - display_reply_date => 1, opac => 1 - }, "_censor: notes_staff = 0, reply_date = 0"); + $censor_out = $illrq_obj->_censor( { foo => 'bar', baz => 564, opac => 1 } ); + is_deeply( + $censor_out, + { + foo => 'bar', baz => 564, censor_notes_staff => 1, + display_reply_date => 1, opac => 1 + }, + "_censor: notes_staff = 0, reply_date = 0" + ); $schema->storage->txn_rollback; }; @@ -1193,125 +1390,138 @@ subtest 'Checking out' => sub { $schema->storage->txn_begin; - my $itemtype = $builder->build_object({ - class => 'Koha::ItemTypes', - value => { - notforloan => 1 + my $itemtype = $builder->build_object( + { + class => 'Koha::ItemTypes', + value => { notforloan => 1 } } - }); - my $library = $builder->build_object({ class => 'Koha::Libraries' }); - my $biblio = $builder->build_sample_biblio(); - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); - my $request = $builder->build_object({ - class => 'Koha::ILL::Requests', - value => { - borrowernumber => $patron->borrowernumber, - biblio_id => $biblio->biblionumber + ); + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); + my $biblio = $builder->build_sample_biblio(); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + my $request = $builder->build_object( + { + class => 'Koha::ILL::Requests', + value => { + borrowernumber => $patron->borrowernumber, + biblio_id => $biblio->biblionumber + } } - }); + ); # First test that calling check_out without a stage param returns # what's required to build the form my $no_stage = $request->check_out(); - is($no_stage->{method}, 'check_out'); - is($no_stage->{stage}, 'form'); - isa_ok($no_stage->{value}, 'HASH'); - isa_ok($no_stage->{value}->{itemtypes}, 'Koha::ItemTypes'); - isa_ok($no_stage->{value}->{libraries}, 'Koha::Libraries'); - isa_ok($no_stage->{value}->{statistical}, 'Koha::Patrons'); - isa_ok($no_stage->{value}->{biblio}, 'Koha::Biblio'); + is( $no_stage->{method}, 'check_out' ); + is( $no_stage->{stage}, 'form' ); + isa_ok( $no_stage->{value}, 'HASH' ); + isa_ok( $no_stage->{value}->{itemtypes}, 'Koha::ItemTypes' ); + isa_ok( $no_stage->{value}->{libraries}, 'Koha::Libraries' ); + isa_ok( $no_stage->{value}->{statistical}, 'Koha::Patrons' ); + isa_ok( $no_stage->{value}->{biblio}, 'Koha::Biblio' ); # Now test that form validation works when we supply a 'form' stage # # No item_type - my $form_stage_missing_params = $request->check_out({ - stage => 'form' - }); - is_deeply($form_stage_missing_params->{value}->{errors}, { - item_type => 1 - }); + my $form_stage_missing_params = $request->check_out( { stage => 'form' } ); + is_deeply( $form_stage_missing_params->{value}->{errors}, { item_type => 1 } ); + # inhouse passed but not a valid patron - my $form_stage_bad_patron = $request->check_out({ - stage => 'form', - item_type => $itemtype->itemtype, - inhouse => 'I_DONT_EXIST' - }); - is_deeply($form_stage_bad_patron->{value}->{errors}, { - inhouse => 1 - }); + my $form_stage_bad_patron = $request->check_out( + { + stage => 'form', + item_type => $itemtype->itemtype, + inhouse => 'I_DONT_EXIST' + } + ); + is_deeply( $form_stage_bad_patron->{value}->{errors}, { inhouse => 1 } ); + # Too many items attached to biblio - my $item1 = $builder->build_sample_item({ biblionumber => $biblio->biblionumber }); - my $item2 = $builder->build_sample_item({ biblionumber => $biblio->biblionumber }); - my $form_stage_two_items = $request->check_out({ - stage => 'form', - item_type => $itemtype->itemtype, - }); - is_deeply($form_stage_two_items->{value}->{errors}, { - itemcount => 1 - }); + my $item1 = $builder->build_sample_item( { biblionumber => $biblio->biblionumber } ); + my $item2 = $builder->build_sample_item( { biblionumber => $biblio->biblionumber } ); + my $form_stage_two_items = $request->check_out( + { + stage => 'form', + item_type => $itemtype->itemtype, + } + ); + is_deeply( $form_stage_two_items->{value}->{errors}, { itemcount => 1 } ); # Delete the items we created, so we can test that we can create one $item1->delete; $item2->delete; # We need to mock the user environment for AddIssue - t::lib::Mocks::mock_userenv({ branchcode => $library->branchcode }); + t::lib::Mocks::mock_userenv( { branchcode => $library->branchcode } ); # # First we pass bad parameters to the item creation to test we're # catching the failure of item creation my $form_stage_bad_branchcode; warning_like { - $form_stage_bad_branchcode = $request->check_out({ - stage => 'form', - item_type => $itemtype->itemtype, - branchcode => '---' - }); - } qr/DBD::mysql::st execute failed: Cannot add or update a child row: a foreign key constraint fails/, - "Item creation fails on bad parameters"; + $form_stage_bad_branchcode = $request->check_out( + { + stage => 'form', + item_type => $itemtype->itemtype, + branchcode => '---' + } + ); + } + qr/DBD::mysql::st execute failed: Cannot add or update a child row: a foreign key constraint fails/, + "Item creation fails on bad parameters"; - is_deeply($form_stage_bad_branchcode->{value}->{errors}, { - item_creation => 1 - },"We get expected failure of item creation"); + is_deeply( + $form_stage_bad_branchcode->{value}->{errors}, { + item_creation => 1 + }, "We get expected failure of item creation" + ); # Now create a proper item - my $form_stage_good_branchcode = $request->check_out({ - stage => 'form', - item_type => $itemtype->itemtype, - branchcode => $library->branchcode - }); + my $form_stage_good_branchcode = $request->check_out( + { + stage => 'form', + item_type => $itemtype->itemtype, + branchcode => $library->branchcode + } + ); + # By default, this item should not be loanable, so check that we're # informed of that fact is_deeply( $form_stage_good_branchcode->{value}->{check_out_errors}, { error => { - NOT_FOR_LOAN => 1, + NOT_FOR_LOAN => 1, itemtype_notforloan => $itemtype->itemtype } }, "We get expected error on notforloan of item" ); + # Delete the item that was created $biblio->items->delete; + # Now create an itemtype that is loanable - my $itemtype_loanable = $builder->build_object({ - class => 'Koha::ItemTypes', - value => { - notforloan => 0 + my $itemtype_loanable = $builder->build_object( + { + class => 'Koha::ItemTypes', + value => { notforloan => 0 } } - }); + ); + # We need to mock the user environment for AddIssue - t::lib::Mocks::mock_userenv({ branchcode => $library->branchcode }); - my $form_stage_loanable = $request->check_out({ - stage => 'form', - item_type => $itemtype_loanable->itemtype, - branchcode => $library->branchcode - }); - is($form_stage_loanable->{stage}, 'done_check_out'); - isa_ok($patron->checkouts, 'Koha::Checkouts'); - is($patron->checkouts->count, 1); - is($request->status, 'CHK'); + t::lib::Mocks::mock_userenv( { branchcode => $library->branchcode } ); + my $form_stage_loanable = $request->check_out( + { + stage => 'form', + item_type => $itemtype_loanable->itemtype, + branchcode => $library->branchcode + } + ); + is( $form_stage_loanable->{stage}, 'done_check_out' ); + isa_ok( $patron->checkouts, 'Koha::Checkouts' ); + is( $patron->checkouts->count, 1 ); + is( $request->status, 'CHK' ); $schema->storage->txn_rollback; }; @@ -1320,32 +1530,36 @@ subtest 'Checking out with custom due date' => sub { plan tests => 1; $schema->storage->txn_begin; - my $library = $builder->build_object({ class => 'Koha::Libraries' }); - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); - my $biblio = $builder->build_sample_biblio(); - my $itemtype_loanable = $builder->build_object({ - class => 'Koha::ItemTypes', - value => { - notforloan => 0 + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + my $biblio = $builder->build_sample_biblio(); + my $itemtype_loanable = $builder->build_object( + { + class => 'Koha::ItemTypes', + value => { notforloan => 0 } } - }); - my $request = $builder->build_object({ - class => 'Koha::ILL::Requests', - value => { - borrowernumber => $patron->borrowernumber, - biblio_id => $biblio->biblionumber + ); + my $request = $builder->build_object( + { + class => 'Koha::ILL::Requests', + value => { + borrowernumber => $patron->borrowernumber, + biblio_id => $biblio->biblionumber + } } - }); + ); - t::lib::Mocks::mock_userenv({ branchcode => $library->branchcode }); - my $duedate = '2099-05-21 00:00:00'; - my $form_stage_loanable = $request->check_out({ - stage => 'form', - item_type => $itemtype_loanable->itemtype, - branchcode => $library->branchcode, - duedate => $duedate - }); - is($patron->checkouts->next->date_due, $duedate, "Custom due date was used"); + t::lib::Mocks::mock_userenv( { branchcode => $library->branchcode } ); + my $duedate = '2099-05-21 00:00:00'; + my $form_stage_loanable = $request->check_out( + { + stage => 'form', + item_type => $itemtype_loanable->itemtype, + branchcode => $library->branchcode, + duedate => $duedate + } + ); + is( $patron->checkouts->next->date_due, $duedate, "Custom due date was used" ); $schema->storage->txn_rollback; }; @@ -1359,86 +1573,132 @@ subtest 'Checking Limits' => sub { # Build infrastructure my $backend = Test::MockObject->new; $backend->set_isa('Koha::Illbackends::Mock'); - $backend->set_always('name', 'Mock'); + $backend->set_always( 'name', 'Mock' ); my $config = Test::MockObject->new; - $config->set_always('backend_dir', "/tmp"); + $config->set_always( 'backend_dir', "/tmp" ); - my $illrq = $builder->build({source => 'Illrequest'}); - my $illrq_obj = Koha::ILL::Requests->find($illrq->{illrequest_id}); + my $illrq = $builder->build( { source => 'Illrequest' } ); + my $illrq_obj = Koha::ILL::Requests->find( $illrq->{illrequest_id} ); $illrq_obj->_config($config); $illrq_obj->_backend($backend); # getLimits - $config->set_series('getLimitRules', - { CPL => { count => 1, method => 'test' } }, - { default => { count => 0, method => 'active' } }); - is_deeply($illrq_obj->getLimits({ type => 'branch', value => "CPL" }), - { count => 1, method => 'test' }, - "getLimits: by value."); - is_deeply($illrq_obj->getLimits({ type => 'branch' }), - { count => 0, method => 'active' }, - "getLimits: by default."); - is_deeply($illrq_obj->getLimits({ type => 'branch', value => "CPL" }), - { count => -1, method => 'active' }, - "getLimits: by hard-coded."); + $config->set_series( + 'getLimitRules', + { CPL => { count => 1, method => 'test' } }, + { default => { count => 0, method => 'active' } } + ); + is_deeply( + $illrq_obj->getLimits( { type => 'branch', value => "CPL" } ), + { count => 1, method => 'test' }, + "getLimits: by value." + ); + is_deeply( + $illrq_obj->getLimits( { type => 'branch' } ), + { count => 0, method => 'active' }, + "getLimits: by default." + ); + is_deeply( + $illrq_obj->getLimits( { type => 'branch', value => "CPL" } ), + { count => -1, method => 'active' }, + "getLimits: by hard-coded." + ); #_limit_counter - is($illrq_obj->_limit_counter('annual', { branchcode => $illrq_obj->branchcode }), - 1, "_limit_counter: Initial branch annual count."); - is($illrq_obj->_limit_counter('active', { branchcode => $illrq_obj->branchcode }), - 1, "_limit_counter: Initial branch active count."); - is($illrq_obj->_limit_counter('annual', { borrowernumber => $illrq_obj->borrowernumber }), - 1, "_limit_counter: Initial patron annual count."); - is($illrq_obj->_limit_counter('active', { borrowernumber => $illrq_obj->borrowernumber }), - 1, "_limit_counter: Initial patron active count."); - $builder->build({ - source => 'Illrequest', - value => { - branchcode => $illrq_obj->branchcode, - borrowernumber => $illrq_obj->borrowernumber, + is( + $illrq_obj->_limit_counter( 'annual', { branchcode => $illrq_obj->branchcode } ), + 1, "_limit_counter: Initial branch annual count." + ); + is( + $illrq_obj->_limit_counter( 'active', { branchcode => $illrq_obj->branchcode } ), + 1, "_limit_counter: Initial branch active count." + ); + is( + $illrq_obj->_limit_counter( 'annual', { borrowernumber => $illrq_obj->borrowernumber } ), + 1, "_limit_counter: Initial patron annual count." + ); + is( + $illrq_obj->_limit_counter( 'active', { borrowernumber => $illrq_obj->borrowernumber } ), + 1, "_limit_counter: Initial patron active count." + ); + $builder->build( + { + source => 'Illrequest', + value => { + branchcode => $illrq_obj->branchcode, + borrowernumber => $illrq_obj->borrowernumber, + } } - }); - is($illrq_obj->_limit_counter('annual', { branchcode => $illrq_obj->branchcode }), - 2, "_limit_counter: Add a qualifying request for branch annual count."); - is($illrq_obj->_limit_counter('active', { branchcode => $illrq_obj->branchcode }), - 2, "_limit_counter: Add a qualifying request for branch active count."); - is($illrq_obj->_limit_counter('annual', { borrowernumber => $illrq_obj->borrowernumber }), - 2, "_limit_counter: Add a qualifying request for patron annual count."); - is($illrq_obj->_limit_counter('active', { borrowernumber => $illrq_obj->borrowernumber }), - 2, "_limit_counter: Add a qualifying request for patron active count."); - $builder->build({ - source => 'Illrequest', - value => { - branchcode => $illrq_obj->branchcode, - borrowernumber => $illrq_obj->borrowernumber, - placed => "2005-05-31", + ); + is( + $illrq_obj->_limit_counter( 'annual', { branchcode => $illrq_obj->branchcode } ), + 2, "_limit_counter: Add a qualifying request for branch annual count." + ); + is( + $illrq_obj->_limit_counter( 'active', { branchcode => $illrq_obj->branchcode } ), + 2, "_limit_counter: Add a qualifying request for branch active count." + ); + is( + $illrq_obj->_limit_counter( 'annual', { borrowernumber => $illrq_obj->borrowernumber } ), + 2, "_limit_counter: Add a qualifying request for patron annual count." + ); + is( + $illrq_obj->_limit_counter( 'active', { borrowernumber => $illrq_obj->borrowernumber } ), + 2, "_limit_counter: Add a qualifying request for patron active count." + ); + $builder->build( + { + source => 'Illrequest', + value => { + branchcode => $illrq_obj->branchcode, + borrowernumber => $illrq_obj->borrowernumber, + placed => "2005-05-31", + } } - }); - is($illrq_obj->_limit_counter('annual', { branchcode => $illrq_obj->branchcode }), - 2, "_limit_counter: Add an out-of-date branch request."); - is($illrq_obj->_limit_counter('active', { branchcode => $illrq_obj->branchcode }), - 3, "_limit_counter: Add a qualifying request for branch active count."); - is($illrq_obj->_limit_counter('annual', { borrowernumber => $illrq_obj->borrowernumber }), - 2, "_limit_counter: Add an out-of-date patron request."); - is($illrq_obj->_limit_counter('active', { borrowernumber => $illrq_obj->borrowernumber }), - 3, "_limit_counter: Add a qualifying request for patron active count."); - $builder->build({ - source => 'Illrequest', - value => { - branchcode => $illrq_obj->branchcode, - borrowernumber => $illrq_obj->borrowernumber, - status => "COMP", + ); + is( + $illrq_obj->_limit_counter( 'annual', { branchcode => $illrq_obj->branchcode } ), + 2, "_limit_counter: Add an out-of-date branch request." + ); + is( + $illrq_obj->_limit_counter( 'active', { branchcode => $illrq_obj->branchcode } ), + 3, "_limit_counter: Add a qualifying request for branch active count." + ); + is( + $illrq_obj->_limit_counter( 'annual', { borrowernumber => $illrq_obj->borrowernumber } ), + 2, "_limit_counter: Add an out-of-date patron request." + ); + is( + $illrq_obj->_limit_counter( 'active', { borrowernumber => $illrq_obj->borrowernumber } ), + 3, "_limit_counter: Add a qualifying request for patron active count." + ); + $builder->build( + { + source => 'Illrequest', + value => { + branchcode => $illrq_obj->branchcode, + borrowernumber => $illrq_obj->borrowernumber, + status => "COMP", + } } - }); - is($illrq_obj->_limit_counter('annual', { branchcode => $illrq_obj->branchcode }), - 3, "_limit_counter: Add a qualifying request for branch annual count."); - is($illrq_obj->_limit_counter('active', { branchcode => $illrq_obj->branchcode }), - 3, "_limit_counter: Add a completed request for branch active count."); - is($illrq_obj->_limit_counter('annual', { borrowernumber => $illrq_obj->borrowernumber }), - 3, "_limit_counter: Add a qualifying request for patron annual count."); - is($illrq_obj->_limit_counter('active', { borrowernumber => $illrq_obj->borrowernumber }), - 3, "_limit_counter: Add a completed request for patron active count."); + ); + is( + $illrq_obj->_limit_counter( 'annual', { branchcode => $illrq_obj->branchcode } ), + 3, "_limit_counter: Add a qualifying request for branch annual count." + ); + is( + $illrq_obj->_limit_counter( 'active', { branchcode => $illrq_obj->branchcode } ), + 3, "_limit_counter: Add a completed request for branch active count." + ); + is( + $illrq_obj->_limit_counter( 'annual', { borrowernumber => $illrq_obj->borrowernumber } ), + 3, "_limit_counter: Add a qualifying request for patron annual count." + ); + is( + $illrq_obj->_limit_counter( 'active', { borrowernumber => $illrq_obj->borrowernumber } ), + 3, "_limit_counter: Add a completed request for patron active count." + ); # check_limits: @@ -1447,72 +1707,173 @@ subtest 'Checking Limits' => sub { # configuration declarations. # No limits - $config->set_always('getLimitRules', undef); - is($illrq_obj->check_limits({patron => $illrq_obj->patron, - librarycode => $illrq_obj->branchcode}), - 1, "check_limits: no configuration => no limits."); + $config->set_always( 'getLimitRules', undef ); + is( + $illrq_obj->check_limits( + { + patron => $illrq_obj->patron, + librarycode => $illrq_obj->branchcode + } + ), + 1, + "check_limits: no configuration => no limits." + ); # Branch tests - $config->set_always('getLimitRules', - { $illrq_obj->branchcode => { count => 1, method => 'active' } }); - is($illrq_obj->check_limits({patron => $illrq_obj->patron, - librarycode => $illrq_obj->branchcode}), - 0, "check_limits: branch active limit exceeded."); - $config->set_always('getLimitRules', - { $illrq_obj->branchcode => { count => 1, method => 'annual' } }); - is($illrq_obj->check_limits({patron => $illrq_obj->patron, - librarycode => $illrq_obj->branchcode}), - 0, "check_limits: branch annual limit exceeded."); - $config->set_always('getLimitRules', - { $illrq_obj->branchcode => { count => 4, method => 'active' } }); - is($illrq_obj->check_limits({patron => $illrq_obj->patron, - librarycode => $illrq_obj->branchcode}), - 1, "check_limits: branch active limit OK."); - $config->set_always('getLimitRules', - { $illrq_obj->branchcode => { count => 4, method => 'annual' } }); - is($illrq_obj->check_limits({patron => $illrq_obj->patron, - librarycode => $illrq_obj->branchcode}), - 1, "check_limits: branch annual limit OK."); + $config->set_always( + 'getLimitRules', + { $illrq_obj->branchcode => { count => 1, method => 'active' } } + ); + is( + $illrq_obj->check_limits( + { + patron => $illrq_obj->patron, + librarycode => $illrq_obj->branchcode + } + ), + 0, + "check_limits: branch active limit exceeded." + ); + $config->set_always( + 'getLimitRules', + { $illrq_obj->branchcode => { count => 1, method => 'annual' } } + ); + is( + $illrq_obj->check_limits( + { + patron => $illrq_obj->patron, + librarycode => $illrq_obj->branchcode + } + ), + 0, + "check_limits: branch annual limit exceeded." + ); + $config->set_always( + 'getLimitRules', + { $illrq_obj->branchcode => { count => 4, method => 'active' } } + ); + is( + $illrq_obj->check_limits( + { + patron => $illrq_obj->patron, + librarycode => $illrq_obj->branchcode + } + ), + 1, + "check_limits: branch active limit OK." + ); + $config->set_always( + 'getLimitRules', + { $illrq_obj->branchcode => { count => 4, method => 'annual' } } + ); + is( + $illrq_obj->check_limits( + { + patron => $illrq_obj->patron, + librarycode => $illrq_obj->branchcode + } + ), + 1, + "check_limits: branch annual limit OK." + ); # Patron tests - $config->set_always('getLimitRules', - { $illrq_obj->patron->categorycode => { count => 1, method => 'active' } }); - is($illrq_obj->check_limits({patron => $illrq_obj->patron, - librarycode => $illrq_obj->branchcode}), - 0, "check_limits: patron category active limit exceeded."); - $config->set_always('getLimitRules', - { $illrq_obj->patron->categorycode => { count => 1, method => 'annual' } }); - is($illrq_obj->check_limits({patron => $illrq_obj->patron, - librarycode => $illrq_obj->branchcode}), - 0, "check_limits: patron category annual limit exceeded."); - $config->set_always('getLimitRules', - { $illrq_obj->patron->categorycode => { count => 4, method => 'active' } }); - is($illrq_obj->check_limits({patron => $illrq_obj->patron, - librarycode => $illrq_obj->branchcode}), - 1, "check_limits: patron category active limit OK."); - $config->set_always('getLimitRules', - { $illrq_obj->patron->categorycode => { count => 4, method => 'annual' } }); - is($illrq_obj->check_limits({patron => $illrq_obj->patron, - librarycode => $illrq_obj->branchcode}), - 1, "check_limits: patron category annual limit OK."); + $config->set_always( + 'getLimitRules', + { $illrq_obj->patron->categorycode => { count => 1, method => 'active' } } + ); + is( + $illrq_obj->check_limits( + { + patron => $illrq_obj->patron, + librarycode => $illrq_obj->branchcode + } + ), + 0, + "check_limits: patron category active limit exceeded." + ); + $config->set_always( + 'getLimitRules', + { $illrq_obj->patron->categorycode => { count => 1, method => 'annual' } } + ); + is( + $illrq_obj->check_limits( + { + patron => $illrq_obj->patron, + librarycode => $illrq_obj->branchcode + } + ), + 0, + "check_limits: patron category annual limit exceeded." + ); + $config->set_always( + 'getLimitRules', + { $illrq_obj->patron->categorycode => { count => 4, method => 'active' } } + ); + is( + $illrq_obj->check_limits( + { + patron => $illrq_obj->patron, + librarycode => $illrq_obj->branchcode + } + ), + 1, + "check_limits: patron category active limit OK." + ); + $config->set_always( + 'getLimitRules', + { $illrq_obj->patron->categorycode => { count => 4, method => 'annual' } } + ); + is( + $illrq_obj->check_limits( + { + patron => $illrq_obj->patron, + librarycode => $illrq_obj->branchcode + } + ), + 1, + "check_limits: patron category annual limit OK." + ); # One rule cancels the other - $config->set_series('getLimitRules', - # Branch rules allow request - { $illrq_obj->branchcode => { count => 4, method => 'active' } }, - # Patron rule forbids it - { $illrq_obj->patron->categorycode => { count => 1, method => 'annual' } }); - is($illrq_obj->check_limits({patron => $illrq_obj->patron, - librarycode => $illrq_obj->branchcode}), - 0, "check_limits: patron category veto overrides branch OK."); - $config->set_series('getLimitRules', - # Branch rules allow request - { $illrq_obj->branchcode => { count => 1, method => 'active' } }, - # Patron rule forbids it - { $illrq_obj->patron->categorycode => { count => 4, method => 'annual' } }); - is($illrq_obj->check_limits({patron => $illrq_obj->patron, - librarycode => $illrq_obj->branchcode}), - 0, "check_limits: branch veto overrides patron category OK."); + $config->set_series( + 'getLimitRules', + + # Branch rules allow request + { $illrq_obj->branchcode => { count => 4, method => 'active' } }, + + # Patron rule forbids it + { $illrq_obj->patron->categorycode => { count => 1, method => 'annual' } } + ); + is( + $illrq_obj->check_limits( + { + patron => $illrq_obj->patron, + librarycode => $illrq_obj->branchcode + } + ), + 0, + "check_limits: patron category veto overrides branch OK." + ); + $config->set_series( + 'getLimitRules', + + # Branch rules allow request + { $illrq_obj->branchcode => { count => 1, method => 'active' } }, + + # Patron rule forbids it + { $illrq_obj->patron->categorycode => { count => 4, method => 'annual' } } + ); + is( + $illrq_obj->check_limits( + { + patron => $illrq_obj->patron, + librarycode => $illrq_obj->branchcode + } + ), + 0, + "check_limits: branch veto overrides patron category OK." + ); $schema->storage->txn_rollback; }; @@ -1523,49 +1884,45 @@ subtest 'Custom statuses' => sub { $schema->storage->txn_begin; - my $cat = Koha::AuthorisedValueCategories->search( - { - category_name => 'ILL_STATUS_ALIAS' - } - ); + my $cat = Koha::AuthorisedValueCategories->search( { category_name => 'ILL_STATUS_ALIAS' } ); - if ($cat->count == 0) { - $cat = $builder->build_object( + if ( $cat->count == 0 ) { + $cat = $builder->build_object( { class => 'Koha::AuthorisedValueCategory', - value => { - category_name => 'ILL_STATUS_ALIAS' - } + value => { category_name => 'ILL_STATUS_ALIAS' } } ); - }; + } my $av = $builder->build_object( { class => 'Koha::AuthorisedValues', - value => { - category => 'ILL_STATUS_ALIAS' - } + value => { category => 'ILL_STATUS_ALIAS' } } ); - is($av->category, 'ILL_STATUS_ALIAS', - "Successfully created authorised value for custom status"); + is( + $av->category, 'ILL_STATUS_ALIAS', + "Successfully created authorised value for custom status" + ); my $ill_req = $builder->build_object( { class => 'Koha::ILL::Requests', - value => { - status_alias => $av->authorised_value - } + value => { status_alias => $av->authorised_value } } ); - isa_ok($ill_req->statusalias, 'Koha::AuthorisedValue', - "statusalias correctly returning Koha::AuthorisedValue object"); + isa_ok( + $ill_req->statusalias, 'Koha::AuthorisedValue', + "statusalias correctly returning Koha::AuthorisedValue object" + ); $ill_req->status("COMP"); - is($ill_req->statusalias, undef, - "Koha::ILL::Request->status overloading resetting status_alias"); + is( + $ill_req->statusalias, undef, + "Koha::ILL::Request->status overloading resetting status_alias" + ); $schema->storage->txn_rollback; }; @@ -1579,13 +1936,13 @@ subtest 'Checking in hook' => sub { # Build infrastructure my $backend = Test::MockObject->new; $backend->set_isa('Koha::Illbackends::Mock'); - $backend->set_always('name', 'Mock'); + $backend->set_always( 'name', 'Mock' ); my $config = Test::MockObject->new; - $config->set_always('backend_dir', "/tmp"); + $config->set_always( 'backend_dir', "/tmp" ); my $item = $builder->build_sample_item(); - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); t::lib::Mocks::mock_userenv( { @@ -1607,21 +1964,24 @@ subtest 'Checking in hook' => sub { $illrq->_config($config); $illrq->_backend($backend); - t::lib::Mocks::mock_preference('CirculateILL', 1); + t::lib::Mocks::mock_preference( 'CirculateILL', 1 ); # Add an issue AddIssue( $patron, $item->barcode ); + # Make the item withdrawn so checking-in is rejected - t::lib::Mocks::mock_preference('BlockReturnOfWithdrawnItems', 1); - $item->set({ withdrawn => 1 })->store; + t::lib::Mocks::mock_preference( 'BlockReturnOfWithdrawnItems', 1 ); + $item->set( { withdrawn => 1 } )->store; AddReturn( $item->barcode, $patron->branchcode ); + # refresh request $illrq->discard_changes; isnt( $illrq->status, 'RET' ); # allow the check-in - $item->set({ withdrawn => 0 })->store; + $item->set( { withdrawn => 0 } )->store; AddReturn( $item->barcode, $patron->branchcode ); + # refresh request $illrq->discard_changes; is( $illrq->status, 'RET' ); diff --git a/t/db_dependent/Koha/Import/Record/Auths.t b/t/db_dependent/Koha/Import/Record/Auths.t index d992a41735..cc0c471d5b 100755 --- a/t/db_dependent/Koha/Import/Record/Auths.t +++ b/t/db_dependent/Koha/Import/Record/Auths.t @@ -29,16 +29,20 @@ use t::lib::TestBuilder; my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; -my $builder = t::lib::TestBuilder->new; +my $builder = t::lib::TestBuilder->new; my $nb_of_record_auths = Koha::Import::Record::Auths->search->count; -my $record_auth_1 = $builder->build({ source => 'ImportAuth' }); -my $record_auth_2 = $builder->build({ source => 'ImportAuth' }); +my $record_auth_1 = $builder->build( { source => 'ImportAuth' } ); +my $record_auth_2 = $builder->build( { source => 'ImportAuth' } ); is( Koha::Import::Record::Auths->search->count, $nb_of_record_auths + 2, 'The 2 record auths should have been added' ); -my $retrieved_record_auth_1 = Koha::Import::Record::Auths->search({ import_record_id => $record_auth_1->{import_record_id}})->next; -is_deeply( $retrieved_record_auth_1->unblessed, $record_auth_1, 'Find a record auth by import record id should return the correct record auth' ); +my $retrieved_record_auth_1 = + Koha::Import::Record::Auths->search( { import_record_id => $record_auth_1->{import_record_id} } )->next; +is_deeply( + $retrieved_record_auth_1->unblessed, $record_auth_1, + 'Find a record auth by import record id should return the correct record auth' +); $retrieved_record_auth_1->delete; is( Koha::Import::Record::Auths->search->count, $nb_of_record_auths + 1, 'Delete should have deleted the record auth' ); diff --git a/t/db_dependent/Koha/Import/Record/Biblios.t b/t/db_dependent/Koha/Import/Record/Biblios.t index cfd0f71b9d..2c1106f926 100755 --- a/t/db_dependent/Koha/Import/Record/Biblios.t +++ b/t/db_dependent/Koha/Import/Record/Biblios.t @@ -29,18 +29,28 @@ use t::lib::TestBuilder; my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; -my $builder = t::lib::TestBuilder->new; +my $builder = t::lib::TestBuilder->new; my $nb_of_record_biblios = Koha::Import::Record::Biblios->search->count; -my $record_biblio_1 = $builder->build({ source => 'ImportBiblio' }); -my $record_biblio_2 = $builder->build({ source => 'ImportBiblio' }); +my $record_biblio_1 = $builder->build( { source => 'ImportBiblio' } ); +my $record_biblio_2 = $builder->build( { source => 'ImportBiblio' } ); -is( Koha::Import::Record::Biblios->search->count, $nb_of_record_biblios + 2, 'The 2 record biblios should have been added' ); +is( + Koha::Import::Record::Biblios->search->count, $nb_of_record_biblios + 2, + 'The 2 record biblios should have been added' +); -my $retrieved_record_biblio_1 = Koha::Import::Record::Biblios->search({ import_record_id => $record_biblio_1->{import_record_id}})->next; -is_deeply( $retrieved_record_biblio_1->unblessed, $record_biblio_1, 'Find a record biblio by import record id should return the correct record biblio' ); +my $retrieved_record_biblio_1 = + Koha::Import::Record::Biblios->search( { import_record_id => $record_biblio_1->{import_record_id} } )->next; +is_deeply( + $retrieved_record_biblio_1->unblessed, $record_biblio_1, + 'Find a record biblio by import record id should return the correct record biblio' +); $retrieved_record_biblio_1->delete; -is( Koha::Import::Record::Biblios->search->count, $nb_of_record_biblios + 1, 'Delete should have deleted the record biblio' ); +is( + Koha::Import::Record::Biblios->search->count, $nb_of_record_biblios + 1, + 'Delete should have deleted the record biblio' +); $schema->storage->txn_rollback; diff --git a/t/db_dependent/Koha/Import/Record/Items.t b/t/db_dependent/Koha/Import/Record/Items.t index de5b6dd916..072b74b089 100755 --- a/t/db_dependent/Koha/Import/Record/Items.t +++ b/t/db_dependent/Koha/Import/Record/Items.t @@ -29,16 +29,20 @@ use t::lib::TestBuilder; my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; -my $builder = t::lib::TestBuilder->new; +my $builder = t::lib::TestBuilder->new; my $nb_of_record_items = Koha::Import::Record::Items->search->count; -my $record_item_1 = $builder->build({ source => 'ImportItem' }); -my $record_item_2 = $builder->build({ source => 'ImportItem' }); +my $record_item_1 = $builder->build( { source => 'ImportItem' } ); +my $record_item_2 = $builder->build( { source => 'ImportItem' } ); is( Koha::Import::Record::Items->search->count, $nb_of_record_items + 2, 'The 2 record items should have been added' ); -my $retrieved_record_item_1 = Koha::Import::Record::Items->search({ import_items_id => $record_item_1->{import_items_id}})->next; -is_deeply( $retrieved_record_item_1->unblessed, $record_item_1, 'Find a record item by import items id should return the correct record item' ); +my $retrieved_record_item_1 = + Koha::Import::Record::Items->search( { import_items_id => $record_item_1->{import_items_id} } )->next; +is_deeply( + $retrieved_record_item_1->unblessed, $record_item_1, + 'Find a record item by import items id should return the correct record item' +); $retrieved_record_item_1->delete; is( Koha::Import::Record::Items->search->count, $nb_of_record_items + 1, 'Delete should have deleted the record item' ); diff --git a/t/db_dependent/Koha/Import/Record/Matches.t b/t/db_dependent/Koha/Import/Record/Matches.t index 36c12a6a7b..3f28b0fcb5 100755 --- a/t/db_dependent/Koha/Import/Record/Matches.t +++ b/t/db_dependent/Koha/Import/Record/Matches.t @@ -29,26 +29,35 @@ use t::lib::TestBuilder; my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; -my $builder = t::lib::TestBuilder->new; -my $nb_of_matches = Koha::Import::Record::Matches->search->count; -my $nb_of_chosen_matches = Koha::Import::Record::Matches->search({ chosen => 1 })->count; +my $builder = t::lib::TestBuilder->new; +my $nb_of_matches = Koha::Import::Record::Matches->search->count; +my $nb_of_chosen_matches = Koha::Import::Record::Matches->search( { chosen => 1 } )->count; -my $match_1 = $builder->build({ source => 'ImportRecordMatch', value => { chosen => 1 } }); -my $match_2 = $builder->build({ source => 'ImportRecordMatch', value => { chosen => 1, import_record_id => $match_1->{import_record_id} } }); +my $match_1 = $builder->build( { source => 'ImportRecordMatch', value => { chosen => 1 } } ); +my $match_2 = $builder->build( + { source => 'ImportRecordMatch', value => { chosen => 1, import_record_id => $match_1->{import_record_id} } } ); is( Koha::Import::Record::Matches->search->count, $nb_of_matches + 2, 'The 2 matches should have been added' ); -is( Koha::Import::Record::Matches->search({chosen => 1 })->count, $nb_of_chosen_matches + 2, 'The 2 chosen matches should have been added' ); +is( + Koha::Import::Record::Matches->search( { chosen => 1 } )->count, $nb_of_chosen_matches + 2, + 'The 2 chosen matches should have been added' +); -my $retrieved_match_1 = Koha::Import::Record::Matches->search({ import_record_id => $match_1->{import_record_id}, candidate_match_id => $match_1->{candidate_match_id} })->next; -is_deeply( $retrieved_match_1->unblessed, $match_1, 'Find a match by import record id and candidate should return the correct match' ); +my $retrieved_match_1 = Koha::Import::Record::Matches->search( + { import_record_id => $match_1->{import_record_id}, candidate_match_id => $match_1->{candidate_match_id} } )->next; +is_deeply( + $retrieved_match_1->unblessed, $match_1, + 'Find a match by import record id and candidate should return the correct match' +); $retrieved_match_1->delete; is( Koha::Import::Record::Matches->search->count, $nb_of_matches + 1, 'Delete should have deleted the match' ); -my $retrieved_match_2 = Koha::Import::Record::Matches->search({ import_record_id => $match_2->{import_record_id}, candidate_match_id => $match_2->{candidate_match_id} })->next; +my $retrieved_match_2 = Koha::Import::Record::Matches->search( + { import_record_id => $match_2->{import_record_id}, candidate_match_id => $match_2->{candidate_match_id} } )->next; my $import_record = $retrieved_match_2->import_record; -is( ref($import_record), 'Koha::Import::Record', "import_record has the correct class"); -is( $import_record->import_record_id, $retrieved_match_2->import_record_id, "We have the right record"); +is( ref($import_record), 'Koha::Import::Record', "import_record has the correct class" ); +is( $import_record->import_record_id, $retrieved_match_2->import_record_id, "We have the right record" ); $schema->storage->txn_rollback; diff --git a/t/db_dependent/Koha/Import/Records.t b/t/db_dependent/Koha/Import/Records.t index c6df426207..1de386528b 100755 --- a/t/db_dependent/Koha/Import/Records.t +++ b/t/db_dependent/Koha/Import/Records.t @@ -29,59 +29,80 @@ use t::lib::TestBuilder; my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; -my $builder = t::lib::TestBuilder->new; +my $builder = t::lib::TestBuilder->new; my $nb_of_records = Koha::Import::Records->search->count; -my $record_1 = $builder->build({ source => 'ImportRecord' }); -my $record_2 = $builder->build({ source => 'ImportRecord' }); +my $record_1 = $builder->build( { source => 'ImportRecord' } ); +my $record_2 = $builder->build( { source => 'ImportRecord' } ); is( Koha::Import::Records->search->count, $nb_of_records + 2, 'The 2 records should have been added' ); -my $retrieved_record_1 = Koha::Import::Records->search({ import_record_id => $record_1->{import_record_id}})->next; -is_deeply( $retrieved_record_1->unblessed, $record_1, 'Find a record by import record id should return the correct record' ); +my $retrieved_record_1 = Koha::Import::Records->search( { import_record_id => $record_1->{import_record_id} } )->next; +is_deeply( + $retrieved_record_1->unblessed, $record_1, + 'Find a record by import record id should return the correct record' +); my $matches = $retrieved_record_1->get_import_record_matches(); -is( $matches->count, 0, "No matches returned if none set"); +is( $matches->count, 0, "No matches returned if none set" ); -my $biblio = $builder->build_sample_biblio; +my $biblio = $builder->build_sample_biblio; my $biblio_1 = $builder->build_sample_biblio; my $biblio_2 = $builder->build_sample_biblio; -my $match_1 = $builder->build_object({ class => 'Koha::Import::Record::Matches', - value => { - score => 100, - chosen => 0, - candidate_match_id => $biblio->biblionumber, - import_record_id => $retrieved_record_1->import_record_id - } - }); -my $match_2 = $builder->build_object({ class => 'Koha::Import::Record::Matches', - value => { - score => 50, - chosen => 1, - candidate_match_id => $biblio_1->biblionumber, - import_record_id => $retrieved_record_1->import_record_id - } - }); -my $match_3 = $builder->build_object({ class => 'Koha::Import::Record::Matches', - value => { - score => 100, - chosen => 0, - candidate_match_id => $biblio_2->biblionumber, - import_record_id => $retrieved_record_1->import_record_id - } - }); +my $match_1 = $builder->build_object( + { + class => 'Koha::Import::Record::Matches', + value => { + score => 100, + chosen => 0, + candidate_match_id => $biblio->biblionumber, + import_record_id => $retrieved_record_1->import_record_id + } + } +); +my $match_2 = $builder->build_object( + { + class => 'Koha::Import::Record::Matches', + value => { + score => 50, + chosen => 1, + candidate_match_id => $biblio_1->biblionumber, + import_record_id => $retrieved_record_1->import_record_id + } + } +); +my $match_3 = $builder->build_object( + { + class => 'Koha::Import::Record::Matches', + value => { + score => 100, + chosen => 0, + candidate_match_id => $biblio_2->biblionumber, + import_record_id => $retrieved_record_1->import_record_id + } + } +); $matches = $retrieved_record_1->get_import_record_matches(); -is( $matches->count, 3, 'We get three matches'); +is( $matches->count, 3, 'We get three matches' ); -is_deeply( $matches->next->unblessed, $match_3->unblessed, "Match order is score desc, biblionumber desc, so 3 is first"); +is_deeply( + $matches->next->unblessed, $match_3->unblessed, + "Match order is score desc, biblionumber desc, so 3 is first" +); -is_deeply( $matches->next->unblessed, $match_1->unblessed, "Match order is score desc, biblionumber desc, so 1 is second"); -is_deeply( $matches->next->unblessed, $match_2->unblessed, "Match order is score desc, biblionumber desc, so 2 is third"); +is_deeply( + $matches->next->unblessed, $match_1->unblessed, + "Match order is score desc, biblionumber desc, so 1 is second" +); +is_deeply( + $matches->next->unblessed, $match_2->unblessed, + "Match order is score desc, biblionumber desc, so 2 is third" +); -$matches = $retrieved_record_1->get_import_record_matches({ chosen => 1 }); -is( $matches->count, 1, 'We get only the chosen match when requesting chosen'); -is_deeply( $matches->next->unblessed, $match_2->unblessed, "Match 2 is the chosen match"); +$matches = $retrieved_record_1->get_import_record_matches( { chosen => 1 } ); +is( $matches->count, 1, 'We get only the chosen match when requesting chosen' ); +is_deeply( $matches->next->unblessed, $match_2->unblessed, "Match 2 is the chosen match" ); $retrieved_record_1->delete; is( Koha::Import::Records->search->count, $nb_of_records + 1, 'Delete should have deleted the record' ); @@ -89,53 +110,54 @@ is( Koha::Import::Records->search->count, $nb_of_records + 1, 'Delete should hav subtest 'replace' => sub { plan tests => 4; - # Replace biblio - my $import_record = $builder->build_object({ class => 'Koha::Import::Records' }); - my $import_record_biblio = $builder->build_object({ - class => 'Koha::Import::Record::Biblios', - value => { - import_record_id => $import_record->id + my $import_record = $builder->build_object( { class => 'Koha::Import::Records' } ); + my $import_record_biblio = $builder->build_object( + { + class => 'Koha::Import::Record::Biblios', + value => { import_record_id => $import_record->id } } - }); + ); - my $koha_biblio = $builder->build_sample_biblio({ title => "The before" }); - my $koha_xml = $koha_biblio->metadata->record->as_xml; - my $import_biblio = $builder->build_sample_biblio({ title => "The after" }); + my $koha_biblio = $builder->build_sample_biblio( { title => "The before" } ); + my $koha_xml = $koha_biblio->metadata->record->as_xml; + my $import_biblio = $builder->build_sample_biblio( { title => "The after" } ); $import_record->marcxml( $import_biblio->metadata->record->as_xml )->store->discard_changes; - $import_record->replace({ biblio => $koha_biblio }); + $import_record->replace( { biblio => $koha_biblio } ); $koha_biblio->discard_changes; $import_record->discard_changes; - is( $koha_biblio->title, "The after", "The Koha biblio is successfully updated" ); - is( $import_record->marcxml_old, $koha_xml, "The old marcxml in import records is correctly updated" ); + is( $koha_biblio->title, "The after", "The Koha biblio is successfully updated" ); + is( $import_record->marcxml_old, $koha_xml, "The old marcxml in import records is correctly updated" ); # Replace authority my $auth_record = MARC::Record->new; $auth_record->append_fields( MARC::Field->new( '100', '', '', a => 'Author' ), ); - my $auth_id = C4::AuthoritiesMarc::AddAuthority($auth_record, undef, 'PERSO_NAME'); - my $koha_auth = Koha::Authorities->find( $auth_id ); - $koha_xml = $koha_auth->marcxml; - $import_record = $builder->build_object({ class => 'Koha::Import::Records' }); - my $import_record_auth = $builder->build_object({ - class => 'Koha::Import::Record::Auths', - value => { - import_record_id => $import_record->id + my $auth_id = C4::AuthoritiesMarc::AddAuthority( $auth_record, undef, 'PERSO_NAME' ); + my $koha_auth = Koha::Authorities->find($auth_id); + $koha_xml = $koha_auth->marcxml; + $import_record = $builder->build_object( { class => 'Koha::Import::Records' } ); + my $import_record_auth = $builder->build_object( + { + class => 'Koha::Import::Record::Auths', + value => { import_record_id => $import_record->id } } - }); - + ); my $field = $auth_record->field('100'); $field->update( 'a' => 'Other author' ); $import_record->marcxml( $auth_record->as_xml )->store->discard_changes; - $import_record->replace({ authority => $koha_auth }); + $import_record->replace( { authority => $koha_auth } ); $koha_auth->discard_changes; $import_record->discard_changes; - my $updated_record = MARC::Record->new_from_xml( $koha_auth->marcxml, 'UTF-8'); - is( $updated_record->field('100')->as_string, $auth_record->field('100')->as_string, "The Koha auhtority record is correctly updated" ); + my $updated_record = MARC::Record->new_from_xml( $koha_auth->marcxml, 'UTF-8' ); + is( + $updated_record->field('100')->as_string, $auth_record->field('100')->as_string, + "The Koha auhtority record is correctly updated" + ); is( $import_record->marcxml_old, $koha_xml, "The old marcxml in import record is correctly updated" ); }; diff --git a/t/db_dependent/Koha/Item.t b/t/db_dependent/Koha/Item.t index 7d115cdb3a..bd3f43b5dc 100755 --- a/t/db_dependent/Koha/Item.t +++ b/t/db_dependent/Koha/Item.t @@ -25,7 +25,7 @@ use Test::Exception; use Test::MockModule; use Test::Warn; -use C4::Biblio qw( GetMarcSubfieldStructure ); +use C4::Biblio qw( GetMarcSubfieldStructure ); use C4::Circulation qw( AddIssue AddReturn ); use Koha::Caches; @@ -135,16 +135,21 @@ subtest 'return_claims relationship' => sub { $schema->storage->txn_begin; my $biblio = $builder->build_sample_biblio(); - my $item = $builder->build_sample_item({ - biblionumber => $biblio->biblionumber, - }); + my $item = $builder->build_sample_item( + { + biblionumber => $biblio->biblionumber, + } + ); my $return_claims = $item->return_claims; - is( ref($return_claims), 'Koha::Checkouts::ReturnClaims', 'return_claims returns a Koha::Checkouts::ReturnClaims object set' ); - is($item->return_claims->count, 0, "Empty Koha::Checkouts::ReturnClaims set returned if no return_claims"); - my $claim1 = $builder->build({ source => 'ReturnClaim', value => { itemnumber => $item->itemnumber }}); - my $claim2 = $builder->build({ source => 'ReturnClaim', value => { itemnumber => $item->itemnumber }}); + is( + ref($return_claims), 'Koha::Checkouts::ReturnClaims', + 'return_claims returns a Koha::Checkouts::ReturnClaims object set' + ); + is( $item->return_claims->count, 0, "Empty Koha::Checkouts::ReturnClaims set returned if no return_claims" ); + my $claim1 = $builder->build( { source => 'ReturnClaim', value => { itemnumber => $item->itemnumber } } ); + my $claim2 = $builder->build( { source => 'ReturnClaim', value => { itemnumber => $item->itemnumber } } ); - is($item->return_claims()->count,2,"Two ReturnClaims found for item"); + is( $item->return_claims()->count, 2, "Two ReturnClaims found for item" ); $schema->storage->txn_rollback; }; @@ -155,32 +160,43 @@ subtest 'return_claim accessor' => sub { $schema->storage->txn_begin; my $biblio = $builder->build_sample_biblio(); - my $item = $builder->build_sample_item({ - biblionumber => $biblio->biblionumber, - }); + my $item = $builder->build_sample_item( + { + biblionumber => $biblio->biblionumber, + } + ); my $return_claim = $item->return_claim; is( $return_claim, undef, 'return_claim returned undefined if there are no claims for this item' ); my $claim1 = $builder->build_object( { class => 'Koha::Checkouts::ReturnClaims', - value => { itemnumber => $item->itemnumber, resolution => undef, created_on => dt_from_string()->subtract( minutes => 10 ) } + value => { + itemnumber => $item->itemnumber, resolution => undef, + created_on => dt_from_string()->subtract( minutes => 10 ) + } } ); my $claim2 = $builder->build_object( { class => 'Koha::Checkouts::ReturnClaims', - value => { itemnumber => $item->itemnumber, resolution => undef, created_on => dt_from_string()->subtract( minutes => 5 ) } + value => { + itemnumber => $item->itemnumber, resolution => undef, + created_on => dt_from_string()->subtract( minutes => 5 ) + } } ); $return_claim = $item->return_claim; - is( ref($return_claim), 'Koha::Checkouts::ReturnClaim', 'return_claim returned a Koha::Checkouts::ReturnClaim object' ); - is( $return_claim->id, $claim2->id, 'return_claim returns the most recent unresolved claim'); + is( + ref($return_claim), 'Koha::Checkouts::ReturnClaim', + 'return_claim returned a Koha::Checkouts::ReturnClaim object' + ); + is( $return_claim->id, $claim2->id, 'return_claim returns the most recent unresolved claim' ); $claim2->resolution('test')->store(); $return_claim = $item->return_claim; - is( $return_claim->id, $claim1->id, 'return_claim returns the only unresolved claim'); + is( $return_claim->id, $claim1->id, 'return_claim returns the only unresolved claim' ); $claim1->resolution('test')->store(); $return_claim = $item->return_claim; @@ -193,16 +209,18 @@ subtest 'tracked_links relationship' => sub { plan tests => 3; my $biblio = $builder->build_sample_biblio(); - my $item = $builder->build_sample_item({ - biblionumber => $biblio->biblionumber, - }); + my $item = $builder->build_sample_item( + { + biblionumber => $biblio->biblionumber, + } + ); my $tracked_links = $item->tracked_links; - is( ref($tracked_links), 'Koha::TrackedLinks', 'tracked_links returns a Koha::TrackedLinks object set' ); - is($item->tracked_links->count, 0, "Empty Koha::TrackedLinks set returned if no tracked_links"); - my $link1 = $builder->build({ source => 'Linktracker', value => { itemnumber => $item->itemnumber }}); - my $link2 = $builder->build({ source => 'Linktracker', value => { itemnumber => $item->itemnumber }}); + is( ref($tracked_links), 'Koha::TrackedLinks', 'tracked_links returns a Koha::TrackedLinks object set' ); + is( $item->tracked_links->count, 0, "Empty Koha::TrackedLinks set returned if no tracked_links" ); + my $link1 = $builder->build( { source => 'Linktracker', value => { itemnumber => $item->itemnumber } } ); + my $link2 = $builder->build( { source => 'Linktracker', value => { itemnumber => $item->itemnumber } } ); - is($item->tracked_links()->count,2,"Two tracked links found"); + is( $item->tracked_links()->count, 2, "Two tracked links found" ); }; subtest 'is_bundle tests' => sub { @@ -210,17 +228,16 @@ subtest 'is_bundle tests' => sub { $schema->storage->txn_begin; - my $item = $builder->build_sample_item(); + my $item = $builder->build_sample_item(); my $is_bundle = $item->is_bundle; - is($is_bundle, 0, 'is_bundle returns 0 when there are no items attached'); + is( $is_bundle, 0, 'is_bundle returns 0 when there are no items attached' ); my $item2 = $builder->build_sample_item(); - $schema->resultset('ItemBundle') - ->create( { host => $item->itemnumber, item => $item2->itemnumber } ); + $schema->resultset('ItemBundle')->create( { host => $item->itemnumber, item => $item2->itemnumber } ); $is_bundle = $item->is_bundle; - is($is_bundle, 1, 'is_bundle returns 1 when there is at least one item attached'); + is( $is_bundle, 1, 'is_bundle returns 1 when there is at least one item attached' ); $schema->storage->txn_rollback; }; @@ -230,17 +247,16 @@ subtest 'in_bundle tests' => sub { $schema->storage->txn_begin; - my $item = $builder->build_sample_item(); + my $item = $builder->build_sample_item(); my $in_bundle = $item->in_bundle; - is($in_bundle, 0, 'in_bundle returns 0 when the item is not in a bundle'); + is( $in_bundle, 0, 'in_bundle returns 0 when the item is not in a bundle' ); my $host_item = $builder->build_sample_item(); - $schema->resultset('ItemBundle') - ->create( { host => $host_item->itemnumber, item => $item->itemnumber } ); + $schema->resultset('ItemBundle')->create( { host => $host_item->itemnumber, item => $item->itemnumber } ); $in_bundle = $item->in_bundle; - is($in_bundle, 1, 'in_bundle returns 1 when the item is in a bundle'); + is( $in_bundle, 1, 'in_bundle returns 1 when the item is in a bundle' ); $schema->storage->txn_rollback; }; @@ -250,29 +266,29 @@ subtest 'bundle_items tests' => sub { $schema->storage->txn_begin; - my $host_item = $builder->build_sample_item(); + my $host_item = $builder->build_sample_item(); my $bundle_items = $host_item->bundle_items; - is( ref($bundle_items), 'Koha::Items', - 'bundle_items returns a Koha::Items object set' ); - is( $bundle_items->count, 0, - 'bundle_items set is empty when no items are bundled' ); + is( + ref($bundle_items), 'Koha::Items', + 'bundle_items returns a Koha::Items object set' + ); + is( + $bundle_items->count, 0, + 'bundle_items set is empty when no items are bundled' + ); my $bundle_item1 = $builder->build_sample_item(); my $bundle_item2 = $builder->build_sample_item(); my $bundle_item3 = $builder->build_sample_item(); - $schema->resultset('ItemBundle') - ->create( - { host => $host_item->itemnumber, item => $bundle_item1->itemnumber } ); - $schema->resultset('ItemBundle') - ->create( - { host => $host_item->itemnumber, item => $bundle_item2->itemnumber } ); - $schema->resultset('ItemBundle') - ->create( - { host => $host_item->itemnumber, item => $bundle_item3->itemnumber } ); + $schema->resultset('ItemBundle')->create( { host => $host_item->itemnumber, item => $bundle_item1->itemnumber } ); + $schema->resultset('ItemBundle')->create( { host => $host_item->itemnumber, item => $bundle_item2->itemnumber } ); + $schema->resultset('ItemBundle')->create( { host => $host_item->itemnumber, item => $bundle_item3->itemnumber } ); $bundle_items = $host_item->bundle_items; - is( $bundle_items->count, 3, - 'bundle_items returns all the bundled items in the set' ); + is( + $bundle_items->count, 3, + 'bundle_items returns all the bundled items in the set' + ); $bundle_item2->itemlost(1)->store; is( $host_item->bundle_items_not_lost->count, 2 ); @@ -287,18 +303,16 @@ subtest 'bundle_host tests' => sub { $schema->storage->txn_begin; - my $host_item = $builder->build_sample_item(); + my $host_item = $builder->build_sample_item(); my $bundle_item1 = $builder->build_sample_item(); my $bundle_item2 = $builder->build_sample_item(); - $schema->resultset('ItemBundle') - ->create( - { host => $host_item->itemnumber, item => $bundle_item2->itemnumber } ); + $schema->resultset('ItemBundle')->create( { host => $host_item->itemnumber, item => $bundle_item2->itemnumber } ); my $bundle_host = $bundle_item1->bundle_host; - is( $bundle_host, undef, 'bundle_host returns undefined when the item it not part of a bundle'); + is( $bundle_host, undef, 'bundle_host returns undefined when the item it not part of a bundle' ); $bundle_host = $bundle_item2->bundle_host; - is( ref($bundle_host), 'Koha::Item', 'bundle_host returns a Koha::Item object when the item is in a bundle'); - is( $bundle_host->id, $host_item->id, 'bundle_host returns the host item when called against an item in a bundle'); + is( ref($bundle_host), 'Koha::Item', 'bundle_host returns a Koha::Item object when the item is in a bundle' ); + is( $bundle_host->id, $host_item->id, 'bundle_host returns the host item when called against an item in a bundle' ); $schema->storage->txn_rollback; }; @@ -310,12 +324,10 @@ subtest 'add_to_bundle tests' => sub { t::lib::Mocks::mock_preference( 'BundleNotLoanValue', 1 ); - my $library = $builder->build_object({ class => 'Koha::Libraries' }); - t::lib::Mocks::mock_userenv({ - branchcode => $library->branchcode - }); + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); + t::lib::Mocks::mock_userenv( { branchcode => $library->branchcode } ); - my $host_item = $builder->build_sample_item(); + my $host_item = $builder->build_sample_item(); my $bundle_item1 = $builder->build_sample_item(); my $bundle_item2 = $builder->build_sample_item(); my $bundle_item3 = $builder->build_sample_item(); @@ -324,7 +336,7 @@ subtest 'add_to_bundle tests' => sub { throws_ok { $host_item->add_to_bundle($host_item) } 'Koha::Exceptions::Item::Bundle::IsBundle', - 'Exception thrown if you try to add the item to itself'; + 'Exception thrown if you try to add the item to itself'; my $reserve_id = C4::Reserves::AddReserve( { @@ -336,40 +348,40 @@ subtest 'add_to_bundle tests' => sub { ); throws_ok { $host_item->add_to_bundle($bundle_item3) } 'Koha::Exceptions::Item::Bundle::ItemHasHolds', - 'Exception thrown if you try to add an item with holds to a bundle'; + 'Exception thrown if you try to add an item with holds to a bundle'; - ok($host_item->add_to_bundle($bundle_item1), 'bundle_item1 added to bundle'); - is($bundle_item1->notforloan, 1, 'add_to_bundle sets notforloan to BundleNotLoanValue'); + ok( $host_item->add_to_bundle($bundle_item1), 'bundle_item1 added to bundle' ); + is( $bundle_item1->notforloan, 1, 'add_to_bundle sets notforloan to BundleNotLoanValue' ); throws_ok { $host_item->add_to_bundle($bundle_item1) } 'Koha::Exceptions::Object::DuplicateID', - 'Exception thrown if you try to add the same item twice'; + 'Exception thrown if you try to add the same item twice'; throws_ok { $bundle_item1->add_to_bundle($bundle_item2) } 'Koha::Exceptions::Item::Bundle::IsBundle', - 'Exception thrown if you try to add an item to a bundled item'; + 'Exception thrown if you try to add an item to a bundled item'; throws_ok { $bundle_item2->add_to_bundle($host_item) } 'Koha::Exceptions::Item::Bundle::IsBundle', - 'Exception thrown if you try to add a bundle host to a bundle item'; + 'Exception thrown if you try to add a bundle host to a bundle item'; C4::Circulation::AddIssue( $patron, $host_item->barcode ); throws_ok { $host_item->add_to_bundle($bundle_item2) } 'Koha::Exceptions::Item::Bundle::BundleIsCheckedOut', - 'Exception thrown if you try to add an item to a checked out bundle'; + 'Exception thrown if you try to add an item to a checked out bundle'; C4::Circulation::AddReturn( $host_item->barcode, $host_item->homebranch ); $host_item->discard_changes; C4::Circulation::AddIssue( $patron, $bundle_item2->barcode ); throws_ok { $host_item->add_to_bundle($bundle_item2) } 'Koha::Exceptions::Item::Bundle::ItemIsCheckedOut', - 'Exception thrown if you try to add a checked out item'; + 'Exception thrown if you try to add a checked out item'; $bundle_item2->withdrawn(1)->store; t::lib::Mocks::mock_preference( 'BlockReturnOfWithdrawnItems', 1 ); throws_ok { $host_item->add_to_bundle( $bundle_item2, { force_checkin => 1 } ) } 'Koha::Exceptions::Checkin::FailedCheckin', - 'Exception thrown if you try to add a checked out item using + 'Exception thrown if you try to add a checked out item using "force_checkin" and the return is not possible'; $bundle_item2->withdrawn(0)->store; @@ -387,8 +399,8 @@ subtest 'remove_from_bundle tests' => sub { $schema->storage->txn_begin; - my $host_item = $builder->build_sample_item(); - my $bundle_item1 = $builder->build_sample_item({ notforloan => 1 }); + my $host_item = $builder->build_sample_item(); + my $bundle_item1 = $builder->build_sample_item( { notforloan => 1 } ); $host_item->add_to_bundle($bundle_item1); my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); @@ -397,14 +409,14 @@ subtest 'remove_from_bundle tests' => sub { C4::Circulation::AddIssue( $patron, $host_item->barcode ); throws_ok { $bundle_item1->remove_from_bundle } 'Koha::Exceptions::Item::Bundle::BundleIsCheckedOut', - 'Exception thrown if you try to add an item to a checked out bundle'; + 'Exception thrown if you try to add an item to a checked out bundle'; my ( $doreturn, $messages, $issue ) = C4::Circulation::AddReturn( $host_item->barcode, $host_item->homebranch ); $bundle_item1->discard_changes; - is($bundle_item1->remove_from_bundle(), 1, 'remove_from_bundle returns 1 when item is removed from a bundle'); - is($bundle_item1->notforloan, 0, 'remove_from_bundle resets notforloan to 0'); + is( $bundle_item1->remove_from_bundle(), 1, 'remove_from_bundle returns 1 when item is removed from a bundle' ); + is( $bundle_item1->notforloan, 0, 'remove_from_bundle resets notforloan to 0' ); $bundle_item1->discard_changes; - is($bundle_item1->remove_from_bundle(), 0, 'remove_from_bundle returns 0 when item is not in a bundle'); + is( $bundle_item1->remove_from_bundle(), 0, 'remove_from_bundle returns 0 when item is not in a bundle' ); $schema->storage->txn_rollback; }; @@ -415,14 +427,14 @@ subtest 'hidden_in_opac() tests' => sub { $schema->storage->txn_begin; - my $item = $builder->build_sample_item({ itemlost => 2 }); + my $item = $builder->build_sample_item( { itemlost => 2 } ); my $rules = {}; # disable hidelostitems as it interteres with OpachiddenItems for the calculation t::lib::Mocks::mock_preference( 'hidelostitems', 0 ); - ok( !$item->hidden_in_opac, 'No rules passed, shouldn\'t hide' ); - ok( !$item->hidden_in_opac({ rules => $rules }), 'Empty rules passed, shouldn\'t hide' ); + ok( !$item->hidden_in_opac, 'No rules passed, shouldn\'t hide' ); + ok( !$item->hidden_in_opac( { rules => $rules } ), 'Empty rules passed, shouldn\'t hide' ); # enable hidelostitems to verify correct behaviour t::lib::Mocks::mock_preference( 'hidelostitems', 1 ); @@ -430,11 +442,11 @@ subtest 'hidden_in_opac() tests' => sub { # disable hidelostitems t::lib::Mocks::mock_preference( 'hidelostitems', 0 ); - my $withdrawn = $item->withdrawn + 1; # make sure this attribute doesn't match + my $withdrawn = $item->withdrawn + 1; # make sure this attribute doesn't match $rules = { withdrawn => [$withdrawn], itype => [ $item->itype ] }; - ok( $item->hidden_in_opac({ rules => $rules }), 'Rule matching itype passed, should hide' ); + ok( $item->hidden_in_opac( { rules => $rules } ), 'Rule matching itype passed, should hide' ); $rules = { ccode => ['FOO'] }; $item = $item->ccode(undef)->store->get_from_storage; @@ -452,8 +464,8 @@ subtest 'has_pending_hold() tests' => sub { $schema->storage->txn_begin; - my $dbh = C4::Context->dbh; - my $item = $builder->build_sample_item({ itemlost => 0 }); + my $dbh = C4::Context->dbh; + my $item = $builder->build_sample_item( { itemlost => 0 } ); my $itemnumber = $item->itemnumber; my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); @@ -461,29 +473,30 @@ subtest 'has_pending_hold() tests' => sub { $dbh->do( "INSERT INTO tmp_holdsqueue (surname,borrowernumber,itemnumber) VALUES ('Clamp',$borrowernumber,$itemnumber)"); - ok( $item->has_pending_hold, "Yes, we have a pending hold"); + ok( $item->has_pending_hold, "Yes, we have a pending hold" ); $dbh->do("DELETE FROM tmp_holdsqueue WHERE itemnumber=$itemnumber"); $item->discard_changes; - ok( !$item->has_pending_hold, "We don't have a pending hold if nothing in the tmp_holdsqueue"); + ok( !$item->has_pending_hold, "We don't have a pending hold if nothing in the tmp_holdsqueue" ); $schema->storage->txn_rollback; }; subtest "as_marc_field() tests" => sub { - my $mss = C4::Biblio::GetMarcSubfieldStructure( '' ); - my ( $itemtag, $itemtagsubfield) = C4::Biblio::GetMarcFromKohaField( "items.itemnumber" ); + my $mss = C4::Biblio::GetMarcSubfieldStructure(''); + my ( $itemtag, $itemtagsubfield ) = C4::Biblio::GetMarcFromKohaField("items.itemnumber"); my @schema_columns = $schema->resultset('Item')->result_source->columns; - my @mapped_columns = grep { exists $mss->{'items.'.$_} } @schema_columns; + my @mapped_columns = grep { exists $mss->{ 'items.' . $_ } } @schema_columns; plan tests => scalar @mapped_columns + 5; $schema->storage->txn_begin; my $item = $builder->build_sample_item; + # Make sure it has at least one undefined attribute - $item->set({ replacementprice => undef })->store->discard_changes; + $item->set( { replacementprice => undef } )->store->discard_changes; my $marc_field = $item->as_marc_field; @@ -495,8 +508,10 @@ subtest "as_marc_field() tests" => sub { foreach my $column (@mapped_columns) { my $tagsubfield = $mss->{ 'items.' . $column }[0]->{tagsubfield}; - is( $marc_field->subfield($tagsubfield), - $item->$column, "Value is mapped correctly for column $column" ); + is( + $marc_field->subfield($tagsubfield), + $item->$column, "Value is mapped correctly for column $column" + ); } my $unmapped_subfield = Koha::MarcSubfieldStructure->new( @@ -519,28 +534,29 @@ subtest "as_marc_field() tests" => sub { push @unlinked_subfields, X => 'Something weird', Y => 'Something else'; $item->more_subfields_xml( C4::Items::_get_unlinked_subfields_xml( \@unlinked_subfields ) )->store; - Koha::Caches->get_instance->clear_from_cache( "MarcStructure-1-" ); - Koha::MarcSubfieldStructures->search( - { frameworkcode => '', tagfield => $itemtag } ) - ->update( { display_order => \['FLOOR( 1 + RAND( ) * 10 )'] } ); + Koha::Caches->get_instance->clear_from_cache("MarcStructure-1-"); + Koha::MarcSubfieldStructures->search( { frameworkcode => '', tagfield => $itemtag } ) + ->update( { display_order => \['FLOOR( 1 + RAND( ) * 10 )'] } ); $marc_field = $item->as_marc_field; - my $tagslib = C4::Biblio::GetMarcStructure(1, ''); + my $tagslib = C4::Biblio::GetMarcStructure( 1, '' ); my @subfields = $marc_field->subfields; - my $result = all { defined $_->[1] } @subfields; + my $result = all { defined $_->[1] } @subfields; ok( $result, 'There are no undef subfields' ); my @ordered_subfields = sort { - $tagslib->{$itemtag}->{ $a->[0] }->{display_order} - <=> $tagslib->{$itemtag}->{ $b->[0] }->{display_order} + $tagslib->{$itemtag}->{ $a->[0] }->{display_order} <=> $tagslib->{$itemtag}->{ $b->[0] }->{display_order} } @subfields; - is_deeply(\@subfields, \@ordered_subfields); + is_deeply( \@subfields, \@ordered_subfields ); - is( scalar $marc_field->subfield('X'), 'Something weird', 'more_subfield_xml is considered when kohafield is NULL' ); + is( + scalar $marc_field->subfield('X'), 'Something weird', + 'more_subfield_xml is considered when kohafield is NULL' + ); is( scalar $marc_field->subfield('Y'), 'Something else', 'more_subfield_xml is considered when kohafield = ""' ); $schema->storage->txn_rollback; - Koha::Caches->get_instance->clear_from_cache( "MarcStructure-1-" ); + Koha::Caches->get_instance->clear_from_cache("MarcStructure-1-"); }; subtest 'pickup_locations() tests' => sub { @@ -551,17 +567,27 @@ subtest 'pickup_locations() tests' => sub { my $dbh = C4::Context->dbh; - my $root1 = $builder->build_object( { class => 'Koha::Library::Groups', value => { ft_local_hold_group => 1, branchcode => undef } } ); - my $root2 = $builder->build_object( { class => 'Koha::Library::Groups', value => { ft_local_hold_group => 1, branchcode => undef } } ); + my $root1 = $builder->build_object( + { class => 'Koha::Library::Groups', value => { ft_local_hold_group => 1, branchcode => undef } } ); + my $root2 = $builder->build_object( + { class => 'Koha::Library::Groups', value => { ft_local_hold_group => 1, branchcode => undef } } ); my $library1 = $builder->build_object( { class => 'Koha::Libraries', value => { pickup_location => 1, } } ); my $library2 = $builder->build_object( { class => 'Koha::Libraries', value => { pickup_location => 1, } } ); my $library3 = $builder->build_object( { class => 'Koha::Libraries', value => { pickup_location => 0, } } ); my $library4 = $builder->build_object( { class => 'Koha::Libraries', value => { pickup_location => 1, } } ); - my $group1_1 = $builder->build_object( { class => 'Koha::Library::Groups', value => { parent_id => $root1->id, branchcode => $library1->branchcode } } ); - my $group1_2 = $builder->build_object( { class => 'Koha::Library::Groups', value => { parent_id => $root1->id, branchcode => $library2->branchcode } } ); + my $group1_1 = $builder->build_object( + { class => 'Koha::Library::Groups', value => { parent_id => $root1->id, branchcode => $library1->branchcode } } + ); + my $group1_2 = $builder->build_object( + { class => 'Koha::Library::Groups', value => { parent_id => $root1->id, branchcode => $library2->branchcode } } + ); - my $group2_1 = $builder->build_object( { class => 'Koha::Library::Groups', value => { parent_id => $root2->id, branchcode => $library3->branchcode } } ); - my $group2_2 = $builder->build_object( { class => 'Koha::Library::Groups', value => { parent_id => $root2->id, branchcode => $library4->branchcode } } ); + my $group2_1 = $builder->build_object( + { class => 'Koha::Library::Groups', value => { parent_id => $root2->id, branchcode => $library3->branchcode } } + ); + my $group2_2 = $builder->build_object( + { class => 'Koha::Library::Groups', value => { parent_id => $root2->id, branchcode => $library4->branchcode } } + ); our @branchcodes = ( $library1->branchcode, $library2->branchcode, @@ -597,15 +623,16 @@ subtest 'pickup_locations() tests' => sub { } ); - throws_ok - { $item1->pickup_locations } - 'Koha::Exceptions::MissingParameter', - 'Exception thrown on missing parameter'; + throws_ok { $item1->pickup_locations } + 'Koha::Exceptions::MissingParameter', + 'Exception thrown on missing parameter'; is( $@->parameter, 'patron', 'Exception param correctly set' ); - my $patron1 = $builder->build_object( { class => 'Koha::Patrons', value => { branchcode => $library1->branchcode, firstname => '1' } } ); - my $patron4 = $builder->build_object( { class => 'Koha::Patrons', value => { branchcode => $library4->branchcode, firstname => '4' } } ); + my $patron1 = $builder->build_object( + { class => 'Koha::Patrons', value => { branchcode => $library1->branchcode, firstname => '1' } } ); + my $patron4 = $builder->build_object( + { class => 'Koha::Patrons', value => { branchcode => $library4->branchcode, firstname => '4' } } ); my $results = { "1-1-from_home_library-any" => 3, @@ -677,19 +704,19 @@ subtest 'pickup_locations() tests' => sub { { branchcode => undef, itemtype => undef, - rules => { - holdallowed => $ha, + rules => { + holdallowed => $ha, hold_fulfillment_policy => $hfp, - returnbranch => 'any' + returnbranch => 'any' } } ); my $ha_value = - $ha eq 'from_local_hold_group' ? 'holdgroup' - : ( + $ha eq 'from_local_hold_group' ? 'holdgroup' + : ( $ha eq 'from_any_library' ? 'any' : 'homebranch' - ); + ); my @pl = map { my $pickup_location = $_; @@ -697,40 +724,30 @@ subtest 'pickup_locations() tests' => sub { } $item->pickup_locations( { patron => $patron } )->as_list; ok( - scalar(@pl) eq $results->{ - $item->copynumber . '-' - . $patron->firstname . '-' - . $ha . '-' - . $hfp - }, + scalar(@pl) eq $results->{ $item->copynumber . '-' . $patron->firstname . '-' . $ha . '-' . $hfp }, 'item' - . $item->copynumber - . ', patron' - . $patron->firstname - . ', holdallowed: ' - . $ha_value - . ', hold_fulfillment_policy: ' - . $hfp - . ' should return ' - . $results->{ - $item->copynumber . '-' - . $patron->firstname . '-' - . $ha . '-' - . $hfp - } - . ' and returns ' - . scalar(@pl) + . $item->copynumber + . ', patron' + . $patron->firstname + . ', holdallowed: ' + . $ha_value + . ', hold_fulfillment_policy: ' + . $hfp + . ' should return ' + . $results->{ $item->copynumber . '-' . $patron->firstname . '-' . $ha . '-' . $hfp } + . ' and returns ' + . scalar(@pl) ); } + foreach my $item ( $item1, $item3 ) { + foreach my $patron ( $patron1, $patron4 ) { - foreach my $item ($item1, $item3) { - foreach my $patron ($patron1, $patron4) { #holdallowed 1: homebranch, 2: any, 3: holdgroup - foreach my $ha ('from_home_library', 'from_any_library', 'from_local_hold_group') { - foreach my $hfp ('any', 'holdgroup', 'patrongroup', 'homebranch', 'holdingbranch') { - _doTest($item, $patron, $ha, $hfp, $results); + foreach my $ha ( 'from_home_library', 'from_any_library', 'from_local_hold_group' ) { + foreach my $hfp ( 'any', 'holdgroup', 'patrongroup', 'homebranch', 'holdingbranch' ) { + _doTest( $item, $patron, $ha, $hfp, $results ); } } } @@ -746,8 +763,8 @@ subtest 'pickup_locations() tests' => sub { } )->store; - t::lib::Mocks::mock_preference('UseBranchTransferLimits', 1); - t::lib::Mocks::mock_preference('BranchTransferLimitsType', 'itemtype'); + t::lib::Mocks::mock_preference( 'UseBranchTransferLimits', 1 ); + t::lib::Mocks::mock_preference( 'BranchTransferLimitsType', 'itemtype' ); Koha::CirculationRules->set_rules( { branchcode => undef, @@ -776,7 +793,10 @@ subtest 'pickup_locations() tests' => sub { grep { $pickup_location->branchcode eq $_ } @branchcodes } $item1->pickup_locations( { patron => $patron1 } )->as_list; - is( scalar @pickup_locations, 3 - 1, "With a transfer limits we get back the libraries that are pickup locations minus 1 limited library"); + is( + scalar @pickup_locations, 3 - 1, + "With a transfer limits we get back the libraries that are pickup locations minus 1 limited library" + ); $builder->build_object( { @@ -795,20 +815,29 @@ subtest 'pickup_locations() tests' => sub { grep { $pickup_location->branchcode eq $_ } @branchcodes } $item1->pickup_locations( { patron => $patron1 } )->as_list; - is( scalar @pickup_locations, 3 - 2, "With 2 transfer limits we get back the libraries that are pickup locations minus 2 limited libraries"); + is( + scalar @pickup_locations, 3 - 2, + "With 2 transfer limits we get back the libraries that are pickup locations minus 2 limited libraries" + ); - t::lib::Mocks::mock_preference('BranchTransferLimitsType', 'ccode'); + t::lib::Mocks::mock_preference( 'BranchTransferLimitsType', 'ccode' ); @pickup_locations = map { my $pickup_location = $_; grep { $pickup_location->branchcode eq $_ } @branchcodes } $item1->pickup_locations( { patron => $patron1 } )->as_list; - is( scalar @pickup_locations, 3, "With no transfer limits of type ccode we get back the libraries that are pickup locations"); + is( + scalar @pickup_locations, 3, + "With no transfer limits of type ccode we get back the libraries that are pickup locations" + ); @pickup_locations = map { my $pickup_location = $_; grep { $pickup_location->branchcode eq $_ } @branchcodes } $item_no_ccode->pickup_locations( { patron => $patron1 } )->as_list; - is( scalar @pickup_locations, 3, "With no transfer limits of type ccode and an item with no ccode we get back the libraries that are pickup locations"); + is( + scalar @pickup_locations, 3, + "With no transfer limits of type ccode and an item with no ccode we get back the libraries that are pickup locations" + ); $builder->build_object( { @@ -826,7 +855,10 @@ subtest 'pickup_locations() tests' => sub { my $pickup_location = $_; grep { $pickup_location->branchcode eq $_ } @branchcodes } $item1->pickup_locations( { patron => $patron1 } )->as_list; - is( scalar @pickup_locations, 3 - 1, "With a transfer limits we get back the libraries that are pickup locations minus 1 limited library"); + is( + scalar @pickup_locations, 3 - 1, + "With a transfer limits we get back the libraries that are pickup locations minus 1 limited library" + ); $builder->build_object( { @@ -844,9 +876,12 @@ subtest 'pickup_locations() tests' => sub { my $pickup_location = $_; grep { $pickup_location->branchcode eq $_ } @branchcodes } $item1->pickup_locations( { patron => $patron1 } )->as_list; - is( scalar @pickup_locations, 3 - 2, "With 2 transfer limits we get back the libraries that are pickup locations minus 2 limited libraries"); + is( + scalar @pickup_locations, 3 - 2, + "With 2 transfer limits we get back the libraries that are pickup locations minus 2 limited libraries" + ); - t::lib::Mocks::mock_preference('UseBranchTransferLimits', 0); + t::lib::Mocks::mock_preference( 'UseBranchTransferLimits', 0 ); $schema->storage->txn_rollback; }; @@ -985,82 +1020,89 @@ subtest 'deletion' => sub { is( $item->deleted_on, undef, 'deleted_on not set for new item' ); my $deleted_item = $item->move_to_deleted; - is( ref( $deleted_item ), 'Koha::Schema::Result::Deleteditem', 'Koha::Item->move_to_deleted should return the Deleted item' ) - ; # FIXME This should be Koha::Deleted::Item + is( + ref($deleted_item), 'Koha::Schema::Result::Deleteditem', + 'Koha::Item->move_to_deleted should return the Deleted item' + ); # FIXME This should be Koha::Deleted::Item is( t::lib::Dates::compare( $deleted_item->deleted_on, dt_from_string() ), 0 ); - is( Koha::Old::Items->search({itemnumber => $item->itemnumber})->count, 1, '->move_to_deleted must have moved the item to deleteditem' ); + is( + Koha::Old::Items->search( { itemnumber => $item->itemnumber } )->count, 1, + '->move_to_deleted must have moved the item to deleteditem' + ); $item = $builder->build_sample_item( { biblionumber => $biblio->biblionumber, } ); $item->delete; - is( Koha::Old::Items->search({itemnumber => $item->itemnumber})->count, 0, '->move_to_deleted must not have moved the item to deleteditem' ); + is( + Koha::Old::Items->search( { itemnumber => $item->itemnumber } )->count, 0, + '->move_to_deleted must not have moved the item to deleteditem' + ); + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); + my $library_2 = $builder->build_object( { class => 'Koha::Libraries' } ); - my $library = $builder->build_object({ class => 'Koha::Libraries' }); - my $library_2 = $builder->build_object({ class => 'Koha::Libraries' }); + my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { flags => 2 ^ 9 } } ); # allow edit items + t::lib::Mocks::mock_userenv( { branchcode => $library->branchcode, borrowernumber => $patron->id } ); - my $patron = $builder->build_object({class => 'Koha::Patrons', value => { flags => 2^9 } }); # allow edit items - t::lib::Mocks::mock_userenv({ branchcode => $library->branchcode, borrowernumber => $patron->id }); - - $item = $builder->build_sample_item({ library => $library->branchcode }); + $item = $builder->build_sample_item( { library => $library->branchcode } ); # book_on_loan C4::Circulation::AddIssue( $patron, $item->barcode ); is( - @{$item->safe_to_delete->messages}[0]->message, + @{ $item->safe_to_delete->messages }[0]->message, 'book_on_loan', 'Koha::Item->safe_to_delete reports item on loan', ); is( - @{$item->safe_to_delete->messages}[0]->message, + @{ $item->safe_to_delete->messages }[0]->message, 'book_on_loan', 'item that is on loan cannot be deleted', ); ok( - ! $item->safe_to_delete, + !$item->safe_to_delete, 'Koha::Item->safe_to_delete shows item NOT safe to delete' ); AddReturn( $item->barcode, $library->branchcode ); # not_same_branch - t::lib::Mocks::mock_preference('IndependentBranches', 1); - my $item_2 = $builder->build_sample_item({ library => $library_2->branchcode }); + t::lib::Mocks::mock_preference( 'IndependentBranches', 1 ); + my $item_2 = $builder->build_sample_item( { library => $library_2->branchcode } ); is( - @{$item_2->safe_to_delete->messages}[0]->message, + @{ $item_2->safe_to_delete->messages }[0]->message, 'not_same_branch', 'Koha::Item->safe_to_delete reports IndependentBranches restriction', ); is( - @{$item_2->safe_to_delete->messages}[0]->message, + @{ $item_2->safe_to_delete->messages }[0]->message, 'not_same_branch', 'IndependentBranches prevents deletion at another branch', ); # linked_analytics - { # codeblock to limit scope of $module->mock + { # codeblock to limit scope of $module->mock my $module = Test::MockModule->new('C4::Items'); $module->mock( GetAnalyticsCount => sub { return 1 } ); $item->discard_changes; is( - @{$item->safe_to_delete->messages}[0]->message, + @{ $item->safe_to_delete->messages }[0]->message, 'linked_analytics', 'Koha::Item->safe_to_delete reports linked analytics', ); is( - @{$item->safe_to_delete->messages}[0]->message, + @{ $item->safe_to_delete->messages }[0]->message, 'linked_analytics', 'Linked analytics prevents deletion of item', ); @@ -1074,9 +1116,10 @@ subtest 'deletion' => sub { $item->safe_delete, - my $test_item = Koha::Items->find( $item->itemnumber ); + my $test_item = Koha::Items->find( $item->itemnumber ); - is( $test_item, undef, + is( + $test_item, undef, "Koha::Item->safe_delete should delete item if safe_to_delete returns true" ); @@ -1091,7 +1134,8 @@ subtest 'deletion' => sub { my $item = $builder->build_sample_item; - my $processing = $builder->build_object( { class => 'Koha::Holds', value => { itemnumber => $item->id, itemnumber => $item->id, found => 'P' } } ); + my $processing = $builder->build_object( + { class => 'Koha::Holds', value => { itemnumber => $item->id, itemnumber => $item->id, found => 'P' } } ); my $safe_to_delete = $item->safe_to_delete; ok( !$safe_to_delete, 'Cannot delete' ); @@ -1103,7 +1147,8 @@ subtest 'deletion' => sub { $processing->delete; - my $in_transit = $builder->build_object( { class => 'Koha::Holds', value => { itemnumber => $item->id, itemnumber => $item->id, found => 'T' } } ); + my $in_transit = $builder->build_object( + { class => 'Koha::Holds', value => { itemnumber => $item->id, itemnumber => $item->id, found => 'T' } } ); $safe_to_delete = $item->safe_to_delete; ok( !$safe_to_delete, 'Cannot delete' ); @@ -1115,7 +1160,8 @@ subtest 'deletion' => sub { $in_transit->delete; - my $waiting = $builder->build_object( { class => 'Koha::Holds', value => { itemnumber => $item->id, itemnumber => $item->id, found => 'W' } } ); + my $waiting = $builder->build_object( + { class => 'Koha::Holds', value => { itemnumber => $item->id, itemnumber => $item->id, found => 'W' } } ); $safe_to_delete = $item->safe_to_delete; ok( !$safe_to_delete, 'Cannot delete' ); @@ -1128,19 +1174,24 @@ subtest 'deletion' => sub { $waiting->delete; # Add am unfilled biblio-level hold to catch the 'last_item_for_hold' use case - $builder->build_object( { class => 'Koha::Holds', value => { biblionumber => $item->biblionumber, itemnumber => undef, found => undef } } ); + $builder->build_object( + { + class => 'Koha::Holds', + value => { biblionumber => $item->biblionumber, itemnumber => undef, found => undef } + } + ); $safe_to_delete = $item->safe_to_delete; ok( !$safe_to_delete ); is( - @{ $safe_to_delete->messages}[0]->message, + @{ $safe_to_delete->messages }[0]->message, 'last_item_for_hold', 'Item cannot be deleted if a biblio-level is placed on the biblio and there is only 1 item attached to the biblio' ); - my $extra_item = $builder->build_sample_item({ biblionumber => $item->biblionumber }); + my $extra_item = $builder->build_sample_item( { biblionumber => $item->biblionumber } ); ok( $item->safe_to_delete ); @@ -1293,9 +1344,9 @@ subtest 'Tests for itemtype|item_type' => sub { plan tests => 4; $schema->storage->txn_begin; - my $biblio = $builder->build_sample_biblio; - my $itemtype = $builder->build_object({ class => 'Koha::ItemTypes' }); - my $item = $builder->build_sample_item({ biblionumber => $biblio->biblionumber, itype => $itemtype->itemtype }); + my $biblio = $builder->build_sample_biblio; + my $itemtype = $builder->build_object( { class => 'Koha::ItemTypes' } ); + my $item = $builder->build_sample_item( { biblionumber => $biblio->biblionumber, itype => $itemtype->itemtype } ); t::lib::Mocks::mock_preference( 'item-level_itypes', 1 ); is( $item->itemtype->itemtype, $item->itype, 'Pref enabled' ); @@ -1463,8 +1514,11 @@ subtest 'get_transfers' => sub { my $item = $builder->build_sample_item(); my $transfers = $item->get_transfers(); - is(ref($transfers), 'Koha::Item::Transfers', 'Koha::Item->get_transfer should return a Koha::Item::Transfers object' ); - is($transfers->count, 0, 'When no transfers exist, the Koha::Item:Transfers object should be empty'); + is( + ref($transfers), 'Koha::Item::Transfers', + 'Koha::Item->get_transfer should return a Koha::Item::Transfers object' + ); + is( $transfers->count, 0, 'When no transfers exist, the Koha::Item:Transfers object should be empty' ); my $library_to = $builder->build_object( { class => 'Koha::Libraries' } ); @@ -1485,7 +1539,10 @@ subtest 'get_transfers' => sub { ); $transfers = $item->get_transfers(); - is($transfers->count, 1, 'When one transfer has been requested, the Koha::Item:Transfers object should contain one result'); + is( + $transfers->count, 1, + 'When one transfer has been requested, the Koha::Item:Transfers object should contain one result' + ); my $transfer_2 = $builder->build_object( { @@ -1520,37 +1577,70 @@ subtest 'get_transfers' => sub { ); $transfers = $item->get_transfers(); - is($transfers->count, 3, 'When there are multiple open transfer requests, the Koha::Item::Transfers object contains them all'); + is( + $transfers->count, 3, + 'When there are multiple open transfer requests, the Koha::Item::Transfers object contains them all' + ); my $result_1 = $transfers->next; my $result_2 = $transfers->next; my $result_3 = $transfers->next; - is( $result_1->branchtransfer_id, $transfer_1->branchtransfer_id, 'Koha::Item->get_transfers returns the oldest transfer request first'); - is( $result_2->branchtransfer_id, $transfer_2->branchtransfer_id, 'Koha::Item->get_transfers returns the newer transfer request second'); - is( $result_3->branchtransfer_id, $transfer_3->branchtransfer_id, 'Koha::Item->get_transfers returns the newest transfer request last'); + is( + $result_1->branchtransfer_id, $transfer_1->branchtransfer_id, + 'Koha::Item->get_transfers returns the oldest transfer request first' + ); + is( + $result_2->branchtransfer_id, $transfer_2->branchtransfer_id, + 'Koha::Item->get_transfers returns the newer transfer request second' + ); + is( + $result_3->branchtransfer_id, $transfer_3->branchtransfer_id, + 'Koha::Item->get_transfers returns the newest transfer request last' + ); - $transfer_2->datesent(\'NOW()')->store; + $transfer_2->datesent( \'NOW()' )->store; $transfers = $item->get_transfers(); - is($transfers->count, 3, 'When one transfer is set to in_transit, the Koha::Item::Transfers object still contains them all'); + is( + $transfers->count, 3, + 'When one transfer is set to in_transit, the Koha::Item::Transfers object still contains them all' + ); $result_1 = $transfers->next; $result_2 = $transfers->next; $result_3 = $transfers->next; - is( $result_1->branchtransfer_id, $transfer_2->branchtransfer_id, 'Koha::Item->get_transfers returns the active transfer request first'); - is( $result_2->branchtransfer_id, $transfer_1->branchtransfer_id, 'Koha::Item->get_transfers returns the other transfers oldest to newest'); - is( $result_3->branchtransfer_id, $transfer_3->branchtransfer_id, 'Koha::Item->get_transfers returns the other transfers oldest to newest'); + is( + $result_1->branchtransfer_id, $transfer_2->branchtransfer_id, + 'Koha::Item->get_transfers returns the active transfer request first' + ); + is( + $result_2->branchtransfer_id, $transfer_1->branchtransfer_id, + 'Koha::Item->get_transfers returns the other transfers oldest to newest' + ); + is( + $result_3->branchtransfer_id, $transfer_3->branchtransfer_id, + 'Koha::Item->get_transfers returns the other transfers oldest to newest' + ); - $transfer_2->datearrived(\'NOW()')->store; + $transfer_2->datearrived( \'NOW()' )->store; $transfers = $item->get_transfers(); - is($transfers->count, 2, 'Once a transfer is received, it no longer appears in the list from ->get_transfers()'); + is( $transfers->count, 2, 'Once a transfer is received, it no longer appears in the list from ->get_transfers()' ); $result_1 = $transfers->next; $result_2 = $transfers->next; - is( $result_1->branchtransfer_id, $transfer_1->branchtransfer_id, 'Koha::Item->get_transfers returns the other transfers oldest to newest'); - is( $result_2->branchtransfer_id, $transfer_3->branchtransfer_id, 'Koha::Item->get_transfers returns the other transfers oldest to newest'); + is( + $result_1->branchtransfer_id, $transfer_1->branchtransfer_id, + 'Koha::Item->get_transfers returns the other transfers oldest to newest' + ); + is( + $result_2->branchtransfer_id, $transfer_3->branchtransfer_id, + 'Koha::Item->get_transfers returns the other transfers oldest to newest' + ); - $transfer_1->datecancelled(\'NOW()')->store; + $transfer_1->datecancelled( \'NOW()' )->store; $transfers = $item->get_transfers(); - is($transfers->count, 1, 'Once a transfer is cancelled, it no longer appears in the list from ->get_transfers()'); + is( $transfers->count, 1, 'Once a transfer is cancelled, it no longer appears in the list from ->get_transfers()' ); $result_1 = $transfers->next; - is( $result_1->branchtransfer_id, $transfer_3->branchtransfer_id, 'Koha::Item->get_transfers returns the only transfer that remains'); + is( + $result_1->branchtransfer_id, $transfer_3->branchtransfer_id, + 'Koha::Item->get_transfers returns the only transfer that remains' + ); subtest "Ensure prefetches don't affect the return order" => sub { plan tests => 13; @@ -1726,37 +1816,43 @@ subtest 'Tests for relationship between item and item_orders via aqorders_item' $schema->storage->txn_begin; my $biblio = $builder->build_sample_biblio(); - my $item = $builder->build_sample_item({ biblionumber => $biblio->biblionumber }); + my $item = $builder->build_sample_item( { biblionumber => $biblio->biblionumber } ); my $orders = $item->orders; - is ($orders->count, 0, 'No order on this item yet'); + is( $orders->count, 0, 'No order on this item yet' ); my $order_note = 'Order for ' . $item->itemnumber; - my $aq_order1 = $builder->build_object({ - class => 'Koha::Acquisition::Orders', - value => { - biblionumber => $biblio->biblionumber, - order_internalnote => $order_note, - }, - }); - my $aq_order2 = $builder->build_object({ - class => 'Koha::Acquisition::Orders', - value => { - biblionumber => $biblio->biblionumber, - }, - }); - my $aq_order_item1 = $builder->build({ - source => 'AqordersItem', - value => { - ordernumber => $aq_order1->ordernumber, - itemnumber => $item->itemnumber, - }, - }); + my $aq_order1 = $builder->build_object( + { + class => 'Koha::Acquisition::Orders', + value => { + biblionumber => $biblio->biblionumber, + order_internalnote => $order_note, + }, + } + ); + my $aq_order2 = $builder->build_object( + { + class => 'Koha::Acquisition::Orders', + value => { + biblionumber => $biblio->biblionumber, + }, + } + ); + my $aq_order_item1 = $builder->build( + { + source => 'AqordersItem', + value => { + ordernumber => $aq_order1->ordernumber, + itemnumber => $item->itemnumber, + }, + } + ); $orders = $item->orders; - is ($orders->count, 1, 'One order found by item with the relationship'); - is ($orders->next->order_internalnote, $order_note, 'Correct order found by item with the relationship'); + is( $orders->count, 1, 'One order found by item with the relationship' ); + is( $orders->next->order_internalnote, $order_note, 'Correct order found by item with the relationship' ); }; subtest 'move_to_biblio() tests' => sub { @@ -1772,168 +1868,235 @@ subtest 'move_to_biblio() tests' => sub { my $source_biblionumber = $source_biblio->biblionumber; my $target_biblionumber = $target_biblio->biblionumber; - my $item1 = $builder->build_sample_item({ biblionumber => $source_biblionumber }); - my $item2 = $builder->build_sample_item({ biblionumber => $source_biblionumber }); - my $item3 = $builder->build_sample_item({ biblionumber => $source_biblionumber }); + my $item1 = $builder->build_sample_item( { biblionumber => $source_biblionumber } ); + my $item2 = $builder->build_sample_item( { biblionumber => $source_biblionumber } ); + my $item3 = $builder->build_sample_item( { biblionumber => $source_biblionumber } ); my $itemnumber1 = $item1->itemnumber; my $itemnumber2 = $item2->itemnumber; - my $library = $builder->build_object({ class => 'Koha::Libraries' }); + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); - my $patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { branchcode => $library->branchcode } - }); + my $patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { branchcode => $library->branchcode } + } + ); my $borrowernumber = $patron->borrowernumber; - my $aq_budget = $builder->build({ - source => 'Aqbudget', - value => { - budget_notes => 'test', - }, - }); + my $aq_budget = $builder->build( + { + source => 'Aqbudget', + value => { + budget_notes => 'test', + }, + } + ); - my $aq_order1 = $builder->build_object({ - class => 'Koha::Acquisition::Orders', - value => { - biblionumber => $source_biblionumber, - budget_id => $aq_budget->{budget_id}, - }, - }); - my $aq_order_item1 = $builder->build({ - source => 'AqordersItem', - value => { - ordernumber => $aq_order1->ordernumber, - itemnumber => $itemnumber1, - }, - }); - my $aq_order2 = $builder->build_object({ - class => 'Koha::Acquisition::Orders', - value => { - biblionumber => $source_biblionumber, - budget_id => $aq_budget->{budget_id}, - }, - }); - my $aq_order_item2 = $builder->build({ - source => 'AqordersItem', - value => { - ordernumber => $aq_order2->ordernumber, - itemnumber => $itemnumber2, - }, - }); + my $aq_order1 = $builder->build_object( + { + class => 'Koha::Acquisition::Orders', + value => { + biblionumber => $source_biblionumber, + budget_id => $aq_budget->{budget_id}, + }, + } + ); + my $aq_order_item1 = $builder->build( + { + source => 'AqordersItem', + value => { + ordernumber => $aq_order1->ordernumber, + itemnumber => $itemnumber1, + }, + } + ); + my $aq_order2 = $builder->build_object( + { + class => 'Koha::Acquisition::Orders', + value => { + biblionumber => $source_biblionumber, + budget_id => $aq_budget->{budget_id}, + }, + } + ); + my $aq_order_item2 = $builder->build( + { + source => 'AqordersItem', + value => { + ordernumber => $aq_order2->ordernumber, + itemnumber => $itemnumber2, + }, + } + ); - my $bib_level_hold = $builder->build_object({ - class => 'Koha::Holds', - value => { - biblionumber => $source_biblionumber, - itemnumber => undef, - }, - }); - my $item_level_hold1 = $builder->build_object({ - class => 'Koha::Holds', - value => { - biblionumber => $source_biblionumber, - itemnumber => $itemnumber1, - }, - }); - my $item_level_hold2 = $builder->build_object({ - class => 'Koha::Holds', - value => { - biblionumber => $source_biblionumber, - itemnumber => $itemnumber2, + my $bib_level_hold = $builder->build_object( + { + class => 'Koha::Holds', + value => { + biblionumber => $source_biblionumber, + itemnumber => undef, + }, } - }); + ); + my $item_level_hold1 = $builder->build_object( + { + class => 'Koha::Holds', + value => { + biblionumber => $source_biblionumber, + itemnumber => $itemnumber1, + }, + } + ); + my $item_level_hold2 = $builder->build_object( + { + class => 'Koha::Holds', + value => { + biblionumber => $source_biblionumber, + itemnumber => $itemnumber2, + } + } + ); - my $tmp_holdsqueue1 = $builder->build({ - source => 'TmpHoldsqueue', - value => { - borrowernumber => $borrowernumber, - biblionumber => $source_biblionumber, - itemnumber => $itemnumber1, + my $tmp_holdsqueue1 = $builder->build( + { + source => 'TmpHoldsqueue', + value => { + borrowernumber => $borrowernumber, + biblionumber => $source_biblionumber, + itemnumber => $itemnumber1, + } } - }); - my $tmp_holdsqueue2 = $builder->build({ - source => 'TmpHoldsqueue', - value => { - borrowernumber => $borrowernumber, - biblionumber => $source_biblionumber, - itemnumber => $itemnumber2, + ); + my $tmp_holdsqueue2 = $builder->build( + { + source => 'TmpHoldsqueue', + value => { + borrowernumber => $borrowernumber, + biblionumber => $source_biblionumber, + itemnumber => $itemnumber2, + } } - }); - my $hold_fill_target1 = $builder->build({ - source => 'HoldFillTarget', - value => { - borrowernumber => $borrowernumber, - biblionumber => $source_biblionumber, - itemnumber => $itemnumber1, + ); + my $hold_fill_target1 = $builder->build( + { + source => 'HoldFillTarget', + value => { + borrowernumber => $borrowernumber, + biblionumber => $source_biblionumber, + itemnumber => $itemnumber1, + } } - }); - my $hold_fill_target2 = $builder->build({ - source => 'HoldFillTarget', - value => { - borrowernumber => $borrowernumber, - biblionumber => $source_biblionumber, - itemnumber => $itemnumber2, + ); + my $hold_fill_target2 = $builder->build( + { + source => 'HoldFillTarget', + value => { + borrowernumber => $borrowernumber, + biblionumber => $source_biblionumber, + itemnumber => $itemnumber2, + } } - }); - my $linktracker1 = $builder->build({ - source => 'Linktracker', - value => { - borrowernumber => $borrowernumber, - biblionumber => $source_biblionumber, - itemnumber => $itemnumber1, + ); + my $linktracker1 = $builder->build( + { + source => 'Linktracker', + value => { + borrowernumber => $borrowernumber, + biblionumber => $source_biblionumber, + itemnumber => $itemnumber1, + } } - }); - my $linktracker2 = $builder->build({ - source => 'Linktracker', - value => { - borrowernumber => $borrowernumber, - biblionumber => $source_biblionumber, - itemnumber => $itemnumber2, + ); + my $linktracker2 = $builder->build( + { + source => 'Linktracker', + value => { + borrowernumber => $borrowernumber, + biblionumber => $source_biblionumber, + itemnumber => $itemnumber2, + } } - }); + ); my $to_biblionumber_after_move = $item1->move_to_biblio($target_biblio); - is($to_biblionumber_after_move, $target_biblionumber, 'move_to_biblio returns the target biblionumber if success'); + is( + $to_biblionumber_after_move, $target_biblionumber, + 'move_to_biblio returns the target biblionumber if success' + ); $to_biblionumber_after_move = $item1->move_to_biblio($target_biblio); - is($to_biblionumber_after_move, undef, 'move_to_biblio returns undef if the move has failed. If called twice, the item is not attached to the first biblio anymore'); + is( + $to_biblionumber_after_move, undef, + 'move_to_biblio returns undef if the move has failed. If called twice, the item is not attached to the first biblio anymore' + ); my $get_item1 = Koha::Items->find( $item1->itemnumber ); - is($get_item1->biblionumber, $target_biblionumber, 'item1 is moved'); + is( $get_item1->biblionumber, $target_biblionumber, 'item1 is moved' ); my $get_item2 = Koha::Items->find( $item2->itemnumber ); - is($get_item2->biblionumber, $source_biblionumber, 'item2 is not moved'); + is( $get_item2->biblionumber, $source_biblionumber, 'item2 is not moved' ); my $get_item3 = Koha::Items->find( $item3->itemnumber ); - is($get_item3->biblionumber, $source_biblionumber, 'item3 is not moved'); + is( $get_item3->biblionumber, $source_biblionumber, 'item3 is not moved' ); $aq_order1->discard_changes; $aq_order2->discard_changes; - is($aq_order1->biblionumber, $target_biblionumber, 'move_to_biblio moves aq_orders for item 1'); - is($aq_order2->biblionumber, $source_biblionumber, 'move_to_biblio does not move aq_orders for item 2'); + is( $aq_order1->biblionumber, $target_biblionumber, 'move_to_biblio moves aq_orders for item 1' ); + is( $aq_order2->biblionumber, $source_biblionumber, 'move_to_biblio does not move aq_orders for item 2' ); $bib_level_hold->discard_changes; $item_level_hold1->discard_changes; $item_level_hold2->discard_changes; - is($bib_level_hold->biblionumber, $source_biblionumber, 'move_to_biblio does not move the biblio-level hold'); - is($item_level_hold1->biblionumber, $target_biblionumber, 'move_to_biblio moves the item-level hold placed on item 1'); - is($item_level_hold2->biblionumber, $source_biblionumber, 'move_to_biblio does not move the item-level hold placed on item 2'); + is( $bib_level_hold->biblionumber, $source_biblionumber, 'move_to_biblio does not move the biblio-level hold' ); + is( + $item_level_hold1->biblionumber, $target_biblionumber, + 'move_to_biblio moves the item-level hold placed on item 1' + ); + is( + $item_level_hold2->biblionumber, $source_biblionumber, + 'move_to_biblio does not move the item-level hold placed on item 2' + ); - my $get_tmp_holdsqueue1 = $schema->resultset('TmpHoldsqueue')->search({ itemnumber => $tmp_holdsqueue1->{itemnumber} })->single; - my $get_tmp_holdsqueue2 = $schema->resultset('TmpHoldsqueue')->search({ itemnumber => $tmp_holdsqueue2->{itemnumber} })->single; - is($get_tmp_holdsqueue1->biblionumber->biblionumber, $target_biblionumber, 'move_to_biblio moves tmp_holdsqueue for item 1'); - is($get_tmp_holdsqueue2->biblionumber->biblionumber, $source_biblionumber, 'move_to_biblio does not move tmp_holdsqueue for item 2'); + my $get_tmp_holdsqueue1 = + $schema->resultset('TmpHoldsqueue')->search( { itemnumber => $tmp_holdsqueue1->{itemnumber} } )->single; + my $get_tmp_holdsqueue2 = + $schema->resultset('TmpHoldsqueue')->search( { itemnumber => $tmp_holdsqueue2->{itemnumber} } )->single; + is( + $get_tmp_holdsqueue1->biblionumber->biblionumber, $target_biblionumber, + 'move_to_biblio moves tmp_holdsqueue for item 1' + ); + is( + $get_tmp_holdsqueue2->biblionumber->biblionumber, $source_biblionumber, + 'move_to_biblio does not move tmp_holdsqueue for item 2' + ); + + my $get_hold_fill_target1 = + $schema->resultset('HoldFillTarget')->search( { itemnumber => $hold_fill_target1->{itemnumber} } )->single; + my $get_hold_fill_target2 = + $schema->resultset('HoldFillTarget')->search( { itemnumber => $hold_fill_target2->{itemnumber} } )->single; - my $get_hold_fill_target1 = $schema->resultset('HoldFillTarget')->search({ itemnumber => $hold_fill_target1->{itemnumber} })->single; - my $get_hold_fill_target2 = $schema->resultset('HoldFillTarget')->search({ itemnumber => $hold_fill_target2->{itemnumber} })->single; # Why does ->biblionumber return a Biblio object??? - is($get_hold_fill_target1->biblionumber->biblionumber, $target_biblionumber, 'move_to_biblio moves hold_fill_targets for item 1'); - is($get_hold_fill_target2->biblionumber->biblionumber, $source_biblionumber, 'move_to_biblio does not move hold_fill_targets for item 2'); + is( + $get_hold_fill_target1->biblionumber->biblionumber, $target_biblionumber, + 'move_to_biblio moves hold_fill_targets for item 1' + ); + is( + $get_hold_fill_target2->biblionumber->biblionumber, $source_biblionumber, + 'move_to_biblio does not move hold_fill_targets for item 2' + ); - my $get_linktracker1 = $schema->resultset('Linktracker')->search({ itemnumber => $linktracker1->{itemnumber} })->single; - my $get_linktracker2 = $schema->resultset('Linktracker')->search({ itemnumber => $linktracker2->{itemnumber} })->single; - is($get_linktracker1->biblionumber->biblionumber, $target_biblionumber, 'move_to_biblio moves linktracker for item 1'); - is($get_linktracker2->biblionumber->biblionumber, $source_biblionumber, 'move_to_biblio does not move linktracker for item 2'); + my $get_linktracker1 = + $schema->resultset('Linktracker')->search( { itemnumber => $linktracker1->{itemnumber} } )->single; + my $get_linktracker2 = + $schema->resultset('Linktracker')->search( { itemnumber => $linktracker2->{itemnumber} } )->single; + is( + $get_linktracker1->biblionumber->biblionumber, $target_biblionumber, + 'move_to_biblio moves linktracker for item 1' + ); + is( + $get_linktracker2->biblionumber->biblionumber, $source_biblionumber, + 'move_to_biblio does not move linktracker for item 2' + ); $schema->storage->txn_rollback; }; @@ -1943,7 +2106,7 @@ subtest 'columns_to_str' => sub { $schema->storage->txn_begin; - my ( $itemtag, $itemsubfield ) = C4::Biblio::GetMarcFromKohaField( "items.itemnumber" ); + my ( $itemtag, $itemsubfield ) = C4::Biblio::GetMarcFromKohaField("items.itemnumber"); my $cache = Koha::Caches->get_instance(); $cache->clear_from_cache("MarcStructure-0-"); @@ -1958,8 +2121,8 @@ subtest 'columns_to_str' => sub { Koha::MarcSubfieldStructures->search( { frameworkcode => '', - tagfield => $itemtag, - tagsubfield => ['é', 'è'], + tagfield => $itemtag, + tagsubfield => [ 'é', 'è' ], } )->delete; # In case it exist already @@ -1989,12 +2152,13 @@ subtest 'columns_to_str' => sub { } )->store; - my $biblio = $builder->build_sample_biblio({ frameworkcode => '' }); - my $item = $builder->build_sample_item({ biblionumber => $biblio->biblionumber }); - my $lost_av = $builder->build_object({ class => 'Koha::AuthorisedValues', value => { category => 'LOST', authorised_value => '42' }}); + my $biblio = $builder->build_sample_biblio( { frameworkcode => '' } ); + my $item = $builder->build_sample_item( { biblionumber => $biblio->biblionumber } ); + my $lost_av = $builder->build_object( + { class => 'Koha::AuthorisedValues', value => { category => 'LOST', authorised_value => '42' } } ); my $dateaccessioned = '2020-12-15'; - my $library = Koha::Libraries->search->next; - my $branchcode = $library->branchcode; + my $library = Koha::Libraries->search->next; + my $branchcode = $library->branchcode; my $some_marc_xml = qq{<?xml version="1.0" encoding="UTF-8"?> <collection @@ -2025,10 +2189,10 @@ subtest 'columns_to_str' => sub { $item = $item->get_from_storage; my $s = $item->columns_to_str; - is( $s->{itemlost}, $lost_av->lib, 'Attributes linked with AV replaced with description' ); - is( $s->{dateaccessioned}, '2020-12-15', 'Date attributes iso formatted'); - is( $s->{'é'}, 'value é', 'subfield ok with more than a-Z'); - is( $s->{'è'}, $library->branchname ); + is( $s->{itemlost}, $lost_av->lib, 'Attributes linked with AV replaced with description' ); + is( $s->{dateaccessioned}, '2020-12-15', 'Date attributes iso formatted' ); + is( $s->{'é'}, 'value é', 'subfield ok with more than a-Z' ); + is( $s->{'è'}, $library->branchname ); $cache->clear_from_cache("MarcStructure-0-"); $cache->clear_from_cache("MarcStructure-1-"); @@ -2155,7 +2319,8 @@ subtest 'strings_map() tests' => sub { } ); - my $class_sort_rule = $builder->build_object( { class => 'Koha::ClassSortRules', value => { sort_routine => 'Generic' } } ); + my $class_sort_rule = + $builder->build_object( { class => 'Koha::ClassSortRules', value => { sort_routine => 'Generic' } } ); my $class_split_rule = $builder->build_object( { class => 'Koha::ClassSplitRules' } ); my $class_source = $builder->build_object( { @@ -2202,8 +2367,8 @@ subtest 'strings_map() tests' => sub { plan tests => 3; ok( exists $strings->{cn_source}, "'cn_source' entry exists" ); - is( $strings->{cn_source}->{str}, $class_source->description, "'str' set to \$class_source->description" ); - is( $strings->{cn_source}->{type}, 'call_number_source', "type is 'library'" ); + is( $strings->{cn_source}->{str}, $class_source->description, "'str' set to \$class_source->description" ); + is( $strings->{cn_source}->{type}, 'call_number_source', "type is 'library'" ); }; subtest 'branches handling' => sub { @@ -2261,7 +2426,7 @@ subtest 'store() tests' => sub { ok( defined $item->dateaccessioned, 'dateaccessioned is set' ); # reset dateaccessioned on the DB - $schema->resultset('Item')->find({ itemnumber => $item->id })->update({ dateaccessioned => undef }); + $schema->resultset('Item')->find( { itemnumber => $item->id } )->update( { dateaccessioned => undef } ); $item->discard_changes; ok( !defined $item->dateaccessioned ); @@ -2280,8 +2445,8 @@ subtest 'store() tests' => sub { $schema->storage->txn_begin; - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); - my $item = $builder->build_sample_item({ itemlost => 1, itemlost_on => dt_from_string() }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + my $item = $builder->build_sample_item( { itemlost => 1, itemlost_on => dt_from_string() } ); # Add a lost item debit my $debit = $patron->account->add_debit( @@ -2347,11 +2512,14 @@ subtest 'store() tests' => sub { ); # Let's build a new item - $item = $builder->build_sample_item({ itemlost => 1, itemlost_on => dt_from_string() }); + $item = $builder->build_sample_item( { itemlost => 1, itemlost_on => dt_from_string() } ); $item->set( { itemlost => 0 } )->store; $messages = $item->object_messages; - is( scalar @{$messages}, 0, 'This item has no history, no associated lost fines, presumed not lost by patron, no messages returned'); + is( + scalar @{$messages}, 0, + 'This item has no history, no associated lost fines, presumed not lost by patron, no messages returned' + ); # NoRefundOnLostFinesPaidAge t::lib::Mocks::mock_preference( 'NoRefundOnLostFinesPaidAge', 10 ); @@ -2415,26 +2583,30 @@ subtest 'store() tests' => sub { my $biblio = $builder->build_sample_biblio; my $mock = Test::MockModule->new('Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue'); - $mock->mock( 'enqueue', sub { - my ( $self, $args ) = @_; - is_deeply( - $args->{biblio_ids}, - [ $biblio->id ], - '->store triggers a holds queue update for the related biblio' - ); - } ); + $mock->mock( + 'enqueue', + sub { + my ( $self, $args ) = @_; + is_deeply( + $args->{biblio_ids}, + [ $biblio->id ], + '->store triggers a holds queue update for the related biblio' + ); + } + ); t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 1 ); # new item - my $item = $builder->build_sample_item({ biblionumber => $biblio->id }); + my $item = $builder->build_sample_item( { biblionumber => $biblio->id } ); # updated item - $item->set({ reserves => 1 })->store; + $item->set( { reserves => 1 } )->store; t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 0 ); + # updated item - $item->set({ reserves => 0 })->store; + $item->set( { reserves => 0 } )->store; $schema->storage->txn_rollback; }; @@ -2446,23 +2618,28 @@ subtest 'Recalls tests' => sub { $schema->storage->txn_begin; - my $item1 = $builder->build_sample_item; - my $biblio = $item1->biblio; + my $item1 = $builder->build_sample_item; + my $biblio = $item1->biblio; my $branchcode = $item1->holdingbranch; - my $patron1 = $builder->build_object({ class => 'Koha::Patrons', value => { branchcode => $branchcode } }); - my $patron2 = $builder->build_object({ class => 'Koha::Patrons', value => { branchcode => $branchcode } }); - my $patron3 = $builder->build_object({ class => 'Koha::Patrons', value => { branchcode => $branchcode } }); - my $item2 = $builder->build_object( - { class => 'Koha::Items', - value => { holdingbranch => $branchcode, homebranch => $branchcode, biblionumber => $biblio->biblionumber, itype => $item1->effective_itemtype } + my $patron1 = $builder->build_object( { class => 'Koha::Patrons', value => { branchcode => $branchcode } } ); + my $patron2 = $builder->build_object( { class => 'Koha::Patrons', value => { branchcode => $branchcode } } ); + my $patron3 = $builder->build_object( { class => 'Koha::Patrons', value => { branchcode => $branchcode } } ); + my $item2 = $builder->build_object( + { + class => 'Koha::Items', + value => { + holdingbranch => $branchcode, homebranch => $branchcode, biblionumber => $biblio->biblionumber, + itype => $item1->effective_itemtype + } } ); t::lib::Mocks::mock_userenv( { patron => $patron1 } ); - t::lib::Mocks::mock_preference('UseRecalls', 1); + t::lib::Mocks::mock_preference( 'UseRecalls', 1 ); my $recall1 = Koha::Recall->new( - { patron_id => $patron1->borrowernumber, + { + patron_id => $patron1->borrowernumber, created_date => \'NOW()', biblio_id => $biblio->biblionumber, pickup_library_id => $branchcode, @@ -2472,7 +2649,8 @@ subtest 'Recalls tests' => sub { } )->store; my $recall2 = Koha::Recall->new( - { patron_id => $patron2->borrowernumber, + { + patron_id => $patron2->borrowernumber, created_date => \'NOW()', biblio_id => $biblio->biblionumber, pickup_library_id => $branchcode, @@ -2487,75 +2665,104 @@ subtest 'Recalls tests' => sub { $recall2->set_cancelled; - t::lib::Mocks::mock_preference('UseRecalls', 0); - is( $item1->can_be_recalled({ patron => $patron1 }), 0, "Can't recall with UseRecalls disabled" ); + t::lib::Mocks::mock_preference( 'UseRecalls', 0 ); + is( $item1->can_be_recalled( { patron => $patron1 } ), 0, "Can't recall with UseRecalls disabled" ); - t::lib::Mocks::mock_preference("UseRecalls", 1); + t::lib::Mocks::mock_preference( "UseRecalls", 1 ); - $item1->update({ notforloan => 1 }); - is( $item1->can_be_recalled({ patron => $patron1 }), 0, "Can't recall that is not for loan" ); - $item1->update({ notforloan => 0, itemlost => 1 }); - is( $item1->can_be_recalled({ patron => $patron1 }), 0, "Can't recall that is marked lost" ); - $item1->update({ itemlost => 0, withdrawn => 1 }); - is( $item1->can_be_recalled({ patron => $patron1 }), 0, "Can't recall that is withdrawn" ); - is( $item1->can_be_recalled({ patron => $patron1 }), 0, "Can't recall item if not checked out" ); + $item1->update( { notforloan => 1 } ); + is( $item1->can_be_recalled( { patron => $patron1 } ), 0, "Can't recall that is not for loan" ); + $item1->update( { notforloan => 0, itemlost => 1 } ); + is( $item1->can_be_recalled( { patron => $patron1 } ), 0, "Can't recall that is marked lost" ); + $item1->update( { itemlost => 0, withdrawn => 1 } ); + is( $item1->can_be_recalled( { patron => $patron1 } ), 0, "Can't recall that is withdrawn" ); + is( $item1->can_be_recalled( { patron => $patron1 } ), 0, "Can't recall item if not checked out" ); - $item1->update({ withdrawn => 0 }); + $item1->update( { withdrawn => 0 } ); C4::Circulation::AddIssue( $patron2, $item1->barcode ); - Koha::CirculationRules->set_rules({ - branchcode => $branchcode, - categorycode => $patron1->categorycode, - itemtype => $item1->effective_itemtype, - rules => { - recalls_allowed => 0, - recalls_per_record => 1, - on_shelf_recalls => 'all', - }, - }); - is( $item1->can_be_recalled({ patron => $patron1 }), 0, "Can't recall if recalls_allowed = 0" ); + Koha::CirculationRules->set_rules( + { + branchcode => $branchcode, + categorycode => $patron1->categorycode, + itemtype => $item1->effective_itemtype, + rules => { + recalls_allowed => 0, + recalls_per_record => 1, + on_shelf_recalls => 'all', + }, + } + ); + is( $item1->can_be_recalled( { patron => $patron1 } ), 0, "Can't recall if recalls_allowed = 0" ); - Koha::CirculationRules->set_rules({ - branchcode => $branchcode, - categorycode => $patron1->categorycode, - itemtype => $item1->effective_itemtype, - rules => { - recalls_allowed => 1, - recalls_per_record => 1, - on_shelf_recalls => 'all', - }, - }); - is( $item1->can_be_recalled({ patron => $patron1 }), 0, "Can't recall if patron has more existing recall(s) than recalls_allowed" ); - is( $item1->can_be_recalled({ patron => $patron1 }), 0, "Can't recall if patron has more existing recall(s) than recalls_per_record" ); - is( $item1->can_be_recalled({ patron => $patron1 }), 0, "Can't recall if patron has already recalled this item" ); + Koha::CirculationRules->set_rules( + { + branchcode => $branchcode, + categorycode => $patron1->categorycode, + itemtype => $item1->effective_itemtype, + rules => { + recalls_allowed => 1, + recalls_per_record => 1, + on_shelf_recalls => 'all', + }, + } + ); + is( + $item1->can_be_recalled( { patron => $patron1 } ), 0, + "Can't recall if patron has more existing recall(s) than recalls_allowed" + ); + is( + $item1->can_be_recalled( { patron => $patron1 } ), 0, + "Can't recall if patron has more existing recall(s) than recalls_per_record" + ); + is( $item1->can_be_recalled( { patron => $patron1 } ), 0, "Can't recall if patron has already recalled this item" ); - my $reserve_id = C4::Reserves::AddReserve({ branchcode => $branchcode, borrowernumber => $patron1->borrowernumber, biblionumber => $item1->biblionumber, itemnumber => $item1->itemnumber }); - is( $item1->can_be_recalled({ patron => $patron1 }), 0, "Can't recall item if patron has already reserved it" ); - C4::Reserves::ModReserve({ rank => 'del', reserve_id => $reserve_id, branchcode => $branchcode, itemnumber => $item1->itemnumber, borrowernumber => $patron1->borrowernumber, biblionumber => $item1->biblionumber }); + my $reserve_id = C4::Reserves::AddReserve( + { + branchcode => $branchcode, borrowernumber => $patron1->borrowernumber, + biblionumber => $item1->biblionumber, itemnumber => $item1->itemnumber + } + ); + is( $item1->can_be_recalled( { patron => $patron1 } ), 0, "Can't recall item if patron has already reserved it" ); + C4::Reserves::ModReserve( + { + rank => 'del', reserve_id => $reserve_id, branchcode => $branchcode, itemnumber => $item1->itemnumber, + borrowernumber => $patron1->borrowernumber, biblionumber => $item1->biblionumber + } + ); $recall1->set_cancelled; - is( $item1->can_be_recalled({ patron => $patron2 }), 0, "Can't recall if patron has already checked out an item attached to this biblio" ); + is( + $item1->can_be_recalled( { patron => $patron2 } ), 0, + "Can't recall if patron has already checked out an item attached to this biblio" + ); - is( $item1->can_be_recalled({ patron => $patron1 }), 0, "Can't recall if on_shelf_recalls = all and items are still available" ); + is( + $item1->can_be_recalled( { patron => $patron1 } ), 0, + "Can't recall if on_shelf_recalls = all and items are still available" + ); - Koha::CirculationRules->set_rules({ - branchcode => $branchcode, - categorycode => $patron1->categorycode, - itemtype => $item1->effective_itemtype, - rules => { - recalls_allowed => 1, - recalls_per_record => 1, - on_shelf_recalls => 'any', - }, - }); + Koha::CirculationRules->set_rules( + { + branchcode => $branchcode, + categorycode => $patron1->categorycode, + itemtype => $item1->effective_itemtype, + rules => { + recalls_allowed => 1, + recalls_per_record => 1, + on_shelf_recalls => 'any', + }, + } + ); C4::Circulation::AddReturn( $item1->barcode, $branchcode ); - is( $item1->can_be_recalled({ patron => $patron1 }), 0, "Can't recall if no items are checked out" ); + is( $item1->can_be_recalled( { patron => $patron1 } ), 0, "Can't recall if no items are checked out" ); C4::Circulation::AddIssue( $patron2, $item1->barcode ); - is( $item1->can_be_recalled({ patron => $patron1 }), 1, "Can recall item" ); + is( $item1->can_be_recalled( { patron => $patron1 } ), 1, "Can recall item" ); $recall1 = Koha::Recall->new( - { patron_id => $patron1->borrowernumber, + { + patron_id => $patron1->borrowernumber, created_date => \'NOW()', biblio_id => $biblio->biblionumber, pickup_library_id => $branchcode, @@ -2567,34 +2774,39 @@ subtest 'Recalls tests' => sub { # Patron2 has Item1 checked out. Patron1 has placed a biblio-level recall on Biblio1, so check if Item1 can fulfill Patron1's recall. - Koha::CirculationRules->set_rules({ - branchcode => $branchcode, - categorycode => $patron1->categorycode, - itemtype => $item1->effective_itemtype, - rules => { - recalls_allowed => 0, - recalls_per_record => 1, - on_shelf_recalls => 'any', - }, - }); + Koha::CirculationRules->set_rules( + { + branchcode => $branchcode, + categorycode => $patron1->categorycode, + itemtype => $item1->effective_itemtype, + rules => { + recalls_allowed => 0, + recalls_per_record => 1, + on_shelf_recalls => 'any', + }, + } + ); is( $item1->can_be_waiting_recall, 0, "Recalls not allowed for this itemtype" ); - Koha::CirculationRules->set_rules({ - branchcode => $branchcode, - categorycode => $patron1->categorycode, - itemtype => $item1->effective_itemtype, - rules => { - recalls_allowed => 1, - recalls_per_record => 1, - on_shelf_recalls => 'any', - }, - }); + Koha::CirculationRules->set_rules( + { + branchcode => $branchcode, + categorycode => $patron1->categorycode, + itemtype => $item1->effective_itemtype, + rules => { + recalls_allowed => 1, + recalls_per_record => 1, + on_shelf_recalls => 'any', + }, + } + ); is( $item1->can_be_waiting_recall, 1, "Recalls are allowed for this itemtype" ); # check_recalls tests $recall1 = Koha::Recall->new( - { patron_id => $patron2->borrowernumber, + { + patron_id => $patron2->borrowernumber, created_date => \'NOW()', biblio_id => $biblio->biblionumber, pickup_library_id => $branchcode, @@ -2604,7 +2816,8 @@ subtest 'Recalls tests' => sub { } )->store; $recall2 = Koha::Recall->new( - { patron_id => $patron1->borrowernumber, + { + patron_id => $patron1->borrowernumber, created_date => \'NOW()', biblio_id => $biblio->biblionumber, pickup_library_id => $branchcode, @@ -2646,17 +2859,17 @@ subtest 'item_group() tests' => sub { $schema->storage->txn_begin; my $biblio = $builder->build_sample_biblio(); - my $item_1 = $builder->build_sample_item({ biblionumber => $biblio->biblionumber }); - my $item_2 = $builder->build_sample_item({ biblionumber => $biblio->biblionumber }); + my $item_1 = $builder->build_sample_item( { biblionumber => $biblio->biblionumber } ); + my $item_2 = $builder->build_sample_item( { biblionumber => $biblio->biblionumber } ); - is( $item_1->item_group, undef, 'Item 1 has no item group'); - is( $item_2->item_group, undef, 'Item 2 has no item group'); + is( $item_1->item_group, undef, 'Item 1 has no item group' ); + is( $item_2->item_group, undef, 'Item 2 has no item group' ); my $item_group_1 = Koha::Biblio::ItemGroup->new( { biblio_id => $biblio->id } )->store(); my $item_group_2 = Koha::Biblio::ItemGroup->new( { biblio_id => $biblio->id } )->store(); - $item_group_1->add_item({ item_id => $item_1->id }); - $item_group_2->add_item({ item_id => $item_2->id }); + $item_group_1->add_item( { item_id => $item_1->id } ); + $item_group_2->add_item( { item_id => $item_2->id } ); is( $item_1->item_group->id, $item_group_1->id, 'Got item group 1 correctly' ); is( $item_2->item_group->id, $item_group_2->id, 'Got item group 2 correctly' ); @@ -2670,16 +2883,16 @@ subtest 'has_pending_recall() tests' => sub { $schema->storage->txn_begin; - my $library = $builder->build_object({ class => 'Koha::Libraries' }); + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); my $item = $builder->build_sample_item; - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); - t::lib::Mocks::mock_userenv({ branchcode => $library->branchcode }); + t::lib::Mocks::mock_userenv( { branchcode => $library->branchcode } ); t::lib::Mocks::mock_preference( 'UseRecalls', 1 ); C4::Circulation::AddIssue( $patron, $item->barcode ); - my ($recall) = Koha::Recalls->add_recall({ biblio => $item->biblio, item => $item, patron => $patron }); + my ($recall) = Koha::Recalls->add_recall( { biblio => $item->biblio, item => $item, patron => $patron } ); ok( !$item->has_pending_recall, 'The item has no pending recalls' ); @@ -2695,59 +2908,67 @@ subtest 'is_denied_renewal' => sub { $schema->storage->txn_begin; - my $library = $builder->build_object({ class => 'Koha::Libraries'}); + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); - my $deny_book = $builder->build_object({ class => 'Koha::Items', value => { - homebranch => $library->branchcode, - withdrawn => 1, - itype => 'HIDE', - location => 'PROC', - itemcallnumber => undef, - itemnotes => "", + my $deny_book = $builder->build_object( + { + class => 'Koha::Items', + value => { + homebranch => $library->branchcode, + withdrawn => 1, + itype => 'HIDE', + location => 'PROC', + itemcallnumber => undef, + itemnotes => "", + } } - }); + ); - my $allow_book = $builder->build_object({ class => 'Koha::Items', value => { - homebranch => $library->branchcode, - withdrawn => 0, - itype => 'NOHIDE', - location => 'NOPROC' + my $allow_book = $builder->build_object( + { + class => 'Koha::Items', + value => { + homebranch => $library->branchcode, + withdrawn => 0, + itype => 'NOHIDE', + location => 'NOPROC' + } } - }); + ); my $idr_rules = ""; - C4::Context->set_preference('ItemsDeniedRenewal', $idr_rules); + C4::Context->set_preference( 'ItemsDeniedRenewal', $idr_rules ); is( $deny_book->is_denied_renewal, 0, 'Renewal allowed when no rules' ); # The wrong column delete should be silently ignored and not trigger item delete - $idr_rules="delete: [yes]\nwithdrawn: [1]"; - C4::Context->set_preference('ItemsDeniedRenewal', $idr_rules); - is( $deny_book->is_denied_renewal, 1, 'Renewal blocked when 1 rules (withdrawn)' ); + $idr_rules = "delete: [yes]\nwithdrawn: [1]"; + C4::Context->set_preference( 'ItemsDeniedRenewal', $idr_rules ); + is( $deny_book->is_denied_renewal, 1, 'Renewal blocked when 1 rules (withdrawn)' ); is( $allow_book->is_denied_renewal, 0, 'Renewal allowed when 1 rules not matched (withdrawn)' ); - $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]"; - is( $deny_book->is_denied_renewal, 1, 'Renewal blocked when 2 rules matched (withdrawn, itype)' ); + $idr_rules = "withdrawn: [1]\nitype: [HIDE,INVISIBLE]"; + is( $deny_book->is_denied_renewal, 1, 'Renewal blocked when 2 rules matched (withdrawn, itype)' ); is( $allow_book->is_denied_renewal, 0, 'Renewal allowed when 2 rules not matched (withdrawn, itype)' ); - $idr_rules="withdrawn: [1]\nitype: [HIDE,INVISIBLE]\nlocation: [PROC]"; - C4::Context->set_preference('ItemsDeniedRenewal', $idr_rules); - is( $deny_book->is_denied_renewal, 1, 'Renewal blocked when 3 rules matched (withdrawn, itype, location)' ); + $idr_rules = "withdrawn: [1]\nitype: [HIDE,INVISIBLE]\nlocation: [PROC]"; + C4::Context->set_preference( 'ItemsDeniedRenewal', $idr_rules ); + is( $deny_book->is_denied_renewal, 1, 'Renewal blocked when 3 rules matched (withdrawn, itype, location)' ); is( $allow_book->is_denied_renewal, 0, 'Renewal allowed when 3 rules not matched (withdrawn, itype, location)' ); - $idr_rules="itemcallnumber: [null]"; - C4::Context->set_preference('ItemsDeniedRenewal', $idr_rules); + $idr_rules = "itemcallnumber: [null]"; + C4::Context->set_preference( 'ItemsDeniedRenewal', $idr_rules ); is( $deny_book->is_denied_renewal, 1, 'Renewal blocked for undef when null in pref' ); - $idr_rules="itemcallnumber: ['']"; - C4::Context->set_preference('ItemsDeniedRenewal', $idr_rules); + $idr_rules = "itemcallnumber: ['']"; + C4::Context->set_preference( 'ItemsDeniedRenewal', $idr_rules ); is( $deny_book->is_denied_renewal, 0, 'Renewal not blocked for undef when "" in pref' ); - $idr_rules="itemnotes: [null]"; - C4::Context->set_preference('ItemsDeniedRenewal', $idr_rules); + $idr_rules = "itemnotes: [null]"; + C4::Context->set_preference( 'ItemsDeniedRenewal', $idr_rules ); is( $deny_book->is_denied_renewal, 0, 'Renewal not blocked for "" when null in pref' ); - $idr_rules="itemnotes: ['']"; - C4::Context->set_preference('ItemsDeniedRenewal', $idr_rules); + $idr_rules = "itemnotes: ['']"; + C4::Context->set_preference( 'ItemsDeniedRenewal', $idr_rules ); is( $deny_book->is_denied_renewal, 1, 'Renewal blocked for empty string when "" in pref' ); $schema->storage->txn_rollback; @@ -2765,10 +2986,14 @@ subtest 'current_branchtransfers relationship' => sub { } ); my $transfers = $item->_result->current_branchtransfers; - is( ref($transfers), 'DBIx::Class::ResultSet', - 'current_branchtransfers returns a DBIx::Class::ResultSet' ); - is( $transfers->count, 0, - "Empty Koha::Item::Transfers set returned if no return_claims" ); + is( + ref($transfers), 'DBIx::Class::ResultSet', + 'current_branchtransfers returns a DBIx::Class::ResultSet' + ); + is( + $transfers->count, 0, + "Empty Koha::Item::Transfers set returned if no return_claims" + ); my $transfer1 = $builder->build( { source => 'Branchtransfer', @@ -2799,8 +3024,10 @@ subtest 'current_branchtransfers relationship' => sub { } ); - is( $item->_result->current_branchtransfers()->count, - 1, "One transfer found for item" ); + is( + $item->_result->current_branchtransfers()->count, + 1, "One transfer found for item" + ); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/Koha/Item/Attributes.t b/t/db_dependent/Koha/Item/Attributes.t index 3f7d8abf2d..c41c746363 100755 --- a/t/db_dependent/Koha/Item/Attributes.t +++ b/t/db_dependent/Koha/Item/Attributes.t @@ -16,7 +16,7 @@ # along with Koha; if not, see <http://www.gnu.org/licenses>. use Modern::Perl; -use Test::More tests=> 10; +use Test::More tests => 10; use utf8; use Koha::Database; @@ -32,8 +32,8 @@ my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; my $builder = t::lib::TestBuilder->new; -my $biblio = $builder->build_sample_biblio({ frameworkcode => '' }); -my $item = $builder->build_sample_item({ biblionumber => $biblio->biblionumber }); +my $biblio = $builder->build_sample_biblio( { frameworkcode => '' } ); +my $item = $builder->build_sample_item( { biblionumber => $biblio->biblionumber } ); my $cache = Koha::Caches->get_instance; $cache->clear_from_cache("MarcStructure-0-"); @@ -45,11 +45,11 @@ $cache->clear_from_cache("MarcSubfieldStructure-"); # $952$y is not repeatable setup_mss(); -$item->more_subfields_xml(undef)->store; # Shouldn't be needed, but we want to make sure +$item->more_subfields_xml(undef)->store; # Shouldn't be needed, but we want to make sure my $attributes = $item->additional_attributes; -is( ref($attributes), 'Koha::Item::Attributes' ); +is( ref($attributes), 'Koha::Item::Attributes' ); is( $attributes->to_marcxml, undef ); -is_deeply($attributes->to_hashref, {}); +is_deeply( $attributes->to_hashref, {} ); my $some_marc_xml = q{<?xml version="1.0" encoding="UTF-8"?> <collection @@ -74,11 +74,11 @@ my $some_marc_xml = q{<?xml version="1.0" encoding="UTF-8"?> $item->more_subfields_xml($some_marc_xml)->store; $attributes = $item->additional_attributes; -is( ref($attributes), 'Koha::Item::Attributes' ); -is( $attributes->{'x'}, "value for x 1 | value for x 2"); -is( $attributes->{'y'}, "value for y"); -is( $attributes->{'é'}, "value for é 1 | value for é 2"); -is( $attributes->{'z'}, "value for z 1 | value for z 2"); +is( ref($attributes), 'Koha::Item::Attributes' ); +is( $attributes->{'x'}, "value for x 1 | value for x 2" ); +is( $attributes->{'y'}, "value for y" ); +is( $attributes->{'é'}, "value for é 1 | value for é 2" ); +is( $attributes->{'z'}, "value for z 1 | value for z 2" ); is( $attributes->to_marcxml, $some_marc_xml ); is_deeply( @@ -91,17 +91,17 @@ is_deeply( } ); -Koha::Caches->get_instance->clear_from_cache( "MarcStructure-1-" ); +Koha::Caches->get_instance->clear_from_cache("MarcStructure-1-"); sub setup_mss { - my ( $itemtag, $itemsubfield ) = C4::Biblio::GetMarcFromKohaField( "items.itemnumber" ); + my ( $itemtag, $itemsubfield ) = C4::Biblio::GetMarcFromKohaField("items.itemnumber"); Koha::MarcSubfieldStructures->search( { frameworkcode => '', - tagfield => $itemtag, - tagsubfield => 'é', + tagfield => $itemtag, + tagsubfield => 'é', } )->delete; # In case it exist already @@ -127,24 +127,23 @@ sub setup_mss { Koha::MarcSubfieldStructures->search( { frameworkcode => '', - tagfield => $itemtag, - tagsubfield => [ 'x', 'é' ], + tagfield => $itemtag, + tagsubfield => [ 'x', 'é' ], } )->update( { repeatable => 1 } ); Koha::MarcSubfieldStructures->search( { frameworkcode => '', - tagfield => $itemtag, - tagsubfield => ['y'], + tagfield => $itemtag, + tagsubfield => ['y'], } )->update( { repeatable => 0 } ); my $i = 0; - for my $sf ( qw( x y é z ) ) { - Koha::MarcSubfieldStructures->search( - { frameworkcode => '', tagfield => $itemtag, tagsubfield => $sf } ) - ->update( { display_order => $i++ } ); + for my $sf (qw( x y é z )) { + Koha::MarcSubfieldStructures->search( { frameworkcode => '', tagfield => $itemtag, tagsubfield => $sf } ) + ->update( { display_order => $i++ } ); } } diff --git a/t/db_dependent/Koha/Item/Search/Field.t b/t/db_dependent/Koha/Item/Search/Field.t index 9e73880478..e98d232dd9 100755 --- a/t/db_dependent/Koha/Item/Search/Field.t +++ b/t/db_dependent/Koha/Item/Search/Field.t @@ -14,25 +14,34 @@ my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; # Start with empty table. -foreach my $field (GetItemSearchFields()) { - DelItemSearchField($field->{name}); +foreach my $field ( GetItemSearchFields() ) { + DelItemSearchField( $field->{name} ); } -is(scalar GetItemSearchFields(), 0, "No existing search field"); +is( scalar GetItemSearchFields(), 0, "No existing search field" ); # Missing keys in hashref parameter, so returns undef -ok(not (defined AddItemSearchField()), "missing keys => fail"); -ok(not (defined AddItemSearchField({})), "missing keys => fail"); -ok(not (defined AddItemSearchField({name => 'foo'})), "missing keys => fail"); -ok(not (defined AddItemSearchField({name => 'foo', label => 'Foo'})), "missing keys => fail"); +ok( not( defined AddItemSearchField() ), "missing keys => fail" ); +ok( not( defined AddItemSearchField( {} ) ), "missing keys => fail" ); +ok( not( defined AddItemSearchField( { name => 'foo' } ) ), "missing keys => fail" ); +ok( not( defined AddItemSearchField( { name => 'foo', label => 'Foo' } ) ), "missing keys => fail" ); # Success, the field hashref is returned -ok('HASH' eq ref AddItemSearchField({name => 'foo', label => 'Foo', tagfield => '001'}), "successful add"); +ok( 'HASH' eq ref AddItemSearchField( { name => 'foo', label => 'Foo', tagfield => '001' } ), "successful add" ); # Check the table now contains one row. -is(scalar GetItemSearchFields(), 1, "Table now contains one row"); +is( scalar GetItemSearchFields(), 1, "Table now contains one row" ); my $field = GetItemSearchField('foo'); -is_deeply($field, {name => 'foo', label => 'Foo', tagfield => '001', tagsubfield => undef, authorised_values_category => undef}); +is_deeply( + $field, + { name => 'foo', label => 'Foo', tagfield => '001', tagsubfield => undef, authorised_values_category => undef } +); -ok((defined ModItemSearchField({name => 'foo', label => 'Foobar', tagfield => '100', 'tagsubfield' => 'a'})), "successful mod"); +ok( + ( defined ModItemSearchField( { name => 'foo', label => 'Foobar', tagfield => '100', 'tagsubfield' => 'a' } ) ), + "successful mod" +); $field = GetItemSearchField('foo'); -is_deeply($field, {name => 'foo', label => 'Foobar', tagfield => '100', tagsubfield => 'a', authorised_values_category => undef}); +is_deeply( + $field, + { name => 'foo', label => 'Foobar', tagfield => '100', tagsubfield => 'a', authorised_values_category => undef } +); diff --git a/t/db_dependent/Koha/Item/Template.t b/t/db_dependent/Koha/Item/Template.t index 8174c2dd44..31f0a4384f 100755 --- a/t/db_dependent/Koha/Item/Template.t +++ b/t/db_dependent/Koha/Item/Template.t @@ -41,11 +41,12 @@ subtest 'Serializing and deserializing contents' => sub { my $data = { location => 'test', - cost => "2\x{20ac}", + cost => "2\x{20ac}", }; my $template = Koha::Item::Template->new( - { name => 'My template', + { + name => 'My template', contents => $data, } )->store(); diff --git a/t/db_dependent/Koha/Item/Templates.t b/t/db_dependent/Koha/Item/Templates.t index dca1e66511..acbd18bcf2 100755 --- a/t/db_dependent/Koha/Item/Templates.t +++ b/t/db_dependent/Koha/Item/Templates.t @@ -83,11 +83,11 @@ subtest 'get_available' => sub { is_shared => 0, } )->store; - $unshared_template->discard_changes; # refresh + $unshared_template->discard_changes; # refresh is( $unshared_template->decoded_contents->{location}, 'test🙂', 'Tested encoding/decoding' ); my $templates = Koha::Item::Templates->get_available( $patron_1->id ); - is( $templates->{owned}->count, 1, "Got back one owned template" ); + is( $templates->{owned}->count, 1, "Got back one owned template" ); is( $templates->{shared}->count, 1, "Got back one shared templated" ); $schema->storage->txn_rollback; diff --git a/t/db_dependent/Koha/Item/Transfer.t b/t/db_dependent/Koha/Item/Transfer.t index 2ac3462351..79af2f161d 100755 --- a/t/db_dependent/Koha/Item/Transfer.t +++ b/t/db_dependent/Koha/Item/Transfer.t @@ -46,7 +46,7 @@ subtest 'item relation tests' => sub { ); my $transfer_item = $transfer->item; - is( ref( $transfer_item ), 'Koha::Item', 'Koha::Item::Transfer->item should return a Koha::Item' ); + is( ref($transfer_item), 'Koha::Item', 'Koha::Item::Transfer->item should return a Koha::Item' ); is( $transfer_item->itemnumber, $item->itemnumber, 'Koha::Item::Transfer->item should return the correct item' ); $schema->storage->txn_rollback; @@ -57,7 +57,7 @@ subtest 'from_library relation tests' => sub { $schema->storage->txn_begin; - my $library = $builder->build_object( { class => 'Koha::Libraries' } ); + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); my $transfer = $builder->build_object( { class => 'Koha::Item::Transfers', @@ -68,8 +68,11 @@ subtest 'from_library relation tests' => sub { ); my $from_library = $transfer->from_library; - is( ref( $from_library ), 'Koha::Library', 'Koha::Item::Transfer->from_library should return a Koha::Library' ); - is( $from_library->branchcode, $library->branchcode, 'Koha::Item::Transfer->from_library should return the correct library' ); + is( ref($from_library), 'Koha::Library', 'Koha::Item::Transfer->from_library should return a Koha::Library' ); + is( + $from_library->branchcode, $library->branchcode, + 'Koha::Item::Transfer->from_library should return the correct library' + ); $schema->storage->txn_rollback; }; @@ -79,7 +82,7 @@ subtest 'to_library relation tests' => sub { $schema->storage->txn_begin; - my $library = $builder->build_object( { class => 'Koha::Libraries' } ); + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); my $transfer = $builder->build_object( { class => 'Koha::Item::Transfers', @@ -90,8 +93,11 @@ subtest 'to_library relation tests' => sub { ); my $to_library = $transfer->to_library; - is( ref( $to_library ), 'Koha::Library', 'Koha::Item::Transfer->to_library should return a Koha::Library' ); - is( $to_library->branchcode, $library->branchcode, 'Koha::Item::Transfer->to_library should return the correct library' ); + is( ref($to_library), 'Koha::Library', 'Koha::Item::Transfer->to_library should return a Koha::Library' ); + is( + $to_library->branchcode, $library->branchcode, + 'Koha::Item::Transfer->to_library should return the correct library' + ); $schema->storage->txn_rollback; }; @@ -128,32 +134,30 @@ subtest 'transit tests' => sub { my $checkout = $builder->build_object( { class => 'Koha::Checkouts', - value => { - itemnumber => $item->itemnumber - } + value => { itemnumber => $item->itemnumber } } ); is( ref($checkout), 'Koha::Checkout', 'Mock checkout added' ); throws_ok { $transfer->transit() } 'Koha::Exceptions::Item::Transfer::OnLoan', - 'Exception thrown if item is checked out'; + 'Exception thrown if item is checked out'; $checkout->delete; # CartToShelf test - $item->set({ location => 'CART', permanent_location => 'TEST' })->store(); - is ( $item->location, 'CART', 'Item location set to CART'); + $item->set( { location => 'CART', permanent_location => 'TEST' } )->store(); + is( $item->location, 'CART', 'Item location set to CART' ); $transfer->discard_changes; $transfer->transit(); $item->discard_changes; - is ( $item->location, 'TEST', 'Item location correctly restored to match permanent location'); + is( $item->location, 'TEST', 'Item location correctly restored to match permanent location' ); # Transit state set ok( $transfer->datesent, 'Transit set the datesent for the transfer' ); # Last seen - ok ( $item->datelastseen, 'Transit set item datelastseen date'); + ok( $item->datelastseen, 'Transit set item datelastseen date' ); $schema->storage->txn_rollback; }; @@ -177,11 +181,11 @@ subtest 'receive tests' => sub { { class => 'Koha::Item::Transfers', value => { - itemnumber => $item->itemnumber, - frombranch => $library2->branchcode, - tobranch => $library1->branchcode, + itemnumber => $item->itemnumber, + frombranch => $library2->branchcode, + tobranch => $library1->branchcode, datearrived => undef, - reason => 'Manual' + reason => 'Manual' } } ); @@ -191,16 +195,14 @@ subtest 'receive tests' => sub { my $checkout = $builder->build_object( { class => 'Koha::Checkouts', - value => { - itemnumber => $item->itemnumber - } + value => { itemnumber => $item->itemnumber } } ); is( ref($checkout), 'Koha::Checkout', 'Mock checkout added' ); throws_ok { $transfer->receive() } 'Koha::Exceptions::Item::Transfer::OnLoan', - 'Exception thrown if item is checked out'; + 'Exception thrown if item is checked out'; $checkout->delete; @@ -223,7 +225,7 @@ subtest 'in_transit tests' => sub { my $library_from = $builder->build_object( { class => 'Koha::Libraries' } ); my $library_to = $builder->build_object( { class => 'Koha::Libraries' } ); - my $item = $builder->build_sample_item( + my $item = $builder->build_sample_item( { homebranch => $library_to->branchcode, holdingbranch => $library_from->branchcode, @@ -242,13 +244,13 @@ subtest 'in_transit tests' => sub { ok( !$transfer->in_transit, 'in_transit returns false when only daterequested is defined' ); $transfer->datesent(dt_from_string)->store; - ok( $transfer->in_transit, 'in_transit returns true when datesent is defined'); + ok( $transfer->in_transit, 'in_transit returns true when datesent is defined' ); $transfer->datearrived(dt_from_string)->store; - ok( !$transfer->in_transit, 'in_transit returns false when datearrived is defined'); + ok( !$transfer->in_transit, 'in_transit returns false when datearrived is defined' ); $transfer->set( { datearrived => undef, datecancelled => dt_from_string } )->store; - ok( !$transfer->in_transit, 'in_transit returns false when datecancelled is defined'); + ok( !$transfer->in_transit, 'in_transit returns false when datecancelled is defined' ); $schema->storage->txn_rollback; }; @@ -288,16 +290,16 @@ subtest 'cancel tests' => sub { # Missing mandatory parameter throws_ok { $transfer->cancel() } 'Koha::Exceptions::MissingParameter', - 'Exception thrown if a reason is not passed to cancel'; + 'Exception thrown if a reason is not passed to cancel'; # Item in transit should result in failure - throws_ok { $transfer->cancel({ reason => $cancellation_reason }) } + throws_ok { $transfer->cancel( { reason => $cancellation_reason } ) } 'Koha::Exceptions::Item::Transfer::InTransit', - 'Exception thrown if item is in transit'; + 'Exception thrown if item is in transit'; - $transfer->cancel({ reason => $cancellation_reason, force => 1}); + $transfer->cancel( { reason => $cancellation_reason, force => 1 } ); ok( $transfer->datecancelled, 'Forced cancellation, cancellation date set' ); - is( $transfer->cancellation_reason, 'Manual', 'Forced cancellation, cancellation reason is set'); + is( $transfer->cancellation_reason, 'Manual', 'Forced cancellation, cancellation reason is set' ); $transfer->datecancelled(undef); $transfer->cancellation_reason(undef); @@ -305,9 +307,9 @@ subtest 'cancel tests' => sub { # Transit state unset $transfer->store()->discard_changes; - $transfer->cancel({ reason => $cancellation_reason }); + $transfer->cancel( { reason => $cancellation_reason } ); ok( $transfer->datecancelled, 'Cancellation date set upon call to cancel' ); - is( $transfer->cancellation_reason, 'Manual', 'Cancellation reason is set'); + is( $transfer->cancellation_reason, 'Manual', 'Cancellation reason is set' ); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/Koha/Item/Transfers.t b/t/db_dependent/Koha/Item/Transfers.t index 35cce33bcb..b182c70848 100755 --- a/t/db_dependent/Koha/Item/Transfers.t +++ b/t/db_dependent/Koha/Item/Transfers.t @@ -35,7 +35,7 @@ $schema->storage->txn_begin; my $builder = t::lib::TestBuilder->new; my $library_from = $builder->build( { source => 'Branch' } ); my $library_to = $builder->build( { source => 'Branch' } ); -my $item = $builder->build_sample_item( +my $item = $builder->build_sample_item( { holdingbranch => $library_from->{branchcode}, homebranch => $library_to->{branchcode} @@ -44,7 +44,8 @@ my $item = $builder->build_sample_item( my $nb_of_transfers = Koha::Item::Transfers->search->count; my $new_transfer_1 = Koha::Item::Transfer->new( - { itemnumber => $item->itemnumber, + { + itemnumber => $item->itemnumber, frombranch => $library_from->{branchcode}, tobranch => $library_to->{branchcode}, datearrived => dt_from_string, @@ -52,7 +53,8 @@ my $new_transfer_1 = Koha::Item::Transfer->new( } )->store; my $new_transfer_2 = Koha::Item::Transfer->new( - { itemnumber => $item->itemnumber, + { + itemnumber => $item->itemnumber, frombranch => $library_from->{branchcode}, tobranch => $library_to->{branchcode}, datearrived => undef, @@ -62,8 +64,11 @@ my $new_transfer_2 = Koha::Item::Transfer->new( is( Koha::Item::Transfers->search->count, $nb_of_transfers + 2, 'The 2 transfers should have been added' ); -my $retrieved_transfer_1 = Koha::Item::Transfers->search( { itemnumber => $new_transfer_1->itemnumber })->next; -is( $retrieved_transfer_1->itemnumber, $new_transfer_1->itemnumber, 'Find a transfer by id should return the correct transfer' ); +my $retrieved_transfer_1 = Koha::Item::Transfers->search( { itemnumber => $new_transfer_1->itemnumber } )->next; +is( + $retrieved_transfer_1->itemnumber, $new_transfer_1->itemnumber, + 'Find a transfer by id should return the correct transfer' +); # FIXME: This does not pass and should be fixed later # "Operation requires a primary key to be declared on 'Branchtransfer' via set_primary_key" @@ -79,14 +84,14 @@ subtest 'daterequested tests' => sub { $schema->storage->txn_begin; my $library_from = $builder->build( { source => 'Branch' } ); my $library_to = $builder->build( { source => 'Branch' } ); - my $item = $builder->build_sample_item( + my $item = $builder->build_sample_item( { holdingbranch => $library_from->{branchcode}, homebranch => $library_to->{branchcode} } ); - my $now = dt_from_string; + my $now = dt_from_string; my $transfer = Koha::Item::Transfer->new( { itemnumber => $item->itemnumber, @@ -97,15 +102,19 @@ subtest 'daterequested tests' => sub { $transfer->discard_changes; ok( $transfer->daterequested, 'daterequested set on creation' ); - is( t::lib::Dates::compare( $transfer->daterequested, $now ), - 0, 'daterequested was set correctly' ); + is( + t::lib::Dates::compare( $transfer->daterequested, $now ), + 0, 'daterequested was set correctly' + ); my $new_date = $now->clone->add( hours => 1 ); - $transfer->set({ datesent => $new_date })->store; + $transfer->set( { datesent => $new_date } )->store; $transfer->discard_changes; - is( t::lib::Dates::compare( $transfer->daterequested, $now ), - 0, 'daterequested is not updated when other fields are updated' ); + is( + t::lib::Dates::compare( $transfer->daterequested, $now ), + 0, 'daterequested is not updated when other fields are updated' + ); $schema->storage->txn_rollback; }; @@ -116,17 +125,21 @@ subtest 'filter_by_current() tests' => sub { $schema->storage->txn_begin; - my $transfer_1 = $builder->build_object({ class => 'Koha::Item::Transfers', value => { datearrived => \'NOW()', datecancelled => undef } }); - my $transfer_2 = $builder->build_object({ class => 'Koha::Item::Transfers', value => { datearrived => undef, datecancelled => \'NOW()' } }); - my $transfer_3 = $builder->build_object({ class => 'Koha::Item::Transfers', value => { datearrived => undef, datecancelled => undef } }); + my $transfer_1 = $builder->build_object( + { class => 'Koha::Item::Transfers', value => { datearrived => \'NOW()', datecancelled => undef } } ); + my $transfer_2 = $builder->build_object( + { class => 'Koha::Item::Transfers', value => { datearrived => undef, datecancelled => \'NOW()' } } ); + my $transfer_3 = $builder->build_object( + { class => 'Koha::Item::Transfers', value => { datearrived => undef, datecancelled => undef } } ); - my $rs = Koha::Item::Transfers->search({ branchtransfer_id => [ $transfer_1->id, $transfer_2->id, $transfer_3->id ] }); + my $rs = + Koha::Item::Transfers->search( { branchtransfer_id => [ $transfer_1->id, $transfer_2->id, $transfer_3->id ] } ); is( $rs->count, 3, 'Resultset has 3 transfers' ); $rs = $rs->filter_by_current; - is( $rs->count, 1, 'Filtered resultset has 1 transfer' ); + is( $rs->count, 1, 'Filtered resultset has 1 transfer' ); is( $rs->next->id, $transfer_3->id, 'Only current transfer left on the resultset' ); $schema->storage->txn_rollback; diff --git a/t/db_dependent/Koha/ItemTypes.t b/t/db_dependent/Koha/ItemTypes.t index d62cf05e48..acc6eef007 100755 --- a/t/db_dependent/Koha/ItemTypes.t +++ b/t/db_dependent/Koha/ItemTypes.t @@ -28,7 +28,7 @@ use C4::Calendar qw( new ); use Koha::Biblioitems; use Koha::Libraries; use Koha::Database; -use Koha::DateUtils qw(dt_from_string);; +use Koha::DateUtils qw(dt_from_string); use Koha::Items; BEGIN { @@ -40,31 +40,37 @@ my $database = Koha::Database->new(); my $schema = $database->schema(); $schema->txn_begin; -my $builder = t::lib::TestBuilder->new; +my $builder = t::lib::TestBuilder->new; my $initial_count = Koha::ItemTypes->search->count; -my $parent1 = $builder->build_object({ class => 'Koha::ItemTypes', value => { description => 'description' } }); -my $child1 = $builder->build_object({ +my $parent1 = $builder->build_object( { class => 'Koha::ItemTypes', value => { description => 'description' } } ); +my $child1 = $builder->build_object( + { class => 'Koha::ItemTypes', value => { parent_type => $parent1->itemtype, description => 'description', } - }); -my $child2 = $builder->build_object({ + } +); +my $child2 = $builder->build_object( + { class => 'Koha::ItemTypes', value => { parent_type => $parent1->itemtype, description => 'description', } - }); -my $child3 = $builder->build_object({ + } +); +my $child3 = $builder->build_object( + { class => 'Koha::ItemTypes', value => { parent_type => $parent1->itemtype, description => 'description', } - }); + } +); Koha::Localization->new( { @@ -91,17 +97,17 @@ Koha::Localization->new( } )->store; -my $type = Koha::ItemTypes->find($child1->itemtype); +my $type = Koha::ItemTypes->find( $child1->itemtype ); ok( defined($type), 'first result' ); -is_deeply( $type->unblessed, $child1->unblessed, "We got back the same object" ); -is_deeply( $type->parent->unblessed, $parent1->unblessed, 'The parent method returns the correct object'); +is_deeply( $type->unblessed, $child1->unblessed, "We got back the same object" ); +is_deeply( $type->parent->unblessed, $parent1->unblessed, 'The parent method returns the correct object' ); -$type = Koha::ItemTypes->find($child2->itemtype); +$type = Koha::ItemTypes->find( $child2->itemtype ); ok( defined($type), 'second result' ); is_deeply( $type->unblessed, $child2->unblessed, "We got back the same object" ); -t::lib::Mocks::mock_preference('language', 'en'); -t::lib::Mocks::mock_preference('OPACLanguages', 'en'); +t::lib::Mocks::mock_preference( 'language', 'en' ); +t::lib::Mocks::mock_preference( 'OPACLanguages', 'en' ); my $itemtypes = Koha::ItemTypes->search_with_localization; is( $itemtypes->count, $initial_count + 4, 'We added 4 item types' ); my $first_itemtype = $itemtypes->next; @@ -111,7 +117,7 @@ is( 'item types should be sorted by translated description' ); -my $children = $parent1->children_with_localization; +my $children = $parent1->children_with_localization; my $first_child = $children->next; is( $first_child->translated_description, @@ -119,19 +125,22 @@ is( 'item types should be sorted by translated description' ); -my $item_type = $builder->build_object({ class => 'Koha::ItemTypes' }); +my $item_type = $builder->build_object( { class => 'Koha::ItemTypes' } ); -is( $item_type->can_be_deleted, 1, 'An item type that is not used can be deleted'); +is( $item_type->can_be_deleted, 1, 'An item type that is not used can be deleted' ); -my $item = $builder->build_sample_item({ itype => $item_type->itemtype }); +my $item = $builder->build_sample_item( { itype => $item_type->itemtype } ); is( $item_type->can_be_deleted, 0, 'An item type that is used by an item cannot be deleted' ); $item->delete; -my $biblio = $builder->build_sample_biblio({ itemtype => $item_type->itemtype }); -is ( $item_type->can_be_deleted, 0, 'An item type that is used by an item and a biblioitem cannot be deleted' ); +my $biblio = $builder->build_sample_biblio( { itemtype => $item_type->itemtype } ); +is( $item_type->can_be_deleted, 0, 'An item type that is used by an item and a biblioitem cannot be deleted' ); $biblio->delete; -is ( $item_type->can_be_deleted, 1, 'The item type that was being used by the removed item and biblioitem can now be deleted' ); +is( + $item_type->can_be_deleted, 1, + 'The item type that was being used by the removed item and biblioitem can now be deleted' +); subtest 'image_location' => sub { plan tests => 3; diff --git a/t/db_dependent/Koha/Items.t b/t/db_dependent/Koha/Items.t index 03b26550eb..31ee1af460 100755 --- a/t/db_dependent/Koha/Items.t +++ b/t/db_dependent/Koha/Items.t @@ -42,25 +42,28 @@ use t::lib::Dates; my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; -my $dbh = C4::Context->dbh; +my $dbh = C4::Context->dbh; my $builder = t::lib::TestBuilder->new; my $library = $builder->build( { source => 'Branch' } ); my $nb_of_items = Koha::Items->search->count; my $biblio = $builder->build_sample_biblio(); -my $new_item_1 = $builder->build_sample_item({ - biblionumber => $biblio->biblionumber, - homebranch => $library->{branchcode}, - holdingbranch => $library->{branchcode}, -}); -my $new_item_2 = $builder->build_sample_item({ - biblionumber => $biblio->biblionumber, - homebranch => $library->{branchcode}, - holdingbranch => $library->{branchcode}, -}); +my $new_item_1 = $builder->build_sample_item( + { + biblionumber => $biblio->biblionumber, + homebranch => $library->{branchcode}, + holdingbranch => $library->{branchcode}, + } +); +my $new_item_2 = $builder->build_sample_item( + { + biblionumber => $biblio->biblionumber, + homebranch => $library->{branchcode}, + holdingbranch => $library->{branchcode}, + } +); - -t::lib::Mocks::mock_userenv({ branchcode => $library->{branchcode} }); +t::lib::Mocks::mock_userenv( { branchcode => $library->{branchcode} } ); like( $new_item_1->itemnumber, qr|^\d+$|, 'Adding a new item should have set the itemnumber' ); is( Koha::Items->search->count, $nb_of_items + 2, 'The 2 items should have been added' ); @@ -82,10 +85,14 @@ subtest 'store' => sub { } )->store->get_from_storage; - is( t::lib::Dates::compare( $item->replacementpricedate, $today ), - 0, 'replacementpricedate must have been set to today if not given' ); - is( t::lib::Dates::compare( dt_from_string($item->datelastseen)->ymd, $today ), - 0, 'datelastseen must have been set to today if not given' ); + is( + t::lib::Dates::compare( $item->replacementpricedate, $today ), + 0, 'replacementpricedate must have been set to today if not given' + ); + is( + t::lib::Dates::compare( dt_from_string( $item->datelastseen )->ymd, $today ), + 0, 'datelastseen must have been set to today if not given' + ); is( $item->itype, $biblio->biblioitem->itemtype, @@ -99,7 +106,7 @@ subtest 'store' => sub { subtest 'location passed to ->store' => sub { plan tests => 7; - my $location = 'my_loc'; + my $location = 'my_loc'; my $attributes = { homebranch => $library->{branchcode}, holdingbranch => $library->{branchcode}, @@ -113,18 +120,22 @@ subtest 'store' => sub { # Not passing permanent_location on creating the item my $item = Koha::Item->new($attributes)->store->get_from_storage; - is( $item->location, $location, - 'location must have been set to location if given' ); - is( $item->permanent_location, $item->location, - 'permanent_location must have been set to location if not given' ); + is( + $item->location, $location, + 'location must have been set to location if given' + ); + is( + $item->permanent_location, $item->location, + 'permanent_location must have been set to location if not given' + ); $item->delete; # Passing permanent_location on creating the item - $item = Koha::Item->new( - { %$attributes, permanent_location => 'perm_loc' } ) - ->store->get_from_storage; - is( $item->permanent_location, 'perm_loc', - 'permanent_location must have been kept if given' ); + $item = Koha::Item->new( { %$attributes, permanent_location => 'perm_loc' } )->store->get_from_storage; + is( + $item->permanent_location, 'perm_loc', + 'permanent_location must have been kept if given' + ); $item->delete; } @@ -135,20 +146,26 @@ subtest 'store' => sub { # Not passing permanent_location on creating the item my $item = Koha::Item->new($attributes)->store->get_from_storage; - is( $item->location, $location, - 'location must have been kept if given' ); - is( $item->permanent_location, $location, - 'permanent_location must have been set to the location given' ); + is( + $item->location, $location, + 'location must have been kept if given' + ); + is( + $item->permanent_location, $location, + 'permanent_location must have been set to the location given' + ); $item->delete; # Passing permanent_location on creating the item - $item = Koha::Item->new( - { %$attributes, permanent_location => 'perm_loc' } ) - ->store->get_from_storage; - is( $item->location, $location, - 'location must have been kept if given' ); - is( $item->permanent_location, 'perm_loc', - 'permanent_location must have been kept if given' ); + $item = Koha::Item->new( { %$attributes, permanent_location => 'perm_loc' } )->store->get_from_storage; + is( + $item->location, $location, + 'location must have been kept if given' + ); + is( + $item->permanent_location, 'perm_loc', + 'permanent_location must have been kept if given' + ); $item->delete; } }; @@ -168,18 +185,22 @@ subtest 'store' => sub { # Not passing permanent_location on creating the item my $item = Koha::Item->new($attributes)->store->get_from_storage; - is( $item->location, undef, - 'location not passed and no default, it is undef' ); - is( $item->permanent_location, $item->location, - 'permanent_location must have been set to location if not given' ); + is( + $item->location, undef, + 'location not passed and no default, it is undef' + ); + is( + $item->permanent_location, $item->location, + 'permanent_location must have been set to location if not given' + ); $item->delete; # Passing permanent_location on creating the item - $item = Koha::Item->new( - { %$attributes, permanent_location => 'perm_loc' } ) - ->store->get_from_storage; - is( $item->permanent_location, 'perm_loc', - 'permanent_location must have been kept if given' ); + $item = Koha::Item->new( { %$attributes, permanent_location => 'perm_loc' } )->store->get_from_storage; + is( + $item->permanent_location, 'perm_loc', + 'permanent_location must have been kept if given' + ); $item->delete; } @@ -190,20 +211,26 @@ subtest 'store' => sub { # Not passing permanent_location on creating the item my $item = Koha::Item->new($attributes)->store->get_from_storage; - is( $item->location, $default_location, - 'location must have been set to default location if not given' ); - is( $item->permanent_location, $default_location, - 'permanent_location must have been set to the default location as well' ); + is( + $item->location, $default_location, + 'location must have been set to default location if not given' + ); + is( + $item->permanent_location, $default_location, + 'permanent_location must have been set to the default location as well' + ); $item->delete; # Passing permanent_location on creating the item - $item = Koha::Item->new( - { %$attributes, permanent_location => 'perm_loc' } ) - ->store->get_from_storage; - is( $item->location, $default_location, - 'location must have been set to default location if not given' ); - is( $item->permanent_location, 'perm_loc', - 'permanent_location must have been kept if given' ); + $item = Koha::Item->new( { %$attributes, permanent_location => 'perm_loc' } )->store->get_from_storage; + is( + $item->location, $default_location, + 'location must have been set to default location if not given' + ); + is( + $item->permanent_location, 'perm_loc', + 'permanent_location must have been kept if given' + ); $item->delete; } }; @@ -216,11 +243,11 @@ subtest 'store' => sub { # Once the '_on' value is set (triggered by the related field turning from false to true) # it should not be re-set for any changes outside of the related field being 'unset'. - my @fields = qw( itemlost withdrawn damaged ); - my $today = dt_from_string(); + my @fields = qw( itemlost withdrawn damaged ); + my $today = dt_from_string(); my $yesterday = $today->clone()->subtract( days => 1 ); - for my $field ( @fields ) { + for my $field (@fields) { my $item = $builder->build_sample_item( { itemlost => 0, @@ -237,20 +264,24 @@ subtest 'store' => sub { Time::Fake->offset( $yesterday->epoch ); $item->$field(1)->store; $item->get_from_storage; - is( t::lib::Dates::compare( $item->$field_on, $yesterday ), - 0, $field_on . " was set upon first truthy setting" ); + is( + t::lib::Dates::compare( $item->$field_on, $yesterday ), + 0, $field_on . " was set upon first truthy setting" + ); # Update the field to a new 'true' value Time::Fake->offset( $today->epoch ); $item->$field(2)->store; $item->get_from_storage; - is( t::lib::Dates::compare( $item->$field_on, $yesterday ), - 0, $field_on . " was not updated upon second truthy setting" ); + is( + t::lib::Dates::compare( $item->$field_on, $yesterday ), + 0, $field_on . " was not updated upon second truthy setting" + ); # Update the field to a new 'false' value $item->$field(0)->store; $item->get_from_storage; - is($item->$field_on, undef, $field_on . " was unset upon untruthy setting"); + is( $item->$field_on, undef, $field_on . " was unset upon untruthy setting" ); Time::Fake->reset; } @@ -284,11 +315,9 @@ subtest 'store' => sub { plan tests => 12; - my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); - my $manager = - $builder->build_object( { class => "Koha::Patrons" } ); - t::lib::Mocks::mock_userenv( - { patron => $manager, branchcode => $manager->branchcode } ); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + my $manager = $builder->build_object( { class => "Koha::Patrons" } ); + t::lib::Mocks::mock_userenv( { patron => $manager, branchcode => $manager->branchcode } ); my $item = $builder->build_sample_item( { @@ -312,15 +341,21 @@ subtest 'store' => sub { debit_type_code => 'PROCESSING' } ); - is( $processing_fee_lines->count, - 1, 'Only one processing fee produced' ); + is( + $processing_fee_lines->count, + 1, 'Only one processing fee produced' + ); my $processing_fee_line = $processing_fee_lines->next; - is( $processing_fee_line->amount + 0, + is( + $processing_fee_line->amount + 0, $processfee_amount, - 'The right PROCESSING amount is generated' ); - is( $processing_fee_line->amountoutstanding + 0, + 'The right PROCESSING amount is generated' + ); + is( + $processing_fee_line->amountoutstanding + 0, $processfee_amount, - 'The right PROCESSING amountoutstanding is generated' ); + 'The right PROCESSING amountoutstanding is generated' + ); my $lost_fee_lines = Koha::Account::Lines->search( { @@ -331,11 +366,15 @@ subtest 'store' => sub { ); is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' ); my $lost_fee_line = $lost_fee_lines->next; - is( $lost_fee_line->amount + 0, - $replacement_amount, 'The right LOST amount is generated' ); - is( $lost_fee_line->amountoutstanding + 0, + is( + $lost_fee_line->amount + 0, + $replacement_amount, 'The right LOST amount is generated' + ); + is( + $lost_fee_line->amountoutstanding + 0, $replacement_amount, - 'The right LOST amountoutstanding is generated' ); + 'The right LOST amountoutstanding is generated' + ); is( $lost_fee_line->status, undef, 'The LOST status was not set' ); my $account = $patron->account; @@ -353,18 +392,29 @@ subtest 'store' => sub { # Simulate item marked as found $item->itemlost(0)->store; - is( scalar ( grep { $_->message eq 'lost_refunded' } @{$item->object_messages} ), 0, 'No LOST_FOUND account line added' ); + is( + scalar( grep { $_->message eq 'lost_refunded' } @{ $item->object_messages } ), 0, + 'No LOST_FOUND account line added' + ); $lost_fee_line->discard_changes; # reload from DB - is( $lost_fee_line->amountoutstanding + 0, - 0, 'Lost fee has no outstanding amount' ); - is( $lost_fee_line->debit_type_code, - 'LOST', 'Lost fee now still has account type of LOST' ); - is( $lost_fee_line->status, 'FOUND', - "Lost fee now has account status of FOUND - No Refund" ); + is( + $lost_fee_line->amountoutstanding + 0, + 0, 'Lost fee has no outstanding amount' + ); + is( + $lost_fee_line->debit_type_code, + 'LOST', 'Lost fee now still has account type of LOST' + ); + is( + $lost_fee_line->status, 'FOUND', + "Lost fee now has account status of FOUND - No Refund" + ); - is( $patron->account->balance, - -0, 'The patron balance is 0, everything was written off' ); + is( + $patron->account->balance, + -0, 'The patron balance is 0, everything was written off' + ); }; subtest 'Full payment tests' => sub { @@ -382,8 +432,7 @@ subtest 'store' => sub { } ); - my $issue = - C4::Circulation::AddIssue( $patron, $item->barcode ); + my $issue = C4::Circulation::AddIssue( $patron, $item->barcode ); # Simulate item marked as lost $item->itemlost(1)->store; @@ -396,15 +445,21 @@ subtest 'store' => sub { debit_type_code => 'PROCESSING' } ); - is( $processing_fee_lines->count, - 1, 'Only one processing fee produced' ); + is( + $processing_fee_lines->count, + 1, 'Only one processing fee produced' + ); my $processing_fee_line = $processing_fee_lines->next; - is( $processing_fee_line->amount + 0, + is( + $processing_fee_line->amount + 0, $processfee_amount, - 'The right PROCESSING amount is generated' ); - is( $processing_fee_line->amountoutstanding + 0, + 'The right PROCESSING amount is generated' + ); + is( + $processing_fee_line->amountoutstanding + 0, $processfee_amount, - 'The right PROCESSING amountoutstanding is generated' ); + 'The right PROCESSING amountoutstanding is generated' + ); my $lost_fee_lines = Koha::Account::Lines->search( { @@ -415,11 +470,15 @@ subtest 'store' => sub { ); is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' ); my $lost_fee_line = $lost_fee_lines->next; - is( $lost_fee_line->amount + 0, - $replacement_amount, 'The right LOST amount is generated' ); - is( $lost_fee_line->amountoutstanding + 0, + is( + $lost_fee_line->amount + 0, + $replacement_amount, 'The right LOST amount is generated' + ); + is( + $lost_fee_line->amountoutstanding + 0, $replacement_amount, - 'The right LOST amountountstanding is generated' ); + 'The right LOST amountountstanding is generated' + ); my $account = $patron->account; my $debts = $account->outstanding_debits; @@ -436,7 +495,7 @@ subtest 'store' => sub { # Simulate item marked as found $item->itemlost(0)->store; - is( scalar ( grep { $_->message eq 'lost_refunded' } @{$item->object_messages} ), 1, 'Refund triggered' ); + is( scalar( grep { $_->message eq 'lost_refunded' } @{ $item->object_messages } ), 1, 'Refund triggered' ); my $credit_return = Koha::Account::Lines->search( { @@ -447,13 +506,15 @@ subtest 'store' => sub { )->single; ok( $credit_return, 'An account line of type LOST_FOUND is added' ); - is( $credit_return->amount + 0, + is( + $credit_return->amount + 0, -99.00, - 'The account line of type LOST_FOUND has an amount of -99' ); + 'The account line of type LOST_FOUND has an amount of -99' + ); is( $credit_return->amountoutstanding + 0, -99.00, -'The account line of type LOST_FOUND has an amountoutstanding of -99' + 'The account line of type LOST_FOUND has an amountoutstanding of -99' ); my $processing_return = Koha::Account::Lines->search( @@ -464,20 +525,29 @@ subtest 'store' => sub { { rows => 1 } )->single; ok( $processing_return, 'An account line of type PROCESSING_FOUND is added' ); - is( $processing_return->amount + 0, + is( + $processing_return->amount + 0, -20.00, - 'The account line of type PROCESSING_FOUND has an amount of -20' ); + 'The account line of type PROCESSING_FOUND has an amount of -20' + ); $lost_fee_line->discard_changes; - is( $lost_fee_line->amountoutstanding + 0, - 0, 'Lost fee has no outstanding amount' ); - is( $lost_fee_line->debit_type_code, - 'LOST', 'Lost fee now still has account type of LOST' ); - is( $lost_fee_line->status, 'FOUND', - "Lost fee now has account status of FOUND" ); + is( + $lost_fee_line->amountoutstanding + 0, + 0, 'Lost fee has no outstanding amount' + ); + is( + $lost_fee_line->debit_type_code, + 'LOST', 'Lost fee now still has account type of LOST' + ); + is( + $lost_fee_line->status, 'FOUND', + "Lost fee now has account status of FOUND" + ); - is( $patron->account->balance, -119, -'The patron balance is -119, a credit that equals the lost fee payment and the processing fee' + is( + $patron->account->balance, -119, + 'The patron balance is -119, a credit that equals the lost fee payment and the processing fee' ); }; @@ -497,8 +567,7 @@ subtest 'store' => sub { } ); - my $issue = - C4::Circulation::AddIssue( $patron, $item->barcode ); + my $issue = C4::Circulation::AddIssue( $patron, $item->barcode ); # Simulate item marked as lost $item->itemlost(3)->store; @@ -511,15 +580,21 @@ subtest 'store' => sub { debit_type_code => 'PROCESSING' } ); - is( $processing_fee_lines->count, - 1, 'Only one processing fee produced' ); + is( + $processing_fee_lines->count, + 1, 'Only one processing fee produced' + ); my $processing_fee_line = $processing_fee_lines->next; - is( $processing_fee_line->amount + 0, + is( + $processing_fee_line->amount + 0, $processfee_amount, - 'The right PROCESSING amount is generated' ); - is( $processing_fee_line->amountoutstanding + 0, + 'The right PROCESSING amount is generated' + ); + is( + $processing_fee_line->amountoutstanding + 0, $processfee_amount, - 'The right PROCESSING amountoutstanding is generated' ); + 'The right PROCESSING amountoutstanding is generated' + ); my $lost_fee_lines = Koha::Account::Lines->search( { @@ -530,11 +605,15 @@ subtest 'store' => sub { ); is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' ); my $lost_fee_line = $lost_fee_lines->next; - is( $lost_fee_line->amount + 0, - $replacement_amount, 'The right LOST amount is generated' ); - is( $lost_fee_line->amountoutstanding + 0, + is( + $lost_fee_line->amount + 0, + $replacement_amount, 'The right LOST amount is generated' + ); + is( + $lost_fee_line->amountoutstanding + 0, $replacement_amount, - 'The right LOST amountountstanding is generated' ); + 'The right LOST amountountstanding is generated' + ); # Set processingreturn_policy to '0' so processing fee is retained # these tests are just for lostreturn @@ -553,7 +632,7 @@ subtest 'store' => sub { # Simulate item marked as found $item->itemlost(0)->store; - is( scalar ( grep { $_->message eq 'lost_refunded' } @{$item->object_messages} ), 1, 'Refund triggered' ); + is( scalar( grep { $_->message eq 'lost_refunded' } @{ $item->object_messages } ), 1, 'Refund triggered' ); my $credit_return = Koha::Account::Lines->search( { @@ -564,37 +643,45 @@ subtest 'store' => sub { )->single; ok( $credit_return, 'An account line of type LOST_FOUND is added' ); - is( $credit_return->amount + 0, + is( + $credit_return->amount + 0, -99.00, - 'The account line of type LOST_FOUND has an amount of -99' ); + 'The account line of type LOST_FOUND has an amount of -99' + ); is( $credit_return->amountoutstanding + 0, 0, -'The account line of type LOST_FOUND has an amountoutstanding of 0' + 'The account line of type LOST_FOUND has an amountoutstanding of 0' ); $lost_fee_line->discard_changes; - is( $lost_fee_line->amountoutstanding + 0, - 0, 'Lost fee has no outstanding amount' ); - is( $lost_fee_line->debit_type_code, - 'LOST', 'Lost fee now still has account type of LOST' ); - is( $lost_fee_line->status, 'FOUND', - "Lost fee now has account status of FOUND" ); + is( + $lost_fee_line->amountoutstanding + 0, + 0, 'Lost fee has no outstanding amount' + ); + is( + $lost_fee_line->debit_type_code, + 'LOST', 'Lost fee now still has account type of LOST' + ); + is( + $lost_fee_line->status, 'FOUND', + "Lost fee now has account status of FOUND" + ); - is( $patron->account->balance, - 20, 'The patron balance is 20, still owes the processing fee' ); + is( + $patron->account->balance, + 20, 'The patron balance is 20, still owes the processing fee' + ); }; - subtest - 'Test with partial payment and write off, and remaining debt' => - sub { + subtest 'Test with partial payment and write off, and remaining debt' => sub { plan tests => 19; t::lib::Mocks::mock_preference( 'AccountAutoReconcile', 0 ); my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); - my $item = $builder->build_sample_item( + my $item = $builder->build_sample_item( { biblionumber => $biblio->biblionumber, library => $library->branchcode, @@ -603,8 +690,7 @@ subtest 'store' => sub { } ); - my $issue = - C4::Circulation::AddIssue( $patron, $item->barcode ); + my $issue = C4::Circulation::AddIssue( $patron, $item->barcode ); # Simulate item marked as lost $item->itemlost(1)->store; @@ -617,15 +703,21 @@ subtest 'store' => sub { debit_type_code => 'PROCESSING' } ); - is( $processing_fee_lines->count, - 1, 'Only one processing fee produced' ); + is( + $processing_fee_lines->count, + 1, 'Only one processing fee produced' + ); my $processing_fee_line = $processing_fee_lines->next; - is( $processing_fee_line->amount + 0, + is( + $processing_fee_line->amount + 0, $processfee_amount, - 'The right PROCESSING amount is generated' ); - is( $processing_fee_line->amountoutstanding + 0, + 'The right PROCESSING amount is generated' + ); + is( + $processing_fee_line->amountoutstanding + 0, $processfee_amount, - 'The right PROCESSING amountoutstanding is generated' ); + 'The right PROCESSING amountoutstanding is generated' + ); my $lost_fee_lines = Koha::Account::Lines->search( { @@ -636,11 +728,15 @@ subtest 'store' => sub { ); is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' ); my $lost_fee_line = $lost_fee_lines->next; - is( $lost_fee_line->amount + 0, - $replacement_amount, 'The right LOST amount is generated' ); - is( $lost_fee_line->amountoutstanding + 0, + is( + $lost_fee_line->amount + 0, + $replacement_amount, 'The right LOST amount is generated' + ); + is( + $lost_fee_line->amountoutstanding + 0, $replacement_amount, - 'The right LOST amountountstanding is generated' ); + 'The right LOST amountountstanding is generated' + ); my $account = $patron->account; is( @@ -672,7 +768,6 @@ subtest 'store' => sub { ); $write_off->apply( { debits => [$lost_fee_line] } ); - my $payment_amount_2 = 3; my $payment_2 = $account->add_credit( { @@ -682,8 +777,7 @@ subtest 'store' => sub { } ); - $payment_2->apply( - { debits => [$lost_fee_line] } ); + $payment_2->apply( { debits => [$lost_fee_line] } ); # Partially write off fee (52 - 5 = 47) my $write_off_amount_2 = 5; @@ -695,30 +789,22 @@ subtest 'store' => sub { } ); - $write_off_2->apply( - { debits => [$lost_fee_line] } ); + $write_off_2->apply( { debits => [$lost_fee_line] } ); is( $account->balance, - $processfee_amount + - $replacement_amount - - $payment_amount - - $write_off_amount - - $payment_amount_2 - - $write_off_amount_2, + $processfee_amount + $replacement_amount - $payment_amount - $write_off_amount - $payment_amount_2 - + $write_off_amount_2, 'Balance is PROCESSING + LOST - PAYMENT 1 - WRITEOFF - PAYMENT 2 - WRITEOFF 2' ); # VOID payment_2 and writeoff_2 - $payment_2->void({ interface => 'test' }); - $write_off_2->void({ interface => 'test' }); + $payment_2->void( { interface => 'test' } ); + $write_off_2->void( { interface => 'test' } ); is( $account->balance, - $processfee_amount + - $replacement_amount - - $payment_amount - - $write_off_amount, + $processfee_amount + $replacement_amount - $payment_amount - $write_off_amount, 'Balance is PROCESSING + LOST - PAYMENT 1 - WRITEOFF (PAYMENT 2 and WRITEOFF 2 VOIDED)' ); @@ -733,7 +819,7 @@ subtest 'store' => sub { # Simulate item marked as found $item->itemlost(0)->store; - is( scalar ( grep { $_->message eq 'lost_refunded' } @{$item->object_messages} ), 1, 'Refund triggered' ); + is( scalar( grep { $_->message eq 'lost_refunded' } @{ $item->object_messages } ), 1, 'Refund triggered' ); my $credit_return = Koha::Account::Lines->search( { @@ -752,37 +838,42 @@ subtest 'store' => sub { ); $lost_fee_line->discard_changes; - is( $lost_fee_line->amountoutstanding + 0, - 0, 'Lost fee has no outstanding amount' ); - is( $lost_fee_line->debit_type_code, - 'LOST', 'Lost fee now still has account type of LOST' ); - is( $lost_fee_line->status, 'FOUND', - "Lost fee now has account status of FOUND" ); + is( + $lost_fee_line->amountoutstanding + 0, + 0, 'Lost fee has no outstanding amount' + ); + is( + $lost_fee_line->debit_type_code, + 'LOST', 'Lost fee now still has account type of LOST' + ); + is( + $lost_fee_line->status, 'FOUND', + "Lost fee now has account status of FOUND" + ); is( $credit_return->amount + 0, ( $payment_amount + $outstanding ) * -1, -'The account line of type LOST_FOUND has an amount equal to the payment 1 + outstanding' + 'The account line of type LOST_FOUND has an amount equal to the payment 1 + outstanding' ); is( $credit_return->amountoutstanding + 0, $payment_amount * -1, -'The account line of type LOST_FOUND has an amountoutstanding equal to the payment' + 'The account line of type LOST_FOUND has an amountoutstanding equal to the payment' ); is( $account->balance, $processfee_amount - $payment_amount, -'The patron balance is the difference between the PROCESSING and the credit' + 'The patron balance is the difference between the PROCESSING and the credit' ); - }; + }; - subtest 'Partial payment, existing debits and AccountAutoReconcile' => - sub { + subtest 'Partial payment, existing debits and AccountAutoReconcile' => sub { plan tests => 10; - my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $barcode = 'KD123456793'; my $replacement_amount = 100; my $processfee_amount = 20; @@ -810,8 +901,7 @@ subtest 'store' => sub { }, )->store; - my $issue = - C4::Circulation::AddIssue( $patron, $barcode ); + my $issue = C4::Circulation::AddIssue( $patron, $barcode ); # Simulate item marked as lost $item->itemlost(1)->store; @@ -826,11 +916,15 @@ subtest 'store' => sub { ); is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' ); my $lost_fee_line = $lost_fee_lines->next; - is( $lost_fee_line->amount + 0, - $replacement_amount, 'The right LOST amount is generated' ); - is( $lost_fee_line->amountoutstanding + 0, + is( + $lost_fee_line->amount + 0, + $replacement_amount, 'The right LOST amount is generated' + ); + is( + $lost_fee_line->amountoutstanding + 0, $replacement_amount, - 'The right LOST amountountstanding is generated' ); + 'The right LOST amountountstanding is generated' + ); my $account = $patron->account; is( $account->balance, $replacement_amount, 'Balance is L' ); @@ -871,7 +965,7 @@ subtest 'store' => sub { # Simulate item marked as found $item->itemlost(0)->store; - is( scalar ( grep { $_->message eq 'lost_refunded' } @{$item->object_messages} ), 1, 'Refund triggered' ); + is( scalar( grep { $_->message eq 'lost_refunded' } @{ $item->object_messages } ), 1, 'Refund triggered' ); my $credit_return = Koha::Account::Lines->search( { @@ -901,12 +995,12 @@ subtest 'store' => sub { $manual_debit_amount - $payment_amount, 'reconcile_balance was called' ); - }; + }; subtest 'Patron deleted' => sub { plan tests => 1; - my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $barcode = 'KD123456794'; my $replacement_amount = 100; my $processfee_amount = 20; @@ -934,8 +1028,7 @@ subtest 'store' => sub { }, )->store; - my $issue = - C4::Circulation::AddIssue( $patron, $barcode ); + my $issue = C4::Circulation::AddIssue( $patron, $barcode ); # Simulate item marked as lost $item->itemlost(1)->store; @@ -946,7 +1039,10 @@ subtest 'store' => sub { # Simulate item marked as found $item->itemlost(0)->store; - is( scalar ( grep { $_->message eq 'lost_refunded' } @{$item->object_messages} ), 0, 'No refund triggered' ); + is( + scalar( grep { $_->message eq 'lost_refunded' } @{ $item->object_messages } ), 0, + 'No refund triggered' + ); }; @@ -954,10 +1050,8 @@ subtest 'store' => sub { plan tests => 8; - my $manager = - $builder->build_object( { class => "Koha::Patrons" } ); - t::lib::Mocks::mock_userenv( - { patron => $manager, branchcode => $manager->branchcode } ); + my $manager = $builder->build_object( { class => "Koha::Patrons" } ); + t::lib::Mocks::mock_userenv( { patron => $manager, branchcode => $manager->branchcode } ); # Set lostreturn_policy to 'restore' for tests my $specific_rule_restore = $builder->build( @@ -984,8 +1078,7 @@ subtest 'store' => sub { } ); - my $issue = - C4::Circulation::AddIssue( $patron, $item->barcode ); + my $issue = C4::Circulation::AddIssue( $patron, $item->barcode ); # Simulate item marked as lost $item->itemlost(1)->store; @@ -998,15 +1091,21 @@ subtest 'store' => sub { debit_type_code => 'PROCESSING' } ); - is( $processing_fee_lines->count, - 1, 'Only one processing fee produced' ); + is( + $processing_fee_lines->count, + 1, 'Only one processing fee produced' + ); my $processing_fee_line = $processing_fee_lines->next; - is( $processing_fee_line->amount + 0, + is( + $processing_fee_line->amount + 0, $processfee_amount, - 'The right PROCESSING amount is generated' ); - is( $processing_fee_line->amountoutstanding + 0, + 'The right PROCESSING amount is generated' + ); + is( + $processing_fee_line->amountoutstanding + 0, $processfee_amount, - 'The right PROCESSING amountoutstanding is generated' ); + 'The right PROCESSING amountoutstanding is generated' + ); my $lost_fee_lines = Koha::Account::Lines->search( { @@ -1017,11 +1116,15 @@ subtest 'store' => sub { ); is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' ); my $lost_fee_line = $lost_fee_lines->next; - is( $lost_fee_line->amount + 0, - $replacement_amount, 'The right LOST amount is generated' ); - is( $lost_fee_line->amountoutstanding + 0, + is( + $lost_fee_line->amount + 0, + $replacement_amount, 'The right LOST amount is generated' + ); + is( + $lost_fee_line->amountoutstanding + 0, $replacement_amount, - 'The right LOST amountountstanding is generated' ); + 'The right LOST amountountstanding is generated' + ); my $account = $patron->account; my $debts = $account->outstanding_debits; @@ -1038,8 +1141,11 @@ subtest 'store' => sub { # Simulate item marked as found $item->itemlost(0)->store; - is( scalar ( grep { $_->message eq 'lost_refunded' } @{$item->object_messages} ), 1, 'Refund triggered' ); - is( scalar ( grep { $_->message eq 'lost_restored' } @{$item->object_messages} ), 0, 'Restore not triggered when there is no overdue fine found' ); + is( scalar( grep { $_->message eq 'lost_refunded' } @{ $item->object_messages } ), 1, 'Refund triggered' ); + is( + scalar( grep { $_->message eq 'lost_restored' } @{ $item->object_messages } ), 0, + 'Restore not triggered when there is no overdue fine found' + ); }; subtest 'restore fine | unforgiven overdue' => sub { @@ -1047,10 +1153,8 @@ subtest 'store' => sub { plan tests => 10; # Set lostreturn_policy to 'restore' for tests - my $manager = - $builder->build_object( { class => "Koha::Patrons" } ); - t::lib::Mocks::mock_userenv( - { patron => $manager, branchcode => $manager->branchcode } ); + my $manager = $builder->build_object( { class => "Koha::Patrons" } ); + t::lib::Mocks::mock_userenv( { patron => $manager, branchcode => $manager->branchcode } ); my $specific_rule_restore = $builder->build( { source => 'CirculationRule', @@ -1075,8 +1179,7 @@ subtest 'store' => sub { } ); - my $issue = - C4::Circulation::AddIssue( $patron, $item->barcode ); + my $issue = C4::Circulation::AddIssue( $patron, $item->barcode ); # Simulate item marked as lost $item->itemlost(1)->store; @@ -1089,15 +1192,21 @@ subtest 'store' => sub { debit_type_code => 'PROCESSING' } ); - is( $processing_fee_lines->count, - 1, 'Only one processing fee produced' ); + is( + $processing_fee_lines->count, + 1, 'Only one processing fee produced' + ); my $processing_fee_line = $processing_fee_lines->next; - is( $processing_fee_line->amount + 0, + is( + $processing_fee_line->amount + 0, $processfee_amount, - 'The right PROCESSING amount is generated' ); - is( $processing_fee_line->amountoutstanding + 0, + 'The right PROCESSING amount is generated' + ); + is( + $processing_fee_line->amountoutstanding + 0, $processfee_amount, - 'The right PROCESSING amountoutstanding is generated' ); + 'The right PROCESSING amountoutstanding is generated' + ); my $lost_fee_lines = Koha::Account::Lines->search( { @@ -1108,11 +1217,15 @@ subtest 'store' => sub { ); is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' ); my $lost_fee_line = $lost_fee_lines->next; - is( $lost_fee_line->amount + 0, - $replacement_amount, 'The right LOST amount is generated' ); - is( $lost_fee_line->amountoutstanding + 0, + is( + $lost_fee_line->amount + 0, + $replacement_amount, 'The right LOST amount is generated' + ); + is( + $lost_fee_line->amountoutstanding + 0, $replacement_amount, - 'The right LOST amountountstanding is generated' ); + 'The right LOST amountountstanding is generated' + ); my $account = $patron->account; my $debts = $account->outstanding_debits; @@ -1140,16 +1253,23 @@ subtest 'store' => sub { )->store(); $overdue->status('LOST')->store(); $overdue->discard_changes; - is( $overdue->status, 'LOST', - 'Overdue status set to LOST' ); + is( + $overdue->status, 'LOST', + 'Overdue status set to LOST' + ); # Simulate item marked as found $item->itemlost(0)->store; - is( scalar ( grep { $_->message eq 'lost_refunded' } @{$item->object_messages} ), 1, 'Refund triggered' ); - is( scalar ( grep { $_->message eq 'lost_restored' } @{$item->object_messages} ), 0, 'Restore not triggered when overdue was not forgiven' ); + is( scalar( grep { $_->message eq 'lost_refunded' } @{ $item->object_messages } ), 1, 'Refund triggered' ); + is( + scalar( grep { $_->message eq 'lost_restored' } @{ $item->object_messages } ), 0, + 'Restore not triggered when overdue was not forgiven' + ); $overdue->discard_changes; - is( $overdue->status, 'FOUND', - 'Overdue status updated to FOUND' ); + is( + $overdue->status, 'FOUND', + 'Overdue status updated to FOUND' + ); }; subtest 'restore fine | forgiven overdue' => sub { @@ -1157,10 +1277,8 @@ subtest 'store' => sub { plan tests => 12; # Set lostreturn_policy to 'restore' for tests - my $manager = - $builder->build_object( { class => "Koha::Patrons" } ); - t::lib::Mocks::mock_userenv( - { patron => $manager, branchcode => $manager->branchcode } ); + my $manager = $builder->build_object( { class => "Koha::Patrons" } ); + t::lib::Mocks::mock_userenv( { patron => $manager, branchcode => $manager->branchcode } ); my $specific_rule_restore = $builder->build( { source => 'CirculationRule', @@ -1185,8 +1303,7 @@ subtest 'store' => sub { } ); - my $issue = - C4::Circulation::AddIssue( $patron, $item->barcode ); + my $issue = C4::Circulation::AddIssue( $patron, $item->barcode ); # Simulate item marked as lost $item->itemlost(1)->store; @@ -1199,15 +1316,21 @@ subtest 'store' => sub { debit_type_code => 'PROCESSING' } ); - is( $processing_fee_lines->count, - 1, 'Only one processing fee produced' ); + is( + $processing_fee_lines->count, + 1, 'Only one processing fee produced' + ); my $processing_fee_line = $processing_fee_lines->next; - is( $processing_fee_line->amount + 0, + is( + $processing_fee_line->amount + 0, $processfee_amount, - 'The right PROCESSING amount is generated' ); - is( $processing_fee_line->amountoutstanding + 0, + 'The right PROCESSING amount is generated' + ); + is( + $processing_fee_line->amountoutstanding + 0, $processfee_amount, - 'The right PROCESSING amountoutstanding is generated' ); + 'The right PROCESSING amountoutstanding is generated' + ); my $lost_fee_lines = Koha::Account::Lines->search( { @@ -1218,11 +1341,15 @@ subtest 'store' => sub { ); is( $lost_fee_lines->count, 1, 'Only one lost item fee produced' ); my $lost_fee_line = $lost_fee_lines->next; - is( $lost_fee_line->amount + 0, - $replacement_amount, 'The right LOST amount is generated' ); - is( $lost_fee_line->amountoutstanding + 0, + is( + $lost_fee_line->amount + 0, + $replacement_amount, 'The right LOST amount is generated' + ); + is( + $lost_fee_line->amountoutstanding + 0, $replacement_amount, - 'The right LOST amountountstanding is generated' ); + 'The right LOST amountountstanding is generated' + ); my $account = $patron->account; my $debts = $account->outstanding_debits; @@ -1249,8 +1376,10 @@ subtest 'store' => sub { } )->store(); $overdue->status('LOST')->store(); - is( $overdue->status, 'LOST', - 'Overdue status set to LOST' ); + is( + $overdue->status, 'LOST', + 'Overdue status set to LOST' + ); t::lib::Mocks::mock_preference( 'AccountAutoReconcile', 0 ); @@ -1269,19 +1398,22 @@ subtest 'store' => sub { # Simulate item marked as found $item->itemlost(0)->store; - is( scalar ( grep { $_->message eq 'lost_refunded' } @{$item->object_messages} ), 1, 'Refund triggered' ); - is( scalar ( grep { $_->message eq 'lost_restored' } @{$item->object_messages} ), 1, 'Restore triggered when overdue was forgiven' ); + is( scalar( grep { $_->message eq 'lost_refunded' } @{ $item->object_messages } ), 1, 'Refund triggered' ); + is( + scalar( grep { $_->message eq 'lost_restored' } @{ $item->object_messages } ), 1, + 'Restore triggered when overdue was forgiven' + ); $overdue->discard_changes; - is( $overdue->status, 'FOUND', 'Overdue status updated to FOUND' ); + is( $overdue->status, 'FOUND', 'Overdue status updated to FOUND' ); is( $overdue->amountoutstanding, $overdue->amount, 'Overdue outstanding has been restored' ); $credit->discard_changes; - is( $credit->status, 'VOID', 'Overdue Forgival has been marked as VOID'); + is( $credit->status, 'VOID', 'Overdue Forgival has been marked as VOID' ); }; subtest 'Continue when userenv is not set' => sub { plan tests => 1; - my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $barcode = 'KD123456795'; my $replacement_amount = 100; my $processfee_amount = 20; @@ -1309,8 +1441,7 @@ subtest 'store' => sub { } ); - my $issue = - C4::Circulation::AddIssue( $patron, $barcode ); + my $issue = C4::Circulation::AddIssue( $patron, $barcode ); # Simulate item marked as lost $item->itemlost(1)->store; @@ -1321,7 +1452,7 @@ subtest 'store' => sub { # Simluate item marked as found $item->itemlost(0)->store; - is( scalar ( grep { $_->message eq 'lost_refunded' } @{$item->object_messages} ), 1, 'Refund triggered' ); + is( scalar( grep { $_->message eq 'lost_refunded' } @{ $item->object_messages } ), 1, 'Refund triggered' ); }; }; @@ -1465,8 +1596,11 @@ subtest 'get_transfer|transfer' => sub { ); $transfer = $new_item_1->get_transfer(); - is( ref($transfer), 'Koha::Item::Transfer', 'Koha::Item->get_transfer should return a Koha::Item::Transfer object' ); - is( ref($new_item_1->transfer), 'Koha::Item::Transfer' ); + is( + ref($transfer), 'Koha::Item::Transfer', + 'Koha::Item->get_transfer should return a Koha::Item::Transfer object' + ); + is( ref( $new_item_1->transfer ), 'Koha::Item::Transfer' ); my $transfer_2 = $builder->build_object( { @@ -1485,11 +1619,17 @@ subtest 'get_transfer|transfer' => sub { ); $transfer = $new_item_1->get_transfer(); - is( $transfer->branchtransfer_id, $transfer_1->branchtransfer_id, 'Koha::Item->get_transfer returns the oldest transfer request'); + is( + $transfer->branchtransfer_id, $transfer_1->branchtransfer_id, + 'Koha::Item->get_transfer returns the oldest transfer request' + ); - $transfer_2->datesent(\'NOW()')->store; + $transfer_2->datesent( \'NOW()' )->store; $transfer = $new_item_1->get_transfer(); - is( $transfer->branchtransfer_id, $transfer_2->branchtransfer_id, 'Koha::Item->get_transfer returns the in_transit transfer'); + is( + $transfer->branchtransfer_id, $transfer_2->branchtransfer_id, + 'Koha::Item->get_transfer returns the in_transit transfer' + ); my $transfer_3 = $builder->build_object( { @@ -1507,14 +1647,20 @@ subtest 'get_transfer|transfer' => sub { } ); - $transfer_2->datearrived(\'NOW()')->store; + $transfer_2->datearrived( \'NOW()' )->store; $transfer = $new_item_1->get_transfer(); - is( $transfer->branchtransfer_id, $transfer_1->branchtransfer_id, 'Koha::Item->get_transfer returns the next queued transfer'); + is( + $transfer->branchtransfer_id, $transfer_1->branchtransfer_id, + 'Koha::Item->get_transfer returns the next queued transfer' + ); is( $transfer->itemnumber, $new_item_1->itemnumber, 'Koha::Item->get_transfer returns the right items transfer' ); - $transfer_1->datecancelled(\'NOW()')->store; + $transfer_1->datecancelled( \'NOW()' )->store; $transfer = $new_item_1->get_transfer(); - is( $transfer->branchtransfer_id, $transfer_3->branchtransfer_id, 'Koha::Item->get_transfer ignores cancelled transfers'); + is( + $transfer->branchtransfer_id, $transfer_3->branchtransfer_id, + 'Koha::Item->get_transfer ignores cancelled transfers' + ); }; subtest 'holds' => sub { @@ -1565,7 +1711,7 @@ subtest 'biblio' => sub { plan tests => 2; my $biblio = $retrieved_item_1->biblio; - is( ref( $biblio ), 'Koha::Biblio', 'Koha::Item->biblio should return a Koha::Biblio' ); + is( ref($biblio), 'Koha::Biblio', 'Koha::Item->biblio should return a Koha::Biblio' ); is( $biblio->biblionumber, $retrieved_item_1->biblionumber, 'Koha::Item->biblio should return the correct biblio' ); }; @@ -1573,25 +1719,29 @@ subtest 'biblioitem' => sub { plan tests => 2; my $biblioitem = $retrieved_item_1->biblioitem; - is( ref( $biblioitem ), 'Koha::Biblioitem', 'Koha::Item->biblioitem should return a Koha::Biblioitem' ); - is( $biblioitem->biblionumber, $retrieved_item_1->biblionumber, 'Koha::Item->biblioitem should return the correct biblioitem' ); + is( ref($biblioitem), 'Koha::Biblioitem', 'Koha::Item->biblioitem should return a Koha::Biblioitem' ); + is( + $biblioitem->biblionumber, $retrieved_item_1->biblionumber, + 'Koha::Item->biblioitem should return the correct biblioitem' + ); }; # Restore userenv -t::lib::Mocks::mock_userenv({ branchcode => $library->{branchcode} }); +t::lib::Mocks::mock_userenv( { branchcode => $library->{branchcode} } ); subtest 'checkout' => sub { plan tests => 5; my $item = Koha::Items->find( $new_item_1->itemnumber ); + # No checkout yet my $checkout = $item->checkout; is( $checkout, undef, 'Koha::Item->checkout should return undef if there is no current checkout on this item' ); # Add a checkout - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); C4::Circulation::AddIssue( $patron, $item->barcode ); $checkout = $retrieved_item_1->checkout; - is( ref( $checkout ), 'Koha::Checkout', 'Koha::Item->checkout should return a Koha::Checkout' ); - is( $checkout->itemnumber, $item->itemnumber, 'Koha::Item->checkout should return the correct checkout' ); + is( ref($checkout), 'Koha::Checkout', 'Koha::Item->checkout should return a Koha::Checkout' ); + is( $checkout->itemnumber, $item->itemnumber, 'Koha::Item->checkout should return the correct checkout' ); is( $checkout->borrowernumber, $patron->borrowernumber, 'Koha::Item->checkout should return the correct checkout' ); # Do the return @@ -1605,38 +1755,60 @@ subtest 'checkout' => sub { subtest 'can_be_transferred' => sub { plan tests => 5; - t::lib::Mocks::mock_preference('UseBranchTransferLimits', 1); - t::lib::Mocks::mock_preference('BranchTransferLimitsType', 'itemtype'); + t::lib::Mocks::mock_preference( 'UseBranchTransferLimits', 1 ); + t::lib::Mocks::mock_preference( 'BranchTransferLimitsType', 'itemtype' ); my $biblio = $builder->build_sample_biblio(); my $library1 = $builder->build_object( { class => 'Koha::Libraries' } ); my $library2 = $builder->build_object( { class => 'Koha::Libraries' } ); - my $item = $builder->build_sample_item({ - biblionumber => $biblio->biblionumber, - homebranch => $library1->branchcode, - holdingbranch => $library1->branchcode, - }); + my $item = $builder->build_sample_item( + { + biblionumber => $biblio->biblionumber, + homebranch => $library1->branchcode, + holdingbranch => $library1->branchcode, + } + ); - is(Koha::Item::Transfer::Limits->search({ - fromBranch => $library1->branchcode, - toBranch => $library2->branchcode, - })->count, 0, 'There are no transfer limits between libraries.'); - ok($item->can_be_transferred({ to => $library2 }), - 'Item can be transferred between libraries.'); + is( + Koha::Item::Transfer::Limits->search( + { + fromBranch => $library1->branchcode, + toBranch => $library2->branchcode, + } + )->count, + 0, + 'There are no transfer limits between libraries.' + ); + ok( + $item->can_be_transferred( { to => $library2 } ), + 'Item can be transferred between libraries.' + ); - my $limit = Koha::Item::Transfer::Limit->new({ - fromBranch => $library1->branchcode, - toBranch => $library2->branchcode, - itemtype => $item->effective_itemtype, - })->store; - is(Koha::Item::Transfer::Limits->search({ - fromBranch => $library1->branchcode, - toBranch => $library2->branchcode, - })->count, 1, 'Given we have added a transfer limit,'); - is($item->can_be_transferred({ to => $library2 }), 0, - 'Item can no longer be transferred between libraries.'); - is($item->can_be_transferred({ to => $library2, from => $library1 }), 0, - 'We get the same result also if we pass the from-library parameter.'); + my $limit = Koha::Item::Transfer::Limit->new( + { + fromBranch => $library1->branchcode, + toBranch => $library2->branchcode, + itemtype => $item->effective_itemtype, + } + )->store; + is( + Koha::Item::Transfer::Limits->search( + { + fromBranch => $library1->branchcode, + toBranch => $library2->branchcode, + } + )->count, + 1, + 'Given we have added a transfer limit,' + ); + is( + $item->can_be_transferred( { to => $library2 } ), 0, + 'Item can no longer be transferred between libraries.' + ); + is( + $item->can_be_transferred( { to => $library2, from => $library1 } ), 0, + 'We get the same result also if we pass the from-library parameter.' + ); }; # Reset nb_of_items prior to testing delete @@ -1654,18 +1826,23 @@ subtest 'filter_by_visible_in_opac() tests' => sub { $schema->storage->txn_begin; - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $mocked_category = Test::MockModule->new('Koha::Patron::Category'); - my $exception = 1; - $mocked_category->mock( 'override_hidden_items', sub { - return $exception; - }); + my $exception = 1; + $mocked_category->mock( + 'override_hidden_items', + sub { + return $exception; + } + ); # have a fresh biblio my $biblio = $builder->build_sample_biblio; + # have two itemtypes - my $itype_1 = $builder->build_object({ class => 'Koha::ItemTypes' }); - my $itype_2 = $builder->build_object({ class => 'Koha::ItemTypes' }); + my $itype_1 = $builder->build_object( { class => 'Koha::ItemTypes' } ); + my $itype_2 = $builder->build_object( { class => 'Koha::ItemTypes' } ); + # have 5 items on that biblio my $item_1 = $builder->build_sample_item( { @@ -1725,18 +1902,25 @@ subtest 'filter_by_visible_in_opac() tests' => sub { my $rules = undef; my $mocked_context = Test::MockModule->new('C4::Context'); - $mocked_context->mock( 'yaml_preference', sub { - return $rules; - }); + $mocked_context->mock( + 'yaml_preference', + sub { + return $rules; + } + ); t::lib::Mocks::mock_preference( 'hidelostitems', 0 ); - is( $biblio->items->filter_by_visible_in_opac->count, - 6, 'No rules passed, hidelostitems unset' ); + is( + $biblio->items->filter_by_visible_in_opac->count, + 6, 'No rules passed, hidelostitems unset' + ); - is( $biblio->items->filter_by_visible_in_opac({ patron => $patron })->count, - 6, 'No rules passed, hidelostitems unset, patron exception changes nothing' ); + is( + $biblio->items->filter_by_visible_in_opac( { patron => $patron } )->count, + 6, 'No rules passed, hidelostitems unset, patron exception changes nothing' + ); - $rules = { copynumber => [ 2 ] }; + $rules = { copynumber => [2] }; t::lib::Mocks::mock_preference( 'hidelostitems', 1 ); is( @@ -1746,7 +1930,7 @@ subtest 'filter_by_visible_in_opac() tests' => sub { ); is( - $biblio->items->filter_by_visible_in_opac({ patron => $patron })->count, + $biblio->items->filter_by_visible_in_opac( { patron => $patron } )->count, 3, 'No rules passed, hidelostitems set, patron exception changes nothing' ); @@ -1760,10 +1944,11 @@ subtest 'filter_by_visible_in_opac() tests' => sub { my $biblio2 = $builder->build_sample_biblio; $rules = { biblionumber => [ $biblio2->biblionumber ] }; - my $prefetched = $biblio->items->search({},{ prefetch => ['branchtransfers','reserves'] })->filter_by_visible_in_opac; - ok( $prefetched->next, "Can retrieve object when prefetching and hiding on a duplicated column"); + my $prefetched = + $biblio->items->search( {}, { prefetch => [ 'branchtransfers', 'reserves' ] } )->filter_by_visible_in_opac; + ok( $prefetched->next, "Can retrieve object when prefetching and hiding on a duplicated column" ); - $rules = { withdrawn => [ 1, 2 ], copynumber => [ 2 ] }; + $rules = { withdrawn => [ 1, 2 ], copynumber => [2] }; is( $biblio->items->filter_by_visible_in_opac->count, 2, @@ -1771,49 +1956,47 @@ subtest 'filter_by_visible_in_opac() tests' => sub { ); is( - $biblio->items->filter_by_visible_in_opac({ patron => $patron })->count, + $biblio->items->filter_by_visible_in_opac( { patron => $patron } )->count, 3, 'hidelostitems set, rules on withdrawn but patron override passed' ); - $rules = { itype => [ $itype_1->itemtype ], copynumber => [ 2 ] }; + $rules = { itype => [ $itype_1->itemtype ], copynumber => [2] }; is( $biblio->items->filter_by_visible_in_opac->count, 2, 'Rules on itype, hidelostitems set' ); - $rules = { withdrawn => [ 1, 2 ], itype => [ $itype_1->itemtype ], copynumber => [ 2 ] }; + $rules = { withdrawn => [ 1, 2 ], itype => [ $itype_1->itemtype ], copynumber => [2] }; is( $biblio->items->filter_by_visible_in_opac->count, 1, 'Rules on itype and withdrawn, hidelostitems set' ); is( - $biblio->items->filter_by_visible_in_opac - ->next->itemnumber, + $biblio->items->filter_by_visible_in_opac->next->itemnumber, $item_4->itemnumber, 'The right item is returned' ); - $rules = { withdrawn => [ 1, 2 ], itype => [ $itype_2->itemtype ], copynumber => [ 2 ] }; + $rules = { withdrawn => [ 1, 2 ], itype => [ $itype_2->itemtype ], copynumber => [2] }; is( $biblio->items->filter_by_visible_in_opac->count, 1, 'Rules on itype and withdrawn, hidelostitems set' ); is( - $biblio->items->filter_by_visible_in_opac - ->next->itemnumber, + $biblio->items->filter_by_visible_in_opac->next->itemnumber, $item_5->itemnumber, 'The right item is returned' ); # Make sure the warning on the about page will work $rules = { itemlost => ['AB'] }; - my $c = Koha::Items->filter_by_visible_in_opac->count; + my $c = Koha::Items->filter_by_visible_in_opac->count; my @warnings = C4::Context->dbh->selectrow_array('SHOW WARNINGS'); - like( $warnings[2], qr/Truncated incorrect (DOUBLE|DECIMAL) value: 'AB'/); + like( $warnings[2], qr/Truncated incorrect (DOUBLE|DECIMAL) value: 'AB'/ ); $schema->storage->txn_rollback; }; @@ -1826,6 +2009,7 @@ subtest 'filter_out_lost() tests' => sub { # have a fresh biblio my $biblio = $builder->build_sample_biblio; + # have 3 items on that biblio my $item_1 = $builder->build_sample_item( { @@ -1847,7 +2031,7 @@ subtest 'filter_out_lost() tests' => sub { ); is( $biblio->items->filter_out_lost->next->itemnumber, $item_2->itemnumber, 'Right item returned' ); - is( $biblio->items->filter_out_lost->count, 1, 'Only one item is not lost' ); + is( $biblio->items->filter_out_lost->count, 1, 'Only one item is not lost' ); $schema->storage->txn_rollback; }; @@ -1860,16 +2044,16 @@ subtest 'move_to_biblio() tests' => sub { my $biblio1 = $builder->build_sample_biblio; my $biblio2 = $builder->build_sample_biblio; - my $item1 = $builder->build_sample_item({ biblionumber => $biblio1->biblionumber }); - my $item2 = $builder->build_sample_item({ biblionumber => $biblio1->biblionumber }); + my $item1 = $builder->build_sample_item( { biblionumber => $biblio1->biblionumber } ); + my $item2 = $builder->build_sample_item( { biblionumber => $biblio1->biblionumber } ); $biblio1->items->move_to_biblio($biblio2); $item1->discard_changes; $item2->discard_changes; - is($item1->biblionumber, $biblio2->biblionumber, "Item 1 moved"); - is($item2->biblionumber, $biblio2->biblionumber, "Item 2 moved"); + is( $item1->biblionumber, $biblio2->biblionumber, "Item 1 moved" ); + is( $item2->biblionumber, $biblio2->biblionumber, "Item 2 moved" ); $schema->storage->txn_rollback; @@ -1881,56 +2065,59 @@ subtest 'search_ordered' => sub { $schema->storage->txn_begin; - my $library_a = $builder->build_object( - { class => 'Koha::Libraries', value => { branchname => 'TEST_A' } } ); - my $library_z = $builder->build_object( - { class => 'Koha::Libraries', value => { branchname => 'TEST_Z' } } ); - my $biblio = $builder->build_sample_biblio( { serial => 0 } ); - my $item1 = $builder->build_sample_item({ biblionumber => $biblio->biblionumber }); - my $item2 = $builder->build_sample_item({ biblionumber => $biblio->biblionumber }); - my $item3 = $builder->build_sample_item({ biblionumber => $biblio->biblionumber }); + my $library_a = $builder->build_object( { class => 'Koha::Libraries', value => { branchname => 'TEST_A' } } ); + my $library_z = $builder->build_object( { class => 'Koha::Libraries', value => { branchname => 'TEST_Z' } } ); + my $biblio = $builder->build_sample_biblio( { serial => 0 } ); + my $item1 = $builder->build_sample_item( { biblionumber => $biblio->biblionumber } ); + my $item2 = $builder->build_sample_item( { biblionumber => $biblio->biblionumber } ); + my $item3 = $builder->build_sample_item( { biblionumber => $biblio->biblionumber } ); - { # Is not a serial + { # Is not a serial # order_by homebranch.branchname $item1->discard_changes->update( { homebranch => $library_z->branchcode } ); $item2->discard_changes->update( { homebranch => $library_a->branchcode } ); $item3->discard_changes->update( { homebranch => $library_z->branchcode } ); - is_deeply( [ map { $_->itemnumber } $biblio->items->search_ordered->as_list ], + is_deeply( + [ map { $_->itemnumber } $biblio->items->search_ordered->as_list ], [ $item2->itemnumber, $item1->itemnumber, $item3->itemnumber ], - "not a serial - order by homebranch" ); + "not a serial - order by homebranch" + ); # order_by me.enumchron $biblio->items->update( { homebranch => $library_a->branchcode } ); $item1->discard_changes->update( { enumchron => 'cc' } ); $item2->discard_changes->update( { enumchron => 'bb' } ); $item3->discard_changes->update( { enumchron => 'aa' } ); - is_deeply( [ map { $_->itemnumber } $biblio->items->search_ordered->as_list ], + is_deeply( + [ map { $_->itemnumber } $biblio->items->search_ordered->as_list ], [ $item3->itemnumber, $item2->itemnumber, $item1->itemnumber ], - "not a serial - order by enumchron" ); + "not a serial - order by enumchron" + ); # order_by -desc => 'me.dateaccessioned' $biblio->items->update( { enumchron => undef } ); $item1->discard_changes->update( { dateaccessioned => '2022-08-19' } ); $item2->discard_changes->update( { dateaccessioned => '2022-07-19' } ); $item3->discard_changes->update( { dateaccessioned => '2022-09-19' } ); - is_deeply( [ map { $_->itemnumber } $biblio->items->search_ordered->as_list ], + is_deeply( + [ map { $_->itemnumber } $biblio->items->search_ordered->as_list ], [ $item3->itemnumber, $item1->itemnumber, $item2->itemnumber ], - "not a serial - order by date accessioned desc" ); + "not a serial - order by date accessioned desc" + ); } { # Is a serial - my $sub_freq = $builder->build( { source => 'SubscriptionFrequency' } ); - my $sub_np = - $builder->build( { source => 'SubscriptionNumberpattern' } ); + my $sub_freq = $builder->build( { source => 'SubscriptionFrequency' } ); + my $sub_np = $builder->build( { source => 'SubscriptionNumberpattern' } ); my $subscription = $builder->build_object( { class => 'Koha::Subscriptions', value => { - biblionumber => $biblio->biblionumber, - periodicity => $sub_freq->{id}, - numberpattern => $sub_np->{id}, + biblionumber => $biblio->biblionumber, + periodicity => $sub_freq->{id}, + numberpattern => $sub_np->{id}, published_on_template => "[% publisheddatetext %] [% biblionumber %]", } } @@ -1946,20 +2133,23 @@ subtest 'search_ordered' => sub { ); $biblio->update( { serial => 1 } ); - my $serialid1 = - C4::Serials::NewIssue( "serialseq", $subscription->subscriptionid, + my $serialid1 = C4::Serials::NewIssue( + "serialseq", $subscription->subscriptionid, $biblio->biblionumber, 1, undef, undef, "publisheddatetext", - "notes", "routingnotes" ); + "notes", "routingnotes" + ); C4::Serials::AddItem2Serial( $serialid1, $item1->itemnumber ); - my $serialid2 = - C4::Serials::NewIssue( "serialseq", $subscription->subscriptionid, + my $serialid2 = C4::Serials::NewIssue( + "serialseq", $subscription->subscriptionid, $biblio->biblionumber, 1, undef, undef, "publisheddatetext", - "notes", "routingnotes" ); + "notes", "routingnotes" + ); C4::Serials::AddItem2Serial( $serialid2, $item2->itemnumber ); - my $serialid3 = - C4::Serials::NewIssue( "serialseq", $subscription->subscriptionid, + my $serialid3 = C4::Serials::NewIssue( + "serialseq", $subscription->subscriptionid, $biblio->biblionumber, 1, undef, undef, "publisheddatetext", - "notes", "routingnotes" ); + "notes", "routingnotes" + ); C4::Serials::AddItem2Serial( $serialid3, $item3->itemnumber ); my $serial1 = Koha::Serials->find($serialid1); my $serial2 = Koha::Serials->find($serialid2); @@ -1976,19 +2166,30 @@ subtest 'search_ordered' => sub { ); # order_by me.enumchron - $serial1->discard_changes->update({ publisheddate => '2022-08-19' }); - $serial2->discard_changes->update({ publisheddate => '2022-08-19' }); - $serial3->discard_changes->update({ publisheddate => '2022-08-19' }); + $serial1->discard_changes->update( { publisheddate => '2022-08-19' } ); + $serial2->discard_changes->update( { publisheddate => '2022-08-19' } ); + $serial3->discard_changes->update( { publisheddate => '2022-08-19' } ); $item1->discard_changes->update( { enumchron => 'cc' } ); $item2->discard_changes->update( { enumchron => 'bb' } ); $item3->discard_changes->update( { enumchron => 'aa' } ); - is_deeply( [ map { $_->itemnumber } $biblio->items->search_ordered->as_list ], + is_deeply( + [ map { $_->itemnumber } $biblio->items->search_ordered->as_list ], [ $item3->itemnumber, $item2->itemnumber, $item1->itemnumber ], - "serial - order by enumchron" ); + "serial - order by enumchron" + ); - is( $serial1->publisheddatetext, "publisheddatetext " . $biblio->biblionumber, "Column publisheddatetext rendered correctly from template for serial1" ); - is( $serial2->publisheddatetext, "publisheddatetext " . $biblio->biblionumber, "Column publisheddatetext rendered correctly from template for serial2" ); - is( $serial3->publisheddatetext, "publisheddatetext " . $biblio->biblionumber, "Column publisheddatetext rendered correctly from template for serial3" ); + is( + $serial1->publisheddatetext, "publisheddatetext " . $biblio->biblionumber, + "Column publisheddatetext rendered correctly from template for serial1" + ); + is( + $serial2->publisheddatetext, "publisheddatetext " . $biblio->biblionumber, + "Column publisheddatetext rendered correctly from template for serial2" + ); + is( + $serial3->publisheddatetext, "publisheddatetext " . $biblio->biblionumber, + "Column publisheddatetext rendered correctly from template for serial3" + ); } @@ -2025,8 +2226,8 @@ subtest 'filter_by_for_hold' => sub { ); my $biblio = $builder->build_sample_biblio; - my $library = $builder->build_object({ class => 'Koha::Libraries' }); - t::lib::Mocks::mock_preference('IndependentBranches', 0); # more robust tests + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); + t::lib::Mocks::mock_preference( 'IndependentBranches', 0 ); # more robust tests is( $biblio->items->filter_by_for_hold->count, 0, 'no item yet' ); $builder->build_sample_item( { biblionumber => $biblio->biblionumber, notforloan => 0, itype => $not_holdable_itemtype } ); @@ -2138,10 +2339,10 @@ subtest 'filter_by_for_hold' => sub { ); Koha::CirculationRules->set_rule( { - branchcode => undef, - itemtype => $not_holdable_itemtype, - rule_name => 'holdallowed', - rule_value => 'not_allowed', + branchcode => undef, + itemtype => $not_holdable_itemtype, + rule_name => 'holdallowed', + rule_value => 'not_allowed', } ); is( $biblio->items->filter_by_for_hold->count, 6, '6 items for hold - holdallowed=not_allowed' ); @@ -2149,10 +2350,10 @@ subtest 'filter_by_for_hold' => sub { # Remove rule, test notforloan on itemtype Koha::CirculationRules->set_rule( { - branchcode => undef, - itemtype => $not_holdable_itemtype, - rule_name => 'holdallowed', - rule_value => undef, + branchcode => undef, + itemtype => $not_holdable_itemtype, + rule_name => 'holdallowed', + rule_value => undef, } ); is( $biblio->items->filter_by_for_hold->count, 7, '7 items for hold - rule deleted' ); @@ -2166,11 +2367,11 @@ subtest 'filter_by_for_hold' => sub { is( $biblio->items->filter_by_for_hold->count, 2, '2 items for hold, filtered by IndependentBranches' ); } - t::lib::Mocks::mock_preference('item-level_itypes', 0); + t::lib::Mocks::mock_preference( 'item-level_itypes', 0 ); $biblio->biblioitem->itemtype($not_holdable_itemtype)->store; is( $biblio->items->filter_by_for_hold->count, 0, '0 item-level_itypes=0' ); - t::lib::Mocks::mock_preference('item-level_itypes', 1); + t::lib::Mocks::mock_preference( 'item-level_itypes', 1 ); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/Koha/Items/BatchUpdate.t b/t/db_dependent/Koha/Items/BatchUpdate.t index af6e5b6c43..eaba531711 100755 --- a/t/db_dependent/Koha/Items/BatchUpdate.t +++ b/t/db_dependent/Koha/Items/BatchUpdate.t @@ -16,7 +16,7 @@ # along with Koha; if not, see <http://www.gnu.org/licenses>. use Modern::Perl; -use Test::More tests=> 8; +use Test::More tests => 8; use Test::Warn; use utf8; @@ -35,7 +35,7 @@ $schema->storage->txn_begin; my $builder = t::lib::TestBuilder->new; -Koha::Caches->get_instance->clear_from_cache( "MarcStructure-1-" ); +Koha::Caches->get_instance->clear_from_cache("MarcStructure-1-"); # 952 $x $é $y are not linked with a kohafield # $952$x $é repeatable @@ -44,45 +44,41 @@ Koha::Caches->get_instance->clear_from_cache( "MarcStructure-1-" ); # 952$t is linked with items.copynumber and is not repeatable setup_mss(); -my $biblio = $builder->build_sample_biblio({ frameworkcode => '' }); -my $item = $builder->build_sample_item({ biblionumber => $biblio->biblionumber }); +my $biblio = $builder->build_sample_biblio( { frameworkcode => '' } ); +my $item = $builder->build_sample_item( { biblionumber => $biblio->biblionumber } ); -my $items = Koha::Items->search({itemnumber => $item->itemnumber}); +my $items = Koha::Items->search( { itemnumber => $item->itemnumber } ); subtest 'MARC subfield linked with kohafield' => sub { plan tests => 9; - $items->batch_update({ - new_values => {itemnotes => 'new note'} - }); + $items->batch_update( { new_values => { itemnotes => 'new note' } } ); $items->reset; $item = $item->get_from_storage; - is( $item->itemnotes, 'new note' ); + is( $item->itemnotes, 'new note' ); is( $item->as_marc_field->subfield('t'), undef ); - is( $items->batch_update({ - new_values => {itemnotes=> 'another note'} - })->count, 1, 'Can be chained'); + is( $items->batch_update( { new_values => { itemnotes => 'another note' } } )->count, 1, 'Can be chained' ); $items->reset; - $items->batch_update({new_values => {itemnotes=> undef }})->reset; + $items->batch_update( { new_values => { itemnotes => undef } } )->reset; $item = $item->get_from_storage; - is( $item->itemnotes, undef, "blank" ); + is( $item->itemnotes, undef, "blank" ); is( $item->as_marc_field->subfield('t'), undef, '' ); - $items->batch_update({new_values => {itemnotes=> 'new note', copynumber => 'new copynumber'}})->reset; + $items->batch_update( { new_values => { itemnotes => 'new note', copynumber => 'new copynumber' } } )->reset; $item = $item->get_from_storage; - is( $item->itemnotes, 'new note', "multi" ); - is( $item->as_marc_field->subfield('z'), 'new note', '' ); - is( $item->copynumber, 'new copynumber', "multi" ); + is( $item->itemnotes, 'new note', "multi" ); + is( $item->as_marc_field->subfield('z'), 'new note', '' ); + is( $item->copynumber, 'new copynumber', "multi" ); is( $item->as_marc_field->subfield('t'), 'new copynumber', '' ); }; subtest 'More marc subfields (no linked)' => sub { plan tests => 1; - $items->batch_update({new_values => {x => 'new xxx' }})->reset; + $items->batch_update( { new_values => { x => 'new xxx' } } )->reset; is( $item->get_from_storage->as_marc_field->subfield('x'), 'new xxx' ); }; @@ -92,23 +88,35 @@ subtest 'repeatable' => sub { subtest 'linked' => sub { plan tests => 4; - $items->batch_update({new_values => {itemnotes => 'new zzz 1|new zzz 2' }})->reset; - is( $item->get_from_storage->itemnotes, 'new zzz 1|new zzz 2'); - is_deeply( [$item->get_from_storage->as_marc_field->subfield('z')], ['new zzz 1', 'new zzz 2'], 'z is repeatable' ); + $items->batch_update( { new_values => { itemnotes => 'new zzz 1|new zzz 2' } } )->reset; + is( $item->get_from_storage->itemnotes, 'new zzz 1|new zzz 2' ); + is_deeply( + [ $item->get_from_storage->as_marc_field->subfield('z') ], [ 'new zzz 1', 'new zzz 2' ], + 'z is repeatable' + ); - $items->batch_update({new_values => {copynumber => 'new ttt 1|new ttt 2' }})->reset; - is( $item->get_from_storage->copynumber, 'new ttt 1|new ttt 2'); - is_deeply( [$item->get_from_storage->as_marc_field->subfield('t')], ['new ttt 1|new ttt 2'], 't is not repeatable' ); + $items->batch_update( { new_values => { copynumber => 'new ttt 1|new ttt 2' } } )->reset; + is( $item->get_from_storage->copynumber, 'new ttt 1|new ttt 2' ); + is_deeply( + [ $item->get_from_storage->as_marc_field->subfield('t') ], ['new ttt 1|new ttt 2'], + 't is not repeatable' + ); }; subtest 'not linked' => sub { plan tests => 2; - $items->batch_update({new_values => {x => 'new xxx 1|new xxx 2' }})->reset; - is_deeply( [$item->get_from_storage->as_marc_field->subfield('x')], ['new xxx 1', 'new xxx 2'], 'i is repeatable' ); + $items->batch_update( { new_values => { x => 'new xxx 1|new xxx 2' } } )->reset; + is_deeply( + [ $item->get_from_storage->as_marc_field->subfield('x') ], [ 'new xxx 1', 'new xxx 2' ], + 'i is repeatable' + ); - $items->batch_update({new_values => {y => 'new yyy 1|new yyy 2' }})->reset; - is_deeply( [$item->get_from_storage->as_marc_field->subfield('y')], ['new yyy 1|new yyy 2'], 'y is not repeatable' ); + $items->batch_update( { new_values => { y => 'new yyy 1|new yyy 2' } } )->reset; + is_deeply( + [ $item->get_from_storage->as_marc_field->subfield('y') ], ['new yyy 1|new yyy 2'], + 'y is not repeatable' + ); }; }; @@ -141,8 +149,10 @@ subtest 'blank' => sub { is( $item->itemnotes, undef ); is( $item->copynumber, undef ); is( $item->as_marc_field->subfield('x'), undef ); - is_deeply( [ $item->as_marc_field->subfield('y') ], - ['new yyy 1|new yyy 2'] ); + is_deeply( + [ $item->as_marc_field->subfield('y') ], + ['new yyy 1|new yyy 2'] + ); $items->batch_update( { @@ -176,12 +186,7 @@ subtest 'regex' => sub { replace => 'awesome', modifiers => '', }; - $items->batch_update( - { - regex_mod => - { itemnotes => $re, copynumber => $re, x => $re, y => $re } - } - )->reset; + $items->batch_update( { regex_mod => { itemnotes => $re, copynumber => $re, x => $re, y => $re } } )->reset; $item = $item->get_from_storage; is( $item->itemnotes, 'awesome notes 1|new notes 2' ); is_deeply( @@ -191,8 +196,10 @@ subtest 'regex' => sub { ); is( $item->copynumber, 'awesome cn 1|new cn 2' ); - is_deeply( [ $item->as_marc_field->subfield('t') ], - ['awesome cn 1|new cn 2'], 't is not repeatable' ); + is_deeply( + [ $item->as_marc_field->subfield('t') ], + ['awesome cn 1|new cn 2'], 't is not repeatable' + ); is_deeply( [ $item->as_marc_field->subfield('x') ], @@ -211,12 +218,7 @@ subtest 'regex' => sub { replace => '$1ness', modifiers => '', }; - $items->batch_update( - { - regex_mod => - { itemnotes => $re, copynumber => $re, x => $re, y => $re } - } - )->reset; + $items->batch_update( { regex_mod => { itemnotes => $re, copynumber => $re, x => $re, y => $re } } )->reset; $item = $item->get_from_storage; is( $item->itemnotes, 'awesomeness notes 1|new notes 2' ); is_deeply( @@ -226,8 +228,10 @@ subtest 'regex' => sub { ); is( $item->copynumber, 'awesomeness cn 1|new cn 2' ); - is_deeply( [ $item->as_marc_field->subfield('t') ], - ['awesomeness cn 1|new cn 2'], 't is not repeatable' ); + is_deeply( + [ $item->as_marc_field->subfield('t') ], + ['awesomeness cn 1|new cn 2'], 't is not repeatable' + ); is_deeply( [ $item->as_marc_field->subfield('x') ], @@ -245,9 +249,7 @@ subtest 'regex' => sub { subtest 'encoding' => sub { plan tests => 1; - $items->batch_update({ - new_values => { 'é' => 'new note é'} - }); + $items->batch_update( { new_values => { 'é' => 'new note é' } } ); $items->reset; $item = $item->get_from_storage; @@ -257,24 +259,25 @@ subtest 'encoding' => sub { subtest 'mark_items_returned' => sub { plan tests => 2; - my $circ = Test::MockModule->new( 'C4::Circulation' ); - $circ->mock( 'MarkIssueReturned', sub { - warn "MarkIssueReturned"; - }); + my $circ = Test::MockModule->new('C4::Circulation'); + $circ->mock( + 'MarkIssueReturned', + sub { + warn "MarkIssueReturned"; + } + ); - my $issue = $builder->build_object({class => 'Koha::Checkouts'}); - my $items = Koha::Items->search({ itemnumber => $issue->itemnumber }); + my $issue = $builder->build_object( { class => 'Koha::Checkouts' } ); + my $items = Koha::Items->search( { itemnumber => $issue->itemnumber } ); - warning_is - { $items->batch_update({new_values => {},mark_items_returned => 1}) } - qq{MarkIssueReturned}, + warning_is { $items->batch_update( { new_values => {}, mark_items_returned => 1 } ) } + qq{MarkIssueReturned}, "MarkIssueReturned called for item"; $items->reset; - warning_is - { $items->batch_update({new_values => {},mark_items_returned => 0}) } - qq{}, + warning_is { $items->batch_update( { new_values => {}, mark_items_returned => 0 } ) } + qq{}, "MarkIssueReturned not called for item"; }; @@ -282,51 +285,34 @@ subtest 'mark_items_returned' => sub { subtest 'report' => sub { plan tests => 5; - my $item_1 = - $builder->build_sample_item( { biblionumber => $biblio->biblionumber } ); - my $item_2 = - $builder->build_sample_item( { biblionumber => $biblio->biblionumber } ); + my $item_1 = $builder->build_sample_item( { biblionumber => $biblio->biblionumber } ); + my $item_2 = $builder->build_sample_item( { biblionumber => $biblio->biblionumber } ); - my $items = Koha::Items->search( - { itemnumber => [ $item_1->itemnumber, $item_2->itemnumber ] } ); + my $items = Koha::Items->search( { itemnumber => [ $item_1->itemnumber, $item_2->itemnumber ] } ); - my ($report) = $items->batch_update( - { - new_values => { itemnotes => 'new note' } - } - ); + my ($report) = $items->batch_update( { new_values => { itemnotes => 'new note' } } ); $items->reset; is_deeply( $report, { - modified_itemnumbers => - [ $item_1->itemnumber, $item_2->itemnumber ], - modified_fields => 2 + modified_itemnumbers => [ $item_1->itemnumber, $item_2->itemnumber ], + modified_fields => 2 } ); - ($report) = $items->batch_update( - { - new_values => { itemnotes => 'new note', copynumber => 'new cn' } - } - ); + ($report) = $items->batch_update( { new_values => { itemnotes => 'new note', copynumber => 'new cn' } } ); $items->reset; is_deeply( $report, { - modified_itemnumbers => - [ $item_1->itemnumber, $item_2->itemnumber ], - modified_fields => 2 + modified_itemnumbers => [ $item_1->itemnumber, $item_2->itemnumber ], + modified_fields => 2 } ); $item_1->get_from_storage->update( { itemnotes => 'not new note' } ); - ($report) = $items->batch_update( - { - new_values => { itemnotes => 'new note', copynumber => 'new cn' } - } - ); + ($report) = $items->batch_update( { new_values => { itemnotes => 'new note', copynumber => 'new cn' } } ); $items->reset; is_deeply( @@ -337,19 +323,14 @@ subtest 'report' => sub { } ); - ($report) = $items->batch_update( - { - new_values => { x => 'new xxx', y => 'new yyy' } - } - ); + ($report) = $items->batch_update( { new_values => { x => 'new xxx', y => 'new yyy' } } ); $items->reset; is_deeply( $report, { - modified_itemnumbers => - [ $item_1->itemnumber, $item_2->itemnumber ], - modified_fields => 4 + modified_itemnumbers => [ $item_1->itemnumber, $item_2->itemnumber ], + modified_fields => 4 } ); @@ -360,36 +341,30 @@ subtest 'report' => sub { }; $item_2->get_from_storage->update( { itemnotes => 'awesome note' } ); - ($report) = $items->batch_update( - { - regex_mod => - { itemnotes => $re, copynumber => $re, x => $re, y => $re } - } - ); + ($report) = $items->batch_update( { regex_mod => { itemnotes => $re, copynumber => $re, x => $re, y => $re } } ); $items->reset; is_deeply( $report, { - modified_itemnumbers => - [ $item_1->itemnumber, $item_2->itemnumber ], - modified_fields => 7 + modified_itemnumbers => [ $item_1->itemnumber, $item_2->itemnumber ], + modified_fields => 7 } ); }; -Koha::Caches->get_instance->clear_from_cache( "MarcStructure-1-" ); +Koha::Caches->get_instance->clear_from_cache("MarcStructure-1-"); sub setup_mss { - my ( $itemtag, $itemsubfield ) = C4::Biblio::GetMarcFromKohaField( "items.itemnumber" ); + my ( $itemtag, $itemsubfield ) = C4::Biblio::GetMarcFromKohaField("items.itemnumber"); Koha::MarcSubfieldStructures->search( { frameworkcode => '', - tagfield => $itemtag, - tagsubfield => 'é', + tagfield => $itemtag, + tagsubfield => 'é', } )->delete; # In case it exist already @@ -415,31 +390,31 @@ sub setup_mss { Koha::MarcSubfieldStructures->search( { frameworkcode => '', - tagfield => $itemtag, - tagsubfield => [ 'x', 'é' ], + tagfield => $itemtag, + tagsubfield => [ 'x', 'é' ], } )->update( { repeatable => 1 } ); Koha::MarcSubfieldStructures->search( { frameworkcode => '', - tagfield => $itemtag, - tagsubfield => ['t'], + tagfield => $itemtag, + tagsubfield => ['t'], } )->update( { repeatable => 0 } ); Koha::MarcSubfieldStructures->search( { frameworkcode => '', - tagfield => $itemtag, - tagsubfield => ['z'], + tagfield => $itemtag, + tagsubfield => ['z'], } )->update( { kohafield => 'items.itemnotes', repeatable => 1 } ); Koha::MarcSubfieldStructures->search( { frameworkcode => '', - tagfield => $itemtag, + tagfield => $itemtag, } )->update( { display_order => \['FLOOR( 1 + RAND( ) * 10 )'] } ); } diff --git a/t/db_dependent/Koha/KeyboardShortcuts.t b/t/db_dependent/Koha/KeyboardShortcuts.t index fc98a1b933..32e15fda1a 100755 --- a/t/db_dependent/Koha/KeyboardShortcuts.t +++ b/t/db_dependent/Koha/KeyboardShortcuts.t @@ -31,7 +31,7 @@ BEGIN { my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; -my $builder = t::lib::TestBuilder->new; +my $builder = t::lib::TestBuilder->new; my $nb_of_shortcuts = Koha::KeyboardShortcuts->search->count; my $shortcut_hash = { @@ -40,12 +40,12 @@ my $shortcut_hash = { }; my $new_shortcut = Koha::KeyboardShortcut->new($shortcut_hash)->store; -is( Koha::KeyboardShortcuts->count, $nb_of_shortcuts + 1, 'Adding a new shortcut increases count'); +is( Koha::KeyboardShortcuts->count, $nb_of_shortcuts + 1, 'Adding a new shortcut increases count' ); -my $found_shortcut = Koha::KeyboardShortcuts->find( "this_cut" ); -is_deeply( $found_shortcut->unblessed, $shortcut_hash, 'We find the right object'); +my $found_shortcut = Koha::KeyboardShortcuts->find("this_cut"); +is_deeply( $found_shortcut->unblessed, $shortcut_hash, 'We find the right object' ); $found_shortcut->delete; -is( Koha::KeyboardShortcuts->count, $nb_of_shortcuts, 'Deleting a new shortcut works'); +is( Koha::KeyboardShortcuts->count, $nb_of_shortcuts, 'Deleting a new shortcut works' ); $schema->storage->txn_rollback; diff --git a/t/db_dependent/Koha/Libraries.t b/t/db_dependent/Koha/Libraries.t index 5c746d679d..4212ff4feb 100755 --- a/t/db_dependent/Koha/Libraries.t +++ b/t/db_dependent/Koha/Libraries.t @@ -40,51 +40,63 @@ my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; # Cleanup default_branch_item_rules -my $dbh = C4::Context->dbh; +my $dbh = C4::Context->dbh; $dbh->do('DELETE FROM circulation_rules'); -my $builder = t::lib::TestBuilder->new; +my $builder = t::lib::TestBuilder->new; my $nb_of_libraries = Koha::Libraries->search->count; -my $new_library_1 = Koha::Library->new({ - branchcode => 'my_bc_1', - branchname => 'my_branchname_1', - branchnotes => 'my_branchnotes_1', - marcorgcode => 'US-MyLib', -})->store; -my $new_library_2 = Koha::Library->new({ - branchcode => 'my_bc_2', - branchname => 'my_branchname_2', - branchnotes => 'my_branchnotes_2', -})->store; +my $new_library_1 = Koha::Library->new( + { + branchcode => 'my_bc_1', + branchname => 'my_branchname_1', + branchnotes => 'my_branchnotes_1', + marcorgcode => 'US-MyLib', + } +)->store; +my $new_library_2 = Koha::Library->new( + { + branchcode => 'my_bc_2', + branchname => 'my_branchname_2', + branchnotes => 'my_branchnotes_2', + } +)->store; -is( Koha::Libraries->search->count, $nb_of_libraries + 2, 'The 2 libraries should have been added' ); +is( Koha::Libraries->search->count, $nb_of_libraries + 2, 'The 2 libraries should have been added' ); my $retrieved_library_1 = Koha::Libraries->find( $new_library_1->branchcode ); -is( $retrieved_library_1->branchname, $new_library_1->branchname, 'Find a library by branchcode should return the correct library' ); +is( + $retrieved_library_1->branchname, $new_library_1->branchname, + 'Find a library by branchcode should return the correct library' +); $retrieved_library_1->delete; is( Koha::Libraries->search->count, $nb_of_libraries + 1, 'Delete should have deleted the library' ); # Stockrotation relationship testing -my $new_library_sr = $builder->build({ source => 'Branch' }); +my $new_library_sr = $builder->build( { source => 'Branch' } ); -$builder->build({ - source => 'Stockrotationstage', - value => { branchcode_id => $new_library_sr->{branchcode} }, -}); -$builder->build({ - source => 'Stockrotationstage', - value => { branchcode_id => $new_library_sr->{branchcode} }, -}); -$builder->build({ - source => 'Stockrotationstage', - value => { branchcode_id => $new_library_sr->{branchcode} }, -}); +$builder->build( + { + source => 'Stockrotationstage', + value => { branchcode_id => $new_library_sr->{branchcode} }, + } +); +$builder->build( + { + source => 'Stockrotationstage', + value => { branchcode_id => $new_library_sr->{branchcode} }, + } +); +$builder->build( + { + source => 'Stockrotationstage', + value => { branchcode_id => $new_library_sr->{branchcode} }, + } +); -my $srstages = Koha::Libraries->find($new_library_sr->{branchcode}) - ->stockrotationstages; -is( $srstages->count, 3, 'Correctly fetched stockrotationstages associated with this branch'); +my $srstages = Koha::Libraries->find( $new_library_sr->{branchcode} )->stockrotationstages; +is( $srstages->count, 3, 'Correctly fetched stockrotationstages associated with this branch' ); isa_ok( $srstages->next, 'Koha::StockRotationStage', "Relationship correctly creates Koha::Objects." ); @@ -96,25 +108,41 @@ subtest '->get_effective_marcorgcode' => sub { $schema->storage->txn_begin; - my $library_1 = $builder->build_object({ class => 'Koha::Libraries', - value => { marcorgcode => 'US-MyLib' } }); - my $library_2 = $builder->build_object({ class => 'Koha::Libraries', - value => { marcorgcode => undef } }); + my $library_1 = $builder->build_object( + { + class => 'Koha::Libraries', + value => { marcorgcode => 'US-MyLib' } + } + ); + my $library_2 = $builder->build_object( + { + class => 'Koha::Libraries', + value => { marcorgcode => undef } + } + ); - t::lib::Mocks::mock_preference('MARCOrgCode', 'US-Default'); + t::lib::Mocks::mock_preference( 'MARCOrgCode', 'US-Default' ); - is( $library_1->get_effective_marcorgcode, 'US-MyLib', - 'If defined, use library\'s own marc org code'); - is( $library_2->get_effective_marcorgcode, 'US-Default', - 'If not defined library\' marc org code, use the one from system preferences'); + is( + $library_1->get_effective_marcorgcode, 'US-MyLib', + 'If defined, use library\'s own marc org code' + ); + is( + $library_2->get_effective_marcorgcode, 'US-Default', + 'If not defined library\' marc org code, use the one from system preferences' + ); - t::lib::Mocks::mock_preference('MARCOrgCode', 'Blah'); - is( $library_2->get_effective_marcorgcode, 'Blah', - 'Fallback is always MARCOrgCode syspref'); + t::lib::Mocks::mock_preference( 'MARCOrgCode', 'Blah' ); + is( + $library_2->get_effective_marcorgcode, 'Blah', + 'Fallback is always MARCOrgCode syspref' + ); $library_2->marcorgcode('ThisIsACode')->store(); - is( $library_2->get_effective_marcorgcode, 'ThisIsACode', - 'Pick library_2 code'); + is( + $library_2->get_effective_marcorgcode, 'ThisIsACode', + 'Pick library_2 code' + ); $schema->storage->txn_rollback; }; @@ -129,23 +157,29 @@ subtest '->from_email_address' => sub { { class => 'Koha::Libraries', value => { - branchemail => 'from@mybranc.com', + branchemail => 'from@mybranc.com', } } ); t::lib::Mocks::mock_preference( 'KohaAdminEmailAddress', 'admin@mylibrary.com' ); - is( $library_1->from_email_address, $library_1->branchemail, - 'If defined, use branches branchemail address'); + is( + $library_1->from_email_address, $library_1->branchemail, + 'If defined, use branches branchemail address' + ); $library_1->branchemail(undef)->store(); - is( $library_1->from_email_address, 'admin@mylibrary.com', - 'Fallback to KohaAdminEmailAddress email address when branchemail is undefined'); + is( + $library_1->from_email_address, 'admin@mylibrary.com', + 'Fallback to KohaAdminEmailAddress email address when branchemail is undefined' + ); t::lib::Mocks::mock_preference( 'KohaAdminEmailAddress', '' ); - is( $library_1->from_email_address, undef, - 'Return undef when branchemail and KohaAdminEmailAddress are both undefined'); + is( + $library_1->from_email_address, undef, + 'Return undef when branchemail and KohaAdminEmailAddress are both undefined' + ); $schema->storage->txn_rollback; }; @@ -166,26 +200,36 @@ subtest '->inbound_email_address' => sub { ); t::lib::Mocks::mock_preference( 'KohaAdminEmailAddress', 'admin@mylibrary.com' ); - t::lib::Mocks::mock_preference( 'ReplytoDefault', 'reply@mylibrary.com' ); + t::lib::Mocks::mock_preference( 'ReplytoDefault', 'reply@mylibrary.com' ); - is( $library_1->inbound_email_address, $library_1->branchreplyto, - 'If defined, use branches replyto address'); + is( + $library_1->inbound_email_address, $library_1->branchreplyto, + 'If defined, use branches replyto address' + ); $library_1->branchreplyto(undef)->store(); - is( $library_1->inbound_email_address, $library_1->branchemail, - 'Fallback to branches email address when branchreplyto is undefined'); + is( + $library_1->inbound_email_address, $library_1->branchemail, + 'Fallback to branches email address when branchreplyto is undefined' + ); $library_1->branchemail(undef)->store(); - is( $library_1->inbound_email_address, 'reply@mylibrary.com', - 'Fallback to ReplytoDefault email address when branchreplyto and branchemail are undefined'); + is( + $library_1->inbound_email_address, 'reply@mylibrary.com', + 'Fallback to ReplytoDefault email address when branchreplyto and branchemail are undefined' + ); t::lib::Mocks::mock_preference( 'ReplytoDefault', '' ); - is( $library_1->inbound_email_address, 'admin@mylibrary.com', - 'Fallback to KohaAdminEmailAddress email address when branchreplyto, branchemail and ReplytoDefault are undefined'); + is( + $library_1->inbound_email_address, 'admin@mylibrary.com', + 'Fallback to KohaAdminEmailAddress email address when branchreplyto, branchemail and ReplytoDefault are undefined' + ); t::lib::Mocks::mock_preference( 'KohaAdminEmailAddress', '' ); - is( $library_1->inbound_email_address, undef, - 'Return undef when email address when branchreplyto, branchemail, ReplytoDefault and KohaAdminEmailAddress are undefined'); + is( + $library_1->inbound_email_address, undef, + 'Return undef when email address when branchreplyto, branchemail, ReplytoDefault and KohaAdminEmailAddress are undefined' + ); $schema->storage->txn_rollback; }; @@ -199,43 +243,57 @@ subtest '->inbound_ill_address' => sub { { class => 'Koha::Libraries', value => { - branchemail => 'from@mylibrary.com', - branchreplyto => 'reply@mylibrary.com', + branchemail => 'from@mylibrary.com', + branchreplyto => 'reply@mylibrary.com', branchillemail => 'ill@mylibrary.com' } } ); t::lib::Mocks::mock_preference( 'KohaAdminEmailAddress', 'admin@mylibrary.com' ); - t::lib::Mocks::mock_preference( 'ReplytoDefault', 'reply@mylibrary.com' ); - t::lib::Mocks::mock_preference( 'ILLDefaultStaffEmail', 'illdefault@mylibrary.com' ); + t::lib::Mocks::mock_preference( 'ReplytoDefault', 'reply@mylibrary.com' ); + t::lib::Mocks::mock_preference( 'ILLDefaultStaffEmail', 'illdefault@mylibrary.com' ); - is( $library_1->inbound_ill_address, $library_1->branchillemail, - 'If defined, use library branchillemail address'); + is( + $library_1->inbound_ill_address, $library_1->branchillemail, + 'If defined, use library branchillemail address' + ); $library_1->branchillemail(undef)->store(); - is( $library_1->inbound_ill_address, 'illdefault@mylibrary.com', - 'Fallback to ILLDefaultStaffEmail preference when branchillemail is undefined'); + is( + $library_1->inbound_ill_address, 'illdefault@mylibrary.com', + 'Fallback to ILLDefaultStaffEmail preference when branchillemail is undefined' + ); t::lib::Mocks::mock_preference( 'ILLDefaultStaffEmail', undef ); - is( $library_1->inbound_ill_address, $library_1->branchreplyto, - 'Fallback to library replyto address when ILLDefaultStaffEmail is undefined'); + is( + $library_1->inbound_ill_address, $library_1->branchreplyto, + 'Fallback to library replyto address when ILLDefaultStaffEmail is undefined' + ); $library_1->branchreplyto(undef)->store(); - is( $library_1->inbound_ill_address, $library_1->branchemail, - 'Fallback to branches email address when branchreplyto is undefined'); + is( + $library_1->inbound_ill_address, $library_1->branchemail, + 'Fallback to branches email address when branchreplyto is undefined' + ); $library_1->branchemail(undef)->store(); - is( $library_1->inbound_ill_address, 'reply@mylibrary.com', - 'Fallback to ReplytoDefault email address when branchreplyto and branchemail are undefined'); + is( + $library_1->inbound_ill_address, 'reply@mylibrary.com', + 'Fallback to ReplytoDefault email address when branchreplyto and branchemail are undefined' + ); t::lib::Mocks::mock_preference( 'ReplytoDefault', '' ); - is( $library_1->inbound_ill_address, 'admin@mylibrary.com', - 'Fallback to KohaAdminEmailAddress email address when branchreplyto, branchemail and ReplytoDefault are undefined'); + is( + $library_1->inbound_ill_address, 'admin@mylibrary.com', + 'Fallback to KohaAdminEmailAddress email address when branchreplyto, branchemail and ReplytoDefault are undefined' + ); t::lib::Mocks::mock_preference( 'KohaAdminEmailAddress', '' ); - is( $library_1->inbound_ill_address, undef, - 'Return undef when email address when branchreplyto, branchemail, ReplytoDefault and KohaAdminEmailAddress are undefined'); + is( + $library_1->inbound_ill_address, undef, + 'Return undef when email address when branchreplyto, branchemail, ReplytoDefault and KohaAdminEmailAddress are undefined' + ); $schema->storage->txn_rollback; }; @@ -245,30 +303,33 @@ subtest 'cash_registers' => sub { $schema->storage->txn_begin; - my $library = $builder->build_object( { class => 'Koha::Libraries' } ); + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); my $register1 = $builder->build_object( { class => 'Koha::Cash::Registers', - value => { branch => $library->branchcode }, + value => { branch => $library->branchcode }, } ); my $register2 = $builder->build_object( { class => 'Koha::Cash::Registers', - value => { branch => $library->branchcode }, + value => { branch => $library->branchcode }, } ); my $registers = $library->cash_registers; - is( ref($registers), 'Koha::Cash::Registers', -'Koha::Library->cash_registers should return a set of Koha::Cash::Registers' + is( + ref($registers), 'Koha::Cash::Registers', + 'Koha::Library->cash_registers should return a set of Koha::Cash::Registers' ); - is( $registers->count, 2, + is( + $registers->count, 2, 'Koha::Library->cash_registers should return the correct cash registers' ); $register1->delete; - is( $library->cash_registers->next->id, $register2->id, + is( + $library->cash_registers->next->id, $register2->id, 'Koha::Library->cash_registers should return the correct cash registers' ); @@ -289,43 +350,72 @@ subtest 'get_hold_libraries and validate_hold_sibling' => sub { my $root1 = $builder->build_object( { class => 'Koha::Library::Groups', value => { ft_local_hold_group => 1 } } ); my $root2 = $builder->build_object( { class => 'Koha::Library::Groups', value => { ft_local_hold_group => 1 } } ); - # G1 - $builder->build_object( { class => 'Koha::Library::Groups', value => { parent_id => $root1->id, branchcode => $library1->branchcode } } ); - $builder->build_object( { class => 'Koha::Library::Groups', value => { parent_id => $root1->id, branchcode => $library2->branchcode } } ); - # G2 - $builder->build_object( { class => 'Koha::Library::Groups', value => { parent_id => $root2->id, branchcode => $library3->branchcode } } ); - $builder->build_object( { class => 'Koha::Library::Groups', value => { parent_id => $root2->id, branchcode => $library4->branchcode } } ); - $builder->build_object( { class => 'Koha::Library::Groups', value => { parent_id => $root2->id, branchcode => $library5->branchcode } } ); - my @hold_libraries_1 = ($library1, $library2); - my @hold_libraries_2 = ($library3, $library4, $library5); + # G1 + $builder->build_object( + { class => 'Koha::Library::Groups', value => { parent_id => $root1->id, branchcode => $library1->branchcode } } + ); + $builder->build_object( + { class => 'Koha::Library::Groups', value => { parent_id => $root1->id, branchcode => $library2->branchcode } } + ); + + # G2 + $builder->build_object( + { class => 'Koha::Library::Groups', value => { parent_id => $root2->id, branchcode => $library3->branchcode } } + ); + $builder->build_object( + { class => 'Koha::Library::Groups', value => { parent_id => $root2->id, branchcode => $library4->branchcode } } + ); + $builder->build_object( + { class => 'Koha::Library::Groups', value => { parent_id => $root2->id, branchcode => $library5->branchcode } } + ); + + my @hold_libraries_1 = ( $library1, $library2 ); + my @hold_libraries_2 = ( $library3, $library4, $library5 ); my @result = $library1->get_hold_libraries()->as_list; + # library1 and library2 are siblings - is(scalar(@result), 2, 'get_hold_libraries returns 2 libraries'); + is( scalar(@result), 2, 'get_hold_libraries returns 2 libraries' ); - my %map = map {$_->branchcode, 1} @result; + my %map = map { $_->branchcode, 1 } @result; - foreach my $hold_library ( @hold_libraries_1 ) { - ok(exists $map{$hold_library->branchcode}, 'library in hold group'); + foreach my $hold_library (@hold_libraries_1) { + ok( exists $map{ $hold_library->branchcode }, 'library in hold group' ); } @result = $library3->get_hold_libraries()->as_list; + # library3, library4 and library5 are siblings - is(scalar(@result), 3, 'get_hold_libraries returns 3 libraries'); + is( scalar(@result), 3, 'get_hold_libraries returns 3 libraries' ); - %map = map {$_->branchcode, 1} @result; + %map = map { $_->branchcode, 1 } @result; - foreach my $hold_library ( @hold_libraries_2 ) { - ok(exists $map{$hold_library->branchcode}, 'library in hold group'); + foreach my $hold_library (@hold_libraries_2) { + ok( exists $map{ $hold_library->branchcode }, 'library in hold group' ); } - ok($library1->validate_hold_sibling( { branchcode => $library2->branchcode } ), 'Library 2 is a valid hold sibling'); - ok(!$library1->validate_hold_sibling( { branchcode => $library3->branchcode } ), 'Library 3 is not a valid hold sibling'); + ok( + $library1->validate_hold_sibling( { branchcode => $library2->branchcode } ), + 'Library 2 is a valid hold sibling' + ); + ok( + !$library1->validate_hold_sibling( { branchcode => $library3->branchcode } ), + 'Library 3 is not a valid hold sibling' + ); - ok($library3->validate_hold_sibling( { branchcode => $library4->branchcode } ), 'Library 4 is a valid hold sibling'); - ok($library3->validate_hold_sibling( { branchcode => $library5->branchcode } ), 'Library 5 is a valid hold sibling'); - ok(!$library3->validate_hold_sibling( { branchcode => $library2->branchcode } ), 'Library 2 is not a valid hold sibling'); + ok( + $library3->validate_hold_sibling( { branchcode => $library4->branchcode } ), + 'Library 4 is a valid hold sibling' + ); + ok( + $library3->validate_hold_sibling( { branchcode => $library5->branchcode } ), + 'Library 5 is a valid hold sibling' + ); + ok( + !$library3->validate_hold_sibling( { branchcode => $library2->branchcode } ), + 'Library 2 is not a valid hold sibling' + ); $schema->storage->txn_rollback; @@ -384,30 +474,33 @@ subtest 'outgoing_transfers' => sub { $schema->storage->txn_begin; - my $library = $builder->build_object( { class => 'Koha::Libraries' } ); + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); my $transfer1 = $builder->build_object( { class => 'Koha::Item::Transfers', - value => { frombranch => $library->branchcode }, + value => { frombranch => $library->branchcode }, } ); my $transfer2 = $builder->build_object( { class => 'Koha::Item::Transfers', - value => { frombranch => $library->branchcode }, + value => { frombranch => $library->branchcode }, } ); my $outgoing_transfers = $library->outgoing_transfers; - is( ref($outgoing_transfers), 'Koha::Item::Transfers', -'Koha::Library->outgoing_transfers should return a set of Koha::Item::Transfers' + is( + ref($outgoing_transfers), 'Koha::Item::Transfers', + 'Koha::Library->outgoing_transfers should return a set of Koha::Item::Transfers' ); - is( $outgoing_transfers->count, 2, + is( + $outgoing_transfers->count, 2, 'Koha::Library->outgoing_transfers should return the correct number of transfers' ); $transfer1->delete; - is( $library->outgoing_transfers->next->id, $transfer2->id, + is( + $library->outgoing_transfers->next->id, $transfer2->id, 'Koha::Library->outgoing_transfers should return the correct transfers' ); diff --git a/t/db_dependent/Koha/Library.t b/t/db_dependent/Koha/Library.t index 661803d815..c35b1e88e7 100755 --- a/t/db_dependent/Koha/Library.t +++ b/t/db_dependent/Koha/Library.t @@ -36,11 +36,11 @@ subtest 'smtp_server() tests' => sub { $schema->storage->txn_begin; - my $library = $builder->build_object({ class => 'Koha::Libraries' }); - my $smtp_server_1 = $builder->build_object({ class => 'Koha::SMTP::Servers' }); - my $smtp_server_2 = $builder->build_object({ class => 'Koha::SMTP::Servers' }); + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); + my $smtp_server_1 = $builder->build_object( { class => 'Koha::SMTP::Servers' } ); + my $smtp_server_2 = $builder->build_object( { class => 'Koha::SMTP::Servers' } ); - is( ref($library->smtp_server), 'Koha::SMTP::Server', 'Type is correct' ); + is( ref( $library->smtp_server ), 'Koha::SMTP::Server', 'Type is correct' ); is_deeply( $library->smtp_server->unblessed, @@ -48,44 +48,44 @@ subtest 'smtp_server() tests' => sub { 'Fresh library is set the default' ); - my $return = $library->smtp_server({ smtp_server => $smtp_server_1 }); + my $return = $library->smtp_server( { smtp_server => $smtp_server_1 } ); $library->discard_changes; - is( ref($return), 'Koha::Library', 'The setter is chainable' ); - is( ref($library->smtp_server), 'Koha::SMTP::Server', 'Type is correct' ); + is( ref($return), 'Koha::Library', 'The setter is chainable' ); + is( ref( $library->smtp_server ), 'Koha::SMTP::Server', 'Type is correct' ); is_deeply( $library->smtp_server->unblessed, $smtp_server_1->unblessed, 'SMTP server correctly set for library' ); - $return = $library->smtp_server({ smtp_server => $smtp_server_2 }); + $return = $library->smtp_server( { smtp_server => $smtp_server_2 } ); $library->discard_changes; - is( ref($return), 'Koha::Library', 'The setter is chainable' ); - is( ref($library->smtp_server), 'Koha::SMTP::Server', 'Type is correct' ); + is( ref($return), 'Koha::Library', 'The setter is chainable' ); + is( ref( $library->smtp_server ), 'Koha::SMTP::Server', 'Type is correct' ); is_deeply( $library->smtp_server->unblessed, $smtp_server_2->unblessed, 'SMTP server correctly set for library' ); - $return = $library->smtp_server({ smtp_server => undef }); + $return = $library->smtp_server( { smtp_server => undef } ); $library->discard_changes; - is( ref($return), 'Koha::Library', 'The setter is chainable' ); - is( ref($library->smtp_server), 'Koha::SMTP::Server', 'Type is correct' ); + is( ref($return), 'Koha::Library', 'The setter is chainable' ); + is( ref( $library->smtp_server ), 'Koha::SMTP::Server', 'Type is correct' ); is_deeply( $library->smtp_server->unblessed, Koha::SMTP::Servers->get_default->unblessed, 'Resetting makes it return the default' ); - $return = $library->smtp_server({ smtp_server => undef }); + $return = $library->smtp_server( { smtp_server => undef } ); $library->discard_changes; - is( ref($return), 'Koha::Library', 'The setter is chainable' ); - is( ref($library->smtp_server), 'Koha::SMTP::Server', 'Type is correct' ); + is( ref($return), 'Koha::Library', 'The setter is chainable' ); + is( ref( $library->smtp_server ), 'Koha::SMTP::Server', 'Type is correct' ); is_deeply( $library->smtp_server->unblessed, Koha::SMTP::Servers->get_default->unblessed, @@ -98,13 +98,16 @@ subtest 'smtp_server() tests' => sub { subtest 'opac_info tests' => sub { plan tests => 8; $schema->storage->txn_begin; - my $library01 = $builder->build_object({ class => 'Koha::Libraries' }); - my $library02 = $builder->build_object({ class => 'Koha::Libraries' }); + my $library01 = $builder->build_object( { class => 'Koha::Libraries' } ); + my $library02 = $builder->build_object( { class => 'Koha::Libraries' } ); my $html01 = $builder->build_object( { class => 'Koha::AdditionalContents', - value => { category => 'html_customizations', location => 'OpacLibraryInfo', branchcode => undef, expirationdate => undef }, + value => { + category => 'html_customizations', location => 'OpacLibraryInfo', branchcode => undef, + expirationdate => undef + }, } ); $html01->translated_contents( @@ -118,7 +121,10 @@ subtest 'opac_info tests' => sub { my $html02 = $builder->build_object( { class => 'Koha::AdditionalContents', - value => { category => 'html_customizations', location => 'OpacLibraryInfo', branchcode => $library01->id, expirationdate => undef }, + value => { + category => 'html_customizations', location => 'OpacLibraryInfo', branchcode => $library01->id, + expirationdate => undef + }, } ); $html02->translated_contents( @@ -136,7 +142,10 @@ subtest 'opac_info tests' => sub { my $html04 = $builder->build_object( { class => 'Koha::AdditionalContents', - value => { category => 'html_customizations', location => 'OpacLibraryInfo', branchcode => undef, expirationdate => undef }, + value => { + category => 'html_customizations', location => 'OpacLibraryInfo', branchcode => undef, + expirationdate => undef + }, } ); $html04->translated_contents( @@ -149,15 +158,18 @@ subtest 'opac_info tests' => sub { ); # Start testing - is( $library01->opac_info->content, '2', 'specific library, default language' ); - is( $library01->opac_info({ lang => 'nl-NL' })->content, '3', 'specific library, specific language' ); - is( $library01->opac_info({ lang => 'nl-BE' })->content, '2', 'specific library, unknown language' ); - is( $library02->opac_info->content, '1', 'unknown library, default language' ); - is( $library02->opac_info({ lang => 'fr-FR' })->content, '4', 'unknown library, specific language' ); - is( $library02->opac_info({ lang => 'de-DE' })->content, '1', 'unknown library, unknown language' ); + is( $library01->opac_info->content, '2', 'specific library, default language' ); + is( $library01->opac_info( { lang => 'nl-NL' } )->content, '3', 'specific library, specific language' ); + is( $library01->opac_info( { lang => 'nl-BE' } )->content, '2', 'specific library, unknown language' ); + is( $library02->opac_info->content, '1', 'unknown library, default language' ); + is( $library02->opac_info( { lang => 'fr-FR' } )->content, '4', 'unknown library, specific language' ); + is( $library02->opac_info( { lang => 'de-DE' } )->content, '1', 'unknown library, unknown language' ); $html01->delete; is( $library02->opac_info, undef, 'unknown library, default language (after removing html01)' ); - is( $library02->opac_info({ lang => 'de-DE' }), undef, 'unknown library, unknown language (after removing html01)' ); + is( + $library02->opac_info( { lang => 'de-DE' } ), undef, + 'unknown library, unknown language (after removing html01)' + ); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/Koha/Library/OverDriveInfos.t b/t/db_dependent/Koha/Library/OverDriveInfos.t index 02802a3b6a..bc67224844 100755 --- a/t/db_dependent/Koha/Library/OverDriveInfos.t +++ b/t/db_dependent/Koha/Library/OverDriveInfos.t @@ -29,25 +29,31 @@ use t::lib::TestBuilder; my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; -my $builder = t::lib::TestBuilder->new; -my $library1 = $builder->build({ source => 'Branch'}); -my $library2 = $builder->build({ source => 'Branch'}); -my $nb_of_infos = Koha::Library::OverDriveInfos->search->count; -my $new_od_info_1 = Koha::Library::OverDriveInfo->new({ - branchcode => $library1->{'branchcode'}, - authname => 'Gorilla' -})->store; -my $new_od_info_2 = Koha::Library::OverDriveInfo->new({ - branchcode => $library2->{'branchcode'}, - authname => 'Cheese' -})->store; +my $builder = t::lib::TestBuilder->new; +my $library1 = $builder->build( { source => 'Branch' } ); +my $library2 = $builder->build( { source => 'Branch' } ); +my $nb_of_infos = Koha::Library::OverDriveInfos->search->count; +my $new_od_info_1 = Koha::Library::OverDriveInfo->new( + { + branchcode => $library1->{'branchcode'}, + authname => 'Gorilla' + } +)->store; +my $new_od_info_2 = Koha::Library::OverDriveInfo->new( + { + branchcode => $library2->{'branchcode'}, + authname => 'Cheese' + } +)->store; - -is( $new_od_info_1->authname, "Gorilla", 'Adding a new authname should have set the authname'); +is( $new_od_info_1->authname, "Gorilla", 'Adding a new authname should have set the authname' ); is( Koha::Library::OverDriveInfos->search->count, $nb_of_infos + 2, 'The 2 infos should have been added' ); my $retrieved_od_info_1 = Koha::Library::OverDriveInfos->find( $new_od_info_1->branchcode ); -is( $retrieved_od_info_1->authname, $new_od_info_1->authname, 'Find an info by branch should return the correct info' ); +is( + $retrieved_od_info_1->authname, $new_od_info_1->authname, + 'Find an info by branch should return the correct info' +); $retrieved_od_info_1->delete; is( Koha::Library::OverDriveInfos->search->count, $nb_of_infos + 1, 'Delete should have deleted the info' ); diff --git a/t/db_dependent/Koha/MarcSubfieldStructures.t b/t/db_dependent/Koha/MarcSubfieldStructures.t index 7a755d9851..4c05ea653e 100755 --- a/t/db_dependent/Koha/MarcSubfieldStructures.t +++ b/t/db_dependent/Koha/MarcSubfieldStructures.t @@ -32,24 +32,32 @@ $schema->storage->txn_begin; subtest 'Trivial tests' => sub { plan tests => 3; - my $builder = t::lib::TestBuilder->new; + my $builder = t::lib::TestBuilder->new; my $nb_of_fields = Koha::MarcSubfieldStructures->search->count; - my $framework = $builder->build({ source => 'BiblioFramework' }); - my $new_field_1 = Koha::MarcSubfieldStructure->new({ - frameworkcode => $framework->{frameworkcode}, - tagfield => 200, - tagsubfield => 'a', - })->store; - my $new_field_2 = Koha::MarcSubfieldStructure->new({ - frameworkcode => $framework->{frameworkcode}, - tagfield => 245, - tagsubfield => 'a', - })->store; + my $framework = $builder->build( { source => 'BiblioFramework' } ); + my $new_field_1 = Koha::MarcSubfieldStructure->new( + { + frameworkcode => $framework->{frameworkcode}, + tagfield => 200, + tagsubfield => 'a', + } + )->store; + my $new_field_2 = Koha::MarcSubfieldStructure->new( + { + frameworkcode => $framework->{frameworkcode}, + tagfield => 245, + tagsubfield => 'a', + } + )->store; is( Koha::MarcSubfieldStructures->search->count, $nb_of_fields + 2, 'The 2 fields should have been added' ); - my $retrieved_fields = Koha::MarcSubfieldStructures->search({ frameworkcode => $framework->{frameworkcode}, tagfield => 200, tagsubfield => 'a' }); - is( $retrieved_fields->count, 1, 'Search for a field by frameworkcode, tagfield and tagsubfield should return the field' ); + my $retrieved_fields = Koha::MarcSubfieldStructures->search( + { frameworkcode => $framework->{frameworkcode}, tagfield => 200, tagsubfield => 'a' } ); + is( + $retrieved_fields->count, 1, + 'Search for a field by frameworkcode, tagfield and tagsubfield should return the field' + ); $retrieved_fields->next->delete; is( Koha::MarcSubfieldStructures->search->count, $nb_of_fields + 1, 'Delete should have deleted the field' ); diff --git a/t/db_dependent/Koha/Notice_Util.t b/t/db_dependent/Koha/Notice_Util.t index 805d6313ad..233e1a8324 100755 --- a/t/db_dependent/Koha/Notice_Util.t +++ b/t/db_dependent/Koha/Notice_Util.t @@ -18,6 +18,7 @@ # along with Koha; if not, see <http://www.gnu.org/licenses>. use Modern::Perl; + #use Data::Dumper qw/Dumper/; use Test::More tests => 4; use Test::MockModule; @@ -46,15 +47,16 @@ subtest 'load_domain_limits' => sub { is( Koha::Notice::Util->load_domain_limits, undef, 'koha-conf contains blank entry' ); t::lib::Mocks::mock_config( 'message_domain_limits', { domain => { name => 'A', limit => 2, unit => '1d' } } ); $domain_limits = Koha::Notice::Util->load_domain_limits; - is( keys %$domain_limits, 1, 'koha-conf contains one domain' ); - is( $domain_limits->{a}->{limit}, 2, 'check limit of first entry' ); - is( $domain_limits->{a}->{unit}, '1d', 'check unit of first entry' ); - t::lib::Mocks::mock_config( 'message_domain_limits', + is( keys %$domain_limits, 1, 'koha-conf contains one domain' ); + is( $domain_limits->{a}->{limit}, 2, 'check limit of first entry' ); + is( $domain_limits->{a}->{unit}, '1d', 'check unit of first entry' ); + t::lib::Mocks::mock_config( + 'message_domain_limits', { domain => [ { name => 'A', limit => 2, unit => '2d' }, { name => 'B', limit => 3, unit => '3h' } ] }, ); $domain_limits = Koha::Notice::Util->load_domain_limits; - is( keys %$domain_limits, 2, 'koha-conf contains two domains' ); - is( $domain_limits->{b}->{limit}, 3, 'check limit of second entry' ); + is( keys %$domain_limits, 2, 'koha-conf contains two domains' ); + is( $domain_limits->{b}->{limit}, 3, 'check limit of second entry' ); is( $domain_limits->{b}->{count}, undef, 'check if count still undefined' ); }; @@ -62,26 +64,42 @@ subtest 'counting in exceeds_limit' => sub { plan tests => 3; my $domain_limits; + # Check counting my @values = ( message_transport_type => 'email', status => 'sent' ); - my $today = dt_from_string(); - #FIXME Why are the three following build calls so slow? - $builder->build_object({ class => 'Koha::Notice::Messages', - value => { @values, to_address => 'a@A', updated_on => $today->clone->subtract( hours => 36 ) }}); - $builder->build_object({ class => 'Koha::Notice::Messages', - value => { @values, to_address => 'b@A', updated_on => $today->clone->subtract( hours => 49 ) }}); - $builder->build_object({ class => 'Koha::Notice::Messages', - value => { @values, to_address => 'c@A', updated_on => $today->clone->subtract( days => 3 ) }}); + my $today = dt_from_string(); - $domain_limits = Koha::Notice::Util->load_domain_limits; # still using last mocked config A:2/2d - Koha::Notice::Util->exceeds_limit({ to => '@A', limits => $domain_limits, incr => 0 }); # force counting + #FIXME Why are the three following build calls so slow? + $builder->build_object( + { + class => 'Koha::Notice::Messages', + value => { @values, to_address => 'a@A', updated_on => $today->clone->subtract( hours => 36 ) } + } + ); + $builder->build_object( + { + class => 'Koha::Notice::Messages', + value => { @values, to_address => 'b@A', updated_on => $today->clone->subtract( hours => 49 ) } + } + ); + $builder->build_object( + { + class => 'Koha::Notice::Messages', + value => { @values, to_address => 'c@A', updated_on => $today->clone->subtract( days => 3 ) } + } + ); + + $domain_limits = Koha::Notice::Util->load_domain_limits; # still using last mocked config A:2/2d + Koha::Notice::Util->exceeds_limit( { to => '@A', limits => $domain_limits, incr => 0 } ); # force counting is( $domain_limits->{a}->{count}, 1, '1 message to A within unit of 2d' ); - t::lib::Mocks::mock_config( 'message_domain_limits', + t::lib::Mocks::mock_config( + 'message_domain_limits', { domain => [ { name => 'A', limit => 2, unit => '50h' }, { name => 'B', limit => 3, unit => '3h' } ] }, ); $domain_limits = Koha::Notice::Util->load_domain_limits; - Koha::Notice::Util->exceeds_limit({ to => 'x@A ', limits => $domain_limits, incr => 0 }); # force counting + Koha::Notice::Util->exceeds_limit( { to => 'x@A ', limits => $domain_limits, incr => 0 } ); # force counting is( $domain_limits->{a}->{count}, 2, '2 messages to A within unit of 50h' ); + # Check count for B; if counted, there would be 0 or higher, otherwise undef ok( !defined $domain_limits->{b}->{count}, 'Prove that we did not count b if not asked for' ); }; @@ -91,12 +109,16 @@ subtest '_convert_unit' => sub { # Date subtraction - edge case (start of summer time) my $mock_context = Test::MockModule->new('C4::Context'); - $mock_context->mock( 'tz', sub { return DateTime::TimeZone->new( name => 'Europe/Amsterdam' )} ); + $mock_context->mock( 'tz', sub { return DateTime::TimeZone->new( name => 'Europe/Amsterdam' ) } ); my $dt = dt_from_string( '2023-03-31 02:30:00', 'iso', '+02:00' ); - is( Koha::Notice::Util::_convert_unit( $dt, '4d')->stringify, '2023-03-27T02:30:00', '02:30 is fine' ); - is( Koha::Notice::Util::_convert_unit( $dt, '1d')->stringify, '2023-03-26T01:30:00', 'Moved 02:30 to 01:30' ); + is( Koha::Notice::Util::_convert_unit( $dt, '4d' )->stringify, '2023-03-27T02:30:00', '02:30 is fine' ); + is( Koha::Notice::Util::_convert_unit( $dt, '1d' )->stringify, '2023-03-26T01:30:00', 'Moved 02:30 to 01:30' ); + # Test bad unit - is( Koha::Notice::Util::_convert_unit( $dt, 'y')->stringify, '2023-03-26T01:30:00', 'No further shift for bad unit' ); + is( + Koha::Notice::Util::_convert_unit( $dt, 'y' )->stringify, '2023-03-26T01:30:00', + 'No further shift for bad unit' + ); $mock_context->unmock('tz'); }; @@ -106,27 +128,44 @@ subtest 'exceeds_limit with group domains' => sub { my $domain_limits; t::lib::Mocks::mock_config( 'message_domain_limits', undef ); $domain_limits = Koha::Notice::Util->load_domain_limits; - is( Koha::Notice::Util->exceeds_limit({ to => 'marcel@koha.nl', limits => $domain_limits }), 0, 'False when having no limits' ); + is( + Koha::Notice::Util->exceeds_limit( { to => 'marcel@koha.nl', limits => $domain_limits } ), 0, + 'False when having no limits' + ); - t::lib::Mocks::mock_config( 'message_domain_limits', { domain => [ - { name => 'A', limit => 3, unit => '5m' }, - { name => 'B', limit => 2, unit => '5m' }, - { name => 'C', belongs_to => 'A' }, - ]}); + t::lib::Mocks::mock_config( + 'message_domain_limits', + { + domain => [ + { name => 'A', limit => 3, unit => '5m' }, + { name => 'B', limit => 2, unit => '5m' }, + { name => 'C', belongs_to => 'A' }, + ] + } + ); $domain_limits = Koha::Notice::Util->load_domain_limits; my $result; - is( Koha::Notice::Util->exceeds_limit({ to => '1@A', limits => $domain_limits }), 0, 'First message to A' ); - is( Koha::Notice::Util->exceeds_limit({ to => '2@C', limits => $domain_limits }), 0, 'Second message to A (via C)' ); + is( Koha::Notice::Util->exceeds_limit( { to => '1@A', limits => $domain_limits } ), 0, 'First message to A' ); + is( + Koha::Notice::Util->exceeds_limit( { to => '2@C', limits => $domain_limits } ), 0, + 'Second message to A (via C)' + ); ok( !exists $domain_limits->{c}->{count}, 'No count exists for grouped domain' ); - warning_like { $result = Koha::Notice::Util->exceeds_limit({ to => '3@A', limits => $domain_limits }) } - qr/Sending messages: domain a reached limit/, 'Check warn for reaching limit A'; + warning_like { $result = Koha::Notice::Util->exceeds_limit( { to => '3@A', limits => $domain_limits } ) } + qr/Sending messages: domain a reached limit/, 'Check warn for reaching limit A'; is( $result, 0, 'Limit for A reached, not exceeded' ); - is( Koha::Notice::Util->exceeds_limit({ to => '4@C', limits => $domain_limits }), 1, 'Limit for A exceeded (via C)' ); - is( Koha::Notice::Util->exceeds_limit({ to => '5@B', limits => $domain_limits }), 0, 'First message to B' ); - is( $domain_limits->{b}->{count}, 1, 'Count B updated' ); - is( Koha::Notice::Util->exceeds_limit({ to => '5@B', limits => $domain_limits, incr => 0 }), 0, 'Test incr flag' ); - is( $domain_limits->{b}->{count}, 1, 'Count B still 1' ); - is( Koha::Notice::Util->exceeds_limit({ to => '6@D', limits => $domain_limits }), 0, 'No limits for D' ); + is( + Koha::Notice::Util->exceeds_limit( { to => '4@C', limits => $domain_limits } ), 1, + 'Limit for A exceeded (via C)' + ); + is( Koha::Notice::Util->exceeds_limit( { to => '5@B', limits => $domain_limits } ), 0, 'First message to B' ); + is( $domain_limits->{b}->{count}, 1, 'Count B updated' ); + is( + Koha::Notice::Util->exceeds_limit( { to => '5@B', limits => $domain_limits, incr => 0 } ), 0, + 'Test incr flag' + ); + is( $domain_limits->{b}->{count}, 1, 'Count B still 1' ); + is( Koha::Notice::Util->exceeds_limit( { to => '6@D', limits => $domain_limits } ), 0, 'No limits for D' ); }; $schema->storage->txn_rollback; diff --git a/t/db_dependent/Koha/Notices.t b/t/db_dependent/Koha/Notices.t index 9a58e9e758..c63516a0e5 100755 --- a/t/db_dependent/Koha/Notices.t +++ b/t/db_dependent/Koha/Notices.t @@ -30,8 +30,8 @@ use t::lib::Mocks; my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; -my $builder = t::lib::TestBuilder->new; -my $library = $builder->build( { source => 'Branch' } ); +my $builder = t::lib::TestBuilder->new; +my $library = $builder->build( { source => 'Branch' } ); my $nb_of_templates = Koha::Notice::Templates->search->count; my ( $module, $mtt ) = ( 'circulation', 'email' ); my $new_template = Koha::Notice::Template->new( @@ -60,12 +60,16 @@ my $retrieved_template = Koha::Notice::Templates->find( message_transport_type => $mtt, } ); -is( $retrieved_template->name, $new_template->name, - 'Find a notice template by pk should return the correct template' ); +is( + $retrieved_template->name, $new_template->name, + 'Find a notice template by pk should return the correct template' +); $retrieved_template->delete; -is( Koha::Notice::Templates->search->count, - $nb_of_templates, 'Delete should have deleted the template' ); +is( + Koha::Notice::Templates->search->count, + $nb_of_templates, 'Delete should have deleted the template' +); ## Tests for Koha::Notice::Messages->get_failed_notices @@ -169,17 +173,15 @@ subtest 'find_effective_template' => sub { plan tests => 7; my $default_template = $builder->build_object( - { class => 'Koha::Notice::Templates', value => { branchcode => '', lang => 'default' } } - ); + { class => 'Koha::Notice::Templates', value => { branchcode => '', lang => 'default' } } ); my $key = { module => $default_template->module, code => $default_template->code, message_transport_type => $default_template->message_transport_type, }; - my $library_specific_template = $builder->build_object( - { class => 'Koha::Notice::Templates', value => { %$key, lang => 'default' } } - ); + my $library_specific_template = + $builder->build_object( { class => 'Koha::Notice::Templates', value => { %$key, lang => 'default' } } ); my $es_template = $builder->build_object( { @@ -195,30 +197,36 @@ subtest 'find_effective_template' => sub { my $template = Koha::Notice::Templates->find_effective_template($key); is( $template->lang, 'default', 'no lang passed, default is returned' ); $template = Koha::Notice::Templates->find_effective_template( { %$key, lang => 'es-ES' } ); - is( $template->lang, 'default', - 'TranslateNotices is off, default is returned' ); + is( + $template->lang, 'default', + 'TranslateNotices is off, default is returned' + ); t::lib::Mocks::mock_preference( 'TranslateNotices', 1 ); $template = Koha::Notice::Templates->find_effective_template($key); is( $template->lang, 'default', 'no lang passed, default is returned' ); $template = Koha::Notice::Templates->find_effective_template( { %$key, lang => 'es-ES' } ); - is( $template->lang, 'es-ES', - 'TranslateNotices is on and es-ES is requested, es-ES is returned' ); - + is( + $template->lang, 'es-ES', + 'TranslateNotices is on and es-ES is requested, es-ES is returned' + ); { # IndependentBranches => 1 t::lib::Mocks::mock_userenv( { branchcode => $library_specific_template->branchcode, flag => 0 } ); t::lib::Mocks::mock_preference( 'IndependentBranches', 1 ); - $template = Koha::Notice::Templates->find_effective_template( { %$key, branchcode => $library_specific_template->branchcode } ); - is( $template->content, $library_specific_template->content, + $template = Koha::Notice::Templates->find_effective_template( + { %$key, branchcode => $library_specific_template->branchcode } ); + is( + $template->content, $library_specific_template->content, 'IndependentBranches is on, logged in patron is not superlibrarian but asks for their specific template, it is returned' ); my $another_library = $builder->build_object( { class => 'Koha::Libraries' } ); t::lib::Mocks::mock_userenv( { branchcode => $another_library->branchcode, flag => 0 } ); $template = Koha::Notice::Templates->find_effective_template($key); - is( $template->content, $default_template->content, -'IndependentBranches is on, logged in patron is not superlibrarian, default is returned' + is( + $template->content, $default_template->content, + 'IndependentBranches is on, logged in patron is not superlibrarian, default is returned' ); } @@ -226,7 +234,8 @@ subtest 'find_effective_template' => sub { $es_template->delete; $template = Koha::Notice::Templates->find_effective_template( { %$key, lang => 'es-ES' } ); - is( $template->lang, 'default', + is( + $template->lang, 'default', 'TranslateNotices is on and es-ES is requested but does not exist, default is returned' ); diff --git a/t/db_dependent/Koha/Object/Mixin/AdditionalFields.t b/t/db_dependent/Koha/Object/Mixin/AdditionalFields.t index c969c42599..4dc716e8f8 100755 --- a/t/db_dependent/Koha/Object/Mixin/AdditionalFields.t +++ b/t/db_dependent/Koha/Object/Mixin/AdditionalFields.t @@ -13,7 +13,7 @@ use C4::Context; use CGI; my $builder = t::lib::TestBuilder->new; -my $schema = Koha::Database->schema; +my $schema = Koha::Database->schema; subtest 'set_additional_fields with marcfield_mode = "get"' => sub { plan tests => 2; @@ -23,9 +23,9 @@ subtest 'set_additional_fields with marcfield_mode = "get"' => sub { my $biblio = $builder->build_sample_biblio(); my $record = $biblio->record; $record->append_fields( - MARC::Field->new('998', '', '', 'Z' => 'some value'), + MARC::Field->new( '998', '', '', 'Z' => 'some value' ), ); - $biblio->metadata->metadata($record->as_xml_record(C4::Context->preference('marcflavour'))); + $biblio->metadata->metadata( $record->as_xml_record( C4::Context->preference('marcflavour') ) ); $biblio->metadata->store()->discard_changes(); my $subscription = Koha::Subscription->new( { @@ -36,9 +36,9 @@ subtest 'set_additional_fields with marcfield_mode = "get"' => sub { my $field = Koha::AdditionalField->new( { - tablename => 'subscription', - name => random_string('c' x 100), - marcfield => '998$Z', + tablename => 'subscription', + name => random_string( 'c' x 100 ), + marcfield => '998$Z', marcfield_mode => 'get', } ); @@ -51,7 +51,7 @@ subtest 'set_additional_fields with marcfield_mode = "get"' => sub { my $values = $subscription->additional_field_values()->as_list(); - is($values->[0]->value, 'some value', 'value was copied from the biblio record to the field'); + is( $values->[0]->value, 'some value', 'value was copied from the biblio record to the field' ); $field->delete; my $get_marcfield_field = Koha::AdditionalField->new( @@ -85,7 +85,7 @@ subtest 'set_additional_fields with marcfield_mode = "set"' => sub { $schema->txn_begin; - my $biblio = $builder->build_sample_biblio(); + my $biblio = $builder->build_sample_biblio(); my $subscription = Koha::Subscription->new( { biblionumber => $biblio->biblionumber, @@ -95,9 +95,9 @@ subtest 'set_additional_fields with marcfield_mode = "set"' => sub { my $field = Koha::AdditionalField->new( { - tablename => 'subscription', - name => random_string('c' x 100), - marcfield => '999$Z', + tablename => 'subscription', + name => random_string( 'c' x 100 ), + marcfield => '999$Z', marcfield_mode => 'set', } ); @@ -105,14 +105,14 @@ subtest 'set_additional_fields with marcfield_mode = "set"' => sub { $subscription->set_additional_fields( [ { - id => $field->id, + id => $field->id, value => 'some value', }, ] ); my $record = $biblio->record; - is($record->subfield('999', 'Z'), 'some value', 'value was copied from the field to the biblio record'); + is( $record->subfield( '999', 'Z' ), 'some value', 'value was copied from the field to the biblio record' ); $schema->txn_rollback; }; @@ -132,16 +132,16 @@ subtest 'get_additional_field_values_for_template' => sub { my $field = Koha::AdditionalField->new( { - tablename => 'subscription', - name => random_string( 'c' x 100 ) + tablename => 'subscription', + name => random_string( 'c' x 100 ) } ); $field->store()->discard_changes(); my $field2 = Koha::AdditionalField->new( { - tablename => 'subscription', - name => random_string( 'c' x 100 ) + tablename => 'subscription', + name => random_string( 'c' x 100 ) } ); $field2->store()->discard_changes(); @@ -226,17 +226,13 @@ subtest 'add_additional_fields' => sub { $subscription->add_additional_fields( { - $field2->id => [ - 'second field' - ], + $field2->id => ['second field'], }, 'subscription' ); my $template_additional_field_values = $subscription->get_additional_field_values_for_template; - - is_deeply( $template_additional_field_values, { $field->id => [ $value . ' 1', $value . ' 2' ], $field2->id => ['second field'] }, diff --git a/t/db_dependent/Koha/Objects.t b/t/db_dependent/Koha/Objects.t index e98ddf8f3a..4d07a4cfb0 100755 --- a/t/db_dependent/Koha/Objects.t +++ b/t/db_dependent/Koha/Objects.t @@ -45,33 +45,39 @@ my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; my $builder = t::lib::TestBuilder->new; -is( ref(Koha::Authority::Types->find('')), 'Koha::Authority::Type', 'Koha::Objects->find should work if the primary key is an empty string' ); +is( + ref( Koha::Authority::Types->find('') ), 'Koha::Authority::Type', + 'Koha::Objects->find should work if the primary key is an empty string' +); -my @columns = Koha::Patrons->columns; +my @columns = Koha::Patrons->columns; my $borrowernumber_exists = grep { /^borrowernumber$/ } @columns; is( $borrowernumber_exists, 1, 'Koha::Objects->columns should return the table columns' ); subtest 'find' => sub { plan tests => 6; - my $patron = $builder->build({source => 'Borrower'}); + my $patron = $builder->build( { source => 'Borrower' } ); my $patron_object = Koha::Patrons->find( $patron->{borrowernumber} ); is( $patron_object->borrowernumber, $patron->{borrowernumber}, '->find should return the correct object' ); my @patrons = Koha::Patrons->find( $patron->{borrowernumber} ); - is(scalar @patrons, 1, '->find in list context returns a value'); - is($patrons[0]->borrowernumber, $patron->{borrowernumber}, '->find in list context returns the same value as in scalar context'); + is( scalar @patrons, 1, '->find in list context returns a value' ); + is( + $patrons[0]->borrowernumber, $patron->{borrowernumber}, + '->find in list context returns the same value as in scalar context' + ); my $patrons = { foo => Koha::Patrons->find('foo'), bar => 'baz', }; - is ($patrons->{foo}, undef, '->find in list context returns undef when no record is found'); + is( $patrons->{foo}, undef, '->find in list context returns undef when no record is found' ); # Test sending undef to find; should not generate a warning - warning_is { $patron = Koha::Patrons->find( undef ); } - "", "Sending undef does not trigger a DBIx warning"; + warning_is { $patron = Koha::Patrons->find(undef); } + "", "Sending undef does not trigger a DBIx warning"; warning_is { $patron = Koha::Patrons->find( undef, undef ); } - "", "Sending two undefs does not trigger a DBIx warning too"; + "", "Sending two undefs does not trigger a DBIx warning too"; }; subtest 'update' => sub { @@ -84,38 +90,62 @@ subtest 'update' => sub { $builder->build( { source => 'City', value => { city_country => 'France' } } ); $builder->build( { source => 'City', value => { city_country => 'Germany' } } ); Koha::Cities->search( { city_country => 'UK' } )->update( { city_country => 'EU' } ); - is( Koha::Cities->search( { city_country => 'EU' } )->count, 3, 'Koha::Objects->update should have updated the 3 rows' ); - is( Koha::Cities->search( { city_country => 'UK' } )->count, 0, 'Koha::Objects->update should have updated the 3 rows' ); + is( + Koha::Cities->search( { city_country => 'EU' } )->count, 3, + 'Koha::Objects->update should have updated the 3 rows' + ); + is( + Koha::Cities->search( { city_country => 'UK' } )->count, 0, + 'Koha::Objects->update should have updated the 3 rows' + ); }; subtest 'reset' => sub { plan tests => 3; - my $patrons = Koha::Patrons->search; - my $first_borrowernumber = $patrons->next->borrowernumber; + my $patrons = Koha::Patrons->search; + my $first_borrowernumber = $patrons->next->borrowernumber; my $second_borrowernumber = $patrons->next->borrowernumber; - is( ref( $patrons->reset ), 'Koha::Patrons', 'Koha::Objects->reset should allow chaining' ); - is( ref( $patrons->reset->next ), 'Koha::Patron', 'Koha::Objects->reset should allow chaining' ); - is( $patrons->reset->next->borrowernumber, $first_borrowernumber, 'Koha::Objects->reset should work as expected'); + is( ref( $patrons->reset ), 'Koha::Patrons', 'Koha::Objects->reset should allow chaining' ); + is( ref( $patrons->reset->next ), 'Koha::Patron', 'Koha::Objects->reset should allow chaining' ); + is( $patrons->reset->next->borrowernumber, $first_borrowernumber, 'Koha::Objects->reset should work as expected' ); }; subtest 'delete' => sub { plan tests => 2; - my $patron_1 = $builder->build({source => 'Borrower'}); - my $patron_2 = $builder->build({source => 'Borrower'}); - is( Koha::Patrons->search({ -or => { borrowernumber => [ $patron_1->{borrowernumber}, $patron_2->{borrowernumber}]}})->delete, 2, ''); - is( Koha::Patrons->search({ -or => { borrowernumber => [ $patron_1->{borrowernumber}, $patron_2->{borrowernumber}]}})->count, 0, ''); + my $patron_1 = $builder->build( { source => 'Borrower' } ); + my $patron_2 = $builder->build( { source => 'Borrower' } ); + is( + Koha::Patrons->search( + { -or => { borrowernumber => [ $patron_1->{borrowernumber}, $patron_2->{borrowernumber} ] } } + )->delete, + 2, + '' + ); + is( + Koha::Patrons->search( + { -or => { borrowernumber => [ $patron_1->{borrowernumber}, $patron_2->{borrowernumber} ] } } + )->count, + 0, + '' + ); }; subtest 'new' => sub { plan tests => 2; - my $a_cat_code = 'A_CAT_CODE'; + my $a_cat_code = 'A_CAT_CODE'; my $patron_category = Koha::Patron::Category->new( { categorycode => $a_cat_code } )->store; - is( Koha::Patron::Categories->find($a_cat_code)->category_type, 'A', 'Koha::Object->new should set the default value' ); + is( + Koha::Patron::Categories->find($a_cat_code)->category_type, 'A', + 'Koha::Object->new should set the default value' + ); Koha::Patron::Categories->find($a_cat_code)->delete; $patron_category = Koha::Patron::Category->new( { categorycode => $a_cat_code, category_type => undef } )->store; - is( Koha::Patron::Categories->find($a_cat_code)->category_type, 'A', 'Koha::Object->new should set the default value even if the argument exists but is not defined' ); + is( + Koha::Patron::Categories->find($a_cat_code)->category_type, 'A', + 'Koha::Object->new should set the default value even if the argument exists but is not defined' + ); Koha::Patron::Categories->find($a_cat_code)->delete; }; @@ -123,20 +153,29 @@ subtest 'find' => sub { plan tests => 4; # check find on a single PK - my $patron = $builder->build({ source => 'Borrower' }); - is( Koha::Patrons->find($patron->{borrowernumber})->surname, + my $patron = $builder->build( { source => 'Borrower' } ); + is( + Koha::Patrons->find( $patron->{borrowernumber} )->surname, $patron->{surname}, "Checking an arbitrary patron column after find" ); + # check find with unique column - my $obj = Koha::Patrons->find($patron->{cardnumber}, { key => 'cardnumber' }); - is( $obj->borrowernumber, $patron->{borrowernumber}, - 'Find with unique column and key specified' ); + my $obj = Koha::Patrons->find( $patron->{cardnumber}, { key => 'cardnumber' } ); + is( + $obj->borrowernumber, $patron->{borrowernumber}, + 'Find with unique column and key specified' + ); + # check find with an additional where clause in the attrs hash # we do not expect to find something now - is( Koha::Patrons->find( - $patron->{borrowernumber}, - { where => { surname => { '!=', $patron->{surname} }}}, - ), undef, 'Additional where clause in find call' ); + is( + Koha::Patrons->find( + $patron->{borrowernumber}, + { where => { surname => { '!=', $patron->{surname} } } }, + ), + undef, + 'Additional where clause in find call' + ); is( Koha::Patrons->find(), undef, 'Find returns undef if no params passed' ); }; @@ -149,93 +188,116 @@ subtest 'search_related' => sub { my $patron_1 = $builder->build( { source => 'Borrower' } ); my $patron_2 = $builder->build( { source => 'Borrower' } ); my $libraries = Koha::Patrons->search( - { - -or => { - borrowernumber => - [ $patron_1->{borrowernumber}, $patron_2->{borrowernumber} ] - } - } - )->search_related('branchcode'); - is( ref($libraries), 'Koha::Libraries', + { -or => { borrowernumber => [ $patron_1->{borrowernumber}, $patron_2->{borrowernumber} ] } } ) + ->search_related('branchcode'); + is( + ref($libraries), 'Koha::Libraries', 'Koha::Objects->search_related should return an instanciated Koha::Objects-based object' ); - is( $libraries->count, 2, - 'Koha::Objects->search_related should work as expected' ); - ok( eq_array( - [ $libraries->get_column('branchcode') ], - [ $patron_1->{branchcode}, $patron_2->{branchcode} ] ), + is( + $libraries->count, 2, + 'Koha::Objects->search_related should work as expected' + ); + ok( + eq_array( + [ $libraries->get_column('branchcode') ], + [ $patron_1->{branchcode}, $patron_2->{branchcode} ] + ), 'Koha::Objects->search_related should work as expected' ); }; subtest 'single' => sub { plan tests => 2; - my $builder = t::lib::TestBuilder->new; - my $patron_1 = $builder->build( { source => 'Borrower' } ); - my $patron_2 = $builder->build( { source => 'Borrower' } ); - my $patron = Koha::Patrons->search({}, { rows => 1 })->single; - is(ref($patron), 'Koha::Patron', 'Koha::Objects->single returns a single Koha::Patron object.'); + my $builder = t::lib::TestBuilder->new; + my $patron_1 = $builder->build( { source => 'Borrower' } ); + my $patron_2 = $builder->build( { source => 'Borrower' } ); + my $patron = Koha::Patrons->search( {}, { rows => 1 } )->single; + is( ref($patron), 'Koha::Patron', 'Koha::Objects->single returns a single Koha::Patron object.' ); warning_like { Koha::Patrons->search->single } qr/SQL that returns multiple rows/, - "Warning is presented if single is used for a result with multiple rows."; + "Warning is presented if single is used for a result with multiple rows."; }; subtest 'last' => sub { plan tests => 3; - my $builder = t::lib::TestBuilder->new; - my $patron_1 = $builder->build( { source => 'Borrower' } ); - my $patron_2 = $builder->build( { source => 'Borrower' } ); + my $builder = t::lib::TestBuilder->new; + my $patron_1 = $builder->build( { source => 'Borrower' } ); + my $patron_2 = $builder->build( { source => 'Borrower' } ); my $last_patron = Koha::Patrons->search->last; is( $last_patron->borrowernumber, $patron_2->{borrowernumber}, '->last should return the last inserted patron' ); - $last_patron = Koha::Patrons->search({ borrowernumber => $patron_1->{borrowernumber} })->last; - is( $last_patron->borrowernumber, $patron_1->{borrowernumber}, '->last should work even if there is only 1 result' ); - $last_patron = Koha::Patrons->search({ surname => 'should_not_exist' })->last; + $last_patron = Koha::Patrons->search( { borrowernumber => $patron_1->{borrowernumber} } )->last; + is( + $last_patron->borrowernumber, $patron_1->{borrowernumber}, + '->last should work even if there is only 1 result' + ); + $last_patron = Koha::Patrons->search( { surname => 'should_not_exist' } )->last; is( $last_patron, undef, '->last should return undef if search does not return any results' ); }; subtest 'get_column' => sub { plan tests => 1; - my @cities = Koha::Cities->search->as_list; + my @cities = Koha::Cities->search->as_list; my @city_names = map { $_->city_name } @cities; - is_deeply( [ Koha::Cities->search->get_column('city_name') ], \@city_names, 'Koha::Objects->get_column should be allowed' ); + is_deeply( + [ Koha::Cities->search->get_column('city_name') ], \@city_names, + 'Koha::Objects->get_column should be allowed' + ); }; subtest 'Exceptions' => sub { plan tests => 7; - my $patron_borrowernumber = $builder->build({ source => 'Borrower' })->{ borrowernumber }; - my $patron = Koha::Patrons->find( $patron_borrowernumber ); + my $patron_borrowernumber = $builder->build( { source => 'Borrower' } )->{borrowernumber}; + my $patron = Koha::Patrons->find($patron_borrowernumber); # Koha::Object try { $patron->blah('blah'); } catch { - ok( $_->isa('Koha::Exceptions::Object::MethodNotCoveredByTests'), - 'Calling a non-covered method should raise a Koha::Exceptions::Object::MethodNotCoveredByTests exception' ); - is( $_->message, 'The method Koha::Patron->blah is not covered by tests!', 'The message raised should contain the package and the method' ); + ok( + $_->isa('Koha::Exceptions::Object::MethodNotCoveredByTests'), + 'Calling a non-covered method should raise a Koha::Exceptions::Object::MethodNotCoveredByTests exception' + ); + is( + $_->message, 'The method Koha::Patron->blah is not covered by tests!', + 'The message raised should contain the package and the method' + ); }; try { - $patron->set({ blah => 'blah' }); + $patron->set( { blah => 'blah' } ); } catch { - ok( $_->isa('Koha::Exceptions::Object::PropertyNotFound'), - 'Setting a non-existent property should raise a Koha::Exceptions::Object::PropertyNotFound exception' ); + ok( + $_->isa('Koha::Exceptions::Object::PropertyNotFound'), + 'Setting a non-existent property should raise a Koha::Exceptions::Object::PropertyNotFound exception' + ); }; # Koha::Objects try { Koha::Patrons->search->not_covered_yet; } catch { - ok( $_->isa('Koha::Exceptions::Object::MethodNotCoveredByTests'), - 'Calling a non-covered method should raise a Koha::Exceptions::Object::MethodNotCoveredByTests exception' ); - is( $_->message, 'The method Koha::Patrons->not_covered_yet is not covered by tests!', 'The message raised should contain the package and the method' ); + ok( + $_->isa('Koha::Exceptions::Object::MethodNotCoveredByTests'), + 'Calling a non-covered method should raise a Koha::Exceptions::Object::MethodNotCoveredByTests exception' + ); + is( + $_->message, 'The method Koha::Patrons->not_covered_yet is not covered by tests!', + 'The message raised should contain the package and the method' + ); }; try { Koha::Patrons->not_covered_yet; } catch { - ok( $_->isa('Koha::Exceptions::Object::MethodNotCoveredByTests'), - 'Calling a non-covered method should raise a Koha::Exceptions::Object::MethodNotCoveredByTests exception' ); - is( $_->message, 'The method Koha::Patrons->not_covered_yet is not covered by tests!', 'The message raised should contain the package and the method' ); + ok( + $_->isa('Koha::Exceptions::Object::MethodNotCoveredByTests'), + 'Calling a non-covered method should raise a Koha::Exceptions::Object::MethodNotCoveredByTests exception' + ); + is( + $_->message, 'The method Koha::Patrons->not_covered_yet is not covered by tests!', + 'The message raised should contain the package and the method' + ); }; }; @@ -249,9 +311,10 @@ subtest '->is_paged and ->pager tests' => sub { # Count existing patrons my $nb_patrons = Koha::Patrons->search()->count; + # Create 10 more patrons - foreach (1..10) { - $builder->build_object({ class => 'Koha::Patrons' }); + foreach ( 1 .. 10 ) { + $builder->build_object( { class => 'Koha::Patrons' } ); } # Non-paginated search @@ -264,8 +327,10 @@ subtest '->is_paged and ->pager tests' => sub { is( $patrons->count, 3, 'Search returns only one page, 3 patrons' ); ok( $patrons->is_paged, 'Search is paged' ); my $pager = $patrons->pager; - is( ref($patrons->pager), 'DBIx::Class::ResultSet::Pager', - 'Koha::Objects->pager returns a valid DBIx::Class object' ); + is( + ref( $patrons->pager ), 'DBIx::Class::ResultSet::Pager', + 'Koha::Objects->pager returns a valid DBIx::Class object' + ); $schema->storage->txn_rollback; }; @@ -280,20 +345,18 @@ subtest "to_api() tests" => sub { my $city_2 = $builder->build_object( { class => 'Koha::Cities' } ); my $cities = Koha::Cities->search( - { - cityid => [ $city_1->cityid, $city_2->cityid ] - }, + { cityid => [ $city_1->cityid, $city_2->cityid ] }, { -orderby => { -desc => 'cityid' } } ); is( $cities->count, 2, 'Count is correct' ); my $cities_api = $cities->to_api; - is( ref( $cities_api ), 'ARRAY', 'to_api returns an array' ); + is( ref($cities_api), 'ARRAY', 'to_api returns an array' ); is_deeply( $cities_api->[0], $city_1->to_api, 'to_api returns the individual objects with ->to_api' ); is_deeply( $cities_api->[1], $city_2->to_api, 'to_api returns the individual objects with ->to_api' ); my $biblio_1 = $builder->build_sample_biblio(); - my $item_1 = $builder->build_sample_item({ biblionumber => $biblio_1->biblionumber }); + my $item_1 = $builder->build_sample_item( { biblionumber => $biblio_1->biblionumber } ); my $hold_1 = $builder->build_object( { class => 'Koha::Holds', @@ -302,7 +365,7 @@ subtest "to_api() tests" => sub { ); my $biblio_2 = $builder->build_sample_biblio(); - my $item_2 = $builder->build_sample_item({ biblionumber => $biblio_2->biblionumber }); + my $item_2 = $builder->build_sample_item( { biblionumber => $biblio_2->biblionumber } ); my $hold_2 = $builder->build_object( { class => 'Koha::Holds', @@ -312,74 +375,57 @@ subtest "to_api() tests" => sub { my $embed = { 'items' => {} }; - my $i = 0; + my $i = 0; my @items = ( $item_1, $item_2 ); my @holds = ( $hold_1, $hold_2 ); - my $biblios_api = Koha::Biblios->search( - { - biblionumber => [ $biblio_1->biblionumber, $biblio_2->biblionumber ] - } - )->to_api( { embed => $embed } ); + my $biblios_api = Koha::Biblios->search( { biblionumber => [ $biblio_1->biblionumber, $biblio_2->biblionumber ] } ) + ->to_api( { embed => $embed } ); - foreach my $biblio_api ( @{ $biblios_api } ) { - ok(exists $biblio_api->{items}, 'Items where embedded in biblio results'); - is($biblio_api->{items}->[0]->{item_id}, $items[$i]->itemnumber, 'Item matches'); - ok(!exists $biblio_api->{items}->[0]->{holds}, 'No holds info should be embedded yet'); + foreach my $biblio_api ( @{$biblios_api} ) { + ok( exists $biblio_api->{items}, 'Items where embedded in biblio results' ); + is( $biblio_api->{items}->[0]->{item_id}, $items[$i]->itemnumber, 'Item matches' ); + ok( !exists $biblio_api->{items}->[0]->{holds}, 'No holds info should be embedded yet' ); $i++; } # One more level - $embed = { - 'items' => { - children => { 'holds' => {} } - } - }; + $embed = { 'items' => { children => { 'holds' => {} } } }; $i = 0; - $biblios_api = Koha::Biblios->search( - { - biblionumber => [ $biblio_1->biblionumber, $biblio_2->biblionumber ] - } - )->to_api( { embed => $embed } ); + $biblios_api = Koha::Biblios->search( { biblionumber => [ $biblio_1->biblionumber, $biblio_2->biblionumber ] } ) + ->to_api( { embed => $embed } ); - foreach my $biblio_api ( @{ $biblios_api } ) { + foreach my $biblio_api ( @{$biblios_api} ) { - ok(exists $biblio_api->{items}, 'Items where embedded in biblio results'); - is($biblio_api->{items}->[0]->{item_id}, $items[$i]->itemnumber, 'Item still matches'); - ok(exists $biblio_api->{items}->[0]->{holds}, 'Holds info should be embedded'); - is($biblio_api->{items}->[0]->{holds}->[0]->{hold_id}, $holds[$i]->reserve_id, 'Hold matches'); + ok( exists $biblio_api->{items}, 'Items where embedded in biblio results' ); + is( $biblio_api->{items}->[0]->{item_id}, $items[$i]->itemnumber, 'Item still matches' ); + ok( exists $biblio_api->{items}->[0]->{holds}, 'Holds info should be embedded' ); + is( $biblio_api->{items}->[0]->{holds}->[0]->{hold_id}, $holds[$i]->reserve_id, 'Hold matches' ); $i++; } subtest 'unprivileged request tests' => sub { - my @all_attrs = Koha::Libraries->columns(); + my @all_attrs = Koha::Libraries->columns(); my $public_attrs = { map { $_ => 1 } @{ Koha::Library->public_read_list() } }; - my $mapping = Koha::Library->to_api_mapping; + my $mapping = Koha::Library->to_api_mapping; # Create sample libraries - my $library_1 = $builder->build_object({ class => 'Koha::Libraries' }); - my $library_2 = $builder->build_object({ class => 'Koha::Libraries' }); + my $library_1 = $builder->build_object( { class => 'Koha::Libraries' } ); + my $library_2 = $builder->build_object( { class => 'Koha::Libraries' } ); my $libraries = Koha::Libraries->search( - { - branchcode => { - '-in' => [ - $library_1->branchcode, $library_2->branchcode - ] - } - } - ); + { branchcode => { '-in' => [ $library_1->branchcode, $library_2->branchcode ] } } ); plan tests => scalar @all_attrs * 2 * $libraries->count; - my $libraries_unprivileged_representation = $libraries->to_api({ public => 1 }); + my $libraries_unprivileged_representation = $libraries->to_api( { public => 1 } ); my $libraries_privileged_representation = $libraries->to_api(); - for (my $i = 0; $i < $libraries->count; $i++) { + for ( my $i = 0 ; $i < $libraries->count ; $i++ ) { my $privileged_representation = $libraries_privileged_representation->[$i]; my $unprivileged_representation = $libraries_unprivileged_representation->[$i]; foreach my $attr (@all_attrs) { @@ -394,15 +440,13 @@ subtest "to_api() tests" => sub { exists $unprivileged_representation->{$mapped}, "Attribute '$attr' is present when public" ); - } - else { + } else { ok( !exists $unprivileged_representation->{$mapped}, "Attribute '$attr' is not present when public" ); } - } - else { + } else { ok( !exists $privileged_representation->{$attr}, "Unmapped attribute '$attr' is not present when privileged" @@ -416,7 +460,6 @@ subtest "to_api() tests" => sub { } }; - $schema->storage->txn_rollback; }; @@ -430,9 +473,7 @@ subtest "TO_JSON() tests" => sub { my $city_2 = $builder->build_object( { class => 'Koha::Cities' } ); my $cities = Koha::Cities->search( - { - cityid => [ $city_1->cityid, $city_2->cityid ] - }, + { cityid => [ $city_1->cityid, $city_2->cityid ] }, { -orderby => { -desc => 'cityid' } } ); @@ -440,7 +481,7 @@ subtest "TO_JSON() tests" => sub { my $cities_json = $cities->TO_JSON; is( ref($cities_json), 'ARRAY', 'to_api returns an array' ); is_deeply( $cities_json->[0], $city_1->TO_JSON, 'TO_JSON returns the individual objects with ->TO_JSON' ); - is_deeply( $cities_json->[1], $city_2->TO_JSON,'TO_JSON returns the individual objects with ->TO_JSON' ); + is_deeply( $cities_json->[1], $city_2->TO_JSON, 'TO_JSON returns the individual objects with ->TO_JSON' ); $schema->storage->txn_rollback; }; @@ -468,21 +509,25 @@ subtest 'Return same values as DBIx::Class' => sub { try { $r_us = $c->delete; } catch { $e_us = $_ }; $c = $schema->resultset('City')->new( { city_name => 'city4test_2' } )->update_or_insert; try { $r_them = $c->delete; } catch { $e_them = $_ }; - ok( ref($r_us) && ref($r_them), - 'Successful delete should return the object ' ); - ok( !defined $e_us && !defined $e_them, - 'Successful delete should not raise an exception' ); + ok( + ref($r_us) && ref($r_them), + 'Successful delete should return the object ' + ); + ok( + !defined $e_us && !defined $e_them, + 'Successful delete should not raise an exception' + ); is( ref($r_us), 'Koha::City', 'Successful delete should return our Koha::Obect based object' ); # CASE 2 - Delete an object that is not in storage - try { $r_us = $r_us->delete; } catch { $e_us = $_ }; + try { $r_us = $r_us->delete; } catch { $e_us = $_ }; try { $r_them = $r_them->delete; } catch { $e_them = $_ }; ok( defined $e_us && defined $e_them, 'Delete an object that is not in storage should raise an exception' ); is( ref($e_us), 'DBIx::Class::Exception' ) - ; # FIXME This needs adjustement, we want to throw a Koha::Exception + ; # FIXME This needs adjustement, we want to throw a Koha::Exception }; @@ -493,9 +538,9 @@ subtest 'Return same values as DBIx::Class' => sub { my ( $r_us, $e_us, $r_them, $e_them ); # CASE 1 - Delete existing objects - my $city_1 = $builder->build_object({ class => 'Koha::Cities' }); - my $city_2 = $builder->build_object({ class => 'Koha::Cities' }); - my $city_3 = $builder->build_object({ class => 'Koha::Cities' }); + my $city_1 = $builder->build_object( { class => 'Koha::Cities' } ); + my $city_2 = $builder->build_object( { class => 'Koha::Cities' } ); + my $city_3 = $builder->build_object( { class => 'Koha::Cities' } ); my $cities = Koha::Cities->search( { cityid => { @@ -510,9 +555,9 @@ subtest 'Return same values as DBIx::Class' => sub { try { $r_us = $cities->delete; } catch { $e_us = $_ }; - $city_1 = $builder->build_object({ class => 'Koha::Cities' }); - $city_2 = $builder->build_object({ class => 'Koha::Cities' }); - $city_3 = $builder->build_object({ class => 'Koha::Cities' }); + $city_1 = $builder->build_object( { class => 'Koha::Cities' } ); + $city_2 = $builder->build_object( { class => 'Koha::Cities' } ); + $city_3 = $builder->build_object( { class => 'Koha::Cities' } ); $cities = $schema->resultset('City')->search( { cityid => { @@ -528,12 +573,12 @@ subtest 'Return same values as DBIx::Class' => sub { try { $r_them = $cities->delete; } catch { $e_them = $_ }; ok( $r_us == 3 && $r_them == 3 ); - ok (!defined($e_us) && !defined($e_them)); + ok( !defined($e_us) && !defined($e_them) ); # CASE 2 - One of the object is not in storage - $city_1 = $builder->build_object({ class => 'Koha::Cities' }); - $city_2 = $builder->build_object({ class => 'Koha::Cities' }); - $city_3 = $builder->build_object({ class => 'Koha::Cities' }); + $city_1 = $builder->build_object( { class => 'Koha::Cities' } ); + $city_2 = $builder->build_object( { class => 'Koha::Cities' } ); + $city_3 = $builder->build_object( { class => 'Koha::Cities' } ); $cities = Koha::Cities->search( { cityid => { @@ -546,12 +591,12 @@ subtest 'Return same values as DBIx::Class' => sub { } ); - $city_2->delete; # We delete one of the object + $city_2->delete; # We delete one of the object try { $r_us = $cities->delete; } catch { $e_us = $_ }; - $city_1 = $builder->build_object({ class => 'Koha::Cities' }); - $city_2 = $builder->build_object({ class => 'Koha::Cities' }); - $city_3 = $builder->build_object({ class => 'Koha::Cities' }); + $city_1 = $builder->build_object( { class => 'Koha::Cities' } ); + $city_2 = $builder->build_object( { class => 'Koha::Cities' } ); + $city_3 = $builder->build_object( { class => 'Koha::Cities' } ); $cities = $schema->resultset('City')->search( { cityid => { @@ -564,11 +609,11 @@ subtest 'Return same values as DBIx::Class' => sub { } ); - $city_2->delete; # We delete one of the object + $city_2->delete; # We delete one of the object try { $r_them = $cities->delete; } catch { $e_them = $_ }; ok( $r_us == 2 && $r_them == 2 ); - ok (!defined($e_us) && !defined($e_them)); + ok( !defined($e_us) && !defined($e_them) ); }; }; @@ -583,30 +628,36 @@ subtest 'Return same values as DBIx::Class' => sub { my ( $r_us, $e_us, $r_them, $e_them ); # CASE 1 - Delete an existing patron - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $patron_data = $patron->unblessed; $patron->delete; - $patron = Koha::Patron->new( $patron_data )->store; - try {$r_us = $patron->delete;} catch { $e_us = $_ }; - $patron = $schema->resultset('Borrower')->new( $patron_data )->update_or_insert; - try {$r_them = $patron->delete;} catch { $e_them = $_ }; - ok( ref($r_us) && ref($r_them), - 'Successful delete should return the patron object' ); - ok( !defined $e_us && !defined $e_them, - 'Successful delete should not raise an exception' ); - is( ref($r_us), 'Koha::Patron', - 'Successful delete should return our Koha::Obect based object' ); + $patron = Koha::Patron->new($patron_data)->store; + try { $r_us = $patron->delete; } catch { $e_us = $_ }; + $patron = $schema->resultset('Borrower')->new($patron_data)->update_or_insert; + try { $r_them = $patron->delete; } catch { $e_them = $_ }; + ok( + ref($r_us) && ref($r_them), + 'Successful delete should return the patron object' + ); + ok( + !defined $e_us && !defined $e_them, + 'Successful delete should not raise an exception' + ); + is( + ref($r_us), 'Koha::Patron', + 'Successful delete should return our Koha::Obect based object' + ); # CASE 2 - Delete a patron that is not in storage - try { $r_us = $r_us->delete; } catch { $e_us = $_ }; + try { $r_us = $r_us->delete; } catch { $e_us = $_ }; try { $r_them = $r_them->delete; } catch { $e_them = $_ }; ok( defined $e_us && defined $e_them, 'Delete a patron that is not in storage should raise an exception' ); is( ref($e_us), 'DBIx::Class::Exception' ) - ; # FIXME This needs adjustement, we want to throw a Koha::Exception + ; # FIXME This needs adjustement, we want to throw a Koha::Exception # CASE 3 - Delete a patron that cannot be deleted (as a checkout) $patron = Koha::Patron->new($patron_data)->store; @@ -624,7 +675,7 @@ subtest 'Return same values as DBIx::Class' => sub { 'Delete a patron that cannot be deleted should raise an exception' ); is( ref($e_us), 'DBIx::Class::Exception' ) - ; # FIXME This needs adjustement, we want to throw a Koha::Exception + ; # FIXME This needs adjustement, we want to throw a Koha::Exception }; subtest 'Koha::Objects->delete' => sub { @@ -634,10 +685,10 @@ subtest 'Return same values as DBIx::Class' => sub { my ( $r_us, $e_us, $r_them, $e_them ); # CASE 1 - Delete existing objects - my $patron_1 = $builder->build_object({ class => 'Koha::Patrons' }); - my $patron_2 = $builder->build_object({ class => 'Koha::Patrons' }); - my $patron_3 = $builder->build_object({ class => 'Koha::Patrons' }); - my $patrons = Koha::Patrons->search( + my $patron_1 = $builder->build_object( { class => 'Koha::Patrons' } ); + my $patron_2 = $builder->build_object( { class => 'Koha::Patrons' } ); + my $patron_3 = $builder->build_object( { class => 'Koha::Patrons' } ); + my $patrons = Koha::Patrons->search( { borrowernumber => { -in => [ @@ -651,10 +702,10 @@ subtest 'Return same values as DBIx::Class' => sub { try { $r_us = $patrons->delete; } catch { $e_us = $_ }; - $patron_1 = $builder->build_object({ class => 'Koha::Patrons' }); - $patron_2 = $builder->build_object({ class => 'Koha::Patrons' }); - $patron_3 = $builder->build_object({ class => 'Koha::Patrons' }); - $patrons = $schema->resultset('Borrower')->search( + $patron_1 = $builder->build_object( { class => 'Koha::Patrons' } ); + $patron_2 = $builder->build_object( { class => 'Koha::Patrons' } ); + $patron_3 = $builder->build_object( { class => 'Koha::Patrons' } ); + $patrons = $schema->resultset('Borrower')->search( { borrowernumber => { -in => [ @@ -669,14 +720,17 @@ subtest 'Return same values as DBIx::Class' => sub { try { $r_them = $patrons->delete; } catch { $e_them = $_ }; ok( $r_us == 3 && $r_them == 3, '->delete should return the number of deleted patrons' ); - ok (!defined($e_us) && !defined($e_them), '->delete should not raise exception if everything went well'); + ok( + !defined($e_us) && !defined($e_them), + '->delete should not raise exception if everything went well' + ); # CASE 2 - One of the patrons is not in storage undef $_ for $r_us, $e_us, $r_them, $e_them; - $patron_1 = $builder->build_object({ class => 'Koha::Patrons' }); - $patron_2 = $builder->build_object({ class => 'Koha::Patrons' }); - $patron_3 = $builder->build_object({ class => 'Koha::Patrons' }); - $patrons = Koha::Patrons->search( + $patron_1 = $builder->build_object( { class => 'Koha::Patrons' } ); + $patron_2 = $builder->build_object( { class => 'Koha::Patrons' } ); + $patron_3 = $builder->build_object( { class => 'Koha::Patrons' } ); + $patrons = Koha::Patrons->search( { borrowernumber => { -in => [ @@ -688,13 +742,13 @@ subtest 'Return same values as DBIx::Class' => sub { } ); - $patron_2->delete; # We delete one of the patron + $patron_2->delete; # We delete one of the patron try { $r_us = $patrons->delete; } catch { $e_us = $_ }; - $patron_1 = $builder->build_object({ class => 'Koha::Patrons' }); - $patron_2 = $builder->build_object({ class => 'Koha::Patrons' }); - $patron_3 = $builder->build_object({ class => 'Koha::Patrons' }); - $patrons = $schema->resultset('Borrower')->search( + $patron_1 = $builder->build_object( { class => 'Koha::Patrons' } ); + $patron_2 = $builder->build_object( { class => 'Koha::Patrons' } ); + $patron_3 = $builder->build_object( { class => 'Koha::Patrons' } ); + $patrons = $schema->resultset('Borrower')->search( { borrowernumber => { -in => [ @@ -706,18 +760,24 @@ subtest 'Return same values as DBIx::Class' => sub { } ); - $patron_2->delete; # We delete one of the patron + $patron_2->delete; # We delete one of the patron try { $r_them = $patrons->delete; } catch { $e_them = $_ }; - ok( $r_us == 2 && $r_them == 2, 'Delete patrons with one that was not in storage should delete the patrons' ); - ok (!defined($e_us) && !defined($e_them), 'no exception should be raised if at least one patron was not in storage'); + ok( + $r_us == 2 && $r_them == 2, + 'Delete patrons with one that was not in storage should delete the patrons' + ); + ok( + !defined($e_us) && !defined($e_them), + 'no exception should be raised if at least one patron was not in storage' + ); # CASE 3 - Delete a set of patrons with one that that cannot be deleted (as a checkout) undef $_ for $r_us, $e_us, $r_them, $e_them; - $patron_1 = $builder->build_object({ class => 'Koha::Patrons' }); - $patron_2 = $builder->build_object({ class => 'Koha::Patrons' }); - $patron_3 = $builder->build_object({ class => 'Koha::Patrons' }); - $patrons = Koha::Patrons->search( + $patron_1 = $builder->build_object( { class => 'Koha::Patrons' } ); + $patron_2 = $builder->build_object( { class => 'Koha::Patrons' } ); + $patron_3 = $builder->build_object( { class => 'Koha::Patrons' } ); + $patrons = Koha::Patrons->search( { borrowernumber => { -in => [ @@ -740,10 +800,10 @@ subtest 'Return same values as DBIx::Class' => sub { try { $r_us = $patrons->delete; } catch { $e_us = $_ }; my $not_deleted_us = $patron_1->in_storage + $patron_2->in_storage + $patron_3->in_storage; - $patron_1 = $builder->build_object({ class => 'Koha::Patrons' }); - $patron_2 = $builder->build_object({ class => 'Koha::Patrons' }); - $patron_3 = $builder->build_object({ class => 'Koha::Patrons' }); - $patrons = $schema->resultset('Borrower')->search( + $patron_1 = $builder->build_object( { class => 'Koha::Patrons' } ); + $patron_2 = $builder->build_object( { class => 'Koha::Patrons' } ); + $patron_3 = $builder->build_object( { class => 'Koha::Patrons' } ); + $patrons = $schema->resultset('Borrower')->search( { borrowernumber => { -in => [ @@ -772,7 +832,10 @@ subtest 'Return same values as DBIx::Class' => sub { ); is( ref($e_us), 'Koha::Exceptions::Object::FKConstraintDeletion' ); - ok($not_deleted_us == 3 && $not_deleted_them == 3, 'If one patron cannot be deleted, none should have been deleted'); + ok( + $not_deleted_us == 3 && $not_deleted_them == 3, + 'If one patron cannot be deleted, none should have been deleted' + ); }; }; @@ -796,20 +859,24 @@ subtest 'Return same values as DBIx::Class' => sub { # CASE 1 - Update an existing object my $c_us = Koha::City->new( { city_name => 'city4test' } )->store; - try { $r_us = $c_us->update({ city_country => 'country4test' }); } catch { $e_us = $_ }; + try { $r_us = $c_us->update( { city_country => 'country4test' } ); } catch { $e_us = $_ }; my $c_them = $schema->resultset('City')->new( { city_name => 'city4test_2' } )->update_or_insert; - try { $r_them = $c_them->update({ city_country => 'country4test_2' }); } catch { $e_them = $_ }; - ok( ref($r_us) && ref($r_them), - 'Successful update should return the object ' ); - ok( !defined $e_us && !defined $e_them, - 'Successful update should not raise an exception' ); + try { $r_them = $c_them->update( { city_country => 'country4test_2' } ); } catch { $e_them = $_ }; + ok( + ref($r_us) && ref($r_them), + 'Successful update should return the object ' + ); + ok( + !defined $e_us && !defined $e_them, + 'Successful update should not raise an exception' + ); is( ref($r_us), 'Koha::City', 'Successful update should return our Koha::Obect based object' ); # CASE 2 - Update an object that is not in storage $c_us->delete; $c_them->delete; - try { $r_us = $c_us->update({ city_country => 'another_country' }); } catch { $e_us = $_ }; - try { $r_them = $c_them->update({ city_country => 'another_country' }); } catch { $e_them = $_ }; + try { $r_us = $c_us->update( { city_country => 'another_country' } ); } catch { $e_us = $_ }; + try { $r_them = $c_them->update( { city_country => 'another_country' } ); } catch { $e_them = $_ }; ok( defined $e_us && defined $e_them, 'Update an object that is not in storage should raise an exception' @@ -824,9 +891,9 @@ subtest 'Return same values as DBIx::Class' => sub { my ( $r_us, $e_us, $r_them, $e_them ); # CASE 1 - update existing objects - my $city_1 = $builder->build_object({ class => 'Koha::Cities' }); - my $city_2 = $builder->build_object({ class => 'Koha::Cities' }); - my $city_3 = $builder->build_object({ class => 'Koha::Cities' }); + my $city_1 = $builder->build_object( { class => 'Koha::Cities' } ); + my $city_2 = $builder->build_object( { class => 'Koha::Cities' } ); + my $city_3 = $builder->build_object( { class => 'Koha::Cities' } ); my $cities = Koha::Cities->search( { cityid => { @@ -839,11 +906,11 @@ subtest 'Return same values as DBIx::Class' => sub { } ); - try { $r_us = $cities->update({ city_country => 'country4test' }); } catch { $e_us = $_ }; + try { $r_us = $cities->update( { city_country => 'country4test' } ); } catch { $e_us = $_ }; - $city_1 = $builder->build_object({ class => 'Koha::Cities' }); - $city_2 = $builder->build_object({ class => 'Koha::Cities' }); - $city_3 = $builder->build_object({ class => 'Koha::Cities' }); + $city_1 = $builder->build_object( { class => 'Koha::Cities' } ); + $city_2 = $builder->build_object( { class => 'Koha::Cities' } ); + $city_3 = $builder->build_object( { class => 'Koha::Cities' } ); $cities = $schema->resultset('City')->search( { cityid => { @@ -856,15 +923,15 @@ subtest 'Return same values as DBIx::Class' => sub { } ); - try { $r_them = $cities->update({ city_country => 'country4test' }); } catch { $e_them = $_ }; + try { $r_them = $cities->update( { city_country => 'country4test' } ); } catch { $e_them = $_ }; ok( $r_us == 3 && $r_them == 3, '->update should return the number of updated cities' ); - ok(!defined($e_us) && !defined($e_them)); + ok( !defined($e_us) && !defined($e_them) ); # CASE 2 - One of the object is not in storage - $city_1 = $builder->build_object({ class => 'Koha::Cities' }); - $city_2 = $builder->build_object({ class => 'Koha::Cities' }); - $city_3 = $builder->build_object({ class => 'Koha::Cities' }); + $city_1 = $builder->build_object( { class => 'Koha::Cities' } ); + $city_2 = $builder->build_object( { class => 'Koha::Cities' } ); + $city_3 = $builder->build_object( { class => 'Koha::Cities' } ); $cities = Koha::Cities->search( { cityid => { @@ -877,12 +944,12 @@ subtest 'Return same values as DBIx::Class' => sub { } ); - $city_2->delete; # We delete one of the object - try { $r_us = $cities->update({ city_country => 'country4test' }); } catch { $e_us = $_ }; + $city_2->delete; # We delete one of the object + try { $r_us = $cities->update( { city_country => 'country4test' } ); } catch { $e_us = $_ }; - $city_1 = $builder->build_object({ class => 'Koha::Cities' }); - $city_2 = $builder->build_object({ class => 'Koha::Cities' }); - $city_3 = $builder->build_object({ class => 'Koha::Cities' }); + $city_1 = $builder->build_object( { class => 'Koha::Cities' } ); + $city_2 = $builder->build_object( { class => 'Koha::Cities' } ); + $city_3 = $builder->build_object( { class => 'Koha::Cities' } ); $cities = $schema->resultset('City')->search( { cityid => { @@ -895,18 +962,20 @@ subtest 'Return same values as DBIx::Class' => sub { } ); - $city_2->delete; # We delete one of the object - try { $r_them = $cities->update({ city_country => 'country4test' }); } catch { $e_them = $_ }; + $city_2->delete; # We delete one of the object + try { $r_them = $cities->update( { city_country => 'country4test' } ); } catch { $e_them = $_ }; ok( $r_us == 2 && $r_them == 2, '->update should return the number of updated cities' ); - ok(!defined($e_us) && !defined($e_them)); + ok( !defined($e_us) && !defined($e_them) ); - throws_ok - { Koha::Cities->update({ city_country => 'Castalia' }); } - 'Koha::Exceptions::Object::NotInstantiated', + throws_ok { Koha::Cities->update( { city_country => 'Castalia' } ); } + 'Koha::Exceptions::Object::NotInstantiated', 'Exception thrown if not instantiated class'; - is( "$@", 'Tried to access the \'update\' method, but Koha::Cities is not instantiated', 'Exception stringified correctly' ); + is( + "$@", 'Tried to access the \'update\' method, but Koha::Cities is not instantiated', + 'Exception stringified correctly' + ); }; }; @@ -922,24 +991,30 @@ subtest 'Return same values as DBIx::Class' => sub { my ( $r_us, $e_us, $r_them, $e_them ); # CASE 1 - Update an existing patron - my $patron_us = $builder->build_object({ class => 'Koha::Patrons' }); - try {$r_us = $patron_us->update({city => 'a_city'});} catch { $e_us = $_ }; + my $patron_us = $builder->build_object( { class => 'Koha::Patrons' } ); + try { $r_us = $patron_us->update( { city => 'a_city' } ); } catch { $e_us = $_ }; - my $patron_data = $builder->build_object({ class => 'Koha::Patrons' })->delete->unblessed; - my $patron_them = $schema->resultset('Borrower')->new( $patron_data )->update_or_insert; - try {$r_them = $patron_them->update({city => 'a_city'});} catch { $e_them = $_ }; - ok( ref($r_us) && ref($r_them), - 'Successful update should return the patron object' ); - ok( !defined $e_us && !defined $e_them, - 'Successful update should not raise an exception' ); - is( ref($r_us), 'Koha::Patron', - 'Successful update should return our Koha::Obect based object' ); + my $patron_data = $builder->build_object( { class => 'Koha::Patrons' } )->delete->unblessed; + my $patron_them = $schema->resultset('Borrower')->new($patron_data)->update_or_insert; + try { $r_them = $patron_them->update( { city => 'a_city' } ); } catch { $e_them = $_ }; + ok( + ref($r_us) && ref($r_them), + 'Successful update should return the patron object' + ); + ok( + !defined $e_us && !defined $e_them, + 'Successful update should not raise an exception' + ); + is( + ref($r_us), 'Koha::Patron', + 'Successful update should return our Koha::Obect based object' + ); # CASE 2 - Update a patron that is not in storage $patron_us->delete; $patron_them->delete; - try { $r_us = $patron_us->update({ city => 'another_city' }); } catch { $e_us = $_ }; - try { $r_them = $patron_them->update({ city => 'another_city' }); } catch { $e_them = $_ }; + try { $r_us = $patron_us->update( { city => 'another_city' } ); } catch { $e_us = $_ }; + try { $r_them = $patron_them->update( { city => 'another_city' } ); } catch { $e_them = $_ }; ok( defined $e_us && defined $e_them, 'Update a patron that is not in storage should raise an exception' @@ -955,9 +1030,9 @@ subtest 'Return same values as DBIx::Class' => sub { my ( $r_us, $e_us, $r_them, $e_them ); # CASE 1 - Update existing objects - my $patron_1 = $builder->build_object({ class => 'Koha::Patrons' }); - my $patron_2 = $builder->build_object({ class => 'Koha::Patrons' }); - my $patron_3 = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron_1 = $builder->build_object( { class => 'Koha::Patrons' } ); + my $patron_2 = $builder->build_object( { class => 'Koha::Patrons' } ); + my $patron_3 = $builder->build_object( { class => 'Koha::Patrons' } ); my $patrons_us = Koha::Patrons->search( { borrowernumber => { @@ -970,11 +1045,11 @@ subtest 'Return same values as DBIx::Class' => sub { } ); - try { $r_us = $patrons_us->update({ city => 'a_city' }); } catch { $e_us = $_ }; + try { $r_us = $patrons_us->update( { city => 'a_city' } ); } catch { $e_us = $_ }; - $patron_1 = $builder->build_object({ class => 'Koha::Patrons' }); - $patron_2 = $builder->build_object({ class => 'Koha::Patrons' }); - $patron_3 = $builder->build_object({ class => 'Koha::Patrons' }); + $patron_1 = $builder->build_object( { class => 'Koha::Patrons' } ); + $patron_2 = $builder->build_object( { class => 'Koha::Patrons' } ); + $patron_3 = $builder->build_object( { class => 'Koha::Patrons' } ); my $patrons_them = $schema->resultset('Borrower')->search( { borrowernumber => { @@ -987,16 +1062,19 @@ subtest 'Return same values as DBIx::Class' => sub { } ); - try { $r_them = $patrons_them->update({ city => 'a_city' }); } catch { $e_them = $_ }; + try { $r_them = $patrons_them->update( { city => 'a_city' } ); } catch { $e_them = $_ }; ok( $r_us == 3 && $r_them == 3, '->update should return the number of update patrons' ); - ok (!defined($e_us) && !defined($e_them), '->update should not raise exception if everything went well'); + ok( + !defined($e_us) && !defined($e_them), + '->update should not raise exception if everything went well' + ); # CASE 2 - One of the patrons is not in storage undef $_ for $r_us, $e_us, $r_them, $e_them; - $patron_1 = $builder->build_object({ class => 'Koha::Patrons' }); - $patron_2 = $builder->build_object({ class => 'Koha::Patrons' }); - $patron_3 = $builder->build_object({ class => 'Koha::Patrons' }); + $patron_1 = $builder->build_object( { class => 'Koha::Patrons' } ); + $patron_2 = $builder->build_object( { class => 'Koha::Patrons' } ); + $patron_3 = $builder->build_object( { class => 'Koha::Patrons' } ); $patrons_us = Koha::Patrons->search( { borrowernumber => { @@ -1009,12 +1087,12 @@ subtest 'Return same values as DBIx::Class' => sub { } ); - $patron_2->delete; # We delete one of the patron - try { $r_us = $patrons_us->update({ city => 'another_city' }); } catch { $e_us = $_ }; + $patron_2->delete; # We delete one of the patron + try { $r_us = $patrons_us->update( { city => 'another_city' } ); } catch { $e_us = $_ }; - $patron_1 = $builder->build_object({ class => 'Koha::Patrons' }); - $patron_2 = $builder->build_object({ class => 'Koha::Patrons' }); - $patron_3 = $builder->build_object({ class => 'Koha::Patrons' }); + $patron_1 = $builder->build_object( { class => 'Koha::Patrons' } ); + $patron_2 = $builder->build_object( { class => 'Koha::Patrons' } ); + $patron_3 = $builder->build_object( { class => 'Koha::Patrons' } ); $patrons_them = $schema->resultset('Borrower')->search( { borrowernumber => { @@ -1027,15 +1105,20 @@ subtest 'Return same values as DBIx::Class' => sub { } ); - $patron_2->delete; # We delete one of the patron - try { $r_them = $patrons_them->update({ city => 'another_city' }); } catch { $e_them = $_ }; - - ok( $r_us == 2 && $r_them == 2, 'Update patrons with one that was not in storage should update the patrons' ); - ok (!defined($e_us) && !defined($e_them), 'no exception should be raised if at least one patron was not in storage'); + $patron_2->delete; # We delete one of the patron + try { $r_them = $patrons_them->update( { city => 'another_city' } ); } catch { $e_them = $_ }; + ok( + $r_us == 2 && $r_them == 2, + 'Update patrons with one that was not in storage should update the patrons' + ); + ok( + !defined($e_us) && !defined($e_them), + 'no exception should be raised if at least one patron was not in storage' + ); # Testing no_triggers - t::lib::Mocks::mock_preference('uppercasesurnames', 1); + t::lib::Mocks::mock_preference( 'uppercasesurnames', 1 ); $patrons_us = Koha::Patrons->search( { borrowernumber => { @@ -1047,11 +1130,12 @@ subtest 'Return same values as DBIx::Class' => sub { } } ); - $patrons_us->update({ surname => 'foo' }); # Koha::Patron->store is supposed to uppercase the surnames - is( $patrons_us->search({ surname => 'FOO' })->count, 2, 'Koha::Patron->store is hit' ); + $patrons_us->update( { surname => 'foo' } ); # Koha::Patron->store is supposed to uppercase the surnames + is( $patrons_us->search( { surname => 'FOO' } )->count, 2, 'Koha::Patron->store is hit' ); - $patrons_us->update({ surname => 'foo' }, { no_triggers => 1 }); # The surnames won't be uppercase as we won't hit Koha::Patron->store - is( $patrons_us->search({ surname => 'foo' })->count, 2, 'Koha::Patron->store is not hit'); + $patrons_us->update( { surname => 'foo' }, { no_triggers => 1 } ) + ; # The surnames won't be uppercase as we won't hit Koha::Patron->store + is( $patrons_us->search( { surname => 'foo' } )->count, 2, 'Koha::Patron->store is not hit' ); }; @@ -1092,65 +1176,54 @@ subtest "filter_by_last_update" => sub { my $now = dt_from_string->truncate( to => 'day' ); my @borrowernumbers; + # Building 6 patrons that have been created today, yesterday, ... 1 per day for my $i ( 0 .. 5 ) { push @borrowernumbers, - $builder->build_object( + $builder->build_object( { class => 'Koha::Patrons', value => { updated_on => $now->clone->subtract( days => $i ) } } - )->borrowernumber; + )->borrowernumber; } - my $patrons = Koha::Patrons->search( - { borrowernumber => { -in => \@borrowernumbers } } ); + my $patrons = Koha::Patrons->search( { borrowernumber => { -in => \@borrowernumbers } } ); try { - $patrons->filter_by_last_update( { timestamp_column_name => 'updated_on' } ) - ->count; - } - catch { + $patrons->filter_by_last_update( { timestamp_column_name => 'updated_on' } )->count; + } catch { ok( $_->isa('Koha::Exceptions::MissingParameter'), 'Should raise an exception if no parameter given' ); }; - my $filtered_patrons = $patrons->filter_by_last_update( - { timestamp_column_name => 'updated_on', days => 2 } ); + my $filtered_patrons = $patrons->filter_by_last_update( { timestamp_column_name => 'updated_on', days => 2 } ); is( ref($filtered_patrons), 'Koha::Patrons', 'filter_by_last_update must return a Koha::Objects-based object' ); - my $count = $patrons->filter_by_last_update( - { timestamp_column_name => 'updated_on', days => 2 } )->count; + my $count = $patrons->filter_by_last_update( { timestamp_column_name => 'updated_on', days => 2 } )->count; is( $count, 3, '3 patrons have been updated before the last 2 days (exclusive)' ); - $count = $patrons->filter_by_last_update( - { timestamp_column_name => 'updated_on', min_days => 2 } )->count; + $count = $patrons->filter_by_last_update( { timestamp_column_name => 'updated_on', min_days => 2 } )->count; is( $count, 4, '4 patrons have been updated before the last 2 days (inclusive)' ); - $count = $patrons->filter_by_last_update( - { timestamp_column_name => 'updated_on', days => 1 } )->count; + $count = $patrons->filter_by_last_update( { timestamp_column_name => 'updated_on', days => 1 } )->count; is( $count, 4, '4 patrons have been updated before yesterday (exclusive)' ); - $count = $patrons->filter_by_last_update( - { timestamp_column_name => 'updated_on', min_days => 1 } )->count; + $count = $patrons->filter_by_last_update( { timestamp_column_name => 'updated_on', min_days => 1 } )->count; is( $count, 5, '5 patrons have been updated before yesterday (inclusive)' ); - $count = $patrons->filter_by_last_update( - { timestamp_column_name => 'updated_on', days => 0 } )->count; + $count = $patrons->filter_by_last_update( { timestamp_column_name => 'updated_on', days => 0 } )->count; is( $count, 5, '5 patrons have been updated before today (exclusive)' ); - $count = $patrons->filter_by_last_update( - { timestamp_column_name => 'updated_on', min_days => 0 } )->count; + $count = $patrons->filter_by_last_update( { timestamp_column_name => 'updated_on', min_days => 0 } )->count; is( $count, 6, '6 patrons have been updated before today (inclusive)' ); - $count = $patrons->filter_by_last_update( - { timestamp_column_name => 'updated_on', from => $now } )->count; + $count = $patrons->filter_by_last_update( { timestamp_column_name => 'updated_on', from => $now } )->count; is( $count, 1, '1 patron has been updated "from today" (inclusive)' ); - $count = $patrons->filter_by_last_update( - { timestamp_column_name => 'updated_on', to => $now } )->count; + $count = $patrons->filter_by_last_update( { timestamp_column_name => 'updated_on', to => $now } )->count; is( $count, 6, '6 patrons have been updated "to today" (inclusive)' ); $count = $patrons->filter_by_last_update( @@ -1163,15 +1236,15 @@ subtest "filter_by_last_update" => sub { is( $count, 3, '3 patrons have been updated between D-4 and D-2' ); throws_ok { - $count = $patrons->filter_by_last_update( - { timestamp_column_name => 'updated_on', from => '1970-12-31' } ) - ->count; - } 'Koha::Exceptions::WrongParameter', 'from parameter must be a DateTime object'; + $count = + $patrons->filter_by_last_update( { timestamp_column_name => 'updated_on', from => '1970-12-31' } )->count; + } + 'Koha::Exceptions::WrongParameter', 'from parameter must be a DateTime object'; throws_ok { - $count = $patrons->filter_by_last_update( - { timestamp_column_name => 'updated_on', to => '1970-12-31' } ) - ->count; - } 'Koha::Exceptions::WrongParameter', 'to parameter must be a DateTime object'; + $count = + $patrons->filter_by_last_update( { timestamp_column_name => 'updated_on', to => '1970-12-31' } )->count; + } + 'Koha::Exceptions::WrongParameter', 'to parameter must be a DateTime object'; subtest 'Parameters older_than, younger_than' => sub { my $now = dt_from_string(); @@ -1263,23 +1336,25 @@ subtest 'empty() tests' => sub { $schema->storage->txn_begin; # Add a patron, we need at least 1 - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); ok( Koha::Patrons->count > 0, 'There is at least one Koha::Patron on the resultset' ); my $empty = Koha::Patrons->new->empty; - is( ref($empty), 'Koha::Patrons', '->empty returns a Koha::Patrons iterator' ); - is( $empty->count, 0, 'The empty resultset is, well, empty :-D' ); + is( ref($empty), 'Koha::Patrons', '->empty returns a Koha::Patrons iterator' ); + is( $empty->count, 0, 'The empty resultset is, well, empty :-D' ); - my $new_rs = $empty->search({ borrowernumber => $patron->borrowernumber }); + my $new_rs = $empty->search( { borrowernumber => $patron->borrowernumber } ); is( $new_rs->count, 0, 'Further chaining an empty resultset, returns an empty resultset' ); - throws_ok - { Koha::Patrons->empty; } - 'Koha::Exceptions::Object::NotInstantiated', + throws_ok { Koha::Patrons->empty; } + 'Koha::Exceptions::Object::NotInstantiated', 'Exception thrown if not instantiated class'; - is( "$@", 'Tried to access the \'empty\' method, but Koha::Patrons is not instantiated', 'Exception stringified correctly' ); + is( + "$@", 'Tried to access the \'empty\' method, but Koha::Patrons is not instantiated', + 'Exception stringified correctly' + ); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/Koha/Objects/Mixin/AdditionalFields.t b/t/db_dependent/Koha/Objects/Mixin/AdditionalFields.t index 301a40ff41..37e90b1e55 100755 --- a/t/db_dependent/Koha/Objects/Mixin/AdditionalFields.t +++ b/t/db_dependent/Koha/Objects/Mixin/AdditionalFields.t @@ -4,7 +4,7 @@ use Modern::Perl; use Test::More tests => 12; -use Koha::Acquisition::Baskets; # Koha::Acquisition::Baskets uses the mixin +use Koha::Acquisition::Baskets; # Koha::Acquisition::Baskets uses the mixin use Koha::AdditionalFields; use Koha::AdditionalFieldValues; use Koha::Database; @@ -15,32 +15,44 @@ my $storage = Koha::Database->new->schema->storage; $storage->txn_begin; my $builder = t::lib::TestBuilder->new; -my $basket1 = $builder->build_object({ - class => 'Koha::Acquisition::Baskets', -}); -my $basket2 = $builder->build_object({ - class => 'Koha::Acquisition::Baskets', -}); +my $basket1 = $builder->build_object( + { + class => 'Koha::Acquisition::Baskets', + } +); +my $basket2 = $builder->build_object( + { + class => 'Koha::Acquisition::Baskets', + } +); -my $foo = Koha::AdditionalField->new({ - tablename => 'aqbasket', - name => 'basket_foo', -})->store; -my $bar = Koha::AdditionalField->new({ - tablename => 'aqbasket', - name => 'basket_bar', -})->store; +my $foo = Koha::AdditionalField->new( + { + tablename => 'aqbasket', + name => 'basket_foo', + } +)->store; +my $bar = Koha::AdditionalField->new( + { + tablename => 'aqbasket', + name => 'basket_bar', + } +)->store; -Koha::AdditionalFieldValue->new({ - field_id => $foo->id, - record_id => $basket1->basketno, - value => 'foo value for basket1', -})->store; -Koha::AdditionalFieldValue->new({ - field_id => $bar->id, - record_id => $basket1->basketno, - value => 'bar value for basket1', -})->store; +Koha::AdditionalFieldValue->new( + { + field_id => $foo->id, + record_id => $basket1->basketno, + value => 'foo value for basket1', + } +)->store; +Koha::AdditionalFieldValue->new( + { + field_id => $bar->id, + record_id => $basket1->basketno, + value => 'bar value for basket1', + } +)->store; my $additional_fields_for_basket2 = [ { @@ -55,7 +67,10 @@ my $additional_fields_for_basket2 = [ $basket2->set_additional_fields($additional_fields_for_basket2); my $additional_fields = $basket2->additional_field_values; -is( ref($additional_fields), 'Koha::AdditionalFieldValues', '->additional_field_values should return a Koha::AdditionalFieldValues object' ); +is( + ref($additional_fields), 'Koha::AdditionalFieldValues', + '->additional_field_values should return a Koha::AdditionalFieldValues object' +); is_deeply( [ map { @@ -65,7 +80,7 @@ is_deeply( record_id => $_->{record_id}, value => $_->{value}, } - } sort{ $a->{id} <=> $b->{id} } @{ $additional_fields->unblessed } + } sort { $a->{id} <=> $b->{id} } @{ $additional_fields->unblessed } ], [ { @@ -83,74 +98,86 @@ is_deeply( '->additional_field_values should return the correct values' ); -my @baskets = Koha::Acquisition::Baskets->filter_by_additional_fields([ - { - id => $foo->id, - value => 'foo value for basket1', - }, -])->as_list; +my @baskets = Koha::Acquisition::Baskets->filter_by_additional_fields( + [ + { + id => $foo->id, + value => 'foo value for basket1', + }, + ] +)->as_list; -is(scalar @baskets, 1, 'search returns only one result'); -is($baskets[0]->basketno, $basket1->basketno, 'result is basket1'); +is( scalar @baskets, 1, 'search returns only one result' ); +is( $baskets[0]->basketno, $basket1->basketno, 'result is basket1' ); -@baskets = Koha::Acquisition::Baskets->filter_by_additional_fields([ - { - id => $foo->id, - value => 'foo value for basket2', - }, -])->as_list; +@baskets = Koha::Acquisition::Baskets->filter_by_additional_fields( + [ + { + id => $foo->id, + value => 'foo value for basket2', + }, + ] +)->as_list; -is(scalar @baskets, 1, 'search returns only one result'); -is($baskets[0]->basketno, $basket2->basketno, 'result is basket2'); +is( scalar @baskets, 1, 'search returns only one result' ); +is( $baskets[0]->basketno, $basket2->basketno, 'result is basket2' ); -@baskets = Koha::Acquisition::Baskets->filter_by_additional_fields([ - { - id => $foo->id, - value => 'foo value for basket1', - }, - { - id => $bar->id, - value => 'bar value for basket1', - }, -])->as_list; +@baskets = Koha::Acquisition::Baskets->filter_by_additional_fields( + [ + { + id => $foo->id, + value => 'foo value for basket1', + }, + { + id => $bar->id, + value => 'bar value for basket1', + }, + ] +)->as_list; -is(scalar @baskets, 1, 'search returns only one result'); -is($baskets[0]->basketno, $basket1->basketno, 'result is basket1'); +is( scalar @baskets, 1, 'search returns only one result' ); +is( $baskets[0]->basketno, $basket1->basketno, 'result is basket1' ); -@baskets = Koha::Acquisition::Baskets->filter_by_additional_fields([ - { - id => $foo->id, - value => 'foo value for basket1', - }, - { - id => $bar->id, - value => 'bar value for basket2', - }, -])->as_list; +@baskets = Koha::Acquisition::Baskets->filter_by_additional_fields( + [ + { + id => $foo->id, + value => 'foo value for basket1', + }, + { + id => $bar->id, + value => 'bar value for basket2', + }, + ] +)->as_list; -is(scalar @baskets, 0, 'search returns no result'); +is( scalar @baskets, 0, 'search returns no result' ); -@baskets = Koha::Acquisition::Baskets->filter_by_additional_fields([ - { - id => $foo->id, - value => 'foo', - }, -])->as_list; +@baskets = Koha::Acquisition::Baskets->filter_by_additional_fields( + [ + { + id => $foo->id, + value => 'foo', + }, + ] +)->as_list; -is(scalar @baskets, 2, 'search returns two results'); +is( scalar @baskets, 2, 'search returns two results' ); -@baskets = Koha::Acquisition::Baskets->filter_by_additional_fields([ - { - id => $foo->id, - value => 'foo', - }, - { - id => $foo->id, - value => 'basket1', - }, -])->as_list; +@baskets = Koha::Acquisition::Baskets->filter_by_additional_fields( + [ + { + id => $foo->id, + value => 'foo', + }, + { + id => $foo->id, + value => 'basket1', + }, + ] +)->as_list; -is(scalar @baskets, 1, 'search returns only one result'); -is($baskets[0]->basketno, $basket1->basketno, 'result is basket1'); +is( scalar @baskets, 1, 'search returns only one result' ); +is( $baskets[0]->basketno, $basket1->basketno, 'result is basket1' ); $storage->txn_rollback; diff --git a/t/db_dependent/Koha/Old.t b/t/db_dependent/Koha/Old.t index 42bdbe4d65..d630d21c5a 100755 --- a/t/db_dependent/Koha/Old.t +++ b/t/db_dependent/Koha/Old.t @@ -38,15 +38,11 @@ subtest 'Koha::Old::Patrons' => sub { $schema->storage->txn_begin; - my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $patron_unblessed = $patron->unblessed; $patron->move_to_deleted; $patron->delete; - my $deleted_patron = Koha::Old::Patrons->search( - { - borrowernumber => $patron->borrowernumber - } - )->next->unblessed; + my $deleted_patron = Koha::Old::Patrons->search( { borrowernumber => $patron->borrowernumber } )->next->unblessed; delete $deleted_patron->{updated_on}; delete $patron_unblessed->{updated_on}; is_deeply( $deleted_patron, $patron_unblessed ); @@ -55,6 +51,7 @@ subtest 'Koha::Old::Patrons' => sub { }; subtest 'Koha::Old::Biblios and Koha::Old::Items' => sub { + # Cannot be tested in a meaningful way so far ok(1); }; @@ -65,17 +62,15 @@ subtest 'Koha::Old::Checkout->library() tests' => sub { $schema->storage->txn_begin; - my $library = $builder->build_object({ class => 'Koha::Libraries' }); + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); my $checkout = $builder->build_object( { class => 'Koha::Old::Checkouts', - value => { - branchcode => $library->branchcode - } + value => { branchcode => $library->branchcode } } ); - is( ref($checkout->library), 'Koha::Library', 'Object type is correct' ); + is( ref( $checkout->library ), 'Koha::Library', 'Object type is correct' ); is( $checkout->library->branchcode, $library->branchcode, 'Right library linked' ); $library->delete; diff --git a/t/db_dependent/Koha/Old/Checkout.t b/t/db_dependent/Koha/Old/Checkout.t index 7cf520e96f..840afe052f 100755 --- a/t/db_dependent/Koha/Old/Checkout.t +++ b/t/db_dependent/Koha/Old/Checkout.t @@ -55,28 +55,32 @@ subtest 'anonymize() tests' => sub { t::lib::Mocks::mock_preference( 'AnonymousPatron', undef ); - throws_ok - { $checkout_1->anonymize; } - 'Koha::Exceptions::SysPref::NotSet', + throws_ok { $checkout_1->anonymize; } + 'Koha::Exceptions::SysPref::NotSet', 'Exception thrown because AnonymousPatron not set'; - is( $@->syspref, 'AnonymousPatron', 'syspref parameter is correctly passed' ); - is( $patron->old_checkouts->count, 2, 'No changes, patron has 2 linked completed checkouts' ); + is( $@->syspref, 'AnonymousPatron', 'syspref parameter is correctly passed' ); + is( $patron->old_checkouts->count, 2, 'No changes, patron has 2 linked completed checkouts' ); - is( $checkout_1->borrowernumber, $patron->id, - 'Anonymized hold not linked to patron' ); - is( $checkout_2->borrowernumber, $patron->id, - 'Not anonymized hold still linked to patron' ); + is( + $checkout_1->borrowernumber, $patron->id, + 'Anonymized hold not linked to patron' + ); + is( + $checkout_2->borrowernumber, $patron->id, + 'Not anonymized hold still linked to patron' + ); - my $anonymous_patron = - $builder->build_object( { class => 'Koha::Patrons' } ); + my $anonymous_patron = $builder->build_object( { class => 'Koha::Patrons' } ); t::lib::Mocks::mock_preference( 'AnonymousPatron', $anonymous_patron->id ); # anonymize second hold $checkout_2->anonymize; $checkout_2->discard_changes; - is( $checkout_2->borrowernumber, $anonymous_patron->id, - 'Anonymized hold linked to anonymouspatron' ); + is( + $checkout_2->borrowernumber, $anonymous_patron->id, + 'Anonymized hold linked to anonymouspatron' + ); $schema->storage->txn_rollback; }; @@ -100,7 +104,7 @@ subtest 'deleteitem() tests' => sub { my $item_to_del = $checkout_3->item; $item_to_del->delete; $checkout_3->discard_changes(); - is( $checkout_3->item, undef, "Item is deleted"); + is( $checkout_3->item, undef, "Item is deleted" ); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/Koha/Old/Checkouts.t b/t/db_dependent/Koha/Old/Checkouts.t index 250b258a6e..73c3368835 100755 --- a/t/db_dependent/Koha/Old/Checkouts.t +++ b/t/db_dependent/Koha/Old/Checkouts.t @@ -36,30 +36,30 @@ subtest 'anonymize() tests' => sub { $schema->storage->txn_begin; - my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); - my $anonymous_patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + my $anonymous_patron = $builder->build_object( { class => 'Koha::Patrons' } ); is( $patron->old_checkouts->count, 0, 'Patron has no old checkouts' ); t::lib::Mocks::mock_preference( 'AnonymousPatron', undef ); - throws_ok - { $patron->old_checkouts->anonymize; } - 'Koha::Exceptions::SysPref::NotSet', + throws_ok { $patron->old_checkouts->anonymize; } + 'Koha::Exceptions::SysPref::NotSet', 'Exception thrown because AnonymousPatron not set'; is( $@->syspref, 'AnonymousPatron', 'syspref parameter is correctly passed' ); t::lib::Mocks::mock_preference( 'AnonymousPatron', $anonymous_patron->id ); - is( $patron->old_checkouts->anonymize + 0, - 0, 'Anonymizing an empty resultset returns 0' ); + is( + $patron->old_checkouts->anonymize + 0, + 0, 'Anonymizing an empty resultset returns 0' + ); my $checkout_1 = $builder->build_object( { class => 'Koha::Old::Checkouts', - value => - { borrowernumber => $patron->id, timestamp => dt_from_string() } + value => { borrowernumber => $patron->id, timestamp => dt_from_string() } } ); my $checkout_2 = $builder->build_object( @@ -93,17 +93,15 @@ subtest 'anonymize() tests' => sub { is( $patron->old_checkouts->count, 4, 'Patron has 4 completed checkouts' ); # filter them so only the older two are part of the resultset - my $checkouts = $patron->old_checkouts->filter_by_last_update( - { min_days => 1 } ); + my $checkouts = $patron->old_checkouts->filter_by_last_update( { min_days => 1 } ); t::lib::Mocks::mock_preference( 'AnonymousPatron', undef ); - throws_ok - { $checkouts->anonymize; } - 'Koha::Exceptions::SysPref::NotSet', + throws_ok { $checkouts->anonymize; } + 'Koha::Exceptions::SysPref::NotSet', 'Exception thrown because AnonymousPatron not set'; - is( $@->syspref, 'AnonymousPatron', 'syspref parameter is correctly passed' ); - is( $patron->old_checkouts->count, 4, 'Patron has 4 completed checkouts' ); + is( $@->syspref, 'AnonymousPatron', 'syspref parameter is correctly passed' ); + is( $patron->old_checkouts->count, 4, 'Patron has 4 completed checkouts' ); t::lib::Mocks::mock_preference( 'AnonymousPatron', $anonymous_patron->id ); @@ -122,16 +120,14 @@ subtest 'filter_by_anonymizable() tests' => sub { $schema->storage->txn_begin; - my $anonymous_patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $anonymous_patron = $builder->build_object( { class => 'Koha::Patrons' } ); t::lib::Mocks::mock_preference( 'AnonymousPatron', $anonymous_patron->id ); # patron_1 => keep records forever - my $patron_1 = $builder->build_object( - { class => 'Koha::Patrons', value => { privacy => 0 } } ); + my $patron_1 = $builder->build_object( { class => 'Koha::Patrons', value => { privacy => 0 } } ); # patron_2 => never keep records - my $patron_2 = $builder->build_object( - { class => 'Koha::Patrons', value => { privacy => 1 } } ); + my $patron_2 = $builder->build_object( { class => 'Koha::Patrons', value => { privacy => 1 } } ); is( $patron_1->old_checkouts->count, 0, 'patron_1 has no old checkouts' ); is( $patron_2->old_checkouts->count, 0, 'patron_2 has no old checkouts' ); @@ -168,6 +164,7 @@ subtest 'filter_by_anonymizable() tests' => sub { } } ); + # borrowernumber == undef => never listed as anonymizable my $checkout_5 = $builder->build_object( { @@ -177,6 +174,7 @@ subtest 'filter_by_anonymizable() tests' => sub { } } ); + # borrowernumber == anonymous patron => never listed as anonymizable my $checkout_6 = $builder->build_object( { @@ -195,14 +193,12 @@ subtest 'filter_by_anonymizable() tests' => sub { is( $patron_2->old_checkouts->count, 2, 'patron_2 has 2 completed checkouts' ); # filter them so only the older two are part of the resultset - my $checkouts = Koha::Old::Checkouts->search( - { 'me.borrowernumber' => [ $patron_1->id, $patron_2->id ] } ); + my $checkouts = Koha::Old::Checkouts->search( { 'me.borrowernumber' => [ $patron_1->id, $patron_2->id ] } ); is( $checkouts->count, 4, 'Total of 4 checkouts returned correctly' ); my $rs = $checkouts->filter_by_anonymizable; is( $rs->count, 2, 'Only 2 can be anonymized' ); - $rs = $checkouts->filter_by_anonymizable->filter_by_last_update( - { days => 1 } ); + $rs = $checkouts->filter_by_anonymizable->filter_by_last_update( { days => 1 } ); is( $rs->count, 1, 'Only 1 can be anonymized with date filter applied' ); diff --git a/t/db_dependent/Koha/Old/Hold.t b/t/db_dependent/Koha/Old/Hold.t index 3b52b5ee27..1204766b72 100755 --- a/t/db_dependent/Koha/Old/Hold.t +++ b/t/db_dependent/Koha/Old/Hold.t @@ -55,28 +55,32 @@ subtest 'anonymize() tests' => sub { t::lib::Mocks::mock_preference( 'AnonymousPatron', undef ); - throws_ok - { $hold_1->anonymize; } - 'Koha::Exceptions::SysPref::NotSet', + throws_ok { $hold_1->anonymize; } + 'Koha::Exceptions::SysPref::NotSet', 'Exception thrown because AnonymousPatron not set'; - is( $@->syspref, 'AnonymousPatron', 'syspref parameter is correctly passed' ); - is( $patron->old_holds->count, 2, 'No changes, patron has 2 linked completed holds' ); + is( $@->syspref, 'AnonymousPatron', 'syspref parameter is correctly passed' ); + is( $patron->old_holds->count, 2, 'No changes, patron has 2 linked completed holds' ); - is( $hold_1->borrowernumber, $patron->id, - 'Anonymized hold not linked to patron' ); - is( $hold_2->borrowernumber, $patron->id, - 'Not anonymized hold still linked to patron' ); + is( + $hold_1->borrowernumber, $patron->id, + 'Anonymized hold not linked to patron' + ); + is( + $hold_2->borrowernumber, $patron->id, + 'Not anonymized hold still linked to patron' + ); - my $anonymous_patron = - $builder->build_object( { class => 'Koha::Patrons' } ); + my $anonymous_patron = $builder->build_object( { class => 'Koha::Patrons' } ); t::lib::Mocks::mock_preference( 'AnonymousPatron', $anonymous_patron->id ); # anonymize second hold $hold_2->anonymize; $hold_2->discard_changes; - is( $hold_2->borrowernumber, $anonymous_patron->id, - 'Anonymized hold linked to anonymouspatron' ); + is( + $hold_2->borrowernumber, $anonymous_patron->id, + 'Anonymized hold linked to anonymouspatron' + ); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/Koha/Old/Holds.t b/t/db_dependent/Koha/Old/Holds.t index cd791ad350..401bdb280b 100755 --- a/t/db_dependent/Koha/Old/Holds.t +++ b/t/db_dependent/Koha/Old/Holds.t @@ -36,16 +36,15 @@ subtest 'anonymize() tests' => sub { $schema->storage->txn_begin; - my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); - my $anonymous_patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + my $anonymous_patron = $builder->build_object( { class => 'Koha::Patrons' } ); is( $patron->old_holds->count, 0, 'Patron has no old holds' ); t::lib::Mocks::mock_preference( 'AnonymousPatron', undef ); - throws_ok - { $patron->old_holds->anonymize; } - 'Koha::Exceptions::SysPref::NotSet', + throws_ok { $patron->old_holds->anonymize; } + 'Koha::Exceptions::SysPref::NotSet', 'Exception thrown because AnonymousPatron not set'; is( $@->syspref, 'AnonymousPatron', 'syspref parameter is correctly passed' ); @@ -57,8 +56,7 @@ subtest 'anonymize() tests' => sub { my $hold_1 = $builder->build_object( { class => 'Koha::Old::Holds', - value => - { borrowernumber => $patron->id, timestamp => dt_from_string() } + value => { borrowernumber => $patron->id, timestamp => dt_from_string() } } ); my $hold_2 = $builder->build_object( @@ -90,18 +88,19 @@ subtest 'anonymize() tests' => sub { ); is( $patron->old_holds->count, 4, 'Patron has 4 completed holds' ); + # filter them so only the older two are part of the resultset - my $holds = $patron->old_holds->search({ timestamp => { '<=' => dt_from_string()->subtract( days => 2 ) } }); + my $holds = $patron->old_holds->search( { timestamp => { '<=' => dt_from_string()->subtract( days => 2 ) } } ); + # Anonymize them t::lib::Mocks::mock_preference( 'AnonymousPatron', undef ); - throws_ok - { $holds->anonymize; } - 'Koha::Exceptions::SysPref::NotSet', + throws_ok { $holds->anonymize; } + 'Koha::Exceptions::SysPref::NotSet', 'Exception thrown because AnonymousPatron not set'; - is( $@->syspref, 'AnonymousPatron', 'syspref parameter is correctly passed' ); - is( $patron->old_holds->count, 4, 'Patron has 4 completed holds' ); + is( $@->syspref, 'AnonymousPatron', 'syspref parameter is correctly passed' ); + is( $patron->old_holds->count, 4, 'Patron has 4 completed holds' ); t::lib::Mocks::mock_preference( 'AnonymousPatron', $anonymous_patron->id ); @@ -120,12 +119,10 @@ subtest 'filter_by_anonymizable() tests' => sub { $schema->storage->txn_begin; # patron_1 => keep records forever - my $patron_1 = $builder->build_object( - { class => 'Koha::Patrons', value => { privacy => 0 } } ); + my $patron_1 = $builder->build_object( { class => 'Koha::Patrons', value => { privacy => 0 } } ); # patron_2 => never keep records - my $patron_2 = $builder->build_object( - { class => 'Koha::Patrons', value => { privacy => 1 } } ); + my $patron_2 = $builder->build_object( { class => 'Koha::Patrons', value => { privacy => 1 } } ); is( $patron_1->old_holds->count, 0, 'patron_1 has no old holds' ); is( $patron_2->old_holds->count, 0, 'patron_2 has no old holds' ); @@ -163,28 +160,24 @@ subtest 'filter_by_anonymizable() tests' => sub { } )->_move_to_old; - $hold_1 = Koha::Old::Holds->find( $hold_1->id ) - ->set( { timestamp => dt_from_string() } )->store; - $hold_2 = Koha::Old::Holds->find( $hold_2->id ) - ->set( { timestamp => dt_from_string()->subtract( days => 1 ) } )->store; - $hold_3 = Koha::Old::Holds->find( $hold_3->id ) - ->set( { timestamp => dt_from_string()->subtract( days => 2 ) } )->store; - $hold_4 = Koha::Old::Holds->find( $hold_4->id ) - ->set( { timestamp => dt_from_string()->subtract( days => 3 ) } )->store; + $hold_1 = Koha::Old::Holds->find( $hold_1->id )->set( { timestamp => dt_from_string() } )->store; + $hold_2 = + Koha::Old::Holds->find( $hold_2->id )->set( { timestamp => dt_from_string()->subtract( days => 1 ) } )->store; + $hold_3 = + Koha::Old::Holds->find( $hold_3->id )->set( { timestamp => dt_from_string()->subtract( days => 2 ) } )->store; + $hold_4 = + Koha::Old::Holds->find( $hold_4->id )->set( { timestamp => dt_from_string()->subtract( days => 3 ) } )->store; is( $patron_1->old_holds->count, 2, 'patron_1 has 2 completed holds' ); is( $patron_2->old_holds->count, 2, 'patron_2 has 2 completed holds' ); # filter them so only the older two are part of the resultset - my $holds = Koha::Old::Holds->search( - { 'me.borrowernumber' => [ $patron_1->id, $patron_2->id ] } ); + my $holds = Koha::Old::Holds->search( { 'me.borrowernumber' => [ $patron_1->id, $patron_2->id ] } ); is( $holds->count, 4, 'Total of 4 holds returned correctly' ); my $rs = $holds->filter_by_anonymizable; is( $rs->count, 2, 'Only 2 can be anonymized' ); - $rs = $holds - ->filter_by_anonymizable - ->filter_by_last_update( { days => 1 } ); + $rs = $holds->filter_by_anonymizable->filter_by_last_update( { days => 1 } ); is( $rs->count, 1, 'Only 1 can be anonymized with date filter applied' ); diff --git a/t/db_dependent/Koha/Patron.t b/t/db_dependent/Koha/Patron.t index 32189c6c95..f1ea69f046 100755 --- a/t/db_dependent/Koha/Patron.t +++ b/t/db_dependent/Koha/Patron.t @@ -126,27 +126,27 @@ subtest 'Accessor tests' => sub { subtest 'Accessor tests after new' => sub { plan tests => 60; - is( $patron->borrowernumber, '12345', 'borrowernumber accessor returns correct value' ); - is( $patron->cardnumber, '1234567890', 'cardnumber accessor returns correct value' ); - is( $patron->surname, 'mySurname', 'surname accessor returns correct value' ); - is( $patron->firstname, 'myFirstname', 'firstname accessor returns correct value' ); - is( $patron->title, 'Mr.', 'title accessor returns correct value' ); - is( $patron->othernames, 'myOthernames', 'othernames accessor returns correct value' ); - is( $patron->initials, 'MM', 'initials accessor returns correct value' ); - is( $patron->streetnumber, '100', 'streetnumber accessor returns correct value' ); - is( $patron->streettype, 'Blvd', 'streettype accessor returns correct value' ); - is( $patron->address, 'my personal address', 'address accessor returns correct value' ); - is( $patron->address2, 'my adress2', 'address2 accessor returns correct value' ); - is( $patron->city, 'Marseille', 'city accessor returns correct value' ); - is( $patron->state, 'mystate', 'state accessor returns correct value' ); - is( $patron->zipcode, '13006', 'zipcode accessor returns correct value' ); - is( $patron->country, 'France', 'country accessor returns correct value' ); - is( $patron->email, 'mySurname.myFirstname@email.com', 'email accessor returns correct value' ); - is( $patron->phone, '0402872934', 'phone accessor returns correct value' ); - is( $patron->mobile, '0627884632', 'mobile accessor returns correct value' ); - is( $patron->fax, '0402872935', 'fax accessor returns correct value' ); - is( $patron->emailpro, 'myEmailPro@email.com', 'emailpro accessor returns correct value' ); - is( $patron->phonepro, '0402873334', 'phonepro accessor returns correct value' ); + is( $patron->borrowernumber, '12345', 'borrowernumber accessor returns correct value' ); + is( $patron->cardnumber, '1234567890', 'cardnumber accessor returns correct value' ); + is( $patron->surname, 'mySurname', 'surname accessor returns correct value' ); + is( $patron->firstname, 'myFirstname', 'firstname accessor returns correct value' ); + is( $patron->title, 'Mr.', 'title accessor returns correct value' ); + is( $patron->othernames, 'myOthernames', 'othernames accessor returns correct value' ); + is( $patron->initials, 'MM', 'initials accessor returns correct value' ); + is( $patron->streetnumber, '100', 'streetnumber accessor returns correct value' ); + is( $patron->streettype, 'Blvd', 'streettype accessor returns correct value' ); + is( $patron->address, 'my personal address', 'address accessor returns correct value' ); + is( $patron->address2, 'my adress2', 'address2 accessor returns correct value' ); + is( $patron->city, 'Marseille', 'city accessor returns correct value' ); + is( $patron->state, 'mystate', 'state accessor returns correct value' ); + is( $patron->zipcode, '13006', 'zipcode accessor returns correct value' ); + is( $patron->country, 'France', 'country accessor returns correct value' ); + is( $patron->email, 'mySurname.myFirstname@email.com', 'email accessor returns correct value' ); + is( $patron->phone, '0402872934', 'phone accessor returns correct value' ); + is( $patron->mobile, '0627884632', 'mobile accessor returns correct value' ); + is( $patron->fax, '0402872935', 'fax accessor returns correct value' ); + is( $patron->emailpro, 'myEmailPro@email.com', 'emailpro accessor returns correct value' ); + is( $patron->phonepro, '0402873334', 'phonepro accessor returns correct value' ); is( $patron->B_streetnumber, '101', 'B_streetnumber accessor returns correct value' ); is( $patron->B_streettype, 'myB_streettype', 'B_streettype accessor returns correct value' ); is( $patron->B_address, 'myB_address', 'B_address accessor returns correct value' ); @@ -355,11 +355,13 @@ subtest 'is_active' => sub { $patron->lastseen($ago)->store; is( $patron->is_active( { days => 1 } ), 0, 'Not active since yesterday' ); is( $patron->is_active( { days => 3 } ), 1, 'Active within last 3 days' ); + # test since parameter my $dt = $ago->clone->add( hours => 1 ); is( $patron->is_active( { since => $dt } ), 0, 'Inactive since ago + 1 hour' ); $dt = $ago->clone->subtract( hours => 1 ); is( $patron->is_active( { since => $dt } ), 1, 'Active since ago - 1 hour' ); + # test weeks parameter is( $patron->is_active( { weeks => 1 } ), 1, 'Active within last week' ); @@ -374,24 +376,22 @@ subtest 'add_guarantor() tests' => sub { t::lib::Mocks::mock_preference( 'borrowerRelationship', 'father1|father2' ); - my $patron_1 = $builder->build_object({ class => 'Koha::Patrons' }); - my $patron_2 = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron_1 = $builder->build_object( { class => 'Koha::Patrons' } ); + my $patron_2 = $builder->build_object( { class => 'Koha::Patrons' } ); - throws_ok - { $patron_1->add_guarantor({ guarantor_id => $patron_2->borrowernumber }); } - 'Koha::Exceptions::Patron::Relationship::InvalidRelationship', + throws_ok { $patron_1->add_guarantor( { guarantor_id => $patron_2->borrowernumber } ); } + 'Koha::Exceptions::Patron::Relationship::InvalidRelationship', 'Exception is thrown as no relationship passed'; is( $patron_1->guarantee_relationships->count, 0, 'No guarantors added' ); - throws_ok - { $patron_1->add_guarantor({ guarantor_id => $patron_2->borrowernumber, relationship => 'father' }); } - 'Koha::Exceptions::Patron::Relationship::InvalidRelationship', + throws_ok { $patron_1->add_guarantor( { guarantor_id => $patron_2->borrowernumber, relationship => 'father' } ); } + 'Koha::Exceptions::Patron::Relationship::InvalidRelationship', 'Exception is thrown as a wrong relationship was passed'; is( $patron_1->guarantee_relationships->count, 0, 'No guarantors added' ); - $patron_1->add_guarantor({ guarantor_id => $patron_2->borrowernumber, relationship => 'father1' }); + $patron_1->add_guarantor( { guarantor_id => $patron_2->borrowernumber, relationship => 'father1' } ); my $guarantors = $patron_1->guarantor_relationships; @@ -400,9 +400,10 @@ subtest 'add_guarantor() tests' => sub { { local *STDERR; open STDERR, '>', '/dev/null'; - throws_ok - { $patron_1->add_guarantor({ guarantor_id => $patron_2->borrowernumber, relationship => 'father2' }); } - 'Koha::Exceptions::Patron::Relationship::DuplicateRelationship', + throws_ok { + $patron_1->add_guarantor( { guarantor_id => $patron_2->borrowernumber, relationship => 'father2' } ); + } + 'Koha::Exceptions::Patron::Relationship::DuplicateRelationship', 'Exception is thrown for duplicated relationship'; close STDERR; } @@ -467,66 +468,68 @@ subtest 'relationships_debt() tests' => sub { t::lib::Mocks::mock_preference( 'borrowerRelationship', 'parent' ); - my $parent_1 = $builder->build_object({ class => 'Koha::Patrons', value => { firstname => "Parent 1" } }); - my $parent_2 = $builder->build_object({ class => 'Koha::Patrons', value => { firstname => "Parent 2" } }); - my $child_1 = $builder->build_object({ class => 'Koha::Patrons', value => { firstname => " Child 1" } }); - my $child_2 = $builder->build_object({ class => 'Koha::Patrons', value => { firstname => " Child 2" } }); + my $parent_1 = $builder->build_object( { class => 'Koha::Patrons', value => { firstname => "Parent 1" } } ); + my $parent_2 = $builder->build_object( { class => 'Koha::Patrons', value => { firstname => "Parent 2" } } ); + my $child_1 = $builder->build_object( { class => 'Koha::Patrons', value => { firstname => " Child 1" } } ); + my $child_2 = $builder->build_object( { class => 'Koha::Patrons', value => { firstname => " Child 2" } } ); - $child_1->add_guarantor({ guarantor_id => $parent_1->borrowernumber, relationship => 'parent' }); - $child_1->add_guarantor({ guarantor_id => $parent_2->borrowernumber, relationship => 'parent' }); - $child_2->add_guarantor({ guarantor_id => $parent_1->borrowernumber, relationship => 'parent' }); - $child_2->add_guarantor({ guarantor_id => $parent_2->borrowernumber, relationship => 'parent' }); + $child_1->add_guarantor( { guarantor_id => $parent_1->borrowernumber, relationship => 'parent' } ); + $child_1->add_guarantor( { guarantor_id => $parent_2->borrowernumber, relationship => 'parent' } ); + $child_2->add_guarantor( { guarantor_id => $parent_1->borrowernumber, relationship => 'parent' } ); + $child_2->add_guarantor( { guarantor_id => $parent_2->borrowernumber, relationship => 'parent' } ); - is( $child_1->guarantor_relationships->guarantors->count, 2, 'Child 1 has correct number of guarantors' ); - is( $child_2->guarantor_relationships->guarantors->count, 2, 'Child 2 has correct number of guarantors' ); + is( $child_1->guarantor_relationships->guarantors->count, 2, 'Child 1 has correct number of guarantors' ); + is( $child_2->guarantor_relationships->guarantors->count, 2, 'Child 2 has correct number of guarantors' ); is( $parent_1->guarantee_relationships->guarantees->count, 2, 'Parent 1 has correct number of guarantees' ); is( $parent_2->guarantee_relationships->guarantees->count, 2, 'Parent 2 has correct number of guarantees' ); my $patrons = [ $parent_1, $parent_2, $child_1, $child_2 ]; # First test: No debt - my ($parent1_debt, $parent2_debt, $child1_debt, $child2_debt) = (0,0,0,0); - _test_combinations($patrons, $parent1_debt,$parent2_debt,$child1_debt,$child2_debt); + my ( $parent1_debt, $parent2_debt, $child1_debt, $child2_debt ) = ( 0, 0, 0, 0 ); + _test_combinations( $patrons, $parent1_debt, $parent2_debt, $child1_debt, $child2_debt ); # Add debt to child_2 $child2_debt = 2; - $child_2->account->add_debit({ type => 'ACCOUNT', amount => $child2_debt, interface => 'commandline' }); + $child_2->account->add_debit( { type => 'ACCOUNT', amount => $child2_debt, interface => 'commandline' } ); is( $child_2->account->non_issues_charges, $child2_debt, 'Debt added to Child 2' ); - _test_combinations($patrons, $parent1_debt,$parent2_debt,$child1_debt,$child2_debt); + _test_combinations( $patrons, $parent1_debt, $parent2_debt, $child1_debt, $child2_debt ); $parent1_debt = 3; - $parent_1->account->add_debit({ type => 'ACCOUNT', amount => $parent1_debt, interface => 'commandline' }); + $parent_1->account->add_debit( { type => 'ACCOUNT', amount => $parent1_debt, interface => 'commandline' } ); is( $parent_1->account->non_issues_charges, $parent1_debt, 'Debt added to Parent 1' ); - _test_combinations($patrons, $parent1_debt,$parent2_debt,$child1_debt,$child2_debt); + _test_combinations( $patrons, $parent1_debt, $parent2_debt, $child1_debt, $child2_debt ); $parent2_debt = 5; - $parent_2->account->add_debit({ type => 'ACCOUNT', amount => $parent2_debt, interface => 'commandline' }); + $parent_2->account->add_debit( { type => 'ACCOUNT', amount => $parent2_debt, interface => 'commandline' } ); is( $parent_2->account->non_issues_charges, $parent2_debt, 'Parent 2 owes correct amount' ); - _test_combinations($patrons, $parent1_debt,$parent2_debt,$child1_debt,$child2_debt); + _test_combinations( $patrons, $parent1_debt, $parent2_debt, $child1_debt, $child2_debt ); $child1_debt = 7; - $child_1->account->add_debit({ type => 'ACCOUNT', amount => $child1_debt, interface => 'commandline' }); + $child_1->account->add_debit( { type => 'ACCOUNT', amount => $child1_debt, interface => 'commandline' } ); is( $child_1->account->non_issues_charges, $child1_debt, 'Child 1 owes correct amount' ); - _test_combinations($patrons, $parent1_debt,$parent2_debt,$child1_debt,$child2_debt); + _test_combinations( $patrons, $parent1_debt, $parent2_debt, $child1_debt, $child2_debt ); $schema->storage->txn_rollback; }; sub _test_combinations { my ( $patrons, $parent1_debt, $parent2_debt, $child1_debt, $child2_debt ) = @_; - note("Testing with parent 1 debt $parent1_debt | Parent 2 debt $parent2_debt | Child 1 debt $child1_debt | Child 2 debt $child2_debt"); + note( + "Testing with parent 1 debt $parent1_debt | Parent 2 debt $parent2_debt | Child 1 debt $child1_debt | Child 2 debt $child2_debt" + ); + # Options # P1 => P1 + C1 + C2 ( - P1 ) ( + P2 ) # P2 => P2 + C1 + C2 ( - P2 ) ( + P1 ) # C1 => P1 + P2 + C1 + C2 ( - C1 ) # C2 => P1 + P2 + C1 + C2 ( - C2 ) -# 3 params, count from 0 to 7 in binary ( 3 places ) to get the set of switches, then do that 4 times, one for each parent and child + # 3 params, count from 0 to 7 in binary ( 3 places ) to get the set of switches, then do that 4 times, one for each parent and child for my $i ( 0 .. 7 ) { - my ( $only_this_guarantor, $include_guarantors, $include_this_patron ) - = split '', sprintf( "%03b", $i ); + my ( $only_this_guarantor, $include_guarantors, $include_this_patron ) = split '', sprintf( "%03b", $i ); note("---------------------"); - for my $patron ( @$patrons ) { + for my $patron (@$patrons) { if ( $only_this_guarantor && !$patron->guarantee_relationships->count ) { @@ -540,28 +543,24 @@ sub _test_combinations { ); } 'Koha::Exceptions::BadParameter', - 'Exception is thrown as patron is not a guarantor'; + 'Exception is thrown as patron is not a guarantor'; - } - else { + } else { my $debt = 0; if ( $patron->firstname eq 'Parent 1' ) { - $debt += $parent1_debt if ($include_this_patron && $include_guarantors); + $debt += $parent1_debt if ( $include_this_patron && $include_guarantors ); $debt += $child1_debt + $child2_debt; - $debt += $parent2_debt unless ($only_this_guarantor || !$include_guarantors); - } - elsif ( $patron->firstname eq 'Parent 2' ) { - $debt += $parent2_debt if ($include_this_patron & $include_guarantors); + $debt += $parent2_debt unless ( $only_this_guarantor || !$include_guarantors ); + } elsif ( $patron->firstname eq 'Parent 2' ) { + $debt += $parent2_debt if ( $include_this_patron & $include_guarantors ); $debt += $child1_debt + $child2_debt; - $debt += $parent1_debt unless ($only_this_guarantor || !$include_guarantors); - } - elsif ( $patron->firstname eq ' Child 1' ) { + $debt += $parent1_debt unless ( $only_this_guarantor || !$include_guarantors ); + } elsif ( $patron->firstname eq ' Child 1' ) { $debt += $child1_debt if ($include_this_patron); $debt += $child2_debt; $debt += $parent1_debt + $parent2_debt if ($include_guarantors); - } - else { + } else { $debt += $child2_debt if ($include_this_patron); $debt += $child1_debt; $debt += $parent1_debt + $parent2_debt if ($include_guarantors); @@ -577,7 +576,9 @@ sub _test_combinations { ), $debt, $patron->firstname - . " debt of " . sprintf('%02d',$debt) . " calculated correctly for ( only_this_guarantor: $only_this_guarantor, include_guarantors: $include_guarantors, include_this_patron: $include_this_patron)" + . " debt of " + . sprintf( '%02d', $debt ) + . " calculated correctly for ( only_this_guarantor: $only_this_guarantor, include_guarantors: $include_guarantors, include_this_patron: $include_this_patron)" ); } } @@ -596,18 +597,14 @@ subtest 'add_enrolment_fee_if_needed() tests' => sub { my $category = $builder->build_object( { class => 'Koha::Patron::Categories', - value => { - enrolmentfee => 20 - } + value => { enrolmentfee => 20 } } ); my $patron = $builder->build_object( { class => 'Koha::Patrons', - value => { - categorycode => $category->categorycode - } + value => { categorycode => $category->categorycode } } ); @@ -615,16 +612,18 @@ subtest 'add_enrolment_fee_if_needed() tests' => sub { is( $enrollment_fee * 1, 20, 'Enrolment fee amount is correct' ); my $account = $patron->account; is( $patron->account->balance * 1, 20, 'Patron charged the enrolment fee' ); + # second enrolment fee, new $enrollment_fee = $patron->add_enrolment_fee_if_needed(0); + # third enrolment fee, renewal $enrollment_fee = $patron->add_enrolment_fee_if_needed(1); is( $patron->account->balance * 1, 60, 'Patron charged the enrolment fees' ); my @debits = $account->outstanding_debits->as_list; - is( scalar @debits, 3, '3 enrolment fees' ); - is( $debits[0]->debit_type_code, 'ACCOUNT', 'Account type set correctly' ); - is( $debits[1]->debit_type_code, 'ACCOUNT', 'Account type set correctly' ); + is( scalar @debits, 3, '3 enrolment fees' ); + is( $debits[0]->debit_type_code, 'ACCOUNT', 'Account type set correctly' ); + is( $debits[1]->debit_type_code, 'ACCOUNT', 'Account type set correctly' ); is( $debits[2]->debit_type_code, 'ACCOUNT_RENEW', 'Account type set correctly' ); $schema->storage->txn_rollback; @@ -639,18 +638,14 @@ subtest 'add_enrolment_fee_if_needed() tests' => sub { my $category = $builder->build_object( { class => 'Koha::Patron::Categories', - value => { - enrolmentfee => 0 - } + value => { enrolmentfee => 0 } } ); my $patron = $builder->build_object( { class => 'Koha::Patrons', - value => { - categorycode => $category->categorycode - } + value => { categorycode => $category->categorycode } } ); @@ -671,48 +666,49 @@ subtest 'messaging_preferences() tests' => sub { $schema->storage->txn_begin; - my $mtt = $builder->build_object({ - class => 'Koha::Patron::MessagePreference::Transport::Types' - }); - my $attribute = $builder->build_object({ - class => 'Koha::Patron::MessagePreference::Attributes' - }); - my $branchcode = $builder->build({ - source => 'Branch' })->{branchcode}; - my $letter = $builder->build_object({ - class => 'Koha::Notice::Templates', - value => { - branchcode => '', - is_html => 0, - message_transport_type => $mtt->message_transport_type + my $mtt = $builder->build_object( { class => 'Koha::Patron::MessagePreference::Transport::Types' } ); + my $attribute = $builder->build_object( { class => 'Koha::Patron::MessagePreference::Attributes' } ); + my $branchcode = $builder->build( { source => 'Branch' } )->{branchcode}; + my $letter = $builder->build_object( + { + class => 'Koha::Notice::Templates', + value => { + branchcode => '', + is_html => 0, + message_transport_type => $mtt->message_transport_type + } } - }); + ); - Koha::Patron::MessagePreference::Transport->new({ - message_attribute_id => $attribute->message_attribute_id, - message_transport_type => $mtt->message_transport_type, - is_digest => 0, - letter_module => $letter->module, - letter_code => $letter->code, - })->store; + Koha::Patron::MessagePreference::Transport->new( + { + message_attribute_id => $attribute->message_attribute_id, + message_transport_type => $mtt->message_transport_type, + is_digest => 0, + letter_module => $letter->module, + letter_code => $letter->code, + } + )->store; - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); - my $preference = Koha::Patron::MessagePreference->new({ - borrowernumber => $patron->borrowernumber, - message_attribute_id => $attribute->message_attribute_id, - wants_digest => 0, - days_in_advance => undef, - })->store; + my $preference = Koha::Patron::MessagePreference->new( + { + borrowernumber => $patron->borrowernumber, + message_attribute_id => $attribute->message_attribute_id, + wants_digest => 0, + days_in_advance => undef, + } + )->store; my $messaging_preferences = $patron->messaging_preferences(); - is($messaging_preferences->count, 1, 'Found one preference'); + is( $messaging_preferences->count, 1, 'Found one preference' ); my $messaging_preference = $messaging_preferences->next; - is($messaging_preference->borrowernumber, $patron->borrowernumber); - is($messaging_preference->message_attribute_id, $attribute->message_attribute_id); - is($messaging_preference->wants_digest, 0); - is($messaging_preference->days_in_advance, undef); + is( $messaging_preference->borrowernumber, $patron->borrowernumber ); + is( $messaging_preference->message_attribute_id, $attribute->message_attribute_id ); + is( $messaging_preference->wants_digest, 0 ); + is( $messaging_preference->days_in_advance, undef ); $schema->storage->txn_rollback; }; @@ -772,7 +768,7 @@ subtest 'login_attempts tests' => sub { $patron->delete; delete $patron_info->{login_attempts}; my $new_patron = Koha::Patron->new($patron_info)->store; - is( $new_patron->discard_changes->login_attempts, 0, "login_attempts defaults to 0 as expected"); + is( $new_patron->discard_changes->login_attempts, 0, "login_attempts defaults to 0 as expected" ); $schema->storage->txn_rollback; }; @@ -787,9 +783,7 @@ subtest 'is_superlibrarian() tests' => sub { { class => 'Koha::Patrons', - value => { - flags => 16 - } + value => { flags => 16 } } ); @@ -813,10 +807,10 @@ subtest 'extended_attributes' => sub { Koha::Patron::Attribute::Types->search->delete; - my $patron_1 = $builder->build_object({class=> 'Koha::Patrons'}); - my $patron_2 = $builder->build_object({class=> 'Koha::Patrons'}); + my $patron_1 = $builder->build_object( { class => 'Koha::Patrons' } ); + my $patron_2 = $builder->build_object( { class => 'Koha::Patrons' } ); - t::lib::Mocks::mock_userenv({ patron => $patron_1 }); + t::lib::Mocks::mock_userenv( { patron => $patron_1 } ); my $attribute_type1 = Koha::Patron::Attribute::Type->new( { @@ -835,39 +829,42 @@ subtest 'extended_attributes' => sub { )->store; my $new_library = $builder->build( { source => 'Branch' } ); - my $attribute_type_limited = Koha::Patron::Attribute::Type->new( - { code => 'my code3', description => 'my description3' } )->store; + my $attribute_type_limited = + Koha::Patron::Attribute::Type->new( { code => 'my code3', description => 'my description3' } )->store; $attribute_type_limited->library_limits( [ $new_library->{branchcode} ] ); my $attributes_for_1 = [ { attribute => 'my attribute1', - code => $attribute_type1->code(), + code => $attribute_type1->code(), }, { attribute => 'my attribute2', - code => $attribute_type2->code(), + code => $attribute_type2->code(), }, { attribute => 'my attribute limited', - code => $attribute_type_limited->code(), + code => $attribute_type_limited->code(), } ]; my $attributes_for_2 = [ { attribute => 'my attribute12', - code => $attribute_type1->code(), + code => $attribute_type1->code(), }, { attribute => 'my attribute limited 2', - code => $attribute_type_limited->code(), + code => $attribute_type_limited->code(), } ]; my $extended_attributes = $patron_1->extended_attributes; - is( ref($extended_attributes), 'Koha::Patron::Attributes', 'Koha::Patron->extended_attributes must return a Koha::Patron::Attribute set' ); - is( $extended_attributes->count, 0, 'There should not be attribute yet'); + is( + ref($extended_attributes), 'Koha::Patron::Attributes', + 'Koha::Patron->extended_attributes must return a Koha::Patron::Attribute set' + ); + is( $extended_attributes->count, 0, 'There should not be attribute yet' ); $patron_1->extended_attributes->filter_by_branch_limitations->delete; $patron_2->extended_attributes->filter_by_branch_limitations->delete; @@ -875,16 +872,19 @@ subtest 'extended_attributes' => sub { $patron_2->extended_attributes($attributes_for_2); my $extended_attributes_for_1 = $patron_1->extended_attributes; - is( $extended_attributes_for_1->count, 3, 'There should be 3 attributes now for patron 1'); + is( $extended_attributes_for_1->count, 3, 'There should be 3 attributes now for patron 1' ); my $extended_attributes_for_2 = $patron_2->extended_attributes; - is( $extended_attributes_for_2->count, 2, 'There should be 2 attributes now for patron 2'); + is( $extended_attributes_for_2->count, 2, 'There should be 2 attributes now for patron 2' ); - my $attribute_12 = $extended_attributes_for_2->search({ code => $attribute_type1->code })->next; + my $attribute_12 = $extended_attributes_for_2->search( { code => $attribute_type1->code } )->next; is( $attribute_12->attribute, 'my attribute12', 'search by code should return the correct attribute' ); $attribute_12 = $patron_2->get_extended_attribute( $attribute_type1->code ); - is( $attribute_12->attribute, 'my attribute12', 'Koha::Patron->get_extended_attribute should return the correct attribute value' ); + is( + $attribute_12->attribute, 'my attribute12', + 'Koha::Patron->get_extended_attribute should return the correct attribute value' + ); my $expected_attributes_for_2 = [ { @@ -896,6 +896,7 @@ subtest 'extended_attributes' => sub { attribute => 'my attribute limited 2', } ]; + # Sorting them by code $expected_attributes_for_2 = [ sort { $a->{code} cmp $b->{code} } @$expected_attributes_for_2 ]; my @extended_attributes_for_2 = $extended_attributes_for_2->as_list; @@ -915,18 +916,28 @@ subtest 'extended_attributes' => sub { ); # TODO - What about multiple? POD explains the problem - my $non_existent = $patron_2->get_extended_attribute( 'not_exist' ); - is( $non_existent, undef, 'Koha::Patron->get_extended_attribute must return undef if the attribute does not exist' ); + my $non_existent = $patron_2->get_extended_attribute('not_exist'); + is( + $non_existent, undef, + 'Koha::Patron->get_extended_attribute must return undef if the attribute does not exist' + ); # Test branch limitations - t::lib::Mocks::mock_userenv({ patron => $patron_2 }); + t::lib::Mocks::mock_userenv( { patron => $patron_2 } ); + # Return all $extended_attributes_for_1 = $patron_1->extended_attributes; - is( $extended_attributes_for_1->count, 3, 'There should be 2 attributes for patron 1, the limited one should be returned'); + is( + $extended_attributes_for_1->count, 3, + 'There should be 2 attributes for patron 1, the limited one should be returned' + ); # Return filtered $extended_attributes_for_1 = $patron_1->extended_attributes->filter_by_branch_limitations; - is( $extended_attributes_for_1->count, 2, 'There should be 2 attributes for patron 1, the limited one should be returned'); + is( + $extended_attributes_for_1->count, 2, + 'There should be 2 attributes for patron 1, the limited one should be returned' + ); # Not filtered my $limited_value = $patron_1->get_extended_attribute( $attribute_type_limited->code ); @@ -945,7 +956,7 @@ subtest 'extended_attributes' => sub { $schema->storage->txn_begin; Koha::Patron::Attribute::Types->search->delete; - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $attribute_type = $builder->build_object( { class => 'Koha::Patron::Attribute::Types', @@ -955,16 +966,15 @@ subtest 'extended_attributes' => sub { is( $patron->extended_attributes->count, 0, 'Patron has no extended attributes' ); - throws_ok - { - $patron->extended_attributes( - [ - { code => $attribute_type->code, attribute => 'a' }, - { code => $attribute_type->code, attribute => 'b' } - ] - ); - } - 'Koha::Exceptions::Patron::Attribute::NonRepeatable', + throws_ok { + $patron->extended_attributes( + [ + { code => $attribute_type->code, attribute => 'a' }, + { code => $attribute_type->code, attribute => 'b' } + ] + ); + } + 'Koha::Exceptions::Patron::Attribute::NonRepeatable', 'Exception thrown on non-repeatable attribute'; is( $patron->extended_attributes->count, 0, 'Extended attributes storing rolled back' ); @@ -980,8 +990,8 @@ subtest 'extended_attributes' => sub { $schema->storage->txn_begin; Koha::Patron::Attribute::Types->search->delete; - my $patron_1 = $builder->build_object({ class => 'Koha::Patrons' }); - my $patron_2 = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron_1 = $builder->build_object( { class => 'Koha::Patrons' } ); + my $patron_2 = $builder->build_object( { class => 'Koha::Patrons' } ); my $attribute_type_1 = $builder->build_object( { @@ -1007,16 +1017,15 @@ subtest 'extended_attributes' => sub { ] ); - throws_ok - { - $patron_2->extended_attributes( - [ - { code => $attribute_type_1->code, attribute => 'a' }, - { code => $attribute_type_2->code, attribute => 'a' } - ] - ); - } - 'Koha::Exceptions::Patron::Attribute::UniqueIDConstraint', + throws_ok { + $patron_2->extended_attributes( + [ + { code => $attribute_type_1->code, attribute => 'a' }, + { code => $attribute_type_2->code, attribute => 'a' } + ] + ); + } + 'Koha::Exceptions::Patron::Attribute::UniqueIDConstraint', 'Exception thrown on unique attribute'; is( $patron_1->extended_attributes->count, 2, 'Extended attributes stored' ); @@ -1033,7 +1042,7 @@ subtest 'extended_attributes' => sub { $schema->storage->txn_begin; Koha::Patron::Attribute::Types->search->delete; - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $attribute_type_1 = $builder->build_object( { @@ -1042,27 +1051,22 @@ subtest 'extended_attributes' => sub { } ); - my $attribute_type_2 = $builder->build_object( - { - class => 'Koha::Patron::Attribute::Types' - } - ); + my $attribute_type_2 = $builder->build_object( { class => 'Koha::Patron::Attribute::Types' } ); my $type_2 = $attribute_type_2->code; $attribute_type_2->delete; is( $patron->extended_attributes->count, 0, 'Patron has no extended attributes' ); - throws_ok - { - $patron->extended_attributes( - [ - { code => $attribute_type_1->code, attribute => 'a' }, - { code => $attribute_type_2->code, attribute => 'b' } - ] - ); - } - 'Koha::Exceptions::Patron::Attribute::InvalidType', + throws_ok { + $patron->extended_attributes( + [ + { code => $attribute_type_1->code, attribute => 'a' }, + { code => $attribute_type_2->code, attribute => 'b' } + ] + ); + } + 'Koha::Exceptions::Patron::Attribute::InvalidType', 'Exception thrown on invalid attribute type'; is( $patron->extended_attributes->count, 0, 'Extended attributes storing rolled back' ); @@ -1167,7 +1171,7 @@ subtest 'extended_attributes' => sub { $schema->storage->txn_begin; Koha::Patron::Attribute::Types->search->delete; - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $attribute_type_1 = $builder->build_object( { @@ -1176,25 +1180,21 @@ subtest 'extended_attributes' => sub { } ); - $patron->extended_attributes( - [ - { code => $attribute_type_1->code, attribute => 'a' } - ] - ); + $patron->extended_attributes( [ { code => $attribute_type_1->code, attribute => 'a' } ] ); is( $patron->extended_attributes->count, 1, 'Extended attributes succeeded' ); - $patron = $builder->build_object({ class => 'Koha::Patrons' }); + $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + # new patron, new category - they shouldn't be required to have any attributes - - ok( $patron->extended_attributes([]), "We can set no attributes, mandatory attribute for other category not required"); - + ok( + $patron->extended_attributes( [] ), + "We can set no attributes, mandatory attribute for other category not required" + ); }; - - }; subtest 'can_log_into() tests' => sub { @@ -1206,28 +1206,26 @@ subtest 'can_log_into() tests' => sub { my $patron = $builder->build_object( { class => 'Koha::Patrons', - value => { - flags => undef - } + value => { flags => undef } } ); - my $library = $builder->build_object({ class => 'Koha::Libraries' }); + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); - t::lib::Mocks::mock_preference('IndependentBranches', 1); + t::lib::Mocks::mock_preference( 'IndependentBranches', 1 ); ok( $patron->can_log_into( $patron->library ), 'Patron can log into its own library' ); - ok( !$patron->can_log_into( $library ), 'Patron cannot log into different library, IndependentBranches on' ); + ok( !$patron->can_log_into($library), 'Patron cannot log into different library, IndependentBranches on' ); # make it a superlibrarian - $patron->set({ flags => 1 })->store->discard_changes; - ok( $patron->can_log_into( $library ), 'Superlibrarian can log into different library, IndependentBranches on' ); + $patron->set( { flags => 1 } )->store->discard_changes; + ok( $patron->can_log_into($library), 'Superlibrarian can log into different library, IndependentBranches on' ); - t::lib::Mocks::mock_preference('IndependentBranches', 0); + t::lib::Mocks::mock_preference( 'IndependentBranches', 0 ); # No special permissions - $patron->set({ flags => undef })->store->discard_changes; + $patron->set( { flags => undef } )->store->discard_changes; ok( $patron->can_log_into( $patron->library ), 'Patron can log into its own library' ); - ok( $patron->can_log_into( $library ), 'Patron can log into any library' ); + ok( $patron->can_log_into($library), 'Patron can log into any library' ); $schema->storage->txn_rollback; }; @@ -1298,8 +1296,10 @@ subtest 'can_request_article() tests' => sub { } ); - ok( !$patron->can_request_article( $library_1->id ), - '3 current requests and a completed one the same day: denied' ); + ok( + !$patron->can_request_article( $library_1->id ), + '3 current requests and a completed one the same day: denied' + ); $completed->updated_on( dt_from_string->add( days => -1 )->set( @@ -1309,8 +1309,10 @@ subtest 'can_request_article() tests' => sub { ) )->store; - ok( $patron->can_request_article( $library_1->id ), - '3 current requests and a completed one the day before: allowed' ); + ok( + $patron->can_request_article( $library_1->id ), + '3 current requests and a completed one the day before: allowed' + ); Koha::CirculationRules->set_rule( { @@ -1321,7 +1323,8 @@ subtest 'can_request_article() tests' => sub { } ); - ok( !$patron->can_request_article, + ok( + !$patron->can_request_article, 'Not passing the library_id param makes it fallback to userenv: denied' ); @@ -1334,14 +1337,16 @@ subtest 'article_requests() tests' => sub { $schema->storage->txn_begin; - my $library = $builder->build_object({ class => 'Koha::Libraries' }); + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); t::lib::Mocks::mock_userenv( { branchcode => $library->id } ); my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $article_requests = $patron->article_requests; - is( ref($article_requests), 'Koha::ArticleRequests', - 'In scalar context, type is correct' ); + is( + ref($article_requests), 'Koha::ArticleRequests', + 'In scalar context, type is correct' + ); is( $article_requests->count, 0, 'No article requests' ); foreach my $i ( 0 .. 3 ) { @@ -1375,21 +1380,18 @@ subtest 'can_patron_change_staff_only_lists() tests' => sub { my $patron = $builder->build_object( { class => 'Koha::Patrons', - value => { - flags => undef - } + value => { flags => undef } } ); - is( $patron->can_patron_change_staff_only_lists(), 0, 'Patron without permissions cannot change staff only lists'); + is( $patron->can_patron_change_staff_only_lists(), 0, 'Patron without permissions cannot change staff only lists' ); # make it a 'Catalogue' permission - $patron->set({ flags => 4 })->store->discard_changes; - is( $patron->can_patron_change_staff_only_lists(), 1, 'Catalogue patron can change staff only lists'); - + $patron->set( { flags => 4 } )->store->discard_changes; + is( $patron->can_patron_change_staff_only_lists(), 1, 'Catalogue patron can change staff only lists' ); # make it a superlibrarian - $patron->set({ flags => 1 })->store->discard_changes; - is( $patron->can_patron_change_staff_only_lists(), 1, 'Superlibrarian patron can change staff only lists'); + $patron->set( { flags => 1 } )->store->discard_changes; + is( $patron->can_patron_change_staff_only_lists(), 1, 'Superlibrarian patron can change staff only lists' ); $schema->storage->txn_rollback; }; @@ -1404,19 +1406,20 @@ subtest 'can_patron_change_permitted_staff_lists() tests' => sub { my $patron = $builder->build_object( { class => 'Koha::Patrons', - value => { - flags => undef - } + value => { flags => undef } } ); - is( $patron->can_patron_change_permitted_staff_lists(), 0, 'Patron without permissions cannot change permitted staff lists'); + is( + $patron->can_patron_change_permitted_staff_lists(), 0, + 'Patron without permissions cannot change permitted staff lists' + ); # make it a 'Catalogue' permission - $patron->set({ flags => 4 })->store->discard_changes; - is( $patron->can_patron_change_permitted_staff_lists(), 0, 'Catalogue patron cannot change permitted staff lists'); + $patron->set( { flags => 4 } )->store->discard_changes; + is( $patron->can_patron_change_permitted_staff_lists(), 0, 'Catalogue patron cannot change permitted staff lists' ); # make it a 'Catalogue' permission and 'edit_public_list_contents' sub-permission - $patron->set({ flags => 4 })->store->discard_changes; + $patron->set( { flags => 4 } )->store->discard_changes; $builder->build( { source => 'UserPermission', @@ -1427,11 +1430,17 @@ subtest 'can_patron_change_permitted_staff_lists() tests' => sub { }, } ); - is( $patron->can_patron_change_permitted_staff_lists(), 1, 'Catalogue and "edit_public_list_contents" patron can change permitted staff lists'); + is( + $patron->can_patron_change_permitted_staff_lists(), 1, + 'Catalogue and "edit_public_list_contents" patron can change permitted staff lists' + ); # make it a superlibrarian - $patron->set({ flags => 1 })->store->discard_changes; - is( $patron->can_patron_change_permitted_staff_lists(), 1, 'Superlibrarian patron can change permitted staff lists'); + $patron->set( { flags => 1 } )->store->discard_changes; + is( + $patron->can_patron_change_permitted_staff_lists(), 1, + 'Superlibrarian patron can change permitted staff lists' + ); $schema->storage->txn_rollback; }; @@ -1605,15 +1614,16 @@ subtest 'safe_to_delete() tests' => sub { $schema->storage->txn_begin; - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); ## Make it the anonymous t::lib::Mocks::mock_preference( 'AnonymousPatron', $patron->id ); ok( !$patron->safe_to_delete, 'Cannot delete, it is the anonymous patron' ); my $message = $patron->safe_to_delete->messages->[0]; - is( $message->type, 'error', 'Type is error' ); + is( $message->type, 'error', 'Type is error' ); is( $message->message, 'is_anonymous_patron', 'Cannot delete, it is the anonymous patron' ); + # cleanup t::lib::Mocks::mock_preference( 'AnonymousPatron', 0 ); @@ -1627,35 +1637,37 @@ subtest 'safe_to_delete() tests' => sub { ok( !$patron->safe_to_delete, 'Cannot delete, has checkouts' ); $message = $patron->safe_to_delete->messages->[0]; - is( $message->type, 'error', 'Type is error' ); + is( $message->type, 'error', 'Type is error' ); is( $message->message, 'has_checkouts', 'Cannot delete, has checkouts' ); + # cleanup $checkout->delete; ## Make it have a guarantee t::lib::Mocks::mock_preference( 'borrowerRelationship', 'parent' ); - $builder->build_object({ class => 'Koha::Patrons' }) - ->add_guarantor({ guarantor_id => $patron->id, relationship => 'parent' }); + $builder->build_object( { class => 'Koha::Patrons' } ) + ->add_guarantor( { guarantor_id => $patron->id, relationship => 'parent' } ); ok( !$patron->safe_to_delete, 'Cannot delete, has guarantees' ); $message = $patron->safe_to_delete->messages->[0]; - is( $message->type, 'error', 'Type is error' ); + is( $message->type, 'error', 'Type is error' ); is( $message->message, 'has_guarantees', 'Cannot delete, has guarantees' ); # cleanup $patron->guarantee_relationships->delete; ## Make it have debt - my $debit = $patron->account->add_debit({ amount => 10, interface => 'intranet', type => 'MANUAL' }); + my $debit = $patron->account->add_debit( { amount => 10, interface => 'intranet', type => 'MANUAL' } ); ok( !$patron->safe_to_delete, 'Cannot delete, has debt' ); $message = $patron->safe_to_delete->messages->[0]; - is( $message->type, 'error', 'Type is error' ); + is( $message->type, 'error', 'Type is error' ); is( $message->message, 'has_debt', 'Cannot delete, has debt' ); + # cleanup my $manager = $builder->build_object( { class => 'Koha::Patrons' } ); t::lib::Mocks::mock_userenv( { borrowernumber => $manager->id } ); - $patron->account->pay({ amount => 10, debits => [ $debit ] }); + $patron->account->pay( { amount => 10, debits => [$debit] } ); ## Make it protected $patron->protected(1); @@ -1692,7 +1704,8 @@ subtest 'article_request_fee() tests' => sub { # Rule that should never be picked, because the patron's category is always picked Koha::CirculationRules->set_rule( - { categorycode => undef, + { + categorycode => undef, branchcode => undef, rule_name => 'article_request_fee', rule_value => 1, @@ -1702,7 +1715,8 @@ subtest 'article_request_fee() tests' => sub { is( $patron->article_request_fee( { library_id => $library_2->id } ), 1, 'library_id used correctly' ); Koha::CirculationRules->set_rule( - { categorycode => $patron->categorycode, + { + categorycode => $patron->categorycode, branchcode => undef, rule_name => 'article_request_fee', rule_value => 2, @@ -1710,7 +1724,8 @@ subtest 'article_request_fee() tests' => sub { ); Koha::CirculationRules->set_rule( - { categorycode => $patron->categorycode, + { + categorycode => $patron->categorycode, branchcode => $library_1->id, rule_name => 'article_request_fee', rule_value => 3, @@ -1746,8 +1761,7 @@ subtest 'add_article_request_fee_if_needed() tests' => sub { my $staff = $builder->build_object( { class => 'Koha::Patrons' } ); my $item = $builder->build_sample_item; - t::lib::Mocks::mock_userenv( - { branchcode => $library_1->id, patron => $staff } ); + t::lib::Mocks::mock_userenv( { branchcode => $library_1->id, patron => $staff } ); my $debit = $patron->add_article_request_fee_if_needed(); is( $debit, undef, 'No fee, no debit line' ); @@ -1755,29 +1769,45 @@ subtest 'add_article_request_fee_if_needed() tests' => sub { # positive value $amount = 1; - $debit = $patron->add_article_request_fee_if_needed({ item_id => $item->id }); + $debit = $patron->add_article_request_fee_if_needed( { item_id => $item->id } ); is( ref($debit), 'Koha::Account::Line', 'Debit object type correct' ); - is( $debit->amount, $amount, - 'amount set to $patron->article_request_fee value' ); - is( $debit->manager_id, $staff->id, - 'manager_id set to userenv session user' ); - is( $debit->branchcode, $library_1->id, - 'branchcode set to userenv session library' ); - is( $debit->debit_type_code, 'ARTICLE_REQUEST', - 'debit_type_code set correctly' ); - is( $debit->itemnumber, $item->id, - 'itemnumber set correctly' ); + is( + $debit->amount, $amount, + 'amount set to $patron->article_request_fee value' + ); + is( + $debit->manager_id, $staff->id, + 'manager_id set to userenv session user' + ); + is( + $debit->branchcode, $library_1->id, + 'branchcode set to userenv session library' + ); + is( + $debit->debit_type_code, 'ARTICLE_REQUEST', + 'debit_type_code set correctly' + ); + is( + $debit->itemnumber, $item->id, + 'itemnumber set correctly' + ); $amount = 100; - $debit = $patron->add_article_request_fee_if_needed({ library_id => $library_2->id }); + $debit = $patron->add_article_request_fee_if_needed( { library_id => $library_2->id } ); is( ref($debit), 'Koha::Account::Line', 'Debit object type correct' ); - is( $debit->amount, $amount, - 'amount set to $patron->article_request_fee value' ); - is( $debit->branchcode, $library_2->id, - 'branchcode set to userenv session library' ); - is( $debit->itemnumber, undef, - 'itemnumber set correctly to undef' ); + is( + $debit->amount, $amount, + 'amount set to $patron->article_request_fee value' + ); + is( + $debit->branchcode, $library_2->id, + 'branchcode set to userenv session library' + ); + is( + $debit->itemnumber, undef, + 'itemnumber set correctly to undef' + ); $schema->storage->txn_rollback; }; @@ -1787,7 +1817,7 @@ subtest 'messages' => sub { $schema->storage->txn_begin; - my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $messages = $patron->messages; is( $messages->count, 0, "No message yet" ); my $message_1 = $builder->build_object( @@ -1804,7 +1834,7 @@ subtest 'messages' => sub { ); $messages = $patron->messages; - is( $messages->count, 2, "There are two messages for this patron" ); + is( $messages->count, 2, "There are two messages for this patron" ); is( $messages->next->message, $message_1->message ); is( $messages->next->message, $message_2->message ); $schema->storage->txn_rollback; @@ -1816,14 +1846,17 @@ subtest 'recalls() tests' => sub { $schema->storage->txn_begin; - my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); - my $biblio1 = $builder->build_object({ class => 'Koha::Biblios' }); - my $item1 = $builder->build_object({ class => 'Koha::Items' }, { value => { biblionumber => $biblio1->biblionumber } }); - my $biblio2 = $builder->build_object({ class => 'Koha::Biblios' }); - my $item2 = $builder->build_object({ class => 'Koha::Items' }, { value => { biblionumber => $biblio2->biblionumber } }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + my $biblio1 = $builder->build_object( { class => 'Koha::Biblios' } ); + my $item1 = + $builder->build_object( { class => 'Koha::Items' }, { value => { biblionumber => $biblio1->biblionumber } } ); + my $biblio2 = $builder->build_object( { class => 'Koha::Biblios' } ); + my $item2 = + $builder->build_object( { class => 'Koha::Items' }, { value => { biblionumber => $biblio2->biblionumber } } ); Koha::Recall->new( - { biblio_id => $biblio1->biblionumber, + { + biblio_id => $biblio1->biblionumber, patron_id => $patron->borrowernumber, item_id => $item1->itemnumber, pickup_library_id => $patron->branchcode, @@ -1832,7 +1865,8 @@ subtest 'recalls() tests' => sub { } )->store; Koha::Recall->new( - { biblio_id => $biblio2->biblionumber, + { + biblio_id => $biblio2->biblionumber, patron_id => $patron->borrowernumber, item_id => $item2->itemnumber, pickup_library_id => $patron->branchcode, @@ -1841,7 +1875,8 @@ subtest 'recalls() tests' => sub { } )->store; Koha::Recall->new( - { biblio_id => $biblio1->biblionumber, + { + biblio_id => $biblio1->biblionumber, patron_id => $patron->borrowernumber, item_id => undef, pickup_library_id => $patron->branchcode, @@ -1850,7 +1885,8 @@ subtest 'recalls() tests' => sub { } )->store; my $recall = Koha::Recall->new( - { biblio_id => $biblio1->biblionumber, + { + biblio_id => $biblio1->biblionumber, patron_id => $patron->borrowernumber, item_id => undef, pickup_library_id => $patron->branchcode, @@ -1860,9 +1896,12 @@ subtest 'recalls() tests' => sub { )->store; $recall->set_cancelled; - is( $patron->recalls->count, 4, "Correctly gets this patron's recalls" ); - is( $patron->recalls->filter_by_current->count, 3, "Correctly gets this patron's active recalls" ); - is( $patron->recalls->filter_by_current->search( { biblio_id => $biblio1->biblionumber } )->count, 2, "Correctly gets this patron's active recalls on a specific biblio" ); + is( $patron->recalls->count, 4, "Correctly gets this patron's recalls" ); + is( $patron->recalls->filter_by_current->count, 3, "Correctly gets this patron's active recalls" ); + is( + $patron->recalls->filter_by_current->search( { biblio_id => $biblio1->biblionumber } )->count, 2, + "Correctly gets this patron's active recalls on a specific biblio" + ); $schema->storage->txn_rollback; }; @@ -1871,15 +1910,15 @@ subtest 'encode_secret and decoded_secret' => sub { plan tests => 5; $schema->storage->txn_begin; - t::lib::Mocks::mock_config('encryption_key', 't0P_secret'); + t::lib::Mocks::mock_config( 'encryption_key', 't0P_secret' ); - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); is( $patron->decoded_secret, undef, 'TestBuilder does not initialize it' ); $patron->secret(q{}); is( $patron->decoded_secret, q{}, 'Empty string case' ); - $patron->encode_secret('encrypt_me'); # Note: lazy testing; should be base32 string normally. - is( length($patron->secret) > 0, 1, 'Secret length' ); + $patron->encode_secret('encrypt_me'); # Note: lazy testing; should be base32 string normally. + is( length( $patron->secret ) > 0, 1, 'Secret length' ); isnt( $patron->secret, 'encrypt_me', 'Encrypted column' ); is( $patron->decoded_secret, 'encrypt_me', 'Decrypted column' ); @@ -1905,39 +1944,55 @@ subtest 'notify_library_of_registration()' => sub { my $patron = $builder->build_object( { class => 'Koha::Patrons', - value => { - branchcode => $library->branchcode - } + value => { branchcode => $library->branchcode } } ); - t::lib::Mocks::mock_preference( 'KohaAdminEmailAddress', 'root@localhost' ); + t::lib::Mocks::mock_preference( 'KohaAdminEmailAddress', 'root@localhost' ); t::lib::Mocks::mock_preference( 'EmailAddressForPatronRegistrations', 'library@localhost' ); # Test when EmailPatronRegistrations equals BranchEmailAddress t::lib::Mocks::mock_preference( 'EmailPatronRegistrations', 'BranchEmailAddress' ); - is( $patron->notify_library_of_registration(C4::Context->preference('EmailPatronRegistrations')), 1, 'OPAC_REG email is queued if EmailPatronRegistration syspref equals BranchEmailAddress'); + is( + $patron->notify_library_of_registration( C4::Context->preference('EmailPatronRegistrations') ), 1, + 'OPAC_REG email is queued if EmailPatronRegistration syspref equals BranchEmailAddress' + ); my $sth = $dbh->prepare("SELECT to_address FROM message_queue where borrowernumber = ?"); $sth->execute( $patron->borrowernumber ); my $to_address = $sth->fetchrow_array; - is( $to_address, 'to@mybranch.com', 'OPAC_REG email queued to go to branchreplyto address when EmailPatronRegistration equals BranchEmailAddress' ); + is( + $to_address, 'to@mybranch.com', + 'OPAC_REG email queued to go to branchreplyto address when EmailPatronRegistration equals BranchEmailAddress' + ); $dbh->do(q|DELETE FROM message_queue|); # Test when EmailPatronRegistrations equals EmailAddressForPatronRegistrations t::lib::Mocks::mock_preference( 'EmailPatronRegistrations', 'EmailAddressForPatronRegistrations' ); - is( $patron->notify_library_of_registration(C4::Context->preference('EmailPatronRegistrations')), 1, 'OPAC_REG email is queued if EmailPatronRegistration syspref equals EmailAddressForPatronRegistrations'); + is( + $patron->notify_library_of_registration( C4::Context->preference('EmailPatronRegistrations') ), 1, + 'OPAC_REG email is queued if EmailPatronRegistration syspref equals EmailAddressForPatronRegistrations' + ); $sth->execute( $patron->borrowernumber ); $to_address = $sth->fetchrow_array; - is( $to_address, 'library@localhost', 'OPAC_REG email queued to go to EmailAddressForPatronRegistrations syspref when EmailPatronRegistration equals EmailAddressForPatronRegistrations' ); + is( + $to_address, 'library@localhost', + 'OPAC_REG email queued to go to EmailAddressForPatronRegistrations syspref when EmailPatronRegistration equals EmailAddressForPatronRegistrations' + ); $dbh->do(q|DELETE FROM message_queue|); # Test when EmailPatronRegistrations equals KohaAdminEmailAddress t::lib::Mocks::mock_preference( 'EmailPatronRegistrations', 'KohaAdminEmailAddress' ); - t::lib::Mocks::mock_preference( 'ReplyToDefault', 'root@localhost' ); # FIXME Remove localhost - is( $patron->notify_library_of_registration(C4::Context->preference('EmailPatronRegistrations')), 1, 'OPAC_REG email is queued if EmailPatronRegistration syspref equals KohaAdminEmailAddress'); + t::lib::Mocks::mock_preference( 'ReplyToDefault', 'root@localhost' ); # FIXME Remove localhost + is( + $patron->notify_library_of_registration( C4::Context->preference('EmailPatronRegistrations') ), 1, + 'OPAC_REG email is queued if EmailPatronRegistration syspref equals KohaAdminEmailAddress' + ); $sth->execute( $patron->borrowernumber ); $to_address = $sth->fetchrow_array; - is( $to_address, 'root@localhost', 'OPAC_REG email queued to go to KohaAdminEmailAddress syspref when EmailPatronRegistration equals KohaAdminEmailAddress' ); + is( + $to_address, 'root@localhost', + 'OPAC_REG email queued to go to KohaAdminEmailAddress syspref when EmailPatronRegistration equals KohaAdminEmailAddress' + ); $dbh->do(q|DELETE FROM message_queue|); $schema->storage->txn_rollback; @@ -1993,10 +2048,13 @@ subtest 'first_valid_email_address' => sub { plan tests => 1; $schema->storage->txn_begin; - my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { emailpro => ''}}); + my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { emailpro => '' } } ); t::lib::Mocks::mock_preference( 'EmailFieldPrecedence', 'emailpro|email' ); - is ($patron->first_valid_email_address, $patron->email, "Koha::Patron->first_valid_email_address returns correct value when EmailFieldPrecedence is 'emailpro|email' and emailpro is empty"); + is( + $patron->first_valid_email_address, $patron->email, + "Koha::Patron->first_valid_email_address returns correct value when EmailFieldPrecedence is 'emailpro|email' and emailpro is empty" + ); $patron->delete; $schema->storage->txn_rollback; @@ -2008,13 +2066,14 @@ subtest 'get_savings tests' => sub { $schema->storage->txn_begin; - my $library = $builder->build_object({ class => 'Koha::Libraries' }); - my $patron = $builder->build_object({ class => 'Koha::Patrons' }, { value => { branchcode => $library->branchcode } }); + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); + my $patron = + $builder->build_object( { class => 'Koha::Patrons' }, { value => { branchcode => $library->branchcode } } ); - t::lib::Mocks::mock_userenv({ patron => $patron, branchcode => $library->branchcode }); + t::lib::Mocks::mock_userenv( { patron => $patron, branchcode => $library->branchcode } ); my $biblio = $builder->build_sample_biblio; - my $item1 = $builder->build_sample_item( + my $item1 = $builder->build_sample_item( { biblionumber => $biblio->biblionumber, library => $library->branchcode, @@ -2032,7 +2091,8 @@ subtest 'get_savings tests' => sub { is( $patron->get_savings, 0, 'No checkouts, no savings' ); # Add an old checkout with deleted itemnumber - $builder->build_object({ class => 'Koha::Old::Checkouts', value => { itemnumber => undef, borrowernumber => $patron->id } }); + $builder->build_object( + { class => 'Koha::Old::Checkouts', value => { itemnumber => undef, borrowernumber => $patron->id } } ); is( $patron->get_savings, 0, 'No checkouts with itemnumber, no savings' ); @@ -2040,12 +2100,18 @@ subtest 'get_savings tests' => sub { AddIssue( $patron, $item2->barcode ); my $savings = $patron->get_savings; - is( $savings + 0, $item1->replacementprice + $item2->replacementprice, "Savings correctly calculated from current issues" ); + is( + $savings + 0, $item1->replacementprice + $item2->replacementprice, + "Savings correctly calculated from current issues" + ); AddReturn( $item2->barcode, $item2->homebranch ); $savings = $patron->get_savings; - is( $savings + 0, $item1->replacementprice + $item2->replacementprice, "Savings correctly calculated from current and old issues" ); + is( + $savings + 0, $item1->replacementprice + $item2->replacementprice, + "Savings correctly calculated from current and old issues" + ); $schema->storage->txn_rollback; }; @@ -2056,32 +2122,34 @@ subtest 'update privacy tests' => sub { plan tests => 5; $schema->storage->txn_begin; - my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { privacy => 1 } }); + my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { privacy => 1 } } ); - my $old_checkout = $builder->build_object({ class => 'Koha::Old::Checkouts', value => { borrowernumber => $patron->id } }); + my $old_checkout = + $builder->build_object( { class => 'Koha::Old::Checkouts', value => { borrowernumber => $patron->id } } ); t::lib::Mocks::mock_preference( 'AnonymousPatron', '0' ); - $patron->privacy(2); #set to never + $patron->privacy(2); #set to never - throws_ok{ $patron->store } 'Koha::Exceptions::Patron::FailedAnonymizing', 'We throw an exception when anonymizing fails'; + throws_ok { $patron->store } 'Koha::Exceptions::Patron::FailedAnonymizing', + 'We throw an exception when anonymizing fails'; - $old_checkout->discard_changes; #refresh from db + $old_checkout->discard_changes; #refresh from db $patron->discard_changes; - is( $old_checkout->borrowernumber, $patron->id, "When anonymizing fails, we don't clear the checkouts"); - is( $patron->privacy(), 1, "When anonymizing fails, we don't chaneg the privacy"); + is( $old_checkout->borrowernumber, $patron->id, "When anonymizing fails, we don't clear the checkouts" ); + is( $patron->privacy(), 1, "When anonymizing fails, we don't chaneg the privacy" ); - my $anon_patron = $builder->build_object({ class => 'Koha::Patrons'}); + my $anon_patron = $builder->build_object( { class => 'Koha::Patrons' } ); t::lib::Mocks::mock_preference( 'AnonymousPatron', $anon_patron->id ); - $patron->privacy(2)->store(); #set to never + $patron->privacy(2)->store(); #set to never - $old_checkout->discard_changes; #refresh from db + $old_checkout->discard_changes; #refresh from db $patron->discard_changes; - is( $old_checkout->borrowernumber, $anon_patron->id, "Checkout is successfully anonymized"); - is( $patron->privacy(), 2, "Patron privacy is successfully updated"); + is( $old_checkout->borrowernumber, $anon_patron->id, "Checkout is successfully anonymized" ); + is( $patron->privacy(), 2, "Patron privacy is successfully updated" ); $schema->storage->txn_rollback; }; @@ -2101,7 +2169,7 @@ subtest 'alert_subscriptions tests' => sub { my @subscriptions = $patron->alert_subscriptions->as_list; - is( @subscriptions, 2, "Number of patron's subscribed alerts successfully fetched" ); + is( @subscriptions, 2, "Number of patron's subscribed alerts successfully fetched" ); is( $subscriptions[0]->subscriptionid, $subscription1->subscriptionid, "First subscribed alert is correct" ); is( $subscriptions[1]->subscriptionid, $subscription2->subscriptionid, "Second subscribed alert is correct" ); @@ -2176,7 +2244,10 @@ subtest 'update_lastseen tests' => sub { $patron->update_lastseen('login'); $patron->_result()->discard_changes(); - isnt( $patron->lastseen, undef, 'Patron should have last seen set when TrackLastPatronActivityTriggers contains values' ); + isnt( + $patron->lastseen, undef, + 'Patron should have last seen set when TrackLastPatronActivityTriggers contains values' + ); my $last_seen = $patron->lastseen; Time::Fake->offset( $now->epoch + 5 ); @@ -2315,7 +2386,10 @@ subtest 'update_lastseen tests' => sub { $cache->clear_from_cache($cache_key); $patron->update_lastseen('login'); $patron->_result()->discard_changes(); - is( $patron->lastseen, undef, 'Patron should still have last seen unchanged when TrackLastPatronActivityTriggers is unset' ); + is( + $patron->lastseen, undef, + 'Patron should still have last seen unchanged when TrackLastPatronActivityTriggers is unset' + ); Time::Fake->reset; $schema->storage->txn_rollback; diff --git a/t/db_dependent/Koha/Patron/Attribute.t b/t/db_dependent/Koha/Patron/Attribute.t index e9e9f9c7fb..e233a39050 100755 --- a/t/db_dependent/Koha/Patron/Attribute.t +++ b/t/db_dependent/Koha/Patron/Attribute.t @@ -80,7 +80,7 @@ subtest 'store() tests' => sub { $schema->storage->txn_begin; - my $patron = $builder->build( { source => 'Borrower' } )->{borrowernumber}; + my $patron = $builder->build( { source => 'Borrower' } )->{borrowernumber}; my $attribute_type_1 = $builder->build( { source => 'BorrowerAttributeType', @@ -88,23 +88,25 @@ subtest 'store() tests' => sub { } ); Koha::Patron::Attribute->new( - { borrowernumber => $patron, + { + borrowernumber => $patron, code => $attribute_type_1->{code}, attribute => 'Foo' } )->store; Koha::Patron::Attribute->new( - { borrowernumber => $patron, + { + borrowernumber => $patron, code => $attribute_type_1->{code}, attribute => 'Bar' } )->store; - my $attr_count - = Koha::Patron::Attributes->search( - { borrowernumber => $patron, code => $attribute_type_1->{code} } ) - ->count; - is( $attr_count, 2, - '2 repeatable attributes stored and retrieved correcctly' ); + my $attr_count = + Koha::Patron::Attributes->search( { borrowernumber => $patron, code => $attribute_type_1->{code} } )->count; + is( + $attr_count, 2, + '2 repeatable attributes stored and retrieved correcctly' + ); my $attribute_type_2 = $builder->build( { @@ -114,14 +116,16 @@ subtest 'store() tests' => sub { ); Koha::Patron::Attribute->new( - { borrowernumber => $patron, + { + borrowernumber => $patron, code => $attribute_type_2->{code}, attribute => 'Foo' } )->store; throws_ok { Koha::Patron::Attribute->new( - { borrowernumber => $patron, + { + borrowernumber => $patron, code => $attribute_type_2->{code}, attribute => 'Bar' } @@ -132,17 +136,17 @@ subtest 'store() tests' => sub { is( "$@", - "Tried to add more than one non-repeatable attributes. type=" - . $attribute_type_2->{code} - . " value=Bar", + "Tried to add more than one non-repeatable attributes. type=" . $attribute_type_2->{code} . " value=Bar", 'Exception stringified correctly, attribute passed correctly' ); - my $attributes = Koha::Patron::Attributes->search( - { borrowernumber => $patron, code => $attribute_type_2->{code} } ); + my $attributes = + Koha::Patron::Attributes->search( { borrowernumber => $patron, code => $attribute_type_2->{code} } ); is( $attributes->count, 1, '1 non-repeatable attribute stored' ); - is( $attributes->next->attribute, - 'Foo', 'Non-repeatable attribute remains unchanged' ); + is( + $attributes->next->attribute, + 'Foo', 'Non-repeatable attribute remains unchanged' + ); $schema->storage->txn_rollback; }; @@ -212,23 +216,24 @@ subtest 'store() tests' => sub { } ); Koha::Patron::Attribute->new( - { borrowernumber => $patron_1, + { + borrowernumber => $patron_1, code => $attribute_type_1->{code}, attribute => 'Foo' } )->store; Koha::Patron::Attribute->new( - { borrowernumber => $patron_2, + { + borrowernumber => $patron_2, code => $attribute_type_1->{code}, attribute => 'Bar' } )->store; - my $attr_count - = Koha::Patron::Attributes->search( - { code => $attribute_type_1->{code} } ) - ->count; - is( $attr_count, 2, - '2 non-unique attributes stored and retrieved correcctly' ); + my $attr_count = Koha::Patron::Attributes->search( { code => $attribute_type_1->{code} } )->count; + is( + $attr_count, 2, + '2 non-unique attributes stored and retrieved correcctly' + ); my $attribute_type_2 = $builder->build( { @@ -238,14 +243,16 @@ subtest 'store() tests' => sub { ); Koha::Patron::Attribute->new( - { borrowernumber => $patron_1, + { + borrowernumber => $patron_1, code => $attribute_type_2->{code}, attribute => 'Foo' } )->store; throws_ok { Koha::Patron::Attribute->new( - { borrowernumber => $patron_2, + { + borrowernumber => $patron_2, code => $attribute_type_2->{code}, attribute => 'Foo' } @@ -256,17 +263,17 @@ subtest 'store() tests' => sub { is( "$@", - "Your action breaks a unique constraint on the attribute. type=" - . $attribute_type_2->{code} - . " value=Foo", + "Your action breaks a unique constraint on the attribute. type=" . $attribute_type_2->{code} . " value=Foo", 'Exception stringified correctly, attribute passed correctly' ); - my $attributes = Koha::Patron::Attributes->search( - { borrowernumber => $patron_1, code => $attribute_type_2->{code} } ); + my $attributes = + Koha::Patron::Attributes->search( { borrowernumber => $patron_1, code => $attribute_type_2->{code} } ); is( $attributes->count, 1, '1 unique attribute stored' ); - is( $attributes->next->attribute, - 'Foo', 'unique attribute remains unchanged' ); + is( + $attributes->next->attribute, + 'Foo', 'unique attribute remains unchanged' + ); $schema->storage->txn_rollback; }; @@ -277,7 +284,7 @@ subtest 'store() tests' => sub { $schema->storage->txn_begin; - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $attribute_type = $builder->build_object( { class => 'Koha::Patron::Attribute::Types', @@ -292,19 +299,20 @@ subtest 'store() tests' => sub { my $code = $attribute_type->code; $attribute_type->delete; - throws_ok - { Koha::Patron::Attribute->new( + throws_ok { + Koha::Patron::Attribute->new( { borrowernumber => $patron->borrowernumber, code => $code, attribute => 'Who knows' - })->store; - } - 'Koha::Exceptions::Patron::Attribute::InvalidType', + } + )->store; + } + 'Koha::Exceptions::Patron::Attribute::InvalidType', 'Exception thrown on invalid attribute code'; - is( $@->type, $code, 'type exception parameter passed' ); + is( $@->type, $code, 'type exception parameter passed' ); $schema->storage->txn_rollback; }; @@ -315,7 +323,7 @@ subtest 'store() tests' => sub { $schema->storage->txn_begin; - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $non_repeatable_type = $builder->build_object( { class => 'Koha::Patron::Attribute::Types', @@ -337,9 +345,7 @@ subtest 'store() tests' => sub { } ); - $non_repeatable_attr->set({ attribute => 'HEY' }) - ->store - ->discard_changes; + $non_repeatable_attr->set( { attribute => 'HEY' } )->store->discard_changes; is( $non_repeatable_attr->attribute, 'HEY', 'Value stored correctly' ); @@ -353,11 +359,11 @@ subtest 'type() tests' => sub { $schema->storage->txn_begin; - my $patron - = $builder->build( { source => 'Borrower' } )->{borrowernumber}; + my $patron = $builder->build( { source => 'Borrower' } )->{borrowernumber}; my $attr_type = $builder->build( { source => 'BorrowerAttributeType' } ); my $attribute = Koha::Patron::Attribute->new( - { borrowernumber => $patron, + { + borrowernumber => $patron, code => $attr_type->{code}, attribute => $patron } @@ -365,21 +371,26 @@ subtest 'type() tests' => sub { my $attribute_type = $attribute->type; - is( ref($attribute_type), + is( + ref($attribute_type), 'Koha::Patron::Attribute::Type', '->type returns a Koha::Patron::Attribute::Type object' ); - is( $attribute_type->code, + is( + $attribute_type->code, $attr_type->{code}, - '->type returns the right Koha::Patron::Attribute::Type object' ); + '->type returns the right Koha::Patron::Attribute::Type object' + ); - is( $attribute_type->opac_editable, + is( + $attribute_type->opac_editable, $attr_type->{opac_editable}, '->type returns the right Koha::Patron::Attribute::Type object' ); - is( $attribute_type->opac_display, + is( + $attribute_type->opac_display, $attr_type->{opac_display}, '->type returns the right Koha::Patron::Attribute::Type object' ); @@ -393,7 +404,7 @@ subtest 'merge_and_replace_with' => sub { my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; - my $patron = $builder->build_object({class=> 'Koha::Patrons'}); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $unique_attribute_type = $builder->build_object( { @@ -436,15 +447,15 @@ subtest 'merge_and_replace_with' => sub { my $attributes = [ { attribute => 'my unique attribute 1', - code => $unique_attribute_type->code(), + code => $unique_attribute_type->code(), }, { attribute => 'my repeatable attribute 1', - code => $repeatable_attribute_type->code(), + code => $repeatable_attribute_type->code(), }, { attribute => 'my normal attribute 1', - code => $normal_attribute_type->code(), + code => $normal_attribute_type->code(), } ]; $patron->extended_attributes($attributes); @@ -452,19 +463,19 @@ subtest 'merge_and_replace_with' => sub { my $new_attributes = [ { attribute => 'my repeatable attribute 2', - code => $repeatable_attribute_type->code(), + code => $repeatable_attribute_type->code(), }, { attribute => 'my repeatable attribute 3', - code => $repeatable_attribute_type->code(), + code => $repeatable_attribute_type->code(), }, { attribute => 'my normal attribute 2', - code => $normal_attribute_type->code(), + code => $normal_attribute_type->code(), }, { attribute => 'my unique attribute 2', - code => $unique_attribute_type->code(), + code => $unique_attribute_type->code(), } ]; @@ -472,39 +483,37 @@ subtest 'merge_and_replace_with' => sub { my $expected = [ { - attribute => 'my normal attribute 2', # Attribute 1 has been replaced by attribute 2 - code => $normal_attribute_type->code(), + attribute => 'my normal attribute 2', # Attribute 1 has been replaced by attribute 2 + code => $normal_attribute_type->code(), }, { - attribute => 'my unique attribute 2', # Attribute 1 has been replaced by attribute 2 - code => $unique_attribute_type->code(), + attribute => 'my unique attribute 2', # Attribute 1 has been replaced by attribute 2 + code => $unique_attribute_type->code(), }, { attribute => 'my repeatable attribute 1', - code => $repeatable_attribute_type->code(), + code => $repeatable_attribute_type->code(), }, { attribute => 'my repeatable attribute 2', - code => $repeatable_attribute_type->code(), + code => $repeatable_attribute_type->code(), }, { attribute => 'my repeatable attribute 3', - code => $repeatable_attribute_type->code(), + code => $repeatable_attribute_type->code(), }, ]; $expected = [ sort { $a->{code} cmp $b->{code} || $a->{attribute} cmp $b->{attribute} } @$expected ]; - is_deeply($new_extended_attributes, $expected); + is_deeply( $new_extended_attributes, $expected ); - - throws_ok - { - $patron->extended_attributes->merge_and_replace_with( - [ - { code => $non_existent_attribute_type_code, attribute => 'foobar' }, - ] - ); - } - 'Koha::Exceptions::Patron::Attribute::InvalidType', + throws_ok { + $patron->extended_attributes->merge_and_replace_with( + [ + { code => $non_existent_attribute_type_code, attribute => 'foobar' }, + ] + ); + } + 'Koha::Exceptions::Patron::Attribute::InvalidType', 'Exception thrown on invalid attribute type'; $schema->storage->txn_rollback; diff --git a/t/db_dependent/Koha/Patron/Attribute/Types.t b/t/db_dependent/Koha/Patron/Attribute/Types.t index c7bb0d2fbc..222251a6de 100755 --- a/t/db_dependent/Koha/Patron/Attribute/Types.t +++ b/t/db_dependent/Koha/Patron/Attribute/Types.t @@ -43,28 +43,33 @@ subtest 'new() tests' => sub { Koha::Patron::Attribute::Types->search()->delete(); my $attribute_type = Koha::Patron::Attribute::Type->new( - { code => 'code', + { + code => 'code', description => 'description', repeatable => 0 } )->store(); - is( Koha::Patron::Attribute::Types->search()->count, - 1, 'Only one object created' ); + is( + Koha::Patron::Attribute::Types->search()->count, + 1, 'Only one object created' + ); - my $cateogory_code - = $builder->build( { source => 'Category' } )->{categorycode}; + my $cateogory_code = $builder->build( { source => 'Category' } )->{categorycode}; my $attribute_type_with_category = Koha::Patron::Attribute::Type->new( - { code => 'code_2', + { + code => 'code_2', description => 'description', category_code => $cateogory_code, repeatable => 0 } )->store(); - is( Koha::Patron::Attribute::Types->search()->count, - 2, 'Two objects created' ); + is( + Koha::Patron::Attribute::Types->search()->count, + 2, 'Two objects created' + ); $schema->storage->txn_rollback; }; @@ -155,7 +160,7 @@ subtest 'store' => sub { 'Koha::Exceptions::Patron::Attribute::Type::CannotChangeProperty', ""; $attribute_112->delete; - ok($attr_type_1->set({ unique_id => 1, repeatable => 0 })->store); + ok( $attr_type_1->set( { unique_id => 1, repeatable => 0 } )->store ); throws_ok { $attr_type_2->unique_id(1)->store; @@ -163,7 +168,7 @@ subtest 'store' => sub { 'Koha::Exceptions::Patron::Attribute::Type::CannotChangeProperty', ""; $attribute_321->attribute(43)->store; - ok($attr_type_2->set({ unique_id => 1, repeatable => 0 })->store); + ok( $attr_type_2->set( { unique_id => 1, repeatable => 0 } )->store ); $schema->storage->txn_rollback; @@ -179,7 +184,8 @@ subtest 'library_limits() tests' => sub { Koha::Patron::Attribute::Types->search()->delete(); my $attribute_type = Koha::Patron::Attribute::Type->new( - { code => 'code', + { + code => 'code', description => 'description', repeatable => 0 } @@ -188,8 +194,10 @@ subtest 'library_limits() tests' => sub { my $library = $builder->build( { source => 'Branch' } )->{branchcode}; my $library_limits = $attribute_type->library_limits(); - is( $library_limits, undef, - 'No branch limitations defined for attribute type' ); + is( + $library_limits, undef, + 'No branch limitations defined for attribute type' + ); my $print_error = $dbh->{PrintError}; $dbh->{PrintError} = 0; @@ -200,8 +208,10 @@ subtest 'library_limits() tests' => sub { 'Koha::Exceptions::CannotAddLibraryLimit', 'Exception thrown on single invalid branchcode'; $library_limits = $attribute_type->library_limits(); - is( $library_limits, undef, - 'No branch limitations defined for attribute type' ); + is( + $library_limits, undef, + 'No branch limitations defined for attribute type' + ); throws_ok { $attribute_type->library_limits( [ 'fake', $library ] ); @@ -210,8 +220,10 @@ subtest 'library_limits() tests' => sub { 'Exception thrown on invalid branchcode present'; $library_limits = $attribute_type->library_limits(); - is( $library_limits, undef, - 'No branch limitations defined for attribute type' ); + is( + $library_limits, undef, + 'No branch limitations defined for attribute type' + ); $dbh->{PrintError} = $print_error; @@ -219,14 +231,16 @@ subtest 'library_limits() tests' => sub { $library_limits = $attribute_type->library_limits; is( $library_limits->count, 1, 'Library limits correctly set (count)' ); my $limit_library = $library_limits->next; - ok( $limit_library->isa('Koha::Library'), + ok( + $limit_library->isa('Koha::Library'), 'Library limits correctly set (type)' ); - is( $limit_library->branchcode, - $library, 'Library limits correctly set (value)' ); + is( + $limit_library->branchcode, + $library, 'Library limits correctly set (value)' + ); - my $another_library - = $builder->build( { source => 'Branch' } )->{branchcode}; + my $another_library = $builder->build( { source => 'Branch' } )->{branchcode}; my @branchcodes_list = ( $library, $another_library ); $attribute_type->library_limits( \@branchcodes_list ); @@ -234,10 +248,12 @@ subtest 'library_limits() tests' => sub { is( $library_limits->count, 2, 'Library limits correctly set (count)' ); while ( $limit_library = $library_limits->next ) { - ok( $limit_library->isa('Koha::Library'), + ok( + $limit_library->isa('Koha::Library'), 'Library limits correctly set (type)' ); - ok( eval { + ok( + eval { grep { $limit_library->branchcode eq $_ } @branchcodes_list; }, 'Library limits correctly set (values)' @@ -257,7 +273,8 @@ subtest 'add_library_limit() tests' => sub { Koha::Patron::Attribute::Types->search()->delete(); my $attribute_type = Koha::Patron::Attribute::Type->new( - { code => 'code', + { + code => 'code', description => 'description', repeatable => 0 } @@ -268,11 +285,12 @@ subtest 'add_library_limit() tests' => sub { my $library = $builder->build( { source => 'Branch' } )->{branchcode}; $attribute_type->add_library_limit($library); - my $rs = Koha::Database->schema->resultset('BorrowerAttributeTypesBranch') - ->search( { bat_code => 'code' } ); + my $rs = Koha::Database->schema->resultset('BorrowerAttributeTypesBranch')->search( { bat_code => 'code' } ); is( $rs->count, 1, 'Library limit successfully added (count)' ); - is( $rs->next->b_branchcode->branchcode, - $library, 'Library limit successfully added (value)' ); + is( + $rs->next->b_branchcode->branchcode, + $library, 'Library limit successfully added (value)' + ); my $print_error = $dbh->{PrintError}; $dbh->{PrintError} = 0; @@ -298,7 +316,8 @@ subtest 'del_library_limit() tests' => sub { Koha::Patron::Attribute::Types->search()->delete(); my $attribute_type = Koha::Patron::Attribute::Type->new( - { code => 'code', + { + code => 'code', description => 'description', repeatable => 0 } @@ -311,8 +330,10 @@ subtest 'del_library_limit() tests' => sub { my $library = $builder->build( { source => 'Branch' } )->{branchcode}; $attribute_type->add_library_limit($library); - is( $attribute_type->del_library_limit($library), - 1, 'Library limit successfully deleted' ); + is( + $attribute_type->del_library_limit($library), + 1, 'Library limit successfully deleted' + ); my $print_error = $dbh->{PrintError}; $dbh->{PrintError} = 0; @@ -344,7 +365,8 @@ subtest 'replace_library_limits() tests' => sub { Koha::Patron::Attribute::Types->search()->delete(); my $attribute_type = Koha::Patron::Attribute::Type->new( - { code => 'code', + { + code => 'code', description => 'description', repeatable => 0 } @@ -354,29 +376,34 @@ subtest 'replace_library_limits() tests' => sub { my $library_limits = $attribute_type->library_limits; is( $library_limits, undef, 'Replacing with empty array yields no library limits' ); - my $library_1 = $builder->build({ source => 'Branch' })->{branchcode}; - my $library_2 = $builder->build({ source => 'Branch' })->{branchcode}; - my $library_3 = $builder->build({ source => 'Branch' })->{branchcode}; + my $library_1 = $builder->build( { source => 'Branch' } )->{branchcode}; + my $library_2 = $builder->build( { source => 'Branch' } )->{branchcode}; + my $library_3 = $builder->build( { source => 'Branch' } )->{branchcode}; $attribute_type->replace_library_limits( [$library_1] ); $library_limits = $attribute_type->library_limits; - is( $library_limits->count, 1, - 'Successfully adds a single library limit' ); + is( + $library_limits->count, 1, + 'Successfully adds a single library limit' + ); my $library_limit = $library_limits->next; - is( $library_limit->branchcode, - $library_1, 'Library limit correctly set' ); + is( + $library_limit->branchcode, + $library_1, 'Library limit correctly set' + ); my @branchcodes_list = ( $library_1, $library_2, $library_3 ); - $attribute_type->replace_library_limits( - [ $library_1, $library_2, $library_3 ] ); + $attribute_type->replace_library_limits( [ $library_1, $library_2, $library_3 ] ); $library_limits = $attribute_type->library_limits; is( $library_limits->count, 3, 'Successfully adds two library limit' ); while ( my $limit_library = $library_limits->next ) { - ok( $limit_library->isa('Koha::Library'), + ok( + $limit_library->isa('Koha::Library'), 'Library limits correctly set (type)' ); - ok( eval { + ok( + eval { grep { $limit_library->branchcode eq $_ } @branchcodes_list; }, 'Library limits correctly set (values)' @@ -395,10 +422,14 @@ subtest 'search_with_library_limits() tests' => sub { # Cleanup before running the tests Koha::Patron::Attribute::Types->search()->delete(); - my $object_code_1 = $builder->build_object({ class => 'Koha::Patron::Attribute::Types', value => { code => 'code_1' } }); - my $object_code_2 = $builder->build_object({ class => 'Koha::Patron::Attribute::Types', value => { code => 'code_2' } }); - my $object_code_3 = $builder->build_object({ class => 'Koha::Patron::Attribute::Types', value => { code => 'code_3' } }); - my $object_code_4 = $builder->build_object({ class => 'Koha::Patron::Attribute::Types', value => { code => 'code_4' } }); + my $object_code_1 = + $builder->build_object( { class => 'Koha::Patron::Attribute::Types', value => { code => 'code_1' } } ); + my $object_code_2 = + $builder->build_object( { class => 'Koha::Patron::Attribute::Types', value => { code => 'code_2' } } ); + my $object_code_3 = + $builder->build_object( { class => 'Koha::Patron::Attribute::Types', value => { code => 'code_3' } } ); + my $object_code_4 = + $builder->build_object( { class => 'Koha::Patron::Attribute::Types', value => { code => 'code_4' } } ); is( Koha::Patron::Attribute::Types->search()->count, 4, 'Three objects created' ); @@ -421,7 +452,7 @@ subtest 'search_with_library_limits() tests' => sub { is( $results->count, 4, 'All attribute types are available with no library pssed' ); - t::lib::Mocks::mock_userenv({ branchcode => $branch_2 }); + t::lib::Mocks::mock_userenv( { branchcode => $branch_2 } ); $results = Koha::Patron::Attribute::Types->search_with_library_limits( {}, { order_by => 'code' }, undef ); diff --git a/t/db_dependent/Koha/Patron/Categories.t b/t/db_dependent/Koha/Patron/Categories.t index 4bee746332..24ba91545b 100755 --- a/t/db_dependent/Koha/Patron/Categories.t +++ b/t/db_dependent/Koha/Patron/Categories.t @@ -33,48 +33,73 @@ use t::lib::Mocks; my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; -my $builder = t::lib::TestBuilder->new; -my $library_1 = $builder->build_object({ class => 'Koha::Libraries', }); -my $library_2 = $builder->build_object({ class => 'Koha::Libraries', }); +my $builder = t::lib::TestBuilder->new; +my $library_1 = $builder->build_object( { class => 'Koha::Libraries', } ); +my $library_2 = $builder->build_object( { class => 'Koha::Libraries', } ); my $nb_of_categories = Koha::Patron::Categories->search->count; -my $new_category_1 = Koha::Patron::Category->new({ - categorycode => 'mycatcodeX', - category_type => 'A', - description => 'mycatdescX', -})->store; +my $new_category_1 = Koha::Patron::Category->new( + { + categorycode => 'mycatcodeX', + category_type => 'A', + description => 'mycatdescX', + } +)->store; $new_category_1->replace_library_limits( [ $library_1->branchcode, $library_2->branchcode ] ); -my $new_category_2 = Koha::Patron::Category->new({ - categorycode => 'mycatcodeY', - category_type => 'S', - description => 'mycatdescY', - checkprevcheckout => undef, -})->store; +my $new_category_2 = Koha::Patron::Category->new( + { + categorycode => 'mycatcodeY', + category_type => 'S', + description => 'mycatdescY', + checkprevcheckout => undef, + } +)->store; is( Koha::Patron::Categories->search->count, $nb_of_categories + 2, 'The 2 patron categories should have been added' ); my $retrieved_category_1 = Koha::Patron::Categories->find( $new_category_1->categorycode ); -is( $retrieved_category_1->categorycode, $new_category_1->categorycode, 'Find a patron category by categorycode should return the correct category' ); -is_deeply( [ sort $retrieved_category_1->library_limits->get_column('branchcode') ], [ sort $library_1->branchcode, $library_2->branchcode ], 'The branch limitation should have been stored and retrieved' ); +is( + $retrieved_category_1->categorycode, $new_category_1->categorycode, + 'Find a patron category by categorycode should return the correct category' +); +is_deeply( + [ sort $retrieved_category_1->library_limits->get_column('branchcode') ], + [ sort $library_1->branchcode, $library_2->branchcode ], + 'The branch limitation should have been stored and retrieved' +); is_deeply( $retrieved_category_1->default_messaging, [], 'By default there is not messaging option' ); my $retrieved_category_2 = Koha::Patron::Categories->find( $new_category_2->categorycode ); -is( $retrieved_category_1->checkprevcheckout, 'inherit', 'Koha::Patron::Category->store should default checkprevcheckout to inherit' ); -is( $retrieved_category_2->checkprevcheckout, 'inherit', 'Koha::Patron::Category->store should default checkprevcheckout to inherit' ); +is( + $retrieved_category_1->checkprevcheckout, 'inherit', + 'Koha::Patron::Category->store should default checkprevcheckout to inherit' +); +is( + $retrieved_category_2->checkprevcheckout, 'inherit', + 'Koha::Patron::Category->store should default checkprevcheckout to inherit' +); subtest 'get_expiry_date' => sub { plan tests => 7; my $next_month = dt_from_string->add( months => 1 ); - my $next_year = dt_from_string->add( months => 12 ); - my $yesterday = dt_from_string->add( days => -1 ); - my $category = Koha::Patron::Category->new({ - categorycode => 'mycat', - category_type => 'A', - description => 'mycatdesc', - enrolmentperiod => undef, - enrolmentperioddate => $next_month, - })->store; - is( $category->get_expiry_date, $next_month, 'Without enrolmentperiod and parameter, ->get_expiry_date should return enrolmentperioddate' ); - is( $category->get_expiry_date( $next_year ), $next_month, 'Without enrolmentperiod, ->get_expiry_date should return enrolmentperiodadate even if a parameter is given' ); + my $next_year = dt_from_string->add( months => 12 ); + my $yesterday = dt_from_string->add( days => -1 ); + my $category = Koha::Patron::Category->new( + { + categorycode => 'mycat', + category_type => 'A', + description => 'mycatdesc', + enrolmentperiod => undef, + enrolmentperioddate => $next_month, + } + )->store; + is( + $category->get_expiry_date, $next_month, + 'Without enrolmentperiod and parameter, ->get_expiry_date should return enrolmentperioddate' + ); + is( + $category->get_expiry_date($next_year), $next_month, + 'Without enrolmentperiod, ->get_expiry_date should return enrolmentperiodadate even if a parameter is given' + ); my $dt = dt_from_string; my $original_dt = $dt->clone; @@ -84,9 +109,15 @@ subtest 'get_expiry_date' => sub { 'Without enrolment period, DateTime object passed as a parameter should not be modified when ->get_expiry_date is called' ); - $category->enrolmentperiod( 12 )->store; - is( t::lib::Dates::compare($category->get_expiry_date, $next_year), 0, 'With enrolmentperiod defined and no parameter, ->get_expiry_date should return today + enrolmentperiod' ); - is( t::lib::Dates::compare($category->get_expiry_date( $yesterday ), $next_year->clone->add( days => -1 )), 0, 'With enrolmentperiod defined and a date given in parameter, ->get_expiry_date should take this date + enrolmentperiod' ); + $category->enrolmentperiod(12)->store; + is( + t::lib::Dates::compare( $category->get_expiry_date, $next_year ), 0, + 'With enrolmentperiod defined and no parameter, ->get_expiry_date should return today + enrolmentperiod' + ); + is( + t::lib::Dates::compare( $category->get_expiry_date($yesterday), $next_year->clone->add( days => -1 ) ), 0, + 'With enrolmentperiod defined and a date given in parameter, ->get_expiry_date should take this date + enrolmentperiod' + ); $dt = dt_from_string; $original_dt = $dt->clone; @@ -97,7 +128,13 @@ subtest 'get_expiry_date' => sub { ); my $hardcoded_date = '2000-01-31'; - is( t::lib::Dates::compare($category->get_expiry_date( $hardcoded_date ), dt_from_string( $hardcoded_date )->add( months => 12 )), 0, 'get_expiry_date accepts strings as well' ); + is( + t::lib::Dates::compare( + $category->get_expiry_date($hardcoded_date), dt_from_string($hardcoded_date)->add( months => 12 ) + ), + 0, + 'get_expiry_date accepts strings as well' + ); $category->delete; }; @@ -105,16 +142,18 @@ subtest 'get_expiry_date' => sub { subtest 'BlockExpiredPatronOpacActions' => sub { plan tests => 4; t::lib::Mocks::mock_preference( 'BlockExpiredPatronOpacActions', 'hold,ill_request' ); - my $category = Koha::Patron::Category->new({ - categorycode => 'ya_cat', - category_type => 'A', - description => 'yacatdesc', - enrolmentperiod => undef, - BlockExpiredPatronOpacActions => 'follow_syspref_BlockExpiredPatronOpacActions', - })->store; - is( $category->effective_BlockExpiredPatronOpacActions_contains('hold'), 1 ); + my $category = Koha::Patron::Category->new( + { + categorycode => 'ya_cat', + category_type => 'A', + description => 'yacatdesc', + enrolmentperiod => undef, + BlockExpiredPatronOpacActions => 'follow_syspref_BlockExpiredPatronOpacActions', + } + )->store; + is( $category->effective_BlockExpiredPatronOpacActions_contains('hold'), 1 ); is( $category->effective_BlockExpiredPatronOpacActions_contains('ill_request'), 1 ); - is( $category->effective_BlockExpiredPatronOpacActions_contains('renew'), undef ); + is( $category->effective_BlockExpiredPatronOpacActions_contains('renew'), undef ); $category->BlockExpiredPatronOpacActions('renew')->store; is( $category->effective_BlockExpiredPatronOpacActions_contains('renew'), 1 ); $category->delete; @@ -124,14 +163,18 @@ $retrieved_category_1->delete; is( Koha::Patron::Categories->search->count, $nb_of_categories + 1, 'Delete should have deleted the patron category' ); my $new_category_4 = Koha::Patron::Category->new( - { categorycode => 'mycatcodeW', - category_type => 'A', - description => 'mycatdescW', - upperagelimit => '', + { + categorycode => 'mycatcodeW', + category_type => 'A', + description => 'mycatdescW', + upperagelimit => '', dateofbirthrequired => '', } )->store; -is( Koha::Patron::Categories->search->count, $nb_of_categories + 2, 'upperagelimit and dateofbirthrequired should have a default value if empty string is passed' ); +is( + Koha::Patron::Categories->search->count, $nb_of_categories + 2, + 'upperagelimit and dateofbirthrequired should have a default value if empty string is passed' +); $schema->storage->txn_rollback; diff --git a/t/db_dependent/Koha/Patron/Category.t b/t/db_dependent/Koha/Patron/Category.t index 0d7f42fa38..27c5725e5a 100755 --- a/t/db_dependent/Koha/Patron/Category.t +++ b/t/db_dependent/Koha/Patron/Category.t @@ -40,12 +40,12 @@ subtest 'effective_reset_password() tests' => sub { $schema->storage->txn_begin; - my $category = $builder->build_object({ - class => 'Koha::Patron::Categories', - value => { - reset_password => 1 + my $category = $builder->build_object( + { + class => 'Koha::Patron::Categories', + value => { reset_password => 1 } } - }); + ); t::lib::Mocks::mock_preference( 'OpacResetPassword', 0 ); ok( $category->effective_reset_password, 'OpacResetPassword unset, but category has the flag set to 1' ); @@ -54,7 +54,7 @@ subtest 'effective_reset_password() tests' => sub { ok( $category->effective_reset_password, 'OpacResetPassword set and category has the flag set to 1' ); # disable - $category->reset_password( 0 )->store->discard_changes; + $category->reset_password(0)->store->discard_changes; t::lib::Mocks::mock_preference( 'OpacResetPassword', 0 ); ok( !$category->effective_reset_password, 'OpacResetPassword unset, but category has the flag set to 0' ); @@ -71,12 +71,12 @@ subtest 'effective_reset_password() tests' => sub { $schema->storage->txn_begin; - my $category = $builder->build_object({ - class => 'Koha::Patron::Categories', - value => { - reset_password => undef + my $category = $builder->build_object( + { + class => 'Koha::Patron::Categories', + value => { reset_password => undef } } - }); + ); t::lib::Mocks::mock_preference( 'OpacResetPassword', 0 ); ok( !$category->effective_reset_password, 'OpacResetPassword set to 0 used' ); @@ -98,12 +98,12 @@ subtest 'effective_change_password() tests' => sub { $schema->storage->txn_begin; - my $category = $builder->build_object({ - class => 'Koha::Patron::Categories', - value => { - change_password => 1 + my $category = $builder->build_object( + { + class => 'Koha::Patron::Categories', + value => { change_password => 1 } } - }); + ); t::lib::Mocks::mock_preference( 'OpacPasswordChange', 0 ); ok( $category->effective_change_password, 'OpacPasswordChange unset, but category has the flag set to 1' ); @@ -112,7 +112,7 @@ subtest 'effective_change_password() tests' => sub { ok( $category->effective_change_password, 'OpacPasswordChange set and category has the flag set to 1' ); # disable - $category->change_password( 0 )->store->discard_changes; + $category->change_password(0)->store->discard_changes; t::lib::Mocks::mock_preference( 'OpacPasswordChange', 0 ); ok( !$category->effective_change_password, 'OpacPasswordChange unset, but category has the flag set to 0' ); @@ -129,12 +129,12 @@ subtest 'effective_change_password() tests' => sub { $schema->storage->txn_begin; - my $category = $builder->build_object({ - class => 'Koha::Patron::Categories', - value => { - change_password => undef + my $category = $builder->build_object( + { + class => 'Koha::Patron::Categories', + value => { change_password => undef } } - }); + ); t::lib::Mocks::mock_preference( 'OpacPasswordChange', 0 ); ok( !$category->effective_change_password, 'OpacPasswordChange set to 0 used' ); @@ -152,10 +152,13 @@ subtest 'override_hidden_items() tests' => sub { $schema->storage->txn_begin; - my $category_1 = $builder->build_object({ class => 'Koha::Patron::Categories' }); - my $category_2 = $builder->build_object({ class => 'Koha::Patron::Categories' }); + my $category_1 = $builder->build_object( { class => 'Koha::Patron::Categories' } ); + my $category_2 = $builder->build_object( { class => 'Koha::Patron::Categories' } ); - t::lib::Mocks::mock_preference( 'OpacHiddenItemsExceptions', $category_1->categorycode . ',' . $category_2->categorycode . ',RANDOM' ); + t::lib::Mocks::mock_preference( + 'OpacHiddenItemsExceptions', + $category_1->categorycode . ',' . $category_2->categorycode . ',RANDOM' + ); ok( $category_1->override_hidden_items, 'Category configured to override' ); ok( $category_2->override_hidden_items, 'Category configured to override' ); @@ -163,45 +166,47 @@ subtest 'override_hidden_items() tests' => sub { t::lib::Mocks::mock_preference( 'OpacHiddenItemsExceptions', 'RANDOM,' . $category_2->categorycode ); ok( !$category_1->override_hidden_items, 'Category not configured to override' ); - ok( $category_2->override_hidden_items, 'Category configured to override' ); + ok( $category_2->override_hidden_items, 'Category configured to override' ); $schema->storage->txn_rollback; }; subtest 'effective_min_password_length' => sub { - plan tests => 2; + plan tests => 2; - $schema->storage->txn_begin; + $schema->storage->txn_begin; - t::lib::Mocks::mock_preference('minPasswordLength', 3); + t::lib::Mocks::mock_preference( 'minPasswordLength', 3 ); - my $category = $builder->build_object({class => 'Koha::Patron::Categories', value => {min_password_length => undef}}); + my $category = + $builder->build_object( { class => 'Koha::Patron::Categories', value => { min_password_length => undef } } ); - is($category->effective_min_password_length, 3, 'Patron should have minimum password length from preference'); + is( $category->effective_min_password_length, 3, 'Patron should have minimum password length from preference' ); - $category->min_password_length(10)->store; + $category->min_password_length(10)->store; - is($category->effective_min_password_length, 10, 'Patron should have minimum password length from category'); + is( $category->effective_min_password_length, 10, 'Patron should have minimum password length from category' ); - $schema->storage->txn_rollback; + $schema->storage->txn_rollback; }; subtest 'effective_require_strong_password' => sub { - plan tests => 2; + plan tests => 2; - $schema->storage->txn_begin; + $schema->storage->txn_begin; - t::lib::Mocks::mock_preference('RequireStrongPassword', 0); + t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 ); - my $category = $builder->build_object({class => 'Koha::Patron::Categories', value => {require_strong_password => undef}}); + my $category = $builder->build_object( + { class => 'Koha::Patron::Categories', value => { require_strong_password => undef } } ); - is($category->effective_require_strong_password, 0, 'Patron should be required strong password from preference'); + is( $category->effective_require_strong_password, 0, 'Patron should be required strong password from preference' ); - $category->require_strong_password(1)->store; + $category->require_strong_password(1)->store; - is($category->effective_require_strong_password, 1, 'Patron should be required strong password from category'); + is( $category->effective_require_strong_password, 1, 'Patron should be required strong password from category' ); - $schema->storage->txn_rollback; + $schema->storage->txn_rollback; }; subtest 'effective_force_password_reset_when_set_by_staff() tests' => sub { @@ -277,20 +282,22 @@ subtest 'effective_force_password_reset_when_set_by_staff() tests' => sub { }; }; - subtest 'get_password_expiry_date() tests' => sub { plan tests => 3; $schema->storage->txn_begin; - my $category = $builder->build_object({ class => 'Koha::Patron::Categories' }); - $category->password_expiry_days( undef )->store; + my $category = $builder->build_object( { class => 'Koha::Patron::Categories' } ); + $category->password_expiry_days(undef)->store; is( $category->get_password_expiry_date(), undef, "No date returned if expiry days undef" ); - $category->password_expiry_days( 32 )->store; - is( $category->get_password_expiry_date(), dt_from_string()->add( days => 32 )->ymd, "Date correctly calculated from password_expiry_days when set"); + $category->password_expiry_days(32)->store; + is( + $category->get_password_expiry_date(), dt_from_string()->add( days => 32 )->ymd, + "Date correctly calculated from password_expiry_days when set" + ); my $dt = dt_from_string; my $original_dt = $dt->clone; @@ -308,11 +315,11 @@ subtest 'can_make_suggestions' => sub { $schema->storage->txn_begin; - t::lib::Mocks::mock_preference( 'suggestion', 0 ); + t::lib::Mocks::mock_preference( 'suggestion', 0 ); t::lib::Mocks::mock_preference( 'suggestionPatronCategoryExceptions', undef ); - my $category_1 = $builder->build_object({ class => 'Koha::Patron::Categories' }); - my $category_2 = $builder->build_object({ class => 'Koha::Patron::Categories' }); + my $category_1 = $builder->build_object( { class => 'Koha::Patron::Categories' } ); + my $category_2 = $builder->build_object( { class => 'Koha::Patron::Categories' } ); ok( !$category_1->can_make_suggestions && !$category_2->can_make_suggestions, @@ -337,7 +344,10 @@ subtest 'can_make_suggestions' => sub { 'suggestions enabled, suggestionPatronCategoryExceptions set, so present categories not allowed' ); - t::lib::Mocks::mock_preference( 'suggestionPatronCategoryExceptions', join( ',', $category_1->categorycode, $category_2->categorycode) ); + t::lib::Mocks::mock_preference( + 'suggestionPatronCategoryExceptions', + join( ',', $category_1->categorycode, $category_2->categorycode ) + ); ok( !$category_1->can_make_suggestions && !$category_2->can_make_suggestions, 'suggestions enabled, suggestionPatronCategoryExceptions set to both categories, both denied' diff --git a/t/db_dependent/Koha/Patron/Consents.t b/t/db_dependent/Koha/Patron/Consents.t index 5120022797..aafd88db38 100755 --- a/t/db_dependent/Koha/Patron/Consents.t +++ b/t/db_dependent/Koha/Patron/Consents.t @@ -31,21 +31,29 @@ use Koha::DateUtils qw/dt_from_string/; use Koha::Patron::Consents; our $builder = t::lib::TestBuilder->new; -our $schema = Koha::Database->new->schema; +our $schema = Koha::Database->new->schema; subtest 'Basic tests for Koha::Patron::Consent' => sub { plan tests => 2; $schema->storage->txn_begin; - my $patron1 = $builder->build_object({ class => 'Koha::Patrons' }); - my $consent1 = Koha::Patron::Consent->new({ - borrowernumber => $patron1->borrowernumber, - type => 'GDPR_PROCESSING', - given_on => dt_from_string, - })->store; - is( Koha::Patron::Consents->search({ borrowernumber => $patron1->borrowernumber })->count, 1, 'One consent for new borrower' ); + my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } ); + my $consent1 = Koha::Patron::Consent->new( + { + borrowernumber => $patron1->borrowernumber, + type => 'GDPR_PROCESSING', + given_on => dt_from_string, + } + )->store; + is( + Koha::Patron::Consents->search( { borrowernumber => $patron1->borrowernumber } )->count, 1, + 'One consent for new borrower' + ); $consent1->delete; - is( Koha::Patron::Consents->search({ borrowernumber => $patron1->borrowernumber })->count, 0, 'No consents left for new borrower' ); + is( + Koha::Patron::Consents->search( { borrowernumber => $patron1->borrowernumber } )->count, 0, + 'No consents left for new borrower' + ); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/Koha/Patron/Images.t b/t/db_dependent/Koha/Patron/Images.t index 86f705d567..9c8c26264b 100755 --- a/t/db_dependent/Koha/Patron/Images.t +++ b/t/db_dependent/Koha/Patron/Images.t @@ -31,20 +31,28 @@ my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; my $builder = t::lib::TestBuilder->new; -my $patron = $builder->build({ source => 'Borrower', }); -$patron = Koha::Patrons->find($patron->{borrowernumber}); +my $patron = $builder->build( { source => 'Borrower', } ); +$patron = Koha::Patrons->find( $patron->{borrowernumber} ); my $nb_of_images = Koha::Patron::Images->search->count; -my $new_image = Koha::Patron::Image->new({ - borrowernumber => $patron->borrowernumber, - mimetype => 'image/png', - imagefile => 'lot of binary content', -})->store; +my $new_image = Koha::Patron::Image->new( + { + borrowernumber => $patron->borrowernumber, + mimetype => 'image/png', + imagefile => 'lot of binary content', + } +)->store; is( Koha::Patron::Images->search->count, $nb_of_images + 1, 'The patron image should have been added' ); my $retrieved_image = Koha::Patron::Images->find( $new_image->borrowernumber ); -is( $retrieved_image->imagefile, $new_image->imagefile, 'Find a patron image by borrowernumber should return the correct image' ); -is( ref($patron->image), 'Koha::Patron::Image', 'Koha::Patron should have a image method which returns a Koha::Patron::Image' ); +is( + $retrieved_image->imagefile, $new_image->imagefile, + 'Find a patron image by borrowernumber should return the correct image' +); +is( + ref( $patron->image ), 'Koha::Patron::Image', + 'Koha::Patron should have a image method which returns a Koha::Patron::Image' +); $retrieved_image->delete; is( Koha::Patron::Images->search->count, $nb_of_images, 'Delete should have deleted the patron image' ); diff --git a/t/db_dependent/Koha/Patron/MessagePreference/Attributes.t b/t/db_dependent/Koha/Patron/MessagePreference/Attributes.t index 2c882578fc..e25a9b5faa 100755 --- a/t/db_dependent/Koha/Patron/MessagePreference/Attributes.t +++ b/t/db_dependent/Koha/Patron/MessagePreference/Attributes.t @@ -23,7 +23,7 @@ use Test::More tests => 2; use Koha::Database; -my $schema = Koha::Database->new->schema; +my $schema = Koha::Database->new->schema; subtest 'Test class imports' => sub { plan tests => 2; @@ -37,36 +37,44 @@ subtest 'Test Koha::Patron::MessagePreference::Attributes' => sub { $schema->storage->txn_begin; - Koha::Patron::MessagePreference::Attribute->new({ - message_name => 'Test_Attribute' - })->store; - Koha::Patron::MessagePreference::Attribute->new({ - message_name => 'Test_Attribute2', - takes_days => 1 - })->store; + Koha::Patron::MessagePreference::Attribute->new( { message_name => 'Test_Attribute' } )->store; + Koha::Patron::MessagePreference::Attribute->new( + { + message_name => 'Test_Attribute2', + takes_days => 1 + } + )->store; - my $attribute = Koha::Patron::MessagePreference::Attributes->find({ - message_name => 'Test_Attribute' }); - my $attribute2 = Koha::Patron::MessagePreference::Attributes->find({ - message_name => 'Test_Attribute2' }); + my $attribute = Koha::Patron::MessagePreference::Attributes->find( { message_name => 'Test_Attribute' } ); + my $attribute2 = Koha::Patron::MessagePreference::Attributes->find( { message_name => 'Test_Attribute2' } ); - is($attribute->message_name, 'Test_Attribute', - 'Added a new messaging attribute.'); - is($attribute->takes_days, 0, - 'For that messaging attribute, takes_days is disabled by default.'); - is($attribute2->message_name, 'Test_Attribute2', - 'Added another messaging attribute.'); - is($attribute2->takes_days, 1, - 'takes_days is enabled for that message attribute (as expected).'); + is( + $attribute->message_name, 'Test_Attribute', + 'Added a new messaging attribute.' + ); + is( + $attribute->takes_days, 0, + 'For that messaging attribute, takes_days is disabled by default.' + ); + is( + $attribute2->message_name, 'Test_Attribute2', + 'Added another messaging attribute.' + ); + is( + $attribute2->takes_days, 1, + 'takes_days is enabled for that message attribute (as expected).' + ); $attribute->delete; $attribute2->delete; - is(Koha::Patron::MessagePreference::Attributes->find({ - message_name => 'Test_Attribute' }), undef, - 'Deleted the first message attribute.'); - is(Koha::Patron::MessagePreference::Attributes->find({ - message_name => 'Test_Attribute2' }), undef, - 'Deleted the second message attribute.'); + is( + Koha::Patron::MessagePreference::Attributes->find( { message_name => 'Test_Attribute' } ), undef, + 'Deleted the first message attribute.' + ); + is( + Koha::Patron::MessagePreference::Attributes->find( { message_name => 'Test_Attribute2' } ), undef, + 'Deleted the second message attribute.' + ); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/Koha/Patron/MessagePreference/Transport/Preferences.t b/t/db_dependent/Koha/Patron/MessagePreference/Transport/Preferences.t index f240a6bdd6..8f9af16e37 100755 --- a/t/db_dependent/Koha/Patron/MessagePreference/Transport/Preferences.t +++ b/t/db_dependent/Koha/Patron/MessagePreference/Transport/Preferences.t @@ -47,65 +47,89 @@ subtest 'Test Koha::Patron::MessagePreference::Transport::Preferences' => sub { $schema->storage->txn_begin; - my $attribute = $builder->build_object({ class => 'Koha::Patron::MessagePreference::Attributes' }); - my $mtt = $builder->build_object({ class => 'Koha::Patron::MessagePreference::Transport::Types' }); - my $letter = build_a_test_letter({ - mtt => $mtt->message_transport_type - }); - Koha::Patron::MessagePreference::Transport->new({ - message_attribute_id => $attribute->message_attribute_id, - message_transport_type => $mtt->message_transport_type, - is_digest => 0, - letter_module => $letter->module, - letter_code => $letter->code, - })->store; + my $attribute = $builder->build_object( { class => 'Koha::Patron::MessagePreference::Attributes' } ); + my $mtt = $builder->build_object( { class => 'Koha::Patron::MessagePreference::Transport::Types' } ); + my $letter = build_a_test_letter( { mtt => $mtt->message_transport_type } ); + Koha::Patron::MessagePreference::Transport->new( + { + message_attribute_id => $attribute->message_attribute_id, + message_transport_type => $mtt->message_transport_type, + is_digest => 0, + letter_module => $letter->module, + letter_code => $letter->code, + } + )->store; subtest 'For a patron' => sub { - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); - my $preference = Koha::Patron::MessagePreference->new({ - borrowernumber => $patron->borrowernumber, - message_attribute_id => $attribute->message_attribute_id, - wants_digest => 0, - days_in_advance => undef, - })->store; + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + my $preference = Koha::Patron::MessagePreference->new( + { + borrowernumber => $patron->borrowernumber, + message_attribute_id => $attribute->message_attribute_id, + wants_digest => 0, + days_in_advance => undef, + } + )->store; - my $pref_id = $preference->borrower_message_preference_id; - my $transport_pref = Koha::Patron::MessagePreference::Transport::Preference->new({ - borrower_message_preference_id => $pref_id, - message_transport_type => $mtt->message_transport_type, - })->store; - is(ref($transport_pref), 'Koha::Patron::MessagePreference::Transport::Preference', - 'Added a new messaging transport preference for patron.'); + my $pref_id = $preference->borrower_message_preference_id; + my $transport_pref = Koha::Patron::MessagePreference::Transport::Preference->new( + { + borrower_message_preference_id => $pref_id, + message_transport_type => $mtt->message_transport_type, + } + )->store; + is( + ref($transport_pref), 'Koha::Patron::MessagePreference::Transport::Preference', + 'Added a new messaging transport preference for patron.' + ); $transport_pref->delete; - is(Koha::Patron::MessagePreference::Transport::Preferences->search({ - borrower_message_preference_id => $pref_id, - message_transport_type => $mtt->message_transport_type, - })->count, 0, 'Deleted the messaging transport preference.'); + is( + Koha::Patron::MessagePreference::Transport::Preferences->search( + { + borrower_message_preference_id => $pref_id, + message_transport_type => $mtt->message_transport_type, + } + )->count, + 0, + 'Deleted the messaging transport preference.' + ); }; subtest 'For a category' => sub { - my $category = $builder->build_object({ class => 'Koha::Patron::Categories' }); - my $preference = Koha::Patron::MessagePreference->new({ - categorycode => $category->categorycode, - message_attribute_id => $attribute->message_attribute_id, - wants_digest => 0, - days_in_advance => undef, - })->store; + my $category = $builder->build_object( { class => 'Koha::Patron::Categories' } ); + my $preference = Koha::Patron::MessagePreference->new( + { + categorycode => $category->categorycode, + message_attribute_id => $attribute->message_attribute_id, + wants_digest => 0, + days_in_advance => undef, + } + )->store; - my $pref_id = $preference->borrower_message_preference_id; - my $transport_pref = Koha::Patron::MessagePreference::Transport::Preference->new({ - borrower_message_preference_id => $pref_id, - message_transport_type => $mtt->message_transport_type, - })->store; - is(ref($transport_pref), 'Koha::Patron::MessagePreference::Transport::Preference', - 'Added a new messaging transport preference for category.'); + my $pref_id = $preference->borrower_message_preference_id; + my $transport_pref = Koha::Patron::MessagePreference::Transport::Preference->new( + { + borrower_message_preference_id => $pref_id, + message_transport_type => $mtt->message_transport_type, + } + )->store; + is( + ref($transport_pref), 'Koha::Patron::MessagePreference::Transport::Preference', + 'Added a new messaging transport preference for category.' + ); $transport_pref->delete; - is(Koha::Patron::MessagePreference::Transport::Preferences->search({ - borrower_message_preference_id => $pref_id, - message_transport_type => $mtt->message_transport_type, - })->count, 0, 'Deleted the messaging transport preference.'); + is( + Koha::Patron::MessagePreference::Transport::Preferences->search( + { + borrower_message_preference_id => $pref_id, + message_transport_type => $mtt->message_transport_type, + } + )->count, + 0, + 'Deleted the messaging transport preference.' + ); }; $schema->storage->txn_rollback; @@ -114,23 +138,26 @@ subtest 'Test Koha::Patron::MessagePreference::Transport::Preferences' => sub { sub build_a_test_letter { my ($params) = @_; - my $mtt = $params->{mtt} ? $params->{mtt} : 'email'; - my $branchcode = $builder->build({ - source => 'Branch' })->{branchcode}; - my $letter = $builder->build({ - source => 'Letter', - value => { - branchcode => '', - is_html => 0, - message_transport_type => $mtt + my $mtt = $params->{mtt} ? $params->{mtt} : 'email'; + my $branchcode = $builder->build( { source => 'Branch' } )->{branchcode}; + my $letter = $builder->build( + { + source => 'Letter', + value => { + branchcode => '', + is_html => 0, + message_transport_type => $mtt + } } - }); + ); - return Koha::Notice::Templates->find({ - module => $letter->{module}, - code => $letter->{code}, - branchcode => $letter->{branchcode}, - }); + return Koha::Notice::Templates->find( + { + module => $letter->{module}, + code => $letter->{code}, + branchcode => $letter->{branchcode}, + } + ); } 1; diff --git a/t/db_dependent/Koha/Patron/MessagePreference/Transport/Types.t b/t/db_dependent/Koha/Patron/MessagePreference/Transport/Types.t index 8231fe28e3..436caab534 100755 --- a/t/db_dependent/Koha/Patron/MessagePreference/Transport/Types.t +++ b/t/db_dependent/Koha/Patron/MessagePreference/Transport/Types.t @@ -23,7 +23,7 @@ use Test::More tests => 2; use Koha::Database; -my $schema = Koha::Database->new->schema; +my $schema = Koha::Database->new->schema; subtest 'Test class imports' => sub { plan tests => 2; @@ -37,16 +37,19 @@ subtest 'Test Koha::Patron::MessagePreference::Transport::Types' => sub { $schema->storage->txn_begin; - my $transport_type = Koha::Patron::MessagePreference::Transport::Type->new({ - message_transport_type => 'test' - })->store; + my $transport_type = + Koha::Patron::MessagePreference::Transport::Type->new( { message_transport_type => 'test' } )->store; - is($transport_type->message_transport_type, 'test', - 'Added a new message transport type.'); + is( + $transport_type->message_transport_type, 'test', + 'Added a new message transport type.' + ); $transport_type->delete; - is(Koha::Patron::MessagePreference::Transport::Types->find('test'), undef, - 'Deleted the message transport type.'); + is( + Koha::Patron::MessagePreference::Transport::Types->find('test'), undef, + 'Deleted the message transport type.' + ); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/Koha/Patron/MessagePreference/Transports.t b/t/db_dependent/Koha/Patron/MessagePreference/Transports.t index 000835ecb2..5aee0a52a2 100755 --- a/t/db_dependent/Koha/Patron/MessagePreference/Transports.t +++ b/t/db_dependent/Koha/Patron/MessagePreference/Transports.t @@ -42,29 +42,37 @@ subtest 'Test Koha::Patron::MessagePreference::Transports' => sub { $schema->storage->txn_begin; - my $attribute = $builder->build_object({ class => 'Koha::Patron::MessagePreference::Attributes' }); - my $mtt = $builder->build_object({ class => 'Koha::Patron::MessagePreference::Transport::Types' }); - my $letter = build_a_test_letter({ - mtt => $mtt->message_transport_type - }); + my $attribute = $builder->build_object( { class => 'Koha::Patron::MessagePreference::Attributes' } ); + my $mtt = $builder->build_object( { class => 'Koha::Patron::MessagePreference::Transport::Types' } ); + my $letter = build_a_test_letter( { mtt => $mtt->message_transport_type } ); - my $transport = Koha::Patron::MessagePreference::Transport->new({ - message_attribute_id => $attribute->message_attribute_id, - message_transport_type => $mtt->message_transport_type, - is_digest => 0, - letter_module => $letter->module, - letter_code => $letter->code, - })->store; + my $transport = Koha::Patron::MessagePreference::Transport->new( + { + message_attribute_id => $attribute->message_attribute_id, + message_transport_type => $mtt->message_transport_type, + is_digest => 0, + letter_module => $letter->module, + letter_code => $letter->code, + } + )->store; - is($transport->message_attribute_id, $attribute->message_attribute_id, - 'Added a new messaging transport.'); + is( + $transport->message_attribute_id, $attribute->message_attribute_id, + 'Added a new messaging transport.' + ); $transport->delete; - is(Koha::Patron::MessagePreference::Transports->search({ - message_attribute_id => $attribute->message_attribute_id, - message_transport_type => $mtt->message_transport_type, - is_digest => 0 - })->count, 0, 'Deleted the messaging transport.'); + is( + Koha::Patron::MessagePreference::Transports->search( + { + message_attribute_id => $attribute->message_attribute_id, + message_transport_type => $mtt->message_transport_type, + is_digest => 0 + } + )->count, + 0, + 'Deleted the messaging transport.' + ); $schema->storage->txn_rollback; }; @@ -72,23 +80,26 @@ subtest 'Test Koha::Patron::MessagePreference::Transports' => sub { sub build_a_test_letter { my ($params) = @_; - my $mtt = $params->{mtt} ? $params->{mtt} : 'email'; - my $branchcode = $builder->build({ - source => 'Branch' })->{branchcode}; - my $letter = $builder->build({ - source => 'Letter', - value => { - branchcode => '', - is_html => 0, - message_transport_type => $mtt + my $mtt = $params->{mtt} ? $params->{mtt} : 'email'; + my $branchcode = $builder->build( { source => 'Branch' } )->{branchcode}; + my $letter = $builder->build( + { + source => 'Letter', + value => { + branchcode => '', + is_html => 0, + message_transport_type => $mtt + } } - }); + ); - return Koha::Notice::Templates->find({ - module => $letter->{module}, - code => $letter->{code}, - branchcode => $letter->{branchcode}, - }); + return Koha::Notice::Templates->find( + { + module => $letter->{module}, + code => $letter->{code}, + branchcode => $letter->{branchcode}, + } + ); } 1; diff --git a/t/db_dependent/Koha/Patron/MessagePreferences.t b/t/db_dependent/Koha/Patron/MessagePreferences.t index 9e60cbff2e..fadb843a54 100755 --- a/t/db_dependent/Koha/Patron/MessagePreferences.t +++ b/t/db_dependent/Koha/Patron/MessagePreferences.t @@ -51,74 +51,101 @@ subtest 'Test Koha::Patron::MessagePreferences' => sub { $schema->storage->txn_begin; - my $attribute = $builder->build_object({ class => 'Koha::Patron::MessagePreference::Attributes' }); - my $letter = build_a_test_letter(); - my $mtt = $builder->build_object({ class => 'Koha::Patron::MessagePreference::Transport::Types' }); - Koha::Patron::MessagePreference::Transport->new({ - message_attribute_id => $attribute->message_attribute_id, - message_transport_type => $mtt->message_transport_type, - is_digest => 0, - letter_module => $letter->module, - letter_code => $letter->code, - })->store; + my $attribute = $builder->build_object( { class => 'Koha::Patron::MessagePreference::Attributes' } ); + my $letter = build_a_test_letter(); + my $mtt = $builder->build_object( { class => 'Koha::Patron::MessagePreference::Transport::Types' } ); + Koha::Patron::MessagePreference::Transport->new( + { + message_attribute_id => $attribute->message_attribute_id, + message_transport_type => $mtt->message_transport_type, + is_digest => 0, + letter_module => $letter->module, + letter_code => $letter->code, + } + )->store; subtest 'Test for a patron' => sub { plan tests => 3; - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); - Koha::Patron::MessagePreference->new({ - borrowernumber => $patron->borrowernumber, - message_attribute_id => $attribute->message_attribute_id, - wants_digest => 0, - days_in_advance => undef, - })->store; + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + Koha::Patron::MessagePreference->new( + { + borrowernumber => $patron->borrowernumber, + message_attribute_id => $attribute->message_attribute_id, + wants_digest => 0, + days_in_advance => undef, + } + )->store; - my $preference = Koha::Patron::MessagePreferences->find({ - borrowernumber => $patron->borrowernumber, - message_attribute_id => $attribute->message_attribute_id - }); - ok($preference->borrower_message_preference_id > 0, - 'Added a new messaging preference for patron.'); + my $preference = Koha::Patron::MessagePreferences->find( + { + borrowernumber => $patron->borrowernumber, + message_attribute_id => $attribute->message_attribute_id + } + ); + ok( + $preference->borrower_message_preference_id > 0, + 'Added a new messaging preference for patron.' + ); subtest 'Test set not throwing an exception on duplicate object' => sub { plan tests => 1; - Koha::Patron::MessagePreference::Attributes->find({ - message_attribute_id => $attribute->message_attribute_id - })->set({ takes_days => 1 })->store; - $preference->set({ days_in_advance => 1 })->store; - is(ref($preference), 'Koha::Patron::MessagePreference', - 'Updating the preference does not cause duplicate object exception'); + Koha::Patron::MessagePreference::Attributes->find( + { message_attribute_id => $attribute->message_attribute_id } )->set( { takes_days => 1 } )->store; + $preference->set( { days_in_advance => 1 } )->store; + is( + ref($preference), 'Koha::Patron::MessagePreference', + 'Updating the preference does not cause duplicate object exception' + ); }; $preference->delete; - is(Koha::Patron::MessagePreferences->search({ - borrowernumber => $patron->borrowernumber, - message_attribute_id => $attribute->message_attribute_id - })->count, 0, 'Deleted the messaging preference.'); + is( + Koha::Patron::MessagePreferences->search( + { + borrowernumber => $patron->borrowernumber, + message_attribute_id => $attribute->message_attribute_id + } + )->count, + 0, + 'Deleted the messaging preference.' + ); }; subtest 'Test for a category' => sub { - my $category = $builder->build_object({ class => 'Koha::Patron::Categories' }); - Koha::Patron::MessagePreference->new({ - categorycode => $category->categorycode, - message_attribute_id => $attribute->message_attribute_id, - wants_digest => 0, - days_in_advance => undef, - })->store; + my $category = $builder->build_object( { class => 'Koha::Patron::Categories' } ); + Koha::Patron::MessagePreference->new( + { + categorycode => $category->categorycode, + message_attribute_id => $attribute->message_attribute_id, + wants_digest => 0, + days_in_advance => undef, + } + )->store; - my $preference = Koha::Patron::MessagePreferences->find({ - categorycode => $category->categorycode, - message_attribute_id => $attribute->message_attribute_id - }); - ok($preference->borrower_message_preference_id > 0, - 'Added a new messaging preference for category.'); + my $preference = Koha::Patron::MessagePreferences->find( + { + categorycode => $category->categorycode, + message_attribute_id => $attribute->message_attribute_id + } + ); + ok( + $preference->borrower_message_preference_id > 0, + 'Added a new messaging preference for category.' + ); $preference->delete; - is(Koha::Patron::MessagePreferences->search({ - categorycode => $category->categorycode, - message_attribute_id => $attribute->message_attribute_id - })->count, 0, 'Deleted the messaging preference.'); + is( + Koha::Patron::MessagePreferences->search( + { + categorycode => $category->categorycode, + message_attribute_id => $attribute->message_attribute_id + } + )->count, + 0, + 'Deleted the messaging preference.' + ); }; $schema->storage->txn_rollback; @@ -130,11 +157,15 @@ subtest 'Test Koha::Patron::MessagePreferences->get_options' => sub { subtest 'Test method availability and return value' => sub { plan tests => 3; - ok(Koha::Patron::MessagePreferences->can('get_options'), - 'Method get_options is available.'); - ok(my $options = Koha::Patron::MessagePreferences->get_options, - 'Called get_options successfully.'); - is(ref($options), 'ARRAY', 'get_options returns a ARRAYref'); + ok( + Koha::Patron::MessagePreferences->can('get_options'), + 'Method get_options is available.' + ); + ok( + my $options = Koha::Patron::MessagePreferences->get_options, + 'Called get_options successfully.' + ); + is( ref($options), 'ARRAY', 'get_options returns a ARRAYref' ); }; subtest 'Make sure options are correct' => sub { @@ -142,19 +173,29 @@ subtest 'Test Koha::Patron::MessagePreferences->get_options' => sub { my $options = Koha::Patron::MessagePreferences->get_options; foreach my $option (@$options) { - my $n = $option->{'message_name'}; - my $attr = Koha::Patron::MessagePreference::Attributes->find($option->{'message_attribute_id'}); - is($option->{'message_attribute_id'}, $attr->message_attribute_id, - '$n: message_attribute_id is set'); - is($option->{'message_name'}, $attr->message_name, '$n: message_name is set'); - is($option->{'takes_days'}, $attr->takes_days, '$n: takes_days is set'); - my $transports = Koha::Patron::MessagePreference::Transports->search({ - message_attribute_id => $option->{'message_attribute_id'}, - is_digest => $option->{'has_digest'} || 0, - }); - while (my $trnzport = $transports->next) { - is($option->{'has_digest'} || 0, $trnzport->is_digest, '$n: has_digest is set for '.$trnzport->message_transport_type); - is($option->{'transport_'.$trnzport->message_transport_type}, ' ', '$n: transport_'.$trnzport->message_transport_type.' is set'); + my $n = $option->{'message_name'}; + my $attr = Koha::Patron::MessagePreference::Attributes->find( $option->{'message_attribute_id'} ); + is( + $option->{'message_attribute_id'}, $attr->message_attribute_id, + '$n: message_attribute_id is set' + ); + is( $option->{'message_name'}, $attr->message_name, '$n: message_name is set' ); + is( $option->{'takes_days'}, $attr->takes_days, '$n: takes_days is set' ); + my $transports = Koha::Patron::MessagePreference::Transports->search( + { + message_attribute_id => $option->{'message_attribute_id'}, + is_digest => $option->{'has_digest'} || 0, + } + ); + while ( my $trnzport = $transports->next ) { + is( + $option->{'has_digest'} || 0, $trnzport->is_digest, + '$n: has_digest is set for ' . $trnzport->message_transport_type + ); + is( + $option->{ 'transport_' . $trnzport->message_transport_type }, ' ', + '$n: transport_' . $trnzport->message_transport_type . ' is set' + ); } } @@ -167,22 +208,38 @@ subtest 'Add preferences from defaults' => sub { $schema->storage->txn_begin; - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); - my ($default, $mtt1, $mtt2) = build_a_test_category_preference({ - patron => $patron, - }); - ok(Koha::Patron::MessagePreference->new_from_default({ - borrowernumber => $patron->borrowernumber, - categorycode => $patron->categorycode, - message_attribute_id => $default->message_attribute_id, - })->store, 'Added a default preference to patron.'); - ok(my $pref = Koha::Patron::MessagePreferences->find({ - borrowernumber => $patron->borrowernumber, - message_attribute_id => $default->message_attribute_id, - }), 'Found the default preference from patron.'); - is(Koha::Patron::MessagePreference::Transport::Preferences->search({ - borrower_message_preference_id => $pref->borrower_message_preference_id - })->count, 2, 'Found the two transport types that we set earlier'); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + my ( $default, $mtt1, $mtt2 ) = build_a_test_category_preference( + { + patron => $patron, + } + ); + ok( + Koha::Patron::MessagePreference->new_from_default( + { + borrowernumber => $patron->borrowernumber, + categorycode => $patron->categorycode, + message_attribute_id => $default->message_attribute_id, + } + )->store, + 'Added a default preference to patron.' + ); + ok( + my $pref = Koha::Patron::MessagePreferences->find( + { + borrowernumber => $patron->borrowernumber, + message_attribute_id => $default->message_attribute_id, + } + ), + 'Found the default preference from patron.' + ); + is( + Koha::Patron::MessagePreference::Transport::Preferences->search( + { borrower_message_preference_id => $pref->borrower_message_preference_id } + )->count, + 2, + 'Found the two transport types that we set earlier' + ); $schema->storage->txn_rollback; }; @@ -190,55 +247,76 @@ subtest 'Add preferences from defaults' => sub { subtest 'Test Koha::Patron::MessagePreference->message_transport_types' => sub { plan tests => 4; - ok(Koha::Patron::MessagePreference->can('message_transport_types'), - 'Method message_transport_types available'); + ok( + Koha::Patron::MessagePreference->can('message_transport_types'), + 'Method message_transport_types available' + ); subtest 'get message_transport_types' => sub { plan tests => 5; $schema->storage->txn_begin; - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); - my ($preference, $mtt1, $mtt2) = build_a_test_complete_preference({ - patron => $patron - }); - Koha::Patron::MessagePreference::Transport::Preferences->search({ - borrower_message_preference_id => $preference->borrower_message_preference_id, - })->delete; - Koha::Patron::MessagePreference::Transport::Preference->new({ - borrower_message_preference_id => $preference->borrower_message_preference_id, - message_transport_type => $mtt1->message_transport_type, - })->store; - Koha::Patron::MessagePreference::Transport::Preference->new({ - borrower_message_preference_id => $preference->borrower_message_preference_id, - message_transport_type => $mtt2->message_transport_type, - })->store; - my $stored_transports = Koha::Patron::MessagePreference::Transport::Preferences->search({ - borrower_message_preference_id => $preference->borrower_message_preference_id, - }); - my $transport1 = Koha::Patron::MessagePreference::Transports->find({ - message_attribute_id => $preference->message_attribute_id, - message_transport_type => $mtt1->message_transport_type, - }); - my $transport2 = Koha::Patron::MessagePreference::Transports->find({ - message_attribute_id => $preference->message_attribute_id, - message_transport_type => $mtt2->message_transport_type, - }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + my ( $preference, $mtt1, $mtt2 ) = build_a_test_complete_preference( { patron => $patron } ); + Koha::Patron::MessagePreference::Transport::Preferences->search( + { + borrower_message_preference_id => $preference->borrower_message_preference_id, + } + )->delete; + Koha::Patron::MessagePreference::Transport::Preference->new( + { + borrower_message_preference_id => $preference->borrower_message_preference_id, + message_transport_type => $mtt1->message_transport_type, + } + )->store; + Koha::Patron::MessagePreference::Transport::Preference->new( + { + borrower_message_preference_id => $preference->borrower_message_preference_id, + message_transport_type => $mtt2->message_transport_type, + } + )->store; + my $stored_transports = Koha::Patron::MessagePreference::Transport::Preferences->search( + { + borrower_message_preference_id => $preference->borrower_message_preference_id, + } + ); + my $transport1 = Koha::Patron::MessagePreference::Transports->find( + { + message_attribute_id => $preference->message_attribute_id, + message_transport_type => $mtt1->message_transport_type, + } + ); + my $transport2 = Koha::Patron::MessagePreference::Transports->find( + { + message_attribute_id => $preference->message_attribute_id, + message_transport_type => $mtt2->message_transport_type, + } + ); my $transports = $preference->message_transport_types; - is(keys %{$transports}, $stored_transports->count, - '->message_transport_types gets correct amount of transport types.'); - is($transports->{$stored_transports->next->message_transport_type}, - $transport1->letter_code, 'Found correct message transport type and letter code.'); - is($transports->{$stored_transports->next->message_transport_type}, - $transport2->letter_code, 'Found correct message transport type and letter code.'); - ok(!$preference->message_transport_types->{'nonexistent'}, - 'Didn\'t find nonexistent transport type.'); + is( + keys %{$transports}, $stored_transports->count, + '->message_transport_types gets correct amount of transport types.' + ); + is( + $transports->{ $stored_transports->next->message_transport_type }, + $transport1->letter_code, 'Found correct message transport type and letter code.' + ); + is( + $transports->{ $stored_transports->next->message_transport_type }, + $transport2->letter_code, 'Found correct message transport type and letter code.' + ); + ok( + !$preference->message_transport_types->{'nonexistent'}, + 'Didn\'t find nonexistent transport type.' + ); subtest 'test logging of warnings by invalid message transport type' => sub { plan tests => 2; - my $log = mytempfile(); - my $conf = mytempfile( <<"HERE" + my $log = mytempfile(); + my $conf = mytempfile( + <<"HERE" log4perl.logger.opac = WARN, OPAC log4perl.appender.OPAC=Log::Log4perl::Appender::TestBuffer log4perl.appender.OPAC.filename=$log @@ -251,31 +329,30 @@ log4perl.appender.INTRANET.mode=append log4perl.appender.INTRANET.layout=SimpleLayout HERE ); - t::lib::Mocks::mock_config('log4perl_conf', $conf); + t::lib::Mocks::mock_config( 'log4perl_conf', $conf ); my $appenders = Log::Log4perl->appenders; - my $appender = Log::Log4perl->appenders->{OPAC}; + my $appender = Log::Log4perl->appenders->{OPAC}; - my $pref = Koha::Patron::MessagePreferences->find( - $preference->borrower_message_preference_id - ); + my $pref = Koha::Patron::MessagePreferences->find( $preference->borrower_message_preference_id ); my $transports = $pref->message_transport_types; - is($appender, undef, 'Nothing in buffer yet'); + is( $appender, undef, 'Nothing in buffer yet' ); - my $mtt_new = $builder->build_object({ class => 'Koha::Patron::MessagePreference::Transport::Types' }); - Koha::Patron::MessagePreference::Transport::Preference->new({ - borrower_message_preference_id => - $pref->borrower_message_preference_id, - message_transport_type => $mtt_new->message_transport_type, - })->store; - $pref = Koha::Patron::MessagePreferences->find( - $pref->borrower_message_preference_id - ); + my $mtt_new = $builder->build_object( { class => 'Koha::Patron::MessagePreference::Transport::Types' } ); + Koha::Patron::MessagePreference::Transport::Preference->new( + { + borrower_message_preference_id => $pref->borrower_message_preference_id, + message_transport_type => $mtt_new->message_transport_type, + } + )->store; + $pref = Koha::Patron::MessagePreferences->find( $pref->borrower_message_preference_id ); $transports = $pref->message_transport_types; - $appender = Log::Log4perl->appenders->{OPAC}; + $appender = Log::Log4perl->appenders->{OPAC}; my $name = $pref->message_name; - my $tt = $mtt_new->message_transport_type; - like($appender->buffer, qr/WARN - $name has no transport with $tt/, - 'Logged invalid message transport type'); + my $tt = $mtt_new->message_transport_type; + like( + $appender->buffer, qr/WARN - $name has no transport with $tt/, + 'Logged invalid message transport type' + ); }; $schema->storage->txn_rollback; @@ -286,134 +363,154 @@ HERE $schema->storage->txn_begin; - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); - my ($preference, $mtt1, $mtt2) = build_a_test_complete_preference({ - patron => $patron - }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + my ( $preference, $mtt1, $mtt2 ) = build_a_test_complete_preference( { patron => $patron } ); my $mtt1_str = $mtt1->message_transport_type; my $mtt2_str = $mtt2->message_transport_type; + # 1/3, use message_transport_types(list) - Koha::Patron::MessagePreference::Transport::Preferences->search({ - borrower_message_preference_id => $preference->borrower_message_preference_id, - })->delete; - ok($preference->message_transport_types($mtt1_str, $mtt2_str)->store, - '1/3 Set returned true.'); - my $stored_transports = Koha::Patron::MessagePreference::Transport::Preferences->search({ - borrower_message_preference_id => $preference->borrower_message_preference_id, - '-or' => [ - message_transport_type => $mtt1_str, - message_transport_type => $mtt2_str - ] - }); - is($stored_transports->count, 2, 'Two transports selected'); + Koha::Patron::MessagePreference::Transport::Preferences->search( + { + borrower_message_preference_id => $preference->borrower_message_preference_id, + } + )->delete; + ok( + $preference->message_transport_types( $mtt1_str, $mtt2_str )->store, + '1/3 Set returned true.' + ); + my $stored_transports = Koha::Patron::MessagePreference::Transport::Preferences->search( + { + borrower_message_preference_id => $preference->borrower_message_preference_id, + '-or' => [ + message_transport_type => $mtt1_str, + message_transport_type => $mtt2_str + ] + } + ); + is( $stored_transports->count, 2, 'Two transports selected' ); # 2/3, use message_transport_types(ARRAYREF) - Koha::Patron::MessagePreference::Transport::Preferences->search({ - borrower_message_preference_id => $preference->borrower_message_preference_id, - })->delete; - ok($preference->message_transport_types([$mtt1_str, $mtt2_str])->store, - '2/3 Set returned true.'); - $stored_transports = Koha::Patron::MessagePreference::Transport::Preferences->search({ - borrower_message_preference_id => $preference->borrower_message_preference_id, - '-or' => [ - message_transport_type => $mtt1_str, - message_transport_type => $mtt2_str - ] - }); - is($stored_transports->count, 2, 'Two transports selected'); + Koha::Patron::MessagePreference::Transport::Preferences->search( + { + borrower_message_preference_id => $preference->borrower_message_preference_id, + } + )->delete; + ok( + $preference->message_transport_types( [ $mtt1_str, $mtt2_str ] )->store, + '2/3 Set returned true.' + ); + $stored_transports = Koha::Patron::MessagePreference::Transport::Preferences->search( + { + borrower_message_preference_id => $preference->borrower_message_preference_id, + '-or' => [ + message_transport_type => $mtt1_str, + message_transport_type => $mtt2_str + ] + } + ); + is( $stored_transports->count, 2, 'Two transports selected' ); # 3/3, use set({ message_transport_types => ARRAYREF }) - Koha::Patron::MessagePreference::Transport::Preferences->search({ - borrower_message_preference_id => $preference->borrower_message_preference_id, - })->delete; - ok($preference->set({ - message_transport_types => [$mtt1_str, $mtt2_str]})->store, - '3/3 Set returned true.'); - $stored_transports = Koha::Patron::MessagePreference::Transport::Preferences->search({ - borrower_message_preference_id => $preference->borrower_message_preference_id, - '-or' => [ - message_transport_type => $mtt1_str, - message_transport_type => $mtt2_str - ] - }); - is($stored_transports->count, 2, 'Two transports selected'); + Koha::Patron::MessagePreference::Transport::Preferences->search( + { + borrower_message_preference_id => $preference->borrower_message_preference_id, + } + )->delete; + ok( + $preference->set( { message_transport_types => [ $mtt1_str, $mtt2_str ] } )->store, + '3/3 Set returned true.' + ); + $stored_transports = Koha::Patron::MessagePreference::Transport::Preferences->search( + { + borrower_message_preference_id => $preference->borrower_message_preference_id, + '-or' => [ + message_transport_type => $mtt1_str, + message_transport_type => $mtt2_str + ] + } + ); + is( $stored_transports->count, 2, 'Two transports selected' ); # Test contact information validation - eval { Koha::Patron::MessagePreference::Transport::Types->new({ - message_transport_type => 'email' - })->store }; - eval { Koha::Patron::MessagePreference::Transport::Types->new({ - message_transport_type => 'itiva' - })->store }; - eval { Koha::Patron::MessagePreference::Transport::Types->new({ - message_transport_type => 'phone' - })->store }; - eval { Koha::Patron::MessagePreference::Transport::Types->new({ - message_transport_type => 'sms' - })->store }; - Koha::Patron::MessagePreference::Transport->new({ - message_attribute_id => $preference->message_attribute_id, - message_transport_type => 'email', - is_digest => 1 - })->store; - Koha::Patron::MessagePreference::Transport->new({ - message_attribute_id => $preference->message_attribute_id, - message_transport_type => 'itiva', - is_digest => 1 - })->store; - Koha::Patron::MessagePreference::Transport->new({ - message_attribute_id => $preference->message_attribute_id, - message_transport_type => 'phone', - is_digest => 1 - })->store; - Koha::Patron::MessagePreference::Transport->new({ - message_attribute_id => $preference->message_attribute_id, - message_transport_type => 'sms', - is_digest => 1 - })->store; - t::lib::Mocks::mock_preference('TalkingTechItivaPhoneNotification', 0); - $patron->set({ email => '', emailpro => '', B_email => '', phone => '', smsalertnumber => '' })->store; - eval { - $preference->message_transport_types('email')->store; - }; - is (ref $@, 'Koha::Exceptions::Patron::MessagePreference::EmailAddressRequired', + eval { Koha::Patron::MessagePreference::Transport::Types->new( { message_transport_type => 'email' } )->store }; + eval { Koha::Patron::MessagePreference::Transport::Types->new( { message_transport_type => 'itiva' } )->store }; + eval { Koha::Patron::MessagePreference::Transport::Types->new( { message_transport_type => 'phone' } )->store }; + eval { Koha::Patron::MessagePreference::Transport::Types->new( { message_transport_type => 'sms' } )->store }; + Koha::Patron::MessagePreference::Transport->new( + { + message_attribute_id => $preference->message_attribute_id, + message_transport_type => 'email', + is_digest => 1 + } + )->store; + Koha::Patron::MessagePreference::Transport->new( + { + message_attribute_id => $preference->message_attribute_id, + message_transport_type => 'itiva', + is_digest => 1 + } + )->store; + Koha::Patron::MessagePreference::Transport->new( + { + message_attribute_id => $preference->message_attribute_id, + message_transport_type => 'phone', + is_digest => 1 + } + )->store; + Koha::Patron::MessagePreference::Transport->new( + { + message_attribute_id => $preference->message_attribute_id, + message_transport_type => 'sms', + is_digest => 1 + } + )->store; + t::lib::Mocks::mock_preference( 'TalkingTechItivaPhoneNotification', 0 ); + $patron->set( { email => '', emailpro => '', B_email => '', phone => '', smsalertnumber => '' } )->store; + eval { $preference->message_transport_types('email')->store; }; + is( + ref $@, 'Koha::Exceptions::Patron::MessagePreference::EmailAddressRequired', 'Adding a message preference with invalid message_transport_type' - .' => Koha::Exceptions::Patron::MessagePreference::EmailAddressRequired'); - is ($@->message_name, $preference->message_name, 'The previous exception ' - .' tells us it which message name it was.'); - is ($@->borrowernumber, $patron->borrowernumber, 'The previous exception ' - .' tells us which patron it was.'); - eval { - $preference->message_transport_types('itiva')->store; - }; - is (ref $@, 'Koha::Exceptions::Patron::MessagePreference::TalkingTechItivaPhoneNotificationRequired', + . ' => Koha::Exceptions::Patron::MessagePreference::EmailAddressRequired' + ); + is( + $@->message_name, $preference->message_name, + 'The previous exception ' . ' tells us it which message name it was.' + ); + is( $@->borrowernumber, $patron->borrowernumber, 'The previous exception ' . ' tells us which patron it was.' ); + eval { $preference->message_transport_types('itiva')->store; }; + is( + ref $@, 'Koha::Exceptions::Patron::MessagePreference::TalkingTechItivaPhoneNotificationRequired', 'Adding a message preference with invalid message_transport_type' - .' => Koha::Exceptions::Patron::MessagePreference::TalkingTechItivaPhoneNotificationRequired'); - is ($@->message_name, $preference->message_name, 'The previous exception ' - .' tells us it which message name it was.'); - is ($@->borrowernumber, $patron->borrowernumber, 'The previous exception ' - .' tells us which patron it was.'); - eval { - $preference->message_transport_types('phone')->store; - }; - is (ref $@, 'Koha::Exceptions::Patron::MessagePreference::PhoneNumberRequired', + . ' => Koha::Exceptions::Patron::MessagePreference::TalkingTechItivaPhoneNotificationRequired' + ); + is( + $@->message_name, $preference->message_name, + 'The previous exception ' . ' tells us it which message name it was.' + ); + is( $@->borrowernumber, $patron->borrowernumber, 'The previous exception ' . ' tells us which patron it was.' ); + eval { $preference->message_transport_types('phone')->store; }; + is( + ref $@, 'Koha::Exceptions::Patron::MessagePreference::PhoneNumberRequired', 'Adding a message preference with invalid message_transport_type' - .' => Koha::Exceptions::Patron::MessagePreference::PhoneNumberRequired'); - is ($@->message_name, $preference->message_name, 'The previous exception ' - .' tells us it which message name it was.'); - is ($@->borrowernumber, $patron->borrowernumber, 'The previous exception ' - .' tells us which patron it was.'); - eval { - $preference->message_transport_types('sms')->store; - }; - is (ref $@, 'Koha::Exceptions::Patron::MessagePreference::SMSNumberRequired', + . ' => Koha::Exceptions::Patron::MessagePreference::PhoneNumberRequired' + ); + is( + $@->message_name, $preference->message_name, + 'The previous exception ' . ' tells us it which message name it was.' + ); + is( $@->borrowernumber, $patron->borrowernumber, 'The previous exception ' . ' tells us which patron it was.' ); + eval { $preference->message_transport_types('sms')->store; }; + is( + ref $@, 'Koha::Exceptions::Patron::MessagePreference::SMSNumberRequired', 'Adding a message preference with invalid message_transport_type' - .' => Koha::Exceptions::Patron::MessagePreference::SMSNumberRequired'); - is ($@->message_name, $preference->message_name, 'The previous exception ' - .' tells us it which message name it was.'); - is ($@->borrowernumber, $patron->borrowernumber, 'The previous exception ' - .' tells us which patron it was.'); + . ' => Koha::Exceptions::Patron::MessagePreference::SMSNumberRequired' + ); + is( + $@->message_name, $preference->message_name, + 'The previous exception ' . ' tells us it which message name it was.' + ); + is( $@->borrowernumber, $patron->borrowernumber, 'The previous exception ' . ' tells us which patron it was.' ); $schema->storage->txn_rollback; }; @@ -423,31 +520,44 @@ HERE $schema->storage->txn_begin; - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $letter = build_a_test_letter(); - my $attribute = $builder->build_object({ class => 'Koha::Patron::MessagePreference::Attributes' }); - my $mtt = $builder->build_object({ class => 'Koha::Patron::MessagePreference::Transport::Types' }); - Koha::Patron::MessagePreference::Transport->new({ - message_attribute_id => $attribute->message_attribute_id, - message_transport_type => $mtt->message_transport_type, - is_digest => 0, - letter_module => $letter->module, - letter_code => $letter->code, - })->store; - ok(my $preference = Koha::Patron::MessagePreference->new({ - borrowernumber => $patron->borrowernumber, - message_attribute_id => $attribute->message_attribute_id, - wants_digest => 0, - days_in_advance => undef, - message_transport_types => $mtt->message_transport_type, - })->store, 'Added a new messaging preference and transport types to patron.'); - ok($preference->message_transport_types->{$mtt->message_transport_type}, - 'The transport type is stored in the object.'); - my $stored_transports = Koha::Patron::MessagePreference::Transport::Preferences->search({ - borrower_message_preference_id => $preference->borrower_message_preference_id, - }); - is($stored_transports->next->message_transport_type, $mtt->message_transport_type, - 'The transport type is stored in the database.'); + my $attribute = $builder->build_object( { class => 'Koha::Patron::MessagePreference::Attributes' } ); + my $mtt = $builder->build_object( { class => 'Koha::Patron::MessagePreference::Transport::Types' } ); + Koha::Patron::MessagePreference::Transport->new( + { + message_attribute_id => $attribute->message_attribute_id, + message_transport_type => $mtt->message_transport_type, + is_digest => 0, + letter_module => $letter->module, + letter_code => $letter->code, + } + )->store; + ok( + my $preference = Koha::Patron::MessagePreference->new( + { + borrowernumber => $patron->borrowernumber, + message_attribute_id => $attribute->message_attribute_id, + wants_digest => 0, + days_in_advance => undef, + message_transport_types => $mtt->message_transport_type, + } + )->store, + 'Added a new messaging preference and transport types to patron.' + ); + ok( + $preference->message_transport_types->{ $mtt->message_transport_type }, + 'The transport type is stored in the object.' + ); + my $stored_transports = Koha::Patron::MessagePreference::Transport::Preferences->search( + { + borrower_message_preference_id => $preference->borrower_message_preference_id, + } + ); + is( + $stored_transports->next->message_transport_type, $mtt->message_transport_type, + 'The transport type is stored in the database.' + ); $schema->storage->txn_rollback; }; @@ -458,17 +568,21 @@ subtest 'Test Koha::Patron::MessagePreference->message_name' => sub { $schema->storage->txn_begin; - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); - my $attribute = $builder->build_object({ class => 'Koha::Patron::MessagePreference::Attributes' }); - my ($preference, $mtt1, $mtt2) = build_a_test_complete_preference({ - patron => $patron, - attr => $attribute, - }); - my $message_name_pref = Koha::Patron::MessagePreferences->search_with_message_name({ - borrowernumber => $patron->{'borrowernumber'}, - message_name => $attribute->message_name, - })->next; - is($message_name_pref->message_name, $attribute->message_name, "Found preference with message_name"); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + my $attribute = $builder->build_object( { class => 'Koha::Patron::MessagePreference::Attributes' } ); + my ( $preference, $mtt1, $mtt2 ) = build_a_test_complete_preference( + { + patron => $patron, + attr => $attribute, + } + ); + my $message_name_pref = Koha::Patron::MessagePreferences->search_with_message_name( + { + borrowernumber => $patron->{'borrowernumber'}, + message_name => $attribute->message_name, + } + )->next; + is( $message_name_pref->message_name, $attribute->message_name, "Found preference with message_name" ); $schema->storage->txn_rollback; }; @@ -478,75 +592,75 @@ subtest 'Test Koha::Patron::MessagePreference->mtt_deliverable' => sub { $schema->storage->txn_begin; - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); - my ($preference, $mtt1, $mtt2) = build_a_test_complete_preference({ - patron => $patron - }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + my ( $preference, $mtt1, $mtt2 ) = build_a_test_complete_preference( { patron => $patron } ); # Test email and smsalertnumber validation - eval { Koha::Patron::MessagePreference::Transport::Types->new({ - message_transport_type => 'email' - })->store }; - eval { Koha::Patron::MessagePreference::Transport::Types->new({ - message_transport_type => 'sms' - })->store }; - eval { Koha::Patron::MessagePreference::Transport::Types->new({ - message_transport_type => 'phone' - })->store }; - eval { Koha::Patron::MessagePreference::Transport::Types->new({ - message_transport_type => 'itiva' - })->store }; - Koha::Patron::MessagePreference::Transport->new({ - message_attribute_id => $preference->message_attribute_id, - message_transport_type => 'email', - is_digest => 1 - })->store; - Koha::Patron::MessagePreference::Transport->new({ - message_attribute_id => $preference->message_attribute_id, - message_transport_type => 'sms', - is_digest => 1 - })->store; - Koha::Patron::MessagePreference::Transport->new({ - message_attribute_id => $preference->message_attribute_id, - message_transport_type => 'phone', - is_digest => 1 - })->store; - Koha::Patron::MessagePreference::Transport->new({ - message_attribute_id => $preference->message_attribute_id, - message_transport_type => 'itiva', - is_digest => 1 - })->store; - $patron->set({ - email => 'nobody@koha-community.org', - emailpro => 'nobody@koha-community.org', - B_email => 'nobody@koha-community.org', - smsalertnumber => '123', - phone => '123', - })->store; - t::lib::Mocks::mock_preference('TalkingTechItivaPhoneNotification', 1); + eval { Koha::Patron::MessagePreference::Transport::Types->new( { message_transport_type => 'email' } )->store }; + eval { Koha::Patron::MessagePreference::Transport::Types->new( { message_transport_type => 'sms' } )->store }; + eval { Koha::Patron::MessagePreference::Transport::Types->new( { message_transport_type => 'phone' } )->store }; + eval { Koha::Patron::MessagePreference::Transport::Types->new( { message_transport_type => 'itiva' } )->store }; + Koha::Patron::MessagePreference::Transport->new( + { + message_attribute_id => $preference->message_attribute_id, + message_transport_type => 'email', + is_digest => 1 + } + )->store; + Koha::Patron::MessagePreference::Transport->new( + { + message_attribute_id => $preference->message_attribute_id, + message_transport_type => 'sms', + is_digest => 1 + } + )->store; + Koha::Patron::MessagePreference::Transport->new( + { + message_attribute_id => $preference->message_attribute_id, + message_transport_type => 'phone', + is_digest => 1 + } + )->store; + Koha::Patron::MessagePreference::Transport->new( + { + message_attribute_id => $preference->message_attribute_id, + message_transport_type => 'itiva', + is_digest => 1 + } + )->store; + $patron->set( + { + email => 'nobody@koha-community.org', + emailpro => 'nobody@koha-community.org', + B_email => 'nobody@koha-community.org', + smsalertnumber => '123', + phone => '123', + } + )->store; + t::lib::Mocks::mock_preference( 'TalkingTechItivaPhoneNotification', 1 ); - is($preference->mtt_deliverable('email'), 1, 'mtt_deliverable - email'); - is($preference->mtt_deliverable('itiva'), 1, 'mtt_deliverable - itiva'); - is($preference->mtt_deliverable('phone'), 1, 'mtt_deliverable - phone'); - is($preference->mtt_deliverable('sms'), 1, 'mtt_deliverable - sms'); + is( $preference->mtt_deliverable('email'), 1, 'mtt_deliverable - email' ); + is( $preference->mtt_deliverable('itiva'), 1, 'mtt_deliverable - itiva' ); + is( $preference->mtt_deliverable('phone'), 1, 'mtt_deliverable - phone' ); + is( $preference->mtt_deliverable('sms'), 1, 'mtt_deliverable - sms' ); - $patron->set({email => '',})->store; - is($preference->mtt_deliverable('email'), 1, 'mtt_deliverable - emailpro'); + $patron->set( { email => '', } )->store; + is( $preference->mtt_deliverable('email'), 1, 'mtt_deliverable - emailpro' ); - $patron->set({emailpro => '',})->store; - is($preference->mtt_deliverable('email'), 1, 'mtt_deliverable - B_email'); + $patron->set( { emailpro => '', } )->store; + is( $preference->mtt_deliverable('email'), 1, 'mtt_deliverable - B_email' ); - $patron->set({B_email => '',})->store; - is($preference->mtt_deliverable('email'), 0, 'mtt_deliverable - email false'); + $patron->set( { B_email => '', } )->store; + is( $preference->mtt_deliverable('email'), 0, 'mtt_deliverable - email false' ); - t::lib::Mocks::mock_preference('TalkingTechItivaPhoneNotification', 0); - is($preference->mtt_deliverable('itiva'), 0, 'mtt_deliverable - itiva false'); + t::lib::Mocks::mock_preference( 'TalkingTechItivaPhoneNotification', 0 ); + is( $preference->mtt_deliverable('itiva'), 0, 'mtt_deliverable - itiva false' ); - $patron->set({phone => '',})->store; - is($preference->mtt_deliverable('phone'), 0, 'mtt_deliverable - phone false'); + $patron->set( { phone => '', } )->store; + is( $preference->mtt_deliverable('phone'), 0, 'mtt_deliverable - phone false' ); - $patron->set({smsalertnumber => '',})->store; - is($preference->mtt_deliverable('sms'), 0, 'mtt_deliverable - smsalertnumber false'); + $patron->set( { smsalertnumber => '', } )->store; + is( $preference->mtt_deliverable('sms'), 0, 'mtt_deliverable - smsalertnumber false' ); $schema->storage->txn_rollback; }; @@ -558,9 +672,10 @@ subtest 'Test adding a new preference with invalid parameters' => sub { plan tests => 1; eval { Koha::Patron::MessagePreference->new->store }; - is(ref $@, 'Koha::Exceptions::MissingParameter', - 'Adding a message preference without parameters' - .' => Koha::Exceptions::MissingParameter'); + is( + ref $@, 'Koha::Exceptions::MissingParameter', + 'Adding a message preference without parameters' . ' => Koha::Exceptions::MissingParameter' + ); }; subtest 'Too many parameters' => sub { @@ -568,14 +683,20 @@ subtest 'Test adding a new preference with invalid parameters' => sub { $schema->storage->txn_begin; - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); - eval { Koha::Patron::MessagePreference->new({ - borrowernumber => $patron->borrowernumber, - categorycode => $patron->categorycode, - })->store }; - is(ref $@, 'Koha::Exceptions::TooManyParameters', + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + eval { + Koha::Patron::MessagePreference->new( + { + borrowernumber => $patron->borrowernumber, + categorycode => $patron->categorycode, + } + )->store; + }; + is( + ref $@, 'Koha::Exceptions::TooManyParameters', 'Adding a message preference for both borrowernumber and categorycode' - .' => Koha::Exceptions::TooManyParameters'); + . ' => Koha::Exceptions::TooManyParameters' + ); $schema->storage->txn_rollback; }; @@ -585,114 +706,166 @@ subtest 'Test adding a new preference with invalid parameters' => sub { $schema->storage->txn_begin; - eval { Koha::Patron::MessagePreference->new({ - borrowernumber => -999, - })->store }; - is(ref $@, 'Koha::Exceptions::Patron::NotFound', - 'Adding a message preference with invalid borrowernumber' - .' => Koha::Exceptions::Patron::NotFound'); + eval { + Koha::Patron::MessagePreference->new( + { + borrowernumber => -999, + } + )->store; + }; + is( + ref $@, 'Koha::Exceptions::Patron::NotFound', + 'Adding a message preference with invalid borrowernumber' . ' => Koha::Exceptions::Patron::NotFound' + ); - eval { Koha::Patron::MessagePreference->new({ - categorycode => 'nonexistent', - })->store }; - is(ref $@, 'Koha::Exceptions::Patron::Category::NotFound', + eval { + Koha::Patron::MessagePreference->new( + { + categorycode => 'nonexistent', + } + )->store; + }; + is( + ref $@, 'Koha::Exceptions::Patron::Category::NotFound', 'Adding a message preference with invalid categorycode' - .' => Koha::Exceptions::Patron::Category::NotFound'); + . ' => Koha::Exceptions::Patron::Category::NotFound' + ); - my $attribute = build_a_test_attribute({ takes_days => 0 }); - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); - eval { Koha::Patron::MessagePreference->new({ - borrowernumber => $patron->borrowernumber, - message_attribute_id => $attribute->message_attribute_id, - days_in_advance => 10, - })->store }; - is(ref $@, 'Koha::Exceptions::Patron::MessagePreference::DaysInAdvanceNotAvailable', + my $attribute = build_a_test_attribute( { takes_days => 0 } ); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + eval { + Koha::Patron::MessagePreference->new( + { + borrowernumber => $patron->borrowernumber, + message_attribute_id => $attribute->message_attribute_id, + days_in_advance => 10, + } + )->store; + }; + is( + ref $@, 'Koha::Exceptions::Patron::MessagePreference::DaysInAdvanceNotAvailable', 'Adding a message preference with days in advance option when not' - .' available => Koha::Exceptions::Patron::MessagePreference::DaysInAdvanceNotAvailable'); + . ' available => Koha::Exceptions::Patron::MessagePreference::DaysInAdvanceNotAvailable' + ); - $attribute->set({ takes_days => 1 })->store; - eval { Koha::Patron::MessagePreference->new({ - borrowernumber => $patron->borrowernumber, - message_attribute_id => $attribute->message_attribute_id, - days_in_advance => -1, - })->store }; - is(ref $@, 'Koha::Exceptions::Patron::MessagePreference::DaysInAdvanceOutOfRange', - 'Adding a message preference with days in advance option is out of range' - .' => Koha::Exceptions::Patron::MessagePreference::DaysInAdvanceOutOfRange'); - is ($@->min, 0, 'The previous exception min value is 0.'); - - eval { Koha::Patron::MessagePreference->new({ - borrowernumber => $patron->borrowernumber, - message_attribute_id => $attribute->message_attribute_id, - days_in_advance => 31, - })->store }; - is(ref $@, 'Koha::Exceptions::Patron::MessagePreference::DaysInAdvanceOutOfRange', - 'Adding a message preference with days in advance option is out of range' - .' => Koha::Exceptions::Patron::MessagePreference::DaysInAdvanceOutOfRange'); - is ($@->max, 30, 'The previous exception max value is 30.'); - - eval { Koha::Patron::MessagePreference->new({ - borrowernumber => $patron->borrowernumber, - message_transport_types => ['nonexistent'] - })->store }; - is (ref $@, 'Koha::Exceptions::Patron::MessagePreference::Transport::TypeNotFound', - 'Adding a message preference with invalid message_transport_type' - .' => Koha::Exceptions::Patron::MessagePreference::Transport::TypeNotFound'); - is ($@->transport_type, 'nonexistent', 'The previous exception ' - .'tells us it which transport type it was.'); - - my $mtt_new = $builder->build_object({ class => 'Koha::Patron::MessagePreference::Transport::Types' }); + $attribute->set( { takes_days => 1 } )->store; eval { - Koha::Patron::MessagePreference->new({ - borrowernumber => $patron->borrowernumber, - message_attribute_id => $attribute->message_attribute_id, - message_transport_types => [$mtt_new->message_transport_type], - wants_digest => 1, - })->store }; - is (ref $@, 'Koha::Exceptions::Patron::MessagePreference::NoTransportType', - 'Adding a message preference with invalid message_transport_type' - .' => Koha::Exceptions::Patron::MessagePreference::NoTransportType'); - is ($@->message_name, $attribute->message_name, 'The previous exception ' - .'tells us which message it was.'); - is ($@->transport_type, $mtt_new->message_transport_type, 'The previous exception ' - .'tells us which message transport type it was.'); + Koha::Patron::MessagePreference->new( + { + borrowernumber => $patron->borrowernumber, + message_attribute_id => $attribute->message_attribute_id, + days_in_advance => -1, + } + )->store; + }; + is( + ref $@, 'Koha::Exceptions::Patron::MessagePreference::DaysInAdvanceOutOfRange', + 'Adding a message preference with days in advance option is out of range' + . ' => Koha::Exceptions::Patron::MessagePreference::DaysInAdvanceOutOfRange' + ); + is( $@->min, 0, 'The previous exception min value is 0.' ); eval { - Koha::Patron::MessagePreference->new({ - borrowernumber => $patron->borrowernumber, - message_attribute_id => $attribute->message_attribute_id, - message_transport_types => [], - wants_digest => 1, - })->store }; - is (ref $@, 'Koha::Exceptions::Patron::MessagePreference::DigestNotAvailable', + Koha::Patron::MessagePreference->new( + { + borrowernumber => $patron->borrowernumber, + message_attribute_id => $attribute->message_attribute_id, + days_in_advance => 31, + } + )->store; + }; + is( + ref $@, 'Koha::Exceptions::Patron::MessagePreference::DaysInAdvanceOutOfRange', + 'Adding a message preference with days in advance option is out of range' + . ' => Koha::Exceptions::Patron::MessagePreference::DaysInAdvanceOutOfRange' + ); + is( $@->max, 30, 'The previous exception max value is 30.' ); + + eval { + Koha::Patron::MessagePreference->new( + { + borrowernumber => $patron->borrowernumber, + message_transport_types => ['nonexistent'] + } + )->store; + }; + is( + ref $@, 'Koha::Exceptions::Patron::MessagePreference::Transport::TypeNotFound', + 'Adding a message preference with invalid message_transport_type' + . ' => Koha::Exceptions::Patron::MessagePreference::Transport::TypeNotFound' + ); + is( $@->transport_type, 'nonexistent', 'The previous exception ' . 'tells us it which transport type it was.' ); + + my $mtt_new = $builder->build_object( { class => 'Koha::Patron::MessagePreference::Transport::Types' } ); + eval { + Koha::Patron::MessagePreference->new( + { + borrowernumber => $patron->borrowernumber, + message_attribute_id => $attribute->message_attribute_id, + message_transport_types => [ $mtt_new->message_transport_type ], + wants_digest => 1, + } + )->store; + }; + is( + ref $@, 'Koha::Exceptions::Patron::MessagePreference::NoTransportType', + 'Adding a message preference with invalid message_transport_type' + . ' => Koha::Exceptions::Patron::MessagePreference::NoTransportType' + ); + is( $@->message_name, $attribute->message_name, 'The previous exception ' . 'tells us which message it was.' ); + is( + $@->transport_type, $mtt_new->message_transport_type, + 'The previous exception ' . 'tells us which message transport type it was.' + ); + + eval { + Koha::Patron::MessagePreference->new( + { + borrowernumber => $patron->borrowernumber, + message_attribute_id => $attribute->message_attribute_id, + message_transport_types => [], + wants_digest => 1, + } + )->store; + }; + is( + ref $@, 'Koha::Exceptions::Patron::MessagePreference::DigestNotAvailable', 'Adding a message preference that has no digest setting' - .' => Koha::Exceptions::Patron::MessagePreference::DigestNotAvailable'); - is ($@->message_name, $attribute->message_name, 'The previous exception tells us' - .' which message it was'); + . ' => Koha::Exceptions::Patron::MessagePreference::DigestNotAvailable' + ); + is( $@->message_name, $attribute->message_name, 'The previous exception tells us' . ' which message it was' ); eval { - Koha::Patron::MessagePreference->new({ - borrowernumber => $patron->borrowernumber, - message_attribute_id => $attribute->message_attribute_id, - message_transport_types => [], - wants_digest => 0, - })->store }; - is (ref $@, 'Koha::Exceptions::Patron::MessagePreference::DigestRequired', + Koha::Patron::MessagePreference->new( + { + borrowernumber => $patron->borrowernumber, + message_attribute_id => $attribute->message_attribute_id, + message_transport_types => [], + wants_digest => 0, + } + )->store; + }; + is( + ref $@, 'Koha::Exceptions::Patron::MessagePreference::DigestRequired', 'Adding a message preference, that requires digest, with no digest' - .' => Koha::Exceptions::Patron::MessagePreference::DigestRequired'); - is ($@->message_name, $attribute->message_name, 'The previous exception tells us' - .' which message it was'); + . ' => Koha::Exceptions::Patron::MessagePreference::DigestRequired' + ); + is( $@->message_name, $attribute->message_name, 'The previous exception tells us' . ' which message it was' ); eval { - Koha::Patron::MessagePreference->new({ - borrowernumber => $patron->borrowernumber, - message_attribute_id => -1, - message_transport_types => [], - })->store }; - is (ref $@, 'Koha::Exceptions::Patron::MessagePreference::AttributeNotFound', + Koha::Patron::MessagePreference->new( + { + borrowernumber => $patron->borrowernumber, + message_attribute_id => -1, + message_transport_types => [], + } + )->store; + }; + is( + ref $@, 'Koha::Exceptions::Patron::MessagePreference::AttributeNotFound', 'Adding a message preference with invalid message_transport_type' - .' => KKoha::Exceptions::Patron::MessagePreference::AttributeNotFound'); - is ($@->message_attribute_id, -1, 'The previous exception tells' - .' us which message attribute id it was.'); + . ' => KKoha::Exceptions::Patron::MessagePreference::AttributeNotFound' + ); + is( $@->message_attribute_id, -1, 'The previous exception tells' . ' us which message attribute id it was.' ); $schema->storage->txn_rollback; }; @@ -702,34 +875,45 @@ subtest 'Test adding a new preference with invalid parameters' => sub { $schema->storage->txn_begin; - my $attribute = $builder->build_object({ class => 'Koha::Patron::MessagePreference::Attributes' }); - my $letter = build_a_test_letter(); - my $mtt = $builder->build_object({ class => 'Koha::Patron::MessagePreference::Transport::Types' }); - Koha::Patron::MessagePreference::Transport->new({ - message_attribute_id => $attribute->message_attribute_id, - message_transport_type => $mtt->message_transport_type, - is_digest => 0, - letter_module => $letter->module, - letter_code => $letter->code, - })->store; - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); - my $preference = Koha::Patron::MessagePreference->new({ - borrowernumber => $patron->borrowernumber, - message_attribute_id => $attribute->message_attribute_id, - wants_digest => 0, - days_in_advance => undef, - })->store; - ok($preference->borrower_message_preference_id, - 'Added a new messaging preference for patron.'); - eval { Koha::Patron::MessagePreference->new({ - borrowernumber => $patron->borrowernumber, - message_attribute_id => $attribute->message_attribute_id, - wants_digest => 0, - days_in_advance => undef, - })->store }; - is(ref $@, 'Koha::Exceptions::DuplicateObject', - 'Adding a duplicate preference' - .' => Koha::Exceptions::DuplicateObject'); + my $attribute = $builder->build_object( { class => 'Koha::Patron::MessagePreference::Attributes' } ); + my $letter = build_a_test_letter(); + my $mtt = $builder->build_object( { class => 'Koha::Patron::MessagePreference::Transport::Types' } ); + Koha::Patron::MessagePreference::Transport->new( + { + message_attribute_id => $attribute->message_attribute_id, + message_transport_type => $mtt->message_transport_type, + is_digest => 0, + letter_module => $letter->module, + letter_code => $letter->code, + } + )->store; + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + my $preference = Koha::Patron::MessagePreference->new( + { + borrowernumber => $patron->borrowernumber, + message_attribute_id => $attribute->message_attribute_id, + wants_digest => 0, + days_in_advance => undef, + } + )->store; + ok( + $preference->borrower_message_preference_id, + 'Added a new messaging preference for patron.' + ); + eval { + Koha::Patron::MessagePreference->new( + { + borrowernumber => $patron->borrowernumber, + message_attribute_id => $attribute->message_attribute_id, + wants_digest => 0, + days_in_advance => undef, + } + )->store; + }; + is( + ref $@, 'Koha::Exceptions::DuplicateObject', + 'Adding a duplicate preference' . ' => Koha::Exceptions::DuplicateObject' + ); $schema->storage->txn_rollback; }; @@ -738,103 +922,122 @@ subtest 'Test adding a new preference with invalid parameters' => sub { sub build_a_test_attribute { my ($params) = @_; - $params->{takes_days} = $params->{takes_days} && $params->{takes_days} > 0 - ? 1 : 0; + $params->{takes_days} = $params->{takes_days} && $params->{takes_days} > 0 ? 1 : 0; - my $attribute = $builder->build({ - source => 'MessageAttribute', - value => $params, - }); - - return Koha::Patron::MessagePreference::Attributes->find( - $attribute->{message_attribute_id} + my $attribute = $builder->build( + { + source => 'MessageAttribute', + value => $params, + } ); + + return Koha::Patron::MessagePreference::Attributes->find( $attribute->{message_attribute_id} ); } sub build_a_test_letter { my ($params) = @_; - my $mtt = $params->{mtt} ? $params->{mtt} : 'email'; - my $branchcode = $builder->build({ - source => 'Branch' })->{branchcode}; - my $letter = $builder->build({ - source => 'Letter', - value => { - branchcode => '', - is_html => 0, - message_transport_type => $mtt + my $mtt = $params->{mtt} ? $params->{mtt} : 'email'; + my $branchcode = $builder->build( { source => 'Branch' } )->{branchcode}; + my $letter = $builder->build( + { + source => 'Letter', + value => { + branchcode => '', + is_html => 0, + message_transport_type => $mtt + } } - }); + ); - return Koha::Notice::Templates->find({ - module => $letter->{module}, - code => $letter->{code}, - branchcode => $letter->{branchcode}, - }); + return Koha::Notice::Templates->find( + { + module => $letter->{module}, + code => $letter->{code}, + branchcode => $letter->{branchcode}, + } + ); } sub build_a_test_category_preference { my ($params) = @_; my $patron = $params->{patron}; - my $attr = $params->{attr} - ? $params->{attr} - : build_a_test_attribute($params->{days_in_advance}); + my $attr = + $params->{attr} + ? $params->{attr} + : build_a_test_attribute( $params->{days_in_advance} ); my $letter = $params->{letter} ? $params->{letter} : build_a_test_letter(); - my $mtt1 = $params->{mtt1} ? $params->{mtt1} : $builder->build_object({ class => 'Koha::Patron::MessagePreference::Transport::Types' }); - my $mtt2 = $params->{mtt2} ? $params->{mtt2} : $builder->build_object({ class => 'Koha::Patron::MessagePreference::Transport::Types' }); + my $mtt1 = + $params->{mtt1} + ? $params->{mtt1} + : $builder->build_object( { class => 'Koha::Patron::MessagePreference::Transport::Types' } ); + my $mtt2 = + $params->{mtt2} + ? $params->{mtt2} + : $builder->build_object( { class => 'Koha::Patron::MessagePreference::Transport::Types' } ); - Koha::Patron::MessagePreference::Transport->new({ - message_attribute_id => $attr->message_attribute_id, - message_transport_type => $mtt1->message_transport_type, - is_digest => $params->{digest} ? 1 : 0, - letter_module => $letter->module, - letter_code => $letter->code, - })->store; + Koha::Patron::MessagePreference::Transport->new( + { + message_attribute_id => $attr->message_attribute_id, + message_transport_type => $mtt1->message_transport_type, + is_digest => $params->{digest} ? 1 : 0, + letter_module => $letter->module, + letter_code => $letter->code, + } + )->store; - Koha::Patron::MessagePreference::Transport->new({ - message_attribute_id => $attr->message_attribute_id, - message_transport_type => $mtt2->message_transport_type, - is_digest => $params->{digest} ? 1 : 0, - letter_module => $letter->module, - letter_code => $letter->code, - })->store; + Koha::Patron::MessagePreference::Transport->new( + { + message_attribute_id => $attr->message_attribute_id, + message_transport_type => $mtt2->message_transport_type, + is_digest => $params->{digest} ? 1 : 0, + letter_module => $letter->module, + letter_code => $letter->code, + } + )->store; - my $default = Koha::Patron::MessagePreference->new({ - categorycode => $patron->categorycode, - message_attribute_id => $attr->message_attribute_id, - wants_digest => $params->{digest} ? 1 : 0, - days_in_advance => $params->{days_in_advance} - ? $params->{days_in_advance} : undef, - })->store; + my $default = Koha::Patron::MessagePreference->new( + { + categorycode => $patron->categorycode, + message_attribute_id => $attr->message_attribute_id, + wants_digest => $params->{digest} ? 1 : 0, + days_in_advance => $params->{days_in_advance} ? $params->{days_in_advance} : undef, + } + )->store; - Koha::Patron::MessagePreference::Transport::Preference->new({ - borrower_message_preference_id => $default->borrower_message_preference_id, - message_transport_type => $mtt1->message_transport_type, - })->store; - Koha::Patron::MessagePreference::Transport::Preference->new({ - borrower_message_preference_id => $default->borrower_message_preference_id, - message_transport_type => $mtt2->message_transport_type, - })->store; + Koha::Patron::MessagePreference::Transport::Preference->new( + { + borrower_message_preference_id => $default->borrower_message_preference_id, + message_transport_type => $mtt1->message_transport_type, + } + )->store; + Koha::Patron::MessagePreference::Transport::Preference->new( + { + borrower_message_preference_id => $default->borrower_message_preference_id, + message_transport_type => $mtt2->message_transport_type, + } + )->store; - return ($default, $mtt1, $mtt2); + return ( $default, $mtt1, $mtt2 ); } sub build_a_test_complete_preference { my ($params) = @_; - my ($default, $mtt1, $mtt2) = build_a_test_category_preference($params); + my ( $default, $mtt1, $mtt2 ) = build_a_test_category_preference($params); my $patron = $params->{patron}; $patron->set_default_messaging_preferences; - return (Koha::Patron::MessagePreferences->search({ - borrowernumber => $patron->borrowernumber - })->next, $mtt1, $mtt2); + return ( + Koha::Patron::MessagePreferences->search( { borrowernumber => $patron->borrowernumber } )->next, $mtt1, + $mtt2 + ); } sub mytempfile { my ( $fh, $fn ) = tempfile( SUFFIX => '.logger.test', UNLINK => 1 ); - print $fh $_[0]//''; + print $fh $_[0] // ''; close $fh; return $fn; } diff --git a/t/db_dependent/Koha/Patron/Messages.t b/t/db_dependent/Koha/Patron/Messages.t index 31f8cf92b4..0ce23763dd 100755 --- a/t/db_dependent/Koha/Patron/Messages.t +++ b/t/db_dependent/Koha/Patron/Messages.t @@ -35,17 +35,18 @@ use t::lib::TestBuilder; my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; -my $builder = t::lib::TestBuilder->new; -my $library = $builder->build( { source => 'Branch' } ); -my $patron = $builder->build( { source => 'Borrower', value => { branchcode => $library->{branchcode} } } ); -my $patron_2 = $builder->build( { source => 'Borrower' } ); -my $patron_3 = $builder->build( { source => 'Borrower' } ); +my $builder = t::lib::TestBuilder->new; +my $library = $builder->build( { source => 'Branch' } ); +my $patron = $builder->build( { source => 'Borrower', value => { branchcode => $library->{branchcode} } } ); +my $patron_2 = $builder->build( { source => 'Borrower' } ); +my $patron_3 = $builder->build( { source => 'Borrower' } ); my $nb_of_logaction = get_nb_of_logactions(); -my $nb_of_messages = Koha::Patron::Messages->search->count; +my $nb_of_messages = Koha::Patron::Messages->search->count; -t::lib::Mocks::mock_preference('BorrowersLog', 0); -my $new_message_1 = Koha::Patron::Message->new( - { borrowernumber => $patron->{borrowernumber}, +t::lib::Mocks::mock_preference( 'BorrowersLog', 0 ); +my $new_message_1 = Koha::Patron::Message->new( + { + borrowernumber => $patron->{borrowernumber}, branchcode => $library->{branchcode}, message_type => 'L', message => 'my message 1', @@ -54,69 +55,93 @@ my $new_message_1 = Koha::Patron::Message->new( is( get_nb_of_logactions(), $nb_of_logaction, 'With BorrowersLog off, no new log should have been added' ); my $context = Test::MockModule->new('C4::Context'); -$context->mock( 'userenv', sub { - return { - number => $patron_2->{borrowernumber}, - }; -}); +$context->mock( + 'userenv', + sub { + return { + number => $patron_2->{borrowernumber}, + }; + } +); -t::lib::Mocks::mock_preference('BorrowersLog', 1); -my $new_message_2 = Koha::Patron::Message->new( - { borrowernumber => $patron->{borrowernumber}, +t::lib::Mocks::mock_preference( 'BorrowersLog', 1 ); +my $new_message_2 = Koha::Patron::Message->new( + { + borrowernumber => $patron->{borrowernumber}, branchcode => $library->{branchcode}, message_type => 'B', message => 'my message 2', } )->store; -my $new_message_3 = Koha::Patron::Message->new( - { borrowernumber => $patron->{borrowernumber}, +my $new_message_3 = Koha::Patron::Message->new( + { + borrowernumber => $patron->{borrowernumber}, branchcode => $library->{branchcode}, message_type => 'B', message => 'my message 2', manager_id => $patron_3->{borrowernumber}, } )->store; -is( get_nb_of_logactions(), $nb_of_logaction + 2, 'With BorrowersLog on, 2 new log should have been added when adding a new message' ); +is( + get_nb_of_logactions(), $nb_of_logaction + 2, + 'With BorrowersLog on, 2 new log should have been added when adding a new message' +); -like( $new_message_1->message_id, qr|^\d+$|, 'Adding a new message should have set the message_id'); +like( $new_message_1->message_id, qr|^\d+$|, 'Adding a new message should have set the message_id' ); is( Koha::Patron::Messages->search->count, $nb_of_messages + 3, 'The 3 messages should have been added' ); my $retrieved_message_1 = Koha::Patron::Messages->find( $new_message_1->message_id ); is( $retrieved_message_1->message, $new_message_1->message, 'Find a message by id should return the correct message' ); is( $retrieved_message_1->manager_id, undef, 'Manager id should not be filled in when it is not defined in userenv' ); my $retrieved_message_2 = Koha::Patron::Messages->find( $new_message_2->message_id ); -is( $retrieved_message_2->manager_id, $patron_2->{borrowernumber}, 'Manager id should be filled in when it is defined in userenv' ); +is( + $retrieved_message_2->manager_id, $patron_2->{borrowernumber}, + 'Manager id should be filled in when it is defined in userenv' +); my $retrieved_message_3 = Koha::Patron::Messages->find( $new_message_3->message_id ); -is( $retrieved_message_3->manager_id, $patron_3->{borrowernumber}, 'Manager id should be overwrite-able even if defined in userenv' ); +is( + $retrieved_message_3->manager_id, $patron_3->{borrowernumber}, + 'Manager id should be overwrite-able even if defined in userenv' +); -t::lib::Mocks::mock_preference('BorrowersLog', 0); +t::lib::Mocks::mock_preference( 'BorrowersLog', 0 ); $retrieved_message_1->delete; is( Koha::Patron::Messages->search->count, $nb_of_messages + 2, 'Delete should have deleted the message 1' ); -is( get_nb_of_logactions(), $nb_of_logaction + 2, 'With BorrowersLog off, no new log should have been added when deleting a new message' ); +is( + get_nb_of_logactions(), $nb_of_logaction + 2, + 'With BorrowersLog off, no new log should have been added when deleting a new message' +); -t::lib::Mocks::mock_preference('BorrowersLog', 1); +t::lib::Mocks::mock_preference( 'BorrowersLog', 1 ); $new_message_2->delete; is( Koha::Patron::Messages->search->count, $nb_of_messages + 1, 'Delete should have deleted the message 2' ); -is( get_nb_of_logactions(), $nb_of_logaction + 3, 'With BorrowersLog on, 1 new log should have been added when deleting a new message' ); +is( + get_nb_of_logactions(), $nb_of_logaction + 3, + 'With BorrowersLog on, 1 new log should have been added when deleting a new message' +); -my $new_message_4 = Koha::Patron::Message->new( - { borrowernumber => $patron->{borrowernumber}, +my $new_message_4 = Koha::Patron::Message->new( + { + borrowernumber => $patron->{borrowernumber}, branchcode => $library->{branchcode}, message_type => 'B', message => 'my message 2', manager_id => $patron_3->{borrowernumber}, } )->store; -my $patron_obj = Koha::Patrons->find( $patron->{borrowernumber} ); +my $patron_obj = Koha::Patrons->find( $patron->{borrowernumber} ); my $current_messages_count = $patron_obj->messages->count; is( $patron_obj->messages->filter_by_unread->count, $current_messages_count, "No messages have been marked as read" ); -$new_message_4->update({ patron_read_date => dt_from_string }); -is( $patron_obj->messages->filter_by_unread->count, $current_messages_count - 1, "One message has been marked as read" ); +$new_message_4->update( { patron_read_date => dt_from_string } ); +is( + $patron_obj->messages->filter_by_unread->count, $current_messages_count - 1, + "One message has been marked as read" +); $schema->storage->txn_rollback; sub get_nb_of_logactions { - return Koha::ActionLogs->search({ module => 'MEMBERS' })->count; + return Koha::ActionLogs->search( { module => 'MEMBERS' } )->count; } diff --git a/t/db_dependent/Koha/Patron/Modifications.t b/t/db_dependent/Koha/Patron/Modifications.t index 4e03a246bd..f430fa452d 100755 --- a/t/db_dependent/Koha/Patron/Modifications.t +++ b/t/db_dependent/Koha/Patron/Modifications.t @@ -51,7 +51,8 @@ subtest 'new() tests' => sub { # Create new pending modification Koha::Patron::Modification->new( - { verification_token => '1234567890', + { + verification_token => '1234567890', changed_fields => 'surname,firstname', surname => 'Hall', firstname => 'Kyle' @@ -59,16 +60,18 @@ subtest 'new() tests' => sub { )->store(); ## Get the new pending modification - my $borrower = Koha::Patron::Modifications->find( - { verification_token => '1234567890' } ); + my $borrower = Koha::Patron::Modifications->find( { verification_token => '1234567890' } ); ## Verify we get the same data - is( $borrower->surname, 'Hall', - 'Found modification has matching surname' ); + is( + $borrower->surname, 'Hall', + 'Found modification has matching surname' + ); throws_ok { Koha::Patron::Modification->new( - { verification_token => '1234567890', + { + verification_token => '1234567890', changed_fields => 'surname,firstname', surname => 'Hall', firstname => 'Daria' @@ -77,7 +80,8 @@ subtest 'new() tests' => sub { } 'Koha::Exceptions::Patron::Modification::DuplicateVerificationToken', 'Attempting to add a duplicate verification raises the correct exception'; - like( "$@", + like( + "$@", qr/Duplicate verification token 1234567890/, 'Exception carries the right message' ); @@ -93,14 +97,14 @@ subtest 'store( extended_attributes ) tests' => sub { Koha::Patron::Modifications->search->delete; - my $patron - = $builder->build( { source => 'Borrower' } )->{borrowernumber}; - my $verification_token = md5_hex( time().{}.rand().{}.$$ ); + my $patron = $builder->build( { source => 'Borrower' } )->{borrowernumber}; + my $verification_token = md5_hex( time() . {} . rand() . {} . $$ ); my $valid_json_text = '[{"code":"CODE","value":"VALUE"}]'; my $invalid_json_text = '[{"code":"CODE";"value":"VALUE"}]'; Koha::Patron::Modification->new( - { verification_token => $verification_token, + { + verification_token => $verification_token, changed_fields => 'borrowernumber,surname,extended_attributes', borrowernumber => $patron, surname => 'Hall', @@ -108,20 +112,23 @@ subtest 'store( extended_attributes ) tests' => sub { } )->store(); - my $patron_modification - = Koha::Patron::Modifications->search( { borrowernumber => $patron } ) - ->next; + my $patron_modification = Koha::Patron::Modifications->search( { borrowernumber => $patron } )->next; - is( $patron_modification->surname, - 'Hall', 'Patron modification correctly stored with valid JSON data' ); - is( $patron_modification->extended_attributes, + is( + $patron_modification->surname, + 'Hall', 'Patron modification correctly stored with valid JSON data' + ); + is( + $patron_modification->extended_attributes, $valid_json_text, - 'Patron modification correctly stored with valid JSON data' ); + 'Patron modification correctly stored with valid JSON data' + ); - $verification_token = md5_hex( time().{}.rand().{}.$$ ); + $verification_token = md5_hex( time() . {} . rand() . {} . $$ ); throws_ok { Koha::Patron::Modification->new( - { verification_token => $verification_token, + { + verification_token => $verification_token, changed_fields => 'borrowernumber,surname,extended_attributes', borrowernumber => $patron, surname => 'Hall', @@ -146,17 +153,13 @@ subtest 'approve tests' => sub { Koha::Patron::Modifications->search->delete; my $patron_hashref = $builder->build( { source => 'Borrower' } ); - $builder->build( - { source => 'BorrowerAttributeType', value => { code => 'CODE_1' } } - ); - $builder->build( - { source => 'BorrowerAttributeType', value => { code => 'CODE_2', repeatable => 1 } } - ); - my $verification_token = md5_hex( time().{}.rand().{}.$$ ); - my $valid_json_text - = '[{"code":"CODE_1","value":"VALUE_1"},{"code":"CODE_2","value":0}]'; + $builder->build( { source => 'BorrowerAttributeType', value => { code => 'CODE_1' } } ); + $builder->build( { source => 'BorrowerAttributeType', value => { code => 'CODE_2', repeatable => 1 } } ); + my $verification_token = md5_hex( time() . {} . rand() . {} . $$ ); + my $valid_json_text = '[{"code":"CODE_1","value":"VALUE_1"},{"code":"CODE_2","value":0}]'; my $patron_modification = Koha::Patron::Modification->new( - { verification_token => $verification_token, + { + verification_token => $verification_token, changed_fields => 'borrowernumber,firstname,extended_attributes', borrowernumber => $patron_hashref->{borrowernumber}, firstname => 'Kyle', @@ -164,32 +167,45 @@ subtest 'approve tests' => sub { } )->store(); - ok( $patron_modification->approve, - 'Patron modification correctly approved' ); + ok( + $patron_modification->approve, + 'Patron modification correctly approved' + ); my $patron = Koha::Patrons->find( $patron_hashref->{borrowernumber} ); isnt( $patron->firstname, $patron_hashref->{firstname}, 'Patron modification changed firstname' ); - is( $patron->firstname, 'Kyle', - 'Patron modification set the right firstname' ); + is( + $patron->firstname, 'Kyle', + 'Patron modification set the right firstname' + ); my $patron_attributes = $patron->extended_attributes; - my $attribute_1 = $patron_attributes->next; - is( $attribute_1->code, - 'CODE_1', 'Patron modification correctly saved attribute code' ); - is( $attribute_1->attribute, - 'VALUE_1', 'Patron modification correctly saved attribute value' ); + my $attribute_1 = $patron_attributes->next; + is( + $attribute_1->code, + 'CODE_1', 'Patron modification correctly saved attribute code' + ); + is( + $attribute_1->attribute, + 'VALUE_1', 'Patron modification correctly saved attribute value' + ); my $attribute_2 = $patron_attributes->next; - is( $attribute_2->code, - 'CODE_2', 'Patron modification correctly saved attribute code' ); - is( $attribute_2->attribute, - 0, 'Patron modification correctly saved attribute with value 0, not confused with delete' ); + is( + $attribute_2->code, + 'CODE_2', 'Patron modification correctly saved attribute code' + ); + is( + $attribute_2->attribute, + 0, 'Patron modification correctly saved attribute with value 0, not confused with delete' + ); # Create a new Koha::Patron::Modification, skip extended_attributes to # bypass checks $patron_modification = Koha::Patron::Modification->new( - { verification_token => $verification_token, + { + verification_token => $verification_token, changed_fields => 'borrowernumber,firstname', borrowernumber => $patron_hashref->{borrowernumber}, firstname => 'Kylie' @@ -197,8 +213,7 @@ subtest 'approve tests' => sub { )->store(); # Add invalid JSON to extended attributes - $patron_modification->extended_attributes( - '[{"code":"CODE";"values:VALUES"}]'); + $patron_modification->extended_attributes('[{"code":"CODE";"values:VALUES"}]'); throws_ok { $patron_modification->approve } 'Koha::Exceptions::Patron::Modification::InvalidData', 'The right exception is thrown if invalid data is on extended_attributes'; @@ -207,63 +222,81 @@ subtest 'approve tests' => sub { isnt( $patron->firstname, 'Kylie', 'Patron modification didn\'t apply' ); # Try changing only a portion of the attributes - my $bigger_json - = '[{"code":"CODE_2","value":"Tomasito"},{"code":"CODE_2","value":"None"}]'; + my $bigger_json = '[{"code":"CODE_2","value":"Tomasito"},{"code":"CODE_2","value":"None"}]'; $verification_token = md5_hex( time() . {} . rand() . {} . $$ ); $patron_modification = Koha::Patron::Modification->new( - { verification_token => $verification_token, + { + verification_token => $verification_token, changed_fields => 'borrowernumber,extended_attributes', borrowernumber => $patron->borrowernumber, extended_attributes => $bigger_json } )->store(); - ok( $patron_modification->approve, - 'Patron modification correctly approved' ); - my @patron_attributes - = map { $_->unblessed } - Koha::Patron::Attributes->search( - { borrowernumber => $patron->borrowernumber } )->as_list; + ok( + $patron_modification->approve, + 'Patron modification correctly approved' + ); + my @patron_attributes = map { $_->unblessed } + Koha::Patron::Attributes->search( { borrowernumber => $patron->borrowernumber } )->as_list; - is( $patron_attributes[0]->{code}, - 'CODE_1', 'Untouched attribute type is preserved (code)' ); - is( $patron_attributes[0]->{attribute}, - 'VALUE_1', 'Untouched attribute type is preserved (attribute)' ); + is( + $patron_attributes[0]->{code}, + 'CODE_1', 'Untouched attribute type is preserved (code)' + ); + is( + $patron_attributes[0]->{attribute}, + 'VALUE_1', 'Untouched attribute type is preserved (attribute)' + ); - is( $patron_attributes[1]->{code}, - 'CODE_2', 'Attribute updated correctly (code)' ); - is( $patron_attributes[1]->{attribute}, - 'None', 'Attribute updated correctly (attribute)' ); + is( + $patron_attributes[1]->{code}, + 'CODE_2', 'Attribute updated correctly (code)' + ); + is( + $patron_attributes[1]->{attribute}, + 'None', 'Attribute updated correctly (attribute)' + ); - is( $patron_attributes[2]->{code}, - 'CODE_2', 'Attribute updated correctly (code)' ); - is( $patron_attributes[2]->{attribute}, - 'Tomasito', 'Attribute updated correctly (attribute)' ); + is( + $patron_attributes[2]->{code}, + 'CODE_2', 'Attribute updated correctly (code)' + ); + is( + $patron_attributes[2]->{attribute}, + 'Tomasito', 'Attribute updated correctly (attribute)' + ); my $empty_code_json = '[{"code":"CODE_2","value":""}]'; $verification_token = md5_hex( time() . {} . rand() . {} . $$ ); $patron_modification = Koha::Patron::Modification->new( - { verification_token => $verification_token, + { + verification_token => $verification_token, changed_fields => 'borrowernumber,extended_attributes', borrowernumber => $patron->borrowernumber, extended_attributes => $empty_code_json } )->store(); - ok( $patron_modification->approve, - 'Patron modification correctly approved' ); - $patron_attributes - = map { $_->unblessed } - Koha::Patron::Attributes->search( - { borrowernumber => $patron->borrowernumber } ); + ok( + $patron_modification->approve, + 'Patron modification correctly approved' + ); + $patron_attributes = + map { $_->unblessed } Koha::Patron::Attributes->search( { borrowernumber => $patron->borrowernumber } ); - is( $patron_attributes[0]->{code}, - 'CODE_1', 'Untouched attribute type is preserved (code)' ); - is( $patron_attributes[0]->{attribute}, - 'VALUE_1', 'Untouched attribute type is preserved (attribute)' ); + is( + $patron_attributes[0]->{code}, + 'CODE_1', 'Untouched attribute type is preserved (code)' + ); + is( + $patron_attributes[0]->{attribute}, + 'VALUE_1', 'Untouched attribute type is preserved (attribute)' + ); - my $count = Koha::Patron::Attributes->search({ borrowernumber => $patron->borrowernumber, code => 'CODE_2' })->count; - is( $count, 0, 'Attributes deleted when modification contained an empty one'); + my $count = + Koha::Patron::Attributes->search( { borrowernumber => $patron->borrowernumber, code => 'CODE_2' } )->count; + is( $count, 0, 'Attributes deleted when modification contained an empty one' ); $schema->storage->txn_rollback; }; @@ -277,53 +310,54 @@ subtest 'pending_count() and pending() tests' => sub { Koha::Patron::Modifications->search->delete; my $library_1 = $builder->build( { source => 'Branch' } )->{branchcode}; my $library_2 = $builder->build( { source => 'Branch' } )->{branchcode}; - $builder->build({ source => 'BorrowerAttributeType', value => { code => 'CODE_1' } }); - $builder->build({ source => 'BorrowerAttributeType', value => { code => 'CODE_2', repeatable => 1 } }); + $builder->build( { source => 'BorrowerAttributeType', value => { code => 'CODE_1' } } ); + $builder->build( { source => 'BorrowerAttributeType', value => { code => 'CODE_2', repeatable => 1 } } ); - my $patron_1 - = $builder->build( - { source => 'Borrower', value => { branchcode => $library_1, flags => 1 } } ); - my $patron_2 - = $builder->build( - { source => 'Borrower', value => { branchcode => $library_2 } } ); - my $patron_3 - = $builder->build( - { source => 'Borrower', value => { branchcode => $library_2 } } ); + my $patron_1 = $builder->build( { source => 'Borrower', value => { branchcode => $library_1, flags => 1 } } ); + my $patron_2 = $builder->build( { source => 'Borrower', value => { branchcode => $library_2 } } ); + my $patron_3 = $builder->build( { source => 'Borrower', value => { branchcode => $library_2 } } ); $patron_1 = Koha::Patrons->find( $patron_1->{borrowernumber} ); $patron_2 = Koha::Patrons->find( $patron_2->{borrowernumber} ); $patron_3 = Koha::Patrons->find( $patron_3->{borrowernumber} ); - my $verification_token_1 = md5_hex( time().{}.rand().{}.$$ ); - my $verification_token_2 = md5_hex( time().{}.rand().{}.$$ ); - my $verification_token_3 = md5_hex( time().{}.rand().{}.$$ ); + my $verification_token_1 = md5_hex( time() . {} . rand() . {} . $$ ); + my $verification_token_2 = md5_hex( time() . {} . rand() . {} . $$ ); + my $verification_token_3 = md5_hex( time() . {} . rand() . {} . $$ ); - Koha::Patron::Attribute->new({ borrowernumber => $patron_1->borrowernumber, code => 'CODE_1', attribute => 'hello' } )->store(); - Koha::Patron::Attribute->new({ borrowernumber => $patron_2->borrowernumber, code => 'CODE_2', attribute => 'bye' } )->store(); + Koha::Patron::Attribute->new( + { borrowernumber => $patron_1->borrowernumber, code => 'CODE_1', attribute => 'hello' } )->store(); + Koha::Patron::Attribute->new( + { borrowernumber => $patron_2->borrowernumber, code => 'CODE_2', attribute => 'bye' } )->store(); my $modification_1 = Koha::Patron::Modification->new( - { verification_token => $verification_token_1, - changed_fields => 'borrowernumber,surname,firstname,extended_attributes', - borrowernumber => $patron_1->borrowernumber, - surname => 'Hall', - firstname => 'Kyle', + { + verification_token => $verification_token_1, + changed_fields => 'borrowernumber,surname,firstname,extended_attributes', + borrowernumber => $patron_1->borrowernumber, + surname => 'Hall', + firstname => 'Kyle', extended_attributes => '[{"code":"CODE_1","value":""}]' } )->store(); - is( Koha::Patron::Modifications->pending_count, - 1, 'pending_count() correctly returns 1' ); + is( + Koha::Patron::Modifications->pending_count, + 1, 'pending_count() correctly returns 1' + ); my $modification_2 = Koha::Patron::Modification->new( - { verification_token => $verification_token_2, - changed_fields => 'borrowernumber,surname,firstname,extended_attributes', - borrowernumber => $patron_2->borrowernumber, - surname => 'Smith', - firstname => 'Sandy', + { + verification_token => $verification_token_2, + changed_fields => 'borrowernumber,surname,firstname,extended_attributes', + borrowernumber => $patron_2->borrowernumber, + surname => 'Smith', + firstname => 'Sandy', extended_attributes => '[{"code":"CODE_2","value":"año"},{"code":"CODE_2","value":"ciao"}]' } )->store(); my $modification_3 = Koha::Patron::Modification->new( - { verification_token => $verification_token_3, + { + verification_token => $verification_token_3, changed_fields => 'borrowernumber,surname,firstname', borrowernumber => $patron_3->borrowernumber, surname => 'Smithy', @@ -331,24 +365,29 @@ subtest 'pending_count() and pending() tests' => sub { } )->store(); - is( Koha::Patron::Modifications->pending_count, - 3, 'pending_count() correctly returns 3' ); + is( + Koha::Patron::Modifications->pending_count, + 3, 'pending_count() correctly returns 3' + ); my $pending = Koha::Patron::Modifications->pending(); is( scalar @{$pending}, 3, 'pending() returns an array with 3 elements' ); my @filtered_modifications = grep { $_->{borrowernumber} eq $patron_1->borrowernumber } @{$pending}; - my $p1_pm = $filtered_modifications[0]; - my $p1_pm_attribute_1 = $p1_pm->{extended_attributes}->[0]; + my $p1_pm = $filtered_modifications[0]; + my $p1_pm_attribute_1 = $p1_pm->{extended_attributes}->[0]; - is( scalar @{$p1_pm->{extended_attributes}}, 1, 'patron 1 has modification has one pending attribute modification' ); - is( ref($p1_pm_attribute_1), 'Koha::Patron::Attribute', 'patron modification has single attribute object' ); - is( $p1_pm_attribute_1->attribute, '', 'patron 1 has an empty value for the attribute' ); + is( + scalar @{ $p1_pm->{extended_attributes} }, 1, + 'patron 1 has modification has one pending attribute modification' + ); + is( ref($p1_pm_attribute_1), 'Koha::Patron::Attribute', 'patron modification has single attribute object' ); + is( $p1_pm_attribute_1->attribute, '', 'patron 1 has an empty value for the attribute' ); @filtered_modifications = grep { $_->{borrowernumber} eq $patron_2->borrowernumber } @{$pending}; my $p2_pm = $filtered_modifications[0]; - is( scalar @{$p2_pm->{extended_attributes}}, 2 , 'patron 2 has 2 attribute modifications' ); + is( scalar @{ $p2_pm->{extended_attributes} }, 2, 'patron 2 has 2 attribute modifications' ); my $p2_pm_attribute_1 = $p2_pm->{extended_attributes}->[0]; my $p2_pm_attribute_2 = $p2_pm->{extended_attributes}->[1]; @@ -356,31 +395,40 @@ subtest 'pending_count() and pending() tests' => sub { is( ref($p2_pm_attribute_1), 'Koha::Patron::Attribute', 'patron modification has single attribute object' ); is( ref($p2_pm_attribute_2), 'Koha::Patron::Attribute', 'patron modification has single attribute object' ); - is( $p2_pm_attribute_1->attribute, 'año', 'patron modification has the right attribute change' ); + is( $p2_pm_attribute_1->attribute, 'año', 'patron modification has the right attribute change' ); is( $p2_pm_attribute_2->attribute, 'ciao', 'patron modification has the right attribute change' ); + t::lib::Mocks::mock_userenv( { patron => $patron_1 } ); + is( + Koha::Patron::Modifications->pending_count($library_1), + 1, 'pending_count() correctly returns 1 if filtered by library' + ); - t::lib::Mocks::mock_userenv({ patron => $patron_1 }); - is( Koha::Patron::Modifications->pending_count($library_1), - 1, 'pending_count() correctly returns 1 if filtered by library' ); - - is( Koha::Patron::Modifications->pending_count($library_2), - 2, 'pending_count() correctly returns 2 if filtered by library' ); + is( + Koha::Patron::Modifications->pending_count($library_2), + 2, 'pending_count() correctly returns 2 if filtered by library' + ); $modification_1->approve; - is( Koha::Patron::Modifications->pending_count, - 2, 'pending_count() correctly returns 2' ); + is( + Koha::Patron::Modifications->pending_count, + 2, 'pending_count() correctly returns 2' + ); $modification_2->approve; - is( Koha::Patron::Modifications->pending_count, - 1, 'pending_count() correctly returns 1' ); + is( + Koha::Patron::Modifications->pending_count, + 1, 'pending_count() correctly returns 1' + ); $modification_3->approve; - is( Koha::Patron::Modifications->pending_count, - 0, 'pending_count() correctly returns 0' ); + is( + Koha::Patron::Modifications->pending_count, + 0, 'pending_count() correctly returns 0' + ); $schema->storage->txn_rollback; }; @@ -391,63 +439,72 @@ subtest 'dateofbirth tests' => sub { $schema->storage->txn_begin; # Cleaning the field - my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { dateofbirth => '1980-01-01', surname => 'a_surname' } } ); - my $patron_modification = Koha::Patron::Modification->new( { + my $patron = $builder->build_object( + { class => 'Koha::Patrons', value => { dateofbirth => '1980-01-01', surname => 'a_surname' } } ); + my $patron_modification = Koha::Patron::Modification->new( + { changed_fields => 'borrowernumber,dateofbirth', borrowernumber => $patron->borrowernumber, - dateofbirth => undef - })->store; + dateofbirth => undef + } + )->store; $patron_modification->approve; $patron->discard_changes; is( $patron->dateofbirth, undef, 'dateofbirth must a been set to NULL if required' ); # FIXME ->approve must have been removed it, but it did not. There may be an hidden bug here. - Koha::Patron::Modifications->search({ borrowernumber => $patron->borrowernumber })->delete; + Koha::Patron::Modifications->search( { borrowernumber => $patron->borrowernumber } )->delete; # Adding a dateofbirth - $patron_modification = Koha::Patron::Modification->new( { + $patron_modification = Koha::Patron::Modification->new( + { changed_fields => 'borrowernumber,dateofbirth', borrowernumber => $patron->borrowernumber, - dateofbirth => '1980-02-02' - })->store; + dateofbirth => '1980-02-02' + } + )->store; $patron_modification->approve; $patron->discard_changes; is( $patron->dateofbirth, '1980-02-02', 'dateofbirth must a been set' ); - is( $patron->surname, 'a_surname', 'surname must not be updated' ); + is( $patron->surname, 'a_surname', 'surname must not be updated' ); # FIXME ->approve must have been removed it, but it did not. There may be an hidden bug here. - Koha::Patron::Modifications->search({ borrowernumber => $patron->borrowernumber })->delete; + Koha::Patron::Modifications->search( { borrowernumber => $patron->borrowernumber } )->delete; # Modifying a dateofbirth - $patron_modification = Koha::Patron::Modification->new( { + $patron_modification = Koha::Patron::Modification->new( + { changed_fields => 'borrowernumber,dateofbirth', borrowernumber => $patron->borrowernumber, - dateofbirth => '1980-03-03', - surname => undef - })->store; + dateofbirth => '1980-03-03', + surname => undef + } + )->store; $patron_modification->approve; $patron->discard_changes; is( $patron->dateofbirth, '1980-03-03', 'dateofbirth must a been updated' ); - is( $patron->surname, 'a_surname', 'surname must not be updated' ); + is( $patron->surname, 'a_surname', 'surname must not be updated' ); # FIXME ->approve must have been removed it, but it did not. There may be an hidden bug here. - Koha::Patron::Modifications->search({ borrowernumber => $patron->borrowernumber })->delete; + Koha::Patron::Modifications->search( { borrowernumber => $patron->borrowernumber } )->delete; # Modifying something else - $patron_modification = Koha::Patron::Modification->new( { + $patron_modification = Koha::Patron::Modification->new( + { changed_fields => 'borrowernumber,surname', borrowernumber => $patron->borrowernumber, - surname => 'another_surname', - dateofbirth => undef - })->store; + surname => 'another_surname', + dateofbirth => undef + } + )->store; $patron_modification->approve; $patron->discard_changes; - is( $patron->surname, 'another_surname', 'surname must be updated' ); - is( $patron->dateofbirth, '1980-03-03', 'dateofbirth should not have been updated if not needed' ); + is( $patron->surname, 'another_surname', 'surname must be updated' ); + is( $patron->dateofbirth, '1980-03-03', 'dateofbirth should not have been updated if not needed' ); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/Koha/Patron/Relationship.t b/t/db_dependent/Koha/Patron/Relationship.t index 495afad126..d8b6457629 100755 --- a/t/db_dependent/Koha/Patron/Relationship.t +++ b/t/db_dependent/Koha/Patron/Relationship.t @@ -45,47 +45,48 @@ subtest 'store() tests' => sub { my $patron_2 = $builder->build_object( { class => 'Koha::Patrons' } ); my $relationship_1 = Koha::Patron::Relationship->new( - { guarantor_id => $patron_2->borrowernumber, + { + guarantor_id => $patron_2->borrowernumber, guarantee_id => $patron_1->borrowernumber } ); - throws_ok - { $relationship_1->store; } - 'Koha::Exceptions::Patron::Relationship::InvalidRelationship', + throws_ok { $relationship_1->store; } + 'Koha::Exceptions::Patron::Relationship::InvalidRelationship', 'Exception is thrown as no relationship passed'; is( "$@", "No relationship passed.", 'Exception stringified correctly' ); - is( Koha::Patron::Relationships->search( { guarantee_id => $patron_1->borrowernumber } )->count, + is( + Koha::Patron::Relationships->search( { guarantee_id => $patron_1->borrowernumber } )->count, 0, 'No guarantors added' ); my $relationship = 'father'; - throws_ok - { $relationship_1->relationship($relationship)->store; } - 'Koha::Exceptions::Patron::Relationship::InvalidRelationship', + throws_ok { $relationship_1->relationship($relationship)->store; } + 'Koha::Exceptions::Patron::Relationship::InvalidRelationship', 'Exception is thrown as a wrong relationship was passed'; is( "$@", "Invalid relationship passed, '$relationship' is not defined.", 'Exception stringified correctly' ); - is( Koha::Patron::Relationships->search( { guarantee_id => $patron_1->borrowernumber } )->count, + is( + Koha::Patron::Relationships->search( { guarantee_id => $patron_1->borrowernumber } )->count, 0, 'No guarantors added' ); $relationship = ''; - throws_ok - { $relationship_1->relationship($relationship)->store; } - 'Koha::Exceptions::Patron::Relationship::InvalidRelationship', + throws_ok { $relationship_1->relationship($relationship)->store; } + 'Koha::Exceptions::Patron::Relationship::InvalidRelationship', 'Exception is thrown as a wrong relationship was passed'; is( "$@", "Invalid relationship passed, '$relationship' is not defined.", 'Exception stringified correctly' ); - is( Koha::Patron::Relationships->search( { guarantee_id => $patron_1->borrowernumber } )->count, + is( + Koha::Patron::Relationships->search( { guarantee_id => $patron_1->borrowernumber } )->count, 0, 'No guarantors added when empty relationship passed and not defined' ); @@ -94,13 +95,15 @@ subtest 'store() tests' => sub { $relationship_1->relationship($relationship)->store; - is( Koha::Patron::Relationships->search( { guarantee_id => $patron_1->borrowernumber } )->count, + is( + Koha::Patron::Relationships->search( { guarantee_id => $patron_1->borrowernumber } )->count, 1, 'Guarantor added' ); my $relationship_2 = Koha::Patron::Relationship->new( - { guarantor_id => $patron_2->borrowernumber, + { + guarantor_id => $patron_2->borrowernumber, guarantee_id => $patron_1->borrowernumber, relationship => 'father2' } @@ -109,12 +112,12 @@ subtest 'store() tests' => sub { { local *STDERR; open STDERR, '>', '/dev/null'; - throws_ok - { $relationship_2->store; } - 'Koha::Exceptions::Patron::Relationship::DuplicateRelationship', + throws_ok { $relationship_2->store; } + 'Koha::Exceptions::Patron::Relationship::DuplicateRelationship', 'Exception is thrown for duplicated relationship'; - is( "$@", + is( + "$@", "There already exists a relationship for the same guarantor (" . $patron_2->borrowernumber . ") and guarantee (" diff --git a/t/db_dependent/Koha/Patron/Restriction/Type.t b/t/db_dependent/Koha/Patron/Restriction/Type.t index 1caae5d873..2f143118e6 100755 --- a/t/db_dependent/Koha/Patron/Restriction/Type.t +++ b/t/db_dependent/Koha/Patron/Restriction/Type.t @@ -38,10 +38,10 @@ subtest 'delete() tests' => sub { $schema->storage->txn_begin; # Default restriction type - my $default_restriction_type = Koha::Patron::Restriction::Types->find({ is_default => 1 }); + my $default_restriction_type = Koha::Patron::Restriction::Types->find( { is_default => 1 } ); throws_ok { $default_restriction_type->delete } 'Koha::Exceptions::CannotDeleteDefault', - 'Delete exception thrown on current default'; + 'Delete exception thrown on current default'; # System restriction type my $system_restriction_type = $builder->build_object( @@ -55,7 +55,7 @@ subtest 'delete() tests' => sub { )->store; throws_ok { $system_restriction_type->delete } 'Koha::Exceptions::CannotDeleteSystem', - 'Delete exception thrown on system type'; + 'Delete exception thrown on system type'; # Used restriction type my $used_restriction_type = $builder->build_object( @@ -81,7 +81,7 @@ subtest 'delete() tests' => sub { } ); ok( $used_restriction_type->delete, 'Used restriction type deleted' ); - my $restrictions = $patron->restrictions; + my $restrictions = $patron->restrictions; my $THE_restriction = $restrictions->next; is( $THE_restriction->type->code, @@ -99,7 +99,7 @@ subtest 'make_default() tests' => sub { $schema->storage->txn_begin; # Get current default restriction type - my $current_default = Koha::Patron::Restriction::Types->find({ is_default => 1 }); + my $current_default = Koha::Patron::Restriction::Types->find( { is_default => 1 } ); # New non-default restriction type my $new_default = $builder->build_object( @@ -112,8 +112,8 @@ subtest 'make_default() tests' => sub { $new_default->make_default; $current_default->discard_changes; - is($current_default->is_default, 0, 'is_default set to false on prior default'); - is($new_default->is_default, 1, 'is_default set true on new default'); + is( $current_default->is_default, 0, 'is_default set to false on prior default' ); + is( $new_default->is_default, 1, 'is_default set true on new default' ); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/Koha/Patron_generate_userid.t b/t/db_dependent/Koha/Patron_generate_userid.t index d44753d883..610876c91e 100755 --- a/t/db_dependent/Koha/Patron_generate_userid.t +++ b/t/db_dependent/Koha/Patron_generate_userid.t @@ -19,6 +19,7 @@ use Modern::Perl; use utf8; + #use Data::Dumper; use Test::More tests => 2; use Test::Warn; @@ -34,29 +35,29 @@ use Koha::Plugins; our $schema = Koha::Database->new->schema; $schema->storage->txn_begin; -our $builder = t::lib::TestBuilder->new; +our $builder = t::lib::TestBuilder->new; our $expected_plugins = []; sub mockedGetPlugins { my @plugins; - foreach my $p ( @$expected_plugins ) { + foreach my $p (@$expected_plugins) { my $object = Test::MockObject->new; my $method; - if( $p eq 'email' ) { + if ( $p eq 'email' ) { $method = sub { return $_[1]->{patron}->email; }; - } elsif( $p eq 'firstname' ) { - $method = sub { return $_[1]->{patron}->firstname. ($_[1]->{patron}->id // 0); }; - } elsif( $p eq 'baduserid' ) { - $method = sub { return ''; }; # bad return - } elsif( $p eq 'die' ) { + } elsif ( $p eq 'firstname' ) { + $method = sub { return $_[1]->{patron}->firstname . ( $_[1]->{patron}->id // 0 ); }; + } elsif ( $p eq 'baduserid' ) { + $method = sub { return ''; }; # bad return + } elsif ( $p eq 'die' ) { $method = sub { die; }; - } elsif( $p eq 'undef' ) { + } elsif ( $p eq 'undef' ) { $method = sub { return; }; - } else { # borrowernumber + } else { # borrowernumber $method = sub { return $_[1]->{patron}->id // 0; }; } - $object->mock('patron_generate_userid', $method); - $object->mock('get_metadata', sub { return { name => $p }}); # called when warning from ->call + $object->mock( 'patron_generate_userid', $method ); + $object->mock( 'get_metadata', sub { return { name => $p } } ); # called when warning from ->call push @plugins, $object; } return @plugins; @@ -65,9 +66,9 @@ sub mockedGetPlugins { subtest 'generate_userid (legacy, without plugins)' => sub { plan tests => 7; - t::lib::Mocks::mock_config('enable_plugins', 0); + t::lib::Mocks::mock_config( 'enable_plugins', 0 ); - my $library = $builder->build_object( { class => 'Koha::Libraries' } ); + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); my $patron_category = $builder->build_object( { class => 'Koha::Patron::Categories', @@ -83,24 +84,28 @@ subtest 'generate_userid (legacy, without plugins)' => sub { ); my $expected_userid_patron_1 = 'tomasito.none'; - my $new_patron = Koha::Patron->new({ firstname => $data{firstname}, surname => $data{surname} } ); + my $new_patron = Koha::Patron->new( { firstname => $data{firstname}, surname => $data{surname} } ); $new_patron->generate_userid; my $userid = $new_patron->userid; is( $userid, $expected_userid_patron_1, 'generate_userid should generate the userid we expect' ); - my $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber; - my $patron_1 = Koha::Patrons->find($borrowernumber); - is ( $patron_1->userid, $expected_userid_patron_1, 'The userid generated should be the one we expect' ); + my $borrowernumber = Koha::Patron->new( \%data )->store->borrowernumber; + my $patron_1 = Koha::Patrons->find($borrowernumber); + is( $patron_1->userid, $expected_userid_patron_1, 'The userid generated should be the one we expect' ); $new_patron->generate_userid; $userid = $new_patron->userid; is( $userid, $expected_userid_patron_1 . '1', 'generate_userid should generate the userid we expect' ); $data{cardnumber} = '987654321'; - my $new_borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber; - my $patron_2 = Koha::Patrons->find($new_borrowernumber); - isnt( $patron_2->userid, 'tomasito', - "Patron with duplicate userid has new userid generated" ); - is( $patron_2->userid, $expected_userid_patron_1 . '1', # TODO we could make that configurable - "Patron with duplicate userid has new userid generated (1 is appended" ); + my $new_borrowernumber = Koha::Patron->new( \%data )->store->borrowernumber; + my $patron_2 = Koha::Patrons->find($new_borrowernumber); + isnt( + $patron_2->userid, 'tomasito', + "Patron with duplicate userid has new userid generated" + ); + is( + $patron_2->userid, $expected_userid_patron_1 . '1', # TODO we could make that configurable + "Patron with duplicate userid has new userid generated (1 is appended" + ); $new_patron->generate_userid; $userid = $new_patron->userid; @@ -119,22 +124,22 @@ subtest 'generate_userid (legacy, without plugins)' => sub { subtest 'Plugins for generate_userid' => sub { plan tests => 6; - t::lib::Mocks::mock_config('enable_plugins', 1); + t::lib::Mocks::mock_config( 'enable_plugins', 1 ); - my $auth = Test::MockModule->new( 'Koha::Plugins' ); - $auth->mock( 'GetPlugins', \&mockedGetPlugins ); + my $auth = Test::MockModule->new('Koha::Plugins'); + $auth->mock( 'GetPlugins', \&mockedGetPlugins ); $auth->mock( 'get_enabled_plugins', \&mockedGetPlugins ); # Check the email plugin - $expected_plugins = [ 'email' ]; - my $patron1 = $builder->build_object({ class => 'Koha::Patrons', value => { email => 'test@domain.com' } }); + $expected_plugins = ['email']; + my $patron1 = $builder->build_object( { class => 'Koha::Patrons', value => { email => 'test@domain.com' } } ); $patron1->generate_userid; is( $patron1->userid, 'test@domain.com', 'generated userid from email plugin' ); # Expect second response from firstname, because empty string from baduserid is not valid $expected_plugins = [ 'baduserid', 'firstname', 'email' ]; $patron1->generate_userid; - my $reg = $patron1->firstname. '\d+'; + my $reg = $patron1->firstname . '\d+'; like( $patron1->userid, qr/$reg/, 'ignored baduserid, generated userid from firstname plugin' ); # Expect third response from fallback for wrong_method, catch warning from die plugin @@ -145,7 +150,8 @@ subtest 'Plugins for generate_userid' => sub { # Testing with an object not in storage; unknown should return id 0, the plugin undef returns undef :) $expected_plugins = [ 'unknown', 'undef' ]; - $patron1= Koha::Patron->new({ firstname => 'A', surname => 'B', email => 'test2@domain.com', userid => 'user999' }); + $patron1 = + Koha::Patron->new( { firstname => 'A', surname => 'B', email => 'test2@domain.com', userid => 'user999' } ); $patron1->generate_userid; is( $patron1->userid, undef, 'No valid plugin responses' ); diff --git a/t/db_dependent/Koha/Patrons.t b/t/db_dependent/Koha/Patrons.t index 994d3fe409..854a12060e 100755 --- a/t/db_dependent/Koha/Patrons.t +++ b/t/db_dependent/Koha/Patrons.t @@ -53,49 +53,66 @@ my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; my $builder = t::lib::TestBuilder->new; -my $library = $builder->build({source => 'Branch' }); -my $category = $builder->build({source => 'Category' }); +my $library = $builder->build( { source => 'Branch' } ); +my $category = $builder->build( { source => 'Category' } ); my $nb_of_patrons = Koha::Patrons->search->count; my $new_patron_1 = Koha::Patron->new( - { cardnumber => 'test_cn_1', - branchcode => $library->{branchcode}, + { + cardnumber => 'test_cn_1', + branchcode => $library->{branchcode}, categorycode => $category->{categorycode}, - surname => 'surname for patron1', - firstname => 'firstname for patron1', - userid => 'a_nonexistent_userid_1', - flags => 1, # Is superlibrarian + surname => 'surname for patron1', + firstname => 'firstname for patron1', + userid => 'a_nonexistent_userid_1', + flags => 1, # Is superlibrarian } )->store; -my $new_patron_2 = Koha::Patron->new( - { cardnumber => 'test_cn_2', - branchcode => $library->{branchcode}, +my $new_patron_2 = Koha::Patron->new( + { + cardnumber => 'test_cn_2', + branchcode => $library->{branchcode}, categorycode => $category->{categorycode}, - surname => 'surname for patron2', - firstname => 'firstname for patron2', - userid => 'a_nonexistent_userid_2', + surname => 'surname for patron2', + firstname => 'firstname for patron2', + userid => 'a_nonexistent_userid_2', } )->store; -t::lib::Mocks::mock_userenv({ patron => $new_patron_1 }); +t::lib::Mocks::mock_userenv( { patron => $new_patron_1 } ); is( Koha::Patrons->search->count, $nb_of_patrons + 2, 'The 2 patrons should have been added' ); my $retrieved_patron_1 = Koha::Patrons->find( $new_patron_1->borrowernumber ); -is( $retrieved_patron_1->cardnumber, $new_patron_1->cardnumber, 'Find a patron by borrowernumber should return the correct patron' ); +is( + $retrieved_patron_1->cardnumber, $new_patron_1->cardnumber, + 'Find a patron by borrowernumber should return the correct patron' +); subtest 'library' => sub { plan tests => 2; - is( $retrieved_patron_1->library->branchcode, $library->{branchcode}, 'Koha::Patron->library should return the correct library' ); - is( ref($retrieved_patron_1->library), 'Koha::Library', 'Koha::Patron->library should return a Koha::Library object' ); + is( + $retrieved_patron_1->library->branchcode, $library->{branchcode}, + 'Koha::Patron->library should return the correct library' + ); + is( + ref( $retrieved_patron_1->library ), 'Koha::Library', + 'Koha::Patron->library should return a Koha::Library object' + ); }; subtest 'sms_provider' => sub { plan tests => 3; - my $sms_provider = $builder->build({source => 'SmsProvider' }); + my $sms_provider = $builder->build( { source => 'SmsProvider' } ); is( $retrieved_patron_1->sms_provider, undef, '->sms_provider should return undef if none defined' ); $retrieved_patron_1->sms_provider_id( $sms_provider->{id} )->store; - is_deeply( $retrieved_patron_1->sms_provider->unblessed, $sms_provider, 'Koha::Patron->sms_provider returns the correct SMS provider' ); - is( ref($retrieved_patron_1->sms_provider), 'Koha::SMS::Provider', 'Koha::Patron->sms_provider should return a Koha::SMS::Provider object' ); + is_deeply( + $retrieved_patron_1->sms_provider->unblessed, $sms_provider, + 'Koha::Patron->sms_provider returns the correct SMS provider' + ); + is( + ref( $retrieved_patron_1->sms_provider ), 'Koha::SMS::Provider', + 'Koha::Patron->sms_provider should return a Koha::SMS::Provider object' + ); }; subtest 'guarantees' => sub { @@ -105,23 +122,33 @@ subtest 'guarantees' => sub { t::lib::Mocks::mock_preference( 'borrowerRelationship', 'test|test2' ); my $guarantees = $new_patron_1->guarantee_relationships; - is( ref($guarantees), 'Koha::Patron::Relationships', 'Koha::Patron->guarantees should return a Koha::Patrons result set in a scalar context' ); + is( + ref($guarantees), 'Koha::Patron::Relationships', + 'Koha::Patron->guarantees should return a Koha::Patrons result set in a scalar context' + ); is( $guarantees->count, 0, 'new_patron_1 should have 0 guarantee relationships' ); - my $guarantee_1 = $builder->build({ source => 'Borrower' }); - my $relationship_1 = Koha::Patron::Relationship->new( { guarantor_id => $new_patron_1->id, guarantee_id => $guarantee_1->{borrowernumber}, relationship => 'test' } )->store(); - my $guarantee_2 = $builder->build({ source => 'Borrower' }); - my $relationship_2 = Koha::Patron::Relationship->new( { guarantor_id => $new_patron_1->id, guarantee_id => $guarantee_2->{borrowernumber}, relationship => 'test' } )->store(); + my $guarantee_1 = $builder->build( { source => 'Borrower' } ); + my $relationship_1 = Koha::Patron::Relationship->new( + { guarantor_id => $new_patron_1->id, guarantee_id => $guarantee_1->{borrowernumber}, relationship => 'test' } ) + ->store(); + my $guarantee_2 = $builder->build( { source => 'Borrower' } ); + my $relationship_2 = Koha::Patron::Relationship->new( + { guarantor_id => $new_patron_1->id, guarantee_id => $guarantee_2->{borrowernumber}, relationship => 'test' } ) + ->store(); $guarantees = $new_patron_1->guarantee_relationships; - is( ref($guarantees), 'Koha::Patron::Relationships', 'Koha::Patron->guarantee_relationships should return a Koha::Patrons result set in a scalar context' ); + is( + ref($guarantees), 'Koha::Patron::Relationships', + 'Koha::Patron->guarantee_relationships should return a Koha::Patrons result set in a scalar context' + ); is( $guarantees->count, 2, 'new_patron_1 should have 2 guarantees' ); $guarantees->delete; #Test return order of guarantees BZ 18635 - my $categorycode = $builder->build({ source => 'Category' })->{categorycode}; - my $branchcode = $builder->build({ source => 'Branch' })->{branchcode}; + my $categorycode = $builder->build( { source => 'Category' } )->{categorycode}; + my $branchcode = $builder->build( { source => 'Branch' } )->{branchcode}; my $guarantor = $builder->build_object( { class => 'Koha::Patrons' } ); @@ -129,7 +156,7 @@ subtest 'guarantees' => sub { { class => 'Koha::Patrons', value => { - surname => 'Zebra', + surname => 'Zebra', } } )->borrowernumber; @@ -137,7 +164,7 @@ subtest 'guarantees' => sub { { class => 'Koha::Patron::Relationships', value => { - guarantor_id => $guarantor->id, + guarantor_id => $guarantor->id, guarantee_id => $order_guarantee1, relationship => 'test', } @@ -148,7 +175,7 @@ subtest 'guarantees' => sub { { class => 'Koha::Patrons', value => { - surname => 'Yak', + surname => 'Yak', } } )->borrowernumber; @@ -156,7 +183,7 @@ subtest 'guarantees' => sub { { class => 'Koha::Patron::Relationships', value => { - guarantor_id => $guarantor->id, + guarantor_id => $guarantor->id, guarantee_id => $order_guarantee2, relationship => 'test', } @@ -167,8 +194,8 @@ subtest 'guarantees' => sub { { class => 'Koha::Patrons', value => { - surname => 'Xerus', - firstname => 'Walrus', + surname => 'Xerus', + firstname => 'Walrus', } } )->borrowernumber; @@ -176,7 +203,7 @@ subtest 'guarantees' => sub { { class => 'Koha::Patron::Relationships', value => { - guarantor_id => $guarantor->id, + guarantor_id => $guarantor->id, guarantee_id => $order_guarantee3, relationship => 'test', } @@ -187,8 +214,8 @@ subtest 'guarantees' => sub { { class => 'Koha::Patrons', value => { - surname => 'Xerus', - firstname => 'Vulture', + surname => 'Xerus', + firstname => 'Vulture', } } )->borrowernumber; @@ -196,7 +223,7 @@ subtest 'guarantees' => sub { { class => 'Koha::Patron::Relationships', value => { - guarantor_id => $guarantor->id, + guarantor_id => $guarantor->id, guarantee_id => $order_guarantee4, relationship => 'test', } @@ -207,8 +234,8 @@ subtest 'guarantees' => sub { { class => 'Koha::Patrons', value => { - surname => 'Xerus', - firstname => 'Unicorn', + surname => 'Xerus', + firstname => 'Unicorn', } } )->borrowernumber; @@ -216,7 +243,7 @@ subtest 'guarantees' => sub { { class => 'Koha::Patron::Relationships', value => { - guarantor_id => $guarantor->id, + guarantor_id => $guarantor->id, guarantee_id => $order_guarantee5, relationship => 'test', } @@ -235,7 +262,7 @@ subtest 'guarantees' => sub { subtest 'category' => sub { plan tests => 2; my $patron_category = $new_patron_1->category; - is( ref( $patron_category), 'Koha::Patron::Category', ); + is( ref($patron_category), 'Koha::Patron::Category', ); is( $patron_category->categorycode, $category->{categorycode}, ); }; @@ -245,16 +272,34 @@ subtest 'siblings' => sub { my $siblings = $new_patron_1->siblings; is( $siblings, undef, 'Koha::Patron->siblings should not crashed if the patron has no guarantor' ); - my $guarantee_1 = $builder->build( { source => 'Borrower' } ); - my $relationship_1 = Koha::Patron::Relationship->new( { guarantor_id => $new_patron_1->borrowernumber, guarantee_id => $guarantee_1->{borrowernumber}, relationship => 'test' } )->store(); + my $guarantee_1 = $builder->build( { source => 'Borrower' } ); + my $relationship_1 = Koha::Patron::Relationship->new( + { + guarantor_id => $new_patron_1->borrowernumber, guarantee_id => $guarantee_1->{borrowernumber}, + relationship => 'test' + } + )->store(); my $retrieved_guarantee_1 = Koha::Patrons->find($guarantee_1); $siblings = $retrieved_guarantee_1->siblings; - is( ref($siblings), 'Koha::Patrons', 'Koha::Patron->siblings should return a Koha::Patrons result set in a scalar context' ); - is( $siblings->count, 0, 'guarantee_1 should not have siblings yet' ); - my $guarantee_2 = $builder->build( { source => 'Borrower' } ); - my $relationship_2 = Koha::Patron::Relationship->new( { guarantor_id => $new_patron_1->borrowernumber, guarantee_id => $guarantee_2->{borrowernumber}, relationship => 'test' } )->store(); - my $guarantee_3 = $builder->build( { source => 'Borrower' } ); - my $relationship_3 = Koha::Patron::Relationship->new( { guarantor_id => $new_patron_1->borrowernumber, guarantee_id => $guarantee_3->{borrowernumber}, relationship => 'test' } )->store(); + is( + ref($siblings), 'Koha::Patrons', + 'Koha::Patron->siblings should return a Koha::Patrons result set in a scalar context' + ); + is( $siblings->count, 0, 'guarantee_1 should not have siblings yet' ); + my $guarantee_2 = $builder->build( { source => 'Borrower' } ); + my $relationship_2 = Koha::Patron::Relationship->new( + { + guarantor_id => $new_patron_1->borrowernumber, guarantee_id => $guarantee_2->{borrowernumber}, + relationship => 'test' + } + )->store(); + my $guarantee_3 = $builder->build( { source => 'Borrower' } ); + my $relationship_3 = Koha::Patron::Relationship->new( + { + guarantor_id => $new_patron_1->borrowernumber, guarantee_id => $guarantee_3->{borrowernumber}, + relationship => 'test' + } + )->store(); $siblings = $retrieved_guarantee_1->siblings; is( $siblings->count, 2, 'guarantee_1 should have 2 siblings' ); is( $guarantee_2->{borrowernumber}, $siblings->next->borrowernumber, 'guarantee_2 should exist in the guarantees' ); @@ -266,16 +311,26 @@ subtest 'siblings' => sub { subtest 'has_overdues' => sub { plan tests => 3; - my $item_1 = $builder->build_sample_item; + my $item_1 = $builder->build_sample_item; my $retrieved_patron = Koha::Patrons->find( $new_patron_1->borrowernumber ); is( $retrieved_patron->has_overdues, 0, ); my $tomorrow = DateTime->today( time_zone => C4::Context->tz() )->add( days => 1 ); - my $issue = Koha::Checkout->new({ borrowernumber => $new_patron_1->id, itemnumber => $item_1->itemnumber, date_due => $tomorrow, branchcode => $library->{branchcode} })->store(); + my $issue = Koha::Checkout->new( + { + borrowernumber => $new_patron_1->id, itemnumber => $item_1->itemnumber, date_due => $tomorrow, + branchcode => $library->{branchcode} + } + )->store(); is( $retrieved_patron->has_overdues, 0, ); $issue->delete(); - my $yesterday = DateTime->today(time_zone => C4::Context->tz())->add( days => -1 ); - $issue = Koha::Checkout->new({ borrowernumber => $new_patron_1->id, itemnumber => $item_1->itemnumber, date_due => $yesterday, branchcode => $library->{branchcode} })->store(); + my $yesterday = DateTime->today( time_zone => C4::Context->tz() )->add( days => -1 ); + $issue = Koha::Checkout->new( + { + borrowernumber => $new_patron_1->id, itemnumber => $item_1->itemnumber, date_due => $yesterday, + branchcode => $library->{branchcode} + } + )->store(); $retrieved_patron = Koha::Patrons->find( $new_patron_1->borrowernumber ); is( $retrieved_patron->has_overdues, 1, ); $issue->delete(); @@ -283,16 +338,16 @@ subtest 'has_overdues' => sub { subtest 'is_expired' => sub { plan tests => 4; - my $patron = $builder->build({ source => 'Borrower' }); + my $patron = $builder->build( { source => 'Borrower' } ); $patron = Koha::Patrons->find( $patron->{borrowernumber} ); - $patron->dateexpiry( undef )->store->discard_changes; - is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is not set'); - $patron->dateexpiry( dt_from_string )->store->discard_changes; - is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is today'); + $patron->dateexpiry(undef)->store->discard_changes; + is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is not set' ); + $patron->dateexpiry(dt_from_string)->store->discard_changes; + is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is today' ); $patron->dateexpiry( dt_from_string->add( days => 1 ) )->store->discard_changes; - is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is tomorrow'); + is( $patron->is_expired, 0, 'Patron should not be considered expired if dateexpiry is tomorrow' ); $patron->dateexpiry( dt_from_string->add( days => -1 ) )->store->discard_changes; - is( $patron->is_expired, 1, 'Patron should be considered expired if dateexpiry is yesterday'); + is( $patron->is_expired, 1, 'Patron should be considered expired if dateexpiry is yesterday' ); $patron->delete; }; @@ -300,70 +355,97 @@ subtest 'is_expired' => sub { subtest 'is_going_to_expire' => sub { plan tests => 9; - my $today = dt_from_string(undef, undef, 'floating'); - my $patron = $builder->build({ source => 'Borrower' }); + my $today = dt_from_string( undef, undef, 'floating' ); + my $patron = $builder->build( { source => 'Borrower' } ); $patron = Koha::Patrons->find( $patron->{borrowernumber} ); - $patron->dateexpiry( undef )->store->discard_changes; - is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is not set'); + $patron->dateexpiry(undef)->store->discard_changes; + is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is not set' ); - t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 0); - $patron->dateexpiry( $today )->store->discard_changes; - is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is today'); + t::lib::Mocks::mock_preference( 'NotifyBorrowerDeparture', 0 ); + $patron->dateexpiry($today)->store->discard_changes; + is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is today' ); - $patron->dateexpiry( $today )->store->discard_changes; - is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is today and pref is 0'); + $patron->dateexpiry($today)->store->discard_changes; + is( + $patron->is_going_to_expire, 0, + 'Patron should not be considered going to expire if dateexpiry is today and pref is 0' + ); - t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 10); + t::lib::Mocks::mock_preference( 'NotifyBorrowerDeparture', 10 ); $patron->dateexpiry( $today->clone->add( days => 11 ) )->store->discard_changes; - is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is 11 days ahead and pref is 10'); + is( + $patron->is_going_to_expire, 0, + 'Patron should not be considered going to expire if dateexpiry is 11 days ahead and pref is 10' + ); - t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 0); + t::lib::Mocks::mock_preference( 'NotifyBorrowerDeparture', 0 ); $patron->dateexpiry( $today->clone->add( days => 10 ) )->store->discard_changes; - is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is 10 days ahead and pref is 0'); + is( + $patron->is_going_to_expire, 0, + 'Patron should not be considered going to expire if dateexpiry is 10 days ahead and pref is 0' + ); - t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 10); + t::lib::Mocks::mock_preference( 'NotifyBorrowerDeparture', 10 ); $patron->dateexpiry( $today->clone->add( days => 10 ) )->store->discard_changes; - is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is 10 days ahead and pref is 10'); + is( + $patron->is_going_to_expire, 0, + 'Patron should not be considered going to expire if dateexpiry is 10 days ahead and pref is 10' + ); $patron->delete; - t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 10); + t::lib::Mocks::mock_preference( 'NotifyBorrowerDeparture', 10 ); $patron->dateexpiry( $today->clone->add( days => 20 ) )->store->discard_changes; - is( $patron->is_going_to_expire, 0, 'Patron should not be considered going to expire if dateexpiry is 20 days ahead and pref is 10'); + is( + $patron->is_going_to_expire, 0, + 'Patron should not be considered going to expire if dateexpiry is 20 days ahead and pref is 10' + ); - t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 20); + t::lib::Mocks::mock_preference( 'NotifyBorrowerDeparture', 20 ); $patron->dateexpiry( $today->clone->add( days => 10 ) )->store->discard_changes; - is( $patron->is_going_to_expire, 1, 'Patron should be considered going to expire if dateexpiry is 10 days ahead and pref is 20'); + is( + $patron->is_going_to_expire, 1, + 'Patron should be considered going to expire if dateexpiry is 10 days ahead and pref is 20' + ); + + { # Testing invalid is going to expiry date + t::lib::Mocks::mock_preference( 'NotifyBorrowerDeparture', 30 ); - { # Testing invalid is going to expiry date - t::lib::Mocks::mock_preference('NotifyBorrowerDeparture', 30); # mock_config does not work here, because of tz vs timezone subroutines my $context = Test::MockModule->new('C4::Context'); - $context->mock( 'tz', sub { - 'America/Sao_Paulo'; - }); - $patron->dateexpiry(DateTime->new( year => 2019, month => 12, day => 3 ))->store; + $context->mock( + 'tz', + sub { + 'America/Sao_Paulo'; + } + ); + $patron->dateexpiry( DateTime->new( year => 2019, month => 12, day => 3 ) )->store; eval { $patron->is_going_to_expire }; - is( $@, '', 'On invalid "is going to expire" date, the method should not crash with "Invalid local time for date in time zone"'); + is( + $@, '', + 'On invalid "is going to expire" date, the method should not crash with "Invalid local time for date in time zone"' + ); $context->unmock('tz'); }; $patron->delete; }; - subtest 'renew_account' => sub { plan tests => 48; for my $date ( '2016-03-31', '2016-11-30', '2019-01-31', dt_from_string() ) { my $dt = dt_from_string( $date, 'iso' ); Time::Fake->offset( $dt->epoch ); - my $a_month_ago = $dt->clone->subtract( months => 1, end_of_month => 'limit' )->truncate( to => 'day' ); - my $a_year_later = $dt->clone->add( months => 12, end_of_month => 'limit' )->truncate( to => 'day' ); - my $a_year_later_minus_a_month = $a_month_ago->clone->add( months => 12, end_of_month => 'limit' )->truncate( to => 'day' ); - my $a_month_later = $dt->clone->add( months => 1 , end_of_month => 'limit' )->truncate( to => 'day' ); - my $a_year_later_plus_a_month = $a_month_later->clone->add( months => 12, end_of_month => 'limit' )->truncate( to => 'day' ); + my $a_month_ago = $dt->clone->subtract( months => 1, end_of_month => 'limit' )->truncate( to => 'day' ); + my $a_year_later = $dt->clone->add( months => 12, end_of_month => 'limit' )->truncate( to => 'day' ); + my $a_year_later_minus_a_month = + $a_month_ago->clone->add( months => 12, end_of_month => 'limit' )->truncate( to => 'day' ); + my $a_month_later = $dt->clone->add( months => 1, end_of_month => 'limit' )->truncate( to => 'day' ); + my $a_year_later_plus_a_month = + $a_month_later->clone->add( months => 12, end_of_month => 'limit' )->truncate( to => 'day' ); my $patron_category = $builder->build( - { source => 'Category', + { + source => 'Category', value => { enrolmentperiod => 12, enrolmentperioddate => undef, @@ -371,43 +453,53 @@ subtest 'renew_account' => sub { } ); my $patron = $builder->build( - { source => 'Borrower', + { + source => 'Borrower', value => { dateexpiry => $a_month_ago, categorycode => $patron_category->{categorycode}, - date_renewed => undef, # Force builder to not populate the column for new patron + date_renewed => undef, # Force builder to not populate the column for new patron } } ); my $patron_2 = $builder->build( - { source => 'Borrower', - value => { - dateexpiry => $a_month_ago, - categorycode => $patron_category->{categorycode}, + { + source => 'Borrower', + value => { + dateexpiry => $a_month_ago, + categorycode => $patron_category->{categorycode}, } } ); my $patron_3 = $builder->build( - { source => 'Borrower', - value => { - dateexpiry => $a_month_later, - categorycode => $patron_category->{categorycode}, - } + { + source => 'Borrower', + value => { + dateexpiry => $a_month_later, + categorycode => $patron_category->{categorycode}, + } } ); - my $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} ); + my $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} ); my $retrieved_patron_2 = Koha::Patrons->find( $patron_2->{borrowernumber} ); my $retrieved_patron_3 = Koha::Patrons->find( $patron_3->{borrowernumber} ); - is( $retrieved_patron->date_renewed, undef, "Date renewed is not set for patrons that have never been renewed" ); + is( + $retrieved_patron->date_renewed, undef, + "Date renewed is not set for patrons that have never been renewed" + ); t::lib::Mocks::mock_preference( 'BorrowerRenewalPeriodBase', 'dateexpiry' ); t::lib::Mocks::mock_preference( 'BorrowersLog', 1 ); my $expiry_date = $retrieved_patron->renew_account; is( $expiry_date, $a_year_later_minus_a_month, "$a_month_ago + 12 months must be $a_year_later_minus_a_month" ); my $retrieved_expiry_date = Koha::Patrons->find( $patron->{borrowernumber} )->dateexpiry; - is( dt_from_string($retrieved_expiry_date), $a_year_later_minus_a_month, "$a_month_ago + 12 months must be $a_year_later_minus_a_month" ); - my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'RENEW', object => $retrieved_patron->borrowernumber } )->count; + is( + dt_from_string($retrieved_expiry_date), $a_year_later_minus_a_month, + "$a_month_ago + 12 months must be $a_year_later_minus_a_month" + ); + my $number_of_logs = $schema->resultset('ActionLog') + ->search( { module => 'MEMBERS', action => 'RENEW', object => $retrieved_patron->borrowernumber } )->count; is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->renew_account should have logged' ); t::lib::Mocks::mock_preference( 'BorrowerRenewalPeriodBase', 'now' ); @@ -415,10 +507,14 @@ subtest 'renew_account' => sub { $expiry_date = $retrieved_patron->renew_account; is( $expiry_date, $a_year_later, "today + 12 months must be $a_year_later" ); $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} ); - is( $retrieved_patron->date_renewed, output_pref({ dt => $dt, dateformat => 'iso', dateonly => 1 }), "Date renewed is set when calling renew_account" ); + is( + $retrieved_patron->date_renewed, output_pref( { dt => $dt, dateformat => 'iso', dateonly => 1 } ), + "Date renewed is set when calling renew_account" + ); $retrieved_expiry_date = $retrieved_patron->dateexpiry; is( dt_from_string($retrieved_expiry_date), $a_year_later, "today + 12 months must be $a_year_later" ); - $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'RENEW', object => $retrieved_patron->borrowernumber } )->count; + $number_of_logs = $schema->resultset('ActionLog') + ->search( { module => 'MEMBERS', action => 'RENEW', object => $retrieved_patron->borrowernumber } )->count; is( $number_of_logs, 1, 'Without BorrowerLogs, Koha::Patron->renew_account should not have logged' ); t::lib::Mocks::mock_preference( 'BorrowerRenewalPeriodBase', 'combination' ); @@ -430,7 +526,10 @@ subtest 'renew_account' => sub { $expiry_date = $retrieved_patron_3->renew_account; is( $expiry_date, $a_year_later_plus_a_month, "$a_month_later + 12 months must be $a_year_later_plus_a_month" ); $retrieved_expiry_date = Koha::Patrons->find( $patron_3->{borrowernumber} )->dateexpiry; - is( dt_from_string($retrieved_expiry_date), $a_year_later_plus_a_month, "$a_month_later + 12 months must be $a_year_later_plus_a_month" ); + is( + dt_from_string($retrieved_expiry_date), $a_year_later_plus_a_month, + "$a_month_later + 12 months must be $a_year_later_plus_a_month" + ); $retrieved_patron->delete; $retrieved_patron_2->delete; @@ -442,124 +541,175 @@ subtest 'renew_account' => sub { subtest "move_to_deleted" => sub { plan tests => 5; my $originally_updated_on = '2016-01-01 12:12:12'; - my $patron = $builder->build( { source => 'Borrower',value => { updated_on => $originally_updated_on } } ); + my $patron = $builder->build( { source => 'Borrower', value => { updated_on => $originally_updated_on } } ); my $retrieved_patron = Koha::Patrons->find( $patron->{borrowernumber} ); - is( ref( $retrieved_patron->move_to_deleted ), 'Koha::Schema::Result::Deletedborrower', 'Koha::Patron->move_to_deleted should return the Deleted patron' ) - ; # FIXME This should be Koha::Deleted::Patron - my $deleted_patron = $schema->resultset('Deletedborrower') - ->search( { borrowernumber => $patron->{borrowernumber} }, { result_class => 'DBIx::Class::ResultClass::HashRefInflator' } ) - ->next; + is( + ref( $retrieved_patron->move_to_deleted ), 'Koha::Schema::Result::Deletedborrower', + 'Koha::Patron->move_to_deleted should return the Deleted patron' + ); # FIXME This should be Koha::Deleted::Patron + my $deleted_patron = $schema->resultset('Deletedborrower')->search( + { borrowernumber => $patron->{borrowernumber} }, + { result_class => 'DBIx::Class::ResultClass::HashRefInflator' } + )->next; ok( $retrieved_patron->updated_on, 'updated_on should be set for borrowers table' ); ok( $deleted_patron->{updated_on}, 'updated_on should be set for deleted_borrowers table' ); - isnt( $deleted_patron->{updated_on}, $retrieved_patron->updated_on, 'Koha::Patron->move_to_deleted should have correctly updated the updated_on column'); - $deleted_patron->{updated_on} = $originally_updated_on; #reset for simplicity in comparing all other fields - is_deeply( $deleted_patron, $patron, 'Koha::Patron->move_to_deleted should have correctly moved the patron to the deleted table' ); + isnt( + $deleted_patron->{updated_on}, $retrieved_patron->updated_on, + 'Koha::Patron->move_to_deleted should have correctly updated the updated_on column' + ); + $deleted_patron->{updated_on} = $originally_updated_on; #reset for simplicity in comparing all other fields + is_deeply( + $deleted_patron, $patron, + 'Koha::Patron->move_to_deleted should have correctly moved the patron to the deleted table' + ); $retrieved_patron->delete( $patron->{borrowernumber} ); # Cleanup }; subtest "delete" => sub { plan tests => 16; - t::lib::Mocks::mock_preference( 'BorrowersLog', 1 ); + t::lib::Mocks::mock_preference( 'BorrowersLog', 1 ); t::lib::Mocks::mock_preference( 'ListOwnershipUponPatronDeletion', 'transfer' ); - t::lib::Mocks::mock_preference( 'ListOwnerDesignated', undef ); + t::lib::Mocks::mock_preference( 'ListOwnerDesignated', undef ); Koha::Virtualshelves->delete; - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); - my $patron_for_sharing = $builder->build_object({ class => 'Koha::Patrons' }); - my $staff_patron = $builder->build_object({ class => 'Koha::Patrons' }); - t::lib::Mocks::mock_userenv({ patron => $staff_patron }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + my $patron_for_sharing = $builder->build_object( { class => 'Koha::Patrons' } ); + my $staff_patron = $builder->build_object( { class => 'Koha::Patrons' } ); + t::lib::Mocks::mock_userenv( { patron => $staff_patron } ); - my $hold = $builder->build_object({ class => 'Koha::Holds', value => { borrowernumber => $patron->borrowernumber } }); - my $modification = $builder->build_object({ class => 'Koha::Patron::Modifications', value => { borrowernumber => $patron->borrowernumber } }); - my $private_list = Koha::Virtualshelf->new({ - shelfname => "private", - owner => $patron->borrowernumber, - public => 0, - })->store; - my $public_list = Koha::Virtualshelf->new({ - shelfname => "public", - owner => $patron->borrowernumber, - public => 1, - })->store; - my $list_to_share = Koha::Virtualshelf->new({ - shelfname => "shared", - owner => $patron->borrowernumber, - public => 0, - })->store; + my $hold = + $builder->build_object( { class => 'Koha::Holds', value => { borrowernumber => $patron->borrowernumber } } ); + my $modification = $builder->build_object( + { class => 'Koha::Patron::Modifications', value => { borrowernumber => $patron->borrowernumber } } ); + my $private_list = Koha::Virtualshelf->new( + { + shelfname => "private", + owner => $patron->borrowernumber, + public => 0, + } + )->store; + my $public_list = Koha::Virtualshelf->new( + { + shelfname => "public", + owner => $patron->borrowernumber, + public => 1, + } + )->store; + my $list_to_share = Koha::Virtualshelf->new( + { + shelfname => "shared", + owner => $patron->borrowernumber, + public => 0, + } + )->store; $list_to_share->share("valid key")->accept( "valid key", $patron_for_sharing->borrowernumber ); - $list_to_share->share("valid key")->accept( "valid key", $staff_patron->borrowernumber ); # this share should be removed at deletion too + $list_to_share->share("valid key")->accept( "valid key", $staff_patron->borrowernumber ) + ; # this share should be removed at deletion too my $deleted = $patron->delete; - is( ref($deleted), 'Koha::Patron', 'Koha::Patron->delete should return the deleted patron object if the patron has been correctly deleted' ); + is( + ref($deleted), 'Koha::Patron', + 'Koha::Patron->delete should return the deleted patron object if the patron has been correctly deleted' + ); ok( $patron->borrowernumber, 'Still have the deleted borrowernumber' ); is( Koha::Patrons->find( $patron->borrowernumber ), undef, 'Koha::Patron->delete should have deleted the patron' ); - is (Koha::Old::Holds->search({ reserve_id => $hold->reserve_id })->count, 1, q|Koha::Patron->delete should have cancelled patron's holds| ); + is( + Koha::Old::Holds->search( { reserve_id => $hold->reserve_id } )->count, 1, + q|Koha::Patron->delete should have cancelled patron's holds| + ); - is( Koha::Holds->search( { borrowernumber => $patron->borrowernumber } )->count, 0, q|Koha::Patron->delete should have cancelled patron's holds 2| ); + is( + Koha::Holds->search( { borrowernumber => $patron->borrowernumber } )->count, 0, + q|Koha::Patron->delete should have cancelled patron's holds 2| + ); - my $transferred_lists = Koha::Virtualshelves->search({ owner => $staff_patron->borrowernumber })->count; - is( $transferred_lists, 2, 'Public and shared lists should stay in database under a different owner with a unique name, while private lists delete, with ListOwnershipPatronDeletion set to Transfer'); - is( Koha::Virtualshelfshares->search({ borrowernumber => $staff_patron->borrowernumber })->count, 0, "New owner of list should have shares removed" ); - is( Koha::Virtualshelfshares->search({ borrowernumber => $patron_for_sharing->borrowernumber })->count, 1, "But the other share is still there" ); - is( Koha::Virtualshelves->search({ owner => $patron->borrowernumber })->count, 0, q|Koha::Patron->delete should have deleted patron's lists/removed their ownership| ); + my $transferred_lists = Koha::Virtualshelves->search( { owner => $staff_patron->borrowernumber } )->count; + is( + $transferred_lists, 2, + 'Public and shared lists should stay in database under a different owner with a unique name, while private lists delete, with ListOwnershipPatronDeletion set to Transfer' + ); + is( + Koha::Virtualshelfshares->search( { borrowernumber => $staff_patron->borrowernumber } )->count, 0, + "New owner of list should have shares removed" + ); + is( + Koha::Virtualshelfshares->search( { borrowernumber => $patron_for_sharing->borrowernumber } )->count, 1, + "But the other share is still there" + ); + is( + Koha::Virtualshelves->search( { owner => $patron->borrowernumber } )->count, 0, + q|Koha::Patron->delete should have deleted patron's lists/removed their ownership| + ); - is( Koha::Patron::Modifications->search( { borrowernumber => $patron->borrowernumber } )->count, 0, q|Koha::Patron->delete should have deleted patron's modifications| ); + is( + Koha::Patron::Modifications->search( { borrowernumber => $patron->borrowernumber } )->count, 0, + q|Koha::Patron->delete should have deleted patron's modifications| + ); - my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'DELETE', object => $patron->borrowernumber } )->count; + my $number_of_logs = $schema->resultset('ActionLog') + ->search( { module => 'MEMBERS', action => 'DELETE', object => $patron->borrowernumber } )->count; is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->delete should have logged' ); # Test deletion with designated fallback owner - my $designated_owner = $builder->build_object({ class => 'Koha::Patrons' }); + my $designated_owner = $builder->build_object( { class => 'Koha::Patrons' } ); t::lib::Mocks::mock_preference( 'ListOwnerDesignated', $designated_owner->id ); - $patron = $builder->build_object({ class => 'Koha::Patrons' }); - $private_list = Koha::Virtualshelf->new({ shelfname => "PR1", owner => $patron->id })->store; - $public_list = Koha::Virtualshelf->new({ shelfname => "PU1", public => 1, owner => $patron->id })->store; - $list_to_share = Koha::Virtualshelf->new({ shelfname => "SH1", owner => $patron->id })->store; + $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + $private_list = Koha::Virtualshelf->new( { shelfname => "PR1", owner => $patron->id } )->store; + $public_list = Koha::Virtualshelf->new( { shelfname => "PU1", public => 1, owner => $patron->id } )->store; + $list_to_share = Koha::Virtualshelf->new( { shelfname => "SH1", owner => $patron->id } )->store; $list_to_share->share("valid key")->accept( "valid key", $patron_for_sharing->id ); $patron->delete; - is( Koha::Virtualshelves->find( $private_list->id ), undef, 'Private list gone' ); - is( $public_list->discard_changes->get_column('owner'), $designated_owner->id, 'Public list transferred' ); + is( Koha::Virtualshelves->find( $private_list->id ), undef, 'Private list gone' ); + is( $public_list->discard_changes->get_column('owner'), $designated_owner->id, 'Public list transferred' ); is( $list_to_share->discard_changes->get_column('owner'), $designated_owner->id, 'Shared list transferred' ); # Finally test deleting lists t::lib::Mocks::mock_preference( 'ListOwnershipUponPatronDeletion', 'delete' ); Koha::Virtualshelves->delete; - my $patron2 = $builder->build_object({ class => 'Koha::Patrons' }); - my $private_list2 = Koha::Virtualshelf->new({ - shelfname => "private", - owner => $patron2->borrowernumber, - public => 0, - })->store; - my $public_list2 = Koha::Virtualshelf->new({ - shelfname => "public", - owner => $patron2->borrowernumber, - public => 1, - })->store; - my $list_to_share2 = Koha::Virtualshelf->new({ - shelfname => "shared", - owner => $patron2->borrowernumber, - public => 0, - })->store; + my $patron2 = $builder->build_object( { class => 'Koha::Patrons' } ); + my $private_list2 = Koha::Virtualshelf->new( + { + shelfname => "private", + owner => $patron2->borrowernumber, + public => 0, + } + )->store; + my $public_list2 = Koha::Virtualshelf->new( + { + shelfname => "public", + owner => $patron2->borrowernumber, + public => 1, + } + )->store; + my $list_to_share2 = Koha::Virtualshelf->new( + { + shelfname => "shared", + owner => $patron2->borrowernumber, + public => 0, + } + )->store; $list_to_share2->share("valid key")->accept( "valid key", $patron_for_sharing->borrowernumber ); # Delete patron2, check if shelves and shares are now empty $patron2->delete; - is( Koha::Virtualshelves->count, 0, 'All lists should be gone now' ); + is( Koha::Virtualshelves->count, 0, 'All lists should be gone now' ); is( Koha::Virtualshelfshares->count, 0, 'All shares should be gone too' ); }; subtest 'Koha::Patrons->delete' => sub { plan tests => 3; - my $patron1 = $builder->build_object({ class => 'Koha::Patrons' }); - my $patron2 = $builder->build_object({ class => 'Koha::Patrons' }); - my $id1 = $patron1->borrowernumber; - my $set = Koha::Patrons->search({ borrowernumber => { -in => [$patron1->borrowernumber, $patron2->borrowernumber]}}); - is( $set->count, 2, 'Two patrons found as expected' ); - is( $set->delete({ move => 1 }), 2, 'Two patrons deleted' ); - my $deleted_patrons = Koha::Old::Patrons->search({ borrowernumber => { -in => [$patron1->borrowernumber, $patron2->borrowernumber]}}); + my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } ); + my $patron2 = $builder->build_object( { class => 'Koha::Patrons' } ); + my $id1 = $patron1->borrowernumber; + my $set = Koha::Patrons->search( + { borrowernumber => { -in => [ $patron1->borrowernumber, $patron2->borrowernumber ] } } ); + is( $set->count, 2, 'Two patrons found as expected' ); + is( $set->delete( { move => 1 } ), 2, 'Two patrons deleted' ); + my $deleted_patrons = Koha::Old::Patrons->search( + { borrowernumber => { -in => [ $patron1->borrowernumber, $patron2->borrowernumber ] } } ); is( $deleted_patrons->count, 2, 'Patrons moved to deletedborrowers' ); # See other tests in t/db_dependent/Koha/Objects.t @@ -568,9 +718,11 @@ subtest 'Koha::Patrons->delete' => sub { subtest 'add_enrolment_fee_if_needed' => sub { plan tests => 4; - my $enrolmentfees = { K => 5, J => 10, YA => 20 }; - foreach( keys %{$enrolmentfees} ) { - ( Koha::Patron::Categories->find( $_ ) // $builder->build_object({ class => 'Koha::Patron::Categories', value => { categorycode => $_ } }) )->enrolmentfee( $enrolmentfees->{$_} )->store; + my $enrolmentfees = { K => 5, J => 10, YA => 20 }; + foreach ( keys %{$enrolmentfees} ) { + ( Koha::Patron::Categories->find($_) + // $builder->build_object( { class => 'Koha::Patron::Categories', value => { categorycode => $_ } } ) ) + ->enrolmentfee( $enrolmentfees->{$_} )->store; } my $enrolmentfee_K = $enrolmentfees->{K}; my $enrolmentfee_J = $enrolmentfees->{J}; @@ -583,34 +735,39 @@ subtest 'add_enrolment_fee_if_needed' => sub { branchcode => $library->{branchcode}, ); - my $borrowernumber = Koha::Patron->new(\%borrower_data)->store->borrowernumber; + my $borrowernumber = Koha::Patron->new( \%borrower_data )->store->borrowernumber; $borrower_data{borrowernumber} = $borrowernumber; - my $patron = Koha::Patrons->find( $borrowernumber ); - my $total = $patron->account->balance; + my $patron = Koha::Patrons->find($borrowernumber); + my $total = $patron->account->balance; is( int($total), int($enrolmentfee_K), "New kid pay $enrolmentfee_K" ); t::lib::Mocks::mock_preference( 'FeeOnChangePatronCategory', 0 ); $borrower_data{categorycode} = 'J'; - $patron->set(\%borrower_data)->store; + $patron->set( \%borrower_data )->store; $total = $patron->account->balance; is( int($total), int($enrolmentfee_K), "Kid growing and become a juvenile, but shouldn't pay for the upgrade " ); $borrower_data{categorycode} = 'K'; - $patron->set(\%borrower_data)->store; + $patron->set( \%borrower_data )->store; t::lib::Mocks::mock_preference( 'FeeOnChangePatronCategory', 1 ); $borrower_data{categorycode} = 'J'; - $patron->set(\%borrower_data)->store; + $patron->set( \%borrower_data )->store; $total = $patron->account->balance; - is( int($total), int($enrolmentfee_K + $enrolmentfee_J), "Kid growing and become a juvenile, they should pay " . ( $enrolmentfee_K + $enrolmentfee_J ) ); + is( + int($total), int( $enrolmentfee_K + $enrolmentfee_J ), + "Kid growing and become a juvenile, they should pay " . ( $enrolmentfee_K + $enrolmentfee_J ) + ); # Check with calling directly Koha::Patron->get_enrolment_fee_if_needed $patron->categorycode('YA')->store; $total = $patron->account->balance; - is( int($total), - int($enrolmentfee_K + $enrolmentfee_J + $enrolmentfee_YA), - "Juvenile growing and become an young adult, they should pay " . ( $enrolmentfee_K + $enrolmentfee_J + $enrolmentfee_YA ) + is( + int($total), + int( $enrolmentfee_K + $enrolmentfee_J + $enrolmentfee_YA ), + "Juvenile growing and become an young adult, they should pay " + . ( $enrolmentfee_K + $enrolmentfee_J + $enrolmentfee_YA ) ); $patron->delete; @@ -619,9 +776,9 @@ subtest 'add_enrolment_fee_if_needed' => sub { subtest 'checkouts + pending_checkouts + overdues + old_checkouts' => sub { plan tests => 19; - my $library = $builder->build( { source => 'Branch' } ); + my $library = $builder->build( { source => 'Branch' } ); my $biblionumber_1 = $builder->build_sample_biblio->biblionumber; - my $item_1 = $builder->build_sample_item( + my $item_1 = $builder->build_sample_item( { library => $library->{branchcode}, biblionumber => $biblionumber_1, @@ -634,7 +791,7 @@ subtest 'checkouts + pending_checkouts + overdues + old_checkouts' => sub { } ); my $biblionumber_2 = $builder->build_sample_biblio->biblionumber; - my $item_3 = $builder->build_sample_item( + my $item_3 = $builder->build_sample_item( { library => $library->{branchcode}, biblionumber => $biblionumber_2, @@ -649,16 +806,16 @@ subtest 'checkouts + pending_checkouts + overdues + old_checkouts' => sub { $patron = Koha::Patrons->find( $patron->{borrowernumber} ); my $checkouts = $patron->checkouts; - is( $checkouts->count, 0, 'checkouts should not return any issues for that patron' ); - is( ref($checkouts), 'Koha::Checkouts', 'checkouts should return a Koha::Checkouts object' ); + is( $checkouts->count, 0, 'checkouts should not return any issues for that patron' ); + is( ref($checkouts), 'Koha::Checkouts', 'checkouts should return a Koha::Checkouts object' ); my $pending_checkouts = $patron->pending_checkouts; is( $pending_checkouts->count, 0, 'pending_checkouts should not return any issues for that patron' ); - is( ref($pending_checkouts), 'Koha::Checkouts', 'pending_checkouts should return a Koha::Checkouts object' ); + is( ref($pending_checkouts), 'Koha::Checkouts', 'pending_checkouts should return a Koha::Checkouts object' ); my $old_checkouts = $patron->old_checkouts; - is( $old_checkouts->count, 0, 'old_checkouts should not return any issues for that patron' ); - is( ref($old_checkouts), 'Koha::Old::Checkouts', 'old_checkouts should return a Koha::Old::Checkouts object' ); + is( $old_checkouts->count, 0, 'old_checkouts should not return any issues for that patron' ); + is( ref($old_checkouts), 'Koha::Old::Checkouts', 'old_checkouts should return a Koha::Old::Checkouts object' ); - t::lib::Mocks::mock_userenv({ branchcode => $library->{branchcode} }); + t::lib::Mocks::mock_userenv( { branchcode => $library->{branchcode} } ); my $issue_1 = AddIssue( $patron, $item_1->barcode, dt_from_string()->subtract( days => 1 ), undef, @@ -694,20 +851,28 @@ subtest 'checkouts + pending_checkouts + overdues + old_checkouts' => sub { ); my $first_checkout = $pending_checkouts->next; - is( $first_checkout->unblessed_all_relateds->{biblionumber}, $item_2->biblionumber, 'pending_checkouts should prefetch values from other tables (here biblio)' ); + is( + $first_checkout->unblessed_all_relateds->{biblionumber}, $item_2->biblionumber, + 'pending_checkouts should prefetch values from other tables (here biblio)' + ); my $overdues = $patron->overdues; - is( $overdues->count, 2, 'Patron should have 2 overdues'); - is( ref($overdues), 'Koha::Checkouts', 'Koha::Patron->overdues should return Koha::Checkouts' ); - is( $overdues->next->itemnumber, $item_1->itemnumber, 'The issue should be returned in the same order as they have been done, first is correct' ); - is( $overdues->next->itemnumber, $item_2->itemnumber, 'The issue should be returned in the same order as they have been done, second is correct' ); - + is( $overdues->count, 2, 'Patron should have 2 overdues' ); + is( ref($overdues), 'Koha::Checkouts', 'Koha::Patron->overdues should return Koha::Checkouts' ); + is( + $overdues->next->itemnumber, $item_1->itemnumber, + 'The issue should be returned in the same order as they have been done, first is correct' + ); + is( + $overdues->next->itemnumber, $item_2->itemnumber, + 'The issue should be returned in the same order as they have been done, second is correct' + ); C4::Circulation::AddReturn( $item_1->barcode ); C4::Circulation::AddReturn( $item_2->barcode ); $old_checkouts = $patron->old_checkouts; - is( $old_checkouts->count, 2, 'old_checkouts should return 2 old checkouts that patron' ); - is( ref($old_checkouts), 'Koha::Old::Checkouts', 'old_checkouts should return a Koha::Old::Checkouts object' ); + is( $old_checkouts->count, 2, 'old_checkouts should return 2 old checkouts that patron' ); + is( ref($old_checkouts), 'Koha::Old::Checkouts', 'old_checkouts should return a Koha::Old::Checkouts object' ); # Clean stuffs Koha::Checkouts->search( { borrowernumber => $patron->borrowernumber } )->delete; @@ -717,9 +882,10 @@ subtest 'checkouts + pending_checkouts + overdues + old_checkouts' => sub { subtest 'get_routing_lists' => sub { plan tests => 5; - my $biblio = Koha::Biblio->new()->store(); - my $subscription = Koha::Subscription->new({ - biblionumber => $biblio->biblionumber, + my $biblio = Koha::Biblio->new()->store(); + my $subscription = Koha::Subscription->new( + { + biblionumber => $biblio->biblionumber, } )->store; @@ -729,31 +895,39 @@ subtest 'get_routing_lists' => sub { is( $patron->get_routing_lists->count, 0, 'Retrieves correct number of routing lists: 0' ); my $routinglist_count = Koha::Subscription::Routinglists->count; - my $routinglist = Koha::Subscription::Routinglist->new({ - borrowernumber => $patron->borrowernumber, - ranking => 5, - subscriptionid => $subscription->subscriptionid - })->store; - - is ($patron->get_routing_lists->count, 1, "Retrieves correct number of routing lists: 1"); - - my $routinglists = $patron->get_routing_lists; - is ($routinglists->next->ranking, 5, "Retrieves ranking: 5"); - is( ref($routinglists), 'Koha::Subscription::Routinglists', 'get_routing_lists returns Koha::Subscription::Routinglists' ); - - my $subscription2 = Koha::Subscription->new({ - biblionumber => $biblio->biblionumber, + my $routinglist = Koha::Subscription::Routinglist->new( + { + borrowernumber => $patron->borrowernumber, + ranking => 5, + subscriptionid => $subscription->subscriptionid } )->store; - my $routinglist2 = Koha::Subscription::Routinglist->new({ - borrowernumber => $patron->borrowernumber, - ranking => 1, - subscriptionid => $subscription2->subscriptionid - })->store; - is ($patron->get_routing_lists->count, 2, "Retrieves correct number of routing lists: 2"); + is( $patron->get_routing_lists->count, 1, "Retrieves correct number of routing lists: 1" ); - $patron->delete; # Clean up for later tests + my $routinglists = $patron->get_routing_lists; + is( $routinglists->next->ranking, 5, "Retrieves ranking: 5" ); + is( + ref($routinglists), 'Koha::Subscription::Routinglists', + 'get_routing_lists returns Koha::Subscription::Routinglists' + ); + + my $subscription2 = Koha::Subscription->new( + { + biblionumber => $biblio->biblionumber, + } + )->store; + my $routinglist2 = Koha::Subscription::Routinglist->new( + { + borrowernumber => $patron->borrowernumber, + ranking => 1, + subscriptionid => $subscription2->subscriptionid + } + )->store; + + is( $patron->get_routing_lists->count, 2, "Retrieves correct number of routing lists: 2" ); + + $patron->delete; # Clean up for later tests }; @@ -813,12 +987,12 @@ subtest 'get_age' => sub { }, ); - $patron->dateofbirth( undef ); + $patron->dateofbirth(undef); is( $patron->get_age, undef, 'get_age should return undef if no dateofbirth is defined' ); - for my $date ( @dates ) { + for my $date (@dates) { - my $dt = dt_from_string($date->{today}); + my $dt = dt_from_string( $date->{today} ); Time::Fake->offset( $dt->epoch ); @@ -859,55 +1033,47 @@ subtest 'is_valid_age' => sub { Time::Fake->offset( $dt->epoch ); - my $category = $builder->build({ - source => 'Category', - value => { - categorycode => 'AGE_5_10', - dateofbirthrequired => 5, - upperagelimit => 10 + my $category = $builder->build( + { + source => 'Category', + value => { + categorycode => 'AGE_5_10', + dateofbirthrequired => 5, + upperagelimit => 10 + } } - }); + ); $category = Koha::Patron::Categories->find( $category->{categorycode} ); - my $patron = $builder->build({ - source => 'Borrower', - value => { - categorycode => $category->categorycode + my $patron = $builder->build( + { + source => 'Borrower', + value => { categorycode => $category->categorycode } } - }); + ); $patron = Koha::Patrons->find( $patron->{borrowernumber} ); - - $patron->dateofbirth( undef ); - is( $patron->is_valid_age, 1, 'Patron with no dateofbirth is always valid for any category'); + $patron->dateofbirth(undef); + is( $patron->is_valid_age, 1, 'Patron with no dateofbirth is always valid for any category' ); my @dates = ( { - today => '2020-02-28', - add_m12_m6_m1 => - { date => '2007-08-27', expected_age => 12, valid => 0 }, - add_m3_m6_m1 => - { date => '2016-08-27', expected_age => 3, valid => 0 }, - add_m7_m6_m1 => - { date => '2013-02-28', expected_age => 7, valid => 1 }, - add_m5_0_0 => - { date => '2015-02-28', expected_age => 5, valid => 1 }, - add_m5_0_p1 => - { date => '2015-03-01', expected_age => 4, valid => 0 }, - add_m5_0_m1 => - { date => '2015-02-27', expected_age => 5, valid => 1 }, - add_m11_0_0 => - { date => '2009-02-28', expected_age => 11, valid => 0 }, - add_m11_0_p1 => - { date => '2009-03-01', expected_age => 10, valid => 1 }, - add_m11_0_m1 => - { date => '2009-02-27', expected_age => 11, valid => 0 }, + today => '2020-02-28', + add_m12_m6_m1 => { date => '2007-08-27', expected_age => 12, valid => 0 }, + add_m3_m6_m1 => { date => '2016-08-27', expected_age => 3, valid => 0 }, + add_m7_m6_m1 => { date => '2013-02-28', expected_age => 7, valid => 1 }, + add_m5_0_0 => { date => '2015-02-28', expected_age => 5, valid => 1 }, + add_m5_0_p1 => { date => '2015-03-01', expected_age => 4, valid => 0 }, + add_m5_0_m1 => { date => '2015-02-27', expected_age => 5, valid => 1 }, + add_m11_0_0 => { date => '2009-02-28', expected_age => 11, valid => 0 }, + add_m11_0_p1 => { date => '2009-03-01', expected_age => 10, valid => 1 }, + add_m11_0_m1 => { date => '2009-02-27', expected_age => 11, valid => 0 }, }, ); - for my $date ( @dates ) { + for my $date (@dates) { - my $dt = dt_from_string($date->{today}); + my $dt = dt_from_string( $date->{today} ); Time::Fake->offset( $dt->epoch ); @@ -940,11 +1106,11 @@ subtest 'is_valid_age' => sub { subtest 'account' => sub { plan tests => 1; - my $patron = $builder->build({source => 'Borrower'}); + my $patron = $builder->build( { source => 'Borrower' } ); $patron = Koha::Patrons->find( $patron->{borrowernumber} ); my $account = $patron->account; - is( ref($account), 'Koha::Account', 'account should return a Koha::Account object' ); + is( ref($account), 'Koha::Account', 'account should return a Koha::Account object' ); $patron->delete; }; @@ -955,78 +1121,110 @@ subtest 'search_upcoming_membership_expires' => sub { my $expiry_days = 15; t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', $expiry_days ); my $nb_of_days_before = 1; - my $nb_of_days_after = 2; + my $nb_of_days_after = 2; my $builder = t::lib::TestBuilder->new(); - my $library = $builder->build({ source => 'Branch' }); + my $library = $builder->build( { source => 'Branch' } ); # before we add borrowers to this branch, add the expires we have now # note that this pertains to the current mocked setting of the pref # for this reason we add the new branchcode to most of the tests my $nb_of_expires = Koha::Patrons->search_upcoming_membership_expires->count; - my $patron_1 = $builder->build({ - source => 'Borrower', - value => { - branchcode => $library->{branchcode}, - dateexpiry => dt_from_string->add( days => $expiry_days ) - }, - }); + my $patron_1 = $builder->build( + { + source => 'Borrower', + value => { + branchcode => $library->{branchcode}, + dateexpiry => dt_from_string->add( days => $expiry_days ) + }, + } + ); - my $patron_2 = $builder->build({ - source => 'Borrower', - value => { - branchcode => $library->{branchcode}, - dateexpiry => dt_from_string->add( days => $expiry_days - $nb_of_days_before ) - }, - }); + my $patron_2 = $builder->build( + { + source => 'Borrower', + value => { + branchcode => $library->{branchcode}, + dateexpiry => dt_from_string->add( days => $expiry_days - $nb_of_days_before ) + }, + } + ); - my $patron_3 = $builder->build({ - source => 'Borrower', - value => { - branchcode => $library->{branchcode}, - dateexpiry => dt_from_string->add( days => $expiry_days + $nb_of_days_after ) - }, - }); + my $patron_3 = $builder->build( + { + source => 'Borrower', + value => { + branchcode => $library->{branchcode}, + dateexpiry => dt_from_string->add( days => $expiry_days + $nb_of_days_after ) + }, + } + ); # Test without extra parameters my $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires(); - is( $upcoming_mem_expires->count, $nb_of_expires + 1, 'Get upcoming membership expires should return one new borrower.' ); + is( + $upcoming_mem_expires->count, $nb_of_expires + 1, + 'Get upcoming membership expires should return one new borrower.' + ); # Test with branch - $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} }); + $upcoming_mem_expires = + Koha::Patrons->search_upcoming_membership_expires( { 'me.branchcode' => $library->{branchcode} } ); is( $upcoming_mem_expires->count, 1, 'Test with branch parameter' ); my $expired = $upcoming_mem_expires->next; is( $expired->surname, $patron_1->{surname}, 'Get upcoming membership expires should return the correct patron.' ); - is( $expired->library->branchemail, $library->{branchemail}, 'Get upcoming membership expires should return the correct patron.' ); - is( $expired->branchcode, $patron_1->{branchcode}, 'Get upcoming membership expires should return the correct patron.' ); + is( + $expired->library->branchemail, $library->{branchemail}, + 'Get upcoming membership expires should return the correct patron.' + ); + is( + $expired->branchcode, $patron_1->{branchcode}, + 'Get upcoming membership expires should return the correct patron.' + ); t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', 0 ); - $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} }); - is( $upcoming_mem_expires->count, 0, 'Get upcoming membership expires with MembershipExpiryDaysNotice==0 should not return new records.' ); + $upcoming_mem_expires = + Koha::Patrons->search_upcoming_membership_expires( { 'me.branchcode' => $library->{branchcode} } ); + is( + $upcoming_mem_expires->count, 0, + 'Get upcoming membership expires with MembershipExpiryDaysNotice==0 should not return new records.' + ); # Test MembershipExpiryDaysNotice == undef t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', undef ); - $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode} }); - is( $upcoming_mem_expires->count, 0, 'Get upcoming membership expires without MembershipExpiryDaysNotice should not return new records.' ); + $upcoming_mem_expires = + Koha::Patrons->search_upcoming_membership_expires( { 'me.branchcode' => $library->{branchcode} } ); + is( + $upcoming_mem_expires->count, 0, + 'Get upcoming membership expires without MembershipExpiryDaysNotice should not return new records.' + ); # Test the before parameter t::lib::Mocks::mock_preference( 'MembershipExpiryDaysNotice', 15 ); - $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode}, before => $nb_of_days_before }); - is( $upcoming_mem_expires->count, 2, 'Expect two results for before'); + $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires( + { 'me.branchcode' => $library->{branchcode}, before => $nb_of_days_before } ); + is( $upcoming_mem_expires->count, 2, 'Expect two results for before' ); + # Test after parameter also - $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires({ 'me.branchcode' => $library->{branchcode}, before => $nb_of_days_before, after => $nb_of_days_after }); + $upcoming_mem_expires = Koha::Patrons->search_upcoming_membership_expires( + { 'me.branchcode' => $library->{branchcode}, before => $nb_of_days_before, after => $nb_of_days_after } ); is( $upcoming_mem_expires->count, 3, 'Expect three results when adding after' ); - Koha::Patrons->search({ borrowernumber => { in => [ $patron_1->{borrowernumber}, $patron_2->{borrowernumber}, $patron_3->{borrowernumber} ] } })->delete; + Koha::Patrons->search( + { + borrowernumber => + { in => [ $patron_1->{borrowernumber}, $patron_2->{borrowernumber}, $patron_3->{borrowernumber} ] } + } + )->delete; }; subtest 'holds and old_holds' => sub { plan tests => 6; - my $library = $builder->build( { source => 'Branch' } ); + my $library = $builder->build( { source => 'Branch' } ); my $biblionumber_1 = $builder->build_sample_biblio->biblionumber; - my $item_1 = $builder->build_sample_item( + my $item_1 = $builder->build_sample_item( { library => $library->{branchcode}, biblionumber => $biblionumber_1, @@ -1039,7 +1237,7 @@ subtest 'holds and old_holds' => sub { } ); my $biblionumber_2 = $builder->build_sample_biblio->biblionumber; - my $item_3 = $builder->build_sample_item( + my $item_3 = $builder->build_sample_item( { library => $library->{branchcode}, biblionumber => $biblionumber_2, @@ -1055,8 +1253,10 @@ subtest 'holds and old_holds' => sub { $patron = Koha::Patrons->find( $patron->{borrowernumber} ); my $holds = $patron->holds; - is( ref($holds), 'Koha::Holds', - 'Koha::Patron->holds should return a Koha::Holds objects' ); + is( + ref($holds), 'Koha::Holds', + 'Koha::Patron->holds should return a Koha::Holds objects' + ); is( $holds->count, 0, 'There should not be holds placed by this patron yet' ); C4::Reserves::AddReserve( @@ -1066,6 +1266,7 @@ subtest 'holds and old_holds' => sub { biblionumber => $biblionumber_1 } ); + # In the future C4::Reserves::AddReserve( { @@ -1080,15 +1281,17 @@ subtest 'holds and old_holds' => sub { is( $holds->count, 2, 'There should be 2 holds placed by this patron' ); my $old_holds = $patron->old_holds; - is( ref($old_holds), 'Koha::Old::Holds', - 'Koha::Patron->old_holds should return a Koha::Old::Holds objects' ); - is( $old_holds->count, 0, 'There should not be any old holds yet'); + is( + ref($old_holds), 'Koha::Old::Holds', + 'Koha::Patron->old_holds should return a Koha::Old::Holds objects' + ); + is( $old_holds->count, 0, 'There should not be any old holds yet' ); my $hold = $holds->next; $hold->cancel; $old_holds = $patron->old_holds; - is( $old_holds->count, 1, 'There should be 1 old (cancelled) hold'); + is( $old_holds->count, 1, 'There should be 1 old (cancelled) hold' ); $old_holds->delete; $holds->delete; @@ -1100,12 +1303,14 @@ subtest 'search_patrons_to_anonymise' => sub { plan tests => 5; # TODO create a subroutine in t::lib::Mocks - my $branch = $builder->build({ source => 'Branch' }); - my $userenv_patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { branchcode => $branch->{branchcode}, flags => 0 }, - }); - t::lib::Mocks::mock_userenv({ patron => $userenv_patron }); + my $branch = $builder->build( { source => 'Branch' } ); + my $userenv_patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { branchcode => $branch->{branchcode}, flags => 0 }, + } + ); + t::lib::Mocks::mock_userenv( { patron => $userenv_patron } ); my $anonymous = $builder->build( { source => 'Borrower', }, ); @@ -1116,7 +1321,7 @@ subtest 'search_patrons_to_anonymise' => sub { my $anonymous_patron = Koha::Patrons->find( $anonymous->{borrowernumber} ); throws_ok { $anonymous_patron->delete(); } - 'Koha::Exceptions::Patron::FailedDeleteAnonymousPatron', + 'Koha::Exceptions::Patron::FailedDeleteAnonymousPatron', 'Attempt to delete anonymous patron throws exception.'; $anonymous_patron = Koha::Patrons->find( $anonymous->{borrowernumber} ); is( $anonymous_patron->id, $anonymous->{borrowernumber}, "Anonymous Patron was not deleted" ); @@ -1125,24 +1330,27 @@ subtest 'search_patrons_to_anonymise' => sub { subtest 'patron privacy is 1 (default)' => sub { plan tests => 9; - t::lib::Mocks::mock_preference('IndependentBranches', 0); + t::lib::Mocks::mock_preference( 'IndependentBranches', 0 ); my $patron = $builder->build( - { source => 'Borrower', + { + source => 'Borrower', value => { privacy => 1, } } ); - my $item_1 = $builder->build_sample_item; + my $item_1 = $builder->build_sample_item; my $issue_1 = $builder->build( - { source => 'Issue', + { + source => 'Issue', value => { borrowernumber => $patron->{borrowernumber}, itemnumber => $item_1->itemnumber, }, } ); - my $item_2 = $builder->build_sample_item; + my $item_2 = $builder->build_sample_item; my $issue_2 = $builder->build( - { source => 'Issue', + { + source => 'Issue', value => { borrowernumber => $patron->{borrowernumber}, itemnumber => $item_2->itemnumber, @@ -1150,19 +1358,21 @@ subtest 'search_patrons_to_anonymise' => sub { } ); - my ( $returned_1, undef, undef ) = C4::Circulation::AddReturn( $item_1->barcode, undef, undef, dt_from_string('2010-10-10') ); - my ( $returned_2, undef, undef ) = C4::Circulation::AddReturn( $item_2->barcode, undef, undef, dt_from_string('2011-11-11') ); + my ( $returned_1, undef, undef ) = + C4::Circulation::AddReturn( $item_1->barcode, undef, undef, dt_from_string('2010-10-10') ); + my ( $returned_2, undef, undef ) = + C4::Circulation::AddReturn( $item_2->barcode, undef, undef, dt_from_string('2011-11-11') ); is( $returned_1 && $returned_2, 1, 'The items should have been returned' ); - my $patrons_to_anonymise = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->search( { 'me.borrowernumber' => $patron->{borrowernumber} } ); + my $patrons_to_anonymise = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } ) + ->search( { 'me.borrowernumber' => $patron->{borrowernumber} } ); is( ref($patrons_to_anonymise), 'Koha::Patrons', 'search_patrons_to_anonymise should return Koha::Patrons' ); my $rows_affected = Koha::Old::Checkouts->search( { borrowernumber => [ - Koha::Patrons->search_patrons_to_anonymise( - { before => '2011-11-12' } - )->get_column('borrowernumber') + Koha::Patrons->search_patrons_to_anonymise( { before => '2011-11-12' } ) + ->get_column('borrowernumber') ], returndate => { '<' => '2011-10-11', } } @@ -1170,64 +1380,78 @@ subtest 'search_patrons_to_anonymise' => sub { ok( $rows_affected > 0, 'AnonymiseIssueHistory should affect at least 1 row' ); $patrons_to_anonymise = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } ); - is( $patrons_to_anonymise->count, 0, 'search_patrons_to_anonymise should return 0 after anonymisation is done' ); + is( + $patrons_to_anonymise->count, 0, + 'search_patrons_to_anonymise should return 0 after anonymisation is done' + ); my $dbh = C4::Context->dbh; my $sth = $dbh->prepare(q|SELECT borrowernumber FROM old_issues where itemnumber = ?|); - $sth->execute($item_1->itemnumber); + $sth->execute( $item_1->itemnumber ); my ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array; - is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'With privacy=1, the issue should have been anonymised' ); - $sth->execute($item_2->itemnumber); + is( + $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, + 'With privacy=1, the issue should have been anonymised' + ); + $sth->execute( $item_2->itemnumber ); ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array; - is( $borrowernumber_used_to_anonymised, $patron->{borrowernumber}, 'The issue should not have been anonymised, the returned date is later' ); + is( + $borrowernumber_used_to_anonymised, $patron->{borrowernumber}, + 'The issue should not have been anonymised, the returned date is later' + ); $rows_affected = Koha::Old::Checkouts->search( { borrowernumber => [ - Koha::Patrons->search_patrons_to_anonymise( - { before => '2011-11-12' } - )->get_column('borrowernumber') + Koha::Patrons->search_patrons_to_anonymise( { before => '2011-11-12' } ) + ->get_column('borrowernumber') ], returndate => { '<' => '2011-11-12', } } )->anonymize; - $sth->execute($item_2->itemnumber); + $sth->execute( $item_2->itemnumber ); ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array; - is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue should have been anonymised, the returned date is before' ); + is( + $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, + 'The issue should have been anonymised, the returned date is before' + ); my $sth_reset = $dbh->prepare(q|UPDATE old_issues SET borrowernumber = ? WHERE itemnumber = ?|); $sth_reset->execute( $patron->{borrowernumber}, $item_1->itemnumber ); $sth_reset->execute( $patron->{borrowernumber}, $item_2->itemnumber ); $rows_affected = Koha::Old::Checkouts->search( - { - borrowernumber => [ - Koha::Patrons->search_patrons_to_anonymise->get_column( - 'borrowernumber') - ] - } - )->anonymize; - $sth->execute($item_1->itemnumber); + { borrowernumber => [ Koha::Patrons->search_patrons_to_anonymise->get_column('borrowernumber') ] } ) + ->anonymize; + $sth->execute( $item_1->itemnumber ); ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array; - is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue 1 should have been anonymised, before parameter was not passed' ); - $sth->execute($item_2->itemnumber); + is( + $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, + 'The issue 1 should have been anonymised, before parameter was not passed' + ); + $sth->execute( $item_2->itemnumber ); ($borrowernumber_used_to_anonymised) = $sth->fetchrow_array; - is( $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, 'The issue 2 should have been anonymised, before parameter was not passed' ); + is( + $borrowernumber_used_to_anonymised, $anonymous->{borrowernumber}, + 'The issue 2 should have been anonymised, before parameter was not passed' + ); - Koha::Patrons->find( $patron->{borrowernumber})->delete; + Koha::Patrons->find( $patron->{borrowernumber} )->delete; }; subtest 'patron privacy is 0 (forever)' => sub { plan tests => 2; - t::lib::Mocks::mock_preference('IndependentBranches', 0); + t::lib::Mocks::mock_preference( 'IndependentBranches', 0 ); my $patron = $builder->build( - { source => 'Borrower', + { + source => 'Borrower', value => { privacy => 0, } } ); - my $item = $builder->build_sample_item; + my $item = $builder->build_sample_item; my $issue = $builder->build( - { source => 'Issue', + { + source => 'Issue', value => { borrowernumber => $patron->{borrowernumber}, itemnumber => $item->itemnumber, @@ -1235,15 +1459,21 @@ subtest 'search_patrons_to_anonymise' => sub { } ); - my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->barcode, undef, undef, dt_from_string('2010-10-10') ); + my ( $returned, undef, undef ) = + C4::Circulation::AddReturn( $item->barcode, undef, undef, dt_from_string('2010-10-10') ); is( $returned, 1, 'The item should have been returned' ); my $dbh = C4::Context->dbh; - my ($borrowernumber_used_to_anonymised) = $dbh->selectrow_array(q| + my ($borrowernumber_used_to_anonymised) = $dbh->selectrow_array( + q| SELECT borrowernumber FROM old_issues where itemnumber = ? - |, undef, $item->itemnumber); - is( $borrowernumber_used_to_anonymised, $patron->{borrowernumber}, 'With privacy=0, the issue should not be anonymised' ); - Koha::Patrons->find( $patron->{borrowernumber})->delete; + |, undef, $item->itemnumber + ); + is( + $borrowernumber_used_to_anonymised, $patron->{borrowernumber}, + 'With privacy=0, the issue should not be anonymised' + ); + Koha::Patrons->find( $patron->{borrowernumber} )->delete; }; t::lib::Mocks::mock_preference( 'AnonymousPatron', '' ); @@ -1252,15 +1482,17 @@ subtest 'search_patrons_to_anonymise' => sub { plan tests => 2; - t::lib::Mocks::mock_preference('IndependentBranches', 0); + t::lib::Mocks::mock_preference( 'IndependentBranches', 0 ); my $patron = $builder->build( - { source => 'Borrower', + { + source => 'Borrower', value => { privacy => 1, } } ); - my $item = $builder->build_sample_item; + my $item = $builder->build_sample_item; my $issue = $builder->build( - { source => 'Issue', + { + source => 'Issue', value => { borrowernumber => $patron->{borrowernumber}, itemnumber => $item->itemnumber, @@ -1268,25 +1500,28 @@ subtest 'search_patrons_to_anonymise' => sub { } ); - my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->barcode, undef, undef, dt_from_string('2010-10-10') ); + my ( $returned, undef, undef ) = + C4::Circulation::AddReturn( $item->barcode, undef, undef, dt_from_string('2010-10-10') ); is( $returned, 1, 'The item should have been returned' ); my $patrons_to_anonymize = Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } ); ok( $patrons_to_anonymize->count > 0, 'search_patrons_to_anonymize' ); - Koha::Patrons->find( $patron->{borrowernumber})->delete; + Koha::Patrons->find( $patron->{borrowernumber} )->delete; }; subtest 'Logged in librarian is not superlibrarian & IndependentBranches' => sub { plan tests => 1; t::lib::Mocks::mock_preference( 'IndependentBranches', 1 ); my $patron = $builder->build( - { source => 'Borrower', + { + source => 'Borrower', value => { privacy => 1 } # Another branchcode than the logged in librarian } ); - my $item = $builder->build_sample_item; + my $item = $builder->build_sample_item; my $issue = $builder->build( - { source => 'Issue', + { + source => 'Issue', value => { borrowernumber => $patron->{borrowernumber}, itemnumber => $item->itemnumber, @@ -1294,16 +1529,17 @@ subtest 'search_patrons_to_anonymise' => sub { } ); - my ( $returned, undef, undef ) = C4::Circulation::AddReturn( $item->barcode, undef, undef, dt_from_string('2010-10-10') ); + my ( $returned, undef, undef ) = + C4::Circulation::AddReturn( $item->barcode, undef, undef, dt_from_string('2010-10-10') ); is( Koha::Patrons->search_patrons_to_anonymise( { before => '2010-10-11' } )->count, 0 ); - Koha::Patrons->find( $patron->{borrowernumber})->delete; + Koha::Patrons->find( $patron->{borrowernumber} )->delete; }; - Koha::Patrons->find( $anonymous->{borrowernumber})->delete; + Koha::Patrons->find( $anonymous->{borrowernumber} )->delete; $userenv_patron->delete; # Reset IndependentBranches for further tests - t::lib::Mocks::mock_preference('IndependentBranches', 0); + t::lib::Mocks::mock_preference( 'IndependentBranches', 0 ); }; subtest @@ -1330,6 +1566,7 @@ subtest Koha::Library::Group->new( { branchcode => $library_11->branchcode, parent_id => $group_1->id } )->store; Koha::Library::Group->new( { branchcode => $library_12->branchcode, parent_id => $group_1->id } )->store; Koha::Library::Group->new( { branchcode => $library_21->branchcode, parent_id => $group_2->id } )->store; + # Library 31, not in any group my $sth = @@ -1523,10 +1760,10 @@ subtest subtest 'account_locked' => sub { plan tests => 13; - my $patron = $builder->build({ source => 'Borrower', value => { login_attempts => 0 } }); + my $patron = $builder->build( { source => 'Borrower', value => { login_attempts => 0 } } ); $patron = Koha::Patrons->find( $patron->{borrowernumber} ); for my $value ( undef, '', 0 ) { - t::lib::Mocks::mock_preference('FailedloginAttempts', $value); + t::lib::Mocks::mock_preference( 'FailedloginAttempts', $value ); $patron->login_attempts(0)->store; is( $patron->account_locked, 0, 'Feature is disabled, patron account should not be considered locked' ); $patron->login_attempts(1)->store; @@ -1535,13 +1772,16 @@ subtest 'account_locked' => sub { is( $patron->account_locked, 1, 'Feature is disabled but administrative lockout has been triggered' ); } - t::lib::Mocks::mock_preference('FailedloginAttempts', 3); + t::lib::Mocks::mock_preference( 'FailedloginAttempts', 3 ); $patron->login_attempts(2)->store; is( $patron->account_locked, 0, 'Patron has 2 failed attempts, account should not be considered locked yet' ); $patron->login_attempts(3)->store; is( $patron->account_locked, 1, 'Patron has 3 failed attempts, account should be considered locked yet' ); $patron->login_attempts(4)->store; - is( $patron->account_locked, 1, 'Patron could not have 4 failed attempts, but account should still be considered locked' ); + is( + $patron->account_locked, 1, + 'Patron could not have 4 failed attempts, but account should still be considered locked' + ); $patron->login_attempts(-1)->store; is( $patron->account_locked, 1, 'Administrative lockout triggered' ); @@ -1633,9 +1873,9 @@ subtest 'is_child | is_adult' => sub { subtest 'overdues' => sub { plan tests => 7; - my $library = $builder->build( { source => 'Branch' } ); + my $library = $builder->build( { source => 'Branch' } ); my $biblionumber_1 = $builder->build_sample_biblio->biblionumber; - my $item_1 = $builder->build_sample_item( + my $item_1 = $builder->build_sample_item( { library => $library->{branchcode}, biblionumber => $biblionumber_1, @@ -1649,7 +1889,7 @@ subtest 'overdues' => sub { ); my $item_3 = $builder->build_sample_item( { - library => $library->{branchcode}, + library => $library->{branchcode}, } ); @@ -1660,7 +1900,7 @@ subtest 'overdues' => sub { } ); - t::lib::Mocks::mock_preference({ branchcode => $library->{branchcode} }); + t::lib::Mocks::mock_preference( { branchcode => $library->{branchcode} } ); $patron = Koha::Patrons->find( $patron->{borrowernumber} ); @@ -1669,16 +1909,22 @@ subtest 'overdues' => sub { AddIssue( $patron, $item_3->barcode ); my $overdues = $patron->overdues; - is( $overdues->count, 2, 'Patron should have 2 overdues'); - is( $overdues->next->itemnumber, $item_1->itemnumber, 'The issue should be returned in the same order as they have been done, first is correct' ); - is( $overdues->next->itemnumber, $item_2->itemnumber, 'The issue should be returned in the same order as they have been done, second is correct' ); + is( $overdues->count, 2, 'Patron should have 2 overdues' ); + is( + $overdues->next->itemnumber, $item_1->itemnumber, + 'The issue should be returned in the same order as they have been done, first is correct' + ); + is( + $overdues->next->itemnumber, $item_2->itemnumber, + 'The issue should be returned in the same order as they have been done, second is correct' + ); - my $o = $overdues->reset->next; + my $o = $overdues->reset->next; my $unblessed_overdue = $o->unblessed_all_relateds; - is( exists( $unblessed_overdue->{issuedate} ), 1, 'Fields from the issues table should be filled' ); + is( exists( $unblessed_overdue->{issuedate} ), 1, 'Fields from the issues table should be filled' ); is( exists( $unblessed_overdue->{itemcallnumber} ), 1, 'Fields from the items table should be filled' ); - is( exists( $unblessed_overdue->{title} ), 1, 'Fields from the biblio table should be filled' ); - is( exists( $unblessed_overdue->{itemtype} ), 1, 'Fields from the biblioitems table should be filled' ); + is( exists( $unblessed_overdue->{title} ), 1, 'Fields from the biblio table should be filled' ); + is( exists( $unblessed_overdue->{itemtype} ), 1, 'Fields from the biblioitems table should be filled' ); # Clean stuffs $patron->checkouts->delete; @@ -1688,7 +1934,7 @@ subtest 'overdues' => sub { subtest 'userid_is_valid' => sub { plan tests => 9; - my $library = $builder->build_object( { class => 'Koha::Libraries' } ); + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); my $patron_category = $builder->build_object( { class => 'Koha::Patron::Categories', @@ -1704,48 +1950,62 @@ subtest 'userid_is_valid' => sub { ); my $expected_userid_patron_1 = 'tomasito.none'; - my $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber; - my $patron_1 = Koha::Patrons->find($borrowernumber); - is( $patron_1->has_valid_userid, 1, "Should be valid when compared against them self" ); - is ( $patron_1->userid, $expected_userid_patron_1, 'The userid generated should be the one we expect' ); + my $borrowernumber = Koha::Patron->new( \%data )->store->borrowernumber; + my $patron_1 = Koha::Patrons->find($borrowernumber); + is( $patron_1->has_valid_userid, 1, "Should be valid when compared against them self" ); + is( $patron_1->userid, $expected_userid_patron_1, 'The userid generated should be the one we expect' ); - $patron_1->userid( 'tomasito.non' ); - is( $patron_1->has_valid_userid, # FIXME Joubu: What is the difference with the next test? - 1, 'recently created userid -> unique (borrowernumber passed)' ); + $patron_1->userid('tomasito.non'); + is( + $patron_1->has_valid_userid, # FIXME Joubu: What is the difference with the next test? + 1, 'recently created userid -> unique (borrowernumber passed)' + ); - $patron_1->userid( 'tomasitoxxx' ); - is( $patron_1->has_valid_userid, - 1, 'non-existent userid -> unique (borrowernumber passed)' ); - $patron_1->discard_changes; # We compare with the original userid later + $patron_1->userid('tomasitoxxx'); + is( + $patron_1->has_valid_userid, + 1, 'non-existent userid -> unique (borrowernumber passed)' + ); + $patron_1->discard_changes; # We compare with the original userid later my $patron_not_in_storage = Koha::Patron->new( { userid => '' } ); - is( $patron_not_in_storage->has_valid_userid, - 0, 'userid exists for another patron, patron is not in storage yet' ); + is( + $patron_not_in_storage->has_valid_userid, + 0, 'userid exists for another patron, patron is not in storage yet' + ); $patron_not_in_storage = Koha::Patron->new( { userid => 'tomasitoxxx' } ); - is( $patron_not_in_storage->has_valid_userid, - 1, 'non-existent userid, patron is not in storage yet' ); + is( + $patron_not_in_storage->has_valid_userid, + 1, 'non-existent userid, patron is not in storage yet' + ); # Regression tests for BZ12226 my $db_patron = Koha::Patron->new( { userid => C4::Context->config('user') } ); - is( $db_patron->has_valid_userid, - 0, 'Koha::Patron->has_valid_userid should return 0 for the DB user (Bug 12226)' ); + is( + $db_patron->has_valid_userid, + 0, 'Koha::Patron->has_valid_userid should return 0 for the DB user (Bug 12226)' + ); # Add a new borrower with the same userid but different cardnumber $data{cardnumber} = "987654321"; - my $new_borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber; - my $patron_2 = Koha::Patrons->find($new_borrowernumber); - $patron_2->userid($patron_1->userid); - is( $patron_2->has_valid_userid, - 0, 'The userid is already in used, it cannot be used for another patron' ); + my $new_borrowernumber = Koha::Patron->new( \%data )->store->borrowernumber; + my $patron_2 = Koha::Patrons->find($new_borrowernumber); + $patron_2->userid( $patron_1->userid ); + is( + $patron_2->has_valid_userid, + 0, 'The userid is already in used, it cannot be used for another patron' + ); my $new_userid = 'a_user_id'; $data{cardnumber} = "234567890"; $data{userid} = 'a_user_id'; - $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber; + $borrowernumber = Koha::Patron->new( \%data )->store->borrowernumber; my $patron_3 = Koha::Patrons->find($borrowernumber); - is( $patron_3->userid, $new_userid, - 'Koha::Patron->store should insert the given userid' ); + is( + $patron_3->userid, $new_userid, + 'Koha::Patron->store should insert the given userid' + ); # Cleanup $patron_1->delete; @@ -1764,19 +2024,21 @@ subtest 'BorrowersLog tests' => sub { my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $cardnumber = $patron->cardnumber; - $patron->set( { cardnumber => 'TESTCARDNUMBER' }); + $patron->set( { cardnumber => 'TESTCARDNUMBER' } ); $patron->store; - my @logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'MODIFY', object => $patron->borrowernumber } ); + my @logs = $schema->resultset('ActionLog') + ->search( { module => 'MEMBERS', action => 'MODIFY', object => $patron->borrowernumber } ); my $log_info = from_json( $logs[0]->info ); - is( $log_info->{cardnumber}->{after}, 'TESTCARDNUMBER', 'Got correct new cardnumber' ); - is( $log_info->{cardnumber}->{before}, $cardnumber, 'Got correct old cardnumber' ); + is( $log_info->{cardnumber}->{after}, 'TESTCARDNUMBER', 'Got correct new cardnumber' ); + is( $log_info->{cardnumber}->{before}, $cardnumber, 'Got correct old cardnumber' ); is( scalar @logs, 1, 'With BorrowerLogs, one detailed MODIFY action should be logged for the modification.' ); t::lib::Mocks::mock_preference( 'TrackLastPatronActivityTriggers', 'connection' ); $patron->update_lastseen('connection'); - @logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'MODIFY', object => $patron->borrowernumber } ); - is( scalar @logs, 1, 'With BorrowerLogs and TrackLastPatronActivityTriggers we should not spam the logs'); + @logs = $schema->resultset('ActionLog') + ->search( { module => 'MEMBERS', action => 'MODIFY', object => $patron->borrowernumber } ); + is( scalar @logs, 1, 'With BorrowerLogs and TrackLastPatronActivityTriggers we should not spam the logs' ); Koha::ActionLogs->search()->delete(); $patron->get_from_storage(); @@ -1805,9 +2067,9 @@ subtest 'Test Koha::Patrons::merge' => sub { $schema->storage->txn_begin; - my $keeper = $builder->build_object({ class => 'Koha::Patrons' }); - my $loser_1 = $builder->build({ source => 'Borrower' })->{borrowernumber}; - my $loser_2 = $builder->build({ source => 'Borrower' })->{borrowernumber}; + my $keeper = $builder->build_object( { class => 'Koha::Patrons' } ); + my $loser_1 = $builder->build( { source => 'Borrower' } )->{borrowernumber}; + my $loser_2 = $builder->build( { source => 'Borrower' } )->{borrowernumber}; my $keeper_protected = $builder->build_object( { class => 'Koha::Patrons' } ); $keeper_protected->protected(1)->store; @@ -1817,24 +2079,24 @@ subtest 'Test Koha::Patrons::merge' => sub { my $loser_protected = $loser_protected_obj->borrowernumber; my $anonymous_patron_orig = C4::Context->preference('AnonymousPatron'); - my $anonymous_patron = $builder->build({ source => 'Borrower' })->{borrowernumber}; + my $anonymous_patron = $builder->build( { source => 'Borrower' } )->{borrowernumber}; t::lib::Mocks::mock_preference( 'AnonymousPatron', $anonymous_patron ); - while (my ($r, $field) = each(%$resultsets)) { - $builder->build({ source => $r, value => { $field => $keeper->id } }); - $builder->build({ source => $r, value => { $field => $loser_1 } }); - $builder->build({ source => $r, value => { $field => $loser_2 } }); + while ( my ( $r, $field ) = each(%$resultsets) ) { + $builder->build( { source => $r, value => { $field => $keeper->id } } ); + $builder->build( { source => $r, value => { $field => $loser_1 } } ); + $builder->build( { source => $r, value => { $field => $loser_2 } } ); my $keeper_rs = - $schema->resultset($r)->search( { $field => $keeper->id } ); + $schema->resultset($r)->search( { $field => $keeper->id } ); is( $keeper_rs->count(), 1, "Found 1 $r rows for keeper" ); my $loser_1_rs = - $schema->resultset($r)->search( { $field => $loser_1 } ); + $schema->resultset($r)->search( { $field => $loser_1 } ); is( $loser_1_rs->count(), 1, "Found 1 $r rows for loser_1" ); my $loser_2_rs = - $schema->resultset($r)->search( { $field => $loser_2 } ); + $schema->resultset($r)->search( { $field => $loser_2 } ); is( $loser_2_rs->count(), 1, "Found 1 $r rows for loser_2" ); } @@ -1847,29 +2109,30 @@ subtest 'Test Koha::Patrons::merge' => sub { my $results = $keeper->merge_with( [ $loser_1, $loser_2, $loser_protected ] ); - while (my ($r, $field) = each(%$resultsets)) { + while ( my ( $r, $field ) = each(%$resultsets) ) { my $keeper_rs = - $schema->resultset($r)->search( {$field => $keeper->id } ); + $schema->resultset($r)->search( { $field => $keeper->id } ); is( $keeper_rs->count(), 3, "Found 2 $r rows for keeper" ); } - is( Koha::Patrons->find($loser_1), undef, 'Loser 1 has been deleted' ); - is( Koha::Patrons->find($loser_2), undef, 'Loser 2 has been deleted' ); + is( Koha::Patrons->find($loser_1), undef, 'Loser 1 has been deleted' ); + is( Koha::Patrons->find($loser_2), undef, 'Loser 2 has been deleted' ); is( ref Koha::Patrons->find($anonymous_patron), 'Koha::Patron', 'Anonymous Patron was not deleted' ); - is( ref Koha::Patrons->find($loser_protected), 'Koha::Patron', 'Protected patron was not deleted' ); + is( ref Koha::Patrons->find($loser_protected), 'Koha::Patron', 'Protected patron was not deleted' ); $anonymous_patron = Koha::Patrons->find($anonymous_patron); - $results = $anonymous_patron->merge_with( [ $keeper->id ] ); + $results = $anonymous_patron->merge_with( [ $keeper->id ] ); is( $results, undef, "Anonymous patron cannot have other patrons merged into it" ); - is( Koha::Patrons->search( { borrowernumber => $keeper->id } )->count, 1, "Patron from attempted merge with AnonymousPatron still exists" ); + is( + Koha::Patrons->search( { borrowernumber => $keeper->id } )->count, 1, + "Patron from attempted merge with AnonymousPatron still exists" + ); subtest 'extended attributes' => sub { plan tests => 8; - my $keep_patron = - $builder->build_object( { class => 'Koha::Patrons' } ); - my $merge_patron = - $builder->build_object( { class => 'Koha::Patrons' } ); + my $keep_patron = $builder->build_object( { class => 'Koha::Patrons' } ); + my $merge_patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $attribute_type_normal_1 = $builder->build_object( { @@ -1924,10 +2187,7 @@ subtest 'Test Koha::Patrons::merge' => sub { my ( $got, $expected, $code ) = @_; is_deeply( - [ - sort $got->search( { code => $code } ) - ->get_column('attribute') - ], + [ sort $got->search( { code => $code } )->get_column('attribute') ], $expected ); } @@ -1952,10 +2212,8 @@ subtest 'Test Koha::Patrons::merge' => sub { $merge_patron->delete; # Recreate but don't expect an exception if 2 non-repeatable attributes exist, pick the one from the patron we keep - $keep_patron = - $builder->build_object( { class => 'Koha::Patrons' } ); - $merge_patron = - $builder->build_object( { class => 'Koha::Patrons' } ); + $keep_patron = $builder->build_object( { class => 'Koha::Patrons' } ); + $merge_patron = $builder->build_object( { class => 'Koha::Patrons' } ); $keep_patron->extended_attributes($attr_keep); $merge_patron->extended_attributes( @@ -1998,40 +2256,44 @@ subtest '->store' => sub { my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; - my $patron_1 = $builder->build_object({class=> 'Koha::Patrons'}); - my $patron_2 = $builder->build_object({class=> 'Koha::Patrons'}); + my $patron_1 = $builder->build_object( { class => 'Koha::Patrons' } ); + my $patron_2 = $builder->build_object( { class => 'Koha::Patrons' } ); throws_ok { $patron_2->userid( $patron_1->userid )->store; } - 'Koha::Exceptions::Patron::InvalidUserid', + 'Koha::Exceptions::Patron::InvalidUserid', 'Koha::Patron->store raises an exception on duplicate ID'; # Clear userid and check regeneration $patron_2->userid(undef)->store; - like( $patron_2->userid, qr/\w+\.\w+/, 'Userid regenerated' ); # old school userid + like( $patron_2->userid, qr/\w+\.\w+/, 'Userid regenerated' ); # old school userid $patron_2->userid('')->store; - like( $patron_2->userid, qr/\w+\.\w+/, 'Userid regenerated' ); # old school userid + like( $patron_2->userid, qr/\w+\.\w+/, 'Userid regenerated' ); # old school userid $patron_2->userid(0)->store; - like( $patron_2->userid, qr/\w+\.\w+/, 'Userid regenerated' ); # old school userid + like( $patron_2->userid, qr/\w+\.\w+/, 'Userid regenerated' ); # old school userid # Test password t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 ); my $password = 'password'; - $patron_1->set_password({ password => $password }); + $patron_1->set_password( { password => $password } ); like( $patron_1->password, qr|^\$2|, 'Password should be hashed using bcrypt (start with $2)' ); my $digest = $patron_1->password; $patron_1->surname('xxx')->store; - is( $patron_1->password, $digest, 'Password should not have changed on ->store'); + is( $patron_1->password, $digest, 'Password should not have changed on ->store' ); # Test uppercasesurnames t::lib::Mocks::mock_preference( 'uppercasesurnames', 1 ); my $surname = lc $patron_1->surname; $patron_1->surname($surname)->store; - isnt( $patron_1->surname, $surname, - 'Surname converts to uppercase on store.'); + isnt( + $patron_1->surname, $surname, + 'Surname converts to uppercase on store.' + ); t::lib::Mocks::mock_preference( 'uppercasesurnames', 0 ); $patron_1->surname($surname)->store; - is( $patron_1->surname, $surname, - 'Surname remains unchanged on store.'); + is( + $patron_1->surname, $surname, + 'Surname remains unchanged on store.' + ); # Test relationship $patron_1->relationship("")->store; @@ -2042,11 +2304,13 @@ subtest '->store' => sub { subtest 'skip updated_on for BorrowersLog' => sub { plan tests => 1; $schema->storage->txn_begin; - t::lib::Mocks::mock_preference('BorrowersLog', 1); - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); - $patron->updated_on(dt_from_string($patron->updated_on)->add( seconds => 1 ))->store; - my $logs = Koha::ActionLogs->search({ module =>'MEMBERS', action => 'MODIFY', object => $patron->borrowernumber }); - is($logs->count, 0, '->store should not have generated a log for updated_on') or diag 'Log generated:'.Dumper($logs->unblessed); + t::lib::Mocks::mock_preference( 'BorrowersLog', 1 ); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + $patron->updated_on( dt_from_string( $patron->updated_on )->add( seconds => 1 ) )->store; + my $logs = + Koha::ActionLogs->search( { module => 'MEMBERS', action => 'MODIFY', object => $patron->borrowernumber } ); + is( $logs->count, 0, '->store should not have generated a log for updated_on' ) + or diag 'Log generated:' . Dumper( $logs->unblessed ); $schema->storage->txn_rollback; }; @@ -2054,7 +2318,7 @@ subtest '->store' => sub { plan tests => 1; $schema->storage->txn_begin; - my $library = $builder->build_object( { class => 'Koha::Libraries' } ); + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); my $patron_category = $builder->build_object( { class => 'Koha::Patron::Categories', @@ -2073,9 +2337,7 @@ subtest '->store' => sub { # Enable notifying patrons of password changes for these tests t::lib::Mocks::mock_preference( 'NotifyPasswordChange', 1 ); my $new_patron = Koha::Patron->new( \%data )->store(); - my $queued_notices = Koha::Notice::Messages->search( - { borrowernumber => $new_patron->borrowernumber } - ); + my $queued_notices = Koha::Notice::Messages->search( { borrowernumber => $new_patron->borrowernumber } ); is( $queued_notices->count, 0, "No notice queued when NotifyPasswordChange enabled and this is a new patron" @@ -2103,59 +2365,61 @@ subtest '->set_password' => sub { # Password-length tests t::lib::Mocks::mock_preference( 'minPasswordLength', undef ); - throws_ok { $patron->set_password({ password => 'ab' }); } - 'Koha::Exceptions::Password::TooShort', + throws_ok { $patron->set_password( { password => 'ab' } ); } + 'Koha::Exceptions::Password::TooShort', 'minPasswordLength is undef, fall back to 3, fail test'; - is( "$@", + is( + "$@", 'Password length (2) is shorter than required (3)', 'Exception parameters passed correctly' ); t::lib::Mocks::mock_preference( 'minPasswordLength', 2 ); - throws_ok { $patron->set_password({ password => 'ab' }); } - 'Koha::Exceptions::Password::TooShort', + throws_ok { $patron->set_password( { password => 'ab' } ); } + 'Koha::Exceptions::Password::TooShort', 'minPasswordLength is 2, fall back to 3, fail test'; t::lib::Mocks::mock_preference( 'minPasswordLength', 5 ); - throws_ok { $patron->set_password({ password => 'abcb' }); } - 'Koha::Exceptions::Password::TooShort', + throws_ok { $patron->set_password( { password => 'abcb' } ); } + 'Koha::Exceptions::Password::TooShort', 'minPasswordLength is 5, fail test'; # Trailing spaces tests - throws_ok { $patron->set_password({ password => 'abcD12d ' }); } - 'Koha::Exceptions::Password::WhitespaceCharacters', + throws_ok { $patron->set_password( { password => 'abcD12d ' } ); } + 'Koha::Exceptions::Password::WhitespaceCharacters', 'Password contains trailing spaces, exception is thrown'; # Require strong password tests t::lib::Mocks::mock_preference( 'RequireStrongPassword', 1 ); - throws_ok { $patron->set_password({ password => 'abcd a' }); } - 'Koha::Exceptions::Password::TooWeak', + throws_ok { $patron->set_password( { password => 'abcd a' } ); } + 'Koha::Exceptions::Password::TooWeak', 'Password is too weak, exception is thrown'; # Refresh patron from DB, just to make sure $patron->discard_changes; is( $patron->login_attempts, 3, 'Previous tests kept login attemps count' ); - $patron->set_password({ password => 'abcD12 34' }); + $patron->set_password( { password => 'abcD12 34' } ); $patron->discard_changes; is( $patron->login_attempts, 0, 'Changing the password resets the login attempts count' ); - lives_ok { $patron->set_password({ password => 'abcd a', skip_validation => 1 }) } - 'Password is weak, but skip_validation was passed, so no exception thrown'; + lives_ok { $patron->set_password( { password => 'abcd a', skip_validation => 1 } ) } + 'Password is weak, but skip_validation was passed, so no exception thrown'; # Completeness t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 ); $patron->login_attempts(3)->store; my $old_digest = $patron->password; - $patron->set_password({ password => 'abcd a' }); + $patron->set_password( { password => 'abcd a' } ); $patron->discard_changes; isnt( $patron->password, $old_digest, 'Password has been updated' ); - ok( checkpw_hash('abcd a', $patron->password), 'Password hash is correct' ); + ok( checkpw_hash( 'abcd a', $patron->password ), 'Password hash is correct' ); is( $patron->login_attempts, 0, 'Login attemps have been reset' ); - my $number_of_logs = $schema->resultset('ActionLog')->search( { module => 'MEMBERS', action => 'CHANGE PASS', object => $patron->borrowernumber } )->count; + my $number_of_logs = $schema->resultset('ActionLog') + ->search( { module => 'MEMBERS', action => 'CHANGE PASS', object => $patron->borrowernumber } )->count; is( $number_of_logs, 0, 'Without BorrowerLogs, Koha::Patron->set_password doesn\'t log password changes' ); # Enable logging password changes @@ -2169,6 +2433,7 @@ subtest '->set_password' => sub { } )->count; is( $number_of_logs, 1, 'With BorrowerLogs, Koha::Patron->set_password does log password changes' ); + # add other action name $patron->set_password( { password => 'abcd b2', action => 'RESET PASS' } ); $number_of_logs = $schema->resultset('ActionLog')->search( @@ -2182,49 +2447,58 @@ subtest '->set_password' => sub { # Enable notifying patrons of password changes t::lib::Mocks::mock_preference( 'NotifyPasswordChange', 1 ); - $patron->set_password({ password => 'abcd c' }); - my $queued_notices = Koha::Notice::Messages->search({ borrowernumber => $patron->borrowernumber }); + $patron->set_password( { password => 'abcd c' } ); + my $queued_notices = Koha::Notice::Messages->search( { borrowernumber => $patron->borrowernumber } ); is( $queued_notices->count, 1, "One notice queued when NotifyPasswordChange enabled" ); my $THE_notice = $queued_notices->next; - is( $THE_notice->status, 'failed', "The notice was handled immediately and failed on wrong email address."); #FIXME Mock sending mail + is( $THE_notice->status, 'failed', "The notice was handled immediately and failed on wrong email address." ) + ; #FIXME Mock sending mail $schema->storage->txn_rollback; }; $schema->storage->txn_begin; subtest 'filter_by_expiration_date' => sub { plan tests => 3; - my $count1 = Koha::Patrons->filter_by_expiration_date({ days => 28 })->count; - my $patron1 = $builder->build_object({ class => 'Koha::Patrons' }); - $patron1->dateexpiry( dt_from_string->subtract(days => 27) )->store; - is( Koha::Patrons->filter_by_expiration_date({ days => 28 })->count, $count1, 'No more expired' ); - $patron1->dateexpiry( dt_from_string->subtract(days => 28) )->store; - is( Koha::Patrons->filter_by_expiration_date({ days => 28 })->count, $count1 + 1, 'One more expired' ); - $patron1->dateexpiry( dt_from_string->subtract(days => 29) )->store; - is( Koha::Patrons->filter_by_expiration_date({ days => 28 })->count, $count1 + 1, 'Same number again' ); + my $count1 = Koha::Patrons->filter_by_expiration_date( { days => 28 } )->count; + my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } ); + $patron1->dateexpiry( dt_from_string->subtract( days => 27 ) )->store; + is( Koha::Patrons->filter_by_expiration_date( { days => 28 } )->count, $count1, 'No more expired' ); + $patron1->dateexpiry( dt_from_string->subtract( days => 28 ) )->store; + is( Koha::Patrons->filter_by_expiration_date( { days => 28 } )->count, $count1 + 1, 'One more expired' ); + $patron1->dateexpiry( dt_from_string->subtract( days => 29 ) )->store; + is( Koha::Patrons->filter_by_expiration_date( { days => 28 } )->count, $count1 + 1, 'Same number again' ); }; subtest 'search_unsubscribed' => sub { plan tests => 4; - t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 3 ); + t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 3 ); t::lib::Mocks::mock_preference( 'UnsubscribeReflectionDelay', '' ); is( Koha::Patrons->search_unsubscribed->count, 0, 'Empty delay should return empty set' ); - my $patron1 = $builder->build_object({ class => 'Koha::Patrons' }); - my $patron2 = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } ); + my $patron2 = $builder->build_object( { class => 'Koha::Patrons' } ); t::lib::Mocks::mock_preference( 'UnsubscribeReflectionDelay', 0 ); - Koha::Patron::Consents->delete; # for correct counts - Koha::Patron::Consent->new({ borrowernumber => $patron1->borrowernumber, type => 'GDPR_PROCESSING', refused_on => dt_from_string })->store; + Koha::Patron::Consents->delete; # for correct counts + Koha::Patron::Consent->new( + { borrowernumber => $patron1->borrowernumber, type => 'GDPR_PROCESSING', refused_on => dt_from_string } ) + ->store; is( Koha::Patrons->search_unsubscribed->count, 1, 'Find patron1' ); # Add another refusal but shift the period t::lib::Mocks::mock_preference( 'UnsubscribeReflectionDelay', 2 ); - Koha::Patron::Consent->new({ borrowernumber => $patron2->borrowernumber, type => 'GDPR_PROCESSING', refused_on => dt_from_string->subtract(days=>2) })->store; + Koha::Patron::Consent->new( + { + borrowernumber => $patron2->borrowernumber, type => 'GDPR_PROCESSING', + refused_on => dt_from_string->subtract( days => 2 ) + } + )->store; is( Koha::Patrons->search_unsubscribed->count, 1, 'Find patron2 only' ); # Try another (special) attempts setting t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 0 ); + # Lockout is now disabled # Patron2 still matches: refused earlier, not locked is( Koha::Patrons->search_unsubscribed->count, 1, 'Lockout disabled' ); @@ -2232,56 +2506,64 @@ subtest 'search_unsubscribed' => sub { subtest 'search_anonymize_candidates' => sub { plan tests => 7; - my $patron1 = $builder->build_object({ class => 'Koha::Patrons' }); - my $patron2 = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } ); + my $patron2 = $builder->build_object( { class => 'Koha::Patrons' } ); $patron1->anonymized(0); - $patron1->dateexpiry( dt_from_string->add(days => 1) )->store; + $patron1->dateexpiry( dt_from_string->add( days => 1 ) )->store; $patron2->anonymized(0); - $patron2->dateexpiry( dt_from_string->add(days => 1) )->store; + $patron2->dateexpiry( dt_from_string->add( days => 1 ) )->store; t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', q{} ); is( Koha::Patrons->search_anonymize_candidates->count, 0, 'Empty set' ); t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', 0 ); my $cnt = Koha::Patrons->search_anonymize_candidates->count; - $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store; - $patron2->dateexpiry( dt_from_string->subtract(days => 3) )->store; - is( Koha::Patrons->search_anonymize_candidates->count, $cnt+2, 'Delay 0' ); + $patron1->dateexpiry( dt_from_string->subtract( days => 1 ) )->store; + $patron2->dateexpiry( dt_from_string->subtract( days => 3 ) )->store; + is( Koha::Patrons->search_anonymize_candidates->count, $cnt + 2, 'Delay 0' ); t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', 2 ); - $patron1->dateexpiry( dt_from_string->add(days => 1) )->store; - $patron2->dateexpiry( dt_from_string->add(days => 1) )->store; + $patron1->dateexpiry( dt_from_string->add( days => 1 ) )->store; + $patron2->dateexpiry( dt_from_string->add( days => 1 ) )->store; $cnt = Koha::Patrons->search_anonymize_candidates->count; - $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store; - $patron2->dateexpiry( dt_from_string->subtract(days => 3) )->store; - is( Koha::Patrons->search_anonymize_candidates->count, $cnt+1, 'Delay 2' ); + $patron1->dateexpiry( dt_from_string->subtract( days => 1 ) )->store; + $patron2->dateexpiry( dt_from_string->subtract( days => 3 ) )->store; + is( Koha::Patrons->search_anonymize_candidates->count, $cnt + 1, 'Delay 2' ); t::lib::Mocks::mock_preference( 'PatronAnonymizeDelay', 4 ); - $patron1->dateexpiry( dt_from_string->add(days => 1) )->store; - $patron2->dateexpiry( dt_from_string->add(days => 1) )->store; + $patron1->dateexpiry( dt_from_string->add( days => 1 ) )->store; + $patron2->dateexpiry( dt_from_string->add( days => 1 ) )->store; $cnt = Koha::Patrons->search_anonymize_candidates->count; - $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store; - $patron2->dateexpiry( dt_from_string->subtract(days => 3) )->store; + $patron1->dateexpiry( dt_from_string->subtract( days => 1 ) )->store; + $patron2->dateexpiry( dt_from_string->subtract( days => 3 ) )->store; is( Koha::Patrons->search_anonymize_candidates->count, $cnt, 'Delay 4' ); t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 3 ); - $patron1->dateexpiry( dt_from_string->subtract(days => 5) )->store; + $patron1->dateexpiry( dt_from_string->subtract( days => 5 ) )->store; $patron1->login_attempts(0)->store; - $patron2->dateexpiry( dt_from_string->subtract(days => 5) )->store; + $patron2->dateexpiry( dt_from_string->subtract( days => 5 ) )->store; $patron2->login_attempts(0)->store; - $cnt = Koha::Patrons->search_anonymize_candidates({locked => 1})->count; + $cnt = Koha::Patrons->search_anonymize_candidates( { locked => 1 } )->count; $patron1->login_attempts(3)->store; - is( Koha::Patrons->search_anonymize_candidates({locked => 1})->count, - $cnt+1, 'Locked flag' ); + is( + Koha::Patrons->search_anonymize_candidates( { locked => 1 } )->count, + $cnt + 1, 'Locked flag' + ); t::lib::Mocks::mock_preference( 'FailedLoginAttempts', q{} ); + # Patron 1 still on 3 == locked - is( Koha::Patrons->search_anonymize_candidates({locked => 1})->count, - $cnt+1, 'Still expect same number for FailedLoginAttempts empty' ); + is( + Koha::Patrons->search_anonymize_candidates( { locked => 1 } )->count, + $cnt + 1, 'Still expect same number for FailedLoginAttempts empty' + ); $patron1->login_attempts(0)->store; + # Patron 1 unlocked - is( Koha::Patrons->search_anonymize_candidates({locked => 1})->count, - $cnt, 'Patron 1 unlocked' ); + is( + Koha::Patrons->search_anonymize_candidates( { locked => 1 } )->count, + $cnt, 'Patron 1 unlocked' + ); }; subtest 'search_anonymized' => sub { @@ -2292,13 +2574,13 @@ subtest 'search_anonymized' => sub { is( Koha::Patrons->search_anonymized->count, 0, 'Empty set' ); t::lib::Mocks::mock_preference( 'PatronRemovalDelay', 1 ); - $patron1->dateexpiry( dt_from_string ); + $patron1->dateexpiry(dt_from_string); $patron1->anonymized(0)->store; my $cnt = Koha::Patrons->search_anonymized->count; $patron1->anonymized(1)->store; is( Koha::Patrons->search_anonymized->count, $cnt, 'Number unchanged' ); - $patron1->dateexpiry( dt_from_string->subtract(days => 1) )->store; - is( Koha::Patrons->search_anonymized->count, $cnt+1, 'Found patron1' ); + $patron1->dateexpiry( dt_from_string->subtract( days => 1 ) )->store; + is( Koha::Patrons->search_anonymized->count, $cnt + 1, 'Found patron1' ); }; subtest 'lock' => sub { @@ -2306,35 +2588,37 @@ subtest 'lock' => sub { my $patron1 = $builder->build_object( { class => 'Koha::Patrons' } ); my $patron2 = $builder->build_object( { class => 'Koha::Patrons' } ); - my $hold = $builder->build_object({ - class => 'Koha::Holds', - value => { borrowernumber => $patron1->borrowernumber }, - }); + my $hold = $builder->build_object( + { + class => 'Koha::Holds', + value => { borrowernumber => $patron1->borrowernumber }, + } + ); t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 3 ); - my $expiry = dt_from_string->add(days => 1); - $patron1->dateexpiry( $expiry ); + my $expiry = dt_from_string->add( days => 1 ); + $patron1->dateexpiry($expiry); $patron1->lock; is( $patron1->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts' ); - is( $patron1->dateexpiry, $expiry, 'Not expired yet' ); - is( $patron1->holds->count, 1, 'No holds removed' ); + is( $patron1->dateexpiry, $expiry, 'Not expired yet' ); + is( $patron1->holds->count, 1, 'No holds removed' ); - $patron1->lock({ expire => 1, remove => 1}); + $patron1->lock( { expire => 1, remove => 1 } ); isnt( $patron1->dateexpiry, $expiry, 'Expiry date adjusted' ); is( $patron1->holds->count, 0, 'Holds removed' ); # Disable lockout feature t::lib::Mocks::mock_preference( 'FailedLoginAttempts', q{} ); $patron1->login_attempts(0); - $patron1->dateexpiry( $expiry ); + $patron1->dateexpiry($expiry); $patron1->store; $patron1->lock; is( $patron1->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts' ); # Trivial wrapper test (Koha::Patrons->lock) $patron1->login_attempts(0)->store; - Koha::Patrons->search({ borrowernumber => [ $patron1->borrowernumber, $patron2->borrowernumber ] })->lock; - $patron1->discard_changes; # refresh + Koha::Patrons->search( { borrowernumber => [ $patron1->borrowernumber, $patron2->borrowernumber ] } )->lock; + $patron1->discard_changes; # refresh $patron2->discard_changes; is( $patron1->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts patron 1' ); is( $patron2->login_attempts, Koha::Patron::ADMINISTRATIVE_LOCKOUT, 'Check login_attempts patron 2' ); @@ -2347,29 +2631,31 @@ subtest 'anonymize' => sub { my $patron2 = $builder->build_object( { class => 'Koha::Patrons' } ); # First try patron with issues - my $issue = $builder->build_object({ class => 'Koha::Checkouts', value => { borrowernumber => $patron2->borrowernumber } }); + my $issue = $builder->build_object( + { class => 'Koha::Checkouts', value => { borrowernumber => $patron2->borrowernumber } } ); warning_like { $patron2->anonymize } qr/still has issues/, 'Skip patron with issues'; $issue->delete; t::lib::Mocks::mock_preference( 'BorrowerMandatoryField', 'surname|email|cardnumber' ); - my $surname = $patron1->surname; # expect change, no clear - my $branchcode = $patron1->branchcode; # expect skip + my $surname = $patron1->surname; # expect change, no clear + my $branchcode = $patron1->branchcode; # expect skip $patron1->anonymize; - is($patron1->anonymized, 1, 'Check flag' ); + is( $patron1->anonymized, 1, 'Check flag' ); is( $patron1->dateofbirth, undef, 'Birth date cleared' ); - is( $patron1->firstname, undef, 'First name cleared' ); + is( $patron1->firstname, undef, 'First name cleared' ); isnt( $patron1->surname, $surname, 'Surname changed' ); ok( $patron1->surname =~ /^\w{10}$/, 'Mandatory surname randomized' ); is( $patron1->branchcode, $branchcode, 'Branch code skipped' ); - is( $patron1->email, undef, 'Email was mandatory, must be cleared' ); + is( $patron1->email, undef, 'Email was mandatory, must be cleared' ); # Test wrapper in Koha::Patrons - $patron1->surname($surname)->store; # restore - my $rs = Koha::Patrons->search({ borrowernumber => [ $patron1->borrowernumber, $patron2->borrowernumber ] })->anonymize; - $patron1->discard_changes; # refresh + $patron1->surname($surname)->store; # restore + my $rs = Koha::Patrons->search( { borrowernumber => [ $patron1->borrowernumber, $patron2->borrowernumber ] } ) + ->anonymize; + $patron1->discard_changes; # refresh isnt( $patron1->surname, $surname, 'Surname patron1 changed again' ); - $patron2->discard_changes; # refresh + $patron2->discard_changes; # refresh is( $patron2->firstname, undef, 'First name patron2 cleared' ); }; @@ -2378,97 +2664,122 @@ subtest 'queue_notice' => sub { my $dbh = C4::Context->dbh; t::lib::Mocks::mock_preference( 'EmailFieldPrimary', 'email' ); - my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); - my $branch = $builder->build_object( { class => 'Koha::Libraries' } ); - my $letter_e = $builder->build_object( { - class => 'Koha::Notice::Templates', - value => { - branchcode => $branch->branchcode, - message_transport_type => 'email', - lang => 'default' + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + my $branch = $builder->build_object( { class => 'Koha::Libraries' } ); + my $letter_e = $builder->build_object( + { + class => 'Koha::Notice::Templates', + value => { + branchcode => $branch->branchcode, + message_transport_type => 'email', + lang => 'default' + } } - }); - my $letter_p = $builder->build_object( { - class => 'Koha::Notice::Templates', - value => { - code => $letter_e->code, - module => $letter_e->module, - branchcode => $branch->branchcode, - message_transport_type => 'print', - lang => 'default' + ); + my $letter_p = $builder->build_object( + { + class => 'Koha::Notice::Templates', + value => { + code => $letter_e->code, + module => $letter_e->module, + branchcode => $branch->branchcode, + message_transport_type => 'print', + lang => 'default' + } } - }); - my $letter_s = $builder->build_object( { - class => 'Koha::Notice::Templates', - value => { - code => $letter_e->code, - module => $letter_e->module, - branchcode => $branch->branchcode, - message_transport_type => 'sms', - lang => 'default' + ); + my $letter_s = $builder->build_object( + { + class => 'Koha::Notice::Templates', + value => { + code => $letter_e->code, + module => $letter_e->module, + branchcode => $branch->branchcode, + message_transport_type => 'sms', + lang => 'default' + } } - }); + ); my $letter_params = { - letter_code => $letter_e->code, - branchcode => $letter_e->branchcode, - module => $letter_e->module, + letter_code => $letter_e->code, + branchcode => $letter_e->branchcode, + module => $letter_e->module, borrowernumber => $patron->borrowernumber, - tables => { + tables => { borrowers => $patron->borrowernumber, } }; my @mtts = ('email'); - is( $patron->queue_notice(), undef, "Nothing is done if no params passed"); - is( $patron->queue_notice({ letter_params => $letter_params }),undef, "Nothing done if only letter"); + is( $patron->queue_notice(), undef, "Nothing is done if no params passed" ); + is( $patron->queue_notice( { letter_params => $letter_params } ), undef, "Nothing done if only letter" ); is_deeply( - $patron->queue_notice({ letter_params => $letter_params, message_transports => \@mtts }), - {sent => ['email'] }, "Email sent" + $patron->queue_notice( { letter_params => $letter_params, message_transports => \@mtts } ), + { sent => ['email'] }, "Email sent" ); $patron->email("")->store; is_deeply( - $patron->queue_notice({ letter_params => $letter_params, message_transports => \@mtts }), - {sent => ['print'],fallback => ['email']}, "Email fallsback to print if no email" + $patron->queue_notice( { letter_params => $letter_params, message_transports => \@mtts } ), + { sent => ['print'], fallback => ['email'] }, "Email fallsback to print if no email" ); push @mtts, 'sms'; is_deeply( - $patron->queue_notice({ letter_params => $letter_params, message_transports => \@mtts }), - {sent => ['print','sms'],fallback => ['email']}, "Email fallsback to print if no email, sms sent" + $patron->queue_notice( { letter_params => $letter_params, message_transports => \@mtts } ), + { sent => [ 'print', 'sms' ], fallback => ['email'] }, "Email fallsback to print if no email, sms sent" ); $patron->smsalertnumber("")->store; - my $counter = Koha::Notice::Messages->search({borrowernumber => $patron->borrowernumber })->count; + my $counter = Koha::Notice::Messages->search( { borrowernumber => $patron->borrowernumber } )->count; is_deeply( - $patron->queue_notice({ letter_params => $letter_params, message_transports => \@mtts }), - {sent => ['print'],fallback => ['email','sms']}, "Email fallsback to print if no emai, sms fallsback to print if no sms, only one print sent" + $patron->queue_notice( { letter_params => $letter_params, message_transports => \@mtts } ), + { sent => ['print'], fallback => [ 'email', 'sms' ] }, + "Email fallsback to print if no emai, sms fallsback to print if no sms, only one print sent" + ); + is( + Koha::Notice::Messages->search( { borrowernumber => $patron->borrowernumber } )->count, $counter + 1, + "Count of queued notices went up by one" ); - is( Koha::Notice::Messages->search({borrowernumber => $patron->borrowernumber })->count, $counter+1,"Count of queued notices went up by one"); # Enable notification for Hold_Filled - Things are hardcoded here but should work with default data - $dbh->do(q|INSERT INTO borrower_message_preferences( borrowernumber, message_attribute_id ) VALUES ( ?, ?)|, undef, $patron->borrowernumber, 4 ); - my $borrower_message_preference_id = $dbh->last_insert_id(undef, undef, "borrower_message_preferences", undef); - $dbh->do(q|INSERT INTO borrower_message_transport_preferences( borrower_message_preference_id, message_transport_type) VALUES ( ?, ? )|, undef, $borrower_message_preference_id, 'email' ); + $dbh->do( + q|INSERT INTO borrower_message_preferences( borrowernumber, message_attribute_id ) VALUES ( ?, ?)|, + undef, $patron->borrowernumber, 4 + ); + my $borrower_message_preference_id = $dbh->last_insert_id( undef, undef, "borrower_message_preferences", undef ); + $dbh->do( + q|INSERT INTO borrower_message_transport_preferences( borrower_message_preference_id, message_transport_type) VALUES ( ?, ? )|, + undef, $borrower_message_preference_id, 'email' + ); - is( $patron->queue_notice({ letter_params => $letter_params, message_transports => \@mtts, message_name => 'Hold_Filled' }),undef, "Nothing done if transports and name sent"); + is( + $patron->queue_notice( + { letter_params => $letter_params, message_transports => \@mtts, message_name => 'Hold_Filled' } + ), + undef, + "Nothing done if transports and name sent" + ); $patron->email(q|awesome@ismymiddle.name|)->store; is_deeply( - $patron->queue_notice({ letter_params => $letter_params, message_name => 'Hold_Filled' }), - {sent => ['email'] }, "Email sent when using borrower preferences" + $patron->queue_notice( { letter_params => $letter_params, message_name => 'Hold_Filled' } ), + { sent => ['email'] }, "Email sent when using borrower preferences" ); - $counter = Koha::Notice::Messages->search({borrowernumber => $patron->borrowernumber })->count; + $counter = Koha::Notice::Messages->search( { borrowernumber => $patron->borrowernumber } )->count; is_deeply( - $patron->queue_notice({ letter_params => $letter_params, message_name => 'Hold_Filled', test_mode => 1 }), - {sent => ['email'] }, "Report that email sent when using borrower preferences in test_mode" + $patron->queue_notice( { letter_params => $letter_params, message_name => 'Hold_Filled', test_mode => 1 } ), + { sent => ['email'] }, "Report that email sent when using borrower preferences in test_mode" + ); + is( + Koha::Notice::Messages->search( { borrowernumber => $patron->borrowernumber } )->count, $counter, + "Count of queued notices not increased in test mode" ); - is( Koha::Notice::Messages->search({borrowernumber => $patron->borrowernumber })->count, $counter,"Count of queued notices not increased in test mode"); }; subtest 'filter_by_amount_owed' => sub { plan tests => 6; - my $library = $builder->build({source => 'Branch' }); - my $category = $builder->build({source => 'Category' }); + my $library = $builder->build( { source => 'Branch' } ); + my $category = $builder->build( { source => 'Category' } ); my $new_patron_cf_1 = Koha::Patron->new( { @@ -2550,38 +2861,39 @@ subtest 'filter_by_amount_owed' => sub { ); my $filtered = $results->filter_by_amount_owed(); - is( ref($filtered), 'Koha::Patrons', -'Koha::Patrons->filter_by_amount_owed should return a Koha::Patrons result set in a scalar context' + is( + ref($filtered), 'Koha::Patrons', + 'Koha::Patrons->filter_by_amount_owed should return a Koha::Patrons result set in a scalar context' ); my $lower_limit = 12.00; my $upper_limit = 16.00; # Catch user with 1 x 12.00 fine and user with no fines. - $filtered = - $results->filter_by_amount_owed( { less_than => $upper_limit } ); - is( $filtered->_resultset->as_subselect_rs->count, 2, -"filter_by_amount_owed({ less_than => $upper_limit }) found two patrons" + $filtered = $results->filter_by_amount_owed( { less_than => $upper_limit } ); + is( + $filtered->_resultset->as_subselect_rs->count, 2, + "filter_by_amount_owed({ less_than => $upper_limit }) found two patrons" ); # Catch user with 1 x 8.00 and 1 x 10.00 fine - $filtered = - $results->filter_by_amount_owed( { more_than => $lower_limit } ); - is( $filtered->_resultset->as_subselect_rs->count, 1, -"filter_by_amount_owed({ more_than => $lower_limit }) found two patrons" + $filtered = $results->filter_by_amount_owed( { more_than => $lower_limit } ); + is( + $filtered->_resultset->as_subselect_rs->count, 1, + "filter_by_amount_owed({ more_than => $lower_limit }) found two patrons" ); # User with 2 fines falls above upper limit - Excluded, # user with 1 fine falls below lower limit - Excluded # and user with no fines falls below lower limit - Excluded. - $filtered = $results->filter_by_amount_owed( - { more_than => $lower_limit, less_than => $upper_limit } ); - is( $filtered->_resultset->as_subselect_rs->count, 0, -"filter_by_amount_owed({ more_than => $lower_limit, less_than => $upper_limit }) found zero patrons" + $filtered = $results->filter_by_amount_owed( { more_than => $lower_limit, less_than => $upper_limit } ); + is( + $filtered->_resultset->as_subselect_rs->count, 0, + "filter_by_amount_owed({ more_than => $lower_limit, less_than => $upper_limit }) found zero patrons" ); - my $library2 = $builder->build({source => 'Branch' }); - my $fine4 = $builder->build( + my $library2 = $builder->build( { source => 'Branch' } ); + my $fine4 = $builder->build( { source => 'Accountline', value => { @@ -2596,14 +2908,16 @@ subtest 'filter_by_amount_owed' => sub { # Catch only the user with a HOLD fee over 6.00 $filtered = $results->filter_by_amount_owed( { more_than => 6.00, debit_type => 'HOLD' } ); - is( $filtered->_resultset->as_subselect_rs->count, 1, -"filter_by_amount_owed({ more_than => 6.00, debit_type => 'HOLD' }) found one patron" + is( + $filtered->_resultset->as_subselect_rs->count, 1, + "filter_by_amount_owed({ more_than => 6.00, debit_type => 'HOLD' }) found one patron" ); # Catch only the user with a fee over 6.00 at the specified library $filtered = $results->filter_by_amount_owed( { more_than => 6.00, library => $library2->{branchcode} } ); - is( $filtered->_resultset->as_subselect_rs->count, 1, -"filter_by_amount_owed({ more_than => 6.00, library => $library2->{branchcode} }) found one patron" + is( + $filtered->_resultset->as_subselect_rs->count, 1, + "filter_by_amount_owed({ more_than => 6.00, library => $library2->{branchcode} }) found one patron" ); }; @@ -2620,8 +2934,8 @@ subtest 'libraries_where_can_edit_items() and can_edit_items_from() tests' => su # library_1B # group2 # library_2A - my $group_1 = Koha::Library::Group->new( { title => 'TEST Group 1', ft_limit_item_editing => 1 } )->store; - my $group_2 = Koha::Library::Group->new( { title => 'TEST Group 2', ft_limit_item_editing => 1 } )->store; + my $group_1 = Koha::Library::Group->new( { title => 'TEST Group 1', ft_limit_item_editing => 1 } )->store; + my $group_2 = Koha::Library::Group->new( { title => 'TEST Group 2', ft_limit_item_editing => 1 } )->store; my $library_1A = $builder->build( { source => 'Branch' } ); my $library_1B = $builder->build( { source => 'Branch' } ); my $library_2A = $builder->build( { source => 'Branch' } ); @@ -2632,23 +2946,32 @@ subtest 'libraries_where_can_edit_items() and can_edit_items_from() tests' => su Koha::Library::Group->new( { branchcode => $library_1B->branchcode, parent_id => $group_1->id } )->store; Koha::Library::Group->new( { branchcode => $library_2A->branchcode, parent_id => $group_2->id } )->store; - my $sth = C4::Context->dbh->prepare(q|INSERT INTO user_permissions( borrowernumber, module_bit, code ) VALUES (?, 9, ?)|); # 9 for editcatalogue - # 2 patrons from library_1A (group1) - # patron_1A_1 see patron's infos from outside its group - # Setting flags => undef to not be considered as superlibrarian - my $patron_1A_1 = $builder->build({ source => 'Borrower', value => { branchcode => $library_1A->branchcode, flags => undef, }}); + my $sth = + C4::Context->dbh->prepare(q|INSERT INTO user_permissions( borrowernumber, module_bit, code ) VALUES (?, 9, ?)|) + ; # 9 for editcatalogue + # 2 patrons from library_1A (group1) + # patron_1A_1 see patron's infos from outside its group + # Setting flags => undef to not be considered as superlibrarian + my $patron_1A_1 = $builder->build( + { source => 'Borrower', value => { branchcode => $library_1A->branchcode, flags => undef, } } ); $patron_1A_1 = Koha::Patrons->find( $patron_1A_1->{borrowernumber} ); $sth->execute( $patron_1A_1->borrowernumber, 'edit_items' ); $sth->execute( $patron_1A_1->borrowernumber, 'edit_any_item' ); + # patron_1A_2 can only see patron's info from its group - my $patron_1A_2 = $builder->build({ source => 'Borrower', value => { branchcode => $library_1A->branchcode, flags => undef, }}); + my $patron_1A_2 = $builder->build( + { source => 'Borrower', value => { branchcode => $library_1A->branchcode, flags => undef, } } ); $patron_1A_2 = Koha::Patrons->find( $patron_1A_2->{borrowernumber} ); $sth->execute( $patron_1A_2->borrowernumber, 'edit_items' ); + # 1 patron from library_1B (group1) - my $patron_1B = $builder->build({ source => 'Borrower', value => { branchcode => $library_1B->branchcode, flags => undef, }}); + my $patron_1B = $builder->build( + { source => 'Borrower', value => { branchcode => $library_1B->branchcode, flags => undef, } } ); $patron_1B = Koha::Patrons->find( $patron_1B->{borrowernumber} ); + # 1 patron from library_2A (group2) can only see patron's info from its group - my $patron_2A = $builder->build({ source => 'Borrower', value => { branchcode => $library_2A->branchcode, flags => undef, }}); + my $patron_2A = $builder->build( + { source => 'Borrower', value => { branchcode => $library_2A->branchcode, flags => undef, } } ); $patron_2A = Koha::Patrons->find( $patron_2A->{borrowernumber} ); $sth->execute( $patron_2A->borrowernumber, 'edit_items' ); @@ -2661,24 +2984,42 @@ subtest 'libraries_where_can_edit_items() and can_edit_items_from() tests' => su is_deeply( \@branchcodes, [], "patron_1A_1 has edit_any_item => No restrictions" ); @branchcodes = $patron_1A_2->libraries_where_can_edit_items; - is_deeply( \@branchcodes, [ sort ( $library_1A->branchcode, $library_1B->branchcode ) ], "patron_1A_2 doesn't have edit_any_item => Can only edit items from its group" ); + is_deeply( + \@branchcodes, [ sort ( $library_1A->branchcode, $library_1B->branchcode ) ], + "patron_1A_2 doesn't have edit_any_item => Can only edit items from its group" + ); @branchcodes = $patron_2A->libraries_where_can_edit_items; - is_deeply( \@branchcodes, [$library_2A->branchcode], "patron_2A doesn't have edit_any_item => Can only see patron's from its group" ); + is_deeply( + \@branchcodes, [ $library_2A->branchcode ], + "patron_2A doesn't have edit_any_item => Can only see patron's from its group" + ); }; subtest 'can_edit_items_from' => sub { plan tests => 6; - t::lib::Mocks::mock_userenv({ patron => $patron_1A_1 }); - is( $patron_1A_1->can_edit_items_from( $library_1A->id ), 1, "patron_1A_1 can see patron_1A_2, from its library" ); - is( $patron_1A_1->can_edit_items_from( $library_1B->id ), 1, "patron_1A_1 can see patron_1B, from its group" ); - is( $patron_1A_1->can_edit_items_from( $library_2A->id ), 1, "patron_1A_1 can see patron_1A_2, from another group" ); + t::lib::Mocks::mock_userenv( { patron => $patron_1A_1 } ); + is( + $patron_1A_1->can_edit_items_from( $library_1A->id ), 1, + "patron_1A_1 can see patron_1A_2, from its library" + ); + is( $patron_1A_1->can_edit_items_from( $library_1B->id ), 1, "patron_1A_1 can see patron_1B, from its group" ); + is( + $patron_1A_1->can_edit_items_from( $library_2A->id ), 1, + "patron_1A_1 can see patron_1A_2, from another group" + ); - t::lib::Mocks::mock_userenv({ patron => $patron_1A_2 }); - is( $patron_1A_2->can_edit_items_from( $library_1A->id ), 1, "patron_1A_2 can see patron_1A_1, from its library" ); - is( $patron_1A_2->can_edit_items_from( $library_1B->id ), 1, "patron_1A_2 can see patron_1B, from its group" ); - is( $patron_1A_2->can_edit_items_from( $library_2A->id ), 0, "patron_1A_2 can NOT see patron_2A, from another group" ); + t::lib::Mocks::mock_userenv( { patron => $patron_1A_2 } ); + is( + $patron_1A_2->can_edit_items_from( $library_1A->id ), 1, + "patron_1A_2 can see patron_1A_1, from its library" + ); + is( $patron_1A_2->can_edit_items_from( $library_1B->id ), 1, "patron_1A_2 can see patron_1B, from its group" ); + is( + $patron_1A_2->can_edit_items_from( $library_2A->id ), 0, + "patron_1A_2 can NOT see patron_2A, from another group" + ); }; }; @@ -2695,7 +3036,7 @@ subtest 'filter_by_have_permission' => sub { } ); - my $patron_2 = $builder->build_object( # 4096 = 1 << 12 for suggestions + my $patron_2 = $builder->build_object( # 4096 = 1 << 12 for suggestions { class => 'Koha::Patrons', value => { flags => 4096, branchcode => $library->branchcode } @@ -2722,8 +3063,7 @@ subtest 'filter_by_have_permission' => sub { is_deeply( [ Koha::Patrons->search( { branchcode => $library->branchcode } ) - ->filter_by_have_permission('suggestions.suggestions_manage') - ->get_column('borrowernumber') + ->filter_by_have_permission('suggestions.suggestions_manage')->get_column('borrowernumber') ], [ $patron_1->borrowernumber, $patron_2->borrowernumber ], 'Superlibrarian and patron with suggestions.suggestions_manage' @@ -2732,8 +3072,7 @@ subtest 'filter_by_have_permission' => sub { is_deeply( [ Koha::Patrons->search( { branchcode => $library->branchcode } ) - ->filter_by_have_permission('acquisition.order_manage') - ->get_column('borrowernumber') + ->filter_by_have_permission('acquisition.order_manage')->get_column('borrowernumber') ], [ $patron_1->borrowernumber, $patron_3->borrowernumber ], 'Superlibrarian and patron with acquisition.order_manage' @@ -2742,8 +3081,7 @@ subtest 'filter_by_have_permission' => sub { is_deeply( [ Koha::Patrons->search( { branchcode => $library->branchcode } ) - ->filter_by_have_permission('parameters.manage_cities') - ->get_column('borrowernumber') + ->filter_by_have_permission('parameters.manage_cities')->get_column('borrowernumber') ], [ $patron_1->borrowernumber ], 'Only Superlibrarian is returned' @@ -2751,9 +3089,8 @@ subtest 'filter_by_have_permission' => sub { is_deeply( [ - Koha::Patrons->search( { branchcode => $library->branchcode } ) - ->filter_by_have_permission('suggestions') - ->get_column('borrowernumber') + Koha::Patrons->search( { branchcode => $library->branchcode } )->filter_by_have_permission('suggestions') + ->get_column('borrowernumber') ], [ $patron_1->borrowernumber, $patron_2->borrowernumber ], 'Superlibrarian and patron with suggestions' @@ -2761,9 +3098,9 @@ subtest 'filter_by_have_permission' => sub { throws_ok { Koha::Patrons->search( { branchcode => $library->branchcode } ) - ->filter_by_have_permission('dont_exist.subperm'); - } 'Koha::Exceptions::ObjectNotFound'; - + ->filter_by_have_permission('dont_exist.subperm'); + } + 'Koha::Exceptions::ObjectNotFound'; $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/Koha/Patrons/Import.t b/t/db_dependent/Koha/Patrons/Import.t index 77ff8db92e..8949574a79 100755 --- a/t/db_dependent/Koha/Patrons/Import.t +++ b/t/db_dependent/Koha/Patrons/Import.t @@ -275,7 +275,7 @@ is( $patron_3->dateexpiry, '2015-07-01', "Expiration date is correct with update my $filename_3c = make_csv( $temp_dir, $csv_headers, $csv_one_line_b ); open( my $handle_3c, "<", $filename_3c ) or die "cannot open < $filename_3: $!"; my $params_3c = { - file => $handle_3c, matchpoint => 'cardnumber', overwrite_cardnumber => 1, preserve_fields => ['firstname'], + file => $handle_3c, matchpoint => 'cardnumber', overwrite_cardnumber => 1, preserve_fields => ['firstname'], update_dateexpiry => 1, update_dateexpiry_from_today => 1 }; @@ -330,7 +330,7 @@ my $filename_3d = make_csv( $temp_dir, $csv_headers, $csv_one_line_b ); open( my $handle_3d, "<", $filename_3d ) or die "cannot open < $filename_3: $!"; $patron_3c->dateexpiry('1980-01-01')->store(); my $params_3d = { - file => $handle_3d, matchpoint => 'cardnumber', overwrite_cardnumber => 1, preserve_fields => ['firstname'], + file => $handle_3d, matchpoint => 'cardnumber', overwrite_cardnumber => 1, preserve_fields => ['firstname'], update_dateexpiry => 1, update_dateexpiry_from_existing => 1 }; warning_is { $patrons_import->import_patrons($params_3d) } @@ -819,8 +819,8 @@ subtest 'Import patron with guarantor' => sub { plan tests => 4; t::lib::Mocks::mock_preference( 'borrowerRelationship', 'guarantor' ); - my $category = $builder->build( { source => 'Category' } )->{categorycode}; - my $branch = $builder->build( { source => 'Branch' } )->{branchcode}; + my $category = $builder->build( { source => 'Category' } )->{categorycode}; + my $branch = $builder->build( { source => 'Branch' } )->{branchcode}; my $guarantor = Koha::Patron->new( { surname => 'Guarantor', @@ -861,11 +861,11 @@ subtest 'test_import_with_password_overwrite' => sub { my $categorycode = $builder->build( { source => "Category", value => { category_type => 'A' } } )->{categorycode}; my $staff_categorycode = $builder->build( { source => "Category", value => { category_type => 'S' } } )->{categorycode}; - my $csv_headers = 'surname,userid,branchcode,categorycode,password'; - my $csv_password = "Worrell,ErnestP,$branchcode,$categorycode,Ernest11"; - my $csv_password_change = "Worrell,ErnestP,$branchcode,$categorycode,Vern1234"; - my $csv_blank_password = "Worel,ErnestP,$branchcode,$categorycode,"; - my $defaults = { cardnumber => "" }; #currently all the defaults come as "" if not filled + my $csv_headers = 'surname,userid,branchcode,categorycode,password'; + my $csv_password = "Worrell,ErnestP,$branchcode,$categorycode,Ernest11"; + my $csv_password_change = "Worrell,ErnestP,$branchcode,$categorycode,Vern1234"; + my $csv_blank_password = "Worel,ErnestP,$branchcode,$categorycode,"; + my $defaults = { cardnumber => "" }; #currently all the defaults come as "" if not filled my $csv_staff_password_change = "Worrell,ErnestP,$branchcode,$staff_categorycode,Vern1234"; #Make the test files for importing @@ -1650,7 +1650,7 @@ subtest 'welcome_email' => sub { $builder->build( { source => "Category", value => { category_type => 'S' } } )->{categorycode}; my $csv_headers = 'surname,userid,branchcode,categorycode,password,email'; my $csv_new = "Spagobi,EldridgeS,$branchcode,$categorycode,H4ckR" . ',me@myemail.com'; - my $defaults = { cardnumber => "" }; #currently all the defaults come as "" if not filled + my $defaults = { cardnumber => "" }; #currently all the defaults come as "" if not filled #Make the test files for importing my $filename_1 = make_csv( $temp_dir, $csv_headers, $csv_new ); @@ -1739,7 +1739,7 @@ subtest 'prevent regression in update of dateexpiry with no date related flags' $patron->dateexpiry('2099-12-31'); $patron->dateenrolled( dt_from_string->add( months => '-24', end_of_month => 'limit' ) )->store; my $csv_values = join( - ',', $patron->cardnumber, $patron->surname, $patron->branchcode, $patron->categorycode, + ',', $patron->cardnumber, $patron->surname, $patron->branchcode, $patron->categorycode, $patron->dateenrolled, '' ); @@ -1755,7 +1755,7 @@ subtest 'prevent regression in update of dateexpiry with no date related flags' ); $csv_values = join( - ',', $patron->cardnumber, $patron->surname, $patron->branchcode, $patron->categorycode, + ',', $patron->cardnumber, $patron->surname, $patron->branchcode, $patron->categorycode, $patron->dateenrolled, '2098-01-01' ); diff --git a/t/db_dependent/Koha/Plugins/Account_hooks.t b/t/db_dependent/Koha/Plugins/Account_hooks.t index 4eade79abc..020248ad73 100755 --- a/t/db_dependent/Koha/Plugins/Account_hooks.t +++ b/t/db_dependent/Koha/Plugins/Account_hooks.t @@ -57,17 +57,16 @@ subtest 'Koha::Account tests' => sub { my $account = $patron->account; warning_like { - $account->add_credit({ amount => 20, interface => 'commandline', type => 'WRITEOFF'}); + $account->add_credit( { amount => 20, interface => 'commandline', type => 'WRITEOFF' } ); } qr/after_account_action called with action: add_credit, type: writeoff, ref: Koha::Account::Line/, - '->add_credit calls the after_account_action hook with type writeoff'; - + '->add_credit calls the after_account_action hook with type writeoff'; warning_like { - $account->add_credit({ amount => 10, interface => 'commandline', type => 'PAYMENT'}); + $account->add_credit( { amount => 10, interface => 'commandline', type => 'PAYMENT' } ); } qr/after_account_action called with action: add_credit, type: payment, ref: Koha::Account::Line/, - '->add_credit calls the after_account_action hook with type payment'; + '->add_credit calls the after_account_action hook with type payment'; Koha::Plugins->RemovePlugins; $schema->storage->txn_rollback; diff --git a/t/db_dependent/Koha/Plugins/BackgroundJob.t b/t/db_dependent/Koha/Plugins/BackgroundJob.t index c5ccd3763f..1bb7e3c26c 100755 --- a/t/db_dependent/Koha/Plugins/BackgroundJob.t +++ b/t/db_dependent/Koha/Plugins/BackgroundJob.t @@ -74,12 +74,14 @@ subtest 'background_tasks() hooks tests' => sub { $plugin = Koha::Plugin::Test->new; - $bj = Koha::BackgroundJob->new; + $bj = Koha::BackgroundJob->new; $tasks = $bj->type_to_class_mapping; - $logger->warn_is("A plugin includes the 'background_tasks' method, but doesn't provide the required 'namespace' method (Koha::Plugin::Test)"); + $logger->warn_is( + "A plugin includes the 'background_tasks' method, but doesn't provide the required 'namespace' method (Koha::Plugin::Test)" + ); t::lib::Mocks::mock_config( 'enable_plugins', 0 ); - $bj = Koha::BackgroundJob->new; + $bj = Koha::BackgroundJob->new; $tasks = $bj->type_to_class_mapping; is_deeply( $tasks, $bj->core_types_to_classes, 'Only core mapping returned when plugins disabled' ); diff --git a/t/db_dependent/Koha/Plugins/Barcode_transform_hooks.t b/t/db_dependent/Koha/Plugins/Barcode_transform_hooks.t index 234f7d572f..c712340119 100755 --- a/t/db_dependent/Koha/Plugins/Barcode_transform_hooks.t +++ b/t/db_dependent/Koha/Plugins/Barcode_transform_hooks.t @@ -59,8 +59,7 @@ subtest 'patron_barcode_transform() and item_barcode_transform() hook tests' => my $plugin = Koha::Plugin::Test->new->enable; - my $patron = $builder->build_object( - { class => 'Koha::Patrons', value => { cardnumber => undef } } ); + my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { cardnumber => undef } } ); t::lib::Mocks::mock_preference( 'autoMemberNum', 1 ); warnings_like { $patron->store(); } @@ -68,17 +67,17 @@ subtest 'patron_barcode_transform() and item_barcode_transform() hook tests' => qr/patron_barcode_transform called with parameter: /, qr/patron_barcode_transform called with parameter: / ], - 'Koha::Patron::store calls the patron_barcode_transform hook twice when autoMemberNum is enabled and cardnumber is undefined'; + 'Koha::Patron::store calls the patron_barcode_transform hook twice when autoMemberNum is enabled and cardnumber is undefined'; $patron->cardnumber('TEST'); warning_like { $patron->store(); } - qr/patron_barcode_transform called with parameter: TEST/, + qr/patron_barcode_transform called with parameter: TEST/, 'Koha::Patron::store calls the patron_barcode_transform hook once when autoMemberNum is enabled and cardnumber is set'; t::lib::Mocks::mock_preference( 'autoMemberNum', 0 ); $patron->cardnumber(undef); warning_like { $patron->store(); } - qr/patron_barcode_transform called with parameter: /, + qr/patron_barcode_transform called with parameter: /, 'Koha::Patron::store calls the patron_barcode_transform hook once when autoMemberNum is disabled and cardnumber is undefined'; t::lib::Mocks::mock_userenv( @@ -90,13 +89,13 @@ subtest 'patron_barcode_transform() and item_barcode_transform() hook tests' => my $item; warning_like { $item = $builder->build_sample_item(); } - qr/Plugin error \(Test Plugin\): Exception 'Koha::Exception' thrown 'item_barcode_transform called with parameter: /, + qr/Plugin error \(Test Plugin\): Exception 'Koha::Exception' thrown 'item_barcode_transform called with parameter: /, 'Koha::Item->store calls the item_barcode_transform hook'; $item->barcode('THISISATEST'); warning_like { $item->store(); } - qr/Plugin error \(Test Plugin\): Exception 'Koha::Exception' thrown 'item_barcode_transform called with parameter: THISISATEST'/, + qr/Plugin error \(Test Plugin\): Exception 'Koha::Exception' thrown 'item_barcode_transform called with parameter: THISISATEST'/, 'Koha::Item->store calls the item_barcode_transform hook'; Koha::Plugins->RemovePlugins; diff --git a/t/db_dependent/Koha/Plugins/Biblio_and_Items_plugin_hooks.t b/t/db_dependent/Koha/Plugins/Biblio_and_Items_plugin_hooks.t index 4464fb407a..68ebfd3a76 100755 --- a/t/db_dependent/Koha/Plugins/Biblio_and_Items_plugin_hooks.t +++ b/t/db_dependent/Koha/Plugins/Biblio_and_Items_plugin_hooks.t @@ -59,30 +59,30 @@ subtest 'after_biblio_action() and after_item_action() hooks tests' => sub { my $biblio_id; warning_like { ( $biblio_id, undef ) = C4::Biblio::AddBiblio( MARC::Record->new(), '' ); } - qr/after_biblio_action called with action: create, ref: Koha::Biblio/, - 'AddBiblio calls the hook with action=create'; + qr/after_biblio_action called with action: create, ref: Koha::Biblio/, + 'AddBiblio calls the hook with action=create'; warning_like { C4::Biblio::ModBiblio( MARC::Record->new(), $biblio_id, '' ); } - qr/after_biblio_action called with action: modify, ref: Koha::Biblio/, - 'ModBiblio calls the hook with action=modify'; + qr/after_biblio_action called with action: modify, ref: Koha::Biblio/, + 'ModBiblio calls the hook with action=modify'; my $item; - warning_like { $item = $builder->build_sample_item({ biblionumber => $biblio_id }); } - qr/after_item_action called with action: create, ref: Koha::Item item_id defined: yes itemnumber defined: yes/, - 'AddItem calls the hook with action=create'; + warning_like { $item = $builder->build_sample_item( { biblionumber => $biblio_id } ); } + qr/after_item_action called with action: create, ref: Koha::Item item_id defined: yes itemnumber defined: yes/, + 'AddItem calls the hook with action=create'; warning_like { $item->location('shelves')->store; } - qr/after_item_action called with action: modify, ref: Koha::Item item_id defined: yes itemnumber defined: yes/, - 'ModItem calls the hook with action=modify'; + qr/after_item_action called with action: modify, ref: Koha::Item item_id defined: yes itemnumber defined: yes/, + 'ModItem calls the hook with action=modify'; my $itemnumber = $item->id; warning_like { $item->delete; } - qr/after_item_action called with action: delete, id: $itemnumber/, - 'DelItem calls the hook with action=delete, item_id passed'; + qr/after_item_action called with action: delete, id: $itemnumber/, + 'DelItem calls the hook with action=delete, item_id passed'; - warning_like { C4::Biblio::DelBiblio( $biblio_id ); } - qr/after_biblio_action called with action: delete, id: $biblio_id/, - 'DelBiblio calls the hook with action=delete biblio_id passed'; + warning_like { C4::Biblio::DelBiblio($biblio_id); } + qr/after_biblio_action called with action: delete, id: $biblio_id/, + 'DelBiblio calls the hook with action=delete biblio_id passed'; Koha::Plugins->RemovePlugins; $schema->storage->txn_rollback; @@ -127,6 +127,7 @@ subtest 'before_biblio_action() hooks tests' => sub { $record = Koha::Biblios->find($biblio_id)->record; @fields_990 = $record->field('990'); + # This is to highlight that is the plugin responsibility to choose what to do on the record is( scalar @fields_990, 2, 'Two saves, two fields' ); diff --git a/t/db_dependent/Koha/Plugins/Circulation_hooks.t b/t/db_dependent/Koha/Plugins/Circulation_hooks.t index 47ac5d58af..a017b25079 100755 --- a/t/db_dependent/Koha/Plugins/Circulation_hooks.t +++ b/t/db_dependent/Koha/Plugins/Circulation_hooks.t @@ -64,8 +64,8 @@ subtest 'after_circ_action() hook tests' => sub { # Avoid testing useless warnings my $test_plugin = Test::MockModule->new('Koha::Plugin::Test'); - $test_plugin->mock( 'after_item_action', undef ); - $test_plugin->mock( 'after_biblio_action', undef ); + $test_plugin->mock( 'after_item_action', undef ); + $test_plugin->mock( 'after_biblio_action', undef ); $test_plugin->mock( 'item_barcode_transform', sub { my ( $self, $barcode ) = @_; return $barcode; } ); my $biblio = $builder->build_sample_biblio(); @@ -77,11 +77,11 @@ subtest 'after_circ_action() hook tests' => sub { warning_like { AddIssue( $patron, $item_1->barcode ); } qr/after_circ_action called with action: checkout, ref: Koha::Checkout type: issue/, - 'AddIssue calls the after_circ_action hook'; + 'AddIssue calls the after_circ_action hook'; warning_like { AddIssue( $patron, $item_2->barcode, undef, undef, undef, undef, { onsite_checkout => 1 } ); } qr/after_circ_action called with action: checkout, ref: Koha::Checkout type: onsite_checkout/, - 'AddIssue calls the after_circ_action hook (onsite_checkout case)'; + 'AddIssue calls the after_circ_action hook (onsite_checkout case)'; }; subtest 'AddRenewal' => sub { @@ -96,28 +96,29 @@ subtest 'after_circ_action() hook tests' => sub { } ); } - qr/after_circ_action called with action: renewal, ref: Koha::Checkout/, - 'AddRenewal calls the after_circ_action hook'; + qr/after_circ_action called with action: renewal, ref: Koha::Checkout/, + 'AddRenewal calls the after_circ_action hook'; }; subtest 'AddReturn' => sub { plan tests => 2; - t::lib::Mocks::mock_preference('BlockReturnOfWithdrawnItems', 1); - $item_1->set({ withdrawn => 1 })->store; + t::lib::Mocks::mock_preference( 'BlockReturnOfWithdrawnItems', 1 ); + $item_1->set( { withdrawn => 1 } )->store; warning_is { AddReturn( $item_1->barcode, $patron->branchcode ); - } undef, 'No hook called because no return happened'; + } + undef, 'No hook called because no return happened'; - t::lib::Mocks::mock_preference('BlockReturnOfWithdrawnItems', 0); - $item_1->set({ withdrawn => 0 })->store; + t::lib::Mocks::mock_preference( 'BlockReturnOfWithdrawnItems', 0 ); + $item_1->set( { withdrawn => 0 } )->store; warning_like { AddReturn( $item_1->barcode, $patron->branchcode ); } qr/after_circ_action called with action: checkin, ref: Koha::Old::Checkout/, - 'AddReturn calls the after_circ_action hook'; + 'AddReturn calls the after_circ_action hook'; }; Koha::Plugins->RemovePlugins; diff --git a/t/db_dependent/Koha/Plugins/Holds_hooks.t b/t/db_dependent/Koha/Plugins/Holds_hooks.t index dd4d84755a..b2df421f8a 100755 --- a/t/db_dependent/Koha/Plugins/Holds_hooks.t +++ b/t/db_dependent/Koha/Plugins/Holds_hooks.t @@ -64,22 +64,29 @@ subtest 'after_hold_create() hook tests' => sub { # Avoid testing useless warnings my $test_plugin = Test::MockModule->new('Koha::Plugin::Test'); - $test_plugin->mock( 'after_item_action', undef ); - $test_plugin->mock( 'after_biblio_action', undef ); + $test_plugin->mock( 'after_item_action', undef ); + $test_plugin->mock( 'after_biblio_action', undef ); $test_plugin->mock( 'item_barcode_transform', undef ); - $test_plugin->mock( 'after_hold_action', undef ); - $test_plugin->mock( 'before_send_messages', undef ); + $test_plugin->mock( 'after_hold_action', undef ); + $test_plugin->mock( 'before_send_messages', undef ); my $biblio = $builder->build_sample_biblio(); my $item_1 = $builder->build_sample_item( { biblionumber => $biblio->biblionumber } ); - warnings_like { AddReserve({ - branchcode => $patron->branchcode, - borrowernumber => $patron->borrowernumber, - biblionumber => $item_1->biblionumber }); } - [ qr/after_hold_create is deprecated and will be removed soon/, - qr/after_hold_create called with parameter Koha::Hold/ ], - 'AddReserve calls the after_hold_create hook, deprecation warning found'; + warnings_like { + AddReserve( + { + branchcode => $patron->branchcode, + borrowernumber => $patron->borrowernumber, + biblionumber => $item_1->biblionumber + } + ); + } + [ + qr/after_hold_create is deprecated and will be removed soon/, + qr/after_hold_create called with parameter Koha::Hold/ + ], + 'AddReserve calls the after_hold_create hook, deprecation warning found'; Koha::Plugins->RemovePlugins; $schema->storage->txn_rollback; @@ -107,23 +114,28 @@ subtest 'after_hold_action (placed) hook tests' => sub { # Avoid testing useless warnings my $test_plugin = Test::MockModule->new('Koha::Plugin::Test'); - $test_plugin->mock( 'after_item_action', undef ); - $test_plugin->mock( 'after_biblio_action', undef ); + $test_plugin->mock( 'after_item_action', undef ); + $test_plugin->mock( 'after_biblio_action', undef ); $test_plugin->mock( 'item_barcode_transform', undef ); - $test_plugin->mock( 'after_hold_create', undef ); + $test_plugin->mock( 'after_hold_create', undef ); my $biblio = $builder->build_sample_biblio(); my $item_1 = $builder->build_sample_item( { biblionumber => $biblio->biblionumber } ); warnings_like { AddReserve( - { branchcode => $patron->branchcode, + { + branchcode => $patron->branchcode, borrowernumber => $patron->borrowernumber, biblionumber => $item_1->biblionumber } ); } - [ qr/after_hold_create is deprecated and will be removed soon/, qr/after_hold_action called with action: place, ref: Koha::Hold/, ], 'AddReserve calls the after_hold_action hook'; + [ + qr/after_hold_create is deprecated and will be removed soon/, + qr/after_hold_action called with action: place, ref: Koha::Hold/, + ], + 'AddReserve calls the after_hold_action hook'; Koha::Plugins->RemovePlugins; $schema->storage->txn_rollback; @@ -159,7 +171,7 @@ subtest 'Koha::Hold tests' => sub { $hold->fill; } qr/after_hold_action called with action: fill, ref: Koha::Old::Hold/, - '->fill calls the after_hold_action hook'; + '->fill calls the after_hold_action hook'; $hold = $builder->build_object( { @@ -174,37 +186,37 @@ subtest 'Koha::Hold tests' => sub { $hold->suspend_hold; } qr/after_hold_action called with action: suspend, ref: Koha::Hold/, - '->suspend_hold calls the after_hold_action hook'; + '->suspend_hold calls the after_hold_action hook'; warning_like { $hold->resume; } qr/after_hold_action called with action: resume, ref: Koha::Hold/, - '->resume calls the after_hold_action hook'; + '->resume calls the after_hold_action hook'; warning_like { $hold->set_transfer; } qr/after_hold_action called with action: transfer, ref: Koha::Hold/, - '->set_transfer calls the after_hold_action hook'; + '->set_transfer calls the after_hold_action hook'; warning_like { $hold->set_processing; } qr/after_hold_action called with action: processing, ref: Koha::Hold/, - '->set_processing calls the after_hold_action hook'; + '->set_processing calls the after_hold_action hook'; warning_like { $hold->set_waiting; } qr/after_hold_action called with action: waiting, ref: Koha::Hold/, - '->set_waiting calls the after_hold_action hook'; + '->set_waiting calls the after_hold_action hook'; warning_like { $hold->cancel; } qr/after_hold_action called with action: cancel, ref: Koha::Old::Hold/, - '->cancel calls the after_hold_action hook'; + '->cancel calls the after_hold_action hook'; Koha::Plugins->RemovePlugins; $schema->storage->txn_rollback; diff --git a/t/db_dependent/Koha/Plugins/Patron.t b/t/db_dependent/Koha/Plugins/Patron.t index eb001c8881..ebe4531b08 100755 --- a/t/db_dependent/Koha/Plugins/Patron.t +++ b/t/db_dependent/Koha/Plugins/Patron.t @@ -70,22 +70,25 @@ subtest 'check_password hook tests' => sub { # store hook (add action) $patron->password('exploder'); throws_ok { $patron->store } 'Koha::Exceptions::Password::Plugin', - 'Plugin Exception raised for adding patron with bad password'; + 'Plugin Exception raised for adding patron with bad password'; $patron->password('1234'); ok( $patron->store, 'Patron created with good password' ); $patron->discard_changes; $patron->password('87654321'); $patron->store; - isnt($patron->password, '87654321', 'Koha::Patron->store silently drops changes to password'); + isnt( $patron->password, '87654321', 'Koha::Patron->store silently drops changes to password' ); # set_password hook (update action) t::lib::Mocks::mock_preference( 'RequireStrongPassword', '0' ); - t::lib::Mocks::mock_preference( 'minPasswordLength', '4' ); # Testing Plugin validation, not internal validation - throws_ok { $patron->set_password({ password => 'explosion' }) } 'Koha::Exceptions::Password::Plugin', - 'Exception raised for update patron password with bad string'; - ok( $patron->set_password({ password => '4321' }), 'Patron password updated with good string' ); - ok( $patron->set_password({ password => 'explosion', skip_validation => 1}), 'Patron password updated via skip validation'); + t::lib::Mocks::mock_preference( 'minPasswordLength', '4' ); # Testing Plugin validation, not internal validation + throws_ok { $patron->set_password( { password => 'explosion' } ) } 'Koha::Exceptions::Password::Plugin', + 'Exception raised for update patron password with bad string'; + ok( $patron->set_password( { password => '4321' } ), 'Patron password updated with good string' ); + ok( + $patron->set_password( { password => 'explosion', skip_validation => 1 } ), + 'Patron password updated via skip validation' + ); Koha::Plugins->RemovePlugins; $schema->storage->txn_rollback; diff --git a/t/db_dependent/Koha/Plugins/Plugins.t b/t/db_dependent/Koha/Plugins/Plugins.t index 90e505c0d3..c8b8163b37 100755 --- a/t/db_dependent/Koha/Plugins/Plugins.t +++ b/t/db_dependent/Koha/Plugins/Plugins.t @@ -20,8 +20,8 @@ use CGI; use Cwd qw(abs_path); use File::Basename; use File::Spec; -use File::Temp qw( tempdir tempfile ); -use FindBin qw($Bin); +use File::Temp qw( tempdir tempfile ); +use FindBin qw($Bin); use Module::Load::Conditional qw(can_load); use Test::MockModule; use Test::More tests => 18; @@ -56,11 +56,12 @@ subtest 'call() tests' => sub { plan tests => 4; $schema->storage->txn_begin; + # Temporarily remove any installed plugins data Koha::Plugins->RemovePlugins( { destructive => 1 } ); - t::lib::Mocks::mock_config('enable_plugins', 1); - my $plugins = Koha::Plugins->new({ enable_plugins => 1 }); + t::lib::Mocks::mock_config( 'enable_plugins', 1 ); + my $plugins = Koha::Plugins->new( { enable_plugins => 1 } ); my @plugins; @@ -70,20 +71,20 @@ subtest 'call() tests' => sub { $plugin->enable(); } - my @responses = Koha::Plugins->call('check_password', { password => 'foo' }); + my @responses = Koha::Plugins->call( 'check_password', { password => 'foo' } ); my $expected = [ { error => 1, msg => 'PIN should be four digits' } ]; - is_deeply(\@responses, $expected, 'call() should return all responses from plugins'); + is_deeply( \@responses, $expected, 'call() should return all responses from plugins' ); # Make sure parameters are correctly passed to the plugin method - @responses = Koha::Plugins->call('check_password', { password => '1234' }); + @responses = Koha::Plugins->call( 'check_password', { password => '1234' } ); $expected = [ { error => 0 } ]; - is_deeply(\@responses, $expected, 'call() should return all responses from plugins'); + is_deeply( \@responses, $expected, 'call() should return all responses from plugins' ); - t::lib::Mocks::mock_config('enable_plugins', 0); - @responses = Koha::Plugins->call('check_password', { password => '1234' }); - is_deeply(\@responses, [], 'call() should return an empty array if plugins are disabled'); + t::lib::Mocks::mock_config( 'enable_plugins', 0 ); + @responses = Koha::Plugins->call( 'check_password', { password => '1234' } ); + is_deeply( \@responses, [], 'call() should return an empty array if plugins are disabled' ); $schema->storage->txn_rollback; }; @@ -93,11 +94,12 @@ subtest 'more call() tests' => sub { plan tests => 6; $schema->storage->txn_begin; + # Temporarily remove any installed plugins data Koha::Plugins->RemovePlugins( { destructive => 1 } ); - t::lib::Mocks::mock_config('enable_plugins', 1); - my $plugins = Koha::Plugins->new({ enable_plugins => 1 }); + t::lib::Mocks::mock_config( 'enable_plugins', 1 ); + my $plugins = Koha::Plugins->new( { enable_plugins => 1 } ); my @plugins; warning_is { @plugins = $plugins->InstallPlugins; } undef; @@ -109,22 +111,24 @@ subtest 'more call() tests' => sub { # Barcode is multiplied by 2 by Koha::Plugin::Test, and again by 4 by Koha::Plugin::TestItemBarcodeTransform # showing that call has passed the same ref to multiple plugins to operate on my $bc = 1; - warnings_are - { Koha::Plugins->call('item_barcode_transform', \$bc); } - [ qq{Plugin error (Test Plugin): Exception 'Koha::Exception' thrown 'item_barcode_transform called with parameter: 1'\n}, - qq{Plugin error (Test Plugin for item_barcode_transform): Exception 'Koha::Exception' thrown 'item_barcode_transform called with parameter: 2'\n} ]; + warnings_are { Koha::Plugins->call( 'item_barcode_transform', \$bc ); } + [ + qq{Plugin error (Test Plugin): Exception 'Koha::Exception' thrown 'item_barcode_transform called with parameter: 1'\n}, + qq{Plugin error (Test Plugin for item_barcode_transform): Exception 'Koha::Exception' thrown 'item_barcode_transform called with parameter: 2'\n} + ]; is( $bc, 8, "Got expected response" ); my $cn = 'abcd'; - warnings_are - { Koha::Plugins->call('item_barcode_transform', \$bc); } - [ qq{Plugin error (Test Plugin): Exception 'Koha::Exception' thrown 'item_barcode_transform called with parameter: 8'\n}, - qq{Plugin error (Test Plugin for item_barcode_transform): Exception 'Koha::Exception' thrown 'item_barcode_transform called with parameter: 16'\n} ]; + warnings_are { Koha::Plugins->call( 'item_barcode_transform', \$bc ); } + [ + qq{Plugin error (Test Plugin): Exception 'Koha::Exception' thrown 'item_barcode_transform called with parameter: 8'\n}, + qq{Plugin error (Test Plugin for item_barcode_transform): Exception 'Koha::Exception' thrown 'item_barcode_transform called with parameter: 16'\n} + ]; is( $cn, 'abcd', "Got expected response" ); - t::lib::Mocks::mock_config('enable_plugins', 0); + t::lib::Mocks::mock_config( 'enable_plugins', 0 ); $bc = 1; - Koha::Plugins->call('item_barcode_transform', \$bc); + Koha::Plugins->call( 'item_barcode_transform', \$bc ); is( $bc, 1, "call should return the original arguments if plugins are disabled" ); $schema->storage->txn_rollback; @@ -166,20 +170,21 @@ subtest 'GetPlugins() tests' => sub { plan tests => 3; $schema->storage->txn_begin; + # Temporarily remove any installed plugins data (FIXME not done) Koha::Plugins->RemovePlugins; - my $plugins = Koha::Plugins->new({ enable_plugins => 1 }); + my $plugins = Koha::Plugins->new( { enable_plugins => 1 } ); warning_is { $plugins->InstallPlugins; } undef; - my @plugins = $plugins->GetPlugins({ method => 'report', all => 1 }); + my @plugins = $plugins->GetPlugins( { method => 'report', all => 1 } ); my @names = map { $_->get_metadata()->{'name'} } @plugins; - is( scalar grep( /^Test Plugin$/, @names), 1, "Koha::Plugins::GetPlugins functions correctly" ); + is( scalar grep( /^Test Plugin$/, @names ), 1, "Koha::Plugins::GetPlugins functions correctly" ); - @plugins = $plugins->GetPlugins({ metadata => { my_example_tag => 'find_me' }, all => 1 }); - @names = map { $_->get_metadata()->{'name'} } @plugins; + @plugins = $plugins->GetPlugins( { metadata => { my_example_tag => 'find_me' }, all => 1 } ); + @names = map { $_->get_metadata()->{'name'} } @plugins; is( scalar @names, 2, "Only two plugins found via a metadata tag" ); $schema->storage->txn_rollback; @@ -212,7 +217,7 @@ subtest 'is_enabled() tests' => sub { # Make sure there's no previous installs or leftovers on DB Koha::Plugins->RemovePlugins( { destructive => 1 } ); - my $plugin = Koha::Plugin::Test->new({ enable_plugins => 1, cgi => CGI->new }); + my $plugin = Koha::Plugin::Test->new( { enable_plugins => 1, cgi => CGI->new } ); ok( $plugin->is_enabled, 'Plugins enabled by default' ); # disable @@ -232,50 +237,66 @@ subtest 'Koha::Plugin::Test' => sub { warning_is { Koha::Plugins->new( { enable_plugins => 1 } )->InstallPlugins(); } undef; - ok( Koha::Plugins::Methods->search( { plugin_class => 'Koha::Plugin::Test' } )->count, 'Test plugin methods added to database' ); - is( Koha::Plugins::Methods->search({ plugin_class => 'Koha::Plugin::Test', plugin_method => '_private_sub' })->count, 0, 'Private methods are skipped' ); + ok( + Koha::Plugins::Methods->search( { plugin_class => 'Koha::Plugin::Test' } )->count, + 'Test plugin methods added to database' + ); + is( Koha::Plugins::Methods->search( { plugin_class => 'Koha::Plugin::Test', plugin_method => '_private_sub' } ) + ->count, 0, 'Private methods are skipped' ); - my $mock_plugin = Test::MockModule->new( 'Koha::Plugin::Test' ); - $mock_plugin->mock( 'test_template', sub { - my ( $self, $file ) = @_; - my $template = $self->get_template({ file => $file }); - $template->param( filename => $file ); - return $template->output; - }); + my $mock_plugin = Test::MockModule->new('Koha::Plugin::Test'); + $mock_plugin->mock( + 'test_template', + sub { + my ( $self, $file ) = @_; + my $template = $self->get_template( { file => $file } ); + $template->param( filename => $file ); + return $template->output; + } + ); ok( can_load( modules => { "Koha::Plugin::Test" => undef } ), 'Test can_load' ); - my $plugin = Koha::Plugin::Test->new({ enable_plugins => 1, cgi => CGI->new }); + my $plugin = Koha::Plugin::Test->new( { enable_plugins => 1, cgi => CGI->new } ); - isa_ok( $plugin, "Koha::Plugin::Test", 'Test plugin class' ); + isa_ok( $plugin, "Koha::Plugin::Test", 'Test plugin class' ); isa_ok( $plugin, "Koha::Plugins::Base", 'Test plugin parent class' ); - ok( $plugin->can('report'), 'Test plugin can report' ); - ok( $plugin->can('tool'), 'Test plugin can tool' ); - ok( $plugin->can('to_marc'), 'Test plugin can to_marc' ); - ok( $plugin->can('intranet_catalog_biblio_enhancements'), 'Test plugin can intranet_catalog_biblio_enhancements'); - ok( $plugin->can('intranet_catalog_biblio_enhancements_toolbar_button'), 'Test plugin can intranet_catalog_biblio_enhancements_toolbar_button' ); - ok( $plugin->can('opac_online_payment'), 'Test plugin can opac_online_payment' ); - ok( $plugin->can('after_hold_create'), 'Test plugin can after_hold_create' ); - ok( $plugin->can('before_send_messages'), 'Test plugin can before_send_messages' ); + ok( $plugin->can('report'), 'Test plugin can report' ); + ok( $plugin->can('tool'), 'Test plugin can tool' ); + ok( $plugin->can('to_marc'), 'Test plugin can to_marc' ); + ok( $plugin->can('intranet_catalog_biblio_enhancements'), 'Test plugin can intranet_catalog_biblio_enhancements' ); + ok( + $plugin->can('intranet_catalog_biblio_enhancements_toolbar_button'), + 'Test plugin can intranet_catalog_biblio_enhancements_toolbar_button' + ); + ok( $plugin->can('opac_online_payment'), 'Test plugin can opac_online_payment' ); + ok( $plugin->can('after_hold_create'), 'Test plugin can after_hold_create' ); + ok( $plugin->can('before_send_messages'), 'Test plugin can before_send_messages' ); ok( $plugin->can('opac_online_payment_begin'), 'Test plugin can opac_online_payment_begin' ); - ok( $plugin->can('opac_online_payment_end'), 'Test plugin can opac_online_payment_end' ); - ok( $plugin->can('opac_head'), 'Test plugin can opac_head' ); - ok( $plugin->can('opac_js'), 'Test plugin can opac_js' ); - ok( $plugin->can('intranet_head'), 'Test plugin can intranet_head' ); - ok( $plugin->can('intranet_js'), 'Test plugin can intranet_js' ); - ok( $plugin->can('item_barcode_transform'), 'Test plugin can barcode_transform' ); - ok( $plugin->can('configure'), 'Test plugin can configure' ); - ok( $plugin->can('install'), 'Test plugin can install' ); - ok( $plugin->can('upgrade'), 'Test plugin can upgrade' ); - ok( $plugin->can('uninstall'), 'Test plugin can install' ); + ok( $plugin->can('opac_online_payment_end'), 'Test plugin can opac_online_payment_end' ); + ok( $plugin->can('opac_head'), 'Test plugin can opac_head' ); + ok( $plugin->can('opac_js'), 'Test plugin can opac_js' ); + ok( $plugin->can('intranet_head'), 'Test plugin can intranet_head' ); + ok( $plugin->can('intranet_js'), 'Test plugin can intranet_js' ); + ok( $plugin->can('item_barcode_transform'), 'Test plugin can barcode_transform' ); + ok( $plugin->can('configure'), 'Test plugin can configure' ); + ok( $plugin->can('install'), 'Test plugin can install' ); + ok( $plugin->can('upgrade'), 'Test plugin can upgrade' ); + ok( $plugin->can('uninstall'), 'Test plugin can install' ); - is( Koha::Plugins::Handler->run({ class => "Koha::Plugin::Test", method => 'report', enable_plugins => 1 }), "Koha::Plugin::Test::report", 'Test run plugin report method' ); + is( + Koha::Plugins::Handler->run( { class => "Koha::Plugin::Test", method => 'report', enable_plugins => 1 } ), + "Koha::Plugin::Test::report", 'Test run plugin report method' + ); my $metadata = $plugin->get_metadata(); is( $metadata->{'name'}, 'Test Plugin', 'Test $plugin->get_metadata()' ); - is( $plugin->get_qualified_table_name('mytable'), 'koha_plugin_test_mytable', 'Test $plugin->get_qualified_table_name()' ); + is( + $plugin->get_qualified_table_name('mytable'), 'koha_plugin_test_mytable', + 'Test $plugin->get_qualified_table_name()' + ); is( $plugin->get_plugin_http_path(), '/plugin/Koha/Plugin/Test', 'Test $plugin->get_plugin_http_path()' ); # test absolute path change in get_template with Koha::Plugin::Test @@ -292,29 +313,29 @@ subtest 'Koha::Plugin::Test' => sub { is( ref($result), 'Koha::Plugin::Test' ); # testing GetPlugins - my @plugins = Koha::Plugins->new({ enable_plugins => 1 })->GetPlugins({ - method => 'report' - }); + my @plugins = Koha::Plugins->new( { enable_plugins => 1 } )->GetPlugins( { method => 'report' } ); my @names = map { $_->get_metadata()->{'name'} } @plugins; - is( scalar grep( /^Test Plugin$/, @names), 1, "Koha::Plugins::GetPlugins functions correctly" ); - @plugins = Koha::Plugins->new({ enable_plugins => 1 })->GetPlugins({ - metadata => { my_example_tag => 'find_me' }, - }); + is( scalar grep( /^Test Plugin$/, @names ), 1, "Koha::Plugins::GetPlugins functions correctly" ); + @plugins = Koha::Plugins->new( { enable_plugins => 1 } )->GetPlugins( + { + metadata => { my_example_tag => 'find_me' }, + } + ); @names = map { $_->get_metadata()->{'name'} } @plugins; - is( scalar grep( /^Test Plugin$/, @names), 1, "GetPlugins also found Test Plugin via a metadata tag" ); + is( scalar grep( /^Test Plugin$/, @names ), 1, "GetPlugins also found Test Plugin via a metadata tag" ); $result = $plugin->disable; is( ref($result), 'Koha::Plugin::Test' ); - @plugins = Koha::Plugins->new({ enable_plugins => 1 })->GetPlugins(); - @names = map { $_->get_metadata()->{'name'} } @plugins; - is( scalar grep( /^Test Plugin$/, @names), 0, "GetPlugins does not found disabled Test Plugin" ); + @plugins = Koha::Plugins->new( { enable_plugins => 1 } )->GetPlugins(); + @names = map { $_->get_metadata()->{'name'} } @plugins; + is( scalar grep( /^Test Plugin$/, @names ), 0, "GetPlugins does not found disabled Test Plugin" ); - @plugins = Koha::Plugins->new({ enable_plugins => 1 })->GetPlugins({ all => 1 }); - @names = map { $_->get_metadata()->{'name'} } @plugins; - is( scalar grep( /^Test Plugin$/, @names), 1, "With all param, GetPlugins found disabled Test Plugin" ); + @plugins = Koha::Plugins->new( { enable_plugins => 1 } )->GetPlugins( { all => 1 } ); + @names = map { $_->get_metadata()->{'name'} } @plugins; + is( scalar grep( /^Test Plugin$/, @names ), 1, "With all param, GetPlugins found disabled Test Plugin" ); $schema->storage->txn_rollback; }; @@ -442,12 +463,12 @@ subtest 'output and output_html tests' => sub { my $stdout; open STDOUT, '>', \$stdout; - my $plugin = Koha::Plugin::Test->new({ enable_plugins => 1, cgi => CGI->new }); + my $plugin = Koha::Plugin::Test->new( { enable_plugins => 1, cgi => CGI->new } ); $plugin->test_output; - like($stdout, qr/Cache-control: no-cache/, 'force_no_caching sets Cache-control as desired'); - like($stdout, qr{Content-Type: application/json; charset=UTF-8}, 'Correct content-type'); - like($stdout, qr{¡Hola output!}, 'Correct data'); + like( $stdout, qr/Cache-control: no-cache/, 'force_no_caching sets Cache-control as desired' ); + like( $stdout, qr{Content-Type: application/json; charset=UTF-8}, 'Correct content-type' ); + like( $stdout, qr{¡Hola output!}, 'Correct data' ); # reset the stdout buffer $stdout = ''; @@ -456,9 +477,9 @@ subtest 'output and output_html tests' => sub { $plugin->test_output_html; - like($stdout, qr/Cache-control: no-cache/, 'force_no_caching sets Cache-control as desired'); - like($stdout, qr{Content-Type: text/html; charset=UTF-8}, 'Correct content-type'); - like($stdout, qr{¡Hola output_html!}, 'Correct data'); + like( $stdout, qr/Cache-control: no-cache/, 'force_no_caching sets Cache-control as desired' ); + like( $stdout, qr{Content-Type: text/html; charset=UTF-8}, 'Correct content-type' ); + like( $stdout, qr{¡Hola output_html!}, 'Correct data' ); }; subtest 'Test _version_compare' => sub { @@ -468,20 +489,20 @@ subtest 'Test _version_compare' => sub { t::lib::Mocks::mock_config( 'enable_plugins', 1 ); is( Koha::Plugins::Base::_version_compare( '1.1.1', '2.2.2' ), -1, "1.1.1 is less then 2.2.2" ); - is( Koha::Plugins::Base::_version_compare( '2.2.2', '1.1.1' ), 1, "1.1.1 is greater then 2.2.2" ); - is( Koha::Plugins::Base::_version_compare( '1.1.1', '1.1.1' ), 0, "1.1.1 is equal to 1.1.1" ); - is( Koha::Plugins::Base::_version_compare( '1.01.001', '1.1.1' ), 0, "1.01.001 is equal to 1.1.1" ); - is( Koha::Plugins::Base::_version_compare( '1', '1.0.0' ), 0, "1 is equal to 1.0.0" ); - is( Koha::Plugins::Base::_version_compare( '1.0', '1.0.0' ), 0, "1.0 is equal to 1.0.0" ); + is( Koha::Plugins::Base::_version_compare( '2.2.2', '1.1.1' ), 1, "1.1.1 is greater then 2.2.2" ); + is( Koha::Plugins::Base::_version_compare( '1.1.1', '1.1.1' ), 0, "1.1.1 is equal to 1.1.1" ); + is( Koha::Plugins::Base::_version_compare( '1.01.001', '1.1.1' ), 0, "1.01.001 is equal to 1.1.1" ); + is( Koha::Plugins::Base::_version_compare( '1', '1.0.0' ), 0, "1 is equal to 1.0.0" ); + is( Koha::Plugins::Base::_version_compare( '1.0', '1.0.0' ), 0, "1.0 is equal to 1.0.0" ); # OO tests my $plugin = Koha::Plugin::Test->new; is( $plugin->_version_compare( '1.1.1', '2.2.2' ), -1, "1.1.1 is less then 2.2.2" ); - is( $plugin->_version_compare( '2.2.2', '1.1.1' ), 1, "1.1.1 is greater then 2.2.2" ); - is( $plugin->_version_compare( '1.1.1', '1.1.1' ), 0, "1.1.1 is equal to 1.1.1" ); - is( $plugin->_version_compare( '1.01.001', '1.1.1' ), 0, "1.01.001 is equal to 1.1.1" ); - is( $plugin->_version_compare( '1', '1.0.0' ), 0, "1 is equal to 1.0.0" ); - is( $plugin->_version_compare( '1.0', '1.0.0' ), 0, "1.0 is equal to 1.0.0" ); + is( $plugin->_version_compare( '2.2.2', '1.1.1' ), 1, "1.1.1 is greater then 2.2.2" ); + is( $plugin->_version_compare( '1.1.1', '1.1.1' ), 0, "1.1.1 is equal to 1.1.1" ); + is( $plugin->_version_compare( '1.01.001', '1.1.1' ), 0, "1.01.001 is equal to 1.1.1" ); + is( $plugin->_version_compare( '1', '1.0.0' ), 0, "1 is equal to 1.0.0" ); + is( $plugin->_version_compare( '1.0', '1.0.0' ), 0, "1.0 is equal to 1.0.0" ); }; subtest 'bundle_path() tests' => sub { @@ -490,13 +511,17 @@ subtest 'bundle_path() tests' => sub { t::lib::Mocks::mock_config( 'enable_plugins', 1 ); - my @current_dir = File::Spec->splitdir(abs_path(__FILE__)); + my @current_dir = File::Spec->splitdir( abs_path(__FILE__) ); + # remote Plugins.t pop @current_dir; + # remove /Plugins pop @current_dir; + # remove /Koha pop @current_dir; + # remove db_dependent pop @current_dir; @@ -510,15 +535,16 @@ subtest 'new() tests' => sub { plan tests => 2; - t::lib::Mocks::mock_config( 'pluginsdir', [ C4::Context->temporary_directory ] ); + t::lib::Mocks::mock_config( 'pluginsdir', [ C4::Context->temporary_directory ] ); t::lib::Mocks::mock_config( 'enable_plugins', 0 ); my $result = Koha::Plugins->new(); is( $result, undef, 'calling new() on disabled plugins returns undef' ); - $result = Koha::Plugins->new({ enable_plugins => 1 }); + $result = Koha::Plugins->new( { enable_plugins => 1 } ); is( ref($result), 'Koha::Plugins', 'calling new with enable_plugins makes it override the config' ); }; $schema->storage->txn_rollback; + #!/usr/bin/perl diff --git a/t/db_dependent/Koha/Plugins/Recall_hooks.t b/t/db_dependent/Koha/Plugins/Recall_hooks.t index 536e4a5660..f62911123d 100755 --- a/t/db_dependent/Koha/Plugins/Recall_hooks.t +++ b/t/db_dependent/Koha/Plugins/Recall_hooks.t @@ -53,46 +53,53 @@ subtest 'after_recall_action hook' => sub { $plugins->InstallPlugins; my $plugin = Koha::Plugin::Test->new->enable; + # Avoid testing useless warnings my $test_plugin = Test::MockModule->new('Koha::Plugin::Test'); - $test_plugin->mock( 'after_item_action', undef ); - $test_plugin->mock( 'after_circ_action', undef ); - $test_plugin->mock( 'after_biblio_action', undef ); + $test_plugin->mock( 'after_item_action', undef ); + $test_plugin->mock( 'after_circ_action', undef ); + $test_plugin->mock( 'after_biblio_action', undef ); $test_plugin->mock( 'patron_barcode_transform', undef ); - $test_plugin->mock( 'item_barcode_transform', undef ); + $test_plugin->mock( 'item_barcode_transform', undef ); - my $item = $builder->build_sample_item(); - my $biblio = $item->biblio; - my $branch = $item->holdingbranch; - my $category = $builder->build({ source => 'Category' })->{ categorycode }; - my $patron1 = $builder->build_object({ class => 'Koha::Patrons', value => { categorycode => $category, branchcode => $branch } }); - my $patron2 = $builder->build_object({ class => 'Koha::Patrons', value => { categorycode => $category, branchcode => $branch } }); - t::lib::Mocks::mock_userenv({ patron => $patron1 }); + my $item = $builder->build_sample_item(); + my $biblio = $item->biblio; + my $branch = $item->holdingbranch; + my $category = $builder->build( { source => 'Category' } )->{categorycode}; + my $patron1 = $builder->build_object( + { class => 'Koha::Patrons', value => { categorycode => $category, branchcode => $branch } } ); + my $patron2 = $builder->build_object( + { class => 'Koha::Patrons', value => { categorycode => $category, branchcode => $branch } } ); + t::lib::Mocks::mock_userenv( { patron => $patron1 } ); - Koha::CirculationRules->set_rules({ - branchcode => undef, - categorycode => undef, - itemtype => undef, - rules => { - 'recall_due_date_interval' => undef, - 'recalls_allowed' => 10, + Koha::CirculationRules->set_rules( + { + branchcode => undef, + categorycode => undef, + itemtype => undef, + rules => { + 'recall_due_date_interval' => undef, + 'recalls_allowed' => 10, + } } - }); + ); C4::Circulation::AddIssue( $patron2, $item->barcode ); warnings_exist { - Koha::Recalls->add_recall({ - patron => $patron1, - biblio => $biblio, - branchcode => $branch, - item => undef, - expirationdate => undef, - interface => 'COMMANDLINE', - }); + Koha::Recalls->add_recall( + { + patron => $patron1, + biblio => $biblio, + branchcode => $branch, + item => undef, + expirationdate => undef, + interface => 'COMMANDLINE', + } + ); } qr/after_recall_action called with action: add, ref: Koha::Recall/, - '->add_recall calls the after_recall_action hook with action add'; + '->add_recall calls the after_recall_action hook with action add'; Koha::Plugins->RemovePlugins; $schema->storage->txn_rollback; diff --git a/t/db_dependent/Koha/Plugins/authority_hooks.t b/t/db_dependent/Koha/Plugins/authority_hooks.t index be0b12c491..5682c5a7a6 100755 --- a/t/db_dependent/Koha/Plugins/authority_hooks.t +++ b/t/db_dependent/Koha/Plugins/authority_hooks.t @@ -57,17 +57,17 @@ subtest 'after_authority_action hook' => sub { $record->append_fields( MARC::Field->new( '100', '1', '2', a => 'Name' ) ); my $type = $builder->build( { source => 'AuthType', value => { auth_tag_to_report => '100' } } ); - warnings_exist { ( $id ) = C4::AuthoritiesMarc::AddAuthority( $record, undef, $type->{authtypecode} ); } - qr/after_authority_action called with action: create, id: \d+/, - 'AddAuthority calls the hook with action=create, id passed'; + warnings_exist { ($id) = C4::AuthoritiesMarc::AddAuthority( $record, undef, $type->{authtypecode} ); } + qr/after_authority_action called with action: create, id: \d+/, + 'AddAuthority calls the hook with action=create, id passed'; warnings_exist { C4::AuthoritiesMarc::ModAuthority( $id, $record, $type->{authtypecode}, { skip_merge => 1 } ); } - qr/after_authority_action called with action: modify, id: $id/, - 'ModAuthority calls the hook with action=modify, id passed'; + qr/after_authority_action called with action: modify, id: $id/, + 'ModAuthority calls the hook with action=modify, id passed'; - warnings_exist { C4::AuthoritiesMarc::DelAuthority({ authid => $id, skip_merge => 1 }); } - qr/after_authority_action called with action: delete, id: $id/, - 'DelAuthority calls the hook with action=delete, id passed'; + warnings_exist { C4::AuthoritiesMarc::DelAuthority( { authid => $id, skip_merge => 1 } ); } + qr/after_authority_action called with action: delete, id: $id/, + 'DelAuthority calls the hook with action=delete, id passed'; Koha::Plugins->RemovePlugins; $schema->storage->txn_rollback; diff --git a/t/db_dependent/Koha/Quotes.t b/t/db_dependent/Koha/Quotes.t index 0ecd7d85f7..e324ee409f 100755 --- a/t/db_dependent/Koha/Quotes.t +++ b/t/db_dependent/Koha/Quotes.t @@ -40,37 +40,57 @@ $schema->storage->txn_begin; my $dbh = C4::Context->dbh; # Ids not starting with 1 to reflect possible deletes, this acts as a regression test for bug 11297 -my $yesterday = dt_from_string()->subtract(days => 1); -my $quote_1 = Koha::Quote->new({ source => 'George Washington', text => 'To be prepared for war is one of the most effectual means of preserving peace.' })->store; -my $quote_2 = Koha::Quote->new({ source => 'Thomas Jefferson', text => 'When angry, count ten, before you speak; if very angry, an hundred.' })->store; -my $quote_3 = Koha::Quote->new({ source => 'Abraham Lincoln', text => 'Four score and seven years ago our fathers brought forth on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal' })->store; -my $quote_4 = Koha::Quote->new({ source => 'Abraham Lincoln', text => 'I have always found that mercy bears richer fruits than strict justice.' })->store; -my $quote_5 = Koha::Quote->new({ source => 'Andrew Johnson', text => 'I feel incompetent to perform duties...which have been so unexpectedly thrown upon me.' })->store; +my $yesterday = dt_from_string()->subtract( days => 1 ); +my $quote_1 = Koha::Quote->new( + { + source => 'George Washington', + text => 'To be prepared for war is one of the most effectual means of preserving peace.' + } +)->store; +my $quote_2 = Koha::Quote->new( + { source => 'Thomas Jefferson', text => 'When angry, count ten, before you speak; if very angry, an hundred.' } ) + ->store; +my $quote_3 = Koha::Quote->new( + { + source => 'Abraham Lincoln', + text => + 'Four score and seven years ago our fathers brought forth on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal' + } +)->store; +my $quote_4 = Koha::Quote->new( + { source => 'Abraham Lincoln', text => 'I have always found that mercy bears richer fruits than strict justice.' } ) + ->store; +my $quote_5 = Koha::Quote->new( + { + source => 'Andrew Johnson', + text => 'I feel incompetent to perform duties...which have been so unexpectedly thrown upon me.' + } +)->store; #First test with QuoteOfTheDay disabled -t::lib::Mocks::mock_preference('QuoteOfTheDay', 0); +t::lib::Mocks::mock_preference( 'QuoteOfTheDay', 0 ); ##Set interface and get nothing because syspref is not set. C4::Context->interface('opac'); -$quote = Koha::Quotes->get_daily_quote(id => $quote_1->id); -ok(not($quote), "'QuoteOfTheDay'-syspref not set so nothing returned"); +$quote = Koha::Quotes->get_daily_quote( id => $quote_1->id ); +ok( not($quote), "'QuoteOfTheDay'-syspref not set so nothing returned" ); ##Set 'QuoteOfTheDay'-syspref to not include current interface 'opac' -t::lib::Mocks::mock_preference('QuoteOfTheDay', 'intranet'); -$quote = Koha::Quotes->get_daily_quote(id => $quote_1->id); -ok(not($quote), "'QuoteOfTheDay'-syspref doesn't include 'opac'"); +t::lib::Mocks::mock_preference( 'QuoteOfTheDay', 'intranet' ); +$quote = Koha::Quotes->get_daily_quote( id => $quote_1->id ); +ok( not($quote), "'QuoteOfTheDay'-syspref doesn't include 'opac'" ); ##Set 'QuoteOfTheDay'-syspref to include current interface 'opac' -t::lib::Mocks::mock_preference('QuoteOfTheDay', 'opac,intranet'); +t::lib::Mocks::mock_preference( 'QuoteOfTheDay', 'opac,intranet' ); -$quote = Koha::Quotes->get_daily_quote('id'=>$quote_3->id); -is($quote->id, $quote_3->id, "Correctly got quote by ID"); -is($quote->text, $quote_3->text, "Quote is correct"); -is(t::lib::Dates::compare($quote->timestamp, dt_from_string), 0, "get_daily_quote updated the timestamp/last seen"); +$quote = Koha::Quotes->get_daily_quote( 'id' => $quote_3->id ); +is( $quote->id, $quote_3->id, "Correctly got quote by ID" ); +is( $quote->text, $quote_3->text, "Quote is correct" ); +is( t::lib::Dates::compare( $quote->timestamp, dt_from_string ), 0, "get_daily_quote updated the timestamp/last seen" ); -$quote = Koha::Quotes->get_daily_quote('random'=>1); -ok($quote, "Got a random quote."); -cmp_ok($quote->id, '>', 0, 'Id is greater than 0'); +$quote = Koha::Quotes->get_daily_quote( 'random' => 1 ); +ok( $quote, "Got a random quote." ); +cmp_ok( $quote->id, '>', 0, 'Id is greater than 0' ); subtest 'timestamp column is updated' => sub { plan tests => 3; @@ -80,27 +100,33 @@ subtest 'timestamp column is updated' => sub { my $now = dt_from_string; my $expected_quote = { - id => $quote_3->id, - source => 'Abraham Lincoln', - text => 'Four score and seven years ago our fathers brought forth on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal.', - timestamp => $yesterday, + id => $quote_3->id, + source => 'Abraham Lincoln', + text => + 'Four score and seven years ago our fathers brought forth on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal.', + timestamp => $yesterday, }; - - Koha::Quotes->find( $expected_quote->{'id'} ) - ->update( { timestamp => $now->clone->subtract( seconds => 10 ) } ); ; # To make it the last one - $quote = Koha::Quotes->get_daily_quote(); # this is the "default" mode of selection - is($quote->id, $expected_quote->{'id'}, "Id is correct"); - is($quote->source, $expected_quote->{'source'}, "Source is correct"); - is(t::lib::Dates::compare($quote->timestamp, $now), 0, "get_daily_quote updated the timestamp/last seen"); + Koha::Quotes->find( $expected_quote->{'id'} )->update( { timestamp => $now->clone->subtract( seconds => 10 ) } ); + ; # To make it the last one + $quote = Koha::Quotes->get_daily_quote(); # this is the "default" mode of selection + is( $quote->id, $expected_quote->{'id'}, "Id is correct" ); + is( $quote->source, $expected_quote->{'source'}, "Source is correct" ); + is( t::lib::Dates::compare( $quote->timestamp, $now ), 0, "get_daily_quote updated the timestamp/last seen" ); }; Koha::Quotes->search()->delete(); -$quote = eval {Koha::Quotes->get_daily_quote();}; +$quote = eval { Koha::Quotes->get_daily_quote(); }; is( $@, '', 'get_daily_quote does not die if no quote exist' ); -is_deeply( $quote, undef, 'return undef if quotes do not exists'); # Is it what we expect? +is_deeply( $quote, undef, 'return undef if quotes do not exists' ); # Is it what we expect? -my $quote_6 = Koha::Quote->new({ source => 'George Washington', text => 'To be prepared for war is one of the most effectual means of preserving peace.', timestamp => dt_from_string() })->store; +my $quote_6 = Koha::Quote->new( + { + source => 'George Washington', + text => 'To be prepared for war is one of the most effectual means of preserving peace.', + timestamp => dt_from_string() + } +)->store; $quote = Koha::Quotes->get_daily_quote(); is( $quote->id, $quote_6->id, ' get_daily_quote returns the only existing quote' ); diff --git a/t/db_dependent/Koha/REST/Plugin/Auth/IdP.t b/t/db_dependent/Koha/REST/Plugin/Auth/IdP.t index 48325367ad..1c86bc65a4 100755 --- a/t/db_dependent/Koha/REST/Plugin/Auth/IdP.t +++ b/t/db_dependent/Koha/REST/Plugin/Auth/IdP.t @@ -35,7 +35,8 @@ post '/register_user' => sub { try { my $domain = Koha::Auth::Identity::Provider::Domains->find( $params->{domain_id} ); my $patron = $c->auth->register( - { data => $params->{data}, + { + data => $params->{data}, domain => $domain, interface => $params->{interface} } @@ -56,7 +57,7 @@ post '/start_session' => sub { try { my $patron = Koha::Patrons->search( { userid => $userid } ); - my ( $status, $cookie, $session_id ) = $c->auth->session({ patron => $patron->next, interface => 'opac' }); + my ( $status, $cookie, $session_id ) = $c->auth->session( { patron => $patron->next, interface => 'opac' } ); $c->render( status => 200, json => { status => $status } ); } catch { if ( ref($_) eq 'Koha::Exceptions::Auth::CannotCreateSession' ) { @@ -87,27 +88,31 @@ subtest 'auth.register helper' => sub { $schema->storage->txn_begin; # generate a random patron - my $patron_to_delete = $builder->build_object({ class => 'Koha::Patrons' }); - my $userid = $patron_to_delete->userid; + my $patron_to_delete = $builder->build_object( { class => 'Koha::Patrons' } ); + my $userid = $patron_to_delete->userid; + # delete patron $patron_to_delete->delete; - my $provider = $builder->build_object( { class => 'Koha::Auth::Identity::Providers', value => { matchpoint => 'email' } } ); + my $provider = + $builder->build_object( { class => 'Koha::Auth::Identity::Providers', value => { matchpoint => 'email' } } ); my $domain_with_register = $builder->build_object( - { class => 'Koha::Auth::Identity::Provider::Domains', + { + class => 'Koha::Auth::Identity::Provider::Domains', value => { identity_provider_id => $provider->id, domain => 'domain1.com', auto_register => 1 } } ); my $domain_without_register = $builder->build_object( - { class => 'Koha::Auth::Identity::Provider::Domains', + { + class => 'Koha::Auth::Identity::Provider::Domains', value => { identity_provider_id => $provider->id, domain => 'domain2.com', auto_register => 0 } } ); - my $library = $builder->build_object( { class => 'Koha::Libraries' } ); - my $category = $builder->build_object( { class => 'Koha::Patron::Categories' } ); + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); + my $category = $builder->build_object( { class => 'Koha::Patron::Categories' } ); my $user_data = { firstname => 'test', @@ -119,11 +124,17 @@ subtest 'auth.register helper' => sub { my $t = Test::Mojo->new; - $t->post_ok( '/register_user' => json => { data => $user_data, domain_id => $domain_with_register->identity_provider_domain_id, interface => 'opac' } )->status_is(200) - ->json_has( '/firstname', 'test' ); + $t->post_ok( + '/register_user' => json => { + data => $user_data, domain_id => $domain_with_register->identity_provider_domain_id, interface => 'opac' + } + )->status_is(200)->json_has( '/firstname', 'test' ); - $t->post_ok( '/register_user' => json => { data => $user_data, domain_id => $domain_without_register->identity_provider_domain_id, interface => 'opac' } )->status_is(401) - ->json_has( '/message', 'unauthorized' ); + $t->post_ok( + '/register_user' => json => { + data => $user_data, domain_id => $domain_without_register->identity_provider_domain_id, interface => 'opac' + } + )->status_is(401)->json_has( '/message', 'unauthorized' ); $schema->storage->txn_rollback; }; @@ -136,7 +147,8 @@ subtest 'auth.session helper' => sub { my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $t = Test::Mojo->new; - $t->post_ok( '/start_session' => json => { userid => $patron->userid } )->status_is(200)->json_has( '/status', 'ok' ); + $t->post_ok( '/start_session' => json => { userid => $patron->userid } )->status_is(200) + ->json_has( '/status', 'ok' ); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/Koha/REST/Plugin/Objects.t b/t/db_dependent/Koha/REST/Plugin/Objects.t index 25a2bce9af..3efbc1f7a4 100755 --- a/t/db_dependent/Koha/REST/Plugin/Objects.t +++ b/t/db_dependent/Koha/REST/Plugin/Objects.t @@ -38,9 +38,9 @@ plugin 'Koha::REST::Plugin::Pagination'; get '/cities' => sub { my $c = shift; - $c->validation->output($c->req->params->to_hash); + $c->validation->output( $c->req->params->to_hash ); $c->stash_embed( { spec => { parameters => [ { name => 'x-koha-embed', items => { enum => ['+strings'] } } ] } } ); - my $cities = $c->objects->search(Koha::Cities->new); + my $cities = $c->objects->search( Koha::Cities->new ); $c->render( status => 200, json => $cities ); }; @@ -54,45 +54,39 @@ get '/cities/rs' => sub { }; get '/cities/:city_id' => sub { - my $c = shift; + my $c = shift; my $id = $c->stash("city_id"); $c->stash_embed( { spec => { parameters => [ { name => 'x-koha-embed', items => { enum => ['+strings'] } } ] } } ); - my $city = $c->objects->find(Koha::Cities->new, $id); + my $city = $c->objects->find( Koha::Cities->new, $id ); $c->render( status => 200, json => $city ); }; get '/orders' => sub { my $c = shift; - $c->stash('koha.embed', ( { fund => {} } ) ); - $c->validation->output($c->req->params->to_hash); - my $orders = $c->objects->search(Koha::Acquisition::Orders->new); + $c->stash( 'koha.embed', ( { fund => {} } ) ); + $c->validation->output( $c->req->params->to_hash ); + my $orders = $c->objects->search( Koha::Acquisition::Orders->new ); $c->render( status => 200, json => $orders ); }; get '/orders/:order_id' => sub { my $c = shift; - $c->stash('koha.embed', ( { fund => {} } ) ); - my $id = $c->stash("order_id"); - my $order = $c->objects->find(Koha::Acquisition::Orders->new, $id); + $c->stash( 'koha.embed', ( { fund => {} } ) ); + my $id = $c->stash("order_id"); + my $order = $c->objects->find( Koha::Acquisition::Orders->new, $id ); $c->render( status => 200, json => $order ); }; get '/biblios' => sub { - my $c = shift; + my $c = shift; my $output = $c->req->params->to_hash; $output->{query} = $c->req->json if defined $c->req->json; my $headers = $c->req->headers->to_hash; $c->validation->output($output); my $biblios_set = Koha::Biblios->new; - $c->stash("koha.embed", { - "suggestions" => { - children => { - "suggester" => {} - } - } - }); + $c->stash( "koha.embed", { "suggestions" => { children => { "suggester" => {} } } } ); my $biblios = $c->objects->search($biblios_set); - $c->render( status => 200, json => {count => scalar(@$biblios), biblios => $biblios} ); + $c->render( status => 200, json => { count => scalar(@$biblios), biblios => $biblios } ); }; get '/libraries/:library_id_1/:library_id_2' => sub { @@ -109,7 +103,7 @@ get '/libraries/:library_id_1/:library_id_2' => sub { { branchcode => [ $library_id_1, $library_id_2 ] }, { order_by => 'branchname' } ); - my $libraries = $c->objects->search( $libraries_rs ); + my $libraries = $c->objects->search($libraries_rs); $c->render( status => 200, @@ -121,7 +115,7 @@ get '/my_patrons' => sub { my $c = shift; - my $patrons = $c->objects->search( scalar Koha::Patrons->search( {}, { order_by => 'borrowernumber' }) ); + my $patrons = $c->objects->search( scalar Koha::Patrons->search( {}, { order_by => 'borrowernumber' } ) ); $c->render( status => 200, @@ -161,107 +155,78 @@ subtest 'objects.search helper' => sub { # Create three sample cities that match the query. This makes sure we # always have a "next" link regardless of Mojolicious::Plugin::OpenAPI version. - $builder->build_object({ - class => 'Koha::Cities', - value => { - city_name => 'Manuel' + $builder->build_object( + { + class => 'Koha::Cities', + value => { city_name => 'Manuel' } } - }); - $builder->build_object({ - class => 'Koha::Cities', - value => { - city_name => 'Manuela' + ); + $builder->build_object( + { + class => 'Koha::Cities', + value => { city_name => 'Manuela' } } - }); - $builder->build_object({ - class => 'Koha::Cities', - value => { - city_name => 'Manuelab' + ); + $builder->build_object( + { + class => 'Koha::Cities', + value => { city_name => 'Manuelab' } } - }); + ); my $t = Test::Mojo->new; - $t->get_ok('/cities?name=manuel&_per_page=1&_page=1') - ->status_is(200) - ->header_like( 'Link' => qr/<http:\/\/.*[\?&]_page=2.*>; rel="next",/ ) - ->json_has('/0') - ->json_hasnt('/1') - ->json_is('/0/name' => 'Manuel'); + $t->get_ok('/cities?name=manuel&_per_page=1&_page=1')->status_is(200) + ->header_like( 'Link' => qr/<http:\/\/.*[\?&]_page=2.*>; rel="next",/ )->json_has('/0')->json_hasnt('/1') + ->json_is( '/0/name' => 'Manuel' ); - $builder->build_object({ - class => 'Koha::Cities', - value => { - city_name => 'Emanuel' + $builder->build_object( + { + class => 'Koha::Cities', + value => { city_name => 'Emanuel' } } - }); + ); # _match=starts_with - $t->get_ok('/cities?name=manuel&_per_page=4&_page=1&_match=starts_with') - ->status_is(200) - ->json_has('/0') - ->json_has('/1') - ->json_has('/2') - ->json_hasnt('/3') - ->json_is('/0/name' => 'Manuel') - ->json_is('/1/name' => 'Manuela') - ->json_is('/2/name' => 'Manuelab'); + $t->get_ok('/cities?name=manuel&_per_page=4&_page=1&_match=starts_with')->status_is(200)->json_has('/0') + ->json_has('/1')->json_has('/2')->json_hasnt('/3')->json_is( '/0/name' => 'Manuel' ) + ->json_is( '/1/name' => 'Manuela' )->json_is( '/2/name' => 'Manuelab' ); # _match=ends_with - $t->get_ok('/cities?name=manuel&_per_page=4&_page=1&_match=ends_with') - ->status_is(200) - ->json_has('/0') - ->json_has('/1') - ->json_hasnt('/2') - ->json_is('/0/name' => 'Manuel') - ->json_is('/1/name' => 'Emanuel'); + $t->get_ok('/cities?name=manuel&_per_page=4&_page=1&_match=ends_with')->status_is(200)->json_has('/0') + ->json_has('/1')->json_hasnt('/2')->json_is( '/0/name' => 'Manuel' )->json_is( '/1/name' => 'Emanuel' ); # _match=exact - $t->get_ok('/cities?name=manuel&_per_page=4&_page=1&_match=exact') - ->status_is(200) - ->json_has('/0') - ->json_hasnt('/1') - ->json_is('/0/name' => 'Manuel'); + $t->get_ok('/cities?name=manuel&_per_page=4&_page=1&_match=exact')->status_is(200)->json_has('/0') + ->json_hasnt('/1')->json_is( '/0/name' => 'Manuel' ); # _match=contains - $t->get_ok('/cities?name=manuel&_per_page=4&_page=1&_match=contains') - ->status_is(200) - ->json_has('/0') - ->json_has('/1') - ->json_has('/2') - ->json_has('/3') - ->json_hasnt('/4') - ->json_is('/0/name' => 'Manuel') - ->json_is('/1/name' => 'Manuela') - ->json_is('/2/name' => 'Manuelab') - ->json_is('/3/name' => 'Emanuel'); + $t->get_ok('/cities?name=manuel&_per_page=4&_page=1&_match=contains')->status_is(200)->json_has('/0') + ->json_has('/1')->json_has('/2')->json_has('/3')->json_hasnt('/4')->json_is( '/0/name' => 'Manuel' ) + ->json_is( '/1/name' => 'Manuela' )->json_is( '/2/name' => 'Manuelab' )->json_is( '/3/name' => 'Emanuel' ); # Add 20 more cities - for ( 1..20 ) { - $builder->build_object({ class => 'Koha::Cities' }); + for ( 1 .. 20 ) { + $builder->build_object( { class => 'Koha::Cities' } ); } - t::lib::Mocks::mock_preference('RESTdefaultPageSize', 20 ); - $t->get_ok('/cities') - ->status_is(200); + t::lib::Mocks::mock_preference( 'RESTdefaultPageSize', 20 ); + $t->get_ok('/cities')->status_is(200); my $response_count = scalar @{ $t->tx->res->json }; is( $response_count, 20, 'RESTdefaultPageSize is honoured by default (20)' ); - t::lib::Mocks::mock_preference('RESTdefaultPageSize', 5 ); - $t->get_ok('/cities') - ->status_is(200); + t::lib::Mocks::mock_preference( 'RESTdefaultPageSize', 5 ); + $t->get_ok('/cities')->status_is(200); $response_count = scalar @{ $t->tx->res->json }; is( $response_count, 5, 'RESTdefaultPageSize is honoured by default (5)' ); - $t->get_ok('/cities?_page=1&_per_page=-1') - ->status_is(200); + $t->get_ok('/cities?_page=1&_per_page=-1')->status_is(200); $response_count = scalar @{ $t->tx->res->json }; is( $response_count, 24, '_per_page=-1 means all resources' ); - $t->get_ok('/cities?_page=100&_per_page=-1') - ->status_is(200); + $t->get_ok('/cities?_page=100&_per_page=-1')->status_is(200); $response_count = scalar @{ $t->tx->res->json }; is( $response_count, 24, 'When _per_page=-1 the page param is not considered' ); @@ -278,61 +243,34 @@ subtest 'objects.search helper, sorting on mapped column' => sub { # Have complete control over the existing cities to ease testing Koha::Cities->delete; - $builder->build_object({ class => 'Koha::Cities', value => { city_name => 'A', city_country => 'Argentina' } }); - $builder->build_object({ class => 'Koha::Cities', value => { city_name => 'B', city_country => 'Argentina' } }); - $builder->build_object({ class => 'Koha::Cities', value => { city_name => 'C', city_country => 'Argentina' } }); - $builder->build_object({ class => 'Koha::Cities', value => { city_name => 'C', city_country => 'Belarus' } }); + $builder->build_object( { class => 'Koha::Cities', value => { city_name => 'A', city_country => 'Argentina' } } ); + $builder->build_object( { class => 'Koha::Cities', value => { city_name => 'B', city_country => 'Argentina' } } ); + $builder->build_object( { class => 'Koha::Cities', value => { city_name => 'C', city_country => 'Argentina' } } ); + $builder->build_object( { class => 'Koha::Cities', value => { city_name => 'C', city_country => 'Belarus' } } ); my $t = Test::Mojo->new; + # CSV-param - $t->get_ok('/cities?_order_by=%2Bname,-country') - ->status_is(200) - ->json_has('/0') - ->json_has('/1') - ->json_is('/0/name' => 'A') - ->json_is('/1/name' => 'B') - ->json_is('/2/name' => 'C') - ->json_is('/2/country' => 'Belarus') - ->json_is('/3/name' => 'C') - ->json_is('/3/country' => 'Argentina') - ->json_hasnt('/4'); + $t->get_ok('/cities?_order_by=%2Bname,-country')->status_is(200)->json_has('/0')->json_has('/1') + ->json_is( '/0/name' => 'A' )->json_is( '/1/name' => 'B' )->json_is( '/2/name' => 'C' ) + ->json_is( '/2/country' => 'Belarus' )->json_is( '/3/name' => 'C' )->json_is( '/3/country' => 'Argentina' ) + ->json_hasnt('/4'); # Multi-param: traditional - $t->get_ok('/cities?_order_by=%2Bname&_order_by=-country') - ->status_is(200) - ->json_has('/0') - ->json_has('/1') - ->json_is('/0/name' => 'A') - ->json_is('/1/name' => 'B') - ->json_is('/2/name' => 'C') - ->json_is('/2/country' => 'Belarus') - ->json_is('/3/name' => 'C') - ->json_is('/3/country' => 'Argentina') - ->json_hasnt('/4'); + $t->get_ok('/cities?_order_by=%2Bname&_order_by=-country')->status_is(200)->json_has('/0')->json_has('/1') + ->json_is( '/0/name' => 'A' )->json_is( '/1/name' => 'B' )->json_is( '/2/name' => 'C' ) + ->json_is( '/2/country' => 'Belarus' )->json_is( '/3/name' => 'C' )->json_is( '/3/country' => 'Argentina' ) + ->json_hasnt('/4'); # Multi-param: PHP Style, Passes validation as above, subsequntly explodes - $t->get_ok('/cities?_order_by[]=%2Bname&_order_by[]=-country') - ->status_is(200) - ->json_has('/0') - ->json_has('/1') - ->json_is('/0/name' => 'A') - ->json_is('/1/name' => 'B') - ->json_is('/2/name' => 'C') - ->json_is('/2/country' => 'Belarus') - ->json_is('/3/name' => 'C') - ->json_is('/3/country' => 'Argentina') - ->json_hasnt('/4'); + $t->get_ok('/cities?_order_by[]=%2Bname&_order_by[]=-country')->status_is(200)->json_has('/0')->json_has('/1') + ->json_is( '/0/name' => 'A' )->json_is( '/1/name' => 'B' )->json_is( '/2/name' => 'C' ) + ->json_is( '/2/country' => 'Belarus' )->json_is( '/3/name' => 'C' )->json_is( '/3/country' => 'Argentina' ) + ->json_hasnt('/4'); # Single-param - $t->get_ok('/cities?_order_by=-name') - ->status_is(200) - ->json_has('/0') - ->json_has('/1') - ->json_is('/0/name' => 'C') - ->json_is('/1/name' => 'C') - ->json_is('/2/name' => 'B') - ->json_is('/3/name' => 'A') - ->json_hasnt('/4'); + $t->get_ok('/cities?_order_by=-name')->status_is(200)->json_has('/0')->json_has('/1')->json_is( '/0/name' => 'C' ) + ->json_is( '/1/name' => 'C' )->json_is( '/2/name' => 'B' )->json_is( '/3/name' => 'A' )->json_hasnt('/4'); $schema->storage->txn_rollback; }; @@ -345,15 +283,12 @@ subtest 'objects.search helper, encoding' => sub { Koha::Cities->delete; - $builder->build_object({ class => 'Koha::Cities', value => { city_name => 'A', city_country => 'Argentina' } }); - $builder->build_object({ class => 'Koha::Cities', value => { city_name => 'B', city_country => '❤Argentina❤' } }); + $builder->build_object( { class => 'Koha::Cities', value => { city_name => 'A', city_country => 'Argentina' } } ); + $builder->build_object( { class => 'Koha::Cities', value => { city_name => 'B', city_country => '❤Argentina❤' } } ); my $t = Test::Mojo->new; - $t->get_ok('/cities?q={"country": "❤Argentina❤"}') - ->status_is(200) - ->json_has('/0') - ->json_hasnt('/1') - ->json_is('/0/name' => 'B'); + $t->get_ok('/cities?q={"country": "❤Argentina❤"}')->status_is(200)->json_has('/0')->json_hasnt('/1') + ->json_is( '/0/name' => 'B' ); $schema->storage->txn_rollback; }; @@ -380,15 +315,13 @@ subtest 'objects.search helper, X-Total-Count and X-Base-Total-Count' => sub { } my $t = Test::Mojo->new; - $t->get_ok('/cities?name=L&_per_page=10&_page=1&_match=starts_with') - ->status_is(200) - ->header_is( 'X-Total-Count' => 20, 'X-Total-Count header present' ) - ->header_is( 'X-Base-Total-Count' => 20, 'X-Base-Total-Count header present' ); + $t->get_ok('/cities?name=L&_per_page=10&_page=1&_match=starts_with')->status_is(200) + ->header_is( 'X-Total-Count' => 20, 'X-Total-Count header present' ) + ->header_is( 'X-Base-Total-Count' => 20, 'X-Base-Total-Count header present' ); - $t->get_ok('/cities?name=Llan&_per_page=10&_page=1&_match=starts_with') - ->status_is(200) - ->header_is( 'X-Total-Count' => 17, 'X-Total-Count header present' ) - ->header_is('X-Base-Total-Count' => 20, 'X-Base-Total-Count header present' ); + $t->get_ok('/cities?name=Llan&_per_page=10&_page=1&_match=starts_with')->status_is(200) + ->header_is( 'X-Total-Count' => 17, 'X-Total-Count header present' ) + ->header_is( 'X-Base-Total-Count' => 20, 'X-Base-Total-Count header present' ); $schema->storage->txn_rollback; }; @@ -399,11 +332,11 @@ subtest 'objects.search helper, embed' => sub { $schema->storage->txn_begin; - my $order = $builder->build_object({ class => 'Koha::Acquisition::Orders' }); + my $order = $builder->build_object( { class => 'Koha::Acquisition::Orders' } ); my $t = Test::Mojo->new; - $t->get_ok('/orders?order_id=' . $order->ordernumber) - ->json_is('/0',$order->to_api({ embed => ( { fund => {} } ) })); + $t->get_ok( '/orders?order_id=' . $order->ordernumber ) + ->json_is( '/0', $order->to_api( { embed => ( { fund => {} } ) } ) ); $schema->storage->txn_rollback; }; @@ -413,31 +346,48 @@ subtest 'objects.search helper with query parameter' => sub { $schema->storage->txn_begin; - my $patron1 = $builder->build_object( { class => "Koha::Patrons" } ); - my $patron2 = $builder->build_object( { class => "Koha::Patrons" } ); - my $biblio1 = $builder->build_sample_biblio; - my $biblio2 = $builder->build_sample_biblio; - my $biblio3 = $builder->build_sample_biblio; - my $suggestion1 = $builder->build_object( { class => "Koha::Suggestions", value => { suggestedby => $patron1->borrowernumber, biblionumber => $biblio1->biblionumber} } ); - my $suggestion2 = $builder->build_object( { class => "Koha::Suggestions", value => { suggestedby => $patron2->borrowernumber, biblionumber => $biblio2->biblionumber} } ); - my $suggestion3 = $builder->build_object( { class => "Koha::Suggestions", value => { suggestedby => $patron2->borrowernumber, biblionumber => $biblio3->biblionumber} } ); + my $patron1 = $builder->build_object( { class => "Koha::Patrons" } ); + my $patron2 = $builder->build_object( { class => "Koha::Patrons" } ); + my $biblio1 = $builder->build_sample_biblio; + my $biblio2 = $builder->build_sample_biblio; + my $biblio3 = $builder->build_sample_biblio; + my $suggestion1 = $builder->build_object( + { + class => "Koha::Suggestions", + value => { suggestedby => $patron1->borrowernumber, biblionumber => $biblio1->biblionumber } + } + ); + my $suggestion2 = $builder->build_object( + { + class => "Koha::Suggestions", + value => { suggestedby => $patron2->borrowernumber, biblionumber => $biblio2->biblionumber } + } + ); + my $suggestion3 = $builder->build_object( + { + class => "Koha::Suggestions", + value => { suggestedby => $patron2->borrowernumber, biblionumber => $biblio3->biblionumber } + } + ); my $t = Test::Mojo->new; # Set valid koha.user in stash for to_api my $superlibrarian = - $builder->build_object( { class => 'Koha::Patrons', value => { flags => 1 } } ); - $t->app->hook(before_dispatch => sub { - my $c = shift; - $c->stash('koha.user' => $superlibrarian); - }); - t::lib::Mocks::mock_userenv({ patron => $superlibrarian }); + $builder->build_object( { class => 'Koha::Patrons', value => { flags => 1 } } ); + $t->app->hook( + before_dispatch => sub { + my $c = shift; + $c->stash( 'koha.user' => $superlibrarian ); + } + ); + t::lib::Mocks::mock_userenv( { patron => $superlibrarian } ); - $t->get_ok('/biblios' => json => {"suggestions.suggester.patron_id" => $patron1->borrowernumber }) - ->json_is('/count' => 1, 'there should be 1 biblio with suggestions of patron 1'); + $t->get_ok( '/biblios' => json => { "suggestions.suggester.patron_id" => $patron1->borrowernumber } ) + ->json_is( '/count' => 1, 'there should be 1 biblio with suggestions of patron 1' ); - $t->get_ok('/biblios' => json => {"suggestions.suggester.patron_id" => $patron2->borrowernumber }) - ->json_is('/count' => 2, 'there should be 2 biblios with suggestions of patron 2'); + $t->get_ok( '/biblios' => json => { "suggestions.suggester.patron_id" => $patron2->borrowernumber } ) + ->json_is( '/count' => 2, 'there should be 2 biblios with suggestions of patron 2' ); $schema->storage->txn_rollback; }; @@ -447,21 +397,36 @@ subtest 'objects.search helper with q parameter' => sub { $schema->storage->txn_begin; - my $patron1 = $builder->build_object( { class => "Koha::Patrons" } ); - my $patron2 = $builder->build_object( { class => "Koha::Patrons" } ); - my $biblio1 = $builder->build_sample_biblio; - my $biblio2 = $builder->build_sample_biblio; - my $biblio3 = $builder->build_sample_biblio; - my $suggestion1 = $builder->build_object( { class => "Koha::Suggestions", value => { suggestedby => $patron1->borrowernumber, biblionumber => $biblio1->biblionumber} } ); - my $suggestion2 = $builder->build_object( { class => "Koha::Suggestions", value => { suggestedby => $patron2->borrowernumber, biblionumber => $biblio2->biblionumber} } ); - my $suggestion3 = $builder->build_object( { class => "Koha::Suggestions", value => { suggestedby => $patron2->borrowernumber, biblionumber => $biblio3->biblionumber} } ); + my $patron1 = $builder->build_object( { class => "Koha::Patrons" } ); + my $patron2 = $builder->build_object( { class => "Koha::Patrons" } ); + my $biblio1 = $builder->build_sample_biblio; + my $biblio2 = $builder->build_sample_biblio; + my $biblio3 = $builder->build_sample_biblio; + my $suggestion1 = $builder->build_object( + { + class => "Koha::Suggestions", + value => { suggestedby => $patron1->borrowernumber, biblionumber => $biblio1->biblionumber } + } + ); + my $suggestion2 = $builder->build_object( + { + class => "Koha::Suggestions", + value => { suggestedby => $patron2->borrowernumber, biblionumber => $biblio2->biblionumber } + } + ); + my $suggestion3 = $builder->build_object( + { + class => "Koha::Suggestions", + value => { suggestedby => $patron2->borrowernumber, biblionumber => $biblio3->biblionumber } + } + ); my $t = Test::Mojo->new; - $t->get_ok('/biblios?q={"suggestions.suggester.patron_id": "'.$patron1->borrowernumber.'"}') - ->json_is('/count' => 1, 'there should be 1 biblio with suggestions of patron 1'); + $t->get_ok( '/biblios?q={"suggestions.suggester.patron_id": "' . $patron1->borrowernumber . '"}' ) + ->json_is( '/count' => 1, 'there should be 1 biblio with suggestions of patron 1' ); - $t->get_ok('/biblios?q={"suggestions.suggester.patron_id": "'.$patron2->borrowernumber.'"}') - ->json_is('/count' => 2, 'there should be 2 biblios with suggestions of patron 2'); + $t->get_ok( '/biblios?q={"suggestions.suggester.patron_id": "' . $patron2->borrowernumber . '"}' ) + ->json_is( '/count' => 2, 'there should be 2 biblios with suggestions of patron 2' ); $schema->storage->txn_rollback; }; @@ -471,16 +436,31 @@ subtest 'objects.search helper with all query methods' => sub { $schema->storage->txn_begin; - my $patron1 = $builder->build_object( { class => "Koha::Patrons" , value => {firstname=>'patron1'} } ); - my $patron2 = $builder->build_object( { class => "Koha::Patrons" , value => {firstname=>'patron2'} } ); - my $biblio1 = $builder->build_sample_biblio; - my $biblio2 = $builder->build_sample_biblio; - my $biblio3 = $builder->build_sample_biblio; - my $suggestion1 = $builder->build_object( { class => "Koha::Suggestions", value => { suggestedby => $patron1->borrowernumber, biblionumber => $biblio1->biblionumber} } ); - my $suggestion2 = $builder->build_object( { class => "Koha::Suggestions", value => { suggestedby => $patron2->borrowernumber, biblionumber => $biblio2->biblionumber} } ); - my $suggestion3 = $builder->build_object( { class => "Koha::Suggestions", value => { suggestedby => $patron2->borrowernumber, biblionumber => $biblio3->biblionumber} } ); + my $patron1 = $builder->build_object( { class => "Koha::Patrons", value => { firstname => 'patron1' } } ); + my $patron2 = $builder->build_object( { class => "Koha::Patrons", value => { firstname => 'patron2' } } ); + my $biblio1 = $builder->build_sample_biblio; + my $biblio2 = $builder->build_sample_biblio; + my $biblio3 = $builder->build_sample_biblio; + my $suggestion1 = $builder->build_object( + { + class => "Koha::Suggestions", + value => { suggestedby => $patron1->borrowernumber, biblionumber => $biblio1->biblionumber } + } + ); + my $suggestion2 = $builder->build_object( + { + class => "Koha::Suggestions", + value => { suggestedby => $patron2->borrowernumber, biblionumber => $biblio2->biblionumber } + } + ); + my $suggestion3 = $builder->build_object( + { + class => "Koha::Suggestions", + value => { suggestedby => $patron2->borrowernumber, biblionumber => $biblio3->biblionumber } + } + ); - my $t = Test::Mojo->new; + my $t = Test::Mojo->new; my $query = { "suggestions.suggester.firstname" => $patron1->firstname, "suggestions.suggester.patron_id" => $patron1->id, @@ -513,17 +493,28 @@ subtest 'objects.search helper order by embedded columns' => sub { $schema->storage->txn_begin; - my $patron1 = $builder->build_object( { class => "Koha::Patrons" , value => {firstname=>'patron1'} } ); - my $patron2 = $builder->build_object( { class => "Koha::Patrons" , value => {firstname=>'patron2'} } ); - my $biblio1 = $builder->build_sample_biblio; - my $biblio2 = $builder->build_sample_biblio; - my $suggestion1 = $builder->build_object( { class => "Koha::Suggestions", value => { suggestedby => $patron1->borrowernumber, biblionumber => $biblio1->biblionumber} } ); - my $suggestion2 = $builder->build_object( { class => "Koha::Suggestions", value => { suggestedby => $patron2->borrowernumber, biblionumber => $biblio2->biblionumber} } ); + my $patron1 = $builder->build_object( { class => "Koha::Patrons", value => { firstname => 'patron1' } } ); + my $patron2 = $builder->build_object( { class => "Koha::Patrons", value => { firstname => 'patron2' } } ); + my $biblio1 = $builder->build_sample_biblio; + my $biblio2 = $builder->build_sample_biblio; + my $suggestion1 = $builder->build_object( + { + class => "Koha::Suggestions", + value => { suggestedby => $patron1->borrowernumber, biblionumber => $biblio1->biblionumber } + } + ); + my $suggestion2 = $builder->build_object( + { + class => "Koha::Suggestions", + value => { suggestedby => $patron2->borrowernumber, biblionumber => $biblio2->biblionumber } + } + ); my $t = Test::Mojo->new; - $t->get_ok('/biblios?_order_by=-suggestions.suggester.firstname' => json => [{"me.biblio_id" => $biblio1->biblionumber}, {"me.biblio_id" => $biblio2->biblionumber}]) - ->json_is('/biblios/0/biblio_id' => $biblio2->biblionumber, 'Biblio 2 should be first') - ->json_is('/biblios/1/biblio_id' => $biblio1->biblionumber, 'Biblio 1 should be second'); + $t->get_ok( '/biblios?_order_by=-suggestions.suggester.firstname' => json => + [ { "me.biblio_id" => $biblio1->biblionumber }, { "me.biblio_id" => $biblio2->biblionumber } ] ) + ->json_is( '/biblios/0/biblio_id' => $biblio2->biblionumber, 'Biblio 2 should be first' ) + ->json_is( '/biblios/1/biblio_id' => $biblio1->biblionumber, 'Biblio 1 should be second' ); $schema->storage->txn_rollback; }; @@ -536,30 +527,24 @@ subtest 'objects.search_rs helper' => sub { # Remove existing cities to have more control on the search results Koha::Cities->delete; - # Create three sample cities that match the query. This makes sure we - # always have a "next" link regardless of Mojolicious::Plugin::OpenAPI version. + # Create three sample cities that match the query. This makes sure we + # always have a "next" link regardless of Mojolicious::Plugin::OpenAPI version. $builder->build_object( { class => 'Koha::Cities', - value => { - city_name => 'city1' - } + value => { city_name => 'city1' } } ); $builder->build_object( { class => 'Koha::Cities', - value => { - city_name => 'city2' - } + value => { city_name => 'city2' } } ); $builder->build_object( { class => 'Koha::Cities', - value => { - city_name => 'city3' - } + value => { city_name => 'city3' } } ); @@ -580,20 +565,14 @@ subtest 'objects.find helper' => sub { my $city_1 = $builder->build_object( { class => 'Koha::Cities' } ); my $city_2 = $builder->build_object( { class => 'Koha::Cities' } ); - $t->get_ok( '/cities/' . $city_1->id ) - ->status_is(200) - ->json_is( $city_1->to_api ); + $t->get_ok( '/cities/' . $city_1->id )->status_is(200)->json_is( $city_1->to_api ); - $t->get_ok( '/cities/' . $city_2->id ) - ->status_is(200) - ->json_is( $city_2->to_api ); + $t->get_ok( '/cities/' . $city_2->id )->status_is(200)->json_is( $city_2->to_api ); # Remove the city my $city_2_id = $city_2->id; $city_2->delete; - $t->get_ok( '/cities/' . $city_2_id ) - ->status_is(200) - ->json_is( undef ); + $t->get_ok( '/cities/' . $city_2_id )->status_is(200)->json_is(undef); $schema->storage->txn_rollback; }; @@ -606,10 +585,9 @@ subtest 'objects.find helper, embed' => sub { $schema->storage->txn_begin; - my $order = $builder->build_object({ class => 'Koha::Acquisition::Orders' }); + my $order = $builder->build_object( { class => 'Koha::Acquisition::Orders' } ); - $t->get_ok( '/orders/' . $order->ordernumber ) - ->json_is( $order->to_api( { embed => ( { fund => {} } ) } ) ); + $t->get_ok( '/orders/' . $order->ordernumber )->json_is( $order->to_api( { embed => ( { fund => {} } ) } ) ); $schema->storage->txn_rollback; }; @@ -620,14 +598,14 @@ subtest 'objects.search helper, public requests' => sub { $schema->storage->txn_begin; - my $library_1 = $builder->build_object({ class => 'Koha::Libraries', value => { branchname => 'A' } }); - my $library_2 = $builder->build_object({ class => 'Koha::Libraries', value => { branchname => 'B' } }); + my $library_1 = $builder->build_object( { class => 'Koha::Libraries', value => { branchname => 'A' } } ); + my $library_2 = $builder->build_object( { class => 'Koha::Libraries', value => { branchname => 'B' } } ); my $t = Test::Mojo->new; - $t->get_ok( '/libraries/'.$library_1->id.'/'.$library_2->id ) - ->json_is('/0' => $library_1->to_api({ public => 1 }), 'Public representation of $library_1 is retrieved') - ->json_is('/1' => $library_2->to_api({ public => 1 }), 'Public representation of $library_2 is retrieved'); + $t->get_ok( '/libraries/' . $library_1->id . '/' . $library_2->id ) + ->json_is( '/0' => $library_1->to_api( { public => 1 } ), 'Public representation of $library_1 is retrieved' ) + ->json_is( '/1' => $library_2->to_api( { public => 1 } ), 'Public representation of $library_2 is retrieved' ); $schema->storage->txn_rollback; }; @@ -638,20 +616,21 @@ subtest 'objects.search helper, search_limited() tests' => sub { $schema->storage->txn_begin; - my $library_1 = $builder->build_object({ class => 'Koha::Libraries' }); - my $library_2 = $builder->build_object({ class => 'Koha::Libraries' }); + my $library_1 = $builder->build_object( { class => 'Koha::Libraries' } ); + my $library_2 = $builder->build_object( { class => 'Koha::Libraries' } ); - my $patron_1 = $builder->build_object({ class => 'Koha::Patrons', value => { branchcode => $library_1->id } }); - my $patron_2 = $builder->build_object({ class => 'Koha::Patrons', value => { branchcode => $library_1->id } }); - my $patron_3 = $builder->build_object({ class => 'Koha::Patrons', value => { branchcode => $library_2->id } }); + my $patron_1 = $builder->build_object( { class => 'Koha::Patrons', value => { branchcode => $library_1->id } } ); + my $patron_2 = $builder->build_object( { class => 'Koha::Patrons', value => { branchcode => $library_1->id } } ); + my $patron_3 = $builder->build_object( { class => 'Koha::Patrons', value => { branchcode => $library_2->id } } ); my @libraries_where_can_see_patrons = ( $library_1->id, $library_2->id ); my $t = Test::Mojo->new; my $mocked_patron = Test::MockModule->new('Koha::Patron'); - $mocked_patron->mock( 'libraries_where_can_see_things', sub - { + $mocked_patron->mock( + 'libraries_where_can_see_things', + sub { return @libraries_where_can_see_patrons; } ); @@ -663,20 +642,16 @@ subtest 'objects.search helper, search_limited() tests' => sub { } ); - t::lib::Mocks::mock_userenv({ patron => $patron }); + t::lib::Mocks::mock_userenv( { patron => $patron } ); $t->get_ok( "/my_patrons?q=" . encode_json( { library_id => [ $library_1->id, $library_2->id ] } ) ) - ->status_is(200) - ->json_is( '/0/patron_id' => $patron_1->id ) - ->json_is( '/1/patron_id' => $patron_2->id ) - ->json_is( '/2/patron_id' => $patron_3->id ); + ->status_is(200)->json_is( '/0/patron_id' => $patron_1->id )->json_is( '/1/patron_id' => $patron_2->id ) + ->json_is( '/2/patron_id' => $patron_3->id ); @libraries_where_can_see_patrons = ( $library_2->id ); my $res = $t->get_ok( "/my_patrons?q=" . encode_json( { library_id => [ $library_1->id, $library_2->id ] } ) ) - ->status_is(200) - ->json_is( '/0/patron_id' => $patron_3->id, 'Returns the only allowed patron' ) - ->tx->res->json; + ->status_is(200)->json_is( '/0/patron_id' => $patron_3->id, 'Returns the only allowed patron' )->tx->res->json; is( scalar @{$res}, 1, 'Only one patron returned' ); @@ -692,8 +667,7 @@ subtest 'objects.find helper with expanded authorised values' => sub { my $t = Test::Mojo->new; Koha::AuthorisedValues->search( { category => 'Countries' } )->delete; - Koha::AuthorisedValueCategories->search( { category_name => 'Countries' } ) - ->delete; + Koha::AuthorisedValueCategories->search( { category_name => 'Countries' } )->delete; my $cat = $builder->build_object( { @@ -736,7 +710,7 @@ subtest 'objects.find helper with expanded authorised values' => sub { $city_class->mock( 'strings_map', sub { - my ($self, $params) = @_; + my ( $self, $params ) = @_; use Koha::AuthorisedValues; my $av = Koha::AuthorisedValues->find( @@ -775,23 +749,18 @@ subtest 'objects.find helper with expanded authorised values' => sub { } ); - $t->get_ok( '/cities/' . $manuel->id => { 'x-koha-embed' => '+strings' } ) - ->status_is(200)->json_is( '/name' => 'Manuel' ) - ->json_has('/_strings') - ->json_is( '/_strings/country/type' => 'av' ) - ->json_is( '/_strings/country/category' => $cat->category_name ) - ->json_is( '/_strings/country/str' => $ar->lib ); + $t->get_ok( '/cities/' . $manuel->id => { 'x-koha-embed' => '+strings' } )->status_is(200) + ->json_is( '/name' => 'Manuel' )->json_has('/_strings')->json_is( '/_strings/country/type' => 'av' ) + ->json_is( '/_strings/country/category' => $cat->category_name ) + ->json_is( '/_strings/country/str' => $ar->lib ); - $t->get_ok( '/cities/' . $manuel->id => { 'x-koha-embed' => '' } ) - ->status_is(200)->json_is( '/name' => 'Manuel' ) - ->json_hasnt('/_strings'); + $t->get_ok( '/cities/' . $manuel->id => { 'x-koha-embed' => '' } )->status_is(200)->json_is( '/name' => 'Manuel' ) + ->json_hasnt('/_strings'); - $t->get_ok( '/cities/' . $manuela->id => { 'x-koha-embed' => '+strings' } ) - ->status_is(200)->json_is( '/name' => 'Manuela' ) - ->json_has('/_strings') - ->json_is( '/_strings/country/type' => 'av' ) - ->json_is( '/_strings/country/category' => $cat->category_name ) - ->json_is( '/_strings/country/str' => $us->lib ); + $t->get_ok( '/cities/' . $manuela->id => { 'x-koha-embed' => '+strings' } )->status_is(200) + ->json_is( '/name' => 'Manuela' )->json_has('/_strings')->json_is( '/_strings/country/type' => 'av' ) + ->json_is( '/_strings/country/category' => $cat->category_name ) + ->json_is( '/_strings/country/str' => $us->lib ); $schema->storage->txn_rollback; }; @@ -805,8 +774,7 @@ subtest 'objects.search helper with expanded authorised values' => sub { $schema->storage->txn_begin; Koha::AuthorisedValues->search( { category => 'Countries' } )->delete; - Koha::AuthorisedValueCategories->search( { category_name => 'Countries' } ) - ->delete; + Koha::AuthorisedValueCategories->search( { category_name => 'Countries' } )->delete; my $cat = $builder->build_object( { @@ -849,7 +817,7 @@ subtest 'objects.search helper with expanded authorised values' => sub { $city_class->mock( 'strings_map', sub { - my ($self, $params) = @_; + my ( $self, $params ) = @_; use Koha::AuthorisedValues; my $av = Koha::AuthorisedValues->find( @@ -869,7 +837,6 @@ subtest 'objects.search helper with expanded authorised values' => sub { } ); - $builder->build_object( { class => 'Koha::Cities', @@ -889,25 +856,18 @@ subtest 'objects.search helper with expanded authorised values' => sub { } ); - $t->get_ok( '/cities?name=manuel&_per_page=4&_page=1&_match=starts_with' => - { 'x-koha-embed' => '+strings' } )->status_is(200) - ->json_has('/0')->json_has('/1')->json_hasnt('/2') - ->json_is( '/0/name' => 'Manuel' ) - ->json_has('/0/_strings') - ->json_is( '/0/_strings/country/str' => $ar->lib ) - ->json_is( '/0/_strings/country/type' => 'av' ) - ->json_is( '/0/_strings/country/category' => $cat->category_name ) - ->json_is( '/1/name' => 'Manuela' ) - ->json_has('/1/_strings') - ->json_is( '/1/_strings/country/str' => $us->lib ) - ->json_is( '/1/_strings/country/type' => 'av' ) - ->json_is( '/1/_strings/country/category' => $cat->category_name ); - - $t->get_ok( '/cities?name=manuel&_per_page=4&_page=1&_match=starts_with' )->status_is(200) - ->json_has('/0')->json_has('/1')->json_hasnt('/2') - ->json_is( '/0/name' => 'Manuel' )->json_hasnt('/0/_strings') - ->json_is( '/1/name' => 'Manuela' )->json_hasnt('/1/_strings'); + $t->get_ok( '/cities?name=manuel&_per_page=4&_page=1&_match=starts_with' => { 'x-koha-embed' => '+strings' } ) + ->status_is(200)->json_has('/0')->json_has('/1')->json_hasnt('/2')->json_is( '/0/name' => 'Manuel' ) + ->json_has('/0/_strings')->json_is( '/0/_strings/country/str' => $ar->lib ) + ->json_is( '/0/_strings/country/type' => 'av' ) + ->json_is( '/0/_strings/country/category' => $cat->category_name )->json_is( '/1/name' => 'Manuela' ) + ->json_has('/1/_strings')->json_is( '/1/_strings/country/str' => $us->lib ) + ->json_is( '/1/_strings/country/type' => 'av' ) + ->json_is( '/1/_strings/country/category' => $cat->category_name ); + $t->get_ok('/cities?name=manuel&_per_page=4&_page=1&_match=starts_with')->status_is(200)->json_has('/0') + ->json_has('/1')->json_hasnt('/2')->json_is( '/0/name' => 'Manuel' )->json_hasnt('/0/_strings') + ->json_is( '/1/name' => 'Manuela' )->json_hasnt('/1/_strings'); $schema->storage->txn_rollback; }; @@ -918,49 +878,40 @@ subtest 'objects.find_rs helper' => sub { $schema->storage->txn_begin; my $superlibrarian = - $builder->build_object( { class => 'Koha::Patrons', value => { flags => 1 } } ); - t::lib::Mocks::mock_userenv({ patron => $superlibrarian }); + $builder->build_object( { class => 'Koha::Patrons', value => { flags => 1 } } ); + t::lib::Mocks::mock_userenv( { patron => $superlibrarian } ); # Remove existing cities to have more control on the search results Koha::Cities->delete; - # Create three sample cities that match the query. This makes sure we - # always have a "next" link regardless of Mojolicious::Plugin::OpenAPI version. + # Create three sample cities that match the query. This makes sure we + # always have a "next" link regardless of Mojolicious::Plugin::OpenAPI version. my $city1 = $builder->build_object( { class => 'Koha::Cities', - value => { - city_name => 'city1' - } + value => { city_name => 'city1' } } ); my $city2 = $builder->build_object( { class => 'Koha::Cities', - value => { - city_name => 'city2' - } + value => { city_name => 'city2' } } ); my $city3 = $builder->build_object( { class => 'Koha::Cities', - value => { - city_name => 'city3' - } + value => { city_name => 'city3' } } ); my $t = Test::Mojo->new; - $t->get_ok( '/cities/' . $city1->id . '/rs' )->status_is(200) - ->json_is( '/name' => 'city1' ); + $t->get_ok( '/cities/' . $city1->id . '/rs' )->status_is(200)->json_is( '/name' => 'city1' ); - $t->get_ok( '/cities/' . $city2->id . '/rs' )->status_is(200) - ->json_is( '/name' => 'city2' ); + $t->get_ok( '/cities/' . $city2->id . '/rs' )->status_is(200)->json_is( '/name' => 'city2' ); - $t->get_ok( '/cities/' . $city3->id . '/rs' )->status_is(200) - ->json_is( '/name' => 'city3' ); + $t->get_ok( '/cities/' . $city3->id . '/rs' )->status_is(200)->json_is( '/name' => 'city3' ); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/Koha/REST/Plugin/Pagination.t b/t/db_dependent/Koha/REST/Plugin/Pagination.t index 5e8a4a3449..2453da8cd3 100755 --- a/t/db_dependent/Koha/REST/Plugin/Pagination.t +++ b/t/db_dependent/Koha/REST/Plugin/Pagination.t @@ -28,7 +28,7 @@ app->log->level('error'); plugin 'Koha::REST::Plugin::Pagination'; -my $schema = Koha::Database->new->schema; +my $schema = Koha::Database->new->schema; my $builder = t::lib::TestBuilder->new; $schema->storage->txn_begin; @@ -36,11 +36,12 @@ $schema->storage->txn_begin; # Add 10 known 'Jonathan' patrons my @patron_ids; for my $i ( 1 .. 10 ) { - push @patron_ids, $builder->build_object({ class => 'Koha::Patrons', value => { firstname => 'Jonathan' } })->id; + push @patron_ids, $builder->build_object( { class => 'Koha::Patrons', value => { firstname => 'Jonathan' } } )->id; } + # Add two non-Jonathans -push @patron_ids, $builder->build_object({ class => 'Koha::Patrons' })->id; -push @patron_ids, $builder->build_object({ class => 'Koha::Patrons' })->id; +push @patron_ids, $builder->build_object( { class => 'Koha::Patrons' } )->id; +push @patron_ids, $builder->build_object( { class => 'Koha::Patrons' } )->id; # For add_pagination_headers() @@ -54,21 +55,23 @@ get '/pagination_headers' => sub { my $args = $c->req->params->to_hash; - my $result_set = Koha::Patrons->search( - { borrowernumber => \@patron_ids } - ); + my $result_set = Koha::Patrons->search( { borrowernumber => \@patron_ids } ); - my $rows = ($args->{_per_page}) ? - ( $args->{_per_page} == -1 ) ? undef : $args->{_per_page} - : C4::Context->preference('RESTdefaultPageSize'); + my $rows = + ( $args->{_per_page} ) + ? ( $args->{_per_page} == -1 ) + ? undef + : $args->{_per_page} + : C4::Context->preference('RESTdefaultPageSize'); - my $objects_rs = $result_set->search( { firstname => 'Jonathan' } ,{ page => $args->{_page} // 1, rows => $rows }); + my $objects_rs = $result_set->search( { firstname => 'Jonathan' }, { page => $args->{_page} // 1, rows => $rows } ); - $c->stash('koha.pagination.page' => $args->{_page}); - $c->stash('koha.pagination.per_page' => $args->{_per_page}); - $c->stash('koha.pagination.base_total' => $result_set->count); - $c->stash('koha.pagination.query_params' => $args); - $c->stash('koha.pagination.total' => $objects_rs->is_paged ? $objects_rs->pager->total_entries : $objects_rs->count); + $c->stash( 'koha.pagination.page' => $args->{_page} ); + $c->stash( 'koha.pagination.per_page' => $args->{_per_page} ); + $c->stash( 'koha.pagination.base_total' => $result_set->count ); + $c->stash( 'koha.pagination.query_params' => $args ); + $c->stash( + 'koha.pagination.total' => $objects_rs->is_paged ? $objects_rs->pager->total_entries : $objects_rs->count ); $c->add_pagination_headers; @@ -78,9 +81,9 @@ get '/pagination_headers' => sub { # For dbic_merge_pagination get '/dbic_merge_pagination' => sub { - my $c = shift; + my $c = shift; my $filter = { firstname => 'Kyle', surname => 'Hall' }; - $filter = $c->dbic_merge_pagination({ filter => $filter, params => { _page => 1, _per_page => 3 } }); + $filter = $c->dbic_merge_pagination( { filter => $filter, params => { _page => 1, _per_page => 3 } } ); $c->render( json => $filter, status => 200 ); }; @@ -97,123 +100,118 @@ subtest 'add_pagination_headers() tests' => sub { my $t = Test::Mojo->new; - $t->get_ok('/empty') - ->status_is( 200 ) - ->header_is( 'X-Total-Count' => undef, 'X-Total-Count is undefined' ) - ->header_is( 'X-Base-Total-Count' => undef, 'X-Base-Total-Count is undefined' ) - ->header_is( 'Link' => undef, 'Link is undefined' ); + $t->get_ok('/empty')->status_is(200)->header_is( 'X-Total-Count' => undef, 'X-Total-Count is undefined' ) + ->header_is( 'X-Base-Total-Count' => undef, 'X-Base-Total-Count is undefined' ) + ->header_is( 'Link' => undef, 'Link is undefined' ); - $t->get_ok('/pagination_headers?firstname=Jonathan&_page=2&_per_page=3') - ->status_is( 200 ) - ->header_is( 'X-Total-Count' => 10, 'X-Total-Count correctly set' ) - ->header_is( 'X-Base-Total-Count' => 12, 'X-Base-Total-Count correctly set' ) - ->header_like( 'Link' => qr/<http:\/\/.*\?.*_per_page=3.*>; rel="prev",/ ) - ->header_like( 'Link' => qr/<http:\/\/.*\?.*_page=1.*>; rel="prev",/ ) - ->header_like( 'Link' => qr/<http:\/\/.*\?.*firstname=Jonathan.*>; rel="prev",/ ) - ->header_like( 'Link' => qr/<http:\/\/.*\?.*_per_page=3.*>; rel="next",/ ) - ->header_like( 'Link' => qr/<http:\/\/.*\?.*_page=3.*>; rel="next",/ ) - ->header_like( 'Link' => qr/<http:\/\/.*\?.*firstname=Jonathan.*>; rel="next",/ ) - ->header_like( 'Link' => qr/<http:\/\/.*\?.*_per_page=3.*>; rel="first",/ ) - ->header_like( 'Link' => qr/<http:\/\/.*\?.*_page=1.*>; rel="first",/ ) - ->header_like( 'Link' => qr/<http:\/\/.*\?.*firstname=Jonathan.*>; rel="first",/ ) - ->header_like( 'Link' => qr/<http:\/\/.*\?.*_per_page=3.*>; rel="last"/ ) - ->header_like( 'Link' => qr/<http:\/\/.*\?.*_page=4.*>; rel="last"/ ) - ->header_like( 'Link' => qr/<http:\/\/.*\?.*firstname=Jonathan.*>; rel="last"/ ); + $t->get_ok('/pagination_headers?firstname=Jonathan&_page=2&_per_page=3')->status_is(200) + ->header_is( 'X-Total-Count' => 10, 'X-Total-Count correctly set' ) + ->header_is( 'X-Base-Total-Count' => 12, 'X-Base-Total-Count correctly set' ) + ->header_like( 'Link' => qr/<http:\/\/.*\?.*_per_page=3.*>; rel="prev",/ ) + ->header_like( 'Link' => qr/<http:\/\/.*\?.*_page=1.*>; rel="prev",/ ) + ->header_like( 'Link' => qr/<http:\/\/.*\?.*firstname=Jonathan.*>; rel="prev",/ ) + ->header_like( 'Link' => qr/<http:\/\/.*\?.*_per_page=3.*>; rel="next",/ ) + ->header_like( 'Link' => qr/<http:\/\/.*\?.*_page=3.*>; rel="next",/ ) + ->header_like( 'Link' => qr/<http:\/\/.*\?.*firstname=Jonathan.*>; rel="next",/ ) + ->header_like( 'Link' => qr/<http:\/\/.*\?.*_per_page=3.*>; rel="first",/ ) + ->header_like( 'Link' => qr/<http:\/\/.*\?.*_page=1.*>; rel="first",/ ) + ->header_like( 'Link' => qr/<http:\/\/.*\?.*firstname=Jonathan.*>; rel="first",/ ) + ->header_like( 'Link' => qr/<http:\/\/.*\?.*_per_page=3.*>; rel="last"/ ) + ->header_like( 'Link' => qr/<http:\/\/.*\?.*_page=4.*>; rel="last"/ ) + ->header_like( 'Link' => qr/<http:\/\/.*\?.*firstname=Jonathan.*>; rel="last"/ ); - $t->get_ok('/pagination_headers?firstname=Jonathan&_page=1&_per_page=3') - ->status_is( 200 ) - ->header_is( 'X-Total-Count' => 10, 'X-Total-Count correctly set' ) - ->header_is( 'X-Base-Total-Count' => 12, 'X-Base-Total-Count correctly set' ) - ->header_unlike( 'Link' => qr/<http:\/\/.*\?.*>; rel="prev",/ ) - ->header_like( 'Link' => qr/<http:\/\/.*\?.*_per_page=3.*>; rel="next",/ ) - ->header_like( 'Link' => qr/<http:\/\/.*\?.*_page=2.*>; rel="next",/ ) - ->header_like( 'Link' => qr/<http:\/\/.*\?.*firstname=Jonathan.*>; rel="next",/ ) - ->header_like( 'Link' => qr/<http:\/\/.*\?.*_per_page=3.*>; rel="first",/ ) - ->header_like( 'Link' => qr/<http:\/\/.*\?.*_page=1.*>; rel="first",/ ) - ->header_like( 'Link' => qr/<http:\/\/.*\?.*firstname=Jonathan.*>; rel="first",/ ) - ->header_like( 'Link' => qr/<http:\/\/.*\?.*_per_page=3.*>; rel="last"/ ) - ->header_like( 'Link' => qr/<http:\/\/.*\?.*_page=4.*>; rel="last"/ ) - ->header_like( 'Link' => qr/<http:\/\/.*\?.*firstname=Jonathan.*>; rel="last"/ ); + $t->get_ok('/pagination_headers?firstname=Jonathan&_page=1&_per_page=3')->status_is(200) + ->header_is( 'X-Total-Count' => 10, 'X-Total-Count correctly set' ) + ->header_is( 'X-Base-Total-Count' => 12, 'X-Base-Total-Count correctly set' ) + ->header_unlike( 'Link' => qr/<http:\/\/.*\?.*>; rel="prev",/ ) + ->header_like( 'Link' => qr/<http:\/\/.*\?.*_per_page=3.*>; rel="next",/ ) + ->header_like( 'Link' => qr/<http:\/\/.*\?.*_page=2.*>; rel="next",/ ) + ->header_like( 'Link' => qr/<http:\/\/.*\?.*firstname=Jonathan.*>; rel="next",/ ) + ->header_like( 'Link' => qr/<http:\/\/.*\?.*_per_page=3.*>; rel="first",/ ) + ->header_like( 'Link' => qr/<http:\/\/.*\?.*_page=1.*>; rel="first",/ ) + ->header_like( 'Link' => qr/<http:\/\/.*\?.*firstname=Jonathan.*>; rel="first",/ ) + ->header_like( 'Link' => qr/<http:\/\/.*\?.*_per_page=3.*>; rel="last"/ ) + ->header_like( 'Link' => qr/<http:\/\/.*\?.*_page=4.*>; rel="last"/ ) + ->header_like( 'Link' => qr/<http:\/\/.*\?.*firstname=Jonathan.*>; rel="last"/ ); - $t->get_ok('/pagination_headers?firstname=Jonathan&_page=4&_per_page=3') - ->status_is( 200 ) - ->header_is( 'X-Total-Count' => 10, 'X-Total-Count correctly set' ) - ->header_is( 'X-Base-Total-Count' => 12, 'X-Base-Total-Count correctly set' ) - ->header_like( 'Link' => qr/<http:\/\/.*\?.*_per_page=3.*>; rel="prev",/ ) - ->header_like( 'Link' => qr/<http:\/\/.*\?.*_page=3.*>; rel="prev",/ ) - ->header_like( 'Link' => qr/<http:\/\/.*\?.*firstname=Jonathan.*>; rel="prev",/ ) - ->header_unlike( 'Link' => qr/<http:\/\/.*\?.*>; rel="next",/ ) - ->header_like( 'Link' => qr/<http:\/\/.*\?.*_per_page=3.*>; rel="first",/ ) - ->header_like( 'Link' => qr/<http:\/\/.*\?.*_page=1.*>; rel="first",/ ) - ->header_like( 'Link' => qr/<http:\/\/.*\?.*firstname=Jonathan.*>; rel="first",/ ) - ->header_like( 'Link' => qr/<http:\/\/.*\?.*_per_page=3.*>; rel="last"/ ) - ->header_like( 'Link' => qr/<http:\/\/.*\?.*_page=4.*>; rel="last"/ ) - ->header_like( 'Link' => qr/<http:\/\/.*\?.*firstname=Jonathan.*>; rel="last"/ ); + $t->get_ok('/pagination_headers?firstname=Jonathan&_page=4&_per_page=3')->status_is(200) + ->header_is( 'X-Total-Count' => 10, 'X-Total-Count correctly set' ) + ->header_is( 'X-Base-Total-Count' => 12, 'X-Base-Total-Count correctly set' ) + ->header_like( 'Link' => qr/<http:\/\/.*\?.*_per_page=3.*>; rel="prev",/ ) + ->header_like( 'Link' => qr/<http:\/\/.*\?.*_page=3.*>; rel="prev",/ ) + ->header_like( 'Link' => qr/<http:\/\/.*\?.*firstname=Jonathan.*>; rel="prev",/ ) + ->header_unlike( 'Link' => qr/<http:\/\/.*\?.*>; rel="next",/ ) + ->header_like( 'Link' => qr/<http:\/\/.*\?.*_per_page=3.*>; rel="first",/ ) + ->header_like( 'Link' => qr/<http:\/\/.*\?.*_page=1.*>; rel="first",/ ) + ->header_like( 'Link' => qr/<http:\/\/.*\?.*firstname=Jonathan.*>; rel="first",/ ) + ->header_like( 'Link' => qr/<http:\/\/.*\?.*_per_page=3.*>; rel="last"/ ) + ->header_like( 'Link' => qr/<http:\/\/.*\?.*_page=4.*>; rel="last"/ ) + ->header_like( 'Link' => qr/<http:\/\/.*\?.*firstname=Jonathan.*>; rel="last"/ ); - t::lib::Mocks::mock_preference('RESTdefaultPageSize', 3); - $t->get_ok('/pagination_headers?firstname=Jonathan&_page=2') - ->status_is( 200 ) - ->header_is( 'X-Total-Count' => 10, 'X-Total-Count correctly set' ) - ->header_is( 'X-Base-Total-Count' => 12, 'X-Base-Total-Count correctly set' ) - ->header_like( 'Link' => qr/<http:\/\/.*\?.*per_page=3.*>; rel="prev",/ ) - ->header_like( 'Link' => qr/<http:\/\/.*\?.*page=1.*>; rel="prev",/ ) - ->header_like( 'Link' => qr/<http:\/\/.*\?.*firstname=Jonathan.*>; rel="prev",/ ) - ->header_like( 'Link' => qr/<http:\/\/.*\?.*per_page=3.*>; rel="next",/ ) - ->header_like( 'Link' => qr/<http:\/\/.*\?.*page=3.*>; rel="next",/ ) - ->header_like( 'Link' => qr/<http:\/\/.*\?.*firstname=Jonathan.*>; rel="next",/ ) - ->header_like( 'Link' => qr/<http:\/\/.*\?.*per_page=3.*>; rel="first",/ ) - ->header_like( 'Link' => qr/<http:\/\/.*\?.*page=1.*>; rel="first",/ ) - ->header_like( 'Link' => qr/<http:\/\/.*\?.*firstname=Jonathan.*>; rel="first",/ ) - ->header_like( 'Link' => qr/<http:\/\/.*\?.*per_page=3.*>; rel="last"/ ) - ->header_like( 'Link' => qr/<http:\/\/.*\?.*page=4.*>; rel="last"/ ) - ->header_like( 'Link' => qr/<http:\/\/.*\?.*firstname=Jonathan.*>; rel="last"/ ); + t::lib::Mocks::mock_preference( 'RESTdefaultPageSize', 3 ); + $t->get_ok('/pagination_headers?firstname=Jonathan&_page=2')->status_is(200) + ->header_is( 'X-Total-Count' => 10, 'X-Total-Count correctly set' ) + ->header_is( 'X-Base-Total-Count' => 12, 'X-Base-Total-Count correctly set' ) + ->header_like( 'Link' => qr/<http:\/\/.*\?.*per_page=3.*>; rel="prev",/ ) + ->header_like( 'Link' => qr/<http:\/\/.*\?.*page=1.*>; rel="prev",/ ) + ->header_like( 'Link' => qr/<http:\/\/.*\?.*firstname=Jonathan.*>; rel="prev",/ ) + ->header_like( 'Link' => qr/<http:\/\/.*\?.*per_page=3.*>; rel="next",/ ) + ->header_like( 'Link' => qr/<http:\/\/.*\?.*page=3.*>; rel="next",/ ) + ->header_like( 'Link' => qr/<http:\/\/.*\?.*firstname=Jonathan.*>; rel="next",/ ) + ->header_like( 'Link' => qr/<http:\/\/.*\?.*per_page=3.*>; rel="first",/ ) + ->header_like( 'Link' => qr/<http:\/\/.*\?.*page=1.*>; rel="first",/ ) + ->header_like( 'Link' => qr/<http:\/\/.*\?.*firstname=Jonathan.*>; rel="first",/ ) + ->header_like( 'Link' => qr/<http:\/\/.*\?.*per_page=3.*>; rel="last"/ ) + ->header_like( 'Link' => qr/<http:\/\/.*\?.*page=4.*>; rel="last"/ ) + ->header_like( 'Link' => qr/<http:\/\/.*\?.*firstname=Jonathan.*>; rel="last"/ ); - $t->get_ok('/pagination_headers?firstname=Jonathan&_per_page=3') - ->status_is( 200 ) - ->header_is( 'X-Total-Count' => 10, 'X-Total-Count header present, even without page param' ) - ->header_is( 'X-Base-Total-Count' => 12, 'X-Base-Total-Count correctly set' ) - ->header_unlike( 'Link' => qr/<http:\/\/.*\?.*per_page=3.*>; rel="prev",/, 'First page, no previous' ) - ->header_unlike( 'Link' => qr/<http:\/\/.*\?.*page=1.*>; rel="prev",/, 'First page, no previous' ) - ->header_unlike( 'Link' => qr/<http:\/\/.*\?.*firstname=Jonathan.*>; rel="prev",/, 'First page, no previous' ) - ->header_like( 'Link' => qr/<http:\/\/.*\?.*per_page=3.*>; rel="next",/ ) - ->header_like( 'Link' => qr/<http:\/\/.*\?.*page=2.*>; rel="next",/ ) - ->header_like( 'Link' => qr/<http:\/\/.*\?.*firstname=Jonathan.*>; rel="next",/ ) - ->header_like( 'Link' => qr/<http:\/\/.*\?.*per_page=3.*>; rel="first",/ ) - ->header_like( 'Link' => qr/<http:\/\/.*\?.*page=1.*>; rel="first",/ ) - ->header_like( 'Link' => qr/<http:\/\/.*\?.*firstname=Jonathan.*>; rel="first",/ ) - ->header_like( 'Link' => qr/<http:\/\/.*\?.*per_page=3.*>; rel="last"/ ) - ->header_like( 'Link' => qr/<http:\/\/.*\?.*page=4.*>; rel="last"/ ) - ->header_like( 'Link' => qr/<http:\/\/.*\?.*firstname=Jonathan.*>; rel="last"/ ); + $t->get_ok('/pagination_headers?firstname=Jonathan&_per_page=3')->status_is(200) + ->header_is( 'X-Total-Count' => 10, 'X-Total-Count header present, even without page param' ) + ->header_is( 'X-Base-Total-Count' => 12, 'X-Base-Total-Count correctly set' ) + ->header_unlike( 'Link' => qr/<http:\/\/.*\?.*per_page=3.*>; rel="prev",/, 'First page, no previous' ) + ->header_unlike( 'Link' => qr/<http:\/\/.*\?.*page=1.*>; rel="prev",/, 'First page, no previous' ) + ->header_unlike( 'Link' => qr/<http:\/\/.*\?.*firstname=Jonathan.*>; rel="prev",/, 'First page, no previous' ) + ->header_like( 'Link' => qr/<http:\/\/.*\?.*per_page=3.*>; rel="next",/ ) + ->header_like( 'Link' => qr/<http:\/\/.*\?.*page=2.*>; rel="next",/ ) + ->header_like( 'Link' => qr/<http:\/\/.*\?.*firstname=Jonathan.*>; rel="next",/ ) + ->header_like( 'Link' => qr/<http:\/\/.*\?.*per_page=3.*>; rel="first",/ ) + ->header_like( 'Link' => qr/<http:\/\/.*\?.*page=1.*>; rel="first",/ ) + ->header_like( 'Link' => qr/<http:\/\/.*\?.*firstname=Jonathan.*>; rel="first",/ ) + ->header_like( 'Link' => qr/<http:\/\/.*\?.*per_page=3.*>; rel="last"/ ) + ->header_like( 'Link' => qr/<http:\/\/.*\?.*page=4.*>; rel="last"/ ) + ->header_like( 'Link' => qr/<http:\/\/.*\?.*firstname=Jonathan.*>; rel="last"/ ); - $t->get_ok('/pagination_headers?firstname=Jonathan&_per_page=-1') - ->status_is( 200 ) - ->header_is( 'X-Total-Count' => 10, 'X-Total-Count header present, with per_page=-1' ) - ->header_is( 'X-Base-Total-Count' => 12, 'X-Base-Total-Count correctly set' ) - ->header_unlike( 'Link' => qr/<http:\/\/.*\?.*per_page=-1.*>; rel="prev",/, 'First page, no previous' ) - ->header_unlike( 'Link' => qr/<http:\/\/.*\?.*page=1.*>; rel="prev",/, 'First page, no previous' ) - ->header_unlike( 'Link' => qr/<http:\/\/.*\?.*firstname=Jonathan.*>; rel="prev",/, 'First page, no previous' ) - ->header_unlike( 'Link' => qr/<http:\/\/.*\?.*per_page=-1.*>; rel="next",/, 'No next page, all resources are fetched' ) - ->header_like( 'Link' => qr/<http:\/\/.*\?.*per_page=-1.*>; rel="first",/ ) - ->header_like( 'Link' => qr/<http:\/\/.*\?.*page=1.*>; rel="first",/ ) - ->header_like( 'Link' => qr/<http:\/\/.*\?.*firstname=Jonathan.*>; rel="first",/ ) - ->header_like( 'Link' => qr/<http:\/\/.*\?.*per_page=-1.*>; rel="last"/ ) - ->header_like( 'Link' => qr/<http:\/\/.*\?.*page=1.*>; rel="last"/ ) - ->header_like( 'Link' => qr/<http:\/\/.*\?.*firstname=Jonathan.*>; rel="last"/ ); + $t->get_ok('/pagination_headers?firstname=Jonathan&_per_page=-1')->status_is(200) + ->header_is( 'X-Total-Count' => 10, 'X-Total-Count header present, with per_page=-1' ) + ->header_is( 'X-Base-Total-Count' => 12, 'X-Base-Total-Count correctly set' ) + ->header_unlike( 'Link' => qr/<http:\/\/.*\?.*per_page=-1.*>; rel="prev",/, 'First page, no previous' ) + ->header_unlike( 'Link' => qr/<http:\/\/.*\?.*page=1.*>; rel="prev",/, 'First page, no previous' ) + ->header_unlike( 'Link' => qr/<http:\/\/.*\?.*firstname=Jonathan.*>; rel="prev",/, 'First page, no previous' ) + ->header_unlike( + 'Link' => qr/<http:\/\/.*\?.*per_page=-1.*>; rel="next",/, + 'No next page, all resources are fetched' + )->header_like( 'Link' => qr/<http:\/\/.*\?.*per_page=-1.*>; rel="first",/ ) + ->header_like( 'Link' => qr/<http:\/\/.*\?.*page=1.*>; rel="first",/ ) + ->header_like( 'Link' => qr/<http:\/\/.*\?.*firstname=Jonathan.*>; rel="first",/ ) + ->header_like( 'Link' => qr/<http:\/\/.*\?.*per_page=-1.*>; rel="last"/ ) + ->header_like( 'Link' => qr/<http:\/\/.*\?.*page=1.*>; rel="last"/ ) + ->header_like( 'Link' => qr/<http:\/\/.*\?.*firstname=Jonathan.*>; rel="last"/ ); - $t->get_ok('/pagination_headers?firstname=Jonathan&_per_page=-1&_page=100') - ->status_is( 200 ) - ->header_is( 'X-Total-Count' => 10, 'X-Total-Count header present, with per_page=-1' ) - ->header_is( 'X-Base-Total-Count' => 12, 'X-Base-Total-Count correctly set' ) - ->header_unlike( 'Link' => qr/<http:\/\/.*\?.*per_page=-1.*>; rel="prev",/, 'First page, no previous' ) - ->header_unlike( 'Link' => qr/<http:\/\/.*\?.*page=1.*>; rel="prev",/, 'First page, no previous' ) - ->header_unlike( 'Link' => qr/<http:\/\/.*\?.*firstname=Jonathan.*>; rel="prev",/, 'First page, no previous' ) - ->header_unlike( 'Link' => qr/<http:\/\/.*\?.*per_page=-1.*>; rel="next",/, 'No next page, all resources are fetched' ) - ->header_like( 'Link' => qr/<http:\/\/.*\?.*per_page=-1.*>; rel="first",/ ) - ->header_like( 'Link' => qr/<http:\/\/.*\?.*page=1.*>; rel="first",/ ) - ->header_like( 'Link' => qr/<http:\/\/.*\?.*firstname=Jonathan.*>; rel="first",/ ) - ->header_like( 'Link' => qr/<http:\/\/.*\?.*per_page=-1.*>; rel="last"/ ) - ->header_like( 'Link' => qr/<http:\/\/.*\?.*page=1.*>; rel="last"/ ) - ->header_like( 'Link' => qr/<http:\/\/.*\?.*firstname=Jonathan.*>; rel="last"/ ); + $t->get_ok('/pagination_headers?firstname=Jonathan&_per_page=-1&_page=100')->status_is(200) + ->header_is( 'X-Total-Count' => 10, 'X-Total-Count header present, with per_page=-1' ) + ->header_is( 'X-Base-Total-Count' => 12, 'X-Base-Total-Count correctly set' ) + ->header_unlike( 'Link' => qr/<http:\/\/.*\?.*per_page=-1.*>; rel="prev",/, 'First page, no previous' ) + ->header_unlike( 'Link' => qr/<http:\/\/.*\?.*page=1.*>; rel="prev",/, 'First page, no previous' ) + ->header_unlike( 'Link' => qr/<http:\/\/.*\?.*firstname=Jonathan.*>; rel="prev",/, 'First page, no previous' ) + ->header_unlike( + 'Link' => qr/<http:\/\/.*\?.*per_page=-1.*>; rel="next",/, + 'No next page, all resources are fetched' + )->header_like( 'Link' => qr/<http:\/\/.*\?.*per_page=-1.*>; rel="first",/ ) + ->header_like( 'Link' => qr/<http:\/\/.*\?.*page=1.*>; rel="first",/ ) + ->header_like( 'Link' => qr/<http:\/\/.*\?.*firstname=Jonathan.*>; rel="first",/ ) + ->header_like( 'Link' => qr/<http:\/\/.*\?.*per_page=-1.*>; rel="last"/ ) + ->header_like( 'Link' => qr/<http:\/\/.*\?.*page=1.*>; rel="last"/ ) + ->header_like( 'Link' => qr/<http:\/\/.*\?.*firstname=Jonathan.*>; rel="last"/ ); }; subtest 'dbic_merge_pagination() tests' => sub { @@ -222,7 +220,6 @@ subtest 'dbic_merge_pagination() tests' => sub { my $t = Test::Mojo->new; - $t->get_ok('/dbic_merge_pagination') - ->status_is(200) - ->json_is({ firstname => 'Kyle', surname => 'Hall', page => 1, rows => 3 }); + $t->get_ok('/dbic_merge_pagination')->status_is(200) + ->json_is( { firstname => 'Kyle', surname => 'Hall', page => 1, rows => 3 } ); }; diff --git a/t/db_dependent/Koha/REST/Plugin/PluginRoutes.t b/t/db_dependent/Koha/REST/Plugin/PluginRoutes.t index df9553065b..9138c5a7ee 100755 --- a/t/db_dependent/Koha/REST/Plugin/PluginRoutes.t +++ b/t/db_dependent/Koha/REST/Plugin/PluginRoutes.t @@ -39,10 +39,13 @@ use Koha::Plugins; use t::lib::TestBuilder; my $logger = Test::MockModule->new('Koha::Logger'); -$logger->mock('error', sub { - shift; - warn @_; -}); +$logger->mock( + 'error', + sub { + shift; + warn @_; + } +); my $schema = Koha::Database->new->schema; my $builder = t::lib::TestBuilder->new; @@ -70,18 +73,20 @@ subtest 'Bad plugins tests' => sub { # initialize Koha::REST::V1 after mocking my $t; - warning_like - { $t = Test::Mojo->new('Koha::REST::V1'); } - [qr{Could not load REST API spec bundle: /paths/~0001contrib~0001badass}, + warning_like { $t = Test::Mojo->new('Koha::REST::V1'); } + [ + qr{Could not load REST API spec bundle: /paths/~0001contrib~0001badass}, qr{bother_wrong/put/parameters/0: /oneOf/1 Properties not allowed:}, - qr{Plugin Koha::Plugin::BadAPIRoute route injection failed: The resulting spec is invalid. Skipping Bad API Route Plugin},], + qr{Plugin Koha::Plugin::BadAPIRoute route injection failed: The resulting spec is invalid. Skipping Bad API Route Plugin}, + ], 'Bad plugins raise warning'; my $routes = get_defined_routes($t); + # Support placeholders () and <> (latter style used starting with Mojolicious::Plugin::OpenAPI@1.28) # TODO: remove () if minimum version is bumped to at least 1.28. ok( !exists $routes->{'/contrib/badass/patrons/bother_wrong'}, 'Route doesn\'t exist' ); - ok( exists $routes->{'/contrib/testplugin/patrons/bother'}, 'Route exists' ); + ok( exists $routes->{'/contrib/testplugin/patrons/bother'}, 'Route exists' ); $schema->storage->txn_rollback; }; @@ -111,10 +116,13 @@ subtest 'Disabled plugins tests' => sub { my $t = Test::Mojo->new('Koha::REST::V1'); my $routes = get_defined_routes($t); + # Support placeholders () and <> (latter style used starting with Mojolicious::Plugin::OpenAPI@1.28) # TODO: remove () if minimum version is bumped to at least 1.28. - ok( !exists $routes->{'/contrib/testplugin/patrons/bother'}, - 'Plugin disabled, route not defined' ); + ok( + !exists $routes->{'/contrib/testplugin/patrons/bother'}, + 'Plugin disabled, route not defined' + ); $good_plugin->enable; @@ -123,8 +131,10 @@ subtest 'Disabled plugins tests' => sub { # Support placeholders () and <> (latter style used starting with Mojolicious::Plugin::OpenAPI@1.28) # TODO: remove () if minimum version is bumped to at least 1.28. - ok( exists $routes->{'/contrib/testplugin/patrons/bother'}, - 'Plugin enabled, route defined' ); + ok( + exists $routes->{'/contrib/testplugin/patrons/bother'}, + 'Plugin enabled, route defined' + ); $schema->storage->txn_rollback; }; @@ -137,6 +147,7 @@ subtest 'Permissions and access to plugin routes tests' => sub { # enable plugins t::lib::Mocks::mock_config( 'enable_plugins', 1 ); + # enable BASIC auth t::lib::Mocks::mock_preference( 'RESTBasicAuth', 1 ); @@ -156,31 +167,32 @@ subtest 'Permissions and access to plugin routes tests' => sub { # initialize Koha::REST::V1 after mocking my $t; - warning_like - { $t = Test::Mojo->new('Koha::REST::V1'); } - [qr{Could not load REST API spec bundle: /paths/~0001contrib~0001badass}, + warning_like { $t = Test::Mojo->new('Koha::REST::V1'); } + [ + qr{Could not load REST API spec bundle: /paths/~0001contrib~0001badass}, qr{bother_wrong/put/parameters/0: /oneOf/1 Properties not allowed:}, - qr{Plugin Koha::Plugin::BadAPIRoute route injection failed: The resulting spec is invalid. Skipping Bad API Route Plugin},], + qr{Plugin Koha::Plugin::BadAPIRoute route injection failed: The resulting spec is invalid. Skipping Bad API Route Plugin}, + ], 'Bad plugins raise warning'; my $routes = get_defined_routes($t); - ok( exists $routes->{'/contrib/testplugin/patrons/bother'}, 'Route exists' ); + ok( exists $routes->{'/contrib/testplugin/patrons/bother'}, 'Route exists' ); ok( exists $routes->{'/contrib/testplugin/public/patrons/bother'}, 'Route exists' ); C4::Context->set_preference( 'RESTPublicAnonymousRequests', 0 ); $t->get_ok('/api/v1/contrib/testplugin/public/patrons/bother') - ->status_is(200, 'Plugin routes not affected by RESTPublicAnonymousRequests') - ->json_is( { bothered => Mojo::JSON->true } ); + ->status_is( 200, 'Plugin routes not affected by RESTPublicAnonymousRequests' ) + ->json_is( { bothered => Mojo::JSON->true } ); C4::Context->set_preference( 'RESTPublicAnonymousRequests', 1 ); $t->get_ok('/api/v1/contrib/testplugin/public/patrons/bother') - ->status_is(200, 'Plugin routes not affected by RESTPublicAnonymousRequests') - ->json_is( { bothered => Mojo::JSON->true } ); + ->status_is( 200, 'Plugin routes not affected by RESTPublicAnonymousRequests' ) + ->json_is( { bothered => Mojo::JSON->true } ); $t->get_ok('/api/v1/contrib/testplugin/patrons/bother') - ->status_is(401, 'Plugin routes honour permissions, anonymous access denied'); + ->status_is( 401, 'Plugin routes honour permissions, anonymous access denied' ); # Create a patron with permissions, but the wrong ones: 3 => parameters my $librarian = $builder->build_object( @@ -194,14 +206,14 @@ subtest 'Permissions and access to plugin routes tests' => sub { my $userid = $librarian->userid; $t->get_ok("//$userid:$password@/api/v1/contrib/testplugin/patrons/bother") - ->status_is(403, 'Plugin routes honour permissions, wrong permissions, access denied'); + ->status_is( 403, 'Plugin routes honour permissions, wrong permissions, access denied' ); # Set the patron permissions to the right ones: 4 => borrowers - $librarian->set({ flags => 2 ** 4 })->store->discard_changes; + $librarian->set( { flags => 2**4 } )->store->discard_changes; $t->get_ok("//$userid:$password@/api/v1/contrib/testplugin/patrons/bother") - ->status_is(200, 'Plugin routes honour permissions, right permissions, access granted') - ->json_is( { bothered => Mojo::JSON->true } ); + ->status_is( 200, 'Plugin routes honour permissions, right permissions, access granted' ) + ->json_is( { bothered => Mojo::JSON->true } ); $schema->storage->txn_rollback; }; @@ -221,7 +233,8 @@ subtest 'needs_install use case tests' => sub { $plugins->InstallPlugins; # mock Version before initializing the API class - t::lib::Mocks::mock_preference('Version', undef); + t::lib::Mocks::mock_preference( 'Version', undef ); + # initialize Koha::REST::V1 after mocking my $t = Test::Mojo->new('Koha::REST::V1'); @@ -234,7 +247,7 @@ subtest 'needs_install use case tests' => sub { 'Plugin enabled, route not defined as C4::Context->needs_install is true' ); - t::lib::Mocks::mock_preference('Version', '3.0.0'); + t::lib::Mocks::mock_preference( 'Version', '3.0.0' ); Koha::Plugins->RemovePlugins( { destructive => 1 } ); # FIXME destructive seems not to be needed here $plugins->InstallPlugins; @@ -269,7 +282,7 @@ sub traverse_routes { # Methods my $methods = $route->methods // []; - my $verb = !$methods ? '*' : uc join ',', @$methods; + my $verb = !$methods ? '*' : uc join ',', @$methods; $routes->{$path}->{$verb} = 1; $depth++; diff --git a/t/db_dependent/Koha/REST/V1.t b/t/db_dependent/Koha/REST/V1.t index fc333a0814..d73b26f9fa 100755 --- a/t/db_dependent/Koha/REST/V1.t +++ b/t/db_dependent/Koha/REST/V1.t @@ -32,11 +32,12 @@ subtest 'Type definition tests' => sub { $t = Test::Mojo->new('Koha::REST::V1'); my $types = $t->app->types; - is( $types->type('json'), + is( + $types->type('json'), 'application/json; charset=utf8', 'application/json gets charset added' ); - is( $types->type('marcxml'), 'application/marcxml+xml', 'application/marcxml+xml is defined' ); - is( $types->type('mij'), 'application/marc-in-json', 'application/marc-in-json is defined' ); - is( $types->type('marc'), 'application/marc', 'application/marc is defined' ); + is( $types->type('marcxml'), 'application/marcxml+xml', 'application/marcxml+xml is defined' ); + is( $types->type('mij'), 'application/marc-in-json', 'application/marc-in-json is defined' ); + is( $types->type('marc'), 'application/marc', 'application/marc is defined' ); }; diff --git a/t/db_dependent/Koha/Ratings.t b/t/db_dependent/Koha/Ratings.t index 664a48133f..88f7ee6e64 100755 --- a/t/db_dependent/Koha/Ratings.t +++ b/t/db_dependent/Koha/Ratings.t @@ -29,13 +29,15 @@ my $schema = Koha::Database->schema; $schema->storage->txn_begin; my $builder = t::lib::TestBuilder->new; -my $patron_1 = $builder->build( { source => 'Borrower', } ); -my $patron_2 = $builder->build( { source => 'Borrower', } ); -my $biblio_1 = $builder->build_sample_biblio; +my $patron_1 = $builder->build( { source => 'Borrower', } ); +my $patron_2 = $builder->build( { source => 'Borrower', } ); +my $biblio_1 = $builder->build_sample_biblio; my $biblionumber = $biblio_1->biblionumber; -my $rating_1 = Koha::Rating->new( { biblionumber => $biblionumber, borrowernumber => $patron_1->{borrowernumber}, rating_value => 3 } )->store; -my $rating_2 = Koha::Rating->new( { biblionumber => $biblionumber, borrowernumber => $patron_2->{borrowernumber}, rating_value => 4 } )->store; +my $rating_1 = Koha::Rating->new( + { biblionumber => $biblionumber, borrowernumber => $patron_1->{borrowernumber}, rating_value => 3 } )->store; +my $rating_2 = Koha::Rating->new( + { biblionumber => $biblionumber, borrowernumber => $patron_2->{borrowernumber}, rating_value => 4 } )->store; is( $biblio_1->ratings->get_avg_rating, 3.5, 'get_avg_rating is 3.5' ); @@ -44,15 +46,21 @@ $rating_1->rating_value(5)->store; is( $biblio_1->ratings->get_avg_rating, 4.5, 'get_avg_rating now up to 4.5' ); $rating_1->rating_value(42)->store; -is( Koha::Ratings->find( { biblionumber => $biblionumber, borrowernumber => $patron_1->{borrowernumber} } )->rating_value, - 5, 'Koha::Ratings->store should mark out the boundaries of the rating values, 5 is max' ); +is( + Koha::Ratings->find( { biblionumber => $biblionumber, borrowernumber => $patron_1->{borrowernumber} } ) + ->rating_value, + 5, 'Koha::Ratings->store should mark out the boundaries of the rating values, 5 is max' +); $rating_1->rating_value(-42)->store; -is( Koha::Ratings->find( { biblionumber => $biblionumber, borrowernumber => $patron_1->{borrowernumber} } )->rating_value, - 0, 'Koha::Ratings->store should mark out the boundaries of the rating values, 0 is min' ); +is( + Koha::Ratings->find( { biblionumber => $biblionumber, borrowernumber => $patron_1->{borrowernumber} } ) + ->rating_value, + 0, 'Koha::Ratings->store should mark out the boundaries of the rating values, 0 is min' +); Koha::Ratings->find( { biblionumber => $biblionumber, borrowernumber => $patron_1->{borrowernumber} } )->delete; Koha::Ratings->find( { biblionumber => $biblionumber, borrowernumber => $patron_2->{borrowernumber} } )->delete; is( $biblio_1->ratings->count, 0, 'Delete should have deleted the ratings' ); -is( int($biblio_1->ratings->get_avg_rating), 0, 'get_avg_rating should return 0 if no rating exist' ); +is( int( $biblio_1->ratings->get_avg_rating ), 0, 'get_avg_rating should return 0 if no rating exist' ); diff --git a/t/db_dependent/Koha/Recall.t b/t/db_dependent/Koha/Recall.t index 4d6eff783e..cdd83b1ca1 100755 --- a/t/db_dependent/Koha/Recall.t +++ b/t/db_dependent/Koha/Recall.t @@ -32,7 +32,7 @@ BEGIN { # Start transaction my $database = Koha::Database->new(); -my $schema = $database->schema(); +my $schema = $database->schema(); $schema->storage->txn_begin(); my $dbh = C4::Context->dbh; @@ -40,91 +40,112 @@ my $builder = t::lib::TestBuilder->new; # Setup test variables -my $item1 = $builder->build_sample_item(); -my $biblio1 = $item1->biblio; -my $branch1 = $item1->holdingbranch; +my $item1 = $builder->build_sample_item(); +my $biblio1 = $item1->biblio; +my $branch1 = $item1->holdingbranch; my $itemtype1 = $item1->effective_itemtype; -my $item2 = $builder->build_sample_item(); -my $biblio2 = $item2->biblio; -my $branch2 = $item2->holdingbranch; +my $item2 = $builder->build_sample_item(); +my $biblio2 = $item2->biblio; +my $branch2 = $item2->holdingbranch; my $itemtype2 = $item2->effective_itemtype; -my $category1 = $builder->build({ source => 'Category' })->{ categorycode }; -my $patron1 = $builder->build_object({ class => 'Koha::Patrons', value => { categorycode => $category1, branchcode => $branch1 } }); -my $patron2 = $builder->build_object({ class => 'Koha::Patrons', value => { categorycode => $category1, branchcode => $branch1 } }); -t::lib::Mocks::mock_userenv({ patron => $patron1 }); -my $old_recalls_count = Koha::Recalls->search({ completed => 1 })->count; +my $category1 = $builder->build( { source => 'Category' } )->{categorycode}; +my $patron1 = $builder->build_object( + { class => 'Koha::Patrons', value => { categorycode => $category1, branchcode => $branch1 } } ); +my $patron2 = $builder->build_object( + { class => 'Koha::Patrons', value => { categorycode => $category1, branchcode => $branch1 } } ); +t::lib::Mocks::mock_userenv( { patron => $patron1 } ); +my $old_recalls_count = Koha::Recalls->search( { completed => 1 } )->count; -Koha::CirculationRules->set_rule({ - branchcode => undef, - categorycode => undef, - itemtype => undef, - rule_name => 'recalls_allowed', - rule_value => '10', -}); +Koha::CirculationRules->set_rule( + { + branchcode => undef, + categorycode => undef, + itemtype => undef, + rule_name => 'recalls_allowed', + rule_value => '10', + } +); my $overdue_date = dt_from_string->subtract( days => 4 ); C4::Circulation::AddIssue( $patron2, $item1->barcode, $overdue_date ); -my $recall1 = Koha::Recall->new({ - patron_id => $patron1->borrowernumber, - created_date => dt_from_string, - biblio_id => $biblio1->biblionumber, - pickup_library_id => $branch1, - status => 'requested', - item_id => $item1->itemnumber, - expiration_date => undef, - item_level => 1 -})->store; +my $recall1 = Koha::Recall->new( + { + patron_id => $patron1->borrowernumber, + created_date => dt_from_string, + biblio_id => $biblio1->biblionumber, + pickup_library_id => $branch1, + status => 'requested', + item_id => $item1->itemnumber, + expiration_date => undef, + item_level => 1 + } +)->store; -is( $recall1->biblio->title, $biblio1->title, "Recall biblio relationship correctly linked" ); -is( $recall1->item->homebranch, $item1->homebranch, "Recall item relationship correctly linked" ); -is( $recall1->patron->categorycode, $category1, "Recall patron relationship correctly linked" ); -is( $recall1->library->branchname, Koha::Libraries->find( $branch1 )->branchname, "Recall library relationship correctly linked" ); +is( $recall1->biblio->title, $biblio1->title, "Recall biblio relationship correctly linked" ); +is( $recall1->item->homebranch, $item1->homebranch, "Recall item relationship correctly linked" ); +is( $recall1->patron->categorycode, $category1, "Recall patron relationship correctly linked" ); +is( + $recall1->library->branchname, Koha::Libraries->find($branch1)->branchname, + "Recall library relationship correctly linked" +); is( $recall1->checkout->itemnumber, $item1->itemnumber, "Recall checkout relationship correctly linked" ); ok( $recall1->requested, "Recall has been requested" ); is( $recall1->should_be_overdue, 1, "Correctly calculated that recall should be marked overdue" ); -$recall1->set_overdue({ interface => 'COMMANDLINE' }); +$recall1->set_overdue( { interface => 'COMMANDLINE' } ); ok( $recall1->overdue, "Recall is overdue" ); $recall1->set_cancelled; ok( $recall1->cancelled, "Recall is cancelled" ); -my $recall2 = Koha::Recall->new({ - patron_id => $patron1->borrowernumber, - created_date => dt_from_string, - biblio_id => $biblio1->biblionumber, - pickup_library_id => $branch1, - item_id => $item1->itemnumber, - expiration_date => undef, - item_level => 1 -})->store; +my $recall2 = Koha::Recall->new( + { + patron_id => $patron1->borrowernumber, + created_date => dt_from_string, + biblio_id => $biblio1->biblionumber, + pickup_library_id => $branch1, + item_id => $item1->itemnumber, + expiration_date => undef, + item_level => 1 + } +)->store; -Koha::CirculationRules->set_rule({ - branchcode => undef, - categorycode => undef, - itemtype => undef, - rule_name => 'recall_shelf_time', - rule_value => undef, -}); +Koha::CirculationRules->set_rule( + { + branchcode => undef, + categorycode => undef, + itemtype => undef, + rule_name => 'recall_shelf_time', + rule_value => undef, + } +); t::lib::Mocks::mock_preference( 'RecallsMaxPickUpDelay', 7 ); -my $expected_expirationdate = dt_from_string->add({ days => 7 }); -my $expirationdate = $recall2->calc_expirationdate; -is( t::lib::Dates::compare( $expirationdate, $expected_expirationdate ), 0, "Expiration date calculated based on system preference as no circulation rules are set" ); +my $expected_expirationdate = dt_from_string->add( { days => 7 } ); +my $expirationdate = $recall2->calc_expirationdate; +is( + t::lib::Dates::compare( $expirationdate, $expected_expirationdate ), 0, + "Expiration date calculated based on system preference as no circulation rules are set" +); -Koha::CirculationRules->set_rule({ - branchcode => undef, - categorycode => undef, - itemtype => undef, - rule_name => 'recall_shelf_time', - rule_value => '3', -}); -$expected_expirationdate = dt_from_string->add({ days => 3 }); -$expirationdate = $recall2->calc_expirationdate; -is( t::lib::Dates::compare( $expirationdate, $expected_expirationdate ), 0, "Expiration date calculated based on circulation rules" ); +Koha::CirculationRules->set_rule( + { + branchcode => undef, + categorycode => undef, + itemtype => undef, + rule_name => 'recall_shelf_time', + rule_value => '3', + } +); +$expected_expirationdate = dt_from_string->add( { days => 3 } ); +$expirationdate = $recall2->calc_expirationdate; +is( + t::lib::Dates::compare( $expirationdate, $expected_expirationdate ), 0, + "Expiration date calculated based on circulation rules" +); C4::Members::Messaging::SetMessagingPreference( { @@ -134,27 +155,29 @@ C4::Members::Messaging::SetMessagingPreference( } ); -$recall2->set_waiting({ expirationdate => $expirationdate }); +$recall2->set_waiting( { expirationdate => $expirationdate } ); is( $recall2->waiting, 1, "Recall is waiting" ); my $notice = C4::Message->find_last_message( $patron1->unblessed, 'PICKUP_RECALLED_ITEM', 'email' ); ok( defined $notice, "Patron was notified to pick up waiting recall" ); -$recall2->set_expired({ interface => 'COMMANDLINE' }); +$recall2->set_expired( { interface => 'COMMANDLINE' } ); is( $recall2->expired, 1, "Recall has expired" ); -my $old_recalls_count_now = Koha::Recalls->search({ completed => 1 })->count; +my $old_recalls_count_now = Koha::Recalls->search( { completed => 1 } )->count; is( $old_recalls_count_now, $old_recalls_count + 2, "Recalls have been flagged as old when cancelled or expired" ); -my $recall3 = Koha::Recall->new({ - patron_id => $patron1->borrowernumber, - created_date => dt_from_string, - biblio_id => $biblio1->biblionumber, - pickup_library_id => $branch1, - item_id => $item1->itemnumber, - expiration_date => undef, - item_level => 1 -})->store; +my $recall3 = Koha::Recall->new( + { + patron_id => $patron1->borrowernumber, + created_date => dt_from_string, + biblio_id => $biblio1->biblionumber, + pickup_library_id => $branch1, + item_id => $item1->itemnumber, + expiration_date => undef, + item_level => 1 + } +)->store; # test that recall gets T status $recall3->start_transfer; @@ -169,26 +192,28 @@ $recall3->set_fulfilled; ok( $recall3->fulfilled, "Recall has been fulfilled" ); C4::Circulation::AddIssue( $patron2, $item1->barcode ); -my $recall4 = Koha::Recall->new({ - patron_id => $patron1->borrowernumber, - created_date => dt_from_string, - biblio_id => $biblio1->biblionumber, - pickup_library_id => $branch1, - item_id => undef, - expiration_date => undef, - item_level => 0 -})->store; +my $recall4 = Koha::Recall->new( + { + patron_id => $patron1->borrowernumber, + created_date => dt_from_string, + biblio_id => $biblio1->biblionumber, + pickup_library_id => $branch1, + item_id => undef, + expiration_date => undef, + item_level => 0 + } +)->store; ok( !defined $recall4->item, "No relevant item returned for a biblio-level recall" ); -is( $recall4->checkout->itemnumber, $item1->itemnumber, "Return most relevant checkout for a biblio-level recall"); +is( $recall4->checkout->itemnumber, $item1->itemnumber, "Return most relevant checkout for a biblio-level recall" ); -$recall4->set_waiting({ item => $item1, expirationdate => $expirationdate }); +$recall4->set_waiting( { item => $item1, expirationdate => $expirationdate } ); is( $recall4->item_id, $item1->itemnumber, "Item has been allocated to biblio-level recall" ); $recall4->revert_waiting; ok( !defined $recall4->item_id, "Itemnumber has been removed from biblio-level recall when reverting waiting status" ); -$recall4->start_transfer({ item => $item1 }); +$recall4->start_transfer( { item => $item1 } ); is( $recall4->item_id, $item1->itemnumber, "Itemnumber saved to recall when item is transferred" ); $recall4->revert_transfer; ok( !defined $recall4->item_id, "Itemnumber has been removed from biblio-level recall when reverting transfer status" ); diff --git a/t/db_dependent/Koha/Recalls.t b/t/db_dependent/Koha/Recalls.t index dffc85f77f..05ffc0b47b 100755 --- a/t/db_dependent/Koha/Recalls.t +++ b/t/db_dependent/Koha/Recalls.t @@ -32,7 +32,7 @@ BEGIN { # Start transaction my $database = Koha::Database->new(); -my $schema = $database->schema(); +my $schema = $database->schema(); $schema->storage->txn_begin(); my $dbh = C4::Context->dbh; @@ -40,22 +40,26 @@ my $builder = t::lib::TestBuilder->new; # Setup test variables -my $item1 = $builder->build_sample_item(); -my $biblio1 = $item1->biblio; -my $branch1 = $item1->holdingbranch; +my $item1 = $builder->build_sample_item(); +my $biblio1 = $item1->biblio; +my $branch1 = $item1->holdingbranch; my $itemtype1 = $item1->effective_itemtype; -my $item2 = $builder->build_sample_item({ biblionumber => $biblio1->biblionumber }); -my $item3 = $builder->build_sample_item({ biblionumber => $biblio1->biblionumber }); -my $biblio2 = $item1->biblio; -my $branch2 = $item1->holdingbranch; +my $item2 = $builder->build_sample_item( { biblionumber => $biblio1->biblionumber } ); +my $item3 = $builder->build_sample_item( { biblionumber => $biblio1->biblionumber } ); +my $biblio2 = $item1->biblio; +my $branch2 = $item1->holdingbranch; my $itemtype2 = $item1->effective_itemtype; -my $category1 = $builder->build({ source => 'Category' })->{ categorycode }; -my $patron1 = $builder->build_object({ class => 'Koha::Patrons', value => { categorycode => $category1, branchcode => $branch1 } }); -my $patron2 = $builder->build_object({ class => 'Koha::Patrons', value => { categorycode => $category1, branchcode => $branch2 } }); -my $patron3 = $builder->build_object({ class => 'Koha::Patrons', value => { categorycode => $category1, branchcode => $branch1 } }); -my $patron4 = $builder->build_object({ class => 'Koha::Patrons', value => { categorycode => $category1, branchcode => $branch2 } }); -t::lib::Mocks::mock_userenv({ patron => $patron1 }); +my $category1 = $builder->build( { source => 'Category' } )->{categorycode}; +my $patron1 = $builder->build_object( + { class => 'Koha::Patrons', value => { categorycode => $category1, branchcode => $branch1 } } ); +my $patron2 = $builder->build_object( + { class => 'Koha::Patrons', value => { categorycode => $category1, branchcode => $branch2 } } ); +my $patron3 = $builder->build_object( + { class => 'Koha::Patrons', value => { categorycode => $category1, branchcode => $branch1 } } ); +my $patron4 = $builder->build_object( + { class => 'Koha::Patrons', value => { categorycode => $category1, branchcode => $branch2 } } ); +t::lib::Mocks::mock_userenv( { patron => $patron1 } ); Koha::CirculationRules->set_rules( { @@ -82,78 +86,92 @@ C4::Members::Messaging::SetMessagingPreference( } ); -my ( $recall, $due_interval, $due_date ) = Koha::Recalls->add_recall({ - patron => undef, - biblio => $biblio1, - branchcode => $branch1, - item => $item1, - expirationdate => undef, - interface => 'COMMANDLINE', -}); +my ( $recall, $due_interval, $due_date ) = Koha::Recalls->add_recall( + { + patron => undef, + biblio => $biblio1, + branchcode => $branch1, + item => $item1, + expirationdate => undef, + interface => 'COMMANDLINE', + } +); ok( !defined $recall, "Can't add a recall without specifying a patron" ); -( $recall, $due_interval, $due_date ) = Koha::Recalls->add_recall({ - patron => $patron1, - biblio => undef, - branchcode => $branch1, - item => $item1, - expirationdate => undef, - interface => 'COMMANDLINE', -}); +( $recall, $due_interval, $due_date ) = Koha::Recalls->add_recall( + { + patron => $patron1, + biblio => undef, + branchcode => $branch1, + item => $item1, + expirationdate => undef, + interface => 'COMMANDLINE', + } +); ok( !defined $recall, "Can't add a recall without specifying a biblio" ); -( $recall, $due_interval, $due_date ) = Koha::Recalls->add_recall({ - patron => $patron1, - biblio => undef, - branchcode => $branch1, - item => $item1, - expirationdate => undef, - interface => 'COMMANDLINE', -}); +( $recall, $due_interval, $due_date ) = Koha::Recalls->add_recall( + { + patron => $patron1, + biblio => undef, + branchcode => $branch1, + item => $item1, + expirationdate => undef, + interface => 'COMMANDLINE', + } +); ok( !defined $recall, "Can't add a recall without specifying a biblio" ); my $initial_checkout_due_date = Koha::Checkouts->find( $item2->checkout->issue_id )->date_due; -( $recall, $due_interval, $due_date ) = Koha::Recalls->add_recall({ - patron => $patron2, - biblio => $biblio1, - branchcode => undef, - item => $item2, - expirationdate => undef, - interface => 'COMMANDLINE', -}); +( $recall, $due_interval, $due_date ) = Koha::Recalls->add_recall( + { + patron => $patron2, + biblio => $biblio1, + branchcode => undef, + item => $item2, + expirationdate => undef, + interface => 'COMMANDLINE', + } +); my $checkout_due_date_after_recall = Koha::Checkouts->find( $item2->checkout->issue_id )->date_due; is( $recall->pickup_library_id, $branch2, "No pickup branch specified so patron branch used" ); -is( $due_interval, 5, "Recall due date interval defaults to 5 if not specified" ); +is( $due_interval, 5, "Recall due date interval defaults to 5 if not specified" ); ok( $checkout_due_date_after_recall lt $initial_checkout_due_date, "Checkout due date has been moved backwards" ); -Koha::CirculationRules->set_rule({ - branchcode => undef, - categorycode => undef, - itemtype => undef, - rule_name => 'recall_due_date_interval', - rule_value => 3, -}); -( $recall, $due_interval, $due_date ) = Koha::Recalls->add_recall({ - patron => $patron1, - biblio => $biblio1, - branchcode => undef, - item => $item1, - expirationdate => undef, - interface => 'COMMANDLINE', -}); +Koha::CirculationRules->set_rule( + { + branchcode => undef, + categorycode => undef, + itemtype => undef, + rule_name => 'recall_due_date_interval', + rule_value => 3, + } +); +( $recall, $due_interval, $due_date ) = Koha::Recalls->add_recall( + { + patron => $patron1, + biblio => $biblio1, + branchcode => undef, + item => $item1, + expirationdate => undef, + interface => 'COMMANDLINE', + } +); is( $due_interval, 3, "Recall due date interval is based on circulation rules" ); -( $recall, $due_interval, $due_date ) = Koha::Recalls->add_recall({ - patron => $patron1, - biblio => $biblio1, - branchcode => $branch1, - item => undef, - expirationdate => undef, - interface => 'COMMANDLINE', -}); +( $recall, $due_interval, $due_date ) = Koha::Recalls->add_recall( + { + patron => $patron1, + biblio => $biblio1, + branchcode => $branch1, + item => undef, + expirationdate => undef, + interface => 'COMMANDLINE', + } +); is( $recall->item_level, 0, "No item provided so recall not flagged as item-level" ); my $checkout_timestamp = dt_from_string( $recall->checkout->date_due ); @@ -194,36 +212,40 @@ ok( "Checkout due date has not been moved forward" ); -my $messages_count = Koha::Notice::Messages->search({ borrowernumber => $patron3->borrowernumber, letter_code => 'RETURN_RECALLED_ITEM' })->count; +my $messages_count = Koha::Notice::Messages->search( + { borrowernumber => $patron3->borrowernumber, letter_code => 'RETURN_RECALLED_ITEM' } )->count; is( $messages_count, 6, "RETURN_RECALLED_ITEM notice successfully sent to checkout borrower" ); my $message = Koha::Recalls->move_recall; is( $message, 'no recall_id provided', "Can't move a recall without specifying which recall" ); -$message = Koha::Recalls->move_recall({ recall_id => $recall->recall_id }); +$message = Koha::Recalls->move_recall( { recall_id => $recall->recall_id } ); is( $message, 'no action provided', "No clear action to perform on recall" ); -$message = Koha::Recalls->move_recall({ recall_id => $recall->recall_id, action => 'whatever' }); +$message = Koha::Recalls->move_recall( { recall_id => $recall->recall_id, action => 'whatever' } ); is( $message, 'no action provided', "Legal action not provided to perform on recall" ); -$recall->set_waiting({ item => $item1 }); +$recall->set_waiting( { item => $item1 } ); ok( $recall->waiting, "Recall is waiting" ); -Koha::Recalls->move_recall({ recall_id => $recall->recall_id, action => 'revert' }); +Koha::Recalls->move_recall( { recall_id => $recall->recall_id, action => 'revert' } ); $recall = Koha::Recalls->find( $recall->recall_id ); ok( $recall->requested, "Recall reverted to requested with move_recall" ); -Koha::Recalls->move_recall({ recall_id => $recall->recall_id, action => 'cancel' }); +Koha::Recalls->move_recall( { recall_id => $recall->recall_id, action => 'cancel' } ); $recall = Koha::Recalls->find( $recall->recall_id ); ok( $recall->cancelled, "Recall cancelled with move_recall" ); -( $recall, $due_interval, $due_date ) = Koha::Recalls->add_recall({ - patron => $patron1, - biblio => $biblio1, - branchcode => $branch1, - item => $item2, - expirationdate => undef, - interface => 'COMMANDLINE', -}); -$message = Koha::Recalls->move_recall({ recall_id => $recall->recall_id, item => $item2, borrowernumber => $patron1->borrowernumber }); +( $recall, $due_interval, $due_date ) = Koha::Recalls->add_recall( + { + patron => $patron1, + biblio => $biblio1, + branchcode => $branch1, + item => $item2, + expirationdate => undef, + interface => 'COMMANDLINE', + } +); +$message = Koha::Recalls->move_recall( + { recall_id => $recall->recall_id, item => $item2, borrowernumber => $patron1->borrowernumber } ); $recall = Koha::Recalls->find( $recall->recall_id ); ok( $recall->fulfilled, "Recall fulfilled with move_recall" ); @@ -255,7 +277,7 @@ subtest 'filter_by_current() and filter_by_finished() tests' => sub { $fulfilled->id, ] }, - { order_by => [ 'recall_id' ] } + { order_by => ['recall_id'] } ); is( $recalls->count, 7, 'Resultset count is correct' ); @@ -263,17 +285,17 @@ subtest 'filter_by_current() and filter_by_finished() tests' => sub { my $current_recalls = $recalls->filter_by_current; is( $current_recalls->count, 4, 'Current recalls count correct' ); - is( $current_recalls->next->status, 'in_transit', 'Resultset correctly includes in_transit recall'); - is( $current_recalls->next->status, 'overdue', 'Resultset correctly includes overdue recall'); - is( $current_recalls->next->status, 'requested', 'Resultset correctly includes requested recall'); - is( $current_recalls->next->status, 'waiting', 'Resultset correctly includes waiting recall'); + is( $current_recalls->next->status, 'in_transit', 'Resultset correctly includes in_transit recall' ); + is( $current_recalls->next->status, 'overdue', 'Resultset correctly includes overdue recall' ); + is( $current_recalls->next->status, 'requested', 'Resultset correctly includes requested recall' ); + is( $current_recalls->next->status, 'waiting', 'Resultset correctly includes waiting recall' ); my $finished_recalls = $recalls->filter_by_finished; is( $finished_recalls->count, 3, 'Finished recalls count correct' ); - is( $finished_recalls->next->status, 'cancelled', 'Resultset correctly includes cancelled recall'); - is( $finished_recalls->next->status, 'expired', 'Resultset correctly includes expired recall'); - is( $finished_recalls->next->status, 'fulfilled', 'Resultset correctly includes fulfilled recall'); + is( $finished_recalls->next->status, 'cancelled', 'Resultset correctly includes cancelled recall' ); + is( $finished_recalls->next->status, 'expired', 'Resultset correctly includes expired recall' ); + is( $finished_recalls->next->status, 'fulfilled', 'Resultset correctly includes fulfilled recall' ); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/Koha/Reports.t b/t/db_dependent/Koha/Reports.t index 19bee5bd27..ce9b80b73f 100755 --- a/t/db_dependent/Koha/Reports.t +++ b/t/db_dependent/Koha/Reports.t @@ -29,22 +29,29 @@ use t::lib::TestBuilder; my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; -my $builder = t::lib::TestBuilder->new; +my $builder = t::lib::TestBuilder->new; my $nb_of_reports = Koha::Reports->search->count; -my $new_report_1 = Koha::Report->new({ - report_name => 'report_name_for_test_1', - savedsql => 'SELECT "I wrote a report"', -})->store; -my $new_report_2 = Koha::Report->new({ - report_name => 'report_name_for_test_1', - savedsql => 'SELECT "Oops, I did it again"', -})->store; +my $new_report_1 = Koha::Report->new( + { + report_name => 'report_name_for_test_1', + savedsql => 'SELECT "I wrote a report"', + } +)->store; +my $new_report_2 = Koha::Report->new( + { + report_name => 'report_name_for_test_1', + savedsql => 'SELECT "Oops, I did it again"', + } +)->store; -like( $new_report_1->id, qr|^\d+$|, 'Adding a new report should have set the id'); +like( $new_report_1->id, qr|^\d+$|, 'Adding a new report should have set the id' ); is( Koha::Reports->search->count, $nb_of_reports + 2, 'The 2 reports should have been added' ); my $retrieved_report_1 = Koha::Reports->find( $new_report_1->id ); -is( $retrieved_report_1->report_name, $new_report_1->report_name, 'Find a report by id should return the correct report' ); +is( + $retrieved_report_1->report_name, $new_report_1->report_name, + 'Find a report by id should return the correct report' +); $retrieved_report_1->delete; is( Koha::Reports->search->count, $nb_of_reports + 1, 'Delete should have deleted the report' ); @@ -52,22 +59,35 @@ is( Koha::Reports->search->count, $nb_of_reports + 1, 'Delete should have delete subtest 'prep_report' => sub { plan tests => 4; - my $report = Koha::Report->new({ - report_name => 'report_name_for_test_1', - savedsql => 'SELECT * FROM items WHERE itemnumber IN <<Test|list>>', - })->store; + my $report = Koha::Report->new( + { + report_name => 'report_name_for_test_1', + savedsql => 'SELECT * FROM items WHERE itemnumber IN <<Test|list>>', + } + )->store; my $id = $report->id; - my ($sql, undef) = $report->prep_report( ['Test|list'],["1\n12\n\r243"] ); - is( $sql, qq{SELECT * FROM items WHERE itemnumber IN ('1','12','243') /* saved_sql.id: $id */},'Expected sql generated correctly with single param and name'); + my ( $sql, undef ) = $report->prep_report( ['Test|list'], ["1\n12\n\r243"] ); + is( + $sql, qq{SELECT * FROM items WHERE itemnumber IN ('1','12','243') /* saved_sql.id: $id */}, + 'Expected sql generated correctly with single param and name' + ); $report->savedsql('SELECT * FROM items WHERE itemnumber IN <<Test|list>> AND <<Another>> AND <<Test|list>>')->store; - ($sql, undef) = $report->prep_report( ['Test|list','Another'],["1\n12\n\r243",'the other'] ); - is( $sql, qq{SELECT * FROM items WHERE itemnumber IN ('1','12','243') AND 'the other' AND ('1','12','243') /* saved_sql.id: $id */},'Expected sql generated correctly with multiple params and names'); + ( $sql, undef ) = $report->prep_report( [ 'Test|list', 'Another' ], [ "1\n12\n\r243", 'the other' ] ); + is( + $sql, + qq{SELECT * FROM items WHERE itemnumber IN ('1','12','243') AND 'the other' AND ('1','12','243') /* saved_sql.id: $id */}, + 'Expected sql generated correctly with multiple params and names' + ); - ($sql, undef) = $report->prep_report( [],["1\n12\n\r243",'the other'] ); - is( $sql, qq{SELECT * FROM items WHERE itemnumber IN ('1','12','243') AND 'the other' AND ('1','12','243') /* saved_sql.id: $id */},'Expected sql generated correctly with multiple params and no names'); + ( $sql, undef ) = $report->prep_report( [], [ "1\n12\n\r243", 'the other' ] ); + is( + $sql, + qq{SELECT * FROM items WHERE itemnumber IN ('1','12','243') AND 'the other' AND ('1','12','243') /* saved_sql.id: $id */}, + 'Expected sql generated correctly with multiple params and no names' + ); $report->savedsql( q{SELECT i.itemnumber, i.itemnumber as Exemplarnummber, [[i.itemnumber| itemnumber for batch]] FROM items}) @@ -97,19 +117,12 @@ subtest 'is_sql_valid' => sub { ); foreach my $word (@badwords) { is_deeply( - [ - Koha::Report->new( - { savedsql => 'select FOO;' . $word . ' BAR' } - )->is_sql_valid - ], + [ Koha::Report->new( { savedsql => 'select FOO;' . $word . ' BAR' } )->is_sql_valid ], [ 0, [ { sqlerr => $word } ] ], 'select FOO with ' . $word . ' BAR' ); is_deeply( - [ - Koha::Report->new( { savedsql => $word . ' qux' } ) - ->is_sql_valid - ], + [ Koha::Report->new( { savedsql => $word . ' qux' } )->is_sql_valid ], [ 0, [ { sqlerr => $word } ] ], $word . ' qux' ); diff --git a/t/db_dependent/Koha/Reviews.t b/t/db_dependent/Koha/Reviews.t index 0c8dcdc9c4..8fcc07dbad 100755 --- a/t/db_dependent/Koha/Reviews.t +++ b/t/db_dependent/Koha/Reviews.t @@ -31,52 +31,70 @@ use t::lib::Mocks; my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; -my $builder = t::lib::TestBuilder->new; -my $patron_1 = $builder->build({ source => 'Borrower', value => { flags => undef } }); -my $patron_2 = $builder->build({ source => 'Borrower' }); +my $builder = t::lib::TestBuilder->new; +my $patron_1 = $builder->build( { source => 'Borrower', value => { flags => undef } } ); +my $patron_2 = $builder->build( { source => 'Borrower' } ); $patron_1 = Koha::Patrons->find( $patron_1->{borrowernumber} ); $patron_2 = Koha::Patrons->find( $patron_2->{borrowernumber} ); -my $biblio_1 = $builder->build_sample_biblio; -my $biblio_2 = $builder->build_sample_biblio; -my $nb_of_reviews = Koha::Reviews->search->count; -my $nb_of_approved_reviews = Koha::Reviews->search({ approved => 1 })->count; -my $new_review_1_1 = Koha::Review->new({ - borrowernumber => $patron_1->borrowernumber, - biblionumber => $biblio_1->biblionumber, - review => 'a kind review', -})->store; -my $new_review_1_2 = Koha::Review->new({ - borrowernumber => $patron_1->borrowernumber, - biblionumber => $biblio_2->biblionumber, - review => 'anoter kind review', -})->store; -my $new_review_2_1 = Koha::Review->new({ - borrowernumber => $patron_2->borrowernumber, - biblionumber => $biblio_1->biblionumber, - review => 'just anoter review', -})->store; +my $biblio_1 = $builder->build_sample_biblio; +my $biblio_2 = $builder->build_sample_biblio; +my $nb_of_reviews = Koha::Reviews->search->count; +my $nb_of_approved_reviews = Koha::Reviews->search( { approved => 1 } )->count; +my $new_review_1_1 = Koha::Review->new( + { + borrowernumber => $patron_1->borrowernumber, + biblionumber => $biblio_1->biblionumber, + review => 'a kind review', + } +)->store; +my $new_review_1_2 = Koha::Review->new( + { + borrowernumber => $patron_1->borrowernumber, + biblionumber => $biblio_2->biblionumber, + review => 'anoter kind review', + } +)->store; +my $new_review_2_1 = Koha::Review->new( + { + borrowernumber => $patron_2->borrowernumber, + biblionumber => $biblio_1->biblionumber, + review => 'just anoter review', + } +)->store; -like( $new_review_1_1->reviewid, qr|^\d+$|, 'Adding a new review should have set the reviewid'); +like( $new_review_1_1->reviewid, qr|^\d+$|, 'Adding a new review should have set the reviewid' ); is( Koha::Reviews->search->count, $nb_of_reviews + 3, 'The 3 reviews should have been added' ); -is( Koha::Reviews->search({approved => 1})->count, $nb_of_approved_reviews, 'There should not be new approved reviews' ); +is( + Koha::Reviews->search( { approved => 1 } )->count, $nb_of_approved_reviews, + 'There should not be new approved reviews' +); $new_review_1_1->approve; -is( Koha::Reviews->search({approved => 1})->count, $nb_of_approved_reviews + 1, 'There should be 1 new approved review' ); +is( + Koha::Reviews->search( { approved => 1 } )->count, $nb_of_approved_reviews + 1, + 'There should be 1 new approved review' +); $new_review_1_1->unapprove; -is( Koha::Reviews->search({approved => 1})->count, $nb_of_approved_reviews, 'There should not be any new approved review anymore' ); +is( + Koha::Reviews->search( { approved => 1 } )->count, $nb_of_approved_reviews, + 'There should not be any new approved review anymore' +); my $retrieved_review_1_1 = Koha::Reviews->find( $new_review_1_1->reviewid ); is( $retrieved_review_1_1->review, $new_review_1_1->review, 'Find a review by id should return the correct review' ); subtest 'search_limited' => sub { plan tests => 2; - my $group_1 = Koha::Library::Group->new( { title => 'TEST Group 1', ft_hide_patron_info => 1 } )->store; - my $group_2 = Koha::Library::Group->new( { title => 'TEST Group 2', ft_hide_patron_info => 1 } )->store; - Koha::Library::Group->new({ parent_id => $group_1->id, branchcode => $patron_1->branchcode })->store(); - Koha::Library::Group->new({ parent_id => $group_2->id, branchcode => $patron_2->branchcode })->store(); + my $group_1 = Koha::Library::Group->new( { title => 'TEST Group 1', ft_hide_patron_info => 1 } )->store; + my $group_2 = Koha::Library::Group->new( { title => 'TEST Group 2', ft_hide_patron_info => 1 } )->store; + Koha::Library::Group->new( { parent_id => $group_1->id, branchcode => $patron_1->branchcode } )->store(); + Koha::Library::Group->new( { parent_id => $group_2->id, branchcode => $patron_2->branchcode } )->store(); t::lib::Mocks::mock_userenv( { patron => $patron_1 } ); is( Koha::Reviews->search->count, $nb_of_approved_reviews + 3, 'Koha::Reviews->search should return all reviews' ); - is( Koha::Reviews->search_limited->count, $nb_of_approved_reviews + 2, 'Koha::Reviews->search_limited should return reviews depending on patron permissions' ); + is( + Koha::Reviews->search_limited->count, $nb_of_approved_reviews + 2, + 'Koha::Reviews->search_limited should return reviews depending on patron permissions' + ); }; $retrieved_review_1_1->delete; diff --git a/t/db_dependent/Koha/SMS_Providers.t b/t/db_dependent/Koha/SMS_Providers.t index a469d77649..7834ee4cf8 100755 --- a/t/db_dependent/Koha/SMS_Providers.t +++ b/t/db_dependent/Koha/SMS_Providers.t @@ -32,13 +32,9 @@ $schema->storage->txn_begin; my $count = Koha::SMS::Providers->search->count; -my $builder = t::lib::TestBuilder->new; -my $provider1 = - Koha::SMS::Provider->new( { name => 'Test 1', domain => 'test1.com' } ) - ->store(); -my $provider2 = - Koha::SMS::Provider->new( { name => 'Test 2', domain => 'test2.com' } ) - ->store(); +my $builder = t::lib::TestBuilder->new; +my $provider1 = Koha::SMS::Provider->new( { name => 'Test 1', domain => 'test1.com' } )->store(); +my $provider2 = Koha::SMS::Provider->new( { name => 'Test 2', domain => 'test2.com' } )->store(); my $patron1 = $builder->build( { @@ -54,21 +50,29 @@ my $patron2 = $builder->build( } ); -like( $provider1->id, qr|^\d+$|, - 'Adding a new provider should have set the id' ); -is( Koha::SMS::Providers->search->count, - $count + 2, 'The 2 providers should have been added' ); +like( + $provider1->id, qr|^\d+$|, + 'Adding a new provider should have set the id' +); +is( + Koha::SMS::Providers->search->count, + $count + 2, 'The 2 providers should have been added' +); -is ( $provider1->patrons_using(), 2, 'Found the correct number of patrons using provider' ); -is ( $provider2->patrons_using(), 0, 'Found the correct number of patrons using unused provider' ); +is( $provider1->patrons_using(), 2, 'Found the correct number of patrons using provider' ); +is( $provider2->patrons_using(), 0, 'Found the correct number of patrons using unused provider' ); my $provider = Koha::SMS::Providers->find( $provider1->id ); -is( $provider->name, $provider1->name, - 'Find a provider by id should return the correct provider' ); +is( + $provider->name, $provider1->name, + 'Find a provider by id should return the correct provider' +); $provider1->delete; -is( Koha::SMS::Providers->search->count, - $count + 1, 'Delete should have deleted the provider' ); +is( + Koha::SMS::Providers->search->count, + $count + 1, 'Delete should have deleted the provider' +); $schema->storage->txn_rollback; diff --git a/t/db_dependent/Koha/SMTP/Server.t b/t/db_dependent/Koha/SMTP/Server.t index bb84b8da6a..bd7ddeb851 100755 --- a/t/db_dependent/Koha/SMTP/Server.t +++ b/t/db_dependent/Koha/SMTP/Server.t @@ -45,16 +45,16 @@ subtest 'transport() tests' => sub { my $transport = $server->transport; is( ref($transport), 'Email::Sender::Transport::SMTP::Persistent', 'Type is correct' ); - is( $transport->ssl, 0, 'SSL is not set' ); + is( $transport->ssl, 0, 'SSL is not set' ); - $server->set({ ssl_mode => '1' })->store; + $server->set( { ssl_mode => '1' } )->store; $transport = $server->transport; - is( ref($transport), 'Email::Sender::Transport::SMTP::Persistent', 'Type is correct' ); - is( $transport->ssl, '1', 'SSL is set' ); - is( $transport->debug, '0', 'Debug setting honoured (disabled)' ); + is( ref($transport), 'Email::Sender::Transport::SMTP::Persistent', 'Type is correct' ); + is( $transport->ssl, '1', 'SSL is set' ); + is( $transport->debug, '0', 'Debug setting honoured (disabled)' ); - $server->set({ debug => 1 })->store; + $server->set( { debug => 1 } )->store; $transport = $server->transport; is( $transport->debug, '1', 'Debug setting honoured (enabled)' ); @@ -99,7 +99,7 @@ subtest 'to_api() tests' => sub { $schema->storage->txn_begin; - my $smtp_server = $builder->build_object({ class => 'Koha::SMTP::Servers' }); + my $smtp_server = $builder->build_object( { class => 'Koha::SMTP::Servers' } ); ok( !exists $smtp_server->to_api->{password}, 'Password is not part of the API representation' ); $schema->storage->txn_rollback; @@ -113,12 +113,9 @@ subtest 'store() tests' => sub { Koha::SMTP::Servers->search->delete; - my $server_1 = $builder->build_object( - { class => 'Koha::SMTP::Servers', value => { is_default => 0 } } ); - my $server_2 = $builder->build_object( - { class => 'Koha::SMTP::Servers', value => { is_default => 0 } } ); - my $server_3 = $builder->build_object( - { class => 'Koha::SMTP::Servers', value => { is_default => 1 } } ); + my $server_1 = $builder->build_object( { class => 'Koha::SMTP::Servers', value => { is_default => 0 } } ); + my $server_2 = $builder->build_object( { class => 'Koha::SMTP::Servers', value => { is_default => 0 } } ); + my $server_3 = $builder->build_object( { class => 'Koha::SMTP::Servers', value => { is_default => 1 } } ); my $default_servers = Koha::SMTP::Servers->search( { is_default => 1 } ); diff --git a/t/db_dependent/Koha/SMTP/Servers.t b/t/db_dependent/Koha/SMTP/Servers.t index b3506b76b1..195ebd0f3b 100755 --- a/t/db_dependent/Koha/SMTP/Servers.t +++ b/t/db_dependent/Koha/SMTP/Servers.t @@ -35,12 +35,16 @@ subtest 'get_default() tests' => sub { t::lib::Mocks::mock_config( 'smtp_server', undef ); - my $server = Koha::SMTP::Servers->get_default; - is( ref($server), 'Koha::SMTP::Server', - 'An object of the right type is returned' ); + my $server = Koha::SMTP::Servers->get_default; + is( + ref($server), 'Koha::SMTP::Server', + 'An object of the right type is returned' + ); - ok( !$server->in_storage, - 'The default server is correctly retrieved' ); + ok( + !$server->in_storage, + 'The default server is correctly retrieved' + ); my $unblessed_server = $server->unblessed; delete $unblessed_server->{id}; @@ -66,8 +70,10 @@ subtest 'get_default() tests' => sub { my $smtp_config = C4::Context->config('smtp_server'); $server = Koha::SMTP::Servers->get_default; - is( ref($server), 'Koha::SMTP::Server', - 'An object of the right type is returned' ); + is( + ref($server), 'Koha::SMTP::Server', + 'An object of the right type is returned' + ); $unblessed_server = $server->unblessed; delete $unblessed_server->{id}; diff --git a/t/db_dependent/Koha/SearchEngine/Elasticsearch.t b/t/db_dependent/Koha/SearchEngine/Elasticsearch.t index 3df796fb36..2b46b66d3a 100755 --- a/t/db_dependent/Koha/SearchEngine/Elasticsearch.t +++ b/t/db_dependent/Koha/SearchEngine/Elasticsearch.t @@ -51,7 +51,7 @@ subtest '_read_configuration() tests' => sub { $configuration = Koha::SearchEngine::Elasticsearch::_read_configuration; } 'Koha::Exceptions::Config::MissingEntry', - 'Configuration problem, exception thrown'; + 'Configuration problem, exception thrown'; is( $@->message, "Missing <elasticsearch> entry in koha-conf.xml", @@ -64,7 +64,7 @@ subtest '_read_configuration() tests' => sub { $configuration = Koha::SearchEngine::Elasticsearch::_read_configuration; } 'Koha::Exceptions::Config::MissingEntry', - 'Configuration problem, exception thrown'; + 'Configuration problem, exception thrown'; is( $@->message, "Missing <elasticsearch>/<server> entry in koha-conf.xml", @@ -77,7 +77,7 @@ subtest '_read_configuration() tests' => sub { $configuration = Koha::SearchEngine::Elasticsearch::_read_configuration; } 'Koha::Exceptions::Config::MissingEntry', - 'Configuration problem, exception thrown'; + 'Configuration problem, exception thrown'; is( $@->message, "Missing <elasticsearch>/<index_name> entry in koha-conf.xml", @@ -85,20 +85,20 @@ subtest '_read_configuration() tests' => sub { ); # Correct configuration, only one server - t::lib::Mocks::mock_config( 'elasticsearch', { server => 'a_server', index_name => 'index' } ); + t::lib::Mocks::mock_config( 'elasticsearch', { server => 'a_server', index_name => 'index' } ); $configuration = Koha::SearchEngine::Elasticsearch::_read_configuration; is( $configuration->{index_name}, 'index', 'Index configuration parsed correctly' ); is_deeply( $configuration->{nodes}, ['a_server'], 'Server configuration parsed correctly' ); # Correct configuration, two servers - my @servers = ('a_server', 'another_server'); + my @servers = ( 'a_server', 'another_server' ); t::lib::Mocks::mock_config( 'elasticsearch', { server => \@servers, index_name => 'index' } ); $configuration = Koha::SearchEngine::Elasticsearch::_read_configuration; - is( $configuration->{index_name}, 'index', 'Index configuration parsed correctly' ); - is( $configuration->{cxn_pool}, 'Static', 'cxn_pool configuration set correctly to Static if not specified' ); - is_deeply( $configuration->{nodes}, \@servers , 'Server configuration parsed correctly' ); + is( $configuration->{index_name}, 'index', 'Index configuration parsed correctly' ); + is( $configuration->{cxn_pool}, 'Static', 'cxn_pool configuration set correctly to Static if not specified' ); + is_deeply( $configuration->{nodes}, \@servers, 'Server configuration parsed correctly' ); t::lib::Mocks::mock_config( 'elasticsearch', { server => \@servers, index_name => 'index', cxn_pool => 'Sniff' } ); @@ -107,13 +107,22 @@ subtest '_read_configuration() tests' => sub { isnt( defined $configuration->{trace_to}, 'trace_to is not defined if not set' ); my $params = Koha::SearchEngine::Elasticsearch::get_elasticsearch_params; - is_deeply( $configuration->{nodes}, \@servers , 'get_elasticsearch_params is just a wrapper for _read_configuration' ); + is_deeply( + $configuration->{nodes}, \@servers, + 'get_elasticsearch_params is just a wrapper for _read_configuration' + ); - t::lib::Mocks::mock_config( 'elasticsearch', { server => \@servers, index_name => 'index', cxn_pool => 'Sniff', trace_to => 'Stderr', request_timeout => 42 } ); + t::lib::Mocks::mock_config( + 'elasticsearch', + { + server => \@servers, index_name => 'index', cxn_pool => 'Sniff', trace_to => 'Stderr', + request_timeout => 42 + } + ); $configuration = Koha::SearchEngine::Elasticsearch::_read_configuration; - is( $configuration->{trace_to}, 'Stderr', 'trace_to configuration parsed correctly' ); - is( $configuration->{request_timeout}, '42', 'additional configuration (request_timeout) parsed correctly' ); + is( $configuration->{trace_to}, 'Stderr', 'trace_to configuration parsed correctly' ); + is( $configuration->{request_timeout}, '42', 'additional configuration (request_timeout) parsed correctly' ); }; subtest 'get_elasticsearch_settings() tests' => sub { @@ -123,9 +132,12 @@ subtest 'get_elasticsearch_settings() tests' => sub { my $settings; # test reading index settings - my $es = Koha::SearchEngine::Elasticsearch->new( {index => $Koha::SearchEngine::Elasticsearch::BIBLIOS_INDEX} ); + my $es = Koha::SearchEngine::Elasticsearch->new( { index => $Koha::SearchEngine::Elasticsearch::BIBLIOS_INDEX } ); $settings = $es->get_elasticsearch_settings(); - is( $settings->{index}{analysis}{analyzer}{analyzer_phrase}{tokenizer}, 'keyword', 'Index settings parsed correctly' ); + is( + $settings->{index}{analysis}{analyzer}{analyzer_phrase}{tokenizer}, 'keyword', + 'Index settings parsed correctly' + ); }; subtest 'get_elasticsearch_mappings() tests' => sub { @@ -136,14 +148,14 @@ subtest 'get_elasticsearch_mappings() tests' => sub { my @mappings = ( { - name => 'cn-sort', - type => 'callnumber', - facet => 0, + name => 'cn-sort', + type => 'callnumber', + facet => 0, suggestible => 0, - searchable => 1, - sort => 1, - marc_type => 'marc21', - marc_field => '001', + searchable => 1, + sort => 1, + marc_type => 'marc21', + marc_field => '001', }, { name => 'isbn', @@ -158,29 +170,39 @@ subtest 'get_elasticsearch_mappings() tests' => sub { }, ); my $search_engine_module = Test::MockModule->new('Koha::SearchEngine::Elasticsearch'); - $search_engine_module->mock('_foreach_mapping', sub { - my ($self, $sub) = @_; + $search_engine_module->mock( + '_foreach_mapping', + sub { + my ( $self, $sub ) = @_; - foreach my $map (@mappings) { - $sub->( - $map->{name}, - $map->{type}, - $map->{facet}, - $map->{suggestible}, - $map->{sort}, - $map->{searchable}, - $map->{filter}, - $map->{marc_type}, - $map->{marc_field} - ); + foreach my $map (@mappings) { + $sub->( + $map->{name}, + $map->{type}, + $map->{facet}, + $map->{suggestible}, + $map->{sort}, + $map->{searchable}, + $map->{filter}, + $map->{marc_type}, + $map->{marc_field} + ); + } } - }); + ); - my $search_engine_elasticsearch = Koha::SearchEngine::Elasticsearch::Search->new({ index => $Koha::SearchEngine::Elasticsearch::BIBLIOS_INDEX }); + my $search_engine_elasticsearch = Koha::SearchEngine::Elasticsearch::Search->new( + { index => $Koha::SearchEngine::Elasticsearch::BIBLIOS_INDEX } ); $mappings = $search_engine_elasticsearch->get_elasticsearch_mappings(); - is( $mappings->{properties}{"cn-sort__sort"}{index}, 'false', 'Field mappings parsed correctly for sort for callnumber type' ); - is( $mappings->{properties}{"cn-sort__sort"}{numeric}, 'false', 'Field mappings parsed correctly for sort for callnumber type' ); + is( + $mappings->{properties}{"cn-sort__sort"}{index}, 'false', + 'Field mappings parsed correctly for sort for callnumber type' + ); + is( + $mappings->{properties}{"cn-sort__sort"}{numeric}, 'false', + 'Field mappings parsed correctly for sort for callnumber type' + ); is( $mappings->{properties}{isbn__sort}{index}, 'false', 'Field mappings parsed correctly' ); }; @@ -189,59 +211,59 @@ subtest 'Koha::SearchEngine::Elasticsearch::marc_records_to_documents () tests' plan tests => 70; - t::lib::Mocks::mock_preference('marcflavour', 'MARC21'); - t::lib::Mocks::mock_preference('ElasticsearchMARCFormat', 'ISO2709'); + t::lib::Mocks::mock_preference( 'marcflavour', 'MARC21' ); + t::lib::Mocks::mock_preference( 'ElasticsearchMARCFormat', 'ISO2709' ); my @mappings = ( { - name => 'control_number', - type => 'string', - facet => 0, + name => 'control_number', + type => 'string', + facet => 0, suggestible => 0, - searchable => 1, - sort => undef, - marc_type => 'marc21', - marc_field => '001', + searchable => 1, + sort => undef, + marc_type => 'marc21', + marc_field => '001', }, { - name => 'isbn', - type => 'isbn', - facet => 0, + name => 'isbn', + type => 'isbn', + facet => 0, suggestible => 0, - searchable => 1, - sort => 0, - marc_type => 'marc21', - marc_field => '020a', + searchable => 1, + sort => 0, + marc_type => 'marc21', + marc_field => '020a', }, { - name => 'author', - type => 'string', - facet => 1, + name => 'author', + type => 'string', + facet => 1, suggestible => 1, - searchable => 1, - sort => undef, - marc_type => 'marc21', - marc_field => '100a', + searchable => 1, + sort => undef, + marc_type => 'marc21', + marc_field => '100a', }, { - name => 'author', - type => 'string', - facet => 1, + name => 'author', + type => 'string', + facet => 1, suggestible => 1, - searchable => 1, - sort => 1, - marc_type => 'marc21', - marc_field => '110a', + searchable => 1, + sort => 1, + marc_type => 'marc21', + marc_field => '110a', }, { - name => 'title', - type => 'string', - facet => 0, + name => 'title', + type => 'string', + facet => 0, suggestible => 1, - searchable => 1, - sort => 1, - marc_type => 'marc21', - marc_field => '245(ab)ab', + searchable => 1, + sort => 1, + marc_type => 'marc21', + marc_field => '245(ab)ab', }, { name => 'title-no-punctuation', @@ -255,144 +277,144 @@ subtest 'Koha::SearchEngine::Elasticsearch::marc_records_to_documents () tests' marc_field => '245(ab)ab', }, { - name => 'unimarc_title', - type => 'string', - facet => 0, + name => 'unimarc_title', + type => 'string', + facet => 0, suggestible => 1, - searchable => 1, - sort => 1, - marc_type => 'unimarc', - marc_field => '245a', + searchable => 1, + sort => 1, + marc_type => 'unimarc', + marc_field => '245a', }, { - name => 'title', - type => 'string', - facet => 0, + name => 'title', + type => 'string', + facet => 0, suggestible => undef, - searchable => 1, - sort => 0, - marc_type => 'marc21', - marc_field => '220', + searchable => 1, + sort => 0, + marc_type => 'marc21', + marc_field => '220', }, { - name => 'uniform_title', - type => 'string', - facet => 0, + name => 'uniform_title', + type => 'string', + facet => 0, suggestible => 0, - searchable => 1, - sort => 1, - marc_type => 'marc21', - marc_field => '240a', + searchable => 1, + sort => 1, + marc_type => 'marc21', + marc_field => '240a', }, { - name => 'title_wildcard', - type => 'string', - facet => 0, + name => 'title_wildcard', + type => 'string', + facet => 0, suggestible => 0, - searchable => 1, - sort => undef, - marc_type => 'marc21', - marc_field => '245', + searchable => 1, + sort => undef, + marc_type => 'marc21', + marc_field => '245', }, { - name => 'sum_item_price', - type => 'sum', - facet => 0, + name => 'sum_item_price', + type => 'sum', + facet => 0, suggestible => 0, - searchable => 1, - sort => 0, - marc_type => 'marc21', - marc_field => '952g', + searchable => 1, + sort => 0, + marc_type => 'marc21', + marc_field => '952g', }, { - name => 'items_withdrawn_status', - type => 'boolean', - facet => 0, + name => 'items_withdrawn_status', + type => 'boolean', + facet => 0, suggestible => 0, - searchable => 1, - sort => 0, - marc_type => 'marc21', - marc_field => '9520', + searchable => 1, + sort => 0, + marc_type => 'marc21', + marc_field => '9520', }, { - name => 'local_classification', - type => 'string', - facet => 0, + name => 'local_classification', + type => 'string', + facet => 0, suggestible => 0, - searchable => 1, - sort => 1, - marc_type => 'marc21', - marc_field => '952o', + searchable => 1, + sort => 1, + marc_type => 'marc21', + marc_field => '952o', }, { - name => 'type_of_record', - type => 'string', - facet => 0, + name => 'type_of_record', + type => 'string', + facet => 0, suggestible => 0, - searchable => 1, - sort => 0, - marc_type => 'marc21', - marc_field => 'leader_/6', + searchable => 1, + sort => 0, + marc_type => 'marc21', + marc_field => 'leader_/6', }, { - name => 'type_of_record_and_bib_level', - type => 'string', - facet => 0, + name => 'type_of_record_and_bib_level', + type => 'string', + facet => 0, suggestible => 0, - searchable => 1, - sort => 0, - marc_type => 'marc21', - marc_field => 'leader_/6-7', + searchable => 1, + sort => 0, + marc_type => 'marc21', + marc_field => 'leader_/6-7', }, { - name => 'ff7-00', - type => 'string', - facet => 0, + name => 'ff7-00', + type => 'string', + facet => 0, suggestible => 0, - searchable => 1, - sort => 0, - marc_type => 'marc21', - marc_field => '007_/0', + searchable => 1, + sort => 0, + marc_type => 'marc21', + marc_field => '007_/0', }, { - name => 'issues', - type => 'sum', - facet => 0, + name => 'issues', + type => 'sum', + facet => 0, suggestible => 0, - searchable => 1, - sort => 1, - marc_type => 'marc21', - marc_field => '952l', - }, - { - name => 'copydate', - type => 'year', - facet => 0, - suggestible => 0, - searchable => 1, - sort => 1, - marc_type => 'marc21', - marc_field => '260c', - }, - { - name => 'date-of-publication', - type => 'year', - facet => 0, - suggestible => 0, - searchable => 1, - sort => 1, - marc_type => 'marc21', - marc_field => '008_/7-10', + searchable => 1, + sort => 1, + marc_type => 'marc21', + marc_field => '952l', }, { - name => 'subject', - type => 'string', - facet => 0, + name => 'copydate', + type => 'year', + facet => 0, suggestible => 0, - searchable => 1, - sort => 1, - marc_type => 'marc21', - marc_field => '650(avxyz)', + searchable => 1, + sort => 1, + marc_type => 'marc21', + marc_field => '260c', + }, + { + name => 'date-of-publication', + type => 'year', + facet => 0, + suggestible => 0, + searchable => 1, + sort => 1, + marc_type => 'marc21', + marc_field => '008_/7-10', + }, + { + name => 'subject', + type => 'string', + facet => 0, + suggestible => 0, + searchable => 1, + sort => 1, + marc_type => 'marc21', + marc_field => '650(avxyz)', }, { name => 'note', @@ -407,111 +429,130 @@ subtest 'Koha::SearchEngine::Elasticsearch::marc_records_to_documents () tests' ); my $se = Test::MockModule->new('Koha::SearchEngine::Elasticsearch'); - $se->mock('_foreach_mapping', sub { - my ($self, $sub) = @_; + $se->mock( + '_foreach_mapping', + sub { + my ( $self, $sub ) = @_; - foreach my $map (@mappings) { - $sub->( - $map->{name}, - $map->{type}, - $map->{facet}, - $map->{suggestible}, - $map->{sort}, - $map->{searchable}, - $map->{filter}, - $map->{marc_type}, - $map->{marc_field} - ); + foreach my $map (@mappings) { + $sub->( + $map->{name}, + $map->{type}, + $map->{facet}, + $map->{suggestible}, + $map->{sort}, + $map->{searchable}, + $map->{filter}, + $map->{marc_type}, + $map->{marc_field} + ); + } } - }); + ); - my $see = Koha::SearchEngine::Elasticsearch::Search->new({ index => $Koha::SearchEngine::Elasticsearch::BIBLIOS_INDEX }); + my $see = Koha::SearchEngine::Elasticsearch::Search->new( + { index => $Koha::SearchEngine::Elasticsearch::BIBLIOS_INDEX } ); - my $callno = 'ABC123'; - my $callno2 = 'ABC456'; + my $callno = 'ABC123'; + my $callno2 = 'ABC456'; my $long_callno = '1234567890' x 30; my $marc_record_1 = MARC::Record->new(); $marc_record_1->leader(' cam 22 a 4500'); $marc_record_1->append_fields( - MARC::Field->new('001', '123'), - MARC::Field->new('007', 'ku'), - MARC::Field->new('008', '901111s1962 xxk|||| |00| ||eng c'), - MARC::Field->new('020', '', '', a => '1-56619-909-3'), - MARC::Field->new('100', '', '', a => 'Author 1'), - MARC::Field->new('110', '', '', a => 'Corp Author'), - MARC::Field->new('210', '', '', a => 'Title 1'), - MARC::Field->new('240', '', '4', a => 'The uniform title with nonfiling indicator'), - MARC::Field->new('245', '', '', a => 'Title:', b => 'first record'), - MARC::Field->new('260', '', '', a => 'New York :', b => 'Ace ,', c => 'c1962'), - MARC::Field->new('650', '', '', a => 'Heading', z => 'Geohead', v => 'Formhead'), - MARC::Field->new('650', '', '', a => 'Heading', x => 'Gensubhead', z => 'Geohead'), - MARC::Field->new('999', '', '', c => '1234567'), + MARC::Field->new( '001', '123' ), + MARC::Field->new( '007', 'ku' ), + MARC::Field->new( '008', '901111s1962 xxk|||| |00| ||eng c' ), + MARC::Field->new( '020', '', '', a => '1-56619-909-3' ), + MARC::Field->new( '100', '', '', a => 'Author 1' ), + MARC::Field->new( '110', '', '', a => 'Corp Author' ), + MARC::Field->new( '210', '', '', a => 'Title 1' ), + MARC::Field->new( '240', '', '4', a => 'The uniform title with nonfiling indicator' ), + MARC::Field->new( '245', '', '', a => 'Title:', b => 'first record' ), + MARC::Field->new( '260', '', '', a => 'New York :', b => 'Ace ,', c => 'c1962' ), + MARC::Field->new( '650', '', '', a => 'Heading', z => 'Geohead', v => 'Formhead' ), + MARC::Field->new( '650', '', '', a => 'Heading', x => 'Gensubhead', z => 'Geohead' ), + MARC::Field->new( '999', '', '', c => '1234567' ), + # ' ' for testing trimming of white space in boolean value callback: - MARC::Field->new('952', '', '', 0 => ' ', g => '123.30', o => $callno, l => 3), - MARC::Field->new('952', '', '', 0 => 0, g => '127.20', o => $callno2, l => 2), - MARC::Field->new('952', '', '', 0 => 1, g => '0.00', o => $long_callno, l => 1), + MARC::Field->new( '952', '', '', 0 => ' ', g => '123.30', o => $callno, l => 3 ), + MARC::Field->new( '952', '', '', 0 => 0, g => '127.20', o => $callno2, l => 2 ), + MARC::Field->new( '952', '', '', 0 => 1, g => '0.00', o => $long_callno, l => 1 ), ); my $marc_record_2 = MARC::Record->new(); $marc_record_2->leader(' cam 22 a 4500'); $marc_record_2->append_fields( - MARC::Field->new('008', '901111s19uu xxk|||| |00| ||eng c'), - MARC::Field->new('100', '', '', a => 'Author 2'), + MARC::Field->new( '008', '901111s19uu xxk|||| |00| ||eng c' ), + MARC::Field->new( '100', '', '', a => 'Author 2' ), + # MARC::Field->new('210', '', '', a => 'Title 2'), # MARC::Field->new('245', '', '', a => 'Title: second record'), - MARC::Field->new('260', '', '', a => 'New York :', b => 'Ace ,', c => '1963-2003'), - MARC::Field->new('999', '', '', c => '1234568'), - MARC::Field->new('952', '', '', 0 => 1, g => 'string where should be numeric', o => $long_callno), + MARC::Field->new( '260', '', '', a => 'New York :', b => 'Ace ,', c => '1963-2003' ), + MARC::Field->new( '999', '', '', c => '1234568' ), + MARC::Field->new( '952', '', '', 0 => 1, g => 'string where should be numeric', o => $long_callno ), ); my $marc_record_3 = MARC::Record->new(); $marc_record_3->leader(' cam 22 a 4500'); $marc_record_3->append_fields( - MARC::Field->new('008', '901111s19uu xxk|||| |00| ||eng c'), - MARC::Field->new('100', '', '', a => 'Author 2'), + MARC::Field->new( '008', '901111s19uu xxk|||| |00| ||eng c' ), + MARC::Field->new( '100', '', '', a => 'Author 2' ), + # MARC::Field->new('210', '', '', a => 'Title 3'), # MARC::Field->new('245', '', '', a => 'Title: third record'), - MARC::Field->new('260', '', '', a => 'New York :', b => 'Ace ,', c => ' 89 '), - MARC::Field->new('999', '', '', c => '1234568'), - MARC::Field->new('952', '', '', 0 => 1, g => 'string where should be numeric', o => $long_callno), + MARC::Field->new( '260', '', '', a => 'New York :', b => 'Ace ,', c => ' 89 ' ), + MARC::Field->new( '999', '', '', c => '1234568' ), + MARC::Field->new( '952', '', '', 0 => 1, g => 'string where should be numeric', o => $long_callno ), ); my $marc_record_4 = MARC::Record->new(); $marc_record_4->leader(' cam 22 a 4500'); $marc_record_4->append_fields( MARC::Field->new( '008', '901111s19uu xxk|||| |00| ||eng c' ), - MARC::Field->new( '100', '', '', a => 'Author 2' ), + MARC::Field->new( '100', '', '', a => 'Author 2' ), MARC::Field->new( '245', '', '4', a => 'The Title\'s the thing :', b => 'fourth record' ), - MARC::Field->new( '260', '', '', a => 'New York :', b => 'Ace ,', c => ' 89 ' ), - MARC::Field->new( '999', '', '', c => '1234568' ), + MARC::Field->new( '260', '', '', a => 'New York :', b => 'Ace ,', c => ' 89 ' ), + MARC::Field->new( '999', '', '', c => '1234568' ), ); - my $records = [$marc_record_1, $marc_record_2, $marc_record_3, $marc_record_4]; + my $records = [ $marc_record_1, $marc_record_2, $marc_record_3, $marc_record_4 ]; $see->get_elasticsearch_mappings(); #sort_fields will call this and use the actual db values unless we call it first my $docs = $see->marc_records_to_documents($records); # First record: - is(scalar @{$docs}, 4, 'Four records converted to documents'); + is( scalar @{$docs}, 4, 'Four records converted to documents' ); - is_deeply($docs->[0]->{control_number}, ['123'], 'First record control number should be set correctly'); + is_deeply( $docs->[0]->{control_number}, ['123'], 'First record control number should be set correctly' ); - is_deeply($docs->[0]->{'ff7-00'}, ['k'], 'First record ff7-00 should be set correctly'); + is_deeply( $docs->[0]->{'ff7-00'}, ['k'], 'First record ff7-00 should be set correctly' ); - is(scalar @{$docs->[0]->{author}}, 2, 'First document author field should contain two values'); - is_deeply($docs->[0]->{author}, ['Author 1', 'Corp Author'], 'First document author field should be set correctly'); + is( scalar @{ $docs->[0]->{author} }, 2, 'First document author field should contain two values' ); + is_deeply( + $docs->[0]->{author}, [ 'Author 1', 'Corp Author' ], + 'First document author field should be set correctly' + ); - is(scalar @{$docs->[0]->{subject}}, 2, 'First document subject field should contain two values'); - is_deeply($docs->[0]->{subject}, ['Heading Geohead Formhead', 'Heading Gensubhead Geohead'], 'First document asubject field should be set correctly, record order preserved for grouped subfield mapping'); + is( scalar @{ $docs->[0]->{subject} }, 2, 'First document subject field should contain two values' ); + is_deeply( + $docs->[0]->{subject}, [ 'Heading Geohead Formhead', 'Heading Gensubhead Geohead' ], + 'First document asubject field should be set correctly, record order preserved for grouped subfield mapping' + ); - is(scalar @{$docs->[0]->{author__sort}}, 1, 'First document author__sort field should have a single value'); - is_deeply($docs->[0]->{author__sort}, ['Author 1 Corp Author'], 'First document author__sort field should be set correctly'); + is( scalar @{ $docs->[0]->{author__sort} }, 1, 'First document author__sort field should have a single value' ); + is_deeply( + $docs->[0]->{author__sort}, ['Author 1 Corp Author'], + 'First document author__sort field should be set correctly' + ); - is(scalar @{$docs->[0]->{title__sort}}, 1, 'First document title__sort field should have a single'); - is_deeply($docs->[0]->{title__sort}, ['Title: first record Title: first record'], 'First document title__sort field should be set correctly'); + is( scalar @{ $docs->[0]->{title__sort} }, 1, 'First document title__sort field should have a single' ); + is_deeply( + $docs->[0]->{title__sort}, ['Title: first record Title: first record'], + 'First document title__sort field should be set correctly' + ); - is(scalar @{$docs->[3]->{title__sort}}, 1, 'First document title__sort field should have a single'); + is( scalar @{ $docs->[3]->{title__sort} }, 1, 'First document title__sort field should have a single' ); is_deeply( $docs->[3]->{title__sort}, ['Title\'s the thing : fourth record The Title\'s the thing : fourth record'], 'Fourth document title__sort field should be set correctly' @@ -522,28 +563,32 @@ subtest 'Koha::SearchEngine::Elasticsearch::marc_records_to_documents () tests' 'Fourth document title-no-punctuation field should be set correctly' ); - is($docs->[0]->{issues}, 6, 'Issues field should be sum of the issues for each item'); - is($docs->[0]->{issues__sort}, 6, 'Issues sort field should also be a sum of the issues'); + is( $docs->[0]->{issues}, 6, 'Issues field should be sum of the issues for each item' ); + is( $docs->[0]->{issues__sort}, 6, 'Issues sort field should also be a sum of the issues' ); - is(scalar @{$docs->[0]->{title_wildcard}}, 2, 'First document title_wildcard field should have two values'); - is_deeply($docs->[0]->{title_wildcard}, ['Title:', 'first record'], 'First document title_wildcard field should be set correctly'); + is( scalar @{ $docs->[0]->{title_wildcard} }, 2, 'First document title_wildcard field should have two values' ); + is_deeply( + $docs->[0]->{title_wildcard}, [ 'Title:', 'first record' ], + 'First document title_wildcard field should be set correctly' + ); - - is(scalar @{$docs->[0]->{author__suggestion}}, 2, 'First document author__suggestion field should contain two values'); + is( + scalar @{ $docs->[0]->{author__suggestion} }, 2, + 'First document author__suggestion field should contain two values' + ); is_deeply( $docs->[0]->{author__suggestion}, [ - { - 'input' => 'Author 1' - }, - { - 'input' => 'Corp Author' - } + { 'input' => 'Author 1' }, + { 'input' => 'Corp Author' } ], 'First document author__suggestion field should be set correctly' ); - is(scalar @{$docs->[0]->{title__suggestion}}, 3, 'First document title__suggestion field should contain three values'); + is( + scalar @{ $docs->[0]->{title__suggestion} }, 3, + 'First document title__suggestion field should contain three values' + ); is_deeply( $docs->[0]->{title__suggestion}, [ @@ -554,19 +599,22 @@ subtest 'Koha::SearchEngine::Elasticsearch::marc_records_to_documents () tests' 'First document title__suggestion field should be set correctly' ); - ok(!(defined $docs->[0]->{title__facet}), 'First document should have no title__facet field'); + ok( !( defined $docs->[0]->{title__facet} ), 'First document should have no title__facet field' ); - is(scalar @{$docs->[0]->{author__facet}}, 2, 'First document author__facet field should have two values'); + is( scalar @{ $docs->[0]->{author__facet} }, 2, 'First document author__facet field should have two values' ); is_deeply( $docs->[0]->{author__facet}, - ['Author 1', 'Corp Author'], + [ 'Author 1', 'Corp Author' ], 'First document author__facet field should be set correctly' ); - is(scalar @{$docs->[0]->{items_withdrawn_status}}, 2, 'First document items_withdrawn_status field should have two values'); + is( + scalar @{ $docs->[0]->{items_withdrawn_status} }, 2, + 'First document items_withdrawn_status field should have two values' + ); is_deeply( $docs->[0]->{items_withdrawn_status}, - ['false', 'true'], + [ 'false', 'true' ], 'First document items_withdrawn_status field should be set correctly' ); @@ -576,35 +624,44 @@ subtest 'Koha::SearchEngine::Elasticsearch::marc_records_to_documents () tests' 'First document sum_item_price field should be set correctly' ); - ok(defined $docs->[0]->{marc_data}, 'First document marc_data field should be set'); - ok(defined $docs->[0]->{marc_format}, 'First document marc_format field should be set'); - is($docs->[0]->{marc_format}, 'base64ISO2709', 'First document marc_format should be set correctly'); + ok( defined $docs->[0]->{marc_data}, 'First document marc_data field should be set' ); + ok( defined $docs->[0]->{marc_format}, 'First document marc_format field should be set' ); + is( $docs->[0]->{marc_format}, 'base64ISO2709', 'First document marc_format should be set correctly' ); - my $decoded_marc_record = $see->decode_record_from_result($docs->[0]); + my $decoded_marc_record = $see->decode_record_from_result( $docs->[0] ); - ok($decoded_marc_record->isa('MARC::Record'), "base64ISO2709 record successfully decoded from result"); - is($decoded_marc_record->as_usmarc(), $marc_record_1->as_usmarc(), "Decoded base64ISO2709 record has same data as original record"); + ok( $decoded_marc_record->isa('MARC::Record'), "base64ISO2709 record successfully decoded from result" ); + is( + $decoded_marc_record->as_usmarc(), $marc_record_1->as_usmarc(), + "Decoded base64ISO2709 record has same data as original record" + ); - is(scalar @{$docs->[0]->{type_of_record}}, 1, 'First document type_of_record field should have one value'); + is( scalar @{ $docs->[0]->{type_of_record} }, 1, 'First document type_of_record field should have one value' ); is_deeply( $docs->[0]->{type_of_record}, ['a'], 'First document type_of_record field should be set correctly' ); - is(scalar @{$docs->[0]->{type_of_record_and_bib_level}}, 1, 'First document type_of_record_and_bib_level field should have one value'); + is( + scalar @{ $docs->[0]->{type_of_record_and_bib_level} }, 1, + 'First document type_of_record_and_bib_level field should have one value' + ); is_deeply( $docs->[0]->{type_of_record_and_bib_level}, ['am'], 'First document type_of_record_and_bib_level field should be set correctly' ); - is(scalar @{$docs->[0]->{isbn}}, 4, 'First document isbn field should contain four values'); - is_deeply($docs->[0]->{isbn}, ['978-1-56619-909-4', '9781566199094', '1-56619-909-3', '1566199093'], 'First document isbn field should be set correctly'); + is( scalar @{ $docs->[0]->{isbn} }, 4, 'First document isbn field should contain four values' ); + is_deeply( + $docs->[0]->{isbn}, [ '978-1-56619-909-4', '9781566199094', '1-56619-909-3', '1566199093' ], + 'First document isbn field should be set correctly' + ); is_deeply( $docs->[0]->{'local_classification'}, - [$callno, $callno2, $long_callno], + [ $callno, $callno2, $long_callno ], 'First document local_classification field should be set correctly' ); @@ -621,21 +678,30 @@ subtest 'Koha::SearchEngine::Elasticsearch::marc_records_to_documents () tests' ); # Tests for 'year' type - is(scalar @{$docs->[0]->{'date-of-publication'}}, 1, 'First document date-of-publication field should contain one value'); - is_deeply($docs->[0]->{'date-of-publication'}, ['1962'], 'First document date-of-publication field should be set correctly'); + is( + scalar @{ $docs->[0]->{'date-of-publication'} }, 1, + 'First document date-of-publication field should contain one value' + ); + is_deeply( + $docs->[0]->{'date-of-publication'}, ['1962'], + 'First document date-of-publication field should be set correctly' + ); is_deeply( - $docs->[0]->{'copydate'}, - ['1962'], - 'First document copydate field should be set correctly' + $docs->[0]->{'copydate'}, + ['1962'], + 'First document copydate field should be set correctly' ); # Second record: - is(scalar @{$docs->[1]->{author}}, 1, 'Second document author field should contain one value'); - is_deeply($docs->[1]->{author}, ['Author 2'], 'Second document author field should be set correctly'); + is( scalar @{ $docs->[1]->{author} }, 1, 'Second document author field should contain one value' ); + is_deeply( $docs->[1]->{author}, ['Author 2'], 'Second document author field should be set correctly' ); - is(scalar @{$docs->[1]->{items_withdrawn_status}}, 1, 'Second document items_withdrawn_status field should have one value'); + is( + scalar @{ $docs->[1]->{items_withdrawn_status} }, 1, + 'Second document items_withdrawn_status field should have one value' + ); is_deeply( $docs->[1]->{items_withdrawn_status}, ['true'], @@ -650,33 +716,33 @@ subtest 'Koha::SearchEngine::Elasticsearch::marc_records_to_documents () tests' is_deeply( $docs->[1]->{local_classification__sort}, - [substr($long_callno, 0, 255)], + [ substr( $long_callno, 0, 255 ) ], 'Second document local_classification__sort field should be set correctly' ); # Tests for 'year' type is_deeply( - $docs->[1]->{'copydate'}, - ['1963', '2003'], - 'Second document copydate field should be set correctly' + $docs->[1]->{'copydate'}, + [ '1963', '2003' ], + 'Second document copydate field should be set correctly' ); is_deeply( - $docs->[1]->{'date-of-publication'}, - ['1900'], - 'Second document date-of-publication field should be set correctly' + $docs->[1]->{'date-of-publication'}, + ['1900'], + 'Second document date-of-publication field should be set correctly' ); # Third record: is_deeply( - $docs->[2]->{'copydate'}, - ['0890'], - 'Third document copydate field should be set correctly' + $docs->[2]->{'copydate'}, + ['0890'], + 'Third document copydate field should be set correctly' ); # Mappings marc_type: - ok(!(defined $docs->[0]->{unimarc_title}), "No mapping when marc_type doesn't match marc flavour"); + ok( !( defined $docs->[0]->{unimarc_title} ), "No mapping when marc_type doesn't match marc flavour" ); # Marc serialization format fallback for records exceeding ISO2709 max record size @@ -684,84 +750,91 @@ subtest 'Koha::SearchEngine::Elasticsearch::marc_records_to_documents () tests' $large_marc_record->leader(' cam 22 a 4500'); $large_marc_record->append_fields( - MARC::Field->new('100', '', '', a => 'Author 1'), - MARC::Field->new('110', '', '', a => 'Corp Author'), - MARC::Field->new('210', '', '', a => 'Title 1'), - MARC::Field->new('245', '', '', a => 'Title:', b => 'large record'), - MARC::Field->new('999', '', '', c => '1234567'), + MARC::Field->new( '100', '', '', a => 'Author 1' ), + MARC::Field->new( '110', '', '', a => 'Corp Author' ), + MARC::Field->new( '210', '', '', a => 'Title 1' ), + MARC::Field->new( '245', '', '', a => 'Title:', b => 'large record' ), + MARC::Field->new( '999', '', '', c => '1234567' ), ); - my $item_field = MARC::Field->new('952', '', '', o => '123456789123456789123456789', p => '123456789', z => Encode::decode('UTF-8','To naprawdę bardzo długa notatka. Myślę, że będzie sprawiać kłopoty.')); + my $item_field = MARC::Field->new( + '952', '', '', o => '123456789123456789123456789', p => '123456789', + z => Encode::decode( 'UTF-8', 'To naprawdę bardzo długa notatka. Myślę, że będzie sprawiać kłopoty.' ) + ); my $items_count = 1638; - while(--$items_count) { + while ( --$items_count ) { $large_marc_record->append_fields($item_field); } - $docs = $see->marc_records_to_documents([$large_marc_record]); + $docs = $see->marc_records_to_documents( [$large_marc_record] ); - is($docs->[0]->{marc_format}, 'MARCXML', 'For record exceeding max record size marc_format should be set correctly'); + is( + $docs->[0]->{marc_format}, 'MARCXML', + 'For record exceeding max record size marc_format should be set correctly' + ); - $decoded_marc_record = $see->decode_record_from_result($docs->[0]); + $decoded_marc_record = $see->decode_record_from_result( $docs->[0] ); - ok($decoded_marc_record->isa('MARC::Record'), "MARCXML record successfully decoded from result"); - is($decoded_marc_record->as_xml_record(), $large_marc_record->as_xml_record(), "Decoded MARCXML record has same data as original record"); + ok( $decoded_marc_record->isa('MARC::Record'), "MARCXML record successfully decoded from result" ); + is( + $decoded_marc_record->as_xml_record(), $large_marc_record->as_xml_record(), + "Decoded MARCXML record has same data as original record" + ); push @mappings, { - name => 'title', - type => 'string', - facet => 0, + name => 'title', + type => 'string', + facet => 0, suggestible => 1, - sort => 1, - marc_type => 'marc21', - marc_field => '245((ab)ab', + sort => 1, + marc_type => 'marc21', + marc_field => '245((ab)ab', }; my $exception = try { $see->marc_records_to_documents($records); - } - catch { + } catch { return $_; }; - ok(defined $exception, "Exception has been thrown when processing mapping with unmatched opening parenthesis"); - ok($exception->isa("Koha::Exceptions::Elasticsearch::MARCFieldExprParseError"), "Exception is of correct class"); - ok($exception->message =~ /Unmatched opening parenthesis/, "Exception has the correct message"); + ok( defined $exception, "Exception has been thrown when processing mapping with unmatched opening parenthesis" ); + ok( $exception->isa("Koha::Exceptions::Elasticsearch::MARCFieldExprParseError"), "Exception is of correct class" ); + ok( $exception->message =~ /Unmatched opening parenthesis/, "Exception has the correct message" ); pop @mappings; push @mappings, { - name => 'title', - type => 'string', - facet => 0, + name => 'title', + type => 'string', + facet => 0, suggestible => 1, - sort => 1, - marc_type => 'marc21', - marc_field => '245(ab))ab', + sort => 1, + marc_type => 'marc21', + marc_field => '245(ab))ab', }; $exception = try { $see->marc_records_to_documents($records); - } - catch { + } catch { return $_; }; - ok(defined $exception, "Exception has been thrown when processing mapping with unmatched closing parenthesis"); - ok($exception->isa("Koha::Exceptions::Elasticsearch::MARCFieldExprParseError"), "Exception is of correct class"); - ok($exception->message =~ /Unmatched closing parenthesis/, "Exception has the correct message"); + ok( defined $exception, "Exception has been thrown when processing mapping with unmatched closing parenthesis" ); + ok( $exception->isa("Koha::Exceptions::Elasticsearch::MARCFieldExprParseError"), "Exception is of correct class" ); + ok( $exception->message =~ /Unmatched closing parenthesis/, "Exception has the correct message" ); pop @mappings; my $marc_record_with_blank_field = MARC::Record->new(); $marc_record_with_blank_field->leader(' cam 22 a 4500'); $marc_record_with_blank_field->append_fields( - MARC::Field->new('100', '', '', a => ''), - MARC::Field->new('210', '', '', a => 'Title 1'), - MARC::Field->new('245', '', '', a => 'Title:', b => 'large record'), - MARC::Field->new('999', '', '', c => '1234567'), + MARC::Field->new( '100', '', '', a => '' ), + MARC::Field->new( '210', '', '', a => 'Title 1' ), + MARC::Field->new( '245', '', '', a => 'Title:', b => 'large record' ), + MARC::Field->new( '999', '', '', c => '1234567' ), ); - $docs = $see->marc_records_to_documents([$marc_record_with_blank_field]); - is_deeply( $docs->[0]->{author},[],'No value placed into field if mapped marc field is blank'); - is_deeply( $docs->[0]->{author__suggestion},[],'No value placed into suggestion if mapped marc field is blank'); + $docs = $see->marc_records_to_documents( [$marc_record_with_blank_field] ); + is_deeply( $docs->[0]->{author}, [], 'No value placed into field if mapped marc field is blank' ); + is_deeply( $docs->[0]->{author__suggestion}, [], 'No value placed into suggestion if mapped marc field is blank' ); my $marc_record_with_large_field = MARC::Record->new(); $marc_record_with_large_field->leader(' cam 22 a 4500'); @@ -808,62 +881,67 @@ subtest 'Koha::SearchEngine::Elasticsearch::marc_records_to_documents_array () t plan tests => 5; - t::lib::Mocks::mock_preference('marcflavour', 'MARC21'); - t::lib::Mocks::mock_preference('ElasticsearchMARCFormat', 'ARRAY'); + t::lib::Mocks::mock_preference( 'marcflavour', 'MARC21' ); + t::lib::Mocks::mock_preference( 'ElasticsearchMARCFormat', 'ARRAY' ); my @mappings = ( { - name => 'control_number', - type => 'string', - facet => 0, + name => 'control_number', + type => 'string', + facet => 0, suggestible => 0, - sort => undef, - searchable => 1, - marc_type => 'marc21', - marc_field => '001', + sort => undef, + searchable => 1, + marc_type => 'marc21', + marc_field => '001', } ); my $se = Test::MockModule->new('Koha::SearchEngine::Elasticsearch'); - $se->mock('_foreach_mapping', sub { - my ($self, $sub) = @_; + $se->mock( + '_foreach_mapping', + sub { + my ( $self, $sub ) = @_; - foreach my $map (@mappings) { - $sub->( - $map->{name}, - $map->{type}, - $map->{facet}, - $map->{suggestible}, - $map->{sort}, - $map->{searchable}, - $map->{filter}, - $map->{marc_type}, - $map->{marc_field} - ); + foreach my $map (@mappings) { + $sub->( + $map->{name}, + $map->{type}, + $map->{facet}, + $map->{suggestible}, + $map->{sort}, + $map->{searchable}, + $map->{filter}, + $map->{marc_type}, + $map->{marc_field} + ); + } } - }); + ); - my $see = Koha::SearchEngine::Elasticsearch::Search->new({ index => $Koha::SearchEngine::Elasticsearch::BIBLIOS_INDEX }); + my $see = Koha::SearchEngine::Elasticsearch::Search->new( + { index => $Koha::SearchEngine::Elasticsearch::BIBLIOS_INDEX } ); my $marc_record_1 = MARC::Record->new(); $marc_record_1->leader(' cam 22 a 4500'); $marc_record_1->append_fields( - MARC::Field->new('001', '123'), - MARC::Field->new('020', '', '', a => '1-56619-909-3'), - MARC::Field->new('100', '', '', a => 'Author 1'), - MARC::Field->new('110', '', '', a => 'Corp Author'), - MARC::Field->new('210', '', '', a => 'Title 1'), - MARC::Field->new('245', '', '', a => 'Title:', b => 'first record'), - MARC::Field->new('999', '', '', c => '1234567'), + MARC::Field->new( '001', '123' ), + MARC::Field->new( '020', '', '', a => '1-56619-909-3' ), + MARC::Field->new( '100', '', '', a => 'Author 1' ), + MARC::Field->new( '110', '', '', a => 'Corp Author' ), + MARC::Field->new( '210', '', '', a => 'Title 1' ), + MARC::Field->new( '245', '', '', a => 'Title:', b => 'first record' ), + MARC::Field->new( '999', '', '', c => '1234567' ), ); my $marc_record_2 = MARC::Record->new(); $marc_record_2->leader(' cam 22 a 4500'); $marc_record_2->append_fields( - MARC::Field->new('100', '', '', a => 'Author 2'), + MARC::Field->new( '100', '', '', a => 'Author 2' ), + # MARC::Field->new('210', '', '', a => 'Title 2'), # MARC::Field->new('245', '', '', a => 'Title: second record'), - MARC::Field->new('999', '', '', c => '1234568'), - MARC::Field->new('952', '', '', 0 => 1, g => 'string where should be numeric'), + MARC::Field->new( '999', '', '', c => '1234568' ), + MARC::Field->new( '952', '', '', 0 => 1, g => 'string where should be numeric' ), ); my $records = [ $marc_record_1, $marc_record_2 ]; @@ -872,88 +950,96 @@ subtest 'Koha::SearchEngine::Elasticsearch::marc_records_to_documents_array () t my $docs = $see->marc_records_to_documents($records); # First record: - is(scalar @{$docs}, 2, 'Two records converted to documents'); + is( scalar @{$docs}, 2, 'Two records converted to documents' ); - is_deeply($docs->[0]->{control_number}, ['123'], 'First record control number should be set correctly'); + is_deeply( $docs->[0]->{control_number}, ['123'], 'First record control number should be set correctly' ); - is($docs->[0]->{marc_format}, 'ARRAY', 'First document marc_format should be set correctly'); + is( $docs->[0]->{marc_format}, 'ARRAY', 'First document marc_format should be set correctly' ); - my $decoded_marc_record = $see->decode_record_from_result($docs->[0]); + my $decoded_marc_record = $see->decode_record_from_result( $docs->[0] ); - ok($decoded_marc_record->isa('MARC::Record'), "ARRAY record successfully decoded from result"); - is($decoded_marc_record->as_usmarc(), $marc_record_1->as_usmarc(), "Decoded ARRAY record has same data as original record"); + ok( $decoded_marc_record->isa('MARC::Record'), "ARRAY record successfully decoded from result" ); + is( + $decoded_marc_record->as_usmarc(), $marc_record_1->as_usmarc(), + "Decoded ARRAY record has same data as original record" + ); }; subtest 'Koha::SearchEngine::Elasticsearch::marc_records_to_documents () authority tests' => sub { plan tests => 5; - t::lib::Mocks::mock_preference('marcflavour', 'MARC21'); - t::lib::Mocks::mock_preference('ElasticsearchMARCFormat', 'ISO2709'); + t::lib::Mocks::mock_preference( 'marcflavour', 'MARC21' ); + t::lib::Mocks::mock_preference( 'ElasticsearchMARCFormat', 'ISO2709' ); my $builder = t::lib::TestBuilder->new; - my $auth_type = $builder->build_object({ class => 'Koha::Authority::Types', value =>{ - auth_tag_to_report => '150' - } - }); + my $auth_type = + $builder->build_object( { class => 'Koha::Authority::Types', value => { auth_tag_to_report => '150' } } ); my @mappings = ( { - name => 'match', - type => 'string', - facet => 0, + name => 'match', + type => 'string', + facet => 0, suggestible => 0, - searchable => 1, - sort => 0, - marc_type => 'marc21', - marc_field => '150(aevxyz)', + searchable => 1, + sort => 0, + marc_type => 'marc21', + marc_field => '150(aevxyz)', }, { - name => 'match', - type => 'string', - facet => 0, + name => 'match', + type => 'string', + facet => 0, suggestible => 0, - searchable => 1, - sort => 0, - marc_type => 'marc21', - marc_field => '185v', + searchable => 1, + sort => 0, + marc_type => 'marc21', + marc_field => '185v', } ); my $se = Test::MockModule->new('Koha::SearchEngine::Elasticsearch'); - $se->mock('_foreach_mapping', sub { - my ($self, $sub) = @_; + $se->mock( + '_foreach_mapping', + sub { + my ( $self, $sub ) = @_; - foreach my $map (@mappings) { - $sub->( - $map->{name}, - $map->{type}, - $map->{facet}, - $map->{suggestible}, - $map->{sort}, - $map->{searchable}, - $map->{filter}, - $map->{marc_type}, - $map->{marc_field} - ); + foreach my $map (@mappings) { + $sub->( + $map->{name}, + $map->{type}, + $map->{facet}, + $map->{suggestible}, + $map->{sort}, + $map->{searchable}, + $map->{filter}, + $map->{marc_type}, + $map->{marc_field} + ); + } } - }); + ); - my $see = Koha::SearchEngine::Elasticsearch::Search->new({ index => $Koha::SearchEngine::Elasticsearch::AUTHORITIES_INDEX }); + my $see = Koha::SearchEngine::Elasticsearch::Search->new( + { index => $Koha::SearchEngine::Elasticsearch::AUTHORITIES_INDEX } ); my $marc_record_1 = MARC::Record->new(); $marc_record_1->append_fields( - MARC::Field->new('001', '123'), - MARC::Field->new('007', 'ku'), - MARC::Field->new('020', '', '', a => '1-56619-909-3'), - MARC::Field->new('150', '', '', a => 'Subject', v => 'Genresubdiv', x => 'Generalsubdiv', z => 'Geosubdiv'), + MARC::Field->new( '001', '123' ), + MARC::Field->new( '007', 'ku' ), + MARC::Field->new( '020', '', '', a => '1-56619-909-3' ), + MARC::Field->new( '150', '', '', a => 'Subject', v => 'Genresubdiv', x => 'Generalsubdiv', z => 'Geosubdiv' ), ); my $marc_record_2 = MARC::Record->new(); $marc_record_2->append_fields( - MARC::Field->new('150', '', '', a => 'Subject', v => 'Genresubdiv', z => 'Geosubdiv', x => 'Generalsubdiv', e => 'wrongsubdiv' ), + MARC::Field->new( + '150', '', '', a => 'Subject', v => 'Genresubdiv', z => 'Geosubdiv', x => 'Generalsubdiv', + e => 'wrongsubdiv' + ), ); my $marc_record_3 = MARC::Record->new(); $marc_record_3->append_fields( - MARC::Field->new('185', '', '', v => 'Formsubdiv' ), + MARC::Field->new( '185', '', '', v => 'Formsubdiv' ), ); my $records = [ $marc_record_1, $marc_record_2, $marc_record_3 ]; @@ -962,24 +1048,24 @@ subtest 'Koha::SearchEngine::Elasticsearch::marc_records_to_documents () authori my $docs = $see->marc_records_to_documents($records); is_deeply( - [ "Subject formsubdiv Genresubdiv generalsubdiv Generalsubdiv geographicsubdiv Geosubdiv" ], + ["Subject formsubdiv Genresubdiv generalsubdiv Generalsubdiv geographicsubdiv Geosubdiv"], $docs->[0]->{'match-heading'}, "First record match-heading should contain the correctly formatted heading" ); is_deeply( - [ "Subject formsubdiv Genresubdiv geographicsubdiv Geosubdiv generalsubdiv Generalsubdiv" ], + ["Subject formsubdiv Genresubdiv geographicsubdiv Geosubdiv generalsubdiv Generalsubdiv"], $docs->[1]->{'match-heading'}, "Second record match-heading should contain the correctly formatted heading without wrong subfield" ); is_deeply( - [ "Subject Genresubdiv Geosubdiv Generalsubdiv wrongsubdiv" ], - $docs->[1]->{'match'} , + ["Subject Genresubdiv Geosubdiv Generalsubdiv wrongsubdiv"], + $docs->[1]->{'match'}, "Second record heading should contain the subfields with record order retained" ); - ok( !exists $docs->[2]->{'match-heading'}, "No match heading defined for subdivision record"); + ok( !exists $docs->[2]->{'match-heading'}, "No match heading defined for subdivision record" ); is_deeply( - [ "Formsubdiv" ], - $docs->[2]->{'match'} , + ["Formsubdiv"], + $docs->[2]->{'match'}, "Third record heading should contain the subfield" ); @@ -989,89 +1075,100 @@ subtest 'Koha::SearchEngine::Elasticsearch::marc_records_to_documents with Inclu plan tests => 4; - t::lib::Mocks::mock_preference('marcflavour', 'MARC21'); - t::lib::Mocks::mock_preference('IncludeSeeFromInSearches', '1'); + t::lib::Mocks::mock_preference( 'marcflavour', 'MARC21' ); + t::lib::Mocks::mock_preference( 'IncludeSeeFromInSearches', '1' ); my $dbh = C4::Context->dbh; - my $builder = t::lib::TestBuilder->new; - my $auth_type = $builder->build_object({ - class => 'Koha::Authority::Types', - value => { - auth_tag_to_report => '150' + my $builder = t::lib::TestBuilder->new; + my $auth_type = $builder->build_object( + { + class => 'Koha::Authority::Types', + value => { auth_tag_to_report => '150' } } - }); + ); my $authority_record = MARC::Record->new(); $authority_record->append_fields( - MARC::Field->new(150, '', '', a => 'Foo'), - MARC::Field->new(450, '', '', a => 'Bar'), + MARC::Field->new( 150, '', '', a => 'Foo' ), + MARC::Field->new( 450, '', '', a => 'Bar' ), + ); + $dbh->do( + "INSERT INTO auth_header (datecreated,marcxml) values (NOW(),?)", undef, + ( $authority_record->as_xml_record('MARC21') ) ); - $dbh->do( "INSERT INTO auth_header (datecreated,marcxml) values (NOW(),?)", undef, ($authority_record->as_xml_record('MARC21') ) ); my $authid = $dbh->last_insert_id( undef, undef, 'auth_header', 'authid' ); my @mappings = ( { - name => 'subject', - type => 'string', - facet => 1, + name => 'subject', + type => 'string', + facet => 1, suggestible => 1, - sort => undef, - searchable => 1, - marc_type => 'marc21', - marc_field => '650a', + sort => undef, + searchable => 1, + marc_type => 'marc21', + marc_field => '650a', } ); my $se = Test::MockModule->new('Koha::SearchEngine::Elasticsearch'); - $se->mock('_foreach_mapping', sub { - my ($self, $sub) = @_; + $se->mock( + '_foreach_mapping', + sub { + my ( $self, $sub ) = @_; - foreach my $map (@mappings) { - $sub->( - $map->{name}, - $map->{type}, - $map->{facet}, - $map->{suggestible}, - $map->{sort}, - $map->{searchable}, - $map->{filter}, - $map->{marc_type}, - $map->{marc_field} - ); + foreach my $map (@mappings) { + $sub->( + $map->{name}, + $map->{type}, + $map->{facet}, + $map->{suggestible}, + $map->{sort}, + $map->{searchable}, + $map->{filter}, + $map->{marc_type}, + $map->{marc_field} + ); + } } - }); + ); - my $see = Koha::SearchEngine::Elasticsearch::Search->new({ index => $Koha::SearchEngine::Elasticsearch::BIBLIOS_INDEX }); + my $see = Koha::SearchEngine::Elasticsearch::Search->new( + { index => $Koha::SearchEngine::Elasticsearch::BIBLIOS_INDEX } ); my $marc_record_1 = MARC::Record->new(); $marc_record_1->leader(' cam 22 a 4500'); $marc_record_1->append_fields( - MARC::Field->new('001', '123'), - MARC::Field->new('245', '', '', a => 'Title'), - MARC::Field->new('650', '', '', a => 'Foo', 9 => $authid), - MARC::Field->new('999', '', '', c => '1234567'), + MARC::Field->new( '001', '123' ), + MARC::Field->new( '245', '', '', a => 'Title' ), + MARC::Field->new( '650', '', '', a => 'Foo', 9 => $authid ), + MARC::Field->new( '999', '', '', c => '1234567' ), ); # sort_fields will call this and use the actual db values unless we call it first $see->get_elasticsearch_mappings(); - my $docs = $see->marc_records_to_documents([$marc_record_1]); + my $docs = $see->marc_records_to_documents( [$marc_record_1] ); - is_deeply($docs->[0]->{subject}, ['Foo', 'Bar'], 'subject should include "See from"'); - is_deeply($docs->[0]->{subject__facet}, ['Foo'], 'subject__facet should not include "See from"'); - is_deeply($docs->[0]->{subject__suggestion}, [{ input => 'Foo' }], 'subject__suggestion should not include "See from"'); - is_deeply($docs->[0]->{subject__sort}, ['Foo'], 'subject__sort should not include "See from"'); + is_deeply( $docs->[0]->{subject}, [ 'Foo', 'Bar' ], 'subject should include "See from"' ); + is_deeply( $docs->[0]->{subject__facet}, ['Foo'], 'subject__facet should not include "See from"' ); + is_deeply( + $docs->[0]->{subject__suggestion}, [ { input => 'Foo' } ], + 'subject__suggestion should not include "See from"' + ); + is_deeply( $docs->[0]->{subject__sort}, ['Foo'], 'subject__sort should not include "See from"' ); }; subtest 'marc_records_to_documents should set the "available" field' => sub { plan tests => 8; - t::lib::Mocks::mock_preference('marcflavour', 'MARC21'); + t::lib::Mocks::mock_preference( 'marcflavour', 'MARC21' ); my $dbh = C4::Context->dbh; my $se = Test::MockModule->new('Koha::SearchEngine::Elasticsearch'); $se->noop('_foreach_mapping'); - my $see = Koha::SearchEngine::Elasticsearch::Search->new({ index => $Koha::SearchEngine::Elasticsearch::BIBLIOS_INDEX }); + my $see = Koha::SearchEngine::Elasticsearch::Search->new( + { index => $Koha::SearchEngine::Elasticsearch::BIBLIOS_INDEX } ); # sort_fields will call this and use the actual db values unless we call it first $see->get_elasticsearch_mappings(); @@ -1079,45 +1176,52 @@ subtest 'marc_records_to_documents should set the "available" field' => sub { my $marc_record_1 = MARC::Record->new(); $marc_record_1->leader(' cam 22 a 4500'); $marc_record_1->append_fields( - MARC::Field->new('245', '', '', a => 'Title'), + MARC::Field->new( '245', '', '', a => 'Title' ), ); my ($biblionumber) = C4::Biblio::AddBiblio( $marc_record_1, '' ); - my $docs = $see->marc_records_to_documents([$marc_record_1]); - is_deeply($docs->[0]->{available}, \0, 'a biblio without items is not available'); + my $docs = $see->marc_records_to_documents( [$marc_record_1] ); + is_deeply( $docs->[0]->{available}, \0, 'a biblio without items is not available' ); - my $item = Koha::Item->new({ - biblionumber => $biblionumber, - })->store(); + my $item = Koha::Item->new( + { + biblionumber => $biblionumber, + } + )->store(); - $docs = $see->marc_records_to_documents([$marc_record_1]); - is_deeply($docs->[0]->{available}, \1, 'a biblio with one item that has no particular status is available'); + $docs = $see->marc_records_to_documents( [$marc_record_1] ); + is_deeply( $docs->[0]->{available}, \1, 'a biblio with one item that has no particular status is available' ); $item->notforloan(1)->store(); - $docs = $see->marc_records_to_documents([$marc_record_1]); - is_deeply($docs->[0]->{available}, \1, 'a biblio with one item that is "notforloan" is available'); + $docs = $see->marc_records_to_documents( [$marc_record_1] ); + is_deeply( $docs->[0]->{available}, \1, 'a biblio with one item that is "notforloan" is available' ); - $item->set({ notforloan => 0, onloan => '2022-03-03' })->store(); - $docs = $see->marc_records_to_documents([$marc_record_1]); - is_deeply($docs->[0]->{available}, \0, 'a biblio with one item that is on loan is not available'); + $item->set( { notforloan => 0, onloan => '2022-03-03' } )->store(); + $docs = $see->marc_records_to_documents( [$marc_record_1] ); + is_deeply( $docs->[0]->{available}, \0, 'a biblio with one item that is on loan is not available' ); - $item->set({ onloan => undef, withdrawn => 1 })->store(); - $docs = $see->marc_records_to_documents([$marc_record_1]); - is_deeply($docs->[0]->{available}, \1, 'a biblio with one item that is withdrawn is available'); + $item->set( { onloan => undef, withdrawn => 1 } )->store(); + $docs = $see->marc_records_to_documents( [$marc_record_1] ); + is_deeply( $docs->[0]->{available}, \1, 'a biblio with one item that is withdrawn is available' ); - $item->set({ withdrawn => 0, itemlost => 1 })->store(); - $docs = $see->marc_records_to_documents([$marc_record_1]); - is_deeply($docs->[0]->{available}, \0, 'a biblio with one item that is lost is not available'); + $item->set( { withdrawn => 0, itemlost => 1 } )->store(); + $docs = $see->marc_records_to_documents( [$marc_record_1] ); + is_deeply( $docs->[0]->{available}, \0, 'a biblio with one item that is lost is not available' ); - $item->set({ itemlost => 0, damaged => 1 })->store(); - $docs = $see->marc_records_to_documents([$marc_record_1]); - is_deeply($docs->[0]->{available}, \1, 'a biblio with one item that is damaged is available'); + $item->set( { itemlost => 0, damaged => 1 } )->store(); + $docs = $see->marc_records_to_documents( [$marc_record_1] ); + is_deeply( $docs->[0]->{available}, \1, 'a biblio with one item that is damaged is available' ); - my $item2 = Koha::Item->new({ - biblionumber => $biblionumber, - })->store(); - $docs = $see->marc_records_to_documents([$marc_record_1]); - is_deeply($docs->[0]->{available}, \1, 'a biblio with at least one item that has no particular status is available'); + my $item2 = Koha::Item->new( + { + biblionumber => $biblionumber, + } + )->store(); + $docs = $see->marc_records_to_documents( [$marc_record_1] ); + is_deeply( + $docs->[0]->{available}, \1, + 'a biblio with at least one item that has no particular status is available' + ); }; $schema->storage->txn_rollback; diff --git a/t/db_dependent/Koha/SearchEngine/Elasticsearch/ExportConfig.t b/t/db_dependent/Koha/SearchEngine/Elasticsearch/ExportConfig.t index b2328a8d46..9fc6f7b57c 100755 --- a/t/db_dependent/Koha/SearchEngine/Elasticsearch/ExportConfig.t +++ b/t/db_dependent/Koha/SearchEngine/Elasticsearch/ExportConfig.t @@ -33,89 +33,97 @@ Koha::SearchFields->search->delete; Koha::SearchMarcMaps->search->delete; $schema->resultset('SearchMarcToField')->search->delete; - - my $search_field = Koha::SearchFields->find_or_create( { - name => 'title', - label => 'Title', - type => 'string', - weight => 17, + name => 'title', + label => 'Title', + type => 'string', + weight => 17, staff_client => 0, opac => 1, mandatory => 1 }, - { key => 'name' } ); + { key => 'name' } +); my $marc_field = Koha::SearchMarcMaps->find_or_create( { index_name => 'biblios', - marc_type => 'marc21', + marc_type => 'marc21', marc_field => '247' - } ); + } +); -$search_field->add_to_search_marc_maps($marc_field, +$search_field->add_to_search_marc_maps( + $marc_field, { - facet => 0, + facet => 0, suggestible => 0, - sort => 0 - } ); + sort => 0 + } +); $marc_field = Koha::SearchMarcMaps->find_or_create( { index_name => 'biblios', - marc_type => 'marc21', + marc_type => 'marc21', marc_field => '212' - } ); + } +); -$search_field->add_to_search_marc_maps($marc_field, +$search_field->add_to_search_marc_maps( + $marc_field, { - facet => 0, + facet => 0, suggestible => 0, - sort => 0 - } ); + sort => 0 + } +); $marc_field = Koha::SearchMarcMaps->find_or_create( { index_name => 'biblios', - marc_type => 'unimarc', + marc_type => 'unimarc', marc_field => '200a' - } ); + } +); -$search_field->add_to_search_marc_maps($marc_field, +$search_field->add_to_search_marc_maps( + $marc_field, { - facet => 0, + facet => 0, suggestible => 1, - sort => 0 - } ); + sort => 0 + } +); my $mappings = Koha::SearchEngine::Elasticsearch::raw_elasticsearch_mappings(); -is( $mappings->{biblios}{title}{type}, 'string', 'Title is of type string'); -is( $mappings->{biblios}{title}{label}, 'Title', 'title has label Title'); -is( $mappings->{biblios}{title}{facet_order}, undef, 'Facet order is undef'); -is( $mappings->{biblios}{title}{opac}, 1, 'title is opac searchable'); -is( $mappings->{biblios}{title}{staff_client}, 0, 'title is not staff searchable'); -is( $mappings->{biblios}{title}{mandatory}, 1, 'title is mandatory'); +is( $mappings->{biblios}{title}{type}, 'string', 'Title is of type string' ); +is( $mappings->{biblios}{title}{label}, 'Title', 'title has label Title' ); +is( $mappings->{biblios}{title}{facet_order}, undef, 'Facet order is undef' ); +is( $mappings->{biblios}{title}{opac}, 1, 'title is opac searchable' ); +is( $mappings->{biblios}{title}{staff_client}, 0, 'title is not staff searchable' ); +is( $mappings->{biblios}{title}{mandatory}, 1, 'title is mandatory' ); -is(scalar(@{ $mappings->{biblios}{title}{mappings} }), 3, 'Title has 3 mappings'); +is( scalar( @{ $mappings->{biblios}{title}{mappings} } ), 3, 'Title has 3 mappings' ); my $f212_map = $mappings->{biblios}{title}{mappings}[0]; -is( $f212_map->{marc_field}, 212, 'First mapping is on field 212'); -is( $f212_map->{marc_type}, 'marc21', 'First mapping is for marc21'); -is( $f212_map->{facet}, '', 'First mapping facet is empty'); -is( $f212_map->{suggestible}, '', 'First mapping is not suggestible'); -is( $f212_map->{sort}, 0, 'First mapping is not sortable'); +is( $f212_map->{marc_field}, 212, 'First mapping is on field 212' ); +is( $f212_map->{marc_type}, 'marc21', 'First mapping is for marc21' ); +is( $f212_map->{facet}, '', 'First mapping facet is empty' ); +is( $f212_map->{suggestible}, '', 'First mapping is not suggestible' ); +is( $f212_map->{sort}, 0, 'First mapping is not sortable' ); my $f247_map = $mappings->{biblios}{title}{mappings}[1]; -is( $f247_map->{marc_field}, 247, 'Second mapping is on field 247'); -is( $f247_map->{marc_type}, 'marc21', 'Second mapping is for marc21'); -is( $f247_map->{facet}, '', 'Second mapping facet is empty'); -is( $f247_map->{suggestible}, '', 'Second mapping is not suggestible'); -is( $f247_map->{sort}, 0, 'Second mapping is not sortable'); +is( $f247_map->{marc_field}, 247, 'Second mapping is on field 247' ); +is( $f247_map->{marc_type}, 'marc21', 'Second mapping is for marc21' ); +is( $f247_map->{facet}, '', 'Second mapping facet is empty' ); +is( $f247_map->{suggestible}, '', 'Second mapping is not suggestible' ); +is( $f247_map->{sort}, 0, 'Second mapping is not sortable' ); $mappings = Koha::SearchEngine::Elasticsearch::raw_elasticsearch_mappings('unimarc'); -is(scalar(@{ $mappings->{biblios}{title}{mappings} }), 1, 'Title has 1 mappings'); +is( scalar( @{ $mappings->{biblios}{title}{mappings} } ), 1, 'Title has 1 mappings' ); $schema->storage->txn_rollback; diff --git a/t/db_dependent/Koha/SearchEngine/Elasticsearch/QueryBuilder.t b/t/db_dependent/Koha/SearchEngine/Elasticsearch/QueryBuilder.t index ca0e3666b6..2c0b746fac 100755 --- a/t/db_dependent/Koha/SearchEngine/Elasticsearch/QueryBuilder.t +++ b/t/db_dependent/Koha/SearchEngine/Elasticsearch/QueryBuilder.t @@ -33,75 +33,54 @@ use Koha::SearchFilters; my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; -my $se = Test::MockModule->new( 'Koha::SearchEngine::Elasticsearch' ); -$se->mock( 'get_elasticsearch_mappings', sub { - my ($self) = @_; +my $se = Test::MockModule->new('Koha::SearchEngine::Elasticsearch'); +$se->mock( + 'get_elasticsearch_mappings', + sub { + my ($self) = @_; - my %all_mappings; + my %all_mappings; - my $mappings = { - properties => { - title => { - type => 'text' - }, - title__sort => { - type => 'text' - }, - subject => { - type => 'text', - facet => 1 - }, - 'subject-heading-thesaurus' => { - type => 'text', - facet => 1 - }, - 'subject-heading-thesaurus-conventions' => { - type => 'text' - }, - itemnumber => { - type => 'integer' - }, - sortablenumber => { - type => 'integer' - }, - sortablenumber__sort => { - type => 'integer' - }, - heading => { - type => 'text' - }, - 'heading-main' => { - type => 'text' - }, - heading__sort => { - type => 'text' - }, - match => { - type => 'text' - }, - 'match-heading' => { - type => 'text' - }, - 'match-heading-see-from' => { - type => 'text' - }, - } - }; - $all_mappings{$self->index} = $mappings; + my $mappings = { + properties => { + title => { type => 'text' }, + title__sort => { type => 'text' }, + subject => { + type => 'text', + facet => 1 + }, + 'subject-heading-thesaurus' => { + type => 'text', + facet => 1 + }, + 'subject-heading-thesaurus-conventions' => { type => 'text' }, + itemnumber => { type => 'integer' }, + sortablenumber => { type => 'integer' }, + sortablenumber__sort => { type => 'integer' }, + heading => { type => 'text' }, + 'heading-main' => { type => 'text' }, + heading__sort => { type => 'text' }, + match => { type => 'text' }, + 'match-heading' => { type => 'text' }, + 'match-heading-see-from' => { type => 'text' }, + } + }; + $all_mappings{ $self->index } = $mappings; - my $sort_fields = { - $self->index => { - title => 1, - subject => 0, - itemnumber => 0, - sortablenumber => 1, - mainentry => 1 - } - }; - $self->sort_fields($sort_fields->{$self->index}); + my $sort_fields = { + $self->index => { + title => 1, + subject => 0, + itemnumber => 0, + sortablenumber => 1, + mainentry => 1 + } + }; + $self->sort_fields( $sort_fields->{ $self->index } ); - return $all_mappings{$self->index}; -}); + return $all_mappings{ $self->index }; + } +); subtest 'build_authorities_query_compat() tests' => sub { @@ -110,89 +89,115 @@ subtest 'build_authorities_query_compat() tests' => sub { my $qb; ok( - $qb = Koha::SearchEngine::Elasticsearch::QueryBuilder->new({ 'index' => 'authorities' }), + $qb = Koha::SearchEngine::Elasticsearch::QueryBuilder->new( { 'index' => 'authorities' } ), 'Creating new query builder object for authorities' ); my $koha_to_index_name = $Koha::SearchEngine::Elasticsearch::QueryBuilder::koha_to_index_name; - my $search_term = 'a'; - foreach my $koha_name ( keys %{ $koha_to_index_name } ) { - my $query = $qb->build_authorities_query_compat( [ $koha_name ], undef, undef, ['contains'], [$search_term], 'AUTH_TYPE', 'asc' ); + my $search_term = 'a'; + foreach my $koha_name ( keys %{$koha_to_index_name} ) { + my $query = $qb->build_authorities_query_compat( + [$koha_name], undef, undef, ['contains'], [$search_term], 'AUTH_TYPE', + 'asc' + ); if ( $koha_name eq 'all' || $koha_name eq 'any' ) { - is( $query->{query}->{bool}->{must}[0]->{query_string}->{query}, - "a*"); + is( + $query->{query}->{bool}->{must}[0]->{query_string}->{query}, + "a*" + ); } else { - is( $query->{query}->{bool}->{must}[0]->{query_string}->{query}, - "a*"); + is( + $query->{query}->{bool}->{must}[0]->{query_string}->{query}, + "a*" + ); } - is( $query->{query}->{bool}->{must}[0]->{query_string}->{analyze_wildcard}, JSON::true, 'Set analyze_wildcard true' ); + is( + $query->{query}->{bool}->{must}[0]->{query_string}->{analyze_wildcard}, JSON::true, + 'Set analyze_wildcard true' + ); is( $query->{query}->{bool}->{must}[0]->{query_string}->{lenient}, JSON::true, 'Set lenient true' ); } $search_term = 'Donald Duck'; - foreach my $koha_name ( keys %{ $koha_to_index_name } ) { - my $query = $qb->build_authorities_query_compat( [ $koha_name ], undef, undef, ['contains'], [$search_term], 'AUTH_TYPE', 'asc' ); + foreach my $koha_name ( keys %{$koha_to_index_name} ) { + my $query = $qb->build_authorities_query_compat( + [$koha_name], undef, undef, ['contains'], [$search_term], 'AUTH_TYPE', + 'asc' + ); is( $query->{query}->{bool}->{must}[0]->{query_string}->{query}, "(Donald*) AND (Duck*)" ); if ( $koha_name eq 'all' || $koha_name eq 'any' ) { - isa_ok( $query->{query}->{bool}->{must}[0]->{query_string}->{fields}, 'ARRAY') + isa_ok( $query->{query}->{bool}->{must}[0]->{query_string}->{fields}, 'ARRAY' ); } else { - is( $query->{query}->{bool}->{must}[0]->{query_string}->{default_field}, $koha_to_index_name->{$koha_name} ); + is( + $query->{query}->{bool}->{must}[0]->{query_string}->{default_field}, + $koha_to_index_name->{$koha_name} + ); } } - foreach my $koha_name ( keys %{ $koha_to_index_name } ) { - my $query = $qb->build_authorities_query_compat( [ $koha_name ], undef, undef, ['is'], [$search_term], 'AUTH_TYPE', 'asc' ); + foreach my $koha_name ( keys %{$koha_to_index_name} ) { + my $query = $qb->build_authorities_query_compat( + [$koha_name], undef, undef, ['is'], [$search_term], 'AUTH_TYPE', + 'asc' + ); if ( $koha_name eq 'all' || $koha_name eq 'any' ) { is( $query->{query}->{bool}->{must}[0]->{multi_match}->{query}, "Donald Duck" ); - my $all_matches = all { /\.ci_raw$/ } - @{$query->{query}->{bool}->{must}[0]->{multi_match}->{fields}}; + my $all_matches = all { /\.ci_raw$/ } @{ $query->{query}->{bool}->{must}[0]->{multi_match}->{fields} }; ok( $all_matches, 'Correct fields parameter for "is" query in "any" or "all"' ); } else { is( - $query->{query}->{bool}->{must}[0]->{term}->{$koha_to_index_name->{$koha_name} . ".ci_raw"}, + $query->{query}->{bool}->{must}[0]->{term}->{ $koha_to_index_name->{$koha_name} . ".ci_raw" }, "Donald Duck" ); } } - foreach my $koha_name ( keys %{ $koha_to_index_name } ) { - my $query = $qb->build_authorities_query_compat( [ $koha_name ], undef, undef, ['start'], [$search_term], 'AUTH_TYPE', 'asc' ); + foreach my $koha_name ( keys %{$koha_to_index_name} ) { + my $query = $qb->build_authorities_query_compat( + [$koha_name], undef, undef, ['start'], [$search_term], 'AUTH_TYPE', + 'asc' + ); if ( $koha_name eq 'all' || $koha_name eq 'any' ) { - my $all_matches = all { (%{$_->{prefix}})[0] =~ /\.ci_raw$/ && (%{$_->{prefix}})[1] eq "Donald Duck" } - @{$query->{query}->{bool}->{must}[0]->{bool}->{should}}; + my $all_matches = + all { ( %{ $_->{prefix} } )[0] =~ /\.ci_raw$/ && ( %{ $_->{prefix} } )[1] eq "Donald Duck" } + @{ $query->{query}->{bool}->{must}[0]->{bool}->{should} }; ok( $all_matches, "Correct multiple prefix query" ); } else { - is( $query->{query}->{bool}->{must}[0]->{prefix}->{$koha_to_index_name->{$koha_name} . ".ci_raw"}, "Donald Duck" ); + is( + $query->{query}->{bool}->{must}[0]->{prefix}->{ $koha_to_index_name->{$koha_name} . ".ci_raw" }, + "Donald Duck" + ); } } # Sorting - my $query = $qb->build_authorities_query_compat( [ 'mainentry' ], undef, undef, ['start'], [$search_term], 'AUTH_TYPE', 'HeadingAsc' ); + my $query = $qb->build_authorities_query_compat( + ['mainentry'], undef, undef, ['start'], [$search_term], 'AUTH_TYPE', + 'HeadingAsc' + ); is_deeply( $query->{sort}, - [ - { - 'heading__sort' => 'asc' - } - ], + [ { 'heading__sort' => 'asc' } ], "ascending sort parameter properly formed" ); - $query = $qb->build_authorities_query_compat( [ 'mainentry' ], undef, undef, ['start'], [$search_term], 'AUTH_TYPE', 'HeadingDsc' ); + $query = $qb->build_authorities_query_compat( + ['mainentry'], undef, undef, ['start'], [$search_term], 'AUTH_TYPE', + 'HeadingDsc' + ); is_deeply( $query->{sort}, - [ - { - 'heading__sort' => 'desc' - } - ], + [ { 'heading__sort' => 'desc' } ], "descending sort parameter properly formed" ); # Authorities type - $query = $qb->build_authorities_query_compat( [ 'mainentry' ], undef, undef, ['contains'], [$search_term], 'AUTH_TYPE', 'asc' ); + $query = $qb->build_authorities_query_compat( + ['mainentry'], undef, undef, ['contains'], [$search_term], 'AUTH_TYPE', + 'asc' + ); is_deeply( $query->{query}->{bool}->{filter}, { term => { 'authtype.raw' => 'AUTH_TYPE' } }, @@ -201,10 +206,13 @@ subtest 'build_authorities_query_compat() tests' => sub { # Authorities marclist check warning_like { - $query = $qb->build_authorities_query_compat( [ 'tomas','mainentry' ], undef, undef, ['contains'], [$search_term,$search_term], 'AUTH_TYPE', 'asc' ) + $query = $qb->build_authorities_query_compat( + [ 'tomas', 'mainentry' ], undef, undef, ['contains'], + [ $search_term, $search_term ], 'AUTH_TYPE', 'asc' + ) } qr/Unknown search field tomas/, - "Warning for unknown field in marclist"; + "Warning for unknown field in marclist"; is_deeply( $query->{query}->{bool}->{must}[0]->{query_string}->{default_field}, 'tomas', @@ -224,35 +232,35 @@ subtest 'build_query tests' => sub { my $qb; ok( - $qb = Koha::SearchEngine::Elasticsearch::QueryBuilder->new({ 'index' => 'biblios' }), + $qb = Koha::SearchEngine::Elasticsearch::QueryBuilder->new( { 'index' => 'biblios' } ), 'Creating new query builder object for biblios' ); - my @sort_by = 'title_asc'; + my @sort_by = 'title_asc'; my @sort_params = $qb->_convert_sort_fields(@sort_by); my %options; $options{sort} = \@sort_params; - my $query = $qb->build_query('test', %options); + my $query = $qb->build_query( 'test', %options ); is_deeply( $query->{sort}, - [ - { - 'title__sort' => { - 'order' => 'asc' - } - } - ], + [ { 'title__sort' => { 'order' => 'asc' } } ], "sort parameter properly formed" ); - t::lib::Mocks::mock_preference('FacetMaxCount','37'); - t::lib::Mocks::mock_preference('DisplayLibraryFacets','both'); - $query = $qb->build_query('test', %options); - ok( defined $query->{aggregations}{ccode}{terms}{size},'we need to ask for a size or we get only 5 facet' ); - is( $query->{aggregations}{ccode}{terms}{size}, 37,'we ask for the size as defined by the syspref FacetMaxCount'); - is( $query->{aggregations}{homebranch}{terms}{size}, 37,'we ask for the size as defined by the syspref FacetMaxCount for homebranch'); - is( $query->{aggregations}{holdingbranch}{terms}{size}, 37,'we ask for the size as defined by the syspref FacetMaxCount for holdingbranch'); + t::lib::Mocks::mock_preference( 'FacetMaxCount', '37' ); + t::lib::Mocks::mock_preference( 'DisplayLibraryFacets', 'both' ); + $query = $qb->build_query( 'test', %options ); + ok( defined $query->{aggregations}{ccode}{terms}{size}, 'we need to ask for a size or we get only 5 facet' ); + is( $query->{aggregations}{ccode}{terms}{size}, 37, 'we ask for the size as defined by the syspref FacetMaxCount' ); + is( + $query->{aggregations}{homebranch}{terms}{size}, 37, + 'we ask for the size as defined by the syspref FacetMaxCount for homebranch' + ); + is( + $query->{aggregations}{holdingbranch}{terms}{size}, 37, + 'we ask for the size as defined by the syspref FacetMaxCount for holdingbranch' + ); t::lib::Mocks::mock_preference( 'QueryAutoTruncate', '' ); @@ -277,17 +285,18 @@ subtest 'build_query tests' => sub { 'multiple words in a query term are enclosed in parenthesis' ); - ( undef, $query ) = $qb->build_query_compat( ['AND'], ['donald duck', 'disney'], ['title', 'author'] ); + ( undef, $query ) = $qb->build_query_compat( ['AND'], [ 'donald duck', 'disney' ], [ 'title', 'author' ] ); is( $query->{query}{query_string}{query}, '(title:(donald duck)) AND (author:disney)', 'multiple query terms are enclosed in parenthesis while a single one is not' ); - my ($simple_query, $query_cgi, $query_desc); - ( undef, $query, $simple_query, $query_cgi, $query_desc ) = $qb->build_query_compat( undef, ['"donald duck"', 'walt disney'], ['ti', 'au'] ); - is($query_cgi, 'idx=ti&q=%22donald%20duck%22&idx=au&q=walt%20disney', 'query cgi ok for multiterm query'); - is($query_desc, '(title:("donald duck")) (author:(walt disney))', 'query desc ok for multiterm query'); + my ( $simple_query, $query_cgi, $query_desc ); + ( undef, $query, $simple_query, $query_cgi, $query_desc ) = + $qb->build_query_compat( undef, [ '"donald duck"', 'walt disney' ], [ 'ti', 'au' ] ); + is( $query_cgi, 'idx=ti&q=%22donald%20duck%22&idx=au&q=walt%20disney', 'query cgi ok for multiterm query' ); + is( $query_desc, '(title:("donald duck")) (author:(walt disney))', 'query desc ok for multiterm query' ); ( undef, $query ) = $qb->build_query_compat( undef, ['2019'], ['yr,st-year'] ); is( @@ -324,8 +333,10 @@ subtest 'build_query tests' => sub { 'Open end year in year range of an st-year search is handled properly' ); - ( undef, $query ) = $qb->build_query_compat( undef, ['2019-'], ['yr,st-year'], - ['yr,st-numeric:-2019','yr,st-numeric:2005','yr,st-numeric:1984-2022'] ); + ( undef, $query ) = $qb->build_query_compat( + undef, ['2019-'], ['yr,st-year'], + [ 'yr,st-numeric:-2019', 'yr,st-numeric:2005', 'yr,st-numeric:1984-2022' ] + ); is( $query->{query}{query_string}{query}, '(date-of-publication:[2019 TO *]) AND (date-of-publication:[* TO 2019]) AND (date-of-publication:2005) AND (date-of-publication:[1984 TO 2022])', @@ -343,8 +354,10 @@ subtest 'build_query tests' => sub { ); # Ensure reserved words are not truncated - ( undef, $query ) = $qb->build_query_compat( undef, - ['donald or duck and mickey not mouse'] ); + ( undef, $query ) = $qb->build_query_compat( + undef, + ['donald or duck and mickey not mouse'] + ); is( $query->{query}{query_string}{query}, "(donald* or duck* and mickey* not mouse*)", @@ -379,7 +392,6 @@ subtest 'build_query tests' => sub { "query with quotes is unaltered when QueryAutoTruncate is enabled" ); - ( undef, $query ) = $qb->build_query_compat( undef, ['"donald duck" and "the mouse"'] ); is( $query->{query}{query_string}{query}, @@ -570,51 +582,63 @@ subtest 'build_query tests' => sub { 'words of a multi-word term are properly truncated' ); - ( undef, $query ) = $qb->build_query_compat( ['AND'], ['donald duck', 'disney'], ['title', 'author'] ); + ( undef, $query ) = $qb->build_query_compat( ['AND'], [ 'donald duck', 'disney' ], [ 'title', 'author' ] ); is( $query->{query}{query_string}{query}, '(title:(donald* duck*)) AND (author:disney*)', 'words of a multi-word term and single-word term are properly truncated' ); - ( undef, $query ) = $qb->build_query_compat( undef, ['title:"donald duck"'], undef, undef, undef, undef, undef, { suppress => 1 } ); + ( undef, $query ) = + $qb->build_query_compat( undef, ['title:"donald duck"'], undef, undef, undef, undef, undef, { suppress => 1 } ); is( $query->{query}{query_string}{query}, '(title:"donald duck") AND suppress:false', "query of specific field is added AND suppress:false" ); - ( undef, $query, $simple_query, $query_cgi, $query_desc ) = $qb->build_query_compat( undef, ['title:"donald duck"'], undef, undef, undef, undef, undef, { suppress => 0 } ); + ( undef, $query, $simple_query, $query_cgi, $query_desc ) = + $qb->build_query_compat( undef, ['title:"donald duck"'], undef, undef, undef, undef, undef, { suppress => 0 } ); is( $query->{query}{query_string}{query}, '(title:"donald duck")', "query of specific field is not added AND suppress:0" ); - ( undef, $query ) = $qb->build_query_compat( ['AND'], ['title:"donald duck"'], undef, ['author:Dillinger Escaplan'] ); + ( undef, $query ) = + $qb->build_query_compat( ['AND'], ['title:"donald duck"'], undef, ['author:Dillinger Escaplan'] ); is( $query->{query}{query_string}{query}, '(title:"donald duck") AND author:("Dillinger Escaplan")', "Simple query with limit term quoted in parentheses" ); - ( undef, $query ) = $qb->build_query_compat( ['AND'], ['title:"donald duck"'], undef, ['author:Dillinger Escaplan', 'itype:BOOK'] ); + ( undef, $query ) = $qb->build_query_compat( + ['AND'], ['title:"donald duck"'], undef, + [ 'author:Dillinger Escaplan', 'itype:BOOK' ] + ); is( $query->{query}{query_string}{query}, '(title:"donald duck") AND (author:("Dillinger Escaplan")) AND (itype:("BOOK"))', "Simple query with each limit's term quoted in parentheses" ); - is($query_cgi, 'idx=&q=title%3A%22donald%20duck%22', 'query cgi'); - is($query_desc, 'title:"donald duck"', 'query desc ok'); + is( $query_cgi, 'idx=&q=title%3A%22donald%20duck%22', 'query cgi' ); + is( $query_desc, 'title:"donald duck"', 'query desc ok' ); - ( undef, $query ) = $qb->build_query_compat( ['AND'], ['title:"donald duck"'], undef, ['author:Dillinger Escaplan', 'mc-itype,phr:BOOK', 'mc-itype,phr:CD'] ); + ( undef, $query ) = $qb->build_query_compat( + ['AND'], ['title:"donald duck"'], undef, + [ 'author:Dillinger Escaplan', 'mc-itype,phr:BOOK', 'mc-itype,phr:CD' ] + ); is( $query->{query}{query_string}{query}, '(title:"donald duck") AND (author:("Dillinger Escaplan")) AND itype:(("BOOK") OR ("CD"))', "Limits quoted correctly when passed as phrase" ); - ( undef, $query ) = $qb->build_query_compat( ['OR'], ['title:"donald duck"', 'author:"Dillinger Escaplan"'], undef, ['itype:BOOK'] ); + ( undef, $query ) = $qb->build_query_compat( + ['OR'], [ 'title:"donald duck"', 'author:"Dillinger Escaplan"' ], undef, + ['itype:BOOK'] + ); is( $query->{query}{query_string}{query}, '((title:"donald duck") OR (author:"Dillinger Escaplan")) AND itype:("BOOK")', @@ -629,7 +653,8 @@ subtest 'build_query tests' => sub { ); # Scan queries - ( undef, $query, $simple_query, $query_cgi, $query_desc ) = $qb->build_query_compat( undef, ['new'], ['au'], undef, undef, 1 ); + ( undef, $query, $simple_query, $query_cgi, $query_desc ) = + $qb->build_query_compat( undef, ['new'], ['au'], undef, undef, 1 ); is( $query->{query}{query_string}{query}, '*', @@ -638,16 +663,17 @@ subtest 'build_query tests' => sub { is_deeply( $query->{aggregations}{'author'}{'terms'}, { - field => 'author__facet', - order => { '_key' => 'asc' }, + field => 'author__facet', + order => { '_key' => 'asc' }, include => '[nN][eE][wW].*' }, "scan aggregation request is properly formed" ); - is($query_cgi, 'idx=au&q=new&scan=1', 'query cgi'); - is($query_desc, 'new', 'query desc ok'); + is( $query_cgi, 'idx=au&q=new&scan=1', 'query cgi' ); + is( $query_desc, 'new', 'query desc ok' ); - ( undef, $query, $simple_query, $query_cgi, $query_desc ) = $qb->build_query_compat( undef, ['new'], [], undef, undef, 1 ); + ( undef, $query, $simple_query, $query_cgi, $query_desc ) = + $qb->build_query_compat( undef, ['new'], [], undef, undef, 1 ); is( $query->{query}{query_string}{query}, '*', @@ -656,20 +682,33 @@ subtest 'build_query tests' => sub { is_deeply( $query->{aggregations}{'subject'}{'terms'}, { - field => 'subject__facet', - order => { '_key' => 'asc' }, + field => 'subject__facet', + order => { '_key' => 'asc' }, include => '[nN][eE][wW].*' }, "scan aggregation request is properly formed" ); - is($query_cgi, 'idx=&q=new&scan=1', 'query cgi'); - is($query_desc, 'new', 'query desc ok'); + is( $query_cgi, 'idx=&q=new&scan=1', 'query cgi' ); + is( $query_desc, 'new', 'query desc ok' ); - my( $limit, $limit_cgi, $limit_desc ); - ( undef, $query, $simple_query, $query_cgi, $query_desc, $limit, $limit_cgi, $limit_desc ) = $qb->build_query_compat( ['AND'], ['kw:""'], undef, ['author:Dillinger Escaplan', 'mc-itype,phr:BOOK', 'mc-itype,phr:CD'] ); - is( $limit, '(author:("Dillinger Escaplan")) AND itype:(("BOOK") OR ("CD"))', "Limit formed correctly when no search terms"); - is( $limit_cgi,'&limit=author%3ADillinger%20Escaplan&limit=mc-itype%2Cphr%3ABOOK&limit=mc-itype%2Cphr%3ACD', "Limit CGI formed correctly when no search terms"); - is( $limit_desc,'(author:("Dillinger Escaplan")) AND itype:(("BOOK") OR ("CD"))',"Limit desc formed correctly when no search terms"); + my ( $limit, $limit_cgi, $limit_desc ); + ( undef, $query, $simple_query, $query_cgi, $query_desc, $limit, $limit_cgi, $limit_desc ) = + $qb->build_query_compat( + ['AND'], ['kw:""'], undef, + [ 'author:Dillinger Escaplan', 'mc-itype,phr:BOOK', 'mc-itype,phr:CD' ] + ); + is( + $limit, '(author:("Dillinger Escaplan")) AND itype:(("BOOK") OR ("CD"))', + "Limit formed correctly when no search terms" + ); + is( + $limit_cgi, '&limit=author%3ADillinger%20Escaplan&limit=mc-itype%2Cphr%3ABOOK&limit=mc-itype%2Cphr%3ACD', + "Limit CGI formed correctly when no search terms" + ); + is( + $limit_desc, '(author:("Dillinger Escaplan")) AND itype:(("BOOK") OR ("CD"))', + "Limit desc formed correctly when no search terms" + ); ( undef, $query ) = $qb->build_query_compat( undef, ['barcode123123'], ['bc'], @@ -712,134 +751,160 @@ subtest 'build_query tests' => sub { ); }; - subtest 'build query from form subtests' => sub { plan tests => 5; - my $qb = Koha::SearchEngine::Elasticsearch::QueryBuilder->new({ 'index' => 'authorities' }), - #when searching for authorities from a record the form returns marclist with blanks for unentered terms - my @marclist = ('mainmainentry','mainentry','match', 'all'); - my @values = ( undef, 'Hamilton', undef, undef); - my @operator = ( 'contains', 'contains', 'contains', 'contains'); + my $qb = Koha::SearchEngine::Elasticsearch::QueryBuilder->new( { 'index' => 'authorities' } ), - my $query = $qb->build_authorities_query_compat( \@marclist, undef, - undef, \@operator , \@values, 'AUTH_TYPE', 'asc' ); - is($query->{query}->{bool}->{must}[0]->{query_string}->{query}, "Hamilton*","Expected search is populated"); - is( scalar @{ $query->{query}->{bool}->{must} }, 1,"Only defined search is populated"); + #when searching for authorities from a record the form returns marclist with blanks for unentered terms + my @marclist = ( 'mainmainentry', 'mainentry', 'match', 'all' ); + my @values = ( undef, 'Hamilton', undef, undef ); + my @operator = ( 'contains', 'contains', 'contains', 'contains' ); + + my $query = $qb->build_authorities_query_compat( + \@marclist, undef, + undef, \@operator, \@values, 'AUTH_TYPE', 'asc' + ); + is( $query->{query}->{bool}->{must}[0]->{query_string}->{query}, "Hamilton*", "Expected search is populated" ); + is( scalar @{ $query->{query}->{bool}->{must} }, 1, "Only defined search is populated" ); @values[2] = 'Jefferson'; - $query = $qb->build_authorities_query_compat( \@marclist, undef, - undef, \@operator , \@values, 'AUTH_TYPE', 'asc' ); - is($query->{query}->{bool}->{must}[0]->{query_string}->{query}, "Hamilton*","First index searched as expected"); - is($query->{query}->{bool}->{must}[1]->{query_string}->{query}, "Jefferson*","Second index searched when populated"); - is( scalar @{ $query->{query}->{bool}->{must} }, 2,"Only defined searches are populated"); - + $query = $qb->build_authorities_query_compat( + \@marclist, undef, + undef, \@operator, \@values, 'AUTH_TYPE', 'asc' + ); + is( $query->{query}->{bool}->{must}[0]->{query_string}->{query}, "Hamilton*", "First index searched as expected" ); + is( + $query->{query}->{bool}->{must}[1]->{query_string}->{query}, "Jefferson*", + "Second index searched when populated" + ); + is( scalar @{ $query->{query}->{bool}->{must} }, 2, "Only defined searches are populated" ); }; subtest 'build_query with weighted fields tests' => sub { plan tests => 6; - $se->mock( '_load_elasticsearch_mappings', sub { - return { - authorities => { - Heading => { - label => 'heading', - type => 'string', - opac => 0, - staff_client => 1, - mappings => [{ - marc_field => '150', - marc_type => 'marc21', - }] + $se->mock( + '_load_elasticsearch_mappings', + sub { + return { + authorities => { + Heading => { + label => 'heading', + type => 'string', + opac => 0, + staff_client => 1, + mappings => [ + { + marc_field => '150', + marc_type => 'marc21', + } + ] + }, + Headingmain => { + label => 'headingmain', + type => 'string', + opac => 1, + staff_client => 1, + mappings => [ + { + marc_field => '150', + marc_type => 'marc21', + } + ] + } }, - Headingmain => { - label => 'headingmain', - type => 'string', - opac => 1, - staff_client => 1, - mappings => [{ - marc_field => '150', - marc_type => 'marc21', - }] + biblios => { + abstract => { + label => 'abstract', + type => 'string', + opac => 1, + staff_client => 0, + mappings => [ + { + marc_field => '520', + marc_type => 'marc21', + } + ] + }, + acqdate => { + label => 'acqdate', + type => 'string', + opac => 0, + staff_client => 1, + mappings => [ + { + marc_field => '952d', + marc_type => 'marc21', + search => 0, + }, + { + marc_field => '9955', + marc_type => 'marc21', + search => 0, + } + ] + }, + title => { + label => 'title', + type => 'string', + opac => 0, + staff_client => 1, + mappings => [ + { + marc_field => '130', + marc_type => 'marc21' + } + ] + }, + subject => { + label => 'subject', + type => 'string', + opac => 0, + staff_client => 1, + mappings => [ + { + marc_field => '600a', + marc_type => 'marc21' + } + ] + } } - }, - biblios => { - abstract => { - label => 'abstract', - type => 'string', - opac => 1, - staff_client => 0, - mappings => [{ - marc_field => '520', - marc_type => 'marc21', - }] - }, - acqdate => { - label => 'acqdate', - type => 'string', - opac => 0, - staff_client => 1, - mappings => [{ - marc_field => '952d', - marc_type => 'marc21', - search => 0, - }, { - marc_field => '9955', - marc_type => 'marc21', - search => 0, - }] - }, - title => { - label => 'title', - type => 'string', - opac => 0, - staff_client => 1, - mappings => [{ - marc_field => '130', - marc_type => 'marc21' - }] - }, - subject => { - label => 'subject', - type => 'string', - opac => 0, - staff_client => 1, - mappings => [{ - marc_field => '600a', - marc_type => 'marc21' - }] - } - } - }; - }); + }; + } + ); my $qb = Koha::SearchEngine::Elasticsearch::QueryBuilder->new( { index => 'biblios' } ); - Koha::SearchFields->search({})->delete; + Koha::SearchFields->search( {} )->delete; Koha::SearchEngine::Elasticsearch->reset_elasticsearch_mappings(); my $search_field; - $search_field = Koha::SearchFields->find({ name => 'title' }); - $search_field->update({ weight => 25.0 }); - $search_field = Koha::SearchFields->find({ name => 'subject' }); - $search_field->update({ weight => 15.5 }); + $search_field = Koha::SearchFields->find( { name => 'title' } ); + $search_field->update( { weight => 25.0 } ); + $search_field = Koha::SearchFields->find( { name => 'subject' } ); + $search_field->update( { weight => 15.5 } ); Koha::SearchEngine::Elasticsearch->clear_search_fields_cache(); - my ( undef, $query ) = $qb->build_query_compat( undef, ['title:"donald duck"'], undef, undef, - undef, undef, undef, { weighted_fields => 1 }); + my ( undef, $query ) = $qb->build_query_compat( + undef, ['title:"donald duck"'], undef, undef, + undef, undef, undef, { weighted_fields => 1 } + ); my $fields = $query->{query}{query_string}{fields}; - is(@{$fields}, 2, 'Search field with no searchable mappings has been excluded'); + is( @{$fields}, 2, 'Search field with no searchable mappings has been excluded' ); my @found = grep { $_ eq 'title^25.00' } @{$fields}; - is(@found, 1, 'Search field title has correct weight'); + is( @found, 1, 'Search field title has correct weight' ); @found = grep { $_ eq 'subject^15.50' } @{$fields}; - is(@found, 1, 'Search field subject has correct weight'); + is( @found, 1, 'Search field subject has correct weight' ); - ( undef, $query ) = $qb->build_query_compat( undef, ['title:"donald duck"'], undef, undef, - undef, undef, undef, { weighted_fields => 1, is_opac => 1 }); + ( undef, $query ) = $qb->build_query_compat( + undef, ['title:"donald duck"'], undef, undef, + undef, undef, undef, { weighted_fields => 1, is_opac => 1 } + ); $fields = $query->{query}{query_string}{fields}; @@ -850,15 +915,19 @@ subtest 'build_query with weighted fields tests' => sub { ); $qb = Koha::SearchEngine::Elasticsearch::QueryBuilder->new( { index => 'authorities' } ); - ( undef, $query ) = $qb->build_query_compat( undef, ['title:"donald duck"'], undef, undef, - undef, undef, undef, { weighted_fields => 1 }); + ( undef, $query ) = $qb->build_query_compat( + undef, ['title:"donald duck"'], undef, undef, + undef, undef, undef, { weighted_fields => 1 } + ); $fields = $query->{query}{query_string}{fields}; - is_deeply( [sort @$fields], ['heading','headingmain'],'Authorities fields retrieve for authorities index'); + is_deeply( [ sort @$fields ], [ 'heading', 'headingmain' ], 'Authorities fields retrieve for authorities index' ); - ( undef, $query ) = $qb->build_query_compat( undef, ['title:"donald duck"'], undef, undef, - undef, undef, undef, { weighted_fields => 1, is_opac => 1 }); + ( undef, $query ) = $qb->build_query_compat( + undef, ['title:"donald duck"'], undef, undef, + undef, undef, undef, { weighted_fields => 1, is_opac => 1 } + ); $fields = $query->{query}{query_string}{fields}; - is_deeply($fields,['headingmain'],'Only opac authorities fields retrieved for authorities index is is_opac'); + is_deeply( $fields, ['headingmain'], 'Only opac authorities fields retrieved for authorities index is is_opac' ); }; @@ -870,65 +939,103 @@ subtest 'build_query_compat() SearchLimitLibrary tests' => sub { my $builder = t::lib::TestBuilder->new; - my $branch_1 = $builder->build_object({ class => 'Koha::Libraries' }); - my $branch_2 = $builder->build_object({ class => 'Koha::Libraries' }); - my $group = $builder->build_object({ class => 'Koha::Library::Groups', value => { - ft_search_groups_opac => 1, - ft_search_groups_staff => 1, - parent_id => undef, - branchcode => undef + my $branch_1 = $builder->build_object( { class => 'Koha::Libraries' } ); + my $branch_2 = $builder->build_object( { class => 'Koha::Libraries' } ); + my $group = $builder->build_object( + { + class => 'Koha::Library::Groups', + value => { + ft_search_groups_opac => 1, + ft_search_groups_staff => 1, + parent_id => undef, + branchcode => undef + } } - }); - my $group_1 = $builder->build_object({ class => 'Koha::Library::Groups', value => { - parent_id => $group->id, - branchcode => $branch_1->id + ); + my $group_1 = $builder->build_object( + { + class => 'Koha::Library::Groups', + value => { + parent_id => $group->id, + branchcode => $branch_1->id + } } - }); - my $group_2 = $builder->build_object({ class => 'Koha::Library::Groups', value => { - parent_id => $group->id, - branchcode => $branch_2->id + ); + my $group_2 = $builder->build_object( + { + class => 'Koha::Library::Groups', + value => { + parent_id => $group->id, + branchcode => $branch_2->id + } } - }); - my $groupid = $group->id; + ); + my $groupid = $group->id; my @branchcodes = sort { $a cmp $b } ( $branch_1->id, $branch_2->id ); - - my $query_builder = Koha::SearchEngine::Elasticsearch::QueryBuilder->new({index => $Koha::SearchEngine::BIBLIOS_INDEX}); - t::lib::Mocks::mock_preference('SearchLimitLibrary', 'both'); + my $query_builder = + Koha::SearchEngine::Elasticsearch::QueryBuilder->new( { index => $Koha::SearchEngine::BIBLIOS_INDEX } ); + t::lib::Mocks::mock_preference( 'SearchLimitLibrary', 'both' ); my ( undef, undef, undef, undef, undef, $limit, $limit_cgi, $limit_desc, undef ) = - $query_builder->build_query_compat( undef, undef, undef, [ "branch:CPL" ], undef, undef, undef, undef ); - is( $limit, '(homebranch: "CPL" OR holdingbranch: "CPL")', "Branch limit expanded to home/holding branch"); - is( $limit_desc, '(homebranch: "CPL" OR holdingbranch: "CPL")', "Limit description correctly expanded"); - is( $limit_cgi, '&limit=branch%3ACPL', "Limit cgi does not get expanded"); - ( undef, undef, undef, undef, undef, $limit, $limit_cgi, $limit_desc, undef ) = - $query_builder->build_query_compat( undef, undef, undef, [ "multibranchlimit:$groupid" ], undef, undef, undef, undef ); - is( $limit, "(homebranch: \"$branchcodes[0]\" OR homebranch: \"$branchcodes[1]\" OR holdingbranch: \"$branchcodes[0]\" OR holdingbranch: \"$branchcodes[1]\")", "Multibranch limit expanded to home/holding branches"); - is( $limit_desc, "(homebranch: \"$branchcodes[0]\" OR homebranch: \"$branchcodes[1]\" OR holdingbranch: \"$branchcodes[0]\" OR holdingbranch: \"$branchcodes[1]\")", "Multibranch limit description correctly expanded"); - is( $limit_cgi, "&limit=multibranchlimit%3A$groupid", "Multibranch limit cgi does not get expanded"); + $query_builder->build_query_compat( undef, undef, undef, ["branch:CPL"], undef, undef, undef, undef ); + is( $limit, '(homebranch: "CPL" OR holdingbranch: "CPL")', "Branch limit expanded to home/holding branch" ); + is( $limit_desc, '(homebranch: "CPL" OR holdingbranch: "CPL")', "Limit description correctly expanded" ); + is( $limit_cgi, '&limit=branch%3ACPL', "Limit cgi does not get expanded" ); + ( undef, undef, undef, undef, undef, $limit, $limit_cgi, $limit_desc, undef ) = $query_builder->build_query_compat( + undef, undef, undef, ["multibranchlimit:$groupid"], undef, undef, undef, + undef + ); + is( + $limit, + "(homebranch: \"$branchcodes[0]\" OR homebranch: \"$branchcodes[1]\" OR holdingbranch: \"$branchcodes[0]\" OR holdingbranch: \"$branchcodes[1]\")", + "Multibranch limit expanded to home/holding branches" + ); + is( + $limit_desc, + "(homebranch: \"$branchcodes[0]\" OR homebranch: \"$branchcodes[1]\" OR holdingbranch: \"$branchcodes[0]\" OR holdingbranch: \"$branchcodes[1]\")", + "Multibranch limit description correctly expanded" + ); + is( $limit_cgi, "&limit=multibranchlimit%3A$groupid", "Multibranch limit cgi does not get expanded" ); - t::lib::Mocks::mock_preference('SearchLimitLibrary', 'homebranch'); + t::lib::Mocks::mock_preference( 'SearchLimitLibrary', 'homebranch' ); ( undef, undef, undef, undef, undef, $limit, $limit_cgi, $limit_desc, undef ) = - $query_builder->build_query_compat( undef, undef, undef, [ "branch:CPL" ], undef, undef, undef, undef ); - is( $limit, "(homebranch: \"CPL\")", "branch limit expanded to home branch"); - is( $limit_desc, "(homebranch: \"CPL\")", "limit description correctly expanded"); - is( $limit_cgi, "&limit=branch%3ACPL", "limit cgi does not get expanded"); - ( undef, undef, undef, undef, undef, $limit, $limit_cgi, $limit_desc, undef ) = - $query_builder->build_query_compat( undef, undef, undef, [ "multibranchlimit:$groupid" ], undef, undef, undef, undef ); - is( $limit, "(homebranch: \"$branchcodes[0]\" OR homebranch: \"$branchcodes[1]\")", "branch limit expanded to home branch"); - is( $limit_desc, "(homebranch: \"$branchcodes[0]\" OR homebranch: \"$branchcodes[1]\")", "limit description correctly expanded"); - is( $limit_cgi, "&limit=multibranchlimit%3A$groupid", "Limit cgi does not get expanded"); + $query_builder->build_query_compat( undef, undef, undef, ["branch:CPL"], undef, undef, undef, undef ); + is( $limit, "(homebranch: \"CPL\")", "branch limit expanded to home branch" ); + is( $limit_desc, "(homebranch: \"CPL\")", "limit description correctly expanded" ); + is( $limit_cgi, "&limit=branch%3ACPL", "limit cgi does not get expanded" ); + ( undef, undef, undef, undef, undef, $limit, $limit_cgi, $limit_desc, undef ) = $query_builder->build_query_compat( + undef, undef, undef, ["multibranchlimit:$groupid"], undef, undef, undef, + undef + ); + is( + $limit, "(homebranch: \"$branchcodes[0]\" OR homebranch: \"$branchcodes[1]\")", + "branch limit expanded to home branch" + ); + is( + $limit_desc, "(homebranch: \"$branchcodes[0]\" OR homebranch: \"$branchcodes[1]\")", + "limit description correctly expanded" + ); + is( $limit_cgi, "&limit=multibranchlimit%3A$groupid", "Limit cgi does not get expanded" ); - t::lib::Mocks::mock_preference('SearchLimitLibrary', 'holdingbranch'); + t::lib::Mocks::mock_preference( 'SearchLimitLibrary', 'holdingbranch' ); ( undef, undef, undef, undef, undef, $limit, $limit_cgi, $limit_desc, undef ) = - $query_builder->build_query_compat( undef, undef, undef, [ "branch:CPL" ], undef, undef, undef, undef ); - is( $limit, "(holdingbranch: \"CPL\")", "branch limit expanded to holding branch"); - is( $limit_desc, "(holdingbranch: \"CPL\")", "Limit description correctly expanded"); - is( $limit_cgi, "&limit=branch%3ACPL", "Limit cgi does not get expanded"); - ( undef, undef, undef, undef, undef, $limit, $limit_cgi, $limit_desc, undef ) = - $query_builder->build_query_compat( undef, undef, undef, [ "multibranchlimit:$groupid" ], undef, undef, undef, undef ); - is( $limit, "(holdingbranch: \"$branchcodes[0]\" OR holdingbranch: \"$branchcodes[1]\")", "branch limit expanded to holding branch"); - is( $limit_desc, "(holdingbranch: \"$branchcodes[0]\" OR holdingbranch: \"$branchcodes[1]\")", "Limit description correctly expanded"); - is( $limit_cgi, "&limit=multibranchlimit%3A$groupid", "Limit cgi does not get expanded"); + $query_builder->build_query_compat( undef, undef, undef, ["branch:CPL"], undef, undef, undef, undef ); + is( $limit, "(holdingbranch: \"CPL\")", "branch limit expanded to holding branch" ); + is( $limit_desc, "(holdingbranch: \"CPL\")", "Limit description correctly expanded" ); + is( $limit_cgi, "&limit=branch%3ACPL", "Limit cgi does not get expanded" ); + ( undef, undef, undef, undef, undef, $limit, $limit_cgi, $limit_desc, undef ) = $query_builder->build_query_compat( + undef, undef, undef, ["multibranchlimit:$groupid"], undef, undef, undef, + undef + ); + is( + $limit, "(holdingbranch: \"$branchcodes[0]\" OR holdingbranch: \"$branchcodes[1]\")", + "branch limit expanded to holding branch" + ); + is( + $limit_desc, "(holdingbranch: \"$branchcodes[0]\" OR holdingbranch: \"$branchcodes[1]\")", + "Limit description correctly expanded" + ); + is( $limit_cgi, "&limit=multibranchlimit%3A$groupid", "Limit cgi does not get expanded" ); }; @@ -938,35 +1045,47 @@ subtest "Handle search filters" => sub { my $qb; ok( - $qb = Koha::SearchEngine::Elasticsearch::QueryBuilder->new({ 'index' => 'biblios' }), + $qb = Koha::SearchEngine::Elasticsearch::QueryBuilder->new( { 'index' => 'biblios' } ), 'Creating new query builder object for biblios' ); - my $filter = Koha::SearchFilter->new({ - name => "test", - query => q|{"operands":["cat","bat","rat"],"indexes":["kw","ti","au"],"operators":["AND","OR"]}|, - limits => q|{"limits":["mc-itype,phr:BK","mc-itype,phr:MU","available"]}|, - })->store; + my $filter = Koha::SearchFilter->new( + { + name => "test", + query => q|{"operands":["cat","bat","rat"],"indexes":["kw","ti","au"],"operators":["AND","OR"]}|, + limits => q|{"limits":["mc-itype,phr:BK","mc-itype,phr:MU","available"]}|, + } + )->store; my $filter_id = $filter->id; - my ( undef, undef, undef, undef, undef, $limit, $limit_cgi, $limit_desc ) = $qb->build_query_compat( undef, undef, undef, ["search_filter:$filter_id"] ); + my ( undef, undef, undef, undef, undef, $limit, $limit_cgi, $limit_desc ) = + $qb->build_query_compat( undef, undef, undef, ["search_filter:$filter_id"] ); - is( $limit,q{(available:true) AND (((cat) AND title:(bat) OR author:(rat))) AND itype:(("BK") OR ("MU"))},"Limit correctly formed"); - is( $limit_cgi,"&limit=search_filter%3A$filter_id","CGI limit is not expanded"); - is( $limit_desc,q{(available:true) AND (((cat) AND title:(bat) OR author:(rat))) AND itype:(("BK") OR ("MU"))},"Limit description is correctly expanded"); + is( + $limit, q{(available:true) AND (((cat) AND title:(bat) OR author:(rat))) AND itype:(("BK") OR ("MU"))}, + "Limit correctly formed" + ); + is( $limit_cgi, "&limit=search_filter%3A$filter_id", "CGI limit is not expanded" ); + is( + $limit_desc, q{(available:true) AND (((cat) AND title:(bat) OR author:(rat))) AND itype:(("BK") OR ("MU"))}, + "Limit description is correctly expanded" + ); - $filter = Koha::SearchFilter->new({ - name => "test", - query => q|{"operands":["su:biography"],"indexes":[],"operators":[]}|, - limits => q|{"limits":[]}|, - })->store; + $filter = Koha::SearchFilter->new( + { + name => "test", + query => q|{"operands":["su:biography"],"indexes":[],"operators":[]}|, + limits => q|{"limits":[]}|, + } + )->store; $filter_id = $filter->id; - ( undef, undef, undef, undef, undef, $limit, $limit_cgi, $limit_desc ) = $qb->build_query_compat( undef, undef, undef, ["search_filter:$filter_id"] ); + ( undef, undef, undef, undef, undef, $limit, $limit_cgi, $limit_desc ) = + $qb->build_query_compat( undef, undef, undef, ["search_filter:$filter_id"] ); - is( $limit,q{((subject:biography))},"Limit correctly formed for ccl type query"); - is( $limit_cgi,"&limit=search_filter%3A$filter_id","CGI limit is not expanded"); - is( $limit_desc,q{((subject:biography))},"Limit description is correctly handled for ccl type query"); + is( $limit, q{((subject:biography))}, "Limit correctly formed for ccl type query" ); + is( $limit_cgi, "&limit=search_filter%3A$filter_id", "CGI limit is not expanded" ); + is( $limit_desc, q{((subject:biography))}, "Limit description is correctly handled for ccl type query" ); }; @@ -976,7 +1095,7 @@ subtest "_convert_sort_fields() tests" => sub { my $qb; ok( - $qb = Koha::SearchEngine::Elasticsearch::QueryBuilder->new({ 'index' => 'biblios' }), + $qb = Koha::SearchEngine::Elasticsearch::QueryBuilder->new( { 'index' => 'biblios' } ), 'Creating new query builder object for biblios' ); @@ -1008,7 +1127,7 @@ subtest "_sort_field() tests" => sub { my $qb; ok( - $qb = Koha::SearchEngine::Elasticsearch::QueryBuilder->new({ 'index' => 'biblios' }), + $qb = Koha::SearchEngine::Elasticsearch::QueryBuilder->new( { 'index' => 'biblios' } ), 'Creating new query builder object for biblios' ); diff --git a/t/db_dependent/Koha/SearchEngine/Elasticsearch/Reset.t b/t/db_dependent/Koha/SearchEngine/Elasticsearch/Reset.t index 64a3874081..bcc44698f8 100755 --- a/t/db_dependent/Koha/SearchEngine/Elasticsearch/Reset.t +++ b/t/db_dependent/Koha/SearchEngine/Elasticsearch/Reset.t @@ -26,20 +26,20 @@ use Koha::Caches; my $indexes = { 'authorities' => { 'Match' => { - 'label' => 'Match', - 'type' => '', - 'weight' => 15, + 'label' => 'Match', + 'type' => '', + 'weight' => 15, 'mandatory' => 0, - 'mappings' => [] + 'mappings' => [] } }, 'biblios' => { 'title' => { - 'label' => 'title', - 'type' => '', - 'weight' => 20, + 'label' => 'title', + 'type' => '', + 'weight' => 20, 'mandatory' => 1, - 'mapping' => [] + 'mapping' => [] } } }; @@ -57,22 +57,24 @@ Koha::SearchFields->search->delete; Koha::SearchMarcMaps->search->delete; $schema->resultset('SearchMarcToField')->search->delete; - Koha::SearchEngine::Elasticsearch->reset_elasticsearch_mappings; my $cache = Koha::Caches->get_instance(); -is( $cache->get_from_cache('elasticsearch_search_fields_staff_client'), undef, 'Cache has been flushed by reset_elasticsearch_mappings' ); +is( + $cache->get_from_cache('elasticsearch_search_fields_staff_client'), undef, + 'Cache has been flushed by reset_elasticsearch_mappings' +); -my $search_fields = Koha::SearchFields->search({}); -is($search_fields->count, 2, 'There is 2 search fields after reset'); +my $search_fields = Koha::SearchFields->search( {} ); +is( $search_fields->count, 2, 'There is 2 search fields after reset' ); -my $match_sf = Koha::SearchFields->search({ name => 'Match' })->next; -is($match_sf->weight, '15.00', 'Match search field is weighted with 15'); -is($match_sf->mandatory, '0', 'Match search field is not mandatory'); +my $match_sf = Koha::SearchFields->search( { name => 'Match' } )->next; +is( $match_sf->weight, '15.00', 'Match search field is weighted with 15' ); +is( $match_sf->mandatory, '0', 'Match search field is not mandatory' ); -my $title_sf = Koha::SearchFields->search({ name => 'title' })->next; -is($title_sf->weight, '20.00', 'Title search field is weighted with 20'); -is($title_sf->mandatory, '1', 'Title search field is mandatory'); +my $title_sf = Koha::SearchFields->search( { name => 'title' } )->next; +is( $title_sf->weight, '20.00', 'Title search field is weighted with 20' ); +is( $title_sf->mandatory, '1', 'Title search field is mandatory' ); $schema->storage->txn_rollback; diff --git a/t/db_dependent/Koha/SearchEngine/Elasticsearch/Search.t b/t/db_dependent/Koha/SearchEngine/Elasticsearch/Search.t index 64de5729b6..47d06bd134 100755 --- a/t/db_dependent/Koha/SearchEngine/Elasticsearch/Search.t +++ b/t/db_dependent/Koha/SearchEngine/Elasticsearch/Search.t @@ -25,63 +25,53 @@ use Koha::SearchEngine::Elasticsearch::QueryBuilder; use Koha::SearchEngine::Elasticsearch::Indexer; use Koha::SearchFields; -my $se = Test::MockModule->new( 'Koha::SearchEngine::Elasticsearch' ); -$se->mock( 'get_elasticsearch_mappings', sub { - my ($self) = @_; +my $se = Test::MockModule->new('Koha::SearchEngine::Elasticsearch'); +$se->mock( + 'get_elasticsearch_mappings', + sub { + my ($self) = @_; - my %all_mappings; + my %all_mappings; - my $mappings = { - properties => { - title => { - type => 'text' - }, - title__sort => { - type => 'text' - }, - subject => { - type => 'text' - }, - itemnumber => { - type => 'integer' - }, - sortablenumber => { - type => 'integer' - }, - sortablenumber__sort => { - type => 'integer' + my $mappings = { + properties => { + title => { type => 'text' }, + title__sort => { type => 'text' }, + subject => { type => 'text' }, + itemnumber => { type => 'integer' }, + sortablenumber => { type => 'integer' }, + sortablenumber__sort => { type => 'integer' } } - } - }; - $all_mappings{$self->index} = $mappings; + }; + $all_mappings{ $self->index } = $mappings; - my $sort_fields = { - $self->index => { - title => 1, - subject => 0, - itemnumber => 0, - sortablenumber => 1 - } - }; - $self->sort_fields($sort_fields->{$self->index}); + my $sort_fields = { + $self->index => { + title => 1, + subject => 0, + itemnumber => 0, + sortablenumber => 1 + } + }; + $self->sort_fields( $sort_fields->{ $self->index } ); - return $all_mappings{$self->index}; -}); + return $all_mappings{ $self->index }; + } +); my $builder = Koha::SearchEngine::Elasticsearch::QueryBuilder->new( { index => 'mydb' } ); use_ok('Koha::SearchEngine::Elasticsearch::Search'); ok( - my $searcher = Koha::SearchEngine::Elasticsearch::Search->new( - { 'nodes' => ['localhost:9200'], 'index' => 'mydb' } - ), + my $searcher = + Koha::SearchEngine::Elasticsearch::Search->new( { 'nodes' => ['localhost:9200'], 'index' => 'mydb' } ), 'Creating a Koha::SearchEngine::Elasticsearch::Search object' ); is( $searcher->index, 'mydb', 'Testing basic accessor' ); -ok( my $query = $builder->build_query('easy'), 'Build a search query'); +ok( my $query = $builder->build_query('easy'), 'Build a search query' ); SKIP: { @@ -90,40 +80,43 @@ SKIP: { skip 'Elasticsearch configuration not available', 9 if $@; - Koha::SearchEngine::Elasticsearch::Indexer->new({ index => 'mydb' })->drop_index; - Koha::SearchEngine::Elasticsearch::Indexer->new({ index => 'mydb' })->create_index; + Koha::SearchEngine::Elasticsearch::Indexer->new( { index => 'mydb' } )->drop_index; + Koha::SearchEngine::Elasticsearch::Indexer->new( { index => 'mydb' } )->create_index; - ok( my $results = $searcher->search( $query) , 'Do a search ' ); + ok( my $results = $searcher->search($query), 'Do a search ' ); - is (my $count = $searcher->count( $query ), 0 , 'Get a count of the results, without returning results '); + is( my $count = $searcher->count($query), 0, 'Get a count of the results, without returning results ' ); - ok ($results = $searcher->search_compat( $query ), 'Test search_compat' ); + ok( $results = $searcher->search_compat($query), 'Test search_compat' ); my ( undef, $scan_query ) = $builder->build_query_compat( undef, ['easy'], [], undef, undef, 1 ); - ok ((undef, $results) = $searcher->search_compat( $scan_query, undef, [], [], 20, 0, undef, undef, undef, 1 ), 'Test search_compat scan query' ); + ok( + ( undef, $results ) = $searcher->search_compat( $scan_query, undef, [], [], 20, 0, undef, undef, undef, 1 ), + 'Test search_compat scan query' + ); my $expected = { biblioserver => { - hits => 0, + hits => 0, RECORDS => [] } }; - is_deeply($results, $expected, 'Scan query results ok'); + is_deeply( $results, $expected, 'Scan query results ok' ); - ok (($results,$count) = $searcher->search_auth_compat ( $query ), 'Test search_auth_compat' ); + ok( ( $results, $count ) = $searcher->search_auth_compat($query), 'Test search_auth_compat' ); - is ( $count = $searcher->count_auth_use($searcher,1), 0, 'Testing count_auth_use'); + is( $count = $searcher->count_auth_use( $searcher, 1 ), 0, 'Testing count_auth_use' ); - is ($searcher->max_result_window, 1000000, 'By default, max_result_window is 1000000'); + is( $searcher->max_result_window, 1000000, 'By default, max_result_window is 1000000' ); $searcher->get_elasticsearch()->indices->put_settings( index => $searcher->index_name, - body => { + body => { 'index' => { 'max_result_window' => 12000, }, } ); - is ($searcher->max_result_window, 12000, 'max_result_window returns the correct value'); + is( $searcher->max_result_window, 12000, 'max_result_window returns the correct value' ); subtest "_convert_facets" => sub { plan tests => 5; diff --git a/t/db_dependent/Koha/SearchEngine/Indexer.t b/t/db_dependent/Koha/SearchEngine/Indexer.t index 0240935179..9b3938fd19 100755 --- a/t/db_dependent/Koha/SearchEngine/Indexer.t +++ b/t/db_dependent/Koha/SearchEngine/Indexer.t @@ -16,9 +16,9 @@ use t::lib::Mocks; #use C4::Biblio qw//; use C4::AuthoritiesMarc qw( AddAuthority DelAuthority merge ); -use C4::Biblio qw( ModZebra ModBiblio ModBiblioMarc DelBiblio ); -use C4::Circulation qw( MarkIssueReturned AddReturn LostItem AddRenewal ); -use C4::Items qw( ModDateLastSeen ModItemTransfer ); +use C4::Biblio qw( ModZebra ModBiblio ModBiblioMarc DelBiblio ); +use C4::Circulation qw( MarkIssueReturned AddReturn LostItem AddRenewal ); +use C4::Items qw( ModDateLastSeen ModItemTransfer ); use Koha::Database; use Koha::SearchEngine::Elasticsearch; use Koha::SearchEngine::Indexer; @@ -35,26 +35,32 @@ subtest 'Test indexer object creation' => sub { plan tests => 6; t::lib::Mocks::mock_preference( 'SearchEngine', 'Zebra' ); - my $indexer = Koha::SearchEngine::Indexer->new({ index => $Koha::SearchEngine::BIBLIOS_INDEX }); - is( ref $indexer, 'Koha::SearchEngine::Zebra::Indexer', 'We get the correct class for Zebra biblios'); - $indexer = Koha::SearchEngine::Indexer->new({ index => $Koha::SearchEngine::AUTHORITIES_INDEX }); - is( ref $indexer, 'Koha::SearchEngine::Zebra::Indexer', 'We get the correct class for Zebra authorities'); + my $indexer = Koha::SearchEngine::Indexer->new( { index => $Koha::SearchEngine::BIBLIOS_INDEX } ); + is( ref $indexer, 'Koha::SearchEngine::Zebra::Indexer', 'We get the correct class for Zebra biblios' ); + $indexer = Koha::SearchEngine::Indexer->new( { index => $Koha::SearchEngine::AUTHORITIES_INDEX } ); + is( ref $indexer, 'Koha::SearchEngine::Zebra::Indexer', 'We get the correct class for Zebra authorities' ); t::lib::Mocks::mock_preference( 'SearchEngine', 'Elasticsearch' ); - SKIP: { +SKIP: { eval { Koha::SearchEngine::Elasticsearch->get_elasticsearch_params; }; skip 'Elasticsearch configuration not available', 4 if $@; - $indexer = Koha::SearchEngine::Indexer->new({ index => $Koha::SearchEngine::BIBLIOS_INDEX }); - is( ref $indexer, 'Koha::SearchEngine::Elasticsearch::Indexer', 'We get the correct class for Elasticsearch biblios'); - ok( $indexer->index_name =~ /biblios$/, "The index is set correctly for biblios"); - $indexer = Koha::SearchEngine::Indexer->new({ index => $Koha::SearchEngine::AUTHORITIES_INDEX }); - is( ref $indexer, 'Koha::SearchEngine::Elasticsearch::Indexer', 'We get the correct class for Elasticsearch authorities'); - ok( $indexer->index_name =~ /authorities$/, "The index is set correctly for authorities"); + $indexer = Koha::SearchEngine::Indexer->new( { index => $Koha::SearchEngine::BIBLIOS_INDEX } ); + is( + ref $indexer, 'Koha::SearchEngine::Elasticsearch::Indexer', + 'We get the correct class for Elasticsearch biblios' + ); + ok( $indexer->index_name =~ /biblios$/, "The index is set correctly for biblios" ); + $indexer = Koha::SearchEngine::Indexer->new( { index => $Koha::SearchEngine::AUTHORITIES_INDEX } ); + is( + ref $indexer, 'Koha::SearchEngine::Elasticsearch::Indexer', + 'We get the correct class for Elasticsearch authorities' + ); + ok( $indexer->index_name =~ /authorities$/, "The index is set correctly for authorities" ); } }; @@ -65,52 +71,59 @@ subtest 'Test indexer calls' => sub { my @engines = ('Zebra'); eval { Koha::SearchEngine::Elasticsearch->get_elasticsearch_params; }; push @engines, 'Elasticsearch' unless $@; - SKIP: { - skip 'Elasticsearch configuration not available', 20 +SKIP: { + skip 'Elasticsearch configuration not available', 20 if scalar @engines == 1; } t::lib::Mocks::mock_userenv(); t::lib::Mocks::mock_preference( 'AutoLinkBiblios', 0 ); - for my $engine ( @engines ){ + for my $engine (@engines) { t::lib::Mocks::mock_preference( 'SearchEngine', $engine ); - my $mock_index = Test::MockModule->new("Koha::SearchEngine::".$engine."::Indexer"); + my $mock_index = Test::MockModule->new( "Koha::SearchEngine::" . $engine . "::Indexer" ); my $biblionumber1 = $builder->build_sample_biblio()->biblionumber; my $biblionumber2 = $builder->build_sample_biblio()->biblionumber; my $mock_zebra = Test::MockModule->new("Koha::SearchEngine::Zebra::Indexer"); $mock_zebra->mock( ModZebra => sub { warn "ModZebra"; } ); - my $indexer = Koha::SearchEngine::Indexer->new({ index => $Koha::SearchEngine::BIBLIOS_INDEX }); - warnings_are{ - $indexer->index_records([$biblionumber1,$biblionumber1],"specialUpdate","biblioserver",undef); - } ["ModZebra","ModZebra"],"ModZebra called for each record being indexed for $engine"; + my $indexer = Koha::SearchEngine::Indexer->new( { index => $Koha::SearchEngine::BIBLIOS_INDEX } ); + warnings_are { + $indexer->index_records( [ $biblionumber1, $biblionumber1 ], "specialUpdate", "biblioserver", undef ); + } + [ "ModZebra", "ModZebra" ], "ModZebra called for each record being indexed for $engine"; - $mock_index->mock( index_records => sub { - warn $engine; - my ($package, undef, undef) = caller; - warn $package; - }); + $mock_index->mock( + index_records => sub { + warn $engine; + my ( $package, undef, undef ) = caller; + warn $package; + } + ); my $auth = MARC::Record->new; my $authid; - warnings_are{ + warnings_are { $authid = AddAuthority( $auth, undef, 'TOPIC_TERM' ); - } [$engine,"C4::AuthoritiesMarc"], "index_records is called for $engine is called when adding authority"; + } + [ $engine, "C4::AuthoritiesMarc" ], "index_records is called for $engine is called when adding authority"; - warnings_are{ - $authid = DelAuthority({ authid => $authid, skip_merge => 1 }); - } [$engine,"C4::AuthoritiesMarc"], "index_records is called for $engine is called when adding authority"; + warnings_are { + $authid = DelAuthority( { authid => $authid, skip_merge => 1 } ); + } + [ $engine, "C4::AuthoritiesMarc" ], "index_records is called for $engine is called when adding authority"; my $biblio; my $biblio2; my $biblio3; - warnings_are{ - $biblio = $builder->build_sample_biblio(); + warnings_are { + $biblio = $builder->build_sample_biblio(); $biblio2 = $builder->build_sample_biblio(); $biblio3 = $builder->build_sample_biblio(); - } [$engine,'C4::Biblio',$engine,'C4::Biblio',$engine,'C4::Biblio'], "index_records is called for $engine when adding a biblio (ModBiblioMarc)"; + } + [ $engine, 'C4::Biblio', $engine, 'C4::Biblio', $engine, 'C4::Biblio' ], + "index_records is called for $engine when adding a biblio (ModBiblioMarc)"; my $item; my $item2; @@ -118,130 +131,172 @@ subtest 'Test indexer calls' => sub { my $item4; my $item5; my $item6; - warnings_are{ - $item = $builder->build_sample_item({ - biblionumber => $biblio->biblionumber, - onloan => '2020-02-02', - datelastseen => '2020-01-01', - replacementprice => 0 - }); - $item2 = $builder->build_sample_item({ - biblionumber => $biblio->biblionumber, - onloan => '2020-12-12', - datelastseen => '2020-11-11', - replacementprice => 0 - }); - $item3 = $builder->build_sample_item({biblionumber => $biblio->biblionumber}); - $item4 = $builder->build_sample_item({biblionumber => $biblio->biblionumber}); - $item5 = $builder->build_sample_item({biblionumber => $biblio3->biblionumber}); - $item6 = $builder->build_sample_item({biblionumber => $biblio3->biblionumber}); - } [$engine,"Koha::Item", - $engine,"Koha::Item", - $engine,"Koha::Item", - $engine,"Koha::Item", - $engine,"Koha::Item", - $engine,"Koha::Item"], "index_records is called for $engine when adding an item (Item->store)"; - warnings_are{ - $item->store({ skip_record_index => 1 }); - } undef, "index_records is not called for $engine when adding an item (Item->store) if skip_record_index passed"; + warnings_are { + $item = $builder->build_sample_item( + { + biblionumber => $biblio->biblionumber, + onloan => '2020-02-02', + datelastseen => '2020-01-01', + replacementprice => 0 + } + ); + $item2 = $builder->build_sample_item( + { + biblionumber => $biblio->biblionumber, + onloan => '2020-12-12', + datelastseen => '2020-11-11', + replacementprice => 0 + } + ); + $item3 = $builder->build_sample_item( { biblionumber => $biblio->biblionumber } ); + $item4 = $builder->build_sample_item( { biblionumber => $biblio->biblionumber } ); + $item5 = $builder->build_sample_item( { biblionumber => $biblio3->biblionumber } ); + $item6 = $builder->build_sample_item( { biblionumber => $biblio3->biblionumber } ); + } + [ + $engine, "Koha::Item", + $engine, "Koha::Item", + $engine, "Koha::Item", + $engine, "Koha::Item", + $engine, "Koha::Item", + $engine, "Koha::Item" + ], + "index_records is called for $engine when adding an item (Item->store)"; + warnings_are { + $item->store( { skip_record_index => 1 } ); + } + undef, "index_records is not called for $engine when adding an item (Item->store) if skip_record_index passed"; - my $issue = $builder->build({ - source => 'Issue', - value => { - itemnumber => $item->itemnumber + my $issue = $builder->build( + { + source => 'Issue', + value => { itemnumber => $item->itemnumber } } - }); - my $issue2 = $builder->build({ - source => 'Issue', - value => { - itemnumber => $item2->itemnumber + ); + my $issue2 = $builder->build( + { + source => 'Issue', + value => { itemnumber => $item2->itemnumber } } - }); - warnings_are{ - MarkIssueReturned( $issue->{borrowernumber}, $item->itemnumber); - } [$engine,"Koha::Item"], "index_records is called for $engine when calling MarkIssueReturned"; - warnings_are{ - MarkIssueReturned( $issue2->{borrowernumber}, $item2->itemnumber, undef, undef, { skip_record_index => 1}); - } undef, "index_records is not called for $engine when calling MarkIssueReturned if skip_record_index passed"; + ); + warnings_are { + MarkIssueReturned( $issue->{borrowernumber}, $item->itemnumber ); + } + [ $engine, "Koha::Item" ], "index_records is called for $engine when calling MarkIssueReturned"; + warnings_are { + MarkIssueReturned( + $issue2->{borrowernumber}, $item2->itemnumber, undef, undef, + { skip_record_index => 1 } + ); + } + undef, "index_records is not called for $engine when calling MarkIssueReturned if skip_record_index passed"; - warnings_are{ - AddReturn($item->barcode, $item->homebranch, 0, undef); - } [$engine,'C4::Circulation'], "index_records is called once for $engine when calling AddReturn if item not issued"; - $issue = $builder->build({ - source => 'Issue', - value => { - itemnumber => $item->itemnumber + warnings_are { + AddReturn( $item->barcode, $item->homebranch, 0, undef ); + } + [ $engine, 'C4::Circulation' ], + "index_records is called once for $engine when calling AddReturn if item not issued"; + $issue = $builder->build( + { + source => 'Issue', + value => { itemnumber => $item->itemnumber } } - }); - warnings_are{ - AddReturn($item->barcode, $item->homebranch, 0, undef); - } [$engine,'C4::Circulation'], "index_records is called once for $engine when calling AddReturn if item not issued"; + ); + warnings_are { + AddReturn( $item->barcode, $item->homebranch, 0, undef ); + } + [ $engine, 'C4::Circulation' ], + "index_records is called once for $engine when calling AddReturn if item not issued"; - warnings_are{ + warnings_are { $item3->move_to_biblio($biblio2); - } [$engine,"Koha::Item",$engine,"Koha::Item"], "index_records is called twice for $engine when moving an item to another biblio (Item->move_to_biblio)"; - warnings_are{ - $item4->move_to_biblio($biblio2, { skip_record_index => 1 }); - } undef, "index_records is not called for $engine when moving an item to another biblio (Item->move_to_biblio) if skip_record_index passed"; + } + [ $engine, "Koha::Item", $engine, "Koha::Item" ], + "index_records is called twice for $engine when moving an item to another biblio (Item->move_to_biblio)"; + warnings_are { + $item4->move_to_biblio( $biblio2, { skip_record_index => 1 } ); + } + undef, + "index_records is not called for $engine when moving an item to another biblio (Item->move_to_biblio) if skip_record_index passed"; - warnings_are{ + warnings_are { $biblio->items->move_to_biblio($biblio2); - } [$engine,"Koha::Items",$engine,"Koha::Items"], "index_records is called for from and to biblios for $engine when adopting items (Biblio->items->move_to_biblio(Biblio)"; + } + [ $engine, "Koha::Items", $engine, "Koha::Items" ], + "index_records is called for from and to biblios for $engine when adopting items (Biblio->items->move_to_biblio(Biblio)"; - my $items = Koha::Items->search({ itemnumber => [ $item2->itemnumber, $item5->itemnumber, $item6->itemnumber ] }); - warnings_are{ + my $items = + Koha::Items->search( { itemnumber => [ $item2->itemnumber, $item5->itemnumber, $item6->itemnumber ] } ); + warnings_are { $items->move_to_biblio($biblio); - } [$engine,"Koha::Items",$engine,"Koha::Items",$engine,"Koha::Items"], "index_records is called for all from and to biblios for $engine when adopting items (Items->move_to_biblio(Biblio)"; + } + [ $engine, "Koha::Items", $engine, "Koha::Items", $engine, "Koha::Items" ], + "index_records is called for all from and to biblios for $engine when adopting items (Items->move_to_biblio(Biblio)"; - $builder->build({ - source => 'Issue', - value => { - itemnumber => $item->itemnumber + $builder->build( + { + source => 'Issue', + value => { itemnumber => $item->itemnumber } } - }); - $item->onloan('2000-01-01')->store({ skip_record_index => 1 }); - warnings_are{ - LostItem( $item->itemnumber, "tests", 1); - } [$engine,"Koha::Item"], "index_records is called for $engine when calling LostItem with 'force_mark_returned'"; - $builder->build({ - source => 'Issue', - value => { - itemnumber => $item->itemnumber + ); + $item->onloan('2000-01-01')->store( { skip_record_index => 1 } ); + warnings_are { + LostItem( $item->itemnumber, "tests", 1 ); + } + [ $engine, "Koha::Item" ], + "index_records is called for $engine when calling LostItem with 'force_mark_returned'"; + $builder->build( + { + source => 'Issue', + value => { itemnumber => $item->itemnumber } } - }); - $item->onloan('2000-01-01')->store({ skip_record_index => 1 }); - warnings_are{ - LostItem( $item->itemnumber, "tests", 1, { skip_record_index => 1 }); - } undef, "index_records is not called for $engine when calling LostItem with 'force_mark_returned' if skip_record_index"; + ); + $item->onloan('2000-01-01')->store( { skip_record_index => 1 } ); + warnings_are { + LostItem( $item->itemnumber, "tests", 1, { skip_record_index => 1 } ); + } + undef, + "index_records is not called for $engine when calling LostItem with 'force_mark_returned' if skip_record_index"; - $item->datelastseen('2001-01-01')->store({skip_record_index=>1}); - warnings_are{ + $item->datelastseen('2001-01-01')->store( { skip_record_index => 1 } ); + warnings_are { my $t1 = ModDateLastSeen( $item->itemnumber, 1, undef ); - } [$engine, "Koha::Item"], "index_records is called for $engine when calling ModDateLastSeen"; - warnings_are{ - ModDateLastSeen( $item->itemnumber, 1, { skip_record_index =>1 } ); - } undef, "index_records is not called for $engine when calling ModDateLastSeen if skip_record_index"; + } + [ $engine, "Koha::Item" ], "index_records is called for $engine when calling ModDateLastSeen"; + warnings_are { + ModDateLastSeen( $item->itemnumber, 1, { skip_record_index => 1 } ); + } + undef, "index_records is not called for $engine when calling ModDateLastSeen if skip_record_index"; - warnings_are{ - ModItemTransfer( $item->itemnumber, $item2->homebranch, $item->homebranch,'Manual'); - } [$engine,"Koha::Item"], "index_records is called for $engine when calling ModItemTransfer"; - warnings_are{ - ModItemTransfer( $item->itemnumber, $item->homebranch, $item2->homebranch,'Manual',{skip_record_index=>1}); - } undef, "index_records is not called for $engine when calling ModItemTransfer with skip_record_index"; + warnings_are { + ModItemTransfer( $item->itemnumber, $item2->homebranch, $item->homebranch, 'Manual' ); + } + [ $engine, "Koha::Item" ], "index_records is called for $engine when calling ModItemTransfer"; + warnings_are { + ModItemTransfer( + $item->itemnumber, $item->homebranch, $item2->homebranch, 'Manual', + { skip_record_index => 1 } + ); + } + undef, "index_records is not called for $engine when calling ModItemTransfer with skip_record_index"; - warnings_are{ + warnings_are { $item->delete(); - } [$engine,"Koha::Item"], "index_records is called for $engine when deleting an item (Item->delete)"; - warnings_are{ - $item2->delete({ skip_record_index => 1 }); - } undef, "index_records is not called for $engine when adding an item (Item->store) if skip_record_index passed"; + } + [ $engine, "Koha::Item" ], "index_records is called for $engine when deleting an item (Item->delete)"; + warnings_are { + $item2->delete( { skip_record_index => 1 } ); + } + undef, "index_records is not called for $engine when adding an item (Item->store) if skip_record_index passed"; - warnings_are{ + warnings_are { DelBiblio( $biblio3->biblionumber ); - } [$engine, "C4::Biblio"], "index_records is called for $engine when calling DelBiblio"; - warnings_are{ - DelBiblio( $biblio3->biblionumber, { skip_record_index =>1 }); - } undef, "index_records is not called for $engine when calling DelBiblio if skip_record_index passed"; + } + [ $engine, "C4::Biblio" ], "index_records is called for $engine when calling DelBiblio"; + warnings_are { + DelBiblio( $biblio3->biblionumber, { skip_record_index => 1 } ); + } + undef, "index_records is not called for $engine when calling DelBiblio if skip_record_index passed"; } @@ -253,38 +308,41 @@ subtest 'Test AddRenewal indexer call' => sub { my @engines = ('Zebra'); eval { Koha::SearchEngine::Elasticsearch->get_elasticsearch_params; }; push @engines, 'Elasticsearch' unless $@; - SKIP: { - skip 'Elasticsearch configuration not available', 20 +SKIP: { + skip 'Elasticsearch configuration not available', 20 if scalar @engines == 1; } - for my $engine ( @engines ){ + for my $engine (@engines) { t::lib::Mocks::mock_preference( 'SearchEngine', $engine ); - my $mock_index = Test::MockModule->new("Koha::SearchEngine::".$engine."::Indexer"); + my $mock_index = Test::MockModule->new( "Koha::SearchEngine::" . $engine . "::Indexer" ); my $biblio = $builder->build_sample_biblio(); - my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); - my $item = $builder->build_sample_item({ - biblionumber => $biblio->biblionumber, - onloan => '2020-02-02', - datelastseen => '2020-01-01', - replacementprice => 0 - }); - my $issue = $builder->build({ - source => 'Issue', - value => { - itemnumber => $item->itemnumber + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + my $item = $builder->build_sample_item( + { + biblionumber => $biblio->biblionumber, + onloan => '2020-02-02', + datelastseen => '2020-01-01', + replacementprice => 0 } - }); + ); + my $issue = $builder->build( + { + source => 'Issue', + value => { itemnumber => $item->itemnumber } + } + ); - $mock_index->mock( index_records => sub { - warn $engine; - my ($package, undef, undef) = caller; - warn $package; - }); + $mock_index->mock( + index_records => sub { + warn $engine; + my ( $package, undef, undef ) = caller; + warn $package; + } + ); - - warnings_are{ + warnings_are { AddRenewal( { borrowernumber => $patron->borrowernumber, @@ -293,8 +351,9 @@ subtest 'Test AddRenewal indexer call' => sub { seen => 0 } ); - } [$engine,"C4::Circulation"], "index_records is called for $engine when adding a renewal (AddRenewal())"; - warnings_are{ + } + [ $engine, "C4::Circulation" ], "index_records is called for $engine when adding a renewal (AddRenewal())"; + warnings_are { AddRenewal( { borrowernumber => $patron->borrowernumber, @@ -304,7 +363,8 @@ subtest 'Test AddRenewal indexer call' => sub { skip_record_index => 1 } ); - } undef, "index_records is not called for $engine when adding a renewal (AddRenewal()) with skip_record_index"; + } + undef, "index_records is not called for $engine when adding a renewal (AddRenewal()) with skip_record_index"; } }; diff --git a/t/db_dependent/Koha/SearchEngine/Search.t b/t/db_dependent/Koha/SearchEngine/Search.t index e3780b34eb..f7838a3c16 100755 --- a/t/db_dependent/Koha/SearchEngine/Search.t +++ b/t/db_dependent/Koha/SearchEngine/Search.t @@ -17,30 +17,30 @@ use t::lib::Mocks; use Koha::Database; use Koha::SearchEngine::Search; -my $schema = Koha::Database->new->schema; +my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; subtest 'Test extract_biblionumber' => sub { plan tests => 2; t::lib::Mocks::mock_preference( 'SearchEngine', 'Zebra' ); - my $biblio_mod = Test::MockModule->new( 'C4::Biblio' ); - my $search_mod = Test::MockModule->new( 'C4::Search' ); + my $biblio_mod = Test::MockModule->new('C4::Biblio'); + my $search_mod = Test::MockModule->new('C4::Search'); my $koha_fields = [ '001', '' ]; - $biblio_mod->mock( 'GetMarcFromKohaField', sub { return @$koha_fields; }); + $biblio_mod->mock( 'GetMarcFromKohaField', sub { return @$koha_fields; } ); $search_mod->mock( 'new_record_from_zebra', \&test_record ); # Extract using 001 my $searcher = Koha::SearchEngine::Search->new; - my $bibno = $searcher->extract_biblionumber( 'fake_result' ); + my $bibno = $searcher->extract_biblionumber('fake_result'); is( $bibno, 3456, 'Extracted biblio number for Zebra' ); # Now use 999c with Elasticsearch t::lib::Mocks::mock_preference( 'SearchEngine', 'Elasticsearch' ); - $search_mod->unmock( 'new_record_from_zebra' ); + $search_mod->unmock('new_record_from_zebra'); $koha_fields = [ '999', 'c' ]; - $searcher = Koha::SearchEngine::Search->new({ index => 'biblios' }); - $bibno = $searcher->extract_biblionumber( test_record() ); + $searcher = Koha::SearchEngine::Search->new( { index => 'biblios' } ); + $bibno = $searcher->extract_biblionumber( test_record() ); is( $bibno, 4567, 'Extracted biblio number for Zebra' ); }; diff --git a/t/db_dependent/Koha/SearchEngine/Zebra/QueryBuilder.t b/t/db_dependent/Koha/SearchEngine/Zebra/QueryBuilder.t index df8cfce77f..5d169de939 100755 --- a/t/db_dependent/Koha/SearchEngine/Zebra/QueryBuilder.t +++ b/t/db_dependent/Koha/SearchEngine/Zebra/QueryBuilder.t @@ -35,65 +35,102 @@ subtest 'build_query_compat() SearchLimitLibrary tests' => sub { my $builder = t::lib::TestBuilder->new; - my $branch_1 = $builder->build_object({ class => 'Koha::Libraries' }); - my $branch_2 = $builder->build_object({ class => 'Koha::Libraries' }); - my $group = $builder->build_object({ class => 'Koha::Library::Groups', value => { - ft_search_groups_opac => 1, - ft_search_groups_staff => 1, - parent_id => undef, - branchcode => undef + my $branch_1 = $builder->build_object( { class => 'Koha::Libraries' } ); + my $branch_2 = $builder->build_object( { class => 'Koha::Libraries' } ); + my $group = $builder->build_object( + { + class => 'Koha::Library::Groups', + value => { + ft_search_groups_opac => 1, + ft_search_groups_staff => 1, + parent_id => undef, + branchcode => undef + } } - }); - my $group_1 = $builder->build_object({ class => 'Koha::Library::Groups', value => { - parent_id => $group->id, - branchcode => $branch_1->id + ); + my $group_1 = $builder->build_object( + { + class => 'Koha::Library::Groups', + value => { + parent_id => $group->id, + branchcode => $branch_1->id + } } - }); - my $group_2 = $builder->build_object({ class => 'Koha::Library::Groups', value => { - parent_id => $group->id, - branchcode => $branch_2->id + ); + my $group_2 = $builder->build_object( + { + class => 'Koha::Library::Groups', + value => { + parent_id => $group->id, + branchcode => $branch_2->id + } } - }); - my $groupid = $group->id; + ); + my $groupid = $group->id; my @branchcodes = sort { $a cmp $b } ( $branch_1->id, $branch_2->id ); - - my $query_builder = Koha::SearchEngine::Zebra::QueryBuilder->new({index => $Koha::SearchEngine::BIBLIOS_INDEX}); - t::lib::Mocks::mock_preference('SearchLimitLibrary', 'both'); + my $query_builder = Koha::SearchEngine::Zebra::QueryBuilder->new( { index => $Koha::SearchEngine::BIBLIOS_INDEX } ); + t::lib::Mocks::mock_preference( 'SearchLimitLibrary', 'both' ); my ( undef, undef, undef, undef, undef, $limit, $limit_cgi, $limit_desc, undef ) = - $query_builder->build_query_compat( undef, undef, undef, [ "branch:CPL" ], undef, undef, undef, undef ); - is( $limit, "(homebranch= CPL or holdingbranch= CPL)", "Branch limit expanded to home/holding branch"); - is( $limit_desc, "(homebranch: CPL or holdingbranch: CPL)", "Limit description correctly expanded"); - is( $limit_cgi, "&limit=branch%3ACPL", "Limit cgi does not get expanded"); - ( undef, undef, undef, undef, undef, $limit, $limit_cgi, $limit_desc, undef ) = - $query_builder->build_query_compat( undef, undef, undef, [ "multibranchlimit:$groupid" ], undef, undef, undef, undef ); - is( $limit, "(homebranch= $branchcodes[0] or homebranch= $branchcodes[1] or holdingbranch= $branchcodes[0] or holdingbranch= $branchcodes[1])", "Multibranch limit expanded to home/holding branches"); - is( $limit_desc, "(homebranch: $branchcodes[0] or homebranch: $branchcodes[1] or holdingbranch: $branchcodes[0] or holdingbranch: $branchcodes[1])", "Multibranch limit description correctly expanded"); - is( $limit_cgi, "&limit=multibranchlimit%3A$groupid", "Multibranch limit cgi does not get expanded"); + $query_builder->build_query_compat( undef, undef, undef, ["branch:CPL"], undef, undef, undef, undef ); + is( $limit, "(homebranch= CPL or holdingbranch= CPL)", "Branch limit expanded to home/holding branch" ); + is( $limit_desc, "(homebranch: CPL or holdingbranch: CPL)", "Limit description correctly expanded" ); + is( $limit_cgi, "&limit=branch%3ACPL", "Limit cgi does not get expanded" ); + ( undef, undef, undef, undef, undef, $limit, $limit_cgi, $limit_desc, undef ) = $query_builder->build_query_compat( + undef, undef, undef, ["multibranchlimit:$groupid"], undef, undef, undef, + undef + ); + is( + $limit, + "(homebranch= $branchcodes[0] or homebranch= $branchcodes[1] or holdingbranch= $branchcodes[0] or holdingbranch= $branchcodes[1])", + "Multibranch limit expanded to home/holding branches" + ); + is( + $limit_desc, + "(homebranch: $branchcodes[0] or homebranch: $branchcodes[1] or holdingbranch: $branchcodes[0] or holdingbranch: $branchcodes[1])", + "Multibranch limit description correctly expanded" + ); + is( $limit_cgi, "&limit=multibranchlimit%3A$groupid", "Multibranch limit cgi does not get expanded" ); - t::lib::Mocks::mock_preference('SearchLimitLibrary', 'homebranch'); + t::lib::Mocks::mock_preference( 'SearchLimitLibrary', 'homebranch' ); ( undef, undef, undef, undef, undef, $limit, $limit_cgi, $limit_desc, undef ) = - $query_builder->build_query_compat( undef, undef, undef, [ "branch:CPL" ], undef, undef, undef, undef ); - is( $limit, "(homebranch= CPL)", "branch limit expanded to home branch"); - is( $limit_desc, "(homebranch: CPL)", "limit description correctly expanded"); - is( $limit_cgi, "&limit=branch%3ACPL", "limit cgi does not get expanded"); - ( undef, undef, undef, undef, undef, $limit, $limit_cgi, $limit_desc, undef ) = - $query_builder->build_query_compat( undef, undef, undef, [ "multibranchlimit:$groupid" ], undef, undef, undef, undef ); - is( $limit, "(homebranch= $branchcodes[0] or homebranch= $branchcodes[1])", "branch limit expanded to home branch"); - is( $limit_desc, "(homebranch: $branchcodes[0] or homebranch: $branchcodes[1])", "limit description correctly expanded"); - is( $limit_cgi, "&limit=multibranchlimit%3A$groupid", "Limit cgi does not get expanded"); + $query_builder->build_query_compat( undef, undef, undef, ["branch:CPL"], undef, undef, undef, undef ); + is( $limit, "(homebranch= CPL)", "branch limit expanded to home branch" ); + is( $limit_desc, "(homebranch: CPL)", "limit description correctly expanded" ); + is( $limit_cgi, "&limit=branch%3ACPL", "limit cgi does not get expanded" ); + ( undef, undef, undef, undef, undef, $limit, $limit_cgi, $limit_desc, undef ) = $query_builder->build_query_compat( + undef, undef, undef, ["multibranchlimit:$groupid"], undef, undef, undef, + undef + ); + is( + $limit, "(homebranch= $branchcodes[0] or homebranch= $branchcodes[1])", + "branch limit expanded to home branch" + ); + is( + $limit_desc, "(homebranch: $branchcodes[0] or homebranch: $branchcodes[1])", + "limit description correctly expanded" + ); + is( $limit_cgi, "&limit=multibranchlimit%3A$groupid", "Limit cgi does not get expanded" ); - t::lib::Mocks::mock_preference('SearchLimitLibrary', 'holdingbranch'); + t::lib::Mocks::mock_preference( 'SearchLimitLibrary', 'holdingbranch' ); ( undef, undef, undef, undef, undef, $limit, $limit_cgi, $limit_desc, undef ) = - $query_builder->build_query_compat( undef, undef, undef, [ "branch:CPL" ], undef, undef, undef, undef ); - is( $limit, "(holdingbranch= CPL)", "branch limit expanded to holding branch"); - is( $limit_desc, "(holdingbranch: CPL)", "Limit description correctly expanded"); - is( $limit_cgi, "&limit=branch%3ACPL", "Limit cgi does not get expanded"); - ( undef, undef, undef, undef, undef, $limit, $limit_cgi, $limit_desc, undef ) = - $query_builder->build_query_compat( undef, undef, undef, [ "multibranchlimit:$groupid" ], undef, undef, undef, undef ); - is( $limit, "(holdingbranch= $branchcodes[0] or holdingbranch= $branchcodes[1])", "branch limit expanded to holding branch"); - is( $limit_desc, "(holdingbranch: $branchcodes[0] or holdingbranch: $branchcodes[1])", "Limit description correctly expanded"); - is( $limit_cgi, "&limit=multibranchlimit%3A$groupid", "Limit cgi does not get expanded"); + $query_builder->build_query_compat( undef, undef, undef, ["branch:CPL"], undef, undef, undef, undef ); + is( $limit, "(holdingbranch= CPL)", "branch limit expanded to holding branch" ); + is( $limit_desc, "(holdingbranch: CPL)", "Limit description correctly expanded" ); + is( $limit_cgi, "&limit=branch%3ACPL", "Limit cgi does not get expanded" ); + ( undef, undef, undef, undef, undef, $limit, $limit_cgi, $limit_desc, undef ) = $query_builder->build_query_compat( + undef, undef, undef, ["multibranchlimit:$groupid"], undef, undef, undef, + undef + ); + is( + $limit, "(holdingbranch= $branchcodes[0] or holdingbranch= $branchcodes[1])", + "branch limit expanded to holding branch" + ); + is( + $limit_desc, "(holdingbranch: $branchcodes[0] or holdingbranch: $branchcodes[1])", + "Limit description correctly expanded" + ); + is( $limit_cgi, "&limit=multibranchlimit%3A$groupid", "Limit cgi does not get expanded" ); }; @@ -103,34 +140,48 @@ subtest "Handle search filters" => sub { my $qb; ok( - $qb = Koha::SearchEngine::Zebra::QueryBuilder->new({ 'index' => 'biblios' }), + $qb = Koha::SearchEngine::Zebra::QueryBuilder->new( { 'index' => 'biblios' } ), 'Creating new query builder object for biblios' ); - my $filter = Koha::SearchFilter->new({ - name => "test", - query => q|{"operands":["cat","bat","rat"],"indexes":["kw","ti","au"],"operators":["AND","OR"]}|, - limits => q|{"limits":["mc-itype,phr:BK","mc-itype,phr:MU","available"]}|, - })->store; + my $filter = Koha::SearchFilter->new( + { + name => "test", + query => q|{"operands":["cat","bat","rat"],"indexes":["kw","ti","au"],"operators":["AND","OR"]}|, + limits => q|{"limits":["mc-itype,phr:BK","mc-itype,phr:MU","available"]}|, + } + )->store; my $filter_id = $filter->id; - my ( undef, undef, undef, undef, undef, $limit, $limit_cgi, $limit_desc ) = $qb->build_query_compat( undef, undef, undef, ["search_filter:$filter_id"] ); + my ( undef, undef, undef, undef, undef, $limit, $limit_cgi, $limit_desc ) = + $qb->build_query_compat( undef, undef, undef, ["search_filter:$filter_id"] ); - is( $limit,q{(kw=(cat) AND ti=(bat) OR au=(rat)) and (mc-itype,phr=BK or mc-itype,phr=MU) and (( (allrecords,AlwaysMatches='') and (not-onloan-count,st-numeric >= 1) and (lost,st-numeric=0) ))},"Limit correctly formed"); - is( $limit_cgi,"&limit=search_filter%3A$filter_id","CGI limit is not expanded"); - is( $limit_desc,q{(kw=(cat) AND ti=(bat) OR au=(rat)) and (mc-itype,phr=BK or mc-itype,phr=MU) and (( (allrecords,AlwaysMatches='') and (not-onloan-count,st-numeric >= 1) and (lost,st-numeric=0) ))},"Limit description is correctly expanded"); + is( + $limit, + q{(kw=(cat) AND ti=(bat) OR au=(rat)) and (mc-itype,phr=BK or mc-itype,phr=MU) and (( (allrecords,AlwaysMatches='') and (not-onloan-count,st-numeric >= 1) and (lost,st-numeric=0) ))}, + "Limit correctly formed" + ); + is( $limit_cgi, "&limit=search_filter%3A$filter_id", "CGI limit is not expanded" ); + is( + $limit_desc, + q{(kw=(cat) AND ti=(bat) OR au=(rat)) and (mc-itype,phr=BK or mc-itype,phr=MU) and (( (allrecords,AlwaysMatches='') and (not-onloan-count,st-numeric >= 1) and (lost,st-numeric=0) ))}, + "Limit description is correctly expanded" + ); - $filter = Koha::SearchFilter->new({ - name => "test", - query => q|{"operands":["su:biography"],"indexes":[],"operators":[]}|, - limits => q|{"limits":[]}|, - })->store; + $filter = Koha::SearchFilter->new( + { + name => "test", + query => q|{"operands":["su:biography"],"indexes":[],"operators":[]}|, + limits => q|{"limits":[]}|, + } + )->store; $filter_id = $filter->id; - ( undef, undef, undef, undef, undef, $limit, $limit_cgi, $limit_desc ) = $qb->build_query_compat( undef, undef, undef, ["search_filter:$filter_id"] ); + ( undef, undef, undef, undef, undef, $limit, $limit_cgi, $limit_desc ) = + $qb->build_query_compat( undef, undef, undef, ["search_filter:$filter_id"] ); - is( $limit,q{((su=biography))},"Limit correctly formed for ccl type query"); - is( $limit_cgi,"&limit=search_filter%3A$filter_id","CGI limit is not expanded"); - is( $limit_desc,q{((su=biography))},"Limit description is correctly handled for ccl type query"); + is( $limit, q{((su=biography))}, "Limit correctly formed for ccl type query" ); + is( $limit_cgi, "&limit=search_filter%3A$filter_id", "CGI limit is not expanded" ); + is( $limit_desc, q{((su=biography))}, "Limit description is correctly handled for ccl type query" ); }; diff --git a/t/db_dependent/Koha/SearchField.t b/t/db_dependent/Koha/SearchField.t index bf25b396f2..2abbf60408 100755 --- a/t/db_dependent/Koha/SearchField.t +++ b/t/db_dependent/Koha/SearchField.t @@ -33,11 +33,13 @@ $schema->storage->txn_begin; my $builder = t::lib::TestBuilder->new; -t::lib::Mocks::mock_preference('marcflavour', 'marc21'); +t::lib::Mocks::mock_preference( 'marcflavour', 'marc21' ); -my $sf = $builder->build({ - source => 'SearchField', -}); +my $sf = $builder->build( + { + source => 'SearchField', + } +); my $search_field = Koha::SearchFields->find( $sf->{id} ); ok( !$search_field->is_mapped, 'Search field 1 is not mapped' ); @@ -69,108 +71,128 @@ ok( $search_field->is_mapped, 'Search field 1 is mapped' ); Koha::SearchMarcMaps->search( {} )->delete; $schema->resultset('SearchMarcToField')->search( {} )->delete; -my $smm = $builder->build({ - source => 'SearchMarcMap', - value => { - index_name => 'biblios', - marc_type => 'marc21', - marc_field => '410abcdef' +my $smm = $builder->build( + { + source => 'SearchMarcMap', + value => { + index_name => 'biblios', + marc_type => 'marc21', + marc_field => '410abcdef' + } } -}); +); -my $smtf = $builder->build({ - source => 'SearchMarcToField', - value => { - search_marc_map_id => $smm->{id}, - search_field_id => $sf->{id} +my $smtf = $builder->build( + { + source => 'SearchMarcToField', + value => { + search_marc_map_id => $smm->{id}, + search_field_id => $sf->{id} + } } -}); +); -my $smm2 = $builder->build({ - source => 'SearchMarcMap', - value => { - index_name => 'biblios', - marc_type => 'unimarc', - marc_field => '410abcdef' +my $smm2 = $builder->build( + { + source => 'SearchMarcMap', + value => { + index_name => 'biblios', + marc_type => 'unimarc', + marc_field => '410abcdef' + } } -}); +); -my $smtf2 = $builder->build({ - source => 'SearchMarcToField', - value => { - search_marc_map_id => $smm2->{id}, - search_field_id => $sf->{id} +my $smtf2 = $builder->build( + { + source => 'SearchMarcToField', + value => { + search_marc_map_id => $smm2->{id}, + search_field_id => $sf->{id} + } } -}); +); -$search_field = Koha::SearchFields->find($sf->{id}); +$search_field = Koha::SearchFields->find( $sf->{id} ); my $marc_maps = $search_field->search_marc_maps; -my $marc_map = $marc_maps->next; -is($marc_maps->count, 1, 'search_marc_maps should return 1 marc map'); -is($marc_map->get_column('index_name'), 'biblios', 'Marc map index name is biblios'); -is($marc_map->get_column('marc_type'), 'marc21', 'Marc map type is marc21'); -is($marc_map->get_column('marc_field'), '410abcdef', 'Marc map field is 410abcdef'); +my $marc_map = $marc_maps->next; +is( $marc_maps->count, 1, 'search_marc_maps should return 1 marc map' ); +is( $marc_map->get_column('index_name'), 'biblios', 'Marc map index name is biblios' ); +is( $marc_map->get_column('marc_type'), 'marc21', 'Marc map type is marc21' ); +is( $marc_map->get_column('marc_field'), '410abcdef', 'Marc map field is 410abcdef' ); -ok($search_field->is_mapped_biblios, 'Search field 1 is mapped with biblios'); +ok( $search_field->is_mapped_biblios, 'Search field 1 is mapped with biblios' ); -my $sf2 = $builder->build({ - source => 'SearchField', -}); - -my $smm3 = $builder->build({ - source => 'SearchMarcMap', - value => { - index_name => 'authorities', - marc_type => 'marc21', - marc_field => '700a' +my $sf2 = $builder->build( + { + source => 'SearchField', } -}); +); -my $smtf3 = $builder->build({ - source => 'SearchMarcToField', - value => { - search_marc_map_id => $smm3->{id}, - search_field_id => $sf2->{id} +my $smm3 = $builder->build( + { + source => 'SearchMarcMap', + value => { + index_name => 'authorities', + marc_type => 'marc21', + marc_field => '700a' + } } -}); +); -$search_field = Koha::SearchFields->find($sf2->{id}); -ok(!$search_field->is_mapped_biblios, 'Search field is mapped with authorities only'); - -my $smm4 = $builder->build({ - source => 'SearchMarcMap', - value => { - index_name => 'biblios', - marc_type => 'marc21', - marc_field => '200a' +my $smtf3 = $builder->build( + { + source => 'SearchMarcToField', + value => { + search_marc_map_id => $smm3->{id}, + search_field_id => $sf2->{id} + } } -}); +); -my $smtf4 = $builder->build({ - source => 'SearchMarcToField', - value => { - search_marc_map_id => $smm4->{id}, - search_field_id => $sf2->{id} +$search_field = Koha::SearchFields->find( $sf2->{id} ); +ok( !$search_field->is_mapped_biblios, 'Search field is mapped with authorities only' ); + +my $smm4 = $builder->build( + { + source => 'SearchMarcMap', + value => { + index_name => 'biblios', + marc_type => 'marc21', + marc_field => '200a' + } } -}); +); -$search_field = Koha::SearchFields->find($sf2->{id}); -ok($search_field->is_mapped_biblios, 'Search field is mapped with authorities and biblios'); - -my $sf3 = $builder->build({ - source => 'SearchField', - value => { - mandatory => 1, +my $smtf4 = $builder->build( + { + source => 'SearchMarcToField', + value => { + search_marc_map_id => $smm4->{id}, + search_field_id => $sf2->{id} + } } -}); +); -$search_field = Koha::SearchFields->find($sf3->{id}); -ok(!$search_field->is_mapped_biblios, 'Search field is not mapped'); +$search_field = Koha::SearchFields->find( $sf2->{id} ); +ok( $search_field->is_mapped_biblios, 'Search field is mapped with authorities and biblios' ); -ok($search_field->mandatory, 'Search field can be marked mandatory'); +my $sf3 = $builder->build( + { + source => 'SearchField', + value => { + mandatory => 1, + } + } +); + +$search_field = Koha::SearchFields->find( $sf3->{id} ); +ok( !$search_field->is_mapped_biblios, 'Search field is not mapped' ); + +ok( $search_field->mandatory, 'Search field can be marked mandatory' ); $search_field->mandatory(0)->store; -ok(!$search_field->mandatory, 'Search field can be marked not mandatory'); +ok( !$search_field->mandatory, 'Search field can be marked not mandatory' ); -Koha::SearchFields->search({})->delete; +Koha::SearchFields->search( {} )->delete; $schema->storage->txn_rollback; diff --git a/t/db_dependent/Koha/SharedContent.t b/t/db_dependent/Koha/SharedContent.t index fab02d4170..14bc0c82de 100755 --- a/t/db_dependent/Koha/SharedContent.t +++ b/t/db_dependent/Koha/SharedContent.t @@ -37,128 +37,136 @@ $schema->storage->txn_begin; my $builder = t::lib::TestBuilder->new(); -my $want_error = 0; +my $want_error = 0; my $post_request = 0; -my $query = {}; +my $query = {}; -t::lib::Mocks::mock_config( 'mana_config', 'https://foo.bar'); +t::lib::Mocks::mock_config( 'mana_config', 'https://foo.bar' ); -is(Koha::SharedContent::get_sharing_url(), 'https://foo.bar', 'Mana URL'); +is( Koha::SharedContent::get_sharing_url(), 'https://foo.bar', 'Mana URL' ); -my $result = Koha::SharedContent::search_entities('report', $query); -ok($result->{msg} =~ /Can\'t connect to foo.bar:443/, 'Unable to connect'); -is($result->{code}, 500, 'Code is 500'); +my $result = Koha::SharedContent::search_entities( 'report', $query ); +ok( $result->{msg} =~ /Can\'t connect to foo.bar:443/, 'Unable to connect' ); +is( $result->{code}, 500, 'Code is 500' ); my $ua = Test::MockModule->new('LWP::UserAgent'); -$ua->mock('simple_request', sub { +$ua->mock( + 'simple_request', + sub { return mock_response(); -}); + } +); $want_error = 1; -$query = {query => 'foo', usecomments => 1}; -$result = Koha::SharedContent::search_entities('report', $query); -ok($result->{msg} =~ /^Error thrown by decoded_content/, 'Error in decoded_content'); -is($result->{code}, 500, 'Code is 500'); +$query = { query => 'foo', usecomments => 1 }; +$result = Koha::SharedContent::search_entities( 'report', $query ); +ok( $result->{msg} =~ /^Error thrown by decoded_content/, 'Error in decoded_content' ); +is( $result->{code}, 500, 'Code is 500' ); $want_error = 0; -$query = {title => 'foo', usecomments => 1}; -$result = Koha::SharedContent::search_entities('subscription', $query); -is($result->{code}, 200, 'search_entities success'); +$query = { title => 'foo', usecomments => 1 }; +$result = Koha::SharedContent::search_entities( 'subscription', $query ); +is( $result->{code}, 200, 'search_entities success' ); -$result = Koha::SharedContent::get_entity_by_id('subscription', 23); -is($result->{code}, 200, 'get_entity_by_id success'); +$result = Koha::SharedContent::get_entity_by_id( 'subscription', 23 ); +is( $result->{code}, 200, 'get_entity_by_id success' ); my $params = { - title => 'The English historical review', - issn => '0013-8266', - ean => '', + title => 'The English historical review', + issn => '0013-8266', + ean => '', publishercode => 'Longman' }; # Search a subscription. -my $request = Koha::SharedContent::build_request('get', 'subscription', $params); -is($request->method, 'GET', 'Get subscription - Method is get'); +my $request = Koha::SharedContent::build_request( 'get', 'subscription', $params ); +is( $request->method, 'GET', 'Get subscription - Method is get' ); my %query = $request->uri->query_form; -is($query{title}, 'The English historical review', 'Check title'); -is($query{issn}, '0013-8266', 'Check issn'); -is($query{ean}, undef, 'Check ean'); -is($query{publishercode}, 'Longman', 'Check publisher'); +is( $query{title}, 'The English historical review', 'Check title' ); +is( $query{issn}, '0013-8266', 'Check issn' ); +is( $query{ean}, undef, 'Check ean' ); +is( $query{publishercode}, 'Longman', 'Check publisher' ); -is($request->uri->path, '/subscription.json', 'Path is subscription'); +is( $request->uri->path, '/subscription.json', 'Path is subscription' ); # Get a report by id. -$request = Koha::SharedContent::build_request('getwithid', 'report', 26); -is($request->method, 'GET', 'Get with id - Method is get'); +$request = Koha::SharedContent::build_request( 'getwithid', 'report', 26 ); +is( $request->method, 'GET', 'Get with id - Method is get' ); -is($request->uri->path, '/report/26.json', 'Path is report/26.json'); +is( $request->uri->path, '/report/26.json', 'Path is report/26.json' ); # Share a report. my $content = { - 'kohaversion' => '17.06.00.008', - 'language' => 'fr-FR', - 'notes' => 'some notes', + 'kohaversion' => '17.06.00.008', + 'language' => 'fr-FR', + 'notes' => 'some notes', 'report_group' => '', - 'exportemail' => 'xx@xx.com', - 'report_name' => 'A useless report', - 'savedsql' => 'SELECT * FROM ITEMS', - 'type' => undef + 'exportemail' => 'xx@xx.com', + 'report_name' => 'A useless report', + 'savedsql' => 'SELECT * FROM ITEMS', + 'type' => undef }; -$request = Koha::SharedContent::build_request('post', 'report', $content); -is($request->method, 'POST', 'Share report - Method is post'); +$request = Koha::SharedContent::build_request( 'post', 'report', $content ); +is( $request->method, 'POST', 'Share report - Method is post' ); -is($request->uri->path, '/report.json', 'Path is report.json'); +is( $request->uri->path, '/report.json', 'Path is report.json' ); # prepare shared data -my $library = $builder->build_object({ - class => 'Koha::Libraries', -}); - -my $loggedinuser = $builder->build_object({ - class => 'Koha::Patrons', - value => { - email => '', - emailpro => '', - B_email => '', - branchcode => $library->branchcode, +my $library = $builder->build_object( + { + class => 'Koha::Libraries', } -}); +); + +my $loggedinuser = $builder->build_object( + { + class => 'Koha::Patrons', + value => { + email => '', + emailpro => '', + B_email => '', + branchcode => $library->branchcode, + } + } +); my $biblio = $builder->build_sample_biblio; -my $subscriptionFrequency = $builder->build({ - source => 'SubscriptionFrequency' -}); +my $subscriptionFrequency = $builder->build( { source => 'SubscriptionFrequency' } ); -my $subscriptionNumberpattern = $builder->build({ - source => 'SubscriptionNumberpattern' -}); +my $subscriptionNumberpattern = $builder->build( { source => 'SubscriptionNumberpattern' } ); -my $subscription = $builder->build({ - source => 'Subscription', - value => { - biblionumber => $biblio->biblionumber, - periodicity => $subscriptionFrequency->{id}, - numberpattern => $subscriptionNumberpattern->{id}, - mana_id => undef +my $subscription = $builder->build( + { + source => 'Subscription', + value => { + biblionumber => $biblio->biblionumber, + periodicity => $subscriptionFrequency->{id}, + numberpattern => $subscriptionNumberpattern->{id}, + mana_id => undef + } } -}); +); -t::lib::Mocks::mock_userenv({ patron => $loggedinuser}); +t::lib::Mocks::mock_userenv( { patron => $loggedinuser } ); -t::lib::Mocks::mock_preference('language', 'en'); +t::lib::Mocks::mock_preference( 'language', 'en' ); $post_request = 1; -$result = Koha::SharedContent::send_entity('en', $loggedinuser->borrowernumber, $subscription->{subscriptionid}, 'subscription'); -is($result->{code}, 200, 'send_entity success'); +$result = Koha::SharedContent::send_entity( + 'en', $loggedinuser->borrowernumber, $subscription->{subscriptionid}, + 'subscription' +); +is( $result->{code}, 200, 'send_entity success' ); -my $s = Koha::Subscriptions->find($subscription->{subscriptionid}); -is($s->mana_id, 5, 'Mana id is set'); +my $s = Koha::Subscriptions->find( $subscription->{subscriptionid} ); +is( $s->mana_id, 5, 'Mana id is set' ); -$content = { resource_id => $subscription->{mana_id}, resource_type => 'subscription', message => 'My comment'}; -$result = Koha::SharedContent::comment_entity('resource_comment', $content); -is($result->{code}, 200, 'Comment success'); +$content = { resource_id => $subscription->{mana_id}, resource_type => 'subscription', message => 'My comment' }; +$result = Koha::SharedContent::comment_entity( 'resource_comment', $content ); +is( $result->{code}, 200, 'Comment success' ); my $data = Koha::SharedContent::prepare_entity_data( '', @@ -167,77 +175,106 @@ my $data = Koha::SharedContent::prepare_entity_data( 'subscription' ); -is($data->{language}, 'en', 'Language is set to default'); -is($data->{exportemail}, $library->branchemail, 'Email is set with the userenv branch one'); -is($data->{title}, $biblio->title, 'Shared title'); -is($data->{sfdescription}, $subscriptionFrequency->{description}, 'Shared sfdescription'); -is($data->{unit}, $subscriptionFrequency->{unit}, 'Shared unit'); -is($data->{unitsperissue}, $subscriptionFrequency->{unitsperissue}, 'Shared unitsperissue'); -is($data->{issuesperunit}, $subscriptionFrequency->{issuesperunit}, 'Shared issuesperunit'); +is( $data->{language}, 'en', 'Language is set to default' ); +is( $data->{exportemail}, $library->branchemail, 'Email is set with the userenv branch one' ); +is( $data->{title}, $biblio->title, 'Shared title' ); +is( $data->{sfdescription}, $subscriptionFrequency->{description}, 'Shared sfdescription' ); +is( $data->{unit}, $subscriptionFrequency->{unit}, 'Shared unit' ); +is( $data->{unitsperissue}, $subscriptionFrequency->{unitsperissue}, 'Shared unitsperissue' ); +is( $data->{issuesperunit}, $subscriptionFrequency->{issuesperunit}, 'Shared issuesperunit' ); -is($data->{label}, $subscriptionNumberpattern->{label}, 'Shared np label'); -is($data->{sndescription}, $subscriptionNumberpattern->{description}, 'Shared np description'); -is($data->{numberingmethod}, $subscriptionNumberpattern->{numberingmethod}, 'Shared numberingmethod'); -is($data->{label1}, $subscriptionNumberpattern->{label1}, 'Shared label1'); -is($data->{add1}, $subscriptionNumberpattern->{add1}, 'Shared add1'); -is($data->{every1}, $subscriptionNumberpattern->{every1}, 'Shared every1'); -is($data->{whenmorethan1}, $subscriptionNumberpattern->{whenmorethan1}, 'Shared whenmorethan1'); -is($data->{setto1}, $subscriptionNumberpattern->{setto1}, 'Shared setto1'); -is($data->{numbering1}, $subscriptionNumberpattern->{numbering1}, 'Shared numbering1'); +is( $data->{label}, $subscriptionNumberpattern->{label}, 'Shared np label' ); +is( $data->{sndescription}, $subscriptionNumberpattern->{description}, 'Shared np description' ); +is( $data->{numberingmethod}, $subscriptionNumberpattern->{numberingmethod}, 'Shared numberingmethod' ); +is( $data->{label1}, $subscriptionNumberpattern->{label1}, 'Shared label1' ); +is( $data->{add1}, $subscriptionNumberpattern->{add1}, 'Shared add1' ); +is( $data->{every1}, $subscriptionNumberpattern->{every1}, 'Shared every1' ); +is( $data->{whenmorethan1}, $subscriptionNumberpattern->{whenmorethan1}, 'Shared whenmorethan1' ); +is( $data->{setto1}, $subscriptionNumberpattern->{setto1}, 'Shared setto1' ); +is( $data->{numbering1}, $subscriptionNumberpattern->{numbering1}, 'Shared numbering1' ); my $biblioitem = $biblio->biblioitem; -is($data->{issn}, $biblioitem->issn, 'Shared ISSN'); -is($data->{ean}, $biblioitem->ean, 'Shared EAN'); -is($data->{publishercode}, $biblioitem->publishercode, 'Shared publishercode'); +is( $data->{issn}, $biblioitem->issn, 'Shared ISSN' ); +is( $data->{ean}, $biblioitem->ean, 'Shared EAN' ); +is( $data->{publishercode}, $biblioitem->publishercode, 'Shared publishercode' ); sub mock_response { my $response = Test::MockObject->new(); if ($want_error) { - $response->mock('code', sub { - return 500; - }); - $response->mock('is_error', sub { - return 0; - }); - $response->mock('decoded_content', sub { - die 'Error thrown by decoded_content'; - }); - } elsif ( $post_request ) { - $response->mock('code', sub { - return 200; - }); - $response->mock('is_error', sub { - return 0; - }); - $response->mock('decoded_content', sub { - return '{"code": "200", "msg": "foo", "id": "5"}'; - }); + $response->mock( + 'code', + sub { + return 500; + } + ); + $response->mock( + 'is_error', + sub { + return 0; + } + ); + $response->mock( + 'decoded_content', + sub { + die 'Error thrown by decoded_content'; + } + ); + } elsif ($post_request) { + $response->mock( + 'code', + sub { + return 200; + } + ); + $response->mock( + 'is_error', + sub { + return 0; + } + ); + $response->mock( + 'decoded_content', + sub { + return '{"code": "200", "msg": "foo", "id": "5"}'; + } + ); } else { - $response->mock('code', sub { - return 200; - }); - $response->mock('is_error', sub { - return 0; - }); - $response->mock('decoded_content', sub { - return ''; - }); + $response->mock( + 'code', + sub { + return 200; + } + ); + $response->mock( + 'is_error', + sub { + return 0; + } + ); + $response->mock( + 'decoded_content', + sub { + return ''; + } + ); } } # Increment request. -$request = Koha::SharedContent::build_request('increment', - 'subscription', - 12, - 'foo'); +$request = Koha::SharedContent::build_request( + 'increment', + 'subscription', + 12, + 'foo' +); -is($request->method, 'POST', 'Increment subscription - Method is post'); +is( $request->method, 'POST', 'Increment subscription - Method is post' ); %query = $request->uri->query_form; -is($query{id}, 12, 'Check id'); -is($query{step}, 1, 'Step is default'); -is($query{resource}, 'subscription', 'Check ressource'); +is( $query{id}, 12, 'Check id' ); +is( $query{step}, 1, 'Step is default' ); +is( $query{resource}, 'subscription', 'Check ressource' ); -is($request->uri->path, '/subscription/12.json/increment/foo', 'Path is subscription'); +is( $request->uri->path, '/subscription/12.json/increment/foo', 'Path is subscription' ); $schema->storage->txn_rollback; diff --git a/t/db_dependent/Koha/Subscription.t b/t/db_dependent/Koha/Subscription.t index e32f871bf5..c5c98dffc9 100755 --- a/t/db_dependent/Koha/Subscription.t +++ b/t/db_dependent/Koha/Subscription.t @@ -32,47 +32,51 @@ use t::lib::TestBuilder; my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; -my $builder = t::lib::TestBuilder->new; +my $builder = t::lib::TestBuilder->new; use_ok('Koha::Subscription'); subtest 'Koha::Subscription->biblio' => sub { plan tests => 1; - my $biblio = Koha::Biblio->new()->store(); - my $subscription = Koha::Subscription->new({ - biblionumber => $biblio->biblionumber, - })->store(); + my $biblio = Koha::Biblio->new()->store(); + my $subscription = Koha::Subscription->new( + { + biblionumber => $biblio->biblionumber, + } + )->store(); my $b = $subscription->biblio; - is($b->biblionumber, $biblio->biblionumber, 'Koha::Subscription->biblio returns the correct biblio'); + is( $b->biblionumber, $biblio->biblionumber, 'Koha::Subscription->biblio returns the correct biblio' ); }; subtest 'Notifications on new issues - add_subscriber|remove_subscriber|subscribers' => sub { plan tests => 5; - my $subscriber_1 = $builder->build_object( { class => 'Koha::Patrons' }); - my $subscriber_2 = $builder->build_object( { class => 'Koha::Patrons' }); + my $subscriber_1 = $builder->build_object( { class => 'Koha::Patrons' } ); + my $subscriber_2 = $builder->build_object( { class => 'Koha::Patrons' } ); - my $subscription = Koha::Subscription->new({ - biblionumber => Koha::Biblio->new->store->biblionumber, - })->store(); + my $subscription = Koha::Subscription->new( + { + biblionumber => Koha::Biblio->new->store->biblionumber, + } + )->store(); my $subscribers = $subscription->subscribers; - is( $subscribers->count, 0, '->subscribers should return 0 if there are no subscribers'); - is( ref($subscribers), 'Koha::Patrons', '->subscribers should return a Koha::Patrons object'); + is( $subscribers->count, 0, '->subscribers should return 0 if there are no subscribers' ); + is( ref($subscribers), 'Koha::Patrons', '->subscribers should return a Koha::Patrons object' ); - $subscription->add_subscriber( $subscriber_1 ); - $subscription->add_subscriber( $subscriber_2 ); + $subscription->add_subscriber($subscriber_1); + $subscription->add_subscriber($subscriber_2); $subscribers = $subscription->subscribers; is( $subscribers->count, 2, '->subscribers should return 2 if there are 2 subscribers' ); - $subscription->remove_subscriber( $subscriber_1 ); + $subscription->remove_subscriber($subscriber_1); $subscribers = $subscription->subscribers; is( $subscribers->count, 1, '->remove_subscriber should have remove the subscriber' ); - $subscription->remove_subscriber( $subscriber_1 ); # We do not explode if the patron is not a subscriber + $subscription->remove_subscriber($subscriber_1); # We do not explode if the patron is not a subscriber my $is_subscriber = $subscribers->find( $subscriber_2->borrowernumber ); ok( $is_subscriber, 'This structure is used in the code and should work as expected' ); @@ -81,7 +85,7 @@ subtest 'Notifications on new issues - add_subscriber|remove_subscriber|subscrib subtest 'Koha::Subscription->vendor' => sub { plan tests => 3; - my $vendor = $builder->build_object( { class => 'Koha::Acquisition::Booksellers' } ); + my $vendor = $builder->build_object( { class => 'Koha::Acquisition::Booksellers' } ); my $subscription = $builder->build_object( { class => 'Koha::Subscriptions', @@ -104,15 +108,21 @@ subtest 'Koha::Subscription->vendor' => sub { subtest 'Koha::Subscription->frequency' => sub { plan tests => 2; - my $frequency = $builder->build_object( { class => 'Koha::Subscription::Frequencies' } ); + my $frequency = $builder->build_object( { class => 'Koha::Subscription::Frequencies' } ); my $subscription = $builder->build_object( { - class => 'Koha::Subscriptions', - value => { periodicity => $frequency->id } + class => 'Koha::Subscriptions', + value => { periodicity => $frequency->id } } ); - is( ref($subscription->frequency), 'Koha::Subscription::Frequency', 'Koha::Subscription->frequency should return a Koha::Subscription::Frequency' ); - is( $subscription->frequency->id, $frequency->id, 'Koha::Subscription->frequency should return the correct frequency' ); + is( + ref( $subscription->frequency ), 'Koha::Subscription::Frequency', + 'Koha::Subscription->frequency should return a Koha::Subscription::Frequency' + ); + is( + $subscription->frequency->id, $frequency->id, + 'Koha::Subscription->frequency should return the correct frequency' + ); }; my $nb_of_subs = Koha::Subscriptions->search->count; @@ -141,11 +151,15 @@ is( $biblio_1->biblionumber, 'The link between sub and biblio is well done' ); -is( $sub_1->{periodicity}, $sub_freq_1->{id}, - 'The link between sub and sub_freq is well done' ); -is( $sub_1->{numberpattern}, +is( + $sub_1->{periodicity}, $sub_freq_1->{id}, + 'The link between sub and sub_freq is well done' +); +is( + $sub_1->{numberpattern}, $sub_np_1->{id}, - 'The link between sub and sub_numberpattern is well done' ); + 'The link between sub and sub_numberpattern is well done' +); my $ref = { 'title' => $biblio_1->title, @@ -180,8 +194,10 @@ my $ref = { 'publishercode' => $bi_1->publishercode, }; -is_deeply( Koha::Subscription->get_sharable_info( $sub_1->{subscriptionid} ), - $ref, "get_sharable_info function is ok" ); +is_deeply( + Koha::Subscription->get_sharable_info( $sub_1->{subscriptionid} ), + $ref, "get_sharable_info function is ok" +); $schema->storage->txn_rollback; diff --git a/t/db_dependent/Koha/Subscription/Numberpatterns.t b/t/db_dependent/Koha/Subscription/Numberpatterns.t index 6aa26c4f40..63635504f1 100755 --- a/t/db_dependent/Koha/Subscription/Numberpatterns.t +++ b/t/db_dependent/Koha/Subscription/Numberpatterns.t @@ -32,66 +32,68 @@ my $builder = t::lib::TestBuilder->new; my $dbh = C4::Context->dbh; $dbh->do('DELETE FROM subscription_numberpatterns'); -my $numberpattern = $builder->build({ - source => 'SubscriptionNumberpattern', - value => { - label => 'Volume, Number, Issue', - description => 'Volume Number Issue 1', - numberingmethod => 'Vol.{X}, Number {Y}, Issue {Z}', - label1 => 'Volume', - add1 => '1', - every1 => '48', - whenmorethan1 => '99999', - setto1 => '1', - numbering1 => undef, - label2 => 'Number', - add2 => '1', - every2 => '4', - whenmorethan2 => '12', - setto2 => '1', - numbering2 => undef, - label3 => 'Issue', - add3 => '1', - every3 => '1', - whenmorethan3 => '4', - setto3 => '1', - numbering3 => undef +my $numberpattern = $builder->build( + { + source => 'SubscriptionNumberpattern', + value => { + label => 'Volume, Number, Issue', + description => 'Volume Number Issue 1', + numberingmethod => 'Vol.{X}, Number {Y}, Issue {Z}', + label1 => 'Volume', + add1 => '1', + every1 => '48', + whenmorethan1 => '99999', + setto1 => '1', + numbering1 => undef, + label2 => 'Number', + add2 => '1', + every2 => '4', + whenmorethan2 => '12', + setto2 => '1', + numbering2 => undef, + label3 => 'Issue', + add3 => '1', + every3 => '1', + whenmorethan3 => '4', + setto3 => '1', + numbering3 => undef + } } -}); +); my $search_ok = { - umberingmethod => 'Vol.{X}, Number {Y}, Issue {Z}', - label1 => 'Volume', add1 => '1', every1 => '48', - whenmorethan1 => '99999', setto1 => '1', - label2 => 'Number', add2 => '1', every2 => '4', - whenmorethan2 => '12', setto2 => '1', - label3 => 'Issue', add3 => '1', every3 => '1', - whenmorethan3 => '4', setto3 => '1', + umberingmethod => 'Vol.{X}, Number {Y}, Issue {Z}', + label1 => 'Volume', add1 => '1', every1 => '48', + whenmorethan1 => '99999', setto1 => '1', + label2 => 'Number', add2 => '1', every2 => '4', + whenmorethan2 => '12', setto2 => '1', + label3 => 'Issue', add3 => '1', every3 => '1', + whenmorethan3 => '4', setto3 => '1', numbering_pattern => 'mana' }; my $number_pattern_id = Koha::Subscription::Numberpatterns->new_or_existing($search_ok); -is($number_pattern_id, $numberpattern->{id}, 'new_or_existing method should find the existing number pattern'); +is( $number_pattern_id, $numberpattern->{id}, 'new_or_existing method should find the existing number pattern' ); -$number_pattern_id = Koha::Subscription::Numberpatterns->new_or_existing({numbering_pattern => 1}); -is($number_pattern_id, 1, 'new_or_existing method should return passed numbering_pattern'); +$number_pattern_id = Koha::Subscription::Numberpatterns->new_or_existing( { numbering_pattern => 1 } ); +is( $number_pattern_id, 1, 'new_or_existing method should return passed numbering_pattern' ); my $search_not_ok = { - patternname => 'Number', - sndescription => 'Simple Numbering method', - numberingmethod => 'No.{X}', - label1 => 'Number', - add1 => 1, - every1 => 1, - whenmorethan1 => 99999, - setto1 => 1, + patternname => 'Number', + sndescription => 'Simple Numbering method', + numberingmethod => 'No.{X}', + label1 => 'Number', + add1 => 1, + every1 => 1, + whenmorethan1 => 99999, + setto1 => 1, numbering_pattern => 'mana' }; $number_pattern_id = Koha::Subscription::Numberpatterns->new_or_existing($search_not_ok); my $new_number_pattern = Koha::Subscription::Numberpatterns->find($number_pattern_id); -is($new_number_pattern->label, 'Number'); -is($new_number_pattern->description, 'Simple Numbering method'); -is($new_number_pattern->numberingmethod, 'No.{X}'); +is( $new_number_pattern->label, 'Number' ); +is( $new_number_pattern->description, 'Simple Numbering method' ); +is( $new_number_pattern->numberingmethod, 'No.{X}' ); $schema->storage->txn_rollback; diff --git a/t/db_dependent/Koha/Subscription/Routinglists.t b/t/db_dependent/Koha/Subscription/Routinglists.t index 1eff86ca54..83ad435fdd 100755 --- a/t/db_dependent/Koha/Subscription/Routinglists.t +++ b/t/db_dependent/Koha/Subscription/Routinglists.t @@ -35,32 +35,38 @@ subtest 'new() tests' => sub { $schema->storage->txn_begin; - my $biblio = Koha::Biblio->new()->store(); - my $subscription = Koha::Subscription->new({ - biblionumber => $biblio->biblionumber, + my $biblio = Koha::Biblio->new()->store(); + my $subscription = Koha::Subscription->new( + { + biblionumber => $biblio->biblionumber, } )->store; - my $library = $builder->build_object({ class => 'Koha::Libraries' }); - my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { branchcode => $library->id } }); + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); + my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { branchcode => $library->id } } ); my $routinglist_count = Koha::Subscription::Routinglists->count; - my $routinglist = Koha::Subscription::Routinglist->new({ - borrowernumber => $patron->borrowernumber, - ranking => 1, - subscriptionid => $subscription->subscriptionid - })->store; + my $routinglist = Koha::Subscription::Routinglist->new( + { + borrowernumber => $patron->borrowernumber, + ranking => 1, + subscriptionid => $subscription->subscriptionid + } + )->store; - is( Koha::Subscription::Routinglists->search->count, $routinglist_count +1, 'One routing list added' ); + is( Koha::Subscription::Routinglists->search->count, $routinglist_count + 1, 'One routing list added' ); my $retrieved_routinglist = Koha::Subscription::Routinglists->find( $routinglist->routingid ); - is ( $retrieved_routinglist->routingid, $routinglist->routingid, "Find a routing list by id returns the correct routing list"); + is( + $retrieved_routinglist->routingid, $routinglist->routingid, + "Find a routing list by id returns the correct routing list" + ); $routinglist->ranking(4)->update; - is ( $routinglist->ranking, 4, "Routing list ranking has been updated"); + is( $routinglist->ranking, 4, "Routing list ranking has been updated" ); $routinglist->delete; - is ( Koha::Subscription::Routinglists->search->count, $routinglist_count, 'One subscription list deleted' ); + is( Koha::Subscription::Routinglists->search->count, $routinglist_count, 'One subscription list deleted' ); }; diff --git a/t/db_dependent/Koha/Suggestion.t b/t/db_dependent/Koha/Suggestion.t index 1de342436e..ccf5c5af9b 100755 --- a/t/db_dependent/Koha/Suggestion.t +++ b/t/db_dependent/Koha/Suggestion.t @@ -36,12 +36,12 @@ subtest 'suggester() tests' => sub { $schema->storage->txn_begin; my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); - my $suggestion = $builder->build_object( - { class => 'Koha::Suggestions', value => { suggestedby => undef } } ); + my $suggestion = $builder->build_object( { class => 'Koha::Suggestions', value => { suggestedby => undef } } ); is( $suggestion->suggester, undef, 'Returns undef if no suggester' ); + # Set a borrowernumber - $suggestion->suggestedby($patron->borrowernumber)->store->discard_changes; + $suggestion->suggestedby( $patron->borrowernumber )->store->discard_changes; my $suggester = $suggestion->suggester; is( ref($suggester), 'Koha::Patron', 'Type is correct for suggester' ); is_deeply( $patron->unblessed, $suggester->unblessed, 'It returns the right patron' ); diff --git a/t/db_dependent/Koha/Suggestions.t b/t/db_dependent/Koha/Suggestions.t index 1254248e43..dd032d22f3 100755 --- a/t/db_dependent/Koha/Suggestions.t +++ b/t/db_dependent/Koha/Suggestions.t @@ -39,33 +39,39 @@ my $biblio_2 = $builder->build_sample_biblio; my $patron = $builder->build( { source => 'Borrower' } ); my $nb_of_suggestions = Koha::Suggestions->search->count; my $new_suggestion_1 = Koha::Suggestion->new( - { suggestedby => $patron->{borrowernumber}, + { + suggestedby => $patron->{borrowernumber}, biblionumber => $biblio_1->biblionumber, } )->store; my $new_suggestion_2 = Koha::Suggestion->new( - { suggestedby => $patron->{borrowernumber}, + { + suggestedby => $patron->{borrowernumber}, biblionumber => $biblio_2->biblionumber, } )->store; subtest 'store' => sub { plan tests => 8; - my $suggestion = Koha::Suggestion->new( - { suggestedby => $patron->{borrowernumber}, + my $suggestion = Koha::Suggestion->new( + { + suggestedby => $patron->{borrowernumber}, biblionumber => $biblio_1->biblionumber, } )->store; is( $suggestion->suggesteddate, dt_from_string()->ymd, "If suggesteddate not passed in, it will default to today" ); - my $two_days_ago = dt_from_string->subtract( days => 2 ); - my $two_days_ago_sql = output_pref({dt => $two_days_ago, dateformat => 'sql', dateonly => 1 }); + my $two_days_ago = dt_from_string->subtract( days => 2 ); + my $two_days_ago_sql = output_pref( { dt => $two_days_ago, dateformat => 'sql', dateonly => 1 } ); $suggestion->suggesteddate($two_days_ago)->store; $suggestion = Koha::Suggestions->find( $suggestion->suggestionid ); is( $suggestion->suggesteddate, $two_days_ago_sql, 'If suggesteddate passed in, it should be taken into account' ); $suggestion->reason('because!')->store; $suggestion = Koha::Suggestions->find( $suggestion->suggestionid ); - is( $suggestion->suggesteddate, $two_days_ago_sql, 'If suggestion id modified, suggesteddate should not be modified' ); + is( + $suggestion->suggesteddate, $two_days_ago_sql, + 'If suggestion id modified, suggesteddate should not be modified' + ); t::lib::Mocks::mock_preference( 'EmailPurchaseSuggestions', 0 ); Koha::Notice::Messages->search->delete; @@ -124,7 +130,10 @@ like( $new_suggestion_1->suggestionid, qr|^\d+$|, 'Adding a new suggestion shoul is( Koha::Suggestions->search->count, $nb_of_suggestions + 2, 'The 2 suggestions should have been added' ); my $retrieved_suggestion_1 = Koha::Suggestions->find( $new_suggestion_1->suggestionid ); -is( $retrieved_suggestion_1->biblionumber, $new_suggestion_1->biblionumber, 'Find a suggestion by id should return the correct suggestion' ); +is( + $retrieved_suggestion_1->biblionumber, $new_suggestion_1->biblionumber, + 'Find a suggestion by id should return the correct suggestion' +); $retrieved_suggestion_1->delete; is( Koha::Suggestions->search->count, $nb_of_suggestions + 1, 'Delete should have deleted the suggestion' ); @@ -158,41 +167,50 @@ subtest 'constraints' => sub { ); my $nonexistent_borrowernumber = $patron->borrowernumber; + # suggestedby $patron->delete; $suggestion = $suggestion->get_from_storage; - is( $suggestion->suggestedby, undef, - "The suggestion is not deleted when the related patron is deleted" ); + is( + $suggestion->suggestedby, undef, + "The suggestion is not deleted when the related patron is deleted" + ); # biblionumber $biblio->delete; $suggestion = $suggestion->get_from_storage; - is( $suggestion->biblionumber, undef, - "The suggestion is not deleted when the related biblio is deleted" ); + is( + $suggestion->biblionumber, undef, + "The suggestion is not deleted when the related biblio is deleted" + ); # branchcode $branch->delete; $suggestion = $suggestion->get_from_storage; - is( $suggestion->branchcode, undef, - "The suggestion is not deleted when the related branch is deleted" ); + is( + $suggestion->branchcode, undef, + "The suggestion is not deleted when the related branch is deleted" + ); # managerid - { # hide useless warnings + { # hide useless warnings local *STDERR; open STDERR, '>', '/dev/null'; throws_ok { $suggestion->managedby($nonexistent_borrowernumber)->store; } 'Koha::Exceptions::Object::FKConstraint', - 'store raises an exception on invalid managerid'; + 'store raises an exception on invalid managerid'; close STDERR; } my $manager = $builder->build_object( { class => "Koha::Patrons" } ); $suggestion->managedby( $manager->borrowernumber )->store; $manager->delete; $suggestion = $suggestion->get_from_storage; - is( $suggestion->managedby, undef, - "The suggestion is not deleted when the related manager is deleted" ); + is( + $suggestion->managedby, undef, + "The suggestion is not deleted when the related manager is deleted" + ); # acceptedby { # hide useless warnings @@ -202,15 +220,17 @@ subtest 'constraints' => sub { $suggestion->acceptedby($nonexistent_borrowernumber)->store; } 'Koha::Exceptions::Object::FKConstraint', - 'store raises an exception on invalid acceptedby id'; + 'store raises an exception on invalid acceptedby id'; close STDERR; } my $acceptor = $builder->build_object( { class => "Koha::Patrons" } ); $suggestion->acceptedby( $acceptor->borrowernumber )->store; $acceptor->delete; $suggestion = $suggestion->get_from_storage; - is( $suggestion->acceptedby, undef, - "The suggestion is not deleted when the related acceptor is deleted" ); + is( + $suggestion->acceptedby, undef, + "The suggestion is not deleted when the related acceptor is deleted" + ); # rejectedby { # hide useless warnings @@ -220,15 +240,17 @@ subtest 'constraints' => sub { $suggestion->rejectedby($nonexistent_borrowernumber)->store; } 'Koha::Exceptions::Object::FKConstraint', - 'store raises an exception on invalid rejectedby id'; + 'store raises an exception on invalid rejectedby id'; close STDERR; } my $rejecter = $builder->build_object( { class => "Koha::Patrons" } ); $suggestion->rejectedby( $rejecter->borrowernumber )->store; $rejecter->delete; $suggestion = $suggestion->get_from_storage; - is( $suggestion->rejectedby, undef, - "The suggestion is not deleted when the related rejecter is deleted" ); + is( + $suggestion->rejectedby, undef, + "The suggestion is not deleted when the related rejecter is deleted" + ); # budgetid { # hide useless warnings @@ -237,15 +259,17 @@ subtest 'constraints' => sub { throws_ok { $suggestion->budgetid($nonexistent_borrowernumber)->store; } 'Koha::Exceptions::Object::FKConstraint', - 'store raises an exception on invalid budgetid'; + 'store raises an exception on invalid budgetid'; close STDERR; } my $fund = $builder->build_object( { class => "Koha::Acquisition::Funds" } ); $suggestion->budgetid( $fund->id )->store; $fund->delete; $suggestion = $suggestion->get_from_storage; - is( $suggestion->budgetid, undef, - "The suggestion is not deleted when the related budget is deleted" ); + is( + $suggestion->budgetid, undef, + "The suggestion is not deleted when the related budget is deleted" + ); $schema->storage->dbh->{PrintError} = $print_error; $schema->storage->txn_rollback; @@ -257,18 +281,26 @@ subtest 'manager, suggester, rejecter, last_modifier' => sub { my $suggestion = $builder->build_object( { class => 'Koha::Suggestions' } ); - is( ref( $suggestion->manager ), + is( + ref( $suggestion->manager ), 'Koha::Patron', - '->manager should have returned a Koha::Patron object' ); - is( ref( $suggestion->rejecter ), + '->manager should have returned a Koha::Patron object' + ); + is( + ref( $suggestion->rejecter ), 'Koha::Patron', - '->rejecter should have returned a Koha::Patron object' ); - is( ref( $suggestion->suggester ), + '->rejecter should have returned a Koha::Patron object' + ); + is( + ref( $suggestion->suggester ), 'Koha::Patron', - '->suggester should have returned a Koha::Patron object' ); - is( ref( $suggestion->last_modifier ), + '->suggester should have returned a Koha::Patron object' + ); + is( + ref( $suggestion->last_modifier ), 'Koha::Patron', - '->last_modifier should have returned a Koha::Patron object' ); + '->last_modifier should have returned a Koha::Patron object' + ); $suggestion->set( { @@ -279,15 +311,23 @@ subtest 'manager, suggester, rejecter, last_modifier' => sub { } ); - is( $suggestion->manager, undef, - '->manager should have returned undef if no manager set' ); - is( $suggestion->rejecter, undef, - '->rejecter should have returned undef if no rejecter set' ); - is( $suggestion->suggester, undef, - '->suggester should have returned undef if no suggester set' ); - is( $suggestion->last_modifier, + is( + $suggestion->manager, undef, + '->manager should have returned undef if no manager set' + ); + is( + $suggestion->rejecter, undef, + '->rejecter should have returned undef if no rejecter set' + ); + is( + $suggestion->suggester, undef, + '->suggester should have returned undef if no suggester set' + ); + is( + $suggestion->last_modifier, undef, - '->last_modifier should have returned undef if no last_modifier set' ); + '->last_modifier should have returned undef if no last_modifier set' + ); $schema->storage->txn_rollback; }; @@ -298,14 +338,18 @@ subtest 'fund' => sub { $schema->storage->txn_begin; my $suggestion = $builder->build_object( { class => 'Koha::Suggestions' } ); - is( ref( $suggestion->fund ), + is( + ref( $suggestion->fund ), 'Koha::Acquisition::Fund', - '->fund should have returned a Koha::Acquisition::Fund object' ); + '->fund should have returned a Koha::Acquisition::Fund object' + ); $suggestion->set( { budgetid => undef } ); - is( $suggestion->fund, undef, - '->fund should have returned undef if not fund set' ); + is( + $suggestion->fund, undef, + '->fund should have returned undef if not fund set' + ); $schema->storage->txn_rollback; }; @@ -317,8 +361,8 @@ subtest 'search_limited() tests' => sub { $schema->storage->txn_begin; # Two libraries - my $library_1 = $builder->build_object({ class => 'Koha::Libraries' }); - my $library_2 = $builder->build_object({ class => 'Koha::Libraries' }); + my $library_1 = $builder->build_object( { class => 'Koha::Libraries' } ); + my $library_2 = $builder->build_object( { class => 'Koha::Libraries' } ); # A patron from $library_1, that is not superlibrarian at all my $patron = $builder->build_object( @@ -350,12 +394,13 @@ subtest 'search_limited() tests' => sub { my $resultset = Koha::Suggestions->search( { branchcode => [ $library_1->id, $library_2->id ] }, - { order_by => { -desc => ['author'] } } ); + { order_by => { -desc => ['author'] } } + ); is( $resultset->count, 3, 'Only this three suggestions are returned' ); # Now the tests - t::lib::Mocks::mock_userenv({ patron => $patron, branchcode => $library_1->id }); + t::lib::Mocks::mock_userenv( { patron => $patron, branchcode => $library_1->id } ); # Disable IndependentBranches t::lib::Mocks::mock_preference( 'IndependentBranches', 0 ); @@ -372,8 +417,9 @@ subtest 'search_limited() tests' => sub { # Make the patron superlibrarian to override IndependentBranches $patron->flags(1)->store; + # So it reloads C4::Context->userenv->{flags} - t::lib::Mocks::mock_userenv({ patron => $patron, branchcode => $library_1->id }); + t::lib::Mocks::mock_userenv( { patron => $patron, branchcode => $library_1->id } ); $filtered_rs = $resultset->search_limited; is( $filtered_rs->count, 3, 'IndependentBranches but patron is superlibrarian, all suggestions returned' ); @@ -391,9 +437,10 @@ subtest 'filter_by_pending() tests' => sub { my $suggestion_2 = $builder->build_object( { class => 'Koha::Suggestions', value => { STATUS => 'ACCEPTED' } } ); my $suggestion_3 = $builder->build_object( { class => 'Koha::Suggestions', value => { STATUS => 'ASKED' } } ); - my $suggestions = - Koha::Suggestions->search( { suggestionid => [ $suggestion_1->id, $suggestion_2->id, $suggestion_3->id ] }, - { order_by => ['suggestionid'] } ); + my $suggestions = Koha::Suggestions->search( + { suggestionid => [ $suggestion_1->id, $suggestion_2->id, $suggestion_3->id ] }, + { order_by => ['suggestionid'] } + ); is( $suggestions->count, 3 ); @@ -425,9 +472,10 @@ subtest 'filter_by_suggested_days_range() tests' => sub { my $suggestion_3 = $builder->build_object( { class => 'Koha::Suggestions', value => { suggesteddate => $dtf->format_date($today_minus_three) } } ); - my $suggestions = - Koha::Suggestions->search( { suggestionid => [ $suggestion_1->id, $suggestion_2->id, $suggestion_3->id ] }, - { order_by => ['suggestionid'] } ); + my $suggestions = Koha::Suggestions->search( + { suggestionid => [ $suggestion_1->id, $suggestion_2->id, $suggestion_3->id ] }, + { order_by => ['suggestionid'] } + ); is( $suggestions->count, 3 ); diff --git a/t/db_dependent/Koha/Tags.t b/t/db_dependent/Koha/Tags.t index a1a3939fd7..e66aa36697 100755 --- a/t/db_dependent/Koha/Tags.t +++ b/t/db_dependent/Koha/Tags.t @@ -24,7 +24,7 @@ use t::lib::TestBuilder; use Koha::Database; use Koha::Tags; -my $schema = Koha::Database->schema; +my $schema = Koha::Database->schema; my $builder = t::lib::TestBuilder->new; subtest 'search() tests' => sub { @@ -35,8 +35,8 @@ subtest 'search() tests' => sub { my $current_count = Koha::Tags->search->count; - my $approval_1 = $builder->build_object({ class => 'Koha::Tags' }); - my $approval_2 = $builder->build_object({ class => 'Koha::Tags' }); + my $approval_1 = $builder->build_object( { class => 'Koha::Tags' } ); + my $approval_2 = $builder->build_object( { class => 'Koha::Tags' } ); is( Koha::Tags->search->count, $current_count + 2, 'Tags count consistent' ); diff --git a/t/db_dependent/Koha/Tags/Approvals.t b/t/db_dependent/Koha/Tags/Approvals.t index dc2a438a0e..ce18008246 100755 --- a/t/db_dependent/Koha/Tags/Approvals.t +++ b/t/db_dependent/Koha/Tags/Approvals.t @@ -24,7 +24,7 @@ use t::lib::TestBuilder; use Koha::Database; use Koha::Tags::Approvals; -my $schema = Koha::Database->schema; +my $schema = Koha::Database->schema; my $builder = t::lib::TestBuilder->new; subtest 'search() tests' => sub { @@ -35,8 +35,8 @@ subtest 'search() tests' => sub { my $current_count = Koha::Tags::Approvals->search->count; - my $approval_1 = $builder->build_object({ class => 'Koha::Tags::Approvals' }); - my $approval_2 = $builder->build_object({ class => 'Koha::Tags::Approvals' }); + my $approval_1 = $builder->build_object( { class => 'Koha::Tags::Approvals' } ); + my $approval_2 = $builder->build_object( { class => 'Koha::Tags::Approvals' } ); is( Koha::Tags::Approvals->search->count, $current_count + 2, 'Approvals count consistent' ); diff --git a/t/db_dependent/Koha/Tags/Indexes.t b/t/db_dependent/Koha/Tags/Indexes.t index 770bee33b6..888d3c1c55 100755 --- a/t/db_dependent/Koha/Tags/Indexes.t +++ b/t/db_dependent/Koha/Tags/Indexes.t @@ -24,7 +24,7 @@ use t::lib::TestBuilder; use Koha::Database; use Koha::Tags::Indexes; -my $schema = Koha::Database->schema; +my $schema = Koha::Database->schema; my $builder = t::lib::TestBuilder->new; subtest 'search() tests' => sub { @@ -35,8 +35,8 @@ subtest 'search() tests' => sub { my $current_count = Koha::Tags::Indexes->search->count; - my $approval_1 = $builder->build_object({ class => 'Koha::Tags::Indexes' }); - my $approval_2 = $builder->build_object({ class => 'Koha::Tags::Indexes' }); + my $approval_1 = $builder->build_object( { class => 'Koha::Tags::Indexes' } ); + my $approval_2 = $builder->build_object( { class => 'Koha::Tags::Indexes' } ); is( Koha::Tags::Indexes->search->count, $current_count + 2, 'Indexes count consistent' ); diff --git a/t/db_dependent/Koha/Template/Plugin/Asset.t b/t/db_dependent/Koha/Template/Plugin/Asset.t index 0d507ad135..9620fe8550 100755 --- a/t/db_dependent/Koha/Template/Plugin/Asset.t +++ b/t/db_dependent/Koha/Template/Plugin/Asset.t @@ -6,74 +6,76 @@ use Test::More tests => 16; use Template; use Test::MockModule; -my $version = "22.0509045"; -my $koha_module = Test::MockModule->new( "Koha" ); +my $version = "22.0509045"; +my $koha_module = Test::MockModule->new("Koha"); $koha_module->mock( "version", sub { return "22.05.09.045" } ); -my $template = Template->new({ - PLUGIN_BASE => 'Koha::Template::Plugin', -}); +my $template = Template->new( + { + PLUGIN_BASE => 'Koha::Template::Plugin', + } +); my $intranet_vars = { interface => '/intranet-tmpl', - theme => 'prog', + theme => 'prog', }; my $opac_vars = { interface => '/opac-tmpl', - theme => 'bootstrap', + theme => 'bootstrap', }; my $output; $output = ''; -$template->process(url_template("js/staff-global.js"), $intranet_vars, \$output); -is($output, "/intranet-tmpl/prog/js/staff-global_$version.js"); +$template->process( url_template("js/staff-global.js"), $intranet_vars, \$output ); +is( $output, "/intranet-tmpl/prog/js/staff-global_$version.js" ); $output = ''; -$template->process(url_template("js/browser.js"), $intranet_vars, \$output); -is($output, "/intranet-tmpl/prog/js/browser_$version.js"); +$template->process( url_template("js/browser.js"), $intranet_vars, \$output ); +is( $output, "/intranet-tmpl/prog/js/browser_$version.js" ); $output = ''; -$template->process(url_template("css/staff-global.css"), $intranet_vars, \$output); -is($output, "/intranet-tmpl/prog/css/staff-global_$version.css"); +$template->process( url_template("css/staff-global.css"), $intranet_vars, \$output ); +is( $output, "/intranet-tmpl/prog/css/staff-global_$version.css" ); $output = ''; -$template->process(url_template("lib/fontawesome/css/fontawesome.min.css"), $intranet_vars, \$output); -is($output, "/intranet-tmpl/lib/fontawesome/css/fontawesome.min_$version.css"); +$template->process( url_template("lib/fontawesome/css/fontawesome.min.css"), $intranet_vars, \$output ); +is( $output, "/intranet-tmpl/lib/fontawesome/css/fontawesome.min_$version.css" ); $output = ''; -$template->process(url_template("js/global.js"), $opac_vars, \$output); -is($output, "/opac-tmpl/bootstrap/js/global_$version.js"); +$template->process( url_template("js/global.js"), $opac_vars, \$output ); +is( $output, "/opac-tmpl/bootstrap/js/global_$version.js" ); $output = ''; -$template->process(url_template("lib/datatables/datatables.min.js"), $opac_vars, \$output); -is($output, "/opac-tmpl/lib/datatables/datatables.min_$version.js"); +$template->process( url_template("lib/datatables/datatables.min.js"), $opac_vars, \$output ); +is( $output, "/opac-tmpl/lib/datatables/datatables.min_$version.js" ); $output = ''; -$template->process(url_template("css/opac.css"), $opac_vars, \$output); -is($output, "/opac-tmpl/bootstrap/css/opac_$version.css"); +$template->process( url_template("css/opac.css"), $opac_vars, \$output ); +is( $output, "/opac-tmpl/bootstrap/css/opac_$version.css" ); $output = ''; -$template->process(url_template("lib/emoji-picker/css/emoji.css"), $opac_vars, \$output); -is($output, "/opac-tmpl/lib/emoji-picker/css/emoji_$version.css"); +$template->process( url_template("lib/emoji-picker/css/emoji.css"), $opac_vars, \$output ); +is( $output, "/opac-tmpl/lib/emoji-picker/css/emoji_$version.css" ); $output = ''; -$template->process(css_template("css/opac.css"), $opac_vars, \$output); -like($output, qr/<link .*href="\/opac-tmpl\/bootstrap\/css\/opac_\Q$version\E\.css".*>/); -like($output, qr/<link .*type="text\/css".*>/); -like($output, qr/<link .*rel="stylesheet".*>/); +$template->process( css_template("css/opac.css"), $opac_vars, \$output ); +like( $output, qr/<link .*href="\/opac-tmpl\/bootstrap\/css\/opac_\Q$version\E\.css".*>/ ); +like( $output, qr/<link .*type="text\/css".*>/ ); +like( $output, qr/<link .*rel="stylesheet".*>/ ); $output = ''; -$template->process(\'[% USE Asset %][% Asset.css("css/print.css", { media = "print" }) %]', $opac_vars, \$output); -like($output, qr/<link .*href="\/opac-tmpl\/bootstrap\/css\/print_\Q$version\E\.css".*>/); -like($output, qr/<link .*type="text\/css".*>/); -like($output, qr/<link .*rel="stylesheet".*>/); -like($output, qr/<link .*media="print".*>/); +$template->process( \'[% USE Asset %][% Asset.css("css/print.css", { media = "print" }) %]', $opac_vars, \$output ); +like( $output, qr/<link .*href="\/opac-tmpl\/bootstrap\/css\/print_\Q$version\E\.css".*>/ ); +like( $output, qr/<link .*type="text\/css".*>/ ); +like( $output, qr/<link .*rel="stylesheet".*>/ ); +like( $output, qr/<link .*media="print".*>/ ); $output = ''; -$template->process(js_template("js/global.js"), $opac_vars, \$output); -like($output, qr/<script .*src="\/opac-tmpl\/bootstrap\/js\/global_\Q$version\E\.js".*>/); +$template->process( js_template("js/global.js"), $opac_vars, \$output ); +like( $output, qr/<script .*src="\/opac-tmpl\/bootstrap\/js\/global_\Q$version\E\.js".*>/ ); sub url_template { my ($filename) = @_; diff --git a/t/db_dependent/Koha/Template/Plugin/ClassSources.t b/t/db_dependent/Koha/Template/Plugin/ClassSources.t index d897838b7d..70cad83f87 100755 --- a/t/db_dependent/Koha/Template/Plugin/ClassSources.t +++ b/t/db_dependent/Koha/Template/Plugin/ClassSources.t @@ -24,66 +24,72 @@ BEGIN { use_ok('Koha::Template::Plugin::ClassSources'); } -my $schema = Koha::Database->schema; +my $schema = Koha::Database->schema; subtest 'all' => sub { plan tests => 4; $schema->storage->txn_begin; $schema->resultset('ClassSource')->delete(); - $schema->resultset('ClassSource')->create({ - cn_source => 'anscr', - description => 'ANSCR (Sound Recordings)', - used => 0, - class_sort_rule => 'generic', - class_split_rule => 'generic', - }); - $schema->resultset('ClassSource')->create({ - cn_source => 'ddc', - description => 'Dewey Decimal Classification', - used => 1, - class_sort_rule => 'dewey', - class_split_rule => 'dewey', - }); - $schema->resultset('ClassSource')->create({ - cn_source => 'z', - description => 'Other/Generic Classification Scheme', - used => 0, - class_sort_rule => 'generic', - class_split_rule => 'generic', - }); + $schema->resultset('ClassSource')->create( + { + cn_source => 'anscr', + description => 'ANSCR (Sound Recordings)', + used => 0, + class_sort_rule => 'generic', + class_split_rule => 'generic', + } + ); + $schema->resultset('ClassSource')->create( + { + cn_source => 'ddc', + description => 'Dewey Decimal Classification', + used => 1, + class_sort_rule => 'dewey', + class_split_rule => 'dewey', + } + ); + $schema->resultset('ClassSource')->create( + { + cn_source => 'z', + description => 'Other/Generic Classification Scheme', + used => 0, + class_sort_rule => 'generic', + class_split_rule => 'generic', + } + ); - t::lib::Mocks::mock_preference('DefaultClassificationSource', ''); + t::lib::Mocks::mock_preference( 'DefaultClassificationSource', '' ); my $plugin = Koha::Template::Plugin::ClassSources->new(); subtest 'when given no parameters' => sub { plan tests => 2; my @class_sources = $plugin->all(); - is(scalar @class_sources, 1, 'it returns only "used" class sources'); - is($class_sources[0]->used, 1, 'it returns only "used" class sources'); + is( scalar @class_sources, 1, 'it returns only "used" class sources' ); + is( $class_sources[0]->used, 1, 'it returns only "used" class sources' ); }; subtest 'when given parameter "selected"' => sub { plan tests => 1; - my @class_sources = $plugin->all({ selected => 'anscr' }); + my @class_sources = $plugin->all( { selected => 'anscr' } ); - ok(scalar @class_sources == 2, 'it returns "used" class sources and the selected one'); + ok( scalar @class_sources == 2, 'it returns "used" class sources and the selected one' ); }; subtest 'when DefaultClassificationSource is set to a not used class source' => sub { plan tests => 1; - t::lib::Mocks::mock_preference('DefaultClassificationSource', 'anscr'); + t::lib::Mocks::mock_preference( 'DefaultClassificationSource', 'anscr' ); my @class_sources = $plugin->all(); - ok(scalar @class_sources == 2, 'it returns "used" class sources and the default one'); + ok( scalar @class_sources == 2, 'it returns "used" class sources and the default one' ); }; subtest 'when DefaultClassificationSource is set and "selected" parameter is given' => sub { plan tests => 1; - t::lib::Mocks::mock_preference('DefaultClassificationSource', 'anscr'); - my @class_sources = $plugin->all({ selected => 'z' }); - ok(scalar @class_sources == 3, 'it returns "used" class sources, the default one and the selected one'); + t::lib::Mocks::mock_preference( 'DefaultClassificationSource', 'anscr' ); + my @class_sources = $plugin->all( { selected => 'z' } ); + ok( scalar @class_sources == 3, 'it returns "used" class sources, the default one and the selected one' ); }; $schema->storage->txn_rollback; diff --git a/t/db_dependent/Koha/Template/Plugin/ItemTypes.t b/t/db_dependent/Koha/Template/Plugin/ItemTypes.t index 59726397e5..cfaa4b97d7 100755 --- a/t/db_dependent/Koha/Template/Plugin/ItemTypes.t +++ b/t/db_dependent/Koha/Template/Plugin/ItemTypes.t @@ -38,10 +38,10 @@ my $plugin = Koha::Template::Plugin::ItemTypes->new(); ok( $plugin, "initialized ItemTypes plugin" ); my $GetDescriptionUndef = $plugin->GetDescription(undef); -is($GetDescriptionUndef, q{}, "GetDescription call with undef"); +is( $GetDescriptionUndef, q{}, "GetDescription call with undef" ); my $GetDescriptionUnknown = $plugin->GetDescription("deliriumtremenssyndrome"); -is($GetDescriptionUnknown, q{}, "GetDescription call with unknown type"); +is( $GetDescriptionUnknown, q{}, "GetDescription call with unknown type" ); my $itemtypeA = $builder->build_object( { @@ -62,7 +62,7 @@ Koha::Localization->new( )->store; my $itemtypeB = $builder->build_object( { - class => 'Koha::ItemTypes', + class => 'Koha::ItemTypes', value => { parent_type => $itemtypeA->itemtype, description => "Desc itemtype B", @@ -87,18 +87,24 @@ my $itemtypeC = $builder->build_object( } ); -my $GetDescriptionA1 = $plugin->GetDescription($itemtypeA->itemtype); -is($GetDescriptionA1, "Translated itemtype A", "ItemType without parent - GetDescription without want parent"); -my $GetDescriptionA2 = $plugin->GetDescription($itemtypeA->itemtype, 1); -is($GetDescriptionA2, "Translated itemtype A", "ItemType without parent - GetDescription with want parent"); +my $GetDescriptionA1 = $plugin->GetDescription( $itemtypeA->itemtype ); +is( $GetDescriptionA1, "Translated itemtype A", "ItemType without parent - GetDescription without want parent" ); +my $GetDescriptionA2 = $plugin->GetDescription( $itemtypeA->itemtype, 1 ); +is( $GetDescriptionA2, "Translated itemtype A", "ItemType without parent - GetDescription with want parent" ); -my $GetDescriptionB1 = $plugin->GetDescription($itemtypeB->itemtype); -is($GetDescriptionB1, "Translated itemtype B", "ItemType with parent - GetDescription without want parent"); -my $GetDescriptionB2 = $plugin->GetDescription($itemtypeB->itemtype, 1); -is($GetDescriptionB2, "Translated itemtype A->Translated itemtype B", "ItemType with parent - GetDescription with want parent"); +my $GetDescriptionB1 = $plugin->GetDescription( $itemtypeB->itemtype ); +is( $GetDescriptionB1, "Translated itemtype B", "ItemType with parent - GetDescription without want parent" ); +my $GetDescriptionB2 = $plugin->GetDescription( $itemtypeB->itemtype, 1 ); +is( + $GetDescriptionB2, "Translated itemtype A->Translated itemtype B", + "ItemType with parent - GetDescription with want parent" +); -my $GetDescriptionC1 = $plugin->GetDescription($itemtypeC->itemtype); -is($GetDescriptionC1, "Desc itemtype C", "ItemType without parent - GetDescription without want parent - No translation"); +my $GetDescriptionC1 = $plugin->GetDescription( $itemtypeC->itemtype ); +is( + $GetDescriptionC1, "Desc itemtype C", + "ItemType without parent - GetDescription without want parent - No translation" +); $itemtypeC->description("New desc itemtype C")->store(); @@ -106,8 +112,11 @@ $itemtypeC->description("New desc itemtype C")->store(); my $memory_cache = Koha::Cache::Memory::Lite->get_instance(); $memory_cache->flush; -$GetDescriptionC1 = $plugin->GetDescription($itemtypeC->itemtype); -is($GetDescriptionC1, "New desc itemtype C", "ItemType without parent - GetDescription without want parent - No translation - updated value returned"); +$GetDescriptionC1 = $plugin->GetDescription( $itemtypeC->itemtype ); +is( + $GetDescriptionC1, "New desc itemtype C", + "ItemType without parent - GetDescription without want parent - No translation - updated value returned" +); $schema->storage->txn_rollback; diff --git a/t/db_dependent/Koha/Template/Plugin/JSConsents.t b/t/db_dependent/Koha/Template/Plugin/JSConsents.t index 27428f0bbe..37f14a487a 100755 --- a/t/db_dependent/Koha/Template/Plugin/JSConsents.t +++ b/t/db_dependent/Koha/Template/Plugin/JSConsents.t @@ -28,7 +28,7 @@ subtest "all" => sub { { 'name' => 'test', 'cookiePath' => '/', - 'code' => + 'code' => 'KGZ1bmN0aW9uKCkgeyAKICAgIGNvbnNvbGUubG9nKCdIZWxsbyBmcm9tIHRlc3QxJyk7IAogICAgZG9jdW1lbnQuY29va2llID0gInRlc3QxPXRlc3Rpbmc7IGRvbWFpbj1sb2NhbGhvc3Q7IHBhdGg9LzsgU2FtZVNpdGU9Tm9uZTsgU2VjdXJlIjsgCn0pKCk7', 'staffConsent' => 1, 'matchPattern' => 'test1', diff --git a/t/db_dependent/Koha/Template/Plugin/KohaPlugins.t b/t/db_dependent/Koha/Template/Plugin/KohaPlugins.t index 4e34e60288..f17d6d3e23 100755 --- a/t/db_dependent/Koha/Template/Plugin/KohaPlugins.t +++ b/t/db_dependent/Koha/Template/Plugin/KohaPlugins.t @@ -8,7 +8,7 @@ use CGI; use File::Basename; use File::Spec; use File::Temp qw( tempdir tempfile ); -use FindBin qw($Bin); +use FindBin qw($Bin); use Archive::Extract; use Module::Load::Conditional qw(can_load); use Test::MockModule; @@ -33,25 +33,40 @@ $schema->storage->txn_begin; # Enable all plugins my $plugins = Koha::Plugins->new; $plugins->InstallPlugins; -my @plugins = $plugins->GetPlugins({ all => 1, class => 'Koha::Plugin::Test' }); +my @plugins = $plugins->GetPlugins( { all => 1, class => 'Koha::Plugin::Test' } ); map { $_->enable; } @plugins; -my $mock_plugin = Test::MockModule->new( 'Koha::Plugin::Test' ); -$mock_plugin->mock( 'test_template', sub { - my ( $self, $file ) = @_; - my $template = $self->get_template({ file => $file }); - $template->param( filename => $file ); - return $template->output; -}); +my $mock_plugin = Test::MockModule->new('Koha::Plugin::Test'); +$mock_plugin->mock( + 'test_template', + sub { + my ( $self, $file ) = @_; + my $template = $self->get_template( { file => $file } ); + $template->param( filename => $file ); + return $template->output; + } +); use_ok( 'Koha::Template::Plugin::KohaPlugins', 'Can use Koha::Template::Plugin::KohaPlugins' ); ok( my $plugin = Koha::Template::Plugin::KohaPlugins->new(), 'Able to instantiate template plugin' ); -ok( index( $plugin->get_plugins_opac_js, 'Koha::Plugin::Test::opac_js' ) != -1, 'Test plugin opac_js return value is part of code returned by get_plugins_opac_js' ); -ok( index( $plugin->get_plugins_opac_head, 'Koha::Plugin::Test::opac_head' ) != -1, 'Test plugin opac_head return value is part of code returned by get_plugins_opac_head' ); -ok( index( $plugin->get_plugins_intranet_js, 'Koha::Plugin::Test::intranet_js' ) != -1, 'Test plugin intranet_js return value is part of code returned by get_plugins_intranet_js' ); -ok( index( $plugin->get_plugins_intranet_head, 'Koha::Plugin::Test::intranet_head' ) != -1, 'Test plugin intranet_head return value is part of code returned by get_plugins_intranet_head' ); +ok( + index( $plugin->get_plugins_opac_js, 'Koha::Plugin::Test::opac_js' ) != -1, + 'Test plugin opac_js return value is part of code returned by get_plugins_opac_js' +); +ok( + index( $plugin->get_plugins_opac_head, 'Koha::Plugin::Test::opac_head' ) != -1, + 'Test plugin opac_head return value is part of code returned by get_plugins_opac_head' +); +ok( + index( $plugin->get_plugins_intranet_js, 'Koha::Plugin::Test::intranet_js' ) != -1, + 'Test plugin intranet_js return value is part of code returned by get_plugins_intranet_js' +); +ok( + index( $plugin->get_plugins_intranet_head, 'Koha::Plugin::Test::intranet_head' ) != -1, + 'Test plugin intranet_head return value is part of code returned by get_plugins_intranet_head' +); sub boom { my ( $self, $file ) = @_; @@ -61,15 +76,19 @@ $mock_plugin->mock( 'opac_head', \&boom ); $mock_plugin->mock( 'opac_js', \&boom ); $mock_plugin->mock( 'intranet_head', \&boom ); $mock_plugin->mock( 'intranet_js', \&boom ); -warning_like { $plugin->get_plugins_opac_head } qr{Error calling 'opac_head' on the Koha::Plugin::Testplugin \(Something wrong is happening in this hook}; -warning_like { $plugin->get_plugins_opac_js } qr{Error calling 'opac_js' on the Koha::Plugin::Testplugin \(Something wrong is happening in this hook}; -warning_like { $plugin->get_plugins_intranet_head } qr{Error calling 'intranet_head' on the Koha::Plugin::Testplugin \(Something wrong is happening in this hook}; -warning_like { $plugin->get_plugins_intranet_js } qr{Error calling 'intranet_js' on the Koha::Plugin::Testplugin \(Something wrong is happening in this hook}; +warning_like { $plugin->get_plugins_opac_head } +qr{Error calling 'opac_head' on the Koha::Plugin::Testplugin \(Something wrong is happening in this hook}; +warning_like { $plugin->get_plugins_opac_js } +qr{Error calling 'opac_js' on the Koha::Plugin::Testplugin \(Something wrong is happening in this hook}; +warning_like { $plugin->get_plugins_intranet_head } +qr{Error calling 'intranet_head' on the Koha::Plugin::Testplugin \(Something wrong is happening in this hook}; +warning_like { $plugin->get_plugins_intranet_js } +qr{Error calling 'intranet_js' on the Koha::Plugin::Testplugin \(Something wrong is happening in this hook}; -t::lib::Mocks::mock_config('enable_plugins',0); -is( $plugin->get_plugins_opac_js, q{}, 'Test plugin opac_js return value is empty' ); -is( $plugin->get_plugins_opac_head, q{}, 'Test plugin opac_head return value is empty' ); -is( $plugin->get_plugins_intranet_js, q{}, 'Test plugin intranet_js return value is empty' ); +t::lib::Mocks::mock_config( 'enable_plugins', 0 ); +is( $plugin->get_plugins_opac_js, q{}, 'Test plugin opac_js return value is empty' ); +is( $plugin->get_plugins_opac_head, q{}, 'Test plugin opac_head return value is empty' ); +is( $plugin->get_plugins_intranet_js, q{}, 'Test plugin intranet_js return value is empty' ); is( $plugin->get_plugins_intranet_head, q{}, 'Test plugin intranet_head return value is empty' ); $schema->storage->txn_rollback; diff --git a/t/db_dependent/Koha/Template/Plugin/Registers.t b/t/db_dependent/Koha/Template/Plugin/Registers.t index 9c361bde70..a8b6393479 100755 --- a/t/db_dependent/Koha/Template/Plugin/Registers.t +++ b/t/db_dependent/Koha/Template/Plugin/Registers.t @@ -38,11 +38,15 @@ subtest 'session_register_id' => sub { my $plugin = Koha::Template::Plugin::Registers->new(); ok( $plugin, "Plugin initialized" ); - is( $plugin->session_register_id, - '', "Returns empty string if no userenv is set" ); + is( + $plugin->session_register_id, + '', "Returns empty string if no userenv is set" + ); t::lib::Mocks::mock_userenv( { register_id => '1' } ); - is( $plugin->session_register_id, - '1', "Returns the register id when set in the userenv" ); + is( + $plugin->session_register_id, + '1', "Returns the register id when set in the userenv" + ); # Unset the userenv C4::Context->unset_userenv(); @@ -54,11 +58,15 @@ subtest 'session_register_name' => sub { my $plugin = Koha::Template::Plugin::Registers->new(); ok( $plugin, "Plugin initialized" ); - is( $plugin->session_register_name, - '', "Returns empty string if no userenv is set" ); + is( + $plugin->session_register_name, + '', "Returns empty string if no userenv is set" + ); t::lib::Mocks::mock_userenv( { register_name => 'Register One' } ); - is( $plugin->session_register_name, - 'Register One', "Returns the register name when set in the userenv" ); + is( + $plugin->session_register_name, + 'Register One', "Returns the register name when set in the userenv" + ); # Unset the userenv C4::Context->unset_userenv(); @@ -72,16 +80,14 @@ subtest 'all() tests' => sub { t::lib::Mocks::mock_preference( 'UseCashRegisters', 1 ); - my $count = Koha::Cash::Registers->search({ archived => 0 })->count; - my $max_register = Koha::Cash::Registers->search( {}, - { order_by => { '-desc' => 'id' }, rows => 1 } )->single; + my $count = Koha::Cash::Registers->search( { archived => 0 } )->count; + my $max_register = Koha::Cash::Registers->search( + {}, + { order_by => { '-desc' => 'id' }, rows => 1 } + )->single; my $max_id = $max_register ? $max_register->id : 0; - my $library1 = $builder->build_object( - { - class => 'Koha::Libraries' - } - ); + my $library1 = $builder->build_object( { class => 'Koha::Libraries' } ); my $register1 = $builder->build_object( { class => 'Koha::Cash::Registers', @@ -103,11 +109,7 @@ subtest 'all() tests' => sub { } ); - my $library2 = $builder->build_object( - { - class => 'Koha::Libraries' - } - ); + my $library2 = $builder->build_object( { class => 'Koha::Libraries' } ); my $register3 = $builder->build_object( { class => 'Koha::Cash::Registers', @@ -123,75 +125,90 @@ subtest 'all() tests' => sub { my $result = $plugin->all; is( ref($result), 'ARRAY', "Return arrayref (no userenv, no filters)" ); - is( scalar( @{$result} ), - 3 + $count, "Array contains all test registers (no userenv, no filters)" ); + is( + scalar( @{$result} ), + 3 + $count, "Array contains all test registers (no userenv, no filters)" + ); for my $register ( @{$result} ) { next if $register->{id} <= $max_id; is( $register->{selected}, 0, "Register is not selected (no userenv)" ); } $result = $plugin->all( { filters => { current_branch => 1 } } ); - is( ref($result), 'ARRAY', - "Return arrayref (no userenv, filters: current_branch)" ); + is( + ref($result), 'ARRAY', + "Return arrayref (no userenv, filters: current_branch)" + ); t::lib::Mocks::mock_userenv( { branchcode => $library1->branchcode } ); $result = $plugin->all; - is( ref($result), 'ARRAY', - "Return arrayref (userenv: branchcode, no filters)" ); - is( scalar( @{$result} ), - 3 + $count, "Array contains all test registers (userenv: branchcode, no filters)" ); - for my $register ( @{$result} ) { - next if $register->{id} <= $max_id; - is( $register->{selected}, 0, - "Register is not selected (userenv: branchcode, no filters)" ); - } - - $result = $plugin->all( { filters => { current_branch => 1 } } ); - is( ref($result), 'ARRAY', - "Return arrayref (userenv: branchcode, filters: current_branch)" ); + is( + ref($result), 'ARRAY', + "Return arrayref (userenv: branchcode, no filters)" + ); is( scalar( @{$result} ), - 2, -"Array contains 2 branch registers (userenv: branchcode, filters: current_branch)" + 3 + $count, "Array contains all test registers (userenv: branchcode, no filters)" ); for my $register ( @{$result} ) { - is( $register->{selected}, 0, -"Register is not selected (userenv: branchcode, filters: current_branch)" + next if $register->{id} <= $max_id; + is( + $register->{selected}, 0, + "Register is not selected (userenv: branchcode, no filters)" ); } - t::lib::Mocks::mock_userenv( - { branchcode => $library1->branchcode, register_id => $register2->id } - ); $result = $plugin->all( { filters => { current_branch => 1 } } ); - is( ref($result), 'ARRAY', -"Return arrayref (userenv: branchcode + register_id, filters: current_branch)" + is( + ref($result), 'ARRAY', + "Return arrayref (userenv: branchcode, filters: current_branch)" ); is( scalar( @{$result} ), 2, -"Array contains 2 branch registers (userenv: branchcode + register_id, filters: current_branch)" + "Array contains 2 branch registers (userenv: branchcode, filters: current_branch)" + ); + for my $register ( @{$result} ) { + is( + $register->{selected}, 0, + "Register is not selected (userenv: branchcode, filters: current_branch)" + ); + } + + t::lib::Mocks::mock_userenv( { branchcode => $library1->branchcode, register_id => $register2->id } ); + $result = $plugin->all( { filters => { current_branch => 1 } } ); + is( + ref($result), 'ARRAY', + "Return arrayref (userenv: branchcode + register_id, filters: current_branch)" + ); + is( + scalar( @{$result} ), + 2, + "Array contains 2 branch registers (userenv: branchcode + register_id, filters: current_branch)" ); for my $register ( @{$result} ) { my $selected = ( $register->{id} == $register2->id ) ? 1 : 0; - is( $register->{selected}, $selected, -"Register is selected $selected (userenv: brancode, filters: current_branch)" + is( + $register->{selected}, $selected, + "Register is selected $selected (userenv: brancode, filters: current_branch)" ); } $result = $plugin->all( { filters => { current_branch => 1 }, selected => $register1->id } ); - is( ref($result), 'ARRAY', -"Return arrayref (userenv: branchcode + register_id, filters: current_branch, selected: register 1)" + is( + ref($result), 'ARRAY', + "Return arrayref (userenv: branchcode + register_id, filters: current_branch, selected: register 1)" ); is( scalar( @{$result} ), 2, -"Array contains 2 branch registers (userenv: branchcode + register_id, filters: current_branch, selected: register 1)" + "Array contains 2 branch registers (userenv: branchcode + register_id, filters: current_branch, selected: register 1)" ); for my $register ( @{$result} ) { my $selected = ( $register->{id} == $register1->id ) ? 1 : 0; - is( $register->{selected}, $selected, -"Register is selected $selected (userenv: brancode, filters: current_branch, selected: register 1)" + is( + $register->{selected}, $selected, + "Register is selected $selected (userenv: brancode, filters: current_branch, selected: register 1)" ); } diff --git a/t/db_dependent/Koha/Template/Plugin/TablesSettings.t b/t/db_dependent/Koha/Template/Plugin/TablesSettings.t index 0aa04fa6de..08a5289bad 100755 --- a/t/db_dependent/Koha/Template/Plugin/TablesSettings.t +++ b/t/db_dependent/Koha/Template/Plugin/TablesSettings.t @@ -9,7 +9,7 @@ use Test::More tests => 3; use t::lib::Mocks; BEGIN { - use_ok('Koha::Template::Plugin::TablesSettings', "Can use Koha::Template::Plugin::TablesSettings"); + use_ok( 'Koha::Template::Plugin::TablesSettings', "Can use Koha::Template::Plugin::TablesSettings" ); } ok( my $settings = Koha::Template::Plugin::TablesSettings->new(), 'Able to instantiate template plugin' ); @@ -17,8 +17,14 @@ ok( my $settings = Koha::Template::Plugin::TablesSettings->new(), 'Able to insta subtest "is_hidden" => sub { plan tests => 2; - is( $settings->is_hidden('opac', 'biblio-detail', 'holdingst', 'item_materials'), 1, 'Returns true if the column is hidden'); - is( $settings->is_hidden('opac', 'biblio-detail', 'holdingst', 'item_callnumber'), 0, 'Returns false if the column is not hidden'); + is( + $settings->is_hidden( 'opac', 'biblio-detail', 'holdingst', 'item_materials' ), 1, + 'Returns true if the column is hidden' + ); + is( + $settings->is_hidden( 'opac', 'biblio-detail', 'holdingst', 'item_callnumber' ), 0, + 'Returns false if the column is not hidden' + ); }; 1; diff --git a/t/db_dependent/Koha/Ticket.t b/t/db_dependent/Koha/Ticket.t index adee018514..c31fdc04fb 100755 --- a/t/db_dependent/Koha/Ticket.t +++ b/t/db_dependent/Koha/Ticket.t @@ -34,19 +34,17 @@ subtest 'reporter() tests' => sub { $schema->storage->txn_begin; - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $ticket = $builder->build_object( { class => 'Koha::Tickets', - value => { - reporter_id => $patron->id - } + value => { reporter_id => $patron->id } } ); my $reporter = $ticket->reporter; is( ref($reporter), 'Koha::Patron', 'Koha::Ticket->reporter returns a Koha::Patron object' ); - is( $reporter->id, $patron->id, 'Koha::Ticket->reporter returns the right Koha::Patron' ); + is( $reporter->id, $patron->id, 'Koha::Ticket->reporter returns the right Koha::Patron' ); $schema->storage->txn_rollback; }; @@ -78,19 +76,17 @@ subtest 'resolver() tests' => sub { $schema->storage->txn_begin; - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $ticket = $builder->build_object( { class => 'Koha::Tickets', - value => { - resolver_id => $patron->id - } + value => { resolver_id => $patron->id } } ); my $resolver = $ticket->resolver; is( ref($resolver), 'Koha::Patron', 'Koha::Ticket->resolver returns a Koha::Patron object' ); - is( $resolver->id, $patron->id, 'Koha::Ticket->resolver returns the right Koha::Patron' ); + is( $resolver->id, $patron->id, 'Koha::Ticket->resolver returns the right Koha::Patron' ); $schema->storage->txn_rollback; }; @@ -101,19 +97,17 @@ subtest 'biblio() tests' => sub { $schema->storage->txn_begin; - my $biblio = $builder->build_object({ class => 'Koha::Biblios' }); + my $biblio = $builder->build_object( { class => 'Koha::Biblios' } ); my $ticket = $builder->build_object( { class => 'Koha::Tickets', - value => { - biblio_id => $biblio->id - } + value => { biblio_id => $biblio->id } } ); my $related_biblio = $ticket->biblio; is( ref($related_biblio), 'Koha::Biblio', 'Koha::Ticket->biblio returns a Koha::Biblio object' ); - is( $related_biblio->id, $biblio->id, 'Koha::Ticket->biblio returns the right Koha::Biblio' ); + is( $related_biblio->id, $biblio->id, 'Koha::Ticket->biblio returns the right Koha::Biblio' ); $schema->storage->txn_rollback; }; @@ -124,13 +118,13 @@ subtest 'updates() tests' => sub { $schema->storage->txn_begin; - my $ticket = $builder->build_object( { class => 'Koha::Tickets' } ); + my $ticket = $builder->build_object( { class => 'Koha::Tickets' } ); my $updates = $ticket->updates; is( ref($updates), 'Koha::Ticket::Updates', 'Koha::Ticket->updates should return a Koha::Ticket::Updates object' ); is( $updates->count, 0, 'Koha::Ticket->updates should return a count of 0 when there are no related updates' ); # Add two updates - foreach (1..2) { + foreach ( 1 .. 2 ) { $builder->build_object( { class => 'Koha::Ticket::Updates', @@ -141,7 +135,7 @@ subtest 'updates() tests' => sub { $updates = $ticket->updates; is( ref($updates), 'Koha::Ticket::Updates', 'Koha::Ticket->updates should return a Koha::Ticket::Updates object' ); - is( $updates->count, 2, 'Koha::Ticket->updates should return the correct number of updates' ); + is( $updates->count, 2, 'Koha::Ticket->updates should return the correct number of updates' ); $schema->storage->txn_rollback; }; @@ -154,14 +148,15 @@ subtest 'add_update() tests' => sub { my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $ticket = $builder->build_object( { class => 'Koha::Tickets' } ); - my $update = $ticket->add_update( - { user_id => $patron->id, public => 1, message => "Some message" } ); - is( ref($update), 'Koha::Ticket::Update', + my $update = $ticket->add_update( { user_id => $patron->id, public => 1, message => "Some message" } ); + is( + ref($update), 'Koha::Ticket::Update', 'Koha::Ticket->add_update should return a Koha::Ticket::Update object' ); my $updates = $ticket->updates; - is( $updates->count, 1, + is( + $updates->count, 1, 'Koha::Ticket->add_update should have added 1 update linked to this ticket' ); @@ -188,20 +183,25 @@ subtest 'store() tests' => sub { } )->store(); - is( ref($new_ticket), 'Koha::Ticket', - 'Koha::Ticket->store() returned the Koha::Ticket object' ); - my $notices = - Koha::Notice::Messages->search( { borrowernumber => $patron->id } ); - is( $notices->count, 1, - 'One acknowledgement notice queued for the ticket reporter' ); + is( + ref($new_ticket), 'Koha::Ticket', + 'Koha::Ticket->store() returned the Koha::Ticket object' + ); + my $notices = Koha::Notice::Messages->search( { borrowernumber => $patron->id } ); + is( + $notices->count, 1, + 'One acknowledgement notice queued for the ticket reporter' + ); my $THE_notice = $notices->next; - isnt( $THE_notice->status, 'pending', - 'Acknowledgement notice is sent immediately' ); + isnt( + $THE_notice->status, 'pending', + 'Acknowledgement notice is sent immediately' + ); $new_ticket->set( { title => "Changed title" } )->store(); - $notices = - Koha::Notice::Messages->search( { borrowernumber => $patron->id } ); - is( $notices->count, 1, + $notices = Koha::Notice::Messages->search( { borrowernumber => $patron->id } ); + is( + $notices->count, 1, 'Further acknowledgement notices are not queud on subsequent stores' ); @@ -228,20 +228,25 @@ subtest 'store() tests' => sub { } )->store(); - is( ref($new_ticket), 'Koha::Ticket', - 'Koha::Ticket->store() returned the Koha::Ticket object' ); - my $notices = - Koha::Notice::Messages->search( { to_address => $catemail } ); - is( $notices->count, 1, - 'One notification notice queued for the catalogers when ticket reported' ); + is( + ref($new_ticket), 'Koha::Ticket', + 'Koha::Ticket->store() returned the Koha::Ticket object' + ); + my $notices = Koha::Notice::Messages->search( { to_address => $catemail } ); + is( + $notices->count, 1, + 'One notification notice queued for the catalogers when ticket reported' + ); my $THE_notice = $notices->next; - isnt( $THE_notice->status, 'pending', - 'Notification notice is sent immediately' ); + isnt( + $THE_notice->status, 'pending', + 'Notification notice is sent immediately' + ); $new_ticket->set( { title => "Changed title" } )->store(); - $notices = - Koha::Notice::Messages->search( { to_address => $catemail } ); - is( $notices->count, 1, + $notices = Koha::Notice::Messages->search( { to_address => $catemail } ); + is( + $notices->count, 1, 'Further notification notices are not queud on subsequent stores' ); diff --git a/t/db_dependent/Koha/Ticket/Update.t b/t/db_dependent/Koha/Ticket/Update.t index ec33fa89fc..cd7d3cbd7c 100755 --- a/t/db_dependent/Koha/Ticket/Update.t +++ b/t/db_dependent/Koha/Ticket/Update.t @@ -33,19 +33,17 @@ subtest 'ticket() tests' => sub { $schema->storage->txn_begin; - my $ticket = $builder->build_object({ class => 'Koha::Tickets' }); + my $ticket = $builder->build_object( { class => 'Koha::Tickets' } ); my $update = $builder->build_object( { class => 'Koha::Ticket::Updates', - value => { - ticket_id => $ticket->id - } + value => { ticket_id => $ticket->id } } ); my $linked_ticket = $update->ticket; is( ref($linked_ticket), 'Koha::Ticket', 'Koha::Ticket::Update->ticket returns a Koha::Ticket object' ); - is( $linked_ticket->id, $ticket->id, 'Koha::Ticket::Update->ticket returns the right Koha::Ticket' ); + is( $linked_ticket->id, $ticket->id, 'Koha::Ticket::Update->ticket returns the right Koha::Ticket' ); $schema->storage->txn_rollback; }; @@ -56,19 +54,17 @@ subtest 'user() tests' => sub { $schema->storage->txn_begin; - my $user = $builder->build_object({ class => 'Koha::Patrons' }); + my $user = $builder->build_object( { class => 'Koha::Patrons' } ); my $update = $builder->build_object( { class => 'Koha::Ticket::Updates', - value => { - user_id => $user->id - } + value => { user_id => $user->id } } ); my $linked_user = $update->user; is( ref($linked_user), 'Koha::Patron', 'Koha::Ticket::Update->user returns a Koha::Patron object' ); - is( $linked_user->id, $user->id, 'Koha::Ticket::Update->user returns the right Koha::Patron' ); + is( $linked_user->id, $user->id, 'Koha::Ticket::Update->user returns the right Koha::Patron' ); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/Koha/UI/Form/Builder/Biblio.t b/t/db_dependent/Koha/UI/Form/Builder/Biblio.t index b331d06b37..6354684521 100755 --- a/t/db_dependent/Koha/UI/Form/Builder/Biblio.t +++ b/t/db_dependent/Koha/UI/Form/Builder/Biblio.t @@ -41,15 +41,15 @@ subtest 'generate_subfield_form default value' => sub { my $subfield = $builder->generate_subfield_form( { - tag => '999', - subfield => '9', - value => '', - index_tag => int(rand(1000000)), - tagslib => { + tag => '999', + subfield => '9', + value => '', + index_tag => int( rand(1000000) ), + tagslib => { '999' => { '9' => { defaultvalue => 'The date is <<YYYY>>-<<MM>>-<<DD>> and user is <<USER>>', - hidden => 0, + hidden => 0, } } }, @@ -57,7 +57,7 @@ subtest 'generate_subfield_form default value' => sub { ); my $today = dt_from_string()->ymd; - is($subfield->{marc_value}->{value}, "The date is $today and user is superlibrarian"); + is( $subfield->{marc_value}->{value}, "The date is $today and user is superlibrarian" ); }; subtest 'generate_subfield_form branches' => sub { @@ -65,28 +65,28 @@ subtest 'generate_subfield_form branches' => sub { my $subfield = $builder->generate_subfield_form( { - tag => '999', - subfield => '9', - value => '', - index_tag => int(rand(1000000)), - tagslib => { + tag => '999', + subfield => '9', + value => '', + index_tag => int( rand(1000000) ), + tagslib => { '999' => { '9' => { authorised_value => 'branches', - hidden => 0, + hidden => 0, } } }, }, ); - my @libraries = Koha::Libraries->search({}, {order_by => 'branchname'})->as_list; - my %labels = map { $_->branchcode => $_->branchname } @libraries; - my @values = map { $_->branchcode } @libraries; + my @libraries = Koha::Libraries->search( {}, { order_by => 'branchname' } )->as_list; + my %labels = map { $_->branchcode => $_->branchname } @libraries; + my @values = map { $_->branchcode } @libraries; - is($subfield->{marc_value}->{type}, 'select'); - is_deeply($subfield->{marc_value}->{labels}, \%labels); - is_deeply($subfield->{marc_value}->{values}, \@values); + is( $subfield->{marc_value}->{type}, 'select' ); + is_deeply( $subfield->{marc_value}->{labels}, \%labels ); + is_deeply( $subfield->{marc_value}->{values}, \@values ); }; subtest 'generate_subfield_form itemtypes' => sub { @@ -94,15 +94,15 @@ subtest 'generate_subfield_form itemtypes' => sub { my $subfield = $builder->generate_subfield_form( { - tag => '999', - subfield => '9', - value => '', - index_tag => int(rand(1000000)), - tagslib => { + tag => '999', + subfield => '9', + value => '', + index_tag => int( rand(1000000) ), + tagslib => { '999' => { '9' => { authorised_value => 'itemtypes', - hidden => 0, + hidden => 0, } } }, @@ -110,12 +110,12 @@ subtest 'generate_subfield_form itemtypes' => sub { ); my @itemtypes = Koha::ItemTypes->search_with_localization()->as_list; - my %labels = map { $_->itemtype => $_->description } @itemtypes; - my @values = ('', map { $_->itemtype } @itemtypes); + my %labels = map { $_->itemtype => $_->description } @itemtypes; + my @values = ( '', map { $_->itemtype } @itemtypes ); - is($subfield->{marc_value}->{type}, 'select'); - is_deeply($subfield->{marc_value}->{labels}, \%labels); - is_deeply($subfield->{marc_value}->{values}, \@values); + is( $subfield->{marc_value}->{type}, 'select' ); + is_deeply( $subfield->{marc_value}->{labels}, \%labels ); + is_deeply( $subfield->{marc_value}->{values}, \@values ); }; subtest 'generate_subfield_form class sources' => sub { @@ -123,15 +123,15 @@ subtest 'generate_subfield_form class sources' => sub { my $subfield = $builder->generate_subfield_form( { - tag => '999', - subfield => '9', - value => '', - index_tag => int(rand(1000000)), - tagslib => { + tag => '999', + subfield => '9', + value => '', + index_tag => int( rand(1000000) ), + tagslib => { '999' => { '9' => { authorised_value => 'cn_source', - hidden => 0, + hidden => 0, } } }, @@ -152,28 +152,29 @@ subtest 'generate_subfield_form authorised value' => sub { my $subfield = $builder->generate_subfield_form( { - tag => '999', - subfield => '9', - value => '', - index_tag => int(rand(1000000)), - tagslib => { + tag => '999', + subfield => '9', + value => '', + index_tag => int( rand(1000000) ), + tagslib => { '999' => { '9' => { authorised_value => 'YES_NO', - hidden => 0, + hidden => 0, } } }, }, ); - my @authorised_values = Koha::AuthorisedValues->search({category => 'YES_NO'}, {order_by => ['lib', 'lib_opac']})->as_list; + my @authorised_values = + Koha::AuthorisedValues->search( { category => 'YES_NO' }, { order_by => [ 'lib', 'lib_opac' ] } )->as_list; my %labels = map { $_->authorised_value => $_->lib } @authorised_values; - my @values = ('', map { $_->authorised_value } @authorised_values); + my @values = ( '', map { $_->authorised_value } @authorised_values ); - is($subfield->{marc_value}->{type}, 'select'); - is_deeply($subfield->{marc_value}->{labels}, \%labels); - is_deeply($subfield->{marc_value}->{values}, \@values); + is( $subfield->{marc_value}->{type}, 'select' ); + is_deeply( $subfield->{marc_value}->{labels}, \%labels ); + is_deeply( $subfield->{marc_value}->{values}, \@values ); }; subtest 'generate_subfield_form framework plugin' => sub { @@ -181,25 +182,25 @@ subtest 'generate_subfield_form framework plugin' => sub { my $subfield = $builder->generate_subfield_form( { - tag => '999', - subfield => '9', - value => '', - index_tag => int(rand(1000000)), - tagslib => { + tag => '999', + subfield => '9', + value => '', + index_tag => int( rand(1000000) ), + tagslib => { '999' => { '9' => { value_builder => 'barcode.pl', - hidden => 0, + hidden => 0, } } }, }, ); - is($subfield->{marc_value}->{type}, 'text_complex'); - is($subfield->{marc_value}->{plugin}, 'barcode.pl'); - is($subfield->{marc_value}->{noclick}, 1); - like($subfield->{marc_value}->{javascript}, qr,<script>.*</script>,s); + is( $subfield->{marc_value}->{type}, 'text_complex' ); + is( $subfield->{marc_value}->{plugin}, 'barcode.pl' ); + is( $subfield->{marc_value}->{noclick}, 1 ); + like( $subfield->{marc_value}->{javascript}, qr,<script>.*</script>,s ); }; $schema->storage->txn_rollback; diff --git a/t/db_dependent/Koha/UI/Form/Builder/Item.t b/t/db_dependent/Koha/UI/Form/Builder/Item.t index 251287a530..00556935db 100755 --- a/t/db_dependent/Koha/UI/Form/Builder/Item.t +++ b/t/db_dependent/Koha/UI/Form/Builder/Item.t @@ -52,49 +52,46 @@ $cache->clear_from_cache("MarcSubfieldStructure-"); setup_mss(); subtest 'authorised values' => sub { + #plan tests => 1; - my $biblio = $builder->build_sample_biblio({ value => {frameworkcode => ''}}); + my $biblio = $builder->build_sample_biblio( { value => { frameworkcode => '' } } ); # FIXME Later in this script we are comparing itemtypes, ordered by their description. # MySQL and Perl don't sort _ identically. # If you have one itemtype BK and another one B_K, MySQL will sort B_K first when Perl will sort it last my @itemtypes = Koha::ItemTypes->search->as_list; - for my $itemtype ( @itemtypes ) { + for my $itemtype (@itemtypes) { my $d = $itemtype->description; $d =~ s|_||g; $itemtype->description($d)->store; } - my $subfields = - Koha::UI::Form::Builder::Item->new( - { biblionumber => $biblio->biblionumber } )->edit_form; + my $subfields = Koha::UI::Form::Builder::Item->new( { biblionumber => $biblio->biblionumber } )->edit_form; my @display_orders = uniq map { $_->{display_order} } @$subfields; - is_deeply( \@display_orders, [sort {$a <=> $b} @display_orders], 'subfields are sorted by display order' ); + is_deeply( \@display_orders, [ sort { $a <=> $b } @display_orders ], 'subfields are sorted by display order' ); subtest 'normal AV' => sub { plan tests => 2; my ($subfield) = - grep { $_->{kohafield} eq 'items.notforloan' } @$subfields; + grep { $_->{kohafield} eq 'items.notforloan' } @$subfields; my $avs = Koha::AuthorisedValues->search( { category => 'NOT_LOAN' } ); is_deeply( $subfield->{marc_value}->{values}, [ "", - map { $_->authorised_value } - sort { $a->lib cmp $b->lib } - $avs->as_list + map { $_->authorised_value } + sort { $a->lib cmp $b->lib } $avs->as_list ], 'AVs are sorted by lib and en empty option is created first' ); is_deeply( $subfield->{marc_value}->{labels}, { - map { $_->authorised_value => $_->lib } - sort { $a->lib cmp $b->lib } - $avs->as_list + map { $_->authorised_value => $_->lib } + sort { $a->lib cmp $b->lib } $avs->as_list } ); }; @@ -113,8 +110,8 @@ subtest 'authorised values' => sub { }; subtest 'branches' => sub { plan tests => 2; - my ( $subfield ) = grep { $_->{kohafield} eq 'items.homebranch' } @$subfields; - my $libraries = Koha::Libraries->search({}, { order_by => 'branchname' }); + my ($subfield) = grep { $_->{kohafield} eq 'items.homebranch' } @$subfields; + my $libraries = Koha::Libraries->search( {}, { order_by => 'branchname' } ); is_deeply( $subfield->{marc_value}->{values}, [ $libraries->get_column('branchcode') ] @@ -132,10 +129,10 @@ subtest 'authorised values' => sub { my $expected = [ "", - map { $_->itemtype } - # We need to sort using uc or perl won't be case insensitive - sort { uc($a->translated_description) cmp uc($b->translated_description) } - @itemtypes + map { $_->itemtype } + + # We need to sort using uc or perl won't be case insensitive + sort { uc( $a->translated_description ) cmp uc( $b->translated_description ) } @itemtypes ]; is_deeply( $subfield->{marc_value}->{values}, @@ -143,8 +140,9 @@ subtest 'authorised values' => sub { "Item types should be sorted by description and an empty entry should be shown" ); - is_deeply( $subfield->{marc_value}->{labels}, - { map { $_->itemtype => $_->description } @itemtypes}, + is_deeply( + $subfield->{marc_value}->{labels}, + { map { $_->itemtype => $_->description } @itemtypes }, 'Labels should be correctly displayed' ); }; @@ -153,89 +151,88 @@ subtest 'authorised values' => sub { subtest 'prefill_with_default_values' => sub { plan tests => 3; - my $biblio = $builder->build_sample_biblio({ value => {frameworkcode => ''}}); - my $subfields = - Koha::UI::Form::Builder::Item->new( - { biblionumber => $biblio->biblionumber } )->edit_form; - + my $biblio = $builder->build_sample_biblio( { value => { frameworkcode => '' } } ); + my $subfields = Koha::UI::Form::Builder::Item->new( { biblionumber => $biblio->biblionumber } )->edit_form; my ($subfield) = grep { $_->{subfield} eq 'é' } @$subfields; is( $subfield->{marc_value}->{value}, '', 'no default value if prefill_with_default_values not passed' ); $subfields = - Koha::UI::Form::Builder::Item->new( - { biblionumber => $biblio->biblionumber } )->edit_form({ prefill_with_default_values => 1 }); - + Koha::UI::Form::Builder::Item->new( { biblionumber => $biblio->biblionumber } ) + ->edit_form( { prefill_with_default_values => 1 } ); ($subfield) = grep { $_->{subfield} eq 'é' } @$subfields; - is( $subfield->{marc_value}->{value}, 'ééé', 'default value should be set if prefill_with_default_values passed'); + is( $subfield->{marc_value}->{value}, 'ééé', 'default value should be set if prefill_with_default_values passed' ); # Do the same for an existing item; we do not expect the defaultvalue to popup my $item = $builder->build_sample_item; - $subfields = Koha::UI::Form::Builder::Item->new({ - biblionumber => $biblio->biblionumber, - item => $item->unblessed, - })->edit_form({ prefill_with_default_values => 1 }); + $subfields = Koha::UI::Form::Builder::Item->new( + { + biblionumber => $biblio->biblionumber, + item => $item->unblessed, + } + )->edit_form( { prefill_with_default_values => 1 } ); ($subfield) = grep { $_->{subfield} eq 'é' } @$subfields; - is( $subfield->{marc_value}->{value}, q{}, 'default value not applied to existing item'); + is( $subfield->{marc_value}->{value}, q{}, 'default value not applied to existing item' ); }; subtest 'subfields_to_prefill' => sub { plan tests => 2; - my $biblio = $builder->build_sample_biblio({ value => {frameworkcode => ''}}); + my $biblio = $builder->build_sample_biblio( { value => { frameworkcode => '' } } ); - my $more_subfields_xml = Koha::Item::Attributes->new({ "é" => "prefill é" })->to_marcxml; + my $more_subfields_xml = Koha::Item::Attributes->new( { "é" => "prefill é" } )->to_marcxml; my $subfields = - Koha::UI::Form::Builder::Item->new( - { biblionumber => $biblio->biblionumber, item => {more_subfields_xml => $more_subfields_xml}})->edit_form({subfields_to_prefill => ['é']}); + Koha::UI::Form::Builder::Item->new( + { biblionumber => $biblio->biblionumber, item => { more_subfields_xml => $more_subfields_xml } } ) + ->edit_form( { subfields_to_prefill => ['é'] } ); my ($subfield) = grep { $_->{subfield} eq 'é' } @$subfields; is( $subfield->{marc_value}->{value}, 'prefill é', 'Not mapped subfield prefilled if needed' ); $subfields = - Koha::UI::Form::Builder::Item->new( - { biblionumber => $biblio->biblionumber, item => {itemnotes => 'prefill z'}})->edit_form({subfields_to_prefill => ['z']}); + Koha::UI::Form::Builder::Item->new( + { biblionumber => $biblio->biblionumber, item => { itemnotes => 'prefill z' } } ) + ->edit_form( { subfields_to_prefill => ['z'] } ); ($subfield) = grep { $_->{subfield} eq 'z' } @$subfields; - is( $subfield->{marc_value}->{value}, 'prefill z', 'Mapped subfield prefilled if needed'); + is( $subfield->{marc_value}->{value}, 'prefill z', 'Mapped subfield prefilled if needed' ); }; subtest 'branchcode' => sub { plan tests => 2; - my $biblio = $builder->build_sample_biblio({ value => {frameworkcode => ''}}); - my $library = $builder->build_object({ class => 'Koha::Libraries' }); - my $subfields = - Koha::UI::Form::Builder::Item->new( - { biblionumber => $biblio->biblionumber } )->edit_form; + my $biblio = $builder->build_sample_biblio( { value => { frameworkcode => '' } } ); + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); + my $subfields = Koha::UI::Form::Builder::Item->new( { biblionumber => $biblio->biblionumber } )->edit_form; - my ( $subfield ) = grep { $_->{kohafield} eq 'items.homebranch' } @$subfields; - is( $subfield->{marc_value}->{default}, '', 'no library preselected if no branchcode passed'); + my ($subfield) = grep { $_->{kohafield} eq 'items.homebranch' } @$subfields; + is( $subfield->{marc_value}->{default}, '', 'no library preselected if no branchcode passed' ); $subfields = - Koha::UI::Form::Builder::Item->new( - { biblionumber => $biblio->biblionumber } )->edit_form({ branchcode => $library->branchcode }); + Koha::UI::Form::Builder::Item->new( { biblionumber => $biblio->biblionumber } ) + ->edit_form( { branchcode => $library->branchcode } ); - ( $subfield ) = grep { $_->{kohafield} eq 'items.homebranch' } @$subfields; - is( $subfield->{marc_value}->{default}, $library->branchcode, 'the correct library should be preselected if branchcode is passed'); + ($subfield) = grep { $_->{kohafield} eq 'items.homebranch' } @$subfields; + is( + $subfield->{marc_value}->{default}, $library->branchcode, + 'the correct library should be preselected if branchcode is passed' + ); }; subtest 'default_branches_empty' => sub { plan tests => 2; - my $biblio = $builder->build_sample_biblio({ value => {frameworkcode => ''}}); - my $subfields = - Koha::UI::Form::Builder::Item->new( - { biblionumber => $biblio->biblionumber } )->edit_form; + my $biblio = $builder->build_sample_biblio( { value => { frameworkcode => '' } } ); + my $subfields = Koha::UI::Form::Builder::Item->new( { biblionumber => $biblio->biblionumber } )->edit_form; - my ( $subfield ) = grep { $_->{kohafield} eq 'items.homebranch' } @$subfields; + my ($subfield) = grep { $_->{kohafield} eq 'items.homebranch' } @$subfields; isnt( $subfield->{marc_value}->{values}->[0], "", 'No empty option for branches' ); $subfields = - Koha::UI::Form::Builder::Item->new( - { biblionumber => $biblio->biblionumber } )->edit_form({ default_branches_empty => 1 }); + Koha::UI::Form::Builder::Item->new( { biblionumber => $biblio->biblionumber } ) + ->edit_form( { default_branches_empty => 1 } ); - ( $subfield ) = grep { $_->{kohafield} eq 'items.homebranch' } @$subfields; + ($subfield) = grep { $_->{kohafield} eq 'items.homebranch' } @$subfields; is( $subfield->{marc_value}->{values}->[0], "", 'empty option for branches if default_branches_empty passed' ); }; @@ -243,23 +240,24 @@ subtest 'kohafields_to_add_datepicker' => sub { plan tests => 5; my $biblio = - $builder->build_sample_biblio( { value => { frameworkcode => '' } } ); - my $subfields = - Koha::UI::Form::Builder::Item->new( - { biblionumber => $biblio->biblionumber } )->edit_form; + $builder->build_sample_biblio( { value => { frameworkcode => '' } } ); + my $subfields = Koha::UI::Form::Builder::Item->new( { biblionumber => $biblio->biblionumber } )->edit_form; my @itemfield_test_cases = ( - { kohafield => 'items.dateaccessioned', expected_type => 'date' }, + { kohafield => 'items.dateaccessioned', expected_type => 'date' }, { kohafield => 'items.replacementpricedate', expected_type => 'date' }, - { kohafield => 'items.datelastborrowed', expected_type => 'date' }, - { kohafield => 'items.onloan', expected_type => 'date' }, - { kohafield => 'items.datelastseen', expected_type => 'datetime' }, + { kohafield => 'items.datelastborrowed', expected_type => 'date' }, + { kohafield => 'items.onloan', expected_type => 'date' }, + { kohafield => 'items.datelastseen', expected_type => 'datetime' }, ); foreach my $itemfield_test_case (@itemfield_test_cases) { - my ( $subfield ) = grep { $_->{kohafield} eq $itemfield_test_case->{kohafield} } @$subfields; - if ( $subfield ) { - is( $subfield->{data_type}, $itemfield_test_case->{expected_type}, "Correct datetype for $itemfield_test_case->{kohafield}" ); + my ($subfield) = grep { $_->{kohafield} eq $itemfield_test_case->{kohafield} } @$subfields; + if ($subfield) { + is( + $subfield->{data_type}, $itemfield_test_case->{expected_type}, + "Correct datetype for $itemfield_test_case->{kohafield}" + ); } else { ok( 0, "Subfield for $itemfield_test_case->{kohafield} not found" ); } @@ -270,21 +268,19 @@ subtest 'kohafields_to_ignore' => sub { plan tests => 2; my $biblio = - $builder->build_sample_biblio( { value => { frameworkcode => '' } } ); - my $subfields = - Koha::UI::Form::Builder::Item->new( - { biblionumber => $biblio->biblionumber } )->edit_form; + $builder->build_sample_biblio( { value => { frameworkcode => '' } } ); + my $subfields = Koha::UI::Form::Builder::Item->new( { biblionumber => $biblio->biblionumber } )->edit_form; my ($subfield) = grep { $_->{kohafield} eq 'items.barcode' } @$subfields; isnt( $subfield, undef, 'barcode subfield should be in the subfield list' ); $subfields = - Koha::UI::Form::Builder::Item->new( - { biblionumber => $biblio->biblionumber } ) - ->edit_form( { kohafields_to_ignore => ['items.barcode'] } ); + Koha::UI::Form::Builder::Item->new( { biblionumber => $biblio->biblionumber } ) + ->edit_form( { kohafields_to_ignore => ['items.barcode'] } ); ($subfield) = grep { $_->{kohafield} eq 'items.barcode' } @$subfields; - is( $subfield, undef, + is( + $subfield, undef, 'barcode subfield should have not been built if passed to kohafields_to_ignore' ); }; @@ -292,19 +288,17 @@ subtest 'kohafields_to_ignore' => sub { subtest 'subfields_to_allow & ignore_not_allowed_subfields' => sub { plan tests => 6; - my ( $tag_cn, $subtag_cn ) = C4::Biblio::GetMarcFromKohaField("items.itemcallnumber"); + my ( $tag_cn, $subtag_cn ) = C4::Biblio::GetMarcFromKohaField("items.itemcallnumber"); my ( $tag_notes, $subtag_notes ) = C4::Biblio::GetMarcFromKohaField("items.itemnotes"); - my $biblio = $builder->build_sample_biblio( { value => { frameworkcode => '' } } ); - my $subfields = - Koha::UI::Form::Builder::Item->new( - { biblionumber => $biblio->biblionumber } )->edit_form( - { - subfields_to_allow => [ - sprintf( '%s$%s', $tag_cn, $subtag_cn ), - sprintf( '%s$%s', $tag_notes, $subtag_notes ) - ] - } - ); + my $biblio = $builder->build_sample_biblio( { value => { frameworkcode => '' } } ); + my $subfields = Koha::UI::Form::Builder::Item->new( { biblionumber => $biblio->biblionumber } )->edit_form( + { + subfields_to_allow => [ + sprintf( '%s$%s', $tag_cn, $subtag_cn ), + sprintf( '%s$%s', $tag_notes, $subtag_notes ) + ] + } + ); isnt( scalar(@$subfields), 2, "There are more than the 2 subfields we allowed" ); my ($subfield) = grep { $_->{kohafield} eq 'items.itemcallnumber' } @$subfields; @@ -312,21 +306,19 @@ subtest 'subfields_to_allow & ignore_not_allowed_subfields' => sub { ($subfield) = grep { $_->{kohafield} eq 'items.copynumber' } @$subfields; isnt( $subfield->{marc_value}->{readonly}, 1, "subfields that are not in the allow list are marked as readonly" ); - $subfields = - Koha::UI::Form::Builder::Item->new( - { biblionumber => $biblio->biblionumber } )->edit_form( - { - subfields_to_allow => [ - sprintf( '%s$%s', $tag_cn, $subtag_cn ), - sprintf( '%s$%s', $tag_notes, $subtag_notes ) - ], - ignore_not_allowed_subfields => 1, - } - ); + $subfields = Koha::UI::Form::Builder::Item->new( { biblionumber => $biblio->biblionumber } )->edit_form( + { + subfields_to_allow => [ + sprintf( '%s$%s', $tag_cn, $subtag_cn ), + sprintf( '%s$%s', $tag_notes, $subtag_notes ) + ], + ignore_not_allowed_subfields => 1, + } + ); is( scalar(@$subfields), 2, "With ignore_not_allowed_subfields, only the subfields to ignore are returned" ); ($subfield) = - grep { $_->{kohafield} eq 'items.itemcallnumber' } @$subfields; + grep { $_->{kohafield} eq 'items.itemcallnumber' } @$subfields; is( $subfield->{marc_value}->{readonly}, undef, "subfields to allowed are not marked as readonly" ); ($subfield) = grep { $_->{kohafield} eq 'items.copynumber' } @$subfields; is( $subfield, undef, "subfield that is not in the allow list is not returned" ); @@ -336,7 +328,7 @@ subtest 'ignore_invisible_subfields' => sub { plan tests => 2; my $biblio = - $builder->build_sample_biblio( { value => { frameworkcode => '' } } ); + $builder->build_sample_biblio( { value => { frameworkcode => '' } } ); my $item = $builder->build_sample_item( { issues => 42, @@ -358,26 +350,24 @@ subtest 'ignore_invisible_subfields' => sub { biblionumber => $biblio->biblionumber, item => $item->unblessed, } - )->edit_form( - { - ignore_invisible_subfields => 1 - } - ); + )->edit_form( { ignore_invisible_subfields => 1 } ); ($subfield) = grep { $_->{subfield} eq 'l' } @$subfields; - is( $subfield->{marc_value}->{value}, - undef, 'items.issues not copied if ignore_invisible_subfields is passed' ); + is( + $subfield->{marc_value}->{value}, + undef, 'items.issues not copied if ignore_invisible_subfields is passed' + ); }; subtest 'Fix subfill_with_default_values - no biblionumber passed' => sub { plan tests => 1; - t::lib::Mocks::mock_preference('itemcallnumber', '082ab,092ab'); - my $item = $builder->build_sample_item; + t::lib::Mocks::mock_preference( 'itemcallnumber', '082ab,092ab' ); + my $item = $builder->build_sample_item; my $subfields = Koha::UI::Form::Builder::Item->new( { - item => $item->unblessed, + item => $item->unblessed, } - )->edit_form({ prefill_with_default_values => 1 }); + )->edit_form( { prefill_with_default_values => 1 } ); pass(); }; @@ -387,13 +377,13 @@ $cache->clear_from_cache("MarcSubfieldStructure-"); sub setup_mss { - my ( $itemtag, $itemsubfield ) = C4::Biblio::GetMarcFromKohaField( "items.itemnumber" ); + my ( $itemtag, $itemsubfield ) = C4::Biblio::GetMarcFromKohaField("items.itemnumber"); Koha::MarcSubfieldStructures->search( { frameworkcode => '', - tagfield => $itemtag, - tagsubfield => 'é', + tagfield => $itemtag, + tagsubfield => 'é', } )->delete; # In case it exist already @@ -413,46 +403,46 @@ sub setup_mss { { frameworkcode => '', tagfield => $itemtag, - tagsubfield => [ 'x' ] + tagsubfield => ['x'] } )->update( { kohafield => undef } ); Koha::MarcSubfieldStructures->search( { frameworkcode => '', - tagfield => $itemtag, - tagsubfield => [ 'x', 'é' ], + tagfield => $itemtag, + tagsubfield => [ 'x', 'é' ], } )->update( { repeatable => 1 } ); Koha::MarcSubfieldStructures->search( { frameworkcode => '', - tagfield => $itemtag, - tagsubfield => ['t'], + tagfield => $itemtag, + tagsubfield => ['t'], } )->update( { repeatable => 0 } ); Koha::MarcSubfieldStructures->search( { frameworkcode => '', - tagfield => $itemtag, - tagsubfield => ['l'], + tagfield => $itemtag, + tagsubfield => ['l'], } )->update( { hidden => -4 } ); Koha::MarcSubfieldStructures->search( { frameworkcode => '', - tagfield => $itemtag, - tagsubfield => ['z'], + tagfield => $itemtag, + tagsubfield => ['z'], } )->update( { kohafield => 'items.itemnotes', repeatable => 1 } ); Koha::MarcSubfieldStructures->search( { frameworkcode => '', - tagfield => $itemtag, + tagfield => $itemtag, } )->update( { display_order => \['FLOOR( 1 + RAND( ) * 10 )'] } ); } diff --git a/t/db_dependent/Koha/Virtualshelves.t b/t/db_dependent/Koha/Virtualshelves.t index 20d2454c99..36c1bda5c7 100755 --- a/t/db_dependent/Koha/Virtualshelves.t +++ b/t/db_dependent/Koha/Virtualshelves.t @@ -38,9 +38,9 @@ subtest 'disown_or_delete() tests' => sub { $schema->storage->txn_begin; - my $patron_1 = $builder->build_object({ class => 'Koha::Patrons' }); - my $patron_2 = $builder->build_object({ class => 'Koha::Patrons' }); - my $patron_3 = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron_1 = $builder->build_object( { class => 'Koha::Patrons' } ); + my $patron_2 = $builder->build_object( { class => 'Koha::Patrons' } ); + my $patron_3 = $builder->build_object( { class => 'Koha::Patrons' } ); my $public_list = $builder->build_object( { @@ -67,14 +67,16 @@ subtest 'disown_or_delete() tests' => sub { $builder->build_object( { class => 'Koha::Virtualshelfshares', - value => { shelfnumber => $private_list_shared->id, invitekey => undef, borrowernumber => $patron_3->id } + value => + { shelfnumber => $private_list_shared->id, invitekey => undef, borrowernumber => $patron_3->id } } ); t::lib::Mocks::mock_preference( 'ListOwnershipUponPatronDeletion', 'transfer' ); - t::lib::Mocks::mock_preference( 'ListOwnerDesignated', $patron_2->id ); + t::lib::Mocks::mock_preference( 'ListOwnerDesignated', $patron_2->id ); - my $rs = Koha::Virtualshelves->search( { shelfnumber => [ $public_list->id, $private_list->id, $private_list_shared->id ] } ); + my $rs = Koha::Virtualshelves->search( + { shelfnumber => [ $public_list->id, $private_list->id, $private_list_shared->id ] } ); my $result = $rs->disown_or_delete; is( ref($result), 'Koha::Virtualshelves', 'Return type is correct' ); @@ -82,11 +84,11 @@ subtest 'disown_or_delete() tests' => sub { is( $rs->count, 2, 'The private/non-shared list was deleted' ); my $first = $rs->next; - is( $first->id, $public_list->id ); + is( $first->id, $public_list->id ); is( $first->owner, $patron_2->id ); my $second = $rs->next; - is( $second->id, $private_list_shared->id ); + is( $second->id, $private_list_shared->id ); is( $second->owner, $patron_2->id ); $schema->storage->txn_rollback; @@ -98,9 +100,9 @@ subtest 'disown_or_delete() tests' => sub { $schema->storage->txn_begin; - my $patron_1 = $builder->build_object({ class => 'Koha::Patrons' }); - my $patron_2 = $builder->build_object({ class => 'Koha::Patrons' }); - my $patron_3 = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron_1 = $builder->build_object( { class => 'Koha::Patrons' } ); + my $patron_2 = $builder->build_object( { class => 'Koha::Patrons' } ); + my $patron_3 = $builder->build_object( { class => 'Koha::Patrons' } ); my $public_list = $builder->build_object( { @@ -127,12 +129,13 @@ subtest 'disown_or_delete() tests' => sub { $builder->build_object( { class => 'Koha::Virtualshelfshares', - value => { shelfnumber => $private_list_shared->id, invitekey => undef, borrowernumber => $patron_2->id } + value => + { shelfnumber => $private_list_shared->id, invitekey => undef, borrowernumber => $patron_2->id } } ); t::lib::Mocks::mock_preference( 'ListOwnershipUponPatronDeletion', 'transfer' ); - t::lib::Mocks::mock_preference( 'ListOwnerDesignated', undef ); + t::lib::Mocks::mock_preference( 'ListOwnerDesignated', undef ); my $public_list_to_delete = $builder->build_object( { @@ -141,27 +144,28 @@ subtest 'disown_or_delete() tests' => sub { } ); - my $rs = Koha::Virtualshelves->search({ shelfnumber => $public_list_to_delete->id }); + my $rs = Koha::Virtualshelves->search( { shelfnumber => $public_list_to_delete->id } ); my $result = $rs->disown_or_delete; is( ref($result), 'Koha::Virtualshelves', 'Return type is correct' ); $rs->reset; is( $rs->count, 0, 'ListOwnerDesignated and userenv not set yield deletion' ); - t::lib::Mocks::mock_userenv({ patron => $patron_3 }); + t::lib::Mocks::mock_userenv( { patron => $patron_3 } ); - $rs = Koha::Virtualshelves->search( { shelfnumber => [ $public_list->id, $private_list->id, $private_list_shared->id ] } ); + $rs = Koha::Virtualshelves->search( + { shelfnumber => [ $public_list->id, $private_list->id, $private_list_shared->id ] } ); $rs->disown_or_delete; $rs->reset; is( $rs->count, 2, 'The private/non-shared list was deleted' ); my $first = $rs->next; - is( $first->id, $public_list->id ); + is( $first->id, $public_list->id ); is( $first->owner, $patron_3->id ); my $second = $rs->next; - is( $second->id, $private_list_shared->id ); + is( $second->id, $private_list_shared->id ); is( $second->owner, $patron_3->id ); $schema->storage->txn_rollback; @@ -173,9 +177,9 @@ subtest 'disown_or_delete() tests' => sub { $schema->storage->txn_begin; - my $patron_1 = $builder->build_object({ class => 'Koha::Patrons' }); - my $patron_2 = $builder->build_object({ class => 'Koha::Patrons' }); - my $patron_3 = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron_1 = $builder->build_object( { class => 'Koha::Patrons' } ); + my $patron_2 = $builder->build_object( { class => 'Koha::Patrons' } ); + my $patron_3 = $builder->build_object( { class => 'Koha::Patrons' } ); my $public_list = $builder->build_object( { @@ -202,13 +206,15 @@ subtest 'disown_or_delete() tests' => sub { $builder->build_object( { class => 'Koha::Virtualshelfshares', - value => { shelfnumber => $private_list_shared->id, invitekey => undef, borrowernumber => $patron_2->id } + value => + { shelfnumber => $private_list_shared->id, invitekey => undef, borrowernumber => $patron_2->id } } ); t::lib::Mocks::mock_preference( 'ListOwnershipUponPatronDeletion', 'delete' ); - my $rs = Koha::Virtualshelves->search( { shelfnumber => [ $public_list->id, $private_list->id, $private_list_shared->id ] } ); + my $rs = Koha::Virtualshelves->search( + { shelfnumber => [ $public_list->id, $private_list->id, $private_list_shared->id ] } ); my $result = $rs->disown_or_delete; is( ref($result), 'Koha::Virtualshelves', 'Return type is correct' ); diff --git a/t/db_dependent/Koha/XSLT/Base.t b/t/db_dependent/Koha/XSLT/Base.t index a13f109554..cdba853253 100755 --- a/t/db_dependent/Koha/XSLT/Base.t +++ b/t/db_dependent/Koha/XSLT/Base.t @@ -25,15 +25,15 @@ use Test::Warn; use Koha::XSLT::Base; -my $engine=Koha::XSLT::Base->new; +my $engine = Koha::XSLT::Base->new; is( ref $engine, 'Koha::XSLT::Base', 'Testing creation of handler object' ); $engine->transform(''); is( $engine->err, Koha::XSLT::Base::XSLTH_ERR_1, 'Engine returns error on no file' ); $engine->transform( '', 'thisfileshouldnotexist.%$#@' ); -is( $engine->err, Koha::XSLT::Base::XSLTH_ERR_2, 'Engine returns error on bad file' ); -is( $engine->refresh( 'asdjhaskjh'), 0, 'Test on invalid refresh' ); +is( $engine->err, Koha::XSLT::Base::XSLTH_ERR_2, 'Engine returns error on bad file' ); +is( $engine->refresh('asdjhaskjh'), 0, 'Test on invalid refresh' ); #check first test xsl my $xsl_1 = <<'XSL_1'; @@ -66,69 +66,72 @@ XSL_1 # Testing not-xml strings (undef, empty, some text, malformed xml # Undefined text tests my $output; -$output = $engine->transform({ xml => undef, code => $xsl_1 }); +$output = $engine->transform( { xml => undef, code => $xsl_1 } ); is( $engine->err, Koha::XSLT::Base::XSLTH_ERR_7, 'Engine returns error on undefined text' ); # Empty string tests -warning_like {$output = $engine->transform({ xml => '', code => $xsl_1 }) } - qr/XSLT::Base: Empty String/, +warning_like { $output = $engine->transform( { xml => '', code => $xsl_1 } ) } +qr/XSLT::Base: Empty String/, 'Empty string warning detected'; is( $engine->err, Koha::XSLT::Base::XSLTH_ERR_5, 'Engine returns error on empty string' ); # Non-XML tests $engine->print_warns(1); -warning_like { $output = $engine->transform({ xml => 'abcdef', code => $xsl_1 }) } - qr{parser error : Start tag expected, '<' not found}, +warning_like { $output = $engine->transform( { xml => 'abcdef', code => $xsl_1 } ) } +qr{parser error : Start tag expected, '<' not found}, "Non-XML warning correctly displayed"; is( $engine->err, Koha::XSLT::Base::XSLTH_ERR_5, 'Engine returns error on non-xml' ); # Malformed XML tests -warning_like { $output = $engine->transform({ xml => '<a></b>', code => $xsl_1 }) } - qr{parser error : Opening and ending tag mismatch: a line (0|1) and b}, +warning_like { $output = $engine->transform( { xml => '<a></b>', code => $xsl_1 } ) } +qr{parser error : Opening and ending tag mismatch: a line (0|1) and b}, "Malformed XML warning correctly displayed"; is( $engine->err, Koha::XSLT::Base::XSLTH_ERR_5, 'Engine returns error on malformed xml' ); #Test not returning source on failure when asked for #Include passing do_not_return via constructor on second engine -my $secondengine=Koha::XSLT::Base->new( { - do_not_return_source => 'very_true', - some_unknown_attrib => 'just_for_fun', -}); +my $secondengine = Koha::XSLT::Base->new( + { + do_not_return_source => 'very_true', + some_unknown_attrib => 'just_for_fun', + } +); $engine->do_not_return_source(1); -warning_like { $output = $engine->transform({ xml => '<a></b>', code => $xsl_1 }) } - qr{parser error : Opening and ending tag mismatch: a line (0|1) and b}, +warning_like { $output = $engine->transform( { xml => '<a></b>', code => $xsl_1 } ) } +qr{parser error : Opening and ending tag mismatch: a line (0|1) and b}, "Malformed XML warning correctly displayed"; -is( defined $output? 1: 0, 0, 'Engine respects do_not_return_source==1'); +is( defined $output ? 1 : 0, 0, 'Engine respects do_not_return_source==1' ); $secondengine->print_warns(1); -warning_like { $output = $secondengine->transform({ xml => '<a></b>', code => $xsl_1 }) } - qr{parser error : Opening and ending tag mismatch: a line (0|1) and b}, +warning_like { $output = $secondengine->transform( { xml => '<a></b>', code => $xsl_1 } ) } +qr{parser error : Opening and ending tag mismatch: a line (0|1) and b}, "Malformed XML warning correctly displayed"; -is( defined $output? 1: 0, 0, 'Second engine respects it too'); -undef $secondengine; #bye +is( defined $output ? 1 : 0, 0, 'Second engine respects it too' ); +undef $secondengine; #bye $engine->do_not_return_source(0); -warning_like { $output = $engine->transform({ xml => '<a></b>', code => $xsl_1 }) } - qr{parser error : Opening and ending tag mismatch: a line (0|1) and b}, +warning_like { $output = $engine->transform( { xml => '<a></b>', code => $xsl_1 } ) } +qr{parser error : Opening and ending tag mismatch: a line (0|1) and b}, "Malformed XML warning correctly displayed"; -is( defined $output? 1: 0, 1, 'Engine respects do_not_return_source==0'); +is( defined $output ? 1 : 0, 1, 'Engine respects do_not_return_source==0' ); #Testing valid refresh now my $xsltfile_1 = mytempfile($xsl_1); $output = $engine->transform( '<records/>', $xsltfile_1 ); is( $engine->refresh($xsltfile_1), 1, 'Test on valid refresh' ); -is( $engine->refresh, 1, 'Second refresh returns 1 for code xsl_1' ); -is( $engine->refresh, 0, 'Third refresh: nothing left' ); +is( $engine->refresh, 1, 'Second refresh returns 1 for code xsl_1' ); +is( $engine->refresh, 0, 'Third refresh: nothing left' ); #Testing a string that should not change too much -my $xml_1=<<'EOT'; +my $xml_1 = <<'EOT'; <just_a_tagname> </just_a_tagname> EOT -$output= $engine->transform({ xml => $xml_1, code => $xsl_1 }); -is( $engine->err, undef, 'Engine returned no error for xml_1' ); -is( index($output,'<just_a_tagname>')>0, 1, 'No real change expected for xml_1' ); #Just very simple check if the tag was still there +$output = $engine->transform( { xml => $xml_1, code => $xsl_1 } ); +is( $engine->err, undef, 'Engine returned no error for xml_1' ); +is( index( $output, '<just_a_tagname>' ) > 0, 1, 'No real change expected for xml_1' ) + ; #Just very simple check if the tag was still there #Test of adding a new datafield to rudimentary 'marc record' -my $xml_2=<<'EOT'; +my $xml_2 = <<'EOT'; <?xml version="1.0" encoding="UTF-8"?> <collection> <record> @@ -137,24 +140,34 @@ my $xml_2=<<'EOT'; </record> </collection> EOT -$output= $engine->transform( $xml_2 ); - #note: second parameter not passed again -is( $engine->err, undef, 'Engine returned no error for xml_2' ); -is( index($output,'I saw you')>0, 1, 'Saw the expected change for xml_2' ); #Just very simple check if new datafield was added +$output = $engine->transform($xml_2); + +#note: second parameter not passed again +is( $engine->err, undef, 'Engine returned no error for xml_2' ); +is( index( $output, 'I saw you' ) > 0, 1, 'Saw the expected change for xml_2' ) + ; #Just very simple check if new datafield was added + #Test alternative parameter passing my $output2; $output2 = $engine->transform( { file => $xsltfile_1, xml => $xml_2 } ); -is( $output, $output2, 'Try hash parameter file'); +is( $output, $output2, 'Try hash parameter file' ); $output2 = $engine->transform( { code => $xsl_1, xml => $xml_2 } ); -is( $output, $output2, 'Try hash parameter code'); +is( $output, $output2, 'Try hash parameter code' ); + #Check rerun on last code -$output2 = $engine->transform( $xml_2 ); -is( $output, $output2, 'Rerun on previous passed code'); +$output2 = $engine->transform($xml_2); +is( $output, $output2, 'Rerun on previous passed code' ); + #Check format xmldoc -is( ref $engine->transform({ - file => $xsltfile_1, xml => $xml_2, format => 'xmldoc', -}), 'XML::LibXML::Document', -'Format parameter returns a xml document object' ); +is( + ref $engine->transform( + { + file => $xsltfile_1, xml => $xml_2, format => 'xmldoc', + } + ), + 'XML::LibXML::Document', + 'Format parameter returns a xml document object' +); #The second test xsl contains bad code my $xsl_2 = <<'XSL_2'; @@ -174,7 +187,7 @@ my $xsl_2 = <<'XSL_2'; XSL_2 $engine->print_warns(0); -$output = $engine->transform({ xml => $xml_2, code => $xsl_2 }); +$output = $engine->transform( { xml => $xml_2, code => $xsl_2 } ); is( $engine->err, Koha::XSLT::Base::XSLTH_ERR_4, 'Engine returned error for parsing bad xsl' ); #The third test xsl is okay again; main use is clearing two items from cache @@ -198,9 +211,9 @@ my $xsl_3 = <<'XSL_3'; </xsl:stylesheet> XSL_3 -$output= $engine->transform({ xml => $xml_2, code => $xsl_3 }); -is( $engine->err, undef, 'Unexpected error on transform with third xsl' ); -is( $engine->refresh, 3, 'Final test on clearing cache' ); +$output = $engine->transform( { xml => $xml_2, code => $xsl_3 } ); +is( $engine->err, undef, 'Unexpected error on transform with third xsl' ); +is( $engine->refresh, 3, 'Final test on clearing cache' ); # Test xsl no 4 my $xsl_4 = <<'XSL_4'; @@ -224,28 +237,32 @@ my $xsl_4 = <<'XSL_4'; </xsl:stylesheet> XSL_4 -my $parameters = { injected_variable => "'this is a test'",}; -$output = $engine->transform({ - xml => $xml_1, - code => $xsl_4, - parameters => $parameters, - }); +my $parameters = { injected_variable => "'this is a test'", }; +$output = $engine->transform( + { + xml => $xml_1, + code => $xsl_4, + parameters => $parameters, + } +); require XML::LibXML; -my $dom = XML::LibXML->load_xml(string => $output); -my $result = $dom->find( '/just_a_tagname' ); -is ( $result->to_literal(), 'this is a test', "Successfully injected string into XSLT parameter/variable"); +my $dom = XML::LibXML->load_xml( string => $output ); +my $result = $dom->find('/just_a_tagname'); +is( $result->to_literal(), 'this is a test', "Successfully injected string into XSLT parameter/variable" ); -$output = $engine->transform({ - xml => $xml_1, - code => $xsl_4, - }); -$dom = XML::LibXML->load_xml(string => $output); -$result = $dom->find( '/just_a_tagname' ); -is ( $result->to_literal(), '', "As expected, no XSLT parameters/variables were added"); +$output = $engine->transform( + { + xml => $xml_1, + code => $xsl_4, + } +); +$dom = XML::LibXML->load_xml( string => $output ); +$result = $dom->find('/just_a_tagname'); +is( $result->to_literal(), '', "As expected, no XSLT parameters/variables were added" ); sub mytempfile { my ( $fh, $fn ) = tempfile( SUFFIX => '.xsl', UNLINK => 1 ); - print $fh $_[0]//''; + print $fh $_[0] // ''; close $fh; return $fn; } diff --git a/t/db_dependent/Koha/XSLT/Security.t b/t/db_dependent/Koha/XSLT/Security.t index 50a47c31ce..1d1557fc63 100755 --- a/t/db_dependent/Koha/XSLT/Security.t +++ b/t/db_dependent/Koha/XSLT/Security.t @@ -26,10 +26,10 @@ use Koha::XSLT::Base; use t::lib::Mocks; t::lib::Mocks::mock_config( 'koha_xslt_security', { expand_entities_unsafe => 1 } ); -my $engine=Koha::XSLT::Base->new; +my $engine = Koha::XSLT::Base->new; my $secret_file = mytempfile('Big secret'); -my $xslt=<<"EOT"; +my $xslt = <<"EOT"; <!DOCTYPE test [<!ENTITY secret SYSTEM "$secret_file">]> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" encoding="UTF-8" version="1.0" indent="yes"/> @@ -39,17 +39,17 @@ my $xslt=<<"EOT"; </xsl:template> </xsl:stylesheet> EOT -my $output= $engine->transform({ xml => "<ignored/>", code => $xslt }); -like($output, qr/Big secret/, 'external entity got through'); +my $output = $engine->transform( { xml => "<ignored/>", code => $xslt } ); +like( $output, qr/Big secret/, 'external entity got through' ); t::lib::Mocks::mock_config( 'koha_xslt_security', { expand_entities_unsafe => 0 } ); -$engine=Koha::XSLT::Base->new; -$output= $engine->transform({ xml => "<ignored/>", code => $xslt }); -unlike($output, qr/Big secret/, 'external entity did not get through'); +$engine = Koha::XSLT::Base->new; +$output = $engine->transform( { xml => "<ignored/>", code => $xslt } ); +unlike( $output, qr/Big secret/, 'external entity did not get through' ); # Adding a document call to trigger callback for read_file # Does not depend on expand_entities. -$xslt=<<"EOT"; +$xslt = <<"EOT"; <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" encoding="UTF-8" version="1.0" indent="yes"/> <xsl:template match="/"> @@ -57,12 +57,12 @@ $xslt=<<"EOT"; </xsl:template> </xsl:stylesheet> EOT -warnings_like { $output= $engine->transform({ xml => "<ignored/>", code => $xslt }); } - [ qr/read_file called in XML::LibXSLT/, qr/runtime error/ ], +warnings_like { $output = $engine->transform( { xml => "<ignored/>", code => $xslt } ); } +[ qr/read_file called in XML::LibXSLT/, qr/runtime error/ ], 'Triggered security callback for read_file'; # Trigger write_file -$xslt=<<"EOT"; +$xslt = <<"EOT"; <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:exsl="http://exslt.org/common" extension-element-prefixes="exsl"> <xsl:output method="xml" encoding="UTF-8" version="1.0" indent="yes"/> <xsl:template match="/"> @@ -70,12 +70,12 @@ $xslt=<<"EOT"; </xsl:template> </xsl:stylesheet> EOT -warnings_like { $output= $engine->transform({ xml => "<ignored/>", code => $xslt }); } - [ qr/write_file called in XML::LibXSLT/, qr/runtime error/ ], +warnings_like { $output = $engine->transform( { xml => "<ignored/>", code => $xslt } ); } +[ qr/write_file called in XML::LibXSLT/, qr/runtime error/ ], 'Triggered security callback for write_file'; # Trigger read_net -$xslt=<<"EOT"; +$xslt = <<"EOT"; <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" encoding="UTF-8" version="1.0" indent="yes"/> <xsl:template match="/"> @@ -83,12 +83,12 @@ $xslt=<<"EOT"; </xsl:template> </xsl:stylesheet> EOT -warnings_like { $output= $engine->transform({ xml => "<ignored/>", code => $xslt }); } - [ qr/read_net called in XML::LibXSLT/, qr/runtime error/ ], +warnings_like { $output = $engine->transform( { xml => "<ignored/>", code => $xslt } ); } +[ qr/read_net called in XML::LibXSLT/, qr/runtime error/ ], 'Triggered security callback for read_net'; # Trigger write_net -$xslt=<<"EOT"; +$xslt = <<"EOT"; <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:exsl="http://exslt.org/common" extension-element-prefixes="exsl"> <xsl:output method="xml" encoding="UTF-8" version="1.0" indent="yes"/> <xsl:template match="/"> @@ -98,14 +98,14 @@ $xslt=<<"EOT"; </xsl:template> </xsl:stylesheet> EOT -warnings_like { $output= $engine->transform({ xml => "<ignored/>", code => $xslt }); } - [ qr/write_net called in XML::LibXSLT/, qr/runtime error/ ], +warnings_like { $output = $engine->transform( { xml => "<ignored/>", code => $xslt } ); } +[ qr/write_net called in XML::LibXSLT/, qr/runtime error/ ], 'Triggered security callback for write_net'; # Check remote import (include should be similar) # Trusting koha-community.org DNS here ;) # This should not trigger read_net but fail on the missing import. -$xslt=<<"EOT"; +$xslt = <<"EOT"; <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:import href="http://notexpected.koha-community.org/noxsl/nothing.xsl"/> <xsl:output method="xml" encoding="UTF-8" version="1.0" indent="yes"/> @@ -116,13 +116,14 @@ $engine->print_warns(1); { my @warn; local $SIG{__WARN__} = sub { push @warn, $_[0]; }; - $output= $engine->transform({ xml => "<ignored/>", code => $xslt }); - is( ( grep { /failed to load (external entity|HTTP resource)/ } @warn ), 1, 'Expected import error' ); # we saw both messages on Jenkins passing by + $output = $engine->transform( { xml => "<ignored/>", code => $xslt } ); + is( ( grep { /failed to load (external entity|HTTP resource)/ } @warn ), 1, 'Expected import error' ) + ; # we saw both messages on Jenkins passing by is( ( grep { /read_net/ } @warn ), 0, 'No read_net warn for remote import' ); } sub mytempfile { - my ($fh, $fn) = tempfile( UNLINK => 1 ); + my ( $fh, $fn ) = tempfile( UNLINK => 1 ); print $fh $_[0] if $_[0]; close $fh; return $fn; diff --git a/t/db_dependent/Koha/Z3950Responder/GenericSession.t b/t/db_dependent/Koha/Z3950Responder/GenericSession.t index 74d0e9fd92..21b5cb2a4a 100755 --- a/t/db_dependent/Koha/Z3950Responder/GenericSession.t +++ b/t/db_dependent/Koha/Z3950Responder/GenericSession.t @@ -25,131 +25,146 @@ subtest 'test_search' => sub { plan tests => 20; - t::lib::Mocks::mock_preference('SearchEngine', 'Elasticsearch'); + t::lib::Mocks::mock_preference( 'SearchEngine', 'Elasticsearch' ); my $marc_record_1 = MARC::Record->new(); $marc_record_1->leader(' cam 22 a 4500'); $marc_record_1->append_fields( - MARC::Field->new('001', '123'), - MARC::Field->new('020', '', '', a => '1-56619-909-3'), - MARC::Field->new('100', '', '', a => 'Author 1'), - MARC::Field->new('110', '', '', a => 'Corp Author'), - MARC::Field->new('210', '', '', a => 'Title 1'), - MARC::Field->new('245', '', '', a => 'Title:', b => 'first record'), - MARC::Field->new('999', '', '', c => '1234567'), + MARC::Field->new( '001', '123' ), + MARC::Field->new( '020', '', '', a => '1-56619-909-3' ), + MARC::Field->new( '100', '', '', a => 'Author 1' ), + MARC::Field->new( '110', '', '', a => 'Corp Author' ), + MARC::Field->new( '210', '', '', a => 'Title 1' ), + MARC::Field->new( '245', '', '', a => 'Title:', b => 'first record' ), + MARC::Field->new( '999', '', '', c => '1234567' ), ); my $marc_record_2 = MARC::Record->new(); $marc_record_2->leader(' cam 22 a 4500'); $marc_record_2->append_fields( - MARC::Field->new('001', '234'), - MARC::Field->new('020', '', '', a => '1-56619-909-3'), - MARC::Field->new('100', '', '', a => 'Author 2'), - MARC::Field->new('110', '', '', a => 'Corp Author'), - MARC::Field->new('210', '', '', a => 'Title 2'), - MARC::Field->new('245', '', '', a => 'Title:', b => 'second record'), - MARC::Field->new('999', '', '', c => '1234567'), + MARC::Field->new( '001', '234' ), + MARC::Field->new( '020', '', '', a => '1-56619-909-3' ), + MARC::Field->new( '100', '', '', a => 'Author 2' ), + MARC::Field->new( '110', '', '', a => 'Corp Author' ), + MARC::Field->new( '210', '', '', a => 'Title 2' ), + MARC::Field->new( '245', '', '', a => 'Title:', b => 'second record' ), + MARC::Field->new( '999', '', '', c => '1234567' ), ); my $yaml = Test::MockModule->new('YAML::XS'); - $yaml->mock('LoadFile', sub { - return { - biblios => { - use => { - 1 => 'author', - 4 => 'title', - 1003 => 'author' + $yaml->mock( + 'LoadFile', + sub { + return { + biblios => { + use => { + 1 => 'author', + 4 => 'title', + 1003 => 'author' + } } - } - }; - }); + }; + } + ); my $builder = Test::MockModule->new('Koha::SearchEngine::Elasticsearch::QueryBuilder'); - $builder->mock('build_query_compat', sub { - my ( $self, $operators, $operands ) = @_; + $builder->mock( + 'build_query_compat', + sub { + my ( $self, $operators, $operands ) = @_; - return (undef, $operands->[0]); - }); + return ( undef, $operands->[0] ); + } + ); my $search = Test::MockModule->new('Koha::SearchEngine::Elasticsearch::Search'); - $search->mock('simple_search_compat', sub { - my ( $self, $query ) = @_; + $search->mock( + 'simple_search_compat', + sub { + my ( $self, $query ) = @_; - return ('unexpected query', undef, 0) unless $query eq '((author:(author)) AND ((title:(title\(s\))) OR (title:(speciäl))))' || $query eq "(simple search)"; + return ( 'unexpected query', undef, 0 ) + unless $query eq '((author:(author)) AND ((title:(title\(s\))) OR (title:(speciäl))))' + || $query eq "(simple search)"; - my @records = ($marc_record_1, $marc_record_2); - return (undef, \@records, 2); - }); + my @records = ( $marc_record_1, $marc_record_2 ); + return ( undef, \@records, 2 ); + } + ); $child = fork(); - if ($child == 0) { + if ( $child == 0 ) { my $config_dir = $Bin . '/'; - my $z = Koha::Z3950Responder->new( { - config_dir => $config_dir - }); + my $z = Koha::Z3950Responder->new( { config_dir => $config_dir } ); $z->start(); exit; } - sleep(10); # Just a try to see if it fixes Jenkins + sleep(10); # Just a try to see if it fixes Jenkins # Z39.50 protocol tests my $o = ZOOM::Options->new(); - $o->option(preferredRecordSyntax => 'xml'); - $o->option(elementSetName => 'marcxml'); - $o->option(databaseName => 'biblios'); + $o->option( preferredRecordSyntax => 'xml' ); + $o->option( elementSetName => 'marcxml' ); + $o->option( databaseName => 'biblios' ); my $Zconn = ZOOM::Connection->create($o); - ok($Zconn, 'ZOOM connection created'); + ok( $Zconn, 'ZOOM connection created' ); - $Zconn->connect('localhost:42111', 0); - is($Zconn->errcode(), 0, 'Connection is successful: ' . $Zconn->errmsg()); + $Zconn->connect( 'localhost:42111', 0 ); + is( $Zconn->errcode(), 0, 'Connection is successful: ' . $Zconn->errmsg() ); my $rs = $Zconn->search_pqf('@and @attr 1=1 @attr 4=1 author @or @attr 1=4 title(s) @attr 1=4 speciäl'); - is($Zconn->errcode(), 0, 'Search is successful: ' . $Zconn->errmsg()); + is( $Zconn->errcode(), 0, 'Search is successful: ' . $Zconn->errmsg() ); - is($rs->size(), 2, 'Two results returned'); + is( $rs->size(), 2, 'Two results returned' ); - my $returned1 = MARC::Record->new_from_xml($rs->record(0)->raw(), 'UTF-8'); - ok($returned1, 'Record 1 returned as MARCXML'); - is($returned1->as_xml, $marc_record_1->as_xml, 'Record 1 returned properly'); + my $returned1 = MARC::Record->new_from_xml( $rs->record(0)->raw(), 'UTF-8' ); + ok( $returned1, 'Record 1 returned as MARCXML' ); + is( $returned1->as_xml, $marc_record_1->as_xml, 'Record 1 returned properly' ); - my $returned2= MARC::Record->new_from_xml($rs->record(1)->raw(), 'UTF-8'); - ok($returned2, 'Record 2 returned as MARCXML'); - is($returned2->as_xml, $marc_record_2->as_xml, 'Record 2 returned properly'); + my $returned2 = MARC::Record->new_from_xml( $rs->record(1)->raw(), 'UTF-8' ); + ok( $returned2, 'Record 2 returned as MARCXML' ); + is( $returned2->as_xml, $marc_record_2->as_xml, 'Record 2 returned properly' ); $rs = $Zconn->search_pqf('"simple search"'); - is($Zconn->errcode(), 0, 'Search is successful: ' . $Zconn->errmsg()); + is( $Zconn->errcode(), 0, 'Search is successful: ' . $Zconn->errmsg() ); # SRU protocol tests - my $base = 'http://localhost:42111'; - my $ns = 'http://www.loc.gov/zing/srw/'; + my $base = 'http://localhost:42111'; + my $ns = 'http://www.loc.gov/zing/srw/'; my $marc_ns = 'http://www.loc.gov/MARC21/slim'; - my $agent = Test::WWW::Mechanize->new( autocheck => 1 ); + my $agent = Test::WWW::Mechanize->new( autocheck => 1 ); - $agent->get_ok("$base?version=1.1", 'Retrieve explain response'); - my $dom = XML::LibXML->load_xml(string => $agent->content()); - my @nodes = $dom->getElementsByTagNameNS($ns, 'explainResponse'); - is(scalar(@nodes), 1, 'explainResponse returned'); + $agent->get_ok( "$base?version=1.1", 'Retrieve explain response' ); + my $dom = XML::LibXML->load_xml( string => $agent->content() ); + my @nodes = $dom->getElementsByTagNameNS( $ns, 'explainResponse' ); + is( scalar(@nodes), 1, 'explainResponse returned' ); - $agent->get_ok("$base/biblios?operation=searchRetrieve&recordSchema=marcxml&version=1.1&maximumRecords=10&query=", 'Try bad search query'); - $dom = XML::LibXML->load_xml(string => $agent->content()); - @nodes = $dom->getElementsByTagNameNS($ns, 'diagnostics'); - is(scalar(@nodes), 1, 'diagnostics returned for bad query'); + $agent->get_ok( + "$base/biblios?operation=searchRetrieve&recordSchema=marcxml&version=1.1&maximumRecords=10&query=", + 'Try bad search query' + ); + $dom = XML::LibXML->load_xml( string => $agent->content() ); + @nodes = $dom->getElementsByTagNameNS( $ns, 'diagnostics' ); + is( scalar(@nodes), 1, 'diagnostics returned for bad query' ); - $agent->get_ok("$base/biblios?operation=searchRetrieve&recordSchema=marcxml&version=1.1&maximumRecords=10&query=(dc.author%3dauthor AND (dc.title%3d\"title(s)\" OR dc.title%3dspeciäl))", 'Retrieve search results'); - $dom = XML::LibXML->load_xml(string => $agent->content()); - @nodes = $dom->getElementsByTagNameNS($ns, 'searchRetrieveResponse'); - is(scalar(@nodes), 1, 'searchRetrieveResponse returned'); - my @records = $nodes[0]->getElementsByTagNameNS($marc_ns, 'record'); - is(scalar(@records), 2, 'Two results returned'); + $agent->get_ok( + "$base/biblios?operation=searchRetrieve&recordSchema=marcxml&version=1.1&maximumRecords=10&query=(dc.author%3dauthor AND (dc.title%3d\"title(s)\" OR dc.title%3dspeciäl))", + 'Retrieve search results' + ); + $dom = XML::LibXML->load_xml( string => $agent->content() ); + @nodes = $dom->getElementsByTagNameNS( $ns, 'searchRetrieveResponse' ); + is( scalar(@nodes), 1, 'searchRetrieveResponse returned' ); + my @records = $nodes[0]->getElementsByTagNameNS( $marc_ns, 'record' ); + is( scalar(@records), 2, 'Two results returned' ); - $returned1 = MARC::Record->new_from_xml($records[0]->toString(), 'UTF-8'); - ok($returned1, 'Record 1 returned as MARCXML'); - is($returned1->as_xml, $marc_record_1->as_xml, 'Record 1 returned properly'); + $returned1 = MARC::Record->new_from_xml( $records[0]->toString(), 'UTF-8' ); + ok( $returned1, 'Record 1 returned as MARCXML' ); + is( $returned1->as_xml, $marc_record_1->as_xml, 'Record 1 returned properly' ); - $returned2= MARC::Record->new_from_xml($records[1]->toString(), 'UTF-8'); - ok($returned2, 'Record 2 returned as MARCXML'); - is($returned2->as_xml, $marc_record_2->as_xml, 'Record 2 returned properly'); + $returned2 = MARC::Record->new_from_xml( $records[1]->toString(), 'UTF-8' ); + ok( $returned2, 'Record 2 returned as MARCXML' ); + is( $returned2->as_xml, $marc_record_2->as_xml, 'Record 2 returned properly' ); cleanup(); }; diff --git a/t/db_dependent/Koha/Z3950Responder/Session.t b/t/db_dependent/Koha/Z3950Responder/Session.t index f6e7c65f95..ea9071cc6a 100755 --- a/t/db_dependent/Koha/Z3950Responder/Session.t +++ b/t/db_dependent/Koha/Z3950Responder/Session.t @@ -31,10 +31,10 @@ subtest 'add_item_status' => sub { withdrawn => 1, } ); - my ( $itemtag, $itemsubfield ) = C4::Biblio::GetMarcFromKohaField( "items.itemnumber" ); - my $item_marc_1 = C4::Items::GetMarcItem( $item_1->biblionumber, $item_1->itemnumber ); + my ( $itemtag, $itemsubfield ) = C4::Biblio::GetMarcFromKohaField("items.itemnumber"); + my $item_marc_1 = C4::Items::GetMarcItem( $item_1->biblionumber, $item_1->itemnumber ); my $item_field_1 = scalar $item_marc_1->field($itemtag); - $builder->build({ source => 'Reserve', value=> { itemnumber => $item_1->itemnumber } }); + $builder->build( { source => 'Reserve', value => { itemnumber => $item_1->itemnumber } } ); $builder->build( { source => 'Branchtransfer', @@ -49,27 +49,30 @@ subtest 'add_item_status' => sub { ## END FIRST ITEM ## ## SECOND ITEM HAS NO STATUSES ## - my $item_2 = $builder->build_sample_item; - my $item_marc_2 = C4::Items::GetMarcItem( $item_2->biblionumber, $item_2->itemnumber ); + my $item_2 = $builder->build_sample_item; + my $item_marc_2 = C4::Items::GetMarcItem( $item_2->biblionumber, $item_2->itemnumber ); my $item_field_2 = scalar $item_marc_2->field($itemtag); ## END SECOND ITEM ## # We want to test the default values, so we remove custom status alias if present - my $available = Koha::AuthorisedValues->find({ category => 'Z3950_STATUS', authorised_value => 'AVAILABLE' }); + my $available = Koha::AuthorisedValues->find( { category => 'Z3950_STATUS', authorised_value => 'AVAILABLE' } ); $available->delete if $available; # Create the responder - my $args={ PEER_NAME => 'PEER'}; - my $zR = Koha::Z3950Responder->new({add_item_status_subfield => 'k'}); + my $args = { PEER_NAME => 'PEER' }; + my $zR = Koha::Z3950Responder->new( { add_item_status_subfield => 'k' } ); $zR->init_handler($args); $args->{HANDLE}->add_item_status($item_field_1); - is($item_field_1->subfield('k'),"Checked Out, Lost, Not for Loan, Damaged, Withdrawn, In Transit, On Hold","All statuses added in one field as expected"); + is( + $item_field_1->subfield('k'), "Checked Out, Lost, Not for Loan, Damaged, Withdrawn, In Transit, On Hold", + "All statuses added in one field as expected" + ); $args->{HANDLE}->add_item_status($item_field_2); - is($item_field_2->subfield('k'),'Available',"Available status added as expected"); + is( $item_field_2->subfield('k'), 'Available', "Available status added as expected" ); - is($item_field_2->subfield( $itemsubfield ), $item_2->itemnumber, "Itemnumber not removed when status added"); + is( $item_field_2->subfield($itemsubfield), $item_2->itemnumber, "Itemnumber not removed when status added" ); }; diff --git a/t/db_dependent/Koha/Z3950Responder/Session2.t b/t/db_dependent/Koha/Z3950Responder/Session2.t index 5912d8ff2f..7ac2145f65 100755 --- a/t/db_dependent/Koha/Z3950Responder/Session2.t +++ b/t/db_dependent/Koha/Z3950Responder/Session2.t @@ -27,29 +27,33 @@ subtest 'add_item_status' => sub { # This time we are sustituting some values - my $available = Koha::AuthorisedValues->find({ category => 'Z3950_STATUS', authorised_value => 'AVAILABLE' }); - unless( $available ){ - $available = $builder->build_object({ - class => 'Koha::AuthorisedValues', - value => { - category => 'Z3950_STATUS', - authorised_value => 'AVAILABLE', - lib => "Free as a bird" + my $available = Koha::AuthorisedValues->find( { category => 'Z3950_STATUS', authorised_value => 'AVAILABLE' } ); + unless ($available) { + $available = $builder->build_object( + { + class => 'Koha::AuthorisedValues', + value => { + category => 'Z3950_STATUS', + authorised_value => 'AVAILABLE', + lib => "Free as a bird" + } } - }); + ); } my $available_status = $available->lib; - my $damaged = Koha::AuthorisedValues->find({ category => 'Z3950_STATUS', authorised_value => 'DAMAGED' }); - unless( $damaged ){ - $damaged = $builder->build_object({ - class => 'Koha::AuthorisedValues', - value => { - category => 'Z3950_STATUS', - authorised_value => 'DAMAGED', - lib => "Borked completely" + my $damaged = Koha::AuthorisedValues->find( { category => 'Z3950_STATUS', authorised_value => 'DAMAGED' } ); + unless ($damaged) { + $damaged = $builder->build_object( + { + class => 'Koha::AuthorisedValues', + value => { + category => 'Z3950_STATUS', + authorised_value => 'DAMAGED', + lib => "Borked completely" + } } - }); + ); } my $damaged_status = $damaged->lib; @@ -63,9 +67,9 @@ subtest 'add_item_status' => sub { withdrawn => 1, } ); - my $item_marc_1 = C4::Items::GetMarcItem( $item_1->biblionumber, $item_1->itemnumber ); + my $item_marc_1 = C4::Items::GetMarcItem( $item_1->biblionumber, $item_1->itemnumber ); my $item_field_1 = scalar $item_marc_1->field('952'); - $builder->build({ source => 'Reserve', value=> { itemnumber => $item_1->itemnumber } }); + $builder->build( { source => 'Reserve', value => { itemnumber => $item_1->itemnumber } } ); $builder->build( { source => 'Branchtransfer', @@ -80,21 +84,28 @@ subtest 'add_item_status' => sub { ## END FIRST ITEM ## ## SECOND ITEM HAS NO STATUSES ## - my $item_2 = $builder->build_sample_item; - my $item_marc_2 = C4::Items::GetMarcItem( $item_2->biblionumber, $item_2->itemnumber ); + my $item_2 = $builder->build_sample_item; + my $item_marc_2 = C4::Items::GetMarcItem( $item_2->biblionumber, $item_2->itemnumber ); my $item_field_2 = scalar $item_marc_2->field('952'); ## END SECOND ITEM ## # Create the responder - my $args={ PEER_NAME => 'PEER'}; - my $zR = Koha::Z3950Responder->new({add_item_status_subfield => 'k'}); + my $args = { PEER_NAME => 'PEER' }; + my $zR = Koha::Z3950Responder->new( { add_item_status_subfield => 'k' } ); $zR->init_handler($args); $args->{HANDLE}->add_item_status($item_field_1); - is($item_field_1->subfield('k'),"Checked Out, Lost, Not for Loan, $damaged_status, Withdrawn, In Transit, On Hold","All statuses added in one field as expected"); + is( + $item_field_1->subfield('k'), + "Checked Out, Lost, Not for Loan, $damaged_status, Withdrawn, In Transit, On Hold", + "All statuses added in one field as expected" + ); $args->{HANDLE}->add_item_status($item_field_2); - is($item_field_2->subfield('k'),"$available_status","Available status is '$available_status' added as expected"); + is( + $item_field_2->subfield('k'), "$available_status", + "Available status is '$available_status' added as expected" + ); }; diff --git a/t/db_dependent/Koha/Z3950Responder/ZebraSession.t b/t/db_dependent/Koha/Z3950Responder/ZebraSession.t index 70e38f09d1..47cc4d6263 100755 --- a/t/db_dependent/Koha/Z3950Responder/ZebraSession.t +++ b/t/db_dependent/Koha/Z3950Responder/ZebraSession.t @@ -19,99 +19,119 @@ subtest 'test_search' => sub { plan tests => 8; - t::lib::Mocks::mock_preference('SearchEngine', 'Zebra'); + t::lib::Mocks::mock_preference( 'SearchEngine', 'Zebra' ); my $marc_record_1 = MARC::Record->new(); $marc_record_1->leader(' cam 22 a 4500'); $marc_record_1->append_fields( - MARC::Field->new('001', '123'), - MARC::Field->new('020', '', '', a => '1-56619-909-3'), - MARC::Field->new('100', '', '', a => 'Author 1'), - MARC::Field->new('110', '', '', a => 'Corp Author'), - MARC::Field->new('210', '', '', a => 'Title 1'), - MARC::Field->new('245', '', '', a => 'Title:', b => 'first record'), - MARC::Field->new('999', '', '', c => '1234567'), + MARC::Field->new( '001', '123' ), + MARC::Field->new( '020', '', '', a => '1-56619-909-3' ), + MARC::Field->new( '100', '', '', a => 'Author 1' ), + MARC::Field->new( '110', '', '', a => 'Corp Author' ), + MARC::Field->new( '210', '', '', a => 'Title 1' ), + MARC::Field->new( '245', '', '', a => 'Title:', b => 'first record' ), + MARC::Field->new( '999', '', '', c => '1234567' ), ); my $marc_record_2 = MARC::Record->new(); $marc_record_2->leader(' cam 22 a 4500'); $marc_record_2->append_fields( - MARC::Field->new('001', '234'), - MARC::Field->new('020', '', '', a => '1-56619-909-3'), - MARC::Field->new('100', '', '', a => 'Author 2'), - MARC::Field->new('110', '', '', a => 'Corp Author'), - MARC::Field->new('210', '', '', a => 'Title 2'), - MARC::Field->new('245', '', '', a => 'Title:', b => 'second record'), - MARC::Field->new('999', '', '', c => '1234567'), + MARC::Field->new( '001', '234' ), + MARC::Field->new( '020', '', '', a => '1-56619-909-3' ), + MARC::Field->new( '100', '', '', a => 'Author 2' ), + MARC::Field->new( '110', '', '', a => 'Corp Author' ), + MARC::Field->new( '210', '', '', a => 'Title 2' ), + MARC::Field->new( '245', '', '', a => 'Title:', b => 'second record' ), + MARC::Field->new( '999', '', '', c => '1234567' ), ); my $context = Test::MockModule->new('C4::Context'); - $context->mock('Zconn', sub { - my $Zconn = Test::MockObject->new(); - $Zconn->mock('connect', sub {}); - $Zconn->mock('err_code', sub { - return 0; - }); - $Zconn->mock('search_pqf', sub { - my $results = Test::MockObject->new(); - $results->mock('size', sub { - return 2; - }); - $results->mock('record_immediate', sub { - my ($self, $index) = @_; - - my $record; - if ($index == 0) { - $record = $marc_record_1; - } elsif ($index == 1) { - $record = $marc_record_2; + $context->mock( + 'Zconn', + sub { + my $Zconn = Test::MockObject->new(); + $Zconn->mock( 'connect', sub { } ); + $Zconn->mock( + 'err_code', + sub { + return 0; } - my $Zrecord = Test::MockObject->new(); - $Zrecord->mock('raw', sub { - return $record->as_xml(); - }); - return $Zrecord; - }); - $results->mock('records', sub {}); - $results->mock('destroy', sub {}); - }); - }); + ); + $Zconn->mock( + 'search_pqf', + sub { + my $results = Test::MockObject->new(); + $results->mock( + 'size', + sub { + return 2; + } + ); + $results->mock( + 'record_immediate', + sub { + my ( $self, $index ) = @_; + + my $record; + if ( $index == 0 ) { + $record = $marc_record_1; + } elsif ( $index == 1 ) { + $record = $marc_record_2; + } + my $Zrecord = Test::MockObject->new(); + $Zrecord->mock( + 'raw', + sub { + return $record->as_xml(); + } + ); + return $Zrecord; + } + ); + $results->mock( 'records', sub { } ); + $results->mock( 'destroy', sub { } ); + } + ); + } + ); $child = fork(); - if ($child == 0) { - my @yaz_options = ( '@:42111' ); - my $z = Koha::Z3950Responder->new( { - config_dir => '', - yaz_options => [ @yaz_options ] - }); + if ( $child == 0 ) { + my @yaz_options = ('@:42111'); + my $z = Koha::Z3950Responder->new( + { + config_dir => '', + yaz_options => [@yaz_options] + } + ); $z->start(); exit; } - sleep(10); # Just a try to see if it fixes Jenkins + sleep(10); # Just a try to see if it fixes Jenkins my $o = ZOOM::Options->new(); - $o->option(preferredRecordSyntax => 'xml'); - $o->option(elementSetName => 'marcxml'); - $o->option(databaseName => 'biblios'); + $o->option( preferredRecordSyntax => 'xml' ); + $o->option( elementSetName => 'marcxml' ); + $o->option( databaseName => 'biblios' ); my $Zconn = ZOOM::Connection->create($o); - ok($Zconn, 'ZOOM connection created'); + ok( $Zconn, 'ZOOM connection created' ); - $Zconn->connect('127.0.0.1:42111', 0); - is($Zconn->errcode(), 0, 'Connection is successful: ' . $Zconn->errmsg()); + $Zconn->connect( '127.0.0.1:42111', 0 ); + is( $Zconn->errcode(), 0, 'Connection is successful: ' . $Zconn->errmsg() ); my $rs = $Zconn->search_pqf('@and @attr 1=1 author @attr 1=4 title'); - is($Zconn->errcode(), 0, 'Search is successful: ' . $Zconn->errmsg()); + is( $Zconn->errcode(), 0, 'Search is successful: ' . $Zconn->errmsg() ); - is($rs->size(), 2, 'Two results returned'); + is( $rs->size(), 2, 'Two results returned' ); - my $returned1 = MARC::Record->new_from_xml($rs->record(0)->raw(), 'UTF-8'); - ok ($returned1, 'Record 1 returned as MARCXML'); - is($returned1->as_xml, $marc_record_1->as_xml, 'Record 1 returned properly'); + my $returned1 = MARC::Record->new_from_xml( $rs->record(0)->raw(), 'UTF-8' ); + ok( $returned1, 'Record 1 returned as MARCXML' ); + is( $returned1->as_xml, $marc_record_1->as_xml, 'Record 1 returned properly' ); - my $returned2= MARC::Record->new_from_xml($rs->record(1)->raw(), 'UTF-8'); - ok ($returned2, 'Record 2 returned as MARCXML'); - is($returned2->as_xml, $marc_record_2->as_xml, 'Record 2 returned properly'); + my $returned2 = MARC::Record->new_from_xml( $rs->record(1)->raw(), 'UTF-8' ); + ok( $returned2, 'Record 2 returned as MARCXML' ); + is( $returned2->as_xml, $marc_record_2->as_xml, 'Record 2 returned properly' ); cleanup(); }; diff --git a/t/db_dependent/Koha/Z3950Servers.t b/t/db_dependent/Koha/Z3950Servers.t index 6f6dbd81c3..556617f37f 100755 --- a/t/db_dependent/Koha/Z3950Servers.t +++ b/t/db_dependent/Koha/Z3950Servers.t @@ -26,39 +26,46 @@ use Koha::Database; use Koha::Z3950Server; use Koha::Z3950Servers; -my $schema = Koha::Database->new->schema; +my $schema = Koha::Database->new->schema; my $builder = t::lib::TestBuilder->new; subtest 'new, find and delete tests' => sub { plan tests => 4; $schema->storage->txn_begin; my $nb_of_z39s = Koha::Z3950Servers->search->count; - my $new_z39_1 = Koha::Z3950Server->new({ - host => 'my_host1.org', - port => '32', - db => 'db1', - servername => 'my_test_1', - servertype => 'zed', - recordtype => 'biblio', - syntax => 'USMARC', - encoding => 'MARC-8', - })->store; - my $new_z39_2 = Koha::Z3950Server->new({ - host => 'my_host2.org', - port => '64', - db => 'db2', - servername => 'my_test_2', - servertype => 'zed', - recordtype => 'authority', - syntax => 'USMARC', - encoding => 'MARC-8', - })->store; + my $new_z39_1 = Koha::Z3950Server->new( + { + host => 'my_host1.org', + port => '32', + db => 'db1', + servername => 'my_test_1', + servertype => 'zed', + recordtype => 'biblio', + syntax => 'USMARC', + encoding => 'MARC-8', + } + )->store; + my $new_z39_2 = Koha::Z3950Server->new( + { + host => 'my_host2.org', + port => '64', + db => 'db2', + servername => 'my_test_2', + servertype => 'zed', + recordtype => 'authority', + syntax => 'USMARC', + encoding => 'MARC-8', + } + )->store; - like( $new_z39_1->id, qr|^\d+$|, 'Adding a new z39 server should have set the id'); + like( $new_z39_1->id, qr|^\d+$|, 'Adding a new z39 server should have set the id' ); is( Koha::Z3950Servers->search->count, $nb_of_z39s + 2, 'The 2 z39 servers should have been added' ); my $retrieved_z39_1 = Koha::Z3950Servers->find( $new_z39_1->id ); - is( $retrieved_z39_1->servername, $new_z39_1->servername, 'Find a z39 server by id should return the correct z39 server' ); + is( + $retrieved_z39_1->servername, $new_z39_1->servername, + 'Find a z39 server by id should return the correct z39 server' + ); $retrieved_z39_1->delete; is( Koha::Z3950Servers->search->count, $nb_of_z39s + 1, 'Delete should have deleted the z39 server' ); @@ -69,15 +76,17 @@ subtest 'new, find and delete tests' => sub { subtest 'Host, syntax and encoding are NOT NULL now (BZ 30571)' => sub { plan tests => 7; $schema->storage->txn_begin; - local $SIG{__WARN__} = sub {}; # TODO Needed it for suppressing DBIx warns + local $SIG{__WARN__} = sub { }; # TODO Needed it for suppressing DBIx warns - my $server = Koha::Z3950Server->new({ - port => '80', - db => 'db', - servername => 'my_test_3', - servertype => 'zed', - recordtype => 'biblio', - }); + my $server = Koha::Z3950Server->new( + { + port => '80', + db => 'db', + servername => 'my_test_3', + servertype => 'zed', + recordtype => 'biblio', + } + ); throws_ok { $server->store } 'DBIx::Class::Exception', 'Exception on empty host'; like( $@->{msg}, qr/'host' doesn't have a default value/, 'Verified that DBIx blamed host' ); diff --git a/t/db_dependent/Koha_Database.t b/t/db_dependent/Koha_Database.t index dd51feb707..19dbaec6b7 100755 --- a/t/db_dependent/Koha_Database.t +++ b/t/db_dependent/Koha_Database.t @@ -17,25 +17,35 @@ my $schema; ok( $schema = $database->schema(), 'Get a schema' ); my $dbh; ok( $dbh = $schema->storage->dbh(), 'Get an old fashioned DBI dbh handle' ); -ok( $schema->storage->connected(), 'Check our db connection is active' ); +ok( $schema->storage->connected(), 'Check our db connection is active' ); is( ref($schema), 'Koha::Schema', 'Koha::Database->new->schema should return a Koha::Schema' ); my $another_schema = $database->schema(); -is( $another_schema->storage->_conn_pid, $schema->storage->_conn_pid, 'Getting another schema should return the same one, it has correctly been cached' ); +is( + $another_schema->storage->_conn_pid, $schema->storage->_conn_pid, + 'Getting another schema should return the same one, it has correctly been cached' +); $another_schema = Koha::Database->new->schema(); -is( $another_schema->storage->_conn_pid, $schema->storage->_conn_pid, 'Getting another schema should return the same one, it has correctly been cached' ); +is( + $another_schema->storage->_conn_pid, $schema->storage->_conn_pid, + 'Getting another schema should return the same one, it has correctly been cached' +); # run in a transaction $schema->storage->txn_begin(); # clear the way -$schema->resultset('Category')->search({ categorycode => 'GIFT-RUS' })->delete; +$schema->resultset('Category')->search( { categorycode => 'GIFT-RUS' } )->delete; my $gift = 'подарок'; -$schema->resultset('Category')->create({ - categorycode => 'GIFT-RUS', - description => $gift, -}); -my $desc = $schema->resultset('Category')->search({ - categorycode => 'GIFT-RUS', -})->single->get_column('description'); -is($desc, $gift, 'stored and retrieved UTF8 string'); +$schema->resultset('Category')->create( + { + categorycode => 'GIFT-RUS', + description => $gift, + } +); +my $desc = $schema->resultset('Category')->search( + { + categorycode => 'GIFT-RUS', + } +)->single->get_column('description'); +is( $desc, $gift, 'stored and retrieved UTF8 string' ); $schema->storage->txn_rollback(); diff --git a/t/db_dependent/Koha_Elasticsearch.t b/t/db_dependent/Koha_Elasticsearch.t index 63402d7ccc..0942a2e4de 100755 --- a/t/db_dependent/Koha_Elasticsearch.t +++ b/t/db_dependent/Koha_Elasticsearch.t @@ -25,7 +25,7 @@ use MARC::Record; use Koha::SearchFields; use Koha::SearchEngine::Elasticsearch; -my $schema = Koha::Database->schema; +my $schema = Koha::Database->schema; my $builder = t::lib::TestBuilder->new; subtest 'get_facet_fields() tests' => sub { @@ -36,94 +36,110 @@ subtest 'get_facet_fields() tests' => sub { Koha::SearchFields->search()->delete; - $builder->build({ - source => 'SearchField', - value => { - name => 'author', - label => 'author', - type => 'string', - facet_order => undef + $builder->build( + { + source => 'SearchField', + value => { + name => 'author', + label => 'author', + type => 'string', + facet_order => undef + } } - }); - $builder->build({ - source => 'SearchField', - value => { - name => 'holdingbranch', - label => 'holdingbranch', - type => 'string', - facet_order => 1 + ); + $builder->build( + { + source => 'SearchField', + value => { + name => 'holdingbranch', + label => 'holdingbranch', + type => 'string', + facet_order => 1 + } } - }); - $builder->build({ - source => 'SearchField', - value => { - name => 'homebranch', - label => 'homebranch', - type => 'string', - facet_order => 2 + ); + $builder->build( + { + source => 'SearchField', + value => { + name => 'homebranch', + label => 'homebranch', + type => 'string', + facet_order => 2 + } } - }); - $builder->build({ - source => 'SearchField', - value => { - name => 'itype', - label => 'itype', - type => 'string', - facet_order => 3 + ); + $builder->build( + { + source => 'SearchField', + value => { + name => 'itype', + label => 'itype', + type => 'string', + facet_order => 3 + } } - }); - $builder->build({ - source => 'SearchField', - value => { - name => 'title-series', - label => 'titles-series', - type => 'string', - facet_order => 4 + ); + $builder->build( + { + source => 'SearchField', + value => { + name => 'title-series', + label => 'titles-series', + type => 'string', + facet_order => 4 + } } - }); - $builder->build({ - source => 'SearchField', - value => { - name => 'su-geo', - label => 'su-geo', - type => 'string', - facet_order => 5 + ); + $builder->build( + { + source => 'SearchField', + value => { + name => 'su-geo', + label => 'su-geo', + type => 'string', + facet_order => 5 + } } - }); - $builder->build({ - source => 'SearchField', - value => { - name => 'subject', - label => 'subject', - type => 'string', - facet_order => 6 + ); + $builder->build( + { + source => 'SearchField', + value => { + name => 'subject', + label => 'subject', + type => 'string', + facet_order => 6 + } } - }); - $builder->build({ - source => 'SearchField', - value => { - name => 'not_facetable_field', - label => 'not_facetable_field', - type => 'string', - facet_order => undef + ); + $builder->build( + { + source => 'SearchField', + value => { + name => 'not_facetable_field', + label => 'not_facetable_field', + type => 'string', + facet_order => undef + } } - }); + ); my @faceted_fields = Koha::SearchEngine::Elasticsearch->get_facet_fields(); - is(scalar(@faceted_fields), 6); + is( scalar(@faceted_fields), 6 ); - is($faceted_fields[0]->name, 'holdingbranch'); - is($faceted_fields[0]->facet_order, 1); - is($faceted_fields[1]->name, 'homebranch'); - is($faceted_fields[1]->facet_order, 2); - is($faceted_fields[2]->name, 'itype'); - is($faceted_fields[2]->facet_order, 3); - is($faceted_fields[3]->name, 'title-series'); - is($faceted_fields[3]->facet_order, 4); - is($faceted_fields[4]->name, 'su-geo'); - is($faceted_fields[4]->facet_order, 5); - is($faceted_fields[5]->name, 'subject'); - is($faceted_fields[5]->facet_order, 6); + is( $faceted_fields[0]->name, 'holdingbranch' ); + is( $faceted_fields[0]->facet_order, 1 ); + is( $faceted_fields[1]->name, 'homebranch' ); + is( $faceted_fields[1]->facet_order, 2 ); + is( $faceted_fields[2]->name, 'itype' ); + is( $faceted_fields[2]->facet_order, 3 ); + is( $faceted_fields[3]->name, 'title-series' ); + is( $faceted_fields[3]->facet_order, 4 ); + is( $faceted_fields[4]->name, 'su-geo' ); + is( $faceted_fields[4]->facet_order, 5 ); + is( $faceted_fields[5]->name, 'subject' ); + is( $faceted_fields[5]->facet_order, 6 ); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/Koha_ExternalContent_OverDrive.t b/t/db_dependent/Koha_ExternalContent_OverDrive.t index d8c5c97289..1815634dd0 100755 --- a/t/db_dependent/Koha_ExternalContent_OverDrive.t +++ b/t/db_dependent/Koha_ExternalContent_OverDrive.t @@ -12,33 +12,33 @@ BEGIN { if ( check_install( module => 'WebService::ILS::OverDrive::Patron' ) ) { plan tests => 6; } else { - plan skip_all => "Need WebService::ILS::OverDrive::Patron" + plan skip_all => "Need WebService::ILS::OverDrive::Patron"; } } use_ok('Koha::ExternalContent::OverDrive'); -t::lib::Mocks::mock_preference('SessionStorage','tmp'); +t::lib::Mocks::mock_preference( 'SessionStorage', 'tmp' ); -t::lib::Mocks::mock_preference('OverDriveClientKey', 'DUMMY'); -t::lib::Mocks::mock_preference('OverDriveClientSecret', 'DUMMY'); -t::lib::Mocks::mock_preference('OverDriveLibraryID', 'DUMMY'); +t::lib::Mocks::mock_preference( 'OverDriveClientKey', 'DUMMY' ); +t::lib::Mocks::mock_preference( 'OverDriveClientSecret', 'DUMMY' ); +t::lib::Mocks::mock_preference( 'OverDriveLibraryID', 'DUMMY' ); -my $client = Koha::ExternalContent::OverDrive->new({koha_session_id => 'DUMMY'}); +my $client = Koha::ExternalContent::OverDrive->new( { koha_session_id => 'DUMMY' } ); my $user_agent_string = $client->user_agent->agent(); -ok ($user_agent_string =~ m/^Koha/, 'User Agent string is set') +ok( $user_agent_string =~ m/^Koha/, 'User Agent string is set' ) or diag("User Agent string: $user_agent_string"); my $base_url = "http://mykoha.org"; -ok ($client->auth_url($base_url), 'auth_url()'); +ok( $client->auth_url($base_url), 'auth_url()' ); local $@; -eval { $client->auth_by_code("blah", $base_url) }; -ok($@, "auth_by_code() dies with bogus credentials"); +eval { $client->auth_by_code( "blah", $base_url ) }; +ok( $@, "auth_by_code() dies with bogus credentials" ); SKIP: { skip "No exception", 1 unless $@; my $error_message = $client->error_message($@); - ok($error_message =~ m/Authorization Failed/i, "error_message()") + ok( $error_message =~ m/Authorization Failed/i, "error_message()" ) or diag("Original:\n$@\nTurned into:\n$error_message"); } @@ -46,7 +46,7 @@ subtest 'logger() tests' => sub { plan tests => 2; - my $external_content = Koha::ExternalContent::OverDrive->new({koha_session_id => 'DUMMY'}); + my $external_content = Koha::ExternalContent::OverDrive->new( { koha_session_id => 'DUMMY' } ); ok( $external_content->can('logger'), 'A Koha::ExternalContent object has a logger accessor' ); - is( ref($external_content->logger), 'Koha::Logger', 'The accessor return the right object type' ); + is( ref( $external_content->logger ), 'Koha::Logger', 'The accessor return the right object type' ); }; diff --git a/t/db_dependent/Koha_MetadataRecord_Authority.t b/t/db_dependent/Koha_MetadataRecord_Authority.t index 88315524c0..3156dee252 100755 --- a/t/db_dependent/Koha_MetadataRecord_Authority.t +++ b/t/db_dependent/Koha_MetadataRecord_Authority.t @@ -52,42 +52,52 @@ $record2->add_fields( subtest 'Test new, authorized_heading, authid, get_from_authid' => sub { plan tests => 7; - my $auth1 = $builder->build_object({ class => 'Koha::Authorities', - value => { marcxml => $record1->as_xml }, - }); - my $auth2 = $builder->build_object({ class => 'Koha::Authorities', - value => { marcxml => $record2->as_xml }, - }); + my $auth1 = $builder->build_object( + { + class => 'Koha::Authorities', + value => { marcxml => $record1->as_xml }, + } + ); + my $auth2 = $builder->build_object( + { + class => 'Koha::Authorities', + value => { marcxml => $record2->as_xml }, + } + ); - my $authority = Koha::MetadataRecord::Authority->new( $record1 ); - is(ref($authority), 'Koha::MetadataRecord::Authority', 'Created valid Koha::MetadataRecord::Authority object'); - is($authority->authorized_heading(), 'Cooking', 'Authorized heading was correct'); - is_deeply($authority->record, $record1, 'Saved record'); + my $authority = Koha::MetadataRecord::Authority->new($record1); + is( ref($authority), 'Koha::MetadataRecord::Authority', 'Created valid Koha::MetadataRecord::Authority object' ); + is( $authority->authorized_heading(), 'Cooking', 'Authorized heading was correct' ); + is_deeply( $authority->record, $record1, 'Saved record' ); $authority = Koha::MetadataRecord::Authority->get_from_authid( $auth2->id ); - is(ref($authority), 'Koha::MetadataRecord::Authority', 'Retrieved valid Koha::MetadataRecord::Authority object'); - is($authority->authid, $auth2->id, 'Object authid is correct'); - is($authority->record->field('001')->data(), '2345', 'Retrieved original 001'); # Note: not created via AddAuthority + is( ref($authority), 'Koha::MetadataRecord::Authority', 'Retrieved valid Koha::MetadataRecord::Authority object' ); + is( $authority->authid, $auth2->id, 'Object authid is correct' ); + is( $authority->record->field('001')->data(), '2345', 'Retrieved original 001' ) + ; # Note: not created via AddAuthority $authority = Koha::MetadataRecord::Authority->get_from_authid('alphabetsoup'); - is($authority, undef, 'No invalid record is retrieved'); + is( $authority, undef, 'No invalid record is retrieved' ); }; subtest 'Test get_from_breeding' => sub { plan tests => 4; - my $import = $builder->build({ source => 'ImportRecord', - value => { marcxml => $record1->as_xml, record_type => 'auth' }, - }); + my $import = $builder->build( + { + source => 'ImportRecord', + value => { marcxml => $record1->as_xml, record_type => 'auth' }, + } + ); my $import_record_id = $import->{import_record_id}; my $authority = Koha::MetadataRecord::Authority->get_from_breeding($import_record_id); - is(ref($authority), 'Koha::MetadataRecord::Authority', 'Retrieved valid Koha::MetadataRecord::Authority object'); - is($authority->authid, undef, 'Records in reservoir do not have an authid'); - is(ref($authority->record), 'MARC::Record', 'MARC record attached to authority'); + is( ref($authority), 'Koha::MetadataRecord::Authority', 'Retrieved valid Koha::MetadataRecord::Authority object' ); + is( $authority->authid, undef, 'Records in reservoir do not have an authid' ); + is( ref( $authority->record ), 'MARC::Record', 'MARC record attached to authority' ); $authority = Koha::MetadataRecord::Authority->get_from_breeding('alphabetsoup'); - is($authority, undef, 'No invalid record is retrieved from reservoir'); + is( $authority, undef, 'No invalid record is retrieved from reservoir' ); }; $schema->storage->txn_rollback; diff --git a/t/db_dependent/Koha_Misc_Files.t b/t/db_dependent/Koha_Misc_Files.t index 814a306426..f435beb716 100755 --- a/t/db_dependent/Koha_Misc_Files.t +++ b/t/db_dependent/Koha_Misc_Files.t @@ -16,71 +16,75 @@ my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; ## new() parameter handling check -is(Koha::Misc::Files->new(), undef, "new() param check test/0"); -is(Koha::Misc::Files->new(recordid => 12), undef, "new() param check test/1"); -is(Koha::Misc::Files->new(recordid => 'aa123', tabletag => 'ttag_a'), undef, "new() param check test/2"); +is( Koha::Misc::Files->new(), undef, "new() param check test/0" ); +is( Koha::Misc::Files->new( recordid => 12 ), undef, "new() param check test/1" ); +is( Koha::Misc::Files->new( recordid => 'aa123', tabletag => 'ttag_a' ), undef, "new() param check test/2" ); ## create some test objects with arbitrary (tabletag, recordid) pairs -my $mf_a_123 = Koha::Misc::Files->new(recordid => '123', tabletag => 'tst_table_a'); -my $mf_a_124 = Koha::Misc::Files->new(recordid => '124', tabletag => 'tst_table_a'); -my $mf_b_221 = Koha::Misc::Files->new(recordid => '221', tabletag => 'tst_table_b'); -is(ref($mf_a_123), "Koha::Misc::Files", "new() returned object type"); +my $mf_a_123 = Koha::Misc::Files->new( recordid => '123', tabletag => 'tst_table_a' ); +my $mf_a_124 = Koha::Misc::Files->new( recordid => '124', tabletag => 'tst_table_a' ); +my $mf_b_221 = Koha::Misc::Files->new( recordid => '221', tabletag => 'tst_table_b' ); +is( ref($mf_a_123), "Koha::Misc::Files", "new() returned object type" ); ## GetFilesInfo() initial tests (dummy AddFile() / parameter handling checks) -is(ref($mf_a_123->GetFilesInfo()), 'ARRAY', "GetFilesInfo() return type"); -is(scalar @{$mf_a_123->GetFilesInfo()}, 0, "GetFilesInfo() empty/non-empty result/1"); -$mf_a_123->AddFile(name => '', type => 'text/plain', content => "aaabbcc"); -is(scalar @{$mf_a_123->GetFilesInfo()}, 0, "GetFilesInfo() empty/non-empty result/2"); +is( ref( $mf_a_123->GetFilesInfo() ), 'ARRAY', "GetFilesInfo() return type" ); +is( scalar @{ $mf_a_123->GetFilesInfo() }, 0, "GetFilesInfo() empty/non-empty result/1" ); +$mf_a_123->AddFile( name => '', type => 'text/plain', content => "aaabbcc" ); +is( scalar @{ $mf_a_123->GetFilesInfo() }, 0, "GetFilesInfo() empty/non-empty result/2" ); ## AddFile(); add 5 sample file records for 3 test objects -$mf_a_123->AddFile(name => 'File_name_1.txt', type => 'text/plain', - content => "file contents\n1111\n", description => "File #1 sample description"); -$mf_a_123->AddFile(name => 'File_name_2.txt', type => 'text/plain', - content => "file contents\n2222\n", description => "File #2 sample description"); -$mf_a_124->AddFile(name => 'File_name_3.txt', content => "file contents\n3333\n", type => 'text/whatever'); -$mf_a_124->AddFile(name => 'File_name_4.txt', content => "file contents\n4444\n"); -$mf_b_221->AddFile(name => 'File_name_5.txt', content => "file contents\n5555\n"); +$mf_a_123->AddFile( + name => 'File_name_1.txt', type => 'text/plain', + content => "file contents\n1111\n", description => "File #1 sample description" +); +$mf_a_123->AddFile( + name => 'File_name_2.txt', type => 'text/plain', + content => "file contents\n2222\n", description => "File #2 sample description" +); +$mf_a_124->AddFile( name => 'File_name_3.txt', content => "file contents\n3333\n", type => 'text/whatever' ); +$mf_a_124->AddFile( name => 'File_name_4.txt', content => "file contents\n4444\n" ); +$mf_b_221->AddFile( name => 'File_name_5.txt', content => "file contents\n5555\n" ); ## check GetFilesInfo() results for added files my $files_a_123_infos = $mf_a_123->GetFilesInfo(); -is(scalar @$files_a_123_infos, 2, "GetFilesInfo() result count/1"); -is(scalar @{$mf_b_221->GetFilesInfo()}, 1, "GetFilesInfo() result count/2"); -is(ref($files_a_123_infos->[0]), 'HASH', "GetFilesInfo() item file result type"); -is($files_a_123_infos->[0]->{file_name}, 'File_name_1.txt', "GetFilesInfo() result check/1"); -is($files_a_123_infos->[1]->{file_name}, 'File_name_2.txt', "GetFilesInfo() result check/2"); -is($files_a_123_infos->[1]->{file_type}, 'text/plain', "GetFilesInfo() result check/3"); -is($files_a_123_infos->[1]->{file_size}, 19, "GetFilesInfo() result check/4"); -is($files_a_123_infos->[1]->{file_description}, 'File #2 sample description', "GetFilesInfo() result check/5"); +is( scalar @$files_a_123_infos, 2, "GetFilesInfo() result count/1" ); +is( scalar @{ $mf_b_221->GetFilesInfo() }, 1, "GetFilesInfo() result count/2" ); +is( ref( $files_a_123_infos->[0] ), 'HASH', "GetFilesInfo() item file result type" ); +is( $files_a_123_infos->[0]->{file_name}, 'File_name_1.txt', "GetFilesInfo() result check/1" ); +is( $files_a_123_infos->[1]->{file_name}, 'File_name_2.txt', "GetFilesInfo() result check/2" ); +is( $files_a_123_infos->[1]->{file_type}, 'text/plain', "GetFilesInfo() result check/3" ); +is( $files_a_123_infos->[1]->{file_size}, 19, "GetFilesInfo() result check/4" ); +is( $files_a_123_infos->[1]->{file_description}, 'File #2 sample description', "GetFilesInfo() result check/5" ); ## GetFile() result checks -is($mf_a_123->GetFile(), undef, "GetFile() result check/1"); -is($mf_a_123->GetFile(id => 0), undef, "GetFile() result check/2"); +is( $mf_a_123->GetFile(), undef, "GetFile() result check/1" ); +is( $mf_a_123->GetFile( id => 0 ), undef, "GetFile() result check/2" ); -my $a123_file_1 = $mf_a_123->GetFile(id => $files_a_123_infos->[0]->{file_id}); -is(ref($a123_file_1), 'HASH', "GetFile() result check/3"); -is($a123_file_1->{file_id}, $files_a_123_infos->[0]->{file_id}, "GetFile() result check/4"); -is($a123_file_1->{file_content}, "file contents\n1111\n", "GetFile() result check/5"); +my $a123_file_1 = $mf_a_123->GetFile( id => $files_a_123_infos->[0]->{file_id} ); +is( ref($a123_file_1), 'HASH', "GetFile() result check/3" ); +is( $a123_file_1->{file_id}, $files_a_123_infos->[0]->{file_id}, "GetFile() result check/4" ); +is( $a123_file_1->{file_content}, "file contents\n1111\n", "GetFile() result check/5" ); ## MergeFileRecIds() tests -$mf_a_123->MergeFileRecIds(123,221); +$mf_a_123->MergeFileRecIds( 123, 221 ); $files_a_123_infos = $mf_a_123->GetFilesInfo(); -is(scalar @$files_a_123_infos, 2, "GetFilesInfo() result count after dummy MergeFileRecIds()"); +is( scalar @$files_a_123_infos, 2, "GetFilesInfo() result count after dummy MergeFileRecIds()" ); $mf_a_123->MergeFileRecIds(124); $files_a_123_infos = $mf_a_123->GetFilesInfo(); -is(scalar @$files_a_123_infos, 4, "GetFilesInfo() result count after MergeFileRecIds()/1"); -is(scalar @{$mf_a_124->GetFilesInfo()}, 0, "GetFilesInfo() result count after MergeFileRecIds()/2"); -is($files_a_123_infos->[-1]->{file_name}, 'File_name_4.txt', "GetFilesInfo() result check after MergeFileRecIds()"); +is( scalar @$files_a_123_infos, 4, "GetFilesInfo() result count after MergeFileRecIds()/1" ); +is( scalar @{ $mf_a_124->GetFilesInfo() }, 0, "GetFilesInfo() result count after MergeFileRecIds()/2" ); +is( $files_a_123_infos->[-1]->{file_name}, 'File_name_4.txt', "GetFilesInfo() result check after MergeFileRecIds()" ); ## DelFile() test -$mf_a_123->DelFile(id => $files_a_123_infos->[-1]->{file_id}); +$mf_a_123->DelFile( id => $files_a_123_infos->[-1]->{file_id} ); $files_a_123_infos = $mf_a_123->GetFilesInfo(); -is(scalar @$files_a_123_infos, 3, "GetFilesInfo() result count after DelFile()"); +is( scalar @$files_a_123_infos, 3, "GetFilesInfo() result count after DelFile()" ); ## DelAllFiles() tests my $number_of_deleted_files_a_123 = $mf_a_123->DelAllFiles(); is( $number_of_deleted_files_a_123, 3, "DelAllFiles returns the number of deleted files/1" ); $files_a_123_infos = $mf_a_123->GetFilesInfo(); -is(scalar @$files_a_123_infos, 0, "GetFilesInfo() result count after DelAllFiles()/1"); +is( scalar @$files_a_123_infos, 0, "GetFilesInfo() result count after DelAllFiles()/1" ); my $number_of_deleted_files_b_221 = $mf_b_221->DelAllFiles(); -is( $number_of_deleted_files_b_221, 1, "DelAllFiles returns the number of deleted files/2" ); -is(scalar @{$mf_b_221->GetFilesInfo()}, 0, "GetFilesInfo() result count after DelAllFiles()/2"); +is( $number_of_deleted_files_b_221, 1, "DelAllFiles returns the number of deleted files/2" ); +is( scalar @{ $mf_b_221->GetFilesInfo() }, 0, "GetFilesInfo() result count after DelAllFiles()/2" ); diff --git a/t/db_dependent/LDAP/test_ldap_add.pl b/t/db_dependent/LDAP/test_ldap_add.pl index 3258a0397a..1d762c1d6b 100755 --- a/t/db_dependent/LDAP/test_ldap_add.pl +++ b/t/db_dependent/LDAP/test_ldap_add.pl @@ -1,9 +1,9 @@ #!/usr/bin/perl # # To start out, try something like this against your LDAP: -# ldapadd -w metavore -D'cn=Manager,dc=metavore,dc=com' -c -f example3.ldif -# ldapmodify -w metavore -D'cn=Manager,dc=metavore,dc=com' -c -f example3.ldif -# +# ldapadd -w metavore -D'cn=Manager,dc=metavore,dc=com' -c -f example3.ldif +# ldapmodify -w metavore -D'cn=Manager,dc=metavore,dc=com' -c -f example3.ldif +# # Then run this script to test perl interaction w/ LDAP. # @@ -13,87 +13,87 @@ use strict; use Net::LDAP; use Net::LDAP::Filter; -my $host = (@ARGV) ? shift : 'localhost'; -my $filter = Net::LDAP::Filter->new((@ARGV) ? shift : 'objectClass=inetOrgPerson'); +my $host = (@ARGV) ? shift : 'localhost'; +my $filter = Net::LDAP::Filter->new( (@ARGV) ? shift : 'objectClass=inetOrgPerson' ); my %params = ( - base => (@ARGV) ? shift : 'dc=metavore,dc=com', - filter => $filter, + base => (@ARGV) ? shift : 'dc=metavore,dc=com', + filter => $filter, ); -my $ldap = Net::LDAP->new($host) or die "Cannot connect to ldap on $host"; -$ldap->bind("cn=Manager," . $params{'base'}, password=>'metavore') or die "Cannot bind to ldap on $host"; +my $ldap = Net::LDAP->new($host) or die "Cannot connect to ldap on $host"; +$ldap->bind( "cn=Manager," . $params{'base'}, password => 'metavore' ) or die "Cannot bind to ldap on $host"; &ldap_dse; &ldap_search; &ldap_add; &ldap_search; sub hashup { - my $query = shift or die "Bad hashup call"; - my %memberhash = (); - my $key; - foreach my $user ($query->shift_entry){ - foreach my $k (@$user) { - foreach my $k2 ( keys %$k ) { - if ($k2 eq 'type') { - $key = $$k{$k2}; - } else { - $memberhash{$key} .= map {$_ . " "} @$k{$k2}; - } - } - } - } - return %memberhash; + my $query = shift or die "Bad hashup call"; + my %memberhash = (); + my $key; + foreach my $user ( $query->shift_entry ) { + foreach my $k (@$user) { + foreach my $k2 ( keys %$k ) { + if ( $k2 eq 'type' ) { + $key = $$k{$k2}; + } else { + $memberhash{$key} .= map { $_ . " " } @$k{$k2}; + } + } + } + } + return %memberhash; } sub recursive_breakdown { my $dse = shift or return; - if (ref($dse) =~ /HASH/) { - return join "\n", map {"$_\t=> " . recursive_breakdown($dse->{$_})} keys %$dse; - } elsif (ref($dse) =~ /ARRAY/) { - return " (\n" . join("\n", map {recursive_breakdown($_)} @$dse) . "\n)\n"; - } else { - return $dse; - } + if ( ref($dse) =~ /HASH/ ) { + return join "\n", map { "$_\t=> " . recursive_breakdown( $dse->{$_} ) } keys %$dse; + } elsif ( ref($dse) =~ /ARRAY/ ) { + return " (\n" . join( "\n", map { recursive_breakdown($_) } @$dse ) . "\n)\n"; + } else { + return $dse; + } } sub ldap_dse { - print "my root DSE: \n"; - print recursive_breakdown $ldap->root_dse(); + print "my root DSE: \n"; + print recursive_breakdown $ldap->root_dse(); } sub ldap_search { - my $query = $ldap->search(%params) or print "Search failed\n"; - $query->code and die sprintf 'error (code:%s) - %s', $query->code , $query->error; - my $size = scalar($query->entries); - my $i=5; - print "\nNumber of records returned from search: $size.\n"; - ($size > $i) and print "Displaying the last $i records.\n\n"; - foreach ($query->entries) { - ($size-- > $i) and next; - $_->dump; - } + my $query = $ldap->search(%params) or print "Search failed\n"; + $query->code and die sprintf 'error (code:%s) - %s', $query->code, $query->error; + my $size = scalar( $query->entries ); + my $i = 5; + print "\nNumber of records returned from search: $size.\n"; + ( $size > $i ) and print "Displaying the last $i records.\n\n"; + foreach ( $query->entries ) { + ( $size-- > $i ) and next; + $_->dump; + } } sub ldap_add { - my $cn = shift or return 0; - my $mail = lc $cn; - $mail =~ s/\s+/./; - print "Adding user $cn\n"; - my $add; - $add = $ldap->add( - "cn=$cn," . $params{'base'}, - attr => [ - cn => $cn, - sn => 'atz', - mail => $mail . '@liblime.com', - telephoneNumber => '1 614 266 9798', - description => 'Implementer and Destroyer', - objectclass => ['person','inetOrgPerson'], - ]) - or printf "Add failed (code %s): %s\n", ($add->code||'unknown'), ($add->error||'unknown'); + my $cn = shift or return 0; + my $mail = lc $cn; + $mail =~ s/\s+/./; + print "Adding user $cn\n"; + my $add; + $add = $ldap->add( + "cn=$cn," . $params{'base'}, + attr => [ + cn => $cn, + sn => 'atz', + mail => $mail . '@liblime.com', + telephoneNumber => '1 614 266 9798', + description => 'Implementer and Destroyer', + objectclass => [ 'person', 'inetOrgPerson' ], + ] + ) or printf "Add failed (code %s): %s\n", ( $add->code || 'unknown' ), ( $add->error || 'unknown' ); } END { - ($ldap) and $ldap->unbind; - print "\ndone.\n"; + ($ldap) and $ldap->unbind; + print "\ndone.\n"; } diff --git a/t/db_dependent/Labels/t_Batch.t b/t/db_dependent/Labels/t_Batch.t index 61a3710129..eaa29a4111 100755 --- a/t/db_dependent/Labels/t_Batch.t +++ b/t/db_dependent/Labels/t_Batch.t @@ -27,13 +27,13 @@ use MARC::Field; use t::lib::TestBuilder; use C4::Context; -use C4::Items qw( AddItemBatchFromMarc ); +use C4::Items qw( AddItemBatchFromMarc ); use C4::Biblio qw( GetMarcFromKohaField AddBiblio ); use Koha::Database; use Koha::Libraries; BEGIN { - use_ok('C4::Labels::Batch', qw( save retrieve delete )); + use_ok( 'C4::Labels::Batch', qw( save retrieve delete ) ); } my $schema = Koha::Database->new->schema; @@ -41,45 +41,47 @@ $schema->storage->txn_begin; my $dbh = C4::Context->dbh; my $builder = t::lib::TestBuilder->new; -$builder->build({ source => 'Branch', value => { branchcode => 'CPL' } }) +$builder->build( { source => 'Branch', value => { branchcode => 'CPL' } } ) unless Koha::Libraries->find('CPL'); my $sth = $dbh->prepare('SELECT branchcode FROM branches b LIMIT 0,1'); $sth->execute(); my $branch_code = $sth->fetchrow_hashref()->{'branchcode'}; -diag sprintf('Database returned the following error: %s', $sth->errstr) if $sth->errstr; +diag sprintf( 'Database returned the following error: %s', $sth->errstr ) if $sth->errstr; my $expected_batch = { - description => '', - creator => 'Labels', - items => [], - branch_code => $branch_code, - batch_stat => 0, # False if any data has changed and the db has not been updated - }; + description => '', + creator => 'Labels', + items => [], + branch_code => $branch_code, + batch_stat => 0, # False if any data has changed and the db has not been updated +}; -my $batch = 0; +my $batch = 0; my $item_number = 0; # Testing Batch->new() method. -ok($batch = C4::Labels::Batch->new(branch_code => $branch_code), "C4::Labels::Batch-->new() succeeds"); +ok( $batch = C4::Labels::Batch->new( branch_code => $branch_code ), "C4::Labels::Batch-->new() succeeds" ); my $batch_id = $batch->get_attr('batch_id'); $expected_batch->{'batch_id'} = $batch_id; -is_deeply($batch, $expected_batch, "New batch object is correct."); +is_deeply( $batch, $expected_batch, "New batch object is correct." ); # Testing Batch->get_attr() method. -foreach my $key (keys %{$expected_batch}) { - if (ref($expected_batch->{$key}) eq 'ARRAY') { - ok(ref($expected_batch->{$key}) eq ref($batch->get_attr($key)), "Batch->get_attr() SUCCESS on attribute $key."); - } - else { - ok($expected_batch->{$key} eq $batch->get_attr($key), "Batch->get_attr() SUCCESS on attribute $key."); +foreach my $key ( keys %{$expected_batch} ) { + if ( ref( $expected_batch->{$key} ) eq 'ARRAY' ) { + ok( + ref( $expected_batch->{$key} ) eq ref( $batch->get_attr($key) ), + "Batch->get_attr() SUCCESS on attribute $key." + ); + } else { + ok( $expected_batch->{$key} eq $batch->get_attr($key), "Batch->get_attr() SUCCESS on attribute $key." ); } } # Testing Batch->add_item() method. # Create the item -my ( $f_holdingbranch, $sf_holdingbranch ) = GetMarcFromKohaField( 'items.holdingbranch' ); -my ( $f_homebranch, $sf_homebranch ) = GetMarcFromKohaField( 'items.homebranch' ); +my ( $f_holdingbranch, $sf_holdingbranch ) = GetMarcFromKohaField('items.holdingbranch'); +my ( $f_homebranch, $sf_homebranch ) = GetMarcFromKohaField('items.homebranch'); is( $f_holdingbranch, $f_homebranch, "items information should be in the same field" ); my $field = $f_holdingbranch; @@ -96,27 +98,27 @@ $record->append_fields( MARC::Field->new( $field, '', '', $sf_homebranch => 'CPL', $sf_holdingbranch => 'CPL' ), MARC::Field->new( $field, '', '', $sf_homebranch => 'CPL', $sf_holdingbranch => 'CPL' ), ); -my ( $biblionumber, $biblioitemnumber ) = C4::Biblio::AddBiblio($record, ''); +my ( $biblionumber, $biblioitemnumber ) = C4::Biblio::AddBiblio( $record, '' ); my @iteminfo = C4::Items::AddItemBatchFromMarc( $record, $biblionumber, $biblioitemnumber, '' ); my $itemnumbers = $iteminfo[0]; -for my $itemnumber ( @$itemnumbers ) { - ok($batch->add_item($itemnumber) eq 0 , "Batch->add_item() success."); +for my $itemnumber (@$itemnumbers) { + ok( $batch->add_item($itemnumber) eq 0, "Batch->add_item() success." ); } $batch_id = $batch->get_attr('batch_id'); # Testing Batch->retrieve() method. -ok(my $saved_batch = C4::Labels::Batch->retrieve(batch_id => $batch_id), "Batch->retrieve() success."); -is_deeply($saved_batch, $batch, "Batch object retrieved correctly" ); +ok( my $saved_batch = C4::Labels::Batch->retrieve( batch_id => $batch_id ), "Batch->retrieve() success." ); +is_deeply( $saved_batch, $batch, "Batch object retrieved correctly" ); # Testing Batch->remove_item() method. my $itemnumber = @$itemnumbers[0]; -ok($batch->remove_item($itemnumber) eq 0, "Batch->remove_item() success."); +ok( $batch->remove_item($itemnumber) eq 0, "Batch->remove_item() success." ); -my $updated_batch = C4::Labels::Batch->retrieve(batch_id => $batch_id); -is_deeply($updated_batch, $batch, "Updated batch object is correct."); +my $updated_batch = C4::Labels::Batch->retrieve( batch_id => $batch_id ); +is_deeply( $updated_batch, $batch, "Updated batch object is correct." ); # Testing Batch->delete() method. my $del_results = $batch->delete(); -ok($del_results eq 0, "Batch->delete() success."); +ok( $del_results eq 0, "Batch->delete() success." ); diff --git a/t/db_dependent/Labels/t_Layout.t b/t/db_dependent/Labels/t_Layout.t index 6271f125cd..63fe00c1de 100755 --- a/t/db_dependent/Labels/t_Layout.t +++ b/t/db_dependent/Labels/t_Layout.t @@ -3,7 +3,7 @@ # Copyright 2007 Foundations Bible College. # # This file is part of Koha. -# +# # Koha 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 3 of the License, or @@ -53,13 +53,15 @@ my $default_layout = { my $layout; # Testing Layout->new() -ok($layout = C4::Labels::Layout->new(layout_name => 'TEST'), "Layout->new() success"); -is_deeply($layout, $default_layout, "New layout object is the expected"); +ok( $layout = C4::Labels::Layout->new( layout_name => 'TEST' ), "Layout->new() success" ); +is_deeply( $layout, $default_layout, "New layout object is the expected" ); # Testing Layout->get_attr() -foreach my $key (keys %{$default_layout}) { - ok($default_layout->{$key} eq $layout->get_attr($key), - "Layout->get_attr() success on attribute $key."); +foreach my $key ( keys %{$default_layout} ) { + ok( + $default_layout->{$key} eq $layout->get_attr($key), + "Layout->get_attr() success on attribute $key." + ); } # Testing Layout->set_attr() @@ -82,45 +84,52 @@ my $new_attr = { units => 'POINT', }; -foreach my $key (keys %{$new_attr}) { - $layout->set_attr($key => $new_attr->{$key}); - ok($new_attr->{$key} eq $layout->get_attr($key), - "Layout->set_attr() success on attribute $key."); +foreach my $key ( keys %{$new_attr} ) { + $layout->set_attr( $key => $new_attr->{$key} ); + ok( + $new_attr->{$key} eq $layout->get_attr($key), + "Layout->set_attr() success on attribute $key." + ); } # Testing Layout->save() method with a new object my $sav_results = $layout->save(); -ok($sav_results ne -1, "Layout->save() success"); +ok( $sav_results ne -1, "Layout->save() success" ); my $saved_layout; + # Testing Layout->retrieve() $new_attr->{'layout_id'} = $sav_results; -ok($saved_layout = C4::Labels::Layout->retrieve(layout_id => $sav_results), - "Layout->retrieve() success"); +ok( + $saved_layout = C4::Labels::Layout->retrieve( layout_id => $sav_results ), + "Layout->retrieve() success" +); foreach my $key ( keys %{$new_attr} ) { if ( $key eq 'scale_height' || $key eq 'scale_width' ) { + # workaround for is_deeply failing to compare scale_height and scale_width is( $saved_layout->{$key} + 0.00, $new_attr->{$key} ); - } - else { + } else { is( $saved_layout->{$key}, $new_attr->{$key} ); } } # Testing Layout->save() method with an updated object -$saved_layout->set_attr(font => 'C'); +$saved_layout->set_attr( font => 'C' ); my $upd_results = $saved_layout->save(); -ok($upd_results ne -1, "Layout->save() success"); -my $updated_layout = C4::Labels::Layout->retrieve(layout_id => $sav_results); -is_deeply($updated_layout, $saved_layout, "Updated layout object is the expected"); +ok( $upd_results ne -1, "Layout->save() success" ); +my $updated_layout = C4::Labels::Layout->retrieve( layout_id => $sav_results ); +is_deeply( $updated_layout, $saved_layout, "Updated layout object is the expected" ); # Testing Layout->get_text_wrap_cols() -is($updated_layout->get_text_wrap_cols(label_width => 180, left_text_margin => 18), 21, - "Layout->get_text_wrap_cols()"); +is( + $updated_layout->get_text_wrap_cols( label_width => 180, left_text_margin => 18 ), 21, + "Layout->get_text_wrap_cols()" +); # Testing Layout->delete() my $del_results = $updated_layout->delete(); -ok( ! defined($del_results) , "Layout->delete() success"); +ok( !defined($del_results), "Layout->delete() success" ); $schema->storage->txn_rollback; diff --git a/t/db_dependent/Labels/t_Profile.t b/t/db_dependent/Labels/t_Profile.t index 7139c7e4e0..b6de7ee6f5 100755 --- a/t/db_dependent/Labels/t_Profile.t +++ b/t/db_dependent/Labels/t_Profile.t @@ -3,7 +3,7 @@ # Copyright 2007 Foundations Bible College. # # This file is part of Koha. -# +# # Koha 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 3 of the License, or @@ -32,72 +32,82 @@ my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; my $expected_profile = { - creator => 'Labels', - printer_name => 'Circulation Desk', - template_id => 0, - paper_bin => 'bypass', - offset_horz => 0, - offset_vert => 0, - creep_horz => 0, - creep_vert => 0, - units => 'POINT', + creator => 'Labels', + printer_name => 'Circulation Desk', + template_id => 0, + paper_bin => 'bypass', + offset_horz => 0, + offset_vert => 0, + creep_horz => 0, + creep_vert => 0, + units => 'POINT', }; my $err = 0; # Testing Profile->new() -ok(my $profile = C4::Labels::Profile->new(printer_name => 'Circulation Desk',paper_bin => 'bypass'), "Profile->new() success"); -is_deeply($profile, $expected_profile, "New profile object verify success"); +ok( + my $profile = C4::Labels::Profile->new( printer_name => 'Circulation Desk', paper_bin => 'bypass' ), + "Profile->new() success" +); +is_deeply( $profile, $expected_profile, "New profile object verify success" ); # Testing Profile->get_attr() -foreach my $key (keys %{$expected_profile}) { - ok($expected_profile->{$key} eq $profile->get_attr($key), - "Profile->get_attr() success on attribute $key"); +foreach my $key ( keys %{$expected_profile} ) { + ok( + $expected_profile->{$key} eq $profile->get_attr($key), + "Profile->get_attr() success on attribute $key" + ); } # Testing Profile->set_attr() my $new_attr = { - printer_name => 'Cataloging Desk', - template_id => '1', - paper_bin => 'tray 1', - offset_horz => 0.3, - offset_vert => 0.85, - creep_horz => 0.156, - creep_vert => 0.67, - units => 'INCH', - creator => 'Labels', + printer_name => 'Cataloging Desk', + template_id => '1', + paper_bin => 'tray 1', + offset_horz => 0.3, + offset_vert => 0.85, + creep_horz => 0.156, + creep_vert => 0.67, + units => 'INCH', + creator => 'Labels', }; -foreach my $key (keys %{$new_attr}) { - $err = $profile->set_attr($key, $new_attr->{$key}); - ok(($new_attr->{$key} eq $profile->get_attr($key)) && ($err lt 1), - "Profile->set_attr() success on attribute $key"); +foreach my $key ( keys %{$new_attr} ) { + $err = $profile->set_attr( $key, $new_attr->{$key} ); + ok( + ( $new_attr->{$key} eq $profile->get_attr($key) ) && ( $err lt 1 ), + "Profile->set_attr() success on attribute $key" + ); } # Testing Profile->save()with a new object my $sav_results = $profile->save(); -ok($sav_results ne -1, "Profile->save() success"); +ok( $sav_results ne -1, "Profile->save() success" ); my $saved_profile; -if ($sav_results ne -1) { +if ( $sav_results ne -1 ) { + # Testing Profile->retrieve() $new_attr->{'profile_id'} = $sav_results; - ok($saved_profile = C4::Labels::Profile->retrieve(profile_id => $sav_results), - "Profile->retrieve() success"); - is_deeply($saved_profile, $new_attr, "Retrieved profile object verify success"); + ok( + $saved_profile = C4::Labels::Profile->retrieve( profile_id => $sav_results ), + "Profile->retrieve() success" + ); + is_deeply( $saved_profile, $new_attr, "Retrieved profile object verify success" ); } # Testing Profile->save() with an updated object -$err = 0; # Reset error code -$err = $saved_profile->set_attr(units => 'CM'); +$err = 0; # Reset error code +$err = $saved_profile->set_attr( units => 'CM' ); my $upd_results = $saved_profile->save(); -ok(($upd_results ne -1) && ($err lt 1), "Profile->save() success"); -my $updated_profile = C4::Labels::Profile->retrieve(profile_id => $sav_results); -is_deeply($updated_profile, $saved_profile, "Updated layout object verify success"); +ok( ( $upd_results ne -1 ) && ( $err lt 1 ), "Profile->save() success" ); +my $updated_profile = C4::Labels::Profile->retrieve( profile_id => $sav_results ); +is_deeply( $updated_profile, $saved_profile, "Updated layout object verify success" ); # Testing Profile->delete() my $del_results = $updated_profile->delete(); -ok($del_results ne -1, "Profile->delete() success"); +ok( $del_results ne -1, "Profile->delete() success" ); $schema->storage->txn_rollback; diff --git a/t/db_dependent/Labels/t_Template.t b/t/db_dependent/Labels/t_Template.t index 98a04d30c9..4ea7b72a88 100755 --- a/t/db_dependent/Labels/t_Template.t +++ b/t/db_dependent/Labels/t_Template.t @@ -3,7 +3,7 @@ # Copyright 2007 Foundations Bible College. # # This file is part of Koha. -# +# # Koha 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 3 of the License, or @@ -32,112 +32,124 @@ my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; my $expect_template = { - creator => 'Labels', - profile_id => 0, - template_code => 'DEFAULT TEMPLATE', - template_desc => 'Default description', - page_width => 8.5, - page_height => 0, - label_width => 0, - label_height => 0, - top_text_margin => 0, - left_text_margin => 0, - top_margin => 0, - left_margin => 0, - cols => 3, - rows => 0, - col_gap => 0, - row_gap => 0, - units => 'POINT', - template_stat => 0, + creator => 'Labels', + profile_id => 0, + template_code => 'DEFAULT TEMPLATE', + template_desc => 'Default description', + page_width => 8.5, + page_height => 0, + label_width => 0, + label_height => 0, + top_text_margin => 0, + left_text_margin => 0, + top_margin => 0, + left_margin => 0, + cols => 3, + rows => 0, + col_gap => 0, + row_gap => 0, + units => 'POINT', + template_stat => 0, }; my $template; # Testing Template->new() -ok($template = C4::Labels::Template->new(page_width => 8.5,cols => 3), - "Template->new() success."); -is_deeply($template, $expect_template, "New template object verify success"); +ok( + $template = C4::Labels::Template->new( page_width => 8.5, cols => 3 ), + "Template->new() success." +); +is_deeply( $template, $expect_template, "New template object verify success" ); # Testing Template->get_attr() -foreach my $key (keys %{$expect_template}) { - ok($expect_template->{$key} eq $template->get_attr($key), - "Template->get_attr() success on attribute $key"); +foreach my $key ( keys %{$expect_template} ) { + ok( + $expect_template->{$key} eq $template->get_attr($key), + "Template->get_attr() success on attribute $key" + ); } # Testing Template->set_attr() my $new_attr = { - creator => 'Labels', - profile_id => 0, - template_code => 'Avery 5160 | 1 x 2-5/8', - template_desc => '3 columns, 10 rows of labels', - page_width => 8.5, - page_height => 11, - label_width => 2.63, - label_height => 1, - top_text_margin => 0.139, - left_text_margin => 0.0417, - top_margin => 0.35, - left_margin => 0.23, - cols => 3, - rows => 10, - col_gap => 0.13, - row_gap => 0, - units => 'INCH', - template_stat => 1, + creator => 'Labels', + profile_id => 0, + template_code => 'Avery 5160 | 1 x 2-5/8', + template_desc => '3 columns, 10 rows of labels', + page_width => 8.5, + page_height => 11, + label_width => 2.63, + label_height => 1, + top_text_margin => 0.139, + left_text_margin => 0.0417, + top_margin => 0.35, + left_margin => 0.23, + cols => 3, + rows => 10, + col_gap => 0.13, + row_gap => 0, + units => 'INCH', + template_stat => 1, }; -foreach my $key (keys %{$new_attr}) { - next if ($key eq 'template_stat'); - $template->set_attr($key, $new_attr->{$key}); - ok($new_attr->{$key} eq $template->get_attr($key), - "Template->set_attr() success on attribute $key"); +foreach my $key ( keys %{$new_attr} ) { + next if ( $key eq 'template_stat' ); + $template->set_attr( $key, $new_attr->{$key} ); + ok( + $new_attr->{$key} eq $template->get_attr($key), + "Template->set_attr() success on attribute $key" + ); } # Testing Template->save() with a new object my $sav_results = $template->save(); -ok($sav_results ne -1, "Template->save() success"); +ok( $sav_results ne -1, "Template->save() success" ); my $saved_template; -if ($sav_results ne -1) { +if ( $sav_results ne -1 ) { + # Testing Template->retrieve() $new_attr->{'template_id'} = $sav_results; - ok($saved_template = C4::Labels::Template->retrieve(template_id => $sav_results), - "Template->retrieve() success"); - is_deeply($saved_template, $new_attr, - "Retrieved template object verify success"); + ok( + $saved_template = C4::Labels::Template->retrieve( template_id => $sav_results ), + "Template->retrieve() success" + ); + is_deeply( + $saved_template, $new_attr, + "Retrieved template object verify success" + ); } # Testing Template->save with an updated object -$saved_template->set_attr(template_desc => 'A test template'); +$saved_template->set_attr( template_desc => 'A test template' ); my $upd_results = $saved_template->save(); -ok($upd_results ne -1, "Template->save() success"); -my $updated_template = C4::Labels::Template->retrieve(template_id => $sav_results); -is_deeply($updated_template, $saved_template, "Updated template object verify success"); +ok( $upd_results ne -1, "Template->save() success" ); +my $updated_template = C4::Labels::Template->retrieve( template_id => $sav_results ); +is_deeply( $updated_template, $saved_template, "Updated template object verify success" ); # Testing Template->retrieve() convert points option -my $conv_template = C4::Labels::Template->retrieve(template_id => $sav_results, convert => 1); -my $expect_conv = { - page_width => 612, - page_height => 792, - label_width => 189.36, - label_height => 72, - top_text_margin => 10.008, - left_text_margin => 3.0024, - top_margin => 25.2, - left_margin => 16.56, - col_gap => 9.36, - row_gap => 0, +my $conv_template = C4::Labels::Template->retrieve( template_id => $sav_results, convert => 1 ); +my $expect_conv = { + page_width => 612, + page_height => 792, + label_width => 189.36, + label_height => 72, + top_text_margin => 10.008, + left_text_margin => 3.0024, + top_margin => 25.2, + left_margin => 16.56, + col_gap => 9.36, + row_gap => 0, }; -foreach my $key (keys %{$expect_conv}) { - ok($expect_conv->{$key} eq $conv_template->get_attr($key), - "Template->retrieve() convert points option success ($expect_conv->{$key})") - || diag("Expected " . $expect_conv->{$key} . " but got " . $conv_template->get_attr($key) . "."); +foreach my $key ( keys %{$expect_conv} ) { + ok( + $expect_conv->{$key} eq $conv_template->get_attr($key), + "Template->retrieve() convert points option success ($expect_conv->{$key})" + ) || diag( "Expected " . $expect_conv->{$key} . " but got " . $conv_template->get_attr($key) . "." ); } # Testing Template->delete() my $del_results = $updated_template->delete(); -ok($del_results ne -1, "Template->delete() success"); +ok( $del_results ne -1, "Template->delete() success" ); $schema->storage->txn_rollback; diff --git a/t/db_dependent/Languages.t b/t/db_dependent/Languages.t index 3a5967ee7d..baac53b541 100755 --- a/t/db_dependent/Languages.t +++ b/t/db_dependent/Languages.t @@ -16,103 +16,114 @@ use t::lib::Mocks; use Koha::Database; BEGIN { - use_ok('C4::Languages', qw( accept_language getAllLanguages getLanguages getTranslatedLanguages get_rfc4646_from_iso639 )); + use_ok( + 'C4::Languages', + qw( accept_language getAllLanguages getLanguages getTranslatedLanguages get_rfc4646_from_iso639 ) + ); } my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; my $dbh = C4::Context->dbh; -isnt(C4::Languages::_get_themes(), undef, 'testing _get_themes doesnt return undef'); +isnt( C4::Languages::_get_themes(), undef, 'testing _get_themes doesnt return undef' ); -ok(C4::Languages::_get_language_dirs(), 'test getting _get_language_dirs'); +ok( C4::Languages::_get_language_dirs(), 'test getting _get_language_dirs' ); my $result; warning_is { $result = C4::Languages::accept_language(); } - q{accept_language(x,y) called with no clientPreferences (x).}, +q{accept_language(x,y) called with no clientPreferences (x).}, 'accept_language() generated expected warning'; -is($result,undef, 'test that accept_languages returns undef when nothing is entered'); +is( $result, undef, 'test that accept_languages returns undef when nothing is entered' ); -ok(C4::Languages::getAllLanguages(), 'test get all languages'); +ok( C4::Languages::getAllLanguages(), 'test get all languages' ); -t::lib::Mocks::mock_preference('AdvancedSearchLanguages', ''); +t::lib::Mocks::mock_preference( 'AdvancedSearchLanguages', '' ); my $all_languages = C4::Languages::getAllLanguages('eng'); -ok(@$all_languages > 10, 'retrieved a bunch of languges'); +ok( @$all_languages > 10, 'retrieved a bunch of languges' ); my $languages = C4::Languages::getLanguages('eng'); -is_deeply($languages, $all_languages, 'getLanguages() and getAllLanguages() return the same list'); +is_deeply( $languages, $all_languages, 'getLanguages() and getAllLanguages() return the same list' ); -$languages = C4::Languages::getLanguages('eng', 1); -is_deeply($languages, $all_languages, 'getLanguages() and getAllLanguages() with filtering selected but AdvancedSearchLanguages blank return the same list'); +$languages = C4::Languages::getLanguages( 'eng', 1 ); +is_deeply( + $languages, $all_languages, + 'getLanguages() and getAllLanguages() with filtering selected but AdvancedSearchLanguages blank return the same list' +); -t::lib::Mocks::mock_preference('AdvancedSearchLanguages', 'ita|eng'); -$languages = C4::Languages::getLanguages('eng', 1); -is(scalar(@$languages), 2, 'getLanguages() filtering using AdvancedSearchLanguages works'); +t::lib::Mocks::mock_preference( 'AdvancedSearchLanguages', 'ita|eng' ); +$languages = C4::Languages::getLanguages( 'eng', 1 ); +is( scalar(@$languages), 2, 'getLanguages() filtering using AdvancedSearchLanguages works' ); my $translatedlanguages1; warnings_are { $translatedlanguages1 = C4::Languages::getTranslatedLanguages( 'opac', 'prog' ) } - [], - 'no warnings for calling getTranslatedLanguages'; +[], + 'no warnings for calling getTranslatedLanguages'; my @currentcheck1 = map { $_->{current} } @$translatedlanguages1; -my $onlyzeros = first { $_ != 0 } @currentcheck1; -ok(! $onlyzeros, "Everything was zeros.\n"); +my $onlyzeros = first { $_ != 0 } @currentcheck1; +ok( !$onlyzeros, "Everything was zeros.\n" ); my $translatedlanguages2; warnings_are { $translatedlanguages2 = C4::Languages::getTranslatedLanguages( 'opac', 'prog', 'en' ) } - [], - 'no warnings for calling getTranslatedLanguages'; +[], + 'no warnings for calling getTranslatedLanguages'; my @currentcheck2 = map { $_->{current} } @$translatedlanguages2; $onlyzeros = first { $_ != 0 } @currentcheck2; -ok($onlyzeros, "There is a $onlyzeros\n"); +ok( $onlyzeros, "There is a $onlyzeros\n" ); # Bug 32775 -my @languages = ('de-DE', 'en', 'en-NZ', 'mi-NZ'); -my @enabledlanguages = ('de-DE', 'en-NZ', 'mi-NZ'); +my @languages = ( 'de-DE', 'en', 'en-NZ', 'mi-NZ' ); +my @enabledlanguages = ( 'de-DE', 'en-NZ', 'mi-NZ' ); my $translatedlanguages3; -$translatedlanguages3 = C4::Languages::_build_languages_arrayref(\@languages,'en',\@enabledlanguages); -is( $translatedlanguages3->[0]->{rfc4646_subtag}, 'de-DE', '_build_languages_arrayref() returns first language of "de-DE"' ); -is( $translatedlanguages3->[1]->{rfc4646_subtag}, 'en', '_build_languages_arrayref() returns second language of "en"'); -is( $translatedlanguages3->[2]->{rfc4646_subtag}, 'mi-NZ', '_build_languages_arrayref() returns third language of "mi-NZ"'); - +$translatedlanguages3 = C4::Languages::_build_languages_arrayref( \@languages, 'en', \@enabledlanguages ); +is( + $translatedlanguages3->[0]->{rfc4646_subtag}, 'de-DE', + '_build_languages_arrayref() returns first language of "de-DE"' +); +is( $translatedlanguages3->[1]->{rfc4646_subtag}, 'en', '_build_languages_arrayref() returns second language of "en"' ); +is( + $translatedlanguages3->[2]->{rfc4646_subtag}, 'mi-NZ', + '_build_languages_arrayref() returns third language of "mi-NZ"' +); # Language Descriptions my $sth = $dbh->prepare("SELECT DISTINCT subtag,type,lang,description from language_descriptions;"); $sth->execute(); -my $DistinctLangDesc = $sth->fetchall_arrayref({}); +my $DistinctLangDesc = $sth->fetchall_arrayref( {} ); $sth = $dbh->prepare("SELECT subtag,type,lang,description from language_descriptions;"); $sth->execute(); -my $LangDesc = $sth->fetchall_arrayref({}); +my $LangDesc = $sth->fetchall_arrayref( {} ); -is(scalar(@$LangDesc),scalar(@$DistinctLangDesc),"No unexpected language_description duplicates."); +is( scalar(@$LangDesc), scalar(@$DistinctLangDesc), "No unexpected language_description duplicates." ); # Language_subtag_registry $sth = $dbh->prepare("SELECT DISTINCT subtag,type,description,added FROM language_subtag_registry;"); $sth->execute(); -my $DistinctLangReg = $sth->fetchall_arrayref({}); +my $DistinctLangReg = $sth->fetchall_arrayref( {} ); $sth = $dbh->prepare("SELECT subtag,type,description,added FROM language_subtag_registry;"); $sth->execute(); -my $LangReg = $sth->fetchall_arrayref({}); +my $LangReg = $sth->fetchall_arrayref( {} ); -is(scalar(@$LangReg),scalar(@$DistinctLangReg),"No unexpected language_subtag_registry duplicates."); +is( scalar(@$LangReg), scalar(@$DistinctLangReg), "No unexpected language_subtag_registry duplicates." ); # Language RFC4646 to ISO639 $sth = $dbh->prepare("SELECT DISTINCT rfc4646_subtag,iso639_2_code FROM language_rfc4646_to_iso639;"); $sth->execute(); -my $DistinctLangRfc4646 = $sth->fetchall_arrayref({}); +my $DistinctLangRfc4646 = $sth->fetchall_arrayref( {} ); $sth = $dbh->prepare("SELECT rfc4646_subtag,iso639_2_code FROM language_rfc4646_to_iso639;"); $sth->execute(); -my $LangRfc4646 = $sth->fetchall_arrayref({}); +my $LangRfc4646 = $sth->fetchall_arrayref( {} ); -is(scalar(@$LangRfc4646),scalar(@$DistinctLangRfc4646),"No unexpected language_rfc4646_to_iso639 duplicates."); +is( scalar(@$LangRfc4646), scalar(@$DistinctLangRfc4646), "No unexpected language_rfc4646_to_iso639 duplicates." ); my $i = 0; -foreach my $pair (@$DistinctLangRfc4646){ +foreach my $pair (@$DistinctLangRfc4646) { $i++ if $pair->{rfc4646_subtag} eq C4::Languages::get_rfc4646_from_iso639( $pair->{iso639_2_code} ); } -is($i,scalar(@$DistinctLangRfc4646),"get_rfc4646_from_iso639 returns correct rfc for all iso values."); +is( $i, scalar(@$DistinctLangRfc4646), "get_rfc4646_from_iso639 returns correct rfc for all iso values." ); $schema->storage->txn_rollback; subtest 'getLanguages()' => sub { diff --git a/t/db_dependent/Letters.t b/t/db_dependent/Letters.t index a1526f8e22..b5fe828fa0 100755 --- a/t/db_dependent/Letters.t +++ b/t/db_dependent/Letters.t @@ -48,9 +48,12 @@ $email_sender_module->mock( use_ok('C4::Context'); use_ok('C4::Members'); -use_ok('C4::Acquisition', qw( NewBasket )); -use_ok('C4::Biblio', qw( AddBiblio GetBiblioData )); -use_ok('C4::Letters', qw( GetMessageTransportTypes GetMessage EnqueueLetter GetQueuedMessages SendQueuedMessages ResendMessage GetLetters GetPreparedLetter SendAlerts )); +use_ok( 'C4::Acquisition', qw( NewBasket ) ); +use_ok( 'C4::Biblio', qw( AddBiblio GetBiblioData ) ); +use_ok( + 'C4::Letters', + qw( GetMessageTransportTypes GetMessage EnqueueLetter GetQueuedMessages SendQueuedMessages ResendMessage GetLetters GetPreparedLetter SendAlerts ) +); use t::lib::Mocks; use t::lib::TestBuilder; use Koha::Database; @@ -69,47 +72,50 @@ my $schema = Koha::Database->schema; $schema->storage->txn_begin(); my $builder = t::lib::TestBuilder->new; -my $dbh = C4::Context->dbh; +my $dbh = C4::Context->dbh; $dbh->do(q|DELETE FROM letter|); $dbh->do(q|DELETE FROM message_queue|); $dbh->do(q|DELETE FROM message_transport_types|); t::lib::Mocks::mock_preference( 'EmailFieldPrimary', '' ); -my $library = $builder->build({ - source => 'Branch', - value => { - branchemail => 'branchemail@address.com', - branchreplyto => 'branchreplyto@address.com', - branchreturnpath => 'branchreturnpath@address.com', +my $library = $builder->build( + { + source => 'Branch', + value => { + branchemail => 'branchemail@address.com', + branchreplyto => 'branchreplyto@address.com', + branchreturnpath => 'branchreturnpath@address.com', + } } -}); -my $patron_category = $builder->build({ source => 'Category' })->{categorycode}; -my $date = dt_from_string; -my $borrowernumber = Koha::Patron->new({ - firstname => 'Jane', - surname => 'Smith', - categorycode => $patron_category, - branchcode => $library->{branchcode}, - dateofbirth => $date, - smsalertnumber => undef, -})->store->borrowernumber; +); +my $patron_category = $builder->build( { source => 'Category' } )->{categorycode}; +my $date = dt_from_string; +my $borrowernumber = Koha::Patron->new( + { + firstname => 'Jane', + surname => 'Smith', + categorycode => $patron_category, + branchcode => $library->{branchcode}, + dateofbirth => $date, + smsalertnumber => undef, + } +)->store->borrowernumber; my $marc_record = MARC::Record->new; -my( $biblionumber, $biblioitemnumber ) = AddBiblio( $marc_record, '' ); - - +my ( $biblionumber, $biblioitemnumber ) = AddBiblio( $marc_record, '' ); # GetMessageTransportTypes my $mtts = C4::Letters::GetMessageTransportTypes(); is( @$mtts, 0, 'GetMessageTransportTypes returns the correct number of message types' ); -$dbh->do(q| +$dbh->do( + q| INSERT INTO message_transport_types( message_transport_type ) VALUES ('email'), ('phone'), ('print'), ('sms') -|); +| +); $mtts = C4::Letters::GetMessageTransportTypes(); -is_deeply( $mtts, ['email', 'phone', 'print', 'sms'], 'GetMessageTransportTypes returns all values' ); - +is_deeply( $mtts, [ 'email', 'phone', 'print', 'sms' ], 'GetMessageTransportTypes returns all values' ); # EnqueueLetter is( C4::Letters::EnqueueLetter(), undef, 'EnqueueLetter without argument returns undef' ); @@ -137,29 +143,33 @@ is( $message_id, undef, 'EnqueueLetter without the message type argument argumen $my_message->{message_transport_type} = 'sms'; $message_id = C4::Letters::EnqueueLetter($my_message); -ok(defined $message_id && $message_id > 0, 'new message successfully queued'); - +ok( defined $message_id && $message_id > 0, 'new message successfully queued' ); # GetQueuedMessages my $messages = C4::Letters::GetQueuedMessages(); is( @$messages, 1, 'GetQueuedMessages without argument returns all the entries' ); -$messages = C4::Letters::GetQueuedMessages({ borrowernumber => $borrowernumber }); -is( @$messages, 1, 'one message stored for the borrower' ); -is( $messages->[0]->{message_id}, $message_id, 'EnqueueLetter returns the message id correctly' ); +$messages = C4::Letters::GetQueuedMessages( { borrowernumber => $borrowernumber } ); +is( @$messages, 1, 'one message stored for the borrower' ); +is( $messages->[0]->{message_id}, $message_id, 'EnqueueLetter returns the message id correctly' ); is( $messages->[0]->{borrowernumber}, $borrowernumber, 'EnqueueLetter stores the borrower number correctly' ); -is( $messages->[0]->{subject}, $my_message->{letter}->{title}, 'EnqueueLetter stores the subject correctly' ); -is( $messages->[0]->{content}, $my_message->{letter}->{content}, 'EnqueueLetter stores the content correctly' ); -is( $messages->[0]->{message_transport_type}, $my_message->{message_transport_type}, 'EnqueueLetter stores the message type correctly' ); +is( $messages->[0]->{subject}, $my_message->{letter}->{title}, 'EnqueueLetter stores the subject correctly' ); +is( $messages->[0]->{content}, $my_message->{letter}->{content}, 'EnqueueLetter stores the content correctly' ); +is( + $messages->[0]->{message_transport_type}, $my_message->{message_transport_type}, + 'EnqueueLetter stores the message type correctly' +); is( $messages->[0]->{status}, 'pending', 'EnqueueLetter stores the status pending correctly' ); isnt( $messages->[0]->{time_queued}, undef, 'Time queued inserted by default in message_queue table' ); -is( $messages->[0]->{updated_on}, $messages->[0]->{time_queued}, 'Time status changed equals time queued when created in message_queue table' ); -is( $messages->[0]->{failure_code}, '', 'Failure code for successful message correctly empty'); +is( + $messages->[0]->{updated_on}, $messages->[0]->{time_queued}, + 'Time status changed equals time queued when created in message_queue table' +); +is( $messages->[0]->{failure_code}, '', 'Failure code for successful message correctly empty' ); # Setting time_queued to something else than now my $yesterday = dt_from_string->subtract( days => 1 ); -Koha::Notice::Messages->find($messages->[0]->{message_id})->time_queued($yesterday)->store; - +Koha::Notice::Messages->find( $messages->[0]->{message_id} )->time_queued($yesterday)->store; # EnqueueLetter - Test characters limitation for SMS $my_message->{letter}->{content} = "a" x 2000; @@ -193,11 +203,11 @@ throws_ok { } 'Koha::Exceptions::BadParameter', 'Empty string message_id throws an exception'; -my $messages_processed = C4::Letters::SendQueuedMessages( { type => 'email' }); -is($messages_processed, 0, 'No queued messages processed if type limit passed with unused type'); -$messages_processed = C4::Letters::SendQueuedMessages( { type => 'sms' }); -is($messages_processed, 0, 'All queued messages processed, nothing sent'); -$messages = C4::Letters::GetQueuedMessages({ borrowernumber => $borrowernumber }); +my $messages_processed = C4::Letters::SendQueuedMessages( { type => 'email' } ); +is( $messages_processed, 0, 'No queued messages processed if type limit passed with unused type' ); +$messages_processed = C4::Letters::SendQueuedMessages( { type => 'sms' } ); +is( $messages_processed, 0, 'All queued messages processed, nothing sent' ); +$messages = C4::Letters::GetQueuedMessages( { borrowernumber => $borrowernumber } ); is( $messages->[0]->{status}, 'failed', @@ -208,15 +218,18 @@ is( 'MISSING_SMS', 'Correct failure code set for borrower with no smsalertnumber set' ); -isnt($messages->[0]->{updated_on}, $messages->[0]->{time_queued}, 'Time status changed differs from time queued when status changes' ); -is(dt_from_string($messages->[0]->{time_queued}), $yesterday, 'Time queued remaines inmutable' ); +isnt( + $messages->[0]->{updated_on}, $messages->[0]->{time_queued}, + 'Time status changed differs from time queued when status changes' +); +is( dt_from_string( $messages->[0]->{time_queued} ), $yesterday, 'Time queued remaines inmutable' ); # ResendMessage -my $resent = C4::Letters::ResendMessage($messages->[0]->{message_id}); -$message = C4::Letters::GetMessage( $messages->[0]->{message_id}); -is( $resent, 1, 'The message should have been resent' ); -is($message->{status},'pending', 'ResendMessage sets status to pending correctly (bug 12426)'); -$resent = C4::Letters::ResendMessage($messages->[0]->{message_id}); +my $resent = C4::Letters::ResendMessage( $messages->[0]->{message_id} ); +$message = C4::Letters::GetMessage( $messages->[0]->{message_id} ); +is( $resent, 1, 'The message should have been resent' ); +is( $message->{status}, 'pending', 'ResendMessage sets status to pending correctly (bug 12426)' ); +$resent = C4::Letters::ResendMessage( $messages->[0]->{message_id} ); is( $resent, 0, 'The message should not have been resent again' ); $resent = C4::Letters::ResendMessage(); is( $resent, undef, 'ResendMessage should return undef if not message_id given' ); @@ -228,7 +241,7 @@ is( $messages->[0]->{failure_code}, 'MISSING_SMS', 'Failure code set correctly f my $letters = C4::Letters::GetLetters(); is( @$letters, 0, 'GetLetters returns the correct number of letters' ); -my $title = q|<<branches.branchname>> - <<status>>|; +my $title = q|<<branches.branchname>> - <<status>>|; my $content = q{Dear <<borrowers.firstname>> <<borrowers.surname>>, According to our current records, you have items that are overdue.Your library does not charge late fines, but please return or renew them at the branch below as soon as possible. @@ -245,12 +258,15 @@ Don't forget your date of birth: <<borrowers.dateofbirth>>. Look at this wonderful biblio timestamp: <<biblio.timestamp>>. }; -$dbh->do( q|INSERT INTO letter(branchcode,module,code,name,is_html,title,content,message_transport_type) VALUES (?,'my module','my code','my name',1,?,?,'email')|, undef, $library->{branchcode}, $title, $content ); +$dbh->do( + q|INSERT INTO letter(branchcode,module,code,name,is_html,title,content,message_transport_type) VALUES (?,'my module','my code','my name',1,?,?,'email')|, + undef, $library->{branchcode}, $title, $content +); $letters = C4::Letters::GetLetters(); -is( @$letters, 1, 'GetLetters returns the correct number of letters' ); +is( @$letters, 1, 'GetLetters returns the correct number of letters' ); is( $letters->[0]->{module}, 'my module', 'GetLetters gets the module correctly' ); -is( $letters->[0]->{code}, 'my code', 'GetLetters gets the code correctly' ); -is( $letters->[0]->{name}, 'my name', 'GetLetters gets the name correctly' ); +is( $letters->[0]->{code}, 'my code', 'GetLetters gets the code correctly' ); +is( $letters->[0]->{name}, 'my name', 'GetLetters gets the name correctly' ); my $data_1 = { module => 'blah', code => 'ISBN', name => 'book' }; my $data_2 = { module => 'blah', code => 'ISSN' }; @@ -264,17 +280,20 @@ my ($ISBN_letter) = grep { $_->{code} eq 'ISBN' } @$letters; is( $ISBN_letter->{name}, 'book', 'letter name for "ISBN" letter is book' ); # GetPreparedLetter -t::lib::Mocks::mock_preference('OPACBaseURL', 'http://thisisatest.com'); +t::lib::Mocks::mock_preference( 'OPACBaseURL', 'http://thisisatest.com' ); t::lib::Mocks::mock_preference( 'SendAllEmailsTo', '' ); -t::lib::Mocks::mock_preference( 'ReplytoDefault', q{} ); +t::lib::Mocks::mock_preference( 'ReplytoDefault', q{} ); my $sms_content = 'This is a SMS for an <<status>>'; -$dbh->do( q|INSERT INTO letter(branchcode,module,code,name,is_html,title,content,message_transport_type) VALUES (?,'my module','my code','my name',1,'my title',?,'sms')|, undef, $library->{branchcode}, $sms_content ); +$dbh->do( + q|INSERT INTO letter(branchcode,module,code,name,is_html,title,content,message_transport_type) VALUES (?,'my module','my code','my name',1,'my title',?,'sms')|, + undef, $library->{branchcode}, $sms_content +); my $tables = { borrowers => $borrowernumber, - branches => $library->{branchcode}, - biblio => $biblionumber, + branches => $library->{branchcode}, + biblio => $biblionumber, }; my $substitute = { status => 'overdue', @@ -289,22 +308,24 @@ my $repeat = [ barcode => '5678', }, ]; -my $prepared_letter = GetPreparedLetter(( - module => 'my module', - branchcode => $library->{branchcode}, - letter_code => 'my code', - tables => $tables, - substitute => $substitute, - repeat => $repeat, -)); -my $retrieved_library = Koha::Libraries->find($library->{branchcode}); -my $my_title_letter = $retrieved_library->branchname . qq| - $substitute->{status}|; -my $biblio_timestamp = dt_from_string( GetBiblioData($biblionumber)->{timestamp} ); +my $prepared_letter = GetPreparedLetter( + ( + module => 'my module', + branchcode => $library->{branchcode}, + letter_code => 'my code', + tables => $tables, + substitute => $substitute, + repeat => $repeat, + ) +); +my $retrieved_library = Koha::Libraries->find( $library->{branchcode} ); +my $my_title_letter = $retrieved_library->branchname . qq| - $substitute->{status}|; +my $biblio_timestamp = dt_from_string( GetBiblioData($biblionumber)->{timestamp} ); my $my_content_letter = qq|Dear Jane Smith, According to our current records, you have items that are overdue.Your library does not charge late fines, but please return or renew them at the branch below as soon as possible. -|.$retrieved_library->branchname.qq| -|.$retrieved_library->branchaddress1.qq| +| . $retrieved_library->branchname . qq| +| . $retrieved_library->branchaddress1 . qq| URL: http://thisisatest.com The following item(s) is/are currently $substitute->{status}: @@ -313,87 +334,120 @@ The following item(s) is/are currently $substitute->{status}: <item> 2. $repeat->[1]->{itemcallnumber}, Barcode: $repeat->[1]->{barcode} </item> Thank-you for your prompt attention to this matter. -Don't forget your date of birth: | . output_pref({ dt => $date, dateonly => 1 }) . q|. -Look at this wonderful biblio timestamp: | . output_pref({ dt => $biblio_timestamp }) . ".\n"; +Don't forget your date of birth: | . output_pref( { dt => $date, dateonly => 1 } ) . q|. +Look at this wonderful biblio timestamp: | . output_pref( { dt => $biblio_timestamp } ) . ".\n"; -is( $prepared_letter->{title}, $my_title_letter, 'GetPreparedLetter returns the title correctly' ); +is( $prepared_letter->{title}, $my_title_letter, 'GetPreparedLetter returns the title correctly' ); is( $prepared_letter->{content}, $my_content_letter, 'GetPreparedLetter returns the content correctly' ); -$prepared_letter = GetPreparedLetter(( - module => 'my module', - branchcode => $library->{branchcode}, - letter_code => 'my code', - tables => $tables, - substitute => $substitute, - repeat => $repeat, - message_transport_type => 'sms', -)); -$my_content_letter = qq|This is a SMS for an $substitute->{status}|; -is( $prepared_letter->{content}, $my_content_letter, 'GetPreparedLetter returns the content correctly' ); - -warning_is { - $prepared_letter = GetPreparedLetter(( +$prepared_letter = GetPreparedLetter( + ( module => 'my module', branchcode => $library->{branchcode}, letter_code => 'my code', tables => $tables, - substitute => { status => undef }, + substitute => $substitute, repeat => $repeat, message_transport_type => 'sms', - )); + ) +); +$my_content_letter = qq|This is a SMS for an $substitute->{status}|; +is( $prepared_letter->{content}, $my_content_letter, 'GetPreparedLetter returns the content correctly' ); + +warning_is { + $prepared_letter = GetPreparedLetter( + ( + module => 'my module', + branchcode => $library->{branchcode}, + letter_code => 'my code', + tables => $tables, + substitute => { status => undef }, + repeat => $repeat, + message_transport_type => 'sms', + ) + ); } undef, "No warning if GetPreparedLetter called with substitute containing undefined value"; -is( $prepared_letter->{content}, q|This is a SMS for an |, 'GetPreparedLetter returns the content correctly when substitute contains undefined value' ); +is( + $prepared_letter->{content}, q|This is a SMS for an |, + 'GetPreparedLetter returns the content correctly when substitute contains undefined value' +); -$dbh->do(q{INSERT INTO letter (module, code, name, title, content) VALUES ('test_date','TEST_DATE','Test dates','A title with a timestamp: <<biblio.timestamp>>','This one only contains the date: <<biblio.timestamp | dateonly>>.');}); -$prepared_letter = GetPreparedLetter(( - module => 'test_date', - branchcode => '', - letter_code => 'test_date', - tables => $tables, - substitute => $substitute, - repeat => $repeat, -)); -is( $prepared_letter->{content}, q|This one only contains the date: | . output_pref({ dt => $date, dateonly => 1 }) . q|.|, 'dateonly test 1' ); +$dbh->do( + q{INSERT INTO letter (module, code, name, title, content) VALUES ('test_date','TEST_DATE','Test dates','A title with a timestamp: <<biblio.timestamp>>','This one only contains the date: <<biblio.timestamp | dateonly>>.');} +); +$prepared_letter = GetPreparedLetter( + ( + module => 'test_date', + branchcode => '', + letter_code => 'test_date', + tables => $tables, + substitute => $substitute, + repeat => $repeat, + ) +); +is( + $prepared_letter->{content}, + q|This one only contains the date: | . output_pref( { dt => $date, dateonly => 1 } ) . q|.|, 'dateonly test 1' +); $dbh->do(q{UPDATE letter SET content = 'And also this one:<<timestamp | dateonly>>.' WHERE code = 'test_date';}); -$prepared_letter = GetPreparedLetter(( - module => 'test_date', - branchcode => '', - letter_code => 'test_date', - tables => $tables, - substitute => $substitute, - repeat => $repeat, -)); -is( $prepared_letter->{content}, q|And also this one:| . output_pref({ dt => $date, dateonly => 1 }) . q|.|, 'dateonly test 2' ); +$prepared_letter = GetPreparedLetter( + ( + module => 'test_date', + branchcode => '', + letter_code => 'test_date', + tables => $tables, + substitute => $substitute, + repeat => $repeat, + ) +); +is( + $prepared_letter->{content}, q|And also this one:| . output_pref( { dt => $date, dateonly => 1 } ) . q|.|, + 'dateonly test 2' +); $dbh->do(q{UPDATE letter SET content = 'And also this one:<<timestamp|dateonly >>.' WHERE code = 'test_date';}); -$prepared_letter = GetPreparedLetter(( - module => 'test_date', - branchcode => '', - letter_code => 'test_date', - tables => $tables, - substitute => $substitute, - repeat => $repeat, -)); -is( $prepared_letter->{content}, q|And also this one:| . output_pref({ dt => $date, dateonly => 1 }) . q|.|, 'dateonly test 3' ); +$prepared_letter = GetPreparedLetter( + ( + module => 'test_date', + branchcode => '', + letter_code => 'test_date', + tables => $tables, + substitute => $substitute, + repeat => $repeat, + ) +); +is( + $prepared_letter->{content}, q|And also this one:| . output_pref( { dt => $date, dateonly => 1 } ) . q|.|, + 'dateonly test 3' +); t::lib::Mocks::mock_preference( 'TimeFormat', '12hr' ); my $yesterday_night = $date->clone->add( days => -1 )->set_hour(22); -$dbh->do(q|UPDATE biblio SET timestamp = ? WHERE biblionumber = ?|, undef, $yesterday_night, $biblionumber ); +$dbh->do( q|UPDATE biblio SET timestamp = ? WHERE biblionumber = ?|, undef, $yesterday_night, $biblionumber ); $dbh->do(q{UPDATE letter SET content = 'And also this one:<<timestamp>>.' WHERE code = 'test_date';}); -$prepared_letter = GetPreparedLetter(( - module => 'test_date', - branchcode => '', - letter_code => 'test_date', - tables => $tables, - substitute => $substitute, - repeat => $repeat, -)); -is( $prepared_letter->{content}, q|And also this one:| . output_pref({ dt => $yesterday_night }) . q|.|, 'dateonly test 3' ); +$prepared_letter = GetPreparedLetter( + ( + module => 'test_date', + branchcode => '', + letter_code => 'test_date', + tables => $tables, + substitute => $substitute, + repeat => $repeat, + ) +); +is( + $prepared_letter->{content}, q|And also this one:| . output_pref( { dt => $yesterday_night } ) . q|.|, + 'dateonly test 3' +); -$dbh->do(q{INSERT INTO letter (module, code, name, title, content) VALUES ('claimacquisition','TESTACQCLAIM','Acquisition Claim','Item Not Received','<<aqbooksellers.name>>|<<aqcontacts.name>>|<order>Ordernumber <<aqorders.ordernumber>> (<<biblio.title>>) (<<aqorders.quantity>> ordered)</order>');}); -$dbh->do(q{INSERT INTO letter (module, code, name, title, content) VALUES ('orderacquisition','TESTACQORDER','Acquisition Order','Order','<<aqbooksellers.name>>|<<aqcontacts.name>>|<order>Ordernumber <<aqorders.ordernumber>> (<<biblio.title>>) (<<aqorders.quantity>> ordered)</order> Basket name: [% basket.basketname %]');}); +$dbh->do( + q{INSERT INTO letter (module, code, name, title, content) VALUES ('claimacquisition','TESTACQCLAIM','Acquisition Claim','Item Not Received','<<aqbooksellers.name>>|<<aqcontacts.name>>|<order>Ordernumber <<aqorders.ordernumber>> (<<biblio.title>>) (<<aqorders.quantity>> ordered)</order>');} +); +$dbh->do( + q{INSERT INTO letter (module, code, name, title, content) VALUES ('orderacquisition','TESTACQORDER','Acquisition Order','Order','<<aqbooksellers.name>>|<<aqcontacts.name>>|<order>Ordernumber <<aqorders.ordernumber>> (<<biblio.title>>) (<<aqorders.quantity>> ordered)</order> Basket name: [% basket.basketname %]');} +); my $testacqorder2_content = <<EOF; [%- USE Price -%] @@ -403,38 +457,46 @@ Ordernumber [% order.ordernumber %] [% order.quantity %] [% order.listprice | \$ [% END %] EOF -$dbh->do("INSERT INTO letter (module, code, name, title, content) VALUES ('orderacquisition','TESTACQORDER2','Acquisition Order','Order','$testacqorder2_content');"); +$dbh->do( + "INSERT INTO letter (module, code, name, title, content) VALUES ('orderacquisition','TESTACQORDER2','Acquisition Order','Order','$testacqorder2_content');" +); -my $popito = $builder->build({ - source => 'Aqbookseller', - value => { name => 'Popito' } -}); - -my $order_1 = $builder->build({ - source => 'Aqorder', - value => { - quantity => 2, - listprice => '12.00' +my $popito = $builder->build( + { + source => 'Aqbookseller', + value => { name => 'Popito' } } -}); +); -my $order_2 = $builder->build({ - source => 'Aqorder', - value => { - quantity => 1, - listprice => '23.50' +my $order_1 = $builder->build( + { + source => 'Aqorder', + value => { + quantity => 2, + listprice => '12.00' + } } -}); +); -$prepared_letter = GetPreparedLetter(( - module => 'orderacquisition', - branchcode => '', - letter_code => 'TESTACQORDER2', - tables => { 'aqbooksellers' => $popito->{id} }, - loops => { - aqorders => [ $order_1->{ordernumber}, $order_2->{ordernumber} ] +my $order_2 = $builder->build( + { + source => 'Aqorder', + value => { + quantity => 1, + listprice => '23.50' + } } -)); +); + +$prepared_letter = GetPreparedLetter( + ( + module => 'orderacquisition', + branchcode => '', + letter_code => 'TESTACQORDER2', + tables => { 'aqbooksellers' => $popito->{id} }, + loops => { aqorders => [ $order_1->{ordernumber}, $order_2->{ordernumber} ] } + ) +); my $testacqorder2_expected = qq|Popito @@ -444,12 +506,12 @@ Ordernumber | . $order_2->{ordernumber} . qq| 1 23.50 |; -is($prepared_letter->{content}, $testacqorder2_expected); +is( $prepared_letter->{content}, $testacqorder2_expected ); # Test that _parseletter doesn't modify its parameters bug 15429 { my $values = { dateexpiry => '2015-12-13', }; - C4::Letters::_parseletter($prepared_letter, 'borrowers', $values); + C4::Letters::_parseletter( $prepared_letter, 'borrowers', $values ); is( $values->{dateexpiry}, '2015-12-13', "_parseletter doesn't modify its parameters" ); } @@ -457,31 +519,37 @@ is($prepared_letter->{content}, $testacqorder2_expected); { my $values = { dateexpiry => '2015-12-13', }; - t::lib::Mocks::mock_preference('dateformat', 'metric'); - t::lib::Mocks::mock_preference('timeformat', '24hr'); - my $letter = C4::Letters::_parseletter({ content => "expiry on <<borrowers.dateexpiry>>"}, 'borrowers', $values); + t::lib::Mocks::mock_preference( 'dateformat', 'metric' ); + t::lib::Mocks::mock_preference( 'timeformat', '24hr' ); + my $letter = C4::Letters::_parseletter( { content => "expiry on <<borrowers.dateexpiry>>" }, 'borrowers', $values ); is( $letter->{content}, 'expiry on 13/12/2015' ); - t::lib::Mocks::mock_preference('dateformat', 'metric'); - t::lib::Mocks::mock_preference('timeformat', '12hr'); - $letter = C4::Letters::_parseletter({ content => "expiry on <<borrowers.dateexpiry>>"}, 'borrowers', $values); + t::lib::Mocks::mock_preference( 'dateformat', 'metric' ); + t::lib::Mocks::mock_preference( 'timeformat', '12hr' ); + $letter = C4::Letters::_parseletter( { content => "expiry on <<borrowers.dateexpiry>>" }, 'borrowers', $values ); is( $letter->{content}, 'expiry on 13/12/2015' ); } my $bookseller = Koha::Acquisition::Bookseller->new( { - name => "my vendor", - address1 => "bookseller's address", - phone => "0123456", - active => 1, + name => "my vendor", + address1 => "bookseller's address", + phone => "0123456", + active => 1, deliverytime => 5, } )->store; my $booksellerid = $bookseller->id; -Koha::Acquisition::Bookseller::Contact->new( { name => 'John Smith', phone => '0123456x1', claimacquisition => 1, orderacquisition => 1, booksellerid => $booksellerid } )->store; -Koha::Acquisition::Bookseller::Contact->new( { name => 'Leo Tolstoy', phone => '0123456x2', claimissues => 1, booksellerid => $booksellerid } )->store; -my $basketno = NewBasket($booksellerid, 1, 'The basket name'); +Koha::Acquisition::Bookseller::Contact->new( + { + name => 'John Smith', phone => '0123456x1', claimacquisition => 1, orderacquisition => 1, + booksellerid => $booksellerid + } +)->store; +Koha::Acquisition::Bookseller::Contact->new( + { name => 'Leo Tolstoy', phone => '0123456x2', claimissues => 1, booksellerid => $booksellerid } )->store; +my $basketno = NewBasket( $booksellerid, 1, 'The basket name' ); my $budget_period_id = C4::Budgets::AddBudgetPeriod( { @@ -501,13 +569,13 @@ my $budgetid = C4::Budgets::AddBudget( ); my $bib = MARC::Record->new(); -if (C4::Context->preference('marcflavour') eq 'UNIMARC') { +if ( C4::Context->preference('marcflavour') eq 'UNIMARC' ) { $bib->append_fields( - MARC::Field->new('200', ' ', ' ', a => 'Silence in the library'), + MARC::Field->new( '200', ' ', ' ', a => 'Silence in the library' ), ); } else { $bib->append_fields( - MARC::Field->new('245', ' ', ' ', a => 'Silence in the library'), + MARC::Field->new( '245', ' ', ' ', a => 'Silence in the library' ), ); } @@ -521,28 +589,29 @@ my $logged_in_user = $builder->build_object( } ); -t::lib::Mocks::mock_userenv({ patron => $logged_in_user }); +t::lib::Mocks::mock_userenv( { patron => $logged_in_user } ); -($biblionumber, $biblioitemnumber) = AddBiblio($bib, ''); +( $biblionumber, $biblioitemnumber ) = AddBiblio( $bib, '' ); my $order = Koha::Acquisition::Order->new( { - basketno => $basketno, - quantity => 1, + basketno => $basketno, + quantity => 1, biblionumber => $biblionumber, - budget_id => $budgetid, + budget_id => $budgetid, } )->store; my $ordernumber = $order->ordernumber; -Koha::Acquisition::Baskets->find( $basketno )->close; +Koha::Acquisition::Baskets->find($basketno)->close; my $err; warning_like { - $err = SendAlerts( 'claimacquisition', [ $ordernumber ], 'TESTACQCLAIM' ) } - qr/^Bookseller .* without emails at/, + $err = SendAlerts( 'claimacquisition', [$ordernumber], 'TESTACQCLAIM' ) +} +qr/^Bookseller .* without emails at/, "SendAlerts prints a warning"; -is($err->{'error'}, 'no_email', "Trying to send an alert when there's no e-mail results in an error"); +is( $err->{'error'}, 'no_email', "Trying to send an alert when there's no e-mail results in an error" ); -$bookseller = Koha::Acquisition::Booksellers->find( $booksellerid ); +$bookseller = Koha::Acquisition::Booksellers->find($booksellerid); $bookseller->contacts->next->email('testemail@mydomain.com')->store; # Ensure that the preference 'ClaimsLog' is set to logging @@ -612,94 +681,119 @@ t::lib::Mocks::mock_preference( 'KohaAdminEmailAddress', 'library@domain.com' ); } { -warning_like { - $err = SendAlerts( 'claimacquisition', [ $ordernumber ], 'TESTACQCLAIM' ) } + warning_like { + $err = SendAlerts( 'claimacquisition', [$ordernumber], 'TESTACQCLAIM' ) + } qr|Fake send_or_die|, - "SendAlerts is using the mocked send_or_die routine"; + "SendAlerts is using the mocked send_or_die routine"; -is($err, 1, "Successfully sent claim"); -is($email_object->email->header('To'), 'testemail@mydomain.com', "mailto correct in sent claim"); -is($email_object->email->body, 'my vendor|John Smith|Ordernumber ' . $ordernumber . ' (Silence in the library) (1 ordered)', 'Claim notice text constructed successfully'); + is( $err, 1, "Successfully sent claim" ); + is( $email_object->email->header('To'), 'testemail@mydomain.com', "mailto correct in sent claim" ); + is( + $email_object->email->body, + 'my vendor|John Smith|Ordernumber ' . $ordernumber . ' (Silence in the library) (1 ordered)', + 'Claim notice text constructed successfully' + ); -my $mocked_koha_email = Test::MockModule->new('Koha::Email'); -$mocked_koha_email->mock( 'send_or_die', sub { - Email::Sender::Failure->throw('something went wrong'); -}); + my $mocked_koha_email = Test::MockModule->new('Koha::Email'); + $mocked_koha_email->mock( + 'send_or_die', + sub { + Email::Sender::Failure->throw('something went wrong'); + } + ); -warning_like { - $err = SendAlerts( 'claimacquisition', [ $ordernumber ] , 'TESTACQCLAIM' ); } + warning_like { + $err = SendAlerts( 'claimacquisition', [$ordernumber], 'TESTACQCLAIM' ); + } qr{something went wrong}, - 'Warning is printed'; + 'Warning is printed'; -is($err->{error}, 'something went wrong', "Send exception, error message returned"); + is( $err->{error}, 'something went wrong', "Send exception, error message returned" ); } { -use C4::Serials qw( NewSubscription GetSerials findSerialsByStatus ModSerialStatus ); + use C4::Serials qw( NewSubscription GetSerials findSerialsByStatus ModSerialStatus ); -my $notes = 'notes'; -my $internalnotes = 'intnotes'; -my $number_pattern = $builder->build_object( - { - class => 'Koha::Subscription::Numberpatterns', - value => { numberingmethod => 'No. {X}' } + my $notes = 'notes'; + my $internalnotes = 'intnotes'; + my $number_pattern = $builder->build_object( + { + class => 'Koha::Subscription::Numberpatterns', + value => { numberingmethod => 'No. {X}' } + } + ); + my $subscriptionid = NewSubscription( + undef, "", undef, undef, undef, $biblionumber, + '2013-01-01', 1, undef, undef, undef, + undef, undef, undef, undef, undef, undef, + 1, $notes, undef, '2013-01-01', undef, $number_pattern->id, + undef, undef, 0, $internalnotes, 0, + undef, undef, 0, undef, '2013-12-31', 0 + ); + $dbh->do( + q{INSERT INTO letter (module, code, name, title, content) VALUES ('serial','RLIST','Serial issue notification','Serial issue notification','<<biblio.title>>,<<subscription.subscriptionid>>,<<serial.serialseq>>');} + ); + my ( $serials_count, @serials ) = GetSerials($subscriptionid); + my $serial = $serials[0]; + + my $patron = Koha::Patron->new( + { + firstname => 'John', + surname => 'Smith', + categorycode => $patron_category, + branchcode => $library->{branchcode}, + dateofbirth => $date, + email => 'john.smith@test.de', + } + )->store; + my $borrowernumber = $patron->borrowernumber; + my $subscription = Koha::Subscriptions->find($subscriptionid); + $subscription->add_subscriber($patron); + + t::lib::Mocks::mock_userenv( { branch => $library->{branchcode} } ); + my $err2; + warning_like { + $err2 = SendAlerts( 'issue', $serial->{serialid}, 'RLIST' ) } -); -my $subscriptionid = NewSubscription( - undef, "", undef, undef, undef, $biblionumber, - '2013-01-01', 1, undef, undef, undef, - undef, undef, undef, undef, undef, undef, - 1, $notes,undef, '2013-01-01', undef, $number_pattern->id, - undef, undef, 0, $internalnotes, 0, - undef, undef, 0, undef, '2013-12-31', 0 -); -$dbh->do(q{INSERT INTO letter (module, code, name, title, content) VALUES ('serial','RLIST','Serial issue notification','Serial issue notification','<<biblio.title>>,<<subscription.subscriptionid>>,<<serial.serialseq>>');}); -my ($serials_count, @serials) = GetSerials($subscriptionid); -my $serial = $serials[0]; - -my $patron = Koha::Patron->new({ - firstname => 'John', - surname => 'Smith', - categorycode => $patron_category, - branchcode => $library->{branchcode}, - dateofbirth => $date, - email => 'john.smith@test.de', -})->store; -my $borrowernumber = $patron->borrowernumber; -my $subscription = Koha::Subscriptions->find( $subscriptionid ); -$subscription->add_subscriber( $patron ); - -t::lib::Mocks::mock_userenv({ branch => $library->{branchcode} }); -my $err2; -warning_like { -$err2 = SendAlerts( 'issue', $serial->{serialid}, 'RLIST' ) } qr|Fake send_or_die|, - "SendAlerts is using the mocked send_or_die routine"; + "SendAlerts is using the mocked send_or_die routine"; -is($err2, 1, "Successfully sent serial notification"); -is($email_object->email->header('To'), 'john.smith@test.de', "mailto correct in sent serial notification"); -is($email_object->email->body, 'Silence in the library,'.$subscriptionid.',No. 0', 'Serial notification text constructed successfully'); + is( $err2, 1, "Successfully sent serial notification" ); + is( $email_object->email->header('To'), 'john.smith@test.de', "mailto correct in sent serial notification" ); + is( + $email_object->email->body, 'Silence in the library,' . $subscriptionid . ',No. 0', + 'Serial notification text constructed successfully' + ); -t::lib::Mocks::mock_preference( 'SendAllEmailsTo', 'robert.tables@mail.com' ); + t::lib::Mocks::mock_preference( 'SendAllEmailsTo', 'robert.tables@mail.com' ); -my $err3; -warning_like { -$err3 = SendAlerts( 'issue', $serial->{serialid}, 'RLIST' ) } + my $err3; + warning_like { + $err3 = SendAlerts( 'issue', $serial->{serialid}, 'RLIST' ) + } qr|Fake send_or_die|, - "SendAlerts is using the mocked send_or_die routine"; -is($email_object->email->header('To'), 'robert.tables@mail.com', "mailto address overwritten by SendAllMailsTo preference"); + "SendAlerts is using the mocked send_or_die routine"; + is( + $email_object->email->header('To'), 'robert.tables@mail.com', + "mailto address overwritten by SendAllMailsTo preference" + ); -my $mocked_koha_email = Test::MockModule->new('Koha::Email'); -$mocked_koha_email->mock( 'send_or_die', sub { - Email::Sender::Failure->throw('something went wrong'); -}); + my $mocked_koha_email = Test::MockModule->new('Koha::Email'); + $mocked_koha_email->mock( + 'send_or_die', + sub { + Email::Sender::Failure->throw('something went wrong'); + } + ); -warning_like { - $err = SendAlerts( 'issue', $serial->{serialid} , 'RLIST' ); } + warning_like { + $err = SendAlerts( 'issue', $serial->{serialid}, 'RLIST' ); + } qr{something went wrong}, - 'Warning is printed'; + 'Warning is printed'; -is($err->{error}, 'something went wrong', "Send exception, error message returned"); + is( $err->{error}, 'something went wrong', "Send exception, error message returned" ); } t::lib::Mocks::mock_preference( 'SendAllEmailsTo', '' ); @@ -723,34 +817,37 @@ subtest 'SendAlerts - claimissue' => sub { use C4::Serials; - $dbh->do(q{INSERT INTO letter (module, code, name, title, content) VALUES ('claimissues','TESTSERIALCLAIM','Serial claim test','Serial claim test','<<serial.serialid>>|<<subscription.startdate>>|<<biblio.title>>|<<biblioitems.issn>>');}); + $dbh->do( + q{INSERT INTO letter (module, code, name, title, content) VALUES ('claimissues','TESTSERIALCLAIM','Serial claim test','Serial claim test','<<serial.serialid>>|<<subscription.startdate>>|<<biblio.title>>|<<biblioitems.issn>>');} + ); my $bookseller = Koha::Acquisition::Bookseller->new( { - name => "my vendor", - address1 => "bookseller's address", - phone => "0123456", - active => 1, + name => "my vendor", + address1 => "bookseller's address", + phone => "0123456", + active => 1, deliverytime => 5, } )->store; my $booksellerid = $bookseller->id; - Koha::Acquisition::Bookseller::Contact->new( { name => 'Leo Tolstoy', phone => '0123456x2', claimissues => 1, booksellerid => $booksellerid } )->store; + Koha::Acquisition::Bookseller::Contact->new( + { name => 'Leo Tolstoy', phone => '0123456x2', claimissues => 1, booksellerid => $booksellerid } )->store; my $bib = MARC::Record->new(); - if (C4::Context->preference('marcflavour') eq 'UNIMARC') { + if ( C4::Context->preference('marcflavour') eq 'UNIMARC' ) { $bib->append_fields( - MARC::Field->new('011', ' ', ' ', a => 'xxxx-yyyy'), - MARC::Field->new('200', ' ', ' ', a => 'Silence in the library'), + MARC::Field->new( '011', ' ', ' ', a => 'xxxx-yyyy' ), + MARC::Field->new( '200', ' ', ' ', a => 'Silence in the library' ), ); } else { $bib->append_fields( - MARC::Field->new('022', ' ', ' ', a => 'xxxx-yyyy'), - MARC::Field->new('245', ' ', ' ', a => 'Silence in the library'), + MARC::Field->new( '022', ' ', ' ', a => 'xxxx-yyyy' ), + MARC::Field->new( '245', ' ', ' ', a => 'Silence in the library' ), ); } - my ($biblionumber) = AddBiblio($bib, ''); + my ($biblionumber) = AddBiblio( $bib, '' ); my $number_pattern = $builder->build_object( { @@ -760,101 +857,118 @@ subtest 'SendAlerts - claimissue' => sub { ); my $subscriptionid = NewSubscription( - undef, "", $booksellerid, undef, undef, $biblionumber, - '2013-01-01', 1, undef, undef, undef, - undef, undef, undef, undef, undef, undef, - 1, 'public',undef, '2013-01-01', undef, $number_pattern->id, - undef, undef, 0, 'internal', 0, - undef, undef, 0, undef, '2013-12-31', 0 + undef, "", $booksellerid, undef, undef, $biblionumber, + '2013-01-01', 1, undef, undef, undef, + undef, undef, undef, undef, undef, undef, + 1, 'public', undef, '2013-01-01', undef, $number_pattern->id, + undef, undef, 0, 'internal', 0, + undef, undef, 0, undef, '2013-12-31', 0 ); - my ($serials_count, @serials) = GetSerials($subscriptionid); - my @serialids = ($serials[0]->{serialid}); + my ( $serials_count, @serials ) = GetSerials($subscriptionid); + my @serialids = ( $serials[0]->{serialid} ); my $err; warning_like { - $err = SendAlerts( 'claimissues', \@serialids, 'TESTSERIALCLAIM' ) } - qr/^Bookseller .* without emails at/, + $err = SendAlerts( 'claimissues', \@serialids, 'TESTSERIALCLAIM' ) + } + qr/^Bookseller .* without emails at/, "Warn on vendor without email address"; - $bookseller = Koha::Acquisition::Booksellers->find( $booksellerid ); + $bookseller = Koha::Acquisition::Booksellers->find($booksellerid); $bookseller->contacts->next->email('testemail@mydomain.com')->store; # Ensure that the preference 'ClaimsLog' is set to logging t::lib::Mocks::mock_preference( 'ClaimsLog', 'on' ); # SendAlerts needs branchemail or KohaAdminEmailAddress as sender - t::lib::Mocks::mock_userenv({ branchcode => $library->{branchcode} }); + t::lib::Mocks::mock_userenv( { branchcode => $library->{branchcode} } ); t::lib::Mocks::mock_preference( 'KohaAdminEmailAddress', 'library@domain.com' ); { - warning_like { - $err = SendAlerts( 'claimissues', \@serialids , 'TESTSERIALCLAIM' ) } + warning_like { + $err = SendAlerts( 'claimissues', \@serialids, 'TESTSERIALCLAIM' ) + } qr|Fake send_or_die|, - "SendAlerts is using the mocked send_or_die routine (claimissues)"; - is( $err, 1, "Successfully sent claim" ); - is( $email_object->email->header('To'), - 'testemail@mydomain.com', "mailto correct in sent claim" ); - is( scalar $email_object->email->header('Reply-To'), undef, "reply-to is not set" ); - is( - $email_object->email->body, - "$serialids[0]|2013-01-01|Silence in the library|xxxx-yyyy", - 'Serial claim letter for 1 issue constructed successfully' - ); + "SendAlerts is using the mocked send_or_die routine (claimissues)"; + is( $err, 1, "Successfully sent claim" ); + is( + $email_object->email->header('To'), + 'testemail@mydomain.com', "mailto correct in sent claim" + ); + is( scalar $email_object->email->header('Reply-To'), undef, "reply-to is not set" ); + is( + $email_object->email->body, + "$serialids[0]|2013-01-01|Silence in the library|xxxx-yyyy", + 'Serial claim letter for 1 issue constructed successfully' + ); } t::lib::Mocks::mock_preference( 'SerialsDefaultEmailAddress', 'ser-default@domain.com' ); - t::lib::Mocks::mock_preference( 'SerialsDefaultReplyTo', 'ser-replyto@domain.com' ); + t::lib::Mocks::mock_preference( 'SerialsDefaultReplyTo', 'ser-replyto@domain.com' ); { - warning_like { - $err = SendAlerts( 'claimissues', \@serialids , 'TESTSERIALCLAIM' ) } + warning_like { + $err = SendAlerts( 'claimissues', \@serialids, 'TESTSERIALCLAIM' ) + } qr|Fake send_or_die|, - "SendAlerts is using the mocked send_or_die routine (claimissues)"; - is( $email_object->email->header('From'), - 'ser-default@domain.com', "SerialsDefaultEmailAddress is used to serial claim issue" ); - is( $email_object->email->header('Reply-To'), - 'ser-replyto@domain.com', "SerialsDefaultReplyTo is used to sent serial claim issue" ); + "SendAlerts is using the mocked send_or_die routine (claimissues)"; + is( + $email_object->email->header('From'), + 'ser-default@domain.com', "SerialsDefaultEmailAddress is used to serial claim issue" + ); + is( + $email_object->email->header('Reply-To'), + 'ser-replyto@domain.com', "SerialsDefaultReplyTo is used to sent serial claim issue" + ); - my $mocked_koha_email = Test::MockModule->new('Koha::Email'); - $mocked_koha_email->mock( 'send_or_die', sub { - Email::Sender::Failure->throw('something went wrong'); - }); + my $mocked_koha_email = Test::MockModule->new('Koha::Email'); + $mocked_koha_email->mock( + 'send_or_die', + sub { + Email::Sender::Failure->throw('something went wrong'); + } + ); - warning_like { - $err = SendAlerts( 'claimissues', \@serialids , 'TESTSERIALCLAIM' ); } + warning_like { + $err = SendAlerts( 'claimissues', \@serialids, 'TESTSERIALCLAIM' ); + } qr{something went wrong}, - 'Warning is printed'; + 'Warning is printed'; - is($err->{error}, 'something went wrong', "Send exception, error message returned"); + is( $err->{error}, 'something went wrong', "Send exception, error message returned" ); } { - my $publisheddate = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 }); - my $serialexpected = ( C4::Serials::findSerialsByStatus( 1, $subscriptionid ) )[0]; - ModSerialStatus( $serials[0]->{serialid}, "No. 1", $publisheddate, $publisheddate, $publisheddate, '3', 'a note' ); - ($serials_count, @serials) = GetSerials($subscriptionid); - push @serialids, ($serials[1]->{serialid}); + my $publisheddate = output_pref( { dt => dt_from_string, dateformat => 'iso', dateonly => 1 } ); + my $serialexpected = ( C4::Serials::findSerialsByStatus( 1, $subscriptionid ) )[0]; + ModSerialStatus( + $serials[0]->{serialid}, "No. 1", $publisheddate, $publisheddate, $publisheddate, '3', + 'a note' + ); + ( $serials_count, @serials ) = GetSerials($subscriptionid); + push @serialids, ( $serials[1]->{serialid} ); - warning_like { $err = SendAlerts( 'claimissues', \@serialids, 'TESTSERIALCLAIM' ); } + warning_like { $err = SendAlerts( 'claimissues', \@serialids, 'TESTSERIALCLAIM' ); } qr|Fake send_or_die|, - "SendAlerts is using the mocked send_or_die routine (claimissues)"; + "SendAlerts is using the mocked send_or_die routine (claimissues)"; - is( - $email_object->email->body, - "$serialids[0]|2013-01-01|Silence in the library|xxxx-yyyy" - . $email_object->email->crlf - . "$serialids[1]|2013-01-01|Silence in the library|xxxx-yyyy", - "Serial claim letter for 2 issues constructed successfully" - ); + is( + $email_object->email->body, + "$serialids[0]|2013-01-01|Silence in the library|xxxx-yyyy" + . $email_object->email->crlf + . "$serialids[1]|2013-01-01|Silence in the library|xxxx-yyyy", + "Serial claim letter for 2 issues constructed successfully" + ); - $dbh->do(q{DELETE FROM letter WHERE code = 'TESTSERIALCLAIM';}); - warning_like { - $err = SendAlerts( 'orderacquisition', $basketno , 'TESTSERIALCLAIM' ) } + $dbh->do(q{DELETE FROM letter WHERE code = 'TESTSERIALCLAIM';}); + warning_like { + $err = SendAlerts( 'orderacquisition', $basketno, 'TESTSERIALCLAIM' ) + } qr/No orderacquisition TESTSERIALCLAIM letter transported by email/, - "GetPreparedLetter warns about missing notice template"; - is($err->{'error'}, 'no_letter', "No TESTSERIALCLAIM letter was defined"); + "GetPreparedLetter warns about missing notice template"; + is( $err->{'error'}, 'no_letter', "No TESTSERIALCLAIM letter was defined" ); } }; @@ -878,9 +992,10 @@ subtest 'GetPreparedLetter' => sub { ); } qr{^ERROR: nothing to substitute}, -'GetPreparedLetter should warn if tables, substiture and repeat are not set'; - is( $letter, undef, -'No letter should be returned by GetPreparedLetter if something went wrong' + 'GetPreparedLetter should warn if tables, substiture and repeat are not set'; + is( + $letter, undef, + 'No letter should be returned by GetPreparedLetter if something went wrong' ); warning_like { @@ -891,9 +1006,10 @@ subtest 'GetPreparedLetter' => sub { ); } qr{^ERROR: nothing to substitute}, -'GetPreparedLetter should warn if tables, substiture and repeat are not set, even if the key is passed'; - is( $letter, undef, -'No letter should be returned by GetPreparedLetter if something went wrong' + 'GetPreparedLetter should warn if tables, substiture and repeat are not set, even if the key is passed'; + is( + $letter, undef, + 'No letter should be returned by GetPreparedLetter if something went wrong' ); }; @@ -1025,11 +1141,12 @@ subtest 'Test SMS handling in SendQueuedMessages' => sub { plan tests => 14; - t::lib::Mocks::mock_preference( 'SMSSendDriver', 'Email' ); - t::lib::Mocks::mock_preference('EmailSMSSendDriverFromAddress', ''); + t::lib::Mocks::mock_preference( 'SMSSendDriver', 'Email' ); + t::lib::Mocks::mock_preference( 'EmailSMSSendDriverFromAddress', '' ); my $patron = Koha::Patrons->find($borrowernumber); - $dbh->do(q| + $dbh->do( + q| INSERT INTO message_queue(borrowernumber, subject, content, message_transport_type, status, letter_code) VALUES (?, 'subject', 'content', 'sms', 'pending', 'just_a_code') |, undef, $borrowernumber @@ -1037,12 +1154,13 @@ subtest 'Test SMS handling in SendQueuedMessages' => sub { eval { C4::Letters::SendQueuedMessages(); }; is( $@, '', 'SendQueuedMessages should not explode if the patron does not have a sms provider set' ); - my $sms_pro = $builder->build_object({ class => 'Koha::SMS::Providers', value => { domain => 'kidclamp.rocks' } }); + my $sms_pro = + $builder->build_object( { class => 'Koha::SMS::Providers', value => { domain => 'kidclamp.rocks' } } ); $patron->set( { smsalertnumber => '5555555555', sms_provider_id => $sms_pro->id() } )->store; - $message_id = C4::Letters::EnqueueLetter($my_message); #using datas set around line 95 and forward + $message_id = C4::Letters::EnqueueLetter($my_message); #using datas set around line 95 and forward warning_like { C4::Letters::SendQueuedMessages(); } - qr|Fake send_or_die|, + qr|Fake send_or_die|, "SendAlerts is using the mocked send_or_die routine (claimissues)"; $message = $schema->resultset('MessageQueue')->search( @@ -1053,26 +1171,32 @@ subtest 'Test SMS handling in SendQueuedMessages' => sub { )->next(); is( $message->letter_id, $messages->[0]->{id}, "Message letter_id is set correctly" ); - is( $message->to_address(), '5555555555@kidclamp.rocks', 'SendQueuedMessages populates the to address correctly for SMS by email when to_address not set' ); + is( + $message->to_address(), '5555555555@kidclamp.rocks', + 'SendQueuedMessages populates the to address correctly for SMS by email when to_address not set' + ); is( $message->from_address(), 'from@example.com', 'SendQueuedMessages uses message queue item \"from address\" for SMS by email when EmailSMSSendDriverFromAddress system preference is not set' ); - $schema->resultset('MessageQueue')->search({borrowernumber => $borrowernumber, status => 'sent'})->delete(); #clear borrower queue + $schema->resultset('MessageQueue')->search( { borrowernumber => $borrowernumber, status => 'sent' } )->delete() + ; #clear borrower queue - t::lib::Mocks::mock_preference('EmailSMSSendDriverFromAddress', 'override@example.com'); + t::lib::Mocks::mock_preference( 'EmailSMSSendDriverFromAddress', 'override@example.com' ); $message_id = C4::Letters::EnqueueLetter($my_message); warning_like { C4::Letters::SendQueuedMessages(); } - qr|Fake send_or_die|, + qr|Fake send_or_die|, "SendAlerts is using the mocked send_or_die routine (claimissues)"; - $message = $schema->resultset('MessageQueue')->search({ - borrowernumber => $borrowernumber, - status => 'sent' - })->next(); + $message = $schema->resultset('MessageQueue')->search( + { + borrowernumber => $borrowernumber, + status => 'sent' + } + )->next(); is( $message->from_address(), @@ -1080,40 +1204,55 @@ subtest 'Test SMS handling in SendQueuedMessages' => sub { 'SendQueuedMessages uses EmailSMSSendDriverFromAddress value for SMS by email when EmailSMSSendDriverFromAddress is set' ); - $schema->resultset('MessageQueue')->search({borrowernumber => $borrowernumber,status => 'sent'})->delete(); #clear borrower queue + $schema->resultset('MessageQueue')->search( { borrowernumber => $borrowernumber, status => 'sent' } )->delete() + ; #clear borrower queue $my_message->{to_address} = 'fixme@kidclamp.iswrong'; $message_id = C4::Letters::EnqueueLetter($my_message); - my $number_attempted = C4::Letters::SendQueuedMessages({ - borrowernumber => -1, # -1 still triggers the borrowernumber condition - letter_code => 'PASSWORD_RESET', - }); - is ( $number_attempted, 0, 'There were no password reset messages for SendQueuedMessages to attempt.' ); + my $number_attempted = C4::Letters::SendQueuedMessages( + { + borrowernumber => -1, # -1 still triggers the borrowernumber condition + letter_code => 'PASSWORD_RESET', + } + ); + is( $number_attempted, 0, 'There were no password reset messages for SendQueuedMessages to attempt.' ); warning_like { C4::Letters::SendQueuedMessages(); } - qr|Fake send_or_die|, + qr|Fake send_or_die|, "SendAlerts is using the mocked send_or_die routine (claimissues)"; - my $sms_message_address = $schema->resultset('MessageQueue')->search({ - borrowernumber => $borrowernumber, - status => 'sent' - })->next()->to_address(); - is( $sms_message_address, '5555555555@kidclamp.rocks', 'SendQueuedMessages populates the to address correctly for SMS by email when to_address is set incorrectly' ); + my $sms_message_address = $schema->resultset('MessageQueue')->search( + { + borrowernumber => $borrowernumber, + status => 'sent' + } + )->next()->to_address(); + is( + $sms_message_address, '5555555555@kidclamp.rocks', + 'SendQueuedMessages populates the to address correctly for SMS by email when to_address is set incorrectly' + ); # Test using SMS::Send::Test driver that's bundled with SMS::Send - t::lib::Mocks::mock_preference('SMSSendDriver', "AU::Test"); + t::lib::Mocks::mock_preference( 'SMSSendDriver', "AU::Test" ); - $schema->resultset('MessageQueue')->search({borrowernumber => $borrowernumber, status => 'sent'})->delete(); #clear borrower queue + $schema->resultset('MessageQueue')->search( { borrowernumber => $borrowernumber, status => 'sent' } )->delete() + ; #clear borrower queue C4::Letters::EnqueueLetter($my_message); C4::Letters::SendQueuedMessages(); - $sms_message_address = $schema->resultset('MessageQueue')->search({ - borrowernumber => $borrowernumber, - status => 'sent' - })->next()->to_address(); - is( $sms_message_address, '5555555555', 'SendQueuedMessages populates the to address correctly for SMS by SMS::Send driver to smsalertnumber when to_address is set incorrectly' ); + $sms_message_address = $schema->resultset('MessageQueue')->search( + { + borrowernumber => $borrowernumber, + status => 'sent' + } + )->next()->to_address(); + is( + $sms_message_address, '5555555555', + 'SendQueuedMessages populates the to address correctly for SMS by SMS::Send driver to smsalertnumber when to_address is set incorrectly' + ); - $schema->resultset('MessageQueue')->search({borrowernumber => $borrowernumber, status => 'sent'})->delete(); #clear borrower queue + $schema->resultset('MessageQueue')->search( { borrowernumber => $borrowernumber, status => 'sent' } )->delete() + ; #clear borrower queue }; subtest 'Test guarantor handling in SendQueuedMessages' => sub { @@ -1121,9 +1260,9 @@ subtest 'Test guarantor handling in SendQueuedMessages' => sub { plan tests => 19; t::lib::Mocks::mock_preference( 'borrowerRelationship', 'test' ); - t::lib::Mocks::mock_preference( 'ChildNeedsGuarantor', 1 ); + t::lib::Mocks::mock_preference( 'ChildNeedsGuarantor', 1 ); - my $patron = Koha::Patrons->find($borrowernumber); + my $patron = Koha::Patrons->find($borrowernumber); my $patron_category = $builder->build( { source => 'Category', value => { category_type => 'A', can_be_guarantee => 0 } } ) @@ -1216,13 +1355,15 @@ subtest 'Test guarantor handling in SendQueuedMessages' => sub { is( $message->cc_address(), - $guarantor1->email.",".$guarantor2->email, + $guarantor1->email . "," . $guarantor2->email, 'SendQueuedMessages sets cc address to both guarantor emails when patron has email defined' ); is( $email_object->email->header('To'), $patron->email, "mailto correctly uses patrons email address" ); - is( $email_object->email->header('Cc'), $guarantor1->email.", ".$guarantor2->email, "cc correctly uses both guarantors" ); - + is( + $email_object->email->header('Cc'), $guarantor1->email . ", " . $guarantor2->email, + "cc correctly uses both guarantors" + ); # reset message - testing explicit to passed to enqueue Koha::Notice::Messages->find($message_id)->delete; @@ -1248,12 +1389,15 @@ subtest 'Test guarantor handling in SendQueuedMessages' => sub { is( $message->cc_address(), - $guarantor1->email.",".$guarantor2->email, + $guarantor1->email . "," . $guarantor2->email, 'SendQueuedMessages sets cc address to both guarantor emails when "to" is already specified' ); is( $email_object->email->header('To'), 'to@example.com', "mailto correctly uses passed email" ); - is( $email_object->email->header('Cc'), $guarantor1->email.", ".$guarantor2->email, "cc correctly uses both guarantors" ); + is( + $email_object->email->header('Cc'), $guarantor1->email . ", " . $guarantor2->email, + "cc correctly uses both guarantors" + ); # clear borrower queue Koha::Notice::Messages->find($message_id)->delete; @@ -1264,36 +1408,49 @@ subtest 'Test guarantor handling in SendQueuedMessages' => sub { subtest 'get_item_content' => sub { plan tests => 2; - t::lib::Mocks::mock_preference('dateformat', 'metric'); - t::lib::Mocks::mock_preference('timeformat', '24hr'); + t::lib::Mocks::mock_preference( 'dateformat', 'metric' ); + t::lib::Mocks::mock_preference( 'timeformat', '24hr' ); my @items = ( - {date_due => '2041-01-01 12:34', title => 'a first title', barcode => 'a_first_barcode', author => 'a_first_author', itemnumber => 1 }, - {date_due => '2042-01-02 23:45', title => 'a second title', barcode => 'a_second_barcode', author => 'a_second_author', itemnumber => 2 }, + { + date_due => '2041-01-01 12:34', title => 'a first title', barcode => 'a_first_barcode', + author => 'a_first_author', itemnumber => 1 + }, + { + date_due => '2042-01-02 23:45', title => 'a second title', barcode => 'a_second_barcode', + author => 'a_second_author', itemnumber => 2 + }, ); my @item_content_fields = qw( date_due title barcode author itemnumber ); my $items_content; - for my $item ( @items ) { - $items_content .= C4::Letters::get_item_content( { item => $item, item_content_fields => \@item_content_fields } ); + for my $item (@items) { + $items_content .= + C4::Letters::get_item_content( { item => $item, item_content_fields => \@item_content_fields } ); } my $expected_items_content = <<EOF; 01/01/2041 12:34\ta first title\ta_first_barcode\ta_first_author\t1 02/01/2042 23:45\ta second title\ta_second_barcode\ta_second_author\t2 EOF - is( $items_content, $expected_items_content, 'get_item_content should return correct items info with time (default)' ); - + is( + $items_content, $expected_items_content, + 'get_item_content should return correct items info with time (default)' + ); $items_content = q||; - for my $item ( @items ) { - $items_content .= C4::Letters::get_item_content( { item => $item, item_content_fields => \@item_content_fields, dateonly => 1, } ); + for my $item (@items) { + $items_content .= C4::Letters::get_item_content( + { item => $item, item_content_fields => \@item_content_fields, dateonly => 1, } ); } $expected_items_content = <<EOF; 01/01/2041\ta first title\ta_first_barcode\ta_first_author\t1 02/01/2042\ta second title\ta_second_barcode\ta_second_author\t2 EOF - is( $items_content, $expected_items_content, 'get_item_content should return correct items info without time (if dateonly => 1)' ); + is( + $items_content, $expected_items_content, + 'get_item_content should return correct items info without time (if dateonly => 1)' + ); }; subtest 'Test where parameter for SendQueuedMessages' => sub { @@ -1301,13 +1458,15 @@ subtest 'Test where parameter for SendQueuedMessages' => sub { my $dbh = C4::Context->dbh; - my $borrowernumber = Koha::Patron->new({ - firstname => 'Jane', - surname => 'Smith', - categorycode => $patron_category, - branchcode => $library->{branchcode}, - dateofbirth => $date, - })->store->borrowernumber; + my $borrowernumber = Koha::Patron->new( + { + firstname => 'Jane', + surname => 'Smith', + categorycode => $patron_category, + branchcode => $library->{branchcode}, + dateofbirth => $date, + } + )->store->borrowernumber; $dbh->do(q|DELETE FROM message_queue|); $my_message = { @@ -1349,18 +1508,21 @@ subtest 'Test where parameter for SendQueuedMessages' => sub { 'message_transport_type' => 'sms', 'from_address' => 'from@example.com' }; - my @id = ( C4::Letters::EnqueueLetter($my_message), + my @id = ( + C4::Letters::EnqueueLetter($my_message), C4::Letters::EnqueueLetter($my_message2), C4::Letters::EnqueueLetter($my_message3), ); - C4::Letters::SendQueuedMessages({ - # Test scalar/arrayref in parameter too - letter_code => [ 'TEST_MESSAGE', 'SOMETHING_NOT_THERE' ], - type => 'sms', - where => q{content NOT LIKE '%skipped%'}, - }); - is( Koha::Notice::Messages->find( $id[0] )->status, 'failed', 'Processed but failed' ); - is( Koha::Notice::Messages->find( $id[1] )->status, 'failed', 'Processed but failed' ); + C4::Letters::SendQueuedMessages( + { + # Test scalar/arrayref in parameter too + letter_code => [ 'TEST_MESSAGE', 'SOMETHING_NOT_THERE' ], + type => 'sms', + where => q{content NOT LIKE '%skipped%'}, + } + ); + is( Koha::Notice::Messages->find( $id[0] )->status, 'failed', 'Processed but failed' ); + is( Koha::Notice::Messages->find( $id[1] )->status, 'failed', 'Processed but failed' ); is( Koha::Notice::Messages->find( $id[2] )->status, 'pending', 'Skipped, still pending' ); }; @@ -1369,14 +1531,16 @@ subtest 'Test limit parameter for SendQueuedMessages' => sub { my $dbh = C4::Context->dbh; - my $borrowernumber = Koha::Patron->new({ - firstname => 'Jane', - surname => 'Smith', - categorycode => $patron_category, - branchcode => $library->{branchcode}, - dateofbirth => $date, - email => 'shouldnotwork@wrong.net', - })->store->borrowernumber; + my $borrowernumber = Koha::Patron->new( + { + firstname => 'Jane', + surname => 'Smith', + categorycode => $patron_category, + branchcode => $library->{branchcode}, + dateofbirth => $date, + email => 'shouldnotwork@wrong.net', + } + )->store->borrowernumber; $dbh->do(q|DELETE FROM message_queue|); $my_message = { @@ -1392,62 +1556,81 @@ subtest 'Test limit parameter for SendQueuedMessages' => sub { 'message_transport_type' => 'email', 'from_address' => 'from@example.com' }; - C4::Letters::EnqueueLetter($my_message) for 1..5; + C4::Letters::EnqueueLetter($my_message) for 1 .. 5; - $send_or_die_count = 0; # reset + $send_or_die_count = 0; # reset my $messages_sent; my $regex = qr|Fake send_or_die|; warning_like { - $messages_sent = C4::Letters::SendQueuedMessages( { limit => 1 } ) } - $regex, + $messages_sent = C4::Letters::SendQueuedMessages( { limit => 1 } ) + } + $regex, "SendQueuedMessages with limit 1"; - is( $messages_sent, 1, - 'Sent 1 message with limit of 1 and 5 unprocessed messages' ); + is( + $messages_sent, 1, + 'Sent 1 message with limit of 1 and 5 unprocessed messages' + ); warnings_like { - $messages_sent = C4::Letters::SendQueuedMessages( { limit => 2 } ) } - [ map { $regex } 1..2 ], + $messages_sent = C4::Letters::SendQueuedMessages( { limit => 2 } ) + } + [ map { $regex } 1 .. 2 ], "SendQueuedMessages with limit 2"; - is( $messages_sent, 2, - 'Sent 2 messages with limit of 2 and 4 unprocessed messages' ); + is( + $messages_sent, 2, + 'Sent 2 messages with limit of 2 and 4 unprocessed messages' + ); warnings_like { - $messages_sent = C4::Letters::SendQueuedMessages( { limit => 3 } ) } - [ map { $regex } 1..2 ], + $messages_sent = C4::Letters::SendQueuedMessages( { limit => 3 } ) + } + [ map { $regex } 1 .. 2 ], "SendQueuedMessages with limit 3"; - is( $messages_sent, 2, - 'Sent 2 messages with limit of 3 and 2 unprocessed messages' ); + is( + $messages_sent, 2, + 'Sent 2 messages with limit of 3 and 2 unprocessed messages' + ); is( $send_or_die_count, 5, '5 messages sent' ); + # Mimic correct status in queue for next tests - Koha::Notice::Messages->search({ to_address => { 'LIKE', '%wrong.net' }})->update({ status => 'sent' }); + Koha::Notice::Messages->search( { to_address => { 'LIKE', '%wrong.net' } } )->update( { status => 'sent' } ); # Now add a few domain limits too, sending 2 more mails to wrongnet, 2 to fake1, 2 to fake2 # Since we already sent 5 to wrong.net, we expect one deferral when limiting to 6 # Similarly we arrange for 1 deferral for fake1, and 2 for fake2 # We set therefore limit to 3 sent messages: we expect 2 sent, 4 deferred (so 6 processed) - t::lib::Mocks::mock_config( 'message_domain_limits', { domain => [ - { name => 'wrong.net', limit => 6, unit => '1m' }, - { name => 'fake1.domain', limit => 1, unit => '1m' }, - { name => 'fake2.domain', limit => 0, unit => '1m' }, - ]}); - C4::Letters::EnqueueLetter($my_message) for 1..2; + t::lib::Mocks::mock_config( + 'message_domain_limits', + { + domain => [ + { name => 'wrong.net', limit => 6, unit => '1m' }, + { name => 'fake1.domain', limit => 1, unit => '1m' }, + { name => 'fake2.domain', limit => 0, unit => '1m' }, + ] + } + ); + C4::Letters::EnqueueLetter($my_message) for 1 .. 2; $my_message->{to_address} = 'someone@fake1.domain'; - C4::Letters::EnqueueLetter($my_message) for 1..2; + C4::Letters::EnqueueLetter($my_message) for 1 .. 2; $my_message->{to_address} = 'another@fake2.domain'; - C4::Letters::EnqueueLetter($my_message) for 1..2; - my $mocked_util = Test::MockModule->new('Koha::Notice::Util'); + C4::Letters::EnqueueLetter($my_message) for 1 .. 2; + my $mocked_util = Test::MockModule->new('Koha::Notice::Util'); my $count_exceeds_calls = 0; - $mocked_util->mock( 'exceeds_limit', sub { - $count_exceeds_calls++; - $mocked_util->original('exceeds_limit')->(@_); - }); + $mocked_util->mock( + 'exceeds_limit', + sub { + $count_exceeds_calls++; + $mocked_util->original('exceeds_limit')->(@_); + } + ); warnings_like { - $messages_sent = C4::Letters::SendQueuedMessages({ limit => 3 }) } - [ qr/wrong.net reached limit/, $regex, qr/fake1.domain reached limit/, $regex ], + $messages_sent = C4::Letters::SendQueuedMessages( { limit => 3 } ) + } + [ qr/wrong.net reached limit/, $regex, qr/fake1.domain reached limit/, $regex ], "SendQueuedMessages with limit 2 and domain limits"; - is( $messages_sent, 2, 'Only expecting 2 sent messages' ); - is( Koha::Notice::Messages->search({ status => 'pending' })->count, 4, 'Still 4 pending' ); + is( $messages_sent, 2, 'Only expecting 2 sent messages' ); + is( Koha::Notice::Messages->search( { status => 'pending' } )->count, 4, 'Still 4 pending' ); is( $count_exceeds_calls, 6, 'We saw 6 messages while checking domain limits: so we deferred 4' ); }; @@ -1457,14 +1640,16 @@ subtest 'Test message_id parameter for SendQueuedMessages' => sub { my $dbh = C4::Context->dbh; - my $borrowernumber = Koha::Patron->new({ - firstname => 'Jane', - surname => 'Smith', - categorycode => $patron_category, - branchcode => $library->{branchcode}, - dateofbirth => $date, - smsalertnumber => undef, - })->store->borrowernumber; + my $borrowernumber = Koha::Patron->new( + { + firstname => 'Jane', + surname => 'Smith', + categorycode => $patron_category, + branchcode => $library->{branchcode}, + dateofbirth => $date, + smsalertnumber => undef, + } + )->store->borrowernumber; $dbh->do(q|DELETE FROM message_queue|); $my_message = { @@ -1478,26 +1663,26 @@ subtest 'Test message_id parameter for SendQueuedMessages' => sub { 'borrowernumber' => $borrowernumber, 'to_address' => 'to@example.org', 'message_transport_type' => 'email', - 'from_address' => '@example.com' # invalid from_address + 'from_address' => '@example.com' # invalid from_address }; my $message_id = C4::Letters::EnqueueLetter($my_message); - $send_or_die_count = 0; # reset + $send_or_die_count = 0; # reset my $processed = C4::Letters::SendQueuedMessages( { message_id => $message_id } ); is( $send_or_die_count, 0, 'Nothing sent when one message_id passed' ); my $message_1 = C4::Letters::GetMessage($message_id); - is( $message_1->{status}, 'failed', 'Invalid from_address => status failed' ); - is( $message_1->{failure_code}, 'INVALID_EMAIL:from', 'Failure code set correctly for invalid email parameter'); + is( $message_1->{status}, 'failed', 'Invalid from_address => status failed' ); + is( $message_1->{failure_code}, 'INVALID_EMAIL:from', 'Failure code set correctly for invalid email parameter' ); - $my_message->{from_address} = 'root@example.org'; # valid from_address + $my_message->{from_address} = 'root@example.org'; # valid from_address $message_id = C4::Letters::EnqueueLetter($my_message); warning_like { C4::Letters::SendQueuedMessages( { message_id => $message_id } ); } - qr|Fake send_or_die|, + qr|Fake send_or_die|, "SendQueuedMessages is using the mocked send_or_die routine"; is( $send_or_die_count, 1, 'One message passed through' ); - $message_1 = C4::Letters::GetMessage($message_1->{message_id}); + $message_1 = C4::Letters::GetMessage( $message_1->{message_id} ); my $message_2 = C4::Letters::GetMessage($message_id); is( $message_1->{status}, 'failed', 'Message 1 status is unchanged' ); - is( $message_2->{status}, 'sent', 'Valid from_address => status sent' ); + is( $message_2->{status}, 'sent', 'Valid from_address => status sent' ); }; subtest 'Template toolkit syntax in parameters' => sub { diff --git a/t/db_dependent/Letters/GetLetterTemplates.t b/t/db_dependent/Letters/GetLetterTemplates.t index 31a8571150..3e2e77d6d3 100755 --- a/t/db_dependent/Letters/GetLetterTemplates.t +++ b/t/db_dependent/Letters/GetLetterTemplates.t @@ -95,42 +95,51 @@ my $letters = [ ]; my $sth = $dbh->prepare( -q|INSERT INTO letter(module, code, branchcode, name, title, content, message_transport_type, lang) VALUES (?, ?, ?, ?, ?, ?, ?, ?)| + q|INSERT INTO letter(module, code, branchcode, name, title, content, message_transport_type, lang) VALUES (?, ?, ?, ?, ?, ?, ?, ?)| ); for my $l (@$letters) { - $sth->execute( $l->{module}, $l->{code}, $l->{branchcode}, $l->{name}, - $l->{title}, $l->{content}, $l->{message_transport_type}, $l->{lang} ); + $sth->execute( + $l->{module}, $l->{code}, $l->{branchcode}, $l->{name}, + $l->{title}, $l->{content}, $l->{message_transport_type}, $l->{lang} + ); } -t::lib::Mocks::mock_preference('TranslateNotices', 1); +t::lib::Mocks::mock_preference( 'TranslateNotices', 1 ); my $letter_templates; $letter_templates = C4::Letters::GetLetterTemplates; -is_deeply( $letter_templates, [], - 'GetLetterTemplates should not return templates if not param is given' ); +is_deeply( + $letter_templates, [], + 'GetLetterTemplates should not return templates if not param is given' +); -$letter_templates = C4::Letters::GetLetterTemplates( - { module => 'circulation', code => 'code1', branchcode => '' } ); -is( scalar( @$letter_templates ), - 2, '2 default templates should exist for circulation code1' ); +$letter_templates = C4::Letters::GetLetterTemplates( { module => 'circulation', code => 'code1', branchcode => '' } ); +is( + scalar(@$letter_templates), + 2, '2 default templates should exist for circulation code1' +); my $has_email = grep { $_->{message_transport_type} eq 'email' } @$letter_templates; is( $has_email, 1, 'The mtt email should exist for circulation code1' ); my $has_sms = grep { $_->{message_transport_type} eq 'sms' } @$letter_templates; is( $has_sms, 1, 'The mtt sms should exist for circulation code1' ); -$letter_templates = C4::Letters::GetLetterTemplates( - { module => 'circulation', code => 'code1', branchcode => 'CPL' } ); -is( scalar( @$letter_templates ), - 1, '1 template should exist for circulation CPL code1' ); +$letter_templates = + C4::Letters::GetLetterTemplates( { module => 'circulation', code => 'code1', branchcode => 'CPL' } ); +is( + scalar(@$letter_templates), + 1, '1 template should exist for circulation CPL code1' +); $has_email = grep { $_->{message_transport_type} eq 'email' } @$letter_templates; is( $has_email, 1, 'The mtt should be email for circulation CPL code1' ); -$letter_templates = C4::Letters::GetLetterTemplates( - { module => 'circulation', code => 'code1' } ); -is( scalar( @$letter_templates ), - 2, '2 default templates should exist for circulation code1 (even if branchcode is not given)' ); +$letter_templates = C4::Letters::GetLetterTemplates( { module => 'circulation', code => 'code1' } ); +is( + scalar(@$letter_templates), + 2, '2 default templates should exist for circulation code1 (even if branchcode is not given)' +); -t::lib::Mocks::mock_preference('TranslateNotices', 0); -$letter_templates = C4::Letters::GetLetterTemplates( - { module => 'circulation', code => 'code1' } ); -is( scalar( @$letter_templates ), - 1, 'There should exist only 1 template circulation code1 for default language' ); +t::lib::Mocks::mock_preference( 'TranslateNotices', 0 ); +$letter_templates = C4::Letters::GetLetterTemplates( { module => 'circulation', code => 'code1' } ); +is( + scalar(@$letter_templates), + 1, 'There should exist only 1 template circulation code1 for default language' +); diff --git a/t/db_dependent/Letters/GetLettersAvailableForALibrary.t b/t/db_dependent/Letters/GetLettersAvailableForALibrary.t index 3a49e7d68e..7664540d9a 100755 --- a/t/db_dependent/Letters/GetLettersAvailableForALibrary.t +++ b/t/db_dependent/Letters/GetLettersAvailableForALibrary.t @@ -97,11 +97,13 @@ my $letters = [ ]; my $sth = $dbh->prepare( -q|INSERT INTO letter(module, code, branchcode, name, title, content, message_transport_type) VALUES (?, ?, ?, ?, ?, ?, ?)| + q|INSERT INTO letter(module, code, branchcode, name, title, content, message_transport_type) VALUES (?, ?, ?, ?, ?, ?, ?)| ); for my $l (@$letters) { - $sth->execute( $l->{module}, $l->{code}, $l->{branchcode}, $l->{name}, - $l->{title}, $l->{content}, $l->{message_transport_type} ); + $sth->execute( + $l->{module}, $l->{code}, $l->{branchcode}, $l->{name}, + $l->{title}, $l->{content}, $l->{message_transport_type} + ); # GetLettersAvailableForALibrary does not return these fields delete $l->{title}; @@ -111,67 +113,86 @@ for my $l (@$letters) { } my $available_letters; -$available_letters = - C4::Letters::GetLettersAvailableForALibrary( { module => 'circulation' } ); -is( scalar(@$available_letters), - 3, 'There should be 3 default letters for circulation (3 distinct codes)' ); - -$available_letters = C4::Letters::GetLettersAvailableForALibrary( - { module => 'circulation', branchcode => '' } ); -is( scalar(@$available_letters), 3, -'There should be 3 default letters for circulation (3 distinct codes), branchcode=""' +$available_letters = C4::Letters::GetLettersAvailableForALibrary( { module => 'circulation' } ); +is( + scalar(@$available_letters), + 3, 'There should be 3 default letters for circulation (3 distinct codes)' ); -is_deeply( $available_letters->[0], - $letters->[2], 'The letters should be sorted by name (A)' ); -is_deeply( $available_letters->[1], - $letters->[0], 'The letters should be sorted by name (B)' ); -is_deeply( $available_letters->[2], - $letters->[3], 'The letters should be sorted by name (C)' ); -$available_letters = C4::Letters::GetLettersAvailableForALibrary( - { module => 'circulation', branchcode => 'CPL' } ); -is( scalar(@$available_letters), 3, -'There should be 3 default letters for circulation (3 distinct codes), branchcode="CPL"' +$available_letters = C4::Letters::GetLettersAvailableForALibrary( { module => 'circulation', branchcode => '' } ); +is( + scalar(@$available_letters), 3, + 'There should be 3 default letters for circulation (3 distinct codes), branchcode=""' +); +is_deeply( + $available_letters->[0], + $letters->[2], 'The letters should be sorted by name (A)' +); +is_deeply( + $available_letters->[1], + $letters->[0], 'The letters should be sorted by name (B)' +); +is_deeply( + $available_letters->[2], + $letters->[3], 'The letters should be sorted by name (C)' ); -is_deeply( $available_letters->[0], - $letters->[6], 'The letters should be sorted by name (A)' ); -is_deeply( $available_letters->[1], - $letters->[5], 'The letters should be sorted by name (B)' ); -is_deeply( $available_letters->[2], - $letters->[3], 'The letters should be sorted by name (C)' ); -$available_letters = C4::Letters::GetLettersAvailableForALibrary( - { module => 'circulation', branchcode => 'MPL' } ); -is( scalar(@$available_letters), 3, -'There should be 3 default letters for circulation (3 distinct codes), branchcode="CPL"' +$available_letters = C4::Letters::GetLettersAvailableForALibrary( { module => 'circulation', branchcode => 'CPL' } ); +is( + scalar(@$available_letters), 3, + 'There should be 3 default letters for circulation (3 distinct codes), branchcode="CPL"' +); +is_deeply( + $available_letters->[0], + $letters->[6], 'The letters should be sorted by name (A)' +); +is_deeply( + $available_letters->[1], + $letters->[5], 'The letters should be sorted by name (B)' +); +is_deeply( + $available_letters->[2], + $letters->[3], 'The letters should be sorted by name (C)' +); + +$available_letters = C4::Letters::GetLettersAvailableForALibrary( { module => 'circulation', branchcode => 'MPL' } ); +is( + scalar(@$available_letters), 3, + 'There should be 3 default letters for circulation (3 distinct codes), branchcode="CPL"' +); +is_deeply( + $available_letters->[0], + $letters->[2], 'The letters should be sorted by name (A)' +); +is_deeply( + $available_letters->[1], + $letters->[7], 'The letters should be sorted by name (B)' +); +is_deeply( + $available_letters->[2], + $letters->[3], 'The letters should be sorted by name (C)' ); -is_deeply( $available_letters->[0], - $letters->[2], 'The letters should be sorted by name (A)' ); -is_deeply( $available_letters->[1], - $letters->[7], 'The letters should be sorted by name (B)' ); -is_deeply( $available_letters->[2], - $letters->[3], 'The letters should be sorted by name (C)' ); my $letters_by_module = C4::Letters::GetLetters( { module => 'circulation' } ); -is( scalar(@$letters_by_module), - 3, '3 different letter codes exist for circulation' ); +is( + scalar(@$letters_by_module), + 3, '3 different letter codes exist for circulation' +); my $letters_by_branchcode = C4::Letters::GetLetters( { branchcode => 'CPL' } ); -is( scalar(@$letters_by_branchcode), - 2, '2 different letter codes exist for CPL' ); +is( + scalar(@$letters_by_branchcode), + 2, '2 different letter codes exist for CPL' +); # On the way, we test DelLetter is( - C4::Letters::DelLetter( - { module => 'cataloguing', code => 'code1', branchcode => 'MPL' } - ), + C4::Letters::DelLetter( { module => 'cataloguing', code => 'code1', branchcode => 'MPL' } ), '0E0', 'No letter exist for MPL cat/code1' ); is( - C4::Letters::DelLetter( - { module => 'circulation', code => 'code1', branchcode => '' } - ), + C4::Letters::DelLetter( { module => 'circulation', code => 'code1', branchcode => '' } ), 2, '2 default letters existed for circ/code1 (1 for email and 1 for sms)' ); @@ -188,9 +209,7 @@ is( '1 letter existed for CPL circ/code1/email' ); is( - C4::Letters::DelLetter( - { module => 'circulation', code => 'code1', branchcode => 'MPL' } - ), + C4::Letters::DelLetter( { module => 'circulation', code => 'code1', branchcode => 'MPL' } ), 1, '1 letter existed for MPL circ/code1' ); diff --git a/t/db_dependent/Letters/TemplateToolkit.t b/t/db_dependent/Letters/TemplateToolkit.t index 35c836a97c..0ac1f928c2 100755 --- a/t/db_dependent/Letters/TemplateToolkit.t +++ b/t/db_dependent/Letters/TemplateToolkit.t @@ -29,8 +29,8 @@ use t::lib::TestBuilder; use t::lib::Mocks; use C4::Circulation qw( AddIssue AddReturn ); -use C4::Letters qw( GetPreparedLetter ); -use C4::Members qw( IssueSlip ); +use C4::Letters qw( GetPreparedLetter ); +use C4::Members qw( IssueSlip ); use C4::Biblio; use Koha::Database; use Koha::DateUtils qw( dt_from_string output_pref ); @@ -65,7 +65,7 @@ my $mocked_datetime = Test::MockModule->new('DateTime'); $mocked_datetime->mock( 'now', sub { return $now_value->clone; } ); my $library = $builder->build( { source => 'Branch' } ); -my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); +my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $patron2 = $builder->build( { source => 'Borrower' } ); @@ -89,8 +89,7 @@ my $news = $builder->build_object( my $serial = $builder->build_object( { class => 'Koha::Serials' } ); my $subscription = $builder->build_object( { class => 'Koha::Subscriptions' } ); my $suggestion = $builder->build_object( { class => 'Koha::Suggestions' } ); -my $checkout = $builder->build_object( - { class => 'Koha::Checkouts', value => { itemnumber => $item->id } } ); +my $checkout = $builder->build_object( { class => 'Koha::Checkouts', value => { itemnumber => $item->id } } ); my $modification = $builder->build_object( { class => 'Koha::Patron::Modifications', @@ -103,8 +102,7 @@ my $modification = $builder->build_object( my $prepared_letter; -my $sth = - $dbh->prepare(q{INSERT INTO letter (module, code, name, title, content) VALUES ('test',?,'Test',?,?)}); +my $sth = $dbh->prepare(q{INSERT INTO letter (module, code, name, title, content) VALUES ('test',?,'Test',?,?)}); $sth->execute( "TEST_PATRON", "[% borrower.firstname %]", "[% borrower.id %]" ); $prepared_letter = GetPreparedLetter( @@ -117,7 +115,7 @@ $prepared_letter = GetPreparedLetter( ) ); is( $prepared_letter->{content}, $patron->borrowernumber, 'Patron object used correctly with scalar for content' ); -is( $prepared_letter->{title}, $patron->firstname, 'Patron object used correctly with scalar for title' ); +is( $prepared_letter->{title}, $patron->firstname, 'Patron object used correctly with scalar for title' ); $prepared_letter = GetPreparedLetter( ( @@ -129,7 +127,7 @@ $prepared_letter = GetPreparedLetter( ) ); is( $prepared_letter->{content}, $patron->borrowernumber, 'Patron object used correctly with hashref for content' ); -is( $prepared_letter->{title}, $patron->firstname, 'Patron object used correctly with hashref for title' ); +is( $prepared_letter->{title}, $patron->firstname, 'Patron object used correctly with hashref for title' ); $prepared_letter = GetPreparedLetter( ( @@ -141,13 +139,13 @@ $prepared_letter = GetPreparedLetter( ) ); is( $prepared_letter->{content}, $patron->borrowernumber, 'Patron object used correctly with arrayref for content' ); -is( $prepared_letter->{title}, $patron->firstname, 'Patron object used correctly with arrayref for title' ); +is( $prepared_letter->{title}, $patron->firstname, 'Patron object used correctly with arrayref for title' ); $prepared_letter = GetPreparedLetter( ( module => 'test', letter_code => 'TEST_PATRON', - objects => { + objects => { borrower => scalar Koha::Patrons->find( $patron->borrowernumber ), }, ) @@ -164,47 +162,41 @@ $prepared_letter = GetPreparedLetter( }, ) ); -is( $prepared_letter->{content}, $item->biblionumber, 'Biblio object used correctly for content' ); -is( $prepared_letter->{title}, $item->biblio->title, 'Biblio object used correctly for title' ); +is( $prepared_letter->{content}, $item->biblionumber, 'Biblio object used correctly for content' ); +is( $prepared_letter->{title}, $item->biblio->title, 'Biblio object used correctly for title' ); $sth->execute( "TEST_LIBRARY", "[% branch.branchcode %]", "[% branch.id %]" ); $prepared_letter = GetPreparedLetter( ( module => 'test', letter_code => 'TEST_LIBRARY', - tables => { - branches => $library->{branchcode} - }, + tables => { branches => $library->{branchcode} }, ) ); is( $prepared_letter->{content}, $library->{branchcode}, 'Library object used correctly for content' ); -is( $prepared_letter->{title}, $library->{branchcode}, 'Library object used correctly for title' ); +is( $prepared_letter->{title}, $library->{branchcode}, 'Library object used correctly for title' ); $sth->execute( "TEST_ITEM", "[% item.barcode %]", "[% item.id %]" ); $prepared_letter = GetPreparedLetter( ( module => 'test', letter_code => 'TEST_ITEM', - tables => { - items => $item->id() - }, + tables => { items => $item->id() }, ) ); -is( $prepared_letter->{content}, $item->id(), 'Item object used correctly for content' ); -is( $prepared_letter->{title}, $item->barcode, 'Item object used correctly for title' ); +is( $prepared_letter->{content}, $item->id(), 'Item object used correctly for content' ); +is( $prepared_letter->{title}, $item->barcode, 'Item object used correctly for title' ); $sth->execute( "TEST_NEWS", "[% additional_content.id %]", "[% additional_content.id %]" ); $prepared_letter = GetPreparedLetter( ( module => 'test', letter_code => 'TEST_NEWS', - tables => { - additional_contents => $news->id() - }, + tables => { additional_contents => $news->id() }, ) ); is( $prepared_letter->{content}, $news->id(), 'News object used correctly for content' ); -is( $prepared_letter->{title}, $news->id(), 'News object used correctly for title' ); +is( $prepared_letter->{title}, $news->id(), 'News object used correctly for title' ); $sth->execute( "TEST_HOLD", "[% hold.borrowernumber %]", "[% hold.id %]" ); $prepared_letter = GetPreparedLetter( @@ -216,8 +208,8 @@ $prepared_letter = GetPreparedLetter( }, ) ); -is( $prepared_letter->{content}, $hold->id(), 'Hold object used correctly for content' ); -is( $prepared_letter->{title}, $hold->borrowernumber, 'Hold object used correctly for title' ); +is( $prepared_letter->{content}, $hold->id(), 'Hold object used correctly for content' ); +is( $prepared_letter->{title}, $hold->borrowernumber, 'Hold object used correctly for title' ); eval { $prepared_letter = GetPreparedLetter( @@ -228,10 +220,13 @@ eval { reserves => [ $patron->borrowernumber, $item->biblionumber ], }, ) - ) + ); }; my $croak = $@; -like( $croak, qr{^Multiple foreign keys \(table reserves\) should be passed using an hashref.*}, "GetPreparedLetter should not be called with arrayref for multiple FK" ); +like( + $croak, qr{^Multiple foreign keys \(table reserves\) should be passed using an hashref.*}, + "GetPreparedLetter should not be called with arrayref for multiple FK" +); # Bug 16942 $prepared_letter = GetPreparedLetter( @@ -255,9 +250,7 @@ $prepared_letter = GetPreparedLetter( ( module => 'test', letter_code => 'TEST_SERIAL', - tables => { - serial => $serial->id() - }, + tables => { serial => $serial->id() }, ) ); is( $prepared_letter->{content}, $serial->id(), 'Serial object used correctly' ); @@ -267,9 +260,7 @@ $prepared_letter = GetPreparedLetter( ( module => 'test', letter_code => 'TEST_SUBSCRIPTION', - tables => { - subscription => $subscription->id() - }, + tables => { subscription => $subscription->id() }, ) ); is( $prepared_letter->{content}, $subscription->id(), 'Subscription object used correctly' ); @@ -279,9 +270,7 @@ $prepared_letter = GetPreparedLetter( ( module => 'test', letter_code => 'TEST_SUGGESTION', - tables => { - suggestions => $suggestion->id() - }, + tables => { suggestions => $suggestion->id() }, ) ); is( $prepared_letter->{content}, $suggestion->id(), 'Suggestion object used correctly' ); @@ -291,9 +280,7 @@ $prepared_letter = GetPreparedLetter( ( module => 'test', letter_code => 'TEST_ISSUE', - tables => { - issues => $item->id() - }, + tables => { issues => $item->id() }, ) ); is( $prepared_letter->{content}, $checkout->id(), 'Checkout object used correctly' ); @@ -313,8 +300,8 @@ is( $prepared_letter->{content}, $modification->id(), 'Patron modification objec subtest 'regression tests' => sub { plan tests => 8; - my $library = $builder->build( { source => 'Branch' } ); - my $itemtype = $builder->build_object({ class => 'Koha::ItemTypes' })->store->itemtype; + my $library = $builder->build( { source => 'Branch' } ); + my $itemtype = $builder->build_object( { class => 'Koha::ItemTypes' } )->store->itemtype; my $item1 = $builder->build_sample_item( { @@ -326,7 +313,7 @@ subtest 'regression tests' => sub { ); my $biblio1 = $item1->biblio->unblessed; $item1 = $item1->unblessed; - my $item2 = $builder->build_sample_item( + my $item2 = $builder->build_sample_item( { barcode => 'another_t_barcode', library => $library->{branchcode}, @@ -336,7 +323,7 @@ subtest 'regression tests' => sub { ); my $biblio2 = $item2->biblio->unblessed; $item2 = $item2->unblessed; - my $item3 = $builder->build_sample_item( + my $item3 = $builder->build_sample_item( { barcode => 'another_t_barcode_3', library => $library->{branchcode}, @@ -347,34 +334,37 @@ subtest 'regression tests' => sub { my $biblio3 = $item3->biblio->unblessed; $item3 = $item3->unblessed; - t::lib::Mocks::mock_userenv({ branchcode => $library->{branchcode} }); + t::lib::Mocks::mock_userenv( { branchcode => $library->{branchcode} } ); subtest 'ACQ_NOTIF_ON_RECEIV ' => sub { plan tests => 1; - my $code = 'ACQ_NOTIF_ON_RECEIV'; + my $code = 'ACQ_NOTIF_ON_RECEIV'; my $branchcode = $library->{branchcode}; - my $order = $builder->build({ source => 'Aqorder' }); + my $order = $builder->build( { source => 'Aqorder' } ); my $template = q| Dear <<borrowers.firstname>> <<borrowers.surname>>, The order <<aqorders.ordernumber>> (<<biblio.title>>) has been received. Your library. |; - my $params = { code => $code, branchcode => $branchcode, tables => { branches => $library, borrowers => $patron->unblessed, biblio => $biblio1, aqorders => $order } }; - my $letter = process_letter( { template => $template, %$params }); + my $params = { + code => $code, branchcode => $branchcode, + tables => { branches => $library, borrowers => $patron->unblessed, biblio => $biblio1, aqorders => $order } + }; + my $letter = process_letter( { template => $template, %$params } ); my $tt_template = q| Dear [% borrower.firstname %] [% borrower.surname %], The order [% order.ordernumber %] ([% biblio.title %]) has been received. Your library. |; - my $tt_letter = process_letter( { template => $tt_template, %$params }); + my $tt_letter = process_letter( { template => $tt_template, %$params } ); is( $tt_letter->{content}, $letter->{content}, 'Verified letter content' ); }; subtest 'AR_*' => sub { plan tests => 2; - my $code = 'AR_CANCELED'; + my $code = 'AR_CANCELED'; my $branchcode = $library->{branchcode}; my $template = q| @@ -425,28 +415,42 @@ Notes: [% article_request.patron_notes %] $article_request->cancel; my $tt_letter = Koha::Notice::Messages->search( {}, { order_by => { -desc => 'message_id' } } )->next; is( $tt_letter->content, $letter->content, 'Compare AR_* notices' ); - isnt( $tt_letter->message_id, $letter->message_id, 'Comparing AR_* notices should compare 2 different messages' ); + isnt( + $tt_letter->message_id, $letter->message_id, + 'Comparing AR_* notices should compare 2 different messages' + ); }; subtest 'CHECKOUT+CHECKIN' => sub { plan tests => 4; my $checkout_code = 'CHECKOUT'; - my $checkin_code = 'CHECKIN'; + my $checkin_code = 'CHECKIN'; my $dbh = C4::Context->dbh; + # Enable notification for CHECKOUT - Things are hardcoded here but should work with default data - $dbh->do(q|INSERT INTO borrower_message_preferences( borrowernumber, message_attribute_id ) VALUES ( ?, ? )|, - undef, $patron->borrowernumber, 6 ); - my $borrower_message_preference_id = $dbh->last_insert_id(undef, undef, "borrower_message_preferences", undef); - $dbh->do(q|INSERT INTO borrower_message_transport_preferences( borrower_message_preference_id, message_transport_type) VALUES ( ?, ? )|, undef, $borrower_message_preference_id, 'email' ); + $dbh->do( + q|INSERT INTO borrower_message_preferences( borrowernumber, message_attribute_id ) VALUES ( ?, ? )|, + undef, $patron->borrowernumber, 6 + ); + my $borrower_message_preference_id = + $dbh->last_insert_id( undef, undef, "borrower_message_preferences", undef ); + $dbh->do( + q|INSERT INTO borrower_message_transport_preferences( borrower_message_preference_id, message_transport_type) VALUES ( ?, ? )|, + undef, $borrower_message_preference_id, 'email' + ); # Enable notification for CHECKIN - Things are hardcoded here but should work with default data - $dbh->do(q|INSERT INTO borrower_message_preferences( borrowernumber, message_attribute_id ) VALUES ( ?, ? )|, - undef, $patron->borrowernumber, 5); - $borrower_message_preference_id = $dbh->last_insert_id(undef, undef, "borrower_message_preferences", undef); - $dbh->do(q|INSERT INTO borrower_message_transport_preferences( borrower_message_preference_id, message_transport_type) VALUES ( ?, ? )|, undef, $borrower_message_preference_id, 'email' ); - + $dbh->do( + q|INSERT INTO borrower_message_preferences( borrowernumber, message_attribute_id ) VALUES ( ?, ? )|, + undef, $patron->borrowernumber, 5 + ); + $borrower_message_preference_id = $dbh->last_insert_id( undef, undef, "borrower_message_preferences", undef ); + $dbh->do( + q|INSERT INTO borrower_message_transport_preferences( borrower_message_preference_id, message_transport_type) VALUES ( ?, ? )|, + undef, $borrower_message_preference_id, 'email' + ); # historic syntax my $checkout_template = q| @@ -467,16 +471,20 @@ Thank you for visiting <<branches.branchname>>. reset_template( { template => $checkin_template, code => $checkin_code, module => 'circulation' } ); C4::Circulation::AddIssue( $patron, $item1->{barcode} ); - my $first_checkout_letter = Koha::Notice::Messages->search( {}, { order_by => { -desc => 'message_id' } } )->next; + my $first_checkout_letter = + Koha::Notice::Messages->search( {}, { order_by => { -desc => 'message_id' } } )->next; C4::Circulation::AddIssue( $patron, $item2->{barcode} ); - my $second_checkout_letter = Koha::Notice::Messages->search( {}, { order_by => { -desc => 'message_id' } } )->next; + my $second_checkout_letter = + Koha::Notice::Messages->search( {}, { order_by => { -desc => 'message_id' } } )->next; AddReturn( $item1->{barcode} ); - my $first_checkin_letter = Koha::Notice::Messages->search( {}, { order_by => { -desc => 'message_id' } } )->next; + my $first_checkin_letter = + Koha::Notice::Messages->search( {}, { order_by => { -desc => 'message_id' } } )->next; AddReturn( $item2->{barcode} ); - my $second_checkin_letter = Koha::Notice::Messages->search( {}, { order_by => { -desc => 'message_id' } } )->next; + my $second_checkin_letter = + Koha::Notice::Messages->search( {}, { order_by => { -desc => 'message_id' } } )->next; Koha::Notice::Messages->delete; @@ -499,21 +507,25 @@ Thank you for visiting [% branch.branchname %]. reset_template( { template => $checkin_template, code => $checkin_code, module => 'circulation' } ); C4::Circulation::AddIssue( $patron, $item1->{barcode} ); - my $first_checkout_tt_letter = Koha::Notice::Messages->search( {}, { order_by => { -desc => 'message_id' } } )->next; + my $first_checkout_tt_letter = + Koha::Notice::Messages->search( {}, { order_by => { -desc => 'message_id' } } )->next; C4::Circulation::AddIssue( $patron, $item2->{barcode} ); - my $second_checkout_tt_letter = Koha::Notice::Messages->search( {}, { order_by => { -desc => 'message_id' } } )->next; + my $second_checkout_tt_letter = + Koha::Notice::Messages->search( {}, { order_by => { -desc => 'message_id' } } )->next; AddReturn( $item1->{barcode} ); - my $first_checkin_tt_letter = Koha::Notice::Messages->search( {}, { order_by => { -desc => 'message_id' } } )->next; + my $first_checkin_tt_letter = + Koha::Notice::Messages->search( {}, { order_by => { -desc => 'message_id' } } )->next; AddReturn( $item2->{barcode} ); - my $second_checkin_tt_letter = Koha::Notice::Messages->search( {}, { order_by => { -desc => 'message_id' } } )->next; + my $second_checkin_tt_letter = + Koha::Notice::Messages->search( {}, { order_by => { -desc => 'message_id' } } )->next; - is( $first_checkout_tt_letter->content, $first_checkout_letter->content, 'Verify first checkout letter' ); + is( $first_checkout_tt_letter->content, $first_checkout_letter->content, 'Verify first checkout letter' ); is( $second_checkout_tt_letter->content, $second_checkout_letter->content, 'Verify second checkout letter' ); - is( $first_checkin_tt_letter->content, $first_checkin_letter->content, 'Verify first checkin letter' ); - is( $second_checkin_tt_letter->content, $second_checkin_letter->content, 'Verify second checkin letter' ); + is( $first_checkin_tt_letter->content, $first_checkin_letter->content, 'Verify first checkin letter' ); + is( $second_checkin_tt_letter->content, $second_checkin_letter->content, 'Verify second checkin letter' ); }; @@ -523,25 +535,33 @@ Thank you for visiting [% branch.branchname %]. my $code = 'DUEDGST'; my $dbh = C4::Context->dbh; + # Enable notification for DUEDGST - Things are hardcoded here but should work with default data - $dbh->do(q|INSERT INTO borrower_message_preferences( borrowernumber, message_attribute_id ) VALUES ( ?, ? )|, undef, $patron->borrowernumber, 1 ); - my $borrower_message_preference_id = $dbh->last_insert_id(undef, undef, "borrower_message_preferences", undef); - $dbh->do(q|INSERT INTO borrower_message_transport_preferences( borrower_message_preference_id, message_transport_type) VALUES ( ?, ? )|, undef, $borrower_message_preference_id, 'email' ); + $dbh->do( + q|INSERT INTO borrower_message_preferences( borrowernumber, message_attribute_id ) VALUES ( ?, ? )|, + undef, $patron->borrowernumber, 1 + ); + my $borrower_message_preference_id = + $dbh->last_insert_id( undef, undef, "borrower_message_preferences", undef ); + $dbh->do( + q|INSERT INTO borrower_message_transport_preferences( borrower_message_preference_id, message_transport_type) VALUES ( ?, ? )|, + undef, $borrower_message_preference_id, 'email' + ); my $params = { - code => $code, + code => $code, substitute => { count => 42 }, }; my $template = q| You have <<count>> items due |; - my $letter = process_letter( { template => $template, %$params }); + my $letter = process_letter( { template => $template, %$params } ); my $tt_template = q| You have [% count %] items due |; - my $tt_letter = process_letter( { template => $tt_template, %$params }); + my $tt_letter = process_letter( { template => $tt_template, %$params } ); is( $tt_letter->{content}, $letter->{content}, ); }; @@ -609,8 +629,10 @@ You have [% count %] items due EOF reset_template( { template => $template, code => $code, module => 'circulation' } ); - my $letter_for_item1 = C4::Reserves::ReserveSlip( { branchcode => $library->{branchcode}, reserve_id => $reserve_id1 } ); - my $letter_for_item2 = C4::Reserves::ReserveSlip( { branchcode => $library->{branchcode}, reserve_id => $reserve_id3 } ); + my $letter_for_item1 = + C4::Reserves::ReserveSlip( { branchcode => $library->{branchcode}, reserve_id => $reserve_id1 } ); + my $letter_for_item2 = + C4::Reserves::ReserveSlip( { branchcode => $library->{branchcode}, reserve_id => $reserve_id3 } ); my $tt_template = <<EOF; <h5>Date: [% today | \$KohaDates with_hours => 1 %]</h5> @@ -643,8 +665,10 @@ EOF EOF reset_template( { template => $tt_template, code => $code, module => 'circulation' } ); - my $tt_letter_for_item1 = C4::Reserves::ReserveSlip( { branchcode => $library->{branchcode}, reserve_id => $reserve_id1 } ); - my $tt_letter_for_item2 = C4::Reserves::ReserveSlip( { branchcode => $library->{branchcode}, reserve_id => $reserve_id3 } ); + my $tt_letter_for_item1 = + C4::Reserves::ReserveSlip( { branchcode => $library->{branchcode}, reserve_id => $reserve_id1 } ); + my $tt_letter_for_item2 = + C4::Reserves::ReserveSlip( { branchcode => $library->{branchcode}, reserve_id => $reserve_id3 } ); is( $tt_letter_for_item1->{content}, $letter_for_item1->{content}, ); is( $tt_letter_for_item2->{content}, $letter_for_item2->{content}, ); @@ -653,8 +677,8 @@ EOF subtest 'ISSUESLIP|checkedout|repeat|news' => sub { plan tests => 3; - my $code = 'ISSUESLIP'; - my $now = dt_from_string; + my $code = 'ISSUESLIP'; + my $now = dt_from_string; my $one_minute_ago = dt_from_string->subtract( minutes => 1 ); my $branchcode = $library->{branchcode}; @@ -727,14 +751,14 @@ EOF reset_template( { template => $template, code => $code, module => 'circulation' } ); - my $checkout = C4::Circulation::AddIssue( $patron, $item1->{barcode} ); # Add a first checkout + my $checkout = C4::Circulation::AddIssue( $patron, $item1->{barcode} ); # Add a first checkout $checkout->set( { timestamp => $now, issuedate => $one_minute_ago } )->store; my $first_slip = C4::Members::IssueSlip( $branchcode, $patron->borrowernumber ); - $checkout = C4::Circulation::AddIssue( $patron, $item2->{barcode} ); # Add a second checkout + $checkout = C4::Circulation::AddIssue( $patron, $item2->{barcode} ); # Add a second checkout $checkout->set( { timestamp => $now, issuedate => $now } )->store; my $yesterday = dt_from_string->subtract( days => 1 ); - C4::Circulation::AddIssue( $patron, $item3->{barcode}, $yesterday ); # Add an overdue + C4::Circulation::AddIssue( $patron, $item3->{barcode}, $yesterday ); # Add an overdue my $second_slip = C4::Members::IssueSlip( $branchcode, $patron->borrowernumber ); # Cleanup @@ -789,13 +813,13 @@ EOF reset_template( { template => $tt_template, code => $code, module => 'circulation' } ); - $checkout = C4::Circulation::AddIssue( $patron, $item1->{barcode} ); # Add a first checkout + $checkout = C4::Circulation::AddIssue( $patron, $item1->{barcode} ); # Add a first checkout $checkout->set( { timestamp => $now, issuedate => $one_minute_ago } )->store; my $first_tt_slip = C4::Members::IssueSlip( $branchcode, $patron->borrowernumber ); - $checkout = C4::Circulation::AddIssue( $patron, $item2->{barcode} ); # Add a second checkout + $checkout = C4::Circulation::AddIssue( $patron, $item2->{barcode} ); # Add a second checkout $checkout->set( { timestamp => $now, issuedate => $now } )->store; - C4::Circulation::AddIssue( $patron, $item3->{barcode}, $yesterday ); # Add an overdue + C4::Circulation::AddIssue( $patron, $item3->{barcode}, $yesterday ); # Add an overdue my $second_tt_slip = C4::Members::IssueSlip( $branchcode, $patron->borrowernumber ); # There is too many line breaks generated by the historic syntax @@ -803,7 +827,7 @@ EOF my $news_item_title = $content->title; like( $first_slip->{content}, qr{$news_item_title} ); - is( $first_tt_slip->{content}, $first_slip->{content}, ); + is( $first_tt_slip->{content}, $first_slip->{content}, ); is( $second_tt_slip->{content}, $second_slip->{content}, ); # Cleanup @@ -850,32 +874,35 @@ EOF reset_template( { template => $template, code => $code, module => 'circulation' } ); - my $yesterday = dt_from_string->subtract( days => 1 ); + my $yesterday = dt_from_string->subtract( days => 1 ); my $two_days_ago = dt_from_string->subtract( days => 2 ); - my $issue1 = C4::Circulation::AddIssue( $patron, $item1->{barcode} ); # Add a first checkout - my $issue2 = C4::Circulation::AddIssue( $patron, $item2->{barcode}, $yesterday ); # Add an first overdue - my $issue3 = C4::Circulation::AddIssue( $patron, $item3->{barcode}, $two_days_ago ); # Add an second overdue + my $issue1 = C4::Circulation::AddIssue( $patron, $item1->{barcode} ); # Add a first checkout + my $issue2 = C4::Circulation::AddIssue( $patron, $item2->{barcode}, $yesterday ); # Add an first overdue + my $issue3 = C4::Circulation::AddIssue( $patron, $item3->{barcode}, $two_days_ago ); # Add an second overdue $issue1 = $issue1->unblessed; $issue2 = $issue2->unblessed; $issue3 = $issue3->unblessed; # For items.content - my @item_fields = qw( date_due title barcode author itemnumber ); - my $items_content = C4::Letters::get_item_content( { item => { %$item1, %$biblio1, %$issue1 }, item_content_fields => \@item_fields, dateonly => 1 } ); - $items_content .= C4::Letters::get_item_content( { item => { %$item2, %$biblio2, %$issue2 }, item_content_fields => \@item_fields, dateonly => 1 } ); - $items_content .= C4::Letters::get_item_content( { item => { %$item3, %$biblio3, %$issue3 }, item_content_fields => \@item_fields, dateonly => 1 } ); + my @item_fields = qw( date_due title barcode author itemnumber ); + my $items_content = C4::Letters::get_item_content( + { item => { %$item1, %$biblio1, %$issue1 }, item_content_fields => \@item_fields, dateonly => 1 } ); + $items_content .= C4::Letters::get_item_content( + { item => { %$item2, %$biblio2, %$issue2 }, item_content_fields => \@item_fields, dateonly => 1 } ); + $items_content .= C4::Letters::get_item_content( + { item => { %$item3, %$biblio3, %$issue3 }, item_content_fields => \@item_fields, dateonly => 1 } ); - my @items = ( $item1, $item2, $item3 ); + my @items = ( $item1, $item2, $item3 ); my $letter = C4::Overdues::parse_overdues_letter( { - letter_code => $code, + letter_code => $code, borrowernumber => $patron->borrowernumber, - branchcode => $library->{branchcode}, - items => \@items, - substitute => { + branchcode => $library->{branchcode}, + items => \@items, + substitute => { bib => $library->{branchname}, 'items.content' => $items_content, - count => scalar( @items ), + count => scalar(@items), message_transport_type => 'email', } } @@ -886,7 +913,6 @@ EOF AddReturn( $item2->{barcode} ); AddReturn( $item3->{barcode} ); - # historic syntax my $tt_template = <<EOF; [%- USE Price -%] @@ -921,20 +947,20 @@ EOF reset_template( { template => $tt_template, code => $code, module => 'circulation' } ); - C4::Circulation::AddIssue( $patron, $item1->{barcode} ); # Add a first checkout - C4::Circulation::AddIssue( $patron, $item2->{barcode}, $yesterday ); # Add an first overdue - C4::Circulation::AddIssue( $patron, $item3->{barcode}, $two_days_ago ); # Add an second overdue + C4::Circulation::AddIssue( $patron, $item1->{barcode} ); # Add a first checkout + C4::Circulation::AddIssue( $patron, $item2->{barcode}, $yesterday ); # Add an first overdue + C4::Circulation::AddIssue( $patron, $item3->{barcode}, $two_days_ago ); # Add an second overdue my $tt_letter = C4::Overdues::parse_overdues_letter( { - letter_code => $code, + letter_code => $code, borrowernumber => $patron->borrowernumber, - branchcode => $library->{branchcode}, - items => \@items, - substitute => { + branchcode => $library->{branchcode}, + items => \@items, + substitute => { bib => $library->{branchname}, 'items.content' => $items_content, - count => scalar( @items ), + count => scalar(@items), message_transport_type => 'email', } } @@ -943,11 +969,12 @@ EOF is( $tt_letter->{content}, $letter->{content}, ); }; - subtest 'Bug 19743 - Header and Footer should be updated on each item for checkin / checkout / renewal notices' => sub { + subtest 'Bug 19743 - Header and Footer should be updated on each item for checkin / checkout / renewal notices' => + sub { plan tests => 8; my $checkout_code = 'CHECKOUT'; - my $checkin_code = 'CHECKIN'; + my $checkin_code = 'CHECKIN'; my $dbh = C4::Context->dbh; $dbh->do("DELETE FROM letter"); @@ -955,13 +982,27 @@ EOF $dbh->do("DELETE FROM message_queue"); # Enable notification for CHECKOUT - Things are hardcoded here but should work with default data - $dbh->do(q|INSERT INTO borrower_message_preferences( borrowernumber, message_attribute_id ) VALUES ( ?, ? )|, undef, $patron->borrowernumber, 6 ); - my $borrower_message_preference_id = $dbh->last_insert_id(undef, undef, "borrower_message_preferences", undef); - $dbh->do(q|INSERT INTO borrower_message_transport_preferences( borrower_message_preference_id, message_transport_type) VALUES ( ?, ? )|, undef, $borrower_message_preference_id, 'email' ); + $dbh->do( + q|INSERT INTO borrower_message_preferences( borrowernumber, message_attribute_id ) VALUES ( ?, ? )|, + undef, $patron->borrowernumber, 6 + ); + my $borrower_message_preference_id = + $dbh->last_insert_id( undef, undef, "borrower_message_preferences", undef ); + $dbh->do( + q|INSERT INTO borrower_message_transport_preferences( borrower_message_preference_id, message_transport_type) VALUES ( ?, ? )|, + undef, $borrower_message_preference_id, 'email' + ); + # Enable notification for CHECKIN - Things are hardcoded here but should work with default data - $dbh->do(q|INSERT INTO borrower_message_preferences( borrowernumber, message_attribute_id ) VALUES ( ?, ? )|, undef, $patron->borrowernumber, 5 ); - $borrower_message_preference_id = $dbh->last_insert_id(undef, undef, "borrower_message_preferences", undef); - $dbh->do(q|INSERT INTO borrower_message_transport_preferences( borrower_message_preference_id, message_transport_type) VALUES ( ?, ? )|, undef, $borrower_message_preference_id, 'email' ); + $dbh->do( + q|INSERT INTO borrower_message_preferences( borrowernumber, message_attribute_id ) VALUES ( ?, ? )|, + undef, $patron->borrowernumber, 5 + ); + $borrower_message_preference_id = $dbh->last_insert_id( undef, undef, "borrower_message_preferences", undef ); + $dbh->do( + q|INSERT INTO borrower_message_transport_preferences( borrower_message_preference_id, message_transport_type) VALUES ( ?, ? )|, + undef, $borrower_message_preference_id, 'email' + ); my $checkout_template = q| <<branches.branchname>> @@ -977,7 +1018,8 @@ EOF reset_template( { template => $checkin_template, code => $checkin_code, module => 'circulation' } ); my $issue = C4::Circulation::AddIssue( $patron, $item1->{barcode} ); - my $first_checkout_letter = Koha::Notice::Messages->search( {}, { order_by => { -desc => 'message_id' } } )->next; + my $first_checkout_letter = + Koha::Notice::Messages->search( {}, { order_by => { -desc => 'message_id' } } )->next; my $library_object = Koha::Libraries->find( $issue->branchcode ); my $old_branchname = $library_object->branchname; @@ -988,24 +1030,27 @@ EOF $library_object->store(); C4::Circulation::AddIssue( $patron, $item2->{barcode} ); - my $second_checkout_letter = Koha::Notice::Messages->search( {}, { order_by => { -desc => 'message_id' } } )->next; + my $second_checkout_letter = + Koha::Notice::Messages->search( {}, { order_by => { -desc => 'message_id' } } )->next; # Restore old name for first checkin notice - $library_object->branchname( $old_branchname ); + $library_object->branchname($old_branchname); $library_object->store(); AddReturn( $item1->{barcode} ); - my $first_checkin_letter = Koha::Notice::Messages->search( {}, { order_by => { -desc => 'message_id' } } )->next; + my $first_checkin_letter = + Koha::Notice::Messages->search( {}, { order_by => { -desc => 'message_id' } } )->next; # Change branch name for second checkin notice $library_object->branchname($new_branchname); $library_object->store(); AddReturn( $item2->{barcode} ); - my $second_checkin_letter = Koha::Notice::Messages->search( {}, { order_by => { -desc => 'message_id' } } )->next; + my $second_checkin_letter = + Koha::Notice::Messages->search( {}, { order_by => { -desc => 'message_id' } } )->next; # Restore old name for first TT checkout notice - $library_object->branchname( $old_branchname ); + $library_object->branchname($old_branchname); $library_object->store(); Koha::Notice::Messages->delete; @@ -1025,28 +1070,32 @@ EOF reset_template( { template => $checkin_template, code => $checkin_code, module => 'circulation' } ); C4::Circulation::AddIssue( $patron, $item1->{barcode} ); - my $first_checkout_tt_letter = Koha::Notice::Messages->search( {}, { order_by => { -desc => 'message_id' } } )->next; + my $first_checkout_tt_letter = + Koha::Notice::Messages->search( {}, { order_by => { -desc => 'message_id' } } )->next; # Change branch name for second checkout notice $library_object->branchname($new_branchname); $library_object->store(); C4::Circulation::AddIssue( $patron, $item2->{barcode} ); - my $second_checkout_tt_letter = Koha::Notice::Messages->search( {}, { order_by => { -desc => 'message_id' } } )->next; + my $second_checkout_tt_letter = + Koha::Notice::Messages->search( {}, { order_by => { -desc => 'message_id' } } )->next; # Restore old name for first checkin notice - $library_object->branchname( $old_branchname ); + $library_object->branchname($old_branchname); $library_object->store(); AddReturn( $item1->{barcode} ); - my $first_checkin_tt_letter = Koha::Notice::Messages->search( {}, { order_by => { -desc => 'message_id' } } )->next; -# + my $first_checkin_tt_letter = + Koha::Notice::Messages->search( {}, { order_by => { -desc => 'message_id' } } )->next; + # # Change branch name for second checkin notice $library_object->branchname($new_branchname); $library_object->store(); AddReturn( $item2->{barcode} ); - my $second_checkin_tt_letter = Koha::Notice::Messages->search( {}, { order_by => { -desc => 'message_id' } } )->next; + my $second_checkin_tt_letter = + Koha::Notice::Messages->search( {}, { order_by => { -desc => 'message_id' } } )->next; my $first_letter = qq[ $old_branchname @@ -1055,47 +1104,54 @@ $old_branchname $new_branchname ]; - - is( $first_checkout_letter->content, $first_letter, 'Verify first checkout letter' ); + is( $first_checkout_letter->content, $first_letter, 'Verify first checkout letter' ); is( $second_checkout_letter->content, $second_letter, 'Verify second checkout letter' ); - is( $first_checkin_letter->content, $first_letter, 'Verify first checkin letter' ); - is( $second_checkin_letter->content, $second_letter, 'Verify second checkin letter' ); + is( $first_checkin_letter->content, $first_letter, 'Verify first checkin letter' ); + is( $second_checkin_letter->content, $second_letter, 'Verify second checkin letter' ); - is( $first_checkout_tt_letter->content, $first_letter, 'Verify TT first checkout letter' ); + is( $first_checkout_tt_letter->content, $first_letter, 'Verify TT first checkout letter' ); is( $second_checkout_tt_letter->content, $second_letter, 'Verify TT second checkout letter' ); - is( $first_checkin_tt_letter->content, $first_letter, 'Verify TT first checkin letter' ); - is( $second_checkin_tt_letter->content, $second_letter, 'Verify TT second checkin letter' ); - }; + is( $first_checkin_tt_letter->content, $first_letter, 'Verify TT first checkin letter' ); + is( $second_checkin_tt_letter->content, $second_letter, 'Verify TT second checkin letter' ); + }; }; subtest 'loops' => sub { plan tests => 2; - my $code = "TEST"; + my $code = "TEST"; my $module = "TEST"; subtest 'primary key is AI' => sub { plan tests => 1; - my $patron_1 = $builder->build({ source => 'Borrower' }); - my $patron_2 = $builder->build({ source => 'Borrower' }); + my $patron_1 = $builder->build( { source => 'Borrower' } ); + my $patron_2 = $builder->build( { source => 'Borrower' } ); my $template = q|[% FOREACH patron IN borrowers %][% patron.surname %][% END %]|; reset_template( { template => $template, code => $code, module => $module } ); - my $letter = GetPreparedLetter( module => $module, letter_code => $code, loops => { borrowers => [ $patron_1->{borrowernumber}, $patron_2->{borrowernumber} ] } ); + my $letter = GetPreparedLetter( + module => $module, letter_code => $code, + loops => { borrowers => [ $patron_1->{borrowernumber}, $patron_2->{borrowernumber} ] } + ); my $expected_letter = join '', ( $patron_1->{surname}, $patron_2->{surname} ); is( $letter->{content}, $expected_letter, ); }; subtest 'foreign key is used' => sub { plan tests => 1; - my $patron_1 = $builder->build({ source => 'Borrower' }); - my $patron_2 = $builder->build({ source => 'Borrower' }); - my $checkout_1 = $builder->build({ source => 'Issue', value => { borrowernumber => $patron_1->{borrowernumber} } } ); - my $checkout_2 = $builder->build({ source => 'Issue', value => { borrowernumber => $patron_1->{borrowernumber} } } ); + my $patron_1 = $builder->build( { source => 'Borrower' } ); + my $patron_2 = $builder->build( { source => 'Borrower' } ); + my $checkout_1 = + $builder->build( { source => 'Issue', value => { borrowernumber => $patron_1->{borrowernumber} } } ); + my $checkout_2 = + $builder->build( { source => 'Issue', value => { borrowernumber => $patron_1->{borrowernumber} } } ); my $template = q|[% FOREACH checkout IN checkouts %][% checkout.issue_id %][% END %]|; reset_template( { template => $template, code => $code, module => $module } ); - my $letter = GetPreparedLetter( module => $module, letter_code => $code, loops => { issues => [ $checkout_1->{itemnumber}, $checkout_2->{itemnumber} ] } ); + my $letter = GetPreparedLetter( + module => $module, letter_code => $code, + loops => { issues => [ $checkout_1->{itemnumber}, $checkout_2->{itemnumber} ] } + ); my $expected_letter = join '', ( $checkout_1->{issue_id}, $checkout_2->{issue_id} ); is( $letter->{content}, $expected_letter, ); }; @@ -1112,9 +1168,7 @@ subtest 'add_tt_filters' => sub { value => { surname => "with_punctuation_" } } ); - my $biblio = $builder->build_object( - { class => 'Koha::Biblios', value => { title => "with_punctuation_" } } - ); + my $biblio = $builder->build_object( { class => 'Koha::Biblios', value => { title => "with_punctuation_" } } ); my $biblioitem = $builder->build_object( { class => 'Koha::Biblioitems', @@ -1137,35 +1191,37 @@ subtest 'add_tt_filters' => sub { } ); my $expected_letter = q|patron=with_punctuation_;biblio=with_punctuation;biblioitems=with_punctuation|; - is( $letter->{content}, $expected_letter, "Pre-processing should call TT plugin to remove punctuation if table is biblio or biblioitems"); + is( + $letter->{content}, $expected_letter, + "Pre-processing should call TT plugin to remove punctuation if table is biblio or biblioitems" + ); }; subtest 'Handle includes' => sub { plan tests => 1; - my $cgi = CGI->new(); + my $cgi = CGI->new(); my $code = 'TEST_INCLUDE'; my $account = - $builder->build_object( { class => 'Koha::Account::Lines', value => { credit_type_code => 'PAYMENT', status => 'CANCELLED' } } ); + $builder->build_object( + { class => 'Koha::Account::Lines', value => { credit_type_code => 'PAYMENT', status => 'CANCELLED' } } ); my $template = <<EOF; [%- USE Price -%] [%- PROCESS 'accounts.inc' -%] [%- PROCESS account_type_description account=credit -%] EOF - reset_template({ template => $template, code => $code, module => 'test' }); + reset_template( { template => $template, code => $code, module => 'test' } ); my $letter = GetPreparedLetter( module => 'test', letter_code => $code, - tables => { - credits => $account->accountlines_id - } + tables => { credits => $account->accountlines_id } ); - is($letter->{content},'<span>Payment</span><span> (Cancelled)</span>', "Include used in notice"); + is( $letter->{content}, '<span>Payment</span><span> (Cancelled)</span>', "Include used in notice" ); }; subtest 'Dates formatting' => sub { plan tests => 1; my $code = 'TEST_DATE'; - t::lib::Mocks::mock_preference('dateformat', 'metric'); # MM/DD/YYYY + t::lib::Mocks::mock_preference( 'dateformat', 'metric' ); # MM/DD/YYYY my $biblio = $builder->build_object( { class => 'Koha::Biblios', @@ -1191,15 +1247,16 @@ subtest 'Dates formatting' => sub { [% KohaDates.output_preference( str => biblio.timestamp, dateformat => 'iso' ) %] [% KohaDates.output_preference( str => biblio.timestamp, dateformat => 'iso', dateonly => 1 ) %] EOF - reset_template({ template => $template, code => $code, module => 'test' }); + reset_template( { template => $template, code => $code, module => 'test' } ); my $letter = GetPreparedLetter( - module => 'test', + module => 'test', letter_code => $code, - tables => { + tables => { biblio => $biblio->biblionumber, } ); - my $expected_content = sprintf("%s\n%s\n%s\n\n%s\n%s\n%s\n%s\n%s\n\n%s\n%s\n%s\n", + my $expected_content = sprintf( + "%s\n%s\n%s\n\n%s\n%s\n%s\n%s\n%s\n\n%s\n%s\n%s\n", '2018-12-13 20:21:22', '13/12/2018', '13/12/2018 20:21', @@ -1220,7 +1277,7 @@ EOF subtest 'KohaDates::dt_from_string' => sub { plan tests => 1; my $code = 'TEST_DATE'; - t::lib::Mocks::mock_preference('dateformat', 'metric'); # MM/DD/YYYY + t::lib::Mocks::mock_preference( 'dateformat', 'metric' ); # MM/DD/YYYY my $biblio = $builder->build_object( { class => 'Koha::Biblios', @@ -1232,11 +1289,11 @@ subtest 'KohaDates::dt_from_string' => sub { ); my $template = q{[% USE KohaDates %][% KohaDates.datetime_from_string('2000-12-01').dmy %]}; - reset_template({ template => $template, code => $code, module => 'test' }); + reset_template( { template => $template, code => $code, module => 'test' } ); my $letter = GetPreparedLetter( - module => 'test', + module => 'test', letter_code => $code, - tables => { + tables => { biblio => $biblio->biblionumber, } ); @@ -1245,13 +1302,13 @@ subtest 'KohaDates::dt_from_string' => sub { subtest 'Execute TT process in a DB transaction' => sub { plan tests => 2; - my $code = 'TEST_TXN'; - my $library = $builder->build_object( { class => 'Koha::Libraries' } ); + my $code = 'TEST_TXN'; + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); my $template = <<EOF; =[% branch.branchcode %]= [%~ branch.delete ~%] EOF - reset_template({ template => $template, code => $code, module => 'test' }); + reset_template( { template => $template, code => $code, module => 'test' } ); my $letter = GetPreparedLetter( module => 'test', letter_code => $code, @@ -1260,8 +1317,8 @@ EOF } ); my $branchcode = $library->branchcode; - like($letter->{content}, qr{=$branchcode=}, 'content generated with the library'); - is( ref($library->get_from_storage), 'Koha::Library', 'calling ->delete on the object has not been comitted'); + like( $letter->{content}, qr{=$branchcode=}, 'content generated with the library' ); + is( ref( $library->get_from_storage ), 'Koha::Library', 'calling ->delete on the object has not been comitted' ); }; @@ -1270,20 +1327,20 @@ subtest '_process_letter croaks on parsing error' => sub { plan tests => 1; my $params = { - code => 'TEST_CROAK', + code => 'TEST_CROAK', substitute => { count => 42 }, }; my $tt_template = q|[% IF %]|; eval { process_letter( { template => $tt_template, %$params } ) }; - like($@, qr{^ERROR PROCESSING TEMPLATE: }); + like( $@, qr{^ERROR PROCESSING TEMPLATE: } ); }; sub reset_template { - my ( $params ) = @_; - my $template = $params->{template}; - my $code = $params->{code}; - my $module = $params->{module} || 'test_module'; + my ($params) = @_; + my $template = $params->{template}; + my $code = $params->{code}; + my $module = $params->{module} || 'test_module'; Koha::Notice::Templates->search( { code => $code } )->delete; Koha::Notice::Template->new( @@ -1308,7 +1365,7 @@ sub process_letter { my $module = $params->{module} || 'test_module'; my $branchcode = $params->{branchcode}; - reset_template( $params ); + reset_template($params); my $letter = C4::Letters::GetPreparedLetter( module => $module, diff --git a/t/db_dependent/LibraryGroups.t b/t/db_dependent/LibraryGroups.t index 00e699bd95..c190a334bf 100755 --- a/t/db_dependent/LibraryGroups.t +++ b/t/db_dependent/LibraryGroups.t @@ -34,27 +34,30 @@ my $library6 = $builder->build( { source => 'Branch' } ); my $library7 = $builder->build( { source => 'Branch' } ); my $root_group = - Koha::Library::Group->new( { title => "Test root group" } )->store(); + Koha::Library::Group->new( { title => "Test root group" } )->store(); my @root_groups = Koha::Library::Groups->get_root_groups->as_list; -my $in_list = any { $_->id eq $root_group->id } @root_groups; -ok( $in_list, 'New root group is in the list returned by the get_root_groups method'); +my $in_list = any { $_->id eq $root_group->id } @root_groups; +ok( $in_list, 'New root group is in the list returned by the get_root_groups method' ); -my $groupA = Koha::Library::Group->new({ parent_id => $root_group->id, title => 'Group A' })->store(); -my $groupA1 = Koha::Library::Group->new({ parent_id => $groupA->id, title => 'Group A1' })->store(); -my $groupA2 = Koha::Library::Group->new({ parent_id => $groupA->id, title => 'Group A2' })->store(); -my $groupB = Koha::Library::Group->new({ parent_id => $root_group->id, title => 'Group B' })->store(); +my $groupA = Koha::Library::Group->new( { parent_id => $root_group->id, title => 'Group A' } )->store(); +my $groupA1 = Koha::Library::Group->new( { parent_id => $groupA->id, title => 'Group A1' } )->store(); +my $groupA2 = Koha::Library::Group->new( { parent_id => $groupA->id, title => 'Group A2' } )->store(); +my $groupB = Koha::Library::Group->new( { parent_id => $root_group->id, title => 'Group B' } )->store(); -my $groupA_library1 = Koha::Library::Group->new({ parent_id => $groupA->id, branchcode => $library1->{branchcode} })->store(); -my $groupB_library1 = Koha::Library::Group->new({ parent_id => $groupB->id, branchcode => $library1->{branchcode} })->store(); -my $groupA1_library2 = Koha::Library::Group->new({ parent_id => $groupA1->id, branchcode => $library2->{branchcode} })->store(); +my $groupA_library1 = + Koha::Library::Group->new( { parent_id => $groupA->id, branchcode => $library1->{branchcode} } )->store(); +my $groupB_library1 = + Koha::Library::Group->new( { parent_id => $groupB->id, branchcode => $library1->{branchcode} } )->store(); +my $groupA1_library2 = + Koha::Library::Group->new( { parent_id => $groupA1->id, branchcode => $library2->{branchcode} } )->store(); my @children = $root_group->children()->as_list(); is( $children[0]->id, $groupA->id, 'Child of root group set correctly' ); @children = $groupA->children()->as_list(); -is( $children[1]->id, $groupA1->id, 'Child 1 of 2nd level group set correctly' ); -is( $children[2]->id, $groupA2->id, 'Child 2 of 2nd level group set correctly' ); +is( $children[1]->id, $groupA1->id, 'Child 1 of 2nd level group set correctly' ); +is( $children[2]->id, $groupA2->id, 'Child 2 of 2nd level group set correctly' ); is( $children[0]->id, $groupA_library1->id, 'Child 3 of 2nd level group set correctly' ); is( $children[0]->branchcode, $groupA_library1->branchcode, 'Child 3 is correctly set as leaf node' ); @@ -63,26 +66,32 @@ is( $children[0]->branchcode, $groupA_library1->branchcode, 'Child 3 is correctl is( $children[0]->branchcode, $library2->{branchcode}, 'Child 1 of 3rd level group correctly set as leaf node' ); my $library = $groupA_library1->library(); -is( ref( $library ), 'Koha::Library', 'Method library returns a Koha::Library object' ); -is( $library->id, $groupA_library1->branchcode, 'Branchcode for fetched library matches' ); +is( ref($library), 'Koha::Library', 'Method library returns a Koha::Library object' ); +is( $library->id, $groupA_library1->branchcode, 'Branchcode for fetched library matches' ); my @libraries_not_direct_children = $groupA->libraries_not_direct_children->as_list; $in_list = any { $_->id eq $groupA_library1->branchcode } @libraries_not_direct_children; -ok( !$in_list, 'Method libraries_not_direct_children returns all libraries not direct descendants of group, library 1 is not in the list'); +ok( + !$in_list, + 'Method libraries_not_direct_children returns all libraries not direct descendants of group, library 1 is not in the list' +); $in_list = any { $_->id eq $groupA1_library2->branchcode } @libraries_not_direct_children; -ok( $in_list, 'Method libraries_not_direct_children returns all libraries not direct descendants of group, library 2 is in the list'); +ok( + $in_list, + 'Method libraries_not_direct_children returns all libraries not direct descendants of group, library 2 is in the list' +); subtest 'Koha::Library->library_groups' => sub { plan tests => 4; my $library3 = Koha::Libraries->find( $library3->{branchcode} ); - my $groups = $library3->library_groups; - is( ref( $groups ), 'Koha::Library::Groups', 'Koha::Library->library_groups should return Koha::Library::Groups' ); - is( $groups->count, 0, 'Library 3 should not be part of any groups'); + my $groups = $library3->library_groups; + is( ref($groups), 'Koha::Library::Groups', 'Koha::Library->library_groups should return Koha::Library::Groups' ); + is( $groups->count, 0, 'Library 3 should not be part of any groups' ); my $library1 = Koha::Libraries->find( $library1->{branchcode} ); $groups = $library1->library_groups; - is( ref( $groups ), 'Koha::Library::Groups', 'Koha::Library->library_groups should return Koha::Library::Groups' ); - is( $groups->count, 2, 'Library 1 should be part of 2 groups' ); + is( ref($groups), 'Koha::Library::Groups', 'Koha::Library->library_groups should return Koha::Library::Groups' ); + is( $groups->count, 2, 'Library 1 should be part of 2 groups' ); }; # root_group @@ -119,47 +128,60 @@ subtest 'Koha::Library::Group->get_search_groups' => sub { $groupA = Koha::Library::Groups->find( $groupA->id ); $groupB = Koha::Library::Groups->find( $groupB->id ); - my @groups = Koha::Library::Groups->get_search_groups({ interface => 'opac' })->as_list; + my @groups = Koha::Library::Groups->get_search_groups( { interface => 'opac' } )->as_list; is_deeply( $groups[0]->unblessed, $groupA->unblessed, 'Get search groups opac should return enabled group' ); - @groups = Koha::Library::Groups->get_search_groups({ interface => 'staff' })->as_list; + @groups = Koha::Library::Groups->get_search_groups( { interface => 'staff' } )->as_list; is_deeply( $groups[0]->unblessed, $groupB->unblessed, 'Get search groups staff should return enabled group' ); }; my $groupX = Koha::Library::Group->new( { title => "Group X" } )->store(); -my $groupX_library1 = Koha::Library::Group->new({ parent_id => $groupX->id, branchcode => $library1->{branchcode} })->store(); -my $groupX_library2 = Koha::Library::Group->new({ parent_id => $groupX->id, branchcode => $library2->{branchcode} })->store(); -my $groupX1 = Koha::Library::Group->new({ parent_id => $groupX->id, title => 'Group X1' })->store(); -my $groupX1_library3 = Koha::Library::Group->new({ parent_id => $groupX1->id, branchcode => $library3->{branchcode} })->store(); -my $groupX1_library4 = Koha::Library::Group->new({ parent_id => $groupX1->id, branchcode => $library4->{branchcode} })->store(); -my $groupX2 = Koha::Library::Group->new({ parent_id => $groupX->id, title => 'Group X2' })->store(); -my $groupX2_library5 = Koha::Library::Group->new({ parent_id => $groupX2->id, branchcode => $library5->{branchcode} })->store(); -my $groupX2_library6 = Koha::Library::Group->new({ parent_id => $groupX2->id, branchcode => $library6->{branchcode} })->store(); +my $groupX_library1 = + Koha::Library::Group->new( { parent_id => $groupX->id, branchcode => $library1->{branchcode} } )->store(); +my $groupX_library2 = + Koha::Library::Group->new( { parent_id => $groupX->id, branchcode => $library2->{branchcode} } )->store(); +my $groupX1 = Koha::Library::Group->new( { parent_id => $groupX->id, title => 'Group X1' } )->store(); +my $groupX1_library3 = + Koha::Library::Group->new( { parent_id => $groupX1->id, branchcode => $library3->{branchcode} } )->store(); +my $groupX1_library4 = + Koha::Library::Group->new( { parent_id => $groupX1->id, branchcode => $library4->{branchcode} } )->store(); +my $groupX2 = Koha::Library::Group->new( { parent_id => $groupX->id, title => 'Group X2' } )->store(); +my $groupX2_library5 = + Koha::Library::Group->new( { parent_id => $groupX2->id, branchcode => $library5->{branchcode} } )->store(); +my $groupX2_library6 = + Koha::Library::Group->new( { parent_id => $groupX2->id, branchcode => $library6->{branchcode} } )->store(); -my @branchcodes = sort( $library1->{branchcode}, $library2->{branchcode} ); +my @branchcodes = sort( $library1->{branchcode}, $library2->{branchcode} ); my @group_branchcodes = sort( map { $_->branchcode } $groupX->libraries->as_list ); is_deeply( \@branchcodes, \@group_branchcodes, "Group libraries are returned correctly" ); -is( ref($groupX->libraries), 'Koha::Libraries', '->libraries should return a Koha::Libraries iterator' ); +is( ref( $groupX->libraries ), 'Koha::Libraries', '->libraries should return a Koha::Libraries iterator' ); -@branchcodes = sort( $library1->{branchcode}, $library2->{branchcode}, $library3->{branchcode}, $library4->{branchcode}, $library5->{branchcode}, $library6->{branchcode} ); +@branchcodes = sort( $library1->{branchcode}, $library2->{branchcode}, $library3->{branchcode}, $library4->{branchcode}, + $library5->{branchcode}, $library6->{branchcode} ); @group_branchcodes = sort( map { $_->branchcode } $groupX->all_libraries ); is_deeply( \@branchcodes, \@group_branchcodes, "Group all_libraries are returned correctly" ); -is( ref(($groupX->all_libraries)[0]), 'Koha::Library', '->all_libraries should return a list of Koha::Library - in the future it should be fixed to return a Koha::Libraries iterator instead'); # FIXME +is( + ref( ( $groupX->all_libraries )[0] ), 'Koha::Library', + '->all_libraries should return a list of Koha::Library - in the future it should be fixed to return a Koha::Libraries iterator instead' +); # FIXME subtest 'Koha::Library::Groups->get_root_ancestor' => sub { plan tests => 2; my $groupY = Koha::Library::Group->new( { title => "Group Y" } )->store(); - my $groupY_library1 = Koha::Library::Group->new({ parent_id => $groupY->id, branchcode => $library1->{branchcode} })->store(); + my $groupY_library1 = + Koha::Library::Group->new( { parent_id => $groupY->id, branchcode => $library1->{branchcode} } )->store(); my $groupY1 = Koha::Library::Group->new( { parent_id => $groupY->id, title => "Group Y1" } )->store(); - my $groupY1_library2 = Koha::Library::Group->new({ parent_id => $groupY1->id, branchcode => $library2->{branchcode} })->store(); - my $groupZ = Koha::Library::Group->new({ title => "Group Z" })->store(); - my $groupZ1 = Koha::Library::Group->new({ parent_id => $groupZ->id, title => "Group Z1" })->store(); - my $groupZ2 = Koha::Library::Group->new({ parent_id => $groupZ1->id, title => "Group Z2" })->store(); - my $groupZ2_library2 = Koha::Library::Group->new({ parent_id => $groupZ2->id, branchcode => $library2->{branchcode} })->store(); + my $groupY1_library2 = + Koha::Library::Group->new( { parent_id => $groupY1->id, branchcode => $library2->{branchcode} } )->store(); + my $groupZ = Koha::Library::Group->new( { title => "Group Z" } )->store(); + my $groupZ1 = Koha::Library::Group->new( { parent_id => $groupZ->id, title => "Group Z1" } )->store(); + my $groupZ2 = Koha::Library::Group->new( { parent_id => $groupZ1->id, title => "Group Z2" } )->store(); + my $groupZ2_library2 = + Koha::Library::Group->new( { parent_id => $groupZ2->id, branchcode => $library2->{branchcode} } )->store(); - my $ancestor1 = Koha::Library::Groups->get_root_ancestor($groupY1_library2->unblessed); - my $ancestor2 = Koha::Library::Groups->get_root_ancestor($groupZ2_library2->unblessed); + my $ancestor1 = Koha::Library::Groups->get_root_ancestor( $groupY1_library2->unblessed ); + my $ancestor2 = Koha::Library::Groups->get_root_ancestor( $groupZ2_library2->unblessed ); - is($ancestor1->id, $groupY->id, "Get root ancestor should return group's root ancestor"); - ok($ancestor1->id ne $ancestor2->id, "Both root groups should have different ids"); + is( $ancestor1->id, $groupY->id, "Get root ancestor should return group's root ancestor" ); + ok( $ancestor1->id ne $ancestor2->id, "Both root groups should have different ids" ); }; diff --git a/t/db_dependent/Linker_Default.t b/t/db_dependent/Linker_Default.t index 9a878da8dc..9e92920df2 100755 --- a/t/db_dependent/Linker_Default.t +++ b/t/db_dependent/Linker_Default.t @@ -33,7 +33,7 @@ BEGIN { # Mock C4::Heading->authorities() so tests will all pass. # This completely bypasses any search engine calls. -my $authid=0; +my $authid = 0; my $mock_heading = Test::MockModule->new('C4::Heading'); $mock_heading->mock( authorities => sub { return [ { authid => $authid++ } ]; } ); @@ -44,20 +44,21 @@ $schema->storage->txn_begin; subtest 'Test caching in get_link and update_cache' => sub { plan tests => 18; - my @tags = C4::Context->preference('marcflavour') eq 'UNIMARC' ? (601,'j',602,'a') : (650,'a',655,'a'); + my @tags = C4::Context->preference('marcflavour') eq 'UNIMARC' ? ( 601, 'j', 602, 'a' ) : ( 650, 'a', 655, 'a' ); + + my $subject_field = MARC::Field->new( $tags[0], 0, 2, $tags[1] => 'Science fiction' ); + my $subject_field2 = MARC::Field->new( $tags[0], 0, 2, $tags[1] => 'Science fiction' ); + my $subject_field3 = MARC::Field->new( $tags[0], 0, 0, $tags[1] => 'Science fiction' ); + my $subject_field4 = MARC::Field->new( $tags[0], 0, 7, $tags[1] => 'Science fiction', '2' => 'bnb' ); + my $subject_field5 = MARC::Field->new( $tags[0], 0, 7, $tags[1] => 'Science fiction', '2' => 'sao' ); + my $subject_field6 = MARC::Field->new( $tags[0], 0, 7, $tags[1] => 'Science fiction', '2' => 'sao' ); + my $subject_field7 = MARC::Field->new( $tags[0], 0, 4, $tags[1] => 'Science fiction' ); + my $subject_field8 = MARC::Field->new( $tags[0], 0, 7, $tags[1] => 'Science fiction', '2' => 'oth' ); + my $subject_field9 = MARC::Field->new( $tags[0], 0, 3, $tags[1] => 'Science fiction' ); + my $genre_field = MARC::Field->new( $tags[2], 0, 2, $tags[3] => 'Science fiction' ); - my $subject_field = MARC::Field->new($tags[0],0,2,$tags[1]=>'Science fiction'); - my $subject_field2 = MARC::Field->new($tags[0],0,2,$tags[1]=>'Science fiction'); - my $subject_field3 = MARC::Field->new($tags[0],0,0,$tags[1]=>'Science fiction'); - my $subject_field4 = MARC::Field->new($tags[0],0,7,$tags[1]=>'Science fiction','2'=>'bnb'); - my $subject_field5 = MARC::Field->new($tags[0],0,7,$tags[1]=>'Science fiction','2'=>'sao'); - my $subject_field6 = MARC::Field->new($tags[0],0,7,$tags[1]=>'Science fiction','2'=>'sao'); - my $subject_field7 = MARC::Field->new($tags[0],0,4,$tags[1]=>'Science fiction'); - my $subject_field8 = MARC::Field->new($tags[0],0,7,$tags[1]=>'Science fiction','2'=>'oth'); - my $subject_field9 = MARC::Field->new($tags[0],0,3,$tags[1]=>'Science fiction'); - my $genre_field = MARC::Field->new($tags[2],0,2,$tags[3]=>'Science fiction'); # Can we build a heading from it? - my $subject_heading = C4::Heading->new_from_field( $subject_field, q{} ); + my $subject_heading = C4::Heading->new_from_field( $subject_field, q{} ); my $subject_heading2 = C4::Heading->new_from_field( $subject_field2, q{} ); my $subject_heading3 = C4::Heading->new_from_field( $subject_field3, q{} ); my $subject_heading4 = C4::Heading->new_from_field( $subject_field4, q{} ); @@ -66,64 +67,86 @@ subtest 'Test caching in get_link and update_cache' => sub { my $subject_heading7 = C4::Heading->new_from_field( $subject_field7, q{} ); my $subject_heading8 = C4::Heading->new_from_field( $subject_field8, q{} ); my $subject_heading9 = C4::Heading->new_from_field( $subject_field9, q{} ); - my $genre_heading = C4::Heading->new_from_field( $genre_field, q{} ); + my $genre_heading = C4::Heading->new_from_field( $genre_field, q{} ); - t::lib::Mocks::mock_preference('LinkerConsiderThesaurus',1); + t::lib::Mocks::mock_preference( 'LinkerConsiderThesaurus', 1 ); # Now test to see if C4::Linker can find it. my $linker = C4::Linker::Default->new(); $linker->get_link($subject_heading); - is( keys %{$linker->{cache}},1, "First term added to cache"); + is( keys %{ $linker->{cache} }, 1, "First term added to cache" ); $linker->get_link($genre_heading); - is( keys %{$linker->{cache}},2, "Second (matching) term added to cache because of different type"); + is( keys %{ $linker->{cache} }, 2, "Second (matching) term added to cache because of different type" ); $linker->get_link($subject_heading2); - is( keys %{$linker->{cache}},2, "Third (matching) term not added to cache because of matching type"); + is( keys %{ $linker->{cache} }, 2, "Third (matching) term not added to cache because of matching type" ); $linker->get_link($subject_heading3); - is( keys %{$linker->{cache}},3, "Fourth (matching) term added to cache because of different thesaurus (lcsh)"); + is( keys %{ $linker->{cache} }, 3, "Fourth (matching) term added to cache because of different thesaurus (lcsh)" ); $linker->get_link($subject_heading4); - is( keys %{$linker->{cache}},4, "Fifth (matching) term added to cache because of different thesaurus (bnb)"); + is( keys %{ $linker->{cache} }, 4, "Fifth (matching) term added to cache because of different thesaurus (bnb)" ); $linker->get_link($subject_heading5); - is( keys %{$linker->{cache}},5, "Sixth (matching) term added to cache because of different thesaurus (sao)"); + is( keys %{ $linker->{cache} }, 5, "Sixth (matching) term added to cache because of different thesaurus (sao)" ); $linker->get_link($subject_heading6); - is( keys %{$linker->{cache}},5, "Seventh (matching) term not added to cache because of matching type and thesaurus (sao)"); + is( + keys %{ $linker->{cache} }, 5, + "Seventh (matching) term not added to cache because of matching type and thesaurus (sao)" + ); $linker->get_link($subject_heading7); - is( keys %{$linker->{cache}},6, "Eighth (matching) term added to cache because of thesaurus source not specified (2nd indicator is 4)"); + is( + keys %{ $linker->{cache} }, 6, + "Eighth (matching) term added to cache because of thesaurus source not specified (2nd indicator is 4)" + ); - t::lib::Mocks::mock_preference('LinkerConsiderThesaurus',0); + t::lib::Mocks::mock_preference( 'LinkerConsiderThesaurus', 0 ); $linker->get_link($subject_heading); - is( keys %{$linker->{cache}},7, "First term added to cache because cache key now has 'notconsidered' for thesaurus"); + is( + keys %{ $linker->{cache} }, 7, + "First term added to cache because cache key now has 'notconsidered' for thesaurus" + ); $linker->get_link($subject_heading8); - is( keys %{$linker->{cache}},7, "Ninth (matching) term not added to cache because thesaurus differs but is not considered"); + is( + keys %{ $linker->{cache} }, 7, + "Ninth (matching) term not added to cache because thesaurus differs but is not considered" + ); $linker->get_link($subject_heading9); - is( keys %{$linker->{cache}},7, "Tenth (matching) term not added to cache because thesaurus differs but is not considered"); + is( + keys %{ $linker->{cache} }, 7, + "Tenth (matching) term not added to cache because thesaurus differs but is not considered" + ); - t::lib::Mocks::mock_preference('LinkerConsiderThesaurus',1); + t::lib::Mocks::mock_preference( 'LinkerConsiderThesaurus', 1 ); - $linker->update_cache($subject_heading,32); - is( $linker->{cache}->{$subject_heading->search_form.$subject_heading->auth_type.$subject_heading->{'thesaurus'}}->{authid}, 32, "Linker cache is correctly updated by 'update_cache'"); + $linker->update_cache( $subject_heading, 32 ); + is( $linker->{cache} + ->{ $subject_heading->search_form . $subject_heading->auth_type . $subject_heading->{'thesaurus'} } + ->{authid}, 32, "Linker cache is correctly updated by 'update_cache'" ); my ( $authid, undef ) = $linker->get_link($subject_heading); is( $authid, 32, "Correct id is retrieved from the cache" ); ( $authid, undef ) = $linker->get_link($genre_heading); - isnt( $authid, 32, "Genre term is not updated by update_cache"); + isnt( $authid, 32, "Genre term is not updated by update_cache" ); ( $authid, undef ) = $linker->get_link($subject_heading5); is( $authid, 4, "Correct id for sao term is retrieved from the cache" ); - $linker->update_cache($subject_heading4,78); - is( $linker->{cache}->{$subject_heading4->search_form.$subject_heading4->auth_type.$subject_heading4->{'thesaurus'}}->{authid}, 78, "Linker cache for the bnb record is correctly updated by 'update_cache'"); + $linker->update_cache( $subject_heading4, 78 ); + is( $linker->{cache} + ->{ $subject_heading4->search_form . $subject_heading4->auth_type . $subject_heading4->{'thesaurus'} } + ->{authid}, 78, "Linker cache for the bnb record is correctly updated by 'update_cache'" ); - t::lib::Mocks::mock_preference('LinkerConsiderThesaurus',0); - $linker->update_cache($subject_heading,32); - is( $linker->{cache}->{$subject_heading->search_form.$subject_heading->auth_type.'notconsidered'}->{authid}, 32, "Linker cache is correctly updated by 'update_cache'"); + t::lib::Mocks::mock_preference( 'LinkerConsiderThesaurus', 0 ); + $linker->update_cache( $subject_heading, 32 ); + is( + $linker->{cache}->{ $subject_heading->search_form . $subject_heading->auth_type . 'notconsidered' }->{authid}, + 32, "Linker cache is correctly updated by 'update_cache'" + ); ( $authid, undef ) = $linker->get_link($subject_heading); is( $authid, 32, "Correct id is retrieved from the cache" ); diff --git a/t/db_dependent/Linker_FirstMatch.t b/t/db_dependent/Linker_FirstMatch.t index d4d211a9dc..c411c37453 100755 --- a/t/db_dependent/Linker_FirstMatch.t +++ b/t/db_dependent/Linker_FirstMatch.t @@ -62,11 +62,7 @@ sub run_tests { $builder->delete( { source => 'AuthHeader' } ); - my $auth_header = $builder->build( - { - source => 'AuthHeader' - } - ); + my $auth_header = $builder->build( { source => 'AuthHeader' } ); $authid = $auth_header->{authid}; @@ -76,11 +72,7 @@ sub run_tests { my $fake_marc = $auth->as_usmarc(); my $fake_xml = $auth->as_xml($authid); - my $auth_header_record = $schema->resultset('AuthHeader')->find( - { - authid => $authid - } - ); + my $auth_header_record = $schema->resultset('AuthHeader')->find( { authid => $authid } ); $auth_header_record->marcxml($fake_xml); $auth_header_record->marc($fake_marc); $auth_header_record->update; @@ -89,8 +81,7 @@ sub run_tests { my $fieldmatch; if ( C4::Context->preference('MARCFlavour') eq 'UNIMARC' ) { $fieldmatch = '2..'; - } - else { + } else { $fieldmatch = '1..'; } my $bibfield = $auth->field($fieldmatch); @@ -109,9 +100,7 @@ sub run_tests { # Can we build a heading from it? my $heading; ok( - defined( - $heading = C4::Heading->new_from_field( $new_bibfield, q{} ) - ), + defined( $heading = C4::Heading->new_from_field( $new_bibfield, q{} ) ), 'Creating heading from bib field' ); @@ -130,7 +119,7 @@ sub run_tests { sub get_authority_record { my ( $marc_flavour, $auth_id ) = @_; my $main_heading_field = ( $marc_flavour eq 'UNIMARC' ) ? '200' : '100'; - my $auth = MARC::Record->new(); + my $auth = MARC::Record->new(); $auth->append_fields( MARC::Field->new( '001', $auth_id ), MARC::Field->new( diff --git a/t/db_dependent/Log.t b/t/db_dependent/Log.t index 2aaad4bdd0..13e1ab464a 100755 --- a/t/db_dependent/Log.t +++ b/t/db_dependent/Log.t @@ -19,18 +19,18 @@ use Data::Dumper qw( Dumper ); use Test::More tests => 7; use C4::Context; -use C4::Log qw( logaction cronlogaction ); +use C4::Log qw( logaction cronlogaction ); use C4::Auth qw( checkpw ); use Koha::Database; use Koha::ActionLogs; -use t::lib::Mocks qw/mock_preference/; # to mock CronjobLog +use t::lib::Mocks qw/mock_preference/; # to mock CronjobLog use t::lib::TestBuilder; use JSON qw( decode_json ); # Make sure we can rollback. -our $schema = Koha::Database->new->schema; +our $schema = Koha::Database->new->schema; $schema->storage->txn_begin; subtest 'Existing tests' => sub { @@ -39,24 +39,24 @@ subtest 'Existing tests' => sub { my $success; eval { # FIXME: are we sure there is an member number 1? - logaction("MEMBERS","MODIFY",1,"test operation"); + logaction( "MEMBERS", "MODIFY", 1, "test operation" ); $success = 1; } or do { diag($@); $success = 0; }; - ok($success, "logaction seemed to work"); + ok( $success, "logaction seemed to work" ); # We want numbers to be the same between runs. Koha::ActionLogs->search->delete; - t::lib::Mocks::mock_preference('CronjobLog',0); + t::lib::Mocks::mock_preference( 'CronjobLog', 0 ); cronlogaction(); - is(Koha::ActionLogs->search({ module => 'CRONJOBS' })->count,0,"Cronjob not logged as expected."); + is( Koha::ActionLogs->search( { module => 'CRONJOBS' } )->count, 0, "Cronjob not logged as expected." ); - t::lib::Mocks::mock_preference('CronjobLog',1); + t::lib::Mocks::mock_preference( 'CronjobLog', 1 ); cronlogaction(); - is(Koha::ActionLogs->search({ module => 'CRONJOBS' })->count,1,"Cronjob logged as expected."); + is( Koha::ActionLogs->search( { module => 'CRONJOBS' } )->count, 1, "Cronjob logged as expected." ); }; subtest 'logaction(): interface is correctly logged' => sub { @@ -65,55 +65,55 @@ subtest 'logaction(): interface is correctly logged' => sub { # No interface passed, using C4::Context->interface Koha::ActionLogs->search->delete; - C4::Context->interface( 'commandline' ); - logaction( "MEMBERS", "MODIFY", 1, "test operation"); + C4::Context->interface('commandline'); + logaction( "MEMBERS", "MODIFY", 1, "test operation" ); my $log = Koha::ActionLogs->search->next; - is( $log->interface, 'commandline', 'Interface correctly deduced (commandline)'); + is( $log->interface, 'commandline', 'Interface correctly deduced (commandline)' ); # No interface passed, using C4::Context->interface Koha::ActionLogs->search->delete; - C4::Context->interface( 'opac' ); - logaction( "MEMBERS", "MODIFY", 1, "test operation"); + C4::Context->interface('opac'); + logaction( "MEMBERS", "MODIFY", 1, "test operation" ); $log = Koha::ActionLogs->search->next; - is( $log->interface, 'opac', 'Interface correctly deduced (opac)'); + is( $log->interface, 'opac', 'Interface correctly deduced (opac)' ); # Explicit interfaces Koha::ActionLogs->search->delete; - C4::Context->interface( 'intranet' ); - logaction( "MEMBERS", "MODIFY", 1, 'test info', 'intranet'); + C4::Context->interface('intranet'); + logaction( "MEMBERS", "MODIFY", 1, 'test info', 'intranet' ); $log = Koha::ActionLogs->search->next; - is( $log->interface, 'intranet', 'Passed interface is respected (intranet)'); + is( $log->interface, 'intranet', 'Passed interface is respected (intranet)' ); # Explicit interfaces Koha::ActionLogs->search->delete; - C4::Context->interface( 'sip' ); - logaction( "MEMBERS", "MODIFY", 1, 'test info', 'sip'); + C4::Context->interface('sip'); + logaction( "MEMBERS", "MODIFY", 1, 'test info', 'sip' ); $log = Koha::ActionLogs->search->next; - is( $log->interface, 'sip', 'Passed interface is respected (sip)'); + is( $log->interface, 'sip', 'Passed interface is respected (sip)' ); }; subtest 'logaction / trace' => sub { plan tests => 2; - C4::Context->interface( 'intranet' ); - t::lib::Mocks::mock_preference('ActionLogsTraceDepth',0); + C4::Context->interface('intranet'); + t::lib::Mocks::mock_preference( 'ActionLogsTraceDepth', 0 ); - logaction( "MEMBERS", "MODIFY", 1, "test1"); - is( Koha::ActionLogs->search({ info => 'test1' })->last->trace, undef, 'No trace at level 0' ); - t::lib::Mocks::mock_preference('ActionLogsTraceDepth',2); - logaction( "MEMBERS", "MODIFY", 1, "test2"); - like( Koha::ActionLogs->search({ info => 'test2' })->last->trace, qr/("line":.*){2}/, 'Found two trace levels' ); + logaction( "MEMBERS", "MODIFY", 1, "test1" ); + is( Koha::ActionLogs->search( { info => 'test1' } )->last->trace, undef, 'No trace at level 0' ); + t::lib::Mocks::mock_preference( 'ActionLogsTraceDepth', 2 ); + logaction( "MEMBERS", "MODIFY", 1, "test2" ); + like( Koha::ActionLogs->search( { info => 'test2' } )->last->trace, qr/("line":.*){2}/, 'Found two trace levels' ); - t::lib::Mocks::mock_preference('ActionLogsTraceDepth',0); + t::lib::Mocks::mock_preference( 'ActionLogsTraceDepth', 0 ); }; subtest 'GDPR logging' => sub { plan tests => 6; my $builder = t::lib::TestBuilder->new; - my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); - t::lib::Mocks::mock_userenv({ patron => $patron }); + t::lib::Mocks::mock_userenv( { patron => $patron } ); logaction( 'AUTH', 'FAILURE', $patron->id, '', 'opac' ); my $logs = Koha::ActionLogs->search( { @@ -125,33 +125,35 @@ subtest 'GDPR logging' => sub { ); is( $logs->count, 1, 'We should find one auth failure' ); - t::lib::Mocks::mock_preference('AuthFailureLog', 1); + t::lib::Mocks::mock_preference( 'AuthFailureLog', 1 ); my $strong_password = 'N0tStr0ngAnyM0reN0w:)'; - $patron->set_password({ password => $strong_password }); - my @ret = checkpw( $patron->userid, 'WrongPassword', undef, undef, 1); + $patron->set_password( { password => $strong_password } ); + my @ret = checkpw( $patron->userid, 'WrongPassword', undef, undef, 1 ); is( $ret[0], 0, 'Authentication failed' ); + # Look for auth failure but NOT on patron id, pass userid in info parameter $logs = Koha::ActionLogs->search( { module => 'AUTH', action => 'FAILURE', - info => { -like => '%'.$patron->userid.'%' }, + info => { -like => '%' . $patron->userid . '%' }, } ); is( $logs->count, 1, 'We should find one auth failure with this userid' ); - t::lib::Mocks::mock_preference('AuthFailureLog', 0); - @ret = checkpw( $patron->userid, 'WrongPassword', undef, undef, 1); + t::lib::Mocks::mock_preference( 'AuthFailureLog', 0 ); + @ret = checkpw( $patron->userid, 'WrongPassword', undef, undef, 1 ); $logs = Koha::ActionLogs->search( { module => 'AUTH', action => 'FAILURE', - info => { -like => '%'.$patron->userid.'%' }, + info => { -like => '%' . $patron->userid . '%' }, } ); is( $logs->count, 1, 'Still only one failure with this userid' ); - t::lib::Mocks::mock_preference('AuthSuccessLog', 1); - @ret = checkpw( $patron->userid, $strong_password, undef, undef, 1); + t::lib::Mocks::mock_preference( 'AuthSuccessLog', 1 ); + @ret = checkpw( $patron->userid, $strong_password, undef, undef, 1 ); is( $ret[0], 1, 'Authentication succeeded' ); + # Now we can look for patron id $logs = Koha::ActionLogs->search( { @@ -169,30 +171,30 @@ subtest 'Reduce log size by unblessing Koha objects' => sub { plan tests => 7; my $builder = t::lib::TestBuilder->new; - my $item = $builder->build_sample_item; + my $item = $builder->build_sample_item; logaction( 'MY_MODULE', 'TEST01', $item->itemnumber, $item, 'opac' ); - my $str = Dumper($item->unblessed); - my $logs = Koha::ActionLogs->search({ module => 'MY_MODULE', action => 'TEST01', object => $item->itemnumber }); - is( $logs->count, 1, 'Action found' ); - is( length($logs->next->info), length($str), 'Length exactly identical' ); + my $str = Dumper( $item->unblessed ); + my $logs = Koha::ActionLogs->search( { module => 'MY_MODULE', action => 'TEST01', object => $item->itemnumber } ); + is( $logs->count, 1, 'Action found' ); + is( length( $logs->next->info ), length($str), 'Length exactly identical' ); logaction( 'CATALOGUING', 'MODIFY', $item->itemnumber, $item, 'opac', $item ); - $logs = Koha::ActionLogs->search({ module => 'CATALOGUING', action => 'MODIFY', object => $item->itemnumber }); - is( substr($logs->next->info, 0, 5), 'item ', 'Prefix item' ); - is( length($logs->reset->next->info), 5+length($str), 'Length + 5' ); + $logs = Koha::ActionLogs->search( { module => 'CATALOGUING', action => 'MODIFY', object => $item->itemnumber } ); + is( substr( $logs->next->info, 0, 5 ), 'item ', 'Prefix item' ); + is( length( $logs->reset->next->info ), 5 + length($str), 'Length + 5' ); - my $hold = $builder->build_object({ class => 'Koha::Holds' }); + my $hold = $builder->build_object( { class => 'Koha::Holds' } ); logaction( 'MY_CIRC_MODULE', 'TEST', $item->itemnumber, $hold, 'opac' ); - $logs = Koha::ActionLogs->search({ module => 'MY_CIRC_MODULE', action => 'TEST', object => $item->itemnumber }); - is( length($logs->next->info), length( Dumper($hold->unblessed)), 'Length of dumped unblessed hold' ); + $logs = Koha::ActionLogs->search( { module => 'MY_CIRC_MODULE', action => 'TEST', object => $item->itemnumber } ); + is( length( $logs->next->info ), length( Dumper( $hold->unblessed ) ), 'Length of dumped unblessed hold' ); logaction( 'MY_MODULE', 'TEST02', $item->itemnumber, [], 'opac' ); - $logs = Koha::ActionLogs->search({ module => 'MY_MODULE', action => 'TEST02', object => $item->itemnumber }); + $logs = Koha::ActionLogs->search( { module => 'MY_MODULE', action => 'TEST02', object => $item->itemnumber } ); like( $logs->next->info, qr/^ARRAY\(/, 'Dumped arrayref' ); logaction( 'MY_MODULE', 'TEST03', $item->itemnumber, $builder, 'opac' ); - $logs = Koha::ActionLogs->search({ module => 'MY_MODULE', action => 'TEST03', object => $item->itemnumber }); + $logs = Koha::ActionLogs->search( { module => 'MY_MODULE', action => 'TEST03', object => $item->itemnumber } ); like( $logs->next->info, qr/^t::lib::TestBuilder/, 'Dumped TestBuilder object' ); }; diff --git a/t/db_dependent/MarcModificationTemplates.t b/t/db_dependent/MarcModificationTemplates.t index 35adf6919d..da21466fec 100755 --- a/t/db_dependent/MarcModificationTemplates.t +++ b/t/db_dependent/MarcModificationTemplates.t @@ -11,7 +11,10 @@ use t::lib::Mocks; use_ok("MARC::Field"); use_ok("MARC::Record"); -use_ok('C4::MarcModificationTemplates', qw( AddModificationTemplate AddModificationTemplateAction GetModificationTemplateAction GetModificationTemplateActions ModModificationTemplateAction MoveModificationTemplateAction DelModificationTemplate DelModificationTemplateAction ModifyRecordWithTemplate GetModificationTemplates )); +use_ok( + 'C4::MarcModificationTemplates', + qw( AddModificationTemplate AddModificationTemplateAction GetModificationTemplateAction GetModificationTemplateActions ModModificationTemplateAction MoveModificationTemplateAction DelModificationTemplate DelModificationTemplateAction ModifyRecordWithTemplate GetModificationTemplates ) +); my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; @@ -23,117 +26,138 @@ $dbh->do(q|DELETE FROM marc_modification_templates|); my $template_id = AddModificationTemplate("template_name"); like( $template_id, qr|^\d+$|, "new template returns an id" ); -is( AddModificationTemplateAction( - $template_id, 'move_field', 1, - '464', 'u', '', '464', '3', - '', '', '', - '', '', '', '', '', '', - 'move first 464$u to 464$3' -), 1, "Add first action"); +is( + AddModificationTemplateAction( + $template_id, 'move_field', 1, + '464', 'u', '', '464', '3', + '', '', '', + '', '', '', '', '', '', + 'move first 464$u to 464$3' + ), + 1, + "Add first action" +); -is( AddModificationTemplateAction( - $template_id, 'update_field', 0, - '099', 't', 'LIV', '', '', - '', '', '', - 'if', '200', 'b', 'equals', 'Text', '', - 'Update field 099$t with value LIV if 200$b matches "Text"' -), 1, "Add second action"); +is( + AddModificationTemplateAction( + $template_id, 'update_field', 0, + '099', 't', 'LIV', '', '', + '', '', '', + 'if', '200', 'b', 'equals', 'Text', '', + 'Update field 099$t with value LIV if 200$b matches "Text"' + ), + 1, + "Add second action" +); -is( AddModificationTemplateAction( - $template_id, 'copy_field', 0, - '606', 'a', '', '607', 'a', - '', '', '', - 'unless', '606', 'a', 'not_equals', '^AJAX', '1', - 'Copy field 606$a to 607$a unless 606$a matches RegEx m^AJAX' -), 1, "Add third action"); +is( + AddModificationTemplateAction( + $template_id, 'copy_field', 0, + '606', 'a', '', '607', 'a', + '', '', '', + 'unless', '606', 'a', 'not_equals', '^AJAX', '1', + 'Copy field 606$a to 607$a unless 606$a matches RegEx m^AJAX' + ), + 1, + "Add third action" +); + +is( + AddModificationTemplateAction( + $template_id, 'add_field', 0, + '650', 'a', 'Additional', '', '', + '', '', '', + 'unless', '650', 'a', 'exists', '', '', + 'Add field 650$aAdditional unless 650$a exists' + ), + 1, + "Add fourth action" +); -is( AddModificationTemplateAction( - $template_id, 'add_field', 0, - '650', 'a', 'Additional', '', '', - '', '', '', - 'unless', '650', 'a', 'exists', '', '', - 'Add field 650$aAdditional unless 650$a exists' -), 1, "Add fourth action"); # Getter -my @actions = GetModificationTemplateActions( $template_id ); -is( @actions, 4, "4 actions are inserted"); +my @actions = GetModificationTemplateActions($template_id); +is( @actions, 4, "4 actions are inserted" ); -for my $action ( @actions ) { +for my $action (@actions) { isnt( GetModificationTemplateAction( $action->{mmta_id} ), undef, "action with id $action->{mmta_id} exists" ); } my $first_action = $actions[0]; -is( $first_action->{ordering}, 1, "test ordering for first action" ); -is( $first_action->{action}, 'move_field', "test action for first action" ); -is( $first_action->{from_field}, '464', "test from_field for first action" ); -is( $first_action->{from_subfield}, 'u', "test from_subfield for first action" ); -is( $first_action->{to_field}, '464', "test to_field for first action" ); -is( $first_action->{to_subfield}, '3', "test to_subfield for first action" ); +is( $first_action->{ordering}, 1, "test ordering for first action" ); +is( $first_action->{action}, 'move_field', "test action for first action" ); +is( $first_action->{from_field}, '464', "test from_field for first action" ); +is( $first_action->{from_subfield}, 'u', "test from_subfield for first action" ); +is( $first_action->{to_field}, '464', "test to_field for first action" ); +is( $first_action->{to_subfield}, '3', "test to_subfield for first action" ); my $second_action = $actions[1]; -is( $second_action->{ordering}, 2, "test ordering for second action" ); -is( $second_action->{action}, 'update_field', "test action for second action" ); -is( $second_action->{from_field}, '099',"test from_field for second action" ); -is( $second_action->{from_subfield}, 't', "test from_subfield for second action" ); -is( $second_action->{field_value}, 'LIV', "test firld_value for second action" ); -is( $second_action->{to_field}, '', "test to_field for second action" ); -is( $second_action->{to_subfield}, '', "test to_subfield for second action" ); -is( $second_action->{conditional}, 'if', "test conditional for second action" ); -is( $second_action->{conditional_field}, '200', "test conditional_field for second action" ); -is( $second_action->{conditional_subfield}, 'b', "test conditional_subfield for second action" ); -is( $second_action->{conditional_comparison}, 'equals', "test conditional_comparison for second action" ); +is( $second_action->{ordering}, 2, "test ordering for second action" ); +is( $second_action->{action}, 'update_field', "test action for second action" ); +is( $second_action->{from_field}, '099', "test from_field for second action" ); +is( $second_action->{from_subfield}, 't', "test from_subfield for second action" ); +is( $second_action->{field_value}, 'LIV', "test firld_value for second action" ); +is( $second_action->{to_field}, '', "test to_field for second action" ); +is( $second_action->{to_subfield}, '', "test to_subfield for second action" ); +is( $second_action->{conditional}, 'if', "test conditional for second action" ); +is( $second_action->{conditional_field}, '200', "test conditional_field for second action" ); +is( $second_action->{conditional_subfield}, 'b', "test conditional_subfield for second action" ); +is( $second_action->{conditional_comparison}, 'equals', "test conditional_comparison for second action" ); my $third_action = $actions[2]; -is( $third_action->{ordering}, 3, "test ordering for third action" ); -is( $third_action->{action}, 'copy_field', "test action for third action" ); -is( $third_action->{from_field}, '606', "test from_field for third action" ); -is( $third_action->{from_subfield}, 'a', "test from_subfield for third action" ); -is( $third_action->{to_field}, '607', "test to_field for third action" ); -is( $third_action->{to_subfield}, 'a', "test to_subfield for third action" ); -is( $third_action->{conditional}, 'unless', "test conditional for third action" ); -is( $third_action->{conditional_field}, '606', "test conditional_field for third action" ); -is( $third_action->{conditional_subfield}, 'a', "test conditional_subfield for third action" ); +is( $third_action->{ordering}, 3, "test ordering for third action" ); +is( $third_action->{action}, 'copy_field', "test action for third action" ); +is( $third_action->{from_field}, '606', "test from_field for third action" ); +is( $third_action->{from_subfield}, 'a', "test from_subfield for third action" ); +is( $third_action->{to_field}, '607', "test to_field for third action" ); +is( $third_action->{to_subfield}, 'a', "test to_subfield for third action" ); +is( $third_action->{conditional}, 'unless', "test conditional for third action" ); +is( $third_action->{conditional_field}, '606', "test conditional_field for third action" ); +is( $third_action->{conditional_subfield}, 'a', "test conditional_subfield for third action" ); is( $third_action->{conditional_comparison}, 'not_equals', "test conditional_comparison for third action" ); -is( $third_action->{conditional_value}, '^AJAX', "test conditional_value for third action" ); +is( $third_action->{conditional_value}, '^AJAX', "test conditional_value for third action" ); my $fourth_action = $actions[3]; -is( $fourth_action->{ordering}, 4, "test ordering for fourth action" ); -is( $fourth_action->{action}, 'add_field', "test action for fourth action" ); -is( $fourth_action->{from_field}, '650', "test from_field for fourth action" ); -is( $fourth_action->{from_subfield}, 'a', "test from_subfield for fourth action" ); -is( $fourth_action->{to_field}, '', "test to_field for fourth action" ); -is( $fourth_action->{to_subfield}, '', "test to_subfield for fourth action" ); -is( $fourth_action->{conditional}, 'unless', "test conditional for fourth action" ); -is( $fourth_action->{conditional_field}, '650', "test conditional_field for fourth action" ); -is( $fourth_action->{conditional_subfield}, 'a', "test conditional_subfield for fourth action" ); -is( $fourth_action->{conditional_comparison}, 'exists', "test conditional_comparison for fourth action" ); -is( $fourth_action->{conditional_value}, '', "test conditional_value for fourth action" ); +is( $fourth_action->{ordering}, 4, "test ordering for fourth action" ); +is( $fourth_action->{action}, 'add_field', "test action for fourth action" ); +is( $fourth_action->{from_field}, '650', "test from_field for fourth action" ); +is( $fourth_action->{from_subfield}, 'a', "test from_subfield for fourth action" ); +is( $fourth_action->{to_field}, '', "test to_field for fourth action" ); +is( $fourth_action->{to_subfield}, '', "test to_subfield for fourth action" ); +is( $fourth_action->{conditional}, 'unless', "test conditional for fourth action" ); +is( $fourth_action->{conditional_field}, '650', "test conditional_field for fourth action" ); +is( $fourth_action->{conditional_subfield}, 'a', "test conditional_subfield for fourth action" ); +is( $fourth_action->{conditional_comparison}, 'exists', "test conditional_comparison for fourth action" ); +is( $fourth_action->{conditional_value}, '', "test conditional_value for fourth action" ); # Modifications -is( ModModificationTemplateAction( - $actions[1]->{mmta_id}, 'update_field', 0, - '100', 'u', 'LIV', '', '', - '', '', '', - 'if', '200', 'c', 'equals', 'Text', '', - 'Update field 099$t with value LIV if 200$b matches "Text"' -), 1, "Modify second action"); +is( + ModModificationTemplateAction( + $actions[1]->{mmta_id}, 'update_field', 0, + '100', 'u', 'LIV', '', '', + '', '', '', + 'if', '200', 'c', 'equals', 'Text', '', + 'Update field 099$t with value LIV if 200$b matches "Text"' + ), + 1, + "Modify second action" +); $second_action = GetModificationTemplateAction( $actions[1]->{mmta_id} ); -is( $second_action->{ordering}, 2, "test ordering for second action modified" ); -is( $second_action->{action}, 'update_field', "test action for second action modified" ); -is( $second_action->{from_field}, '100',"test from_field for second action modified" ); -is( $second_action->{from_subfield}, 'u', "test from_subfield for second action modified" ); -is( $second_action->{field_value}, 'LIV', "test firld_value for second action modified" ); -is( $second_action->{to_field}, '', "test to_field for second action modified" ); -is( $second_action->{to_subfield}, '', "test to_subfield for second action modified" ); -is( $second_action->{conditional}, 'if', "test conditional for second action modified" ); -is( $second_action->{conditional_field}, '200', "test conditional_field for second action modified" ); -is( $second_action->{conditional_subfield}, 'c', "test conditional_subfield for second action modified" ); +is( $second_action->{ordering}, 2, "test ordering for second action modified" ); +is( $second_action->{action}, 'update_field', "test action for second action modified" ); +is( $second_action->{from_field}, '100', "test from_field for second action modified" ); +is( $second_action->{from_subfield}, 'u', "test from_subfield for second action modified" ); +is( $second_action->{field_value}, 'LIV', "test firld_value for second action modified" ); +is( $second_action->{to_field}, '', "test to_field for second action modified" ); +is( $second_action->{to_subfield}, '', "test to_subfield for second action modified" ); +is( $second_action->{conditional}, 'if', "test conditional for second action modified" ); +is( $second_action->{conditional_field}, '200', "test conditional_field for second action modified" ); +is( $second_action->{conditional_subfield}, 'c', "test conditional_subfield for second action modified" ); is( $second_action->{conditional_comparison}, 'equals', "test conditional_comparison for second action modified" ); # Up and down -is( MoveModificationTemplateAction( $actions[2]->{mmta_id}, 'top' ), '1', 'Move the third action on top' ); +is( MoveModificationTemplateAction( $actions[2]->{mmta_id}, 'top' ), '1', 'Move the third action on top' ); is( MoveModificationTemplateAction( $actions[0]->{mmta_id}, 'bottom' ), '1', 'Move the first action on bottom' ); is( GetModificationTemplateAction( $actions[0]->{mmta_id} )->{ordering}, '4', 'First becomes fourth' ); @@ -141,8 +165,8 @@ is( GetModificationTemplateAction( $actions[1]->{mmta_id} )->{ordering}, '2', 'S is( GetModificationTemplateAction( $actions[2]->{mmta_id} )->{ordering}, '1', 'Third becomes first' ); is( GetModificationTemplateAction( $actions[3]->{mmta_id} )->{ordering}, '3', 'Fourth becomes third' ); -is( MoveModificationTemplateAction( $actions[0]->{mmta_id}, 'up' ), '1', 'Move up the first action (was fourth)' ); -is( MoveModificationTemplateAction( $actions[0]->{mmta_id}, 'up' ), '1', 'Move up the first action (was third)' ); +is( MoveModificationTemplateAction( $actions[0]->{mmta_id}, 'up' ), '1', 'Move up the first action (was fourth)' ); +is( MoveModificationTemplateAction( $actions[0]->{mmta_id}, 'up' ), '1', 'Move up the first action (was third)' ); is( MoveModificationTemplateAction( $actions[2]->{mmta_id}, 'down' ), '1', 'Move down the third action (was first)' ); is( GetModificationTemplateAction( $actions[0]->{mmta_id} )->{ordering}, '1', 'First becomes again first' ); @@ -151,16 +175,16 @@ is( GetModificationTemplateAction( $actions[2]->{mmta_id} )->{ordering}, '2', 'T is( GetModificationTemplateAction( $actions[3]->{mmta_id} )->{ordering}, '4', 'Fourth becomes again fourth' ); # Cleaning -is( DelModificationTemplateAction( $actions[0]->{mmta_id} ), 3, "Delete the first action, 2 others are reordered" ); +is( DelModificationTemplateAction( $actions[0]->{mmta_id} ), 3, "Delete the first action, 2 others are reordered" ); is( GetModificationTemplateAction( $actions[0]->{mmta_id} ), undef, "first action does not exist anymore" ); -is( DelModificationTemplate( $template_id ), 1, "The template has been deleted" ); +is( DelModificationTemplate($template_id), 1, "The template has been deleted" ); is( GetModificationTemplateAction( $actions[1]->{mmta_id} ), undef, "second action does not exist anymore" ); is( GetModificationTemplateAction( $actions[2]->{mmta_id} ), undef, "third action does not exist anymore" ); is( GetModificationTemplateAction( $actions[3]->{mmta_id} ), undef, "fourth action does not exist anymore" ); -is( GetModificationTemplateActions( $template_id ), 0, "There is no action for deleted template" ); +is( GetModificationTemplateActions($template_id), 0, "There is no action for deleted template" ); # ModifyRecordWithTemplate t::lib::Mocks::mock_userenv(); @@ -168,213 +192,307 @@ t::lib::Mocks::mock_userenv(); $template_id = AddModificationTemplate("new_template_test"); like( $template_id, qr|^\d+$|, "new template returns an id" ); -is( AddModificationTemplateAction( - $template_id, 'delete_field', 0, - '245', '', '', '', '', - '', '', '', - 'if', '245', 'a', 'equals', 'Bad title', '', - 'Delete field 245 if 245$a eq "Bad title"' -), 1, 'Add first action: delete field 245 if 245$a eq "Bad title"'); +is( + AddModificationTemplateAction( + $template_id, 'delete_field', 0, + '245', '', '', '', '', + '', '', '', + 'if', '245', 'a', 'equals', 'Bad title', '', + 'Delete field 245 if 245$a eq "Bad title"' + ), + 1, + 'Add first action: delete field 245 if 245$a eq "Bad title"' +); -is( AddModificationTemplateAction( - $template_id, 'copy_field', 0, - '245', 'a', '', '246', 'a', - '', '', '', - '', '', '', '', '', '', - 'copy field 245$a to 246$a' -), 1, 'Add second action: copy 245$a to 246$a'); +is( + AddModificationTemplateAction( + $template_id, 'copy_field', 0, + '245', 'a', '', '246', 'a', + '', '', '', + '', '', '', '', '', '', + 'copy field 245$a to 246$a' + ), + 1, + 'Add second action: copy 245$a to 246$a' +); -is( AddModificationTemplateAction( - $template_id, 'delete_field', 0, - '650', 'a', '', '', '', - '', '', '', - 'if', '650', '9', 'equals', '462', '', - 'Delete field 650$a if 650$9=462' -), 1, 'Add third action: delete field 650$a if 650$9=462'); +is( + AddModificationTemplateAction( + $template_id, 'delete_field', 0, + '650', 'a', '', '', '', + '', '', '', + 'if', '650', '9', 'equals', '462', '', + 'Delete field 650$a if 650$9=462' + ), + 1, + 'Add third action: delete field 650$a if 650$9=462' +); -is( AddModificationTemplateAction( - $template_id, 'update_field', 0, - '952', 'p', '3010023917_updated', '', '', - '', '', '', - 'unless', '650', '9', 'equals', '42', '', - 'Update field 952$p with "3010023917_updated" if 650$9 != 42' -), 1, 'Add fourth action: update field 952$p with "3010023917_updated" if 650$9 != 42'); +is( + AddModificationTemplateAction( + $template_id, 'update_field', 0, + '952', 'p', '3010023917_updated', '', '', + '', '', '', + 'unless', '650', '9', 'equals', '42', '', + 'Update field 952$p with "3010023917_updated" if 650$9 != 42' + ), + 1, + 'Add fourth action: update field 952$p with "3010023917_updated" if 650$9 != 42' +); -is( AddModificationTemplateAction( - $template_id, 'move_field', 0, - '952', 'd', '', '952', 'e', - '', '', '', - 'if', '952', 'c', 'equals', '^GEN', '1', - 'Move field 952$d to 952$e if 952$c =~ /^GEN/' -), 1, 'Add fifth action: move field 952$d to 952$e if 952$c =~ /^GEN/'); +is( + AddModificationTemplateAction( + $template_id, 'move_field', 0, + '952', 'd', '', '952', 'e', + '', '', '', + 'if', '952', 'c', 'equals', '^GEN', '1', + 'Move field 952$d to 952$e if 952$c =~ /^GEN/' + ), + 1, + 'Add fifth action: move field 952$d to 952$e if 952$c =~ /^GEN/' +); -is( AddModificationTemplateAction( - $template_id, 'update_field', 0, - '650', 'a', 'Computer algorithms.', '', '', - '', '', '', - 'if', '650', '9', 'equals', '499', '', - 'Update field 650$a with "Computer algorithms." to 651 if 650$9 == 499' -), 1, 'Add sixth action: update field 650$a with "Computer algorithms." if 650$9 == 499'); +is( + AddModificationTemplateAction( + $template_id, 'update_field', 0, + '650', 'a', 'Computer algorithms.', '', '', + '', '', '', + 'if', '650', '9', 'equals', '499', '', + 'Update field 650$a with "Computer algorithms." to 651 if 650$9 == 499' + ), + 1, + 'Add sixth action: update field 650$a with "Computer algorithms." if 650$9 == 499' +); -is( AddModificationTemplateAction( - $template_id, 'move_field', 0, - '650', '', '', '651', '', - '', '', '', - 'if', '650', '9', 'equals', '499', '', - 'Move field 650 to 651 if 650$9 == 499' -), 1, 'Add seventh action: move field 650 to 651 if 650$9 == 499'); +is( + AddModificationTemplateAction( + $template_id, 'move_field', 0, + '650', '', '', '651', '', + '', '', '', + 'if', '650', '9', 'equals', '499', '', + 'Move field 650 to 651 if 650$9 == 499' + ), + 1, + 'Add seventh action: move field 650 to 651 if 650$9 == 499' +); -is( AddModificationTemplateAction( - $template_id, 'update_field', 0, - '999', 'a', 'non existent.', '', '', - '', '', '', - '', '', '', '', '', '', - 'Update non existent field 999$a with "non existent"' -), 1, 'Add eighth action: update field non existent 999$a with "non existent."'); +is( + AddModificationTemplateAction( + $template_id, 'update_field', 0, + '999', 'a', 'non existent.', '', '', + '', '', '', + '', '', '', '', '', '', + 'Update non existent field 999$a with "non existent"' + ), + 1, + 'Add eighth action: update field non existent 999$a with "non existent."' +); -is( AddModificationTemplateAction( - $template_id, 'update_field', 0, - '999', 'a', 'existent - updated.', '', '', - '', '', '', - '', '', '', '', '', '', - 'Update existent field 999$a with "existent - updated."' -), 1, 'Add ninth action: update field non existent 999$a with "existent - updated."'); +is( + AddModificationTemplateAction( + $template_id, 'update_field', 0, + '999', 'a', 'existent - updated.', '', '', + '', '', '', + '', '', '', '', '', '', + 'Update existent field 999$a with "existent - updated."' + ), + 1, + 'Add ninth action: update field non existent 999$a with "existent - updated."' +); -is( AddModificationTemplateAction( - $template_id, 'add_field', 0, - '999', 'a', 'additional existent.', '', '', - '', '', '', - '', '', '', '', '', '', - 'Add new existent field 999$a with "additional existent"' -), 1, 'Add tenth action: add additional field existent 999$a with "additional existent."'); +is( + AddModificationTemplateAction( + $template_id, 'add_field', 0, + '999', 'a', 'additional existent.', '', '', + '', '', '', + '', '', '', '', '', '', + 'Add new existent field 999$a with "additional existent"' + ), + 1, + 'Add tenth action: add additional field existent 999$a with "additional existent."' +); -is( AddModificationTemplateAction( - $template_id, 'add_field', 0, - '007', '', 'vxcdq', '', '', - '', '', '', - '', '', '', '', '', '', - 'Add new existent field 999$a with "additional existent"' -), 1, 'Add eleventh action: add additional field existent 007'); +is( + AddModificationTemplateAction( + $template_id, 'add_field', 0, + '007', '', 'vxcdq', '', '', + '', '', '', + '', '', '', '', '', '', + 'Add new existent field 999$a with "additional existent"' + ), + 1, + 'Add eleventh action: add additional field existent 007' +); my $record = new_record(); is( ModifyRecordWithTemplate( $template_id, $record ), undef, "The ModifyRecordWithTemplate returns undef" ); my $expected_record = expected_record_1(); -is_deeply( $record, $expected_record, "Record modification as expected"); +is_deeply( $record, $expected_record, "Record modification as expected" ); $template_id = AddModificationTemplate("another_template_test"); # Duplicate 245 => 3x245 -is( AddModificationTemplateAction( - $template_id, 'copy_field', 0, - '245', '', '', '245', '', - '', '', '', - 'if', '245', 'a', 'equals', 'Bad title', '', - 'Copy field 245 if 245$a eq "Bad title"' -), 1, 'Add action: copy field 245 if 245$a eq "Bad title"'); +is( + AddModificationTemplateAction( + $template_id, 'copy_field', 0, + '245', '', '', '245', '', + '', '', '', + 'if', '245', 'a', 'equals', 'Bad title', '', + 'Copy field 245 if 245$a eq "Bad title"' + ), + 1, + 'Add action: copy field 245 if 245$a eq "Bad title"' +); $record = new_record(); is( ModifyRecordWithTemplate( $template_id, $record ), undef, "The ModifyRecordWithTemplate returns undef" ); -my @fields_245a = Koha::SimpleMARC::read_field({ - record => $record, - field => '245', - subfield => 'a', -}); -is_deeply( \@fields_245a, [ +my @fields_245a = Koha::SimpleMARC::read_field( + { + record => $record, + field => '245', + subfield => 'a', + } +); +is_deeply( + \@fields_245a, + [ 'Bad title', 'The art of computer programming', 'Bad title', - ], 'Copy field has copied the "Bad title"' ); + ], + 'Copy field has copied the "Bad title"' +); # Update first "Bad title" -is( AddModificationTemplateAction( - $template_id, 'update_field', 1, - '245', 'a', 'Bad title updated', '', '', - '', '', '', - 'if', '245', 'a', 'equals', 'Bad title', '', - 'Update first 245$a matching "Bad title" with "Bad title updated"' -), 1, 'Add action: update field 245$a matching "Bad title" with "Bad title updated'); +is( + AddModificationTemplateAction( + $template_id, 'update_field', 1, + '245', 'a', 'Bad title updated', '', '', + '', '', '', + 'if', '245', 'a', 'equals', 'Bad title', '', + 'Update first 245$a matching "Bad title" with "Bad title updated"' + ), + 1, + 'Add action: update field 245$a matching "Bad title" with "Bad title updated' +); $record = new_record(); is( ModifyRecordWithTemplate( $template_id, $record ), undef, "The ModifyRecordWithTemplate returns undef" ); -@fields_245a = Koha::SimpleMARC::read_field({ - record => $record, - field => '245', - subfield => 'a', -}); -is_deeply( \@fields_245a, [ +@fields_245a = Koha::SimpleMARC::read_field( + { + record => $record, + field => '245', + subfield => 'a', + } +); +is_deeply( + \@fields_245a, + [ 'Bad title updated', 'The art of computer programming', 'Bad title', - ], 'update_field has update first the "Bad title"' ); + ], + 'update_field has update first the "Bad title"' +); # Duplicate first 245 => 3x245 -is( AddModificationTemplateAction( - $template_id, 'copy_field', 1, - '245', '', '', '245', '', - '', '', '', - 'if', '245', 'a', 'equals', '^Bad title', '1', - 'Copy field 245 if 245$a =~ "^Bad title"' -), 1, 'Add action: copy field 245 if 245$a =~ "^Bad title"'); +is( + AddModificationTemplateAction( + $template_id, 'copy_field', 1, + '245', '', '', '245', '', + '', '', '', + 'if', '245', 'a', 'equals', '^Bad title', '1', + 'Copy field 245 if 245$a =~ "^Bad title"' + ), + 1, + 'Add action: copy field 245 if 245$a =~ "^Bad title"' +); $record = new_record(); is( ModifyRecordWithTemplate( $template_id, $record ), undef, "The ModifyRecordWithTemplate returns undef" ); -@fields_245a = Koha::SimpleMARC::read_field({ - record => $record, - field => '245', - subfield => 'a', -}); -is_deeply( \@fields_245a, [ +@fields_245a = Koha::SimpleMARC::read_field( + { + record => $record, + field => '245', + subfield => 'a', + } +); +is_deeply( + \@fields_245a, + [ 'Bad title updated', 'Bad title updated', 'The art of computer programming', 'Bad title', - ], 'Copy field has copied first "^Bad title"' ); + ], + 'Copy field has copied first "^Bad title"' +); # Delete first ^Bad title -is( AddModificationTemplateAction( - $template_id, 'delete_field', 1, - '245', '', '', '', '', - '', '', '', - 'if', '245', 'a', 'equals', '^Bad title', '1', +is( + AddModificationTemplateAction( + $template_id, 'delete_field', 1, + '245', '', '', '', '', + '', '', '', + 'if', '245', 'a', 'equals', '^Bad title', '1', + 'Delete first 245$a mathing ^Bad title' + ), + 1, 'Delete first 245$a mathing ^Bad title' -), 1, 'Delete first 245$a mathing ^Bad title'); +); $record = new_record(); is( ModifyRecordWithTemplate( $template_id, $record ), undef, "The ModifyRecordWithTemplate returns undef" ); -@fields_245a = Koha::SimpleMARC::read_field({ - record => $record, - field => '245', - subfield => 'a', -}); -is_deeply( \@fields_245a, [ +@fields_245a = Koha::SimpleMARC::read_field( + { + record => $record, + field => '245', + subfield => 'a', + } +); +is_deeply( + \@fields_245a, + [ 'Bad title updated', 'The art of computer programming', 'Bad title', - ], 'delete field has been deleted the right field"' ); + ], + 'delete field has been deleted the right field"' +); -is( AddModificationTemplateAction( - $template_id, 'delete_field', 0, - '245', '', '', '', '', - '', '', '', - 'if', '245', 'a', 'equals', 'updated$', '1', +is( + AddModificationTemplateAction( + $template_id, 'delete_field', 0, + '245', '', '', '', '', + '', '', '', + 'if', '245', 'a', 'equals', 'updated$', '1', + 'Delete first 245$a mathing updated$' + ), + 1, 'Delete first 245$a mathing updated$' -), 1, 'Delete first 245$a mathing updated$'); +); $record = new_record(); is( ModifyRecordWithTemplate( $template_id, $record ), undef, "The ModifyRecordWithTemplate returns undef" ); -@fields_245a = Koha::SimpleMARC::read_field({ - record => $record, - field => '245', - subfield => 'a', -}); -is_deeply( \@fields_245a, [ +@fields_245a = Koha::SimpleMARC::read_field( + { + record => $record, + field => '245', + subfield => 'a', + } +); +is_deeply( + \@fields_245a, + [ 'The art of computer programming', 'Bad title' - ], 'delete field has been deleted the right field"' ); + ], + 'delete field has been deleted the right field"' +); subtest 'GetModificationTemplates' => sub { plan tests => 1; @@ -383,7 +501,7 @@ subtest 'GetModificationTemplates' => sub { AddModificationTemplate("aaa"); AddModificationTemplate("mmm"); my @templates = GetModificationTemplates(); - is_deeply( [map{$_->{name}} @templates], ['aaa', 'mmm', 'zzz'] ); + is_deeply( [ map { $_->{name} } @templates ], [ 'aaa', 'mmm', 'zzz' ] ); }; subtest "not_equals" => sub { @@ -392,9 +510,9 @@ subtest "not_equals" => sub { my $template_id = AddModificationTemplate("template_name"); AddModificationTemplateAction( $template_id, 'move_field', 0, - '650', '', '', '651', '', - '', '', '', - 'if', '650', '9', 'not_equals', '499', '', + '650', '', '', '651', '', + '', '', '', + 'if', '650', '9', 'not_equals', '499', '', 'Move field 650 to 651 if 650$9 != 499' ); my $record = new_record(); @@ -406,9 +524,9 @@ subtest "not_equals" => sub { $template_id = AddModificationTemplate("template_name"); AddModificationTemplateAction( $template_id, 'move_field', 0, - '650', '', '', '651', '', - '', '', '', - 'if', '650', 'b', 'not_equals', '499', '', + '650', '', '', '651', '', + '', '', '', + 'if', '650', 'b', 'not_equals', '499', '', 'Move field 650 to 651 if 650$b != 499' ); $record = new_record(); @@ -423,9 +541,9 @@ subtest "when conditional field doesn't match the from field" => sub { my $template_id = AddModificationTemplate("template_name"); AddModificationTemplateAction( $template_id, 'delete_field', 0, - '650', '9', '', '', '', - '', '', '', - 'if', '245', 'a', 'equals', 'Bad title', '', + '650', '9', '', '', '', + '', '', '', + 'if', '245', 'a', 'equals', 'Bad title', '', 'Delete fields 650$9 if 245$a == "Bad title"' ); my $record = new_record(); @@ -437,9 +555,9 @@ subtest "when conditional field doesn't match the from field" => sub { $template_id = AddModificationTemplate("template_name"); AddModificationTemplateAction( $template_id, 'delete_field', 0, - '650', '9', '', '', '', - '', '', '', - 'if', '245', 'a', 'exists', '', '', + '650', '9', '', '', '', + '', '', '', + 'if', '245', 'a', 'exists', '', '', 'Delete fields 650$9 if 245$a exists' ); $record = new_record(); @@ -451,9 +569,9 @@ subtest "when conditional field doesn't match the from field" => sub { $template_id = AddModificationTemplate("template_name"); AddModificationTemplateAction( $template_id, 'delete_field', 1, - '650', '', '', '', '', - '', '', '', - 'if', '245', 'a', 'exists', '', '', + '650', '', '', '', '', + '', '', '', + 'if', '245', 'a', 'exists', '', '', 'Delete 1st field 650 if 245$a exists' ); $record = new_record(); @@ -508,7 +626,7 @@ sub expected_record_1 { $record->leader('03174nam a2200445 a 4500'); my @fields = ( MARC::Field->new( - '007', 'vxcdq', + '007', 'vxcdq', ), MARC::Field->new( 100, '1', ' ', @@ -765,99 +883,137 @@ $template_id = AddModificationTemplate("template_test_subfield_0"); like( $template_id, qr|^\d+$|, "new template returns an id" ); # Delete subfield 100$0 -is( AddModificationTemplateAction( - $template_id, 'delete_field', 0, - '100', '0', '', '', '', - '', '', '', - '', '', '', '', '', '', +is( + AddModificationTemplateAction( + $template_id, 'delete_field', 0, + '100', '0', '', '', '', + '', '', '', + '', '', '', '', '', '', + 'Action 1: Delete subfield 100$0' + ), + 1, 'Action 1: Delete subfield 100$0' -), 1, 'Action 1: Delete subfield 100$0'); +); # Add new subfield 100$0 with value "Test" # This adds a new 100 field to the record -is( AddModificationTemplateAction( - $template_id, 'add_field', 0, - '100', '0', 'Test', '', '', - '', '', '', - '', '', '', '', '', '', - 'Action 2: Add new subfield 100$0 with value "Test"' -), 1, 'Action 2: Add new subfield 100$0'); +is( + AddModificationTemplateAction( + $template_id, 'add_field', 0, + '100', '0', 'Test', '', '', + '', '', '', + '', '', '', '', '', '', + 'Action 2: Add new subfield 100$0 with value "Test"' + ), + 1, + 'Action 2: Add new subfield 100$0' +); # Update existing or add new subfield 100$0 with value "TestUpdated" # This updates the new 100 create above, and adds a new 100$0 to the original 100 field -is( AddModificationTemplateAction( - $template_id, 'update_field', 0, - '100', '0', 'TestUpdated', '', '', - '', '', '', - '', '', '', '', '', '', +is( + AddModificationTemplateAction( + $template_id, 'update_field', 0, + '100', '0', 'TestUpdated', '', '', + '', '', '', + '', '', '', '', '', '', + 'Action 3: Update existing or add new subfield 100$0 with value "TestUpdated"' + ), + 1, 'Action 3: Update existing or add new subfield 100$0 with value "TestUpdated"' -), 1, 'Action 3: Update existing or add new subfield 100$0 with value "TestUpdated"'); +); # Move subfield 100$0 to 600$0 # This removes the newly created 100, and removes the 100$0 from the original 100 field # Two 600 fields with a single 0 subfield are created -is( AddModificationTemplateAction( - $template_id, 'move_field', 0, - '100', '0', '', '600', '0', - '', '', '', - '', '', '', '', '', '', +is( + AddModificationTemplateAction( + $template_id, 'move_field', 0, + '100', '0', '', '600', '0', + '', '', '', + '', '', '', '', '', '', + 'Action 4: Move subfield 100$0 to 600$0' + ), + 1, 'Action 4: Move subfield 100$0 to 600$0' -), 1, 'Action 4: Move subfield 100$0 to 600$0'); +); # Copy subfield 600$0 to 100$0 # Copy subfield adds to existing fields if found, so we get two 100$0 on the original field -is( AddModificationTemplateAction( - $template_id, 'copy_field', 0, - '600', '0', '', '100', '0', - '', '', '', - '', '', '', '', '', '', +is( + AddModificationTemplateAction( + $template_id, 'copy_field', 0, + '600', '0', '', '100', '0', + '', '', '', + '', '', '', '', '', '', + 'Action 5: Copy subfield 600$0 to 100$0' + ), + 1, 'Action 5: Copy subfield 600$0 to 100$0' -), 1, 'Action 5: Copy subfield 600$0 to 100$0'); +); # Copy and replace subfield 245$0 to 700$0 # Copy and replace in this case makes a new 700$0 as it wasn't there -is( AddModificationTemplateAction( - $template_id, 'copy_and_replace_field', 0, - '245', '0', '', '700', '0', - '', '', '', - '', '', '', '', '', '', +is( + AddModificationTemplateAction( + $template_id, 'copy_and_replace_field', 0, + '245', '0', '', '700', '0', + '', '', '', + '', '', '', '', '', '', + 'Action 6: Copy and replace subfield 245$0 to 700$0' + ), + 1, 'Action 6: Copy and replace subfield 245$0 to 700$0' -), 1, 'Action 6: Copy and replace subfield 245$0 to 700$0'); +); # Copy subfield 590$0 to 690$0 # Copies the single subfield from 590 to a new 690 -is( AddModificationTemplateAction( - $template_id, 'copy_field', 0, - '590', '0', '', '690', '0', - '', '', '', - '', '', '', '', '', '', +is( + AddModificationTemplateAction( + $template_id, 'copy_field', 0, + '590', '0', '', '690', '0', + '', '', '', + '', '', '', '', '', '', + 'Action 7: Copy subfield 590$0 to 690$0' + ), + 1, 'Action 7: Copy subfield 590$0 to 690$0' -), 1, 'Action 7: Copy subfield 590$0 to 690$0'); +); # Copy subfield 590$a to 690$a # Copy subfield adds to existing 690 a new subfield a -is( AddModificationTemplateAction( - $template_id, 'copy_field', 0, - '590', 'a', '', '690', 'a', - '', '', '', - '', '', '', '', '', '', +is( + AddModificationTemplateAction( + $template_id, 'copy_field', 0, + '590', 'a', '', '690', 'a', + '', '', '', + '', '', '', '', '', '', + 'Action 8: Copy subfield 690$a to 690$a' + ), + 1, 'Action 8: Copy subfield 690$a to 690$a' -), 1, 'Action 8: Copy subfield 690$a to 690$a'); - +); # Copy field 590 to 690 # Copy field copies existing to a new 690, does not add to existing -is( AddModificationTemplateAction( - $template_id, 'copy_field', 0, - '590', '', '', '690', '', - '', '', '', - '', '', '', '', '', '', +is( + AddModificationTemplateAction( + $template_id, 'copy_field', 0, + '590', '', '', '690', '', + '', '', '', + '', '', '', '', '', '', + 'Action 9: Copy subfield 590 to 690' + ), + 1, 'Action 9: Copy subfield 590 to 690' -), 1, 'Action 9: Copy subfield 590 to 690'); +); -my @actions_0 = GetModificationTemplateActions( $template_id ); -is( @actions_0, 9, "9 actions are inserted"); +my @actions_0 = GetModificationTemplateActions($template_id); +is( @actions_0, 9, "9 actions are inserted" ); ModifyRecordWithTemplate( $template_id, $record ); my $expected_record_0 = expected_record_0(); -is_deeply( $record, $expected_record_0, '100$0 has been deleted, added back, updated, moved to 600$0, and copied back to 100$0; finally, 245$0 has been copied and replaced to 700$0' ); +is_deeply( + $record, $expected_record_0, + '100$0 has been deleted, added back, updated, moved to 600$0, and copied back to 100$0; finally, 245$0 has been copied and replaced to 700$0' +); diff --git a/t/db_dependent/Matcher.t b/t/db_dependent/Matcher.t index cda2dcbea4..975aef6a77 100755 --- a/t/db_dependent/Matcher.t +++ b/t/db_dependent/Matcher.t @@ -34,12 +34,18 @@ subtest 'GetMatcherList' => sub { plan tests => 9; $schema->resultset('MarcMatcher')->delete_all; - my $matcher1 = $builder->build({ source => 'MarcMatcher', - value => { code => 'ISBN', description => 'ISBN', record_type => 'red', threshold => 1 }, - }); - my $matcher2 = $builder->build({ source => 'MarcMatcher', - value => { code => 'ISSN', description => 'ISSN', record_type => 'blue', threshold => 0 }, - }); + my $matcher1 = $builder->build( + { + source => 'MarcMatcher', + value => { code => 'ISBN', description => 'ISBN', record_type => 'red', threshold => 1 }, + } + ); + my $matcher2 = $builder->build( + { + source => 'MarcMatcher', + value => { code => 'ISSN', description => 'ISSN', record_type => 'blue', threshold => 0 }, + } + ); my @matchers = C4::Matcher::GetMatcherList(); is( $matchers[0]->{'matcher_id'}, $matcher1->{matcher_id}, 'First matcher_id value' ); @@ -49,7 +55,7 @@ subtest 'GetMatcherList' => sub { is( $matcher_id, $matcher1->{matcher_id}, 'testing getmatcherid' ); my $testmatcher; - ok( $testmatcher = C4::Matcher->new( 'red', 1 ), 'testing matcher new' ); + ok( $testmatcher = C4::Matcher->new( 'red', 1 ), 'testing matcher new' ); ok( $testmatcher = C4::Matcher->new( 'blue', 0 ), 'testing matcher new' ); $testmatcher->threshold(1000); @@ -68,208 +74,293 @@ subtest 'GetMatcherList' => sub { subtest '_get_match_keys() tests' => sub { plan tests => 21; - my $matchpoint = get_title_matchpoint({ - length => 0, - norms => [ 'legacy_default' ], - offset => 0 - }); + my $matchpoint = get_title_matchpoint( + { + length => 0, + norms => ['legacy_default'], + offset => 0 + } + ); my $record = MARC::Record->new(); $record->append_fields( - MARC::Field->new('020', '1', ' ', - a => '978-1451697216 (alk. paper)'), - MARC::Field->new('020', '1', ' ', - a => '145169721X (alk. paper)'), - MARC::Field->new('020', '1', ' ', - a => '1NOTISBN3'), - MARC::Field->new('100', '1', ' ', - a => 'King, Stephen', - d => 'd1947-'), - MARC::Field->new('245', ' ', ' ', - a => ' .; thE t[]:,aliS(m)/An\'"', - c => 'Stephen King, Peter Straub.' ), - MARC::Field->new('700', ' ', ' ', - a => 'Straub, Peter', - d => '1943-') + MARC::Field->new( + '020', '1', ' ', + a => '978-1451697216 (alk. paper)' + ), + MARC::Field->new( + '020', '1', ' ', + a => '145169721X (alk. paper)' + ), + MARC::Field->new( + '020', '1', ' ', + a => '1NOTISBN3' + ), + MARC::Field->new( + '100', '1', ' ', + a => 'King, Stephen', + d => 'd1947-' + ), + MARC::Field->new( + '245', ' ', ' ', + a => ' .; thE t[]:,aliS(m)/An\'"', + c => 'Stephen King, Peter Straub.' + ), + MARC::Field->new( + '700', ' ', ' ', + a => 'Straub, Peter', + d => '1943-' + ) ); my @keys = C4::Matcher::_get_match_keys( $record, $matchpoint ); - is( $keys[0], 'THE TALISMAN STEPHEN KING PETER STRAUB', - 'Match key correctly calculated with no $norms'); + is( + $keys[0], 'THE TALISMAN STEPHEN KING PETER STRAUB', + 'Match key correctly calculated with no $norms' + ); - $matchpoint = get_title_matchpoint({ - length => 9, - norms => [ 'legacy_default' ], - offset => 0 - }); + $matchpoint = get_title_matchpoint( + { + length => 9, + norms => ['legacy_default'], + offset => 0 + } + ); @keys = C4::Matcher::_get_match_keys( $record, $matchpoint ); - is( $keys[0], 'THE', - 'Match key correctly calculated with length 9'); + is( + $keys[0], 'THE', + 'Match key correctly calculated with length 9' + ); - $matchpoint = get_title_matchpoint({ - length => 9, - norms => [ 'legacy_default' ], - offset => 1 - }); + $matchpoint = get_title_matchpoint( + { + length => 9, + norms => ['legacy_default'], + offset => 1 + } + ); @keys = C4::Matcher::_get_match_keys( $record, $matchpoint ); - is( $keys[0], 'THE T', - 'Match key correctly calculated with length 9 and offset 1'); + is( + $keys[0], 'THE T', + 'Match key correctly calculated with length 9 and offset 1' + ); - $matchpoint = get_title_matchpoint({ - length => 9, - norms => [ 'legacy_default' ], - offset => 2 - }); + $matchpoint = get_title_matchpoint( + { + length => 9, + norms => ['legacy_default'], + offset => 2 + } + ); @keys = C4::Matcher::_get_match_keys( $record, $matchpoint ); - is( $keys[0], 'THE T', - 'Match key correctly calculated with length 9 and offset 2, should not remove space'); + is( + $keys[0], 'THE T', + 'Match key correctly calculated with length 9 and offset 2, should not remove space' + ); - $matchpoint = get_authors_matchpoint({ - length => 0, - norms => [ 'legacy_default' ], - offset => 0 - }); + $matchpoint = get_authors_matchpoint( + { + length => 0, + norms => ['legacy_default'], + offset => 0 + } + ); @keys = C4::Matcher::_get_match_keys( $record, $matchpoint ); - is( $keys[0], 'STRAUB PETER KING STEPHEN', - 'Match key correctly calculated with multiple components'); + is( + $keys[0], 'STRAUB PETER KING STEPHEN', + 'Match key correctly calculated with multiple components' + ); - $matchpoint = get_authors_matchpoint({ - length => 9, - norms => [ 'legacy_default' ], - offset => 0 - }); + $matchpoint = get_authors_matchpoint( + { + length => 9, + norms => ['legacy_default'], + offset => 0 + } + ); @keys = C4::Matcher::_get_match_keys( $record, $matchpoint ); - is( $keys[0], 'STRAUB P KING STE', - 'Match key correctly calculated with multiple components, length 9'); + is( + $keys[0], 'STRAUB P KING STE', + 'Match key correctly calculated with multiple components, length 9' + ); - $matchpoint = get_authors_matchpoint({ - length => 10, - norms => [ 'legacy_default' ], - offset => 0 - }); + $matchpoint = get_authors_matchpoint( + { + length => 10, + norms => ['legacy_default'], + offset => 0 + } + ); @keys = C4::Matcher::_get_match_keys( $record, $matchpoint ); - is( $keys[0], 'STRAUB PE KING STEP', - 'Match key correctly calculated with multiple components, length 10'); + is( + $keys[0], 'STRAUB PE KING STEP', + 'Match key correctly calculated with multiple components, length 10' + ); - $matchpoint = get_authors_matchpoint({ - length => 10, - norms => [ 'legacy_default' ], - offset => 2 - }); + $matchpoint = get_authors_matchpoint( + { + length => 10, + norms => ['legacy_default'], + offset => 2 + } + ); @keys = C4::Matcher::_get_match_keys( $record, $matchpoint ); - is( $keys[0], 'RAUB PETE NG STEPHE', - 'Match key correctly calculated with multiple components, length 10, offset 1'); + is( + $keys[0], 'RAUB PETE NG STEPHE', + 'Match key correctly calculated with multiple components, length 10, offset 1' + ); - $matchpoint = get_title_matchpoint({ - length => 0, - norms => [ 'none', 'none' ], - offset => 0 - }); + $matchpoint = get_title_matchpoint( + { + length => 0, + norms => [ 'none', 'none' ], + offset => 0 + } + ); @keys = C4::Matcher::_get_match_keys( $record, $matchpoint ); - is( $keys[0], ' .; thE t[]:,aliS(m)/An\'" Stephen King, Peter Straub.', - 'Match key intact if \'none\' specified, length 0 and offset 0' ); + is( + $keys[0], ' .; thE t[]:,aliS(m)/An\'" Stephen King, Peter Straub.', + 'Match key intact if \'none\' specified, length 0 and offset 0' + ); - $matchpoint = get_authors_matchpoint({ - length => 0, - norms => [ 'upper_case' ], - offset => 0 - }); + $matchpoint = get_authors_matchpoint( + { + length => 0, + norms => ['upper_case'], + offset => 0 + } + ); @keys = C4::Matcher::_get_match_keys( $record, $matchpoint ); - is( $keys[0], 'STRAUB, PETER KING, STEPHEN', - 'Match key correctly calculated with multiple components, \'upper_case\' norm'); + is( + $keys[0], 'STRAUB, PETER KING, STEPHEN', + 'Match key correctly calculated with multiple components, \'upper_case\' norm' + ); - $matchpoint = get_authors_matchpoint({ - length => 0, - norms => [ 'lower_case' ], - offset => 0 - }); + $matchpoint = get_authors_matchpoint( + { + length => 0, + norms => ['lower_case'], + offset => 0 + } + ); @keys = C4::Matcher::_get_match_keys( $record, $matchpoint ); - is( $keys[0], 'straub, peter king, stephen', - 'Match key correctly calculated with multiple components, \'lower_case\' norm'); + is( + $keys[0], 'straub, peter king, stephen', + 'Match key correctly calculated with multiple components, \'lower_case\' norm' + ); - $matchpoint = get_authors_matchpoint({ - length => 0, - norms => [ 'remove_spaces' ], - offset => 0 - }); + $matchpoint = get_authors_matchpoint( + { + length => 0, + norms => ['remove_spaces'], + offset => 0 + } + ); @keys = C4::Matcher::_get_match_keys( $record, $matchpoint ); - is( $keys[0], 'Straub,Peter King,Stephen', - 'Match key correctly calculated with multiple components, \'remove_spaces\' norm'); + is( + $keys[0], 'Straub,Peter King,Stephen', + 'Match key correctly calculated with multiple components, \'remove_spaces\' norm' + ); - $matchpoint = get_authors_matchpoint({ - length => 0, - norms => [ 'remove_spaces', 'lower_case' ], - offset => 0 - }); + $matchpoint = get_authors_matchpoint( + { + length => 0, + norms => [ 'remove_spaces', 'lower_case' ], + offset => 0 + } + ); @keys = C4::Matcher::_get_match_keys( $record, $matchpoint ); - is( $keys[0], 'straub,peter king,stephen', - 'Match key correctly calculated with multiple components, \'remove_spaces\' and \'lower_case\' norm'); + is( + $keys[0], 'straub,peter king,stephen', + 'Match key correctly calculated with multiple components, \'remove_spaces\' and \'lower_case\' norm' + ); my $norm = 'unknown_norm'; - $matchpoint = get_title_matchpoint({ - length => 0, - norms => [ $norm ], - offset => 0 - }); - warning_is - { @keys = C4::Matcher::_get_match_keys( $record, $matchpoint ) } - qq{Invalid normalization routine required ($norm)}, - 'Passing an invalid normalization routine name raises a warning'; + $matchpoint = get_title_matchpoint( + { + length => 0, + norms => [$norm], + offset => 0 + } + ); + warning_is { @keys = C4::Matcher::_get_match_keys( $record, $matchpoint ) } + qq{Invalid normalization routine required ($norm)}, + 'Passing an invalid normalization routine name raises a warning'; - is( $keys[0], ' .; thE t[]:,aliS(m)/An\'" Stephen King, Peter Straub.', - 'Match key intact if invalid normalization routine specified' ); + is( + $keys[0], ' .; thE t[]:,aliS(m)/An\'" Stephen King, Peter Straub.', + 'Match key intact if invalid normalization routine specified' + ); - $matchpoint = get_title_matchpoint({ - length => 0, - norms => [ $norm, 'upper_case' ], - offset => 0 - }); - warning_is - { @keys = C4::Matcher::_get_match_keys( $record, $matchpoint ) } - qq{Invalid normalization routine required ($norm)}, - 'Passing an invalid normalization routine name raises a warning'; + $matchpoint = get_title_matchpoint( + { + length => 0, + norms => [ $norm, 'upper_case' ], + offset => 0 + } + ); + warning_is { @keys = C4::Matcher::_get_match_keys( $record, $matchpoint ) } + qq{Invalid normalization routine required ($norm)}, + 'Passing an invalid normalization routine name raises a warning'; - is( $keys[0], ' .; THE T[]:,ALIS(M)/AN\'" STEPHEN KING, PETER STRAUB.', - 'Match key correctly normalized if invalid normalization routine specified' ); + is( + $keys[0], ' .; THE T[]:,ALIS(M)/AN\'" STEPHEN KING, PETER STRAUB.', + 'Match key correctly normalized if invalid normalization routine specified' + ); - $matchpoint = get_isbn_matchpoint({ - length => 0, - norms => [ 'ISBN' ], - offset => 0 - }); + $matchpoint = get_isbn_matchpoint( + { + length => 0, + norms => ['ISBN'], + offset => 0 + } + ); @keys = C4::Matcher::_get_match_keys( $record, $matchpoint ); - is( $keys[0], '9781451697216', - 'Match key correctly calculated as ISBN13 when ISBN normalizer used'); - is( $keys[1], '9781451697216', - 'Match key correctly calculated as ISBN13 when ISBN normalizer used'); - is( $keys[2], '1NOTISBN3', - 'Match key passed through if not an isbn when ISBN normalizer used'); + is( + $keys[0], '9781451697216', + 'Match key correctly calculated as ISBN13 when ISBN normalizer used' + ); + is( + $keys[1], '9781451697216', + 'Match key correctly calculated as ISBN13 when ISBN normalizer used' + ); + is( + $keys[2], '1NOTISBN3', + 'Match key passed through if not an isbn when ISBN normalizer used' + ); - $matchpoint = get_title_matchpoint({ - length => 0, - offset => 0 - }); + $matchpoint = get_title_matchpoint( + { + length => 0, + offset => 0 + } + ); delete $matchpoint->{component}->{subfields}; @keys = C4::Matcher::_get_match_keys( $record, $matchpoint ); - is( $keys[0], ' .; thE t[]:,aliS(m)/An\'" Stephen King, Peter Straub.', "Match key correctly returns whole field if no subfields specified" ) + is( + $keys[0], ' .; thE t[]:,aliS(m)/An\'" Stephen King, Peter Straub.', + "Match key correctly returns whole field if no subfields specified" + ); }; subtest '_get_match_keys() leader tests' => sub { plan tests => 2; - my $record = MARC::Record->new(); - my $matchpoint = get_leader_matchpoint({ - length => 1, - offset => 6, - }); + my $record = MARC::Record->new(); + my $matchpoint = get_leader_matchpoint( + { + length => 1, + offset => 6, + } + ); my @keys = C4::Matcher::_get_match_keys( $record, $matchpoint ); - is( $keys[0], ' ', 'Match key correctly calculated as " " from LDR6 when no leader available'); + is( $keys[0], ' ', 'Match key correctly calculated as " " from LDR6 when no leader available' ); $record->leader('01344cam a22003014a 4500'); @keys = C4::Matcher::_get_match_keys( $record, $matchpoint ); - is( $keys[0], 'a', 'Match key correctly calculated as "a" from LDR6'); + is( $keys[0], 'a', 'Match key correctly calculated as "a" from LDR6' ); }; sub get_title_matchpoint { @@ -280,16 +371,15 @@ sub get_title_matchpoint { my $offset = $params->{offset} // 0; my $matchpoint = { - components => [ + components => [ { length => $length, norms => $norms, offset => $offset, - subfields => - { - a => 1, - c => 1 - }, + subfields => { + a => 1, + c => 1 + }, tag => '245' } ], @@ -308,26 +398,20 @@ sub get_authors_matchpoint { my $offset = $params->{offset} // 0; my $matchpoint = { - components => [ + components => [ { length => $length, norms => $norms, offset => $offset, - subfields => - { - a => 1 - }, - tag => '700' + subfields => { a => 1 }, + tag => '700' }, { length => $length, norms => $norms, offset => $offset, - subfields => - { - a => 1 - }, - tag => '100' + subfields => { a => 1 }, + tag => '100' } ], index => "author", @@ -345,16 +429,13 @@ sub get_isbn_matchpoint { my $offset = $params->{offset} // 0; my $matchpoint = { - components => [ + components => [ { length => $length, norms => $norms, offset => $offset, - subfields => - { - a => 1 - }, - tag => '020' + subfields => { a => 1 }, + tag => '020' }, ], index => "isbn", @@ -371,12 +452,12 @@ sub get_leader_matchpoint { my $offset = $params->{offset} // 0; my $matchpoint = { - components => [ + components => [ { - length => $length, - norms => $norms, - offset => $offset, - tag => 'LDR' + length => $length, + norms => $norms, + offset => $offset, + tag => 'LDR' }, ], }; diff --git a/t/db_dependent/Members.t b/t/db_dependent/Members.t index 8b4c38fd54..7e1650829d 100755 --- a/t/db_dependent/Members.t +++ b/t/db_dependent/Members.t @@ -33,25 +33,29 @@ use t::lib::Mocks; use t::lib::TestBuilder; BEGIN { - use_ok('C4::Members', qw( GetBorrowersToExpunge )); + use_ok( 'C4::Members', qw( GetBorrowersToExpunge ) ); } my $schema = Koha::Database->schema; $schema->storage->txn_begin; my $builder = t::lib::TestBuilder->new; -my $dbh = C4::Context->dbh; +my $dbh = C4::Context->dbh; -my $library1 = $builder->build({ - source => 'Branch', -}); -my $library2 = $builder->build({ - source => 'Branch', -}); -my $patron_category = $builder->build({ source => 'Category' }); -my $CARDNUMBER = 'TESTCARD01'; -my $FIRSTNAME = 'Marie'; -my $SURNAME = 'Mcknight'; -my $BRANCHCODE = $library1->{branchcode}; +my $library1 = $builder->build( + { + source => 'Branch', + } +); +my $library2 = $builder->build( + { + source => 'Branch', + } +); +my $patron_category = $builder->build( { source => 'Category' } ); +my $CARDNUMBER = 'TESTCARD01'; +my $FIRSTNAME = 'Marie'; +my $SURNAME = 'Mcknight'; +my $BRANCHCODE = $library1->{branchcode}; my $CHANGED_FIRSTNAME = "Marry Ann"; my $EMAIL = "Marie\@email.com"; @@ -62,31 +66,30 @@ t::lib::Mocks::mock_userenv(); # Make a borrower for testing my %data = ( - cardnumber => $CARDNUMBER, - firstname => $FIRSTNAME . q{ }, - surname => $SURNAME, + cardnumber => $CARDNUMBER, + firstname => $FIRSTNAME . q{ }, + surname => $SURNAME, categorycode => $patron_category->{categorycode}, - branchcode => $BRANCHCODE, - dateofbirth => '', - dateexpiry => '9999-12-31', - userid => 'tomasito' + branchcode => $BRANCHCODE, + dateofbirth => '', + dateexpiry => '9999-12-31', + userid => 'tomasito' ); -my $addmem=Koha::Patron->new(\%data)->store->borrowernumber; -ok($addmem, "Koha::Patron->store()"); +my $addmem = Koha::Patron->new( \%data )->store->borrowernumber; +ok( $addmem, "Koha::Patron->store()" ); my $patron = Koha::Patrons->find( { cardnumber => $CARDNUMBER } ) - or BAIL_OUT("Cannot read member with card $CARDNUMBER"); + or BAIL_OUT("Cannot read member with card $CARDNUMBER"); my $member = $patron->unblessed; -ok ( $member->{firstname} eq $FIRSTNAME && - $member->{surname} eq $SURNAME && - $member->{categorycode} eq $patron_category->{categorycode} && - $member->{branchcode} eq $BRANCHCODE - , "Got member") - or diag("Mismatching member details: ".Dumper(\%data, $member)); +ok( $member->{firstname} eq $FIRSTNAME + && $member->{surname} eq $SURNAME + && $member->{categorycode} eq $patron_category->{categorycode} + && $member->{branchcode} eq $BRANCHCODE, "Got member" ) + or diag( "Mismatching member details: " . Dumper( \%data, $member ) ); -is($member->{dateofbirth}, undef, "Empty dates handled correctly"); +is( $member->{dateofbirth}, undef, "Empty dates handled correctly" ); $member->{firstname} = $CHANGED_FIRSTNAME . q{ }; $member->{email} = $EMAIL; @@ -94,12 +97,11 @@ $member->{phone} = $PHONE; $member->{emailpro} = $EMAILPRO; $patron->set($member)->store; my $changedmember = Koha::Patrons->find( { cardnumber => $CARDNUMBER } )->unblessed; -ok ( $changedmember->{firstname} eq $CHANGED_FIRSTNAME && - $changedmember->{email} eq $EMAIL && - $changedmember->{phone} eq $PHONE && - $changedmember->{emailpro} eq $EMAILPRO - , "Member Changed") - or diag("Mismatching member details: ".Dumper($member, $changedmember)); +ok( $changedmember->{firstname} eq $CHANGED_FIRSTNAME + && $changedmember->{email} eq $EMAIL + && $changedmember->{phone} eq $PHONE + && $changedmember->{emailpro} eq $EMAILPRO, "Member Changed" ) + or diag( "Mismatching member details: " . Dumper( $member, $changedmember ) ); # Add a new borrower %data = ( @@ -114,171 +116,247 @@ ok ( $changedmember->{firstname} eq $CHANGED_FIRSTNAME && dateenrolled => '', ); my $borrowernumber = Koha::Patron->new( \%data )->store->borrowernumber; -$patron = Koha::Patrons->find( $borrowernumber ); +$patron = Koha::Patrons->find($borrowernumber); my $borrower = $patron->unblessed; -is( $borrower->{dateofbirth}, undef, 'Koha::Patron->store should undef dateofbirth if empty string is given'); -is( $borrower->{debarred}, undef, 'Koha::Patron->store should undef debarred if empty string is given'); -isnt( $borrower->{dateexpiry}, '0000-00-00', 'Koha::Patron->store should not set dateexpiry to 0000-00-00 if empty string is given'); -isnt( $borrower->{dateenrolled}, '0000-00-00', 'Koha::Patron->store should not set dateenrolled to 0000-00-00 if empty string is given'); +is( $borrower->{dateofbirth}, undef, 'Koha::Patron->store should undef dateofbirth if empty string is given' ); +is( $borrower->{debarred}, undef, 'Koha::Patron->store should undef debarred if empty string is given' ); +isnt( + $borrower->{dateexpiry}, '0000-00-00', + 'Koha::Patron->store should not set dateexpiry to 0000-00-00 if empty string is given' +); +isnt( + $borrower->{dateenrolled}, '0000-00-00', + 'Koha::Patron->store should not set dateenrolled to 0000-00-00 if empty string is given' +); -$patron->set({ dateofbirth => '', debarred => '', dateexpiry => '', dateenrolled => '' })->store; -$borrower = Koha::Patrons->find( $borrowernumber )->unblessed; -is( $borrower->{dateofbirth}, undef, 'Koha::Patron->store should undef dateofbirth if empty string is given'); -is( $borrower->{debarred}, undef, 'Koha::Patron->store should undef debarred if empty string is given'); -isnt( $borrower->{dateexpiry}, '0000-00-00', 'Koha::Patron->store should not set dateexpiry to 0000-00-00 if empty string is given'); -isnt( $borrower->{dateenrolled}, '0000-00-00', 'Koha::Patron->store should not set dateenrolled to 0000-00-00 if empty string is given'); +$patron->set( { dateofbirth => '', debarred => '', dateexpiry => '', dateenrolled => '' } )->store; +$borrower = Koha::Patrons->find($borrowernumber)->unblessed; +is( $borrower->{dateofbirth}, undef, 'Koha::Patron->store should undef dateofbirth if empty string is given' ); +is( $borrower->{debarred}, undef, 'Koha::Patron->store should undef debarred if empty string is given' ); +isnt( + $borrower->{dateexpiry}, '0000-00-00', + 'Koha::Patron->store should not set dateexpiry to 0000-00-00 if empty string is given' +); +isnt( + $borrower->{dateenrolled}, '0000-00-00', + 'Koha::Patron->store should not set dateenrolled to 0000-00-00 if empty string is given' +); -$patron->set({ dateofbirth => '1970-01-01', debarred => '2042-01-01', dateexpiry => '9999-12-31', dateenrolled => '2015-09-06' })->store; -$borrower = Koha::Patrons->find( $borrowernumber )->unblessed; -is( $borrower->{dateofbirth}, '1970-01-01', 'Koha::Patron->store should correctly set dateofbirth if a valid date is given'); -is( $borrower->{debarred}, '2042-01-01', 'Koha::Patron->store should correctly set debarred if a valid date is given'); -is( $borrower->{dateexpiry}, '9999-12-31', 'Koha::Patron->store should correctly set dateexpiry if a valid date is given'); -is( $borrower->{dateenrolled}, '2015-09-06', 'Koha::Patron->store should correctly set dateenrolled if a valid date is given'); +$patron->set( + { dateofbirth => '1970-01-01', debarred => '2042-01-01', dateexpiry => '9999-12-31', dateenrolled => '2015-09-06' } +)->store; +$borrower = Koha::Patrons->find($borrowernumber)->unblessed; +is( + $borrower->{dateofbirth}, '1970-01-01', + 'Koha::Patron->store should correctly set dateofbirth if a valid date is given' +); +is( $borrower->{debarred}, '2042-01-01', 'Koha::Patron->store should correctly set debarred if a valid date is given' ); +is( + $borrower->{dateexpiry}, '9999-12-31', + 'Koha::Patron->store should correctly set dateexpiry if a valid date is given' +); +is( + $borrower->{dateenrolled}, '2015-09-06', + 'Koha::Patron->store should correctly set dateenrolled if a valid date is given' +); #Regression tests for bug 10612 -my $library3 = $builder->build({ - source => 'Branch', -}); -$builder->build({ +my $library3 = $builder->build( + { + source => 'Branch', + } +); +$builder->build( + { source => 'Category', - value => { - categorycode => 'STAFFER', - description => 'Staff dont batch del', - category_type => 'S', + value => { + categorycode => 'STAFFER', + description => 'Staff dont batch del', + category_type => 'S', }, -}); + } +); -$builder->build({ +$builder->build( + { source => 'Category', - value => { - categorycode => 'CIVILIAN', - description => 'Civilian batch del', - category_type => 'A', + value => { + categorycode => 'CIVILIAN', + description => 'Civilian batch del', + category_type => 'A', }, -}); + } +); -$builder->build({ +$builder->build( + { source => 'Category', - value => { - categorycode => 'KIDclamp', - description => 'Kid to be guaranteed', - category_type => 'C', + value => { + categorycode => 'KIDclamp', + description => 'Kid to be guaranteed', + category_type => 'C', }, -}); + } +); -my $borrower1 = $builder->build({ +my $borrower1 = $builder->build( + { source => 'Borrower', value => { - categorycode=>'STAFFER', - branchcode => $library3->{branchcode}, - dateexpiry => '2015-01-01', - flags => undef, + categorycode => 'STAFFER', + branchcode => $library3->{branchcode}, + dateexpiry => '2015-01-01', + flags => undef, }, -}); + } +); my $bor1inlist = $borrower1->{borrowernumber}; -my $borrower2 = $builder->build({ +my $borrower2 = $builder->build( + { source => 'Borrower', value => { - categorycode=>'STAFFER', - branchcode => $library3->{branchcode}, - dateexpiry => '2015-01-01', - flags => undef, + categorycode => 'STAFFER', + branchcode => $library3->{branchcode}, + dateexpiry => '2015-01-01', + flags => undef, }, -}); + } +); -my $guarantee = $builder->build({ +my $guarantee = $builder->build( + { source => 'Borrower', value => { - categorycode=>'KIDclamp', - branchcode => $library3->{branchcode}, - dateexpiry => '2015-01-01', - flags => undef, + categorycode => 'KIDclamp', + branchcode => $library3->{branchcode}, + dateexpiry => '2015-01-01', + flags => undef, }, -}); + } +); my $bor2inlist = $borrower2->{borrowernumber}; -$builder->build({ +$builder->build( + { source => 'OldIssue', value => { borrowernumber => $bor2inlist, - timestamp => '2016-01-01', + timestamp => '2016-01-01', }, -}); + } +); # The following calls to GetBorrowersToExpunge are assuming that the pref # IndependentBranches is off. -t::lib::Mocks::mock_preference('IndependentBranches', 0); +t::lib::Mocks::mock_preference( 'IndependentBranches', 0 ); -my $anonymous_patron = Koha::Patron->new({ categorycode => 'CIVILIAN', branchcode => $library2->{branchcode} })->store->borrowernumber; -t::lib::Mocks::mock_preference('AnonymousPatron', $anonymous_patron); +my $anonymous_patron = + Koha::Patron->new( { categorycode => 'CIVILIAN', branchcode => $library2->{branchcode} } )->store->borrowernumber; +t::lib::Mocks::mock_preference( 'AnonymousPatron', $anonymous_patron ); -my $owner = Koha::Patron->new({ categorycode => 'STAFFER', branchcode => $library2->{branchcode} })->store->borrowernumber; +my $owner = + Koha::Patron->new( { categorycode => 'STAFFER', branchcode => $library2->{branchcode} } )->store->borrowernumber; my $list1 = AddPatronList( { name => 'Test List 1', owner => $owner } ); AddPatronsToList( { list => $list1, borrowernumbers => [$anonymous_patron] } ); my $patstodel = GetBorrowersToExpunge( { patron_list_id => $list1->patron_list_id() } ); is( scalar(@$patstodel), 0, 'Anonymous Patron not deleted from list' ); -my @listpatrons = ($bor1inlist, $bor2inlist); -AddPatronsToList( { list => $list1, borrowernumbers => \@listpatrons }); -$patstodel = GetBorrowersToExpunge( {patron_list_id => $list1->patron_list_id() } ); -is( scalar(@$patstodel),0,'No staff deleted from list of all staff'); -Koha::Patrons->find($bor2inlist)->set({ categorycode => 'CIVILIAN' })->store; -$patstodel = GetBorrowersToExpunge( {patron_list_id => $list1->patron_list_id()} ); -ok( scalar(@$patstodel)== 1 && $patstodel->[0]->{'borrowernumber'} eq $bor2inlist,'Staff patron not deleted from list'); -$patstodel = GetBorrowersToExpunge( {branchcode => $library3->{branchcode},patron_list_id => $list1->patron_list_id() } ); -ok( scalar(@$patstodel) == 1 && $patstodel->[0]->{'borrowernumber'} eq $bor2inlist,'Staff patron not deleted by branchcode and list'); -$patstodel = GetBorrowersToExpunge( {expired_before => '2015-01-02', patron_list_id => $list1->patron_list_id() } ); -ok( scalar(@$patstodel) == 1 && $patstodel->[0]->{'borrowernumber'} eq $bor2inlist,'Staff patron not deleted by expirationdate and list'); -$patstodel = GetBorrowersToExpunge( {not_borrowed_since => '2016-01-02', patron_list_id => $list1->patron_list_id() } ); -ok( scalar(@$patstodel) == 1 && $patstodel->[0]->{'borrowernumber'} eq $bor2inlist,'Staff patron not deleted by last issue date'); +my @listpatrons = ( $bor1inlist, $bor2inlist ); +AddPatronsToList( { list => $list1, borrowernumbers => \@listpatrons } ); +$patstodel = GetBorrowersToExpunge( { patron_list_id => $list1->patron_list_id() } ); +is( scalar(@$patstodel), 0, 'No staff deleted from list of all staff' ); +Koha::Patrons->find($bor2inlist)->set( { categorycode => 'CIVILIAN' } )->store; +$patstodel = GetBorrowersToExpunge( { patron_list_id => $list1->patron_list_id() } ); +ok( + scalar(@$patstodel) == 1 && $patstodel->[0]->{'borrowernumber'} eq $bor2inlist, + 'Staff patron not deleted from list' +); +$patstodel = + GetBorrowersToExpunge( { branchcode => $library3->{branchcode}, patron_list_id => $list1->patron_list_id() } ); +ok( + scalar(@$patstodel) == 1 && $patstodel->[0]->{'borrowernumber'} eq $bor2inlist, + 'Staff patron not deleted by branchcode and list' +); +$patstodel = GetBorrowersToExpunge( { expired_before => '2015-01-02', patron_list_id => $list1->patron_list_id() } ); +ok( + scalar(@$patstodel) == 1 && $patstodel->[0]->{'borrowernumber'} eq $bor2inlist, + 'Staff patron not deleted by expirationdate and list' +); +$patstodel = + GetBorrowersToExpunge( { not_borrowed_since => '2016-01-02', patron_list_id => $list1->patron_list_id() } ); +ok( + scalar(@$patstodel) == 1 && $patstodel->[0]->{'borrowernumber'} eq $bor2inlist, + 'Staff patron not deleted by last issue date' +); -Koha::Patrons->find($bor1inlist)->set({ categorycode => 'CIVILIAN' })->store; +Koha::Patrons->find($bor1inlist)->set( { categorycode => 'CIVILIAN' } )->store; t::lib::Mocks::mock_preference( 'borrowerRelationship', 'test' ); -my $relationship = Koha::Patron::Relationship->new( { guarantor_id => $bor1inlist, guarantee_id => $guarantee->{borrowernumber}, relationship => 'test' } )->store(); +my $relationship = Koha::Patron::Relationship->new( + { guarantor_id => $bor1inlist, guarantee_id => $guarantee->{borrowernumber}, relationship => 'test' } )->store(); -$patstodel = GetBorrowersToExpunge( {patron_list_id => $list1->patron_list_id()} ); -ok( scalar(@$patstodel)== 1 && $patstodel->[0]->{'borrowernumber'} eq $bor2inlist,'Guarantor patron not deleted from list'); -$patstodel = GetBorrowersToExpunge( {branchcode => $library3->{branchcode},patron_list_id => $list1->patron_list_id() } ); -ok( scalar(@$patstodel) == 1 && $patstodel->[0]->{'borrowernumber'} eq $bor2inlist,'Guarantor patron not deleted by branchcode and list'); -$patstodel = GetBorrowersToExpunge( {expired_before => '2015-01-02', patron_list_id => $list1->patron_list_id() } ); -ok( scalar(@$patstodel) == 1 && $patstodel->[0]->{'borrowernumber'} eq $bor2inlist,'Guarantor patron not deleted by expirationdate and list'); -$patstodel = GetBorrowersToExpunge( {not_borrowed_since => '2016-01-02', patron_list_id => $list1->patron_list_id() } ); -ok( scalar(@$patstodel) == 1 && $patstodel->[0]->{'borrowernumber'} eq $bor2inlist,'Guarantor patron not deleted by last issue date'); +$patstodel = GetBorrowersToExpunge( { patron_list_id => $list1->patron_list_id() } ); +ok( + scalar(@$patstodel) == 1 && $patstodel->[0]->{'borrowernumber'} eq $bor2inlist, + 'Guarantor patron not deleted from list' +); +$patstodel = + GetBorrowersToExpunge( { branchcode => $library3->{branchcode}, patron_list_id => $list1->patron_list_id() } ); +ok( + scalar(@$patstodel) == 1 && $patstodel->[0]->{'borrowernumber'} eq $bor2inlist, + 'Guarantor patron not deleted by branchcode and list' +); +$patstodel = GetBorrowersToExpunge( { expired_before => '2015-01-02', patron_list_id => $list1->patron_list_id() } ); +ok( + scalar(@$patstodel) == 1 && $patstodel->[0]->{'borrowernumber'} eq $bor2inlist, + 'Guarantor patron not deleted by expirationdate and list' +); +$patstodel = + GetBorrowersToExpunge( { not_borrowed_since => '2016-01-02', patron_list_id => $list1->patron_list_id() } ); +ok( + scalar(@$patstodel) == 1 && $patstodel->[0]->{'borrowernumber'} eq $bor2inlist, + 'Guarantor patron not deleted by last issue date' +); $relationship->delete(); -$builder->build({ +$builder->build( + { source => 'Issue', value => { borrowernumber => $bor2inlist, }, -}); -$patstodel = GetBorrowersToExpunge( {patron_list_id => $list1->patron_list_id()} ); -is( scalar(@$patstodel),1,'Borrower with issue not deleted from list'); -$patstodel = GetBorrowersToExpunge( {branchcode => $library3->{branchcode},patron_list_id => $list1->patron_list_id() } ); -is( scalar(@$patstodel),1,'Borrower with issue not deleted by branchcode and list'); -$patstodel = GetBorrowersToExpunge( {category_code => 'CIVILIAN',patron_list_id => $list1->patron_list_id() } ); -is( scalar(@$patstodel),1,'Borrower with issue not deleted by category_code and list'); -$patstodel = GetBorrowersToExpunge( {category_code => [], patron_list_id => $list1->patron_list_id() } ); -is( scalar(@$patstodel),1,'category_code can contain an empty arrayref'); -$patstodel = GetBorrowersToExpunge( {category_code => ['CIVILIAN','STAFFER'],patron_list_id => $list1->patron_list_id() } ); -is( scalar(@$patstodel),1,'Borrower with issue not deleted by multiple category_code and list'); -$patstodel = GetBorrowersToExpunge( {expired_before => '2015-01-02',patron_list_id => $list1->patron_list_id() } ); -is( scalar(@$patstodel),1,'Borrower with issue not deleted by expiration_date and list'); -$builder->schema->resultset( 'Issue' )->delete_all; -$patstodel = GetBorrowersToExpunge( {patron_list_id => $list1->patron_list_id()} ); -ok( scalar(@$patstodel)== 2,'Borrowers without issue deleted from list'); -$patstodel = GetBorrowersToExpunge( {category_code => 'CIVILIAN',patron_list_id => $list1->patron_list_id() } ); -is( scalar(@$patstodel),2,'Borrowers without issues deleted by category_code and list'); -$patstodel = GetBorrowersToExpunge( {category_code => ['CIVILIAN','STAFFER'],patron_list_id => $list1->patron_list_id() } ); -is( scalar(@$patstodel),2,'Borrowers without issues deleted by multiple category_code and list'); -$patstodel = GetBorrowersToExpunge( {expired_before => '2015-01-02',patron_list_id => $list1->patron_list_id() } ); -is( scalar(@$patstodel),2,'Borrowers without issues deleted by expiration_date and list'); -$patstodel = GetBorrowersToExpunge( {not_borrowed_since => '2016-01-02', patron_list_id => $list1->patron_list_id() } ); -is( scalar(@$patstodel),2,'Borrowers without issues deleted by last issue date'); + } +); +$patstodel = GetBorrowersToExpunge( { patron_list_id => $list1->patron_list_id() } ); +is( scalar(@$patstodel), 1, 'Borrower with issue not deleted from list' ); +$patstodel = + GetBorrowersToExpunge( { branchcode => $library3->{branchcode}, patron_list_id => $list1->patron_list_id() } ); +is( scalar(@$patstodel), 1, 'Borrower with issue not deleted by branchcode and list' ); +$patstodel = GetBorrowersToExpunge( { category_code => 'CIVILIAN', patron_list_id => $list1->patron_list_id() } ); +is( scalar(@$patstodel), 1, 'Borrower with issue not deleted by category_code and list' ); +$patstodel = GetBorrowersToExpunge( { category_code => [], patron_list_id => $list1->patron_list_id() } ); +is( scalar(@$patstodel), 1, 'category_code can contain an empty arrayref' ); +$patstodel = + GetBorrowersToExpunge( { category_code => [ 'CIVILIAN', 'STAFFER' ], patron_list_id => $list1->patron_list_id() } ); +is( scalar(@$patstodel), 1, 'Borrower with issue not deleted by multiple category_code and list' ); +$patstodel = GetBorrowersToExpunge( { expired_before => '2015-01-02', patron_list_id => $list1->patron_list_id() } ); +is( scalar(@$patstodel), 1, 'Borrower with issue not deleted by expiration_date and list' ); +$builder->schema->resultset('Issue')->delete_all; +$patstodel = GetBorrowersToExpunge( { patron_list_id => $list1->patron_list_id() } ); +ok( scalar(@$patstodel) == 2, 'Borrowers without issue deleted from list' ); +$patstodel = GetBorrowersToExpunge( { category_code => 'CIVILIAN', patron_list_id => $list1->patron_list_id() } ); +is( scalar(@$patstodel), 2, 'Borrowers without issues deleted by category_code and list' ); +$patstodel = + GetBorrowersToExpunge( { category_code => [ 'CIVILIAN', 'STAFFER' ], patron_list_id => $list1->patron_list_id() } ); +is( scalar(@$patstodel), 2, 'Borrowers without issues deleted by multiple category_code and list' ); +$patstodel = GetBorrowersToExpunge( { expired_before => '2015-01-02', patron_list_id => $list1->patron_list_id() } ); +is( scalar(@$patstodel), 2, 'Borrowers without issues deleted by expiration_date and list' ); +$patstodel = + GetBorrowersToExpunge( { not_borrowed_since => '2016-01-02', patron_list_id => $list1->patron_list_id() } ); +is( scalar(@$patstodel), 2, 'Borrowers without issues deleted by last issue date' ); # Test GetBorrowersToExpunge and TrackLastPatronActivityTriggers my $new_category = $builder->build_object( @@ -287,69 +365,81 @@ my $new_category = $builder->build_object( value => { category_type => 'A' }, # should not be S for GetBorrowersToExpunge } ); -$builder->build({ - source => 'Borrower', - value => { - lastseen => '2016-01-01 01:01:01', - categorycode => $new_category->categorycode, - flags => undef, +$builder->build( + { + source => 'Borrower', + value => { + lastseen => '2016-01-01 01:01:01', + categorycode => $new_category->categorycode, + flags => undef, + } } -}); -$builder->build({ - source => 'Borrower', - value => { - lastseen => '2016-02-02 02:02:02', - categorycode => $new_category->categorycode, - flags => undef, +); +$builder->build( + { + source => 'Borrower', + value => { + lastseen => '2016-02-02 02:02:02', + categorycode => $new_category->categorycode, + flags => undef, + } } -}); -$builder->build({ - source => 'Borrower', - value => { - lastseen => '2016-03-03 03:03:03', - categorycode => $new_category->categorycode, - flags => undef, +); +$builder->build( + { + source => 'Borrower', + value => { + lastseen => '2016-03-03 03:03:03', + categorycode => $new_category->categorycode, + flags => undef, + } } -}); -$patstodel = GetBorrowersToExpunge( { category_code => $new_category->categorycode, last_seen => '1999-12-12' }); +); +$patstodel = GetBorrowersToExpunge( { category_code => $new_category->categorycode, last_seen => '1999-12-12' } ); is( scalar @$patstodel, 0, 'TrackLastPatronActivityTriggers - 0 patrons must be deleted' ); -$patstodel = GetBorrowersToExpunge( { category_code => $new_category->categorycode, last_seen => '2016-02-15' }); +$patstodel = GetBorrowersToExpunge( { category_code => $new_category->categorycode, last_seen => '2016-02-15' } ); is( scalar @$patstodel, 2, 'TrackLastPatronActivityTriggers - 2 patrons must be deleted' ); -$patstodel = GetBorrowersToExpunge( { category_code => $new_category->categorycode, last_seen => '2016-04-04' }); +$patstodel = GetBorrowersToExpunge( { category_code => $new_category->categorycode, last_seen => '2016-04-04' } ); is( scalar @$patstodel, 3, 'TrackLastPatronActivityTriggers - 3 patrons must be deleted' ); -my $patron2 = $builder->build({ - source => 'Borrower', - value => { - lastseen => undef, - flags => undef, +my $patron2 = $builder->build( + { + source => 'Borrower', + value => { + lastseen => undef, + flags => undef, + } } -}); +); t::lib::Mocks::mock_preference( 'TrackLastPatronActivityTriggers', 'connection' ); Koha::Patrons->find( $patron2->{borrowernumber} )->update_lastseen('connection'); isnt( Koha::Patrons->find( $patron2->{borrowernumber} )->lastseen, undef, 'Lastseen should be changed now' ); # Test GetBorrowersToExpunge and regular patron with permission -$builder->build({ +$builder->build( + { source => 'Category', - value => { - categorycode => 'SMALLSTAFF', - description => 'Small staff', - category_type => 'A', + value => { + categorycode => 'SMALLSTAFF', + description => 'Small staff', + category_type => 'A', }, -}); -$borrowernumber = Koha::Patron->new({ - categorycode => 'SMALLSTAFF', - branchcode => $library2->{branchcode}, - flags => undef, -})->store->borrowernumber; -$patron = Koha::Patrons->find( $borrowernumber ); -$patstodel = GetBorrowersToExpunge( {category_code => 'SMALLSTAFF' } ); + } +); +$borrowernumber = Koha::Patron->new( + { + categorycode => 'SMALLSTAFF', + branchcode => $library2->{branchcode}, + flags => undef, + } +)->store->borrowernumber; +$patron = Koha::Patrons->find($borrowernumber); +$patstodel = GetBorrowersToExpunge( { category_code => 'SMALLSTAFF' } ); is( scalar @$patstodel, 1, 'Regular patron with flags=undef can be deleted' ); -$patron->set({ flags => 0 })->store; -$patstodel = GetBorrowersToExpunge( {category_code => 'SMALLSTAFF' } ); +$patron->set( { flags => 0 } )->store; +$patstodel = GetBorrowersToExpunge( { category_code => 'SMALLSTAFF' } ); is( scalar @$patstodel, 1, 'Regular patron with flags=0 can be deleted' ); -$patron->set({ flags => 4 })->store; -$patstodel = GetBorrowersToExpunge( {category_code => 'SMALLSTAFF' } ); +$patron->set( { flags => 4 } )->store; +$patstodel = GetBorrowersToExpunge( { category_code => 'SMALLSTAFF' } ); is( scalar @$patstodel, 0, 'Regular patron with flags>0 can not be deleted' ); # Test GetBorrowersToExpunge and patrons with "protected" status (borrowers.protected = 1) @@ -380,13 +470,18 @@ is( scalar @$patstodel, 0, 'Patron with protected status set can not be deleted' ## Remove all entries with userid='' (should be only 1 max) $dbh->do(q|DELETE FROM borrowers WHERE userid = ''|); ## And create a patron with a userid='' -$borrowernumber = Koha::Patron->new({ categorycode => $patron_category->{categorycode}, branchcode => $library2->{branchcode} })->store->borrowernumber; -$dbh->do(q|UPDATE borrowers SET userid = '' WHERE borrowernumber = ?|, undef, $borrowernumber); +$borrowernumber = + Koha::Patron->new( { categorycode => $patron_category->{categorycode}, branchcode => $library2->{branchcode} } ) + ->store->borrowernumber; +$dbh->do( q|UPDATE borrowers SET userid = '' WHERE borrowernumber = ?|, undef, $borrowernumber ); + # Create another patron and verify the userid has been generated -$borrowernumber = Koha::Patron->new({ categorycode => $patron_category->{categorycode}, branchcode => $library2->{branchcode} })->store->borrowernumber; +$borrowernumber = + Koha::Patron->new( { categorycode => $patron_category->{categorycode}, branchcode => $library2->{branchcode} } ) + ->store->borrowernumber; ok( $borrowernumber > 0, 'Koha::Patron->store should have inserted the patron even if no userid is given' ); -$borrower = Koha::Patrons->find( $borrowernumber )->unblessed; -ok( $borrower->{userid}, 'A userid should have been generated correctly' ); +$borrower = Koha::Patrons->find($borrowernumber)->unblessed; +ok( $borrower->{userid}, 'A userid should have been generated correctly' ); sub _find_member { my ($resultset) = @_; @@ -398,22 +493,21 @@ $schema->storage->txn_rollback; subtest 'Koha::Patron->store (invalid categorycode) tests' => sub { plan tests => 1; + # TODO Move this to t/db_dependent/Koha/Patrons.t subtest ->store $schema->storage->txn_begin; - my $category = $builder->build_object({ class => 'Koha::Patron::Categories' }); + my $category = $builder->build_object( { class => 'Koha::Patron::Categories' } ); my $category_id = $category->id; + # Remove category to make sure the id is not on the DB $category->delete; - my $patron_data = { - categorycode => $category_id - }; + my $patron_data = { categorycode => $category_id }; - throws_ok - { Koha::Patron->new( $patron_data )->store; } - 'Koha::Exceptions::Object::FKConstraint', + throws_ok { Koha::Patron->new($patron_data)->store; } + 'Koha::Exceptions::Object::FKConstraint', 'AddMember raises an exception on invalid categorycode'; $schema->storage->txn_rollback; diff --git a/t/db_dependent/Members/IssueSlip.t b/t/db_dependent/Members/IssueSlip.t index bbf4bb3a7d..302f223f62 100755 --- a/t/db_dependent/Members/IssueSlip.t +++ b/t/db_dependent/Members/IssueSlip.t @@ -15,17 +15,16 @@ # You should have received a copy of the GNU General Public License # along with Koha; if not, see <http://www.gnu.org/licenses>. - use Modern::Perl; -use Data::Dumper; # REMOVEME with diag +use Data::Dumper; # REMOVEME with diag use Test::More tests => 3; use Test::MockModule; use Test::MockTime qw( set_fixed_time ); use t::lib::TestBuilder; use C4::Circulation qw( AddIssue AddReturn ); -use C4::Biblio qw( AddBiblio ); +use C4::Biblio qw( AddBiblio ); use C4::Items; use C4::Members qw( IssueSlip ); @@ -48,11 +47,11 @@ $dbh->do(q|DELETE FROM categories|); $dbh->do(q|DELETE FROM letter|); my $builder = t::lib::TestBuilder->new; -set_fixed_time(CORE::time()); +set_fixed_time( CORE::time() ); -my $branchcode = $builder->build({ source => 'Branch' })->{ branchcode }; -my $categorycode = $builder->build({ source => 'Category' })->{ categorycode }; -my $itemtype = $builder->build({ source => 'Itemtype' })->{ itemtype }; +my $branchcode = $builder->build( { source => 'Branch' } )->{branchcode}; +my $categorycode = $builder->build( { source => 'Category' } )->{categorycode}; +my $itemtype = $builder->build( { source => 'Itemtype' } )->{itemtype}; my %item_infos = ( homebranch => $branchcode, @@ -60,7 +59,6 @@ my %item_infos = ( itype => $itemtype ); - my $slip_content = <<EOS; Checked out: <checkedout> @@ -77,9 +75,11 @@ Date due: <<issues.date_due>> </overdue> EOS -$dbh->do(q| +$dbh->do( + q| INSERT INTO letter( module, code, branchcode, name, is_html, title, content, message_transport_type) VALUES ('circulation', 'ISSUESLIP', '', 'Issue Slip', 0, 'Issue Slip', ?, 'email') -|, {}, $slip_content); +|, {}, $slip_content +); my $quick_slip_content = <<EOS; Checked out today: @@ -90,40 +90,44 @@ Date due: <<issues.date_due>> </checkedout> EOS -$dbh->do(q| +$dbh->do( + q| INSERT INTO letter( module, code, branchcode, name, is_html, title, content, message_transport_type) VALUES ('circulation', 'ISSUEQSLIP', '', 'Issue Quick Slip', 0, 'Issue Quick Slip', ?, 'email') -|, {}, $quick_slip_content); +|, {}, $quick_slip_content +); -my ( $title1, $title2 ) = ( 'My title 1', 'My title 2' ); -my ( $barcode1, $barcode2 ) = ('BC0101', 'BC0202' ); # FIXME Must not be hardcoded, tests could fail +my ( $title1, $title2 ) = ( 'My title 1', 'My title 2' ); +my ( $barcode1, $barcode2 ) = ( 'BC0101', 'BC0202' ); # FIXME Must not be hardcoded, tests could fail my $record = MARC::Record->new; $record->append_fields( MARC::Field->new( 245, '1', '4', - a => $title1, + a => $title1, ), ); my ($biblionumber1) = AddBiblio( $record, '' ); -my $itemnumber1 = $builder->build_sample_item({ biblionumber => $biblionumber1, barcode => $barcode1, %item_infos })->itemnumber; +my $itemnumber1 = + $builder->build_sample_item( { biblionumber => $biblionumber1, barcode => $barcode1, %item_infos } )->itemnumber; $record = MARC::Record->new; $record->append_fields( MARC::Field->new( 245, '1', '4', - a => $title2, + a => $title2, ), ); my ($biblionumber2) = AddBiblio( $record, '' ); -my $itemnumber2 = $builder->build_sample_item({ biblionumber => $biblionumber2, barcode => $barcode2, %item_infos })->itemnumber; +my $itemnumber2 = + $builder->build_sample_item( { biblionumber => $biblionumber2, barcode => $barcode2, %item_infos } )->itemnumber; my $borrowernumber = - Koha::Patron->new({ categorycode => $categorycode, branchcode => $branchcode })->store->borrowernumber; -my $borrower = Koha::Patrons->find( $borrowernumber ); + Koha::Patron->new( { categorycode => $categorycode, branchcode => $branchcode } )->store->borrowernumber; +my $borrower = Koha::Patrons->find($borrowernumber); my $module = Test::MockModule->new('C4::Context'); $module->mock( 'userenv', sub { { branch => $branchcode } } ); -my $today = dt_from_string; +my $today = dt_from_string; my $yesterday = dt_from_string->subtract_duration( DateTime::Duration->new( days => 1 ) ); subtest 'Issue slip' => sub { @@ -131,7 +135,7 @@ subtest 'Issue slip' => sub { subtest 'Empty slip' => sub { plan tests => 1; - my $slip = IssueSlip( $branchcode, $borrowernumber ); + my $slip = IssueSlip( $branchcode, $borrowernumber ); my $empty_slip = <<EOS; Checked out: @@ -139,7 +143,10 @@ Checked out: Overdues: EOS - is( $slip->{content}, $empty_slip, 'No checked out or overdues return an empty slip, it should return undef (FIXME)' ); + is( + $slip->{content}, $empty_slip, + 'No checked out or overdues return an empty slip, it should return undef (FIXME)' + ); }; subtest 'Daily loans' => sub { @@ -148,24 +155,24 @@ EOS } else { plan tests => 2; } + # Test 1: No overdue - my $today_daily = $today->clone->set( hour => 23, minute => 59 ); - my $today_daily_as_formatted = output_pref( $today_daily ); - my $yesterday_daily = $yesterday->clone->set( hour => 23, minute => 59 ); - my $yesterday_daily_as_formatted = output_pref( $yesterday_daily ); + my $today_daily = $today->clone->set( hour => 23, minute => 59 ); + my $today_daily_as_formatted = output_pref($today_daily); + my $yesterday_daily = $yesterday->clone->set( hour => 23, minute => 59 ); + my $yesterday_daily_as_formatted = output_pref($yesterday_daily); my ( $date_due, $issue_date, $slip, $expected_slip ); - $date_due = $today_daily; + $date_due = $today_daily; $issue_date = $today_daily->clone->subtract_duration( DateTime::Duration->new( minutes => 1 ) ); AddIssue( $borrower, $barcode1, $date_due, undef, $issue_date ); - $date_due = $today_daily; + $date_due = $today_daily; $issue_date = $yesterday_daily; AddIssue( $borrower, $barcode2, $date_due, undef, $issue_date ); # Set timestamps to the same value to avoid a different order - Koha::Checkouts->search( - { borrowernumber => $borrower->borrowernumber } - )->update( { timestamp => dt_from_string } ); + Koha::Checkouts->search( { borrowernumber => $borrower->borrowernumber } ) + ->update( { timestamp => dt_from_string } ); $expected_slip = <<EOS; Checked out: @@ -184,16 +191,16 @@ Overdues: EOS $slip = IssueSlip( $branchcode, $borrowernumber ); - is( $slip->{content}, $expected_slip , 'IssueSlip should return a slip with 2 checkouts'); + is( $slip->{content}, $expected_slip, 'IssueSlip should return a slip with 2 checkouts' ); AddReturn( $barcode1, $branchcode ); AddReturn( $barcode2, $branchcode ); # Test 2: 1 Overdue - $date_due = $today_daily; + $date_due = $today_daily; $issue_date = $today_daily->clone->subtract_duration( DateTime::Duration->new( minutes => 1 ) ); AddIssue( $borrower, $barcode1, $date_due, undef, $issue_date ); - $date_due = $yesterday_daily; + $date_due = $yesterday_daily; $issue_date = $yesterday_daily; AddIssue( $borrower, $barcode2, $date_due, undef, $issue_date ); @@ -213,7 +220,7 @@ Date due: $yesterday_daily_as_formatted EOS $slip = IssueSlip( $branchcode, $borrowernumber ); - is( $slip->{content}, $expected_slip, 'IssueSlip should return a slip with 1 checkout and 1 overdue'); + is( $slip->{content}, $expected_slip, 'IssueSlip should return a slip with 1 checkout and 1 overdue' ); AddReturn( $barcode1, $branchcode ); AddReturn( $barcode2, $branchcode ); @@ -225,20 +232,24 @@ EOS } else { plan tests => 2; } + # Test 1: No overdue - my ( $date_due_in_time, $date_due_in_time_as_formatted, $date_due_in_late, $date_due_in_late_as_formatted, $issue_date, $slip, $expected_slip ); + my ( + $date_due_in_time, $date_due_in_time_as_formatted, $date_due_in_late, $date_due_in_late_as_formatted, + $issue_date, $slip, $expected_slip + ); + # Assuming today is not hour = 23 and minute = 59 - $date_due_in_time = $today->clone->set(hour => ($today->hour < 23 ? $today->hour + 1 : 23), minute => 59); - $date_due_in_time_as_formatted = output_pref( $date_due_in_time ); + $date_due_in_time = $today->clone->set( hour => ( $today->hour < 23 ? $today->hour + 1 : 23 ), minute => 59 ); + $date_due_in_time_as_formatted = output_pref($date_due_in_time); $issue_date = $date_due_in_time->clone->subtract_duration( DateTime::Duration->new( minutes => 1 ) ); AddIssue( $borrower, $barcode1, $date_due_in_time, undef, $issue_date ); $issue_date = $yesterday->clone; AddIssue( $borrower, $barcode2, $date_due_in_time, undef, $issue_date ); # Set timestamps to the same value to avoid a different order - Koha::Checkouts->search( - { borrowernumber => $borrower->borrowernumber } - )->update( { timestamp => dt_from_string } ); + Koha::Checkouts->search( { borrowernumber => $borrower->borrowernumber } ) + ->update( { timestamp => dt_from_string } ); $expected_slip = <<EOS; Checked out: @@ -258,19 +269,20 @@ Overdues: EOS $slip = IssueSlip( $branchcode, $borrowernumber ); is( $slip->{content}, $expected_slip, 'IssueSlip should return a slip with 2 checkouts' ) - or diag(Dumper(Koha::Checkouts->search({borrowernumber => $borrower->{borrowernumber}})->unblessed)); + or + diag( Dumper( Koha::Checkouts->search( { borrowernumber => $borrower->{borrowernumber} } )->unblessed ) ); AddReturn( $barcode1, $branchcode ); AddReturn( $barcode2, $branchcode ); # Test 2: 1 Overdue - $date_due_in_time = $today->clone->set(hour => ($today->hour < 23 ? $today->hour + 1 : 23), minute => 59); - $date_due_in_time_as_formatted = output_pref( $date_due_in_time ); + $date_due_in_time = $today->clone->set( hour => ( $today->hour < 23 ? $today->hour + 1 : 23 ), minute => 59 ); + $date_due_in_time_as_formatted = output_pref($date_due_in_time); $issue_date = $date_due_in_time->clone->subtract_duration( DateTime::Duration->new( minutes => 1 ) ); AddIssue( $borrower, $barcode1, $date_due_in_time, undef, $issue_date ); - $date_due_in_late = $today->clone->subtract( hours => 1 ); - $date_due_in_late_as_formatted = output_pref( $date_due_in_late ); - $issue_date = $yesterday->clone; + $date_due_in_late = $today->clone->subtract( hours => 1 ); + $date_due_in_late_as_formatted = output_pref($date_due_in_late); + $issue_date = $yesterday->clone; AddIssue( $borrower, $barcode2, $date_due_in_late, undef, $issue_date ); $expected_slip = <<EOS; @@ -302,12 +314,15 @@ subtest 'Quick slip' => sub { subtest 'Empty slip' => sub { plan tests => 1; - my $slip = IssueSlip( $branchcode, $borrowernumber, 'quick slip' ); + my $slip = IssueSlip( $branchcode, $borrowernumber, 'quick slip' ); my $empty_slip = <<EOS; Checked out today: EOS - is( $slip->{content}, $empty_slip, 'No checked out or overdues return an empty slip, it should return undef (FIXME)' ); + is( + $slip->{content}, $empty_slip, + 'No checked out or overdues return an empty slip, it should return undef (FIXME)' + ); }; subtest 'Daily loans' => sub { @@ -316,17 +331,18 @@ EOS } else { plan tests => 2; } + # Test 1: No overdue - my $today_daily = $today->clone->set( hour => 23, minute => 59 ); - my $today_daily_as_formatted = output_pref( $today_daily ); - my $yesterday_daily = $yesterday->clone->set( hour => 23, minute => 59 ); - my $yesterday_daily_as_formatted = output_pref( $yesterday_daily ); + my $today_daily = $today->clone->set( hour => 23, minute => 59 ); + my $today_daily_as_formatted = output_pref($today_daily); + my $yesterday_daily = $yesterday->clone->set( hour => 23, minute => 59 ); + my $yesterday_daily_as_formatted = output_pref($yesterday_daily); my ( $date_due, $issue_date, $slip, $expected_slip ); - $date_due = $today_daily; + $date_due = $today_daily; $issue_date = $today_daily->clone->subtract_duration( DateTime::Duration->new( minutes => 1 ) ); AddIssue( $borrower, $barcode1, $date_due, undef, $issue_date ); - $date_due = $today_daily; + $date_due = $today_daily; $issue_date = $yesterday_daily; AddIssue( $borrower, $barcode2, $date_due, undef, $issue_date ); @@ -339,16 +355,16 @@ Date due: $today_daily_as_formatted EOS $slip = IssueSlip( $branchcode, $borrowernumber, 'quick slip' ); - is( $slip->{content}, $expected_slip, 'IssueSlip should return 2 checkouts for today'); + is( $slip->{content}, $expected_slip, 'IssueSlip should return 2 checkouts for today' ); AddReturn( $barcode1, $branchcode ); AddReturn( $barcode2, $branchcode ); # Test 2: 1 Overdue - $date_due = $today_daily; + $date_due = $today_daily; $issue_date = $today_daily->clone->subtract_duration( DateTime::Duration->new( minutes => 1 ) ); AddIssue( $borrower, $barcode1, $date_due, undef, $issue_date ); - $date_due = $yesterday_daily; + $date_due = $yesterday_daily; $issue_date = $yesterday_daily; AddIssue( $borrower, $barcode2, $date_due, undef, $issue_date ); @@ -366,11 +382,16 @@ EOS subtest 'Hourly loans' => sub { plan tests => 2; + # Test 1: No overdue - my ( $date_due_in_time, $date_due_in_time_as_formatted, $date_due_in_late, $date_due_in_late_as_formatted, $issue_date, $slip, $expected_slip ); + my ( + $date_due_in_time, $date_due_in_time_as_formatted, $date_due_in_late, $date_due_in_late_as_formatted, + $issue_date, $slip, $expected_slip + ); + # Assuming today is not hour = 23 and minute = 59 - $date_due_in_time = $today->clone->set(hour => ($today->hour < 23 ? $today->hour + 1 : 23), minute => 59); - $date_due_in_time_as_formatted = output_pref( $date_due_in_time ); + $date_due_in_time = $today->clone->set( hour => ( $today->hour < 23 ? $today->hour + 1 : 23 ), minute => 59 ); + $date_due_in_time_as_formatted = output_pref($date_due_in_time); $issue_date = $date_due_in_time->clone->subtract_duration( DateTime::Duration->new( minutes => 1 ) ); AddIssue( $borrower, $barcode1, $date_due_in_time, undef, $issue_date ); $issue_date = $yesterday->clone; @@ -391,13 +412,13 @@ EOS AddReturn( $barcode2, $branchcode ); # Test 2: 1 Overdue - $date_due_in_time = $today->clone->set(hour => ($today->hour < 23 ? $today->hour + 1 : 23), minute => 59); - $date_due_in_time_as_formatted = output_pref( $date_due_in_time ); + $date_due_in_time = $today->clone->set( hour => ( $today->hour < 23 ? $today->hour + 1 : 23 ), minute => 59 ); + $date_due_in_time_as_formatted = output_pref($date_due_in_time); $issue_date = $date_due_in_time->clone->subtract_duration( DateTime::Duration->new( minutes => 1 ) ); AddIssue( $borrower, $barcode1, $date_due_in_time, undef, $issue_date ); - $date_due_in_late = $today->clone->subtract( hours => 1 ); - $date_due_in_late_as_formatted = output_pref( $date_due_in_late ); - $issue_date = $yesterday->clone; + $date_due_in_late = $today->clone->subtract( hours => 1 ); + $date_due_in_late_as_formatted = output_pref($date_due_in_late); + $issue_date = $yesterday->clone; AddIssue( $borrower, $barcode2, $date_due_in_late, undef, $issue_date ); $expected_slip = <<EOS; diff --git a/t/db_dependent/Members/Statistics.t b/t/db_dependent/Members/Statistics.t index fc1a62049c..7e84b7eb82 100755 --- a/t/db_dependent/Members/Statistics.t +++ b/t/db_dependent/Members/Statistics.t @@ -6,7 +6,7 @@ use Test::More tests => 2; use t::lib::Mocks; use C4::Members::Statistics qw( get_fields ); -use Koha::Database; # we need the db here; get_fields looks for the item columns +use Koha::Database; # we need the db here; get_fields looks for the item columns my $schema = Koha::Database->schema; $schema->storage->txn_begin; @@ -15,6 +15,9 @@ t::lib::Mocks::mock_preference( 'StatisticsFields', undef ); is( C4::Members::Statistics::get_fields(), 'location|itype|ccode', 'Check default' ); t::lib::Mocks::mock_preference( 'StatisticsFields', 'barcode|garbagexxx|itemcallnumber|notexistent' ); -is( C4::Members::Statistics::get_fields(), 'barcode|itemcallnumber', 'Check if wrong item fields were removed by get_fields' ); +is( + C4::Members::Statistics::get_fields(), 'barcode|itemcallnumber', + 'Check if wrong item fields were removed by get_fields' +); $schema->storage->txn_rollback; diff --git a/t/db_dependent/Message.t b/t/db_dependent/Message.t index c100dd5450..ea05d7ec7d 100755 --- a/t/db_dependent/Message.t +++ b/t/db_dependent/Message.t @@ -30,16 +30,18 @@ my $schema = Koha::Database->schema; $schema->storage->txn_begin(); my $builder = t::lib::TestBuilder->new(); -my $dbh = C4::Context->dbh; -$dbh->do(q{INSERT INTO letter (module, code, name, title, content) VALUES ('test', 'TEST_MESSAGE','Test', '[% biblio.title %]', " +my $dbh = C4::Context->dbh; +$dbh->do( + q{INSERT INTO letter (module, code, name, title, content) VALUES ('test', 'TEST_MESSAGE','Test', '[% biblio.title %]', " ---- <<biblio.title>> ---- -")}); -my $biblio_1 = $builder->build_sample_biblio({ title => "heÄllo" }); -my $biblio_2 = $builder->build_sample_biblio({ title => "hell❤️" }); -my $patron = $builder->build_object({ class => 'Koha::Patrons' }); -my $letter = C4::Letters::GetPreparedLetter( +")} +); +my $biblio_1 = $builder->build_sample_biblio( { title => "heÄllo" } ); +my $biblio_2 = $builder->build_sample_biblio( { title => "hell❤️" } ); +my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); +my $letter = C4::Letters::GetPreparedLetter( ( module => 'test', letter_code => 'TEST_MESSAGE', @@ -49,12 +51,11 @@ my $letter = C4::Letters::GetPreparedLetter( ) ); - t::lib::Mocks::mock_preference( 'EmailFieldPrimary', '' ); -C4::Message->enqueue($letter, $patron, 'email'); -my $message = C4::Message->find_last_message($patron->unblessed, 'TEST_MESSAGE', 'email'); +C4::Message->enqueue( $letter, $patron, 'email' ); +my $message = C4::Message->find_last_message( $patron->unblessed, 'TEST_MESSAGE', 'email' ); like( $message->{metadata}, qr{heÄllo} ); -is ($message->{to_address}, $patron->email, "To address set correctly for EmailFieldPrimary 'off'"); +is( $message->{to_address}, $patron->email, "To address set correctly for EmailFieldPrimary 'off'" ); $letter = C4::Letters::GetPreparedLetter( ( @@ -70,6 +71,6 @@ like( $message->{metadata}, qr{heÄllo} ); like( $message->{metadata}, qr{hell❤️} ); t::lib::Mocks::mock_preference( 'EmailFieldPrimary', 'emailpro' ); -C4::Message->enqueue($letter, $patron, 'email'); -$message = C4::Message->find_last_message($patron->unblessed, 'TEST_MESSAGE', 'email'); -is ($patron->notice_email_address, $patron->emailpro, "To address set correctly for EmailFieldPrimary 'emailpro'"); +C4::Message->enqueue( $letter, $patron, 'email' ); +$message = C4::Message->find_last_message( $patron->unblessed, 'TEST_MESSAGE', 'email' ); +is( $patron->notice_email_address, $patron->emailpro, "To address set correctly for EmailFieldPrimary 'emailpro'" ); diff --git a/t/db_dependent/MungeMarcPrice.t b/t/db_dependent/MungeMarcPrice.t index 1a514232af..c510023c5b 100755 --- a/t/db_dependent/MungeMarcPrice.t +++ b/t/db_dependent/MungeMarcPrice.t @@ -7,7 +7,7 @@ use Koha::Acquisition::Currencies; use Test::More; # work around wide character warnings -binmode Test::More->builder->output, ":encoding(UTF-8)"; +binmode Test::More->builder->output, ":encoding(UTF-8)"; binmode Test::More->builder->failure_output, ":encoding(UTF-8)"; my $schema = Koha::Database->new->schema; @@ -15,26 +15,27 @@ $schema->storage->txn_begin; my $dbh = C4::Context->dbh; # set some test price strings and expected output -my @prices2test=( { string => '25,5 £, $34,55, $LD35', expected => '34.55' }, - { string => '32 EUR, 42.50$ USD, 54 CAD', expected=>'42.50' }, - { string => '38.80 Ksh, ¥300, 51,50 USD', expected => '51.50' }, - { string => '44 $, 33 €, 64 Br, £30', expected => '44' }, - { string => '9 EUR,$34,55 USD,$7.35 CAN', expected => '34.55' }, - { string => '$55.32', expected => '55.32' }, - { string => '9.99 USD (paperback)', expected => '9.99' }, - { string => '$9.99 USD (paperback)', expected => '9.99' }, - { string => '18.95 (U.S.)', expected => '18.95' }, - { string => '$5.99 ($7.75 CAN)', expected => '5.99' }, - { string => '5.99 (7.75 CAN)', expected => '5.99' }, - ); +my @prices2test = ( + { string => '25,5 £, $34,55, $LD35', expected => '34.55' }, + { string => '32 EUR, 42.50$ USD, 54 CAD', expected => '42.50' }, + { string => '38.80 Ksh, ¥300, 51,50 USD', expected => '51.50' }, + { string => '44 $, 33 €, 64 Br, £30', expected => '44' }, + { string => '9 EUR,$34,55 USD,$7.35 CAN', expected => '34.55' }, + { string => '$55.32', expected => '55.32' }, + { string => '9.99 USD (paperback)', expected => '9.99' }, + { string => '$9.99 USD (paperback)', expected => '9.99' }, + { string => '18.95 (U.S.)', expected => '18.95' }, + { string => '$5.99 ($7.75 CAN)', expected => '5.99' }, + { string => '5.99 (7.75 CAN)', expected => '5.99' }, +); plan tests => 2 * scalar @prices2test; # set active currency test data my $CURRENCY = 'TEST'; -my $SYMBOL = '$'; -my $ISOCODE = 'USD'; -my $RATE= 1; +my $SYMBOL = '$'; +my $ISOCODE = 'USD'; +my $RATE = 1; # disables existing active currency if necessary. my $active_currency = Koha::Acquisition::Currencies->get_active; @@ -44,11 +45,13 @@ if ($active_currency) { $dbh->do("UPDATE currency set active = 0 where currency = '$curr'"); } -$dbh->do("INSERT INTO currency ( currency,symbol,isocode,rate,active ) - VALUES ('$CURRENCY','$SYMBOL','$ISOCODE','$RATE',1)"); +$dbh->do( + "INSERT INTO currency ( currency,symbol,isocode,rate,active ) + VALUES ('$CURRENCY','$SYMBOL','$ISOCODE','$RATE',1)" +); foreach my $price (@prices2test) { is( - MungeMarcPrice($price->{'string'}), + MungeMarcPrice( $price->{'string'} ), $price->{'expected'}, "got expected price from $price->{'string'} (using currency.isocode)", ); @@ -57,12 +60,14 @@ foreach my $price (@prices2test) { # run tests again, but fall back to currency name $dbh->do('DELETE FROM aqbasket'); $dbh->do('DELETE FROM currency'); -$dbh->do("INSERT INTO currency ( currency, symbol, rate, active ) - VALUES ('$ISOCODE', '$SYMBOL', '$RATE', 1)"); +$dbh->do( + "INSERT INTO currency ( currency, symbol, rate, active ) + VALUES ('$ISOCODE', '$SYMBOL', '$RATE', 1)" +); foreach my $price (@prices2test) { is( - MungeMarcPrice($price->{'string'}), + MungeMarcPrice( $price->{'string'} ), $price->{'expected'}, "got expected price from $price->{'string'} (using ISO code as currency name)", ); diff --git a/t/db_dependent/OAI/AndSets.t b/t/db_dependent/OAI/AndSets.t index 0489de6457..6dda34f22b 100755 --- a/t/db_dependent/OAI/AndSets.t +++ b/t/db_dependent/OAI/AndSets.t @@ -30,7 +30,7 @@ use Koha::Biblios; use t::lib::TestBuilder; -my $schema = Koha::Database->new->schema; +my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; my $dbh = C4::Context->dbh; @@ -50,121 +50,120 @@ my $set1_id = AddOAISet($set1); my $marcflavour = C4::Context->preference('marcflavour'); my $mapping1; -if ($marcflavour eq 'UNIMARC' ){ +if ( $marcflavour eq 'UNIMARC' ) { $mapping1 = [ { - rule_order => 1, - marcfield => '200', + rule_order => 1, + marcfield => '200', marcsubfield => 'a', - operator => 'equal', - marcvalue => 'myTitle' + operator => 'equal', + marcvalue => 'myTitle' }, { - rule_order => 2, + rule_order => 2, rule_operator => 'and', - marcfield => '200', - marcsubfield => 'f', - operator => 'equal', - marcvalue => 'myAuthor' + marcfield => '200', + marcsubfield => 'f', + operator => 'equal', + marcvalue => 'myAuthor' }, ]; } else { $mapping1 = [ { - rule_order => 1, - marcfield => '245', + rule_order => 1, + marcfield => '245', marcsubfield => 'a', - operator => 'equal', - marcvalue => 'myTitle' + operator => 'equal', + marcvalue => 'myTitle' }, { - rule_order => 2, + rule_order => 2, rule_operator => 'and', - marcfield => '100', - marcsubfield => 'a', - operator => 'equal', - marcvalue => 'myAuthor' + marcfield => '100', + marcsubfield => 'a', + operator => 'equal', + marcvalue => 'myAuthor' }, ]; } #Add 1st mapping for set1 -ModOAISetMappings($set1_id, $mapping1); +ModOAISetMappings( $set1_id, $mapping1 ); -my $biblio_1 = $builder->build_sample_biblio({ title => 'myTitle' }); -my $biblio_2 = $builder->build_sample_biblio({ title => 'myTitle', author => 'myAuthor' }); +my $biblio_1 = $builder->build_sample_biblio( { title => 'myTitle' } ); +my $biblio_2 = $builder->build_sample_biblio( { title => 'myTitle', author => 'myAuthor' } ); my $biblionumber1 = $biblio_1->biblionumber; my $biblionumber2 = $biblio_2->biblionumber; - my $record = $biblio_1->metadata->record; my @setsEq = CalcOAISetsBiblio($record); -ok(!@setsEq, 'If only one condition is true, the record does not belong to the set'); +ok( !@setsEq, 'If only one condition is true, the record does not belong to the set' ); $record = $biblio_2->metadata->record; @setsEq = CalcOAISetsBiblio($record); -is_deeply(@setsEq, $set1_id, 'If all conditions are true, the record belongs to the set'); +is_deeply( @setsEq, $set1_id, 'If all conditions are true, the record belongs to the set' ); -if ($marcflavour eq 'UNIMARC' ){ +if ( $marcflavour eq 'UNIMARC' ) { $mapping1 = [ { - rule_order => 1, - marcfield => '200', + rule_order => 1, + marcfield => '200', marcsubfield => 'a', - operator => 'equal', - marcvalue => 'myTitle' + operator => 'equal', + marcvalue => 'myTitle' }, { - rule_order => 2, + rule_order => 2, rule_operator => 'or', - marcfield => '200', - marcsubfield => 'f', - operator => 'equal', - marcvalue => 'myAuthor' + marcfield => '200', + marcsubfield => 'f', + operator => 'equal', + marcvalue => 'myAuthor' }, { - rule_order => 3, + rule_order => 3, rule_operator => 'and', - marcfield => '995', - marcsubfield => 'r', - operator => 'equal', - marcvalue => 'myItemType' + marcfield => '995', + marcsubfield => 'r', + operator => 'equal', + marcvalue => 'myItemType' }, ]; } else { $mapping1 = [ { - rule_order => 1, - marcfield => '245', + rule_order => 1, + marcfield => '245', marcsubfield => 'a', - operator => 'equal', - marcvalue => 'myTitle' + operator => 'equal', + marcvalue => 'myTitle' }, { - rule_order => 2, + rule_order => 2, rule_operator => 'or', - marcfield => '100', - marcsubfield => 'a', - operator => 'equal', - marcvalue => 'myAuthor' + marcfield => '100', + marcsubfield => 'a', + operator => 'equal', + marcvalue => 'myAuthor' }, { - rule_order => 3, + rule_order => 3, rule_operator => 'and', - marcfield => '942', - marcsubfield => 'c', - operator => 'equal', - marcvalue => 'myItemType' + marcfield => '942', + marcsubfield => 'c', + operator => 'equal', + marcvalue => 'myItemType' }, ]; } -ModOAISetMappings($set1_id, $mapping1); +ModOAISetMappings( $set1_id, $mapping1 ); -$biblio_1 = $builder->build_sample_biblio({ title => 'myTitle' }); -$biblio_2 = $builder->build_sample_biblio({ author => 'myAuthor', itemtype => 'myItemType' }); +$biblio_1 = $builder->build_sample_biblio( { title => 'myTitle' } ); +$biblio_2 = $builder->build_sample_biblio( { author => 'myAuthor', itemtype => 'myItemType' } ); $biblionumber1 = $biblio_1->biblionumber; $biblionumber2 = $biblio_2->biblionumber; @@ -172,10 +171,16 @@ $biblionumber2 = $biblio_2->biblionumber; $record = $biblio_1->metadata->record; @setsEq = CalcOAISetsBiblio($record); -is_deeply(@setsEq, $set1_id, 'Boolean operators precedence is respected, the record with only the title belongs to the set'); +is_deeply( + @setsEq, $set1_id, + 'Boolean operators precedence is respected, the record with only the title belongs to the set' +); $record = $biblio_2->metadata->record; @setsEq = CalcOAISetsBiblio($record); -is_deeply(@setsEq, $set1_id, 'Boolean operators precedence is respected, the record with author and itemtype belongs to the set'); +is_deeply( + @setsEq, $set1_id, + 'Boolean operators precedence is respected, the record with author and itemtype belongs to the set' +); $schema->storage->txn_rollback; diff --git a/t/db_dependent/OAI/Server.t b/t/db_dependent/OAI/Server.t index 5da76b4f36..d8d11cd9d0 100755 --- a/t/db_dependent/OAI/Server.t +++ b/t/db_dependent/OAI/Server.t @@ -18,7 +18,7 @@ # along with Koha; if not, see <http://www.gnu.org/licenses>. use Modern::Perl; -use Test::Deep qw( cmp_deeply re ); +use Test::Deep qw( cmp_deeply re ); use Test::MockTime qw/set_fixed_time set_relative_time restore_time/; use Test::More tests => 35; @@ -62,7 +62,7 @@ use constant NUMBER_OF_MARC_RECORDS => 10; # Mocked CGI module in order to be able to send CGI parameters to OAI Server my %param; my $module = Test::MockModule->new('CGI'); -$module->mock('Vars', sub { %param; }); +$module->mock( 'Vars', sub { %param; } ); my $schema = Koha::Database->schema; $schema->storage->txn_begin; @@ -76,69 +76,70 @@ $dbh->do('DELETE FROM deletedbiblioitems'); $dbh->do('DELETE FROM deleteditems'); $dbh->do('DELETE FROM oai_sets'); -set_fixed_time(CORE::time()); +set_fixed_time( CORE::time() ); -my $base_datetime = dt_from_string(undef, undef, 'UTC'); -my $date_added = $base_datetime->ymd . ' ' .$base_datetime->hms . 'Z'; -my $date_to = substr($date_added, 0, 10) . 'T23:59:59Z'; -my (@header, @marcxml, @oaidc, @marcxml_transformed); -my $sth = $dbh->prepare('UPDATE biblioitems SET timestamp=? WHERE biblionumber=?'); -my $sth2 = $dbh->prepare('UPDATE biblio_metadata SET timestamp=? WHERE biblionumber=?'); +my $base_datetime = dt_from_string( undef, undef, 'UTC' ); +my $date_added = $base_datetime->ymd . ' ' . $base_datetime->hms . 'Z'; +my $date_to = substr( $date_added, 0, 10 ) . 'T23:59:59Z'; +my ( @header, @marcxml, @oaidc, @marcxml_transformed ); +my $sth = $dbh->prepare('UPDATE biblioitems SET timestamp=? WHERE biblionumber=?'); +my $sth2 = $dbh->prepare('UPDATE biblio_metadata SET timestamp=? WHERE biblionumber=?'); my $first_bn = 0; # Add biblio records foreach my $index ( 0 .. NUMBER_OF_MARC_RECORDS - 1 ) { my $record = MARC::Record->new(); - if (C4::Context->preference('marcflavour') eq 'UNIMARC') { - $record->append_fields( MARC::Field->new('101', '', '', 'a' => "lng" ) ); - $record->append_fields( MARC::Field->new('200', '', '', 'a' => "Title $index" ) ); - $record->append_fields( MARC::Field->new('952', '', '', 'a' => "Code" ) ); + if ( C4::Context->preference('marcflavour') eq 'UNIMARC' ) { + $record->append_fields( MARC::Field->new( '101', '', '', 'a' => "lng" ) ); + $record->append_fields( MARC::Field->new( '200', '', '', 'a' => "Title $index" ) ); + $record->append_fields( MARC::Field->new( '952', '', '', 'a' => "Code" ) ); } else { - $record->append_fields( MARC::Field->new('008', ' lng' ) ); - $record->append_fields( MARC::Field->new('245', '', '', 'a' => "Title $index" ) ); - $record->append_fields( MARC::Field->new('952', '', '', 'a' => "Code" ) ); + $record->append_fields( MARC::Field->new( '008', ' lng' ) ); + $record->append_fields( MARC::Field->new( '245', '', '', 'a' => "Title $index" ) ); + $record->append_fields( MARC::Field->new( '952', '', '', 'a' => "Code" ) ); } - my ($biblionumber) = AddBiblio($record, ''); + my ($biblionumber) = AddBiblio( $record, '' ); $first_bn = $biblionumber unless $first_bn; - my $timestamp = $base_datetime->ymd . ' ' .$base_datetime->hms; - $sth->execute($timestamp,$biblionumber); - $sth2->execute($timestamp,$biblionumber); + my $timestamp = $base_datetime->ymd . ' ' . $base_datetime->hms; + $sth->execute( $timestamp, $biblionumber ); + $sth2->execute( $timestamp, $biblionumber ); $timestamp .= 'Z'; $timestamp =~ s/ /T/; my $biblio = Koha::Biblios->find($biblionumber); $record = $biblio->metadata_record; my $record_transformed = $record->clone; - $record_transformed->delete_fields( $record_transformed->field('952')); - $record_transformed = XMLin($record_transformed->as_xml_record); - $record = XMLin($record->as_xml_record); + $record_transformed->delete_fields( $record_transformed->field('952') ); + $record_transformed = XMLin( $record_transformed->as_xml_record ); + $record = XMLin( $record->as_xml_record ); push @header, { datestamp => $timestamp, identifier => "TEST:$biblionumber" }; my $dc = { - 'dc:title' => "Title $index", - 'dc:language' => "lng", - 'dc:type' => {}, - 'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance', - 'xmlns:oai_dc' => 'http://www.openarchives.org/OAI/2.0/oai_dc/', - 'xmlns:dc' => 'http://purl.org/dc/elements/1.1/', - 'xsi:schemaLocation' => 'http://www.openarchives.org/OAI/2.0/oai_dc/ http://www.openarchives.org/OAI/2.0/oai_dc.xsd', + 'dc:title' => "Title $index", + 'dc:language' => "lng", + 'dc:type' => {}, + 'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance', + 'xmlns:oai_dc' => 'http://www.openarchives.org/OAI/2.0/oai_dc/', + 'xmlns:dc' => 'http://purl.org/dc/elements/1.1/', + 'xsi:schemaLocation' => + 'http://www.openarchives.org/OAI/2.0/oai_dc/ http://www.openarchives.org/OAI/2.0/oai_dc.xsd', }; - if (C4::Context->preference('marcflavour') eq 'UNIMARC') { + if ( C4::Context->preference('marcflavour') eq 'UNIMARC' ) { $dc->{'dc:identifier'} = $biblionumber; } push @oaidc, { - header => $header[$index], + header => $header[$index], metadata => { 'oai_dc:dc' => $dc, }, }; push @marcxml, { - header => $header[$index], + header => $header[$index], metadata => { record => $record, }, }; push @marcxml_transformed, { - header => $header[$index], + header => $header[$index], metadata => { record => $record_transformed, }, @@ -153,21 +154,22 @@ my $syspref = { 'OAI-PMH:MaxCount' => 3, 'OAI-PMH:DeletedRecord' => 'persistent', }; -while ( my ($name, $value) = each %$syspref ) { +while ( my ( $name, $value ) = each %$syspref ) { t::lib::Mocks::mock_preference( $name => $value ); } sub test_query { - my ($test, $param, $expected) = @_; + my ( $test, $param, $expected ) = @_; %param = %$param; my %full_expected = ( %$expected, ( - request => 'http://localhost', - xmlns => 'http://www.openarchives.org/OAI/2.0/', - 'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance', - 'xsi:schemaLocation' => 'http://www.openarchives.org/OAI/2.0/ http://www.openarchives.org/OAI/2.0/OAI-PMH.xsd', + request => 'http://localhost', + xmlns => 'http://www.openarchives.org/OAI/2.0/', + 'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance', + 'xsi:schemaLocation' => + 'http://www.openarchives.org/OAI/2.0/ http://www.openarchives.org/OAI/2.0/OAI-PMH.xsd', ) ); @@ -181,207 +183,263 @@ sub test_query { } delete $response->{responseDate}; - unless (cmp_deeply($response, \%full_expected, $test)) { - diag - "PARAM:" . YAML::XS::Dump($param) . - "EXPECTED:" . YAML::XS::Dump(\%full_expected) . - "RESPONSE:" . YAML::XS::Dump($response); + unless ( cmp_deeply( $response, \%full_expected, $test ) ) { + diag "PARAM:" + . YAML::XS::Dump($param) + . "EXPECTED:" + . YAML::XS::Dump( \%full_expected ) + . "RESPONSE:" + . YAML::XS::Dump($response); } } -test_query('ListMetadataFormats', {verb => 'ListMetadataFormats'}, { - ListMetadataFormats => { - metadataFormat => [ - { - metadataNamespace => 'http://www.openarchives.org/OAI/2.0/oai_dc/', - metadataPrefix=> 'oai_dc', - schema => 'http://www.openarchives.org/OAI/2.0/oai_dc.xsd', - }, - { - metadataNamespace => 'http://www.loc.gov/MARC21/slim http://www.loc.gov/standards/marcxml/schema/MARC21slim', - metadataPrefix => 'marc21', - schema => 'http://www.loc.gov/standards/marcxml/schema/MARC21slim.xsd', - }, - { - metadataNamespace => 'http://www.loc.gov/MARC21/slim http://www.loc.gov/standards/marcxml/schema/MARC21slim', - metadataPrefix => 'marcxml', - schema => 'http://www.loc.gov/standards/marcxml/schema/MARC21slim.xsd', - }, - ], - }, -}); - -test_query('ListIdentifiers without metadataPrefix', {verb => 'ListIdentifiers'}, { - error => { - code => 'badArgument', - content => "Required argument 'metadataPrefix' was undefined", - }, -}); - -test_query('ListIdentifiers', {verb => 'ListIdentifiers', metadataPrefix => 'marcxml'}, { - ListIdentifiers => { - header => [ @header[0..2] ], - resumptionToken => { - content => re( qr{^marcxml/3////0/0/\d+$} ), - cursor => 3, +test_query( + 'ListMetadataFormats', + { verb => 'ListMetadataFormats' }, + { + ListMetadataFormats => { + metadataFormat => [ + { + metadataNamespace => 'http://www.openarchives.org/OAI/2.0/oai_dc/', + metadataPrefix => 'oai_dc', + schema => 'http://www.openarchives.org/OAI/2.0/oai_dc.xsd', + }, + { + metadataNamespace => + 'http://www.loc.gov/MARC21/slim http://www.loc.gov/standards/marcxml/schema/MARC21slim', + metadataPrefix => 'marc21', + schema => 'http://www.loc.gov/standards/marcxml/schema/MARC21slim.xsd', + }, + { + metadataNamespace => + 'http://www.loc.gov/MARC21/slim http://www.loc.gov/standards/marcxml/schema/MARC21slim', + metadataPrefix => 'marcxml', + schema => 'http://www.loc.gov/standards/marcxml/schema/MARC21slim.xsd', + }, + ], }, - }, -}); + } +); -test_query('ListIdentifiers', {verb => 'ListIdentifiers', metadataPrefix => 'marcxml'}, { - ListIdentifiers => { - header => [ @header[0..2] ], - resumptionToken => { - content => re( qr{^marcxml/3////0/0/\d+$} ), - cursor => 3, +test_query( + 'ListIdentifiers without metadataPrefix', + { verb => 'ListIdentifiers' }, + { + error => { + code => 'badArgument', + content => "Required argument 'metadataPrefix' was undefined", }, - }, -}); + } +); + +test_query( + 'ListIdentifiers', + { verb => 'ListIdentifiers', metadataPrefix => 'marcxml' }, + { + ListIdentifiers => { + header => [ @header[ 0 .. 2 ] ], + resumptionToken => { + content => re(qr{^marcxml/3////0/0/\d+$}), + cursor => 3, + }, + }, + } +); + +test_query( + 'ListIdentifiers', + { verb => 'ListIdentifiers', metadataPrefix => 'marcxml' }, + { + ListIdentifiers => { + header => [ @header[ 0 .. 2 ] ], + resumptionToken => { + content => re(qr{^marcxml/3////0/0/\d+$}), + cursor => 3, + }, + }, + } +); test_query( 'ListIdentifiers with resumptionToken 1', - { verb => 'ListIdentifiers', resumptionToken => "marcxml/3/1970-01-01T00:00:00Z/$date_to//0/0/" . ($first_bn + 3) }, + { + verb => 'ListIdentifiers', + resumptionToken => "marcxml/3/1970-01-01T00:00:00Z/$date_to//0/0/" . ( $first_bn + 3 ) + }, { ListIdentifiers => { - header => [ @header[3..5] ], + header => [ @header[ 3 .. 5 ] ], resumptionToken => { - content => re( qr{^marcxml/6/1970-01-01T00:00:00Z/$date_to//0/0/\d+$} ), - cursor => 6, + content => re(qr{^marcxml/6/1970-01-01T00:00:00Z/$date_to//0/0/\d+$}), + cursor => 6, }, - }, + }, }, ); test_query( 'ListIdentifiers with resumptionToken 2', - { verb => 'ListIdentifiers', resumptionToken => "marcxml/6/1970-01-01T00:00:00Z/$date_to//0/0/" . ($first_bn + 6) }, + { + verb => 'ListIdentifiers', + resumptionToken => "marcxml/6/1970-01-01T00:00:00Z/$date_to//0/0/" . ( $first_bn + 6 ) + }, { ListIdentifiers => { - header => [ @header[6..8] ], + header => [ @header[ 6 .. 8 ] ], resumptionToken => { - content => re( qr{^marcxml/9/1970-01-01T00:00:00Z/$date_to//0/0/\d+$} ), - cursor => 9, + content => re(qr{^marcxml/9/1970-01-01T00:00:00Z/$date_to//0/0/\d+$}), + cursor => 9, }, - }, + }, }, ); test_query( 'ListIdentifiers with resumptionToken 3, response without resumption', - { verb => 'ListIdentifiers', resumptionToken => "marcxml/9/1970-01-01T00:00:00Z/$date_to//0/0/" . ($first_bn + 9) }, + { + verb => 'ListIdentifiers', + resumptionToken => "marcxml/9/1970-01-01T00:00:00Z/$date_to//0/0/" . ( $first_bn + 9 ) + }, { ListIdentifiers => { header => $header[9], - }, + }, }, ); -test_query('ListRecords marcxml without metadataPrefix', {verb => 'ListRecords'}, { - error => { - code => 'badArgument', - content => "Required argument 'metadataPrefix' was undefined", - }, -}); - -test_query('ListRecords marcxml', {verb => 'ListRecords', metadataPrefix => 'marcxml'}, { - ListRecords => { - record => [ @marcxml[0..2] ], - resumptionToken => { - content => re( qr{^marcxml/3////0/0/\d+$} ), - cursor => 3, +test_query( + 'ListRecords marcxml without metadataPrefix', + { verb => 'ListRecords' }, + { + error => { + code => 'badArgument', + content => "Required argument 'metadataPrefix' was undefined", }, - }, -}); + } +); + +test_query( + 'ListRecords marcxml', + { verb => 'ListRecords', metadataPrefix => 'marcxml' }, + { + ListRecords => { + record => [ @marcxml[ 0 .. 2 ] ], + resumptionToken => { + content => re(qr{^marcxml/3////0/0/\d+$}), + cursor => 3, + }, + }, + } +); test_query( 'ListRecords marcxml with resumptionToken 1', - { verb => 'ListRecords', resumptionToken => "marcxml/3////0/0/" . ($first_bn + 3) }, - { ListRecords => { - record => [ @marcxml[3..5] ], - resumptionToken => { - content => re( qr{^marcxml/6////0/0/\d+$} ), - cursor => 6, + { verb => 'ListRecords', resumptionToken => "marcxml/3////0/0/" . ( $first_bn + 3 ) }, + { + ListRecords => { + record => [ @marcxml[ 3 .. 5 ] ], + resumptionToken => { + content => re(qr{^marcxml/6////0/0/\d+$}), + cursor => 6, + }, }, - }, -}); + } +); test_query( 'ListRecords marcxml with resumptionToken 2', - { verb => 'ListRecords', resumptionToken => "marcxml/6/1970-01-01T00:00:00Z/$date_to//0/0/" . ($first_bn + 6) }, - { ListRecords => { - record => [ @marcxml[6..8] ], - resumptionToken => { - content => re( qr{^marcxml/9/1970-01-01T00:00:00Z/$date_to//0/0/\d+$} ), - cursor => 9, + { verb => 'ListRecords', resumptionToken => "marcxml/6/1970-01-01T00:00:00Z/$date_to//0/0/" . ( $first_bn + 6 ) }, + { + ListRecords => { + record => [ @marcxml[ 6 .. 8 ] ], + resumptionToken => { + content => re(qr{^marcxml/9/1970-01-01T00:00:00Z/$date_to//0/0/\d+$}), + cursor => 9, + }, }, - }, -}); + } +); # Last record, so no resumption token test_query( 'ListRecords marcxml with resumptionToken 3, response without resumption', - { verb => 'ListRecords', resumptionToken => "marcxml/9/1970-01-01T00:00:00Z/$date_to//0/0/" . ($first_bn + 9) }, - { ListRecords => { - record => $marcxml[9], - }, -}); - -test_query('ListRecords oai_dc', {verb => 'ListRecords', metadataPrefix => 'oai_dc'}, { - ListRecords => { - record => [ @oaidc[0..2] ], - resumptionToken => { - content => re( qr{^oai_dc/3////0/0/\d+$} ), - cursor => 3, + { verb => 'ListRecords', resumptionToken => "marcxml/9/1970-01-01T00:00:00Z/$date_to//0/0/" . ( $first_bn + 9 ) }, + { + ListRecords => { + record => $marcxml[9], }, - }, -}); + } +); + +test_query( + 'ListRecords oai_dc', + { verb => 'ListRecords', metadataPrefix => 'oai_dc' }, + { + ListRecords => { + record => [ @oaidc[ 0 .. 2 ] ], + resumptionToken => { + content => re(qr{^oai_dc/3////0/0/\d+$}), + cursor => 3, + }, + }, + } +); test_query( 'ListRecords oai_dc with resumptionToken 1', - { verb => 'ListRecords', resumptionToken => "oai_dc/3////0/0/" . ($first_bn + 3) }, - { ListRecords => { - record => [ @oaidc[3..5] ], - resumptionToken => { - content => re( qr{^oai_dc/6////0/0/\d+$} ), - cursor => 6, + { verb => 'ListRecords', resumptionToken => "oai_dc/3////0/0/" . ( $first_bn + 3 ) }, + { + ListRecords => { + record => [ @oaidc[ 3 .. 5 ] ], + resumptionToken => { + content => re(qr{^oai_dc/6////0/0/\d+$}), + cursor => 6, + }, }, - }, -}); + } +); test_query( 'ListRecords oai_dc with resumptionToken 2', - { verb => 'ListRecords', resumptionToken => "oai_dc/6/1970-01-01T00:00:00Z/$date_to//0/0/" . ($first_bn + 6) }, - { ListRecords => { - record => [ @oaidc[6..8] ], - resumptionToken => { - content => re( qr{^oai_dc/9/1970-01-01T00:00:00Z/$date_to//0/0/\d+$} ), - cursor => 9, + { verb => 'ListRecords', resumptionToken => "oai_dc/6/1970-01-01T00:00:00Z/$date_to//0/0/" . ( $first_bn + 6 ) }, + { + ListRecords => { + record => [ @oaidc[ 6 .. 8 ] ], + resumptionToken => { + content => re(qr{^oai_dc/9/1970-01-01T00:00:00Z/$date_to//0/0/\d+$}), + cursor => 9, + }, }, - }, -}); + } +); # Last record, so no resumption token test_query( 'ListRecords oai_dc with resumptionToken 3, response without resumption', - { verb => 'ListRecords', resumptionToken => "oai_dc/9/1970-01-01T00:00:00Z/$date_to//0/0/" . ($first_bn + 9) }, - { ListRecords => { - record => $oaidc[9], - }, -}); + { verb => 'ListRecords', resumptionToken => "oai_dc/9/1970-01-01T00:00:00Z/$date_to//0/0/" . ( $first_bn + 9 ) }, + { + ListRecords => { + record => $oaidc[9], + }, + } +); # List records, but now transformed by XSLT -t::lib::Mocks::mock_preference("OAI-PMH:ConfFile" => File::Spec->rel2abs(dirname(__FILE__)) . "/oaiconf.yaml"); -test_query('ListRecords marcxml with xsl transformation', +t::lib::Mocks::mock_preference( "OAI-PMH:ConfFile" => File::Spec->rel2abs( dirname(__FILE__) ) . "/oaiconf.yaml" ); +test_query( + 'ListRecords marcxml with xsl transformation', { verb => 'ListRecords', metadataPrefix => 'marcxml' }, - { ListRecords => { - record => [ @marcxml_transformed[0..2] ], - resumptionToken => { - content => re( qr{^marcxml/3////0/0/\d+$} ), - cursor => 3, - } - }, -}); -t::lib::Mocks::mock_preference("OAI-PMH:ConfFile" => ''); + { + ListRecords => { + record => [ @marcxml_transformed[ 0 .. 2 ] ], + resumptionToken => { + content => re(qr{^marcxml/3////0/0/\d+$}), + cursor => 3, + } + }, + } +); +t::lib::Mocks::mock_preference( "OAI-PMH:ConfFile" => '' ); restore_time(); @@ -392,24 +450,26 @@ subtest 'Bug 19725: OAI-PMH ListRecords and ListIdentifiers should use biblio_me sleep 1; # Modify record to trigger auto update of timestamp - (my $biblionumber = $marcxml[0]->{header}->{identifier}) =~ s/^.*:(.*)/$1/; + ( my $biblionumber = $marcxml[0]->{header}->{identifier} ) =~ s/^.*:(.*)/$1/; my $biblio = Koha::Biblios->find($biblionumber); my $record = $biblio->metadata_record; - $record->append_fields(MARC::Field->new(999, '', '', z => '_')); + $record->append_fields( MARC::Field->new( 999, '', '', z => '_' ) ); ModBiblio( $record, $biblionumber ); my $from_dt = dt_from_string( - Koha::Biblio::Metadatas->find({ biblionumber => $biblionumber, format => 'marcxml', schema => 'MARC21' })->timestamp - ); + Koha::Biblio::Metadatas->find( { biblionumber => $biblionumber, format => 'marcxml', schema => 'MARC21' } ) + ->timestamp ); my $from = $from_dt->ymd . 'T' . $from_dt->hms . 'Z'; $oaidc[0]->{header}->{datestamp} = $from; test_query( 'ListRecords oai_dc with parameter from', { verb => 'ListRecords', metadataPrefix => 'oai_dc', from => $from }, - { ListRecords => { - record => $oaidc[0], - }, - }); + { + ListRecords => { + record => $oaidc[0], + }, + } + ); }; subtest 'Bug 20665: OAI-PMH Provider should reset the MySQL connection time zone' => sub { @@ -418,22 +478,24 @@ subtest 'Bug 20665: OAI-PMH Provider should reset the MySQL connection time zone # Set time zone to SYSTEM so that it can be checked later $dbh->do("SET time_zone='SYSTEM'"); - - test_query('ListIdentifiers without metadataPrefix', {verb => 'ListIdentifiers'}, { - error => { - code => 'badArgument', - content => "Required argument 'metadataPrefix' was undefined", - }, - }); + test_query( + 'ListIdentifiers without metadataPrefix', + { verb => 'ListIdentifiers' }, + { + error => { + code => 'badArgument', + content => "Required argument 'metadataPrefix' was undefined", + }, + } + ); my $sth = C4::Context->dbh->prepare('SELECT @@session.time_zone'); $sth->execute(); - my ( $tz ) = $sth->fetchrow(); + my ($tz) = $sth->fetchrow(); - ok ( $tz eq 'SYSTEM', 'MySQL connection time zone is SYSTEM' ); + ok( $tz eq 'SYSTEM', 'MySQL connection time zone is SYSTEM' ); }; - $schema->storage->txn_rollback; subtest 'ListSets tests' => sub { @@ -452,7 +514,8 @@ subtest 'ListSets tests' => sub { for my $i ( 1 .. 3 ) { AddOAISet( - { 'spec' => "setSpec_$i", + { + 'spec' => "setSpec_$i", 'name' => "setName_$i", } ); @@ -464,7 +527,8 @@ subtest 'ListSets tests' => sub { for my $i ( 4 .. 6 ) { AddOAISet( - { 'spec' => "setSpec_$i", + { + 'spec' => "setSpec_$i", 'name' => "setName_$i", } ); @@ -472,7 +536,8 @@ subtest 'ListSets tests' => sub { } AddOAISet( - { 'spec' => "setSpec_7", + { + 'spec' => "setSpec_7", 'name' => "setName_7", } ); @@ -480,36 +545,35 @@ subtest 'ListSets tests' => sub { test_query( 'ListSets', { verb => 'ListSets' }, - { ListSets => { - resumptionToken => { - content => re( qr{^/3////1/0/4$} ), - cursor => 3, - }, - set => \@first_page_sets - } + { + ListSets => { + resumptionToken => { + content => re(qr{^/3////1/0/4$}), + cursor => 3, + }, + set => \@first_page_sets + } } ); test_query( 'ListSets', { verb => 'ListSets', resumptionToken => '/3////1/0/4' }, - { ListSets => { - resumptionToken => { - content => re( qr{^/6////1/0/7$} ), - cursor => 6, - }, - set => \@second_page_sets - } + { + ListSets => { + resumptionToken => { + content => re(qr{^/6////1/0/7$}), + cursor => 6, + }, + set => \@second_page_sets + } } ); test_query( 'ListSets', - { verb => 'ListSets', resumptionToken => "/6////1/0/7" }, - { ListSets => { - set => { setSpec => "setSpec_7", setName => "setName_7" } - } - } + { verb => 'ListSets', resumptionToken => "/6////1/0/7" }, + { ListSets => { set => { setSpec => "setSpec_7", setName => "setName_7" } } } ); $schema->storage->txn_rollback; @@ -596,55 +660,52 @@ subtest 'Tests for timestamp handling' => sub { t::lib::Mocks::mock_preference( 'OAI::PMH' => 1 ); t::lib::Mocks::mock_preference( 'OAI-PMH:MaxCount' => 3 ); - t::lib::Mocks::mock_preference( 'OAI-PMH:ConfFile' => File::Spec->rel2abs(dirname(__FILE__)) . '/oaiconf_items.yaml' ); + t::lib::Mocks::mock_preference( + 'OAI-PMH:ConfFile' => File::Spec->rel2abs( dirname(__FILE__) ) . '/oaiconf_items.yaml' ); $schema->storage->txn_begin; - my $sth_metadata = $dbh->prepare('UPDATE biblio_metadata SET timestamp=? WHERE biblionumber=?'); + my $sth_metadata = $dbh->prepare('UPDATE biblio_metadata SET timestamp=? WHERE biblionumber=?'); my $sth_del_metadata = $dbh->prepare('UPDATE deletedbiblio_metadata SET timestamp=? WHERE biblionumber=?'); - my $sth_item = $dbh->prepare('UPDATE items SET timestamp=? WHERE itemnumber=?'); - my $sth_del_item = $dbh->prepare('UPDATE deleteditems SET timestamp=? WHERE itemnumber=?'); + my $sth_item = $dbh->prepare('UPDATE items SET timestamp=? WHERE itemnumber=?'); + my $sth_del_item = $dbh->prepare('UPDATE deleteditems SET timestamp=? WHERE itemnumber=?'); my $builder = t::lib::TestBuilder->new; - set_fixed_time(CORE::time()); + set_fixed_time( CORE::time() ); - my $utc_datetime = dt_from_string(undef, undef, 'UTC'); + my $utc_datetime = dt_from_string( undef, undef, 'UTC' ); my $utc_timestamp = $utc_datetime->ymd . 'T' . $utc_datetime->hms . 'Z'; - my $timestamp = dt_from_string(undef, 'sql'); + my $timestamp = dt_from_string( undef, 'sql' ); # Test a bib with one item my $biblio1 = $builder->build_sample_biblio; - Koha::Biblios->find($biblio1->biblionumber)->timestamp('1970-05-07 13:36:23')->store; + Koha::Biblios->find( $biblio1->biblionumber )->timestamp('1970-05-07 13:36:23')->store; - $sth_metadata->execute($timestamp, $biblio1->biblionumber); - my $item1 = $builder->build_sample_item( - { - biblionumber => $biblio1->biblionumber - } - ); - $sth_item->execute($timestamp, $item1->itemnumber); + $sth_metadata->execute( $timestamp, $biblio1->biblionumber ); + my $item1 = $builder->build_sample_item( { biblionumber => $biblio1->biblionumber } ); + $sth_item->execute( $timestamp, $item1->itemnumber ); my $list_items = { - verb => 'ListRecords', + verb => 'ListRecords', metadataPrefix => 'marc21', - from => $utc_timestamp + from => $utc_timestamp }; my $list_no_items = { - verb => 'ListRecords', + verb => 'ListRecords', metadataPrefix => 'marcxml', - from => $utc_timestamp + from => $utc_timestamp }; my $get_items = { - verb => 'GetRecord', + verb => 'GetRecord', metadataPrefix => 'marc21', - identifier => 'TEST:' . $biblio1->biblionumber + identifier => 'TEST:' . $biblio1->biblionumber }; my $get_no_items = { - verb => 'GetRecord', + verb => 'GetRecord', metadataPrefix => 'marcxml', - identifier => 'TEST:' . $biblio1->biblionumber + identifier => 'TEST:' . $biblio1->biblionumber }; my $expected = { @@ -689,11 +750,12 @@ subtest 'Tests for timestamp handling' => sub { $get_no_items, { GetRecord => $expected_no_items } ); - t::lib::Mocks::mock_preference('KohaAdminEmailAddress', 'root@localhost'); + t::lib::Mocks::mock_preference( 'KohaAdminEmailAddress', 'root@localhost' ); test_query( 'Identify - earliestDatestamp in the right format', { verb => 'Identify' }, - { Identify => { + { + Identify => { adminEmail => 'root@localhost', baseURL => 'http://localhost', compression => 'gzip', @@ -709,16 +771,12 @@ subtest 'Tests for timestamp handling' => sub { # Add an item 10 seconds later and check results set_relative_time(10); - $utc_datetime = dt_from_string(undef, undef, 'UTC'); + $utc_datetime = dt_from_string( undef, undef, 'UTC' ); $utc_timestamp = $utc_datetime->ymd . 'T' . $utc_datetime->hms . 'Z'; - $timestamp = dt_from_string(undef, 'sql'); + $timestamp = dt_from_string( undef, 'sql' ); - my $item2 = $builder->build_sample_item( - { - biblionumber => $biblio1->biblionumber - } - ); - $sth_item->execute($timestamp, $item2->itemnumber); + my $item2 = $builder->build_sample_item( { biblionumber => $biblio1->biblionumber } ); + $sth_item->execute( $timestamp, $item2->itemnumber ); $expected->{record}{header}{datestamp} = $utc_timestamp; $expected->{record}{metadata}{record} = @@ -747,13 +805,13 @@ subtest 'Tests for timestamp handling' => sub { # Set biblio timestamp 10 seconds later and check results set_relative_time(10); - $utc_datetime = dt_from_string(undef, undef, 'UTC'); - $utc_timestamp= $utc_datetime->ymd . 'T' . $utc_datetime->hms . 'Z'; - $timestamp = dt_from_string(undef, 'sql'); + $utc_datetime = dt_from_string( undef, undef, 'UTC' ); + $utc_timestamp = $utc_datetime->ymd . 'T' . $utc_datetime->hms . 'Z'; + $timestamp = dt_from_string( undef, 'sql' ); - $sth_metadata->execute($timestamp, $biblio1->biblionumber); + $sth_metadata->execute( $timestamp, $biblio1->biblionumber ); - $expected->{record}{header}{datestamp} = $utc_timestamp; + $expected->{record}{header}{datestamp} = $utc_timestamp; $expected_no_items->{record}{header}{datestamp} = $utc_timestamp; test_query( @@ -779,11 +837,11 @@ subtest 'Tests for timestamp handling' => sub { # Delete an item 10 seconds later and check results set_relative_time(10); - $utc_datetime = dt_from_string(undef, undef, 'UTC'); + $utc_datetime = dt_from_string( undef, undef, 'UTC' ); $utc_timestamp = $utc_datetime->ymd . 'T' . $utc_datetime->hms . 'Z'; - $item1->safe_delete({ skip_record_index =>1 }); - $sth_del_item->execute($timestamp, $item1->itemnumber); + $item1->safe_delete( { skip_record_index => 1 } ); + $sth_del_item->execute( $timestamp, $item1->itemnumber ); $expected->{record}{header}{datestamp} = $utc_timestamp; $expected->{record}{metadata}{record} = @@ -811,8 +869,8 @@ subtest 'Tests for timestamp handling' => sub { ); # Delete also the second item and verify results - $item2->safe_delete({ skip_record_index =>1 }); - $sth_del_item->execute($timestamp, $item2->itemnumber); + $item2->safe_delete( { skip_record_index => 1 } ); + $sth_del_item->execute( $timestamp, $item2->itemnumber ); $expected->{record}{metadata}{record} = XMLin( $biblio1->metadata_record( { embed_items => 1, interface => 'opac' } )->as_xml_record() ); @@ -840,19 +898,19 @@ subtest 'Tests for timestamp handling' => sub { # Delete the biblio 10 seconds later and check results set_relative_time(10); - $utc_datetime = dt_from_string(undef, undef, 'UTC'); + $utc_datetime = dt_from_string( undef, undef, 'UTC' ); $utc_timestamp = $utc_datetime->ymd . 'T' . $utc_datetime->hms . 'Z'; - $timestamp = dt_from_string(undef, 'sql'); + $timestamp = dt_from_string( undef, 'sql' ); - is(undef, DelBiblio($biblio1->biblionumber, { skip_record_index =>1 }), 'Biblio deleted'); - $sth_del_metadata->execute($timestamp, $biblio1->biblionumber); + is( undef, DelBiblio( $biblio1->biblionumber, { skip_record_index => 1 } ), 'Biblio deleted' ); + $sth_del_metadata->execute( $timestamp, $biblio1->biblionumber ); my $expected_header = { record => { header => { - datestamp => $utc_timestamp, + datestamp => $utc_timestamp, identifier => 'TEST:' . $biblio1->biblionumber, - status => 'deleted' + status => 'deleted' } } }; @@ -880,12 +938,12 @@ subtest 'Tests for timestamp handling' => sub { # Add a second biblio 10 seconds later and check that both are returned properly set_relative_time(10); - $utc_datetime = dt_from_string(undef, undef, 'UTC'); + $utc_datetime = dt_from_string( undef, undef, 'UTC' ); $utc_timestamp = $utc_datetime->ymd . 'T' . $utc_datetime->hms . 'Z'; - $timestamp = dt_from_string(undef, 'sql'); + $timestamp = dt_from_string( undef, 'sql' ); my $biblio2 = $builder->build_sample_biblio(); - $sth_metadata->execute($timestamp, $biblio2->biblionumber); + $sth_metadata->execute( $timestamp, $biblio2->biblionumber ); my $expected2 = { record => [ @@ -953,8 +1011,8 @@ subtest 'ListSets() tests' => sub { ); # Add a couple sets - AddOAISet({ spec => 'set_1', name => 'Set 1' }); - AddOAISet({ spec => 'set_2', name => 'Set 2' }); + AddOAISet( { spec => 'set_1', name => 'Set 1' } ); + AddOAISet( { spec => 'set_2', name => 'Set 2' } ); test_query( 'ListSets - no sets should return a noSetHierarchy exception', diff --git a/t/db_dependent/OAI/Sets.t b/t/db_dependent/OAI/Sets.t index 327643f267..9bb726ce7b 100755 --- a/t/db_dependent/OAI/Sets.t +++ b/t/db_dependent/OAI/Sets.t @@ -24,12 +24,13 @@ use Test::Warn; use MARC::Record; use Koha::Database; -use C4::OAI::Sets qw( AddOAISet GetOAISets GetOAISet GetOAISetBySpec ModOAISet ModOAISetMappings GetOAISetsMappings GetOAISetMappings AddOAISetsBiblios GetOAISetsBiblio ModOAISetsBiblios DelOAISet DelOAISetsBiblio UpdateOAISetsBiblio CalcOAISetsBiblio ); +use C4::OAI::Sets + qw( AddOAISet GetOAISets GetOAISet GetOAISetBySpec ModOAISet ModOAISetMappings GetOAISetsMappings GetOAISetMappings AddOAISetsBiblios GetOAISetsBiblio ModOAISetsBiblios DelOAISet DelOAISetsBiblio UpdateOAISetsBiblio CalcOAISetsBiblio ); use t::lib::TestBuilder; use t::lib::Mocks; -my $schema = Koha::Database->new->schema; +my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; my $dbh = C4::Context->dbh; @@ -39,33 +40,37 @@ $dbh->do('DELETE FROM oai_sets_mappings'); $dbh->do('DELETE FROM oai_sets_biblios'); my $builder = t::lib::TestBuilder->new; + # ---------- Testing AddOAISet ------------------ -ok (!defined(AddOAISet), 'AddOAISet without argument is undef'); +ok( !defined(AddOAISet), 'AddOAISet without argument is undef' ); -my $set_without_spec_and_name_and_desc = {}; -ok (!defined(AddOAISet($set_without_spec_and_name_and_desc)), 'AddOAISet without "field", "name" and "descriptions" fields is undef'); +my $set_without_spec_and_name_and_desc = {}; +ok( + !defined( AddOAISet($set_without_spec_and_name_and_desc) ), + 'AddOAISet without "field", "name" and "descriptions" fields is undef' +); -my $set_without_spec_and_name = { +my $set_without_spec_and_name = { 'descriptions' => ['descNoSpecNoName'], }; -ok (!defined(AddOAISet($set_without_spec_and_name)), 'AddOAISet without "field" and "name" fields is undef'); +ok( !defined( AddOAISet($set_without_spec_and_name) ), 'AddOAISet without "field" and "name" fields is undef' ); -my $set_without_spec = { - 'name' => 'nameNoSpec', +my $set_without_spec = { + 'name' => 'nameNoSpec', 'descriptions' => ['descNoSpec'], }; -ok (!defined(AddOAISet($set_without_spec)), 'AddOAISet without "field" field is undef'); +ok( !defined( AddOAISet($set_without_spec) ), 'AddOAISet without "field" field is undef' ); -my $set_without_name = { - 'spec' => 'specNoName', +my $set_without_name = { + 'spec' => 'specNoName', 'descriptions' => ['descNoName'], }; -ok (!defined(AddOAISet($set_without_name)), 'AddOAISet without "name" field is undef'); +ok( !defined( AddOAISet($set_without_name) ), 'AddOAISet without "name" field is undef' ); #Test to enter in the 'else' case of 'AddOAISet' line 280 { - my $dbi_st = Test::MockModule->new('DBI::st', no_auto => 1); # ref($sth) == 'DBI::st' - $dbi_st->mock('execute', sub { return 0; }); + my $dbi_st = Test::MockModule->new( 'DBI::st', no_auto => 1 ); # ref($sth) == 'DBI::st' + $dbi_st->mock( 'execute', sub { return 0; } ); my $setWrong = { 'spec' => 'specWrong', @@ -73,10 +78,10 @@ ok (!defined(AddOAISet($set_without_name)), 'AddOAISet without "name" field is u }; my $setWrong_id; warning_is { $setWrong_id = AddOAISet($setWrong) } - 'AddOAISet failed', - 'AddOAISet raises warning if there is a problem with SET spec or SET name'; + 'AddOAISet failed', + 'AddOAISet raises warning if there is a problem with SET spec or SET name'; - ok(!defined $setWrong_id, '$setWrong_id is not defined'); + ok( !defined $setWrong_id, '$setWrong_id is not defined' ); } #Adding a Set without description @@ -85,287 +90,282 @@ my $set1 = { 'name' => 'nameSet1', }; my $set1_id = AddOAISet($set1); -isa_ok(\$set1_id, 'SCALAR', '$set1_id is a SCALAR'); +isa_ok( \$set1_id, 'SCALAR', '$set1_id is a SCALAR' ); my $sth = $dbh->prepare("SELECT count(*) FROM oai_sets"); $sth->execute; my $setsCount = $sth->fetchrow_array; -is ($setsCount, 1, 'There is 1 set'); +is( $setsCount, 1, 'There is 1 set' ); $sth = $dbh->prepare("SELECT spec, name FROM oai_sets"); $sth->execute; -my ($spec, $name) = $sth->fetchrow_array; -is ($spec, 'specSet1', 'spec field is "specSet1"'); -is ($name, 'nameSet1', 'name field is "nameSet1"'); +my ( $spec, $name ) = $sth->fetchrow_array; +is( $spec, 'specSet1', 'spec field is "specSet1"' ); +is( $name, 'nameSet1', 'name field is "nameSet1"' ); $sth = $dbh->prepare("SELECT description FROM oai_sets_descriptions"); $sth->execute; -my $desc = $sth -> rows; -is ($desc, 0, 'There is NO set description'); +my $desc = $sth->rows; +is( $desc, 0, 'There is NO set description' ); #Adding a Set with a description my $set2 = { - 'spec' => 'specSet2', - 'name' => 'nameSet2', + 'spec' => 'specSet2', + 'name' => 'nameSet2', 'descriptions' => ['descSet2'], }; my $set2_id = AddOAISet($set2); -isa_ok(\$set2_id, 'SCALAR', '$set2_id is a SCALAR'); +isa_ok( \$set2_id, 'SCALAR', '$set2_id is a SCALAR' ); $sth = $dbh->prepare("SELECT count(*) FROM oai_sets"); $sth->execute; $setsCount = $sth->fetchrow_array; -is ($setsCount, 2, 'There is 2 sets'); +is( $setsCount, 2, 'There is 2 sets' ); $sth = $dbh->prepare("SELECT spec, name FROM oai_sets ORDER BY id DESC"); $sth->execute; -($spec, $name) = $sth->fetchrow_array; -is ($spec, 'specSet2', 'spec field is "specSet2"'); -is ($name, 'nameSet2', 'name field is "nameSet2"'); +( $spec, $name ) = $sth->fetchrow_array; +is( $spec, 'specSet2', 'spec field is "specSet2"' ); +is( $name, 'nameSet2', 'name field is "nameSet2"' ); $sth = $dbh->prepare("SELECT description FROM oai_sets_descriptions"); $sth->execute; $desc = $sth->fetchrow_array; -is ($desc, 'descSet2', 'description field is "descSet2"'); - +is( $desc, 'descSet2', 'description field is "descSet2"' ); # ---------- Testing GetOAISets ----------------- my $oai_sets = GetOAISets; -isa_ok($oai_sets, 'ARRAY', '$oai_sets is an array reference of hash reference describing the sets'); +isa_ok( $oai_sets, 'ARRAY', '$oai_sets is an array reference of hash reference describing the sets' ); -isa_ok($oai_sets->[0], 'HASH', '$set1 is defined as a hash'); -is ($oai_sets->[0]->{spec}, 'specSet1', 'spec field is "specSet1"'); -is ($oai_sets->[0]->{name}, 'nameSet1', 'name field is "nameSet1"'); +isa_ok( $oai_sets->[0], 'HASH', '$set1 is defined as a hash' ); +is( $oai_sets->[0]->{spec}, 'specSet1', 'spec field is "specSet1"' ); +is( $oai_sets->[0]->{name}, 'nameSet1', 'name field is "nameSet1"' ); -isa_ok($oai_sets->[1], 'HASH', '$set2 is defined as a hash'); -is ($oai_sets->[1]->{spec}, 'specSet2', 'spec field is "specSet2"'); -is ($oai_sets->[1]->{name}, 'nameSet2', 'name field is "nameSet2"'); -is_deeply ($oai_sets->[1]->{descriptions}, ['descSet2'], 'description field is "descSet2"'); - -ok(!defined($oai_sets->[2]), 'There are only 2 sets'); +isa_ok( $oai_sets->[1], 'HASH', '$set2 is defined as a hash' ); +is( $oai_sets->[1]->{spec}, 'specSet2', 'spec field is "specSet2"' ); +is( $oai_sets->[1]->{name}, 'nameSet2', 'name field is "nameSet2"' ); +is_deeply( $oai_sets->[1]->{descriptions}, ['descSet2'], 'description field is "descSet2"' ); +ok( !defined( $oai_sets->[2] ), 'There are only 2 sets' ); # ---------- Testing GetOAISet ------------------ -ok (!defined(GetOAISet), 'GetOAISet without argument is undef'); +ok( !defined(GetOAISet), 'GetOAISet without argument is undef' ); my $set = GetOAISet($set1_id); -isa_ok($set, 'HASH', '$set is a hash reference describing the set with the given set_id'); -is ($set->{spec}, 'specSet1', 'spec field is "specSet1"'); -is ($set->{name}, 'nameSet1', 'name field is "nameSet1"'); +isa_ok( $set, 'HASH', '$set is a hash reference describing the set with the given set_id' ); +is( $set->{spec}, 'specSet1', 'spec field is "specSet1"' ); +is( $set->{name}, 'nameSet1', 'name field is "nameSet1"' ); $set = GetOAISet($set2_id); -isa_ok($set, 'HASH', '$set is a hash reference describing the set with the given set_id'); -is ($set->{spec}, 'specSet2', 'spec field is "specSet2"'); -is ($set->{name}, 'nameSet2', 'name field is "nameSet2"'); -is_deeply ($set->{descriptions}, ['descSet2'], 'description field is "descSet2"'); - +isa_ok( $set, 'HASH', '$set is a hash reference describing the set with the given set_id' ); +is( $set->{spec}, 'specSet2', 'spec field is "specSet2"' ); +is( $set->{name}, 'nameSet2', 'name field is "nameSet2"' ); +is_deeply( $set->{descriptions}, ['descSet2'], 'description field is "descSet2"' ); # ---------- Testing GetOAISetBySpec ------------ -ok (!defined(GetOAISetBySpec), 'GetOAISetBySpec without argument is undef'); +ok( !defined(GetOAISetBySpec), 'GetOAISetBySpec without argument is undef' ); -$set = GetOAISetBySpec($set1->{spec}); -isa_ok($set, 'HASH', '$set is a hash describing the set whose spec is $oai_sets->[0]->{spec}'); -is ($set->{spec}, 'specSet1', 'spec field is "specSet1"'); -is ($set->{name}, 'nameSet1', 'name field is "nameSet1"'); +$set = GetOAISetBySpec( $set1->{spec} ); +isa_ok( $set, 'HASH', '$set is a hash describing the set whose spec is $oai_sets->[0]->{spec}' ); +is( $set->{spec}, 'specSet1', 'spec field is "specSet1"' ); +is( $set->{name}, 'nameSet1', 'name field is "nameSet1"' ); + +$set = GetOAISetBySpec( $set2->{spec} ); +isa_ok( $set, 'HASH', '$set is a hash describing the set whose spec is $oai_sets->[1]->{spec}' ); +is( $set->{spec}, 'specSet2', 'spec field is "specSet2"' ); +is( $set->{name}, 'nameSet2', 'name field is "nameSet2"' ); -$set = GetOAISetBySpec($set2->{spec}); -isa_ok($set, 'HASH', '$set is a hash describing the set whose spec is $oai_sets->[1]->{spec}'); -is ($set->{spec}, 'specSet2', 'spec field is "specSet2"'); -is ($set->{name}, 'nameSet2', 'name field is "nameSet2"'); #GetOAISetBySpec does't return the description field. - # ---------- Testing ModOAISet ------------------ -ok (!defined(ModOAISet), 'ModOAISet without argument is undef'); +ok( !defined(ModOAISet), 'ModOAISet without argument is undef' ); -my $new_set_without_id = { - 'spec' => 'specNoName', - 'name' => 'nameNoSpec', +my $new_set_without_id = { + 'spec' => 'specNoName', + 'name' => 'nameNoSpec', 'descriptions' => ['descNoSpecNoName'], }; my $res; warning_is { $res = ModOAISet($new_set_without_id) } - 'Set ID not defined, can\'t modify the set', - 'ModOAISet raises warning if Set ID is not defined'; -ok(!defined($res), 'ModOAISet returns undef if Set ID is not defined'); +'Set ID not defined, can\'t modify the set', + 'ModOAISet raises warning if Set ID is not defined'; +ok( !defined($res), 'ModOAISet returns undef if Set ID is not defined' ); -my $new_set_without_spec_and_name = { - 'id' => $set1_id, +my $new_set_without_spec_and_name = { + 'id' => $set1_id, 'descriptions' => ['descNoSpecNoName'], }; -ok (!defined(ModOAISet($new_set_without_spec_and_name)), 'ModOAISet without "field" and "name" fields is undef'); +ok( !defined( ModOAISet($new_set_without_spec_and_name) ), 'ModOAISet without "field" and "name" fields is undef' ); -my $new_set_without_spec = { - 'id' => $set1_id, - 'name' => 'nameNoSpec', +my $new_set_without_spec = { + 'id' => $set1_id, + 'name' => 'nameNoSpec', 'descriptions' => ['descNoSpec'], }; -ok (!defined(ModOAISet($new_set_without_spec)), 'ModOAISet without "field" field is undef'); +ok( !defined( ModOAISet($new_set_without_spec) ), 'ModOAISet without "field" field is undef' ); -my $new_set_without_name = { - 'id' => $set1_id, - 'spec' => 'specNoName', +my $new_set_without_name = { + 'id' => $set1_id, + 'spec' => 'specNoName', 'descriptions' => ['descNoName'], }; -ok (!defined(ModOAISet($new_set_without_name)), 'ModOAISet without "name" field is undef'); +ok( !defined( ModOAISet($new_set_without_name) ), 'ModOAISet without "name" field is undef' ); -my $new_set1 = { - 'id' => $set1_id, - 'spec' => 'new_specSet1', - 'name' => 'new_nameSet1', +my $new_set1 = { + 'id' => $set1_id, + 'spec' => 'new_specSet1', + 'name' => 'new_nameSet1', 'descriptions' => ['new_descSet1'], }; ModOAISet($new_set1); -my $new_set2 = { - 'id' => $set2_id, +my $new_set2 = { + 'id' => $set2_id, 'spec' => 'new_specSet2', 'name' => 'new_nameSet2', }; ModOAISet($new_set2); $set1 = GetOAISet($set1_id); -isa_ok($set1, 'HASH', '$set1 is defined as a hash'); -is ($set1->{spec}, 'new_specSet1', 'spec field is "new_specSet1"'); -is ($set1->{name}, 'new_nameSet1', 'name field is "new_nameSet1"'); -is_deeply ($set1->{descriptions}, ['new_descSet1'], 'description field is "new_descSet1"'); +isa_ok( $set1, 'HASH', '$set1 is defined as a hash' ); +is( $set1->{spec}, 'new_specSet1', 'spec field is "new_specSet1"' ); +is( $set1->{name}, 'new_nameSet1', 'name field is "new_nameSet1"' ); +is_deeply( $set1->{descriptions}, ['new_descSet1'], 'description field is "new_descSet1"' ); $set2 = GetOAISet($set2_id); -isa_ok($set2, 'HASH', '$new_set2 is defined as a hash'); -is ($set2->{spec}, 'new_specSet2', 'spec field is "new_specSet2"'); -is ($set2->{name}, 'new_nameSet2', 'name field is "new_nameSet2"'); - +isa_ok( $set2, 'HASH', '$new_set2 is defined as a hash' ); +is( $set2->{spec}, 'new_specSet2', 'spec field is "new_specSet2"' ); +is( $set2->{name}, 'new_nameSet2', 'name field is "new_nameSet2"' ); # ---------- Testing ModOAISetMappings ---------- -ok (!defined(ModOAISetMappings), 'ModOAISetMappings without argument is undef'); +ok( !defined(ModOAISetMappings), 'ModOAISetMappings without argument is undef' ); + #Add 1st mapping for set1 my $mapping1 = [ { - marcfield => '206', + marcfield => '206', marcsubfield => 'a', - operator => 'equal', - marcvalue => 'myMarcValue' + operator => 'equal', + marcvalue => 'myMarcValue' }, ]; -ModOAISetMappings($set1_id, $mapping1); +ModOAISetMappings( $set1_id, $mapping1 ); $sth = $dbh->prepare("SELECT count(*) FROM oai_sets_mappings"); $sth->execute; my $mappingsCount = $sth->fetchrow_array; -is ($mappingsCount, 1, 'There is 1 mapping'); +is( $mappingsCount, 1, 'There is 1 mapping' ); $sth = $dbh->prepare("SELECT marcfield, marcsubfield, operator, marcvalue FROM oai_sets_mappings"); $sth->execute; -my ($marcfield, $marcsubfield, $operator, $marcvalue) = $sth->fetchrow_array; -is ($marcfield, '206', 'marcfield field is "206"'); -is ($marcsubfield, 'a', 'marcsubfield field is "a"'); -is ($operator, 'equal', 'operator field is "equal"'); -is ($marcvalue, 'myMarcValue', 'marcvalue field is "myMarcValue"'); +my ( $marcfield, $marcsubfield, $operator, $marcvalue ) = $sth->fetchrow_array; +is( $marcfield, '206', 'marcfield field is "206"' ); +is( $marcsubfield, 'a', 'marcsubfield field is "a"' ); +is( $operator, 'equal', 'operator field is "equal"' ); +is( $marcvalue, 'myMarcValue', 'marcvalue field is "myMarcValue"' ); #Mod 1st mapping of set1 my $mapping1_bis = [ { - marcfield => '256', + marcfield => '256', marcsubfield => 'b', - operator => 'notequal', - marcvalue => 'myMarcValueBis' + operator => 'notequal', + marcvalue => 'myMarcValueBis' }, ]; -ModOAISetMappings($set1_id, $mapping1_bis); +ModOAISetMappings( $set1_id, $mapping1_bis ); $sth = $dbh->prepare("SELECT count(*) FROM oai_sets_mappings"); $sth->execute; $mappingsCount = $sth->fetchrow_array; -is ($mappingsCount, 1, 'There is 1 mapping'); +is( $mappingsCount, 1, 'There is 1 mapping' ); $sth = $dbh->prepare("SELECT marcfield, marcsubfield, operator, marcvalue FROM oai_sets_mappings"); $sth->execute; -($marcfield, $marcsubfield, $operator, $marcvalue) = $sth->fetchrow_array; -is ($marcfield, '256', 'marcfield field is "256"'); -is ($marcsubfield, 'b', 'marcsubfield field is "b"'); -is ($operator, 'notequal', 'operator field is "notequal"'); -is ($marcvalue, 'myMarcValueBis', 'marcvalue field is "myMarcValueBis"'); +( $marcfield, $marcsubfield, $operator, $marcvalue ) = $sth->fetchrow_array; +is( $marcfield, '256', 'marcfield field is "256"' ); +is( $marcsubfield, 'b', 'marcsubfield field is "b"' ); +is( $operator, 'notequal', 'operator field is "notequal"' ); +is( $marcvalue, 'myMarcValueBis', 'marcvalue field is "myMarcValueBis"' ); #Add 1st mapping of set2 my $mapping2 = [ { - marcfield => '306', + marcfield => '306', marcsubfield => 'c', - operator => 'equal', - marcvalue => 'myOtherMarcValue' + operator => 'equal', + marcvalue => 'myOtherMarcValue' }, ]; -ModOAISetMappings($set2_id, $mapping2); +ModOAISetMappings( $set2_id, $mapping2 ); $sth = $dbh->prepare("SELECT count(*) FROM oai_sets_mappings"); $sth->execute; $mappingsCount = $sth->fetchrow_array; -is ($mappingsCount, 2, 'There is 2 mappings'); +is( $mappingsCount, 2, 'There is 2 mappings' ); -$sth = $dbh->prepare("SELECT marcfield, marcsubfield, operator, marcvalue FROM oai_sets_mappings ORDER BY set_id DESC LIMIT 1"); +$sth = $dbh->prepare( + "SELECT marcfield, marcsubfield, operator, marcvalue FROM oai_sets_mappings ORDER BY set_id DESC LIMIT 1"); $sth->execute; -($marcfield, $marcsubfield, $operator, $marcvalue) = $sth->fetchrow_array; -is ($marcfield, '306', 'marcfield field is "306"'); -is ($marcsubfield, 'c', 'marcsubfield field is "c"'); -is ($operator, 'equal', 'operator field is "equal"'); -is ($marcvalue, 'myOtherMarcValue', 'marcvalue field is "myOtherMarcValue"'); - +( $marcfield, $marcsubfield, $operator, $marcvalue ) = $sth->fetchrow_array; +is( $marcfield, '306', 'marcfield field is "306"' ); +is( $marcsubfield, 'c', 'marcsubfield field is "c"' ); +is( $operator, 'equal', 'operator field is "equal"' ); +is( $marcvalue, 'myOtherMarcValue', 'marcvalue field is "myOtherMarcValue"' ); # ---------- Testing GetOAISetsMappings --------- my $mappings = GetOAISetsMappings; -isa_ok($mappings, 'HASH', '$mappings is a hashref of arrayrefs of hashrefs'); -isa_ok($mappings->{$set1_id}, 'ARRAY', '$mappings->{$set1_id} is a arrayrefs of hashrefs'); -isa_ok($mappings->{$set1_id}->[0], 'HASH', '$mappings->{$set1_id}->[0] is a hashrefs'); -is ($mappings->{$set1_id}->[0]->{marcfield}, '256', 'marcfield field is "256"'); -is ($mappings->{$set1_id}->[0]->{marcsubfield}, 'b', 'marcsubfield field is "b"'); -is ($mappings->{$set1_id}->[0]->{operator}, 'notequal', 'operator field is "notequal"'); -is ($mappings->{$set1_id}->[0]->{marcvalue}, 'myMarcValueBis', 'marcvalue field is "myMarcValueBis"'); - -isa_ok($mappings->{$set2_id}, 'ARRAY', '$mappings->{$set2_id} is a arrayrefs of hashrefs'); -isa_ok($mappings->{$set2_id}, 'ARRAY', '$mappings->{$set2_id} is a arrayrefs of hashrefs'); -isa_ok($mappings->{$set2_id}->[0], 'HASH', '$mappings->{$set2_id}->[0] is a hashrefs'); -is ($mappings->{$set2_id}->[0]->{marcfield}, '306', 'marcfield field is "306"'); -is ($mappings->{$set2_id}->[0]->{marcsubfield}, 'c', 'marcsubfield field is "c"'); -is ($mappings->{$set2_id}->[0]->{operator}, 'equal', 'operator field is "equal"'); -is ($mappings->{$set2_id}->[0]->{marcvalue}, 'myOtherMarcValue', 'marcvalue field is "myOtherMarcValue"'); +isa_ok( $mappings, 'HASH', '$mappings is a hashref of arrayrefs of hashrefs' ); +isa_ok( $mappings->{$set1_id}, 'ARRAY', '$mappings->{$set1_id} is a arrayrefs of hashrefs' ); +isa_ok( $mappings->{$set1_id}->[0], 'HASH', '$mappings->{$set1_id}->[0] is a hashrefs' ); +is( $mappings->{$set1_id}->[0]->{marcfield}, '256', 'marcfield field is "256"' ); +is( $mappings->{$set1_id}->[0]->{marcsubfield}, 'b', 'marcsubfield field is "b"' ); +is( $mappings->{$set1_id}->[0]->{operator}, 'notequal', 'operator field is "notequal"' ); +is( $mappings->{$set1_id}->[0]->{marcvalue}, 'myMarcValueBis', 'marcvalue field is "myMarcValueBis"' ); +isa_ok( $mappings->{$set2_id}, 'ARRAY', '$mappings->{$set2_id} is a arrayrefs of hashrefs' ); +isa_ok( $mappings->{$set2_id}, 'ARRAY', '$mappings->{$set2_id} is a arrayrefs of hashrefs' ); +isa_ok( $mappings->{$set2_id}->[0], 'HASH', '$mappings->{$set2_id}->[0] is a hashrefs' ); +is( $mappings->{$set2_id}->[0]->{marcfield}, '306', 'marcfield field is "306"' ); +is( $mappings->{$set2_id}->[0]->{marcsubfield}, 'c', 'marcsubfield field is "c"' ); +is( $mappings->{$set2_id}->[0]->{operator}, 'equal', 'operator field is "equal"' ); +is( $mappings->{$set2_id}->[0]->{marcvalue}, 'myOtherMarcValue', 'marcvalue field is "myOtherMarcValue"' ); # ---------- Testing GetOAISetMappings ---------- -ok (!defined(GetOAISetMappings), 'GetOAISetMappings without argument is undef'); +ok( !defined(GetOAISetMappings), 'GetOAISetMappings without argument is undef' ); my $set_mappings1 = GetOAISetMappings($set1_id); -isa_ok($set_mappings1->[0], 'HASH', '$set_mappings1->[0] is a hashref'); -is ($set_mappings1->[0]->{marcfield}, '256', 'marcfield field is "256"'); -is ($set_mappings1->[0]->{marcsubfield}, 'b', 'marcsubfield field is "b"'); -is ($set_mappings1->[0]->{operator}, 'notequal', 'operator field is "notequal"'); -is ($set_mappings1->[0]->{marcvalue}, 'myMarcValueBis', 'marcvalue field is "myMarcValueBis"'); +isa_ok( $set_mappings1->[0], 'HASH', '$set_mappings1->[0] is a hashref' ); +is( $set_mappings1->[0]->{marcfield}, '256', 'marcfield field is "256"' ); +is( $set_mappings1->[0]->{marcsubfield}, 'b', 'marcsubfield field is "b"' ); +is( $set_mappings1->[0]->{operator}, 'notequal', 'operator field is "notequal"' ); +is( $set_mappings1->[0]->{marcvalue}, 'myMarcValueBis', 'marcvalue field is "myMarcValueBis"' ); my $set_mappings2 = GetOAISetMappings($set2_id); -isa_ok($mappings->{$set2_id}->[0], 'HASH', '$mappings->{$set2_id}->[0] is a hashref'); -is ($mappings->{$set2_id}->[0]->{marcfield}, '306', 'marcfield field is "306"'); -is ($mappings->{$set2_id}->[0]->{marcsubfield}, 'c', 'marcsubfield field is "c"'); -is ($mappings->{$set2_id}->[0]->{operator}, 'equal', 'operator field is "equal"'); -is ($mappings->{$set2_id}->[0]->{marcvalue}, 'myOtherMarcValue', 'marcvalue field is "myOtherMarcValue"'); - +isa_ok( $mappings->{$set2_id}->[0], 'HASH', '$mappings->{$set2_id}->[0] is a hashref' ); +is( $mappings->{$set2_id}->[0]->{marcfield}, '306', 'marcfield field is "306"' ); +is( $mappings->{$set2_id}->[0]->{marcsubfield}, 'c', 'marcsubfield field is "c"' ); +is( $mappings->{$set2_id}->[0]->{operator}, 'equal', 'operator field is "equal"' ); +is( $mappings->{$set2_id}->[0]->{marcvalue}, 'myOtherMarcValue', 'marcvalue field is "myOtherMarcValue"' ); # ---------- Testing AddOAISetsBiblios with OAI-PMH:AutoUpdateSets disabled ---------- -ok (!defined(AddOAISetsBiblios), 'AddOAISetsBiblios without argument is undef'); -ok (!defined(AddOAISetsBiblios(my $arg=[])), 'AddOAISetsBiblios with a no HASH argument is undef'); -ok (defined(AddOAISetsBiblios($arg={})), 'AddOAISetsBiblios with a HASH argument is def'); +ok( !defined(AddOAISetsBiblios), 'AddOAISetsBiblios without argument is undef' ); +ok( !defined( AddOAISetsBiblios( my $arg = [] ) ), 'AddOAISetsBiblios with a no HASH argument is undef' ); +ok( defined( AddOAISetsBiblios( $arg = {} ) ), 'AddOAISetsBiblios with a HASH argument is def' ); t::lib::Mocks::mock_preference( 'OAI-PMH:AutoUpdateSets', 0 ); # Create a biblio instance for testing -my $biblio_1 = $builder->build_sample_biblio({ author => 'Moffat, Steven' }); +my $biblio_1 = $builder->build_sample_biblio( { author => 'Moffat, Steven' } ); my $biblionumber1 = $biblio_1->biblionumber; -isa_ok(\$biblionumber1, 'SCALAR', '$biblionumber1 is a SCALAR'); -my $biblio_2 = $builder->build_sample_biblio({ author => 'Moffat, Steven' }); +isa_ok( \$biblionumber1, 'SCALAR', '$biblionumber1 is a SCALAR' ); +my $biblio_2 = $builder->build_sample_biblio( { author => 'Moffat, Steven' } ); my $biblionumber2 = $biblio_2->biblionumber; -isa_ok(\$biblionumber2, 'SCALAR', '$biblionumber2 is a SCALAR'); +isa_ok( \$biblionumber2, 'SCALAR', '$biblionumber2 is a SCALAR' ); my $oai_sets_biblios = { - $set1_id => [$biblionumber1, $biblionumber2], # key is the set_id, and value is an array ref of biblionumbers + $set1_id => [ $biblionumber1, $biblionumber2 ], # key is the set_id, and value is an array ref of biblionumbers $set2_id => [], }; AddOAISetsBiblios($oai_sets_biblios); @@ -373,73 +373,72 @@ AddOAISetsBiblios($oai_sets_biblios); $sth = $dbh->prepare("SELECT count(*) FROM oai_sets_biblios"); $sth->execute; my $bibliosCount = $sth->fetchrow_array; -is ($bibliosCount, 2, 'There are 2 biblios in oai_sets_biblios'); +is( $bibliosCount, 2, 'There are 2 biblios in oai_sets_biblios' ); #testing biblio for set1_id $sth = $dbh->prepare("SELECT * FROM oai_sets_biblios WHERE set_id = ?"); $sth->execute($set1_id); my $count = $sth->rows; -is ($count, '2', '$set_id1 has 2 biblio'); +is( $count, '2', '$set_id1 has 2 biblio' ); $sth->execute($set1_id); my $line = ${ $sth->fetchall_arrayref( {} ) }[0]; -is($line->{set_id}, $set1_id, "set_id is good"); -is($line->{biblionumber}, $biblionumber1, "biblionumber is good"); +is( $line->{set_id}, $set1_id, "set_id is good" ); +is( $line->{biblionumber}, $biblionumber1, "biblionumber is good" ); $sth->execute($set1_id); $line = ${ $sth->fetchall_arrayref( {} ) }[1]; -is($line->{set_id}, $set1_id, "set_id is good"); -is($line->{biblionumber}, $biblionumber2, "biblionumber is good"); +is( $line->{set_id}, $set1_id, "set_id is good" ); +is( $line->{biblionumber}, $biblionumber2, "biblionumber is good" ); #testing biblio for set2_id $sth->execute($set2_id); $count = $sth->rows; -is ($count, '0', '$set_id2 has 0 biblio'); +is( $count, '0', '$set_id2 has 0 biblio' ); # ---------- Testing AddOAISetsBiblios with OAI-PMH:AutoUpdateSets enabled ---------- t::lib::Mocks::mock_preference( 'OAI-PMH:AutoUpdateSets', 1 ); -my $biblio_3 = $builder->build_sample_biblio({ author => 'Moffat, Steven' }); +my $biblio_3 = $builder->build_sample_biblio( { author => 'Moffat, Steven' } ); my $biblionumber3 = $biblio_3->biblionumber; -isa_ok(\$biblionumber3, 'SCALAR', '$biblionumber3 is a SCALAR'); +isa_ok( \$biblionumber3, 'SCALAR', '$biblionumber3 is a SCALAR' ); $sth = $dbh->prepare("SELECT count(*) FROM oai_sets_biblios"); $sth->execute; $bibliosCount = $sth->fetchrow_array; -is ($bibliosCount, 3, 'There are 3 biblios in oai_sets_biblios'); +is( $bibliosCount, 3, 'There are 3 biblios in oai_sets_biblios' ); #testing biblio for set1_id $sth = $dbh->prepare("SELECT * FROM oai_sets_biblios WHERE set_id = ?"); $sth->execute($set1_id); $count = $sth->rows; -is ($count, '3', '$set_id1 has 3 biblio'); +is( $count, '3', '$set_id1 has 3 biblio' ); $sth->execute($set1_id); $line = ${ $sth->fetchall_arrayref( {} ) }[2]; -is($line->{set_id}, $set1_id, "set_id is good"); -is($line->{biblionumber}, $biblionumber3, "biblionumber is good"); +is( $line->{set_id}, $set1_id, "set_id is good" ); +is( $line->{biblionumber}, $biblionumber3, "biblionumber is good" ); # ---------- Testing GetOAISetsBiblio ----------- $oai_sets = GetOAISetsBiblio($biblionumber1); -isa_ok($oai_sets, 'ARRAY', '$oai_sets is an arrayref of hashref where each element of the array is a set'); -isa_ok($oai_sets->[0], 'HASH', '$oai_sets->[0] is a hashrefs of $set1_id'); -is($oai_sets->[0]->{id}, $set1_id, 'id is $set1_id'); -is($oai_sets->[0]->{spec}, $set1->{spec}, 'spec is new_specset1'); -is($oai_sets->[0]->{name}, $set1->{name}, 'name is new_specname1'); +isa_ok( $oai_sets, 'ARRAY', '$oai_sets is an arrayref of hashref where each element of the array is a set' ); +isa_ok( $oai_sets->[0], 'HASH', '$oai_sets->[0] is a hashrefs of $set1_id' ); +is( $oai_sets->[0]->{id}, $set1_id, 'id is $set1_id' ); +is( $oai_sets->[0]->{spec}, $set1->{spec}, 'spec is new_specset1' ); +is( $oai_sets->[0]->{name}, $set1->{name}, 'name is new_specname1' ); $oai_sets = GetOAISetsBiblio($biblionumber2); -isa_ok($oai_sets, 'ARRAY', '$oai_sets is an arrayref of hashref where each element of the array is a set'); -isa_ok($oai_sets->[0], 'HASH', '$oai_sets->[0] is a hashrefs of $set2_id'); -is($oai_sets->[0]->{id}, $set1_id, 'id is $set1_id'); -is($oai_sets->[0]->{spec}, $set1->{spec}, 'spec is new_specset1'); -is($oai_sets->[0]->{name}, $set1->{name}, 'name is new_specname1'); - +isa_ok( $oai_sets, 'ARRAY', '$oai_sets is an arrayref of hashref where each element of the array is a set' ); +isa_ok( $oai_sets->[0], 'HASH', '$oai_sets->[0] is a hashrefs of $set2_id' ); +is( $oai_sets->[0]->{id}, $set1_id, 'id is $set1_id' ); +is( $oai_sets->[0]->{spec}, $set1->{spec}, 'spec is new_specset1' ); +is( $oai_sets->[0]->{name}, $set1->{name}, 'name is new_specname1' ); # ---------- Testing ModOAISetsBiblios ---------- -ok (!defined(ModOAISetsBiblios), 'ModOAISetsBiblios without argument is undef'); -ok (!defined(ModOAISetsBiblios($arg=[])), 'ModOAISetsBiblios with a no HASH argument is undef'); -ok (defined(ModOAISetsBiblios($arg={})), 'ModOAISetsBiblios with a HASH argument is def'); +ok( !defined(ModOAISetsBiblios), 'ModOAISetsBiblios without argument is undef' ); +ok( !defined( ModOAISetsBiblios( $arg = [] ) ), 'ModOAISetsBiblios with a no HASH argument is undef' ); +ok( defined( ModOAISetsBiblios( $arg = {} ) ), 'ModOAISetsBiblios with a HASH argument is def' ); $oai_sets_biblios = { $set1_id => [$biblionumber1], @@ -450,66 +449,63 @@ ModOAISetsBiblios($oai_sets_biblios); $sth = $dbh->prepare("SELECT count(*) FROM oai_sets_biblios"); $sth->execute; $bibliosCount = $sth->fetchrow_array; -is ($bibliosCount, 2, 'There are 2 biblios in oai_sets_biblios'); +is( $bibliosCount, 2, 'There are 2 biblios in oai_sets_biblios' ); #testing biblio for set1_id $sth = $dbh->prepare("SELECT * FROM oai_sets_biblios WHERE set_id = ?"); $sth->execute($set1_id); $count = $sth->rows; -is ($count, '1', '$set_id1 has 2 biblio'); +is( $count, '1', '$set_id1 has 2 biblio' ); $sth->execute($set1_id); $line = ${ $sth->fetchall_arrayref( {} ) }[0]; -is($line->{set_id}, $set1_id, "set_id is good"); -is($line->{biblionumber}, $biblionumber1, "biblionumber is good"); +is( $line->{set_id}, $set1_id, "set_id is good" ); +is( $line->{biblionumber}, $biblionumber1, "biblionumber is good" ); #testing biblio for set2_id $sth->execute($set2_id); $count = $sth->rows; -is ($count, '1', '$set_id2 has 1 biblio'); +is( $count, '1', '$set_id2 has 1 biblio' ); $sth->execute($set2_id); $line = ${ $sth->fetchall_arrayref( {} ) }[0]; -is($line->{set_id}, $set2_id, "set_id is good"); -is($line->{biblionumber}, $biblionumber2, "biblionumber is good"); - +is( $line->{set_id}, $set2_id, "set_id is good" ); +is( $line->{biblionumber}, $biblionumber2, "biblionumber is good" ); # ---------- Testing DelOAISetsBiblio ----------- -ok (!defined(DelOAISetsBiblio), 'DelOAISetsBiblio without argument is undef'); +ok( !defined(DelOAISetsBiblio), 'DelOAISetsBiblio without argument is undef' ); DelOAISetsBiblio($biblionumber1); -is_deeply(GetOAISetsBiblio($biblionumber1), [], "no biblio1 appear in any OAI sets"); +is_deeply( GetOAISetsBiblio($biblionumber1), [], "no biblio1 appear in any OAI sets" ); DelOAISetsBiblio($biblionumber2); -is_deeply(GetOAISetsBiblio($biblionumber2), [], "no biblio2 appear in any OAI sets"); - +is_deeply( GetOAISetsBiblio($biblionumber2), [], "no biblio2 appear in any OAI sets" ); # ---------- Testing DelOAISet ------------------ -ok (!defined(DelOAISet), 'DelOAISet without argument is undef'); +ok( !defined(DelOAISet), 'DelOAISet without argument is undef' ); DelOAISet($set1_id); $sth = $dbh->prepare("SELECT count(*) FROM oai_sets"); $sth->execute; $setsCount = $sth->fetchrow_array; -is ($setsCount, 1, 'There is 1 set left'); +is( $setsCount, 1, 'There is 1 set left' ); $set1 = GetOAISet($set1_id); -is_deeply ($set1, {}, '$set1 is empty'); +is_deeply( $set1, {}, '$set1 is empty' ); DelOAISet($set2_id); $sth = $dbh->prepare("SELECT count(*) FROM oai_sets"); $sth->execute; $setsCount = $sth->fetchrow_array; -is ($setsCount, 0, 'There is no set anymore'); +is( $setsCount, 0, 'There is no set anymore' ); $set2 = GetOAISet($set2_id); -is_deeply ($set2, {}, '$set2 is empty'); - -$oai_sets=GetOAISets; -is_deeply ($oai_sets, [], '$oai_sets is empty'); +is_deeply( $set2, {}, '$set2 is empty' ); +$oai_sets = GetOAISets; +is_deeply( $oai_sets, [], '$oai_sets is empty' ); # ---------- Testing UpdateOAISetsBiblio -------- -ok (!defined(UpdateOAISetsBiblio), 'UpdateOAISetsBiblio without argument is undef'); -ok (!defined(UpdateOAISetsBiblio($arg)), 'UpdateOAISetsBiblio with only 1 argument is undef'); +ok( !defined(UpdateOAISetsBiblio), 'UpdateOAISetsBiblio without argument is undef' ); +ok( !defined( UpdateOAISetsBiblio($arg) ), 'UpdateOAISetsBiblio with only 1 argument is undef' ); #Create a set my $setVH = { @@ -522,43 +518,41 @@ my $setVH_id = AddOAISet($setVH); my $marcflavour = C4::Context->preference('marcflavour'); my $mappingsVH; -if ($marcflavour eq 'UNIMARC' ){ +if ( $marcflavour eq 'UNIMARC' ) { $mappingsVH = [ { - marcfield => '200', + marcfield => '200', marcsubfield => 'f', - operator => 'equal', - marcvalue => 'Victor Hugo' + operator => 'equal', + marcvalue => 'Victor Hugo' + } + ]; +} else { + $mappingsVH = [ + { + marcfield => '100', + marcsubfield => 'a', + operator => 'equal', + marcvalue => 'Victor Hugo' } ]; } -else { - $mappingsVH = [ - { - marcfield => '100', - marcsubfield => 'a', - operator => 'equal', - marcvalue => 'Victor Hugo' - } - ]; -} -ModOAISetMappings($setVH_id, $mappingsVH); - +ModOAISetMappings( $setVH_id, $mappingsVH ); #Create a biblio notice corresponding at one of mappings -my $biblio_VH = $builder->build_sample_biblio({ author => 'Victor Hugo' }); +my $biblio_VH = $builder->build_sample_biblio( { author => 'Victor Hugo' } ); my $biblionumberVH = $biblio_VH->biblionumber; #Update -my $biblio = Koha::Biblios->find( $biblionumberVH ); +my $biblio = Koha::Biblios->find($biblionumberVH); my $record = $biblio->metadata->record; -UpdateOAISetsBiblio($biblionumberVH, $record); +UpdateOAISetsBiblio( $biblionumberVH, $record ); #is biblio attached to setVH ? my $oai_setsVH = GetOAISetsBiblio($biblionumberVH); -is($oai_setsVH->[0]->{id}, $setVH_id, 'id is ok'); -is($oai_setsVH->[0]->{spec}, $setVH->{spec}, 'id is ok'); -is($oai_setsVH->[0]->{name}, $setVH->{name}, 'id is ok'); +is( $oai_setsVH->[0]->{id}, $setVH_id, 'id is ok' ); +is( $oai_setsVH->[0]->{spec}, $setVH->{spec}, 'id is ok' ); +is( $oai_setsVH->[0]->{name}, $setVH->{name}, 'id is ok' ); subtest 'OAI-PMH:AutoUpdateSetsEmbedItemData' => sub { @@ -615,10 +609,10 @@ subtest 'OAI-PMH:AutoUpdateSetsEmbedItemData' => sub { }; # ---------- Testing CalcOAISetsBiblio ---------- -ok (!defined(CalcOAISetsBiblio), 'CalcOAISetsBiblio without argument is undef'); +ok( !defined(CalcOAISetsBiblio), 'CalcOAISetsBiblio without argument is undef' ); my @setsEq = CalcOAISetsBiblio($record); -is_deeply(@setsEq, $setVH_id, 'The $record only belongs to $setVH'); +is_deeply( @setsEq, $setVH_id, 'The $record only belongs to $setVH' ); #Testing CalcOAISetsBiblio for a mapping which operator is 'notequal' #Create a set @@ -632,46 +626,44 @@ my $setNotVH_id = AddOAISet($setNotVH); $marcflavour = C4::Context->preference('marcflavour'); my $mappingsNotVH; -if ($marcflavour eq 'UNIMARC' ){ +if ( $marcflavour eq 'UNIMARC' ) { $mappingsNotVH = [ { - marcfield => '200', + marcfield => '200', marcsubfield => 'f', - operator => 'notequal', - marcvalue => 'Victor Hugo' + operator => 'notequal', + marcvalue => 'Victor Hugo' + } + ]; +} else { + $mappingsNotVH = [ + { + marcfield => '100', + marcsubfield => 'a', + operator => 'notequal', + marcvalue => 'Victor Hugo' } ]; } -else { - $mappingsNotVH = [ - { - marcfield => '100', - marcsubfield => 'a', - operator => 'notequal', - marcvalue => 'Victor Hugo' - } - ]; -} -ModOAISetMappings($setNotVH_id, $mappingsNotVH); - +ModOAISetMappings( $setNotVH_id, $mappingsNotVH ); #Create a biblio notice corresponding at one of mappings -my $biblio_NotVH = $builder->build_sample_biblio({ author => 'Sponge, Bob' }); +my $biblio_NotVH = $builder->build_sample_biblio( { author => 'Sponge, Bob' } ); my $biblionumberNotVH = $biblio_NotVH->biblionumber; #Update -$biblio = Koha::Biblios->find( $biblionumberNotVH ); +$biblio = Koha::Biblios->find($biblionumberNotVH); $record = $biblio->metadata->record; -UpdateOAISetsBiblio($biblionumberNotVH, $record); +UpdateOAISetsBiblio( $biblionumberNotVH, $record ); my @setsNotEq = CalcOAISetsBiblio($record); -is_deeply(@setsNotEq, $setNotVH_id, 'The $record only belongs to $setNotVH'); +is_deeply( @setsNotEq, $setNotVH_id, 'The $record only belongs to $setNotVH' ); # ---------- Testing CalcOAISetsBiblio with repeated field ---------- # Delete all existing sets to avoid false positives my $all_sets = GetOAISets; -foreach my $set ( @$all_sets ) { +foreach my $set (@$all_sets) { DelOAISet( $set->{'id'} ); } @@ -690,52 +682,56 @@ my $setRep = { 'name' => 'Rep' }; my $setRep_id = AddOAISet($setRep); + # Create a mapping : 374$a should be "A" my $mappingRepA = [ { - marcfield => '374', + marcfield => '374', marcsubfield => 'a', - operator => 'equal', - marcvalue => 'A', + operator => 'equal', + marcvalue => 'A', }, ]; + # Add the mapping to the set -ModOAISetMappings($setRep_id, $mappingRepA); +ModOAISetMappings( $setRep_id, $mappingRepA ); # Get a list of set ids the record belongs to my @setsRepA = CalcOAISetsBiblio($record_rep); -is_deeply(\@setsRepA, [$setRep_id], 'The $record belongs to $setRep_id (matching on first field, first subfield)'); +is_deeply( \@setsRepA, [$setRep_id], 'The $record belongs to $setRep_id (matching on first field, first subfield)' ); # Create another mapping : 374$a should now be "B" my $mappingRepB = [ { - marcfield => '374', + marcfield => '374', marcsubfield => 'a', - operator => 'equal', - marcvalue => 'B', + operator => 'equal', + marcvalue => 'B', }, ]; + # Replace the first mapping with the second one -ModOAISetMappings($setRep_id, $mappingRepB); +ModOAISetMappings( $setRep_id, $mappingRepB ); # Get a list of set ids the record belongs to my @setsRepB = CalcOAISetsBiblio($record_rep); -is_deeply(\@setsRepB, [$setRep_id], 'The $record belongs to $setRep_id (matching on second field, first subfield)'); +is_deeply( \@setsRepB, [$setRep_id], 'The $record belongs to $setRep_id (matching on second field, first subfield)' ); # Create another mapping : 374$a should now be "C" my $mappingRepC = [ { - marcfield => '374', + marcfield => '374', marcsubfield => 'a', - operator => 'equal', - marcvalue => 'C', + operator => 'equal', + marcvalue => 'C', }, ]; + # Replace the first mapping with the second one -ModOAISetMappings($setRep_id, $mappingRepC); +ModOAISetMappings( $setRep_id, $mappingRepC ); # Get a list of set ids the record belongs to my @setsRepC = CalcOAISetsBiblio($record_rep); -is_deeply(\@setsRepC, [$setRep_id], 'The $record belongs to $setRep_id (matching on second field, second subfield)'); +is_deeply( \@setsRepC, [$setRep_id], 'The $record belongs to $setRep_id (matching on second field, second subfield)' ); $schema->storage->txn_rollback; diff --git a/t/db_dependent/Overdues.t b/t/db_dependent/Overdues.t index af719faf76..979f378a25 100755 --- a/t/db_dependent/Overdues.t +++ b/t/db_dependent/Overdues.t @@ -11,11 +11,11 @@ use Koha::Libraries; use t::lib::Mocks; use t::lib::TestBuilder; -use_ok('C4::Overdues', qw( GetOverdueMessageTransportTypes GetBranchcodesWithOverdueRules UpdateFine )); -can_ok('C4::Overdues', 'GetOverdueMessageTransportTypes'); -can_ok('C4::Overdues', 'GetBranchcodesWithOverdueRules'); +use_ok( 'C4::Overdues', qw( GetOverdueMessageTransportTypes GetBranchcodesWithOverdueRules UpdateFine ) ); +can_ok( 'C4::Overdues', 'GetOverdueMessageTransportTypes' ); +can_ok( 'C4::Overdues', 'GetBranchcodesWithOverdueRules' ); -my $schema = Koha::Database->new->schema; +my $schema = Koha::Database->new->schema; my $builder = t::lib::TestBuilder->new; $schema->storage->txn_begin; @@ -27,19 +27,24 @@ $dbh->do(q|DELETE FROM message_transport_types|); $dbh->do(q|DELETE FROM overduerules|); $dbh->do(q|DELETE FROM overduerules_transport_types|); -$dbh->do(q| +$dbh->do( + q| INSERT INTO message_transport_types( message_transport_type ) VALUES ('email'), ('phone'), ('print'), ('sms') -|); +| +); -$dbh->do(q| +$dbh->do( + q| INSERT INTO overduerules ( overduerules_id, branchcode, categorycode ) VALUES (1, 'CPL', 'PT'), (2, 'CPL', 'YA'), (3, '', 'PT'), (4, '', 'YA') -|); +| +); -$dbh->do(q|INSERT INTO overduerules_transport_types (overduerules_id, letternumber, message_transport_type) VALUES +$dbh->do( + q|INSERT INTO overduerules_transport_types (overduerules_id, letternumber, message_transport_type) VALUES (1, 1, 'email'), (1, 2, 'sms'), (1, 3, 'email'), @@ -51,36 +56,43 @@ $dbh->do(q|INSERT INTO overduerules_transport_types (overduerules_id, letternumb (3, 3, 'email'), (3, 3, 'print'), (4, 2, 'sms') -|); +| +); my $mtts; -$mtts = C4::Overdues::GetOverdueMessageTransportTypes('CPL', 'PT'); +$mtts = C4::Overdues::GetOverdueMessageTransportTypes( 'CPL', 'PT' ); is( $mtts, undef, 'GetOverdueMessageTransportTypes: returns undef if no letternumber given' ); -$mtts = C4::Overdues::GetOverdueMessageTransportTypes('CPL', undef, 1); +$mtts = C4::Overdues::GetOverdueMessageTransportTypes( 'CPL', undef, 1 ); is( $mtts, undef, 'GetOverdueMessageTransportTypes: returns undef if no categorycode given' ); $mtts = C4::Overdues::GetOverdueMessageTransportTypes('CPL'); is( $mtts, undef, 'GetOverdueMessageTransportTypes: returns undef if no letternumber and categorycode given' ); -$mtts = C4::Overdues::GetOverdueMessageTransportTypes('CPL', 'PT', 1); +$mtts = C4::Overdues::GetOverdueMessageTransportTypes( 'CPL', 'PT', 1 ); is_deeply( $mtts, ['email'], 'GetOverdueMessageTransportTypes: first overdue is by email for PT (CPL)' ); -$mtts = C4::Overdues::GetOverdueMessageTransportTypes('CPL', 'PT', 2); +$mtts = C4::Overdues::GetOverdueMessageTransportTypes( 'CPL', 'PT', 2 ); is_deeply( $mtts, ['sms'], 'GetOverdueMessageTransportTypes: second overdue is by sms for PT (CPL)' ); -$mtts = C4::Overdues::GetOverdueMessageTransportTypes('CPL', 'PT', 3); +$mtts = C4::Overdues::GetOverdueMessageTransportTypes( 'CPL', 'PT', 3 ); is_deeply( $mtts, ['email'], 'GetOverdueMessageTransportTypes: third overdue is by email for PT (CPL)' ); -$mtts = C4::Overdues::GetOverdueMessageTransportTypes('', 'PT', 1); +$mtts = C4::Overdues::GetOverdueMessageTransportTypes( '', 'PT', 1 ); is_deeply( $mtts, ['email'], 'GetOverdueMessageTransportTypes: first overdue is by email for PT (default)' ); -$mtts = C4::Overdues::GetOverdueMessageTransportTypes('', 'PT', 2); -is_deeply( $mtts, ['email', 'sms'], 'GetOverdueMessageTransportTypes: second overdue is by email and sms for PT (default)' ); +$mtts = C4::Overdues::GetOverdueMessageTransportTypes( '', 'PT', 2 ); +is_deeply( + $mtts, [ 'email', 'sms' ], + 'GetOverdueMessageTransportTypes: second overdue is by email and sms for PT (default)' +); -$mtts = C4::Overdues::GetOverdueMessageTransportTypes('', 'PT', 3); -is_deeply( $mtts, ['print', 'sms', 'email'], 'GetOverdueMessageTransportTypes: third overdue is by print, sms and email for PT (default). With print in first.' ); +$mtts = C4::Overdues::GetOverdueMessageTransportTypes( '', 'PT', 3 ); +is_deeply( + $mtts, [ 'print', 'sms', 'email' ], + 'GetOverdueMessageTransportTypes: third overdue is by print, sms and email for PT (default). With print in first.' +); # Test GetBranchcodesWithOverdueRules $dbh->do(q|DELETE FROM overduerules|); @@ -89,50 +101,64 @@ my @overdue_branches; warnings_are { @overdue_branches = C4::Overdues::GetBranchcodesWithOverdueRules(); } [], "No warnings thrown when no overdue rules exist"; -$dbh->do(q| +$dbh->do( + q| INSERT INTO overduerules ( branchcode,categorycode, delay1,letter1,debarred1, delay2,letter2,debarred2, delay3,letter3,debarred3 ) VALUES ( '', '', 1, 'LETTER_CODE1', 1, 5, 'LETTER_CODE2', 1, 10, 'LETTER_CODE3', 1 ) -|); +| +); my @branchcodes = map { $_->branchcode } Koha::Libraries->search->as_list; @overdue_branches = C4::Overdues::GetBranchcodesWithOverdueRules(); -is_deeply( [ sort @overdue_branches ], [ sort @branchcodes ], 'If a default rule exists, all branches should be returned' ); +is_deeply( + [ sort @overdue_branches ], [ sort @branchcodes ], + 'If a default rule exists, all branches should be returned' +); -$dbh->do(q| +$dbh->do( + q| INSERT INTO overduerules ( branchcode,categorycode, delay1,letter1,debarred1, delay2,letter2,debarred2, delay3,letter3,debarred3 ) VALUES ( 'CPL', '', 1, 'LETTER_CODE1', 1, 5, 'LETTER_CODE2', 1, 10, 'LETTER_CODE3', 1 ) -|); +| +); @overdue_branches = C4::Overdues::GetBranchcodesWithOverdueRules(); -is_deeply( [ sort @overdue_branches ], [ sort @branchcodes ], 'If a default rule exists and a specific rule exists, all branches should be returned' ); +is_deeply( + [ sort @overdue_branches ], [ sort @branchcodes ], + 'If a default rule exists and a specific rule exists, all branches should be returned' +); $dbh->do(q|DELETE FROM overduerules|); -$dbh->do(q| +$dbh->do( + q| INSERT INTO overduerules ( branchcode,categorycode, delay1,letter1,debarred1, delay2,letter2,debarred2, delay3,letter3,debarred3 ) VALUES ( 'CPL', '', 1, 'LETTER_CODE1', 1, 5, 'LETTER_CODE2', 1, 10, 'LETTER_CODE3', 1 ) -|); +| +); @overdue_branches = C4::Overdues::GetBranchcodesWithOverdueRules(); -is_deeply( \@overdue_branches, ['CPL'] , 'If only a specific rule exist, only 1 branch should be returned' ); +is_deeply( \@overdue_branches, ['CPL'], 'If only a specific rule exist, only 1 branch should be returned' ); $dbh->do(q|DELETE FROM overduerules|); -$dbh->do(q| +$dbh->do( + q| INSERT INTO overduerules ( branchcode,categorycode, delay1,letter1,debarred1, delay2,letter2,debarred2, delay3,letter3,debarred3 ) VALUES ( 'CPL', '', 1, 'LETTER_CODE1_CPL', 1, 5, 'LETTER_CODE2_CPL', 1, 10, 'LETTER_CODE3_CPL', 1 ), ( 'MPL', '', 1, 'LETTER_CODE1_MPL', 1, 5, 'LETTER_CODE2_MPL', 1, 10, 'LETTER_CODE3_MPL', 1 ) -|); +| +); @overdue_branches = C4::Overdues::GetBranchcodesWithOverdueRules(); -is_deeply( \@overdue_branches, ['CPL', 'MPL'] , 'If only 2 specific rules exist, 2 branches should be returned' ); +is_deeply( \@overdue_branches, [ 'CPL', 'MPL' ], 'If only 2 specific rules exist, 2 branches should be returned' ); $schema->storage->txn_rollback; @@ -171,9 +197,9 @@ subtest 'UpdateFine tests' => sub { } ); - my $fines = Koha::Account::Lines->search( - { borrowernumber => $patron->borrowernumber } ); + my $fines = Koha::Account::Lines->search( { borrowernumber => $patron->borrowernumber } ); is( $fines->count, 0, "No fine added when amount is 0" ); + # Total : Outstanding : MaxFine # 0 : 0 : 100 @@ -188,14 +214,14 @@ subtest 'UpdateFine tests' => sub { } ); - $fines = Koha::Account::Lines->search( - { borrowernumber => $patron->borrowernumber } ); + $fines = Koha::Account::Lines->search( { borrowernumber => $patron->borrowernumber } ); is( $fines->count, 1, "Fine added when amount is greater than 0" ); my $fine = $fines->next; - is( $fine->amount+0, 50, "Fine amount correctly set to 50" ); - is( $fine->amountoutstanding+0, 50, "Fine amountoutstanding correctly set to 50" ); - is( $fine->issue_id, $checkout1->issue_id, "Fine is associated with the correct issue" ); - is( $fine->itemnumber, $checkout1->itemnumber, "Fine is associated with the correct item" ); + is( $fine->amount + 0, 50, "Fine amount correctly set to 50" ); + is( $fine->amountoutstanding + 0, 50, "Fine amountoutstanding correctly set to 50" ); + is( $fine->issue_id, $checkout1->issue_id, "Fine is associated with the correct issue" ); + is( $fine->itemnumber, $checkout1->itemnumber, "Fine is associated with the correct item" ); + # Total : Outstanding : MaxFine # 50 : 50 : 100 @@ -210,12 +236,12 @@ subtest 'UpdateFine tests' => sub { } ); - $fines = Koha::Account::Lines->search( - { borrowernumber => $patron->borrowernumber } ); + $fines = Koha::Account::Lines->search( { borrowernumber => $patron->borrowernumber } ); is( $fines->count, 1, "Existing fine updated" ); $fine = $fines->next; - is( $fine->amount+0, 80, "Fine amount correctly updated to 80" ); - is( $fine->amountoutstanding+0, 80, "Fine amountoutstanding correctly updated to 80" ); + is( $fine->amount + 0, 80, "Fine amount correctly updated to 80" ); + is( $fine->amountoutstanding + 0, 80, "Fine amountoutstanding correctly updated to 80" ); + # Total : Outstanding : MaxFine # 80 : 80 : 100 @@ -234,17 +260,18 @@ subtest 'UpdateFine tests' => sub { { borrowernumber => $patron->borrowernumber }, { order_by => { '-asc' => 'accountlines_id' } } ); - is( $fines->count, 2, "New fine added for second checkout" ); + is( $fines->count, 2, "New fine added for second checkout" ); $fine = $fines->next; - is( $fine->amount+0, 80, "First fine amount unchanged" ); - is( $fine->amountoutstanding+0, 80, "First fine amountoutstanding unchanged" ); + is( $fine->amount + 0, 80, "First fine amount unchanged" ); + is( $fine->amountoutstanding + 0, 80, "First fine amountoutstanding unchanged" ); my $fine2 = $fines->next; - is( $fine2->amount+0, 20, "Second fine capped at '20' by MaxFine" ); - is( $fine2->amountoutstanding+0, 20, "Second fine amountoutstanding capped at '20' by MaxFine" ); - is( $fine2->issue_id, $checkout2->issue_id, "Second fine is associated with the correct issue" ); - is( $fine2->itemnumber, $checkout2->itemnumber, "Second fine is associated with the correct item" ); - is( $fine->amount + $fine2->amount, '100', "Total fines = 100" ); + is( $fine2->amount + 0, 20, "Second fine capped at '20' by MaxFine" ); + is( $fine2->amountoutstanding + 0, 20, "Second fine amountoutstanding capped at '20' by MaxFine" ); + is( $fine2->issue_id, $checkout2->issue_id, "Second fine is associated with the correct issue" ); + is( $fine2->itemnumber, $checkout2->itemnumber, "Second fine is associated with the correct item" ); + is( $fine->amount + $fine2->amount, '100', "Total fines = 100" ); is( $fine->amountoutstanding + $fine2->amountoutstanding, '100', "Total outstanding = 100" ); + # Total : Outstanding : MaxFine # 100 : 100 : 100 @@ -264,22 +291,24 @@ subtest 'UpdateFine tests' => sub { { borrowernumber => $patron->borrowernumber }, { order_by => { '-asc' => 'accountlines_id' } } ); - is( $fines->count, 2, "Existing fine updated for second checkout, no new fine added" ); + is( $fines->count, 2, "Existing fine updated for second checkout, no new fine added" ); $fine = $fines->next; - is( $fine->amount+0, 80, "First fine amount unchanged" ); - is( $fine->amountoutstanding+0, 80, "First fine amountoutstanding unchanged" ); + is( $fine->amount + 0, 80, "First fine amount unchanged" ); + is( $fine->amountoutstanding + 0, 80, "First fine amountoutstanding unchanged" ); $fine2 = $fines->next; - is( $fine2->amount+0, 20, "Second fine capped at '20' by MaxFine" ); - is( $fine2->amountoutstanding+0, 20, "Second fine amountoutstanding capped at '20' by MaxFine" ); - is( $fine2->issue_id, $checkout2->issue_id, "Second fine is associated with the correct issue" ); - is( $fine2->itemnumber, $checkout2->itemnumber, "Second fine is associated with the correct item" ); - is( $fine->amount + $fine2->amount, '100', "Total fines = 100" ); + is( $fine2->amount + 0, 20, "Second fine capped at '20' by MaxFine" ); + is( $fine2->amountoutstanding + 0, 20, "Second fine amountoutstanding capped at '20' by MaxFine" ); + is( $fine2->issue_id, $checkout2->issue_id, "Second fine is associated with the correct issue" ); + is( $fine2->itemnumber, $checkout2->itemnumber, "Second fine is associated with the correct item" ); + is( $fine->amount + $fine2->amount, '100', "Total fines = 100" ); is( $fine->amountoutstanding + $fine2->amountoutstanding, '100', "Total outstanding = 100" ); + # Total : Outstanding : MaxFine # 100 : 100 : 100 # Partial pay fine 1 $fine->amountoutstanding(50)->store; + # Total : Outstanding : MaxFine # 100 : 50 : 100 @@ -298,15 +327,16 @@ subtest 'UpdateFine tests' => sub { { borrowernumber => $patron->borrowernumber }, { order_by => { '-asc' => 'accountlines_id' } } ); - is( $fines->count, 2, "Still two fines after second checkout update" ); + is( $fines->count, 2, "Still two fines after second checkout update" ); $fine = $fines->next; - is( $fine->amount+0, 80, "First fine amount unchanged" ); - is( $fine->amountoutstanding+0, 50, "First fine amountoutstanding unchanged" ); + is( $fine->amount + 0, 80, "First fine amount unchanged" ); + is( $fine->amountoutstanding + 0, 50, "First fine amountoutstanding unchanged" ); $fine2 = $fines->next; - is( $fine2->amount+0, 30, "Second fine increased after partial payment of first" ); - is( $fine2->amountoutstanding+0, 30, "Second fine amountoutstanding increased after partial payment of first" ); - is( $fine->amount + $fine2->amount, '110', "Total fines = 100" ); - is( $fine->amountoutstanding + $fine2->amountoutstanding, '80', "Total outstanding = 80" ); + is( $fine2->amount + 0, 30, "Second fine increased after partial payment of first" ); + is( $fine2->amountoutstanding + 0, 30, "Second fine amountoutstanding increased after partial payment of first" ); + is( $fine->amount + $fine2->amount, '110', "Total fines = 100" ); + is( $fine->amountoutstanding + $fine2->amountoutstanding, '80', "Total outstanding = 80" ); + # Total : Outstanding : MaxFine # 110 : 80 : 100 @@ -328,27 +358,35 @@ subtest 'UpdateFine tests' => sub { { borrowernumber => $patron->borrowernumber }, { order_by => { '-asc' => 'accountlines_id' } } ); - is( $fines->count, 3, "Third fine added for overdue renewal" ); + is( $fines->count, 3, "Third fine added for overdue renewal" ); $fine = $fines->next; - is( $fine->amount+0, 80, "First fine amount unchanged" ); - is( $fine->amountoutstanding+0, 50, "First fine amountoutstanding unchanged" ); + is( $fine->amount + 0, 80, "First fine amount unchanged" ); + is( $fine->amountoutstanding + 0, 50, "First fine amountoutstanding unchanged" ); $fine2 = $fines->next; - is( $fine2->amount+0, 30, "Second fine amount unchanged" ); - is( $fine2->amountoutstanding+0, 30, "Second fine amountoutstanding unchanged" ); + is( $fine2->amount + 0, 30, "Second fine amount unchanged" ); + is( $fine2->amountoutstanding + 0, 30, "Second fine amountoutstanding unchanged" ); my $fine3 = $fines->next; - is( $fine3->amount+0, 20, "Third fine amount capped due to MaxFine" ); - is( $fine3->amountoutstanding+0, 20, "Third fine amountoutstanding capped at '20' by MaxFine" ); - is( $fine3->issue_id, $checkout1->issue_id, "Third fine is associated with the correct issue" ); - is( $fine3->itemnumber, $checkout1->itemnumber, "Third fine is associated with the correct item" ); + is( $fine3->amount + 0, 20, "Third fine amount capped due to MaxFine" ); + is( $fine3->amountoutstanding + 0, 20, "Third fine amountoutstanding capped at '20' by MaxFine" ); + is( $fine3->issue_id, $checkout1->issue_id, "Third fine is associated with the correct issue" ); + is( $fine3->itemnumber, $checkout1->itemnumber, "Third fine is associated with the correct item" ); is( $fine->amount + $fine2->amount + $fine3->amount, '130', "Total fines = 130" ); - is( $fine->amountoutstanding + $fine2->amountoutstanding + $fine3->amountoutstanding, '100', "Total outstanding = 100" ); + is( + $fine->amountoutstanding + $fine2->amountoutstanding + $fine3->amountoutstanding, '100', + "Total outstanding = 100" + ); + # Total : Outstanding : MaxFine # 130 : 100 : 100 # Payoff accruing fine and ensure next increment doesn't create a new one (bug #24146) $fine3->amountoutstanding('0')->store; is( $fine->amount + $fine2->amount + $fine3->amount, '130', "Total fines = 130" ); - is( $fine->amountoutstanding + $fine2->amountoutstanding + $fine3->amountoutstanding, '80', "Total outstanding = 80" ); + is( + $fine->amountoutstanding + $fine2->amountoutstanding + $fine3->amountoutstanding, '80', + "Total outstanding = 80" + ); + # Total : Outstanding : MaxFine # 130 : 80 : 100 @@ -367,20 +405,24 @@ subtest 'UpdateFine tests' => sub { { borrowernumber => $patron->borrowernumber }, { order_by => { '-asc' => 'accountlines_id' } } ); - is( $fines->count, 3, "Still three fines after third checkout update" ); + is( $fines->count, 3, "Still three fines after third checkout update" ); $fine = $fines->next; - is( $fine->amount+0, 80, "First fine amount unchanged" ); - is( $fine->amountoutstanding+0, 50, "First fine amountoutstanding unchanged" ); + is( $fine->amount + 0, 80, "First fine amount unchanged" ); + is( $fine->amountoutstanding + 0, 50, "First fine amountoutstanding unchanged" ); $fine2 = $fines->next; - is( $fine2->amount+0, 30, "Second fine amount unchanged" ); - is( $fine2->amountoutstanding+0, 30, "Second fine amountoutstanding unchanged" ); + is( $fine2->amount + 0, 30, "Second fine amount unchanged" ); + is( $fine2->amountoutstanding + 0, 30, "Second fine amountoutstanding unchanged" ); $fine3 = $fines->next; - is( $fine3->amount+0, 40, "Third fine amount capped due to MaxFine" ); - is( $fine3->amountoutstanding+0, 20, "Third fine amountoutstanding increased ..." ); - is( $fine3->issue_id, $checkout1->issue_id, "Third fine is associated with the correct issue" ); - is( $fine3->itemnumber, $checkout1->itemnumber, "Third fine is associated with the correct item" ); + is( $fine3->amount + 0, 40, "Third fine amount capped due to MaxFine" ); + is( $fine3->amountoutstanding + 0, 20, "Third fine amountoutstanding increased ..." ); + is( $fine3->issue_id, $checkout1->issue_id, "Third fine is associated with the correct issue" ); + is( $fine3->itemnumber, $checkout1->itemnumber, "Third fine is associated with the correct item" ); is( $fine->amount + $fine2->amount + $fine3->amount, '150', "Total fines = 150" ); - is( $fine->amountoutstanding + $fine2->amountoutstanding + $fine3->amountoutstanding, '100', "Total outstanding = 100" ); + is( + $fine->amountoutstanding + $fine2->amountoutstanding + $fine3->amountoutstanding, '100', + "Total outstanding = 100" + ); + # Total : Outstanding : MaxFine # 150 : 100 : 100 @@ -403,14 +445,14 @@ subtest 'UpdateFine tests' => sub { { borrowernumber => $patron->borrowernumber }, { order_by => { '-asc' => 'accountlines_id' } } ); - is( $fines->count, 3, "Still only three fines after MaxFine cap removed" ); + is( $fines->count, 3, "Still only three fines after MaxFine cap removed" ); $fine = $fines->next; - is( $fine->amount+0, 80, "First fine amount unchanged" ); + is( $fine->amount + 0, 80, "First fine amount unchanged" ); $fine2 = $fines->next; - is( $fine2->amount+0, 30, "Second fine amount unchanged" ); + is( $fine2->amount + 0, 30, "Second fine amount unchanged" ); $fine3 = $fines->next; - is( $fine3->amount+0, 50, "Third fine increased now MaxFine cap is disabled" ); - is( $fine3->amountoutstanding+0, 30, "Third fine increased now MaxFine cap is disabled" ); + is( $fine3->amount + 0, 50, "Third fine increased now MaxFine cap is disabled" ); + is( $fine3->amountoutstanding + 0, 30, "Third fine increased now MaxFine cap is disabled" ); # If somehow the fine should be reduced, we changed rules or checkout date or something UpdateFine( @@ -427,14 +469,14 @@ subtest 'UpdateFine tests' => sub { { borrowernumber => $patron->borrowernumber }, { order_by => { '-asc' => 'accountlines_id' } } ); - is( $fines->count, 3, "Still only three fines after MaxFine cap removed and third fine altered" ); + is( $fines->count, 3, "Still only three fines after MaxFine cap removed and third fine altered" ); $fine = $fines->next; - is( $fine->amount+0, 80, "First fine amount unchanged" ); + is( $fine->amount + 0, 80, "First fine amount unchanged" ); $fine2 = $fines->next; - is( $fine2->amount+0, 30, "Second fine amount unchanged" ); + is( $fine2->amount + 0, 30, "Second fine amount unchanged" ); $fine3 = $fines->next; - is( $fine3->amount+0, 30, "Third fine reduced" ); - is( $fine3->amountoutstanding+0, 10, "Third fine amount outstanding is reduced" ); + is( $fine3->amount + 0, 30, "Third fine reduced" ); + is( $fine3->amountoutstanding + 0, 10, "Third fine amount outstanding is reduced" ); # Ensure maxfine calculations work correctly for floats (bug #25127) # 7.2 (maxfine) - 7.2 (total_amount_other) != 8.88178419700125e-16 (😢) @@ -506,8 +548,11 @@ subtest 'UpdateFine tests' => sub { { borrowernumber => $patron_1->borrowernumber }, { order_by => { '-asc' => 'accountlines_id' } } ); - is( $fines->count, 4, "New amount should be 0 so no fine added" ); - ok( C4::Circulation::AddReturn( $item_1->barcode, $item_1->homebranch, 1), "Returning the item and forgiving fines succeeds"); + is( $fines->count, 4, "New amount should be 0 so no fine added" ); + ok( + C4::Circulation::AddReturn( $item_1->barcode, $item_1->homebranch, 1 ), + "Returning the item and forgiving fines succeeds" + ); t::lib::Mocks::mock_preference( 'MaxFine', 0 ); @@ -523,13 +568,13 @@ subtest 'UpdateFine tests' => sub { due => $checkout_2->date_due } ); - $fine = Koha::Account::Lines->search({ issue_id => $checkout_2->issue_id })->single; - ok( $fine, 'Fine added for checkout 2'); - is( $fine->amount, "1.800000", "Fine amount is 1.800000 as expected"); + $fine = Koha::Account::Lines->search( { issue_id => $checkout_2->issue_id } )->single; + ok( $fine, 'Fine added for checkout 2' ); + is( $fine->amount, "1.800000", "Fine amount is 1.800000 as expected" ); $fine->amountoutstanding(0)->store; $fine->discard_changes; - is( $fine->amountoutstanding + 0, 0, "Fine was paid off"); + is( $fine->amountoutstanding + 0, 0, "Fine was paid off" ); UpdateFine( { issue_id => $checkout_2->issue_id, @@ -539,7 +584,8 @@ subtest 'UpdateFine tests' => sub { due => $checkout_2->date_due } ); - my $refunds = Koha::Account::Lines->search({ itemnumber => $item_2->itemnumber, credit_type_code => 'OVERPAYMENT' }); + my $refunds = + Koha::Account::Lines->search( { itemnumber => $item_2->itemnumber, credit_type_code => 'OVERPAYMENT' } ); is( $refunds->count, 0, "Overpayment refund not added when the amounts are equal" ); # Adding an OVERDUE fine not linked with a checkout (possible with historical OVERDUE fines) @@ -547,8 +593,8 @@ subtest 'UpdateFine tests' => sub { { class => "Koha::Account::Lines", value => { - borrowernumber => $patron_1->borrowernumber, - issue_id => undef, + borrowernumber => $patron_1->borrowernumber, + issue_id => undef, debit_type_code => 'OVERDUE', } } @@ -564,7 +610,8 @@ subtest 'UpdateFine tests' => sub { due => $checkout_2->date_due } ); - } [], 'No warning generated if fine is not linked with a checkout'; + } + [], 'No warning generated if fine is not linked with a checkout'; $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/Passwordrecovery.t b/t/db_dependent/Passwordrecovery.t index 02001a913b..332e9d357d 100755 --- a/t/db_dependent/Passwordrecovery.t +++ b/t/db_dependent/Passwordrecovery.t @@ -44,7 +44,7 @@ $email_sender_module->mock( use_ok('Koha::Patron::Password::Recovery'); -t::lib::Mocks::mock_preference('KohaAdminEmailAddress', 'test@koha-community.org'); +t::lib::Mocks::mock_preference( 'KohaAdminEmailAddress', 'test@koha-community.org' ); my $schema = Koha::Database->new()->schema(); $schema->storage->txn_begin(); @@ -52,54 +52,56 @@ $schema->storage->txn_begin(); # # Start with fresh data # -my $builder = t::lib::TestBuilder->new; +my $builder = t::lib::TestBuilder->new; my $borrowernumber1 = '2000000000'; my $borrowernumber2 = '2000000001'; my $borrowernumber3 = '2000000002'; -my $userid1 = "I83MFItzRpGPxD3vW0"; -my $userid2 = "Gh5t43980hfSAOcvne"; -my $userid3 = "adsfada80hfSAOcvne"; -my $email1 = $userid1 . '@koha-community.org'; -my $email2 = $userid2 . '@koha-community.org'; -my $email3 = $userid3 . '@koha-community.org'; -my $uuid1 = "ABCD1234"; -my $uuid2 = "WXYZ0987"; -my $uuid3 = "LMNO4561"; +my $userid1 = "I83MFItzRpGPxD3vW0"; +my $userid2 = "Gh5t43980hfSAOcvne"; +my $userid3 = "adsfada80hfSAOcvne"; +my $email1 = $userid1 . '@koha-community.org'; +my $email2 = $userid2 . '@koha-community.org'; +my $email3 = $userid3 . '@koha-community.org'; +my $uuid1 = "ABCD1234"; +my $uuid2 = "WXYZ0987"; +my $uuid3 = "LMNO4561"; -my $patron_category = $builder->build({ source => 'Category' }); -my $branch = $builder->build({ - source => 'Branch', - value => { - branchemail => undef, - branchreplyto => undef, - branchreturnpath => $email1, - }, -}); +my $patron_category = $builder->build( { source => 'Category' } ); +my $branch = $builder->build( + { + source => 'Branch', + value => { + branchemail => undef, + branchreplyto => undef, + branchreturnpath => $email1, + }, + } +); $schema->resultset('BorrowerPasswordRecovery')->delete_all(); $schema->resultset('Borrower')->create( { - borrowernumber => $borrowernumber1, - surname => '', - address => '', - city => '', - userid => $userid1, - email => $email1, - categorycode => $patron_category->{categorycode}, - branchcode => $branch->{branchcode}, + borrowernumber => $borrowernumber1, + surname => '', + address => '', + city => '', + userid => $userid1, + email => $email1, + categorycode => $patron_category->{categorycode}, + branchcode => $branch->{branchcode}, } ); $schema->resultset('Borrower')->create( { - borrowernumber => $borrowernumber2, - surname => '', - address => '', - city => '', - userid => $userid2, - email => $email2, - categorycode => $patron_category->{categorycode}, - branchcode => $branch->{branchcode}, + borrowernumber => $borrowernumber2, + surname => '', + address => '', + city => '', + userid => $userid2, + email => $email2, + categorycode => $patron_category->{categorycode}, + branchcode => $branch->{branchcode}, } ); $schema->resultset('Borrower')->create( @@ -137,35 +139,49 @@ $schema->resultset('BorrowerPasswordRecovery')->create( } ); - -can_ok( "Koha::Patron::Password::Recovery", qw(ValidateBorrowernumber GetValidLinkInfo SendPasswordRecoveryEmail CompletePasswordRecovery) ); +can_ok( + "Koha::Patron::Password::Recovery", + qw(ValidateBorrowernumber GetValidLinkInfo SendPasswordRecoveryEmail CompletePasswordRecovery) +); ############################################################ # Koha::Patron::Password::Recovery::ValidateBorrowernumber # ############################################################ -ok( Koha::Patron::Password::Recovery::ValidateBorrowernumber($borrowernumber1), "[ValidateBorrowernumber] Borrower has a password recovery entry" ); -ok( ! Koha::Patron::Password::Recovery::ValidateBorrowernumber($borrowernumber2), "[ValidateBorrowernumber] Borrower's number is not found; password recovery entry is expired" ); -ok( ! Koha::Patron::Password::Recovery::ValidateBorrowernumber(9999), "[ValidateBorrowernumber] Borrower has no password recovery entry" ); +ok( + Koha::Patron::Password::Recovery::ValidateBorrowernumber($borrowernumber1), + "[ValidateBorrowernumber] Borrower has a password recovery entry" +); +ok( + !Koha::Patron::Password::Recovery::ValidateBorrowernumber($borrowernumber2), + "[ValidateBorrowernumber] Borrower's number is not found; password recovery entry is expired" +); +ok( + !Koha::Patron::Password::Recovery::ValidateBorrowernumber(9999), + "[ValidateBorrowernumber] Borrower has no password recovery entry" +); ###################################################### # Koha::Patron::Password::Recovery::GetValidLinkInfo # ###################################################### -my ($bnum1, $uname1) = Koha::Patron::Password::Recovery::GetValidLinkInfo($uuid1); -my ($bnum2, $uname2) = Koha::Patron::Password::Recovery::GetValidLinkInfo($uuid2); -my ($bnum3, $uname3) = Koha::Patron::Password::Recovery::GetValidLinkInfo("THISISANINVALIDUUID"); +my ( $bnum1, $uname1 ) = Koha::Patron::Password::Recovery::GetValidLinkInfo($uuid1); +my ( $bnum2, $uname2 ) = Koha::Patron::Password::Recovery::GetValidLinkInfo($uuid2); +my ( $bnum3, $uname3 ) = Koha::Patron::Password::Recovery::GetValidLinkInfo("THISISANINVALIDUUID"); -is( $bnum1, $borrowernumber1, "[GetValidLinkInfo] Borrower has a valid link" ); -is( $uname1, $userid1, "[GetValidLinkInfo] Borrower's username is fetched when a valid link is found" ); -ok( ! defined($bnum2), "[GetValidLinkInfo] Borrower's link is no longer valid; entry is expired" ); -ok( ! defined($bnum3), "[GetValidLinkInfo] Invalid UUID returns no borrowernumber" ); +is( $bnum1, $borrowernumber1, "[GetValidLinkInfo] Borrower has a valid link" ); +is( $uname1, $userid1, "[GetValidLinkInfo] Borrower's username is fetched when a valid link is found" ); +ok( !defined($bnum2), "[GetValidLinkInfo] Borrower's link is no longer valid; entry is expired" ); +ok( !defined($bnum3), "[GetValidLinkInfo] Invalid UUID returns no borrowernumber" ); ############################################################## # Koha::Patron::Password::Recovery::CompletePasswordRecovery # ############################################################## -is( Koha::Patron::Password::Recovery::CompletePasswordRecovery($uuid1), 3, "[CompletePasswordRecovery] Completing a password recovery deletes the used entry" ); +is( + Koha::Patron::Password::Recovery::CompletePasswordRecovery($uuid1), 3, + "[CompletePasswordRecovery] Completing a password recovery deletes the used entry" +); $schema->resultset('BorrowerPasswordRecovery')->create( { @@ -175,8 +191,14 @@ $schema->resultset('BorrowerPasswordRecovery')->create( } ); -ok( Koha::Patron::Password::Recovery::CompletePasswordRecovery($uuid2) == 1, "[CompletePasswordRecovery] An expired or invalid UUID purges expired entries" ); -ok( Koha::Patron::Password::Recovery::CompletePasswordRecovery($uuid2) == 0, "[CompletePasswordRecovery] Returns 0 on a clean table" ); +ok( + Koha::Patron::Password::Recovery::CompletePasswordRecovery($uuid2) == 1, + "[CompletePasswordRecovery] An expired or invalid UUID purges expired entries" +); +ok( + Koha::Patron::Password::Recovery::CompletePasswordRecovery($uuid2) == 0, + "[CompletePasswordRecovery] Returns 0 on a clean table" +); ################################################################### # Koha::Patron::Password::Recovery::DeleteExpiredPasswordRecovery # @@ -190,8 +212,14 @@ $schema->resultset('BorrowerPasswordRecovery')->create( } ); -ok( Koha::Patron::Password::Recovery::DeleteExpiredPasswordRecovery($borrowernumber3) == 1, "[DeleteExpiredPasswordRecovery] we can delete the unused entry" ); -ok( Koha::Patron::Password::Recovery::DeleteExpiredPasswordRecovery($borrowernumber3) == 0, "[DeleteExpiredPasswordRecovery] Returns 0 on a clean table" ); +ok( + Koha::Patron::Password::Recovery::DeleteExpiredPasswordRecovery($borrowernumber3) == 1, + "[DeleteExpiredPasswordRecovery] we can delete the unused entry" +); +ok( + Koha::Patron::Password::Recovery::DeleteExpiredPasswordRecovery($borrowernumber3) == 0, + "[DeleteExpiredPasswordRecovery] Returns 0 on a clean table" +); ############################################################### # Koha::Patron::Password::Recovery::SendPasswordRecoveryEmail # @@ -200,20 +228,22 @@ ok( Koha::Patron::Password::Recovery::DeleteExpiredPasswordRecovery($borrowernum my $borrower = Koha::Patrons->search( { userid => $userid1 } )->next; my $success; warning_is { - $success = Koha::Patron::Password::Recovery::SendPasswordRecoveryEmail($borrower, $email1 ); } - "Fake sendmail", + $success = Koha::Patron::Password::Recovery::SendPasswordRecoveryEmail( $borrower, $email1 ); +} +"Fake sendmail", '[SendPasswordRecoveryEmail] expecting fake sendmail'; -ok( $success == 1, '[SendPasswordRecoveryEmail] Returns 1 on success'); +ok( $success == 1, '[SendPasswordRecoveryEmail] Returns 1 on success' ); my $letters = C4::Letters::GetQueuedMessages( { borrowernumber => $borrowernumber1, limit => 99 } ); -ok( scalar @$letters == 1, "[SendPasswordRecoveryEmail] There is a letter in the queue for our borrower"); +ok( scalar @$letters == 1, "[SendPasswordRecoveryEmail] There is a letter in the queue for our borrower" ); -my $bpr = $schema->resultset('BorrowerPasswordRecovery')->search( { borrowernumber => $borrowernumber1 } ); +my $bpr = $schema->resultset('BorrowerPasswordRecovery')->search( { borrowernumber => $borrowernumber1 } ); my $tempuuid1 = $bpr->next->uuid; warning_is { - Koha::Patron::Password::Recovery::SendPasswordRecoveryEmail($borrower, $email1 ); } - "Fake sendmail", + Koha::Patron::Password::Recovery::SendPasswordRecoveryEmail( $borrower, $email1 ); +} +"Fake sendmail", '[SendPasswordRecoveryEmail] expecting fake sendmail'; $bpr = $schema->resultset('BorrowerPasswordRecovery')->search( { borrowernumber => $borrowernumber1 } ); @@ -221,12 +251,17 @@ my $tempuuid2 = $bpr->next->uuid; $letters = C4::Letters::GetQueuedMessages( { borrowernumber => $borrowernumber1, limit => 99 } ); -ok( $tempuuid1 ne $tempuuid2, "[SendPasswordRecoveryEmail] UPDATE == ON changes uuid in the database and updates the expirydate"); -ok( scalar @$letters == 2, "[SendPasswordRecoveryEmail] UPDATE == ON sends a new letter with updated uuid"); +ok( + $tempuuid1 ne $tempuuid2, + "[SendPasswordRecoveryEmail] UPDATE == ON changes uuid in the database and updates the expirydate" +); +ok( scalar @$letters == 2, "[SendPasswordRecoveryEmail] UPDATE == ON sends a new letter with updated uuid" ); foreach my $letter (@$letters) { - ok( $letter->{status} eq 'sent', - 'Test SendPasswordRecoverEmail sent due to TestBuilder Sender being a valid email address as expected.' ); + ok( + $letter->{status} eq 'sent', + 'Test SendPasswordRecoverEmail sent due to TestBuilder Sender being a valid email address as expected.' + ); } $schema->storage->txn_rollback(); diff --git a/t/db_dependent/Patron/Borrower_Debarments.t b/t/db_dependent/Patron/Borrower_Debarments.t index ae47365a9b..9ecea5bf4d 100755 --- a/t/db_dependent/Patron/Borrower_Debarments.t +++ b/t/db_dependent/Patron/Borrower_Debarments.t @@ -20,16 +20,18 @@ use_ok('Koha::Patron::Debarments'); my $schema = Koha::Database->schema; $schema->storage->txn_begin; my $builder = t::lib::TestBuilder->new; -my $dbh = C4::Context->dbh; +my $dbh = C4::Context->dbh; -my $library = $builder->build({ - source => 'Branch', -}); - -my $patron_category = $builder->build({ source => 'Category' }); -my $patron = $builder->build_object( +my $library = $builder->build( { - class => 'Koha::Patrons', + source => 'Branch', + } +); + +my $patron_category = $builder->build( { source => 'Category' } ); +my $patron = $builder->build_object( + { + class => 'Koha::Patrons', value => { firstname => 'my firstname', surname => 'my surname', @@ -40,56 +42,60 @@ my $patron = $builder->build_object( ); my $borrowernumber = $patron->borrowernumber; -my $success = Koha::Patron::Debarments::AddDebarment({ - borrowernumber => $borrowernumber, - expiration => '9999-06-10', - type => 'MANUAL', - comment => 'Test 1', -}); +my $success = Koha::Patron::Debarments::AddDebarment( + { + borrowernumber => $borrowernumber, + expiration => '9999-06-10', + type => 'MANUAL', + comment => 'Test 1', + } +); is( $success, 1, "AddDebarment returned true" ); - -my $restrictions = $patron->restrictions; +my $restrictions = $patron->restrictions; my $THE_restriction = $restrictions->next; -is( $restrictions->count, 1, '$patron->restrictions returns 1 restriction' ); -is( $THE_restriction->type->code, 'MANUAL', "Correctly stored 'type'" ); +is( $restrictions->count, 1, '$patron->restrictions returns 1 restriction' ); +is( $THE_restriction->type->code, 'MANUAL', "Correctly stored 'type'" ); is( $THE_restriction->expiration, '9999-06-10', "Correctly stored 'expiration'" ); -is( $THE_restriction->comment, 'Test 1', "Correctly stored 'comment'" ); +is( $THE_restriction->comment, 'Test 1', "Correctly stored 'comment'" ); +$success = Koha::Patron::Debarments::AddDebarment( + { + borrowernumber => $borrowernumber, + comment => 'Test 2', + } +); -$success = Koha::Patron::Debarments::AddDebarment({ - borrowernumber => $borrowernumber, - comment => 'Test 2', -}); - -$restrictions = $patron->restrictions; +$restrictions = $patron->restrictions; $THE_restriction = $restrictions->last; -is( $restrictions->count, 2, '$patron->restrictions returns 2 restrictions' ); +is( $restrictions->count, 2, '$patron->restrictions returns 2 restrictions' ); is( $THE_restriction->type->code, 'MANUAL', "Correctly stored 'type'" ); -is( $THE_restriction->expiration, undef, "Correctly stored debarrment with no expiration" ); -is( $THE_restriction->comment, 'Test 2', "Correctly stored 'comment'" ); +is( $THE_restriction->expiration, undef, "Correctly stored debarrment with no expiration" ); +is( $THE_restriction->comment, 'Test 2', "Correctly stored 'comment'" ); +Koha::Patron::Debarments::ModDebarment( + { + borrower_debarment_id => $THE_restriction->borrower_debarment_id, + comment => 'Test 3', + expiration => '9998-06-10', + } +); -Koha::Patron::Debarments::ModDebarment({ - borrower_debarment_id => $THE_restriction->borrower_debarment_id, - comment => 'Test 3', - expiration => '9998-06-10', -}); - -$restrictions = $patron->restrictions; +$restrictions = $patron->restrictions; $THE_restriction = $restrictions->last; -is( $restrictions->count, 2, '$patron->restrictions returns 2 restrictions' ); +is( $restrictions->count, 2, '$patron->restrictions returns 2 restrictions' ); is( $THE_restriction->comment, 'Test 3', "ModDebarment functions correctly" ); $patron = $patron->get_from_storage; -is( $patron->debarred, '9999-06-10', "Field borrowers.debarred set correctly" ); +is( $patron->debarred, '9999-06-10', "Field borrowers.debarred set correctly" ); is( $patron->debarredcomment, "Test 1\nTest 3", "Field borrowers.debarredcomment set correctly" ); - -Koha::Patron::Debarments::AddUniqueDebarment({ - borrowernumber => $borrowernumber, - type => 'OVERDUES' -}); +Koha::Patron::Debarments::AddUniqueDebarment( + { + borrowernumber => $borrowernumber, + type => 'OVERDUES' + } +); $restrictions = $patron->restrictions->search( { @@ -97,14 +103,19 @@ $restrictions = $patron->restrictions->search( } ); $THE_restriction = $restrictions->next; -is( $restrictions->count, 1, '$patron->restrictions->search({ type => "OVERDUES" }) returns 1 OVERDUES restriction after running AddUniqueDebarment once' ); +is( + $restrictions->count, 1, + '$patron->restrictions->search({ type => "OVERDUES" }) returns 1 OVERDUES restriction after running AddUniqueDebarment once' +); is( $THE_restriction->type->code, 'OVERDUES', "AddOverduesDebarment created new debarment correctly" ); -Koha::Patron::Debarments::AddUniqueDebarment({ - borrowernumber => $borrowernumber, - expiration => '9999-11-09', - type => 'OVERDUES' -}); +Koha::Patron::Debarments::AddUniqueDebarment( + { + borrowernumber => $borrowernumber, + expiration => '9999-11-09', + type => 'OVERDUES' + } +); $restrictions = $patron->restrictions->search( { @@ -112,12 +123,13 @@ $restrictions = $patron->restrictions->search( } ); $THE_restriction = $restrictions->next; -is( $restrictions->count, 1, '$patron->restrictions->search({ type => "OVERDUES" }) returns 1 OVERDUES restriction after running AddUniqueDebarent twice' ); +is( + $restrictions->count, 1, + '$patron->restrictions->search({ type => "OVERDUES" }) returns 1 OVERDUES restriction after running AddUniqueDebarent twice' +); is( $THE_restriction->expiration, '9999-11-09', "AddUniqueDebarment updated the OVERDUES restriction correctly" ); - -my $delUniqueDebarment = Koha::Patron::Debarments::DelUniqueDebarment({ -}); +my $delUniqueDebarment = Koha::Patron::Debarments::DelUniqueDebarment( {} ); is( $delUniqueDebarment, undef, "DelUniqueDebarment without the arguments 'borrowernumber' and 'type' returns undef" ); $restrictions = $patron->restrictions->search( @@ -125,11 +137,16 @@ $restrictions = $patron->restrictions->search( type => 'OVERDUES', } ); -is( $restrictions->count, 1, "DelUniqueDebarment without the arguments 'borrowernumber' and 'type' does not delete the debarment" ); +is( + $restrictions->count, 1, + "DelUniqueDebarment without the arguments 'borrowernumber' and 'type' does not delete the debarment" +); -$delUniqueDebarment = Koha::Patron::Debarments::DelUniqueDebarment({ - borrowernumber => $borrowernumber, -}); +$delUniqueDebarment = Koha::Patron::Debarments::DelUniqueDebarment( + { + borrowernumber => $borrowernumber, + } +); is( $delUniqueDebarment, undef, "DelUniqueDebarment without the argument 'type' returns undef" ); $restrictions = $patron->restrictions->search( @@ -139,9 +156,7 @@ $restrictions = $patron->restrictions->search( ); is( $restrictions->count, 1, "DelUniqueDebarment without the argument 'type' does not delete the debarment" ); -$delUniqueDebarment = Koha::Patron::Debarments::DelUniqueDebarment({ - type => 'OVERDUES' -}); +$delUniqueDebarment = Koha::Patron::Debarments::DelUniqueDebarment( { type => 'OVERDUES' } ); is( $delUniqueDebarment, undef, "DelUniqueDebarment without the argument 'borrowernumber' returns undef" ); $restrictions = $patron->restrictions->search( @@ -151,10 +166,12 @@ $restrictions = $patron->restrictions->search( ); is( $restrictions->count, 1, "DelUniqueDebarment without the argument 'borrowerumber' does not delete the debarment" ); -$delUniqueDebarment = Koha::Patron::Debarments::DelUniqueDebarment({ - borrowernumber => $borrowernumber, - type => 'SUSPENSION', -}); +$delUniqueDebarment = Koha::Patron::Debarments::DelUniqueDebarment( + { + borrowernumber => $borrowernumber, + type => 'SUSPENSION', + } +); is( $delUniqueDebarment, undef, "DelUniqueDebarment with wrong arguments returns undef" ); $restrictions = $patron->restrictions->search( @@ -164,10 +181,12 @@ $restrictions = $patron->restrictions->search( ); is( $restrictions->count, 1, "DelUniqueDebarment with wrong arguments does not delete the debarment" ); -$delUniqueDebarment = Koha::Patron::Debarments::DelUniqueDebarment({ - borrowernumber => $borrowernumber, - type => 'OVERDUES', -}); +$delUniqueDebarment = Koha::Patron::Debarments::DelUniqueDebarment( + { + borrowernumber => $borrowernumber, + type => 'OVERDUES', + } +); is( $delUniqueDebarment, 1, "DelUniqueDebarment returns 1" ); $restrictions = $patron->restrictions->search( @@ -186,13 +205,19 @@ $restrictions = $patron->restrictions; is( $restrictions->count, 0, "DelDebarment functions correctly" ); $dbh->do(q|UPDATE borrowers SET debarred = '1970-01-01'|); -is( Koha::Patrons->find( $borrowernumber )->is_debarred, undef, 'A patron with a debarred date in the past is not debarred' ); +is( + Koha::Patrons->find($borrowernumber)->is_debarred, undef, + 'A patron with a debarred date in the past is not debarred' +); $dbh->do(q|UPDATE borrowers SET debarred = NULL|); -is( Koha::Patrons->find( $borrowernumber )->is_debarred, undef, 'A patron without a debarred date is not debarred' ); +is( Koha::Patrons->find($borrowernumber)->is_debarred, undef, 'A patron without a debarred date is not debarred' ); -$dbh->do(q|UPDATE borrowers SET debarred = '9999-12-31'|); # Note: Change this test before the first of January 10000! -is( Koha::Patrons->find( $borrowernumber )->is_debarred, '9999-12-31', 'A patron with a debarred date in the future is debarred' ); +$dbh->do(q|UPDATE borrowers SET debarred = '9999-12-31'|); # Note: Change this test before the first of January 10000! +is( + Koha::Patrons->find($borrowernumber)->is_debarred, '9999-12-31', + 'A patron with a debarred date in the future is debarred' +); # Test patrons merge my $borrowernumber2 = Koha::Patron->new( @@ -203,7 +228,7 @@ my $borrowernumber2 = Koha::Patron->new( branchcode => $library->{branchcode}, } )->store->borrowernumber; -my $debarreddate2 = '9999-06-10'; # Be sure to be in the future +my $debarreddate2 = '9999-06-10'; # Be sure to be in the future my $debarredcomment2 = 'Test merge'; Koha::Patron::Debarments::AddDebarment( { @@ -222,10 +247,14 @@ my $borrowernumber3 = Koha::Patron->new( } )->store->borrowernumber; Koha::Patrons->find($borrowernumber3)->merge_with( [$borrowernumber2] ); -is( Koha::Patrons->find($borrowernumber3)->debarred, - $debarreddate2, 'Koha::Patron->merge_with() transfers well debarred' ); -is( Koha::Patrons->find($borrowernumber3)->debarredcomment, - $debarredcomment2, 'Koha::Patron->merge_with() transfers well debarredcomment' ); +is( + Koha::Patrons->find($borrowernumber3)->debarred, + $debarreddate2, 'Koha::Patron->merge_with() transfers well debarred' +); +is( + Koha::Patrons->find($borrowernumber3)->debarredcomment, + $debarredcomment2, 'Koha::Patron->merge_with() transfers well debarredcomment' +); # Test removing debartments after payment $builder->build( diff --git a/t/db_dependent/Patron/Borrower_Discharge.t b/t/db_dependent/Patron/Borrower_Discharge.t index 4b04530b9f..9274096d96 100755 --- a/t/db_dependent/Patron/Borrower_Discharge.t +++ b/t/db_dependent/Patron/Borrower_Discharge.t @@ -25,7 +25,7 @@ use IPC::Cmd qw(can_run); use MARC::Record; use C4::Circulation qw( AddIssue AddReturn ); -use C4::Biblio qw( AddBiblio ); +use C4::Biblio qw( AddBiblio ); use C4::Context; use Koha::Patrons; @@ -35,7 +35,7 @@ use Koha::Database; use t::lib::TestBuilder; use t::lib::Mocks; -my $schema = Koha::Database->new->schema; +my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; my $builder = t::lib::TestBuilder->new; @@ -43,35 +43,41 @@ my $builder = t::lib::TestBuilder->new; my $dbh = C4::Context->dbh; $dbh->do(q|DELETE FROM discharges|); -my $library = $builder->build({ source => 'Branch' }); -my $another_library = $builder->build({ source => 'Branch' }); -my $itemtype = $builder->build({ source => 'Itemtype' })->{itemtype}; +my $library = $builder->build( { source => 'Branch' } ); +my $another_library = $builder->build( { source => 'Branch' } ); +my $itemtype = $builder->build( { source => 'Itemtype' } )->{itemtype}; -my $patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { - branchcode => $library->{branchcode}, - flags => 1, # superlibrarian +my $patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { + branchcode => $library->{branchcode}, + flags => 1, # superlibrarian + } } -}); -t::lib::Mocks::mock_userenv({ patron => $patron }); +); +t::lib::Mocks::mock_userenv( { patron => $patron } ); -my $patron2 = $builder->build_object({ - class => 'Koha::Patrons', - value => { - branchcode => $library->{branchcode}, +my $patron2 = $builder->build_object( + { + class => 'Koha::Patrons', + value => { + branchcode => $library->{branchcode}, + } } -}); -my $patron3 = $builder->build_object({ - class => 'Koha::Patrons', - value => { - branchcode => $another_library->{branchcode}, - flags => undef, +); +my $patron3 = $builder->build_object( + { + class => 'Koha::Patrons', + value => { + branchcode => $another_library->{branchcode}, + flags => undef, + } } -}); +); # Discharge not possible with issues -my ( $biblionumber ) = AddBiblio( MARC::Record->new, ''); +my ($biblionumber) = AddBiblio( MARC::Record->new, '' ); my $barcode = 'BARCODE42'; $builder->build_sample_item( { @@ -83,38 +89,65 @@ $builder->build_sample_item( ); AddIssue( $patron, $barcode ); -is( Koha::Patron::Discharge::can_be_discharged({ borrowernumber => $patron->borrowernumber }), 0, 'A patron with issues cannot be discharged' ); +is( + Koha::Patron::Discharge::can_be_discharged( { borrowernumber => $patron->borrowernumber } ), 0, + 'A patron with issues cannot be discharged' +); -is( Koha::Patron::Discharge::request({ borrowernumber => $patron->borrowernumber }), undef, 'No request done if patron has issues' ); -is( Koha::Patron::Discharge::discharge({ borrowernumber => $patron->borrowernumber }), undef, 'No discharge done if patron has issues' ); -is_deeply( [ Koha::Patron::Discharge::get_pendings ], [], 'There is no pending discharge request' ); -is_deeply( [ Koha::Patron::Discharge::get_validated ], [], 'There is no validated discharge' ); +is( + Koha::Patron::Discharge::request( { borrowernumber => $patron->borrowernumber } ), undef, + 'No request done if patron has issues' +); +is( + Koha::Patron::Discharge::discharge( { borrowernumber => $patron->borrowernumber } ), undef, + 'No discharge done if patron has issues' +); +is_deeply( [Koha::Patron::Discharge::get_pendings], [], 'There is no pending discharge request' ); +is_deeply( [Koha::Patron::Discharge::get_validated], [], 'There is no validated discharge' ); -AddReturn( $barcode ); +AddReturn($barcode); # Discharge possible without issue -is( Koha::Patron::Discharge::can_be_discharged({ borrowernumber => $patron->borrowernumber }), 1, 'A patron without issues can be discharged' ); +is( + Koha::Patron::Discharge::can_be_discharged( { borrowernumber => $patron->borrowernumber } ), 1, + 'A patron without issues can be discharged' +); -is(Koha::Patron::Discharge::generate_as_pdf,undef,"Confirm failure when lacking borrower number"); +is( Koha::Patron::Discharge::generate_as_pdf, undef, "Confirm failure when lacking borrower number" ); # Verify that the user is not discharged anymore if the restriction has been lifted Koha::Patron::Discharge::discharge( { borrowernumber => $patron->borrowernumber } ); Koha::Patron::Discharge::discharge( { borrowernumber => $patron2->borrowernumber } ); Koha::Patron::Discharge::discharge( { borrowernumber => $patron3->borrowernumber } ); -is( Koha::Patron::Discharge::is_discharged( { borrowernumber => $patron->borrowernumber } ), 1, 'The patron has been discharged' ); -is( Koha::Patrons->find( $patron->borrowernumber )->is_debarred, '9999-12-31', 'The patron has been debarred after discharge' ); -is( scalar( Koha::Patron::Discharge::get_validated ), 3, 'There are 3 validated discharges' ); -is( scalar( Koha::Patron::Discharge::get_validated( { borrowernumber => $patron->borrowernumber } ) ), 1, 'There is 1 validated discharge for a given patron' ); -is( scalar( Koha::Patron::Discharge::get_validated( { branchcode => $library->{branchcode} } ) ), 2, 'There is 2 validated discharges for a given branchcode' ); # This is not used in the code yet +is( + Koha::Patron::Discharge::is_discharged( { borrowernumber => $patron->borrowernumber } ), 1, + 'The patron has been discharged' +); +is( + Koha::Patrons->find( $patron->borrowernumber )->is_debarred, '9999-12-31', + 'The patron has been debarred after discharge' +); +is( scalar(Koha::Patron::Discharge::get_validated), 3, 'There are 3 validated discharges' ); +is( + scalar( Koha::Patron::Discharge::get_validated( { borrowernumber => $patron->borrowernumber } ) ), 1, + 'There is 1 validated discharge for a given patron' +); +is( + scalar( Koha::Patron::Discharge::get_validated( { branchcode => $library->{branchcode} } ) ), 2, + 'There is 2 validated discharges for a given branchcode' +); # This is not used in the code yet Koha::Patron::Debarments::DelUniqueDebarment( { 'borrowernumber' => $patron->borrowernumber, 'type' => 'DISCHARGE' } ); ok( !Koha::Patrons->find( $patron->borrowernumber )->is_debarred, 'The debarment has been lifted' ); -ok( !Koha::Patron::Discharge::is_discharged( { borrowernumber => $patron->borrowernumber } ), 'The patron is not discharged after the restriction has been lifted' ); +ok( + !Koha::Patron::Discharge::is_discharged( { borrowernumber => $patron->borrowernumber } ), + 'The patron is not discharged after the restriction has been lifted' +); # Verify that the discharge works multiple times -Koha::Patron::Discharge::request({ borrowernumber => $patron->borrowernumber }); -is(scalar( Koha::Patron::Discharge::get_pendings ), 1, 'There is a pending discharge request (second time)'); +Koha::Patron::Discharge::request( { borrowernumber => $patron->borrowernumber } ); +is( scalar(Koha::Patron::Discharge::get_pendings), 1, 'There is a pending discharge request (second time)' ); Koha::Patron::Discharge::discharge( { borrowernumber => $patron->borrowernumber } ); -is_deeply( [ Koha::Patron::Discharge::get_pendings ], [], 'There is no pending discharge request (second time)'); +is_deeply( [Koha::Patron::Discharge::get_pendings], [], 'There is no pending discharge request (second time)' ); SKIP: { skip "Skipping because weasyprint is not installed", @@ -131,46 +164,54 @@ SKIP: { $mocked_ipc->mock( 'run', sub { return 0, 'Some error' } ); my $result; - warning_is - { $result = Koha::Patron::Discharge::generate_as_pdf( { borrowernumber => $patron->borrowernumber } ); } - 'Some error', + warning_is { $result = Koha::Patron::Discharge::generate_as_pdf( { borrowernumber => $patron->borrowernumber } ); } + 'Some error', 'Failed call to run() prints the generated error'; is( $result, undef, 'undef returned if failed run' ); $mocked_ipc->mock( 'can_run', undef ); - warning_is - { $result = Koha::Patron::Discharge::generate_as_pdf( { borrowernumber => $patron->borrowernumber } ); } - 'weasyprint not found!', + warning_is { $result = Koha::Patron::Discharge::generate_as_pdf( { borrowernumber => $patron->borrowernumber } ); } + 'weasyprint not found!', 'Expected failure because of missing weasyprint'; is( $result, undef, 'undef returned if missing weasyprint' ); } # FIXME Should be a Koha::Object object -is( ref(Koha::Patron::Discharge::request({ borrowernumber => $patron->borrowernumber })), 'Koha::Schema::Result::Discharge', 'Discharge request sent' ); +is( + ref( Koha::Patron::Discharge::request( { borrowernumber => $patron->borrowernumber } ) ), + 'Koha::Schema::Result::Discharge', 'Discharge request sent' +); subtest 'search_limited' => sub { plan tests => 4; $dbh->do(q|DELETE FROM discharges|); my $group_1 = Koha::Library::Group->new( { title => 'TEST Group 1', ft_hide_patron_info => 1 } )->store; my $group_2 = Koha::Library::Group->new( { title => 'TEST Group 2', ft_hide_patron_info => 1 } )->store; + # $patron and $patron2 are from the same library, $patron3 from another one # Logged in user is $patron, superlibrarian - t::lib::Mocks::mock_userenv({ patron => $patron }); - Koha::Library::Group->new({ parent_id => $group_1->id, branchcode => $patron->branchcode })->store(); - Koha::Library::Group->new({ parent_id => $group_2->id, branchcode => $patron3->branchcode })->store(); - Koha::Patron::Discharge::request({ borrowernumber => $patron->borrowernumber }); - Koha::Patron::Discharge::request({ borrowernumber => $patron2->borrowernumber }); - Koha::Patron::Discharge::request({ borrowernumber => $patron3->borrowernumber }); - is( scalar( Koha::Patron::Discharge::get_pendings), 3, 'With permission, all discharges are visible' ); - is( Koha::Patron::Discharge::count({pending => 1}), 3, 'With permission, all discharges are visible' ); + t::lib::Mocks::mock_userenv( { patron => $patron } ); + Koha::Library::Group->new( { parent_id => $group_1->id, branchcode => $patron->branchcode } )->store(); + Koha::Library::Group->new( { parent_id => $group_2->id, branchcode => $patron3->branchcode } )->store(); + Koha::Patron::Discharge::request( { borrowernumber => $patron->borrowernumber } ); + Koha::Patron::Discharge::request( { borrowernumber => $patron2->borrowernumber } ); + Koha::Patron::Discharge::request( { borrowernumber => $patron3->borrowernumber } ); + is( scalar(Koha::Patron::Discharge::get_pendings), 3, 'With permission, all discharges are visible' ); + is( Koha::Patron::Discharge::count( { pending => 1 } ), 3, 'With permission, all discharges are visible' ); # With patron 3 logged in, only discharges from their group are visible - t::lib::Mocks::mock_userenv({ patron => $patron3 }); - is( scalar( Koha::Patron::Discharge::get_pendings), 1, 'Without permission, only discharge from our group are visible' ); - is( Koha::Patron::Discharge::count({pending => 1}), 1, 'Without permission, only discharge from our group are visible' ); + t::lib::Mocks::mock_userenv( { patron => $patron3 } ); + is( + scalar(Koha::Patron::Discharge::get_pendings), 1, + 'Without permission, only discharge from our group are visible' + ); + is( + Koha::Patron::Discharge::count( { pending => 1 } ), 1, + 'Without permission, only discharge from our group are visible' + ); }; $schema->storage->txn_rollback; diff --git a/t/db_dependent/Patron/Borrower_Files.t b/t/db_dependent/Patron/Borrower_Files.t index b0cfc74552..f22eb7706d 100755 --- a/t/db_dependent/Patron/Borrower_Files.t +++ b/t/db_dependent/Patron/Borrower_Files.t @@ -32,29 +32,32 @@ use_ok('Koha::Patron::Files'); my $schema = Koha::Database->schema; $schema->storage->txn_begin; my $builder = t::lib::TestBuilder->new; -my $dbh = C4::Context->dbh; +my $dbh = C4::Context->dbh; $dbh->do(q|DELETE FROM issues|); $dbh->do(q|DELETE FROM borrowers|); $dbh->do(q|DELETE FROM borrower_files|); -my $library = $builder->build({ - source => 'Branch', -}); +my $library = $builder->build( + { + source => 'Branch', + } +); -my $patron_category = $builder->build({ source => 'Category' }); -my $borrowernumber = Koha::Patron->new({ - firstname => 'my firstname', - surname => 'my surname', - categorycode => $patron_category->{categorycode}, - branchcode => $library->{branchcode}, -})->store->borrowernumber; +my $patron_category = $builder->build( { source => 'Category' } ); +my $borrowernumber = Koha::Patron->new( + { + firstname => 'my firstname', + surname => 'my surname', + categorycode => $patron_category->{categorycode}, + branchcode => $library->{branchcode}, + } +)->store->borrowernumber; my $bf = Koha::Patron::Files->new( borrowernumber => $borrowernumber, ); - my $addFile = $bf->AddFile( name => 'my filename', type => 'text/plain', @@ -64,39 +67,37 @@ my $files = $bf->GetFilesInfo(); is( @$files, 0, 'AddFile does not add a file without the parameter content' ); $addFile = $bf->AddFile( - type => 'text/plain', + type => 'text/plain', content => 'my filecontent', ); is( $addFile, undef, 'AddFile without the required parameter name returns undef' ); $files = $bf->GetFilesInfo(); is( @$files, 0, 'AddFile does not add a file without the parameter name' ); - my $file1 = { - name => 'my filename1', - type => 'text/plain', + name => 'my filename1', + type => 'text/plain', content => 'my filecontent1', }; $addFile = $bf->AddFile(%$file1); is( $addFile, 1, 'AddFile with the required parameters returns 1' ); $files = $bf->GetFilesInfo(); -is( @$files, 1, 'GetFilesInfo returns 1 file' ); +is( @$files, 1, 'GetFilesInfo returns 1 file' ); is( $files->[0]->{file_name}, $file1->{name}, 'Correctly stored name' ); is( $files->[0]->{file_type}, $file1->{type}, 'Correctly stored type' ); - my $file2 = { - name => 'my filename2', - type => 'text/html', + name => 'my filename2', + type => 'text/html', description => 'my filedescription2', - content => 'my filecontent2', + content => 'my filecontent2', }; $addFile = $bf->AddFile(%$file2); is( $addFile, 1, 'AddFile with the required parameters returns 1' ); $files = $bf->GetFilesInfo(); -is( @$files, 2, "GetFilesInfo returns 2 files" ); -is( $files->[1]->{file_name}, $file2->{name}, 'Correctly stored name' ); -is( $files->[1]->{file_type}, $file2->{type}, 'Correctly stored type' ); +is( @$files, 2, "GetFilesInfo returns 2 files" ); +is( $files->[1]->{file_name}, $file2->{name}, 'Correctly stored name' ); +is( $files->[1]->{file_type}, $file2->{type}, 'Correctly stored type' ); is( $files->[1]->{file_description}, $file2->{description}, 'Correctly stored description' ); my $file = $bf->GetFile(); @@ -105,11 +106,10 @@ is( $file, undef, 'GetFile without parameters returns undef' ); $file = $bf->GetFile( id => $files->[1]->{file_id}, ); -is( $file->{file_name}, $files->[1]->{file_name}, 'GetFile returns the correct name' ); -is( $file->{file_type}, $files->[1]->{file_type}, 'GetFile returns the correct type' ); +is( $file->{file_name}, $files->[1]->{file_name}, 'GetFile returns the correct name' ); +is( $file->{file_type}, $files->[1]->{file_type}, 'GetFile returns the correct type' ); is( $file->{file_description}, $files->[1]->{file_description}, 'GetFile returns the correct description' ); - $bf->DelFile(); $files = $bf->GetFilesInfo(); is( @$files, 2, 'DelFile without parameters does not delete a file' ); @@ -118,7 +118,7 @@ $bf->DelFile( id => $files->[1]->{file_id}, ); $files = $bf->GetFilesInfo(); -is( @$files, 1, 'DelFile delete a file' ); +is( @$files, 1, 'DelFile delete a file' ); is( $files->[0]->{file_name}, $file1->{name}, 'DelFile delete the correct entry' ); is( $files->[0]->{file_type}, $file1->{type}, 'DelFile delete the correct entry' ); diff --git a/t/db_dependent/Patron/Borrower_PrevCheckout.t b/t/db_dependent/Patron/Borrower_PrevCheckout.t index 310458d119..57fdde783b 100755 --- a/t/db_dependent/Patron/Borrower_PrevCheckout.t +++ b/t/db_dependent/Patron/Borrower_PrevCheckout.t @@ -17,36 +17,42 @@ use t::lib::Mocks; my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; -my $builder = t::lib::TestBuilder->new; -my $yesCatCode = $builder->build({ - source => 'Category', - value => { - categorycode => 'yesCat', - checkprevcheckout => 'yes', - }, -}); +my $builder = t::lib::TestBuilder->new; +my $yesCatCode = $builder->build( + { + source => 'Category', + value => { + categorycode => 'yesCat', + checkprevcheckout => 'yes', + }, + } +); -my $noCatCode = $builder->build({ - source => 'Category', - value => { - categorycode => 'noCat', - checkprevcheckout => 'no', - }, -}); +my $noCatCode = $builder->build( + { + source => 'Category', + value => { + categorycode => 'noCat', + checkprevcheckout => 'no', + }, + } +); -my $inheritCatCode = $builder->build({ - source => 'Category', - value => { - categorycode => 'inheritCat', - checkprevcheckout => 'inherit', - }, -}); +my $inheritCatCode = $builder->build( + { + source => 'Category', + value => { + categorycode => 'inheritCat', + checkprevcheckout => 'inherit', + }, + } +); # Create context for some tests late on in the file. -my $library = $builder->build({ source => 'Branch' }); -my $staff = $builder->build({source => 'Borrower'}); +my $library = $builder->build( { source => 'Branch' } ); +my $staff = $builder->build( { source => 'Borrower' } ); -t::lib::Mocks::mock_userenv({ branchcode => $library->{branchcode} }); +t::lib::Mocks::mock_userenv( { branchcode => $library->{branchcode} } ); # wants_check_for_previous_checkout @@ -70,25 +76,25 @@ my $mappings = [ { setting => 'yes', patrons => [ - {setting => 'yes', result => 1}, - {setting => 'no', result => 1}, - {setting => 'inherit', result => 1}, + { setting => 'yes', result => 1 }, + { setting => 'no', result => 1 }, + { setting => 'inherit', result => 1 }, ], }, { setting => 'no', patrons => [ - {setting => 'yes', result => 1}, - {setting => 'no', result => 1}, - {setting => 'inherit', result => 1}, + { setting => 'yes', result => 1 }, + { setting => 'no', result => 1 }, + { setting => 'inherit', result => 1 }, ], }, { setting => 'inherit', patrons => [ - {setting => 'yes', result => 1}, - {setting => 'no', result => 1}, - {setting => 'inherit', result => 1}, + { setting => 'yes', result => 1 }, + { setting => 'no', result => 1 }, + { setting => 'inherit', result => 1 }, ], }, ], @@ -99,25 +105,25 @@ my $mappings = [ { setting => 'yes', patrons => [ - {setting => 'yes', result => 1}, - {setting => 'no', result => 0}, - {setting => 'inherit', result => 1}, + { setting => 'yes', result => 1 }, + { setting => 'no', result => 0 }, + { setting => 'inherit', result => 1 }, ], }, { setting => 'no', patrons => [ - {setting => 'yes', result => 1}, - {setting => 'no', result => 0}, - {setting => 'inherit', result => 0}, + { setting => 'yes', result => 1 }, + { setting => 'no', result => 0 }, + { setting => 'inherit', result => 0 }, ], }, { setting => 'inherit', patrons => [ - {setting => 'yes', result => 1}, - {setting => 'no', result => 0}, - {setting => 'inherit', result => 1}, + { setting => 'yes', result => 1 }, + { setting => 'no', result => 0 }, + { setting => 'inherit', result => 1 }, ], }, ], @@ -128,25 +134,25 @@ my $mappings = [ { setting => 'yes', patrons => [ - {setting => 'yes', result => 1}, - {setting => 'no', result => 0}, - {setting => 'inherit', result => 1}, + { setting => 'yes', result => 1 }, + { setting => 'no', result => 0 }, + { setting => 'inherit', result => 1 }, ], }, { setting => 'no', patrons => [ - {setting => 'yes', result => 1}, - {setting => 'no', result => 0}, - {setting => 'inherit', result => 0}, + { setting => 'yes', result => 1 }, + { setting => 'no', result => 0 }, + { setting => 'inherit', result => 0 }, ], }, { setting => 'inherit', patrons => [ - {setting => 'yes', result => 1}, - {setting => 'no', result => 0}, - {setting => 'inherit', result => 0}, + { setting => 'yes', result => 1 }, + { setting => 'no', result => 0 }, + { setting => 'inherit', result => 0 }, ], }, ], @@ -157,25 +163,25 @@ my $mappings = [ { setting => 'yes', patrons => [ - {setting => 'yes', result => 0}, - {setting => 'no', result => 0}, - {setting => 'inherit', result => 0}, + { setting => 'yes', result => 0 }, + { setting => 'no', result => 0 }, + { setting => 'inherit', result => 0 }, ], }, { setting => 'no', patrons => [ - {setting => 'yes', result => 0}, - {setting => 'no', result => 0}, - {setting => 'inherit', result => 0}, + { setting => 'yes', result => 0 }, + { setting => 'no', result => 0 }, + { setting => 'inherit', result => 0 }, ], }, { setting => 'inherit', patrons => [ - {setting => 'yes', result => 0}, - {setting => 'no', result => 0}, - {setting => 'inherit', result => 0}, + { setting => 'yes', result => 0 }, + { setting => 'no', result => 0 }, + { setting => 'inherit', result => 0 }, ], }, ], @@ -184,25 +190,26 @@ my $mappings = [ map { my $syspref = $_->{syspref}; - t::lib::Mocks::mock_preference('checkprevcheckout', $syspref); + t::lib::Mocks::mock_preference( 'checkprevcheckout', $syspref ); map { my $code = $_->{setting} . 'Cat'; map { - my $kpatron = $builder->build({ - source => 'Borrower', - value => { - checkprevcheckout => $_->{setting}, - categorycode => $code, - }, - }); - my $patron = Koha::Patrons->find($kpatron->{borrowernumber}); + my $kpatron = $builder->build( + { + source => 'Borrower', + value => { + checkprevcheckout => $_->{setting}, + categorycode => $code, + }, + } + ); + my $patron = Koha::Patrons->find( $kpatron->{borrowernumber} ); is( $patron->wants_check_for_previous_checkout, $_->{result}, - "Predicate with syspref " . $syspref . ", cat " . $code - . ", patron " . $_->{setting} - ); - } @{$_->{patrons}}; - } @{$_->{categories}}; + "Predicate with syspref " . $syspref . ", cat " . $code . ", patron " . $_->{setting} + ); + } @{ $_->{patrons} }; + } @{ $_->{categories} }; } @{$mappings}; # do_check_for_previous_checkout @@ -233,121 +240,121 @@ map { # Requirements: # $patron, $different_patron, $items (same bib number), $different_item -my $patron = $builder->build({source => 'Borrower'}); -my $patron_d = $builder->build({source => 'Borrower'}); +my $patron = $builder->build( { source => 'Borrower' } ); +my $patron_d = $builder->build( { source => 'Borrower' } ); my $biblio = $builder->build_sample_biblio; $biblio->serial(0)->store; -my $item_1 = $builder->build_sample_item({biblionumber => $biblio->biblionumber})->unblessed; -my $item_2 = $builder->build_sample_item({biblionumber => $biblio->biblionumber})->unblessed; +my $item_1 = $builder->build_sample_item( { biblionumber => $biblio->biblionumber } )->unblessed; +my $item_2 = $builder->build_sample_item( { biblionumber => $biblio->biblionumber } )->unblessed; my $item_d = $builder->build_sample_item->unblessed; ## Testing Sub sub test_it { - my ($mapping, $stage) = @_; + my ( $mapping, $stage ) = @_; map { - my $patron = Koha::Patrons->find($_->{patron}->{borrowernumber}); + my $patron = Koha::Patrons->find( $_->{patron}->{borrowernumber} ); is( - $patron->do_check_for_previous_checkout($_->{item}), + $patron->do_check_for_previous_checkout( $_->{item} ), $_->{result}, $stage . ": " . $_->{msg} ); } @{$mapping}; -}; +} ## Initial Mappings my $cpvmappings = [ { - msg => "Item, patron [0]", - item => $item_1, + msg => "Item, patron [0]", + item => $item_1, patron => $patron, result => 0, }, { - msg => "Diff item, same bib, same patron [0]", - item => $item_2, + msg => "Diff item, same bib, same patron [0]", + item => $item_2, patron => $patron, result => 0, }, { - msg => "Diff item, diff bib, same patron [0]", - item => $item_d, + msg => "Diff item, diff bib, same patron [0]", + item => $item_d, patron => $patron, result => 0, }, { - msg => "Same item, diff patron [0]", - item => $item_1, + msg => "Same item, diff patron [0]", + item => $item_1, patron => $patron_d, result => 0, }, { - msg => "Diff item, same bib, diff patron [0]", - item => $item_2, + msg => "Diff item, same bib, diff patron [0]", + item => $item_2, patron => $patron_d, result => 0, }, { - msg => "Diff item, diff bib, diff patron [0]", - item => $item_d, + msg => "Diff item, diff bib, diff patron [0]", + item => $item_d, patron => $patron_d, result => 0, }, ]; -test_it($cpvmappings, "PreIssue"); +test_it( $cpvmappings, "PreIssue" ); # Issue item_1 to $patron: my $patron_get_mem = Koha::Patrons->find( $patron->{borrowernumber} ); BAIL_OUT("Issue failed") - unless AddIssue($patron_get_mem, $item_1->{barcode}); + unless AddIssue( $patron_get_mem, $item_1->{barcode} ); # Then test: my $cpvPmappings = [ { - msg => "Same item, same patron [1]", - item => $item_1, + msg => "Same item, same patron [1]", + item => $item_1, patron => $patron, result => 1, }, { - msg => "Diff item, same bib, same patron [1]", - item => $item_2, + msg => "Diff item, same bib, same patron [1]", + item => $item_2, patron => $patron, result => 1, }, { - msg => "Diff item, diff bib, same patron [0]", - item => $item_d, + msg => "Diff item, diff bib, same patron [0]", + item => $item_d, patron => $patron, result => 0, }, { - msg => "Same item, diff patron [0]", - item => $item_1, + msg => "Same item, diff patron [0]", + item => $item_1, patron => $patron_d, result => 0, }, { - msg => "Diff item, same bib, diff patron [0]", - item => $item_2, + msg => "Diff item, same bib, diff patron [0]", + item => $item_2, patron => $patron_d, result => 0, }, { - msg => "Diff item, diff bib, diff patron [0]", - item => $item_d, + msg => "Diff item, diff bib, diff patron [0]", + item => $item_d, patron => $patron_d, result => 0, }, ]; -test_it($cpvPmappings, "PostIssue"); +test_it( $cpvPmappings, "PostIssue" ); # Return item_1 from patron: -BAIL_OUT("Return Failed") unless AddReturn($item_1->{barcode}, $patron->{branchcode}); +BAIL_OUT("Return Failed") unless AddReturn( $item_1->{barcode}, $patron->{branchcode} ); # Then: -test_it($cpvPmappings, "PostReturn"); +test_it( $cpvPmappings, "PostReturn" ); # Finally test C4::Circulation::CanBookBeIssued @@ -373,16 +380,19 @@ test_it($cpvPmappings, "PostReturn"); # - $checkprevcheckout pref (first hardno, then hardyes) # Our Patron -my $patron_category = $builder->build({ source => 'Category', value => { category_type => 'P', enrolmentfee => 0 } }); -my $CBBI_patron = $builder->build({source => 'Borrower', value => { categorycode => $patron_category->{categorycode} }}); +my $patron_category = $builder->build( { source => 'Category', value => { category_type => 'P', enrolmentfee => 0 } } ); +my $CBBI_patron = + $builder->build( { source => 'Borrower', value => { categorycode => $patron_category->{categorycode} } } ); $patron = Koha::Patrons->find( $CBBI_patron->{borrowernumber} ); + # Our Items -my $new_item = $builder->build_sample_item->unblessed; +my $new_item = $builder->build_sample_item->unblessed; my $prev_item = $builder->build_sample_item->unblessed; + # Second is Checked Out BAIL_OUT("CanBookBeIssued Issue failed") - unless AddIssue($patron, $prev_item->{barcode}); + unless AddIssue( $patron, $prev_item->{barcode} ); # Mappings my $CBBI_mappings = [ @@ -415,12 +425,9 @@ my $CBBI_mappings = [ # Tests map { - t::lib::Mocks::mock_preference('checkprevcheckout', $_->{syspref}); - my ( $issuingimpossible, $needsconfirmation ) = - C4::Circulation::CanBookBeIssued( - $patron, $_->{item}->{barcode} - ); - is($needsconfirmation->{PREVISSUE}, $_->{result}, $_->{msg}); + t::lib::Mocks::mock_preference( 'checkprevcheckout', $_->{syspref} ); + my ( $issuingimpossible, $needsconfirmation ) = C4::Circulation::CanBookBeIssued( $patron, $_->{item}->{barcode} ); + is( $needsconfirmation->{PREVISSUE}, $_->{result}, $_->{msg} ); } @{$CBBI_mappings}; $schema->storage->txn_rollback; @@ -429,26 +436,32 @@ subtest 'Check previous checkouts for serial' => sub { plan tests => 2; $schema->storage->txn_begin; - my $library = $builder->build_object({ class => 'Koha::Libraries'}); + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); - my $patron = $builder->build_object({ + my $patron = $builder->build_object( + { class => 'Koha::Patrons', - value => { - branchcode => $library->branchcode - } - }); - t::lib::Mocks::mock_userenv({ patron => $patron }); + value => { branchcode => $library->branchcode } + } + ); + t::lib::Mocks::mock_userenv( { patron => $patron } ); my $biblio = $builder->build_sample_biblio; $biblio->serial(1)->store; - my $item1 = $builder->build_sample_item({ biblionumber => $biblio->biblionumber }); - my $item2 = $builder->build_sample_item({ biblionumber => $biblio->biblionumber }); + my $item1 = $builder->build_sample_item( { biblionumber => $biblio->biblionumber } ); + my $item2 = $builder->build_sample_item( { biblionumber => $biblio->biblionumber } ); - AddIssue($patron, $item1->barcode); + AddIssue( $patron, $item1->barcode ); - is($patron->do_check_for_previous_checkout($item1->unblessed), 1, 'Check only one item if bibliographic record is serial'); - is($patron->do_check_for_previous_checkout($item2->unblessed), 0, 'Check only one item if bibliographic record is serial'); + is( + $patron->do_check_for_previous_checkout( $item1->unblessed ), 1, + 'Check only one item if bibliographic record is serial' + ); + is( + $patron->do_check_for_previous_checkout( $item2->unblessed ), 0, + 'Check only one item if bibliographic record is serial' + ); $schema->storage->txn_rollback; }; @@ -456,31 +469,36 @@ subtest 'Check previous checkouts for serial' => sub { subtest 'Check previous checkouts with delay' => sub { plan tests => 3; $schema->storage->txn_begin; - my $library = $builder->build_object({ class => 'Koha::Libraries'}); - my $biblio = $builder->build_sample_biblio; - my $patron = $builder->build({source => 'Borrower'}); - my $item_object = $builder->build_sample_item({ biblionumber => $biblio->biblionumber }); + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); + my $biblio = $builder->build_sample_biblio; + my $patron = $builder->build( { source => 'Borrower' } ); + my $item_object = $builder->build_sample_item( { biblionumber => $biblio->biblionumber } ); - my $issue = Koha::Checkout->new({ branchcode => $library->branchcode, borrowernumber => $patron->{borrowernumber}, itemnumber => $item_object->itemnumber })->store; + my $issue = Koha::Checkout->new( + { + branchcode => $library->branchcode, borrowernumber => $patron->{borrowernumber}, + itemnumber => $item_object->itemnumber + } + )->store; my $returndate = dt_from_string()->subtract( days => 3 ); - my $return = AddReturn($item_object->barcode, $library->branchcode, undef, $returndate); + my $return = AddReturn( $item_object->barcode, $library->branchcode, undef, $returndate ); - t::lib::Mocks::mock_preference('checkprevcheckout', 'hardyes'); - t::lib::Mocks::mock_preference('checkprevcheckoutdelay', 0); - my $patron1 = Koha::Patrons->find($patron->{borrowernumber}); + t::lib::Mocks::mock_preference( 'checkprevcheckout', 'hardyes' ); + t::lib::Mocks::mock_preference( 'checkprevcheckoutdelay', 0 ); + my $patron1 = Koha::Patrons->find( $patron->{borrowernumber} ); is( - $patron1->do_check_for_previous_checkout($item_object->unblessed), - 1, "Checking CheckPrevCheckoutDelay disabled" + $patron1->do_check_for_previous_checkout( $item_object->unblessed ), + 1, "Checking CheckPrevCheckoutDelay disabled" ); - t::lib::Mocks::mock_preference('checkprevcheckoutdelay', 5); + t::lib::Mocks::mock_preference( 'checkprevcheckoutdelay', 5 ); is( - $patron1->do_check_for_previous_checkout($item_object->unblessed), - 1, "Checking CheckPrevCheckoutDelay enabled within delay" + $patron1->do_check_for_previous_checkout( $item_object->unblessed ), + 1, "Checking CheckPrevCheckoutDelay enabled within delay" ); - t::lib::Mocks::mock_preference('checkprevcheckoutdelay', 1); + t::lib::Mocks::mock_preference( 'checkprevcheckoutdelay', 1 ); is( - $patron1->do_check_for_previous_checkout($item_object->unblessed), - 0, "Checking CheckPrevCheckoutDelay enabled after delay" + $patron1->do_check_for_previous_checkout( $item_object->unblessed ), + 0, "Checking CheckPrevCheckoutDelay enabled after delay" ); $schema->storage->txn_rollback; -} + } diff --git a/t/db_dependent/Patron/Housebound.t b/t/db_dependent/Patron/Housebound.t index b5024bc4df..c3ac52ff8c 100755 --- a/t/db_dependent/Patron/Housebound.t +++ b/t/db_dependent/Patron/Housebound.t @@ -18,18 +18,19 @@ $schema->storage->txn_begin; my $builder = t::lib::TestBuilder->new; -my $patron = $builder->build({ source => 'Borrower' }); -my $profile = $builder->build({ - source => 'HouseboundProfile', - value => { - borrowernumber => $patron->{borrowernumber}, - }, -}); +my $patron = $builder->build( { source => 'Borrower' } ); +my $profile = $builder->build( + { + source => 'HouseboundProfile', + value => { + borrowernumber => $patron->{borrowernumber}, + }, + } +); # Test housebound_profile is( - Koha::Patrons->find($patron->{borrowernumber}) - ->housebound_profile->frequency, + Koha::Patrons->find( $patron->{borrowernumber} )->housebound_profile->frequency, $profile->{frequency}, "Fetch housebound_profile." ); diff --git a/t/db_dependent/Patron/HouseboundProfiles.t b/t/db_dependent/Patron/HouseboundProfiles.t index 48e21c94d6..f7caec3b47 100755 --- a/t/db_dependent/Patron/HouseboundProfiles.t +++ b/t/db_dependent/Patron/HouseboundProfiles.t @@ -33,17 +33,15 @@ subtest 'housebound_visits() tests' => sub { $schema->storage->txn_begin; - my $profile = $builder->build({ source => 'HouseboundProfile' }); + my $profile = $builder->build( { source => 'HouseboundProfile' } ); is( - Koha::Patron::HouseboundProfiles - ->find($profile->{borrowernumber})->borrowernumber, + Koha::Patron::HouseboundProfiles->find( $profile->{borrowernumber} )->borrowernumber, $profile->{borrowernumber}, "Find created profile." ); - my @profiles = Koha::Patron::HouseboundProfiles - ->search({ day => $profile->{day} })->as_list; + my @profiles = Koha::Patron::HouseboundProfiles->search( { day => $profile->{day} } )->as_list; my $found_profile = shift @profiles; is( $found_profile->borrowernumber, @@ -53,18 +51,22 @@ subtest 'housebound_visits() tests' => sub { # ->housebound_profile Tests - my $visit1 = $builder->build({ - source => 'HouseboundVisit', - value => { - borrowernumber => $profile->{borrowernumber}, - }, - }); - my $visit2 = $builder->build({ - source => 'HouseboundVisit', - value => { - borrowernumber => $profile->{borrowernumber}, - }, - }); + my $visit1 = $builder->build( + { + source => 'HouseboundVisit', + value => { + borrowernumber => $profile->{borrowernumber}, + }, + } + ); + my $visit2 = $builder->build( + { + source => 'HouseboundVisit', + value => { + borrowernumber => $profile->{borrowernumber}, + }, + } + ); is( $found_profile->housebound_visits->count, diff --git a/t/db_dependent/Patron/HouseboundRoles.t b/t/db_dependent/Patron/HouseboundRoles.t index 797a2d7437..6ed0f9a5a7 100755 --- a/t/db_dependent/Patron/HouseboundRoles.t +++ b/t/db_dependent/Patron/HouseboundRoles.t @@ -32,17 +32,15 @@ my $builder = t::lib::TestBuilder->new; # Profile Tests -my $role = $builder->build({ source => 'HouseboundRole' }); +my $role = $builder->build( { source => 'HouseboundRole' } ); is( - Koha::Patron::HouseboundRoles - ->find($role->{borrowernumber_id})->borrowernumber_id, + Koha::Patron::HouseboundRoles->find( $role->{borrowernumber_id} )->borrowernumber_id, $role->{borrowernumber_id}, "Find created role." ); -my @roles = Koha::Patron::HouseboundRoles - ->search({ borrowernumber_id => $role->{borrowernumber_id} })->as_list; +my @roles = Koha::Patron::HouseboundRoles->search( { borrowernumber_id => $role->{borrowernumber_id} } )->as_list; my $found_role = shift @roles; is( $found_role->borrowernumber_id, @@ -57,33 +55,36 @@ my $orig_del_count = Koha::Patrons->search_housebound_deliverers->count; my $orig_cho_count = Koha::Patrons->search_housebound_choosers->count; # We add one, just in case the above is 0, so we're guaranteed one of each. -my $patron_chooser = $builder->build({ source => 'Borrower' }); -$builder->build({ - source => 'HouseboundRole', - value => { - borrowernumber_id => $patron_chooser->{borrowernumber}, - housebound_chooser => 1, - housebound_deliverer => 0, - }, -}); +my $patron_chooser = $builder->build( { source => 'Borrower' } ); +$builder->build( + { + source => 'HouseboundRole', + value => { + borrowernumber_id => $patron_chooser->{borrowernumber}, + housebound_chooser => 1, + housebound_deliverer => 0, + }, + } +); -my $patron_deliverer = $builder->build({ source => 'Borrower' }); -$builder->build({ - source => 'HouseboundRole', - value => { - borrowernumber_id => $patron_deliverer->{borrowernumber}, - housebound_deliverer => 1, - housebound_chooser => 0, - }, -}); +my $patron_deliverer = $builder->build( { source => 'Borrower' } ); +$builder->build( + { + source => 'HouseboundRole', + value => { + borrowernumber_id => $patron_deliverer->{borrowernumber}, + housebound_deliverer => 1, + housebound_chooser => 0, + }, + } +); # Test search_housebound_choosers -is(Koha::Patrons->search_housebound_choosers->count, $orig_cho_count + 1, "Correct count of choosers."); -is(Koha::Patrons->search_housebound_deliverers->count, $orig_del_count + 1, "Correct count of deliverers"); - -isa_ok(Koha::Patrons->search_housebound_choosers->next, "Koha::Patron"); -isa_ok(Koha::Patrons->search_housebound_deliverers->next, "Koha::Patron"); +is( Koha::Patrons->search_housebound_choosers->count, $orig_cho_count + 1, "Correct count of choosers." ); +is( Koha::Patrons->search_housebound_deliverers->count, $orig_del_count + 1, "Correct count of deliverers" ); +isa_ok( Koha::Patrons->search_housebound_choosers->next, "Koha::Patron" ); +isa_ok( Koha::Patrons->search_housebound_deliverers->next, "Koha::Patron" ); $schema->storage->txn_rollback; diff --git a/t/db_dependent/Patron/HouseboundVisits.t b/t/db_dependent/Patron/HouseboundVisits.t index 23e8ddca18..a0e145834c 100755 --- a/t/db_dependent/Patron/HouseboundVisits.t +++ b/t/db_dependent/Patron/HouseboundVisits.t @@ -32,11 +32,10 @@ my $builder = t::lib::TestBuilder->new; ########### Test HouseboundVisits -my $visit = $builder->build({ source => 'HouseboundVisit' }); +my $visit = $builder->build( { source => 'HouseboundVisit' } ); is( - Koha::Patron::HouseboundVisits - ->find($visit->{id})->id, + Koha::Patron::HouseboundVisits->find( $visit->{id} )->id, $visit->{id}, "Find created visit." ); @@ -44,8 +43,7 @@ is( # Using our Prefetching search # Does it work implicitly? -my @visits = Koha::Patron::HouseboundVisits - ->special_search({ borrowernumber => $visit->{borrowernumber} })->as_list; +my @visits = Koha::Patron::HouseboundVisits->special_search( { borrowernumber => $visit->{borrowernumber} } )->as_list; my $found_visit = shift @visits; is( $found_visit->borrowernumber, @@ -54,8 +52,8 @@ is( ); # Does it work Explicitly? -@visits = Koha::Patron::HouseboundVisits - ->special_search({ 'me.borrowernumber' => $visit->{borrowernumber} })->as_list; +@visits = + Koha::Patron::HouseboundVisits->special_search( { 'me.borrowernumber' => $visit->{borrowernumber} } )->as_list; $found_visit = shift @visits; is( $found_visit->borrowernumber, @@ -64,8 +62,9 @@ is( ); # Does it work without prefetcing? -@visits = Koha::Patron::HouseboundVisits - ->special_search({ borrowernumber => $visit->{borrowernumber} }, { prefetch => [] })->as_list; +@visits = + Koha::Patron::HouseboundVisits->special_search( { borrowernumber => $visit->{borrowernumber} }, { prefetch => [] } ) + ->as_list; $found_visit = shift @visits; is( $found_visit->borrowernumber, @@ -75,14 +74,14 @@ is( ########### Test HouseboundVisit -my $result = Koha::Patron::HouseboundVisits->find($visit->{id}); +my $result = Koha::Patron::HouseboundVisits->find( $visit->{id} ); is( $result->deliverer->borrowernumber, $visit->{deliverer_brwnumber} ); is( $result->chooser->borrowernumber, $visit->{chooser_brwnumber} ); -isa_ok( $result->deliverer, "Koha::Patron"); -isa_ok( $result->chooser, "Koha::Patron"); +isa_ok( $result->deliverer, "Koha::Patron" ); +isa_ok( $result->chooser, "Koha::Patron" ); $schema->storage->txn_rollback; diff --git a/t/db_dependent/Patron/Messages.t b/t/db_dependent/Patron/Messages.t index 8da4915d10..8b28613f42 100755 --- a/t/db_dependent/Patron/Messages.t +++ b/t/db_dependent/Patron/Messages.t @@ -21,7 +21,7 @@ use Koha::Patrons; use Koha::Patron::Messages; use t::lib::TestBuilder; -my $schema = Koha::Database->new->schema; +my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; my $builder = t::lib::TestBuilder->new; @@ -29,22 +29,27 @@ my $builder = t::lib::TestBuilder->new; subtest 'Delete a patron having messages' => sub { plan tests => 2; - my $patron = $builder->build({ source => 'Borrower' }); - my $message = $builder->build({ - source => 'Message', - value => { - borrowernumber => $patron->{borrowernumber}, - message => 'This is a message.' + my $patron = $builder->build( { source => 'Borrower' } ); + my $message = $builder->build( + { + source => 'Message', + value => { + borrowernumber => $patron->{borrowernumber}, + message => 'This is a message.' + } } - }); + ); - is(Koha::Patron::Messages->find($message->{message_id})->message, 'This is a message.', 'Got the right message'); + is( + Koha::Patron::Messages->find( $message->{message_id} )->message, 'This is a message.', + 'Got the right message' + ); my $patron_to_delete = Koha::Patrons->find( $patron->{borrowernumber} ); $patron_to_delete->move_to_deleted; $patron_to_delete->delete; - is(Koha::Patron::Messages->find($message->{message_id}), undef, 'Message is deleted'); + is( Koha::Patron::Messages->find( $message->{message_id} ), undef, 'Message is deleted' ); }; $schema->storage->txn_rollback; diff --git a/t/db_dependent/Patron/Messaging.t b/t/db_dependent/Patron/Messaging.t index 14a1f49164..2f02c3ef4b 100755 --- a/t/db_dependent/Patron/Messaging.t +++ b/t/db_dependent/Patron/Messaging.t @@ -74,9 +74,7 @@ DELETESQL my $message_attribute = $builder->build( { source => 'MessageAttribute', - value => { - message_name => 'Advance_Notice' - } + value => { message_name => 'Advance_Notice' } } ); @@ -98,11 +96,10 @@ DELETESQL { source => 'BorrowerMessagePreference', value => { - borrowernumber => $borrower->{borrowernumber}, - wants_digest => 1, - days_in_advance => 1, - message_attribute_id => - $message_attribute->{message_attribute_id} + borrowernumber => $borrower->{borrowernumber}, + wants_digest => 1, + days_in_advance => 1, + message_attribute_id => $message_attribute->{message_attribute_id} } } ); @@ -111,9 +108,8 @@ DELETESQL { source => 'BorrowerMessageTransportPreference', value => { - borrower_message_preference_id => $borrower_message_preference - ->{borrower_message_preference_id}, - message_transport_type => 'email' + borrower_message_preference_id => $borrower_message_preference->{borrower_message_preference_id}, + message_transport_type => 'email' } } ); @@ -122,16 +118,24 @@ DELETESQL { source => 'BorrowerMessageTransportPreference', value => { - borrower_message_preference_id => $borrower_message_preference - ->{borrower_message_preference_id}, - message_transport_type => 'phone' + borrower_message_preference_id => $borrower_message_preference->{borrower_message_preference_id}, + message_transport_type => 'phone' } } ); my $patron = Koha::Patrons->find( $borrower->{borrowernumber} ); - is( $patron->has_messaging_preference({ message_name => 'Advance_Notice', message_transport_type => 'email' }), 1, "Patron has Advance_Notice email preference" ); - is( $patron->has_messaging_preference({ message_name => 'Advance_Notice', message_transport_type => 'phone' }), 1, "Patron has Advance_Notice phone preference" ); - is( $patron->has_messaging_preference({ message_name => 'Advance_Notice', message_transport_type => 'sms' }), 0, "Patron has no Advance_Notice sms preference" ); + is( + $patron->has_messaging_preference( { message_name => 'Advance_Notice', message_transport_type => 'email' } ), + 1, "Patron has Advance_Notice email preference" + ); + is( + $patron->has_messaging_preference( { message_name => 'Advance_Notice', message_transport_type => 'phone' } ), + 1, "Patron has Advance_Notice phone preference" + ); + is( + $patron->has_messaging_preference( { message_name => 'Advance_Notice', message_transport_type => 'sms' } ), 0, + "Patron has no Advance_Notice sms preference" + ); }; diff --git a/t/db_dependent/Patron/Relationships.t b/t/db_dependent/Patron/Relationships.t index dacac11bf3..70d476f0f9 100755 --- a/t/db_dependent/Patron/Relationships.t +++ b/t/db_dependent/Patron/Relationships.t @@ -79,73 +79,77 @@ my $kylie = $builder->build_object( } ); -Koha::Patron::Relationship->new({ guarantor_id => $kyle->id, guarantee_id => $daria->id, relationship => 'father' })->store(); -Koha::Patron::Relationship->new({ guarantor_id => $kyle->id, guarantee_id => $kylie->id, relationship => 'father' })->store(); -Koha::Patron::Relationship->new({ guarantor_id => $chelsea->id, guarantee_id => $daria->id, relationship => 'mother' })->store(); -Koha::Patron::Relationship->new({ guarantor_id => $chelsea->id, guarantee_id => $kylie->id, relationship => 'mother' })->store(); +Koha::Patron::Relationship->new( { guarantor_id => $kyle->id, guarantee_id => $daria->id, relationship => 'father' } ) + ->store(); +Koha::Patron::Relationship->new( { guarantor_id => $kyle->id, guarantee_id => $kylie->id, relationship => 'father' } ) + ->store(); +Koha::Patron::Relationship->new( + { guarantor_id => $chelsea->id, guarantee_id => $daria->id, relationship => 'mother' } )->store(); +Koha::Patron::Relationship->new( + { guarantor_id => $chelsea->id, guarantee_id => $kylie->id, relationship => 'mother' } )->store(); my @gr; @gr = $kyle->guarantee_relationships()->as_list; -is( @gr, 2, 'Found 2 guarantee relationships for father' ); -is( $gr[0]->guarantor_id, $kyle->id, 'Guarantor matches for first relationship' ); -is( $gr[0]->guarantee_id, $daria->id, 'Guarantee matches for first relationship' ); -is( $gr[0]->relationship, 'father', 'Relationship is father' ); -is( ref($gr[0]->guarantee), 'Koha::Patron', 'Method guarantee returns a Koha::Patron' ); -is( $gr[0]->guarantee->id, $daria->id, 'Koha::Patron returned is the correct guarantee' ); -is( ref($gr[0]->guarantor), 'Koha::Patron', 'Method guarantor returns a Koha::Patron' ); -is( $gr[0]->guarantor->id, $kyle->id, 'Koha::Patron returned is the correct guarantor' ); +is( @gr, 2, 'Found 2 guarantee relationships for father' ); +is( $gr[0]->guarantor_id, $kyle->id, 'Guarantor matches for first relationship' ); +is( $gr[0]->guarantee_id, $daria->id, 'Guarantee matches for first relationship' ); +is( $gr[0]->relationship, 'father', 'Relationship is father' ); +is( ref( $gr[0]->guarantee ), 'Koha::Patron', 'Method guarantee returns a Koha::Patron' ); +is( $gr[0]->guarantee->id, $daria->id, 'Koha::Patron returned is the correct guarantee' ); +is( ref( $gr[0]->guarantor ), 'Koha::Patron', 'Method guarantor returns a Koha::Patron' ); +is( $gr[0]->guarantor->id, $kyle->id, 'Koha::Patron returned is the correct guarantor' ); -is( $gr[1]->guarantor_id, $kyle->id, 'Guarantor matches for first relationship' ); -is( $gr[1]->guarantee_id, $kylie->id, 'Guarantee matches for first relationship' ); -is( $gr[1]->relationship, 'father', 'Relationship is father' ); -is( ref($gr[1]->guarantee), 'Koha::Patron', 'Method guarantee returns a Koha::Patron' ); -is( $gr[1]->guarantee->id, $kylie->id, 'Koha::Patron returned is the correct guarantee' ); -is( ref($gr[1]->guarantor), 'Koha::Patron', 'Method guarantor returns a Koha::Patron' ); -is( $gr[1]->guarantor->id, $kyle->id, 'Koha::Patron returned is the correct guarantor' ); +is( $gr[1]->guarantor_id, $kyle->id, 'Guarantor matches for first relationship' ); +is( $gr[1]->guarantee_id, $kylie->id, 'Guarantee matches for first relationship' ); +is( $gr[1]->relationship, 'father', 'Relationship is father' ); +is( ref( $gr[1]->guarantee ), 'Koha::Patron', 'Method guarantee returns a Koha::Patron' ); +is( $gr[1]->guarantee->id, $kylie->id, 'Koha::Patron returned is the correct guarantee' ); +is( ref( $gr[1]->guarantor ), 'Koha::Patron', 'Method guarantor returns a Koha::Patron' ); +is( $gr[1]->guarantor->id, $kyle->id, 'Koha::Patron returned is the correct guarantor' ); @gr = $chelsea->guarantee_relationships()->as_list; -is( @gr, 2, 'Found 2 guarantee relationships for mother' ); -is( $gr[0]->guarantor_id, $chelsea->id, 'Guarantor matches for first relationship' ); -is( $gr[0]->guarantee_id, $daria->id, 'Guarantee matches for first relationship' ); -is( $gr[0]->relationship, 'mother', 'Relationship is mother' ); -is( ref($gr[0]->guarantee), 'Koha::Patron', 'Method guarantee returns a Koha::Patron' ); -is( $gr[0]->guarantee->id, $daria->id, 'Koha::Patron returned is the correct guarantee' ); -is( ref($gr[0]->guarantor), 'Koha::Patron', 'Method guarantor returns a Koha::Patron' ); -is( $gr[0]->guarantor->id, $chelsea->id, 'Koha::Patron returned is the correct guarantor' ); +is( @gr, 2, 'Found 2 guarantee relationships for mother' ); +is( $gr[0]->guarantor_id, $chelsea->id, 'Guarantor matches for first relationship' ); +is( $gr[0]->guarantee_id, $daria->id, 'Guarantee matches for first relationship' ); +is( $gr[0]->relationship, 'mother', 'Relationship is mother' ); +is( ref( $gr[0]->guarantee ), 'Koha::Patron', 'Method guarantee returns a Koha::Patron' ); +is( $gr[0]->guarantee->id, $daria->id, 'Koha::Patron returned is the correct guarantee' ); +is( ref( $gr[0]->guarantor ), 'Koha::Patron', 'Method guarantor returns a Koha::Patron' ); +is( $gr[0]->guarantor->id, $chelsea->id, 'Koha::Patron returned is the correct guarantor' ); -is( $gr[1]->guarantor_id, $chelsea->id, 'Guarantor matches for first relationship' ); -is( $gr[1]->guarantee_id, $kylie->id, 'Guarantee matches for first relationship' ); -is( $gr[1]->relationship, 'mother', 'Relationship is mother' ); -is( ref($gr[1]->guarantee), 'Koha::Patron', 'Method guarantee returns a Koha::Patron' ); -is( $gr[1]->guarantee->id, $kylie->id, 'Koha::Patron returned is the correct guarantee' ); -is( ref($gr[1]->guarantor), 'Koha::Patron', 'Method guarantor returns a Koha::Patron' ); -is( $gr[1]->guarantor->id, $chelsea->id, 'Koha::Patron returned is the correct guarantor' ); +is( $gr[1]->guarantor_id, $chelsea->id, 'Guarantor matches for first relationship' ); +is( $gr[1]->guarantee_id, $kylie->id, 'Guarantee matches for first relationship' ); +is( $gr[1]->relationship, 'mother', 'Relationship is mother' ); +is( ref( $gr[1]->guarantee ), 'Koha::Patron', 'Method guarantee returns a Koha::Patron' ); +is( $gr[1]->guarantee->id, $kylie->id, 'Koha::Patron returned is the correct guarantee' ); +is( ref( $gr[1]->guarantor ), 'Koha::Patron', 'Method guarantor returns a Koha::Patron' ); +is( $gr[1]->guarantor->id, $chelsea->id, 'Koha::Patron returned is the correct guarantor' ); @gr = $daria->guarantor_relationships()->as_list; -is( @gr, 2, 'Found 4 guarantor relationships for child' ); -is( $gr[0]->guarantor_id, $kyle->id, 'Guarantor matches for first relationship' ); -is( $gr[0]->guarantee_id, $daria->id, 'Guarantee matches for first relationship' ); -is( $gr[0]->relationship, 'father', 'Relationship is father' ); -is( ref($gr[0]->guarantee), 'Koha::Patron', 'Method guarantee returns a Koha::Patron' ); -is( $gr[0]->guarantee->id, $daria->id, 'Koha::Patron returned is the correct guarantee' ); -is( ref($gr[0]->guarantor), 'Koha::Patron', 'Method guarantor returns a Koha::Patron' ); -is( $gr[0]->guarantor->id, $kyle->id, 'Koha::Patron returned is the correct guarantor' ); +is( @gr, 2, 'Found 4 guarantor relationships for child' ); +is( $gr[0]->guarantor_id, $kyle->id, 'Guarantor matches for first relationship' ); +is( $gr[0]->guarantee_id, $daria->id, 'Guarantee matches for first relationship' ); +is( $gr[0]->relationship, 'father', 'Relationship is father' ); +is( ref( $gr[0]->guarantee ), 'Koha::Patron', 'Method guarantee returns a Koha::Patron' ); +is( $gr[0]->guarantee->id, $daria->id, 'Koha::Patron returned is the correct guarantee' ); +is( ref( $gr[0]->guarantor ), 'Koha::Patron', 'Method guarantor returns a Koha::Patron' ); +is( $gr[0]->guarantor->id, $kyle->id, 'Koha::Patron returned is the correct guarantor' ); -is( $gr[1]->guarantor_id, $chelsea->id, 'Guarantor matches for first relationship' ); -is( $gr[1]->guarantee_id, $daria->id, 'Guarantee matches for first relationship' ); -is( $gr[1]->relationship, 'mother', 'Relationship is mother' ); -is( ref($gr[1]->guarantee), 'Koha::Patron', 'Method guarantee returns a Koha::Patron' ); -is( $gr[1]->guarantee->id, $daria->id, 'Koha::Patron returned is the correct guarantee' ); -is( ref($gr[1]->guarantor), 'Koha::Patron', 'Method guarantor returns a Koha::Patron' ); -is( $gr[1]->guarantor->id, $chelsea->id, 'Koha::Patron returned is the correct guarantor' ); +is( $gr[1]->guarantor_id, $chelsea->id, 'Guarantor matches for first relationship' ); +is( $gr[1]->guarantee_id, $daria->id, 'Guarantee matches for first relationship' ); +is( $gr[1]->relationship, 'mother', 'Relationship is mother' ); +is( ref( $gr[1]->guarantee ), 'Koha::Patron', 'Method guarantee returns a Koha::Patron' ); +is( $gr[1]->guarantee->id, $daria->id, 'Koha::Patron returned is the correct guarantee' ); +is( ref( $gr[1]->guarantor ), 'Koha::Patron', 'Method guarantor returns a Koha::Patron' ); +is( $gr[1]->guarantor->id, $chelsea->id, 'Koha::Patron returned is the correct guarantor' ); my $siblings = $daria->siblings; -my $sibling = $siblings->next(); -is( ref($siblings), 'Koha::Patrons', 'Calling siblings in scalar context results in a Koha::Patrons object' ); -is( ref($sibling), 'Koha::Patron', 'Method next returns a Koha::Patron' ); -is( $sibling->firstname, 'Kylie', 'Sibling from scalar first name matches correctly' ); -is( $sibling->surname, 'Hall', 'Sibling from scalar surname matches correctly' ); -is( $sibling->id, $kylie->id, 'Sibling from scalar patron id matches correctly' ); +my $sibling = $siblings->next(); +is( ref($siblings), 'Koha::Patrons', 'Calling siblings in scalar context results in a Koha::Patrons object' ); +is( ref($sibling), 'Koha::Patron', 'Method next returns a Koha::Patron' ); +is( $sibling->firstname, 'Kylie', 'Sibling from scalar first name matches correctly' ); +is( $sibling->surname, 'Hall', 'Sibling from scalar surname matches correctly' ); +is( $sibling->id, $kylie->id, 'Sibling from scalar patron id matches correctly' ); $schema->storage->txn_rollback; diff --git a/t/db_dependent/PatronLists.t b/t/db_dependent/PatronLists.t index b2edc8d8ff..52090b4b3e 100755 --- a/t/db_dependent/PatronLists.t +++ b/t/db_dependent/PatronLists.t @@ -35,14 +35,14 @@ t::lib::Mocks::mock_userenv(); # Create 10 sample borrowers my @borrowers = (); -foreach (1..10) { - push @borrowers, $builder->build({ source => 'Borrower' }); +foreach ( 1 .. 10 ) { + push @borrowers, $builder->build( { source => 'Borrower' } ); } my $owner = $borrowers[0]->{borrowernumber}; my $owner2 = $borrowers[1]->{borrowernumber}; -my @lists = GetPatronLists( { owner => $owner } ); +my @lists = GetPatronLists( { owner => $owner } ); my $list_count_original = @lists; my $list1 = AddPatronList( { name => 'Test List 1', owner => $owner } ); @@ -60,12 +60,10 @@ ModPatronList( $list2->discard_changes(); is( $list2->name(), 'Test List 3', 'ModPatronList works' ); -AddPatronsToList( - { list => $list1, cardnumbers => [ map { $_->{cardnumber} } @borrowers ] } -); +AddPatronsToList( { list => $list1, cardnumbers => [ map { $_->{cardnumber} } @borrowers ] } ); is( scalar @borrowers, - $list1->patron_list_patrons()->search_related('borrowernumber')->all(), + $list1->patron_list_patrons()->search_related('borrowernumber')->all(), 'AddPatronsToList works for cardnumbers' ); @@ -77,19 +75,19 @@ AddPatronsToList( ); is( scalar @borrowers, - $list2->patron_list_patrons()->search_related('borrowernumber')->all(), + $list2->patron_list_patrons()->search_related('borrowernumber')->all(), 'AddPatronsToList works for borrowernumbers' ); -my $deleted_patron = $builder->build_object({ class => 'Koha::Patrons' }); +my $deleted_patron = $builder->build_object( { class => 'Koha::Patrons' } ); $deleted_patron->delete; -my @result = AddPatronsToList({list => $list2,borrowernumbers => [ $deleted_patron->borrowernumber ]}); -is( scalar @result, 0,'Invalid borrowernumber not added'); -@result = AddPatronsToList({list => $list2,cardnumbers => [ $deleted_patron->cardnumber ]}); -is( scalar @result, 0,'Invalid cardnumber not added'); +my @result = AddPatronsToList( { list => $list2, borrowernumbers => [ $deleted_patron->borrowernumber ] } ); +is( scalar @result, 0, 'Invalid borrowernumber not added' ); +@result = AddPatronsToList( { list => $list2, cardnumbers => [ $deleted_patron->cardnumber ] } ); +is( scalar @result, 0, 'Invalid cardnumber not added' ); my @ids = - $list1->patron_list_patrons()->get_column('patron_list_patron_id')->all(); + $list1->patron_list_patrons()->get_column('patron_list_patron_id')->all(); DelPatronsFromList( { list => $list1, @@ -99,8 +97,8 @@ DelPatronsFromList( $list1->discard_changes(); is( $list1->patron_list_patrons()->count(), 0, 'DelPatronsFromList works.' ); -my $patron = $builder->build_object({ class => 'Koha::Patrons' }); -AddPatronsToList({list => $list2,borrowernumbers => [ $patron->borrowernumber ]}); +my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); +AddPatronsToList( { list => $list2, borrowernumbers => [ $patron->borrowernumber ] } ); @lists = $patron->get_lists_with_patron; is( scalar @lists, 1, 'get_lists_with_patron works' ); @@ -119,7 +117,7 @@ DelPatronList( { patron_list_id => $list1->patron_list_id(), owner => $owner } ) DelPatronList( { patron_list_id => $list2->patron_list_id(), owner => $owner } ); @lists = - GetPatronLists( { patron_list_id => $list1->patron_list_id(), owner => $owner } ); + GetPatronLists( { patron_list_id => $list1->patron_list_id(), owner => $owner } ); is( scalar @lists, 0, 'DelPatronList works' ); $schema->storage->txn_rollback; diff --git a/t/db_dependent/Patrons.t b/t/db_dependent/Patrons.t index 2d93fa7831..ad63834212 100755 --- a/t/db_dependent/Patrons.t +++ b/t/db_dependent/Patrons.t @@ -35,12 +35,12 @@ BEGIN { # Start transaction my $database = Koha::Database->new(); -my $schema = $database->schema(); +my $schema = $database->schema(); $schema->storage->txn_begin(); my $builder = t::lib::TestBuilder->new; -my $categorycode = $builder->build({ source => 'Category' })->{categorycode}; -my $branchcode = $builder->build({ source => 'Branch' })->{branchcode}; +my $categorycode = $builder->build( { source => 'Category' } )->{categorycode}; +my $branchcode = $builder->build( { source => 'Branch' } )->{branchcode}; my $b1 = Koha::Patron->new( { @@ -51,7 +51,7 @@ my $b1 = Koha::Patron->new( ); $b1->store(); my $now = dt_from_string; -my $b2 = Koha::Patron->new( +my $b2 = Koha::Patron->new( { surname => 'Test 2', branchcode => $branchcode, @@ -60,7 +60,7 @@ my $b2 = Koha::Patron->new( ); $b2->store(); my $three_days_ago = dt_from_string->add( days => -3 ); -my $b3 = Koha::Patron->new( +my $b3 = Koha::Patron->new( { surname => 'Test 3', branchcode => $branchcode, @@ -73,18 +73,27 @@ $b3->store(); my $b1_new = Koha::Patrons->find( $b1->borrowernumber() ); is( $b1->surname(), $b1_new->surname(), "Found matching patron" ); isnt( $b1_new->updated_on, undef, "borrowers.updated_on should be set" ); -is( t::lib::Dates::compare( $b1_new->updated_on, $now), 0, "borrowers.updated_on should have been set to now on creating" ); +is( + t::lib::Dates::compare( $b1_new->updated_on, $now ), 0, + "borrowers.updated_on should have been set to now on creating" +); my $b3_new = Koha::Patrons->find( $b3->borrowernumber() ); -is( t::lib::Dates::compare( $b3_new->updated_on, $three_days_ago), 0, "borrowers.updated_on should have been kept to what we set on creating" ); -$b3_new->set({ firstname => 'Some first name for Test 3' })->store(); +is( + t::lib::Dates::compare( $b3_new->updated_on, $three_days_ago ), 0, + "borrowers.updated_on should have been kept to what we set on creating" +); +$b3_new->set( { firstname => 'Some first name for Test 3' } )->store(); $b3_new = Koha::Patrons->find( $b3->borrowernumber() ); -is( t::lib::Dates::compare( $b3_new->updated_on, $now), 0, "borrowers.updated_on should have been set to now on updating" ); +is( + t::lib::Dates::compare( $b3_new->updated_on, $now ), 0, + "borrowers.updated_on should have been set to now on updating" +); my @patrons = Koha::Patrons->search( { branchcode => $branchcode } )->as_list; is( @patrons, 3, "Found 3 patrons with Search" ); -my $unexistent = Koha::Patrons->find( '1234567890' ); +my $unexistent = Koha::Patrons->find('1234567890'); is( $unexistent, undef, 'Koha::Objects->Find should return undef if the record does not exist' ); my $patrons = Koha::Patrons->search( { branchcode => $branchcode } ); @@ -108,109 +117,229 @@ foreach my $b ( $patrons->as_list() ) { subtest "Update patron categories" => sub { plan tests => 29; t::lib::Mocks::mock_preference( 'borrowerRelationship', 'test' ); - my $c_categorycode = $builder->build({ source => 'Category', value => { - category_type=>'C', - upperagelimit=>17, - dateofbirthrequired=>5, - can_be_guarantee=>1, - } })->{categorycode}; - my $c_categorycode_2 = $builder->build({ source => 'Category', value => { - category_type=>'C', - upperagelimit=>17, - dateofbirthrequired=>5, - can_be_guarantee=>1, - } })->{categorycode}; - my $a_categorycode = $builder->build({ source => 'Category', value => {category_type=>'A', can_be_guarantee=>0} })->{categorycode}; - my $a_categorycode_2 = $builder->build({ source => 'Category', value => {category_type=>'A', can_be_guarantee=>1} })->{categorycode}; - my $p_categorycode = $builder->build({ source => 'Category', value => {category_type=>'P'} })->{categorycode}; - my $i_categorycode = $builder->build({ source => 'Category', value => {category_type=>'I'} })->{categorycode}; - my $branchcode1 = $builder->build({ source => 'Branch' })->{branchcode}; - my $branchcode2 = $builder->build({ source => 'Branch' })->{branchcode}; - my $adult1 = $builder->build_object({class => 'Koha::Patrons', value => { - categorycode=>$a_categorycode, - branchcode=>$branchcode1, - dateenrolled=>'2018-01-01', - sort1 =>'quack', + my $c_categorycode = $builder->build( + { + source => 'Category', + value => { + category_type => 'C', + upperagelimit => 17, + dateofbirthrequired => 5, + can_be_guarantee => 1, + } } - }); - my $adult2 = $builder->build_object({class => 'Koha::Patrons', value => { - categorycode=>$a_categorycode, - branchcode=>$branchcode2, - dateenrolled=>'2017-01-01', + )->{categorycode}; + my $c_categorycode_2 = $builder->build( + { + source => 'Category', + value => { + category_type => 'C', + upperagelimit => 17, + dateofbirthrequired => 5, + can_be_guarantee => 1, + } } - }); - my $inst = $builder->build_object({class => 'Koha::Patrons', value => { - categorycode=>$i_categorycode, - branchcode=>$branchcode2, + )->{categorycode}; + my $a_categorycode = + $builder->build( { source => 'Category', value => { category_type => 'A', can_be_guarantee => 0 } } ) + ->{categorycode}; + my $a_categorycode_2 = + $builder->build( { source => 'Category', value => { category_type => 'A', can_be_guarantee => 1 } } ) + ->{categorycode}; + my $p_categorycode = $builder->build( { source => 'Category', value => { category_type => 'P' } } )->{categorycode}; + my $i_categorycode = $builder->build( { source => 'Category', value => { category_type => 'I' } } )->{categorycode}; + my $branchcode1 = $builder->build( { source => 'Branch' } )->{branchcode}; + my $branchcode2 = $builder->build( { source => 'Branch' } )->{branchcode}; + my $adult1 = $builder->build_object( + { + class => 'Koha::Patrons', + value => { + categorycode => $a_categorycode, + branchcode => $branchcode1, + dateenrolled => '2018-01-01', + sort1 => 'quack', + } } - }); - my $prof = $builder->build_object({class => 'Koha::Patrons', value => { - categorycode=>$p_categorycode, - branchcode=>$branchcode2, + ); + my $adult2 = $builder->build_object( + { + class => 'Koha::Patrons', + value => { + categorycode => $a_categorycode, + branchcode => $branchcode2, + dateenrolled => '2017-01-01', + } } - }); - $prof->add_guarantor({guarantor_id => $inst->borrowernumber, relationship => 'test'}); - my $child1 = $builder->build_object({class => 'Koha::Patrons', value => { - dateofbirth => dt_from_string->add(years=>-4), - categorycode=>$c_categorycode, - branchcode=>$branchcode1, + ); + my $inst = $builder->build_object( + { + class => 'Koha::Patrons', + value => { + categorycode => $i_categorycode, + branchcode => $branchcode2, + } } - }); - $child1->add_guarantor({guarantor_id => $adult1->borrowernumber, relationship => 'test'}); - my $child2 = $builder->build_object({class => 'Koha::Patrons', value => { - dateofbirth => dt_from_string->add(years=>-8), - categorycode=>$c_categorycode, - branchcode=>$branchcode1, + ); + my $prof = $builder->build_object( + { + class => 'Koha::Patrons', + value => { + categorycode => $p_categorycode, + branchcode => $branchcode2, + } } - }); - $child2->add_guarantor({guarantor_id => $adult1->borrowernumber, relationship => 'test'}); - my $child3 = $builder->build_object({class => 'Koha::Patrons', value => { - dateofbirth => dt_from_string->add(years=>-18), - categorycode=>$c_categorycode, - branchcode=>$branchcode1, + ); + $prof->add_guarantor( { guarantor_id => $inst->borrowernumber, relationship => 'test' } ); + my $child1 = $builder->build_object( + { + class => 'Koha::Patrons', + value => { + dateofbirth => dt_from_string->add( years => -4 ), + categorycode => $c_categorycode, + branchcode => $branchcode1, + } } - }); - $child3->add_guarantor({guarantor_id => $adult1->borrowernumber, relationship => 'test'}); - $builder->build({source=>'Accountline',value => {amountoutstanding=>4.99,borrowernumber=>$adult1->borrowernumber}}); - $builder->build({source=>'Accountline',value => {amountoutstanding=>5.01,borrowernumber=>$adult2->borrowernumber}}); + ); + $child1->add_guarantor( { guarantor_id => $adult1->borrowernumber, relationship => 'test' } ); + my $child2 = $builder->build_object( + { + class => 'Koha::Patrons', + value => { + dateofbirth => dt_from_string->add( years => -8 ), + categorycode => $c_categorycode, + branchcode => $branchcode1, + } + } + ); + $child2->add_guarantor( { guarantor_id => $adult1->borrowernumber, relationship => 'test' } ); + my $child3 = $builder->build_object( + { + class => 'Koha::Patrons', + value => { + dateofbirth => dt_from_string->add( years => -18 ), + categorycode => $c_categorycode, + branchcode => $branchcode1, + } + } + ); + $child3->add_guarantor( { guarantor_id => $adult1->borrowernumber, relationship => 'test' } ); + $builder->build( + { source => 'Accountline', value => { amountoutstanding => 4.99, borrowernumber => $adult1->borrowernumber } } + ); + $builder->build( + { source => 'Accountline', value => { amountoutstanding => 5.01, borrowernumber => $adult2->borrowernumber } } + ); - is( Koha::Patrons->search_patrons_to_update_category({from=>$c_categorycode})->count,3,'Three patrons in child category'); - is( Koha::Patrons->search_patrons_to_update_category({from=>$c_categorycode,too_young=>1})->count,1,'One under age patron in child category'); - is( Koha::Patrons->search_patrons_to_update_category({from=>$c_categorycode,too_young=>1})->next->borrowernumber,$child1->borrowernumber,'Under age patron in child category is expected one'); - is( Koha::Patrons->search_patrons_to_update_category({from=>$c_categorycode,too_old=>1})->count,1,'One over age patron in child category'); - is( Koha::Patrons->search_patrons_to_update_category({from=>$c_categorycode,too_old=>1})->next->borrowernumber,$child3->borrowernumber,'Over age patron in child category is expected one'); - is( Koha::Patrons->search({branchcode=>$branchcode2})->search_patrons_to_update_category({from=>$a_categorycode})->count,1,'One patron in branch 2'); - is( Koha::Patrons->search({branchcode=>$branchcode2})->search_patrons_to_update_category({from=>$a_categorycode})->next->borrowernumber,$adult2->borrowernumber,'Adult patron in branch 2 is expected one'); - is( Koha::Patrons->search_patrons_to_update_category({from=>$a_categorycode,fine_min=>5})->count,1,'One patron with fines over $5'); - is( Koha::Patrons->search_patrons_to_update_category({from=>$a_categorycode,fine_min=>5})->next->borrowernumber,$adult2->borrowernumber,'One patron with fines over $5 is expected one'); - is( Koha::Patrons->search_patrons_to_update_category({from=>$a_categorycode,fine_max=>5})->count,1,'One patron with fines under $5'); - is( Koha::Patrons->search_patrons_to_update_category({from=>$a_categorycode,fine_max=>5})->next->borrowernumber,$adult1->borrowernumber,'One patron with fines under $5 is expected one'); + is( + Koha::Patrons->search_patrons_to_update_category( { from => $c_categorycode } )->count, 3, + 'Three patrons in child category' + ); + is( + Koha::Patrons->search_patrons_to_update_category( { from => $c_categorycode, too_young => 1 } )->count, 1, + 'One under age patron in child category' + ); + is( Koha::Patrons->search_patrons_to_update_category( { from => $c_categorycode, too_young => 1 } ) + ->next->borrowernumber, $child1->borrowernumber, 'Under age patron in child category is expected one' ); + is( + Koha::Patrons->search_patrons_to_update_category( { from => $c_categorycode, too_old => 1 } )->count, 1, + 'One over age patron in child category' + ); + is( Koha::Patrons->search_patrons_to_update_category( { from => $c_categorycode, too_old => 1 } ) + ->next->borrowernumber, $child3->borrowernumber, 'Over age patron in child category is expected one' ); + is( Koha::Patrons->search( { branchcode => $branchcode2 } ) + ->search_patrons_to_update_category( { from => $a_categorycode } )->count, 1, 'One patron in branch 2' ); + is( + Koha::Patrons->search( { branchcode => $branchcode2 } ) + ->search_patrons_to_update_category( { from => $a_categorycode } )->next->borrowernumber, + $adult2->borrowernumber, 'Adult patron in branch 2 is expected one' + ); + is( + Koha::Patrons->search_patrons_to_update_category( { from => $a_categorycode, fine_min => 5 } )->count, 1, + 'One patron with fines over $5' + ); + is( Koha::Patrons->search_patrons_to_update_category( { from => $a_categorycode, fine_min => 5 } ) + ->next->borrowernumber, $adult2->borrowernumber, 'One patron with fines over $5 is expected one' ); + is( + Koha::Patrons->search_patrons_to_update_category( { from => $a_categorycode, fine_max => 5 } )->count, 1, + 'One patron with fines under $5' + ); + is( Koha::Patrons->search_patrons_to_update_category( { from => $a_categorycode, fine_max => 5 } ) + ->next->borrowernumber, $adult1->borrowernumber, 'One patron with fines under $5 is expected one' ); - my $adult3 = $builder->build_object({class => 'Koha::Patrons', value => { - categorycode=>$a_categorycode, - branchcode=>$branchcode1, + my $adult3 = $builder->build_object( + { + class => 'Koha::Patrons', + value => { + categorycode => $a_categorycode, + branchcode => $branchcode1, + } } - }); - is( Koha::Patrons->search_patrons_to_update_category({from=>$a_categorycode,fine_max=>5})->count,2,'Two patrons with fines under $5, patron with no fine history is found'); + ); + is( + Koha::Patrons->search_patrons_to_update_category( { from => $a_categorycode, fine_max => 5 } )->count, 2, + 'Two patrons with fines under $5, patron with no fine history is found' + ); - is( Koha::Patrons->find($adult1->borrowernumber)->guarantee_relationships->guarantees->count,3,'Guarantor has 3 guarantees'); - is( Koha::Patrons->search_patrons_to_update_category({from=>$c_categorycode})->update_category_to({category=>$c_categorycode_2}),3,'Three child patrons updated to another child category with no params passed'); + is( + Koha::Patrons->find( $adult1->borrowernumber )->guarantee_relationships->guarantees->count, 3, + 'Guarantor has 3 guarantees' + ); + is( + Koha::Patrons->search_patrons_to_update_category( { from => $c_categorycode } ) + ->update_category_to( { category => $c_categorycode_2 } ), 3, + 'Three child patrons updated to another child category with no params passed' + ); # FIXME - The script currently allows you to move patrons to a category that is invalid, this test confirms the current behaviour - is( Koha::Patrons->find($adult1->borrowernumber)->guarantee_relationships->guarantees->count,3,'Guarantees not removed when made changing child categories'); - is( Koha::Patrons->search_patrons_to_update_category({from=>$c_categorycode_2,too_young=>1})->next->borrowernumber, $child1->borrowernumber ); - is( Koha::Patrons->search_patrons_to_update_category({from=>$c_categorycode_2,too_young=>1})->update_category_to({category=>$a_categorycode}),1,'One child patron updated to adult category because too young'); - is( Koha::Patrons->find($adult1->borrowernumber)->guarantee_relationships->guarantees->count,2,'Guarantee was removed when made adult'); + is( + Koha::Patrons->find( $adult1->borrowernumber )->guarantee_relationships->guarantees->count, 3, + 'Guarantees not removed when made changing child categories' + ); + is( Koha::Patrons->search_patrons_to_update_category( { from => $c_categorycode_2, too_young => 1 } ) + ->next->borrowernumber, $child1->borrowernumber ); + is( + Koha::Patrons->search_patrons_to_update_category( { from => $c_categorycode_2, too_young => 1 } ) + ->update_category_to( { category => $a_categorycode } ), 1, + 'One child patron updated to adult category because too young' + ); + is( + Koha::Patrons->find( $adult1->borrowernumber )->guarantee_relationships->guarantees->count, 2, + 'Guarantee was removed when made adult' + ); - is( Koha::Patrons->search_patrons_to_update_category({from=>$c_categorycode_2,too_old=>1})->next->borrowernumber, $child3->borrowernumber ); - is( Koha::Patrons->search_patrons_to_update_category({from=>$c_categorycode_2,too_old=>1})->update_category_to({category=>$a_categorycode}),1,'One child patron updated to adult category because too old'); - is( Koha::Patrons->find($adult1->borrowernumber)->guarantee_relationships->guarantees->count,1,'Guarantee was removed when made adult'); - is( Koha::Patrons->search_patrons_to_update_category({from=>$c_categorycode_2})->update_category_to({category=>$a_categorycode_2}),1,'Two child patrons updated to adult category'); - is( Koha::Patrons->find($adult1->borrowernumber)->guarantee_relationships->guarantees->count,1,'Guarantees were not removed when made adult which can be guarantee'); + is( Koha::Patrons->search_patrons_to_update_category( { from => $c_categorycode_2, too_old => 1 } ) + ->next->borrowernumber, $child3->borrowernumber ); + is( + Koha::Patrons->search_patrons_to_update_category( { from => $c_categorycode_2, too_old => 1 } ) + ->update_category_to( { category => $a_categorycode } ), 1, + 'One child patron updated to adult category because too old' + ); + is( + Koha::Patrons->find( $adult1->borrowernumber )->guarantee_relationships->guarantees->count, 1, + 'Guarantee was removed when made adult' + ); + is( + Koha::Patrons->search_patrons_to_update_category( { from => $c_categorycode_2 } ) + ->update_category_to( { category => $a_categorycode_2 } ), 1, + 'Two child patrons updated to adult category' + ); + is( + Koha::Patrons->find( $adult1->borrowernumber )->guarantee_relationships->guarantees->count, 1, + 'Guarantees were not removed when made adult which can be guarantee' + ); - is( Koha::Patrons->find($inst->borrowernumber)->guarantee_relationships->guarantees->count,1,'Guarantor has 1 guarantees'); - is( Koha::Patrons->search_patrons_to_update_category({from=>$p_categorycode})->update_category_to({category=>$a_categorycode}),1,'One professional patron updated to adult category'); - is( Koha::Patrons->find($inst->borrowernumber)->guarantee_relationships->guarantees->count,0,'Guarantee was removed when made adult'); + is( + Koha::Patrons->find( $inst->borrowernumber )->guarantee_relationships->guarantees->count, 1, + 'Guarantor has 1 guarantees' + ); + is( + Koha::Patrons->search_patrons_to_update_category( { from => $p_categorycode } ) + ->update_category_to( { category => $a_categorycode } ), 1, + 'One professional patron updated to adult category' + ); + is( + Koha::Patrons->find( $inst->borrowernumber )->guarantee_relationships->guarantees->count, 0, + 'Guarantee was removed when made adult' + ); is( Koha::Patrons->search_patrons_to_update_category( { from => $a_categorycode, fine_max => 5 } ) @@ -227,7 +356,5 @@ subtest "Update patron categories" => sub { is( $adult1->userid, $userid_before, "Patron userid not changed by updated" ); }; - - $schema->storage->txn_rollback(); diff --git a/t/db_dependent/Prices.t b/t/db_dependent/Prices.t index 2b4ade38ac..5ce15e5136 100755 --- a/t/db_dependent/Prices.t +++ b/t/db_dependent/Prices.t @@ -10,7 +10,7 @@ use t::lib::TestBuilder; use Koha::Database; use Koha::Number::Price; -my $schema = Koha::Database->new->schema; +my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; my $builder = t::lib::TestBuilder->new; @@ -22,7 +22,7 @@ subtest 'Tests from t' => sub { my ( @booksellers, @baskets, @biblios ); my @names = ( '0 0', '0 1', '1 0', '1 1' ); - foreach my $i ( 1..4 ) { + foreach my $i ( 1 .. 4 ) { push @booksellers, $builder->build_object( { class => 'Koha::Acquisition::Booksellers', @@ -33,39 +33,41 @@ subtest 'Tests from t' => sub { push @baskets, $builder->build_object( { class => 'Koha::Acquisition::Baskets', - value => - { basketname => $names[ $i - 1 ], booksellerid => $booksellers[$i-1]->id } + value => { basketname => $names[ $i - 1 ], booksellerid => $booksellers[ $i - 1 ]->id } } ); - push @biblios, $builder->build_sample_biblio; + push @biblios, $builder->build_sample_biblio; } my ( $basketno_0_0, $basketno_0_1, $basketno_1_0, $basketno_1_1 ) = map { $_->id } @baskets; my ( $invoiceid_0_0, $invoiceid_1_1 ); my $today; - for my $currency_format ( qw( US FR ) ) { + for my $currency_format (qw( US FR )) { t::lib::Mocks::mock_preference( 'CurrencyFormat', $currency_format ); - subtest 'Configuration 1: 0 0 (Vendor List prices do not include tax / Invoice prices do not include tax)' => sub { + subtest 'Configuration 1: 0 0 (Vendor List prices do not include tax / Invoice prices do not include tax)' => + sub { plan tests => 8; my $biblionumber_0_0 = $biblios[0]->id; - my $order_0_0 = Koha::Acquisition::Order->new({ - biblionumber => $biblionumber_0_0, - quantity => 2, - listprice => 82, - unitprice => 73.80, - quantityreceived => 2, - basketno => $basketno_0_0, - invoiceid => $invoiceid_0_0, - rrp => 82.00, - ecost => 73.80, - tax_rate_on_ordering => 0.0500, - tax_rate_on_receiving => 0.0500, - discount => 10, - datereceived => $today - }); + my $order_0_0 = Koha::Acquisition::Order->new( + { + biblionumber => $biblionumber_0_0, + quantity => 2, + listprice => 82, + unitprice => 73.80, + quantityreceived => 2, + basketno => $basketno_0_0, + invoiceid => $invoiceid_0_0, + rrp => 82.00, + ecost => 73.80, + tax_rate_on_ordering => 0.0500, + tax_rate_on_receiving => 0.0500, + discount => 10, + datereceived => $today + } + ); $order_0_0->populate_with_prices_for_ordering(); compare( @@ -135,27 +137,29 @@ subtest 'Tests from t' => sub { field => 'tax_value' } ); - }; + }; subtest 'Configuration 1: 1 1 (Vendor List prices do include tax / Invoice prices include tax)' => sub { plan tests => 11; my $biblionumber_1_1 = $biblios[3]->id; - my $order_1_1 = Koha::Acquisition::Order->new({ - biblionumber => $biblionumber_1_1, - quantity => 2, - listprice => 82, - unitprice => 73.80, - quantityreceived => 2, - basketno => $basketno_1_1, - invoiceid => $invoiceid_1_1, - rrp => 82.00, - ecost => 73.80, - tax_rate_on_ordering => 0.0500, - tax_rate_on_receiving => 0.0500, - discount => 10, - datereceived => $today - }); + my $order_1_1 = Koha::Acquisition::Order->new( + { + biblionumber => $biblionumber_1_1, + quantity => 2, + listprice => 82, + unitprice => 73.80, + quantityreceived => 2, + basketno => $basketno_1_1, + invoiceid => $invoiceid_1_1, + rrp => 82.00, + ecost => 73.80, + tax_rate_on_ordering => 0.0500, + tax_rate_on_receiving => 0.0500, + discount => 10, + datereceived => $today + } + ); $order_1_1->populate_with_prices_for_ordering(); @@ -230,21 +234,23 @@ subtest 'Tests from t' => sub { # When unitprice is 0.00 # Koha::Acquisition::Order::populate_with_prices_for_ordering() falls # back to using ecost_tax_included and ecost_tax_excluded - $order_1_1 = Koha::Acquisition::Order->new({ - biblionumber => $biblionumber_1_1, - quantity => 1, - listprice => 10, - unitprice => '0.00', - quantityreceived => 1, - basketno => $basketno_1_1, - invoiceid => $invoiceid_1_1, - rrp => 10.00, - ecost => 10.00, - tax_rate_on_ordering => 0.1500, - tax_rate_on_receiving => 0.1500, - discount => 0, - datereceived => $today - }); + $order_1_1 = Koha::Acquisition::Order->new( + { + biblionumber => $biblionumber_1_1, + quantity => 1, + listprice => 10, + unitprice => '0.00', + quantityreceived => 1, + basketno => $basketno_1_1, + invoiceid => $invoiceid_1_1, + rrp => 10.00, + ecost => 10.00, + tax_rate_on_ordering => 0.1500, + tax_rate_on_receiving => 0.1500, + discount => 0, + datereceived => $today + } + ); $order_1_1->populate_with_prices_for_ordering(); @@ -278,21 +284,23 @@ subtest 'Tests from t' => sub { plan tests => 9; my $biblionumber_1_0 = $biblios[2]->id; - my $order_1_0 = Koha::Acquisition::Order->new({ - biblionumber => $biblionumber_1_0, - quantity => 2, - listprice => 82, - unitprice => 0, - quantityreceived => 2, - basketno => $basketno_1_0, - invoiceid => $invoiceid_1_1, - rrp => 82.00, - ecost => 73.80, - tax_rate_on_ordering => 0.0500, - tax_rate_on_receiving => 0.0500, - discount => 10, - datereceived => $today - }); + my $order_1_0 = Koha::Acquisition::Order->new( + { + biblionumber => $biblionumber_1_0, + quantity => 2, + listprice => 82, + unitprice => 0, + quantityreceived => 2, + basketno => $basketno_1_0, + invoiceid => $invoiceid_1_1, + rrp => 82.00, + ecost => 73.80, + tax_rate_on_ordering => 0.0500, + tax_rate_on_receiving => 0.0500, + discount => 10, + datereceived => $today + } + ); $order_1_0->populate_with_prices_for_ordering(); @@ -328,6 +336,7 @@ subtest 'Tests from t' => sub { field => 'ecost_tax_excluded' } ); + # If we order with unitprice = 0, tax is calculated from the ecost # (note that in addorder.pl and addorderiso2709 the unitprice may/will be set to the ecost compare( @@ -383,21 +392,23 @@ subtest 'Tests from t' => sub { plan tests => 9; my $biblionumber_0_1 = $biblios[1]->id; - my $order_0_1 = Koha::Acquisition::Order->new({ - biblionumber => $biblionumber_0_1, - quantity => 2, - listprice => 82, - unitprice => 0, - quantityreceived => 2, - basketno => $basketno_0_1, - invoiceid => $invoiceid_1_1, - rrp => 82.00, - ecost => 73.80, - tax_rate_on_ordering => 0.0500, - tax_rate_on_receiving => 0.0500, - discount => 10, - datereceived => $today - }); + my $order_0_1 = Koha::Acquisition::Order->new( + { + biblionumber => $biblionumber_0_1, + quantity => 2, + listprice => 82, + unitprice => 0, + quantityreceived => 2, + basketno => $basketno_0_1, + invoiceid => $invoiceid_1_1, + rrp => 82.00, + ecost => 73.80, + tax_rate_on_ordering => 0.0500, + tax_rate_on_receiving => 0.0500, + discount => 10, + datereceived => $today + } + ); $order_0_1->populate_with_prices_for_ordering(); @@ -433,6 +444,7 @@ subtest 'Tests from t' => sub { field => 'ecost_tax_excluded' } ); + # If we order with unitprice = 0, tax is calculated from the ecost # (note that in addorder.pl and addorderiso2709 the unitprice may/will be set to the ecost compare( diff --git a/t/db_dependent/Record.t b/t/db_dependent/Record.t index 9c9b237c8e..43d4c2b204 100755 --- a/t/db_dependent/Record.t +++ b/t/db_dependent/Record.t @@ -10,7 +10,7 @@ use C4::Context; use Koha::Database; BEGIN { - use_ok('C4::Record', qw( marc2marc marc2marcxml marcxml2marc marc2dcxml marc2modsxml marc2bibtex marc2cites )); + use_ok( 'C4::Record', qw( marc2marc marc2marcxml marcxml2marc marc2dcxml marc2modsxml marc2bibtex marc2cites ) ); } my $schema = Koha::Database->new->schema; @@ -18,12 +18,12 @@ $schema->storage->txn_begin; t::lib::Mocks::mock_preference( "BibtexExportAdditionalFields", q{} ); -my @marcarray=marc2marc; -is ($marcarray[0],"Feature not yet implemented\n","error works"); +my @marcarray = marc2marc; +is( $marcarray[0], "Feature not yet implemented\n", "error works" ); -my $marc=MARC::Record->new; -my $marcxml=marc2marcxml($marc); -my $testxml=qq(<?xml version="1.0" encoding="UTF-8"?> +my $marc = MARC::Record->new; +my $marcxml = marc2marcxml($marc); +my $testxml = qq(<?xml version="1.0" encoding="UTF-8"?> <record xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.loc.gov/MARC21/slim http://www.loc.gov/standards/marcxml/schema/MARC21slim.xsd" @@ -32,11 +32,11 @@ my $testxml=qq(<?xml version="1.0" encoding="UTF-8"?> <leader> a </leader> </record> ); -is ($marcxml, $testxml, "testing marc2xml"); +is( $marcxml, $testxml, "testing marc2xml" ); -my $rawmarc=$marc->as_usmarc; -$marcxml=marc2marcxml($rawmarc); -$testxml=qq(<?xml version="1.0" encoding="UTF-8"?> +my $rawmarc = $marc->as_usmarc; +$marcxml = marc2marcxml($rawmarc); +$testxml = qq(<?xml version="1.0" encoding="UTF-8"?> <record xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.loc.gov/MARC21/slim http://www.loc.gov/standards/marcxml/schema/MARC21slim.xsd" @@ -45,52 +45,52 @@ $testxml=qq(<?xml version="1.0" encoding="UTF-8"?> <leader>00026 a2200025 4500</leader> </record> ); -is ($marcxml, $testxml, "testing marc2xml"); +is( $marcxml, $testxml, "testing marc2xml" ); -my $marcconvert=marcxml2marc($marcxml); -is ($marcconvert->as_xml,$marc->as_xml, "testing xml2marc"); +my $marcconvert = marcxml2marc($marcxml); +is( $marcconvert->as_xml, $marc->as_xml, "testing xml2marc" ); -my $marcsrwdc=marc2dcxml( $marc, undef, undef, "srwdc" ); -my $test2xml=qq(<?xml version="1.0" encoding="UTF-8"?> +my $marcsrwdc = marc2dcxml( $marc, undef, undef, "srwdc" ); +my $test2xml = qq(<?xml version="1.0" encoding="UTF-8"?> <srw_dc:dc xmlns:srw_dc="info:srw/schema/1/dc-schema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="info:srw/schema/1/dc-schema http://www.loc.gov/z3950/agency/zing/srw/dc-schema.xsd"> <type xmlns="http://purl.org/dc/elements/1.1/"/> </srw_dc:dc> ); -is ($marcsrwdc, $test2xml, "testing SRWDC Metadata"); +is( $marcsrwdc, $test2xml, "testing SRWDC Metadata" ); -my $marcoaidc=marc2dcxml( $marc, undef, undef, "oaidc" ); -my $test3xml=qq(<?xml version="1.0" encoding="UTF-8"?> +my $marcoaidc = marc2dcxml( $marc, undef, undef, "oaidc" ); +my $test3xml = qq(<?xml version="1.0" encoding="UTF-8"?> <oai_dc:dc xmlns:oai_dc="http://www.openarchives.org/OAI/2.0/oai_dc/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.openarchives.org/OAI/2.0/oai_dc/ http://www.openarchives.org/OAI/2.0/oai_dc.xsd"> <dc:type/> <dc:language/> </oai_dc:dc> ); -is ($marcoaidc, $test3xml, "testing OAIDC Metadata"); +is( $marcoaidc, $test3xml, "testing OAIDC Metadata" ); -my $marcrdfdc=marc2dcxml( $marc, undef, undef, "rdfdc" ); -my $test4Axml=qq(<?xml version="1.0" encoding="UTF-8"?> +my $marcrdfdc = marc2dcxml( $marc, undef, undef, "rdfdc" ); +my $test4Axml = qq(<?xml version="1.0" encoding="UTF-8"?> <rdf:Description xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/"> <dc:type/> <dc:language/> </rdf:Description> ); -is ($marcrdfdc, $test4Axml, "testing RDFDC Metadata"); +is( $marcrdfdc, $test4Axml, "testing RDFDC Metadata" ); -my $marcdc=marc2dcxml( $marc, undef, undef, "dc" ); -my $test4Bxml=qq(<?xml version="1.0" encoding="UTF-8"?> +my $marcdc = marc2dcxml( $marc, undef, undef, "dc" ); +my $test4Bxml = qq(<?xml version="1.0" encoding="UTF-8"?> <rdf:Description xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/"> <dc:type/> <dc:language/> </rdf:Description> ); -is ($marcrdfdc, $test4Bxml, "testing DC Metadata"); +is( $marcrdfdc, $test4Bxml, "testing DC Metadata" ); -my $mods=marc2modsxml($marc); -my $test5xml=qq(<?xml version="1.0" encoding="UTF-8"?> +my $mods = marc2modsxml($marc); +my $test5xml = qq(<?xml version="1.0" encoding="UTF-8"?> <mods xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.loc.gov/mods/v3" version="3.1" xsi:schemaLocation="http://www.loc.gov/mods/v3 http://www.loc.gov/standards/mods/v3/mods-3-1.xsd"> <typeOfResource/> <originInfo> @@ -100,22 +100,18 @@ my $test5xml=qq(<?xml version="1.0" encoding="UTF-8"?> </mods> ); -is ($mods, $test5xml, "testing marc2modsxml"); +is( $mods, $test5xml, "testing marc2modsxml" ); -$marc->append_fields(MARC::Field->new( - '100', ' ', ' ', a => 'Rowling, J.K.' -)); -my $field = MARC::Field->new('245','','','a' => "Harry potter"); +$marc->append_fields( MARC::Field->new( '100', ' ', ' ', a => 'Rowling, J.K.' ) ); +my $field = MARC::Field->new( '245', '', '', 'a' => "Harry potter" ); $marc->append_fields($field); -$marc->append_fields(MARC::Field->new( - '260', ' ', ' ', b => 'Scholastic', c => '2001' -)); +$marc->append_fields( MARC::Field->new( '260', ' ', ' ', b => 'Scholastic', c => '2001' ) ); #my $endnote=marc2endnote($marc->as_usmarc); #print $endnote; -my $bibtex=marc2bibtex($marc, 'testID'); -my $test6xml=qq(\@book{testID, +my $bibtex = marc2bibtex( $marc, 'testID' ); +my $test6xml = qq(\@book{testID, author = {Rowling, J.K.}, title = {Harry potter}, publisher = {Scholastic}, @@ -123,7 +119,7 @@ my $test6xml=qq(\@book{testID, } ); -is ($bibtex, $test6xml, "testing bibtex"); +is( $bibtex, $test6xml, "testing bibtex" ); t::lib::Mocks::mock_preference( "BibtexExportAdditionalFields", "'\@': 260\$b\ntest: 260\$b" ); $bibtex = marc2bibtex( $marc, 'testID' ); @@ -138,10 +134,8 @@ my $test7xml = qq(\@Scholastic{testID, is( $bibtex, $test7xml, "testing bibtex" ); t::lib::Mocks::mock_preference( "BibtexExportAdditionalFields", q{} ); -$marc->append_fields(MARC::Field->new( - '264', '3', '1', b => 'Reprints', c => '2011' -)); -$bibtex = marc2bibtex($marc, 'testID'); +$marc->append_fields( MARC::Field->new( '264', '3', '1', b => 'Reprints', c => '2011' ) ); +$bibtex = marc2bibtex( $marc, 'testID' ); my $rdabibtex = qq(\@book{testID, author = {Rowling, J.K.}, title = {Harry potter}, @@ -149,11 +143,10 @@ my $rdabibtex = qq(\@book{testID, year = {2011} } ); -is ($bibtex, $rdabibtex, "testing bibtex with RDA 264 field"); - -my @entity=C4::Record::_entity_encode("Björn"); -is ($entity[0], "Björn", "Html umlauts"); +is( $bibtex, $rdabibtex, "testing bibtex with RDA 264 field" ); +my @entity = C4::Record::_entity_encode("Björn"); +is( $entity[0], "Björn", "Html umlauts" ); $marc->field('260')->add_subfields( a => 'Hogwarts' ); my $cites = marc2cites($marc); diff --git a/t/db_dependent/Record/Record.t b/t/db_dependent/Record/Record.t index 495f8e05b1..53122066a3 100755 --- a/t/db_dependent/Record/Record.t +++ b/t/db_dependent/Record/Record.t @@ -25,7 +25,8 @@ use warnings; use constant WHEREAMI => 't/db_dependent/Record/testrecords'; # specify the number of tests -use Test::More tests => 21; #FIXME Commented out two failing tests +use Test::More tests => 21; #FIXME Commented out two failing tests + #use C4::Context; use C4::Record qw( marc2marc marc2marcxml marc2dcxml changeEncoding ); @@ -42,93 +43,124 @@ $ ./Record_test.pl ## FIXME: Preliminarily grab the modules dir so we can run this in context -ok (1, 'module compiled'); +ok( 1, 'module compiled' ); # open some files for testing -open my $MARC21MARC8, '<', WHEREAMI."/marc21_marc8.dat" or die $!; -my $marc21_marc8; # = scalar (MARC21MARC8); +open my $MARC21MARC8, '<', WHEREAMI . "/marc21_marc8.dat" or die $!; +my $marc21_marc8; # = scalar (MARC21MARC8); foreach my $line (<$MARC21MARC8>) { $marc21_marc8 .= $line; } $marc21_marc8 =~ s/\n$//; close $MARC21MARC8; -open (my $MARC21UTF8, '<:encoding(UTF-8)', WHEREAMI."/marc21_utf8.dat") or die $!; +open( my $MARC21UTF8, '<:encoding(UTF-8)', WHEREAMI . "/marc21_utf8.dat" ) or die $!; my $marc21_utf8; foreach my $line (<$MARC21UTF8>) { - $marc21_utf8 .= $line; + $marc21_utf8 .= $line; } $marc21_utf8 =~ s/\n$//; close $MARC21UTF8; -open(my $MARC21MARC8COMBCHARS, '<', WHEREAMI."/marc21_marc8_combining_chars.dat") or die $!; +open( my $MARC21MARC8COMBCHARS, '<', WHEREAMI . "/marc21_marc8_combining_chars.dat" ) or die $!; my $marc21_marc8_combining_chars; -foreach my $line(<$MARC21MARC8COMBCHARS>) { - $marc21_marc8_combining_chars.=$line; +foreach my $line (<$MARC21MARC8COMBCHARS>) { + $marc21_marc8_combining_chars .= $line; } -$marc21_marc8_combining_chars =~ s/\n$//; #FIXME: why is a newline ending up here? +$marc21_marc8_combining_chars =~ s/\n$//; #FIXME: why is a newline ending up here? close $MARC21MARC8COMBCHARS; -open (my $MARC21UTF8COMBCHARS, '<:encoding(UTF-8)', WHEREAMI."/marc21_utf8_combining_chars.dat") or die $!; +open( my $MARC21UTF8COMBCHARS, '<:encoding(UTF-8)', WHEREAMI . "/marc21_utf8_combining_chars.dat" ) or die $!; my $marc21_utf8_combining_chars; -foreach my $line(<$MARC21UTF8COMBCHARS>) { - $marc21_utf8_combining_chars.=$line; +foreach my $line (<$MARC21UTF8COMBCHARS>) { + $marc21_utf8_combining_chars .= $line; } close $MARC21UTF8COMBCHARS; -open (my $MARCXMLUTF8, '<:encoding(UTF-8)', WHEREAMI."/marcxml_utf8.xml") or die $!; +open( my $MARCXMLUTF8, '<:encoding(UTF-8)', WHEREAMI . "/marcxml_utf8.xml" ) or die $!; my $marcxml_utf8; foreach my $line (<$MARCXMLUTF8>) { - $marcxml_utf8 .= $line; + $marcxml_utf8 .= $line; } close $MARCXMLUTF8; $marcxml_utf8 =~ s/\n//g; ## The Tests: -my $error; my $marc; my $marcxml; # some scalars to store values +my $error; +my $marc; +my $marcxml; # some scalars to store values ## MARC to MARCXML print "\n1. Checking conversion of simple ISO-2709 (MARC21) records to MARCXML\n"; -ok (($error,$marcxml) = marc2marcxml($marc21_marc8,'UTF-8','MARC21'), 'marc2marcxml - from MARC-8 to UTF-8 (MARC21)'); -ok (!$error, 'no errors in conversion'); +ok( + ( $error, $marcxml ) = marc2marcxml( $marc21_marc8, 'UTF-8', 'MARC21' ), + 'marc2marcxml - from MARC-8 to UTF-8 (MARC21)' +); +ok( !$error, 'no errors in conversion' ); + #FIXME This test fails # $marcxml =~ s/\n//g; # $marcxml =~ s/v\/ s/v\/s/g; # FIXME: bug in new_from_xml_record!! #is ($marcxml,$marcxml_utf8, 'record matches antitype'); -ok (($error,$marcxml) = marc2marcxml($marc21_utf8,'UTF-8','MARC21'), 'marc2marcxml - from UTF-8 to UTF-8 (MARC21)'); -ok (!$error, 'no errors in conversion'); +ok( + ( $error, $marcxml ) = marc2marcxml( $marc21_utf8, 'UTF-8', 'MARC21' ), + 'marc2marcxml - from UTF-8 to UTF-8 (MARC21)' +); +ok( !$error, 'no errors in conversion' ); + #FIXME This test fails # $marcxml =~ s/\n//g; # $marcxml =~ s/v\/ s/v\/s/g; #is ($marcxml,$marcxml_utf8, 'record matches antitype'); print "\n2. checking binary MARC21 records with combining characters to MARCXML\n"; -ok (($error,$marcxml) = marc2marcxml($marc21_marc8_combining_chars,'MARC-8','MARC21'), 'marc2marcxml - from MARC-8 to MARC-8 with combining characters(MARC21)'); -ok (!$error, 'no errors in conversion'); +ok( + ( $error, $marcxml ) = marc2marcxml( $marc21_marc8_combining_chars, 'MARC-8', 'MARC21' ), + 'marc2marcxml - from MARC-8 to MARC-8 with combining characters(MARC21)' +); +ok( !$error, 'no errors in conversion' ); -ok (($error,$marcxml) = marc2marcxml($marc21_marc8_combining_chars,'UTF-8','MARC21'), 'marc2marcxml - from MARC-8 to UTF-8 with combining characters (MARC21)'); -ok (!$error, 'no errors in conversion'); +ok( + ( $error, $marcxml ) = marc2marcxml( $marc21_marc8_combining_chars, 'UTF-8', 'MARC21' ), + 'marc2marcxml - from MARC-8 to UTF-8 with combining characters (MARC21)' +); +ok( !$error, 'no errors in conversion' ); -ok (($error,$marcxml) = marc2marcxml($marc21_utf8_combining_chars,'UTF-8','MARC21'), 'marc2marcxml - from UTF-8 to UTF-8 with combining characters (MARC21)'); -ok (!$error, 'no errors in conversion'); +ok( + ( $error, $marcxml ) = marc2marcxml( $marc21_utf8_combining_chars, 'UTF-8', 'MARC21' ), + 'marc2marcxml - from UTF-8 to UTF-8 with combining characters (MARC21)' +); +ok( !$error, 'no errors in conversion' ); -ok (eval{marc2dcxml($marc21_utf8, undef, undef, 'oaidc')}, 'marc2dcxml - from ISO-2709 to Dublin Core'); +ok( eval { marc2dcxml( $marc21_utf8, undef, undef, 'oaidc' ) }, 'marc2dcxml - from ISO-2709 to Dublin Core' ); $error = $@; -ok (!$error, 'no errors in conversion to DublinCore'); +ok( !$error, 'no errors in conversion to DublinCore' ); print "\n3. checking ability to alter encoding\n"; -ok (($error,$marc) = changeEncoding($marc21_marc8,'MARC','MARC21','UTF-8'), 'changeEncoding - MARC21 from MARC-8 to UTF-8'); -ok (!$error, 'no errors in conversion'); +ok( + ( $error, $marc ) = changeEncoding( $marc21_marc8, 'MARC', 'MARC21', 'UTF-8' ), + 'changeEncoding - MARC21 from MARC-8 to UTF-8' +); +ok( !$error, 'no errors in conversion' ); -ok (($error,$marc) = changeEncoding($marc21_utf8,'MARC','MARC21','MARC-8'), 'changeEncoding - MARC21 from UTF-8 to MARC-8'); -ok (!$error, 'no errors in conversion'); +ok( + ( $error, $marc ) = changeEncoding( $marc21_utf8, 'MARC', 'MARC21', 'MARC-8' ), + 'changeEncoding - MARC21 from UTF-8 to MARC-8' +); +ok( !$error, 'no errors in conversion' ); -ok (($error,$marc) = changeEncoding($marc21_marc8,'MARC','MARC21','MARC-8'), 'changeEncoding - MARC21 from MARC-8 to MARC-8'); -ok (!$error, 'no errors in conversion'); +ok( + ( $error, $marc ) = changeEncoding( $marc21_marc8, 'MARC', 'MARC21', 'MARC-8' ), + 'changeEncoding - MARC21 from MARC-8 to MARC-8' +); +ok( !$error, 'no errors in conversion' ); -ok (($error,$marc) = changeEncoding($marc21_utf8,'MARC','MARC21','UTF-8'), 'changeEncoding - MARC21 from UTF-8 to UTF-8'); -ok (!$error, 'no errors in conversion'); +ok( + ( $error, $marc ) = changeEncoding( $marc21_utf8, 'MARC', 'MARC21', 'UTF-8' ), + 'changeEncoding - MARC21 from UTF-8 to UTF-8' +); +ok( !$error, 'no errors in conversion' ); __END__ diff --git a/t/db_dependent/Record/marcrecord2csv.t b/t/db_dependent/Record/marcrecord2csv.t index bf3df2101f..1dd1000e39 100755 --- a/t/db_dependent/Record/marcrecord2csv.t +++ b/t/db_dependent/Record/marcrecord2csv.t @@ -21,99 +21,145 @@ my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; my $dbh = C4::Context->dbh; -my $builder = t::lib::TestBuilder->new; +my $builder = t::lib::TestBuilder->new; my $module_biblio = Test::MockModule->new('C4::Biblio'); -my $record = new_record(); +my $record = new_record(); my $frameworkcode = q||; my ( $biblionumber, $biblioitemnumber ) = AddBiblio( $record, $frameworkcode ); -my $csv_content = q(Title=245$a|Author=245$c|Subject=650$a); -my $csv_profile_id_1 = insert_csv_profile({ csv_content => $csv_content }); -my $csv = Text::CSV::Encoded->new( { formula => 'empty' } ); +my $csv_content = q(Title=245$a|Author=245$c|Subject=650$a); +my $csv_profile_id_1 = insert_csv_profile( { csv_content => $csv_content } ); +my $csv = Text::CSV::Encoded->new( { formula => 'empty' } ); # Test bad biblionumber case my $csv_output = C4::Record::marcrecord2csv( -1, $csv_profile_id_1, 1, $csv ); -ok(! defined $csv_output, 'Bad biblionumber gives undef as expected.'); +ok( !defined $csv_output, 'Bad biblionumber gives undef as expected.' ); $csv_output = C4::Record::marcrecord2csv( $biblionumber, $csv_profile_id_1, 1, $csv ); -is( $csv_output, q[Title|Author|Subject +is( + $csv_output, q[Title|Author|Subject "The art of computer programming,The art of another title"|"Donald E. Knuth.,Donald E. Knuth. II"|"Computer programming.,Computer algorithms." -], q|normal way: display headers and content| ); +], q|normal way: display headers and content| +); $csv_output = C4::Record::marcrecord2csv( $biblionumber, $csv_profile_id_1, 0, $csv ); -is( $csv_output, q["The art of computer programming,The art of another title"|"Donald E. Knuth.,Donald E. Knuth. II"|"Computer programming.,Computer algorithms." -], q|normal way: don't display headers| ); +is( + $csv_output, + q["The art of computer programming,The art of another title"|"Donald E. Knuth.,Donald E. Knuth. II"|"Computer programming.,Computer algorithms." +], q|normal way: don't display headers| +); $csv_content = q(245|650); -my $csv_profile_id_2 = insert_csv_profile({ csv_content => $csv_content }); +my $csv_profile_id_2 = insert_csv_profile( { csv_content => $csv_content } ); $csv_output = C4::Record::marcrecord2csv( $biblionumber, $csv_profile_id_2, 1, $csv ); -is( $csv_output, q["TITLE STATEMENT"|"SUBJECT ADDED ENTRY--TOPICAL TERM" +is( + $csv_output, q["TITLE STATEMENT"|"SUBJECT ADDED ENTRY--TOPICAL TERM" "The art of computer programming,Donald E. Knuth.,0;The art of another title,Donald E. Knuth. II,1"|"Computer programming.,462;Computer algorithms.,499" -], q|normal way: headers retrieved from the DB| ); +], q|normal way: headers retrieved from the DB| +); $csv_output = C4::Record::marcrecord2csv( $biblionumber, $csv_profile_id_2, 0, $csv ); -is( $csv_output, q["The art of computer programming,Donald E. Knuth.,0;The art of another title,Donald E. Knuth. II,1"|"Computer programming.,462;Computer algorithms.,499" -], q|normal way: headers are not display if not needed| ); +is( + $csv_output, + q["The art of computer programming,Donald E. Knuth.,0;The art of another title,Donald E. Knuth. II,1"|"Computer programming.,462;Computer algorithms.,499" +], q|normal way: headers are not display if not needed| +); -$csv_content = q(Title and author=[% FOREACH field IN fields.245 %][% field.a.0 %] [% field.c.0 %][% END %]|Subject=650$a); -my $csv_profile_id_3 = insert_csv_profile({ csv_content => $csv_content }); +$csv_content = + q(Title and author=[% FOREACH field IN fields.245 %][% field.a.0 %] [% field.c.0 %][% END %]|Subject=650$a); +my $csv_profile_id_3 = insert_csv_profile( { csv_content => $csv_content } ); $csv_output = C4::Record::marcrecord2csv( $biblionumber, $csv_profile_id_3, 1, $csv ); -is( $csv_output, q["Title and author"|Subject +is( + $csv_output, q["Title and author"|Subject "The art of computer programming Donald E. Knuth.The art of another title Donald E. Knuth. II"|"Computer programming.,Computer algorithms." -], q|TT way: display all 245$a and 245$c| ); +], q|TT way: display all 245$a and 245$c| +); $csv_content = q(Subject=[% FOREACH field IN fields.650 %][% IF field.indicator.2 %][% field.a.0 %][% END %][% END %]); -my $csv_profile_id_4 = insert_csv_profile({ csv_content => $csv_content }); +my $csv_profile_id_4 = insert_csv_profile( { csv_content => $csv_content } ); $csv_output = C4::Record::marcrecord2csv( $biblionumber, $csv_profile_id_4, 1, $csv ); -is( $csv_output, q[Subject +is( + $csv_output, q[Subject "Computer programming." -], q|TT way: display 650$a if indicator 2 for 650 is set| ); +], q|TT way: display 650$a if indicator 2 for 650 is set| +); $csv_content = q|Language=[% fields.008.0.substr( 28, 3 ) %]|; -my $csv_profile_id_5 = insert_csv_profile({ csv_content => $csv_content }); +my $csv_profile_id_5 = insert_csv_profile( { csv_content => $csv_content } ); $csv_output = C4::Record::marcrecord2csv( $biblionumber, $csv_profile_id_5, 1, $csv ); -is( $csv_output, q[Language +is( + $csv_output, q[Language eng -], q|TT way: export language from the control field 008| ); +], q|TT way: export language from the control field 008| +); $csv_content = q|Title=[% IF fields.100.0.indicator.1 %][% fields.245.0.a.0 %][% END %]|; -my $csv_profile_id_6 = insert_csv_profile({ csv_content => $csv_content }); +my $csv_profile_id_6 = insert_csv_profile( { csv_content => $csv_content } ); $csv_output = C4::Record::marcrecord2csv( $biblionumber, $csv_profile_id_6, 1, $csv ); -is( $csv_output, q[Title +is( + $csv_output, q[Title "The art of computer programming" -], q|TT way: display first subfield a for first field 245 if indicator 1 for field 100 is set| ); +], q|TT way: display first subfield a for first field 245 if indicator 1 for field 100 is set| +); $csv_content = q|Title=[% IF fields.100.0.indicator.1 == 1 %][% fields.245.0.a.0 %][% END %]|; -my $csv_profile_id_7 = insert_csv_profile({ csv_content => $csv_content }); +my $csv_profile_id_7 = insert_csv_profile( { csv_content => $csv_content } ); $csv_output = C4::Record::marcrecord2csv( $biblionumber, $csv_profile_id_7, 1, $csv ); -is( $csv_output, q[Title +is( + $csv_output, q[Title "The art of computer programming" -], q|TT way: display first subfield a for first field 245 if indicator 1 == 1 for field 100 is set| ); +], q|TT way: display first subfield a for first field 245 if indicator 1 == 1 for field 100 is set| +); - -my $authorised_value_1 = - $builder->build( { source => 'AuthorisedValue', value => { category => 'MY_AV_1', authorised_value => 1, lib => 'This is an AV', lib_opac => 'This is an AV (opac)' } } ); +my $authorised_value_1 = $builder->build( + { + source => 'AuthorisedValue', + value => { + category => 'MY_AV_1', authorised_value => 1, lib => 'This is an AV', lib_opac => 'This is an AV (opac)' + } + } +); my $authorised_value_2 = $builder->build( - { source => 'AuthorisedValue', value => { category => 'MY_AV_2', authorised_value => 2, lib => 'This is another AV', lib_opac => 'This is another AV (opac)' } } ); + { + source => 'AuthorisedValue', + value => { + category => 'MY_AV_2', authorised_value => 2, lib => 'This is another AV', + lib_opac => 'This is another AV (opac)' + } + } +); $dbh->do(q|DELETE FROM marc_subfield_structure WHERE tagfield='998' and ( tagsubfield='8' or tagsubfield='9')|); $builder->build( - { source => 'MarcSubfieldStructure', value => { authorised_value => $authorised_value_1->{category}, tagfield => 998, tagsubfield => '8', frameworkcode => $frameworkcode } } + { + source => 'MarcSubfieldStructure', + value => { + authorised_value => $authorised_value_1->{category}, tagfield => 998, tagsubfield => '8', + frameworkcode => $frameworkcode + } + } ); $builder->build( - { source => 'MarcSubfieldStructure', value => { authorised_value => $authorised_value_2->{category}, tagfield => 998, tagsubfield => '9', frameworkcode => $frameworkcode } } + { + source => 'MarcSubfieldStructure', + value => { + authorised_value => $authorised_value_2->{category}, tagfield => 998, tagsubfield => '9', + frameworkcode => $frameworkcode + } + } ); $csv_content = q(Title=245$a|AV1=998$8|AV2=998$9); my $csv_profile_id_8 = insert_csv_profile( { csv_content => $csv_content } ); $csv_output = C4::Record::marcrecord2csv( $biblionumber, $csv_profile_id_8, 1, $csv ); -is( $csv_output, q[Title|AV1|AV2 +is( + $csv_output, q[Title|AV1|AV2 "The art of computer programming,The art of another title"|"This is an AV"|"This is another AV" ], q|TT way: display first subfield a for first field 245 if indicator 1 == 1 for field 100 is set| ); @@ -121,7 +167,8 @@ is( $csv_output, q[Title|AV1|AV2 $csv_content = q(Title=245$a|AVs=998); my $csv_profile_id_9 = insert_csv_profile( { csv_content => $csv_content } ); $csv_output = C4::Record::marcrecord2csv( $biblionumber, $csv_profile_id_9, 1, $csv ); -is( $csv_output, q[Title|AVs +is( + $csv_output, q[Title|AVs "The art of computer programming,The art of another title"|"This is an AV,This is another AV" ], q|TT way: display first subfield a for first field 245 if indicator 1 == 1 for field 100 is set| ); @@ -146,7 +193,7 @@ subtest 'Test for subfields 0' => sub { # We add two item to two record to test fieldtag 952 and subfieldtag 9520 my ( undef, undef, $itemnumber2 ) = AddItemFromMarc( $record2, $biblionumber ); - my ( undef, undef, $itemnumber ) = AddItemFromMarc( $record, $biblionumber ); + my ( undef, undef, $itemnumber ) = AddItemFromMarc( $record, $biblionumber ); $csv_content = q(Titre=245a|Nom de personne=100a|Statut « Élagué »=9520); my $csv_profile_id_10 = insert_csv_profile( { csv_content => $csv_content } ); $csv_output = C4::Record::marcrecord2csv( $biblionumber, $csv_profile_id_10, 1, $csv ); @@ -161,11 +208,12 @@ subtest 'Test for subfields 0' => sub { }; sub insert_csv_profile { - my ( $params ) = @_; + my ($params) = @_; my $csv_content = $params->{csv_content}; - $dbh->do(q| + $dbh->do( + q| INSERT INTO export_format(profile, description, content, csv_separator, field_separator, subfield_separator, encoding, type) VALUES (?, ?, ?, ?, ?, ?, ?, ?) - |, {}, ("TEST_PROFILE4", "my desc", $csv_content, '|', ';', ',', 'utf8', 'marc') + |, {}, ( "TEST_PROFILE4", "my desc", $csv_content, '|', ';', ',', 'utf8', 'marc' ) ); return $dbh->last_insert_id( undef, undef, 'export_format', undef ); } @@ -174,9 +222,7 @@ sub new_record { my $record = MARC::Record->new; $record->leader('03174nam a2200445 a 4500'); my @fields = ( - MARC::Field->new( - '008', "140211b xxu||||| |||| 00| 0 eng d" - ), + MARC::Field->new( '008', "140211b xxu||||| |||| 00| 0 eng d" ), MARC::Field->new( 100, '1', ' ', a => 'Knuth, Donald Ervin', diff --git a/t/db_dependent/RecordProcessor_EmbedSeeFromHeadings.t b/t/db_dependent/RecordProcessor_EmbedSeeFromHeadings.t index 9d7b4efc32..37a62ea6db 100755 --- a/t/db_dependent/RecordProcessor_EmbedSeeFromHeadings.t +++ b/t/db_dependent/RecordProcessor_EmbedSeeFromHeadings.t @@ -28,42 +28,44 @@ use Test::MockModule; use Test::MockObject; BEGIN { - use_ok('Koha::RecordProcessor'); + use_ok('Koha::RecordProcessor'); } my $module = Test::MockModule->new('MARC::Record'); -$module->mock('new_from_xml', sub { - my $record = MARC::Record->new; +$module->mock( + 'new_from_xml', + sub { + my $record = MARC::Record->new; - $record->add_fields( - [ '001', '1234' ], - [ '150', ' ', ' ', a => 'Cooking' ], - [ '450', ' ', ' ', a => 'Cookery' ], + $record->add_fields( + [ '001', '1234' ], + [ '150', ' ', ' ', a => 'Cooking' ], + [ '450', ' ', ' ', a => 'Cookery' ], ); - return $record; -}); + return $record; + } +); my $bib = MARC::Record->new; $bib->add_fields( [ '245', '0', '4', a => 'The Ifrane cookbook' ], [ '650', ' ', ' ', a => 'Cooking', 9 => '1234' ] - ); +); my $resultbib = MARC::Record->new; $resultbib->add_fields( [ '245', '0', '4', a => 'The Ifrane cookbook' ], [ '650', ' ', ' ', a => 'Cooking', 9 => '1234' ], [ '650', 'z', ' ', a => 'Cookery' ] - ); +); -my $processor = Koha::RecordProcessor->new( { filters => ( 'EmbedSeeFromHeadings' ) } ); -is(ref($processor), 'Koha::RecordProcessor', 'Created record processor'); +my $processor = Koha::RecordProcessor->new( { filters => ('EmbedSeeFromHeadings') } ); +is( ref($processor), 'Koha::RecordProcessor', 'Created record processor' ); my $result = $processor->process($bib); -is_deeply($result, $resultbib, 'Inserted see-from heading to record'); - +is_deeply( $result, $resultbib, 'Inserted see-from heading to record' ); subtest "EmbedSeeFromHeadings should skip holdings fields" => sub { @@ -81,34 +83,34 @@ subtest "EmbedSeeFromHeadings should skip holdings fields" => sub { [ '952', ' ', ' ', a => 'Cooking', 9 => '1234' ] ); - my $koha_authority = Test::MockModule->new('Koha::MetadataRecord::Authority'); - $koha_authority->mock( 'get_from_authid', sub { + $koha_authority->mock( + 'get_from_authid', + sub { - my $auth_record = MARC::Record->new; + my $auth_record = MARC::Record->new; - $auth_record->add_fields( - [ '001', '1234' ], - [ '150', ' ', ' ', a => 'Cooking' ], - [ '450', ' ', ' ', a => 'Cookery' ], - ); + $auth_record->add_fields( + [ '001', '1234' ], + [ '150', ' ', ' ', a => 'Cooking' ], + [ '450', ' ', ' ', a => 'Cookery' ], + ); - my $authority_object = Test::MockObject->new(); - $authority_object->mock( 'authid', sub { return '1234'; }); - $authority_object->mock( 'authtype', sub { return 'TOPIC_TERM'; }); - $authority_object->mock( 'schema', sub { return 'marc21'; }); - $authority_object->mock( 'record', sub { return $auth_record; }); + my $authority_object = Test::MockObject->new(); + $authority_object->mock( 'authid', sub { return '1234'; } ); + $authority_object->mock( 'authtype', sub { return 'TOPIC_TERM'; } ); + $authority_object->mock( 'schema', sub { return 'marc21'; } ); + $authority_object->mock( 'record', sub { return $auth_record; } ); - return $authority_object; - }); + return $authority_object; + } + ); - my $processor = Koha::RecordProcessor->new({ - filters => ( 'EmbedSeeFromHeadings' ) - }); + my $processor = Koha::RecordProcessor->new( { filters => ('EmbedSeeFromHeadings') } ); my $result = $processor->process($biblio_record); - is_deeply($result, $record_copy, 'Holdings fields not processed to introduce See-from heading'); + is_deeply( $result, $record_copy, 'Holdings fields not processed to introduce See-from heading' ); }; done_testing(); diff --git a/t/db_dependent/Reports.t b/t/db_dependent/Reports.t index 9cf56abef3..421f12f129 100755 --- a/t/db_dependent/Reports.t +++ b/t/db_dependent/Reports.t @@ -1,6 +1,6 @@ #!/usr/bin/perl # -# This Koha test module is a stub! +# This Koha test module is a stub! # Add more tests here!!! use strict; @@ -9,8 +9,8 @@ use warnings; use Test::More tests => 2; BEGIN { - use_ok('C4::Reports', qw( GetDelimiterChoices )); + use_ok( 'C4::Reports', qw( GetDelimiterChoices ) ); } - -ok(GetDelimiterChoices(),"Testing getting delimeter choices"); #Not testing the value of the output just that it returns something. +ok( GetDelimiterChoices(), "Testing getting delimeter choices" ) + ; #Not testing the value of the output just that it returns something. diff --git a/t/db_dependent/Reports/Guided.t b/t/db_dependent/Reports/Guided.t index d139940588..1e4e34d93a 100755 --- a/t/db_dependent/Reports/Guided.t +++ b/t/db_dependent/Reports/Guided.t @@ -31,7 +31,10 @@ use Koha::Items; use Koha::Reports; use Koha::Notice::Messages; -use_ok('C4::Reports::Guided', qw( execute_query save_report delete_report strip_limit GetReservedAuthorisedValues IsAuthorisedValueValid GetParametersFromSQL ValidateSQLParameters get_saved_reports update_sql get_report_areas convert_sql EmailReport nb_rows )); +use_ok( + 'C4::Reports::Guided', + qw( execute_query save_report delete_report strip_limit GetReservedAuthorisedValues IsAuthorisedValueValid GetParametersFromSQL ValidateSQLParameters get_saved_reports update_sql get_report_areas convert_sql EmailReport nb_rows ) +); can_ok( 'C4::Reports::Guided', qw(save_report delete_report execute_query) @@ -42,6 +45,7 @@ $schema->storage->txn_begin; my $builder = t::lib::TestBuilder->new; subtest 'strip_limit' => sub { + # This is the query I found that triggered bug 8594. my $sql = "SELECT aqorders.ordernumber, biblio.title, biblio.biblionumber, items.homebranch, aqorders.entrydate, aqorders.datereceived, @@ -62,91 +66,102 @@ subtest 'strip_limit' => sub { AND items.homebranch LIKE 'INFO' ORDER BY title"; - my ($res_sql, $res_lim1, $res_lim2) = C4::Reports::Guided::strip_limit($sql); - is($res_sql, $sql, "Not breaking subqueries"); - is($res_lim1, 0, "Returns correct default offset"); - is($res_lim2, undef, "Returns correct default LIMIT"); + my ( $res_sql, $res_lim1, $res_lim2 ) = C4::Reports::Guided::strip_limit($sql); + is( $res_sql, $sql, "Not breaking subqueries" ); + is( $res_lim1, 0, "Returns correct default offset" ); + is( $res_lim2, undef, "Returns correct default LIMIT" ); # Now the same thing, but we want it to remove the LIMIT from the end my $test_sql = $res_sql . " LIMIT 242"; - ($res_sql, $res_lim1, $res_lim2) = C4::Reports::Guided::strip_limit($test_sql); + ( $res_sql, $res_lim1, $res_lim2 ) = C4::Reports::Guided::strip_limit($test_sql); + # The replacement drops a ' ' where the limit was - is(trim($res_sql), $sql, "Correctly removes only final LIMIT"); - is($res_lim1, 0, "Returns correct default offset"); - is($res_lim2, 242, "Returns correct extracted LIMIT"); + is( trim($res_sql), $sql, "Correctly removes only final LIMIT" ); + is( $res_lim1, 0, "Returns correct default offset" ); + is( $res_lim2, 242, "Returns correct extracted LIMIT" ); $test_sql = $res_sql . " LIMIT 13,242"; - ($res_sql, $res_lim1, $res_lim2) = C4::Reports::Guided::strip_limit($test_sql); + ( $res_sql, $res_lim1, $res_lim2 ) = C4::Reports::Guided::strip_limit($test_sql); + # The replacement drops a ' ' where the limit was - is(trim($res_sql), $sql, "Correctly removes only final LIMIT (with offset)"); - is($res_lim1, 13, "Returns correct extracted offset"); - is($res_lim2, 242, "Returns correct extracted LIMIT"); + is( trim($res_sql), $sql, "Correctly removes only final LIMIT (with offset)" ); + is( $res_lim1, 13, "Returns correct extracted offset" ); + is( $res_lim2, 242, "Returns correct extracted LIMIT" ); # After here is the simpler case, where there isn't a WHERE clause to worry # about. # First case with nothing to change $sql = "SELECT * FROM items"; - ($res_sql, $res_lim1, $res_lim2) = C4::Reports::Guided::strip_limit($sql); - is($res_sql, $sql, "Not breaking simple queries"); - is($res_lim1, 0, "Returns correct default offset"); - is($res_lim2, undef, "Returns correct default LIMIT"); + ( $res_sql, $res_lim1, $res_lim2 ) = C4::Reports::Guided::strip_limit($sql); + is( $res_sql, $sql, "Not breaking simple queries" ); + is( $res_lim1, 0, "Returns correct default offset" ); + is( $res_lim2, undef, "Returns correct default LIMIT" ); $test_sql = $sql . " LIMIT 242"; - ($res_sql, $res_lim1, $res_lim2) = C4::Reports::Guided::strip_limit($test_sql); - is(trim($res_sql), $sql, "Correctly removes LIMIT in simple case"); - is($res_lim1, 0, "Returns correct default offset"); - is($res_lim2, 242, "Returns correct extracted LIMIT"); + ( $res_sql, $res_lim1, $res_lim2 ) = C4::Reports::Guided::strip_limit($test_sql); + is( trim($res_sql), $sql, "Correctly removes LIMIT in simple case" ); + is( $res_lim1, 0, "Returns correct default offset" ); + is( $res_lim2, 242, "Returns correct extracted LIMIT" ); $test_sql = $sql . " LIMIT 13,242"; - ($res_sql, $res_lim1, $res_lim2) = C4::Reports::Guided::strip_limit($test_sql); - is(trim($res_sql), $sql, "Correctly removes LIMIT in simple case (with offset)"); - is($res_lim1, 13, "Returns correct extracted offset"); - is($res_lim2, 242, "Returns correct extracted LIMIT"); + ( $res_sql, $res_lim1, $res_lim2 ) = C4::Reports::Guided::strip_limit($test_sql); + is( trim($res_sql), $sql, "Correctly removes LIMIT in simple case (with offset)" ); + is( $res_lim1, 13, "Returns correct extracted offset" ); + is( $res_lim2, 242, "Returns correct extracted LIMIT" ); }; -$_->delete for Koha::AuthorisedValues->search({ category => 'XXX' }); -Koha::AuthorisedValue->new({category => 'LOC'})->store; +$_->delete for Koha::AuthorisedValues->search( { category => 'XXX' } ); +Koha::AuthorisedValue->new( { category => 'LOC' } )->store; subtest 'GetReservedAuthorisedValues' => sub { plan tests => 1; + # This one will catch new reserved words not added # to GetReservedAuthorisedValues my %test_authval = ( - 'date' => 1, - 'branches' => 1, - 'itemtypes' => 1, - 'cn_source' => 1, - 'categorycode' => 1, + 'date' => 1, + 'branches' => 1, + 'itemtypes' => 1, + 'cn_source' => 1, + 'categorycode' => 1, 'biblio_framework' => 1, - 'list' => 1, - 'cash_registers' => 1, - 'debit_types' => 1, - 'credit_types' => 1 + 'list' => 1, + 'cash_registers' => 1, + 'debit_types' => 1, + 'credit_types' => 1 ); my $reserved_authorised_values = GetReservedAuthorisedValues(); - is_deeply(\%test_authval, $reserved_authorised_values, - 'GetReservedAuthorisedValues returns a fixed list'); + is_deeply( + \%test_authval, $reserved_authorised_values, + 'GetReservedAuthorisedValues returns a fixed list' + ); }; subtest 'IsAuthorisedValueValid' => sub { plan tests => 12; - ok( IsAuthorisedValueValid('LOC'), - 'User defined authorised value category is valid'); + ok( + IsAuthorisedValueValid('LOC'), + 'User defined authorised value category is valid' + ); - ok( ! IsAuthorisedValueValid('XXX'), - 'Not defined authorised value category is invalid'); + ok( + !IsAuthorisedValueValid('XXX'), + 'Not defined authorised value category is invalid' + ); # Loop through the reserved authorised values - foreach my $authorised_value ( keys %{GetReservedAuthorisedValues()} ) { - ok( IsAuthorisedValueValid($authorised_value), - '\''.$authorised_value.'\' is a reserved word, and thus a valid authorised value'); + foreach my $authorised_value ( keys %{ GetReservedAuthorisedValues() } ) { + ok( + IsAuthorisedValueValid($authorised_value), + '\'' . $authorised_value . '\' is a reserved word, and thus a valid authorised value' + ); } }; -subtest 'GetParametersFromSQL+ValidateSQLParameters' => sub { +subtest 'GetParametersFromSQL+ValidateSQLParameters' => sub { plan tests => 3; my $test_query_1 = " SELECT date_due @@ -158,20 +173,24 @@ subtest 'GetParametersFromSQL+ValidateSQLParameters' => sub { "; my @test_parameters_with_custom_list = ( - { 'name' => 'Year', 'authval' => 'custom_list' }, - { 'name' => 'Branch', 'authval' => 'branches' }, - { 'name' => 'Borrower', 'authval' => undef }, + { 'name' => 'Year', 'authval' => 'custom_list' }, + { 'name' => 'Branch', 'authval' => 'branches' }, + { 'name' => 'Borrower', 'authval' => undef }, { 'name' => 'Item type', 'authval' => 'itemtypes' } ); - is_deeply( GetParametersFromSQL($test_query_1), \@test_parameters_with_custom_list, - 'SQL params are correctly parsed'); + is_deeply( + GetParametersFromSQL($test_query_1), \@test_parameters_with_custom_list, + 'SQL params are correctly parsed' + ); my @problematic_parameters = (); push @problematic_parameters, { 'name' => 'Year', 'authval' => 'custom_list' }; - is_deeply( ValidateSQLParameters( $test_query_1 ), - \@problematic_parameters, - '\'custom_list\' not a valid category' ); + is_deeply( + ValidateSQLParameters($test_query_1), + \@problematic_parameters, + '\'custom_list\' not a valid category' + ); my $test_query_2 = " SELECT date_due @@ -181,7 +200,8 @@ subtest 'GetParametersFromSQL+ValidateSQLParameters' => sub { borrowernumber = <<Borrower|LOC>> "; - is_deeply( ValidateSQLParameters( $test_query_2 ), + is_deeply( + ValidateSQLParameters($test_query_2), [], 'All parameters valid, empty problematic authvals list' ); @@ -198,39 +218,46 @@ subtest 'get_saved_reports' => sub { is( $count, 0, "There is no report" ); my @report_ids; - foreach my $ii ( 1..3 ) { - my $id = $builder->build({ source => 'Borrower' })->{ borrowernumber }; - push @report_ids, save_report({ - borrowernumber => $id, - sql => "SQL$id", - name => "Name$id", - area => "area$ii", # ii vs id area is varchar(6) - group => "group$id", - subgroup => "subgroup$id", - type => "type$id", - notes => "note$id", - cache_expiry => undef, - public => 0, - }); + foreach my $ii ( 1 .. 3 ) { + my $id = $builder->build( { source => 'Borrower' } )->{borrowernumber}; + push @report_ids, save_report( + { + borrowernumber => $id, + sql => "SQL$id", + name => "Name$id", + area => "area$ii", # ii vs id area is varchar(6) + group => "group$id", + subgroup => "subgroup$id", + type => "type$id", + notes => "note$id", + cache_expiry => undef, + public => 0, + } + ); $count++; } like( $report_ids[0], '/^\d+$/', "Save_report returns an id for first" ); like( $report_ids[1], '/^\d+$/', "Save_report returns an id for second" ); like( $report_ids[2], '/^\d+$/', "Save_report returns an id for third" ); - is( scalar @{ get_saved_reports() }, - $count, "$count reports have been added" ); + is( + scalar @{ get_saved_reports() }, + $count, "$count reports have been added" + ); ok( 0 < scalar @{ get_saved_reports( $report_ids[0] ) }, "filter takes report id" ); - ok( 0 < scalar @{ get_saved_reports({date => dt_from_string->ymd }) }, "filter takes date" ); + ok( 0 < scalar @{ get_saved_reports( { date => dt_from_string->ymd } ) }, "filter takes date" ); - my $r1 = Koha::Reports->find($report_ids[0]); - $r1 = update_sql($r1->id, { %{$r1->unblessed}, borrowernumber => $r1->borrowernumber, name => 'Just another report' }); + my $r1 = Koha::Reports->find( $report_ids[0] ); + $r1 = update_sql( + $r1->id, + { %{ $r1->unblessed }, borrowernumber => $r1->borrowernumber, name => 'Just another report' } + ); is( $r1->cache_expiry, 300, 'cache_expiry has the correct default value, from DBMS' ); #Test delete_report - is (delete_report(),undef, "Without id delete_report returns undef"); + is( delete_report(), undef, "Without id delete_report returns undef" ); is( delete_report( $report_ids[0] ), 1, "report 1 is deleted" ); $count--; @@ -240,8 +267,10 @@ subtest 'get_saved_reports' => sub { is( delete_report( $report_ids[1], $report_ids[2] ), 2, "report 2 and 3 are deleted" ); $count -= 2; - is( scalar @{ get_saved_reports() }, - $count, "Report2 and report3 have been deleted" ); + is( + scalar @{ get_saved_reports() }, + $count, "Report2 and report3 have been deleted" + ); my $sth = execute_query( { @@ -251,7 +280,7 @@ subtest 'get_saved_reports' => sub { } ); my $results = $sth->fetchall_arrayref; - is(scalar @$results, 1, 'running a query returned a result'); + is( scalar @$results, 1, 'running a query returned a result' ); my $version = C4::Context->preference('Version'); $sth = execute_query( @@ -265,7 +294,7 @@ subtest 'get_saved_reports' => sub { $results = $sth->fetchall_arrayref; is_deeply( $results, - [ [ $version ] ], + [ [$version] ], 'running a query with a parameter returned the expected result' ); @@ -282,14 +311,16 @@ subtest 'get_saved_reports' => sub { ) } qr/DBD::mysql::st execute failed: You have an error in your SQL syntax;/, - "Wrong SQL syntax raises warning"; + "Wrong SQL syntax raises warning"; ok( - defined($errors) && exists($errors->{queryerr}), + defined($errors) && exists( $errors->{queryerr} ), 'attempting to run a report with an SQL syntax error returns error message (Bug 12214)' ); - is_deeply( get_report_areas(), [ 'CIRC', 'CAT', 'PAT', 'ACQ', 'ACC', 'SER' ], - "get_report_areas returns the correct array of report areas"); + is_deeply( + get_report_areas(), [ 'CIRC', 'CAT', 'PAT', 'ACQ', 'ACC', 'SER' ], + "get_report_areas returns the correct array of report areas" + ); }; subtest 'Ensure last_run is populated' => sub { @@ -313,7 +344,7 @@ subtest 'Ensure last_run is populated' => sub { isnt( $report->last_run, undef, 'First run of report populates last_run' ); my $previous_last_run = $report->last_run; - sleep(1); # last_run is stored to the second, so we need to ensure at least one second has passed between runs + sleep(1); # last_run is stored to the second, so we need to ensure at least one second has passed between runs execute_query( { sql => $report->savedsql, report_id => $report->id } ); $report->discard_changes(); @@ -334,7 +365,10 @@ subtest 'convert_sql' => sub { FROM biblio_metadata HAVING count505 > 1|; - is( C4::Reports::Guided::convert_sql( $sql ), $expected_converted_sql, "Simple query should have been correctly converted"); + is( + C4::Reports::Guided::convert_sql($sql), $expected_converted_sql, + "Simple query should have been correctly converted" + ); $sql = q| SELECT biblionumber, substring( @@ -351,7 +385,10 @@ title FROM biblio_metadata INNER JOIN biblio USING (biblionumber) WHERE biblionumber = 14|; - is( C4::Reports::Guided::convert_sql( $sql ), $expected_converted_sql, "Query with biblio info should have been correctly converted"); + is( + C4::Reports::Guided::convert_sql($sql), $expected_converted_sql, + "Query with biblio info should have been correctly converted" + ); $sql = q| SELECT concat(b.title, ' ', ExtractValue(m.marcxml, @@ -372,7 +409,10 @@ count(h.reservedate) AS 'holds' LEFT JOIN reserves h ON (b.biblionumber=h.biblionumber) GROUP BY b.biblionumber HAVING count(h.reservedate) >= 42|; - is( C4::Reports::Guided::convert_sql( $sql ), $expected_converted_sql, "Query with 2 joins should have been correctly converted"); + is( + C4::Reports::Guided::convert_sql($sql), $expected_converted_sql, + "Query with 2 joins should have been correctly converted" + ); $sql = q| SELECT t1.marcxml AS first, t2.marcxml AS second, @@ -383,7 +423,10 @@ count(h.reservedate) AS 'holds' SELECT t1.metadata AS first, t2.metadata AS second, FROM biblio_metadata t1 LEFT JOIN biblio_metadata t2 USING ( biblionumber )|; - is( C4::Reports::Guided::convert_sql( $sql ), $expected_converted_sql, "Query with multiple instances of marcxml and biblioitems should have them all replaced"); + is( + C4::Reports::Guided::convert_sql($sql), $expected_converted_sql, + "Query with multiple instances of marcxml and biblioitems should have them all replaced" + ); }; subtest 'Email report test' => sub { @@ -391,75 +434,113 @@ subtest 'Email report test' => sub { plan tests => 14; my $dbh = C4::Context->dbh; - my $id1 = $builder->build({ source => 'Borrower',value => { surname => 'mailer', email => 'a@b.com', emailpro => 'b@c.com' } })->{ borrowernumber }; - my $id2 = $builder->build({ source => 'Borrower',value => { surname => 'nomailer', email => undef, emailpro => 'd@e.com' } })->{ borrowernumber }; - my $id3 = $builder->build({ source => 'Borrower',value => { surname => 'norman', email => 'a@b.com', emailpro => undef } })->{ borrowernumber }; - my $report1 = $builder->build({ source => 'SavedSql', value => { savedsql => "SELECT surname,borrowernumber,email,emailpro FROM borrowers WHERE borrowernumber IN ($id1,$id2,$id3)" } })->{ id }; - my $report2 = $builder->build({ source => 'SavedSql', value => { savedsql => "SELECT potato FROM mashed" } })->{ id }; - - my $letter1 = $builder->build({ - source => 'Letter', - value => { - content => "[% surname %]", - branchcode => "", - message_transport_type => 'email', - is_html => undef + my $id1 = $builder->build( + { source => 'Borrower', value => { surname => 'mailer', email => 'a@b.com', emailpro => 'b@c.com' } } ) + ->{borrowernumber}; + my $id2 = $builder->build( + { source => 'Borrower', value => { surname => 'nomailer', email => undef, emailpro => 'd@e.com' } } ) + ->{borrowernumber}; + my $id3 = $builder->build( + { source => 'Borrower', value => { surname => 'norman', email => 'a@b.com', emailpro => undef } } ) + ->{borrowernumber}; + my $report1 = $builder->build( + { + source => 'SavedSql', + value => { + savedsql => + "SELECT surname,borrowernumber,email,emailpro FROM borrowers WHERE borrowernumber IN ($id1,$id2,$id3)" } - }); - my $letter2 = $builder->build({ - source => 'Letter', - value => { - content => "[% firstname %]", - branchcode => "", - message_transport_type => 'email', - is_html => 0 - } - }); + } + )->{id}; + my $report2 = + $builder->build( { source => 'SavedSql', value => { savedsql => "SELECT potato FROM mashed" } } )->{id}; - my $letter3 = $builder->build({ + my $letter1 = $builder->build( + { source => 'Letter', - value => { - content => "[% surname %]", - branchcode => "", + value => { + content => "[% surname %]", + branchcode => "", message_transport_type => 'email', - is_html => 1 + is_html => undef } - }); + } + ); + my $letter2 = $builder->build( + { + source => 'Letter', + value => { + content => "[% firstname %]", + branchcode => "", + message_transport_type => 'email', + is_html => 0 + } + } + ); - my $message_count = Koha::Notice::Messages->search({})->count; + my $letter3 = $builder->build( + { + source => 'Letter', + value => { + content => "[% surname %]", + branchcode => "", + message_transport_type => 'email', + is_html => 1 + } + } + ); + + my $message_count = Koha::Notice::Messages->search( {} )->count; my ( $emails, $errors ) = C4::Reports::Guided::EmailReport(); - is( $errors->[0]{FATAL}, 'MISSING_PARAMS', "Need to enter required params"); + is( $errors->[0]{FATAL}, 'MISSING_PARAMS', "Need to enter required params" ); - ($emails, $errors ) = C4::Reports::Guided::EmailReport({report_id => $report1, module => $letter1->{module}, code => $letter2->{code}}); - is( $errors->[0]{FATAL}, 'NO_LETTER', "Must have a letter that exists"); + ( $emails, $errors ) = C4::Reports::Guided::EmailReport( + { report_id => $report1, module => $letter1->{module}, code => $letter2->{code} } ); + is( $errors->[0]{FATAL}, 'NO_LETTER', "Must have a letter that exists" ); # for next test, we want to let execute_query capture any SQL errors - warning_like { local $dbh->{RaiseError} = 0; ($emails, $errors ) = C4::Reports::Guided::EmailReport({report_id => $report2, module => $letter1->{module} , code => $letter1->{code} }) } - qr/DBD::mysql::st execute failed/, + warning_like { + local $dbh->{RaiseError} = 0; + ( $emails, $errors ) = C4::Reports::Guided::EmailReport( + { report_id => $report2, module => $letter1->{module}, code => $letter1->{code} } ) + } + qr/DBD::mysql::st execute failed/, 'Error from bad report'; - is( $errors->[0]{FATAL}, 'REPORT_FAIL', "Bad report returns failure"); + is( $errors->[0]{FATAL}, 'REPORT_FAIL', "Bad report returns failure" ); - ($emails, $errors ) = C4::Reports::Guided::EmailReport({report_id => $report1, module => $letter1->{module} , code => $letter1->{code} }); - is( $errors->[0]{NO_FROM_COL} == 1 && $errors->[1]{NO_EMAIL_COL} == 2 && $errors->[2]{NO_FROM_COL} == 2, 1, "Correct warnings from the routine"); + ( $emails, $errors ) = C4::Reports::Guided::EmailReport( + { report_id => $report1, module => $letter1->{module}, code => $letter1->{code} } ); + is( + $errors->[0]{NO_FROM_COL} == 1 && $errors->[1]{NO_EMAIL_COL} == 2 && $errors->[2]{NO_FROM_COL} == 2, 1, + "Correct warnings from the routine" + ); - ($emails, $errors ) = C4::Reports::Guided::EmailReport({report_id => $report1, module => $letter1->{module} , code => $letter1->{code}, from => 'the@future.ooh' }); - is( $errors->[0]{NO_EMAIL_COL}, 2, "Warning only for patron with no email"); + ( $emails, $errors ) = C4::Reports::Guided::EmailReport( + { report_id => $report1, module => $letter1->{module}, code => $letter1->{code}, from => 'the@future.ooh' } ); + is( $errors->[0]{NO_EMAIL_COL}, 2, "Warning only for patron with no email" ); - is( $message_count, Koha::Notice::Messages->search({})->count, "Messages not added without commit"); + is( $message_count, Koha::Notice::Messages->search( {} )->count, "Messages not added without commit" ); - ($emails, $errors ) = C4::Reports::Guided::EmailReport({report_id => $report1, module => $letter1->{module} , code => $letter1->{code}, from => 'the@future.ooh' }); - is( $emails->[0]{letter}->{content}, "mailer", "Message has expected content"); - is( $emails->[1]{letter}->{content}, "norman", "Message has expected content"); - is( $emails->[0]{letter}->{'content-type'}, undef, "Message content type is not set for plain text mail"); + ( $emails, $errors ) = C4::Reports::Guided::EmailReport( + { report_id => $report1, module => $letter1->{module}, code => $letter1->{code}, from => 'the@future.ooh' } ); + is( $emails->[0]{letter}->{content}, "mailer", "Message has expected content" ); + is( $emails->[1]{letter}->{content}, "norman", "Message has expected content" ); + is( $emails->[0]{letter}->{'content-type'}, undef, "Message content type is not set for plain text mail" ); - ($emails, $errors ) = C4::Reports::Guided::EmailReport({report_id => $report1, module => $letter1->{module} , code => $letter1->{code}, from => 'the@future.ooh', email => 'emailpro' }); - is_deeply( $errors, [{'NO_EMAIL_COL'=>3}],"We report missing email in emailpro column"); - is( $emails->[0]->{to_address}, 'b@c.com', "Message uses correct email"); - is( $emails->[1]->{to_address}, 'd@e.com', "Message uses correct email"); + ( $emails, $errors ) = C4::Reports::Guided::EmailReport( + { + report_id => $report1, module => $letter1->{module}, code => $letter1->{code}, from => 'the@future.ooh', + email => 'emailpro' + } + ); + is_deeply( $errors, [ { 'NO_EMAIL_COL' => 3 } ], "We report missing email in emailpro column" ); + is( $emails->[0]->{to_address}, 'b@c.com', "Message uses correct email" ); + is( $emails->[1]->{to_address}, 'd@e.com', "Message uses correct email" ); - ($emails) = C4::Reports::Guided::EmailReport({report_id => $report1, module => $letter3->{module} , code => $letter3->{code}, from => 'the@future.ooh' }); - is( $emails->[0]{letter}->{'content-type'}, 'text/html; charset="UTF-8"', "Message has expected content type"); + ($emails) = C4::Reports::Guided::EmailReport( + { report_id => $report1, module => $letter3->{module}, code => $letter3->{code}, from => 'the@future.ooh' } ); + is( $emails->[0]{letter}->{'content-type'}, 'text/html; charset="UTF-8"', "Message has expected content type" ); }; @@ -473,15 +554,15 @@ subtest 'nb_rows() tests' => sub { $schema->storage->txn_begin; my $items_count = Koha::Items->search->count; - $builder->build_object({ class => 'Koha::Items' }); - $builder->build_object({ class => 'Koha::Items' }); + $builder->build_object( { class => 'Koha::Items' } ); + $builder->build_object( { class => 'Koha::Items' } ); $items_count += 2; my $query = q{ SELECT * FROM items xxx }; - my $nb_rows = nb_rows( $query ); + my $nb_rows = nb_rows($query); is( $nb_rows, $items_count, 'nb_rows returns the right value' ); @@ -490,10 +571,9 @@ subtest 'nb_rows() tests' => sub { }; # for next test, we want to let execute_query capture any SQL errors - - warning_like - { $nb_rows = nb_rows( $bad_query ) } - qr/DBD::mysql::st execute failed:/, + + warning_like { $nb_rows = nb_rows($bad_query) } + qr/DBD::mysql::st execute failed:/, 'Bad queries raise a warning'; is( $nb_rows, 0, 'nb_rows returns 0 on bad queries' ); diff --git a/t/db_dependent/Reserves.t b/t/db_dependent/Reserves.t index 12538a4888..93ab654c18 100755 --- a/t/db_dependent/Reserves.t +++ b/t/db_dependent/Reserves.t @@ -32,7 +32,8 @@ use C4::Items; use C4::Biblio qw( GetMarcFromKohaField ModBiblio ); use C4::HoldsQueue; use C4::Members; -use C4::Reserves qw( AddReserve AlterPriority CheckReserves ModReserve ModReserveAffect ReserveSlip CalculatePriority CanBookBeReserved IsAvailableForItemLevelRequest MoveReserve ChargeReserveFee RevertWaitingStatus CanItemBeReserved MergeHolds ); +use C4::Reserves + qw( AddReserve AlterPriority CheckReserves ModReserve ModReserveAffect ReserveSlip CalculatePriority CanBookBeReserved IsAvailableForItemLevelRequest MoveReserve ChargeReserveFee RevertWaitingStatus CanItemBeReserved MergeHolds ); use Koha::ActionLogs; use Koha::Biblios; use Koha::Caches; @@ -51,7 +52,7 @@ BEGIN { # Start transaction my $database = Koha::Database->new(); -my $schema = $database->schema(); +my $schema = $database->schema(); $schema->storage->txn_begin(); my $dbh = C4::Context->dbh; $dbh->do('DELETE FROM circulation_rules'); @@ -60,11 +61,13 @@ my $builder = t::lib::TestBuilder->new; my $frameworkcode = q//; - -t::lib::Mocks::mock_preference('ReservesNeedReturns', 1); +t::lib::Mocks::mock_preference( 'ReservesNeedReturns', 1 ); # Somewhat arbitrary field chosen for age restriction unit tests. Must be added to db before the framework is cached -$dbh->do("update marc_subfield_structure set kohafield='biblioitems.agerestriction' where tagfield='521' and tagsubfield='a' and frameworkcode=?", undef, $frameworkcode); +$dbh->do( + "update marc_subfield_structure set kohafield='biblioitems.agerestriction' where tagfield='521' and tagsubfield='a' and frameworkcode=?", + undef, $frameworkcode +); my $cache = Koha::Caches->get_instance; $cache->clear_from_cache("MarcStructure-0-$frameworkcode"); $cache->clear_from_cache("MarcStructure-1-$frameworkcode"); @@ -72,40 +75,41 @@ $cache->clear_from_cache("MarcSubfieldStructure-$frameworkcode"); ## Setup Test # Add branches -my $branch_1 = $builder->build({ source => 'Branch' })->{ branchcode }; -my $branch_2 = $builder->build({ source => 'Branch' })->{ branchcode }; -my $branch_3 = $builder->build({ source => 'Branch' })->{ branchcode }; +my $branch_1 = $builder->build( { source => 'Branch' } )->{branchcode}; +my $branch_2 = $builder->build( { source => 'Branch' } )->{branchcode}; +my $branch_3 = $builder->build( { source => 'Branch' } )->{branchcode}; + # Add categories -my $category_1 = $builder->build({ source => 'Category' })->{ categorycode }; -my $category_2 = $builder->build({ source => 'Category' })->{ categorycode }; +my $category_1 = $builder->build( { source => 'Category' } )->{categorycode}; +my $category_2 = $builder->build( { source => 'Category' } )->{categorycode}; + # Add an item type my $itemtype = $builder->build( { source => 'Itemtype', value => { notforloan => 0 } } )->{itemtype}; -t::lib::Mocks::mock_userenv({ branchcode => $branch_1 }); +t::lib::Mocks::mock_userenv( { branchcode => $branch_1 } ); -my $bibnum = $builder->build_sample_biblio({frameworkcode => $frameworkcode})->biblionumber; +my $bibnum = $builder->build_sample_biblio( { frameworkcode => $frameworkcode } )->biblionumber; # Create a helper item instance for testing -my $item = $builder->build_sample_item({ biblionumber => $bibnum, library => $branch_1, itype => $itemtype }); +my $item = $builder->build_sample_item( { biblionumber => $bibnum, library => $branch_1, itype => $itemtype } ); my $biblio_with_no_item = $builder->build_sample_biblio; # Modify item; setting barcode. my $testbarcode = '97531'; -$item->barcode($testbarcode)->store; # FIXME We should not hardcode a barcode! Also, what's the purpose of this? - +$item->barcode($testbarcode)->store; # FIXME We should not hardcode a barcode! Also, what's the purpose of this? # Create a borrower my %data = ( - firstname => 'my firstname', - surname => 'my surname', + firstname => 'my firstname', + surname => 'my surname', categorycode => $category_1, - branchcode => $branch_1, + branchcode => $branch_1, ); -Koha::Patron::Categories->find($category_1)->set({ enrolmentfee => 0})->store; -my $borrowernumber = Koha::Patron->new(\%data)->store->borrowernumber; -my $patron = Koha::Patrons->find( $borrowernumber ); -my $borrower = $patron->unblessed; +Koha::Patron::Categories->find($category_1)->set( { enrolmentfee => 0 } )->store; +my $borrowernumber = Koha::Patron->new( \%data )->store->borrowernumber; +my $patron = Koha::Patrons->find($borrowernumber); +my $borrower = $patron->unblessed; my $biblionumber = $bibnum; my $branchcode = Koha::Libraries->search->next->branchcode; @@ -119,41 +123,49 @@ AddReserve( } ); -my ($status, $reserve, $all_reserves) = CheckReserves( $item ); +my ( $status, $reserve, $all_reserves ) = CheckReserves($item); -is($status, "Reserved", "CheckReserves Test 1"); +is( $status, "Reserved", "CheckReserves Test 1" ); -ok(exists($reserve->{reserve_id}), 'CheckReserves() include reserve_id in its response'); +ok( exists( $reserve->{reserve_id} ), 'CheckReserves() include reserve_id in its response' ); -($status, $reserve, $all_reserves) = CheckReserves( $item ); -is($status, "Reserved", "CheckReserves Test 2"); +( $status, $reserve, $all_reserves ) = CheckReserves($item); +is( $status, "Reserved", "CheckReserves Test 2" ); ### ### Regression test for bug 10272 ### my %requesters = (); -$requesters{$branch_1} = Koha::Patron->new({ - branchcode => $branch_1, - categorycode => $category_2, - surname => "borrower from $branch_1", -})->store; -for my $i ( 2 .. 5 ) { - $requesters{"CPL$i"} = Koha::Patron->new({ +$requesters{$branch_1} = Koha::Patron->new( + { branchcode => $branch_1, categorycode => $category_2, - surname => "borrower $i from $branch_1", - })->store; + surname => "borrower from $branch_1", + } +)->store; +for my $i ( 2 .. 5 ) { + $requesters{"CPL$i"} = Koha::Patron->new( + { + branchcode => $branch_1, + categorycode => $category_2, + surname => "borrower $i from $branch_1", + } + )->store; } -$requesters{$branch_2} = Koha::Patron->new({ - branchcode => $branch_2, - categorycode => $category_2, - surname => "borrower from $branch_2", -})->store; -$requesters{$branch_3} = Koha::Patron->new({ - branchcode => $branch_3, - categorycode => $category_2, - surname => "borrower from $branch_3", -})->store; +$requesters{$branch_2} = Koha::Patron->new( + { + branchcode => $branch_2, + categorycode => $category_2, + surname => "borrower from $branch_2", + } +)->store; +$requesters{$branch_3} = Koha::Patron->new( + { + branchcode => $branch_3, + categorycode => $category_2, + surname => "borrower from $branch_3", + } +)->store; # Configure rules so that $branch_1 allows only $branch_1 patrons # to request its items, while $branch_2 will allow its items @@ -166,7 +178,7 @@ Koha::CirculationRules->set_rules( categorycode => undef, itemtype => undef, rules => { - reservesallowed => 25, + reservesallowed => 25, holds_per_record => 1, } } @@ -175,9 +187,9 @@ Koha::CirculationRules->set_rules( # CPL allows only its own patrons to request its items Koha::CirculationRules->set_rules( { - branchcode => $branch_1, - itemtype => undef, - rules => { + branchcode => $branch_1, + itemtype => undef, + rules => { holdallowed => 'from_home_library', returnbranch => 'homebranch', } @@ -187,18 +199,18 @@ Koha::CirculationRules->set_rules( # ... while FPL allows anybody to request its items Koha::CirculationRules->set_rules( { - branchcode => $branch_2, - itemtype => undef, - rules => { + branchcode => $branch_2, + itemtype => undef, + rules => { holdallowed => 'from_any_library', returnbranch => 'homebranch', } } ); -my $bibnum2 = $builder->build_sample_biblio({frameworkcode => $frameworkcode})->biblionumber; +my $bibnum2 = $builder->build_sample_biblio( { frameworkcode => $frameworkcode } )->biblionumber; -my ($itemnum_cpl, $itemnum_fpl); +my ( $itemnum_cpl, $itemnum_fpl ); $itemnum_cpl = $builder->build_sample_item( { biblionumber => $bibnum2, @@ -218,7 +230,7 @@ $itemnum_fpl = $builder->build_sample_item( # Ensure that priorities are numbered correcly when a hold is moved to waiting # (bug 11947) -$dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum2)); +$dbh->do( "DELETE FROM reserves WHERE biblionumber=?", undef, ($bibnum2) ); AddReserve( { branchcode => $branch_3, @@ -243,21 +255,23 @@ AddReserve( priority => 3, } ); -ModReserveAffect($itemnum_cpl, $requesters{$branch_3}->borrowernumber, 0); +ModReserveAffect( $itemnum_cpl, $requesters{$branch_3}->borrowernumber, 0 ); # Now it should have different priorities. -my $biblio = Koha::Biblios->find( $bibnum2 ); -my $holds = $biblio->holds({}, { order_by => 'reserve_id' });; -is($holds->next->priority, 0, 'Item is correctly waiting'); -is($holds->next->priority, 1, 'Item is correctly priority 1'); -is($holds->next->priority, 2, 'Item is correctly priority 2'); +my $biblio = Koha::Biblios->find($bibnum2); +my $holds = $biblio->holds( {}, { order_by => 'reserve_id' } ); +is( $holds->next->priority, 0, 'Item is correctly waiting' ); +is( $holds->next->priority, 1, 'Item is correctly priority 1' ); +is( $holds->next->priority, 2, 'Item is correctly priority 2' ); -my @reserves = Koha::Holds->search({ borrowernumber => $requesters{$branch_3}->borrowernumber })->waiting->as_list; +my @reserves = Koha::Holds->search( { borrowernumber => $requesters{$branch_3}->borrowernumber } )->waiting->as_list; is( @reserves, 1, 'GetWaiting got only the waiting reserve' ); -is( $reserves[0]->borrowernumber(), $requesters{$branch_3}->borrowernumber, 'GetWaiting got the reserve for the correct borrower' ); +is( + $reserves[0]->borrowernumber(), $requesters{$branch_3}->borrowernumber, + 'GetWaiting got the reserve for the correct borrower' +); - -$dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum2)); +$dbh->do( "DELETE FROM reserves WHERE biblionumber=?", undef, ($bibnum2) ); AddReserve( { branchcode => $branch_3, @@ -288,13 +302,16 @@ AddReserve( t::lib::Mocks::mock_preference( 'ReservesControlBranch', 'ItemHomeLibrary' ); my $messages; + # Return the CPL item at FPL. The hold that should be triggered is # the one placed by the CPL patron, as the other two patron's hold # requests cannot be filled by that item per policy. -(undef, $messages, undef, undef) = AddReturn('bug10272_CPL', $branch_2); -is( $messages->{ResFound}->{borrowernumber}, +( undef, $messages, undef, undef ) = AddReturn( 'bug10272_CPL', $branch_2 ); +is( + $messages->{ResFound}->{borrowernumber}, $requesters{$branch_1}->borrowernumber, - 'restrictive library\'s items only fill requests by own patrons (bug 10272)'); + 'restrictive library\'s items only fill requests by own patrons (bug 10272)' +); # Return the FPL item at FPL. The hold that should be triggered is # the one placed by the RPL patron, as that patron is first in line @@ -303,20 +320,22 @@ is( $messages->{ResFound}->{borrowernumber}, # Ensure that the preference 'LocalHoldsPriority' is not set (Bug 15244): t::lib::Mocks::mock_preference( 'LocalHoldsPriority', '' ); -(undef, $messages, undef, undef) = AddReturn('bug10272_FPL', $branch_2); -is( $messages->{ResFound}->{borrowernumber}, +( undef, $messages, undef, undef ) = AddReturn( 'bug10272_FPL', $branch_2 ); +is( + $messages->{ResFound}->{borrowernumber}, $requesters{$branch_3}->borrowernumber, - 'for generous library, its items fill first hold request in line (bug 10272)'); + 'for generous library, its items fill first hold request in line (bug 10272)' +); -$biblio = Koha::Biblios->find( $biblionumber ); -$holds = $biblio->holds; -is($holds->count, 1, "Only one reserves for this biblio"); +$biblio = Koha::Biblios->find($biblionumber); +$holds = $biblio->holds; +is( $holds->count, 1, "Only one reserves for this biblio" ); $holds->next->reserve_id; # Tests for bug 9761 (ConfirmFutureHolds): new CheckReserves lookahead parameter, and corresponding change in AddReturn # Note that CheckReserve uses its lookahead parameter and does not check ConfirmFutureHolds pref (it should be passed if needed like AddReturn does) # Test 9761a: Add a reserve without date, CheckReserve should return it -$dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum)); +$dbh->do( "DELETE FROM reserves WHERE biblionumber=?", undef, ($bibnum) ); AddReserve( { branchcode => $branch_1, @@ -325,16 +344,16 @@ AddReserve( priority => 1, } ); -($status)=CheckReserves( $item ); -is( $status, 'Reserved', 'CheckReserves returns reserve without lookahead'); -($status)=CheckReserves( $item, 7 ); -is( $status, 'Reserved', 'CheckReserves also returns reserve with lookahead'); +($status) = CheckReserves($item); +is( $status, 'Reserved', 'CheckReserves returns reserve without lookahead' ); +($status) = CheckReserves( $item, 7 ); +is( $status, 'Reserved', 'CheckReserves also returns reserve with lookahead' ); # Test 9761b: Add a reserve with future date, CheckReserve should not return it -$dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum)); -t::lib::Mocks::mock_preference('AllowHoldDateInFuture', 1); -my $resdate= dt_from_string(); -$resdate->add_duration(DateTime::Duration->new(days => 4)); +$dbh->do( "DELETE FROM reserves WHERE biblionumber=?", undef, ($bibnum) ); +t::lib::Mocks::mock_preference( 'AllowHoldDateInFuture', 1 ); +my $resdate = dt_from_string(); +$resdate->add_duration( DateTime::Duration->new( days => 4 ) ); my $reserve_id = AddReserve( { branchcode => $branch_1, @@ -344,31 +363,36 @@ my $reserve_id = AddReserve( reservation_date => $resdate, } ); -($status)=CheckReserves( $item ); -is( $status, '', 'CheckReserves returns no future reserve without lookahead'); +($status) = CheckReserves($item); +is( $status, '', 'CheckReserves returns no future reserve without lookahead' ); # Test 9761c: Add a reserve with future date, CheckReserve should return it if lookahead is high enough -($status)=CheckReserves( $item, 3 ); -is( $status, '', 'CheckReserves returns no future reserve with insufficient lookahead'); -($status)=CheckReserves( $item, 4 ); -is( $status, 'Reserved', 'CheckReserves returns future reserve with sufficient lookahead'); +($status) = CheckReserves( $item, 3 ); +is( $status, '', 'CheckReserves returns no future reserve with insufficient lookahead' ); +($status) = CheckReserves( $item, 4 ); +is( $status, 'Reserved', 'CheckReserves returns future reserve with sufficient lookahead' ); # Test 9761d: Check ResFound message of AddReturn for future hold # Note that AddReturn is in Circulation.pm, but this test really pertains to reserves; AddReturn uses the ConfirmFutureHolds pref when calling CheckReserves # In this test we do not need an issued item; it is just a 'checkin' -t::lib::Mocks::mock_preference('ConfirmFutureHolds', 0); -(my $doreturn, $messages)= AddReturn($testbarcode,$branch_1); -is($messages->{ResFound}//'', '', 'AddReturn does not care about future reserve when ConfirmFutureHolds is off'); -t::lib::Mocks::mock_preference('ConfirmFutureHolds', 3); -($doreturn, $messages)= AddReturn($testbarcode,$branch_1); -is(exists $messages->{ResFound}?1:0, 0, 'AddReturn ignores future reserve beyond ConfirmFutureHolds days'); -t::lib::Mocks::mock_preference('ConfirmFutureHolds', 7); -($doreturn, $messages)= AddReturn($testbarcode,$branch_1); -is(exists $messages->{ResFound}?1:0, 1, 'AddReturn considers future reserve within ConfirmFutureHolds days'); +t::lib::Mocks::mock_preference( 'ConfirmFutureHolds', 0 ); +( my $doreturn, $messages ) = AddReturn( $testbarcode, $branch_1 ); +is( $messages->{ResFound} // '', '', 'AddReturn does not care about future reserve when ConfirmFutureHolds is off' ); +t::lib::Mocks::mock_preference( 'ConfirmFutureHolds', 3 ); +( $doreturn, $messages ) = AddReturn( $testbarcode, $branch_1 ); +is( exists $messages->{ResFound} ? 1 : 0, 0, 'AddReturn ignores future reserve beyond ConfirmFutureHolds days' ); +t::lib::Mocks::mock_preference( 'ConfirmFutureHolds', 7 ); +( $doreturn, $messages ) = AddReturn( $testbarcode, $branch_1 ); +is( exists $messages->{ResFound} ? 1 : 0, 1, 'AddReturn considers future reserve within ConfirmFutureHolds days' ); -my $now_holder = $builder->build_object({ class => 'Koha::Patrons', value => { - branchcode => $branch_1, -}}); +my $now_holder = $builder->build_object( + { + class => 'Koha::Patrons', + value => { + branchcode => $branch_1, + } + } +); my $now_reserve_id = AddReserve( { branchcode => $branch_1, @@ -379,46 +403,50 @@ my $now_reserve_id = AddReserve( } ); my $which_highest; -($status,$which_highest)=CheckReserves( $item, 3 ); -is( $which_highest->{reserve_id}, $now_reserve_id, 'CheckReserves returns lower priority current reserve with insufficient lookahead'); -($status, $which_highest)=CheckReserves( $item, 4 ); -is( $which_highest->{reserve_id}, $reserve_id, 'CheckReserves returns higher priority future reserve with sufficient lookahead'); -ModReserve({ reserve_id => $now_reserve_id, rank => 'del', cancellation_reason => 'test reserve' }); - +( $status, $which_highest ) = CheckReserves( $item, 3 ); +is( + $which_highest->{reserve_id}, $now_reserve_id, + 'CheckReserves returns lower priority current reserve with insufficient lookahead' +); +( $status, $which_highest ) = CheckReserves( $item, 4 ); +is( + $which_highest->{reserve_id}, $reserve_id, + 'CheckReserves returns higher priority future reserve with sufficient lookahead' +); +ModReserve( { reserve_id => $now_reserve_id, rank => 'del', cancellation_reason => 'test reserve' } ); # End of tests for bug 9761 (ConfirmFutureHolds) - # test marking a hold as captured my $hold_notice_count = count_hold_print_messages(); -ModReserveAffect($item->itemnumber, $requesters{$branch_1}->borrowernumber, 0); +ModReserveAffect( $item->itemnumber, $requesters{$branch_1}->borrowernumber, 0 ); my $new_count = count_hold_print_messages(); -is($new_count, $hold_notice_count + 1, 'patron notified when item set to waiting'); +is( $new_count, $hold_notice_count + 1, 'patron notified when item set to waiting' ); # test that duplicate notices aren't generated -ModReserveAffect($item->itemnumber, $requesters{$branch_1}->borrowernumber, 0); +ModReserveAffect( $item->itemnumber, $requesters{$branch_1}->borrowernumber, 0 ); $new_count = count_hold_print_messages(); -is($new_count, $hold_notice_count + 1, 'patron not notified a second time (bug 11445)'); +is( $new_count, $hold_notice_count + 1, 'patron not notified a second time (bug 11445)' ); # avoiding the not_same_branch error -t::lib::Mocks::mock_preference('IndependentBranches', 0); -$item = Koha::Items->find($item->itemnumber); +t::lib::Mocks::mock_preference( 'IndependentBranches', 0 ); +$item = Koha::Items->find( $item->itemnumber ); is( - @{$item->safe_delete->messages}[0]->message, + @{ $item->safe_delete->messages }[0]->message, 'book_reserved', 'item that is captured to fill a hold cannot be deleted', ); my $letter = ReserveSlip( { branchcode => $branch_1, reserve_id => $reserve_id } ); -ok(defined($letter), 'can successfully generate hold slip (bug 10949)'); +ok( defined($letter), 'can successfully generate hold slip (bug 10949)' ); # Tests for bug 9788: Does Koha::Item->current_holds return a future wait? # 9788a: current_holds does not return future next available hold -$dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum)); -t::lib::Mocks::mock_preference('ConfirmFutureHolds', 2); -t::lib::Mocks::mock_preference('AllowHoldDateInFuture', 1); -$resdate= dt_from_string(); -$resdate->add_duration(DateTime::Duration->new(days => 2)); +$dbh->do( "DELETE FROM reserves WHERE biblionumber=?", undef, ($bibnum) ); +t::lib::Mocks::mock_preference( 'ConfirmFutureHolds', 2 ); +t::lib::Mocks::mock_preference( 'AllowHoldDateInFuture', 1 ); +$resdate = dt_from_string(); +$resdate->add_duration( DateTime::Duration->new( days => 2 ) ); AddReserve( { branchcode => $branch_1, @@ -430,11 +458,12 @@ AddReserve( ); $holds = $item->current_holds; -my $dtf = Koha::Database->new->schema->storage->datetime_parser; -my $future_holds = $holds->search({ reservedate => { '>' => $dtf->format_date( dt_from_string ) } } ); -is( $future_holds->count, 0, 'current_holds does not return a future next available hold'); +my $dtf = Koha::Database->new->schema->storage->datetime_parser; +my $future_holds = $holds->search( { reservedate => { '>' => $dtf->format_date(dt_from_string) } } ); +is( $future_holds->count, 0, 'current_holds does not return a future next available hold' ); + # 9788b: current_holds does not return future item level hold -$dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum)); +$dbh->do( "DELETE FROM reserves WHERE biblionumber=?", undef, ($bibnum) ); AddReserve( { branchcode => $branch_1, @@ -444,19 +473,22 @@ AddReserve( reservation_date => $resdate, itemnumber => $item->itemnumber, } -); #item level hold -$future_holds = $holds->search({ reservedate => { '>' => $dtf->format_date( dt_from_string ) } } ); +); #item level hold +$future_holds = $holds->search( { reservedate => { '>' => $dtf->format_date(dt_from_string) } } ); is( $future_holds->count, 0, 'current_holds does not return a future item level hold' ); + # 9788c: current_holds returns future wait (confirmed future hold) -ModReserveAffect( $item->itemnumber, $requesters{$branch_1}->borrowernumber, 0); #confirm hold -$future_holds = $holds->search({ reservedate => { '>' => $dtf->format_date( dt_from_string ) } } ); +ModReserveAffect( $item->itemnumber, $requesters{$branch_1}->borrowernumber, 0 ); #confirm hold +$future_holds = $holds->search( { reservedate => { '>' => $dtf->format_date(dt_from_string) } } ); is( $future_holds->count, 1, 'current_holds returns a future wait (confirmed future hold)' ); + # End of tests for bug 9788 -$dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum)); +$dbh->do( "DELETE FROM reserves WHERE biblionumber=?", undef, ($bibnum) ); + # Tests for CalculatePriority (bug 8918) my $p = C4::Reserves::CalculatePriority($bibnum2); -is($p, 4, 'CalculatePriority should now return priority 4'); +is( $p, 4, 'CalculatePriority should now return priority 4' ); AddReserve( { branchcode => $branch_1, @@ -466,11 +498,13 @@ AddReserve( } ); $p = C4::Reserves::CalculatePriority($bibnum2); -is($p, 5, 'CalculatePriority should now return priority 5'); +is( $p, 5, 'CalculatePriority should now return priority 5' ); + #some tests on bibnum -$dbh->do("DELETE FROM reserves WHERE biblionumber=?",undef,($bibnum)); +$dbh->do( "DELETE FROM reserves WHERE biblionumber=?", undef, ($bibnum) ); $p = C4::Reserves::CalculatePriority($bibnum); -is($p, 1, 'CalculatePriority should now return priority 1'); +is( $p, 1, 'CalculatePriority should now return priority 1' ); + #add a new reserve and confirm it to waiting AddReserve( { @@ -482,10 +516,11 @@ AddReserve( } ); $p = C4::Reserves::CalculatePriority($bibnum); -is($p, 2, 'CalculatePriority should now return priority 2'); -ModReserveAffect( $item->itemnumber, $requesters{$branch_1}->borrowernumber, 0); +is( $p, 2, 'CalculatePriority should now return priority 2' ); +ModReserveAffect( $item->itemnumber, $requesters{$branch_1}->borrowernumber, 0 ); $p = C4::Reserves::CalculatePriority($bibnum); -is($p, 1, 'CalculatePriority should now return priority 1'); +is( $p, 1, 'CalculatePriority should now return priority 1' ); + #add another biblio hold, no resdate AddReserve( { @@ -496,69 +531,87 @@ AddReserve( } ); $p = C4::Reserves::CalculatePriority($bibnum); -is($p, 2, 'CalculatePriority should now return priority 2'); +is( $p, 2, 'CalculatePriority should now return priority 2' ); + #add another future hold -t::lib::Mocks::mock_preference('AllowHoldDateInFuture', 1); -$resdate= dt_from_string(); -$resdate->add_duration(DateTime::Duration->new(days => 1)); +t::lib::Mocks::mock_preference( 'AllowHoldDateInFuture', 1 ); +$resdate = dt_from_string(); +$resdate->add_duration( DateTime::Duration->new( days => 1 ) ); AddReserve( { - branchcode => $branch_1, - borrowernumber => $requesters{'CPL2'}->borrowernumber, - biblionumber => $bibnum, - priority => $p, + branchcode => $branch_1, + borrowernumber => $requesters{'CPL2'}->borrowernumber, + biblionumber => $bibnum, + priority => $p, reservation_date => $resdate, } ); $p = C4::Reserves::CalculatePriority($bibnum); -is($p, 2, 'CalculatePriority should now still return priority 2'); +is( $p, 2, 'CalculatePriority should now still return priority 2' ); + #calc priority with future resdate -$p = C4::Reserves::CalculatePriority($bibnum, $resdate); -is($p, 3, 'CalculatePriority should now return priority 3'); +$p = C4::Reserves::CalculatePriority( $bibnum, $resdate ); +is( $p, 3, 'CalculatePriority should now return priority 3' ); + # End of tests for bug 8918 # regression test for bug 12630 # Now there are 2 reserves on $bibnum -t::lib::Mocks::mock_preference('AllowHoldDateInFuture', 1); -my $bor_tmp_1 = $builder->build_object({ class => 'Koha::Patrons',value =>{ - firstname => 'my firstname tmp 1', - surname => 'my surname tmp 1', - categorycode => 'S', - branchcode => 'CPL', -}}); -my $bor_tmp_2 = $builder->build_object({ class => 'Koha::Patrons',value =>{ - firstname => 'my firstname tmp 2', - surname => 'my surname tmp 2', - categorycode => 'S', - branchcode => 'CPL', -}}); +t::lib::Mocks::mock_preference( 'AllowHoldDateInFuture', 1 ); +my $bor_tmp_1 = $builder->build_object( + { + class => 'Koha::Patrons', + value => { + firstname => 'my firstname tmp 1', + surname => 'my surname tmp 1', + categorycode => 'S', + branchcode => 'CPL', + } + } +); +my $bor_tmp_2 = $builder->build_object( + { + class => 'Koha::Patrons', + value => { + firstname => 'my firstname tmp 2', + surname => 'my surname tmp 2', + categorycode => 'S', + branchcode => 'CPL', + } + } +); my $borrowernumber_tmp_1 = $bor_tmp_1->borrowernumber; my $borrowernumber_tmp_2 = $bor_tmp_2->borrowernumber; -my $date_in_future = dt_from_string(); -$date_in_future = $date_in_future->add_duration(DateTime::Duration->new(days => 1)); -AddReserve({ - branchcode => 'CPL', - borrowernumber => $borrowernumber_tmp_1, - biblionumber => $bibnum, - priority => 3, - reservation_date => $date_in_future -}); -AddReserve({ - branchcode => 'CPL', - borrowernumber => $borrowernumber_tmp_2, - biblionumber => $bibnum, - priority => 4, - reservation_date => $date_in_future -}); -my @r1 = Koha::Holds->search({ borrowernumber => $borrowernumber_tmp_1 })->as_list; -my @r2 = Koha::Holds->search({ borrowernumber => $borrowernumber_tmp_2 })->as_list; -is( $r1[0]->priority, 3, 'priority for hold in future should be correct'); -is( $r2[0]->priority, 4, 'priority for hold not in future should be correct'); +my $date_in_future = dt_from_string(); +$date_in_future = $date_in_future->add_duration( DateTime::Duration->new( days => 1 ) ); +AddReserve( + { + branchcode => 'CPL', + borrowernumber => $borrowernumber_tmp_1, + biblionumber => $bibnum, + priority => 3, + reservation_date => $date_in_future + } +); +AddReserve( + { + branchcode => 'CPL', + borrowernumber => $borrowernumber_tmp_2, + biblionumber => $bibnum, + priority => 4, + reservation_date => $date_in_future + } +); +my @r1 = Koha::Holds->search( { borrowernumber => $borrowernumber_tmp_1 } )->as_list; +my @r2 = Koha::Holds->search( { borrowernumber => $borrowernumber_tmp_2 } )->as_list; +is( $r1[0]->priority, 3, 'priority for hold in future should be correct' ); +is( $r2[0]->priority, 4, 'priority for hold not in future should be correct' ); + # end of tests for bug 12630 - #### +#### ####### Testing Bug 13113 - Prevent juvenile/children from reserving ageRestricted material >>> - #### +#### t::lib::Mocks::mock_preference( 'AgeRestrictionMarker', 'FSK|PEGI|Age|K' ); @@ -567,32 +620,44 @@ t::lib::Mocks::mock_preference( 'AgeRestrictionMarker', 'FSK|PEGI|Age|K' ); #Set the ageRestriction for the Biblio $biblio = Koha::Biblios->find($bibnum); my $record = $biblio->metadata->record; -my ( $ageres_tagid, $ageres_subfieldid ) = GetMarcFromKohaField( "biblioitems.agerestriction" ); -$record->append_fields( MARC::Field->new($ageres_tagid, '', '', $ageres_subfieldid => 'PEGI 16') ); +my ( $ageres_tagid, $ageres_subfieldid ) = GetMarcFromKohaField("biblioitems.agerestriction"); +$record->append_fields( MARC::Field->new( $ageres_tagid, '', '', $ageres_subfieldid => 'PEGI 16' ) ); C4::Biblio::ModBiblio( $record, $bibnum, $frameworkcode ); -is( C4::Reserves::CanBookBeReserved($borrowernumber, $biblionumber)->{status} , 'OK', "Reserving an ageRestricted Biblio without a borrower dateofbirth succeeds" ); +is( + C4::Reserves::CanBookBeReserved( $borrowernumber, $biblionumber )->{status}, 'OK', + "Reserving an ageRestricted Biblio without a borrower dateofbirth succeeds" +); #Set the dateofbirth for the Borrower making them "too young". $borrower->{dateofbirth} = DateTime->now->add( years => -15 ); -Koha::Patrons->find( $borrowernumber )->set({ dateofbirth => $borrower->{dateofbirth} })->store; +Koha::Patrons->find($borrowernumber)->set( { dateofbirth => $borrower->{dateofbirth} } )->store; -is( C4::Reserves::CanBookBeReserved($borrowernumber, $biblionumber)->{status} , 'ageRestricted', "Reserving a 'PEGI 16' Biblio by a 15 year old borrower fails"); +is( + C4::Reserves::CanBookBeReserved( $borrowernumber, $biblionumber )->{status}, 'ageRestricted', + "Reserving a 'PEGI 16' Biblio by a 15 year old borrower fails" +); #Set the dateofbirth for the Borrower making them "too old". $borrower->{dateofbirth} = DateTime->now->add( years => -30 ); -Koha::Patrons->find( $borrowernumber )->set({ dateofbirth => $borrower->{dateofbirth} })->store; +Koha::Patrons->find($borrowernumber)->set( { dateofbirth => $borrower->{dateofbirth} } )->store; -is( C4::Reserves::CanBookBeReserved($borrowernumber, $biblionumber)->{status} , 'OK', "Reserving a 'PEGI 16' Biblio by a 30 year old borrower succeeds"); +is( + C4::Reserves::CanBookBeReserved( $borrowernumber, $biblionumber )->{status}, 'OK', + "Reserving a 'PEGI 16' Biblio by a 30 year old borrower succeeds" +); -is( C4::Reserves::CanBookBeReserved($borrowernumber, $biblio_with_no_item->biblionumber)->{status} , '', "Biblio with no item. Status is empty"); - #### +is( + C4::Reserves::CanBookBeReserved( $borrowernumber, $biblio_with_no_item->biblionumber )->{status}, '', + "Biblio with no item. Status is empty" +); +#### ####### EO Bug 13113 <<< - #### +#### -ok( C4::Reserves::IsAvailableForItemLevelRequest($item, $patron), "Reserving a book on item level" ); +ok( C4::Reserves::IsAvailableForItemLevelRequest( $item, $patron ), "Reserving a book on item level" ); -my $pickup_branch = $builder->build({ source => 'Branch' })->{ branchcode }; +my $pickup_branch = $builder->build( { source => 'Branch' } )->{branchcode}; t::lib::Mocks::mock_preference( 'UseBranchTransferLimits', '1' ); t::lib::Mocks::mock_preference( 'BranchTransferLimitsType', 'itemtype' ); my $limit = Koha::Item::Transfer::Limit->new( @@ -602,17 +667,20 @@ my $limit = Koha::Item::Transfer::Limit->new( itemtype => $item->effective_itemtype, } )->store(); -is( C4::Reserves::IsAvailableForItemLevelRequest($item, $patron, $pickup_branch), 0, "Item level request not available due to transfer limit" ); -t::lib::Mocks::mock_preference( 'UseBranchTransferLimits', '0' ); +is( + C4::Reserves::IsAvailableForItemLevelRequest( $item, $patron, $pickup_branch ), 0, + "Item level request not available due to transfer limit" +); +t::lib::Mocks::mock_preference( 'UseBranchTransferLimits', '0' ); -my $categorycode = $borrower->{categorycode}; +my $categorycode = $borrower->{categorycode}; my $holdingbranch = $item->{holdingbranch}; Koha::CirculationRules->set_rules( { categorycode => $categorycode, itemtype => $item->effective_itemtype, branchcode => $holdingbranch, - rules => { + rules => { onshelfholds => 1, } } @@ -620,9 +688,9 @@ Koha::CirculationRules->set_rules( # tests for MoveReserve in relation to ConfirmFutureHolds (BZ 14526) # hold from A pos 1, today, no fut holds: MoveReserve should fill it -$dbh->do('DELETE FROM reserves', undef, ($bibnum)); -t::lib::Mocks::mock_preference('ConfirmFutureHolds', 0); -t::lib::Mocks::mock_preference('AllowHoldDateInFuture', 1); +$dbh->do( 'DELETE FROM reserves', undef, ($bibnum) ); +t::lib::Mocks::mock_preference( 'ConfirmFutureHolds', 0 ); +t::lib::Mocks::mock_preference( 'AllowHoldDateInFuture', 1 ); AddReserve( { branchcode => $branch_1, @@ -632,10 +700,11 @@ AddReserve( } ); MoveReserve( $item->itemnumber, $borrowernumber ); -($status)=CheckReserves( $item ); -is( $status, '', 'MoveReserve filled hold'); +($status) = CheckReserves($item); +is( $status, '', 'MoveReserve filled hold' ); + # hold from A waiting, today, no fut holds: MoveReserve should fill it -my $other_item = $builder->build_sample_item({ biblionumber => $biblio->id }); +my $other_item = $builder->build_sample_item( { biblionumber => $biblio->id } ); AddReserve( { branchcode => $branch_1, @@ -647,67 +716,71 @@ AddReserve( } ); MoveReserve( $item->itemnumber, $borrowernumber ); -($status)=CheckReserves( $item ); -is( $status, '', 'MoveReserve filled waiting hold'); +($status) = CheckReserves($item); +is( $status, '', 'MoveReserve filled waiting hold' ); + # hold from A pos 1, tomorrow, no fut holds: not filled -$resdate= dt_from_string(); -$resdate->add_duration(DateTime::Duration->new(days => 1)); +$resdate = dt_from_string(); +$resdate->add_duration( DateTime::Duration->new( days => 1 ) ); AddReserve( { - branchcode => $branch_1, - borrowernumber => $borrowernumber, - biblionumber => $bibnum, - priority => 1, + branchcode => $branch_1, + borrowernumber => $borrowernumber, + biblionumber => $bibnum, + priority => 1, reservation_date => $resdate, } ); MoveReserve( $item->itemnumber, $borrowernumber ); -($status)=CheckReserves( $item, 1 ); -is( $status, 'Reserved', 'MoveReserve did not fill future hold'); -$dbh->do('DELETE FROM reserves', undef, ($bibnum)); +($status) = CheckReserves( $item, 1 ); +is( $status, 'Reserved', 'MoveReserve did not fill future hold' ); +$dbh->do( 'DELETE FROM reserves', undef, ($bibnum) ); + # hold from A pos 1, tomorrow, fut holds=2: MoveReserve should fill it -t::lib::Mocks::mock_preference('ConfirmFutureHolds', 2); +t::lib::Mocks::mock_preference( 'ConfirmFutureHolds', 2 ); AddReserve( { - branchcode => $branch_1, - borrowernumber => $borrowernumber, - biblionumber => $bibnum, - priority => 1, + branchcode => $branch_1, + borrowernumber => $borrowernumber, + biblionumber => $bibnum, + priority => 1, reservation_date => $resdate, } ); MoveReserve( $item->itemnumber, $borrowernumber ); -($status)=CheckReserves( $item, undef, 2 ); -is( $status, '', 'MoveReserve filled future hold now'); +($status) = CheckReserves( $item, undef, 2 ); +is( $status, '', 'MoveReserve filled future hold now' ); + # hold from A waiting, tomorrow, fut holds=2: MoveReserve should fill it AddReserve( { - branchcode => $branch_1, - borrowernumber => $borrowernumber, - biblionumber => $bibnum, - priority => 1, + branchcode => $branch_1, + borrowernumber => $borrowernumber, + biblionumber => $bibnum, + priority => 1, reservation_date => $resdate, } ); MoveReserve( $item->itemnumber, $borrowernumber ); -($status)=CheckReserves( $item, undef, 2 ); -is( $status, '', 'MoveReserve filled future waiting hold now'); +($status) = CheckReserves( $item, undef, 2 ); +is( $status, '', 'MoveReserve filled future waiting hold now' ); + # hold from A pos 1, today+3, fut holds=2: MoveReserve should not fill it -$resdate= dt_from_string(); -$resdate->add_duration(DateTime::Duration->new(days => 3)); +$resdate = dt_from_string(); +$resdate->add_duration( DateTime::Duration->new( days => 3 ) ); AddReserve( { - branchcode => $branch_1, - borrowernumber => $borrowernumber, - biblionumber => $bibnum, - priority => 1, + branchcode => $branch_1, + borrowernumber => $borrowernumber, + biblionumber => $bibnum, + priority => 1, reservation_date => $resdate, } ); MoveReserve( $item->itemnumber, $borrowernumber ); -($status)=CheckReserves( $item, 3 ); -is( $status, 'Reserved', 'MoveReserve did not fill future hold of 3 days'); -$dbh->do('DELETE FROM reserves', undef, ($bibnum)); +($status) = CheckReserves( $item, 3 ); +is( $status, 'Reserved', 'MoveReserve did not fill future hold of 3 days' ); +$dbh->do( 'DELETE FROM reserves', undef, ($bibnum) ); $cache->clear_from_cache("MarcStructure-0-$frameworkcode"); $cache->clear_from_cache("MarcStructure-1-$frameworkcode"); @@ -717,63 +790,73 @@ subtest '_koha_notify_reserve() tests' => sub { plan tests => 4; - my $branch = $builder->build_object({ - class => 'Koha::Libraries', - value => { - branchemail => 'branch@e.mail', - branchreplyto => 'branch@reply.to', - pickup_location => 1 + my $branch = $builder->build_object( + { + class => 'Koha::Libraries', + value => { + branchemail => 'branch@e.mail', + branchreplyto => 'branch@reply.to', + pickup_location => 1 + } } - }); - my $item = $builder->build_sample_item({ - homebranch => $branch->branchcode, - holdingbranch => $branch->branchcode - }); + ); + my $item = $builder->build_sample_item( + { + homebranch => $branch->branchcode, + holdingbranch => $branch->branchcode + } + ); my $wants_hold_and_email = { wants_digest => '0', - transports => { - sms => 'HOLD', + transports => { + sms => 'HOLD', email => 'HOLD', - }, + }, letter_code => 'HOLD' }; - my $mp = Test::MockModule->new( 'C4::Members::Messaging' ); + my $mp = Test::MockModule->new('C4::Members::Messaging'); - $mp->mock("GetMessagingPreferences",$wants_hold_and_email); + $mp->mock( "GetMessagingPreferences", $wants_hold_and_email ); $dbh->do('DELETE FROM letter'); - my $email_hold_notice = $builder->build({ + my $email_hold_notice = $builder->build( + { source => 'Letter', - value => { + value => { message_transport_type => 'email', - branchcode => '', - code => 'HOLD', - module => 'reserves', - lang => 'default', + branchcode => '', + code => 'HOLD', + module => 'reserves', + lang => 'default', } - }); + } + ); - my $sms_hold_notice = $builder->build({ + my $sms_hold_notice = $builder->build( + { source => 'Letter', - value => { + value => { message_transport_type => 'sms', - branchcode => '', - code => 'HOLD', - module => 'reserves', - lang=>'default', + branchcode => '', + code => 'HOLD', + module => 'reserves', + lang => 'default', } - }); + } + ); - my $hold_borrower = $builder->build({ + my $hold_borrower = $builder->build( + { source => 'Borrower', - value => { - smsalertnumber=>'5555555555', - email=>'a@b.com', + value => { + smsalertnumber => '5555555555', + email => 'a@b.com', } - })->{borrowernumber}; + } + )->{borrowernumber}; C4::Reserves::AddReserve( { @@ -783,19 +866,23 @@ subtest '_koha_notify_reserve() tests' => sub { } ); - ModReserveAffect($item->itemnumber, $hold_borrower, 0); - my $sms_message_address = $schema->resultset('MessageQueue')->search({ - letter_code => 'HOLD', + ModReserveAffect( $item->itemnumber, $hold_borrower, 0 ); + my $sms_message_address = $schema->resultset('MessageQueue')->search( + { + letter_code => 'HOLD', message_transport_type => 'sms', - borrowernumber => $hold_borrower, - })->next()->to_address(); - is($sms_message_address, undef ,"We should not populate the sms message with the sms number, sending will do so"); + borrowernumber => $hold_borrower, + } + )->next()->to_address(); + is( $sms_message_address, undef, "We should not populate the sms message with the sms number, sending will do so" ); - my $email = $schema->resultset('MessageQueue')->search({ - letter_code => 'HOLD', + my $email = $schema->resultset('MessageQueue')->search( + { + letter_code => 'HOLD', message_transport_type => 'email', - borrowernumber => $hold_borrower, - })->next(); + borrowernumber => $hold_borrower, + } + )->next(); my $email_to_address = $email->to_address(); is( $email_to_address, undef, @@ -811,19 +898,19 @@ subtest '_koha_notify_reserve() tests' => sub { subtest 'ReservesNeedReturns' => sub { plan tests => 18; - my $library = $builder->build_object( { class => 'Koha::Libraries' } ); - my $item_info = { - homebranch => $library->branchcode, - holdingbranch => $library->branchcode, + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); + my $item_info = { + homebranch => $library->branchcode, + holdingbranch => $library->branchcode, }; - my $item = $builder->build_sample_item($item_info); - my $patron = $builder->build_object( + my $item = $builder->build_sample_item($item_info); + my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { branchcode => $library->branchcode, } } ); - my $patron_2 = $builder->build_object( + my $patron_2 = $builder->build_object( { class => 'Koha::Patrons', value => { branchcode => $library->branchcode, } @@ -832,16 +919,17 @@ subtest 'ReservesNeedReturns' => sub { my $priority = 1; - t::lib::Mocks::mock_preference('ReservesNeedReturns', 1); # Test with feature disabled + t::lib::Mocks::mock_preference( 'ReservesNeedReturns', 1 ); # Test with feature disabled my $hold = place_item_hold( $patron, $item, $library, $priority ); is( $hold->priority, $priority, 'If ReservesNeedReturns is 1, priority must not have been set to changed' ); - is( $hold->found, undef, 'If ReservesNeedReturns is 1, found must not have been set waiting' ); + is( $hold->found, undef, 'If ReservesNeedReturns is 1, found must not have been set waiting' ); $hold->delete; - t::lib::Mocks::mock_preference('ReservesNeedReturns', 0); # '0' means 'Automatically mark a hold as found and waiting' + t::lib::Mocks::mock_preference( 'ReservesNeedReturns', 0 ) + ; # '0' means 'Automatically mark a hold as found and waiting' $hold = place_item_hold( $patron, $item, $library, $priority ); - is( $hold->priority, 0, 'If ReservesNeedReturns is 0 and no other status, priority must have been set to 0' ); - is( $hold->found, 'W', 'If ReservesNeedReturns is 0 and no other status, found must have been set waiting' ); + is( $hold->priority, 0, 'If ReservesNeedReturns is 0 and no other status, priority must have been set to 0' ); + is( $hold->found, 'W', 'If ReservesNeedReturns is 0 and no other status, found must have been set waiting' ); $hold->delete; $item->onloan('2010-01-01')->store; @@ -849,63 +937,71 @@ subtest 'ReservesNeedReturns' => sub { is( $hold->priority, 1, 'If ReservesNeedReturns is 0 but item onloan priority must be set to 1' ); $hold->delete; - t::lib::Mocks::mock_preference('AllowHoldsOnDamagedItems', 0); # '0' means damaged holds not allowed + t::lib::Mocks::mock_preference( 'AllowHoldsOnDamagedItems', 0 ); # '0' means damaged holds not allowed $item->onloan(undef)->damaged(1)->store; $hold = place_item_hold( $patron, $item, $library, $priority ); - is( $hold->priority, 1, 'If ReservesNeedReturns is 0 but item damaged and not allowed holds on damaged items priority must be set to 1' ); + is( + $hold->priority, 1, + 'If ReservesNeedReturns is 0 but item damaged and not allowed holds on damaged items priority must be set to 1' + ); $hold->delete; - t::lib::Mocks::mock_preference('AllowHoldsOnDamagedItems', 1); # '0' means damaged holds not allowed + t::lib::Mocks::mock_preference( 'AllowHoldsOnDamagedItems', 1 ); # '0' means damaged holds not allowed $hold = place_item_hold( $patron, $item, $library, $priority ); is( $hold->priority, 0, 'If ReservesNeedReturns is 0 and damaged holds allowed, priority must have been set to 0' ); - is( $hold->found, 'W', 'If ReservesNeedReturns is 0 and damaged holds allowed, found must have been set waiting' ); + is( $hold->found, 'W', 'If ReservesNeedReturns is 0 and damaged holds allowed, found must have been set waiting' ); $hold->delete; my $hold_1 = place_item_hold( $patron, $item, $library, $priority ); - is( $hold_1->found, 'W', 'First hold on item is set to waiting with ReservesNeedReturns set to 0' ); - is( $hold_1->priority, 0, 'First hold on item is set to waiting with ReservesNeedReturns set to 0' ); + is( $hold_1->found, 'W', 'First hold on item is set to waiting with ReservesNeedReturns set to 0' ); + is( $hold_1->priority, 0, 'First hold on item is set to waiting with ReservesNeedReturns set to 0' ); $hold = place_item_hold( $patron_2, $item, $library, $priority ); is( $hold->priority, 1, 'If ReservesNeedReturns is 0 but item already on hold priority must be set to 1' ); $hold->delete; $hold_1->delete; - my $transfer = $builder->build_object({ - class => "Koha::Item::Transfers", - value => { - itemnumber => $item->itemnumber, - datearrived => undef, - datecancelled => undef + my $transfer = $builder->build_object( + { + class => "Koha::Item::Transfers", + value => { + itemnumber => $item->itemnumber, + datearrived => undef, + datecancelled => undef + } } - }); + ); $item->damaged(0)->store; $hold = place_item_hold( $patron, $item, $library, $priority ); - is( $hold->found, undef, 'If ReservesNeedReturns is 0 but item in transit the hold must not be set to waiting' ); - is( $hold->priority, 1, 'If ReservesNeedReturns is 0 but item in transit the hold must not be set to waiting' ); + is( $hold->found, undef, 'If ReservesNeedReturns is 0 but item in transit the hold must not be set to waiting' ); + is( $hold->priority, 1, 'If ReservesNeedReturns is 0 but item in transit the hold must not be set to waiting' ); $hold->delete; $transfer->delete; $hold = place_item_hold( $patron, $item, $library, $priority ); - is( $hold->priority, 0, 'If ReservesNeedReturns is 0 and no other status, priority must have been set to 0' ); - is( $hold->found, 'W', 'If ReservesNeedReturns is 0 and no other status, found must have been set waiting' ); + is( $hold->priority, 0, 'If ReservesNeedReturns is 0 and no other status, priority must have been set to 0' ); + is( $hold->found, 'W', 'If ReservesNeedReturns is 0 and no other status, found must have been set waiting' ); $hold_1 = place_item_hold( $patron, $item, $library, $priority ); is( $hold_1->priority, 1, 'If ReservesNeedReturns is 0 but item has a hold priority is 1' ); - $hold_1->suspend(1)->store; # We suspend the hold - $hold->delete; # Delete the waiting hold + $hold_1->suspend(1)->store; # We suspend the hold + $hold->delete; # Delete the waiting hold $hold = place_item_hold( $patron, $item, $library, $priority ); - is( $hold->priority, 0, 'If ReservesNeedReturns is 0 and other hold(s) suspended, priority must have been set to 0' ); - is( $hold->found, 'W', 'If ReservesNeedReturns is 0 and other hold(s) suspended, found must have been set waiting' ); + is( + $hold->priority, 0, + 'If ReservesNeedReturns is 0 and other hold(s) suspended, priority must have been set to 0' + ); + is( + $hold->found, 'W', + 'If ReservesNeedReturns is 0 and other hold(s) suspended, found must have been set waiting' + ); - - - - t::lib::Mocks::mock_preference('ReservesNeedReturns', 1); # Don't affect other tests + t::lib::Mocks::mock_preference( 'ReservesNeedReturns', 1 ); # Don't affect other tests }; subtest 'ChargeReserveFee tests' => sub { plan tests => 8; - my $library = $builder->build_object({ class => 'Koha::Libraries' }); - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $fee = 20; my $title = 'A title'; @@ -915,14 +1011,14 @@ subtest 'ChargeReserveFee tests' => sub { my $line = C4::Reserves::ChargeReserveFee( $patron->id, $fee, $title ); - is( ref($line), 'Koha::Account::Line' , 'Returns a Koha::Account::Line object'); + is( ref($line), 'Koha::Account::Line', 'Returns a Koha::Account::Line object' ); ok( $line->is_debit, 'Generates a debit line' ); - is( $line->debit_type_code, 'RESERVE' , 'generates RESERVE debit_type'); - is( $line->borrowernumber, $patron->id , 'generated line belongs to the passed patron'); - is( $line->amount, $fee , 'amount set correctly'); - is( $line->amountoutstanding, $fee , 'amountoutstanding set correctly'); - is( $line->description, "$title" , 'description is title of reserved item'); - is( $line->branchcode, $library->id , "Library id is picked from userenv and stored correctly" ); + is( $line->debit_type_code, 'RESERVE', 'generates RESERVE debit_type' ); + is( $line->borrowernumber, $patron->id, 'generated line belongs to the passed patron' ); + is( $line->amount, $fee, 'amount set correctly' ); + is( $line->amountoutstanding, $fee, 'amountoutstanding set correctly' ); + is( $line->description, "$title", 'description is title of reserved item' ); + is( $line->branchcode, $library->id, "Library id is picked from userenv and stored correctly" ); }; subtest 'reserves.item_level_hold' => sub { @@ -955,14 +1051,17 @@ subtest 'reserves.item_level_hold' => sub { ModReserveAffect( $item->itemnumber, $patron->borrowernumber, 1 ); my $mock = Test::MockModule->new('Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue'); - $mock->mock( 'enqueue', sub { - my ( $self, $args ) = @_; - is_deeply( - $args->{biblio_ids}, - [ $hold->biblionumber ], - "AlterPriority triggers a holds queue update for the related biblio" - ); - } ); + $mock->mock( + 'enqueue', + sub { + my ( $self, $args ) = @_; + is_deeply( + $args->{biblio_ids}, + [ $hold->biblionumber ], + "AlterPriority triggers a holds queue update for the related biblio" + ); + } + ); t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 1 ); t::lib::Mocks::mock_preference( 'HoldsLog', 1 ); @@ -1012,7 +1111,10 @@ subtest 'reserves.item_level_hold' => sub { ); my $hold = Koha::Holds->find($reserve_id); - is( $hold->item_level_hold, 0, 'item_level_hold should not be set when AddReserve is called without a specific item' ); + is( + $hold->item_level_hold, 0, + 'item_level_hold should not be set when AddReserve is called without a specific item' + ); # Mark it waiting ModReserveAffect( $item->itemnumber, $patron->borrowernumber, 1 ); @@ -1037,11 +1139,13 @@ subtest 'MoveReserve additional test' => sub { # Create the items and patrons we need my $biblio = $builder->build_sample_biblio(); - my $itype = $builder->build_object({ class => "Koha::ItemTypes", value => { notforloan => 0 } }); - my $item_1 = $builder->build_sample_item({ biblionumber => $biblio->biblionumber,notforloan => 0, itype => $itype->itemtype }); - my $item_2 = $builder->build_sample_item({ biblionumber => $biblio->biblionumber, notforloan => 0, itype => $itype->itemtype }); - my $patron_1 = $builder->build_object({ class => "Koha::Patrons" }); - my $patron_2 = $builder->build_object({ class => "Koha::Patrons" }); + my $itype = $builder->build_object( { class => "Koha::ItemTypes", value => { notforloan => 0 } } ); + my $item_1 = $builder->build_sample_item( + { biblionumber => $biblio->biblionumber, notforloan => 0, itype => $itype->itemtype } ); + my $item_2 = $builder->build_sample_item( + { biblionumber => $biblio->biblionumber, notforloan => 0, itype => $itype->itemtype } ); + my $patron_1 = $builder->build_object( { class => "Koha::Patrons" } ); + my $patron_2 = $builder->build_object( { class => "Koha::Patrons" } ); # Place a hold on the title for both patrons my $reserve_1 = AddReserve( @@ -1062,16 +1166,22 @@ subtest 'MoveReserve additional test' => sub { itemnumber => $item_1->itemnumber, } ); - is($patron_1->holds->next()->reserve_id, $reserve_1, "The 1st patron has a hold"); - is($patron_2->holds->next()->reserve_id, $reserve_2, "The 2nd patron has a hold"); + is( $patron_1->holds->next()->reserve_id, $reserve_1, "The 1st patron has a hold" ); + is( $patron_2->holds->next()->reserve_id, $reserve_2, "The 2nd patron has a hold" ); # Fake the holds queue - $dbh->do(q{INSERT INTO hold_fill_targets VALUES (?, ?, ?, ?, ?,?)},undef,($patron_1->borrowernumber,$biblio->biblionumber,$item_1->itemnumber,$item_1->homebranch,0,$reserve_1)); + $dbh->do( + q{INSERT INTO hold_fill_targets VALUES (?, ?, ?, ?, ?,?)}, undef, + ( $patron_1->borrowernumber, $biblio->biblionumber, $item_1->itemnumber, $item_1->homebranch, 0, $reserve_1 ) + ); # The 2nd hold should be filed even if the item is preselected for the first hold - MoveReserve($item_1->itemnumber,$patron_2->borrowernumber); - is($patron_2->holds->count, 0, "The 2nd patrons no longer has a hold"); - is($patron_2->old_holds->next()->reserve_id, $reserve_2, "The 2nd patrons hold was filled and moved to old holds"); + MoveReserve( $item_1->itemnumber, $patron_2->borrowernumber ); + is( $patron_2->holds->count, 0, "The 2nd patrons no longer has a hold" ); + is( + $patron_2->old_holds->next()->reserve_id, $reserve_2, + "The 2nd patrons hold was filled and moved to old holds" + ); }; @@ -1082,9 +1192,8 @@ subtest 'RevertWaitingStatus' => sub { # Create the items and patrons we need my $biblio = $builder->build_sample_biblio(); my $library = $builder->build_object( { class => 'Koha::Libraries' } ); - my $itype = $builder->build_object( - { class => "Koha::ItemTypes", value => { notforloan => 0 } } ); - my $item_1 = $builder->build_sample_item( + my $itype = $builder->build_object( { class => "Koha::ItemTypes", value => { notforloan => 0 } } ); + my $item_1 = $builder->build_sample_item( { biblionumber => $biblio->biblionumber, itype => $itype->itemtype, @@ -1098,10 +1207,10 @@ subtest 'RevertWaitingStatus' => sub { # Place a hold on the title for both patrons my $priority = 1; - my $hold_1 = place_item_hold( $patron_1, $item_1, $library, $priority ); - my $hold_2 = place_item_hold( $patron_2, $item_1, $library, $priority ); - my $hold_3 = place_item_hold( $patron_3, $item_1, $library, $priority ); - my $hold_4 = place_item_hold( $patron_4, $item_1, $library, $priority ); + my $hold_1 = place_item_hold( $patron_1, $item_1, $library, $priority ); + my $hold_2 = place_item_hold( $patron_2, $item_1, $library, $priority ); + my $hold_3 = place_item_hold( $patron_3, $item_1, $library, $priority ); + my $hold_4 = place_item_hold( $patron_4, $item_1, $library, $priority ); $hold_1->set_waiting; AddIssue( $patron_3, $item_1->barcode, undef, 'revert' ); @@ -1122,7 +1231,7 @@ subtest 'CheckReserves additional tests' => sub { plan tests => 8; - my $item = $builder->build_sample_item; + my $item = $builder->build_sample_item; my $reserve1 = $builder->build_object( { class => "Koha::Holds", @@ -1184,40 +1293,47 @@ subtest 'CheckReserves additional tests' => sub { } ); - ModReserveAffect( $item->itemnumber, $reserve1->borrowernumber, 1, - $reserve1->reserve_id ); - my ( $status, $matched_reserve, $possible_reserves ) = - CheckReserves( $item ); + ModReserveAffect( + $item->itemnumber, $reserve1->borrowernumber, 1, + $reserve1->reserve_id + ); + my ( $status, $matched_reserve, $possible_reserves ) = CheckReserves($item); is( $status, 'Transferred', "We found a reserve" ); - is( $matched_reserve->{reserve_id}, - $reserve1->reserve_id, "We got the Transit reserve" ); + is( + $matched_reserve->{reserve_id}, + $reserve1->reserve_id, "We got the Transit reserve" + ); is( scalar @$possible_reserves, 2, 'We do get both reserves' ); - my $patron_B = $builder->build_object({ class => "Koha::Patrons" }); - my $item_A = $builder->build_sample_item; - my $item_B = $builder->build_sample_item({ - homebranch => $patron_B->branchcode, - biblionumber => $item_A->biblionumber, - itype => $item_A->itype - }); + my $patron_B = $builder->build_object( { class => "Koha::Patrons" } ); + my $item_A = $builder->build_sample_item; + my $item_B = $builder->build_sample_item( + { + homebranch => $patron_B->branchcode, + biblionumber => $item_A->biblionumber, + itype => $item_A->itype + } + ); Koha::CirculationRules->set_rules( { branchcode => undef, categorycode => undef, itemtype => $item_A->itype, rules => { - reservesallowed => 25, + reservesallowed => 25, holds_per_record => 1, } } ); - Koha::CirculationRules->set_rule({ - branchcode => undef, - itemtype => $item_A->itype, - rule_name => 'holdallowed', - rule_value => 'from_home_library' - }); + Koha::CirculationRules->set_rule( + { + branchcode => undef, + itemtype => $item_A->itype, + rule_name => 'holdallowed', + rule_value => 'from_home_library' + } + ); my $reserve_id = AddReserve( { branchcode => $patron_B->branchcode, @@ -1228,32 +1344,35 @@ subtest 'CheckReserves additional tests' => sub { } ); - ok( $reserve_id, "We can place a record level hold because one item is owned by patron's home library"); - t::lib::Mocks::mock_preference('ReservesControlBranch', 'ItemHomeLibrary'); - ( $status, $matched_reserve, $possible_reserves ) = CheckReserves( $item_A ); - is( $status, "", "We do not fill the hold with item A because it is not from the patron's homebranch"); - Koha::CirculationRules->set_rule({ - branchcode => $item_A->homebranch, - itemtype => $item_A->itype, - rule_name => 'holdallowed', - rule_value => 'from_any_library' - }); - ( $status, $matched_reserve, $possible_reserves ) = CheckReserves( $item_A ); - is( $status, "Reserved", "We fill the hold with item A because item's branch rule says allow any"); - + ok( $reserve_id, "We can place a record level hold because one item is owned by patron's home library" ); + t::lib::Mocks::mock_preference( 'ReservesControlBranch', 'ItemHomeLibrary' ); + ( $status, $matched_reserve, $possible_reserves ) = CheckReserves($item_A); + is( $status, "", "We do not fill the hold with item A because it is not from the patron's homebranch" ); + Koha::CirculationRules->set_rule( + { + branchcode => $item_A->homebranch, + itemtype => $item_A->itype, + rule_name => 'holdallowed', + rule_value => 'from_any_library' + } + ); + ( $status, $matched_reserve, $possible_reserves ) = CheckReserves($item_A); + is( $status, "Reserved", "We fill the hold with item A because item's branch rule says allow any" ); # Changing the control branch should change only the rule we get - t::lib::Mocks::mock_preference('ReservesControlBranch', 'PatronLibrary'); - ( $status, $matched_reserve, $possible_reserves ) = CheckReserves( $item_A ); - is( $status, "", "We do not fill the hold with item A because it is not from the patron's homebranch"); - Koha::CirculationRules->set_rule({ - branchcode => $patron_B->branchcode, - itemtype => $item_A->itype, - rule_name => 'holdallowed', - rule_value => 'from_any_library' - }); - ( $status, $matched_reserve, $possible_reserves ) = CheckReserves( $item_A ); - is( $status, "Reserved", "We fill the hold with item A because patron's branch rule says allow any"); + t::lib::Mocks::mock_preference( 'ReservesControlBranch', 'PatronLibrary' ); + ( $status, $matched_reserve, $possible_reserves ) = CheckReserves($item_A); + is( $status, "", "We do not fill the hold with item A because it is not from the patron's homebranch" ); + Koha::CirculationRules->set_rule( + { + branchcode => $patron_B->branchcode, + itemtype => $item_A->itype, + rule_name => 'holdallowed', + rule_value => 'from_any_library' + } + ); + ( $status, $matched_reserve, $possible_reserves ) = CheckReserves($item_A); + is( $status, "Reserved", "We fill the hold with item A because patron's branch rule says allow any" ); }; @@ -1263,46 +1382,64 @@ subtest 'AllowHoldOnPatronPossession test' => sub { # Create the items and patrons we need my $biblio = $builder->build_sample_biblio(); - my $itype = $builder->build_object({ class => "Koha::ItemTypes", value => { notforloan => 0 } }); - my $item = $builder->build_sample_item({ biblionumber => $biblio->biblionumber,notforloan => 0, itype => $itype->itemtype }); - my $patron = $builder->build_object({ class => "Koha::Patrons", - value => { branchcode => $item->homebranch }}); + my $itype = $builder->build_object( { class => "Koha::ItemTypes", value => { notforloan => 0 } } ); + my $item = $builder->build_sample_item( + { biblionumber => $biblio->biblionumber, notforloan => 0, itype => $itype->itemtype } ); + my $patron = $builder->build_object( + { + class => "Koha::Patrons", + value => { branchcode => $item->homebranch } + } + ); - C4::Circulation::AddIssue($patron, - $item->barcode); - t::lib::Mocks::mock_preference('AllowHoldsOnPatronsPossessions', 0); + C4::Circulation::AddIssue( + $patron, + $item->barcode + ); + t::lib::Mocks::mock_preference( 'AllowHoldsOnPatronsPossessions', 0 ); - is(C4::Reserves::CanBookBeReserved($patron->borrowernumber, - $item->biblionumber)->{status}, - 'alreadypossession', - 'Patron cannot place hold on a book loaned to itself'); + is( + C4::Reserves::CanBookBeReserved( + $patron->borrowernumber, + $item->biblionumber + )->{status}, + 'alreadypossession', + 'Patron cannot place hold on a book loaned to itself' + ); - is(C4::Reserves::CanItemBeReserved( $patron, $item )->{status}, - 'alreadypossession', - 'Patron cannot place hold on an item loaned to itself'); + is( + C4::Reserves::CanItemBeReserved( $patron, $item )->{status}, + 'alreadypossession', + 'Patron cannot place hold on an item loaned to itself' + ); - t::lib::Mocks::mock_preference('AllowHoldsOnPatronsPossessions', 1); + t::lib::Mocks::mock_preference( 'AllowHoldsOnPatronsPossessions', 1 ); - is(C4::Reserves::CanBookBeReserved($patron->borrowernumber, - $item->biblionumber)->{status}, - 'OK', - 'Patron can place hold on a book loaned to itself'); + is( + C4::Reserves::CanBookBeReserved( + $patron->borrowernumber, + $item->biblionumber + )->{status}, + 'OK', + 'Patron can place hold on a book loaned to itself' + ); - is(C4::Reserves::CanItemBeReserved( $patron, $item )->{status}, - 'OK', - 'Patron can place hold on an item loaned to itself'); + is( + C4::Reserves::CanItemBeReserved( $patron, $item )->{status}, + 'OK', + 'Patron can place hold on an item loaned to itself' + ); }; subtest 'MergeHolds' => sub { plan tests => 1; - my $biblio_1 = $builder->build_sample_biblio(); - my $biblio_2 = $builder->build_sample_biblio(); - my $library = $builder->build_object( { class => 'Koha::Libraries' } ); - my $itype = $builder->build_object( - { class => "Koha::ItemTypes", value => { notforloan => 0 } } ); - my $item_1 = $builder->build_sample_item( + my $biblio_1 = $builder->build_sample_biblio(); + my $biblio_2 = $builder->build_sample_biblio(); + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); + my $itype = $builder->build_object( { class => "Koha::ItemTypes", value => { notforloan => 0 } } ); + my $item_1 = $builder->build_sample_item( { biblionumber => $biblio_1->biblionumber, itype => $itype->itemtype, @@ -1316,7 +1453,7 @@ subtest 'MergeHolds' => sub { place_item_hold( $patron_1, $item_1, $library, $priority ); # Move and make sure hold is now on $biblio_2 - C4::Reserves::MergeHolds($dbh, $biblio_2->biblionumber, $biblio_1->biblionumber); + C4::Reserves::MergeHolds( $dbh, $biblio_2->biblionumber, $biblio_1->biblionumber ); is( $biblio_2->holds->count, 1, 'Hold has been transferred' ); }; @@ -1324,7 +1461,7 @@ subtest 'ModReserveAffect logging' => sub { plan tests => 4; - my $item = $builder->build_sample_item; + my $item = $builder->build_sample_item; my $patron = $builder->build_object( { class => "Koha::Patrons", @@ -1332,8 +1469,8 @@ subtest 'ModReserveAffect logging' => sub { } ); - t::lib::Mocks::mock_userenv({ patron => $patron }); - t::lib::Mocks::mock_preference('HoldsLog', 1); + t::lib::Mocks::mock_userenv( { patron => $patron } ); + t::lib::Mocks::mock_preference( 'HoldsLog', 1 ); my $reserve_id = AddReserve( { @@ -1345,7 +1482,7 @@ subtest 'ModReserveAffect logging' => sub { } ); - my $hold = Koha::Holds->find($reserve_id); + my $hold = Koha::Holds->find($reserve_id); my $previous_timestamp = '1970-01-01 12:34:56'; $hold->timestamp($previous_timestamp)->store; @@ -1363,23 +1500,25 @@ subtest 'ModReserveAffect logging' => sub { ok( $hold->is_waiting, 'Hold has been set waiting' ); isnt( $hold->timestamp, $previous_timestamp, 'The timestamp has been modified' ); - my $log = Koha::ActionLogs->search({ module => 'HOLDS', action => 'MODIFY', object => $hold->reserve_id })->next; + my $log = Koha::ActionLogs->search( { module => 'HOLDS', action => 'MODIFY', object => $hold->reserve_id } )->next; my $expected = sprintf q{'timestamp' => '%s'}, $hold->timestamp; like( $log->info, qr{$expected}, 'Timestamp logged is the current one' ); }; sub count_hold_print_messages { - my $message_count = $dbh->selectall_arrayref(q{ + my $message_count = $dbh->selectall_arrayref( + q{ SELECT COUNT(*) FROM message_queue WHERE letter_code = 'HOLD' AND message_transport_type = 'print' - }); + } + ); return $message_count->[0]->[0]; } sub place_item_hold { - my ($patron,$item,$library,$priority) = @_; + my ( $patron, $item, $library, $priority ) = @_; my $hold_id = C4::Reserves::AddReserve( { @@ -1464,14 +1603,17 @@ subtest 'AddReserve() tests' => sub { my $biblio = $builder->build_sample_biblio; my $mock = Test::MockModule->new('Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue'); - $mock->mock( 'enqueue', sub { - my ( $self, $args ) = @_; - is_deeply( - $args->{biblio_ids}, - [ $biblio->id ], - "AddReserve triggers a holds queue update for the related biblio" - ); - } ); + $mock->mock( + 'enqueue', + sub { + my ( $self, $args ) = @_; + is_deeply( + $args->{biblio_ids}, + [ $biblio->id ], + "AddReserve triggers a holds queue update for the related biblio" + ); + } + ); t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 1 ); @@ -1505,11 +1647,11 @@ subtest 'AlterPriorty() tests' => sub { $schema->storage->txn_begin; - my $library = $builder->build_object({ class => 'Koha::Libraries' }); - my $patron_1 = $builder->build_object({ class => 'Koha::Patrons' }); - my $patron_2 = $builder->build_object({ class => 'Koha::Patrons' }); - my $patron_3 = $builder->build_object({ class => 'Koha::Patrons' }); - my $biblio = $builder->build_sample_biblio; + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); + my $patron_1 = $builder->build_object( { class => 'Koha::Patrons' } ); + my $patron_2 = $builder->build_object( { class => 'Koha::Patrons' } ); + my $patron_3 = $builder->build_object( { class => 'Koha::Patrons' } ); + my $biblio = $builder->build_sample_biblio; my $reserve_id = AddReserve( { @@ -1534,14 +1676,17 @@ subtest 'AlterPriorty() tests' => sub { ); my $mock = Test::MockModule->new('Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue'); - $mock->mock( 'enqueue', sub { - my ( $self, $args ) = @_; - is_deeply( - $args->{biblio_ids}, - [ $biblio->id ], - "AlterPriority triggers a holds queue update for the related biblio" - ); - } ); + $mock->mock( + 'enqueue', + sub { + my ( $self, $args ) = @_; + is_deeply( + $args->{biblio_ids}, + [ $biblio->id ], + "AlterPriority triggers a holds queue update for the related biblio" + ); + } + ); t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 1 ); @@ -1549,7 +1694,7 @@ subtest 'AlterPriorty() tests' => sub { my $hold = Koha::Holds->find($reserve_id); - is($hold->priority,3,'Successfully altered priority to bottom'); + is( $hold->priority, 3, 'Successfully altered priority to bottom' ); t::lib::Mocks::mock_preference( 'RealTimeHoldsQueue', 0 ); @@ -1564,16 +1709,13 @@ subtest 'CanBookBeReserved() tests' => sub { $schema->storage->txn_begin; - my $library = $builder->build_object( - { class => 'Koha::Libraries', value => { pickup_location => 1 } } ); - my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); - my $itype = $builder->build_object( { class => 'Koha::ItemTypes' } ); + my $library = $builder->build_object( { class => 'Koha::Libraries', value => { pickup_location => 1 } } ); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + my $itype = $builder->build_object( { class => 'Koha::ItemTypes' } ); my $biblio = $builder->build_sample_biblio(); - my $item_1 = $builder->build_sample_item( - { biblionumber => $biblio->id, itype => $itype->id } ); - my $item_2 = $builder->build_sample_item( - { biblionumber => $biblio->id, itype => $itype->id } ); + my $item_1 = $builder->build_sample_item( { biblionumber => $biblio->id, itype => $itype->id } ); + my $item_2 = $builder->build_sample_item( { biblionumber => $biblio->id, itype => $itype->id } ); Koha::CirculationRules->delete; Koha::CirculationRules->set_rules( @@ -1609,10 +1751,14 @@ subtest 'CanBookBeReserved() tests' => sub { ## Limit on item type is 2, only one hold, success tests - my $res = CanBookBeReserved( $patron->id, $biblio->id, $library->id, - { itemtype => $itype->id } ); - is_deeply( $res, { status => 'OK' }, - 'Holds on itemtype limit not reached' ); + my $res = CanBookBeReserved( + $patron->id, $biblio->id, $library->id, + { itemtype => $itype->id } + ); + is_deeply( + $res, { status => 'OK' }, + 'Holds on itemtype limit not reached' + ); # Add a second hold, biblio-level and item type-constrained C4::Reserves::AddReserve( @@ -1627,8 +1773,10 @@ subtest 'CanBookBeReserved() tests' => sub { ## Limit on item type is 2, two holds, one of them biblio-level/item type-constrained - $res = CanBookBeReserved( $patron->id, $biblio->id, $library->id, - { itemtype => $itype->id } ); + $res = CanBookBeReserved( + $patron->id, $biblio->id, $library->id, + { itemtype => $itype->id } + ); is_deeply( $res, { status => '' }, 'Holds on itemtype limit reached' ); $schema->storage->txn_rollback; @@ -1645,12 +1793,13 @@ subtest 'CanItemBeReserved() tests' => sub { my $itype = $builder->build_object( { class => 'Koha::ItemTypes' } ); my $biblio = $builder->build_sample_biblio(); - my $item_1 = $builder->build_sample_item({ biblionumber => $biblio->id, itype => $itype->id }); - my $item_2 = $builder->build_sample_item({ biblionumber => $biblio->id, itype => $itype->id }); + my $item_1 = $builder->build_sample_item( { biblionumber => $biblio->id, itype => $itype->id } ); + my $item_2 = $builder->build_sample_item( { biblionumber => $biblio->id, itype => $itype->id } ); Koha::CirculationRules->delete; Koha::CirculationRules->set_rules( - { branchcode => undef, + { + branchcode => undef, categorycode => undef, itemtype => undef, rules => { @@ -1659,7 +1808,8 @@ subtest 'CanItemBeReserved() tests' => sub { } ); Koha::CirculationRules->set_rules( - { branchcode => undef, + { + branchcode => undef, categorycode => undef, itemtype => $itype->id, rules => { @@ -1706,24 +1856,26 @@ subtest 'DefaultHoldExpiration tests' => sub { plan tests => 2; $schema->storage->txn_begin; - t::lib::Mocks::mock_preference( 'DefaultHoldExpirationdate', 1 ); + t::lib::Mocks::mock_preference( 'DefaultHoldExpirationdate', 1 ); t::lib::Mocks::mock_preference( 'DefaultHoldExpirationdatePeriod', 365 ); t::lib::Mocks::mock_preference( 'DefaultHoldExpirationUnitOfTime', 'days;' ); - my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); - my $item = $builder->build_sample_item(); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + my $item = $builder->build_sample_item(); - my $reserve_id = AddReserve({ - branchcode => $item->homebranch, - borrowernumber => $patron->id, - biblionumber => $item->biblionumber, - }); + my $reserve_id = AddReserve( + { + branchcode => $item->homebranch, + borrowernumber => $patron->id, + biblionumber => $item->biblionumber, + } + ); my $today = dt_from_string(); - my $hold = Koha::Holds->find( $reserve_id ); + my $hold = Koha::Holds->find($reserve_id); - is( $hold->reservedate, $today->ymd, "Hold created today" ); - is( $hold->expirationdate, $today->add( days => 365)->ymd, "Reserve date set 1 year from today" ); + is( $hold->reservedate, $today->ymd, "Hold created today" ); + is( $hold->expirationdate, $today->add( days => 365 )->ymd, "Reserve date set 1 year from today" ); $schema->txn_rollback; }; @@ -1756,8 +1908,8 @@ subtest '_Findgroupreserves' => sub { C4::HoldsQueue::AddToHoldTargetMap( { $item->id => { - borrowernumber => $patron_1->id, biblionumber => $item->biblionumber, - holdingbranch => $item->holdingbranch, item_level => 0, reserve_id => $reserve_id_1 + borrowernumber => $patron_1->id, biblionumber => $item->biblionumber, + holdingbranch => $item->holdingbranch, item_level => 0, reserve_id => $reserve_id_1 } } ); @@ -1795,8 +1947,6 @@ subtest '_Findgroupreserves' => sub { is( scalar @reserves, 1, "We should still only get the item level hold that is in the map" ); is( $reserves[0]->{reserve_id}, $reserve_id_1, "We got the expected reserve which has been updated" ); - - $schema->txn_rollback; }; diff --git a/t/db_dependent/Reserves/AutoUnsuspendReserves.t b/t/db_dependent/Reserves/AutoUnsuspendReserves.t index e1fefc9fd5..29595aa3a4 100755 --- a/t/db_dependent/Reserves/AutoUnsuspendReserves.t +++ b/t/db_dependent/Reserves/AutoUnsuspendReserves.t @@ -27,7 +27,7 @@ use Koha::Database; use Koha::DateUtils qw( dt_from_string ); use Koha::Holds; -my $schema = Koha::Database->new->schema; +my $schema = Koha::Database->new->schema; my $builder = t::lib::TestBuilder->new; subtest 'AutoUnsuspendReserves test' => sub { @@ -37,33 +37,37 @@ subtest 'AutoUnsuspendReserves test' => sub { $schema->storage->txn_begin; my $today = dt_from_string(); - my $tomorrow = $today->clone->add(days=>1); + my $tomorrow = $today->clone->add( days => 1 ); # Not expired hold - my $hold_1 = $builder->build_object({ - class => 'Koha::Holds', - value => { - expirationdate => undef, - cancellationdate => undef, - priority => 5, - found => undef, - }, - }); + my $hold_1 = $builder->build_object( + { + class => 'Koha::Holds', + value => { + expirationdate => undef, + cancellationdate => undef, + priority => 5, + found => undef, + }, + } + ); - $hold_1->suspend_hold( $today ); + $hold_1->suspend_hold($today); # Expired hold - my $hold_2 = $builder->build_object({ - class => 'Koha::Holds', - value => { - expirationdate => undef, - cancellationdate => undef, - priority => 6, - found => undef, - }, - }); + my $hold_2 = $builder->build_object( + { + class => 'Koha::Holds', + value => { + expirationdate => undef, + cancellationdate => undef, + priority => 6, + found => undef, + }, + } + ); - $hold_2->suspend_hold( $tomorrow ); + $hold_2->suspend_hold($tomorrow); AutoUnsuspendReserves(); @@ -71,8 +75,8 @@ subtest 'AutoUnsuspendReserves test' => sub { $hold_1->discard_changes; $hold_2->discard_changes; - ok(!$hold_1->is_suspended, 'Hold suspended until today should be unsuspended.'); - ok( $hold_2->is_suspended, 'Hold suspended after today should be suspended.'); + ok( !$hold_1->is_suspended, 'Hold suspended until today should be unsuspended.' ); + ok( $hold_2->is_suspended, 'Hold suspended after today should be suspended.' ); subtest 'logging enabled' => sub { @@ -82,7 +86,8 @@ subtest 'AutoUnsuspendReserves test' => sub { t::lib::Mocks::mock_preference( 'HoldsLog', 1 ); my $hold_3 = $builder->build_object( - { class => 'Koha::Holds', + { + class => 'Koha::Holds', value => { expirationdate => undef, cancellationdate => undef, @@ -92,20 +97,20 @@ subtest 'AutoUnsuspendReserves test' => sub { } } ); - $hold_3->suspend_hold( $today ); + $hold_3->suspend_hold($today); - my $logs_count = $schema->resultset('ActionLog') - ->search( { module => 'HOLDS', action => 'RESUME' } )->count; + my $logs_count = $schema->resultset('ActionLog')->search( { module => 'HOLDS', action => 'RESUME' } )->count; AutoUnsuspendReserves(); $hold_3->discard_changes; - ok(!$hold_3->is_suspended, 'Hold suspended until today should be unsuspended.'); + ok( !$hold_3->is_suspended, 'Hold suspended until today should be unsuspended.' ); - my $new_logs_count = $schema->resultset('ActionLog') - ->search( { module => 'HOLDS', action => 'RESUME' } )->count; + my $new_logs_count = + $schema->resultset('ActionLog')->search( { module => 'HOLDS', action => 'RESUME' } )->count; - is( $new_logs_count, + is( + $new_logs_count, $logs_count + 1, 'If logging is enabled, calling AutoUnsuspendReserves gets logged' ); @@ -119,7 +124,8 @@ subtest 'AutoUnsuspendReserves test' => sub { t::lib::Mocks::mock_preference( 'HoldsLog', 0 ); my $hold_4 = $builder->build_object( - { class => 'Koha::Holds', + { + class => 'Koha::Holds', value => { expirationdate => undef, cancellationdate => undef, @@ -129,20 +135,20 @@ subtest 'AutoUnsuspendReserves test' => sub { } ); - my $logs_count = $schema->resultset('ActionLog') - ->search( { module => 'HOLDS', action => 'RESUME' } )->count; + my $logs_count = $schema->resultset('ActionLog')->search( { module => 'HOLDS', action => 'RESUME' } )->count; - $hold_4->suspend_hold( $today ); + $hold_4->suspend_hold($today); AutoUnsuspendReserves(); $hold_4->discard_changes; - ok(!defined($hold_4->suspend_until), 'Hold suspended until today should be unsuspended.'); + ok( !defined( $hold_4->suspend_until ), 'Hold suspended until today should be unsuspended.' ); - my $new_logs_count = $schema->resultset('ActionLog') - ->search( { module => 'HOLDS', action => 'RESUME' } )->count; + my $new_logs_count = + $schema->resultset('ActionLog')->search( { module => 'HOLDS', action => 'RESUME' } )->count; - is( $new_logs_count, + is( + $new_logs_count, $logs_count, 'If logging is not enabled, no logging from AutoUnsuspendReserves calls' ); diff --git a/t/db_dependent/Reserves/CancelExpiredReserves.t b/t/db_dependent/Reserves/CancelExpiredReserves.t index 9d83564a16..b9713ebd14 100755 --- a/t/db_dependent/Reserves/CancelExpiredReserves.t +++ b/t/db_dependent/Reserves/CancelExpiredReserves.t @@ -21,87 +21,95 @@ subtest 'CancelExpiredReserves tests incl. holidays' => sub { my $builder = t::lib::TestBuilder->new(); - t::lib::Mocks::mock_preference('ExpireReservesOnHolidays', 0); + t::lib::Mocks::mock_preference( 'ExpireReservesOnHolidays', 0 ); + # Waiting holds could be cancelled only if ExpireReservesMaxPickUpDelay is set to "allow", see bug 19260 - t::lib::Mocks::mock_preference('ExpireReservesMaxPickUpDelay', 1); + t::lib::Mocks::mock_preference( 'ExpireReservesMaxPickUpDelay', 1 ); - - my $today = dt_from_string(); + my $today = dt_from_string(); my $reserve_reservedate = $today->clone; - $reserve_reservedate->subtract(days => 30); + $reserve_reservedate->subtract( days => 30 ); my $reserve1_expirationdate = $today->clone; - $reserve1_expirationdate->add(days => 1); + $reserve1_expirationdate->add( days => 1 ); # Reserve not expired - my $reserve1 = $builder->build({ - source => 'Reserve', - value => { - reservedate => $reserve_reservedate, - patron_expiration_date => $reserve1_expirationdate, - cancellationdate => undef, - priority => 0, - found => 'W', - }, - }); + my $reserve1 = $builder->build( + { + source => 'Reserve', + value => { + reservedate => $reserve_reservedate, + patron_expiration_date => $reserve1_expirationdate, + cancellationdate => undef, + priority => 0, + found => 'W', + }, + } + ); CancelExpiredReserves(); - my $r1 = Koha::Holds->find($reserve1->{reserve_id}); - ok($r1, 'Reserve 1 should not be canceled.'); + my $r1 = Koha::Holds->find( $reserve1->{reserve_id} ); + ok( $r1, 'Reserve 1 should not be canceled.' ); my $reserve2_expirationdate = $today->clone; - $reserve2_expirationdate->subtract(days => 1); + $reserve2_expirationdate->subtract( days => 1 ); # Reserve expired - my $reserve2 = $builder->build({ - source => 'Reserve', - value => { - reservedate => $reserve_reservedate, - patron_expiration_date => $reserve2_expirationdate, - cancellationdate => undef, - priority => 0, - found => 'W', - }, - }); + my $reserve2 = $builder->build( + { + source => 'Reserve', + value => { + reservedate => $reserve_reservedate, + patron_expiration_date => $reserve2_expirationdate, + cancellationdate => undef, + priority => 0, + found => 'W', + }, + } + ); CancelExpiredReserves(); - my $r2 = Koha::Holds->find($reserve2->{reserve_id}); - is($r2, undef,'reserve 2 should be canceled.'); + my $r2 = Koha::Holds->find( $reserve2->{reserve_id} ); + is( $r2, undef, 'reserve 2 should be canceled.' ); # Reserve expired on holiday - my $reserve3 = $builder->build({ - source => 'Reserve', - value => { - reservedate => $reserve_reservedate, - patron_expiration_date => $reserve2_expirationdate, - branchcode => 'LIB1', - cancellationdate => undef, - priority => 0, - found => 'W', - }, - }); + my $reserve3 = $builder->build( + { + source => 'Reserve', + value => { + reservedate => $reserve_reservedate, + patron_expiration_date => $reserve2_expirationdate, + branchcode => 'LIB1', + cancellationdate => undef, + priority => 0, + found => 'W', + }, + } + ); Koha::Caches->get_instance()->flush_all(); - my $holiday = $builder->build({ - source => 'SpecialHoliday', - value => { - branchcode => 'LIB1', - day => $today->day, - month => $today->month, - year => $today->year, - title => 'My holiday', - isexception => 0 - }, - }); + my $holiday = $builder->build( + { + source => 'SpecialHoliday', + value => { + branchcode => 'LIB1', + day => $today->day, + month => $today->month, + year => $today->year, + title => 'My holiday', + isexception => 0 + }, + } + ); CancelExpiredReserves(); - my $r3 = Koha::Holds->find($reserve3->{reserve_id}); - ok($r3,'Reserve 3 should not be canceled.'); + my $r3 = Koha::Holds->find( $reserve3->{reserve_id} ); + ok( $r3, 'Reserve 3 should not be canceled.' ); - t::lib::Mocks::mock_preference('ExpireReservesOnHolidays', 1); + t::lib::Mocks::mock_preference( 'ExpireReservesOnHolidays', 1 ); CancelExpiredReserves(); - $r3 = Koha::Holds->find($reserve3->{reserve_id}); - is($r3, undef,'Reserve 3 should be canceled.'); + $r3 = Koha::Holds->find( $reserve3->{reserve_id} ); + is( $r3, undef, 'Reserve 3 should be canceled.' ); }; subtest 'Test handling of waiting reserves by CancelExpiredReserves' => sub { @@ -109,57 +117,65 @@ subtest 'Test handling of waiting reserves by CancelExpiredReserves' => sub { Koha::Holds->delete; - my $builder = t::lib::TestBuilder->new(); - my $category = $builder->build({ source => 'Category' }); - my $branchcode = $builder->build({ source => 'Branch' })->{ branchcode }; - my $item = $builder->build_sample_item; - my $itemnumber = $item->itemnumber; - my $borrowernumber = $builder->build({ source => 'Borrower', value => { categorycode => $category->{categorycode}, branchcode => $branchcode }})->{borrowernumber}; + my $builder = t::lib::TestBuilder->new(); + my $category = $builder->build( { source => 'Category' } ); + my $branchcode = $builder->build( { source => 'Branch' } )->{branchcode}; + my $item = $builder->build_sample_item; + my $itemnumber = $item->itemnumber; + my $borrowernumber = $builder->build( + { source => 'Borrower', value => { categorycode => $category->{categorycode}, branchcode => $branchcode } } ) + ->{borrowernumber}; - my $resdate = dt_from_string->add( days => -20 ); - my $expdate = dt_from_string->add( days => -2 ); + my $resdate = dt_from_string->add( days => -20 ); + my $expdate = dt_from_string->add( days => -2 ); my $notexpdate = dt_from_string->add( days => 2 ); - my $hold1 = Koha::Hold->new({ - branchcode => $branchcode, - borrowernumber => $borrowernumber, - biblionumber => $item->biblionumber, - priority => 1, - reservedate => $resdate, - expirationdate => $notexpdate, - found => undef, - })->store; + my $hold1 = Koha::Hold->new( + { + branchcode => $branchcode, + borrowernumber => $borrowernumber, + biblionumber => $item->biblionumber, + priority => 1, + reservedate => $resdate, + expirationdate => $notexpdate, + found => undef, + } + )->store; - my $hold2 = Koha::Hold->new({ - branchcode => $branchcode, - borrowernumber => $borrowernumber, - biblionumber => $item->biblionumber, - priority => 2, - reservedate => $resdate, - expirationdate => $expdate, - found => undef, - })->store; + my $hold2 = Koha::Hold->new( + { + branchcode => $branchcode, + borrowernumber => $borrowernumber, + biblionumber => $item->biblionumber, + priority => 2, + reservedate => $resdate, + expirationdate => $expdate, + found => undef, + } + )->store; - my $hold3 = Koha::Hold->new({ - branchcode => $branchcode, - borrowernumber => $borrowernumber, - biblionumber => $item->biblionumber, - itemnumber => $itemnumber, - priority => 0, - reservedate => $resdate, - expirationdate => $expdate, - found => 'W', - })->store; + my $hold3 = Koha::Hold->new( + { + branchcode => $branchcode, + borrowernumber => $borrowernumber, + biblionumber => $item->biblionumber, + itemnumber => $itemnumber, + priority => 0, + reservedate => $resdate, + expirationdate => $expdate, + found => 'W', + } + )->store; t::lib::Mocks::mock_preference( 'ExpireReservesMaxPickUpDelay', 0 ); CancelExpiredReserves(); my $count1 = Koha::Holds->search->count; - is( $count1, 2, 'Only the non-waiting expired holds should be cancelled'); + is( $count1, 2, 'Only the non-waiting expired holds should be cancelled' ); t::lib::Mocks::mock_preference( 'ExpireReservesMaxPickUpDelay', 1 ); CancelExpiredReserves(); my $count2 = Koha::Holds->search->count; - is( $count2, 1, 'Also the waiting expired hold should be cancelled now'); + is( $count2, 1, 'Also the waiting expired hold should be cancelled now' ); }; @@ -170,33 +186,37 @@ subtest 'Test handling of in transit reserves by CancelExpiredReserves' => sub { t::lib::Mocks::mock_preference( 'ExpireReservesMaxPickUpDelay', 1 ); my $expdate = dt_from_string->add( days => -2 ); - my $reserve = $builder->build({ - source => 'Reserve', - value => { - patron_expiration_date => '2018-01-01', - found => 'T', - cancellationdate => undef, - suspend => 0, - suspend_until => undef + my $reserve = $builder->build( + { + source => 'Reserve', + value => { + patron_expiration_date => '2018-01-01', + found => 'T', + cancellationdate => undef, + suspend => 0, + suspend_until => undef + } } - }); + ); my $count = Koha::Holds->search->count; CancelExpiredReserves(); - is(Koha::Holds->search->count, $count-1, "Transit hold is cancelled if ExpireReservesMaxPickUpDelay set"); + is( Koha::Holds->search->count, $count - 1, "Transit hold is cancelled if ExpireReservesMaxPickUpDelay set" ); t::lib::Mocks::mock_preference( 'ExpireReservesMaxPickUpDelay', 0 ); - my $reserve2 = $builder->build({ - source => 'Reserve', - value => { - patron_expiration_date => '2018-01-01', - found => 'T', - cancellationdate => undef, - suspend => 0, - suspend_until => undef + my $reserve2 = $builder->build( + { + source => 'Reserve', + value => { + patron_expiration_date => '2018-01-01', + found => 'T', + cancellationdate => undef, + suspend => 0, + suspend_until => undef + } } - }); + ); CancelExpiredReserves(); - is(Koha::Holds->search->count, $count-1, "Transit hold is cancelled if ExpireReservesMaxPickUpDelay unset"); + is( Koha::Holds->search->count, $count - 1, "Transit hold is cancelled if ExpireReservesMaxPickUpDelay unset" ); }; @@ -206,22 +226,24 @@ subtest 'Test handling of cancellation reason if passed' => sub { my $builder = t::lib::TestBuilder->new(); my $expdate = dt_from_string->add( days => -2 ); - my $reserve = $builder->build({ - source => 'Reserve', - value => { - patron_expiration_date => '2018-01-01', - found => 'T', - cancellationdate => undef, - suspend => 0, - suspend_until => undef + my $reserve = $builder->build( + { + source => 'Reserve', + value => { + patron_expiration_date => '2018-01-01', + found => 'T', + cancellationdate => undef, + suspend => 0, + suspend_until => undef + } } - }); + ); my $reserve_id = $reserve->{reserve_id}; - my $count = Koha::Holds->search->count; + my $count = Koha::Holds->search->count; CancelExpiredReserves("EXPIRED"); - is(Koha::Holds->search->count, $count-1, "Hold is cancelled when reason is passed"); + is( Koha::Holds->search->count, $count - 1, "Hold is cancelled when reason is passed" ); my $old_reserve = Koha::Old::Holds->find($reserve_id); - is($old_reserve->cancellation_reason, 'EXPIRED', "Hold cancellation_reason was set correctly"); + is( $old_reserve->cancellation_reason, 'EXPIRED', "Hold cancellation_reason was set correctly" ); }; $schema->storage->txn_rollback; diff --git a/t/db_dependent/Reserves/GetReserveFee.t b/t/db_dependent/Reserves/GetReserveFee.t index 03029d8333..6c1dfc97cc 100755 --- a/t/db_dependent/Reserves/GetReserveFee.t +++ b/t/db_dependent/Reserves/GetReserveFee.t @@ -27,63 +27,80 @@ use t::lib::TestBuilder; use t::lib::Mocks; use C4::Circulation qw( AddIssue ); -use C4::Reserves qw( GetReserveFee ChargeReserveFee AddReserve ); +use C4::Reserves qw( GetReserveFee ChargeReserveFee AddReserve ); use Koha::Database; my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; my $builder = t::lib::TestBuilder->new(); -my $library = $builder->build({ - source => 'Branch', -}); +my $library = $builder->build( + { + source => 'Branch', + } +); my $mContext = Test::MockModule->new('C4::Context'); -$mContext->mock( 'userenv', sub { - return { branch => $library->{branchcode} }; -}); +$mContext->mock( + 'userenv', + sub { + return { branch => $library->{branchcode} }; + } +); -my $dbh = C4::Context->dbh; # after start transaction of testbuilder +my $dbh = C4::Context->dbh; # after start transaction of testbuilder # Category with hold fee, two patrons -$builder->build({ - source => 'Category', - value => { - categorycode => 'XYZ1', - reservefee => 2, - }, -}); -$builder->build({ - source => 'Category', - value => { - categorycode => 'XYZ2', - reservefee => 0, - }, -}); -my $patron1 = $builder->build_object({ - class => 'Koha::Patrons', - value => { - categorycode => 'XYZ1', - }, -}); -my $patron2 = $builder->build_object({ - class => 'Koha::Patrons', - value => { - categorycode => 'XYZ1', - }, -}); -my $patron3 = $builder->build_object({ - class => 'Koha::Patrons', -}); -my $patron4 = $builder->build_object({ - class => 'Koha::Patrons', - value => { - categorycode => 'XYZ2', - }, -}); +$builder->build( + { + source => 'Category', + value => { + categorycode => 'XYZ1', + reservefee => 2, + }, + } +); +$builder->build( + { + source => 'Category', + value => { + categorycode => 'XYZ2', + reservefee => 0, + }, + } +); +my $patron1 = $builder->build_object( + { + class => 'Koha::Patrons', + value => { + categorycode => 'XYZ1', + }, + } +); +my $patron2 = $builder->build_object( + { + class => 'Koha::Patrons', + value => { + categorycode => 'XYZ1', + }, + } +); +my $patron3 = $builder->build_object( + { + class => 'Koha::Patrons', + } +); +my $patron4 = $builder->build_object( + { + class => 'Koha::Patrons', + value => { + categorycode => 'XYZ2', + }, + } +); # One biblio and two items my $biblio = $builder->build_sample_biblio; -my $item1 = $builder->build_sample_item( +my $item1 = $builder->build_sample_item( { biblionumber => $biblio->biblionumber, notforloan => 0, @@ -99,31 +116,33 @@ my $item2 = $builder->build_sample_item( subtest 'GetReserveFee' => sub { plan tests => 6; - C4::Circulation::AddIssue( $patron1, $item1->barcode, '2015-12-31', 0, undef, 0, {} ); # the date does not really matter - C4::Circulation::AddIssue( $patron3, $item2->barcode, '2015-12-31', 0, undef, 0, {} ); # the date does not really matter + C4::Circulation::AddIssue( $patron1, $item1->barcode, '2015-12-31', 0, undef, 0, {} ) + ; # the date does not really matter + C4::Circulation::AddIssue( $patron3, $item2->barcode, '2015-12-31', 0, undef, 0, {} ) + ; # the date does not really matter my $acc2 = acctlines( $patron2->borrowernumber ); my $res1 = addreserve( $patron1->borrowernumber ); - t::lib::Mocks::mock_preference('HoldFeeMode', 'not_always'); + t::lib::Mocks::mock_preference( 'HoldFeeMode', 'not_always' ); my $fee = C4::Reserves::GetReserveFee( $patron2->borrowernumber, $biblio->biblionumber ); is( $fee > 0, 1, 'Patron 2 should be charged cf GetReserveFee' ); C4::Reserves::ChargeReserveFee( $patron2->borrowernumber, $fee, $biblio->title ); is( acctlines( $patron2->borrowernumber ), $acc2 + 1, 'Patron 2 has been charged by ChargeReserveFee' ); # If we delete the reserve, there should be no charge - $dbh->do( "DELETE FROM reserves WHERE borrowernumber = ?", undef, ( $patron1->borrowernumber) ); + $dbh->do( "DELETE FROM reserves WHERE borrowernumber = ?", undef, ( $patron1->borrowernumber ) ); $fee = C4::Reserves::GetReserveFee( $patron2->borrowernumber, $biblio->biblionumber ); is( $fee, 0, 'HoldFeeMode=not_always, Patron 2 should not be charged' ); - t::lib::Mocks::mock_preference('HoldFeeMode', 'any_time_is_placed'); + t::lib::Mocks::mock_preference( 'HoldFeeMode', 'any_time_is_placed' ); $fee = C4::Reserves::GetReserveFee( $patron2->borrowernumber, $biblio->biblionumber ); is( int($fee), 2, 'HoldFeeMode=any_time_is_placed, Patron 2 should be charged' ); - t::lib::Mocks::mock_preference('HoldFeeMode', 'any_time_is_collected'); + t::lib::Mocks::mock_preference( 'HoldFeeMode', 'any_time_is_collected' ); $fee = C4::Reserves::GetReserveFee( $patron2->borrowernumber, $biblio->biblionumber ); is( int($fee), 2, 'HoldFeeMode=any_time_is_collected, Patron 2 should be charged' ); - t::lib::Mocks::mock_preference('HoldFeeMode', 'any_time_is_placed'); + t::lib::Mocks::mock_preference( 'HoldFeeMode', 'any_time_is_placed' ); $fee = C4::Reserves::GetReserveFee( $patron4->borrowernumber, $biblio->biblionumber ); is( $fee, 0, 'HoldFeeMode=any_time_is_placed ; fee == 0, Patron 4 should not be charged' ); }; @@ -136,55 +155,70 @@ subtest 'Integration with AddReserve' => sub { subtest 'Items are not issued' => sub { plan tests => 3; - t::lib::Mocks::mock_preference('HoldFeeMode', 'not_always'); - $dbh->do( "DELETE FROM reserves WHERE biblionumber=?", undef, $biblio->biblionumber ); + t::lib::Mocks::mock_preference( 'HoldFeeMode', 'not_always' ); + $dbh->do( "DELETE FROM reserves WHERE biblionumber=?", undef, $biblio->biblionumber ); $dbh->do( "DELETE FROM accountlines WHERE borrowernumber=?", undef, $patron1->borrowernumber ); addreserve( $patron1->borrowernumber ); is( acctlines( $patron1->borrowernumber ), 0, 'not_always - No fee charged for patron 1 if not issued' ); - t::lib::Mocks::mock_preference('HoldFeeMode', 'any_time_is_placed'); - $dbh->do( "DELETE FROM reserves WHERE biblionumber=?", undef, $biblio->biblionumber ); + t::lib::Mocks::mock_preference( 'HoldFeeMode', 'any_time_is_placed' ); + $dbh->do( "DELETE FROM reserves WHERE biblionumber=?", undef, $biblio->biblionumber ); $dbh->do( "DELETE FROM accountlines WHERE borrowernumber=?", undef, $patron1->borrowernumber ); addreserve( $patron1->borrowernumber ); is( acctlines( $patron1->borrowernumber ), 1, 'any_time_is_placed - Patron should be always charged' ); - t::lib::Mocks::mock_preference('HoldFeeMode', 'any_time_is_collected'); - $dbh->do( "DELETE FROM reserves WHERE biblionumber=?", undef, $biblio->biblionumber ); + t::lib::Mocks::mock_preference( 'HoldFeeMode', 'any_time_is_collected' ); + $dbh->do( "DELETE FROM reserves WHERE biblionumber=?", undef, $biblio->biblionumber ); $dbh->do( "DELETE FROM accountlines WHERE borrowernumber=?", undef, $patron1->borrowernumber ); addreserve( $patron1->borrowernumber ); - is( acctlines( $patron1->borrowernumber ), 0, 'any_time_is_collected - Patron should not be charged when placing a hold' ); + is( + acctlines( $patron1->borrowernumber ), 0, + 'any_time_is_collected - Patron should not be charged when placing a hold' + ); }; subtest 'Items are issued' => sub { plan tests => 4; - $dbh->do( "DELETE FROM issues WHERE itemnumber=?", undef, $item1->itemnumber); - $dbh->do( "DELETE FROM issues WHERE itemnumber=?", undef, $item2->itemnumber); + $dbh->do( "DELETE FROM issues WHERE itemnumber=?", undef, $item1->itemnumber ); + $dbh->do( "DELETE FROM issues WHERE itemnumber=?", undef, $item2->itemnumber ); C4::Circulation::AddIssue( $patron2, $item1->barcode, '2015-12-31', 0, undef, 0, {} ); - t::lib::Mocks::mock_preference('HoldFeeMode', 'not_always'); - $dbh->do( "DELETE FROM reserves WHERE biblionumber=?", undef, $biblio->biblionumber ); + t::lib::Mocks::mock_preference( 'HoldFeeMode', 'not_always' ); + $dbh->do( "DELETE FROM reserves WHERE biblionumber=?", undef, $biblio->biblionumber ); $dbh->do( "DELETE FROM accountlines WHERE borrowernumber=?", undef, $patron1->borrowernumber ); addreserve( $patron1->borrowernumber ); - is( acctlines( $patron1->borrowernumber ), 0, 'not_always - Patron should not be charged if items are not all checked out' ); + is( + acctlines( $patron1->borrowernumber ), 0, + 'not_always - Patron should not be charged if items are not all checked out' + ); - $dbh->do( "DELETE FROM reserves WHERE biblionumber=?", undef, $biblio->biblionumber ); + $dbh->do( "DELETE FROM reserves WHERE biblionumber=?", undef, $biblio->biblionumber ); $dbh->do( "DELETE FROM accountlines WHERE borrowernumber=?", undef, $patron1->borrowernumber ); addreserve( $patron3->borrowernumber ); addreserve( $patron1->borrowernumber ); - is( acctlines( $patron1->borrowernumber ), 0, 'not_always - Patron should not be charged if all the items are not checked out, even if 1 hold is already placed' ); + is( + acctlines( $patron1->borrowernumber ), 0, + 'not_always - Patron should not be charged if all the items are not checked out, even if 1 hold is already placed' + ); C4::Circulation::AddIssue( $patron3, $item2->barcode, '2015-12-31', 0, undef, 0, {} ); - $dbh->do( "DELETE FROM reserves WHERE biblionumber=?", undef, $biblio->biblionumber ); + $dbh->do( "DELETE FROM reserves WHERE biblionumber=?", undef, $biblio->biblionumber ); $dbh->do( "DELETE FROM accountlines WHERE borrowernumber=?", undef, $patron1->borrowernumber ); addreserve( $patron1->borrowernumber ); - is( acctlines( $patron1->borrowernumber ), 0, 'not_always - Patron should not be charged if all items are checked out but no holds are placed' ); + is( + acctlines( $patron1->borrowernumber ), 0, + 'not_always - Patron should not be charged if all items are checked out but no holds are placed' + ); - $dbh->do( "DELETE FROM reserves WHERE biblionumber=?", undef, $biblio->biblionumber ); + $dbh->do( "DELETE FROM reserves WHERE biblionumber=?", undef, $biblio->biblionumber ); $dbh->do( "DELETE FROM accountlines WHERE borrowernumber=?", undef, $patron1->borrowernumber ); addreserve( $patron3->borrowernumber ); addreserve( $patron1->borrowernumber ); - is( acctlines( $patron1->borrowernumber ), 1, 'not_always - Patron should only be charged if all items are checked out and at least 1 hold is already placed' ); + is( + acctlines( $patron1->borrowernumber ), 1, + 'not_always - Patron should only be charged if all items are checked out and at least 1 hold is already placed' + ); }; }; @@ -192,31 +226,40 @@ subtest 'Integration with AddIssue' => sub { plan tests => 5; $dbh->do( "DELETE FROM issues WHERE borrowernumber = ?", undef, $patron1->borrowernumber ); - $dbh->do( "DELETE FROM reserves WHERE biblionumber=?", undef, $biblio->biblionumber ); - $dbh->do( "DELETE FROM accountlines WHERE borrowernumber=?", undef, $patron1->borrowernumber ); + $dbh->do( "DELETE FROM reserves WHERE biblionumber=?", undef, $biblio->biblionumber ); + $dbh->do( "DELETE FROM accountlines WHERE borrowernumber=?", undef, $patron1->borrowernumber ); - t::lib::Mocks::mock_preference('HoldFeeMode', 'not_always'); + t::lib::Mocks::mock_preference( 'HoldFeeMode', 'not_always' ); C4::Circulation::AddIssue( $patron1, $item1->barcode, '2015-12-31', 0, undef, 0, {} ); is( acctlines( $patron1->borrowernumber ), 0, 'not_always - Patron should not be charged' ); - t::lib::Mocks::mock_preference('HoldFeeMode', 'any_time_is_placed'); + t::lib::Mocks::mock_preference( 'HoldFeeMode', 'any_time_is_placed' ); $dbh->do( "DELETE FROM issues WHERE borrowernumber = ?", undef, $patron1->borrowernumber ); C4::Circulation::AddIssue( $patron1, $item1->barcode, '2015-12-31', 0, undef, 0, {} ); is( acctlines( $patron1->borrowernumber ), 0, 'not_always - Patron should not be charged' ); - t::lib::Mocks::mock_preference('HoldFeeMode', 'any_time_is_collected'); + t::lib::Mocks::mock_preference( 'HoldFeeMode', 'any_time_is_collected' ); $dbh->do( "DELETE FROM issues WHERE borrowernumber = ?", undef, $patron1->borrowernumber ); C4::Circulation::AddIssue( $patron1, $item1->barcode, '2015-12-31', 0, undef, 0, {} ); - is( acctlines( $patron1->borrowernumber ), 0, 'any_time_is_collected - Patron should not be charged when checking out an item which was not placed hold for him' ); + is( + acctlines( $patron1->borrowernumber ), 0, + 'any_time_is_collected - Patron should not be charged when checking out an item which was not placed hold for him' + ); $dbh->do( "DELETE FROM issues WHERE borrowernumber = ?", undef, $patron1->borrowernumber ); my $id = addreserve( $patron1->borrowernumber ); - is( acctlines( $patron1->borrowernumber ), 0, 'any_time_is_collected - Patron should not be charged yet (just checking to make sure)'); + is( + acctlines( $patron1->borrowernumber ), 0, + 'any_time_is_collected - Patron should not be charged yet (just checking to make sure)' + ); C4::Circulation::AddIssue( $patron1, $item1->barcode, '2015-12-31', 0, undef, 0, {} ); - is( acctlines( $patron1->borrowernumber ), 1, 'any_time_is_collected - Patron should not be charged when checking out an item which was not placed hold for him' ); + is( + acctlines( $patron1->borrowernumber ), 1, + 'any_time_is_collected - Patron should not be charged when checking out an item which was not placed hold for him' + ); }; -sub acctlines { #calculate number of accountlines for a patron +sub acctlines { #calculate number of accountlines for a patron my @temp = $dbh->selectrow_array( "SELECT COUNT(*) FROM accountlines WHERE borrowernumber=?", undef, ( $_[0] ) ); return $temp[0]; } diff --git a/t/db_dependent/Reserves/MultiplePerRecord.t b/t/db_dependent/Reserves/MultiplePerRecord.t index 56da6d5036..6f751c5fb6 100755 --- a/t/db_dependent/Reserves/MultiplePerRecord.t +++ b/t/db_dependent/Reserves/MultiplePerRecord.t @@ -52,20 +52,12 @@ my $patron = $builder->build( } ); -my $itemtype1 = $builder->build( - { - source => 'Itemtype' - } -); +my $itemtype1 = $builder->build( { source => 'Itemtype' } ); -my $itemtype2 = $builder->build( - { - source => 'Itemtype' - } -); +my $itemtype2 = $builder->build( { source => 'Itemtype' } ); my $biblio = $builder->build_sample_biblio; -my $item1 = $builder->build_sample_item( +my $item1 = $builder->build_sample_item( { biblionumber => $biblio->biblionumber, itype => $itemtype1->{itemtype}, @@ -102,7 +94,7 @@ Koha::CirculationRules->set_rules( } ); -t::lib::Mocks::mock_preference('item-level_itypes', 1); # Assuming the item type is defined at item level +t::lib::Mocks::mock_preference( 'item-level_itypes', 1 ); # Assuming the item type is defined at item level my $max = GetMaxPatronHoldsForRecord( $patron->{borrowernumber}, $biblio->biblionumber ); is( $max, 1, 'GetMaxPatronHoldsForRecord returns max of 1' ); @@ -180,7 +172,10 @@ Koha::CirculationRules->set_rules( ); $max = GetMaxPatronHoldsForRecord( $patron->{borrowernumber}, $biblio->biblionumber ); -is( $max, 9, 'GetMaxPatronHoldsForRecord returns max of 9 because Library specific all itemtypes all categories rule comes before All libraries specific type and specific category' ); +is( + $max, 9, + 'GetMaxPatronHoldsForRecord returns max of 9 because Library specific all itemtypes all categories rule comes before All libraries specific type and specific category' +); Koha::CirculationRules->delete(); @@ -188,13 +183,15 @@ my $holds = Koha::Holds->search( { borrowernumber => $patron->{borrowernumber} } is( $holds->forced_hold_level, undef, "No holds does not force an item or record level hold" ); # Test Koha::Holds::forced_hold_level -my $hold = Koha::Hold->new({ - borrowernumber => $patron->{borrowernumber}, - reservedate => '1981-06-10', - biblionumber => $biblio->biblionumber, - branchcode => $library->{branchcode}, - priority => 1, -})->store(); +my $hold = Koha::Hold->new( + { + borrowernumber => $patron->{borrowernumber}, + reservedate => '1981-06-10', + biblionumber => $biblio->biblionumber, + branchcode => $library->{branchcode}, + priority => 1, + } +)->store(); $holds = Koha::Holds->search( { borrowernumber => $patron->{borrowernumber} } ); is( $holds->forced_hold_level, 'record', "Record level hold forces record level holds" ); @@ -206,7 +203,7 @@ $holds = Koha::Holds->search( { borrowernumber => $patron->{borrowernumber} } ); is( $holds->forced_hold_level, 'item', "Item level hold forces item level holds" ); my $item_group = Koha::Biblio::ItemGroup->new( { biblio_id => $biblio->id } )->store(); -$hold->itemnumber( undef ); +$hold->itemnumber(undef); $hold->item_group_id( $item_group->id ); $hold->store(); @@ -228,7 +225,7 @@ Koha::CirculationRules->set_rules( } ); -my $can = CanBookBeReserved($patron->{borrowernumber}, $biblio->biblionumber); +my $can = CanBookBeReserved( $patron->{borrowernumber}, $biblio->biblionumber ); is( $can->{status}, 'OK', 'Hold can be placed with 0 holds' ); my $hold_id = AddReserve( { @@ -240,7 +237,7 @@ my $hold_id = AddReserve( ); ok( $hold_id, 'First hold was placed' ); -$can = CanBookBeReserved($patron->{borrowernumber}, $biblio->biblionumber); +$can = CanBookBeReserved( $patron->{borrowernumber}, $biblio->biblionumber ); is( $can->{status}, 'OK', 'Hold can be placed with 1 hold' ); $hold_id = AddReserve( { @@ -252,11 +249,11 @@ $hold_id = AddReserve( ); ok( $hold_id, 'Second hold was placed' ); -$can = CanBookBeReserved($patron->{borrowernumber}, $biblio->biblionumber); +$can = CanBookBeReserved( $patron->{borrowernumber}, $biblio->biblionumber ); is( $can->{status}, 'tooManyHoldsForThisRecord', 'Third hold exceeds limit of holds per record' ); Koha::Holds->find($hold_id)->found("W")->store; -$can = CanBookBeReserved($patron->{borrowernumber}, $biblio->biblionumber); +$can = CanBookBeReserved( $patron->{borrowernumber}, $biblio->biblionumber ); is( $can->{status}, 'tooManyHoldsForThisRecord', 'Third hold exceeds limit of holds per record' ); $schema->storage->txn_rollback; diff --git a/t/db_dependent/Reserves/ReserveSlip.t b/t/db_dependent/Reserves/ReserveSlip.t index 664f9a1b0c..342db33e6f 100755 --- a/t/db_dependent/Reserves/ReserveSlip.t +++ b/t/db_dependent/Reserves/ReserveSlip.t @@ -49,9 +49,8 @@ my $patron = $builder->build( } ); - my $biblio = $builder->build_sample_biblio; -my $item1 = $builder->build_sample_item( +my $item1 = $builder->build_sample_item( { biblionumber => $biblio->biblionumber, library => $library->{branchcode}, @@ -88,28 +87,42 @@ my $letter = $builder->build( { source => 'Letter', value => { - module => 'circulation', - code => 'HOLD_SLIP', - lang => 'default', + module => 'circulation', + code => 'HOLD_SLIP', + lang => 'default', branchcode => $library->{branchcode}, - content => 'Hold found for <<borrowers.firstname>>: Please pick up <<biblio.title>> with barcode <<items.barcode>> at <<branches.branchcode>>.', + content => + 'Hold found for <<borrowers.firstname>>: Please pick up <<biblio.title>> with barcode <<items.barcode>> at <<branches.branchcode>>.', message_transport_type => 'email', }, } ); -is ( ReserveSlip(), undef, "No hold slip returned if invalid or undef borrowernumber and/or biblionumber" ); -is ( ReserveSlip({ - branchcode => $library->{branchcode}, - reserve_id => $hold1->reserve_id, - })->{code}, - 'HOLD_SLIP', "Get a hold slip from library, patron and biblio" ); +is( ReserveSlip(), undef, "No hold slip returned if invalid or undef borrowernumber and/or biblionumber" ); +is( + ReserveSlip( + { + branchcode => $library->{branchcode}, + reserve_id => $hold1->reserve_id, + } + )->{code}, + 'HOLD_SLIP', + "Get a hold slip from library, patron and biblio" +); -is (ReserveSlip({ - branchcode => $library->{branchcode}, - reserve_id => $hold1->reserve_id, - })->{content}, - sprintf( "Hold found for %s: Please pick up %s with barcode %s at %s.", $patron->{firstname}, $biblio->title, $item1->barcode, $library->{branchcode}),"Hold slip contains correctly parsed content"); +is( + ReserveSlip( + { + branchcode => $library->{branchcode}, + reserve_id => $hold1->reserve_id, + } + )->{content}, + sprintf( + "Hold found for %s: Please pick up %s with barcode %s at %s.", $patron->{firstname}, $biblio->title, + $item1->barcode, $library->{branchcode} + ), + "Hold slip contains correctly parsed content" +); subtest 'title level hold' => sub { plan tests => 2; @@ -145,7 +158,7 @@ subtest 'title level hold' => sub { $slip->{content}, sprintf( "Hold found for %s: Please pick up %s with barcode %s at %s.", $patron->{firstname}, $biblio->title, - $item->barcode, $library->{branchcode} + $item->barcode, $library->{branchcode} ), "Hold slip contents correctly use the passed item" ); diff --git a/t/db_dependent/RotatingCollections.t b/t/db_dependent/RotatingCollections.t index 855e33897c..c7b151d1a0 100755 --- a/t/db_dependent/RotatingCollections.t +++ b/t/db_dependent/RotatingCollections.t @@ -19,7 +19,8 @@ use Modern::Perl; use Test::More tests => 53; use C4::Context; -use C4::RotatingCollections qw( AddItemToCollection CreateCollection DeleteCollection GetCollection GetCollectionItemBranches GetCollections GetItemsInCollection RemoveItemFromCollection TransferCollection UpdateCollection isItemInAnyCollection isItemInThisCollection ); +use C4::RotatingCollections + qw( AddItemToCollection CreateCollection DeleteCollection GetCollection GetCollectionItemBranches GetCollections GetItemsInCollection RemoveItemFromCollection TransferCollection UpdateCollection isItemInAnyCollection isItemInThisCollection ); use C4::Biblio qw( AddBiblio ); use Koha::Database; use Koha::Library; @@ -32,19 +33,19 @@ BEGIN { can_ok( 'C4::RotatingCollections', qw( - AddItemToCollection - CreateCollection - DeleteCollection - GetCollection - GetCollectionItemBranches - GetCollections - GetItemsInCollection - RemoveItemFromCollection - TransferCollection - UpdateCollection - isItemInAnyCollection - isItemInThisCollection - ) + AddItemToCollection + CreateCollection + DeleteCollection + GetCollection + GetCollectionItemBranches + GetCollections + GetItemsInCollection + RemoveItemFromCollection + TransferCollection + UpdateCollection + isItemInAnyCollection + isItemInThisCollection + ) ); my $schema = Koha::Database->new->schema; @@ -66,33 +67,41 @@ my $builder = t::lib::TestBuilder->new; my $collections = GetCollections(); my $countcollection = scalar(@$collections); -my ($success,$errorCode,$errorMessage); +my ( $success, $errorCode, $errorMessage ); -($success,$errorCode,$errorMessage) = CreateCollection( 'Collection1', 'Description1' ); +( $success, $errorCode, $errorMessage ) = CreateCollection( 'Collection1', 'Description1' ); is( $success, 1, "All parameters have been given - Collection 1 added" ); -ok( !defined $errorCode && !defined $errorMessage, - "Collection added, no error code or message"); +ok( + !defined $errorCode && !defined $errorMessage, + "Collection added, no error code or message" +); my $collection_id1 = $dbh->last_insert_id( undef, undef, 'collections', undef ); -($success,$errorCode,$errorMessage) = CreateCollection( 'Collection2', 'Description2' ); +( $success, $errorCode, $errorMessage ) = CreateCollection( 'Collection2', 'Description2' ); is( $success, 1, "All parameters have been given - Collection 2 added" ); -ok( !defined $errorCode && !defined $errorMessage, - "Collection added, no error code or message"); +ok( + !defined $errorCode && !defined $errorMessage, + "Collection added, no error code or message" +); my $collection_id2 = $dbh->last_insert_id( undef, undef, 'collections', undef ); $collections = GetCollections(); -is( scalar(@$collections), $countcollection + 2, - "Collection1 and Collection2 have been added" ); +is( + scalar(@$collections), $countcollection + 2, + "Collection1 and Collection2 have been added" +); -($success,$errorCode,$errorMessage) = CreateCollection('Collection3'); +( $success, $errorCode, $errorMessage ) = CreateCollection('Collection3'); is( $success, 1, "Collections can be created without description" ); -ok( !defined $errorCode && !defined $errorMessage, - "Collection added, no error code or message"); +ok( + !defined $errorCode && !defined $errorMessage, + "Collection added, no error code or message" +); my $collection_id3 = $dbh->last_insert_id( undef, undef, 'collections', undef ); -($success,$errorCode,$errorMessage) = CreateCollection(); -is( $success, 0, "Title missing, fails to create collection" ); -is( $errorCode, 1, "Title missing, error code is 1" ); +( $success, $errorCode, $errorMessage ) = CreateCollection(); +is( $success, 0, "Title missing, fails to create collection" ); +is( $errorCode, 1, "Title missing, error code is 1" ); is( $errorMessage, 'NO_TITLE', "Title missing, error message is NO_TITLE" ); $collections = GetCollections(); @@ -130,21 +139,22 @@ is_deeply( ); #Test UpdateCollection -($success,$errorCode,$errorMessage) = - UpdateCollection( $collection_id2, 'Collection2bis', undef ); -is( $success, 1, "UpdateCollection succeeds without description"); +( $success, $errorCode, $errorMessage ) = UpdateCollection( $collection_id2, 'Collection2bis', undef ); +is( $success, 1, "UpdateCollection succeeds without description" ); -($success,$errorCode,$errorMessage) = +( $success, $errorCode, $errorMessage ) = UpdateCollection( $collection_id2, 'Collection2 modified', 'Description2 modified' ); is( $success, 1, "Collection2 has been modified" ); -ok( !defined $errorCode && !defined $errorMessage, - "Collection2 modified, no error code or message"); +ok( + !defined $errorCode && !defined $errorMessage, + "Collection2 modified, no error code or message" +); -($success,$errorCode,$errorMessage) = +( $success, $errorCode, $errorMessage ) = UpdateCollection( $collection_id2, undef, 'Description' ), -ok( !$success, "UpdateCollection fails without title" ); -is( $errorCode, 2, "Title missing, error code is 2"); -is( $errorMessage, 'NO_TITLE', "Title missing, error message is NO_TITLE"); + ok( !$success, "UpdateCollection fails without title" ); +is( $errorCode, 2, "Title missing, error code is 2" ); +is( $errorMessage, 'NO_TITLE', "Title missing, error message is NO_TITLE" ); is( UpdateCollection(), 'NO_ID', "UpdateCollection without params" ); @@ -194,8 +204,10 @@ my $samplebranch = { }; Koha::Library->new($samplebranch)->store; my ( $transferred, $messages ) = TransferCollection( $collection_id1, $samplebranch->{branchcode} ); -is( $transferred, - 1, "Collection1 has been transfered in the branch SAB" ); +is( + $transferred, + 1, "Collection1 has been transfered in the branch SAB" +); @collection1 = GetCollection($collection_id1); is_deeply( \@collection1, @@ -208,8 +220,10 @@ is_deeply( ( $transferred, $messages ) = TransferCollection(); is( $messages->[0]->{code}, "NO_ID", "TransferCollection without ID" ); ( $transferred, $messages ) = TransferCollection($collection_id1); -is( $messages->[0]->{code}, - 'NO_BRANCHCODE', "TransferCollection without branchcode" ); +is( + $messages->[0]->{code}, + 'NO_BRANCHCODE', "TransferCollection without branchcode" +); #Test AddItemToCollection my $record = MARC::Record->new(); @@ -223,29 +237,33 @@ $record->append_fields( my ( $biblionumber, $biblioitemnumber ) = C4::Biblio::AddBiblio( $record, '', ); my $item_id1 = $builder->build_sample_item( { - biblionumber => $biblionumber, - library => $samplebranch->{branchcode}, - barcode => 1, # FIXME This must not be hardcoded! + biblionumber => $biblionumber, + library => $samplebranch->{branchcode}, + barcode => 1, # FIXME This must not be hardcoded! itemcallnumber => 'callnumber1', } )->itemnumber; my $item_id2 = $builder->build_sample_item( { - biblionumber => $biblionumber, - library => $samplebranch->{branchcode}, - barcode => 2, # FIXME This must not be hardcoded! + biblionumber => $biblionumber, + library => $samplebranch->{branchcode}, + barcode => 2, # FIXME This must not be hardcoded! itemcallnumber => 'callnumber2', } )->itemnumber; -is( AddItemToCollection( $collection_id1, $item_id1 ), - 1, "Sampleitem1 has been added to Collection1" ); -is( AddItemToCollection( $collection_id1, $item_id2 ), - 1, "Sampleitem2 has been added to Collection1" ); +is( + AddItemToCollection( $collection_id1, $item_id1 ), + 1, "Sampleitem1 has been added to Collection1" +); +is( + AddItemToCollection( $collection_id1, $item_id2 ), + 1, "Sampleitem2 has been added to Collection1" +); #Test GetItemsInCollection my $itemsincollection1; -($itemsincollection1,$success,$errorCode,$errorMessage) = GetItemsInCollection($collection_id1); +( $itemsincollection1, $success, $errorCode, $errorMessage ) = GetItemsInCollection($collection_id1); is( scalar @$itemsincollection1, 2, "Collection1 has 2 items" ); is_deeply( $itemsincollection1, @@ -265,55 +283,65 @@ is_deeply( ], "Collection1 has Item1 and Item2" ); -($itemsincollection1,$success,$errorCode,$errorMessage) = GetItemsInCollection(); +( $itemsincollection1, $success, $errorCode, $errorMessage ) = GetItemsInCollection(); ok( !$success, "GetItemsInCollection fails without a collection ID" ); -is( $errorCode, 1, "Title missing, error code is 2"); -is( $errorMessage, 'NO_ID', "Collection ID missing, error message is NO_ID"); +is( $errorCode, 1, "Title missing, error code is 2" ); +is( $errorMessage, 'NO_ID', "Collection ID missing, error message is NO_ID" ); #Test RemoveItemFromCollection -is( RemoveItemFromCollection( $collection_id1, $item_id2 ), - 1, "Item2 has been removed from collection 1" ); +is( + RemoveItemFromCollection( $collection_id1, $item_id2 ), + 1, "Item2 has been removed from collection 1" +); $itemsincollection1 = GetItemsInCollection($collection_id1); is( scalar @$itemsincollection1, 1, "Collection1 has 1 items" ); #Test isItemInAnyCollection -is( C4::RotatingCollections::isItemInAnyCollection($item_id1), - 1, "Item1 is in a collection" ); -is( C4::RotatingCollections::isItemInAnyCollection($item_id2), - 0, "Item2 is not in a collection" ); -is( C4::RotatingCollections::isItemInAnyCollection(), - 0, "isItemInAnyCollection returns 0 if no itemid given " ); -is( C4::RotatingCollections::isItemInAnyCollection(-1), - 0, "isItemInAnyCollection returns 0 if a wrong id is given" ); +is( + C4::RotatingCollections::isItemInAnyCollection($item_id1), + 1, "Item1 is in a collection" +); +is( + C4::RotatingCollections::isItemInAnyCollection($item_id2), + 0, "Item2 is not in a collection" +); +is( + C4::RotatingCollections::isItemInAnyCollection(), + 0, "isItemInAnyCollection returns 0 if no itemid given " +); +is( + C4::RotatingCollections::isItemInAnyCollection(-1), + 0, "isItemInAnyCollection returns 0 if a wrong id is given" +); #Test isItemInThisCollection is( - C4::RotatingCollections::isItemInThisCollection( - $item_id1, $collection_id1 - ), + C4::RotatingCollections::isItemInThisCollection( $item_id1, $collection_id1 ), 1, "Item1 is in the Collection1" ); is( - C4::RotatingCollections::isItemInThisCollection( - $item_id1, $collection_id2 - ), + C4::RotatingCollections::isItemInThisCollection( $item_id1, $collection_id2 ), 0, "Item1 is not in the Collection2" ); is( - C4::RotatingCollections::isItemInThisCollection( - $item_id2, $collection_id2 - ), + C4::RotatingCollections::isItemInThisCollection( $item_id2, $collection_id2 ), 0, "Item2 is not in the Collection2" ); -is( C4::RotatingCollections::isItemInThisCollection($collection_id1), - 0, "isItemInThisCollection returns 0 is ItemId is missing" ); -is( C4::RotatingCollections::isItemInThisCollection($item_id1), - 0, "isItemInThisCollection returns 0 is Collectionid if missing" ); -is( C4::RotatingCollections::isItemInThisCollection(), - 0, "isItemInThisCollection returns 0 if no params given" ); +is( + C4::RotatingCollections::isItemInThisCollection($collection_id1), + 0, "isItemInThisCollection returns 0 is ItemId is missing" +); +is( + C4::RotatingCollections::isItemInThisCollection($item_id1), + 0, "isItemInThisCollection returns 0 is Collectionid if missing" +); +is( + C4::RotatingCollections::isItemInThisCollection(), + 0, "isItemInThisCollection returns 0 if no params given" +); #Re-add item to test deletion of collection AddItemToCollection( $collection_id1, $item_id1 ); @@ -333,12 +361,12 @@ is( "Two Collections have been deleted" ); -is( C4::RotatingCollections::isItemInAnyCollection($item_id1), - 0, "Item1 is no longer in a collection after it is deleted" ); is( - C4::RotatingCollections::isItemInThisCollection( - $item_id1, $collection_id1 - ), + C4::RotatingCollections::isItemInAnyCollection($item_id1), + 0, "Item1 is no longer in a collection after it is deleted" +); +is( + C4::RotatingCollections::isItemInThisCollection( $item_id1, $collection_id1 ), 0, "Item1 is not in the deleted Collection1" ); diff --git a/t/db_dependent/SIP/ILS.t b/t/db_dependent/SIP/ILS.t index b0bcdbfd8d..0e38cd4009 100755 --- a/t/db_dependent/SIP/ILS.t +++ b/t/db_dependent/SIP/ILS.t @@ -25,7 +25,7 @@ use Test::More tests => 15; use t::lib::TestBuilder; use t::lib::Mocks; -use C4::Reserves qw( AddReserve ); +use C4::Reserves qw( AddReserve ); use C4::Circulation qw( AddIssue ); use Koha::CirculationRules; use Koha::Database; @@ -40,10 +40,10 @@ $schema->storage->txn_begin; my $builder = t::lib::TestBuilder->new(); -my $class = 'C4::SIP::ILS'; +my $class = 'C4::SIP::ILS'; my $institution = { id => 'CPL', }; -my $ils = $class->new( $institution ); +my $ils = $class->new($institution); isa_ok( $ils, $class ); @@ -62,14 +62,20 @@ is( $ils->institution_id(), 'CPL', 'institution_id method returns id' ); is( $ils->supports('checkout'), 1, 'checkout supported' ); -is( $ils->supports('security_inhibit'), - q{}, 'unsupported feature returns false' ); +is( + $ils->supports('security_inhibit'), + q{}, 'unsupported feature returns false' +); -is( $ils->test_cardnumber_compare( 'A1234', 'a1234' ), - 1, 'borrower bc test is case insensitive' ); +is( + $ils->test_cardnumber_compare( 'A1234', 'a1234' ), + 1, 'borrower bc test is case insensitive' +); -is( $ils->test_cardnumber_compare( 'A1234', 'b1234' ), - q{}, 'borrower bc test identifies difference' ); +is( + $ils->test_cardnumber_compare( 'A1234', 'b1234' ), + q{}, 'borrower bc test identifies difference' +); subtest add_hold => sub { plan tests => 4; @@ -77,9 +83,7 @@ subtest add_hold => sub { my $library = $builder->build_object( { class => 'Koha::Libraries', - value => { - pickup_location => 1 - } + value => { pickup_location => 1 } } ); my $patron = $builder->build_object( @@ -90,8 +94,7 @@ subtest add_hold => sub { } } ); - t::lib::Mocks::mock_userenv( - { branchcode => $library->branchcode, flags => 1 } ); + t::lib::Mocks::mock_userenv( { branchcode => $library->branchcode, flags => 1 } ); my $item = $builder->build_sample_item( { @@ -123,17 +126,18 @@ subtest add_hold => sub { 'Invalid patron password.', "Empty password succeeds" ); - ok( $transaction->{ok}, "Transaction returned success"); - is( $item->biblio->holds->count(), 1, "Hold was placed on bib"); + ok( $transaction->{ok}, "Transaction returned success" ); + is( $item->biblio->holds->count(), 1, "Hold was placed on bib" ); + # FIXME: Should we not allow for item-level holds when we're passed an item barcode... - is( $item->holds->count(),0,"Hold was placed at bib level"); + is( $item->holds->count(), 0, "Hold was placed at bib level" ); }; subtest cancel_hold => sub { plan tests => 6; - my $library = $builder->build_object ({ class => 'Koha::Libraries' }); - my $patron = $builder->build_object( + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); + my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { @@ -141,11 +145,13 @@ subtest cancel_hold => sub { } } ); - t::lib::Mocks::mock_userenv({ branchcode => $library->branchcode, flags => 1 }); + t::lib::Mocks::mock_userenv( { branchcode => $library->branchcode, flags => 1 } ); - my $item = $builder->build_sample_item({ - library => $library->branchcode, - }); + my $item = $builder->build_sample_item( + { + library => $library->branchcode, + } + ); Koha::CirculationRules->set_rules( { @@ -170,25 +176,25 @@ subtest cancel_hold => sub { itemnumber => $item->itemnumber, } ); - is( $item->biblio->holds->count(), 1, "Hold was placed on bib"); - is( $item->holds->count(),1,"Hold was placed on specific item"); + is( $item->biblio->holds->count(), 1, "Hold was placed on bib" ); + is( $item->holds->count(), 1, "Hold was placed on specific item" ); - my $ils = C4::SIP::ILS->new({ id => $library->branchcode }); - my $sip_patron = C4::SIP::ILS::Patron->new( $patron->cardnumber ); - my $transaction = $ils->cancel_hold($patron->cardnumber,"",$item->barcode,undef); + my $ils = C4::SIP::ILS->new( { id => $library->branchcode } ); + my $sip_patron = C4::SIP::ILS::Patron->new( $patron->cardnumber ); + my $transaction = $ils->cancel_hold( $patron->cardnumber, "", $item->barcode, undef ); isnt( $transaction->{screen_msg}, 'Invalid patron password.', "Empty password succeeds" ); - is( $transaction->{screen_msg},"Hold Cancelled.","We get a success message when hold cancelled"); + is( $transaction->{screen_msg}, "Hold Cancelled.", "We get a success message when hold cancelled" ); - is( $item->biblio->holds->count(), 0, "Bib has 0 holds remaining"); - is( $item->holds->count(), 0, "Item has 0 holds remaining"); + is( $item->biblio->holds->count(), 0, "Bib has 0 holds remaining" ); + is( $item->holds->count(), 0, "Item has 0 holds remaining" ); }; subtest cancel_waiting_hold => sub { plan tests => 7; - my $library = $builder->build_object ({ class => 'Koha::Libraries' }); - my $patron = $builder->build_object( + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); + my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { @@ -196,11 +202,13 @@ subtest cancel_waiting_hold => sub { } } ); - t::lib::Mocks::mock_userenv({ branchcode => $library->branchcode, flags => 1 }); + t::lib::Mocks::mock_userenv( { branchcode => $library->branchcode, flags => 1 } ); - my $item = $builder->build_sample_item({ - library => $library->branchcode, - }); + my $item = $builder->build_sample_item( + { + library => $library->branchcode, + } + ); Koha::CirculationRules->set_rules( { @@ -225,31 +233,31 @@ subtest cancel_waiting_hold => sub { itemnumber => $item->itemnumber, } ); - is( $item->biblio->holds->count(), 1, "Hold was placed on bib"); - is( $item->holds->count(),1,"Hold was placed on specific item"); + is( $item->biblio->holds->count(), 1, "Hold was placed on bib" ); + is( $item->holds->count(), 1, "Hold was placed on specific item" ); - my $hold = Koha::Holds->find( $reserve_id ); + my $hold = Koha::Holds->find($reserve_id); ok( $hold, 'Get hold object' ); - $hold->update({ found => 'W' }); + $hold->update( { found => 'W' } ); $hold->get_from_storage; is( $hold->found, 'W', "Hold was correctly set to waiting." ); - my $ils = C4::SIP::ILS->new({ id => $library->branchcode }); - my $sip_patron = C4::SIP::ILS::Patron->new( $patron->cardnumber ); - my $transaction = $ils->cancel_hold($patron->cardnumber,undef,$item->barcode,undef); + my $ils = C4::SIP::ILS->new( { id => $library->branchcode } ); + my $sip_patron = C4::SIP::ILS::Patron->new( $patron->cardnumber ); + my $transaction = $ils->cancel_hold( $patron->cardnumber, undef, $item->barcode, undef ); - is( $transaction->{screen_msg},"Hold Cancelled.","We get a success message when hold cancelled"); + is( $transaction->{screen_msg}, "Hold Cancelled.", "We get a success message when hold cancelled" ); - is( $item->biblio->holds->count(), 0, "Bib has 0 holds remaining"); - is( $item->holds->count(), 0, "Item has 0 holds remaining"); + is( $item->biblio->holds->count(), 0, "Bib has 0 holds remaining" ); + is( $item->holds->count(), 0, "Item has 0 holds remaining" ); }; subtest checkout => sub { plan tests => 4; - my $library = $builder->build_object ({ class => 'Koha::Libraries' }); - my $patron = $builder->build_object( + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); + my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { @@ -257,11 +265,13 @@ subtest checkout => sub { } } ); - t::lib::Mocks::mock_userenv({ branchcode => $library->branchcode, flags => 1 }); + t::lib::Mocks::mock_userenv( { branchcode => $library->branchcode, flags => 1 } ); - my $item = $builder->build_sample_item({ - library => $library->branchcode, - }); + my $item = $builder->build_sample_item( + { + library => $library->branchcode, + } + ); Koha::CirculationRules->set_rules( { @@ -281,24 +291,27 @@ subtest checkout => sub { AddIssue( $patron, $item->barcode, undef, 0 ); my $checkout = $item->checkout; - ok( defined($checkout), "Checkout added"); - is( $checkout->renewals_count, 0, "Correct renewals"); + ok( defined($checkout), "Checkout added" ); + is( $checkout->renewals_count, 0, "Correct renewals" ); - my $ils = C4::SIP::ILS->new({ id => $library->branchcode }); - my $sip_patron = C4::SIP::ILS::Patron->new( $patron->cardnumber ); - my $transaction = $ils->checkout($patron->cardnumber, $item->barcode); + my $ils = C4::SIP::ILS->new( { id => $library->branchcode } ); + my $sip_patron = C4::SIP::ILS::Patron->new( $patron->cardnumber ); + my $transaction = $ils->checkout( $patron->cardnumber, $item->barcode ); - is( $transaction->{screen_msg},"Item already checked out to you: renewing item.", "We get a success message when issue is renewed"); + is( + $transaction->{screen_msg}, "Item already checked out to you: renewing item.", + "We get a success message when issue is renewed" + ); $checkout->discard_changes(); - is( $checkout->renewals_count, 1, "Renewals has been reduced"); + is( $checkout->renewals_count, 1, "Renewals has been reduced" ); }; subtest renew_all => sub { plan tests => 1; - my $library = $builder->build_object ({ class => 'Koha::Libraries' }); - my $patron = $builder->build_object( + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); + my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { @@ -306,9 +319,9 @@ subtest renew_all => sub { } } ); - t::lib::Mocks::mock_userenv({ branchcode => $library->branchcode, flags => 1 }); + t::lib::Mocks::mock_userenv( { branchcode => $library->branchcode, flags => 1 } ); - my $ils = C4::SIP::ILS->new({ id => $library->branchcode }); + my $ils = C4::SIP::ILS->new( { id => $library->branchcode } ); # Send empty AD segments (i.e. empty string for patron_pwd) my $transaction = $ils->renew_all( $patron->cardnumber, "", undef ); diff --git a/t/db_dependent/SIP/Message.t b/t/db_dependent/SIP/Message.t index dea011311a..598eaef2f2 100755 --- a/t/db_dependent/SIP/Message.t +++ b/t/db_dependent/SIP/Message.t @@ -30,7 +30,7 @@ use Test::Warn; use t::lib::Mocks; use t::lib::TestBuilder; -use C4::Reserves qw( AddReserve ); +use C4::Reserves qw( AddReserve ); use C4::Circulation qw( AddIssue AddReturn ); use Koha::Database; use Koha::AuthUtils qw(hash_password); @@ -44,7 +44,7 @@ use Koha::Holds; use C4::SIP::ILS; use C4::SIP::ILS::Patron; -use C4::SIP::Sip qw(write_msg); +use C4::SIP::Sip qw(write_msg); use C4::SIP::Sip::Constants qw(:all); use C4::SIP::Sip::MsgType; @@ -131,29 +131,35 @@ subtest 'UseLocationAsAQInSIP syspref tests' => sub { my $builder = t::lib::TestBuilder->new(); - my $branchcode = $builder->build({ source => 'Branch' })->{branchcode}; + my $branchcode = $builder->build( { source => 'Branch' } )->{branchcode}; - t::lib::Mocks::mock_preference('UseLocationAsAQInSIP', 0); + t::lib::Mocks::mock_preference( 'UseLocationAsAQInSIP', 0 ); - my $item = $builder->build_sample_item( + my $item = $builder->build_sample_item( { - damaged => 0, - withdrawn => 0, - itemlost => 0, - restricted => 0, - homebranch => $branchcode, - holdingbranch => $branchcode, + damaged => 0, + withdrawn => 0, + itemlost => 0, + restricted => 0, + homebranch => $branchcode, + holdingbranch => $branchcode, permanent_location => "PERMANENT_LOCATION" } ); my $sip_item = C4::SIP::ILS::Item->new( $item->barcode ); - is( $sip_item->permanent_location, $branchcode, "When UseLocationAsAQInSIP is not set SIP item has permanent_location set to value of homebranch" ); + is( + $sip_item->permanent_location, $branchcode, + "When UseLocationAsAQInSIP is not set SIP item has permanent_location set to value of homebranch" + ); - t::lib::Mocks::mock_preference('UseLocationAsAQInSIP', 1); + t::lib::Mocks::mock_preference( 'UseLocationAsAQInSIP', 1 ); $sip_item = C4::SIP::ILS::Item->new( $item->barcode ); - is( $sip_item->permanent_location, "PERMANENT_LOCATION", "When UseLocationAsAQInSIP is set SIP item has permanent_location set to value of item permanent_location" ); + is( + $sip_item->permanent_location, "PERMANENT_LOCATION", + "When UseLocationAsAQInSIP is set SIP item has permanent_location set to value of item permanent_location" + ); $schema->storage->txn_rollback; }; @@ -167,7 +173,7 @@ subtest 'hold_patron_name() tests' => sub { my $builder = t::lib::TestBuilder->new(); - my $branchcode = $builder->build({ source => 'Branch' })->{branchcode}; + my $branchcode = $builder->build( { source => 'Branch' } )->{branchcode}; my ( $response, $findpatron ); my $mocks = create_mocks( \$response, \$findpatron, \$branchcode ); @@ -182,7 +188,7 @@ subtest 'hold_patron_name() tests' => sub { } ); - my $server = { ils => $mocks->{ils} }; + my $server = { ils => $mocks->{ils} }; my $sip_item = C4::SIP::ILS::Item->new( $item->barcode ); is( $sip_item->hold_patron_name, q{}, "SIP item with no hold returns empty string for patron name" ); @@ -203,48 +209,61 @@ subtest 'Lastseen response patron info' => sub { my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; - - my $builder = t::lib::TestBuilder->new(); - my $branchcode = $builder->build({ source => 'Branch' })->{branchcode}; + my $builder = t::lib::TestBuilder->new(); + my $branchcode = $builder->build( { source => 'Branch' } )->{branchcode}; my ( $response, $findpatron ); - my $mocks = create_mocks( \$response, \$findpatron, \$branchcode ); - my $seen_patron = $builder->build({ - source => 'Borrower', - value => { - lastseen => '2001-01-01', - password => hash_password( PATRON_PW ), - branchcode => $branchcode, - }, - }); - my $cardnum = $seen_patron->{cardnumber}; - my $sip_patron = C4::SIP::ILS::Patron->new( $cardnum ); + my $mocks = create_mocks( \$response, \$findpatron, \$branchcode ); + my $seen_patron = $builder->build( + { + source => 'Borrower', + value => { + lastseen => '2001-01-01', + password => hash_password(PATRON_PW), + branchcode => $branchcode, + }, + } + ); + my $cardnum = $seen_patron->{cardnumber}; + my $sip_patron = C4::SIP::ILS::Patron->new($cardnum); $findpatron = $sip_patron; - my $siprequest = PATRON_INFO. 'engYYYYMMDDZZZZHHMMSS'.'Y '. - FID_INST_ID. $branchcode. '|'. - FID_PATRON_ID. $cardnum. '|'. - FID_PATRON_PWD. PATRON_PW. '|'; + my $siprequest = + PATRON_INFO + . 'engYYYYMMDDZZZZHHMMSS' + . 'Y ' + . FID_INST_ID + . $branchcode . '|' + . FID_PATRON_ID + . $cardnum . '|' + . FID_PATRON_PWD + . PATRON_PW . '|'; my $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 ); my $server = { ils => $mocks->{ils} }; undef $response; t::lib::Mocks::mock_preference( 'TrackLastPatronActivityTriggers', '' ); - $msg->handle_patron_info( $server ); + $msg->handle_patron_info($server); isnt( $response, undef, 'At least we got a response.' ); my $respcode = substr( $response, 0, 2 ); is( $respcode, PATRON_INFO_RESP, 'Response code fine' ); - $seen_patron = Koha::Patrons->find({ cardnumber => $seen_patron->{cardnumber} }); - is( output_pref({str => $seen_patron->lastseen(), dateonly => 1}), output_pref({str => '2001-01-01', dateonly => 1}),'Last seen not updated if not tracking patrons'); + $seen_patron = Koha::Patrons->find( { cardnumber => $seen_patron->{cardnumber} } ); + is( + output_pref( { str => $seen_patron->lastseen(), dateonly => 1 } ), + output_pref( { str => '2001-01-01', dateonly => 1 } ), 'Last seen not updated if not tracking patrons' + ); undef $response; t::lib::Mocks::mock_preference( 'TrackLastPatronActivityTriggers', 'connection' ); - $msg->handle_patron_info( $server ); + $msg->handle_patron_info($server); isnt( $response, undef, 'At least we got a response.' ); $respcode = substr( $response, 0, 2 ); is( $respcode, PATRON_INFO_RESP, 'Response code fine' ); - $seen_patron = Koha::Patrons->find({ cardnumber => $seen_patron->cardnumber() }); - is( output_pref({str => $seen_patron->lastseen(), dateonly => 1}), output_pref({dt => dt_from_string(), dateonly => 1}),'Last seen updated if tracking patrons'); + $seen_patron = Koha::Patrons->find( { cardnumber => $seen_patron->cardnumber() } ); + is( + output_pref( { str => $seen_patron->lastseen(), dateonly => 1 } ), + output_pref( { dt => dt_from_string(), dateonly => 1 } ), 'Last seen updated if tracking patrons' + ); $schema->storage->txn_rollback; }; @@ -332,46 +351,47 @@ subtest 'Fine items, currency, start and end item response in patron info' => su $schema->storage->txn_rollback; }; - subtest "Test patron_status_string" => sub { my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; plan tests => 9; - my $builder = t::lib::TestBuilder->new(); - my $branchcode = $builder->build({ source => 'Branch' })->{branchcode}; - my $patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { - branchcode => $branchcode, - }, - }); + my $builder = t::lib::TestBuilder->new(); + my $branchcode = $builder->build( { source => 'Branch' } )->{branchcode}; + my $patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { + branchcode => $branchcode, + }, + } + ); my $sip_patron = C4::SIP::ILS::Patron->new( $patron->cardnumber ); - t::lib::Mocks::mock_userenv({ branchcode => $branchcode }); + t::lib::Mocks::mock_userenv( { branchcode => $branchcode } ); - my $item1 = $builder->build_sample_item( + my $item1 = $builder->build_sample_item( { - damaged => 0, - withdrawn => 0, - itemlost => 0, - restricted => 0, - homebranch => $branchcode, - holdingbranch => $branchcode, + damaged => 0, + withdrawn => 0, + itemlost => 0, + restricted => 0, + homebranch => $branchcode, + holdingbranch => $branchcode, permanent_location => "PERMANENT_LOCATION" } ); - AddIssue( $patron, $item1->barcode ); + AddIssue( $patron, $item1->barcode ); - my $item2 = $builder->build_sample_item( + my $item2 = $builder->build_sample_item( { - damaged => 0, - withdrawn => 0, - itemlost => 0, - restricted => 0, - homebranch => $branchcode, - holdingbranch => $branchcode, + damaged => 0, + withdrawn => 0, + itemlost => 0, + restricted => 0, + homebranch => $branchcode, + holdingbranch => $branchcode, permanent_location => "PERMANENT_LOCATION" } ); @@ -395,33 +415,54 @@ subtest "Test patron_status_string" => sub { my $server->{account}->{lost_block_checkout} = undef; my $patron_status_string = C4::SIP::Sip::MsgType::patron_status_string( $sip_patron, $server ); - is( substr($patron_status_string, 9, 1), q{ }, "lost_block_checkout = 0 does not block checkouts with 2 lost checkouts" );; + is( + substr( $patron_status_string, 9, 1 ), q{ }, + "lost_block_checkout = 0 does not block checkouts with 2 lost checkouts" + ); $server->{account}->{lost_block_checkout} = 0; $patron_status_string = C4::SIP::Sip::MsgType::patron_status_string( $sip_patron, $server ); - is( substr($patron_status_string, 9, 1), q{ }, "lost_block_checkout = 0 does not block checkouts with 2 lost checkouts" );; + is( + substr( $patron_status_string, 9, 1 ), q{ }, + "lost_block_checkout = 0 does not block checkouts with 2 lost checkouts" + ); $server->{account}->{lost_block_checkout} = 1; $patron_status_string = C4::SIP::Sip::MsgType::patron_status_string( $sip_patron, $server ); - is( substr($patron_status_string, 9, 1), q{Y}, "lost_block_checkout = 1 does block checkouts with 2 lost checkouts" );; + is( + substr( $patron_status_string, 9, 1 ), q{Y}, + "lost_block_checkout = 1 does block checkouts with 2 lost checkouts" + ); $server->{account}->{lost_block_checkout} = 2; $patron_status_string = C4::SIP::Sip::MsgType::patron_status_string( $sip_patron, $server ); - is( substr($patron_status_string, 9, 1), q{Y}, "lost_block_checkout = 2 does block checkouts with 2 lost checkouts" );; + is( + substr( $patron_status_string, 9, 1 ), q{Y}, + "lost_block_checkout = 2 does block checkouts with 2 lost checkouts" + ); $server->{account}->{lost_block_checkout} = 3; $patron_status_string = C4::SIP::Sip::MsgType::patron_status_string( $sip_patron, $server ); - is( substr($patron_status_string, 9, 1), q{ }, "lost_block_checkout = 3 does not block checkouts with 2 lost checkouts" );; + is( + substr( $patron_status_string, 9, 1 ), q{ }, + "lost_block_checkout = 3 does not block checkouts with 2 lost checkouts" + ); - $server->{account}->{lost_block_checkout} = 2; + $server->{account}->{lost_block_checkout} = 2; $server->{account}->{lost_block_checkout_value} = 2; $patron_status_string = C4::SIP::Sip::MsgType::patron_status_string( $sip_patron, $server ); - is( substr($patron_status_string, 9, 1), q{ }, "lost_block_checkout = 2, lost_block_checkout_value = 2 does not block checkouts with 2 lost checkouts where only 1 has itemlost = 2" ); + is( + substr( $patron_status_string, 9, 1 ), q{ }, + "lost_block_checkout = 2, lost_block_checkout_value = 2 does not block checkouts with 2 lost checkouts where only 1 has itemlost = 2" + ); - $server->{account}->{lost_block_checkout} = 1; + $server->{account}->{lost_block_checkout} = 1; $server->{account}->{lost_block_checkout_value} = 2; $patron_status_string = C4::SIP::Sip::MsgType::patron_status_string( $sip_patron, $server ); - is( substr($patron_status_string, 9, 1), q{Y}, "lost_block_checkout = 2, lost_block_checkout_value = 2 does block checkouts with 2 lost checkouts where only 1 has itemlost = 2" ); + is( + substr( $patron_status_string, 9, 1 ), q{Y}, + "lost_block_checkout = 2, lost_block_checkout_value = 2 does block checkouts with 2 lost checkouts where only 1 has itemlost = 2" + ); $schema->storage->txn_rollback; }; @@ -537,22 +578,25 @@ subtest "Test build_additional_item_fields_string" => sub { my $builder = t::lib::TestBuilder->new(); - my $item = $builder->build_sample_item; + my $item = $builder->build_sample_item; my $ils_item = C4::SIP::ILS::Item->new( $item->barcode ); my $server = {}; - $server->{account}->{item_field}->{code} = 'itemnumber'; + $server->{account}->{item_field}->{code} = 'itemnumber'; $server->{account}->{item_field}->{field} = 'XY'; - my $attribute_string = $ils_item->build_additional_item_fields_string( $server ); - is( $attribute_string, "XY".$item->itemnumber."|", 'Attribute field generated correctly with single param' ); + my $attribute_string = $ils_item->build_additional_item_fields_string($server); + is( $attribute_string, "XY" . $item->itemnumber . "|", 'Attribute field generated correctly with single param' ); - $server = {}; - $server->{account}->{item_field}->[0]->{code} = 'itemnumber'; + $server = {}; + $server->{account}->{item_field}->[0]->{code} = 'itemnumber'; $server->{account}->{item_field}->[0]->{field} = 'XY'; - $server->{account}->{item_field}->[1]->{code} = 'biblionumber'; + $server->{account}->{item_field}->[1]->{code} = 'biblionumber'; $server->{account}->{item_field}->[1]->{field} = 'YZ'; - $attribute_string = $ils_item->build_additional_item_fields_string( $server ); - is( $attribute_string, sprintf("XY%s|YZ%s|", $item->itemnumber, $item->biblionumber), 'Attribute field generated correctly with multiple params' ); + $attribute_string = $ils_item->build_additional_item_fields_string($server); + is( + $attribute_string, sprintf( "XY%s|YZ%s|", $item->itemnumber, $item->biblionumber ), + 'Attribute field generated correctly with multiple params' + ); $schema->storage->txn_rollback; }; @@ -565,24 +609,27 @@ subtest "Test build_custom_field_string" => sub { my $builder = t::lib::TestBuilder->new(); - my $item = $builder->build_sample_item; - my $item_id = $item->id; + my $item = $builder->build_sample_item; + my $item_id = $item->id; my $item_barcode = $item->barcode; - my $ils_item = C4::SIP::ILS::Item->new( $item->barcode ); + my $ils_item = C4::SIP::ILS::Item->new( $item->barcode ); my $server = {}; - $server->{account}->{custom_item_field}->{field} = "XY"; + $server->{account}->{custom_item_field}->{field} = "XY"; $server->{account}->{custom_item_field}->{template} = "[% item.id %] [% item.barcode %], woo!"; - my $attribute_string = $ils_item->build_additional_item_fields_string( $server ); + my $attribute_string = $ils_item->build_additional_item_fields_string($server); is( $attribute_string, "XY$item_id $item_barcode, woo!|", 'Attribute field generated correctly with single param' ); - $server = {}; - $server->{account}->{custom_item_field}->[0]->{field} = "ZY"; + $server = {}; + $server->{account}->{custom_item_field}->[0]->{field} = "ZY"; $server->{account}->{custom_item_field}->[0]->{template} = "[% item.id %]!"; - $server->{account}->{custom_item_field}->[1]->{field} = "ZX"; + $server->{account}->{custom_item_field}->[1]->{field} = "ZX"; $server->{account}->{custom_item_field}->[1]->{template} = "[% item.barcode %]*"; - $attribute_string = $ils_item->build_additional_item_fields_string( $server ); - is( $attribute_string, sprintf("ZY%s!|ZX%s*|", $item_id, $item_barcode), 'Attribute field generated correctly with multiple params' ); + $attribute_string = $ils_item->build_additional_item_fields_string($server); + is( + $attribute_string, sprintf( "ZY%s!|ZX%s*|", $item_id, $item_barcode ), + 'Attribute field generated correctly with multiple params' + ); $schema->storage->txn_rollback; }; @@ -593,107 +640,137 @@ subtest "Test cr_item_field" => sub { plan tests => 8; - my $builder = t::lib::TestBuilder->new(); - my $branchcode = $builder->build({ source => 'Branch' })->{branchcode}; - my $branchcode2 = $builder->build({ source => 'Branch' })->{branchcode}; + my $builder = t::lib::TestBuilder->new(); + my $branchcode = $builder->build( { source => 'Branch' } )->{branchcode}; + my $branchcode2 = $builder->build( { source => 'Branch' } )->{branchcode}; my ( $response, $findpatron ); my $mocks = create_mocks( \$response, \$findpatron, \$branchcode ); # create some data - my $patron1 = $builder->build({ - source => 'Borrower', - value => { - password => hash_password( PATRON_PW ), - }, - }); - my $card1 = $patron1->{cardnumber}; - my $sip_patron1 = C4::SIP::ILS::Patron->new( $card1 ); + my $patron1 = $builder->build( + { + source => 'Borrower', + value => { + password => hash_password(PATRON_PW), + }, + } + ); + my $card1 = $patron1->{cardnumber}; + my $sip_patron1 = C4::SIP::ILS::Patron->new($card1); $findpatron = $sip_patron1; - my $item_object = $builder->build_sample_item({ - damaged => 0, - withdrawn => 0, - itemlost => 0, - restricted => 0, - homebranch => $branchcode, - holdingbranch => $branchcode, - datelastseen => '1900-01-01', - }); + my $item_object = $builder->build_sample_item( + { + damaged => 0, + withdrawn => 0, + itemlost => 0, + restricted => 0, + homebranch => $branchcode, + holdingbranch => $branchcode, + datelastseen => '1900-01-01', + } + ); my $mockILS = $mocks->{ils}; - my $server = { ils => $mockILS, account => {} }; + my $server = { ils => $mockILS, account => {} }; $mockILS->mock( 'institution', sub { $branchcode; } ); - $mockILS->mock( 'supports', sub { return; } ); - $mockILS->mock( 'checkin', sub { - shift; - return C4::SIP::ILS->checkin(@_); - }); + $mockILS->mock( 'supports', sub { return; } ); + $mockILS->mock( + 'checkin', + sub { + shift; + return C4::SIP::ILS->checkin(@_); + } + ); my $today = dt_from_string; my $respcode; # Not checked out, toggle option checked_in_ok - my $siprequest = CHECKIN . 'N' . 'YYYYMMDDZZZZHHMMSS' . - siprequestdate( $today->clone->add( days => 1) ) . - FID_INST_ID . $branchcode . '|'. - FID_ITEM_ID . $item_object->barcode . '|' . - FID_TERMINAL_PWD . 'ignored' . '|'; + my $siprequest = + CHECKIN . 'N' + . 'YYYYMMDDZZZZHHMMSS' + . siprequestdate( $today->clone->add( days => 1 ) ) + . FID_INST_ID + . $branchcode . '|' + . FID_ITEM_ID + . $item_object->barcode . '|' + . FID_TERMINAL_PWD + . 'ignored' . '|'; undef $response; my $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 ); $server->{account}->{cr_item_field} = 'itemnumber'; - $msg->handle_checkin( $server ); + $msg->handle_checkin($server); my $id = $item_object->id; - ok( $response =~ m/CR$id/, "Found correct CR field in response"); + ok( $response =~ m/CR$id/, "Found correct CR field in response" ); - $siprequest = ITEM_INFORMATION . 'YYYYMMDDZZZZHHMMSS' . - FID_INST_ID . $branchcode . '|'. - FID_ITEM_ID . $item_object->barcode . '|' . - FID_TERMINAL_PWD . 'ignored' . '|'; + $siprequest = + ITEM_INFORMATION + . 'YYYYMMDDZZZZHHMMSS' + . FID_INST_ID + . $branchcode . '|' + . FID_ITEM_ID + . $item_object->barcode . '|' + . FID_TERMINAL_PWD + . 'ignored' . '|'; undef $response; $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 ); - $mockILS->mock( 'find_item', sub { - return C4::SIP::ILS::Item->new( $item_object->barcode ); - }); + $mockILS->mock( + 'find_item', + sub { + return C4::SIP::ILS::Item->new( $item_object->barcode ); + } + ); $server->{account}->{cr_item_field} = 'itype'; $server->{account}->{seen_on_item_information} = ''; - $msg->handle_item_information( $server ); + $msg->handle_item_information($server); $item_object->get_from_storage; my $stored_date = "1900-01-01 00:00:00"; is( $item_object->datelastseen, $stored_date, "datelastseen remains unchanged" ); - $item_object->update({ itemlost => 1, datelastseen => '1900-01-01' }); + $item_object->update( { itemlost => 1, datelastseen => '1900-01-01' } ); $server->{account}->{seen_on_item_information} = 'keep_lost'; - $msg->handle_item_information( $server ); + $msg->handle_item_information($server); $item_object = Koha::Items->find( $item_object->id ); isnt( $item_object->datelastseen, $stored_date, "datelastseen updated" ); is( $item_object->itemlost, 1, "item remains lost" ); - $item_object->update({ itemlost => 1, datelastseen => '1900-01-01' }); + $item_object->update( { itemlost => 1, datelastseen => '1900-01-01' } ); $server->{account}->{seen_on_item_information} = 'mark_found'; - $msg->handle_item_information( $server ); + $msg->handle_item_information($server); $item_object = Koha::Items->find( $item_object->id ); isnt( $item_object->datelastseen, $stored_date, "datelastseen updated" ); is( $item_object->itemlost, 0, "item is no longer lost" ); my $itype = $item_object->itype; - ok( $response =~ m/CR$itype/, "Found correct CR field in response"); + ok( $response =~ m/CR$itype/, "Found correct CR field in response" ); $server->{account}->{format_due_date} = 1; - t::lib::Mocks::mock_preference( 'dateFormat', 'sql' ); - my $issue = Koha::Checkout->new({ branchcode => $branchcode, borrowernumber => $patron1->{borrowernumber}, itemnumber => $item_object->itemnumber, date_due => "1999-01-01 12:59:00" })->store; - $siprequest = ITEM_INFORMATION . 'YYYYMMDDZZZZHHMMSS' . - FID_INST_ID . $branchcode . '|'. - FID_ITEM_ID . $item_object->barcode . '|' . - FID_TERMINAL_PWD . 'ignored' . '|'; + t::lib::Mocks::mock_preference( 'dateFormat', 'sql' ); + my $issue = Koha::Checkout->new( + { + branchcode => $branchcode, borrowernumber => $patron1->{borrowernumber}, + itemnumber => $item_object->itemnumber, date_due => "1999-01-01 12:59:00" + } + )->store; + $siprequest = + ITEM_INFORMATION + . 'YYYYMMDDZZZZHHMMSS' + . FID_INST_ID + . $branchcode . '|' + . FID_ITEM_ID + . $item_object->barcode . '|' + . FID_TERMINAL_PWD + . 'ignored' . '|'; undef $response; $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 ); - $msg->handle_item_information( $server ); - ok( $response =~ m/AH1999-01-01 12:59/, "Found correct CR field in response"); + $msg->handle_item_information($server); + ok( $response =~ m/AH1999-01-01 12:59/, "Found correct CR field in response" ); $schema->storage->txn_rollback; }; @@ -704,20 +781,22 @@ subtest 'Patron info summary > 5 should not crash server' => sub { $schema->storage->txn_begin; plan tests => 22; - my $builder = t::lib::TestBuilder->new(); - my $branchcode = $builder->build({ source => 'Branch' })->{branchcode}; + my $builder = t::lib::TestBuilder->new(); + my $branchcode = $builder->build( { source => 'Branch' } )->{branchcode}; my ( $response, $findpatron ); - my $mocks = create_mocks( \$response, \$findpatron, \$branchcode ); - my $seen_patron = $builder->build({ - source => 'Borrower', - value => { - lastseen => '2001-01-01', - password => hash_password( PATRON_PW ), - branchcode => $branchcode, - }, - }); - my $cardnum = $seen_patron->{cardnumber}; - my $sip_patron = C4::SIP::ILS::Patron->new( $cardnum ); + my $mocks = create_mocks( \$response, \$findpatron, \$branchcode ); + my $seen_patron = $builder->build( + { + source => 'Borrower', + value => { + lastseen => '2001-01-01', + password => hash_password(PATRON_PW), + branchcode => $branchcode, + }, + } + ); + my $cardnum = $seen_patron->{cardnumber}; + my $sip_patron = C4::SIP::ILS::Patron->new($cardnum); $findpatron = $sip_patron; my @summaries = ( @@ -733,16 +812,22 @@ subtest 'Patron info summary > 5 should not crash server' => sub { ' Y ', ' Y', ); - for my $summary ( @summaries ) { - my $siprequest = PATRON_INFO . 'engYYYYMMDDZZZZHHMMSS' . $summary . - FID_INST_ID . $branchcode . '|' . - FID_PATRON_ID . $cardnum . '|' . - FID_PATRON_PWD . PATRON_PW . '|'; + for my $summary (@summaries) { + my $siprequest = + PATRON_INFO + . 'engYYYYMMDDZZZZHHMMSS' + . $summary + . FID_INST_ID + . $branchcode . '|' + . FID_PATRON_ID + . $cardnum . '|' + . FID_PATRON_PWD + . PATRON_PW . '|'; my $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 ); my $server = { ils => $mocks->{ils} }; undef $response; - $msg->handle_patron_info( $server ); + $msg->handle_patron_info($server); isnt( $response, undef, 'At least we got a response.' ); my $respcode = substr( $response, 0, 2 ); @@ -759,34 +844,34 @@ subtest 'SC status tests' => sub { plan tests => 2; - my $builder = t::lib::TestBuilder->new(); - my $branchcode = $builder->build({ source => 'Branch' })->{branchcode}; - my $sip_user = $builder->build_object({ class => "Koha::Patrons" }); + my $builder = t::lib::TestBuilder->new(); + my $branchcode = $builder->build( { source => 'Branch' } )->{branchcode}; + my $sip_user = $builder->build_object( { class => "Koha::Patrons" } ); my ( $response, $findpatron ); - my $mocks = create_mocks( \$response, \$findpatron, \$branchcode ); + my $mocks = create_mocks( \$response, \$findpatron, \$branchcode ); my $mockILS = $mocks->{ils}; - $mockILS->mock( 'checkout_ok', sub {1} ); - $mockILS->mock( 'checkin_ok', sub {1} ); - $mockILS->mock( 'status_update_ok', sub {1} ); - $mockILS->mock( 'offline_ok', sub {1} ); - $mockILS->mock( 'supports', sub {1} ); + $mockILS->mock( 'checkout_ok', sub { 1 } ); + $mockILS->mock( 'checkin_ok', sub { 1 } ); + $mockILS->mock( 'status_update_ok', sub { 1 } ); + $mockILS->mock( 'offline_ok', sub { 1 } ); + $mockILS->mock( 'supports', sub { 1 } ); my $server = Test::MockObject->new(); - $server->mock( 'get_timeout', sub {'100'}); - $server->{ils} = $mockILS; + $server->mock( 'get_timeout', sub { '100' } ); + $server->{ils} = $mockILS; $server->{sip_username} = $sip_user->userid; - $server->{account} = {}; - $server->{policy} = { renewal =>1,retries=>'000'}; + $server->{account} = {}; + $server->{policy} = { renewal => 1, retries => '000' }; my $siprequest = SC_STATUS . '0' . '030' . '2.00'; - my $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 ); - $msg->handle_sc_status( $server ); + my $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 ); + $msg->handle_sc_status($server); like( $response, qr/98YYYYYY100000[0-9 ]{19}.00AO|BXYYYYYYYYYYYYYYYY|/, 'At least we got a response.' ); $sip_user->delete; - dies_ok { $msg->handle_sc_status( $server ) } "Dies if sip user cannot be found"; + dies_ok { $msg->handle_sc_status($server) } "Dies if sip user cannot be found"; $schema->storage->txn_rollback; }; @@ -887,118 +972,148 @@ subtest 'test_allow_additional_materials_checkout' => sub { # END of main code sub test_request_patron_status_v2 { - my $builder = t::lib::TestBuilder->new(); - my $branchcode = $builder->build({ source => 'Branch' })->{branchcode}; + my $builder = t::lib::TestBuilder->new(); + my $branchcode = $builder->build( { source => 'Branch' } )->{branchcode}; my ( $response, $findpatron ); my $mocks = create_mocks( \$response, \$findpatron, \$branchcode ); - my $patron1 = $builder->build({ - source => 'Borrower', - value => { - password => hash_password( PATRON_PW ), - }, - }); - my $card1 = $patron1->{cardnumber}; - my $sip_patron1 = C4::SIP::ILS::Patron->new( $card1 ); + my $patron1 = $builder->build( + { + source => 'Borrower', + value => { + password => hash_password(PATRON_PW), + }, + } + ); + my $card1 = $patron1->{cardnumber}; + my $sip_patron1 = C4::SIP::ILS::Patron->new($card1); $findpatron = $sip_patron1; - my $siprequest = PATRON_STATUS_REQ. 'engYYYYMMDDZZZZHHMMSS'. - FID_INST_ID. $branchcode. '|'. - FID_PATRON_ID. $card1. '|'. - FID_PATRON_PWD. PATRON_PW. '|'; + my $siprequest = + PATRON_STATUS_REQ + . 'engYYYYMMDDZZZZHHMMSS' + . FID_INST_ID + . $branchcode . '|' + . FID_PATRON_ID + . $card1 . '|' + . FID_PATRON_PWD + . PATRON_PW . '|'; my $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 ); my $server = { ils => $mocks->{ils} }; undef $response; - $msg->handle_patron_status( $server ); + $msg->handle_patron_status($server); isnt( $response, undef, 'At least we got a response.' ); my $respcode = substr( $response, 0, 2 ); is( $respcode, PATRON_STATUS_RESP, 'Response code fine' ); - check_field( $respcode, $response, FID_INST_ID, $branchcode , 'Verified institution id' ); - check_field( $respcode, $response, FID_PATRON_ID, $card1, 'Verified patron id' ); - check_field( $respcode, $response, FID_PERSONAL_NAME, $patron1->{surname}, 'Verified patron name', 'contains' ); - check_field( $respcode, $response, FID_VALID_PATRON, 'Y', 'Verified code BL' ); - check_field( $respcode, $response, FID_VALID_PATRON_PWD, 'Y', 'Verified code CQ' ); - check_field( $respcode, $response, FID_SCREEN_MSG, '.+', 'Verified non-empty screen message', 'regex' ); + check_field( $respcode, $response, FID_INST_ID, $branchcode, 'Verified institution id' ); + check_field( $respcode, $response, FID_PATRON_ID, $card1, 'Verified patron id' ); + check_field( $respcode, $response, FID_PERSONAL_NAME, $patron1->{surname}, 'Verified patron name', 'contains' ); + check_field( $respcode, $response, FID_VALID_PATRON, 'Y', 'Verified code BL' ); + check_field( $respcode, $response, FID_VALID_PATRON_PWD, 'Y', 'Verified code CQ' ); + check_field( $respcode, $response, FID_SCREEN_MSG, '.+', 'Verified non-empty screen message', 'regex' ); # Now, we pass a wrong password and verify CQ again - $siprequest = PATRON_STATUS_REQ. 'engYYYYMMDDZZZZHHMMSS'. - FID_INST_ID. $branchcode. '|'. - FID_PATRON_ID. $card1. '|'. - FID_PATRON_PWD. 'wrong_password'. '|'; + $siprequest = + PATRON_STATUS_REQ + . 'engYYYYMMDDZZZZHHMMSS' + . FID_INST_ID + . $branchcode . '|' + . FID_PATRON_ID + . $card1 . '|' + . FID_PATRON_PWD + . 'wrong_password' . '|'; $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 ); undef $response; - $msg->handle_patron_status( $server ); + $msg->handle_patron_status($server); $respcode = substr( $response, 0, 2 ); check_field( $respcode, $response, FID_VALID_PATRON_PWD, 'N', 'Verified code CQ for wrong pw' ); # Check empty password and verify CQ again - $siprequest = PATRON_STATUS_REQ. 'engYYYYMMDDZZZZHHMMSS'. - FID_INST_ID. $branchcode. '|'. - FID_PATRON_ID. $card1. '|'. - FID_PATRON_PWD. '|'; + $siprequest = + PATRON_STATUS_REQ + . 'engYYYYMMDDZZZZHHMMSS' + . FID_INST_ID + . $branchcode . '|' + . FID_PATRON_ID + . $card1 . '|' + . FID_PATRON_PWD . '|'; $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 ); undef $response; - $msg->handle_patron_status( $server ); + $msg->handle_patron_status($server); $respcode = substr( $response, 0, 2 ); check_field( $respcode, $response, FID_VALID_PATRON_PWD, 'N', 'code CQ should be N for empty AD' ); # Finally, we send a wrong card number and check AE, BL # This is done by removing the new patron first - Koha::Patrons->search({ cardnumber => $card1 })->delete; + Koha::Patrons->search( { cardnumber => $card1 } )->delete; undef $findpatron; - $siprequest = PATRON_STATUS_REQ. 'engYYYYMMDDZZZZHHMMSS'. - FID_INST_ID. $branchcode. '|'. - FID_PATRON_ID. $card1. '|'. - FID_PATRON_PWD. PATRON_PW. '|'; + $siprequest = + PATRON_STATUS_REQ + . 'engYYYYMMDDZZZZHHMMSS' + . FID_INST_ID + . $branchcode . '|' + . FID_PATRON_ID + . $card1 . '|' + . FID_PATRON_PWD + . PATRON_PW . '|'; $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 ); undef $response; - $msg->handle_patron_status( $server ); + $msg->handle_patron_status($server); $respcode = substr( $response, 0, 2 ); - check_field( $respcode, $response, FID_VALID_PATRON, 'N', 'Verified code BL for wrong cardnumber' ); - check_field( $respcode, $response, FID_PERSONAL_NAME, '', 'Name should be empty now' ); - check_field( $respcode, $response, FID_SCREEN_MSG, '.+', 'But we have a screen msg', 'regex' ); + check_field( $respcode, $response, FID_VALID_PATRON, 'N', 'Verified code BL for wrong cardnumber' ); + check_field( $respcode, $response, FID_PERSONAL_NAME, '', 'Name should be empty now' ); + check_field( $respcode, $response, FID_SCREEN_MSG, '.+', 'But we have a screen msg', 'regex' ); } sub test_request_patron_info_v2 { - my $builder = t::lib::TestBuilder->new(); - my $branchcode = $builder->build({ source => 'Branch' })->{branchcode}; + my $builder = t::lib::TestBuilder->new(); + my $branchcode = $builder->build( { source => 'Branch' } )->{branchcode}; my ( $response, $findpatron ); my $mocks = create_mocks( \$response, \$findpatron, \$branchcode ); - my $patron2 = $builder->build({ - source => 'Borrower', - value => { - password => hash_password( PATRON_PW ), - }, - }); - my $card = $patron2->{cardnumber}; - my $sip_patron2 = C4::SIP::ILS::Patron->new( $card ); + my $patron2 = $builder->build( + { + source => 'Borrower', + value => { + password => hash_password(PATRON_PW), + }, + } + ); + my $card = $patron2->{cardnumber}; + my $sip_patron2 = C4::SIP::ILS::Patron->new($card); $findpatron = $sip_patron2; - my $siprequest = PATRON_INFO. 'engYYYYMMDDZZZZHHMMSS'.'Y '. - FID_INST_ID. $branchcode. '|'. - FID_PATRON_ID. $card. '|'. - FID_PATRON_PWD. PATRON_PW. '|'; + my $siprequest = + PATRON_INFO + . 'engYYYYMMDDZZZZHHMMSS' + . 'Y ' + . FID_INST_ID + . $branchcode . '|' + . FID_PATRON_ID + . $card . '|' + . FID_PATRON_PWD + . PATRON_PW . '|'; my $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 ); my $server = { ils => $mocks->{ils} }; undef $response; - $msg->handle_patron_info( $server ); + $msg->handle_patron_info($server); isnt( $response, undef, 'At least we got a response.' ); my $respcode = substr( $response, 0, 2 ); is( $respcode, PATRON_INFO_RESP, 'Response code fine' ); - check_field( $respcode, $response, FID_INST_ID, $branchcode , 'Verified institution id' ); - check_field( $respcode, $response, FID_PATRON_ID, $card, 'Verified patron id' ); - check_field( $respcode, $response, FID_PERSONAL_NAME, $patron2->{surname}, 'Verified patron name', 'contains' ); - check_field( $respcode, $response, FID_VALID_PATRON, 'Y', 'Verified code BL' ); - check_field( $respcode, $response, FID_VALID_PATRON_PWD, 'Y', 'Verified code CQ' ); - check_field( $respcode, $response, FID_FEE_LMT, '.*', 'Checked existence of fee limit', 'regex' ); - check_field( $respcode, $response, FID_HOME_ADDR, $patron2->{address}, 'Address in BD', 'contains' ); - check_field( $respcode, $response, FID_EMAIL, $patron2->{email}, 'Verified email in BE' ); - check_field( $respcode, $response, FID_HOME_PHONE, $patron2->{phone}, 'Verified home phone in BF' ); + check_field( $respcode, $response, FID_INST_ID, $branchcode, 'Verified institution id' ); + check_field( $respcode, $response, FID_PATRON_ID, $card, 'Verified patron id' ); + check_field( $respcode, $response, FID_PERSONAL_NAME, $patron2->{surname}, 'Verified patron name', 'contains' ); + check_field( $respcode, $response, FID_VALID_PATRON, 'Y', 'Verified code BL' ); + check_field( $respcode, $response, FID_VALID_PATRON_PWD, 'Y', 'Verified code CQ' ); + check_field( $respcode, $response, FID_FEE_LMT, '.*', 'Checked existence of fee limit', 'regex' ); + check_field( $respcode, $response, FID_HOME_ADDR, $patron2->{address}, 'Address in BD', 'contains' ); + check_field( $respcode, $response, FID_EMAIL, $patron2->{email}, 'Verified email in BE' ); + check_field( $respcode, $response, FID_HOME_PHONE, $patron2->{phone}, 'Verified home phone in BF' ); + # No check for custom fields here (unofficial PB, PC and PI) check_field( $respcode, $response, FID_SCREEN_MSG, '.+', 'We have a screen msg', 'regex' ); @@ -1007,396 +1122,497 @@ sub test_request_patron_info_v2 { $server->{account}->{ae_field_template} = "X[% patron.surname %]Y"; $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 ); undef $response; - $msg->handle_patron_info( $server ); + $msg->handle_patron_info($server); $respcode = substr( $response, 0, 2 ); - check_field( $respcode, $response, FID_PERSONAL_NAME, 'X' . $patron2->{surname} . 'Y', 'Check customized patron name' ); + check_field( + $respcode, $response, FID_PERSONAL_NAME, 'X' . $patron2->{surname} . 'Y', + 'Check customized patron name' + ); # Test hide_fields undef $response; $server->{account}->{hide_fields} = join( ",", FID_HOME_ADDR, FID_EMAIL, FID_HOME_PHONE, FID_PATRON_BIRTHDATE ); - $msg->handle_patron_info( $server ); + $msg->handle_patron_info($server); $respcode = substr( $response, 0, 2 ); - check_field( $respcode, $response, FID_HOME_ADDR, undef, 'Home address successfully stripped from response' ); - check_field( $respcode, $response, FID_EMAIL, undef, 'Email address successfully stripped from response' ); + check_field( $respcode, $response, FID_HOME_ADDR, undef, 'Home address successfully stripped from response' ); + check_field( $respcode, $response, FID_EMAIL, undef, 'Email address successfully stripped from response' ); check_field( $respcode, $response, FID_HOME_PHONE, undef, 'Home phone successfully stripped from response' ); - check_field( $respcode, $response, FID_PATRON_BIRTHDATE, undef, 'Date of birth successfully stripped from response' ); + check_field( + $respcode, $response, FID_PATRON_BIRTHDATE, undef, + 'Date of birth successfully stripped from response' + ); delete $server->{account}->{hide_fields}; # Test allow_fields undef $response; $server->{account}->{allow_fields} = join( ",", FID_EMAIL, FID_HOME_PHONE ); - $msg->handle_patron_info( $server ); + $msg->handle_patron_info($server); $respcode = substr( $response, 0, 2 ); check_field( $respcode, $response, FID_HOME_ADDR, undef, 'Home address successfully stripped from response' ); - check_field( $respcode, $response, FID_EMAIL, $patron2->{email}, 'Email address successfully retained in response' ); - check_field( $respcode, $response, FID_HOME_PHONE, $patron2->{phone}, 'Home phone successfully retained in from response' ); - check_field( $respcode, $response, FID_PATRON_BIRTHDATE, undef, 'Date of birth successfully stripped from response' ); + check_field( + $respcode, $response, FID_EMAIL, $patron2->{email}, + 'Email address successfully retained in response' + ); + check_field( + $respcode, $response, FID_HOME_PHONE, $patron2->{phone}, + 'Home phone successfully retained in from response' + ); + check_field( + $respcode, $response, FID_PATRON_BIRTHDATE, undef, + 'Date of birth successfully stripped from response' + ); delete $server->{account}->{allow_fields}; # Test hide_fields should take precedence over allow_fields undef $response; - $server->{account}->{hide_fields} = join( ",", FID_HOME_ADDR, FID_EMAIL, FID_PATRON_BIRTHDATE ); - $server->{account}->{allow_fields} = join( ",", FID_EMAIL, FID_HOME_PHONE ); - $msg->handle_patron_info( $server ); + $server->{account}->{hide_fields} = join( ",", FID_HOME_ADDR, FID_EMAIL, FID_PATRON_BIRTHDATE ); + $server->{account}->{allow_fields} = join( ",", FID_EMAIL, FID_HOME_PHONE ); + $msg->handle_patron_info($server); $respcode = substr( $response, 0, 2 ); check_field( $respcode, $response, FID_HOME_ADDR, undef, 'Home address successfully stripped from response' ); - check_field( $respcode, $response, FID_EMAIL, undef, 'Email address successfully stripped from response' ); - check_field( $respcode, $response, FID_HOME_PHONE, $patron2->{phone}, 'Home phone successfully retained in from response' ); - check_field( $respcode, $response, FID_PATRON_BIRTHDATE, undef, 'Date of birth successfully stripped from response' ); + check_field( $respcode, $response, FID_EMAIL, undef, 'Email address successfully stripped from response' ); + check_field( + $respcode, $response, FID_HOME_PHONE, $patron2->{phone}, + 'Home phone successfully retained in from response' + ); + check_field( + $respcode, $response, FID_PATRON_BIRTHDATE, undef, + 'Date of birth successfully stripped from response' + ); delete $server->{account}->{hide_fields}; delete $server->{account}->{allow_fields}; # Check empty password and verify CQ again - $siprequest = PATRON_INFO. 'engYYYYMMDDZZZZHHMMSS'.'Y '. - FID_INST_ID. $branchcode. '|'. - FID_PATRON_ID. $card. '|'. - FID_PATRON_PWD. '|'; + $siprequest = + PATRON_INFO + . 'engYYYYMMDDZZZZHHMMSS' + . 'Y ' + . FID_INST_ID + . $branchcode . '|' + . FID_PATRON_ID + . $card . '|' + . FID_PATRON_PWD . '|'; $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 ); undef $response; - $msg->handle_patron_info( $server ); + $msg->handle_patron_info($server); $respcode = substr( $response, 0, 2 ); check_field( $respcode, $response, FID_VALID_PATRON_PWD, 'N', 'code CQ should be N for empty AD' ); + # Test empty password is OK if account configured to allow $server->{account}->{allow_empty_passwords} = 1; $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 ); undef $response; - $msg->handle_patron_info( $server ); + $msg->handle_patron_info($server); $respcode = substr( $response, 0, 2 ); check_field( $respcode, $response, FID_VALID_PATRON_PWD, 'Y', 'code CQ should be Y if empty AD allowed' ); t::lib::Mocks::mock_preference( 'FailedLoginAttempts', '1' ); - my $patron = Koha::Patrons->find({ cardnumber => $card }); - $patron->update({ login_attempts => 0 }); + my $patron = Koha::Patrons->find( { cardnumber => $card } ); + $patron->update( { login_attempts => 0 } ); is( $patron->account_locked, 0, "Patron account not locked already" ); - $msg->handle_patron_info( $server ); - $patron = Koha::Patrons->find({ cardnumber => $card }); + $msg->handle_patron_info($server); + $patron = Koha::Patrons->find( { cardnumber => $card } ); is( $patron->account_locked, 0, "Patron account is not locked by patron info messages with empty password" ); # Finally, we send a wrong card number - Koha::Patrons->search({ cardnumber => $card })->delete; + Koha::Patrons->search( { cardnumber => $card } )->delete; undef $findpatron; $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 ); undef $response; - $msg->handle_patron_info( $server ); + $msg->handle_patron_info($server); $respcode = substr( $response, 0, 2 ); - check_field( $respcode, $response, FID_VALID_PATRON, 'N', 'Verified code BL for wrong cardnumber' ); - check_field( $respcode, $response, FID_PERSONAL_NAME, '', 'Name should be empty now' ); - check_field( $respcode, $response, FID_SCREEN_MSG, '.+', 'But we have a screen msg', 'regex' ); + check_field( $respcode, $response, FID_VALID_PATRON, 'N', 'Verified code BL for wrong cardnumber' ); + check_field( $respcode, $response, FID_PERSONAL_NAME, '', 'Name should be empty now' ); + check_field( $respcode, $response, FID_SCREEN_MSG, '.+', 'But we have a screen msg', 'regex' ); } sub test_checkout_v2 { - my $builder = t::lib::TestBuilder->new(); - my $branchcode = $builder->build({ source => 'Branch' })->{branchcode}; - my $branchcode2 = $builder->build({ source => 'Branch' })->{branchcode}; + my $builder = t::lib::TestBuilder->new(); + my $branchcode = $builder->build( { source => 'Branch' } )->{branchcode}; + my $branchcode2 = $builder->build( { source => 'Branch' } )->{branchcode}; my ( $response, $findpatron ); my $mocks = create_mocks( \$response, \$findpatron, \$branchcode ); - - # create some data - my $patron1 = $builder->build({ - source => 'Borrower', - value => { - password => hash_password( PATRON_PW ), - }, - }); - my $card1 = $patron1->{cardnumber}; - my $sip_patron1 = C4::SIP::ILS::Patron->new( $card1 ); + my $patron1 = $builder->build( + { + source => 'Borrower', + value => { + password => hash_password(PATRON_PW), + }, + } + ); + my $card1 = $patron1->{cardnumber}; + my $sip_patron1 = C4::SIP::ILS::Patron->new($card1); $findpatron = $sip_patron1; - my $item_object = $builder->build_sample_item({ - damaged => 0, - withdrawn => 0, - itemlost => 0, - restricted => 0, - homebranch => $branchcode, - holdingbranch => $branchcode, - }); + my $item_object = $builder->build_sample_item( + { + damaged => 0, + withdrawn => 0, + itemlost => 0, + restricted => 0, + homebranch => $branchcode, + holdingbranch => $branchcode, + } + ); my $mockILS = $mocks->{ils}; - my $server = { ils => $mockILS, account => {} }; + my $server = { ils => $mockILS, account => {} }; $mockILS->mock( 'institution', sub { $branchcode; } ); - $mockILS->mock( 'supports', sub { return; } ); - $mockILS->mock( 'checkout', sub { - shift; - return C4::SIP::ILS->checkout(@_); - }); + $mockILS->mock( 'supports', sub { return; } ); + $mockILS->mock( + 'checkout', + sub { + shift; + return C4::SIP::ILS->checkout(@_); + } + ); my $today = dt_from_string; - t::lib::Mocks::mock_userenv({ branchcode => $branchcode, flags => 1 }); - t::lib::Mocks::mock_preference( 'CheckPrevCheckout', 'hardyes' ); + t::lib::Mocks::mock_userenv( { branchcode => $branchcode, flags => 1 } ); + t::lib::Mocks::mock_preference( 'CheckPrevCheckout', 'hardyes' ); - my $issue = Koha::Checkout->new({ branchcode => $branchcode, borrowernumber => $patron1->{borrowernumber}, itemnumber => $item_object->itemnumber })->store; - my $return = AddReturn($item_object->barcode, $branchcode); + my $issue = Koha::Checkout->new( + { + branchcode => $branchcode, borrowernumber => $patron1->{borrowernumber}, + itemnumber => $item_object->itemnumber + } + )->store; + my $return = AddReturn( $item_object->barcode, $branchcode ); - my $siprequest = CHECKOUT . 'YN' . siprequestdate($today) . - siprequestdate( $today->clone->add( days => 1) ) . - FID_INST_ID . $branchcode . '|'. - FID_PATRON_ID . $sip_patron1->id . '|' . - FID_ITEM_ID . $item_object->barcode . '|' . - FID_TERMINAL_PWD . 'ignored' . '|'; + my $siprequest = + CHECKOUT . 'YN' + . siprequestdate($today) + . siprequestdate( $today->clone->add( days => 1 ) ) + . FID_INST_ID + . $branchcode . '|' + . FID_PATRON_ID + . $sip_patron1->id . '|' + . FID_ITEM_ID + . $item_object->barcode . '|' + . FID_TERMINAL_PWD + . 'ignored' . '|'; undef $response; my $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 ); $server->{account}->{prevcheckout_block_checkout} = 1; - $msg->handle_checkout( $server ); + $msg->handle_checkout($server); my $respcode = substr( $response, 0, 2 ); - check_field( $respcode, $response, FID_SCREEN_MSG, 'This item was previously checked out by you', 'Check screen msg', 'equals' ); + check_field( + $respcode, $response, FID_SCREEN_MSG, 'This item was previously checked out by you', + 'Check screen msg', 'equals' + ); - is( Koha::Checkouts->search({ itemnumber => $item_object->id })->count, 0, "Item was not checked out (prevcheckout_block_checkout enabled)"); + is( + Koha::Checkouts->search( { itemnumber => $item_object->id } )->count, 0, + "Item was not checked out (prevcheckout_block_checkout enabled)" + ); $server->{account}->{prevcheckout_block_checkout} = 0; - $msg->handle_checkout( $server ); + $msg->handle_checkout($server); $respcode = substr( $response, 0, 2 ); - is( Koha::Checkouts->search({ itemnumber => $item_object->id })->count, 1, "Item was checked out (prevcheckout_block_checkout disabled)"); + is( + Koha::Checkouts->search( { itemnumber => $item_object->id } )->count, 1, + "Item was checked out (prevcheckout_block_checkout disabled)" + ); - $msg->handle_checkout( $server ); - ok( $response =~ m/AH\d{8} \d{6}/, "Found AH field as timestamp in response"); + $msg->handle_checkout($server); + ok( $response =~ m/AH\d{8} \d{6}/, "Found AH field as timestamp in response" ); $server->{account}->{format_due_date} = 1; - t::lib::Mocks::mock_preference( 'dateFormat', 'sql' ); + t::lib::Mocks::mock_preference( 'dateFormat', 'sql' ); undef $response; - $msg->handle_checkout( $server ); - ok( $response =~ m/AH\d{4}-\d{2}-\d{2}/, "Found AH field as SQL date in response"); + $msg->handle_checkout($server); + ok( $response =~ m/AH\d{4}-\d{2}-\d{2}/, "Found AH field as SQL date in response" ); #returning item and now testing for blocked_item_types - t::lib::Mocks::mock_preference( 'CheckPrevCheckout', 'hardno' ); - AddReturn($item_object->barcode, $branchcode); + t::lib::Mocks::mock_preference( 'CheckPrevCheckout', 'hardno' ); + AddReturn( $item_object->barcode, $branchcode ); $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 ); - $server->{account}->{blocked_item_types} = "CR|".$item_object->itype; - $msg->handle_checkout( $server ); + $server->{account}->{blocked_item_types} = "CR|" . $item_object->itype; + $msg->handle_checkout($server); $respcode = substr( $response, 0, 2 ); - check_field( $respcode, $response, FID_SCREEN_MSG, 'Item type cannot be checked out at this checkout location', 'Check screen msg', 'equals' ); + check_field( + $respcode, $response, FID_SCREEN_MSG, 'Item type cannot be checked out at this checkout location', + 'Check screen msg', 'equals' + ); - is( Koha::Checkouts->search({ itemnumber => $item_object->id })->count, 0, "Item was not checked out (item type matched blocked_item_types)"); + is( + Koha::Checkouts->search( { itemnumber => $item_object->id } )->count, 0, + "Item was not checked out (item type matched blocked_item_types)" + ); $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 ); $server->{account}->{blocked_item_types} = ""; - $msg->handle_checkout( $server ); + $msg->handle_checkout($server); $respcode = substr( $response, 0, 2 ); - is( Koha::Checkouts->search({ itemnumber => $item_object->id })->count, 1, "Item was checked out successfully"); + is( Koha::Checkouts->search( { itemnumber => $item_object->id } )->count, 1, "Item was checked out successfully" ); } sub test_checkin_v2 { - my $builder = t::lib::TestBuilder->new(); - my $branchcode = $builder->build({ source => 'Branch' })->{branchcode}; - my $branchcode2 = $builder->build({ source => 'Branch' })->{branchcode}; + my $builder = t::lib::TestBuilder->new(); + my $branchcode = $builder->build( { source => 'Branch' } )->{branchcode}; + my $branchcode2 = $builder->build( { source => 'Branch' } )->{branchcode}; my ( $response, $findpatron ); my $mocks = create_mocks( \$response, \$findpatron, \$branchcode ); # create some data - my $patron1 = $builder->build({ - source => 'Borrower', - value => { - password => hash_password( PATRON_PW ), - }, - }); - my $card1 = $patron1->{cardnumber}; - my $sip_patron1 = C4::SIP::ILS::Patron->new( $card1 ); + my $patron1 = $builder->build( + { + source => 'Borrower', + value => { + password => hash_password(PATRON_PW), + }, + } + ); + my $card1 = $patron1->{cardnumber}; + my $sip_patron1 = C4::SIP::ILS::Patron->new($card1); $findpatron = $sip_patron1; - my $item_object = $builder->build_sample_item({ - damaged => 0, - withdrawn => 0, - itemlost => 0, - restricted => 0, - homebranch => $branchcode, - holdingbranch => $branchcode, - }); + my $item_object = $builder->build_sample_item( + { + damaged => 0, + withdrawn => 0, + itemlost => 0, + restricted => 0, + homebranch => $branchcode, + holdingbranch => $branchcode, + } + ); my $mockILS = $mocks->{ils}; - my $server = { ils => $mockILS, account => {} }; + my $server = { ils => $mockILS, account => {} }; $mockILS->mock( 'institution', sub { $branchcode; } ); - $mockILS->mock( 'supports', sub { return; } ); - $mockILS->mock( 'checkin', sub { - shift; - return C4::SIP::ILS->checkin(@_); - }); + $mockILS->mock( 'supports', sub { return; } ); + $mockILS->mock( + 'checkin', + sub { + shift; + return C4::SIP::ILS->checkin(@_); + } + ); my $today = dt_from_string; # Checkin invalid barcode - Koha::Items->search({ barcode => 'not_to_be_found' })->delete; - my $siprequest = CHECKIN . 'N' . 'YYYYMMDDZZZZHHMMSS' . - siprequestdate( $today->clone->add( days => 1) ) . - FID_INST_ID . $branchcode . '|'. - FID_ITEM_ID . 'not_to_be_found' . '|' . - FID_TERMINAL_PWD . 'ignored' . '|'; + Koha::Items->search( { barcode => 'not_to_be_found' } )->delete; + my $siprequest = + CHECKIN . 'N' + . 'YYYYMMDDZZZZHHMMSS' + . siprequestdate( $today->clone->add( days => 1 ) ) + . FID_INST_ID + . $branchcode . '|' + . FID_ITEM_ID + . 'not_to_be_found' . '|' + . FID_TERMINAL_PWD + . 'ignored' . '|'; undef $response; my $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 ); - warnings_like { $msg->handle_checkin( $server ); } - [ qr/No item 'not_to_be_found'/, qr/no item found in object to resensitize/ ], + warnings_like { $msg->handle_checkin($server); } + [ qr/No item 'not_to_be_found'/, qr/no item found in object to resensitize/ ], 'Checkin of invalid item with two warnings'; my $respcode = substr( $response, 0, 2 ); is( $respcode, CHECKIN_RESP, 'Response code fine' ); - is( substr($response,2,1), '0', 'OK flag is false' ); - is( substr($response,5,1), 'Y', 'Alert flag is set' ); + is( substr( $response, 2, 1 ), '0', 'OK flag is false' ); + is( substr( $response, 5, 1 ), 'Y', 'Alert flag is set' ); check_field( $respcode, $response, FID_SCREEN_MSG, 'Invalid Item', 'Check screen msg', 'regex' ); check_field( $respcode, $response, FID_PERM_LOCN, '', 'Check that AQ is in the response' ); # Not checked out, toggle option checked_in_ok - $siprequest = CHECKIN . 'N' . 'YYYYMMDDZZZZHHMMSS' . - siprequestdate( $today->clone->add( days => 1) ) . - FID_INST_ID . $branchcode . '|'. - FID_ITEM_ID . $item_object->barcode . '|' . - FID_TERMINAL_PWD . 'ignored' . '|'; + $siprequest = + CHECKIN . 'N' + . 'YYYYMMDDZZZZHHMMSS' + . siprequestdate( $today->clone->add( days => 1 ) ) + . FID_INST_ID + . $branchcode . '|' + . FID_ITEM_ID + . $item_object->barcode . '|' + . FID_TERMINAL_PWD + . 'ignored' . '|'; undef $response; $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 ); - $msg->handle_checkin( $server ); + $msg->handle_checkin($server); $respcode = substr( $response, 0, 2 ); - is( substr($response,2,1), '0', 'OK flag is false when checking in an item that was not checked out' ); - is( substr($response,5,1), 'Y', 'Alert flag is set' ); + is( substr( $response, 2, 1 ), '0', 'OK flag is false when checking in an item that was not checked out' ); + is( substr( $response, 5, 1 ), 'Y', 'Alert flag is set' ); check_field( $respcode, $response, FID_SCREEN_MSG, 'not checked out', 'Check screen msg', 'regex' ); + # Toggle option $server->{account}->{checked_in_ok} = 1; undef $response; $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 ); - $msg->handle_checkin( $server ); - is( substr($response,2,1), '1', 'OK flag is true now with checked_in_ok flag set when checking in an item that was not checked out' ); - is( substr($response,5,1), 'N', 'Alert flag no longer set' ); + $msg->handle_checkin($server); + is( + substr( $response, 2, 1 ), '1', + 'OK flag is true now with checked_in_ok flag set when checking in an item that was not checked out' + ); + is( substr( $response, 5, 1 ), 'N', 'Alert flag no longer set' ); check_field( $respcode, $response, FID_SCREEN_MSG, undef, 'No screen msg' ); # Move item to another holding branch to trigger CV of 04 with alert flag t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'holdingbranch' ); - $item_object->holdingbranch( $branchcode2 )->store(); + $item_object->holdingbranch($branchcode2)->store(); undef $response; $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 ); - $msg->handle_checkin( $server ); - is( substr($response,5,1), 'Y', 'Alert flag is set with check_in_ok, item is checked in but needs transfer' ); - check_field( $respcode, $response, FID_ALERT_TYPE, '04', 'Got FID_ALERT_TYPE (CV) field with value 04 ( needs transfer )' ); - $item_object->holdingbranch( $branchcode )->store(); + $msg->handle_checkin($server); + is( substr( $response, 5, 1 ), 'Y', 'Alert flag is set with check_in_ok, item is checked in but needs transfer' ); + check_field( + $respcode, $response, FID_ALERT_TYPE, '04', + 'Got FID_ALERT_TYPE (CV) field with value 04 ( needs transfer )' + ); + $item_object->holdingbranch($branchcode)->store(); t::lib::Mocks::mock_preference( ' AllowReturnToBranch ', 'anywhere' ); $server->{account}->{cv_send_00_on_success} = 0; undef $response; $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 ); - $msg->handle_checkin( $server ); + $msg->handle_checkin($server); $respcode = substr( $response, 0, 2 ); check_field( $respcode, $response, FID_ALERT_TYPE, undef, 'No FID_ALERT_TYPE (CV) field' ); $server->{account}->{cv_send_00_on_success} = 1; undef $response; $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 ); - $msg->handle_checkin( $server ); + $msg->handle_checkin($server); $respcode = substr( $response, 0, 2 ); check_field( $respcode, $response, FID_ALERT_TYPE, '00', 'FID_ALERT_TYPE (CV) field is 00' ); - $server->{account}->{checked_in_ok} = 0; + $server->{account}->{checked_in_ok} = 0; $server->{account}->{cv_send_00_on_success} = 0; t::lib::Mocks::mock_preference( 'RecordLocalUseOnReturn', '1' ); - $server->{account}->{checked_in_ok} = 0; + $server->{account}->{checked_in_ok} = 0; $server->{account}->{cv_triggers_alert} = 0; undef $response; $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 ); - $msg->handle_checkin( $server ); + $msg->handle_checkin($server); $respcode = substr( $response, 0, 2 ); is( substr( $response, 5, 1 ), 'Y', 'Checkin without CV triggers alert flag when cv_triggers_alert is off' ); t::lib::Mocks::mock_preference( 'RecordLocalUseOnReturn', '0' ); $server->{account}->{cv_triggers_alert} = 1; undef $response; $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 ); - $msg->handle_checkin( $server ); + $msg->handle_checkin($server); $respcode = substr( $response, 0, 2 ); is( substr( $response, 5, 1 ), 'N', 'Checkin without CV does not trigger alert flag when cv_triggers_alert is on' ); $server->{account}->{cv_triggers_alert} = 0; t::lib::Mocks::mock_preference( 'RecordLocalUseOnReturn', '1' ); - $server->{account}->{checked_in_ok} = 1; + $server->{account}->{checked_in_ok} = 1; $server->{account}->{ct_always_send} = 0; undef $response; $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 ); - $msg->handle_checkin( $server ); + $msg->handle_checkin($server); $respcode = substr( $response, 0, 2 ); check_field( $respcode, $response, FID_DESTINATION_LOCATION, undef, 'No FID_DESTINATION_LOCATION (CT) field' ); $server->{account}->{ct_always_send} = 1; undef $response; $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 ); - $msg->handle_checkin( $server ); + $msg->handle_checkin($server); $respcode = substr( $response, 0, 2 ); - check_field( $respcode, $response, FID_DESTINATION_LOCATION, q{}, 'FID_DESTINATION_LOCATION (CT) field is empty but present' ); - $server->{account}->{checked_in_ok} = 0; + check_field( + $respcode, $response, FID_DESTINATION_LOCATION, q{}, + 'FID_DESTINATION_LOCATION (CT) field is empty but present' + ); + $server->{account}->{checked_in_ok} = 0; $server->{account}->{ct_always_send} = 0; # Checkin at wrong branch: issue item and switch branch, and checkin - my $issue = Koha::Checkout->new({ branchcode => $branchcode, borrowernumber => $patron1->{borrowernumber}, itemnumber => $item_object->itemnumber })->store; - $branchcode = $builder->build({ source => 'Branch' })->{branchcode}; + my $issue = Koha::Checkout->new( + { + branchcode => $branchcode, borrowernumber => $patron1->{borrowernumber}, + itemnumber => $item_object->itemnumber + } + )->store; + $branchcode = $builder->build( { source => 'Branch' } )->{branchcode}; t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'homebranch' ); undef $response; $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 ); - $msg->handle_checkin( $server ); - is( substr($response,2,1), '0', 'OK flag is false when we check in at the wrong branch and we do not allow it' ); - is( substr($response,5,1), 'Y', 'Alert flag is set' ); + $msg->handle_checkin($server); + is( + substr( $response, 2, 1 ), '0', + 'OK flag is false when we check in at the wrong branch and we do not allow it' + ); + is( substr( $response, 5, 1 ), 'Y', 'Alert flag is set' ); check_field( $respcode, $response, FID_SCREEN_MSG, 'Checkin failed', 'Check screen msg' ); - $branchcode = $item_object->homebranch; # switch back + $branchcode = $item_object->homebranch; # switch back t::lib::Mocks::mock_preference( 'AllowReturnToBranch', 'anywhere' ); # Data corrupted: add same issue_id to old_issues - Koha::Old::Checkout->new({ issue_id => $issue->issue_id })->store; + Koha::Old::Checkout->new( { issue_id => $issue->issue_id } )->store; undef $response; $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 ); - warnings_like { $msg->handle_checkin( $server ); } - [ qr/Duplicate entry/, qr/data issues/ ], + warnings_like { $msg->handle_checkin($server); } + [ qr/Duplicate entry/, qr/data issues/ ], 'DBIx error on duplicate issue_id'; - is( substr($response,2,1), '0', 'OK flag is false when we encounter data corruption in old_issues' ); - is( substr($response,5,1), 'Y', 'Alert flag is set' ); + is( substr( $response, 2, 1 ), '0', 'OK flag is false when we encounter data corruption in old_issues' ); + is( substr( $response, 5, 1 ), 'Y', 'Alert flag is set' ); check_field( $respcode, $response, FID_SCREEN_MSG, 'Checkin failed: data problem', 'Check screen msg' ); # Finally checkin without problems (remove duplicate id) - Koha::Old::Checkouts->search({ issue_id => $issue->issue_id })->delete; + Koha::Old::Checkouts->search( { issue_id => $issue->issue_id } )->delete; undef $response; $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 ); - $msg->handle_checkin( $server ); - is( substr($response,2,1), '1', 'OK flag is true when we checkin after removing the duplicate' ); - is( substr($response,5,1), 'N', 'Alert flag is not set' ); - is( Koha::Checkouts->find( $issue->issue_id ), undef, - 'Issue record is gone now' ); + $msg->handle_checkin($server); + is( substr( $response, 2, 1 ), '1', 'OK flag is true when we checkin after removing the duplicate' ); + is( substr( $response, 5, 1 ), 'N', 'Alert flag is not set' ); + is( + Koha::Checkouts->find( $issue->issue_id ), undef, + 'Issue record is gone now' + ); # Test account option no_holds_check that prevents items on hold from being checked in via SIP - $issue = Koha::Checkout->new({ branchcode => $branchcode, borrowernumber => $patron1->{borrowernumber}, itemnumber => $item_object->itemnumber })->store; - is( Koha::Checkouts->search({ itemnumber => $item_object->id })->count, 1, "Item is checked out"); - Koha::Old::Checkouts->search({ issue_id => $issue->issue_id })->delete; + $issue = Koha::Checkout->new( + { + branchcode => $branchcode, borrowernumber => $patron1->{borrowernumber}, + itemnumber => $item_object->itemnumber + } + )->store; + is( Koha::Checkouts->search( { itemnumber => $item_object->id } )->count, 1, "Item is checked out" ); + Koha::Old::Checkouts->search( { issue_id => $issue->issue_id } )->delete; $server->{account}->{holds_block_checkin} = 1; - my $reserve_id = AddReserve({ - branchcode => $branchcode, - borrowernumber => $patron1->{borrowernumber}, - biblionumber => $item_object->biblionumber, - priority => 1, - }); - my $hold = Koha::Holds->find( $reserve_id ); + my $reserve_id = AddReserve( + { + branchcode => $branchcode, + borrowernumber => $patron1->{borrowernumber}, + biblionumber => $item_object->biblionumber, + priority => 1, + } + ); + my $hold = Koha::Holds->find($reserve_id); is( $hold->id, $reserve_id, "Hold was created successfully" ); undef $response; $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 ); - $msg->handle_checkin( $server ); - is( substr($response,2,1), '0', 'OK flag is false when we check in an item on hold and we do not allow it' ); - is( substr($response,5,1), 'Y', 'Alert flag is set' ); - is( Koha::Checkouts->search({ itemnumber => $item_object->id })->count, 1, "Item was not checked in"); + $msg->handle_checkin($server); + is( substr( $response, 2, 1 ), '0', 'OK flag is false when we check in an item on hold and we do not allow it' ); + is( substr( $response, 5, 1 ), 'Y', 'Alert flag is set' ); + is( Koha::Checkouts->search( { itemnumber => $item_object->id } )->count, 1, "Item was not checked in" ); $hold->discard_changes; - is( $hold->found, undef, "Hold was not marked as found by SIP when holds_block_checkin enabled"); + is( $hold->found, undef, "Hold was not marked as found by SIP when holds_block_checkin enabled" ); $server->{account}->{holds_block_checkin} = 0; # Test account option holds_get_captured that automatically sets the hold as found for a hold and possibly sets it to in transit $server->{account}->{holds_get_captured} = 0; undef $response; $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 ); - $msg->handle_checkin( $server ); - is( substr($response,2,1), '1', 'OK flag is true when we check in an item on hold and we allow it but do not capture it' ); - is( substr($response,5,1), 'Y', 'Alert flag is set' ); - is( Koha::Checkouts->search({ itemnumber => $item_object->id })->count, 0, "Item was checked in"); + $msg->handle_checkin($server); + is( + substr( $response, 2, 1 ), '1', + 'OK flag is true when we check in an item on hold and we allow it but do not capture it' + ); + is( substr( $response, 5, 1 ), 'Y', 'Alert flag is set' ); + is( Koha::Checkouts->search( { itemnumber => $item_object->id } )->count, 0, "Item was checked in" ); $hold->discard_changes; - is( $hold->found, undef, "Hold was not marked as found by SIP when holds_get_captured disabled"); + is( $hold->found, undef, "Hold was not marked as found by SIP when holds_get_captured disabled" ); $hold->delete(); $server->{account}->{holds_get_captured} = 1; } sub test_hold_patron_bcode { - my $builder = t::lib::TestBuilder->new(); - my $branchcode = $builder->build({ source => 'Branch' })->{branchcode}; + my $builder = t::lib::TestBuilder->new(); + my $branchcode = $builder->build( { source => 'Branch' } )->{branchcode}; my ( $response, $findpatron ); my $mocks = create_mocks( \$response, \$findpatron, \$branchcode ); - my $item = $builder->build_sample_item( - { - library => $branchcode - } - ); + my $item = $builder->build_sample_item( { library => $branchcode } ); - my $server = { ils => $mocks->{ils} }; + my $server = { ils => $mocks->{ils} }; my $sip_item = C4::SIP::ILS::Item->new( $item->barcode ); is( $sip_item->hold_patron_bcode, q{}, "SIP item with no hold returns empty string" ); @@ -1406,67 +1622,80 @@ sub test_hold_patron_bcode { } sub test_checkout_desensitize { - my $builder = t::lib::TestBuilder->new(); - my $branchcode = $builder->build({ source => 'Branch' })->{branchcode}; + my $builder = t::lib::TestBuilder->new(); + my $branchcode = $builder->build( { source => 'Branch' } )->{branchcode}; my ( $response, $findpatron ); my $mocks = create_mocks( \$response, \$findpatron, \$branchcode ); # create some data - my $patron1 = $builder->build({ - source => 'Borrower', - value => { - password => hash_password( PATRON_PW ), - }, - }); - my $card1 = $patron1->{cardnumber}; - my $sip_patron1 = C4::SIP::ILS::Patron->new( $card1 ); + my $patron1 = $builder->build( + { + source => 'Borrower', + value => { + password => hash_password(PATRON_PW), + }, + } + ); + my $card1 = $patron1->{cardnumber}; + my $sip_patron1 = C4::SIP::ILS::Patron->new($card1); my $patron_category = $sip_patron1->ptype(); $findpatron = $sip_patron1; - my $item_object = $builder->build_sample_item({ - damaged => 0, - withdrawn => 0, - itemlost => 0, - restricted => 0, - homebranch => $branchcode, - holdingbranch => $branchcode, - }); + my $item_object = $builder->build_sample_item( + { + damaged => 0, + withdrawn => 0, + itemlost => 0, + restricted => 0, + homebranch => $branchcode, + holdingbranch => $branchcode, + } + ); my $itemtype = $item_object->effective_itemtype; my $mockILS = $mocks->{ils}; - my $server = { ils => $mockILS, account => {} }; + my $server = { ils => $mockILS, account => {} }; $mockILS->mock( 'institution', sub { $branchcode; } ); - $mockILS->mock( 'supports', sub { return; } ); - $mockILS->mock( 'checkout', sub { - shift; - return C4::SIP::ILS->checkout(@_); - }); + $mockILS->mock( 'supports', sub { return; } ); + $mockILS->mock( + 'checkout', + sub { + shift; + return C4::SIP::ILS->checkout(@_); + } + ); my $today = dt_from_string; - t::lib::Mocks::mock_userenv({ branchcode => $branchcode, flags => 1 }); - t::lib::Mocks::mock_preference( 'CheckPrevCheckout', 'hardyes' ); + t::lib::Mocks::mock_userenv( { branchcode => $branchcode, flags => 1 } ); + t::lib::Mocks::mock_preference( 'CheckPrevCheckout', 'hardyes' ); - my $siprequest = CHECKOUT . 'YN' . siprequestdate($today) . - siprequestdate( $today->clone->add( days => 1) ) . - FID_INST_ID . $branchcode . '|'. - FID_PATRON_ID . $sip_patron1->id . '|' . - FID_ITEM_ID . $item_object->barcode . '|' . - FID_TERMINAL_PWD . 'ignored' . '|'; + my $siprequest = + CHECKOUT . 'YN' + . siprequestdate($today) + . siprequestdate( $today->clone->add( days => 1 ) ) + . FID_INST_ID + . $branchcode . '|' + . FID_PATRON_ID + . $sip_patron1->id . '|' + . FID_ITEM_ID + . $item_object->barcode . '|' + . FID_TERMINAL_PWD + . 'ignored' . '|'; undef $response; my $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 ); $server->{account}->{inhouse_patron_categories} = "A,$patron_category,Z"; - $msg->handle_checkout( $server ); + $msg->handle_checkout($server); my $respcode = substr( $response, 5, 1 ); is( $respcode, 'N', "Desensitize flag was not set for patron category in inhouse_patron_categories" ); undef $response; $server->{account}->{inhouse_patron_categories} = "A,B,C"; - $msg->handle_checkout( $server ); + $msg->handle_checkout($server); $respcode = substr( $response, 5, 1 ); is( $respcode, 'Y', "Desensitize flag was set for patron category not in inhouse_patron_categories" ); undef $response; $server->{account}->{inhouse_patron_categories} = ""; - $msg->handle_checkout( $server ); + $msg->handle_checkout($server); $respcode = substr( $response, 5, 1 ); is( $respcode, 'Y', "Desensitize flag was set for empty inhouse_patron_categories" ); @@ -1474,19 +1703,19 @@ sub test_checkout_desensitize { undef $response; $server->{account}->{inhouse_item_types} = "A,$itemtype,Z"; - $msg->handle_checkout( $server ); + $msg->handle_checkout($server); $respcode = substr( $response, 5, 1 ); is( $respcode, 'N', "Desensitize flag was not set for itemtype in inhouse_item_types" ); undef $response; $server->{account}->{inhouse_item_types} = "A,B,C"; - $msg->handle_checkout( $server ); + $msg->handle_checkout($server); $respcode = substr( $response, 5, 1 ); is( $respcode, 'Y', "Desensitize flag was set for item type not in inhouse_item_types" ); undef $response; $server->{account}->{inhouse_item_types} = ""; - $msg->handle_checkout( $server ); + $msg->handle_checkout($server); $respcode = substr( $response, 5, 1 ); is( $respcode, 'Y', "Desensitize flag was set for empty inhouse_item_types" ); } @@ -1587,68 +1816,86 @@ sub test_renew_all { } sub test_renew_desensitize { - my $builder = t::lib::TestBuilder->new(); - my $branchcode = $builder->build({ source => 'Branch' })->{branchcode}; + my $builder = t::lib::TestBuilder->new(); + my $branchcode = $builder->build( { source => 'Branch' } )->{branchcode}; my ( $response, $findpatron ); my $mocks = create_mocks( \$response, \$findpatron, \$branchcode ); # create some data - my $patron1 = $builder->build({ - source => 'Borrower', - value => { - password => hash_password( PATRON_PW ), - }, - }); - my $card1 = $patron1->{cardnumber}; - my $sip_patron1 = C4::SIP::ILS::Patron->new( $card1 ); + my $patron1 = $builder->build( + { + source => 'Borrower', + value => { + password => hash_password(PATRON_PW), + }, + } + ); + my $card1 = $patron1->{cardnumber}; + my $sip_patron1 = C4::SIP::ILS::Patron->new($card1); my $patron_category = $sip_patron1->ptype(); $findpatron = $sip_patron1; - my $item_object = $builder->build_sample_item({ - damaged => 0, - withdrawn => 0, - itemlost => 0, - restricted => 0, - homebranch => $branchcode, - holdingbranch => $branchcode, - }); + my $item_object = $builder->build_sample_item( + { + damaged => 0, + withdrawn => 0, + itemlost => 0, + restricted => 0, + homebranch => $branchcode, + holdingbranch => $branchcode, + } + ); my $itemtype = $item_object->effective_itemtype; my $mockILS = $mocks->{ils}; - my $server = { ils => $mockILS, account => {} }; + my $server = { ils => $mockILS, account => {} }; $mockILS->mock( 'institution', sub { $branchcode; } ); - $mockILS->mock( 'supports', sub { return; } ); - $mockILS->mock( 'checkout', sub { - shift; - return C4::SIP::ILS->checkout(@_); - }); + $mockILS->mock( 'supports', sub { return; } ); + $mockILS->mock( + 'checkout', + sub { + shift; + return C4::SIP::ILS->checkout(@_); + } + ); my $today = dt_from_string; - t::lib::Mocks::mock_userenv({ branchcode => $branchcode, flags => 1 }); + t::lib::Mocks::mock_userenv( { branchcode => $branchcode, flags => 1 } ); - my $issue = Koha::Checkout->new({ branchcode => $branchcode, borrowernumber => $patron1->{borrowernumber}, itemnumber => $item_object->itemnumber })->store; + my $issue = Koha::Checkout->new( + { + branchcode => $branchcode, borrowernumber => $patron1->{borrowernumber}, + itemnumber => $item_object->itemnumber + } + )->store; - my $siprequest = RENEW . 'YN' . siprequestdate($today) . - siprequestdate( $today->clone->add( days => 1) ) . - FID_INST_ID . $branchcode . '|'. - FID_PATRON_ID . $sip_patron1->id . '|' . - FID_ITEM_ID . $item_object->barcode . '|' . - FID_TERMINAL_PWD . 'ignored' . '|'; + my $siprequest = + RENEW . 'YN' + . siprequestdate($today) + . siprequestdate( $today->clone->add( days => 1 ) ) + . FID_INST_ID + . $branchcode . '|' + . FID_PATRON_ID + . $sip_patron1->id . '|' + . FID_ITEM_ID + . $item_object->barcode . '|' + . FID_TERMINAL_PWD + . 'ignored' . '|'; undef $response; my $msg = C4::SIP::Sip::MsgType->new( $siprequest, 0 ); $server->{account}->{inhouse_patron_categories} = "A,$patron_category,Z"; - $msg->handle_checkout( $server ); + $msg->handle_checkout($server); my $respcode = substr( $response, 5, 1 ); is( $respcode, 'N', "Desensitize flag was not set for patron category in inhouse_patron_categories" ); undef $response; $server->{account}->{inhouse_patron_categories} = "A,B,C"; - $msg->handle_checkout( $server ); + $msg->handle_checkout($server); $respcode = substr( $response, 5, 1 ); is( $respcode, 'Y', "Desensitize flag was set for patron category not in inhouse_patron_categories" ); undef $response; $server->{account}->{inhouse_patron_categories} = ""; - $msg->handle_checkout( $server ); + $msg->handle_checkout($server); $respcode = substr( $response, 5, 1 ); is( $respcode, 'Y', "Desensitize flag was set for empty inhouse_patron_categories" ); @@ -1656,19 +1903,19 @@ sub test_renew_desensitize { undef $response; $server->{account}->{inhouse_item_types} = "A,B,C"; - $msg->handle_checkout( $server ); + $msg->handle_checkout($server); $respcode = substr( $response, 5, 1 ); is( $respcode, 'Y', "Desensitize flag was set for item type not in inhouse_item_types" ); undef $response; $server->{account}->{inhouse_item_types} = ""; - $msg->handle_checkout( $server ); + $msg->handle_checkout($server); $respcode = substr( $response, 5, 1 ); is( $respcode, 'Y', "Desensitize flag was set for empty inhouse_item_types" ); undef $response; $server->{account}->{inhouse_item_types} = "A,$itemtype,Z"; - $msg->handle_checkout( $server ); + $msg->handle_checkout($server); $respcode = substr( $response, 5, 1 ); is( $respcode, 'N', "Desensitize flag was not set for itemtype in inhouse_item_types" ); @@ -1699,17 +1946,17 @@ subtest 'Test convert_nonprinting_characters' => sub { # Helper routines sub create_mocks { - my ( $response, $findpatron, $branchcode ) = @_; # referenced variables ! + my ( $response, $findpatron, $branchcode ) = @_; # referenced variables ! # mock write_msg (imported from Sip.pm into Message.pm) - my $mockMsg = Test::MockModule->new( 'C4::SIP::Sip::MsgType' ); - $mockMsg->mock( 'write_msg', sub { $$response = $_[1]; } ); # save response + my $mockMsg = Test::MockModule->new('C4::SIP::Sip::MsgType'); + $mockMsg->mock( 'write_msg', sub { $$response = $_[1]; } ); # save response # mock ils object my $mockILS = Test::MockObject->new; - $mockILS->mock( 'check_inst_id', sub {} ); + $mockILS->mock( 'check_inst_id', sub { } ); $mockILS->mock( 'institution_id', sub { $$branchcode; } ); - $mockILS->mock( 'find_patron', sub { $$findpatron; } ); + $mockILS->mock( 'find_patron', sub { $$findpatron; } ); Koha::CirculationRules->set_rule( { @@ -1726,40 +1973,41 @@ sub create_mocks { sub check_field { my ( $code, $resp, $fld, $expr, $msg, $mode ) = @_; + # mode: contains || equals || regex (by default: equals) # strip fixed part; prefix to simplify next regex - $resp = '|'. substr( $resp, fixed_length( $code ) ); + $resp = '|' . substr( $resp, fixed_length($code) ); my $fldval; - if( $resp =~ /\|$fld([^\|]*)\|/ ) { + if ( $resp =~ /\|$fld([^\|]*)\|/ ) { $fldval = $1; - } elsif( !defined($expr) ) { # field should not be found + } elsif ( !defined($expr) ) { # field should not be found ok( 1, $msg ); return; - } else { # test fails + } else { # test fails is( 0, 1, "Code $fld not found in '$resp'?" ); return; } - if( !$mode || $mode eq 'equals' ) { # default + if ( !$mode || $mode eq 'equals' ) { # default is( $fldval, $expr, $msg ); - } elsif( $mode eq 'regex' ) { + } elsif ( $mode eq 'regex' ) { is( $fldval =~ /$expr/, 1, $msg ); - } else { # contains + } else { # contains is( index( $fldval, $expr ) > -1, 1, $msg ); } } sub siprequestdate { - my ( $dt ) = @_; - return $dt->ymd('').(' 'x4).$dt->hms(''); + my ($dt) = @_; + return $dt->ymd('') . ( ' ' x 4 ) . $dt->hms(''); } -sub fixed_length { #length of fixed fields including response code +sub fixed_length { #length of fixed fields including response code return { - ( PATRON_STATUS_RESP ) => 37, - ( PATRON_INFO_RESP ) => 61, - ( CHECKIN_RESP ) => 24, - ( CHECKOUT_RESP ) => 24, - }->{$_[0]}; + (PATRON_STATUS_RESP) => 37, + (PATRON_INFO_RESP) => 61, + (CHECKIN_RESP) => 24, + (CHECKOUT_RESP) => 24, + }->{ $_[0] }; } diff --git a/t/db_dependent/SIP/Patron.t b/t/db_dependent/SIP/Patron.t index 2c95245ed2..1267c834c7 100755 --- a/t/db_dependent/SIP/Patron.t +++ b/t/db_dependent/SIP/Patron.t @@ -20,29 +20,25 @@ my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; my $builder = t::lib::TestBuilder->new(); -my $patron1 = $builder->build({ source => 'Borrower' }); -my $card = $patron1->{cardnumber}; +my $patron1 = $builder->build( { source => 'Borrower' } ); +my $card = $patron1->{cardnumber}; # Check existing card number -my $sip_patron = C4::SIP::ILS::Patron->new( $card ); +my $sip_patron = C4::SIP::ILS::Patron->new($card); is( defined $sip_patron, 1, "Patron is valid" ); # Check invalid cardnumber by deleting patron -$schema->resultset('Borrower')->search({ cardnumber => $card })->delete; -my $sip_patron2 = C4::SIP::ILS::Patron->new( $card ); +$schema->resultset('Borrower')->search( { cardnumber => $card } )->delete; +my $sip_patron2 = C4::SIP::ILS::Patron->new($card); is( $sip_patron2, undef, "Patron is not valid (anymore)" ); subtest "new tests" => sub { plan tests => 5; - my $patron = $builder->build( - { - source => 'Borrower' - } - ); + my $patron = $builder->build( { source => 'Borrower' } ); - my $cardnumber = $patron->{cardnumber}; + my $cardnumber = $patron->{cardnumber}; my $userid = $patron->{userid}; my $borrowernumber = $patron->{borrowernumber}; @@ -66,7 +62,7 @@ subtest "OverduesBlockCirc tests" => sub { { source => 'Borrower', value => { - dateexpiry => "3000-01-01", + dateexpiry => "3000-01-01", } } ); @@ -74,32 +70,36 @@ subtest "OverduesBlockCirc tests" => sub { { source => 'Borrower', value => { - dateexpiry => "3000-01-01", + dateexpiry => "3000-01-01", } } ); - my $odue = $builder->build({ source => 'Issue', value => { - borrowernumber => $odue_patron->{borrowernumber}, - date_due => '2017-01-01', + my $odue = $builder->build( + { + source => 'Issue', + value => { + borrowernumber => $odue_patron->{borrowernumber}, + date_due => '2017-01-01', } - }); + } + ); t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'noblock' ); my $odue_sip_patron = C4::SIP::ILS::Patron->new( $odue_patron->{cardnumber} ); - is( $odue_sip_patron->{charge_ok}, 1, "Not blocked with overdues when set to 'Don't block'"); + is( $odue_sip_patron->{charge_ok}, 1, "Not blocked with overdues when set to 'Don't block'" ); $odue_sip_patron = C4::SIP::ILS::Patron->new( $good_patron->{cardnumber} ); - is( $odue_sip_patron->{charge_ok}, 1, "Not blocked without overdues when set to 'Don't block'"); + is( $odue_sip_patron->{charge_ok}, 1, "Not blocked without overdues when set to 'Don't block'" ); t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'confirmation' ); $odue_sip_patron = C4::SIP::ILS::Patron->new( $odue_patron->{cardnumber} ); - is( $odue_sip_patron->{charge_ok}, '', "Blocked with overdues when set to 'Ask for confirmation'"); + is( $odue_sip_patron->{charge_ok}, '', "Blocked with overdues when set to 'Ask for confirmation'" ); $odue_sip_patron = C4::SIP::ILS::Patron->new( $good_patron->{cardnumber} ); - is( $odue_sip_patron->{charge_ok}, 1, "Not blocked without overdues when set to 'confirmation'"); + is( $odue_sip_patron->{charge_ok}, 1, "Not blocked without overdues when set to 'confirmation'" ); t::lib::Mocks::mock_preference( 'OverduesBlockCirc', 'block' ); $odue_sip_patron = C4::SIP::ILS::Patron->new( $odue_patron->{cardnumber} ); - is( $odue_sip_patron->{charge_ok}, '', "Blocked with overdues when set to 'Block'"); + is( $odue_sip_patron->{charge_ok}, '', "Blocked with overdues when set to 'Block'" ); $odue_sip_patron = C4::SIP::ILS::Patron->new( $good_patron->{cardnumber} ); - is( $odue_sip_patron->{charge_ok}, 1, "Not blocked without overdues when set to 'Block'"); + is( $odue_sip_patron->{charge_ok}, 1, "Not blocked without overdues when set to 'Block'" ); }; @@ -110,7 +110,7 @@ subtest "Test build_patron_attribute_string" => sub { my $patron = $builder->build( { source => 'Borrower' } ); my $attribute_type = $builder->build( { source => 'BorrowerAttributeType' } ); - my $attribute = Koha::Patron::Attribute->new( + my $attribute = Koha::Patron::Attribute->new( { borrowernumber => $patron->{borrowernumber}, code => $attribute_type->{code}, @@ -119,7 +119,7 @@ subtest "Test build_patron_attribute_string" => sub { )->store(); my $attribute_type2 = $builder->build( { source => 'BorrowerAttributeType' } ); - my $attribute2 = Koha::Patron::Attribute->new( + my $attribute2 = Koha::Patron::Attribute->new( { borrowernumber => $patron->{borrowernumber}, code => $attribute_type2->{code}, @@ -130,61 +130,73 @@ subtest "Test build_patron_attribute_string" => sub { my $ils_patron = C4::SIP::ILS::Patron->new( $patron->{cardnumber} ); my $server = {}; - $server->{account}->{patron_attribute}->{code} = $attribute->code; + $server->{account}->{patron_attribute}->{code} = $attribute->code; $server->{account}->{patron_attribute}->{field} = 'XY'; - my $attribute_string = $ils_patron->build_patron_attributes_string( $server ); + my $attribute_string = $ils_patron->build_patron_attributes_string($server); is( $attribute_string, "XYTest Attribute|", 'Attribute field generated correctly with single param' ); - $server = {}; - $server->{account}->{patron_attribute}->[0]->{code} = $attribute->code; + $server = {}; + $server->{account}->{patron_attribute}->[0]->{code} = $attribute->code; $server->{account}->{patron_attribute}->[0]->{field} = 'XY'; - $server->{account}->{patron_attribute}->[1]->{code} = $attribute2->code; + $server->{account}->{patron_attribute}->[1]->{code} = $attribute2->code; $server->{account}->{patron_attribute}->[1]->{field} = 'YZ'; - $attribute_string = $ils_patron->build_patron_attributes_string( $server ); - is( $attribute_string, "XYTest Attribute|YZAnother Test Attribute|", 'Attribute field generated correctly with multiple params' ); + $attribute_string = $ils_patron->build_patron_attributes_string($server); + is( + $attribute_string, "XYTest Attribute|YZAnother Test Attribute|", + 'Attribute field generated correctly with multiple params' + ); }; subtest "Test build_custom_field_string" => sub { plan tests => 5; - my $patron = $builder->build_object( { class => 'Koha::Patrons',value=>{surname => "Duck", firstname => "Darkwing"} } ); - + my $patron = + $builder->build_object( { class => 'Koha::Patrons', value => { surname => "Duck", firstname => "Darkwing" } } ); my $ils_patron = C4::SIP::ILS::Patron->new( $patron->cardnumber ); my $server = {}; $server->{account}->{custom_patron_field}->{field} = "DW"; - my $attribute_string = $ils_patron->build_custom_field_string( $server ); + my $attribute_string = $ils_patron->build_custom_field_string($server); is( $attribute_string, "", 'Custom field not generated if no value passed' ); - $server = {}; + $server = {}; $server->{account}->{custom_patron_field}->{template} = "[% patron.surname %]"; - $attribute_string = $ils_patron->build_custom_field_string( $server ); + $attribute_string = $ils_patron->build_custom_field_string($server); is( $attribute_string, "", 'Custom field not generated if no field passed' ); - $server = {}; $server->{account}->{custom_patron_field}->{field} = "DW"; - $server->{account}->{custom_patron_field}->{template} = "[% patron.firstname %] [% patron.surname %], let's get dangerous!"; - $attribute_string = $ils_patron->build_custom_field_string( $server ); + $server->{account}->{custom_patron_field}->{template} = + "[% patron.firstname %] [% patron.surname %], let's get dangerous!"; + $attribute_string = $ils_patron->build_custom_field_string($server); is( $attribute_string, "DWDarkwing Duck, let's get dangerous!|", 'Custom field processed correctly' ); $server = {}; $server->{account}->{custom_patron_field}->[0]->{field} = "DW"; - $server->{account}->{custom_patron_field}->[0]->{template} = "[% patron.firstname %] [% patron.surname %], let's get dangerous!"; - $server->{account}->{custom_patron_field}->[1]->{field} = "LM"; + $server->{account}->{custom_patron_field}->[0]->{template} = + "[% patron.firstname %] [% patron.surname %], let's get dangerous!"; + $server->{account}->{custom_patron_field}->[1]->{field} = "LM"; $server->{account}->{custom_patron_field}->[1]->{template} = "Launchpad McQuack crashed on [% patron.dateexpiry %]"; - $attribute_string = $ils_patron->build_custom_field_string( $server ); - is( $attribute_string, "DWDarkwing Duck, let's get dangerous!|LMLaunchpad McQuack crashed on ".$patron->dateexpiry."|", 'Custom fields processed correctly when multiple exist' ); + $attribute_string = $ils_patron->build_custom_field_string($server); + is( + $attribute_string, + "DWDarkwing Duck, let's get dangerous!|LMLaunchpad McQuack crashed on " . $patron->dateexpiry . "|", + 'Custom fields processed correctly when multiple exist' + ); $server = {}; $server->{account}->{custom_patron_field}->[0]->{field} = "DW"; - $server->{account}->{custom_patron_field}->[0]->{template} = "[% IF (patron.firstname) %] patron.surname, let's get dangerous!"; - $server->{account}->{custom_patron_field}->[1]->{field} = "LM"; + $server->{account}->{custom_patron_field}->[0]->{template} = + "[% IF (patron.firstname) %] patron.surname, let's get dangerous!"; + $server->{account}->{custom_patron_field}->[1]->{field} = "LM"; $server->{account}->{custom_patron_field}->[1]->{template} = "Launchpad McQuack crashed on [% patron.dateexpiry %]"; - $attribute_string = $ils_patron->build_custom_field_string( $server ); - is( $attribute_string, "LMLaunchpad McQuack crashed on ".$patron->dateexpiry."|", 'Custom fields processed correctly, bad template generate no text' ); + $attribute_string = $ils_patron->build_custom_field_string($server); + is( + $attribute_string, "LMLaunchpad McQuack crashed on " . $patron->dateexpiry . "|", + 'Custom fields processed correctly, bad template generate no text' + ); }; @@ -202,7 +214,7 @@ subtest "fine_items tests" => sub { { source => 'Accountline', value => { - borrowernumber => $patron->{borrowernumber}, + borrowernumber => $patron->{borrowernumber}, amountoutstanding => 1, } } @@ -212,7 +224,7 @@ subtest "fine_items tests" => sub { { source => 'Accountline', value => { - borrowernumber => $patron->{borrowernumber}, + borrowernumber => $patron->{borrowernumber}, amountoutstanding => 1, } } @@ -224,29 +236,29 @@ subtest "fine_items tests" => sub { is( @$all_fine_items, 2, "Got all fine items" ); # Should return only the first fine item - my $fine_items = $sip_patron->fine_items(1,1); - is( @$fine_items, 1, "Got one fine item" ); - is( $fine_items->[0]->{barcode}, $all_fine_items->[0]->{barcode}, "Got correct fine item"); + my $fine_items = $sip_patron->fine_items( 1, 1 ); + is( @$fine_items, 1, "Got one fine item" ); + is( $fine_items->[0]->{barcode}, $all_fine_items->[0]->{barcode}, "Got correct fine item" ); # Should return only the second fine item - $fine_items = $sip_patron->fine_items(2,2); - is( @$fine_items, 1, "Got one fine item" ); - is( $fine_items->[0]->{barcode}, $all_fine_items->[1]->{barcode}, "Got correct fine item"); + $fine_items = $sip_patron->fine_items( 2, 2 ); + is( @$fine_items, 1, "Got one fine item" ); + is( $fine_items->[0]->{barcode}, $all_fine_items->[1]->{barcode}, "Got correct fine item" ); # Should return all fine items - $fine_items = $sip_patron->fine_items(1,2); - is( @$fine_items, 2, "Got two fine items" ); - is( $fine_items->[0]->{barcode}, $all_fine_items->[0]->{barcode}, "Got correct first fine item"); - is( $fine_items->[1]->{barcode}, $all_fine_items->[1]->{barcode}, "Got correct second fine item"); + $fine_items = $sip_patron->fine_items( 1, 2 ); + is( @$fine_items, 2, "Got two fine items" ); + is( $fine_items->[0]->{barcode}, $all_fine_items->[0]->{barcode}, "Got correct first fine item" ); + is( $fine_items->[1]->{barcode}, $all_fine_items->[1]->{barcode}, "Got correct second fine item" ); # Check an invalid end boundary - $fine_items = $sip_patron->fine_items(1,99); - is( @$fine_items, 2, "Got two fine items" ); - is( $fine_items->[0]->{barcode}, $all_fine_items->[0]->{barcode}, "Got correct first fine item"); - is( $fine_items->[1]->{barcode}, $all_fine_items->[1]->{barcode}, "Got correct second fine item"); + $fine_items = $sip_patron->fine_items( 1, 99 ); + is( @$fine_items, 2, "Got two fine items" ); + is( $fine_items->[0]->{barcode}, $all_fine_items->[0]->{barcode}, "Got correct first fine item" ); + is( $fine_items->[1]->{barcode}, $all_fine_items->[1]->{barcode}, "Got correct second fine item" ); # Check an invalid start boundary - $fine_items = $sip_patron->fine_items(98,99); + $fine_items = $sip_patron->fine_items( 98, 99 ); is( @$fine_items, 0, "Got zero fine items" ); }; @@ -334,20 +346,20 @@ subtest "NoIssuesChargeGuarantees tests" => sub { } } ); - my $child = $builder->build_object({ class => 'Koha::Patrons' }); - my $sibling = $builder->build_object({ class => 'Koha::Patrons' }); - $child->add_guarantor({ guarantor_id => $patron->borrowernumber, relationship => 'parent' }); - $sibling->add_guarantor({ guarantor_id => $patron->borrowernumber, relationship => 'parent' }); + my $child = $builder->build_object( { class => 'Koha::Patrons' } ); + my $sibling = $builder->build_object( { class => 'Koha::Patrons' } ); + $child->add_guarantor( { guarantor_id => $patron->borrowernumber, relationship => 'parent' } ); + $sibling->add_guarantor( { guarantor_id => $patron->borrowernumber, relationship => 'parent' } ); - t::lib::Mocks::mock_preference('noissuescharge', 50); - t::lib::Mocks::mock_preference('NoIssuesChargeGuarantees', 11.01); - t::lib::Mocks::mock_preference('NoIssuesChargeGuarantorsWithGuarantees', undef); + t::lib::Mocks::mock_preference( 'noissuescharge', 50 ); + t::lib::Mocks::mock_preference( 'NoIssuesChargeGuarantees', 11.01 ); + t::lib::Mocks::mock_preference( 'NoIssuesChargeGuarantorsWithGuarantees', undef ); my $fee1 = $builder->build_object( { class => 'Koha::Account::Lines', - value => { - borrowernumber => $patron->borrowernumber, + value => { + borrowernumber => $patron->borrowernumber, amountoutstanding => 11, debit_type_code => 'OVERDUE', } @@ -357,8 +369,8 @@ subtest "NoIssuesChargeGuarantees tests" => sub { my $fee2 = $builder->build_object( { class => 'Koha::Account::Lines', - value => { - borrowernumber => $child->borrowernumber, + value => { + borrowernumber => $child->borrowernumber, amountoutstanding => 0.11, debit_type_code => 'OVERDUE', } @@ -368,8 +380,8 @@ subtest "NoIssuesChargeGuarantees tests" => sub { my $fee3 = $builder->build_object( { class => 'Koha::Account::Lines', - value => { - borrowernumber => $sibling->borrowernumber, + value => { + borrowernumber => $sibling->borrowernumber, amountoutstanding => 11.11, debit_type_code => 'OVERDUE', } @@ -378,15 +390,21 @@ subtest "NoIssuesChargeGuarantees tests" => sub { my $sip_patron = C4::SIP::ILS::Patron->new( $patron->cardnumber ); - is( $sip_patron->fines_amount, 11, "Only patron's fines are reported in total"); - ok( !$sip_patron->charge_ok, "Guarantor blocked"); - like( $sip_patron->screen_msg, qr/Patron blocked by fines \(22\.22\) on guaranteed accounts/,"Screen message includes related fines total"); + is( $sip_patron->fines_amount, 11, "Only patron's fines are reported in total" ); + ok( !$sip_patron->charge_ok, "Guarantor blocked" ); + like( + $sip_patron->screen_msg, qr/Patron blocked by fines \(22\.22\) on guaranteed accounts/, + "Screen message includes related fines total" + ); $sip_patron = C4::SIP::ILS::Patron->new( $child->cardnumber ); - is( $sip_patron->fines_amount, 0.11,"Guarantee only fines correctly counted"); - ok( $sip_patron->charge_ok, "Guarantee not blocked by guarantor fines"); - unlike( $sip_patron->screen_msg, qr/Patron blocked by fines .* on guaranteed accounts/,"Screen message does not include blocked message"); + is( $sip_patron->fines_amount, 0.11, "Guarantee only fines correctly counted" ); + ok( $sip_patron->charge_ok, "Guarantee not blocked by guarantor fines" ); + unlike( + $sip_patron->screen_msg, qr/Patron blocked by fines .* on guaranteed accounts/, + "Screen message does not include blocked message" + ); $schema->storage->txn_rollback; }; @@ -425,16 +443,16 @@ subtest "NoIssuesChargeGuarantorsWithGuarantees tests" => sub { } } ); - $child->add_guarantor({ guarantor_id => $patron->borrowernumber, relationship => 'parent' }); + $child->add_guarantor( { guarantor_id => $patron->borrowernumber, relationship => 'parent' } ); - t::lib::Mocks::mock_preference('noissuescharge', 50); - t::lib::Mocks::mock_preference('NoIssuesChargeGuarantorsWithGuarantees', 11.01); + t::lib::Mocks::mock_preference( 'noissuescharge', 50 ); + t::lib::Mocks::mock_preference( 'NoIssuesChargeGuarantorsWithGuarantees', 11.01 ); my $fee1 = $builder->build_object( { class => 'Koha::Account::Lines', - value => { - borrowernumber => $patron->borrowernumber, + value => { + borrowernumber => $patron->borrowernumber, amountoutstanding => 11, debit_type_code => 'OVERDUE', } @@ -444,8 +462,8 @@ subtest "NoIssuesChargeGuarantorsWithGuarantees tests" => sub { my $fee2 = $builder->build_object( { class => 'Koha::Account::Lines', - value => { - borrowernumber => $child->borrowernumber, + value => { + borrowernumber => $child->borrowernumber, amountoutstanding => 0.11, debit_type_code => 'OVERDUE', } @@ -454,29 +472,41 @@ subtest "NoIssuesChargeGuarantorsWithGuarantees tests" => sub { my $sip_patron = C4::SIP::ILS::Patron->new( $patron->cardnumber ); - is( $sip_patron->fines_amount, 11, "Personal fines correctly reported"); - ok( !$sip_patron->charge_ok, "Guarantor blocked"); - like( $sip_patron->screen_msg, qr/Patron blocked by fines \(11\.11\) on related accounts/,"Screen message includes related fines total"); + is( $sip_patron->fines_amount, 11, "Personal fines correctly reported" ); + ok( !$sip_patron->charge_ok, "Guarantor blocked" ); + like( + $sip_patron->screen_msg, qr/Patron blocked by fines \(11\.11\) on related accounts/, + "Screen message includes related fines total" + ); $sip_patron = C4::SIP::ILS::Patron->new( $child->cardnumber ); - is( $sip_patron->fines_amount, 0.11, "Personal fines correctly reported"); - ok( !$sip_patron->charge_ok, "Guarantee blocked"); - like( $sip_patron->screen_msg, qr/Patron blocked by fines \(11\.11\) on related accounts/,"Screen message includes related fines total"); + is( $sip_patron->fines_amount, 0.11, "Personal fines correctly reported" ); + ok( !$sip_patron->charge_ok, "Guarantee blocked" ); + like( + $sip_patron->screen_msg, qr/Patron blocked by fines \(11\.11\) on related accounts/, + "Screen message includes related fines total" + ); - t::lib::Mocks::mock_preference('NoIssuesChargeGuarantorsWithGuarantees', 12.01); + t::lib::Mocks::mock_preference( 'NoIssuesChargeGuarantorsWithGuarantees', 12.01 ); $sip_patron = C4::SIP::ILS::Patron->new( $child->cardnumber ); - is( $sip_patron->fines_amount, 0.11, "Personal fines correctly reported"); - ok( $sip_patron->charge_ok, "Guarantee not blocked"); - unlike( $sip_patron->screen_msg, qr/Patron blocked by fines .* on related accounts/,"Screen message does not indicate block"); + is( $sip_patron->fines_amount, 0.11, "Personal fines correctly reported" ); + ok( $sip_patron->charge_ok, "Guarantee not blocked" ); + unlike( + $sip_patron->screen_msg, qr/Patron blocked by fines .* on related accounts/, + "Screen message does not indicate block" + ); $sip_patron = C4::SIP::ILS::Patron->new( $patron->cardnumber ); - is( $sip_patron->fines_amount, 11, "Personal fines correctly reported"); - ok( $sip_patron->charge_ok, "Patron not blocked"); - unlike( $sip_patron->screen_msg, qr/Patron blocked by fines .* on related accounts/,"Screen message does not indicate block"); + is( $sip_patron->fines_amount, 11, "Personal fines correctly reported" ); + ok( $sip_patron->charge_ok, "Patron not blocked" ); + unlike( + $sip_patron->screen_msg, qr/Patron blocked by fines .* on related accounts/, + "Screen message does not indicate block" + ); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/SIP/SIPServer.t b/t/db_dependent/SIP/SIPServer.t index 8d6d574776..eb476d1614 100755 --- a/t/db_dependent/SIP/SIPServer.t +++ b/t/db_dependent/SIP/SIPServer.t @@ -30,11 +30,11 @@ BEGIN { # Configuration->new and PreFork->run. use Test::MockModule; use C4::SIP::Sip::Configuration; - $mockConfig = Test::MockModule->new( 'C4::SIP::Sip::Configuration' ); + $mockConfig = Test::MockModule->new('C4::SIP::Sip::Configuration'); $mockConfig->mock( 'new', sub { return {}; } ); use Net::Server::PreFork; - $mockPrefork = Test::MockModule->new( 'Net::Server::PreFork' ); - $mockPrefork->mock( 'run', sub {} ); + $mockPrefork = Test::MockModule->new('Net::Server::PreFork'); + $mockPrefork->mock( 'run', sub { } ); } use C4::SIP::SIPServer qw( get_timeout ); @@ -45,19 +45,20 @@ use C4::SIP::SIPServer qw( get_timeout ); subtest 'Get_timeout' => sub { plan tests => 11; - my $server = { policy => { timeout => 1 }, - config => { timeout => 2 }, - service => { - timeout => 3, - client_timeout => 4, - }, + my $server = { + policy => { timeout => 1 }, + config => { timeout => 2 }, + service => { + timeout => 3, + client_timeout => 4, + }, }; is( C4::SIP::SIPServer::get_timeout(), 30, "Default fallback" ); - is( C4::SIP::SIPServer::get_timeout( undef, { fallback => 25 } ), 25, "Fallback parameter" ); - is( C4::SIP::SIPServer::get_timeout( $server, { transport => 1 } ), 3, "Transport value" ); - is( C4::SIP::SIPServer::get_timeout( $server, { client => 1 } ), 4, "Client value" ); - is( C4::SIP::SIPServer::get_timeout( $server, { policy => 1 } ), '001', "Policy value" ); + is( C4::SIP::SIPServer::get_timeout( undef, { fallback => 25 } ), 25, "Fallback parameter" ); + is( C4::SIP::SIPServer::get_timeout( $server, { transport => 1 } ), 3, "Transport value" ); + is( C4::SIP::SIPServer::get_timeout( $server, { client => 1 } ), 4, "Client value" ); + is( C4::SIP::SIPServer::get_timeout( $server, { policy => 1 } ), '001', "Policy value" ); delete $server->{policy}->{timeout}; is( C4::SIP::SIPServer::get_timeout( $server, { policy => 1 } ), '000', "No policy" ); diff --git a/t/db_dependent/SIP/Transaction.t b/t/db_dependent/SIP/Transaction.t index afdef84fa4..d7c4d8f5ac 100755 --- a/t/db_dependent/SIP/Transaction.t +++ b/t/db_dependent/SIP/Transaction.t @@ -928,8 +928,7 @@ subtest do_checkout_with_noblock => sub { } ); - t::lib::Mocks::mock_userenv( - { branchcode => $library->branchcode, flags => 1 } ); + t::lib::Mocks::mock_userenv( { branchcode => $library->branchcode, flags => 1 } ); my $item = $builder->build_sample_item( { @@ -940,12 +939,15 @@ subtest do_checkout_with_noblock => sub { my $sip_patron = C4::SIP::ILS::Patron->new( $patron->cardnumber ); my $sip_item = C4::SIP::ILS::Item->new( $item->barcode ); - my $circ = - $ils->checkout( $patron->cardnumber, $item->barcode, undef, undef, - $server->{account}, '19990102 030405' ); + my $circ = $ils->checkout( + $patron->cardnumber, $item->barcode, undef, undef, + $server->{account}, '19990102 030405' + ); - is( $patron->checkouts->count, - 1, 'No Block checkout was performed for debarred patron' ); + is( + $patron->checkouts->count, + 1, 'No Block checkout was performed for debarred patron' + ); }; subtest do_checkout_with_holds => sub { @@ -1148,7 +1150,7 @@ RULES my $item_dvd = $builder->build_sample_item( { library => $library2->branchcode, - itype => 'DVD' + itype => 'DVD' } ); diff --git a/t/db_dependent/Search.t b/t/db_dependent/Search.t index 00ce65abda..4896f79e67 100755 --- a/t/db_dependent/Search.t +++ b/t/db_dependent/Search.t @@ -47,240 +47,262 @@ use File::Path; our @cleanup; sub matchesExplodedTerms { - my ($message, $query, @terms) = @_; - my $match = '(' . join ('|', map { " \@attr 1=Subject \@attr 4=1 \"$_\"" } @terms) . "){" . scalar(@terms) . "}"; - like($query, qr/$match/, $message); + my ( $message, $query, @terms ) = @_; + my $match = '(' . join( '|', map { " \@attr 1=Subject \@attr 4=1 \"$_\"" } @terms ) . "){" . scalar(@terms) . "}"; + like( $query, qr/$match/, $message ); } -our $QueryStemming = 0; +our $QueryStemming = 0; our $QueryAutoTruncate = 0; our $QueryWeightFields = 0; -our $QueryFuzzy = 0; -our $SearchEngine = 'Zebra'; -our $marcflavour = 'MARC21'; -our $htdocs = File::Spec->rel2abs(dirname($0)); +our $QueryFuzzy = 0; +our $SearchEngine = 'Zebra'; +our $marcflavour = 'MARC21'; +our $htdocs = File::Spec->rel2abs( dirname($0) ); my @htdocs = split /\//, $htdocs; $htdocs[-2] = 'koha-tmpl'; $htdocs[-1] = 'opac-tmpl'; -$htdocs = join '/', @htdocs; +$htdocs = join '/', @htdocs; our $contextmodule = Test::MockModule->new('C4::Context'); -$contextmodule->mock('preference', sub { - my ($self, $pref) = @_; - if ($pref eq 'marcflavour') { - return $marcflavour; - } elsif ($pref eq 'QueryStemming') { - return $QueryStemming; - } elsif ($pref eq 'QueryAutoTruncate') { - return $QueryAutoTruncate; - } elsif ($pref eq 'QueryWeightFields') { - return $QueryWeightFields; - } elsif ($pref eq 'QueryFuzzy') { - return $QueryFuzzy; - } elsif ($pref eq 'SearchEngine') { - return $SearchEngine; - } elsif ($pref eq 'maxRecordsForFacets') { - return 20; - } elsif ($pref eq 'FacetLabelTruncationLength') { - return 20; - } elsif ($pref eq 'FacetMaxCount') { - return 20; - } elsif ($pref eq 'OpacHiddenItems') { - return ''; - } elsif ($pref eq 'opacthemes') { - return 'bootstrap'; - } elsif ($pref eq 'OPACLanguages') { - return 'en'; - } elsif ($pref eq 'AlternateHoldingsField') { - return '490av'; - } elsif ($pref eq 'AuthoritySeparator') { - return '--'; - } elsif ($pref eq 'DisplayLibraryFacets') { - return 'holding'; - } elsif ($pref eq 'UNIMARCAuthorsFacetsSeparator') { - return '--'; - } elsif ($pref eq 'casAuthentication' or $pref eq 'casLogout' or $pref eq 'casServerUrl' ) { - return ''; - } elsif ($pref eq 'template') { - return 'prog'; - } elsif ($pref eq 'OPACXSLTResultsDisplay') { - return C4::XSLT::_get_best_default_xslt_filename($htdocs, 'bootstrap','en',$marcflavour . 'slim2OPACResults.xsl'); - } elsif ($pref eq 'BiblioDefaultView') { - return 'normal'; - } elsif ($pref eq 'IdRef') { - return '0'; - } elsif ($pref eq 'IntranetBiblioDefaultView') { - return 'normal'; - } elsif ($pref eq 'OPACBaseURL') { - return 'http://library.mydnsname.org'; - } elsif ($pref eq 'OPACResultsLibrary') { - return 'homebranch'; - } elsif ($pref eq 'OpacSuppression') { - return '0'; - } elsif ($pref eq 'OPACURLOpenInNewWindow') { - return '0'; - } elsif ($pref eq 'TraceCompleteSubfields') { - return '0'; - } elsif ($pref eq 'TraceSubjectSubdivisions') { - return '0'; - } elsif ($pref eq 'TrackClicks') { - return '0'; - } elsif ($pref eq 'URLLinkText') { - return q{}; - } elsif ($pref eq 'UseAuthoritiesForTracings') { - return '1'; - } elsif ($pref eq 'UseControlNumber') { - return '0'; - } elsif ($pref eq 'UseICUStyleQuotes') { - return '0'; - } elsif ($pref eq 'viewISBD') { - return '1'; - } elsif ($pref eq 'EasyAnalyticalRecords') { - return '0'; - } elsif ($pref eq 'OpenURLResolverURL') { - return '0'; - } elsif ($pref eq 'OPACShowOpenURL') { - return '0'; - } elsif ($pref eq 'OpenURLText') { - return '0'; - } elsif ($pref eq 'OPACShowMusicalInscripts') { - return '0'; - } elsif ($pref eq 'OPACPlayMusicalInscripts') { - return '0'; - } elsif ($pref eq 'Reference_NFL_Statuses') { - return '0'; - } elsif ($pref eq 'FacetOrder') { - return 'Alphabetical'; - } elsif ($pref eq 'OPACResultsUnavailableGroupingBy') { - return 'branch'; - } elsif ($pref eq 'SearchLimitLibrary') { - return 'both'; - } elsif ($pref eq 'UseRecalls') { - return '0'; - } elsif ( $pref eq 'ContentWarningField' ) { - return q{}; - } elsif ( $pref eq 'AuthorLinkSortBy' ) { - return q{}; - } elsif ( $pref eq 'AuthorLinkSortOrder' ) { - return q{}; - } elsif ( $pref eq 'COinSinOPACResults' ) { - return q{}; - } else { - warn "The syspref $pref was requested but I don't know what to say; this indicates that the test requires updating" - unless $pref =~ m/(XSLT|item|branch|holding|image)/i; - return 0; +$contextmodule->mock( + 'preference', + sub { + my ( $self, $pref ) = @_; + if ( $pref eq 'marcflavour' ) { + return $marcflavour; + } elsif ( $pref eq 'QueryStemming' ) { + return $QueryStemming; + } elsif ( $pref eq 'QueryAutoTruncate' ) { + return $QueryAutoTruncate; + } elsif ( $pref eq 'QueryWeightFields' ) { + return $QueryWeightFields; + } elsif ( $pref eq 'QueryFuzzy' ) { + return $QueryFuzzy; + } elsif ( $pref eq 'SearchEngine' ) { + return $SearchEngine; + } elsif ( $pref eq 'maxRecordsForFacets' ) { + return 20; + } elsif ( $pref eq 'FacetLabelTruncationLength' ) { + return 20; + } elsif ( $pref eq 'FacetMaxCount' ) { + return 20; + } elsif ( $pref eq 'OpacHiddenItems' ) { + return ''; + } elsif ( $pref eq 'opacthemes' ) { + return 'bootstrap'; + } elsif ( $pref eq 'OPACLanguages' ) { + return 'en'; + } elsif ( $pref eq 'AlternateHoldingsField' ) { + return '490av'; + } elsif ( $pref eq 'AuthoritySeparator' ) { + return '--'; + } elsif ( $pref eq 'DisplayLibraryFacets' ) { + return 'holding'; + } elsif ( $pref eq 'UNIMARCAuthorsFacetsSeparator' ) { + return '--'; + } elsif ( $pref eq 'casAuthentication' or $pref eq 'casLogout' or $pref eq 'casServerUrl' ) { + return ''; + } elsif ( $pref eq 'template' ) { + return 'prog'; + } elsif ( $pref eq 'OPACXSLTResultsDisplay' ) { + return C4::XSLT::_get_best_default_xslt_filename( + $htdocs, 'bootstrap', 'en', + $marcflavour . 'slim2OPACResults.xsl' + ); + } elsif ( $pref eq 'BiblioDefaultView' ) { + return 'normal'; + } elsif ( $pref eq 'IdRef' ) { + return '0'; + } elsif ( $pref eq 'IntranetBiblioDefaultView' ) { + return 'normal'; + } elsif ( $pref eq 'OPACBaseURL' ) { + return 'http://library.mydnsname.org'; + } elsif ( $pref eq 'OPACResultsLibrary' ) { + return 'homebranch'; + } elsif ( $pref eq 'OpacSuppression' ) { + return '0'; + } elsif ( $pref eq 'OPACURLOpenInNewWindow' ) { + return '0'; + } elsif ( $pref eq 'TraceCompleteSubfields' ) { + return '0'; + } elsif ( $pref eq 'TraceSubjectSubdivisions' ) { + return '0'; + } elsif ( $pref eq 'TrackClicks' ) { + return '0'; + } elsif ( $pref eq 'URLLinkText' ) { + return q{}; + } elsif ( $pref eq 'UseAuthoritiesForTracings' ) { + return '1'; + } elsif ( $pref eq 'UseControlNumber' ) { + return '0'; + } elsif ( $pref eq 'UseICUStyleQuotes' ) { + return '0'; + } elsif ( $pref eq 'viewISBD' ) { + return '1'; + } elsif ( $pref eq 'EasyAnalyticalRecords' ) { + return '0'; + } elsif ( $pref eq 'OpenURLResolverURL' ) { + return '0'; + } elsif ( $pref eq 'OPACShowOpenURL' ) { + return '0'; + } elsif ( $pref eq 'OpenURLText' ) { + return '0'; + } elsif ( $pref eq 'OPACShowMusicalInscripts' ) { + return '0'; + } elsif ( $pref eq 'OPACPlayMusicalInscripts' ) { + return '0'; + } elsif ( $pref eq 'Reference_NFL_Statuses' ) { + return '0'; + } elsif ( $pref eq 'FacetOrder' ) { + return 'Alphabetical'; + } elsif ( $pref eq 'OPACResultsUnavailableGroupingBy' ) { + return 'branch'; + } elsif ( $pref eq 'SearchLimitLibrary' ) { + return 'both'; + } elsif ( $pref eq 'UseRecalls' ) { + return '0'; + } elsif ( $pref eq 'ContentWarningField' ) { + return q{}; + } elsif ( $pref eq 'AuthorLinkSortBy' ) { + return q{}; + } elsif ( $pref eq 'AuthorLinkSortOrder' ) { + return q{}; + } elsif ( $pref eq 'COinSinOPACResults' ) { + return q{}; + } else { + warn + "The syspref $pref was requested but I don't know what to say; this indicates that the test requires updating" + unless $pref =~ m/(XSLT|item|branch|holding|image)/i; + return 0; + } } -}); +); our $bibliomodule = Test::MockModule->new('C4::Biblio'); sub mock_GetMarcSubfieldStructure { my $marc_type = shift; - if ($marc_type eq 'MARC21') { - $bibliomodule->mock('GetMarcSubfieldStructure', sub { - return { - 'biblio.biblionumber' => [{ tagfield => '999', tagsubfield => 'c' }], - 'biblio.isbn' => [{ tagfield => '020', tagsubfield => 'a' }], - 'biblio.title' => [{ tagfield => '245', tagsubfield => 'a' }], - 'biblio.author' => [{ tagfield => '100', tagsubfield => 'a' }], - 'biblio.notes' => [{ tagfield => '500', tagsubfield => 'a' }], - 'items.barcode' => [{ tagfield => '952', tagsubfield => 'p' }], - 'items.booksellerid' => [{ tagfield => '952', tagsubfield => 'e' }], - 'items.ccode' => [{ tagfield => '952', tagsubfield => '8' }], - 'items.cn_sort' => [{ tagfield => '952', tagsubfield => '6' }], - 'items.cn_source' => [{ tagfield => '952', tagsubfield => '2' }], - 'items.coded_location_qualifier' => [{ tagfield => '952', tagsubfield => 'f' }], - 'items.copynumber' => [{ tagfield => '952', tagsubfield => 't' }], - 'items.damaged' => [{ tagfield => '952', tagsubfield => '4' }], - 'items.dateaccessioned' => [{ tagfield => '952', tagsubfield => 'd' }], - 'items.datelastborrowed' => [{ tagfield => '952', tagsubfield => 's' }], - 'items.datelastseen' => [{ tagfield => '952', tagsubfield => 'r' }], - 'items.enumchron' => [{ tagfield => '952', tagsubfield => 'h' }], - 'items.holdingbranch' => [{ tagfield => '952', tagsubfield => 'b' }], - 'items.homebranch' => [{ tagfield => '952', tagsubfield => 'a' }], - 'items.issues' => [{ tagfield => '952', tagsubfield => 'l' }], - 'items.itemcallnumber' => [{ tagfield => '952', tagsubfield => 'o' }], - 'items.itemlost' => [{ tagfield => '952', tagsubfield => '1' }], - 'items.itemnotes' => [{ tagfield => '952', tagsubfield => 'z' }], - 'items.itemnumber' => [{ tagfield => '952', tagsubfield => '9' }], - 'items.itype' => [{ tagfield => '952', tagsubfield => 'y' }], - 'items.location' => [{ tagfield => '952', tagsubfield => 'c' }], - 'items.materials' => [{ tagfield => '952', tagsubfield => '3' }], - 'items.nonpublicnote' => [{ tagfield => '952', tagsubfield => 'x' }], - 'items.notforloan' => [{ tagfield => '952', tagsubfield => '7' }], - 'items.onloan' => [{ tagfield => '952', tagsubfield => 'q' }], - 'items.price' => [{ tagfield => '952', tagsubfield => 'g' }], - 'items.renewals' => [{ tagfield => '952', tagsubfield => 'm' }], - 'items.replacementprice' => [{ tagfield => '952', tagsubfield => 'v' }], - 'items.replacementpricedate' => [{ tagfield => '952', tagsubfield => 'w' }], - 'items.reserves' => [{ tagfield => '952', tagsubfield => 'n' }], - 'items.restricted' => [{ tagfield => '952', tagsubfield => '5' }], - 'items.stack' => [{ tagfield => '952', tagsubfield => 'j' }], - 'items.uri' => [{ tagfield => '952', tagsubfield => 'u' }], - 'items.withdrawn' => [{ tagfield => '952', tagsubfield => '0' }], + if ( $marc_type eq 'MARC21' ) { + $bibliomodule->mock( + 'GetMarcSubfieldStructure', + sub { + return { + 'biblio.biblionumber' => [ { tagfield => '999', tagsubfield => 'c' } ], + 'biblio.isbn' => [ { tagfield => '020', tagsubfield => 'a' } ], + 'biblio.title' => [ { tagfield => '245', tagsubfield => 'a' } ], + 'biblio.author' => [ { tagfield => '100', tagsubfield => 'a' } ], + 'biblio.notes' => [ { tagfield => '500', tagsubfield => 'a' } ], + 'items.barcode' => [ { tagfield => '952', tagsubfield => 'p' } ], + 'items.booksellerid' => [ { tagfield => '952', tagsubfield => 'e' } ], + 'items.ccode' => [ { tagfield => '952', tagsubfield => '8' } ], + 'items.cn_sort' => [ { tagfield => '952', tagsubfield => '6' } ], + 'items.cn_source' => [ { tagfield => '952', tagsubfield => '2' } ], + 'items.coded_location_qualifier' => [ { tagfield => '952', tagsubfield => 'f' } ], + 'items.copynumber' => [ { tagfield => '952', tagsubfield => 't' } ], + 'items.damaged' => [ { tagfield => '952', tagsubfield => '4' } ], + 'items.dateaccessioned' => [ { tagfield => '952', tagsubfield => 'd' } ], + 'items.datelastborrowed' => [ { tagfield => '952', tagsubfield => 's' } ], + 'items.datelastseen' => [ { tagfield => '952', tagsubfield => 'r' } ], + 'items.enumchron' => [ { tagfield => '952', tagsubfield => 'h' } ], + 'items.holdingbranch' => [ { tagfield => '952', tagsubfield => 'b' } ], + 'items.homebranch' => [ { tagfield => '952', tagsubfield => 'a' } ], + 'items.issues' => [ { tagfield => '952', tagsubfield => 'l' } ], + 'items.itemcallnumber' => [ { tagfield => '952', tagsubfield => 'o' } ], + 'items.itemlost' => [ { tagfield => '952', tagsubfield => '1' } ], + 'items.itemnotes' => [ { tagfield => '952', tagsubfield => 'z' } ], + 'items.itemnumber' => [ { tagfield => '952', tagsubfield => '9' } ], + 'items.itype' => [ { tagfield => '952', tagsubfield => 'y' } ], + 'items.location' => [ { tagfield => '952', tagsubfield => 'c' } ], + 'items.materials' => [ { tagfield => '952', tagsubfield => '3' } ], + 'items.nonpublicnote' => [ { tagfield => '952', tagsubfield => 'x' } ], + 'items.notforloan' => [ { tagfield => '952', tagsubfield => '7' } ], + 'items.onloan' => [ { tagfield => '952', tagsubfield => 'q' } ], + 'items.price' => [ { tagfield => '952', tagsubfield => 'g' } ], + 'items.renewals' => [ { tagfield => '952', tagsubfield => 'm' } ], + 'items.replacementprice' => [ { tagfield => '952', tagsubfield => 'v' } ], + 'items.replacementpricedate' => [ { tagfield => '952', tagsubfield => 'w' } ], + 'items.reserves' => [ { tagfield => '952', tagsubfield => 'n' } ], + 'items.restricted' => [ { tagfield => '952', tagsubfield => '5' } ], + 'items.stack' => [ { tagfield => '952', tagsubfield => 'j' } ], + 'items.uri' => [ { tagfield => '952', tagsubfield => 'u' } ], + 'items.withdrawn' => [ { tagfield => '952', tagsubfield => '0' } ], }; - }); + } + ); } } sub run_marc21_search_tests { $marcflavour = 'MARC21'; - my $mock_zebra = t::lib::Mocks::Zebra->new({marcflavour => $marcflavour}); + my $mock_zebra = t::lib::Mocks::Zebra->new( { marcflavour => $marcflavour } ); push @cleanup, $mock_zebra; mock_GetMarcSubfieldStructure($marcflavour); - use_ok('C4::Search', qw( getIndexes FindDuplicate SimpleSearch getRecords buildQuery searchResults )); + use_ok( 'C4::Search', qw( getIndexes FindDuplicate SimpleSearch getRecords buildQuery searchResults ) ); # set search syspreferences to a known starting point - $QueryStemming = 0; + $QueryStemming = 0; $QueryAutoTruncate = 0; $QueryWeightFields = 0; - $QueryFuzzy = 0; + $QueryFuzzy = 0; my $indexes = C4::Search::getIndexes(); - is(scalar(grep(/^ti$/, @$indexes)), 1, "Title index supported"); - is(scalar(grep(/^arl$/, @$indexes)), 1, "Accelerated reading level index supported"); - is(scalar(grep(/^arp$/, @$indexes)), 1, "Accelerated reading point index supported"); + is( scalar( grep( /^ti$/, @$indexes ) ), 1, "Title index supported" ); + is( scalar( grep( /^arl$/, @$indexes ) ), 1, "Accelerated reading level index supported" ); + is( scalar( grep( /^arp$/, @$indexes ) ), 1, "Accelerated reading point index supported" ); my $bibliomodule = Test::MockModule->new('C4::Biblio'); my %branches = ( 'CPL' => { 'branchaddress1' => 'Jefferson Summit', 'branchcode' => 'CPL', 'branchname' => 'Centerville', }, - 'FFL' => { 'branchaddress1' => 'River Station', 'branchcode' => 'FFL', 'branchname' => 'Fairfield', }, - 'FPL' => { 'branchaddress1' => 'Hickory Squere', 'branchcode' => 'FPL', 'branchname' => 'Fairview', }, - 'FRL' => { 'branchaddress1' => 'Smith Heights', 'branchcode' => 'FRL', 'branchname' => 'Franklin', }, + 'FFL' => { 'branchaddress1' => 'River Station', 'branchcode' => 'FFL', 'branchname' => 'Fairfield', }, + 'FPL' => { 'branchaddress1' => 'Hickory Squere', 'branchcode' => 'FPL', 'branchname' => 'Fairview', }, + 'FRL' => { 'branchaddress1' => 'Smith Heights', 'branchcode' => 'FRL', 'branchname' => 'Franklin', }, 'IPT' => { 'branchaddress1' => '', 'branchcode' => 'IPT', 'branchname' => "Institut Protestant de Théologie", }, - 'LPL' => { 'branchaddress1' => 'East Hills', 'branchcode' => 'LPL', 'branchname' => 'Liberty', }, + 'LPL' => { 'branchaddress1' => 'East Hills', 'branchcode' => 'LPL', 'branchname' => 'Liberty', }, 'MPL' => { 'branchaddress1' => '372 Forest Street', 'branchcode' => 'MPL', 'branchname' => 'Midway', }, - 'PVL' => { 'branchaddress1' => 'Meadow Grove', 'branchcode' => 'PVL', 'branchname' => 'Pleasant Valley', }, - 'RPL' => { 'branchaddress1' => 'Johnson Terrace', 'branchcode' => 'RPL', 'branchname' => 'Riverside', }, + 'PVL' => { 'branchaddress1' => 'Meadow Grove', 'branchcode' => 'PVL', 'branchname' => 'Pleasant Valley', }, + 'RPL' => { 'branchaddress1' => 'Johnson Terrace', 'branchcode' => 'RPL', 'branchname' => 'Riverside', }, 'SPL' => { 'branchaddress1' => 'Highland Boulevard', 'branchcode' => 'SPL', 'branchname' => 'Springfield', }, - 'S' => { 'branchaddress1' => '', 'branchcode' => 'S', 'branchname' => 'Test', }, - 'TPL' => { 'branchaddress1' => 'Valley Way', 'branchcode' => 'TPL', 'branchname' => 'Troy', }, - 'UPL' => { 'branchaddress1' => 'Chestnut Hollow', 'branchcode' => 'UPL', 'branchname' => 'Union', }, + 'S' => { 'branchaddress1' => '', 'branchcode' => 'S', 'branchname' => 'Test', }, + 'TPL' => { 'branchaddress1' => 'Valley Way', 'branchcode' => 'TPL', 'branchname' => 'Troy', }, + 'UPL' => { 'branchaddress1' => 'Chestnut Hollow', 'branchcode' => 'UPL', 'branchname' => 'Union', }, ); my %itemtypes = ( 'BK' => { 'imageurl' => 'bridge/book.png', 'summary' => '', 'itemtype' => 'BK', 'description' => 'Books' }, - 'CF' => { 'imageurl' => 'bridge/computer_file.png', 'summary' => '', 'itemtype' => 'CF', 'description' => 'Computer Files' }, - 'CR' => { 'imageurl' => 'bridge/periodical.png', 'summary' => '', 'itemtype' => 'CR', 'description' => 'Continuing Resources' }, - 'MP' => { 'imageurl' => 'bridge/map.png', 'summary' => '', 'itemtype' => 'MP', 'description' => 'Maps' }, + 'CF' => { + 'imageurl' => 'bridge/computer_file.png', 'summary' => '', 'itemtype' => 'CF', + 'description' => 'Computer Files' + }, + 'CR' => { + 'imageurl' => 'bridge/periodical.png', 'summary' => '', 'itemtype' => 'CR', + 'description' => 'Continuing Resources' + }, + 'MP' => { 'imageurl' => 'bridge/map.png', 'summary' => '', 'itemtype' => 'MP', 'description' => 'Maps' }, 'MU' => { 'imageurl' => 'bridge/sound.png', 'summary' => '', 'itemtype' => 'MU', 'description' => 'Music' }, - 'MX' => { 'imageurl' => 'bridge/kit.png', 'summary' => '', 'itemtype' => 'MX', 'description' => 'Mixed Materials' }, + 'MX' => + { 'imageurl' => 'bridge/kit.png', 'summary' => '', 'itemtype' => 'MX', 'description' => 'Mixed Materials' }, 'REF' => { 'imageurl' => '', 'summary' => '', 'itemtype' => 'REF', 'description' => 'Reference' }, - 'VM' => { 'imageurl' => 'bridge/dvd.png', 'summary' => '', 'itemtype' => 'VM', 'description' => 'Visual Materials' }, + 'VM' => { + 'imageurl' => 'bridge/dvd.png', 'summary' => '', 'itemtype' => 'VM', 'description' => 'Visual Materials' + }, ); my $sourcedir = dirname(__FILE__) . "/data"; $mock_zebra->load_records( sprintf( "%s/%s/zebraexport/biblio", $sourcedir, lc($marcflavour) ), - 'iso2709', 'biblios', 1 ); + 'iso2709', 'biblios', 1 + ); $mock_zebra->load_records( sprintf( "%s/%s/zebraexport/large_biblio", $sourcedir, lc($marcflavour) ), - 'marcxml', 'biblios', 0 + 'marcxml', + 'biblios', + 0 ); $mock_zebra->load_records( sprintf( "%s/%s/zebraexport/authority", $sourcedir, lc($marcflavour) ), @@ -289,245 +311,357 @@ sub run_marc21_search_tests { $mock_zebra->launch_zebra; - my ($biblionumber, $title); + my ( $biblionumber, $title ); my $record = MARC::Record->new; $record->add_fields( - [ '020', ' ', ' ', a => '9788522421718' ], - [ '245', '0', '0', a => 'Administração da produção /' ] - ); - ($biblionumber,undef,$title) = FindDuplicate($record); - is($biblionumber, 51, 'Found duplicate with ISBN'); + [ '020', ' ', ' ', a => '9788522421718' ], + [ '245', '0', '0', a => 'Administração da produção /' ] + ); + ( $biblionumber, undef, $title ) = FindDuplicate($record); + is( $biblionumber, 51, 'Found duplicate with ISBN' ); $record = MARC::Record->new; $record->add_fields( - [ '020', ' ', ' ', a => '0465039146' ], - [ '020', ' ', ' ', a => '9780465039142' ], - [ '245', '0', '0', a => 'Doesnt matter, searching isbn /' ] - ); - ($biblionumber,undef,$title) = FindDuplicate($record); - is($biblionumber, 48, 'Found duplicate with ISBN when two ISBNs in record'); + [ '020', ' ', ' ', a => '0465039146' ], + [ '020', ' ', ' ', a => '9780465039142' ], + [ '245', '0', '0', a => 'Doesnt matter, searching isbn /' ] + ); + ( $biblionumber, undef, $title ) = FindDuplicate($record); + is( $biblionumber, 48, 'Found duplicate with ISBN when two ISBNs in record' ); $record = MARC::Record->new; $record->add_fields( - [ '100', '1', ' ', a => 'Carter, Philip J.' ], - [ '245', '1', '4', a => 'Test your emotional intelligence :' ] - ); - ($biblionumber,undef,$title) = FindDuplicate($record); - is($biblionumber, 203, 'Found duplicate with author/title'); + [ '100', '1', ' ', a => 'Carter, Philip J.' ], + [ '245', '1', '4', a => 'Test your emotional intelligence :' ] + ); + ( $biblionumber, undef, $title ) = FindDuplicate($record); + is( $biblionumber, 203, 'Found duplicate with author/title' ); # Testing SimpleSearch - my ( $error, $marcresults, $total_hits ) = SimpleSearch("book", 0, 9); + my ( $error, $marcresults, $total_hits ) = SimpleSearch( "book", 0, 9 ); - is(scalar @$marcresults, 9, "SimpleSearch retrieved requested number of records"); - is($total_hits, 101, "SimpleSearch for 'book' matched right number of records"); - is($error, undef, "SimpleSearch does not return an error when successful"); + is( scalar @$marcresults, 9, "SimpleSearch retrieved requested number of records" ); + is( $total_hits, 101, "SimpleSearch for 'book' matched right number of records" ); + is( $error, undef, "SimpleSearch does not return an error when successful" ); my $marcresults2; - ( $error, $marcresults2, $total_hits ) = SimpleSearch("book", 5, 5); - is($marcresults->[5], $marcresults2->[0], "SimpleSearch cursor functions"); + ( $error, $marcresults2, $total_hits ) = SimpleSearch( "book", 5, 5 ); + is( $marcresults->[5], $marcresults2->[0], "SimpleSearch cursor functions" ); - ( $error, $marcresults, $total_hits ) = SimpleSearch("kw=book", 0, 10); - is($total_hits, 101, "SimpleSearch handles simple CCL"); + ( $error, $marcresults, $total_hits ) = SimpleSearch( "kw=book", 0, 10 ); + is( $total_hits, 101, "SimpleSearch handles simple CCL" ); - ( $error, $marcresults, $total_hits ) = SimpleSearch("Music-number=49631-2", 0, 10); - is($total_hits, 1, "SimpleSearch on music publisher number works (bug 8252)"); - ( $error, $marcresults, $total_hits ) = SimpleSearch("Identifier-publisher-for-music=49631-2", 0, 10); - is($total_hits, 1, "SimpleSearch on music publisher number works using Identifier-publisher-for-music (bug 8252)"); + ( $error, $marcresults, $total_hits ) = SimpleSearch( "Music-number=49631-2", 0, 10 ); + is( $total_hits, 1, "SimpleSearch on music publisher number works (bug 8252)" ); + ( $error, $marcresults, $total_hits ) = SimpleSearch( "Identifier-publisher-for-music=49631-2", 0, 10 ); + is( + $total_hits, 1, + "SimpleSearch on music publisher number works using Identifier-publisher-for-music (bug 8252)" + ); # Testing getRecords my $results_hashref; my $facets_loop; ( undef, $results_hashref, $facets_loop ) = - getRecords('kw:book', 'book', [], [ 'biblioserver' ], '19', 0, \%branches, \%itemtypes, 'ccl', undef); - is($results_hashref->{biblioserver}->{hits}, 101, "getRecords keyword search for 'book' matched right number of records"); - is(scalar @{$results_hashref->{biblioserver}->{RECORDS}}, 19, "getRecords returned requested number of records"); + getRecords( 'kw:book', 'book', [], ['biblioserver'], '19', 0, \%branches, \%itemtypes, 'ccl', undef ); + is( + $results_hashref->{biblioserver}->{hits}, 101, + "getRecords keyword search for 'book' matched right number of records" + ); + is( + scalar @{ $results_hashref->{biblioserver}->{RECORDS} }, 19, + "getRecords returned requested number of records" + ); my $record5 = $results_hashref->{biblioserver}->{RECORDS}->[5]; ( undef, $results_hashref, $facets_loop ) = - getRecords('kw:book', 'book', [], [ 'biblioserver' ], '20', 5, \%branches, \%itemtypes, 'ccl', undef); - ok(!defined $results_hashref->{biblioserver}->{RECORDS}->[0] && - !defined $results_hashref->{biblioserver}->{RECORDS}->[1] && - !defined $results_hashref->{biblioserver}->{RECORDS}->[2] && - !defined $results_hashref->{biblioserver}->{RECORDS}->[3] && - !defined $results_hashref->{biblioserver}->{RECORDS}->[4] && - $results_hashref->{biblioserver}->{RECORDS}->[5] eq $record5, "getRecords cursor works"); + getRecords( 'kw:book', 'book', [], ['biblioserver'], '20', 5, \%branches, \%itemtypes, 'ccl', undef ); + ok( !defined $results_hashref->{biblioserver}->{RECORDS}->[0] + && !defined $results_hashref->{biblioserver}->{RECORDS}->[1] + && !defined $results_hashref->{biblioserver}->{RECORDS}->[2] + && !defined $results_hashref->{biblioserver}->{RECORDS}->[3] + && !defined $results_hashref->{biblioserver}->{RECORDS}->[4] + && $results_hashref->{biblioserver}->{RECORDS}->[5] eq $record5, "getRecords cursor works" ); ( undef, $results_hashref, $facets_loop ) = - getRecords('ti:book', 'ti:book', [], [ 'biblioserver' ], '20', 0, \%branches, \%itemtypes, 'ccl', undef); - is($results_hashref->{biblioserver}->{hits}, 11, "getRecords title search for 'book' matched right number of records"); + getRecords( 'ti:book', 'ti:book', [], ['biblioserver'], '20', 0, \%branches, \%itemtypes, 'ccl', undef ); + is( + $results_hashref->{biblioserver}->{hits}, 11, + "getRecords title search for 'book' matched right number of records" + ); ( undef, $results_hashref, $facets_loop ) = - getRecords('au:Lessig', 'au:Lessig', [], [ 'biblioserver' ], '20', 0, \%branches, \%itemtypes, 'ccl', undef); - is($results_hashref->{biblioserver}->{hits}, 4, "getRecords title search for 'Australia' matched right number of records"); - -( undef, $results_hashref, $facets_loop ) = - getRecords('salud', 'salud', [], [ 'biblioserver' ], '19', 0, \%branches, \%itemtypes, 'ccl', undef); -ok(MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[0],'UTF-8')->title_proper() =~ m/^Efectos del ambiente/ && - MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[7],'UTF-8')->title_proper() eq 'Salud y seguridad de los trabajadores del sector salud: manual para gerentes y administradores^ies' && - MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[18],'UTF-8')->title_proper() =~ m/^Indicadores de resultados identificados/ - , "Simple relevance sorting in getRecords matches old behavior"); - -( undef, $results_hashref, $facets_loop ) = - getRecords('salud', 'salud', [ 'author_az' ], [ 'biblioserver' ], '38', 0, \%branches, \%itemtypes, 'ccl', undef); -ok(MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[0],'UTF-8')->title_proper() =~ m/la enfermedad laboral\^ies$/ && - MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[6],'UTF-8')->title_proper() =~ m/^Indicadores de resultados identificados/ && - MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[18],'UTF-8')->title_proper() eq 'World health statistics 2009^ien' - , "Simple ascending author sorting in getRecords matches old behavior"); - -( undef, $results_hashref, $facets_loop ) = - getRecords('salud', 'salud', [ 'author_za' ], [ 'biblioserver' ], '38', 0, \%branches, \%itemtypes, 'ccl', undef); -ok(MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[0],'UTF-8')->title_proper() eq 'World health statistics 2009^ien' && - MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[12],'UTF-8')->title_proper() =~ m/^Indicadores de resultados identificados/ && - MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[18],'UTF-8')->title_proper() =~ m/la enfermedad laboral\^ies$/ - , "Simple descending author sorting in getRecords matches old behavior"); - -( undef, $results_hashref, $facets_loop ) = - getRecords('salud', 'salud', [ 'pubdate_asc' ], [ 'biblioserver' ], '38', 0, \%branches, \%itemtypes, 'ccl', undef); -ok(MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[0],'UTF-8')->title_proper() eq 'Manual de higiene industrial^ies' && - MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[7],'UTF-8')->title_proper() =~ m/seguridad e higiene del trabajo\^ies$/ && - MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[18],'UTF-8')->title_proper() =~ m/^Indicadores de resultados identificados/ - , "Simple ascending publication date sorting in getRecords matches old behavior"); - -( undef, $results_hashref, $facets_loop ) = - getRecords('salud', 'salud', [ 'pubdate_dsc' ], [ 'biblioserver' ], '38', 0, \%branches, \%itemtypes, 'ccl', undef); -ok(MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[0],'UTF-8')->title_proper() =~ m/^Estado de salud/ && - MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[7],'UTF-8')->title_proper() eq 'World health statistics 2009^ien' && - MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[18],'UTF-8')->title_proper() eq 'Manual de higiene industrial^ies' - , "Simple descending publication date sorting in getRecords matches old behavior"); + getRecords( 'au:Lessig', 'au:Lessig', [], ['biblioserver'], '20', 0, \%branches, \%itemtypes, 'ccl', undef ); + is( + $results_hashref->{biblioserver}->{hits}, 4, + "getRecords title search for 'Australia' matched right number of records" + ); ( undef, $results_hashref, $facets_loop ) = - getRecords('books', 'books', [ 'relevance' ], [ 'biblioserver' ], '20', 0, \%branches, \%itemtypes, undef, 1); - $record = MARC::Record::new_from_usmarc($results_hashref->{biblioserver}->{RECORDS}->[0]); - is($record->title_proper(), 'Books', "Scan returned requested item"); - is($record->subfield('100', 'a'), 2, "Scan returned correct number of records matching term"); + getRecords( 'salud', 'salud', [], ['biblioserver'], '19', 0, \%branches, \%itemtypes, 'ccl', undef ); + ok( + MARC::Record::new_from_xml( $results_hashref->{biblioserver}->{RECORDS}->[0], 'UTF-8' )->title_proper() =~ + m/^Efectos del ambiente/ + && MARC::Record::new_from_xml( $results_hashref->{biblioserver}->{RECORDS}->[7], 'UTF-8' )->title_proper() + eq 'Salud y seguridad de los trabajadores del sector salud: manual para gerentes y administradores^ies' + && MARC::Record::new_from_xml( $results_hashref->{biblioserver}->{RECORDS}->[18], 'UTF-8' )->title_proper() + =~ m/^Indicadores de resultados identificados/, + "Simple relevance sorting in getRecords matches old behavior" + ); + + ( undef, $results_hashref, $facets_loop ) = + getRecords( 'salud', 'salud', ['author_az'], ['biblioserver'], '38', 0, \%branches, \%itemtypes, 'ccl', undef ); + ok( + MARC::Record::new_from_xml( $results_hashref->{biblioserver}->{RECORDS}->[0], 'UTF-8' )->title_proper() =~ + m/la enfermedad laboral\^ies$/ + && MARC::Record::new_from_xml( $results_hashref->{biblioserver}->{RECORDS}->[6], 'UTF-8' )->title_proper() + =~ m/^Indicadores de resultados identificados/ + && MARC::Record::new_from_xml( $results_hashref->{biblioserver}->{RECORDS}->[18], 'UTF-8' )->title_proper() + eq 'World health statistics 2009^ien', + "Simple ascending author sorting in getRecords matches old behavior" + ); + + ( undef, $results_hashref, $facets_loop ) = + getRecords( 'salud', 'salud', ['author_za'], ['biblioserver'], '38', 0, \%branches, \%itemtypes, 'ccl', undef ); + ok( MARC::Record::new_from_xml( $results_hashref->{biblioserver}->{RECORDS}->[0], 'UTF-8' )->title_proper() eq + 'World health statistics 2009^ien' + && MARC::Record::new_from_xml( $results_hashref->{biblioserver}->{RECORDS}->[12], 'UTF-8' )->title_proper() + =~ m/^Indicadores de resultados identificados/ + && MARC::Record::new_from_xml( $results_hashref->{biblioserver}->{RECORDS}->[18], 'UTF-8' )->title_proper() + =~ m/la enfermedad laboral\^ies$/, "Simple descending author sorting in getRecords matches old behavior" ); + + ( undef, $results_hashref, $facets_loop ) = getRecords( + 'salud', 'salud', ['pubdate_asc'], ['biblioserver'], '38', 0, \%branches, \%itemtypes, 'ccl', + undef + ); + ok( + MARC::Record::new_from_xml( $results_hashref->{biblioserver}->{RECORDS}->[0], 'UTF-8' )->title_proper() eq + 'Manual de higiene industrial^ies' + && MARC::Record::new_from_xml( $results_hashref->{biblioserver}->{RECORDS}->[7], 'UTF-8' )->title_proper() + =~ m/seguridad e higiene del trabajo\^ies$/ + && MARC::Record::new_from_xml( $results_hashref->{biblioserver}->{RECORDS}->[18], 'UTF-8' )->title_proper() + =~ m/^Indicadores de resultados identificados/, + "Simple ascending publication date sorting in getRecords matches old behavior" + ); + + ( undef, $results_hashref, $facets_loop ) = getRecords( + 'salud', 'salud', ['pubdate_dsc'], ['biblioserver'], '38', 0, \%branches, \%itemtypes, 'ccl', + undef + ); + ok( + MARC::Record::new_from_xml( $results_hashref->{biblioserver}->{RECORDS}->[0], 'UTF-8' )->title_proper() =~ + m/^Estado de salud/ + && MARC::Record::new_from_xml( $results_hashref->{biblioserver}->{RECORDS}->[7], 'UTF-8' )->title_proper() + eq 'World health statistics 2009^ien' + && MARC::Record::new_from_xml( $results_hashref->{biblioserver}->{RECORDS}->[18], 'UTF-8' )->title_proper() + eq 'Manual de higiene industrial^ies', + "Simple descending publication date sorting in getRecords matches old behavior" + ); + + ( undef, $results_hashref, $facets_loop ) = + getRecords( 'books', 'books', ['relevance'], ['biblioserver'], '20', 0, \%branches, \%itemtypes, undef, 1 ); + $record = MARC::Record::new_from_usmarc( $results_hashref->{biblioserver}->{RECORDS}->[0] ); + is( $record->title_proper(), 'Books', "Scan returned requested item" ); + is( $record->subfield( '100', 'a' ), 2, "Scan returned correct number of records matching term" ); + # Time to test buildQuery and searchResults too. - my ( $query, $simple_query, $query_cgi, - $query_desc, $limit, $limit_cgi, $limit_desc, - $query_type ); - ( $error, $query, $simple_query, $query_cgi, - $query_desc, $limit, $limit_cgi, $limit_desc, - $query_type ) = buildQuery([], [ 'salud' ], [], [], [], 0, 'en'); - like($query, qr/kw\W.*salud/, "Built CCL keyword query"); + my ( + $query, $simple_query, $query_cgi, + $query_desc, $limit, $limit_cgi, $limit_desc, + $query_type + ); + ( + $error, $query, $simple_query, $query_cgi, + $query_desc, $limit, $limit_cgi, $limit_desc, + $query_type + ) = buildQuery( [], ['salud'], [], [], [], 0, 'en' ); + like( $query, qr/kw\W.*salud/, "Built CCL keyword query" ); - ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0); - is($results_hashref->{biblioserver}->{hits}, 19, "getRecords generated keyword search for 'salud' matched right number of records"); + ( $error, $results_hashref, $facets_loop ) = + getRecords( $query, $simple_query, [], ['biblioserver'], 20, 0, \%branches, \%itemtypes, $query_type, 0 ); + is( + $results_hashref->{biblioserver}->{hits}, 19, + "getRecords generated keyword search for 'salud' matched right number of records" + ); - my @newresults = searchResults({'interface' => 'opac'}, $query_desc, $results_hashref->{'biblioserver'}->{'hits'}, 18, 0, 0, - $results_hashref->{'biblioserver'}->{"RECORDS"}); - is(scalar @newresults,18, "searchResults returns requested number of hits"); + my @newresults = searchResults( + { 'interface' => 'opac' }, $query_desc, $results_hashref->{'biblioserver'}->{'hits'}, 18, 0, 0, + $results_hashref->{'biblioserver'}->{"RECORDS"} + ); + is( scalar @newresults, 18, "searchResults returns requested number of hits" ); - ( $error, $query, $simple_query, $query_cgi, - $query_desc, $limit, $limit_cgi, $limit_desc, - $query_type ) = buildQuery([ 'AND' ], [ 'salud', 'higiene' ], [], [], [], 0, 'en'); - like($query, qr/kw\W.*salud\W.*AND.*kw\W.*higiene/, "Built composed explicit-and CCL keyword query"); + ( + $error, $query, $simple_query, $query_cgi, + $query_desc, $limit, $limit_cgi, $limit_desc, + $query_type + ) = buildQuery( ['AND'], [ 'salud', 'higiene' ], [], [], [], 0, 'en' ); + like( $query, qr/kw\W.*salud\W.*AND.*kw\W.*higiene/, "Built composed explicit-and CCL keyword query" ); - ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0); - is($results_hashref->{biblioserver}->{hits}, 3, "getRecords generated composed keyword search for 'salud' explicit-and 'higiene' matched right number of records"); + ( $error, $results_hashref, $facets_loop ) = + getRecords( $query, $simple_query, [], ['biblioserver'], 20, 0, \%branches, \%itemtypes, $query_type, 0 ); + is( + $results_hashref->{biblioserver}->{hits}, 3, + "getRecords generated composed keyword search for 'salud' explicit-and 'higiene' matched right number of records" + ); - ( $error, $query, $simple_query, $query_cgi, - $query_desc, $limit, $limit_cgi, $limit_desc, - $query_type ) = buildQuery([ 'OR' ], [ 'salud', 'higiene' ], [], [], [], 0, 'en'); - like($query, qr/kw\W.*salud\W.*OR.*kw\W.*higiene/, "Built composed explicit-or CCL keyword query"); + ( + $error, $query, $simple_query, $query_cgi, + $query_desc, $limit, $limit_cgi, $limit_desc, + $query_type + ) = buildQuery( ['OR'], [ 'salud', 'higiene' ], [], [], [], 0, 'en' ); + like( $query, qr/kw\W.*salud\W.*OR.*kw\W.*higiene/, "Built composed explicit-or CCL keyword query" ); - ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0); - is($results_hashref->{biblioserver}->{hits}, 20, "getRecords generated composed keyword search for 'salud' explicit-or 'higiene' matched right number of records"); + ( $error, $results_hashref, $facets_loop ) = + getRecords( $query, $simple_query, [], ['biblioserver'], 20, 0, \%branches, \%itemtypes, $query_type, 0 ); + is( + $results_hashref->{biblioserver}->{hits}, 20, + "getRecords generated composed keyword search for 'salud' explicit-or 'higiene' matched right number of records" + ); - ( $error, $query, $simple_query, $query_cgi, - $query_desc, $limit, $limit_cgi, $limit_desc, - $query_type ) = buildQuery([], [ 'salud', 'higiene' ], [], [], [], 0, 'en'); - like($query, qr/kw\W.*salud\W.*AND.*kw\W.*higiene/, "Built composed implicit-and CCL keyword query"); + ( + $error, $query, $simple_query, $query_cgi, + $query_desc, $limit, $limit_cgi, $limit_desc, + $query_type + ) = buildQuery( [], [ 'salud', 'higiene' ], [], [], [], 0, 'en' ); + like( $query, qr/kw\W.*salud\W.*AND.*kw\W.*higiene/, "Built composed implicit-and CCL keyword query" ); - ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0); - is($results_hashref->{biblioserver}->{hits}, 3, "getRecords generated composed keyword search for 'salud' implicit-and 'higiene' matched right number of records"); + ( $error, $results_hashref, $facets_loop ) = + getRecords( $query, $simple_query, [], ['biblioserver'], 20, 0, \%branches, \%itemtypes, $query_type, 0 ); + is( + $results_hashref->{biblioserver}->{hits}, 3, + "getRecords generated composed keyword search for 'salud' implicit-and 'higiene' matched right number of records" + ); - ( $error, $query, $simple_query, $query_cgi, - $query_desc, $limit, $limit_cgi, $limit_desc, - $query_type ) = buildQuery([], [ 'salud' ], [ 'kw' ], [ 'su-to:Laboratorios' ], [], 0, 'en'); - like($query, qr/kw\W.*salud\W*and\W*su-to\W.*Laboratorios/, "Faceted query generated correctly"); - unlike($query_desc, qr/Laboratorios/, "Facets not included in query description"); + ( + $error, $query, $simple_query, $query_cgi, + $query_desc, $limit, $limit_cgi, $limit_desc, + $query_type + ) = buildQuery( [], ['salud'], ['kw'], ['su-to:Laboratorios'], [], 0, 'en' ); + like( $query, qr/kw\W.*salud\W*and\W*su-to\W.*Laboratorios/, "Faceted query generated correctly" ); + unlike( $query_desc, qr/Laboratorios/, "Facets not included in query description" ); - ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0); - is($results_hashref->{biblioserver}->{hits}, 2, "getRecords generated faceted search matched right number of records"); + ( $error, $results_hashref, $facets_loop ) = + getRecords( $query, $simple_query, [], ['biblioserver'], 20, 0, \%branches, \%itemtypes, $query_type, 0 ); + is( + $results_hashref->{biblioserver}->{hits}, 2, + "getRecords generated faceted search matched right number of records" + ); + ( + $error, $query, $simple_query, $query_cgi, + $query_desc, $limit, $limit_cgi, $limit_desc, + $query_type + ) = buildQuery( [], [''], ['kw'], [ 'mc-itype:MP', 'mc-itype:MU' ], [], 0, 'en' ); - ( $error, $query, $simple_query, $query_cgi, - $query_desc, $limit, $limit_cgi, $limit_desc, - $query_type ) = buildQuery([], [ '' ], [ 'kw' ], [ 'mc-itype:MP', 'mc-itype:MU' ], [], 0, 'en'); + ( $error, $results_hashref, $facets_loop ) = + getRecords( $query, $simple_query, [], ['biblioserver'], 20, 0, \%branches, \%itemtypes, $query_type, 0 ); + is( + $results_hashref->{biblioserver}->{hits}, 2, + "getRecords generated mc-faceted search matched right number of records" + ); - ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0); - is($results_hashref->{biblioserver}->{hits}, 2, "getRecords generated mc-faceted search matched right number of records"); + ( + $error, $query, $simple_query, $query_cgi, + $query_desc, $limit, $limit_cgi, $limit_desc, + $query_type + ) = buildQuery( [], [''], ['kw'], [ 'mc-loc:GEN', 'branch:FFL' ], [], 0, 'en' ); + ( $error, $results_hashref, $facets_loop ) = + getRecords( $query, $simple_query, [], ['biblioserver'], 20, 0, \%branches, \%itemtypes, $query_type, 0 ); + is( + $results_hashref->{biblioserver}->{hits}, 2, + "getRecords generated multi-faceted search matched right number of records" + ); - ( $error, $query, $simple_query, $query_cgi, - $query_desc, $limit, $limit_cgi, $limit_desc, - $query_type ) = buildQuery([], [ '' ], [ 'kw' ], [ 'mc-loc:GEN', 'branch:FFL' ], [], 0, 'en'); + ( + $error, $query, $simple_query, $query_cgi, + $query_desc, $limit, $limit_cgi, $limit_desc, + $query_type + ) = buildQuery( [], ['NEKLS'], ['Code-institution'], [], [], 0, 'en' ); + ( $error, $results_hashref, $facets_loop ) = + getRecords( $query, $simple_query, [], ['biblioserver'], 20, 0, \%branches, \%itemtypes, $query_type, 0 ); + is( + $results_hashref->{biblioserver}->{hits}, 12, + 'search using index whose name contains "ns" returns expected results (bug 10271)' + ); - ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0); - is($results_hashref->{biblioserver}->{hits}, 2, "getRecords generated multi-faceted search matched right number of records"); + ( + $error, $query, $simple_query, $query_cgi, + $query_desc, $limit, $limit_cgi, $limit_desc, + $query_type + ) = buildQuery( [], [''], ['kw'], ['available'], [], 0, 'en' ); - ( $error, $query, $simple_query, $query_cgi, - $query_desc, $limit, $limit_cgi, $limit_desc, - $query_type ) = buildQuery([], [ 'NEKLS' ], [ 'Code-institution' ], [], [], 0, 'en'); - ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0); - is($results_hashref->{biblioserver}->{hits}, 12, - 'search using index whose name contains "ns" returns expected results (bug 10271)'); - - ( $error, $query, $simple_query, $query_cgi, - $query_desc, $limit, $limit_cgi, $limit_desc, - $query_type ) = buildQuery([], [ '' ], [ 'kw' ], [ 'available' ], [], 0, 'en'); - - ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0); - is($results_hashref->{biblioserver}->{hits}, 2, "getRecords generated availability-limited search matched right number of records"); + ( $error, $results_hashref, $facets_loop ) = + getRecords( $query, $simple_query, [], ['biblioserver'], 20, 0, \%branches, \%itemtypes, $query_type, 0 ); + is( + $results_hashref->{biblioserver}->{hits}, 2, + "getRecords generated availability-limited search matched right number of records" + ); { my $mock_items = Test::MockModule->new('Koha::Items'); $mock_items->mock( 'count', 1 ); - @newresults = searchResults({'interface'=>'opac'}, $query_desc, $results_hashref->{'biblioserver'}->{'hits'}, 17, 0, 0, - $results_hashref->{'biblioserver'}->{"RECORDS"}); + @newresults = searchResults( + { 'interface' => 'opac' }, $query_desc, $results_hashref->{'biblioserver'}->{'hits'}, 17, 0, 0, + $results_hashref->{'biblioserver'}->{"RECORDS"} + ); my $allavailable = 'true'; foreach my $result (@newresults) { $allavailable = 'false' unless $result->{availablecount} > 0; } - is ($allavailable, 'true', 'All records have at least one item available'); + is( $allavailable, 'true', 'All records have at least one item available' ); } my $mocked_xslt = Test::MockModule->new('Koha::XSLT::Base'); - $mocked_xslt->mock( 'transform', sub { - my ($self, $xml) = @_; - return $xml; - }); + $mocked_xslt->mock( + 'transform', + sub { + my ( $self, $xml ) = @_; + return $xml; + } + ); - @newresults = searchResults({'interface'=>'opac'}, $query_desc, $results_hashref->{'biblioserver'}->{'hits'}, 17, 0, 0, - $results_hashref->{'biblioserver'}->{"RECORDS"}, { anonymous_session => 1 }); + @newresults = searchResults( + { 'interface' => 'opac' }, $query_desc, $results_hashref->{'biblioserver'}->{'hits'}, 17, 0, 0, + $results_hashref->{'biblioserver'}->{"RECORDS"}, { anonymous_session => 1 } + ); - like( $newresults[0]->{XSLTResultsRecord}, qr/<variable name="anonymous_session">1<\/variable>/, "Variable injected correctly" ); + like( + $newresults[0]->{XSLTResultsRecord}, qr/<variable name="anonymous_session">1<\/variable>/, + "Variable injected correctly" + ); my $biblio_id = $newresults[0]->{biblionumber}; - my $fw = C4::Biblio::GetFrameworkCode($biblio_id) // ''; + my $fw = C4::Biblio::GetFrameworkCode($biblio_id) // ''; my $dbh = C4::Context->dbh; + # FIXME This change is revert in END # Hide subfield 'p' in OPAC - $dbh->do(qq{ + $dbh->do( + qq{ UPDATE marc_subfield_structure SET hidden=4 WHERE frameworkcode='$fw' AND tagfield='952' AND tagsubfield='p'; - }); + } + ); # Hide subfield 'y' in Staff - $dbh->do(qq{ + $dbh->do( + qq{ UPDATE marc_subfield_structure SET hidden=-7 WHERE frameworkcode='$fw' AND tagfield='952' AND tagsubfield='y'; - }); + } + ); Koha::Caches->get_instance->flush_all; @@ -541,7 +675,10 @@ ok(MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[0],' $results_hashref->{'biblioserver'}->{"RECORDS"} ); - unlike( $newresults[0]->{XSLTResultsRecord}, qr/<subfield code="p">TEST11111<\/subfield>/, '952\$p hidden in OPAC' ); + unlike( + $newresults[0]->{XSLTResultsRecord}, qr/<subfield code="p">TEST11111<\/subfield>/, + '952\$p hidden in OPAC' + ); @newresults = searchResults( { 'interface' => 'intranet' }, @@ -553,236 +690,369 @@ ok(MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[0],' $results_hashref->{'biblioserver'}->{"RECORDS"} ); - unlike( $newresults[0]->{XSLTResultsRecord}, qr/<subfield code="y">Books<\/subfield>/, '952\$y hidden on staff interface' ); + unlike( + $newresults[0]->{XSLTResultsRecord}, qr/<subfield code="y">Books<\/subfield>/, + '952\$y hidden on staff interface' + ); - ( $error, $query, $simple_query, $query_cgi, - $query_desc, $limit, $limit_cgi, $limit_desc, - $query_type ) = buildQuery([], [ 'pqf=@attr 1=_ALLRECORDS @attr 2=103 ""' ], [], [], [], 0, 'en'); + ( + $error, $query, $simple_query, $query_cgi, + $query_desc, $limit, $limit_cgi, $limit_desc, + $query_type + ) = buildQuery( [], ['pqf=@attr 1=_ALLRECORDS @attr 2=103 ""'], [], [], [], 0, 'en' ); - ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0); - is($results_hashref->{biblioserver}->{hits}, 180, "getRecords on _ALLRECORDS PQF returned all records"); + ( $error, $results_hashref, $facets_loop ) = + getRecords( $query, $simple_query, [], ['biblioserver'], 20, 0, \%branches, \%itemtypes, $query_type, 0 ); + is( $results_hashref->{biblioserver}->{hits}, 180, "getRecords on _ALLRECORDS PQF returned all records" ); - ( $error, $query, $simple_query, $query_cgi, - $query_desc, $limit, $limit_cgi, $limit_desc, - $query_type ) = buildQuery([], [ 'pqf=@attr 1=1016 "Lessig"' ], [], [], [], 0, 'en'); + ( + $error, $query, $simple_query, $query_cgi, + $query_desc, $limit, $limit_cgi, $limit_desc, + $query_type + ) = buildQuery( [], ['pqf=@attr 1=1016 "Lessig"'], [], [], [], 0, 'en' ); - ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0); - is($results_hashref->{biblioserver}->{hits}, 4, "getRecords PQF author search for Lessig returned proper number of matches"); + ( $error, $results_hashref, $facets_loop ) = + getRecords( $query, $simple_query, [], ['biblioserver'], 20, 0, \%branches, \%itemtypes, $query_type, 0 ); + is( + $results_hashref->{biblioserver}->{hits}, 4, + "getRecords PQF author search for Lessig returned proper number of matches" + ); - ( $error, $query, $simple_query, $query_cgi, - $query_desc, $limit, $limit_cgi, $limit_desc, - $query_type ) = buildQuery([], [ 'ccl=au:Lessig' ], [], [], [], 0, 'en'); + ( + $error, $query, $simple_query, $query_cgi, + $query_desc, $limit, $limit_cgi, $limit_desc, + $query_type + ) = buildQuery( [], ['ccl=au:Lessig'], [], [], [], 0, 'en' ); - ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0); - is($results_hashref->{biblioserver}->{hits}, 4, "getRecords CCL author search for Lessig returned proper number of matches"); + ( $error, $results_hashref, $facets_loop ) = + getRecords( $query, $simple_query, [], ['biblioserver'], 20, 0, \%branches, \%itemtypes, $query_type, 0 ); + is( + $results_hashref->{biblioserver}->{hits}, 4, + "getRecords CCL author search for Lessig returned proper number of matches" + ); - ( $error, $query, $simple_query, $query_cgi, - $query_desc, $limit, $limit_cgi, $limit_desc, - $query_type ) = buildQuery([], [ 'cql=dc.author any lessig' ], [], [], [], 0, 'en'); + ( + $error, $query, $simple_query, $query_cgi, + $query_desc, $limit, $limit_cgi, $limit_desc, + $query_type + ) = buildQuery( [], ['cql=dc.author any lessig'], [], [], [], 0, 'en' ); - ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0); - is($results_hashref->{biblioserver}->{hits}, 4, "getRecords CQL author search for Lessig returned proper number of matches"); + ( $error, $results_hashref, $facets_loop ) = + getRecords( $query, $simple_query, [], ['biblioserver'], 20, 0, \%branches, \%itemtypes, $query_type, 0 ); + is( + $results_hashref->{biblioserver}->{hits}, 4, + "getRecords CQL author search for Lessig returned proper number of matches" + ); - $QueryStemming = $QueryAutoTruncate = $QueryFuzzy = 0; + $QueryStemming = $QueryAutoTruncate = $QueryFuzzy = 0; $QueryWeightFields = 1; - ( $error, $query, $simple_query, $query_cgi, - $query_desc, $limit, $limit_cgi, $limit_desc, - $query_type ) = buildQuery([], [ 'salud' ], [ 'kw' ], [], [], 0, 'en'); + ( + $error, $query, $simple_query, $query_cgi, + $query_desc, $limit, $limit_cgi, $limit_desc, + $query_type + ) = buildQuery( [], ['salud'], ['kw'], [], [], 0, 'en' ); - ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0); - is($results_hashref->{biblioserver}->{hits}, 19, "Weighted query returned correct number of results"); - is(MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[0],'UTF-8')->title_proper(), 'Salud y seguridad de los trabajadores del sector salud: manual para gerentes y administradores^ies', "Weighted query returns best match first"); + ( $error, $results_hashref, $facets_loop ) = + getRecords( $query, $simple_query, [], ['biblioserver'], 20, 0, \%branches, \%itemtypes, $query_type, 0 ); + is( $results_hashref->{biblioserver}->{hits}, 19, "Weighted query returned correct number of results" ); + is( + MARC::Record::new_from_xml( $results_hashref->{biblioserver}->{RECORDS}->[0], 'UTF-8' )->title_proper(), + 'Salud y seguridad de los trabajadores del sector salud: manual para gerentes y administradores^ies', + "Weighted query returns best match first" + ); - $QueryStemming = $QueryWeightFields = $QueryFuzzy = 0; + $QueryStemming = $QueryWeightFields = $QueryFuzzy = 0; $QueryAutoTruncate = 1; - ( $error, $query, $simple_query, $query_cgi, - $query_desc, $limit, $limit_cgi, $limit_desc, - $query_type ) = buildQuery([], [ 'medic' ], [ 'kw' ], [], [], 0, 'en'); + ( + $error, $query, $simple_query, $query_cgi, + $query_desc, $limit, $limit_cgi, $limit_desc, + $query_type + ) = buildQuery( [], ['medic'], ['kw'], [], [], 0, 'en' ); - ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0); - is($results_hashref->{biblioserver}->{hits}, 5, "Search for 'medic' returns matches with automatic truncation on"); + ( $error, $results_hashref, $facets_loop ) = + getRecords( $query, $simple_query, [], ['biblioserver'], 20, 0, \%branches, \%itemtypes, $query_type, 0 ); + is( + $results_hashref->{biblioserver}->{hits}, 5, + "Search for 'medic' returns matches with automatic truncation on" + ); - ( $error, $query, $simple_query, $query_cgi, - $query_desc, $limit, $limit_cgi, $limit_desc, - $query_type ) = buildQuery([], [ 'medic*' ], [ 'kw' ], [], [], 0, 'en'); + ( + $error, $query, $simple_query, $query_cgi, + $query_desc, $limit, $limit_cgi, $limit_desc, + $query_type + ) = buildQuery( [], ['medic*'], ['kw'], [], [], 0, 'en' ); - ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0); - is($results_hashref->{biblioserver}->{hits}, 5, "Search for 'medic*' returns matches with automatic truncation on"); + ( $error, $results_hashref, $facets_loop ) = + getRecords( $query, $simple_query, [], ['biblioserver'], 20, 0, \%branches, \%itemtypes, $query_type, 0 ); + is( + $results_hashref->{biblioserver}->{hits}, 5, + "Search for 'medic*' returns matches with automatic truncation on" + ); - $QueryStemming = $QueryFuzzy = $QueryAutoTruncate = 0; + $QueryStemming = $QueryFuzzy = $QueryAutoTruncate = 0; $QueryWeightFields = 1; - ( $error, $query, $simple_query, $query_cgi, - $query_desc, $limit, $limit_cgi, $limit_desc, - $query_type ) = buildQuery([], [ 'web application' ], [ 'kw' ], [], [], 0, 'en'); - ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0); - is($results_hashref->{biblioserver}->{hits}, 1, "Search for 'web application' returns one hit with QueryWeightFields on"); + ( + $error, $query, $simple_query, $query_cgi, + $query_desc, $limit, $limit_cgi, $limit_desc, + $query_type + ) = buildQuery( [], ['web application'], ['kw'], [], [], 0, 'en' ); + ( $error, $results_hashref, $facets_loop ) = + getRecords( $query, $simple_query, [], ['biblioserver'], 20, 0, \%branches, \%itemtypes, $query_type, 0 ); + is( + $results_hashref->{biblioserver}->{hits}, 1, + "Search for 'web application' returns one hit with QueryWeightFields on" + ); - ( $error, $query, $simple_query, $query_cgi, - $query_desc, $limit, $limit_cgi, $limit_desc, - $query_type ) = buildQuery([], [ 'web "application' ], [ 'kw' ], [], [], 0, 'en'); - ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0); - is($results_hashref->{biblioserver}->{hits}, 1, "Search for 'web \"application' returns one hit with QueryWeightFields on (bug 7518)"); + ( + $error, $query, $simple_query, $query_cgi, + $query_desc, $limit, $limit_cgi, $limit_desc, + $query_type + ) = buildQuery( [], ['web "application'], ['kw'], [], [], 0, 'en' ); + ( $error, $results_hashref, $facets_loop ) = + getRecords( $query, $simple_query, [], ['biblioserver'], 20, 0, \%branches, \%itemtypes, $query_type, 0 ); + is( + $results_hashref->{biblioserver}->{hits}, 1, + "Search for 'web \"application' returns one hit with QueryWeightFields on (bug 7518)" + ); $QueryStemming = $QueryWeightFields = $QueryFuzzy = $QueryAutoTruncate = 0; - ( $error, $query, $simple_query, $query_cgi, - $query_desc, $limit, $limit_cgi, $limit_desc, - $query_type ) = buildQuery([], [ 'medic' ], [ 'kw' ], [], [], 0, 'en'); + ( + $error, $query, $simple_query, $query_cgi, + $query_desc, $limit, $limit_cgi, $limit_desc, + $query_type + ) = buildQuery( [], ['medic'], ['kw'], [], [], 0, 'en' ); - ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0); - is($results_hashref->{biblioserver}->{hits}, undef, "Search for 'medic' returns no matches with automatic truncation off"); + ( $error, $results_hashref, $facets_loop ) = + getRecords( $query, $simple_query, [], ['biblioserver'], 20, 0, \%branches, \%itemtypes, $query_type, 0 ); + is( + $results_hashref->{biblioserver}->{hits}, undef, + "Search for 'medic' returns no matches with automatic truncation off" + ); - ( $error, $query, $simple_query, $query_cgi, - $query_desc, $limit, $limit_cgi, $limit_desc, - $query_type ) = buildQuery([], [ 'medic*' ], [ 'kw' ], [], [], 0, 'en'); + ( + $error, $query, $simple_query, $query_cgi, + $query_desc, $limit, $limit_cgi, $limit_desc, + $query_type + ) = buildQuery( [], ['medic*'], ['kw'], [], [], 0, 'en' ); - ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0); - is($results_hashref->{biblioserver}->{hits}, 5, "Search for 'medic*' returns matches with automatic truncation off"); + ( $error, $results_hashref, $facets_loop ) = + getRecords( $query, $simple_query, [], ['biblioserver'], 20, 0, \%branches, \%itemtypes, $query_type, 0 ); + is( + $results_hashref->{biblioserver}->{hits}, 5, + "Search for 'medic*' returns matches with automatic truncation off" + ); $QueryStemming = $QueryWeightFields = 1; - $QueryFuzzy = $QueryAutoTruncate = 0; - ( $error, $query, $simple_query, $query_cgi, - $query_desc, $limit, $limit_cgi, $limit_desc, - $query_type ) = buildQuery([], [ 'pressed' ], [ 'kw' ], [], [], 0, 'en'); + $QueryFuzzy = $QueryAutoTruncate = 0; + ( + $error, $query, $simple_query, $query_cgi, + $query_desc, $limit, $limit_cgi, $limit_desc, + $query_type + ) = buildQuery( [], ['pressed'], ['kw'], [], [], 0, 'en' ); - ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0); - is($results_hashref->{biblioserver}->{hits}, 7, "Search for 'pressed' returns matches when stemming (and query weighting) is on"); + ( $error, $results_hashref, $facets_loop ) = + getRecords( $query, $simple_query, [], ['biblioserver'], 20, 0, \%branches, \%itemtypes, $query_type, 0 ); + is( + $results_hashref->{biblioserver}->{hits}, 7, + "Search for 'pressed' returns matches when stemming (and query weighting) is on" + ); $QueryStemming = $QueryWeightFields = $QueryFuzzy = $QueryAutoTruncate = 0; - ( $error, $query, $simple_query, $query_cgi, - $query_desc, $limit, $limit_cgi, $limit_desc, - $query_type ) = buildQuery([], [ 'pressed' ], [ 'kw' ], [], [], 0, 'en'); + ( + $error, $query, $simple_query, $query_cgi, + $query_desc, $limit, $limit_cgi, $limit_desc, + $query_type + ) = buildQuery( [], ['pressed'], ['kw'], [], [], 0, 'en' ); - ($error, $results_hashref, $facets_loop) = getRecords($query,$simple_query,[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0); - is($results_hashref->{biblioserver}->{hits}, undef, "Search for 'pressed' returns no matches when stemming is off"); + ( $error, $results_hashref, $facets_loop ) = + getRecords( $query, $simple_query, [], ['biblioserver'], 20, 0, \%branches, \%itemtypes, $query_type, 0 ); + is( + $results_hashref->{biblioserver}->{hits}, undef, + "Search for 'pressed' returns no matches when stemming is off" + ); - ( $error, $query, $simple_query, $query_cgi, - $query_desc, $limit, $limit_cgi, $limit_desc, - $query_type ) = buildQuery([], [ 'ccl=an:42' ], [], ['available'], [], 0, 'en'); - is( $query, "an:42 and (( (allrecords,AlwaysMatches='') and (not-onloan-count,st-numeric >= 1) and (lost,st-numeric=0) ))", 'buildQuery should add the available part to the query if requested with ccl' ); + ( + $error, $query, $simple_query, $query_cgi, + $query_desc, $limit, $limit_cgi, $limit_desc, + $query_type + ) = buildQuery( [], ['ccl=an:42'], [], ['available'], [], 0, 'en' ); + is( + $query, + "an:42 and (( (allrecords,AlwaysMatches='') and (not-onloan-count,st-numeric >= 1) and (lost,st-numeric=0) ))", + 'buildQuery should add the available part to the query if requested with ccl' + ); is( $query_desc, 'an:42', 'buildQuery should remove the available part from the query' ); - ( $error, $query, $simple_query, $query_cgi, - $query_desc, $limit, $limit_cgi, $limit_desc, - $query_type ) = buildQuery([], [ 'ccl=an:42' ], [], ['branch:CPL'], [], 0, 'en'); - is( $query, "an:42 and (homebranch: CPL or holdingbranch: CPL)", 'buildQuery should expand the limit as necessary for ccl queries' ); + ( + $error, $query, $simple_query, $query_cgi, + $query_desc, $limit, $limit_cgi, $limit_desc, + $query_type + ) = buildQuery( [], ['ccl=an:42'], [], ['branch:CPL'], [], 0, 'en' ); + is( + $query, "an:42 and (homebranch: CPL or holdingbranch: CPL)", + 'buildQuery should expand the limit as necessary for ccl queries' + ); is( $query_desc, 'an:42', 'buildQuery should not add limit to limit desc for ccl queries' ); - ( $error, $query, $simple_query, $query_cgi, - $query_desc, $limit, $limit_cgi, $limit_desc, - $query_type ) = buildQuery([], [ 0 ], [ 'su,phr' ], [], [], 0, 'en'); - is($query, 'su,phr=(rk=(0)) ', 'buildQuery should keep 0 value in query'); - is($query_cgi, 'idx=su%2Cphr&q=0', 'buildQuery should keep 0 value in query_cgi'); - is($query_desc, 'su,phr: 0', 'buildQuery should keep 0 value in query_desc'); + ( + $error, $query, $simple_query, $query_cgi, + $query_desc, $limit, $limit_cgi, $limit_desc, + $query_type + ) = buildQuery( [], [0], ['su,phr'], [], [], 0, 'en' ); + is( $query, 'su,phr=(rk=(0)) ', 'buildQuery should keep 0 value in query' ); + is( $query_cgi, 'idx=su%2Cphr&q=0', 'buildQuery should keep 0 value in query_cgi' ); + is( $query_desc, 'su,phr: 0', 'buildQuery should keep 0 value in query_desc' ); # Bug 23086 - ( $error, $query, $simple_query, $query_cgi, - $query_desc, $limit, $limit_cgi, $limit_desc, - $query_type ) = buildQuery([], [], [], [ 'mc-ccode:NF(IC'], [], 0, 'en'); - like($query, qr/ccode="NF\(IC"/, "Limit quoted correctly"); + ( + $error, $query, $simple_query, $query_cgi, + $query_desc, $limit, $limit_cgi, $limit_desc, + $query_type + ) = buildQuery( [], [], [], ['mc-ccode:NF(IC'], [], 0, 'en' ); + like( $query, qr/ccode="NF\(IC"/, "Limit quoted correctly" ); # Let's see what happens when we pass bad data into these routines. # We have to catch warnings since we're not very good about returning errors. - warning_like { ( $error, $marcresults, $total_hits ) = SimpleSearch("@==ccl blah", 0, 9) } qr/CCL parsing error/, + warning_like { ( $error, $marcresults, $total_hits ) = SimpleSearch( "@==ccl blah", 0, 9 ) } qr/CCL parsing error/, "SimpleSearch warns about CCL parsing error with nonsense query"; - isnt($error, undef, "SimpleSearch returns an error when passed gibberish"); + isnt( $error, undef, "SimpleSearch returns an error when passed gibberish" ); - warning_like {( undef, $results_hashref, $facets_loop ) = - getRecords('kw:book', 'book', [], [ 'biblioserver' ], '19', 0, \%branches, \%itemtypes, 'nonsense', undef) } - qr/Unknown query_type/, "getRecords warns about unknown query type"; + warning_like { + ( undef, $results_hashref, $facets_loop ) = + getRecords( 'kw:book', 'book', [], ['biblioserver'], '19', 0, \%branches, \%itemtypes, 'nonsense', undef ) + } + qr/Unknown query_type/, "getRecords warns about unknown query type"; - warning_like {( undef, $results_hashref, $facets_loop ) = - getRecords('pqf=@attr 1=4 "title"', 'pqf=@attr 1=4 "title"', [], [ 'biblioserver' ], '19', 0, \%branches, \%itemtypes, '', undef) } - qr/WARNING: query problem/, "getRecords warns when query type is not specified for non-CCL query"; + warning_like { + ( undef, $results_hashref, $facets_loop ) = getRecords( + 'pqf=@attr 1=4 "title"', 'pqf=@attr 1=4 "title"', [], ['biblioserver'], '19', 0, \%branches, + \%itemtypes, '', undef + ) + } + qr/WARNING: query problem/, "getRecords warns when query type is not specified for non-CCL query"; # Let's just test a few other bits and bobs, just for fun - ($error, $results_hashref, $facets_loop) = getRecords("Godzina pąsowej róży","Godzina pąsowej róży",[ ], [ 'biblioserver' ],20,0,\%branches,\%itemtypes,$query_type,0); - @newresults = searchResults({'interface'=>'intranet'}, $query_desc, $results_hashref->{'biblioserver'}->{'hits'}, 17, 0, 0, - $results_hashref->{'biblioserver'}->{"RECORDS"}); - is(scalar(@{$newresults[0]->{'ALTERNATEHOLDINGS'}}), 1, 'Alternate holdings filled in correctly'); + ( $error, $results_hashref, $facets_loop ) = getRecords( + "Godzina pąsowej róży", "Godzina pąsowej róży", [], ['biblioserver'], 20, 0, \%branches, + \%itemtypes, $query_type, 0 + ); + @newresults = searchResults( + { 'interface' => 'intranet' }, $query_desc, $results_hashref->{'biblioserver'}->{'hits'}, 17, 0, 0, + $results_hashref->{'biblioserver'}->{"RECORDS"} + ); + is( scalar( @{ $newresults[0]->{'ALTERNATEHOLDINGS'} } ), 1, 'Alternate holdings filled in correctly' ); ## Regression test for bug 10684 - ( undef, $results_hashref, $facets_loop ) = - getRecords('ti:punctuation', 'punctuation', [], [ 'biblioserver' ], '19', 0, \%branches, \%itemtypes, 'ccl', undef); - is($results_hashref->{biblioserver}->{hits}, 1, "search for ti:punctuation returned expected number of records"); - warning_like { @newresults = searchResults({'intranet' => 'intranet'}, $query_desc, - $results_hashref->{'biblioserver'}->{'hits'}, 20, 0, 0, - $results_hashref->{'biblioserver'}->{"RECORDS"}) } - qr/^ERROR DECODING RECORD - Tag "50%" is not a valid tag/, - "Warning is raised correctly for invalid tags in MARC::Record"; - is(scalar(@newresults), 0, 'a record that cannot be parsed by MARC::Record is simply skipped (bug 10684)'); + ( undef, $results_hashref, $facets_loop ) = getRecords( + 'ti:punctuation', 'punctuation', [], ['biblioserver'], '19', 0, \%branches, \%itemtypes, 'ccl', + undef + ); + is( $results_hashref->{biblioserver}->{hits}, 1, "search for ti:punctuation returned expected number of records" ); + warning_like { + @newresults = searchResults( + { 'intranet' => 'intranet' }, $query_desc, + $results_hashref->{'biblioserver'}->{'hits'}, 20, 0, 0, + $results_hashref->{'biblioserver'}->{"RECORDS"} + ) + } + qr/^ERROR DECODING RECORD - Tag "50%" is not a valid tag/, + "Warning is raised correctly for invalid tags in MARC::Record"; + is( scalar(@newresults), 0, 'a record that cannot be parsed by MARC::Record is simply skipped (bug 10684)' ); - my ($auths, $count) = SearchAuthorities( - ['mainentry'], ['and'], [''], ['starts'], + my ( $auths, $count ) = SearchAuthorities( + ['mainentry'], ['and'], [''], ['starts'], ['shakespeare'], 0, 10, '', '', 1 ); - is($count, 1, 'MARC21 authorities: one hit on mainentry starts with "shakespeare"'); - ($auths, $count) = SearchAuthorities( - ['mainentry'], ['and'], [''], ['starts'], + is( $count, 1, 'MARC21 authorities: one hit on mainentry starts with "shakespeare"' ); + ( $auths, $count ) = SearchAuthorities( + ['mainentry'], ['and'], [''], ['starts'], ['shakespeare'], 0, 10, '', 'HeadingAsc', 1 ); - is($count, 1, 'MARC21 authorities: one hit on mainentry starts with "shakespeare" sorted by heading ascending'); - ($auths, $count) = SearchAuthorities( - ['mainentry'], ['and'], [''], ['starts'], + is( $count, 1, 'MARC21 authorities: one hit on mainentry starts with "shakespeare" sorted by heading ascending' ); + ( $auths, $count ) = SearchAuthorities( + ['mainentry'], ['and'], [''], ['starts'], ['shakespeare'], 0, 10, '', 'HeadingDsc', 1 ); - is($count, 1, 'MARC21 authorities: one hit on mainentry starts with "shakespeare" sorted by heading descending'); - ($auths, $count) = SearchAuthorities( - ['match'], ['and'], [''], ['contains'], + is( $count, 1, 'MARC21 authorities: one hit on mainentry starts with "shakespeare" sorted by heading descending' ); + ( $auths, $count ) = SearchAuthorities( + ['match'], ['and'], [''], ['contains'], ['沙士北亞威廉姆'], 0, 10, '', '', 1 ); - is($count, 1, 'MARC21 authorities: one hit on match contains "沙士北亞威廉姆"'); - ($auths, $count) = SearchAuthorities( + is( $count, 1, 'MARC21 authorities: one hit on match contains "沙士北亞威廉姆"' ); + ( $auths, $count ) = SearchAuthorities( ['LC-card-number'], ['and'], [''], ['contains'], ['99282477'], 0, 10, '', '', 1 ); - is($count, 1, 'MARC21 authorities: one hit on LC-card-number contains "99282477"'); - ($auths, $count) = SearchAuthorities( + is( $count, 1, 'MARC21 authorities: one hit on LC-card-number contains "99282477"' ); + ( $auths, $count ) = SearchAuthorities( ['all'], ['and'], [''], ['contains'], ['professional wrestler'], 0, 10, '', '', 1 ); - is($count, 1, 'MARC21 authorities: one hit on "all" (entire record) contains "professional wrestler"'); + is( $count, 1, 'MARC21 authorities: one hit on "all" (entire record) contains "professional wrestler"' ); #NOTE: the 2nd parameter is unused in SearchAuthorities... - ($auths, $count) = SearchAuthorities( - ['Any','Any'], [''], [''], ['contains'], - ['professional wrestler','shakespeare'], 0, 10, '', '', 1 + ( $auths, $count ) = SearchAuthorities( + [ 'Any', 'Any' ], [''], [''], ['contains'], + [ 'professional wrestler', 'shakespeare' ], 0, 10, '', '', 1 ); - is($count, 2, 'MARC21 authorities: multiple values create operands implicitly joined by OR'); + is( $count, 2, 'MARC21 authorities: multiple values create operands implicitly joined by OR' ); # retrieve records that are larger than the MARC limit of 99,999 octets - ( undef, $results_hashref, $facets_loop ) = - getRecords('ti:marc the large record', '', [], [ 'biblioserver' ], '20', 0, \%branches, \%itemtypes, 'ccl', undef); - is($results_hashref->{biblioserver}->{hits}, 1, "Can do a search that retrieves an over-large bib record (bug 11096)"); + ( undef, $results_hashref, $facets_loop ) = getRecords( + 'ti:marc the large record', '', [], ['biblioserver'], '20', 0, \%branches, \%itemtypes, 'ccl', + undef + ); + is( + $results_hashref->{biblioserver}->{hits}, 1, + "Can do a search that retrieves an over-large bib record (bug 11096)" + ); { my $mock_items = Test::MockModule->new('Koha::Items'); $mock_items->mock( 'count', 1 ); - @newresults = searchResults({'interface' =>'opac'}, $query_desc, $results_hashref->{'biblioserver'}->{'hits'}, 10, 0, 0, - $results_hashref->{'biblioserver'}->{"RECORDS"}); - is($newresults[0]->{title}, 'Marc the Large Record', 'Able to render the title for over-large bib record (bug 11096)'); - is($newresults[0]->{biblionumber}, '300', 'Over-large bib record has the correct biblionumber (bug 11096)'); - like($newresults[0]->{notes}, qr/This is large note #550/, 'Able to render the notes field for over-large bib record (bug 11096)'); + @newresults = searchResults( + { 'interface' => 'opac' }, $query_desc, $results_hashref->{'biblioserver'}->{'hits'}, 10, 0, 0, + $results_hashref->{'biblioserver'}->{"RECORDS"} + ); + is( + $newresults[0]->{title}, 'Marc the Large Record', + 'Able to render the title for over-large bib record (bug 11096)' + ); + is( $newresults[0]->{biblionumber}, '300', 'Over-large bib record has the correct biblionumber (bug 11096)' ); + like( + $newresults[0]->{notes}, qr/This is large note #550/, + 'Able to render the notes field for over-large bib record (bug 11096)' + ); } # notforloancount should be returned as part of searchResults output - ok( defined $newresults[0]->{notforloancount}, - '\'notforloancount\' defined in searchResults output (Bug 12419)'); - is( $newresults[0]->{notforloancount}, 2, - '\'notforloancount\' == 2 (Bug 12419)'); + ok( + defined $newresults[0]->{notforloancount}, + '\'notforloancount\' defined in searchResults output (Bug 12419)' + ); + is( + $newresults[0]->{notforloancount}, 2, + '\'notforloancount\' == 2 (Bug 12419)' + ); # verify that we don't attempt to sort if no results were returned # because of a query error - warning_like {( undef, $results_hashref, $facets_loop ) = - getRecords('ccl=( AND )', '', ['title_az'], [ 'biblioserver' ], '20', 0, \%branches, \%itemtypes, 'ccl', undef) - } qr/WARNING: query problem with/, 'got warning instead of crash when attempting to run invalid query (bug 9578)'; - + warning_like { + ( undef, $results_hashref, $facets_loop ) = getRecords( + 'ccl=( AND )', '', ['title_az'], ['biblioserver'], '20', 0, \%branches, \%itemtypes, 'ccl', + undef + ) + } + qr/WARNING: query problem with/, 'got warning instead of crash when attempting to run invalid query (bug 9578)'; + # Test facet calculation my $facets_counter = {}; my $facets = C4::Koha::getFacets(); + # Create a record with a 100$z field - my $marc_record = MARC::Record->new; + my $marc_record = MARC::Record->new; $marc_record->add_fields( [ '001', '1234' ], [ '100', ' ', ' ', a => 'Cohen Arazi, Tomas' ], @@ -790,9 +1060,11 @@ ok(MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[0],' [ '245', ' ', ' ', a => 'First try' ] ); C4::Search::_get_facets_data_from_record( $marc_record, $facets, $facets_counter ); - is_deeply( { au => { 'Cohen Arazi, Tomas' => 1 } }, $facets_counter, - "_get_facets_data_from_record doesn't count 100\$z (Bug 12788)"); - $marc_record = MARC::Record->new; + is_deeply( + { au => { 'Cohen Arazi, Tomas' => 1 } }, $facets_counter, + "_get_facets_data_from_record doesn't count 100\$z (Bug 12788)" + ); + $marc_record = MARC::Record->new; $marc_record->add_fields( [ '001', '1234' ], [ '100', ' ', ' ', a => 'Cohen Arazi, Tomas' ], @@ -800,26 +1072,30 @@ ok(MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[0],' [ '245', ' ', ' ', a => 'Second try' ] ); C4::Search::_get_facets_data_from_record( $marc_record, $facets, $facets_counter ); - is_deeply( { au => { 'Cohen Arazi, Tomas' => 2 } }, $facets_counter, - "_get_facets_data_from_record correctly counts author facet twice"); + is_deeply( + { au => { 'Cohen Arazi, Tomas' => 2 } }, $facets_counter, + "_get_facets_data_from_record correctly counts author facet twice" + ); # Test _get_facets_info - my $facets_info = C4::Search::_get_facets_info( $facets ); + my $facets_info = C4::Search::_get_facets_info($facets); my $expected_facets_info_marc21 = { - 'au' => { 'label_value' => "Authors" }, - 'ccode' => { 'label_value' => "Collections" }, + 'au' => { 'label_value' => "Authors" }, + 'ccode' => { 'label_value' => "Collections" }, 'holdingbranch' => { 'label_value' => "Holding libraries" }, - 'itype' => { 'label_value' => "Item types" }, - 'location' => { 'label_value' => "Location" }, - 'se' => { 'label_value' => "Series" }, - 'su-geo' => { 'label_value' => "Places" }, - 'su-to' => { 'label_value' => "Topics" }, - 'su-ut' => { 'label_value' => "Titles" } + 'itype' => { 'label_value' => "Item types" }, + 'location' => { 'label_value' => "Location" }, + 'se' => { 'label_value' => "Series" }, + 'su-geo' => { 'label_value' => "Places" }, + 'su-to' => { 'label_value' => "Topics" }, + 'su-ut' => { 'label_value' => "Titles" } }; delete $expected_facets_info_marc21->{holdingbranch} if Koha::Libraries->count == 1; - is_deeply( $facets_info, $expected_facets_info_marc21, - "_get_facets_info returns the correct data"); + is_deeply( + $facets_info, $expected_facets_info_marc21, + "_get_facets_info returns the correct data" + ); $mock_zebra->cleanup; } @@ -827,29 +1103,32 @@ ok(MARC::Record::new_from_xml($results_hashref->{biblioserver}->{RECORDS}->[0],' sub run_unimarc_search_tests { $marcflavour = 'UNIMARC'; - my $mock_zebra = t::lib::Mocks::Zebra->new({marcflavour => $marcflavour}); + my $mock_zebra = t::lib::Mocks::Zebra->new( { marcflavour => $marcflavour } ); push @cleanup, $mock_zebra; mock_GetMarcSubfieldStructure($marcflavour); - use_ok('C4::Search', qw( getIndexes FindDuplicate SimpleSearch getRecords buildQuery searchResults )); + use_ok( 'C4::Search', qw( getIndexes FindDuplicate SimpleSearch getRecords buildQuery searchResults ) ); # set search syspreferences to a known starting point - $QueryStemming = 0; + $QueryStemming = 0; $QueryAutoTruncate = 0; $QueryWeightFields = 0; - $QueryFuzzy = 0; + $QueryFuzzy = 0; my $sourcedir = dirname(__FILE__) . "/data"; $mock_zebra->load_records( sprintf( "%s/%s/zebraexport/biblio", $sourcedir, lc($marcflavour) ), - 'iso2709', 'biblios', 1 ); + 'iso2709', 'biblios', 1 + ); $mock_zebra->load_records( sprintf( "%s/%s/zebraexport/large_biblio", $sourcedir, lc($marcflavour) ), - 'marcxml', 'biblios', 0 + 'marcxml', + 'biblios', + 0 ); $mock_zebra->load_records( sprintf( "%s/%s/zebraexport/authority", $sourcedir, lc($marcflavour) ), @@ -857,67 +1136,70 @@ sub run_unimarc_search_tests { ); $mock_zebra->launch_zebra; - my ( $error, $marcresults, $total_hits ) = SimpleSearch("ti=Järnvägarnas efterfrågan och den svenska industrin", 0, 10); - is($total_hits, 1, 'UNIMARC title search'); - ( $error, $marcresults, $total_hits ) = SimpleSearch("ta=u", 0, 10); - is($total_hits, 1, 'UNIMARC target audience = u'); - ( $error, $marcresults, $total_hits ) = SimpleSearch("ta=k", 0, 10); - is($total_hits, 4, 'UNIMARC target audience = k'); - ( $error, $marcresults, $total_hits ) = SimpleSearch("ta=m", 0, 10); - is($total_hits, 3, 'UNIMARC target audience = m'); - ( $error, $marcresults, $total_hits ) = SimpleSearch("item=EXCLU DU PRET", 0, 10); - is($total_hits, 1, 'UNIMARC generic item index (bug 10037)'); + my ( $error, $marcresults, $total_hits ) = + SimpleSearch( "ti=Järnvägarnas efterfrågan och den svenska industrin", 0, 10 ); + is( $total_hits, 1, 'UNIMARC title search' ); + ( $error, $marcresults, $total_hits ) = SimpleSearch( "ta=u", 0, 10 ); + is( $total_hits, 1, 'UNIMARC target audience = u' ); + ( $error, $marcresults, $total_hits ) = SimpleSearch( "ta=k", 0, 10 ); + is( $total_hits, 4, 'UNIMARC target audience = k' ); + ( $error, $marcresults, $total_hits ) = SimpleSearch( "ta=m", 0, 10 ); + is( $total_hits, 3, 'UNIMARC target audience = m' ); + ( $error, $marcresults, $total_hits ) = SimpleSearch( "item=EXCLU DU PRET", 0, 10 ); + is( $total_hits, 1, 'UNIMARC generic item index (bug 10037)' ); # authority records - use_ok('C4::AuthoritiesMarc', qw( SearchAuthorities )); + use_ok( 'C4::AuthoritiesMarc', qw( SearchAuthorities ) ); - my ($auths, $count) = SearchAuthorities( + my ( $auths, $count ) = SearchAuthorities( ['mainentry'], ['and'], [''], ['contains'], ['wil'], 0, 10, '', '', 1 ); - is($count, 11, 'UNIMARC authorities: hits on mainentry contains "wil"'); - ($auths, $count) = SearchAuthorities( + is( $count, 11, 'UNIMARC authorities: hits on mainentry contains "wil"' ); + ( $auths, $count ) = SearchAuthorities( ['match'], ['and'], [''], ['contains'], - ['wil'], 0, 10, '', '', 1 + ['wil'], 0, 10, '', '', 1 ); - is($count, 11, 'UNIMARC authorities: hits on match contains "wil"'); - ($auths, $count) = SearchAuthorities( + is( $count, 11, 'UNIMARC authorities: hits on match contains "wil"' ); + ( $auths, $count ) = SearchAuthorities( ['mainentry'], ['and'], [''], ['contains'], - ['michel'], 0, 20, '', '', 1 + ['michel'], 0, 20, '', '', 1 ); - is($count, 14, 'UNIMARC authorities: hits on mainentry contains "michel"'); - ($auths, $count) = SearchAuthorities( + is( $count, 14, 'UNIMARC authorities: hits on mainentry contains "michel"' ); + ( $auths, $count ) = SearchAuthorities( ['mainmainentry'], ['and'], [''], ['exact'], ['valley'], 0, 20, '', '', 1 ); - is($count, 1, 'UNIMARC authorities: hits on mainmainentry = "valley"'); - ($auths, $count) = SearchAuthorities( + is( $count, 1, 'UNIMARC authorities: hits on mainmainentry = "valley"' ); + ( $auths, $count ) = SearchAuthorities( ['mainmainentry'], ['and'], [''], ['exact'], ['vall'], 0, 20, '', '', 1 ); - is($count, 0, 'UNIMARC authorities: no hits on mainmainentry = "vall"'); - ($auths, $count) = SearchAuthorities( - ['Any'], ['and'], [''], ['starts'], + is( $count, 0, 'UNIMARC authorities: no hits on mainmainentry = "vall"' ); + ( $auths, $count ) = SearchAuthorities( + ['Any'], ['and'], [''], ['starts'], ['jean'], 0, 30, '', '', 1 ); - is($count, 24, 'UNIMARC authorities: hits on any starts with "jean"'); + is( $count, 24, 'UNIMARC authorities: hits on any starts with "jean"' ); # Test _get_facets_info - my $facets = C4::Koha::getFacets(); - my $facets_info = C4::Search::_get_facets_info( $facets ); + my $facets = C4::Koha::getFacets(); + my $facets_info = C4::Search::_get_facets_info($facets); my $expected_facets_info_unimarc = { - 'au' => { 'label_value' => "Authors" }, - 'ccode' => { 'label_value' => "Collections" }, + 'au' => { 'label_value' => "Authors" }, + 'ccode' => { 'label_value' => "Collections" }, 'holdingbranch' => { 'label_value' => "Holding libraries" }, - 'location' => { 'label_value' => "Location" }, - 'se' => { 'label_value' => "Series" }, - 'su-geo' => { 'label_value' => "Places" }, - 'su-to' => { 'label_value' => "Topics" } + 'location' => { 'label_value' => "Location" }, + 'se' => { 'label_value' => "Series" }, + 'su-geo' => { 'label_value' => "Places" }, + 'su-to' => { 'label_value' => "Topics" } }; delete $expected_facets_info_unimarc->{holdingbranch} if Koha::Libraries->count == 1; - is_deeply( $facets_info, $expected_facets_info_unimarc, - "_get_facets_info returns the correct data"); + is_deeply( + $facets_info, $expected_facets_info_unimarc, + "_get_facets_info returns the correct data" + ); $mock_zebra->cleanup; } @@ -932,59 +1214,60 @@ subtest 'UNIMARC + DOM' => sub { run_unimarc_search_tests(); }; - subtest 'FindDuplicate' => sub { plan tests => 8; Koha::Caches->get_instance('config')->flush_all; - t::lib::Mocks::mock_preference('marcflavour', 'MARC21' ); + t::lib::Mocks::mock_preference( 'marcflavour', 'MARC21' ); mock_GetMarcSubfieldStructure('MARC21'); my $z_searcher = Test::MockModule->new('C4::Search'); - $z_searcher->mock('SimpleSearch', sub { - warn shift @_; - return 1; - }); + $z_searcher->mock( + 'SimpleSearch', + sub { + warn shift @_; + return 1; + } + ); my $e_searcher = Test::MockModule->new('Koha::SearchEngine::Elasticsearch::Search'); - $e_searcher->mock('simple_search_compat', sub { - shift @_; - warn shift @_; - return 1; - }); + $e_searcher->mock( + 'simple_search_compat', + sub { + shift @_; + warn shift @_; + return 1; + } + ); my $record_1 = MARC::Record->new; - $record_1 ->add_fields( - [ '100', '0', '0', a => 'Morgenstern, Erin' ], - [ '245', '0', '0', a => 'The night circus /' ] + $record_1->add_fields( + [ '100', '0', '0', a => 'Morgenstern, Erin' ], + [ '245', '0', '0', a => 'The night circus /' ] ); my $record_2 = MARC::Record->new; - $record_2 ->add_fields( - [ '245', '0', '0', a => 'The book of nothing /' ] - ); + $record_2->add_fields( [ '245', '0', '0', a => 'The book of nothing /' ] ); my $record_3 = MARC::Record->new; - $record_3->add_fields( - [ '245', '0', '0', a => 'Frog and toad all year /' ] - ); + $record_3->add_fields( [ '245', '0', '0', a => 'Frog and toad all year /' ] ); my $record_4 = MARC::Record->new; - $record_4 ->add_fields( - [ '020', ' ', ' ', a => '9780307744432' ], - [ '020', ' ', ' ', a => '0307744434' ], - [ '100', '0', '0', a => 'Morgenstern, Erin' ], - [ '245', '0', '0', a => 'The night circus /' ] + $record_4->add_fields( + [ '020', ' ', ' ', a => '9780307744432' ], + [ '020', ' ', ' ', a => '0307744434' ], + [ '100', '0', '0', a => 'Morgenstern, Erin' ], + [ '245', '0', '0', a => 'The night circus /' ] ); - foreach my $engine ('Zebra','Elasticsearch'){ - t::lib::Mocks::mock_preference('searchEngine', $engine ); + foreach my $engine ( 'Zebra', 'Elasticsearch' ) { + t::lib::Mocks::mock_preference( 'searchEngine', $engine ); - warning_is { C4::Search::FindDuplicate($record_1);} - q/ti,ext:"The night circus \/" AND au,ext:"Morgenstern, Erin"/,"Term correctly formed and passed to $engine"; + warning_is { C4::Search::FindDuplicate($record_1); } + q/ti,ext:"The night circus \/" AND au,ext:"Morgenstern, Erin"/, "Term correctly formed and passed to $engine"; - warning_is { C4::Search::FindDuplicate($record_2);} - q/ti,ext:"The book of nothing \/"/,"Term correctly formed and passed to $engine"; + warning_is { C4::Search::FindDuplicate($record_2); } + q/ti,ext:"The book of nothing \/"/, "Term correctly formed and passed to $engine"; - warning_is { C4::Search::FindDuplicate($record_3);} - q/ti,ext:"Frog and toad all year \/"/,"Term correctly formed and passed to $engine"; + warning_is { C4::Search::FindDuplicate($record_3); } + q/ti,ext:"Frog and toad all year \/"/, "Term correctly formed and passed to $engine"; - warning_is { C4::Search::FindDuplicate($record_4);} - q/isbn:9780307744432 OR 0307744434/,"Term correctly formed and passed to $engine"; + warning_is { C4::Search::FindDuplicate($record_4); } + q/isbn:9780307744432 OR 0307744434/, "Term correctly formed and passed to $engine"; } }; @@ -996,13 +1279,16 @@ END { $_->cleanup for @cleanup; my $dbh = C4::Context->dbh; + # Restore visibility of subfields in OPAC - $dbh->do(q{ + $dbh->do( + q{ UPDATE marc_subfield_structure SET hidden=0 WHERE tagfield='952' AND ( tagsubfield IN ('p', 'y') ) - }); + } + ); Koha::Caches->get_instance->flush_all; -}; +} diff --git a/t/db_dependent/Search/History.t b/t/db_dependent/Search/History.t index 4c084e121a..860344ad05 100755 --- a/t/db_dependent/Search/History.t +++ b/t/db_dependent/Search/History.t @@ -28,206 +28,250 @@ my $dbh = C4::Context->dbh; t::lib::Mocks::mock_preference( 'SessionStorage', 'tmp' ); use_ok('Koha::DateUtils'); -use_ok('C4::Search::History', qw( add get delete get_from_session )); +use_ok( 'C4::Search::History', qw( add get delete get_from_session ) ); -my $userid = 123; +my $userid = 123; my $previous_sessionid = "PREVIOUS_SESSIONID"; -my $current_sessionid = "CURRENT_SESSIONID"; -my $total = 42; -my $query_cgi_b = q{idx=kw&idx=ti&idx=au%2Cwrdl&q=word1é&q=word2è&q=word3à&do=Search&sort_by=author_az}; -my $query_cgi_a = q{op=do_search&type=opac&authtypecode=NP&operator=start&value=Harry&marclist=match&and_or=and&orderby=HeadingAsc}; +my $current_sessionid = "CURRENT_SESSIONID"; +my $total = 42; +my $query_cgi_b = q{idx=kw&idx=ti&idx=au%2Cwrdl&q=word1é&q=word2è&q=word3à&do=Search&sort_by=author_az}; +my $query_cgi_a = + q{op=do_search&type=opac&authtypecode=NP&operator=start&value=Harry&marclist=match&and_or=and&orderby=HeadingAsc}; # add my $added = add( $userid, $current_sessionid, $previous_sessionid, $total, $query_cgi_b, $query_cgi_a ); -is ( $added, 9, '9 searches are added' ); +is( $added, 9, '9 searches are added' ); # get -my $searches_for_userid = C4::Search::History::get({ - userid => $userid, -}); +my $searches_for_userid = C4::Search::History::get( + { + userid => $userid, + } +); is( scalar(@$searches_for_userid), 9, 'There are 9 searches in all' ); -my $searches_for_current_session = C4::Search::History::get({ - userid => $userid, - sessionid => $current_sessionid, -}); +my $searches_for_current_session = C4::Search::History::get( + { + userid => $userid, + sessionid => $current_sessionid, + } +); is( scalar(@$searches_for_current_session), 5, 'There are 5 searches for the current session' ); -my $searches_for_previous_sessions = C4::Search::History::get({ - userid => $userid, - sessionid => $current_sessionid, - previous => 1, -}); +my $searches_for_previous_sessions = C4::Search::History::get( + { + userid => $userid, + sessionid => $current_sessionid, + previous => 1, + } +); is( scalar(@$searches_for_previous_sessions), 4, 'There are 4 searches for previous sessions' ); -my $authority_searches_for_current_session = C4::Search::History::get({ - userid => $userid, - sessionid => $current_sessionid, - type => 'authority', -}); +my $authority_searches_for_current_session = C4::Search::History::get( + { + userid => $userid, + sessionid => $current_sessionid, + type => 'authority', + } +); is( scalar(@$authority_searches_for_current_session), 3, 'There are 3 authority searches for the current session' ); -my $authority_searches_for_previous_session = C4::Search::History::get({ - userid => $userid, - sessionid => $current_sessionid, - type => 'authority', - previous => 1, -}); +my $authority_searches_for_previous_session = C4::Search::History::get( + { + userid => $userid, + sessionid => $current_sessionid, + type => 'authority', + previous => 1, + } +); is( scalar(@$authority_searches_for_previous_session), 2, 'There are 2 authority searches for previous sessions' ); -my $biblio_searches_for_userid = C4::Search::History::get({ - userid => $userid, - type => 'biblio', -}); +my $biblio_searches_for_userid = C4::Search::History::get( + { + userid => $userid, + type => 'biblio', + } +); is( scalar(@$biblio_searches_for_userid), 4, 'There are 5 searches for the current session' ); -my $authority_searches_for_userid = C4::Search::History::get({ - userid => $userid, - type => 'authority', -}); +my $authority_searches_for_userid = C4::Search::History::get( + { + userid => $userid, + type => 'authority', + } +); is( scalar(@$authority_searches_for_userid), 5, 'There are 4 searches for previous sessions' ); -delete_all( $userid ); +delete_all($userid); # delete add( $userid, $current_sessionid, $previous_sessionid, $total, $query_cgi_b, $query_cgi_a ); -C4::Search::History::delete({ - userid => $userid, - sessionid => $current_sessionid, - type => 'authority', -}); -my $all = C4::Search::History::get({userid => $userid}); +C4::Search::History::delete( + { + userid => $userid, + sessionid => $current_sessionid, + type => 'authority', + } +); +my $all = C4::Search::History::get( { userid => $userid } ); is( scalar(@$all), 6, 'There are 6 searches in all after deleting current biblio searches' ); -delete_all( $userid ); +delete_all($userid); add( $userid, $current_sessionid, $previous_sessionid, $total, $query_cgi_b, $query_cgi_a ); -C4::Search::History::delete({ - userid => $userid, - sessionid => $current_sessionid, - type => 'biblio', - previous => 1, -}); -$all = C4::Search::History::get({userid => $userid}); +C4::Search::History::delete( + { + userid => $userid, + sessionid => $current_sessionid, + type => 'biblio', + previous => 1, + } +); +$all = C4::Search::History::get( { userid => $userid } ); is( scalar(@$all), 7, 'There are 7 searches in all after deleting previous authority searches' ); -delete_all( $userid ); +delete_all($userid); add( $userid, $current_sessionid, $previous_sessionid, $total, $query_cgi_b, $query_cgi_a ); -C4::Search::History::delete({ - userid => $userid, - sessionid => $current_sessionid, - previous => 1, -}); -$all = C4::Search::History::get({userid => $userid}); +C4::Search::History::delete( + { + userid => $userid, + sessionid => $current_sessionid, + previous => 1, + } +); +$all = C4::Search::History::get( { userid => $userid } ); is( scalar(@$all), 5, 'There are 5 searches in all after deleting all previous searches' ); -delete_all( $userid ); +delete_all($userid); add( $userid, $current_sessionid, $previous_sessionid, $total, $query_cgi_b, $query_cgi_a ); -C4::Search::History::delete({ - userid => $userid, - sessionid => $current_sessionid, -}); -$all = C4::Search::History::get({userid => $userid}); +C4::Search::History::delete( + { + userid => $userid, + sessionid => $current_sessionid, + } +); +$all = C4::Search::History::get( { userid => $userid } ); is( scalar(@$all), 4, 'There are 5 searches in all after deleting all searches for a sessionid' ); -delete_all( $userid ); +delete_all($userid); add( $userid, $current_sessionid, $previous_sessionid, $total, $query_cgi_b, $query_cgi_a ); -C4::Search::History::delete({ - userid => $userid, -}); -$all = C4::Search::History::get({userid => $userid}); +C4::Search::History::delete( + { + userid => $userid, + } +); +$all = C4::Search::History::get( { userid => $userid } ); is( scalar(@$all), 0, 'There are 0 search after deleting all searches for a userid' ); -delete_all( $userid ); +delete_all($userid); add( $userid, $current_sessionid, $previous_sessionid, $total, $query_cgi_b, $query_cgi_a ); -warning_like { C4::Search::History::delete({}) } - qr/^ERROR: userid, id or interval is required for history deletion/, - 'Calling delete without userid raises warning'; -$all = C4::Search::History::get({userid => $userid}); +warning_like { C4::Search::History::delete( {} ) } +qr/^ERROR: userid, id or interval is required for history deletion/, + 'Calling delete without userid raises warning'; +$all = C4::Search::History::get( { userid => $userid } ); is( scalar(@$all), 9, 'There are still 9 searches after calling delete without userid' ); -delete_all( $userid ); +delete_all($userid); # Delete (with a given id) add( $userid, $current_sessionid, $previous_sessionid, $total, $query_cgi_b, $query_cgi_a ); -$all = C4::Search::History::get({ userid => $userid }); +$all = C4::Search::History::get( { userid => $userid } ); + # Delete 5 searches my $ids = [ shuffle map { $_->{id} } @$all ]; for my $id ( @$ids[ 0 .. 4 ] ) { - C4::Search::History::delete({ id => $id }); + C4::Search::History::delete( { id => $id } ); } -$all = C4::Search::History::get({ userid => $userid }); +$all = C4::Search::History::get( { userid => $userid } ); is( scalar(@$all), 4, 'There are 4 searches after calling 5 times delete with id' ); -delete_all( $userid ); +delete_all($userid); add( $userid, $current_sessionid, $previous_sessionid, $total, $query_cgi_b, $query_cgi_a ); -$all = C4::Search::History::get({ userid => $userid }); +$all = C4::Search::History::get( { userid => $userid } ); + # Delete 5 searches $ids = [ shuffle map { $_->{id} } @$all ]; -C4::Search::History::delete({ id => [ @$ids[0..4] ] }); -$all = C4::Search::History::get({ userid => $userid }); +C4::Search::History::delete( { id => [ @$ids[ 0 .. 4 ] ] } ); +$all = C4::Search::History::get( { userid => $userid } ); is( scalar(@$all), 4, 'There are 4 searches after calling delete with 5 ids' ); -delete_all( $userid ); +delete_all($userid); # Test delete with interval add( $userid, $current_sessionid, $previous_sessionid, $total, $query_cgi_b, $query_cgi_a ); -C4::Search::History::delete({ - userid => $userid, - interval => 10, -}); -$all = C4::Search::History::get({userid => $userid}); +C4::Search::History::delete( + { + userid => $userid, + interval => 10, + } +); +$all = C4::Search::History::get( { userid => $userid } ); is( scalar(@$all), 9, 'There are still 9 searches after calling delete with an interval = 10 days' ); -C4::Search::History::delete({ - userid => $userid, - interval => 6, -}); -$all = C4::Search::History::get({userid => $userid}); +C4::Search::History::delete( + { + userid => $userid, + interval => 6, + } +); +$all = C4::Search::History::get( { userid => $userid } ); is( scalar(@$all), 8, 'There are still 8 searches after calling delete with an interval = 6 days' ); -C4::Search::History::delete({ - userid => $userid, - interval => 2, -}); -$all = C4::Search::History::get({userid => $userid}); +C4::Search::History::delete( + { + userid => $userid, + interval => 2, + } +); +$all = C4::Search::History::get( { userid => $userid } ); is( scalar(@$all), 2, 'There are still 2 searches after calling delete with an interval = 2 days' ); -delete_all( $userid ); +delete_all($userid); add( $userid, $current_sessionid, $previous_sessionid, $total, $query_cgi_b, $query_cgi_a ); -C4::Search::History::delete({ - userid => $userid, - interval => 5, - type => 'biblio', -}); -$all = C4::Search::History::get({userid => $userid}); +C4::Search::History::delete( + { + userid => $userid, + interval => 5, + type => 'biblio', + } +); +$all = C4::Search::History::get( { userid => $userid } ); is( scalar(@$all), 8, 'There are still 9 searches after calling delete with an interval = 5 days for biblio' ); -C4::Search::History::delete({ - userid => $userid, - interval => 5, - type => 'authority', -}); -$all = C4::Search::History::get({userid => $userid}); +C4::Search::History::delete( + { + userid => $userid, + interval => 5, + type => 'authority', + } +); +$all = C4::Search::History::get( { userid => $userid } ); is( scalar(@$all), 6, 'There are still 6 searches after calling delete with an interval = 5 days for authority' ); -C4::Search::History::delete({ - userid => $userid, - interval => -1, -}); -$all = C4::Search::History::get({userid => $userid}); +C4::Search::History::delete( + { + userid => $userid, + interval => -1, + } +); +$all = C4::Search::History::get( { userid => $userid } ); is( scalar(@$all), 0, 'There is no search after calling delete with an interval = -1 days' ); # If time is null, it must be set to NOW() my $query_desc_b1_p = q{first previous biblio search}; -C4::Search::History::add( { - userid => $userid, - sessionid => $previous_sessionid, - query_desc => $query_desc_b1_p, - query_cgi => $query_cgi_b, - total => $total, - type => 'biblio', -}); +C4::Search::History::add( + { + userid => $userid, + sessionid => $previous_sessionid, + query_desc => $query_desc_b1_p, + query_cgi => $query_cgi_b, + total => $total, + type => 'biblio', + } +); my $search_history_id = $dbh->last_insert_id( undef, undef, 'search_history', undef ); -my $search_history = C4::Search::History::get({ id => $search_history_id }); -is( output_pref({ dt => dt_from_string($search_history->[0]->{time}), dateonly => 1 }), output_pref({ dt => dt_from_string, dateonly => 1 }), "Inserting a new search history should handle undefined time" ); +my $search_history = C4::Search::History::get( { id => $search_history_id } ); +is( + output_pref( { dt => dt_from_string( $search_history->[0]->{time} ), dateonly => 1 } ), + output_pref( { dt => dt_from_string, dateonly => 1 } ), + "Inserting a new search history should handle undefined time" +); - -delete_all( $userid ); +delete_all($userid); sub add { my ( $userid, $current_session_id, $previous_sessionid, $total, $query_cgi_b, $query_cgi_a ) = @_; @@ -237,241 +281,244 @@ sub add { my $days_ago_6 = dt_from_string()->add_duration( DateTime::Duration->new( days => -6, minutes => 1 ) ); my $days_ago_8 = dt_from_string()->add_duration( DateTime::Duration->new( days => -8, minutes => 1 ) ); - my $query_desc_b1_p = q{first previous biblio search}; + my $query_desc_b1_p = q{first previous biblio search}; my $first_previous_biblio_search = { - userid => $userid, - sessionid => $previous_sessionid, + userid => $userid, + sessionid => $previous_sessionid, query_desc => $query_desc_b1_p, - query_cgi => $query_cgi_b, - total => $total, - type => 'biblio', - time => $days_ago_2, + query_cgi => $query_cgi_b, + total => $total, + type => 'biblio', + time => $days_ago_2, }; - my $query_desc_a1_p = q{first previous authority search}; + my $query_desc_a1_p = q{first previous authority search}; my $first_previous_authority_search = { - userid => $userid, - sessionid => $previous_sessionid, + userid => $userid, + sessionid => $previous_sessionid, query_desc => $query_desc_a1_p, - query_cgi => $query_cgi_a, - total => $total, - type => 'authority', - time => $days_ago_2, + query_cgi => $query_cgi_a, + total => $total, + type => 'authority', + time => $days_ago_2, }; - my $query_desc_b2_p = q{second previous biblio search}; + my $query_desc_b2_p = q{second previous biblio search}; my $second_previous_biblio_search = { - userid => $userid, - sessionid => $previous_sessionid, + userid => $userid, + sessionid => $previous_sessionid, query_desc => $query_desc_b2_p, - query_cgi => $query_cgi_b, - total => $total, - type => 'biblio', - time => $days_ago_4, + query_cgi => $query_cgi_b, + total => $total, + type => 'biblio', + time => $days_ago_4, }; - my $query_desc_a2_p = q{second previous authority search}; + my $query_desc_a2_p = q{second previous authority search}; my $second_previous_authority_search = { - userid => $userid, - sessionid => $previous_sessionid, + userid => $userid, + sessionid => $previous_sessionid, query_desc => $query_desc_a2_p, - query_cgi => $query_cgi_a, - total => $total, - type => 'authority', - time => $days_ago_4, + query_cgi => $query_cgi_a, + total => $total, + type => 'authority', + time => $days_ago_4, }; - my $query_desc_b1_c = q{first current biblio search}; my $first_current_biblio_search = { - userid => $userid, - sessionid => $current_sessionid, + userid => $userid, + sessionid => $current_sessionid, query_desc => $query_desc_b1_c, - query_cgi => $query_cgi_b, - total => $total, - type => 'biblio', - time => $days_ago_4, + query_cgi => $query_cgi_b, + total => $total, + type => 'biblio', + time => $days_ago_4, }; - my $query_desc_a1_c = q{first current authority search}; + my $query_desc_a1_c = q{first current authority search}; my $first_current_authority_search = { - userid => $userid, - sessionid => $current_sessionid, + userid => $userid, + sessionid => $current_sessionid, query_desc => $query_desc_a1_c, - query_cgi => $query_cgi_a, - total => $total, - type => 'authority', - time => $days_ago_4, + query_cgi => $query_cgi_a, + total => $total, + type => 'authority', + time => $days_ago_4, }; - my $query_desc_b2_c = q{second current biblio search}; + my $query_desc_b2_c = q{second current biblio search}; my $second_current_biblio_search = { - userid => $userid, - sessionid => $current_sessionid, + userid => $userid, + sessionid => $current_sessionid, query_desc => $query_desc_b2_c, - query_cgi => $query_cgi_b, - total => $total, - type => 'biblio', - time => $days_ago_6, + query_cgi => $query_cgi_b, + total => $total, + type => 'biblio', + time => $days_ago_6, }; - my $query_desc_a2_c = q{second current authority search}; + my $query_desc_a2_c = q{second current authority search}; my $second_current_authority_search = { - userid => $userid, - sessionid => $current_sessionid, + userid => $userid, + sessionid => $current_sessionid, query_desc => $query_desc_a2_c, - query_cgi => $query_cgi_a, - total => $total, - type => 'authority', - time => $days_ago_6, + query_cgi => $query_cgi_a, + total => $total, + type => 'authority', + time => $days_ago_6, }; - my $query_desc_a3_c = q{third current authority search}; + my $query_desc_a3_c = q{third current authority search}; my $third_current_authority_search = { - userid => $userid, - sessionid => $current_sessionid, + userid => $userid, + sessionid => $current_sessionid, query_desc => $query_desc_a3_c, - query_cgi => $query_cgi_a, - total => $total, - type => 'authority', - time => $days_ago_8, + query_cgi => $query_cgi_a, + total => $total, + type => 'authority', + time => $days_ago_8, }; - my $r = 0; - $r += C4::Search::History::add( $first_current_biblio_search ); - $r += C4::Search::History::add( $first_current_authority_search ); - $r += C4::Search::History::add( $second_current_biblio_search ); - $r += C4::Search::History::add( $second_current_authority_search ); - $r += C4::Search::History::add( $first_previous_biblio_search ); - $r += C4::Search::History::add( $first_previous_authority_search ); - $r += C4::Search::History::add( $second_previous_biblio_search ); - $r += C4::Search::History::add( $second_previous_authority_search ); - $r += C4::Search::History::add( $third_current_authority_search ); + $r += C4::Search::History::add($first_current_biblio_search); + $r += C4::Search::History::add($first_current_authority_search); + $r += C4::Search::History::add($second_current_biblio_search); + $r += C4::Search::History::add($second_current_authority_search); + $r += C4::Search::History::add($first_previous_biblio_search); + $r += C4::Search::History::add($first_previous_authority_search); + $r += C4::Search::History::add($second_previous_biblio_search); + $r += C4::Search::History::add($second_previous_authority_search); + $r += C4::Search::History::add($third_current_authority_search); return $r; } sub delete_all { my $userid = shift; - C4::Search::History::delete({ - userid => $userid, - }); + C4::Search::History::delete( + { + userid => $userid, + } + ); } subtest 'LoadSearchHistoryToTheFirstLoggedUser working' => sub { -plan tests =>2; + plan tests => 2; -my $query = CGI->new; + my $query = CGI->new; -my $schema = Koha::Database->schema; -my $builder = t::lib::TestBuilder->new; + my $schema = Koha::Database->schema; + my $builder = t::lib::TestBuilder->new; -# Borrower Creation -our $patron = $builder->build( { source => 'Borrower' } ); -t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 ); -Koha::Patrons->find( $patron->{borrowernumber} )->set_password({ password => 'password' }); + # Borrower Creation + our $patron = $builder->build( { source => 'Borrower' } ); + t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 ); + Koha::Patrons->find( $patron->{borrowernumber} )->set_password( { password => 'password' } ); -my $session = C4::Auth::get_session(""); -$session->flush; + my $session = C4::Auth::get_session(""); + $session->flush; -sub myMockedget_from_session { - my $expected_recent_searches = [ - { - 'time' => dt_from_string, - 'query_cgi' => 'cgi_test', - 'total' => 2, - 'query_desc' => 'kw,wrdl: history, ' - } - ]; - return @{$expected_recent_searches}; + sub myMockedget_from_session { + my $expected_recent_searches = [ + { + 'time' => dt_from_string, + 'query_cgi' => 'cgi_test', + 'total' => 2, + 'query_desc' => 'kw,wrdl: history, ' + } + ]; + return @{$expected_recent_searches}; -} - -my $getfrom = Test::MockModule->new( 'C4::Search::History' ); -$getfrom->mock( 'get_from_session', \&myMockedget_from_session ); - -my $cgi = Test::MockModule->new( 'CGI'); -$cgi->mock('cookie', sub { - my ($self, $key) = @_; - if (!ref($key) && $key eq 'CGISESSID'){ - return 'ID'; - } -}); - -sub MockedCheckauth { - my ($query,$authnotrequired,$flagsrequired,$type) = @_; - my $userid = $patron->{userid}; - my $sessionID = 234; - my $flags = { - superlibrarian => 1, acquisition => 0, - borrowers => 0, - catalogue => 1, circulate => 0, - coursereserves => 0, editauthorities => 0, - editcatalogue => 0, - parameters => 0, permissions => 0, - plugins => 0, reports => 0, - reserveforothers => 0, serials => 0, - staffaccess => 0, tools => 0, - updatecharges => 0 - }; - - my $session_cookie = $query->cookie( - -name => 'CGISESSID', - -value => '9884013ae2c441d12e0bc9376242d2a8', - -HttpOnly => 1 - ); - return ( $userid, $session_cookie, $sessionID, $flags ); -} - -# Mock checkauth -my $auth = Test::MockModule->new( 'C4::Auth' ); -$auth->mock( 'checkauth', \&MockedCheckauth ); - -$query->param('koha_login_context', 'opac'); -$query->param('userid', $patron->{userid}); -$query->param('password', 'password'); - -# Test when the syspref is disabled -t::lib::Mocks::mock_preference('LoadSearchHistoryToTheFirstLoggedUser', 0); -my $result = $schema->resultset('SearchHistory')->search()->count; - -my ( $template, $loggedinuser, $cookies ) = get_template_and_user( - { - template_name => "opac-user.tt", - query => $query, - type => "opac", - debug => 1 } -); -my $result2 = $schema->resultset('SearchHistory')->search()->count; -is($result2, $result, 'no new search added to borrower'); + my $getfrom = Test::MockModule->new('C4::Search::History'); + $getfrom->mock( 'get_from_session', \&myMockedget_from_session ); -# Test when the syspref is enabled -t::lib::Mocks::mock_preference('LoadSearchHistoryToTheFirstLoggedUser', 1); -$query->param('koha_login_context', 'opac'); -$query->param('userid', $patron->{userid}); -$query->param('password', 'password'); -$query->cookie( + my $cgi = Test::MockModule->new('CGI'); + $cgi->mock( + 'cookie', + sub { + my ( $self, $key ) = @_; + if ( !ref($key) && $key eq 'CGISESSID' ) { + return 'ID'; + } + } + ); + + sub MockedCheckauth { + my ( $query, $authnotrequired, $flagsrequired, $type ) = @_; + my $userid = $patron->{userid}; + my $sessionID = 234; + my $flags = { + superlibrarian => 1, acquisition => 0, + borrowers => 0, + catalogue => 1, circulate => 0, + coursereserves => 0, editauthorities => 0, + editcatalogue => 0, + parameters => 0, permissions => 0, + plugins => 0, reports => 0, + reserveforothers => 0, serials => 0, + staffaccess => 0, tools => 0, + updatecharges => 0 + }; + + my $session_cookie = $query->cookie( + -name => 'CGISESSID', + -value => '9884013ae2c441d12e0bc9376242d2a8', + -HttpOnly => 1 + ); + return ( $userid, $session_cookie, $sessionID, $flags ); + } + + # Mock checkauth + my $auth = Test::MockModule->new('C4::Auth'); + $auth->mock( 'checkauth', \&MockedCheckauth ); + + $query->param( 'koha_login_context', 'opac' ); + $query->param( 'userid', $patron->{userid} ); + $query->param( 'password', 'password' ); + + # Test when the syspref is disabled + t::lib::Mocks::mock_preference( 'LoadSearchHistoryToTheFirstLoggedUser', 0 ); + my $result = $schema->resultset('SearchHistory')->search()->count; + + my ( $template, $loggedinuser, $cookies ) = get_template_and_user( + { + template_name => "opac-user.tt", + query => $query, + type => "opac", + debug => 1 + } + ); + + my $result2 = $schema->resultset('SearchHistory')->search()->count; + is( $result2, $result, 'no new search added to borrower' ); + + # Test when the syspref is enabled + t::lib::Mocks::mock_preference( 'LoadSearchHistoryToTheFirstLoggedUser', 1 ); + $query->param( 'koha_login_context', 'opac' ); + $query->param( 'userid', $patron->{userid} ); + $query->param( 'password', 'password' ); + $query->cookie( -name => 'CGISESSID', -value => $session->id, -HttpOnly => 1 -); + ); -$result = $schema->resultset('SearchHistory')->search()->count; + $result = $schema->resultset('SearchHistory')->search()->count; -( $template, $loggedinuser, $cookies ) = get_template_and_user( - { - template_name => "opac-user.tt", - query => $query, - type => "opac", - debug => 1 - } -); + ( $template, $loggedinuser, $cookies ) = get_template_and_user( + { + template_name => "opac-user.tt", + query => $query, + type => "opac", + debug => 1 + } + ); -$result2 = $schema->resultset('SearchHistory')->search()->count; -is($result2, $result+1, 'new search added to borrower'); + $result2 = $schema->resultset('SearchHistory')->search()->count; + is( $result2, $result + 1, 'new search added to borrower' ); }; done_testing; diff --git a/t/db_dependent/Serials.t b/t/db_dependent/Serials.t index 0c9ce3dffe..5f9ea770ea 100755 --- a/t/db_dependent/Serials.t +++ b/t/db_dependent/Serials.t @@ -5,12 +5,13 @@ use Modern::Perl; -use C4::Serials qw( getroutinglist updateClaim NewSubscription GetSubscription GetSubscriptionHistoryFromSubscriptionId SearchSubscriptions ModSubscription GetExpirationDate GetSerials GetSerialInformation NewIssue AddItem2Serial DelSubscription GetFullSubscription PrepareSerialsData GetSubscriptionsFromBiblionumber ModSubscriptionHistory GetSerials2 GetLatestSerials GetNextSeq GetSeq CountSubscriptionFromBiblionumber ModSerialStatus findSerialsByStatus HasSubscriptionStrictlyExpired HasSubscriptionExpired GetLateOrMissingIssues check_routing addroutingmember GetNextDate ); +use C4::Serials + qw( getroutinglist updateClaim NewSubscription GetSubscription GetSubscriptionHistoryFromSubscriptionId SearchSubscriptions ModSubscription GetExpirationDate GetSerials GetSerialInformation NewIssue AddItem2Serial DelSubscription GetFullSubscription PrepareSerialsData GetSubscriptionsFromBiblionumber ModSubscriptionHistory GetSerials2 GetLatestSerials GetNextSeq GetSeq CountSubscriptionFromBiblionumber ModSerialStatus findSerialsByStatus HasSubscriptionStrictlyExpired HasSubscriptionExpired GetLateOrMissingIssues check_routing addroutingmember GetNextDate ); use C4::Serials::Frequency; use C4::Serials::Numberpattern; -use C4::Biblio qw( AddBiblio GetMarcFromKohaField ); +use C4::Biblio qw( AddBiblio GetMarcFromKohaField ); use C4::Budgets qw( AddBudgetPeriod AddBudget ); -use C4::Items qw( AddItemFromMarc ); +use C4::Items qw( AddItemFromMarc ); use Koha::Database; use Koha::DateUtils qw( dt_from_string output_pref ); use Koha::Acquisition::Booksellers; @@ -20,7 +21,10 @@ use Test::MockModule; use Test::More tests => 63; BEGIN { - use_ok('C4::Serials', qw( updateClaim NewSubscription GetSubscription GetSubscriptionHistoryFromSubscriptionId SearchSubscriptions ModSubscription GetExpirationDate GetSerials GetSerialInformation NewIssue AddItem2Serial DelSubscription GetFullSubscription PrepareSerialsData GetSubscriptionsFromBiblionumber ModSubscriptionHistory GetSerials2 GetLatestSerials GetNextSeq GetSeq CountSubscriptionFromBiblionumber ModSerialStatus findSerialsByStatus HasSubscriptionStrictlyExpired HasSubscriptionExpired GetLateOrMissingIssues check_routing addroutingmember GetNextDate )); + use_ok( + 'C4::Serials', + qw( updateClaim NewSubscription GetSubscription GetSubscriptionHistoryFromSubscriptionId SearchSubscriptions ModSubscription GetExpirationDate GetSerials GetSerialInformation NewIssue AddItem2Serial DelSubscription GetFullSubscription PrepareSerialsData GetSubscriptionsFromBiblionumber ModSubscriptionHistory GetSerials2 GetLatestSerials GetNextSeq GetSeq CountSubscriptionFromBiblionumber ModSerialStatus findSerialsByStatus HasSubscriptionStrictlyExpired HasSubscriptionExpired GetLateOrMissingIssues check_routing addroutingmember GetNextDate ) + ); } # Auth required for cataloguing plugins @@ -37,51 +41,59 @@ my $builder = t::lib::TestBuilder->new(); # This could/should be used for all untested methods my @methods = ('updateClaim'); -can_ok('C4::Serials', @methods); +can_ok( 'C4::Serials', @methods ); -$dbh->do(q|UPDATE marc_subfield_structure SET value_builder="callnumber.pl" where kohafield="items.itemcallnumber" and frameworkcode=''|); +$dbh->do( + q|UPDATE marc_subfield_structure SET value_builder="callnumber.pl" where kohafield="items.itemcallnumber" and frameworkcode=''| +); my $bookseller = Koha::Acquisition::Bookseller->new( { - name => "my vendor", + name => "my vendor", address1 => "bookseller's address", - phone => "0123456", - active => 1 + phone => "0123456", + active => 1 } ); -my ($biblionumber, $biblioitemnumber) = AddBiblio(MARC::Record->new, ''); +my ( $biblionumber, $biblioitemnumber ) = AddBiblio( MARC::Record->new, '' ); -my $bpid = AddBudgetPeriod({ - budget_period_startdate => '2015-01-01', - budget_period_enddate => '2015-12-31', - budget_period_description => "budget desc" -}); +my $bpid = AddBudgetPeriod( + { + budget_period_startdate => '2015-01-01', + budget_period_enddate => '2015-12-31', + budget_period_description => "budget desc" + } +); -my $budget_id = AddBudget({ - budget_code => "ABCD", - budget_amount => "123.132", - budget_name => "Périodiques", - budget_notes => "This is a note", - budget_period_id => $bpid -}); +my $budget_id = AddBudget( + { + budget_code => "ABCD", + budget_amount => "123.132", + budget_name => "Périodiques", + budget_notes => "This is a note", + budget_period_id => $bpid + } +); -my $frequency_id = AddSubscriptionFrequency({ description => "Test frequency 1" }); -my $pattern_id = AddSubscriptionNumberpattern({ - label => 'Test numberpattern 1', - description => 'Description for numberpattern 1', - numberingmethod => '{X}', - label1 => q{}, - add1 => 1, - every1 => 1, - every1 => 1, - numbering1 => 1, - whenmorethan1 => 1, -}); +my $frequency_id = AddSubscriptionFrequency( { description => "Test frequency 1" } ); +my $pattern_id = AddSubscriptionNumberpattern( + { + label => 'Test numberpattern 1', + description => 'Description for numberpattern 1', + numberingmethod => '{X}', + label1 => q{}, + add1 => 1, + every1 => 1, + every1 => 1, + numbering1 => 1, + whenmorethan1 => 1, + } +); -my $notes = "a\nnote\non\nseveral\nlines"; -my $internalnotes = 'intnotes'; -my $ccode = 'FIC'; +my $notes = "a\nnote\non\nseveral\nlines"; +my $internalnotes = 'intnotes'; +my $ccode = 'FIC'; my $subscriptionid = NewSubscription( undef, "", @@ -163,36 +175,39 @@ NewSubscription( $ccode ); -my $subscriptioninformation = GetSubscription( $subscriptionid ); +my $subscriptioninformation = GetSubscription($subscriptionid); -is( $subscriptioninformation->{notes}, $notes, 'NewSubscription should set notes' ); +is( $subscriptioninformation->{notes}, $notes, 'NewSubscription should set notes' ); is( $subscriptioninformation->{internalnotes}, $internalnotes, 'NewSubscription should set internalnotes' ); -is( $subscriptioninformation->{ccode}, $ccode, 'NewSubscription should set ccode' ); +is( $subscriptioninformation->{ccode}, $ccode, 'NewSubscription should set ccode' ); my $subscription_history = C4::Serials::GetSubscriptionHistoryFromSubscriptionId($subscriptionid); is( $subscription_history->{opacnote}, undef, 'NewSubscription should not set subscriptionhistory opacnotes' ); -is( $subscription_history->{librariannote}, undef, 'NewSubscription should not set subscriptionhistory librariannotes' ); +is( + $subscription_history->{librariannote}, undef, + 'NewSubscription should not set subscriptionhistory librariannotes' +); -my @subscriptions = SearchSubscriptions({string => $subscriptioninformation->{bibliotitle}, orderby => 'title' }); +my @subscriptions = SearchSubscriptions( { string => $subscriptioninformation->{bibliotitle}, orderby => 'title' } ); isa_ok( \@subscriptions, 'ARRAY' ); -@subscriptions = SearchSubscriptions({ issn => $subscriptioninformation->{issn}, orderby => 'title' }); +@subscriptions = SearchSubscriptions( { issn => $subscriptioninformation->{issn}, orderby => 'title' } ); isa_ok( \@subscriptions, 'ARRAY' ); -@subscriptions = SearchSubscriptions({ ean => $subscriptioninformation->{ean}, orderby => 'title' }); +@subscriptions = SearchSubscriptions( { ean => $subscriptioninformation->{ean}, orderby => 'title' } ); isa_ok( \@subscriptions, 'ARRAY' ); -@subscriptions = SearchSubscriptions({ biblionumber => $subscriptioninformation->{bibnum}, orderby => 'title' }); +@subscriptions = SearchSubscriptions( { biblionumber => $subscriptioninformation->{bibnum}, orderby => 'title' } ); isa_ok( \@subscriptions, 'ARRAY' ); -@subscriptions = SearchSubscriptions({}); +@subscriptions = SearchSubscriptions( {} ); is( @subscriptions, 2, 'SearchSubscriptions returned the expected number of subscriptions when results_limit is not set' ); -@subscriptions = SearchSubscriptions({}, { results_limit => 1 }); +@subscriptions = SearchSubscriptions( {}, { results_limit => 1 } ); is( @subscriptions, 1, @@ -254,56 +269,60 @@ is( 'SearchSubscriptions returned the correct subscription' ); -my $frequency = GetSubscriptionFrequency($subscriptioninformation->{periodicity}); +my $frequency = GetSubscriptionFrequency( $subscriptioninformation->{periodicity} ); my $old_frequency; -if (not $frequency->{unit}) { - $old_frequency = $frequency->{id}; - $frequency->{unit} = "month"; - $frequency->{unitsperissue} = 1; - $frequency->{issuesperunit} = 1; - $frequency->{description} = "Frequency created by t/db_dependant/Serials.t"; - $subscriptioninformation->{periodicity} = AddSubscriptionFrequency($frequency); +if ( not $frequency->{unit} ) { + $old_frequency = $frequency->{id}; + $frequency->{unit} = "month"; + $frequency->{unitsperissue} = 1; + $frequency->{issuesperunit} = 1; + $frequency->{description} = "Frequency created by t/db_dependant/Serials.t"; + $subscriptioninformation->{periodicity} = AddSubscriptionFrequency($frequency); $subscriptioninformation->{serialsadditems} = 1; - $subscriptioninformation->{ccode} = 'NFIC'; + $subscriptioninformation->{ccode} = 'NFIC'; - ModSubscription( @$subscriptioninformation{qw( - librarian branchcode aqbooksellerid cost aqbudgetid startdate - periodicity firstacquidate irregularity numberpattern locale - numberlength weeklength monthlength lastvalue1 innerloop1 lastvalue2 - innerloop2 lastvalue3 innerloop3 status biblionumber callnumber notes - letter manualhistory internalnotes serialsadditems staffdisplaycount - opacdisplaycount graceperiod location enddate subscriptionid - skip_serialseq itemtype previousitemtype mana_id ccode - )} ); + ModSubscription( + @$subscriptioninformation{ + qw( + librarian branchcode aqbooksellerid cost aqbudgetid startdate + periodicity firstacquidate irregularity numberpattern locale + numberlength weeklength monthlength lastvalue1 innerloop1 lastvalue2 + innerloop2 lastvalue3 innerloop3 status biblionumber callnumber notes + letter manualhistory internalnotes serialsadditems staffdisplaycount + opacdisplaycount graceperiod location enddate subscriptionid + skip_serialseq itemtype previousitemtype mana_id ccode + ) + } + ); } -my $expirationdate = GetExpirationDate($subscriptionid) ; +my $expirationdate = GetExpirationDate($subscriptionid); ok( $expirationdate, "expiration date is not NULL" ); # Check ModSubscription has updated the ccode my $subscriptioninformation2 = GetSubscription($subscriptionid); is( $subscriptioninformation2->{ccode}, 'NFIC', 'ModSubscription should update ccode' ); -ok(C4::Serials::GetSubscriptionHistoryFromSubscriptionId($subscriptionid), 'test getting history from sub-scription'); +ok( C4::Serials::GetSubscriptionHistoryFromSubscriptionId($subscriptionid), 'test getting history from sub-scription' ); -my ($serials_count, @serials) = GetSerials($subscriptionid); -ok($serials_count > 0, 'Subscription has at least one serial'); +my ( $serials_count, @serials ) = GetSerials($subscriptionid); +ok( $serials_count > 0, 'Subscription has at least one serial' ); my $serial = $serials[0]; -isa_ok(C4::Serials::GetSerialInformation($serial->{serialid}), 'HASH', 'test getting Serial Information'); +isa_ok( C4::Serials::GetSerialInformation( $serial->{serialid} ), 'HASH', 'test getting Serial Information' ); subtest 'Values should not be erased on editing' => sub { plan tests => 1; - my $biblio = $builder->build_sample_biblio(); + my $biblio = $builder->build_sample_biblio(); my $biblionumber = $biblio->biblionumber; - my ( $icn_tag, $icn_sf ) = GetMarcFromKohaField( 'items.itemcallnumber' ); - my ( $it_tag, $it_sf ) = GetMarcFromKohaField( 'items.itype' ); + my ( $icn_tag, $icn_sf ) = GetMarcFromKohaField('items.itemcallnumber'); + my ( $it_tag, $it_sf ) = GetMarcFromKohaField('items.itype'); - my $itemtype = $builder->build( { source => 'Itemtype' } )->{itemtype}; + my $itemtype = $builder->build( { source => 'Itemtype' } )->{itemtype}; my $itemcallnumber = 'XXXmy itemcallnumberXXX'; - my $item_record = MARC::Record->new; + my $item_record = MARC::Record->new; $item_record->append_fields( MARC::Field->new( '080', '', '', "a" => "default" ), @@ -314,12 +333,14 @@ subtest 'Values should not be erased on editing' => sub { ) ); my ( undef, undef, $itemnumber ) = C4::Items::AddItemFromMarc( $item_record, $biblionumber ); - my $serialid = C4::Serials::NewIssue( "serialseq", $subscriptionid, $biblionumber, - 1, undef, undef, "publisheddatetext", "notes", "routingnotes" ); + my $serialid = C4::Serials::NewIssue( + "serialseq", $subscriptionid, $biblionumber, + 1, undef, undef, "publisheddatetext", "notes", "routingnotes" + ); C4::Serials::AddItem2Serial( $serialid, $itemnumber ); my $serial_info = C4::Serials::GetSerialInformation($serialid); - my ($itemcallnumber_info) = grep { $_->{kohafield} eq 'items.itemcallnumber' } - @{ $serial_info->{items}[0]->{iteminformation} }; + my ($itemcallnumber_info) = + grep { $_->{kohafield} eq 'items.itemcallnumber' } @{ $serial_info->{items}[0]->{iteminformation} }; like( $itemcallnumber_info->{marc_value}, qr|value="$itemcallnumber"| ); }; @@ -328,84 +349,96 @@ if ($old_frequency) { my $freq_to_delete = $subscriptioninformation->{periodicity}; $subscriptioninformation->{periodicity} = $old_frequency; - ModSubscription( @$subscriptioninformation{qw( - librarian branchcode aqbooksellerid cost aqbudgetid startdate - periodicity firstacquidate irregularity numberpattern locale - numberlength weeklength monthlength lastvalue1 innerloop1 lastvalue2 - innerloop2 lastvalue3 innerloop3 status biblionumber callnumber notes - letter manualhistory internalnotes serialsadditems staffdisplaycount - opacdisplaycount graceperiod location enddate subscriptionid - skip_serialseq - )} ); + ModSubscription( + @$subscriptioninformation{ + qw( + librarian branchcode aqbooksellerid cost aqbudgetid startdate + periodicity firstacquidate irregularity numberpattern locale + numberlength weeklength monthlength lastvalue1 innerloop1 lastvalue2 + innerloop2 lastvalue3 innerloop3 status biblionumber callnumber notes + letter manualhistory internalnotes serialsadditems staffdisplaycount + opacdisplaycount graceperiod location enddate subscriptionid + skip_serialseq + ) + } + ); DelSubscriptionFrequency($freq_to_delete); } # Test calling subs without parameters -is(C4::Serials::AddItem2Serial(), undef, 'test adding item to serial'); -is(C4::Serials::GetFullSubscription(), undef, 'test getting full subscription'); -is(C4::Serials::PrepareSerialsData(), undef, 'test preparing serial data'); +is( C4::Serials::AddItem2Serial(), undef, 'test adding item to serial' ); +is( C4::Serials::GetFullSubscription(), undef, 'test getting full subscription' ); +is( C4::Serials::PrepareSerialsData(), undef, 'test preparing serial data' ); subtest 'GetSubscriptionsFromBiblionumber' => sub { plan tests => 4; - is( C4::Serials::GetSubscriptionsFromBiblionumber(), - undef, 'test getting subscriptions form biblio number' ); + is( + C4::Serials::GetSubscriptionsFromBiblionumber(), + undef, 'test getting subscriptions form biblio number' + ); my $subscriptions = C4::Serials::GetSubscriptionsFromBiblionumber($biblionumber); - ModSubscriptionHistory( $subscriptions->[0]->{subscriptionid}, - undef, undef, $notes, $notes, $notes ); + ModSubscriptionHistory( + $subscriptions->[0]->{subscriptionid}, + undef, undef, $notes, $notes, $notes + ); $subscriptions = C4::Serials::GetSubscriptionsFromBiblionumber($biblionumber); - is( $subscriptions->[0]->{opacnote}, $notes, + is( + $subscriptions->[0]->{opacnote}, $notes, 'GetSubscriptionsFromBiblionumber should have returned the opacnote as it is in DB, ie. without br tags' ); - is( $subscriptions->[0]->{recievedlist}, $notes, + is( + $subscriptions->[0]->{recievedlist}, $notes, 'GetSubscriptionsFromBiblionumber should have returned recievedlist as it is in DB, ie. without br tags' ); - is( $subscriptions->[0]->{missinglist}, $notes, + is( + $subscriptions->[0]->{missinglist}, $notes, 'GetSubscriptionsFromBiblionumber should have returned missinglist as it is in DB, ie. without br tags' ); }; -is(C4::Serials::GetSerials(), undef, 'test getting serials when you enter nothing'); -is(C4::Serials::GetSerials2(), undef, 'test getting serials when you enter nothing'); +is( C4::Serials::GetSerials(), undef, 'test getting serials when you enter nothing' ); +is( C4::Serials::GetSerials2(), undef, 'test getting serials when you enter nothing' ); -is(C4::Serials::GetLatestSerials(), undef, 'test getting lastest serials'); +is( C4::Serials::GetLatestSerials(), undef, 'test getting lastest serials' ); -is(C4::Serials::GetNextSeq(), undef, 'test getting next seq when you enter nothing'); +is( C4::Serials::GetNextSeq(), undef, 'test getting next seq when you enter nothing' ); -is(C4::Serials::GetSeq(), undef, 'test getting seq when you enter nothing'); +is( C4::Serials::GetSeq(), undef, 'test getting seq when you enter nothing' ); -is(C4::Serials::CountSubscriptionFromBiblionumber(), undef, 'test counting subscription when nothing is entered'); +is( C4::Serials::CountSubscriptionFromBiblionumber(), undef, 'test counting subscription when nothing is entered' ); -is(C4::Serials::ModSubscriptionHistory(), undef, 'test modding subscription history'); +is( C4::Serials::ModSubscriptionHistory(), undef, 'test modding subscription history' ); -is(C4::Serials::ModSerialStatus(),undef, 'test modding serials'); +is( C4::Serials::ModSerialStatus(), undef, 'test modding serials' ); -is(C4::Serials::findSerialsByStatus(), 0, 'test finding serial by status with no parameters'); +is( C4::Serials::findSerialsByStatus(), 0, 'test finding serial by status with no parameters' ); -is(C4::Serials::NewIssue(), undef, 'test getting 0 when nothing is entered'); +is( C4::Serials::NewIssue(), undef, 'test getting 0 when nothing is entered' ); -is(C4::Serials::HasSubscriptionStrictlyExpired(), undef, 'test if the subscriptions has expired'); -is(C4::Serials::HasSubscriptionExpired(), undef, 'test if the subscriptions has expired'); +is( C4::Serials::HasSubscriptionStrictlyExpired(), undef, 'test if the subscriptions has expired' ); +is( C4::Serials::HasSubscriptionExpired(), undef, 'test if the subscriptions has expired' ); -is(C4::Serials::GetLateOrMissingIssues(), undef, 'test getting last or missing issues'); +is( C4::Serials::GetLateOrMissingIssues(), undef, 'test getting last or missing issues' ); subtest 'test_updateClaim' => sub { plan tests => 11; - my $today = output_pref({ dt => dt_from_string, dateonly => 1 }); + my $today = output_pref( { dt => dt_from_string, dateonly => 1 } ); + # Given ... nothing much # When ... Then ... my $result_0 = C4::Serials::updateClaim(undef); - is($result_0, undef, 'Got the expected undef from update claim with nothin'); + is( $result_0, undef, 'Got the expected undef from update claim with nothin' ); # Given ... 3 serial. 2 of them updated. - my $claimdate_1 = dt_from_string('2001-01-13'); # arbitrary date some time in the past. + my $claimdate_1 = dt_from_string('2001-01-13'); # arbitrary date some time in the past. my $claim_count_1 = 5; - my $biblio = $builder->build_sample_biblio; - my $serial1 = $builder->build_object( + my $biblio = $builder->build_sample_biblio; + my $serial1 = $builder->build_object( { class => 'Koha::Serials', value => { @@ -446,91 +479,130 @@ subtest 'test_updateClaim' => sub { ); # When ... - my $result_1 = C4::Serials::updateClaim([$serial1->serialid, $serial2->serialid]); + my $result_1 = C4::Serials::updateClaim( [ $serial1->serialid, $serial2->serialid ] ); # Then ... - is($result_1, 2, 'Got the expected 2 from update claim with 2 serial ids'); + is( $result_1, 2, 'Got the expected 2 from update claim with 2 serial ids' ); - my @late_or_missing_issues_1_0 = C4::Serials::GetLateOrMissingIssues(undef, $serial1->serialid); - is(output_pref({str => $late_or_missing_issues_1_0[0]->{claimdate}, dateonly => 1}), $today, 'Got the expected first different claim date from update claim'); - is($late_or_missing_issues_1_0[0]->{claims_count}, $claim_count_1+1, 'Got the expected first claim count from update claim'); - is($late_or_missing_issues_1_0[0]->{status}, 7, 'Got the expected first claim status from update claim'); + my @late_or_missing_issues_1_0 = C4::Serials::GetLateOrMissingIssues( undef, $serial1->serialid ); + is( + output_pref( { str => $late_or_missing_issues_1_0[0]->{claimdate}, dateonly => 1 } ), $today, + 'Got the expected first different claim date from update claim' + ); + is( + $late_or_missing_issues_1_0[0]->{claims_count}, $claim_count_1 + 1, + 'Got the expected first claim count from update claim' + ); + is( $late_or_missing_issues_1_0[0]->{status}, 7, 'Got the expected first claim status from update claim' ); - my @late_or_missing_issues_1_1 = C4::Serials::GetLateOrMissingIssues(undef, $serial2->serialid); - is(output_pref({str => $late_or_missing_issues_1_1[0]->{claimdate}, dateonly => 1}), $today, 'Got the expected second different claim date from update claim'); - is($late_or_missing_issues_1_1[0]->{claims_count}, $claim_count_1+1, 'Got the expected second claim count from update claim'); - is($late_or_missing_issues_1_1[0]->{status}, 7, 'Got the expected second claim status from update claim'); + my @late_or_missing_issues_1_1 = C4::Serials::GetLateOrMissingIssues( undef, $serial2->serialid ); + is( + output_pref( { str => $late_or_missing_issues_1_1[0]->{claimdate}, dateonly => 1 } ), $today, + 'Got the expected second different claim date from update claim' + ); + is( + $late_or_missing_issues_1_1[0]->{claims_count}, $claim_count_1 + 1, + 'Got the expected second claim count from update claim' + ); + is( $late_or_missing_issues_1_1[0]->{status}, 7, 'Got the expected second claim status from update claim' ); - my @late_or_missing_issues_1_2 = C4::Serials::GetLateOrMissingIssues(undef, $serial3->serialid); - is(output_pref({str => $late_or_missing_issues_1_2[0]->{claimdate}, dateonly => 1}), output_pref({ dt => $claimdate_1, dateonly => 1}), 'Got the expected unchanged claim date from update claim'); - is($late_or_missing_issues_1_2[0]->{claims_count}, $claim_count_1, 'Got the expected unchanged claim count from update claim'); - is($late_or_missing_issues_1_2[0]->{status}, 3, 'Got the expected unchanged claim status from update claim'); + my @late_or_missing_issues_1_2 = C4::Serials::GetLateOrMissingIssues( undef, $serial3->serialid ); + is( + output_pref( { str => $late_or_missing_issues_1_2[0]->{claimdate}, dateonly => 1 } ), + output_pref( { dt => $claimdate_1, dateonly => 1 } ), + 'Got the expected unchanged claim date from update claim' + ); + is( + $late_or_missing_issues_1_2[0]->{claims_count}, $claim_count_1, + 'Got the expected unchanged claim count from update claim' + ); + is( $late_or_missing_issues_1_2[0]->{status}, 3, 'Got the expected unchanged claim status from update claim' ); }; -is(C4::Serials::check_routing(), undef, 'test checking route'); -is(C4::Serials::check_routing($subscriptionid), 0, 'There should not have any routing list for the subscription'); +is( C4::Serials::check_routing(), undef, 'test checking route' ); +is( C4::Serials::check_routing($subscriptionid), 0, 'There should not have any routing list for the subscription' ); + # TODO really test this check_routing subroutine -is(C4::Serials::addroutingmember(),undef, 'test adding route member'); - +is( C4::Serials::addroutingmember(), undef, 'test adding route member' ); # Unit tests for statuses management (Bug 11689) $subscriptionid = NewSubscription( - undef, "", undef, undef, $budget_id, $biblionumber, - '2013-01-01', $frequency_id, undef, undef, undef, - undef, undef, undef, undef, undef, undef, - 1, $notes,undef, '2013-01-01', undef, $pattern_id, - undef, undef, 0, $internalnotes, 0, - undef, undef, 0, undef, '2013-12-31', 0 + undef, "", undef, undef, $budget_id, $biblionumber, + '2013-01-01', $frequency_id, undef, undef, undef, + undef, undef, undef, undef, undef, undef, + 1, $notes, undef, '2013-01-01', undef, $pattern_id, + undef, undef, 0, $internalnotes, 0, + undef, undef, 0, undef, '2013-12-31', 0 ); my $total_issues; -( $total_issues, @serials ) = C4::Serials::GetSerials( $subscriptionid ); +( $total_issues, @serials ) = C4::Serials::GetSerials($subscriptionid); is( $total_issues, 1, "NewSubscription created a first serial" ); -is( @serials, 1, "GetSerials returns the serial" ); +is( @serials, 1, "GetSerials returns the serial" ); my $subscription = C4::Serials::GetSubscription($subscriptionid); -my $pattern = C4::Serials::Numberpattern::GetSubscriptionNumberpattern($subscription->{numberpattern}); -( $total_issues, @serials ) = C4::Serials::GetSerials( $subscriptionid ); -my $publisheddate = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 }); -( $total_issues, @serials ) = C4::Serials::GetSerials( $subscriptionid ); -$frequency = C4::Serials::Frequency::GetSubscriptionFrequency($subscription->{periodicity}); -my $nextpublisheddate = C4::Serials::GetNextDate($subscription, $publisheddate, $frequency, 1); -my @statuses = qw( 2 2 3 3 3 3 3 4 4 41 42 43 44 5 ); +my $pattern = C4::Serials::Numberpattern::GetSubscriptionNumberpattern( $subscription->{numberpattern} ); +( $total_issues, @serials ) = C4::Serials::GetSerials($subscriptionid); +my $publisheddate = output_pref( { dt => dt_from_string, dateformat => 'iso', dateonly => 1 } ); +( $total_issues, @serials ) = C4::Serials::GetSerials($subscriptionid); +$frequency = C4::Serials::Frequency::GetSubscriptionFrequency( $subscription->{periodicity} ); +my $nextpublisheddate = C4::Serials::GetNextDate( $subscription, $publisheddate, $frequency, 1 ); +my @statuses = qw( 2 2 3 3 3 3 3 4 4 41 42 43 44 5 ); + # Add 14 serials my $counter = 0; -for my $status ( @statuses ) { - my $serialseq = "No.".$counter; - my ( $expected_serial ) = GetSerials2( $subscriptionid, [1] ); - C4::Serials::ModSerialStatus( $expected_serial->{serialid}, $serialseq, $publisheddate, $publisheddate, $publisheddate, $statuses[$counter], 'an useless note' ); +for my $status (@statuses) { + my $serialseq = "No." . $counter; + my ($expected_serial) = GetSerials2( $subscriptionid, [1] ); + C4::Serials::ModSerialStatus( + $expected_serial->{serialid}, $serialseq, $publisheddate, $publisheddate, + $publisheddate, $statuses[$counter], 'an useless note' + ); $counter++; } + # Here we have 15 serials with statuses : 2*2 + 5*3 + 2*4 + 1*41 + 1*42 + 1*43 + 1*44 + 1*5 + 1*1 -my @serialsByStatus = C4::Serials::findSerialsByStatus(2,$subscriptionid); -is(@serialsByStatus,2,"findSerialsByStatus returns all serials with chosen status"); -( $total_issues, @serials ) = C4::Serials::GetSerials( $subscriptionid ); +my @serialsByStatus = C4::Serials::findSerialsByStatus( 2, $subscriptionid ); +is( @serialsByStatus, 2, "findSerialsByStatus returns all serials with chosen status" ); +( $total_issues, @serials ) = C4::Serials::GetSerials($subscriptionid); is( $total_issues, @statuses + 1, "GetSerials returns total_issues" ); -my @arrived_missing = map { my $status = $_->{status}; ( grep { /^$status$/ } qw( 2 4 41 42 43 44 5 ) ) ? $_ : () } @serials; -my @others = map { my $status = $_->{status}; ( grep { /^$status$/ } qw( 2 4 41 42 43 44 5 ) ) ? () : $_ } @serials; +my @arrived_missing = map { + my $status = $_->{status}; + ( grep { /^$status$/ } qw( 2 4 41 42 43 44 5 ) ) ? $_ : () +} @serials; +my @others = map { + my $status = $_->{status}; + ( grep { /^$status$/ } qw( 2 4 41 42 43 44 5 ) ) ? () : $_ +} @serials; is( @arrived_missing, 5, "GetSerials returns 5 arrived/missing by default" ); -is( @others, 6, "GetSerials returns all serials not arrived and not missing" ); +is( @others, 6, "GetSerials returns all serials not arrived and not missing" ); ( $total_issues, @serials ) = C4::Serials::GetSerials( $subscriptionid, 10 ); is( $total_issues, @statuses + 1, "GetSerials returns total_issues" ); -@arrived_missing = map { my $status = $_->{status}; ( grep { /^$status$/ } qw( 2 4 41 42 43 44 5 ) ) ? $_ : () } @serials; -@others = map { my $status = $_->{status}; ( grep { /^$status$/ } qw( 2 4 41 42 43 44 5 ) ) ? () : $_ } @serials; +@arrived_missing = map { + my $status = $_->{status}; + ( grep { /^$status$/ } qw( 2 4 41 42 43 44 5 ) ) ? $_ : () +} @serials; +@others = map { + my $status = $_->{status}; + ( grep { /^$status$/ } qw( 2 4 41 42 43 44 5 ) ) ? () : $_ +} @serials; is( @arrived_missing, 9, "GetSerials returns all arrived/missing if count given" ); -is( @others, 6, "GetSerials returns all serials not arrived and not missing if count given" ); +is( @others, 6, "GetSerials returns all serials not arrived and not missing if count given" ); -$subscription = C4::Serials::GetSubscription($subscriptionid); # Retrieve the updated subscription +$subscription = C4::Serials::GetSubscription($subscriptionid); # Retrieve the updated subscription my @serialseqs; -for my $am ( @arrived_missing ) { - if ( grep {/^$am->{status}$/} qw( 4 41 42 43 44 ) ) { - push @serialseqs, $am->{serialseq} - } elsif ( grep {/^$am->{status}$/} qw( 5 ) ) { +for my $am (@arrived_missing) { + if ( grep { /^$am->{status}$/ } qw( 4 41 42 43 44 ) ) { + push @serialseqs, $am->{serialseq}; + } elsif ( grep { /^$am->{status}$/ } qw( 5 ) ) { push @serialseqs, 'not issued ' . $am->{serialseq}; } } -is( $subscription->{missinglist}, join('; ', @serialseqs), "subscription missinglist is updated after ModSerialStatus" ); +is( + $subscription->{missinglist}, join( '; ', @serialseqs ), + "subscription missinglist is updated after ModSerialStatus" +); subtest "Do not generate an expected if one already exists" => sub { plan tests => 2; @@ -540,16 +612,25 @@ subtest "Do not generate an expected if one already exists" => sub { my $serialexpected = ( C4::Serials::findSerialsByStatus( 1, $subscriptionid ) )[0]; #delete serial with status Expected - C4::Serials::ModSerialStatus( $serialexpected->{serialid}, $serialexpected->{serialseq}, $publisheddate, $publisheddate, $publisheddate, '1', 'an useless note' ); + C4::Serials::ModSerialStatus( + $serialexpected->{serialid}, $serialexpected->{serialseq}, $publisheddate, + $publisheddate, $publisheddate, '1', 'an useless note' + ); @serialsByStatus = C4::Serials::findSerialsByStatus( 1, $subscriptionid ); is( @serialsByStatus, 1, "ModSerialStatus delete corectly serial expected and create another if not exist" ); # add 1 serial with status=Expected 1 - C4::Serials::ModSerialStatus( $expected_serial->{serialid}, 'NO.20', $publisheddate, $publisheddate, $publisheddate, '1', 'an useless note' ); + C4::Serials::ModSerialStatus( + $expected_serial->{serialid}, 'NO.20', $publisheddate, $publisheddate, + $publisheddate, '1', 'an useless note' + ); #Now we have two serials it have status expected #put status delete for last serial - C4::Serials::ModSerialStatus( $serialexpected->{serialid}, $serialexpected->{serialseq}, $publisheddate, $publisheddate, $publisheddate, '1', 'an useless note' ); + C4::Serials::ModSerialStatus( + $serialexpected->{serialid}, $serialexpected->{serialseq}, $publisheddate, + $publisheddate, $publisheddate, '1', 'an useless note' + ); #try if create or not another serial with status is expected @serialsByStatus = C4::Serials::findSerialsByStatus( 1, $subscriptionid ); @@ -562,49 +643,62 @@ subtest "PreserveSerialNotes preference" => sub { t::lib::Mocks::mock_preference( 'PreserveSerialNotes', 1 ); - C4::Serials::ModSerialStatus( $expected_serial->{serialid}, 'NO.20', $publisheddate, $publisheddate, $publisheddate, '1', 'an useless note' ); + C4::Serials::ModSerialStatus( + $expected_serial->{serialid}, 'NO.20', $publisheddate, $publisheddate, + $publisheddate, '1', 'an useless note' + ); @serialsByStatus = C4::Serials::findSerialsByStatus( 1, $subscriptionid ); - is( $serialsByStatus[0]->{note},$expected_serial->{note}, "note passed through if supposed to"); + is( $serialsByStatus[0]->{note}, $expected_serial->{note}, "note passed through if supposed to" ); t::lib::Mocks::mock_preference( 'PreserveSerialNotes', 0 ); $expected_serial = $serialsByStatus[0]; - C4::Serials::ModSerialStatus( $expected_serial->{serialid}, 'NO.20', $publisheddate, $publisheddate, $publisheddate, '1', 'an useless note' ); - is( $serialsByStatus[0]->{note},$expected_serial->{note}, "note not passed through if not supposed to"); + C4::Serials::ModSerialStatus( + $expected_serial->{serialid}, 'NO.20', $publisheddate, $publisheddate, + $publisheddate, '1', 'an useless note' + ); + is( $serialsByStatus[0]->{note}, $expected_serial->{note}, "note not passed through if not supposed to" ); }; subtest "NewSubscription|ModSubscription" => sub { plan tests => 4; my $subscriptionid = NewSubscription( - "", "", "", "", $budget_id, $biblionumber, - '2013-01-01', $frequency_id, "", "", "", - "", "", "", "", "", "", - 1, $notes,"", '2013-01-01', "", $pattern_id, - "", "", 0, $internalnotes, 0, - "", "", 0, "", '2013-12-31', 0 + "", "", "", "", $budget_id, $biblionumber, + '2013-01-01', $frequency_id, "", "", "", + "", "", "", "", "", "", + 1, $notes, "", '2013-01-01', "", $pattern_id, + "", "", 0, $internalnotes, 0, + "", "", 0, "", '2013-12-31', 0 ); - ok($subscriptionid, "Sending empty string instead of undef to reflect use of the interface"); + ok( $subscriptionid, "Sending empty string instead of undef to reflect use of the interface" ); my $subscription = Koha::Subscriptions->find($subscriptionid); - my $serials = Koha::Serials->search({ subscriptionid => $subscriptionid }); + my $serials = Koha::Serials->search( { subscriptionid => $subscriptionid } ); is( $serials->count, 1, "NewSubscription created a first serial" ); - my $biblio_2 = $builder->build_sample_biblio; + my $biblio_2 = $builder->build_sample_biblio; my $subscription_info = $subscription->unblessed; $subscription_info->{biblionumber} = $biblio_2->biblionumber; - ModSubscription( @$subscription_info{qw( - librarian branchcode aqbooksellerid cost aqbudgetid startdate - periodicity firstacquidate irregularity numberpattern locale - numberlength weeklength monthlength lastvalue1 innerloop1 lastvalue2 - innerloop2 lastvalue3 innerloop3 status biblionumber callnumber notes - letter manualhistory internalnotes serialsadditems staffdisplaycount - opacdisplaycount graceperiod location enddate subscriptionid - skip_serialseq - )} ); + ModSubscription( + @$subscription_info{ + qw( + librarian branchcode aqbooksellerid cost aqbudgetid startdate + periodicity firstacquidate irregularity numberpattern locale + numberlength weeklength monthlength lastvalue1 innerloop1 lastvalue2 + innerloop2 lastvalue3 innerloop3 status biblionumber callnumber notes + letter manualhistory internalnotes serialsadditems staffdisplaycount + opacdisplaycount graceperiod location enddate subscriptionid + skip_serialseq + ) + } + ); - $serials = Koha::Serials->search({ subscriptionid => $subscriptionid }); + $serials = Koha::Serials->search( { subscriptionid => $subscriptionid } ); is( $serials->count, 1, "Still only one serial" ); - is( $serials->next->biblionumber, $biblio_2->biblionumber, 'ModSubscription should have updated serial.biblionumber'); + is( + $serials->next->biblionumber, $biblio_2->biblionumber, + 'ModSubscription should have updated serial.biblionumber' + ); }; subtest "test numbering pattern with dates in GetSeq GetNextSeq" => sub { @@ -647,17 +741,17 @@ subtest "_numeration" => sub { plan tests => 6; - my $s = C4::Serials::_numeration(0, 'monthname', 'cat'); + my $s = C4::Serials::_numeration( 0, 'monthname', 'cat' ); is( $s, "gener" ); - $s = C4::Serials::_numeration(0, 'monthname', 'es'); + $s = C4::Serials::_numeration( 0, 'monthname', 'es' ); is( $s, "enero" ); - $s = C4::Serials::_numeration(0, 'monthname', 'fr'); + $s = C4::Serials::_numeration( 0, 'monthname', 'fr' ); is( $s, "janvier" ); - $s = C4::Serials::_numeration(0, 'monthabrv', 'cat'); + $s = C4::Serials::_numeration( 0, 'monthabrv', 'cat' ); is( $s, "de gen." ); - $s = C4::Serials::_numeration(0, 'monthabrv', 'es'); + $s = C4::Serials::_numeration( 0, 'monthabrv', 'es' ); like( $s, qr{^ene\.?} ); - $s = C4::Serials::_numeration(0, 'monthabrv', 'fr'); + $s = C4::Serials::_numeration( 0, 'monthabrv', 'fr' ); is( $s, "janv." ); }; diff --git a/t/db_dependent/Serials/Claims.t b/t/db_dependent/Serials/Claims.t index afc3a18e66..47113a6372 100755 --- a/t/db_dependent/Serials/Claims.t +++ b/t/db_dependent/Serials/Claims.t @@ -5,7 +5,7 @@ use C4::Acquisition; use C4::Budgets qw( AddBudgetPeriod AddBudget ); use Koha::Database; use Koha::Acquisition::Booksellers; -use_ok('C4::Serials', qw( GetSuppliersWithLateIssues NewSubscription GetLateOrMissingIssues updateClaim )); +use_ok( 'C4::Serials', qw( GetSuppliersWithLateIssues NewSubscription GetLateOrMissingIssues updateClaim ) ); use Koha::DateUtils qw( dt_from_string output_pref ); @@ -17,22 +17,26 @@ $dbh->do(q|DELETE FROM issues|); $dbh->do(q|DELETE FROM subscription|); my $branchcode = 'CPL'; -my $bpid = AddBudgetPeriod({ - budget_period_startdate => '2015-01-01', - budget_period_enddate => '2015-12-31', - budget_period_description => "budget desc" -}); +my $bpid = AddBudgetPeriod( + { + budget_period_startdate => '2015-01-01', + budget_period_enddate => '2015-12-31', + budget_period_description => "budget desc" + } +); -my $budget_id = AddBudget({ - budget_code => "ABCD", - budget_amount => "123.132", - budget_name => "Périodiques", - budget_notes => "This is a note", - budget_period_id => $bpid -}); +my $budget_id = AddBudget( + { + budget_code => "ABCD", + budget_amount => "123.132", + budget_name => "Périodiques", + budget_notes => "This is a note", + budget_period_id => $bpid + } +); my $record = MARC::Record->new(); -my ( $biblionumber, $biblioitemnumber ) = C4::Biblio::AddBiblio($record, ''); +my ( $biblionumber, $biblioitemnumber ) = C4::Biblio::AddBiblio( $record, '' ); my $sample_supplier1 = { name => 'Name1', @@ -49,7 +53,7 @@ my $sample_supplier1 = { gstreg => 1, listincgst => 1, invoiceincgst => 1, - tax_rate => '1.0000', + tax_rate => '1.0000', discount => '1.0000', notes => 'notes1', deliverytime => undef @@ -69,96 +73,98 @@ my $sample_supplier2 = { gstreg => 1, listincgst => 1, invoiceincgst => 1, - tax_rate => '2.0000', + tax_rate => '2.0000', discount => '2.0000', notes => 'notes2', deliverytime => 2 }; -my $supplier1 = Koha::Acquisition::Bookseller->new($sample_supplier1)->store; -my $supplier2 = Koha::Acquisition::Bookseller->new($sample_supplier2)->store; +my $supplier1 = Koha::Acquisition::Bookseller->new($sample_supplier1)->store; +my $supplier2 = Koha::Acquisition::Bookseller->new($sample_supplier2)->store; my $supplier_id1 = $supplier1->id; my $supplier_id2 = $supplier2->id; my $supplierlist = eval { GetSuppliersWithLateIssues() }; -is( length($@), 0, "No SQL problem in GetSuppliersWithLateIssues" ); -is ( scalar(@$supplierlist), 0, 'There is no late issues yet'); +is( length($@), 0, "No SQL problem in GetSuppliersWithLateIssues" ); +is( scalar(@$supplierlist), 0, 'There is no late issues yet' ); my $subscriptionid_not_late = NewSubscription( - undef, $branchcode, $supplier_id1, undef, $budget_id, $biblionumber, - '2013-01-01', undef, undef, undef, undef, - undef, undef, undef, undef, undef, undef, - 1, "notes",undef, '9999-01-01', undef, undef, - undef, undef, 0, "intnotes", 0, - undef, undef, 0, undef, '2013-12-31', 0 + undef, $branchcode, $supplier_id1, undef, $budget_id, $biblionumber, + '2013-01-01', undef, undef, undef, undef, + undef, undef, undef, undef, undef, undef, + 1, "notes", undef, '9999-01-01', undef, undef, + undef, undef, 0, "intnotes", 0, + undef, undef, 0, undef, '2013-12-31', 0 ); $supplierlist = GetSuppliersWithLateIssues(); -is ( scalar(@$supplierlist), 0, 'There is still no late issues yet'); +is( scalar(@$supplierlist), 0, 'There is still no late issues yet' ); my $subscriptionid_inlate1 = NewSubscription( - undef, $branchcode, $supplier_id1, undef, $budget_id, $biblionumber, - '2013-01-01', undef, undef, undef, undef, - undef, undef, undef, undef, undef, undef, - 1, "notes",undef, '2013-01-01', undef, undef, - undef, undef, 0, "intnotes", 0, - undef, undef, 0, undef, '2013-12-31', 0 + undef, $branchcode, $supplier_id1, undef, $budget_id, $biblionumber, + '2013-01-01', undef, undef, undef, undef, + undef, undef, undef, undef, undef, undef, + 1, "notes", undef, '2013-01-01', undef, undef, + undef, undef, 0, "intnotes", 0, + undef, undef, 0, undef, '2013-12-31', 0 ); my $subscriptionid_inlate2 = NewSubscription( - undef, $branchcode, $supplier_id2, undef, $budget_id, $biblionumber, - '2013-01-01', undef, undef, undef, undef, - undef, undef, undef, undef, undef, undef, - 1, "notes",undef, '2013-01-01', undef, undef, - undef, undef, 0, "intnotes", 0, - undef, undef, 0, undef, '2013-12-31', 0 + undef, $branchcode, $supplier_id2, undef, $budget_id, $biblionumber, + '2013-01-01', undef, undef, undef, undef, + undef, undef, undef, undef, undef, undef, + 1, "notes", undef, '2013-01-01', undef, undef, + undef, undef, 0, "intnotes", 0, + undef, undef, 0, undef, '2013-12-31', 0 ); my $subscriptionid_inlate3 = NewSubscription( - undef, $branchcode, $supplier_id2, undef, $budget_id, $biblionumber, - '2013-01-02', undef, undef, undef, undef, - undef, undef, undef, undef, undef, undef, - 1, "notes",undef, '2013-01-02', undef, undef, - undef, undef, 0, "intnotes", 0, - undef, undef, 0, undef, '2013-12-31', 0 + undef, $branchcode, $supplier_id2, undef, $budget_id, $biblionumber, + '2013-01-02', undef, undef, undef, undef, + undef, undef, undef, undef, undef, undef, + 1, "notes", undef, '2013-01-02', undef, undef, + undef, undef, 0, "intnotes", 0, + undef, undef, 0, undef, '2013-12-31', 0 ); - $supplierlist = GetSuppliersWithLateIssues(); -is ( scalar(@$supplierlist), 2, '2 suppliers should have issues in late'); +is( scalar(@$supplierlist), 2, '2 suppliers should have issues in late' ); is( GetLateOrMissingIssues(), undef, 'GetLateOrMissingIssues should return undef without parameter' ); -my @late_or_missing_issues = GetLateOrMissingIssues( $supplier_id1 ); +my @late_or_missing_issues = GetLateOrMissingIssues($supplier_id1); is( scalar(@late_or_missing_issues), 1, 'supplier 1 should have 1 issue in late' ); -@late_or_missing_issues = GetLateOrMissingIssues( $supplier_id2); +@late_or_missing_issues = GetLateOrMissingIssues($supplier_id2); is( scalar(@late_or_missing_issues), 2, 'supplier 2 should have 2 issues in late' ); -is( exists $late_or_missing_issues[0]->{claimdate}, 1, 'GetLateOrMissingIssues returns claimdate' ); +is( exists $late_or_missing_issues[0]->{claimdate}, 1, 'GetLateOrMissingIssues returns claimdate' ); is( exists $late_or_missing_issues[0]->{claims_count}, 1, 'GetLateOrMissingIssues returns claims_count' ); -is( $late_or_missing_issues[0]->{claims_count}, 0, 'The issues should not habe been claimed yet' ); +is( $late_or_missing_issues[0]->{claims_count}, 0, 'The issues should not habe been claimed yet' ); is( updateClaim(), undef, 'updateClaim should return undef if not param passed' ); my $serialid_to_claim = $late_or_missing_issues[0]->{serialid}; -updateClaim( $serialid_to_claim ); +updateClaim($serialid_to_claim); -@late_or_missing_issues = GetLateOrMissingIssues( $supplier_id2); -is( scalar(@late_or_missing_issues), 2, 'supplier 2 should have 2 issues in late (already claimed issues are returns)' ); +@late_or_missing_issues = GetLateOrMissingIssues($supplier_id2); +is( + scalar(@late_or_missing_issues), 2, + 'supplier 2 should have 2 issues in late (already claimed issues are returns)' +); -my ( $serial_claimed ) = grep { ($_->{serialid} == $serialid_to_claim) ? $_ : () } @late_or_missing_issues; +my ($serial_claimed) = grep { ( $_->{serialid} == $serialid_to_claim ) ? $_ : () } @late_or_missing_issues; is( $serial_claimed->{claims_count}, 1, 'The serial should have been claimed' ); my @serials_to_claim = map { $_->{serialid} } @late_or_missing_issues; updateClaim( \@serials_to_claim ); -@late_or_missing_issues = GetLateOrMissingIssues( $supplier_id2); +@late_or_missing_issues = GetLateOrMissingIssues($supplier_id2); is( scalar(@late_or_missing_issues), 2, 'supplier 2 should have 2 issues in late' ); -( $serial_claimed ) = grep { ($_->{serialid} == $serials_to_claim[0]) ? $_ : () } @late_or_missing_issues; +($serial_claimed) = grep { ( $_->{serialid} == $serials_to_claim[0] ) ? $_ : () } @late_or_missing_issues; is( $serial_claimed->{claims_count}, 2, 'The serial should have been claimed' ); -( $serial_claimed ) = grep { ($_->{serialid} == $serials_to_claim[1]) ? $_ : () } @late_or_missing_issues; +($serial_claimed) = grep { ( $_->{serialid} == $serials_to_claim[1] ) ? $_ : () } @late_or_missing_issues; is( $serial_claimed->{claims_count}, 1, 'The serial should have been claimed' ); +my $today = output_pref( { dt => dt_from_string, dateformat => 'iso', dateonly => 1 } ); -my $today = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 }); # FIXME: This test should pass. The GetLateOrMissingIssues should not deal with date format! #is( $serial_claimed->{claimdate}, $today, 'The serial should have been claimed today' ); diff --git a/t/db_dependent/Serials/Frequency.t b/t/db_dependent/Serials/Frequency.t index 02a64f7f99..4d2925e9c9 100755 --- a/t/db_dependent/Serials/Frequency.t +++ b/t/db_dependent/Serials/Frequency.t @@ -8,81 +8,86 @@ use Modern::Perl; my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; -use C4::Serials::Frequency qw( GetSubscriptionFrequencies DelSubscriptionFrequency GetSubscriptionFrequency ModSubscriptionFrequency AddSubscriptionFrequency ); +use C4::Serials::Frequency + qw( GetSubscriptionFrequencies DelSubscriptionFrequency GetSubscriptionFrequency ModSubscriptionFrequency AddSubscriptionFrequency ); # Start by deleting all frequencies. my @frequencies = GetSubscriptionFrequencies(); foreach my $f (@frequencies) { - DelSubscriptionFrequency($f->{id}); + DelSubscriptionFrequency( $f->{id} ); } @frequencies = GetSubscriptionFrequencies(); -is(scalar @frequencies, 0, "There is no frequencies in database"); +is( scalar @frequencies, 0, "There is no frequencies in database" ); my $frequency = GetSubscriptionFrequency(1); -is($frequency, undef, "GetSubscriptionFrequency(1) returns undef"); +is( $frequency, undef, "GetSubscriptionFrequency(1) returns undef" ); my $rv = ModSubscriptionFrequency($frequency); -is($rv, undef, "ModSubscriptionFrequency(undef) returns undef"); +is( $rv, undef, "ModSubscriptionFrequency(undef) returns undef" ); $frequency = {}; -$rv = ModSubscriptionFrequency($frequency); -is($rv, undef, "ModSubscriptionFrequency({}) returns undef"); +$rv = ModSubscriptionFrequency($frequency); +is( $rv, undef, "ModSubscriptionFrequency({}) returns undef" ); + # returns 0 because id doesn't exist $frequency = { id => 1, description => "Test frequency 1" }; -$rv = ModSubscriptionFrequency($frequency); -is($rv, '0E0', "ModSubscriptionFrequency({id=1,description=>'Test frequency 1'}) returns '0 but true'"); +$rv = ModSubscriptionFrequency($frequency); +is( $rv, '0E0', "ModSubscriptionFrequency({id=1,description=>'Test frequency 1'}) returns '0 but true'" ); $frequency = undef; my $id = AddSubscriptionFrequency($frequency); -is($id, undef, "AddSubscriptionFrequency(undef) returns undef"); +is( $id, undef, "AddSubscriptionFrequency(undef) returns undef" ); $frequency = {}; -$id = AddSubscriptionFrequency($frequency); -is($id, undef, "AddSubscriptionFrequency({}) returns undef"); +$id = AddSubscriptionFrequency($frequency); +is( $id, undef, "AddSubscriptionFrequency({}) returns undef" ); $frequency = { description => "Test frequency 1" }; -$id = AddSubscriptionFrequency($frequency); -ok((defined($id) && ($id > 0)), "AddSubscriptionFrequency({description => 'Test frequency 1'}) returns frequency id"); +$id = AddSubscriptionFrequency($frequency); +ok( + ( defined($id) && ( $id > 0 ) ), + "AddSubscriptionFrequency({description => 'Test frequency 1'}) returns frequency id" +); $frequency = GetSubscriptionFrequency($id); -isa_ok($frequency, 'HASH', "GetSubscriptionFrequency($id)"); -is($frequency->{description}, "Test frequency 1", "description OK"); -is($frequency->{unit}, undef, "unit OK"); -is($frequency->{issuesperunit}, 1, "issuesperunit OK"); -is($frequency->{unitsperissue}, 1, "unitsperissue OK"); -is($frequency->{expectedissuesayear}, undef, "expectedissuesayear OK"); -is($frequency->{displayorder}, undef, "displayorder OK"); +isa_ok( $frequency, 'HASH', "GetSubscriptionFrequency($id)" ); +is( $frequency->{description}, "Test frequency 1", "description OK" ); +is( $frequency->{unit}, undef, "unit OK" ); +is( $frequency->{issuesperunit}, 1, "issuesperunit OK" ); +is( $frequency->{unitsperissue}, 1, "unitsperissue OK" ); +is( $frequency->{expectedissuesayear}, undef, "expectedissuesayear OK" ); +is( $frequency->{displayorder}, undef, "displayorder OK" ); -$frequency->{description} = $frequency->{description} . " (modified)"; -$frequency->{unit} = 'day'; +$frequency->{description} = $frequency->{description} . " (modified)"; +$frequency->{unit} = 'day'; $frequency->{unitsperissue} = 3; -$frequency->{displayorder} = 1; -$rv = ModSubscriptionFrequency($frequency); -is($rv, 1, "ModSubscriptionFrequency(\$frequency) returns 1"); +$frequency->{displayorder} = 1; +$rv = ModSubscriptionFrequency($frequency); +is( $rv, 1, "ModSubscriptionFrequency(\$frequency) returns 1" ); $frequency = GetSubscriptionFrequency($id); -isa_ok($frequency, 'HASH', "GetSubscriptionFrequency($id)"); -is($frequency->{description}, "Test frequency 1 (modified)", "description OK"); -is($frequency->{unit}, 'day', "unit OK"); -is($frequency->{issuesperunit}, 1, "issuesperunit OK"); -is($frequency->{unitsperissue}, 3, "unitsperissue OK"); -is($frequency->{expectedissuesayear}, undef, "expectedissuesayear OK"); -is($frequency->{displayorder}, 1, "displayorder OK"); +isa_ok( $frequency, 'HASH', "GetSubscriptionFrequency($id)" ); +is( $frequency->{description}, "Test frequency 1 (modified)", "description OK" ); +is( $frequency->{unit}, 'day', "unit OK" ); +is( $frequency->{issuesperunit}, 1, "issuesperunit OK" ); +is( $frequency->{unitsperissue}, 3, "unitsperissue OK" ); +is( $frequency->{expectedissuesayear}, undef, "expectedissuesayear OK" ); +is( $frequency->{displayorder}, 1, "displayorder OK" ); @frequencies = GetSubscriptionFrequencies(); -is(scalar @frequencies, 1, "There is one frequency"); +is( scalar @frequencies, 1, "There is one frequency" ); # Add another frequency undef $frequency->{id}; my $id2 = AddSubscriptionFrequency($frequency); @frequencies = GetSubscriptionFrequencies(); -is(scalar @frequencies, 2, "There are two frequencies"); +is( scalar @frequencies, 2, "There are two frequencies" ); # Delete one frequency DelSubscriptionFrequency($id); @frequencies = GetSubscriptionFrequencies(); -is(scalar @frequencies, 1, "There is one frequency"); +is( scalar @frequencies, 1, "There is one frequency" ); # Delete the other frequency DelSubscriptionFrequency($id2); @frequencies = GetSubscriptionFrequencies(); -is(scalar @frequencies, 0, "There is no frequency"); +is( scalar @frequencies, 0, "There is no frequency" ); diff --git a/t/db_dependent/Serials/GetFictiveIssueNumber.t b/t/db_dependent/Serials/GetFictiveIssueNumber.t index 5a5e6b0057..3e3b361220 100755 --- a/t/db_dependent/Serials/GetFictiveIssueNumber.t +++ b/t/db_dependent/Serials/GetFictiveIssueNumber.t @@ -9,7 +9,7 @@ use Koha::Database; use C4::Serials qw( GetFictiveIssueNumber GetSubscription ); use C4::Serials::Frequency; -my $schema = Koha::Database->new->schema; +my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; my $dbh = C4::Context->dbh; @@ -17,89 +17,99 @@ subtest 'Tests for irregular frequency' => sub { plan tests => 2; # Add a frequency - my $freq_irr = AddSubscriptionFrequency({ - description => "Irregular", - unit => undef, - }); + my $freq_irr = AddSubscriptionFrequency( + { + description => "Irregular", + unit => undef, + } + ); # Test it my $subscription = { - periodicity => $freq_irr, + periodicity => $freq_irr, firstacquidate => '1972-02-07', }; - is( C4::Serials::GetFictiveIssueNumber($subscription, '1972-12-31'), undef, 'Irregular: should be undef' ); - is( C4::Serials::GetFictiveIssueNumber($subscription, '1973-12-31'), undef, 'Irregular: still undef' ); + is( C4::Serials::GetFictiveIssueNumber( $subscription, '1972-12-31' ), undef, 'Irregular: should be undef' ); + is( C4::Serials::GetFictiveIssueNumber( $subscription, '1973-12-31' ), undef, 'Irregular: still undef' ); }; subtest 'Tests for yearly frequencies' => sub { plan tests => 10; # First add a few frequencies - my $freq_1i_1y = AddSubscriptionFrequency({ - description => "1 issue per year", - unit => 'year', - issuesperunit => 1, - unitsperissue => 1, - }); - my $freq_1i_3y = AddSubscriptionFrequency({ - description => "1 issue per 3 years", - unit => 'year', - issuesperunit => 1, - unitsperissue => 3, - }); - my $freq_5i_1y = AddSubscriptionFrequency({ - description => "5 issues per year", - unit => 'year', - issuesperunit => 5, - unitsperissue => 1, - }); - my $freq_366i_1y = AddSubscriptionFrequency({ - description => "366 issue per year", - unit => 'year', - issuesperunit => 366, - unitsperissue => 1, - }); + my $freq_1i_1y = AddSubscriptionFrequency( + { + description => "1 issue per year", + unit => 'year', + issuesperunit => 1, + unitsperissue => 1, + } + ); + my $freq_1i_3y = AddSubscriptionFrequency( + { + description => "1 issue per 3 years", + unit => 'year', + issuesperunit => 1, + unitsperissue => 3, + } + ); + my $freq_5i_1y = AddSubscriptionFrequency( + { + description => "5 issues per year", + unit => 'year', + issuesperunit => 5, + unitsperissue => 1, + } + ); + my $freq_366i_1y = AddSubscriptionFrequency( + { + description => "366 issue per year", + unit => 'year', + issuesperunit => 366, + unitsperissue => 1, + } + ); # TEST CASE - 1 issue per year my $subscription = { - periodicity => $freq_1i_1y, - firstacquidate => '1972-02-10', + periodicity => $freq_1i_1y, + firstacquidate => '1972-02-10', countissuesperunit => 1, }; my $frequency = GetSubscriptionFrequency($freq_1i_1y); - is( C4::Serials::GetFictiveIssueNumber($subscription, '1973-02-09', $frequency), 1, 'Feb 9 still 1' ); - is( C4::Serials::GetFictiveIssueNumber($subscription, '1973-02-10', $frequency), 2, 'Feb 10 goes to 2' ); + is( C4::Serials::GetFictiveIssueNumber( $subscription, '1973-02-09', $frequency ), 1, 'Feb 9 still 1' ); + is( C4::Serials::GetFictiveIssueNumber( $subscription, '1973-02-10', $frequency ), 2, 'Feb 10 goes to 2' ); # TEST CASE - 1 issue per 3 years - $subscription->{periodicity} = $freq_1i_3y; + $subscription->{periodicity} = $freq_1i_3y; $subscription->{firstacquidate} = '1972-02-20'; - $frequency = GetSubscriptionFrequency($freq_1i_3y); - is( C4::Serials::GetFictiveIssueNumber($subscription, '1975-02-19', $frequency), 1, 'Feb 19, 1975 still 1' ); - is( C4::Serials::GetFictiveIssueNumber($subscription, '1975-02-20', $frequency), 2, 'Feb 20, 1975 goes to 2' ); + $frequency = GetSubscriptionFrequency($freq_1i_3y); + is( C4::Serials::GetFictiveIssueNumber( $subscription, '1975-02-19', $frequency ), 1, 'Feb 19, 1975 still 1' ); + is( C4::Serials::GetFictiveIssueNumber( $subscription, '1975-02-20', $frequency ), 2, 'Feb 20, 1975 goes to 2' ); # TEST CASE - 5 issues per year - $subscription->{periodicity} = $freq_5i_1y; - $subscription->{firstacquidate} = '1972-02-29'; #leap year + $subscription->{periodicity} = $freq_5i_1y; + $subscription->{firstacquidate} = '1972-02-29'; #leap year $subscription->{countissuesperunit} = 1; - $frequency = GetSubscriptionFrequency($freq_5i_1y); - is( C4::Serials::GetFictiveIssueNumber($subscription, '1972-05-11', $frequency), 1, 'May 11 still 1' ); + $frequency = GetSubscriptionFrequency($freq_5i_1y); + is( C4::Serials::GetFictiveIssueNumber( $subscription, '1972-05-11', $frequency ), 1, 'May 11 still 1' ); $subscription->{countissuesperunit} = 2; - is( C4::Serials::GetFictiveIssueNumber($subscription, '1972-05-12', $frequency), 2, 'May 12 goes to 2' ); + is( C4::Serials::GetFictiveIssueNumber( $subscription, '1972-05-12', $frequency ), 2, 'May 12 goes to 2' ); $subscription->{countissuesperunit} = 5; - is( C4::Serials::GetFictiveIssueNumber($subscription, '1973-02-27', $frequency), 5, 'Feb 27 should still be 5' ); + is( C4::Serials::GetFictiveIssueNumber( $subscription, '1973-02-27', $frequency ), 5, 'Feb 27 should still be 5' ); $subscription->{countissuesperunit} = 1; - is( C4::Serials::GetFictiveIssueNumber($subscription, '1973-02-28', $frequency), 6, 'Feb 28 goes to 6' ); + is( C4::Serials::GetFictiveIssueNumber( $subscription, '1973-02-28', $frequency ), 6, 'Feb 28 goes to 6' ); # TEST CASE - 366 issues per year (hypothetical example) # Testing prevention of divide by zero - $subscription->{periodicity} = $freq_366i_1y; - $subscription->{firstacquidate} = '1972-02-29'; #leap year + $subscription->{periodicity} = $freq_366i_1y; + $subscription->{firstacquidate} = '1972-02-29'; #leap year $subscription->{countissuesperunit} = 366; - $frequency = GetSubscriptionFrequency($freq_366i_1y); - is( C4::Serials::GetFictiveIssueNumber($subscription, '1973-02-27', $frequency), 366, 'Feb 27 still at 366' ); - is( C4::Serials::GetFictiveIssueNumber($subscription, '1973-02-28', $frequency), 732, 'Feb 28 goes to 732' ); + $frequency = GetSubscriptionFrequency($freq_366i_1y); + is( C4::Serials::GetFictiveIssueNumber( $subscription, '1973-02-27', $frequency ), 366, 'Feb 27 still at 366' ); + is( C4::Serials::GetFictiveIssueNumber( $subscription, '1973-02-28', $frequency ), 732, 'Feb 28 goes to 732' ); }; @@ -107,45 +117,49 @@ subtest 'Tests for monthly frequencies' => sub { plan tests => 8; # First add a few frequencies - my $freq_1i_5m = AddSubscriptionFrequency({ - description => "1 issue per 5 months", - unit => 'month', - issuesperunit => 1, - unitsperissue => 5, - }); - my $freq_4i_1m = AddSubscriptionFrequency({ - description => "4 issue per month", - unit => 'month', - issuesperunit => 4, - unitsperissue => 1, - }); + my $freq_1i_5m = AddSubscriptionFrequency( + { + description => "1 issue per 5 months", + unit => 'month', + issuesperunit => 1, + unitsperissue => 5, + } + ); + my $freq_4i_1m = AddSubscriptionFrequency( + { + description => "4 issue per month", + unit => 'month', + issuesperunit => 4, + unitsperissue => 1, + } + ); # TEST CASE - 1 issue per 5 months my $subscription = { - periodicity => $freq_1i_5m, - firstacquidate => '1972-02-10', + periodicity => $freq_1i_5m, + firstacquidate => '1972-02-10', countissuesperunit => 1, }; my $frequency = GetSubscriptionFrequency($freq_1i_5m); - is( C4::Serials::GetFictiveIssueNumber($subscription, '1972-07-09', $frequency), 1, 'Jul 9 still 1' ); - is( C4::Serials::GetFictiveIssueNumber($subscription, '1972-07-10', $frequency), 2, 'Jul 10 goes to 2' ); - is( C4::Serials::GetFictiveIssueNumber($subscription, '1973-05-09', $frequency), 3, 'May 9 still 3' ); - is( C4::Serials::GetFictiveIssueNumber($subscription, '1973-05-10', $frequency), 4, 'May 10 goes to 4' ); + is( C4::Serials::GetFictiveIssueNumber( $subscription, '1972-07-09', $frequency ), 1, 'Jul 9 still 1' ); + is( C4::Serials::GetFictiveIssueNumber( $subscription, '1972-07-10', $frequency ), 2, 'Jul 10 goes to 2' ); + is( C4::Serials::GetFictiveIssueNumber( $subscription, '1973-05-09', $frequency ), 3, 'May 9 still 3' ); + is( C4::Serials::GetFictiveIssueNumber( $subscription, '1973-05-10', $frequency ), 4, 'May 10 goes to 4' ); # TEST CASE - 4 issue per 1 months $subscription = { - periodicity => $freq_4i_1m, - firstacquidate => '1972-02-22', + periodicity => $freq_4i_1m, + firstacquidate => '1972-02-22', countissuesperunit => 1, }; $frequency = GetSubscriptionFrequency($freq_4i_1m); - is( C4::Serials::GetFictiveIssueNumber($subscription, '1972-02-28', $frequency), 1, 'Feb 28 still 1' ); + is( C4::Serials::GetFictiveIssueNumber( $subscription, '1972-02-28', $frequency ), 1, 'Feb 28 still 1' ); $subscription->{countissuesperunit} = 2; - is( C4::Serials::GetFictiveIssueNumber($subscription, '1972-02-29', $frequency), 2, 'Feb 29 goes to 2' ); + is( C4::Serials::GetFictiveIssueNumber( $subscription, '1972-02-29', $frequency ), 2, 'Feb 29 goes to 2' ); $subscription->{countissuesperunit} = 4; - is( C4::Serials::GetFictiveIssueNumber($subscription, '1972-03-21', $frequency), 4, 'Mar 21 still 4' ); + is( C4::Serials::GetFictiveIssueNumber( $subscription, '1972-03-21', $frequency ), 4, 'Mar 21 still 4' ); $subscription->{countissuesperunit} = 1; - is( C4::Serials::GetFictiveIssueNumber($subscription, '1972-03-22', $frequency), 5, 'Mar 22 goes to 5' ); + is( C4::Serials::GetFictiveIssueNumber( $subscription, '1972-03-22', $frequency ), 5, 'Mar 22 goes to 5' ); }; @@ -153,80 +167,88 @@ subtest 'Tests for weekly frequencies' => sub { plan tests => 4; # First add a few frequencies - my $freq_1i_7w = AddSubscriptionFrequency({ - description => "1 issue per 7 weeks", - unit => 'week', - issuesperunit => 1, - unitsperissue => 7, - }); - my $freq_3i_1w = AddSubscriptionFrequency({ - description => "3 issues per week", - unit => 'week', - issuesperunit => 3, - unitsperissue => 1, - }); + my $freq_1i_7w = AddSubscriptionFrequency( + { + description => "1 issue per 7 weeks", + unit => 'week', + issuesperunit => 1, + unitsperissue => 7, + } + ); + my $freq_3i_1w = AddSubscriptionFrequency( + { + description => "3 issues per week", + unit => 'week', + issuesperunit => 3, + unitsperissue => 1, + } + ); # TEST CASE - 1 issue per 7 weeks my $subscription = { - periodicity => $freq_1i_7w, - firstacquidate => '1972-02-10', + periodicity => $freq_1i_7w, + firstacquidate => '1972-02-10', countissuesperunit => 1, }; my $frequency = GetSubscriptionFrequency($freq_1i_7w); - is( C4::Serials::GetFictiveIssueNumber($subscription, '1972-03-29', $frequency), 1, 'Mar 29 still 1' ); - is( C4::Serials::GetFictiveIssueNumber($subscription, '1972-03-30', $frequency), 2, 'Mar 30 goes to 2' ); + is( C4::Serials::GetFictiveIssueNumber( $subscription, '1972-03-29', $frequency ), 1, 'Mar 29 still 1' ); + is( C4::Serials::GetFictiveIssueNumber( $subscription, '1972-03-30', $frequency ), 2, 'Mar 30 goes to 2' ); # TEST CASE - 3 issue per 1 week $subscription = { - periodicity => $freq_3i_1w, - firstacquidate => '1972-02-03', + periodicity => $freq_3i_1w, + firstacquidate => '1972-02-03', countissuesperunit => 1, }; $subscription->{countissuesperunit} = 3; $frequency = GetSubscriptionFrequency($freq_3i_1w); - is( C4::Serials::GetFictiveIssueNumber($subscription, '1972-02-09', $frequency), 3, 'Feb 9 still 3' ); + is( C4::Serials::GetFictiveIssueNumber( $subscription, '1972-02-09', $frequency ), 3, 'Feb 9 still 3' ); $subscription->{countissuesperunit} = 1; - is( C4::Serials::GetFictiveIssueNumber($subscription, '1972-02-10', $frequency), 4, 'Feb 10 goes to 4' ); + is( C4::Serials::GetFictiveIssueNumber( $subscription, '1972-02-10', $frequency ), 4, 'Feb 10 goes to 4' ); }; subtest 'Tests for dayly frequencies' => sub { plan tests => 4; # First add a few frequencies - my $freq_1i_12d = AddSubscriptionFrequency({ - description => "1 issue per 12 days", - unit => 'day', - issuesperunit => 1, - unitsperissue => 12, - }); - my $freq_3i_1d = AddSubscriptionFrequency({ - description => "3 issues per day", - unit => 'day', - issuesperunit => 3, - unitsperissue => 1, - }); + my $freq_1i_12d = AddSubscriptionFrequency( + { + description => "1 issue per 12 days", + unit => 'day', + issuesperunit => 1, + unitsperissue => 12, + } + ); + my $freq_3i_1d = AddSubscriptionFrequency( + { + description => "3 issues per day", + unit => 'day', + issuesperunit => 3, + unitsperissue => 1, + } + ); # TEST CASE - 1 issue per 12 days my $subscription = { - periodicity => $freq_1i_12d, - firstacquidate => '1972-03-16', + periodicity => $freq_1i_12d, + firstacquidate => '1972-03-16', countissuesperunit => 1, }; my $frequency = GetSubscriptionFrequency($freq_1i_12d); - is( C4::Serials::GetFictiveIssueNumber($subscription, '1972-03-27', $frequency), 1, 'Mar 27 still 1' ); - is( C4::Serials::GetFictiveIssueNumber($subscription, '1972-03-28', $frequency), 2, 'Mar 28 goes to 2' ); + is( C4::Serials::GetFictiveIssueNumber( $subscription, '1972-03-27', $frequency ), 1, 'Mar 27 still 1' ); + is( C4::Serials::GetFictiveIssueNumber( $subscription, '1972-03-28', $frequency ), 2, 'Mar 28 goes to 2' ); # TEST CASE - 3 issue per day $subscription = { - periodicity => $freq_3i_1d, - firstacquidate => '1972-04-23', + periodicity => $freq_3i_1d, + firstacquidate => '1972-04-23', countissuesperunit => 1, }; $subscription->{countissuesperunit} = 3; $frequency = GetSubscriptionFrequency($freq_3i_1d); - is( C4::Serials::GetFictiveIssueNumber($subscription, '1972-05-01', $frequency), 27, 'May 1 still 27' ); + is( C4::Serials::GetFictiveIssueNumber( $subscription, '1972-05-01', $frequency ), 27, 'May 1 still 27' ); $subscription->{countissuesperunit} = 1; - is( C4::Serials::GetFictiveIssueNumber($subscription, '1972-05-02', $frequency), 28, 'May 2 goes to 28' ); + is( C4::Serials::GetFictiveIssueNumber( $subscription, '1972-05-02', $frequency ), 28, 'May 2 goes to 28' ); }; $schema->storage->txn_rollback; diff --git a/t/db_dependent/Serials/GetNextDate.t b/t/db_dependent/Serials/GetNextDate.t index 4081dea09a..6ba6d5f1ea 100755 --- a/t/db_dependent/Serials/GetNextDate.t +++ b/t/db_dependent/Serials/GetNextDate.t @@ -7,444 +7,445 @@ use Koha::Database; use C4::Serials qw( GetNextDate ); use C4::Serials::Frequency; -my $schema = Koha::Database->new->schema; +my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; my $dbh = C4::Context->dbh; - # TEST CASE - 1 issue per day, no irregularities my $frequency = { - description => "One issue per day", - unit => 'day', + description => "One issue per day", + unit => 'day', issuesperunit => 1, unitsperissue => 1, }; my $subscription = { - firstacquidate => '1970-01-01', - irregularity => '', + firstacquidate => '1970-01-01', + irregularity => '', countissuesperunit => 1, }; my $publisheddate = $subscription->{firstacquidate}; -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-01-02'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-01-03'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-01-04'); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-01-02' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-01-03' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-01-04' ); # TEST CASE - 1 issue per day, irregularities $subscription = { - firstacquidate => '1970-01-01', - irregularity => '2;4', # Skip the second and fourth issues + firstacquidate => '1970-01-01', + irregularity => '2;4', # Skip the second and fourth issues countissuesperunit => 1, }; $publisheddate = $subscription->{firstacquidate}; -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-01-03'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-01-05'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-01-06'); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-01-03' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-01-05' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-01-06' ); # TEST CASE - 2 issues per day, no irregularity $frequency = { - description => "Two issues per day", - unit => 'day', + description => "Two issues per day", + unit => 'day', issuesperunit => 2, unitsperissue => 1, }; $subscription = { - firstacquidate => '1970-01-01', - irregularity => '', + firstacquidate => '1970-01-01', + irregularity => '', countissuesperunit => 1, }; $publisheddate = $subscription->{firstacquidate}; -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-01-01'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-01-02'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-01-02'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-01-03'); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-01-01' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-01-02' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-01-02' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-01-03' ); # TEST CASE - 2 issues per day, irregularities $subscription = { - firstacquidate => '1970-01-01', - irregularity => '3;5;6', + firstacquidate => '1970-01-01', + irregularity => '3;5;6', countissuesperunit => 1, }; $publisheddate = $subscription->{firstacquidate}; -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-01-01'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-01-02'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-01-04'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-01-04'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-01-05'); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-01-01' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-01-02' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-01-04' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-01-04' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-01-05' ); # TEST CASE - 1 issue every 2 days, no irregularity $frequency = { - description => "one issue every two days", - unit => 'day', + description => "one issue every two days", + unit => 'day', issuesperunit => 1, unitsperissue => 2, }; $subscription = { - firstacquidate => '1970-01-01', - irregularity => '', + firstacquidate => '1970-01-01', + irregularity => '', countissuesperunit => 1, }; $publisheddate = $subscription->{firstacquidate}; -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-01-03'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-01-05'); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-01-03' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-01-05' ); # TEST CASE - 1 issue every 2 days, irregularities $subscription = { - firstacquidate => '1970-01-01', - irregularity => '3', + firstacquidate => '1970-01-01', + irregularity => '3', countissuesperunit => 1, }; $publisheddate = $subscription->{firstacquidate}; -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-01-03'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-01-07'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-01-09'); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-01-03' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-01-07' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-01-09' ); # TEST CASE - 1 issue per week, no irregularity $frequency = { - description => "one issue per week", - unit => 'week', + description => "one issue per week", + unit => 'week', issuesperunit => 1, unitsperissue => 1, }; $subscription = { - firstacquidate => '1970-01-01', - irregularity => '', + firstacquidate => '1970-01-01', + irregularity => '', countissuesperunit => 1, }; $publisheddate = $subscription->{firstacquidate}; -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-01-08'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-01-15'); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-01-08' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-01-15' ); # TEST CASE - 1 issue per week, irregularities $subscription = { - firstacquidate => '1970-01-01', - irregularity => '3', + firstacquidate => '1970-01-01', + irregularity => '3', countissuesperunit => 1, }; $publisheddate = $subscription->{firstacquidate}; -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-01-08'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-01-22'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-01-29'); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-01-08' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-01-22' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-01-29' ); # TEST CASE - 1 issue every 2 weeks, no irregularity $frequency = { - description => "one issue every 2 weeks", - unit => 'week', + description => "one issue every 2 weeks", + unit => 'week', issuesperunit => 1, unitsperissue => 2, }; $subscription = { - firstacquidate => '1970-01-01', - irregularity => '', + firstacquidate => '1970-01-01', + irregularity => '', countissuesperunit => 1, }; $publisheddate = $subscription->{firstacquidate}; -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-01-15'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-01-29'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-02-12'); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-01-15' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-01-29' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-02-12' ); # TEST CASE - 1 issue every 2 weeks, irregularities $subscription = { - firstacquidate => '1970-01-01', - irregularity => '3', + firstacquidate => '1970-01-01', + irregularity => '3', countissuesperunit => 1, }; $publisheddate = $subscription->{firstacquidate}; -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-01-15'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-02-12'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-02-26'); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-01-15' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-02-12' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-02-26' ); # TEST CASE - 2 issues per week, no irregularity $frequency = { - description => "two issues per week", - unit => 'week', + description => "two issues per week", + unit => 'week', issuesperunit => 2, unitsperissue => 1, }; $subscription = { - firstacquidate => '1970-01-01', - irregularity => '', + firstacquidate => '1970-01-01', + irregularity => '', countissuesperunit => 1, }; $publisheddate = $subscription->{firstacquidate}; -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-01-04'); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-01-04' ); + # when more than 1 issue per week, date is automatically set to the same day of # week as firstacquidate -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-01-08'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-01-11'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-01-15'); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-01-08' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-01-11' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-01-15' ); # TEST CASE - 2 issues per week, irregularities $subscription = { - firstacquidate => '1970-01-01', - irregularity => '3;5;6', + firstacquidate => '1970-01-01', + irregularity => '3;5;6', countissuesperunit => 1, }; $publisheddate = $subscription->{firstacquidate}; -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-01-04'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-01-11'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-01-22'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-01-25'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-01-29'); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-01-04' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-01-11' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-01-22' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-01-25' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-01-29' ); # TEST CASE - 6 issues per week, no irregularity $frequency = { - description => "six issues per week", - unit => 'week', + description => "six issues per week", + unit => 'week', issuesperunit => 6, unitsperissue => 1, }; $subscription = { - firstacquidate => '1970-01-06', - irregularity => '', + firstacquidate => '1970-01-06', + irregularity => '', countissuesperunit => 1, }; $publisheddate = $subscription->{firstacquidate}; -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-01-07'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-01-08'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-01-09'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-01-10'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-01-11'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-01-13'); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-01-07' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-01-08' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-01-09' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-01-10' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-01-11' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-01-13' ); # TEST CASE - 6 issues per week, irregularities $subscription = { - firstacquidate => '1970-01-06', - irregularity => '3;5;6', + firstacquidate => '1970-01-06', + irregularity => '3;5;6', countissuesperunit => 1, }; $publisheddate = $subscription->{firstacquidate}; -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-01-07'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-01-09'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-01-13'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-01-14'); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-01-07' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-01-09' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-01-13' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-01-14' ); # TEST CASE - 1 issue per month, no irregularity $frequency = { - description => "1 issue per month", - unit => 'month', + description => "1 issue per month", + unit => 'month', issuesperunit => 1, unitsperissue => 1, }; $subscription = { - firstacquidate => '1970-01-01', - irregularity => '', + firstacquidate => '1970-01-01', + irregularity => '', countissuesperunit => 1, }; $publisheddate = $subscription->{firstacquidate}; -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-02-01'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-03-01'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-04-01'); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-02-01' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-03-01' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-04-01' ); # TEST CASE - 1 issue per month, irregularities $subscription = { - firstacquidate => '1970-01-01', - irregularity => '2;4', + firstacquidate => '1970-01-01', + irregularity => '2;4', countissuesperunit => 1, }; $publisheddate = $subscription->{firstacquidate}; -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-03-01'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-05-01'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-06-01'); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-03-01' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-05-01' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-06-01' ); # TEST CASE - 1 issue every 2 months, no irregularity $frequency = { - description => "1 issue every 2 months", - unit => 'month', + description => "1 issue every 2 months", + unit => 'month', issuesperunit => 1, unitsperissue => 2, }; $subscription = { - firstacquidate => '1970-01-01', - irregularity => '', + firstacquidate => '1970-01-01', + irregularity => '', countissuesperunit => 1, }; $publisheddate = $subscription->{firstacquidate}; -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-03-01'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-05-01'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-07-01'); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-03-01' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-05-01' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-07-01' ); # TEST CASE - 1 issue every 2 months, irregularities $subscription = { - firstacquidate => '1970-01-01', - irregularity => '2;3', + firstacquidate => '1970-01-01', + irregularity => '2;3', countissuesperunit => 1, }; $publisheddate = $subscription->{firstacquidate}; -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-07-01'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-09-01'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-11-01'); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-07-01' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-09-01' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-11-01' ); # TEST CASE - 2 issues per month, no irregularity $frequency = { - description => "2 issues per month", - unit => 'month', + description => "2 issues per month", + unit => 'month', issuesperunit => 2, unitsperissue => 1, }; $subscription = { - firstacquidate => '1970-01-01', - irregularity => '', + firstacquidate => '1970-01-01', + irregularity => '', countissuesperunit => 1, }; $publisheddate = $subscription->{firstacquidate}; -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-01-16', 'January has 31 days'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-02-01'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-02-16', 'February has only 28 days'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-03-01'); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-01-16', 'January has 31 days' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-02-01' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-02-16', 'February has only 28 days' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-03-01' ); # TEST CASE - 2 issues per month, irregularities $subscription = { - firstacquidate => '1970-01-01', - irregularity => '3;5;6', + firstacquidate => '1970-01-01', + irregularity => '3;5;6', countissuesperunit => 1, }; $publisheddate = $subscription->{firstacquidate}; -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-01-16', 'January has 31 days'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-02-16', 'February has only 28 days'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-04-01'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-04-16', 'April has 30 days'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-05-01'); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-01-16', 'January has 31 days' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-02-16', 'February has only 28 days' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-04-01' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-04-16', 'April has 30 days' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-05-01' ); # TEST CASE - 1 issue per year, no irregularity $frequency = { - description => "1 issue per year", - unit => 'year', + description => "1 issue per year", + unit => 'year', issuesperunit => 1, unitsperissue => 1, }; $subscription = { - firstacquidate => '1970-01-01', - irregularity => '', + firstacquidate => '1970-01-01', + irregularity => '', countissuesperunit => 1, }; $publisheddate = $subscription->{firstacquidate}; -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1971-01-01'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1972-01-01'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1973-01-01'); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1971-01-01' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1972-01-01' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1973-01-01' ); # TEST CASE - 1 issue per year, irregularities $subscription = { - firstacquidate => '1970-01-01', - irregularity => '2;4', + firstacquidate => '1970-01-01', + irregularity => '2;4', countissuesperunit => 1, }; $publisheddate = $subscription->{firstacquidate}; -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1972-01-01'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1974-01-01'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1975-01-01'); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1972-01-01' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1974-01-01' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1975-01-01' ); # TEST CASE - 1 issue every 2 years, no irregularity $frequency = { - description => "1 issue every 2 years", - unit => 'year', + description => "1 issue every 2 years", + unit => 'year', issuesperunit => 1, unitsperissue => 2, }; $subscription = { - firstacquidate => '1970-01-01', - irregularity => '', + firstacquidate => '1970-01-01', + irregularity => '', countissuesperunit => 1, }; $publisheddate = $subscription->{firstacquidate}; -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1972-01-01'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1974-01-01'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1976-01-01'); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1972-01-01' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1974-01-01' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1976-01-01' ); # TEST CASE - 1 issue every 2 years, irregularities $subscription = { - firstacquidate => '1970-01-01', - irregularity => '2;4', + firstacquidate => '1970-01-01', + irregularity => '2;4', countissuesperunit => 1, }; $publisheddate = $subscription->{firstacquidate}; -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1974-01-01'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1978-01-01'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1980-01-01'); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1974-01-01' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1978-01-01' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1980-01-01' ); + # Move publisheddate to Feb 29 (leap year 1980) $publisheddate = '1980-02-29'; $publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); @@ -452,92 +453,98 @@ is( $publisheddate, '1982-02-28', 'Test +2 year from Feb 29' ); # TEST CASE - 2 issues per year, no irregularity $frequency = { - description => "1 issue every 2 years", - unit => 'year', + description => "1 issue every 2 years", + unit => 'year', issuesperunit => 2, unitsperissue => 1, }; $subscription = { - firstacquidate => '1970-01-01', - irregularity => '', + firstacquidate => '1970-01-01', + irregularity => '', countissuesperunit => 1, }; $publisheddate = $subscription->{firstacquidate}; -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-07-02'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1971-01-01'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1971-07-02'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1972-01-01'); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-07-02' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1971-01-01' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1971-07-02' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1972-01-01' ); # TEST CASE - 2 issues per year, irregularities $subscription = { - firstacquidate => '1970-01-01', - irregularity => '3;5;6', + firstacquidate => '1970-01-01', + irregularity => '3;5;6', countissuesperunit => 1, }; $publisheddate = $subscription->{firstacquidate}; -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1970-07-02'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1971-07-02'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1973-01-01'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1973-07-02'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, '1974-01-01'); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1970-07-02' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1971-07-02' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1973-01-01' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1973-07-02' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, '1974-01-01' ); # TEST CASE - 9 issues per year, dates spread throughout month $frequency = { - description => "9 issues per year", - unit => 'year', + description => "9 issues per year", + unit => 'year', issuesperunit => 9, unitsperissue => 1, }; $subscription = { - firstacquidate => '1970-08-10', - irregularity => '', + firstacquidate => '1970-08-10', + irregularity => '', countissuesperunit => 1, }; my @dates = ( $subscription->{firstacquidate} ); -foreach(1..27) { +foreach ( 1 .. 27 ) { push @dates, GetNextDate( $subscription, $dates[-1], $frequency ); } is( $dates[9], '1971-08-10', 'Freq 9/yr, 1 year passed' ); is( $dates[18], '1972-08-10', 'Freq 9/yr, 2 years passed (leap year)' ); is( $dates[27], '1973-08-10', 'Freq 9/yr, 3 years passed' ); + # Keep (first) position in cycle, but shift back 9 days is( GetNextDate( $subscription, '1973-08-01', $frequency ), '1973-09-10', 'Back 9 days, without annual correction' ); + # Set position to last in cycle, and shift back 9 days; annual correction $subscription->{countissuesperunit} = 9; -is( GetNextDate( $subscription, '1973-08-01', $frequency ), '1973-09-15', 'Last in cycle, back 9 days, expect annual correction' ); +is( + GetNextDate( $subscription, '1973-08-01', $frequency ), '1973-09-15', + 'Last in cycle, back 9 days, expect annual correction' +); # TEST CASE - Irregular $frequency = { - description => "Irregular", - unit => undef, + description => "Irregular", + unit => undef, issuesperunit => 1, unitsperissue => 1, }; $subscription = { - firstacquidate => '1970-01-01', - irregularity => '', + firstacquidate => '1970-01-01', + irregularity => '', countissuesperunit => 1, }; $publisheddate = $subscription->{firstacquidate}; + # GetNextDate always return undef if subscription is irregular -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -is($publisheddate, undef); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +is( $publisheddate, undef ); # GetNextDate returns undef if one of two first parameters is undef -$publisheddate = GetNextDate($subscription, undef, $frequency); -is($publisheddate, undef); -$publisheddate = GetNextDate(undef, $subscription->{firstacquidate}, $frequency); -is($publisheddate, undef); -$publisheddate = GetNextDate(undef, undef, $frequency); -is($publisheddate, undef); +$publisheddate = GetNextDate( $subscription, undef, $frequency ); +is( $publisheddate, undef ); +$publisheddate = GetNextDate( undef, $subscription->{firstacquidate}, $frequency ); +is( $publisheddate, undef ); +$publisheddate = GetNextDate( undef, undef, $frequency ); +is( $publisheddate, undef ); $schema->storage->txn_rollback; diff --git a/t/db_dependent/Serials/GetNextSeq.t b/t/db_dependent/Serials/GetNextSeq.t index 270568de60..098a9f1d54 100755 --- a/t/db_dependent/Serials/GetNextSeq.t +++ b/t/db_dependent/Serials/GetNextSeq.t @@ -12,8 +12,8 @@ use C4::Serials::Frequency; use C4::Serials qw( GetNextDate GetNextSeq ); my $frequency = { - description => "One issue per day", - unit => 'day', + description => "One issue per day", + unit => 'day', issuesperunit => 1, unitsperissue => 1, }; @@ -21,255 +21,258 @@ my $id = AddSubscriptionFrequency($frequency); # TEST CASE 1 - 1 variable, from 1 to 4 my $pattern = { - add1 => 1, add2 => 0, add3 => 0, - every1 => 1, every2 => 0, every3 => 0, - whenmorethan1 => 4, whenmorethan2 => 0, whenmorethan3 => 0, - setto1 => 1, setto2 => 0, setto3 => 0, + add1 => 1, add2 => 0, add3 => 0, + every1 => 1, every2 => 0, every3 => 0, + whenmorethan1 => 4, whenmorethan2 => 0, whenmorethan3 => 0, + setto1 => 1, setto2 => 0, setto3 => 0, numberingmethod => 'X: {X}', - numbering1 => '', - numbering2 => '', - numbering3 => '', + numbering1 => '', + numbering2 => '', + numbering3 => '', }; my $subscription = { - periodicity => $id, - firstacquidate => '1970-01-01', - lastvalue1 => 1, lastvalue2 => 1, lastvalue3 => 1, - innerloop1 => 0, innerloop2 => 0, innerloop3 => 0, - skip_serialseq => 1, - irregularity => '3;5', + periodicity => $id, + firstacquidate => '1970-01-01', + lastvalue1 => 1, lastvalue2 => 1, lastvalue3 => 1, + innerloop1 => 0, innerloop2 => 0, innerloop3 => 0, + skip_serialseq => 1, + irregularity => '3;5', countissuesperunit => 1, - locale => 'en', + locale => 'en', }; my $publisheddate = $subscription->{firstacquidate}; -my $seq = _next_seq($subscription, $pattern, $frequency, $publisheddate); -is($seq, 'X: 2'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -$seq = _next_seq($subscription, $pattern, $frequency, $publisheddate); -is($seq, 'X: 4'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -$seq = _next_seq($subscription, $pattern, $frequency, $publisheddate); -is($seq, 'X: 2'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -$seq = _next_seq($subscription, $pattern, $frequency, $publisheddate); -is($seq, 'X: 3'); +my $seq = _next_seq( $subscription, $pattern, $frequency, $publisheddate ); +is( $seq, 'X: 2' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +$seq = _next_seq( $subscription, $pattern, $frequency, $publisheddate ); +is( $seq, 'X: 4' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +$seq = _next_seq( $subscription, $pattern, $frequency, $publisheddate ); +is( $seq, 'X: 2' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +$seq = _next_seq( $subscription, $pattern, $frequency, $publisheddate ); +is( $seq, 'X: 3' ); # TEST CASE 2 - 1 variable, use 'dayname' numbering, from 1 to 7 $subscription = { - periodicity => $id, - firstacquidate => '1970-01-01', - lastvalue1 => 1, lastvalue2 => 1, lastvalue3 => 1, - innerloop1 => 0, innerloop2 => 0, innerloop3 => 0, - skip_serialseq => 1, - irregularity => '3;4;6', + periodicity => $id, + firstacquidate => '1970-01-01', + lastvalue1 => 1, lastvalue2 => 1, lastvalue3 => 1, + innerloop1 => 0, innerloop2 => 0, innerloop3 => 0, + skip_serialseq => 1, + irregularity => '3;4;6', countissuesperunit => 1, - locale => 'C', + locale => 'C', }; $pattern = { - add1 => 1, add2 => 0, add3 => 0, - every1 => 1, every2 => 0, every3 => 0, - whenmorethan1 => 7, whenmorethan2 => 0, whenmorethan3 => 0, - setto1 => 1, setto2 => 0, setto3 => 0, + add1 => 1, add2 => 0, add3 => 0, + every1 => 1, every2 => 0, every3 => 0, + whenmorethan1 => 7, whenmorethan2 => 0, whenmorethan3 => 0, + setto1 => 1, setto2 => 0, setto3 => 0, numberingmethod => 'X: {X}', - numbering1 => 'dayname', - numbering2 => '', - numbering3 => '', + numbering1 => 'dayname', + numbering2 => '', + numbering3 => '', }; $publisheddate = $subscription->{firstacquidate}; -$seq = _next_seq($subscription, $pattern, $frequency, $publisheddate); -is($seq, 'X: Tuesday'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -$seq = _next_seq($subscription, $pattern, $frequency, $publisheddate); -is($seq, 'X: Friday'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -$seq = _next_seq($subscription, $pattern, $frequency, $publisheddate); -is($seq, 'X: Sunday'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -$seq = _next_seq($subscription, $pattern, $frequency, $publisheddate); -is($seq, 'X: Monday'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -$seq = _next_seq($subscription, $pattern, $frequency, $publisheddate); -is($seq, 'X: Tuesday'); +$seq = _next_seq( $subscription, $pattern, $frequency, $publisheddate ); +is( $seq, 'X: Tuesday' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +$seq = _next_seq( $subscription, $pattern, $frequency, $publisheddate ); +is( $seq, 'X: Friday' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +$seq = _next_seq( $subscription, $pattern, $frequency, $publisheddate ); +is( $seq, 'X: Sunday' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +$seq = _next_seq( $subscription, $pattern, $frequency, $publisheddate ); +is( $seq, 'X: Monday' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +$seq = _next_seq( $subscription, $pattern, $frequency, $publisheddate ); +is( $seq, 'X: Tuesday' ); # TEST CASE 3 - 1 variable, use 'monthname' numbering, from 0 to 11 by step of 2 $subscription = { - periodicity => $id, - firstacquidate => '1970-01-01', - lastvalue1 => 0, lastvalue2 => 1, lastvalue3 => 1, - innerloop1 => 0, innerloop2 => 0, innerloop3 => 0, - skip_serialseq => 1, - irregularity => '3;4;6', + periodicity => $id, + firstacquidate => '1970-01-01', + lastvalue1 => 0, lastvalue2 => 1, lastvalue3 => 1, + innerloop1 => 0, innerloop2 => 0, innerloop3 => 0, + skip_serialseq => 1, + irregularity => '3;4;6', countissuesperunit => 1, - locale => 'C', + locale => 'C', }; $pattern = { - add1 => 2, add2 => 0, add3 => 0, - every1 => 1, every2 => 0, every3 => 0, - whenmorethan1 => 11, whenmorethan2 => 0, whenmorethan3 => 0, - setto1 => 0, setto2 => 0, setto3 => 0, + add1 => 2, add2 => 0, add3 => 0, + every1 => 1, every2 => 0, every3 => 0, + whenmorethan1 => 11, whenmorethan2 => 0, whenmorethan3 => 0, + setto1 => 0, setto2 => 0, setto3 => 0, numberingmethod => 'X: {X}', - numbering1 => 'monthname', - numbering2 => '', - numbering3 => '', + numbering1 => 'monthname', + numbering2 => '', + numbering3 => '', }; $publisheddate = $subscription->{firstacquidate}; -$seq = _next_seq($subscription, $pattern, $frequency, $publisheddate); -is($seq, 'X: March'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -$seq = _next_seq($subscription, $pattern, $frequency, $publisheddate); -is($seq, 'X: September'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -$seq = _next_seq($subscription, $pattern, $frequency, $publisheddate); -is($seq, 'X: January'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -$seq = _next_seq($subscription, $pattern, $frequency, $publisheddate); -is($seq, 'X: March'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -$seq = _next_seq($subscription, $pattern, $frequency, $publisheddate); -is($seq, 'X: May'); +$seq = _next_seq( $subscription, $pattern, $frequency, $publisheddate ); +is( $seq, 'X: March' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +$seq = _next_seq( $subscription, $pattern, $frequency, $publisheddate ); +is( $seq, 'X: September' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +$seq = _next_seq( $subscription, $pattern, $frequency, $publisheddate ); +is( $seq, 'X: January' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +$seq = _next_seq( $subscription, $pattern, $frequency, $publisheddate ); +is( $seq, 'X: March' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +$seq = _next_seq( $subscription, $pattern, $frequency, $publisheddate ); +is( $seq, 'X: May' ); # TEST CASE 4 - 1 variable, use 'season' numbering, from 0 to 3 $subscription = { - periodicity => $id, - firstacquidate => '1970-01-01', - lastvalue1 => 0, lastvalue2 => 1, lastvalue3 => 1, - innerloop1 => 0, innerloop2 => 0, innerloop3 => 0, - skip_serialseq => 1, - irregularity => '3;4;6', + periodicity => $id, + firstacquidate => '1970-01-01', + lastvalue1 => 0, lastvalue2 => 1, lastvalue3 => 1, + innerloop1 => 0, innerloop2 => 0, innerloop3 => 0, + skip_serialseq => 1, + irregularity => '3;4;6', countissuesperunit => 1, - locale => 'C', + locale => 'C', }; $pattern = { - add1 => 1, add2 => 0, add3 => 0, - every1 => 1, every2 => 0, every3 => 0, - whenmorethan1 => 3, whenmorethan2 => 0, whenmorethan3 => 0, - setto1 => 0, setto2 => 0, setto3 => 0, + add1 => 1, add2 => 0, add3 => 0, + every1 => 1, every2 => 0, every3 => 0, + whenmorethan1 => 3, whenmorethan2 => 0, whenmorethan3 => 0, + setto1 => 0, setto2 => 0, setto3 => 0, numberingmethod => 'X: {X}', - numbering1 => 'season', - numbering2 => '', - numbering3 => '', + numbering1 => 'season', + numbering2 => '', + numbering3 => '', }; $publisheddate = $subscription->{firstacquidate}; -$seq = _next_seq($subscription, $pattern, $frequency, $publisheddate); -is($seq, 'X: Summer'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -$seq = _next_seq($subscription, $pattern, $frequency, $publisheddate); -is($seq, 'X: Spring'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -$seq = _next_seq($subscription, $pattern, $frequency, $publisheddate); -is($seq, 'X: Fall'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -$seq = _next_seq($subscription, $pattern, $frequency, $publisheddate); -is($seq, 'X: Winter'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -$seq = _next_seq($subscription, $pattern, $frequency, $publisheddate); -is($seq, 'X: Spring'); +$seq = _next_seq( $subscription, $pattern, $frequency, $publisheddate ); +is( $seq, 'X: Summer' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +$seq = _next_seq( $subscription, $pattern, $frequency, $publisheddate ); +is( $seq, 'X: Spring' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +$seq = _next_seq( $subscription, $pattern, $frequency, $publisheddate ); +is( $seq, 'X: Fall' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +$seq = _next_seq( $subscription, $pattern, $frequency, $publisheddate ); +is( $seq, 'X: Winter' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +$seq = _next_seq( $subscription, $pattern, $frequency, $publisheddate ); +is( $seq, 'X: Spring' ); # TEST CASE 5 - 2 variables, from 1 to 12, and from 1 to 4 $subscription = { - periodicity => $id, - firstacquidate => '1970-01-01', - lastvalue1 => 1, lastvalue2 => 1, lastvalue3 => 1, - innerloop1 => 0, innerloop2 => 0, innerloop3 => 0, - skip_serialseq => 1, - irregularity => '3;4;6', + periodicity => $id, + firstacquidate => '1970-01-01', + lastvalue1 => 1, lastvalue2 => 1, lastvalue3 => 1, + innerloop1 => 0, innerloop2 => 0, innerloop3 => 0, + skip_serialseq => 1, + irregularity => '3;4;6', countissuesperunit => 1, - locale => 'C', + locale => 'C', }; $pattern = { - add1 => 1, add2 => 1, add3 => 0, - every1 => 1, every2 => 4, every3 => 0, - whenmorethan1 => 4, whenmorethan2 => 12, whenmorethan3 => 0, - setto1 => 1, setto2 => 1, setto3 => 0, + add1 => 1, add2 => 1, add3 => 0, + every1 => 1, every2 => 4, every3 => 0, + whenmorethan1 => 4, whenmorethan2 => 12, whenmorethan3 => 0, + setto1 => 1, setto2 => 1, setto3 => 0, numberingmethod => 'Y: {Y}, X: {X}', - numbering1 => '', - numbering2 => '', - numbering3 => '', + numbering1 => '', + numbering2 => '', + numbering3 => '', }; $publisheddate = $subscription->{firstacquidate}; -$seq = _next_seq($subscription, $pattern, $frequency, $publisheddate); -is($seq, 'Y: 1, X: 2'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -$seq = _next_seq($subscription, $pattern, $frequency, $publisheddate); -is($seq, 'Y: 2, X: 1'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -$seq = _next_seq($subscription, $pattern, $frequency, $publisheddate); -is($seq, 'Y: 2, X: 3'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -$seq = _next_seq($subscription, $pattern, $frequency, $publisheddate); -is($seq, 'Y: 2, X: 4'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -$seq = _next_seq($subscription, $pattern, $frequency, $publisheddate); -is($seq, 'Y: 3, X: 1'); +$seq = _next_seq( $subscription, $pattern, $frequency, $publisheddate ); +is( $seq, 'Y: 1, X: 2' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +$seq = _next_seq( $subscription, $pattern, $frequency, $publisheddate ); +is( $seq, 'Y: 2, X: 1' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +$seq = _next_seq( $subscription, $pattern, $frequency, $publisheddate ); +is( $seq, 'Y: 2, X: 3' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +$seq = _next_seq( $subscription, $pattern, $frequency, $publisheddate ); +is( $seq, 'Y: 2, X: 4' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +$seq = _next_seq( $subscription, $pattern, $frequency, $publisheddate ); +is( $seq, 'Y: 3, X: 1' ); # TEST CASE 6 - 3 variables, from 1 to 12, from 1 to 8, and from 1 to 4 $subscription = { - periodicity => $id, - firstacquidate => '1970-01-01', - lastvalue1 => 1, lastvalue2 => 1, lastvalue3 => 1, - innerloop1 => 0, innerloop2 => 0, innerloop3 => 0, - skip_serialseq => 1, - irregularity => '3;4;6;110', + periodicity => $id, + firstacquidate => '1970-01-01', + lastvalue1 => 1, lastvalue2 => 1, lastvalue3 => 1, + innerloop1 => 0, innerloop2 => 0, innerloop3 => 0, + skip_serialseq => 1, + irregularity => '3;4;6;110', countissuesperunit => 1, - locale => 'C', + locale => 'C', }; $pattern = { - add1 => 1, add2 => 1, add3 => 1, - every1 => 1, every2 => 4, every3 => 32, - whenmorethan1 => 4, whenmorethan2 => 8, whenmorethan3 => 12, - setto1 => 1, setto2 => 1, setto3 => 1, + add1 => 1, add2 => 1, add3 => 1, + every1 => 1, every2 => 4, every3 => 32, + whenmorethan1 => 4, whenmorethan2 => 8, whenmorethan3 => 12, + setto1 => 1, setto2 => 1, setto3 => 1, numberingmethod => 'Z: {Z}, Y: {Y}, X: {X}', - numbering1 => '', - numbering2 => '', - numbering3 => '', + numbering1 => '', + numbering2 => '', + numbering3 => '', }; $publisheddate = $subscription->{firstacquidate}; -$seq = _next_seq($subscription, $pattern, $frequency, $publisheddate); -is($seq, 'Z: 1, Y: 1, X: 2'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -$seq = _next_seq($subscription, $pattern, $frequency, $publisheddate); -is($seq, 'Z: 1, Y: 2, X: 1'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -$seq = _next_seq($subscription, $pattern, $frequency, $publisheddate); -is($seq, 'Z: 1, Y: 2, X: 3'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -$seq = _next_seq($subscription, $pattern, $frequency, $publisheddate); -is($seq, 'Z: 1, Y: 2, X: 4'); -for (1..100) { - $publisheddate = GetNextDate($subscription, $publisheddate, $frequency); - $seq = _next_seq($subscription, $pattern, $frequency, $publisheddate); +$seq = _next_seq( $subscription, $pattern, $frequency, $publisheddate ); +is( $seq, 'Z: 1, Y: 1, X: 2' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +$seq = _next_seq( $subscription, $pattern, $frequency, $publisheddate ); +is( $seq, 'Z: 1, Y: 2, X: 1' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +$seq = _next_seq( $subscription, $pattern, $frequency, $publisheddate ); +is( $seq, 'Z: 1, Y: 2, X: 3' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +$seq = _next_seq( $subscription, $pattern, $frequency, $publisheddate ); +is( $seq, 'Z: 1, Y: 2, X: 4' ); + +for ( 1 .. 100 ) { + $publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); + $seq = _next_seq( $subscription, $pattern, $frequency, $publisheddate ); } -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -$seq = _next_seq($subscription, $pattern, $frequency, $publisheddate); -is($seq, 'Z: 4, Y: 4, X: 1'); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +$seq = _next_seq( $subscription, $pattern, $frequency, $publisheddate ); +is( $seq, 'Z: 4, Y: 4, X: 1' ); + # 110th is here -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -$seq = _next_seq($subscription, $pattern, $frequency, $publisheddate); -is($seq, 'Z: 4, Y: 4, X: 3'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -$seq = _next_seq($subscription, $pattern, $frequency, $publisheddate); -is($seq, 'Z: 4, Y: 4, X: 4'); -$publisheddate = GetNextDate($subscription, $publisheddate, $frequency); -$seq = _next_seq($subscription, $pattern, $frequency, $publisheddate); -is($seq, 'Z: 4, Y: 5, X: 1'); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +$seq = _next_seq( $subscription, $pattern, $frequency, $publisheddate ); +is( $seq, 'Z: 4, Y: 4, X: 3' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +$seq = _next_seq( $subscription, $pattern, $frequency, $publisheddate ); +is( $seq, 'Z: 4, Y: 4, X: 4' ); +$publisheddate = GetNextDate( $subscription, $publisheddate, $frequency ); +$seq = _next_seq( $subscription, $pattern, $frequency, $publisheddate ); +is( $seq, 'Z: 4, Y: 5, X: 1' ); sub _next_seq { - my ($subscription, $pattern, $frequency, $publisheddate) = @_; + my ( $subscription, $pattern, $frequency, $publisheddate ) = @_; my $seq; - ($seq, $subscription->{lastvalue1}, $subscription->{lastvalue2}, + ( + $seq, $subscription->{lastvalue1}, $subscription->{lastvalue2}, $subscription->{lastvalue3}, $subscription->{innerloop1}, - $subscription->{innerloop2}, $subscription->{innerloop3}) = - GetNextSeq($subscription, $pattern, $frequency, $publisheddate); + $subscription->{innerloop2}, $subscription->{innerloop3} + ) = GetNextSeq( $subscription, $pattern, $frequency, $publisheddate ); return $seq; } diff --git a/t/db_dependent/Serials/Numberpattern.t b/t/db_dependent/Serials/Numberpattern.t index 65e1f420f1..95e23a0a63 100755 --- a/t/db_dependent/Serials/Numberpattern.t +++ b/t/db_dependent/Serials/Numberpattern.t @@ -9,94 +9,99 @@ use Koha::Database; my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; -use C4::Serials::Numberpattern qw( GetSubscriptionNumberpatterns GetSubscriptionNumberpattern DelSubscriptionNumberpattern ModSubscriptionNumberpattern AddSubscriptionNumberpattern ); +use C4::Serials::Numberpattern + qw( GetSubscriptionNumberpatterns GetSubscriptionNumberpattern DelSubscriptionNumberpattern ModSubscriptionNumberpattern AddSubscriptionNumberpattern ); # Start by deleting all numberpatterns. my @numberpatterns = GetSubscriptionNumberpatterns(); foreach my $n (@numberpatterns) { - DelSubscriptionNumberpattern($n->{id}); + DelSubscriptionNumberpattern( $n->{id} ); } @numberpatterns = GetSubscriptionNumberpatterns(); -is(scalar @numberpatterns, 0, "There is no numberpatterns in database"); +is( scalar @numberpatterns, 0, "There is no numberpatterns in database" ); my $numberpattern = GetSubscriptionNumberpattern(1); -is($numberpattern, undef, "GetSubscriptionNumberpattern(1) returns undef"); +is( $numberpattern, undef, "GetSubscriptionNumberpattern(1) returns undef" ); my $rv = ModSubscriptionNumberpattern($numberpattern); -is($rv, undef, "ModSubscriptionNumberpattern(undef) returns undef"); +is( $rv, undef, "ModSubscriptionNumberpattern(undef) returns undef" ); $numberpattern = {}; -$rv = ModSubscriptionNumberpattern($numberpattern); -is($rv, undef, "ModSubscriptionNumberpattern({}) returns undef"); +$rv = ModSubscriptionNumberpattern($numberpattern); +is( $rv, undef, "ModSubscriptionNumberpattern({}) returns undef" ); + # returns 0 because id doesn't exist $numberpattern = { id => 1, label => "Test numberpattern 1", description => '' }; -$rv = ModSubscriptionNumberpattern($numberpattern); -is($rv, '0E0', "ModSubscriptionNumberpattern({id=1,label=>'Test numberpattern 1'}) returns '0 but true'"); +$rv = ModSubscriptionNumberpattern($numberpattern); +is( $rv, '0E0', "ModSubscriptionNumberpattern({id=1,label=>'Test numberpattern 1'}) returns '0 but true'" ); $numberpattern = undef; my $id = AddSubscriptionNumberpattern($numberpattern); -is($id, undef, "AddSubscriptionNumberpattern(undef) returns undef"); +is( $id, undef, "AddSubscriptionNumberpattern(undef) returns undef" ); $numberpattern = {}; -$id = AddSubscriptionNumberpattern($numberpattern); -is($id, undef, "AddSubscriptionNumberpattern({}) returns undef"); +$id = AddSubscriptionNumberpattern($numberpattern); +is( $id, undef, "AddSubscriptionNumberpattern({}) returns undef" ); $numberpattern = { label => "Test numberpattern 1", numberingmethod => "{X}", description => '' }; -$id = AddSubscriptionNumberpattern($numberpattern); -ok((defined($id) && ($id > 0)), "AddSubscriptionNumberpattern({label => 'Test numberpattern 1', numberingmethod => '{X}'}) returns numberpattern id"); +$id = AddSubscriptionNumberpattern($numberpattern); +ok( + ( defined($id) && ( $id > 0 ) ), + "AddSubscriptionNumberpattern({label => 'Test numberpattern 1', numberingmethod => '{X}'}) returns numberpattern id" +); $numberpattern = GetSubscriptionNumberpattern($id); -isa_ok($numberpattern, 'HASH', "GetSubscriptionNumberpattern($id)"); -is($numberpattern->{label}, "Test numberpattern 1", "label OK"); -is($numberpattern->{numberingmethod}, '{X}', "unit OK"); -is($numberpattern->{description}, '', "description OK"); -is($numberpattern->{displayorder}, undef, "displayorder OK"); +isa_ok( $numberpattern, 'HASH', "GetSubscriptionNumberpattern($id)" ); +is( $numberpattern->{label}, "Test numberpattern 1", "label OK" ); +is( $numberpattern->{numberingmethod}, '{X}', "unit OK" ); +is( $numberpattern->{description}, '', "description OK" ); +is( $numberpattern->{displayorder}, undef, "displayorder OK" ); foreach my $key (qw(label add every setto whenmorethan numbering)) { - foreach my $index (1,2,3) { - ok(exists $numberpattern->{$key . $index}, "$key$index exists"); - is($numberpattern->{$key . $index}, undef, "$key$index is undef"); + foreach my $index ( 1, 2, 3 ) { + ok( exists $numberpattern->{ $key . $index }, "$key$index exists" ); + is( $numberpattern->{ $key . $index }, undef, "$key$index is undef" ); } } -$numberpattern->{label} = $numberpattern->{label} . " (modified)"; +$numberpattern->{label} = $numberpattern->{label} . " (modified)"; $numberpattern->{displayorder} = 1; my $i = 0; foreach my $key (qw(label add every setto whenmorethan numbering)) { - foreach my $index (1,2,3) { - $numberpattern->{$key . $index} = $i++; + foreach my $index ( 1, 2, 3 ) { + $numberpattern->{ $key . $index } = $i++; } } $rv = ModSubscriptionNumberpattern($numberpattern); -is($rv, 1, "ModSubscriptionNumberpattern(\$numberpattern) returns 1"); +is( $rv, 1, "ModSubscriptionNumberpattern(\$numberpattern) returns 1" ); $numberpattern = GetSubscriptionNumberpattern($id); -isa_ok($numberpattern, 'HASH', "GetSubscriptionNumberpattern($id)"); -is($numberpattern->{label}, "Test numberpattern 1 (modified)", "label OK"); -is($numberpattern->{numberingmethod}, '{X}', "unit OK"); -is($numberpattern->{description}, '', "description OK"); -is($numberpattern->{displayorder}, 1, "displayorder OK"); +isa_ok( $numberpattern, 'HASH', "GetSubscriptionNumberpattern($id)" ); +is( $numberpattern->{label}, "Test numberpattern 1 (modified)", "label OK" ); +is( $numberpattern->{numberingmethod}, '{X}', "unit OK" ); +is( $numberpattern->{description}, '', "description OK" ); +is( $numberpattern->{displayorder}, 1, "displayorder OK" ); $i = 0; foreach my $key (qw(label add every setto whenmorethan numbering)) { - foreach my $index (1,2,3) { - ok(exists $numberpattern->{$key . $index}, "$key$index exists"); - is($numberpattern->{$key . $index}, $i++, "$key$index is $i"); + foreach my $index ( 1, 2, 3 ) { + ok( exists $numberpattern->{ $key . $index }, "$key$index exists" ); + is( $numberpattern->{ $key . $index }, $i++, "$key$index is $i" ); } } @numberpatterns = GetSubscriptionNumberpatterns(); -is(scalar @numberpatterns, 1, "There is one numberpattern"); +is( scalar @numberpatterns, 1, "There is one numberpattern" ); # Add another numberpattern undef $numberpattern->{id}; my $id2 = AddSubscriptionNumberpattern($numberpattern); @numberpatterns = GetSubscriptionNumberpatterns(); -is(scalar @numberpatterns, 2, "There are two numberpatterns"); +is( scalar @numberpatterns, 2, "There are two numberpatterns" ); # Delete one numberpattern DelSubscriptionNumberpattern($id); @numberpatterns = GetSubscriptionNumberpatterns(); -is(scalar @numberpatterns, 1, "There is one numberpattern"); +is( scalar @numberpatterns, 1, "There is one numberpattern" ); # Delete the other numberpattern DelSubscriptionNumberpattern($id2); @numberpatterns = GetSubscriptionNumberpatterns(); -is(scalar @numberpatterns, 0, "There is no numberpattern"); +is( scalar @numberpatterns, 0, "There is no numberpattern" ); diff --git a/t/db_dependent/Serials/ReNewSubscription.t b/t/db_dependent/Serials/ReNewSubscription.t index 84ab1c01b2..b7b9712b6b 100755 --- a/t/db_dependent/Serials/ReNewSubscription.t +++ b/t/db_dependent/Serials/ReNewSubscription.t @@ -38,51 +38,59 @@ $schema->storage->txn_begin; my $builder = t::lib::TestBuilder->new(); # create fake numberpattern & fake periodicity -my $frequency = $builder->build({ - source => 'SubscriptionFrequency', - value => { - description => "daily", - unit => "day", - unitsperissue => 1, - }, -}); - -my $pattern = $builder->build({ - source => 'SubscriptionNumberpattern', - value => { - label => 'mock', - description =>'mock', - numberingmethod => 'Issue {X}', - add1 => 1, - every1 => 1, - setto1 => 100, +my $frequency = $builder->build( + { + source => 'SubscriptionFrequency', + value => { + description => "daily", + unit => "day", + unitsperissue => 1, + }, } -}); +); + +my $pattern = $builder->build( + { + source => 'SubscriptionNumberpattern', + value => { + label => 'mock', + description => 'mock', + numberingmethod => 'Issue {X}', + add1 => 1, + every1 => 1, + setto1 => 100, + } + } +); my $biblio = $builder->build_sample_biblio(); # Create fake subscription, daily subscription, duration 12 months, issues startint at #100 -my $subscription = $builder->build({ - source => 'Subscription', - value => { - biblionumber => $biblio->biblionumber, - startdate => '2015-01-01', - enddate => '2015-12-31', - periodicity => $frequency->{id}, - numberpattern => $pattern->{id}, - monthlength => 12, - }, -}); - -my $subscriptionhistory = $builder->build({ - source => 'Subscriptionhistory', - value => { - biblionumber => $biblio->biblionumber, - subscriptionid => $subscription->{subscriptionid}, - histenddate => undef, - opacnote => 'Testing', +my $subscription = $builder->build( + { + source => 'Subscription', + value => { + biblionumber => $biblio->biblionumber, + startdate => '2015-01-01', + enddate => '2015-12-31', + periodicity => $frequency->{id}, + numberpattern => $pattern->{id}, + monthlength => 12, + }, } -}); +); + +my $subscriptionhistory = $builder->build( + { + source => 'Subscriptionhistory', + value => { + biblionumber => $biblio->biblionumber, + subscriptionid => $subscription->{subscriptionid}, + histenddate => undef, + opacnote => 'Testing', + } + } +); t::lib::Mocks::mock_preference( 'RenewSerialAddsSuggestion', '0' ); my $suggestions_count = Koha::Suggestions->search()->count; @@ -98,9 +106,15 @@ ReNewSubscription( ); $subscription = Koha::Subscriptions->find( $subscription->{subscriptionid} ); -is( $subscription->enddate, '2017-01-01', "We don't update the subscription end date when renewing with a month length"); +is( + $subscription->enddate, '2017-01-01', + "We don't update the subscription end date when renewing with a month length" +); -is( $suggestions_count, Koha::Suggestions->search()->count, "Suggestion not added when RenewSerialAddsSuggestion set to Don't add"); +is( + $suggestions_count, Koha::Suggestions->search()->count, + "Suggestion not added when RenewSerialAddsSuggestion set to Don't add" +); t::lib::Mocks::mock_preference( 'RenewSerialAddsSuggestion', '1' ); @@ -112,33 +126,37 @@ ReNewSubscription( } ); -is( $suggestions_count + 1, Koha::Suggestions->search()->count, "Suggestion added when RenewSerialAddsSuggestion set to add"); +is( + $suggestions_count + 1, Koha::Suggestions->search()->count, + "Suggestion added when RenewSerialAddsSuggestion set to add" +); -my $history = Koha::Subscription::Histories->find($subscription->subscriptionid); +my $history = Koha::Subscription::Histories->find( $subscription->subscriptionid ); + +is( $history->histenddate(), undef, 'subscription history not empty after renewal' ); -is ( $history->histenddate(), undef, 'subscription history not empty after renewal'); # Calculate the subscription length for the renewal for issues, days and months -my ($numberlength, $weeklength, $monthlength) = GetSubscriptionLength('issues', 7); -is ( $numberlength, 7, "Subscription length is 7 issues"); +my ( $numberlength, $weeklength, $monthlength ) = GetSubscriptionLength( 'issues', 7 ); +is( $numberlength, 7, "Subscription length is 7 issues" ); -($numberlength, $weeklength, $monthlength) = GetSubscriptionLength('weeks', 7); -is ( $weeklength, 7, "Subscription length is 7 weeks"); +( $numberlength, $weeklength, $monthlength ) = GetSubscriptionLength( 'weeks', 7 ); +is( $weeklength, 7, "Subscription length is 7 weeks" ); -($numberlength, $weeklength, $monthlength) = GetSubscriptionLength('months', 7); -is ( $monthlength, 7, "Subscription length is 7 months"); +( $numberlength, $weeklength, $monthlength ) = GetSubscriptionLength( 'months', 7 ); +is( $monthlength, 7, "Subscription length is 7 months" ); # Check subscription length when no value is inputted into the numeric sublength field -($numberlength, $weeklength, $monthlength) = GetSubscriptionLength('months', ''); -is ($monthlength, undef, "Subscription length is undef months, invalid month data was not stored"); +( $numberlength, $weeklength, $monthlength ) = GetSubscriptionLength( 'months', '' ); +is( $monthlength, undef, "Subscription length is undef months, invalid month data was not stored" ); # Check subscription length when a letter is inputted into the numeric sublength field -($numberlength, $weeklength, $monthlength) = GetSubscriptionLength('issues', 'w'); -is ($monthlength, undef, "Subscription length is undef issues, invalid issue data was not stored"); +( $numberlength, $weeklength, $monthlength ) = GetSubscriptionLength( 'issues', 'w' ); +is( $monthlength, undef, "Subscription length is undef issues, invalid issue data was not stored" ); # Check subscription length when a special character is inputted into numberic sublength field -($numberlength, $weeklength, $monthlength) = GetSubscriptionLength('weeks', '!'); -is ($weeklength, undef, "Subscription length is undef weeks, invalid weeks data was not stored"); +( $numberlength, $weeklength, $monthlength ) = GetSubscriptionLength( 'weeks', '!' ); +is( $weeklength, undef, "Subscription length is undef weeks, invalid weeks data was not stored" ); # End of tests diff --git a/t/db_dependent/Serials/updateClaim.t b/t/db_dependent/Serials/updateClaim.t index 1eed7db318..bb50c448be 100755 --- a/t/db_dependent/Serials/updateClaim.t +++ b/t/db_dependent/Serials/updateClaim.t @@ -13,30 +13,31 @@ $dbh->do(q|DELETE FROM issues|); $dbh->do(q|DELETE FROM subscription|); my $branchcode = 'CPL'; -my $record = MARC::Record->new(); -my ( $biblionumber, $biblioitemnumber ) = C4::Biblio::AddBiblio($record, ''); +my $record = MARC::Record->new(); +my ( $biblionumber, $biblioitemnumber ) = C4::Biblio::AddBiblio( $record, '' ); # Create a new subscription my $subscriptionid_claims = C4::Serials::NewSubscription( -undef, $branchcode, undef, undef, undef, $biblionumber, -'2013-01-01', undef, undef, undef, undef, -undef, undef, undef, undef, undef, undef, -1, "notes",undef, '9999-01-01', undef, undef, -undef, undef, 0, "intnotes", 0, -undef, undef, 0, undef, '2013-12-31', 0 + undef, $branchcode, undef, undef, undef, $biblionumber, + '2013-01-01', undef, undef, undef, undef, + undef, undef, undef, undef, undef, undef, + 1, "notes", undef, '9999-01-01', undef, undef, + undef, undef, 0, "intnotes", 0, + undef, undef, 0, undef, '2013-12-31', 0 ); # Verify and get the serial ID of the subscription -my ( $totalissues, @serials ) = C4::Serials::GetSerials($subscriptionid_claims, 1); +my ( $totalissues, @serials ) = C4::Serials::GetSerials( $subscriptionid_claims, 1 ); + +C4::Serials::updateClaim( $serials[0]->{serialid} ); # Updating the claim -C4::Serials::updateClaim( $serials[0]->{serialid} ); # Updating the claim # sort the result to separate the CLAIMED and EXPECTED status @serials = sort { $a->{serialid} <=> $b->{serialid} } @serials; # Verify if serial IDs are correctly generated ( $totalissues, @serials ) = C4::Serials::GetSerials($subscriptionid_claims); -is ( scalar(@serials), 2, "le test est terminé" ); # Gives the length of the @serials +is( scalar(@serials), 2, "le test est terminé" ); # Gives the length of the @serials -is ( ($serials[0]->{status}), C4::Serials::CLAIMED, "test CLAIMED" ); -is ( ($serials[1]->{status}), C4::Serials::EXPECTED, "test EXPECTED" ); +is( ( $serials[0]->{status} ), C4::Serials::CLAIMED, "test CLAIMED" ); +is( ( $serials[1]->{status} ), C4::Serials::EXPECTED, "test EXPECTED" ); diff --git a/t/db_dependent/Serials_2.t b/t/db_dependent/Serials_2.t index d0a1b7a615..eb0e7ba1de 100755 --- a/t/db_dependent/Serials_2.t +++ b/t/db_dependent/Serials_2.t @@ -10,8 +10,8 @@ use Koha::Database; use Koha::Patrons; use t::lib::Mocks; use t::lib::TestBuilder; -use_ok('C4::Serials', qw( NewSubscription GetSubscription NewIssue GetPreviousSerialid )); -use_ok('C4::Budgets', qw( AddBudgetPeriod AddBudget )); +use_ok( 'C4::Serials', qw( NewSubscription GetSubscription NewIssue GetPreviousSerialid ) ); +use_ok( 'C4::Budgets', qw( AddBudgetPeriod AddBudget ) ); # Mock userenv local $SIG{__WARN__} = sub { warn $_[0] unless $_[0] =~ /redefined/ }; @@ -20,234 +20,290 @@ my $userenv; my $schema = Koha::Database->schema; $schema->storage->txn_begin; -my $builder = t::lib::TestBuilder->new; -my $library1 = $builder->build({ - source => 'Branch', -}); -my $library2 = $builder->build({ - source => 'Branch', -}); -my $patron_category = $builder->build({ source => 'Category' }); -my $dbh = C4::Context->dbh; +my $builder = t::lib::TestBuilder->new; +my $library1 = $builder->build( + { + source => 'Branch', + } +); +my $library2 = $builder->build( + { + source => 'Branch', + } +); +my $patron_category = $builder->build( { source => 'Category' } ); +my $dbh = C4::Context->dbh; my $record = MARC::Record->new(); $record->append_fields( - MARC::Field->new( '952', '0', '0', a => $library1->{branchcode}, b => $library1->{branchcode} ) -); -my ( $biblionumber, $biblioitemnumber ) = C4::Biblio::AddBiblio($record, ''); + MARC::Field->new( '952', '0', '0', a => $library1->{branchcode}, b => $library1->{branchcode} ) ); +my ( $biblionumber, $biblioitemnumber ) = C4::Biblio::AddBiblio( $record, '' ); -my $my_branch = $library1->{branchcode}; +my $my_branch = $library1->{branchcode}; my $another_branch = $library2->{branchcode}; -my $bpid = AddBudgetPeriod({ - budget_period_startdate => '2015-01-01', - budget_period_enddate => '2015-12-31', - budget_period_description => "budget desc" -}); +my $bpid = AddBudgetPeriod( + { + budget_period_startdate => '2015-01-01', + budget_period_enddate => '2015-12-31', + budget_period_description => "budget desc" + } +); -my $budget_id = AddBudget({ - budget_code => "ABCD", - budget_amount => "123.132", - budget_name => "Périodiques", - budget_notes => "This is a note", - budget_period_id => $bpid -}); +my $budget_id = AddBudget( + { + budget_code => "ABCD", + budget_amount => "123.132", + budget_name => "Périodiques", + budget_notes => "This is a note", + budget_period_id => $bpid + } +); my $subscriptionid_from_my_branch = NewSubscription( - undef, $my_branch, undef, undef, $budget_id, $biblionumber, - '2013-01-01', undef, undef, undef, undef, - undef, undef, undef, undef, undef, undef, - 1, "notes",undef, '2013-01-01', undef, undef, - undef, undef, 0, "intnotes", 0, - undef, undef, 0, undef, '2013-12-31', 0 + undef, $my_branch, undef, undef, $budget_id, $biblionumber, + '2013-01-01', undef, undef, undef, undef, + undef, undef, undef, undef, undef, undef, + 1, "notes", undef, '2013-01-01', undef, undef, + undef, undef, 0, "intnotes", 0, + undef, undef, 0, undef, '2013-12-31', 0 ); die unless $subscriptionid_from_my_branch; my $subscriptionid_from_another_branch = NewSubscription( - undef, $another_branch, undef, undef, $budget_id, $biblionumber, - '2013-01-01', undef, undef, undef, undef, - undef, undef, undef, undef, undef, undef, - 1, "notes",undef, '2013-01-01', undef, undef, - undef, undef, 0, "intnotes", 0, - undef, undef, 0, undef, '2013-12-31', 0 + undef, $another_branch, undef, undef, $budget_id, $biblionumber, + '2013-01-01', undef, undef, undef, undef, + undef, undef, undef, undef, undef, undef, + 1, "notes", undef, '2013-01-01', undef, undef, + undef, undef, 0, "intnotes", 0, + undef, undef, 0, undef, '2013-12-31', 0 ); +my $subscription_from_my_branch = GetSubscription($subscriptionid_from_my_branch); +is( + C4::Serials::can_edit_subscription($subscription_from_my_branch), 0, + "cannot edit a subscription without userenv set" +); +is( + C4::Serials::can_claim_subscription($subscription_from_my_branch), 0, + "cannot edit a subscription without userenv set" +); -my $subscription_from_my_branch = GetSubscription( $subscriptionid_from_my_branch ); -is( C4::Serials::can_edit_subscription($subscription_from_my_branch), 0, "cannot edit a subscription without userenv set"); -is( C4::Serials::can_claim_subscription($subscription_from_my_branch), 0, "cannot edit a subscription without userenv set"); - -my $userid = 'my_userid'; -my $borrowernumber = Koha::Patron->new({ - firstname => 'my fistname', - surname => 'my surname', - categorycode => $patron_category->{categorycode}, - branchcode => $my_branch, - userid => $userid, -})->store->borrowernumber; +my $userid = 'my_userid'; +my $borrowernumber = Koha::Patron->new( + { + firstname => 'my fistname', + surname => 'my surname', + categorycode => $patron_category->{categorycode}, + branchcode => $my_branch, + userid => $userid, + } +)->store->borrowernumber; $userenv = { flags => 1, id => $borrowernumber, branch => '' }; # Can edit a subscription -is( C4::Serials::can_edit_subscription($subscription_from_my_branch), 1, "User can edit a subscription with an empty branchcode"); -is( C4::Serials::can_claim_subscription($subscription_from_my_branch), 1, "User can edit a subscription with an empty branchcode"); +is( + C4::Serials::can_edit_subscription($subscription_from_my_branch), 1, + "User can edit a subscription with an empty branchcode" +); +is( + C4::Serials::can_claim_subscription($subscription_from_my_branch), 1, + "User can edit a subscription with an empty branchcode" +); -my $subscription_from_another_branch = GetSubscription( $subscriptionid_from_another_branch ); +my $subscription_from_another_branch = GetSubscription($subscriptionid_from_another_branch); -$userenv->{id} = $userid; +$userenv->{id} = $userid; $userenv->{branch} = $my_branch; # Branches are independent t::lib::Mocks::mock_preference( "IndependentBranches", 1 ); set_flags( 'superlibrarian', $borrowernumber ); -is( C4::Serials::can_edit_subscription($subscription_from_my_branch), 1, -"With IndependentBranches, superlibrarian can edit a subscription from his branch" +is( + C4::Serials::can_edit_subscription($subscription_from_my_branch), 1, + "With IndependentBranches, superlibrarian can edit a subscription from his branch" ); -is( C4::Serials::can_edit_subscription($subscription_from_another_branch), 1, -"With IndependentBranches, superlibrarian can edit a subscription from another branch" +is( + C4::Serials::can_edit_subscription($subscription_from_another_branch), 1, + "With IndependentBranches, superlibrarian can edit a subscription from another branch" ); -is( C4::Serials::can_show_subscription($subscription_from_my_branch), 1, -"With IndependentBranches, superlibrarian can show a subscription from his branch" +is( + C4::Serials::can_show_subscription($subscription_from_my_branch), 1, + "With IndependentBranches, superlibrarian can show a subscription from his branch" ); -is( C4::Serials::can_show_subscription($subscription_from_another_branch), 1, -"With IndependentBranches, superlibrarian can show a subscription from another branch" +is( + C4::Serials::can_show_subscription($subscription_from_another_branch), 1, + "With IndependentBranches, superlibrarian can show a subscription from another branch" ); -is( C4::Serials::can_claim_subscription($subscription_from_my_branch), 1, -"With IndependentBranches, superlibrarian can claim a subscription from his branch" +is( + C4::Serials::can_claim_subscription($subscription_from_my_branch), 1, + "With IndependentBranches, superlibrarian can claim a subscription from his branch" ); -is( C4::Serials::can_claim_subscription($subscription_from_another_branch), 1, -"With IndependentBranches, superlibrarian can claim a subscription from another branch" +is( + C4::Serials::can_claim_subscription($subscription_from_another_branch), 1, + "With IndependentBranches, superlibrarian can claim a subscription from another branch" ); - set_flags( 'superserials', $borrowernumber ); -is( C4::Serials::can_edit_subscription($subscription_from_my_branch), 1, -"With IndependentBranches, superserials can edit a subscription from his branch" +is( + C4::Serials::can_edit_subscription($subscription_from_my_branch), 1, + "With IndependentBranches, superserials can edit a subscription from his branch" ); -is( C4::Serials::can_edit_subscription($subscription_from_another_branch), 1, -"With IndependentBranches, superserials can edit a subscription from another branch" +is( + C4::Serials::can_edit_subscription($subscription_from_another_branch), 1, + "With IndependentBranches, superserials can edit a subscription from another branch" ); -is( C4::Serials::can_show_subscription($subscription_from_my_branch), 1, -"With IndependentBranches, superserials can show a subscription from his branch" +is( + C4::Serials::can_show_subscription($subscription_from_my_branch), 1, + "With IndependentBranches, superserials can show a subscription from his branch" ); -is( C4::Serials::can_show_subscription($subscription_from_another_branch), 1, -"With IndependentBranches, superserials can show a subscription from another branch" +is( + C4::Serials::can_show_subscription($subscription_from_another_branch), 1, + "With IndependentBranches, superserials can show a subscription from another branch" ); -is( C4::Serials::can_claim_subscription($subscription_from_my_branch), 1, -"With IndependentBranches, superserials can claim a subscription from his branch" +is( + C4::Serials::can_claim_subscription($subscription_from_my_branch), 1, + "With IndependentBranches, superserials can claim a subscription from his branch" ); -is( C4::Serials::can_claim_subscription($subscription_from_another_branch), 1, -"With IndependentBranches, superserials can claim a subscription from another branch" +is( + C4::Serials::can_claim_subscription($subscription_from_another_branch), 1, + "With IndependentBranches, superserials can claim a subscription from another branch" ); - - set_flags( 'edit_subscription', $borrowernumber ); -is( C4::Serials::can_edit_subscription($subscription_from_my_branch), 1, -"With IndependentBranches, edit_subscription can edit a subscription from his branch" +is( + C4::Serials::can_edit_subscription($subscription_from_my_branch), 1, + "With IndependentBranches, edit_subscription can edit a subscription from his branch" ); -is( C4::Serials::can_edit_subscription($subscription_from_another_branch), 0, -"With IndependentBranches, edit_subscription cannot edit a subscription from another branch" +is( + C4::Serials::can_edit_subscription($subscription_from_another_branch), 0, + "With IndependentBranches, edit_subscription cannot edit a subscription from another branch" ); -is( C4::Serials::can_show_subscription($subscription_from_my_branch), 1, -"With IndependentBranches, show_subscription can show a subscription from his branch" +is( + C4::Serials::can_show_subscription($subscription_from_my_branch), 1, + "With IndependentBranches, show_subscription can show a subscription from his branch" ); -is( C4::Serials::can_show_subscription($subscription_from_another_branch), 0, -"With IndependentBranches, show_subscription cannot show a subscription from another branch" +is( + C4::Serials::can_show_subscription($subscription_from_another_branch), 0, + "With IndependentBranches, show_subscription cannot show a subscription from another branch" ); -is( C4::Serials::can_claim_subscription($subscription_from_my_branch), 0, -"With IndependentBranches, claim_subscription cannot claim a subscription from his branch with the edit_subscription permission" +is( + C4::Serials::can_claim_subscription($subscription_from_my_branch), 0, + "With IndependentBranches, claim_subscription cannot claim a subscription from his branch with the edit_subscription permission" ); -is( C4::Serials::can_claim_subscription($subscription_from_another_branch), 0, -"With IndependentBranches, claim_subscription cannot claim a subscription from another branch" +is( + C4::Serials::can_claim_subscription($subscription_from_another_branch), 0, + "With IndependentBranches, claim_subscription cannot claim a subscription from another branch" ); - set_flags( 'renew_subscription', $borrowernumber ); -is( C4::Serials::can_edit_subscription($subscription_from_my_branch), 0, -"With IndependentBranches, renew_subscription cannot edit a subscription from his branch" +is( + C4::Serials::can_edit_subscription($subscription_from_my_branch), 0, + "With IndependentBranches, renew_subscription cannot edit a subscription from his branch" ); -is( C4::Serials::can_edit_subscription($subscription_from_another_branch), 0, -"With IndependentBranches, renew_subscription cannot edit a subscription from another branch" +is( + C4::Serials::can_edit_subscription($subscription_from_another_branch), 0, + "With IndependentBranches, renew_subscription cannot edit a subscription from another branch" ); -is( C4::Serials::can_show_subscription($subscription_from_my_branch), 1, -"With IndependentBranches, renew_subscription can show a subscription from his branch" +is( + C4::Serials::can_show_subscription($subscription_from_my_branch), 1, + "With IndependentBranches, renew_subscription can show a subscription from his branch" ); -is( C4::Serials::can_show_subscription($subscription_from_another_branch), 0, -"With IndependentBranches, renew_subscription cannot show a subscription from another branch" +is( + C4::Serials::can_show_subscription($subscription_from_another_branch), 0, + "With IndependentBranches, renew_subscription cannot show a subscription from another branch" ); set_flags( 'claim_serials', $borrowernumber ); -is( C4::Serials::can_claim_subscription($subscription_from_my_branch), 1, -"With IndependentBranches, claim_subscription can claim a subscription from his branch with the edit_subscription permission" +is( + C4::Serials::can_claim_subscription($subscription_from_my_branch), 1, + "With IndependentBranches, claim_subscription can claim a subscription from his branch with the edit_subscription permission" ); -is( C4::Serials::can_claim_subscription($subscription_from_another_branch), 0, -"With IndependentBranches, claim_subscription cannot claim a subscription from another branch" +is( + C4::Serials::can_claim_subscription($subscription_from_another_branch), 0, + "With IndependentBranches, claim_subscription cannot claim a subscription from another branch" ); # Branches are not independent t::lib::Mocks::mock_preference( "IndependentBranches", 0 ); set_flags( 'superlibrarian', $borrowernumber ); -is( C4::Serials::can_edit_subscription($subscription_from_my_branch), 1, -"Without IndependentBranches, superlibrarian can edit a subscription from his branch" +is( + C4::Serials::can_edit_subscription($subscription_from_my_branch), 1, + "Without IndependentBranches, superlibrarian can edit a subscription from his branch" ); -is( C4::Serials::can_edit_subscription($subscription_from_another_branch), 1, -"Without IndependentBranches, superlibrarian can edit a subscription from another branch" +is( + C4::Serials::can_edit_subscription($subscription_from_another_branch), 1, + "Without IndependentBranches, superlibrarian can edit a subscription from another branch" ); -is( C4::Serials::can_show_subscription($subscription_from_my_branch), 1, -"Without IndependentBranches, superlibrarian can show a subscription from his branch" +is( + C4::Serials::can_show_subscription($subscription_from_my_branch), 1, + "Without IndependentBranches, superlibrarian can show a subscription from his branch" ); -is( C4::Serials::can_show_subscription($subscription_from_another_branch), 1, -"Without IndependentBranches, superlibrarian can show a subscription from another branch" +is( + C4::Serials::can_show_subscription($subscription_from_another_branch), 1, + "Without IndependentBranches, superlibrarian can show a subscription from another branch" ); set_flags( 'superserials', $borrowernumber ); -is( C4::Serials::can_edit_subscription($subscription_from_my_branch), 1, -"Without IndependentBranches, superserials can edit a subscription from his branch" +is( + C4::Serials::can_edit_subscription($subscription_from_my_branch), 1, + "Without IndependentBranches, superserials can edit a subscription from his branch" ); -is( C4::Serials::can_edit_subscription($subscription_from_another_branch), 1, -"Without IndependentBranches, superserials can edit a subscription from another branch" +is( + C4::Serials::can_edit_subscription($subscription_from_another_branch), 1, + "Without IndependentBranches, superserials can edit a subscription from another branch" ); -is( C4::Serials::can_show_subscription($subscription_from_my_branch), 1, -"Without IndependentBranches, superserials can show a subscription from his branch" +is( + C4::Serials::can_show_subscription($subscription_from_my_branch), 1, + "Without IndependentBranches, superserials can show a subscription from his branch" ); -is( C4::Serials::can_show_subscription($subscription_from_another_branch), 1, -"Without IndependentBranches, superserials can show a subscription from another branch" +is( + C4::Serials::can_show_subscription($subscription_from_another_branch), 1, + "Without IndependentBranches, superserials can show a subscription from another branch" ); set_flags( 'edit_subscription', $borrowernumber ); -is( C4::Serials::can_edit_subscription($subscription_from_my_branch), 1, -"Without IndependentBranches, edit_subscription can edit a subscription from his branch" +is( + C4::Serials::can_edit_subscription($subscription_from_my_branch), 1, + "Without IndependentBranches, edit_subscription can edit a subscription from his branch" ); -is( C4::Serials::can_edit_subscription($subscription_from_another_branch), 1, -"Without IndependentBranches, edit_subscription can edit a subscription from another branch" +is( + C4::Serials::can_edit_subscription($subscription_from_another_branch), 1, + "Without IndependentBranches, edit_subscription can edit a subscription from another branch" ); -is( C4::Serials::can_show_subscription($subscription_from_my_branch), 1, -"Without IndependentBranches, show_subscription can show a subscription from his branch" +is( + C4::Serials::can_show_subscription($subscription_from_my_branch), 1, + "Without IndependentBranches, show_subscription can show a subscription from his branch" ); -is( C4::Serials::can_show_subscription($subscription_from_another_branch), 1, -"Without IndependentBranches, show_subscription can show a subscription from another branch" +is( + C4::Serials::can_show_subscription($subscription_from_another_branch), 1, + "Without IndependentBranches, show_subscription can show a subscription from another branch" ); set_flags( 'renew_subscription', $borrowernumber ); -is( C4::Serials::can_edit_subscription($subscription_from_my_branch), 0, -"Without IndependentBranches, renew_subscription cannot edit a subscription from his branch" +is( + C4::Serials::can_edit_subscription($subscription_from_my_branch), 0, + "Without IndependentBranches, renew_subscription cannot edit a subscription from his branch" ); -is( C4::Serials::can_edit_subscription($subscription_from_another_branch), 0, -"Without IndependentBranches, renew_subscription cannot edit a subscription from another branch" +is( + C4::Serials::can_edit_subscription($subscription_from_another_branch), 0, + "Without IndependentBranches, renew_subscription cannot edit a subscription from another branch" ); -is( C4::Serials::can_show_subscription($subscription_from_my_branch), 1, -"Without IndependentBranches, renew_subscription cannot show a subscription from his branch" +is( + C4::Serials::can_show_subscription($subscription_from_my_branch), 1, + "Without IndependentBranches, renew_subscription cannot show a subscription from his branch" ); -is( C4::Serials::can_show_subscription($subscription_from_another_branch), 1, -"Without IndependentBranches, renew_subscription cannot show a subscription from another branch" +is( + C4::Serials::can_show_subscription($subscription_from_another_branch), 1, + "Without IndependentBranches, renew_subscription cannot show a subscription from another branch" ); # GetPreviousSerialid my $serialid1 = NewIssue( 1, $subscriptionid_from_my_branch, $biblionumber, 2 ); my $serialid2 = NewIssue( 2, $subscriptionid_from_my_branch, $biblionumber, 2 ); my $serialid3 = NewIssue( 3, $subscriptionid_from_my_branch, $biblionumber, 2 ); -is( GetPreviousSerialid( $subscriptionid_from_my_branch ), $serialid2, "get previous serialid without parameter"); +is( GetPreviousSerialid($subscriptionid_from_my_branch), $serialid2, "get previous serialid without parameter" ); is( GetPreviousSerialid( $subscriptionid_from_my_branch, 1 ), $serialid2, "get previous serialid with 1" ); is( GetPreviousSerialid( $subscriptionid_from_my_branch, 2 ), $serialid1, "get previous serialid with 2" ); is( GetPreviousSerialid( $subscriptionid_from_my_branch, 3 ), undef, "get previous serialid with 3, does not exist" ); @@ -269,8 +325,7 @@ sub set_flags { |, {}, $superlibrarian_flags, $borrowernumber ); $userenv->{flags} = $superlibrarian_flags; - } - else { + } else { $dbh->do( q| UPDATE borrowers SET flags=? WHERE borrowernumber=? diff --git a/t/db_dependent/Service.t b/t/db_dependent/Service.t index 497cc1bc7f..04f5e600b4 100755 --- a/t/db_dependent/Service.t +++ b/t/db_dependent/Service.t @@ -1,6 +1,6 @@ #!/usr/bin/perl # -# This Koha test module is a stub! +# This Koha test module is a stub! # Add more tests here!!! use strict; @@ -9,6 +9,6 @@ use warnings; use Test::More tests => 1; BEGIN { - use_ok('C4::Service'); + use_ok('C4::Service'); } diff --git a/t/db_dependent/ShelfBrowser.t b/t/db_dependent/ShelfBrowser.t index 27d37419ad..7716c1ef4f 100755 --- a/t/db_dependent/ShelfBrowser.t +++ b/t/db_dependent/ShelfBrowser.t @@ -13,20 +13,22 @@ use Koha::Database; use t::lib::TestBuilder; -use_ok('C4::ShelfBrowser', qw( GetNearbyItems )); +use_ok( 'C4::ShelfBrowser', qw( GetNearbyItems ) ); my $schema = Koha::Database->schema; $schema->storage->txn_begin; my $builder = t::lib::TestBuilder->new; -my $dbh = C4::Context->dbh; +my $dbh = C4::Context->dbh; $dbh->do(q|DELETE FROM reserves|); $dbh->do(q|DELETE FROM issues|); $dbh->do(q|DELETE FROM items|); -my $library = $builder->build({ - source => 'Branch', -}); +my $library = $builder->build( + { + source => 'Branch', + } +); my $cn; @@ -55,10 +57,10 @@ my @callnumbers = qw( my $record = MARC::Record->new(); $record->append_fields( - MARC::Field->new('100', ' ', ' ', a => 'Donald E. Knuth.'), - MARC::Field->new('245', ' ', ' ', a => 'The art of computer programming'), + MARC::Field->new( '100', ' ', ' ', a => 'Donald E. Knuth.' ), + MARC::Field->new( '245', ' ', ' ', a => 'The art of computer programming' ), ); -my ( $biblionumber ) = C4::Biblio::AddBiblio($record, ''); +my ($biblionumber) = C4::Biblio::AddBiblio( $record, '' ); for my $callnumber ( shuffle @callnumbers ) { my $itemnumber = $builder->build_sample_item( @@ -69,152 +71,166 @@ for my $callnumber ( shuffle @callnumbers ) { } )->itemnumber; $cn->{$callnumber} = { - biblionumber => $biblionumber, - itemnumber => $itemnumber, + biblionumber => $biblionumber, + itemnumber => $itemnumber, itemcallnumber => $callnumber, - } + }; } my $nearby; $nearby = C4::ShelfBrowser::GetNearbyItems( $cn->{'500.100'}{itemnumber} ); + # We have # < 320.000 400.100 410.100 500.100 510.100 520.100 600.000 > # 6 7 8 [9] 10 11 12 # Clicking on previous, we want a link to 150.100 -is( $nearby->{prev_item}{itemcallnumber}, '150.100', "Simple case: previous link 1/2" ); -is( $nearby->{prev_item}{itemnumber}, $cn->{'150.100'}{itemnumber}, "Simple case: previous link 2/2" ); -# Clicking on next, we want a link to 730.100 -is( $nearby->{next_item}{itemcallnumber}, '720.100', "Simple case: next link 1/2" ); -is( $nearby->{next_item}{itemnumber}, $cn->{'720.100'}{itemnumber}, "Simple case: next link 2/2" ); +is( $nearby->{prev_item}{itemcallnumber}, '150.100', "Simple case: previous link 1/2" ); +is( $nearby->{prev_item}{itemnumber}, $cn->{'150.100'}{itemnumber}, "Simple case: previous link 2/2" ); -is( $nearby->{items}[0]{itemcallnumber}, '320.000', "Simple case: item 1"); -is( $nearby->{items}[1]{itemcallnumber}, '400.100', "Simple case: item 2"); -is( $nearby->{items}[2]{itemcallnumber}, '410.100', "Simple case: item 3"); -is( $nearby->{items}[3]{itemcallnumber}, '500.100', "Simple case: item 4"); -is( $nearby->{items}[4]{itemcallnumber}, '510.100', "Simple case: item 5"); -is( $nearby->{items}[5]{itemcallnumber}, '520.100', "Simple case: item 6"); -is( $nearby->{items}[6]{itemcallnumber}, '600.000', "Simple case: item 7"); +# Clicking on next, we want a link to 730.100 +is( $nearby->{next_item}{itemcallnumber}, '720.100', "Simple case: next link 1/2" ); +is( $nearby->{next_item}{itemnumber}, $cn->{'720.100'}{itemnumber}, "Simple case: next link 2/2" ); + +is( $nearby->{items}[0]{itemcallnumber}, '320.000', "Simple case: item 1" ); +is( $nearby->{items}[1]{itemcallnumber}, '400.100', "Simple case: item 2" ); +is( $nearby->{items}[2]{itemcallnumber}, '410.100', "Simple case: item 3" ); +is( $nearby->{items}[3]{itemcallnumber}, '500.100', "Simple case: item 4" ); +is( $nearby->{items}[4]{itemcallnumber}, '510.100', "Simple case: item 5" ); +is( $nearby->{items}[5]{itemcallnumber}, '520.100', "Simple case: item 6" ); +is( $nearby->{items}[6]{itemcallnumber}, '600.000', "Simple case: item 7" ); $nearby = C4::ShelfBrowser::GetNearbyItems( $cn->{'500.100'}{itemnumber}, 2, 3 ); + # We have # < 400.100 410.100 500.100 510.100 520.100 > # 7 8 [9] 10 11 # Clicking on previous, we want a link to 320.000 -is( $nearby->{prev_item}{itemcallnumber}, '320.000', "Test gap: previous link 1/2" ); -is( $nearby->{prev_item}{itemnumber}, $cn->{'320.000'}{itemnumber}, "Test gap: previous link 2/2" ); -# Clicking on next, we want a link to 600.000 -is( $nearby->{next_item}{itemcallnumber}, '600.000', "Test gap: next link 1/2" ); -is( $nearby->{next_item}{itemnumber}, $cn->{'600.000'}{itemnumber}, "Test gap: next link 2/2" ); +is( $nearby->{prev_item}{itemcallnumber}, '320.000', "Test gap: previous link 1/2" ); +is( $nearby->{prev_item}{itemnumber}, $cn->{'320.000'}{itemnumber}, "Test gap: previous link 2/2" ); -is( scalar( @{$nearby->{items}} ), 5, "Test gap: got 5 items" ); -is( $nearby->{items}[0]{itemcallnumber}, '400.100', "Test gap: item 1"); -is( $nearby->{items}[1]{itemcallnumber}, '410.100', "Test gap: item 2"); -is( $nearby->{items}[2]{itemcallnumber}, '500.100', "Test gap: item 3"); -is( $nearby->{items}[3]{itemcallnumber}, '510.100', "Test gap: item 4"); -is( $nearby->{items}[4]{itemcallnumber}, '520.100', "Test gap: item 5"); +# Clicking on next, we want a link to 600.000 +is( $nearby->{next_item}{itemcallnumber}, '600.000', "Test gap: next link 1/2" ); +is( $nearby->{next_item}{itemnumber}, $cn->{'600.000'}{itemnumber}, "Test gap: next link 2/2" ); + +is( scalar( @{ $nearby->{items} } ), 5, "Test gap: got 5 items" ); +is( $nearby->{items}[0]{itemcallnumber}, '400.100', "Test gap: item 1" ); +is( $nearby->{items}[1]{itemcallnumber}, '410.100', "Test gap: item 2" ); +is( $nearby->{items}[2]{itemcallnumber}, '500.100', "Test gap: item 3" ); +is( $nearby->{items}[3]{itemcallnumber}, '510.100', "Test gap: item 4" ); +is( $nearby->{items}[4]{itemcallnumber}, '520.100', "Test gap: item 5" ); $nearby = C4::ShelfBrowser::GetNearbyItems( $cn->{'300.000'}{itemnumber} ); + # We have # < 150.100 200.100 210.100 300.000 320.000 400.100 410.100 > # 2 3 4 [5] 6 7 8 # Clicking on previous, we want a link to 100.100 -is( $nearby->{prev_item}{itemcallnumber}, '100.100', "Test start shelf: previous link 1/2" ); -is( $nearby->{prev_item}{itemnumber}, $cn->{'100.100'}{itemnumber}, "Test start shelf: previous link 2/2" ); +is( $nearby->{prev_item}{itemcallnumber}, '100.100', "Test start shelf: previous link 1/2" ); +is( $nearby->{prev_item}{itemnumber}, $cn->{'100.100'}{itemnumber}, "Test start shelf: previous link 2/2" ); + # Clicking on next, we want a link to 600.000 -is( $nearby->{next_item}{itemcallnumber}, '600.000', "Test start shelf: next link 1/2" ); -is( $nearby->{next_item}{itemnumber}, $cn->{'600.000'}{itemnumber}, "Test start shelf: next link 2/2" ); - -is( $nearby->{items}[0]{itemcallnumber}, '150.100', "Test start shelf: item 1"); -is( $nearby->{items}[1]{itemcallnumber}, '200.100', "Test start shelf: item 2"); -is( $nearby->{items}[2]{itemcallnumber}, '210.100', "Test start shelf: item 3"); -is( $nearby->{items}[3]{itemcallnumber}, '300.000', "Test start shelf: item 4"); -is( $nearby->{items}[4]{itemcallnumber}, '320.000', "Test start shelf: item 5"); -is( $nearby->{items}[5]{itemcallnumber}, '400.100', "Test start shelf: item 6"); -is( $nearby->{items}[6]{itemcallnumber}, '410.100', "Test start shelf: item 7"); - +is( $nearby->{next_item}{itemcallnumber}, '600.000', "Test start shelf: next link 1/2" ); +is( $nearby->{next_item}{itemnumber}, $cn->{'600.000'}{itemnumber}, "Test start shelf: next link 2/2" ); +is( $nearby->{items}[0]{itemcallnumber}, '150.100', "Test start shelf: item 1" ); +is( $nearby->{items}[1]{itemcallnumber}, '200.100', "Test start shelf: item 2" ); +is( $nearby->{items}[2]{itemcallnumber}, '210.100', "Test start shelf: item 3" ); +is( $nearby->{items}[3]{itemcallnumber}, '300.000', "Test start shelf: item 4" ); +is( $nearby->{items}[4]{itemcallnumber}, '320.000', "Test start shelf: item 5" ); +is( $nearby->{items}[5]{itemcallnumber}, '400.100', "Test start shelf: item 6" ); +is( $nearby->{items}[6]{itemcallnumber}, '410.100', "Test start shelf: item 7" ); $nearby = C4::ShelfBrowser::GetNearbyItems( $cn->{'100.100'}{itemnumber} ); + # We have # 100.100 150.100 200.100 210.100 > # [1] 2 3 4 # There is no previous link is( $nearby->{prev_item}, undef, "Test first item on a shelf: no previous link" ); + # Clicking on next, we want a link to 410.100 -is( $nearby->{next_item}{itemcallnumber}, '410.100', "Test first item on a shelf: next link 1/2" ); -is( $nearby->{next_item}{itemnumber}, $cn->{'410.100'}{itemnumber}, "Test first item on a shelf: next link 2/2" ); - -is( scalar( @{$nearby->{items}} ), 4, "Test first item on a shelf: There are 4 items displayed" ); -is( $nearby->{items}[0]{itemcallnumber}, '100.100', "Test first item on a shelf: item 1"); -is( $nearby->{items}[1]{itemcallnumber}, '150.100', "Test first item on a shelf: item 2"); -is( $nearby->{items}[2]{itemcallnumber}, '200.100', "Test first item on a shelf: item 3"); -is( $nearby->{items}[3]{itemcallnumber}, '210.100', "Test first item on a shelf: item 4"); +is( $nearby->{next_item}{itemcallnumber}, '410.100', "Test first item on a shelf: next link 1/2" ); +is( $nearby->{next_item}{itemnumber}, $cn->{'410.100'}{itemnumber}, "Test first item on a shelf: next link 2/2" ); +is( scalar( @{ $nearby->{items} } ), 4, "Test first item on a shelf: There are 4 items displayed" ); +is( $nearby->{items}[0]{itemcallnumber}, '100.100', "Test first item on a shelf: item 1" ); +is( $nearby->{items}[1]{itemcallnumber}, '150.100', "Test first item on a shelf: item 2" ); +is( $nearby->{items}[2]{itemcallnumber}, '200.100', "Test first item on a shelf: item 3" ); +is( $nearby->{items}[3]{itemcallnumber}, '210.100', "Test first item on a shelf: item 4" ); $nearby = C4::ShelfBrowser::GetNearbyItems( $cn->{'150.100'}{itemnumber} ); + # We have # 100.100 150.100 200.100 210.100 300.000 > # 1 [2] 3 4 5 # There is no previous link is( $nearby->{prev_item}, undef, "Test second item on a shelf: no previous link" ); + # Clicking on next, we want a link to 500.100 -is( $nearby->{next_item}{itemcallnumber}, '500.100', "Test second item on a shelf: next link 1/2" ); -is( $nearby->{next_item}{itemnumber}, $cn->{'500.100'}{itemnumber}, "Test second item on a shelf: next link 2/2" ); - -is( scalar( @{$nearby->{items}} ), 5, "Test second item on a shelf: got 5 items" ); -is( $nearby->{items}[0]{itemcallnumber}, '100.100', "Test second item on a shelf: item 1"); -is( $nearby->{items}[1]{itemcallnumber}, '150.100', "Test second item on a shelf: item 2"); -is( $nearby->{items}[2]{itemcallnumber}, '200.100', "Test second item on a shelf: item 3"); -is( $nearby->{items}[3]{itemcallnumber}, '210.100', "Test second item on a shelf: item 4"); -is( $nearby->{items}[4]{itemcallnumber}, '300.000', "Test second item on a shelf: item 5"); +is( $nearby->{next_item}{itemcallnumber}, '500.100', "Test second item on a shelf: next link 1/2" ); +is( $nearby->{next_item}{itemnumber}, $cn->{'500.100'}{itemnumber}, "Test second item on a shelf: next link 2/2" ); +is( scalar( @{ $nearby->{items} } ), 5, "Test second item on a shelf: got 5 items" ); +is( $nearby->{items}[0]{itemcallnumber}, '100.100', "Test second item on a shelf: item 1" ); +is( $nearby->{items}[1]{itemcallnumber}, '150.100', "Test second item on a shelf: item 2" ); +is( $nearby->{items}[2]{itemcallnumber}, '200.100', "Test second item on a shelf: item 3" ); +is( $nearby->{items}[3]{itemcallnumber}, '210.100', "Test second item on a shelf: item 4" ); +is( $nearby->{items}[4]{itemcallnumber}, '300.000', "Test second item on a shelf: item 5" ); $nearby = C4::ShelfBrowser::GetNearbyItems( $cn->{'710.100'}{itemnumber} ); + # We have # < 600.000 610.000 700.100 710.100 720.100 730.100 740.100 > # 12 13 14 [15] 16 17 18 # Clicking on previous, we want a link to 410.100 -is( $nearby->{prev_item}{itemcallnumber}, '410.100', "Test end shelf: previous link 1/2" ); -is( $nearby->{prev_item}{itemnumber}, $cn->{'410.100'}{itemnumber}, "Test end shelf: previous link 2/2" ); +is( $nearby->{prev_item}{itemcallnumber}, '410.100', "Test end shelf: previous link 1/2" ); +is( $nearby->{prev_item}{itemnumber}, $cn->{'410.100'}{itemnumber}, "Test end shelf: previous link 2/2" ); + # Clicking on next, we want a link to 730.100 is( $nearby->{next_item}{itemcallnumber}, '750.100', "Test end shelf: next link is a link to the last item 1/2" ); -is( $nearby->{next_item}{itemnumber}, $cn->{'750.100'}{itemnumber}, "Test end shelf: next link is a link to the last item 2/2" ); - -is( $nearby->{items}[0]{itemcallnumber}, '600.000', "Test end shelf: item 1"); -is( $nearby->{items}[1]{itemcallnumber}, '610.000', "Test end shelf: item 2"); -is( $nearby->{items}[2]{itemcallnumber}, '700.100', "Test end shelf: item 3"); -is( $nearby->{items}[3]{itemcallnumber}, '710.100', "Test end shelf: item 4"); -is( $nearby->{items}[4]{itemcallnumber}, '720.100', "Test end shelf: item 5"); -is( $nearby->{items}[5]{itemcallnumber}, '730.100', "Test end shelf: item 6"); -is( $nearby->{items}[6]{itemcallnumber}, '740.100', "Test end shelf: item 7"); +is( + $nearby->{next_item}{itemnumber}, $cn->{'750.100'}{itemnumber}, + "Test end shelf: next link is a link to the last item 2/2" +); +is( $nearby->{items}[0]{itemcallnumber}, '600.000', "Test end shelf: item 1" ); +is( $nearby->{items}[1]{itemcallnumber}, '610.000', "Test end shelf: item 2" ); +is( $nearby->{items}[2]{itemcallnumber}, '700.100', "Test end shelf: item 3" ); +is( $nearby->{items}[3]{itemcallnumber}, '710.100', "Test end shelf: item 4" ); +is( $nearby->{items}[4]{itemcallnumber}, '720.100', "Test end shelf: item 5" ); +is( $nearby->{items}[5]{itemcallnumber}, '730.100', "Test end shelf: item 6" ); +is( $nearby->{items}[6]{itemcallnumber}, '740.100', "Test end shelf: item 7" ); $nearby = C4::ShelfBrowser::GetNearbyItems( $cn->{'740.100'}{itemnumber} ); + # We have # < 710.100 720.100 730.100 740.100 750.100 # 15 16 17 [18] 19 # Clicking on previous, we want a link to -is( $nearby->{prev_item}{itemcallnumber}, '520.100', "Test end of the shelf: previous link 1/2" ); -is( $nearby->{prev_item}{itemnumber}, $cn->{'520.100'}{itemnumber}, "Test end of the shelf: previous link 2/2" ); +is( $nearby->{prev_item}{itemcallnumber}, '520.100', "Test end of the shelf: previous link 1/2" ); +is( $nearby->{prev_item}{itemnumber}, $cn->{'520.100'}{itemnumber}, "Test end of the shelf: previous link 2/2" ); + # No next link is( $nearby->{next_item}, undef, "Test end of the shelf: no next link" ); -is( scalar( @{$nearby->{items}} ), 5, "Test end of the shelf: got 5 items" ); -is( $nearby->{items}[0]{itemcallnumber}, '710.100', "Test end of the shelf: item 1"); -is( $nearby->{items}[1]{itemcallnumber}, '720.100', "Test end of the shelf: item 2"); -is( $nearby->{items}[2]{itemcallnumber}, '730.100', "Test end of the shelf: item 3"); -is( $nearby->{items}[3]{itemcallnumber}, '740.100', "Test end of the shelf: item 4"); -is( $nearby->{items}[4]{itemcallnumber}, '750.100', "Test end of the shelf: item 5"); +is( scalar( @{ $nearby->{items} } ), 5, "Test end of the shelf: got 5 items" ); +is( $nearby->{items}[0]{itemcallnumber}, '710.100', "Test end of the shelf: item 1" ); +is( $nearby->{items}[1]{itemcallnumber}, '720.100', "Test end of the shelf: item 2" ); +is( $nearby->{items}[2]{itemcallnumber}, '730.100', "Test end of the shelf: item 3" ); +is( $nearby->{items}[3]{itemcallnumber}, '740.100', "Test end of the shelf: item 4" ); +is( $nearby->{items}[4]{itemcallnumber}, '750.100', "Test end of the shelf: item 5" ); $nearby = C4::ShelfBrowser::GetNearbyItems( $cn->{'750.100'}{itemnumber} ); + # We have # < 720.100 730.100 740.100 750.100 # 16 17 18 [19] # Clicking on previous, we want a link to -is( $nearby->{prev_item}{itemcallnumber}, '600.000', "Test last item of the shelf: previous link 1/2" ); +is( $nearby->{prev_item}{itemcallnumber}, '600.000', "Test last item of the shelf: previous link 1/2" ); is( $nearby->{prev_item}{itemnumber}, $cn->{'600.000'}{itemnumber}, "Test last item of the shelf: previous link 2/2" ); + # No next link is( $nearby->{next_item}, undef, "Test end of the shelf: no next link" ); -is( scalar( @{$nearby->{items}} ), 4, "Test last item of the shelf: got 4 items" ); +is( scalar( @{ $nearby->{items} } ), 4, "Test last item of the shelf: got 4 items" ); diff --git a/t/db_dependent/Sitemapper.t b/t/db_dependent/Sitemapper.t index ebf69ce402..c1ea2536a7 100755 --- a/t/db_dependent/Sitemapper.t +++ b/t/db_dependent/Sitemapper.t @@ -58,7 +58,7 @@ subtest 'Sitemapper' => sub { dir => $dir, short => 0, ); - $sitemapper->run( "biblionumber>=$id1" ); + $sitemapper->run("biblionumber>=$id1"); my $file = "$dir/sitemapindex.xml"; ok( -e "$dir/sitemapindex.xml", 'File sitemapindex.xml created' ); @@ -103,7 +103,7 @@ EOS dir => $dir, short => 1, ); - $sitemapper->run( "biblionumber>=$id1" ); + $sitemapper->run("biblionumber>=$id1"); $file = "$dir/sitemap_0001.xml"; ok( -e $file, 'File sitemap_0001.xml with short URLs created' ); @@ -127,8 +127,9 @@ EOS # No need to create 75000 biblios here. Let's create 10 more with $MAX == 6. # Expecting 3 files: index plus 2 url files with 6 and 4 urls (when we start after biblio2). $Koha::Sitemapper::Writer::MAX = 6; - for my $count ( 0..9 ) { - my $biblio2 = $builder->build_sample_biblio->set({ datecreated => '2015-08-31', timestamp => '2015-08-31' })->store; + for my $count ( 0 .. 9 ) { + my $biblio2 = + $builder->build_sample_biblio->set( { datecreated => '2015-08-31', timestamp => '2015-08-31' } )->store; } $sitemapper = Koha::Sitemapper->new( @@ -137,7 +138,7 @@ EOS dir => $dir, short => 1, ); - $sitemapper->run( "biblionumber>$id2" ); # Note: new filter + $sitemapper->run("biblionumber>$id2"); # Note: new filter $file = "$dir/sitemapindex.xml"; ok( -e "$dir/sitemapindex.xml", 'File sitemapindex.xml for 10 bibs created' ); diff --git a/t/db_dependent/SocialData.t b/t/db_dependent/SocialData.t index b0f51c3a3e..d5e534834d 100755 --- a/t/db_dependent/SocialData.t +++ b/t/db_dependent/SocialData.t @@ -31,34 +31,36 @@ my $builder = t::lib::TestBuilder->new; $schema->storage->txn_begin; # trivial data for trivial tests -Koha::Biblioitems->search->update({ isbn => undef }); -$builder->build({ source => 'Biblioitem', value => { isbn => '0-596-52674-1' } }); -$builder->build({ source => 'Biblioitem', value => { isbn => '0-596-00289-0' } }); -$builder->build({ source => 'SocialData', value => { isbn => '0-596-52674-1', score_avg => 6.5 } }); -$builder->build({ source => 'SocialData', value => { isbn => '0-596-00289-0', score_avg => 7 } }); +Koha::Biblioitems->search->update( { isbn => undef } ); +$builder->build( { source => 'Biblioitem', value => { isbn => '0-596-52674-1' } } ); +$builder->build( { source => 'Biblioitem', value => { isbn => '0-596-00289-0' } } ); +$builder->build( { source => 'SocialData', value => { isbn => '0-596-52674-1', score_avg => 6.5 } } ); +$builder->build( { source => 'SocialData', value => { isbn => '0-596-00289-0', score_avg => 7 } } ); subtest 'get_data' => sub { plan tests => 3; my $data = C4::SocialData::get_data(); - is( $data, undef, 'get_data should return undef if no param given'); + is( $data, undef, 'get_data should return undef if no param given' ); $data = C4::SocialData::get_data('0-596-52674-1'); - is( $data->{isbn}, '0-596-52674-1', 'get_data should return the matching row'); - is( sprintf("%3.1f", $data->{score_avg}), 6.5, 'check score_avg'); + is( $data->{isbn}, '0-596-52674-1', 'get_data should return the matching row' ); + is( sprintf( "%3.1f", $data->{score_avg} ), 6.5, 'check score_avg' ); }; subtest 'get_report' => sub { plan tests => 3; - my $report = C4::SocialData::get_report(); + my $report = C4::SocialData::get_report(); + # if isbn not normalized, social data not found, resulting in without key is( $report->{'without'}->[0]->{'original'}, '0-596-52674-1', 'testing get_report gives isbn' ); - is( $report->{'without'}->[0]->{'isbn'}, '9780596526740', 'testing get_report' ); + is( $report->{'without'}->[0]->{'isbn'}, '9780596526740', 'testing get_report' ); # test if we can get with key instead - $schema->resultset('SocialData')->search({ isbn => '0-596-52674-1' })->next->update({ isbn => '9780596526740' }); - $report = C4::SocialData::get_report(); + $schema->resultset('SocialData')->search( { isbn => '0-596-52674-1' } ) + ->next->update( { isbn => '9780596526740' } ); + $report = C4::SocialData::get_report(); is( $report->{with}->[0]->{isbn}, '9780596526740', 'this isbn has social data' ); }; diff --git a/t/db_dependent/StockRotationItems.t b/t/db_dependent/StockRotationItems.t index c6b3afee25..90abf8bfc9 100755 --- a/t/db_dependent/StockRotationItems.t +++ b/t/db_dependent/StockRotationItems.t @@ -44,18 +44,20 @@ subtest 'Basic object tests' => sub { $schema->storage->txn_begin; - my $itm = $builder->build_sample_item; - my $stage = $builder->build({ source => 'Stockrotationstage' }); + my $itm = $builder->build_sample_item; + my $stage = $builder->build( { source => 'Stockrotationstage' } ); - my $item = $builder->build({ - source => 'Stockrotationitem', - value => { - itemnumber_id => $itm->itemnumber, - stage_id => $stage->{stage_id}, - }, - }); + my $item = $builder->build( + { + source => 'Stockrotationitem', + value => { + itemnumber_id => $itm->itemnumber, + stage_id => $stage->{stage_id}, + }, + } + ); - my $sritem = Koha::StockRotationItems->find($item->{itemnumber_id}); + my $sritem = Koha::StockRotationItems->find( $item->{itemnumber_id} ); isa_ok( $sritem, 'Koha::StockRotationItem', @@ -70,7 +72,6 @@ subtest 'Basic object tests' => sub { isa_ok( $sritem->stage, 'Koha::StockRotationStage', "Fetched related stage." ); is( $sritem->stage->stage_id, $stage->{stage_id}, "Related stage OK." ); - $schema->storage->txn_rollback; }; @@ -84,23 +85,24 @@ subtest 'Tests for needs_repatriating' => sub { my $sritem = $builder->build( { source => 'Stockrotationitem', - value => - { itemnumber_id => $builder->build_sample_item->itemnumber } + value => { itemnumber_id => $builder->build_sample_item->itemnumber } } ); - my $dbitem = Koha::StockRotationItems->find($sritem->{itemnumber_id}); - $dbitem->item->homebranch($dbitem->stage->branchcode_id); - $dbitem->item->holdingbranch($dbitem->stage->branchcode_id); + my $dbitem = Koha::StockRotationItems->find( $sritem->{itemnumber_id} ); + $dbitem->item->homebranch( $dbitem->stage->branchcode_id ); + $dbitem->item->holdingbranch( $dbitem->stage->branchcode_id ); $dbitem->stage->position(1); - my $dbrota = $dbitem->stage->rota; - my $newstage = $builder->build({ - source => 'Stockrotationstage', - value => { - rota_id => $dbrota->rota_id, - position => 2, + my $dbrota = $dbitem->stage->rota; + my $newstage = $builder->build( + { + source => 'Stockrotationstage', + value => { + rota_id => $dbrota->rota_id, + position => 2, + } } - }); + ); # - homebranch == holdingbranch [0] is( @@ -108,8 +110,8 @@ subtest 'Tests for needs_repatriating' => sub { "Homebranch == Holdingbranch." ); - my $branch = $builder->build({ source => 'Branch' }); - $dbitem->item->holdingbranch($branch->{branchcode}); + my $branch = $builder->build( { source => 'Branch' } ); + $dbitem->item->holdingbranch( $branch->{branchcode} ); # - homebranch != holdingbranch [1] is( @@ -118,8 +120,9 @@ subtest 'Tests for needs_repatriating' => sub { ); # Set to incorrect homebranch. - $dbitem->item->holdingbranch($dbitem->stage->branchcode_id); - $dbitem->item->homebranch($branch->{branchcode}); + $dbitem->item->holdingbranch( $dbitem->stage->branchcode_id ); + $dbitem->item->homebranch( $branch->{branchcode} ); + # - homebranch != stockrotationstage.branch & not in transit [1] is( $dbitem->needs_repatriating, 1, @@ -127,7 +130,8 @@ subtest 'Tests for needs_repatriating' => sub { ); # Set to in transit (by implication). - $dbitem->stage($newstage->{stage_id}); + $dbitem->stage( $newstage->{stage_id} ); + # - homebranch != stockrotaitonstage.branch & in transit [0] is( $dbitem->needs_repatriating, 1, @@ -144,46 +148,44 @@ subtest "Tests for repatriate." => sub { my $sritem_1 = $builder->build_object( { class => 'Koha::StockRotationItems', - value => { - itemnumber_id => $builder->build_sample_item->itemnumber - } + value => { itemnumber_id => $builder->build_sample_item->itemnumber } } ); - my $item_id = $sritem_1->item->itemnumber; + my $item_id = $sritem_1->item->itemnumber; my $srstage_1 = $sritem_1->stage; $sritem_1->discard_changes; $sritem_1->stage->position(1); $sritem_1->stage->duration(50); - my $branch = $builder->build({ source => 'Branch' }); - $sritem_1->item->holdingbranch($branch->{branchcode}); + my $branch = $builder->build( { source => 'Branch' } ); + $sritem_1->item->holdingbranch( $branch->{branchcode} ); # Test a straight up repatriate - ok($sritem_1->repatriate, "Repatriation done."); + ok( $sritem_1->repatriate, "Repatriation done." ); my $intransfer = $sritem_1->item->get_transfer; - is($intransfer->frombranch, $branch->{branchcode}, "Origin correct."); - is($intransfer->tobranch, $sritem_1->stage->branchcode_id, "Target Correct."); + is( $intransfer->frombranch, $branch->{branchcode}, "Origin correct." ); + is( $intransfer->tobranch, $sritem_1->stage->branchcode_id, "Target Correct." ); # Reset - $intransfer->datearrived(dt_from_string())->store; - $sritem_1->item->holdingbranch($branch->{branchcode}); + $intransfer->datearrived( dt_from_string() )->store; + $sritem_1->item->holdingbranch( $branch->{branchcode} ); # Setup a conflicting manual transfer my $item = Koha::Items->find($item_id); - $item->request_transfer({ to => $srstage_1->branchcode, reason => "Manual" }); + $item->request_transfer( { to => $srstage_1->branchcode, reason => "Manual" } ); $intransfer = $item->get_transfer; - is (ref($intransfer), 'Koha::Item::Transfer', "Conflicting transfer added"); - is ($intransfer->reason, 'Manual', "Conflicting transfer reason is 'Manual'"); + is( ref($intransfer), 'Koha::Item::Transfer', "Conflicting transfer added" ); + is( $intransfer->reason, 'Manual', "Conflicting transfer reason is 'Manual'" ); # Stockrotation should handle transfer clashes - is($sritem_1->repatriate, 0, "Repatriation skipped if transfer in progress."); + is( $sritem_1->repatriate, 0, "Repatriation skipped if transfer in progress." ); # Reset - $intransfer->datearrived(dt_from_string())->store; - $sritem_1->item->holdingbranch($branch->{branchcode}); + $intransfer->datearrived( dt_from_string() )->store; + $sritem_1->item->holdingbranch( $branch->{branchcode} ); # Confirm that stockrotation ignores transfer limits - t::lib::Mocks::mock_preference('UseBranchTransferLimits', 1); - t::lib::Mocks::mock_preference('BranchTransferLimitsType', 'itemtype'); + t::lib::Mocks::mock_preference( 'UseBranchTransferLimits', 1 ); + t::lib::Mocks::mock_preference( 'BranchTransferLimitsType', 'itemtype' ); my $limit = Koha::Item::Transfer::Limit->new( { fromBranch => $branch->{branchcode}, @@ -193,10 +195,10 @@ subtest "Tests for repatriate." => sub { )->store; # Stockrotation should overrule transfer limits - ok($sritem_1->repatriate, "Repatriation done regardless of transfer limits."); + ok( $sritem_1->repatriate, "Repatriation done regardless of transfer limits." ); $intransfer = $sritem_1->item->get_transfer; - is($intransfer->frombranch, $branch->{branchcode}, "Origin correct."); - is($intransfer->tobranch, $sritem_1->stage->branchcode_id, "Target Correct."); + is( $intransfer->frombranch, $branch->{branchcode}, "Origin correct." ); + is( $intransfer->tobranch, $sritem_1->stage->branchcode_id, "Target Correct." ); $schema->storage->txn_rollback; }; @@ -215,8 +217,8 @@ subtest "Tests for needs_advancing." => sub { }, } ); - my $dbitem = Koha::StockRotationItems->find($sritem->{itemnumber_id}); - is($dbitem->needs_advancing, 1, "An item that is fresh will always need advancing."); + my $dbitem = Koha::StockRotationItems->find( $sritem->{itemnumber_id} ); + is( $dbitem->needs_advancing, 1, "An item that is fresh will always need advancing." ); # Setup a pristine stockrotation context. $sritem = $builder->build( @@ -228,52 +230,59 @@ subtest "Tests for needs_advancing." => sub { } } ); - $dbitem = Koha::StockRotationItems->find($sritem->{itemnumber_id}); - $dbitem->item->homebranch($dbitem->stage->branchcode_id); - $dbitem->item->holdingbranch($dbitem->stage->branchcode_id); + $dbitem = Koha::StockRotationItems->find( $sritem->{itemnumber_id} ); + $dbitem->item->homebranch( $dbitem->stage->branchcode_id ); + $dbitem->item->holdingbranch( $dbitem->stage->branchcode_id ); $dbitem->stage->position(1); $dbitem->stage->duration(50); - my $dbtransfer = Koha::Item::Transfer->new({ - 'itemnumber' => $dbitem->itemnumber_id, - 'frombranch' => $dbitem->stage->branchcode_id, - 'tobranch' => $dbitem->stage->branchcode_id, - 'datesent' => dt_from_string(), - 'datearrived' => undef, - 'reason' => "StockrotationAdvance", - })->store; + my $dbtransfer = Koha::Item::Transfer->new( + { + 'itemnumber' => $dbitem->itemnumber_id, + 'frombranch' => $dbitem->stage->branchcode_id, + 'tobranch' => $dbitem->stage->branchcode_id, + 'datesent' => dt_from_string(), + 'datearrived' => undef, + 'reason' => "StockrotationAdvance", + } + )->store; # Test item will not be advanced if in transit. - is($dbitem->needs_advancing, 0, "Not ready to advance: in transfer."); + is( $dbitem->needs_advancing, 0, "Not ready to advance: in transfer." ); + # Test item will not be advanced if in transit even if fresh. $dbitem->fresh(1)->store; - is($dbitem->needs_advancing, 0, "Not ready to advance: in transfer (fresh)."); + is( $dbitem->needs_advancing, 0, "Not ready to advance: in transfer (fresh)." ); $dbitem->fresh(0)->store; # Test item will not be advanced if it has not spent enough time. - $dbtransfer->datearrived(dt_from_string())->store; - is($dbitem->needs_advancing, 0, "Not ready to advance: Not spent enough time."); + $dbtransfer->datearrived( dt_from_string() )->store; + is( $dbitem->needs_advancing, 0, "Not ready to advance: Not spent enough time." ); + # Test item will be advanced if it has not spent enough time, but is fresh. $dbitem->fresh(1)->store; - is($dbitem->needs_advancing, 1, "Advance: Not spent enough time, but fresh."); + is( $dbitem->needs_advancing, 1, "Advance: Not spent enough time, but fresh." ); $dbitem->fresh(0)->store; # Test item will be advanced if it has spent enough time. - $dbtransfer->datesent( # Item was sent 100 days ago... + $dbtransfer->datesent( # Item was sent 100 days ago... dt_from_string() - DateTime::Duration->new( days => 100 ) )->store; - $dbtransfer->datearrived( # And arrived 75 days ago. + $dbtransfer->datearrived( # And arrived 75 days ago. dt_from_string() - DateTime::Duration->new( days => 75 ) )->store; - is($dbitem->needs_advancing, 1, "Ready to be advanced."); + is( $dbitem->needs_advancing, 1, "Ready to be advanced." ); # Bug 30518: Confirm that DST boundaries do not explode. # mock_config does not work here, because of tz vs timezone subroutines my $context = Test::MockModule->new('C4::Context'); - $context->mock( 'tz', sub { - 'Europe/London'; - }); - my $bad_date = dt_from_string("2020-09-29T01:15:30", 'iso'); + $context->mock( + 'tz', + sub { + 'Europe/London'; + } + ); + my $bad_date = dt_from_string( "2020-09-29T01:15:30", 'iso' ); $dbtransfer->datesent($bad_date)->store; $dbtransfer->datearrived($bad_date)->store; $dbitem->stage->duration(180)->store; @@ -282,7 +291,9 @@ subtest "Tests for needs_advancing." => sub { # Test that missing historical branch transfers do not crash $dbtransfer->delete; - warning_is {$dbitem->needs_advancing} "We have no historical branch transfer for item " . $dbitem->item->itemnumber . "; This should not have happened!", "Missing transfer is warned."; + warning_is { $dbitem->needs_advancing } + "We have no historical branch transfer for item " . $dbitem->item->itemnumber . "; This should not have happened!", + "Missing transfer is warned."; $schema->storage->txn_rollback; }; @@ -294,95 +305,98 @@ subtest "Tests for advance." => sub { my $sritem_1 = $builder->build_object( { class => 'Koha::StockRotationItems', - value => { + value => { 'fresh' => 1, itemnumber_id => $builder->build_sample_item->itemnumber } } ); $sritem_1->discard_changes; - $sritem_1->item->holdingbranch($sritem_1->stage->branchcode_id); - my $item_id = $sritem_1->item->itemnumber; + $sritem_1->item->holdingbranch( $sritem_1->stage->branchcode_id ); + my $item_id = $sritem_1->item->itemnumber; my $srstage_1 = $sritem_1->stage; - $srstage_1->position(1)->duration(50)->store; # Configure stage. - # Configure item - $sritem_1->item->holdingbranch($srstage_1->branchcode_id)->store; - $sritem_1->item->homebranch($srstage_1->branchcode_id)->store; + $srstage_1->position(1)->duration(50)->store; # Configure stage. + # Configure item + $sritem_1->item->holdingbranch( $srstage_1->branchcode_id )->store; + $sritem_1->item->homebranch( $srstage_1->branchcode_id )->store; + # Sanity check - is($sritem_1->stage->stage_id, $srstage_1->stage_id, "Stage sanity check."); + is( $sritem_1->stage->stage_id, $srstage_1->stage_id, "Stage sanity check." ); # Test if an item is fresh, always move to first stage. - is($sritem_1->fresh, 1, "Fresh is correct."); + is( $sritem_1->fresh, 1, "Fresh is correct." ); $sritem_1->advance; - is($sritem_1->stage->stage_id, $srstage_1->stage_id, "Stage is first stage after fresh advance."); - is($sritem_1->fresh, 0, "Fresh reset after advance."); + is( $sritem_1->stage->stage_id, $srstage_1->stage_id, "Stage is first stage after fresh advance." ); + is( $sritem_1->fresh, 0, "Fresh reset after advance." ); # Test cases of single stage - $srstage_1->rota->cyclical(1)->store; # Set Rota to cyclical. - ok($sritem_1->advance, "Single stage cyclical advance done."); + $srstage_1->rota->cyclical(1)->store; # Set Rota to cyclical. + ok( $sritem_1->advance, "Single stage cyclical advance done." ); ## Refetch sritem_1 $sritem_1->discard_changes; - is($sritem_1->stage->stage_id, $srstage_1->stage_id, "Single stage cyclical stage OK."); + is( $sritem_1->stage->stage_id, $srstage_1->stage_id, "Single stage cyclical stage OK." ); # Test with indemand advance $sritem_1->indemand(1)->store; - ok($sritem_1->advance, "Indemand item advance done."); + ok( $sritem_1->advance, "Indemand item advance done." ); ## Refetch sritem_1 $sritem_1->discard_changes; - is($sritem_1->indemand, 0, "Indemand OK."); - is($sritem_1->stage->stage_id, $srstage_1->stage_id, "Indemand item advance stage OK."); + is( $sritem_1->indemand, 0, "Indemand OK." ); + is( $sritem_1->stage->stage_id, $srstage_1->stage_id, "Indemand item advance stage OK." ); # Multi stages - my $srstage_2 = $builder->build_object({ - class => 'Koha::StockRotationStages', - value => { duration => 50 } - }); + my $srstage_2 = $builder->build_object( + { + class => 'Koha::StockRotationStages', + value => { duration => 50 } + } + ); $srstage_2->discard_changes; - $srstage_2->move_to_group($sritem_1->stage->rota_id); + $srstage_2->move_to_group( $sritem_1->stage->rota_id ); $srstage_2->move_last; # Test a straight up advance - ok($sritem_1->advance, "Advancement done."); + ok( $sritem_1->advance, "Advancement done." ); ## Refetch sritem_1 $sritem_1->discard_changes; ## Test results - is($sritem_1->stage->stage_id, $srstage_2->stage_id, "Stage updated."); + is( $sritem_1->stage->stage_id, $srstage_2->stage_id, "Stage updated." ); is( $sritem_1->item->homebranch, $srstage_2->branchcode_id, "Item homebranch updated" ); my $transfer_request = $sritem_1->item->get_transfer; - is($transfer_request->frombranch, $srstage_1->branchcode_id, "Origin correct."); - is($transfer_request->tobranch, $srstage_2->branchcode_id, "Target Correct."); - is($transfer_request->datesent, undef, "Transfer requested, but not sent."); + is( $transfer_request->frombranch, $srstage_1->branchcode_id, "Origin correct." ); + is( $transfer_request->tobranch, $srstage_2->branchcode_id, "Target Correct." ); + is( $transfer_request->datesent, undef, "Transfer requested, but not sent." ); # Arrive at new branch - $transfer_request->datearrived(dt_from_string())->store; - $sritem_1->item->holdingbranch($srstage_2->branchcode_id)->store; + $transfer_request->datearrived( dt_from_string() )->store; + $sritem_1->item->holdingbranch( $srstage_2->branchcode_id )->store; # Test a cyclical advance - ok($sritem_1->advance, "Cyclical advancement done."); + ok( $sritem_1->advance, "Cyclical advancement done." ); ## Refetch sritem_1 $sritem_1->discard_changes; ## Test results - is($sritem_1->stage->stage_id, $srstage_1->stage_id, "Stage updated."); + is( $sritem_1->stage->stage_id, $srstage_1->stage_id, "Stage updated." ); is( $sritem_1->item->homebranch, $srstage_1->branchcode_id, "Item homebranch updated" ); $transfer_request = $sritem_1->item->get_transfer; - is($transfer_request->frombranch, $srstage_2->branchcode_id, "Origin correct."); - is($transfer_request->tobranch, $srstage_1->branchcode_id, "Target correct."); + is( $transfer_request->frombranch, $srstage_2->branchcode_id, "Origin correct." ); + is( $transfer_request->tobranch, $srstage_1->branchcode_id, "Target correct." ); # Arrive at new branch - $transfer_request->datearrived(dt_from_string())->store; - $sritem_1->item->holdingbranch($srstage_1->branchcode_id)->store; + $transfer_request->datearrived( dt_from_string() )->store; + $sritem_1->item->holdingbranch( $srstage_1->branchcode_id )->store; # Confirm that stockrotation ignores transfer limits - t::lib::Mocks::mock_preference('UseBranchTransferLimits', 1); - t::lib::Mocks::mock_preference('BranchTransferLimitsType', 'itemtype'); + t::lib::Mocks::mock_preference( 'UseBranchTransferLimits', 1 ); + t::lib::Mocks::mock_preference( 'BranchTransferLimitsType', 'itemtype' ); my $limit = Koha::Item::Transfer::Limit->new( { fromBranch => $srstage_1->branchcode_id, @@ -391,33 +405,33 @@ subtest "Tests for advance." => sub { } )->store; - ok($sritem_1->advance, "Advancement overrules transfer limits."); + ok( $sritem_1->advance, "Advancement overrules transfer limits." ); ## Refetch sritem_1 $sritem_1->discard_changes; ## Test results - is($sritem_1->stage->stage_id, $srstage_2->stage_id, "Stage updated ignoring transfer limits."); + is( $sritem_1->stage->stage_id, $srstage_2->stage_id, "Stage updated ignoring transfer limits." ); is( $sritem_1->item->homebranch, $srstage_2->branchcode_id, "Item homebranch updated ignoring transfer limits" ); $transfer_request = $sritem_1->item->get_transfer; - is($transfer_request->frombranch, $srstage_1->branchcode_id, "Origin correct ignoring transfer limits."); - is($transfer_request->tobranch, $srstage_2->branchcode_id, "Target correct ignoring transfer limits."); + is( $transfer_request->frombranch, $srstage_1->branchcode_id, "Origin correct ignoring transfer limits." ); + is( $transfer_request->tobranch, $srstage_2->branchcode_id, "Target correct ignoring transfer limits." ); # Arrive at new branch - $transfer_request->datearrived(dt_from_string())->store; - $sritem_1->item->holdingbranch($srstage_2->branchcode_id)->store; + $transfer_request->datearrived( dt_from_string() )->store; + $sritem_1->item->holdingbranch( $srstage_2->branchcode_id )->store; # Setup a conflicting manual transfer my $item = Koha::Items->find($item_id); - $item->request_transfer({ to => $srstage_1->branchcode, reason => "Manual" }); + $item->request_transfer( { to => $srstage_1->branchcode, reason => "Manual" } ); $transfer_request = $item->get_transfer; - is (ref($transfer_request), 'Koha::Item::Transfer', "Conflicting transfer added"); - is ($transfer_request->reason, 'Manual', "Conflicting transfer reason is 'Manual'"); + is( ref($transfer_request), 'Koha::Item::Transfer', "Conflicting transfer added" ); + is( $transfer_request->reason, 'Manual', "Conflicting transfer reason is 'Manual'" ); # Advance item whilst conflicting manual transfer exists - ok($sritem_1->advance, "Advancement done."); + ok( $sritem_1->advance, "Advancement done." ); ## Refetch sritem_1 $sritem_1->discard_changes; @@ -425,26 +439,26 @@ subtest "Tests for advance." => sub { $transfer_request->discard_changes; # Conflicted transfer should have been cancelled - isnt($transfer_request->datecancelled, undef, "Conflicting manual transfer was cancelled"); + isnt( $transfer_request->datecancelled, undef, "Conflicting manual transfer was cancelled" ); # StockRotationAdvance transfer added $transfer_request = $sritem_1->item->get_transfer; - is($transfer_request->reason, 'StockrotationAdvance', "StockrotationAdvance transfer added"); - is($transfer_request->frombranch, $srstage_2->branchcode_id, "Origin correct."); - is($transfer_request->tobranch, $srstage_1->branchcode_id, "Target correct."); + is( $transfer_request->reason, 'StockrotationAdvance', "StockrotationAdvance transfer added" ); + is( $transfer_request->frombranch, $srstage_2->branchcode_id, "Origin correct." ); + is( $transfer_request->tobranch, $srstage_1->branchcode_id, "Target correct." ); # Arrive at new branch - $transfer_request->datearrived(dt_from_string())->store; - $sritem_1->item->holdingbranch($srstage_1->branchcode_id)->store; + $transfer_request->datearrived( dt_from_string() )->store; + $sritem_1->item->holdingbranch( $srstage_1->branchcode_id )->store; # Setup a conflicting reserve transfer - $item->request_transfer({ to => $srstage_2->branchcode, reason => "Reserve" }); + $item->request_transfer( { to => $srstage_2->branchcode, reason => "Reserve" } ); $transfer_request = $item->get_transfer; - is (ref($transfer_request), 'Koha::Item::Transfer', "Conflicting transfer added"); - is ($transfer_request->reason, 'Reserve', "Conflicting transfer reason is 'Reserve'"); + is( ref($transfer_request), 'Koha::Item::Transfer', "Conflicting transfer added" ); + is( $transfer_request->reason, 'Reserve', "Conflicting transfer reason is 'Reserve'" ); # Advance item whilst conflicting reserve transfer exists - ok($sritem_1->advance, "Advancement done."); + ok( $sritem_1->advance, "Advancement done." ); ## Refetch sritem_1 $sritem_1->discard_changes; @@ -452,7 +466,7 @@ subtest "Tests for advance." => sub { $transfer_request->discard_changes; # Conflicted transfer should not been cancelled - is($transfer_request->datecancelled, undef, "Conflicting reserve transfer was not cancelled"); + is( $transfer_request->datecancelled, undef, "Conflicting reserve transfer was not cancelled" ); # StockRotationAdvance transfer added my $transfer_requests = Koha::Item::Transfers->search( @@ -462,70 +476,76 @@ subtest "Tests for advance." => sub { datecancelled => undef } ); - is($transfer_requests->count, '2', "StockrotationAdvance transfer queued"); + is( $transfer_requests->count, '2', "StockrotationAdvance transfer queued" ); # Arrive at new branch - $transfer_request->datearrived(dt_from_string())->store; - $sritem_1->item->holdingbranch($srstage_2->branchcode_id)->store; + $transfer_request->datearrived( dt_from_string() )->store; + $sritem_1->item->holdingbranch( $srstage_2->branchcode_id )->store; # StockRotationAdvance transfer added $transfer_request = $sritem_1->item->get_transfer; - is($transfer_request->reason, 'StockrotationAdvance', "StockrotationAdvance transfer remains after reserve is met"); - is($transfer_request->frombranch, $srstage_1->branchcode_id, "Origin correct."); - is($transfer_request->tobranch, $srstage_2->branchcode_id, "Target correct."); + is( + $transfer_request->reason, 'StockrotationAdvance', + "StockrotationAdvance transfer remains after reserve is met" + ); + is( $transfer_request->frombranch, $srstage_1->branchcode_id, "Origin correct." ); + is( $transfer_request->tobranch, $srstage_2->branchcode_id, "Target correct." ); # Arrive at new branch - $transfer_request->datearrived(dt_from_string())->store; - $sritem_1->item->holdingbranch($srstage_2->branchcode_id)->store; + $transfer_request->datearrived( dt_from_string() )->store; + $sritem_1->item->holdingbranch( $srstage_2->branchcode_id )->store; # Checked out item, advanced to next stage, checkedout from next stage # transfer should be generated, but not initiated - my $issue = $builder->build_object({ - class => 'Koha::Checkouts', - value => { - branchcode => $srstage_1->branchcode_id, - itemnumber => $sritem_1->item->itemnumber, - returndate => undef + my $issue = $builder->build_object( + { + class => 'Koha::Checkouts', + value => { + branchcode => $srstage_1->branchcode_id, + itemnumber => $sritem_1->item->itemnumber, + returndate => undef + } } - }); - $sritem_1->item->holdingbranch($srstage_1->branchcode_id)->store; - ok($sritem_1->advance, "Advancement done."); + ); + $sritem_1->item->holdingbranch( $srstage_1->branchcode_id )->store; + ok( $sritem_1->advance, "Advancement done." ); $transfer_request = $sritem_1->item->get_transfer; - is($transfer_request->frombranch, $srstage_1->branchcode_id, "Origin correct."); - is($transfer_request->tobranch, $srstage_1->branchcode_id, "Target correct."); - is($transfer_request->datesent, undef, "Transfer waiting to initiate until return."); + is( $transfer_request->frombranch, $srstage_1->branchcode_id, "Origin correct." ); + is( $transfer_request->tobranch, $srstage_1->branchcode_id, "Target correct." ); + is( $transfer_request->datesent, undef, "Transfer waiting to initiate until return." ); - $issue->delete; #remove issue - $sritem_1->advance; #advance back to second stage - # Set arrived - $transfer_request->datearrived(dt_from_string())->store; - $sritem_1->item->holdingbranch($srstage_2->branchcode_id)->store; + $issue->delete; #remove issue + $sritem_1->advance; #advance back to second stage + # Set arrived + $transfer_request->datearrived( dt_from_string() )->store; + $sritem_1->item->holdingbranch( $srstage_2->branchcode_id )->store; + $srstage_1->rota->cyclical(0)->store; # Set Rota to non-cyclical. - $srstage_1->rota->cyclical(0)->store; # Set Rota to non-cyclical. - - my $srstage_3 = $builder->build_object({ - class => 'Koha::StockRotationStages', - value => { duration => 50 } - }); + my $srstage_3 = $builder->build_object( + { + class => 'Koha::StockRotationStages', + value => { duration => 50 } + } + ); $srstage_3->discard_changes; - $srstage_3->move_to_group($sritem_1->stage->rota_id); + $srstage_3->move_to_group( $sritem_1->stage->rota_id ); $srstage_3->move_last; # Advance again, to end of rota. - ok($sritem_1->advance, "Non-cyclical advance to last stage."); + ok( $sritem_1->advance, "Non-cyclical advance to last stage." ); # Arrive at new branch - $transfer_request->datearrived(dt_from_string())->store; - $sritem_1->item->holdingbranch($srstage_3->branchcode_id)->store; + $transfer_request->datearrived( dt_from_string() )->store; + $sritem_1->item->holdingbranch( $srstage_3->branchcode_id )->store; # Advance again, Remove from rota. - ok($sritem_1->advance, "Non-cyclical advance."); + ok( $sritem_1->advance, "Non-cyclical advance." ); ## Refetch sritem_1 - $sritem_1 = Koha::StockRotationItems->find({ itemnumber_id => $item_id }); - is($sritem_1, undef, "StockRotationItem has been removed."); + $sritem_1 = Koha::StockRotationItems->find( { itemnumber_id => $item_id } ); + is( $sritem_1, undef, "StockRotationItem has been removed." ); $item = Koha::Items->find($item_id); - is($item->homebranch, $srstage_3->branchcode_id, "Item homebranch remains"); + is( $item->homebranch, $srstage_3->branchcode_id, "Item homebranch remains" ); $schema->storage->txn_rollback; }; @@ -544,8 +564,8 @@ subtest "Tests for investigate (singular)." => sub { } } ); - my $dbitem = Koha::StockRotationItems->find($sritem->{itemnumber_id}); - is($dbitem->investigate->{reason}, 'initiation', "fresh item initiates."); + my $dbitem = Koha::StockRotationItems->find( $sritem->{itemnumber_id} ); + is( $dbitem->investigate->{reason}, 'initiation', "fresh item initiates." ); # Test brand new item at stagebranch ['initiation'] $sritem = $builder->build( @@ -557,10 +577,10 @@ subtest "Tests for investigate (singular)." => sub { } } ); - $dbitem = Koha::StockRotationItems->find($sritem->{itemnumber_id}); - $dbitem->item->homebranch($dbitem->stage->branchcode_id)->store; - $dbitem->item->holdingbranch($dbitem->stage->branchcode_id)->store; - is($dbitem->investigate->{reason}, 'initiation', "fresh item at stagebranch initiates."); + $dbitem = Koha::StockRotationItems->find( $sritem->{itemnumber_id} ); + $dbitem->item->homebranch( $dbitem->stage->branchcode_id )->store; + $dbitem->item->holdingbranch( $dbitem->stage->branchcode_id )->store; + is( $dbitem->investigate->{reason}, 'initiation', "fresh item at stagebranch initiates." ); # Test item not at stagebranch with branchtransfer history ['repatriation'] $sritem = $builder->build( @@ -572,16 +592,18 @@ subtest "Tests for investigate (singular)." => sub { } } ); - $dbitem = Koha::StockRotationItems->find($sritem->{itemnumber_id}); - my $dbtransfer = Koha::Item::Transfer->new({ - 'itemnumber' => $dbitem->itemnumber_id, - 'frombranch' => $dbitem->item->homebranch, - 'tobranch' => $dbitem->item->homebranch, - 'datesent' => dt_from_string(), - 'datearrived' => dt_from_string(), - 'reason' => "StockrotationAdvance", - })->store; - is($dbitem->investigate->{reason}, 'repatriation', "older item repatriates."); + $dbitem = Koha::StockRotationItems->find( $sritem->{itemnumber_id} ); + my $dbtransfer = Koha::Item::Transfer->new( + { + 'itemnumber' => $dbitem->itemnumber_id, + 'frombranch' => $dbitem->item->homebranch, + 'tobranch' => $dbitem->item->homebranch, + 'datesent' => dt_from_string(), + 'datearrived' => dt_from_string(), + 'reason' => "StockrotationAdvance", + } + )->store; + is( $dbitem->investigate->{reason}, 'repatriation', "older item repatriates." ); # Test item at stagebranch with branchtransfer history ['not-ready'] $sritem = $builder->build( @@ -593,18 +615,20 @@ subtest "Tests for investigate (singular)." => sub { } } ); - $dbitem = Koha::StockRotationItems->find($sritem->{itemnumber_id}); - $dbtransfer = Koha::Item::Transfer->new({ - 'itemnumber' => $dbitem->itemnumber_id, - 'frombranch' => $dbitem->item->homebranch, - 'tobranch' => $dbitem->stage->branchcode_id, - 'datesent' => dt_from_string(), - 'datearrived' => dt_from_string(), - 'reason' => "StockrotationAdvance", - })->store; - $dbitem->item->homebranch($dbitem->stage->branchcode_id)->store; - $dbitem->item->holdingbranch($dbitem->stage->branchcode_id)->store; - is($dbitem->investigate->{reason}, 'not-ready', "older item at stagebranch not-ready."); + $dbitem = Koha::StockRotationItems->find( $sritem->{itemnumber_id} ); + $dbtransfer = Koha::Item::Transfer->new( + { + 'itemnumber' => $dbitem->itemnumber_id, + 'frombranch' => $dbitem->item->homebranch, + 'tobranch' => $dbitem->stage->branchcode_id, + 'datesent' => dt_from_string(), + 'datearrived' => dt_from_string(), + 'reason' => "StockrotationAdvance", + } + )->store; + $dbitem->item->homebranch( $dbitem->stage->branchcode_id )->store; + $dbitem->item->holdingbranch( $dbitem->stage->branchcode_id )->store; + is( $dbitem->investigate->{reason}, 'not-ready', "older item at stagebranch not-ready." ); # Test item due for advancement ['advancement'] $sritem = $builder->build( @@ -616,23 +640,27 @@ subtest "Tests for investigate (singular)." => sub { } } ); - $dbitem = Koha::StockRotationItems->find($sritem->{itemnumber_id}); + $dbitem = Koha::StockRotationItems->find( $sritem->{itemnumber_id} ); $dbitem->indemand(0)->store; $dbitem->stage->duration(50)->store; - my $sent_duration = DateTime::Duration->new( days => 55); - my $arrived_duration = DateTime::Duration->new( days => 52); - $dbtransfer = Koha::Item::Transfer->new({ - 'itemnumber' => $dbitem->itemnumber_id, - 'frombranch' => $dbitem->item->homebranch, - 'tobranch' => $dbitem->stage->branchcode_id, - 'datesent' => dt_from_string() - $sent_duration, - 'datearrived' => dt_from_string() - $arrived_duration, - 'reason' => "StockrotationAdvance", - })->store; - $dbitem->item->homebranch($dbitem->stage->branchcode_id)->store; - $dbitem->item->holdingbranch($dbitem->stage->branchcode_id)->store; - is($dbitem->investigate->{reason}, 'advancement', - "Item ready for advancement."); + my $sent_duration = DateTime::Duration->new( days => 55 ); + my $arrived_duration = DateTime::Duration->new( days => 52 ); + $dbtransfer = Koha::Item::Transfer->new( + { + 'itemnumber' => $dbitem->itemnumber_id, + 'frombranch' => $dbitem->item->homebranch, + 'tobranch' => $dbitem->stage->branchcode_id, + 'datesent' => dt_from_string() - $sent_duration, + 'datearrived' => dt_from_string() - $arrived_duration, + 'reason' => "StockrotationAdvance", + } + )->store; + $dbitem->item->homebranch( $dbitem->stage->branchcode_id )->store; + $dbitem->item->holdingbranch( $dbitem->stage->branchcode_id )->store; + is( + $dbitem->investigate->{reason}, 'advancement', + "Item ready for advancement." + ); # Test item due for advancement but in-demand ['in-demand'] $sritem = $builder->build( @@ -644,23 +672,27 @@ subtest "Tests for investigate (singular)." => sub { } } ); - $dbitem = Koha::StockRotationItems->find($sritem->{itemnumber_id}); + $dbitem = Koha::StockRotationItems->find( $sritem->{itemnumber_id} ); $dbitem->indemand(1)->store; $dbitem->stage->duration(50)->store; - $sent_duration = DateTime::Duration->new( days => 55); - $arrived_duration = DateTime::Duration->new( days => 52); - $dbtransfer = Koha::Item::Transfer->new({ - 'itemnumber' => $dbitem->itemnumber_id, - 'frombranch' => $dbitem->item->homebranch, - 'tobranch' => $dbitem->stage->branchcode_id, - 'datesent' => dt_from_string() - $sent_duration, - 'datearrived' => dt_from_string() - $arrived_duration, - 'reason' => "StockrotationAdvance", - })->store; - $dbitem->item->homebranch($dbitem->stage->branchcode_id)->store; - $dbitem->item->holdingbranch($dbitem->stage->branchcode_id)->store; - is($dbitem->investigate->{reason}, 'in-demand', - "Item advances, but in-demand."); + $sent_duration = DateTime::Duration->new( days => 55 ); + $arrived_duration = DateTime::Duration->new( days => 52 ); + $dbtransfer = Koha::Item::Transfer->new( + { + 'itemnumber' => $dbitem->itemnumber_id, + 'frombranch' => $dbitem->item->homebranch, + 'tobranch' => $dbitem->stage->branchcode_id, + 'datesent' => dt_from_string() - $sent_duration, + 'datearrived' => dt_from_string() - $arrived_duration, + 'reason' => "StockrotationAdvance", + } + )->store; + $dbitem->item->homebranch( $dbitem->stage->branchcode_id )->store; + $dbitem->item->holdingbranch( $dbitem->stage->branchcode_id )->store; + is( + $dbitem->investigate->{reason}, 'in-demand', + "Item advances, but in-demand." + ); # Test item ready for advancement, but at wrong library ['repatriation'] $sritem = $builder->build( @@ -672,21 +704,25 @@ subtest "Tests for investigate (singular)." => sub { } } ); - $dbitem = Koha::StockRotationItems->find($sritem->{itemnumber_id}); + $dbitem = Koha::StockRotationItems->find( $sritem->{itemnumber_id} ); $dbitem->indemand(0)->store; $dbitem->stage->duration(50)->store; - $sent_duration = DateTime::Duration->new( days => 55); - $arrived_duration = DateTime::Duration->new( days => 52); - $dbtransfer = Koha::Item::Transfer->new({ - 'itemnumber' => $dbitem->itemnumber_id, - 'frombranch' => $dbitem->item->homebranch, - 'tobranch' => $dbitem->stage->branchcode_id, - 'datesent' => dt_from_string() - $sent_duration, - 'datearrived' => dt_from_string() - $arrived_duration, - 'reason' => "StockrotationAdvance", - })->store; - is($dbitem->investigate->{reason}, 'repatriation', - "Item advances, but not at stage branch."); + $sent_duration = DateTime::Duration->new( days => 55 ); + $arrived_duration = DateTime::Duration->new( days => 52 ); + $dbtransfer = Koha::Item::Transfer->new( + { + 'itemnumber' => $dbitem->itemnumber_id, + 'frombranch' => $dbitem->item->homebranch, + 'tobranch' => $dbitem->stage->branchcode_id, + 'datesent' => dt_from_string() - $sent_duration, + 'datearrived' => dt_from_string() - $arrived_duration, + 'reason' => "StockrotationAdvance", + } + )->store; + is( + $dbitem->investigate->{reason}, 'repatriation', + "Item advances, but not at stage branch." + ); $schema->storage->txn_rollback; }; @@ -695,54 +731,59 @@ subtest "Tests for toggle_indemand" => sub { plan tests => 15; $schema->storage->txn_begin; - my $sritem = $builder->build({ - source => 'Stockrotationitem', - value => { 'fresh' => 0, 'indemand' => 0 } - }); - my $dbitem = Koha::StockRotationItems->find($sritem->{itemnumber_id}); + my $sritem = $builder->build( + { + source => 'Stockrotationitem', + value => { 'fresh' => 0, 'indemand' => 0 } + } + ); + my $dbitem = Koha::StockRotationItems->find( $sritem->{itemnumber_id} ); my $firstbranch = $dbitem->stage->branchcode_id; $dbitem->item->holdingbranch($firstbranch)->store; my $dbstage = $dbitem->stage; - $dbstage->position(1)->duration(50)->store; # Configure stage. - # Configure item + $dbstage->position(1)->duration(50)->store; # Configure stage. + # Configure item $dbitem->item->holdingbranch($firstbranch)->store; $dbitem->item->homebranch($firstbranch)->store; + # Sanity check - is($dbitem->stage->stage_id, $dbstage->stage_id, "Stage sanity check."); + is( $dbitem->stage->stage_id, $dbstage->stage_id, "Stage sanity check." ); # Test if an item is not in transfer, toggle always acts. - is($dbitem->indemand, 0, "Item not in transfer starts with indemand disabled."); + is( $dbitem->indemand, 0, "Item not in transfer starts with indemand disabled." ); $dbitem->toggle_indemand; - is($dbitem->indemand, 1, "Item not in transfer toggled correctly first time."); + is( $dbitem->indemand, 1, "Item not in transfer toggled correctly first time." ); $dbitem->toggle_indemand; - is($dbitem->indemand, 0, "Item not in transfer toggled correctly second time."); + is( $dbitem->indemand, 0, "Item not in transfer toggled correctly second time." ); # Add stages - my $srstage = $builder->build({ - source => 'Stockrotationstage', - value => { duration => 50 } - }); - my $dbstage2 = Koha::StockRotationStages->find($srstage->{stage_id}); - $dbstage2->move_to_group($dbitem->stage->rota_id); + my $srstage = $builder->build( + { + source => 'Stockrotationstage', + value => { duration => 50 } + } + ); + my $dbstage2 = Koha::StockRotationStages->find( $srstage->{stage_id} ); + $dbstage2->move_to_group( $dbitem->stage->rota_id ); $dbstage2->position(2)->store; my $secondbranch = $dbstage2->branchcode_id; # Test an item in transfer, toggle cancels transfer and resets indemand. - ok($dbitem->advance, "Advancement done."); + ok( $dbitem->advance, "Advancement done." ); $dbitem->get_from_storage; my $transfer = $dbitem->item->get_transfer; - is(ref($transfer), 'Koha::Item::Transfer', 'Item set to in transfer as expected'); - is($transfer->frombranch, $firstbranch, 'Transfer from set correctly'); - is($transfer->tobranch, $secondbranch, 'Transfer to set correctly'); - is($transfer->datearrived, undef, 'Transfer datearrived not set'); + is( ref($transfer), 'Koha::Item::Transfer', 'Item set to in transfer as expected' ); + is( $transfer->frombranch, $firstbranch, 'Transfer from set correctly' ); + is( $transfer->tobranch, $secondbranch, 'Transfer to set correctly' ); + is( $transfer->datearrived, undef, 'Transfer datearrived not set' ); $dbitem->toggle_indemand; my $updated_transfer = $transfer->get_from_storage; - is($updated_transfer->frombranch, $firstbranch, 'Transfer from retained correctly'); - is($updated_transfer->tobranch, $firstbranch, 'Transfer to updated correctly'); - isnt($updated_transfer->datearrived, undef, 'Transfer datearrived set as expected'); - is($dbitem->indemand, 0, "Item retains indemand as expected."); - is($dbitem->stage_id, $dbstage->id, 'Item stage reset as expected.'); - is($dbitem->item->homebranch, $firstbranch, 'Item homebranch reset as expected.'); + is( $updated_transfer->frombranch, $firstbranch, 'Transfer from retained correctly' ); + is( $updated_transfer->tobranch, $firstbranch, 'Transfer to updated correctly' ); + isnt( $updated_transfer->datearrived, undef, 'Transfer datearrived set as expected' ); + is( $dbitem->indemand, 0, "Item retains indemand as expected." ); + is( $dbitem->stage_id, $dbstage->id, 'Item stage reset as expected.' ); + is( $dbitem->item->homebranch, $firstbranch, 'Item homebranch reset as expected.' ); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/StockRotationRotas.t b/t/db_dependent/StockRotationRotas.t index 9d5401f140..8e6cc00623 100755 --- a/t/db_dependent/StockRotationRotas.t +++ b/t/db_dependent/StockRotationRotas.t @@ -37,30 +37,36 @@ subtest 'Basic object tests' => sub { my $builder = t::lib::TestBuilder->new; - my $rota = $builder->build({ source => 'Stockrotationrota' }); + my $rota = $builder->build( { source => 'Stockrotationrota' } ); - my $srrota = Koha::StockRotationRotas->find($rota->{rota_id}); + my $srrota = Koha::StockRotationRotas->find( $rota->{rota_id} ); isa_ok( $srrota, 'Koha::StockRotationRota', "Correctly create and load a stock rotation rota." ); - $builder->build({ - source => 'Stockrotationstage', - value => { rota_id => $rota->{rota_id} }, - }); - $builder->build({ - source => 'Stockrotationstage', - value => { rota_id => $rota->{rota_id} }, - }); - $builder->build({ - source => 'Stockrotationstage', - value => { rota_id => $rota->{rota_id} }, - }); + $builder->build( + { + source => 'Stockrotationstage', + value => { rota_id => $rota->{rota_id} }, + } + ); + $builder->build( + { + source => 'Stockrotationstage', + value => { rota_id => $rota->{rota_id} }, + } + ); + $builder->build( + { + source => 'Stockrotationstage', + value => { rota_id => $rota->{rota_id} }, + } + ); my $srstages = $srrota->stockrotationstages; - is( $srstages->count, 3, 'Correctly fetched stockrotationstages associated with this rota'); + is( $srstages->count, 3, 'Correctly fetched stockrotationstages associated with this rota' ); isa_ok( $srstages->next, 'Koha::StockRotationStage', "Relationship correctly creates Koha::Objects." ); @@ -68,27 +74,29 @@ subtest 'Basic object tests' => sub { my $item = $builder->build_sample_item; - $srrota->add_item($item->itemnumber); + $srrota->add_item( $item->itemnumber ); is( - Koha::StockRotationItems->find($item->itemnumber)->stage_id, + Koha::StockRotationItems->find( $item->itemnumber )->stage_id, $srrota->first_stage->stage_id, "Adding an item results in a new sritem item being assigned to the first stage." ); - my $newrota = $builder->build({ source => 'Stockrotationrota' }); + my $newrota = $builder->build( { source => 'Stockrotationrota' } ); - my $srnewrota = Koha::StockRotationRotas->find($newrota->{rota_id}); + my $srnewrota = Koha::StockRotationRotas->find( $newrota->{rota_id} ); - $builder->build({ - source => 'Stockrotationstage', - value => { rota_id => $newrota->{rota_id} }, - }); + $builder->build( + { + source => 'Stockrotationstage', + value => { rota_id => $newrota->{rota_id} }, + } + ); - $srnewrota->add_item($item->itemnumber); + $srnewrota->add_item( $item->itemnumber ); is( - Koha::StockRotationItems->find($item->itemnumber)->stage_id, + Koha::StockRotationItems->find( $item->itemnumber )->stage_id, $srnewrota->stockrotationstages->next->stage_id, "Moving an item results in that sritem being assigned to the new first stage." ); @@ -103,30 +111,39 @@ subtest '->first_stage test' => sub { my $builder = t::lib::TestBuilder->new; - my $rota = $builder->build({ source => 'Stockrotationrota' }); + my $rota = $builder->build( { source => 'Stockrotationrota' } ); - my $stage1 = $builder->build({ - source => 'Stockrotationstage', - value => { rota_id => $rota->{rota_id} }, - }); - my $stage2 = $builder->build({ - source => 'Stockrotationstage', - value => { rota_id => $rota->{rota_id} }, - }); - my $stage3 = $builder->build({ - source => 'Stockrotationstage', - value => { rota_id => $rota->{rota_id} }, - }); + my $stage1 = $builder->build( + { + source => 'Stockrotationstage', + value => { rota_id => $rota->{rota_id} }, + } + ); + my $stage2 = $builder->build( + { + source => 'Stockrotationstage', + value => { rota_id => $rota->{rota_id} }, + } + ); + my $stage3 = $builder->build( + { + source => 'Stockrotationstage', + value => { rota_id => $rota->{rota_id} }, + } + ); - my $srrota = Koha::StockRotationRotas->find($rota->{rota_id}); - my $srstage2 = Koha::StockRotationStages->find($stage2->{stage_id}); + my $srrota = Koha::StockRotationRotas->find( $rota->{rota_id} ); + my $srstage2 = Koha::StockRotationStages->find( $stage2->{stage_id} ); my $firststage = $srstage2->first_sibling || $srstage2; is( $srrota->first_stage->stage_id, $firststage->stage_id, "First stage works" ); $srstage2->move_first; - is( Koha::StockRotationRotas->find($rota->{rota_id})->first_stage->stage_id, $stage2->{stage_id}, "Stage re-organized" ); + is( + Koha::StockRotationRotas->find( $rota->{rota_id} )->first_stage->stage_id, $stage2->{stage_id}, + "Stage re-organized" + ); $schema->storage->txn_rollback; }; @@ -138,31 +155,41 @@ subtest '->items test' => sub { my $builder = t::lib::TestBuilder->new; - my $rota = $builder->build({ source => 'Stockrotationrota' }); + my $rota = $builder->build( { source => 'Stockrotationrota' } ); - my $stage1 = $builder->build({ - source => 'Stockrotationstage', - value => { rota_id => $rota->{rota_id} }, - }); - my $stage2 = $builder->build({ - source => 'Stockrotationstage', - value => { rota_id => $rota->{rota_id} }, - }); - my $stage3 = $builder->build({ - source => 'Stockrotationstage', - value => { rota_id => $rota->{rota_id} }, - }); + my $stage1 = $builder->build( + { + source => 'Stockrotationstage', + value => { rota_id => $rota->{rota_id} }, + } + ); + my $stage2 = $builder->build( + { + source => 'Stockrotationstage', + value => { rota_id => $rota->{rota_id} }, + } + ); + my $stage3 = $builder->build( + { + source => 'Stockrotationstage', + value => { rota_id => $rota->{rota_id} }, + } + ); - map { $builder->build({ - source => 'Stockrotationitem', - value => { stage_id => $_ }, - }) } ( + map { + $builder->build( + { + source => 'Stockrotationitem', + value => { stage_id => $_ }, + } + ) + } ( $stage1->{stage_id}, $stage1->{stage_id}, $stage2->{stage_id}, $stage2->{stage_id}, $stage3->{stage_id}, $stage3->{stage_id}, ); - my $srrota = Koha::StockRotationRotas->find($rota->{rota_id}); + my $srrota = Koha::StockRotationRotas->find( $rota->{rota_id} ); is( $srrota->stockrotationitems->count, diff --git a/t/db_dependent/StockRotationStages.t b/t/db_dependent/StockRotationStages.t index ae94473e22..0ebca2e75c 100755 --- a/t/db_dependent/StockRotationStages.t +++ b/t/db_dependent/StockRotationStages.t @@ -36,17 +36,19 @@ subtest 'Basic object tests' => sub { $schema->storage->txn_begin; - my $library = $builder->build({ source => 'Branch' }); - my $rota = $builder->build({ source => 'Stockrotationrota' }); - my $stage = $builder->build({ - source => 'Stockrotationstage', - value => { - branchcode_id => $library->{branchcode}, - rota_id => $rota->{rota_id}, - }, - }); + my $library = $builder->build( { source => 'Branch' } ); + my $rota = $builder->build( { source => 'Stockrotationrota' } ); + my $stage = $builder->build( + { + source => 'Stockrotationstage', + value => { + branchcode_id => $library->{branchcode}, + rota_id => $rota->{rota_id}, + }, + } + ); - my $srstage = Koha::StockRotationStages->find($stage->{stage_id}); + my $srstage = Koha::StockRotationStages->find( $stage->{stage_id} ); isa_ok( $srstage, 'Koha::StockRotationStage', @@ -69,34 +71,44 @@ subtest 'DBIx::Class::Ordered tests' => sub { $schema->storage->txn_begin; - my $library = $builder->build({ source => 'Branch' }); - my $rota = $builder->build({ source => 'Stockrotationrota' }); - my $stagefirst = $builder->build({ - source => 'Stockrotationstage', - value => { rota_id => $rota->{rota_id}, position => 1 } - }); - my $stageprevious = $builder->build({ - source => 'Stockrotationstage', - value => { rota_id => $rota->{rota_id}, position => 2 } - }); - my $stage = $builder->build({ - source => 'Stockrotationstage', - value => { rota_id => $rota->{rota_id}, position => 3 }, - }); - my $stagenext = $builder->build({ - source => 'Stockrotationstage', - value => { rota_id => $rota->{rota_id}, position => 4 } - }); - my $stagelast = $builder->build({ - source => 'Stockrotationstage', - value => { rota_id => $rota->{rota_id}, position => 5 } - }); + my $library = $builder->build( { source => 'Branch' } ); + my $rota = $builder->build( { source => 'Stockrotationrota' } ); + my $stagefirst = $builder->build( + { + source => 'Stockrotationstage', + value => { rota_id => $rota->{rota_id}, position => 1 } + } + ); + my $stageprevious = $builder->build( + { + source => 'Stockrotationstage', + value => { rota_id => $rota->{rota_id}, position => 2 } + } + ); + my $stage = $builder->build( + { + source => 'Stockrotationstage', + value => { rota_id => $rota->{rota_id}, position => 3 }, + } + ); + my $stagenext = $builder->build( + { + source => 'Stockrotationstage', + value => { rota_id => $rota->{rota_id}, position => 4 } + } + ); + my $stagelast = $builder->build( + { + source => 'Stockrotationstage', + value => { rota_id => $rota->{rota_id}, position => 5 } + } + ); - my $srstage = Koha::StockRotationStages->find($stage->{stage_id}); + my $srstage = Koha::StockRotationStages->find( $stage->{stage_id} ); - is($srstage->siblings->count, 4, "Siblings works."); - is($srstage->previous_siblings->count, 2, "Previous Siblings works."); - is($srstage->next_siblings->count, 2, "Next Siblings works."); + is( $srstage->siblings->count, 4, "Siblings works." ); + is( $srstage->previous_siblings->count, 2, "Previous Siblings works." ); + is( $srstage->next_siblings->count, 2, "Next Siblings works." ); my $map = { first_sibling => $stagefirst, @@ -104,52 +116,53 @@ subtest 'DBIx::Class::Ordered tests' => sub { next_sibling => $stagenext, last_sibling => $stagelast, }; + # Test plain relations: while ( my ( $srxsr, $check ) = each %{$map} ) { my $sr = $srstage->$srxsr; - isa_ok($sr, 'Koha::StockRotationStage', "Fetched using '$srxsr'."); - is($sr->stage_id, $check->{stage_id}, "'$srxsr' data is correct."); - }; + isa_ok( $sr, 'Koha::StockRotationStage', "Fetched using '$srxsr'." ); + is( $sr->stage_id, $check->{stage_id}, "'$srxsr' data is correct." ); + } # Test mutators ## Move Previous - ok($srstage->move_previous, "Previous."); - is($srstage->previous_sibling->stage_id, $stagefirst->{stage_id}, "Previous, correct previous."); - is($srstage->next_sibling->stage_id, $stageprevious->{stage_id}, "Previous, correct next."); + ok( $srstage->move_previous, "Previous." ); + is( $srstage->previous_sibling->stage_id, $stagefirst->{stage_id}, "Previous, correct previous." ); + is( $srstage->next_sibling->stage_id, $stageprevious->{stage_id}, "Previous, correct next." ); ## Move Next - ok($srstage->move_next, "Back to middle."); - is($srstage->previous_sibling->stage_id, $stageprevious->{stage_id}, "Middle, correct previous."); - is($srstage->next_sibling->stage_id, $stagenext->{stage_id}, "Middle, correct next."); + ok( $srstage->move_next, "Back to middle." ); + is( $srstage->previous_sibling->stage_id, $stageprevious->{stage_id}, "Middle, correct previous." ); + is( $srstage->next_sibling->stage_id, $stagenext->{stage_id}, "Middle, correct next." ); ## Move First - ok($srstage->move_first, "First."); - is($srstage->previous_sibling, 0, "First, correct previous."); - is($srstage->next_sibling->stage_id, $stagefirst->{stage_id}, "First, correct next."); + ok( $srstage->move_first, "First." ); + is( $srstage->previous_sibling, 0, "First, correct previous." ); + is( $srstage->next_sibling->stage_id, $stagefirst->{stage_id}, "First, correct next." ); ## Move Last - ok($srstage->move_last, "Last."); - is($srstage->previous_sibling->stage_id, $stagelast->{stage_id}, "Last, correct previous."); - is($srstage->next_sibling, 0, "Last, correct next."); + ok( $srstage->move_last, "Last." ); + is( $srstage->previous_sibling->stage_id, $stagelast->{stage_id}, "Last, correct previous." ); + is( $srstage->next_sibling, 0, "Last, correct next." ); ## Move To ### Out of range moves. is( - $srstage->move_to($srstage->siblings->count + 2), + $srstage->move_to( $srstage->siblings->count + 2 ), 0, "Move above count of stages." ); - is($srstage->move_to(0), 0, "Move to 0th position."); - is($srstage->move_to(-1), 0, "Move to negative position."); + is( $srstage->move_to(0), 0, "Move to 0th position." ); + is( $srstage->move_to(-1), 0, "Move to negative position." ); ### Move To - ok($srstage->move_to(3), "Move."); - is($srstage->previous_sibling->stage_id, $stageprevious->{stage_id}, "Move, correct previous."); - is($srstage->next_sibling->stage_id, $stagenext->{stage_id}, "Move, correct next."); + ok( $srstage->move_to(3), "Move." ); + is( $srstage->previous_sibling->stage_id, $stageprevious->{stage_id}, "Move, correct previous." ); + is( $srstage->next_sibling->stage_id, $stagenext->{stage_id}, "Move, correct next." ); # Group manipulation - my $newrota = $builder->build({ source => 'Stockrotationrota' }); - ok($srstage->move_to_group($newrota->{rota_id}), "Move to Group."); - is(Koha::StockRotationStages->find($srstage->stage_id)->rota_id, $newrota->{rota_id}, "Moved correctly."); + my $newrota = $builder->build( { source => 'Stockrotationrota' } ); + ok( $srstage->move_to_group( $newrota->{rota_id} ), "Move to Group." ); + is( Koha::StockRotationStages->find( $srstage->stage_id )->rota_id, $newrota->{rota_id}, "Moved correctly." ); # Delete in ordered context - ok($srstage->delete, "Deleted OK."); + ok( $srstage->delete, "Deleted OK." ); is( Koha::StockRotationStages->find($stageprevious)->next_sibling->stage_id, $stagenext->{stage_id}, @@ -163,7 +176,7 @@ subtest 'Relationship to stockrotationitems' => sub { plan tests => 2; $schema->storage->txn_begin; - my $stage = $builder->build({ source => 'Stockrotationstage' }); + my $stage = $builder->build( { source => 'Stockrotationstage' } ); $builder->build( { @@ -193,7 +206,7 @@ subtest 'Relationship to stockrotationitems' => sub { } ); - my $srstage = Koha::StockRotationStages->find($stage->{stage_id}); + my $srstage = Koha::StockRotationStages->find( $stage->{stage_id} ); my $sritems = $srstage->stockrotationitems; is( $sritems->count, 3, @@ -208,7 +221,6 @@ subtest 'Relationship to stockrotationitems' => sub { $schema->storage->txn_rollback; }; - subtest 'Tests for investigate (singular)' => sub { plan tests => 3; @@ -229,67 +241,79 @@ subtest 'Tests for investigate (singular)' => sub { $schema->storage->txn_begin; # Libraries - my $library1 = $builder->build({ source => 'Branch' }); - my $library2 = $builder->build({ source => 'Branch' }); - my $library3 = $builder->build({ source => 'Branch' }); + my $library1 = $builder->build( { source => 'Branch' } ); + my $library2 = $builder->build( { source => 'Branch' } ); + my $library3 = $builder->build( { source => 'Branch' } ); - my $stage1lib = $builder->build({ source => 'Branch' }); - my $stage2lib = $builder->build({ source => 'Branch' }); - my $stage3lib = $builder->build({ source => 'Branch' }); - my $stage4lib = $builder->build({ source => 'Branch' }); + my $stage1lib = $builder->build( { source => 'Branch' } ); + my $stage2lib = $builder->build( { source => 'Branch' } ); + my $stage3lib = $builder->build( { source => 'Branch' } ); + my $stage4lib = $builder->build( { source => 'Branch' } ); - my $libraries = [ $library1, $library2, $library3, $stage1lib, $stage2lib, - $stage3lib, $stage4lib ]; + my $libraries = [ + $library1, $library2, $library3, $stage1lib, $stage2lib, + $stage3lib, $stage4lib + ]; # Rota - my $rota = $builder->build({ - source => 'Stockrotationrota', - value => { cyclical => 0 }, - }); + my $rota = $builder->build( + { + source => 'Stockrotationrota', + value => { cyclical => 0 }, + } + ); # Stages - my $stage1 = $builder->build({ - source => 'Stockrotationstage', - value => { - rota_id => $rota->{rota_id}, - branchcode_id => $stage1lib->{branchcode}, - duration => 10, - position => 1, - }, - }); - my $stage2 = $builder->build({ - source => 'Stockrotationstage', - value => { - rota_id => $rota->{rota_id}, - branchcode_id => $stage2lib->{branchcode}, - duration => 20, - position => 2, - }, - }); - my $stage3 = $builder->build({ - source => 'Stockrotationstage', - value => { - rota_id => $rota->{rota_id}, - branchcode_id => $stage3lib->{branchcode}, - duration => 10, - position => 3, - }, - }); - my $stage4 = $builder->build({ - source => 'Stockrotationstage', - value => { - rota_id => $rota->{rota_id}, - branchcode_id => $stage4lib->{branchcode}, - duration => 20, - position => 4, - }, - }); + my $stage1 = $builder->build( + { + source => 'Stockrotationstage', + value => { + rota_id => $rota->{rota_id}, + branchcode_id => $stage1lib->{branchcode}, + duration => 10, + position => 1, + }, + } + ); + my $stage2 = $builder->build( + { + source => 'Stockrotationstage', + value => { + rota_id => $rota->{rota_id}, + branchcode_id => $stage2lib->{branchcode}, + duration => 20, + position => 2, + }, + } + ); + my $stage3 = $builder->build( + { + source => 'Stockrotationstage', + value => { + rota_id => $rota->{rota_id}, + branchcode_id => $stage3lib->{branchcode}, + duration => 10, + position => 3, + }, + } + ); + my $stage4 = $builder->build( + { + source => 'Stockrotationstage', + value => { + rota_id => $rota->{rota_id}, + branchcode_id => $stage4lib->{branchcode}, + duration => 20, + position => 4, + }, + } + ); # Test on an empty report. - my $spec = { - $library1->{branchcode} => 1, - $library2->{branchcode} => 1, - $library3->{branchcode} => 1, + my $spec = { + $library1->{branchcode} => 1, + $library2->{branchcode} => 1, + $library3->{branchcode} => 1, $stage1lib->{branchcode} => 2, $stage2lib->{branchcode} => 1, $stage3lib->{branchcode} => 3, @@ -310,28 +334,26 @@ subtest 'Tests for investigate (singular)' => sub { } ); my $dbitem = Koha::StockRotationItems->find($item); - $dbitem->item->homebranch($code) - ->holdingbranch($code)->store; + $dbitem->item->homebranch($code)->holdingbranch($code)->store; $cnt++; } } - my $report = Koha::StockRotationStages - ->find($stage1->{stage_id})->investigate; + my $report = Koha::StockRotationStages->find( $stage1->{stage_id} )->investigate; my $results = []; foreach my $lib ( @{$libraries} ) { - my $items = $report->{branched}->{$lib->{branchcode}}->{items} || []; + my $items = $report->{branched}->{ $lib->{branchcode} }->{items} || []; push @{$results}, scalar @{$items}; } # Items assigned to stag1lib -> log, hence $results[4] = 0; - is_deeply( $results, [ 1, 1, 1, 2, 1, 3, 4 ], "Empty report test 1."); + is_deeply( $results, [ 1, 1, 1, 2, 1, 3, 4 ], "Empty report test 1." ); # Now we test by adding the next stage's items to the same report. - $spec = { - $library1->{branchcode} => 3, - $library2->{branchcode} => 2, - $library3->{branchcode} => 1, + $spec = { + $library1->{branchcode} => 3, + $library2->{branchcode} => 2, + $library3->{branchcode} => 1, $stage1lib->{branchcode} => 4, $stage2lib->{branchcode} => 2, $stage3lib->{branchcode} => 0, @@ -352,45 +374,42 @@ subtest 'Tests for investigate (singular)' => sub { } ); my $dbitem = Koha::StockRotationItems->find($item); - $dbitem->item->homebranch($code) - ->holdingbranch($code)->store; + $dbitem->item->homebranch($code)->holdingbranch($code)->store; $cnt++; } } - $report = Koha::StockRotationStages - ->find($stage2->{stage_id})->investigate($report); + $report = Koha::StockRotationStages->find( $stage2->{stage_id} )->investigate($report); $results = []; foreach my $lib ( @{$libraries} ) { - my $items = $report->{branched}->{$lib->{branchcode}}->{items} || []; + my $items = $report->{branched}->{ $lib->{branchcode} }->{items} || []; push @{$results}, scalar @{$items}; } - is_deeply( $results, [ 4, 3, 2, 6, 3, 3, 7 ], "full report test."); + is_deeply( $results, [ 4, 3, 2, 6, 3, 3, 7 ], "full report test." ); # Carry out db updates - foreach my $item (@{$report->{items}}) { + foreach my $item ( @{ $report->{items} } ) { my $reason = $item->{reason}; if ( $reason eq 'repatriation' ) { $item->{object}->repatriate; - } elsif ( grep { $reason eq $_ } - qw/in-demand advancement initiation/ ) { + } elsif ( grep { $reason eq $_ } qw/in-demand advancement initiation/ ) { $item->{object}->advance; } } - $report = Koha::StockRotationStages - ->find($stage1->{stage_id})->investigate; + $report = Koha::StockRotationStages->find( $stage1->{stage_id} )->investigate; $results = []; foreach my $lib ( @{$libraries} ) { - my $items = $report->{branched}->{$lib->{branchcode}}->{items} || []; + my $items = $report->{branched}->{ $lib->{branchcode} }->{items} || []; push @{$results}, scalar @{$items}; } + # All items have been 'initiated', which means they are either happily in # transit or happily at the library they are supposed to be. Either way # they will register as 'not-ready' in the stock rotation report. - is_deeply( $results, [ 0, 0, 0, 0, 0, 0, 0 ], "All items now in logs."); + is_deeply( $results, [ 0, 0, 0, 0, 0, 0, 0 ], "All items now in logs." ); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/SuggestionEngine_ExplodedTerms.t b/t/db_dependent/SuggestionEngine_ExplodedTerms.t index 4e310b6a9d..b9e0493ac5 100755 --- a/t/db_dependent/SuggestionEngine_ExplodedTerms.t +++ b/t/db_dependent/SuggestionEngine_ExplodedTerms.t @@ -26,13 +26,19 @@ is( ref($suggestor), 'Koha::SuggestionEngine', 'Created suggestion engine' ); my $result = $suggestor->get_suggestions( { search => 'Cookery' } ); -ok( ( grep { $_->{'search'} eq 'su-na:Cookery' } @$result ) && ( grep { $_->{'search'} eq 'su-br:Cookery' } @$result ) && ( grep { $_->{'search'} eq 'su-rl:Cookery' } @$result ), +ok( + ( grep { $_->{'search'} eq 'su-na:Cookery' } @$result ) + && ( grep { $_->{'search'} eq 'su-br:Cookery' } @$result ) + && ( grep { $_->{'search'} eq 'su-rl:Cookery' } @$result ), "Suggested correct alternatives for keyword search 'Cookery'" ); $result = $suggestor->get_suggestions( { search => 'su:Cookery' } ); -ok( ( grep { $_->{'search'} eq 'su-na:Cookery' } @$result ) && ( grep { $_->{'search'} eq 'su-br:Cookery' } @$result ) && ( grep { $_->{'search'} eq 'su-rl:Cookery' } @$result ), +ok( + ( grep { $_->{'search'} eq 'su-na:Cookery' } @$result ) + && ( grep { $_->{'search'} eq 'su-br:Cookery' } @$result ) + && ( grep { $_->{'search'} eq 'su-rl:Cookery' } @$result ), "Suggested correct alternatives for subject search 'Cookery'" ); diff --git a/t/db_dependent/Suggestions.t b/t/db_dependent/Suggestions.t index c25a97da7d..767848cb1f 100755 --- a/t/db_dependent/Suggestions.t +++ b/t/db_dependent/Suggestions.t @@ -35,15 +35,18 @@ use Koha::Patrons; use Koha::Suggestions; BEGIN { - use_ok('C4::Suggestions', qw( GetSuggestion ModSuggestion GetSuggestionInfo GetSuggestionFromBiblionumber GetSuggestionInfoFromBiblionumber GetSuggestionByStatus ConnectSuggestionAndBiblio DelSuggestion MarcRecordFromNewSuggestion GetUnprocessedSuggestions DelSuggestionsOlderThan )); + use_ok( + 'C4::Suggestions', + qw( GetSuggestion ModSuggestion GetSuggestionInfo GetSuggestionFromBiblionumber GetSuggestionInfoFromBiblionumber GetSuggestionByStatus ConnectSuggestionAndBiblio DelSuggestion MarcRecordFromNewSuggestion GetUnprocessedSuggestions DelSuggestionsOlderThan ) + ); } -my $schema = Koha::Database->new->schema; +my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; -my $dbh = C4::Context->dbh; +my $dbh = C4::Context->dbh; my $builder = t::lib::TestBuilder->new; -t::lib::Mocks::mock_preference( "EmailPurchaseSuggestions", "0"); +t::lib::Mocks::mock_preference( "EmailPurchaseSuggestions", "0" ); # Reset item types to only the default ones $dbh->do(q|DELETE FROM itemtypes;|); @@ -65,35 +68,37 @@ $dbh->do(q|DELETE FROM letter|); $dbh->do(q|DELETE FROM message_queue|); $dbh->do(q|INSERT INTO letter(module, code, content) VALUES ('suggestions', 'CHECKED', 'my content')|); $dbh->do(q|INSERT INTO letter(module, code, content) VALUES ('suggestions', 'ORDERED', 'my content')|); -$dbh->do(q|INSERT INTO letter(module, code, content) VALUES ('suggestions', 'NEW_SUGGESTION', 'Content for new suggestion')|); +$dbh->do( + q|INSERT INTO letter(module, code, content) VALUES ('suggestions', 'NEW_SUGGESTION', 'Content for new suggestion')| +); # Add CPL if missing. -if (not defined Koha::Libraries->find('CPL')) { - Koha::Library->new({ branchcode => 'CPL', branchname => 'Centerville' })->store; +if ( not defined Koha::Libraries->find('CPL') ) { + Koha::Library->new( { branchcode => 'CPL', branchname => 'Centerville' } )->store; } -my $patron_category = $builder->build({ source => 'Category' }); +my $patron_category = $builder->build( { source => 'Category' } ); my $member = { - firstname => 'my firstname', - surname => 'my surname', - categorycode => $patron_category->{categorycode}, - branchcode => 'CPL', + firstname => 'my firstname', + surname => 'my surname', + categorycode => $patron_category->{categorycode}, + branchcode => 'CPL', smsalertnumber => 12345, }; my $member2 = { - firstname => 'my firstname', - surname => 'my surname', + firstname => 'my firstname', + surname => 'my surname', categorycode => $patron_category->{categorycode}, - branchcode => 'CPL', - email => 'to@example.com', + branchcode => 'CPL', + email => 'to@example.com', }; -my $borrowernumber = Koha::Patron->new($member)->store->borrowernumber; +my $borrowernumber = Koha::Patron->new($member)->store->borrowernumber; my $borrowernumber2 = Koha::Patron->new($member2)->store->borrowernumber; -my $biblio_1 = $builder->build_object({ class => 'Koha::Biblios' }); +my $biblio_1 = $builder->build_object( { class => 'Koha::Biblios' } ); my $my_suggestion = { title => 'my title', author => 'my author', @@ -105,29 +110,33 @@ my $my_suggestion = { manageddate => '', accepteddate => dt_from_string, note => 'my note', - quantity => '', # Insert an empty string into int to catch strict SQL modes errors + quantity => '', # Insert an empty string into int to catch strict SQL modes errors }; -my $budgetperiod_id = AddBudgetPeriod({ - budget_period_startdate => '2008-01-01', - budget_period_enddate => '2008-12-31', - budget_period_description => 'MAPERI', - budget_period_active => 1, -}); +my $budgetperiod_id = AddBudgetPeriod( + { + budget_period_startdate => '2008-01-01', + budget_period_enddate => '2008-12-31', + budget_period_description => 'MAPERI', + budget_period_active => 1, + } +); -my $budget_id = AddBudget({ - budget_code => 'ABCD', - budget_amount => '123.132000', - budget_name => 'ABCD', - budget_notes => 'This is a note', - budget_period_id => $budgetperiod_id, -}); +my $budget_id = AddBudget( + { + budget_code => 'ABCD', + budget_amount => '123.132000', + budget_name => 'ABCD', + budget_notes => 'This is a note', + budget_period_id => $budgetperiod_id, + } +); my $my_suggestion_with_budget = { title => 'my title 2', author => 'my author 2', publishercode => 'my publishercode 2', suggestedby => $borrowernumber, - branchcode => '', # This should not fail be set to undef instead + branchcode => '', # This should not fail be set to undef instead biblionumber => $biblio_1->biblionumber, managedby => '', manageddate => '', @@ -158,26 +167,26 @@ my $my_suggestion_without_suggestedby = { manageddate => '', accepteddate => dt_from_string, note => 'my note', - quantity => '', # Insert an empty string into int to catch strict SQL modes errors + quantity => '', # Insert an empty string into int to catch strict SQL modes errors }; my $my_suggestion_object = Koha::Suggestion->new($my_suggestion)->store; -my $my_suggestionid = $my_suggestion_object->id; +my $my_suggestionid = $my_suggestion_object->id; isnt( $my_suggestionid, 0, 'Suggestion is correctly saved' ); my $my_suggestion_with_budget_object = Koha::Suggestion->new($my_suggestion_with_budget)->store; -my $my_suggestionid_with_budget = $my_suggestion_with_budget_object->id; +my $my_suggestionid_with_budget = $my_suggestion_with_budget_object->id; is( GetSuggestion(), undef, 'GetSuggestion without the suggestion id returns undef' ); my $suggestion = GetSuggestion($my_suggestionid); -is( $suggestion->{title}, $my_suggestion->{title}, 'Suggestion stores the title correctly' ); -is( $suggestion->{author}, $my_suggestion->{author}, 'Suggestion stores the author correctly' ); +is( $suggestion->{title}, $my_suggestion->{title}, 'Suggestion stores the title correctly' ); +is( $suggestion->{author}, $my_suggestion->{author}, 'Suggestion stores the author correctly' ); is( $suggestion->{publishercode}, $my_suggestion->{publishercode}, 'Suggestion stores the publishercode correctly' ); -is( $suggestion->{suggestedby}, $my_suggestion->{suggestedby}, 'Suggestion stores the borrower number correctly' ); -is( $suggestion->{biblionumber}, $my_suggestion->{biblionumber}, 'Suggestion stores the biblio number correctly' ); -is( $suggestion->{STATUS}, 'ASKED', 'Suggestion stores a suggestion with the status ASKED by default' ); +is( $suggestion->{suggestedby}, $my_suggestion->{suggestedby}, 'Suggestion stores the borrower number correctly' ); +is( $suggestion->{biblionumber}, $my_suggestion->{biblionumber}, 'Suggestion stores the biblio number correctly' ); +is( $suggestion->{STATUS}, 'ASKED', 'Suggestion stores a suggestion with the status ASKED by default' ); is( $suggestion->{managedby}, undef, 'Suggestion stores empty string as undef for non existent foreign key (integer)' ); is( $suggestion->{manageddate}, undef, 'Suggestion stores empty string as undef for date' ); -is( $suggestion->{budgetid}, undef, 'Suggestion should set budgetid to NULL if not given' ); +is( $suggestion->{budgetid}, undef, 'Suggestion should set budgetid to NULL if not given' ); is( ModSuggestion(), undef, 'ModSuggestion without the suggestion returns undef' ); my $mod_suggestion1 = { @@ -194,17 +203,21 @@ $mod_suggestion1->{suggestionid} = $my_suggestionid; $status = ModSuggestion($mod_suggestion1); is( $status, 1, 'ModSuggestion modifies one entry' ); $suggestion = GetSuggestion($my_suggestionid); -is( $suggestion->{title}, $mod_suggestion1->{title}, 'ModSuggestion modifies the title correctly' ); +is( $suggestion->{title}, $mod_suggestion1->{title}, 'ModSuggestion modifies the title correctly' ); is( $suggestion->{author}, $mod_suggestion1->{author}, 'ModSuggestion modifies the author correctly' ); -is( $suggestion->{publishercode}, $mod_suggestion1->{publishercode}, 'ModSuggestion modifies the publishercode correctly' ); -is( $suggestion->{managedby}, undef, 'ModSuggestion stores empty string as undef for non existent foreign key (integer)' ); +is( + $suggestion->{publishercode}, $mod_suggestion1->{publishercode}, + 'ModSuggestion modifies the publishercode correctly' +); +is( + $suggestion->{managedby}, undef, + 'ModSuggestion stores empty string as undef for non existent foreign key (integer)' +); is( $suggestion->{manageddate}, undef, 'ModSuggestion stores empty string as undef for date' ); isnt( $suggestion->{accepteddate}, undef, 'ModSuggestion does not update a non given date value' ); is( $suggestion->{note}, 'my note', 'ModSuggestion should not erase data if not given' ); -my $messages = C4::Letters::GetQueuedMessages({ - borrowernumber => $borrowernumber -}); +my $messages = C4::Letters::GetQueuedMessages( { borrowernumber => $borrowernumber } ); is( @$messages, 0, 'ModSuggestions does not send an email if the status is not updated' ); my $authorised_value = Koha::AuthorisedValue->new( @@ -218,9 +231,9 @@ my $mod_suggestion2 = { suggestionid => $my_suggestionid, }; warning_is { $status = ModSuggestion($mod_suggestion2) } - "No suggestions STALLED letter transported by email", - "ModSuggestion status warning is correct"; -is( $status, 1, "ModSuggestion Status OK"); +"No suggestions STALLED letter transported by email", + "ModSuggestion status warning is correct"; +is( $status, 1, "ModSuggestion Status OK" ); my $mod_suggestion3 = { STATUS => 'CHECKED', @@ -235,11 +248,12 @@ $status = ModSuggestion($mod_suggestion3); is( $status, 1, 'ModSuggestion modifies one entry' ); $suggestion = GetSuggestion($my_suggestionid); is( $suggestion->{STATUS}, $mod_suggestion3->{STATUS}, 'ModSuggestion modifies the status correctly' ); -$messages = C4::Letters::GetQueuedMessages({ - borrowernumber => $borrowernumber -}); +$messages = C4::Letters::GetQueuedMessages( { borrowernumber => $borrowernumber } ); is( @$messages, 1, 'ModSuggestion sends an email if the status is updated' ); -is ($messages->[0]->{message_transport_type}, 'email', 'When FallbackToSMSIfNoEmail syspref is disabled the suggestion message_transport_type is always email'); +is( + $messages->[0]->{message_transport_type}, 'email', + 'When FallbackToSMSIfNoEmail syspref is disabled the suggestion message_transport_type is always email' +); #Check the message_transport_type when the 'FallbackToSMSIfNoEmail' syspref is enabled and the borrower has a smsalertnumber and no email t::lib::Mocks::mock_preference( 'FallbackToSMSIfNoEmail', 1 ); @@ -248,14 +262,15 @@ my $mod_suggestion3a = { suggestionid => $my_suggestionid, }; ModSuggestion($mod_suggestion3a); -$messages = C4::Letters::GetQueuedMessages({ - borrowernumber => $borrowernumber -}); -is ($messages->[1]->{message_transport_type}, 'sms', 'When FallbackToSMSIfNoEmail syspref is enabled the suggestion message_transport_type is sms if the borrower has no email'); +$messages = C4::Letters::GetQueuedMessages( { borrowernumber => $borrowernumber } ); +is( + $messages->[1]->{message_transport_type}, 'sms', + 'When FallbackToSMSIfNoEmail syspref is enabled the suggestion message_transport_type is sms if the borrower has no email' +); #Make a new suggestion for a borrower with defined email and no smsalertnumber my $my_suggestion_2_object = Koha::Suggestion->new($my_suggestion_with_budget2)->store(); -my $my_suggestion_2_id = $my_suggestion_2_object->id; +my $my_suggestion_2_id = $my_suggestion_2_object->id; #Check the message_transport_type when the 'FallbackToSMSIfNoEmail' syspref is enabled and the borrower has a defined email and no smsalertnumber t::lib::Mocks::mock_preference( 'FallbackToSMSIfNoEmail', 1 ); @@ -264,10 +279,11 @@ my $mod_suggestion4 = { suggestionid => $my_suggestion_2_id, }; ModSuggestion($mod_suggestion4); -$messages = C4::Letters::GetQueuedMessages({ - borrowernumber => $borrowernumber2 -}); -is ($messages->[0]->{message_transport_type}, 'email', 'When FallbackToSMSIfNoEmail syspref is enabled the suggestion message_transport_type is email if the borrower has an email'); +$messages = C4::Letters::GetQueuedMessages( { borrowernumber => $borrowernumber2 } ); +is( + $messages->[0]->{message_transport_type}, 'email', + 'When FallbackToSMSIfNoEmail syspref is enabled the suggestion message_transport_type is email if the borrower has an email' +); # changing STATUS from ORDERED to CHECKED should generate a message my $mod_suggestion5 = { @@ -291,127 +307,211 @@ is( @$messages, 3, 'ModSuggestions does send a message if the status has been ch $mod_suggestion4->{manageddate} = 'invalid date!'; ModSuggestion($mod_suggestion4); - $messages = C4::Letters::GetQueuedMessages({ - borrowernumber => $borrowernumber2 - }); + $messages = C4::Letters::GetQueuedMessages( { borrowernumber => $borrowernumber2 } ); close STDERR; - is (scalar(@$messages), 1, 'No new letter should have been generated if the update raised an error'); + is( scalar(@$messages), 1, 'No new letter should have been generated if the update raised an error' ); } is( GetSuggestionInfo(), undef, 'GetSuggestionInfo without the suggestion id returns undef' ); $suggestion = GetSuggestionInfo($my_suggestionid); -is( $suggestion->{suggestionid}, $my_suggestionid, 'GetSuggestionInfo returns the suggestion id correctly' ); -is( $suggestion->{title}, $mod_suggestion1->{title}, 'GetSuggestionInfo returns the title correctly' ); -is( $suggestion->{author}, $mod_suggestion1->{author}, 'GetSuggestionInfo returns the author correctly' ); -is( $suggestion->{publishercode}, $mod_suggestion1->{publishercode}, 'GetSuggestionInfo returns the publisher code correctly' ); -is( $suggestion->{suggestedby}, $my_suggestion->{suggestedby}, 'GetSuggestionInfo returns the borrower number correctly' ); -is( $suggestion->{biblionumber}, $my_suggestion->{biblionumber}, 'GetSuggestionInfo returns the biblio number correctly' ); -is( $suggestion->{STATUS}, $mod_suggestion3->{STATUS}, 'GetSuggestionInfo returns the status correctly' ); -is( $suggestion->{surnamesuggestedby}, $member->{surname}, 'GetSuggestionInfo returns the surname correctly' ); +is( $suggestion->{suggestionid}, $my_suggestionid, 'GetSuggestionInfo returns the suggestion id correctly' ); +is( $suggestion->{title}, $mod_suggestion1->{title}, 'GetSuggestionInfo returns the title correctly' ); +is( $suggestion->{author}, $mod_suggestion1->{author}, 'GetSuggestionInfo returns the author correctly' ); +is( + $suggestion->{publishercode}, $mod_suggestion1->{publishercode}, + 'GetSuggestionInfo returns the publisher code correctly' +); +is( + $suggestion->{suggestedby}, $my_suggestion->{suggestedby}, + 'GetSuggestionInfo returns the borrower number correctly' +); +is( + $suggestion->{biblionumber}, $my_suggestion->{biblionumber}, + 'GetSuggestionInfo returns the biblio number correctly' +); +is( $suggestion->{STATUS}, $mod_suggestion3->{STATUS}, 'GetSuggestionInfo returns the status correctly' ); +is( $suggestion->{surnamesuggestedby}, $member->{surname}, 'GetSuggestionInfo returns the surname correctly' ); is( $suggestion->{firstnamesuggestedby}, $member->{firstname}, 'GetSuggestionInfo returns the firstname correctly' ); -is( $suggestion->{borrnumsuggestedby}, $my_suggestion->{suggestedby}, 'GetSuggestionInfo returns the borrower number correctly' ); - +is( + $suggestion->{borrnumsuggestedby}, $my_suggestion->{suggestedby}, + 'GetSuggestionInfo returns the borrower number correctly' +); is( GetSuggestionFromBiblionumber(), undef, 'GetSuggestionFromBiblionumber without the biblio number returns undef' ); -is( GetSuggestionFromBiblionumber(2), undef, 'GetSuggestionFromBiblionumber with an invalid biblio number returns undef' ); -is( GetSuggestionFromBiblionumber($biblio_1->biblionumber), $my_suggestionid, 'GetSuggestionFromBiblionumber functions correctly' ); +is( + GetSuggestionFromBiblionumber(2), undef, + 'GetSuggestionFromBiblionumber with an invalid biblio number returns undef' +); +is( + GetSuggestionFromBiblionumber( $biblio_1->biblionumber ), $my_suggestionid, + 'GetSuggestionFromBiblionumber functions correctly' +); - -is( GetSuggestionInfoFromBiblionumber(), undef, 'GetSuggestionInfoFromBiblionumber without the biblio number returns undef' ); -is( GetSuggestionInfoFromBiblionumber(2), undef, 'GetSuggestionInfoFromBiblionumber with an invalid biblio number returns undef' ); -$suggestion = GetSuggestionInfoFromBiblionumber($biblio_1->biblionumber); -is( $suggestion->{suggestionid}, $my_suggestionid, 'GetSuggestionInfoFromBiblionumber returns the suggestion id correctly' ); +is( + GetSuggestionInfoFromBiblionumber(), undef, + 'GetSuggestionInfoFromBiblionumber without the biblio number returns undef' +); +is( + GetSuggestionInfoFromBiblionumber(2), undef, + 'GetSuggestionInfoFromBiblionumber with an invalid biblio number returns undef' +); +$suggestion = GetSuggestionInfoFromBiblionumber( $biblio_1->biblionumber ); +is( + $suggestion->{suggestionid}, $my_suggestionid, + 'GetSuggestionInfoFromBiblionumber returns the suggestion id correctly' +); is( $suggestion->{title}, $mod_suggestion1->{title}, 'GetSuggestionInfoFromBiblionumber returns the title correctly' ); -is( $suggestion->{author}, $mod_suggestion1->{author}, 'GetSuggestionInfoFromBiblionumber returns the author correctly' ); -is( $suggestion->{publishercode}, $mod_suggestion1->{publishercode}, 'GetSuggestionInfoFromBiblionumber returns the publisher code correctly' ); -is( $suggestion->{suggestedby}, $my_suggestion->{suggestedby}, 'GetSuggestionInfoFromBiblionumber returns the borrower number correctly' ); -is( $suggestion->{biblionumber}, $my_suggestion->{biblionumber}, 'GetSuggestionInfoFromBiblionumber returns the biblio number correctly' ); -is( $suggestion->{STATUS}, $mod_suggestion3->{STATUS}, 'GetSuggestionInfoFromBiblionumber returns the status correctly' ); -is( $suggestion->{surnamesuggestedby}, $member->{surname}, 'GetSuggestionInfoFromBiblionumber returns the surname correctly' ); -is( $suggestion->{firstnamesuggestedby}, $member->{firstname}, 'GetSuggestionInfoFromBiblionumber returns the firstname correctly' ); -is( $suggestion->{borrnumsuggestedby}, $my_suggestion->{suggestedby}, 'GetSuggestionInfoFromBiblionumeber returns the borrower number correctly' ); - +is( + $suggestion->{author}, $mod_suggestion1->{author}, + 'GetSuggestionInfoFromBiblionumber returns the author correctly' +); +is( + $suggestion->{publishercode}, $mod_suggestion1->{publishercode}, + 'GetSuggestionInfoFromBiblionumber returns the publisher code correctly' +); +is( + $suggestion->{suggestedby}, $my_suggestion->{suggestedby}, + 'GetSuggestionInfoFromBiblionumber returns the borrower number correctly' +); +is( + $suggestion->{biblionumber}, $my_suggestion->{biblionumber}, + 'GetSuggestionInfoFromBiblionumber returns the biblio number correctly' +); +is( + $suggestion->{STATUS}, $mod_suggestion3->{STATUS}, + 'GetSuggestionInfoFromBiblionumber returns the status correctly' +); +is( + $suggestion->{surnamesuggestedby}, $member->{surname}, + 'GetSuggestionInfoFromBiblionumber returns the surname correctly' +); +is( + $suggestion->{firstnamesuggestedby}, $member->{firstname}, + 'GetSuggestionInfoFromBiblionumber returns the firstname correctly' +); +is( + $suggestion->{borrnumsuggestedby}, $my_suggestion->{suggestedby}, + 'GetSuggestionInfoFromBiblionumeber returns the borrower number correctly' +); my $suggestions = GetSuggestionByStatus(); is( @$suggestions, 0, 'GetSuggestionByStatus without the status returns an empty array' ); $suggestions = GetSuggestionByStatus('CHECKED'); -is( @$suggestions, 2, 'GetSuggestionByStatus returns the correct number of suggestions' ); +is( @$suggestions, 2, 'GetSuggestionByStatus returns the correct number of suggestions' ); is( $suggestions->[0]->{suggestionid}, $my_suggestionid, 'GetSuggestionByStatus returns the suggestion id correctly' ); -is( $suggestions->[0]->{title}, $mod_suggestion1->{title}, 'GetSuggestionByStatus returns the title correctly' ); +is( $suggestions->[0]->{title}, $mod_suggestion1->{title}, 'GetSuggestionByStatus returns the title correctly' ); is( $suggestions->[0]->{author}, $mod_suggestion1->{author}, 'GetSuggestionByStatus returns the author correctly' ); -is( $suggestions->[0]->{publishercode}, $mod_suggestion1->{publishercode}, 'GetSuggestionByStatus returns the publisher code correctly' ); -is( $suggestions->[0]->{suggestedby}, $my_suggestion->{suggestedby}, 'GetSuggestionByStatus returns the borrower number correctly' ); -is( $suggestions->[0]->{biblionumber}, $my_suggestion->{biblionumber}, 'GetSuggestionByStatus returns the biblio number correctly' ); +is( + $suggestions->[0]->{publishercode}, $mod_suggestion1->{publishercode}, + 'GetSuggestionByStatus returns the publisher code correctly' +); +is( + $suggestions->[0]->{suggestedby}, $my_suggestion->{suggestedby}, + 'GetSuggestionByStatus returns the borrower number correctly' +); +is( + $suggestions->[0]->{biblionumber}, $my_suggestion->{biblionumber}, + 'GetSuggestionByStatus returns the biblio number correctly' +); is( $suggestions->[0]->{STATUS}, $mod_suggestion3->{STATUS}, 'GetSuggestionByStatus returns the status correctly' ); -is( $suggestions->[0]->{surnamesuggestedby}, $member->{surname}, 'GetSuggestionByStatus returns the surname correctly' ); -is( $suggestions->[0]->{firstnamesuggestedby}, $member->{firstname}, 'GetSuggestionByStatus returns the firstname correctly' ); -is( $suggestions->[0]->{branchcodesuggestedby}, $member->{branchcode}, 'GetSuggestionByStatus returns the branch code correctly' ); -is( $suggestions->[0]->{borrnumsuggestedby}, $my_suggestion->{suggestedby}, 'GetSuggestionByStatus returns the borrower number correctly' ); -is( $suggestions->[0]->{categorycodesuggestedby}, $member->{categorycode}, 'GetSuggestionByStatus returns the category code correctly' ); - +is( + $suggestions->[0]->{surnamesuggestedby}, $member->{surname}, + 'GetSuggestionByStatus returns the surname correctly' +); +is( + $suggestions->[0]->{firstnamesuggestedby}, $member->{firstname}, + 'GetSuggestionByStatus returns the firstname correctly' +); +is( + $suggestions->[0]->{branchcodesuggestedby}, $member->{branchcode}, + 'GetSuggestionByStatus returns the branch code correctly' +); +is( + $suggestions->[0]->{borrnumsuggestedby}, $my_suggestion->{suggestedby}, + 'GetSuggestionByStatus returns the borrower number correctly' +); +is( + $suggestions->[0]->{categorycodesuggestedby}, $member->{categorycode}, + 'GetSuggestionByStatus returns the category code correctly' +); is( ConnectSuggestionAndBiblio(), '0E0', 'ConnectSuggestionAndBiblio without arguments returns 0E0' ); -my $biblio_2 = $builder->build_object({ class => 'Koha::Biblios' }); -my $connect_suggestion_and_biblio = ConnectSuggestionAndBiblio($my_suggestionid, $biblio_2->biblionumber); +my $biblio_2 = $builder->build_object( { class => 'Koha::Biblios' } ); +my $connect_suggestion_and_biblio = ConnectSuggestionAndBiblio( $my_suggestionid, $biblio_2->biblionumber ); is( $connect_suggestion_and_biblio, '1', 'ConnectSuggestionAndBiblio returns 1' ); $suggestion = GetSuggestion($my_suggestionid); -is( $suggestion->{biblionumber}, $biblio_2->biblionumber, 'ConnectSuggestionAndBiblio updates the biblio number correctly' ); +is( + $suggestion->{biblionumber}, $biblio_2->biblionumber, + 'ConnectSuggestionAndBiblio updates the biblio number correctly' +); my $del_suggestion = { - title => 'my deleted title', - STATUS => 'CHECKED', + title => 'my deleted title', + STATUS => 'CHECKED', suggestedby => $borrowernumber, }; my $del_suggestion_object = Koha::Suggestion->new($del_suggestion)->store(); -my $del_suggestionid = $del_suggestion_object->id; +my $del_suggestionid = $del_suggestion_object->id; -is( DelSuggestion(), '0E0', 'DelSuggestion without arguments returns 0E0' ); -is( DelSuggestion($borrowernumber), '', 'DelSuggestion without the suggestion id returns an empty string' ); -is( DelSuggestion(undef, $my_suggestionid), '', 'DelSuggestion with an invalid borrower number returns an empty string' ); -$suggestion = DelSuggestion($borrowernumber, $my_suggestionid); +is( DelSuggestion(), '0E0', 'DelSuggestion without arguments returns 0E0' ); +is( DelSuggestion($borrowernumber), '', 'DelSuggestion without the suggestion id returns an empty string' ); +is( + DelSuggestion( undef, $my_suggestionid ), '', + 'DelSuggestion with an invalid borrower number returns an empty string' +); +$suggestion = DelSuggestion( $borrowernumber, $my_suggestionid ); is( $suggestion, 1, 'DelSuggestion deletes one suggestion' ); $suggestions = GetSuggestionByStatus('CHECKED'); -is( @$suggestions, 2, 'DelSuggestion deletes one suggestion' ); +is( @$suggestions, 2, 'DelSuggestion deletes one suggestion' ); is( $suggestions->[1]->{title}, $del_suggestion->{title}, 'DelSuggestion deletes the correct suggestion' ); # Test budgetid fk -$my_suggestion->{budgetid} = ''; # If budgetid == '', NULL should be set in DB +$my_suggestion->{budgetid} = ''; # If budgetid == '', NULL should be set in DB my $my_suggestionid_test_budget_object = Koha::Suggestion->new($my_suggestion)->store; -my $my_suggestionid_test_budgetid = $my_suggestionid_test_budget_object->id; +my $my_suggestionid_test_budgetid = $my_suggestionid_test_budget_object->id; $suggestion = GetSuggestion($my_suggestionid_test_budgetid); is( $suggestion->{budgetid}, undef, 'Suggestion Should set budgetid to NULL if equals an empty string' ); -$my_suggestion->{budgetid} = ''; # If budgetid == '', NULL should be set in DB -ModSuggestion( $my_suggestion ); +$my_suggestion->{budgetid} = ''; # If budgetid == '', NULL should be set in DB +ModSuggestion($my_suggestion); $suggestion = GetSuggestion($my_suggestionid_test_budgetid); is( $suggestion->{budgetid}, undef, 'Suggestion Should set budgetid to NULL if equals an empty string' ); my $suggestion2 = { - title => "Cuisine d'automne", - author => "Catherine", + title => "Cuisine d'automne", + author => "Catherine", itemtype => "LIV" }; my $record = MarcRecordFromNewSuggestion($suggestion2); -is("MARC::Record", ref($record), "MarcRecordFromNewSuggestion should return a MARC::Record object"); +is( "MARC::Record", ref($record), "MarcRecordFromNewSuggestion should return a MARC::Record object" ); -my ($title_tag, $title_subfield) = C4::Biblio::GetMarcFromKohaField('biblio.title'); +my ( $title_tag, $title_subfield ) = C4::Biblio::GetMarcFromKohaField('biblio.title'); -is($record->field( $title_tag )->subfield( $title_subfield ), "Cuisine d'automne", "Record from suggestion title should be 'Cuisine d'automne'"); +is( + $record->field($title_tag)->subfield($title_subfield), "Cuisine d'automne", + "Record from suggestion title should be 'Cuisine d'automne'" +); -my ($author_tag, $author_subfield) = C4::Biblio::GetMarcFromKohaField('biblio.author'); +my ( $author_tag, $author_subfield ) = C4::Biblio::GetMarcFromKohaField('biblio.author'); -is($record->field( $author_tag )->subfield( $author_subfield ), "Catherine", "Record from suggestion author should be 'Catherine'"); +is( + $record->field($author_tag)->subfield($author_subfield), "Catherine", + "Record from suggestion author should be 'Catherine'" +); subtest 'GetUnprocessedSuggestions' => sub { plan tests => 11; $dbh->do(q|DELETE FROM suggestions|); my $my_suggestionid = Koha::Suggestion->new($my_suggestion)->store->id; my $unprocessed_suggestions = C4::Suggestions::GetUnprocessedSuggestions; - is( scalar(@$unprocessed_suggestions), 0, 'GetUnprocessedSuggestions should return 0 if a suggestion has been processed but not linked to a fund' ); + is( + scalar(@$unprocessed_suggestions), 0, + 'GetUnprocessedSuggestions should return 0 if a suggestion has been processed but not linked to a fund' + ); my $status = ModSuggestion($mod_suggestion1); my $suggestion = GetSuggestion($my_suggestionid); is( $suggestion->{budgetid}, undef, 'ModSuggestion should set budgetid to NULL if not given' ); @@ -420,25 +520,47 @@ subtest 'GetUnprocessedSuggestions' => sub { is( $suggestion->{budgetid}, $budget_id, 'ModSuggestion should modify budgetid if given' ); $unprocessed_suggestions = C4::Suggestions::GetUnprocessedSuggestions; - is( scalar(@$unprocessed_suggestions), 1, 'GetUnprocessedSuggestions should return the suggestion if the suggestion is linked to a fund and has not been processed yet' ); + is( + scalar(@$unprocessed_suggestions), 1, + 'GetUnprocessedSuggestions should return the suggestion if the suggestion is linked to a fund and has not been processed yet' + ); warning_is { ModSuggestion( { suggestionid => $my_suggestionid, STATUS => 'REJECTED' } ) } - 'No suggestions REJECTED letter transported by email', - 'Warning raised if no REJECTED letter by email'; + 'No suggestions REJECTED letter transported by email', + 'Warning raised if no REJECTED letter by email'; $unprocessed_suggestions = C4::Suggestions::GetUnprocessedSuggestions; - is( scalar(@$unprocessed_suggestions), 0, 'GetUnprocessedSuggestions should return the suggestion if the suggestion is linked to a fund and has not been processed yet' ); + is( + scalar(@$unprocessed_suggestions), 0, + 'GetUnprocessedSuggestions should return the suggestion if the suggestion is linked to a fund and has not been processed yet' + ); - warning_is { ModSuggestion( { suggestionid => $my_suggestionid, STATUS => 'ASKED', suggesteddate => dt_from_string->add_duration( DateTime::Duration->new( days => -4 ) ) } ); } - 'No suggestions ASKED letter transported by email', - 'Warning raised if no ASKED letter by email'; + warning_is { + ModSuggestion( + { + suggestionid => $my_suggestionid, STATUS => 'ASKED', + suggesteddate => dt_from_string->add_duration( DateTime::Duration->new( days => -4 ) ) + } + ); + } + 'No suggestions ASKED letter transported by email', + 'Warning raised if no ASKED letter by email'; $unprocessed_suggestions = C4::Suggestions::GetUnprocessedSuggestions; is( scalar(@$unprocessed_suggestions), 0, 'GetUnprocessedSuggestions should use 0 as default value for days' ); $unprocessed_suggestions = C4::Suggestions::GetUnprocessedSuggestions(4); - is( scalar(@$unprocessed_suggestions), 1, 'GetUnprocessedSuggestions should return the suggestion suggested 4 days ago' ); + is( + scalar(@$unprocessed_suggestions), 1, + 'GetUnprocessedSuggestions should return the suggestion suggested 4 days ago' + ); $unprocessed_suggestions = C4::Suggestions::GetUnprocessedSuggestions(3); - is( scalar(@$unprocessed_suggestions), 0, 'GetUnprocessedSuggestions should not return the suggestion, it has not been suggested 3 days ago' ); + is( + scalar(@$unprocessed_suggestions), 0, + 'GetUnprocessedSuggestions should not return the suggestion, it has not been suggested 3 days ago' + ); $unprocessed_suggestions = C4::Suggestions::GetUnprocessedSuggestions(5); - is( scalar(@$unprocessed_suggestions), 0, 'GetUnprocessedSuggestions should not return the suggestion, it has not been suggested 5 days ago' ); + is( + scalar(@$unprocessed_suggestions), 0, + 'GetUnprocessedSuggestions should not return the suggestion, it has not been suggested 5 days ago' + ); }; subtest 'DelSuggestionsOlderThan' => sub { @@ -447,19 +569,25 @@ subtest 'DelSuggestionsOlderThan' => sub { Koha::Suggestions->delete; # Add four suggestions; note that STATUS needs uppercase (FIXME) - my $d1 = output_pref({ dt => dt_from_string->add(days => -2), dateformat => 'sql' }); - my $d2 = output_pref({ dt => dt_from_string->add(days => -4), dateformat => 'sql' }); - my $sugg01 = $builder->build({ source => 'Suggestion', value => { manageddate => $d1, date => $d2, STATUS => 'ASKED' }}); - my $sugg02 = $builder->build({ source => 'Suggestion', value => { manageddate => $d1, date => $d2, STATUS => 'CHECKED' }}); - my $sugg03 = $builder->build({ source => 'Suggestion', value => { manageddate => $d2, date => $d2, STATUS => 'ASKED' }}); - my $sugg04 = $builder->build({ source => 'Suggestion', value => { manageddate => $d2, date => $d2, STATUS => 'ACCEPTED' }}); + my $d1 = output_pref( { dt => dt_from_string->add( days => -2 ), dateformat => 'sql' } ); + my $d2 = output_pref( { dt => dt_from_string->add( days => -4 ), dateformat => 'sql' } ); + my $sugg01 = + $builder->build( { source => 'Suggestion', value => { manageddate => $d1, date => $d2, STATUS => 'ASKED' } } ); + my $sugg02 = $builder->build( + { source => 'Suggestion', value => { manageddate => $d1, date => $d2, STATUS => 'CHECKED' } } ); + my $sugg03 = + $builder->build( { source => 'Suggestion', value => { manageddate => $d2, date => $d2, STATUS => 'ASKED' } } ); + my $sugg04 = $builder->build( + { source => 'Suggestion', value => { manageddate => $d2, date => $d2, STATUS => 'ACCEPTED' } } ); # Test no parameter: should do nothing C4::Suggestions::DelSuggestionsOlderThan(); is( Koha::Suggestions->count, 4, 'No suggestions deleted' ); + # Test zero: should do nothing too C4::Suggestions::DelSuggestionsOlderThan(0); is( Koha::Suggestions->count, 4, 'No suggestions deleted again' ); + # Test negative value C4::Suggestions::DelSuggestionsOlderThan(-1); is( Koha::Suggestions->count, 4, 'No suggestions deleted for -1' ); @@ -478,23 +606,23 @@ subtest 'EmailPurchaseSuggestions' => sub { $dbh->do(q|DELETE FROM message_queue|); - t::lib::Mocks::mock_preference( "KohaAdminEmailAddress", - 'noreply@hosting.com' ); + t::lib::Mocks::mock_preference( + "KohaAdminEmailAddress", + 'noreply@hosting.com' + ); # EmailPurchaseSuggestions set to disabled t::lib::Mocks::mock_preference( "EmailPurchaseSuggestions", "0" ); Koha::Suggestion->new($my_suggestion)->store; - my $newsuggestions_messages = C4::Letters::GetQueuedMessages( - { - borrowernumber => $borrowernumber - } + my $newsuggestions_messages = C4::Letters::GetQueuedMessages( { borrowernumber => $borrowernumber } ); + is( + @$newsuggestions_messages, 0, + 'New suggestion does not send an email when EmailPurchaseSuggestions disabled' ); - is( @$newsuggestions_messages, 0, - 'New suggestion does not send an email when EmailPurchaseSuggestions disabled' ); # EmailPurchaseSuggestions set to BranchEmailAddress - t::lib::Mocks::mock_preference( "EmailPurchaseSuggestions", "BranchEmailAddress" ); - t::lib::Mocks::mock_preference( "ReplytoDefault", "" ); + t::lib::Mocks::mock_preference( "EmailPurchaseSuggestions", "BranchEmailAddress" ); + t::lib::Mocks::mock_preference( "ReplytoDefault", "" ); t::lib::Mocks::mock_preference( "EmailAddressForSuggestions", "" ); Koha::Libraries->find('CPL')->update( { branchemail => '', branchreplyto => '' } ); Koha::Suggestion->new($my_suggestion)->store; @@ -508,36 +636,38 @@ subtest 'EmailPurchaseSuggestions' => sub { Koha::Libraries->find('CPL')->update( { branchreplyto => 'branchemail@b.c' } ); Koha::Suggestion->new($my_suggestion)->store; - $newsuggestions_messages = C4::Letters::GetQueuedMessages( - { - borrowernumber => $borrowernumber - } - ); + $newsuggestions_messages = C4::Letters::GetQueuedMessages( { borrowernumber => $borrowernumber } ); isnt( @$newsuggestions_messages, 0, 'New suggestions sends an email wne EmailPurchaseSuggestions enabled' ); my $message1 = - C4::Letters::GetMessage( $newsuggestions_messages->[0]->{message_id} ); - is( $message1->{to_address}, 'noreply@hosting.com', -'BranchEmailAddress falls back to KohaAdminEmailAddress if branchreplyto, branchemail and ReplytoDefault are not set' + C4::Letters::GetMessage( $newsuggestions_messages->[0]->{message_id} ); + is( + $message1->{to_address}, 'noreply@hosting.com', + 'BranchEmailAddress falls back to KohaAdminEmailAddress if branchreplyto, branchemail and ReplytoDefault are not set' ); my $message2 = - C4::Letters::GetMessage( $newsuggestions_messages->[1]->{message_id} ); - is( $message2->{to_address}, 'library@b.c', -'BranchEmailAddress falls back to ReplytoDefault if neither branchreplyto or branchemail are set' + C4::Letters::GetMessage( $newsuggestions_messages->[1]->{message_id} ); + is( + $message2->{to_address}, 'library@b.c', + 'BranchEmailAddress falls back to ReplytoDefault if neither branchreplyto or branchemail are set' ); my $message3 = - C4::Letters::GetMessage( $newsuggestions_messages->[2]->{message_id} ); - is( $message3->{to_address}, 'branchemail@hosting.com', -'BranchEmailAddress uses branchemail if branch_replto is not set' + C4::Letters::GetMessage( $newsuggestions_messages->[2]->{message_id} ); + is( + $message3->{to_address}, 'branchemail@hosting.com', + 'BranchEmailAddress uses branchemail if branch_replto is not set' ); my $message4 = - C4::Letters::GetMessage( $newsuggestions_messages->[3]->{message_id} ); - is( $message4->{to_address}, 'branchemail@b.c', -'BranchEmailAddress uses branchreplyto in preference to branchemail when set' + C4::Letters::GetMessage( $newsuggestions_messages->[3]->{message_id} ); + is( + $message4->{to_address}, 'branchemail@b.c', + 'BranchEmailAddress uses branchreplyto in preference to branchemail when set' ); # EmailPurchaseSuggestions set to KohaAdminEmailAddress - t::lib::Mocks::mock_preference( "EmailPurchaseSuggestions", - "KohaAdminEmailAddress" ); + t::lib::Mocks::mock_preference( + "EmailPurchaseSuggestions", + "KohaAdminEmailAddress" + ); t::lib::Mocks::mock_preference( "ReplytoDefault", undef ); Koha::Suggestion->new($my_suggestion)->store; @@ -545,23 +675,25 @@ subtest 'EmailPurchaseSuggestions' => sub { t::lib::Mocks::mock_preference( "ReplytoDefault", 'library@b.c' ); Koha::Suggestion->new($my_suggestion)->store; - $newsuggestions_messages = C4::Letters::GetQueuedMessages( - { - borrowernumber => $borrowernumber - } - ); + $newsuggestions_messages = C4::Letters::GetQueuedMessages( { borrowernumber => $borrowernumber } ); my $message5 = - C4::Letters::GetMessage( $newsuggestions_messages->[4]->{message_id} ); - is( $message5->{to_address}, - 'noreply@hosting.com', 'KohaAdminEmailAddress uses KohaAdminEmailAddress when ReplytoDefault is not set' ); + C4::Letters::GetMessage( $newsuggestions_messages->[4]->{message_id} ); + is( + $message5->{to_address}, + 'noreply@hosting.com', 'KohaAdminEmailAddress uses KohaAdminEmailAddress when ReplytoDefault is not set' + ); my $message6 = - C4::Letters::GetMessage( $newsuggestions_messages->[5]->{message_id} ); - is( $message6->{to_address}, - 'library@b.c', 'KohaAdminEmailAddress uses ReplytoDefualt when ReplytoDefault is set' ); + C4::Letters::GetMessage( $newsuggestions_messages->[5]->{message_id} ); + is( + $message6->{to_address}, + 'library@b.c', 'KohaAdminEmailAddress uses ReplytoDefualt when ReplytoDefault is set' + ); # EmailPurchaseSuggestions set to EmailAddressForSuggestions - t::lib::Mocks::mock_preference( "EmailPurchaseSuggestions", - "EmailAddressForSuggestions" ); + t::lib::Mocks::mock_preference( + "EmailPurchaseSuggestions", + "EmailAddressForSuggestions" + ); t::lib::Mocks::mock_preference( "ReplytoDefault", undef ); Koha::Suggestion->new($my_suggestion)->store; @@ -569,29 +701,34 @@ subtest 'EmailPurchaseSuggestions' => sub { t::lib::Mocks::mock_preference( "ReplytoDefault", 'library@b.c' ); Koha::Suggestion->new($my_suggestion)->store; - t::lib::Mocks::mock_preference( "EmailAddressForSuggestions", - 'suggestions@b.c' ); + t::lib::Mocks::mock_preference( + "EmailAddressForSuggestions", + 'suggestions@b.c' + ); Koha::Suggestion->new($my_suggestion)->store; - $newsuggestions_messages = C4::Letters::GetQueuedMessages( - { - borrowernumber => $borrowernumber - } - ); + $newsuggestions_messages = C4::Letters::GetQueuedMessages( { borrowernumber => $borrowernumber } ); my $message7 = - C4::Letters::GetMessage( $newsuggestions_messages->[6]->{message_id} ); - is( $message7->{to_address}, - 'noreply@hosting.com', 'EmailAddressForSuggestions uses KohaAdminEmailAddress when neither EmailAddressForSuggestions or ReplytoDefault are set' ); + C4::Letters::GetMessage( $newsuggestions_messages->[6]->{message_id} ); + is( + $message7->{to_address}, + 'noreply@hosting.com', + 'EmailAddressForSuggestions uses KohaAdminEmailAddress when neither EmailAddressForSuggestions or ReplytoDefault are set' + ); my $message8 = - C4::Letters::GetMessage( $newsuggestions_messages->[7]->{message_id} ); - is( $message8->{to_address}, - 'library@b.c', 'EmailAddressForSuggestions uses ReplytoDefault when EmailAddressForSuggestions is not set' ); + C4::Letters::GetMessage( $newsuggestions_messages->[7]->{message_id} ); + is( + $message8->{to_address}, + 'library@b.c', 'EmailAddressForSuggestions uses ReplytoDefault when EmailAddressForSuggestions is not set' + ); my $message9 = - C4::Letters::GetMessage( $newsuggestions_messages->[8]->{message_id} ); - is( $message9->{to_address}, - 'suggestions@b.c', 'EmailAddressForSuggestions uses EmailAddressForSuggestions when set' ); + C4::Letters::GetMessage( $newsuggestions_messages->[8]->{message_id} ); + is( + $message9->{to_address}, + 'suggestions@b.c', 'EmailAddressForSuggestions uses EmailAddressForSuggestions when set' + ); }; subtest 'ModSuggestion should work on suggestions without a suggester' => sub { @@ -661,24 +798,30 @@ subtest 'place_hold tests' => sub { subtest 'Suggestion with ISBN' => sub { my $suggestion_with_isbn = { - isbn => '1940997232', - title => "The Clouds", - author => "Aristophanes", + isbn => '1940997232', + title => "The Clouds", + author => "Aristophanes", }; - my $record = MarcRecordFromNewSuggestion( $suggestion_with_isbn ); - is("MARC::Record", ref($record), "MarcRecordFromNewSuggestion should return a MARC::Record object"); + my $record = MarcRecordFromNewSuggestion($suggestion_with_isbn); + is( "MARC::Record", ref($record), "MarcRecordFromNewSuggestion should return a MARC::Record object" ); - my ($isbn_tag, $isbn_subfield) = C4::Biblio::GetMarcFromKohaField('biblioitems.isbn'); - is($record->field( $isbn_tag )->subfield( $isbn_subfield ), "1940997232", "ISBN Record from suggestion ISBN should be '1940997232'"); + my ( $isbn_tag, $isbn_subfield ) = C4::Biblio::GetMarcFromKohaField('biblioitems.isbn'); + is( + $record->field($isbn_tag)->subfield($isbn_subfield), "1940997232", + "ISBN Record from suggestion ISBN should be '1940997232'" + ); - my ($issn_tag, $issn_subfield) = C4::Biblio::GetMarcFromKohaField('biblioitems.issn'); - is($record->field( $issn_tag )->subfield( $issn_subfield ), "1940997232", "ISSN Record from suggestion ISBN should also be '1940997232'"); + my ( $issn_tag, $issn_subfield ) = C4::Biblio::GetMarcFromKohaField('biblioitems.issn'); + is( + $record->field($issn_tag)->subfield($issn_subfield), "1940997232", + "ISSN Record from suggestion ISBN should also be '1940997232'" + ); - my ($title_tag, $title_subfield) = C4::Biblio::GetMarcFromKohaField('biblio.title'); - is($record->field( $title_tag), undef, "Record from suggestion title should be empty"); + my ( $title_tag, $title_subfield ) = C4::Biblio::GetMarcFromKohaField('biblio.title'); + is( $record->field($title_tag), undef, "Record from suggestion title should be empty" ); - my ($author_tag, $author_subfield) = C4::Biblio::GetMarcFromKohaField('biblio.author'); - is($record->field( $author_tag), undef, "Record from suggestion author should be empty"); + my ( $author_tag, $author_subfield ) = C4::Biblio::GetMarcFromKohaField('biblio.author'); + is( $record->field($author_tag), undef, "Record from suggestion author should be empty" ); }; $schema->storage->txn_rollback; diff --git a/t/db_dependent/TablesSettings.t b/t/db_dependent/TablesSettings.t index 4113cbde26..3d4f14074b 100755 --- a/t/db_dependent/TablesSettings.t +++ b/t/db_dependent/TablesSettings.t @@ -47,7 +47,7 @@ $module->mock( { columnname => 'active' }, { columnname => 'actions' } ] - } + } } }, } @@ -117,52 +117,52 @@ my $modules_expected = { 'admin' => { 'currency' => { 'currencies-table' => { - default_display_length => 20, - default_sort_order => 1, - default_save_state => 1, + default_display_length => 20, + default_sort_order => 1, + default_save_state => 1, default_save_state_search => 0, - columns => [ + columns => [ { columnname => 'currency', cannot_be_toggled => 1, cannot_be_modified => 1, - is_hidden => 0, + is_hidden => 0, }, { columnname => 'rate', cannot_be_toggled => 1, cannot_be_modified => 1, - is_hidden => 0, + is_hidden => 0, }, { - columnname => 'symbol', + columnname => 'symbol', cannot_be_toggled => 0, cannot_be_modified => 0, - is_hidden => 0, + is_hidden => 0, }, { - columnname => 'iso_code', + columnname => 'iso_code', cannot_be_toggled => 0, cannot_be_modified => 0, - is_hidden => 0, + is_hidden => 0, }, { - columnname => 'last_updated', + columnname => 'last_updated', cannot_be_toggled => 0, cannot_be_modified => 0, - is_hidden => 0, + is_hidden => 0, }, { - columnname => 'active', + columnname => 'active', cannot_be_toggled => 0, cannot_be_modified => 0, - is_hidden => 1, + is_hidden => 1, }, { - columnname => 'actions', - cannot_be_toggled => 1, + columnname => 'actions', + cannot_be_toggled => 1, cannot_be_modified => 0, - is_hidden => 0, + is_hidden => 0, }, ] } @@ -175,19 +175,18 @@ is_deeply( $modules, $modules_expected, 'get_modules returns all values' ); for my $m ( keys %$modules ) { for my $p ( keys %{ $modules->{$m} } ) { for my $t ( keys %{ $modules->{$m}{$p} } ) { - my $columns = - C4::Utils::DataTables::TablesSettings::get_columns( $m, $p, $t ); + my $columns = C4::Utils::DataTables::TablesSettings::get_columns( $m, $p, $t ); + # We do not store default_save_state and default_save_state_search in the yml file # Removing them before comparison - delete $_->{default_save_state} for @$columns; + delete $_->{default_save_state} for @$columns; delete $_->{default_save_state_search} for @$columns; is_deeply( $columns, $modules->{$m}{$p}{$t}{columns}, "columns for $m>$p>$t" ); - my $table_settings = - C4::Utils::DataTables::TablesSettings::get_table_settings( $m, $p, $t ); + my $table_settings = C4::Utils::DataTables::TablesSettings::get_table_settings( $m, $p, $t ); is_deeply( { default_display_length => $table_settings->{default_display_length}, diff --git a/t/db_dependent/Tags.t b/t/db_dependent/Tags.t index b72ebd7b41..c6234fad8d 100755 --- a/t/db_dependent/Tags.t +++ b/t/db_dependent/Tags.t @@ -35,7 +35,7 @@ use C4::Tags qw( add_tag_approval add_tag add_tag_index get_tag_rows stratify_ta # So any output is readable :-D binmode STDOUT, ':encoding(utf8)'; -my $schema = Koha::Database->schema; +my $schema = Koha::Database->schema; my $builder = t::lib::TestBuilder->new; subtest 'add_tag_approval() tests' => sub { @@ -48,24 +48,25 @@ subtest 'add_tag_approval() tests' => sub { Koha::Tags::Approvals->search->delete; my $terms = { - # term => count - '🐋a' => 3, # added an ASCII char to make it differ from just emojis + + # term => count + '🐋a' => 3, # added an ASCII char to make it differ from just emojis '🌮' => 2, '👍' => 1, }; - for my $term ( keys %{ $terms } ) { - for (my $i=1; $i <= $terms->{$term}; $i++) { - C4::Tags::add_tag_approval( $term ); + for my $term ( keys %{$terms} ) { + for ( my $i = 1 ; $i <= $terms->{$term} ; $i++ ) { + C4::Tags::add_tag_approval($term); } } my $approvals = Koha::Tags::Approvals->search; - is( $approvals->count, scalar keys %{ $terms }, 'All terms got their approval row' ); + is( $approvals->count, scalar keys %{$terms}, 'All terms got their approval row' ); while ( my $approval = $approvals->next ) { - ok( exists $terms->{$approval->term}, 'The returned term is in our list' ); - is( $approval->weight_total, $terms->{$approval->term} ); + ok( exists $terms->{ $approval->term }, 'The returned term is in our list' ); + is( $approval->weight_total, $terms->{ $approval->term } ); } $schema->storage->txn_rollback; @@ -80,28 +81,29 @@ subtest 'add_tag_index() tests' => sub { # Make sure there's no pollution on the DB Koha::Tags::Indexes->search->delete; - my $biblio = $builder->build_object({ class => 'Koha::Biblios' }); + my $biblio = $builder->build_object( { class => 'Koha::Biblios' } ); my $terms = { - # term => count - '🐋a' => 3, # added an ASCII char to make it differ from just emojis + + # term => count + '🐋a' => 3, # added an ASCII char to make it differ from just emojis '🌮' => 2, '👍' => 1, }; while ( my ( $term, $count ) = each %$terms ) { - for ( 1 .. $count ) { - C4::Tags::add_tag_approval( $term ); + for ( 1 .. $count ) { + C4::Tags::add_tag_approval($term); C4::Tags::add_tag_index( $term, $biblio->biblionumber ); } } - my $indexes = Koha::Tags::Indexes->search({ biblionumber => $biblio->biblionumber }); - is( $indexes->count, scalar keys %{ $terms }, 'All terms got their index row' ); + my $indexes = Koha::Tags::Indexes->search( { biblionumber => $biblio->biblionumber } ); + is( $indexes->count, scalar keys %{$terms}, 'All terms got their index row' ); while ( my $index = $indexes->next ) { - ok( exists $terms->{$index->term}, 'The returned term is in our list' ); - is( $index->weight, $terms->{$index->term} ); + ok( exists $terms->{ $index->term }, 'The returned term is in our list' ); + is( $index->weight, $terms->{ $index->term } ); } $schema->storage->txn_rollback; @@ -116,28 +118,33 @@ subtest 'get_tag_rows() tests' => sub { # Make sure there's no pollution on the DB Koha::Tags->search->delete; - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); - my $biblio = $builder->build_object({ class => 'Koha::Biblios' }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + my $biblio = $builder->build_object( { class => 'Koha::Biblios' } ); my @terms = ( '🐋a', '🌮', '👍' ); - for my $term ( @terms ) { - $builder->build_object({ class => 'Koha::Tags', value => { - borrowernumber => $patron->id, - biblionumber => $biblio->id, - term => $term, - } }); + for my $term (@terms) { + $builder->build_object( + { + class => 'Koha::Tags', + value => { + borrowernumber => $patron->id, + biblionumber => $biblio->id, + term => $term, + } + } + ); } - my $tags = Koha::Tags->search({ borrowernumber => $patron->id }); + my $tags = Koha::Tags->search( { borrowernumber => $patron->id } ); is( $tags->count, scalar @terms, 'All terms got their row' ); while ( my $tag = $tags->next ) { - ok( any { $_ eq $tag->term } @terms , 'The returned term is in our list' ); + ok( any { $_ eq $tag->term } @terms, 'The returned term is in our list' ); } - for my $term ( @terms ) { - my @result = @{ C4::Tags::get_tag_rows({ term => $term }) }; + for my $term (@terms) { + my @result = @{ C4::Tags::get_tag_rows( { term => $term } ) }; is( scalar @result, 1, 'Only one row matches each' ); } @@ -148,50 +155,50 @@ subtest 'get_tag_rows() tests' => sub { # Check no tags case. my @tagsarray; my $tags = \@tagsarray; -my ($min, $max) = C4::Tags::stratify_tags(0, $tags); -is($min, 0, 'Empty array min'); -is($max, 0, 'Empty array max'); +my ( $min, $max ) = C4::Tags::stratify_tags( 0, $tags ); +is( $min, 0, 'Empty array min' ); +is( $max, 0, 'Empty array max' ); # Simple 'sequential 5' test -$tags = make_tags(1,2,3,4,5); -my @strata = (0,1,2,3,4); -($min, $max) = C4::Tags::stratify_tags(5, $tags); -check_tag_strata($tags, \@strata, 'Sequential 5'); -is($min, 0, 'Sequential 5 min'); -is($max, 4, 'Sequential 5 max'); +$tags = make_tags( 1, 2, 3, 4, 5 ); +my @strata = ( 0, 1, 2, 3, 4 ); +( $min, $max ) = C4::Tags::stratify_tags( 5, $tags ); +check_tag_strata( $tags, \@strata, 'Sequential 5' ); +is( $min, 0, 'Sequential 5 min' ); +is( $max, 4, 'Sequential 5 max' ); # Reverse test - should have the same results as previous -$tags = make_tags(5,4,3,2,1); -@strata = (4,3,2,1,0); -($min, $max) = C4::Tags::stratify_tags(5, $tags); -check_tag_strata($tags, \@strata, 'Reverse Sequential 5'); -is($min, 0, 'Sequential 5 min'); -is($max, 4, 'Sequential 5 max'); +$tags = make_tags( 5, 4, 3, 2, 1 ); +@strata = ( 4, 3, 2, 1, 0 ); +( $min, $max ) = C4::Tags::stratify_tags( 5, $tags ); +check_tag_strata( $tags, \@strata, 'Reverse Sequential 5' ); +is( $min, 0, 'Sequential 5 min' ); +is( $max, 4, 'Sequential 5 max' ); # All the same test - should all have the same results -$tags = make_tags(4,4,4,4,4); -@strata = (0,0,0,0,0); -($min, $max) = C4::Tags::stratify_tags(5, $tags); -check_tag_strata($tags, \@strata, 'All The Same'); -is($min, 0, 'Sequential 5 min'); -is($max, 0, 'Sequential 5 max'); +$tags = make_tags( 4, 4, 4, 4, 4 ); +@strata = ( 0, 0, 0, 0, 0 ); +( $min, $max ) = C4::Tags::stratify_tags( 5, $tags ); +check_tag_strata( $tags, \@strata, 'All The Same' ); +is( $min, 0, 'Sequential 5 min' ); +is( $max, 0, 'Sequential 5 max' ); # Some the same, some different -$tags = make_tags(1,2,2,3,3,8); -@strata = (0,0,0,1,1,4); -($min, $max) = C4::Tags::stratify_tags(5, $tags); -check_tag_strata($tags, \@strata, 'All The Same'); -is($min, 0, 'Sequential 5 min'); -is($max, 7, 'Sequential 5 max'); +$tags = make_tags( 1, 2, 2, 3, 3, 8 ); +@strata = ( 0, 0, 0, 1, 1, 4 ); +( $min, $max ) = C4::Tags::stratify_tags( 5, $tags ); +check_tag_strata( $tags, \@strata, 'All The Same' ); +is( $min, 0, 'Sequential 5 min' ); +is( $max, 7, 'Sequential 5 max' ); # Runs tests against the results sub check_tag_strata { - my ($tags, $expected, $name) = @_; + my ( $tags, $expected, $name ) = @_; foreach my $t (@$tags) { my $w = $t->{weight_total}; my $s = $t->{stratum}; - is($s, shift @$expected, $name . " - $w ($s)"); + is( $s, shift @$expected, $name . " - $w ($s)" ); } } diff --git a/t/db_dependent/Template/Plugin/AdditionalContents.t b/t/db_dependent/Template/Plugin/AdditionalContents.t index 95c519f0f0..229ef7d95b 100755 --- a/t/db_dependent/Template/Plugin/AdditionalContents.t +++ b/t/db_dependent/Template/Plugin/AdditionalContents.t @@ -27,7 +27,7 @@ use Koha::Template::Plugin::AdditionalContents; use t::lib::TestBuilder; use t::lib::Mocks; -my $schema = Koha::Database->schema; +my $schema = Koha::Database->schema; my $builder = t::lib::TestBuilder->new; $schema->storage->txn_begin; diff --git a/t/db_dependent/Template/Plugin/AuthorisedValues.t b/t/db_dependent/Template/Plugin/AuthorisedValues.t index 722a229f0f..0a6aa66a6e 100755 --- a/t/db_dependent/Template/Plugin/AuthorisedValues.t +++ b/t/db_dependent/Template/Plugin/AuthorisedValues.t @@ -27,7 +27,7 @@ use Koha::Template::Plugin::AuthorisedValues; use t::lib::TestBuilder; use t::lib::Mocks; -my $schema = Koha::Database->schema; +my $schema = Koha::Database->schema; my $builder = t::lib::TestBuilder->new; subtest 'GetByCode' => sub { @@ -35,8 +35,7 @@ subtest 'GetByCode' => sub { $schema->storage->txn_begin; - my $avc = - $builder->build_object( { class => 'Koha::AuthorisedValueCategories' } ); + my $avc = $builder->build_object( { class => 'Koha::AuthorisedValueCategories' } ); my $av_1 = $builder->build_object( { class => 'Koha::AuthorisedValues', @@ -49,23 +48,27 @@ subtest 'GetByCode' => sub { value => { category => $avc->category_name } } ); - my $description = - Koha::Template::Plugin::AuthorisedValues->GetByCode( $avc->category_name, - $av_1->authorised_value ); + my $description = Koha::Template::Plugin::AuthorisedValues->GetByCode( + $avc->category_name, + $av_1->authorised_value + ); is( $description, $av_1->lib, 'GetByCode should return the correct dsecription' ); - my $opac_description = - Koha::Template::Plugin::AuthorisedValues->GetByCode( $avc->category_name, - $av_1->authorised_value, 'opac' ); + my $opac_description = Koha::Template::Plugin::AuthorisedValues->GetByCode( + $avc->category_name, + $av_1->authorised_value, 'opac' + ); is( $opac_description, $av_1->opac_description, 'GetByCode should return the correct opac_description' ); $av_1->lib_opac(undef)->store; - $opac_description = - Koha::Template::Plugin::AuthorisedValues->GetByCode( $avc->category_name, - $av_1->authorised_value, 'opac' ); + $opac_description = Koha::Template::Plugin::AuthorisedValues->GetByCode( + $avc->category_name, + $av_1->authorised_value, 'opac' + ); is( $opac_description, $av_1->lib, 'GetByCode should return the staff description if the lib_opac is not filled' ); - $description = - Koha::Template::Plugin::AuthorisedValues->GetByCode( $avc->category_name, - 'does_not_exist' ); + $description = Koha::Template::Plugin::AuthorisedValues->GetByCode( + $avc->category_name, + 'does_not_exist' + ); is( $description, 'does_not_exist', 'GetByCode should return the code passed if the AV does not exist' ); $schema->storage->txn_rollback; @@ -99,17 +102,20 @@ subtest 'GetDescriptionByKohaField' => sub { # Make sure we are not catch by cache Koha::Caches->get_instance->flush_all; my $av_1 = $builder->build_object( - { class => 'Koha::AuthorisedValues', + { + class => 'Koha::AuthorisedValues', value => { category => $avc->category_name, lib_opac => 'lib_opac', lib => 'lib' } } )->store; my $av_2 = $builder->build_object( - { class => 'Koha::AuthorisedValues', + { + class => 'Koha::AuthorisedValues', value => { category => $avc->category_name, lib_opac => undef, lib => 'lib' } } )->store; my $av_3 = $builder->build_object( - { class => 'Koha::AuthorisedValues', + { + class => 'Koha::AuthorisedValues', value => { category => $avc->category_name, lib_opac => undef, lib => undef } } )->store; @@ -130,10 +136,16 @@ subtest 'GetDescriptionByKohaField' => sub { is( $av, 'lib', 'For OPAC: The staff description should be displayed if none exists for OPAC' ); $av = Koha::Template::Plugin::AuthorisedValues->GetDescriptionByKohaField( { opac => 1, kohafield => 'dummy.field', authorised_value => $av_3->authorised_value } ); - is( $av, $av_3->authorised_value, 'For OPAC: If both OPAC and staff descriptions are missing, the code should be displayed'); + is( + $av, $av_3->authorised_value, + 'For OPAC: If both OPAC and staff descriptions are missing, the code should be displayed' + ); $av = Koha::Template::Plugin::AuthorisedValues->GetDescriptionByKohaField( { opac => 1, kohafield => 'dummy.field', authorised_value => $non_existent_av } ); - is( $av, $non_existent_av, 'For OPAC: If both OPAC and staff descriptions are missing, the parameter should be displayed'); + is( + $av, $non_existent_av, + 'For OPAC: If both OPAC and staff descriptions are missing, the parameter should be displayed' + ); # Staff display $av = Koha::Template::Plugin::AuthorisedValues->GetDescriptionByKohaField( @@ -141,13 +153,16 @@ subtest 'GetDescriptionByKohaField' => sub { is( $av, 'lib', 'The staff description should be displayed' ); $av = Koha::Template::Plugin::AuthorisedValues->GetDescriptionByKohaField( { kohafield => 'dummy.field', authorised_value => $av_3->authorised_value } ); - is( $av, $av_3->authorised_value, 'If both OPAC and staff descriptions are missing, the code should be displayed'); + is( $av, $av_3->authorised_value, 'If both OPAC and staff descriptions are missing, the code should be displayed' ); $av = Koha::Template::Plugin::AuthorisedValues->GetDescriptionByKohaField( { kohafield => 'dummy.field', authorised_value => $non_existent_av } ); - is( $av, $non_existent_av, 'If both OPAC and staff descriptions are missing, the parameter should be displayed'); + is( $av, $non_existent_av, 'If both OPAC and staff descriptions are missing, the parameter should be displayed' ); $av = Koha::Template::Plugin::AuthorisedValues->GetDescriptionByKohaField( { kohafield => 'dummy.field', authorised_value => undef } ); - is( $av, '', 'If both OPAC and staff descriptions are missing, and the parameter is undef, an empty string should be displayed'); + is( + $av, '', + 'If both OPAC and staff descriptions are missing, and the parameter is undef, an empty string should be displayed' + ); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/Template/Plugin/Branches.t b/t/db_dependent/Template/Plugin/Branches.t index 163696d190..75d474e0e0 100755 --- a/t/db_dependent/Template/Plugin/Branches.t +++ b/t/db_dependent/Template/Plugin/Branches.t @@ -23,7 +23,7 @@ use C4::Context; use C4::Biblio qw(AddBiblio); use Koha::Database; -use Clone qw(clone); +use Clone qw(clone); use List::MoreUtils qw(any); use t::lib::TestBuilder; @@ -42,73 +42,100 @@ subtest 'all() tests' => sub { $schema->storage->txn_begin; - my $library = $builder->build({ - source => 'Branch', - value => { - branchcode => 'MYLIBRARY', - branchname => 'My sweet library' + my $library = $builder->build( + { + source => 'Branch', + value => { + branchcode => 'MYLIBRARY', + branchname => 'My sweet library' + } } - }); - my $another_library = $builder->build({ - source => 'Branch', - value => { - branchcode => 'ANOTHERLIB', + ); + my $another_library = $builder->build( + { + source => 'Branch', + value => { + branchcode => 'ANOTHERLIB', + } } - }); + ); my $plugin = Koha::Template::Plugin::Branches->new(); - ok($plugin, "initialized Branches plugin"); + ok( $plugin, "initialized Branches plugin" ); - my $name = $plugin->GetName($library->{branchcode}); - is($name, $library->{branchname}, 'retrieved expected name for library'); + my $name = $plugin->GetName( $library->{branchcode} ); + is( $name, $library->{branchname}, 'retrieved expected name for library' ); $name = $plugin->GetName('__ANY__'); - is($name, '', 'received empty string as name of the "__ANY__" placeholder library code'); + is( $name, '', 'received empty string as name of the "__ANY__" placeholder library code' ); $name = $plugin->GetName(undef); - is($name, '', 'received empty string as name of NULL/undefined library code'); + is( $name, '', 'received empty string as name of NULL/undefined library code' ); $name = $plugin->GetName(q{}); - is($name, '', 'received empty string as name of empty string library code'); + is( $name, '', 'received empty string as name of empty string library code' ); - is($plugin->GetLoggedInBranchcode(), '', 'no active library code if there is no active user session'); - is($plugin->GetLoggedInBranchname(), '', 'no active library name if there is no active user session'); + is( $plugin->GetLoggedInBranchcode(), '', 'no active library code if there is no active user session' ); + is( $plugin->GetLoggedInBranchname(), '', 'no active library name if there is no active user session' ); - t::lib::Mocks::mock_userenv({ branchcode => 'MYLIBRARY', branchname => 'My sweet library' }); - is($plugin->GetLoggedInBranchcode(), 'MYLIBRARY', 'GetLoggedInBranchcode() returns active library code'); - is($plugin->GetLoggedInBranchname(), 'My sweet library', 'GetLoggedInBranchname() returns active library name'); + t::lib::Mocks::mock_userenv( { branchcode => 'MYLIBRARY', branchname => 'My sweet library' } ); + is( $plugin->GetLoggedInBranchcode(), 'MYLIBRARY', 'GetLoggedInBranchcode() returns active library code' ); + is( $plugin->GetLoggedInBranchname(), 'My sweet library', 'GetLoggedInBranchname() returns active library name' ); t::lib::Mocks::mock_preference( 'IndependentBranches', 0 ); my $libraries = $plugin->all(); ok( scalar(@$libraries) > 1, 'If IndependentBranches is not set, all libraries should be returned' ); - is( grep ( { $_->{branchcode} eq 'MYLIBRARY' and $_->{selected} == 1 } @$libraries ), 1, 'Without selected parameter, my library should be preselected' ); - is( grep ( { $_->{branchcode} eq 'ANOTHERLIB' and not exists $_->{selected} } @$libraries ), 1, 'Without selected parameter, other library should not be preselected' ); + is( + grep ( { $_->{branchcode} eq 'MYLIBRARY' and $_->{selected} == 1 } @$libraries ), 1, + 'Without selected parameter, my library should be preselected' + ); + is( + grep ( { $_->{branchcode} eq 'ANOTHERLIB' and not exists $_->{selected} } @$libraries ), 1, + 'Without selected parameter, other library should not be preselected' + ); $libraries = $plugin->all( { selected => 'ANOTHERLIB' } ); - is( grep ( { $_->{branchcode} eq 'MYLIBRARY' and not exists $_->{selected} } @$libraries ), 1, 'With selected parameter, my library should not be preselected' ); - is( grep ( { $_->{branchcode} eq 'ANOTHERLIB' and $_->{selected} == 1 } @$libraries ), 1, 'With selected parameter, other library should be preselected' ); + is( + grep ( { $_->{branchcode} eq 'MYLIBRARY' and not exists $_->{selected} } @$libraries ), 1, + 'With selected parameter, my library should not be preselected' + ); + is( + grep ( { $_->{branchcode} eq 'ANOTHERLIB' and $_->{selected} == 1 } @$libraries ), 1, + 'With selected parameter, other library should be preselected' + ); $libraries = $plugin->all( { selected => '' } ); - is( grep ( { exists $_->{selected} } @$libraries ), 0, 'With selected parameter set to an empty string, no library should be preselected' ); + is( + grep ( { exists $_->{selected} } @$libraries ), 0, + 'With selected parameter set to an empty string, no library should be preselected' + ); - my $total = @{$plugin->all}; - my $pickupable = @{$plugin->all( { search_params => { pickup_location => 1 } }) }; - my $yet_another_library = $builder->build({ - source => 'Branch', - value => { - branchcode => 'CANTPICKUP', - pickup_location => 0, + my $total = @{ $plugin->all }; + my $pickupable = @{ $plugin->all( { search_params => { pickup_location => 1 } } ) }; + my $yet_another_library = $builder->build( + { + source => 'Branch', + value => { + branchcode => 'CANTPICKUP', + pickup_location => 0, + } } - }); - is(@{$plugin->all( { search_params => { pickup_location => 1 } }) }, $pickupable, - 'Adding a new library with pickups' - .' disabled does not increase the amount returned by ->pickup_locations'); - is(@{$plugin->all}, $total+1, 'However, adding a new library increases' - .' the total amount gotten with ->all'); + ); + is( + @{ $plugin->all( { search_params => { pickup_location => 1 } } ) }, $pickupable, + 'Adding a new library with pickups' . ' disabled does not increase the amount returned by ->pickup_locations' + ); + is( + @{ $plugin->all }, $total + 1, + 'However, adding a new library increases' . ' the total amount gotten with ->all' + ); t::lib::Mocks::mock_preference( 'IndependentBranches', 1 ); $libraries = $plugin->all(); is( scalar(@$libraries), 1, 'If IndependentBranches is set, only 1 library should be returned' ); $libraries = $plugin->all( { unfiltered => 1 } ); - ok( scalar(@$libraries) > 1, 'If IndependentBranches is set, all libraries should be returned if the unfiltered flag is set' ); + ok( + scalar(@$libraries) > 1, + 'If IndependentBranches is set, all libraries should be returned if the unfiltered flag is set' + ); $schema->storage->txn_rollback; }; @@ -119,56 +146,54 @@ subtest 'pickup_locations() tests' => sub { $schema->storage->txn_begin; - Koha::Libraries->search->update({ pickup_location => 0 }); + Koha::Libraries->search->update( { pickup_location => 0 } ); - my $library_1 = $builder->build_object({ class => 'Koha::Libraries', value => { pickup_location => 1 } }); - my $library_2 = $builder->build_object({ class => 'Koha::Libraries', value => { pickup_location => 1 } }); - my $library_3 = $builder->build_object({ class => 'Koha::Libraries', value => { pickup_location => 1 } }); + my $library_1 = $builder->build_object( { class => 'Koha::Libraries', value => { pickup_location => 1 } } ); + my $library_2 = $builder->build_object( { class => 'Koha::Libraries', value => { pickup_location => 1 } } ); + my $library_3 = $builder->build_object( { class => 'Koha::Libraries', value => { pickup_location => 1 } } ); my $plugin = Koha::Template::Plugin::Branches->new(); my $pickup_locations = $plugin->pickup_locations(); is( scalar @{$pickup_locations}, 3, 'Libraries count is correct' ); - $pickup_locations = $plugin->pickup_locations({ search_params => { item => undef }}); + $pickup_locations = $plugin->pickup_locations( { search_params => { item => undef } } ); is( scalar @{$pickup_locations}, 3, 'item parameter not a ref, fallback to general search' ); - $pickup_locations = $plugin->pickup_locations({ search_params => { biblio => undef }}); + $pickup_locations = $plugin->pickup_locations( { search_params => { biblio => undef } } ); is( scalar @{$pickup_locations}, 3, 'biblio parameter not a ref, fallback to general search' ); my $item_class = Test::MockModule->new('Koha::Item'); $item_class->mock( 'pickup_locations', sub { - return Koha::Libraries->search( - { branchcode => $library_1->branchcode } ); + return Koha::Libraries->search( { branchcode => $library_1->branchcode } ); } ); my $item = $builder->build_sample_item(); - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); - $pickup_locations = $plugin->pickup_locations( - { search_params => { item => $item, patron => Koha::Patron->new } } ); + $pickup_locations = + $plugin->pickup_locations( { search_params => { item => $item, patron => Koha::Patron->new } } ); - is( scalar @{$pickup_locations}, 1, 'Only the library returned by $item->pickup_locations is returned' ); + is( scalar @{$pickup_locations}, 1, 'Only the library returned by $item->pickup_locations is returned' ); is( $pickup_locations->[0]->{branchcode}, $library_1->branchcode, 'Not cheating' ); my $biblio_class = Test::MockModule->new('Koha::Biblio'); $biblio_class->mock( 'pickup_locations', sub { - return Koha::Libraries->search( - { branchcode => $library_2->branchcode } ); + return Koha::Libraries->search( { branchcode => $library_2->branchcode } ); } ); my $biblio = $builder->build_sample_biblio(); - $pickup_locations = $plugin->pickup_locations( - { search_params => { biblio => $biblio, patron => Koha::Patron->new } } ); + $pickup_locations = + $plugin->pickup_locations( { search_params => { biblio => $biblio, patron => Koha::Patron->new } } ); - is( scalar @{$pickup_locations}, 1, 'Only the library returned by $biblio->pickup_locations is returned' ); + is( scalar @{$pickup_locations}, 1, 'Only the library returned by $biblio->pickup_locations is returned' ); is( $pickup_locations->[0]->{branchcode}, $library_2->branchcode, 'Not cheating' ); subtest 'Koha::Item->pickup_locations and Koha::Biblio->pickup_locations empty tests' => sub { @@ -180,7 +205,7 @@ subtest 'pickup_locations() tests' => sub { my $biblio = $builder->build_sample_biblio; - my @pickup_locations = @{$plugin->pickup_locations({ search_params => { biblio => $biblio->id } })}; + my @pickup_locations = @{ $plugin->pickup_locations( { search_params => { biblio => $biblio->id } } ) }; is( scalar @pickup_locations, 0, 'No pickup locations returned' ); my $item_class = Test::MockModule->new('Koha::Item'); @@ -188,7 +213,7 @@ subtest 'pickup_locations() tests' => sub { my $item = $builder->build_sample_item; - @pickup_locations = @{$plugin->pickup_locations({ search_params => { item => $item->id } })}; + @pickup_locations = @{ $plugin->pickup_locations( { search_params => { item => $item->id } } ) }; is( scalar @pickup_locations, 0, 'No pickup locations returned' ); }; @@ -196,20 +221,20 @@ subtest 'pickup_locations() tests' => sub { plan tests => 4; - t::lib::Mocks::mock_userenv({ branchcode => $library_2->branchcode }); + t::lib::Mocks::mock_userenv( { branchcode => $library_2->branchcode } ); $pickup_locations = $plugin->pickup_locations(); is( scalar @{$pickup_locations}, 3, 'Libraries count is correct' ); - foreach my $pickup_location (@{ $pickup_locations }) { + foreach my $pickup_location ( @{$pickup_locations} ) { next unless exists $pickup_location->{selected} and $pickup_location->{selected} == 1; is( $pickup_location->{branchcode}, $library_2->branchcode, 'The right library is marked as selected' ); } - $pickup_locations = $plugin->pickup_locations({ selected => $library_3->branchcode }); + $pickup_locations = $plugin->pickup_locations( { selected => $library_3->branchcode } ); is( scalar @{$pickup_locations}, 3, 'Libraries count is correct' ); - foreach my $pickup_location (@{ $pickup_locations }) { + foreach my $pickup_location ( @{$pickup_locations} ) { next unless exists $pickup_location->{selected} and $pickup_location->{selected} == 1; is( $pickup_location->{branchcode}, $library_3->branchcode, 'The right library is marked as selected' ); } @@ -224,38 +249,42 @@ subtest 'branch specific js and css' => sub { $schema->storage->txn_begin; - my $newbranch_with = $builder->build({ - source => 'Branch', - value => { - opacuserjs => 'console.log(\'Hello World\');', - opacusercss => 'body { background-color: blue; }' + my $newbranch_with = $builder->build( + { + source => 'Branch', + value => { + opacuserjs => 'console.log(\'Hello World\');', + opacusercss => 'body { background-color: blue; }' + } } - }); - my $newbranch_none = $builder->build({ - source => 'Branch', - value => { - opacuserjs => '', - opacusercss => '' + ); + my $newbranch_none = $builder->build( + { + source => 'Branch', + value => { + opacuserjs => '', + opacusercss => '' + } } - }); + ); my $plugin = Koha::Template::Plugin::Branches->new(); - my $opacuserjs = $plugin->GetBranchSpecificJS($newbranch_with->{branchcode}); - is($opacuserjs, $newbranch_with->{opacuserjs},'received correct JS string from function'); + my $opacuserjs = $plugin->GetBranchSpecificJS( $newbranch_with->{branchcode} ); + is( $opacuserjs, $newbranch_with->{opacuserjs}, 'received correct JS string from function' ); - my $opacusercss = $plugin->GetBranchSpecificCSS($newbranch_with->{branchcode}); - is($opacusercss, $newbranch_with->{opacusercss},'received correct CSS string from function'); + my $opacusercss = $plugin->GetBranchSpecificCSS( $newbranch_with->{branchcode} ); + is( $opacusercss, $newbranch_with->{opacusercss}, 'received correct CSS string from function' ); - $opacuserjs = $plugin->GetBranchSpecificJS($newbranch_none->{branchcode}); - $opacusercss = $plugin->GetBranchSpecificCSS($newbranch_none->{branchcode}); - is($opacuserjs, q{},'received correct blank string from function when branch has none'); - is($opacusercss, q{},'received correct blank string from function when branch has none'); + $opacuserjs = $plugin->GetBranchSpecificJS( $newbranch_none->{branchcode} ); + $opacusercss = $plugin->GetBranchSpecificCSS( $newbranch_none->{branchcode} ); + is( $opacuserjs, q{}, 'received correct blank string from function when branch has none' ); + is( $opacusercss, q{}, 'received correct blank string from function when branch has none' ); - $opacuserjs = $plugin->GetBranchSpecificJS(); + $opacuserjs = $plugin->GetBranchSpecificJS(); $opacusercss = $plugin->GetBranchSpecificCSS(); - is($opacuserjs, q{},'received correct blank string from function when no branch set'); - is($opacusercss, q{},'received correct blank string from function when no branch set'); + is( $opacuserjs, q{}, 'received correct blank string from function when no branch set' ); + is( $opacusercss, q{}, 'received correct blank string from function when no branch set' ); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/Template/Plugin/Categories.t b/t/db_dependent/Template/Plugin/Categories.t index 04580d7912..2a3e489951 100755 --- a/t/db_dependent/Template/Plugin/Categories.t +++ b/t/db_dependent/Template/Plugin/Categories.t @@ -30,15 +30,17 @@ use Koha::Template::Plugin::Categories; my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; -my $builder = t::lib::TestBuilder->new; +my $builder = t::lib::TestBuilder->new; my $nb_categories = Koha::Patron::Categories->count; # Create sample categories -my $category_1 = $builder->build_object( { class => 'Koha::Patron::Categories', value => { description => 'ZZZZZZ' } } ); +my $category_1 = + $builder->build_object( { class => 'Koha::Patron::Categories', value => { description => 'ZZZZZZ' } } ); my @categories = Koha::Template::Plugin::Categories->new->all->as_list; is( scalar(@categories), 1 + $nb_categories, '->all returns all defined categories' ); -my $category_2 = $builder->build_object( { class => 'Koha::Patron::Categories', value => { description => 'AAAAAA' } } ); +my $category_2 = + $builder->build_object( { class => 'Koha::Patron::Categories', value => { description => 'AAAAAA' } } ); @categories = Koha::Template::Plugin::Categories->new->all->as_list; is( scalar(@categories), 2 + $nb_categories, '->all returns all defined categories' ); @@ -55,9 +57,8 @@ for ( my $i = 0 ; $i < scalar(@categories) ; $i++ ) { } ok( $category_1_pos > $category_2_pos, 'Categories are sorted by description' ); -is( Koha::Template::Plugin::Categories->GetName( - $category_1->categorycode - ), +is( + Koha::Template::Plugin::Categories->GetName( $category_1->categorycode ), $category_1->description, '->GetName returns the right description' ); @@ -68,10 +69,14 @@ $category_1->library_limits( [ $library_1->branchcode ] ); $category_2->library_limits( [ $library_2->branchcode ] ); t::lib::Mocks::mock_userenv( { branchcode => $library_1->branchcode } ); my $limited = Koha::Template::Plugin::Categories->limited; -is( $limited->search( { 'me.categorycode' => $category_1->categorycode } )->count, - 1, 'Category 1 is available from library 1' ); -is( $limited->search( { 'me.categorycode' => $category_2->categorycode } )->count, - 0, 'Category 2 is not available from library 1' ); +is( + $limited->search( { 'me.categorycode' => $category_1->categorycode } )->count, + 1, 'Category 1 is available from library 1' +); +is( + $limited->search( { 'me.categorycode' => $category_2->categorycode } )->count, + 0, 'Category 2 is not available from library 1' +); $schema->storage->txn_rollback; @@ -82,17 +87,20 @@ subtest 'can_any_reset_password() tests' => sub { $schema->storage->txn_begin; # Make sure all existing categories have reset_password set to 0 - Koha::Patron::Categories->search->update({ reset_password => 0 }); + Koha::Patron::Categories->search->update( { reset_password => 0 } ); ok( !Koha::Template::Plugin::Categories->new->can_any_reset_password, 'No category is allowed to reset password' ); t::lib::Mocks::mock_preference( 'OpacResetPassword', 0 ); - my $category = $builder->build_object({ class => 'Koha::Patron::Categories', value => { reset_password => 1 } }); + my $category = $builder->build_object( { class => 'Koha::Patron::Categories', value => { reset_password => 1 } } ); - ok( Koha::Template::Plugin::Categories->new->can_any_reset_password, 'There\'s at least a category that is allowed to reset password' ); + ok( + Koha::Template::Plugin::Categories->new->can_any_reset_password, + 'There\'s at least a category that is allowed to reset password' + ); - $category->reset_password( undef )->store; + $category->reset_password(undef)->store; ok( !Koha::Template::Plugin::Categories->new->can_any_reset_password, 'No category is allowed to reset password' ); diff --git a/t/db_dependent/Template/Plugin/CirculationRules.t b/t/db_dependent/Template/Plugin/CirculationRules.t index 50b158acee..e531083be6 100755 --- a/t/db_dependent/Template/Plugin/CirculationRules.t +++ b/t/db_dependent/Template/Plugin/CirculationRules.t @@ -37,20 +37,20 @@ subtest 'Basic function tests' => sub { $schema->storage->txn_begin; - my $library_1 = $builder->build_object({ class => 'Koha::Libraries' }); - my $library_2 = $builder->build_object({ class => 'Koha::Libraries' }); + my $library_1 = $builder->build_object( { class => 'Koha::Libraries' } ); + my $library_2 = $builder->build_object( { class => 'Koha::Libraries' } ); my $plugin = Koha::Template::Plugin::CirculationRules->new(); - ok($plugin, "initialized CirculationRules plugin"); + ok( $plugin, "initialized CirculationRules plugin" ); - my $rule_value = $plugin->Get($library_1->branchcode,'*','*','maxholds'); - is($rule_value, undef, 'Max holds not set, Get returns undef'); + my $rule_value = $plugin->Get( $library_1->branchcode, '*', '*', 'maxholds' ); + is( $rule_value, undef, 'Max holds not set, Get returns undef' ); - $rule_value = $plugin->Search($library_1->branchcode,'*','*','maxholds'); - is($rule_value, undef, 'Max holds not set, Search returns undef'); + $rule_value = $plugin->Search( $library_1->branchcode, '*', '*', 'maxholds' ); + is( $rule_value, undef, 'Max holds not set, Search returns undef' ); - my $rule = $plugin->Search($library_1->branchcode,'*','*','maxholds', { want_rule => 1 } ); - is($rule, undef, 'Max holds not set, Search with want_rule returns undef'); + my $rule = $plugin->Search( $library_1->branchcode, '*', '*', 'maxholds', { want_rule => 1 } ); + is( $rule, undef, 'Max holds not set, Search with want_rule returns undef' ); Koha::CirculationRules->set_rule( { @@ -70,23 +70,24 @@ subtest 'Basic function tests' => sub { } ); - $rule_value = $plugin->Get($library_1->branchcode,'*','*','max_holds'); - is($rule_value, "", 'Max holds set to blank string (unlimited), Get returns blank string for branch'); + $rule_value = $plugin->Get( $library_1->branchcode, '*', '*', 'max_holds' ); + is( $rule_value, "", 'Max holds set to blank string (unlimited), Get returns blank string for branch' ); - $rule = $plugin->Search($library_1->branchcode,'*','*','max_holds', { want_rule => 1 } ); - is(ref $rule, "Koha::CirculationRule" , 'Max holds set to blank string, Search with want_rule returns a circulation rules object'); - is( $rule->rule_value, "",'Max holds set to blank string (unlimited), returned rule has correct value'); + $rule = $plugin->Search( $library_1->branchcode, '*', '*', 'max_holds', { want_rule => 1 } ); + is( + ref $rule, "Koha::CirculationRule", + 'Max holds set to blank string, Search with want_rule returns a circulation rules object' + ); + is( $rule->rule_value, "", 'Max holds set to blank string (unlimited), returned rule has correct value' ); - $rule_value = $plugin->Get($library_2->branchcode,'*','*','max_holds'); - is($rule_value, 5, 'Max holds default set to 5, Get returns 5 for branch with no rule set'); - - $rule_value = $plugin->Search('*','*','*','max_holds'); - is($rule_value, 5, 'Search for all libraries max holds rule, Search returns 5'); - - $rule_value = $plugin->Search($library_1->branchcode,'*','*','max_holds'); - is($rule_value, "", 'Max holds set to blank string (unlimited), Get returns blank string for branch'); + $rule_value = $plugin->Get( $library_2->branchcode, '*', '*', 'max_holds' ); + is( $rule_value, 5, 'Max holds default set to 5, Get returns 5 for branch with no rule set' ); + $rule_value = $plugin->Search( '*', '*', '*', 'max_holds' ); + is( $rule_value, 5, 'Search for all libraries max holds rule, Search returns 5' ); + $rule_value = $plugin->Search( $library_1->branchcode, '*', '*', 'max_holds' ); + is( $rule_value, "", 'Max holds set to blank string (unlimited), Get returns blank string for branch' ); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/Template/Plugin/Frameworks.t b/t/db_dependent/Template/Plugin/Frameworks.t index be3a16935a..b43b677a29 100755 --- a/t/db_dependent/Template/Plugin/Frameworks.t +++ b/t/db_dependent/Template/Plugin/Frameworks.t @@ -34,7 +34,7 @@ $schema->storage->txn_begin; subtest 'GetName tests' => sub { plan tests => 3; - my $framework = $builder->build_object({ class => 'Koha::BiblioFrameworks' })->store; + my $framework = $builder->build_object( { class => 'Koha::BiblioFrameworks' } )->store; my $plugin = Koha::Template::Plugin::Frameworks->new(); diff --git a/t/db_dependent/Template/Plugin/KohaDates.t b/t/db_dependent/Template/Plugin/KohaDates.t index 5d7300c6f5..2978ff0f0a 100755 --- a/t/db_dependent/Template/Plugin/KohaDates.t +++ b/t/db_dependent/Template/Plugin/KohaDates.t @@ -10,35 +10,35 @@ use Test::More tests => 9; use t::lib::Mocks; BEGIN { - use_ok('Koha::Template::Plugin::KohaDates'); + use_ok('Koha::Template::Plugin::KohaDates'); } my $module_context = Test::MockModule->new('C4::Context'); -my $date = "1973-05-21"; +my $date = "1973-05-21"; my $context = C4::Context->new(); my $filter = Koha::Template::Plugin::KohaDates->new(); -ok ($filter, "new()"); +ok( $filter, "new()" ); t::lib::Mocks::mock_preference( "dateformat", 'iso' ); $context->clear_syspref_cache(); my $filtered_date = $filter->filter($date); -is ($filtered_date,$date, "iso conversion") or diag ("iso conversion fails"); +is( $filtered_date, $date, "iso conversion" ) or diag("iso conversion fails"); #$filter = Koha::Template::Plugin::KohaDates->new(); t::lib::Mocks::mock_preference( "dateformat", 'us' ); $context->clear_syspref_cache(); $filtered_date = $filter->filter($date); -is ($filtered_date,'05/21/1973', "us conversion") or diag ("us conversion fails $filtered_date"); +is( $filtered_date, '05/21/1973', "us conversion" ) or diag("us conversion fails $filtered_date"); t::lib::Mocks::mock_preference( "dateformat", 'metric' ); $context->clear_syspref_cache(); $filtered_date = $filter->filter($date); -is ($filtered_date,'21/05/1973', "metric conversion") or diag ("metric conversion fails $filtered_date"); +is( $filtered_date, '21/05/1973', "metric conversion" ) or diag("metric conversion fails $filtered_date"); $module_context->mock( 'tz', @@ -50,10 +50,13 @@ $module_context->mock( $filtered_date = $filter->filter('1979-04-01'); is( $filtered_date, '01/04/1979', 'us: dt_from_string should return the valid date if a dst is given' ); -$filtered_date = $filter->filter('1979-04-01', undef, { dateformat => 'iso' } ); +$filtered_date = $filter->filter( '1979-04-01', undef, { dateformat => 'iso' } ); is( $filtered_date, '1979-04-01', 'date should be returned in ISO if dateformat is passed with a value of iso' ); -is( Koha::DateUtils::output_pref( dt_from_string ), $filter->output_preference( dt_from_string ), 'Filter output_preference method output matches output_pref' ); +is( + Koha::DateUtils::output_pref(dt_from_string), $filter->output_preference(dt_from_string), + 'Filter output_preference method output matches output_pref' +); $module_context->mock( 'tz', diff --git a/t/db_dependent/Templates.t b/t/db_dependent/Templates.t index ebab637078..2c38b45e3d 100755 --- a/t/db_dependent/Templates.t +++ b/t/db_dependent/Templates.t @@ -30,18 +30,21 @@ use t::lib::Mocks; use C4::Auth qw( get_template_and_user ); BEGIN { - use_ok('C4::Templates', qw( getlanguagecookie setlanguagecookie themelanguage gettemplate param output availablethemes badtemplatecheck )); + use_ok( + 'C4::Templates', + qw( getlanguagecookie setlanguagecookie themelanguage gettemplate param output availablethemes badtemplatecheck ) + ); can_ok( 'C4::Templates', qw( - getlanguagecookie - setlanguagecookie - themelanguage - gettemplate - _get_template_file - param - output - ) + getlanguagecookie + setlanguagecookie + themelanguage + gettemplate + _get_template_file + param + output + ) ); } @@ -57,38 +60,38 @@ subtest 'Testing themelanguage' => sub { } ); - my $cgi = CGI->new(); - my $htdocs = C4::Context->config('intrahtdocs'); + my $cgi = CGI->new(); + my $htdocs = C4::Context->config('intrahtdocs'); my $section = 'intranet'; t::lib::Mocks::mock_preference( 'template', 'prog' ); # trigger first case. $testing_language = 'en'; - my ($theme, $lang, $availablethemes) = C4::Templates::themelanguage( $htdocs, 'about.tt', $section, $cgi); - is($theme,'prog',"Expected theme: set en - $theme"); - is($lang,'en','Expected language: set en'); - cmp_deeply( $availablethemes, [ 'prog' ], 'We only expect one available theme for set en' ); + my ( $theme, $lang, $availablethemes ) = C4::Templates::themelanguage( $htdocs, 'about.tt', $section, $cgi ); + is( $theme, 'prog', "Expected theme: set en - $theme" ); + is( $lang, 'en', 'Expected language: set en' ); + cmp_deeply( $availablethemes, ['prog'], 'We only expect one available theme for set en' ); # trigger second case. $testing_language = q{}; - ($theme, $lang, $availablethemes) = C4::Templates::themelanguage($htdocs, 'about.tt', $section, $cgi); - is($theme,'prog',"Expected theme: default en - $theme"); - is($lang,'en','Expected language: default en'); - cmp_deeply( $availablethemes, [ 'prog' ], 'We only expect one available theme for default en' ); + ( $theme, $lang, $availablethemes ) = C4::Templates::themelanguage( $htdocs, 'about.tt', $section, $cgi ); + is( $theme, 'prog', "Expected theme: default en - $theme" ); + is( $lang, 'en', 'Expected language: default en' ); + cmp_deeply( $availablethemes, ['prog'], 'We only expect one available theme for default en' ); # trigger third case. my $template = $htdocs . '/prog/en/modules/about.tt'; - ($theme, $lang, $availablethemes) = C4::Templates::themelanguage($htdocs, $template, $section, $cgi); - is($theme,'prog',"Expected defined theme: unset - $theme"); - is($lang,q{},'Expected language: unset'); - cmp_deeply( $availablethemes, [ 'prog' ], 'We only expect one available theme for unset' ); + ( $theme, $lang, $availablethemes ) = C4::Templates::themelanguage( $htdocs, $template, $section, $cgi ); + is( $theme, 'prog', "Expected defined theme: unset - $theme" ); + is( $lang, q{}, 'Expected language: unset' ); + cmp_deeply( $availablethemes, ['prog'], 'We only expect one available theme for unset' ); # trigger bad case. $template = $htdocs . '/prog/en/kaboom/about.tt'; - ($theme, $lang, $availablethemes) = C4::Templates::themelanguage($htdocs, $template, $section, $cgi); - is($lang,undef,'Expected language: not coded for'); + ( $theme, $lang, $availablethemes ) = C4::Templates::themelanguage( $htdocs, $template, $section, $cgi ); + is( $lang, undef, 'Expected language: not coded for' ); is( $availablethemes, undef, 'We do not expect any available themes -- not coded for' ); - is($theme,undef,"Expected no theme: not coded for"); + is( $theme, undef, "Expected no theme: not coded for" ); return; }; @@ -98,24 +101,54 @@ subtest 'Testing gettemplate/badtemplatecheck' => sub { my $cgi = CGI->new; my $template; - warning_like { eval { $template = C4::Templates::gettemplate( '/etc/passwd', 'opac', $cgi ) }; warn $@ if $@; } qr/bad template/, 'Bad template check'; - is( $template ? $template->output: '', '', 'Check output' ); + warning_like { + eval { $template = C4::Templates::gettemplate( '/etc/passwd', 'opac', $cgi ) }; + warn $@ if $@; + } + qr/bad template/, 'Bad template check'; + is( $template ? $template->output : '', '', 'Check output' ); # Test a few more bad paths to gettemplate triggering badtemplatecheck - warning_like { eval { C4::Templates::gettemplate( '../topsecret.tt', 'opac', $cgi ) }; warn $@ if $@; } qr/bad template/, 'No safe chars'; - warning_like { eval { C4::Templates::gettemplate( '/noaccess/topsecret.tt', 'opac', $cgi ) }; warn $@ if $@; } qr/bad template/, 'Directory not allowed'; - warning_like { eval { C4::Templates::gettemplate( C4::Context->config('intrahtdocs') . '2/prog/en/modules/about.tt', 'intranet', $cgi ) }; warn $@ if $@; } qr/bad template/, 'Directory not allowed too'; + warning_like { + eval { C4::Templates::gettemplate( '../topsecret.tt', 'opac', $cgi ) }; + warn $@ if $@; + } + qr/bad template/, 'No safe chars'; + warning_like { + eval { C4::Templates::gettemplate( '/noaccess/topsecret.tt', 'opac', $cgi ) }; + warn $@ if $@; + } + qr/bad template/, 'Directory not allowed'; + warning_like { + eval { + C4::Templates::gettemplate( + C4::Context->config('intrahtdocs') . '2/prog/en/modules/about.tt', 'intranet', + $cgi + ); + }; + warn $@ if $@; + } + qr/bad template/, 'Directory not allowed too'; # Allow templates from /tmp - t::lib::Mocks::mock_config( 'pluginsdir', [ '/tmp' ] ); - warning_like { eval { C4::Templates::badtemplatecheck( '/tmp/about.tt' ) }; warn $@ if $@; } undef, 'No warn on template from plugin dir'; + t::lib::Mocks::mock_config( 'pluginsdir', ['/tmp'] ); + warning_like { + eval { C4::Templates::badtemplatecheck('/tmp/about.tt') }; + warn $@ if $@; + } + undef, 'No warn on template from plugin dir'; + # Refuse wrong extension - warning_like { eval { C4::Templates::badtemplatecheck( '/tmp/about.tmpl' ) }; warn $@ if $@; } qr/bad template/, 'Warn on bad extension'; + warning_like { + eval { C4::Templates::badtemplatecheck('/tmp/about.tmpl') }; + warn $@ if $@; + } + qr/bad template/, 'Warn on bad extension'; # Make sure badtemplatecheck works on a copy of pluginsdir and doesn't modify its values t::lib::Mocks::mock_config( 'pluginsdir', [ '/tmp', '/tmp2' ] ); C4::Templates::badtemplatecheck('/tmp/test.tt'); - cmp_deeply( C4::Context->config('pluginsdir'), ['/tmp', '/tmp2'], "Doesn't modify configuration values" ); + cmp_deeply( C4::Context->config('pluginsdir'), [ '/tmp', '/tmp2' ], "Doesn't modify configuration values" ); }; @@ -125,17 +158,19 @@ subtest "Absolute path change in _get_template_file" => sub { # We create a simple template in /tmp. # We simulate an anonymous OPAC session; the OPACBaseURL template variable # should be filled by get_template_and_user. - t::lib::Mocks::mock_config( 'pluginsdir', [ C4::Context::temporary_directory ] ); + t::lib::Mocks::mock_config( 'pluginsdir', [C4::Context::temporary_directory] ); t::lib::Mocks::mock_preference( 'OPACBaseURL', 'without any doubt' ); my ( $fh, $fn ) = tempfile( SUFFIX => '.tt', UNLINK => 1, DIR => C4::Context::temporary_directory ); print $fh q|I am a [% quality %] template [% OPACBaseURL %]|; close $fh; - my ( $template, $login, $cookie ) = C4::Auth::get_template_and_user({ - template_name => $fn, - query => CGI::new, - type => "opac", - authnotrequired => 1, - }); + my ( $template, $login, $cookie ) = C4::Auth::get_template_and_user( + { + template_name => $fn, + query => CGI::new, + type => "opac", + authnotrequired => 1, + } + ); $template->param( quality => 'good-for-nothing' ); like( $template->output, qr/a good.+template.+doubt/, 'Testing a template with an absolute path' ); }; diff --git a/t/db_dependent/TestBuilder.t b/t/db_dependent/TestBuilder.t index 9946df3174..cf2d85caf8 100755 --- a/t/db_dependent/TestBuilder.t +++ b/t/db_dependent/TestBuilder.t @@ -46,28 +46,32 @@ subtest 'Start with some trivial tests' => sub { my $data; warning_like { $data = $builder->build; } qr/.+/, 'Catch a warning'; - is( $data, undef, 'build without arguments returns undef' ); - is( ref( $builder->schema ), 'Koha::Schema', 'check schema' ); - is( ref( $builder->can('delete') ), 'CODE', 'found delete method' ); + is( $data, undef, 'build without arguments returns undef' ); + is( ref( $builder->schema ), 'Koha::Schema', 'check schema' ); + is( ref( $builder->can('delete') ), 'CODE', 'found delete method' ); # invalid argument - warning_like { $builder->build({ - source => 'Borrower', - value => { surname => { invalid_hash => 1 } }, - }) } qr/^Hash not allowed for surname/, + warning_like { + $builder->build( + { + source => 'Borrower', + value => { surname => { invalid_hash => 1 } }, + } + ) + } + qr/^Hash not allowed for surname/, 'Build should not accept a hash for this column'; # return undef if a record exists - my $branchcode = $builder->build({ source => 'Branch' })->{branchcode}; - my $param = { source => 'Branch', value => { branchcode => $branchcode } }; - warning_like { $builder->build( $param ) } - qr/Violation of unique constraint/, + my $branchcode = $builder->build( { source => 'Branch' } )->{branchcode}; + my $param = { source => 'Branch', value => { branchcode => $branchcode } }; + warning_like { $builder->build($param) } + qr/Violation of unique constraint/, 'Catch warn on adding existing record'; $schema->storage->txn_rollback; }; - subtest 'Build all sources' => sub { plan tests => 1; @@ -75,44 +79,51 @@ subtest 'Build all sources' => sub { my @sources = $builder->schema->sources; my @source_in_failure; - for my $source ( @sources ) { + for my $source (@sources) { my $res; + # Skip the source if it is a view next if $schema->source($source)->isa('DBIx::Class::ResultSource::View'); eval { $res = $builder->build( { source => $source } ); }; - push @source_in_failure, $source if $@ || !defined( $res ); + push @source_in_failure, $source if $@ || !defined($res); } - is( @source_in_failure, 0, - 'TestBuilder should be able to create an object for every source' ); - if ( @source_in_failure ) { - diag( "The following sources have not been generated correctly: " . - join ', ', @source_in_failure ); + is( + @source_in_failure, 0, + 'TestBuilder should be able to create an object for every source' + ); + if (@source_in_failure) { + diag( "The following sources have not been generated correctly: " . join ', ', @source_in_failure ); } $schema->storage->txn_rollback; }; - subtest 'Test length of some generated fields' => sub { plan tests => 3; $schema->storage->txn_begin; # Test the length of a returned character field - my $bookseller = $builder->build({ source => 'Aqbookseller' }); - my $max = $schema->source('Aqbookseller')->column_info('phone')->{size}; - is( length( $bookseller->{phone} ) > 0, 1, - 'The length for a generated string (phone) should not be zero' ); - is( length( $bookseller->{phone} ) <= $max, 1, - 'Check maximum length for a generated string (phone)' ); + my $bookseller = $builder->build( { source => 'Aqbookseller' } ); + my $max = $schema->source('Aqbookseller')->column_info('phone')->{size}; + is( + length( $bookseller->{phone} ) > 0, 1, + 'The length for a generated string (phone) should not be zero' + ); + is( + length( $bookseller->{phone} ) <= $max, 1, + 'Check maximum length for a generated string (phone)' + ); - my $item = $builder->build({ source => 'Item' }); - is( $item->{replacementprice}, sprintf("%.2f", $item->{replacementprice}), "The number of decimals for floats should not be more than 2" ); + my $item = $builder->build( { source => 'Item' } ); + is( + $item->{replacementprice}, sprintf( "%.2f", $item->{replacementprice} ), + "The number of decimals for floats should not be more than 2" + ); $schema->storage->txn_rollback; }; - subtest 'Test FKs in overduerules_transport_type' => sub { plan tests => 5; @@ -128,10 +139,12 @@ subtest 'Test FKs in overduerules_transport_type' => sub { }, }; - my $overduerules_transport_type = $builder->build({ - source => 'OverduerulesTransportType', - value => $my_overduerules_transport_type, - }); + my $overduerules_transport_type = $builder->build( + { + source => 'OverduerulesTransportType', + value => $my_overduerules_transport_type, + } + ); is( $overduerules_transport_type->{message_transport_type}, $my_overduerules_transport_type->{message_transport_type}->{message_transport_type}, @@ -148,7 +161,8 @@ subtest 'Test FKs in overduerules_transport_type' => sub { 'build stores the categorycode correctly' ); is( - $schema->resultset('MessageTransportType')->find( $overduerules_transport_type->{message_transport_type} )->message_transport_type, + $schema->resultset('MessageTransportType')->find( $overduerules_transport_type->{message_transport_type} ) + ->message_transport_type, $overduerules_transport_type->{message_transport_type}, 'build stores the foreign key message_transport_type correctly' ); @@ -161,17 +175,18 @@ subtest 'Test FKs in overduerules_transport_type' => sub { $schema->storage->txn_rollback; }; - subtest 'Tests with composite FK in userpermission' => sub { plan tests => 9; $schema->storage->txn_begin; my $my_user_permission = default_userpermission(); - my $user_permission = $builder->build({ - source => 'UserPermission', - value => $my_user_permission, - }); + my $user_permission = $builder->build( + { + source => 'UserPermission', + value => $my_user_permission, + } + ); # Checks on top level of userpermission isnt( @@ -186,7 +201,7 @@ subtest 'Tests with composite FK in userpermission' => sub { ); # Checks one level deeper userpermission -> borrower - my $patron = $schema->resultset('Borrower')->find({ borrowernumber => $user_permission->{borrowernumber} }); + my $patron = $schema->resultset('Borrower')->find( { borrowernumber => $user_permission->{borrowernumber} } ); is( $patron->surname, $my_user_permission->{borrowernumber}->{surname}, @@ -199,7 +214,7 @@ subtest 'Tests with composite FK in userpermission' => sub { ); # Checks two levels deeper userpermission -> borrower -> branch - my $branch = $schema->resultset('Branch')->find({ branchcode => $patron->branchcode->branchcode }); + my $branch = $schema->resultset('Branch')->find( { branchcode => $patron->branchcode->branchcode } ); is( $branch->branchname, $my_user_permission->{borrowernumber}->{branchcode}->{branchname}, @@ -212,7 +227,8 @@ subtest 'Tests with composite FK in userpermission' => sub { ); # Checks with composite FK: userpermission -> permission - my $perm = $schema->resultset('Permission')->find({ module_bit => $user_permission->{module_bit}, code => $my_user_permission->{code}->{code} }); + my $perm = $schema->resultset('Permission') + ->find( { module_bit => $user_permission->{module_bit}, code => $my_user_permission->{code}->{code} } ); isnt( $perm, undef, 'build generated record for composite FK' ); is( $perm->code, @@ -231,9 +247,9 @@ subtest 'Tests with composite FK in userpermission' => sub { sub default_userpermission { return { borrowernumber => { - surname => 'my surname', - address => 'my adress', - city => 'my city', + surname => 'my surname', + address => 'my adress', + city => 'my city', branchcode => { branchname => 'my branchname', }, @@ -246,7 +262,7 @@ sub default_userpermission { }, module_bit => { module_bit => { - flag => 'my flag', + flag => 'my flag', }, }, code => { @@ -256,74 +272,99 @@ sub default_userpermission { }; } - subtest 'Test build with NULL values' => sub { plan tests => 3; $schema->storage->txn_begin; # PK should not be null - my $params = { source => 'Branch', value => { branchcode => undef }}; - warning_like { $builder->build( $params ) } - qr/Null value for branchcode/, + my $params = { source => 'Branch', value => { branchcode => undef } }; + warning_like { $builder->build($params) } + qr/Null value for branchcode/, 'Catch warn on adding branch with a null branchcode'; + # Nullable column - my $info = $schema->source( 'Item' )->column_info( 'barcode' ); - $params = { source => 'Item', value => { barcode => undef }}; - my $item = $builder->build( $params ); - is( $info->{is_nullable} && $item && !defined( $item->{barcode} ), 1, - 'Barcode can be NULL' ); + my $info = $schema->source('Item')->column_info('barcode'); + $params = { source => 'Item', value => { barcode => undef } }; + my $item = $builder->build($params); + is( + $info->{is_nullable} && $item && !defined( $item->{barcode} ), 1, + 'Barcode can be NULL' + ); + # Nullable FK - $params = { source => 'Reserve', value => { itemnumber => undef }}; - my $reserve = $builder->build( $params ); - $info = $schema->source( 'Reserve' )->column_info( 'itemnumber' ); - is( $reserve && $info->{is_nullable} && $info->{is_foreign_key} && - !defined( $reserve->{itemnumber} ), 1, 'Nullable FK' ); + $params = { source => 'Reserve', value => { itemnumber => undef } }; + my $reserve = $builder->build($params); + $info = $schema->source('Reserve')->column_info('itemnumber'); + is( + $reserve && $info->{is_nullable} && $info->{is_foreign_key} && !defined( $reserve->{itemnumber} ), 1, + 'Nullable FK' + ); $schema->storage->txn_rollback; }; - subtest 'Tests for delete method' => sub { plan tests => 11; $schema->storage->txn_begin; # Test delete with single and multiple records - my $basket1 = $builder->build({ source => 'Aqbasket' }); - my $basket2 = $builder->build({ source => 'Aqbasket' }); - my $basket3 = $builder->build({ source => 'Aqbasket' }); + my $basket1 = $builder->build( { source => 'Aqbasket' } ); + my $basket2 = $builder->build( { source => 'Aqbasket' } ); + my $basket3 = $builder->build( { source => 'Aqbasket' } ); my ( $id1, $id2 ) = ( $basket1->{basketno}, $basket2->{basketno} ); - $builder->delete({ source => 'Aqbasket', records => $basket1 }); + $builder->delete( { source => 'Aqbasket', records => $basket1 } ); isnt( exists $basket1->{basketno}, 1, 'Delete cleared PK hash value' ); - is( $builder->schema->resultset('Aqbasket')->search({ basketno => $id1 })->count, 0, 'Basket1 is no longer found' ); - is( $builder->schema->resultset('Aqbasket')->search({ basketno => $id2 })->count, 1, 'Basket2 is still found' ); - is( $builder->delete({ source => 'Aqbasket', records => [ $basket2, $basket3 ] }), 2, "Returned two delete attempts" ); - is( $builder->schema->resultset('Aqbasket')->search({ basketno => $id2 })->count, 0, 'Basket2 is no longer found' ); - + is( + $builder->schema->resultset('Aqbasket')->search( { basketno => $id1 } )->count, 0, + 'Basket1 is no longer found' + ); + is( $builder->schema->resultset('Aqbasket')->search( { basketno => $id2 } )->count, 1, 'Basket2 is still found' ); + is( + $builder->delete( { source => 'Aqbasket', records => [ $basket2, $basket3 ] } ), 2, + "Returned two delete attempts" + ); + is( + $builder->schema->resultset('Aqbasket')->search( { basketno => $id2 } )->count, 0, + 'Basket2 is no longer found' + ); # Test delete in table without primary key (..) - is( $schema->source('AccountCreditTypesBranch')->primary_columns, 0, - 'Table without primary key detected' ); + is( + $schema->source('AccountCreditTypesBranch')->primary_columns, 0, + 'Table without primary key detected' + ); my $cnt1 = $schema->resultset('AccountCreditTypesBranch')->count; + # Insert a new record in AccountCreditTypesBranch with that biblionumber - my $rec = $builder->build({ source => 'AccountCreditTypesBranch' }); + my $rec = $builder->build( { source => 'AccountCreditTypesBranch' } ); my $cnt2 = $schema->resultset('AccountCreditTypesBranch')->count; - is( defined($rec) && $cnt2 == $cnt1 + 1 , 1, 'Created a record' ); - is( $builder->delete({ source => 'AccountCreditTypesBranch', records => $rec }), - undef, 'delete returns undef' ); - is( $schema->resultset('AccountCreditTypesBranch')->count, $cnt2, - "Method did not delete record in table without PK" ); + is( defined($rec) && $cnt2 == $cnt1 + 1, 1, 'Created a record' ); + is( + $builder->delete( { source => 'AccountCreditTypesBranch', records => $rec } ), + undef, 'delete returns undef' + ); + is( + $schema->resultset('AccountCreditTypesBranch')->count, $cnt2, + "Method did not delete record in table without PK" + ); # Test delete with NULL values my $val = { branchcode => undef }; - is( $builder->delete({ source => 'Branch', records => $val }), 0, - 'delete returns zero for an undef search with one key' ); - $val = { module_bit => 1, #catalogue - code => undef }; - is( $builder->delete({ source => 'Permission', records => $val }), 0, - 'delete returns zero for an undef search with a composite PK' ); + is( + $builder->delete( { source => 'Branch', records => $val } ), 0, + 'delete returns zero for an undef search with one key' + ); + $val = { + module_bit => 1, #catalogue + code => undef + }; + is( + $builder->delete( { source => 'Permission', records => $val } ), 0, + 'delete returns zero for an undef search with a composite PK' + ); $schema->storage->txn_rollback; }; @@ -334,27 +375,35 @@ subtest 'Auto-increment values tests' => sub { $schema->storage->txn_begin; # Pick a table with AI PK - my $source = 'Biblio'; # table - my $column = 'biblionumber'; # ai column + my $source = 'Biblio'; # table + my $column = 'biblionumber'; # ai column - my $col_info = $schema->source( $source )->column_info( $column ); - is( $col_info->{is_auto_increment}, 1, "biblio.biblionumber is detected as autoincrement"); + my $col_info = $schema->source($source)->column_info($column); + is( $col_info->{is_auto_increment}, 1, "biblio.biblionumber is detected as autoincrement" ); # Create a biblio - my $biblio_1 = $builder->build({ source => $source }); + my $biblio_1 = $builder->build( { source => $source } ); + # Get the AI value - my $ai_value = $biblio_1->{ biblionumber }; + my $ai_value = $biblio_1->{biblionumber}; + # Create a biblio - my $biblio_2 = $builder->build({ source => $source }); + my $biblio_2 = $builder->build( { source => $source } ); + # Get the next AI value - my $next_ai_value = $biblio_2->{ biblionumber }; - is( $ai_value + 1, $next_ai_value, "AI values are consecutive"); + my $next_ai_value = $biblio_2->{biblionumber}; + is( $ai_value + 1, $next_ai_value, "AI values are consecutive" ); # respect autoincr column - warning_like { $builder->build({ - source => $source, - value => { biblionumber => 123 }, - }) } qr/^Value not allowed for auto_incr/, + warning_like { + $builder->build( + { + source => $source, + value => { biblionumber => 123 }, + } + ) + } + qr/^Value not allowed for auto_incr/, 'Build should not overwrite an auto_incr column'; $schema->storage->txn_rollback; @@ -387,11 +436,13 @@ subtest 'Default values' => sub { subtest 'generated dynamically (coderef)' => sub { plan tests => 2; - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); like( $patron->category->category_type, qr{^(A|C|S|I|P|)$}, ); - my $patron_category_X = $builder->build_object({ class => 'Koha::Patron::Categories', value => { category_type => 'X' } }); - $patron = $builder->build_object({ class => 'Koha::Patrons', value => {categorycode => $patron_category_X->categorycode} }); + my $patron_category_X = + $builder->build_object( { class => 'Koha::Patron::Categories', value => { category_type => 'X' } } ); + $patron = $builder->build_object( + { class => 'Koha::Patrons', value => { categorycode => $patron_category_X->categorycode } } ); is( $patron->category->category_type, 'X', ); }; @@ -406,12 +457,13 @@ subtest 'build_object() tests' => sub { $builder = t::lib::TestBuilder->new(); - my $branchcode = $builder->build( { source => 'Branch' } )->{branchcode}; + my $branchcode = $builder->build( { source => 'Branch' } )->{branchcode}; my $categorycode = $builder->build( { source => 'Category' } )->{categorycode}; - my $itemtype = $builder->build( { source => 'Itemtype' } )->{itemtype}; + my $itemtype = $builder->build( { source => 'Itemtype' } )->{itemtype}; my $issuing_rule = $builder->build_object( - { class => 'Koha::CirculationRules', + { + class => 'Koha::CirculationRules', value => { branchcode => $branchcode, categorycode => $categorycode, @@ -421,15 +473,17 @@ subtest 'build_object() tests' => sub { ); is( ref($issuing_rule), 'Koha::CirculationRule', 'Type is correct' ); - is( $issuing_rule->categorycode, - $categorycode, 'Category code correctly set' ); + is( + $issuing_rule->categorycode, + $categorycode, 'Category code correctly set' + ); is( $issuing_rule->itemtype, $itemtype, 'Item type correctly set' ); subtest 'Test all classes' => sub { - my $Koha_modules_dir = dirname(__FILE__) . '/../../Koha'; + my $Koha_modules_dir = dirname(__FILE__) . '/../../Koha'; my @koha_object_based_modules = `/bin/grep -rl -e '^sub object_class' $Koha_modules_dir`; my @source_in_failure; - for my $module_filepath ( @koha_object_based_modules ) { + for my $module_filepath (@koha_object_based_modules) { chomp $module_filepath; next unless $module_filepath =~ m|\.pm$|; my $module = $module_filepath; @@ -439,18 +493,20 @@ subtest 'build_object() tests' => sub { eval "require $module"; my $object = $builder->build_object( { class => $module } ); is( ref($object), $module->object_class, "Testing $module" ); - if ( ! grep {$module eq $_ } qw( Koha::Old::Patrons Koha::Statistics ) ) { # FIXME deletedborrowers and statistics do not have a PK - eval {$object->get_from_storage}; + + if ( !grep { $module eq $_ } qw( Koha::Old::Patrons Koha::Statistics ) ) + { # FIXME deletedborrowers and statistics do not have a PK + eval { $object->get_from_storage }; is( $@, '', "Module $module should have koha_object[s]_class method if needed" ); } # Testing koha_object_class and koha_objects_class - my $object_class = Koha::Object::_get_object_class($object->_result->result_class); + my $object_class = Koha::Object::_get_object_class( $object->_result->result_class ); eval "require $object_class"; - is( $@, '', "Module $object_class should be defined"); - my $objects_class = Koha::Objects::_get_objects_class($object->_result->result_class); + is( $@, '', "Module $object_class should be defined" ); + my $objects_class = Koha::Objects::_get_objects_class( $object->_result->result_class ); eval "require $objects_class"; - is( $@, '', "Module $objects_class should be defined"); + is( $@, '', "Module $objects_class should be defined" ); } }; @@ -460,13 +516,15 @@ subtest 'build_object() tests' => sub { warning_is { $issuing_rule = $builder->build_object( {} ); } { carped => 'Missing class param' }, 'The class parameter is mandatory, raises a warning if absent'; - is( $issuing_rule, undef, - 'If the class parameter is missing, undef is returned' ); + is( + $issuing_rule, undef, + 'If the class parameter is missing, undef is returned' + ); warnings_like { - $builder->build_object( - { class => 'Koha::Patrons', categorycode => 'foobar' } ); - } qr{Unknown parameter\(s\): categorycode}, "Unknown parameter detected"; + $builder->build_object( { class => 'Koha::Patrons', categorycode => 'foobar' } ); + } + qr{Unknown parameter\(s\): categorycode}, "Unknown parameter detected"; }; $schema->storage->txn_rollback; @@ -479,31 +537,38 @@ subtest '->build parameter' => sub { # Test to make sure build() warns user of unknown parameters. warnings_are { - $builder->build({ - source => 'Branch', - value => { - branchcode => 'BRANCH_1' + $builder->build( + { + source => 'Branch', + value => { branchcode => 'BRANCH_1' } } - }) - } [], "No warnings on correct use"; - - warnings_like { - $builder->build({ - source => 'Branch', - branchcode => 'BRANCH_2' # This is wrong! - }) - } qr/unknown param/i, "Carp unknown parameters"; - - warnings_like { - $builder->build({ - zource => 'Branch', # Intentional spelling error - }) - } qr/Source parameter not specified/, "Catch warning on missing source"; + ) + } + [], "No warnings on correct use"; warnings_like { $builder->build( - { source => 'Borrower', categorycode => 'foobar' } ); - } qr{Unknown parameter\(s\): categorycode}, "Unkown parameter detected"; + { + source => 'Branch', + branchcode => 'BRANCH_2' # This is wrong! + } + ) + } + qr/unknown param/i, "Carp unknown parameters"; + + warnings_like { + $builder->build( + { + zource => 'Branch', # Intentional spelling error + } + ) + } + qr/Source parameter not specified/, "Catch warning on missing source"; + + warnings_like { + $builder->build( { source => 'Borrower', categorycode => 'foobar' } ); + } + qr{Unknown parameter\(s\): categorycode}, "Unkown parameter detected"; $schema->storage->txn_rollback; }; @@ -514,9 +579,8 @@ subtest 'build_sample_biblio() tests' => sub { $schema->storage->txn_begin; - warnings_are - { $builder->build_sample_biblio({ title => 'hell❤️' }); } - [], + warnings_are { $builder->build_sample_biblio( { title => 'hell❤️' } ); } + [], "No encoding warnings!"; $schema->storage->txn_rollback; @@ -529,16 +593,17 @@ subtest 'Existence of object is only checked using primary keys' => sub { $schema->storage->txn_begin; my $biblio = $builder->build_sample_biblio(); - my $item1 = $builder->build_sample_item({ biblionumber => $biblio->biblionumber }); - my $item2 = $builder->build_sample_item({ biblionumber => $biblio->biblionumber }); + my $item1 = $builder->build_sample_item( { biblionumber => $biblio->biblionumber } ); + my $item2 = $builder->build_sample_item( { biblionumber => $biblio->biblionumber } ); warnings_are { - $builder->build_object({ - class => 'Koha::Holds', - value => { - biblionumber => $biblio->biblionumber - } - }); - } [], "No warning about query returning more than one row"; + $builder->build_object( + { + class => 'Koha::Holds', + value => { biblionumber => $biblio->biblionumber } + } + ); + } + [], "No warning about query returning more than one row"; $schema->storage->txn_rollback; }; @@ -548,27 +613,27 @@ subtest 'Test bad columns' => sub { $schema->storage->txn_begin; try { - my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { wrong => 1 } }); + my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { wrong => 1 } } ); ok( 0, 'Unexpected pass with wrong column' ); - } - catch { + } catch { like( $_, qr/^Error: value hash contains unrecognized columns: wrong/, 'Column wrong is bad' ); }; try { - my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { surname => 'Pass', nested => { ignored => 1 }} }); + my $patron = $builder->build_object( + { class => 'Koha::Patrons', value => { surname => 'Pass', nested => { ignored => 1 } } } ); ok( 1, 'Nested hash ignored' ); - } - catch { + } catch { ok( 0, 'Unexpected trouble with nested hash' ); }; try { - my $patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { surname => 'WontPass', categorycode => { description => 'bla', wrong_nested => 1 }}, - }); + my $patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { surname => 'WontPass', categorycode => { description => 'bla', wrong_nested => 1 } }, + } + ); ok( 0, 'Unexpected pass with wrong nested column' ); - } - catch { + } catch { like( $_, qr/^Error: value hash contains unrecognized columns: wrong_nested/, 'Column wrong_nested is bad' ); }; diff --git a/t/db_dependent/Upload.t b/t/db_dependent/Upload.t index 8b3fa3c1f0..2b57781764 100755 --- a/t/db_dependent/Upload.t +++ b/t/db_dependent/Upload.t @@ -16,12 +16,12 @@ use Koha::DateUtils qw( dt_from_string ); use Koha::UploadedFiles; use Koha::Uploader; -my $schema = Koha::Database->new->schema; +my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; our $builder = t::lib::TestBuilder->new; our $current_upload = 0; -our $uploads = [ +our $uploads = [ [ { name => 'file1', cat => 'A', size => 6000 }, { name => 'file2', cat => 'A', size => 8000 }, @@ -30,14 +30,15 @@ our $uploads = [ { name => 'file3', cat => 'B', size => 1000 }, ], [ - { name => 'file4', cat => undef, size => 5000 }, # temporary + { name => 'file4', cat => undef, size => 5000 }, # temporary ], [ { name => 'file2', cat => 'A', size => 8000 }, + # uploading a duplicate in cat A should fail ], [ - { name => 'file4', cat => undef, size => 5000 }, # temp duplicate + { name => 'file4', cat => undef, size => 5000 }, # temp duplicate ], [ { name => 'file5', cat => undef, size => 7000 }, @@ -50,10 +51,10 @@ our $uploads = [ # Redirect upload dir structure and mock C4::Context and CGI my $tempdir = tempdir( CLEANUP => 1 ); -t::lib::Mocks::mock_config('upload_path', $tempdir); -my $specmod = Test::MockModule->new( 'C4::Context' ); +t::lib::Mocks::mock_config( 'upload_path', $tempdir ); +my $specmod = Test::MockModule->new('C4::Context'); $specmod->mock( 'temporary_directory' => sub { return $tempdir; } ); -my $cgimod = Test::MockModule->new( 'CGI' ); +my $cgimod = Test::MockModule->new('CGI'); $cgimod->mock( 'new' => \&newCGI ); # Start testing @@ -64,7 +65,7 @@ subtest 'Make a fresh start' => sub { # Passing keep_file suppresses warnings (and does not delete files) # Note that your files are not in danger, since we redirected # all files to a new empty temp folder - Koha::UploadedFiles->delete({ keep_file => 1 }); + Koha::UploadedFiles->delete( { keep_file => 1 } ); is( Koha::UploadedFiles->count, 0, 'No records left' ); }; @@ -72,64 +73,70 @@ subtest 'permanent_directory and temporary_directory' => sub { plan tests => 2; # Check mocked directories - is( Koha::UploadedFile->permanent_directory, $tempdir, - 'Check permanent directory' ); - is( C4::Context::temporary_directory, $tempdir, - 'Check temporary directory' ); + is( + Koha::UploadedFile->permanent_directory, $tempdir, + 'Check permanent directory' + ); + is( + C4::Context::temporary_directory, $tempdir, + 'Check temporary directory' + ); }; subtest 'Add two uploads in category A' => sub { plan tests => 9; - my $upl = Koha::Uploader->new({ - category => $uploads->[$current_upload]->[0]->{cat}, - }); - my $cgi= $upl->cgi; - my $res= $upl->result; - is( $res =~ /^\d+,\d+$/, 1, 'Upload 1 includes two files' ); - is( $upl->count, 2, 'Count returns 2 also' ); - is( $upl->err, undef, 'No errors reported' ); + my $upl = Koha::Uploader->new( + { + category => $uploads->[$current_upload]->[0]->{cat}, + } + ); + my $cgi = $upl->cgi; + my $res = $upl->result; + is( $res =~ /^\d+,\d+$/, 1, 'Upload 1 includes two files' ); + is( $upl->count, 2, 'Count returns 2 also' ); + is( $upl->err, undef, 'No errors reported' ); - my $rs = Koha::UploadedFiles->search({ - id => [ split ',', $res ] - }, { order_by => { -asc => 'filename' }}); + my $rs = Koha::UploadedFiles->search( { id => [ split ',', $res ] }, { order_by => { -asc => 'filename' } } ); my $rec = $rs->next; - is( $rec->filename, 'file1', 'Check file name' ); - is( $rec->uploadcategorycode, 'A', 'Check category A' ); - is( $rec->filesize, 6000, 'Check size of file1' ); + is( $rec->filename, 'file1', 'Check file name' ); + is( $rec->uploadcategorycode, 'A', 'Check category A' ); + is( $rec->filesize, 6000, 'Check size of file1' ); $rec = $rs->next; is( $rec->filename, 'file2', 'Check file name 2' ); - is( $rec->filesize, 8000, 'Check size of file2' ); - is( $rec->public, undef, 'Check public undefined' ); + is( $rec->filesize, 8000, 'Check size of file2' ); + is( $rec->public, undef, 'Check public undefined' ); }; subtest 'Add another upload, check file_handle' => sub { plan tests => 5; - my $upl = Koha::Uploader->new({ - category => $uploads->[$current_upload]->[0]->{cat}, - public => 1, - }); - my $cgi= $upl->cgi; + my $upl = Koha::Uploader->new( + { + category => $uploads->[$current_upload]->[0]->{cat}, + public => 1, + } + ); + my $cgi = $upl->cgi; is( $upl->count, 1, 'Upload 2 includes one file' ); - my $res= $upl->result; - my $rec = Koha::UploadedFiles->find( $res ); + my $res = $upl->result; + my $rec = Koha::UploadedFiles->find($res); is( $rec->uploadcategorycode, 'B', 'Check category B' ); - is( $rec->public, 1, 'Check public == 1' ); + is( $rec->public, 1, 'Check public == 1' ); my $fh = $rec->file_handle; is( ref($fh) eq 'IO::File' && $fh->opened, 1, 'Get returns a file handle' ); my $orgname = $rec->filename; - $rec->filename( 'doesprobablynotexist' )->store; + $rec->filename('doesprobablynotexist')->store; is( $rec->file_handle, undef, 'Sabotage with file handle' ); - $rec->filename( $orgname )->store; + $rec->filename($orgname)->store; }; subtest 'Add temporary upload' => sub { plan tests => 2; - my $upl = Koha::Uploader->new({ tmp => 1 }); #temporary - my $cgi= $upl->cgi; + my $upl = Koha::Uploader->new( { tmp => 1 } ); #temporary + my $cgi = $upl->cgi; is( $upl->count, 1, 'Upload 3 includes one temporary file' ); my $rec = Koha::UploadedFiles->find( $upl->result ); is( $rec->uploadcategorycode =~ /_upload$/, 1, 'Check category temp file' ); @@ -138,11 +145,13 @@ subtest 'Add temporary upload' => sub { subtest 'Add same file in same category' => sub { plan tests => 3; - my $upl = Koha::Uploader->new({ - category => $uploads->[$current_upload]->[0]->{cat}, - }); - my $cgi= $upl->cgi; - is( $upl->count, 0, 'Upload 4 failed as expected' ); + my $upl = Koha::Uploader->new( + { + category => $uploads->[$current_upload]->[0]->{cat}, + } + ); + my $cgi = $upl->cgi; + is( $upl->count, 0, 'Upload 4 failed as expected' ); is( $upl->result, undef, 'Result is undefined' ); my $e = $upl->err; is( $e->{file2}->{code}, Koha::Uploader::ERR_EXISTS, "Already exists error reported" ); @@ -152,43 +161,43 @@ subtest 'Test delete via UploadedFile as well as UploadedFiles' => sub { plan tests => 10; # add temporary file with same name and contents (file4) - my $upl = Koha::Uploader->new({ tmp => 1 }); - my $cgi= $upl->cgi; + my $upl = Koha::Uploader->new( { tmp => 1 } ); + my $cgi = $upl->cgi; is( $upl->count, 1, 'Add duplicate temporary file (file4)' ); - my $id = $upl->result; - my $path = Koha::UploadedFiles->find( $id )->full_path; + my $id = $upl->result; + my $path = Koha::UploadedFiles->find($id)->full_path; # testing delete via UploadedFiles (plural) - my $delete = Koha::UploadedFiles->search({ id => $id })->delete; - isnt( $delete, "0E0", 'Delete successful' ); - isnt( -e $path, 1, 'File no longer found after delete' ); - is( Koha::UploadedFiles->find( $id ), undef, 'Record also gone' ); + my $delete = Koha::UploadedFiles->search( { id => $id } )->delete; + isnt( $delete, "0E0", 'Delete successful' ); + isnt( -e $path, 1, 'File no longer found after delete' ); + is( Koha::UploadedFiles->find($id), undef, 'Record also gone' ); # testing delete via UploadedFile (singular) # Note that find returns a Koha::Object - $upl = Koha::Uploader->new({ tmp => 1 }); + $upl = Koha::Uploader->new( { tmp => 1 } ); $upl->cgi; my $kohaobj = Koha::UploadedFiles->find( $upl->result ); - $path = $kohaobj->full_path; + $path = $kohaobj->full_path; $delete = $kohaobj->delete; ok( $delete, 'Delete successful' ); isnt( -e $path, 1, 'File no longer found after delete' ); # add another record with TestBuilder, so file does not exist # catch warning (which occurs when deleting permanent file) - my $upload01 = $builder->build({ source => 'UploadedFile', value => { permanent => 1 } }); + my $upload01 = $builder->build( { source => 'UploadedFile', value => { permanent => 1 } } ); warning_like { $delete = Koha::UploadedFiles->find( $upload01->{id} )->delete; } - qr/file was missing/, + qr/file was missing/, 'delete warns when permanent file is missing'; ok( $delete, 'Deleting record was successful' ); is( Koha::UploadedFiles->count, 4, 'Back to four uploads now' ); # add another one with TestBuilder and delete twice (file does not exist) - $upload01 = $builder->build({ source => 'UploadedFile' }); - $kohaobj = Koha::UploadedFiles->find( $upload01->{id} ); - $delete = $kohaobj->delete({ keep_file => 1 }); + $upload01 = $builder->build( { source => 'UploadedFile' } ); + $kohaobj = Koha::UploadedFiles->find( $upload01->{id} ); + $delete = $kohaobj->delete( { keep_file => 1 } ); try { - $delete = $kohaobj->delete({ keep_file => 1 }); + $delete = $kohaobj->delete( { keep_file => 1 } ); } catch { ok( $_->isa("DBIx::Class::Exception"), 'Repeated delete unsuccessful' ); } @@ -198,17 +207,25 @@ subtest 'Test delete_missing' => sub { plan tests => 5; # If we add files via TestBuilder, they do not exist - my $upload01 = $builder->build({ source => 'UploadedFile' }); - my $upload02 = $builder->build({ source => 'UploadedFile' }); + my $upload01 = $builder->build( { source => 'UploadedFile' } ); + my $upload02 = $builder->build( { source => 'UploadedFile' } ); + # dry run first - my $deleted = Koha::UploadedFiles->delete_missing({ keep_record => 1 }); + my $deleted = Koha::UploadedFiles->delete_missing( { keep_record => 1 } ); is( $deleted, 2, 'Expect two records with missing files' ); isnt( Koha::UploadedFiles->find( $upload01->{id} ), undef, 'Not deleted' ); $deleted = Koha::UploadedFiles->delete_missing; ok( $deleted =~ /^(2)$/, 'Deleted two records with missing files' ); - is( Koha::UploadedFiles->search({ - id => [ $upload01->{id}, $upload02->{id} ], - })->count, 0, 'Records are gone' ); + is( + Koha::UploadedFiles->search( + { + id => [ $upload01->{id}, $upload02->{id} ], + } + )->count, + 0, + 'Records are gone' + ); + # Repeat it $deleted = Koha::UploadedFiles->delete_missing; is( $deleted, "0E0", "Return value of 0E0 expected" ); @@ -217,22 +234,33 @@ subtest 'Test delete_missing' => sub { subtest 'Call search_term with[out] private flag' => sub { plan tests => 3; - my @recs = Koha::UploadedFiles->search_term({ term => 'file' })->as_list; - is( @recs, 1, 'Returns only one public result' ); + my @recs = Koha::UploadedFiles->search_term( { term => 'file' } )->as_list; + is( @recs, 1, 'Returns only one public result' ); is( $recs[0]->filename, 'file3', 'Should be file3' ); - is( Koha::UploadedFiles->search_term({ - term => 'file', include_private => 1, - })->count, 4, 'Returns now four results' ); + is( + Koha::UploadedFiles->search_term( + { + term => 'file', include_private => 1, + } + )->count, + 4, + 'Returns now four results' + ); }; subtest 'Simple tests for httpheaders and getCategories' => sub { plan tests => 2; - my $rec = Koha::UploadedFiles->search_term({ term => 'file' })->next; + my $rec = Koha::UploadedFiles->search_term( { term => 'file' } )->next; my @hdrs = $rec->httpheaders; - is( @hdrs == 4 && $hdrs[1] =~ /application\/octet-stream/, 1, 'Simple test for httpheaders'); - $builder->build({ source => 'AuthorisedValue', value => { category => 'UPLOAD', authorised_value => 'HAVE_AT_LEAST_ONE', lib => 'Hi there' } }); + is( @hdrs == 4 && $hdrs[1] =~ /application\/octet-stream/, 1, 'Simple test for httpheaders' ); + $builder->build( + { + source => 'AuthorisedValue', + value => { category => 'UPLOAD', authorised_value => 'HAVE_AT_LEAST_ONE', lib => 'Hi there' } + } + ); my $cat = Koha::UploadedFiles->getCategories; is( @$cat >= 1, 1, 'getCategories returned at least one category' ); }; @@ -240,59 +268,73 @@ subtest 'Simple tests for httpheaders and getCategories' => sub { subtest 'Testing allows_add_by' => sub { plan tests => 4; - my $patron = $builder->build({ - source => 'Borrower', - value => { flags => 0 }, #no permissions - }); + my $patron = $builder->build( + { + source => 'Borrower', + value => { flags => 0 }, #no permissions + } + ); my $patronid = $patron->{borrowernumber}; - is( Koha::Uploader->allows_add_by( $patron->{userid} ), - undef, 'Patron is not allowed to do anything' ); + is( + Koha::Uploader->allows_add_by( $patron->{userid} ), + undef, 'Patron is not allowed to do anything' + ); # add some permissions: edit_catalogue - my $fl = 2**9; # edit_catalogue - $schema->resultset('Borrower')->find( $patronid )->update({ flags => $fl }); - is( Koha::Uploader->allows_add_by( $patron->{userid} ), - undef, 'Patron is still not allowed to add uploaded files' ); + my $fl = 2**9; # edit_catalogue + $schema->resultset('Borrower')->find($patronid)->update( { flags => $fl } ); + is( + Koha::Uploader->allows_add_by( $patron->{userid} ), + undef, 'Patron is still not allowed to add uploaded files' + ); # replace flags by all tools - $fl = 2**13; # tools - $schema->resultset('Borrower')->find( $patronid )->update({ flags => $fl }); - is( Koha::Uploader->allows_add_by( $patron->{userid} ), - 1, 'Patron should be allowed now to add uploaded files' ); + $fl = 2**13; # tools + $schema->resultset('Borrower')->find($patronid)->update( { flags => $fl } ); + is( + Koha::Uploader->allows_add_by( $patron->{userid} ), + 1, 'Patron should be allowed now to add uploaded files' + ); # remove all tools and add upload_general_files only - $fl = 0; # no modules - $schema->resultset('Borrower')->find( $patronid )->update({ flags => $fl }); - $builder->build({ - source => 'UserPermission', - value => { - borrowernumber => $patronid, - module_bit => { module_bit => { flag => 'tools' } }, - code => 'upload_general_files', - }, - }); - is( Koha::Uploader->allows_add_by( $patron->{userid} ), - 1, 'Patron is still allowed to add uploaded files' ); + $fl = 0; # no modules + $schema->resultset('Borrower')->find($patronid)->update( { flags => $fl } ); + $builder->build( + { + source => 'UserPermission', + value => { + borrowernumber => $patronid, + module_bit => { module_bit => { flag => 'tools' } }, + code => 'upload_general_files', + }, + } + ); + is( + Koha::Uploader->allows_add_by( $patron->{userid} ), + 1, 'Patron is still allowed to add uploaded files' + ); }; subtest 'Testing delete_temporary' => sub { plan tests => 9; # Add two temporary files: result should be 3 + 3 - Koha::Uploader->new({ tmp => 1 })->cgi; # add file6 and file7 + Koha::Uploader->new( { tmp => 1 } )->cgi; # add file6 and file7 is( Koha::UploadedFiles->search->count, 6, 'Test starting count' ); - is( Koha::UploadedFiles->search({ permanent => 1 })->count, 3, - 'Includes 3 permanent' ); + is( + Koha::UploadedFiles->search( { permanent => 1 } )->count, 3, + 'Includes 3 permanent' + ); # Move all permanents to today - 1 # Move temp 1 to today - 3, and temp 2,3 to today - 5 my $today = dt_from_string; - $today->subtract( minutes => 2 ); # should be enough :) + $today->subtract( minutes => 2 ); # should be enough :) my $dt = $today->clone->subtract( days => 1 ); - foreach my $rec ( Koha::UploadedFiles->search({ permanent => 1 })->as_list ) { + foreach my $rec ( Koha::UploadedFiles->search( { permanent => 1 } )->as_list ) { $rec->dtcreated($dt)->store; } - my @recs = Koha::UploadedFiles->search({ permanent => 0 })->as_list; + my @recs = Koha::UploadedFiles->search( { permanent => 0 } )->as_list; $dt = $today->clone->subtract( days => 3 ); $recs[0]->dtcreated($dt)->store; $dt = $today->clone->subtract( days => 5 ); @@ -300,35 +342,38 @@ subtest 'Testing delete_temporary' => sub { $recs[2]->dtcreated($dt)->store; # Now call delete_temporary with 6, 5 and 0 - t::lib::Mocks::mock_preference('UploadPurgeTemporaryFilesDays', 6 ); + t::lib::Mocks::mock_preference( 'UploadPurgeTemporaryFilesDays', 6 ); my $delete = Koha::UploadedFiles->delete_temporary; - is( $delete, '0E0', 'Check return value with 6' ); - is( Koha::UploadedFiles->search->count, 6, 'Delete with pref==6' ); + is( $delete, '0E0', 'Check return value with 6' ); + is( Koha::UploadedFiles->search->count, 6, 'Delete with pref==6' ); # use override parameter - $delete = Koha::UploadedFiles->delete_temporary({ override_pref => 5 }); - is( $delete, 2, 'Check return value with 5' ); + $delete = Koha::UploadedFiles->delete_temporary( { override_pref => 5 } ); + is( $delete, 2, 'Check return value with 5' ); is( Koha::UploadedFiles->search->count, 4, 'Delete with override==5' ); - t::lib::Mocks::mock_preference('UploadPurgeTemporaryFilesDays', 0 ); + t::lib::Mocks::mock_preference( 'UploadPurgeTemporaryFilesDays', 0 ); $delete = Koha::UploadedFiles->delete_temporary; - is( $delete, 1, 'Check return value with 0' ); + is( $delete, 1, 'Check return value with 0' ); is( Koha::UploadedFiles->search->count, 3, 'Delete with pref==0 makes 3' ); - is( Koha::UploadedFiles->search({ permanent => 1 })->count, 3, - 'Still 3 permanent uploads' ); + is( + Koha::UploadedFiles->search( { permanent => 1 } )->count, 3, + 'Still 3 permanent uploads' + ); }; subtest 'Testing download headers' => sub { plan tests => 2; - my $test_pdf = Koha::UploadedFile->new({ filename => 'pdf.pdf', uploadcategorycode => 'B', filesize => 1000 }); - my $test_not = Koha::UploadedFile->new({ filename => 'pdf.not', uploadcategorycode => 'B', filesize => 1000 }); - my @pdf_expect = ( '-type'=>'application/pdf','Content-Disposition'=>'inline; filename="pdf.pdf"' ); - my @not_expect = ( '-type'=>'application/octet-stream','-attachment'=>'pdf.not' ); - my @pdf_head = $test_pdf->httpheaders; - my @not_head = $test_not->httpheaders; - is_deeply(\@pdf_head, \@pdf_expect,"Get inline pdf headers for pdf"); - is_deeply(\@not_head, \@not_expect,"Get download headers for non pdf"); + my $test_pdf = Koha::UploadedFile->new( { filename => 'pdf.pdf', uploadcategorycode => 'B', filesize => 1000 } ); + my $test_not = Koha::UploadedFile->new( { filename => 'pdf.not', uploadcategorycode => 'B', filesize => 1000 } ); + my @pdf_expect = ( '-type' => 'application/pdf', 'Content-Disposition' => 'inline; filename="pdf.pdf"' ); + my @not_expect = ( '-type' => 'application/octet-stream', '-attachment' => 'pdf.not' ); + my @pdf_head = $test_pdf->httpheaders; + my @not_head = $test_not->httpheaders; + is_deeply( \@pdf_head, \@pdf_expect, "Get inline pdf headers for pdf" ); + is_deeply( \@not_head, \@not_expect, "Get download headers for non pdf" ); }; + # The end $schema->storage->txn_rollback; @@ -336,10 +381,10 @@ $schema->storage->txn_rollback; sub newCGI { my ( $class, $hook ) = @_; my $read = 0; - foreach my $uh ( @{$uploads->[ $current_upload ]} ) { - for( my $i=0; $i< $uh->{size}; $i+=1000 ) { - $read+= 1000; - &$hook( $uh->{name}, 'a'x1000, $read ); + foreach my $uh ( @{ $uploads->[$current_upload] } ) { + for ( my $i = 0 ; $i < $uh->{size} ; $i += 1000 ) { + $read += 1000; + &$hook( $uh->{name}, 'a' x 1000, $read ); } } $current_upload++; diff --git a/t/db_dependent/UsageStats.t b/t/db_dependent/UsageStats.t index 2d72af35d5..7604937acd 100755 --- a/t/db_dependent/UsageStats.t +++ b/t/db_dependent/UsageStats.t @@ -33,14 +33,14 @@ use Koha::Old::Holds; use Koha::Patrons; BEGIN { - use_ok('C4::UsageStats', qw( BuildReport ReportToCommunity _count )); + use_ok( 'C4::UsageStats', qw( BuildReport ReportToCommunity _count ) ); } can_ok( 'C4::UsageStats', qw( - BuildReport - ReportToCommunity - _count ) + BuildReport + ReportToCommunity + _count ) ); my $builder = t::lib::TestBuilder->new; @@ -104,13 +104,13 @@ subtest 'BuildReport() tests' => sub { isa_ok( $report, 'HASH', '$report is a HASH' ); isa_ok( $report->{volumetry}, 'HASH', '$report->{volumetry} is a HASH' ); - is( scalar( keys %{ $report->{volumetry} } ), 8, "There are 8 fields in 'volumetry'" ); - is( $report->{volumetry}->{biblio}, Koha::Biblios->count, "Biblios count correct" ); - is( $report->{volumetry}->{items}, Koha::Items->count, "Items count correct" ); - is( $report->{volumetry}->{auth_header}, Koha::Authorities->count, "Authorities count correct" ); - is( $report->{volumetry}->{old_issues}, Koha::Old::Checkouts->count, "Old checkouts count correct" ); - is( $report->{volumetry}->{old_reserves}, Koha::Old::Holds->count, "Old holds count correct" ); - is( $report->{volumetry}->{borrowers}, Koha::Patrons->count, "Patrons count correct" ); + is( scalar( keys %{ $report->{volumetry} } ), 8, "There are 8 fields in 'volumetry'" ); + is( $report->{volumetry}->{biblio}, Koha::Biblios->count, "Biblios count correct" ); + is( $report->{volumetry}->{items}, Koha::Items->count, "Items count correct" ); + is( $report->{volumetry}->{auth_header}, Koha::Authorities->count, "Authorities count correct" ); + is( $report->{volumetry}->{old_issues}, Koha::Old::Checkouts->count, "Old checkouts count correct" ); + is( $report->{volumetry}->{old_reserves}, Koha::Old::Holds->count, "Old holds count correct" ); + is( $report->{volumetry}->{borrowers}, Koha::Patrons->count, "Patrons count correct" ); is( $report->{volumetry}->{aqorders}, Koha::Acquisition::Orders->count, "Orders count correct" ); is( $report->{volumetry}->{subscription}, Koha::Subscriptions->count, "Suscriptions count correct" ); diff --git a/t/db_dependent/Utils/Datatables_Virtualshelves.t b/t/db_dependent/Utils/Datatables_Virtualshelves.t index de4398a7c7..e1f054e723 100755 --- a/t/db_dependent/Utils/Datatables_Virtualshelves.t +++ b/t/db_dependent/Utils/Datatables_Virtualshelves.t @@ -29,7 +29,7 @@ use Koha::Virtualshelves; use t::lib::Mocks; -use_ok( "C4::Utils::DataTables::VirtualShelves" ); +use_ok("C4::Utils::DataTables::VirtualShelves"); my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; @@ -41,11 +41,11 @@ $dbh->do(q|DELETE FROM virtualshelves|); my @categories = Koha::Patron::Categories->search_with_library_limits->as_list; my $categorycode = $categories[0]->categorycode; my $branchcode = "ABC"; -my $branch_data = { - branchcode => $branchcode, - branchname => 'my branchname', +my $branch_data = { + branchcode => $branchcode, + branchname => 'my branchname', }; -Koha::Library->new( $branch_data )->store; +Koha::Library->new($branch_data)->store; my %john_doe = ( cardnumber => '123456', @@ -60,7 +60,7 @@ my %john_doe = ( my %jane_doe = ( cardnumber => '234567', - firstname => 'Jane', + firstname => 'Jane', surname => 'Doe', categorycode => $categorycode, branchcode => $branchcode, @@ -70,7 +70,7 @@ my %jane_doe = ( ); my %john_smith = ( cardnumber => '345678', - firstname => 'John', + firstname => 'John', surname => 'Smith', categorycode => $categorycode, branchcode => $branchcode, @@ -80,8 +80,8 @@ my %john_smith = ( ); my $john_doe_patron = Koha::Patron->new( \%john_doe )->store; -$john_doe{borrowernumber} = $john_doe_patron->borrowernumber; -$jane_doe{borrowernumber} = Koha::Patron->new( \%jane_doe )->store->borrowernumber; +$john_doe{borrowernumber} = $john_doe_patron->borrowernumber; +$jane_doe{borrowernumber} = Koha::Patron->new( \%jane_doe )->store->borrowernumber; $john_smith{borrowernumber} = Koha::Patron->new( \%john_smith )->store->borrowernumber; my $shelf1 = Koha::Virtualshelf->new( @@ -139,7 +139,7 @@ my $biblionumber9 = _add_biblio('title 9'); my $biblionumber10 = _add_biblio('title 10'); my $biblionumber11 = _add_biblio('title 11'); my $biblionumber12 = _add_biblio('title 12'); -$shelf3->add_biblio( $biblionumber9, $jane_doe{borrowernumber} ); +$shelf3->add_biblio( $biblionumber9, $jane_doe{borrowernumber} ); $shelf3->add_biblio( $biblionumber10, $jane_doe{borrowernumber} ); $shelf3->add_biblio( $biblionumber11, $jane_doe{borrowernumber} ); $shelf3->add_biblio( $biblionumber12, $jane_doe{borrowernumber} ); @@ -177,81 +177,113 @@ for my $i ( 6 .. 15 ) { # Set common datatables params my %dt_params = ( - length => 10, - start => 0 + length => 10, + start => 0 ); my $search_results; -t::lib::Mocks::mock_userenv({ patron => $john_doe_patron }); +t::lib::Mocks::mock_userenv( { patron => $john_doe_patron } ); # Search private lists by title -$search_results = C4::Utils::DataTables::VirtualShelves::search({ - shelfname => "ist", - %dt_params, - public => 0, -}); +$search_results = C4::Utils::DataTables::VirtualShelves::search( + { + shelfname => "ist", + %dt_params, + public => 0, + } +); -is( $search_results->{ recordsTotal }, 2, - "There should be 2 private shelves in total" ); +is( + $search_results->{recordsTotal}, 2, + "There should be 2 private shelves in total" +); -is( $search_results->{ recordsFiltered }, 2, - "There should be 2 private shelves with title like '%ist%" ); +is( + $search_results->{recordsFiltered}, 2, + "There should be 2 private shelves with title like '%ist%" +); -is( @{ $search_results->{ shelves } }, 2, - "There should be 2 private shelves returned" ); +is( + @{ $search_results->{shelves} }, 2, + "There should be 2 private shelves returned" +); # Search by type only -$search_results = C4::Utils::DataTables::VirtualShelves::search({ - %dt_params, - public => 1, -}); -is( $search_results->{ recordsTotal }, 12, - "There should be 12 public shelves in total" ); +$search_results = C4::Utils::DataTables::VirtualShelves::search( + { + %dt_params, + public => 1, + } +); +is( + $search_results->{recordsTotal}, 12, + "There should be 12 public shelves in total" +); -is( $search_results->{ recordsFiltered }, 12, - "There should be 12 private shelves" ); +is( + $search_results->{recordsFiltered}, 12, + "There should be 12 private shelves" +); -is( @{ $search_results->{ shelves } }, 10, - "There should be 10 public shelves returned" ); +is( + @{ $search_results->{shelves} }, 10, + "There should be 10 public shelves returned" +); # Search by owner -$search_results = C4::Utils::DataTables::VirtualShelves::search({ - owner => "jane", - %dt_params, - public => 1, -}); -is( $search_results->{ recordsTotal }, 12, - "There should be 12 public shelves in total" ); +$search_results = C4::Utils::DataTables::VirtualShelves::search( + { + owner => "jane", + %dt_params, + public => 1, + } +); +is( + $search_results->{recordsTotal}, 12, + "There should be 12 public shelves in total" +); -is( $search_results->{ recordsFiltered }, 2, - "There should be 1 public shelves for jane" ); +is( + $search_results->{recordsFiltered}, 2, + "There should be 1 public shelves for jane" +); -is( @{ $search_results->{ shelves } }, 2, - "There should be 1 public shelf returned" ); +is( + @{ $search_results->{shelves} }, 2, + "There should be 1 public shelf returned" +); # Search by owner and shelf name -$search_results = C4::Utils::DataTables::VirtualShelves::search({ - owner => "smith", - shelfname => "public list 1", - %dt_params, - public => 1, -}); -is( $search_results->{ recordsTotal }, 12, - "There should be 12 public shelves in total" ); +$search_results = C4::Utils::DataTables::VirtualShelves::search( + { + owner => "smith", + shelfname => "public list 1", + %dt_params, + public => 1, + } +); +is( + $search_results->{recordsTotal}, 12, + "There should be 12 public shelves in total" +); -is( $search_results->{ recordsFiltered }, 6, - "There should be 6 public shelves for john with name like %public list 1%" ); +is( + $search_results->{recordsFiltered}, 6, + "There should be 6 public shelves for john with name like %public list 1%" +); -is( @{ $search_results->{ shelves } }, 6, - "There should be 6 public chalves returned" ); +is( + @{ $search_results->{shelves} }, 6, + "There should be 6 public chalves returned" +); sub _add_biblio { - my ( $title ) = @_; + my ($title) = @_; my $biblio = MARC::Record->new(); $biblio->append_fields( - MARC::Field->new('245', ' ', ' ', a => $title), + MARC::Field->new( '245', ' ', ' ', a => $title ), ); - my ($biblionumber, $biblioitemnumber) = AddBiblio($biblio, ''); + my ( $biblionumber, $biblioitemnumber ) = AddBiblio( $biblio, '' ); return $biblionumber; } diff --git a/t/db_dependent/Virtualshelves.t b/t/db_dependent/Virtualshelves.t index 25eb2e4bdc..6ef580fbad 100755 --- a/t/db_dependent/Virtualshelves.t +++ b/t/db_dependent/Virtualshelves.t @@ -40,67 +40,85 @@ teardown(); subtest 'CRUD' => sub { plan tests => 15; - my $patron = $builder->build({ - source => 'Borrower', - }); + my $patron = $builder->build( + { + source => 'Borrower', + } + ); my $number_of_shelves = Koha::Virtualshelves->search->count; is( $number_of_shelves, 0, 'No shelves should exist' ); - my $shelf = Koha::Virtualshelf->new({ + my $shelf = Koha::Virtualshelf->new( + { shelfname => "my first shelf", - owner => $patron->{borrowernumber}, - public => 0, + owner => $patron->{borrowernumber}, + public => 0, } )->store; - is( ref( $shelf ), 'Koha::Virtualshelf', 'The constructor should return a valid object' ); + is( ref($shelf), 'Koha::Virtualshelf', 'The constructor should return a valid object' ); $number_of_shelves = Koha::Virtualshelves->search->count; - is( $number_of_shelves, 1, '1 shelf should have been inserted' ); - is( $shelf->allow_change_from_owner, 1, 'The default value for allow_change_from_owner should be 1' ); + is( $number_of_shelves, 1, '1 shelf should have been inserted' ); + is( $shelf->allow_change_from_owner, 1, 'The default value for allow_change_from_owner should be 1' ); is( $shelf->allow_change_from_others, 0, 'The default value for allow_change_from_others should be 0' ); - is ( $shelf->allow_change_from_staff, 0, 'The default value for allow_change_from_staff should be 0'); - is ( $shelf->allow_change_from_permitted_staff, 0, 'The default value for allow_change_from_permitted_staff should be 0'); - is( t::lib::Dates::compare( $shelf->created_on, dt_from_string), 0, 'The creation time should have been set to today' ); + is( $shelf->allow_change_from_staff, 0, 'The default value for allow_change_from_staff should be 0' ); + is( + $shelf->allow_change_from_permitted_staff, 0, + 'The default value for allow_change_from_permitted_staff should be 0' + ); + is( + t::lib::Dates::compare( $shelf->created_on, dt_from_string ), 0, + 'The creation time should have been set to today' + ); # Test if creation date will not be overwritten by store my $created = dt_from_string->subtract( hours => 1 ); - $shelf->created_on( $created ); + $shelf->created_on($created); $shelf->store; my $retrieved_shelf = Koha::Virtualshelves->find( $shelf->shelfnumber ); is( $retrieved_shelf->shelfname, $shelf->shelfname, 'Find should correctly return the shelfname' ); - is( t::lib::Dates::compare( $retrieved_shelf->created_on, $created), 0, 'Creation date is the same after update (Bug 18672)' ); + is( + t::lib::Dates::compare( $retrieved_shelf->created_on, $created ), 0, + 'Creation date is the same after update (Bug 18672)' + ); # Insert with the same name eval { - $shelf = Koha::Virtualshelf->new({ + $shelf = Koha::Virtualshelf->new( + { shelfname => "my first shelf", - owner => $patron->{borrowernumber}, - public => 0, + owner => $patron->{borrowernumber}, + public => 0, } )->store; }; - is( ref($@), 'Koha::Exceptions::Virtualshelf::DuplicateObject', - 'Exception on duplicate name' ); + is( + ref($@), 'Koha::Exceptions::Virtualshelf::DuplicateObject', + 'Exception on duplicate name' + ); $number_of_shelves = Koha::Virtualshelves->search->count; is( $number_of_shelves, 1, 'To be sure the number of shelves is still 1' ); - my $another_patron = $builder->build({ - source => 'Borrower', - }); + my $another_patron = $builder->build( + { + source => 'Borrower', + } + ); - $shelf = Koha::Virtualshelf->new({ + $shelf = Koha::Virtualshelf->new( + { shelfname => "my first shelf", - owner => $another_patron->{borrowernumber}, - public => 0, + owner => $another_patron->{borrowernumber}, + public => 0, } )->store; $number_of_shelves = Koha::Virtualshelves->search->count; - is( $number_of_shelves, 2, 'Another patron should be able to create a shelf with an existing shelfname'); + is( $number_of_shelves, 2, 'Another patron should be able to create a shelf with an existing shelfname' ); my $is_deleted = Koha::Virtualshelves->find( $shelf->shelfnumber )->delete; ok( $is_deleted, 'The shelf has been deleted correctly' ); @@ -112,64 +130,91 @@ subtest 'CRUD' => sub { subtest 'Sharing' => sub { plan tests => 21; - my $patron_wants_to_share = $builder->build({ - source => 'Borrower', - }); - my $share_with_me = $builder->build({ - source => 'Borrower', - }); - my $just_another_patron = $builder->build({ - source => 'Borrower', - }); + my $patron_wants_to_share = $builder->build( + { + source => 'Borrower', + } + ); + my $share_with_me = $builder->build( + { + source => 'Borrower', + } + ); + my $just_another_patron = $builder->build( + { + source => 'Borrower', + } + ); my $number_of_shelves_shared = Koha::Virtualshelfshares->search->count; is( $number_of_shelves_shared, 0, 'No shelves should exist' ); - my $shelf_to_share = Koha::Virtualshelf->new({ + my $shelf_to_share = Koha::Virtualshelf->new( + { shelfname => "my first shelf", - owner => $patron_wants_to_share->{borrowernumber}, - public => 0, + owner => $patron_wants_to_share->{borrowernumber}, + public => 0, } )->store; - my $shelf_not_to_share = Koha::Virtualshelf->new({ + my $shelf_not_to_share = Koha::Virtualshelf->new( + { shelfname => "my second shelf", - owner => $patron_wants_to_share->{borrowernumber}, - public => 0, + owner => $patron_wants_to_share->{borrowernumber}, + public => 0, } )->store; my $shared_shelf = eval { $shelf_to_share->share }; - is ( ref( $@ ), 'Koha::Exceptions::Virtualshelf::InvalidKeyOnSharing', 'Do not share if no key given' ); + is( ref($@), 'Koha::Exceptions::Virtualshelf::InvalidKeyOnSharing', 'Do not share if no key given' ); $shared_shelf = eval { $shelf_to_share->share('valid key') }; - is( ref( $shared_shelf ), 'Koha::Virtualshelfshare', 'On sharing, the method should return a valid Koha::Virtualshelfshare object' ); + is( + ref($shared_shelf), 'Koha::Virtualshelfshare', + 'On sharing, the method should return a valid Koha::Virtualshelfshare object' + ); - my $another_shared_shelf = eval { $shelf_to_share->share('valid key2') }; # Just to have 2 shares in DB + my $another_shared_shelf = eval { $shelf_to_share->share('valid key2') }; # Just to have 2 shares in DB $number_of_shelves_shared = Koha::Virtualshelfshares->search->count; is( $number_of_shelves_shared, 2, '2 shares should have been inserted' ); - my $is_accepted = eval { - $shared_shelf->accept( 'invalid k', $share_with_me->{borrowernumber} ); - }; + my $is_accepted = eval { $shared_shelf->accept( 'invalid k', $share_with_me->{borrowernumber} ); }; is( $is_accepted, undef, 'The share should have not been accepted if the key is invalid' ); - is( ref( $@ ), 'Koha::Exceptions::Virtualshelf::InvalidInviteKey', 'accept with an invalid key should raise an exception' ); + is( + ref($@), 'Koha::Exceptions::Virtualshelf::InvalidInviteKey', + 'accept with an invalid key should raise an exception' + ); $is_accepted = $shared_shelf->accept( 'valid key', $share_with_me->{borrowernumber} ); ok( defined($is_accepted), 'The share should have been accepted if the key valid' ); - is( $shelf_to_share->is_shared, 1, 'first shelf is shared' ); + is( $shelf_to_share->is_shared, 1, 'first shelf is shared' ); is( $shelf_not_to_share->is_shared, 0, 'second shelf is not shared' ); - is( $shelf_to_share->is_shared_with( $patron_wants_to_share->{borrowernumber} ), 0 , "The shelf should not be shared with the owner" ); - is( $shelf_to_share->is_shared_with( $share_with_me->{borrowernumber} ), 1 , "The shelf should be shared with share_with_me" ); - is( $shelf_to_share->is_shared_with( $just_another_patron->{borrowernumber} ), 0, "The shelf should not be shared with just_another_patron" ); + is( + $shelf_to_share->is_shared_with( $patron_wants_to_share->{borrowernumber} ), 0, + "The shelf should not be shared with the owner" + ); + is( + $shelf_to_share->is_shared_with( $share_with_me->{borrowernumber} ), 1, + "The shelf should be shared with share_with_me" + ); + is( + $shelf_to_share->is_shared_with( $just_another_patron->{borrowernumber} ), 0, + "The shelf should not be shared with just_another_patron" + ); - is( $shelf_to_share->remove_share( $just_another_patron->{borrowernumber} ), 0, 'No share should be removed if the share has not been done with this patron' ); + is( + $shelf_to_share->remove_share( $just_another_patron->{borrowernumber} ), 0, + 'No share should be removed if the share has not been done with this patron' + ); $number_of_shelves_shared = Koha::Virtualshelfshares->search->count; is( $number_of_shelves_shared, 2, 'To be sure no shares have been removed' ); - is( $shelf_not_to_share->remove_share( $share_with_me->{borrowernumber} ), 0, '0 share should have been removed if the shelf is not share' ); + is( + $shelf_not_to_share->remove_share( $share_with_me->{borrowernumber} ), 0, + '0 share should have been removed if the shelf is not share' + ); $number_of_shelves_shared = Koha::Virtualshelfshares->search->count; is( $number_of_shelves_shared, 2, 'To be sure no shares have been removed' ); @@ -177,11 +222,14 @@ subtest 'Sharing' => sub { my $third_share = $shelf_to_share->share('valid key3'); is( Koha::Virtualshelfshares->search->count, 3, 'Three shares' ); $is_accepted = $third_share->accept( 'valid key3', $share_with_me->{borrowernumber} ); - is( $is_accepted->shelfnumber, $shelf_to_share->shelfnumber, 'Accept returned the existing share' ); + is( $is_accepted->shelfnumber, $shelf_to_share->shelfnumber, 'Accept returned the existing share' ); is( Koha::Virtualshelfshares->search->count, 2, 'Check that number of shares went down again' ); # Remove the first accept - ok( $shelf_to_share->remove_share( $share_with_me->{borrowernumber} ), '1 share should have been removed if the shelf was shared with this patron' ); + ok( + $shelf_to_share->remove_share( $share_with_me->{borrowernumber} ), + '1 share should have been removed if the shelf was shared with this patron' + ); $number_of_shelves_shared = Koha::Virtualshelfshares->search->count; is( $number_of_shelves_shared, 1, 'To be sure the share has been removed' ); @@ -193,29 +241,30 @@ subtest 'Shelf content' => sub { plan tests => 26; my $patron1 = $builder->build( { source => 'Borrower', } ); my $patron2 = $builder->build( { source => 'Borrower', } ); - my $patron3 = $builder->build( { source => 'Borrower', value => {flags => 1} }); + my $patron3 = $builder->build( { source => 'Borrower', value => { flags => 1 } } ); my $patron4 = $builder->build( { source => 'Borrower', } ); $builder->build( { source => 'UserPermission', value => { borrowernumber => $patron4->{borrowernumber}, - module_bit => 20, # lists + module_bit => 20, # lists code => 'eit_public_list_contents', }, } ); - my $biblio1 = $builder->build_sample_biblio; - my $biblio2 = $builder->build_sample_biblio; - my $biblio3 = $builder->build_sample_biblio; - my $biblio4 = $builder->build_sample_biblio; + my $biblio1 = $builder->build_sample_biblio; + my $biblio2 = $builder->build_sample_biblio; + my $biblio3 = $builder->build_sample_biblio; + my $biblio4 = $builder->build_sample_biblio; my $number_of_contents = Koha::Virtualshelfcontents->search->count; is( $number_of_contents, 0, 'No content should exist' ); my $dt_yesterday = dt_from_string->subtract_duration( DateTime::Duration->new( days => 1 ) ); - my $shelf = Koha::Virtualshelf->new( - { shelfname => "my first shelf", + my $shelf = Koha::Virtualshelf->new( + { + shelfname => "my first shelf", owner => $patron1->{borrowernumber}, public => 0, lastmodified => $dt_yesterday, @@ -223,11 +272,20 @@ subtest 'Shelf content' => sub { )->store; $shelf = Koha::Virtualshelves->find( $shelf->shelfnumber ); - is( t::lib::Dates::compare( $shelf->lastmodified, $dt_yesterday), 0, 'The lastmodified has been set to yesterday, will be useful for another test later' ); + is( + t::lib::Dates::compare( $shelf->lastmodified, $dt_yesterday ), 0, + 'The lastmodified has been set to yesterday, will be useful for another test later' + ); my $content1 = $shelf->add_biblio( $biblio1->biblionumber, $patron1->{borrowernumber} ); - is( ref($content1), 'Koha::Virtualshelfcontent', 'add_biblio to a shelf should return a Koha::Virtualshelfcontent object if inserted' ); + is( + ref($content1), 'Koha::Virtualshelfcontent', + 'add_biblio to a shelf should return a Koha::Virtualshelfcontent object if inserted' + ); $shelf = Koha::Virtualshelves->find( $shelf->shelfnumber ); - is( t::lib::Dates::compare( $shelf->lastmodified, dt_from_string), 0, 'Adding a biblio to a shelf should update the lastmodified for the shelf' ); + is( + t::lib::Dates::compare( $shelf->lastmodified, dt_from_string ), 0, + 'Adding a biblio to a shelf should update the lastmodified for the shelf' + ); my $content2 = $shelf->add_biblio( $biblio2->biblionumber, $patron1->{borrowernumber} ); $number_of_contents = Koha::Virtualshelfcontents->search->count; is( $number_of_contents, 2, '2 biblio should have been inserted' ); @@ -243,68 +301,77 @@ subtest 'Shelf content' => sub { # Patron 2 will try to remove biblios # allow_change_from_owner = 1, allow_change_from_others = 0 (defaults) - my $number_of_deleted_biblios = $shelf->remove_biblios( { biblionumbers => [ $biblio1->biblionumber ], borrowernumber => $patron2->{borrowernumber} } ); + my $number_of_deleted_biblios = $shelf->remove_biblios( + { biblionumbers => [ $biblio1->biblionumber ], borrowernumber => $patron2->{borrowernumber} } ); is( $number_of_deleted_biblios, 0, 'Patron 2 removed nothing' ); + # Now try with patron 1 - $number_of_deleted_biblios = $shelf->remove_biblios( { biblionumbers => [ $biblio1->biblionumber ], borrowernumber => $patron1->{borrowernumber} } ); + $number_of_deleted_biblios = $shelf->remove_biblios( + { biblionumbers => [ $biblio1->biblionumber ], borrowernumber => $patron1->{borrowernumber} } ); is( $number_of_deleted_biblios, 1, 'Patron 1 removed biblio' ); $number_of_contents = Koha::Virtualshelfcontents->search->count; is( $number_of_contents, 1, 'To be sure the content has been deleted' ); # allow_change_from_owner == 0 (readonly) - $shelf->allow_change_from_owner( 0 ); + $shelf->allow_change_from_owner(0); $shelf->store; - $number_of_deleted_biblios = $shelf->remove_biblios( { biblionumbers => [ $biblio2->biblionumber ], borrowernumber => $patron1->{borrowernumber} } ); + $number_of_deleted_biblios = $shelf->remove_biblios( + { biblionumbers => [ $biblio2->biblionumber ], borrowernumber => $patron1->{borrowernumber} } ); is( $number_of_deleted_biblios, 0, 'Owner could not delete' ); $number_of_contents = Koha::Virtualshelfcontents->search->count; is( $number_of_contents, 1, 'Number of entries still equal to 1' ); $shelf->add_biblio( $biblio2->biblionumber, $patron1->{borrowernumber} ); $number_of_contents = Koha::Virtualshelfcontents->search->count; is( $number_of_contents, 1, 'Biblio not added to the list' ); + # Add back biblio1 - $shelf->allow_change_from_owner( 1 ); + $shelf->allow_change_from_owner(1); $shelf->add_biblio( $biblio1->biblionumber, $patron1->{borrowernumber} ); $number_of_contents = Koha::Virtualshelfcontents->search->count; is( $number_of_contents, 2, 'Biblio added to the list' ); # allow_change_from_others == 1 - $shelf->allow_change_from_others( 1 ); + $shelf->allow_change_from_others(1); my $content3 = $shelf->add_biblio( $biblio3->biblionumber, $patron2->{borrowernumber} ); my $content4 = $shelf->add_biblio( $biblio4->biblionumber, $patron2->{borrowernumber} ); $number_of_contents = Koha::Virtualshelfcontents->search->count; is( $number_of_contents, 4, 'The biblio should have been added to the shelf by the patron 2' ); - $number_of_deleted_biblios = $shelf->remove_biblios( { biblionumbers => [ $biblio3->biblionumber ], borrowernumber => $patron2->{borrowernumber} } ); + $number_of_deleted_biblios = $shelf->remove_biblios( + { biblionumbers => [ $biblio3->biblionumber ], borrowernumber => $patron2->{borrowernumber} } ); is( $number_of_deleted_biblios, 1, 'Biblio 3 deleted by patron 2' ); $number_of_contents = Koha::Virtualshelfcontents->search->count; is( $number_of_contents, 3, 'Back to three entries' ); # allow_change_from_staff == 1 and allow_change_from_others == 0 - $shelf->allow_change_from_staff( 1 ); - $shelf->allow_change_from_others( 0 ); - $content4 = $shelf->add_biblio( $biblio3->biblionumber, $patron3->{borrowernumber} ); + $shelf->allow_change_from_staff(1); + $shelf->allow_change_from_others(0); + $content4 = $shelf->add_biblio( $biblio3->biblionumber, $patron3->{borrowernumber} ); $number_of_contents = Koha::Virtualshelfcontents->search->count; - is( $number_of_contents, 4, 'The biblio should have been added to the shelf by patron 2'); - $number_of_deleted_biblios = $shelf->remove_biblios( { biblionumbers => [ $biblio3->biblionumber ], borrowernumber => $patron3->{borrowernumber} } ); + is( $number_of_contents, 4, 'The biblio should have been added to the shelf by patron 2' ); + $number_of_deleted_biblios = $shelf->remove_biblios( + { biblionumbers => [ $biblio3->biblionumber ], borrowernumber => $patron3->{borrowernumber} } ); is( $number_of_deleted_biblios, 1, 'Biblio 3 deleted by patron 2' ); $number_of_contents = Koha::Virtualshelfcontents->search->count; is( $number_of_contents, 3, 'Back to three entries' ); # allow_change_from_permitted_staff == 1 and allow_change_from_staff = 1 and allow_change_from_others == 0 - $shelf->allow_change_from_permitted_staff( 1 ); - $shelf->allow_change_from_staff( 0 ); - $shelf->allow_change_from_others( 1 ); - $content4 = $shelf->add_biblio( $biblio3->biblionumber, $patron3->{borrowernumber} ); + $shelf->allow_change_from_permitted_staff(1); + $shelf->allow_change_from_staff(0); + $shelf->allow_change_from_others(1); + $content4 = $shelf->add_biblio( $biblio3->biblionumber, $patron3->{borrowernumber} ); $number_of_contents = Koha::Virtualshelfcontents->search->count; - is( $number_of_contents, 4, 'The biblio should have been added to the shelf by patron 3'); - $number_of_deleted_biblios = $shelf->remove_biblios( { biblionumbers => [ $biblio3->biblionumber ], borrowernumber => $patron3->{borrowernumber} } ); + is( $number_of_contents, 4, 'The biblio should have been added to the shelf by patron 3' ); + $number_of_deleted_biblios = $shelf->remove_biblios( + { biblionumbers => [ $biblio3->biblionumber ], borrowernumber => $patron3->{borrowernumber} } ); is( $number_of_deleted_biblios, 1, 'Biblio 3 deleted by patron 3' ); $number_of_contents = Koha::Virtualshelfcontents->search->count; is( $number_of_contents, 3, 'Back to three entries' ); - $content4 = $shelf->add_biblio( $biblio3->biblionumber, $patron4->{borrowernumber} ); + $content4 = $shelf->add_biblio( $biblio3->biblionumber, $patron4->{borrowernumber} ); $number_of_contents = Koha::Virtualshelfcontents->search->count; - is( $number_of_contents, 4, 'The biblio should have been added to the shelf by patron 4'); - $number_of_deleted_biblios = $shelf->remove_biblios( { biblionumbers => [ $biblio3->biblionumber ], borrowernumber => $patron4->{borrowernumber} } ); + is( $number_of_contents, 4, 'The biblio should have been added to the shelf by patron 4' ); + $number_of_deleted_biblios = $shelf->remove_biblios( + { biblionumbers => [ $biblio3->biblionumber ], borrowernumber => $patron4->{borrowernumber} } ); $number_of_contents = Koha::Virtualshelfcontents->search->count; is( $number_of_contents, 3, 'Back to three entries' ); @@ -314,15 +381,21 @@ subtest 'Shelf content' => sub { subtest 'Shelf permissions' => sub { plan tests => 175; - my $patron1 = $builder->build( { source => 'Borrower', value => { flags => '2096766' } } ); # 2096766 is everything checked but not superlibrarian - my $patron2 = $builder->build( { source => 'Borrower', value => { flags => '1048190' } } ); # 1048190 is everything checked but not superlibrarian and delete_public_lists - my $patron3 = $builder->build( { source => 'Borrower', value => { flags => '0' } } ); # this is a patron with no special permissions + my $patron1 = $builder->build( { source => 'Borrower', value => { flags => '2096766' } } ) + ; # 2096766 is everything checked but not superlibrarian + my $patron2 = $builder->build( { source => 'Borrower', value => { flags => '1048190' } } ) + ; # 1048190 is everything checked but not superlibrarian and delete_public_lists + my $patron3 = $builder->build( { source => 'Borrower', value => { flags => '0' } } ) + ; # this is a patron with no special permissions my $patron4 = $builder->build( { source => 'Borrower', value => { flags => '0' } } ); my $patron5 = $builder->build( { source => 'Borrower', value => { flags => '4' } } ); - my $sth = $dbh->prepare("INSERT INTO user_permissions (borrowernumber, module_bit, code) VALUES (?,?,?)"); - $sth->execute($patron2->{borrowernumber}, 20, 'edit_public_list_contents'); # $patron2 has everything checked but not superlibrarian and delete_public_lists - $sth->execute($patron4->{borrowernumber}, 20, 'edit_public_lists'); # $patron4 only has the edit_public_lists sub-permission checked - $sth->execute($patron5->{borrowernumber}, 20, 'edit_public_list_contents'); # $patron5 has the 'catalogue' permission and edit_public_list_contents sub-permission checked + my $sth = $dbh->prepare("INSERT INTO user_permissions (borrowernumber, module_bit, code) VALUES (?,?,?)"); + $sth->execute( $patron2->{borrowernumber}, 20, 'edit_public_list_contents' ) + ; # $patron2 has everything checked but not superlibrarian and delete_public_lists + $sth->execute( $patron4->{borrowernumber}, 20, 'edit_public_lists' ) + ; # $patron4 only has the edit_public_lists sub-permission checked + $sth->execute( $patron5->{borrowernumber}, 20, 'edit_public_list_contents' ) + ; # $patron5 has the 'catalogue' permission and edit_public_list_contents sub-permission checked my $biblio1 = $builder->build_sample_biblio; my $biblio2 = $builder->build_sample_biblio; @@ -332,9 +405,10 @@ subtest 'Shelf permissions' => sub { my $biblio6 = $builder->build_sample_biblio; my $public_shelf = Koha::Virtualshelf->new( - { shelfname => "my first shelf", - owner => $patron1->{borrowernumber}, - public => 1, + { + shelfname => "my first shelf", + owner => $patron1->{borrowernumber}, + public => 1, allow_change_from_owner => 0, allow_change_from_others => 0, allow_change_from_staff => 0, @@ -342,175 +416,539 @@ subtest 'Shelf permissions' => sub { } )->store; - is( $public_shelf->can_be_viewed( $patron1->{borrowernumber} ), 1, 'The owner should be able to view their public list' ); - is( $public_shelf->can_be_viewed( $patron2->{borrowernumber} ), 1, 'Public list should be viewed by another staff member'); - is( $public_shelf->can_be_viewed( $patron3->{borrowernumber} ), 1, 'Public list should be viewed by someone with no special permissions' ); - is( $public_shelf->can_be_viewed( $patron4->{borrowernumber} ), 1, 'Public list should be viewed by someone with the edit_public_lists sub-permission checked' ); - is( $public_shelf->can_be_viewed( $patron5->{borrowernumber} ), 1, 'Public list should be viewed by someone with the edit_public_list_contents sub-permission checked' ); + is( + $public_shelf->can_be_viewed( $patron1->{borrowernumber} ), 1, + 'The owner should be able to view their public list' + ); + is( + $public_shelf->can_be_viewed( $patron2->{borrowernumber} ), 1, + 'Public list should be viewed by another staff member' + ); + is( + $public_shelf->can_be_viewed( $patron3->{borrowernumber} ), 1, + 'Public list should be viewed by someone with no special permissions' + ); + is( + $public_shelf->can_be_viewed( $patron4->{borrowernumber} ), 1, + 'Public list should be viewed by someone with the edit_public_lists sub-permission checked' + ); + is( + $public_shelf->can_be_viewed( $patron5->{borrowernumber} ), 1, + 'Public list should be viewed by someone with the edit_public_list_contents sub-permission checked' + ); - is( $public_shelf->can_be_deleted( $patron1->{borrowernumber} ), 1, 'The owner should be able to delete their list' ); - is( $public_shelf->can_be_deleted( $patron2->{borrowernumber} ), 0, 'Public list should not be deleted by another staff member' ); - is( $public_shelf->can_be_deleted( $patron3->{borrowernumber} ), 0, 'Public list should not be deleted by someone with no special permissions' ); - is( $public_shelf->can_be_deleted( $patron4->{borrowernumber} ), 0, 'Public list should not be deleted by someone with the edit_public_lists sub-permission checked' ); - is( $public_shelf->can_be_deleted( $patron5->{borrowernumber} ), 0, 'Public list should not be deleted by someone with the edit_public_list_contents sub-permission checked' ); + is( + $public_shelf->can_be_deleted( $patron1->{borrowernumber} ), 1, + 'The owner should be able to delete their list' + ); + is( + $public_shelf->can_be_deleted( $patron2->{borrowernumber} ), 0, + 'Public list should not be deleted by another staff member' + ); + is( + $public_shelf->can_be_deleted( $patron3->{borrowernumber} ), 0, + 'Public list should not be deleted by someone with no special permissions' + ); + is( + $public_shelf->can_be_deleted( $patron4->{borrowernumber} ), 0, + 'Public list should not be deleted by someone with the edit_public_lists sub-permission checked' + ); + is( + $public_shelf->can_be_deleted( $patron5->{borrowernumber} ), 0, + 'Public list should not be deleted by someone with the edit_public_list_contents sub-permission checked' + ); - is( $public_shelf->can_be_managed( $patron1->{borrowernumber} ), 1, 'The owner should be able to manage their list' ); - is( $public_shelf->can_be_managed( $patron2->{borrowernumber} ), 0, 'Public list should not be managed by another staff member' ); - is( $public_shelf->can_be_managed( $patron3->{borrowernumber} ), 0, 'Public list should not be managed by someone with no special permissions' ); - is( $public_shelf->can_be_managed( $patron4->{borrowernumber} ), 1, 'Public list should be managed by someone with the edit_public_lists sub-permission checked' ); - is( $public_shelf->can_be_managed( $patron5->{borrowernumber} ), 0, 'Public list should be managed by someone with the edit_public_list_contents sub-permission checked' ); + is( + $public_shelf->can_be_managed( $patron1->{borrowernumber} ), 1, + 'The owner should be able to manage their list' + ); + is( + $public_shelf->can_be_managed( $patron2->{borrowernumber} ), 0, + 'Public list should not be managed by another staff member' + ); + is( + $public_shelf->can_be_managed( $patron3->{borrowernumber} ), 0, + 'Public list should not be managed by someone with no special permissions' + ); + is( + $public_shelf->can_be_managed( $patron4->{borrowernumber} ), 1, + 'Public list should be managed by someone with the edit_public_lists sub-permission checked' + ); + is( + $public_shelf->can_be_managed( $patron5->{borrowernumber} ), 0, + 'Public list should be managed by someone with the edit_public_list_contents sub-permission checked' + ); - is( $public_shelf->can_biblios_be_added( $patron1->{borrowernumber} ), 0, 'The owner should not be able to add biblios to their list' ); - is( $public_shelf->can_biblios_be_added( $patron2->{borrowernumber} ), 0, 'Public list should not be modified (add) by another staff member' ); - is( $public_shelf->can_biblios_be_added( $patron3->{borrowernumber} ), 0, 'Public list should not be modified (add) by someone with no special permissions' ); - is( $public_shelf->can_biblios_be_added( $patron4->{borrowernumber} ), 0, 'Public list should not be modified (add) by someone with the edit_public_lists sub-permission checked' ); - is( $public_shelf->can_biblios_be_added( $patron5->{borrowernumber} ), 0, 'Public list should not be modified (add) by someone with the edit_public_list_contents sub-permission checked' ); + is( + $public_shelf->can_biblios_be_added( $patron1->{borrowernumber} ), 0, + 'The owner should not be able to add biblios to their list' + ); + is( + $public_shelf->can_biblios_be_added( $patron2->{borrowernumber} ), 0, + 'Public list should not be modified (add) by another staff member' + ); + is( + $public_shelf->can_biblios_be_added( $patron3->{borrowernumber} ), 0, + 'Public list should not be modified (add) by someone with no special permissions' + ); + is( + $public_shelf->can_biblios_be_added( $patron4->{borrowernumber} ), 0, + 'Public list should not be modified (add) by someone with the edit_public_lists sub-permission checked' + ); + is( + $public_shelf->can_biblios_be_added( $patron5->{borrowernumber} ), 0, + 'Public list should not be modified (add) by someone with the edit_public_list_contents sub-permission checked' + ); - is( $public_shelf->can_biblios_be_removed( $patron1->{borrowernumber} ), 0, 'The owner should not be able to remove biblios to their list' ); - is( $public_shelf->can_biblios_be_removed( $patron2->{borrowernumber} ), 0, 'Public list should not be modified (remove) by another staff member' ); - is ( $public_shelf->can_biblios_be_removed( $patron3->{borrowernumber} ), 0, 'Public list should not be modified (removed) by someone with no special permissions' ); - is( $public_shelf->can_biblios_be_removed( $patron4->{borrowernumber} ), 0, 'Public list should not be modified (removed) by someone with the edit_public_lists sub-permission checked' ); - is( $public_shelf->can_biblios_be_removed( $patron5->{borrowernumber} ), 0, 'Public list should not be modified (removed) by someone with the edit_public_list_contents sub-permission checked' ); + is( + $public_shelf->can_biblios_be_removed( $patron1->{borrowernumber} ), 0, + 'The owner should not be able to remove biblios to their list' + ); + is( + $public_shelf->can_biblios_be_removed( $patron2->{borrowernumber} ), 0, + 'Public list should not be modified (remove) by another staff member' + ); + is( + $public_shelf->can_biblios_be_removed( $patron3->{borrowernumber} ), 0, + 'Public list should not be modified (removed) by someone with no special permissions' + ); + is( + $public_shelf->can_biblios_be_removed( $patron4->{borrowernumber} ), 0, + 'Public list should not be modified (removed) by someone with the edit_public_lists sub-permission checked' + ); + is( + $public_shelf->can_biblios_be_removed( $patron5->{borrowernumber} ), 0, + 'Public list should not be modified (removed) by someone with the edit_public_list_contents sub-permission checked' + ); $public_shelf->allow_change_from_owner(1); $public_shelf->store; - is( $public_shelf->can_be_viewed( $patron1->{borrowernumber} ), 1, 'The owner should be able to view their public list' ); + is( + $public_shelf->can_be_viewed( $patron1->{borrowernumber} ), 1, + 'The owner should be able to view their public list' + ); is( $public_shelf->can_be_viewed( $patron2->{borrowernumber} ), 1, 'Public list should be viewed by staff member' ); - is( $public_shelf->can_be_viewed( $patron3->{borrowernumber} ), 1, 'Public list should be viewed by someone with no special permissions' ); - is( $public_shelf->can_be_viewed( $patron4->{borrowernumber} ), 1, 'Public list should be viewable by someone with the edit_public_lists sub-permission checked' ); - is( $public_shelf->can_be_viewed( $patron5->{borrowenumber} ), 1, 'Public list should be viewable by someone with the edit_public_list_contents sub-permission checked' ); + is( + $public_shelf->can_be_viewed( $patron3->{borrowernumber} ), 1, + 'Public list should be viewed by someone with no special permissions' + ); + is( + $public_shelf->can_be_viewed( $patron4->{borrowernumber} ), 1, + 'Public list should be viewable by someone with the edit_public_lists sub-permission checked' + ); + is( + $public_shelf->can_be_viewed( $patron5->{borrowenumber} ), 1, + 'Public list should be viewable by someone with the edit_public_list_contents sub-permission checked' + ); - is( $public_shelf->can_be_deleted( $patron1->{borrowernumber} ), 1, 'The owner should be able to delete their list' ); - is( $public_shelf->can_be_deleted( $patron2->{borrowernumber} ), 0, 'Public list should not be deleted by another staff member' ); - is( $public_shelf->can_be_deleted( $patron3->{borrowernumber} ), 0, 'Public list should not be deleted by someone with no special permissions' ); - is( $public_shelf->can_be_deleted( $patron4->{borrowernumber} ), 0, 'Public list should not be deleted by someone with the edit_public_lists sub-permission checked' ); - is( $public_shelf->can_be_deleted( $patron5->{borrowernumber} ), 0, 'Public list should not be deleted by someome with the edit_public_list_contents sub-permission checked' ); + is( + $public_shelf->can_be_deleted( $patron1->{borrowernumber} ), 1, + 'The owner should be able to delete their list' + ); + is( + $public_shelf->can_be_deleted( $patron2->{borrowernumber} ), 0, + 'Public list should not be deleted by another staff member' + ); + is( + $public_shelf->can_be_deleted( $patron3->{borrowernumber} ), 0, + 'Public list should not be deleted by someone with no special permissions' + ); + is( + $public_shelf->can_be_deleted( $patron4->{borrowernumber} ), 0, + 'Public list should not be deleted by someone with the edit_public_lists sub-permission checked' + ); + is( + $public_shelf->can_be_deleted( $patron5->{borrowernumber} ), 0, + 'Public list should not be deleted by someome with the edit_public_list_contents sub-permission checked' + ); - is( $public_shelf->can_be_managed( $patron1->{borrowernumber} ), 1, 'The owner should be able to manage their list' ); - is( $public_shelf->can_be_managed( $patron2->{borrowernumber} ), 0, 'Public list should not be managed by another staff member' ); - is( $public_shelf->can_be_managed( $patron3->{borrowernumber} ), 0, 'Public list should not be managed by someone with no special permissions' ); - is( $public_shelf->can_be_managed( $patron4->{borrowernumber} ), 1, 'Public list should be managed by someone with the edit_public_lists sub-permission checked' ); - is( $public_shelf->can_be_managed( $patron5->{borrowernumber} ), 0, 'Public list should be managed by someone with the edit_public_list_contents sub-permission checked' ); + is( + $public_shelf->can_be_managed( $patron1->{borrowernumber} ), 1, + 'The owner should be able to manage their list' + ); + is( + $public_shelf->can_be_managed( $patron2->{borrowernumber} ), 0, + 'Public list should not be managed by another staff member' + ); + is( + $public_shelf->can_be_managed( $patron3->{borrowernumber} ), 0, + 'Public list should not be managed by someone with no special permissions' + ); + is( + $public_shelf->can_be_managed( $patron4->{borrowernumber} ), 1, + 'Public list should be managed by someone with the edit_public_lists sub-permission checked' + ); + is( + $public_shelf->can_be_managed( $patron5->{borrowernumber} ), 0, + 'Public list should be managed by someone with the edit_public_list_contents sub-permission checked' + ); - is( $public_shelf->can_biblios_be_added( $patron1->{borrowernumber} ), 1, 'The owner should be able to add biblios to their list' ); - is( $public_shelf->can_biblios_be_added( $patron2->{borrowernumber} ), 0, 'Public list should not be modified (add) by another staff member' ); - is( $public_shelf->can_biblios_be_added( $patron3->{borrowernumber} ), 0, 'Public list should not be modified (add) by someone with no special permissions' ); - is( $public_shelf->can_biblios_be_added( $patron4->{borrowernumber} ), 0, 'Public list should not be modified (add) by someone with the edit_public_lists sub-permission checked' ); - is( $public_shelf->can_biblios_be_added( $patron5->{borrowernumber} ), 0, 'Public list should not be modified (add) by someone with the edit_public_list_contents sub-permission checked' ); + is( + $public_shelf->can_biblios_be_added( $patron1->{borrowernumber} ), 1, + 'The owner should be able to add biblios to their list' + ); + is( + $public_shelf->can_biblios_be_added( $patron2->{borrowernumber} ), 0, + 'Public list should not be modified (add) by another staff member' + ); + is( + $public_shelf->can_biblios_be_added( $patron3->{borrowernumber} ), 0, + 'Public list should not be modified (add) by someone with no special permissions' + ); + is( + $public_shelf->can_biblios_be_added( $patron4->{borrowernumber} ), 0, + 'Public list should not be modified (add) by someone with the edit_public_lists sub-permission checked' + ); + is( + $public_shelf->can_biblios_be_added( $patron5->{borrowernumber} ), 0, + 'Public list should not be modified (add) by someone with the edit_public_list_contents sub-permission checked' + ); - is( $public_shelf->can_biblios_be_removed( $patron1->{borrowernumber} ), 1, 'The owner should be able to remove biblios to their list' ); - is( $public_shelf->can_biblios_be_removed( $patron2->{borrowernumber} ), 0, 'Public list should not be modified (remove) by another staff member' ); - is( $public_shelf->can_biblios_be_removed( $patron3->{borrowernumber} ), 0, 'Public list should not be modified (remove) by someone with no special permissions' ); - is( $public_shelf->can_biblios_be_removed( $patron4->{borrowernumber} ), 0, 'Public list should not be modified (remove) by someone with the edit_public_list sub-permission checked' ); - is( $public_shelf->can_biblios_be_removed( $patron5->{borrowernumber} ), 0, 'Public list should not be modified (remove) by someome with the edit_public_list_contents sub-permission checked' ); + is( + $public_shelf->can_biblios_be_removed( $patron1->{borrowernumber} ), 1, + 'The owner should be able to remove biblios to their list' + ); + is( + $public_shelf->can_biblios_be_removed( $patron2->{borrowernumber} ), 0, + 'Public list should not be modified (remove) by another staff member' + ); + is( + $public_shelf->can_biblios_be_removed( $patron3->{borrowernumber} ), 0, + 'Public list should not be modified (remove) by someone with no special permissions' + ); + is( + $public_shelf->can_biblios_be_removed( $patron4->{borrowernumber} ), 0, + 'Public list should not be modified (remove) by someone with the edit_public_list sub-permission checked' + ); + is( + $public_shelf->can_biblios_be_removed( $patron5->{borrowernumber} ), 0, + 'Public list should not be modified (remove) by someome with the edit_public_list_contents sub-permission checked' + ); $public_shelf->allow_change_from_staff(1); $public_shelf->store; - is( $public_shelf->can_be_viewed( $patron1->{borrowernumber} ), 1, 'The owner should be able to view their public list' ); + is( + $public_shelf->can_be_viewed( $patron1->{borrowernumber} ), 1, + 'The owner should be able to view their public list' + ); is( $public_shelf->can_be_viewed( $patron2->{borrowernumber} ), 1, 'Public list should be viewed by staff member' ); - is( $public_shelf->can_be_viewed( $patron3->{borrowernumber} ), 1, 'Public list should be viewed by someone with no special permissions' ); - is( $public_shelf->can_be_viewed( $patron4->{borrowernumber} ), 1, 'Public list should be viewable by someone with the edit_public_lists sub-permission checked' ); - is( $public_shelf->can_be_viewed( $patron5->{borrowernumber} ), 1, 'Public list should be viewable by someone with the edit_public_list_contents sub-permission checked' ); + is( + $public_shelf->can_be_viewed( $patron3->{borrowernumber} ), 1, + 'Public list should be viewed by someone with no special permissions' + ); + is( + $public_shelf->can_be_viewed( $patron4->{borrowernumber} ), 1, + 'Public list should be viewable by someone with the edit_public_lists sub-permission checked' + ); + is( + $public_shelf->can_be_viewed( $patron5->{borrowernumber} ), 1, + 'Public list should be viewable by someone with the edit_public_list_contents sub-permission checked' + ); - is( $public_shelf->can_be_deleted( $patron1->{borrowernumber} ), 1, 'The owner should be able to delete their list' ); - is( $public_shelf->can_be_deleted( $patron2->{borrowernumber} ), 0, 'Public list should not be deleted by another staff member' ); - is( $public_shelf->can_be_deleted( $patron3->{borrowernumber} ), 0, 'Public list should not be deleted by someone with no special permissions' ); - is( $public_shelf->can_be_deleted( $patron4->{borrowernumber} ), 0, 'Public list should not be deleted by someone with the edit_public_lists sub-permission checked' ); - is( $public_shelf->can_be_deleted( $patron5->{borrowernumber} ), 0, 'Public list should not be deleted by someone with the edit_public_list_contents sub-permission checked' ); + is( + $public_shelf->can_be_deleted( $patron1->{borrowernumber} ), 1, + 'The owner should be able to delete their list' + ); + is( + $public_shelf->can_be_deleted( $patron2->{borrowernumber} ), 0, + 'Public list should not be deleted by another staff member' + ); + is( + $public_shelf->can_be_deleted( $patron3->{borrowernumber} ), 0, + 'Public list should not be deleted by someone with no special permissions' + ); + is( + $public_shelf->can_be_deleted( $patron4->{borrowernumber} ), 0, + 'Public list should not be deleted by someone with the edit_public_lists sub-permission checked' + ); + is( + $public_shelf->can_be_deleted( $patron5->{borrowernumber} ), 0, + 'Public list should not be deleted by someone with the edit_public_list_contents sub-permission checked' + ); - is( $public_shelf->can_be_managed( $patron1->{borrowernumber} ), 1, 'The owner should be able to manage their list' ); - is( $public_shelf->can_be_managed( $patron2->{borrowernumber} ), 0, 'Public list should not be managed by another staff member' ); - is( $public_shelf->can_be_managed( $patron3->{borrowernumber} ), 0, 'Public list should not be managed by someone with no special permissions' ); - is( $public_shelf->can_be_managed( $patron4->{borrowernumber} ), 1, 'Public list should be managed by someone with the edit_public_lists sub-permission checked' ); - is( $public_shelf->can_be_managed( $patron5->{borrowernumber} ), 0, 'Public list should be managed by someone with the edit_public_list_contents sub-permission checked' ); + is( + $public_shelf->can_be_managed( $patron1->{borrowernumber} ), 1, + 'The owner should be able to manage their list' + ); + is( + $public_shelf->can_be_managed( $patron2->{borrowernumber} ), 0, + 'Public list should not be managed by another staff member' + ); + is( + $public_shelf->can_be_managed( $patron3->{borrowernumber} ), 0, + 'Public list should not be managed by someone with no special permissions' + ); + is( + $public_shelf->can_be_managed( $patron4->{borrowernumber} ), 1, + 'Public list should be managed by someone with the edit_public_lists sub-permission checked' + ); + is( + $public_shelf->can_be_managed( $patron5->{borrowernumber} ), 0, + 'Public list should be managed by someone with the edit_public_list_contents sub-permission checked' + ); - is( $public_shelf->can_biblios_be_added( $patron1->{borrowernumber} ), 1, 'The owner should be able to add biblios to their list' ); - is( $public_shelf->can_biblios_be_added( $patron2->{borrowernumber} ), 1, 'Public list should not be modified (add) by another staff member' ); - is( $public_shelf->can_biblios_be_added( $patron3->{borrowernumber} ), 0, 'Public list should not be modified (add) by someone with no special permissions' ); - is( $public_shelf->can_biblios_be_added( $patron4->{borrowernumber} ), 0, 'Public list should not be modified (add) by someone with the edit_public_lists sub-permission checked' ); - is( $public_shelf->can_biblios_be_added( $patron5->{borrowernumber} ), 1, 'Public list should be modified (add) by someone with the edit_public_list_contents sub-permission checked' ); + is( + $public_shelf->can_biblios_be_added( $patron1->{borrowernumber} ), 1, + 'The owner should be able to add biblios to their list' + ); + is( + $public_shelf->can_biblios_be_added( $patron2->{borrowernumber} ), 1, + 'Public list should not be modified (add) by another staff member' + ); + is( + $public_shelf->can_biblios_be_added( $patron3->{borrowernumber} ), 0, + 'Public list should not be modified (add) by someone with no special permissions' + ); + is( + $public_shelf->can_biblios_be_added( $patron4->{borrowernumber} ), 0, + 'Public list should not be modified (add) by someone with the edit_public_lists sub-permission checked' + ); + is( + $public_shelf->can_biblios_be_added( $patron5->{borrowernumber} ), 1, + 'Public list should be modified (add) by someone with the edit_public_list_contents sub-permission checked' + ); - is( $public_shelf->can_biblios_be_removed( $patron1->{borrowernumber} ), 1, 'The owner should be able to remove biblios to their list' ); - is( $public_shelf->can_biblios_be_removed( $patron2->{borrowernumber} ), 1, 'Public list should not be modified (remove) by another staff member' ); - is( $public_shelf->can_biblios_be_removed( $patron3->{borrowernumber} ), 0, 'Public list should not be modified (remove) by someone with no special permissions' ); - is( $public_shelf->can_biblios_be_removed( $patron4->{borrowernumber} ), 0, 'Public list should not be modified (remove) by someone with the edit_public_list sub-permission checked' ); - is( $public_shelf->can_biblios_be_removed( $patron5->{borrowernumber} ), 1, 'Public list should be modified (remove) by someone with the edit_public_list_contents sub-permission checked' ); + is( + $public_shelf->can_biblios_be_removed( $patron1->{borrowernumber} ), 1, + 'The owner should be able to remove biblios to their list' + ); + is( + $public_shelf->can_biblios_be_removed( $patron2->{borrowernumber} ), 1, + 'Public list should not be modified (remove) by another staff member' + ); + is( + $public_shelf->can_biblios_be_removed( $patron3->{borrowernumber} ), 0, + 'Public list should not be modified (remove) by someone with no special permissions' + ); + is( + $public_shelf->can_biblios_be_removed( $patron4->{borrowernumber} ), 0, + 'Public list should not be modified (remove) by someone with the edit_public_list sub-permission checked' + ); + is( + $public_shelf->can_biblios_be_removed( $patron5->{borrowernumber} ), 1, + 'Public list should be modified (remove) by someone with the edit_public_list_contents sub-permission checked' + ); $public_shelf->allow_change_from_permitted_staff(1); $public_shelf->store; - is( $public_shelf->can_be_viewed( $patron1->{borrowernumber} ), 1, 'The owner should be able to view their public list' ); + is( + $public_shelf->can_be_viewed( $patron1->{borrowernumber} ), 1, + 'The owner should be able to view their public list' + ); is( $public_shelf->can_be_viewed( $patron2->{borrowernumber} ), 1, 'Public list should be viewed by staff member' ); - is( $public_shelf->can_be_viewed( $patron3->{borrowernumber} ), 1, 'Public list should be viewed by someone with no special permissions' ); - is( $public_shelf->can_be_viewed( $patron4->{borrowernumber} ), 1, 'Public list should be viewable by someone with the edit_public_lists sub-permission checked' ); - is( $public_shelf->can_be_viewed( $patron5->{borrowernumber} ), 1, 'Public list should be viewable by someone with the edit_public_list_contents sub-permission checked' ); + is( + $public_shelf->can_be_viewed( $patron3->{borrowernumber} ), 1, + 'Public list should be viewed by someone with no special permissions' + ); + is( + $public_shelf->can_be_viewed( $patron4->{borrowernumber} ), 1, + 'Public list should be viewable by someone with the edit_public_lists sub-permission checked' + ); + is( + $public_shelf->can_be_viewed( $patron5->{borrowernumber} ), 1, + 'Public list should be viewable by someone with the edit_public_list_contents sub-permission checked' + ); - is( $public_shelf->can_be_deleted( $patron1->{borrowernumber} ), 1, 'The owner should be able to delete their list' ); - is( $public_shelf->can_be_deleted( $patron2->{borrowernumber} ), 0, 'Public list should not be deleted by another staff member' ); - is( $public_shelf->can_be_deleted( $patron3->{borrowernumber} ), 0, 'Public list should not be deleted by someone with no special permissions' ); - is( $public_shelf->can_be_deleted( $patron4->{borrowernumber} ), 0, 'Public list should not be deleted by someone with the edit_public_lists sub-permission checked' ); - is( $public_shelf->can_be_deleted( $patron5->{borrowernumber} ), 0, 'Public list should not be deleted by someone with the edit_public_list_contents sub-permission checked' ); + is( + $public_shelf->can_be_deleted( $patron1->{borrowernumber} ), 1, + 'The owner should be able to delete their list' + ); + is( + $public_shelf->can_be_deleted( $patron2->{borrowernumber} ), 0, + 'Public list should not be deleted by another staff member' + ); + is( + $public_shelf->can_be_deleted( $patron3->{borrowernumber} ), 0, + 'Public list should not be deleted by someone with no special permissions' + ); + is( + $public_shelf->can_be_deleted( $patron4->{borrowernumber} ), 0, + 'Public list should not be deleted by someone with the edit_public_lists sub-permission checked' + ); + is( + $public_shelf->can_be_deleted( $patron5->{borrowernumber} ), 0, + 'Public list should not be deleted by someone with the edit_public_list_contents sub-permission checked' + ); - is( $public_shelf->can_be_managed( $patron1->{borrowernumber} ), 1, 'The owner should be able to manage their list' ); - is( $public_shelf->can_be_managed( $patron2->{borrowernumber} ), 0, 'Public list should not be managed by another staff member' ); - is( $public_shelf->can_be_managed( $patron3->{borrowernumber} ), 0, 'Public list should not be managed by someone with no special permissions' ); - is( $public_shelf->can_be_managed( $patron4->{borrowernumber} ), 1, 'Public list should be managed by someone with the edit_public_lists sub-permission checked' ); - is( $public_shelf->can_be_managed( $patron5->{borrowernumber} ), 0, 'Public list should be managed by someone with the edit_public_list_contents sub-permission checked' ); + is( + $public_shelf->can_be_managed( $patron1->{borrowernumber} ), 1, + 'The owner should be able to manage their list' + ); + is( + $public_shelf->can_be_managed( $patron2->{borrowernumber} ), 0, + 'Public list should not be managed by another staff member' + ); + is( + $public_shelf->can_be_managed( $patron3->{borrowernumber} ), 0, + 'Public list should not be managed by someone with no special permissions' + ); + is( + $public_shelf->can_be_managed( $patron4->{borrowernumber} ), 1, + 'Public list should be managed by someone with the edit_public_lists sub-permission checked' + ); + is( + $public_shelf->can_be_managed( $patron5->{borrowernumber} ), 0, + 'Public list should be managed by someone with the edit_public_list_contents sub-permission checked' + ); - is( $public_shelf->can_biblios_be_added( $patron1->{borrowernumber} ), 1, 'The owner should be able to add biblios to their list' ); - is( $public_shelf->can_biblios_be_added( $patron2->{borrowernumber} ), 1, 'Public list should be modified (add) by another staff member' ); - is( $public_shelf->can_biblios_be_added( $patron3->{borrowernumber} ), 0, 'Public list should not be modified (add) by someone with no special permissions' ); - is( $public_shelf->can_biblios_be_added( $patron4->{borrowernumber} ), 0, 'Public list should not be modified (add) by someone with the edit_public_lists sub-permission checked' ); - is( $public_shelf->can_biblios_be_added( $patron5->{borrowernumber} ), 1, 'Public list should not be modified (add) by someone with the edit_public_list_contents sub-permission checked' ); + is( + $public_shelf->can_biblios_be_added( $patron1->{borrowernumber} ), 1, + 'The owner should be able to add biblios to their list' + ); + is( + $public_shelf->can_biblios_be_added( $patron2->{borrowernumber} ), 1, + 'Public list should be modified (add) by another staff member' + ); + is( + $public_shelf->can_biblios_be_added( $patron3->{borrowernumber} ), 0, + 'Public list should not be modified (add) by someone with no special permissions' + ); + is( + $public_shelf->can_biblios_be_added( $patron4->{borrowernumber} ), 0, + 'Public list should not be modified (add) by someone with the edit_public_lists sub-permission checked' + ); + is( + $public_shelf->can_biblios_be_added( $patron5->{borrowernumber} ), 1, + 'Public list should not be modified (add) by someone with the edit_public_list_contents sub-permission checked' + ); - is( $public_shelf->can_biblios_be_removed( $patron1->{borrowernumber} ), 1, 'The owner should be able to remove biblios to their list' ); - is( $public_shelf->can_biblios_be_removed( $patron2->{borrowernumber} ), 1, 'Public list should be modified (remove) by another staff member' ); - is( $public_shelf->can_biblios_be_removed( $patron3->{borrowernumber} ), 0, 'Public list should not be modified (remove) by someone with no special permissions' ); - is( $public_shelf->can_biblios_be_removed( $patron4->{borrowernumber} ), 0, 'Public list should not be modified (remove) by someone with the edit_public_list sub-permission checked' ); - is( $public_shelf->can_biblios_be_removed( $patron5->{borrowernumber} ), 1, 'Public list should be modified (remove) by someone with the edit_public_list_contents sub-permission checked' ); + is( + $public_shelf->can_biblios_be_removed( $patron1->{borrowernumber} ), 1, + 'The owner should be able to remove biblios to their list' + ); + is( + $public_shelf->can_biblios_be_removed( $patron2->{borrowernumber} ), 1, + 'Public list should be modified (remove) by another staff member' + ); + is( + $public_shelf->can_biblios_be_removed( $patron3->{borrowernumber} ), 0, + 'Public list should not be modified (remove) by someone with no special permissions' + ); + is( + $public_shelf->can_biblios_be_removed( $patron4->{borrowernumber} ), 0, + 'Public list should not be modified (remove) by someone with the edit_public_list sub-permission checked' + ); + is( + $public_shelf->can_biblios_be_removed( $patron5->{borrowernumber} ), 1, + 'Public list should be modified (remove) by someone with the edit_public_list_contents sub-permission checked' + ); my $private_shelf = Koha::Virtualshelf->new( - { shelfname => "my first shelf", - owner => $patron1->{borrowernumber}, - public => 0, - allow_change_from_owner => 0, - allow_change_from_others => 0, - allow_change_from_staff => 0, + { + shelfname => "my first shelf", + owner => $patron1->{borrowernumber}, + public => 0, + allow_change_from_owner => 0, + allow_change_from_others => 0, + allow_change_from_staff => 0, allow_change_from_permitted_staff => 0 } )->store; is( $private_shelf->can_be_viewed( $patron1->{borrowernumber} ), 1, 'The owner should be able to view their list' ); - is( $private_shelf->can_be_viewed( $patron2->{borrowernumber} ), 0, 'Private list should not be viewed by another staff member' ); - is( $private_shelf->can_be_viewed( $patron3->{borrowernumber} ), 0, 'Private list should not be viewed by someone with no special permissions' ); - is( $private_shelf->can_be_viewed( $patron4->{borrowernumber} ), 0, 'Private list should not be viewed by someone with the edit_public_lists sub-permission checked' ); - is( $private_shelf->can_be_viewed( $patron5->{borrowernumber} ), 0, 'Private list should not be viewed by someone with the edit_public_list_contents sub-permission checked' ); + is( + $private_shelf->can_be_viewed( $patron2->{borrowernumber} ), 0, + 'Private list should not be viewed by another staff member' + ); + is( + $private_shelf->can_be_viewed( $patron3->{borrowernumber} ), 0, + 'Private list should not be viewed by someone with no special permissions' + ); + is( + $private_shelf->can_be_viewed( $patron4->{borrowernumber} ), 0, + 'Private list should not be viewed by someone with the edit_public_lists sub-permission checked' + ); + is( + $private_shelf->can_be_viewed( $patron5->{borrowernumber} ), 0, + 'Private list should not be viewed by someone with the edit_public_list_contents sub-permission checked' + ); - is( $private_shelf->can_be_deleted( $patron1->{borrowernumber} ), 1, 'The owner should be able to delete their list' ); - is( $private_shelf->can_be_deleted( $patron2->{borrowernumber} ), 0, 'Private list should not be deleted by another staff member' ); - is( $private_shelf->can_be_deleted( $patron3->{borrowernumber} ), 0, 'Private list should not be deleted by someone with no special permissions' ); - is( $private_shelf->can_be_deleted( $patron4->{borrowernumber} ), 0, 'Private list should not be deleted by someone with the edit_public_lists sub-permission checked' ); - is( $private_shelf->can_be_deleted( $patron5->{borrowernumber} ), 0, 'Private list should not be deleted by someome with the edit_public_list_contents sub-permission checked' ); + is( + $private_shelf->can_be_deleted( $patron1->{borrowernumber} ), 1, + 'The owner should be able to delete their list' + ); + is( + $private_shelf->can_be_deleted( $patron2->{borrowernumber} ), 0, + 'Private list should not be deleted by another staff member' + ); + is( + $private_shelf->can_be_deleted( $patron3->{borrowernumber} ), 0, + 'Private list should not be deleted by someone with no special permissions' + ); + is( + $private_shelf->can_be_deleted( $patron4->{borrowernumber} ), 0, + 'Private list should not be deleted by someone with the edit_public_lists sub-permission checked' + ); + is( + $private_shelf->can_be_deleted( $patron5->{borrowernumber} ), 0, + 'Private list should not be deleted by someome with the edit_public_list_contents sub-permission checked' + ); - is( $private_shelf->can_be_managed( $patron1->{borrowernumber} ), 1, 'The owner should be able to manage their list' ); - is( $private_shelf->can_be_managed( $patron2->{borrowernumber} ), 0, 'Private list should not be managed by another staff member' ); - is( $private_shelf->can_be_managed( $patron3->{borrowernumber} ), 0, 'Private list should not be managed by someone with no special permissions' ); - is( $private_shelf->can_be_managed( $patron4->{borrowernumber} ), 0, 'Private list should not be managed by someone with the edit_public_lists sub-permission checked' ); - is( $private_shelf->can_be_managed( $patron5->{borrowernumber} ), 0, 'Private list should not be managed by someone with the edit_public_list_contents sub-permission checked' ); + is( + $private_shelf->can_be_managed( $patron1->{borrowernumber} ), 1, + 'The owner should be able to manage their list' + ); + is( + $private_shelf->can_be_managed( $patron2->{borrowernumber} ), 0, + 'Private list should not be managed by another staff member' + ); + is( + $private_shelf->can_be_managed( $patron3->{borrowernumber} ), 0, + 'Private list should not be managed by someone with no special permissions' + ); + is( + $private_shelf->can_be_managed( $patron4->{borrowernumber} ), 0, + 'Private list should not be managed by someone with the edit_public_lists sub-permission checked' + ); + is( + $private_shelf->can_be_managed( $patron5->{borrowernumber} ), 0, + 'Private list should not be managed by someone with the edit_public_list_contents sub-permission checked' + ); - is( $private_shelf->can_biblios_be_added( $patron1->{borrowernumber} ), 0, 'The owner should not be able to add biblios to their list' ); - is( $private_shelf->can_biblios_be_added( $patron2->{borrowernumber} ), 0, 'Private list should not be modified (add) by another staff member' ); - is( $private_shelf->can_biblios_be_added( $patron3->{borrowernumber} ), 0, 'Private list should not be modified (add) by someone with no special permissions' ); - is( $private_shelf->can_biblios_be_added( $patron4->{borrowernumber} ), 0, 'Private list should not be modified (add) by someone with the edit_public_lists sub-permission checked' ); - is( $private_shelf->can_biblios_be_added( $patron5->{borrowernumber} ), 0, 'Private list should not be modified (add) by someone with the edit_public_list_contents sub-permission checked' ); + is( + $private_shelf->can_biblios_be_added( $patron1->{borrowernumber} ), 0, + 'The owner should not be able to add biblios to their list' + ); + is( + $private_shelf->can_biblios_be_added( $patron2->{borrowernumber} ), 0, + 'Private list should not be modified (add) by another staff member' + ); + is( + $private_shelf->can_biblios_be_added( $patron3->{borrowernumber} ), 0, + 'Private list should not be modified (add) by someone with no special permissions' + ); + is( + $private_shelf->can_biblios_be_added( $patron4->{borrowernumber} ), 0, + 'Private list should not be modified (add) by someone with the edit_public_lists sub-permission checked' + ); + is( + $private_shelf->can_biblios_be_added( $patron5->{borrowernumber} ), 0, + 'Private list should not be modified (add) by someone with the edit_public_list_contents sub-permission checked' + ); - is( $private_shelf->can_biblios_be_removed( $patron1->{borrowernumber} ), 0, 'The owner should not be able to remove biblios to their list' ); - is( $private_shelf->can_biblios_be_removed( $patron2->{borrowernumber} ), 0, 'Private list should not be modified (remove) by another staff member' ); - is( $private_shelf->can_biblios_be_removed( $patron3->{borrowernumber} ), 0, 'Private list should not be modified (remove) by someone with no special permissions' ); - is( $private_shelf->can_biblios_be_removed( $patron4->{borrowernumber} ), 0, 'Private list should not be modified (remove) by someone with the edit_public_lists sub-permissions' ); - is( $private_shelf->can_biblios_be_removed( $patron5->{borrowernumber} ), 0, 'Private list should not be modified (remove) by someone with the edit_public_list_contents sub-permissions' ); + is( + $private_shelf->can_biblios_be_removed( $patron1->{borrowernumber} ), 0, + 'The owner should not be able to remove biblios to their list' + ); + is( + $private_shelf->can_biblios_be_removed( $patron2->{borrowernumber} ), 0, + 'Private list should not be modified (remove) by another staff member' + ); + is( + $private_shelf->can_biblios_be_removed( $patron3->{borrowernumber} ), 0, + 'Private list should not be modified (remove) by someone with no special permissions' + ); + is( + $private_shelf->can_biblios_be_removed( $patron4->{borrowernumber} ), 0, + 'Private list should not be modified (remove) by someone with the edit_public_lists sub-permissions' + ); + is( + $private_shelf->can_biblios_be_removed( $patron5->{borrowernumber} ), 0, + 'Private list should not be modified (remove) by someone with the edit_public_list_contents sub-permissions' + ); $private_shelf->allow_change_from_owner(1); $private_shelf->allow_change_from_staff(1); @@ -518,132 +956,289 @@ subtest 'Shelf permissions' => sub { $private_shelf->allow_change_from_permitted_staff(0); $private_shelf->store; is( $private_shelf->can_be_viewed( $patron1->{borrowernumber} ), 1, 'The owner should be able to view their list' ); - is( $private_shelf->can_be_viewed( $patron2->{borrowernumber} ), 0, 'Private list should not be viewed by another staff member' ); - is( $private_shelf->can_be_viewed( $patron3->{borrowernumber} ), 0, 'Private list should not be viewed by someone with no special permissions' ); - is( $private_shelf->can_be_viewed( $patron4->{borrowernumber} ), 0, 'Private list should not be viewed by someone with the edit_public_lists sub-permission checked' ); - is( $private_shelf->can_be_viewed( $patron5->{borrowernumber} ), 0, 'Private list should not be viewed by someone with the edit_public_list_contents sub-permission checked' ); + is( + $private_shelf->can_be_viewed( $patron2->{borrowernumber} ), 0, + 'Private list should not be viewed by another staff member' + ); + is( + $private_shelf->can_be_viewed( $patron3->{borrowernumber} ), 0, + 'Private list should not be viewed by someone with no special permissions' + ); + is( + $private_shelf->can_be_viewed( $patron4->{borrowernumber} ), 0, + 'Private list should not be viewed by someone with the edit_public_lists sub-permission checked' + ); + is( + $private_shelf->can_be_viewed( $patron5->{borrowernumber} ), 0, + 'Private list should not be viewed by someone with the edit_public_list_contents sub-permission checked' + ); - is( $private_shelf->can_be_deleted( $patron1->{borrowernumber} ), 1, 'The owner should be able to delete their list' ); - is( $private_shelf->can_be_deleted( $patron2->{borrowernumber} ), 0, 'Private list should not be deleted by another staff member' ); - is( $private_shelf->can_be_deleted( $patron3->{borrowernumber} ), 0, 'Private list should not be deleted by someone with no special permissions' ); - is( $private_shelf->can_be_deleted( $patron4->{borrowernumber} ), 0, 'Private list should not be deleted by someone with the edit_public_lists sub-permission checked' ); - is( $private_shelf->can_be_deleted( $patron5->{borrowernumber} ), 0, 'Private list should not be viewed by someone with the edit_public_list_contents sub-permission checked' ); + is( + $private_shelf->can_be_deleted( $patron1->{borrowernumber} ), 1, + 'The owner should be able to delete their list' + ); + is( + $private_shelf->can_be_deleted( $patron2->{borrowernumber} ), 0, + 'Private list should not be deleted by another staff member' + ); + is( + $private_shelf->can_be_deleted( $patron3->{borrowernumber} ), 0, + 'Private list should not be deleted by someone with no special permissions' + ); + is( + $private_shelf->can_be_deleted( $patron4->{borrowernumber} ), 0, + 'Private list should not be deleted by someone with the edit_public_lists sub-permission checked' + ); + is( + $private_shelf->can_be_deleted( $patron5->{borrowernumber} ), 0, + 'Private list should not be viewed by someone with the edit_public_list_contents sub-permission checked' + ); - is( $private_shelf->can_be_managed( $patron1->{borrowernumber} ), 1, 'The owner should be able to manage their list' ); - is( $private_shelf->can_be_managed( $patron2->{borrowernumber} ), 0, 'Private list should not be managed by another staff member' ); - is( $private_shelf->can_be_managed( $patron3->{borrowernumber} ), 0, 'Private list should not be managed by someone with no special permissions' ); - is( $private_shelf->can_be_managed( $patron4->{borrowernumber} ), 0, 'Private list should not be managed by someone with the edit_public_lists sub-permission checked' ); - is( $private_shelf->can_be_managed( $patron5->{borrowernumber} ), 0, 'Private list should not be managed by someone with the edit_public_list_contents sub-permission checked' ); + is( + $private_shelf->can_be_managed( $patron1->{borrowernumber} ), 1, + 'The owner should be able to manage their list' + ); + is( + $private_shelf->can_be_managed( $patron2->{borrowernumber} ), 0, + 'Private list should not be managed by another staff member' + ); + is( + $private_shelf->can_be_managed( $patron3->{borrowernumber} ), 0, + 'Private list should not be managed by someone with no special permissions' + ); + is( + $private_shelf->can_be_managed( $patron4->{borrowernumber} ), 0, + 'Private list should not be managed by someone with the edit_public_lists sub-permission checked' + ); + is( + $private_shelf->can_be_managed( $patron5->{borrowernumber} ), 0, + 'Private list should not be managed by someone with the edit_public_list_contents sub-permission checked' + ); - is( $private_shelf->can_biblios_be_added( $patron1->{borrowernumber} ), 1, 'The owner should be able to add biblios to their list' ); - is( $private_shelf->can_biblios_be_added( $patron2->{borrowernumber} ), 1, 'Private list should be modified (add) by another staff member # individual check done later' ); - is( $private_shelf->can_biblios_be_added( $patron3->{borrowernumber} ), 0, 'Private list should not be modified (add) by someone with no special permissions' ); - is ( $private_shelf->can_biblios_be_added( $patron4->{borrowernumber} ), 0, 'Private list should not be modified (add) by someone with the edit_public_lists sub-permission checked' ); - is( $private_shelf->can_biblios_be_added( $patron5->{borrowernumber} ), 1, 'Private list should be modififed (add) by someone with the edit_public_list_contents sub-permission checked' ); + is( + $private_shelf->can_biblios_be_added( $patron1->{borrowernumber} ), 1, + 'The owner should be able to add biblios to their list' + ); + is( + $private_shelf->can_biblios_be_added( $patron2->{borrowernumber} ), 1, + 'Private list should be modified (add) by another staff member # individual check done later' + ); + is( + $private_shelf->can_biblios_be_added( $patron3->{borrowernumber} ), 0, + 'Private list should not be modified (add) by someone with no special permissions' + ); + is( + $private_shelf->can_biblios_be_added( $patron4->{borrowernumber} ), 0, + 'Private list should not be modified (add) by someone with the edit_public_lists sub-permission checked' + ); + is( + $private_shelf->can_biblios_be_added( $patron5->{borrowernumber} ), 1, + 'Private list should be modififed (add) by someone with the edit_public_list_contents sub-permission checked' + ); - is( $private_shelf->can_biblios_be_removed( $patron1->{borrowernumber} ), 1, 'The owner should be able to remove biblios to their list' ); - is( $private_shelf->can_biblios_be_removed( $patron2->{borrowernumber} ), 1, 'Private list should be modified (remove) by another staff member # individual check done later' ); - is( $private_shelf->can_biblios_be_removed( $patron3->{borrowernumber} ), 0, 'Private list should not be modified (remove) by someone with no special permissions' ); - is( $private_shelf->can_biblios_be_removed( $patron4->{borrowernumber} ), 0, 'Private list should not be modified (remove) by someone with the edit_public_lists sub-permission checked' ); - is( $private_shelf->can_biblios_be_removed( $patron5->{borrowernumber} ), 1, 'Private list should be modified (remove) by someone with the edit_public_list_contents sub-permission checked' ); + is( + $private_shelf->can_biblios_be_removed( $patron1->{borrowernumber} ), 1, + 'The owner should be able to remove biblios to their list' + ); + is( + $private_shelf->can_biblios_be_removed( $patron2->{borrowernumber} ), 1, + 'Private list should be modified (remove) by another staff member # individual check done later' + ); + is( + $private_shelf->can_biblios_be_removed( $patron3->{borrowernumber} ), 0, + 'Private list should not be modified (remove) by someone with no special permissions' + ); + is( + $private_shelf->can_biblios_be_removed( $patron4->{borrowernumber} ), 0, + 'Private list should not be modified (remove) by someone with the edit_public_lists sub-permission checked' + ); + is( + $private_shelf->can_biblios_be_removed( $patron5->{borrowernumber} ), 1, + 'Private list should be modified (remove) by someone with the edit_public_list_contents sub-permission checked' + ); $private_shelf->allow_change_from_owner(1); $private_shelf->allow_change_from_others(1); $private_shelf->store; is( $private_shelf->can_be_viewed( $patron1->{borrowernumber} ), 1, 'The owner should be able to view their list' ); - is( $private_shelf->can_be_viewed( $patron2->{borrowernumber} ), 0, 'Private list should not be viewed by another staff member' ); - is( $private_shelf->can_be_viewed( $patron3->{borrowernumber} ), 0, 'Private list should not be viewed by someone with no special permissions' ); - is( $private_shelf->can_be_viewed( $patron4->{borrowernumber} ), 0, 'Private list should not be viewed by someone with the edit_public_lists sub-permission checked' ); - is( $private_shelf->can_be_viewed( $patron5->{borrowernumber} ), 0, 'Private list should not be viewed by someome with the edit_public_list_contents sub-permission checked' ); + is( + $private_shelf->can_be_viewed( $patron2->{borrowernumber} ), 0, + 'Private list should not be viewed by another staff member' + ); + is( + $private_shelf->can_be_viewed( $patron3->{borrowernumber} ), 0, + 'Private list should not be viewed by someone with no special permissions' + ); + is( + $private_shelf->can_be_viewed( $patron4->{borrowernumber} ), 0, + 'Private list should not be viewed by someone with the edit_public_lists sub-permission checked' + ); + is( + $private_shelf->can_be_viewed( $patron5->{borrowernumber} ), 0, + 'Private list should not be viewed by someome with the edit_public_list_contents sub-permission checked' + ); - is( $private_shelf->can_be_deleted( $patron1->{borrowernumber} ), 1, 'The owner should be able to delete their list' ); - is( $private_shelf->can_be_deleted( $patron2->{borrowernumber} ), 0, 'Private list should not be deleted by another staff member' ); - is( $private_shelf->can_be_deleted( $patron3->{borrowernumber} ), 0, 'Private list should not be deleted by someone with no special permissions' ); - is( $private_shelf->can_be_deleted( $patron4->{borrowernumber} ), 0, 'Private list should not be deleted by someone with the edit_public_lists sub-permission checked' ); - is( $private_shelf->can_be_deleted( $patron5->{borrowernumber} ), 0, 'Private list should not be deleted by someone with the edit_public_list_contents sub-permission checked' ); + is( + $private_shelf->can_be_deleted( $patron1->{borrowernumber} ), 1, + 'The owner should be able to delete their list' + ); + is( + $private_shelf->can_be_deleted( $patron2->{borrowernumber} ), 0, + 'Private list should not be deleted by another staff member' + ); + is( + $private_shelf->can_be_deleted( $patron3->{borrowernumber} ), 0, + 'Private list should not be deleted by someone with no special permissions' + ); + is( + $private_shelf->can_be_deleted( $patron4->{borrowernumber} ), 0, + 'Private list should not be deleted by someone with the edit_public_lists sub-permission checked' + ); + is( + $private_shelf->can_be_deleted( $patron5->{borrowernumber} ), 0, + 'Private list should not be deleted by someone with the edit_public_list_contents sub-permission checked' + ); - is( $private_shelf->can_be_managed( $patron1->{borrowernumber} ), 1, 'The owner should be able to manage their list' ); - is( $private_shelf->can_be_managed( $patron2->{borrowernumber} ), 0, 'Private list should not be managed by another staff member' ); - is( $private_shelf->can_be_managed( $patron3->{borrowernumber} ), 0, 'Private list should not be managed by someone with no special permissions' ); - is( $private_shelf->can_be_managed( $patron4->{borrowernumber} ), 0, 'Private list should not be managed by someone with the edit_public_lists sub-permission checked' ); - is( $private_shelf->can_be_managed( $patron5->{borrowernumber} ), 0, 'Private list should not be managed by someone with the edit_public_list_contents sub-permission checked' ); + is( + $private_shelf->can_be_managed( $patron1->{borrowernumber} ), 1, + 'The owner should be able to manage their list' + ); + is( + $private_shelf->can_be_managed( $patron2->{borrowernumber} ), 0, + 'Private list should not be managed by another staff member' + ); + is( + $private_shelf->can_be_managed( $patron3->{borrowernumber} ), 0, + 'Private list should not be managed by someone with no special permissions' + ); + is( + $private_shelf->can_be_managed( $patron4->{borrowernumber} ), 0, + 'Private list should not be managed by someone with the edit_public_lists sub-permission checked' + ); + is( + $private_shelf->can_be_managed( $patron5->{borrowernumber} ), 0, + 'Private list should not be managed by someone with the edit_public_list_contents sub-permission checked' + ); - is( $private_shelf->can_biblios_be_added( $patron1->{borrowernumber} ), 1, 'The owner should be able to add biblios to their list' ); - is( $private_shelf->can_biblios_be_added( $patron2->{borrowernumber} ), 1, 'Private list could be modified (add) by another staff member # individual check done later' ); - is( $private_shelf->can_biblios_be_added( $patron3->{borrowernumber} ), 1, 'Private list could be modified (add) by someone with no special permissions' ); - is( $private_shelf->can_biblios_be_added( $patron4->{borrowernumber} ), 1, 'Private list could be modified (add) by someone with the edit_public_lists sub-permission checked' ); - is( $private_shelf->can_biblios_be_added( $patron5->{borrowernumber} ), 1, 'Private list could be modified (add) by someone with the edit_public_list_contents sub-permission checked' ); + is( + $private_shelf->can_biblios_be_added( $patron1->{borrowernumber} ), 1, + 'The owner should be able to add biblios to their list' + ); + is( + $private_shelf->can_biblios_be_added( $patron2->{borrowernumber} ), 1, + 'Private list could be modified (add) by another staff member # individual check done later' + ); + is( + $private_shelf->can_biblios_be_added( $patron3->{borrowernumber} ), 1, + 'Private list could be modified (add) by someone with no special permissions' + ); + is( + $private_shelf->can_biblios_be_added( $patron4->{borrowernumber} ), 1, + 'Private list could be modified (add) by someone with the edit_public_lists sub-permission checked' + ); + is( + $private_shelf->can_biblios_be_added( $patron5->{borrowernumber} ), 1, + 'Private list could be modified (add) by someone with the edit_public_list_contents sub-permission checked' + ); - is( $private_shelf->can_biblios_be_removed( $patron1->{borrowernumber} ), 1, 'The owner should be able to remove biblios to their list' ); - is( $private_shelf->can_biblios_be_removed( $patron2->{borrowernumber} ), 1, 'Private list could be modified (remove) by another staff member # individual check done later' ); - is( $private_shelf->can_biblios_be_removed( $patron3->{borrowernumber} ), 1, 'Private list could be modified (remove) by someone with no special permissions' ); - is( $private_shelf->can_biblios_be_removed( $patron4->{borrowernumber} ), 1, 'Private list could be modified (remove) by someone with the edit_public_lists sub-permission checked' ); - is( $private_shelf->can_biblios_be_removed( $patron5->{borrowernumber} ), 1, 'Private list could be modified (remove) by someone with the edit_public_list_contents sub-permission checked' ); + is( + $private_shelf->can_biblios_be_removed( $patron1->{borrowernumber} ), 1, + 'The owner should be able to remove biblios to their list' + ); + is( + $private_shelf->can_biblios_be_removed( $patron2->{borrowernumber} ), 1, + 'Private list could be modified (remove) by another staff member # individual check done later' + ); + is( + $private_shelf->can_biblios_be_removed( $patron3->{borrowernumber} ), 1, + 'Private list could be modified (remove) by someone with no special permissions' + ); + is( + $private_shelf->can_biblios_be_removed( $patron4->{borrowernumber} ), 1, + 'Private list could be modified (remove) by someone with the edit_public_lists sub-permission checked' + ); + is( + $private_shelf->can_biblios_be_removed( $patron5->{borrowernumber} ), 1, + 'Private list could be modified (remove) by someone with the edit_public_list_contents sub-permission checked' + ); teardown(); }; subtest 'Get shelves' => sub { plan tests => 5; - my $patron1 = $builder->build({ - source => 'Borrower', - }); - my $patron2 = $builder->build({ - source => 'Borrower', - }); + my $patron1 = $builder->build( + { + source => 'Borrower', + } + ); + my $patron2 = $builder->build( + { + source => 'Borrower', + } + ); - my $private_shelf1_1 = Koha::Virtualshelf->new({ + my $private_shelf1_1 = Koha::Virtualshelf->new( + { shelfname => "private shelf 1 for patron 1", - owner => $patron1->{borrowernumber}, - public => 0, + owner => $patron1->{borrowernumber}, + public => 0, } )->store; - my $private_shelf1_2 = Koha::Virtualshelf->new({ + my $private_shelf1_2 = Koha::Virtualshelf->new( + { shelfname => "private shelf 2 for patron 1", - owner => $patron1->{borrowernumber}, - public => 0, + owner => $patron1->{borrowernumber}, + public => 0, } )->store; - my $private_shelf2_1 = Koha::Virtualshelf->new({ + my $private_shelf2_1 = Koha::Virtualshelf->new( + { shelfname => "private shelf 1 for patron 2", - owner => $patron2->{borrowernumber}, - public => 0, + owner => $patron2->{borrowernumber}, + public => 0, } )->store; - my $public_shelf1_1 = Koha::Virtualshelf->new({ + my $public_shelf1_1 = Koha::Virtualshelf->new( + { shelfname => "public shelf 1 for patron 1", - owner => $patron1->{borrowernumber}, - public => 1, + owner => $patron1->{borrowernumber}, + public => 1, } )->store; - my $public_shelf1_2 = Koha::Virtualshelf->new({ + my $public_shelf1_2 = Koha::Virtualshelf->new( + { shelfname => "public shelf 2 for patron 1", - owner => $patron1->{borrowernumber}, - public => 1, + owner => $patron1->{borrowernumber}, + public => 1, } )->store; - my $shelf_to_share = Koha::Virtualshelf->new({ + my $shelf_to_share = Koha::Virtualshelf->new( + { shelfname => "shared shelf", - owner => $patron1->{borrowernumber}, - public => 0, + owner => $patron1->{borrowernumber}, + public => 0, } )->store; my $private_shelves = Koha::Virtualshelves->get_private_shelves; is( $private_shelves->count, 0, 'Without borrowernumber given, get_private_shelves should not return any shelf' ); - $private_shelves = Koha::Virtualshelves->get_private_shelves({ borrowernumber => $patron1->{borrowernumber} }); + $private_shelves = Koha::Virtualshelves->get_private_shelves( { borrowernumber => $patron1->{borrowernumber} } ); is( $private_shelves->count, 3, 'get_private_shelves should return all shelves for a given patron' ); - $private_shelf2_1->share('a key')->accept('a key', $patron1->{borrowernumber}); - $private_shelves = Koha::Virtualshelves->get_private_shelves({ borrowernumber => $patron1->{borrowernumber} }); - is( $private_shelves->count, 4, 'get_private_shelves should return all shelves for a given patron, even the shared ones' ); + $private_shelf2_1->share('a key')->accept( 'a key', $patron1->{borrowernumber} ); + $private_shelves = Koha::Virtualshelves->get_private_shelves( { borrowernumber => $patron1->{borrowernumber} } ); + is( + $private_shelves->count, 4, + 'get_private_shelves should return all shelves for a given patron, even the shared ones' + ); my $public_shelves = Koha::Virtualshelves->get_public_shelves; is( $public_shelves->count, 2, 'get_public_shelves should return all public shelves, no matter who is the owner' ); - my $shared_shelf = eval { $shelf_to_share->share("valid key") }; - my $shared_shelves = Koha::Virtualshelfshares->search({ borrowernumber => $patron1->{borrowernumber} }); + my $shared_shelf = eval { $shelf_to_share->share("valid key") }; + my $shared_shelves = Koha::Virtualshelfshares->search( { borrowernumber => $patron1->{borrowernumber} } ); is( $shared_shelves->count, 1, 'Found the share for patron1' ); teardown(); @@ -660,21 +1255,24 @@ subtest 'Get shelves containing biblios' => sub { my $biblio4 = $builder->build_sample_biblio; my $shelf1 = Koha::Virtualshelf->new( - { shelfname => "my first shelf", - owner => $patron1->{borrowernumber}, - public => 0, + { + shelfname => "my first shelf", + owner => $patron1->{borrowernumber}, + public => 0, } )->store; my $shelf2 = Koha::Virtualshelf->new( - { shelfname => "my x second shelf", # 'x' to make it sorted after 'third' - owner => $patron2->{borrowernumber}, - public => 0, + { + shelfname => "my x second shelf", # 'x' to make it sorted after 'third' + owner => $patron2->{borrowernumber}, + public => 0, } )->store; my $shelf3 = Koha::Virtualshelf->new( - { shelfname => "my third shelf", - owner => $patron1->{borrowernumber}, - public => 1, + { + shelfname => "my third shelf", + owner => $patron1->{borrowernumber}, + public => 1, } )->store; @@ -690,49 +1288,67 @@ subtest 'Get shelves containing biblios' => sub { biblionumber => $biblio1->biblionumber, } ); - is ( $shelves_with_biblio1_for_any_patrons->count, 0, 'shelf1 is private and should not be displayed if patron is not logged in' ); + is( + $shelves_with_biblio1_for_any_patrons->count, 0, + 'shelf1 is private and should not be displayed if patron is not logged in' + ); my $shelves_with_biblio4_for_any_patrons = Koha::Virtualshelves->get_shelves_containing_record( { biblionumber => $biblio4->biblionumber, } ); - is ( $shelves_with_biblio4_for_any_patrons->count, 1, 'shelf3 is public and should be displayed for any patrons' ); - is ( $shelves_with_biblio4_for_any_patrons->next->shelfname, $shelf3->shelfname, 'The correct shelf (3) should be displayed' ); + is( $shelves_with_biblio4_for_any_patrons->count, 1, 'shelf3 is public and should be displayed for any patrons' ); + is( + $shelves_with_biblio4_for_any_patrons->next->shelfname, $shelf3->shelfname, + 'The correct shelf (3) should be displayed' + ); my $shelves_with_biblio1_for_other_patrons = Koha::Virtualshelves->get_shelves_containing_record( { - biblionumber => $biblio1->biblionumber, + biblionumber => $biblio1->biblionumber, borrowernumber => $patron2->{borrowernumber}, } ); - is ( $shelves_with_biblio1_for_other_patrons->count, 0, 'shelf1 is private and should not be displayed for other patrons' ); + is( + $shelves_with_biblio1_for_other_patrons->count, 0, + 'shelf1 is private and should not be displayed for other patrons' + ); my $shelves_with_biblio1_for_owner = Koha::Virtualshelves->get_shelves_containing_record( { - biblionumber => $biblio1->biblionumber, + biblionumber => $biblio1->biblionumber, borrowernumber => $patron1->{borrowernumber}, } ); - is ( $shelves_with_biblio1_for_owner->count, 1, 'shelf1 is private and should be displayed for the owner' ); + is( $shelves_with_biblio1_for_owner->count, 1, 'shelf1 is private and should be displayed for the owner' ); my $shelves_with_biblio2_for_patron1 = Koha::Virtualshelves->get_shelves_containing_record( { - biblionumber => $biblio2->biblionumber, + biblionumber => $biblio2->biblionumber, borrowernumber => $patron1->{borrowernumber}, } ); - is ( $shelves_with_biblio2_for_patron1->count, 1, 'Only shelf1 should be displayed for patron 1 and biblio 1' ); - is ( $shelves_with_biblio2_for_patron1->next->shelfname, $shelf1->shelfname, 'The correct shelf (1) should be displayed for patron 1' ); + is( $shelves_with_biblio2_for_patron1->count, 1, 'Only shelf1 should be displayed for patron 1 and biblio 1' ); + is( + $shelves_with_biblio2_for_patron1->next->shelfname, $shelf1->shelfname, + 'The correct shelf (1) should be displayed for patron 1' + ); my $shelves_with_biblio4_for_patron2 = Koha::Virtualshelves->get_shelves_containing_record( { - biblionumber => $biblio4->biblionumber, + biblionumber => $biblio4->biblionumber, borrowernumber => $patron2->{borrowernumber}, } ); - is ( $shelves_with_biblio4_for_patron2->count, 2, 'Patron should shown private and public lists for a given biblio' ); - is ( $shelves_with_biblio4_for_patron2->next->shelfname, $shelf3->shelfname, 'The shelves should be sorted by shelfname' ); + is( + $shelves_with_biblio4_for_patron2->count, 2, + 'Patron should shown private and public lists for a given biblio' + ); + is( + $shelves_with_biblio4_for_patron2->next->shelfname, $shelf3->shelfname, + 'The shelves should be sorted by shelfname' + ); teardown(); }; @@ -741,16 +1357,16 @@ subtest 'cannot_be_transferred' => sub { plan tests => 12; # Three patrons and a deleted one - my $staff = $builder->build_object({ class => 'Koha::Patrons', value => { flags => undef } }); - my $listowner = $builder->build_object({ class => 'Koha::Patrons' }); - my $receiver = $builder->build_object({ class => 'Koha::Patrons' }); - my $removed_patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $staff = $builder->build_object( { class => 'Koha::Patrons', value => { flags => undef } } ); + my $listowner = $builder->build_object( { class => 'Koha::Patrons' } ); + my $receiver = $builder->build_object( { class => 'Koha::Patrons' } ); + my $removed_patron = $builder->build_object( { class => 'Koha::Patrons' } ); $removed_patron->delete; # Create three lists - my $private_list = Koha::Virtualshelf->new({ shelfname => "A", owner => $listowner->id })->store; - my $public_list = Koha::Virtualshelf->new({ shelfname => "B", public => 1, owner => $listowner->id })->store; - my $shared_list = Koha::Virtualshelf->new({ shelfname => "C", owner => $listowner->id })->store; + my $private_list = Koha::Virtualshelf->new( { shelfname => "A", owner => $listowner->id } )->store; + my $public_list = Koha::Virtualshelf->new( { shelfname => "B", public => 1, owner => $listowner->id } )->store; + my $shared_list = Koha::Virtualshelf->new( { shelfname => "C", owner => $listowner->id } )->store; $shared_list->share("key")->accept( "key", $receiver->id ); # Test on private list @@ -758,24 +1374,59 @@ subtest 'cannot_be_transferred' => sub { # Test on public list is( $public_list->cannot_be_transferred, 'missing_by_parameter', 'Public list, no parameters' ); - is( $public_list->cannot_be_transferred({ by => $staff->id, to => $receiver->id }), 'unauthorized_transfer', 'Lacks permission' ); - my $perms = $builder->build({ source => 'UserPermission', value => { - borrowernumber => $staff->id, module_bit => 20, code => 'edit_public_lists', - }}); - is( $public_list->cannot_be_transferred({ by => $staff->id, to => $receiver->id }), 0, 'Minimum permission passes' ); + is( + $public_list->cannot_be_transferred( { by => $staff->id, to => $receiver->id } ), 'unauthorized_transfer', + 'Lacks permission' + ); + my $perms = $builder->build( + { + source => 'UserPermission', + value => { + borrowernumber => $staff->id, module_bit => 20, code => 'edit_public_lists', + } + } + ); + is( + $public_list->cannot_be_transferred( { by => $staff->id, to => $receiver->id } ), 0, + 'Minimum permission passes' + ); $staff->flags(1)->store; - is( $public_list->cannot_be_transferred({ by => $staff->id, to => $receiver->id }), 0, 'Superlibrarian permission passes' ); - is( $public_list->cannot_be_transferred({ by => $staff->id, to => $receiver->id, interface => 'opac' }), 'unauthorized_transfer', - 'Not supported on OPAC' ); - is( $public_list->cannot_be_transferred({ by => $staff->id, to => $removed_patron->id }), 'new_owner_not_found', 'Removed patron cannot own' ); + is( + $public_list->cannot_be_transferred( { by => $staff->id, to => $receiver->id } ), 0, + 'Superlibrarian permission passes' + ); + is( + $public_list->cannot_be_transferred( { by => $staff->id, to => $receiver->id, interface => 'opac' } ), + 'unauthorized_transfer', + 'Not supported on OPAC' + ); + is( + $public_list->cannot_be_transferred( { by => $staff->id, to => $removed_patron->id } ), 'new_owner_not_found', + 'Removed patron cannot own' + ); # Test on shared list - is( $shared_list->cannot_be_transferred({ by => $staff->id }), 'unauthorized_transfer', 'Shared list, transfer limited to owner' ); - is( $shared_list->cannot_be_transferred({ by => $receiver->id }), 'unauthorized_transfer', 'Shared list, transfer still limited to owner' ); - is( $shared_list->cannot_be_transferred({ by => $listowner->id, to => $receiver->id }), 0, 'sharee could become owner' ); - is( $shared_list->cannot_be_transferred({ by => $listowner->id, to => $receiver->id, interface => 'intranet' }), 'unauthorized_transfer', - 'Intranet not supported' ); - is( $shared_list->cannot_be_transferred({ by => $listowner->id, to => $staff->id }), 'new_owner_has_no_share', 'staff has no share' ); + is( + $shared_list->cannot_be_transferred( { by => $staff->id } ), 'unauthorized_transfer', + 'Shared list, transfer limited to owner' + ); + is( + $shared_list->cannot_be_transferred( { by => $receiver->id } ), 'unauthorized_transfer', + 'Shared list, transfer still limited to owner' + ); + is( + $shared_list->cannot_be_transferred( { by => $listowner->id, to => $receiver->id } ), 0, + 'sharee could become owner' + ); + is( + $shared_list->cannot_be_transferred( { by => $listowner->id, to => $receiver->id, interface => 'intranet' } ), + 'unauthorized_transfer', + 'Intranet not supported' + ); + is( + $shared_list->cannot_be_transferred( { by => $listowner->id, to => $staff->id } ), 'new_owner_has_no_share', + 'staff has no share' + ); }; $schema->storage->txn_rollback; diff --git a/t/db_dependent/XISBN.t b/t/db_dependent/XISBN.t index 0633d3402c..1d170541da 100755 --- a/t/db_dependent/XISBN.t +++ b/t/db_dependent/XISBN.t @@ -9,7 +9,7 @@ use Test::More tests => 6; use List::MoreUtils qw(any none); use MARC::Record; use C4::Biblio qw( GetMarcFromKohaField AddBiblio ); -use C4::XISBN qw( get_xisbns ); +use C4::XISBN qw( get_xisbns ); use C4::Context; use C4::Search; use Koha::Database; @@ -17,31 +17,32 @@ use t::lib::Mocks; use Test::MockModule; BEGIN { - use_ok('C4::XISBN', qw( get_xisbns )); + use_ok( 'C4::XISBN', qw( get_xisbns ) ); } my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; -my $engine = C4::Context->preference("SearchEngine") // 'Zebra'; +my $engine = C4::Context->preference("SearchEngine") // 'Zebra'; my $search_module = Test::MockModule->new("Koha::SearchEngine::${engine}::Search"); -$search_module->mock('simple_search_compat', \&Mock_simple_search_compat ); +$search_module->mock( 'simple_search_compat', \&Mock_simple_search_compat ); my $context = C4::Context->new; -my ( $biblionumber_tag, $biblionumber_subfield ) = - GetMarcFromKohaField( 'biblio.biblionumber' ); -my ( $isbn_tag, $isbn_subfield ) = - GetMarcFromKohaField( 'biblioitems.isbn' ); +my ( $biblionumber_tag, $biblionumber_subfield ) = GetMarcFromKohaField('biblio.biblionumber'); +my ( $isbn_tag, $isbn_subfield ) = GetMarcFromKohaField('biblioitems.isbn'); # Harry Potter and the Sorcerer's Stone, 1st American ed. 1997 my $isbn1 = '0590353403'; + # ThingISBN match : Silent Wing, First Edition 1998 my $isbn2 = '0684843897'; + # XISBN match : Harry Potter and the Sorcerer's Stone, # 1. Scholastic mass market paperback printing1. my $isbn3 = '043936213X'; + # Finn Family Moomintroll, won't match to other isbns my $isbn4 = '014030150X'; @@ -51,38 +52,48 @@ my $biblionumber3 = _add_biblio_with_isbn($isbn3); my $biblionumber4 = _add_biblio_with_isbn($isbn4); my $trial = C4::XISBN::_get_biblio_from_xisbn($isbn1); -is( $trial->{biblionumber}, - $biblionumber1, "Gets biblionumber like the previous test." ); +is( + $trial->{biblionumber}, + $biblionumber1, "Gets biblionumber like the previous test." +); ## Test ThingISBN t::lib::Mocks::mock_preference( 'ThingISBN', 1 ); my $results_thingisbn; -eval { $results_thingisbn = C4::XISBN::get_xisbns($isbn1, $biblionumber4); }; +eval { $results_thingisbn = C4::XISBN::get_xisbns( $isbn1, $biblionumber4 ); }; SKIP: { skip "Problem retrieving ThingISBN", 2 unless $@ eq ''; - ok( (any { $_->{'biblionumber'} eq $biblionumber1 } @$results_thingisbn), - "Gets correct biblionumber from a book with a similar isbn using ThingISBN." ); - ok( (any { $_->{'biblionumber'} eq $biblionumber3 } @$results_thingisbn), - "Gets correct biblionumber from a book with a similar isbn using ThingISBN." ); + ok( + ( any { $_->{'biblionumber'} eq $biblionumber1 } @$results_thingisbn ), + "Gets correct biblionumber from a book with a similar isbn using ThingISBN." + ); + ok( + ( any { $_->{'biblionumber'} eq $biblionumber3 } @$results_thingisbn ), + "Gets correct biblionumber from a book with a similar isbn using ThingISBN." + ); } -eval { $results_thingisbn = C4::XISBN::get_xisbns($isbn1,$biblionumber1); }; +eval { $results_thingisbn = C4::XISBN::get_xisbns( $isbn1, $biblionumber1 ); }; SKIP: { skip "Problem retrieving ThingISBN", 1 unless $@ eq ''; - is( $results_thingisbn->[0]->{biblionumber}, + is( + $results_thingisbn->[0]->{biblionumber}, $biblionumber3, - "Gets correct biblionumber from a different book with a similar isbn using ThingISBN." ); + "Gets correct biblionumber from a different book with a similar isbn using ThingISBN." + ); } -eval { $results_thingisbn = C4::XISBN::get_xisbns($isbn1,$biblionumber3); }; +eval { $results_thingisbn = C4::XISBN::get_xisbns( $isbn1, $biblionumber3 ); }; SKIP: { skip "Problem retrieving ThingISBN", 1 unless $@ eq ''; - ok( (none { $_->{'biblionumber'} eq $biblionumber3 } @$results_thingisbn), - "Doesn't get biblionumber if the biblionumber matches the one passed to the sub." ); + ok( + ( none { $_->{'biblionumber'} eq $biblionumber3 } @$results_thingisbn ), + "Doesn't get biblionumber if the biblionumber matches the one passed to the sub." + ); } # Util subs @@ -92,7 +103,7 @@ sub _add_biblio_with_isbn { my $isbn = shift; my $marc_record = MARC::Record->new; - my $field = MARC::Field->new( $isbn_tag, '', '', $isbn_subfield => $isbn ); + my $field = MARC::Field->new( $isbn_tag, '', '', $isbn_subfield => $isbn ); $marc_record->append_fields($field); my ( $biblionumber, $biblioitemnumber ) = AddBiblio( $marc_record, '' ); return $biblionumber; @@ -102,7 +113,7 @@ sub _add_biblio_with_isbn { # Koha::SearchEngine::${SearchEngine}::Search::simple_search_compat sub Mock_simple_search_compat { - my $self = shift; + my $self = shift; my $query = shift; my @results; @@ -110,11 +121,9 @@ sub Mock_simple_search_compat { my $ret_biblionumber; if ( $query eq "nb=$isbn1" ) { $ret_biblionumber = $biblionumber1; - } - elsif ( $query eq "nb=$isbn2" ) { + } elsif ( $query eq "nb=$isbn2" ) { $ret_biblionumber = $biblionumber2; - } - elsif ( $query eq "nb=$isbn3" ) { + } elsif ( $query eq "nb=$isbn3" ) { $ret_biblionumber = $biblionumber3; } @@ -122,12 +131,12 @@ sub Mock_simple_search_compat { $record->leader(' ngm a22 7a 4500'); my $biblionumber_field; if ( $biblionumber_tag < 10 ) { - $biblionumber_field = - MARC::Field->new( $biblionumber_tag, $ret_biblionumber ); - } - else { - $biblionumber_field = MARC::Field->new( $biblionumber_tag, '', '', - $biblionumber_subfield => $ret_biblionumber ); + $biblionumber_field = MARC::Field->new( $biblionumber_tag, $ret_biblionumber ); + } else { + $biblionumber_field = MARC::Field->new( + $biblionumber_tag, '', '', + $biblionumber_subfield => $ret_biblionumber + ); } $record->append_fields($biblionumber_field); diff --git a/t/db_dependent/XSLT.t b/t/db_dependent/XSLT.t index 4f7ef3c84b..a7ce290d64 100755 --- a/t/db_dependent/XSLT.t +++ b/t/db_dependent/XSLT.t @@ -30,7 +30,7 @@ use Koha::Libraries; use Koha::ItemTypes; BEGIN { - use_ok('C4::XSLT', qw( buildKohaItemsNamespace )); + use_ok( 'C4::XSLT', qw( buildKohaItemsNamespace ) ); } my $schema = Koha::Database->new->schema; @@ -40,9 +40,9 @@ subtest 'Tests moved from t' => sub { plan tests => 8; $schema->storage->txn_begin; - my $dir = File::Temp->newdir(); - my @themes = ('prog', 'test'); - my @langs = ('en', 'es-ES'); + my $dir = File::Temp->newdir(); + my @themes = ( 'prog', 'test' ); + my @langs = ( 'en', 'es-ES' ); # create temporary files to be tested later foreach my $theme (@themes) { @@ -55,9 +55,9 @@ subtest 'Tests moved from t' => sub { } sub find_and_slurp { - my ($dir, $theme, $lang) = @_; + my ( $dir, $theme, $lang ) = @_; - my $filename = C4::XSLT::_get_best_default_xslt_filename($dir, $theme, $lang, 'my_file.xslt'); + my $filename = C4::XSLT::_get_best_default_xslt_filename( $dir, $theme, $lang, 'my_file.xslt' ); open my $fh, '<', $filename; my $str = <$fh>; close $fh; @@ -66,17 +66,20 @@ subtest 'Tests moved from t' => sub { # These tests verify that we're finding the right XSLT file when present, # and falling back to the right XSLT file when an exact match is not present. - is(find_and_slurp($dir, 'test', 'en' ), 'Theme test, language en', 'Found test/en'); - is(find_and_slurp($dir, 'test', 'es-ES'), 'Theme test, language es-ES', 'Found test/es-ES'); - is(find_and_slurp($dir, 'prog', 'en', ), 'Theme prog, language en', 'Found test/en'); - is(find_and_slurp($dir, 'prog', 'es-ES'), 'Theme prog, language es-ES', 'Found test/es-ES'); - is(find_and_slurp($dir, 'test', 'fr-FR'), 'Theme test, language en', 'Fell back to test/en for test/fr-FR'); - is(find_and_slurp($dir, 'nope', 'es-ES'), 'Theme prog, language es-ES', 'Fell back to prog/es-ES for nope/es-ES'); - is(find_and_slurp($dir, 'nope', 'fr-FR'), 'Theme prog, language en', 'Fell back to prog/en for nope/fr-FR'); + is( find_and_slurp( $dir, 'test', 'en' ), 'Theme test, language en', 'Found test/en' ); + is( find_and_slurp( $dir, 'test', 'es-ES' ), 'Theme test, language es-ES', 'Found test/es-ES' ); + is( find_and_slurp( $dir, 'prog', 'en', ), 'Theme prog, language en', 'Found test/en' ); + is( find_and_slurp( $dir, 'prog', 'es-ES' ), 'Theme prog, language es-ES', 'Found test/es-ES' ); + is( find_and_slurp( $dir, 'test', 'fr-FR' ), 'Theme test, language en', 'Fell back to test/en for test/fr-FR' ); + is( + find_and_slurp( $dir, 'nope', 'es-ES' ), 'Theme prog, language es-ES', + 'Fell back to prog/es-ES for nope/es-ES' + ); + is( find_and_slurp( $dir, 'nope', 'fr-FR' ), 'Theme prog, language en', 'Fell back to prog/en for nope/fr-FR' ); my $matching_string = q{<syspref name="singleBranchMode">0</syspref>}; - my $sysprefs_xml = C4::XSLT::get_xslt_sysprefs(); - ok( $sysprefs_xml =~ m/$matching_string/, 'singleBranchMode has a value of 0'); + my $sysprefs_xml = C4::XSLT::get_xslt_sysprefs(); + ok( $sysprefs_xml =~ m/$matching_string/, 'singleBranchMode has a value of 0' ); $schema->storage->txn_rollback; }; @@ -85,73 +88,73 @@ subtest 'buildKohaItemsNamespace status tests' => sub { plan tests => 20; $schema->storage->txn_begin; - t::lib::Mocks::mock_preference('Reference_NFL_Statuses', '1|2'); - t::lib::Mocks::mock_preference( 'OPACResultsLibrary', 'holdingbranch' ); - t::lib::Mocks::mock_preference( 'OPACResultsMaxItems', '2' ); + t::lib::Mocks::mock_preference( 'Reference_NFL_Statuses', '1|2' ); + t::lib::Mocks::mock_preference( 'OPACResultsLibrary', 'holdingbranch' ); + t::lib::Mocks::mock_preference( 'OPACResultsMaxItems', '2' ); t::lib::Mocks::mock_preference( 'AllowHoldsOnDamagedItems', '0' ); - my $itype = $builder->build_object({ class => 'Koha::ItemTypes' }); - my $itemtype = $builder->build_object({ class => 'Koha::ItemTypes' }); - my $holdinglibrary = $builder->build_object({ class => 'Koha::Libraries' }); - my $item = $builder->build_sample_item({ itype => $itype->itemtype }); + my $itype = $builder->build_object( { class => 'Koha::ItemTypes' } ); + my $itemtype = $builder->build_object( { class => 'Koha::ItemTypes' } ); + my $holdinglibrary = $builder->build_object( { class => 'Koha::Libraries' } ); + my $item = $builder->build_sample_item( { itype => $itype->itemtype } ); $item->holdingbranch( $holdinglibrary->branchcode )->store; - $item->biblioitem->itemtype($itemtype->itemtype)->store; + $item->biblioitem->itemtype( $itemtype->itemtype )->store; - my $xml = C4::XSLT::buildKohaItemsNamespace( $item->biblionumber,[]); - like($xml,qr{<status>available</status>},"Item is available when no other status applied"); + my $xml = C4::XSLT::buildKohaItemsNamespace( $item->biblionumber, [] ); + like( $xml, qr{<status>available</status>}, "Item is available when no other status applied" ); # notforloan { - t::lib::Mocks::mock_preference('item-level_itypes', 0); + t::lib::Mocks::mock_preference( 'item-level_itypes', 0 ); $item->notforloan(0)->store; - Koha::ItemTypes->find($item->itype)->notforloan(0)->store; - Koha::ItemTypes->find($item->biblioitem->itemtype)->notforloan(1)->store; - $xml = C4::XSLT::buildKohaItemsNamespace( $item->biblionumber,[]); - like($xml,qr{<status>reference</status>},"reference if positive itype notforloan value"); + Koha::ItemTypes->find( $item->itype )->notforloan(0)->store; + Koha::ItemTypes->find( $item->biblioitem->itemtype )->notforloan(1)->store; + $xml = C4::XSLT::buildKohaItemsNamespace( $item->biblionumber, [] ); + like( $xml, qr{<status>reference</status>}, "reference if positive itype notforloan value" ); - t::lib::Mocks::mock_preference('item-level_itypes', 1); - Koha::ItemTypes->find($item->itype)->notforloan(1)->store; - Koha::ItemTypes->find($item->biblioitem->itemtype)->notforloan(0)->store; - $xml = C4::XSLT::buildKohaItemsNamespace( $item->biblionumber,[]); - like($xml,qr{<status>reference</status>},"reference if positive itemtype notforloan value"); - Koha::ItemTypes->find($item->itype)->notforloan(0)->store; + t::lib::Mocks::mock_preference( 'item-level_itypes', 1 ); + Koha::ItemTypes->find( $item->itype )->notforloan(1)->store; + Koha::ItemTypes->find( $item->biblioitem->itemtype )->notforloan(0)->store; + $xml = C4::XSLT::buildKohaItemsNamespace( $item->biblionumber, [] ); + like( $xml, qr{<status>reference</status>}, "reference if positive itemtype notforloan value" ); + Koha::ItemTypes->find( $item->itype )->notforloan(0)->store; - my $substatus = Koha::AuthorisedValues->search({ category => 'NOT_LOAN', authorised_value => -1 })->next->lib; + my $substatus = Koha::AuthorisedValues->search( { category => 'NOT_LOAN', authorised_value => -1 } )->next->lib; $item->notforloan(-1)->store; - $xml = C4::XSLT::buildKohaItemsNamespace( $item->biblionumber,[]); - like($xml,qr{<status>reallynotforloan</status>},"reallynotforloan if negative notforloan value"); - like($xml,qr{<substatus>$substatus</substatus>},"substatus set if negative notforloan value"); + $xml = C4::XSLT::buildKohaItemsNamespace( $item->biblionumber, [] ); + like( $xml, qr{<status>reallynotforloan</status>}, "reallynotforloan if negative notforloan value" ); + like( $xml, qr{<substatus>$substatus</substatus>}, "substatus set if negative notforloan value" ); $item->notforloan(1)->store; - $xml = C4::XSLT::buildKohaItemsNamespace( $item->biblionumber,[]); - like($xml,qr{<status>reference</status>},"reference if positive notforloan value"); + $xml = C4::XSLT::buildKohaItemsNamespace( $item->biblionumber, [] ); + like( $xml, qr{<status>reference</status>}, "reference if positive notforloan value" ); # But now make status notforloan==1 count under Not available - t::lib::Mocks::mock_preference('Reference_NFL_Statuses', '2'); - $xml = C4::XSLT::buildKohaItemsNamespace( $item->biblionumber,[]); - like($xml,qr{<status>reallynotforloan</status>},"reallynotforloan when we change Reference_NFL_Statuses"); - t::lib::Mocks::mock_preference('Reference_NFL_Statuses', q{}); # empty, same effect - $xml = C4::XSLT::buildKohaItemsNamespace( $item->biblionumber,[]); - like($xml,qr{<status>reallynotforloan</status>},"reallynotforloan when we empty Reference_NFL_Statuses"); - t::lib::Mocks::mock_preference('Reference_NFL_Statuses', '1|2'); + t::lib::Mocks::mock_preference( 'Reference_NFL_Statuses', '2' ); + $xml = C4::XSLT::buildKohaItemsNamespace( $item->biblionumber, [] ); + like( $xml, qr{<status>reallynotforloan</status>}, "reallynotforloan when we change Reference_NFL_Statuses" ); + t::lib::Mocks::mock_preference( 'Reference_NFL_Statuses', q{} ); # empty, same effect + $xml = C4::XSLT::buildKohaItemsNamespace( $item->biblionumber, [] ); + like( $xml, qr{<status>reallynotforloan</status>}, "reallynotforloan when we empty Reference_NFL_Statuses" ); + t::lib::Mocks::mock_preference( 'Reference_NFL_Statuses', '1|2' ); } $item->onloan('2001-01-01')->store; - $xml = C4::XSLT::buildKohaItemsNamespace( $item->biblionumber,[]); - like( $xml, qr/<status>other<\/status>/, "Checked out is part of other statuses" ); - like($xml,qr{<substatus>Checked out</substatus>},"Checked out status takes precedence over Not for loan"); + $xml = C4::XSLT::buildKohaItemsNamespace( $item->biblionumber, [] ); + like( $xml, qr/<status>other<\/status>/, "Checked out is part of other statuses" ); + like( $xml, qr{<substatus>Checked out</substatus>}, "Checked out status takes precedence over Not for loan" ); $item->withdrawn(1)->store; - $xml = C4::XSLT::buildKohaItemsNamespace( $item->biblionumber,[]); - like($xml,qr{<substatus>Withdrawn</substatus>},"Withdrawn status takes precedence over Checked out"); + $xml = C4::XSLT::buildKohaItemsNamespace( $item->biblionumber, [] ); + like( $xml, qr{<substatus>Withdrawn</substatus>}, "Withdrawn status takes precedence over Checked out" ); $item->itemlost(1)->store; - $xml = C4::XSLT::buildKohaItemsNamespace( $item->biblionumber,[]); - like($xml,qr{<substatus>Lost</substatus>},"Lost status takes precedence over Withdrawn"); + $xml = C4::XSLT::buildKohaItemsNamespace( $item->biblionumber, [] ); + like( $xml, qr{<substatus>Lost</substatus>}, "Lost status takes precedence over Withdrawn" ); $item->damaged(1)->store; - $xml = C4::XSLT::buildKohaItemsNamespace( $item->biblionumber,[]); - like($xml,qr{<substatus>Damaged</substatus>},"Damaged status takes precedence over Lost"); + $xml = C4::XSLT::buildKohaItemsNamespace( $item->biblionumber, [] ); + like( $xml, qr{<substatus>Damaged</substatus>}, "Damaged status takes precedence over Lost" ); my $item2 = $builder->build_sample_item( { itype => $itype->itemtype } ); $item2->holdingbranch( $holdinglibrary->branchcode )->store; @@ -164,36 +167,41 @@ subtest 'buildKohaItemsNamespace status tests' => sub { $xml = C4::XSLT::buildKohaItemsNamespace( $item2->biblionumber, [] ); like( $xml, qr{<status>available</status>}, "Damaged status with AllowHoldsOnDamagedItems results in 'available'" ); - $builder->build({ source => "Branchtransfer", value => { - itemnumber => $item->itemnumber, - datearrived => undef, - datecancelled => undef, + $builder->build( + { + source => "Branchtransfer", + value => { + itemnumber => $item->itemnumber, + datearrived => undef, + datecancelled => undef, + } } - }); - $xml = C4::XSLT::buildKohaItemsNamespace( $item->biblionumber,[]); - like($xml,qr{<substatus>In transit</substatus>},"In-transit status takes precedence over Damaged"); + ); + $xml = C4::XSLT::buildKohaItemsNamespace( $item->biblionumber, [] ); + like( $xml, qr{<substatus>In transit</substatus>}, "In-transit status takes precedence over Damaged" ); - my $hold = $builder->build_object({ class => 'Koha::Holds', value => { - biblionumber => $item->biblionumber, - itemnumber => $item->itemnumber, - found => 'W', - priority => 0, + my $hold = $builder->build_object( + { + class => 'Koha::Holds', + value => { + biblionumber => $item->biblionumber, + itemnumber => $item->itemnumber, + found => 'W', + priority => 0, + } } - }); - $xml = C4::XSLT::buildKohaItemsNamespace( $item->biblionumber,[]); - like($xml,qr{<substatus>Hold waiting</substatus>},"Waiting status takes precedence over In transit (holds)"); + ); + $xml = C4::XSLT::buildKohaItemsNamespace( $item->biblionumber, [] ); + like( $xml, qr{<substatus>Hold waiting</substatus>}, "Waiting status takes precedence over In transit (holds)" ); $hold->cancel; - $builder->build({ source => "TmpHoldsqueue", value => { - itemnumber => $item->itemnumber - } - }); - $xml = C4::XSLT::buildKohaItemsNamespace( $item->biblionumber,[]); - like($xml,qr{<substatus>Pending hold</substatus>},"Pending status takes precedence over all"); + $builder->build( { source => "TmpHoldsqueue", value => { itemnumber => $item->itemnumber } } ); + $xml = C4::XSLT::buildKohaItemsNamespace( $item->biblionumber, [] ); + like( $xml, qr{<substatus>Pending hold</substatus>}, "Pending status takes precedence over all" ); my $library_name = $holdinglibrary->branchname; - like($xml,qr{<resultbranch>${library_name}</resultbranch>}, "Found resultbranch / holding branch" ); + like( $xml, qr{<resultbranch>${library_name}</resultbranch>}, "Found resultbranch / holding branch" ); - t::lib::Mocks::mock_preference('UseRecalls', 1); + t::lib::Mocks::mock_preference( 'UseRecalls', 1 ); my $recall = $builder->build_object( { class => 'Koha::Recalls', @@ -206,9 +214,12 @@ subtest 'buildKohaItemsNamespace status tests' => sub { } ); $recall->set_waiting; - $xml = C4::XSLT::buildKohaItemsNamespace( $item->biblionumber,[]); - like($xml,qr{<substatus>Recall waiting</substatus>},"Waiting status takes precedence over In transit (recalls)"); - t::lib::Mocks::mock_preference('UseRecalls', 0); + $xml = C4::XSLT::buildKohaItemsNamespace( $item->biblionumber, [] ); + like( + $xml, qr{<substatus>Recall waiting</substatus>}, + "Waiting status takes precedence over In transit (recalls)" + ); + t::lib::Mocks::mock_preference( 'UseRecalls', 0 ); $schema->storage->txn_rollback; }; @@ -218,19 +229,19 @@ subtest 'buildKohaItemsNamespace() including/omitting items tests' => sub { $schema->storage->txn_begin; - my $biblio = $builder->build_sample_biblio; + my $biblio = $builder->build_sample_biblio; my $biblio2 = $builder->build_sample_biblio; # Have two known libraries for testing purposes - my $library_1 = $builder->build_object({ class => 'Koha::Libraries' }); - my $library_2 = $builder->build_object({ class => 'Koha::Libraries' }); - my $library_3 = $builder->build_object({ class => 'Koha::Libraries' }); + my $library_1 = $builder->build_object( { class => 'Koha::Libraries' } ); + my $library_2 = $builder->build_object( { class => 'Koha::Libraries' } ); + my $library_3 = $builder->build_object( { class => 'Koha::Libraries' } ); - my $item_1 = $builder->build_sample_item({ biblionumber => $biblio->biblionumber, library => $library_1->id }); - my $item_2 = $builder->build_sample_item({ biblionumber => $biblio->biblionumber, library => $library_2->id }); - my $item_3 = $builder->build_sample_item({ biblionumber => $biblio->biblionumber, library => $library_3->id }); + my $item_1 = $builder->build_sample_item( { biblionumber => $biblio->biblionumber, library => $library_1->id } ); + my $item_2 = $builder->build_sample_item( { biblionumber => $biblio->biblionumber, library => $library_2->id } ); + my $item_3 = $builder->build_sample_item( { biblionumber => $biblio->biblionumber, library => $library_3->id } ); - my $items_rs = $biblio->items->search({ "me.itemnumber" => { '!=' => $item_3->itemnumber } }); + my $items_rs = $biblio->items->search( { "me.itemnumber" => { '!=' => $item_3->itemnumber } } ); ## Test passing items_rs only my $xml = C4::XSLT::buildKohaItemsNamespace( $biblio->biblionumber, undef, $items_rs ); @@ -239,26 +250,30 @@ subtest 'buildKohaItemsNamespace() including/omitting items tests' => sub { my $library_2_name = $library_2->branchname; my $library_3_name = $library_3->branchname; - like( $xml, qr{<homebranch>$library_1_name</homebranch>}, '$item_1 present in the XML' ); - like( $xml, qr{<homebranch>$library_2_name</homebranch>}, '$item_2 present in the XML' ); + like( $xml, qr{<homebranch>$library_1_name</homebranch>}, '$item_1 present in the XML' ); + like( $xml, qr{<homebranch>$library_2_name</homebranch>}, '$item_2 present in the XML' ); unlike( $xml, qr{<homebranch>$library_3_name</homebranch>}, '$item_3 not present in the XML' ); - t::lib::Mocks::mock_preference('OpacHiddenItems', 'biblionumber: ['.$biblio2->biblionumber.']'); - my $hid_rs = $biblio->items->search({ "me.itemnumber" => { '!=' => $item_3->itemnumber } })->filter_by_visible_in_opac(); + t::lib::Mocks::mock_preference( 'OpacHiddenItems', 'biblionumber: [' . $biblio2->biblionumber . ']' ); + my $hid_rs = + $biblio->items->search( { "me.itemnumber" => { '!=' => $item_3->itemnumber } } )->filter_by_visible_in_opac(); $xml = C4::XSLT::buildKohaItemsNamespace( $biblio->biblionumber, undef, $hid_rs ); - like( $xml, qr{<homebranch>$library_1_name</homebranch>}, '$item_1 present in the XML' ); - like( $xml, qr{<homebranch>$library_2_name</homebranch>}, '$item_2 present in the XML' ); + like( $xml, qr{<homebranch>$library_1_name</homebranch>}, '$item_1 present in the XML' ); + like( $xml, qr{<homebranch>$library_2_name</homebranch>}, '$item_2 present in the XML' ); unlike( $xml, qr{<homebranch>$library_3_name</homebranch>}, '$item_3 not present in the XML' ); ## Test passing one item in hidden_items and items_rs $xml = C4::XSLT::buildKohaItemsNamespace( $biblio->biblionumber, [ $item_1->itemnumber ], $items_rs->reset ); unlike( $xml, qr{<homebranch>$library_1_name</homebranch>}, '$item_1 not present in the XML' ); - like( $xml, qr{<homebranch>$library_2_name</homebranch>}, '$item_2 present in the XML' ); + like( $xml, qr{<homebranch>$library_2_name</homebranch>}, '$item_2 present in the XML' ); unlike( $xml, qr{<homebranch>$library_3_name</homebranch>}, '$item_3 not present in the XML' ); ## Test passing both items in hidden_items and items_rs - $xml = C4::XSLT::buildKohaItemsNamespace( $biblio->biblionumber, [ $item_1->itemnumber, $item_2->itemnumber ], $items_rs->reset ); + $xml = C4::XSLT::buildKohaItemsNamespace( + $biblio->biblionumber, [ $item_1->itemnumber, $item_2->itemnumber ], + $items_rs->reset + ); unlike( $xml, qr{<homebranch>$library_1_name</homebranch>}, '$item_1 not present in the XML' ); unlike( $xml, qr{<homebranch>$library_2_name</homebranch>}, '$item_2 not present in the XML' ); @@ -266,7 +281,10 @@ subtest 'buildKohaItemsNamespace() including/omitting items tests' => sub { is( $xml, '<items xmlns="http://www.koha-community.org/items"></items>', 'Empty XML' ); ## Test passing both items in hidden_items and no items_rs - $xml = C4::XSLT::buildKohaItemsNamespace( $biblio->biblionumber, [ $item_1->itemnumber, $item_2->itemnumber, $item_3->itemnumber ] ); + $xml = C4::XSLT::buildKohaItemsNamespace( + $biblio->biblionumber, + [ $item_1->itemnumber, $item_2->itemnumber, $item_3->itemnumber ] + ); unlike( $xml, qr{<homebranch>$library_1_name</homebranch>}, '$item_1 not present in the XML' ); unlike( $xml, qr{<homebranch>$library_2_name</homebranch>}, '$item_2 not present in the XML' ); @@ -277,8 +295,8 @@ subtest 'buildKohaItemsNamespace() including/omitting items tests' => sub { $xml = C4::XSLT::buildKohaItemsNamespace( $biblio->biblionumber, [ $item_1->itemnumber ] ); unlike( $xml, qr{<homebranch>$library_1_name</homebranch>}, '$item_1 not present in the XML' ); - like( $xml, qr{<homebranch>$library_2_name</homebranch>}, '$item_2 present in the XML' ); - like( $xml, qr{<homebranch>$library_3_name</homebranch>}, '$item_3 present in the XML' ); + like( $xml, qr{<homebranch>$library_2_name</homebranch>}, '$item_2 present in the XML' ); + like( $xml, qr{<homebranch>$library_3_name</homebranch>}, '$item_3 present in the XML' ); ## Test not passing any param $xml = C4::XSLT::buildKohaItemsNamespace( $biblio->biblionumber ); diff --git a/t/db_dependent/api/v1/acquisitions_baskets.t b/t/db_dependent/api/v1/acquisitions_baskets.t index b41939a5e3..82a9fe3ab1 100755 --- a/t/db_dependent/api/v1/acquisitions_baskets.t +++ b/t/db_dependent/api/v1/acquisitions_baskets.t @@ -40,30 +40,22 @@ subtest 'list_managers() tests' => sub { $schema->storage->txn_begin; my $patron_with_permission = - $builder->build_object( { class => 'Koha::Patrons', value => { flags => 2**11 } } ) - ; ## 11 == acquisition + $builder->build_object( { class => 'Koha::Patrons', value => { flags => 2**11 } } ); ## 11 == acquisition my $patron_without_permission = - $builder->build_object( { class => 'Koha::Patrons', value => { flags => 0 } } ); + $builder->build_object( { class => 'Koha::Patrons', value => { flags => 0 } } ); my $superlibrarian = - $builder->build_object( { class => 'Koha::Patrons', value => { flags => 1 } } ); + $builder->build_object( { class => 'Koha::Patrons', value => { flags => 1 } } ); my $password = 'thePassword123'; $superlibrarian->set_password( { password => $password, skip_validation => 1 } ); my $userid = $superlibrarian->userid; $superlibrarian->discard_changes; my $api_filter = encode_json( - { 'me.patron_id' => - [ $patron_with_permission->id, $patron_without_permission->id, $superlibrarian->id ] - } - ); + { 'me.patron_id' => [ $patron_with_permission->id, $patron_without_permission->id, $superlibrarian->id ] } ); - $t->get_ok( - "//$userid:$password@/api/v1/acquisitions/baskets/managers?q=$api_filter" - )->status_is(200)->json_is( + $t->get_ok("//$userid:$password@/api/v1/acquisitions/baskets/managers?q=$api_filter")->status_is(200)->json_is( [ - $patron_with_permission->to_api( - { user => $patron_with_permission } - ), + $patron_with_permission->to_api( { user => $patron_with_permission } ), $superlibrarian->to_api( { user => $superlibrarian } ) ] ); diff --git a/t/db_dependent/api/v1/acquisitions_funds.t b/t/db_dependent/api/v1/acquisitions_funds.t index 56283fe9f8..c1824c4fee 100755 --- a/t/db_dependent/api/v1/acquisitions_funds.t +++ b/t/db_dependent/api/v1/acquisitions_funds.t @@ -37,20 +37,24 @@ t::lib::Mocks::mock_preference( 'RESTBasicAuth', 1 ); my $t = Test::Mojo->new('Koha::REST::V1'); -my $librarian = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 2052 } -}); +my $librarian = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 2052 } + } +); my $password = 'thePassword123'; -$librarian->set_password({ password => $password, skip_validation => 1 }); +$librarian->set_password( { password => $password, skip_validation => 1 } ); my $userid = $librarian->userid; -my $patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 0 } -}); +my $patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 0 } + } +); my $unauth_password = 'thePassword123'; -$patron->set_password({ password => $unauth_password, skip_validation => 1 }); +$patron->set_password( { password => $unauth_password, skip_validation => 1 } ); my $unauth_userid = $patron->userid; my $fund_name = 'Periodiques'; @@ -66,24 +70,18 @@ my $fund = $builder->build_object( } ); -$t->get_ok('/api/v1/acquisitions/funds') - ->status_is(401); +$t->get_ok('/api/v1/acquisitions/funds')->status_is(401); -$t->get_ok('/api/v1/acquisitions/funds/?name=testFund') - ->status_is(401); +$t->get_ok('/api/v1/acquisitions/funds/?name=testFund')->status_is(401); -$t->get_ok("//$unauth_userid:$unauth_password@/api/v1/acquisitions/funds") - ->status_is(403); +$t->get_ok("//$unauth_userid:$unauth_password@/api/v1/acquisitions/funds")->status_is(403); -$t->get_ok("//$unauth_userid:$unauth_password@/api/v1/acquisitions/funds?name=" . $fund_name) - ->status_is(403); +$t->get_ok( "//$unauth_userid:$unauth_password@/api/v1/acquisitions/funds?name=" . $fund_name )->status_is(403); -$t->get_ok("//$userid:$password@/api/v1/acquisitions/funds") - ->status_is(200); +$t->get_ok("//$userid:$password@/api/v1/acquisitions/funds")->status_is(200); -$t->get_ok("//$userid:$password@/api/v1/acquisitions/funds?name=" . $fund_name) - ->status_is(200) - ->json_like('/0/name' => qr/$fund_name/); +$t->get_ok( "//$userid:$password@/api/v1/acquisitions/funds?name=" . $fund_name )->status_is(200) + ->json_like( '/0/name' => qr/$fund_name/ ); $schema->storage->txn_rollback; @@ -94,12 +92,11 @@ subtest 'list_owners() and list_users() tests' => sub { $schema->storage->txn_begin; my $patron_with_permission = - $builder->build_object( { class => 'Koha::Patrons', value => { flags => 2**11 } } ) - ; ## 11 == acquisition + $builder->build_object( { class => 'Koha::Patrons', value => { flags => 2**11 } } ); ## 11 == acquisition my $patron_without_permission = - $builder->build_object( { class => 'Koha::Patrons', value => { flags => 0 } } ); + $builder->build_object( { class => 'Koha::Patrons', value => { flags => 0 } } ); my $superlibrarian = - $builder->build_object( { class => 'Koha::Patrons', value => { flags => 1 } } ); + $builder->build_object( { class => 'Koha::Patrons', value => { flags => 1 } } ); my $password = 'thePassword123'; $superlibrarian->set_password( { password => $password, skip_validation => 1 } ); $superlibrarian->discard_changes; @@ -108,32 +105,21 @@ subtest 'list_owners() and list_users() tests' => sub { # Restrict the query to a know list of patrons my $api_filter = encode_json( - { 'me.patron_id' => - [ $patron_with_permission->id, $patron_without_permission->id, $superlibrarian->id ] - } + { 'me.patron_id' => [ $patron_with_permission->id, $patron_without_permission->id, $superlibrarian->id ] } ); + + $t->get_ok("//$userid:$password@/api/v1/acquisitions/funds/owners?q=$api_filter")->status_is(200)->json_is( + [ + $patron_with_permission->to_api( { user => $patron_with_permission } ), + $superlibrarian->to_api( { user => $superlibrarian } ) + ] ); - $t->get_ok( - "//$userid:$password@/api/v1/acquisitions/funds/owners?q=$api_filter") - ->status_is(200)->json_is( + $t->get_ok("//$userid:$password@/api/v1/acquisitions/funds/users?q=$api_filter")->status_is(200)->json_is( [ - $patron_with_permission->to_api( - { user => $patron_with_permission } - ), + $patron_with_permission->to_api( { user => $patron_with_permission } ), $superlibrarian->to_api( { user => $superlibrarian } ) ] - ); - - $t->get_ok( - "//$userid:$password@/api/v1/acquisitions/funds/users?q=$api_filter") - ->status_is(200)->json_is( - [ - $patron_with_permission->to_api( - { user => $patron_with_permission } - ), - $superlibrarian->to_api( { user => $superlibrarian } ) - ] - ); + ); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/api/v1/acquisitions_orders.t b/t/db_dependent/api/v1/acquisitions_orders.t index b02cb891ff..0d7afa38c7 100755 --- a/t/db_dependent/api/v1/acquisitions_orders.t +++ b/t/db_dependent/api/v1/acquisitions_orders.t @@ -42,19 +42,21 @@ subtest 'list() tests' => sub { $schema->storage->txn_begin; - my $patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 1 } - }); + my $patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 1 } + } + ); my $password = 'thePassword123'; - $patron->set_password({ password => $password, skip_validation => 1 }); + $patron->set_password( { password => $password, skip_validation => 1 } ); my $userid = $patron->userid; - my $basket = $builder->build_object({ class => 'Koha::Acquisition::Baskets', value => { is_standing => 1 } }); + my $basket = $builder->build_object( { class => 'Koha::Acquisition::Baskets', value => { is_standing => 1 } } ); - my $biblio = $builder->build_sample_biblio; + my $biblio = $builder->build_sample_biblio; my $biblioitem = $biblio->biblioitem; - $biblioitem->set({ isbn => 'SOMETHING' })->store; + $biblioitem->set( { isbn => 'SOMETHING' } )->store; # Create test context my $order = $builder->build_object( @@ -69,17 +71,17 @@ subtest 'list() tests' => sub { } } ); - my $another_order = $order->unblessed; # create a copy of $order but make - delete $another_order->{ordernumber}; # sure ordernumber will be regenerated - $another_order = $builder->build_object({ class => 'Koha::Acquisition::Orders', value => $another_order }); + my $another_order = $order->unblessed; # create a copy of $order but make + delete $another_order->{ordernumber}; # sure ordernumber will be regenerated + $another_order = $builder->build_object( { class => 'Koha::Acquisition::Orders', value => $another_order } ); ## Authorized user tests my $count_of_orders = Koha::Acquisition::Orders->search( { orderstatus => 'new' } )->count; + # Make sure we are returned with the correct amount of orders - $t->get_ok( "//$userid:$password@/api/v1/acquisitions/orders?status=new&_per_page=-1" ) - ->status_is( 200, 'REST3.2.2' ) - ->json_has('/'.($count_of_orders-1).'/order_id') - ->json_hasnt('/'.($count_of_orders).'/order_id'); + $t->get_ok("//$userid:$password@/api/v1/acquisitions/orders?status=new&_per_page=-1") + ->status_is( 200, 'REST3.2.2' )->json_has( '/' . ( $count_of_orders - 1 ) . '/order_id' ) + ->json_hasnt( '/' . ($count_of_orders) . '/order_id' ); subtest 'query parameters' => sub { @@ -91,57 +93,60 @@ subtest 'list() tests' => sub { my $size = keys %{$fields}; - plan tests => $size * (2 + 2 * $size); + plan tests => $size * ( 2 + 2 * $size ); foreach my $field ( keys %{$fields} ) { - my $model_field = $fields->{ $field }; - my $result = $t->get_ok("//$userid:$password@/api/v1/acquisitions/orders?$field=" . $order->$model_field) - ->status_is(200); + my $model_field = $fields->{$field}; + my $result = $t->get_ok( "//$userid:$password@/api/v1/acquisitions/orders?$field=" . $order->$model_field ) + ->status_is(200); foreach my $key ( keys %{$fields} ) { - my $key_field = $fields->{ $key }; - # Check the result order first since it's not predefined. - if ($result->tx->res->json->[0]->{$key} eq $order->$key_field) { - $result->json_is( "/0/$key", $order->$key_field ); - $result->json_is( "/1/$key", $another_order->$key_field ); - } else { - $result->json_is( "/0/$key", $another_order->$key_field ); - $result->json_is( "/1/$key", $order->$key_field ); - } + my $key_field = $fields->{$key}; + + # Check the result order first since it's not predefined. + if ( $result->tx->res->json->[0]->{$key} eq $order->$key_field ) { + $result->json_is( "/0/$key", $order->$key_field ); + $result->json_is( "/1/$key", $another_order->$key_field ); + } else { + $result->json_is( "/0/$key", $another_order->$key_field ); + $result->json_is( "/1/$key", $order->$key_field ); + } } } }; my $query = { "biblio.isbn" => { "-like" => "\%SOMETHING\%" } }; - $t->get_ok( "//$userid:$password@/api/v1/acquisitions/orders?q=" . encode_json($query) => {'x-koha-embed' => 'biblio'} ) - ->status_is( 200, "Embedding biblio and searching on biblio.isbn doesn't make it explode" ) - ->json_has( "/0/biblio", "biblio object correctly embedded" ) - ->json_is( "/0/biblio/isbn", 'SOMETHING', 'Filtering by a biblioitems column works!' ); + $t->get_ok( + "//$userid:$password@/api/v1/acquisitions/orders?q=" . encode_json($query) => { 'x-koha-embed' => 'biblio' } ) + ->status_is( 200, "Embedding biblio and searching on biblio.isbn doesn't make it explode" ) + ->json_has( "/0/biblio", "biblio object correctly embedded" ) + ->json_is( "/0/biblio/isbn", 'SOMETHING', 'Filtering by a biblioitems column works!' ); $query = { "biblio.isbn" => { "-like" => "\%SOMETHING\%" }, "biblio.title" => { -like => "\%\%" } }; - $t->get_ok( "//$userid:$password@/api/v1/acquisitions/orders?q=" . encode_json($query) => {'x-koha-embed' => 'biblio'} ) - ->status_is( 200, "Embedding biblio and searching on biblio.isbn and biblio.title doesn't make it explode" ) - ->json_has( "/0/biblio", "biblio object correctly embedded" ) - ->json_is( "/0/biblio/isbn", 'SOMETHING', 'Filtering by a biblioitem column works!' ) - ->json_is( "/0/biblio/title", $biblio->title, 'Filtering by a biblioitem and biblio columns works!' ); + $t->get_ok( + "//$userid:$password@/api/v1/acquisitions/orders?q=" . encode_json($query) => { 'x-koha-embed' => 'biblio' } ) + ->status_is( 200, "Embedding biblio and searching on biblio.isbn and biblio.title doesn't make it explode" ) + ->json_has( "/0/biblio", "biblio object correctly embedded" ) + ->json_is( "/0/biblio/isbn", 'SOMETHING', 'Filtering by a biblioitem column works!' ) + ->json_is( "/0/biblio/title", $biblio->title, 'Filtering by a biblioitem and biblio columns works!' ); my $result = $t->get_ok( "//$userid:$password@/api/v1/acquisitions/orders?biblio_id=" . $biblio->biblionumber ) - ->status_is( 200 ); + ->status_is(200); - is( scalar @{ $result->tx->res->json}, 2, 'Two orders fetched' ); + is( scalar @{ $result->tx->res->json }, 2, 'Two orders fetched' ); # Mark $another_order as cancelled - $another_order->set({ orderstatus => 'cancelled' })->store; + $another_order->set( { orderstatus => 'cancelled' } )->store; - $result = $t->get_ok( "//$userid:$password@/api/v1/acquisitions/orders?only_active=1&biblio_id=" . $biblio->biblionumber ) - ->status_is( 200, "only_active parameter accepted" ); + $result = + $t->get_ok( "//$userid:$password@/api/v1/acquisitions/orders?only_active=1&biblio_id=" . $biblio->biblionumber ) + ->status_is( 200, "only_active parameter accepted" ); - is( scalar @{ $result->tx->res->json}, 1, 'Only one order is active' ); + is( scalar @{ $result->tx->res->json }, 1, 'Only one order is active' ); # Warn on unsupported query parameter - $t->get_ok( "//$userid:$password@/api/v1/acquisitions/orders?order_blah=blah" ) - ->status_is(400) - ->json_is( [{ path => '/query/order_blah', message => 'Malformed query string'}] ); + $t->get_ok("//$userid:$password@/api/v1/acquisitions/orders?order_blah=blah")->status_is(400) + ->json_is( [ { path => '/query/order_blah', message => 'Malformed query string' } ] ); subtest 'sorting tests' => sub { @@ -152,7 +157,7 @@ subtest 'list() tests' => sub { my $biblio_1 = $builder->build_sample_biblio(); my $biblio_2 = $builder->build_sample_biblio(); - my $basket = $builder->build_object({ class => 'Koha::Acquisition::Baskets', value => { is_standing => 1 } }); + my $basket = $builder->build_object( { class => 'Koha::Acquisition::Baskets', value => { is_standing => 1 } } ); my $order_1 = $builder->build_object( { class => 'Koha::Acquisition::Orders', @@ -176,9 +181,9 @@ subtest 'list() tests' => sub { # order by order_id my $result = - $t->get_ok( "//$userid:$password@/api/v1/acquisitions/orders?_order_by=+me.order_id&basket_id=" . $basket->id ) - ->status_is( 200, "query successful" ) - ->tx->res->json; + $t->get_ok( + "//$userid:$password@/api/v1/acquisitions/orders?_order_by=+me.order_id&basket_id=" . $basket->id ) + ->status_is( 200, "query successful" )->tx->res->json; is( scalar @$result, 2, 'Two elements returned' ); @@ -187,9 +192,9 @@ subtest 'list() tests' => sub { # now reverse order $result = - $t->get_ok( "//$userid:$password@/api/v1/acquisitions/orders?_order_by=-me.order_id&basket_id=" . $basket->id ) - ->status_is( 200, "query successful" ) - ->tx->res->json; + $t->get_ok( + "//$userid:$password@/api/v1/acquisitions/orders?_order_by=-me.order_id&basket_id=" . $basket->id ) + ->status_is( 200, "query successful" )->tx->res->json; is( scalar @$result, 2, 'Two elements returned' ); @@ -213,9 +218,9 @@ subtest 'list() tests' => sub { )->store; $result = - $t->get_ok( "//$userid:$password@/api/v1/acquisitions/orders?_order_by=-biblio.isbn,+biblio.ean,-biblio.publisher&basket_id=" . $basket->id => {'x-koha-embed' => 'biblio'} ) - ->status_is( 200, "query successful" ) - ->tx->res->json; + $t->get_ok( + "//$userid:$password@/api/v1/acquisitions/orders?_order_by=-biblio.isbn,+biblio.ean,-biblio.publisher&basket_id=" + . $basket->id => { 'x-koha-embed' => 'biblio' } )->status_is( 200, "query successful" )->tx->res->json; is( $result->[0]->{order_id}, $order_2->id, 'Ordered correctly' ); is( $result->[1]->{order_id}, $order_1->id, 'Ordered correctly' ); @@ -238,24 +243,24 @@ subtest 'get() tests' => sub { value => { orderstatus => 'new' } } ); - my $patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 2048 } - }); + my $patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 2048 } + } + ); my $password = 'thePassword123'; - $patron->set_password({ password => $password, skip_validation => 1 }); + $patron->set_password( { password => $password, skip_validation => 1 } ); my $userid = $patron->userid; $t->get_ok( "//$userid:$password@/api/v1/acquisitions/orders/" . $order->ordernumber ) - ->status_is( 200, 'REST3.2.2' ) - ->json_is( '' => $order->to_api, 'REST3.3.2' ); + ->status_is( 200, 'REST3.2.2' )->json_is( '' => $order->to_api, 'REST3.3.2' ); my $non_existent_order_id = $order->ordernumber; $order->delete; - $t->get_ok( "//$userid:$password@/api/v1/acquisitions/orders/" . $non_existent_order_id ) - ->status_is(404) - ->json_is( '/error' => 'Order not found' ); + $t->get_ok( "//$userid:$password@/api/v1/acquisitions/orders/" . $non_existent_order_id )->status_is(404) + ->json_is( '/error' => 'Order not found' ); # FIXME This does not work on all the OS we support ## Regression tests for bug 25513 @@ -284,32 +289,36 @@ subtest 'add() tests' => sub { $schema->storage->txn_begin; - my $authorized_patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 1 } - }); + my $authorized_patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 1 } + } + ); my $password = 'thePassword123'; - $authorized_patron->set_password({ password => $password, skip_validation => 1 }); + $authorized_patron->set_password( { password => $password, skip_validation => 1 } ); my $auth_userid = $authorized_patron->userid; - my $unauthorized_patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 4 } - }); - $unauthorized_patron->set_password({ password => $password, skip_validation => 1 }); + my $unauthorized_patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 4 } + } + ); + $unauthorized_patron->set_password( { password => $password, skip_validation => 1 } ); my $unauth_userid = $unauthorized_patron->userid; my $order_obj = $builder->build_object( { class => 'Koha::Acquisition::Orders', value => { - orderstatus => 'new', - unitprice => 10, - replacementprice => 10, - quantity => 2, - quantityreceived => 0, + orderstatus => 'new', + unitprice => 10, + replacementprice => 10, + quantity => 2, + quantityreceived => 0, datecancellationprinted => undef, - order_internalnote => 'This is a dummy note for testing' + order_internalnote => 'This is a dummy note for testing' } } ); @@ -319,48 +328,45 @@ subtest 'add() tests' => sub { $order->{uncertain_price} = Mojo::JSON->false; # Unauthorized attempt to write - $t->post_ok( "//$unauth_userid:$password@/api/v1/acquisitions/orders" => json => $order ) - ->status_is(403); + $t->post_ok( "//$unauth_userid:$password@/api/v1/acquisitions/orders" => json => $order )->status_is(403); # Authorized attempt to write invalid data - my $order_with_invalid_field = { %$order }; + my $order_with_invalid_field = {%$order}; $order_with_invalid_field->{'orderinvalid'} = 'Order invalid'; $t->post_ok( "//$auth_userid:$password@/api/v1/acquisitions/orders" => json => $order_with_invalid_field ) - ->status_is(400) - ->json_is( + ->status_is(400)->json_is( "/errors" => [ { message => "Properties not allowed: orderinvalid.", path => "/body" } ] - ); + ); # Authorized attempt to write $t->post_ok( "//$auth_userid:$password@/api/v1/acquisitions/orders" => json => $order ) - ->status_is( 201, 'REST3.2.1' ) - ->json_is( '/internal_note' => $order->{internal_note}, 'REST3.3.1' ) - ->header_like( Location => qr/\/api\/v1\/acquisitions\/orders\/\d*/, 'REST3.4.1' ); + ->status_is( 201, 'REST3.2.1' )->json_is( '/internal_note' => $order->{internal_note}, 'REST3.3.1' ) + ->header_like( Location => qr/\/api\/v1\/acquisitions\/orders\/\d*/, 'REST3.4.1' ); # save the order_id my $order_id = $order->{order_id}; + # Authorized attempt to create with null id $order->{order_id} = undef; - $t->post_ok( "//$auth_userid:$password@/api/v1/acquisitions/orders" => json => $order ) - ->status_is(400) - ->json_has('/errors'); + $t->post_ok( "//$auth_userid:$password@/api/v1/acquisitions/orders" => json => $order )->status_is(400) + ->json_has('/errors'); # Authorized attempt to create with existing id $order->{order_id} = $order_id; warning_like { - $t->post_ok( "//$auth_userid:$password@/api/v1/acquisitions/orders" => json => $order ) - ->status_is(409) - ->json_has( '/error' => "Fails when trying to add an existing order_id") - ->json_like( '/conflict' => qr/(aqorders\.)?PRIMARY/ ); } - qr/DBD::mysql::st execute failed: Duplicate entry '(.*)' for key '(aqorders\.)?PRIMARY'/; + $t->post_ok( "//$auth_userid:$password@/api/v1/acquisitions/orders" => json => $order )->status_is(409) + ->json_has( '/error' => "Fails when trying to add an existing order_id" ) + ->json_like( '/conflict' => qr/(aqorders\.)?PRIMARY/ ); + } + qr/DBD::mysql::st execute failed: Duplicate entry '(.*)' for key '(aqorders\.)?PRIMARY'/; $schema->storage->txn_rollback; }; @@ -370,82 +376,85 @@ subtest 'update() tests' => sub { $schema->storage->txn_begin; - my $authorized_patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 1 } - }); + my $authorized_patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 1 } + } + ); my $password = 'thePassword123'; - $authorized_patron->set_password({ password => $password, skip_validation => 1 }); + $authorized_patron->set_password( { password => $password, skip_validation => 1 } ); my $auth_userid = $authorized_patron->userid; - my $unauthorized_patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 4 } - }); - $unauthorized_patron->set_password({ password => $password, skip_validation => 1 }); + my $unauthorized_patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 4 } + } + ); + $unauthorized_patron->set_password( { password => $password, skip_validation => 1 } ); my $unauth_userid = $unauthorized_patron->userid; - my $library = $builder->build_object({ class => 'Koha::Libraries' }); + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); my $library_id = $library->branchcode; # Unauthorized attempt to update - $t->put_ok( "//$unauth_userid:$password@/api/v1/libraries/$library_id" - => json => { name => 'New unauthorized name change' } ) - ->status_is(403); + $t->put_ok( "//$unauth_userid:$password@/api/v1/libraries/$library_id" => json => + { name => 'New unauthorized name change' } )->status_is(403); # Attempt partial update on a PUT my $library_with_missing_field = { address1 => "New library address", }; - my $result = $t->put_ok( "//$auth_userid:$password@/api/v1/libraries/$library_id" => json => $library_with_missing_field ) - ->status_is(400); + my $result = + $t->put_ok( "//$auth_userid:$password@/api/v1/libraries/$library_id" => json => $library_with_missing_field ) + ->status_is(400); + # Check the result order first since it's not predefined. - if ($result->tx->res->json->{errors}->[0]->{path} eq '/body/name') { - $result->json_is( - "/errors", - [ - {message => "Missing property.", path => "/body/name"}, - {message => "Missing property.", path => "/body/library_id"} - ] - ); + if ( $result->tx->res->json->{errors}->[0]->{path} eq '/body/name' ) { + $result->json_is( + "/errors", + [ + { message => "Missing property.", path => "/body/name" }, + { message => "Missing property.", path => "/body/library_id" } + ] + ); } else { - $result->json_is( - "/errors", - [ - {message => "Missing property.", path => "/body/library_id"}, - {message => "Missing property.", path => "/body/name"} - ] - ); + $result->json_is( + "/errors", + [ + { message => "Missing property.", path => "/body/library_id" }, + { message => "Missing property.", path => "/body/name" } + ] + ); } - my $deleted_library = $builder->build_object( { class => 'Koha::Libraries' } ); + my $deleted_library = $builder->build_object( { class => 'Koha::Libraries' } ); my $library_with_updated_field = $deleted_library->to_api; $library_with_updated_field->{library_id} = $library_id; $deleted_library->delete; $t->put_ok( "//$auth_userid:$password@/api/v1/libraries/$library_id" => json => $library_with_updated_field ) - ->status_is(200, 'REST3.2.1') - ->json_is( '' => $library_with_updated_field, 'REST3.3.3' ); + ->status_is( 200, 'REST3.2.1' )->json_is( '' => $library_with_updated_field, 'REST3.3.3' ); # Authorized attempt to write invalid data - my $library_with_invalid_field = { %$library_with_updated_field }; + my $library_with_invalid_field = {%$library_with_updated_field}; $library_with_invalid_field->{'branchinvalid'} = 'Library invalid'; $t->put_ok( "//$auth_userid:$password@/api/v1/libraries/$library_id" => json => $library_with_invalid_field ) - ->status_is(400) - ->json_is( + ->status_is(400)->json_is( "/errors" => [ { message => "Properties not allowed: branchinvalid.", path => "/body" } ] - ); + ); - my $non_existent_code = 'nope'.int(rand(10000)); - $t->put_ok("//$auth_userid:$password@/api/v1/libraries/$non_existent_code" => json => $library_with_updated_field) - ->status_is(404); + my $non_existent_code = 'nope' . int( rand(10000) ); + $t->put_ok( "//$auth_userid:$password@/api/v1/libraries/$non_existent_code" => json => $library_with_updated_field ) + ->status_is(404); $schema->storage->txn_rollback; }; @@ -455,36 +464,37 @@ subtest 'delete() tests' => sub { $schema->storage->txn_begin; - my $authorized_patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 1 } - }); + my $authorized_patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 1 } + } + ); my $password = 'thePassword123'; - $authorized_patron->set_password({ password => $password, skip_validation => 1 }); + $authorized_patron->set_password( { password => $password, skip_validation => 1 } ); my $auth_userid = $authorized_patron->userid; - my $unauthorized_patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 4 } - }); - $unauthorized_patron->set_password({ password => $password, skip_validation => 1 }); + my $unauthorized_patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 4 } + } + ); + $unauthorized_patron->set_password( { password => $password, skip_validation => 1 } ); my $unauth_userid = $unauthorized_patron->userid; my $order = $builder->build_object( { class => 'Koha::Acquisition::Orders' } ); # Unauthorized attempt to delete - $t->delete_ok( "//$unauth_userid:$password@/api/v1/acquisitions/orders/" . $order->ordernumber ) - ->status_is(403); + $t->delete_ok( "//$unauth_userid:$password@/api/v1/acquisitions/orders/" . $order->ordernumber )->status_is(403); # Check if status is cancelled? $order->orderstatus('new')->store; $t->delete_ok( "//$auth_userid:$password@/api/v1/acquisitions/orders/" . $order->ordernumber )->status_is(409); $order->orderstatus('cancelled')->store; $t->delete_ok( "//$auth_userid:$password@/api/v1/acquisitions/orders/" . $order->ordernumber ) - ->status_is(204, 'REST3.2.4') - ->content_is('', 'REST3.3.4'); - $t->delete_ok( "//$auth_userid:$password@/api/v1/acquisitions/orders/" . $order->ordernumber ) - ->status_is(404); + ->status_is( 204, 'REST3.2.4' )->content_is( '', 'REST3.3.4' ); + $t->delete_ok( "//$auth_userid:$password@/api/v1/acquisitions/orders/" . $order->ordernumber )->status_is(404); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/api/v1/acquisitions_vendors.t b/t/db_dependent/api/v1/acquisitions_vendors.t index 6adc66dfcd..d9d6951924 100755 --- a/t/db_dependent/api/v1/acquisitions_vendors.t +++ b/t/db_dependent/api/v1/acquisitions_vendors.t @@ -43,62 +43,53 @@ subtest 'list() and delete() tests | authorized user' => sub { $schema->resultset('Aqbasket')->search->delete; Koha::Acquisition::Booksellers->search->delete; - my $patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 2 ** 11 } ## 11 => acquisitions - }); + my $patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 2**11 } ## 11 => acquisitions + } + ); my $password = 'thePassword123'; - $patron->set_password({ password => $password, skip_validation => 1 }); + $patron->set_password( { password => $password, skip_validation => 1 } ); my $userid = $patron->userid; ## Authorized user tests # No vendors, so empty array should be returned - $t->get_ok( "//$userid:$password@/api/v1/acquisitions/vendors" ) - ->status_is(200) - ->json_is( [] ); + $t->get_ok("//$userid:$password@/api/v1/acquisitions/vendors")->status_is(200)->json_is( [] ); my $vendor_name = 'Ruben libros'; - my $vendor = $builder->build_object({ class => 'Koha::Acquisition::Booksellers', value => { name => $vendor_name } }); + my $vendor = + $builder->build_object( { class => 'Koha::Acquisition::Booksellers', value => { name => $vendor_name } } ); # One vendor created, should get returned - $t->get_ok( "//$userid:$password@/api/v1/acquisitions/vendors" ) - ->status_is(200) - ->json_like( '/0/name' => qr/$vendor_name/ ); + $t->get_ok("//$userid:$password@/api/v1/acquisitions/vendors")->status_is(200) + ->json_like( '/0/name' => qr/$vendor_name/ ); my $other_vendor_name = 'Amerindia'; - my $other_vendor - = $builder->build_object({ class => 'Koha::Acquisition::Booksellers', value => { name => $other_vendor_name } }); + my $other_vendor = $builder->build_object( + { class => 'Koha::Acquisition::Booksellers', value => { name => $other_vendor_name } } ); - $t->get_ok( "//$userid:$password@/api/v1/acquisitions/vendors" ) - ->status_is(200) - ->json_like( '/0/name' => qr/Ruben/ ) - ->json_like( '/1/name' => qr/Amerindia/ ); + $t->get_ok("//$userid:$password@/api/v1/acquisitions/vendors")->status_is(200)->json_like( '/0/name' => qr/Ruben/ ) + ->json_like( '/1/name' => qr/Amerindia/ ); - $t->get_ok( "//$userid:$password@/api/v1/acquisitions/vendors?name=$vendor_name" ) - ->status_is(200) - ->json_like( '/0/name' => qr/Ruben/ ); - - $t->get_ok( "//$userid:$password@/api/v1/acquisitions/vendors?name=$other_vendor_name" ) - ->status_is(200) - ->json_like( '/0/name' => qr/Amerindia/ ); + $t->get_ok("//$userid:$password@/api/v1/acquisitions/vendors?name=$vendor_name")->status_is(200) + ->json_like( '/0/name' => qr/Ruben/ ); + $t->get_ok("//$userid:$password@/api/v1/acquisitions/vendors?name=$other_vendor_name")->status_is(200) + ->json_like( '/0/name' => qr/Amerindia/ ); $t->get_ok( "//$userid:$password@/api/v1/acquisitions/vendors?accountnumber=" . $vendor->accountnumber ) - ->status_is(200) - ->json_like( '/0/name' => qr/Ruben/ ); + ->status_is(200)->json_like( '/0/name' => qr/Ruben/ ); $t->get_ok( "//$userid:$password@/api/v1/acquisitions/vendors?accountnumber=" . $other_vendor->accountnumber ) - ->status_is(200) - ->json_like( '/0/name' => qr/Amerindia/ ); + ->status_is(200)->json_like( '/0/name' => qr/Amerindia/ ); my @aliases = ( { alias => 'alias 1' }, { alias => 'alias 2' } ); $vendor->aliases( \@aliases ); - $t->get_ok( "//$userid:$password@/api/v1/acquisitions/vendors" => - { 'x-koha-embed' => 'aliases' } ) - ->status_is(200) - ->json_has('/0/aliases', 'aliases are embedded') - ->json_is('/0/aliases/0/alias' => 'alias 1', 'alias 1 is embedded') - ->json_is('/0/aliases/1/alias' => 'alias 2', 'alias 2 is embedded'); + $t->get_ok( "//$userid:$password@/api/v1/acquisitions/vendors" => { 'x-koha-embed' => 'aliases' } )->status_is(200) + ->json_has( '/0/aliases', 'aliases are embedded' ) + ->json_is( '/0/aliases/0/alias' => 'alias 1', 'alias 1 is embedded' ) + ->json_is( '/0/aliases/1/alias' => 'alias 2', 'alias 2 is embedded' ); for ( 0 .. 1 ) { $builder->build_object( { class => 'Koha::Subscriptions', value => { aqbooksellerid => $vendor->id } } ); @@ -107,22 +98,16 @@ subtest 'list() and delete() tests | authorized user' => sub { ->status_is(200)->json_has( '/0/subscriptions_count', 'subscriptions_count is embedded' ) ->json_is( '/0/subscriptions_count' => '2', 'subscription count is 2' ); - $t->delete_ok( "//$userid:$password@/api/v1/acquisitions/vendors/" . $vendor->id ) - ->status_is(204, 'REST3.2.4') - ->content_is('', 'REST3.3.4'); + $t->delete_ok( "//$userid:$password@/api/v1/acquisitions/vendors/" . $vendor->id )->status_is( 204, 'REST3.2.4' ) + ->content_is( '', 'REST3.3.4' ); - $t->get_ok( "//$userid:$password@/api/v1/acquisitions/vendors" ) - ->status_is(200) - ->json_like( '/0/name' => qr/$other_vendor_name/ ) - ->json_hasnt( '/1', 'Only one vendor' ); + $t->get_ok("//$userid:$password@/api/v1/acquisitions/vendors")->status_is(200) + ->json_like( '/0/name' => qr/$other_vendor_name/ )->json_hasnt( '/1', 'Only one vendor' ); $t->delete_ok( "//$userid:$password@/api/v1/acquisitions/vendors/" . $other_vendor->id ) - ->status_is(204, 'REST3.2.4') - ->content_is('', 'REST3.3.4'); + ->status_is( 204, 'REST3.2.4' )->content_is( '', 'REST3.3.4' ); - $t->get_ok( "//$userid:$password@/api/v1/acquisitions/vendors" ) - ->status_is(200) - ->json_is( [] ); + $t->get_ok("//$userid:$password@/api/v1/acquisitions/vendors")->status_is(200)->json_is( [] ); $schema->storage->txn_rollback; }; @@ -133,33 +118,32 @@ subtest 'get() test' => sub { $schema->storage->txn_begin; - my $vendor = $builder->build_object({ class => 'Koha::Acquisition::Booksellers' }); - my $nonexistent_vendor = $builder->build_object({ class => 'Koha::Acquisition::Booksellers' }); - my $non_existent_id = $nonexistent_vendor->id; + my $vendor = $builder->build_object( { class => 'Koha::Acquisition::Booksellers' } ); + my $nonexistent_vendor = $builder->build_object( { class => 'Koha::Acquisition::Booksellers' } ); + my $non_existent_id = $nonexistent_vendor->id; $nonexistent_vendor->delete; - my $patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 2 ** 11 } ## 11 => acquisitions - }); + my $patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 2**11 } ## 11 => acquisitions + } + ); my $password = 'thePassword123'; - $patron->set_password({ password => $password, skip_validation => 1 }); + $patron->set_password( { password => $password, skip_validation => 1 } ); my $userid = $patron->userid; - $t->get_ok( "//$userid:$password@/api/v1/acquisitions/vendors/" . $vendor->id ) - ->status_is(200) - ->json_is( $vendor->to_api ); + $t->get_ok( "//$userid:$password@/api/v1/acquisitions/vendors/" . $vendor->id )->status_is(200) + ->json_is( $vendor->to_api ); - $t->get_ok( "//$userid:$password@/api/v1/acquisitions/vendors/" . $non_existent_id ) - ->status_is(404) - ->json_is( '/error' => 'Vendor not found' ); + $t->get_ok( "//$userid:$password@/api/v1/acquisitions/vendors/" . $non_existent_id )->status_is(404) + ->json_is( '/error' => 'Vendor not found' ); # remove permissions - $patron->set({ flags => 0 })->store; + $patron->set( { flags => 0 } )->store; - $t->get_ok( "//$userid:$password@/api/v1/acquisitions/vendors/" . $vendor->id ) - ->status_is(403) - ->json_is( '/error', 'Authorization failure. Missing required permission(s).' ); + $t->get_ok( "//$userid:$password@/api/v1/acquisitions/vendors/" . $vendor->id )->status_is(403) + ->json_is( '/error', 'Authorization failure. Missing required permission(s).' ); $schema->storage->txn_rollback; }; @@ -170,26 +154,29 @@ subtest 'add() tests' => sub { $schema->storage->txn_begin; - my $authorized_patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 2 ** 11 } - }); + my $authorized_patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 2**11 } + } + ); my $password = 'thePassword123'; - $authorized_patron->set_password({ password => $password, skip_validation => 1 }); + $authorized_patron->set_password( { password => $password, skip_validation => 1 } ); my $auth_userid = $authorized_patron->userid; - my $unauthorized_patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 0 } - }); - $unauthorized_patron->set_password({ password => $password, skip_validation => 1 }); + my $unauthorized_patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 0 } + } + ); + $unauthorized_patron->set_password( { password => $password, skip_validation => 1 } ); my $unauth_userid = $unauthorized_patron->userid; my $vendor = { name => 'Ruben libros' }; # Unauthorized attempt to write - $t->post_ok( "//$unauth_userid:$password@/api/v1/acquisitions/vendors" => json => $vendor ) - ->status_is(403); + $t->post_ok( "//$unauth_userid:$password@/api/v1/acquisitions/vendors" => json => $vendor )->status_is(403); # Authorized attempt to write invalid data my $vendor_with_invalid_field = { @@ -198,38 +185,35 @@ subtest 'add() tests' => sub { }; $t->post_ok( "//$auth_userid:$password@/api/v1/acquisitions/vendors" => json => $vendor_with_invalid_field ) - ->status_is(400) - ->json_is( + ->status_is(400)->json_is( "/errors" => [ - { message => "Properties not allowed: address5.", + { + message => "Properties not allowed: address5.", path => "/body" } - ] + ] ); # Authorized attempt to write $t->post_ok( "//$auth_userid:$password@/api/v1/acquisitions/vendors" => json => $vendor ) - ->status_is( 201, 'REST3 .2.1' ) - ->header_like( Location => qr|^\/api\/v1\/acquisitions\/vendors/\d*|, 'REST3.4.1') - ->json_is( '/name' => $vendor->{name} ) - ->json_is( '/address1' => $vendor->{address1} ); + ->status_is( 201, 'REST3 .2.1' ) + ->header_like( Location => qr|^\/api\/v1\/acquisitions\/vendors/\d*|, 'REST3.4.1' ) + ->json_is( '/name' => $vendor->{name} )->json_is( '/address1' => $vendor->{address1} ); # read the response vendor id for later use my $vendor_id = $t->tx->res->json('/id'); # Authorized attempt to create with null id $vendor->{id} = undef; - $t->post_ok( "//$auth_userid:$password@/api/v1/acquisitions/vendors" => json => $vendor ) - ->status_is(400) - ->json_has('/errors'); + $t->post_ok( "//$auth_userid:$password@/api/v1/acquisitions/vendors" => json => $vendor )->status_is(400) + ->json_has('/errors'); # Authorized attempt to create with existing id $vendor->{id} = $vendor_id; - $t->post_ok( "//$auth_userid:$password@/api/v1/acquisitions/vendors" => json => $vendor ) - ->status_is(400) - ->json_is( + $t->post_ok( "//$auth_userid:$password@/api/v1/acquisitions/vendors" => json => $vendor )->status_is(400)->json_is( "/errors" => [ - { message => "Read-only.", + { + message => "Read-only.", path => "/body/id" } ] @@ -244,44 +228,44 @@ subtest 'update() tests' => sub { $schema->storage->txn_begin; - my $authorized_patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 2 ** 11 } - }); + my $authorized_patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 2**11 } + } + ); my $password = 'thePassword123'; - $authorized_patron->set_password({ password => $password, skip_validation => 1 }); + $authorized_patron->set_password( { password => $password, skip_validation => 1 } ); my $auth_userid = $authorized_patron->userid; - my $unauthorized_patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 0 } - }); - $unauthorized_patron->set_password({ password => $password, skip_validation => 1 }); + my $unauthorized_patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 0 } + } + ); + $unauthorized_patron->set_password( { password => $password, skip_validation => 1 } ); my $unauth_userid = $unauthorized_patron->userid; - my $vendor = $builder->build_object({ class => 'Koha::Acquisition::Booksellers' } ); + my $vendor = $builder->build_object( { class => 'Koha::Acquisition::Booksellers' } ); # Unauthorized attempt to update $t->put_ok( "//$unauth_userid:$password@/api/v1/acquisitions/vendors/" - . $vendor->id => json => - { city_name => 'New unauthorized name change' } ) - ->status_is(403); + . $vendor->id => json => { city_name => 'New unauthorized name change' } )->status_is(403); # Attempt partial update on a PUT my $vendor_without_mandatory_field = { address1 => 'New address' }; $t->put_ok( "//$auth_userid:$password@/api/v1/acquisitions/vendors/" - . $vendor->id => json => $vendor_without_mandatory_field ) - ->status_is(400) - ->json_is( "/errors" => [ { message => "Missing property.", path => "/body/name" } ] ); + . $vendor->id => json => $vendor_without_mandatory_field )->status_is(400) + ->json_is( "/errors" => [ { message => "Missing property.", path => "/body/name" } ] ); # Full object update on PUT my $vendor_with_updated_field = { name => "London books", }; - $t->put_ok( "//$auth_userid:$password@/api/v1/acquisitions/vendors/" - . $vendor->id => json => $vendor_with_updated_field ) - ->status_is(200) - ->json_is( '/name' => 'London books' ); + $t->put_ok( + "//$auth_userid:$password@/api/v1/acquisitions/vendors/" . $vendor->id => json => $vendor_with_updated_field ) + ->status_is(200)->json_is( '/name' => 'London books' ); # Authorized attempt to write invalid data my $vendor_with_invalid_field = { @@ -291,31 +275,30 @@ subtest 'update() tests' => sub { address3 => "Address 3" }; - $t->put_ok( "//$auth_userid:$password@/api/v1/acquisitions/vendors/" - . $vendor->id => json => $vendor_with_invalid_field ) - ->status_is(400) - ->json_is( + $t->put_ok( + "//$auth_userid:$password@/api/v1/acquisitions/vendors/" . $vendor->id => json => $vendor_with_invalid_field ) + ->status_is(400)->json_is( "/errors" => [ - { message => "Properties not allowed: blah.", + { + message => "Properties not allowed: blah.", path => "/body" } ] - ); + ); - my $nonexistent_vendor = $builder->build_object({ class => 'Koha::Acquisition::Booksellers' } ); - my $non_existent_id = $nonexistent_vendor->id; + my $nonexistent_vendor = $builder->build_object( { class => 'Koha::Acquisition::Booksellers' } ); + my $non_existent_id = $nonexistent_vendor->id; $nonexistent_vendor->delete; $t->put_ok( "//$auth_userid:$password@/api/v1/acquisitions/vendors/" - . $non_existent_id => json => $vendor_with_updated_field ) - ->status_is(404); + . $non_existent_id => json => $vendor_with_updated_field )->status_is(404); $schema->storage->txn_rollback; # Wrong method (POST) - $t->post_ok( "//$auth_userid:$password@/api/v1/acquisitions/vendors/" - . $vendor->id => json => $vendor_with_updated_field ) - ->status_is(404); + $t->post_ok( + "//$auth_userid:$password@/api/v1/acquisitions/vendors/" . $vendor->id => json => $vendor_with_updated_field ) + ->status_is(404); }; subtest 'delete() tests' => sub { @@ -324,33 +307,34 @@ subtest 'delete() tests' => sub { $schema->storage->txn_begin; - my $authorized_patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 2 ** 11 } - }); + my $authorized_patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 2**11 } + } + ); my $password = 'thePassword123'; - $authorized_patron->set_password({ password => $password, skip_validation => 1 }); + $authorized_patron->set_password( { password => $password, skip_validation => 1 } ); my $auth_userid = $authorized_patron->userid; - my $unauthorized_patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 0 } - }); - $unauthorized_patron->set_password({ password => $password, skip_validation => 1 }); + my $unauthorized_patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 0 } + } + ); + $unauthorized_patron->set_password( { password => $password, skip_validation => 1 } ); my $unauth_userid = $unauthorized_patron->userid; - my $vendor = $builder->build_object({ class => 'Koha::Acquisition::Booksellers' } ); + my $vendor = $builder->build_object( { class => 'Koha::Acquisition::Booksellers' } ); # Unauthorized attempt to delete - $t->delete_ok( "//$unauth_userid:$password@/api/v1/acquisitions/vendors/" . $vendor->id ) - ->status_is(403); + $t->delete_ok( "//$unauth_userid:$password@/api/v1/acquisitions/vendors/" . $vendor->id )->status_is(403); $t->delete_ok( "//$auth_userid:$password@/api/v1/acquisitions/vendors/" . $vendor->id ) - ->status_is(204, 'REST3.2.4') - ->content_is('', 'REST3.3.4'); + ->status_is( 204, 'REST3.2.4' )->content_is( '', 'REST3.3.4' ); - $t->delete_ok( "//$auth_userid:$password@/api/v1/acquisitions/vendors/" . $vendor->id ) - ->status_is(404); + $t->delete_ok( "//$auth_userid:$password@/api/v1/acquisitions/vendors/" . $vendor->id )->status_is(404); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/api/v1/advanced_editor_macros.t b/t/db_dependent/api/v1/advanced_editor_macros.t index 00d6d8a6f6..e6fe8adccd 100755 --- a/t/db_dependent/api/v1/advanced_editor_macros.t +++ b/t/db_dependent/api/v1/advanced_editor_macros.t @@ -38,84 +38,93 @@ $schema->storage->txn_begin; subtest 'list() tests' => sub { plan tests => 8; - - my $patron_1 = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 9 } - }); - my $patron_2 = $builder->build_object({ - class => 'Koha::Patrons', - }); + my $patron_1 = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 9 } + } + ); + my $patron_2 = $builder->build_object( + { + class => 'Koha::Patrons', + } + ); my $password = 'thePassword123'; - $patron_1->set_password({ password => $password, skip_validation => 1 }); + $patron_1->set_password( { password => $password, skip_validation => 1 } ); my $userid = $patron_1->userid; # Create test context - my $macro_1 = $builder->build_object({ class => 'Koha::AdvancedEditorMacros', value => + my $macro_1 = $builder->build_object( { - name => 'Test1', - macro => 'delete 100', - borrowernumber => $patron_1->borrowernumber, - shared => 0, + class => 'Koha::AdvancedEditorMacros', + value => { + name => 'Test1', + macro => 'delete 100', + borrowernumber => $patron_1->borrowernumber, + shared => 0, + } } - }); - my $macro_2 = $builder->build_object({ class => 'Koha::AdvancedEditorMacros', value => + ); + my $macro_2 = $builder->build_object( { - name => 'Test2', - macro => 'delete 100', - borrowernumber => $patron_1->borrowernumber, - shared => 1, + class => 'Koha::AdvancedEditorMacros', + value => { + name => 'Test2', + macro => 'delete 100', + borrowernumber => $patron_1->borrowernumber, + shared => 1, + } } - }); - my $macro_3 = $builder->build_object({ class => 'Koha::AdvancedEditorMacros', value => + ); + my $macro_3 = $builder->build_object( { - name => 'Test3', - macro => 'delete 100', - borrowernumber => $patron_2->borrowernumber, - shared => 0, + class => 'Koha::AdvancedEditorMacros', + value => { + name => 'Test3', + macro => 'delete 100', + borrowernumber => $patron_2->borrowernumber, + shared => 0, + } } - }); - my $macro_4 = $builder->build_object({ class => 'Koha::AdvancedEditorMacros', value => + ); + my $macro_4 = $builder->build_object( { - name => 'Test4', - macro => 'delete 100', - borrowernumber => $patron_2->borrowernumber, - shared => 1, + class => 'Koha::AdvancedEditorMacros', + value => { + name => 'Test4', + macro => 'delete 100', + borrowernumber => $patron_2->borrowernumber, + shared => 1, + } } - }); + ); - my $macros_index = Koha::AdvancedEditorMacros->search({ -or => { shared => 1, borrowernumber => $patron_1->borrowernumber } })->count-1; + my $macros_index = + Koha::AdvancedEditorMacros->search( { -or => { shared => 1, borrowernumber => $patron_1->borrowernumber } } ) + ->count - 1; ## Authorized user tests # Make sure we are returned with the correct amount of macros - $t->get_ok( "//$userid:$password@/api/v1/advanced_editor/macros" ) - ->status_is( 200, 'REST3.2.2' ) - ->json_has('/' . $macros_index . '/macro_id') - ->json_hasnt('/' . ($macros_index + 1) . '/macro_id'); + $t->get_ok("//$userid:$password@/api/v1/advanced_editor/macros")->status_is( 200, 'REST3.2.2' ) + ->json_has( '/' . $macros_index . '/macro_id' )->json_hasnt( '/' . ( $macros_index + 1 ) . '/macro_id' ); subtest 'query parameters' => sub { plan tests => 15; - $t->get_ok("//$userid:$password@/api/v1/advanced_editor/macros?name=" . $macro_2->name) - ->status_is(200) - ->json_is( [ $macro_2->to_api ] ); - $t->get_ok("//$userid:$password@/api/v1/advanced_editor/macros?name=" . $macro_3->name) - ->status_is(200) - ->json_is( [ ] ); - $t->get_ok("//$userid:$password@/api/v1/advanced_editor/macros?macro_text=delete%20100") - ->status_is(200) - ->json_is( [ $macro_1->to_api, $macro_2->to_api, $macro_4->to_api ] ); - $t->get_ok("//$userid:$password@/api/v1/advanced_editor/macros?patron_id=" . $patron_1->borrowernumber) - ->status_is(200) - ->json_is( [ $macro_1->to_api, $macro_2->to_api ] ); - $t->get_ok("//$userid:$password@/api/v1/advanced_editor/macros?shared=1") - ->status_is(200) - ->json_is( [ $macro_2->to_api, $macro_4->to_api ] ); + $t->get_ok( "//$userid:$password@/api/v1/advanced_editor/macros?name=" . $macro_2->name )->status_is(200) + ->json_is( [ $macro_2->to_api ] ); + $t->get_ok( "//$userid:$password@/api/v1/advanced_editor/macros?name=" . $macro_3->name )->status_is(200) + ->json_is( [] ); + $t->get_ok("//$userid:$password@/api/v1/advanced_editor/macros?macro_text=delete%20100")->status_is(200) + ->json_is( [ $macro_1->to_api, $macro_2->to_api, $macro_4->to_api ] ); + $t->get_ok( "//$userid:$password@/api/v1/advanced_editor/macros?patron_id=" . $patron_1->borrowernumber ) + ->status_is(200)->json_is( [ $macro_1->to_api, $macro_2->to_api ] ); + $t->get_ok("//$userid:$password@/api/v1/advanced_editor/macros?shared=1")->status_is(200) + ->json_is( [ $macro_2->to_api, $macro_4->to_api ] ); }; # Warn on unsupported query parameter - $t->get_ok( "//$userid:$password@/api/v1/advanced_editor/macros?macro_blah=blah" ) - ->status_is(400) - ->json_is( [{ path => '/query/macro_blah', message => 'Malformed query string'}] ); + $t->get_ok("//$userid:$password@/api/v1/advanced_editor/macros?macro_blah=blah")->status_is(400) + ->json_is( [ { path => '/query/macro_blah', message => 'Malformed query string' } ] ); }; @@ -123,50 +132,61 @@ subtest 'get() tests' => sub { plan tests => 15; - my $patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 1 } - }); + my $patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 1 } + } + ); my $password = 'thePassword123'; - $patron->set_password({ password => $password, skip_validation => 1 }); + $patron->set_password( { password => $password, skip_validation => 1 } ); my $userid = $patron->userid; - my $macro_1 = $builder->build_object( { class => 'Koha::AdvancedEditorMacros', value => { - shared => 1, + my $macro_1 = $builder->build_object( + { + class => 'Koha::AdvancedEditorMacros', + value => { + shared => 1, + } } - }); - my $macro_2 = $builder->build_object( { class => 'Koha::AdvancedEditorMacros', value => { - shared => 0, + ); + my $macro_2 = $builder->build_object( + { + class => 'Koha::AdvancedEditorMacros', + value => { + shared => 0, + } } - }); - my $macro_3 = $builder->build_object( { class => 'Koha::AdvancedEditorMacros', value => { - borrowernumber => $patron->borrowernumber, - shared => 0, + ); + my $macro_3 = $builder->build_object( + { + class => 'Koha::AdvancedEditorMacros', + value => { + borrowernumber => $patron->borrowernumber, + shared => 0, + } } - }); + ); $t->get_ok( "//$userid:$password@/api/v1/advanced_editor/macros/" . $macro_1->id ) - ->status_is( 403, 'Cannot get a shared macro via regular endpoint' ) - ->json_is( '/error' => 'This macro is shared, you must access it via advanced_editor/macros/shared' ); + ->status_is( 403, 'Cannot get a shared macro via regular endpoint' ) + ->json_is( '/error' => 'This macro is shared, you must access it via advanced_editor/macros/shared' ); $t->get_ok( "//$userid:$password@/api/v1/advanced_editor/macros/shared/" . $macro_1->id ) - ->status_is( 200, 'Can get a shared macro via shared endpoint' ) - ->json_is( $macro_1->to_api ); + ->status_is( 200, 'Can get a shared macro via shared endpoint' )->json_is( $macro_1->to_api ); $t->get_ok( "//$userid:$password@/api/v1/advanced_editor/macros/" . $macro_2->id ) - ->status_is( 403, 'Cannot access another users macro' ) - ->json_is( '/error' => 'You do not have permission to access this macro' ); + ->status_is( 403, 'Cannot access another users macro' ) + ->json_is( '/error' => 'You do not have permission to access this macro' ); $t->get_ok( "//$userid:$password@/api/v1/advanced_editor/macros/" . $macro_3->id ) - ->status_is( 200, 'Can get your own private macro' ) - ->json_is( $macro_3->to_api ); + ->status_is( 200, 'Can get your own private macro' )->json_is( $macro_3->to_api ); my $non_existent_code = $macro_1->id; $macro_1->delete; - $t->get_ok( "//$userid:$password@/api/v1/advanced_editor/macros/" . $non_existent_code ) - ->status_is(404) - ->json_is( '/error' => 'Macro not found' ); + $t->get_ok( "//$userid:$password@/api/v1/advanced_editor/macros/" . $non_existent_code )->status_is(404) + ->json_is( '/error' => 'Macro not found' ); }; @@ -174,66 +194,71 @@ subtest 'add() tests' => sub { plan tests => 24; - my $authorized_patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 0 } - }); - $builder->build({ - source => 'UserPermission', - value => { - borrowernumber => $authorized_patron->borrowernumber, - module_bit => 9, - code => 'advanced_editor', - }, - }); + my $authorized_patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 0 } + } + ); + $builder->build( + { + source => 'UserPermission', + value => { + borrowernumber => $authorized_patron->borrowernumber, + module_bit => 9, + code => 'advanced_editor', + }, + } + ); my $password = 'thePassword123'; - $authorized_patron->set_password({ password => $password, skip_validation => 1 }); + $authorized_patron->set_password( { password => $password, skip_validation => 1 } ); my $auth_userid = $authorized_patron->userid; - my $unauthorized_patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 0 } - }); - $unauthorized_patron->set_password({ password => $password, skip_validation => 1 }); + my $unauthorized_patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 0 } + } + ); + $unauthorized_patron->set_password( { password => $password, skip_validation => 1 } ); my $unauth_userid = $unauthorized_patron->userid; - my $macro = $builder->build_object({ - class => 'Koha::AdvancedEditorMacros', - value => { shared => 0 } - }); + my $macro = $builder->build_object( + { + class => 'Koha::AdvancedEditorMacros', + value => { shared => 0 } + } + ); my $macro_values = $macro->to_api; delete $macro_values->{macro_id}; $macro->delete; # Unauthorized attempt to write - $t->post_ok( "//$unauth_userid:$password@/api/v1/advanced_editor/macros" => json => $macro_values ) - ->status_is(403); + $t->post_ok( "//$unauth_userid:$password@/api/v1/advanced_editor/macros" => json => $macro_values )->status_is(403); # Authorized attempt to write invalid data - my $macro_with_invalid_field = { %$macro_values }; + my $macro_with_invalid_field = {%$macro_values}; $macro_with_invalid_field->{'big_mac_ro'} = 'Mac attack'; $t->post_ok( "//$auth_userid:$password@/api/v1/advanced_editor/macros" => json => $macro_with_invalid_field ) - ->status_is(400) - ->json_is( + ->status_is(400)->json_is( "/errors" => [ { message => "Properties not allowed: big_mac_ro.", path => "/body" } ] - ); + ); # Authorized attempt to write $t->post_ok( "//$auth_userid:$password@/api/v1/advanced_editor/macros" => json => $macro_values ) - ->status_is( 201, 'REST3.2.1' ) - ->json_has( '/macro_id', 'We generated a new id' ) - ->json_is( '/name' => $macro_values->{name}, 'The name matches what we supplied' ) - ->json_is( '/macro_text' => $macro_values->{macro_text}, 'The text matches what we supplied' ) - ->json_is( '/patron_id' => $macro_values->{patron_id}, 'The borrower matches the borrower who submitted' ) - ->json_is( '/shared' => Mojo::JSON->false, 'The macro is not shared' ) - ->header_like( Location => qr|^\/api\/v1\/advanced_editor/macros\/d*|, 'Correct location' ); + ->status_is( 201, 'REST3.2.1' )->json_has( '/macro_id', 'We generated a new id' ) + ->json_is( '/name' => $macro_values->{name}, 'The name matches what we supplied' ) + ->json_is( '/macro_text' => $macro_values->{macro_text}, 'The text matches what we supplied' ) + ->json_is( '/patron_id' => $macro_values->{patron_id}, 'The borrower matches the borrower who submitted' ) + ->json_is( '/shared' => Mojo::JSON->false, 'The macro is not shared' ) + ->header_like( Location => qr|^\/api\/v1\/advanced_editor/macros\/d*|, 'Correct location' ); # save the library_id my $macro_id = 999; @@ -241,235 +266,258 @@ subtest 'add() tests' => sub { # Authorized attempt to create with existing id $macro_values->{macro_id} = $macro_id; - $t->post_ok( "//$auth_userid:$password@/api/v1/advanced_editor/macros" => json => $macro_values ) - ->status_is(400) - ->json_is( '/errors' => [ + $t->post_ok( "//$auth_userid:$password@/api/v1/advanced_editor/macros" => json => $macro_values )->status_is(400) + ->json_is( + '/errors' => [ { message => "Read-only.", - path => "/body/macro_id" + path => "/body/macro_id" } ] - ); + ); $macro_values->{shared} = Mojo::JSON->true; delete $macro_values->{macro_id}; # Unauthorized attempt to write a shared macro on private endpoint - $t->post_ok( "//$auth_userid:$password@/api/v1/advanced_editor/macros" => json => $macro_values ) - ->status_is(403); + $t->post_ok( "//$auth_userid:$password@/api/v1/advanced_editor/macros" => json => $macro_values )->status_is(403); + # Unauthorized attempt to write a private macro on shared endpoint $t->post_ok( "//$auth_userid:$password@/api/v1/advanced_editor/macros/shared" => json => $macro_values ) - ->status_is(403); + ->status_is(403); - $builder->build({ - source => 'UserPermission', - value => { - borrowernumber => $authorized_patron->borrowernumber, - module_bit => 9, - code => 'create_shared_macros', - }, - }); + $builder->build( + { + source => 'UserPermission', + value => { + borrowernumber => $authorized_patron->borrowernumber, + module_bit => 9, + code => 'create_shared_macros', + }, + } + ); # Authorized attempt to write a shared macro on private endpoint - $t->post_ok( "//$auth_userid:$password@/api/v1/advanced_editor/macros" => json => $macro_values ) - ->status_is(403); + $t->post_ok( "//$auth_userid:$password@/api/v1/advanced_editor/macros" => json => $macro_values )->status_is(403); # Authorized attempt to write a shared macro on shared endpoint $t->post_ok( "//$auth_userid:$password@/api/v1/advanced_editor/macros/shared" => json => $macro_values ) - ->status_is(201); + ->status_is(201); }; subtest 'update() tests' => sub { plan tests => 32; - my $authorized_patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 0 } - }); - $builder->build({ - source => 'UserPermission', - value => { - borrowernumber => $authorized_patron->borrowernumber, - module_bit => 9, - code => 'advanced_editor', - }, - }); + my $authorized_patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 0 } + } + ); + $builder->build( + { + source => 'UserPermission', + value => { + borrowernumber => $authorized_patron->borrowernumber, + module_bit => 9, + code => 'advanced_editor', + }, + } + ); my $password = 'thePassword123'; - $authorized_patron->set_password({ password => $password, skip_validation => 1 }); + $authorized_patron->set_password( { password => $password, skip_validation => 1 } ); my $auth_userid = $authorized_patron->userid; - my $unauthorized_patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 0 } - }); - $unauthorized_patron->set_password({ password => $password, skip_validation => 1 }); + my $unauthorized_patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 0 } + } + ); + $unauthorized_patron->set_password( { password => $password, skip_validation => 1 } ); my $unauth_userid = $unauthorized_patron->userid; - my $macro = $builder->build_object({ - class => 'Koha::AdvancedEditorMacros', - value => { borrowernumber => $authorized_patron->borrowernumber, shared => 0 } - }); - my $macro_2 = $builder->build_object({ - class => 'Koha::AdvancedEditorMacros', - value => { borrowernumber => $unauthorized_patron->borrowernumber, shared => 0 } - }); - my $macro_id = $macro->id; - my $macro_2_id = $macro_2->id; + my $macro = $builder->build_object( + { + class => 'Koha::AdvancedEditorMacros', + value => { borrowernumber => $authorized_patron->borrowernumber, shared => 0 } + } + ); + my $macro_2 = $builder->build_object( + { + class => 'Koha::AdvancedEditorMacros', + value => { borrowernumber => $unauthorized_patron->borrowernumber, shared => 0 } + } + ); + my $macro_id = $macro->id; + my $macro_2_id = $macro_2->id; my $macro_values = $macro->to_api; delete $macro_values->{macro_id}; # Unauthorized attempt to update - $t->put_ok( "//$unauth_userid:$password@/api/v1/advanced_editor/macros/$macro_id" - => json => { name => 'New unauthorized name change' } ) - ->status_is(403); + $t->put_ok( "//$unauth_userid:$password@/api/v1/advanced_editor/macros/$macro_id" => json => + { name => 'New unauthorized name change' } )->status_is(403); # Attempt partial update on a PUT my $macro_with_missing_field = { name => "Call it macro-roni", }; - $t->put_ok( "//$auth_userid:$password@/api/v1/advanced_editor/macros/$macro_id" => json => $macro_with_missing_field ) - ->status_is(400) - ->json_has( "/errors" => - [ { message => "Missing property.", path => "/body/macro_text" } ] - ); + $t->put_ok( + "//$auth_userid:$password@/api/v1/advanced_editor/macros/$macro_id" => json => $macro_with_missing_field ) + ->status_is(400)->json_has( "/errors" => [ { message => "Missing property.", path => "/body/macro_text" } ] ); my $macro_update = { - name => "Macro-update", + name => "Macro-update", macro_text => "delete 100", - patron_id => $authorized_patron->borrowernumber, - shared => Mojo::JSON->false, + patron_id => $authorized_patron->borrowernumber, + shared => Mojo::JSON->false, }; - my $test = $t->put_ok( "//$auth_userid:$password@/api/v1/advanced_editor/macros/$macro_id" => json => $macro_update ) - ->status_is(200, 'Authorized user can update a macro') - ->json_is( '/macro_id' => $macro_id, 'We get the id back' ) - ->json_is( '/name' => $macro_update->{name}, 'We get the name back' ) - ->json_is( '/macro_text' => $macro_update->{macro_text}, 'We get the text back' ) - ->json_is( '/patron_id' => $macro_update->{patron_id}, 'We get the patron_id back' ) - ->json_is( '/shared' => $macro_update->{shared}, 'It should still not be shared' ); + my $test = + $t->put_ok( "//$auth_userid:$password@/api/v1/advanced_editor/macros/$macro_id" => json => $macro_update ) + ->status_is( 200, 'Authorized user can update a macro' ) + ->json_is( '/macro_id' => $macro_id, 'We get the id back' ) + ->json_is( '/name' => $macro_update->{name}, 'We get the name back' ) + ->json_is( '/macro_text' => $macro_update->{macro_text}, 'We get the text back' ) + ->json_is( '/patron_id' => $macro_update->{patron_id}, 'We get the patron_id back' ) + ->json_is( '/shared' => $macro_update->{shared}, 'It should still not be shared' ); # Now try to make the macro shared $macro_update->{shared} = Mojo::JSON->true; $t->put_ok( "//$auth_userid:$password@/api/v1/advanced_editor/macros/shared/$macro_id" => json => $macro_update ) - ->status_is(403, 'Cannot make your macro shared on private endpoint'); + ->status_is( 403, 'Cannot make your macro shared on private endpoint' ); $t->put_ok( "//$auth_userid:$password@/api/v1/advanced_editor/macros/shared/$macro_id" => json => $macro_update ) - ->status_is(403, 'Cannot make your macro shared without permission'); + ->status_is( 403, 'Cannot make your macro shared without permission' ); - $builder->build({ - source => 'UserPermission', - value => { - borrowernumber => $authorized_patron->borrowernumber, - module_bit => 9, - code => 'create_shared_macros', - }, - }); + $builder->build( + { + source => 'UserPermission', + value => { + borrowernumber => $authorized_patron->borrowernumber, + module_bit => 9, + code => 'create_shared_macros', + }, + } + ); $t->put_ok( "//$auth_userid:$password@/api/v1/advanced_editor/macros/$macro_id" => json => $macro_update ) - ->status_is(403, 'Cannot make your macro shared on the private endpoint'); + ->status_is( 403, 'Cannot make your macro shared on the private endpoint' ); $t->put_ok( "//$auth_userid:$password@/api/v1/advanced_editor/macros/shared/$macro_id" => json => $macro_update ) - ->status_is(200, 'Can update macro to shared with permission') - ->json_is( '/macro_id' => $macro_id, 'We get back the id' ) - ->json_is( '/name' => $macro_update->{name}, 'We get back the name' ) - ->json_is( '/macro_text' => $macro_update->{macro_text}, 'We get back the text' ) - ->json_is( '/patron_id' => $macro_update->{patron_id}, 'We get back our patron id' ) - ->json_is( '/shared' => Mojo::JSON->true, 'It is shared' ); + ->status_is( 200, 'Can update macro to shared with permission' ) + ->json_is( '/macro_id' => $macro_id, 'We get back the id' ) + ->json_is( '/name' => $macro_update->{name}, 'We get back the name' ) + ->json_is( '/macro_text' => $macro_update->{macro_text}, 'We get back the text' ) + ->json_is( '/patron_id' => $macro_update->{patron_id}, 'We get back our patron id' ) + ->json_is( '/shared' => Mojo::JSON->true, 'It is shared' ); # Authorized attempt to write invalid data - my $macro_with_invalid_field = { %$macro_update }; + my $macro_with_invalid_field = {%$macro_update}; $macro_with_invalid_field->{'big_mac_ro'} = 'Mac attack'; - $t->put_ok( "//$auth_userid:$password@/api/v1/advanced_editor/macros/$macro_id" => json => $macro_with_invalid_field ) - ->status_is(400) - ->json_is( + $t->put_ok( + "//$auth_userid:$password@/api/v1/advanced_editor/macros/$macro_id" => json => $macro_with_invalid_field ) + ->status_is(400)->json_is( "/errors" => [ { message => "Properties not allowed: big_mac_ro.", path => "/body" } ] - ); + ); - my $non_existent_macro = $builder->build_object({class => 'Koha::AdvancedEditorMacros'}); - my $non_existent_code = $non_existent_macro->id; + my $non_existent_macro = $builder->build_object( { class => 'Koha::AdvancedEditorMacros' } ); + my $non_existent_code = $non_existent_macro->id; $non_existent_macro->delete; - $t->put_ok("//$auth_userid:$password@/api/v1/advanced_editor/macros/$non_existent_code" => json => $macro_update) - ->status_is(404); + $t->put_ok( "//$auth_userid:$password@/api/v1/advanced_editor/macros/$non_existent_code" => json => $macro_update ) + ->status_is(404); - $t->put_ok("//$auth_userid:$password@/api/v1/advanced_editor/macros/$macro_2_id" => json => $macro_update) - ->status_is(403, "Cannot update other borrowers private macro"); + $t->put_ok( "//$auth_userid:$password@/api/v1/advanced_editor/macros/$macro_2_id" => json => $macro_update ) + ->status_is( 403, "Cannot update other borrowers private macro" ); }; subtest 'delete() tests' => sub { plan tests => 12; - my $authorized_patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 0 } - }); - $builder->build({ - source => 'UserPermission', - value => { - borrowernumber => $authorized_patron->borrowernumber, - module_bit => 9, - code => 'advanced_editor', - }, - }); + my $authorized_patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 0 } + } + ); + $builder->build( + { + source => 'UserPermission', + value => { + borrowernumber => $authorized_patron->borrowernumber, + module_bit => 9, + code => 'advanced_editor', + }, + } + ); my $password = 'thePassword123'; - $authorized_patron->set_password({ password => $password, skip_validation => 1 }); + $authorized_patron->set_password( { password => $password, skip_validation => 1 } ); my $auth_userid = $authorized_patron->userid; - my $unauthorized_patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 0 } - }); - $unauthorized_patron->set_password({ password => $password, skip_validation => 1 }); + my $unauthorized_patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 0 } + } + ); + $unauthorized_patron->set_password( { password => $password, skip_validation => 1 } ); my $unauth_userid = $unauthorized_patron->userid; - my $macro = $builder->build_object({ - class => 'Koha::AdvancedEditorMacros', - value => { borrowernumber => $authorized_patron->borrowernumber, shared => 0 } - }); - my $macro_2 = $builder->build_object({ - class => 'Koha::AdvancedEditorMacros', - value => { borrowernumber => $unauthorized_patron->borrowernumber, shared => 0 } - }); - my $macro_id = $macro->id; + my $macro = $builder->build_object( + { + class => 'Koha::AdvancedEditorMacros', + value => { borrowernumber => $authorized_patron->borrowernumber, shared => 0 } + } + ); + my $macro_2 = $builder->build_object( + { + class => 'Koha::AdvancedEditorMacros', + value => { borrowernumber => $unauthorized_patron->borrowernumber, shared => 0 } + } + ); + my $macro_id = $macro->id; my $macro_2_id = $macro_2->id; # Unauthorized attempt to delete - $t->delete_ok( "//$unauth_userid:$password@/api/v1/advanced_editor/macros/$macro_2_id") - ->status_is(403, "Cannot delete macro without permission"); + $t->delete_ok("//$unauth_userid:$password@/api/v1/advanced_editor/macros/$macro_2_id") + ->status_is( 403, "Cannot delete macro without permission" ); - $t->delete_ok( "//$auth_userid:$password@/api/v1/advanced_editor/macros/$macro_id") - ->status_is( 204, 'Can delete macro with permission'); + $t->delete_ok("//$auth_userid:$password@/api/v1/advanced_editor/macros/$macro_id") + ->status_is( 204, 'Can delete macro with permission' ); - $t->delete_ok( "//$auth_userid:$password@/api/v1/advanced_editor/macros/$macro_2_id") - ->status_is(403, 'Cannot delete other users macro with permission'); + $t->delete_ok("//$auth_userid:$password@/api/v1/advanced_editor/macros/$macro_2_id") + ->status_is( 403, 'Cannot delete other users macro with permission' ); $macro_2->shared(1)->store(); - $t->delete_ok( "//$auth_userid:$password@/api/v1/advanced_editor/macros/shared/$macro_2_id") - ->status_is(403, 'Cannot delete other users shared macro without permission'); + $t->delete_ok("//$auth_userid:$password@/api/v1/advanced_editor/macros/shared/$macro_2_id") + ->status_is( 403, 'Cannot delete other users shared macro without permission' ); - $builder->build({ - source => 'UserPermission', - value => { - borrowernumber => $authorized_patron->borrowernumber, - module_bit => 9, - code => 'delete_shared_macros', - }, - }); - $t->delete_ok( "//$auth_userid:$password@/api/v1/advanced_editor/macros/$macro_2_id") - ->status_is(403, 'Cannot delete other users shared macro with permission on private endpoint'); - $t->delete_ok( "//$auth_userid:$password@/api/v1/advanced_editor/macros/shared/$macro_2_id") - ->status_is(204, 'Can delete other users shared macro with permission'); + $builder->build( + { + source => 'UserPermission', + value => { + borrowernumber => $authorized_patron->borrowernumber, + module_bit => 9, + code => 'delete_shared_macros', + }, + } + ); + $t->delete_ok("//$auth_userid:$password@/api/v1/advanced_editor/macros/$macro_2_id") + ->status_is( 403, 'Cannot delete other users shared macro with permission on private endpoint' ); + $t->delete_ok("//$auth_userid:$password@/api/v1/advanced_editor/macros/shared/$macro_2_id") + ->status_is( 204, 'Can delete other users shared macro with permission' ); }; diff --git a/t/db_dependent/api/v1/article_requests.t b/t/db_dependent/api/v1/article_requests.t index 9ba0ffb060..55208a91ac 100755 --- a/t/db_dependent/api/v1/article_requests.t +++ b/t/db_dependent/api/v1/article_requests.t @@ -40,22 +40,19 @@ subtest 'cancel() tests' => sub { my $authorized_patron = $builder->build_object( { class => 'Koha::Patrons', - value => { flags => 2 ** 1 } # circulate flag = 1 + value => { flags => 2**1 } # circulate flag = 1 } ); my $password = 'thePassword123'; - $authorized_patron->set_password( - { password => $password, skip_validation => 1 } ); + $authorized_patron->set_password( { password => $password, skip_validation => 1 } ); my $userid = $authorized_patron->userid; - my $deleted_article_request = - $builder->build_object( { class => 'Koha::ArticleRequests' } ); + my $deleted_article_request = $builder->build_object( { class => 'Koha::ArticleRequests' } ); my $deleted_article_request_id = $deleted_article_request->id; $deleted_article_request->delete; - $t->delete_ok( -"//$userid:$password@/api/v1/article_requests/$deleted_article_request_id" - )->status_is(404)->json_is( '/error_code' => 'not_found' ); + $t->delete_ok("//$userid:$password@/api/v1/article_requests/$deleted_article_request_id")->status_is(404) + ->json_is( '/error_code' => 'not_found' ); my $article_request = $builder->build_object( { @@ -68,15 +65,17 @@ subtest 'cancel() tests' => sub { my $notes = 'Some notes'; $t->delete_ok( "//$userid:$password@/api/v1/article_requests/" - . $article_request->id - . "?cancellation_reason=$reason¬es=$notes" ) - ->status_is( 204, 'REST3.2.4' )->content_is( q{}, 'REST3.2.4' ); + . $article_request->id + . "?cancellation_reason=$reason¬es=$notes" )->status_is( 204, 'REST3.2.4' ) + ->content_is( q{}, 'REST3.2.4' ); # refresh object $article_request->discard_changes; - is( $article_request->cancellation_reason, - $reason, 'Reason stored correctly' ); + is( + $article_request->cancellation_reason, + $reason, 'Reason stored correctly' + ); is( $article_request->notes, $notes, 'Notes stored correctly' ); $schema->storage->txn_rollback; @@ -102,24 +101,25 @@ subtest 'patron_cancel() tests' => sub { my $userid = $patron->userid; my $patron_id = $patron->borrowernumber; - my $deleted_article_request = $builder->build_object( { class => 'Koha::ArticleRequests', value => { borrowernumber => $patron_id } } ); + my $deleted_article_request = + $builder->build_object( { class => 'Koha::ArticleRequests', value => { borrowernumber => $patron_id } } ); my $deleted_article_request_id = $deleted_article_request->id; $deleted_article_request->delete; # delete non existent article request $t->delete_ok("//$userid:$password@/api/v1/public/patrons/$patron_id/article_requests/$deleted_article_request_id") - ->status_is(404) - ->json_is( '/error_code' => 'not_found' ); + ->status_is(404)->json_is( '/error_code' => 'not_found' ); - my $another_patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $another_patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $another_patron_id = $another_patron->id; - my $article_request_2 = $builder->build_object({ class => 'Koha::ArticleRequests', value => { borrowernumber => $another_patron_id } }); + my $article_request_2 = $builder->build_object( + { class => 'Koha::ArticleRequests', value => { borrowernumber => $another_patron_id } } ); # delete another patron's request - $t->delete_ok("//$userid:$password@/api/v1/public/patrons/$another_patron_id/article_requests/" . $article_request_2->id) - ->status_is(403) - ->json_is( '/error' => 'Authorization failure. Missing required permission(s).' ); + $t->delete_ok( + "//$userid:$password@/api/v1/public/patrons/$another_patron_id/article_requests/" . $article_request_2->id ) + ->status_is(403)->json_is( '/error' => 'Authorization failure. Missing required permission(s).' ); my $another_article_request = $builder->build_object( { @@ -128,9 +128,9 @@ subtest 'patron_cancel() tests' => sub { } ); - $t->delete_ok("//$userid:$password@/api/v1/public/patrons/$patron_id/article_requests/" . $another_article_request->id) - ->status_is(404) - ->json_is( '/error_code' => 'not_found' ); + $t->delete_ok( + "//$userid:$password@/api/v1/public/patrons/$patron_id/article_requests/" . $another_article_request->id ) + ->status_is(404)->json_is( '/error_code' => 'not_found' ); my $article_request = $builder->build_object( { @@ -142,18 +142,16 @@ subtest 'patron_cancel() tests' => sub { my $reason = 'A reason'; my $notes = 'Some notes'; - $t->delete_ok( - "//$userid:$password@/api/v1/public/patrons/$patron_id/article_requests/" - . $article_request->id - . "?cancellation_reason=$reason¬es=$notes" ) - ->status_is( 204, 'REST3.2.4' ) - ->content_is( q{}, 'REST3.2.4' ); + $t->delete_ok( "//$userid:$password@/api/v1/public/patrons/$patron_id/article_requests/" + . $article_request->id + . "?cancellation_reason=$reason¬es=$notes" )->status_is( 204, 'REST3.2.4' ) + ->content_is( q{}, 'REST3.2.4' ); # refresh object $article_request->discard_changes; is( $article_request->cancellation_reason, $reason, 'Reason stored correctly' ); - is( $article_request->notes, $notes, 'Notes stored correctly' ); + is( $article_request->notes, $notes, 'Notes stored correctly' ); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/api/v1/auth.t b/t/db_dependent/api/v1/auth.t index 5d4f827f58..a3bf90bce5 100755 --- a/t/db_dependent/api/v1/auth.t +++ b/t/db_dependent/api/v1/auth.t @@ -44,15 +44,14 @@ subtest 'under() tests' => sub { $schema->storage->txn_begin; - my ($borrowernumber, $session_id) = create_user_and_session(); + my ( $borrowernumber, $session_id ) = create_user_and_session(); # disable the /public namespace t::lib::Mocks::mock_preference( 'RESTPublicAPI', 0 ); $tx = $t->ua->build_tx( POST => "/api/v1/public/patrons/$borrowernumber/password" ); $tx->req->env( { REMOTE_ADDR => $remote_address } ); - $t->request_ok($tx) - ->status_is(403) - ->json_is('/error', 'Configuration prevents the usage of this endpoint by unprivileged users'); + $t->request_ok($tx)->status_is(403) + ->json_is( '/error', 'Configuration prevents the usage of this endpoint by unprivileged users' ); # enable the /public namespace t::lib::Mocks::mock_preference( 'RESTPublicAPI', 1 ); @@ -63,46 +62,34 @@ subtest 'under() tests' => sub { # 401 (no authentication) $tx = $t->ua->build_tx( GET => "/api/v1/patrons" ); $tx->req->env( { REMOTE_ADDR => $remote_address } ); - $t->request_ok($tx) - ->status_is(401) - ->json_is('/error', 'Authentication failure.'); + $t->request_ok($tx)->status_is(401)->json_is( '/error', 'Authentication failure.' ); # 403 (no permission) $tx = $t->ua->build_tx( GET => "/api/v1/patrons" ); - $tx->req->cookies( - { name => 'CGISESSID', value => $session_id } ); + $tx->req->cookies( { name => 'CGISESSID', value => $session_id } ); $tx->req->env( { REMOTE_ADDR => $remote_address } ); - $t->request_ok($tx) - ->status_is(403) - ->json_is('/error', 'Authorization failure. Missing required permission(s).'); + $t->request_ok($tx)->status_is(403)->json_is( '/error', 'Authorization failure. Missing required permission(s).' ); # 401 (session expired) t::lib::Mocks::mock_preference( 'timeout', '1' ); - ($borrowernumber, $session_id) = create_user_and_session(); + ( $borrowernumber, $session_id ) = create_user_and_session(); $tx = $t->ua->build_tx( GET => "/api/v1/patrons" ); - $tx->req->cookies( - { name => 'CGISESSID', value => $session_id } ); + $tx->req->cookies( { name => 'CGISESSID', value => $session_id } ); $tx->req->env( { REMOTE_ADDR => $remote_address } ); sleep(2); - $t->request_ok($tx) - ->status_is(401) - ->json_is('/error', 'Session has been expired.'); + $t->request_ok($tx)->status_is(401)->json_is( '/error', 'Session has been expired.' ); # 503 (under maintenance & pending update) - t::lib::Mocks::mock_preference('Version', 1); + t::lib::Mocks::mock_preference( 'Version', 1 ); $tx = $t->ua->build_tx( GET => "/api/v1/patrons" ); $tx->req->env( { REMOTE_ADDR => $remote_address } ); - $t->request_ok($tx) - ->status_is(503) - ->json_is('/error', 'System is under maintenance.'); + $t->request_ok($tx)->status_is(503)->json_is( '/error', 'System is under maintenance.' ); # 503 (under maintenance & database not installed) - t::lib::Mocks::mock_preference('Version', undef); + t::lib::Mocks::mock_preference( 'Version', undef ); $tx = $t->ua->build_tx( GET => "/api/v1/patrons" ); $tx->req->env( { REMOTE_ADDR => $remote_address } ); - $t->request_ok($tx) - ->status_is(503) - ->json_is('/error', 'System is under maintenance.'); + $t->request_ok($tx)->status_is(503)->json_is( '/error', 'System is under maintenance.' ); # 503 (public while maintenance syspref activated) t::lib::Mocks::mock_preference( 'OPACMaintenance', 1 ); @@ -120,39 +107,34 @@ subtest 'CORS support' => sub { plan tests => 6; - t::lib::Mocks::mock_preference('AccessControlAllowOrigin',''); - $t->get_ok("/api/v1/patrons") - ->header_is( 'Access-control-allow-origin', undef, 'Header not returned' ); - # FIXME: newer Test::Mojo has header_exists_not + t::lib::Mocks::mock_preference( 'AccessControlAllowOrigin', '' ); + $t->get_ok("/api/v1/patrons")->header_is( 'Access-control-allow-origin', undef, 'Header not returned' ); - t::lib::Mocks::mock_preference('AccessControlAllowOrigin',undef); - $t->get_ok("/api/v1/patrons") - ->header_is( 'Access-control-allow-origin', undef, 'Header not returned' ); # FIXME: newer Test::Mojo has header_exists_not - t::lib::Mocks::mock_preference('AccessControlAllowOrigin','*'); - $t->get_ok("/api/v1/patrons") - ->header_is( 'Access-control-allow-origin', '*', 'Header set' ); + t::lib::Mocks::mock_preference( 'AccessControlAllowOrigin', undef ); + $t->get_ok("/api/v1/patrons")->header_is( 'Access-control-allow-origin', undef, 'Header not returned' ); + + # FIXME: newer Test::Mojo has header_exists_not + + t::lib::Mocks::mock_preference( 'AccessControlAllowOrigin', '*' ); + $t->get_ok("/api/v1/patrons")->header_is( 'Access-control-allow-origin', '*', 'Header set' ); }; subtest 'spec retrieval tests' => sub { plan tests => 4; - $t->get_ok("/api/v1/") - ->status_is(200); + $t->get_ok("/api/v1/")->status_is(200); - $t->get_ok("/api/v1/.html") - ->status_is(200); + $t->get_ok("/api/v1/.html")->status_is(200); }; sub create_user_and_session { my $user = $builder->build( { source => 'Borrower', - value => { - flags => 0 - } + value => { flags => 0 } } ); diff --git a/t/db_dependent/api/v1/auth_authenticate_api_request.t b/t/db_dependent/api/v1/auth_authenticate_api_request.t index d4e8e97445..e5c4d9c728 100755 --- a/t/db_dependent/api/v1/auth_authenticate_api_request.t +++ b/t/db_dependent/api/v1/auth_authenticate_api_request.t @@ -29,7 +29,7 @@ use Koha::Patrons; use t::lib::Mocks; use t::lib::TestBuilder; -my $t = Test::Mojo->new('Koha::REST::V1'); +my $t = Test::Mojo->new('Koha::REST::V1'); my $schema = Koha::Database->new->schema; my $builder = t::lib::TestBuilder->new(); @@ -45,32 +45,30 @@ subtest 'token-based tests' => sub { if ( can_load( modules => { 'Net::OAuth2::AuthorizationServer' => undef } ) ) { plan tests => 15; - } - else { + } else { plan skip_all => 'Net::OAuth2::AuthorizationServer not available'; } $schema->storage->txn_begin; - my $patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 1 }, - }); + my $patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 1 }, + } + ); - t::lib::Mocks::mock_preference('RESTOAuth2ClientCredentials', 1); + t::lib::Mocks::mock_preference( 'RESTOAuth2ClientCredentials', 1 ); - my $api_key = Koha::ApiKey->new({ patron_id => $patron->id, description => 'blah' })->store; + my $api_key = Koha::ApiKey->new( { patron_id => $patron->id, description => 'blah' } )->store; my $formData = { grant_type => 'client_credentials', client_id => $api_key->client_id, client_secret => $api_key->plain_text_secret }; - $t->post_ok('/api/v1/oauth/token', form => $formData) - ->status_is(200) - ->json_is('/expires_in' => 3600) - ->json_is('/token_type' => 'Bearer') - ->json_has('/access_token'); + $t->post_ok( '/api/v1/oauth/token', form => $formData )->status_is(200)->json_is( '/expires_in' => 3600 ) + ->json_is( '/token_type' => 'Bearer' )->json_has('/access_token'); my $access_token = $t->tx->res->json->{access_token}; @@ -100,12 +98,12 @@ subtest 'token-based tests' => sub { $t->request_ok($tx)->status_is(200); my $user = $stash->{'koha.user'}; - ok( defined $user, 'The \'koha.user\' object is defined in the stash') and - is( ref($user), 'Koha::Patron', 'Stashed koha.user object type is Koha::Patron') and - is( $user->borrowernumber, $patron->borrowernumber, 'The stashed user is the right one' ); + ok( defined $user, 'The \'koha.user\' object is defined in the stash' ) + and is( ref($user), 'Koha::Patron', 'Stashed koha.user object type is Koha::Patron' ) + and is( $user->borrowernumber, $patron->borrowernumber, 'The stashed user is the right one' ); is( $userenv->{number}, $patron->borrowernumber, 'userenv set correctly' ); - is( $interface, 'api', "Interface correctly set to \'api\'" ); - is( $language_env, $accept_language, 'HTTP_ACCEPT_LANGUAGE correctly set in %ENV' ); + is( $interface, 'api', "Interface correctly set to \'api\'" ); + is( $language_env, $accept_language, 'HTTP_ACCEPT_LANGUAGE correctly set in %ENV' ); my $embed = $stash->{'koha.embed'}; ok( defined $embed, 'The embed hashref is generated and stashed' ); @@ -120,7 +118,7 @@ subtest 'cookie-based tests' => sub { $schema->storage->txn_begin; - my ( $borrowernumber, $session_id ) = create_user_and_session({ authorized => 1 }); + my ( $borrowernumber, $session_id ) = create_user_and_session( { authorized => 1 } ); my $stash; my $interface; @@ -147,12 +145,12 @@ subtest 'cookie-based tests' => sub { $t->request_ok($tx)->status_is(200); my $user = $stash->{'koha.user'}; - ok( defined $user, 'The \'koha.user\' object is defined in the stash') and - is( ref($user), 'Koha::Patron', 'Stashed koha.user object type is Koha::Patron') and - is( $user->borrowernumber, $borrowernumber, 'The stashed user is the right one' ); - is( $userenv->{number}, $borrowernumber, 'userenv set correctly' ); - is( $interface, 'api', "Interface correctly set to \'api\'" ); - is( $language_env, $accept_language, 'HTTP_ACCEPT_LANGUAGE correctly set in %ENV' ); + ok( defined $user, 'The \'koha.user\' object is defined in the stash' ) + and is( ref($user), 'Koha::Patron', 'Stashed koha.user object type is Koha::Patron' ) + and is( $user->borrowernumber, $borrowernumber, 'The stashed user is the right one' ); + is( $userenv->{number}, $borrowernumber, 'userenv set correctly' ); + is( $interface, 'api', "Interface correctly set to \'api\'" ); + is( $language_env, $accept_language, 'HTTP_ACCEPT_LANGUAGE correctly set in %ENV' ); subtest 'logged-out tests' => sub { plan tests => 3; @@ -165,12 +163,11 @@ subtest 'cookie-based tests' => sub { $session->flush; my $tx = $t->ua->build_tx( GET => '/api/v1/libraries' ); - $tx->req->cookies({ name => 'CGISESSID', value => $session->id }); - $tx->req->env({ REMOTE_ADDR => $remote_address }); + $tx->req->cookies( { name => 'CGISESSID', value => $session->id } ); + $tx->req->env( { REMOTE_ADDR => $remote_address } ); - $t->request_ok($tx) - ->status_is( 401, 'Anonymous session on permission protected resource returns 401' ) - ->json_is( { error => 'Authentication failure.' } ); + $t->request_ok($tx)->status_is( 401, 'Anonymous session on permission protected resource returns 401' ) + ->json_is( { error => 'Authentication failure.' } ); }; $schema->storage->txn_rollback; @@ -186,25 +183,28 @@ subtest 'anonymous requests to public API' => sub { my $password = 'AbcdEFG123'; my $userid = 'tomasito'; + # Add a patron - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); - $patron->set_password({ password => $password }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + $patron->set_password( { password => $password } ); + # Add a biblio my $biblio_id = $builder->build_sample_biblio()->biblionumber; # Enable the public API t::lib::Mocks::mock_preference( 'RESTPublicAPI', 1 ); + # Disable anonymous requests on the public namespace t::lib::Mocks::mock_preference( 'RESTPublicAnonymousRequests', 0 ); - $t->get_ok("/api/v1/public/biblios/" . $biblio_id => { Accept => 'application/marc' }) - ->status_is( 401, 'Unauthorized anonymous attempt to access a resource' ); + $t->get_ok( "/api/v1/public/biblios/" . $biblio_id => { Accept => 'application/marc' } ) + ->status_is( 401, 'Unauthorized anonymous attempt to access a resource' ); # Disable anonymous requests on the public namespace t::lib::Mocks::mock_preference( 'RESTPublicAnonymousRequests', 1 ); - $t->get_ok("/api/v1/public/biblios/" . $biblio_id => { Accept => 'application/marc' }) - ->status_is( 200, 'Successfull anonymous access to a resource' ); + $t->get_ok( "/api/v1/public/biblios/" . $biblio_id => { Accept => 'application/marc' } ) + ->status_is( 200, 'Successfull anonymous access to a resource' ); $schema->storage->txn_rollback; }; @@ -218,31 +218,37 @@ subtest 'x-koha-library tests' => sub { my $stash; my $userenv; - $t->app->hook(after_dispatch => sub { - $stash = shift->stash; - $userenv = C4::Context->userenv; - }); + $t->app->hook( + after_dispatch => sub { + $stash = shift->stash; + $userenv = C4::Context->userenv; + } + ); t::lib::Mocks::mock_preference( 'RESTBasicAuth', 1 ); - my $superlibrarian = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 1 } - }); + my $superlibrarian = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 1 } + } + ); my $password = 'thePassword123'; - $superlibrarian->set_password({ password => $password, skip_validation => 1 }); + $superlibrarian->set_password( { password => $password, skip_validation => 1 } ); my $superlibrarian_userid = $superlibrarian->userid; - my $unprivileged = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => undef } - }); - $unprivileged->set_password({ password => $password, skip_validation => 1 }); + my $unprivileged = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => undef } + } + ); + $unprivileged->set_password( { password => $password, skip_validation => 1 } ); my $unprivileged_userid = $unprivileged->userid; my $library = $builder->build_object( { class => 'Koha::Libraries' } ); ## Independent branches tests - t::lib::Mocks::mock_preference('IndependentBranches', 1); + t::lib::Mocks::mock_preference( 'IndependentBranches', 1 ); $t->get_ok( "//$unprivileged_userid:$password@/api/v1/cities", @@ -251,18 +257,16 @@ subtest 'x-koha-library tests' => sub { is( $userenv->{branch}, $unprivileged->branchcode, 'branch set correctly' ); - $t->get_ok( "//$unprivileged_userid:$password@/api/v1/cities" => - { 'x-koha-library' => $library->id } )->status_is(403) - ->json_is( - '/error' => 'Unauthorized attempt to set library to ' . $library->id ); + $t->get_ok( "//$unprivileged_userid:$password@/api/v1/cities" => { 'x-koha-library' => $library->id } ) + ->status_is(403)->json_is( '/error' => 'Unauthorized attempt to set library to ' . $library->id ); - $t->get_ok( "//$superlibrarian_userid:$password@/api/v1/cities" => - { 'x-koha-library' => $library->id } )->status_is(200); + $t->get_ok( "//$superlibrarian_userid:$password@/api/v1/cities" => { 'x-koha-library' => $library->id } ) + ->status_is(200); is( $userenv->{branch}, $library->id, 'branch set correctly' ); ## !Independent branches tests - t::lib::Mocks::mock_preference('IndependentBranches', 1); + t::lib::Mocks::mock_preference( 'IndependentBranches', 1 ); $t->get_ok( "//$unprivileged_userid:$password@/api/v1/cities", { 'x-koha-library' => $unprivileged->branchcode } @@ -281,28 +285,32 @@ subtest 'x-koha-override stash tests' => sub { $schema->storage->txn_begin; - my $patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 1 } - }); + my $patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 1 } + } + ); my $password = 'thePassword123'; - $patron->set_password({ password => $password, skip_validation => 1 }); + $patron->set_password( { password => $password, skip_validation => 1 } ); my $userid = $patron->userid; my $item = $builder->build_sample_item(); my $hold_data = { - patron_id => $patron->id, - biblio_id => $item->biblionumber, - item_id => $item->id, + patron_id => $patron->id, + biblio_id => $item->biblionumber, + item_id => $item->id, pickup_library_id => $patron->branchcode, }; my $stash; - $t->app->hook(after_dispatch => sub { - $stash = shift->stash; - }); + $t->app->hook( + after_dispatch => sub { + $stash = shift->stash; + } + ); $t->post_ok( "//$userid:$password@/api/v1/holds" => { 'x-koha-override' => "any" } => json => $hold_data ); @@ -343,9 +351,7 @@ sub create_user_and_session { my $user = $builder->build( { source => 'Borrower', - value => { - flags => $flags - } + value => { flags => $flags } } ); diff --git a/t/db_dependent/api/v1/auth_basic.t b/t/db_dependent/api/v1/auth_basic.t index 808dc31bb9..21e0083aad 100755 --- a/t/db_dependent/api/v1/auth_basic.t +++ b/t/db_dependent/api/v1/auth_basic.t @@ -122,33 +122,28 @@ subtest 'failure tests' => sub { t::lib::Mocks::mock_preference( 'RESTBasicAuth', 1 ); - my $patron = $builder->build_object( - { class => 'Koha::Patrons', value => { userid => 'tomasito', flags => 2**4 } } ); - $patron->set_password({ password => $password }); + my $patron = + $builder->build_object( { class => 'Koha::Patrons', value => { userid => 'tomasito', flags => 2**4 } } ); + $patron->set_password( { password => $password } ); my $userid = $patron->userid; - $t->get_ok("//$userid:$password@/api/v1/patrons") - ->status_is( 200, 'All good' ); + $t->get_ok("//$userid:$password@/api/v1/patrons")->status_is( 200, 'All good' ); # expire patron's password $patron->password_expiration_date( dt_from_string->subtract( days => 1 ) )->store; - $t->get_ok("//$userid:$password@/api/v1/patrons") - ->status_is( 403 ) - ->json_is( '/error' => 'Password has expired', 'Password expired' ); + $t->get_ok("//$userid:$password@/api/v1/patrons")->status_is(403) + ->json_is( '/error' => 'Password has expired', 'Password expired' ); - $t->get_ok("//@/api/v1/patrons") - ->status_is( 401, 'No credentials passed' ); + $t->get_ok("//@/api/v1/patrons")->status_is( 401, 'No credentials passed' ); - $t->get_ok("//$userid:$bad_password@/api/v1/patrons") - ->status_is( 403, 'Failed authentication, invalid password' ) - ->json_is( '/error' => 'Invalid password', 'Error message returned' ); + $t->get_ok("//$userid:$bad_password@/api/v1/patrons")->status_is( 403, 'Failed authentication, invalid password' ) + ->json_is( '/error' => 'Invalid password', 'Error message returned' ); t::lib::Mocks::mock_preference( 'RESTBasicAuth', 0 ); - $t->get_ok("//$userid:$password@/api/v1/patrons") - ->status_is( 401, 'Basic authentication is disabled' ) - ->json_is( '/error' => 'Basic authentication disabled', 'Expected error message rendered' ); + $t->get_ok("//$userid:$password@/api/v1/patrons")->status_is( 401, 'Basic authentication is disabled' ) + ->json_is( '/error' => 'Basic authentication disabled', 'Expected error message rendered' ); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/api/v1/authorised_values.t b/t/db_dependent/api/v1/authorised_values.t index 1a322112f4..f3d66e678a 100755 --- a/t/db_dependent/api/v1/authorised_values.t +++ b/t/db_dependent/api/v1/authorised_values.t @@ -43,7 +43,7 @@ subtest 'list_av_from_category() tests' => sub { my $librarian = $builder->build_object( { class => 'Koha::Patrons', - value => { flags => 2 ** 2 } # catalogue flag = 2 + value => { flags => 2**2 } # catalogue flag = 2 } ); my $password = 'thePassword123'; @@ -62,28 +62,24 @@ subtest 'list_av_from_category() tests' => sub { ## Authorized user tests # No category, 404 expected - $t->get_ok("//$userid:$password@/api/v1/authorised_value_categories/NON_EXISTS/authorised_values") - ->status_is(404) - ->json_is( '/error' => 'Category not found' ); + $t->get_ok("//$userid:$password@/api/v1/authorised_value_categories/NON_EXISTS/authorised_values")->status_is(404) + ->json_is( '/error' => 'Category not found' ); - my $av_cat = $builder->build_object({ class => 'Koha::AuthorisedValueCategories' })->category_name; + my $av_cat = $builder->build_object( { class => 'Koha::AuthorisedValueCategories' } )->category_name; # No AVs, so empty array should be returned - $t->get_ok("//$userid:$password@/api/v1/authorised_value_categories/$av_cat/authorised_values") - ->status_is(200) - ->json_is( [] ); + $t->get_ok("//$userid:$password@/api/v1/authorised_value_categories/$av_cat/authorised_values")->status_is(200) + ->json_is( [] ); - my $av = $builder->build_object( - { class => 'Koha::AuthorisedValues', value => { category => $av_cat } } ); + my $av = $builder->build_object( { class => 'Koha::AuthorisedValues', value => { category => $av_cat } } ); # One av created, should get returned - $t->get_ok("//$userid:$password@/api/v1/authorised_value_categories/$av_cat/authorised_values") - ->status_is(200) - ->json_is( [$av->to_api] ); + $t->get_ok("//$userid:$password@/api/v1/authorised_value_categories/$av_cat/authorised_values")->status_is(200) + ->json_is( [ $av->to_api ] ); # Unauthorized access $t->get_ok("//$unauth_userid:$password@/api/v1/authorised_value_categories/$av_cat/authorised_values") - ->status_is(403); + ->status_is(403); # Test the query webservice endpoint for multiple av_cats my $av_cat_2 = @@ -120,7 +116,7 @@ subtest 'list_av_from_category() tests' => sub { category => $av_cat_2->category_name, authorised_value => 'c', lib => 'description_value' - } + } } ); my $av_4 = $builder->build_object( @@ -135,17 +131,16 @@ subtest 'list_av_from_category() tests' => sub { ); my $embedded_av_query = { "me.category_name" => [ $av_cat_2->category_name ] }; - $t->get_ok( "//$userid:$password@/api/v1/authorised_value_categories?_order_by=authorised_values.authorised_value&q=" - . encode_json($embedded_av_query) => { 'x-koha-embed' => 'authorised_values' } )->status_is(200) - ->json_is( - [ - { - %{ $av_cat_2->to_api }, - authorised_values => - [ $av_2->to_api, $av_4->to_api, $av_3->to_api ] - } - ] - ); + $t->get_ok( + "//$userid:$password@/api/v1/authorised_value_categories?_order_by=authorised_values.authorised_value&q=" + . encode_json($embedded_av_query) => { 'x-koha-embed' => 'authorised_values' } )->status_is(200)->json_is( + [ + { + %{ $av_cat_2->to_api }, + authorised_values => [ $av_2->to_api, $av_4->to_api, $av_3->to_api ] + } + ] + ); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/api/v1/authorities.t b/t/db_dependent/api/v1/authorities.t index aa548fc460..a7200fb020 100755 --- a/t/db_dependent/api/v1/authorities.t +++ b/t/db_dependent/api/v1/authorities.t @@ -58,8 +58,11 @@ subtest 'get() tests' => sub { $patron->discard_changes; my $userid = $patron->userid; - my $authority = $builder->build_object({ 'class' => 'Koha::Authorities', value => { - marcxml => q|<?xml version="1.0" encoding="UTF-8"?> + my $authority = $builder->build_object( + { + 'class' => 'Koha::Authorities', + value => { + marcxml => q|<?xml version="1.0" encoding="UTF-8"?> <record xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.loc.gov/MARC21/slim" xsi:schemaLocation="http://www.loc.gov/MARC21/slim http://www.loc.gov/standards/marcxml/schema/MARC21slim.xsd"> <controlfield tag="001">1001</controlfield> <datafield tag="110" ind1=" " ind2=" "> @@ -67,48 +70,43 @@ subtest 'get() tests' => sub { <subfield code="a">My Corporation</subfield> </datafield> </record>| - } }); + } + } + ); - $t->get_ok("//$userid:$password@/api/v1/authorities/" . $authority->id) - ->status_is(403); + $t->get_ok( "//$userid:$password@/api/v1/authorities/" . $authority->id )->status_is(403); $patron->flags(4)->store; - $t->get_ok( "//$userid:$password@/api/v1/authorities/" . $authority->id - => { Accept => 'application/weird+format' } ) - ->status_is(400); + $t->get_ok( + "//$userid:$password@/api/v1/authorities/" . $authority->id => { Accept => 'application/weird+format' } ) + ->status_is(400); - $t->get_ok( "//$userid:$password@/api/v1/authorities/" . $authority->id - => { Accept => 'application/json' } ) - ->status_is(200) - ->json_is( '/authority_id', $authority->id ) - ->json_is( '/framework_id', $authority->authtypecode ); + $t->get_ok( "//$userid:$password@/api/v1/authorities/" . $authority->id => { Accept => 'application/json' } ) + ->status_is(200)->json_is( '/authority_id', $authority->id ) + ->json_is( '/framework_id', $authority->authtypecode ); - $t->get_ok( "//$userid:$password@/api/v1/authorities/" . $authority->id - => { Accept => 'application/marcxml+xml' } ) - ->status_is(200); + $t->get_ok( "//$userid:$password@/api/v1/authorities/" . $authority->id => { Accept => 'application/marcxml+xml' } ) + ->status_is(200); - $t->get_ok( "//$userid:$password@/api/v1/authorities/" . $authority->id - => { Accept => 'application/marc-in-json' } ) - ->status_is(200); + $t->get_ok( + "//$userid:$password@/api/v1/authorities/" . $authority->id => { Accept => 'application/marc-in-json' } ) + ->status_is(200); - $t->get_ok( "//$userid:$password@/api/v1/authorities/" . $authority->id - => { Accept => 'application/marc' } ) - ->status_is(200); + $t->get_ok( "//$userid:$password@/api/v1/authorities/" . $authority->id => { Accept => 'application/marc' } ) + ->status_is(200); - $t->get_ok( "//$userid:$password@/api/v1/authorities/" . $authority->id - => { Accept => 'text/plain' } ) - ->status_is(200) - ->content_is(q|LDR 00079 2200049 4500 + $t->get_ok( "//$userid:$password@/api/v1/authorities/" . $authority->id => { Accept => 'text/plain' } ) + ->status_is(200)->content_is( + q|LDR 00079 2200049 4500 001 1001 110 _9102 - _aMy Corporation|); + _aMy Corporation| + ); $authority->delete; - $t->get_ok( "//$userid:$password@/api/v1/authorities/" . $authority->id - => { Accept => 'application/marc' } ) - ->status_is(404) - ->json_is( '/error', 'Authority record not found' ); + $t->get_ok( "//$userid:$password@/api/v1/authorities/" . $authority->id => { Accept => 'application/marc' } ) + ->status_is(404)->json_is( '/error', 'Authority record not found' ); $schema->storage->txn_rollback; }; @@ -122,15 +120,18 @@ subtest 'delete() tests' => sub { my $patron = $builder->build_object( { class => 'Koha::Patrons', - value => { flags => 0 } # no permissions + value => { flags => 0 } # no permissions } ); my $password = 'thePassword123'; $patron->set_password( { password => $password, skip_validation => 1 } ); my $userid = $patron->userid; - my $authority = $builder->build_object({ 'class' => 'Koha::Authorities', value => { - marcxml => q|<?xml version="1.0" encoding="UTF-8"?> + my $authority = $builder->build_object( + { + 'class' => 'Koha::Authorities', + value => { + marcxml => q|<?xml version="1.0" encoding="UTF-8"?> <record xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.loc.gov/MARC21/slim" xsi:schemaLocation="http://www.loc.gov/MARC21/slim http://www.loc.gov/standards/marcxml/schema/MARC21slim.xsd"> <controlfield tag="001">1001</controlfield> <datafield tag="110" ind1=" " ind2=" "> @@ -138,19 +139,19 @@ subtest 'delete() tests' => sub { <subfield code="a">My Corporation</subfield> </datafield> </record>| - } }); + } + } + ); - $t->delete_ok("//$userid:$password@/api/v1/authorities/".$authority->id) - ->status_is(403, 'Not enough permissions makes it return the right code'); + $t->delete_ok( "//$userid:$password@/api/v1/authorities/" . $authority->id ) + ->status_is( 403, 'Not enough permissions makes it return the right code' ); - $patron->flags( 2 ** 14 )->store; # 14 => editauthorities userflag + $patron->flags( 2**14 )->store; # 14 => editauthorities userflag - $t->delete_ok("//$userid:$password@/api/v1/authorities/".$authority->id) - ->status_is(204, 'REST3.2.4') - ->content_is('', 'REST3.3.4'); + $t->delete_ok( "//$userid:$password@/api/v1/authorities/" . $authority->id )->status_is( 204, 'REST3.2.4' ) + ->content_is( '', 'REST3.3.4' ); - $t->delete_ok("//$userid:$password@/api/v1/authorities/".$authority->id) - ->status_is(404); + $t->delete_ok( "//$userid:$password@/api/v1/authorities/" . $authority->id )->status_is(404); $schema->storage->txn_rollback; }; @@ -167,7 +168,7 @@ subtest 'post() tests' => sub { my $patron = $builder->build_object( { class => 'Koha::Patrons', - value => { flags => 0 } # no permissions + value => { flags => 0 } # no permissions } ); my $password = 'thePassword123'; @@ -183,50 +184,55 @@ subtest 'post() tests' => sub { </datafield> </record>|; - my $mij = '{"fields":[{"001":"1001"},{"110":{"subfields":[{"9":"102"},{"a":"My Corporation"}],"ind1":" ","ind2":" "}}],"leader":" "}'; + my $mij = + '{"fields":[{"001":"1001"},{"110":{"subfields":[{"9":"102"},{"a":"My Corporation"}],"ind1":" ","ind2":" "}}],"leader":" "}'; my $marc = '00079 2200049 45000010005000001100024000051001 9102aMy Corporation'; my $json = { - authtypecode => "CORPO_NAME", - marcxml => $marcxml + authtypecode => "CORPO_NAME", + marcxml => $marcxml }; $t->post_ok("//$userid:$password@/api/v1/authorities") - ->status_is(403, 'Not enough permissions makes it return the right code'); + ->status_is( 403, 'Not enough permissions makes it return the right code' ); # Add permissions - $patron->flags( 2 ** 14 )->store; # 14 => editauthorities userflag + $patron->flags( 2**14 )->store; # 14 => editauthorities userflag # x-koha-override passed to make sure it goes through - $t->post_ok("//$userid:$password@/api/v1/authorities" => {'Content-Type' => 'application/marcxml+xml', 'x-authority-type' => 'CORPO_NAME', 'x-koha-override' => 'any' } => $marcxml) - ->status_is(201) - ->json_is(q{}) - ->header_like( - Location => qr|^\/api\/v1\/authorities/\d*|, - 'REST3.4.1' - ); + $t->post_ok( + "//$userid:$password@/api/v1/authorities" => { + 'Content-Type' => 'application/marcxml+xml', 'x-authority-type' => 'CORPO_NAME', 'x-koha-override' => 'any' + } => $marcxml + )->status_is(201)->json_is(q{})->header_like( + Location => qr|^\/api\/v1\/authorities/\d*|, + 'REST3.4.1' + ); # x-koha-override not passed to force block because duplicate - $t->post_ok("//$userid:$password@/api/v1/authorities" => {'Content-Type' => 'application/marc-in-json', 'x-authority-type' => 'CORPO_NAME' } => $mij) - ->status_is(409) - ->header_exists_not( 'Location', 'Location header is only set when the new resource is created' ) - ->json_like( '/error' => qr/Duplicate record (\d*)/ ) - ->json_is( '/error_code' => q{duplicate} ); + $t->post_ok( "//$userid:$password@/api/v1/authorities" => + { 'Content-Type' => 'application/marc-in-json', 'x-authority-type' => 'CORPO_NAME' } => $mij ) + ->status_is(409) + ->header_exists_not( 'Location', 'Location header is only set when the new resource is created' ) + ->json_like( '/error' => qr/Duplicate record (\d*)/ )->json_is( '/error_code' => q{duplicate} ); - $t->post_ok("//$userid:$password@/api/v1/authorities" => {'Content-Type' => 'application/marc-in-json', 'x-authority-type' => 'CORPO_NAME', 'x-koha-override' => 'duplicate' } => $mij) - ->status_is(201) - ->json_is(q{}) - ->header_like( - Location => qr|^\/api\/v1\/authorities/\d*|, - 'REST3.4.1' - ); + $t->post_ok( + "//$userid:$password@/api/v1/authorities" => { + 'Content-Type' => 'application/marc-in-json', 'x-authority-type' => 'CORPO_NAME', + 'x-koha-override' => 'duplicate' + } => $mij + )->status_is(201)->json_is(q{})->header_like( + Location => qr|^\/api\/v1\/authorities/\d*|, + 'REST3.4.1' + ); - $t->post_ok("//$userid:$password@/api/v1/authorities" => {'Content-Type' => 'application/marc', 'x-authority-type' => 'CORPO_NAME', 'x-koha-override' => 'duplicate' } => $marc) - ->status_is(201) - ->json_is(q{}) - ->header_like( - Location => qr|^\/api\/v1\/authorities/\d*|, - 'REST3.4.1' - ); + $t->post_ok( + "//$userid:$password@/api/v1/authorities" => { + 'Content-Type' => 'application/marc', 'x-authority-type' => 'CORPO_NAME', 'x-koha-override' => 'duplicate' + } => $marc + )->status_is(201)->json_is(q{})->header_like( + Location => qr|^\/api\/v1\/authorities/\d*|, + 'REST3.4.1' + ); $schema->storage->txn_rollback; }; @@ -245,7 +251,7 @@ subtest 'put() tests' => sub { my $patron = $builder->build_object( { class => 'Koha::Patrons', - value => { flags => 0 } # no permissions + value => { flags => 0 } # no permissions } ); my $password = 'thePassword123'; @@ -289,50 +295,49 @@ subtest 'put() tests' => sub { </datafield> </record>|; - my $mij = '{"fields":[{"001":"1001"},{"110":{"subfields":[{"9":"102"},{"a":"MIJ"}],"ind1":" ","ind2":" "}}],"leader":" "}'; + my $mij = + '{"fields":[{"001":"1001"},{"110":{"subfields":[{"9":"102"},{"a":"MIJ"}],"ind1":" ","ind2":" "}}],"leader":" "}'; my $marc = '00079 2200049 45000010005000001100024000051001 9102aUSMARCFormated'; $t->put_ok("//$userid:$password@/api/v1/authorities/$authid") - ->status_is(403, 'Not enough permissions makes it return the right code'); + ->status_is( 403, 'Not enough permissions makes it return the right code' ); # Add permissions - $patron->flags( 2 ** 14 )->store; # 14 => editauthorities userflag + $patron->flags( 2**14 )->store; # 14 => editauthorities userflag - $t->put_ok("//$userid:$password@/api/v1/authorities/$authid" => {'Content-Type' => 'application/marcxml+xml', 'x-authority-type' => $authtypecode} => $marcxml) - ->status_is(200) - ->json_has('/id'); + $t->put_ok( "//$userid:$password@/api/v1/authorities/$authid" => + { 'Content-Type' => 'application/marcxml+xml', 'x-authority-type' => $authtypecode } => $marcxml ) + ->status_is(200)->json_has('/id'); - $authority = Koha::Authorities->find($authid); - $record = $authority->record; - $subfield_a = $record->subfield('110', 'a'); + $authority = Koha::Authorities->find($authid); + $record = $authority->record; + $subfield_a = $record->subfield( '110', 'a' ); - is($subfield_a, 'MARCXML'); + is( $subfield_a, 'MARCXML' ); - $t->put_ok("//$userid:$password@/api/v1/authorities/$authid" => {'Content-Type' => 'application/marc-in-json', 'x-authority-type' => $authtypecode} => $mij) - ->status_is(200) - ->json_has('/id'); + $t->put_ok( "//$userid:$password@/api/v1/authorities/$authid" => + { 'Content-Type' => 'application/marc-in-json', 'x-authority-type' => $authtypecode } => $mij ) + ->status_is(200)->json_has('/id'); - $authority = Koha::Authorities->find($authid); - $record = $authority->record; - $subfield_a = $record->subfield('110', 'a'); + $authority = Koha::Authorities->find($authid); + $record = $authority->record; + $subfield_a = $record->subfield( '110', 'a' ); - is($subfield_a, 'MIJ'); + is( $subfield_a, 'MIJ' ); - $t->put_ok("//$userid:$password@/api/v1/authorities/$authid" => {'Content-Type' => 'application/marc', 'x-authority-type' => $authtypecode} => $marc) - ->status_is(200) - ->json_has('/id'); + $t->put_ok( "//$userid:$password@/api/v1/authorities/$authid" => + { 'Content-Type' => 'application/marc', 'x-authority-type' => $authtypecode } => $marc )->status_is(200) + ->json_has('/id'); - $authority = Koha::Authorities->find($authid); - $record = $authority->record; - $subfield_a = $record->subfield('110', 'a'); + $authority = Koha::Authorities->find($authid); + $record = $authority->record; + $subfield_a = $record->subfield( '110', 'a' ); - is($subfield_a, 'USMARCFormated'); + is( $subfield_a, 'USMARCFormated' ); $schema->storage->txn_rollback; }; - - subtest 'list() tests' => sub { plan tests => 14; @@ -349,8 +354,11 @@ subtest 'list() tests' => sub { $patron->discard_changes; my $userid = $patron->userid; - my $auth_id_1 = $builder->build_object({ 'class' => 'Koha::Authorities', value => { - marcxml => q|<?xml version="1.0" encoding="UTF-8"?> + my $auth_id_1 = $builder->build_object( + { + 'class' => 'Koha::Authorities', + value => { + marcxml => q|<?xml version="1.0" encoding="UTF-8"?> <record xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.loc.gov/MARC21/slim" xsi:schemaLocation="http://www.loc.gov/MARC21/slim http://www.loc.gov/standards/marcxml/schema/MARC21slim.xsd"> <controlfield tag="001">1001</controlfield> <datafield tag="110" ind1=" " ind2=" "> @@ -358,10 +366,15 @@ subtest 'list() tests' => sub { <subfield code="a">My Corporation</subfield> </datafield> </record>| - } })->authid; + } + } + )->authid; - my $auth_id_2 = $builder->build_object({ 'class' => 'Koha::Authorities', value => { - marcxml => q|<?xml version="1.0" encoding="UTF-8"?> + my $auth_id_2 = $builder->build_object( + { + 'class' => 'Koha::Authorities', + value => { + marcxml => q|<?xml version="1.0" encoding="UTF-8"?> <record xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.loc.gov/MARC21/slim" xsi:schemaLocation="http://www.loc.gov/MARC21/slim http://www.loc.gov/standards/marcxml/schema/MARC21slim.xsd"> <controlfield tag="001">1001</controlfield> <datafield tag="110" ind1=" " ind2=" "> @@ -369,7 +382,9 @@ subtest 'list() tests' => sub { <subfield code="a">My Corporation</subfield> </datafield> </record>| - } })->authid; + } + } + )->authid; my $query = encode_json( [ { authority_id => $auth_id_1 }, { authority_id => $auth_id_2 } ] ); diff --git a/t/db_dependent/api/v1/biblios.t b/t/db_dependent/api/v1/biblios.t index 9adfb1194e..f47c5f8bd2 100755 --- a/t/db_dependent/api/v1/biblios.t +++ b/t/db_dependent/api/v1/biblios.t @@ -65,47 +65,41 @@ subtest 'get() tests' => sub { $patron->discard_changes; my $userid = $patron->userid; - my $biblio = $builder->build_sample_biblio({ - title => 'The unbearable lightness of being', - author => 'Milan Kundera' - }); - $t->get_ok("//$userid:$password@/api/v1/biblios/" . $biblio->biblionumber) - ->status_is(403); + my $biblio = $builder->build_sample_biblio( + { + title => 'The unbearable lightness of being', + author => 'Milan Kundera' + } + ); + $t->get_ok( "//$userid:$password@/api/v1/biblios/" . $biblio->biblionumber )->status_is(403); $patron->flags(4)->store; - $t->get_ok( "//$userid:$password@/api/v1/biblios/" . $biblio->biblionumber - => { Accept => 'application/weird+format' } ) - ->status_is(400); + $t->get_ok( + "//$userid:$password@/api/v1/biblios/" . $biblio->biblionumber => { Accept => 'application/weird+format' } ) + ->status_is(400); - $t->get_ok( "//$userid:$password@/api/v1/biblios/" . $biblio->biblionumber - => { Accept => 'application/json' } ) - ->status_is(200) - ->json_is( '/title', 'The unbearable lightness of being' ) - ->json_is( '/author', 'Milan Kundera' ); + $t->get_ok( "//$userid:$password@/api/v1/biblios/" . $biblio->biblionumber => { Accept => 'application/json' } ) + ->status_is(200)->json_is( '/title', 'The unbearable lightness of being' ) + ->json_is( '/author', 'Milan Kundera' ); - $t->get_ok( "//$userid:$password@/api/v1/biblios/" . $biblio->biblionumber - => { Accept => 'application/marcxml+xml' } ) - ->status_is(200); + $t->get_ok( + "//$userid:$password@/api/v1/biblios/" . $biblio->biblionumber => { Accept => 'application/marcxml+xml' } ) + ->status_is(200); - $t->get_ok( "//$userid:$password@/api/v1/biblios/" . $biblio->biblionumber - => { Accept => 'application/marc-in-json' } ) - ->status_is(200); + $t->get_ok( + "//$userid:$password@/api/v1/biblios/" . $biblio->biblionumber => { Accept => 'application/marc-in-json' } ) + ->status_is(200); - $t->get_ok( "//$userid:$password@/api/v1/biblios/" . $biblio->biblionumber - => { Accept => 'application/marc' } ) - ->status_is(200); + $t->get_ok( "//$userid:$password@/api/v1/biblios/" . $biblio->biblionumber => { Accept => 'application/marc' } ) + ->status_is(200); - $t->get_ok( "//$userid:$password@/api/v1/biblios/" . $biblio->biblionumber - => { Accept => 'text/plain' } ) - ->status_is(200) - ->content_is($biblio->metadata->record->as_formatted); + $t->get_ok( "//$userid:$password@/api/v1/biblios/" . $biblio->biblionumber => { Accept => 'text/plain' } ) + ->status_is(200)->content_is( $biblio->metadata->record->as_formatted ); $biblio->delete; - $t->get_ok( "//$userid:$password@/api/v1/biblios/" . $biblio->biblionumber - => { Accept => 'application/marc' } ) - ->status_is(404) - ->json_is( '/error', 'Bibliographic record not found' ); + $t->get_ok( "//$userid:$password@/api/v1/biblios/" . $biblio->biblionumber => { Accept => 'application/marc' } ) + ->status_is(404)->json_is( '/error', 'Bibliographic record not found' ); subtest 'marc-in-json encoding tests' => sub { @@ -120,11 +114,11 @@ subtest 'get() tests' => sub { } ); - my $result = $t->get_ok( "//$userid:$password@/api/v1/biblios/" . $biblio->biblionumber - => { Accept => 'application/marc-in-json' } ) - ->status_is(200)->tx->res->body; + my $result = $t->get_ok( + "//$userid:$password@/api/v1/biblios/" . $biblio->biblionumber => { Accept => 'application/marc-in-json' } ) + ->status_is(200)->tx->res->body; - my $encoded_title = Encode::encode( "UTF-8", $title_with_diacritics ); + my $encoded_title = Encode::encode( "UTF-8", $title_with_diacritics ); like( $result, qr/\Q$encoded_title/, "The title is not double encoded" ); }; @@ -133,8 +127,7 @@ subtest 'get() tests' => sub { plan tests => 3; my $marcflavour = C4::Context->preference('marcflavour'); - t::lib::Mocks::mock_preference('marcflavour', 'UNIMARC'); - + t::lib::Mocks::mock_preference( 'marcflavour', 'UNIMARC' ); my $title_with_diacritics = "L'insoutenable légèreté de l'être"; @@ -147,17 +140,17 @@ subtest 'get() tests' => sub { my $record = $biblio->metadata->record; $record->leader(' nam 3 4500'); - $biblio->metadata->metadata($record->as_xml_record('UNIMARC')); + $biblio->metadata->metadata( $record->as_xml_record('UNIMARC') ); $biblio->metadata->store; - my $result = $t->get_ok( "//$userid:$password@/api/v1/biblios/" . $biblio->biblionumber - => { Accept => 'application/marcxml+xml' } ) - ->status_is(200)->tx->res->body; + my $result = $t->get_ok( + "//$userid:$password@/api/v1/biblios/" . $biblio->biblionumber => { Accept => 'application/marcxml+xml' } ) + ->status_is(200)->tx->res->body; - my $encoded_title = Encode::encode( "UTF-8", $title_with_diacritics ); + my $encoded_title = Encode::encode( "UTF-8", $title_with_diacritics ); like( $result, qr/\Q$encoded_title/, "The title is not double encoded" ); - t::lib::Mocks::mock_preference('marcflavour', $marcflavour); + t::lib::Mocks::mock_preference( 'marcflavour', $marcflavour ); }; $schema->storage->txn_rollback; @@ -181,21 +174,18 @@ subtest 'get_items() tests' => sub { my $userid = $patron->userid; my $biblio = $builder->build_sample_biblio(); - $t->get_ok("//$userid:$password@/api/v1/biblios/" . $biblio->biblionumber . "/items") - ->status_is(403); + $t->get_ok( "//$userid:$password@/api/v1/biblios/" . $biblio->biblionumber . "/items" )->status_is(403); $patron->flags(4)->store; - $t->get_ok( "//$userid:$password@/api/v1/biblios/" . $biblio->biblionumber . "/items") - ->status_is(200) - ->json_is( '' => [], 'No items on the biblio' ); + $t->get_ok( "//$userid:$password@/api/v1/biblios/" . $biblio->biblionumber . "/items" )->status_is(200) + ->json_is( '' => [], 'No items on the biblio' ); - my $item_1 = $builder->build_sample_item({ biblionumber => $biblio->biblionumber }); - my $item_2 = $builder->build_sample_item({ biblionumber => $biblio->biblionumber }); + my $item_1 = $builder->build_sample_item( { biblionumber => $biblio->biblionumber } ); + my $item_2 = $builder->build_sample_item( { biblionumber => $biblio->biblionumber } ); $t->get_ok( "//$userid:$password@/api/v1/biblios/" . $biblio->biblionumber . "/items?_order_by=item_id" ) - ->status_is(200) - ->json_is( '' => [ $item_1->to_api, $item_2->to_api ], 'The items are returned' ); + ->status_is(200)->json_is( '' => [ $item_1->to_api, $item_2->to_api ], 'The items are returned' ); $t->get_ok( "//$userid:$password@/api/v1/biblios/" . $biblio->biblionumber . "/items" => { "x-koha-embed" => "+strings" } ) @@ -253,7 +243,7 @@ subtest 'delete() tests' => sub { my $patron = $builder->build_object( { class => 'Koha::Patrons', - value => { flags => 0 } # no permissions + value => { flags => 0 } # no permissions } ); my $password = 'thePassword123'; @@ -264,7 +254,7 @@ subtest 'delete() tests' => sub { my $biblio_id = $item->biblionumber; $t->delete_ok("//$userid:$password@/api/v1/biblios/$biblio_id") - ->status_is(403, 'Not enough permissions makes it return the right code'); + ->status_is( 403, 'Not enough permissions makes it return the right code' ); # Add permissions $builder->build( @@ -278,20 +268,16 @@ subtest 'delete() tests' => sub { } ); - # Bibs with items cannot be deleted - $t->delete_ok("//$userid:$password@/api/v1/biblios/$biblio_id") - ->status_is(409); + $t->delete_ok("//$userid:$password@/api/v1/biblios/$biblio_id")->status_is(409); $item->delete(); # Bibs with no items can be deleted - $t->delete_ok("//$userid:$password@/api/v1/biblios/$biblio_id") - ->status_is(204, 'REST3.2.4') - ->content_is('', 'REST3.3.4'); + $t->delete_ok("//$userid:$password@/api/v1/biblios/$biblio_id")->status_is( 204, 'REST3.2.4' ) + ->content_is( '', 'REST3.3.4' ); - $t->delete_ok("//$userid:$password@/api/v1/biblios/$biblio_id") - ->status_is(404); + $t->delete_ok("//$userid:$password@/api/v1/biblios/$biblio_id")->status_is(404); $schema->storage->txn_rollback; }; @@ -302,12 +288,12 @@ subtest 'get_public() tests' => sub { $schema->storage->txn_begin; - my $category = $builder->build_object({ class => 'Koha::Patron::Categories' }); - my $patron = $builder->build_object( + my $category = $builder->build_object( { class => 'Koha::Patron::Categories' } ); + my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { - flags => undef, # opac user + flags => undef, # opac user categorycode => $category->categorycode } } @@ -317,64 +303,54 @@ subtest 'get_public() tests' => sub { $patron->discard_changes; my $userid = $patron->userid; - my $biblio = $builder->build_sample_biblio({ - title => 'The unbearable lightness of being', - author => 'Milan Kundera' - }); + my $biblio = $builder->build_sample_biblio( + { + title => 'The unbearable lightness of being', + author => 'Milan Kundera' + } + ); # Make sure author in shown in the OPAC - my $subfields = Koha::MarcSubfieldStructures->search({ tagfield => '100' }); + my $subfields = Koha::MarcSubfieldStructures->search( { tagfield => '100' } ); while ( my $subfield = $subfields->next ) { - $subfield->set({ hidden => -1 })->store; + $subfield->set( { hidden => -1 } )->store; } Koha::Caches->get_instance()->flush_all; - $t->get_ok( "//$userid:$password@/api/v1/public/biblios/" . $biblio->biblionumber - => { Accept => 'application/weird+format' } ) - ->status_is(400); + $t->get_ok( "//$userid:$password@/api/v1/public/biblios/" + . $biblio->biblionumber => { Accept => 'application/weird+format' } )->status_is(400); - $t->get_ok( "//$userid:$password@/api/v1/public/biblios/" . $biblio->biblionumber - => { Accept => 'text/plain' } ) - ->status_is(200) - ->content_like( qr{100\s+_aMilan Kundera} ) - ->content_like( qr{245\s+_aThe unbearable lightness of being} ); + $t->get_ok( "//$userid:$password@/api/v1/public/biblios/" . $biblio->biblionumber => { Accept => 'text/plain' } ) + ->status_is(200)->content_like(qr{100\s+_aMilan Kundera}) + ->content_like(qr{245\s+_aThe unbearable lightness of being}); - $t->get_ok( "//$userid:$password@/api/v1/public/biblios/" . $biblio->biblionumber - => { Accept => 'application/marcxml+xml' } ) - ->status_is(200); + $t->get_ok( "//$userid:$password@/api/v1/public/biblios/" + . $biblio->biblionumber => { Accept => 'application/marcxml+xml' } )->status_is(200); - $t->get_ok( "//$userid:$password@/api/v1/public/biblios/" . $biblio->biblionumber - => { Accept => 'application/marc-in-json' } ) - ->status_is(200); + $t->get_ok( "//$userid:$password@/api/v1/public/biblios/" + . $biblio->biblionumber => { Accept => 'application/marc-in-json' } )->status_is(200); - $t->get_ok( "//$userid:$password@/api/v1/public/biblios/" . $biblio->biblionumber - => { Accept => 'application/marc' } ) - ->status_is(200); + $t->get_ok( + "//$userid:$password@/api/v1/public/biblios/" . $biblio->biblionumber => { Accept => 'application/marc' } ) + ->status_is(200); - $t->get_ok( "//$userid:$password@/api/v1/public/biblios/" . $biblio->biblionumber - => { Accept => 'text/plain' } ) - ->status_is(200) - ->content_is($biblio->metadata->record->as_formatted); + $t->get_ok( "//$userid:$password@/api/v1/public/biblios/" . $biblio->biblionumber => { Accept => 'text/plain' } ) + ->status_is(200)->content_is( $biblio->metadata->record->as_formatted ); subtest 'anonymous access' => sub { plan tests => 9; - $t->get_ok( "/api/v1/public/biblios/" . $biblio->biblionumber - => { Accept => 'application/marcxml+xml' } ) - ->status_is(200); + $t->get_ok( "/api/v1/public/biblios/" . $biblio->biblionumber => { Accept => 'application/marcxml+xml' } ) + ->status_is(200); - $t->get_ok( "/api/v1/public/biblios/" . $biblio->biblionumber - => { Accept => 'application/marc-in-json' } ) - ->status_is(200); + $t->get_ok( "/api/v1/public/biblios/" . $biblio->biblionumber => { Accept => 'application/marc-in-json' } ) + ->status_is(200); - $t->get_ok( "/api/v1/public/biblios/" . $biblio->biblionumber - => { Accept => 'application/marc' } ) - ->status_is(200); + $t->get_ok( "/api/v1/public/biblios/" . $biblio->biblionumber => { Accept => 'application/marc' } ) + ->status_is(200); - $t->get_ok( "/api/v1/public/biblios/" . $biblio->biblionumber - => { Accept => 'text/plain' } ) - ->status_is(200) - ->content_is($biblio->metadata->record->as_formatted); + $t->get_ok( "/api/v1/public/biblios/" . $biblio->biblionumber => { Accept => 'text/plain' } )->status_is(200) + ->content_is( $biblio->metadata->record->as_formatted ); }; subtest 'marc-in-json encoding tests' => sub { @@ -390,28 +366,26 @@ subtest 'get_public() tests' => sub { } ); - my $result = $t->get_ok( "/api/v1/public/biblios/" . $biblio->biblionumber - => { Accept => 'application/marc-in-json' } ) - ->status_is(200)->tx->res->body; + my $result = + $t->get_ok( "/api/v1/public/biblios/" . $biblio->biblionumber => { Accept => 'application/marc-in-json' } ) + ->status_is(200)->tx->res->body; - my $encoded_title = Encode::encode( "UTF-8", $title_with_diacritics ); + my $encoded_title = Encode::encode( "UTF-8", $title_with_diacritics ); like( $result, qr/\Q$encoded_title/, "The title is not double encoded" ); }; # Hide author in OPAC - $subfields = Koha::MarcSubfieldStructures->search({ tagfield => '100' }); + $subfields = Koha::MarcSubfieldStructures->search( { tagfield => '100' } ); while ( my $subfield = $subfields->next ) { - $subfield->set({ hidden => 1 })->store; + $subfield->set( { hidden => 1 } )->store; } Koha::Caches->get_instance()->flush_all; - $t->get_ok( "//$userid:$password@/api/v1/public/biblios/" . $biblio->biblionumber - => { Accept => 'text/plain' } ) - ->status_is(200) - ->content_unlike( qr{100\s+_aMilan Kundera} ) - ->content_like( qr{245\s+_aThe unbearable lightness of being} ); + $t->get_ok( "//$userid:$password@/api/v1/public/biblios/" . $biblio->biblionumber => { Accept => 'text/plain' } ) + ->status_is(200)->content_unlike(qr{100\s+_aMilan Kundera}) + ->content_like(qr{245\s+_aThe unbearable lightness of being}); subtest 'hidden_in_opac tests' => sub { @@ -420,34 +394,33 @@ subtest 'get_public() tests' => sub { my $biblio_hidden_in_opac = 1; my $biblio_class = Test::MockModule->new('Koha::Biblio'); + # force biblio hidden in OPAC $biblio_class->mock( 'hidden_in_opac', sub { return $biblio_hidden_in_opac; } ); - $t->get_ok( "/api/v1/public/biblios/" . $biblio->biblionumber - => { Accept => 'text/plain' } ) - ->status_is(404, 'hidden_in_opac + anonymous => hidden'); + $t->get_ok( "/api/v1/public/biblios/" . $biblio->biblionumber => { Accept => 'text/plain' } ) + ->status_is( 404, 'hidden_in_opac + anonymous => hidden' ); my $category_override_hidden_items = 0; - my $category_class = Test::MockModule->new('Koha::Patron::Category'); + my $category_class = Test::MockModule->new('Koha::Patron::Category'); $category_class->mock( 'override_hidden_items', sub { return $category_override_hidden_items; } ); - $t->get_ok( "//$userid:$password@/api/v1/public/biblios/" . $biblio->biblionumber - => { Accept => 'text/plain' } ) - ->status_is(404, "hidden_in_opac + patron whose category doesn't override => hidden"); + $t->get_ok( + "//$userid:$password@/api/v1/public/biblios/" . $biblio->biblionumber => { Accept => 'text/plain' } ) + ->status_is( 404, "hidden_in_opac + patron whose category doesn't override => hidden" ); # Make the category override $category_override_hidden_items = 1; - $t->get_ok( "//$userid:$password@/api/v1/public/biblios/" . $biblio->biblionumber - => { Accept => 'text/plain' } ) - ->status_is(200, "hidden_in_opac + patron whose category that overrides => displayed"); + $t->get_ok( + "//$userid:$password@/api/v1/public/biblios/" . $biblio->biblionumber => { Accept => 'text/plain' } ) + ->status_is( 200, "hidden_in_opac + patron whose category that overrides => displayed" ); t::lib::Mocks::mock_preference('OpacHiddenItems'); }; $biblio->delete; - $t->get_ok( "//$userid:$password@/api/v1/public/biblios/" . $biblio->biblionumber - => { Accept => 'application/marc' } ) - ->status_is(404) - ->json_is( '/error', 'Bibliographic record not found' ); + $t->get_ok( + "//$userid:$password@/api/v1/public/biblios/" . $biblio->biblionumber => { Accept => 'application/marc' } ) + ->status_is(404)->json_is( '/error', 'Bibliographic record not found' ); $schema->storage->txn_rollback; }; @@ -461,11 +434,14 @@ subtest 'pickup_locations() tests' => sub { t::lib::Mocks::mock_preference( 'AllowHoldPolicyOverride', 0 ); # Small trick to ease testing - Koha::Libraries->search->update({ pickup_location => 0 }); + Koha::Libraries->search->update( { pickup_location => 0 } ); - my $library_1 = $builder->build_object({ class => 'Koha::Libraries', value => { marcorgcode => 'A', pickup_location => 1 } }); - my $library_2 = $builder->build_object({ class => 'Koha::Libraries', value => { marcorgcode => 'B', pickup_location => 1 } }); - my $library_3 = $builder->build_object({ class => 'Koha::Libraries', value => { marcorgcode => 'C', pickup_location => 1 } }); + my $library_1 = + $builder->build_object( { class => 'Koha::Libraries', value => { marcorgcode => 'A', pickup_location => 1 } } ); + my $library_2 = + $builder->build_object( { class => 'Koha::Libraries', value => { marcorgcode => 'B', pickup_location => 1 } } ); + my $library_3 = + $builder->build_object( { class => 'Koha::Libraries', value => { marcorgcode => 'C', pickup_location => 1 } } ); my $library_1_api = $library_1->to_api(); my $library_2_api = $library_2->to_api(); @@ -505,8 +481,10 @@ subtest 'pickup_locations() tests' => sub { sub { my ( $self, $params ) = @_; my $mock_patron = $params->{patron}; - is( $mock_patron->borrowernumber, - $patron->borrowernumber, 'Patron passed correctly' ); + is( + $mock_patron->borrowernumber, + $patron->borrowernumber, 'Patron passed correctly' + ); return Koha::Libraries->search( { branchcode => { @@ -516,7 +494,7 @@ subtest 'pickup_locations() tests' => sub { ] } }, - { # we make sure no surprises in the order of the result + { # we make sure no surprises in the order of the result order_by => { '-asc' => 'marcorgcode' } } ); @@ -525,32 +503,35 @@ subtest 'pickup_locations() tests' => sub { my $biblio = $builder->build_sample_biblio; - $t->get_ok( "//$userid:$password@/api/v1/biblios/" - . $biblio->id - . "/pickup_locations?patron_id=" . $patron->id ) - ->json_is( [ $library_1_api, $library_2_api ] ); + $t->get_ok( "//$userid:$password@/api/v1/biblios/" . $biblio->id . "/pickup_locations?patron_id=" . $patron->id ) + ->json_is( [ $library_1_api, $library_2_api ] ); # filtering works! $t->get_ok( "//$userid:$password@/api/v1/biblios/" - . $biblio->id - . '/pickup_locations?' - . 'patron_id=' . $patron->id . '&q={"marc_org_code": { "-like": "A%" }}' ) - ->json_is( [ $library_1_api ] ); + . $biblio->id + . '/pickup_locations?' + . 'patron_id=' + . $patron->id + . '&q={"marc_org_code": { "-like": "A%" }}' )->json_is( [$library_1_api] ); t::lib::Mocks::mock_preference( 'AllowHoldPolicyOverride', 1 ); - my $library_4 = $builder->build_object({ class => 'Koha::Libraries', value => { pickup_location => 0, marcorgcode => 'X' } }); - my $library_5 = $builder->build_object({ class => 'Koha::Libraries', value => { pickup_location => 1, marcorgcode => 'Y' } }); + my $library_4 = + $builder->build_object( { class => 'Koha::Libraries', value => { pickup_location => 0, marcorgcode => 'X' } } ); + my $library_5 = + $builder->build_object( { class => 'Koha::Libraries', value => { pickup_location => 1, marcorgcode => 'Y' } } ); my $library_5_api = $library_5->to_api(); $library_5_api->{needs_override} = Mojo::JSON->true; $library_5_api->{pickup_items} = []; $t->get_ok( "//$userid:$password@/api/v1/biblios/" - . $biblio->id - . "/pickup_locations?" - . "patron_id=" . $patron->id . "&_order_by=marc_org_code" ) - ->json_is( [ $library_1_api, $library_2_api, $library_3_api, $library_5_api ] ); + . $biblio->id + . "/pickup_locations?" + . "patron_id=" + . $patron->id + . "&_order_by=marc_org_code" ) + ->json_is( [ $library_1_api, $library_2_api, $library_3_api, $library_5_api ] ); subtest 'Pagination and AllowHoldPolicyOverride tests' => sub { @@ -558,61 +539,65 @@ subtest 'pickup_locations() tests' => sub { t::lib::Mocks::mock_preference( 'AllowHoldPolicyOverride', 1 ); - $t->get_ok( "//$userid:$password@/api/v1/biblios/" . $biblio->id . "/pickup_locations?" . "patron_id=" . $patron->id . "&_order_by=marc_org_code" . "&_per_page=1" ) - ->json_is( [$library_1_api] ) - ->header_is( 'X-Total-Count', '4', '4 is the count for libraries with pickup_location=1' ) - ->header_is( 'X-Base-Total-Count', '4', '4 is the count for libraries with pickup_location=1' ) - ->header_unlike( 'Link', qr|rel="prev"| ) - ->header_like( 'Link', qr#(_per_page=1.*\&_page=2.*|_page=2.*\&_per_page=1.*)>\; rel="next"# ) - ->header_like( 'Link', qr#(_per_page=1.*\&_page=1.*|_page=1.*\&_per_page=1).*>\; rel="first"# ) - ->header_like( 'Link', qr#(_per_page=1.*\&_page=4.*|_page=4.*\&_per_page=1).*>\; rel="last"# ); + $t->get_ok( "//$userid:$password@/api/v1/biblios/" + . $biblio->id + . "/pickup_locations?" + . "patron_id=" + . $patron->id + . "&_order_by=marc_org_code" + . "&_per_page=1" )->json_is( [$library_1_api] ) + ->header_is( 'X-Total-Count', '4', '4 is the count for libraries with pickup_location=1' ) + ->header_is( 'X-Base-Total-Count', '4', '4 is the count for libraries with pickup_location=1' ) + ->header_unlike( 'Link', qr|rel="prev"| ) + ->header_like( 'Link', qr#(_per_page=1.*\&_page=2.*|_page=2.*\&_per_page=1.*)>\; rel="next"# ) + ->header_like( 'Link', qr#(_per_page=1.*\&_page=1.*|_page=1.*\&_per_page=1).*>\; rel="first"# ) + ->header_like( 'Link', qr#(_per_page=1.*\&_page=4.*|_page=4.*\&_per_page=1).*>\; rel="last"# ); $t->get_ok( "//$userid:$password@/api/v1/biblios/" - . $biblio->id - . "/pickup_locations?" - . "patron_id=" - . $patron->id - . "&_order_by=marc_org_code" - . "&_per_page=1&_page=3" ) # force the needs_override=1 check - ->json_is( [$library_3_api] ) - ->header_is( 'X-Total-Count', '4', '4 is the count for libraries with pickup_location=1' ) - ->header_is( 'X-Base-Total-Count', '4', '4 is the count for libraries with pickup_location=1' ) - ->header_like( 'Link', qr#(_per_page=1.*\&_page=2.*|_page=2.*\&_per_page=1.*)>\; rel="prev"# ) - ->header_like( 'Link', qr#(_per_page=1.*\&_page=4.*|_page=4.*\&_per_page=1.*)>\; rel="next"# ) - ->header_like( 'Link', qr#(_per_page=1.*\&_page=1.*|_page=1.*\&_per_page=1).*>\; rel="first"# ) - ->header_like( 'Link', qr#(_per_page=1.*\&_page=4.*|_page=4.*\&_per_page=1).*>\; rel="last"# ); + . $biblio->id + . "/pickup_locations?" + . "patron_id=" + . $patron->id + . "&_order_by=marc_org_code" + . "&_per_page=1&_page=3" ) # force the needs_override=1 check + ->json_is( [$library_3_api] ) + ->header_is( 'X-Total-Count', '4', '4 is the count for libraries with pickup_location=1' ) + ->header_is( 'X-Base-Total-Count', '4', '4 is the count for libraries with pickup_location=1' ) + ->header_like( 'Link', qr#(_per_page=1.*\&_page=2.*|_page=2.*\&_per_page=1.*)>\; rel="prev"# ) + ->header_like( 'Link', qr#(_per_page=1.*\&_page=4.*|_page=4.*\&_per_page=1.*)>\; rel="next"# ) + ->header_like( 'Link', qr#(_per_page=1.*\&_page=1.*|_page=1.*\&_per_page=1).*>\; rel="first"# ) + ->header_like( 'Link', qr#(_per_page=1.*\&_page=4.*|_page=4.*\&_per_page=1).*>\; rel="last"# ); t::lib::Mocks::mock_preference( 'AllowHoldPolicyOverride', 0 ); - $t->get_ok( "//$userid:$password@/api/v1/biblios/" . $biblio->id . "/pickup_locations?" . "patron_id=" . $patron->id . "&_order_by=marc_org_code" . "&_per_page=1" ) - ->json_is( [$library_1_api] ) - ->header_is( 'X-Total-Count', '2' ) - ->header_is( 'X-Base-Total-Count', '2' ) - ->header_unlike( 'Link', qr|rel="prev"| ) - ->header_like( 'Link', qr#(_per_page=1.*\&_page=2.*|_page=2.*\&_per_page=1.*)>\; rel="next"# ) - ->header_like( 'Link', qr#(_per_page=1.*\&_page=1.*|_page=1.*\&_per_page=1).*>\; rel="first"# ) - ->header_like( 'Link', qr#(_per_page=1.*\&_page=2.*|_page=2.*\&_per_page=1).*>\; rel="last"# ); + $t->get_ok( "//$userid:$password@/api/v1/biblios/" + . $biblio->id + . "/pickup_locations?" + . "patron_id=" + . $patron->id + . "&_order_by=marc_org_code" + . "&_per_page=1" )->json_is( [$library_1_api] )->header_is( 'X-Total-Count', '2' ) + ->header_is( 'X-Base-Total-Count', '2' )->header_unlike( 'Link', qr|rel="prev"| ) + ->header_like( 'Link', qr#(_per_page=1.*\&_page=2.*|_page=2.*\&_per_page=1.*)>\; rel="next"# ) + ->header_like( 'Link', qr#(_per_page=1.*\&_page=1.*|_page=1.*\&_per_page=1).*>\; rel="first"# ) + ->header_like( 'Link', qr#(_per_page=1.*\&_page=2.*|_page=2.*\&_per_page=1).*>\; rel="last"# ); }; - my $deleted_patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $deleted_patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $deleted_patron_id = $deleted_patron->id; $deleted_patron->delete; $t->get_ok( "//$userid:$password@/api/v1/biblios/" - . $biblio->id - . "/pickup_locations?" - . "patron_id=" . $deleted_patron_id ) - ->status_is( 400 ) - ->json_is( '/error' => 'Patron not found' ); + . $biblio->id + . "/pickup_locations?" + . "patron_id=" + . $deleted_patron_id )->status_is(400)->json_is( '/error' => 'Patron not found' ); $biblio->delete; - $t->get_ok( "//$userid:$password@/api/v1/biblios/" - . $biblio->id - . "/pickup_locations?" - . "patron_id=" . $patron->id ) - ->status_is( 404 ) - ->json_is( '/error' => 'Bibliographic record not found' ); + $t->get_ok( + "//$userid:$password@/api/v1/biblios/" . $biblio->id . "/pickup_locations?" . "patron_id=" . $patron->id ) + ->status_is(404)->json_is( '/error' => 'Bibliographic record not found' ); $schema->storage->txn_rollback; }; @@ -651,52 +636,44 @@ subtest 'get_items_public() tests' => sub { my $biblio = $builder->build_sample_biblio(); - $t->get_ok( - "//$userid:$password@/api/v1/public/biblios/" . $biblio->id . "/items" ) - ->status_is(200)->json_is( '' => [], 'No items on the biblio' ); + $t->get_ok( "//$userid:$password@/api/v1/public/biblios/" . $biblio->id . "/items" )->status_is(200) + ->json_is( '' => [], 'No items on the biblio' ); my $item_1 = $builder->build_sample_item( { biblionumber => $biblio->id } ); - my $item_2 = $builder->build_sample_item( - { biblionumber => $biblio->id, withdrawn => 1 } ); + my $item_2 = $builder->build_sample_item( { biblionumber => $biblio->id, withdrawn => 1 } ); - $t->get_ok( "//$userid:$password@/api/v1/public/biblios/" - . $biblio->biblionumber - . "/items" )->status_is(200)->json_is( + $t->get_ok( "//$userid:$password@/api/v1/public/biblios/" . $biblio->biblionumber . "/items" )->status_is(200) + ->json_is( '' => [ $item_1->to_api( { public => 1 } ), $item_2->to_api( { public => 1 } ) ], 'The items are returned' - ); + ); $rules = { withdrawn => ['1'] }; - $t->get_ok( "//$userid:$password@/api/v1/public/biblios/" - . $biblio->biblionumber - . "/items" )->status_is(200)->json_is( + $t->get_ok( "//$userid:$password@/api/v1/public/biblios/" . $biblio->biblionumber . "/items" )->status_is(200) + ->json_is( '' => [ $item_1->to_api( { public => 1 } ) ], 'The items are returned, hidden one is not returned' - ); + ); - $t->get_ok( "/api/v1/public/biblios/" - . $biblio->biblionumber - . "/items" )->status_is(200)->json_is( + $t->get_ok( "/api/v1/public/biblios/" . $biblio->biblionumber . "/items" )->status_is(200)->json_is( '' => [ $item_1->to_api( { public => 1 } ) ], 'Anonymous user, items are returned, hidden one is not returned' - ); - + ); $override_hidden_items = 1; - $t->get_ok( "//$userid:$password@/api/v1/public/biblios/" - . $biblio->biblionumber - . "/items" )->status_is(200)->json_is( + $t->get_ok( "//$userid:$password@/api/v1/public/biblios/" . $biblio->biblionumber . "/items" )->status_is(200) + ->json_is( '' => [ $item_1->to_api( { public => 1 } ), $item_2->to_api( { public => 1 } ) ], 'The items are returned, the patron category has an override' - ); + ); $schema->storage->txn_rollback; }; @@ -786,8 +763,7 @@ subtest 'get_checkouts() tests' => sub { my $userid = $patron->userid; my $biblio = $builder->build_sample_biblio(); - $t->get_ok("//$userid:$password@/api/v1/biblios/" . $biblio->biblionumber . "/checkouts") - ->status_is(403); + $t->get_ok( "//$userid:$password@/api/v1/biblios/" . $biblio->biblionumber . "/checkouts" )->status_is(403); $builder->build( { @@ -827,32 +803,30 @@ subtest 'get_checkouts() tests' => sub { ->status_is( 200, 'manage_bookings allows checkouts access' ) ->json_is( '' => [], 'No checkouts on the biblio' ); - my $item_1 = $builder->build_sample_item({ biblionumber => $biblio->biblionumber }); - my $item_2 = $builder->build_sample_item({ biblionumber => $biblio->biblionumber }); + my $item_1 = $builder->build_sample_item( { biblionumber => $biblio->biblionumber } ); + my $item_2 = $builder->build_sample_item( { biblionumber => $biblio->biblionumber } ); AddIssue( $patron, $item_1->barcode ); AddIssue( $patron, $item_2->barcode ); - my $ret = $t->get_ok( "//$userid:$password@/api/v1/biblios/" . $biblio->biblionumber . "/checkouts") - ->status_is(200) - ->tx->res->json; + my $ret = + $t->get_ok( "//$userid:$password@/api/v1/biblios/" . $biblio->biblionumber . "/checkouts" )->status_is(200) + ->tx->res->json; - my $checkout_1 = Koha::Checkouts->find({ itemnumber => $item_1->id }); - my $checkout_2 = Koha::Checkouts->find({ itemnumber => $item_2->id }); + my $checkout_1 = Koha::Checkouts->find( { itemnumber => $item_1->id } ); + my $checkout_2 = Koha::Checkouts->find( { itemnumber => $item_2->id } ); is_deeply( $ret, [ $checkout_1->to_api, $checkout_2->to_api ] ); AddReturn( $item_1->barcode ); - $ret = $t->get_ok( "//$userid:$password@/api/v1/biblios/" . $biblio->biblionumber . "/checkouts") - ->status_is(200) - ->tx->res->json; + $ret = $t->get_ok( "//$userid:$password@/api/v1/biblios/" . $biblio->biblionumber . "/checkouts" )->status_is(200) + ->tx->res->json; is_deeply( $ret, [ $checkout_2->to_api ] ); - $ret = $t->get_ok( "//$userid:$password@/api/v1/biblios/" . $biblio->biblionumber . "/checkouts?checked_in=1") - ->status_is(200) - ->tx->res->json; + $ret = $t->get_ok( "//$userid:$password@/api/v1/biblios/" . $biblio->biblionumber . "/checkouts?checked_in=1" ) + ->status_is(200)->tx->res->json; my $old_checkout_1 = Koha::Old::Checkouts->find( $checkout_1->id ); @@ -879,26 +853,22 @@ subtest 'set_rating() tests' => sub { my $userid = $patron->userid; my $biblio = $builder->build_sample_biblio(); - $t->post_ok("/api/v1/public/biblios/" . $biblio->biblionumber . "/ratings" => json => { rating => 3 }) - ->status_is(403); + $t->post_ok( "/api/v1/public/biblios/" . $biblio->biblionumber . "/ratings" => json => { rating => 3 } ) + ->status_is(403); - $t->post_ok("//$userid:$password@/api/v1/public/biblios/" . $biblio->biblionumber . "/ratings" => json => { rating => 3 }) - ->status_is(200) - ->json_is( '/rating', '3' ) - ->json_is( '/average', '3' ) - ->json_is( '/count', '1' ); + $t->post_ok( + "//$userid:$password@/api/v1/public/biblios/" . $biblio->biblionumber . "/ratings" => json => { rating => 3 } ) + ->status_is(200)->json_is( '/rating', '3' )->json_is( '/average', '3' )->json_is( '/count', '1' ); - $t->post_ok("//$userid:$password@/api/v1/public/biblios/" . $biblio->biblionumber . "/ratings" => json => { rating => undef }) - ->status_is(200) - ->json_is( '/rating', undef ) - ->json_is( '/average', '0' ) - ->json_is( '/count', '0' ); + $t->post_ok( "//$userid:$password@/api/v1/public/biblios/" + . $biblio->biblionumber + . "/ratings" => json => { rating => undef } )->status_is(200)->json_is( '/rating', undef ) + ->json_is( '/average', '0' )->json_is( '/count', '0' ); $schema->storage->txn_rollback; }; - subtest 'add() tests' => sub { plan tests => 18; @@ -908,7 +878,7 @@ subtest 'add() tests' => sub { my $patron = $builder->build_object( { class => 'Koha::Patrons', - value => { flags => 0 } # no permissions + value => { flags => 0 } # no permissions } ); my $password = 'thePassword123'; @@ -916,7 +886,7 @@ subtest 'add() tests' => sub { my $userid = $patron->userid; my $frameworkcode = 'BKS'; - my $marcxml = q|<?xml version="1.0" encoding="UTF-8"?> + my $marcxml = q|<?xml version="1.0" encoding="UTF-8"?> <record xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.loc.gov/MARC21/slim http://www.loc.gov/standards/marcxml/schema/MARC21slim.xsd" @@ -1292,10 +1262,11 @@ subtest 'add() tests' => sub { ], "leader": "01102pam a2200289 a 8500" }|; - my $marc = q|01102pam a2200289 a 9500001000800000005001700008008004100025010001700066020002800083020003500111040001800146041001100164050002100175082001200196100003200208245005800240260005600298300003300354500002000387650002700407856009500434856008700529906004500616942001200661955013000673999000900803250439820200421093816.0920610s1993 caub s001 0 eng  a 92021731  a05200784383 (Test usmarc) a05200784463 (Test usmarc) aDLCcDLCdDLC0 aenggrc00aPA522b.M38 199300a4802201 aMastronarde, Donald J.938910aIntroduction to Attic Greek (Using usmarc) /cDonald J. Mastronarde. aBerkeley :bUniversity of California Press,cc1993. aix, 425 p. :bmaps ;c26 cm. aIncludes index. 0aAttic Greek dialect97423Contributor biographical informationuhttp://www.loc.gov/catdir/bios/ucal051/92021731.html423Publisher descriptionuhttp://www.loc.gov/catdir/description/ucal041/92021731.html a7bcbccorignewd1eocipf19gy-gencatlg 2ddccBK apc05 to ea00 06-11-92; ea04 to SCD 06-11-92; fd11 06-11-92 (PA522.M...); fr21 06-12-92; fs62 06-15-92; CIP ver. pv07 11-12-93 c3d3|; + my $marc = + q|01102pam a2200289 a 9500001000800000005001700008008004100025010001700066020002800083020003500111040001800146041001100164050002100175082001200196100003200208245005800240260005600298300003300354500002000387650002700407856009500434856008700529906004500616942001200661955013000673999000900803250439820200421093816.0920610s1993 caub s001 0 eng  a 92021731  a05200784383 (Test usmarc) a05200784463 (Test usmarc) aDLCcDLCdDLC0 aenggrc00aPA522b.M38 199300a4802201 aMastronarde, Donald J.938910aIntroduction to Attic Greek (Using usmarc) /cDonald J. Mastronarde. aBerkeley :bUniversity of California Press,cc1993. aix, 425 p. :bmaps ;c26 cm. aIncludes index. 0aAttic Greek dialect97423Contributor biographical informationuhttp://www.loc.gov/catdir/bios/ucal051/92021731.html423Publisher descriptionuhttp://www.loc.gov/catdir/description/ucal041/92021731.html a7bcbccorignewd1eocipf19gy-gencatlg 2ddccBK apc05 to ea00 06-11-92; ea04 to SCD 06-11-92; fd11 06-11-92 (PA522.M...); fr21 06-12-92; fs62 06-15-92; CIP ver. pv07 11-12-93 c3d3|; $t->post_ok("//$userid:$password@/api/v1/biblios") - ->status_is(403, 'Not enough permissions makes it return the right code'); + ->status_is( 403, 'Not enough permissions makes it return the right code' ); # Add permissions $builder->build( @@ -1309,22 +1280,28 @@ subtest 'add() tests' => sub { } ); - $t->post_ok("//$userid:$password@/api/v1/biblios" => {'Content-Type' => 'application/marcxml+xml', 'x-framework-id' => $frameworkcode, "x-record-schema" => 'INVALID'}) - ->status_is(400, 'Invalid header x-record-schema'); + $t->post_ok( + "//$userid:$password@/api/v1/biblios" => { + 'Content-Type' => 'application/marcxml+xml', 'x-framework-id' => $frameworkcode, + "x-record-schema" => 'INVALID' + } + )->status_is( 400, 'Invalid header x-record-schema' ); $t->post_ok( "//$userid:$password@/api/v1/biblios" => { 'Content-Type' => 'application/marcxml+xml', 'x-framework-id' => $frameworkcode } => $marcxml ) - ->status_is(200) - ->json_has('/id') + ->status_is(200)->json_has('/id') ->header_is( 'Location' => "/api/v1/biblios/" . $t->tx->res->json->{id}, "REST3.4.1" ); - $t->post_ok("//$userid:$password@/api/v1/biblios" => {'Content-Type' => 'application/marc-in-json', 'x-framework-id' => $frameworkcode, 'x-confirm-not-duplicate' => 1} => $mij) - ->status_is(200) - ->json_has('/id'); + $t->post_ok( + "//$userid:$password@/api/v1/biblios" => { + 'Content-Type' => 'application/marc-in-json', 'x-framework-id' => $frameworkcode, + 'x-confirm-not-duplicate' => 1 + } => $mij + )->status_is(200)->json_has('/id'); - $t->post_ok("//$userid:$password@/api/v1/biblios" => {'Content-Type' => 'application/marc', 'x-framework-id' => $frameworkcode} => $marc) - ->status_is(200) - ->json_has('/id'); + $t->post_ok( "//$userid:$password@/api/v1/biblios" => + { 'Content-Type' => 'application/marc', 'x-framework-id' => $frameworkcode } => $marc )->status_is(200) + ->json_has('/id'); subtest 'x-record-source-id header tests' => sub { @@ -1367,8 +1344,7 @@ subtest 'add() tests' => sub { $mock_biblio->mock( 'AddBiblio', sub { return ( undef, undef ); } ); $t->post_ok( "//$userid:$password@/api/v1/biblios" => - { 'Content-Type' => 'application/marc', 'x-framework-id' => $frameworkcode } => $marc ) - ->status_is(400) + { 'Content-Type' => 'application/marc', 'x-framework-id' => $frameworkcode } => $marc )->status_is(400) ->json_is( { error => 'Error creating record', @@ -1388,7 +1364,7 @@ subtest 'put() tests' => sub { my $patron = $builder->build_object( { class => 'Koha::Patrons', - value => { flags => 0 } # no permissions + value => { flags => 0 } # no permissions } ); my $password = 'thePassword123'; @@ -1396,7 +1372,7 @@ subtest 'put() tests' => sub { my $userid = $patron->userid; my $frameworkcode = 'BKS'; - my $biblio = $builder->build_sample_biblio({frameworkcode => $frameworkcode}); + my $biblio = $builder->build_sample_biblio( { frameworkcode => $frameworkcode } ); my $biblionumber = $biblio->biblionumber; @@ -1776,10 +1752,11 @@ subtest 'put() tests' => sub { ], "leader": "01102pam a2200289 a 8500" }|; - my $marc = q|01116pam a2200289 a 4500001000800000005001700008008004100025010001700066020002800083020002800111040001800139041001100157050002100168082001200189100003200201245007500233260005600308300003300364500002000397650002700417856009500444856008700539906004500626942001200671955013000683999001300813250439820221223213433.0920610s1993 caub s001 0 eng  a 92021731  a05200784384 (Test json) a05200784464 (Test json) aDLCcDLCdDLC0 aenggrc00aPA522b.M38 199300a4802201 aMastronarde, Donald J.938910aIntroduction to Attic Greek (Using usmarc) /cDonald J. Mastronarde. aBerkeley :bUniversity of California Press,cc1993. aix, 425 p. :bmaps ;c26 cm. aIncludes index. 0aAttic Greek dialect97423Contributor biographical informationuhttp://www.loc.gov/catdir/bios/ucal051/92021731.html423Publisher descriptionuhttp://www.loc.gov/catdir/description/ucal041/92021731.html a7bcbccorignewd1eocipf19gy-gencatlg 2ddccBK apc05 to ea00 06-11-92; ea04 to SCD 06-11-92; fd11 06-11-92 (PA522.M...); fr21 06-12-92; fs62 06-15-92; CIP ver. pv07 11-12-93 c715d715|; + my $marc = + q|01116pam a2200289 a 4500001000800000005001700008008004100025010001700066020002800083020002800111040001800139041001100157050002100168082001200189100003200201245007500233260005600308300003300364500002000397650002700417856009500444856008700539906004500626942001200671955013000683999001300813250439820221223213433.0920610s1993 caub s001 0 eng  a 92021731  a05200784384 (Test json) a05200784464 (Test json) aDLCcDLCdDLC0 aenggrc00aPA522b.M38 199300a4802201 aMastronarde, Donald J.938910aIntroduction to Attic Greek (Using usmarc) /cDonald J. Mastronarde. aBerkeley :bUniversity of California Press,cc1993. aix, 425 p. :bmaps ;c26 cm. aIncludes index. 0aAttic Greek dialect97423Contributor biographical informationuhttp://www.loc.gov/catdir/bios/ucal051/92021731.html423Publisher descriptionuhttp://www.loc.gov/catdir/description/ucal041/92021731.html a7bcbccorignewd1eocipf19gy-gencatlg 2ddccBK apc05 to ea00 06-11-92; ea04 to SCD 06-11-92; fd11 06-11-92 (PA522.M...); fr21 06-12-92; fs62 06-15-92; CIP ver. pv07 11-12-93 c715d715|; $t->put_ok("//$userid:$password@/api/v1/biblios/$biblionumber") - ->status_is(403, 'Not enough permissions makes it return the right code'); + ->status_is( 403, 'Not enough permissions makes it return the right code' ); # Add permissions $builder->build( @@ -1793,29 +1770,29 @@ subtest 'put() tests' => sub { } ); - $t->put_ok("//$userid:$password@/api/v1/biblios/$biblionumber" => {'Content-Type' => 'application/marcxml+xml', 'x-framework-id' => $frameworkcode} => $marcxml) - ->status_is(200) - ->json_has('/id'); + $t->put_ok( "//$userid:$password@/api/v1/biblios/$biblionumber" => + { 'Content-Type' => 'application/marcxml+xml', 'x-framework-id' => $frameworkcode } => $marcxml ) + ->status_is(200)->json_has('/id'); $biblio = Koha::Biblios->find($biblionumber); - is($biblio->title, 'Introduction to Attic Greek (Using marcxml) /'); + is( $biblio->title, 'Introduction to Attic Greek (Using marcxml) /' ); - $t->put_ok("//$userid:$password@/api/v1/biblios/$biblionumber" => {'Content-Type' => 'application/marc-in-json', 'x-framework-id' => $frameworkcode} => $mij) - ->status_is(200) - ->json_has('/id'); + $t->put_ok( "//$userid:$password@/api/v1/biblios/$biblionumber" => + { 'Content-Type' => 'application/marc-in-json', 'x-framework-id' => $frameworkcode } => $mij ) + ->status_is(200)->json_has('/id'); $biblio = Koha::Biblios->find($biblionumber); - is($biblio->title, 'Introduction to Attic Greek (Using mij) /'); + is( $biblio->title, 'Introduction to Attic Greek (Using mij) /' ); - $t->put_ok("//$userid:$password@/api/v1/biblios/$biblionumber" => {'Content-Type' => 'application/marc', 'x-framework-id' => $frameworkcode} => $marc) - ->status_is(200) - ->json_has('/id'); + $t->put_ok( "//$userid:$password@/api/v1/biblios/$biblionumber" => + { 'Content-Type' => 'application/marc', 'x-framework-id' => $frameworkcode } => $marc )->status_is(200) + ->json_has('/id'); $biblio = Koha::Biblios->find($biblionumber); - is($biblio->title, 'Introduction to Attic Greek (Using usmarc) /'); + is( $biblio->title, 'Introduction to Attic Greek (Using usmarc) /' ); $schema->storage->txn_rollback; }; @@ -1837,10 +1814,10 @@ subtest 'list() tests' => sub { $patron->discard_changes; my $userid = $patron->userid; - t::lib::Mocks::mock_preference('marcflavour', 'UNIMARC'); + t::lib::Mocks::mock_preference( 'marcflavour', 'UNIMARC' ); my $title_with_diacritics = "L'insoutenable légèreté de l'être"; - my $biblio = $builder->build_sample_biblio( + my $biblio = $builder->build_sample_biblio( { title => $title_with_diacritics, author => "Milan Kundera" @@ -1849,11 +1826,11 @@ subtest 'list() tests' => sub { my $record = $biblio->metadata->record; $record->leader(' nam 3 4500'); - $biblio->metadata->metadata($record->as_xml_record('UNIMARC'))->store; + $biblio->metadata->metadata( $record->as_xml_record('UNIMARC') )->store; my $biblio_id_1 = $biblio->id; - t::lib::Mocks::mock_preference('marcflavour', 'MARC21'); + t::lib::Mocks::mock_preference( 'marcflavour', 'MARC21' ); my $biblio_id_2 = $builder->build_sample_biblio->id; my $query = encode_json( [ { biblio_id => $biblio_id_1 }, { biblio_id => $biblio_id_2 } ] ); @@ -1881,15 +1858,11 @@ subtest 'list() tests' => sub { $t->get_ok( "//$userid:$password@/api/v1/biblios?q=$query" => { Accept => 'text/plain' } )->status_is(200); # DELETE any biblio with ISBN = TOMAS - Koha::Biblios->search({ 'biblioitem.isbn' => 'TOMAS' }, { join => [ 'biblioitem' ] }) - ->delete; + Koha::Biblios->search( { 'biblioitem.isbn' => 'TOMAS' }, { join => ['biblioitem'] } )->delete; - - my $isbn_query = encode_json({ isbn => 'TOMAS' }); - $biblio->biblioitem->set({ isbn => 'TOMAS' })->store; - $t->get_ok( "//$userid:$password@/api/v1/biblios?q=$isbn_query" => - { Accept => 'text/plain' } ) - ->status_is(200); + my $isbn_query = encode_json( { isbn => 'TOMAS' } ); + $biblio->biblioitem->set( { isbn => 'TOMAS' } )->store; + $t->get_ok( "//$userid:$password@/api/v1/biblios?q=$isbn_query" => { Accept => 'text/plain' } )->status_is(200); $schema->storage->txn_rollback; }; @@ -1956,61 +1929,63 @@ subtest 'add_item() tests' => sub { }; subtest 'update_item() tests' => sub { - plan tests => 7; + plan tests => 7; - $schema->storage->txn_begin; + $schema->storage->txn_begin; - my $patron = $builder->build_object( - { - class => 'Koha::Patrons', - value => { flags => 0 } - } - ); - my $password = 'thePassword123'; - $patron->set_password( { password => $password, skip_validation => 1 } ); - my $userid = $patron->userid; + my $patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 0 } + } + ); + my $password = 'thePassword123'; + $patron->set_password( { password => $password, skip_validation => 1 } ); + my $userid = $patron->userid; - my $item = $builder->build_sample_item({ replacementprice => 5 }); - my $biblio_id = $item->biblionumber; - my $item_id = $item->itemnumber; + my $item = $builder->build_sample_item( { replacementprice => 5 } ); + my $biblio_id = $item->biblionumber; + my $item_id = $item->itemnumber; - my $biblio = Koha::Biblios->find($item->biblionumber); + my $biblio = Koha::Biblios->find( $item->biblionumber ); - my $matching_items = Koha::Items->search({ barcode => $item->barcode }); + my $matching_items = Koha::Items->search( { barcode => $item->barcode } ); - while (my $mbcitem = $matching_items->next) { - $mbcitem->delete if $mbcitem->biblionumber != $item->biblionumber; - } + while ( my $mbcitem = $matching_items->next ) { + $mbcitem->delete if $mbcitem->biblionumber != $item->biblionumber; + } - $t->put_ok("//$userid:$password@/api/v1/biblios/$biblio_id/items/$item_id" => json => { external_id => 'something' }) - ->status_is(403, 'Not enough permissions to update an item'); + $t->put_ok( + "//$userid:$password@/api/v1/biblios/$biblio_id/items/$item_id" => json => { external_id => 'something' } ) + ->status_is( 403, 'Not enough permissions to update an item' ); - # Add permissions - $builder->build( - { - source => 'UserPermission', - value => { - borrowernumber => $patron->borrowernumber, - module_bit => 9, - code => 'edit_catalogue' - } - } - ); + # Add permissions + $builder->build( + { + source => 'UserPermission', + value => { + borrowernumber => $patron->borrowernumber, + module_bit => 9, + code => 'edit_catalogue' + } + } + ); - my $other_item = $builder->build_sample_item(); + my $other_item = $builder->build_sample_item(); - $t->put_ok("//$userid:$password@/api/v1/biblios/$biblio_id/items/$item_id" => json => { - external_id => $other_item->barcode, - }) - ->status_is(409, 'Barcode not unique'); + $t->put_ok( + "//$userid:$password@/api/v1/biblios/$biblio_id/items/$item_id" => json => { + external_id => $other_item->barcode, + } + )->status_is( 409, 'Barcode not unique' ); - $t->put_ok("//$userid:$password@/api/v1/biblios/$biblio_id/items/$item_id" => json => { - replacement_price => 30, - }) - ->status_is(200, 'Item updated') - ->json_is('/replacement_price', 30); + $t->put_ok( + "//$userid:$password@/api/v1/biblios/$biblio_id/items/$item_id" => json => { + replacement_price => 30, + } + )->status_is( 200, 'Item updated' )->json_is( '/replacement_price', 30 ); - $schema->storage->txn_rollback; + $schema->storage->txn_rollback; }; subtest 'merge() tests' => sub { diff --git a/t/db_dependent/api/v1/bookings.t b/t/db_dependent/api/v1/bookings.t index 17fcb0a6c0..2233461b73 100755 --- a/t/db_dependent/api/v1/bookings.t +++ b/t/db_dependent/api/v1/bookings.t @@ -256,8 +256,8 @@ subtest 'add() tests' => sub { # Authorized attempt to write my $booking_id = $t->post_ok( "//$userid:$password@/api/v1/bookings" => json => $booking )->status_is( 201, 'REST3.2.1' ) - ->header_like( Location => qr|^\/api\/v1\/bookings/\d*|, 'REST3.4.1' ) - ->json_is( '/biblio_id' => $biblio->id )->tx->res->json->{booking_id}; + ->header_like( Location => qr|^\/api\/v1\/bookings/\d*|, 'REST3.4.1' )->json_is( '/biblio_id' => $biblio->id ) + ->tx->res->json->{booking_id}; # Authorized attempt to create with null id $booking->{booking_id} = undef; diff --git a/t/db_dependent/api/v1/cashups.t b/t/db_dependent/api/v1/cashups.t index ab7646d0f9..c5ab5cff70 100755 --- a/t/db_dependent/api/v1/cashups.t +++ b/t/db_dependent/api/v1/cashups.t @@ -67,20 +67,14 @@ subtest 'list() tests' => sub { my $non_existent_cr_id = $cash_register_to_delete->id; $cash_register_to_delete->delete; - $t->get_ok("//$userid:$password@/api/v1/cash_registers/$non_existent_cr_id/cashups") - ->status_is(404)->json_is( '/error' => 'Register not found' ); + $t->get_ok("//$userid:$password@/api/v1/cash_registers/$non_existent_cr_id/cashups")->status_is(404) + ->json_is( '/error' => 'Register not found' ); - my $register = $builder->build_object( - { - class => 'Koha::Cash::Registers' - } - ); + my $register = $builder->build_object( { class => 'Koha::Cash::Registers' } ); my $register_id = $register->id; # No cashups, so empty array should be returned - $t->get_ok( - "//$userid:$password@/api/v1/cash_registers/$register_id/cashups") - ->status_is(200)->json_is( [] ); + $t->get_ok("//$userid:$password@/api/v1/cash_registers/$register_id/cashups")->status_is(200)->json_is( [] ); my $cashup = $builder->build_object( { @@ -94,9 +88,8 @@ subtest 'list() tests' => sub { ); # One cashup created, should get returned - $t->get_ok( - "//$userid:$password@/api/v1/cash_registers/$register_id/cashups") - ->status_is(200)->json_is( [ $cashup->to_api ] ); + $t->get_ok("//$userid:$password@/api/v1/cash_registers/$register_id/cashups")->status_is(200) + ->json_is( [ $cashup->to_api ] ); my $another_cashup = $builder->build_object( { @@ -110,27 +103,22 @@ subtest 'list() tests' => sub { ); # One more cashup created, both should be returned - $t->get_ok( - "//$userid:$password@/api/v1/cash_registers/$register_id/cashups") - ->status_is(200) - ->json_is( [ $another_cashup->to_api, $cashup->to_api, ] ); + $t->get_ok("//$userid:$password@/api/v1/cash_registers/$register_id/cashups")->status_is(200) + ->json_is( [ $another_cashup->to_api, $cashup->to_api, ] ); # Warn on unsupported query parameter - $t->get_ok( -"//$userid:$password@/api/v1/cash_registers/$register_id/cashups?cashup_blah=blah" - )->status_is(400)->json_is( + $t->get_ok("//$userid:$password@/api/v1/cash_registers/$register_id/cashups?cashup_blah=blah")->status_is(400) + ->json_is( [ { path => '/query/cashup_blah', message => 'Malformed query string' } ] - ); + ); # Unauthorized access - $t->get_ok( - "//$unauth_userid:$password@/api/v1/cash_registers/$register_id/cashups" - )->status_is(403); + $t->get_ok("//$unauth_userid:$password@/api/v1/cash_registers/$register_id/cashups")->status_is(403); $schema->storage->txn_rollback; }; @@ -141,8 +129,7 @@ subtest 'get() tests' => sub { $schema->storage->txn_begin; - my $cashup = - $builder->build_object( { class => 'Koha::Cash::Register::Cashups' } ); + my $cashup = $builder->build_object( { class => 'Koha::Cash::Register::Cashups' } ); my $librarian = $builder->build_object( { class => 'Koha::Patrons', @@ -163,19 +150,16 @@ subtest 'get() tests' => sub { $patron->set_password( { password => $password, skip_validation => 1 } ); my $unauth_userid = $patron->userid; - $t->get_ok( "//$userid:$password@/api/v1/cashups/" . $cashup->id ) - ->status_is(200)->json_is( $cashup->to_api ); + $t->get_ok( "//$userid:$password@/api/v1/cashups/" . $cashup->id )->status_is(200)->json_is( $cashup->to_api ); - $t->get_ok( "//$unauth_userid:$password@/api/v1/cashups/" . $cashup->id ) - ->status_is(403); + $t->get_ok( "//$unauth_userid:$password@/api/v1/cashups/" . $cashup->id )->status_is(403); - my $cashup_to_delete = - $builder->build_object( { class => 'Koha::Cash::Register::Cashups' } ); - my $non_existent_id = $cashup_to_delete->id; + my $cashup_to_delete = $builder->build_object( { class => 'Koha::Cash::Register::Cashups' } ); + my $non_existent_id = $cashup_to_delete->id; $cashup_to_delete->delete; - $t->get_ok("//$userid:$password@/api/v1/cashups/$non_existent_id") - ->status_is(404)->json_is( '/error' => 'Cashup not found' ); + $t->get_ok("//$userid:$password@/api/v1/cashups/$non_existent_id")->status_is(404) + ->json_is( '/error' => 'Cashup not found' ); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/api/v1/checkouts.t b/t/db_dependent/api/v1/checkouts.t index 779f00156a..9e20839c8f 100755 --- a/t/db_dependent/api/v1/checkouts.t +++ b/t/db_dependent/api/v1/checkouts.t @@ -32,7 +32,7 @@ use Koha::Database; use Koha::DateUtils qw( dt_from_string output_pref ); use Koha::Token; -my $schema = Koha::Database->schema; +my $schema = Koha::Database->schema; my $builder = t::lib::TestBuilder->new; t::lib::Mocks::mock_preference( 'RESTBasicAuth', 1 ); @@ -42,33 +42,33 @@ $schema->storage->txn_begin; my $dbh = C4::Context->dbh; -my $librarian = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 2 } -}); +my $librarian = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 2 } + } +); my $password = 'thePassword123'; -$librarian->set_password({ password => $password, skip_validation => 1 }); +$librarian->set_password( { password => $password, skip_validation => 1 } ); my $userid = $librarian->userid; -my $patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 0 } -}); +my $patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 0 } + } +); my $unauth_password = 'thePassword000'; -$patron->set_password({ password => $unauth_password, skip_validattion => 1 }); +$patron->set_password( { password => $unauth_password, skip_validattion => 1 } ); my $unauth_userid = $patron->userid; -my $patron_id = $patron->borrowernumber; +my $patron_id = $patron->borrowernumber; -my $branchcode = $builder->build({ source => 'Branch' })->{ branchcode }; +my $branchcode = $builder->build( { source => 'Branch' } )->{branchcode}; -$t->get_ok( "//$userid:$password@/api/v1/checkouts?patron_id=$patron_id" ) - ->status_is(200) - ->json_is([]); +$t->get_ok("//$userid:$password@/api/v1/checkouts?patron_id=$patron_id")->status_is(200)->json_is( [] ); my $notexisting_patron_id = $patron_id + 1; -$t->get_ok( "//$userid:$password@/api/v1/checkouts?patron_id=$notexisting_patron_id" ) - ->status_is(200) - ->json_is([]); +$t->get_ok("//$userid:$password@/api/v1/checkouts?patron_id=$notexisting_patron_id")->status_is(200)->json_is( [] ); my $bookings_librarian = $builder->build_object( { @@ -98,9 +98,9 @@ Koha::CirculationRules->set_rules( itemtype => undef, branchcode => undef, rules => { - renewalperiod => 7, + renewalperiod => 7, renewalsallowed => 1, - issuelength => 5, + issuelength => 5, } } ); @@ -110,157 +110,122 @@ my $item2 = $builder->build_sample_item; my $item3 = $builder->build_sample_item; my $item4 = $builder->build_sample_item; -my $date_due = DateTime->now->add(weeks => 2); -my $issue1 = C4::Circulation::AddIssue($patron, $item1->barcode, $date_due); +my $date_due = DateTime->now->add( weeks => 2 ); +my $issue1 = C4::Circulation::AddIssue( $patron, $item1->barcode, $date_due ); my $date_due1 = Koha::DateUtils::dt_from_string( $issue1->date_due ); -my $issue2 = C4::Circulation::AddIssue($patron, $item2->barcode, $date_due); +my $issue2 = C4::Circulation::AddIssue( $patron, $item2->barcode, $date_due ); my $date_due2 = Koha::DateUtils::dt_from_string( $issue2->date_due ); -my $issue3 = C4::Circulation::AddIssue($librarian, $item3->barcode, $date_due); +my $issue3 = C4::Circulation::AddIssue( $librarian, $item3->barcode, $date_due ); my $date_due3 = Koha::DateUtils::dt_from_string( $issue3->date_due ); -my $issue4 = C4::Circulation::AddIssue($patron, $item4->barcode); -C4::Circulation::AddReturn($item4->barcode, $branchcode); +my $issue4 = C4::Circulation::AddIssue( $patron, $item4->barcode ); +C4::Circulation::AddReturn( $item4->barcode, $branchcode ); -$t->get_ok( "//$userid:$password@/api/v1/checkouts?patron_id=$patron_id" ) - ->status_is(200) - ->json_is('/0/patron_id' => $patron_id) - ->json_is('/0/item_id' => $item1->itemnumber) - ->json_is('/0/due_date' => output_pref({ dateformat => "rfc3339", dt => $date_due1 }) ) - ->json_is('/1/patron_id' => $patron_id) - ->json_is('/1/item_id' => $item2->itemnumber) - ->json_is('/1/due_date' => output_pref({ dateformat => "rfc3339", dt => $date_due2 }) ) - ->json_hasnt('/2'); +$t->get_ok("//$userid:$password@/api/v1/checkouts?patron_id=$patron_id")->status_is(200) + ->json_is( '/0/patron_id' => $patron_id )->json_is( '/0/item_id' => $item1->itemnumber ) + ->json_is( '/0/due_date' => output_pref( { dateformat => "rfc3339", dt => $date_due1 } ) ) + ->json_is( '/1/patron_id' => $patron_id )->json_is( '/1/item_id' => $item2->itemnumber ) + ->json_is( '/1/due_date' => output_pref( { dateformat => "rfc3339", dt => $date_due2 } ) )->json_hasnt('/2'); # Test checked_in parameter, zero means, the response is same as without it -$t->get_ok( "//$userid:$password@/api/v1/checkouts?patron_id=$patron_id&checked_in=0" ) - ->status_is(200) - ->json_is('/0/patron_id' => $patron_id) - ->json_is('/0/item_id' => $item1->itemnumber) - ->json_is('/0/due_date' => output_pref({ dateformat => "rfc3339", dt => $date_due1 }) ) - ->json_is('/1/patron_id' => $patron_id) - ->json_is('/1/item_id' => $item2->itemnumber) - ->json_is('/1/due_date' => output_pref({ dateformat => "rfc3339", dt => $date_due2 }) ) - ->json_hasnt('/2'); +$t->get_ok("//$userid:$password@/api/v1/checkouts?patron_id=$patron_id&checked_in=0")->status_is(200) + ->json_is( '/0/patron_id' => $patron_id )->json_is( '/0/item_id' => $item1->itemnumber ) + ->json_is( '/0/due_date' => output_pref( { dateformat => "rfc3339", dt => $date_due1 } ) ) + ->json_is( '/1/patron_id' => $patron_id )->json_is( '/1/item_id' => $item2->itemnumber ) + ->json_is( '/1/due_date' => output_pref( { dateformat => "rfc3339", dt => $date_due2 } ) )->json_hasnt('/2'); # Test checked_in parameter, one measn, the checked in checkout is in the response too -$t->get_ok( "//$userid:$password@/api/v1/checkouts?patron_id=$patron_id&checked_in=1" ) - ->status_is(200) - ->json_is('/0/patron_id' => $patron_id) - ->json_is('/0/item_id' => $item4->itemnumber) - ->json_hasnt('/1'); +$t->get_ok("//$userid:$password@/api/v1/checkouts?patron_id=$patron_id&checked_in=1")->status_is(200) + ->json_is( '/0/patron_id' => $patron_id )->json_is( '/0/item_id' => $item4->itemnumber )->json_hasnt('/1'); $item4->delete; -$t->get_ok( "//$userid:$password@/api/v1/checkouts?patron_id=$patron_id&checked_in=1" ) - ->status_is(200) - ->json_is('/0/patron_id' => $patron_id) - ->json_is('/0/item_id' => undef); +$t->get_ok("//$userid:$password@/api/v1/checkouts?patron_id=$patron_id&checked_in=1")->status_is(200) + ->json_is( '/0/patron_id' => $patron_id )->json_is( '/0/item_id' => undef ); -$t->get_ok( "//$unauth_userid:$unauth_password@/api/v1/checkouts/" . $issue3->issue_id ) - ->status_is(403) - ->json_is({ error => "Authorization failure. Missing required permission(s).", - required_permissions => { circulate => "circulate_remaining_permissions" } - }); +$t->get_ok( "//$unauth_userid:$unauth_password@/api/v1/checkouts/" . $issue3->issue_id )->status_is(403)->json_is( + { + error => "Authorization failure. Missing required permission(s).", + required_permissions => { circulate => "circulate_remaining_permissions" } + } +); -$t->get_ok( "//$userid:$password@/api/v1/checkouts?patron_id=$patron_id") - ->status_is(200) - ->json_is('/0/patron_id' => $patron_id) - ->json_is('/0/item_id' => $item1->itemnumber) - ->json_is('/0/due_date' => output_pref({ dateformat => "rfc3339", dt => $date_due1 }) ) - ->json_is('/1/patron_id' => $patron_id) - ->json_is('/1/item_id' => $item2->itemnumber) - ->json_is('/1/due_date' => output_pref({ dateformat => "rfc3339", dt => $date_due2 }) ) - ->json_hasnt('/2'); +$t->get_ok("//$userid:$password@/api/v1/checkouts?patron_id=$patron_id")->status_is(200) + ->json_is( '/0/patron_id' => $patron_id )->json_is( '/0/item_id' => $item1->itemnumber ) + ->json_is( '/0/due_date' => output_pref( { dateformat => "rfc3339", dt => $date_due1 } ) ) + ->json_is( '/1/patron_id' => $patron_id )->json_is( '/1/item_id' => $item2->itemnumber ) + ->json_is( '/1/due_date' => output_pref( { dateformat => "rfc3339", dt => $date_due2 } ) )->json_hasnt('/2'); -$t->get_ok( "//$userid:$password@/api/v1/checkouts?patron_id=$patron_id&_per_page=1&_page=1") - ->status_is(200) - ->header_is('X-Total-Count', '2') - ->header_like('Link', qr|rel="next"|) - ->header_like('Link', qr|rel="first"|) - ->header_like('Link', qr|rel="last"|) - ->json_is('/0/patron_id' => $patron_id) - ->json_is('/0/item_id' => $item1->itemnumber) - ->json_is('/0/due_date' => output_pref({ dateformat => "rfc3339", dt => $date_due1 }) ) - ->json_hasnt('/1'); +$t->get_ok("//$userid:$password@/api/v1/checkouts?patron_id=$patron_id&_per_page=1&_page=1")->status_is(200) + ->header_is( 'X-Total-Count', '2' )->header_like( 'Link', qr|rel="next"| )->header_like( 'Link', qr|rel="first"| ) + ->header_like( 'Link', qr|rel="last"| )->json_is( '/0/patron_id' => $patron_id ) + ->json_is( '/0/item_id' => $item1->itemnumber ) + ->json_is( '/0/due_date' => output_pref( { dateformat => "rfc3339", dt => $date_due1 } ) )->json_hasnt('/1'); -$t->get_ok( "//$userid:$password@/api/v1/checkouts?patron_id=$patron_id&_per_page=1&_page=2") - ->status_is(200) - ->header_is('X-Total-Count', '2') - ->header_like('Link', qr|rel="prev"|) - ->header_like('Link', qr|rel="first"|) - ->header_like('Link', qr|rel="last"|) - ->json_is('/0/patron_id' => $patron_id) - ->json_is('/0/item_id' => $item2->itemnumber) - ->json_is('/0/due_date' => output_pref({ dateformat => "rfc3339", dt => $date_due2 }) ) - ->json_hasnt('/1'); +$t->get_ok("//$userid:$password@/api/v1/checkouts?patron_id=$patron_id&_per_page=1&_page=2")->status_is(200) + ->header_is( 'X-Total-Count', '2' )->header_like( 'Link', qr|rel="prev"| )->header_like( 'Link', qr|rel="first"| ) + ->header_like( 'Link', qr|rel="last"| )->json_is( '/0/patron_id' => $patron_id ) + ->json_is( '/0/item_id' => $item2->itemnumber ) + ->json_is( '/0/due_date' => output_pref( { dateformat => "rfc3339", dt => $date_due2 } ) )->json_hasnt('/1'); -$t->get_ok( "//$userid:$password@/api/v1/checkouts/" . $issue1->issue_id) - ->status_is(200) - ->json_is('/patron_id' => $patron_id) - ->json_is('/item_id' => $item1->itemnumber) - ->json_is('/due_date' => output_pref({ dateformat => "rfc3339", dt => $date_due1 }) ) - ->json_hasnt('/1'); +$t->get_ok( "//$userid:$password@/api/v1/checkouts/" . $issue1->issue_id )->status_is(200) + ->json_is( '/patron_id' => $patron_id )->json_is( '/item_id' => $item1->itemnumber ) + ->json_is( '/due_date' => output_pref( { dateformat => "rfc3339", dt => $date_due1 } ) )->json_hasnt('/1'); -$t->get_ok( "//$userid:$password@/api/v1/checkouts/" . $issue1->issue_id) - ->status_is(200) - ->json_is('/due_date' => output_pref({ dateformat => "rfc3339", dt => $date_due1 }) ); +$t->get_ok( "//$userid:$password@/api/v1/checkouts/" . $issue1->issue_id )->status_is(200) + ->json_is( '/due_date' => output_pref( { dateformat => "rfc3339", dt => $date_due1 } ) ); -$t->get_ok( "//$userid:$password@/api/v1/checkouts/" . $issue2->issue_id) - ->status_is(200) - ->json_is('/due_date' => output_pref( { dateformat => "rfc3339", dt => $date_due2 }) ); +$t->get_ok( "//$userid:$password@/api/v1/checkouts/" . $issue2->issue_id )->status_is(200) + ->json_is( '/due_date' => output_pref( { dateformat => "rfc3339", dt => $date_due2 } ) ); -my $expected_datedue = $date_due - ->set_time_zone('local') - ->add(days => 7) - ->set(hour => 23, minute => 59, second => 0); +my $expected_datedue = + $date_due->set_time_zone('local')->add( days => 7 )->set( hour => 23, minute => 59, second => 0 ); -$t->post_ok ( "//$userid:$password@/api/v1/checkouts/" . $issue1->issue_id . "/renewal" ) - ->status_is(201) - ->json_is('/due_date' => output_pref( { dateformat => "rfc3339", dt => $expected_datedue }) ) - ->header_is(Location => "/api/v1/checkouts/" . $issue1->issue_id . "/renewal"); +$t->post_ok( "//$userid:$password@/api/v1/checkouts/" . $issue1->issue_id . "/renewal" )->status_is(201) + ->json_is( '/due_date' => output_pref( { dateformat => "rfc3339", dt => $expected_datedue } ) ) + ->header_is( Location => "/api/v1/checkouts/" . $issue1->issue_id . "/renewal" ); my $renewal = $issue1->renewals->last; is( $renewal->renewal_type, 'Manual', 'Manual renewal recorded' ); -$t->get_ok ( "//$userid:$password@/api/v1/checkouts/" . $issue1->issue_id . "/renewals" ) - ->status_is(200) - ->json_is('/0/checkout_id' => $issue1->issue_id) - ->json_is('/0/interface' => 'api') - ->json_is('/0/renewer_id' => $librarian->borrowernumber ); +$t->get_ok( "//$userid:$password@/api/v1/checkouts/" . $issue1->issue_id . "/renewals" )->status_is(200) + ->json_is( '/0/checkout_id' => $issue1->issue_id )->json_is( '/0/interface' => 'api' ) + ->json_is( '/0/renewer_id' => $librarian->borrowernumber ); -$t->post_ok( "//$unauth_userid:$unauth_password@/api/v1/checkouts/" . $issue3->issue_id . "/renewal" ) - ->status_is(403) - ->json_is({ error => "Authorization failure. Missing required permission(s).", - required_permissions => { circulate => "circulate_remaining_permissions" } - }); +$t->post_ok( "//$unauth_userid:$unauth_password@/api/v1/checkouts/" . $issue3->issue_id . "/renewal" )->status_is(403) + ->json_is( + { + error => "Authorization failure. Missing required permission(s).", + required_permissions => { circulate => "circulate_remaining_permissions" } + } + ); -$t->get_ok( "//$userid:$password@/api/v1/checkouts/" . $issue2->issue_id . "/allows_renewal") - ->status_is(200) - ->json_is({ +$t->get_ok( "//$userid:$password@/api/v1/checkouts/" . $issue2->issue_id . "/allows_renewal" )->status_is(200) + ->json_is( + { allows_renewal => Mojo::JSON->true, max_renewals => 1, unseen_renewals => 0, current_renewals => 0, error => undef - }); + } + ); -$t->post_ok( "//$userid:$password@/api/v1/checkouts/" . $issue2->issue_id . "/renewal" ) - ->status_is(201) - ->json_is('/due_date' => output_pref({ dateformat => "rfc3339", dt => $expected_datedue}) ) - ->header_is(Location => "/api/v1/checkouts/" . $issue2->issue_id . "/renewal"); +$t->post_ok( "//$userid:$password@/api/v1/checkouts/" . $issue2->issue_id . "/renewal" )->status_is(201) + ->json_is( '/due_date' => output_pref( { dateformat => "rfc3339", dt => $expected_datedue } ) ) + ->header_is( Location => "/api/v1/checkouts/" . $issue2->issue_id . "/renewal" ); +$t->post_ok( "//$userid:$password@/api/v1/checkouts/" . $issue1->issue_id . "/renewal" )->status_is(403) + ->json_is( { error => 'Renewal not authorized (too_many)' } ); -$t->post_ok( "//$userid:$password@/api/v1/checkouts/" . $issue1->issue_id . "/renewal" ) - ->status_is(403) - ->json_is({ error => 'Renewal not authorized (too_many)' }); - -$t->get_ok( "//$userid:$password@/api/v1/checkouts/" . $issue2->issue_id . "/allows_renewal") - ->status_is(200) - ->json_is({ +$t->get_ok( "//$userid:$password@/api/v1/checkouts/" . $issue2->issue_id . "/allows_renewal" )->status_is(200) + ->json_is( + { allows_renewal => Mojo::JSON->false, max_renewals => 1, unseen_renewals => 0, current_renewals => 1, error => 'too_many' - }); + } + ); $schema->storage->txn_rollback; diff --git a/t/db_dependent/api/v1/cities.t b/t/db_dependent/api/v1/cities.t index b381b93a9b..7791aefcb9 100755 --- a/t/db_dependent/api/v1/cities.t +++ b/t/db_dependent/api/v1/cities.t @@ -43,7 +43,7 @@ subtest 'list() tests' => sub { my $librarian = $builder->build_object( { class => 'Koha::Patrons', - value => { flags => 2 ** 2 } # catalogue flag = 2 + value => { flags => 2**2 } # catalogue flag = 2 } ); my $password = 'thePassword123'; @@ -62,48 +62,43 @@ subtest 'list() tests' => sub { ## Authorized user tests # No cities, so empty array should be returned - $t->get_ok("//$userid:$password@/api/v1/cities") - ->status_is(200) - ->json_is( [] ); + $t->get_ok("//$userid:$password@/api/v1/cities")->status_is(200)->json_is( [] ); - my $city = $builder->build_object({ class => 'Koha::Cities' }); + my $city = $builder->build_object( { class => 'Koha::Cities' } ); # One city created, should get returned - $t->get_ok("//$userid:$password@/api/v1/cities") - ->status_is(200) - ->json_is( [$city->to_api] ); + $t->get_ok("//$userid:$password@/api/v1/cities")->status_is(200)->json_is( [ $city->to_api ] ); - my $another_city = $builder->build_object( - { class => 'Koha::Cities', value => { city_country => $city->city_country } } ); - my $city_with_another_country = $builder->build_object({ class => 'Koha::Cities' }); + my $another_city = + $builder->build_object( { class => 'Koha::Cities', value => { city_country => $city->city_country } } ); + my $city_with_another_country = $builder->build_object( { class => 'Koha::Cities' } ); # Two cities created, they should both be returned - $t->get_ok("//$userid:$password@/api/v1/cities") - ->status_is(200) - ->json_is([$city->to_api, - $another_city->to_api, - $city_with_another_country->to_api - ] ); + $t->get_ok("//$userid:$password@/api/v1/cities")->status_is(200)->json_is( + [ + $city->to_api, + $another_city->to_api, + $city_with_another_country->to_api + ] + ); # Filtering works, two cities sharing city_country - $t->get_ok("//$userid:$password@/api/v1/cities?country=" . $city->city_country ) - ->status_is(200) - ->json_is([ $city->to_api, - $another_city->to_api - ]); + $t->get_ok( "//$userid:$password@/api/v1/cities?country=" . $city->city_country )->status_is(200)->json_is( + [ + $city->to_api, + $another_city->to_api + ] + ); - $t->get_ok("//$userid:$password@/api/v1/cities?name=" . $city->city_name ) - ->status_is(200) - ->json_is( [$city->to_api] ); + $t->get_ok( "//$userid:$password@/api/v1/cities?name=" . $city->city_name )->status_is(200) + ->json_is( [ $city->to_api ] ); # Warn on unsupported query parameter - $t->get_ok("//$userid:$password@/api/v1/cities?city_blah=blah" ) - ->status_is(400) - ->json_is( [{ path => '/query/city_blah', message => 'Malformed query string'}] ); + $t->get_ok("//$userid:$password@/api/v1/cities?city_blah=blah")->status_is(400) + ->json_is( [ { path => '/query/city_blah', message => 'Malformed query string' } ] ); # Unauthorized access - $t->get_ok("//$unauth_userid:$password@/api/v1/cities") - ->status_is(403); + $t->get_ok("//$unauth_userid:$password@/api/v1/cities")->status_is(403); $schema->storage->txn_rollback; }; @@ -114,7 +109,7 @@ subtest 'get() tests' => sub { $schema->storage->txn_begin; - my $city = $builder->build_object({ class => 'Koha::Cities' }); + my $city = $builder->build_object( { class => 'Koha::Cities' } ); my $librarian = $builder->build_object( { class => 'Koha::Patrons', @@ -135,20 +130,16 @@ subtest 'get() tests' => sub { $patron->set_password( { password => $password, skip_validation => 1 } ); my $unauth_userid = $patron->userid; - $t->get_ok( "//$userid:$password@/api/v1/cities/" . $city->cityid ) - ->status_is(200) - ->json_is($city->to_api); + $t->get_ok( "//$userid:$password@/api/v1/cities/" . $city->cityid )->status_is(200)->json_is( $city->to_api ); - $t->get_ok( "//$unauth_userid:$password@/api/v1/cities/" . $city->cityid ) - ->status_is(403); + $t->get_ok( "//$unauth_userid:$password@/api/v1/cities/" . $city->cityid )->status_is(403); - my $city_to_delete = $builder->build_object({ class => 'Koha::Cities' }); + my $city_to_delete = $builder->build_object( { class => 'Koha::Cities' } ); my $non_existent_id = $city_to_delete->id; $city_to_delete->delete; - $t->get_ok( "//$userid:$password@/api/v1/cities/$non_existent_id" ) - ->status_is(404) - ->json_is( '/error' => 'City not found' ); + $t->get_ok("//$userid:$password@/api/v1/cities/$non_existent_id")->status_is(404) + ->json_is( '/error' => 'City not found' ); $schema->storage->txn_rollback; }; @@ -187,8 +178,7 @@ subtest 'add() tests' => sub { }; # Unauthorized attempt to write - $t->post_ok("//$unauth_userid:$password@/api/v1/cities" => json => $city) - ->status_is(403); + $t->post_ok( "//$unauth_userid:$password@/api/v1/cities" => json => $city )->status_is(403); # Authorized attempt to write invalid data my $city_with_invalid_field = { @@ -198,42 +188,32 @@ subtest 'add() tests' => sub { country => "City Country" }; - $t->post_ok( "//$userid:$password@/api/v1/cities" => json => $city_with_invalid_field ) - ->status_is(400) - ->json_is( + $t->post_ok( "//$userid:$password@/api/v1/cities" => json => $city_with_invalid_field )->status_is(400)->json_is( "/errors" => [ { message => "Properties not allowed: blah.", path => "/body" } ] - ); + ); # Authorized attempt to write my $city_id = - $t->post_ok( "//$userid:$password@/api/v1/cities" => json => $city ) - ->status_is( 201, 'REST3.2.1' ) + $t->post_ok( "//$userid:$password@/api/v1/cities" => json => $city )->status_is( 201, 'REST3.2.1' ) ->header_like( - Location => qr|^\/api\/v1\/cities/\d*|, - 'REST3.4.1' - ) - ->json_is( '/name' => $city->{name} ) - ->json_is( '/state' => $city->{state} ) - ->json_is( '/postal_code' => $city->{postal_code} ) - ->json_is( '/country' => $city->{country} ) + Location => qr|^\/api\/v1\/cities/\d*|, + 'REST3.4.1' + )->json_is( '/name' => $city->{name} )->json_is( '/state' => $city->{state} ) + ->json_is( '/postal_code' => $city->{postal_code} )->json_is( '/country' => $city->{country} ) ->tx->res->json->{city_id}; # Authorized attempt to create with null id $city->{city_id} = undef; - $t->post_ok( "//$userid:$password@/api/v1/cities" => json => $city ) - ->status_is(400) - ->json_has('/errors'); + $t->post_ok( "//$userid:$password@/api/v1/cities" => json => $city )->status_is(400)->json_has('/errors'); # Authorized attempt to create with existing id $city->{city_id} = $city_id; - $t->post_ok( "//$userid:$password@/api/v1/cities" => json => $city ) - ->status_is(400) - ->json_is( + $t->post_ok( "//$userid:$password@/api/v1/cities" => json => $city )->status_is(400)->json_is( "/errors" => [ { message => "Read-only.", @@ -271,11 +251,12 @@ subtest 'update() tests' => sub { $patron->set_password( { password => $password, skip_validation => 1 } ); my $unauth_userid = $patron->userid; - my $city_id = $builder->build_object({ class => 'Koha::Cities' } )->id; + my $city_id = $builder->build_object( { class => 'Koha::Cities' } )->id; # Unauthorized attempt to update - $t->put_ok( "//$unauth_userid:$password@/api/v1/cities/$city_id" => json => { name => 'New unauthorized name change' } ) - ->status_is(403); + $t->put_ok( + "//$unauth_userid:$password@/api/v1/cities/$city_id" => json => { name => 'New unauthorized name change' } ) + ->status_is(403); # Attempt partial update on a PUT my $city_with_missing_field = { @@ -284,11 +265,8 @@ subtest 'update() tests' => sub { country => 'New country' }; - $t->put_ok( "//$userid:$password@/api/v1/cities/$city_id" => json => $city_with_missing_field ) - ->status_is(400) - ->json_is( "/errors" => - [ { message => "Missing property.", path => "/body/postal_code" } ] - ); + $t->put_ok( "//$userid:$password@/api/v1/cities/$city_id" => json => $city_with_missing_field )->status_is(400) + ->json_is( "/errors" => [ { message => "Missing property.", path => "/body/postal_code" } ] ); # Full object update on PUT my $city_with_updated_field = { @@ -298,9 +276,8 @@ subtest 'update() tests' => sub { country => "City Country" }; - $t->put_ok( "//$userid:$password@/api/v1/cities/$city_id" => json => $city_with_updated_field ) - ->status_is(200) - ->json_is( '/name' => 'London' ); + $t->put_ok( "//$userid:$password@/api/v1/cities/$city_id" => json => $city_with_updated_field )->status_is(200) + ->json_is( '/name' => 'London' ); # Authorized attempt to write invalid data my $city_with_invalid_field = { @@ -310,29 +287,27 @@ subtest 'update() tests' => sub { country => "City Country" }; - $t->put_ok( "//$userid:$password@/api/v1/cities/$city_id" => json => $city_with_invalid_field ) - ->status_is(400) - ->json_is( + $t->put_ok( "//$userid:$password@/api/v1/cities/$city_id" => json => $city_with_invalid_field )->status_is(400) + ->json_is( "/errors" => [ { message => "Properties not allowed: blah.", path => "/body" } ] - ); + ); - my $city_to_delete = $builder->build_object({ class => 'Koha::Cities' }); + my $city_to_delete = $builder->build_object( { class => 'Koha::Cities' } ); my $non_existent_id = $city_to_delete->id; $city_to_delete->delete; $t->put_ok( "//$userid:$password@/api/v1/cities/$non_existent_id" => json => $city_with_updated_field ) - ->status_is(404); + ->status_is(404); # Wrong method (POST) $city_with_updated_field->{city_id} = 2; - $t->post_ok( "//$userid:$password@/api/v1/cities/$city_id" => json => $city_with_updated_field ) - ->status_is(404); + $t->post_ok( "//$userid:$password@/api/v1/cities/$city_id" => json => $city_with_updated_field )->status_is(404); $schema->storage->txn_rollback; }; @@ -363,18 +338,15 @@ subtest 'delete() tests' => sub { $patron->set_password( { password => $password, skip_validation => 1 } ); my $unauth_userid = $patron->userid; - my $city_id = $builder->build_object({ class => 'Koha::Cities' })->id; + my $city_id = $builder->build_object( { class => 'Koha::Cities' } )->id; # Unauthorized attempt to delete - $t->delete_ok( "//$unauth_userid:$password@/api/v1/cities/$city_id" ) - ->status_is(403); + $t->delete_ok("//$unauth_userid:$password@/api/v1/cities/$city_id")->status_is(403); - $t->delete_ok("//$userid:$password@/api/v1/cities/$city_id") - ->status_is(204, 'REST3.2.4') - ->content_is('', 'REST3.3.4'); + $t->delete_ok("//$userid:$password@/api/v1/cities/$city_id")->status_is( 204, 'REST3.2.4' ) + ->content_is( '', 'REST3.3.4' ); - $t->delete_ok("//$userid:$password@/api/v1/cities/$city_id") - ->status_is(404); + $t->delete_ok("//$userid:$password@/api/v1/cities/$city_id")->status_is(404); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/api/v1/clubs_holds.t b/t/db_dependent/api/v1/clubs_holds.t index e7de87b838..7684c5d2bb 100755 --- a/t/db_dependent/api/v1/clubs_holds.t +++ b/t/db_dependent/api/v1/clubs_holds.t @@ -1,6 +1,5 @@ #!/usr/bin/env perl - # This file is part of Koha. # # Koha is free software; you can redistribute it and/or modify it @@ -34,7 +33,7 @@ use JSON qw( decode_json ); my $schema = Koha::Database->new->schema; my $builder = t::lib::TestBuilder->new; -my $dbh = C4::Context->dbh; +my $dbh = C4::Context->dbh; my $t = Test::Mojo->new('Koha::REST::V1'); t::lib::Mocks::mock_preference( 'RESTBasicAuth', 1 ); @@ -45,7 +44,7 @@ subtest 'add() tests' => sub { $schema->storage->txn_begin; - my ($club_with_enrollments, $club_without_enrollments, $item, @enrollments) = create_test_data(); + my ( $club_with_enrollments, $club_without_enrollments, $item, @enrollments ) = create_test_data(); unauthorized_access_tests( 'POST', @@ -65,13 +64,13 @@ subtest 'add() tests' => sub { $schema->storage->txn_begin; - my ($club_with_enrollments, $club_without_enrollments, $item, @enrollments) = create_test_data(); + my ( $club_with_enrollments, $club_without_enrollments, $item, @enrollments ) = create_test_data(); my $club_with_enrollments_id = $club_with_enrollments->id; my $librarian = $builder->build_object( { class => 'Koha::Patrons', - value => { flags => 2 ** 6 } # reserveforothers flag = 6 + value => { flags => 2**6 } # reserveforothers flag = 6 } ); my $password = 'thePassword123'; @@ -81,10 +80,9 @@ subtest 'add() tests' => sub { my $non_existent_item = $builder->build_sample_item; my $non_existent_biblio = $non_existent_item->biblio; - my $non_existent_item_id = $non_existent_item->id; - my $non_existent_biblio_id = $non_existent_biblio->id; - my $non_existent_item_homebranch = - $non_existent_item->home_branch->branchcode; + my $non_existent_item_id = $non_existent_item->id; + my $non_existent_biblio_id = $non_existent_biblio->id; + my $non_existent_item_homebranch = $non_existent_item->home_branch->branchcode; $non_existent_item->delete; $non_existent_biblio->delete; @@ -92,45 +90,30 @@ subtest 'add() tests' => sub { my $biblio = $builder->build_sample_biblio; $t->post_ok( - "//$userid:$password@/api/v1/clubs/" - . $club_with_enrollments->id - . "/holds" => json => { + "//$userid:$password@/api/v1/clubs/" . $club_with_enrollments->id . "/holds" => json => { biblio_id => $biblio->id, item_id => $item->id, pickup_library_id => $item->home_branch->branchcode - } - )->status_is(400) - ->json_is( '/error' => "Item " - . $item->id - . " doesn't belong to biblio " - . $biblio->id ); + } + )->status_is(400)->json_is( '/error' => "Item " . $item->id . " doesn't belong to biblio " . $biblio->id ); + + $t->post_ok( "//$userid:$password@/api/v1/clubs/" + . $club_with_enrollments->id + . "/holds" => json => { pickup_library_id => $non_existent_item_homebranch } )->status_is(400) + ->json_is( '/error' => 'At least one of biblio_id, item_id should be given' ); $t->post_ok( - "//$userid:$password@/api/v1/clubs/" - . $club_with_enrollments->id - . "/holds" => json => { - pickup_library_id => $non_existent_item_homebranch - } - )->status_is(400) - ->json_is( - '/error' => 'At least one of biblio_id, item_id should be given' ); - - $t->post_ok( - "//$userid:$password@/api/v1/clubs/" - . $club_with_enrollments->id - . "/holds" => json => { + "//$userid:$password@/api/v1/clubs/" . $club_with_enrollments->id . "/holds" => json => { biblio_id => $non_existent_biblio_id, pickup_library_id => $non_existent_item_homebranch - } + } )->status_is(404)->json_is( '/error' => 'Bibliographic record not found' ); $t->post_ok( - "//$userid:$password@/api/v1/clubs/" - . $club_with_enrollments->id - . "/holds" => json => { + "//$userid:$password@/api/v1/clubs/" . $club_with_enrollments->id . "/holds" => json => { item_id => $non_existent_item_id, pickup_library_id => $non_existent_item_homebranch - } + } )->status_is(404)->json_is( '/error' => 'Item not found' ); my $data = { @@ -138,17 +121,12 @@ subtest 'add() tests' => sub { pickup_library_id => $item->home_branch->branchcode }; - $t->post_ok( "//$userid:$password@/api/v1/clubs/" - . $club_without_enrollments->id - . "/holds" => json => $data ) - ->status_is(409) - ->json_is( '/error' => "Cannot place a hold on a club without patrons." ); + $t->post_ok( "//$userid:$password@/api/v1/clubs/" . $club_without_enrollments->id . "/holds" => json => $data ) + ->status_is(409)->json_is( '/error' => "Cannot place a hold on a club without patrons." ); $t->post_ok( "//$userid:$password@/api/v1/clubs/" . $club_with_enrollments->id . "/holds" => json => $data ) - ->status_is( 201, 'Created Hold' ) - ->json_has( '/club_hold_id', 'got a club hold id' ) - ->json_is( '/club_id' => $club_with_enrollments->id ) - ->json_is( '/biblio_id' => $item->biblionumber ) + ->status_is( 201, 'Created Hold' )->json_has( '/club_hold_id', 'got a club hold id' ) + ->json_is( '/club_id' => $club_with_enrollments->id )->json_is( '/biblio_id' => $item->biblionumber ) ->header_is( 'Location' => '/api/v1/clubs/' . $club_with_enrollments->id . '/holds/' . $t->tx->res->json->{club_hold_id}, 'REST3.4.1' @@ -164,7 +142,7 @@ subtest "default patron home" => sub { $schema->storage->txn_begin; - my ($club_with_enrollments, $club_without_enrollments, $item, @enrollments) = create_test_data(); + my ( $club_with_enrollments, $club_without_enrollments, $item, @enrollments ) = create_test_data(); my $club_with_enrollments_id = $club_with_enrollments->id; my $librarian = $builder->build_object( @@ -183,27 +161,23 @@ subtest "default patron home" => sub { default_patron_home => 1 }; - $t->post_ok( "//$userid:$password@/api/v1/clubs/" - . $club_with_enrollments->id - . "/holds" => json => $data ) - ->status_is( 201, 'Created Hold' ); + $t->post_ok( "//$userid:$password@/api/v1/clubs/" . $club_with_enrollments->id . "/holds" => json => $data ) + ->status_is( 201, 'Created Hold' ); my $json_response = decode_json $t->tx->res->content->get_body_chunk; - my $sth = $dbh->prepare( - "select patron_id, hold_id from club_holds_to_patron_holds where club_hold_id = ?" - ); - $sth->execute($json_response->{club_hold_id}); - while (my $test = $sth->fetchrow_hashref()) { - my $hold = Koha::Holds->find($test->{hold_id}); - my $patron = Koha::Patrons->find($test->{patron_id}); - is($hold->branchcode, $patron->branchcode, 'Pickup location should be patrons home branch'); + my $sth = $dbh->prepare("select patron_id, hold_id from club_holds_to_patron_holds where club_hold_id = ?"); + $sth->execute( $json_response->{club_hold_id} ); + while ( my $test = $sth->fetchrow_hashref() ) { + my $hold = Koha::Holds->find( $test->{hold_id} ); + my $patron = Koha::Patrons->find( $test->{patron_id} ); + is( $hold->branchcode, $patron->branchcode, 'Pickup location should be patrons home branch' ); } $schema->storage->txn_rollback; }; sub unauthorized_access_tests { - my ($verb, $endpoint, $club_hold_id, $json) = @_; + my ( $verb, $endpoint, $club_hold_id, $json ) = @_; $endpoint .= ($club_hold_id) ? "/$club_hold_id" : ''; @@ -212,8 +186,7 @@ sub unauthorized_access_tests { my $verb_ok = lc($verb) . '_ok'; - $t->$verb_ok($endpoint => json => $json) - ->status_is(401); + $t->$verb_ok( $endpoint => json => $json )->status_is(401); my $unauthorized_patron = $builder->build_object( { @@ -222,38 +195,87 @@ sub unauthorized_access_tests { } ); my $password = "thePassword123!"; - $unauthorized_patron->set_password( - { password => $password, skip_validation => 1 } ); + $unauthorized_patron->set_password( { password => $password, skip_validation => 1 } ); my $unauth_userid = $unauthorized_patron->userid; - $t->$verb_ok( "//$unauth_userid:$password\@$endpoint" => json => $json ) - ->status_is(403) - ->json_has('/required_permissions'); + $t->$verb_ok( "//$unauth_userid:$password\@$endpoint" => json => $json )->status_is(403) + ->json_has('/required_permissions'); }; } sub create_test_data { - my $club_with_enrollments = $builder->build_object( { class => 'Koha::Clubs' } ); + my $club_with_enrollments = $builder->build_object( { class => 'Koha::Clubs' } ); my $club_without_enrollments = $builder->build_object( { class => 'Koha::Clubs' } ); - my $lib = $builder->build_object({ class => 'Koha::Libraries', value => {pickup_location => 1}}); - my $patron = $builder->build_object({ class => 'Koha::Patrons', value => {branchcode => $lib->branchcode}}); - my $enrollment1 = $builder->build_object( { class => 'Koha::Club::Enrollments', value => { club_id => $club_with_enrollments->id, date_canceled => undef, borrowernumber => $patron->borrowernumber } } ); - $lib = $builder->build_object({ class => 'Koha::Libraries', value => {pickup_location => 1}}); - $patron = $builder->build_object({ class => 'Koha::Patrons', value => {branchcode => $lib->branchcode}}); - my $enrollment2 = $builder->build_object( { class => 'Koha::Club::Enrollments', value => { club_id => $club_with_enrollments->id, date_canceled => undef, borrowernumber => $patron->borrowernumber } } ); - $lib = $builder->build_object({ class => 'Koha::Libraries', value => {pickup_location => 1}}); - $patron = $builder->build_object({ class => 'Koha::Patrons', value => {branchcode => $lib->branchcode}}); - my $enrollment3 = $builder->build_object( { class => 'Koha::Club::Enrollments', value => { club_id => $club_with_enrollments->id, date_canceled => undef, borrowernumber => $patron->borrowernumber } } ); - $lib = $builder->build_object({ class => 'Koha::Libraries', value => {pickup_location => 1}}); - $patron = $builder->build_object({ class => 'Koha::Patrons', value => {branchcode => $lib->branchcode}}); - my $enrollment4 = $builder->build_object( { class => 'Koha::Club::Enrollments', value => { club_id => $club_with_enrollments->id, date_canceled => undef, borrowernumber => $patron->borrowernumber } } ); - $lib = $builder->build_object({ class => 'Koha::Libraries', value => {pickup_location => 1}}); - $patron = $builder->build_object({ class => 'Koha::Patrons', value => {branchcode => $lib->branchcode}}); - my $enrollment5 = $builder->build_object( { class => 'Koha::Club::Enrollments', value => { club_id => $club_with_enrollments->id, date_canceled => undef, borrowernumber => $patron->borrowernumber } } ); - $lib = $builder->build_object({ class => 'Koha::Libraries', value => {pickup_location => 1}}); - $patron = $builder->build_object({ class => 'Koha::Patrons', value => {branchcode => $lib->branchcode}}); - my $enrollment6 = $builder->build_object( { class => 'Koha::Club::Enrollments', value => { club_id => $club_with_enrollments->id, date_canceled => undef, borrowernumber => $patron->borrowernumber } } ); - $lib = $builder->build_object({ class => 'Koha::Libraries', value => {pickup_location => 1}}); - my $item = $builder->build_sample_item({homebranch => $lib->branchcode}); - return ( $club_with_enrollments, $club_without_enrollments, $item, [ $enrollment1, $enrollment2, $enrollment3, $enrollment4, $enrollment5, $enrollment6 ] ); + my $lib = $builder->build_object( { class => 'Koha::Libraries', value => { pickup_location => 1 } } ); + my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { branchcode => $lib->branchcode } } ); + my $enrollment1 = $builder->build_object( + { + class => 'Koha::Club::Enrollments', + value => { + club_id => $club_with_enrollments->id, date_canceled => undef, + borrowernumber => $patron->borrowernumber + } + } + ); + $lib = $builder->build_object( { class => 'Koha::Libraries', value => { pickup_location => 1 } } ); + $patron = $builder->build_object( { class => 'Koha::Patrons', value => { branchcode => $lib->branchcode } } ); + my $enrollment2 = $builder->build_object( + { + class => 'Koha::Club::Enrollments', + value => { + club_id => $club_with_enrollments->id, date_canceled => undef, + borrowernumber => $patron->borrowernumber + } + } + ); + $lib = $builder->build_object( { class => 'Koha::Libraries', value => { pickup_location => 1 } } ); + $patron = $builder->build_object( { class => 'Koha::Patrons', value => { branchcode => $lib->branchcode } } ); + my $enrollment3 = $builder->build_object( + { + class => 'Koha::Club::Enrollments', + value => { + club_id => $club_with_enrollments->id, date_canceled => undef, + borrowernumber => $patron->borrowernumber + } + } + ); + $lib = $builder->build_object( { class => 'Koha::Libraries', value => { pickup_location => 1 } } ); + $patron = $builder->build_object( { class => 'Koha::Patrons', value => { branchcode => $lib->branchcode } } ); + my $enrollment4 = $builder->build_object( + { + class => 'Koha::Club::Enrollments', + value => { + club_id => $club_with_enrollments->id, date_canceled => undef, + borrowernumber => $patron->borrowernumber + } + } + ); + $lib = $builder->build_object( { class => 'Koha::Libraries', value => { pickup_location => 1 } } ); + $patron = $builder->build_object( { class => 'Koha::Patrons', value => { branchcode => $lib->branchcode } } ); + my $enrollment5 = $builder->build_object( + { + class => 'Koha::Club::Enrollments', + value => { + club_id => $club_with_enrollments->id, date_canceled => undef, + borrowernumber => $patron->borrowernumber + } + } + ); + $lib = $builder->build_object( { class => 'Koha::Libraries', value => { pickup_location => 1 } } ); + $patron = $builder->build_object( { class => 'Koha::Patrons', value => { branchcode => $lib->branchcode } } ); + my $enrollment6 = $builder->build_object( + { + class => 'Koha::Club::Enrollments', + value => { + club_id => $club_with_enrollments->id, date_canceled => undef, + borrowernumber => $patron->borrowernumber + } + } + ); + $lib = $builder->build_object( { class => 'Koha::Libraries', value => { pickup_location => 1 } } ); + my $item = $builder->build_sample_item( { homebranch => $lib->branchcode } ); + return ( + $club_with_enrollments, $club_without_enrollments, $item, + [ $enrollment1, $enrollment2, $enrollment3, $enrollment4, $enrollment5, $enrollment6 ] + ); } diff --git a/t/db_dependent/api/v1/erm_agreements.t b/t/db_dependent/api/v1/erm_agreements.t index b965d88821..b0f8705c16 100755 --- a/t/db_dependent/api/v1/erm_agreements.t +++ b/t/db_dependent/api/v1/erm_agreements.t @@ -62,10 +62,9 @@ subtest 'list() tests' => sub { ## Authorized user tests # No agreements, so empty array should be returned - $t->get_ok("//$userid:$password@/api/v1/erm/agreements")->status_is(200) - ->json_is( [] ); + $t->get_ok("//$userid:$password@/api/v1/erm/agreements")->status_is(200)->json_is( [] ); - my $vendor_1 = $builder->build_object({ class => 'Koha::Acquisition::Booksellers' }); + my $vendor_1 = $builder->build_object( { class => 'Koha::Acquisition::Booksellers' } ); my $agreement = $builder->build_object( { class => 'Koha::ERM::Agreements', @@ -74,8 +73,7 @@ subtest 'list() tests' => sub { ); # One agreement created, should get returned - $t->get_ok("//$userid:$password@/api/v1/erm/agreements")->status_is(200) - ->json_is( [ $agreement->to_api ] ); + $t->get_ok("//$userid:$password@/api/v1/erm/agreements")->status_is(200)->json_is( [ $agreement->to_api ] ); my $another_agreement = $builder->build_object( { @@ -84,7 +82,7 @@ subtest 'list() tests' => sub { } ); - my $vendor_2 = $builder->build_object({ class => 'Koha::Acquisition::Booksellers' }); + my $vendor_2 = $builder->build_object( { class => 'Koha::Acquisition::Booksellers' } ); my $agreement_with_another_vendor_id = $builder->build_object( { class => 'Koha::ERM::Agreements', @@ -93,27 +91,24 @@ subtest 'list() tests' => sub { ); # Two agreements created, they should both be returned - $t->get_ok("//$userid:$password@/api/v1/erm/agreements")->status_is(200) - ->json_is( + $t->get_ok("//$userid:$password@/api/v1/erm/agreements")->status_is(200)->json_is( [ $agreement->to_api, $another_agreement->to_api, $agreement_with_another_vendor_id->to_api ] - ); + ); # Filtering works, two agreements sharing vendor_id - $t->get_ok( "//$userid:$password@/api/v1/erm/agreements?vendor_id=" - . $vendor_1->id )->status_is(200) - ->json_is( [ $agreement->to_api, $another_agreement->to_api ] ); + $t->get_ok( "//$userid:$password@/api/v1/erm/agreements?vendor_id=" . $vendor_1->id )->status_is(200) + ->json_is( [ $agreement->to_api, $another_agreement->to_api ] ); # Attempt to search by name like 'ko' $agreement->delete; $another_agreement->delete; $agreement_with_another_vendor_id->delete; - $t->get_ok( qq~//$userid:$password@/api/v1/erm/agreements?q=[{"me.name":{"like":"%ko%"}}]~) - ->status_is(200) - ->json_is( [] ); + $t->get_ok(qq~//$userid:$password@/api/v1/erm/agreements?q=[{"me.name":{"like":"%ko%"}}]~)->status_is(200) + ->json_is( [] ); my $agreement_to_search = $builder->build_object( { @@ -125,54 +120,43 @@ subtest 'list() tests' => sub { ); # Search works, searching for name like 'ko' - $t->get_ok( qq~//$userid:$password@/api/v1/erm/agreements?q=[{"me.name":{"like":"%ko%"}}]~) - ->status_is(200) - ->json_is( [ $agreement_to_search->to_api ] ); + $t->get_ok(qq~//$userid:$password@/api/v1/erm/agreements?q=[{"me.name":{"like":"%ko%"}}]~)->status_is(200) + ->json_is( [ $agreement_to_search->to_api ] ); # Warn on incorrect filter date format - $t->get_ok( "//$userid:$password@/api/v1/erm/agreements?max_expiration_date=19-03-2021") - ->status_is(400) - ->json_is( - "/errors" => [ - { - message => "Does not match date format.", - path => "/max_expiration_date" - } - ] - ); - - # Attempt to filter by expired on 2021-03-19 - $t->get_ok( "//$userid:$password@/api/v1/erm/agreements?max_expiration_date=2021-03-19") - ->status_is(200) - ->json_is( [] ); - - my $agreement_to_filter = $builder->build_object( - { - class => 'Koha::ERM::Agreements' - } - ); - $agreement_to_filter->periods( - [ + $t->get_ok("//$userid:$password@/api/v1/erm/agreements?max_expiration_date=19-03-2021")->status_is(400)->json_is( + "/errors" => [ { - 'started_on'=>'2021-03-17', - 'ended_on'=>'2021-03-19' + message => "Does not match date format.", + path => "/max_expiration_date" } ] ); + + # Attempt to filter by expired on 2021-03-19 + $t->get_ok("//$userid:$password@/api/v1/erm/agreements?max_expiration_date=2021-03-19")->status_is(200) + ->json_is( [] ); + + my $agreement_to_filter = $builder->build_object( { class => 'Koha::ERM::Agreements' } ); + $agreement_to_filter->periods( + [ + { + 'started_on' => '2021-03-17', + 'ended_on' => '2021-03-19' + } + ] + ); + # Filter by expired on 2021-03-19 - $t->get_ok( "//$userid:$password@/api/v1/erm/agreements?max_expiration_date=2021-03-19") - ->status_is(200) - ->json_is( [ $agreement_to_filter->to_api ] ); + $t->get_ok("//$userid:$password@/api/v1/erm/agreements?max_expiration_date=2021-03-19")->status_is(200) + ->json_is( [ $agreement_to_filter->to_api ] ); # Warn on unsupported query parameter - $t->get_ok("//$userid:$password@/api/v1/erm/agreements?blah=blah") - ->status_is(400) - ->json_is( - [ { path => '/query/blah', message => 'Malformed query string' } ] ); + $t->get_ok("//$userid:$password@/api/v1/erm/agreements?blah=blah")->status_is(400) + ->json_is( [ { path => '/query/blah', message => 'Malformed query string' } ] ); # Unauthorized access - $t->get_ok("//$unauth_userid:$password@/api/v1/erm/agreements") - ->status_is(403); + $t->get_ok("//$unauth_userid:$password@/api/v1/erm/agreements")->status_is(403); $schema->storage->txn_rollback; }; @@ -183,8 +167,7 @@ subtest 'get() tests' => sub { $schema->storage->txn_begin; - my $agreement = - $builder->build_object( { class => 'Koha::ERM::Agreements' } ); + my $agreement = $builder->build_object( { class => 'Koha::ERM::Agreements' } ); my $librarian = $builder->build_object( { class => 'Koha::Patrons', @@ -206,32 +189,32 @@ subtest 'get() tests' => sub { my $unauth_userid = $patron->userid; # This agreement exists, should get returned - $t->get_ok( "//$userid:$password@/api/v1/erm/agreements/" - . $agreement->agreement_id )->status_is(200) - ->json_is( $agreement->to_api ); + $t->get_ok( "//$userid:$password@/api/v1/erm/agreements/" . $agreement->agreement_id )->status_is(200) + ->json_is( $agreement->to_api ); # Return one agreement with some embeds $t->get_ok( "//$userid:$password@/api/v1/erm/agreements/" - . $agreement->agreement_id => {'x-koha-embed' => 'periods,user_roles,agreement_licenses'} )->status_is(200) - ->json_is( { %{ $agreement->to_api }, periods => [], user_roles => [], agreement_licenses => [] }); + . $agreement->agreement_id => { 'x-koha-embed' => 'periods,user_roles,agreement_licenses' } ) + ->status_is(200) + ->json_is( { %{ $agreement->to_api }, periods => [], user_roles => [], agreement_licenses => [] } ); # Return one agreement with all embeds $t->get_ok( "//$userid:$password@/api/v1/erm/agreements/" - . $agreement->agreement_id => {'x-koha-embed' => 'periods,user_roles,user_roles.patron,agreement_licenses,agreement_licenses.license'} )->status_is(200) - ->json_is( { %{ $agreement->to_api }, periods => [], user_roles => [], agreement_licenses => [] }); + . $agreement->agreement_id => + { 'x-koha-embed' => 'periods,user_roles,user_roles.patron,agreement_licenses,agreement_licenses.license' } ) + ->status_is(200) + ->json_is( { %{ $agreement->to_api }, periods => [], user_roles => [], agreement_licenses => [] } ); # Unauthorized access - $t->get_ok( "//$unauth_userid:$password@/api/v1/erm/agreements/" - . $agreement->agreement_id )->status_is(403); + $t->get_ok( "//$unauth_userid:$password@/api/v1/erm/agreements/" . $agreement->agreement_id )->status_is(403); # Attempt to get non-existent agreement - my $agreement_to_delete = - $builder->build_object( { class => 'Koha::ERM::Agreements' } ); - my $non_existent_id = $agreement_to_delete->agreement_id; + my $agreement_to_delete = $builder->build_object( { class => 'Koha::ERM::Agreements' } ); + my $non_existent_id = $agreement_to_delete->agreement_id; $agreement_to_delete->delete; - $t->get_ok("//$userid:$password@/api/v1/erm/agreements/$non_existent_id") - ->status_is(404)->json_is( '/error' => 'Agreement not found' ); + $t->get_ok("//$userid:$password@/api/v1/erm/agreements/$non_existent_id")->status_is(404) + ->json_is( '/error' => 'Agreement not found' ); $schema->storage->txn_rollback; }; @@ -263,7 +246,7 @@ subtest 'add() tests' => sub { my $unauth_userid = $patron->userid; my $agreement = { - vendor_id => undef, + vendor_id => undef, name => "Agreement name", description => "Agreement description", status => "active", @@ -274,8 +257,7 @@ subtest 'add() tests' => sub { }; # Unauthorized attempt to write - $t->post_ok( "//$unauth_userid:$password@/api/v1/erm/agreements" => json => - $agreement )->status_is(403); + $t->post_ok( "//$unauth_userid:$password@/api/v1/erm/agreements" => json => $agreement )->status_is(403); # Authorized attempt to write invalid data my $agreement_with_invalid_field = { @@ -289,51 +271,44 @@ subtest 'add() tests' => sub { license_info => "Agreement license_info", }; - $t->post_ok( "//$userid:$password@/api/v1/erm/agreements" => json => - $agreement_with_invalid_field )->status_is(400)->json_is( + $t->post_ok( "//$userid:$password@/api/v1/erm/agreements" => json => $agreement_with_invalid_field ) + ->status_is(400)->json_is( "/errors" => [ { message => "Properties not allowed: blah.", path => "/body" } ] - ); + ); # Authorized attempt to write my $agreement_id = - $t->post_ok( - "//$userid:$password@/api/v1/erm/agreements" => json => $agreement ) - ->status_is( 201, 'REST3.2.1' )->header_like( + $t->post_ok( "//$userid:$password@/api/v1/erm/agreements" => json => $agreement ) + ->status_is( 201, 'REST3.2.1' )->header_like( Location => qr|^/api/v1/erm/agreements/\d*|, 'REST3.4.1' - )->json_is( '/vendor_id' => $agreement->{vendor_id} ) - ->json_is( '/name' => $agreement->{name} ) - ->json_is( '/description' => $agreement->{description} ) - ->json_is( '/status' => $agreement->{status} ) - ->json_is( '/closure_reason' => $agreement->{closure_reason} ) - ->json_is( '/is_perpetual' => $agreement->{is_perpetual} ) - ->json_is( '/renewal_priority' => $agreement->{renewal_priority} ) - ->json_is( '/license_info' => $agreement->{license_info} ) - ->tx->res->json->{agreement_id}; + )->json_is( '/vendor_id' => $agreement->{vendor_id} )->json_is( '/name' => $agreement->{name} ) + ->json_is( '/description' => $agreement->{description} )->json_is( '/status' => $agreement->{status} ) + ->json_is( '/closure_reason' => $agreement->{closure_reason} ) + ->json_is( '/is_perpetual' => $agreement->{is_perpetual} ) + ->json_is( '/renewal_priority' => $agreement->{renewal_priority} ) + ->json_is( '/license_info' => $agreement->{license_info} )->tx->res->json->{agreement_id}; # Authorized attempt to create with null id $agreement->{agreement_id} = undef; - $t->post_ok( - "//$userid:$password@/api/v1/erm/agreements" => json => $agreement ) - ->status_is(400)->json_has('/errors'); + $t->post_ok( "//$userid:$password@/api/v1/erm/agreements" => json => $agreement )->status_is(400) + ->json_has('/errors'); # Authorized attempt to create with existing id $agreement->{agreement_id} = $agreement_id; - $t->post_ok( - "//$userid:$password@/api/v1/erm/agreements" => json => $agreement ) - ->status_is(400)->json_is( + $t->post_ok( "//$userid:$password@/api/v1/erm/agreements" => json => $agreement )->status_is(400)->json_is( "/errors" => [ { message => "Read-only.", path => "/body/agreement_id" } ] - ); + ); $schema->storage->txn_rollback; }; @@ -364,13 +339,11 @@ subtest 'update() tests' => sub { $patron->set_password( { password => $password, skip_validation => 1 } ); my $unauth_userid = $patron->userid; - my $agreement_id = - $builder->build_object( { class => 'Koha::ERM::Agreements' } )->agreement_id; + my $agreement_id = $builder->build_object( { class => 'Koha::ERM::Agreements' } )->agreement_id; # Unauthorized attempt to update - $t->put_ok( - "//$unauth_userid:$password@/api/v1/erm/agreements/$agreement_id" => - json => { name => 'New unauthorized name change' } )->status_is(403); + $t->put_ok( "//$unauth_userid:$password@/api/v1/erm/agreements/$agreement_id" => json => + { name => 'New unauthorized name change' } )->status_is(403); # Attempt partial update on a PUT my $agreement_with_missing_field = { @@ -382,11 +355,8 @@ subtest 'update() tests' => sub { license_info => 'New license_info', }; - $t->put_ok( - "//$userid:$password@/api/v1/erm/agreements/$agreement_id" => json => - $agreement_with_missing_field )->status_is(400) - ->json_is( "/errors" => - [ { message => "Missing property.", path => "/body/name" } ] ); + $t->put_ok( "//$userid:$password@/api/v1/erm/agreements/$agreement_id" => json => $agreement_with_missing_field ) + ->status_is(400)->json_is( "/errors" => [ { message => "Missing property.", path => "/body/name" } ] ); # Full object update on PUT my $agreement_with_updated_field = { @@ -400,10 +370,8 @@ subtest 'update() tests' => sub { license_info => 'New license_info', }; - $t->put_ok( - "//$userid:$password@/api/v1/erm/agreements/$agreement_id" => json => - $agreement_with_updated_field )->status_is(200) - ->json_is( '/name' => 'New name' ); + $t->put_ok( "//$userid:$password@/api/v1/erm/agreements/$agreement_id" => json => $agreement_with_updated_field ) + ->status_is(200)->json_is( '/name' => 'New name' ); # Authorized attempt to write invalid data my $agreement_with_invalid_field = { @@ -417,32 +385,29 @@ subtest 'update() tests' => sub { license_info => "Agreement license_info", }; - $t->put_ok( - "//$userid:$password@/api/v1/erm/agreements/$agreement_id" => json => - $agreement_with_invalid_field )->status_is(400)->json_is( + $t->put_ok( "//$userid:$password@/api/v1/erm/agreements/$agreement_id" => json => $agreement_with_invalid_field ) + ->status_is(400)->json_is( "/errors" => [ { message => "Properties not allowed: blah.", path => "/body" } ] - ); + ); # Attempt to update non-existent agreement - my $agreement_to_delete = - $builder->build_object( { class => 'Koha::ERM::Agreements' } ); - my $non_existent_id = $agreement_to_delete->agreement_id; + my $agreement_to_delete = $builder->build_object( { class => 'Koha::ERM::Agreements' } ); + my $non_existent_id = $agreement_to_delete->agreement_id; $agreement_to_delete->delete; - $t->put_ok( "//$userid:$password@/api/v1/erm/agreements/$non_existent_id" => - json => $agreement_with_updated_field )->status_is(404); + $t->put_ok( "//$userid:$password@/api/v1/erm/agreements/$non_existent_id" => json => $agreement_with_updated_field ) + ->status_is(404); # Wrong method (POST) $agreement_with_updated_field->{agreement_id} = 2; - $t->post_ok( - "//$userid:$password@/api/v1/erm/agreements/$agreement_id" => json => - $agreement_with_updated_field )->status_is(404); + $t->post_ok( "//$userid:$password@/api/v1/erm/agreements/$agreement_id" => json => $agreement_with_updated_field ) + ->status_is(404); $schema->storage->txn_rollback; }; @@ -473,21 +438,17 @@ subtest 'delete() tests' => sub { $patron->set_password( { password => $password, skip_validation => 1 } ); my $unauth_userid = $patron->userid; - my $agreement_id = - $builder->build_object( { class => 'Koha::ERM::Agreements' } )->agreement_id; + my $agreement_id = $builder->build_object( { class => 'Koha::ERM::Agreements' } )->agreement_id; # Unauthorized attempt to delete - $t->delete_ok( - "//$unauth_userid:$password@/api/v1/erm/agreements/$agreement_id") - ->status_is(403); + $t->delete_ok("//$unauth_userid:$password@/api/v1/erm/agreements/$agreement_id")->status_is(403); # Delete existing agreement - $t->delete_ok("//$userid:$password@/api/v1/erm/agreements/$agreement_id") - ->status_is( 204, 'REST3.2.4' )->content_is( '', 'REST3.3.4' ); + $t->delete_ok("//$userid:$password@/api/v1/erm/agreements/$agreement_id")->status_is( 204, 'REST3.2.4' ) + ->content_is( '', 'REST3.3.4' ); # Attempt to delete non-existent agreement - $t->delete_ok("//$userid:$password@/api/v1/erm/agreements/$agreement_id") - ->status_is(404); + $t->delete_ok("//$userid:$password@/api/v1/erm/agreements/$agreement_id")->status_is(404); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/api/v1/erm_custom_reports.t b/t/db_dependent/api/v1/erm_custom_reports.t index fcb7eba1b0..18f400a1ef 100755 --- a/t/db_dependent/api/v1/erm_custom_reports.t +++ b/t/db_dependent/api/v1/erm_custom_reports.t @@ -30,7 +30,7 @@ use Koha::ERM::EUsage::SushiCounter; use Koha::ERM::EUsage::MonthlyUsages; use Koha::ERM::EUsage::YearlyUsages; -use JSON qw( decode_json ); +use JSON qw( decode_json ); use File::Basename qw( dirname ); use File::Slurp; diff --git a/t/db_dependent/api/v1/erm_documents.t b/t/db_dependent/api/v1/erm_documents.t index 7ace83e9a3..442b2d8812 100755 --- a/t/db_dependent/api/v1/erm_documents.t +++ b/t/db_dependent/api/v1/erm_documents.t @@ -72,9 +72,8 @@ subtest 'get() tests' => sub { my $unauth_userid = $patron->userid; # This document exists, should get returned - $t->get_ok( "//$userid:$password@/api/v1/erm/documents/" - . $document->document_id - . "/file/content" )->status_is(200)->json_is('123'); + $t->get_ok( "//$userid:$password@/api/v1/erm/documents/" . $document->document_id . "/file/content" ) + ->status_is(200)->json_is('123'); # Create a document through a license, gets returned my $license = $builder->build_object( { class => 'Koha::ERM::Licenses' } ); @@ -94,10 +93,8 @@ subtest 'get() tests' => sub { my @documents = $license->documents->as_list; my $license_document_id = $documents[0]->document_id; - $t->get_ok( "//$userid:$password@/api/v1/erm/documents/" - . $license_document_id - . "/file/content" )->status_is(200) - ->content_is( decode_base64('321') ); + $t->get_ok( "//$userid:$password@/api/v1/erm/documents/" . $license_document_id . "/file/content" )->status_is(200) + ->content_is( decode_base64('321') ); # Delete a document through a license, no longer exists my $deleted_document_id = $license_document_id; @@ -113,24 +110,19 @@ subtest 'get() tests' => sub { ] ); - $t->get_ok( "//$userid:$password@/api/v1/erm/documents/" - . $deleted_document_id - . "/file/content" )->status_is(404); + $t->get_ok( "//$userid:$password@/api/v1/erm/documents/" . $deleted_document_id . "/file/content" )->status_is(404); # Unauthorized access - $t->get_ok( "//$unauth_userid:$password@/api/v1/erm/documents/" - . $document->document_id - . "/file/content" )->status_is(403); + $t->get_ok( "//$unauth_userid:$password@/api/v1/erm/documents/" . $document->document_id . "/file/content" ) + ->status_is(403); # Attempt to get non-existent document - my $document_to_delete = - $builder->build_object( { class => 'Koha::ERM::Documents' } ); - my $non_existent_id = $document_to_delete->id; + my $document_to_delete = $builder->build_object( { class => 'Koha::ERM::Documents' } ); + my $non_existent_id = $document_to_delete->id; $document_to_delete->delete; - $t->get_ok( -"//$userid:$password@/api/v1/erm/documents/$non_existent_id/file/content" - )->status_is(404)->json_is( '/error' => 'Document not found' ); + $t->get_ok("//$userid:$password@/api/v1/erm/documents/$non_existent_id/file/content")->status_is(404) + ->json_is( '/error' => 'Document not found' ); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/api/v1/erm_eholdings_packages.t b/t/db_dependent/api/v1/erm_eholdings_packages.t index 93a5c8240a..2cd53ea5e9 100755 --- a/t/db_dependent/api/v1/erm_eholdings_packages.t +++ b/t/db_dependent/api/v1/erm_eholdings_packages.t @@ -62,8 +62,7 @@ subtest 'list() tests' => sub { ## Authorized user tests # No EHoldings package, so empty array should be returned - $t->get_ok("//$userid:$password@/api/v1/erm/eholdings/local/packages") - ->status_is(200)->json_is( [] ); + $t->get_ok("//$userid:$password@/api/v1/erm/eholdings/local/packages")->status_is(200)->json_is( [] ); my $ehpackage = $builder->build_object( { @@ -73,8 +72,8 @@ subtest 'list() tests' => sub { ); # One EHoldings package created, should get returned - $t->get_ok("//$userid:$password@/api/v1/erm/eholdings/local/packages") - ->status_is(200)->json_is( [ $ehpackage->to_api ] ); + $t->get_ok("//$userid:$password@/api/v1/erm/eholdings/local/packages")->status_is(200) + ->json_is( [ $ehpackage->to_api ] ); my $another_ehpackage = $builder->build_object( { @@ -93,28 +92,24 @@ subtest 'list() tests' => sub { ); # Two EHoldings packages created, they should both be returned - $t->get_ok("//$userid:$password@/api/v1/erm/eholdings/local/packages") - ->status_is(200)->json_is( + $t->get_ok("//$userid:$password@/api/v1/erm/eholdings/local/packages")->status_is(200)->json_is( [ $ehpackage->to_api, $another_ehpackage->to_api, $ehpackage_with_another_package_type->to_api ] - ); + ); # Filtering works, two EHoldings packages sharing package_type - $t->get_ok( - "//$userid:$password@/api/v1/erm/eholdings/local/packages?package_type=" - . $ehpackage->package_type )->status_is(200) - ->json_is( [ $ehpackage->to_api, $another_ehpackage->to_api ] ); + $t->get_ok( "//$userid:$password@/api/v1/erm/eholdings/local/packages?package_type=" . $ehpackage->package_type ) + ->status_is(200)->json_is( [ $ehpackage->to_api, $another_ehpackage->to_api ] ); # Attempt to search by name like 'ko' $ehpackage->delete; $another_ehpackage->delete; $ehpackage_with_another_package_type->delete; - $t->get_ok( -qq~//$userid:$password@/api/v1/erm/eholdings/local/packages?q=[{"me.name":{"like":"%ko%"}}]~ - )->status_is(200)->json_is( [] ); + $t->get_ok(qq~//$userid:$password@/api/v1/erm/eholdings/local/packages?q=[{"me.name":{"like":"%ko%"}}]~) + ->status_is(200)->json_is( [] ); my $ehpackage_to_search = $builder->build_object( { @@ -127,21 +122,15 @@ qq~//$userid:$password@/api/v1/erm/eholdings/local/packages?q=[{"me.name":{"like ); # Search works, searching for name like 'ko' - $t->get_ok( -qq~//$userid:$password@/api/v1/erm/eholdings/local/packages?q=[{"me.name":{"like":"%ko%"}}]~ - )->status_is(200)->json_is( [ $ehpackage_to_search->to_api ] ); + $t->get_ok(qq~//$userid:$password@/api/v1/erm/eholdings/local/packages?q=[{"me.name":{"like":"%ko%"}}]~) + ->status_is(200)->json_is( [ $ehpackage_to_search->to_api ] ); # Warn on unsupported query parameter - $t->get_ok( - "//$userid:$password@/api/v1/erm/eholdings/local/packages?blah=blah") - ->status_is(400) - ->json_is( - [ { path => '/query/blah', message => 'Malformed query string' } ] ); + $t->get_ok("//$userid:$password@/api/v1/erm/eholdings/local/packages?blah=blah")->status_is(400) + ->json_is( [ { path => '/query/blah', message => 'Malformed query string' } ] ); # Unauthorized access - $t->get_ok( - "//$unauth_userid:$password@/api/v1/erm/eholdings/local/packages") - ->status_is(403); + $t->get_ok("//$unauth_userid:$password@/api/v1/erm/eholdings/local/packages")->status_is(403); $schema->storage->txn_rollback; }; @@ -152,8 +141,7 @@ subtest 'get() tests' => sub { $schema->storage->txn_begin; - my $ehpackage = - $builder->build_object( { class => 'Koha::ERM::EHoldings::Packages' } ); + my $ehpackage = $builder->build_object( { class => 'Koha::ERM::EHoldings::Packages' } ); my $librarian = $builder->build_object( { class => 'Koha::Patrons', @@ -175,30 +163,25 @@ subtest 'get() tests' => sub { my $unauth_userid = $patron->userid; # This EHoldings package exists, should get returned - $t->get_ok( "//$userid:$password@/api/v1/erm/eholdings/local/packages/" - . $ehpackage->package_id )->status_is(200) - ->json_is( $ehpackage->to_api ); + $t->get_ok( "//$userid:$password@/api/v1/erm/eholdings/local/packages/" . $ehpackage->package_id )->status_is(200) + ->json_is( $ehpackage->to_api ); # Return one EHoldings package with embed $t->get_ok( "//$userid:$password@/api/v1/erm/eholdings/local/packages/" - . $ehpackage->package_id => - { 'x-koha-embed' => 'resources+count' } )->status_is(200) - ->json_is( { %{ $ehpackage->to_api }, resources_count => 0 } ); + . $ehpackage->package_id => { 'x-koha-embed' => 'resources+count' } )->status_is(200) + ->json_is( { %{ $ehpackage->to_api }, resources_count => 0 } ); # Unauthorized access - $t->get_ok( - "//$unauth_userid:$password@/api/v1/erm/eholdings/local/packages/" - . $ehpackage->package_id )->status_is(403); + $t->get_ok( "//$unauth_userid:$password@/api/v1/erm/eholdings/local/packages/" . $ehpackage->package_id ) + ->status_is(403); # Attempt to get non-existent EHoldings package - my $ehpackage_to_delete = - $builder->build_object( { class => 'Koha::ERM::EHoldings::Packages' } ); - my $non_existent_id = $ehpackage_to_delete->package_id; + my $ehpackage_to_delete = $builder->build_object( { class => 'Koha::ERM::EHoldings::Packages' } ); + my $non_existent_id = $ehpackage_to_delete->package_id; $ehpackage_to_delete->delete; - $t->get_ok( -"//$userid:$password@/api/v1/erm/eholdings/local/packages/$non_existent_id" - )->status_is(404)->json_is( '/error' => 'Package not found' ); + $t->get_ok("//$userid:$password@/api/v1/erm/eholdings/local/packages/$non_existent_id")->status_is(404) + ->json_is( '/error' => 'Package not found' ); $schema->storage->txn_rollback; }; @@ -237,9 +220,8 @@ subtest 'add() tests' => sub { }; # Unauthorized attempt to write - $t->post_ok( - "//$unauth_userid:$password@/api/v1/erm/eholdings/local/packages" => - json => $ehpackage )->status_is(403); + $t->post_ok( "//$unauth_userid:$password@/api/v1/erm/eholdings/local/packages" => json => $ehpackage ) + ->status_is(403); # Authorized attempt to write invalid data my $ehpackage_with_invalid_field = { @@ -247,48 +229,42 @@ subtest 'add() tests' => sub { name => "Package name", }; - $t->post_ok( - "//$userid:$password@/api/v1/erm/eholdings/local/packages" => json => - $ehpackage_with_invalid_field )->status_is(400)->json_is( + $t->post_ok( "//$userid:$password@/api/v1/erm/eholdings/local/packages" => json => $ehpackage_with_invalid_field ) + ->status_is(400)->json_is( "/errors" => [ { message => "Properties not allowed: blah.", path => "/body" } ] - ); + ); # Authorized attempt to write my $ehpackage_id = - $t->post_ok( - "//$userid:$password@/api/v1/erm/eholdings/local/packages" => json => - $ehpackage )->status_is( 201, 'REST3.2.1' )->header_like( + $t->post_ok( "//$userid:$password@/api/v1/erm/eholdings/local/packages" => json => $ehpackage ) + ->status_is( 201, 'REST3.2.1' )->header_like( Location => qr|^/api/v1/erm/eholdings/local/packages/\d*|, 'REST3.4.1' - )->json_is( '/name' => $ehpackage->{name} ) - ->json_is( '/print_identifier' => $ehpackage->{print_identifier} ) - ->json_is( '/notes' => $ehpackage->{notes} ) - ->json_is( '/publisher_name' => $ehpackage->{publisher_name} ) - ->tx->res->json->{package_id}; + )->json_is( '/name' => $ehpackage->{name} )->json_is( '/print_identifier' => $ehpackage->{print_identifier} ) + ->json_is( '/notes' => $ehpackage->{notes} )->json_is( '/publisher_name' => $ehpackage->{publisher_name} ) + ->tx->res->json->{package_id}; # Authorized attempt to create with null id $ehpackage->{package_id} = undef; - $t->post_ok( - "//$userid:$password@/api/v1/erm/eholdings/local/packages" => json => - $ehpackage )->status_is(400)->json_has('/errors'); + $t->post_ok( "//$userid:$password@/api/v1/erm/eholdings/local/packages" => json => $ehpackage )->status_is(400) + ->json_has('/errors'); # Authorized attempt to create with existing id $ehpackage->{package_id} = $ehpackage_id; - $t->post_ok( - "//$userid:$password@/api/v1/erm/eholdings/local/packages" => json => - $ehpackage )->status_is(400)->json_is( + $t->post_ok( "//$userid:$password@/api/v1/erm/eholdings/local/packages" => json => $ehpackage )->status_is(400) + ->json_is( "/errors" => [ { message => "Read-only.", path => "/body/package_id" } ] - ); + ); $schema->storage->txn_rollback; }; @@ -319,24 +295,18 @@ subtest 'update() tests' => sub { $patron->set_password( { password => $password, skip_validation => 1 } ); my $unauth_userid = $patron->userid; - my $ehpackage_id = - $builder->build_object( { class => 'Koha::ERM::EHoldings::Packages' } ) - ->package_id; + my $ehpackage_id = $builder->build_object( { class => 'Koha::ERM::EHoldings::Packages' } )->package_id; # Unauthorized attempt to update - $t->put_ok( -"//$unauth_userid:$password@/api/v1/erm/eholdings/local/packages/$ehpackage_id" - => json => { name => 'New unauthorized name change' } ) - ->status_is(403); + $t->put_ok( "//$unauth_userid:$password@/api/v1/erm/eholdings/local/packages/$ehpackage_id" => json => + { name => 'New unauthorized name change' } )->status_is(403); # Attempt partial update on a PUT my $ehpackage_with_missing_field = { package_type => "Package type", }; - $t->put_ok( - "//$userid:$password@/api/v1/erm/eholdings/local/packages/$ehpackage_id" - => json => $ehpackage_with_missing_field )->status_is(400) - ->json_is( "/errors" => - [ { message => "Missing property.", path => "/body/name" } ] ); + $t->put_ok( "//$userid:$password@/api/v1/erm/eholdings/local/packages/$ehpackage_id" => json => + $ehpackage_with_missing_field )->status_is(400) + ->json_is( "/errors" => [ { message => "Missing property.", path => "/body/name" } ] ); # Full object update on PUT my $ehpackage_with_updated_field = { @@ -346,10 +316,8 @@ subtest 'update() tests' => sub { notes => "Notes" }; - $t->put_ok( - "//$userid:$password@/api/v1/erm/eholdings/local/packages/$ehpackage_id" - => json => $ehpackage_with_updated_field )->status_is(200) - ->json_is( '/name' => 'Package name' ); + $t->put_ok( "//$userid:$password@/api/v1/erm/eholdings/local/packages/$ehpackage_id" => json => + $ehpackage_with_updated_field )->status_is(200)->json_is( '/name' => 'Package name' ); # Authorized attempt to write invalid data my $ehpackage_with_invalid_field = { @@ -357,33 +325,29 @@ subtest 'update() tests' => sub { name => "Package name", }; - $t->put_ok( - "//$userid:$password@/api/v1/erm/eholdings/local/packages/$ehpackage_id" - => json => $ehpackage_with_invalid_field )->status_is(400)->json_is( + $t->put_ok( "//$userid:$password@/api/v1/erm/eholdings/local/packages/$ehpackage_id" => json => + $ehpackage_with_invalid_field )->status_is(400)->json_is( "/errors" => [ { message => "Properties not allowed: blah.", path => "/body" } ] - ); + ); # Attempt to update non-existent EHolding package - my $ehpackage_to_delete = - $builder->build_object( { class => 'Koha::ERM::EHoldings::Packages' } ); - my $non_existent_id = $ehpackage_to_delete->package_id; + my $ehpackage_to_delete = $builder->build_object( { class => 'Koha::ERM::EHoldings::Packages' } ); + my $non_existent_id = $ehpackage_to_delete->package_id; $ehpackage_to_delete->delete; - $t->put_ok( -"//$userid:$password@/api/v1/erm/eholdings/local/packages/$non_existent_id" - => json => $ehpackage_with_updated_field )->status_is(404); + $t->put_ok( "//$userid:$password@/api/v1/erm/eholdings/local/packages/$non_existent_id" => json => + $ehpackage_with_updated_field )->status_is(404); # Wrong method (POST) $ehpackage_with_updated_field->{package_id} = 2; - $t->post_ok( - "//$userid:$password@/api/v1/erm/eholdings/local/packages/$ehpackage_id" - => json => $ehpackage_with_updated_field )->status_is(404); + $t->post_ok( "//$userid:$password@/api/v1/erm/eholdings/local/packages/$ehpackage_id" => json => + $ehpackage_with_updated_field )->status_is(404); $schema->storage->txn_rollback; }; @@ -414,24 +378,17 @@ subtest 'delete() tests' => sub { $patron->set_password( { password => $password, skip_validation => 1 } ); my $unauth_userid = $patron->userid; - my $ehpackage_id = - $builder->build_object( { class => 'Koha::ERM::EHoldings::Packages' } ) - ->package_id; + my $ehpackage_id = $builder->build_object( { class => 'Koha::ERM::EHoldings::Packages' } )->package_id; # Unauthorized attempt to delete - $t->delete_ok( -"//$unauth_userid:$password@/api/v1/erm/eholdings/local/packages/$ehpackage_id" - )->status_is(403); + $t->delete_ok("//$unauth_userid:$password@/api/v1/erm/eholdings/local/packages/$ehpackage_id")->status_is(403); # Delete existing EHolding package - $t->delete_ok( - "//$userid:$password@/api/v1/erm/eholdings/local/packages/$ehpackage_id" - )->status_is( 204, 'REST3.2.4' )->content_is( '', 'REST3.3.4' ); + $t->delete_ok("//$userid:$password@/api/v1/erm/eholdings/local/packages/$ehpackage_id") + ->status_is( 204, 'REST3.2.4' )->content_is( '', 'REST3.3.4' ); # Attempt to delete non-existent EHolding package - $t->delete_ok( - "//$userid:$password@/api/v1/erm/eholdings/local/packages/$ehpackage_id" - )->status_is(404); + $t->delete_ok("//$userid:$password@/api/v1/erm/eholdings/local/packages/$ehpackage_id")->status_is(404); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/api/v1/erm_eholdings_resources.t b/t/db_dependent/api/v1/erm_eholdings_resources.t index e2bd68f302..01e73f9804 100755 --- a/t/db_dependent/api/v1/erm_eholdings_resources.t +++ b/t/db_dependent/api/v1/erm_eholdings_resources.t @@ -62,15 +62,13 @@ subtest 'list() tests' => sub { ## Authorized user tests # No resources, so empty array should be returned - $t->get_ok("//$userid:$password@/api/v1/erm/eholdings/local/resources") - ->status_is(200)->json_is( [] ); + $t->get_ok("//$userid:$password@/api/v1/erm/eholdings/local/resources")->status_is(200)->json_is( [] ); - my $resource = - $builder->build_object( { class => 'Koha::ERM::EHoldings::Resources' } ); + my $resource = $builder->build_object( { class => 'Koha::ERM::EHoldings::Resources' } ); # One resource created, should get returned - $t->get_ok("//$userid:$password@/api/v1/erm/eholdings/local/resources") - ->status_is(200)->json_is( [ $resource->to_api ] ); + $t->get_ok("//$userid:$password@/api/v1/erm/eholdings/local/resources")->status_is(200) + ->json_is( [ $resource->to_api ] ); my $another_resource = $builder->build_object( { @@ -78,36 +76,27 @@ subtest 'list() tests' => sub { value => { vendor_id => $resource->vendor_id } } ); - my $resource_with_another_vendor_id = - $builder->build_object( { class => 'Koha::ERM::EHoldings::Resources' } ); + my $resource_with_another_vendor_id = $builder->build_object( { class => 'Koha::ERM::EHoldings::Resources' } ); # Two resources created, they should both be returned - $t->get_ok("//$userid:$password@/api/v1/erm/eholdings/local/resources") - ->status_is(200)->json_is( + $t->get_ok("//$userid:$password@/api/v1/erm/eholdings/local/resources")->status_is(200)->json_is( [ $resource->to_api, $another_resource->to_api, $resource_with_another_vendor_id->to_api ] - ); + ); # Filtering works, two resources sharing vendor_id - $t->get_ok( - "//$userid:$password@/api/v1/erm/eholdings/local/resources?vendor_id=" - . $resource->vendor_id )->status_is(200) - ->json_is( [ $resource->to_api, $another_resource->to_api ] ); + $t->get_ok( "//$userid:$password@/api/v1/erm/eholdings/local/resources?vendor_id=" . $resource->vendor_id ) + ->status_is(200)->json_is( [ $resource->to_api, $another_resource->to_api ] ); # Warn on unsupported query parameter - $t->get_ok( - "//$userid:$password@/api/v1/erm/eholdings/local/resources?blah=blah") - ->status_is(400) - ->json_is( - [ { path => '/query/blah', message => 'Malformed query string' } ] ); + $t->get_ok("//$userid:$password@/api/v1/erm/eholdings/local/resources?blah=blah")->status_is(400) + ->json_is( [ { path => '/query/blah', message => 'Malformed query string' } ] ); # Unauthorized access - $t->get_ok( - "//$unauth_userid:$password@/api/v1/erm/eholdings/local/resources") - ->status_is(403); + $t->get_ok("//$unauth_userid:$password@/api/v1/erm/eholdings/local/resources")->status_is(403); $schema->storage->txn_rollback; }; @@ -118,8 +107,7 @@ subtest 'get() tests' => sub { $schema->storage->txn_begin; - my $resource = - $builder->build_object( { class => 'Koha::ERM::EHoldings::Resources' } ); + my $resource = $builder->build_object( { class => 'Koha::ERM::EHoldings::Resources' } ); my $librarian = $builder->build_object( { class => 'Koha::Patrons', @@ -141,24 +129,20 @@ subtest 'get() tests' => sub { my $unauth_userid = $patron->userid; # This resource exists, should get returned - $t->get_ok( "//$userid:$password@/api/v1/erm/eholdings/local/resources/" - . $resource->resource_id )->status_is(200) - ->json_is( $resource->to_api ); + $t->get_ok( "//$userid:$password@/api/v1/erm/eholdings/local/resources/" . $resource->resource_id )->status_is(200) + ->json_is( $resource->to_api ); # Unauthorized access - $t->get_ok( - "//$unauth_userid:$password@/api/v1/erm/eholdings/local/resources/" - . $resource->resource_id )->status_is(403); + $t->get_ok( "//$unauth_userid:$password@/api/v1/erm/eholdings/local/resources/" . $resource->resource_id ) + ->status_is(403); # Attempt to get non-existent resource - my $resource_to_delete = - $builder->build_object( { class => 'Koha::ERM::EHoldings::Resources' } ); - my $non_existent_id = $resource_to_delete->resource_id; + my $resource_to_delete = $builder->build_object( { class => 'Koha::ERM::EHoldings::Resources' } ); + my $non_existent_id = $resource_to_delete->resource_id; $resource_to_delete->delete; - $t->get_ok( -"//$userid:$password@/api/v1/erm/eholdings/local/resources/$non_existent_id" - )->status_is(404)->json_is( '/error' => 'eHolding resource not found' ); + $t->get_ok("//$userid:$password@/api/v1/erm/eholdings/local/resources/$non_existent_id")->status_is(404) + ->json_is( '/error' => 'eHolding resource not found' ); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/api/v1/erm_eholdings_titles.t b/t/db_dependent/api/v1/erm_eholdings_titles.t index 0ed9f19d89..23e03d1914 100755 --- a/t/db_dependent/api/v1/erm_eholdings_titles.t +++ b/t/db_dependent/api/v1/erm_eholdings_titles.t @@ -66,15 +66,13 @@ subtest 'list() tests' => sub { ## Authorized user tests # No EHoldings title, so empty array should be returned - $t->get_ok("//$userid:$password@/api/v1/erm/eholdings/local/titles") - ->status_is(200)->json_is( [] ); + $t->get_ok("//$userid:$password@/api/v1/erm/eholdings/local/titles")->status_is(200)->json_is( [] ); - my $ehtitle = - $builder->build_object( { class => 'Koha::ERM::EHoldings::Titles' } ); + my $ehtitle = $builder->build_object( { class => 'Koha::ERM::EHoldings::Titles' } ); # One EHoldings title created, should get returned - $t->get_ok("//$userid:$password@/api/v1/erm/eholdings/local/titles") - ->status_is(200)->json_is( [ $ehtitle->to_api ] ); + $t->get_ok("//$userid:$password@/api/v1/erm/eholdings/local/titles")->status_is(200) + ->json_is( [ $ehtitle->to_api ] ); my $another_ehtitle = $builder->build_object( { @@ -82,31 +80,28 @@ subtest 'list() tests' => sub { value => { publication_type => $ehtitle->publication_type } } ); - my $ehtitle_with_another_publication_type = - $builder->build_object( { class => 'Koha::ERM::EHoldings::Titles' } ); + my $ehtitle_with_another_publication_type = $builder->build_object( { class => 'Koha::ERM::EHoldings::Titles' } ); # Two EHoldings titles created, they should both be returned - $t->get_ok("//$userid:$password@/api/v1/erm/eholdings/local/titles") - ->status_is(200)->json_is( + $t->get_ok("//$userid:$password@/api/v1/erm/eholdings/local/titles")->status_is(200)->json_is( [ $ehtitle->to_api, $another_ehtitle->to_api, $ehtitle_with_another_publication_type->to_api ] - ); + ); # Filtering works, two EHoldings titles sharing publication_type $t->get_ok( -"//$userid:$password@/api/v1/erm/eholdings/local/titles?publication_type=" - . $ehtitle->publication_type )->status_is(200) - ->json_is( [ $ehtitle->to_api, $another_ehtitle->to_api ] ); + "//$userid:$password@/api/v1/erm/eholdings/local/titles?publication_type=" . $ehtitle->publication_type ) + ->status_is(200)->json_is( [ $ehtitle->to_api, $another_ehtitle->to_api ] ); # Attempt to search by publication_title like 'ko' $ehtitle->delete; $another_ehtitle->delete; $ehtitle_with_another_publication_type->delete; $t->get_ok(qq~//$userid:$password@/api/v1/erm/eholdings/local/titles?q=[{"me.publication_title":{"like":"%ko%"}}]~) - ->status_is(200)->json_is( [] ); + ->status_is(200)->json_is( [] ); my $ehtitle_to_search = $builder->build_object( { @@ -119,18 +114,14 @@ subtest 'list() tests' => sub { # Search works, searching for publication_title like 'ko' $t->get_ok(qq~//$userid:$password@/api/v1/erm/eholdings/local/titles?q=[{"me.publication_title":{"like":"%ko%"}}]~) - ->status_is(200)->json_is( [ $ehtitle_to_search->to_api ] ); + ->status_is(200)->json_is( [ $ehtitle_to_search->to_api ] ); # Warn on unsupported query parameter - $t->get_ok( - "//$userid:$password@/api/v1/erm/eholdings/local/titles?blah=blah") - ->status_is(400) - ->json_is( - [ { path => '/query/blah', message => 'Malformed query string' } ] ); + $t->get_ok("//$userid:$password@/api/v1/erm/eholdings/local/titles?blah=blah")->status_is(400) + ->json_is( [ { path => '/query/blah', message => 'Malformed query string' } ] ); # Unauthorized access - $t->get_ok("//$unauth_userid:$password@/api/v1/erm/eholdings/local/titles") - ->status_is(403); + $t->get_ok("//$unauth_userid:$password@/api/v1/erm/eholdings/local/titles")->status_is(403); $schema->storage->txn_rollback; }; @@ -141,8 +132,7 @@ subtest 'get() tests' => sub { $schema->storage->txn_begin; - my $ehtitle = - $builder->build_object( { class => 'Koha::ERM::EHoldings::Titles' } ); + my $ehtitle = $builder->build_object( { class => 'Koha::ERM::EHoldings::Titles' } ); my $librarian = $builder->build_object( { class => 'Koha::Patrons', @@ -164,28 +154,24 @@ subtest 'get() tests' => sub { my $unauth_userid = $patron->userid; # This EHoldings title exists, should get returned - $t->get_ok( "//$userid:$password@/api/v1/erm/eholdings/local/titles/" - . $ehtitle->title_id )->status_is(200)->json_is( $ehtitle->to_api ); + $t->get_ok( "//$userid:$password@/api/v1/erm/eholdings/local/titles/" . $ehtitle->title_id )->status_is(200) + ->json_is( $ehtitle->to_api ); # Return one EHoldings title with embed $t->get_ok( "//$userid:$password@/api/v1/erm/eholdings/local/titles/" - . $ehtitle->title_id => - { 'x-koha-embed' => 'resources,resources.package' } )->status_is(200) - ->json_is( { %{ $ehtitle->to_api }, resources => [] } ); + . $ehtitle->title_id => { 'x-koha-embed' => 'resources,resources.package' } )->status_is(200) + ->json_is( { %{ $ehtitle->to_api }, resources => [] } ); # Unauthorized access - $t->get_ok( "//$unauth_userid:$password@/api/v1/erm/eholdings/local/titles/" - . $ehtitle->title_id )->status_is(403); + $t->get_ok( "//$unauth_userid:$password@/api/v1/erm/eholdings/local/titles/" . $ehtitle->title_id )->status_is(403); # Attempt to get non-existent EHoldings title - my $ehtitle_to_delete = - $builder->build_object( { class => 'Koha::ERM::EHoldings::Titles' } ); - my $non_existent_id = $ehtitle_to_delete->title_id; + my $ehtitle_to_delete = $builder->build_object( { class => 'Koha::ERM::EHoldings::Titles' } ); + my $non_existent_id = $ehtitle_to_delete->title_id; $ehtitle_to_delete->delete; - $t->get_ok( -"//$userid:$password@/api/v1/erm/eholdings/local/titles/$non_existent_id" - )->status_is(404)->json_is( '/error' => 'eHolding title not found' ); + $t->get_ok("//$userid:$password@/api/v1/erm/eholdings/local/titles/$non_existent_id")->status_is(404) + ->json_is( '/error' => 'eHolding title not found' ); $schema->storage->txn_rollback; }; @@ -217,41 +203,34 @@ subtest 'add() tests' => sub { my $unauth_userid = $patron->userid; my $ehtitle = { - publication_title => "Publication title", - print_identifier => "Print-format identifier", - online_identifier => "Online-format identifier", - date_first_issue_online => - "Date of first serial issue available online", - num_first_vol_online => "Number of first volume available online", - num_first_issue_online => "Number of first issue available online", - date_last_issue_online => "Date of last issue available online", - num_last_vol_online => "Number of last volume available online", - num_last_issue_online => "Number of last issue available online", - title_url => "Title-level URL", - first_author => "First author", - embargo_info => "Embargo information", - coverage_depth => "Coverage depth", - notes => "Notes", - publisher_name => "Publisher name", - publication_type => "Book", - date_monograph_published_print => - "Date the monograph is first published in print", - date_monograph_published_online => - "Date the monograph is first published online", - monograph_volume => "Number of volume for monograph", - monograph_edition => "Edition of the monograph", - first_editor => "First editor", - parent_publication_title_id => - "Title identifier of the parent publication", - preceding_publication_title_id => - "Title identifier of any preceding publication title", - access_type => "Access type" + publication_title => "Publication title", + print_identifier => "Print-format identifier", + online_identifier => "Online-format identifier", + date_first_issue_online => "Date of first serial issue available online", + num_first_vol_online => "Number of first volume available online", + num_first_issue_online => "Number of first issue available online", + date_last_issue_online => "Date of last issue available online", + num_last_vol_online => "Number of last volume available online", + num_last_issue_online => "Number of last issue available online", + title_url => "Title-level URL", + first_author => "First author", + embargo_info => "Embargo information", + coverage_depth => "Coverage depth", + notes => "Notes", + publisher_name => "Publisher name", + publication_type => "Book", + date_monograph_published_print => "Date the monograph is first published in print", + date_monograph_published_online => "Date the monograph is first published online", + monograph_volume => "Number of volume for monograph", + monograph_edition => "Edition of the monograph", + first_editor => "First editor", + parent_publication_title_id => "Title identifier of the parent publication", + preceding_publication_title_id => "Title identifier of any preceding publication title", + access_type => "Access type" }; # Unauthorized attempt to write - $t->post_ok( - "//$unauth_userid:$password@/api/v1/erm/eholdings/local/titles" => - json => $ehtitle )->status_is(403); + $t->post_ok( "//$unauth_userid:$password@/api/v1/erm/eholdings/local/titles" => json => $ehtitle )->status_is(403); # Authorized attempt to write invalid data my $ehtitle_with_invalid_field = { @@ -260,52 +239,44 @@ subtest 'add() tests' => sub { print_identifier => "Print-format identifier" }; - $t->post_ok( - "//$userid:$password@/api/v1/erm/eholdings/local/titles" => json => - $ehtitle_with_invalid_field )->status_is(400)->json_is( + $t->post_ok( "//$userid:$password@/api/v1/erm/eholdings/local/titles" => json => $ehtitle_with_invalid_field ) + ->status_is(400)->json_is( "/errors" => [ { message => "Properties not allowed: blah.", path => "/body" } ] - ); + ); # Authorized attempt to write my $ehtitle_id = - $t->post_ok( - "//$userid:$password@/api/v1/erm/eholdings/local/titles" => json => - $ehtitle )->status_is( 201, 'REST3.2.1' )->header_like( + $t->post_ok( "//$userid:$password@/api/v1/erm/eholdings/local/titles" => json => $ehtitle ) + ->status_is( 201, 'REST3.2.1' )->header_like( Location => qr|^/api/v1/erm/eholdings/local/titles/\d*|, 'REST3.4.1' )->json_is( '/publication_title' => $ehtitle->{publication_title} ) - ->json_is( '/print_identifier' => $ehtitle->{print_identifier} ) - ->json_is( '/notes' => $ehtitle->{notes} ) - ->json_is( '/publisher_name' => $ehtitle->{publisher_name} ) - ->tx->res->json->{title_id}; + ->json_is( '/print_identifier' => $ehtitle->{print_identifier} )->json_is( '/notes' => $ehtitle->{notes} ) + ->json_is( '/publisher_name' => $ehtitle->{publisher_name} )->tx->res->json->{title_id}; # Import titles from virtualshelf to package - my $ehpackage_id = - $builder->build_object( { class => 'Koha::ERM::EHoldings::Packages' } ) - ->package_id; + my $ehpackage_id = $builder->build_object( { class => 'Koha::ERM::EHoldings::Packages' } )->package_id; - my $virtual_shelf = - $builder->build_object( + my $virtual_shelf = $builder->build_object( { - class => 'Koha::Virtualshelves', - } ); - $virtual_shelf->transfer_ownership($librarian->borrowernumber); - my $virtual_shelf_id = $virtual_shelf->shelfnumber; + class => 'Koha::Virtualshelves', + } + ); + $virtual_shelf->transfer_ownership( $librarian->borrowernumber ); + my $virtual_shelf_id = $virtual_shelf->shelfnumber; - my $import_request = - { - list_id => $virtual_shelf_id, + my $import_request = { + list_id => $virtual_shelf_id, package_id => $ehpackage_id }; - $t->post_ok( - "//$userid:$password@/api/v1/erm/eholdings/local/titles/import" => json => - $import_request )->status_is(201)->json_has('/job_id'); + $t->post_ok( "//$userid:$password@/api/v1/erm/eholdings/local/titles/import" => json => $import_request ) + ->status_is(201)->json_has('/job_id'); # Attempt to import titles from a virtualshelf that doesn't exist $virtual_shelf->delete; @@ -314,22 +285,20 @@ subtest 'add() tests' => sub { # Authorized attempt to create with null id $ehtitle->{title_id} = undef; - $t->post_ok( - "//$userid:$password@/api/v1/erm/eholdings/local/titles" => json => - $ehtitle )->status_is(400)->json_has('/errors'); + $t->post_ok( "//$userid:$password@/api/v1/erm/eholdings/local/titles" => json => $ehtitle )->status_is(400) + ->json_has('/errors'); # Authorized attempt to create with existing id $ehtitle->{title_id} = $ehtitle_id; - $t->post_ok( - "//$userid:$password@/api/v1/erm/eholdings/local/titles" => json => - $ehtitle )->status_is(400)->json_is( + $t->post_ok( "//$userid:$password@/api/v1/erm/eholdings/local/titles" => json => $ehtitle )->status_is(400) + ->json_is( "/errors" => [ { message => "Read-only.", path => "/body/title_id" } ] - ); + ); subtest 'add eholdings title linked to biblio tests' => sub { @@ -381,64 +350,54 @@ subtest 'update() tests' => sub { ->title_id; # Unauthorized attempt to update - $t->put_ok( -"//$unauth_userid:$password@/api/v1/erm/eholdings/local/titles/$ehtitle_id" - => json => - { publication_title => 'New unauthorized publication_title change' } ) - ->status_is(403); + $t->put_ok( "//$unauth_userid:$password@/api/v1/erm/eholdings/local/titles/$ehtitle_id" => json => + { publication_title => 'New unauthorized publication_title change' } )->status_is(403); # Attempt partial update on a PUT - my $ehtitle_with_missing_field = { date_first_issue_online => - "Date of first serial issue available online", }; + my $ehtitle_with_missing_field = { date_first_issue_online => "Date of first serial issue available online", }; $t->put_ok( - "//$userid:$password@/api/v1/erm/eholdings/local/titles/$ehtitle_id" => - json => $ehtitle_with_missing_field )->status_is(400)->json_is( + "//$userid:$password@/api/v1/erm/eholdings/local/titles/$ehtitle_id" => json => $ehtitle_with_missing_field ) + ->status_is(400)->json_is( "/errors" => [ { message => "Missing property.", path => "/body/publication_title" } ] - ); + ); # Full object update on PUT my $ehtitle_with_updated_field = { - publication_title => "Publication title", - print_identifier => "Print-format identifier", - online_identifier => "Online-format identifier", - date_first_issue_online => - "Date of first serial issue available online", - num_first_vol_online => "Number of first volume available online", - num_first_issue_online => "Number of first issue available online", - date_last_issue_online => "Date of last issue available online", - num_last_vol_online => "Number of last volume available online", - num_last_issue_online => "Number of last issue available online", - title_url => "Title-level URL", - first_author => "First author", - embargo_info => "Embargo information", - coverage_depth => "Coverage depth", - notes => "Notes", - publisher_name => "Publisher name", - publication_type => "Book", - date_monograph_published_print => - "Date the monograph is first published in print", - date_monograph_published_online => - "Date the monograph is first published online", - monograph_volume => "Number of volume for monograph", - monograph_edition => "Edition of the monograph", - first_editor => "First editor", - parent_publication_title_id => - "Title identifier of the parent publication", - preceding_publication_title_id => - "Title identifier of any preceding publication title", - access_type => "Access type" + publication_title => "Publication title", + print_identifier => "Print-format identifier", + online_identifier => "Online-format identifier", + date_first_issue_online => "Date of first serial issue available online", + num_first_vol_online => "Number of first volume available online", + num_first_issue_online => "Number of first issue available online", + date_last_issue_online => "Date of last issue available online", + num_last_vol_online => "Number of last volume available online", + num_last_issue_online => "Number of last issue available online", + title_url => "Title-level URL", + first_author => "First author", + embargo_info => "Embargo information", + coverage_depth => "Coverage depth", + notes => "Notes", + publisher_name => "Publisher name", + publication_type => "Book", + date_monograph_published_print => "Date the monograph is first published in print", + date_monograph_published_online => "Date the monograph is first published online", + monograph_volume => "Number of volume for monograph", + monograph_edition => "Edition of the monograph", + first_editor => "First editor", + parent_publication_title_id => "Title identifier of the parent publication", + preceding_publication_title_id => "Title identifier of any preceding publication title", + access_type => "Access type" }; $t->put_ok( - "//$userid:$password@/api/v1/erm/eholdings/local/titles/$ehtitle_id" => - json => $ehtitle_with_updated_field )->status_is(200) - ->json_is( '/publication_title' => 'Publication title' ); + "//$userid:$password@/api/v1/erm/eholdings/local/titles/$ehtitle_id" => json => $ehtitle_with_updated_field ) + ->status_is(200)->json_is( '/publication_title' => 'Publication title' ); # Authorized attempt to write invalid data my $ehtitle_with_invalid_field = { @@ -448,32 +407,30 @@ subtest 'update() tests' => sub { }; $t->put_ok( - "//$userid:$password@/api/v1/erm/eholdings/local/titles/$ehtitle_id" => - json => $ehtitle_with_invalid_field )->status_is(400)->json_is( + "//$userid:$password@/api/v1/erm/eholdings/local/titles/$ehtitle_id" => json => $ehtitle_with_invalid_field ) + ->status_is(400)->json_is( "/errors" => [ { message => "Properties not allowed: blah.", path => "/body" } ] - ); + ); # Attempt to update non-existent EHolding title - my $ehtitle_to_delete = - $builder->build_object( { class => 'Koha::ERM::EHoldings::Titles' } ); - my $non_existent_id = $ehtitle_to_delete->title_id; + my $ehtitle_to_delete = $builder->build_object( { class => 'Koha::ERM::EHoldings::Titles' } ); + my $non_existent_id = $ehtitle_to_delete->title_id; $ehtitle_to_delete->delete; - $t->put_ok( -"//$userid:$password@/api/v1/erm/eholdings/local/titles/$non_existent_id" - => json => $ehtitle_with_updated_field )->status_is(404); + $t->put_ok( "//$userid:$password@/api/v1/erm/eholdings/local/titles/$non_existent_id" => json => + $ehtitle_with_updated_field )->status_is(404); # Wrong method (POST) $ehtitle_with_updated_field->{title_id} = 2; $t->post_ok( - "//$userid:$password@/api/v1/erm/eholdings/local/titles/$ehtitle_id" => - json => $ehtitle_with_updated_field )->status_is(404); + "//$userid:$password@/api/v1/erm/eholdings/local/titles/$ehtitle_id" => json => $ehtitle_with_updated_field ) + ->status_is(404); subtest 'update eholdings title linked to biblio tests' => sub { @@ -538,24 +495,17 @@ subtest 'delete() tests' => sub { $patron->set_password( { password => $password, skip_validation => 1 } ); my $unauth_userid = $patron->userid; - my $ehtitle_id = - $builder->build_object( { class => 'Koha::ERM::EHoldings::Titles' } ) - ->title_id; + my $ehtitle_id = $builder->build_object( { class => 'Koha::ERM::EHoldings::Titles' } )->title_id; # Unauthorized attempt to delete - $t->delete_ok( -"//$unauth_userid:$password@/api/v1/erm/eholdings/local/titles/$ehtitle_id" - )->status_is(403); + $t->delete_ok("//$unauth_userid:$password@/api/v1/erm/eholdings/local/titles/$ehtitle_id")->status_is(403); # Delete existing EHolding title - $t->delete_ok( - "//$userid:$password@/api/v1/erm/eholdings/local/titles/$ehtitle_id") - ->status_is( 204, 'REST3.2.4' )->content_is( '', 'REST3.3.4' ); + $t->delete_ok("//$userid:$password@/api/v1/erm/eholdings/local/titles/$ehtitle_id")->status_is( 204, 'REST3.2.4' ) + ->content_is( '', 'REST3.3.4' ); # Attempt to delete non-existent EHolding title - $t->delete_ok( - "//$userid:$password@/api/v1/erm/eholdings/local/titles/$ehtitle_id") - ->status_is(404); + $t->delete_ok("//$userid:$password@/api/v1/erm/eholdings/local/titles/$ehtitle_id")->status_is(404); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/api/v1/erm_licenses.t b/t/db_dependent/api/v1/erm_licenses.t index 51f1fcd87f..eae6bff8eb 100755 --- a/t/db_dependent/api/v1/erm_licenses.t +++ b/t/db_dependent/api/v1/erm_licenses.t @@ -62,15 +62,12 @@ subtest 'list() tests' => sub { ## Authorized user tests # No licenses, so empty array should be returned - $t->get_ok("//$userid:$password@/api/v1/erm/licenses")->status_is(200) - ->json_is( [] ); + $t->get_ok("//$userid:$password@/api/v1/erm/licenses")->status_is(200)->json_is( [] ); - my $license = - $builder->build_object( { class => 'Koha::ERM::Licenses' } ); + my $license = $builder->build_object( { class => 'Koha::ERM::Licenses' } ); # One license created, should get returned - $t->get_ok("//$userid:$password@/api/v1/erm/licenses")->status_is(200) - ->json_is( [ $license->to_api ] ); + $t->get_ok("//$userid:$password@/api/v1/erm/licenses")->status_is(200)->json_is( [ $license->to_api ] ); my $another_license = $builder->build_object( { @@ -78,31 +75,27 @@ subtest 'list() tests' => sub { value => { vendor_id => $license->vendor_id } } ); - my $license_with_another_vendor_id = - $builder->build_object( { class => 'Koha::ERM::Licenses' } ); + my $license_with_another_vendor_id = $builder->build_object( { class => 'Koha::ERM::Licenses' } ); # Two licenses created, they should both be returned - $t->get_ok("//$userid:$password@/api/v1/erm/licenses")->status_is(200) - ->json_is( + $t->get_ok("//$userid:$password@/api/v1/erm/licenses")->status_is(200)->json_is( [ $license->to_api, $another_license->to_api, $license_with_another_vendor_id->to_api ] - ); + ); # Filtering works, two licenses sharing vendor_id - $t->get_ok( "//$userid:$password@/api/v1/erm/licenses?vendor_id=" - . $license->vendor_id )->status_is(200) - ->json_is( [ $license->to_api, $another_license->to_api ] ); + $t->get_ok( "//$userid:$password@/api/v1/erm/licenses?vendor_id=" . $license->vendor_id )->status_is(200) + ->json_is( [ $license->to_api, $another_license->to_api ] ); # Attempt to search by name like 'ko' $license->delete; $another_license->delete; $license_with_another_vendor_id->delete; - $t->get_ok( qq~//$userid:$password@/api/v1/erm/licenses?q=[{"me.name":{"like":"%ko%"}}]~) - ->status_is(200) - ->json_is( [] ); + $t->get_ok(qq~//$userid:$password@/api/v1/erm/licenses?q=[{"me.name":{"like":"%ko%"}}]~)->status_is(200) + ->json_is( [] ); my $license_to_search = $builder->build_object( { @@ -114,19 +107,15 @@ subtest 'list() tests' => sub { ); # Search works, searching for name like 'ko' - $t->get_ok( qq~//$userid:$password@/api/v1/erm/licenses?q=[{"me.name":{"like":"%ko%"}}]~) - ->status_is(200) - ->json_is( [ $license_to_search->to_api ] ); + $t->get_ok(qq~//$userid:$password@/api/v1/erm/licenses?q=[{"me.name":{"like":"%ko%"}}]~)->status_is(200) + ->json_is( [ $license_to_search->to_api ] ); # Warn on unsupported query parameter - $t->get_ok("//$userid:$password@/api/v1/erm/licenses?blah=blah") - ->status_is(400) - ->json_is( - [ { path => '/query/blah', message => 'Malformed query string' } ] ); + $t->get_ok("//$userid:$password@/api/v1/erm/licenses?blah=blah")->status_is(400) + ->json_is( [ { path => '/query/blah', message => 'Malformed query string' } ] ); # Unauthorized access - $t->get_ok("//$unauth_userid:$password@/api/v1/erm/licenses") - ->status_is(403); + $t->get_ok("//$unauth_userid:$password@/api/v1/erm/licenses")->status_is(403); $schema->storage->txn_rollback; }; @@ -137,8 +126,7 @@ subtest 'get() tests' => sub { $schema->storage->txn_begin; - my $license = - $builder->build_object( { class => 'Koha::ERM::Licenses' } ); + my $license = $builder->build_object( { class => 'Koha::ERM::Licenses' } ); my $librarian = $builder->build_object( { class => 'Koha::Patrons', @@ -160,27 +148,24 @@ subtest 'get() tests' => sub { my $unauth_userid = $patron->userid; # This license exists, should get returned - $t->get_ok( "//$userid:$password@/api/v1/erm/licenses/" - . $license->license_id )->status_is(200) - ->json_is( $license->to_api ); + $t->get_ok( "//$userid:$password@/api/v1/erm/licenses/" . $license->license_id )->status_is(200) + ->json_is( $license->to_api ); # Return one license with embed - $t->get_ok( "//$userid:$password@/api/v1/erm/licenses/" - . $license->license_id => {'x-koha-embed' => 'documents'} )->status_is(200) - ->json_is( { %{ $license->to_api }, documents => [] }); + $t->get_ok( + "//$userid:$password@/api/v1/erm/licenses/" . $license->license_id => { 'x-koha-embed' => 'documents' } ) + ->status_is(200)->json_is( { %{ $license->to_api }, documents => [] } ); # Unauthorized access - $t->get_ok( "//$unauth_userid:$password@/api/v1/erm/licenses/" - . $license->license_id )->status_is(403); + $t->get_ok( "//$unauth_userid:$password@/api/v1/erm/licenses/" . $license->license_id )->status_is(403); # Attempt to get non-existent license - my $license_to_delete = - $builder->build_object( { class => 'Koha::ERM::Licenses' } ); - my $non_existent_id = $license_to_delete->license_id; + my $license_to_delete = $builder->build_object( { class => 'Koha::ERM::Licenses' } ); + my $non_existent_id = $license_to_delete->license_id; $license_to_delete->delete; - $t->get_ok("//$userid:$password@/api/v1/erm/licenses/$non_existent_id") - ->status_is(404)->json_is( '/error' => 'License not found' ); + $t->get_ok("//$userid:$password@/api/v1/erm/licenses/$non_existent_id")->status_is(404) + ->json_is( '/error' => 'License not found' ); $schema->storage->txn_rollback; }; @@ -212,70 +197,62 @@ subtest 'add() tests' => sub { my $unauth_userid = $patron->userid; my $license = { - name => "License name", - description => "License description", - type => 'local', - status => "active", - started_on => undef, - ended_on => undef, + name => "License name", + description => "License description", + type => 'local', + status => "active", + started_on => undef, + ended_on => undef, }; # Unauthorized attempt to write - $t->post_ok( "//$unauth_userid:$password@/api/v1/erm/licenses" => json => - $license )->status_is(403); + $t->post_ok( "//$unauth_userid:$password@/api/v1/erm/licenses" => json => $license )->status_is(403); # Authorized attempt to write invalid data my $license_with_invalid_field = { - blah => "License Blah", - name => "License name", - description => "License description", - type => 'local', - status => "active", - started_on => undef, - ended_on => undef, + blah => "License Blah", + name => "License name", + description => "License description", + type => 'local', + status => "active", + started_on => undef, + ended_on => undef, }; - $t->post_ok( "//$userid:$password@/api/v1/erm/licenses" => json => - $license_with_invalid_field )->status_is(400)->json_is( + $t->post_ok( "//$userid:$password@/api/v1/erm/licenses" => json => $license_with_invalid_field )->status_is(400) + ->json_is( "/errors" => [ { message => "Properties not allowed: blah.", path => "/body" } ] - ); + ); # Authorized attempt to write my $license_id = - $t->post_ok( - "//$userid:$password@/api/v1/erm/licenses" => json => $license ) - ->status_is( 201, 'REST3.2.1' )->header_like( + $t->post_ok( "//$userid:$password@/api/v1/erm/licenses" => json => $license )->status_is( 201, 'REST3.2.1' ) + ->header_like( Location => qr|^/api/v1/erm/licenses/\d*|, 'REST3.4.1' - )->json_is( '/name' => $license->{name} ) - ->json_is( '/description' => $license->{description} ) - ->json_is( '/type' => $license->{type} ) - ->json_is( '/status' => $license->{status} ) - ->tx->res->json->{license_id}; + )->json_is( '/name' => $license->{name} )->json_is( '/description' => $license->{description} ) + ->json_is( '/type' => $license->{type} )->json_is( '/status' => $license->{status} ) + ->tx->res->json->{license_id}; # Authorized attempt to create with null id $license->{license_id} = undef; - $t->post_ok( - "//$userid:$password@/api/v1/erm/licenses" => json => $license ) - ->status_is(400)->json_has('/errors'); + $t->post_ok( "//$userid:$password@/api/v1/erm/licenses" => json => $license )->status_is(400)->json_has('/errors'); # Authorized attempt to create with existing id $license->{license_id} = $license_id; - $t->post_ok( - "//$userid:$password@/api/v1/erm/licenses" => json => $license ) - ->status_is(400)->json_is( + $t->post_ok( "//$userid:$password@/api/v1/erm/licenses" => json => $license )->status_is(400)->json_is( "/errors" => [ { message => "Read-only.", path => "/body/license_id" } ] - ); + ); $schema->storage->txn_rollback; }; @@ -306,81 +283,71 @@ subtest 'update() tests' => sub { $patron->set_password( { password => $password, skip_validation => 1 } ); my $unauth_userid = $patron->userid; - my $license_id = - $builder->build_object( { class => 'Koha::ERM::Licenses' } )->license_id; + my $license_id = $builder->build_object( { class => 'Koha::ERM::Licenses' } )->license_id; # Unauthorized attempt to update - $t->put_ok( - "//$unauth_userid:$password@/api/v1/erm/licenses/$license_id" => - json => { name => 'New unauthorized name change' } )->status_is(403); + $t->put_ok( "//$unauth_userid:$password@/api/v1/erm/licenses/$license_id" => json => + { name => 'New unauthorized name change' } )->status_is(403); # Attempt partial update on a PUT my $license_with_missing_field = { - description => 'New description', - type => 'national', - status => 'expired', - started_on => undef, - ended_on => undef, + description => 'New description', + type => 'national', + status => 'expired', + started_on => undef, + ended_on => undef, }; - $t->put_ok( - "//$userid:$password@/api/v1/erm/licenses/$license_id" => json => - $license_with_missing_field )->status_is(400) - ->json_is( "/errors" => - [ { message => "Missing property.", path => "/body/name" } ] ); + $t->put_ok( "//$userid:$password@/api/v1/erm/licenses/$license_id" => json => $license_with_missing_field ) + ->status_is(400)->json_is( "/errors" => [ { message => "Missing property.", path => "/body/name" } ] ); # Full object update on PUT my $license_with_updated_field = { - name => 'New name', - description => 'New description', - type => 'national', - status => 'expired', - started_on => undef, - ended_on => undef, + name => 'New name', + description => 'New description', + type => 'national', + status => 'expired', + started_on => undef, + ended_on => undef, }; - $t->put_ok( - "//$userid:$password@/api/v1/erm/licenses/$license_id" => json => - $license_with_updated_field )->status_is(200) - ->json_is( '/name' => 'New name' ); + $t->put_ok( "//$userid:$password@/api/v1/erm/licenses/$license_id" => json => $license_with_updated_field ) + ->status_is(200)->json_is( '/name' => 'New name' ); # Authorized attempt to write invalid data my $license_with_invalid_field = { - blah => "License Blah", - name => "License name", - description => "License description", - type => 'national', - status => 'expired', - started_on => undef, - ended_on => undef, + blah => "License Blah", + name => "License name", + description => "License description", + type => 'national', + status => 'expired', + started_on => undef, + ended_on => undef, }; - $t->put_ok( - "//$userid:$password@/api/v1/erm/licenses/$license_id" => json => - $license_with_invalid_field )->status_is(400)->json_is( + $t->put_ok( "//$userid:$password@/api/v1/erm/licenses/$license_id" => json => $license_with_invalid_field ) + ->status_is(400)->json_is( "/errors" => [ { message => "Properties not allowed: blah.", path => "/body" } ] - ); + ); # Attempt to update non-existent license - my $license_to_delete = - $builder->build_object( { class => 'Koha::ERM::Licenses' } ); - my $non_existent_id = $license_to_delete->id; + my $license_to_delete = $builder->build_object( { class => 'Koha::ERM::Licenses' } ); + my $non_existent_id = $license_to_delete->id; $license_to_delete->delete; - $t->put_ok( "//$userid:$password@/api/v1/erm/licenses/$non_existent_id" => - json => $license_with_updated_field )->status_is(404); + $t->put_ok( "//$userid:$password@/api/v1/erm/licenses/$non_existent_id" => json => $license_with_updated_field ) + ->status_is(404); # Wrong method (POST) $license_with_updated_field->{license_id} = 2; - $t->post_ok( - "//$userid:$password@/api/v1/erm/licenses/$license_id" => json => - $license_with_updated_field )->status_is(404); + $t->post_ok( "//$userid:$password@/api/v1/erm/licenses/$license_id" => json => $license_with_updated_field ) + ->status_is(404); $schema->storage->txn_rollback; }; @@ -411,21 +378,17 @@ subtest 'delete() tests' => sub { $patron->set_password( { password => $password, skip_validation => 1 } ); my $unauth_userid = $patron->userid; - my $license_id = - $builder->build_object( { class => 'Koha::ERM::Licenses' } )->license_id; + my $license_id = $builder->build_object( { class => 'Koha::ERM::Licenses' } )->license_id; # Unauthorized attempt to delete - $t->delete_ok( - "//$unauth_userid:$password@/api/v1/erm/licenses/$license_id") - ->status_is(403); + $t->delete_ok("//$unauth_userid:$password@/api/v1/erm/licenses/$license_id")->status_is(403); # Delete existing license - $t->delete_ok("//$userid:$password@/api/v1/erm/licenses/$license_id") - ->status_is( 204, 'REST3.2.4' )->content_is( '', 'REST3.3.4' ); + $t->delete_ok("//$userid:$password@/api/v1/erm/licenses/$license_id")->status_is( 204, 'REST3.2.4' ) + ->content_is( '', 'REST3.3.4' ); # Attempt to delete non-existent license - $t->delete_ok("//$userid:$password@/api/v1/erm/licenses/$license_id") - ->status_is(404); + $t->delete_ok("//$userid:$password@/api/v1/erm/licenses/$license_id")->status_is(404); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/api/v1/erm_users.t b/t/db_dependent/api/v1/erm_users.t index 04268c1db8..08454130ba 100755 --- a/t/db_dependent/api/v1/erm_users.t +++ b/t/db_dependent/api/v1/erm_users.t @@ -30,7 +30,7 @@ my $schema = Koha::Database->new->schema; my $builder = t::lib::TestBuilder->new; my $t = Test::Mojo->new('Koha::REST::V1'); -t::lib::Mocks::mock_preference( 'RESTBasicAuth', 1 ); +t::lib::Mocks::mock_preference( 'RESTBasicAuth', 1 ); t::lib::Mocks::mock_preference( 'ChildNeedsGuarantor', 0 ); subtest 'list() tests' => sub { @@ -86,10 +86,8 @@ subtest 'list() tests' => sub { [ $librarian->to_api( { user => $librarian } ), $another_erm_user->to_api( { user => $another_erm_user } ) ] ); # Warn on unsupported query parameter - $t->get_ok("//$userid:$password@/api/v1/erm/users?blah=blah") - ->status_is(400) - ->json_is( - [ { path => '/query/blah', message => 'Malformed query string' } ] ); + $t->get_ok("//$userid:$password@/api/v1/erm/users?blah=blah")->status_is(400) + ->json_is( [ { path => '/query/blah', message => 'Malformed query string' } ] ); my $patron = $builder->build_object( { diff --git a/t/db_dependent/api/v1/holds.t b/t/db_dependent/api/v1/holds.t index ff78fd5112..c7cd814ed5 100755 --- a/t/db_dependent/api/v1/holds.t +++ b/t/db_dependent/api/v1/holds.t @@ -47,23 +47,25 @@ t::lib::Mocks::mock_preference( 'RESTBasicAuth', 1 ); my $t = Test::Mojo->new('Koha::REST::V1'); -my $categorycode = $builder->build({ source => 'Category' })->{categorycode}; -my $branchcode = $builder->build({ source => 'Branch' })->{branchcode}; -my $branchcode2 = $builder->build({ source => 'Branch' })->{branchcode}; -my $itemtype = $builder->build({ source => 'Itemtype' })->{itemtype}; +my $categorycode = $builder->build( { source => 'Category' } )->{categorycode}; +my $branchcode = $builder->build( { source => 'Branch' } )->{branchcode}; +my $branchcode2 = $builder->build( { source => 'Branch' } )->{branchcode}; +my $itemtype = $builder->build( { source => 'Itemtype' } )->{itemtype}; # Generic password for everyone my $password = 'thePassword123'; # User without any permissions -my $nopermission = $builder->build_object({ - class => 'Koha::Patrons', - value => { - branchcode => $branchcode, - categorycode => $categorycode, - flags => 0 +my $nopermission = $builder->build_object( + { + class => 'Koha::Patrons', + value => { + branchcode => $branchcode, + categorycode => $categorycode, + flags => 0 + } } -}); +); $nopermission->set_password( { password => $password, skip_validation => 1 } ); my $nopermission_userid = $nopermission->userid; @@ -74,7 +76,7 @@ my $patron_1 = $builder->build_object( categorycode => $categorycode, branchcode => $branchcode, surname => 'Test Surname', - flags => 80, #borrowers and reserveforothers flags + flags => 80, #borrowers and reserveforothers flags } } ); @@ -88,7 +90,7 @@ my $patron_2 = $builder->build_object( categorycode => $categorycode, branchcode => $branchcode, surname => 'Test Surname 2', - flags => 16, # borrowers flag + flags => 16, # borrowers flag } } ); @@ -102,7 +104,7 @@ my $patron_3 = $builder->build_object( categorycode => $categorycode, branchcode => $branchcode, surname => 'Test Surname 3', - flags => 64, # reserveforothers flag + flags => 64, # reserveforothers flag } } ); @@ -110,10 +112,10 @@ $patron_3->set_password( { password => $password, skip_validation => 1 } ); my $userid_3 = $patron_3->userid; my $biblio_1 = $builder->build_sample_biblio; -my $item_1 = $builder->build_sample_item({ biblionumber => $biblio_1->biblionumber, itype => $itemtype }); +my $item_1 = $builder->build_sample_item( { biblionumber => $biblio_1->biblionumber, itype => $itemtype } ); my $biblio_2 = $builder->build_sample_biblio; -my $item_2 = $builder->build_sample_item({ biblionumber => $biblio_2->biblionumber, itype => $itemtype }); +my $item_2 = $builder->build_sample_item( { biblionumber => $biblio_2->biblionumber, itype => $itemtype } ); my $dbh = C4::Context->dbh; $dbh->do('DELETE FROM reserves'); @@ -124,7 +126,7 @@ Koha::CirculationRules->set_rules( branchcode => undef, itemtype => undef, rules => { - reservesallowed => 1, + reservesallowed => 1, holds_per_record => 99 } } @@ -151,8 +153,8 @@ my $reserve_id2 = C4::Reserves::AddReserve( } ); -my $suspended_until = DateTime->now->add(days => 10)->truncate( to => 'day' ); -my $expiration_date = DateTime->now->add(days => 10)->truncate( to => 'day' ); +my $suspended_until = DateTime->now->add( days => 10 )->truncate( to => 'day' ); +my $expiration_date = DateTime->now->add( days => 10 )->truncate( to => 'day' ); my $post_data = { patron_id => $patron_1->borrowernumber, @@ -168,116 +170,91 @@ my $patch_data = { subtest "Test endpoints without authentication" => sub { plan tests => 8; - $t->get_ok('/api/v1/holds') - ->status_is(401); - $t->post_ok('/api/v1/holds') - ->status_is(401); - $t->patch_ok('/api/v1/holds/0') - ->status_is(401); - $t->delete_ok('/api/v1/holds/0') - ->status_is(401); + $t->get_ok('/api/v1/holds')->status_is(401); + $t->post_ok('/api/v1/holds')->status_is(401); + $t->patch_ok('/api/v1/holds/0')->status_is(401); + $t->delete_ok('/api/v1/holds/0')->status_is(401); }; subtest "Test endpoints without permission" => sub { plan tests => 10; - $t->get_ok( "//$nopermission_userid:$password@/api/v1/holds?patron_id=" . $patron_1->borrowernumber ) # no permission - ->status_is(403); + $t->get_ok( + "//$nopermission_userid:$password@/api/v1/holds?patron_id=" . $patron_1->borrowernumber ) # no permission + ->status_is(403); - $t->get_ok( "//$userid_2:$password@/api/v1/holds?patron_id=" . $patron_1->borrowernumber ) # no permission - ->status_is(403); + $t->get_ok( "//$userid_2:$password@/api/v1/holds?patron_id=" . $patron_1->borrowernumber ) # no permission + ->status_is(403); - $t->post_ok( "//$nopermission_userid:$password@/api/v1/holds" => json => $post_data ) - ->status_is(403); + $t->post_ok( "//$nopermission_userid:$password@/api/v1/holds" => json => $post_data )->status_is(403); - $t->patch_ok( "//$nopermission_userid:$password@/api/v1/holds/0" => json => $patch_data ) - ->status_is(403); + $t->patch_ok( "//$nopermission_userid:$password@/api/v1/holds/0" => json => $patch_data )->status_is(403); - $t->delete_ok( "//$nopermission_userid:$password@/api/v1/holds/0" ) - ->status_is(403); + $t->delete_ok("//$nopermission_userid:$password@/api/v1/holds/0")->status_is(403); }; subtest "Test endpoints with permission" => sub { plan tests => 45; - $t->get_ok( "//$userid_1:$password@/api/v1/holds" ) - ->status_is(200) - ->json_has('/0') - ->json_has('/1') - ->json_hasnt('/2'); + $t->get_ok("//$userid_1:$password@/api/v1/holds")->status_is(200)->json_has('/0')->json_has('/1')->json_hasnt('/2'); - $t->get_ok( "//$userid_1:$password@/api/v1/holds?priority=2" ) - ->status_is(200) - ->json_is('/0/patron_id', $patron_2->borrowernumber) - ->json_hasnt('/1'); + $t->get_ok("//$userid_1:$password@/api/v1/holds?priority=2")->status_is(200) + ->json_is( '/0/patron_id', $patron_2->borrowernumber )->json_hasnt('/1'); - $t->delete_ok( "//$userid_3:$password@/api/v1/holds/$reserve_id" ) - ->status_is(204, 'REST3.2.4') - ->content_is('', 'REST3.3.4'); + $t->delete_ok("//$userid_3:$password@/api/v1/holds/$reserve_id")->status_is( 204, 'REST3.2.4' ) + ->content_is( '', 'REST3.3.4' ); - $t->patch_ok( "//$userid_3:$password@/api/v1/holds/$reserve_id" => json => $patch_data ) - ->status_is(404) - ->json_has('/error'); + $t->patch_ok( "//$userid_3:$password@/api/v1/holds/$reserve_id" => json => $patch_data )->status_is(404) + ->json_has('/error'); - $t->delete_ok( "//$userid_3:$password@/api/v1/holds/$reserve_id" ) - ->status_is(404) - ->json_has('/error'); + $t->delete_ok("//$userid_3:$password@/api/v1/holds/$reserve_id")->status_is(404)->json_has('/error'); - $t->get_ok( "//$userid_3:$password@/api/v1/holds?patron_id=" . $patron_1->borrowernumber ) - ->status_is(200) - ->json_is([]); + $t->get_ok( "//$userid_3:$password@/api/v1/holds?patron_id=" . $patron_1->borrowernumber )->status_is(200) + ->json_is( [] ); my $inexisting_borrowernumber = $patron_2->borrowernumber * 2; - $t->get_ok( "//$userid_1:$password@/api/v1/holds?patron_id=$inexisting_borrowernumber") - ->status_is(200) - ->json_is([]); + $t->get_ok("//$userid_1:$password@/api/v1/holds?patron_id=$inexisting_borrowernumber")->status_is(200) + ->json_is( [] ); $t->delete_ok( "//$userid_3:$password@/api/v1/holds/$reserve_id2" => json => "Cancellation reason" ) - ->status_is(204, 'REST3.2.4') - ->content_is('', 'REST3.3.4'); + ->status_is( 204, 'REST3.2.4' )->content_is( '', 'REST3.3.4' ); # Make sure pickup location checks doesn't get in the middle my $mock_biblio = Test::MockModule->new('Koha::Biblio'); - $mock_biblio->mock( 'pickup_locations', sub { return Koha::Libraries->search; }); - my $mock_item = Test::MockModule->new('Koha::Item'); - $mock_item->mock( 'pickup_locations', sub { return Koha::Libraries->search }); + $mock_biblio->mock( 'pickup_locations', sub { return Koha::Libraries->search; } ); + my $mock_item = Test::MockModule->new('Koha::Item'); + $mock_item->mock( 'pickup_locations', sub { return Koha::Libraries->search } ); - $t->post_ok( "//$userid_3:$password@/api/v1/holds" => json => $post_data ) - ->status_is(201) - ->json_has('/hold_id') + $t->post_ok( "//$userid_3:$password@/api/v1/holds" => json => $post_data )->status_is(201)->json_has('/hold_id') ->header_is( 'Location' => '/api/v1/holds/' . $t->tx->res->json->{hold_id}, "REST3.4.1" ); # Get id from response $reserve_id = $t->tx->res->json->{hold_id}; - $t->get_ok( "//$userid_1:$password@/api/v1/holds?patron_id=" . $patron_1->borrowernumber ) - ->status_is(200) - ->json_is('/0/hold_id', $reserve_id) - ->json_is('/0/expiration_date', output_pref({ dt => $expiration_date, dateformat => 'iso', dateonly => 1 })) - ->json_is('/0/pickup_library_id', $branchcode); + $t->get_ok( "//$userid_1:$password@/api/v1/holds?patron_id=" . $patron_1->borrowernumber )->status_is(200) + ->json_is( '/0/hold_id', $reserve_id ) + ->json_is( '/0/expiration_date', output_pref( { dt => $expiration_date, dateformat => 'iso', dateonly => 1 } ) ) + ->json_is( '/0/pickup_library_id', $branchcode ); - $t->post_ok( "//$userid_3:$password@/api/v1/holds" => json => $post_data ) - ->status_is(403) - ->json_like('/error', qr/itemAlreadyOnHold/); + $t->post_ok( "//$userid_3:$password@/api/v1/holds" => json => $post_data )->status_is(403) + ->json_like( '/error', qr/itemAlreadyOnHold/ ); $post_data->{biblio_id} = $biblio_2->biblionumber; $post_data->{item_id} = $item_2->itemnumber; - $t->post_ok( "//$userid_3:$password@/api/v1/holds" => json => $post_data ) - ->status_is(403) - ->json_like('/error', qr/Hold cannot be placed. Reason: tooManyReserves/); + $t->post_ok( "//$userid_3:$password@/api/v1/holds" => json => $post_data )->status_is(403) + ->json_like( '/error', qr/Hold cannot be placed. Reason: tooManyReserves/ ); - my $to_delete_patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $to_delete_patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $deleted_patron_id = $to_delete_patron->borrowernumber; $to_delete_patron->delete; my $tmp_patron_id = $post_data->{patron_id}; $post_data->{patron_id} = $deleted_patron_id; - $t->post_ok( "//$userid_3:$password@/api/v1/holds" => json => $post_data ) - ->status_is(400) - ->json_is( { error => 'patron_id not found' } ); + $t->post_ok( "//$userid_3:$password@/api/v1/holds" => json => $post_data )->status_is(400) + ->json_is( { error => 'patron_id not found' } ); # Restore the original patron_id as it is expected by the next subtest # FIXME: this tests need to be rewritten from scratch @@ -288,42 +265,36 @@ subtest 'Reserves with itemtype' => sub { plan tests => 10; my $post_data = { - patron_id => int($patron_1->borrowernumber), - biblio_id => int($biblio_1->biblionumber), + patron_id => int( $patron_1->borrowernumber ), + biblio_id => int( $biblio_1->biblionumber ), pickup_library_id => $branchcode, - item_type => $itemtype, + item_type => $itemtype, }; - $t->delete_ok( "//$userid_3:$password@/api/v1/holds/$reserve_id" ) - ->status_is(204, 'REST3.2.4') - ->content_is('', 'REST3.3.4'); + $t->delete_ok("//$userid_3:$password@/api/v1/holds/$reserve_id")->status_is( 204, 'REST3.2.4' ) + ->content_is( '', 'REST3.3.4' ); # Make sure pickup location checks doesn't get in the middle my $mock_biblio = Test::MockModule->new('Koha::Biblio'); - $mock_biblio->mock( 'pickup_locations', sub { return Koha::Libraries->search; }); - my $mock_item = Test::MockModule->new('Koha::Item'); - $mock_item->mock( 'pickup_locations', sub { return Koha::Libraries->search }); + $mock_biblio->mock( 'pickup_locations', sub { return Koha::Libraries->search; } ); + my $mock_item = Test::MockModule->new('Koha::Item'); + $mock_item->mock( 'pickup_locations', sub { return Koha::Libraries->search } ); - $t->post_ok( "//$userid_3:$password@/api/v1/holds" => json => $post_data ) - ->status_is(201) - ->json_has('/hold_id'); + $t->post_ok( "//$userid_3:$password@/api/v1/holds" => json => $post_data )->status_is(201)->json_has('/hold_id'); $reserve_id = $t->tx->res->json->{hold_id}; - $t->get_ok( "//$userid_1:$password@/api/v1/holds?patron_id=" . $patron_1->borrowernumber ) - ->status_is(200) - ->json_is('/0/hold_id', $reserve_id) - ->json_is('/0/item_type', $itemtype); + $t->get_ok( "//$userid_1:$password@/api/v1/holds?patron_id=" . $patron_1->borrowernumber )->status_is(200) + ->json_is( '/0/hold_id', $reserve_id )->json_is( '/0/item_type', $itemtype ); }; - subtest 'test AllowHoldDateInFuture' => sub { plan tests => 6; $dbh->do('DELETE FROM reserves'); - my $future_hold_date = DateTime->now->add(days => 10)->truncate( to => 'day' ); + my $future_hold_date = DateTime->now->add( days => 10 )->truncate( to => 'day' ); my $post_data = { patron_id => $patron_1->borrowernumber, @@ -336,21 +307,18 @@ subtest 'test AllowHoldDateInFuture' => sub { t::lib::Mocks::mock_preference( 'AllowHoldDateInFuture', 0 ); - $t->post_ok( "//$userid_3:$password@/api/v1/holds" => json => $post_data ) - ->status_is(400) - ->json_has('/error'); + $t->post_ok( "//$userid_3:$password@/api/v1/holds" => json => $post_data )->status_is(400)->json_has('/error'); t::lib::Mocks::mock_preference( 'AllowHoldDateInFuture', 1 ); # Make sure pickup location checks doesn't get in the middle my $mock_biblio = Test::MockModule->new('Koha::Biblio'); - $mock_biblio->mock( 'pickup_locations', sub { return Koha::Libraries->search; }); - my $mock_item = Test::MockModule->new('Koha::Item'); - $mock_item->mock( 'pickup_locations', sub { return Koha::Libraries->search }); + $mock_biblio->mock( 'pickup_locations', sub { return Koha::Libraries->search; } ); + my $mock_item = Test::MockModule->new('Koha::Item'); + $mock_item->mock( 'pickup_locations', sub { return Koha::Libraries->search } ); - $t->post_ok( "//$userid_3:$password@/api/v1/holds" => json => $post_data ) - ->status_is(201) - ->json_is('/hold_date', output_pref({ dt => $future_hold_date, dateformat => 'iso', dateonly => 1 })); + $t->post_ok( "//$userid_3:$password@/api/v1/holds" => json => $post_data )->status_is(201) + ->json_is( '/hold_date', output_pref( { dt => $future_hold_date, dateformat => 'iso', dateonly => 1 } ) ); }; $schema->storage->txn_rollback; @@ -372,17 +340,21 @@ subtest 'x-koha-override and AllowHoldPolicyOverride tests' => sub { $patron->discard_changes; my $userid = $patron->userid; - my $renegade_library = $builder->build_object({ class => 'Koha::Libraries' }); + my $renegade_library = $builder->build_object( { class => 'Koha::Libraries' } ); t::lib::Mocks::mock_preference( 'AllowHoldPolicyOverride', 0 ); # Make sure pickup location checks doesn't get in the middle my $mock_biblio = Test::MockModule->new('Koha::Biblio'); - $mock_biblio->mock( 'pickup_locations', - sub { return Koha::Libraries->search({ branchcode => { '!=' => $renegade_library->branchcode } }); } ); + $mock_biblio->mock( + 'pickup_locations', + sub { return Koha::Libraries->search( { branchcode => { '!=' => $renegade_library->branchcode } } ); } + ); my $mock_item = Test::MockModule->new('Koha::Item'); - $mock_item->mock( 'pickup_locations', - sub { return Koha::Libraries->search({ branchcode => { '!=' => $renegade_library->branchcode } }) } ); + $mock_item->mock( + 'pickup_locations', + sub { return Koha::Libraries->search( { branchcode => { '!=' => $renegade_library->branchcode } } ) } + ); my $can_item_be_reserved_result; my $mock_reserves = Test::MockModule->new('C4::Reserves'); @@ -404,51 +376,42 @@ subtest 'x-koha-override and AllowHoldPolicyOverride tests' => sub { $can_item_be_reserved_result = { status => 'ageRestricted' }; - $t->post_ok( "//$userid:$password@/api/v1/holds" => json => $post_data ) - ->status_is(403) - ->json_is( '/error' => "Hold cannot be placed. Reason: ageRestricted" ); + $t->post_ok( "//$userid:$password@/api/v1/holds" => json => $post_data )->status_is(403) + ->json_is( '/error' => "Hold cannot be placed. Reason: ageRestricted" ); # x-koha-override doesn't override if AllowHoldPolicyOverride not set - $t->post_ok( "//$userid:$password@/api/v1/holds" => - { 'x-koha-override' => 'any' } => json => $post_data ) - ->status_is(403); + $t->post_ok( "//$userid:$password@/api/v1/holds" => { 'x-koha-override' => 'any' } => json => $post_data ) + ->status_is(403); t::lib::Mocks::mock_preference( 'AllowHoldPolicyOverride', 1 ); $can_item_be_reserved_result = { status => 'pickupNotInHoldGroup' }; - $t->post_ok( "//$userid:$password@/api/v1/holds" => json => $post_data ) - ->status_is(403) - ->json_is( - '/error' => "Hold cannot be placed. Reason: pickupNotInHoldGroup" ); + $t->post_ok( "//$userid:$password@/api/v1/holds" => json => $post_data )->status_is(403) + ->json_is( '/error' => "Hold cannot be placed. Reason: pickupNotInHoldGroup" ); # x-koha-override overrides the status - $t->post_ok( "//$userid:$password@/api/v1/holds" => - { 'x-koha-override' => 'any' } => json => $post_data ) - ->status_is(201); + $t->post_ok( "//$userid:$password@/api/v1/holds" => { 'x-koha-override' => 'any' } => json => $post_data ) + ->status_is(201); $can_item_be_reserved_result = { status => 'OK' }; # x-koha-override works when status not need override - $t->post_ok( "//$userid:$password@/api/v1/holds" => - { 'x-koha-override' => 'any' } => json => $post_data ) - ->status_is(201); + $t->post_ok( "//$userid:$password@/api/v1/holds" => { 'x-koha-override' => 'any' } => json => $post_data ) + ->status_is(201); # Test pickup locations can be overridden $post_data->{pickup_library_id} = $renegade_library->branchcode; - $t->post_ok( "//$userid:$password@/api/v1/holds" => json => $post_data ) - ->status_is(400); + $t->post_ok( "//$userid:$password@/api/v1/holds" => json => $post_data )->status_is(400); - $t->post_ok( "//$userid:$password@/api/v1/holds" => - { 'x-koha-override' => 'any' } => json => $post_data ) - ->status_is(201); + $t->post_ok( "//$userid:$password@/api/v1/holds" => { 'x-koha-override' => 'any' } => json => $post_data ) + ->status_is(201); - t::lib::Mocks::mock_preference( 'AllowHoldPolicyOverride', 0); + t::lib::Mocks::mock_preference( 'AllowHoldPolicyOverride', 0 ); - $t->post_ok( "//$userid:$password@/api/v1/holds" => - { 'x-koha-override' => 'any' } => json => $post_data ) - ->status_is(400); + $t->post_ok( "//$userid:$password@/api/v1/holds" => { 'x-koha-override' => 'any' } => json => $post_data ) + ->status_is(400); $schema->storage->txn_rollback; }; @@ -461,8 +424,7 @@ subtest 'suspend and resume tests' => sub { my $password = 'AbcdEFG123'; - my $patron = $builder->build_object( - { class => 'Koha::Patrons', value => { userid => 'tomasito', flags => 0 } } ); + my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { userid => 'tomasito', flags => 0 } } ); $builder->build( { source => 'UserPermission', @@ -474,7 +436,7 @@ subtest 'suspend and resume tests' => sub { } ); - $patron->set_password({ password => $password, skip_validation => 1 }); + $patron->set_password( { password => $password, skip_validation => 1 } ); my $userid = $patron->userid; # Disable logging @@ -482,7 +444,8 @@ subtest 'suspend and resume tests' => sub { t::lib::Mocks::mock_preference( 'RESTBasicAuth', 1 ); my $hold = $builder->build_object( - { class => 'Koha::Holds', + { + class => 'Koha::Holds', value => { suspend => 0, suspend_until => undef, waitingdate => undef, found => undef } } ); @@ -494,62 +457,62 @@ subtest 'suspend and resume tests' => sub { $hold->discard_changes; # refresh object ok( $hold->is_suspended, 'Hold is suspended' ); - $t->json_is('/end_date', undef, 'Hold suspension has no end date'); + $t->json_is( '/end_date', undef, 'Hold suspension has no end date' ); - my $end_date = output_pref({ - dt => dt_from_string( undef ), - dateformat => 'iso', - dateonly => 1 - }); + my $end_date = output_pref( + { + dt => dt_from_string(undef), + dateformat => 'iso', + dateonly => 1 + } + ); - $t->post_ok( "//$userid:$password@/api/v1/holds/" . $hold->id . "/suspension" => json => { end_date => $end_date } ); + $t->post_ok( + "//$userid:$password@/api/v1/holds/" . $hold->id . "/suspension" => json => { end_date => $end_date } ); $hold->discard_changes; # refresh object ok( $hold->is_suspended, 'Hold is suspended' ); $t->json_is( - '/end_date', - output_pref({ - dt => dt_from_string( $hold->suspend_until ), - dateformat => 'iso', - dateonly => 1 - }), - 'Hold suspension has correct end date' + '/end_date', + output_pref( + { + dt => dt_from_string( $hold->suspend_until ), + dateformat => 'iso', + dateonly => 1 + } + ), + 'Hold suspension has correct end date' ); - $t->delete_ok( "//$userid:$password@/api/v1/holds/" . $hold->id . "/suspension" ) - ->status_is(204, 'REST3.2.4') - ->content_is('', 'REST3.3.4'); + $t->delete_ok( "//$userid:$password@/api/v1/holds/" . $hold->id . "/suspension" )->status_is( 204, 'REST3.2.4' ) + ->content_is( '', 'REST3.3.4' ); # Pass a an expiration date for the suspension my $date = dt_from_string()->add( days => 5 ); - $t->post_ok( - "//$userid:$password@/api/v1/holds/" + $t->post_ok( "//$userid:$password@/api/v1/holds/" . $hold->id - . "/suspension" => json => { - end_date => - output_pref( { dt => $date, dateformat => 'iso', dateonly => 1 } ) - } - )->status_is( 201, 'Hold suspension created' ) - ->json_is( '/end_date', - output_pref( { dt => $date, dateformat => 'iso', dateonly => 1 } ) ) - ->header_is( Location => "/api/v1/holds/" . $hold->id . "/suspension", 'The Location header is set' ); + . "/suspension" => json => + { end_date => output_pref( { dt => $date, dateformat => 'iso', dateonly => 1 } ) } ) + ->status_is( 201, 'Hold suspension created' )->json_is( + '/end_date', + output_pref( { dt => $date, dateformat => 'iso', dateonly => 1 } ) + )->header_is( Location => "/api/v1/holds/" . $hold->id . "/suspension", 'The Location header is set' ); - $t->delete_ok( "//$userid:$password@/api/v1/holds/" . $hold->id . "/suspension" ) - ->status_is(204, 'REST3.2.4') - ->content_is('', 'REST3.3.4'); + $t->delete_ok( "//$userid:$password@/api/v1/holds/" . $hold->id . "/suspension" )->status_is( 204, 'REST3.2.4' ) + ->content_is( '', 'REST3.3.4' ); $hold->set_waiting->discard_changes; $t->post_ok( "//$userid:$password@/api/v1/holds/" . $hold->id . "/suspension" ) - ->status_is( 400, 'Cannot suspend waiting hold' ) - ->json_is( '/error', 'Found hold cannot be suspended. Status=W' ); + ->status_is( 400, 'Cannot suspend waiting hold' ) + ->json_is( '/error', 'Found hold cannot be suspended. Status=W' ); $hold->set_transfer->discard_changes; $t->post_ok( "//$userid:$password@/api/v1/holds/" . $hold->id . "/suspension" ) - ->status_is( 400, 'Cannot suspend hold on transfer' ) - ->json_is( '/error', 'Found hold cannot be suspended. Status=T' ); + ->status_is( 400, 'Cannot suspend hold on transfer' ) + ->json_is( '/error', 'Found hold cannot be suspended. Status=T' ); $schema->storage->txn_rollback; }; @@ -562,14 +525,12 @@ subtest 'PUT /holds/{hold_id}/priority tests' => sub { my $password = 'AbcdEFG123'; - my $library = $builder->build_object({ class => 'Koha::Libraries' }); - my $patron_np = $builder->build_object( - { class => 'Koha::Patrons', value => { flags => 0 } } ); + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); + my $patron_np = $builder->build_object( { class => 'Koha::Patrons', value => { flags => 0 } } ); $patron_np->set_password( { password => $password, skip_validation => 1 } ); my $userid_np = $patron_np->userid; - my $patron = $builder->build_object( - { class => 'Koha::Patrons', value => { flags => 0 } } ); + my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { flags => 0 } } ); $patron->set_password( { password => $password, skip_validation => 1 } ); my $userid = $patron->userid; $builder->build( @@ -638,21 +599,17 @@ subtest 'PUT /holds/{hold_id}/priority tests' => sub { ) ); - $t->put_ok( "//$userid_np:$password@/api/v1/holds/" - . $hold_3->id - . "/priority" => json => 1 )->status_is(403); + $t->put_ok( "//$userid_np:$password@/api/v1/holds/" . $hold_3->id . "/priority" => json => 1 )->status_is(403); - $t->put_ok( "//$userid:$password@/api/v1/holds/" - . $hold_3->id - . "/priority" => json => 1 )->status_is(200)->json_is(1); + $t->put_ok( "//$userid:$password@/api/v1/holds/" . $hold_3->id . "/priority" => json => 1 )->status_is(200) + ->json_is(1); is( $hold_1->discard_changes->priority, 2, 'Priority adjusted correctly' ); is( $hold_2->discard_changes->priority, 3, 'Priority adjusted correctly' ); is( $hold_3->discard_changes->priority, 1, 'Priority adjusted correctly' ); - $t->put_ok( "//$userid:$password@/api/v1/holds/" - . $hold_3->id - . "/priority" => json => 3 )->status_is(200)->json_is(3); + $t->put_ok( "//$userid:$password@/api/v1/holds/" . $hold_3->id . "/priority" => json => 3 )->status_is(200) + ->json_is(3); is( $hold_1->discard_changes->priority, 1, 'Priority adjusted correctly' ); is( $hold_2->discard_changes->priority, 2, 'Priority adjusted correctly' ); @@ -673,9 +630,8 @@ subtest 'add() tests (maxreserves behaviour)' => sub { my $password = 'AbcdEFG123'; - my $patron = $builder->build_object( - { class => 'Koha::Patrons', value => { userid => 'tomasito', flags => 1 } } ); - $patron->set_password({ password => $password, skip_validation => 1 }); + my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { userid => 'tomasito', flags => 1 } } ); + $patron->set_password( { password => $password, skip_validation => 1 } ); my $userid = $patron->userid; Koha::CirculationRules->set_rules( @@ -683,9 +639,7 @@ subtest 'add() tests (maxreserves behaviour)' => sub { itemtype => undef, branchcode => undef, categorycode => undef, - rules => { - reservesallowed => 3 - } + rules => { reservesallowed => 3 } } ); @@ -694,74 +648,71 @@ subtest 'add() tests (maxreserves behaviour)' => sub { branchcode => undef, categorycode => $patron->categorycode, rules => { - max_holds => 4, + max_holds => 4, } } ); my $biblio_1 = $builder->build_sample_biblio; - my $item_1 = $builder->build_sample_item({ biblionumber => $biblio_1->biblionumber }); + my $item_1 = $builder->build_sample_item( { biblionumber => $biblio_1->biblionumber } ); my $biblio_2 = $builder->build_sample_biblio; - my $item_2 = $builder->build_sample_item({ biblionumber => $biblio_2->biblionumber }); + my $item_2 = $builder->build_sample_item( { biblionumber => $biblio_2->biblionumber } ); my $biblio_3 = $builder->build_sample_biblio; - my $item_3 = $builder->build_sample_item({ biblionumber => $biblio_3->biblionumber }); + my $item_3 = $builder->build_sample_item( { biblionumber => $biblio_3->biblionumber } ); # Make sure pickup location checks doesn't get in the middle my $mock_biblio = Test::MockModule->new('Koha::Biblio'); - $mock_biblio->mock( 'pickup_locations', sub { return Koha::Libraries->search; }); - my $mock_item = Test::MockModule->new('Koha::Item'); - $mock_item->mock( 'pickup_locations', sub { return Koha::Libraries->search }); + $mock_biblio->mock( 'pickup_locations', sub { return Koha::Libraries->search; } ); + my $mock_item = Test::MockModule->new('Koha::Item'); + $mock_item->mock( 'pickup_locations', sub { return Koha::Libraries->search } ); # Disable logging - t::lib::Mocks::mock_preference( 'HoldsLog', 0 ); - t::lib::Mocks::mock_preference( 'RESTBasicAuth', 1 ); - t::lib::Mocks::mock_preference( 'maxreserves', 2 ); + t::lib::Mocks::mock_preference( 'HoldsLog', 0 ); + t::lib::Mocks::mock_preference( 'RESTBasicAuth', 1 ); + t::lib::Mocks::mock_preference( 'maxreserves', 2 ); t::lib::Mocks::mock_preference( 'AllowHoldPolicyOverride', 0 ); my $post_data = { - patron_id => $patron->borrowernumber, - biblio_id => $biblio_1->biblionumber, + patron_id => $patron->borrowernumber, + biblio_id => $biblio_1->biblionumber, pickup_library_id => $item_1->home_branch->branchcode, - item_type => $item_1->itype, + item_type => $item_1->itype, }; - $t->post_ok( "//$userid:$password@/api/v1/holds" => json => $post_data ) - ->status_is(201); + $t->post_ok( "//$userid:$password@/api/v1/holds" => json => $post_data )->status_is(201); $post_data = { - patron_id => $patron->borrowernumber, - biblio_id => $biblio_2->biblionumber, + patron_id => $patron->borrowernumber, + biblio_id => $biblio_2->biblionumber, pickup_library_id => $item_2->home_branch->branchcode, - item_id => $item_2->itemnumber + item_id => $item_2->itemnumber }; - $t->post_ok( "//$userid:$password@/api/v1/holds" => json => $post_data ) - ->status_is(201); + $t->post_ok( "//$userid:$password@/api/v1/holds" => json => $post_data )->status_is(201); $post_data = { - patron_id => $patron->borrowernumber, - biblio_id => $biblio_3->biblionumber, + patron_id => $patron->borrowernumber, + biblio_id => $biblio_3->biblionumber, pickup_library_id => $item_1->home_branch->branchcode, - item_id => $item_3->itemnumber + item_id => $item_3->itemnumber }; - $t->post_ok( "//$userid:$password@/api/v1/holds" => json => $post_data ) - ->status_is(403) - ->json_is( { error => 'Hold cannot be placed. Reason: tooManyReserves' } ); + $t->post_ok( "//$userid:$password@/api/v1/holds" => json => $post_data )->status_is(403) + ->json_is( { error => 'Hold cannot be placed. Reason: tooManyReserves' } ); t::lib::Mocks::mock_preference( 'maxreserves', 0 ); $t->post_ok( "//$userid:$password@/api/v1/holds" => json => $post_data ) - ->status_is(201, 'maxreserves == 0 => no limit'); + ->status_is( 201, 'maxreserves == 0 => no limit' ); # cleanup for the next tests my $hold_id = $t->tx->res->json->{hold_id}; - Koha::Holds->find( $hold_id )->delete; + Koha::Holds->find($hold_id)->delete; t::lib::Mocks::mock_preference( 'maxreserves', undef ); $t->post_ok( "//$userid:$password@/api/v1/holds" => json => $post_data ) - ->status_is(201, 'maxreserves == undef => no limit'); + ->status_is( 201, 'maxreserves == undef => no limit' ); $schema->storage->txn_rollback; }; @@ -926,9 +877,8 @@ subtest 'edit() tests' => sub { my $password = 'AbcdEFG123'; - my $library = $builder->build_object({ class => 'Koha::Libraries' }); - my $patron = $builder->build_object( - { class => 'Koha::Patrons', value => { flags => 1 } } ); + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); + my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { flags => 1 } } ); $patron->set_password( { password => $password, skip_validation => 1 } ); my $userid = $patron->userid; $builder->build( @@ -943,28 +893,35 @@ subtest 'edit() tests' => sub { ); # Disable logging - t::lib::Mocks::mock_preference( 'HoldsLog', 0 ); - t::lib::Mocks::mock_preference( 'RESTBasicAuth', 1 ); + t::lib::Mocks::mock_preference( 'HoldsLog', 0 ); + t::lib::Mocks::mock_preference( 'RESTBasicAuth', 1 ); t::lib::Mocks::mock_preference( 'AllowHoldPolicyOverride', 1 ); my $mock_biblio = Test::MockModule->new('Koha::Biblio'); my $mock_item = Test::MockModule->new('Koha::Item'); - my $library_1 = $builder->build_object({ class => 'Koha::Libraries' }); - my $library_2 = $builder->build_object({ class => 'Koha::Libraries' }); - my $library_3 = $builder->build_object({ class => 'Koha::Libraries' }); + my $library_1 = $builder->build_object( { class => 'Koha::Libraries' } ); + my $library_2 = $builder->build_object( { class => 'Koha::Libraries' } ); + my $library_3 = $builder->build_object( { class => 'Koha::Libraries' } ); # let's control what Koha::Biblio->pickup_locations returns, for testing - $mock_biblio->mock( 'pickup_locations', sub { - return Koha::Libraries->search( { branchcode => [ $library_2->branchcode, $library_3->branchcode ] } ); - }); + $mock_biblio->mock( + 'pickup_locations', + sub { + return Koha::Libraries->search( { branchcode => [ $library_2->branchcode, $library_3->branchcode ] } ); + } + ); + # let's mock what Koha::Item->pickup_locations returns, for testing - $mock_item->mock( 'pickup_locations', sub { - return Koha::Libraries->search( { branchcode => [ $library_2->branchcode, $library_3->branchcode ] } ); - }); + $mock_item->mock( + 'pickup_locations', + sub { + return Koha::Libraries->search( { branchcode => [ $library_2->branchcode, $library_3->branchcode ] } ); + } + ); my $biblio = $builder->build_sample_biblio; - my $item = $builder->build_sample_item({ biblionumber => $biblio->biblionumber }); + my $item = $builder->build_sample_item( { biblionumber => $biblio->biblionumber } ); # Test biblio-level holds my $biblio_hold = $builder->build_object( @@ -982,51 +939,36 @@ subtest 'edit() tests' => sub { ); my $biblio_hold_api_data = $biblio_hold->to_api; - my $biblio_hold_data = { + my $biblio_hold_data = { pickup_library_id => $library_1->branchcode, priority => $biblio_hold_api_data->{priority} }; - $t->patch_ok( "//$userid:$password@/api/v1/holds/" - . $biblio_hold->id - => json => $biblio_hold_data ) - ->status_is(400) - ->json_is({ error => 'The supplied pickup location is not valid' }); + $t->patch_ok( "//$userid:$password@/api/v1/holds/" . $biblio_hold->id => json => $biblio_hold_data ) + ->status_is(400)->json_is( { error => 'The supplied pickup location is not valid' } ); - $t->put_ok( "//$userid:$password@/api/v1/holds/" - . $biblio_hold->id - => json => $biblio_hold_data ) - ->status_is(400) - ->json_is({ error => 'The supplied pickup location is not valid' }); + $t->put_ok( "//$userid:$password@/api/v1/holds/" . $biblio_hold->id => json => $biblio_hold_data )->status_is(400) + ->json_is( { error => 'The supplied pickup location is not valid' } ); $biblio_hold->discard_changes; is( $biblio_hold->branchcode, $library_3->branchcode, 'branchcode remains untouched' ); - $t->patch_ok( "//$userid:$password@/api/v1/holds/" . $biblio_hold->id - => { 'x-koha-override' => 'any' } - => json => $biblio_hold_data ) - ->status_is(200) - ->json_has( '/pickup_library_id' => $library_1->id ); + $t->patch_ok( "//$userid:$password@/api/v1/holds/" + . $biblio_hold->id => { 'x-koha-override' => 'any' } => json => $biblio_hold_data )->status_is(200) + ->json_has( '/pickup_library_id' => $library_1->id ); - $t->put_ok( "//$userid:$password@/api/v1/holds/" . $biblio_hold->id - => { 'x-koha-override' => 'any' } - => json => $biblio_hold_data ) - ->status_is(200) - ->json_has( '/pickup_library_id' => $library_1->id ); + $t->put_ok( "//$userid:$password@/api/v1/holds/" + . $biblio_hold->id => { 'x-koha-override' => 'any' } => json => $biblio_hold_data )->status_is(200) + ->json_has( '/pickup_library_id' => $library_1->id ); $biblio_hold_data->{pickup_library_id} = $library_2->branchcode; - $t->patch_ok( "//$userid:$password@/api/v1/holds/" - . $biblio_hold->id - => json => $biblio_hold_data ) - ->status_is(200); + $t->patch_ok( "//$userid:$password@/api/v1/holds/" . $biblio_hold->id => json => $biblio_hold_data ) + ->status_is(200); $biblio_hold->discard_changes; is( $biblio_hold->branchcode, $library_2->id, 'Pickup location changed correctly' ); - $t->put_ok( "//$userid:$password@/api/v1/holds/" - . $biblio_hold->id - => json => $biblio_hold_data ) - ->status_is(200); + $t->put_ok( "//$userid:$password@/api/v1/holds/" . $biblio_hold->id => json => $biblio_hold_data )->status_is(200); $biblio_hold->discard_changes; is( $biblio_hold->branchcode, $library_2->id, 'Pickup location changed correctly' ); @@ -1043,7 +985,6 @@ subtest 'edit() tests' => sub { is( $biblio_hold->reservedate, '2022-01-02', 'Hold date changed correctly' ); is( $biblio_hold->expirationdate, '2022-03-02', 'Expiration date changed correctly' ); - # Test item-level holds my $item_hold = $builder->build_object( { @@ -1062,53 +1003,37 @@ subtest 'edit() tests' => sub { ); my $item_hold_api_data = $item_hold->to_api; - my $item_hold_data = { + my $item_hold_data = { pickup_library_id => $library_1->branchcode, priority => $item_hold_api_data->{priority} }; - $t->patch_ok( "//$userid:$password@/api/v1/holds/" - . $item_hold->id - => json => $item_hold_data ) - ->status_is(400) - ->json_is({ error => 'The supplied pickup location is not valid' }); + $t->patch_ok( "//$userid:$password@/api/v1/holds/" . $item_hold->id => json => $item_hold_data )->status_is(400) + ->json_is( { error => 'The supplied pickup location is not valid' } ); - $t->put_ok( "//$userid:$password@/api/v1/holds/" - . $item_hold->id - => json => $item_hold_data ) - ->status_is(400) - ->json_is({ error => 'The supplied pickup location is not valid' }); + $t->put_ok( "//$userid:$password@/api/v1/holds/" . $item_hold->id => json => $item_hold_data )->status_is(400) + ->json_is( { error => 'The supplied pickup location is not valid' } ); $item_hold->discard_changes; is( $item_hold->branchcode, $library_3->branchcode, 'branchcode remains untouched' ); - $t->patch_ok( "//$userid:$password@/api/v1/holds/" . $item_hold->id - => { 'x-koha-override' => 'any' } - => json => $item_hold_data ) - ->status_is(200) - ->json_has( '/pickup_library_id' => $library_1->id ); - - $t->put_ok( "//$userid:$password@/api/v1/holds/" . $item_hold->id - => { 'x-koha-override' => 'any' } - => json => $item_hold_data ) - ->status_is(200) - ->json_has( '/pickup_library_id' => $library_1->id ); - - $item_hold_data->{pickup_library_id} = $library_2->branchcode; $t->patch_ok( "//$userid:$password@/api/v1/holds/" - . $item_hold->id - => json => $item_hold_data ) - ->status_is(200); + . $item_hold->id => { 'x-koha-override' => 'any' } => json => $item_hold_data )->status_is(200) + ->json_has( '/pickup_library_id' => $library_1->id ); $t->put_ok( "//$userid:$password@/api/v1/holds/" - . $item_hold->id - => json => $item_hold_data ) - ->status_is(200); + . $item_hold->id => { 'x-koha-override' => 'any' } => json => $item_hold_data )->status_is(200) + ->json_has( '/pickup_library_id' => $library_1->id ); + + $item_hold_data->{pickup_library_id} = $library_2->branchcode; + $t->patch_ok( "//$userid:$password@/api/v1/holds/" . $item_hold->id => json => $item_hold_data )->status_is(200); + + $t->put_ok( "//$userid:$password@/api/v1/holds/" . $item_hold->id => json => $item_hold_data )->status_is(200); $item_hold->discard_changes; is( $item_hold->branchcode, $library_2->id, 'Pickup location changed correctly' ); - is( $item_hold->suspend, 0, 'Location change should not activate suspended status' ); + is( $item_hold->suspend, 0, 'Location change should not activate suspended status' ); is( $item_hold->suspend_until, undef, 'Location change should keep suspended_until be undef' ); $item_hold_data = { @@ -1134,9 +1059,8 @@ subtest 'add() tests' => sub { my $password = 'AbcdEFG123'; - my $library = $builder->build_object({ class => 'Koha::Libraries' }); - my $patron = $builder->build_object( - { class => 'Koha::Patrons', value => { flags => 1 } } ); + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); + my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { flags => 1 } } ); $patron->set_password( { password => $password, skip_validation => 1 } ); my $userid = $patron->userid; $builder->build( @@ -1157,18 +1081,25 @@ subtest 'add() tests' => sub { my $mock_biblio = Test::MockModule->new('Koha::Biblio'); my $mock_item = Test::MockModule->new('Koha::Item'); - my $library_1 = $builder->build_object({ class => 'Koha::Libraries' }); - my $library_2 = $builder->build_object({ class => 'Koha::Libraries' }); - my $library_3 = $builder->build_object({ class => 'Koha::Libraries' }); + my $library_1 = $builder->build_object( { class => 'Koha::Libraries' } ); + my $library_2 = $builder->build_object( { class => 'Koha::Libraries' } ); + my $library_3 = $builder->build_object( { class => 'Koha::Libraries' } ); # let's control what Koha::Biblio->pickup_locations returns, for testing - $mock_biblio->mock( 'pickup_locations', sub { - return Koha::Libraries->search( { branchcode => [ $library_2->branchcode, $library_3->branchcode ] } ); - }); + $mock_biblio->mock( + 'pickup_locations', + sub { + return Koha::Libraries->search( { branchcode => [ $library_2->branchcode, $library_3->branchcode ] } ); + } + ); + # let's mock what Koha::Item->pickup_locations returns, for testing - $mock_item->mock( 'pickup_locations', sub { - return Koha::Libraries->search( { branchcode => [ $library_2->branchcode, $library_3->branchcode ] } ); - }); + $mock_item->mock( + 'pickup_locations', + sub { + return Koha::Libraries->search( { branchcode => [ $library_2->branchcode, $library_3->branchcode ] } ); + } + ); my $can_biblio_be_reserved = 'OK'; my $can_item_be_reserved = 'OK'; @@ -1191,7 +1122,7 @@ subtest 'add() tests' => sub { ); my $biblio = $builder->build_sample_biblio; - my $item = $builder->build_sample_item({ biblionumber => $biblio->biblionumber }); + my $item = $builder->build_sample_item( { biblionumber => $biblio->biblionumber } ); # Test biblio-level holds my $biblio_hold = $builder->build_object( @@ -1214,13 +1145,11 @@ subtest 'add() tests' => sub { pickup_library_id => $library_1->branchcode, }; - $t->post_ok( "//$userid:$password@/api/v1/holds" => json => $biblio_hold_data ) - ->status_is(400) - ->json_is({ error => 'The supplied pickup location is not valid' }); + $t->post_ok( "//$userid:$password@/api/v1/holds" => json => $biblio_hold_data )->status_is(400) + ->json_is( { error => 'The supplied pickup location is not valid' } ); $biblio_hold_data->{pickup_library_id} = $library_2->branchcode; - $t->post_ok( "//$userid:$password@/api/v1/holds" => json => $biblio_hold_data ) - ->status_is(201); + $t->post_ok( "//$userid:$password@/api/v1/holds" => json => $biblio_hold_data )->status_is(201); # Test biblio-level holds my $item_group = Koha::Biblio::ItemGroup->new( { biblio_id => $biblio->id } )->store(); @@ -1245,13 +1174,11 @@ subtest 'add() tests' => sub { pickup_library_id => $library_1->branchcode, }; - $t->post_ok( "//$userid:$password@/api/v1/holds" => json => $biblio_hold_data ) - ->status_is(400) - ->json_is({ error => 'The supplied pickup location is not valid' }); + $t->post_ok( "//$userid:$password@/api/v1/holds" => json => $biblio_hold_data )->status_is(400) + ->json_is( { error => 'The supplied pickup location is not valid' } ); $biblio_hold_data->{pickup_library_id} = $library_2->branchcode; - $t->post_ok( "//$userid:$password@/api/v1/holds" => json => $biblio_hold_data ) - ->status_is(201); + $t->post_ok( "//$userid:$password@/api/v1/holds" => json => $biblio_hold_data )->status_is(201); # Test item-level holds my $item_hold = $builder->build_object( @@ -1275,9 +1202,8 @@ subtest 'add() tests' => sub { pickup_library_id => $library_1->branchcode, }; - $t->post_ok( "//$userid:$password@/api/v1/holds" => json => $item_hold_data ) - ->status_is(400) - ->json_is({ error => 'The supplied pickup location is not valid' }); + $t->post_ok( "//$userid:$password@/api/v1/holds" => json => $item_hold_data )->status_is(400) + ->json_is( { error => 'The supplied pickup location is not valid' } ); $can_item_be_reserved = 'notReservable'; $can_biblio_be_reserved = 'OK'; @@ -1285,32 +1211,35 @@ subtest 'add() tests' => sub { $item_hold_data->{pickup_library_id} = $library_2->branchcode; $t->post_ok( "//$userid:$password@/api/v1/holds" => json => $item_hold_data ) - ->status_is(403, 'Item checks performed when both biblio_id and item_id passed (Bug 35053)') - ->json_is({ error => 'Hold cannot be placed. Reason: notReservable' }); + ->status_is( 403, 'Item checks performed when both biblio_id and item_id passed (Bug 35053)' ) + ->json_is( { error => 'Hold cannot be placed. Reason: notReservable' } ); $can_item_be_reserved = 'OK'; $can_biblio_be_reserved = 'OK'; - $t->post_ok( "//$userid:$password@/api/v1/holds" => json => $item_hold_data ) - ->status_is(201); + $t->post_ok( "//$userid:$password@/api/v1/holds" => json => $item_hold_data )->status_is(201); # empty cases - $mock_biblio->mock( 'pickup_locations', sub { - return Koha::Libraries->new->empty; - }); + $mock_biblio->mock( + 'pickup_locations', + sub { + return Koha::Libraries->new->empty; + } + ); - $t->post_ok( "//$userid:$password@/api/v1/holds" => json => $biblio_hold_data ) - ->status_is(400) - ->json_is({ error => 'The supplied pickup location is not valid' }); + $t->post_ok( "//$userid:$password@/api/v1/holds" => json => $biblio_hold_data )->status_is(400) + ->json_is( { error => 'The supplied pickup location is not valid' } ); # empty cases - $mock_item->mock( 'pickup_locations', sub { - return Koha::Libraries->new->empty; - }); + $mock_item->mock( + 'pickup_locations', + sub { + return Koha::Libraries->new->empty; + } + ); - $t->post_ok( "//$userid:$password@/api/v1/holds" => json => $item_hold_data ) - ->status_is(400) - ->json_is({ error => 'The supplied pickup location is not valid' }); + $t->post_ok( "//$userid:$password@/api/v1/holds" => json => $item_hold_data )->status_is(400) + ->json_is( { error => 'The supplied pickup location is not valid' } ); $schema->storage->txn_rollback; }; @@ -1324,15 +1253,11 @@ subtest 'PUT /holds/{hold_id}/pickup_location tests' => sub { my $password = 'AbcdEFG123'; # library_1 and library_2 are available pickup locations, not library_3 - my $library_1 = $builder->build_object( - { class => 'Koha::Libraries', value => { pickup_location => 1 } } ); - my $library_2 = $builder->build_object( - { class => 'Koha::Libraries', value => { pickup_location => 1 } } ); - my $library_3 = $builder->build_object( - { class => 'Koha::Libraries', value => { pickup_location => 0 } } ); + my $library_1 = $builder->build_object( { class => 'Koha::Libraries', value => { pickup_location => 1 } } ); + my $library_2 = $builder->build_object( { class => 'Koha::Libraries', value => { pickup_location => 1 } } ); + my $library_3 = $builder->build_object( { class => 'Koha::Libraries', value => { pickup_location => 0 } } ); - my $patron = $builder->build_object( - { class => 'Koha::Patrons', value => { flags => 0 } } ); + my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { flags => 0 } } ); $patron->set_password( { password => $password, skip_validation => 1 } ); my $userid = $patron->userid; $builder->build( @@ -1372,18 +1297,16 @@ subtest 'PUT /holds/{hold_id}/pickup_location tests' => sub { ); $t->put_ok( "//$userid:$password@/api/v1/holds/" - . $hold->id - . "/pickup_location" => json => { pickup_library_id => $library_2->branchcode } ) - ->status_is(200) - ->json_is({ pickup_library_id => $library_2->branchcode }); + . $hold->id + . "/pickup_location" => json => { pickup_library_id => $library_2->branchcode } )->status_is(200) + ->json_is( { pickup_library_id => $library_2->branchcode } ); is( $hold->discard_changes->branchcode, $library_2->branchcode, 'pickup library adjusted correctly' ); $t->put_ok( "//$userid:$password@/api/v1/holds/" - . $hold->id - . "/pickup_location" => json => { pickup_library_id => $library_3->branchcode } ) - ->status_is(400) - ->json_is({ error => '[The supplied pickup location is not valid]' }); + . $hold->id + . "/pickup_location" => json => { pickup_library_id => $library_3->branchcode } )->status_is(400) + ->json_is( { error => '[The supplied pickup location is not valid]' } ); is( $hold->discard_changes->branchcode, $library_2->branchcode, 'pickup library unchanged' ); @@ -1402,10 +1325,9 @@ subtest 'PUT /holds/{hold_id}/pickup_location tests' => sub { # Attempt to use an invalid pickup locations ends in 400 $t->put_ok( "//$userid:$password@/api/v1/holds/" - . $hold->id - . "/pickup_location" => json => { pickup_library_id => $library_3->branchcode } ) - ->status_is(400) - ->json_is({ error => '[The supplied pickup location is not valid]' }); + . $hold->id + . "/pickup_location" => json => { pickup_library_id => $library_3->branchcode } )->status_is(400) + ->json_is( { error => '[The supplied pickup location is not valid]' } ); is( $hold->discard_changes->branchcode, $library_1->branchcode, 'pickup library unchanged' ); @@ -1413,42 +1335,39 @@ subtest 'PUT /holds/{hold_id}/pickup_location tests' => sub { # Attempt to use an invalid pickup locations with override succeeds $t->put_ok( "//$userid:$password@/api/v1/holds/" - . $hold->id - . "/pickup_location" - => { 'x-koha-override' => 'any' } - => json => { pickup_library_id => $library_2->branchcode } ) - ->status_is(200) - ->json_is({ pickup_library_id => $library_2->branchcode }); + . $hold->id + . "/pickup_location" => { 'x-koha-override' => 'any' } => json => + { pickup_library_id => $library_2->branchcode } )->status_is(200) + ->json_is( { pickup_library_id => $library_2->branchcode } ); is( $hold->discard_changes->branchcode, $library_2->branchcode, 'pickup library changed' ); t::lib::Mocks::mock_preference( 'AllowHoldPolicyOverride', 0 ); $t->put_ok( "//$userid:$password@/api/v1/holds/" - . $hold->id - . "/pickup_location" => json => { pickup_library_id => $library_2->branchcode } ) - ->status_is(200) - ->json_is({ pickup_library_id => $library_2->branchcode }); + . $hold->id + . "/pickup_location" => json => { pickup_library_id => $library_2->branchcode } )->status_is(200) + ->json_is( { pickup_library_id => $library_2->branchcode } ); is( $hold->discard_changes->branchcode, $library_2->branchcode, 'pickup library adjusted correctly' ); $t->put_ok( "//$userid:$password@/api/v1/holds/" - . $hold->id - . "/pickup_location" => json => { pickup_library_id => $library_3->branchcode } ) - ->status_is(400) - ->json_is({ error => '[The supplied pickup location is not valid]' }); + . $hold->id + . "/pickup_location" => json => { pickup_library_id => $library_3->branchcode } )->status_is(400) + ->json_is( { error => '[The supplied pickup location is not valid]' } ); is( $hold->discard_changes->branchcode, $library_2->branchcode, 'invalid pickup library not used' ); $t->put_ok( "//$userid:$password@/api/v1/holds/" - . $hold->id - . "/pickup_location" - => { 'x-koha-override' => 'any' } - => json => { pickup_library_id => $library_3->branchcode } ) - ->status_is(400) - ->json_is({ error => '[The supplied pickup location is not valid]' }); + . $hold->id + . "/pickup_location" => { 'x-koha-override' => 'any' } => json => + { pickup_library_id => $library_3->branchcode } )->status_is(400) + ->json_is( { error => '[The supplied pickup location is not valid]' } ); - is( $hold->discard_changes->branchcode, $library_2->branchcode, 'invalid pickup library not used, even if x-koha-override is passed' ); + is( + $hold->discard_changes->branchcode, $library_2->branchcode, + 'invalid pickup library not used, even if x-koha-override is passed' + ); my $waiting_hold = $builder->build_object( { class => 'Koha::Holds', value => { found => 'W' } } ); my $in_processing_hold = $builder->build_object( { class => 'Koha::Holds', value => { found => 'P' } } ); diff --git a/t/db_dependent/api/v1/idp.t b/t/db_dependent/api/v1/idp.t index c67b5124e0..262337be87 100755 --- a/t/db_dependent/api/v1/idp.t +++ b/t/db_dependent/api/v1/idp.t @@ -178,7 +178,10 @@ subtest 'provider endpoint tests' => sub { my $modified_provider_data = \%modified_provider_data_hash; $modified_provider_data->{code} = 'some_code'; - $tx = $t->ua->build_tx( PUT => "/api/v1/auth/identity_providers/" . $provider->identity_provider_id, json => $modified_provider_data ); + $tx = $t->ua->build_tx( + PUT => "/api/v1/auth/identity_providers/" . $provider->identity_provider_id, + json => $modified_provider_data + ); $tx->req->cookies( { name => 'CGISESSID', value => $session_id } ); $tx->req->env( { REMOTE_ADDR => $remote_address } ); @@ -217,7 +220,10 @@ subtest 'domain endpoint tests' => sub { my $provider = $builder->build_object( { class => 'Koha::Auth::Identity::Providers' } ); - my $tx = $t->ua->build_tx( POST => "/api/v1/auth/identity_providers/" . $provider->identity_provider_id . "/domains", json => $domain_not_matching ); + my $tx = $t->ua->build_tx( + POST => "/api/v1/auth/identity_providers/" . $provider->identity_provider_id . "/domains", + json => $domain_not_matching + ); $tx->req->cookies( { name => 'CGISESSID', value => $session_id } ); $tx->req->env( { REMOTE_ADDR => $remote_address } ); @@ -237,7 +243,10 @@ subtest 'domain endpoint tests' => sub { $modified_domain_data->{domain} = 'some.domain.com'; $tx = $t->ua->build_tx( - PUT => "/api/v1/auth/identity_providers/" . $provider->identity_provider_id . "/domains/" . $domain->identity_provider_domain_id, + PUT => "/api/v1/auth/identity_providers/" + . $provider->identity_provider_id + . "/domains/" + . $domain->identity_provider_domain_id, json => $modified_domain_data ); $tx->req->cookies( { name => 'CGISESSID', value => $session_id } ); @@ -245,13 +254,21 @@ subtest 'domain endpoint tests' => sub { $t->request_ok($tx)->status_is(200); - $tx = $t->ua->build_tx( GET => "/api/v1/auth/identity_providers/" . $provider->identity_provider_id . "/domains/" . $domain->identity_provider_domain_id ); + $tx = + $t->ua->build_tx( GET => "/api/v1/auth/identity_providers/" + . $provider->identity_provider_id + . "/domains/" + . $domain->identity_provider_domain_id ); $tx->req->cookies( { name => 'CGISESSID', value => $session_id } ); $tx->req->env( { REMOTE_ADDR => $remote_address } ); $t->request_ok($tx)->json_has( '/domain', 'some.domain.com' ); - $tx = $t->ua->build_tx( DELETE => "/api/v1/auth/identity_providers/" . $provider->identity_provider_id . "/domains/" . $domain->identity_provider_domain_id ); + $tx = + $t->ua->build_tx( DELETE => "/api/v1/auth/identity_providers/" + . $provider->identity_provider_id + . "/domains/" + . $domain->identity_provider_domain_id ); $tx->req->cookies( { name => 'CGISESSID', value => $session_id } ); $tx->req->env( { REMOTE_ADDR => $remote_address } ); @@ -307,7 +324,8 @@ sub create_user_and_session { my $flags = ( $args->{authorized} ) ? 1 : 0; my $user = $builder->build( - { source => 'Borrower', + { + source => 'Borrower', value => { flags => $flags } } ); diff --git a/t/db_dependent/api/v1/ill_backends.t b/t/db_dependent/api/v1/ill_backends.t index 58ac8e9d77..8d7d2307cd 100755 --- a/t/db_dependent/api/v1/ill_backends.t +++ b/t/db_dependent/api/v1/ill_backends.t @@ -82,7 +82,8 @@ subtest 'list() tests' => sub { # Mock Koha::ILL::Request::load_backend (to load Mocked Backend) my $illreqmodule = Test::MockModule->new('Koha::ILL::Request'); - $illreqmodule->mock( 'load_backend', + $illreqmodule->mock( + 'load_backend', sub { my $self = shift; $self->{_my_backend} = $backend; return $self } ); @@ -113,12 +114,7 @@ subtest 'list() tests' => sub { my $unauth_userid = $patron->userid; # Make sure the ILL_STATUS_ALIAS authorised value category is defined - unless ( - Koha::AuthorisedValueCategories->search( - { category_name => 'ILL_STATUS_ALIAS' } - )->count > 0 - ) - { + unless ( Koha::AuthorisedValueCategories->search( { category_name => 'ILL_STATUS_ALIAS' } )->count > 0 ) { $builder->build_object( { class => 'Koha::AuthorisedValueCategories', @@ -141,15 +137,13 @@ subtest 'list() tests' => sub { ); # No backends, expect empty - $t->get_ok("//$userid:$password@/api/v1/ill/backends")->status_is(200) - ->json_is( [] ); + $t->get_ok("//$userid:$password@/api/v1/ill/backends")->status_is(200)->json_is( [] ); # Mock one existing backend $illconfig_module->mock( 'available_backends', sub { ["Mock"] } ); #One backend exists, expect that - $t->get_ok("//$userid:$password@/api/v1/ill/backends")->status_is(200) - ->json_has( '/0/ill_backend_id', 'Mock' ); + $t->get_ok("//$userid:$password@/api/v1/ill/backends")->status_is(200)->json_has( '/0/ill_backend_id', 'Mock' ); # Prepare status my $backend_status = { @@ -170,15 +164,13 @@ subtest 'list() tests' => sub { my $backend_status_req = $builder->build_object( { class => 'Koha::ILL::Requests', - value => - { status => $backend_status->{code}, backend => $backend->name } + value => { status => $backend_status->{code}, backend => $backend->name } } ); my $core_status_req = $builder->build_object( { class => 'Koha::ILL::Requests', - value => - { status => $core_status->{code}, backend => $backend->name } + value => { status => $core_status->{code}, backend => $backend->name } } ); my $alias_status_req = $builder->build_object( @@ -193,22 +185,18 @@ subtest 'list() tests' => sub { ); #Check for backend existing statuses - $t->get_ok("//$userid:$password@/api/v1/ill/backends/Mock" => {'x-koha-embed' => 'statuses+strings'} ) - ->status_is(200) - ->json_has( '/statuses', [ $backend_status, $core_status, $alias_status ] ); + $t->get_ok( "//$userid:$password@/api/v1/ill/backends/Mock" => { 'x-koha-embed' => 'statuses+strings' } ) + ->status_is(200)->json_has( '/statuses', [ $backend_status, $core_status, $alias_status ] ); #Check for backend existing statuses of a backend that doesn't exist - $t->get_ok("//$userid:$password@/api/v1/ill/backends/GhostBackend" => {'x-koha-embed' => 'statuses+strings'} ) - ->status_is(200) - ->json_hasnt( 'statuses' ); + $t->get_ok( "//$userid:$password@/api/v1/ill/backends/GhostBackend" => { 'x-koha-embed' => 'statuses+strings' } ) + ->status_is(200)->json_hasnt('statuses'); # Unauthorized attempt to list - $t->get_ok("//$unauth_userid:$password@/api/v1/ill/backends") - ->status_is(403); + $t->get_ok("//$unauth_userid:$password@/api/v1/ill/backends")->status_is(403); # DELETE method not supported - $t->delete_ok("//$unauth_userid:$password@/api/v1/ill/backends") - ->status_is(404); + $t->delete_ok("//$unauth_userid:$password@/api/v1/ill/backends")->status_is(404); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/api/v1/ill_batchstatuses.t b/t/db_dependent/api/v1/ill_batchstatuses.t index cf73020ec7..652511476c 100755 --- a/t/db_dependent/api/v1/ill_batchstatuses.t +++ b/t/db_dependent/api/v1/ill_batchstatuses.t @@ -169,8 +169,8 @@ subtest 'add() tests' => sub { doh => 1 }; - $t->post_ok( "//$userid:$password@/api/v1/ill/batchstatuses" => json => $status_with_invalid_field )->status_is(400) - ->json_is( + $t->post_ok( "//$userid:$password@/api/v1/ill/batchstatuses" => json => $status_with_invalid_field ) + ->status_is(400)->json_is( "/errors" => [ { message => "Properties not allowed: doh.", @@ -180,11 +180,8 @@ subtest 'add() tests' => sub { ); # Authorized attempt to write - $t->post_ok( "//$userid:$password@/api/v1/ill/batchstatuses" => json => $status_metadata ) - ->status_is(201) - ->json_has( '/id', 'ID' ) - ->json_has( '/name', 'Name' ) - ->json_has( '/code', 'Code' ) + $t->post_ok( "//$userid:$password@/api/v1/ill/batchstatuses" => json => $status_metadata )->status_is(201) + ->json_has( '/id', 'ID' )->json_has( '/name', 'Name' )->json_has( '/code', 'Code' ) ->json_has( '/is_system', 'is_system' ) ->header_is( 'Location' => '/api/v1/ill/batchstatuses/' . $t->tx->res->json->{code}, "REST3.4.1" ); diff --git a/t/db_dependent/api/v1/ill_requests.t b/t/db_dependent/api/v1/ill_requests.t index a2260a23d3..838aec1cdf 100755 --- a/t/db_dependent/api/v1/ill_requests.t +++ b/t/db_dependent/api/v1/ill_requests.t @@ -46,25 +46,26 @@ subtest 'list() tests' => sub { # Mock ILLBackend (as object) my $backend = Test::MockObject->new; $backend->set_isa('Koha::Illbackends::Mock'); - $backend->set_always('name', 'Mock'); - $backend->set_always('capabilities', sub { return 'bar'; } ); + $backend->set_always( 'name', 'Mock' ); + $backend->set_always( 'capabilities', sub { return 'bar'; } ); $backend->mock( 'metadata', sub { my ( $self, $rq ) = @_; return { - ID => $rq->illrequest_id, + ID => $rq->illrequest_id, Title => $rq->patron->borrowernumber - } + }; } ); $backend->mock( - 'status_graph', sub {}, + 'status_graph', sub { }, ); # Mock Koha::ILL::Request::load_backend (to load Mocked Backend) my $illreqmodule = Test::MockModule->new('Koha::ILL::Request'); - $illreqmodule->mock( 'load_backend', + $illreqmodule->mock( + 'load_backend', sub { my $self = shift; $self->{_my_backend} = $backend; return $self } ); @@ -76,7 +77,7 @@ subtest 'list() tests' => sub { my $librarian = $builder->build_object( { class => 'Koha::Patrons', - value => { flags => 2 ** 22 } # 22 => ill + value => { flags => 2**22 } # 22 => ill } ); my $password = 'thePassword123'; @@ -100,42 +101,40 @@ subtest 'list() tests' => sub { { class => 'Koha::AuthorisedValueCategories', value => { category_name => 'ILL_STATUS_ALIAS' } } ); } - my $tag = "Print copy"; + my $tag = "Print copy"; my $av_code = "print_copy"; - my $av = $builder->build_object( - { class => 'Koha::AuthorisedValues', + my $av = $builder->build_object( + { + class => 'Koha::AuthorisedValues', value => { - category => 'ILL_STATUS_ALIAS', + category => 'ILL_STATUS_ALIAS', authorised_value => $av_code, - lib => $tag, + lib => $tag, } } ); # No requests, expect empty - $t->get_ok("//$userid:$password@/api/v1/ill/requests") - ->status_is(200) - ->json_is( [] ); - + $t->get_ok("//$userid:$password@/api/v1/ill/requests")->status_is(200)->json_is( [] ); # Prepare some expected response structure my $request_status = { - code =>"REQ", - str =>"Requested" + code => "REQ", + str => "Requested" }; my $response_status = { backend => $backend->name, - code =>$request_status->{code}, - str =>$request_status->{str}, - type =>"ill_status" + code => $request_status->{code}, + str => $request_status->{str}, + type => "ill_status" }; my $response_status_av = { category => "ILL_STATUS_ALIAS", - code => $av_code, - str => $tag, - type => "av" + code => $av_code, + str => $tag, + type => "av" }; # Create some ILL requests @@ -164,15 +163,18 @@ subtest 'list() tests' => sub { } ); - my $ret = $builder->build_object({ class => 'Koha::ILL::Requests', value => { status => 'RET' } }); + my $ret = $builder->build_object( { class => 'Koha::ILL::Requests', value => { status => 'RET' } } ); # Three requests exist, expect all three to be returned - $t->get_ok("//$userid:$password@/api/v1/ill/requests") - ->status_is(200) - ->json_is( [ $req_1->to_api({user=> $librarian}), $req_2->to_api({user=> $librarian}), $ret->to_api({user=> $librarian}) ]); + $t->get_ok("//$userid:$password@/api/v1/ill/requests")->status_is(200)->json_is( + [ + $req_1->to_api( { user => $librarian } ), $req_2->to_api( { user => $librarian } ), + $ret->to_api( { user => $librarian } ) + ] + ); - my $status_query = encode_json({ status => 'REQ' }); - my $status_alias_query = encode_json({ status_av => $av_code }); + my $status_query = encode_json( { status => 'REQ' } ); + my $status_alias_query = encode_json( { status_av => $av_code } ); # x-koha-embed: +strings # Two requests exist with status 'REQ', expect them to be returned @@ -200,7 +202,7 @@ subtest 'list() tests' => sub { ); # x-koha-embed: patron - my $patron_query = encode_json({ borrowernumber => $patron->borrowernumber }); + my $patron_query = encode_json( { borrowernumber => $patron->borrowernumber } ); # One request related to $patron, make sure it comes back $t->get_ok( "//$userid:$password@/api/v1/ill/requests" => { "x-koha-embed" => "patron" } )->status_is(200) @@ -209,24 +211,30 @@ subtest 'list() tests' => sub { # x-koha-embed: comments # Create comment my $comment_text = "This is the comment"; - my $comment = $builder->build_object({ class => 'Koha::ILL::Comments', value => { illrequest_id => $req_1->illrequest_id, comment => $comment_text , borrowernumber => $patron->borrowernumber } } ); + my $comment = $builder->build_object( + { + class => 'Koha::ILL::Comments', + value => { + illrequest_id => $req_1->illrequest_id, comment => $comment_text, + borrowernumber => $patron->borrowernumber + } + } + ); # Make sure comments come back - $t->get_ok("//$userid:$password@/api/v1/ill/requests" => {"x-koha-embed" => "comments"} ) - ->status_is(200) - ->json_has('/0/comments', $comment_text); + $t->get_ok( "//$userid:$password@/api/v1/ill/requests" => { "x-koha-embed" => "comments" } )->status_is(200) + ->json_has( '/0/comments', $comment_text ); # x-koha-embed: id_prefix # Mock ILL::Request::Config to return a static prefix my $id_prefix = 'ILL'; - my $config = Test::MockObject->new; + my $config = Test::MockObject->new; $config->set_isa('Koha::ILL::Request::Config::Mock'); - $config->set_always('getPrefixes', $id_prefix); + $config->set_always( 'getPrefixes', $id_prefix ); # Make sure id_prefix comes back - $t->get_ok("//$userid:$password@/api/v1/ill/requests" => {"x-koha-embed" => "id_prefix"} ) - ->status_is(200) - ->json_has('/0/id_prefix', $id_prefix); + $t->get_ok( "//$userid:$password@/api/v1/ill/requests" => { "x-koha-embed" => "id_prefix" } )->status_is(200) + ->json_has( '/0/id_prefix', $id_prefix ); # ILLHiddenRequestStatuses syspref # Hide 'REQ', expect to return just 1 'RET' @@ -241,21 +249,14 @@ subtest 'list() tests' => sub { # Status code # Warn on unsupported query parameter - $t->get_ok( "//$userid:$password@/api/v1/ill/requests?request_blah=blah" ) - ->status_is(400) - ->json_is( - [{ path => '/query/request_blah', message => 'Malformed query string'}] - ); + $t->get_ok("//$userid:$password@/api/v1/ill/requests?request_blah=blah")->status_is(400) + ->json_is( [ { path => '/query/request_blah', message => 'Malformed query string' } ] ); # Unauthorized attempt to list - $t->get_ok( - "//$unauth_userid:$password@/api/v1/ill/requests") - ->status_is(403); + $t->get_ok("//$unauth_userid:$password@/api/v1/ill/requests")->status_is(403); # DELETE method not supported - $t->delete_ok( - "//$unauth_userid:$password@/api/v1/ill/requests/1") - ->status_is(404); + $t->delete_ok("//$unauth_userid:$password@/api/v1/ill/requests/1")->status_is(404); #TODO; test complex query on extended_attributes @@ -269,15 +270,17 @@ subtest 'add() tests' => sub { $schema->storage->txn_begin; # create an authorized user - my $patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 2 ** 22 } # 22 => ill - }); + my $patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 2**22 } # 22 => ill + } + ); my $password = 'thePassword123'; - $patron->set_password({ password => $password, skip_validation => 1 }); + $patron->set_password( { password => $password, skip_validation => 1 } ); my $userid = $patron->userid; - my $library = $builder->build_object( { class => 'Koha::Libraries' } ); + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); # Create an ILL request my $illrequest = $builder->build_object( @@ -295,20 +298,20 @@ subtest 'add() tests' => sub { # Mock ILLBackend (as object) my $backend = Test::MockObject->new; $backend->set_isa('Koha::Illbackends::Mock'); - $backend->set_always('name', 'Mock'); + $backend->set_always( 'name', 'Mock' ); $backend->mock( 'metadata', sub { my ( $self, $rq ) = @_; return { - ID => $rq->illrequest_id, + ID => $rq->illrequest_id, Title => $rq->patron->borrowernumber - } + }; } ); $backend->mock( - 'status_graph', sub {}, + 'status_graph', sub { }, ); # Mock Koha::ILL::Request::load_backend (to load Mocked Backend) @@ -325,7 +328,7 @@ subtest 'add() tests' => sub { $self->{_my_backend} = $backend if ($backend); return $self; - } + } ); $illreqmodule->mock( @@ -336,7 +339,7 @@ subtest 'add() tests' => sub { my $capabilities = { create_api => sub { - my ($body, $request ) = @_; + my ( $body, $request ) = @_; my $api_req = $builder->build_object( { @@ -364,13 +367,12 @@ subtest 'add() tests' => sub { my $body = { ill_backend_id => 'Mock', - patron_id => $patron->borrowernumber, - library_id => $library->branchcode + patron_id => $patron->borrowernumber, + library_id => $library->branchcode }; ## Authorized user test - $t->post_ok( "//$userid:$password@/api/v1/ill/requests" => json => $body) - ->status_is(201); + $t->post_ok( "//$userid:$password@/api/v1/ill/requests" => json => $body )->status_is(201); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/api/v1/import_batch_profiles.t b/t/db_dependent/api/v1/import_batch_profiles.t index 88c074c558..a4d19f215c 100755 --- a/t/db_dependent/api/v1/import_batch_profiles.t +++ b/t/db_dependent/api/v1/import_batch_profiles.t @@ -27,7 +27,7 @@ use Koha::ImportBatchProfiles; my $schema = Koha::Database->new->schema; my $builder = t::lib::TestBuilder->new(); -my $dbh = C4::Context->dbh; +my $dbh = C4::Context->dbh; t::lib::Mocks::mock_preference( 'RESTBasicAuth', 1 ); @@ -42,9 +42,7 @@ subtest 'unauth access' => sub { my $patron1 = $builder->build_object( { class => 'Koha::Patrons', - value => { - flags => 4 - } + value => { flags => 4 } } ); @@ -52,21 +50,17 @@ subtest 'unauth access' => sub { my $patron2 = $builder->build_object( { class => 'Koha::Patrons', - value => { - flags => 4096 - } + value => { flags => 4096 } } ); my $uid = $patron1->userid; my $pwd = $patron1->password; - $t->get_ok("//$uid:$pwd@/api/v1/import_batch_profiles?_order_by=+name") - ->status_is(403); + $t->get_ok("//$uid:$pwd@/api/v1/import_batch_profiles?_order_by=+name")->status_is(403); $uid = $patron1->userid; $pwd = $patron1->password; - $t->get_ok("//$uid:$pwd@/api/v1/import_batch_profiles?_order_by=+name") - ->status_is(403); + $t->get_ok("//$uid:$pwd@/api/v1/import_batch_profiles?_order_by=+name")->status_is(403); $schema->storage->txn_rollback; }; @@ -78,33 +72,31 @@ subtest 'list profiles' => sub { Koha::ImportBatchProfiles->search()->delete; - my $ibp1 = $builder->build_object({ class => 'Koha::ImportBatchProfiles', value => { name => 'a_ibp' } }); - my $ibp2 = $builder->build_object({ class => 'Koha::ImportBatchProfiles', value => { name => 'b_ibp' } }); + my $ibp1 = $builder->build_object( { class => 'Koha::ImportBatchProfiles', value => { name => 'a_ibp' } } ); + my $ibp2 = $builder->build_object( { class => 'Koha::ImportBatchProfiles', value => { name => 'b_ibp' } } ); my $patron = $builder->build_object( { class => 'Koha::Patrons', - value => { - flags => 4096 - } + value => { flags => 4096 } } ); - my $sth = $dbh->prepare("INSERT INTO user_permissions (borrowernumber, module_bit, code) + my $sth = $dbh->prepare( + "INSERT INTO user_permissions (borrowernumber, module_bit, code) SELECT ?, bit, ? FROM userflags - WHERE flag = ?"); - $sth->execute($patron->borrowernumber, 'stage_marc_import', 'tools'); + WHERE flag = ?" + ); + $sth->execute( $patron->borrowernumber, 'stage_marc_import', 'tools' ); my $pwd = 'thePassword123'; $patron->set_password( { password => $pwd, skip_validation => 1 } ); my $uid = $patron->userid; - $t->get_ok("//$uid:$pwd@/api/v1/import_batch_profiles?_order_by=+name") - ->status_is(200) - ->json_is('/0/name', $ibp1->name) - ->json_is('/1/name', $ibp2->name); + $t->get_ok("//$uid:$pwd@/api/v1/import_batch_profiles?_order_by=+name")->status_is(200) + ->json_is( '/0/name', $ibp1->name )->json_is( '/1/name', $ibp2->name ); $schema->storage->txn_rollback; @@ -121,31 +113,29 @@ subtest 'add() tests' => sub { my $patron = $builder->build_object( { class => 'Koha::Patrons', - value => { - flags => 4096 - } + value => { flags => 4096 } } ); - my $sth = $dbh->prepare("INSERT INTO user_permissions (borrowernumber, module_bit, code) + my $sth = $dbh->prepare( + "INSERT INTO user_permissions (borrowernumber, module_bit, code) SELECT ?, bit, ? FROM userflags - WHERE flag = ?"); - $sth->execute($patron->borrowernumber, 'stage_marc_import', 'tools'); + WHERE flag = ?" + ); + $sth->execute( $patron->borrowernumber, 'stage_marc_import', 'tools' ); my $pwd = 'thePassword123'; $patron->set_password( { password => $pwd, skip_validation => 1 } ); - my $uid = $patron->userid; + my $uid = $patron->userid; my $post_data = { - name => 'profileName', + name => 'profileName', overlay_action => 'overlay_action' }; - $t->post_ok( "//$uid:$pwd@/api/v1/import_batch_profiles", json => $post_data ) - ->status_is(201) - ->json_has('/profile_id') - ->json_is( '/name', $post_data->{name} ) + $t->post_ok( "//$uid:$pwd@/api/v1/import_batch_profiles", json => $post_data )->status_is(201) + ->json_has('/profile_id')->json_is( '/name', $post_data->{name} ) ->json_is( '/overlay_action', $post_data->{overlay_action} ) ->header_is( 'Location', '/api/v1/import_batch_profiles/' . $t->tx->res->json->{profile_id}, 'REST3.4.1' ); @@ -163,38 +153,33 @@ subtest 'edit profile' => sub { my $patron = $builder->build_object( { class => 'Koha::Patrons', - value => { - flags => 4096 - } + value => { flags => 4096 } } ); - my $sth = $dbh->prepare("INSERT INTO user_permissions (borrowernumber, module_bit, code) + my $sth = $dbh->prepare( + "INSERT INTO user_permissions (borrowernumber, module_bit, code) SELECT ?, bit, ? FROM userflags - WHERE flag = ?"); - $sth->execute($patron->borrowernumber, 'stage_marc_import', 'tools'); + WHERE flag = ?" + ); + $sth->execute( $patron->borrowernumber, 'stage_marc_import', 'tools' ); my $pwd = 'thePassword123'; $patron->set_password( { password => $pwd, skip_validation => 1 } ); my $uid = $patron->userid; - my $ibp = $builder->build_object({class => 'Koha::ImportBatchProfiles', value => { name => 'someProfile' }}); + my $ibp = $builder->build_object( { class => 'Koha::ImportBatchProfiles', value => { name => 'someProfile' } } ); - my $post_data = { - name => 'theProfile' - }; + my $post_data = { name => 'theProfile' }; - $t->put_ok("//$uid:$pwd@/api/v1/import_batch_profiles/".$ibp->id, json => $post_data) - ->status_is(200) - ->json_is('/profile_id', $ibp->id) - ->json_is('/name', $post_data->{name}); + $t->put_ok( "//$uid:$pwd@/api/v1/import_batch_profiles/" . $ibp->id, json => $post_data )->status_is(200) + ->json_is( '/profile_id', $ibp->id )->json_is( '/name', $post_data->{name} ); $ibp->discard_changes; - is($ibp->name, $post_data->{name}, 'profile name should be the updated one'); - + is( $ibp->name, $post_data->{name}, 'profile name should be the updated one' ); $schema->storage->txn_rollback; @@ -210,32 +195,30 @@ subtest 'delete profile' => sub { my $patron = $builder->build_object( { class => 'Koha::Patrons', - value => { - flags => 4096 - } + value => { flags => 4096 } } ); - my $sth = $dbh->prepare("INSERT INTO user_permissions (borrowernumber, module_bit, code) + my $sth = $dbh->prepare( + "INSERT INTO user_permissions (borrowernumber, module_bit, code) SELECT ?, bit, ? FROM userflags - WHERE flag = ?"); - $sth->execute($patron->borrowernumber, 'stage_marc_import', 'tools'); + WHERE flag = ?" + ); + $sth->execute( $patron->borrowernumber, 'stage_marc_import', 'tools' ); my $pwd = 'thePassword123'; $patron->set_password( { password => $pwd, skip_validation => 1 } ); my $uid = $patron->userid; - my $ibp = $builder->build_object({class => 'Koha::ImportBatchProfiles'}); + my $ibp = $builder->build_object( { class => 'Koha::ImportBatchProfiles' } ); - $t->delete_ok("//$uid:$pwd@/api/v1/import_batch_profiles/".$ibp->id) - ->status_is(204); + $t->delete_ok( "//$uid:$pwd@/api/v1/import_batch_profiles/" . $ibp->id )->status_is(204); - my $search = Koha::ImportBatchProfiles->find($ibp->id); - - is($search, undef, 'profile should be erased'); + my $search = Koha::ImportBatchProfiles->find( $ibp->id ); + is( $search, undef, 'profile should be erased' ); $schema->storage->txn_rollback; diff --git a/t/db_dependent/api/v1/import_record_matches.t b/t/db_dependent/api/v1/import_record_matches.t index fd203c3125..0fe47f1420 100755 --- a/t/db_dependent/api/v1/import_record_matches.t +++ b/t/db_dependent/api/v1/import_record_matches.t @@ -42,14 +42,16 @@ subtest 'import record matches tests' => sub { } ); - $builder->build({ - source => 'UserPermission', - value => { - borrowernumber => $librarian->id, - module_bit => 13, # tools - code => 'manage_staged_marc', + $builder->build( + { + source => 'UserPermission', + value => { + borrowernumber => $librarian->id, + module_bit => 13, # tools + code => 'manage_staged_marc', + } } - }); + ); my $password = 'thePassword123'; $librarian->set_password( { password => $password, skip_validation => 1 } ); @@ -65,74 +67,67 @@ subtest 'import record matches tests' => sub { $patron->set_password( { password => $password, skip_validation => 1 } ); my $unauth_userid = $patron->userid; - my $match_1 = $builder->build_object({ - class => 'Koha::Import::Record::Matches', - value => { - chosen => 0, + my $match_1 = $builder->build_object( + { + class => 'Koha::Import::Record::Matches', + value => { + chosen => 0, + } } - }); - my $match_2 = $builder->build_object({ - class => 'Koha::Import::Record::Matches', - value => { - import_record_id => $match_1->import_record_id, - chosen => 1, + ); + my $match_2 = $builder->build_object( + { + class => 'Koha::Import::Record::Matches', + value => { + import_record_id => $match_1->import_record_id, + chosen => 1, + } } - }); - my $del_match = $builder->build_object({ class => 'Koha::Import::Record::Matches' }); + ); + my $del_match = $builder->build_object( { class => 'Koha::Import::Record::Matches' } ); my $del_import_batch_id = $del_match->import_record->import_batch_id; - my $del_match_id = $del_match->import_record_id; + my $del_match_id = $del_match->import_record_id; - $t->put_ok( - "//$unauth_userid:$password@/api/v1/import_batches/" - . $match_1->import_record->import_batch_id - . "/records/" - . $match_1->import_record_id - . "/matches/chosen" => json => { - candidate_match_id => $match_1->candidate_match_id - } - )->status_is(403); + $t->put_ok( "//$unauth_userid:$password@/api/v1/import_batches/" + . $match_1->import_record->import_batch_id + . "/records/" + . $match_1->import_record_id + . "/matches/chosen" => json => { candidate_match_id => $match_1->candidate_match_id } )->status_is(403); # Invalid attempt to allow match on a non-existent record $del_match->delete(); - $t->put_ok( - "//$userid:$password@/api/v1/import_batches/" - . $del_import_batch_id - . "/records/" - . $del_match_id - . "/matches/chosen" => json => { - candidate_match_id => $match_1->candidate_match_id - } - )->status_is(404)->json_is( '/error' => "Match not found" ); + $t->put_ok( "//$userid:$password@/api/v1/import_batches/" + . $del_import_batch_id + . "/records/" + . $del_match_id + . "/matches/chosen" => json => { candidate_match_id => $match_1->candidate_match_id } )->status_is(404) + ->json_is( '/error' => "Match not found" ); # Valid, authorised update - $t->put_ok( - "//$userid:$password@/api/v1/import_batches/" - . $match_1->import_record->import_batch_id - . "/records/" - . $match_1->import_record_id - . "/matches/chosen" => json => { - candidate_match_id => $match_1->candidate_match_id - } - )->status_is(200); + $t->put_ok( "//$userid:$password@/api/v1/import_batches/" + . $match_1->import_record->import_batch_id + . "/records/" + . $match_1->import_record_id + . "/matches/chosen" => json => { candidate_match_id => $match_1->candidate_match_id } )->status_is(200); $match_1->discard_changes; $match_2->discard_changes; - ok( $match_1->chosen,"Match 1 is correctly set to chosen"); - ok( !$match_2->chosen,"Match 2 correctly unset when match 1 is set"); + ok( $match_1->chosen, "Match 1 is correctly set to chosen" ); + ok( !$match_2->chosen, "Match 2 correctly unset when match 1 is set" ); # Valid unsetting $t->delete_ok( "//$userid:$password@/api/v1/import_batches/" - . $match_1->import_record->import_batch_id - . "/records/" - . $match_1->import_record_id - . "/matches/chosen" )->status_is(204); + . $match_1->import_record->import_batch_id + . "/records/" + . $match_1->import_record_id + . "/matches/chosen" )->status_is(204); $match_1->discard_changes; $match_2->discard_changes; - ok( !$match_1->chosen,"Match 1 is correctly unset to chosen"); - ok( !$match_2->chosen,"Match 2 is correctly unset to chosen"); + ok( !$match_1->chosen, "Match 1 is correctly unset to chosen" ); + ok( !$match_2->chosen, "Match 2 is correctly unset to chosen" ); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/api/v1/item_groups.t b/t/db_dependent/api/v1/item_groups.t index 1b3a1bdffa..95c676a96f 100755 --- a/t/db_dependent/api/v1/item_groups.t +++ b/t/db_dependent/api/v1/item_groups.t @@ -33,7 +33,7 @@ use Koha::Database; my $schema = Koha::Database->new->schema; my $builder = t::lib::TestBuilder->new; -t::lib::Mocks::mock_preference( 'RESTBasicAuth', 1 ); +t::lib::Mocks::mock_preference( 'RESTBasicAuth', 1 ); t::lib::Mocks::mock_preference( 'EnableItemGroups', 1 ); my $t = Test::Mojo->new('Koha::REST::V1'); @@ -43,36 +43,39 @@ subtest 'list() tests' => sub { $schema->storage->txn_begin; - my $patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 4 } - }); + my $patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 4 } + } + ); my $password = 'thePassword123'; - $patron->set_password({ password => $password, skip_validation => 1 }); + $patron->set_password( { password => $password, skip_validation => 1 } ); my $userid = $patron->userid; - my $biblio = $builder->build_sample_biblio(); + my $biblio = $builder->build_sample_biblio(); my $biblio_id = $biblio->id; - $t->get_ok( "//$userid:$password@/api/v1/biblios/$biblio_id/item_groups" ) - ->status_is( 200, 'REST3.2.2' ); + $t->get_ok("//$userid:$password@/api/v1/biblios/$biblio_id/item_groups")->status_is( 200, 'REST3.2.2' ); my $response_count = scalar @{ $t->tx->res->json }; - is( $response_count, 0, 'Results count is 2'); + is( $response_count, 0, 'Results count is 2' ); - my $item_group_1 = Koha::Biblio::ItemGroup->new( { biblio_id => $biblio->id, display_order => 1, description => "Vol 1" } )->store(); + my $item_group_1 = + Koha::Biblio::ItemGroup->new( { biblio_id => $biblio->id, display_order => 1, description => "Vol 1" } ) + ->store(); - $t->get_ok( "//$userid:$password@/api/v1/biblios/$biblio_id/item_groups" ) - ->status_is( 200, 'REST3.2.2' ); + $t->get_ok("//$userid:$password@/api/v1/biblios/$biblio_id/item_groups")->status_is( 200, 'REST3.2.2' ); $response_count = scalar @{ $t->tx->res->json }; - is( $response_count, 1, 'Results count is 2'); + is( $response_count, 1, 'Results count is 2' ); - my $item_group_2 = Koha::Biblio::ItemGroup->new( { biblio_id => $biblio->id, display_order => 2, description => "Vol 2" } )->store(); + my $item_group_2 = + Koha::Biblio::ItemGroup->new( { biblio_id => $biblio->id, display_order => 2, description => "Vol 2" } ) + ->store(); - $t->get_ok( "//$userid:$password@/api/v1/biblios/$biblio_id/item_groups" ) - ->status_is( 200, 'REST3.2.2' ); + $t->get_ok("//$userid:$password@/api/v1/biblios/$biblio_id/item_groups")->status_is( 200, 'REST3.2.2' ); $response_count = scalar @{ $t->tx->res->json }; - is( $response_count, 2, 'Results count is 2'); + is( $response_count, 2, 'Results count is 2' ); $schema->storage->txn_rollback; }; @@ -83,39 +86,43 @@ subtest 'add() tests' => sub { $schema->storage->txn_begin; - my $authorized_patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 1 } - }); + my $authorized_patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 1 } + } + ); my $password = 'thePassword123'; - $authorized_patron->set_password({ password => $password, skip_validation => 1 }); + $authorized_patron->set_password( { password => $password, skip_validation => 1 } ); my $auth_userid = $authorized_patron->userid; - my $unauthorized_patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 0 } - }); - $unauthorized_patron->set_password({ password => $password, skip_validation => 1 }); + my $unauthorized_patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 0 } + } + ); + $unauthorized_patron->set_password( { password => $password, skip_validation => 1 } ); my $unauth_userid = $unauthorized_patron->userid; - my $biblio = $builder->build_sample_biblio(); + my $biblio = $builder->build_sample_biblio(); my $biblio_id = $biblio->id; my $item_group = { description => 'Vol 1', display_order => 1 }; # Unauthorized attempt $t->post_ok( "//$unauth_userid:$password@/api/v1/biblios/$biblio_id/item_groups" => json => $item_group ) - ->status_is(403); + ->status_is(403); # Authorized attempt $t->post_ok( "//$auth_userid:$password@/api/v1/biblios/$biblio_id/item_groups" => json => $item_group ) - ->status_is( 201, 'REST3.2.1' ); + ->status_is( 201, 'REST3.2.1' ); # Invalid biblio id - { # hide useless warnings + { # hide useless warnings local *STDERR; open STDERR, '>', '/dev/null'; $t->post_ok( "//$auth_userid:$password@/api/v1/biblios/XXX/item_groups" => json => $item_group ) - ->status_is( 404 ); + ->status_is(404); close STDERR; } @@ -127,42 +134,49 @@ subtest 'update() tests' => sub { $schema->storage->txn_begin; - my $authorized_patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 1 } - }); + my $authorized_patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 1 } + } + ); my $password = 'thePassword123'; - $authorized_patron->set_password({ password => $password, skip_validation => 1 }); + $authorized_patron->set_password( { password => $password, skip_validation => 1 } ); my $auth_userid = $authorized_patron->userid; - my $unauthorized_patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 0 } - }); - $unauthorized_patron->set_password({ password => $password, skip_validation => 1 }); + my $unauthorized_patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 0 } + } + ); + $unauthorized_patron->set_password( { password => $password, skip_validation => 1 } ); my $unauth_userid = $unauthorized_patron->userid; - my $biblio = $builder->build_sample_biblio(); + my $biblio = $builder->build_sample_biblio(); my $biblio_id = $biblio->id; - my $item_group = Koha::Biblio::ItemGroup->new( { biblio_id => $biblio->id, display_order => 1, description => "Vol 1" } )->store(); + my $item_group = + Koha::Biblio::ItemGroup->new( { biblio_id => $biblio->id, display_order => 1, description => "Vol 1" } ) + ->store(); my $item_group_id = $item_group->id; # Unauthorized attempt - $t->put_ok( "//$unauth_userid:$password@/api/v1/biblios/$biblio_id/item_groups/$item_group_id" - => json => { description => 'New unauthorized desc change' } ) - ->status_is(403); + $t->put_ok( "//$unauth_userid:$password@/api/v1/biblios/$biblio_id/item_groups/$item_group_id" => json => + { description => 'New unauthorized desc change' } )->status_is(403); # Authorized attempt - $t->put_ok( "//$auth_userid:$password@/api/v1/biblios/$biblio_id/item_groups/$item_group_id" => json => { description => "Vol A" } ) - ->status_is(200, 'REST3.2.1') - ->json_has( '/description' => "Vol A", 'REST3.3.3' ); + $t->put_ok( "//$auth_userid:$password@/api/v1/biblios/$biblio_id/item_groups/$item_group_id" => json => + { description => "Vol A" } )->status_is( 200, 'REST3.2.1' ) + ->json_has( '/description' => "Vol A", 'REST3.3.3' ); # Invalid biblio id - $t->put_ok( "//$auth_userid:$password@/api/v1/biblios/XXX/item_groups/$item_group_id" => json => { description => "Vol A" } ) - ->status_is(404); + $t->put_ok( + "//$auth_userid:$password@/api/v1/biblios/XXX/item_groups/$item_group_id" => json => { description => "Vol A" } + )->status_is(404); # Invalid item group id - $t->put_ok( "//$auth_userid:$password@/api/v1/biblios/$biblio_id/item_groups/XXX" => json => { description => "Vol A" } ) + $t->put_ok( + "//$auth_userid:$password@/api/v1/biblios/$biblio_id/item_groups/XXX" => json => { description => "Vol A" } ) ->status_is(404); $schema->storage->txn_rollback; @@ -173,39 +187,41 @@ subtest 'delete() tests' => sub { $schema->storage->txn_begin; - my $authorized_patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 1 } - }); + my $authorized_patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 1 } + } + ); my $password = 'thePassword123'; - $authorized_patron->set_password({ password => $password, skip_validation => 1 }); + $authorized_patron->set_password( { password => $password, skip_validation => 1 } ); my $auth_userid = $authorized_patron->userid; - my $unauthorized_patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 0 } - }); - $unauthorized_patron->set_password({ password => $password, skip_validation => 1 }); + my $unauthorized_patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 0 } + } + ); + $unauthorized_patron->set_password( { password => $password, skip_validation => 1 } ); my $unauth_userid = $unauthorized_patron->userid; - my $biblio = $builder->build_sample_biblio(); + my $biblio = $builder->build_sample_biblio(); my $biblio_id = $biblio->id; - my $item_group = Koha::Biblio::ItemGroup->new( { biblio_id => $biblio->id, display_order => 1, description => "Vol 1" } )->store(); + my $item_group = + Koha::Biblio::ItemGroup->new( { biblio_id => $biblio->id, display_order => 1, description => "Vol 1" } ) + ->store(); my $item_groupid = $item_group->id; - $t->delete_ok( "//$auth_userid:$password@/api/v1/biblios/$biblio_id/item_groups/$item_groupid" ) - ->status_is(204, 'REST3.2.4') - ->content_is('', 'REST3.3.4'); + $t->delete_ok("//$auth_userid:$password@/api/v1/biblios/$biblio_id/item_groups/$item_groupid") + ->status_is( 204, 'REST3.2.4' )->content_is( '', 'REST3.3.4' ); # Unauthorized attempt to delete - $t->delete_ok( "//$unauth_userid:$password@/api/v1/biblios/$biblio_id/item_groups/$item_groupid" ) - ->status_is(403); + $t->delete_ok("//$unauth_userid:$password@/api/v1/biblios/$biblio_id/item_groups/$item_groupid")->status_is(403); - $t->delete_ok( "//$auth_userid:$password@/api/v1/biblios/XXX/item_groups/$item_groupid" ) - ->status_is(404); + $t->delete_ok("//$auth_userid:$password@/api/v1/biblios/XXX/item_groups/$item_groupid")->status_is(404); - $t->delete_ok( "//$auth_userid:$password@/api/v1/biblios/$biblio_id/item_groups/XXX" ) - ->status_is(404); + $t->delete_ok("//$auth_userid:$password@/api/v1/biblios/$biblio_id/item_groups/XXX")->status_is(404); $schema->storage->txn_rollback; }; @@ -215,51 +231,54 @@ subtest 'volume items add() + delete() tests' => sub { $schema->storage->txn_begin; - my $patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 4 } - }); + my $patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 4 } + } + ); my $password = 'thePassword123'; - $patron->set_password({ password => $password, skip_validation => 1 }); + $patron->set_password( { password => $password, skip_validation => 1 } ); my $userid = $patron->userid; - my $biblio = $builder->build_sample_biblio(); + my $biblio = $builder->build_sample_biblio(); my $biblio_id = $biblio->id; - my $item_group = Koha::Biblio::ItemGroup->new( { biblio_id => $biblio->id, display_order => 1, description => "Vol 1" } )->store(); + my $item_group = + Koha::Biblio::ItemGroup->new( { biblio_id => $biblio->id, display_order => 1, description => "Vol 1" } ) + ->store(); my $item_groupid = $item_group->id; my @items = $item_group->items->as_list; - is( scalar(@items), 0, 'Item group has no items'); + is( scalar(@items), 0, 'Item group has no items' ); - my $item_1 = $builder->build_sample_item({ biblionumber => $biblio->biblionumber }); + my $item_1 = $builder->build_sample_item( { biblionumber => $biblio->biblionumber } ); my $item_1_id = $item_1->id; - $t->post_ok( "//$userid:$password@/api/v1/biblios/XXX/item_groups/$item_groupid/items" => json => { item_id => $item_1->id } ) - ->status_is( 409 ) - ->json_is( { error => 'Item group does not belong to passed biblio_id' } ); + $t->post_ok( + "//$userid:$password@/api/v1/biblios/XXX/item_groups/$item_groupid/items" => json => { item_id => $item_1->id } + )->status_is(409)->json_is( { error => 'Item group does not belong to passed biblio_id' } ); - $t->post_ok( "//$userid:$password@/api/v1/biblios/$biblio_id/item_groups/$item_groupid/items" => json => { item_id => $item_1->id } ) - ->status_is( 201, 'REST3.2.1' ); + $t->post_ok( "//$userid:$password@/api/v1/biblios/$biblio_id/item_groups/$item_groupid/items" => json => + { item_id => $item_1->id } )->status_is( 201, 'REST3.2.1' ); @items = $item_group->items; - is( scalar(@items), 1, 'Item group now has one item'); + is( scalar(@items), 1, 'Item group now has one item' ); - my $item_2 = $builder->build_sample_item({ biblionumber => $biblio->biblionumber }); + my $item_2 = $builder->build_sample_item( { biblionumber => $biblio->biblionumber } ); my $item_2_id = $item_2->id; - $t->post_ok( "//$userid:$password@/api/v1/biblios/$biblio_id/item_groups/$item_groupid/items" => json => { item_id => $item_2->id } ) - ->status_is( 201, 'REST3.2.1' ); + $t->post_ok( "//$userid:$password@/api/v1/biblios/$biblio_id/item_groups/$item_groupid/items" => json => + { item_id => $item_2->id } )->status_is( 201, 'REST3.2.1' ); @items = $item_group->items->as_list; - is( scalar(@items), 2, 'Item group now has two items'); + is( scalar(@items), 2, 'Item group now has two items' ); - $t->delete_ok( "//$userid:$password@/api/v1/biblios/$biblio_id/item_groups/$item_groupid/items/$item_1_id" ) - ->status_is(204, 'REST3.2.4') - ->content_is('', 'REST3.3.4'); + $t->delete_ok("//$userid:$password@/api/v1/biblios/$biblio_id/item_groups/$item_groupid/items/$item_1_id") + ->status_is( 204, 'REST3.2.4' )->content_is( '', 'REST3.3.4' ); @items = $item_group->items; - is( scalar(@items), 1, 'Item group now has one item'); + is( scalar(@items), 1, 'Item group now has one item' ); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/api/v1/items.t b/t/db_dependent/api/v1/items.t index 4dfcc2200c..f358de297e 100755 --- a/t/db_dependent/api/v1/items.t +++ b/t/db_dependent/api/v1/items.t @@ -56,7 +56,7 @@ subtest 'list() tests' => sub { ); # Make sure we have at least 10 items - for ( 1..10 ) { + for ( 1 .. 10 ) { $builder->build_sample_item; } @@ -69,40 +69,32 @@ subtest 'list() tests' => sub { my $password = 'thePassword123'; - $nonprivilegedpatron->set_password( - { password => $password, skip_validation => 1 } ); + $nonprivilegedpatron->set_password( { password => $password, skip_validation => 1 } ); my $userid = $nonprivilegedpatron->userid; - $t->get_ok( "//$userid:$password@/api/v1/items" ) - ->status_is(403) - ->json_is( - '/error' => 'Authorization failure. Missing required permission(s).' ); + $t->get_ok("//$userid:$password@/api/v1/items")->status_is(403) + ->json_is( '/error' => 'Authorization failure. Missing required permission(s).' ); $patron->set_password( { password => $password, skip_validation => 1 } ); $userid = $patron->userid; - $t->get_ok( "//$userid:$password@/api/v1/items?_per_page=10" ) - ->status_is( 200, 'REST3.2.2' ); + $t->get_ok("//$userid:$password@/api/v1/items?_per_page=10")->status_is( 200, 'REST3.2.2' ); my $response_count = scalar @{ $t->tx->res->json }; is( $response_count, 10, 'The API returns 10 items' ); - $t->get_ok( "//$userid:$password@/api/v1/items?external_id=" . $item->barcode ) - ->status_is(200) - ->json_is( '' => [ $item->to_api ], 'REST3.3.2'); - - $t->get_ok( "//$userid:$password@/api/v1/items?external_id=" . $item->barcode => {'x-koha-embed' => 'biblio'} ) - ->status_is(200) - ->json_is( '' => [ { %{$item->to_api}, biblio => $item->biblio->to_api } ], 'REST3.3.2'); + $t->get_ok( "//$userid:$password@/api/v1/items?external_id=" . $item->barcode )->status_is(200) + ->json_is( '' => [ $item->to_api ], 'REST3.3.2' ); + $t->get_ok( "//$userid:$password@/api/v1/items?external_id=" . $item->barcode => { 'x-koha-embed' => 'biblio' } ) + ->status_is(200)->json_is( '' => [ { %{ $item->to_api }, biblio => $item->biblio->to_api } ], 'REST3.3.2' ); my $barcode = $item->barcode; $item->delete; - $t->get_ok( "//$userid:$password@/api/v1/items?external_id=" . $item->barcode ) - ->status_is(200) - ->json_is( '' => [] ); + $t->get_ok( "//$userid:$password@/api/v1/items?external_id=" . $item->barcode )->status_is(200) + ->json_is( '' => [] ); $schema->storage->txn_rollback; }; @@ -131,9 +123,11 @@ subtest 'list_public() tests' => sub { # have a fresh biblio my $biblio = $builder->build_sample_biblio; + # have two itemtypes - my $itype_1 = $builder->build_object({ class => 'Koha::ItemTypes' }); - my $itype_2 = $builder->build_object({ class => 'Koha::ItemTypes' }); + my $itype_1 = $builder->build_object( { class => 'Koha::ItemTypes' } ); + my $itype_2 = $builder->build_object( { class => 'Koha::ItemTypes' } ); + # have 5 items on that biblio my $item_1 = $builder->build_sample_item( { @@ -190,13 +184,17 @@ subtest 'list_public() tests' => sub { } ); - my $rules = undef; + my $rules = undef; my $mocked_context = Test::MockModule->new('C4::Context'); - $mocked_context->mock( 'yaml_preference', sub { - return $rules; - }); + $mocked_context->mock( + 'yaml_preference', + sub { + return $rules; + } + ); - my $query = encode_json({ item_id => [ $item_1->id, $item_2->id, $item_3->id, $item_4->id, $item_5->id, $item_6->id ] }); + my $query = + encode_json( { item_id => [ $item_1->id, $item_2->id, $item_3->id, $item_4->id, $item_5->id, $item_6->id ] } ); t::lib::Mocks::mock_preference( 'RESTPublicAPI', 1 ); subtest 'anonymous access' => sub { @@ -206,36 +204,34 @@ subtest 'list_public() tests' => sub { t::lib::Mocks::mock_preference( 'hidelostitems', 0 ); my $res = $t->get_ok( "/api/v1/public/items?q=" . $query )->status_is(200)->tx->res->json; - is( scalar @{ $res }, 6, 'No rules set, hidelostitems unset, all items returned'); + is( scalar @{$res}, 6, 'No rules set, hidelostitems unset, all items returned' ); t::lib::Mocks::mock_preference( 'hidelostitems', 1 ); $res = $t->get_ok( "/api/v1/public/items?q=" . $query )->status_is(200)->tx->res->json; - is( scalar @{ $res }, 3, 'No rules set, hidelostitems set, 3 items hidden'); + is( scalar @{$res}, 3, 'No rules set, hidelostitems set, 3 items hidden' ); t::lib::Mocks::mock_preference( 'hidelostitems', 0 ); $rules = { biblionumber => [ $biblio->biblionumber ] }; - $res = $t->get_ok( "/api/v1/public/items?q=" . $query )->status_is(200)->tx->res->json; - is( scalar @{ $res }, 0, 'Biblionumber rule set, hidelostitems unset, all items hidden'); + $res = $t->get_ok( "/api/v1/public/items?q=" . $query )->status_is(200)->tx->res->json; + is( scalar @{$res}, 0, 'Biblionumber rule set, hidelostitems unset, all items hidden' ); $rules = { withdrawn => [ 1, 2 ] }; - $res = $t->get_ok( "/api/v1/public/items?q=" . $query )->status_is(200)->tx->res->json; - is( scalar @{ $res }, 4, 'Withdrawn rule set, hidelostitems unset, 2 items hidden'); + $res = $t->get_ok( "/api/v1/public/items?q=" . $query )->status_is(200)->tx->res->json; + is( scalar @{$res}, 4, 'Withdrawn rule set, hidelostitems unset, 2 items hidden' ); $rules = { itype => [ $itype_1->itemtype ] }; - $res = $t->get_ok( "/api/v1/public/items?q=" . $query )->status_is(200)->tx->res->json; - is( scalar @{ $res }, 2, 'Itype rule set, hidelostitems unset, 4 items hidden'); + $res = $t->get_ok( "/api/v1/public/items?q=" . $query )->status_is(200)->tx->res->json; + is( scalar @{$res}, 2, 'Itype rule set, hidelostitems unset, 4 items hidden' ); - $rules = { withdrawn => [ 1 ] }; - $res = $t->get_ok( "/api/v1/public/items?external_id=" . $item_1->barcode ) - ->status_is(200)->tx->res->json; - is( scalar @{ $res }, 0, 'Withdrawn rule set, hidelostitems unset, search on barcode returns no item'); + $rules = { withdrawn => [1] }; + $res = $t->get_ok( "/api/v1/public/items?external_id=" . $item_1->barcode )->status_is(200)->tx->res->json; + is( scalar @{$res}, 0, 'Withdrawn rule set, hidelostitems unset, search on barcode returns no item' ); $rules = undef; - $t->get_ok( "/api/v1/public/items?external_id=" . $item_1->barcode ) - ->status_is(200)->json_is( + $t->get_ok( "/api/v1/public/items?external_id=" . $item_1->barcode )->status_is(200)->json_is( '/0' => $item_1->to_api( { public => 1 } ), -'No rules set, hidelostitems unset, public form of item returned on barcode search' - ); + 'No rules set, hidelostitems unset, public form of item returned on barcode search' + ); }; subtest 'logged in user access' => sub { @@ -243,12 +239,11 @@ subtest 'list_public() tests' => sub { t::lib::Mocks::mock_preference( 'hidelostitems', 1 ); $rules = { withdrawn => [ 1, 2 ] }; - my $res = $t->get_ok("//$userid:$password@/api/v1/public/items?q=" . $query) - ->status_is(200)->tx->res->json; + my $res = $t->get_ok( "//$userid:$password@/api/v1/public/items?q=" . $query )->status_is(200)->tx->res->json; is( scalar @{$res}, 3, -'Rules on withdrawn but patron with override passed, hidelostitems set' + 'Rules on withdrawn but patron with override passed, hidelostitems set' ); }; @@ -261,78 +256,74 @@ subtest 'get() tests' => sub { $schema->storage->txn_begin; - my $item = $builder->build_sample_item; - my $patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 4 } - }); + my $item = $builder->build_sample_item; + my $patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 4 } + } + ); - my $nonprivilegedpatron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 0 } - }); + my $nonprivilegedpatron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 0 } + } + ); my $password = 'thePassword123'; - $nonprivilegedpatron->set_password({ password => $password, skip_validation => 1 }); + $nonprivilegedpatron->set_password( { password => $password, skip_validation => 1 } ); my $userid = $nonprivilegedpatron->userid; - $t->get_ok( "//$userid:$password@/api/v1/items/" . $item->itemnumber ) - ->status_is(403) - ->json_is( '/error' => 'Authorization failure. Missing required permission(s).' ); + $t->get_ok( "//$userid:$password@/api/v1/items/" . $item->itemnumber )->status_is(403) + ->json_is( '/error' => 'Authorization failure. Missing required permission(s).' ); - $patron->set_password({ password => $password, skip_validation => 1 }); + $patron->set_password( { password => $password, skip_validation => 1 } ); $userid = $patron->userid; - $t->get_ok( "//$userid:$password@/api/v1/items/" . $item->itemnumber ) - ->status_is( 200, 'REST3.2.2' ) - ->json_is( '' => $item->to_api, 'REST3.3.2' ); + $t->get_ok( "//$userid:$password@/api/v1/items/" . $item->itemnumber )->status_is( 200, 'REST3.2.2' ) + ->json_is( '' => $item->to_api, 'REST3.3.2' ); my $non_existent_code = $item->itemnumber; $item->delete; - $t->get_ok( "//$userid:$password@/api/v1/items/" . $non_existent_code ) - ->status_is(404) - ->json_is( '/error' => 'Item not found' ); + $t->get_ok( "//$userid:$password@/api/v1/items/" . $non_existent_code )->status_is(404) + ->json_is( '/error' => 'Item not found' ); t::lib::Mocks::mock_preference( 'item-level_itypes', 0 ); my $biblio = $builder->build_sample_biblio; - my $itype = - $builder->build_object( { class => 'Koha::ItemTypes' } ); - $item = $builder->build_sample_item( - { biblionumber => $biblio->biblionumber, itype => $itype->itemtype } ); + my $itype = $builder->build_object( { class => 'Koha::ItemTypes' } ); + $item = $builder->build_sample_item( { biblionumber => $biblio->biblionumber, itype => $itype->itemtype } ); - isnt( $biblio->itemtype, $itype->itemtype, "Test biblio level itemtype and item level itemtype do not match"); + isnt( $biblio->itemtype, $itype->itemtype, "Test biblio level itemtype and item level itemtype do not match" ); - $t->get_ok( "//$userid:$password@/api/v1/items/" . $item->itemnumber ) - ->status_is( 200, 'REST3.2.2' ) - ->json_is( '/item_type_id' => $itype->itemtype, 'item-level_itypes:0' ) - ->json_is( '/effective_item_type_id' => $biblio->itemtype, 'item-level_itypes:0' ); + $t->get_ok( "//$userid:$password@/api/v1/items/" . $item->itemnumber )->status_is( 200, 'REST3.2.2' ) + ->json_is( '/item_type_id' => $itype->itemtype, 'item-level_itypes:0' ) + ->json_is( '/effective_item_type_id' => $biblio->itemtype, 'item-level_itypes:0' ); t::lib::Mocks::mock_preference( 'item-level_itypes', 1 ); - $t->get_ok( "//$userid:$password@/api/v1/items/" . $item->itemnumber ) - ->status_is( 200, 'REST3.2.2' ) - ->json_is( '/item_type_id' => $itype->itemtype, 'item-level_itype:1' ) - ->json_is( '/effective_item_type_id' => $itype->itemtype, 'item-level_itypes:1' ); + $t->get_ok( "//$userid:$password@/api/v1/items/" . $item->itemnumber )->status_is( 200, 'REST3.2.2' ) + ->json_is( '/item_type_id' => $itype->itemtype, 'item-level_itype:1' ) + ->json_is( '/effective_item_type_id' => $itype->itemtype, 'item-level_itypes:1' ); - - my $biblio_itype = Koha::ItemTypes->find($biblio->itemtype); + my $biblio_itype = Koha::ItemTypes->find( $biblio->itemtype ); $biblio_itype->notforloan(3)->store(); $itype->notforloan(2)->store(); $item->notforloan(1)->store(); - $t->get_ok( "//$userid:$password@/api/v1/items/" . $item->itemnumber ) - ->status_is( 200, 'REST3.2.2' ) - ->json_is( '/not_for_loan_status' => 1, 'not_for_loan_status is 1' ) - ->json_is( '/effective_not_for_loan_status' => 1, 'effective_not_for_loan_status picks up item level' ); + $t->get_ok( "//$userid:$password@/api/v1/items/" . $item->itemnumber )->status_is( 200, 'REST3.2.2' ) + ->json_is( '/not_for_loan_status' => 1, 'not_for_loan_status is 1' ) + ->json_is( '/effective_not_for_loan_status' => 1, 'effective_not_for_loan_status picks up item level' ); $item->notforloan(0)->store(); - $t->get_ok( "//$userid:$password@/api/v1/items/" . $item->itemnumber ) - ->status_is( 200, 'REST3.2.2' ) - ->json_is( '/not_for_loan_status' => 0, 'not_for_loan_status is 0' ) - ->json_is( '/effective_not_for_loan_status' => 2, 'effective_not_for_loan_status now picks up itemtype level - item-level_itypes:1' ); + $t->get_ok( "//$userid:$password@/api/v1/items/" . $item->itemnumber )->status_is( 200, 'REST3.2.2' ) + ->json_is( '/not_for_loan_status' => 0, 'not_for_loan_status is 0' )->json_is( + '/effective_not_for_loan_status' => 2, + 'effective_not_for_loan_status now picks up itemtype level - item-level_itypes:1' + ); $itype->notforloan(0)->store(); $t->get_ok( "//$userid:$password@/api/v1/items/" . $item->itemnumber )->status_is( 200, 'REST3.2.2' ) @@ -342,17 +333,23 @@ subtest 'get() tests' => sub { ); t::lib::Mocks::mock_preference( 'item-level_itypes', 0 ); - $t->get_ok( "//$userid:$password@/api/v1/items/" . $item->itemnumber ) - ->status_is( 200, 'REST3.2.2' ) - ->json_is( '/not_for_loan_status' => 0, 'not_for_loan_status is 0' ) - ->json_is( '/effective_not_for_loan_status' => 3, 'effective_not_for_loan_status now picks up itemtype level - item-level_itypes:0' ); + $t->get_ok( "//$userid:$password@/api/v1/items/" . $item->itemnumber )->status_is( 200, 'REST3.2.2' ) + ->json_is( '/not_for_loan_status' => 0, 'not_for_loan_status is 0' )->json_is( + '/effective_not_for_loan_status' => 3, + 'effective_not_for_loan_status now picks up itemtype level - item-level_itypes:0' + ); my $module = Test::MockModule->new('C4::Languages'); $module->mock( _get_language_dirs => sub { return 'en', 'de-DE' } ); - $schema->resultset('Localization')->create({ entity => 'itemtypes', code => $itype->itemtype, lang => 'de-DE', translation => 'translated' }); - $t->get_ok( "//$userid:$password@/api/v1/items/" . $item->itemnumber, { 'X-Koha-Embed' => '+strings', Cookie => 'KohaOpacLanguage=de-DE', 'Accept-Language' => 'en' } ) - ->status_is( 200, 'SWAGGER3.2.2' ) - ->json_is( '/_strings/item_type_id/str' => 'translated', 'translations in _strings use language set in KohaOpacLanguage cookie' ); + $schema->resultset('Localization') + ->create( { entity => 'itemtypes', code => $itype->itemtype, lang => 'de-DE', translation => 'translated' } ); + $t->get_ok( + "//$userid:$password@/api/v1/items/" . $item->itemnumber, + { 'X-Koha-Embed' => '+strings', Cookie => 'KohaOpacLanguage=de-DE', 'Accept-Language' => 'en' } + )->status_is( 200, 'SWAGGER3.2.2' )->json_is( + '/_strings/item_type_id/str' => 'translated', + 'translations in _strings use language set in KohaOpacLanguage cookie' + ); $schema->storage->txn_rollback; }; @@ -368,14 +365,16 @@ subtest 'delete() tests' => sub { # we want to control all the safe_to_delete use cases my $item_class = Test::MockModule->new('Koha::Item'); - $item_class->mock( 'safe_to_delete', sub { - if ( $fail ) { - return Koha::Result::Boolean->new(0)->add_message({ message => $expected_error }); + $item_class->mock( + 'safe_to_delete', + sub { + if ($fail) { + return Koha::Result::Boolean->new(0)->add_message( { message => $expected_error } ); + } else { + return Koha::Result::Boolean->new(1); + } } - else { - return Koha::Result::Boolean->new(1); - } - }); + ); my $librarian = $builder->build_object( { @@ -390,11 +389,14 @@ subtest 'delete() tests' => sub { my $item = $builder->build_sample_item; my $errors = { - book_on_loan => { code => 'checked_out', description => 'The item is checked out' }, - book_reserved => { code => 'found_hold', description => 'Waiting or in-transit hold for the item' }, - last_item_for_hold => { code => 'last_item_for_hold', description => 'The item is the last one on a record on which a biblio-level hold is placed' }, - linked_analytics => { code => 'linked_analytics', description => 'The item has linked analytic records' }, - not_same_branch => { code => 'not_same_branch', description => 'The item is blocked by independent branches' }, + book_on_loan => { code => 'checked_out', description => 'The item is checked out' }, + book_reserved => { code => 'found_hold', description => 'Waiting or in-transit hold for the item' }, + last_item_for_hold => { + code => 'last_item_for_hold', + description => 'The item is the last one on a record on which a biblio-level hold is placed' + }, + linked_analytics => { code => 'linked_analytics', description => 'The item has linked analytic records' }, + not_same_branch => { code => 'not_same_branch', description => 'The item is blocked by independent branches' }, }; $fail = 1; @@ -403,32 +405,29 @@ subtest 'delete() tests' => sub { $expected_error = $error_code; - $t->delete_ok( "//$userid:$password@/api/v1/items/" . $item->id ) - ->status_is(409) - ->json_is( - { error => $errors->{$error_code}->{description}, - error_code => $errors->{$error_code}->{code}, + $t->delete_ok( "//$userid:$password@/api/v1/items/" . $item->id )->status_is(409)->json_is( + { + error => $errors->{$error_code}->{description}, + error_code => $errors->{$error_code}->{code}, } ); } $expected_error = 'unknown_error'; $t->delete_ok( "//$userid:$password@/api/v1/items/" . $item->id ) - ->status_is(500, 'unhandled error case generated default unhandled exception message') - ->json_is( - { error => 'Something went wrong, check Koha logs for details.', - error_code => 'internal_server_error', + ->status_is( 500, 'unhandled error case generated default unhandled exception message' )->json_is( + { + error => 'Something went wrong, check Koha logs for details.', + error_code => 'internal_server_error', } - ); + ); $fail = 0; - $t->delete_ok("//$userid:$password@/api/v1/items/" . $item->id) - ->status_is(204, 'REST3.2.4') - ->content_is('', 'REST3.3.4'); + $t->delete_ok( "//$userid:$password@/api/v1/items/" . $item->id )->status_is( 204, 'REST3.2.4' ) + ->content_is( '', 'REST3.3.4' ); - $t->delete_ok("//$userid:$password@/api/v1/items/" . $item->id) - ->status_is(404); + $t->delete_ok( "//$userid:$password@/api/v1/items/" . $item->id )->status_is(404); $schema->storage->txn_rollback; }; @@ -442,11 +441,14 @@ subtest 'pickup_locations() tests' => sub { t::lib::Mocks::mock_preference( 'AllowHoldPolicyOverride', 0 ); # Small trick to ease testing - Koha::Libraries->search->update({ pickup_location => 0 }); + Koha::Libraries->search->update( { pickup_location => 0 } ); - my $library_1 = $builder->build_object({ class => 'Koha::Libraries', value => { marcorgcode => 'A', pickup_location => 1 } }); - my $library_2 = $builder->build_object({ class => 'Koha::Libraries', value => { marcorgcode => 'B', pickup_location => 1 } }); - my $library_3 = $builder->build_object({ class => 'Koha::Libraries', value => { marcorgcode => 'C', pickup_location => 1 } }); + my $library_1 = + $builder->build_object( { class => 'Koha::Libraries', value => { marcorgcode => 'A', pickup_location => 1 } } ); + my $library_2 = + $builder->build_object( { class => 'Koha::Libraries', value => { marcorgcode => 'B', pickup_location => 1 } } ); + my $library_3 = + $builder->build_object( { class => 'Koha::Libraries', value => { marcorgcode => 'C', pickup_location => 1 } } ); my $library_1_api = $library_1->to_api(); my $library_2_api = $library_2->to_api(); @@ -484,8 +486,10 @@ subtest 'pickup_locations() tests' => sub { sub { my ( $self, $params ) = @_; my $mock_patron = $params->{patron}; - is( $mock_patron->borrowernumber, - $patron->borrowernumber, 'Patron passed correctly' ); + is( + $mock_patron->borrowernumber, + $patron->borrowernumber, 'Patron passed correctly' + ); return Koha::Libraries->search( { branchcode => { @@ -495,38 +499,41 @@ subtest 'pickup_locations() tests' => sub { ] } }, - { # we make sure no surprises in the order of the result + { # we make sure no surprises in the order of the result order_by => { '-asc' => 'marcorgcode' } } ); } ); - $t->get_ok( "//$userid:$password@/api/v1/items/" - . $item->id - . "/pickup_locations?patron_id=" . $patron->id ) - ->json_is( [ $library_1_api, $library_2_api ] ); + $t->get_ok( "//$userid:$password@/api/v1/items/" . $item->id . "/pickup_locations?patron_id=" . $patron->id ) + ->json_is( [ $library_1_api, $library_2_api ] ); # filtering works! $t->get_ok( "//$userid:$password@/api/v1/items/" - . $item->id - . '/pickup_locations?' - . 'patron_id=' . $patron->id . '&q={"marc_org_code": { "-like": "A%" }}' ) - ->json_is( [ $library_1_api ] ); + . $item->id + . '/pickup_locations?' + . 'patron_id=' + . $patron->id + . '&q={"marc_org_code": { "-like": "A%" }}' )->json_is( [$library_1_api] ); t::lib::Mocks::mock_preference( 'AllowHoldPolicyOverride', 1 ); - my $library_4 = $builder->build_object({ class => 'Koha::Libraries', value => { pickup_location => 0, marcorgcode => 'X' } }); - my $library_5 = $builder->build_object({ class => 'Koha::Libraries', value => { pickup_location => 1, marcorgcode => 'Y' } }); + my $library_4 = + $builder->build_object( { class => 'Koha::Libraries', value => { pickup_location => 0, marcorgcode => 'X' } } ); + my $library_5 = + $builder->build_object( { class => 'Koha::Libraries', value => { pickup_location => 1, marcorgcode => 'Y' } } ); my $library_5_api = $library_5->to_api(); $library_5_api->{needs_override} = Mojo::JSON->true; $t->get_ok( "//$userid:$password@/api/v1/items/" - . $item->id - . "/pickup_locations?" - . "patron_id=" . $patron->id . "&_order_by=marc_org_code" ) - ->json_is( [ $library_1_api, $library_2_api, $library_3_api, $library_5_api ] ); + . $item->id + . "/pickup_locations?" + . "patron_id=" + . $patron->id + . "&_order_by=marc_org_code" ) + ->json_is( [ $library_1_api, $library_2_api, $library_3_api, $library_5_api ] ); subtest 'Pagination and AllowHoldPolicyOverride tests' => sub { @@ -534,61 +541,62 @@ subtest 'pickup_locations() tests' => sub { t::lib::Mocks::mock_preference( 'AllowHoldPolicyOverride', 1 ); - $t->get_ok( "//$userid:$password@/api/v1/items/" . $item->id . "/pickup_locations?" . "patron_id=" . $patron->id . "&_order_by=marc_org_code" . "&_per_page=1" ) - ->json_is( [$library_1_api] ) - ->header_is( 'X-Total-Count', '4', '4 is the count for libraries with pickup_location=1' ) - ->header_is( 'X-Base-Total-Count', '4', '4 is the count for libraries with pickup_location=1' ) - ->header_unlike( 'Link', qr|rel="prev"| ) - ->header_like( 'Link', qr#(_per_page=1.*\&_page=2.*|_page=2.*\&_per_page=1.*)>\; rel="next"# ) - ->header_like( 'Link', qr#(_per_page=1.*\&_page=1.*|_page=1.*\&_per_page=1).*>\; rel="first"# ) - ->header_like( 'Link', qr#(_per_page=1.*\&_page=4.*|_page=4.*\&_per_page=1).*>\; rel="last"# ); + $t->get_ok( "//$userid:$password@/api/v1/items/" + . $item->id + . "/pickup_locations?" + . "patron_id=" + . $patron->id + . "&_order_by=marc_org_code" + . "&_per_page=1" )->json_is( [$library_1_api] ) + ->header_is( 'X-Total-Count', '4', '4 is the count for libraries with pickup_location=1' ) + ->header_is( 'X-Base-Total-Count', '4', '4 is the count for libraries with pickup_location=1' ) + ->header_unlike( 'Link', qr|rel="prev"| ) + ->header_like( 'Link', qr#(_per_page=1.*\&_page=2.*|_page=2.*\&_per_page=1.*)>\; rel="next"# ) + ->header_like( 'Link', qr#(_per_page=1.*\&_page=1.*|_page=1.*\&_per_page=1).*>\; rel="first"# ) + ->header_like( 'Link', qr#(_per_page=1.*\&_page=4.*|_page=4.*\&_per_page=1).*>\; rel="last"# ); $t->get_ok( "//$userid:$password@/api/v1/items/" - . $item->id - . "/pickup_locations?" - . "patron_id=" - . $patron->id - . "&_order_by=marc_org_code" - . "&_per_page=1&_page=3" ) # force the needs_override=1 check - ->json_is( [$library_3_api] ) - ->header_is( 'X-Total-Count', '4', '4 is the count for libraries with pickup_location=1' ) - ->header_is( 'X-Base-Total-Count', '4', '4 is the count for libraries with pickup_location=1' ) - ->header_like( 'Link', qr#(_per_page=1.*\&_page=2.*|_page=2.*\&_per_page=1.*)>\; rel="prev"# ) - ->header_like( 'Link', qr#(_per_page=1.*\&_page=4.*|_page=4.*\&_per_page=1.*)>\; rel="next"# ) - ->header_like( 'Link', qr#(_per_page=1.*\&_page=1.*|_page=1.*\&_per_page=1).*>\; rel="first"# ) - ->header_like( 'Link', qr#(_per_page=1.*\&_page=4.*|_page=4.*\&_per_page=1).*>\; rel="last"# ); + . $item->id + . "/pickup_locations?" + . "patron_id=" + . $patron->id + . "&_order_by=marc_org_code" + . "&_per_page=1&_page=3" ) # force the needs_override=1 check + ->json_is( [$library_3_api] ) + ->header_is( 'X-Total-Count', '4', '4 is the count for libraries with pickup_location=1' ) + ->header_is( 'X-Base-Total-Count', '4', '4 is the count for libraries with pickup_location=1' ) + ->header_like( 'Link', qr#(_per_page=1.*\&_page=2.*|_page=2.*\&_per_page=1.*)>\; rel="prev"# ) + ->header_like( 'Link', qr#(_per_page=1.*\&_page=4.*|_page=4.*\&_per_page=1.*)>\; rel="next"# ) + ->header_like( 'Link', qr#(_per_page=1.*\&_page=1.*|_page=1.*\&_per_page=1).*>\; rel="first"# ) + ->header_like( 'Link', qr#(_per_page=1.*\&_page=4.*|_page=4.*\&_per_page=1).*>\; rel="last"# ); t::lib::Mocks::mock_preference( 'AllowHoldPolicyOverride', 0 ); - $t->get_ok( "//$userid:$password@/api/v1/items/" . $item->id . "/pickup_locations?" . "patron_id=" . $patron->id . "&_order_by=marc_org_code" . "&_per_page=1" ) - ->json_is( [$library_1_api] ) - ->header_is( 'X-Total-Count', '2' ) - ->header_is( 'X-Base-Total-Count', '2' ) - ->header_unlike( 'Link', qr|rel="prev"| ) - ->header_like( 'Link', qr#(_per_page=1.*\&_page=2.*|_page=2.*\&_per_page=1.*)>\; rel="next"# ) - ->header_like( 'Link', qr#(_per_page=1.*\&_page=1.*|_page=1.*\&_per_page=1).*>\; rel="first"# ) - ->header_like( 'Link', qr#(_per_page=1.*\&_page=2.*|_page=2.*\&_per_page=1).*>\; rel="last"# ); + $t->get_ok( "//$userid:$password@/api/v1/items/" + . $item->id + . "/pickup_locations?" + . "patron_id=" + . $patron->id + . "&_order_by=marc_org_code" + . "&_per_page=1" )->json_is( [$library_1_api] )->header_is( 'X-Total-Count', '2' ) + ->header_is( 'X-Base-Total-Count', '2' )->header_unlike( 'Link', qr|rel="prev"| ) + ->header_like( 'Link', qr#(_per_page=1.*\&_page=2.*|_page=2.*\&_per_page=1.*)>\; rel="next"# ) + ->header_like( 'Link', qr#(_per_page=1.*\&_page=1.*|_page=1.*\&_per_page=1).*>\; rel="first"# ) + ->header_like( 'Link', qr#(_per_page=1.*\&_page=2.*|_page=2.*\&_per_page=1).*>\; rel="last"# ); }; - my $deleted_patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $deleted_patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $deleted_patron_id = $deleted_patron->id; $deleted_patron->delete; - $t->get_ok( "//$userid:$password@/api/v1/items/" - . $item->id - . "/pickup_locations?" - . "patron_id=" . $deleted_patron_id ) - ->status_is( 400 ) - ->json_is( '/error' => 'Patron not found' ); + $t->get_ok( + "//$userid:$password@/api/v1/items/" . $item->id . "/pickup_locations?" . "patron_id=" . $deleted_patron_id ) + ->status_is(400)->json_is( '/error' => 'Patron not found' ); $item->delete; - $t->get_ok( "//$userid:$password@/api/v1/items/" - . $item->id - . "/pickup_locations?" - . "patron_id=" . $patron->id ) - ->status_is( 404 ) - ->json_is( '/error' => 'Item not found' ); + $t->get_ok( "//$userid:$password@/api/v1/items/" . $item->id . "/pickup_locations?" . "patron_id=" . $patron->id ) + ->status_is(404)->json_is( '/error' => 'Item not found' ); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/api/v1/jobs.t b/t/db_dependent/api/v1/jobs.t index 7fae9293fc..2df09e67b4 100755 --- a/t/db_dependent/api/v1/jobs.t +++ b/t/db_dependent/api/v1/jobs.t @@ -30,6 +30,7 @@ my $schema = Koha::Database->new->schema; my $builder = t::lib::TestBuilder->new; my $t = Test::Mojo->new('Koha::REST::V1'); + #use t::lib::Mojo; #my $t = t::lib::Mojo->new('Koha::REST::V1'); t::lib::Mocks::mock_preference( 'RESTBasicAuth', 1 ); @@ -50,7 +51,7 @@ my $superlibrarian_userid = $superlibrarian->userid; my $librarian = $builder->build_object( { class => 'Koha::Patrons', - value => { flags => 2 ** 2 }, # catalogue flag = 2 + value => { flags => 2**2 }, # catalogue flag = 2 } ); $librarian->set_password( { password => $password, skip_validation => 1 } ); @@ -65,9 +66,7 @@ my $patron = $builder->build_object( $patron->set_password( { password => $password, skip_validation => 1 } ); my $patron_userid = $patron->userid; -$t->get_ok("//$librarian_userid:$password@/api/v1/jobs") - ->status_is(200) - ->json_is( [] ); +$t->get_ok("//$librarian_userid:$password@/api/v1/jobs")->status_is(200)->json_is( [] ); my $job = $builder->build_object( { @@ -78,9 +77,11 @@ my $job = $builder->build_object( size => 100, borrowernumber => $patron->borrowernumber, type => 'batch_item_record_modification', - queue => 'default', + queue => 'default', + #data => '{"record_ids":["1"],"regex_mod":null,"exclude_from_local_holds_priority":null,"new_values":{"itemnotes":"xxx"}}' , - data => '{"regex_mod":null,"report":{"total_records":1,"modified_fields":1,"modified_itemnumbers":[1]},"new_values":{"itemnotes":"xxx"},"record_ids":["1"],"exclude_from_local_holds_priority":null}', + data => + '{"regex_mod":null,"report":{"total_records":1,"modified_fields":1,"modified_itemnumbers":[1]},"new_values":{"itemnotes":"xxx"},"record_ids":["1"],"exclude_from_local_holds_priority":null}', } } ); @@ -94,54 +95,47 @@ my $job_current = $builder->build_object( size => 100, borrowernumber => $patron->borrowernumber, type => 'batch_item_record_modification', - queue => 'default', + queue => 'default', + #data => '{"record_ids":["1"],"regex_mod":null,"exclude_from_local_holds_priority":null,"new_values":{"itemnotes":"xxx"}}' , - data => '{"regex_mod":null,"report":{"total_records":1,"modified_fields":1,"modified_itemnumbers":[1]},"new_values":{"itemnotes":"xxx"},"record_ids":["1"],"exclude_from_local_holds_priority":null}', + data => + '{"regex_mod":null,"report":{"total_records":1,"modified_fields":1,"modified_itemnumbers":[1]},"new_values":{"itemnotes":"xxx"},"record_ids":["1"],"exclude_from_local_holds_priority":null}', } } ); { - $t->get_ok("//$superlibrarian_userid:$password@/api/v1/jobs") - ->status_is(200)->json_is( [ $job->to_api, $job_current->to_api ] ); + $t->get_ok("//$superlibrarian_userid:$password@/api/v1/jobs")->status_is(200) + ->json_is( [ $job->to_api, $job_current->to_api ] ); - $t->get_ok("//$superlibrarian_userid:$password@/api/v1/jobs?only_current=1") - ->status_is(200)->json_is( [ $job_current->to_api ] ); + $t->get_ok("//$superlibrarian_userid:$password@/api/v1/jobs?only_current=1")->status_is(200) + ->json_is( [ $job_current->to_api ] ); - $t->get_ok("//$librarian_userid:$password@/api/v1/jobs") - ->status_is(200)->json_is( [] ); + $t->get_ok("//$librarian_userid:$password@/api/v1/jobs")->status_is(200)->json_is( [] ); - $t->get_ok("//$patron_userid:$password@/api/v1/jobs") - ->status_is(403); + $t->get_ok("//$patron_userid:$password@/api/v1/jobs")->status_is(403); $job->borrowernumber( $librarian->borrowernumber )->store; - $t->get_ok("//$librarian_userid:$password@/api/v1/jobs") - ->status_is(200)->json_is( [ $job->to_api ] ); + $t->get_ok("//$librarian_userid:$password@/api/v1/jobs")->status_is(200)->json_is( [ $job->to_api ] ); - $t->get_ok("//$librarian_userid:$password@/api/v1/jobs?only_current=1") - ->status_is(200)->json_is( [] ); + $t->get_ok("//$librarian_userid:$password@/api/v1/jobs?only_current=1")->status_is(200)->json_is( [] ); } { - $t->get_ok( "//$superlibrarian_userid:$password@/api/v1/jobs/" - . $job->id )->status_is(200) - ->json_is( $job->to_api ); + $t->get_ok( "//$superlibrarian_userid:$password@/api/v1/jobs/" . $job->id )->status_is(200) + ->json_is( $job->to_api ); - $t->get_ok( "//$librarian_userid:$password@/api/v1/jobs/" - . $job->id )->status_is(200) - ->json_is( $job->to_api ); + $t->get_ok( "//$librarian_userid:$password@/api/v1/jobs/" . $job->id )->status_is(200)->json_is( $job->to_api ); $job->borrowernumber( $superlibrarian->borrowernumber )->store; - $t->get_ok( "//$librarian_userid:$password@/api/v1/jobs/" - . $job->id )->status_is(403); + $t->get_ok( "//$librarian_userid:$password@/api/v1/jobs/" . $job->id )->status_is(403); } { $job->delete; - $t->get_ok( "//$superlibrarian_userid:$password@/api/v1/jobs/" - . $job->id )->status_is(404) - ->json_is( '/error' => 'Job not found' ); + $t->get_ok( "//$superlibrarian_userid:$password@/api/v1/jobs/" . $job->id )->status_is(404) + ->json_is( '/error' => 'Job not found' ); } $schema->storage->txn_rollback; diff --git a/t/db_dependent/api/v1/libraries.t b/t/db_dependent/api/v1/libraries.t index da4e172862..9aa00fa6e3 100755 --- a/t/db_dependent/api/v1/libraries.t +++ b/t/db_dependent/api/v1/libraries.t @@ -41,28 +41,29 @@ subtest 'list() tests' => sub { $schema->storage->txn_begin; - my $patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 4 } - }); + my $patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 4 } + } + ); my $password = 'thePassword123'; - $patron->set_password({ password => $password, skip_validation => 1 }); + $patron->set_password( { password => $password, skip_validation => 1 } ); my $userid = $patron->userid; # Create test context - my $library = $builder->build_object({ class => 'Koha::Libraries' }); - my $another_library = $library->unblessed; # create a copy of $library but make - delete $another_library->{branchcode}; # sure branchcode will be regenerated - $another_library = $builder->build_object({ class => 'Koha::Libraries', value => $another_library }); + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); + my $another_library = $library->unblessed; # create a copy of $library but make + delete $another_library->{branchcode}; # sure branchcode will be regenerated + $another_library = $builder->build_object( { class => 'Koha::Libraries', value => $another_library } ); ## Authorized user tests # Make sure we are returned with the correct amount of libraries - $t->get_ok( "//$userid:$password@/api/v1/libraries" ) - ->status_is( 200, 'REST3.2.2' ); + $t->get_ok("//$userid:$password@/api/v1/libraries")->status_is( 200, 'REST3.2.2' ); my $response_count = scalar @{ $t->tx->res->json }; my $expected_count = min( Koha::Libraries->count, C4::Context->preference('RESTdefaultPageSize') ); - is( $response_count, $expected_count, 'Results count is paginated'); + is( $response_count, $expected_count, 'Results count is paginated' ); subtest 'query parameters' => sub { @@ -87,24 +88,23 @@ subtest 'list() tests' => sub { my $size = keys %{$fields}; - plan tests => $size * (2 + 2 * $size); + plan tests => $size * ( 2 + 2 * $size ); foreach my $field ( keys %{$fields} ) { - my $model_field = $fields->{ $field }; - my $result = $t->get_ok("//$userid:$password@/api/v1/libraries?$field=" . $library->$model_field) - ->status_is(200); + my $model_field = $fields->{$field}; + my $result = + $t->get_ok( "//$userid:$password@/api/v1/libraries?$field=" . $library->$model_field )->status_is(200); foreach my $key ( keys %{$fields} ) { - my $key_field = $fields->{ $key }; - $result->json_is( "/0/$key", $library->$key_field ); - $result->json_is( "/1/$key", $another_library->$key_field ); + my $key_field = $fields->{$key}; + $result->json_is( "/0/$key", $library->$key_field ); + $result->json_is( "/1/$key", $another_library->$key_field ); } } }; # Warn on unsupported query parameter - $t->get_ok( "//$userid:$password@/api/v1/libraries?library_blah=blah" ) - ->status_is(400) - ->json_is( [{ path => '/query/library_blah', message => 'Malformed query string'}] ); + $t->get_ok("//$userid:$password@/api/v1/libraries?library_blah=blah")->status_is(400) + ->json_is( [ { path => '/query/library_blah', message => 'Malformed query string' } ] ); $schema->storage->txn_rollback; }; @@ -116,17 +116,18 @@ subtest 'get() tests' => sub { $schema->storage->txn_begin; my $library = $builder->build_object( { class => 'Koha::Libraries' } ); - my $patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 4 } - }); + my $patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 4 } + } + ); my $password = 'thePassword123'; - $patron->set_password({ password => $password, skip_validation => 1 }); + $patron->set_password( { password => $password, skip_validation => 1 } ); my $userid = $patron->userid; - $t->get_ok( "//$userid:$password@/api/v1/libraries/" . $library->branchcode ) - ->status_is( 200, 'REST3.2.2' ) - ->json_is( '' => $library->to_api, 'REST3.3.2' ); + $t->get_ok( "//$userid:$password@/api/v1/libraries/" . $library->branchcode )->status_is( 200, 'REST3.2.2' ) + ->json_is( '' => $library->to_api, 'REST3.3.2' ); $t->get_ok( "//$userid:$password@/api/v1/libraries/" . $library->branchcode => { 'x-koha-embed' => 'cash_registers,desks' } )->status_is(200) @@ -144,9 +145,8 @@ subtest 'get() tests' => sub { my $non_existent_code = $library->branchcode; $library->delete; - $t->get_ok( "//$userid:$password@/api/v1/libraries/" . $non_existent_code ) - ->status_is(404) - ->json_is( '/error' => 'Library not found' ); + $t->get_ok( "//$userid:$password@/api/v1/libraries/" . $non_existent_code )->status_is(404) + ->json_is( '/error' => 'Library not found' ); $schema->storage->txn_rollback; }; @@ -157,68 +157,69 @@ subtest 'add() tests' => sub { $schema->storage->txn_begin; - my $authorized_patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 1 } - }); + my $authorized_patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 1 } + } + ); my $password = 'thePassword123'; - $authorized_patron->set_password({ password => $password, skip_validation => 1 }); + $authorized_patron->set_password( { password => $password, skip_validation => 1 } ); my $auth_userid = $authorized_patron->userid; - my $unauthorized_patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 4 } - }); - $unauthorized_patron->set_password({ password => $password, skip_validation => 1 }); + my $unauthorized_patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 4 } + } + ); + $unauthorized_patron->set_password( { password => $password, skip_validation => 1 } ); my $unauth_userid = $unauthorized_patron->userid; - my $library_obj = $builder->build_object({ class => 'Koha::Libraries' }); + my $library_obj = $builder->build_object( { class => 'Koha::Libraries' } ); my $library = $library_obj->to_api; $library_obj->delete; # Unauthorized attempt to write - $t->post_ok( "//$unauth_userid:$password@/api/v1/libraries" => json => $library ) - ->status_is(403); + $t->post_ok( "//$unauth_userid:$password@/api/v1/libraries" => json => $library )->status_is(403); # Authorized attempt to write invalid data - my $library_with_invalid_field = { %$library }; + my $library_with_invalid_field = {%$library}; $library_with_invalid_field->{'branchinvalid'} = 'Library invalid'; - $t->post_ok( "//$auth_userid:$password@/api/v1/libraries" => json => $library_with_invalid_field ) - ->status_is(400) - ->json_is( + $t->post_ok( "//$auth_userid:$password@/api/v1/libraries" => json => $library_with_invalid_field )->status_is(400) + ->json_is( "/errors" => [ { message => "Properties not allowed: branchinvalid.", path => "/body" } ] - ); + ); # Authorized attempt to write - $t->post_ok( "//$auth_userid:$password@/api/v1/libraries" => json => $library ) - ->status_is( 201, 'REST3.2.1' ) - ->json_is( '' => $library, 'REST3.3.1' ) - ->header_is( Location => '/api/v1/libraries/' . $library->{library_id}, 'REST3.4.1' ); + $t->post_ok( "//$auth_userid:$password@/api/v1/libraries" => json => $library )->status_is( 201, 'REST3.2.1' ) + ->json_is( '' => $library, 'REST3.3.1' ) + ->header_is( Location => '/api/v1/libraries/' . $library->{library_id}, 'REST3.4.1' ); # save the library_id my $library_id = $library->{library_id}; + # Authorized attempt to create with null id $library->{library_id} = undef; - $t->post_ok( "//$auth_userid:$password@/api/v1/libraries" => json => $library ) - ->status_is(400) - ->json_has('/errors'); + $t->post_ok( "//$auth_userid:$password@/api/v1/libraries" => json => $library )->status_is(400) + ->json_has('/errors'); # Authorized attempt to create with existing id $library->{library_id} = $library_id; warning_like { - $t->post_ok( "//$auth_userid:$password@/api/v1/libraries" => json => $library ) - ->status_is(409) - ->json_has( '/error' => "Fails when trying to add an existing library_id") - ->json_like( '/conflict' => qr/(branches\.)?PRIMARY/ ); } - qr/DBD::mysql::st execute failed: Duplicate entry '(.*)' for key '(branches\.)?PRIMARY'/; + $t->post_ok( "//$auth_userid:$password@/api/v1/libraries" => json => $library )->status_is(409) + ->json_has( '/error' => "Fails when trying to add an existing library_id" ) + ->json_like( '/conflict' => qr/(branches\.)?PRIMARY/ ); + } + qr/DBD::mysql::st execute failed: Duplicate entry '(.*)' for key '(branches\.)?PRIMARY'/; $schema->storage->txn_rollback; }; @@ -228,28 +229,31 @@ subtest 'update() tests' => sub { $schema->storage->txn_begin; - my $authorized_patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 1 } - }); + my $authorized_patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 1 } + } + ); my $password = 'thePassword123'; - $authorized_patron->set_password({ password => $password, skip_validation => 1 }); + $authorized_patron->set_password( { password => $password, skip_validation => 1 } ); my $auth_userid = $authorized_patron->userid; - my $unauthorized_patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 4 } - }); - $unauthorized_patron->set_password({ password => $password, skip_validation => 1 }); + my $unauthorized_patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 4 } + } + ); + $unauthorized_patron->set_password( { password => $password, skip_validation => 1 } ); my $unauth_userid = $unauthorized_patron->userid; - my $library = $builder->build_object({ class => 'Koha::Libraries' }); + my $library = $builder->build_object( { class => 'Koha::Libraries' } ); my $library_id = $library->branchcode; # Unauthorized attempt to update - $t->put_ok( "//$unauth_userid:$password@/api/v1/libraries/$library_id" - => json => { name => 'New unauthorized name change' } ) - ->status_is(403); + $t->put_ok( "//$unauth_userid:$password@/api/v1/libraries/$library_id" => json => + { name => 'New unauthorized name change' } )->status_is(403); # Attempt partial update on a PUT my $library_with_missing_field = { @@ -257,38 +261,33 @@ subtest 'update() tests' => sub { }; $t->put_ok( "//$auth_userid:$password@/api/v1/libraries/$library_id" => json => $library_with_missing_field ) - ->status_is(400) - ->json_has( "/errors" => - [ { message => "Missing property.", path => "/body/address2" } ] - ); + ->status_is(400)->json_has( "/errors" => [ { message => "Missing property.", path => "/body/address2" } ] ); - my $deleted_library = $builder->build_object( { class => 'Koha::Libraries' } ); + my $deleted_library = $builder->build_object( { class => 'Koha::Libraries' } ); my $library_with_updated_field = $deleted_library->to_api; $library_with_updated_field->{library_id} = $library_id; $deleted_library->delete; $t->put_ok( "//$auth_userid:$password@/api/v1/libraries/$library_id" => json => $library_with_updated_field ) - ->status_is(200, 'REST3.2.1') - ->json_is( '' => $library_with_updated_field, 'REST3.3.3' ); + ->status_is( 200, 'REST3.2.1' )->json_is( '' => $library_with_updated_field, 'REST3.3.3' ); # Authorized attempt to write invalid data - my $library_with_invalid_field = { %$library_with_updated_field }; + my $library_with_invalid_field = {%$library_with_updated_field}; $library_with_invalid_field->{'branchinvalid'} = 'Library invalid'; $t->put_ok( "//$auth_userid:$password@/api/v1/libraries/$library_id" => json => $library_with_invalid_field ) - ->status_is(400) - ->json_is( + ->status_is(400)->json_is( "/errors" => [ { message => "Properties not allowed: branchinvalid.", path => "/body" } ] - ); + ); - my $non_existent_code = 'nope'.int(rand(10000)); - $t->put_ok("//$auth_userid:$password@/api/v1/libraries/$non_existent_code" => json => $library_with_updated_field) - ->status_is(404); + my $non_existent_code = 'nope' . int( rand(10000) ); + $t->put_ok( "//$auth_userid:$password@/api/v1/libraries/$non_existent_code" => json => $library_with_updated_field ) + ->status_is(404); $schema->storage->txn_rollback; }; @@ -298,33 +297,34 @@ subtest 'delete() tests' => sub { $schema->storage->txn_begin; - my $authorized_patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 1 } - }); + my $authorized_patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 1 } + } + ); my $password = 'thePassword123'; - $authorized_patron->set_password({ password => $password, skip_validation => 1 }); + $authorized_patron->set_password( { password => $password, skip_validation => 1 } ); my $auth_userid = $authorized_patron->userid; - my $unauthorized_patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 4 } - }); - $unauthorized_patron->set_password({ password => $password, skip_validation => 1 }); + my $unauthorized_patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 4 } + } + ); + $unauthorized_patron->set_password( { password => $password, skip_validation => 1 } ); my $unauth_userid = $unauthorized_patron->userid; my $library_id = $builder->build( { source => 'Branch' } )->{branchcode}; # Unauthorized attempt to delete - $t->delete_ok( "//$unauth_userid:$password@/api/v1/libraries/$library_id" ) - ->status_is(403); + $t->delete_ok("//$unauth_userid:$password@/api/v1/libraries/$library_id")->status_is(403); - $t->delete_ok( "//$auth_userid:$password@/api/v1/libraries/$library_id" ) - ->status_is(204, 'REST3.2.4') - ->content_is('', 'REST3.3.4'); + $t->delete_ok("//$auth_userid:$password@/api/v1/libraries/$library_id")->status_is( 204, 'REST3.2.4' ) + ->content_is( '', 'REST3.3.4' ); - $t->delete_ok( "//$auth_userid:$password@/api/v1/libraries/$library_id" ) - ->status_is(404); + $t->delete_ok("//$auth_userid:$password@/api/v1/libraries/$library_id")->status_is(404); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/api/v1/oauth.t b/t/db_dependent/api/v1/oauth.t index c9381796e8..bc6734f69f 100755 --- a/t/db_dependent/api/v1/oauth.t +++ b/t/db_dependent/api/v1/oauth.t @@ -31,14 +31,13 @@ use Koha::Patrons; use t::lib::Mocks; use t::lib::TestBuilder; -my $t = Test::Mojo->new('Koha::REST::V1'); +my $t = Test::Mojo->new('Koha::REST::V1'); my $schema = Koha::Database->new->schema; my $builder = t::lib::TestBuilder->new(); if ( can_load( modules => { 'Net::OAuth2::AuthorizationServer' => undef } ) ) { plan tests => 2; -} -else { +} else { plan skip_all => 'Net::OAuth2::AuthorizationServer not available'; } @@ -46,37 +45,33 @@ subtest '/oauth/token tests' => sub { plan tests => 10; - t::lib::Mocks::mock_preference('RESTOAuth2ClientCredentials', 0); + t::lib::Mocks::mock_preference( 'RESTOAuth2ClientCredentials', 0 ); # Missing parameter grant_type - $t->post_ok('/api/v1/oauth/token') - ->status_is(400); + $t->post_ok('/api/v1/oauth/token')->status_is(400); # Wrong grant type - $t->post_ok('/api/v1/oauth/token', form => { grant_type => 'password' }) - ->status_is(400) - ->json_is({error => 'Unimplemented grant type'}); + $t->post_ok( '/api/v1/oauth/token', form => { grant_type => 'password' } )->status_is(400) + ->json_is( { error => 'Unimplemented grant type' } ); - t::lib::Mocks::mock_preference('RESTOAuth2ClientCredentials', 1); + t::lib::Mocks::mock_preference( 'RESTOAuth2ClientCredentials', 1 ); # No client_id/client_secret - $t->post_ok('/api/v1/oauth/token', form => { grant_type => 'client_credentials' }) - ->status_is(403) - ->json_is({error => 'unauthorized_client'}); + $t->post_ok( '/api/v1/oauth/token', form => { grant_type => 'client_credentials' } )->status_is(403) + ->json_is( { error => 'unauthorized_client' } ); subtest 'Client credentials in body' => sub { plan tests => 19; - run_oauth_tests( 'body' ); + run_oauth_tests('body'); }; subtest 'Client credentials in Authorization header' => sub { - plan tests => 19; - run_oauth_tests( 'header' ); + run_oauth_tests('header'); }; }; @@ -91,8 +86,8 @@ subtest 'Net::OAuth2::AuthorizationServer missing tests' => sub { # Enable the client credentials grant syspref t::lib::Mocks::mock_preference( 'RESTOAuth2ClientCredentials', 1 ); - my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => 2**4 } }); - my $api_key = Koha::ApiKey->new({ patron_id => $patron->id, description => 'blah' })->store; + my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { flags => 2**4 } } ); + my $api_key = Koha::ApiKey->new( { patron_id => $patron->id, description => 'blah' } )->store; my $form_data = { grant_type => 'client_credentials', @@ -100,9 +95,8 @@ subtest 'Net::OAuth2::AuthorizationServer missing tests' => sub { client_secret => $api_key->plain_text_secret }; - $t->post_ok( '/api/v1/oauth/token', form => $form_data )->status_is(200) - ->json_is( '/expires_in' => 3600 )->json_is( '/token_type' => 'Bearer' ) - ->json_has('/access_token'); + $t->post_ok( '/api/v1/oauth/token', form => $form_data )->status_is(200)->json_is( '/expires_in' => 3600 ) + ->json_is( '/token_type' => 'Bearer' )->json_has('/access_token'); my $access_token = $t->tx->res->json->{access_token}; @@ -110,29 +104,29 @@ subtest 'Net::OAuth2::AuthorizationServer missing tests' => sub { my $tx = $t->ua->build_tx( GET => '/api/v1/patrons' ); $tx->req->headers->authorization("Bearer $access_token"); - $t->request_ok($tx) - ->status_is(403); + $t->request_ok($tx)->status_is(403); - $t->post_ok( '/api/v1/oauth/token', form => $form_data ) - ->status_is(400) - ->json_is( { error => 'Unimplemented grant type' } ); + $t->post_ok( '/api/v1/oauth/token', form => $form_data )->status_is(400) + ->json_is( { error => 'Unimplemented grant type' } ); $schema->storage->txn_rollback; }; sub run_oauth_tests { - my ( $test_case ) = @_; + my ($test_case) = @_; $schema->storage->txn_begin; - my $patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { - flags => 0 # no permissions - }, - }); + my $patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { + flags => 0 # no permissions + }, + } + ); - my $api_key = Koha::ApiKey->new({ patron_id => $patron->id, description => 'blah' })->store; + my $api_key = Koha::ApiKey->new( { patron_id => $patron->id, description => 'blah' } )->store; t::lib::Mocks::mock_preference( 'RESTOAuth2ClientCredentials', 1 ); @@ -144,11 +138,8 @@ sub run_oauth_tests { $formData = { grant_type => 'client_credentials' }; - $t->post_ok("//$client_id:$client_secret@/api/v1/oauth/token", form => $formData) - ->status_is(200) - ->json_is('/expires_in' => 3600) - ->json_is('/token_type' => 'Bearer') - ->json_has('/access_token'); + $t->post_ok( "//$client_id:$client_secret@/api/v1/oauth/token", form => $formData )->status_is(200) + ->json_is( '/expires_in' => 3600 )->json_is( '/token_type' => 'Bearer' )->json_has('/access_token'); } else { $formData = { @@ -157,11 +148,8 @@ sub run_oauth_tests { client_secret => $api_key->plain_text_secret }; - $t->post_ok('/api/v1/oauth/token', form => $formData) - ->status_is(200) - ->json_is('/expires_in' => 3600) - ->json_is('/token_type' => 'Bearer') - ->json_has('/access_token'); + $t->post_ok( '/api/v1/oauth/token', form => $formData )->status_is(200)->json_is( '/expires_in' => 3600 ) + ->json_is( '/token_type' => 'Bearer' )->json_has('/access_token'); } my $access_token = $t->tx->res->json->{access_token}; @@ -170,13 +158,13 @@ sub run_oauth_tests { $t->get_ok('/api/v1/patrons')->status_is(401); # With access token, but without permissions, it returns 403 - my $tx = $t->ua->build_tx(GET => '/api/v1/patrons'); + my $tx = $t->ua->build_tx( GET => '/api/v1/patrons' ); $tx->req->headers->authorization("Bearer $access_token"); $t->request_ok($tx)->status_is(403); # With access token and permissions, it returns 200 - $patron->flags(2**4)->store; - $tx = $t->ua->build_tx(GET => '/api/v1/patrons'); + $patron->flags( 2**4 )->store; + $tx = $t->ua->build_tx( GET => '/api/v1/patrons' ); $tx->req->headers->authorization("Bearer $access_token"); $t->request_ok($tx)->status_is(200); @@ -185,38 +173,32 @@ sub run_oauth_tests { $token->expires( time - 1 )->store; $tx = $t->ua->build_tx( GET => '/api/v1/patrons' ); $tx->req->headers->authorization("Bearer $access_token"); - $t->request_ok($tx) - ->status_is(401); + $t->request_ok($tx)->status_is(401); # revoke key $api_key->active(0)->store; if ( $test_case eq 'header' ) { - $t->post_ok("//$client_id:$client_secret@/api/v1/oauth/token", form => $formData) - ->status_is(403) - ->json_is({ error => 'unauthorized_client' }); + $t->post_ok( "//$client_id:$client_secret@/api/v1/oauth/token", form => $formData )->status_is(403) + ->json_is( { error => 'unauthorized_client' } ); } else { - $t->post_ok('/api/v1/oauth/token', form => $formData) - ->status_is(403) - ->json_is({ error => 'unauthorized_client' }); + $t->post_ok( '/api/v1/oauth/token', form => $formData )->status_is(403) + ->json_is( { error => 'unauthorized_client' } ); } # disable client credentials grant - t::lib::Mocks::mock_preference('RESTOAuth2ClientCredentials', 0); + t::lib::Mocks::mock_preference( 'RESTOAuth2ClientCredentials', 0 ); # enable API key $api_key->active(1)->store; # Wrong grant type if ( $test_case eq 'header' ) { - $t->post_ok("//$client_id:$client_secret@/api/v1/oauth/token", form => $formData ) - ->status_is(400) - ->json_is({ error => 'Unimplemented grant type' }); - } - else { - $t->post_ok('/api/v1/oauth/token', form => $formData ) - ->status_is(400) - ->json_is({ error => 'Unimplemented grant type' }); + $t->post_ok( "//$client_id:$client_secret@/api/v1/oauth/token", form => $formData )->status_is(400) + ->json_is( { error => 'Unimplemented grant type' } ); + } else { + $t->post_ok( '/api/v1/oauth/token', form => $formData )->status_is(400) + ->json_is( { error => 'Unimplemented grant type' } ); } $schema->storage->txn_rollback; diff --git a/t/db_dependent/api/v1/pagination.t b/t/db_dependent/api/v1/pagination.t index fd6ab5479e..fa9702fc3b 100755 --- a/t/db_dependent/api/v1/pagination.t +++ b/t/db_dependent/api/v1/pagination.t @@ -52,8 +52,7 @@ subtest 'list() pagination tests' => sub { Koha::Cities->new->delete; # No cities, so empty array should be returned - $t->get_ok("//$userid:$password@/api/v1/cities")->status_is(200) - ->json_is( [] ); + $t->get_ok("//$userid:$password@/api/v1/cities")->status_is(200)->json_is( [] ); my $names = [ 'AA', @@ -76,30 +75,29 @@ subtest 'list() pagination tests' => sub { t::lib::Mocks::mock_preference( 'RESTdefaultPageSize', 20 ); my $cities = - $t->get_ok("//$userid:$password@/api/v1/cities")->status_is(200) - ->header_is( 'X-Total-Count', '10' ) - ->header_is( 'X-Base-Total-Count', '10' ) - ->header_unlike( 'Link', qr|rel="prev"| ) - ->header_unlike( 'Link', qr|rel="next"| ) - ->header_like( 'Link', - qr#(_per_page=20\&_page=1|_page=1\&_per_page=20)>\; rel="first"# ) - ->header_like( 'Link', - qr#(_per_page=20\&_page=1|_page=1\&_per_page=20)>\; rel="last"# ) - ->tx->res->json; + $t->get_ok("//$userid:$password@/api/v1/cities")->status_is(200)->header_is( 'X-Total-Count', '10' ) + ->header_is( 'X-Base-Total-Count', '10' )->header_unlike( 'Link', qr|rel="prev"| ) + ->header_unlike( 'Link', qr|rel="next"| )->header_like( + 'Link', + qr#(_per_page=20\&_page=1|_page=1\&_per_page=20)>\; rel="first"# + )->header_like( + 'Link', + qr#(_per_page=20\&_page=1|_page=1\&_per_page=20)>\; rel="last"# + )->tx->res->json; is( scalar @{$cities}, 10, '10 cities retrieved' ); $cities = - $t->get_ok("//$userid:$password@/api/v1/cities?q={\"name\":{\"-like\":\"\%A\"}}")->status_is(200) - ->header_is( 'X-Total-Count', '5', 'The resultset has 5 items' ) - ->header_is( 'X-Base-Total-Count', '10', 'The resultset, without the filter, has 10' ) - ->header_unlike( 'Link', qr|rel="prev"| ) - ->header_unlike( 'Link', qr|rel="next"| ) - ->header_like( 'Link', - qr#(_per_page=20.*\&_page=1.*|_page=1.*\&_per_page=20.*)>\; rel="first"# ) - ->header_like( 'Link', - qr#(_per_page=20.*\&_page=1.*|_page=1.*\&_per_page=20.*)>\; rel="last"# ) - ->tx->res->json; + $t->get_ok("//$userid:$password@/api/v1/cities?q={\"name\":{\"-like\":\"\%A\"}}")->status_is(200) + ->header_is( 'X-Total-Count', '5', 'The resultset has 5 items' ) + ->header_is( 'X-Base-Total-Count', '10', 'The resultset, without the filter, has 10' ) + ->header_unlike( 'Link', qr|rel="prev"| )->header_unlike( 'Link', qr|rel="next"| )->header_like( + 'Link', + qr#(_per_page=20.*\&_page=1.*|_page=1.*\&_per_page=20.*)>\; rel="first"# + )->header_like( + 'Link', + qr#(_per_page=20.*\&_page=1.*|_page=1.*\&_per_page=20.*)>\; rel="last"# + )->tx->res->json; is( scalar @{$cities}, 5, '5 cities retrieved' ); @@ -107,82 +105,80 @@ subtest 'list() pagination tests' => sub { # _per_page overrides RESTdefaultPageSize $cities = - $t->get_ok("//$userid:$password@/api/v1/cities?_per_page=20") - ->status_is(200) - ->header_is( 'X-Total-Count', '10' ) - ->header_is( 'X-Base-Total-Count', '10' ) - ->header_unlike( 'Link', qr|rel="prev"| ) - ->header_unlike( 'Link', qr|rel="next"| ) - ->header_like( 'Link', - qr#(_per_page=20\&_page=1|_page=1\&_per_page=20)>\; rel="first"# ) - ->header_like( 'Link', - qr#(_per_page=20\&_page=1|_page=1\&_per_page=20)>\; rel="last"# ) - ->tx->res->json; + $t->get_ok("//$userid:$password@/api/v1/cities?_per_page=20")->status_is(200) + ->header_is( 'X-Total-Count', '10' )->header_is( 'X-Base-Total-Count', '10' ) + ->header_unlike( 'Link', qr|rel="prev"| )->header_unlike( 'Link', qr|rel="next"| )->header_like( + 'Link', + qr#(_per_page=20\&_page=1|_page=1\&_per_page=20)>\; rel="first"# + )->header_like( + 'Link', + qr#(_per_page=20\&_page=1|_page=1\&_per_page=20)>\; rel="last"# + )->tx->res->json; is( scalar @{$cities}, 10, '10 cities retrieved' ); # page 1 $cities = - $t->get_ok("//$userid:$password@/api/v1/cities")->status_is(200) - ->header_is( 'X-Total-Count', '10' ) - ->header_is( 'X-Base-Total-Count', '10' ) - ->header_unlike( 'Link', qr|rel="prev"| ) - ->header_like( 'Link', - qr#(_per_page=3\&_page=1|_page=1\&_per_page=3)>\; rel="first"# ) - ->header_like( 'Link', - qr#(_per_page=3\&_page=2|_page=2\&_per_page=3)>\; rel="next"# ) - ->header_like( 'Link', - qr#(_per_page=3\&_page=4|_page=4\&_per_page=3)>\; rel="last"# ) - ->tx->res->json; + $t->get_ok("//$userid:$password@/api/v1/cities")->status_is(200)->header_is( 'X-Total-Count', '10' ) + ->header_is( 'X-Base-Total-Count', '10' )->header_unlike( 'Link', qr|rel="prev"| )->header_like( + 'Link', + qr#(_per_page=3\&_page=1|_page=1\&_per_page=3)>\; rel="first"# + )->header_like( + 'Link', + qr#(_per_page=3\&_page=2|_page=2\&_per_page=3)>\; rel="next"# + )->header_like( + 'Link', + qr#(_per_page=3\&_page=4|_page=4\&_per_page=3)>\; rel="last"# + )->tx->res->json; is( scalar @{$cities}, 3, '3 cities retrieved' ); # This tests X-Base-Total-Count, .* is used for q=, as we don't want # to add all combinations to the regex $cities = - $t->get_ok("//$userid:$password@/api/v1/cities?_per_page=2&_page=2&q={\"name\":{\"-like\":\"\%A\"}}")->status_is(200) - ->header_is( 'X-Total-Count', '5' ) - ->header_is( 'X-Base-Total-Count', '10' ) - ->header_like( 'Link', - qr#(_per_page=2.*\&_page=1.*|_page=1.*\&_per_page=2.*)>\; rel="prev"# ) - ->header_like( 'Link', - qr#(_per_page=2.*\&_page=1.*|_page=1.*\&_per_page=2.*)>\; rel="first"# ) - ->header_like( 'Link', - qr#(_per_page=2.*\&_page=3.*|_page=3.*\&_per_page=2.*)>\; rel="next"# ) - ->header_like( 'Link', - qr#(_per_page=2.*\&_page=3.*|_page=3.*\&_per_page=2.*)>\; rel="last"# ) - ->tx->res->json; + $t->get_ok("//$userid:$password@/api/v1/cities?_per_page=2&_page=2&q={\"name\":{\"-like\":\"\%A\"}}") + ->status_is(200)->header_is( 'X-Total-Count', '5' )->header_is( 'X-Base-Total-Count', '10' )->header_like( + 'Link', + qr#(_per_page=2.*\&_page=1.*|_page=1.*\&_per_page=2.*)>\; rel="prev"# + )->header_like( + 'Link', + qr#(_per_page=2.*\&_page=1.*|_page=1.*\&_per_page=2.*)>\; rel="first"# + )->header_like( + 'Link', + qr#(_per_page=2.*\&_page=3.*|_page=3.*\&_per_page=2.*)>\; rel="next"# + )->header_like( + 'Link', + qr#(_per_page=2.*\&_page=3.*|_page=3.*\&_per_page=2.*)>\; rel="last"# + )->tx->res->json; is( scalar @{$cities}, 2, '2 cities retrieved' ); # last page, with only one result $cities = - $t->get_ok("//$userid:$password@/api/v1/cities?_page=4")->status_is(200) - ->header_is( 'X-Total-Count', '10' ) - ->header_is( 'X-Base-Total-Count', '10' ) - ->header_like( 'Link', - qr#(_per_page=3\&_page=3|_page=3\&_per_page=3)>\; rel="prev"# ) - ->header_like( 'Link', - qr#(_per_page=3\&_page=1|_page=1\&_per_page=3)>\; rel="first"# ) - ->header_unlike( 'Link', qr#rel="next"# ) - ->header_like( 'Link', - qr#(_per_page=3\&_page=4|_page=4\&_per_page=3)>\; rel="last"# ) - ->tx->res->json; + $t->get_ok("//$userid:$password@/api/v1/cities?_page=4")->status_is(200)->header_is( 'X-Total-Count', '10' ) + ->header_is( 'X-Base-Total-Count', '10' )->header_like( + 'Link', + qr#(_per_page=3\&_page=3|_page=3\&_per_page=3)>\; rel="prev"# + )->header_like( + 'Link', + qr#(_per_page=3\&_page=1|_page=1\&_per_page=3)>\; rel="first"# + )->header_unlike( 'Link', qr#rel="next"# )->header_like( + 'Link', + qr#(_per_page=3\&_page=4|_page=4\&_per_page=3)>\; rel="last"# + )->tx->res->json; is( scalar @{$cities}, 1, '1 city retrieved' ); $cities = - $t->get_ok("//$userid:$password@/api/v1/cities?_per_page=-1") - ->status_is(200) - ->header_is( 'X-Total-Count', '10' ) - ->header_is( 'X-Base-Total-Count', '10' ) - ->header_unlike( 'Link', qr|rel="prev"| ) - ->header_unlike( 'Link', qr|rel="next"| ) - ->header_like( 'Link', - qr#(_per_page=-1\&_page=1|_page=1\&_per_page=-1)>\; rel="first"# ) - ->header_like( 'Link', - qr#(_per_page=-1\&_page=1|_page=1\&_per_page=-1)>\; rel="last"# ) - ->tx->res->json; + $t->get_ok("//$userid:$password@/api/v1/cities?_per_page=-1")->status_is(200) + ->header_is( 'X-Total-Count', '10' )->header_is( 'X-Base-Total-Count', '10' ) + ->header_unlike( 'Link', qr|rel="prev"| )->header_unlike( 'Link', qr|rel="next"| )->header_like( + 'Link', + qr#(_per_page=-1\&_page=1|_page=1\&_per_page=-1)>\; rel="first"# + )->header_like( + 'Link', + qr#(_per_page=-1\&_page=1|_page=1\&_per_page=-1)>\; rel="last"# + )->tx->res->json; is( scalar @{$cities}, 10, '10 cities retrieved, -1 means all' ); diff --git a/t/db_dependent/api/v1/password_validation.t b/t/db_dependent/api/v1/password_validation.t index e5d891200f..f0c6035ad4 100755 --- a/t/db_dependent/api/v1/password_validation.t +++ b/t/db_dependent/api/v1/password_validation.t @@ -39,7 +39,7 @@ $schema->storage->txn_begin; my $librarian = $builder->build_object( { class => 'Koha::Patrons', - value => { flags => 2 ** 4 } # borrowers flag = 4 + value => { flags => 2**4 } # borrowers flag = 4 } ); my $password = 'thePassword123'; @@ -59,15 +59,13 @@ subtest 'password validation - account lock out' => sub { password => "bad", }; - $t->post_ok( "//$userid:$password@/api/v1/auth/password/validation" => json => $json ) - ->status_is(400) - ->json_is({ error => q{Validation failed} }); + $t->post_ok( "//$userid:$password@/api/v1/auth/password/validation" => json => $json )->status_is(400) + ->json_is( { error => q{Validation failed} } ); $json->{password} = $password; - $t->post_ok( "//$userid:$password@/api/v1/auth/password/validation" => json => $json ) - ->status_is(400) - ->json_is({ error => q{Validation failed} }); + $t->post_ok( "//$userid:$password@/api/v1/auth/password/validation" => json => $json )->status_is(400) + ->json_is( { error => q{Validation failed} } ); $schema->storage->txn_rollback; }; @@ -81,7 +79,7 @@ subtest 'password validation - unauthorized user' => sub { my $patron = $builder->build_object( { class => 'Koha::Patrons', - value => { flags => 2 ** 2 } # catalogue flag = 2 + value => { flags => 2**2 } # catalogue flag = 2 } ); my $password = 'thePassword123'; @@ -93,9 +91,8 @@ subtest 'password validation - unauthorized user' => sub { password => "test", }; - $t->post_ok( "//$userid:$password@/api/v1/auth/password/validation" => json => $json ) - ->status_is(403) - ->json_is('/error' => 'Authorization failure. Missing required permission(s).'); + $t->post_ok( "//$userid:$password@/api/v1/auth/password/validation" => json => $json )->status_is(403) + ->json_is( '/error' => 'Authorization failure. Missing required permission(s).' ); $schema->storage->txn_rollback; }; @@ -111,8 +108,7 @@ subtest 'password validation - unauthenticated user' => sub { }; $t->post_ok( "/api/v1/auth/password/validation" => json => $json ) - ->json_is( '/error' => 'Authentication failure.' ) - ->status_is(401); + ->json_is( '/error' => 'Authentication failure.' )->status_is(401); $schema->storage->txn_rollback; }; @@ -193,7 +189,8 @@ subtest 'Password validation - authorized requests tests' => sub { }; $t->post_ok( "//$userid:$password@/api/v1/auth/password/validation" => json => $json ) - ->status_is( 400, 'Validating using a cardnumber as userid fails' )->json_is( { error => 'Validation failed' } ); + ->status_is( 400, 'Validating using a cardnumber as userid fails' ) + ->json_is( { error => 'Validation failed' } ); $json = { identifier => $userid, diff --git a/t/db_dependent/api/v1/patrons.t b/t/db_dependent/api/v1/patrons.t index 4fb5836df4..22b8cc5cc1 100755 --- a/t/db_dependent/api/v1/patrons.t +++ b/t/db_dependent/api/v1/patrons.t @@ -76,7 +76,7 @@ subtest 'list() tests' => sub { plan tests => 3; $schema->storage->txn_begin; - unauthorized_access_tests('GET', undef, undef); + unauthorized_access_tests( 'GET', undef, undef ); $schema->storage->txn_rollback; subtest 'librarian access tests' => sub { @@ -88,7 +88,7 @@ subtest 'list() tests' => sub { my $librarian = $builder->build_object( { class => 'Koha::Patrons', - value => { flags => 2 ** 2 } # catalog only, no additional permissions + value => { flags => 2**2 } # catalog only, no additional permissions } ); @@ -101,15 +101,14 @@ subtest 'list() tests' => sub { module_bit => 4, code => 'view_borrower_infos_from_any_libraries', }, - } + } ); my $password = 'thePassword123'; $librarian->set_password( { password => $password, skip_validation => 1 } ); my $userid = $librarian->userid; - $t->get_ok("//$userid:$password@/api/v1/patrons/") - ->status_is(403, 'Basic librarian unable to see patrons'); + $t->get_ok("//$userid:$password@/api/v1/patrons/")->status_is( 403, 'Basic librarian unable to see patrons' ); $builder->build( { @@ -119,23 +118,19 @@ subtest 'list() tests' => sub { module_bit => 4, code => 'list_borrowers', }, - } + } ); - $t->get_ok("//$userid:$password@/api/v1/patrons") - ->status_is(200, 'list_borrowers makes /patrons accessible'); + $t->get_ok("//$userid:$password@/api/v1/patrons")->status_is( 200, 'list_borrowers makes /patrons accessible' ); - $t->get_ok("//$userid:$password@/api/v1/patrons?cardnumber=" . $librarian->cardnumber) - ->status_is(200) - ->json_is('/0/cardnumber' => $librarian->cardnumber); + $t->get_ok( "//$userid:$password@/api/v1/patrons?cardnumber=" . $librarian->cardnumber )->status_is(200) + ->json_is( '/0/cardnumber' => $librarian->cardnumber ); - $t->get_ok("//$userid:$password@/api/v1/patrons?q={\"cardnumber\":\"" . $librarian->cardnumber ."\"}") - ->status_is(200) - ->json_is('/0/cardnumber' => $librarian->cardnumber); + $t->get_ok( "//$userid:$password@/api/v1/patrons?q={\"cardnumber\":\"" . $librarian->cardnumber . "\"}" ) + ->status_is(200)->json_is( '/0/cardnumber' => $librarian->cardnumber ); - $t->get_ok("//$userid:$password@/api/v1/patrons?address2=" . $librarian->address2) - ->status_is(200) - ->json_is('/0/address2' => $librarian->address2); + $t->get_ok( "//$userid:$password@/api/v1/patrons?address2=" . $librarian->address2 )->status_is(200) + ->json_is( '/0/address2' => $librarian->address2 ); subtest 'restricted & expired' => sub { @@ -145,24 +140,20 @@ subtest 'list() tests' => sub { AddDebarment( { borrowernumber => $patron->borrowernumber } ); - $t->get_ok("//$userid:$password@/api/v1/patrons?restricted=" . Mojo::JSON->true . "&cardnumber=" . $patron->cardnumber ) - ->status_is(200) - ->json_has('/0/restricted') - ->json_is( '/0/restricted' => Mojo::JSON->true ) - ->json_has('/0/expired') - ->json_is( '/0/expired' => Mojo::JSON->false ) - ->json_hasnt('/1'); + $t->get_ok( "//$userid:$password@/api/v1/patrons?restricted=" + . Mojo::JSON->true + . "&cardnumber=" + . $patron->cardnumber )->status_is(200)->json_has('/0/restricted') + ->json_is( '/0/restricted' => Mojo::JSON->true )->json_has('/0/expired') + ->json_is( '/0/expired' => Mojo::JSON->false )->json_hasnt('/1'); - $patron->dateexpiry(dt_from_string->subtract(days => 2))->store; - $t->get_ok("//$userid:$password@/api/v1/patrons/" . $patron->borrowernumber) - ->status_is(200) - ->json_has('/expired') - ->json_is( '/expired' => Mojo::JSON->true ); + $patron->dateexpiry( dt_from_string->subtract( days => 2 ) )->store; + $t->get_ok( "//$userid:$password@/api/v1/patrons/" . $patron->borrowernumber )->status_is(200) + ->json_has('/expired')->json_is( '/expired' => Mojo::JSON->true ); $t->get_ok( "//$userid:$password@/api/v1/patrons?" - . 'q={"extended_attributes.type":"CODE"}' => - { 'x-koha-embed' => 'extended_attributes' } ) - ->status_is( 200, "Works, doesn't explode" ); + . 'q={"extended_attributes.type":"CODE"}' => { 'x-koha-embed' => 'extended_attributes' } ) + ->status_is( 200, "Works, doesn't explode" ); }; subtest 'searching date and date-time fields' => sub { @@ -184,13 +175,17 @@ subtest 'list() tests' => sub { my $last_seen_rfc3339 = $last_seen . "z"; - $t->get_ok("//$userid:$password@/api/v1/patrons?date_of_birth=" . $date_of_birth . "&cardnumber=" . $patron->cardnumber) - ->status_is(200) - ->json_is( '/0/patron_id' => $patron->id, 'Filtering by date works' ); + $t->get_ok( "//$userid:$password@/api/v1/patrons?date_of_birth=" + . $date_of_birth + . "&cardnumber=" + . $patron->cardnumber )->status_is(200) + ->json_is( '/0/patron_id' => $patron->id, 'Filtering by date works' ); - $t->get_ok("//$userid:$password@/api/v1/patrons?last_seen=" . $last_seen_rfc3339 . "&cardnumber=" . $patron->cardnumber) - ->status_is(200) - ->json_is( '/0/patron_id' => $patron->id, 'Filtering by date-time works' ); + $t->get_ok( "//$userid:$password@/api/v1/patrons?last_seen=" + . $last_seen_rfc3339 + . "&cardnumber=" + . $patron->cardnumber )->status_is(200) + ->json_is( '/0/patron_id' => $patron->id, 'Filtering by date-time works' ); my $q = encode_json( { @@ -199,9 +194,8 @@ subtest 'list() tests' => sub { } ); - $t->get_ok("//$userid:$password@/api/v1/patrons?q=$q") - ->status_is(200) - ->json_is( '/0/patron_id' => $patron->id, 'Filtering by date works' ); + $t->get_ok("//$userid:$password@/api/v1/patrons?q=$q")->status_is(200) + ->json_is( '/0/patron_id' => $patron->id, 'Filtering by date works' ); $q = encode_json( { @@ -210,9 +204,8 @@ subtest 'list() tests' => sub { } ); - $t->get_ok("//$userid:$password@/api/v1/patrons?q=$q") - ->status_is(200) - ->json_is( '/0/patron_id' => $patron->id, 'Filtering by date-time works' ); + $t->get_ok("//$userid:$password@/api/v1/patrons?q=$q")->status_is(200) + ->json_is( '/0/patron_id' => $patron->id, 'Filtering by date-time works' ); }; $schema->storage->txn_rollback; @@ -224,18 +217,22 @@ subtest 'list() tests' => sub { $schema->storage->txn_begin; - my $library_1 = $builder->build_object({ class => 'Koha::Libraries' }); - my $library_2 = $builder->build_object({ class => 'Koha::Libraries' }); + my $library_1 = $builder->build_object( { class => 'Koha::Libraries' } ); + my $library_2 = $builder->build_object( { class => 'Koha::Libraries' } ); - my $patron_1 = $builder->build_object({ class => 'Koha::Patrons', value => { branchcode => $library_1->id } }); - my $patron_2 = $builder->build_object({ class => 'Koha::Patrons', value => { branchcode => $library_1->id } }); - my $patron_3 = $builder->build_object({ class => 'Koha::Patrons', value => { branchcode => $library_2->id } }); + my $patron_1 = + $builder->build_object( { class => 'Koha::Patrons', value => { branchcode => $library_1->id } } ); + my $patron_2 = + $builder->build_object( { class => 'Koha::Patrons', value => { branchcode => $library_1->id } } ); + my $patron_3 = + $builder->build_object( { class => 'Koha::Patrons', value => { branchcode => $library_2->id } } ); - my @libraries_where_can_see_patrons = ($library_1->id, $library_2->id); + my @libraries_where_can_see_patrons = ( $library_1->id, $library_2->id ); my $mocked_patron = Test::MockModule->new('Koha::Patron'); - $mocked_patron->mock( 'libraries_where_can_see_patrons', sub - { + $mocked_patron->mock( + 'libraries_where_can_see_patrons', + sub { return @libraries_where_can_see_patrons; } ); @@ -250,18 +247,17 @@ subtest 'list() tests' => sub { $librarian->set_password( { password => $password, skip_validation => 1 } ); my $userid = $librarian->userid; - $t->get_ok("//$userid:$password@/api/v1/patrons?_order_by=patron_id&q=" . encode_json({ library_id => [ $library_1->id, $library_2->id ] })) - ->status_is(200) - ->json_is( '/0/patron_id' => $patron_1->id ) - ->json_is( '/1/patron_id' => $patron_2->id ) - ->json_is( '/2/patron_id' => $patron_3->id ); + $t->get_ok( "//$userid:$password@/api/v1/patrons?_order_by=patron_id&q=" + . encode_json( { library_id => [ $library_1->id, $library_2->id ] } ) )->status_is(200) + ->json_is( '/0/patron_id' => $patron_1->id )->json_is( '/1/patron_id' => $patron_2->id ) + ->json_is( '/2/patron_id' => $patron_3->id ); - @libraries_where_can_see_patrons = ($library_2->id); + @libraries_where_can_see_patrons = ( $library_2->id ); - my $res = $t->get_ok("//$userid:$password@/api/v1/patrons?_order_by=patron_id&q=" . encode_json({ library_id => [ $library_1->id, $library_2->id ] })) - ->status_is(200) - ->json_is( '/0/patron_id' => $patron_3->id, 'Returns the only allowed patron' ) - ->tx->res->json; + my $res = + $t->get_ok( "//$userid:$password@/api/v1/patrons?_order_by=patron_id&q=" + . encode_json( { library_id => [ $library_1->id, $library_2->id ] } ) )->status_is(200) + ->json_is( '/0/patron_id' => $patron_3->id, 'Returns the only allowed patron' )->tx->res->json; is( scalar @{$res}, 1, 'Only one patron returned' ); @@ -274,7 +270,7 @@ subtest 'get() tests' => sub { plan tests => 4; $schema->storage->txn_begin; - unauthorized_access_tests('GET', -1, undef); + unauthorized_access_tests( 'GET', -1, undef ); $schema->storage->txn_rollback; subtest 'librarian access tests' => sub { @@ -286,7 +282,7 @@ subtest 'get() tests' => sub { my $librarian = $builder->build_object( { class => 'Koha::Patrons', - value => { flags => 2 ** 2 } # catalog only, no additional permissions + value => { flags => 2**2 } # catalog only, no additional permissions } ); @@ -299,7 +295,7 @@ subtest 'get() tests' => sub { module_bit => 4, code => 'view_borrower_infos_from_any_libraries', }, - } + } ); my $password = 'thePassword123'; @@ -308,8 +304,8 @@ subtest 'get() tests' => sub { my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); - $t->get_ok("//$userid:$password@/api/v1/patrons/" . $patron->id) - ->status_is(403, 'Basic librarian unable to see patrons'); + $t->get_ok( "//$userid:$password@/api/v1/patrons/" . $patron->id ) + ->status_is( 403, 'Basic librarian unable to see patrons' ); $builder->build( { @@ -319,15 +315,13 @@ subtest 'get() tests' => sub { module_bit => 4, code => 'list_borrowers', }, - } + } ); - $t->get_ok("//$userid:$password@/api/v1/patrons/" . $patron->id) - ->status_is(200, 'list_borrowers permission makes patron visible') - ->json_is('/patron_id' => $patron->id) - ->json_is('/category_id' => $patron->categorycode ) - ->json_is('/surname' => $patron->surname) - ->json_is('/patron_card_lost' => Mojo::JSON->false ); + $t->get_ok( "//$userid:$password@/api/v1/patrons/" . $patron->id ) + ->status_is( 200, 'list_borrowers permission makes patron visible' ) + ->json_is( '/patron_id' => $patron->id )->json_is( '/category_id' => $patron->categorycode ) + ->json_is( '/surname' => $patron->surname )->json_is( '/patron_card_lost' => Mojo::JSON->false ); $schema->storage->txn_rollback; }; @@ -338,25 +332,30 @@ subtest 'get() tests' => sub { $schema->storage->txn_begin; - my $library_1 = $builder->build_object({ class => 'Koha::Libraries' }); - my $library_2 = $builder->build_object({ class => 'Koha::Libraries' }); - my $library_3 = $builder->build_object({ class => 'Koha::Libraries' }); + my $library_1 = $builder->build_object( { class => 'Koha::Libraries' } ); + my $library_2 = $builder->build_object( { class => 'Koha::Libraries' } ); + my $library_3 = $builder->build_object( { class => 'Koha::Libraries' } ); - my $patron_1 = $builder->build_object({ class => 'Koha::Patrons', value => { branchcode => $library_1->id } }); - my $patron_2 = $builder->build_object({ class => 'Koha::Patrons', value => { branchcode => $library_2->id } }); - my $patron_3 = $builder->build_object({ class => 'Koha::Patrons', value => { branchcode => $library_3->id } }); + my $patron_1 = + $builder->build_object( { class => 'Koha::Patrons', value => { branchcode => $library_1->id } } ); + my $patron_2 = + $builder->build_object( { class => 'Koha::Patrons', value => { branchcode => $library_2->id } } ); + my $patron_3 = + $builder->build_object( { class => 'Koha::Patrons', value => { branchcode => $library_3->id } } ); - my @libraries_where_can_see_patrons = ($library_1->id, $library_2->id); + my @libraries_where_can_see_patrons = ( $library_1->id, $library_2->id ); my $mocked_patron = Test::MockModule->new('Koha::Patron'); - $mocked_patron->mock( 'libraries_where_can_see_patrons', sub - { + $mocked_patron->mock( + 'libraries_where_can_see_patrons', + sub { return @libraries_where_can_see_patrons; } ); my $librarian = $builder->build_object( - { class => 'Koha::Patrons', + { + class => 'Koha::Patrons', value => { flags => 2**4, branchcode => $library_3->id } # borrowers flag = 4 } ); @@ -364,19 +363,16 @@ subtest 'get() tests' => sub { $librarian->set_password( { password => $password, skip_validation => 1 } ); my $userid = $librarian->userid; - $t->get_ok("//$userid:$password@/api/v1/patrons/" . $patron_1->id ) - ->status_is(200) - ->json_is( '/patron_id' => $patron_1->id ); + $t->get_ok( "//$userid:$password@/api/v1/patrons/" . $patron_1->id )->status_is(200) + ->json_is( '/patron_id' => $patron_1->id ); - $t->get_ok("//$userid:$password@/api/v1/patrons/" . $patron_2->id ) - ->status_is(200) - ->json_is( '/patron_id' => $patron_2->id ); + $t->get_ok( "//$userid:$password@/api/v1/patrons/" . $patron_2->id )->status_is(200) + ->json_is( '/patron_id' => $patron_2->id ); - @libraries_where_can_see_patrons = ($library_1->id); + @libraries_where_can_see_patrons = ( $library_1->id ); - $t->get_ok("//$userid:$password@/api/v1/patrons/" . $patron_1->id ) - ->status_is(200) - ->json_is( '/patron_id' => $patron_1->id ); + $t->get_ok( "//$userid:$password@/api/v1/patrons/" . $patron_1->id )->status_is(200) + ->json_is( '/patron_id' => $patron_1->id ); $t->get_ok( "//$userid:$password@/api/v1/patrons/" . $patron_2->id )->status_is(404) ->json_is( '/error' => 'Patron not found' ); @@ -423,9 +419,9 @@ subtest 'add() tests' => sub { value => { flags => 2**4 } # borrowers flag = 4 } ); - my $patron = $builder->build_object( { class => 'Koha::Patrons' } )->to_api({ user => $librarian }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } )->to_api( { user => $librarian } ); - unauthorized_access_tests('POST', undef, $patron); + unauthorized_access_tests( 'POST', undef, $patron ); $schema->storage->txn_rollback; @@ -453,7 +449,8 @@ subtest 'add() tests' => sub { ); my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); - my $newpatron = $patron->to_api({ user => $librarian }); + my $newpatron = $patron->to_api( { user => $librarian } ); + # delete RO attributes delete $newpatron->{patron_id}; delete $newpatron->{restricted}; @@ -461,8 +458,9 @@ subtest 'add() tests' => sub { delete $newpatron->{anonymized}; # Create a library just to make sure its ID doesn't exist on the DB - my $library_to_delete = $builder->build_object({ class => 'Koha::Libraries' }); + my $library_to_delete = $builder->build_object( { class => 'Koha::Libraries' } ); my $deleted_library_id = $library_to_delete->id; + # Delete library $library_to_delete->delete; @@ -472,34 +470,33 @@ subtest 'add() tests' => sub { $newpatron->{library_id} = $deleted_library_id; - $t->post_ok("//$userid:$password@/api/v1/patrons" => json => $newpatron) - ->status_is(400) - ->json_is('/error' => "Problem with ". $newpatron->{userid} ); + $t->post_ok( "//$userid:$password@/api/v1/patrons" => json => $newpatron )->status_is(400) + ->json_is( '/error' => "Problem with " . $newpatron->{userid} ); $newpatron->{library_id} = $patron->branchcode; # Create a library just to make sure its ID doesn't exist on the DB - my $category_to_delete = $builder->build_object({ class => 'Koha::Patron::Categories' }); + my $category_to_delete = $builder->build_object( { class => 'Koha::Patron::Categories' } ); my $deleted_category_id = $category_to_delete->id; + # Delete library $category_to_delete->delete; - $newpatron->{category_id} = $deleted_category_id; # Test invalid patron category + $newpatron->{category_id} = $deleted_category_id; # Test invalid patron category - $t->post_ok("//$userid:$password@/api/v1/patrons" => json => $newpatron) - ->status_is(400) - ->json_is('/error' => "Given category_id does not exist"); + $t->post_ok( "//$userid:$password@/api/v1/patrons" => json => $newpatron )->status_is(400) + ->json_is( '/error' => "Given category_id does not exist" ); $newpatron->{category_id} = $patron->categorycode; $newpatron->{falseproperty} = "Non existent property"; - $t->post_ok("//$userid:$password@/api/v1/patrons" => json => $newpatron) - ->status_is(400); + $t->post_ok( "//$userid:$password@/api/v1/patrons" => json => $newpatron )->status_is(400); delete $newpatron->{falseproperty}; - my $patron_to_delete = $builder->build_object({ class => 'Koha::Patrons' }); - $newpatron = $patron_to_delete->to_api({ user => $librarian }); + my $patron_to_delete = $builder->build_object( { class => 'Koha::Patrons' } ); + $newpatron = $patron_to_delete->to_api( { user => $librarian } ); + # delete RO attributes delete $newpatron->{patron_id}; delete $newpatron->{restricted}; @@ -509,35 +506,32 @@ subtest 'add() tests' => sub { # Set a date field $newpatron->{date_of_birth} = '1980-06-18'; + # Set a date-time field - $newpatron->{last_seen} = output_pref({ dt => dt_from_string->add( days => -1 ), dateformat => 'rfc3339' }); + $newpatron->{last_seen} = output_pref( { dt => dt_from_string->add( days => -1 ), dateformat => 'rfc3339' } ); t::lib::Mocks::mock_preference( 'AutoEmailNewUser', 0 ); $letter_enqueued = 0; $t->post_ok( "//$userid:$password@/api/v1/patrons" => { 'x-koha-override' => 'welcome_yes' } => json => $newpatron ) - ->status_is(201, 'Patron created successfully') - ->header_like( + ->status_is( 201, 'Patron created successfully' )->header_like( Location => qr|^\/api\/v1\/patrons/\d*|, 'REST3.4.1' - ) - ->json_has('/patron_id', 'got a patron_id') - ->json_is( '/cardnumber' => $newpatron->{cardnumber}) - ->json_is( '/surname' => $newpatron->{surname}) - ->json_is( '/firstname' => $newpatron->{firstname}) - ->json_is( '/date_of_birth' => $newpatron->{date_of_birth}, 'Date field set (Bug 28585)' ) - ->json_is( '/last_seen' => $newpatron->{last_seen}, 'Date-time field set (Bug 28585)' ); + )->json_has( '/patron_id', 'got a patron_id' )->json_is( '/cardnumber' => $newpatron->{cardnumber} ) + ->json_is( '/surname' => $newpatron->{surname} )->json_is( '/firstname' => $newpatron->{firstname} ) + ->json_is( '/date_of_birth' => $newpatron->{date_of_birth}, 'Date field set (Bug 28585)' ) + ->json_is( '/last_seen' => $newpatron->{last_seen}, 'Date-time field set (Bug 28585)' ); my $p = Koha::Patrons->find( { cardnumber => $newpatron->{cardnumber} } ); - is( $letter_enqueued, 1 , "Patron got welcome notice" ); + is( $letter_enqueued, 1, "Patron got welcome notice" ); - $newpatron->{userid} = undef; # force regeneration + $newpatron->{userid} = undef; # force regeneration warning_like { - $t->post_ok("//$userid:$password@/api/v1/patrons" => json => $newpatron) - ->status_is(409) - ->json_has( '/error', 'Fails when trying to POST duplicate cardnumber' ) - ->json_like( '/conflict' => qr/(borrowers\.)?cardnumber/ ); } - qr/DBD::mysql::st execute failed: Duplicate entry '(.*?)' for key '(borrowers\.)?cardnumber'/; + $t->post_ok( "//$userid:$password@/api/v1/patrons" => json => $newpatron )->status_is(409) + ->json_has( '/error', 'Fails when trying to POST duplicate cardnumber' ) + ->json_like( '/conflict' => qr/(borrowers\.)?cardnumber/ ); + } + qr/DBD::mysql::st execute failed: Duplicate entry '(.*?)' for key '(borrowers\.)?cardnumber'/; subtest 'extended_attributes handling tests' => sub { @@ -573,9 +567,7 @@ subtest 'add() tests' => sub { "city" => "Konstanz", "library_id" => "MPL" } - )->status_is(400) - ->json_is( '/error' => - "Missing mandatory extended attribute (type=$type)" ); + )->status_is(400)->json_is( '/error' => "Missing mandatory extended attribute (type=$type)" ); is( Koha::Patrons->search->count, $patrons_count, 'No patron added' ); @@ -589,9 +581,7 @@ subtest 'add() tests' => sub { "city" => "Konstanz", "library_id" => "MPL" } - )->status_is(400) - ->json_is( '/error' => - "Tried to use an invalid attribute type. type=$type" ); + )->status_is(400)->json_is( '/error' => "Tried to use an invalid attribute type. type=$type" ); is( Koha::Patrons->search->count, $patrons_count, 'No patron added' ); @@ -606,8 +596,7 @@ subtest 'add() tests' => sub { "library_id" => "MPL" } )->status_is(400) - ->json_is( '/error' => - "Tried to add more than one non-repeatable attributes. type=$code value=$attr" ); + ->json_is( '/error' => "Tried to add more than one non-repeatable attributes. type=$code value=$attr" ); is( Koha::Patrons->search->count, $patrons_count, 'No patron added' ); @@ -622,14 +611,16 @@ subtest 'add() tests' => sub { "library_id" => "MPL" } )->status_is(400) - ->json_is( '/error' => - "Your action breaks a unique constraint on the attribute. type=$code value=$attr" ); + ->json_is( + '/error' => "Your action breaks a unique constraint on the attribute. type=$code value=$attr" ); is( Koha::Patrons->search->count, $patrons_count, 'No patron added' ); $mocked_patron->unmock('extended_attributes'); + # Temporarily get rid of mandatory attribute types - Koha::Patron::Attribute::Types->search({ mandatory => 1 })->delete; + Koha::Patron::Attribute::Types->search( { mandatory => 1 } )->delete; + # Create a couple attribute attribute types my $repeatable_1 = $builder->build_object( { @@ -656,12 +647,12 @@ subtest 'add() tests' => sub { my $patron_id = $t->post_ok( "//$userid:$password@/api/v1/patrons" => json => { - "firstname" => "Katrina", - "surname" => "Fischer", - "address" => "Somewhere", - "category_id" => "ST", - "city" => "Konstanz", - "library_id" => "MPL", + "firstname" => "Katrina", + "surname" => "Fischer", + "address" => "Somewhere", + "category_id" => "ST", + "city" => "Konstanz", + "library_id" => "MPL", "extended_attributes" => [ { type => $repeatable_1->code, value => 'a' }, { type => $repeatable_1->code, value => 'b' }, @@ -670,9 +661,10 @@ subtest 'add() tests' => sub { { type => $repeatable_2->code, value => 'e' } ] } - )->status_is(201, 'Patron added')->tx->res->json->{patron_id}; - my $extended_attributes = join( ' ', sort map {$_->attribute} Koha::Patrons->find($patron_id)->extended_attributes->as_list); - is( $extended_attributes, 'a b c d e', 'Extended attributes are stored correctly'); + )->status_is( 201, 'Patron added' )->tx->res->json->{patron_id}; + my $extended_attributes = + join( ' ', sort map { $_->attribute } Koha::Patrons->find($patron_id)->extended_attributes->as_list ); + is( $extended_attributes, 'a b c d e', 'Extended attributes are stored correctly' ); }; subtest 'default patron messaging preferences handling' => sub { @@ -681,12 +673,14 @@ subtest 'add() tests' => sub { t::lib::Mocks::mock_preference( 'EnhancedMessagingPreferences', 1 ); - C4::Members::Messaging::SetMessagingPreference({ - categorycode => 'ST', - message_attribute_id => 1, - message_transport_types => ['email'], - wants_digest => 1 - }); + C4::Members::Messaging::SetMessagingPreference( + { + categorycode => 'ST', + message_attribute_id => 1, + message_transport_types => ['email'], + wants_digest => 1 + } + ); my $patron_id = $t->post_ok( "//$userid:$password@/api/v1/patrons" => json => { @@ -697,17 +691,18 @@ subtest 'add() tests' => sub { "city" => "Smallville", "library_id" => "MPL", } - )->status_is(201, 'Patron added')->tx->res->json->{patron_id}; + )->status_is( 201, 'Patron added' )->tx->res->json->{patron_id}; - my $messaging_preferences = C4::Members::Messaging::GetMessagingPreferences({ borrowernumber => $patron_id, message_name => 'Item_Due' }); + my $messaging_preferences = C4::Members::Messaging::GetMessagingPreferences( + { borrowernumber => $patron_id, message_name => 'Item_Due' } ); is_deeply( $messaging_preferences, { - letter_code => 'DUEDGST', + letter_code => 'DUEDGST', wants_digest => 1, - transports => { email => 'DUEDGST' } - } , + transports => { email => 'DUEDGST' } + }, 'Default messaging preferences set correctly' ); }; @@ -720,7 +715,7 @@ subtest 'update() tests' => sub { plan tests => 2; $schema->storage->txn_begin; - unauthorized_access_tests('PUT', 123, {email => 'nobody@example.com'}); + unauthorized_access_tests( 'PUT', 123, { email => 'nobody@example.com' } ); $schema->storage->txn_rollback; subtest 'librarian access tests' => sub { @@ -736,8 +731,7 @@ subtest 'update() tests' => sub { } ); my $password = 'thePassword123'; - $authorized_patron->set_password( - { password => $password, skip_validation => 1 } ); + $authorized_patron->set_password( { password => $password, skip_validation => 1 } ); my $userid = $authorized_patron->userid; my $unauthorized_patron = $builder->build_object( @@ -751,36 +745,37 @@ subtest 'update() tests' => sub { my $patron_1 = $authorized_patron; my $patron_2 = $unauthorized_patron; - my $newpatron = $unauthorized_patron->to_api({ user => $authorized_patron }); + my $newpatron = $unauthorized_patron->to_api( { user => $authorized_patron } ); + # delete RO attributes delete $newpatron->{patron_id}; delete $newpatron->{restricted}; delete $newpatron->{expired}; delete $newpatron->{anonymized}; - $t->put_ok("//$userid:$password@/api/v1/patrons/-1" => json => $newpatron) - ->status_is(404) - ->json_has('/error', 'Fails when trying to PUT nonexistent patron'); + $t->put_ok( "//$userid:$password@/api/v1/patrons/-1" => json => $newpatron )->status_is(404) + ->json_has( '/error', 'Fails when trying to PUT nonexistent patron' ); # Create a library just to make sure its ID doesn't exist on the DB - my $category_to_delete = $builder->build_object({ class => 'Koha::Patron::Categories' }); + my $category_to_delete = $builder->build_object( { class => 'Koha::Patron::Categories' } ); my $deleted_category_id = $category_to_delete->id; + # Delete library $category_to_delete->delete; # Use an invalid category $newpatron->{category_id} = $deleted_category_id; - $t->put_ok("//$userid:$password@/api/v1/patrons/" . $patron_2->borrowernumber => json => $newpatron) - ->status_is(400) - ->json_is('/error' => "Given category_id does not exist"); + $t->put_ok( "//$userid:$password@/api/v1/patrons/" . $patron_2->borrowernumber => json => $newpatron ) + ->status_is(400)->json_is( '/error' => "Given category_id does not exist" ); # Restore the valid category $newpatron->{category_id} = $patron_2->categorycode; # Create a library just to make sure its ID doesn't exist on the DB - my $library_to_delete = $builder->build_object({ class => 'Koha::Libraries' }); + my $library_to_delete = $builder->build_object( { class => 'Koha::Libraries' } ); my $deleted_library_id = $library_to_delete->id; + # Delete library $library_to_delete->delete; @@ -788,10 +783,10 @@ subtest 'update() tests' => sub { $newpatron->{library_id} = $deleted_library_id; warning_like { - $t->put_ok("//$userid:$password@/api/v1/patrons/" . $patron_2->borrowernumber => json => $newpatron) - ->status_is(400) - ->json_is('/error' => "Given library_id does not exist"); } - qr/DBD::mysql::st execute failed: Cannot add or update a child row: a foreign key constraint fails/; + $t->put_ok( "//$userid:$password@/api/v1/patrons/" . $patron_2->borrowernumber => json => $newpatron ) + ->status_is(400)->json_is( '/error' => "Given library_id does not exist" ); + } + qr/DBD::mysql::st execute failed: Cannot add or update a child row: a foreign key constraint fails/; # Restore the valid library_id $newpatron->{library_id} = $patron_2->branchcode; @@ -800,9 +795,7 @@ subtest 'update() tests' => sub { $newpatron->{falseproperty} = "Non existent property"; $t->put_ok( "//$userid:$password@/api/v1/patrons/" . $patron_2->borrowernumber => json => $newpatron ) - ->status_is(400) - ->json_is('/errors/0/message' => - 'Properties not allowed: falseproperty.'); + ->status_is(400)->json_is( '/errors/0/message' => 'Properties not allowed: falseproperty.' ); # Get rid of the invalid attribute delete $newpatron->{falseproperty}; @@ -812,32 +805,33 @@ subtest 'update() tests' => sub { $newpatron->{userid} = $patron_1->userid; $t->put_ok( "//$userid:$password@/api/v1/patrons/" . $patron_2->borrowernumber => json => $newpatron ) - ->status_is(400) - ->json_has( '/error', "Problem with userid ". $patron_1->userid ); + ->status_is(400)->json_has( '/error', "Problem with userid " . $patron_1->userid ); - $newpatron->{ cardnumber } = $patron_1->id . $patron_2->id; - $newpatron->{ userid } = "user" . $patron_1->id.$patron_2->id; - $newpatron->{ surname } = "user" . $patron_1->id.$patron_2->id; + $newpatron->{cardnumber} = $patron_1->id . $patron_2->id; + $newpatron->{userid} = "user" . $patron_1->id . $patron_2->id; + $newpatron->{surname} = "user" . $patron_1->id . $patron_2->id; ## Trying to set to null on specially handled cases # Special case: a date - $newpatron->{ date_of_birth } = undef; - # Special case: a date-time - $newpatron->{ last_seen } = undef; + $newpatron->{date_of_birth} = undef; - my $result = $t->put_ok( "//$userid:$password@/api/v1/patrons/" . $patron_2->borrowernumber => json => $newpatron ) - ->status_is(200, 'Patron updated successfully'); + # Special case: a date-time + $newpatron->{last_seen} = undef; + + my $result = + $t->put_ok( "//$userid:$password@/api/v1/patrons/" . $patron_2->borrowernumber => json => $newpatron ) + ->status_is( 200, 'Patron updated successfully' ); # Put back the RO attributes - $newpatron->{patron_id} = $unauthorized_patron->to_api({ user => $authorized_patron })->{patron_id}; - $newpatron->{restricted} = $unauthorized_patron->to_api({ user => $authorized_patron })->{restricted}; - $newpatron->{expired} = $unauthorized_patron->to_api({ user => $authorized_patron })->{expired}; - $newpatron->{anonymized} = $unauthorized_patron->to_api({ user => $authorized_patron })->{anonymized}; + $newpatron->{patron_id} = $unauthorized_patron->to_api( { user => $authorized_patron } )->{patron_id}; + $newpatron->{restricted} = $unauthorized_patron->to_api( { user => $authorized_patron } )->{restricted}; + $newpatron->{expired} = $unauthorized_patron->to_api( { user => $authorized_patron } )->{expired}; + $newpatron->{anonymized} = $unauthorized_patron->to_api( { user => $authorized_patron } )->{anonymized}; - my $got = $result->tx->res->json; - my $updated_on_got = delete $got->{updated_on}; + my $got = $result->tx->res->json; + my $updated_on_got = delete $got->{updated_on}; my $updated_on_expected = delete $newpatron->{updated_on}; - is_deeply($got, $newpatron, 'Returned patron from update matches expected'); + is_deeply( $got, $newpatron, 'Returned patron from update matches expected' ); is( t::lib::Dates::compare( dt_from_string( $updated_on_got, 'rfc3339' ), @@ -847,8 +841,10 @@ subtest 'update() tests' => sub { 'updated_on values matched' ); - is(Koha::Patrons->find( $patron_2->id )->cardnumber, - $newpatron->{ cardnumber }, 'Patron is really updated!'); + is( + Koha::Patrons->find( $patron_2->id )->cardnumber, + $newpatron->{cardnumber}, 'Patron is really updated!' + ); my $superlibrarian = $builder->build_object( { @@ -860,6 +856,7 @@ subtest 'update() tests' => sub { $newpatron->{cardnumber} = $superlibrarian->cardnumber; $newpatron->{userid} = $superlibrarian->userid; $newpatron->{email} = 'nosense@no.no'; + # delete RO attributes delete $newpatron->{patron_id}; delete $newpatron->{restricted}; @@ -867,44 +864,48 @@ subtest 'update() tests' => sub { delete $newpatron->{anonymized}; # attempt to update - $authorized_patron->flags( 2**4 )->store; # borrowers flag = 4 + $authorized_patron->flags( 2**4 )->store; # borrowers flag = 4 $t->put_ok( "//$userid:$password@/api/v1/patrons/" . $superlibrarian->borrowernumber => json => $newpatron ) - ->status_is(403, "Non-superlibrarian user change of superlibrarian email forbidden") - ->json_is( { error => "Not enough privileges to change a superlibrarian's email" } ); + ->status_is( 403, "Non-superlibrarian user change of superlibrarian email forbidden" ) + ->json_is( { error => "Not enough privileges to change a superlibrarian's email" } ); # attempt to unset $newpatron->{email} = undef; $t->put_ok( "//$userid:$password@/api/v1/patrons/" . $superlibrarian->borrowernumber => json => $newpatron ) - ->status_is(403, "Non-superlibrarian user change of superlibrarian email to undefined forbidden") - ->json_is( { error => "Not enough privileges to change a superlibrarian's email" } ); + ->status_is( 403, "Non-superlibrarian user change of superlibrarian email to undefined forbidden" ) + ->json_is( { error => "Not enough privileges to change a superlibrarian's email" } ); $newpatron->{email} = $superlibrarian->email; $newpatron->{secondary_email} = 'nonsense@no.no'; # attempt to update $t->put_ok( "//$userid:$password@/api/v1/patrons/" . $superlibrarian->borrowernumber => json => $newpatron ) - ->status_is(403, "Non-superlibrarian user change of superlibrarian secondary_email forbidden") - ->json_is( { error => "Not enough privileges to change a superlibrarian's email" } ); + ->status_is( 403, "Non-superlibrarian user change of superlibrarian secondary_email forbidden" ) + ->json_is( { error => "Not enough privileges to change a superlibrarian's email" } ); # attempt to unset $newpatron->{secondary_email} = undef; $t->put_ok( "//$userid:$password@/api/v1/patrons/" . $superlibrarian->borrowernumber => json => $newpatron ) - ->status_is(403, "Non-superlibrarian user change of superlibrarian secondary_email to undefined forbidden") - ->json_is( { error => "Not enough privileges to change a superlibrarian's email" } ); + ->status_is( + 403, + "Non-superlibrarian user change of superlibrarian secondary_email to undefined forbidden" + )->json_is( { error => "Not enough privileges to change a superlibrarian's email" } ); $newpatron->{secondary_email} = $superlibrarian->emailpro; $newpatron->{altaddress_email} = 'nonsense@no.no'; # attempt to update $t->put_ok( "//$userid:$password@/api/v1/patrons/" . $superlibrarian->borrowernumber => json => $newpatron ) - ->status_is(403, "Non-superlibrarian user change of superlibrarian altaddress_email forbidden") - ->json_is( { error => "Not enough privileges to change a superlibrarian's email" } ); + ->status_is( 403, "Non-superlibrarian user change of superlibrarian altaddress_email forbidden" ) + ->json_is( { error => "Not enough privileges to change a superlibrarian's email" } ); # attempt to unset $newpatron->{altaddress_email} = undef; $t->put_ok( "//$userid:$password@/api/v1/patrons/" . $superlibrarian->borrowernumber => json => $newpatron ) - ->status_is(403, "Non-superlibrarian user change of superlibrarian altaddress_email to undefined forbidden") - ->json_is( { error => "Not enough privileges to change a superlibrarian's email" } ); + ->status_is( + 403, + "Non-superlibrarian user change of superlibrarian altaddress_email to undefined forbidden" + )->json_is( { error => "Not enough privileges to change a superlibrarian's email" } ); # update patron without sending email delete $newpatron->{email}; @@ -913,13 +914,14 @@ subtest 'update() tests' => sub { # Set a date field $newpatron->{date_of_birth} = '1980-06-18'; + # Set a date-time field - $newpatron->{last_seen} = output_pref({ dt => dt_from_string->add( days => -1 ), dateformat => 'rfc3339' }); + $newpatron->{last_seen} = output_pref( { dt => dt_from_string->add( days => -1 ), dateformat => 'rfc3339' } ); $t->put_ok( "//$userid:$password@/api/v1/patrons/" . $superlibrarian->borrowernumber => json => $newpatron ) - ->status_is(200, "Non-superlibrarian user can edit superlibrarian successfully if not changing email") - ->json_is( '/date_of_birth' => $newpatron->{ date_of_birth }, 'Date field set (Bug 28585)' ) - ->json_is( '/last_seen' => $newpatron->{ last_seen }, 'Date-time field set (Bug 28585)' ); + ->status_is( 200, "Non-superlibrarian user can edit superlibrarian successfully if not changing email" ) + ->json_is( '/date_of_birth' => $newpatron->{date_of_birth}, 'Date field set (Bug 28585)' ) + ->json_is( '/last_seen' => $newpatron->{last_seen}, 'Date-time field set (Bug 28585)' ); subtest "extended_attributes tests" => sub { @@ -1050,7 +1052,7 @@ subtest 'delete() tests' => sub { plan tests => 2; $schema->storage->txn_begin; - unauthorized_access_tests('DELETE', 123, undef); + unauthorized_access_tests( 'DELETE', 123, undef ); $schema->storage->txn_rollback; subtest 'librarian access test' => sub { @@ -1066,25 +1068,22 @@ subtest 'delete() tests' => sub { } ); my $password = 'thePassword123'; - $authorized_patron->set_password( - { password => $password, skip_validation => 1 } ); + $authorized_patron->set_password( { password => $password, skip_validation => 1 } ); my $userid = $authorized_patron->userid; - $t->delete_ok("//$userid:$password@/api/v1/patrons/-1") - ->status_is(404, 'Patron not found'); + $t->delete_ok("//$userid:$password@/api/v1/patrons/-1")->status_is( 404, 'Patron not found' ); - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); - t::lib::Mocks::mock_preference('AnonymousPatron', $patron->borrowernumber); + t::lib::Mocks::mock_preference( 'AnonymousPatron', $patron->borrowernumber ); $t->delete_ok( "//$userid:$password@/api/v1/patrons/" . $patron->borrowernumber ) - ->status_is( 409, 'Anonymous patron cannot be deleted' ) - ->json_is( + ->status_is( 409, 'Anonymous patron cannot be deleted' )->json_is( { error => 'Anonymous patron cannot be deleted', error_code => 'is_anonymous_patron' } - ); - t::lib::Mocks::mock_preference('AnonymousPatron', 0); # back to default + ); + t::lib::Mocks::mock_preference( 'AnonymousPatron', 0 ); # back to default t::lib::Mocks::mock_preference( 'borrowerRelationship', 'parent' ); @@ -1094,43 +1093,40 @@ subtest 'delete() tests' => sub { value => { borrowernumber => $patron->borrowernumber } } ); - my $debit = $patron->account->add_debit({ amount => 10, interface => 'intranet', type => 'MANUAL' }); - my $guarantee = $builder->build_object({ class => 'Koha::Patrons' }); + my $debit = $patron->account->add_debit( { amount => 10, interface => 'intranet', type => 'MANUAL' } ); + my $guarantee = $builder->build_object( { class => 'Koha::Patrons' } ); - $guarantee->add_guarantor({ guarantor_id => $patron->id, relationship => 'parent' }); + $guarantee->add_guarantor( { guarantor_id => $patron->id, relationship => 'parent' } ); - $t->delete_ok("//$userid:$password@/api/v1/patrons/" . $patron->borrowernumber) - ->status_is(409, 'Patron with checkouts cannot be deleted') - ->json_is( + $t->delete_ok( "//$userid:$password@/api/v1/patrons/" . $patron->borrowernumber ) + ->status_is( 409, 'Patron with checkouts cannot be deleted' )->json_is( { error => 'Pending checkouts prevent deletion', error_code => 'has_checkouts' } - ); + ); # Make sure it has no pending checkouts $checkout->delete; - $t->delete_ok("//$userid:$password@/api/v1/patrons/" . $patron->borrowernumber) - ->status_is(409, 'Patron with debt cannot be deleted') - ->json_is( + $t->delete_ok( "//$userid:$password@/api/v1/patrons/" . $patron->borrowernumber ) + ->status_is( 409, 'Patron with debt cannot be deleted' )->json_is( { error => 'Pending debts prevent deletion', error_code => 'has_debt' } - ); + ); # Make sure it has no debt - $patron->account->pay({ amount => 10, debits => [ $debit ] }); + $patron->account->pay( { amount => 10, debits => [$debit] } ); - $t->delete_ok("//$userid:$password@/api/v1/patrons/" . $patron->borrowernumber) - ->status_is(409, 'Patron with guarantees cannot be deleted') - ->json_is( + $t->delete_ok( "//$userid:$password@/api/v1/patrons/" . $patron->borrowernumber ) + ->status_is( 409, 'Patron with guarantees cannot be deleted' )->json_is( { error => 'Patron is a guarantor and it prevents deletion', error_code => 'has_guarantees' } - ); + ); # Remove guarantee $patron->guarantee_relationships->delete; @@ -1147,11 +1143,10 @@ subtest 'delete() tests' => sub { $patron->protected(0)->store(); - $t->delete_ok("//$userid:$password@/api/v1/patrons/" . $patron->borrowernumber) - ->status_is(204, 'REST3.2.4') - ->content_is('', 'REST3.3.4'); + $t->delete_ok( "//$userid:$password@/api/v1/patrons/" . $patron->borrowernumber ) + ->status_is( 204, 'REST3.2.4' )->content_is( '', 'REST3.3.4' ); - my $deleted_patrons = Koha::Old::Patrons->search({ borrowernumber => $patron->borrowernumber }); + my $deleted_patrons = Koha::Old::Patrons->search( { borrowernumber => $patron->borrowernumber } ); is( $deleted_patrons->count, 1, 'The patron has been moved to the vault' ); $schema->storage->txn_rollback; @@ -1167,29 +1162,27 @@ subtest 'guarantors_can_see_charges() tests' => sub { $schema->storage->txn_begin; - my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { privacy_guarantor_fines => 0 } }); + my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { privacy_guarantor_fines => 0 } } ); my $password = 'thePassword123'; - $patron->set_password({ password => $password, skip_validation => 1 }); - my $userid = $patron->userid; + $patron->set_password( { password => $password, skip_validation => 1 } ); + my $userid = $patron->userid; my $patron_id = $patron->borrowernumber; t::lib::Mocks::mock_preference( 'AllowPatronToSetFinesVisibilityForGuarantor', 0 ); - $t->put_ok( "//$userid:$password@/api/v1/public/patrons/$patron_id/guarantors/can_see_charges" => json => { allowed => Mojo::JSON->true } ) - ->status_is( 403 ) - ->json_is( '/error', 'The current configuration doesn\'t allow the requested action.' ); + $t->put_ok( "//$userid:$password@/api/v1/public/patrons/$patron_id/guarantors/can_see_charges" => json => + { allowed => Mojo::JSON->true } )->status_is(403) + ->json_is( '/error', 'The current configuration doesn\'t allow the requested action.' ); t::lib::Mocks::mock_preference( 'AllowPatronToSetFinesVisibilityForGuarantor', 1 ); - $t->put_ok( "//$userid:$password@/api/v1/public/patrons/$patron_id/guarantors/can_see_charges" => json => { allowed => Mojo::JSON->true } ) - ->status_is( 200 ) - ->json_is( {} ); + $t->put_ok( "//$userid:$password@/api/v1/public/patrons/$patron_id/guarantors/can_see_charges" => json => + { allowed => Mojo::JSON->true } )->status_is(200)->json_is( {} ); ok( $patron->discard_changes->privacy_guarantor_fines, 'privacy_guarantor_fines has been set correctly' ); - $t->put_ok( "//$userid:$password@/api/v1/public/patrons/$patron_id/guarantors/can_see_charges" => json => { allowed => Mojo::JSON->false } ) - ->status_is( 200 ) - ->json_is( {} ); + $t->put_ok( "//$userid:$password@/api/v1/public/patrons/$patron_id/guarantors/can_see_charges" => json => + { allowed => Mojo::JSON->false } )->status_is(200)->json_is( {} ); ok( !$patron->discard_changes->privacy_guarantor_fines, 'privacy_guarantor_fines has been set correctly' ); @@ -1205,29 +1198,27 @@ subtest 'guarantors_can_see_checkouts() tests' => sub { $schema->storage->txn_begin; - my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { privacy_guarantor_checkouts => 0 } }); + my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { privacy_guarantor_checkouts => 0 } } ); my $password = 'thePassword123'; - $patron->set_password({ password => $password, skip_validation => 1 }); - my $userid = $patron->userid; + $patron->set_password( { password => $password, skip_validation => 1 } ); + my $userid = $patron->userid; my $patron_id = $patron->borrowernumber; t::lib::Mocks::mock_preference( 'AllowPatronToSetCheckoutsVisibilityForGuarantor', 0 ); - $t->put_ok( "//$userid:$password@/api/v1/public/patrons/$patron_id/guarantors/can_see_checkouts" => json => { allowed => Mojo::JSON->true } ) - ->status_is( 403 ) - ->json_is( '/error', 'The current configuration doesn\'t allow the requested action.' ); + $t->put_ok( "//$userid:$password@/api/v1/public/patrons/$patron_id/guarantors/can_see_checkouts" => json => + { allowed => Mojo::JSON->true } )->status_is(403) + ->json_is( '/error', 'The current configuration doesn\'t allow the requested action.' ); t::lib::Mocks::mock_preference( 'AllowPatronToSetCheckoutsVisibilityForGuarantor', 1 ); - $t->put_ok( "//$userid:$password@/api/v1/public/patrons/$patron_id/guarantors/can_see_checkouts" => json => { allowed => Mojo::JSON->true } ) - ->status_is( 200 ) - ->json_is( {} ); + $t->put_ok( "//$userid:$password@/api/v1/public/patrons/$patron_id/guarantors/can_see_checkouts" => json => + { allowed => Mojo::JSON->true } )->status_is(200)->json_is( {} ); ok( $patron->discard_changes->privacy_guarantor_checkouts, 'privacy_guarantor_checkouts has been set correctly' ); - $t->put_ok( "//$userid:$password@/api/v1/public/patrons/$patron_id/guarantors/can_see_checkouts" => json => { allowed => Mojo::JSON->false } ) - ->status_is( 200 ) - ->json_is( {} ); + $t->put_ok( "//$userid:$password@/api/v1/public/patrons/$patron_id/guarantors/can_see_checkouts" => json => + { allowed => Mojo::JSON->false } )->status_is(200)->json_is( {} ); ok( !$patron->discard_changes->privacy_guarantor_checkouts, 'privacy_guarantor_checkouts has been set correctly' ); @@ -1237,7 +1228,7 @@ subtest 'guarantors_can_see_checkouts() tests' => sub { # Centralized tests for 401s and 403s assuming the endpoint requires # borrowers flag for access sub unauthorized_access_tests { - my ($verb, $patron_id, $json) = @_; + my ( $verb, $patron_id, $json ) = @_; my $endpoint = '/api/v1/patrons'; $endpoint .= ($patron_id) ? "/$patron_id" : ''; @@ -1247,8 +1238,7 @@ sub unauthorized_access_tests { my $verb_ok = lc($verb) . '_ok'; - $t->$verb_ok($endpoint => json => $json) - ->status_is(401); + $t->$verb_ok( $endpoint => json => $json )->status_is(401); my $unauthorized_patron = $builder->build_object( { @@ -1257,12 +1247,10 @@ sub unauthorized_access_tests { } ); my $password = "thePassword123!"; - $unauthorized_patron->set_password( - { password => $password, skip_validation => 1 } ); + $unauthorized_patron->set_password( { password => $password, skip_validation => 1 } ); my $unauth_userid = $unauthorized_patron->userid; - $t->$verb_ok( "//$unauth_userid:$password\@$endpoint" => json => $json ) - ->status_is(403) - ->json_has('/required_permissions'); + $t->$verb_ok( "//$unauth_userid:$password\@$endpoint" => json => $json )->status_is(403) + ->json_has('/required_permissions'); }; } diff --git a/t/db_dependent/api/v1/patrons_accounts.t b/t/db_dependent/api/v1/patrons_accounts.t index 63a840b609..c8d3fd4b57 100755 --- a/t/db_dependent/api/v1/patrons_accounts.t +++ b/t/db_dependent/api/v1/patrons_accounts.t @@ -56,14 +56,13 @@ subtest 'get_balance() tests' => sub { my $patron_id = $patron->id; my $account = $patron->account; - $t->get_ok("//$userid:$password@/api/v1/patrons/$patron_id/account") - ->status_is(200)->json_is( + $t->get_ok("//$userid:$password@/api/v1/patrons/$patron_id/account")->status_is(200)->json_is( { balance => 0.00, outstanding_debits => { total => 0, lines => [] }, outstanding_credits => { total => 0, lines => [] } } - ); + ); my $debit_1 = $account->add_debit( { @@ -89,8 +88,8 @@ subtest 'get_balance() tests' => sub { )->store(); $debit_2->discard_changes; - $t->get_ok("//$userid:$password@/api/v1/patrons/$patron_id/account") - ->status_is(200)->or(sub { diag $t->tx->res->body } )->json_is( + $t->get_ok("//$userid:$password@/api/v1/patrons/$patron_id/account")->status_is(200) + ->or( sub { diag $t->tx->res->body } )->json_is( { balance => 100.01, outstanding_debits => { @@ -102,7 +101,7 @@ subtest 'get_balance() tests' => sub { lines => [] } } - ); + ); $account->pay( { @@ -114,14 +113,13 @@ subtest 'get_balance() tests' => sub { } ); - $t->get_ok("//$userid:$password@/api/v1/patrons/$patron_id/account") - ->status_is(200)->json_is( + $t->get_ok("//$userid:$password@/api/v1/patrons/$patron_id/account")->status_is(200)->json_is( { balance => 0, outstanding_debits => { total => 0, lines => [] }, outstanding_credits => { total => 0, lines => [] } } - ); + ); # add a credit my $credit_line = $account->add_credit( @@ -136,8 +134,7 @@ subtest 'get_balance() tests' => sub { # re-read from the DB $credit_line->discard_changes; - $t->get_ok("//$userid:$password@/api/v1/patrons/$patron_id/account") - ->status_is(200)->json_is( + $t->get_ok("//$userid:$password@/api/v1/patrons/$patron_id/account")->status_is(200)->json_is( { balance => -10, outstanding_debits => { @@ -149,7 +146,7 @@ subtest 'get_balance() tests' => sub { lines => [ $credit_line->to_api ] } } - ); + ); # Accountline without manager_id (happens with fines.pl cron for example) my $debit_3 = $account->add_debit( @@ -164,8 +161,7 @@ subtest 'get_balance() tests' => sub { )->store(); $debit_3->discard_changes; - $t->get_ok("//$userid:$password@/api/v1/patrons/$patron_id/account") - ->status_is(200)->json_is( + $t->get_ok("//$userid:$password@/api/v1/patrons/$patron_id/account")->status_is(200)->json_is( { balance => 40.00, outstanding_debits => { @@ -177,7 +173,7 @@ subtest 'get_balance() tests' => sub { lines => [ $credit_line->to_api ] } } - ); + ); $schema->storage->txn_rollback; }; @@ -202,20 +198,23 @@ subtest 'add_credit() tests' => sub { my $patron_id = $patron->id; my $account = $patron->account; - is( $account->outstanding_debits->count, - 0, 'No outstanding debits for patron' ); - is( $account->outstanding_credits->count, - 0, 'No outstanding credits for patron' ); + is( + $account->outstanding_debits->count, + 0, 'No outstanding debits for patron' + ); + is( + $account->outstanding_credits->count, + 0, 'No outstanding credits for patron' + ); my $credit = { amount => 100 }; my $ret = $t->post_ok( "//$userid:$password@/api/v1/patrons/$patron_id/account/credits" => json => $credit ) - ->status_is(201) - ->header_is( + ->status_is(201)->header_is( 'Location' => "/api/v1/patrons/$patron_id/account/credits/" . $t->tx->res->json->{account_line_id}, "REST3.4.1" - )->tx->res->json; + )->tx->res->json; is_deeply( $ret, @@ -249,9 +248,8 @@ subtest 'add_credit() tests' => sub { is( $account->outstanding_debits->total_outstanding, 25 ); $credit->{library_id} = $library->id; - $ret = $t->post_ok( - "//$userid:$password@/api/v1/patrons/$patron_id/account/credits" => - json => $credit )->status_is(201)->tx->res->json; + $ret = $t->post_ok( "//$userid:$password@/api/v1/patrons/$patron_id/account/credits" => json => $credit ) + ->status_is(201)->tx->res->json; is_deeply( $ret, @@ -260,11 +258,15 @@ subtest 'add_credit() tests' => sub { ); my $account_line_id = $t->tx->res->json->{account_line_id}; - is( Koha::Account::Lines->find($account_line_id)->branchcode, - $library->id, 'Library id is sored correctly' ); + is( + Koha::Account::Lines->find($account_line_id)->branchcode, + $library->id, 'Library id is sored correctly' + ); - is( $account->outstanding_debits->total_outstanding, - 0, "Debits have been cancelled automatically" ); + is( + $account->outstanding_debits->total_outstanding, + 0, "Debits have been cancelled automatically" + ); my $debit_3 = $account->add_debit( { @@ -281,9 +283,8 @@ subtest 'add_credit() tests' => sub { account_lines_ids => [ $debit_1->id, $debit_2->id, $debit_3->id ] }; - $ret = $t->post_ok( - "//$userid:$password@/api/v1/patrons/$patron_id/account/credits" => - json => $credit )->status_is(201)->tx->res->json; + $ret = $t->post_ok( "//$userid:$password@/api/v1/patrons/$patron_id/account/credits" => json => $credit ) + ->status_is(201)->tx->res->json; is_deeply( $ret, @@ -303,54 +304,61 @@ subtest 'list_credits() test' => sub { $schema->storage->txn_begin; - my $patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 1 } - }); + my $patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 1 } + } + ); my $password = 'thePassword123'; - $patron->set_password({ password => $password, skip_validation => 1 }); + $patron->set_password( { password => $password, skip_validation => 1 } ); my $userid = $patron->userid; my $patron_id = $patron->borrowernumber; my $account = $patron->account; - $account->add_credit({ - type => 'PAYMENT', - amount => 35, - interface => 'staff', - }); - $account->add_credit({ - type => 'PAYMENT', - amount => 70, - interface => 'staff', - }); + $account->add_credit( + { + type => 'PAYMENT', + amount => 35, + interface => 'staff', + } + ); + $account->add_credit( + { + type => 'PAYMENT', + amount => 70, + interface => 'staff', + } + ); - my $ret = $t->get_ok("//$userid:$password@/api/v1/patrons/$patron_id/account/credits") - ->status_is(200) - ->tx->res->json; + my $ret = + $t->get_ok("//$userid:$password@/api/v1/patrons/$patron_id/account/credits")->status_is(200)->tx->res->json; - is(-105, $ret->[0]->{amount} + $ret->[1]->{amount}, 'Total credits are -105'); + is( -105, $ret->[0]->{amount} + $ret->[1]->{amount}, 'Total credits are -105' ); $schema->storage->txn_rollback; }; - subtest 'list_debits() test' => sub { plan tests => 3; $schema->storage->txn_begin; - my $patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 1 } - }); + my $patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 1 } + } + ); my $password = 'thePassword123'; - $patron->set_password({ password => $password, skip_validation => 1 }); + $patron->set_password( { password => $password, skip_validation => 1 } ); my $userid = $patron->userid; my $patron_id = $patron->borrowernumber; my $account = $patron->account; $account->add_debit( - { amount => 100, + { + amount => 100, description => "A description", type => "NEW_CARD", user_id => $patron->borrowernumber, @@ -358,7 +366,8 @@ subtest 'list_debits() test' => sub { } ); $account->add_debit( - { amount => 40, + { + amount => 40, description => "A description", type => "NEW_CARD", user_id => $patron->borrowernumber, @@ -366,11 +375,10 @@ subtest 'list_debits() test' => sub { } ); - my $ret = $t->get_ok("//$userid:$password@/api/v1/patrons/$patron_id/account/debits") - ->status_is(200) - ->tx->res->json; + my $ret = + $t->get_ok("//$userid:$password@/api/v1/patrons/$patron_id/account/debits")->status_is(200)->tx->res->json; - is(140, $ret->[0]->{amount} + $ret->[1]->{amount}, 'Total debits are 140'); + is( 140, $ret->[0]->{amount} + $ret->[1]->{amount}, 'Total debits are 140' ); }; subtest 'add_debit() tests' => sub { @@ -387,8 +395,8 @@ subtest 'add_debit() tests' => sub { ); my $password = 'thePassword123'; $librarian->set_password( { password => $password, skip_validation => 1 } ); - my $userid = $librarian->userid; - my $librarian_x = $builder->build_object({ class => 'Koha::Patrons' }); + my $userid = $librarian->userid; + my $librarian_x = $builder->build_object( { class => 'Koha::Patrons' } ); my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $library = $builder->build_object( { class => 'Koha::Libraries' } ); @@ -449,8 +457,7 @@ subtest 'add_debit() tests' => sub { my $account_line_id = $ret->{account_line_id}; - $t->post_ok( "//$userid:$password@/api/v1/patrons/$patron_id/account/debits" => json => $debit ) - ->status_is(201) + $t->post_ok( "//$userid:$password@/api/v1/patrons/$patron_id/account/debits" => json => $debit )->status_is(201) ->header_is( 'Location' => "/api/v1/patrons/$patron_id/account/debits/" . $t->tx->res->json->{account_line_id}, "REST3.4.1" diff --git a/t/db_dependent/api/v1/patrons_extended_attributes.t b/t/db_dependent/api/v1/patrons_extended_attributes.t index d7bf3def84..da7eeed122 100755 --- a/t/db_dependent/api/v1/patrons_extended_attributes.t +++ b/t/db_dependent/api/v1/patrons_extended_attributes.t @@ -38,42 +38,44 @@ subtest 'list_patron_attributes() tests' => sub { $schema->storage->txn_begin; - my $patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 2 ** 4 } # 'borrowers' flag == 4 - }); + my $patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 2**4 } # 'borrowers' flag == 4 + } + ); my $password = 'thePassword123'; - $patron->set_password({ password => $password, skip_validation => 1 }); + $patron->set_password( { password => $password, skip_validation => 1 } ); my $userid = $patron->userid; - $t->get_ok("//$userid:$password@/api/v1/patrons/" . $patron->id . '/extended_attributes') - ->status_is( 200, 'REST3.2.2' ) - ->json_is( [] ); + $t->get_ok( "//$userid:$password@/api/v1/patrons/" . $patron->id . '/extended_attributes' ) + ->status_is( 200, 'REST3.2.2' )->json_is( [] ); # Let's add 3 attributes - foreach my $i ( 1..5 ) { - $builder->build_object({ class => 'Koha::Patron::Attributes', value => { borrowernumber => $patron->id } }); + foreach my $i ( 1 .. 5 ) { + $builder->build_object( { class => 'Koha::Patron::Attributes', value => { borrowernumber => $patron->id } } ); } - $t->get_ok("//$userid:$password@/api/v1/patrons/" . $patron->id . '/extended_attributes') - ->status_is( 200, 'REST3.2.2' ) - ->json_is( '' => $patron->extended_attributes->to_api, 'Extended attributes retrieved correctly' ); + $t->get_ok( "//$userid:$password@/api/v1/patrons/" . $patron->id . '/extended_attributes' ) + ->status_is( 200, 'REST3.2.2' ) + ->json_is( '' => $patron->extended_attributes->to_api, 'Extended attributes retrieved correctly' ); - my $non_existent_patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $non_existent_patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $non_existent_patron_id = $non_existent_patron->id; + # get rid of the patron $non_existent_patron->delete; - $t->get_ok("//$userid:$password@/api/v1/patrons/" . $non_existent_patron_id . '/extended_attributes') - ->status_is( 404 ) - ->json_is( '/error' => 'Patron not found' ); + $t->get_ok( "//$userid:$password@/api/v1/patrons/" . $non_existent_patron_id . '/extended_attributes' ) + ->status_is(404)->json_is( '/error' => 'Patron not found' ); subtest 'nullable value' => sub { + # FIXME This is not correct, we should remove the NULLABLE clause at the DBMS level # This test will need to be adjusted on bug 32331 plan tests => 3; - my $user = $builder->build_object({class => 'Koha::Patrons'}); + my $user = $builder->build_object( { class => 'Koha::Patrons' } ); $builder->build_object( { @@ -82,13 +84,11 @@ subtest 'list_patron_attributes() tests' => sub { } ); - $t->get_ok( "//$userid:$password@/api/v1/patrons/" - . $user->id - . '/extended_attributes' )->status_is( 200, 'REST3.2.2' ) - ->json_is( + $t->get_ok( "//$userid:$password@/api/v1/patrons/" . $user->id . '/extended_attributes' ) + ->status_is( 200, 'REST3.2.2' )->json_is( '' => $user->extended_attributes->to_api, 'Extended attributes retrieved correctly' - ); + ); }; @@ -101,12 +101,14 @@ subtest 'add() tests' => sub { $schema->storage->txn_begin; - my $patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 2 ** 4 } # 'borrowers' flag == 4 - }); + my $patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 2**4 } # 'borrowers' flag == 4 + } + ); my $password = 'thePassword123'; - $patron->set_password({ password => $password, skip_validation => 1 }); + $patron->set_password( { password => $password, skip_validation => 1 } ); my $userid = $patron->userid; my $mandatory_attr_type = $builder->build_object( @@ -143,22 +145,22 @@ subtest 'add() tests' => sub { } ); - my $non_existent_patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $non_existent_patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $non_existent_patron_id = $non_existent_patron->id; + # get rid of the patron $non_existent_patron->delete; $t->post_ok( "//$userid:$password@/api/v1/patrons/" - . $non_existent_patron_id - . '/extended_attributes' => json => - { type => $repeatable_attr_type->code, value => 'something' } ) - ->status_is(404)->json_is( '/error' => 'Patron not found' ); + . $non_existent_patron_id + . '/extended_attributes' => json => { type => $repeatable_attr_type->code, value => 'something' } ) + ->status_is(404)->json_is( '/error' => 'Patron not found' ); - my $response = $t->post_ok( "//$userid:$password@/api/v1/patrons/" - . $patron->id - . '/extended_attributes' => json => - { type => $repeatable_attr_type->code, value => 'something' } ) - ->status_is(201)->tx->res->json; + my $response = + $t->post_ok( "//$userid:$password@/api/v1/patrons/" + . $patron->id + . '/extended_attributes' => json => { type => $repeatable_attr_type->code, value => 'something' } ) + ->status_is(201)->tx->res->json; is_deeply( Koha::Patron::Attributes->find( $response->{extended_attribute_id} )->to_api, @@ -168,23 +170,19 @@ subtest 'add() tests' => sub { subtest 'Repeatability tests' => sub { $t->post_ok( "//$userid:$password@/api/v1/patrons/" - . $patron->id - . '/extended_attributes' => json => - { type => $repeatable_attr_type->code, value => 'something' } ) - ->status_is(201, 'Repeatable attributes go through'); + . $patron->id + . '/extended_attributes' => json => { type => $repeatable_attr_type->code, value => 'something' } ) + ->status_is( 201, 'Repeatable attributes go through' ); # Let's add a non-repeatable one - $patron->add_extended_attribute( - { code => $unique_attr_type->code, attribute => 'non_repeatable_1' } ); + $patron->add_extended_attribute( { code => $unique_attr_type->code, attribute => 'non_repeatable_1' } ); $t->post_ok( "//$userid:$password@/api/v1/patrons/" - . $patron->id - . '/extended_attributes' => json => - { type => $unique_attr_type->code, value => 'non_repeatable_2' } ) - ->status_is(409) - ->json_is( '/error' => - 'Tried to add more than one non-repeatable attributes. type=' - . $unique_attr_type->code - . ' value=non_repeatable_2' ); + . $patron->id + . '/extended_attributes' => json => { type => $unique_attr_type->code, value => 'non_repeatable_2' } ) + ->status_is(409) + ->json_is( '/error' => 'Tried to add more than one non-repeatable attributes. type=' + . $unique_attr_type->code + . ' value=non_repeatable_2' ); }; subtest 'Attribute uniqueness tests' => sub { @@ -193,30 +191,26 @@ subtest 'add() tests' => sub { my $patron_2 = $builder->build_object( { class => 'Koha::Patrons' } ); $t->post_ok( "//$userid:$password@/api/v1/patrons/" - . $patron_2->id - . '/extended_attributes' => json => - { type => $unique_attr_type->code, value => 'non_repeatable_1' } ) - ->status_is(409) - ->json_is( '/error' => - 'Your action breaks a unique constraint on the attribute. type=' - . $unique_attr_type->code - . ' value=non_repeatable_1' ); + . $patron_2->id + . '/extended_attributes' => json => { type => $unique_attr_type->code, value => 'non_repeatable_1' } ) + ->status_is(409) + ->json_is( '/error' => 'Your action breaks a unique constraint on the attribute. type=' + . $unique_attr_type->code + . ' value=non_repeatable_1' ); }; subtest 'Invalid type tests' => sub { plan tests => 3; - my $invalid_type_obj = $builder->build_object({ class => 'Koha::Patron::Attribute::Types' }); - my $invalid_type = $invalid_type_obj->code; + my $invalid_type_obj = $builder->build_object( { class => 'Koha::Patron::Attribute::Types' } ); + my $invalid_type = $invalid_type_obj->code; $invalid_type_obj->delete; $t->post_ok( "//$userid:$password@/api/v1/patrons/" - . $patron->id - . '/extended_attributes' => json => - { type => $invalid_type, value => 'blah' } ) - ->status_is(400) - ->json_is( '/error' => "Tried to use an invalid attribute type. type=$invalid_type" ); + . $patron->id + . '/extended_attributes' => json => { type => $invalid_type, value => 'blah' } )->status_is(400) + ->json_is( '/error' => "Tried to use an invalid attribute type. type=$invalid_type" ); }; $schema->storage->txn_rollback; @@ -230,12 +224,14 @@ subtest 'overwrite() tests' => sub { Koha::Patron::Attribute::Types->delete; - my $patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 2 ** 4 } # 'borrowers' flag == 4 - }); + my $patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 2**4 } # 'borrowers' flag == 4 + } + ); my $password = 'thePassword123'; - $patron->set_password({ password => $password, skip_validation => 1 }); + $patron->set_password( { password => $password, skip_validation => 1 } ); my $userid = $patron->userid; my $mandatory_attr_type = $builder->build_object( @@ -271,70 +267,65 @@ subtest 'overwrite() tests' => sub { } } ); - my $invalid_type_obj = $builder->build_object( - { - class => 'Koha::Patron::Attribute::Types' - } - ); - my $invalid_type = $invalid_type_obj->code; + my $invalid_type_obj = $builder->build_object( { class => 'Koha::Patron::Attribute::Types' } ); + my $invalid_type = $invalid_type_obj->code; $invalid_type_obj->delete; - my $non_existent_patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $non_existent_patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $non_existent_patron_id = $non_existent_patron->id; + # get rid of the patron $non_existent_patron->delete; $t->put_ok( "//$userid:$password@/api/v1/patrons/" - . $non_existent_patron_id - . '/extended_attributes' => json => - [ { type => $repeatable_attr_type->code, value => 'something' } ] ) - ->status_is(404) - ->json_is( '/error' => 'Patron not found' ); + . $non_existent_patron_id + . '/extended_attributes' => json => [ { type => $repeatable_attr_type->code, value => 'something' } ] ) + ->status_is(404)->json_is( '/error' => 'Patron not found' ); $t->put_ok( "//$userid:$password@/api/v1/patrons/" - . $patron->id - . '/extended_attributes' => json => - [ { type => $invalid_type, value => 'something' } ] ) - ->status_is(400) - ->json_is( '/error' => "Tried to use an invalid attribute type. type=$invalid_type" ); + . $patron->id + . '/extended_attributes' => json => [ { type => $invalid_type, value => 'something' } ] )->status_is(400) + ->json_is( '/error' => "Tried to use an invalid attribute type. type=$invalid_type" ); my $unique_value = 'The only one!'; - my $dummy_patron = $builder->build_object({ class => 'Koha::Patrons' }); - $dummy_patron->add_extended_attribute({ code => $unique_attr_type->code, attribute => $unique_value }); + my $dummy_patron = $builder->build_object( { class => 'Koha::Patrons' } ); + $dummy_patron->add_extended_attribute( { code => $unique_attr_type->code, attribute => $unique_value } ); $t->put_ok( "//$userid:$password@/api/v1/patrons/" - . $patron->id - . '/extended_attributes' => json => - [ { type => $unique_attr_type->code, value => $unique_value } ] ) - ->status_is(409) - ->json_is( '/error' => "Your action breaks a unique constraint on the attribute. type=" . $unique_attr_type->code . " value=$unique_value" ); + . $patron->id + . '/extended_attributes' => json => [ { type => $unique_attr_type->code, value => $unique_value } ] ) + ->status_is(409) + ->json_is( '/error' => "Your action breaks a unique constraint on the attribute. type=" + . $unique_attr_type->code + . " value=$unique_value" ); my $value_1 = 'value_1'; my $value_2 = 'value_2'; - $t->put_ok( "//$userid:$password@/api/v1/patrons/" - . $patron->id - . '/extended_attributes' => json => - [ { type => $unique_attr_type->code, value => $value_1 }, - { type => $unique_attr_type->code, value => $value_2 } ] ) - ->status_is(409) - ->json_is( '/error' => "Tried to add more than one non-repeatable attributes. type=" . $unique_attr_type->code . " value=$value_2" ); + $t->put_ok( + "//$userid:$password@/api/v1/patrons/" . $patron->id . '/extended_attributes' => json => [ + { type => $unique_attr_type->code, value => $value_1 }, + { type => $unique_attr_type->code, value => $value_2 } + ] + )->status_is(409) + ->json_is( '/error' => "Tried to add more than one non-repeatable attributes. type=" + . $unique_attr_type->code + . " value=$value_2" ); $t->put_ok( "//$userid:$password@/api/v1/patrons/" - . $patron->id - . '/extended_attributes' => json => - [ { type => $unique_attr_type->code, value => $value_1 } ] ) - ->status_is(400) - ->json_is( '/error' => "Missing mandatory extended attribute (type=" . $mandatory_attr_type->code . ')' ); + . $patron->id + . '/extended_attributes' => json => [ { type => $unique_attr_type->code, value => $value_1 } ] ) + ->status_is(400) + ->json_is( '/error' => "Missing mandatory extended attribute (type=" . $mandatory_attr_type->code . ')' ); - $patron->add_extended_attribute({ code => $repeatable_attr_type->code, attribute => 'repeatable_1' }); - $patron->add_extended_attribute({ code => $repeatable_attr_type->code, attribute => 'repeatable_2' }); - $patron->add_extended_attribute({ code => $mandatory_attr_type->code, attribute => 'mandatory' }); - $patron->add_extended_attribute({ code => $unique_attr_type->code, attribute => 'unique' }); + $patron->add_extended_attribute( { code => $repeatable_attr_type->code, attribute => 'repeatable_1' } ); + $patron->add_extended_attribute( { code => $repeatable_attr_type->code, attribute => 'repeatable_2' } ); + $patron->add_extended_attribute( { code => $mandatory_attr_type->code, attribute => 'mandatory' } ); + $patron->add_extended_attribute( { code => $unique_attr_type->code, attribute => 'unique' } ); - $t->get_ok("//$userid:$password@/api/v1/patrons/" . $patron->id . '/extended_attributes') - ->status_is( 200, 'REST3.2.2' ) - ->json_is( '' => $patron->extended_attributes->to_api, 'Extended attributes retrieved correctly' ); + $t->get_ok( "//$userid:$password@/api/v1/patrons/" . $patron->id . '/extended_attributes' ) + ->status_is( 200, 'REST3.2.2' ) + ->json_is( '' => $patron->extended_attributes->to_api, 'Extended attributes retrieved correctly' ); my $updated_attributes = [ { @@ -355,19 +346,16 @@ subtest 'overwrite() tests' => sub { } ]; - $t->put_ok( "//$userid:$password@/api/v1/patrons/" - . $patron->id - . '/extended_attributes' => json => $updated_attributes ) - ->status_is(200) - ->json_is( '/0/type' => $updated_attributes->[0]->{type} ) - ->json_is( '/0/value' => $updated_attributes->[0]->{value} ) - ->json_is( '/1/type' => $updated_attributes->[1]->{type} ) - ->json_is( '/1/value' => $updated_attributes->[1]->{value} ) - ->json_is( '/2/type' => $updated_attributes->[2]->{type} ) - ->json_is( '/2/value' => $updated_attributes->[2]->{value} ) - ->json_is( '/3/type' => $updated_attributes->[3]->{type} ) - ->json_is( '/3/value' => $updated_attributes->[3]->{value} ) - ->json_hasnt( '/4'); + $t->put_ok( + "//$userid:$password@/api/v1/patrons/" . $patron->id . '/extended_attributes' => json => $updated_attributes ) + ->status_is(200)->json_is( '/0/type' => $updated_attributes->[0]->{type} ) + ->json_is( '/0/value' => $updated_attributes->[0]->{value} ) + ->json_is( '/1/type' => $updated_attributes->[1]->{type} ) + ->json_is( '/1/value' => $updated_attributes->[1]->{value} ) + ->json_is( '/2/type' => $updated_attributes->[2]->{type} ) + ->json_is( '/2/value' => $updated_attributes->[2]->{value} ) + ->json_is( '/3/type' => $updated_attributes->[3]->{type} ) + ->json_is( '/3/value' => $updated_attributes->[3]->{value} )->json_hasnt('/4'); $schema->storage->txn_rollback; }; @@ -378,12 +366,14 @@ subtest 'delete() tests' => sub { $schema->storage->txn_begin; - my $patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 2 ** 4 } # 'borrowers' flag == 4 - }); + my $patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 2**4 } # 'borrowers' flag == 4 + } + ); my $password = 'thePassword123'; - $patron->set_password({ password => $password, skip_validation => 1 }); + $patron->set_password( { password => $password, skip_validation => 1 } ); my $userid = $patron->userid; my $attr_type = $builder->build_object( @@ -398,23 +388,20 @@ subtest 'delete() tests' => sub { } ); - my $dummy_patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $dummy_patron = $builder->build_object( { class => 'Koha::Patrons' } ); - my $attr = $dummy_patron->add_extended_attribute({ code => $attr_type->code, attribute => 'blah' }); + my $attr = $dummy_patron->add_extended_attribute( { code => $attr_type->code, attribute => 'blah' } ); - $t->delete_ok("//$userid:$password@/api/v1/patrons/" . $dummy_patron->id . '/extended_attributes/' . $attr->id ) - ->status_is(204, 'REST3.2.4') - ->content_is('', 'REST3.3.4'); + $t->delete_ok( "//$userid:$password@/api/v1/patrons/" . $dummy_patron->id . '/extended_attributes/' . $attr->id ) + ->status_is( 204, 'REST3.2.4' )->content_is( '', 'REST3.3.4' ); - $t->delete_ok("//$userid:$password@/api/v1/patrons/" . $dummy_patron->id . '/extended_attributes/' . $attr->id ) - ->status_is(404) - ->json_is( '/error' => 'Attribute not found' ); + $t->delete_ok( "//$userid:$password@/api/v1/patrons/" . $dummy_patron->id . '/extended_attributes/' . $attr->id ) + ->status_is(404)->json_is( '/error' => 'Attribute not found' ); $dummy_patron->delete; - $t->delete_ok("//$userid:$password@/api/v1/patrons/" . $dummy_patron->id . '/extended_attributes/' . $attr->id ) - ->status_is(404) - ->json_is( '/error' => 'Patron not found' ); + $t->delete_ok( "//$userid:$password@/api/v1/patrons/" . $dummy_patron->id . '/extended_attributes/' . $attr->id ) + ->status_is(404)->json_is( '/error' => 'Patron not found' ); $schema->storage->txn_rollback; }; @@ -476,35 +463,31 @@ subtest 'update() tests' => sub { my $non_existent_attribute_id = $non_existent_attribute->id; $non_existent_attribute->delete; - my $non_existent_patron = - $builder->build_object( { class => 'Koha::Patrons' } ); + my $non_existent_patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $non_existent_patron_id = $non_existent_patron->id; # get rid of the patron $non_existent_patron->delete; $t->patch_ok( "//$userid:$password@/api/v1/patrons/" - . $non_existent_patron_id - . '/extended_attributes/' - . 123 => json => { value => 'something' } )->status_is(404) - ->json_is( '/error' => 'Patron not found' ); + . $non_existent_patron_id + . '/extended_attributes/' + . 123 => json => { value => 'something' } )->status_is(404)->json_is( '/error' => 'Patron not found' ); $t->patch_ok( "//$userid:$password@/api/v1/patrons/" - . $patron->id - . '/extended_attributes/' - . $non_existent_attribute_id => json => { value => 'something' } ) - ->status_is(404)->json_is( '/error' => 'Attribute not found' ); + . $patron->id + . '/extended_attributes/' + . $non_existent_attribute_id => json => { value => 'something' } )->status_is(404) + ->json_is( '/error' => 'Attribute not found' ); my $response = - $t->patch_ok( "//$userid:$password@/api/v1/patrons/" - . $patron->id - . '/extended_attributes/' - . $unique_attribute->id => json => { value => 'HEY' } ) - ->status_is(200)->tx->res->json; + $t->patch_ok( "//$userid:$password@/api/v1/patrons/" + . $patron->id + . '/extended_attributes/' + . $unique_attribute->id => json => { value => 'HEY' } )->status_is(200)->tx->res->json; is_deeply( - Koha::Patron::Attributes->find( $response->{extended_attribute_id} ) - ->to_api, + Koha::Patron::Attributes->find( $response->{extended_attribute_id} )->to_api, $response, "The returned object is on the DB" ); @@ -512,23 +495,20 @@ subtest 'update() tests' => sub { my $unique_value = 'HEHE'; # Add a patron with the unique attribute to test changing to it - $builder->build_object( { class => 'Koha::Patrons' } ) - ->add_extended_attribute( + $builder->build_object( { class => 'Koha::Patrons' } )->add_extended_attribute( { code => $unique_attr_type->code, attribute => $unique_value } - ); + ); $t->patch_ok( "//$userid:$password@/api/v1/patrons/" - . $patron->id - . '/extended_attributes/' - . $unique_attribute->id => json => { value => $unique_value } ) - ->status_is(409) - ->json_is( '/error' => - "Your action breaks a unique constraint on the attribute. type=" - . $unique_attr_type->code - . " value=$unique_value" ); + . $patron->id + . '/extended_attributes/' + . $unique_attribute->id => json => { value => $unique_value } )->status_is(409) + ->json_is( '/error' => "Your action breaks a unique constraint on the attribute. type=" + . $unique_attr_type->code + . " value=$unique_value" ); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/api/v1/patrons_holds.t b/t/db_dependent/api/v1/patrons_holds.t index c7a494c681..e4f7e98174 100755 --- a/t/db_dependent/api/v1/patrons_holds.t +++ b/t/db_dependent/api/v1/patrons_holds.t @@ -39,17 +39,18 @@ subtest 'list() tests' => sub { $schema->storage->txn_begin; - my $patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 2 ** 4 } # 'borrowers' flag == 4 - }); + my $patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 2**4 } # 'borrowers' flag == 4 + } + ); my $password = 'thePassword123'; - $patron->set_password({ password => $password, skip_validation => 1 }); + $patron->set_password( { password => $password, skip_validation => 1 } ); my $userid = $patron->userid; - $t->get_ok("//$userid:$password@/api/v1/patrons/" . $patron->id . '/holds') - ->status_is( 200, 'REST3.2.2' ) - ->json_is( [] ); + $t->get_ok( "//$userid:$password@/api/v1/patrons/" . $patron->id . '/holds' )->status_is( 200, 'REST3.2.2' ) + ->json_is( [] ); my $hold_1 = $builder->build_object( { class => 'Koha::Holds', value => { borrowernumber => $patron->id } } ); my $hold_2 = $builder->build_object( { class => 'Koha::Holds', value => { borrowernumber => $patron->id } } ); @@ -79,14 +80,14 @@ subtest 'list() tests' => sub { 'Old holds even after item and library removed' ); - my $non_existent_patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $non_existent_patron = $builder->build_object( { class => 'Koha::Patrons' } ); my $non_existent_patron_id = $non_existent_patron->id; + # get rid of the patron $non_existent_patron->delete; - $t->get_ok("//$userid:$password@/api/v1/patrons/" . $non_existent_patron_id . '/holds') - ->status_is( 404 ) - ->json_is( '/error' => 'Patron not found' ); + $t->get_ok( "//$userid:$password@/api/v1/patrons/" . $non_existent_patron_id . '/holds' )->status_is(404) + ->json_is( '/error' => 'Patron not found' ); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/api/v1/patrons_password.t b/t/db_dependent/api/v1/patrons_password.t index 8f79a4b81b..1551a36150 100755 --- a/t/db_dependent/api/v1/patrons_password.t +++ b/t/db_dependent/api/v1/patrons_password.t @@ -46,8 +46,7 @@ subtest 'set() (authorized user tests)' => sub { } ); my $password = 'thePassword123'; - $privileged_patron->set_password( - { password => $password, skip_validation => 1 } ); + $privileged_patron->set_password( { password => $password, skip_validation => 1 } ); my $userid = $privileged_patron->userid; my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); @@ -58,59 +57,45 @@ subtest 'set() (authorized user tests)' => sub { my $new_password = 'abc'; $t->post_ok( "//$userid:$password@/api/v1/patrons/" - . $patron->id - . "/password" => json => - { password => $new_password, password_2 => $new_password } ) - ->status_is(200)->json_is(''); + . $patron->id + . "/password" => json => { password => $new_password, password_2 => $new_password } )->status_is(200) + ->json_is(''); $t->post_ok( "//$userid:$password@/api/v1/patrons/" - . $patron->id - . "/password" => json => - { password => $new_password, password_2 => 'cde' } )->status_is(400) - ->json_is( { error => 'Passwords don\'t match' } ); + . $patron->id + . "/password" => json => { password => $new_password, password_2 => 'cde' } )->status_is(400) + ->json_is( { error => 'Passwords don\'t match' } ); t::lib::Mocks::mock_preference( 'minPasswordLength', 5 ); $t->post_ok( "//$userid:$password@/api/v1/patrons/" - . $patron->id - . "/password" => json => - { password => $new_password, password_2 => $new_password } ) - ->status_is(400) - ->json_is( - { error => 'Password length (3) is shorter than required (5)' } ); + . $patron->id + . "/password" => json => { password => $new_password, password_2 => $new_password } )->status_is(400) + ->json_is( { error => 'Password length (3) is shorter than required (5)' } ); $new_password = 'abc '; $t->post_ok( "//$userid:$password@/api/v1/patrons/" - . $patron->id - . "/password" => json => - { password => $new_password, password_2 => $new_password } ) - ->status_is(400)->json_is( - { - error => - '[Password contains leading/trailing whitespace character(s)]' - } - ); + . $patron->id + . "/password" => json => { password => $new_password, password_2 => $new_password } )->status_is(400) + ->json_is( { error => '[Password contains leading/trailing whitespace character(s)]' } ); $new_password = 'abcdefg'; $t->post_ok( "//$userid:$password@/api/v1/patrons/" - . $patron->id - . "/password" => json => - { password => $new_password, password_2 => $new_password } ) - ->status_is(200)->json_is(''); + . $patron->id + . "/password" => json => { password => $new_password, password_2 => $new_password } )->status_is(200) + ->json_is(''); t::lib::Mocks::mock_preference( 'RequireStrongPassword', 1 ); $t->post_ok( "//$userid:$password@/api/v1/patrons/" - . $patron->id - . "/password" => json => - { password => $new_password, password_2 => $new_password } ) - ->status_is(400)->json_is( { error => '[Password is too weak]' } ); + . $patron->id + . "/password" => json => { password => $new_password, password_2 => $new_password } )->status_is(400) + ->json_is( { error => '[Password is too weak]' } ); $new_password = 'ABcde123%&'; $t->post_ok( "//$userid:$password@/api/v1/patrons/" - . $patron->id - . "/password" => json => - { password => $new_password, password_2 => $new_password } ) - ->status_is(200)->json_is(''); + . $patron->id + . "/password" => json => { password => $new_password, password_2 => $new_password } )->status_is(200) + ->json_is(''); $schema->storage->txn_rollback; }; @@ -124,7 +109,7 @@ subtest 'set_public() (unprivileged user tests)' => sub { my $category = $builder->build_object( { class => 'Koha::Patron::Categories', - value => { change_password => 0 } # disallow changing password for the patron category + value => { change_password => 0 } # disallow changing password for the patron category } ); my $patron = $builder->build_object( @@ -149,82 +134,59 @@ subtest 'set_public() (unprivileged user tests)' => sub { my $new_password = 'abc'; $t->post_ok( - "//$userid:$password@/api/v1/public/patrons/" - . $patron->id - . "/password" => json => { + "//$userid:$password@/api/v1/public/patrons/" . $patron->id . "/password" => json => { password => $new_password, password_repeated => $new_password, old_password => 'blah' - } - )->status_is(403)->json_is( - { - error => 'Changing password is forbidden' } - ); + )->status_is(403)->json_is( { error => 'Changing password is forbidden' } ); t::lib::Mocks::mock_preference( 'OpacPasswordChange', 1 ); $t->post_ok( - "//$userid:$password@/api/v1/public/patrons/" - . $other_patron->id - . "/password" => json => { + "//$userid:$password@/api/v1/public/patrons/" . $other_patron->id . "/password" => json => { password => $new_password, password_repeated => $new_password, old_password => $password - } - )->status_is(403) - ->json_is( '/error', - "Authorization failure. Missing required permission(s)." ); + } + )->status_is(403)->json_is( + '/error', + "Authorization failure. Missing required permission(s)." + ); $t->post_ok( - "//$userid:$password@/api/v1/public/patrons/" - . $patron->id - . "/password" => json => { + "//$userid:$password@/api/v1/public/patrons/" . $patron->id . "/password" => json => { password => $new_password, password_repeated => $new_password, old_password => $password - } - )->status_is(403)->json_is({ error => 'Changing password is forbidden' }); + } + )->status_is(403)->json_is( { error => 'Changing password is forbidden' } ); # Allow password changing to the patron category $category->change_password(1)->store; $t->post_ok( - "//$userid:$password@/api/v1/public/patrons/" - . $patron->id - . "/password" => json => { + "//$userid:$password@/api/v1/public/patrons/" . $patron->id . "/password" => json => { password => $new_password, password_repeated => 'wrong_password', old_password => $password - } - )->status_is(400)->json_is( - { - error => "Passwords don't match" } - ); + )->status_is(400)->json_is( { error => "Passwords don't match" } ); $t->post_ok( - "//$userid:$password@/api/v1/public/patrons/" - . $patron->id - . "/password" => json => { + "//$userid:$password@/api/v1/public/patrons/" . $patron->id . "/password" => json => { password => $new_password, password_repeated => $new_password, old_password => 'badpassword' - } - )->status_is(400)->json_is( - { - error => "Invalid password" } - ); + )->status_is(400)->json_is( { error => "Invalid password" } ); $t->post_ok( - "//$userid:$password@/api/v1/public/patrons/" - . $patron->id - . "/password" => json => { + "//$userid:$password@/api/v1/public/patrons/" . $patron->id . "/password" => json => { password => $new_password, password_repeated => $new_password, old_password => $password - } + } )->status_is(200)->json_is(''); $schema->storage->txn_rollback; diff --git a/t/db_dependent/api/v1/patrons_password_expiration.t b/t/db_dependent/api/v1/patrons_password_expiration.t index 9e444acbf0..fc4b0eb90b 100755 --- a/t/db_dependent/api/v1/patrons_password_expiration.t +++ b/t/db_dependent/api/v1/patrons_password_expiration.t @@ -46,8 +46,7 @@ subtest 'basic tests' => sub { } ); my $password = 'thePassword123'; - $privileged_patron->set_password( - { password => $password, skip_validation => 1 } ); + $privileged_patron->set_password( { password => $password, skip_validation => 1 } ); my $userid = $privileged_patron->userid; my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); @@ -55,35 +54,29 @@ subtest 'basic tests' => sub { my $new_password = 'abc'; $t->put_ok( "//$userid:$password@/api/v1/patrons/" - . $patron->id - . "/password/expiration_date" => json => - { expiration_date => '2021-01-01' } ) - ->status_is(200)->json_is(''); + . $patron->id + . "/password/expiration_date" => json => { expiration_date => '2021-01-01' } )->status_is(200)->json_is(''); $t->put_ok( "//$userid:$password@/api/v1/patrons/" - . $patron->id - . "/password/expiration_date" => json => - { expiration_date => '01/13/2021' } ) - ->status_is(400)->json_is('/errors/0/message' => 'Does not match date format.'); + . $patron->id + . "/password/expiration_date" => json => { expiration_date => '01/13/2021' } )->status_is(400) + ->json_is( '/errors/0/message' => 'Does not match date format.' ); $t->put_ok( "//$userid:$password@/api/v1/patrons/" - . $patron->id - . "/password/expiration_date" => json => - { expiration_date => '13/01/2021' } ) - ->status_is(400)->json_is('/errors/0/message' => 'Does not match date format.'); + . $patron->id + . "/password/expiration_date" => json => { expiration_date => '13/01/2021' } )->status_is(400) + ->json_is( '/errors/0/message' => 'Does not match date format.' ); $privileged_patron->flags(0)->store(); $t->put_ok( "//$userid:$password@/api/v1/patrons/" - . $patron->id - . "/password/expiration_date" => json => - { expiration_date => '2021-01-01' } ) - ->status_is(403)->json_is({ - error => "Authorization failure. Missing required permission(s).", - "required_permissions" => { - "superlibrarian" => "1" - } - }); + . $patron->id + . "/password/expiration_date" => json => { expiration_date => '2021-01-01' } )->status_is(403)->json_is( + { + error => "Authorization failure. Missing required permission(s).", + "required_permissions" => { "superlibrarian" => "1" } + } + ); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/api/v1/patrons_recalls.t b/t/db_dependent/api/v1/patrons_recalls.t index 96843a6f41..196401bd7a 100755 --- a/t/db_dependent/api/v1/patrons_recalls.t +++ b/t/db_dependent/api/v1/patrons_recalls.t @@ -59,8 +59,7 @@ subtest 'list() tests' => sub { my $recall_3 = $builder->build_object( { class => 'Koha::Recalls', value => { patron_id => $patron_2->id } } ); $t->get_ok( "//$userid:$password@/api/v1/patrons/" . $patron->id . '/recalls?_order_by=+me.recall_id' ) - ->status_is( 200, 'REST3.2.2' ) - ->json_is( '' => [ $recall_1->to_api, $recall_2->to_api ], 'Recalls retrieved' ); + ->status_is( 200, 'REST3.2.2' )->json_is( '' => [ $recall_1->to_api, $recall_2->to_api ], 'Recalls retrieved' ); $t->get_ok( "//$userid:$password@/api/v1/patrons/" . $patron_2->id . '/recalls?_order_by=+me.recall_id' ) ->status_is( 200, 'REST3.2.2' )->json_is( '' => [ $recall_3->to_api ], 'Recalls retrieved' ); diff --git a/t/db_dependent/api/v1/preservation_Processings.t b/t/db_dependent/api/v1/preservation_Processings.t index b34bf42af4..2b922b8058 100755 --- a/t/db_dependent/api/v1/preservation_Processings.t +++ b/t/db_dependent/api/v1/preservation_Processings.t @@ -336,8 +336,8 @@ subtest 'delete() tests' => sub { $t->delete_ok("//$unauth_userid:$password@/api/v1/preservation/processings/$processing_id")->status_is(403); # Delete existing processing - $t->delete_ok("//$userid:$password@/api/v1/preservation/processings/$processing_id") - ->status_is( 204, 'REST3.2.4' )->content_is( '', 'REST3.3.4' ); + $t->delete_ok("//$userid:$password@/api/v1/preservation/processings/$processing_id")->status_is( 204, 'REST3.2.4' ) + ->content_is( '', 'REST3.3.4' ); # Attempt to delete non-existent processing $t->delete_ok("//$userid:$password@/api/v1/preservation/processings/$processing_id")->status_is(404); diff --git a/t/db_dependent/api/v1/query.t b/t/db_dependent/api/v1/query.t index f807f21ea2..100f6b427f 100755 --- a/t/db_dependent/api/v1/query.t +++ b/t/db_dependent/api/v1/query.t @@ -52,56 +52,46 @@ subtest 'q handling tests' => sub { Koha::Cities->new->delete; # No cities, so empty array should be returned - $t->get_ok("//$userid:$password@/api/v1/cities")->status_is(200) - ->json_is( [] ); + $t->get_ok("//$userid:$password@/api/v1/cities")->status_is(200)->json_is( [] ); my $names = [ 'AA', 'BA', 'BA', 'CA', 'DA', 'EB', 'FB', 'GB', 'HB', 'IB', ]; # Add 10 cities foreach my $i ( 0 .. 9 ) { - $builder->build_object( - { class => 'Koha::Cities', value => { city_name => $names->[$i] } } - ); + $builder->build_object( { class => 'Koha::Cities', value => { city_name => $names->[$i] } } ); } t::lib::Mocks::mock_preference( 'RESTdefaultPageSize', 20 ); my $q_ends_with_a = 'q={"name":{"-like":"%A"}}'; - my $cities = - $t->get_ok( - "//$userid:$password@/api/v1/cities?$q_ends_with_a") - ->status_is(200)->tx->res->json; + my $cities = $t->get_ok("//$userid:$password@/api/v1/cities?$q_ends_with_a")->status_is(200)->tx->res->json; is( scalar @{$cities}, 5, '5 cities retrieved' ); my $q_starts_with_a = 'q={"name":{"-like":"A%"}}'; $cities = - $t->get_ok( - "//$userid:$password@/api/v1/cities?$q_ends_with_a&$q_starts_with_a") - ->status_is(200)->tx->res->json; + $t->get_ok("//$userid:$password@/api/v1/cities?$q_ends_with_a&$q_starts_with_a")->status_is(200)->tx->res->json; is( scalar @{$cities}, 1, '1 city retrieved' ); my $q_empty_list = "q=[]"; $cities = - $t->get_ok( - "//$userid:$password@/api/v1/cities?$q_ends_with_a&$q_starts_with_a&$q_empty_list") - ->status_is(200)->tx->res->json; + $t->get_ok("//$userid:$password@/api/v1/cities?$q_ends_with_a&$q_starts_with_a&$q_empty_list")->status_is(200) + ->tx->res->json; is( scalar @{$cities}, 1, 'empty list as trailing query, 1 city retrieved' ); $cities = - $t->get_ok( - "//$userid:$password@/api/v1/cities?$q_empty_list&$q_ends_with_a&$q_starts_with_a") - ->status_is(200)->tx->res->json; + $t->get_ok("//$userid:$password@/api/v1/cities?$q_empty_list&$q_ends_with_a&$q_starts_with_a")->status_is(200) + ->tx->res->json; is( scalar @{$cities}, 1, 'empty list as first query, 1 city retrieved' ); - $t->get_ok("//$userid:$password@/api/v1/cities" => { 'x-koha-request-id' => 100 } ) - ->header_is( 'x-koha-request-id' => 100 ); + $t->get_ok( "//$userid:$password@/api/v1/cities" => { 'x-koha-request-id' => 100 } ) + ->header_is( 'x-koha-request-id' => 100 ); $schema->storage->txn_rollback; }; @@ -124,27 +114,18 @@ subtest 'x-koha-embed tests' => sub { my $patron_id = $builder->build_object( { class => 'Koha::Patrons' } )->id; - my $res = $t->get_ok( - "//$userid:$password@/api/v1/patrons?q={\"me.patron_id\":$patron_id}" - => { 'x-koha-embed' => 'extended_attributes' } )->status_is(200) - ->tx->res->json; + my $res = $t->get_ok( "//$userid:$password@/api/v1/patrons?q={\"me.patron_id\":$patron_id}" => + { 'x-koha-embed' => 'extended_attributes' } )->status_is(200)->tx->res->json; is( scalar @{$res}, 1, 'One patron returned' ); - $res = $t->get_ok( - "//$userid:$password@/api/v1/patrons?q={\"me.patron_id\":$patron_id}" => { - 'x-koha-embed' => - 'extended_attributes,custom_bad_embed,another_bad_embed' - } - )->status_is(400); + $res = $t->get_ok( "//$userid:$password@/api/v1/patrons?q={\"me.patron_id\":$patron_id}" => + { 'x-koha-embed' => 'extended_attributes,custom_bad_embed,another_bad_embed' } )->status_is(400); - $res = $t->get_ok( - "//$userid:$password@/api/v1/cities" => { - 'x-koha-embed' => 'any_embed' - } - )->status_is(400)->tx->res->json; + $res = $t->get_ok( "//$userid:$password@/api/v1/cities" => { 'x-koha-embed' => 'any_embed' } )->status_is(400) + ->tx->res->json; - is($res, 'Embedding objects is not allowed on this endpoint.', 'Correct error message is returned'); + is( $res, 'Embedding objects is not allowed on this endpoint.', 'Correct error message is returned' ); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/api/v1/return_claims.t b/t/db_dependent/api/v1/return_claims.t index c43557adbe..72646dad71 100755 --- a/t/db_dependent/api/v1/return_claims.t +++ b/t/db_dependent/api/v1/return_claims.t @@ -59,7 +59,7 @@ subtest 'claim_returned() tests' => sub { } ); - t::lib::Mocks::mock_userenv({ branchcode => $librarian->branchcode }); + t::lib::Mocks::mock_userenv( { branchcode => $librarian->branchcode } ); my $item = $builder->build_sample_item; my $issue = AddIssue( $patron, $item->barcode, dt_from_string->add( weeks => 2 ) ); @@ -107,8 +107,7 @@ subtest 'claim_returned() tests' => sub { created_by => $librarian->id, notes => "This is a test note." } - )->status_is(404) - ->json_is( '/error' => 'Checkout not found' ); + )->status_is(404)->json_is( '/error' => 'Checkout not found' ); $schema->storage->txn_rollback; }; @@ -131,11 +130,12 @@ subtest 'update_notes() tests' => sub { my $item = $builder->build_sample_item; - t::lib::Mocks::mock_userenv( { branchcode => $item->homebranch } ) - ; # needed by AddIssue + t::lib::Mocks::mock_userenv( { branchcode => $item->homebranch } ); # needed by AddIssue - my $issue = AddIssue( $librarian, $item->barcode, - dt_from_string->add( weeks => 2 ) ); + my $issue = AddIssue( + $librarian, $item->barcode, + dt_from_string->add( weeks => 2 ) + ); my $claim = $issue->claim_returned( { @@ -170,8 +170,7 @@ subtest 'update_notes() tests' => sub { notes => "This is a different test note.", updated_by => $librarian->id, } - )->status_is(404) - ->json_is( '/error' => 'Claim not found' ); + )->status_is(404)->json_is( '/error' => 'Claim not found' ); $schema->storage->txn_rollback; }; @@ -194,11 +193,11 @@ subtest 'resolve_claim() tests' => sub { my $item = $builder->build_sample_item; - t::lib::Mocks::mock_userenv( { branchcode => $item->homebranch } ); # needed by AddIssue + t::lib::Mocks::mock_userenv( { branchcode => $item->homebranch } ); # needed by AddIssue # Picking 1 that should exist my $ClaimReturnedLostValue = 1; - t::lib::Mocks::mock_preference('ClaimReturnedLostValue', $ClaimReturnedLostValue); + t::lib::Mocks::mock_preference( 'ClaimReturnedLostValue', $ClaimReturnedLostValue ); my $issue = AddIssue( $librarian, $item->barcode, dt_from_string->add( weeks => 2 ) ); @@ -216,7 +215,7 @@ subtest 'resolve_claim() tests' => sub { created_by => undef, updated_by => undef, } - )->store; # resolve the claim must work even if the created_by patron has been removed + )->store; # resolve the claim must work even if the created_by patron has been removed # Resolve a claim $t->put_ok( @@ -227,36 +226,33 @@ subtest 'resolve_claim() tests' => sub { )->status_is(200); $claim->discard_changes; - is( $claim->resolution, "FOUNDINLIB" ); + is( $claim->resolution, "FOUNDINLIB" ); is( $claim->resolved_by, $librarian->id ); - is( $claim->updated_by, $librarian->id ); + is( $claim->updated_by, $librarian->id ); ok( $claim->resolved_on ); is( $claim->checkout->item->itemlost, $ClaimReturnedLostValue ); - $claim->update({resolution => undef, resolved_by => undef, resolved_on => undef }); + $claim->update( { resolution => undef, resolved_by => undef, resolved_on => undef } ); $t->put_ok( "//$userid:$password@/api/v1/return_claims/$claim_id/resolve" => json => { - resolved_by => $librarian->id, - resolution => "FOUNDINLIB", + resolved_by => $librarian->id, + resolution => "FOUNDINLIB", new_lost_status => 0, } )->status_is(200); is( $claim->get_from_storage->checkout->item->itemlost, 0 ); - # Make sure the claim doesn't exist on the DB anymore $claim->delete; ## Invalid claim id $t->put_ok( - "//$userid:$password@/api/v1/return_claims/$claim_id/resolve" => json => - { + "//$userid:$password@/api/v1/return_claims/$claim_id/resolve" => json => { resolved_by => $librarian->id, resolution => "FOUNDINLIB", } - )->status_is(404) - ->json_is( '/error' => 'Claim not found' ); + )->status_is(404)->json_is( '/error' => 'Claim not found' ); $schema->storage->txn_rollback; }; @@ -279,10 +275,12 @@ subtest 'delete() tests' => sub { my $item = $builder->build_sample_item; - t::lib::Mocks::mock_userenv({ branchcode => $item->homebranch }); + t::lib::Mocks::mock_userenv( { branchcode => $item->homebranch } ); - my $issue = C4::Circulation::AddIssue( $librarian, - $item->barcode, dt_from_string->add( weeks => 2 ) ); + my $issue = C4::Circulation::AddIssue( + $librarian, + $item->barcode, dt_from_string->add( weeks => 2 ) + ); my $claim = $issue->claim_returned( { @@ -292,16 +290,14 @@ subtest 'delete() tests' => sub { ); # Test deleting a return claim - $t->delete_ok("//$userid:$password@/api/v1/return_claims/" . $claim->id) - ->status_is( 204, 'REST3.2.4' ) - ->content_is( '', 'REST3.3.4' ); + $t->delete_ok( "//$userid:$password@/api/v1/return_claims/" . $claim->id )->status_is( 204, 'REST3.2.4' ) + ->content_is( '', 'REST3.3.4' ); - my $THE_claim = Koha::Checkouts::ReturnClaims->find($claim->id); + my $THE_claim = Koha::Checkouts::ReturnClaims->find( $claim->id ); isnt( $THE_claim, "Return claim was deleted" ); - $t->delete_ok("//$userid:$password@/api/v1/return_claims/" . $claim->id) - ->status_is(404) - ->json_is( '/error' => 'Claim not found' ); + $t->delete_ok( "//$userid:$password@/api/v1/return_claims/" . $claim->id )->status_is(404) + ->json_is( '/error' => 'Claim not found' ); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/api/v1/search_filters.t b/t/db_dependent/api/v1/search_filters.t index 6b16603b60..6a7c592109 100755 --- a/t/db_dependent/api/v1/search_filters.t +++ b/t/db_dependent/api/v1/search_filters.t @@ -41,59 +41,70 @@ subtest 'list() tests' => sub { Koha::SearchFilters->search()->delete(); - my $patron_1 = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 3 } - }); + my $patron_1 = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 3 } + } + ); my $password = 'thePassword123'; - $patron_1->set_password({ password => $password, skip_validation => 1 }); + $patron_1->set_password( { password => $password, skip_validation => 1 } ); my $userid = $patron_1->userid; # Create test context - my $search_filter_1 = $builder->build_object({ class => 'Koha::SearchFilters', value => + my $search_filter_1 = $builder->build_object( { - name => 'Test1', - query => 'kw:this', - limits => 'mc-itype,phr:BK', - opac => 1, - staff_client => 1 + class => 'Koha::SearchFilters', + value => { + name => 'Test1', + query => 'kw:this', + limits => 'mc-itype,phr:BK', + opac => 1, + staff_client => 1 + } } - }); - my $search_filter_2 = $builder->build_object({ class => 'Koha::SearchFilters', value => + ); + my $search_filter_2 = $builder->build_object( { - name => 'Test2', - query => 'kw:that', - limits => 'mc-itype,phr:BK', - opac => 0, - staff_client => 1 + class => 'Koha::SearchFilters', + value => { + name => 'Test2', + query => 'kw:that', + limits => 'mc-itype,phr:BK', + opac => 0, + staff_client => 1 + } } - }); - my $search_filter_3 = $builder->build_object({ class => 'Koha::SearchFilters', value => + ); + my $search_filter_3 = $builder->build_object( { - name => 'Test3', - query => 'kw:any', - limits => 'mc-itype,phr:CD', - opac => 0, - staff_client => 0 + class => 'Koha::SearchFilters', + value => { + name => 'Test3', + query => 'kw:any', + limits => 'mc-itype,phr:CD', + opac => 0, + staff_client => 0 + } } - }); - my $search_filter_4 = $builder->build_object({ class => 'Koha::SearchFilters', value => + ); + my $search_filter_4 = $builder->build_object( { - name => 'Test4', - query => 'kw:some', - limits => 'mc-itype,phr:CD', - opac => 1, - staff_client => 0 + class => 'Koha::SearchFilters', + value => { + name => 'Test4', + query => 'kw:some', + limits => 'mc-itype,phr:CD', + opac => 1, + staff_client => 0 + } } - }); + ); # Make sure we are returned with the correct amount of macros - $t->get_ok( "//$userid:$password@/api/v1/search_filters" ) - ->status_is( 200, 'REST3.2.2' ) - ->json_has('/0/search_filter_id') - ->json_has('/1/search_filter_id') - ->json_has('/2/search_filter_id') - ->json_has('/3/search_filter_id'); + $t->get_ok("//$userid:$password@/api/v1/search_filters")->status_is( 200, 'REST3.2.2' ) + ->json_has('/0/search_filter_id')->json_has('/1/search_filter_id')->json_has('/2/search_filter_id') + ->json_has('/3/search_filter_id'); $schema->storage->txn_rollback; }; @@ -104,12 +115,14 @@ subtest 'get() tests' => sub { $schema->storage->txn_begin; - my $patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 3 } - }); + my $patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 3 } + } + ); my $password = 'thePassword123'; - $patron->set_password({ password => $password, skip_validation => 1 }); + $patron->set_password( { password => $password, skip_validation => 1 } ); my $userid = $patron->userid; my $search_filter_1 = $builder->build_object( { class => 'Koha::SearchFilters' } ); @@ -117,20 +130,18 @@ subtest 'get() tests' => sub { my $search_filter_3 = $builder->build_object( { class => 'Koha::SearchFilters' } ); $t->get_ok( "//$userid:$password@/api/v1/search_filters/" . $search_filter_1->id ) - ->status_is( 200, 'Filter retrieved correctly' ) - ->json_is( $search_filter_1->to_api ); + ->status_is( 200, 'Filter retrieved correctly' )->json_is( $search_filter_1->to_api ); my $non_existent_code = $search_filter_1->id; $search_filter_1->delete; - $t->get_ok( "//$userid:$password@/api/v1/search_filters/" . $non_existent_code ) - ->status_is(404) - ->json_is( '/error' => 'Search filter not found' ); + $t->get_ok( "//$userid:$password@/api/v1/search_filters/" . $non_existent_code )->status_is(404) + ->json_is( '/error' => 'Search filter not found' ); $patron->flags(4)->store; $t->get_ok( "//$userid:$password/api/v1/search_filters/" . $search_filter_2->id ) - ->status_is( 401, 'Cannot search filters without permission' ) - ->json_is( '/error' => 'Authentication failure.' ); + ->status_is( 401, 'Cannot search filters without permission' ) + ->json_is( '/error' => 'Authentication failure.' ); $schema->storage->txn_rollback; }; @@ -141,64 +152,67 @@ subtest 'add() tests' => sub { $schema->storage->txn_begin; - my $authorized_patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 0 } - }); - $builder->build({ - source => 'UserPermission', - value => { - borrowernumber => $authorized_patron->borrowernumber, - module_bit => 3, - code => 'manage_search_filters', - }, - }); + my $authorized_patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 0 } + } + ); + $builder->build( + { + source => 'UserPermission', + value => { + borrowernumber => $authorized_patron->borrowernumber, + module_bit => 3, + code => 'manage_search_filters', + }, + } + ); my $password = 'thePassword123'; - $authorized_patron->set_password({ password => $password, skip_validation => 1 }); + $authorized_patron->set_password( { password => $password, skip_validation => 1 } ); my $auth_userid = $authorized_patron->userid; - my $unauthorized_patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 0 } - }); - $unauthorized_patron->set_password({ password => $password, skip_validation => 1 }); + my $unauthorized_patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 0 } + } + ); + $unauthorized_patron->set_password( { password => $password, skip_validation => 1 } ); my $unauth_userid = $unauthorized_patron->userid; - my $search_filter = $builder->build_object({ class => 'Koha::SearchFilters' }); + my $search_filter = $builder->build_object( { class => 'Koha::SearchFilters' } ); my $search_filter_values = $search_filter->to_api; delete $search_filter_values->{search_filter_id}; $search_filter->delete; # Unauthorized attempt to write - $t->post_ok( "//$unauth_userid:$password@/api/v1/search_filters" => json => $search_filter_values ) - ->status_is(403); + $t->post_ok( "//$unauth_userid:$password@/api/v1/search_filters" => json => $search_filter_values )->status_is(403); # Authorized attempt to write invalid data - my $search_filter_with_invalid_field = { %$search_filter_values }; + my $search_filter_with_invalid_field = {%$search_filter_values}; $search_filter_with_invalid_field->{'coffee_filter'} = 'Chemex'; $t->post_ok( "//$auth_userid:$password@/api/v1/search_filters" => json => $search_filter_with_invalid_field ) - ->status_is(400) - ->json_is( + ->status_is(400)->json_is( "/errors" => [ { message => "Properties not allowed: coffee_filter.", path => "/body" } ] - ); + ); # Authorized attempt to write $t->post_ok( "//$auth_userid:$password@/api/v1/search_filters" => json => $search_filter_values ) - ->status_is( 201, 'REST3.2.1' ) - ->json_has( '/search_filter_id', 'We generated a new id' ) - ->json_is( '/name' => $search_filter_values->{name}, 'The name matches what we supplied' ) - ->json_is( '/query' => $search_filter_values->{query}, 'The query matches what we supplied' ) - ->json_is( '/limits' => $search_filter_values->{limits}, 'The limits match what we supplied' ) - ->json_is( '/opac' => $search_filter_values->{opac}, 'The limits match what we supplied' ) - ->json_is( '/staff_client' => $search_filter_values->{staff_client}, 'The limits match what we supplied' ) - ->header_like( Location => qr|^\/api\/v1\/search_filters\/d*|, 'Correct location' ); + ->status_is( 201, 'REST3.2.1' )->json_has( '/search_filter_id', 'We generated a new id' ) + ->json_is( '/name' => $search_filter_values->{name}, 'The name matches what we supplied' ) + ->json_is( '/query' => $search_filter_values->{query}, 'The query matches what we supplied' ) + ->json_is( '/limits' => $search_filter_values->{limits}, 'The limits match what we supplied' ) + ->json_is( '/opac' => $search_filter_values->{opac}, 'The limits match what we supplied' ) + ->json_is( '/staff_client' => $search_filter_values->{staff_client}, 'The limits match what we supplied' ) + ->header_like( Location => qr|^\/api\/v1\/search_filters\/d*|, 'Correct location' ); # save the library_id my $search_filter_id = 999; @@ -206,15 +220,15 @@ subtest 'add() tests' => sub { # Authorized attempt to create with existing id $search_filter_values->{search_filter_id} = $search_filter_id; - $t->post_ok( "//$auth_userid:$password@/api/v1/search_filters" => json => $search_filter_values ) - ->status_is(400) - ->json_is( '/errors' => [ + $t->post_ok( "//$auth_userid:$password@/api/v1/search_filters" => json => $search_filter_values )->status_is(400) + ->json_is( + '/errors' => [ { message => "Read-only.", - path => "/body/search_filter_id" + path => "/body/search_filter_id" } ] - ); + ); $schema->storage->txn_rollback; }; @@ -225,39 +239,44 @@ subtest 'update() tests' => sub { $schema->storage->txn_begin; - my $authorized_patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 0 } - }); - $builder->build({ - source => 'UserPermission', - value => { - borrowernumber => $authorized_patron->borrowernumber, - module_bit => 3, - code => 'manage_search_filters', - }, - }); + my $authorized_patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 0 } + } + ); + $builder->build( + { + source => 'UserPermission', + value => { + borrowernumber => $authorized_patron->borrowernumber, + module_bit => 3, + code => 'manage_search_filters', + }, + } + ); my $password = 'thePassword123'; - $authorized_patron->set_password({ password => $password, skip_validation => 1 }); + $authorized_patron->set_password( { password => $password, skip_validation => 1 } ); my $auth_userid = $authorized_patron->userid; - my $unauthorized_patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 0 } - }); - $unauthorized_patron->set_password({ password => $password, skip_validation => 1 }); + my $unauthorized_patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 0 } + } + ); + $unauthorized_patron->set_password( { password => $password, skip_validation => 1 } ); my $unauth_userid = $unauthorized_patron->userid; - my $search_filter = $builder->build_object({ class => 'Koha::SearchFilters' }); - my $search_filter_id = $search_filter->id; + my $search_filter = $builder->build_object( { class => 'Koha::SearchFilters' } ); + my $search_filter_id = $search_filter->id; my $search_filter_values = $search_filter->to_api; delete $search_filter_values->{search_filter_id}; # Unauthorized attempt to update - $t->put_ok( "//$unauth_userid:$password@/api/v1/search_filters/$search_filter_id" - => json => { name => 'New unauthorized name change' } ) - ->status_is(403); + $t->put_ok( "//$unauth_userid:$password@/api/v1/search_filters/$search_filter_id" => json => + { name => 'New unauthorized name change' } )->status_is(403); my $search_filter_update = { name => "Filter update", @@ -265,36 +284,36 @@ subtest 'update() tests' => sub { limits => "mc-ccode:fantasy", }; - my $test = $t->put_ok( "//$auth_userid:$password@/api/v1/search_filters/$search_filter_id" => json => $search_filter_update ) - ->status_is(200, 'Authorized user can update a macro') - ->json_is( '/search_filter_id' => $search_filter_id, 'We get back the id' ) - ->json_is( '/name' => $search_filter_update->{name}, 'We get back the name' ) - ->json_is( '/query' => $search_filter_update->{query}, 'We get back our query' ) - ->json_is( '/limits' => $search_filter_update->{limits}, 'We get back our limits' ) - ->json_is( '/opac' => 1, 'We get back our opac visibility unchanged' ) - ->json_is( '/staff_client' => 1, 'We get back our staff client visibility unchanged' ); + my $test = $t->put_ok( + "//$auth_userid:$password@/api/v1/search_filters/$search_filter_id" => json => $search_filter_update ) + ->status_is( 200, 'Authorized user can update a macro' ) + ->json_is( '/search_filter_id' => $search_filter_id, 'We get back the id' ) + ->json_is( '/name' => $search_filter_update->{name}, 'We get back the name' ) + ->json_is( '/query' => $search_filter_update->{query}, 'We get back our query' ) + ->json_is( '/limits' => $search_filter_update->{limits}, 'We get back our limits' ) + ->json_is( '/opac' => 1, 'We get back our opac visibility unchanged' ) + ->json_is( '/staff_client' => 1, 'We get back our staff client visibility unchanged' ); # Authorized attempt to write invalid data - my $search_filter_with_invalid_field = { %$search_filter_update }; + my $search_filter_with_invalid_field = {%$search_filter_update}; $search_filter_with_invalid_field->{'coffee_filter'} = 'Chemex'; - $t->put_ok( "//$auth_userid:$password@/api/v1/search_filters/$search_filter_id" => json => $search_filter_with_invalid_field ) - ->status_is(400) - ->json_is( + $t->put_ok( "//$auth_userid:$password@/api/v1/search_filters/$search_filter_id" => json => + $search_filter_with_invalid_field )->status_is(400)->json_is( "/errors" => [ { message => "Properties not allowed: coffee_filter.", path => "/body" } ] - ); + ); - my $non_existent_macro = $builder->build_object({class => 'Koha::SearchFilters'}); - my $non_existent_code = $non_existent_macro->id; + my $non_existent_macro = $builder->build_object( { class => 'Koha::SearchFilters' } ); + my $non_existent_code = $non_existent_macro->id; $non_existent_macro->delete; - $t->put_ok("//$auth_userid:$password@/api/v1/search_filters/$non_existent_code" => json => $search_filter_update) - ->status_is(404); + $t->put_ok( "//$auth_userid:$password@/api/v1/search_filters/$non_existent_code" => json => $search_filter_update ) + ->status_is(404); $schema->storage->txn_rollback; }; @@ -305,41 +324,47 @@ subtest 'delete() tests' => sub { $schema->storage->txn_begin; - my $authorized_patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 0 } - }); - $builder->build({ - source => 'UserPermission', - value => { - borrowernumber => $authorized_patron->borrowernumber, - module_bit => 3, - code => 'manage_search_filters', - }, - }); + my $authorized_patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 0 } + } + ); + $builder->build( + { + source => 'UserPermission', + value => { + borrowernumber => $authorized_patron->borrowernumber, + module_bit => 3, + code => 'manage_search_filters', + }, + } + ); my $password = 'thePassword123'; - $authorized_patron->set_password({ password => $password, skip_validation => 1 }); + $authorized_patron->set_password( { password => $password, skip_validation => 1 } ); my $auth_userid = $authorized_patron->userid; - my $unauthorized_patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 0 } - }); - $unauthorized_patron->set_password({ password => $password, skip_validation => 1 }); + my $unauthorized_patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 0 } + } + ); + $unauthorized_patron->set_password( { password => $password, skip_validation => 1 } ); my $unauth_userid = $unauthorized_patron->userid; - my $search_filter = $builder->build_object({ class => 'Koha::SearchFilters' }); - my $search_filter_2 = $builder->build_object({ class => 'Koha::SearchFilters' }); - my $search_filter_id = $search_filter->id; + my $search_filter = $builder->build_object( { class => 'Koha::SearchFilters' } ); + my $search_filter_2 = $builder->build_object( { class => 'Koha::SearchFilters' } ); + my $search_filter_id = $search_filter->id; my $search_filter_2_id = $search_filter_2->id; # Unauthorized attempt to delete - $t->delete_ok( "//$unauth_userid:$password@/api/v1/search_filters/$search_filter_2_id") - ->status_is(403, "Cannot delete search filter without permission"); + $t->delete_ok("//$unauth_userid:$password@/api/v1/search_filters/$search_filter_2_id") + ->status_is( 403, "Cannot delete search filter without permission" ); - $t->delete_ok( "//$auth_userid:$password@/api/v1/search_filters/$search_filter_id") - ->status_is( 204, 'Can delete search filter with permission'); + $t->delete_ok("//$auth_userid:$password@/api/v1/search_filters/$search_filter_id") + ->status_is( 204, 'Can delete search filter with permission' ); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/api/v1/smtp_servers.t b/t/db_dependent/api/v1/smtp_servers.t index d509d0f8f8..b095ef6fbd 100755 --- a/t/db_dependent/api/v1/smtp_servers.t +++ b/t/db_dependent/api/v1/smtp_servers.t @@ -62,27 +62,21 @@ subtest 'list() tests' => sub { ## Authorized user tests # No SMTP servers, so empty array should be returned - $t->get_ok("//$userid:$password@/api/v1/config/smtp_servers") - ->status_is(200)->json_is( [] ); + $t->get_ok("//$userid:$password@/api/v1/config/smtp_servers")->status_is(200)->json_is( [] ); - my $smtp_server = - $builder->build_object( { class => 'Koha::SMTP::Servers' } ); + my $smtp_server = $builder->build_object( { class => 'Koha::SMTP::Servers' } ); # One smtp server created, should get returned - $t->get_ok("//$userid:$password@/api/v1/config/smtp_servers") - ->status_is(200)->json_is( [ $smtp_server->to_api ] ); + $t->get_ok("//$userid:$password@/api/v1/config/smtp_servers")->status_is(200)->json_is( [ $smtp_server->to_api ] ); - my $another_smtp_server = - $builder->build_object( { class => 'Koha::SMTP::Servers' } ); + my $another_smtp_server = $builder->build_object( { class => 'Koha::SMTP::Servers' } ); # Two SMTP servers created, they should both be returned - $t->get_ok("//$userid:$password@/api/v1/config/smtp_servers") - ->status_is(200) - ->json_is( [ $smtp_server->to_api, $another_smtp_server->to_api, ] ); + $t->get_ok("//$userid:$password@/api/v1/config/smtp_servers")->status_is(200) + ->json_is( [ $smtp_server->to_api, $another_smtp_server->to_api, ] ); # Unauthorized access - $t->get_ok("//$unauth_userid:$password@/api/v1/config/smtp_servers") - ->status_is(403); + $t->get_ok("//$unauth_userid:$password@/api/v1/config/smtp_servers")->status_is(403); $schema->storage->txn_rollback; }; @@ -93,9 +87,8 @@ subtest 'get() tests' => sub { $schema->storage->txn_begin; - my $smtp_server = - $builder->build_object( { class => 'Koha::SMTP::Servers' } ); - my $librarian = $builder->build_object( + my $smtp_server = $builder->build_object( { class => 'Koha::SMTP::Servers' } ); + my $librarian = $builder->build_object( { class => 'Koha::Patrons', value => { flags => 3**2 } # parameters flag = 3 @@ -115,21 +108,17 @@ subtest 'get() tests' => sub { $patron->set_password( { password => $password, skip_validation => 1 } ); my $unauth_userid = $patron->userid; - $t->get_ok( - "//$userid:$password@/api/v1/config/smtp_servers/" . $smtp_server->id ) - ->status_is(200)->json_is( $smtp_server->to_api ); + $t->get_ok( "//$userid:$password@/api/v1/config/smtp_servers/" . $smtp_server->id )->status_is(200) + ->json_is( $smtp_server->to_api ); - $t->get_ok( "//$unauth_userid:$password@/api/v1/config/smtp_servers/" - . $smtp_server->id )->status_is(403); + $t->get_ok( "//$unauth_userid:$password@/api/v1/config/smtp_servers/" . $smtp_server->id )->status_is(403); - my $smtp_server_to_delete = - $builder->build_object( { class => 'Koha::SMTP::Servers' } ); - my $non_existent_id = $smtp_server_to_delete->id; + my $smtp_server_to_delete = $builder->build_object( { class => 'Koha::SMTP::Servers' } ); + my $non_existent_id = $smtp_server_to_delete->id; $smtp_server_to_delete->delete; - $t->get_ok( - "//$userid:$password@/api/v1/config/smtp_servers/$non_existent_id") - ->status_is(404)->json_is( '/error' => 'SMTP server not found' ); + $t->get_ok("//$userid:$password@/api/v1/config/smtp_servers/$non_existent_id")->status_is(404) + ->json_is( '/error' => 'SMTP server not found' ); $schema->storage->txn_rollback; }; @@ -162,16 +151,14 @@ subtest 'add() tests' => sub { $patron->set_password( { password => $password, skip_validation => 1 } ); my $unauth_userid = $patron->userid; - my $smtp_server = - $builder->build_object( { class => 'Koha::SMTP::Servers' } ); + my $smtp_server = $builder->build_object( { class => 'Koha::SMTP::Servers' } ); my $smtp_server_data = $smtp_server->to_api; delete $smtp_server_data->{smtp_server_id}; $smtp_server->delete; # Unauthorized attempt to write - $t->post_ok( - "//$unauth_userid:$password@/api/v1/config/smtp_servers" => json => - $smtp_server_data )->status_is(403); + $t->post_ok( "//$unauth_userid:$password@/api/v1/config/smtp_servers" => json => $smtp_server_data ) + ->status_is(403); # Authorized attempt to write invalid data my $smtp_server_with_invalid_field = { @@ -179,44 +166,42 @@ subtest 'add() tests' => sub { blah => 'blah' }; - $t->post_ok( "//$userid:$password@/api/v1/config/smtp_servers" => json => - $smtp_server_with_invalid_field )->status_is(400)->json_is( + $t->post_ok( "//$userid:$password@/api/v1/config/smtp_servers" => json => $smtp_server_with_invalid_field ) + ->status_is(400)->json_is( "/errors" => [ { message => "Properties not allowed: blah.", path => "/body" } ] - ); + ); # Authorized attempt to write my $smtp_server_id = - $t->post_ok( "//$userid:$password@/api/v1/config/smtp_servers" => json => - $smtp_server_data )->status_is( 201, 'REST3.2.1' )->header_like( + $t->post_ok( "//$userid:$password@/api/v1/config/smtp_servers" => json => $smtp_server_data ) + ->status_is( 201, 'REST3.2.1' )->header_like( Location => qr|^\/api\/v1\/config\/smtp_servers\/\d*|, 'REST3.4.1' - )->json_is( '/name' => $smtp_server_data->{name} ) - ->json_is( '/state' => $smtp_server_data->{state} ) - ->json_is( '/postal_code' => $smtp_server_data->{postal_code} ) - ->json_is( '/country' => $smtp_server_data->{country} ) - ->tx->res->json->{smtp_server_id}; + )->json_is( '/name' => $smtp_server_data->{name} )->json_is( '/state' => $smtp_server_data->{state} ) + ->json_is( '/postal_code' => $smtp_server_data->{postal_code} ) + ->json_is( '/country' => $smtp_server_data->{country} )->tx->res->json->{smtp_server_id}; # Authorized attempt to create with null id $smtp_server_data->{smtp_server_id} = undef; - $t->post_ok( "//$userid:$password@/api/v1/config/smtp_servers" => json => - $smtp_server_data )->status_is(400)->json_has('/errors'); + $t->post_ok( "//$userid:$password@/api/v1/config/smtp_servers" => json => $smtp_server_data )->status_is(400) + ->json_has('/errors'); # Authorized attempt to create with existing id $smtp_server_data->{smtp_server_id} = $smtp_server_id; - $t->post_ok( "//$userid:$password@/api/v1/config/smtp_servers" => json => - $smtp_server_data )->status_is(400)->json_is( + $t->post_ok( "//$userid:$password@/api/v1/config/smtp_servers" => json => $smtp_server_data )->status_is(400) + ->json_is( "/errors" => [ { message => "Read-only.", path => "/body/smtp_server_id" } ] - ); + ); $schema->storage->txn_rollback; }; @@ -247,14 +232,11 @@ subtest 'update() tests' => sub { $patron->set_password( { password => $password, skip_validation => 1 } ); my $unauth_userid = $patron->userid; - my $smtp_server_id = - $builder->build_object( { class => 'Koha::SMTP::Servers' } )->id; + my $smtp_server_id = $builder->build_object( { class => 'Koha::SMTP::Servers' } )->id; # Unauthorized attempt to update - $t->put_ok( - "//$unauth_userid:$password@/api/v1/config/smtp_servers/$smtp_server_id" - => json => { name => 'New unauthorized name change' } ) - ->status_is(403); + $t->put_ok( "//$unauth_userid:$password@/api/v1/config/smtp_servers/$smtp_server_id" => json => + { name => 'New unauthorized name change' } )->status_is(403); # Attempt partial update on a PUT my $smtp_server_with_missing_field = { @@ -263,18 +245,15 @@ subtest 'update() tests' => sub { }; $t->put_ok( - "//$userid:$password@/api/v1/config/smtp_servers/$smtp_server_id" => - json => $smtp_server_with_missing_field )->status_is(400) - ->json_is( "/errors" => - [ { message => "Missing property.", path => "/body/name" } ] ); + "//$userid:$password@/api/v1/config/smtp_servers/$smtp_server_id" => json => $smtp_server_with_missing_field ) + ->status_is(400)->json_is( "/errors" => [ { message => "Missing property.", path => "/body/name" } ] ); # Full object update on PUT my $smtp_server_with_updated_field = { name => "Some name", }; $t->put_ok( - "//$userid:$password@/api/v1/config/smtp_servers/$smtp_server_id" => - json => $smtp_server_with_updated_field )->status_is(200) - ->json_is( '/name' => 'Some name' ); + "//$userid:$password@/api/v1/config/smtp_servers/$smtp_server_id" => json => $smtp_server_with_updated_field ) + ->status_is(200)->json_is( '/name' => 'Some name' ); # Authorized attempt to write invalid data my $smtp_server_with_invalid_field = { @@ -283,31 +262,30 @@ subtest 'update() tests' => sub { }; $t->put_ok( - "//$userid:$password@/api/v1/config/smtp_servers/$smtp_server_id" => - json => $smtp_server_with_invalid_field )->status_is(400)->json_is( + "//$userid:$password@/api/v1/config/smtp_servers/$smtp_server_id" => json => $smtp_server_with_invalid_field ) + ->status_is(400)->json_is( "/errors" => [ { message => "Properties not allowed: blah.", path => "/body" } ] - ); + ); - my $smtp_server_to_delete = - $builder->build_object( { class => 'Koha::SMTP::Servers' } ); - my $non_existent_id = $smtp_server_to_delete->id; + my $smtp_server_to_delete = $builder->build_object( { class => 'Koha::SMTP::Servers' } ); + my $non_existent_id = $smtp_server_to_delete->id; $smtp_server_to_delete->delete; $t->put_ok( - "//$userid:$password@/api/v1/config/smtp_servers/$non_existent_id" => - json => $smtp_server_with_updated_field )->status_is(404); + "//$userid:$password@/api/v1/config/smtp_servers/$non_existent_id" => json => $smtp_server_with_updated_field ) + ->status_is(404); # Wrong method (POST) $smtp_server_with_updated_field->{smtp_server_id} = 2; $t->post_ok( - "//$userid:$password@/api/v1/config/smtp_servers/$smtp_server_id" => - json => $smtp_server_with_updated_field )->status_is(404); + "//$userid:$password@/api/v1/config/smtp_servers/$smtp_server_id" => json => $smtp_server_with_updated_field ) + ->status_is(404); $schema->storage->txn_rollback; }; @@ -338,21 +316,15 @@ subtest 'delete() tests' => sub { $patron->set_password( { password => $password, skip_validation => 1 } ); my $unauth_userid = $patron->userid; - my $smtp_server_id = - $builder->build_object( { class => 'Koha::SMTP::Servers' } )->id; + my $smtp_server_id = $builder->build_object( { class => 'Koha::SMTP::Servers' } )->id; # Unauthorized attempt to delete - $t->delete_ok( - "//$unauth_userid:$password@/api/v1/config/smtp_servers/$smtp_server_id" - )->status_is(403); + $t->delete_ok("//$unauth_userid:$password@/api/v1/config/smtp_servers/$smtp_server_id")->status_is(403); - $t->delete_ok( - "//$userid:$password@/api/v1/config/smtp_servers/$smtp_server_id") - ->status_is( 204, 'REST3.2.4' )->content_is( '', 'REST3.3.4' ); + $t->delete_ok("//$userid:$password@/api/v1/config/smtp_servers/$smtp_server_id")->status_is( 204, 'REST3.2.4' ) + ->content_is( '', 'REST3.3.4' ); - $t->delete_ok( - "//$userid:$password@/api/v1/config/smtp_servers/$smtp_server_id") - ->status_is(404); + $t->delete_ok("//$userid:$password@/api/v1/config/smtp_servers/$smtp_server_id")->status_is(404); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/api/v1/stockrotationstage.t b/t/db_dependent/api/v1/stockrotationstage.t index 0281470a1b..5b5e8eedaf 100755 --- a/t/db_dependent/api/v1/stockrotationstage.t +++ b/t/db_dependent/api/v1/stockrotationstage.t @@ -38,75 +38,73 @@ subtest 'move() tests' => sub { $schema->storage->txn_begin; - my $authorized_patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 2 ** 24 } # stockrotation => 24 - }); + my $authorized_patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 2**24 } # stockrotation => 24 + } + ); my $password = 'thePassword123'; - $authorized_patron->set_password({ password => $password, skip_validation => 1 }); + $authorized_patron->set_password( { password => $password, skip_validation => 1 } ); my $auth_userid = $authorized_patron->userid; - my $unauthorized_patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 0 } - }); - $unauthorized_patron->set_password({ password => $password, skip_validation => 1 }); + my $unauthorized_patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 0 } + } + ); + $unauthorized_patron->set_password( { password => $password, skip_validation => 1 } ); my $unauth_userid = $unauthorized_patron->userid; - my $library1 = $builder->build({ source => 'Branch' }); - my $library2 = $builder->build({ source => 'Branch' }); - my $rota = $builder->build({ source => 'Stockrotationrota' }); - my $stage1 = $builder->build({ - source => 'Stockrotationstage', - value => { - branchcode_id => $library1->{branchcode}, - rota_id => $rota->{rota_id}, + my $library1 = $builder->build( { source => 'Branch' } ); + my $library2 = $builder->build( { source => 'Branch' } ); + my $rota = $builder->build( { source => 'Stockrotationrota' } ); + my $stage1 = $builder->build( + { + source => 'Stockrotationstage', + value => { + branchcode_id => $library1->{branchcode}, + rota_id => $rota->{rota_id}, + } } - }); - my $stage2 = $builder->build({ - source => 'Stockrotationstage', - value => { - branchcode_id => $library2->{branchcode}, - rota_id => $rota->{rota_id}, + ); + my $stage2 = $builder->build( + { + source => 'Stockrotationstage', + value => { + branchcode_id => $library2->{branchcode}, + rota_id => $rota->{rota_id}, + } } - }); - my $rota_id = $rota->{rota_id}; + ); + my $rota_id = $rota->{rota_id}; my $stage1_id = $stage1->{stage_id}; # Unauthorized attempt to update - $t->put_ok( "//$unauth_userid:$password@/api/v1/rotas/$rota_id/stages/$stage1_id/position" - => json => 2 ) - ->status_is(403); + $t->put_ok( "//$unauth_userid:$password@/api/v1/rotas/$rota_id/stages/$stage1_id/position" => json => 2 ) + ->status_is(403); # Invalid attempt to move a stage on a non-existant rota - $t->put_ok( "//$auth_userid:$password@/api/v1/rotas/99999999/stages/$stage1_id/position" - => json => 2 ) - ->status_is(404) - ->json_is( '/error' => "Rota not found" ); + $t->put_ok( "//$auth_userid:$password@/api/v1/rotas/99999999/stages/$stage1_id/position" => json => 2 ) + ->status_is(404)->json_is( '/error' => "Rota not found" ); # Invalid attempt to move an non-existant stage - $t->put_ok( "//$auth_userid:$password@/api/v1/rotas/$rota_id/stages/999999999/position" - => json => 2 ) - ->status_is(404) - ->json_is( '/error' => "Stage not found" ); + $t->put_ok( "//$auth_userid:$password@/api/v1/rotas/$rota_id/stages/999999999/position" => json => 2 ) + ->status_is(404)->json_is( '/error' => "Stage not found" ); # Invalid attempt to move stage to current position my $curr_position = $stage1->{position}; - $t->put_ok( "//$auth_userid:$password@/api/v1/rotas/$rota_id/stages/$stage1_id/position" - => json => $curr_position ) - ->status_is(400) - ->json_is( '/error' => "Bad request - new position invalid" ); + $t->put_ok( "//$auth_userid:$password@/api/v1/rotas/$rota_id/stages/$stage1_id/position" => json => $curr_position ) + ->status_is(400)->json_is( '/error' => "Bad request - new position invalid" ); # Invalid attempt to move stage to invalid position - $t->put_ok( "//$auth_userid:$password@/api/v1/rotas/$rota_id/stages/$stage1_id/position" - => json => 99999999 ) - ->status_is(400) - ->json_is( '/error' => "Bad request - new position invalid" ); + $t->put_ok( "//$auth_userid:$password@/api/v1/rotas/$rota_id/stages/$stage1_id/position" => json => 99999999 ) + ->status_is(400)->json_is( '/error' => "Bad request - new position invalid" ); # Valid, authorised move - $t->put_ok( "//$auth_userid:$password@/api/v1/rotas/$rota_id/stages/$stage1_id/position" - => json => 2 ) - ->status_is(200); + $t->put_ok( "//$auth_userid:$password@/api/v1/rotas/$rota_id/stages/$stage1_id/position" => json => 2 ) + ->status_is(200); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/api/v1/suggestions.t b/t/db_dependent/api/v1/suggestions.t index cac5172acb..c373bf8782 100755 --- a/t/db_dependent/api/v1/suggestions.t +++ b/t/db_dependent/api/v1/suggestions.t @@ -41,7 +41,7 @@ subtest 'list() tests' => sub { my $librarian = $builder->build_object( { class => 'Koha::Patrons', - value => { flags => 2 ** 12 } # suggestions flag = 12 + value => { flags => 2**12 } # suggestions flag = 12 } ); my $password = 'thePassword123'; @@ -62,8 +62,8 @@ subtest 'list() tests' => sub { ## Authorized user tests # No suggestions by patron, so empty array should be returned - $t->get_ok("//$userid:$password@/api/v1/suggestions?q={\"suggested_by\":\"$patron_id\"}") - ->status_is(200)->json_is( [] ); + $t->get_ok("//$userid:$password@/api/v1/suggestions?q={\"suggested_by\":\"$patron_id\"}")->status_is(200) + ->json_is( [] ); my $suggestion_1 = $builder->build_object( { @@ -73,8 +73,8 @@ subtest 'list() tests' => sub { ); # One suggestion created, should get returned - $t->get_ok("//$userid:$password@/api/v1/suggestions?q={\"suggested_by\":\"$patron_id\"}") - ->status_is(200)->json_is( [ $suggestion_1->to_api ] ); + $t->get_ok("//$userid:$password@/api/v1/suggestions?q={\"suggested_by\":\"$patron_id\"}")->status_is(200) + ->json_is( [ $suggestion_1->to_api ] ); my $suggestion_2 = $builder->build_object( { @@ -84,13 +84,11 @@ subtest 'list() tests' => sub { ); # Two SMTP servers created, they should both be returned - $t->get_ok("//$userid:$password@/api/v1/suggestions?q={\"suggested_by\":\"$patron_id\"}") - ->status_is(200) - ->json_is( [ $suggestion_1->to_api, $suggestion_2->to_api, ] ); + $t->get_ok("//$userid:$password@/api/v1/suggestions?q={\"suggested_by\":\"$patron_id\"}")->status_is(200) + ->json_is( [ $suggestion_1->to_api, $suggestion_2->to_api, ] ); # Unauthorized access - $t->get_ok("//$unauth_userid:$password@/api/v1/suggestions") - ->status_is(403); + $t->get_ok("//$unauth_userid:$password@/api/v1/suggestions")->status_is(403); $schema->storage->txn_rollback; }; @@ -101,10 +99,10 @@ subtest 'get() tests' => sub { $schema->storage->txn_begin; - my $librarian = $builder->build_object( + my $librarian = $builder->build_object( { class => 'Koha::Patrons', - value => { flags => 2 ** 12 } # suggestions flag = 12 + value => { flags => 2**12 } # suggestions flag = 12 } ); my $password = 'thePassword123'; @@ -120,7 +118,7 @@ subtest 'get() tests' => sub { $patron->set_password( { password => $password, skip_validation => 1 } ); my $unauth_userid = $patron->userid; - my $patron_id = $patron->id; + my $patron_id = $patron->id; my $suggestion = $builder->build_object( { @@ -129,9 +127,8 @@ subtest 'get() tests' => sub { } ); - $t->get_ok( - "//$userid:$password@/api/v1/suggestions/" . $suggestion->id ) - ->status_is(200)->json_is( $suggestion->to_api ); + $t->get_ok( "//$userid:$password@/api/v1/suggestions/" . $suggestion->id )->status_is(200) + ->json_is( $suggestion->to_api ); my $authorised_value = Koha::AuthorisedValue->new( { @@ -144,16 +141,14 @@ subtest 'get() tests' => sub { $t->get_ok( "//$userid:$password@/api/v1/suggestions/" . $suggestion->id )->status_is(200) ->json_is( $suggestion->to_api ); - $t->get_ok( "//$unauth_userid:$password@/api/v1/suggestions/" - . $suggestion->id )->status_is(403); + $t->get_ok( "//$unauth_userid:$password@/api/v1/suggestions/" . $suggestion->id )->status_is(403); my $suggestion_to_delete = $builder->build_object( { class => 'Koha::Suggestions' } ); - my $non_existent_id = $suggestion_to_delete->id; + my $non_existent_id = $suggestion_to_delete->id; $suggestion_to_delete->delete; - $t->get_ok( - "//$userid:$password@/api/v1/suggestions/$non_existent_id") - ->status_is(404)->json_is( '/error' => 'Suggestion not found' ); + $t->get_ok("//$userid:$password@/api/v1/suggestions/$non_existent_id")->status_is(404) + ->json_is( '/error' => 'Suggestion not found' ); $schema->storage->txn_rollback; }; @@ -167,7 +162,7 @@ subtest 'add() tests' => sub { my $librarian = $builder->build_object( { class => 'Koha::Patrons', - value => { flags => 2 ** 12 } # suggestions flag = 12 + value => { flags => 2**12 } # suggestions flag = 12 } ); my $password = 'thePassword123'; @@ -197,29 +192,25 @@ subtest 'add() tests' => sub { $suggestion->delete; # Unauthorized attempt to write - $t->post_ok( - "//$unauth_userid:$password@/api/v1/suggestions" => json => - $suggestion_data )->status_is(403); + $t->post_ok( "//$unauth_userid:$password@/api/v1/suggestions" => json => $suggestion_data )->status_is(403); # Authorized attempt to write invalid data - my $suggestion_with_invalid_field = { - blah => 'blah' - }; + my $suggestion_with_invalid_field = { blah => 'blah' }; - $t->post_ok( "//$userid:$password@/api/v1/suggestions" => json => - $suggestion_with_invalid_field )->status_is(400)->json_is( + $t->post_ok( "//$userid:$password@/api/v1/suggestions" => json => $suggestion_with_invalid_field )->status_is(400) + ->json_is( "/errors" => [ { message => "Properties not allowed: blah.", path => "/body" } ] - ); + ); # Authorized attempt to write my $generated_suggestion = - $t->post_ok( "//$userid:$password@/api/v1/suggestions" => json => - $suggestion_data )->status_is( 201, 'REST3.2.1' )->header_like( + $t->post_ok( "//$userid:$password@/api/v1/suggestions" => json => $suggestion_data ) + ->status_is( 201, 'REST3.2.1' )->header_like( Location => qr|^\/api\/v1\/suggestions\/\d*|, 'REST3.4.1' )->tx->res->json; @@ -233,20 +224,19 @@ subtest 'add() tests' => sub { # Authorized attempt to create with null id $suggestion_data->{suggestion_id} = undef; - $t->post_ok( "//$userid:$password@/api/v1/suggestions" => json => - $suggestion_data )->status_is(400)->json_has('/errors'); + $t->post_ok( "//$userid:$password@/api/v1/suggestions" => json => $suggestion_data )->status_is(400) + ->json_has('/errors'); # Authorized attempt to create with existing id $suggestion_data->{suggestion_id} = $suggestion_id; - $t->post_ok( "//$userid:$password@/api/v1/suggestions" => json => - $suggestion_data )->status_is(400)->json_is( + $t->post_ok( "//$userid:$password@/api/v1/suggestions" => json => $suggestion_data )->status_is(400)->json_is( "/errors" => [ { message => "Read-only.", path => "/body/suggestion_id" } ] - ); + ); subtest 'x-koha-override tests' => sub { @@ -259,7 +249,8 @@ subtest 'add() tests' => sub { t::lib::Mocks::mock_preference( 'NumberOfSuggestionDays', 2 ); my $suggestion = $builder->build_object( - { class => 'Koha::Suggestions', + { + class => 'Koha::Suggestions', value => { suggestedby => $patron->id, STATUS => 'ACCEPTED' } } ); @@ -269,27 +260,23 @@ subtest 'add() tests' => sub { delete $suggestion_data->{status}; $t->post_ok( "//$userid:$password@/api/v1/suggestions" => json => $suggestion_data ) - ->status_is( 201, 'First pending suggestion' ); + ->status_is( 201, 'First pending suggestion' ); $t->post_ok( "//$userid:$password@/api/v1/suggestions" => json => $suggestion_data ) - ->status_is( 201, 'Second pending suggestion' ); + ->status_is( 201, 'Second pending suggestion' ); - $t->post_ok( "//$userid:$password@/api/v1/suggestions" => json => $suggestion_data ) - ->status_is(400) - ->json_is( '/error_code' => 'max_pending_reached' ); + $t->post_ok( "//$userid:$password@/api/v1/suggestions" => json => $suggestion_data )->status_is(400) + ->json_is( '/error_code' => 'max_pending_reached' ); - $t->post_ok( "//$userid:$password@/api/v1/suggestions" - => { 'x-koha-override' => 'max_pending' } - => json => $suggestion_data ) - ->status_is( 201, 'max_pending override does the job' ); + $t->post_ok( "//$userid:$password@/api/v1/suggestions" => { 'x-koha-override' => 'max_pending' } => json => + $suggestion_data )->status_is( 201, 'max_pending override does the job' ); - $t->post_ok( "//$userid:$password@/api/v1/suggestions" => json => $suggestion_data ) - ->status_is(400) - ->json_is( '/error_code' => 'max_total_reached' ); + $t->post_ok( "//$userid:$password@/api/v1/suggestions" => json => $suggestion_data )->status_is(400) + ->json_is( '/error_code' => 'max_total_reached' ); $t->post_ok( "//$userid:$password@/api/v1/suggestions" => { 'x-koha-override' => 'any' } => json => $suggestion_data ) - ->status_is( 201, 'any overrides anything' ); + ->status_is( 201, 'any overrides anything' ); }; $schema->storage->txn_rollback; @@ -304,7 +291,7 @@ subtest 'update() tests' => sub { my $librarian = $builder->build_object( { class => 'Koha::Patrons', - value => { flags => 2 ** 12 } # suggestions flag = 12 + value => { flags => 2**12 } # suggestions flag = 12 } ); my $password = 'thePassword123'; @@ -329,18 +316,14 @@ subtest 'update() tests' => sub { )->id; # Unauthorized attempt to update - $t->put_ok( - "//$unauth_userid:$password@/api/v1/suggestions/$suggestion_id" - => json => { name => 'New unauthorized name change' } ) - ->status_is(403); + $t->put_ok( "//$unauth_userid:$password@/api/v1/suggestions/$suggestion_id" => json => + { name => 'New unauthorized name change' } )->status_is(403); # Full object update on PUT my $suggestion_with_updated_field = { reason => "Some reason", }; - $t->put_ok( - "//$userid:$password@/api/v1/suggestions/$suggestion_id" => - json => $suggestion_with_updated_field )->status_is(200) - ->json_is( '/reason' => 'Some reason' ); + $t->put_ok( "//$userid:$password@/api/v1/suggestions/$suggestion_id" => json => $suggestion_with_updated_field ) + ->status_is(200)->json_is( '/reason' => 'Some reason' ); # Authorized attempt to write invalid data my $suggestion_with_invalid_field = { @@ -348,31 +331,28 @@ subtest 'update() tests' => sub { reason => 'Some reason' }; - $t->put_ok( - "//$userid:$password@/api/v1/suggestions/$suggestion_id" => - json => $suggestion_with_invalid_field )->status_is(400)->json_is( + $t->put_ok( "//$userid:$password@/api/v1/suggestions/$suggestion_id" => json => $suggestion_with_invalid_field ) + ->status_is(400)->json_is( "/errors" => [ { message => "Properties not allowed: blah.", path => "/body" } ] - ); + ); - my $suggestion_to_delete = $builder->build_object({ class => 'Koha::Suggestions' }); - my $non_existent_id = $suggestion_to_delete->id; + my $suggestion_to_delete = $builder->build_object( { class => 'Koha::Suggestions' } ); + my $non_existent_id = $suggestion_to_delete->id; $suggestion_to_delete->delete; - $t->put_ok( - "//$userid:$password@/api/v1/suggestions/$non_existent_id" => - json => $suggestion_with_updated_field )->status_is(404); + $t->put_ok( "//$userid:$password@/api/v1/suggestions/$non_existent_id" => json => $suggestion_with_updated_field ) + ->status_is(404); # Wrong method (POST) $suggestion_with_updated_field->{smtp_server_id} = 2; - $t->post_ok( - "//$userid:$password@/api/v1/suggestions/$suggestion_id" => - json => $suggestion_with_updated_field )->status_is(404); + $t->post_ok( "//$userid:$password@/api/v1/suggestions/$suggestion_id" => json => $suggestion_with_updated_field ) + ->status_is(404); $schema->storage->txn_rollback; }; @@ -386,7 +366,7 @@ subtest 'delete() tests' => sub { my $librarian = $builder->build_object( { class => 'Koha::Patrons', - value => { flags => 2 ** 12 } # suggestions flag = 12 + value => { flags => 2**12 } # suggestions flag = 12 } ); my $password = 'thePassword123'; @@ -403,20 +383,15 @@ subtest 'delete() tests' => sub { $patron->set_password( { password => $password, skip_validation => 1 } ); my $unauth_userid = $patron->userid; - my $suggestion_id = $builder->build_object({ class => 'Koha::Suggestions' } )->id; + my $suggestion_id = $builder->build_object( { class => 'Koha::Suggestions' } )->id; # Unauthorized attempt to delete - $t->delete_ok( - "//$unauth_userid:$password@/api/v1/suggestions/$suggestion_id" - )->status_is(403); + $t->delete_ok("//$unauth_userid:$password@/api/v1/suggestions/$suggestion_id")->status_is(403); - $t->delete_ok( - "//$userid:$password@/api/v1/suggestions/$suggestion_id") - ->status_is( 204, 'REST3.2.4' )->content_is( q{}, 'REST3.3.4' ); + $t->delete_ok("//$userid:$password@/api/v1/suggestions/$suggestion_id")->status_is( 204, 'REST3.2.4' ) + ->content_is( q{}, 'REST3.3.4' ); - $t->delete_ok( - "//$userid:$password@/api/v1/suggestions/$suggestion_id") - ->status_is(404); + $t->delete_ok("//$userid:$password@/api/v1/suggestions/$suggestion_id")->status_is(404); $schema->storage->txn_rollback; }; @@ -456,8 +431,7 @@ subtest 'Permissions tests' => sub { $suggestion->delete; # Unauthorized attempt to write - $t->post_ok( "//$userid:$password@/api/v1/suggestions" => json => $suggestion_data ) - ->status_is( 403, 'REST3.2.1' ); + $t->post_ok( "//$userid:$password@/api/v1/suggestions" => json => $suggestion_data )->status_is( 403, 'REST3.2.1' ); $builder->build( { diff --git a/t/db_dependent/api/v1/ticket_updates.t b/t/db_dependent/api/v1/ticket_updates.t index 5f7c7c0df3..58cdfac7af 100755 --- a/t/db_dependent/api/v1/ticket_updates.t +++ b/t/db_dependent/api/v1/ticket_updates.t @@ -30,7 +30,7 @@ my $schema = Koha::Database->new->schema; my $builder = t::lib::TestBuilder->new; my $t = Test::Mojo->new('Koha::REST::V1'); -t::lib::Mocks::mock_preference( 'RESTBasicAuth', 1 ); +t::lib::Mocks::mock_preference( 'RESTBasicAuth', 1 ); t::lib::Mocks::mock_preference( 'NotifyPasswordChange', 0 ); subtest 'list_updates() tests' => sub { @@ -66,8 +66,7 @@ subtest 'list_updates() tests' => sub { ## Authorized user tests # No updates, so empty array should be returned - $t->get_ok("//$userid:$password@/api/v1/tickets/$ticket_id/updates") - ->status_is(200)->json_is( [] ); + $t->get_ok("//$userid:$password@/api/v1/tickets/$ticket_id/updates")->status_is(200)->json_is( [] ); my $update = $builder->build_object( { @@ -77,8 +76,8 @@ subtest 'list_updates() tests' => sub { ); # One ticket update added, should get returned - $t->get_ok("//$userid:$password@/api/v1/tickets/$ticket_id/updates") - ->status_is(200)->json_is( [ $update->to_api ] ); + $t->get_ok("//$userid:$password@/api/v1/tickets/$ticket_id/updates")->status_is(200) + ->json_is( [ $update->to_api ] ); my $update_2 = $builder->build_object( { @@ -94,14 +93,11 @@ subtest 'list_updates() tests' => sub { ); # Two ticket updates added, they should both be returned - $t->get_ok("//$userid:$password@/api/v1/tickets/$ticket_id/updates") - ->status_is(200) - ->json_is( [ $update->to_api, $update_2->to_api, $update_3->to_api, ] ); + $t->get_ok("//$userid:$password@/api/v1/tickets/$ticket_id/updates")->status_is(200) + ->json_is( [ $update->to_api, $update_2->to_api, $update_3->to_api, ] ); # Warn on unsupported query parameter - $t->get_ok( -"//$userid:$password@/api/v1/tickets/$ticket_id/updates?ticket_blah=blah" - )->status_is(400)->json_is( + $t->get_ok("//$userid:$password@/api/v1/tickets/$ticket_id/updates?ticket_blah=blah")->status_is(400)->json_is( [ { path => '/query/ticket_blah', @@ -161,83 +157,75 @@ subtest 'add_update() tests' => sub { }; # Unauthorized attempt to write - $t->post_ok( - "//$unauth_userid:$password@/api/v1/tickets/$ticket_id/updates" => - json => $update )->status_is(403); + $t->post_ok( "//$unauth_userid:$password@/api/v1/tickets/$ticket_id/updates" => json => $update )->status_is(403); # Authorized attempt to write my $update_id = - $t->post_ok( - "//$userid:$password@/api/v1/tickets/$ticket_id/updates" => json => - $update )->status_is( 201, 'REST3.2.1' )->header_like( + $t->post_ok( "//$userid:$password@/api/v1/tickets/$ticket_id/updates" => json => $update ) + ->status_is( 201, 'REST3.2.1' )->header_like( Location => qr|^\/api\/v1\/tickets/\d*|, 'REST3.4.1' - )->json_is( '/message' => $update->{message} ) - ->json_is( '/public' => $update->{public} ) - ->json_is( '/status' => undef ) - ->json_is( '/assignee_id' => undef ) - ->json_is( '/user_id' => $librarian->id )->tx->res->json->{update_id}; + )->json_is( '/message' => $update->{message} )->json_is( '/public' => $update->{public} ) + ->json_is( '/status' => undef )->json_is( '/assignee_id' => undef )->json_is( '/user_id' => $librarian->id ) + ->tx->res->json->{update_id}; # Check that notice trigger didn't fire for non-public update - my $notices = - Koha::Notice::Messages->search( { borrowernumber => $patron->id } ); - is( $notices->count, 0, - 'No notices queued when the update is marked as not public' ); + my $notices = Koha::Notice::Messages->search( { borrowernumber => $patron->id } ); + is( + $notices->count, 0, + 'No notices queued when the update is marked as not public' + ); # Authorized attempt to create with null id $update->{update_id} = undef; - $t->post_ok( - "//$userid:$password@/api/v1/tickets/$ticket_id/updates" => json => - $update )->status_is(400)->json_has('/errors'); + $t->post_ok( "//$userid:$password@/api/v1/tickets/$ticket_id/updates" => json => $update )->status_is(400) + ->json_has('/errors'); # Authorized attempt to create with existing id $update->{update_id} = $update_id; - $t->post_ok( - "//$userid:$password@/api/v1/tickets/$ticket_id/updates" => json => - $update )->status_is(400)->json_is( + $t->post_ok( "//$userid:$password@/api/v1/tickets/$ticket_id/updates" => json => $update )->status_is(400) + ->json_is( "/errors" => [ { message => "Read-only.", path => "/body/update_id" } ] - ); + ); delete $update->{update_id}; # Authorized attempt to write missing data my $update_with_missing_field = { message => "Another ticket update" }; - $t->post_ok( - "//$userid:$password@/api/v1/tickets/$ticket_id/updates" => json => - $update_with_missing_field )->status_is(400)->json_is( + $t->post_ok( "//$userid:$password@/api/v1/tickets/$ticket_id/updates" => json => $update_with_missing_field ) + ->status_is(400)->json_is( "/errors" => [ { message => "Missing property.", path => "/body/public" } ] - ); + ); # Check that notice trigger fired for public update $update->{public} = Mojo::JSON->true; $update_id = - $t->post_ok( - "//$userid:$password@/api/v1/tickets/$ticket_id/updates" => json => - $update )->status_is( 201, 'REST3.2.1' )->header_like( + $t->post_ok( "//$userid:$password@/api/v1/tickets/$ticket_id/updates" => json => $update ) + ->status_is( 201, 'REST3.2.1' )->header_like( Location => qr|^\/api\/v1\/tickets/\d*|, 'REST3.4.1' - )->json_is( '/message' => $update->{message} ) - ->json_is( '/public' => $update->{public} ) - ->json_is( '/status' => undef ) - ->json_is( '/assignee_id' => undef ) - ->json_is( '/user_id' => $librarian->id )->tx->res->json->{update_id}; + )->json_is( '/message' => $update->{message} )->json_is( '/public' => $update->{public} ) + ->json_is( '/status' => undef )->json_is( '/assignee_id' => undef )->json_is( '/user_id' => $librarian->id ) + ->tx->res->json->{update_id}; - $notices = - Koha::Notice::Messages->search( { borrowernumber => $patron->id } ); - is( $notices->count, 1, - 'One notice queued when the update is marked as public' ); + $notices = Koha::Notice::Messages->search( { borrowernumber => $patron->id } ); + is( + $notices->count, 1, + 'One notice queued when the update is marked as public' + ); my $THE_notice = $notices->next; - is( $THE_notice->letter_code, 'TICKET_UPDATE', + is( + $THE_notice->letter_code, 'TICKET_UPDATE', 'Notice queued was a TICKET_UPDATE for non-status changing update' ); $THE_notice->delete; @@ -245,23 +233,22 @@ subtest 'add_update() tests' => sub { # Check that state change triggers correct notice $update->{state} = 'resolved'; $update_id = - $t->post_ok( - "//$userid:$password@/api/v1/tickets/$ticket_id/updates" => json => - $update )->status_is( 201, 'REST3.2.1' )->header_like( + $t->post_ok( "//$userid:$password@/api/v1/tickets/$ticket_id/updates" => json => $update ) + ->status_is( 201, 'REST3.2.1' )->header_like( Location => qr|^\/api\/v1\/tickets/\d*|, 'REST3.4.1' - )->json_is( '/message' => $update->{message} ) - ->json_is( '/public' => $update->{public} ) - ->json_is( '/status' => undef ) - ->json_is( '/assignee_id' => undef ) - ->json_is( '/user_id' => $librarian->id )->tx->res->json->{update_id}; + )->json_is( '/message' => $update->{message} )->json_is( '/public' => $update->{public} ) + ->json_is( '/status' => undef )->json_is( '/assignee_id' => undef )->json_is( '/user_id' => $librarian->id ) + ->tx->res->json->{update_id}; - $notices = - Koha::Notice::Messages->search( { borrowernumber => $patron->id } ); - is( $notices->count, 1, - 'One notice queued when the update is marked as public' ); + $notices = Koha::Notice::Messages->search( { borrowernumber => $patron->id } ); + is( + $notices->count, 1, + 'One notice queued when the update is marked as public' + ); $THE_notice = $notices->next; - is( $THE_notice->letter_code, 'TICKET_RESOLVE', + is( + $THE_notice->letter_code, 'TICKET_RESOLVE', 'Notice queued was a TICKET_RESOLVED for status changing update' ); @@ -274,21 +261,18 @@ subtest 'add_update() tests' => sub { isnt( $ticket->resolved_date, undef, "Ticket was given resolved_date when state was updated to 'resolved'" ); $update->{public} = Mojo::JSON->false; - $update->{state} = undef; + $update->{state} = undef; # Check that status change is carried over to ticket $update->{status} = 'TEST'; $update_id = - $t->post_ok( - "//$userid:$password@/api/v1/tickets/$ticket_id/updates" => json => - $update )->status_is( 201, 'REST3.2.1' )->header_like( + $t->post_ok( "//$userid:$password@/api/v1/tickets/$ticket_id/updates" => json => $update ) + ->status_is( 201, 'REST3.2.1' )->header_like( Location => qr|^\/api\/v1\/tickets/\d*|, 'REST3.4.1' - )->json_is( '/message' => $update->{message} ) - ->json_is( '/public' => $update->{public} ) - ->json_is( '/status' => $update->{status} ) - ->json_is( '/assignee_id' => undef ) - ->json_is( '/user_id' => $librarian->id )->tx->res->json->{update_id}; + )->json_is( '/message' => $update->{message} )->json_is( '/public' => $update->{public} ) + ->json_is( '/status' => $update->{status} )->json_is( '/assignee_id' => undef ) + ->json_is( '/user_id' => $librarian->id )->tx->res->json->{update_id}; $ticket = $ticket->get_from_storage; is( @@ -301,16 +285,13 @@ subtest 'add_update() tests' => sub { # Check that assignee is carried over to ticket $update->{assignee_id} = $librarian->id; $update_id = - $t->post_ok( - "//$userid:$password@/api/v1/tickets/$ticket_id/updates" => json => - $update )->status_is( 201, 'REST3.2.1' )->header_like( + $t->post_ok( "//$userid:$password@/api/v1/tickets/$ticket_id/updates" => json => $update ) + ->status_is( 201, 'REST3.2.1' )->header_like( Location => qr|^\/api\/v1\/tickets/\d*|, 'REST3.4.1' - )->json_is( '/message' => $update->{message} ) - ->json_is( '/public' => $update->{public} ) - ->json_is( '/status' => $update->{status} ) - ->json_is( '/assignee_id' => $update->{assignee_id} ) - ->json_is( '/user_id' => $librarian->id )->tx->res->json->{update_id}; + )->json_is( '/message' => $update->{message} )->json_is( '/public' => $update->{public} ) + ->json_is( '/status' => $update->{status} )->json_is( '/assignee_id' => $update->{assignee_id} ) + ->json_is( '/user_id' => $librarian->id )->tx->res->json->{update_id}; $ticket = $ticket->get_from_storage; is( diff --git a/t/db_dependent/api/v1/tickets.t b/t/db_dependent/api/v1/tickets.t index 2519256d91..51d7dd5cc2 100755 --- a/t/db_dependent/api/v1/tickets.t +++ b/t/db_dependent/api/v1/tickets.t @@ -62,18 +62,15 @@ subtest 'list() tests' => sub { ## Authorized user tests # No tickets, so empty array should be returned - $t->get_ok("//$userid:$password@/api/v1/tickets")->status_is(200) - ->json_is( [] ); + $t->get_ok("//$userid:$password@/api/v1/tickets")->status_is(200)->json_is( [] ); my $ticket = $builder->build_object( { class => 'Koha::Tickets' } ); # One ticket created, should get returned - $t->get_ok("//$userid:$password@/api/v1/tickets")->status_is(200) - ->json_is( [ $ticket->to_api ] ); + $t->get_ok("//$userid:$password@/api/v1/tickets")->status_is(200)->json_is( [ $ticket->to_api ] ); - my $another_ticket = $builder->build_object( { class => 'Koha::Tickets' } ); - my $and_another_ticket = - $builder->build_object( { class => 'Koha::Tickets' } ); + my $another_ticket = $builder->build_object( { class => 'Koha::Tickets' } ); + my $and_another_ticket = $builder->build_object( { class => 'Koha::Tickets' } ); # Two tickets created, they should both be returned $t->get_ok("//$userid:$password@/api/v1/tickets")->status_is(200)->json_is( @@ -84,15 +81,14 @@ subtest 'list() tests' => sub { ); # Warn on unsupported query parameter - $t->get_ok("//$userid:$password@/api/v1/tickets?ticket_blah=blah") - ->status_is(400)->json_is( + $t->get_ok("//$userid:$password@/api/v1/tickets?ticket_blah=blah")->status_is(400)->json_is( [ { path => '/query/ticket_blah', message => 'Malformed query string' } ] - ); + ); # Unauthorized access $t->get_ok("//$unauth_userid:$password@/api/v1/tickets")->status_is(403); @@ -127,19 +123,16 @@ subtest 'get() tests' => sub { $patron->set_password( { password => $password, skip_validation => 1 } ); my $unauth_userid = $patron->userid; - $t->get_ok( "//$userid:$password@/api/v1/tickets/" . $ticket->id ) - ->status_is(200)->json_is( $ticket->to_api ); + $t->get_ok( "//$userid:$password@/api/v1/tickets/" . $ticket->id )->status_is(200)->json_is( $ticket->to_api ); - $t->get_ok( "//$unauth_userid:$password@/api/v1/tickets/" . $ticket->id ) - ->status_is(403); + $t->get_ok( "//$unauth_userid:$password@/api/v1/tickets/" . $ticket->id )->status_is(403); - my $ticket_to_delete = - $builder->build_object( { class => 'Koha::Tickets' } ); - my $non_existent_id = $ticket_to_delete->id; + my $ticket_to_delete = $builder->build_object( { class => 'Koha::Tickets' } ); + my $non_existent_id = $ticket_to_delete->id; $ticket_to_delete->delete; - $t->get_ok("//$userid:$password@/api/v1/tickets/$non_existent_id") - ->status_is(404)->json_is( '/error' => 'Ticket not found' ); + $t->get_ok("//$userid:$password@/api/v1/tickets/$non_existent_id")->status_is(404) + ->json_is( '/error' => 'Ticket not found' ); $schema->storage->txn_rollback; }; @@ -179,9 +172,7 @@ subtest 'add() tests' => sub { }; # Unauthorized attempt to write - $t->post_ok( - "//$unauth_userid:$password@/api/v1/tickets" => json => $ticket ) - ->status_is(403); + $t->post_ok( "//$unauth_userid:$password@/api/v1/tickets" => json => $ticket )->status_is(403); # Authorized attempt to write invalid data my $ticket_with_invalid_field = { @@ -192,43 +183,40 @@ subtest 'add() tests' => sub { body => "Test ticket details", }; - $t->post_ok( "//$userid:$password@/api/v1/tickets" => json => - $ticket_with_invalid_field )->status_is(400)->json_is( + $t->post_ok( "//$userid:$password@/api/v1/tickets" => json => $ticket_with_invalid_field )->status_is(400) + ->json_is( "/errors" => [ { message => "Properties not allowed: blah.", path => "/body" } ] - ); + ); # Authorized attempt to write my $ticket_id = - $t->post_ok( "//$userid:$password@/api/v1/tickets" => json => $ticket ) - ->status_is( 201, 'REST3.2.1' )->header_like( + $t->post_ok( "//$userid:$password@/api/v1/tickets" => json => $ticket )->status_is( 201, 'REST3.2.1' ) + ->header_like( Location => qr|^\/api\/v1\/tickets/\d*|, 'REST3.4.1' - )->json_is( '/biblio_id' => $ticket->{biblio_id} ) - ->json_is( '/title' => $ticket->{title} ) - ->json_is( '/body' => $ticket->{body} ) - ->json_is( '/reporter_id' => $librarian->id )->tx->res->json->{ticket_id}; + )->json_is( '/biblio_id' => $ticket->{biblio_id} )->json_is( '/title' => $ticket->{title} ) + ->json_is( '/body' => $ticket->{body} )->json_is( '/reporter_id' => $librarian->id ) + ->tx->res->json->{ticket_id}; # Authorized attempt to create with null id $ticket->{ticket_id} = undef; - $t->post_ok( "//$userid:$password@/api/v1/tickets" => json => $ticket ) - ->status_is(400)->json_has('/errors'); + $t->post_ok( "//$userid:$password@/api/v1/tickets" => json => $ticket )->status_is(400)->json_has('/errors'); # Authorized attempt to create with existing id $ticket->{ticket_id} = $ticket_id; - $t->post_ok( "//$userid:$password@/api/v1/tickets" => json => $ticket ) - ->status_is(400)->json_is( + $t->post_ok( "//$userid:$password@/api/v1/tickets" => json => $ticket )->status_is(400)->json_is( "/errors" => [ { message => "Read-only.", path => "/body/ticket_id" } ] - ); + ); # Authorized attempt to write missing data my $ticket_with_missing_field = { @@ -237,15 +225,15 @@ subtest 'add() tests' => sub { body => "Test ticket details", }; - $t->post_ok( "//$userid:$password@/api/v1/tickets" => json => - $ticket_with_missing_field )->status_is(400)->json_is( + $t->post_ok( "//$userid:$password@/api/v1/tickets" => json => $ticket_with_missing_field )->status_is(400) + ->json_is( "/errors" => [ { message => "Missing property.", path => "/body/title" } ] - ); + ); subtest 'public add' => sub { plan tests => 7; @@ -295,13 +283,13 @@ subtest 'update() tests' => sub { $patron->set_password( { password => $password, skip_validation => 1 } ); my $unauth_userid = $patron->userid; - my $ticket = $builder->build_object( { class => 'Koha::Tickets' } ); + my $ticket = $builder->build_object( { class => 'Koha::Tickets' } ); my $ticket_id = $ticket->id; # Unauthorized attempt to update $t->put_ok( - "//$unauth_userid:$password@/api/v1/tickets/$ticket_id" => json => - { name => 'New unauthorized name change' } )->status_is(403); + "//$unauth_userid:$password@/api/v1/tickets/$ticket_id" => json => { name => 'New unauthorized name change' } ) + ->status_is(403); # Attempt partial update on a PUT my $ticket_with_missing_field = { @@ -309,10 +297,8 @@ subtest 'update() tests' => sub { body => "Test ticket details", }; - $t->put_ok( "//$userid:$password@/api/v1/tickets/$ticket_id" => json => - $ticket_with_missing_field )->status_is(400) - ->json_is( "/errors" => - [ { message => "Missing property.", path => "/body/title" } ] ); + $t->put_ok( "//$userid:$password@/api/v1/tickets/$ticket_id" => json => $ticket_with_missing_field ) + ->status_is(400)->json_is( "/errors" => [ { message => "Missing property.", path => "/body/title" } ] ); # Full object update on PUT my $ticket_with_updated_field = { @@ -321,16 +307,13 @@ subtest 'update() tests' => sub { body => "Test ticket update details", }; - $t->put_ok( "//$userid:$password@/api/v1/tickets/$ticket_id" => json => - $ticket_with_updated_field )->status_is(200) - ->json_is( '/title' => 'Test ticket update' ); + $t->put_ok( "//$userid:$password@/api/v1/tickets/$ticket_id" => json => $ticket_with_updated_field ) + ->status_is(200)->json_is( '/title' => 'Test ticket update' ); # Set the assignee on PUT $ticket_with_updated_field->{assignee_id} = $librarian->id; - $t->put_ok( "//$userid:$password@/api/v1/tickets/$ticket_id" => json => - $ticket_with_updated_field )->status_is(200) - ->json_is( '/title' => 'Test ticket update' ) - ->json_is( '/assignee_id' => $librarian->id ); + $t->put_ok( "//$userid:$password@/api/v1/tickets/$ticket_id" => json => $ticket_with_updated_field ) + ->status_is(200)->json_is( '/title' => 'Test ticket update' )->json_is( '/assignee_id' => $librarian->id ); my $updates = $ticket->updates; is( $updates->count, 1, "Ticket update added for assignee change" ); @@ -343,30 +326,28 @@ subtest 'update() tests' => sub { body => "Test ticket update details", }; - $t->put_ok( "//$userid:$password@/api/v1/tickets/$ticket_id" => json => - $ticket_with_invalid_field )->status_is(400)->json_is( + $t->put_ok( "//$userid:$password@/api/v1/tickets/$ticket_id" => json => $ticket_with_invalid_field ) + ->status_is(400)->json_is( "/errors" => [ { message => "Properties not allowed: blah.", path => "/body" } ] - ); + ); - my $ticket_to_delete = - $builder->build_object( { class => 'Koha::Tickets' } ); - my $non_existent_id = $ticket_to_delete->id; + my $ticket_to_delete = $builder->build_object( { class => 'Koha::Tickets' } ); + my $non_existent_id = $ticket_to_delete->id; $ticket_to_delete->delete; - $t->put_ok( - "//$userid:$password@/api/v1/tickets/$non_existent_id" => json => - $ticket_with_updated_field )->status_is(404); + $t->put_ok( "//$userid:$password@/api/v1/tickets/$non_existent_id" => json => $ticket_with_updated_field ) + ->status_is(404); # Wrong method (POST) $ticket_with_updated_field->{ticket_id} = 2; - $t->post_ok( "//$userid:$password@/api/v1/tickets/$ticket_id" => json => - $ticket_with_updated_field )->status_is(404); + $t->post_ok( "//$userid:$password@/api/v1/tickets/$ticket_id" => json => $ticket_with_updated_field ) + ->status_is(404); $schema->storage->txn_rollback; }; @@ -400,14 +381,12 @@ subtest 'delete() tests' => sub { my $ticket_id = $builder->build_object( { class => 'Koha::Tickets' } )->id; # Unauthorized attempt to delete - $t->delete_ok("//$unauth_userid:$password@/api/v1/tickets/$ticket_id") - ->status_is(403); + $t->delete_ok("//$unauth_userid:$password@/api/v1/tickets/$ticket_id")->status_is(403); - $t->delete_ok("//$userid:$password@/api/v1/tickets/$ticket_id") - ->status_is( 204, 'REST3.2.4' )->content_is( '', 'REST3.3.4' ); + $t->delete_ok("//$userid:$password@/api/v1/tickets/$ticket_id")->status_is( 204, 'REST3.2.4' ) + ->content_is( '', 'REST3.3.4' ); - $t->delete_ok("//$userid:$password@/api/v1/tickets/$ticket_id") - ->status_is(404); + $t->delete_ok("//$userid:$password@/api/v1/tickets/$ticket_id")->status_is(404); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/api/v1/transfer_limits.t b/t/db_dependent/api/v1/transfer_limits.t index 5949040150..c783d67922 100755 --- a/t/db_dependent/api/v1/transfer_limits.t +++ b/t/db_dependent/api/v1/transfer_limits.t @@ -43,19 +43,20 @@ subtest 'list() tests' => sub { Koha::Item::Transfer::Limits->delete; - my $patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 1 } - }); + my $patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 1 } + } + ); my $password = 'thePassword123'; - $patron->set_password({ password => $password, skip_validation => 1 }); + $patron->set_password( { password => $password, skip_validation => 1 } ); my $userid = $patron->userid; - my $limit = $builder->build_object({ class => 'Koha::Item::Transfer::Limits' }); + my $limit = $builder->build_object( { class => 'Koha::Item::Transfer::Limits' } ); - $t->get_ok( "//$userid:$password@/api/v1/transfer_limits" ) - ->status_is( 200, 'REST3.2.2' ) - ->json_is( [$limit->to_api] ); + $t->get_ok("//$userid:$password@/api/v1/transfer_limits")->status_is( 200, 'REST3.2.2' ) + ->json_is( [ $limit->to_api ] ); $schema->storage->txn_rollback; }; @@ -66,57 +67,58 @@ subtest 'add() tests' => sub { $schema->storage->txn_begin; - my $authorized_patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 1 } - }); + my $authorized_patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 1 } + } + ); my $password = 'thePassword123'; - $authorized_patron->set_password({ password => $password, skip_validation => 1 }); + $authorized_patron->set_password( { password => $password, skip_validation => 1 } ); my $auth_userid = $authorized_patron->userid; - my $unauthorized_patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 4 } - }); - $unauthorized_patron->set_password({ password => $password, skip_validation => 1 }); + my $unauthorized_patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 4 } + } + ); + $unauthorized_patron->set_password( { password => $password, skip_validation => 1 } ); my $unauth_userid = $unauthorized_patron->userid; - my $limit = $builder->build_object({ class => 'Koha::Item::Transfer::Limits' }); + my $limit = $builder->build_object( { class => 'Koha::Item::Transfer::Limits' } ); my $limit_hashref = $limit->to_api; delete $limit_hashref->{limit_id}; $limit->delete; # Unauthorized attempt to write - $t->post_ok( "//$unauth_userid:$password@/api/v1/transfer_limits" => json => $limit_hashref ) - ->status_is(403); + $t->post_ok( "//$unauth_userid:$password@/api/v1/transfer_limits" => json => $limit_hashref )->status_is(403); # Authorized attempt to write invalid data - my $limit_with_invalid_field = {'invalid' => 'invalid'}; + my $limit_with_invalid_field = { 'invalid' => 'invalid' }; $t->post_ok( "//$auth_userid:$password@/api/v1/transfer_limits" => json => $limit_with_invalid_field ) - ->status_is(400) - ->json_is( + ->status_is(400)->json_is( "/errors" => [ { message => "Properties not allowed: invalid.", path => "/body" } ] - ); + ); # Authorized attempt to write $t->post_ok( "//$auth_userid:$password@/api/v1/transfer_limits" => json => $limit_hashref ) - ->status_is( 201, 'REST3.2.1' ) - ->json_has( '' => $limit_hashref, 'REST3.3.1' ) + ->status_is( 201, 'REST3.2.1' )->json_has( '' => $limit_hashref, 'REST3.3.1' ) ->header_is( 'Location' => '/api/v1/transfer_limits/' . $t->tx->res->json->{limit_id}, 'REST3.4.1' ); $t->post_ok( "//$auth_userid:$password@/api/v1/transfer_limits" => json => $limit_hashref ) - ->status_is( 409, 'Conflict creating the resource' ) - ->json_is( + ->status_is( 409, 'Conflict creating the resource' )->json_is( { - error => qq{Exception 'Koha::Exceptions::TransferLimit::Duplicate' thrown 'A transfer limit with the given parameters already exists!'\n} + error => + qq{Exception 'Koha::Exceptions::TransferLimit::Duplicate' thrown 'A transfer limit with the given parameters already exists!'\n} } - ); + ); $schema->storage->txn_rollback; }; @@ -126,34 +128,35 @@ subtest 'delete() tests' => sub { $schema->storage->txn_begin; - my $authorized_patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 1 } - }); + my $authorized_patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 1 } + } + ); my $password = 'thePassword123'; - $authorized_patron->set_password({ password => $password, skip_validation => 1 }); + $authorized_patron->set_password( { password => $password, skip_validation => 1 } ); my $auth_userid = $authorized_patron->userid; - my $unauthorized_patron = $builder->build_object({ - class => 'Koha::Patrons', - value => { flags => 4 } - }); - $unauthorized_patron->set_password({ password => $password, skip_validation => 1 }); + my $unauthorized_patron = $builder->build_object( + { + class => 'Koha::Patrons', + value => { flags => 4 } + } + ); + $unauthorized_patron->set_password( { password => $password, skip_validation => 1 } ); my $unauth_userid = $unauthorized_patron->userid; - my $limit = $builder->build_object({ class => 'Koha::Item::Transfer::Limits' }); + my $limit = $builder->build_object( { class => 'Koha::Item::Transfer::Limits' } ); my $limit_id = $limit->id; # Unauthorized attempt to delete - $t->delete_ok( "//$unauth_userid:$password@/api/v1/transfer_limits/$limit_id" ) - ->status_is(403); + $t->delete_ok("//$unauth_userid:$password@/api/v1/transfer_limits/$limit_id")->status_is(403); - $t->delete_ok( "//$auth_userid:$password@/api/v1/transfer_limits/$limit_id" ) - ->status_is(204, 'REST3.2.4') - ->content_is('', 'REST3.3.4'); + $t->delete_ok("//$auth_userid:$password@/api/v1/transfer_limits/$limit_id")->status_is( 204, 'REST3.2.4' ) + ->content_is( '', 'REST3.3.4' ); - $t->delete_ok( "//$auth_userid:$password@/api/v1/transfer_limits/$limit_id" ) - ->status_is(404); + $t->delete_ok("//$auth_userid:$password@/api/v1/transfer_limits/$limit_id")->status_is(404); $schema->storage->txn_rollback; }; diff --git a/t/db_dependent/api/v1/two_factor_auth.t b/t/db_dependent/api/v1/two_factor_auth.t index 3a890c3d65..1ddc0cd4b5 100755 --- a/t/db_dependent/api/v1/two_factor_auth.t +++ b/t/db_dependent/api/v1/two_factor_auth.t @@ -37,9 +37,12 @@ my $remote_address = '127.0.0.1'; my $t = Test::Mojo->new('Koha::REST::V1'); my $mocked_koha_email = Test::MockModule->new('Koha::Email'); -$mocked_koha_email->mock( 'send_or_die', sub { - return 1; -}); +$mocked_koha_email->mock( + 'send_or_die', + sub { + return 1; + } +); subtest 'registration and verification' => sub { @@ -47,13 +50,13 @@ subtest 'registration and verification' => sub { $schema->storage->txn_begin; - t::lib::Mocks::mock_preference('TwoFactorAuthentication', 'enabled'); + t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 'enabled' ); my $patron = $builder->build_object( { class => 'Koha::Patrons', - value => { - flags => 20, # Staff access and Patron info + value => { + flags => 20, # Staff access and Patron info } } ); @@ -75,8 +78,8 @@ subtest 'registration and verification' => sub { $t->request_ok($tx)->status_is(401); # Authenticated - can register - $session->param( 'number', $patron->borrowernumber ); - $session->param( 'id', $patron->userid ); + $session->param( 'number', $patron->borrowernumber ); + $session->param( 'id', $patron->userid ); $session->flush; $patron->auth_method('password'); @@ -92,25 +95,26 @@ subtest 'registration and verification' => sub { $tx = $t->ua->build_tx( POST => "/api/v1/auth/two-factor/registration/verification" ); $tx->req->cookies( { name => 'CGISESSID', value => $session->id } ); $tx->req->env( { REMOTE_ADDR => $remote_address } ); - $t->request_ok($tx)->status_is(400); # Missing parameter + $t->request_ok($tx)->status_is(400); # Missing parameter - my $auth = Koha::Auth::TwoFactorAuth->new({patron => $patron, secret32 => $secret32}); + my $auth = Koha::Auth::TwoFactorAuth->new( { patron => $patron, secret32 => $secret32 } ); my $pin_code = $auth->code; - $tx = $t->ua->build_tx( POST => "/api/v1/auth/two-factor/registration/verification" => form => {secret32 => $secret32, pin_code => $pin_code} ); + $tx = $t->ua->build_tx( POST => "/api/v1/auth/two-factor/registration/verification" => form => + { secret32 => $secret32, pin_code => $pin_code } ); $tx->req->cookies( { name => 'CGISESSID', value => $session->id } ); $tx->req->env( { REMOTE_ADDR => $remote_address } ); $t->request_ok($tx)->status_is(204); $patron = $patron->get_from_storage; - is($patron->auth_method, 'two-factor'); - isnt($patron->secret, undef); + is( $patron->auth_method, 'two-factor' ); + isnt( $patron->secret, undef ); $patron->auth_method('password'); $patron->secret(undef); $patron->store; # Setting up 2FA - can register - $session->param('waiting-for-2FA-setup', 1); + $session->param( 'waiting-for-2FA-setup', 1 ); $session->flush; $tx = $t->ua->build_tx( POST => "/api/v1/auth/two-factor/registration" ); $tx->req->cookies( { name => 'CGISESSID', value => $session->id } ); @@ -118,23 +122,24 @@ subtest 'registration and verification' => sub { $t->request_ok($tx)->status_is(201); $secret32 = $t->tx->res->json->{secret32}; - $auth = Koha::Auth::TwoFactorAuth->new({patron => $patron, secret32 => $secret32}); + $auth = Koha::Auth::TwoFactorAuth->new( { patron => $patron, secret32 => $secret32 } ); $pin_code = $auth->code; - $tx = $t->ua->build_tx( POST => "/api/v1/auth/two-factor/registration/verification" => form => {secret32 => $secret32, pin_code => $pin_code} ); + $tx = $t->ua->build_tx( POST => "/api/v1/auth/two-factor/registration/verification" => form => + { secret32 => $secret32, pin_code => $pin_code } ); $tx->req->cookies( { name => 'CGISESSID', value => $session->id } ); $tx->req->env( { REMOTE_ADDR => $remote_address } ); $t->request_ok($tx)->status_is(204); $patron = $patron->get_from_storage; - is($patron->auth_method, 'two-factor'); - isnt($patron->secret, undef); + is( $patron->auth_method, 'two-factor' ); + isnt( $patron->secret, undef ); # 2FA already enabled - cannot register again $patron->auth_method('two-factor'); $patron->encode_secret("nv4v65dpobpxgzldojsxiii"); $patron->store; - $session->param('waiting-for-2FA-setup', undef); + $session->param( 'waiting-for-2FA-setup', undef ); $session->flush; $tx = $t->ua->build_tx( POST => "/api/v1/auth/two-factor/registration" ); @@ -156,13 +161,13 @@ subtest 'send_otp_token' => sub { $schema->storage->txn_begin; - t::lib::Mocks::mock_preference('TwoFactorAuthentication', 'enabled'); + t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 'enabled' ); my $patron = $builder->build_object( { class => 'Koha::Patrons', - value => { - flags => 20, # Staff access and Patron info + value => { + flags => 20, # Staff access and Patron info } } ); @@ -180,9 +185,9 @@ subtest 'send_otp_token' => sub { $t->request_ok($tx)->status_is(401); # Patron is partially authenticated (credentials correct) - $session->param( 'number', $patron->borrowernumber ); - $session->param( 'id', $patron->userid ); - $session->param('waiting-for-2FA', 1); + $session->param( 'number', $patron->borrowernumber ); + $session->param( 'id', $patron->userid ); + $session->param( 'waiting-for-2FA', 1 ); $session->flush; $patron->library->set( @@ -202,7 +207,7 @@ subtest 'send_otp_token' => sub { $tx->req->env( { REMOTE_ADDR => $remote_address } ); # Invalid email - $t->request_ok($tx)->status_is(400)->json_is({ error => 'email_not_sent' }); + $t->request_ok($tx)->status_is(400)->json_is( { error => 'email_not_sent' } ); $patron->email('to@example.org')->store; $tx = $t->ua->build_tx( POST => "/api/v1/auth/otp/token_delivery" ); @@ -221,7 +226,7 @@ subtest 'send_otp_token' => sub { $patron->flags(20)->store; # Patron is fully authenticated, cannot request a token again - $session->param('waiting-for-2FA', 0); + $session->param( 'waiting-for-2FA', 0 ); $session->flush; $tx = $t->ua->build_tx( POST => "/api/v1/auth/otp/token_delivery" ); $tx->req->cookies( { name => 'CGISESSID', value => $session->id } ); diff --git a/t/db_dependent/api/v1/unhandled_exceptions.t b/t/db_dependent/api/v1/unhandled_exceptions.t index 61517453ce..1d7aa4bb32 100755 --- a/t/db_dependent/api/v1/unhandled_exceptions.t +++ b/t/db_dependent/api/v1/unhandled_exceptions.t @@ -46,8 +46,7 @@ subtest 'unhandled_exception() tests' => sub { } ); my $password = 'thePassword123'; - $authorized_patron->set_password( - { password => $password, skip_validation => 1 } ); + $authorized_patron->set_password( { password => $password, skip_validation => 1 } ); my $userid = $authorized_patron->userid; my $message = 'delete died'; @@ -55,12 +54,11 @@ subtest 'unhandled_exception() tests' => sub { my $mock_patron = Test::MockModule->new('Koha::Patron'); $mock_patron->mock( 'delete', sub { Koha::Exception->throw($message); } ); - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); - $t->delete_ok( "//$userid:$password@/api/v1/patrons/" . $patron->id ) - ->status_is('500') - ->json_is( - { error => 'Something went wrong, check Koha logs for details.', + $t->delete_ok( "//$userid:$password@/api/v1/patrons/" . $patron->id )->status_is('500')->json_is( + { + error => 'Something went wrong, check Koha logs for details.', error_code => 'internal_server_error', } ); diff --git a/t/db_dependent/check_kohastructure.t b/t/db_dependent/check_kohastructure.t index ec5c48c98e..740cddf1e6 100755 --- a/t/db_dependent/check_kohastructure.t +++ b/t/db_dependent/check_kohastructure.t @@ -19,8 +19,7 @@ use Modern::Perl; use Test::More tests => 1; use File::Slurp; use C4::Context; -my $content = read_file( C4::Context->config("intranetdir") - . '/installer/data/mysql/kohastructure.sql' ); +my $content = read_file( C4::Context->config("intranetdir") . '/installer/data/mysql/kohastructure.sql' ); my @drop_stmt_missing; my $ccc = $content; while ( $content =~ m|CREATE TABLE `?([^`\n ]*)`?\s?\(\s*\n|g ) { @@ -32,9 +31,9 @@ is( @drop_stmt_missing, 0, 'DROP TABLE statements should exist for all tables' - . ( + . ( @drop_stmt_missing ? ' but missing for ' . join( ',', @drop_stmt_missing ) : '' - ) + ) ); diff --git a/t/db_dependent/check_sysprefs.t b/t/db_dependent/check_sysprefs.t index 3d194e4a56..9bd0102f22 100755 --- a/t/db_dependent/check_sysprefs.t +++ b/t/db_dependent/check_sysprefs.t @@ -32,8 +32,8 @@ GetOptions( 'showsql' => \$showsql ); use Test::More tests => 2; our $dbh = C4::Context->dbh; -my $intranetdir = C4::Context->config('intranetdir'); -my $root_dir = $intranetdir . '/installer/data/mysql/mandatory'; +my $intranetdir = C4::Context->config('intranetdir'); +my $root_dir = $intranetdir . '/installer/data/mysql/mandatory'; my $base_syspref_file = "sysprefs.sql"; open my $ref_fh, '<', "$root_dir/$base_syspref_file" or croak "Can't open '$root_dir/$base_syspref_file': $!"; @@ -80,7 +80,6 @@ subtest 'Compare sysprefs.sql with YAML files' => sub { } }; - # # Get sysprefs from SQL file populating sysprefs table with INSERT statement. # @@ -136,8 +135,9 @@ sub check_db { my $res = $sth->fetchrow_arrayref; my $dbcount = $res->[0]; if ( !$showsql ) { - cmp_ok( $dbcount, ">=", scalar( keys %$sysprefs ), -"There are at least as many sysprefs in the database as in the sysprefs.sql" + cmp_ok( + $dbcount, ">=", scalar( keys %$sysprefs ), + "There are at least as many sysprefs in the database as in the sysprefs.sql" ); } @@ -150,8 +150,7 @@ sub check_db { my $count = $res->[0]; if ( !$showsql ) { is( $count, 1, "Syspref $_ exists in the database" ); - } - else { + } else { if ( $count != 1 ) { print $sysprefs->{$_}; } diff --git a/t/db_dependent/cronjobs/advance_notices_digest.t b/t/db_dependent/cronjobs/advance_notices_digest.t index b912f2a631..e2755a9e2b 100755 --- a/t/db_dependent/cronjobs/advance_notices_digest.t +++ b/t/db_dependent/cronjobs/advance_notices_digest.t @@ -27,10 +27,10 @@ use File::Basename; use Koha::DateUtils qw( dt_from_string ); -my $scriptDir = dirname(File::Spec->rel2abs( __FILE__ )); +my $scriptDir = dirname( File::Spec->rel2abs(__FILE__) ); -my $schema = Koha::Database->new->schema; -my $dbh = C4::Context->dbh; +my $schema = Koha::Database->new->schema; +my $dbh = C4::Context->dbh; my $library1; my $library2; @@ -40,25 +40,33 @@ my $borrower; sub build_test_objects { # Set only to avoid exception. - t::lib::Mocks::mock_preference('dateformat', 'metric'); + t::lib::Mocks::mock_preference( 'dateformat', 'metric' ); my $builder = t::lib::TestBuilder->new; - $library1 = $builder->build({ - source => 'Branch', - }); - $library2 = $builder->build({ - source => 'Branch', - }); - $library3 = $builder->build({ - source => 'Branch', - }); - $borrower = $builder->build({ - source => 'Borrower', - value => { - branchcode => $library1->{branchcode}, + $library1 = $builder->build( + { + source => 'Branch', } - }); + ); + $library2 = $builder->build( + { + source => 'Branch', + } + ); + $library3 = $builder->build( + { + source => 'Branch', + } + ); + $borrower = $builder->build( + { + source => 'Borrower', + value => { + branchcode => $library1->{branchcode}, + } + } + ); $dbh->do(<<DELETESQL); DELETE FROM letter WHERE module='circulation' @@ -71,91 +79,105 @@ DELETESQL DELETE FROM message_attributes WHERE message_name = 'Advance_Notice' DELETESQL - my $message_attribute = $builder->build({ - source => 'MessageAttribute', - value => { - message_name => 'Advance_Notice' + my $message_attribute = $builder->build( + { + source => 'MessageAttribute', + value => { message_name => 'Advance_Notice' } } - }); + ); - my $letter = $builder->build({ - source => 'Letter', - value => { - module => 'circulation', - code => 'PREDUEDGST', - branchcode => '', - message_transport_type => 'email', - lang => 'default', - is_html => 0, - content => '<<count>> <<branches.branchname>>' + my $letter = $builder->build( + { + source => 'Letter', + value => { + module => 'circulation', + code => 'PREDUEDGST', + branchcode => '', + message_transport_type => 'email', + lang => 'default', + is_html => 0, + content => '<<count>> <<branches.branchname>>' + } } - }); - my $borrower_message_preference = $builder->build({ - source => 'BorrowerMessagePreference', - value => { - borrowernumber => $borrower->{borrowernumber}, - wants_digest => 1, - days_in_advance => 1, - message_attribute_id => $message_attribute->{message_attribute_id} + ); + my $borrower_message_preference = $builder->build( + { + source => 'BorrowerMessagePreference', + value => { + borrowernumber => $borrower->{borrowernumber}, + wants_digest => 1, + days_in_advance => 1, + message_attribute_id => $message_attribute->{message_attribute_id} + } } - }); + ); - my $borrower_message_transport_preference = $builder->build({ - source => 'BorrowerMessageTransportPreference', - value => { - borrower_message_preference_id => $borrower_message_preference->{borrower_message_preference_id}, - message_transport_type => 'email' + my $borrower_message_transport_preference = $builder->build( + { + source => 'BorrowerMessageTransportPreference', + value => { + borrower_message_preference_id => $borrower_message_preference->{borrower_message_preference_id}, + message_transport_type => 'email' + } } - }); + ); #Adding a second preference for a notice that isn't defined, should just be skipped - my $borrower_message_transport_preference_1 = $builder->build({ - source => 'BorrowerMessageTransportPreference', - value => { - borrower_message_preference_id => $borrower_message_preference->{borrower_message_preference_id}, - message_transport_type => 'phone' + my $borrower_message_transport_preference_1 = $builder->build( + { + source => 'BorrowerMessageTransportPreference', + value => { + borrower_message_preference_id => $borrower_message_preference->{borrower_message_preference_id}, + message_transport_type => 'phone' + } } - }); + ); - my $item1 = $builder->build_sample_item; - my $item2 = $builder->build_sample_item; - my $item3 = $builder->build_sample_item; - my $now = dt_from_string(); - my $tomorrow = $now->add(days => 1)->strftime('%F'); + my $item1 = $builder->build_sample_item; + my $item2 = $builder->build_sample_item; + my $item3 = $builder->build_sample_item; + my $now = dt_from_string(); + my $tomorrow = $now->add( days => 1 )->strftime('%F'); - my $issue1 = $builder->build({ - source => 'Issue', - value => { - date_due => $tomorrow, - itemnumber => $item1->itemnumber, - branchcode => $library2->{branchcode}, - borrowernumber => $borrower->{borrowernumber}, - returndate => undef + my $issue1 = $builder->build( + { + source => 'Issue', + value => { + date_due => $tomorrow, + itemnumber => $item1->itemnumber, + branchcode => $library2->{branchcode}, + borrowernumber => $borrower->{borrowernumber}, + returndate => undef + } } - }); + ); - my $issue2 = $builder->build({ - source => 'Issue', - value => { - date_due => $tomorrow, - itemnumber => $item2->itemnumber, - branchcode => $library3->{branchcode}, - borrowernumber => $borrower->{borrowernumber}, - returndate => undef + my $issue2 = $builder->build( + { + source => 'Issue', + value => { + date_due => $tomorrow, + itemnumber => $item2->itemnumber, + branchcode => $library3->{branchcode}, + borrowernumber => $borrower->{borrowernumber}, + returndate => undef + } } - }); - my $issue3 = $builder->build({ - source => 'Issue', - value => { - date_due => $tomorrow, - itemnumber => $item3->itemnumber, - branchcode => $library3->{branchcode}, - borrowernumber => $borrower->{borrowernumber}, - returndate => undef + ); + my $issue3 = $builder->build( + { + source => 'Issue', + value => { + date_due => $tomorrow, + itemnumber => $item3->itemnumber, + branchcode => $library3->{branchcode}, + borrowernumber => $borrower->{borrowernumber}, + returndate => undef + } } - }); + ); - C4::Context->set_preference('EnhancedMessagingPreferences', 1); + C4::Context->set_preference( 'EnhancedMessagingPreferences', 1 ); } sub run_script { @@ -165,13 +187,13 @@ sub run_script { # We simulate script execution by evaluating the script code in the context # of this unit test. - eval $script; ## no critic (StringyEval) + eval $script; ## no critic (StringyEval) die $@ if $@; } my $scriptContent = ''; -my $scriptFile = "$scriptDir/../../../misc/cronjobs/advance_notices.pl"; +my $scriptFile = "$scriptDir/../../../misc/cronjobs/advance_notices.pl"; open my $scriptfh, "<", $scriptFile or die "Failed to open $scriptFile: $!"; while (<$scriptfh>) { @@ -189,21 +211,21 @@ subtest 'Default behaviour tests' => sub { build_test_objects(); - run_script($scriptContent, 'advanced_notices.pl', '-c'); + run_script( $scriptContent, 'advanced_notices.pl', '-c' ); - $sthmq->execute($borrower->{borrowernumber}); + $sthmq->execute( $borrower->{borrowernumber} ); my $messages = $sthmq->fetchall_hashref('message_id'); - is(scalar(keys %$messages), 1, 'There is one message in the queue'); + is( scalar( keys %$messages ), 1, 'There is one message in the queue' ); - for my $message (keys %$messages) { + for my $message ( keys %$messages ) { $messages->{$message}->{content} =~ /(\d+) (.*)/; - my $count = $1; + my $count = $1; my $branchname = $2; - is ($count, '3', 'Issue count is 3'); - is ($branchname, $library1->{branchname}, 'Branchname is that of borrowers home branch.'); + is( $count, '3', 'Issue count is 3' ); + is( $branchname, $library1->{branchname}, 'Branchname is that of borrowers home branch.' ); } $schema->storage->txn_rollback; @@ -217,13 +239,13 @@ subtest '--digest-per-branch tests' => sub { build_test_objects(); - run_script($scriptContent, 'advanced_notices.pl', '-c', '-digest-per-branch'); + run_script( $scriptContent, 'advanced_notices.pl', '-c', '-digest-per-branch' ); - $sthmq->execute($borrower->{borrowernumber}); + $sthmq->execute( $borrower->{borrowernumber} ); my $messages = $sthmq->fetchall_hashref('message_id'); - is(scalar(keys %$messages), 2, 'There are two messages in the queue'); + is( scalar( keys %$messages ), 2, 'There are two messages in the queue' ); my %expected = ( $library2->{branchname} => { @@ -232,7 +254,7 @@ subtest '--digest-per-branch tests' => sub { $library3->{branchname} => { count => 2, } - ); + ); my %expected_branchnames = ( $library2->{branchname} => 1, @@ -240,16 +262,16 @@ subtest '--digest-per-branch tests' => sub { ); my $i = 0; - for my $message (keys %$messages) { + for my $message ( keys %$messages ) { $messages->{$message}->{content} =~ /(\d+) (.*)/; - my $count = $1; + my $count = $1; my $branchname = $2; - ok ($expected_branchnames{$branchname}, 'Branchname is that of expected issuing branch.'); + ok( $expected_branchnames{$branchname}, 'Branchname is that of expected issuing branch.' ); $expected_branchnames{$branchname} = 0; - is ($count, $expected{$branchname}->{count}, 'Issue count is ' . $expected{$branchname}->{count}); + is( $count, $expected{$branchname}->{count}, 'Issue count is ' . $expected{$branchname}->{count} ); $i++; } diff --git a/t/db_dependent/db_structure.t b/t/db_dependent/db_structure.t index 41de50750c..307a465c03 100755 --- a/t/db_dependent/db_structure.t +++ b/t/db_dependent/db_structure.t @@ -21,36 +21,39 @@ use Test::More; use Koha::Database; my @modules = ( - [ qw( Borrower Deletedborrower ) ], - [ qw( Biblio Deletedbiblio ) ], - [ qw( Biblioitem Deletedbiblioitem ) ], - [ qw( Item Deleteditem ) ], + [qw( Borrower Deletedborrower )], + [qw( Biblio Deletedbiblio )], + [qw( Biblioitem Deletedbiblioitem )], + [qw( Item Deleteditem )], ); my @keys_to_check = qw( size is_nullable data_type accessor datetime_undef_if_invalid default_value ); -for my $modules ( @modules ) { - my $rs_1 = Koha::Database->new->schema->resultset($modules->[0]); - my $rs_2 = Koha::Database->new->schema->resultset($modules->[1]); +for my $modules (@modules) { + my $rs_1 = Koha::Database->new->schema->resultset( $modules->[0] ); + my $rs_2 = Koha::Database->new->schema->resultset( $modules->[1] ); my $col_infos_1 = $rs_1->result_source->columns_info; my $col_infos_2 = $rs_2->result_source->columns_info; while ( my ( $column_name, $column_infos ) = each %$col_infos_1 ) { while ( my ( $column_attribute, $value ) = each %$column_infos ) { - if ( grep {$_ eq $column_attribute} @keys_to_check ) { + if ( grep { $_ eq $column_attribute } @keys_to_check ) { my $val_1 = $col_infos_1->{$column_name}{$column_attribute}; my $val_2 = $col_infos_2->{$column_name}{$column_attribute}; + # Dereference if we got a reference to a scalar if ( ref($val_1) eq 'SCALAR' ) { $val_1 = ${$val_1}; $val_2 = ${$val_2}; } - if ( ref($val_1) eq 'ARRAY') { - is_deeply( $val_1, $val_2, + if ( ref($val_1) eq 'ARRAY' ) { + is_deeply( + $val_1, $val_2, "tables related to $modules->[0] and $modules->[1] should not differ on $column_name.$column_attribute" ); } else { - is( $val_1, $val_2, + is( + $val_1, $val_2, "tables related to $modules->[0] and $modules->[1] should not differ on $column_name.$column_attribute" ); } diff --git a/t/db_dependent/misc/translator/xgettext-installer.t b/t/db_dependent/misc/translator/xgettext-installer.t index d8a3286b32..cd6e30d905 100755 --- a/t/db_dependent/misc/translator/xgettext-installer.t +++ b/t/db_dependent/misc/translator/xgettext-installer.t @@ -4,16 +4,15 @@ use Modern::Perl; use File::Slurp; use File::Temp qw(tempdir); -use FindBin qw($Bin); +use FindBin qw($Bin); use Locale::PO; use Test::More tests => 4; -my $tempdir = tempdir(CLEANUP => 1); +my $tempdir = tempdir( CLEANUP => 1 ); -write_file("$tempdir/files", "$Bin/sample.yml"); +write_file( "$tempdir/files", "$Bin/sample.yml" ); -my $xgettext_cmd = "$Bin/../../../../misc/translator/xgettext-installer " - . "-o $tempdir/Koha.pot -f $tempdir/files"; +my $xgettext_cmd = "$Bin/../../../../misc/translator/xgettext-installer " . "-o $tempdir/Koha.pot -f $tempdir/files"; system($xgettext_cmd); my $pot = Locale::PO->load_file_asarray("$tempdir/Koha.pot"); @@ -25,8 +24,8 @@ my @expected = ( { msgid => '"foo ツ"' }, ); -for (my $i = 0; $i < @expected; $i++) { - my $expected = $expected[$i]->{msgid}; +for ( my $i = 0 ; $i < @expected ; $i++ ) { + my $expected = $expected[$i]->{msgid}; my $expected_str = defined $expected ? $expected : 'not defined'; - is($pot->[$i + 1]->msgid, $expected, "$i: msgid is $expected_str"); + is( $pot->[ $i + 1 ]->msgid, $expected, "$i: msgid is $expected_str" ); } diff --git a/t/db_dependent/misc/translator/xgettext-pref.t b/t/db_dependent/misc/translator/xgettext-pref.t index 2e5bcdeba0..4e9c072789 100755 --- a/t/db_dependent/misc/translator/xgettext-pref.t +++ b/t/db_dependent/misc/translator/xgettext-pref.t @@ -4,16 +4,15 @@ use Modern::Perl; use File::Slurp; use File::Temp qw(tempdir); -use FindBin qw($Bin); +use FindBin qw($Bin); use Locale::PO; use Test::More tests => 16; -my $tempdir = tempdir(CLEANUP => 1); +my $tempdir = tempdir( CLEANUP => 1 ); -write_file("$tempdir/files", "$Bin/sample.pref"); +write_file( "$tempdir/files", "$Bin/sample.pref" ); -my $xgettext_cmd = "$Bin/../../../../misc/translator/xgettext-pref " - . "-o $tempdir/Koha.pot -f $tempdir/files"; +my $xgettext_cmd = "$Bin/../../../../misc/translator/xgettext-pref " . "-o $tempdir/Koha.pot -f $tempdir/files"; system($xgettext_cmd); my $pot = Locale::PO->load_file_asarray("$tempdir/Koha.pot"); @@ -45,10 +44,10 @@ my @expected = ( }, ); -for (my $i = 0; $i < @expected; $i++) { +for ( my $i = 0 ; $i < @expected ; $i++ ) { for my $key (qw(msgid msgctxt)) { - my $expected = $expected[$i]->{$key}; + my $expected = $expected[$i]->{$key}; my $expected_str = defined $expected ? $expected : 'not defined'; - is($pot->[$i + 1]->$key, $expected, "$i: $key is $expected_str"); + is( $pot->[ $i + 1 ]->$key, $expected, "$i: $key is $expected_str" ); } } diff --git a/t/db_dependent/misc/translator/xgettext-tt2.t b/t/db_dependent/misc/translator/xgettext-tt2.t index 0c18473ebb..f99a164eff 100755 --- a/t/db_dependent/misc/translator/xgettext-tt2.t +++ b/t/db_dependent/misc/translator/xgettext-tt2.t @@ -4,16 +4,16 @@ use Modern::Perl; use File::Slurp; use File::Temp qw(tempdir); -use FindBin qw($Bin); +use FindBin qw($Bin); use Locale::PO; use Test::More tests => 36; -my $tempdir = tempdir(CLEANUP => 1); +my $tempdir = tempdir( CLEANUP => 1 ); -write_file("$tempdir/files", "$Bin/sample.tt"); +write_file( "$tempdir/files", "$Bin/sample.tt" ); -my $xgettext_cmd = "$Bin/../../../../misc/translator/xgettext-tt2 --from-code=UTF-8 " - . "-o $tempdir/Koha.pot -f $tempdir/files"; +my $xgettext_cmd = + "$Bin/../../../../misc/translator/xgettext-tt2 --from-code=UTF-8 " . "-o $tempdir/Koha.pot -f $tempdir/files"; system($xgettext_cmd); my $pot = Locale::PO->load_file_asarray("$tempdir/Koha.pot"); @@ -26,30 +26,30 @@ my @expected = ( msgid => '"hello {name}"', }, { - msgid => '"item"', + msgid => '"item"', msgid_plural => '"items"', }, { - msgid => '"{count} item"', + msgid => '"{count} item"', msgid_plural => '"{count} items"', }, { - msgid => '"hello"', + msgid => '"hello"', msgctxt => '"context"', }, { - msgid => '"hello {name}"', + msgid => '"hello {name}"', msgctxt => '"context"', }, { - msgid => '"item"', + msgid => '"item"', msgid_plural => '"items"', - msgctxt => '"context"', + msgctxt => '"context"', }, { - msgid => '"{count} item"', + msgid => '"{count} item"', msgid_plural => '"{count} items"', - msgctxt => '"context"', + msgctxt => '"context"', }, { msgid => '"status is {status}"', @@ -65,10 +65,10 @@ my @expected = ( }, ); -for (my $i = 0; $i < @expected; $i++) { +for ( my $i = 0 ; $i < @expected ; $i++ ) { for my $key (qw(msgid msgid_plural msgctxt)) { - my $expected = $expected[$i]->{$key}; + my $expected = $expected[$i]->{$key}; my $expected_str = defined $expected ? $expected : 'not defined'; - is($pot->[$i + 1]->$key, $expected, "$i: $key is $expected_str"); + is( $pot->[ $i + 1 ]->$key, $expected, "$i: $key is $expected_str" ); } } diff --git a/t/db_dependent/rollingloans.t b/t/db_dependent/rollingloans.t index 60a4d6522c..7741a7836d 100755 --- a/t/db_dependent/rollingloans.t +++ b/t/db_dependent/rollingloans.t @@ -17,19 +17,19 @@ my $schema = Koha::Database->new->schema; $schema->storage->txn_begin; my $builder = t::lib::TestBuilder->new; -$builder->build({ source => 'Branch', value => { branchcode => 'CPL' } }) +$builder->build( { source => 'Branch', value => { branchcode => 'CPL' } } ) unless Koha::Libraries->find('CPL'); -t::lib::Mocks::mock_userenv({ branchcode => 'CPL' }); +t::lib::Mocks::mock_userenv( { branchcode => 'CPL' } ); -t::lib::Mocks::mock_preference('BlockReturnOfWithdrawnItems',0); -my $test_patron = '23529001223651'; +t::lib::Mocks::mock_preference( 'BlockReturnOfWithdrawnItems', 0 ); +my $test_patron = '23529001223651'; my $test_item_fic = '502326000402'; -my $test_item_24 = '502326000404'; -my $test_item_48 = '502326000403'; +my $test_item_24 = '502326000404'; +my $test_item_48 = '502326000403'; -my $borrower1 = $builder->build_object({ class => 'Koha::Patrons', value => { cardnumber => $test_patron } }); -my $item1 = $builder->build_sample_item( +my $borrower1 = $builder->build_object( { class => 'Koha::Patrons', value => { cardnumber => $test_patron } } ); +my $item1 = $builder->build_sample_item( { barcode => $test_item_fic, } @@ -47,7 +47,7 @@ my $item3 = $builder->build_sample_item( SKIP: { skip 'Missing test borrower or item, skipping tests', 8 - unless ( defined $borrower1 && defined $item1 ); + unless ( defined $borrower1 && defined $item1 ); for my $item_barcode ( $test_item_fic, $test_item_24, $test_item_48 ) { my $duedate = try_issue( $test_patron, $item_barcode ); @@ -62,16 +62,16 @@ SKIP: { } sub try_issue { - my ($cardnumber, $item_barcode ) = @_; + my ( $cardnumber, $item_barcode ) = @_; my $issuedate = '2011-05-16'; - my $patron = Koha::Patrons->find( { cardnumber => $cardnumber } ); - my ($issuingimpossible,$needsconfirmation) = CanBookBeIssued( $patron, $item_barcode ); - my $issue = AddIssue($patron, $item_barcode, undef, 0, $issuedate); + my $patron = Koha::Patrons->find( { cardnumber => $cardnumber } ); + my ( $issuingimpossible, $needsconfirmation ) = CanBookBeIssued( $patron, $item_barcode ); + my $issue = AddIssue( $patron, $item_barcode, undef, 0, $issuedate ); return dt_from_string( $issue->date_due ); } sub try_return { my $item_barcode = shift; - my ($ret, $messages, $iteminformation, $borrower) = AddReturn($item_barcode); + my ( $ret, $messages, $iteminformation, $borrower ) = AddReturn($item_barcode); return $ret; } diff --git a/t/db_dependent/selenium/00-onboarding.t b/t/db_dependent/selenium/00-onboarding.t index e1218011e8..8cad7a86dc 100755 --- a/t/db_dependent/selenium/00-onboarding.t +++ b/t/db_dependent/selenium/00-onboarding.t @@ -49,7 +49,10 @@ SKIP: { eval { require Selenium::Remote::Driver; }; skip "Selenium::Remote::Driver is needed for selenium tests.", 2 if $@; - skip "This test must be run with an empty DB. We are using KOHA_TESTING that is set by our CI\nIf you really want to run it, set this env var.", 2 unless $ENV{KOHA_TESTING}; + skip + "This test must be run with an empty DB. We are using KOHA_TESTING that is set by our CI\nIf you really want to run it, set this env var.", + 2 + unless $ENV{KOHA_TESTING}; my $dbh = eval { C4::Context->dbh; }; skip "Tests won't run if the database does not exist", 2 if $@; @@ -58,33 +61,35 @@ SKIP: { my $dup_err; local *STDERR; open STDERR, ">>", \$dup_err; - $dbh->do(q| + $dbh->do( + q| SELECT * FROM systempreferences WHERE 1 = 0 | ); close STDERR; - if ( $dup_err ) { + if ($dup_err) { skip "Tests won't run if the database is not empty", 2 if $@; } } my $s = t::lib::Selenium->new; - my $driver = $s->driver; + my $driver = $s->driver; my $base_url = $s->base_url; - my $db_user = C4::Context->config('user'); - my $db_pass = C4::Context->config('pass'); + my $db_user = C4::Context->config('user'); + my $db_pass = C4::Context->config('pass'); - $driver->get($base_url."mainpage.pl"); + $driver->get( $base_url . "mainpage.pl" ); - my $lang = "en"; # The idea here is to loop on all languages + my $lang = "en"; # The idea here is to loop on all languages + + $driver->set_window_size( 3840, 1080 ); - $driver->set_window_size(3840,1080); # Welcome to the Koha web installer - $s->fill_form({userid => $db_user, password => $db_pass }); + $s->fill_form( { userid => $db_user, password => $db_pass } ); $s->submit_form; # Choose your language - $s->fill_form({ language => $languages->{$lang} }); + $s->fill_form( { language => $languages->{$lang} } ); $s->submit_form; # Check Perl dependencies @@ -110,7 +115,7 @@ SKIP: { $s->submit_form; # Select your MARC flavor - $s->fill_form({ marcflavour => 'MARC21' }); + $s->fill_form( { marcflavour => 'MARC21' } ); $s->submit_form; # Selecting default settings @@ -121,7 +126,8 @@ SKIP: { #} $s->submit_form; - for (1..20){ # FIXME This is really ugly, but for an unknown reason the next submit_form is resubmitting the same form. So waiting for the next page to be effectively loaded + for ( 1 .. 20 ) + { # FIXME This is really ugly, but for an unknown reason the next submit_form is resubmitting the same form. So waiting for the next page to be effectively loaded my $title = $s->driver->get_title; last if $title =~ m|Default data loaded|; sleep 1; @@ -134,45 +140,52 @@ SKIP: { $s->click( { href => '/installer/onboarding.pl', main => 'installer-step3' } ); # Create a library - $s->fill_form({ branchcode => 'CPL', branchname => 'Centerville' }); + $s->fill_form( { branchcode => 'CPL', branchname => 'Centerville' } ); $s->submit_form; # Library created! $s->driver->find_element('//div[@class="alert alert-success"]'); + # Create a patron category - $s->fill_form({ categorycode => 'S', description => 'Staff', enrolmentperiod => 12 }); + $s->fill_form( { categorycode => 'S', description => 'Staff', enrolmentperiod => 12 } ); $s->submit_form; # Patron category created! $s->driver->find_element('//div[@class="alert alert-success"]'); + # Create Koha administrator patron - $s->fill_form({ %$superlibrarian, password2 => $superlibrarian->{password} }); + $s->fill_form( { %$superlibrarian, password2 => $superlibrarian->{password} } ); $s->submit_form; #Administrator account created! $s->driver->find_element('//div[@class="alert alert-success"]'); + # Create a new item type - $s->fill_form({ itemtype => 'BK', description => 'Book' }); + $s->fill_form( { itemtype => 'BK', description => 'Book' } ); $s->submit_form; # New item type created! $s->driver->find_element('//div[@class="alert alert-success"]'); + # Create a new circulation rule # Keep default values $s->submit_form; # Get the interface in the correct language - C4::Context->set_preference('language', $languages->{$lang} ); - C4::Context->set_preference('opaclanguages', $languages->{$lang} ); + C4::Context->set_preference( 'language', $languages->{$lang} ); + C4::Context->set_preference( 'opaclanguages', $languages->{$lang} ); $s->click( { href => '/mainpage.pl', main => 'onboarding-step5' } ); - $s->fill_form({ userid => $superlibrarian->{userid}, password => $superlibrarian->{password} }); + $s->fill_form( { userid => $superlibrarian->{userid}, password => $superlibrarian->{password} } ); - like( $s->driver->get_title, qr(Log in to Koha), 'After the onboarding process the user should have landed in the login form page'); + like( + $s->driver->get_title, qr(Log in to Koha), + 'After the onboarding process the user should have landed in the login form page' + ); $s->submit_form; - is( $s->driver->get_title, 'Koha staff interface', 'The credentials we created should work'); + is( $s->driver->get_title, 'Koha staff interface', 'The credentials we created should work' ); $driver->quit(); -}; +} diff --git a/t/db_dependent/selenium/01-installation.t b/t/db_dependent/selenium/01-installation.t index ce9841b81f..e5e3db5d66 100755 --- a/t/db_dependent/selenium/01-installation.t +++ b/t/db_dependent/selenium/01-installation.t @@ -50,7 +50,10 @@ SKIP: { eval { require Selenium::Remote::Driver; }; skip "Selenium::Remote::Driver is needed for selenium tests.", 2 if $@; - skip "This test must be run with an empty DB. We are using KOHA_TESTING that is set by our CI\nIf you really want to run it, set this env var.", 2 unless $ENV{KOHA_TESTING}; + skip + "This test must be run with an empty DB. We are using KOHA_TESTING that is set by our CI\nIf you really want to run it, set this env var.", + 2 + unless $ENV{KOHA_TESTING}; my $dbh = eval { C4::Context->dbh; }; skip "Tests won't run if the database does not exist", 2 if $@; @@ -59,33 +62,35 @@ SKIP: { my $dup_err; local *STDERR; open STDERR, ">>", \$dup_err; - $dbh->do(q| + $dbh->do( + q| SELECT * FROM systempreferences WHERE 1 = 0 | ); close STDERR; - if ( $dup_err ) { + if ($dup_err) { skip "Tests won't run if the database is not empty", 2 if $@; } } my $s = t::lib::Selenium->new; - my $driver = $s->driver; + my $driver = $s->driver; my $base_url = $s->base_url; - my $db_user = C4::Context->config('user'); - my $db_pass = C4::Context->config('pass'); + my $db_user = C4::Context->config('user'); + my $db_pass = C4::Context->config('pass'); - $driver->get($base_url."mainpage.pl"); + $driver->get( $base_url . "mainpage.pl" ); - my $lang = "en"; # The idea here is to loop on all languages + my $lang = "en"; # The idea here is to loop on all languages + + $driver->set_window_size( 3840, 1080 ); - $driver->set_window_size(3840,1080); # Welcome to the Koha web installer - $s->fill_form({userid => $db_user, password => $db_pass }); + $s->fill_form( { userid => $db_user, password => $db_pass } ); $s->submit_form; # Choose your language - $s->fill_form({ language => $languages->{$lang} }); + $s->fill_form( { language => $languages->{$lang} } ); $s->submit_form; # Check Perl dependencies @@ -111,17 +116,18 @@ SKIP: { $s->submit_form; # Select your MARC flavor - $s->fill_form({ marcflavour => 'MARC21' }); + $s->fill_form( { marcflavour => 'MARC21' } ); $s->submit_form; # Selecting default settings my @checkboxes = $driver->find_elements('//input[@type="checkbox" and not(@checked="checked")]'); - for my $c ( @checkboxes ) { + for my $c (@checkboxes) { $c->click; } $s->submit_form; - for (1..20){ # FIXME This is really ugly, but for an unknown reason the next submit_form is resubmitting the same form. So waiting for the next page to be effectively loaded + for ( 1 .. 20 ) + { # FIXME This is really ugly, but for an unknown reason the next submit_form is resubmitting the same form. So waiting for the next page to be effectively loaded my $title = $s->driver->get_title; last if $title =~ m|Default data loaded|; sleep 1; @@ -132,34 +138,37 @@ SKIP: { my $RequireStrongPassword = C4::Context->preference('RequireStrongPassword'); my $minPasswordLength = C4::Context->preference('minPasswordLength'); - C4::Context->set_preference('RequireStrongPassword', 0 ); - C4::Context->set_preference('minPasswordLength', 3 ); + C4::Context->set_preference( 'RequireStrongPassword', 0 ); + C4::Context->set_preference( 'minPasswordLength', 3 ); # Installation complete $s->click( { href => '/installer/onboarding.pl', main => 'installer-step3' } ); # Create Koha administrator patron - $s->fill_form({ %$superlibrarian, password2 => $superlibrarian->{password} }); + $s->fill_form( { %$superlibrarian, password2 => $superlibrarian->{password} } ); $s->submit_form; - C4::Context->set_preference('RequireStrongPassword', $RequireStrongPassword ); - C4::Context->set_preference('minPasswordLength', $minPasswordLength ); + C4::Context->set_preference( 'RequireStrongPassword', $RequireStrongPassword ); + C4::Context->set_preference( 'minPasswordLength', $minPasswordLength ); # Create a new circulation rule # Keep default values $s->submit_form; # Get the interface in the correct language - C4::Context->set_preference('language', $languages->{$lang} ); - C4::Context->set_preference('opaclanguages', $languages->{$lang} ); + C4::Context->set_preference( 'language', $languages->{$lang} ); + C4::Context->set_preference( 'opaclanguages', $languages->{$lang} ); $s->click( { href => '/mainpage.pl', main => 'onboarding-step5' } ); - $s->fill_form({ userid => $superlibrarian->{userid}, password => $superlibrarian->{password} }); + $s->fill_form( { userid => $superlibrarian->{userid}, password => $superlibrarian->{password} } ); - like( $s->driver->get_title, qr(Log in to Koha), 'After the onboarding process the user should have landed in the login form page'); + like( + $s->driver->get_title, qr(Log in to Koha), + 'After the onboarding process the user should have landed in the login form page' + ); $s->submit_form; - is( $s->driver->get_title, 'Koha staff interface', 'The credentials we created should work'); + is( $s->driver->get_title, 'Koha staff interface', 'The credentials we created should work' ); $driver->quit(); -}; +} diff --git a/t/db_dependent/selenium/administration_tasks.t b/t/db_dependent/selenium/administration_tasks.t index 4dc1d4362b..64cec37e71 100755 --- a/t/db_dependent/selenium/administration_tasks.t +++ b/t/db_dependent/selenium/administration_tasks.t @@ -33,7 +33,7 @@ my $builder = t::lib::TestBuilder->new; my $login = $ENV{KOHA_USER} || 'koha'; my $itemtype = 'UT_DVD'; -my $frameworkcode = 'UTFW'; # frameworkcode is only 4 characters max! +my $frameworkcode = 'UTFW'; # frameworkcode is only 4 characters max! my $branchcode = 'UT_BC'; my $av_category = 'AV_CAT_TEST'; my $category_code = 'PATRON_CAT'; @@ -45,60 +45,61 @@ SKIP: { $cleanup_needed = 1; - my $s = t::lib::Selenium->new; - my $driver = $s->driver; - $driver->set_window_size(3840,1080); + my $s = t::lib::Selenium->new; + my $driver = $s->driver; + $driver->set_window_size( 3840, 1080 ); my $mainpage = $s->base_url . q|mainpage.pl|; $driver->get($mainpage); like( $driver->get_title(), qr(Log in to Koha), ); $s->auth; - { # Item types - # Navigate to the Administration area and create an item type - $s->click( { href => '/admin/admin-home.pl', main => 'container-main' } ) - ; # Koha administration - $s->click( { href => '/admin/itemtypes.pl', main_class => 'main container-fluid' } ); # Item Types + { # Item types + # Navigate to the Administration area and create an item type + $s->click( { href => '/admin/admin-home.pl', main => 'container-main' } ); # Koha administration + $s->click( { href => '/admin/itemtypes.pl', main_class => 'main container-fluid' } ); # Item Types $s->click( { href => '/admin/itemtypes.pl?op=add_form', main_class => 'main container-fluid' } ) - ; # New item type - $s->fill_form( - { itemtype => $itemtype, description => "Digital Optical Disc" } ); + ; # New item type + $s->fill_form( { itemtype => $itemtype, description => "Digital Optical Disc" } ); $s->submit_form; $s->click( { - href => '/admin/itemtypes.pl?op=add_form&itemtype=' . $itemtype, + href => '/admin/itemtypes.pl?op=add_form&itemtype=' . $itemtype, main_class => 'main container-fluid' } - ); # New item type + ); # New item type }; - { # Circulation/fine rules - my $itype = $builder->build_object({ class => "Koha::ItemTypes" }); + { # Circulation/fine rules + my $itype = $builder->build_object( { class => "Koha::ItemTypes" } ); $driver->get($mainpage); - $s->click( { href => '/admin/admin-home.pl', main => 'container-main' } ) - ; # Koha administration + $s->click( { href => '/admin/admin-home.pl', main => 'container-main' } ); # Koha administration $s->click( { href => '/admin/smart-rules.pl', main_class => 'main container-fluid' } ) - ; # Circulation and fine rules - my $elt = $driver->find_element('//tr[@id="edit_row"]/td/select[@id="matrixitemtype"]/option[@value="'.$itype->itemtype.'"]'); - is( $elt->get_text(),$itype->description,"Our new itemtype is in the list"); + ; # Circulation and fine rules + my $elt = $driver->find_element( + '//tr[@id="edit_row"]/td/select[@id="matrixitemtype"]/option[@value="' . $itype->itemtype . '"]' ); + is( $elt->get_text(), $itype->description, "Our new itemtype is in the list" ); $elt->click(); $elt = $driver->find_element('//tr[@id="edit_row"]/td[@class="actions"]/button[@type="submit"]'); $elt->click(); - $elt = $driver->find_elements('//table[@id="default-circulation-rules"]/tbody/tr/td[contains(text(),"'.$itype->description.'")]/following-sibling::td/span[text() = "Unlimited"]'); + $elt = + $driver->find_elements( '//table[@id="default-circulation-rules"]/tbody/tr/td[contains(text(),"' + . $itype->description + . '")]/following-sibling::td/span[text() = "Unlimited"]' ); is( @$elt, 5, "We have unlimited checkouts and holds" ); + #Clean up Koha::CirculationRules->search( { itemtype => $itype->itemtype } )->delete; $itype->delete; - # TODO Create more smart rules navigation here + + # TODO Create more smart rules navigation here }; - { # Biblio frameworks + { # Biblio frameworks $driver->get($mainpage); - $s->click( { href => '/admin/admin-home.pl', main => 'container-main' } ) - ; # Koha administration + $s->click( { href => '/admin/admin-home.pl', main => 'container-main' } ); # Koha administration $s->click( { href => '/admin/biblio_framework.pl', main_class => 'main container-fluid' } ) - ; # MARC bibliographic framework - $s->click( - { href => '/admin/biblio_framework.pl?op=add_form', main_class => 'main container-fluid' } ) - ; # New framework + ; # MARC bibliographic framework + $s->click( { href => '/admin/biblio_framework.pl?op=add_form', main_class => 'main container-fluid' } ) + ; # New framework $s->fill_form( { frameworkcode => $frameworkcode, @@ -109,21 +110,18 @@ SKIP: { $s->click( { id => 'frameworkactions' . $frameworkcode } ); $s->click( { - href => 'marctagstructure.pl?frameworkcode=' . $frameworkcode, + href => 'marctagstructure.pl?frameworkcode=' . $frameworkcode, main_class => 'main container-fluid' } ); # MARC structure # FIXME '/admin/' is missing in the url # TODO Click on OK to create the MARC structure }; - { #Libraries + { #Libraries $driver->get($mainpage); - $s->click( { href => '/admin/admin-home.pl', main => 'container-main' } ) - ; # Koha administration - $s->click( { href => '/admin/branches.pl', main_class => 'main container-fluid' } ) - ; # Libraries and groups - $s->click( { href => '/admin/branches.pl?op=add_form', main_class => 'main container-fluid' } ) - ; # New library + $s->click( { href => '/admin/admin-home.pl', main => 'container-main' } ); # Koha administration + $s->click( { href => '/admin/branches.pl', main_class => 'main container-fluid' } ); # Libraries and groups + $s->click( { href => '/admin/branches.pl?op=add_form', main_class => 'main container-fluid' } ); # New library $s->fill_form( { branchcode => $branchcode, branchname => 'my library' } ); $s->submit_form; @@ -131,10 +129,10 @@ SKIP: { $s->show_all_entries('//div[@id="libraries_wrapper"]'); $s->click( { - href => '/admin/branches.pl?op=add_form&branchcode=' . $branchcode, + href => '/admin/branches.pl?op=add_form&branchcode=' . $branchcode, main_class => 'main container-fluid' } - ); # Edit + ); # Edit $s->fill_form( { branchname => 'another branchname' } ); $s->submit_form; @@ -142,24 +140,29 @@ SKIP: { $s->show_all_entries('//div[@id="libraries_wrapper"]'); $s->click( { - id => 'delete_library_'.$branchcode, + id => 'delete_library_' . $branchcode, } - ); # Delete + ); # Delete }; - { #Authorized values + { #Authorized values $driver->get($mainpage); - $s->click( { href => '/admin/admin-home.pl', main => 'container-main' } ); #Koha administration + $s->click( { href => '/admin/admin-home.pl', main => 'container-main' } ); #Koha administration $s->click( { href => '/admin/authorised_values.pl', main_class => 'main container-fluid' } ); #Authorized values - $s->click( { href => { 'ends-with' => '/admin/authorised_values.pl?op=add_form' }, main_class => 'main container-fluid' } ); # New category + $s->click( + { + href => { 'ends-with' => '/admin/authorised_values.pl?op=add_form' }, + main_class => 'main container-fluid' + } + ); # New category $s->fill_form( { category => $av_category } ); $s->submit_form; $s->click( { - href => '/admin/authorised_values.pl?op=add_form&category=' . $av_category, + href => '/admin/authorised_values.pl?op=add_form&category=' . $av_category, main_class => 'main container-fluid' } ); # New authorised value for ... @@ -173,11 +176,14 @@ SKIP: { $s->submit_form; my $dbh = C4::Context->dbh; - my ( $av_id ) = $dbh->selectrow_array(q| - SELECT id FROM authorised_values WHERE category=?|, undef, $av_category ); + my ($av_id) = $dbh->selectrow_array( + q| + SELECT id FROM authorised_values WHERE category=?|, undef, $av_category + ); + #$driver->find_element('//input[@id="'.$av_id.'"]/following-sibling::button[text() = "Delete"]')->click; - $driver->find_element('//input[@name="id"][@value="'.$av_id.'"]/following-sibling::button')->click; - $s->driver->accept_alert; # Accept the modal "Are you sure you want to delete this authorized value?" + $driver->find_element( '//input[@name="id"][@value="' . $av_id . '"]/following-sibling::button' )->click; + $s->driver->accept_alert; # Accept the modal "Are you sure you want to delete this authorized value?" # For an unknown reason the click on the next admin-home link does not work # We were still on the authorised value list view. @@ -185,13 +191,19 @@ SKIP: { sleep 1; }; - { # Patron categories + { # Patron categories $driver->get($mainpage); - $s->click( { href => '/admin/admin-home.pl', main => 'container-main' } ); # Koha administration - $s->click( { href => '/admin/categories.pl', main_class => 'main container-fluid' } ); # Patron categories - $s->click( { href => '/admin/categories.pl?op=add_form', main_class => 'main container-fluid' } ); # New patron category + $s->click( { href => '/admin/admin-home.pl', main => 'container-main' } ); # Koha administration + $s->click( { href => '/admin/categories.pl', main_class => 'main container-fluid' } ); # Patron categories + $s->click( { href => '/admin/categories.pl?op=add_form', main_class => 'main container-fluid' } ) + ; # New patron category - $s->fill_form( { categorycode => $category_code, description => 'Test category', enrolmentperiod => 12, category_type => 'A' } ); + $s->fill_form( + { + categorycode => $category_code, description => 'Test category', enrolmentperiod => 12, + category_type => 'A' + } + ); $s->submit_form; # Select "Show all" in the datatable "Show x entries" dropdown list to make sure our category is not hidden @@ -213,12 +225,12 @@ SKIP: { $s->click( { - href => '/admin/categories.pl?op=delete_confirm&categorycode=' . $category_code, + href => '/admin/categories.pl?op=delete_confirm&categorycode=' . $category_code, main_class => 'main container-fluid' } - ); # Delete button + ); # Delete button - $s->submit_form; # Delete this category + $s->submit_form; # Delete this category # TODO Make sure the category has been deleted }; @@ -228,13 +240,13 @@ SKIP: { END { cleanup() if $cleanup_needed; -}; +} sub cleanup { my $dbh = C4::Context->dbh; - $dbh->do(q|DELETE FROM itemtypes WHERE itemtype=?|, undef, $itemtype); - $dbh->do(q|DELETE FROM biblio_framework WHERE frameworkcode=?|, undef, $frameworkcode); - $dbh->do(q|DELETE FROM branches WHERE branchcode=?|, undef, $branchcode); - $dbh->do(q|DELETE FROM authorised_value_categories WHERE category_name=?|, undef, $av_category); - $dbh->do(q|DELETE FROM categories WHERE categorycode=?|, undef, $category_code); + $dbh->do( q|DELETE FROM itemtypes WHERE itemtype=?|, undef, $itemtype ); + $dbh->do( q|DELETE FROM biblio_framework WHERE frameworkcode=?|, undef, $frameworkcode ); + $dbh->do( q|DELETE FROM branches WHERE branchcode=?|, undef, $branchcode ); + $dbh->do( q|DELETE FROM authorised_value_categories WHERE category_name=?|, undef, $av_category ); + $dbh->do( q|DELETE FROM categories WHERE categorycode=?|, undef, $category_code ); } diff --git a/t/db_dependent/selenium/authentication.t b/t/db_dependent/selenium/authentication.t index bf39a6e6c2..6e31eb8f95 100755 --- a/t/db_dependent/selenium/authentication.t +++ b/t/db_dependent/selenium/authentication.t @@ -37,24 +37,27 @@ SKIP: { eval { require Selenium::Remote::Driver; }; skip "Selenium::Remote::Driver is needed for selenium tests.", 3 if $@; - my $builder = t::lib::TestBuilder->new; - my $s = t::lib::Selenium->new; - my $driver = $s->driver; + my $builder = t::lib::TestBuilder->new; + my $s = t::lib::Selenium->new; + my $driver = $s->driver; subtest 'Staff interface authentication' => sub { plan tests => 7; my $mainpage = $s->base_url . q|mainpage.pl|; $driver->get($mainpage); - like( $driver->get_title, qr(Log in to Koha), 'Hitting the main page should redirect to the login form'); + like( $driver->get_title, qr(Log in to Koha), 'Hitting the main page should redirect to the login form' ); - my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => 0 }}); - my $password = Koha::AuthUtils::generate_password($patron->category); + my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { flags => 0 } } ); + my $password = Koha::AuthUtils::generate_password( $patron->category ); t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 ); - $patron->set_password({ password => $password }); + $patron->set_password( { password => $password } ); # Patron is authenticated but is not authorized to access staff interface $s->auth( $patron->userid, $password ); - like( $driver->get_title, qr(Access denied), 'Patron without permission should be redirected to the login form' ); + like( + $driver->get_title, qr(Access denied), + 'Patron without permission should be redirected to the login form' + ); # Try logging in as someone else (even a non-existent patron) and you should still be denied access $s->auth( 'Bond', 'James Bond' ); @@ -63,30 +66,34 @@ SKIP: { 'Trying to change to a non-existent user should fail login' ); - $driver->get($mainpage . q|?logout.x=1|); - $patron->flags(4)->store; # catalogue permission + $driver->get( $mainpage . q|?logout.x=1| ); + $patron->flags(4)->store; # catalogue permission $s->auth( $patron->userid, $password ); like( $driver->get_title, qr(Koha staff interface), 'Patron with flags catalogue should be able to login' ); - $driver->get($mainpage . q|?logout.x=1|); + $driver->get( $mainpage . q|?logout.x=1| ); like( $driver->get_title(), qr(Log in to Koha), 'If logout is requested, login form should be displayed' ); - $patron->flags(1)->store; # superlibrarian permission + $patron->flags(1)->store; # superlibrarian permission $s->auth( $patron->userid, $password ); - like( $driver->get_title, qr(Koha staff interface), 'Patron with flags superlibrarian should be able to login' ); + like( + $driver->get_title, qr(Koha staff interface), + 'Patron with flags superlibrarian should be able to login' + ); subtest 'not authorized' => sub { plan tests => 17; # First, logout! - $driver->get($mainpage . q|?logout.x=1|); - $patron->flags(4)->store; # Patron has only catalogue permission + $driver->get( $mainpage . q|?logout.x=1| ); + $patron->flags(4)->store; # Patron has only catalogue permission like( $driver->get_title, qr(Log in to Koha), 'Patron should hit the login form after logout' ); + # Login! - $s->fill_form({ userid => $patron->userid, password => $password }); + $s->fill_form( { userid => $patron->userid, password => $password } ); $s->driver->find_element('//input[@id="submit-button"]')->click; - my $cookie = $driver->get_cookie_named('CGISESSID'); + my $cookie = $driver->get_cookie_named('CGISESSID'); my $first_sessionID = $cookie->{value}; # Patron is logged in and got a CGISESSID cookie, miam @@ -103,6 +110,7 @@ SKIP: { # Unauthorized page redirect to the login form $driver->get( $s->base_url . q|circ/circulation.pl| ); like( $driver->get_title, qr(Access denied), 'Patron cannot access the circulation module' ); + # But the patron does not lose the CGISESSID cookie! $cookie = $driver->get_cookie_named('CGISESSID'); is( $cookie->{value}, $first_sessionID, 'no new session if unauthorized page is hit' ); @@ -116,9 +124,11 @@ SKIP: { # As well as the search $driver->get( $s->base_url . q|catalogue/search.pl| ); like( $driver->get_title, qr(Advanced search), 'Patron can access advanced search' ); + # But circulation module is prohibided! $driver->get( $s->base_url . q|circ/circulation.pl| ); like( $driver->get_title, qr(Access denied), 'Patron cannot access the circulation module' ); + # Still can reuse the same cookie $cookie = $driver->get_cookie_named('CGISESSID'); is( $cookie->{value}, $first_sessionID, 'no new session if unauthorized page is hit' ); @@ -131,10 +141,17 @@ SKIP: { # Check with a script that is using check_cookie_auth, session must not be deleted! $driver->get( $s->base_url . q|svc/checkouts| ); + #FIXME - 500 is the current behaviour, but it's not nice. It could be improved. - like( $driver->get_title, qr(An Error Occurred), 'Patron cannot access svc script where circulate permissions are required'); + like( + $driver->get_title, qr(An Error Occurred), + 'Patron cannot access svc script where circulate permissions are required' + ); $driver->get( $s->base_url . q|catalogue/search.pl| ); - like( $driver->get_title, qr(Advanced search), 'Patron can reuse the cookie after a script that used check_cookie_auth' ); + like( + $driver->get_title, qr(Advanced search), + 'Patron can reuse the cookie after a script that used check_cookie_auth' + ); $cookie = $driver->get_cookie_named('CGISESSID'); is( $cookie->{value}, $first_sessionID, 'no new session if unauthorized page is hit' ); }; @@ -146,15 +163,19 @@ SKIP: { my $mainpage = $s->opac_base_url . q|opac-main.pl|; - $driver->get($mainpage . q|?logout.x=1|); # Disconnect first! We are logged in if staff and opac interfaces are separated by ports + $driver->get( $mainpage . q|?logout.x=1| ) + ; # Disconnect first! We are logged in if staff and opac interfaces are separated by ports $driver->get($mainpage); - like( $driver->get_title, qr(Koha online catalog), 'Hitting the main page should not redirect to the login form'); + like( + $driver->get_title, qr(Koha online catalog), + 'Hitting the main page should not redirect to the login form' + ); - my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => 0 }}); - my $password = Koha::AuthUtils::generate_password($patron->category); + my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { flags => 0 } } ); + my $password = Koha::AuthUtils::generate_password( $patron->category ); t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 ); - $patron->set_password({ password => $password }); + $patron->set_password( { password => $password } ); # Using the modal $driver->find_element('//a[@class="nav-link login-link loginModal-trigger"]')->click; @@ -177,32 +198,41 @@ SKIP: { $driver->find_element('//div[@id="loginModal"]//input[@class="show-password-toggle-checkbox"]')->click; $driver->find_element('//div[@id="loginModal"]//input[@type="submit"]')->click; - like( $driver->get_title, qr(Koha online catalog), 'Patron without permission should be able to login to the OPAC using the modal' ); + like( + $driver->get_title, qr(Koha online catalog), + 'Patron without permission should be able to login to the OPAC using the modal' + ); $driver->find_element('//div[@id="userdetails"]'); - like( $driver->get_title, qr(Your library home), 'Patron without permissions should be able to login to the OPAC using the modal'); + like( + $driver->get_title, qr(Your library home), + 'Patron without permissions should be able to login to the OPAC using the modal' + ); $driver->find_element('//a[@id="user-menu"]')->click; $driver->find_element('//a[@id="logout"]')->click; - $driver->get($mainpage); # This should not be needed but we the next find_element fails randomly + $driver->get($mainpage); # This should not be needed but we the next find_element fails randomly - { # Temporary debug + { # Temporary debug $driver->error_handler( sub { my ( $driver, $selenium_error ) = @_; print STDERR "\nSTRACE:"; my $i = 1; - while ( (my @call_details = (caller($i++))) ){ - print STDERR "\t" . $call_details[1]. ":" . $call_details[2] . " in " . $call_details[3]."\n"; + while ( ( my @call_details = ( caller( $i++ ) ) ) ) { + print STDERR "\t" + . $call_details[1] . ":" + . $call_details[2] . " in " + . $call_details[3] . "\n"; } print STDERR "\n"; - print STDERR sprintf("Is logged in patron: %s (%s)?\n", $patron->firstname, $patron->surname ); - $s->capture( $driver ); + print STDERR sprintf( "Is logged in patron: %s (%s)?\n", $patron->firstname, $patron->surname ); + $s->capture($driver); croak $selenium_error; } ); - $driver->find_element('//div[@id="login"]'); # logged out - $s->add_error_handler; # Reset to the default error handler + $driver->find_element('//div[@id="login"]'); # logged out + $s->add_error_handler; # Reset to the default error handler } # Using the form on the right @@ -225,39 +255,47 @@ SKIP: { $driver->find_element('//div[@id="login"]//input[@class="show-password-toggle-checkbox"]')->click; $s->submit_form; $driver->find_element('//div[@id="userdetails"]'); - like( $driver->get_title, qr(Your library home), 'Patron without permissions should be able to login to the OPAC using the form on the right'); + like( + $driver->get_title, qr(Your library home), + 'Patron without permissions should be able to login to the OPAC using the form on the right' + ); $driver->find_element('//a[@id="user-menu"]')->click; $driver->find_element('//a[@id="logout"]')->click; - $driver->find_element('//div[@id="login"]'); # logged out + $driver->find_element('//div[@id="login"]'); # logged out - - $patron->flags(4)->store; # catalogue permission + $patron->flags(4)->store; # catalogue permission $s->fill_form( { userid => $patron->userid, password => $password } ); $s->submit_form; $driver->find_element('//div[@id="userdetails"]'); - like( $driver->get_title, qr(Your library home), 'Patron with catalogue permission should be able to login to the OPAC'); + like( + $driver->get_title, qr(Your library home), + 'Patron with catalogue permission should be able to login to the OPAC' + ); $driver->find_element('//a[@id="user-menu"]')->click; $driver->find_element('//a[@id="logout"]')->click; - $driver->find_element('//div[@id="login"]'); # logged out + $driver->find_element('//div[@id="login"]'); # logged out - $patron->flags(1)->store; # superlibrarian permission + $patron->flags(1)->store; # superlibrarian permission $s->fill_form( { userid => $patron->userid, password => $password } ); $s->submit_form; $driver->find_element('//div[@id="userdetails"]'); - like( $driver->get_title, qr(Your library home), 'Patron with superlibrarian permission should be able to login to the OPAC'); + like( + $driver->get_title, qr(Your library home), + 'Patron with superlibrarian permission should be able to login to the OPAC' + ); $driver->find_element('//a[@id="user-menu"]')->click; $driver->find_element('//a[@id="logout"]')->click; - $driver->find_element('//div[@id="login"]'); # logged out + $driver->find_element('//div[@id="login"]'); # logged out subtest 'not authorized' => sub { plan tests => 13; - $driver->get($mainpage . q|?logout.x=1|); + $driver->get( $mainpage . q|?logout.x=1| ); $driver->get($mainpage); - my $cookie = $driver->get_cookie_named('CGISESSID'); + my $cookie = $driver->get_cookie_named('CGISESSID'); my $first_sessionID = $cookie->{value}; # User is not logged in, navigation does not generate a new cookie @@ -281,12 +319,13 @@ SKIP: { is( $cookie->{value}, $first_sessionID, ); # Logged in user can place holds - $driver->get( $s->opac_base_url . q|opac-reserve.pl| ); # We may need to pass a biblionumber here in the future + $driver->get( $s->opac_base_url . q|opac-reserve.pl| ) + ; # We may need to pass a biblionumber here in the future like( $driver->get_title, qr(Placing a hold) ); $cookie = $driver->get_cookie_named('CGISESSID'); is( $cookie->{value}, $first_sessionID, ); - $driver->get($mainpage . q|?logout.x=1|); + $driver->get( $mainpage . q|?logout.x=1| ); # FIXME This new get should not be needed, but the cookie is not modified right after logout # However it's not the behaviour when testing the UI @@ -298,8 +337,10 @@ SKIP: { $first_sessionID = $cookie->{value}; $driver->get( $s->opac_base_url . q|svc/checkout_notes| ); + #FIXME - 500 is the current behaviour, but it's not nice. It could be improved. - like( $driver->get_title, qr(An error has occurred), 'Patron cannot access svc'); + like( $driver->get_title, qr(An error has occurred), 'Patron cannot access svc' ); + # No new cookie generated $cookie = $driver->get_cookie_named('CGISESSID'); is( $cookie->{value}, $first_sessionID, ); @@ -322,14 +363,14 @@ SKIP: { my $mainpage = $s->base_url . q|mainpage.pl|; - my $patron_1 = $builder->build_object({ class => 'Koha::Patrons', value => { flags => 1 }}); - my $patron_2 = $builder->build_object({ class => 'Koha::Patrons', value => { flags => 0 }}); + my $patron_1 = $builder->build_object( { class => 'Koha::Patrons', value => { flags => 1 } } ); + my $patron_2 = $builder->build_object( { class => 'Koha::Patrons', value => { flags => 0 } } ); my $password = 'password'; t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 ); - $patron_1->set_password({ password => $password }); - $patron_2->set_password({ password => $password }); + $patron_1->set_password( { password => $password } ); + $patron_2->set_password( { password => $password } ); - $driver->get($mainpage . q|?logout.x=1|); + $driver->get( $mainpage . q|?logout.x=1| ); $s->auth( $patron_2->userid, $password ); like( $driver->get_title, qr(Access denied), 'Patron without permissions should not be able to login' ); @@ -341,8 +382,8 @@ SKIP: { }; $driver->quit(); -}; +} END { $_->delete for @data_to_cleanup; -}; +} diff --git a/t/db_dependent/selenium/authentication_2fa.t b/t/db_dependent/selenium/authentication_2fa.t index 9ef2e22cb0..0a7a7bb880 100755 --- a/t/db_dependent/selenium/authentication_2fa.t +++ b/t/db_dependent/selenium/authentication_2fa.t @@ -33,80 +33,89 @@ SKIP: { eval { require Selenium::Remote::Driver; }; skip "Selenium::Remote::Driver is needed for selenium tests.", 2 if $@; - my $builder = t::lib::TestBuilder->new; + my $builder = t::lib::TestBuilder->new; my $library_name = 'my ❤ library'; my $library = $builder->build_object( { class => 'Koha::Libraries', value => { branchname => $library_name } } ); - my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { flags => 1, branchcode => $library->branchcode } } ); - $patron->flags(1)->store; # superlibrarian permission - my $password = Koha::AuthUtils::generate_password($patron->category); + my $patron = $builder->build_object( + { class => 'Koha::Patrons', value => { flags => 1, branchcode => $library->branchcode } } ); + $patron->flags(1)->store; # superlibrarian permission + my $password = Koha::AuthUtils::generate_password( $patron->category ); t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 ); - $patron->set_password({ password => $password }); + $patron->set_password( { password => $password } ); push @data_to_cleanup, $patron, $patron->category, $patron->library; - my $s = t::lib::Selenium->new({ login => $patron->userid, password => $password }); - my $driver = $s->driver; + my $s = t::lib::Selenium->new( { login => $patron->userid, password => $password } ); + my $driver = $s->driver; subtest 'Setup' => sub { plan tests => 13; my $mainpage = $s->base_url . q|mainpage.pl|; $driver->get($mainpage); - like( $driver->get_title, qr(Log in to Koha), 'Hitting the main page should redirect to the login form'); + like( $driver->get_title, qr(Log in to Koha), 'Hitting the main page should redirect to the login form' ); - C4::Context->set_preference('TwoFactorAuthentication', 'disabled'); + C4::Context->set_preference( 'TwoFactorAuthentication', 'disabled' ); fill_login_form($s); - like( $driver->get_title, qr(Koha staff interface), 'Patron with flags superlibrarian should be able to login' ); + like( + $driver->get_title, qr(Koha staff interface), + 'Patron with flags superlibrarian should be able to login' + ); - $driver->get($s->base_url . q|members/two_factor_auth.pl|); + $driver->get( $s->base_url . q|members/two_factor_auth.pl| ); like( $driver->get_title, qr(Error 404), 'Must be redirected to 404 is the pref is off' ); - C4::Context->set_preference('TwoFactorAuthentication', 'enabled'); - $driver->get($s->base_url . q|members/two_factor_auth.pl|); + C4::Context->set_preference( 'TwoFactorAuthentication', 'enabled' ); + $driver->get( $s->base_url . q|members/two_factor_auth.pl| ); like( $driver->get_title, qr(Two-factor authentication), 'Must be on the page with the pref on' ); is( - $driver->find_element( '//div[@id="registration-status-disabled"]/div[@class="alert alert-info two-factor-status"]' )->get_text, + $driver->find_element( + '//div[@id="registration-status-disabled"]/div[@class="alert alert-info two-factor-status"]')->get_text, 'Status: Disabled', '2FA is disabled' ); is( - $driver->find_element( '//div[@id="registration-status-enabled"]/div[@class="alert alert-info two-factor-status"]' )->get_text, - '', # 'Status: Enabled' is not shown + $driver->find_element( + '//div[@id="registration-status-enabled"]/div[@class="alert alert-info two-factor-status"]')->get_text, + '', # 'Status: Enabled' is not shown '2FA is disabled' ); $driver->find_element('//*[@id="enable-2FA"]')->click; $s->wait_for_ajax; - ok($driver->find_element('//img[@id="qr_code"]'), 'There is a QR code'); - is($driver->find_element('//span[@id="issuer"]')->get_text, $library_name); + ok( $driver->find_element('//img[@id="qr_code"]'), 'There is a QR code' ); + is( $driver->find_element('//span[@id="issuer"]')->get_text, $library_name ); $driver->find_element('//*[@id="pin_code"]')->send_keys('wrong_code'); $driver->find_element('//*[@id="register-2FA"]')->click; $s->wait_for_ajax; - ok($driver->find_element('//div[@class="alert alert-error"][contains(text(), "Invalid PIN code")]')); + ok( $driver->find_element('//div[@class="alert alert-error"][contains(text(), "Invalid PIN code")]') ); is( $patron->get_from_storage->secret, undef, 'secret is not set in DB yet' ); my $secret32 = $driver->find_element('//*[@id="secret32"]')->get_value(); - my $auth = Koha::Auth::TwoFactorAuth->new({patron => $patron, secret32 => $secret32}); - my $code = $auth->code(); + my $auth = Koha::Auth::TwoFactorAuth->new( { patron => $patron, secret32 => $secret32 } ); + my $code = $auth->code(); $driver->find_element('//*[@id="pin_code"]')->clear; $driver->find_element('//*[@id="pin_code"]')->send_keys($code); $driver->find_element('//*[@id="register-2FA"]')->click; + # Wait for the response then go to the page, don't wait for the redirect $s->wait_for_ajax; - $driver->get($s->base_url . q|members/two_factor_auth.pl|); + $driver->get( $s->base_url . q|members/two_factor_auth.pl| ); is( - $driver->find_element( '//div[@id="registration-status-disabled"]/div[@class="alert alert-info two-factor-status"]' )->get_text, - '', # 'Status: Disabled' is not shown + $driver->find_element( + '//div[@id="registration-status-disabled"]/div[@class="alert alert-info two-factor-status"]')->get_text, + '', # 'Status: Disabled' is not shown '2FA is enabled' ); is( - $driver->find_element( '//div[@id="registration-status-enabled"]/div[@class="alert alert-info two-factor-status"]' )->get_text, + $driver->find_element( + '//div[@id="registration-status-enabled"]/div[@class="alert alert-info two-factor-status"]')->get_text, 'Status: Enabled', '2FA is enabled' ); @@ -122,16 +131,15 @@ SKIP: { my $mainpage = $s->base_url . q|mainpage.pl|; my $secret32 = $patron->decoded_secret; - { # ok first try - $driver->get($mainpage . q|?logout.x=1|); - $driver->get($s->base_url . q|circ/circulation.pl?borrowernumber=|.$patron->borrowernumber); + { # ok first try + $driver->get( $mainpage . q|?logout.x=1| ); + $driver->get( $s->base_url . q|circ/circulation.pl?borrowernumber=| . $patron->borrowernumber ); like( $driver->get_title, qr(Log in to Koha), 'Must be on the first auth screen' ); fill_login_form($s); like( $driver->get_title, qr(Two-factor authentication), 'Must be on the second auth screen' ); is( login_error($s), undef ); - my $auth = Koha::Auth::TwoFactorAuth->new( - { patron => $patron, secret32 => $secret32 } ); + my $auth = Koha::Auth::TwoFactorAuth->new( { patron => $patron, secret32 => $secret32 } ); my $code = $auth->code(); $auth->clear; $driver->find_element('//form[@id="loginform"]//input[@id="otp_token"]')->send_keys($code); @@ -139,9 +147,9 @@ SKIP: { like( $driver->get_title, qr(Checking out to ), 'Must be redirected to the original page' ); } - { # second try and logout - $driver->get($mainpage . q|?logout.x=1|); - $driver->get($s->base_url . q|circ/circulation.pl?borrowernumber=|.$patron->borrowernumber); + { # second try and logout + $driver->get( $mainpage . q|?logout.x=1| ); + $driver->get( $s->base_url . q|circ/circulation.pl?borrowernumber=| . $patron->borrowernumber ); like( $driver->get_title, qr(Log in to Koha), 'Must be on the first auth screen' ); fill_login_form($s); like( $driver->get_title, qr(Two-factor authentication), 'Must be on the second auth screen' ); @@ -158,10 +166,10 @@ SKIP: { is( login_error($s), undef ); } - { # second try and success + { # second try and success - $driver->get($mainpage . q|?logout.x=1|); - $driver->get($s->base_url . q|circ/circulation.pl?borrowernumber=|.$patron->borrowernumber); + $driver->get( $mainpage . q|?logout.x=1| ); + $driver->get( $s->base_url . q|circ/circulation.pl?borrowernumber=| . $patron->borrowernumber ); like( $driver->get_title, qr(Log in to Koha), 'Must be on the first auth screen' ); like( login_error($s), qr(Session timed out) ); fill_login_form($s); @@ -171,8 +179,7 @@ SKIP: { $driver->find_element('//input[@type="submit"]')->click; is( login_error($s), "Invalid two-factor code" ); - my $auth = Koha::Auth::TwoFactorAuth->new( - { patron => $patron, secret32 => $secret32 } ); + my $auth = Koha::Auth::TwoFactorAuth->new( { patron => $patron, secret32 => $secret32 } ); my $code = $auth->code(); $auth->clear; $driver->find_element('//form[@id="loginform"]//input[@id="otp_token"]')->send_keys($code); @@ -264,30 +271,33 @@ SKIP: { 'Must be on the 2FA auth setup screen' ); - $s->wait_for_ajax; # There is an ajax request to populate the qr_code and the secret + $s->wait_for_ajax; # There is an ajax request to populate the qr_code and the secret $driver->set_window_size( 3840, 1080 ); $s->wait_for_element_visible('//*[@id="registration-form"]'); isnt( $driver->find_element('//*[@id="qr_code"]')->get_attribute("src"), "" ); my $secret32 = $driver->find_element('//*[@id="secret32"]')->get_value; - my $auth = Koha::Auth::TwoFactorAuth->new( - { patron => $patron, secret32 => $secret32 } ); + my $auth = Koha::Auth::TwoFactorAuth->new( { patron => $patron, secret32 => $secret32 } ); my $pin_code = $auth->code; $driver->find_element('//*[@id="pin_code"]')->send_keys("wrong code"); $driver->find_element('//*[@id="register-2FA"]')->click; $s->wait_for_ajax; - is( $driver->find_element('//*[@id="errors"]')->get_text, - "Invalid PIN code" ); + is( + $driver->find_element('//*[@id="errors"]')->get_text, + "Invalid PIN code" + ); $driver->find_element('//*[@id="pin_code"]')->clear; $driver->find_element('//*[@id="pin_code"]')->send_keys($pin_code); $driver->find_element('//*[@id="register-2FA"]')->click; - is( $s->get_next_alert_text, + is( + $s->get_next_alert_text, "Two-factor authentication correctly configured. You will be redirected to the login screen." ); $driver->accept_alert; + # FIXME How to test the redirect to the mainpage here $patron = $patron->get_from_storage; @@ -304,20 +314,21 @@ SKIP: { my $auth = Koha::Auth::TwoFactorAuth->new( { patron => $patron } ); my $code = $auth->code(); $auth->clear; - $driver->find_element('//form[@id="loginform"]//input[@id="otp_token"]') - ->send_keys($code); + $driver->find_element('//form[@id="loginform"]//input[@id="otp_token"]')->send_keys($code); $driver->find_element('//input[@type="submit"]')->click; $driver->get( $s->base_url . q|members/two_factor_auth.pl| ); is( - $driver->find_element( '//div[@id="registration-status-disabled"]/div[@class="alert alert-info two-factor-status"]' )->get_text, - '', # 'Status: Disabled' is not shown + $driver->find_element( + '//div[@id="registration-status-disabled"]/div[@class="alert alert-info two-factor-status"]')->get_text, + '', # 'Status: Disabled' is not shown '2FA is enabled' ); is( - $driver->find_element( '//div[@id="registration-status-enabled"]/div[@class="alert alert-info two-factor-status"]' )->get_text, + $driver->find_element( + '//div[@id="registration-status-enabled"]/div[@class="alert alert-info two-factor-status"]')->get_text, 'Status: Enabled', '2FA is enabled' ); @@ -325,34 +336,35 @@ SKIP: { $driver->find_element('//form[@id="two-factor-auth"]//input[@type="submit"]')->click; is( - $driver->find_element( '//div[@id="registration-status-disabled"]/div[@class="alert alert-info two-factor-status"]' )->get_text, + $driver->find_element( + '//div[@id="registration-status-disabled"]/div[@class="alert alert-info two-factor-status"]')->get_text, 'Status: Disabled', '2FA is disabled' ); is( - $driver->find_element( '//div[@id="registration-status-enabled"]/div[@class="alert alert-info two-factor-status"]' )->get_text, - '', # 'Status: Enabled' is not shown + $driver->find_element( + '//div[@id="registration-status-enabled"]/div[@class="alert alert-info two-factor-status"]')->get_text, + '', # 'Status: Enabled' is not shown '2FA is disabled' ); $patron = $patron->get_from_storage; - is( $patron->secret, undef, "Secret has been cleared" ); + is( $patron->secret, undef, "Secret has been cleared" ); is( $patron->auth_method(), 'password', 'auth_method has been reset to "password"' ); }; $driver->quit(); -}; +} END { $_->delete for @data_to_cleanup; - C4::Context->set_preference('TwoFactorAuthentication', $pref_value); -}; - + C4::Context->set_preference( 'TwoFactorAuthentication', $pref_value ); +} sub login_error { - my ( $s ) = @_; - my $driver = $s->driver; + my ($s) = @_; + my $driver = $s->driver; $s->remove_error_handler; my $login_error = eval { @@ -365,7 +377,7 @@ sub login_error { # Don't use the usual t::lib::Selenium->auth as we don't want the ->get($mainpage) to test the redirect sub fill_login_form { - my ( $s ) = @_; - $s->fill_form({ userid => $s->login, password => $s->password }); + my ($s) = @_; + $s->fill_form( { userid => $s->login, password => $s->password } ); $s->driver->find_element('//input[@id="submit-button"]')->click; } diff --git a/t/db_dependent/selenium/basic_workflow.t b/t/db_dependent/selenium/basic_workflow.t index b58e823e24..b20409c82a 100755 --- a/t/db_dependent/selenium/basic_workflow.t +++ b/t/db_dependent/selenium/basic_workflow.t @@ -15,8 +15,6 @@ # You should have received a copy of the GNU General Public License # along with Koha; if not, see <http://www.gnu.org/licenses>. - - # wget https://selenium-release.storage.googleapis.com/2.53/selenium-server-standalone-2.53.1.jar # Does not work with 3.4, did not test the ones between # sudo apt-get install xvfb firefox-esr # SELENIUM_PATH=/home/vagrant/selenium-server-standalone-2.53.1.jar @@ -35,7 +33,7 @@ use Modern::Perl; use Time::HiRes qw(gettimeofday); -use POSIX qw(strftime); +use POSIX qw(strftime); use C4::Context; use C4::Biblio qw( AddBiblio ); @@ -47,7 +45,7 @@ use MARC::Field; use t::lib::Selenium; -my $dbh = C4::Context->dbh; +my $dbh = C4::Context->dbh; my $number_of_biblios_to_insert = 3; our $sample_data = { @@ -71,17 +69,17 @@ our $sample_data = { notforloan => 0, }, issuingrule => { - categorycode => 'test_cat', - itemtype => 'IT4test', - branchcode => undef, - maxissueqty => '5', - issuelength => '5', - lengthunit => 'days', - renewalperiod => '5', + categorycode => 'test_cat', + itemtype => 'IT4test', + branchcode => undef, + maxissueqty => '5', + issuelength => '5', + lengthunit => 'days', + renewalperiod => '5', reservesallowed => '5', - onshelfholds => '1', - opacitemholds => 'Y', - }, + onshelfholds => '1', + opacitemholds => 'Y', + }, }; our ( $borrowernumber, $start, $prev_time, $cleanup_needed ); @@ -91,23 +89,23 @@ SKIP: { $cleanup_needed = 1; - $dbh->do(q|INSERT INTO itemtypes(itemtype) VALUES (?)|, undef, $sample_data->{itemtype}{itemtype}); + $dbh->do( q|INSERT INTO itemtypes(itemtype) VALUES (?)|, undef, $sample_data->{itemtype}{itemtype} ); open my $fh, '>>', '/tmp/output.txt'; my $s = t::lib::Selenium->new; - my $driver = $s->driver; + my $driver = $s->driver; my $base_url = $s->base_url; - $start = gettimeofday; + $start = gettimeofday; $prev_time = $start; - $driver->get($base_url."mainpage.pl"); + $driver->get( $base_url . "mainpage.pl" ); like( $driver->get_title(), qr(Log in to Koha), ); $s->auth; time_diff("main"); - $driver->get($base_url.'admin/categories.pl'); + $driver->get( $base_url . 'admin/categories.pl' ); like( $driver->get_title(), qr(Patron categories), ); $driver->find_element('//a[@id="newcategory"]')->click; like( $driver->get_title(), qr(New category), ); @@ -115,12 +113,13 @@ SKIP: { $driver->find_element('//fieldset[@class="action"]/input[@type="submit"]')->click; time_diff("add patron category"); - $driver->get($base_url.'/members/memberentry.pl?op=add_form&categorycode='.$sample_data->{category}{categorycode}); + $driver->get( + $base_url . '/members/memberentry.pl?op=add_form&categorycode=' . $sample_data->{category}{categorycode} ); like( $driver->get_title(), qr(Add .*$sample_data->{category}{description}), ); $s->fill_form( $sample_data->{patron} ); $driver->find_element('//button[@id="saverecord"]')->click; my $borrowernumber = Koha::Patrons->_resultset->get_column('borrowernumber')->max; - $driver->get($base_url.'/members/moremember.pl?borrowernumber='.$borrowernumber); + $driver->get( $base_url . '/members/moremember.pl?borrowernumber=' . $borrowernumber ); like( $driver->get_title(), qr(Patron details for $sample_data->{patron}{surname}), ); ####$driver->get($base_url.'/members/members-home.pl'); @@ -130,28 +129,31 @@ SKIP: { time_diff("add patron"); - $borrowernumber = $dbh->selectcol_arrayref(q|SELECT borrowernumber FROM borrowers WHERE userid=?|, {}, $sample_data->{patron}{userid} )->[0]; + $borrowernumber = $dbh->selectcol_arrayref( + q|SELECT borrowernumber FROM borrowers WHERE userid=?|, {}, + $sample_data->{patron}{userid} + )->[0]; my $itemtype = $sample_data->{itemtype}; my @biblionumbers; for my $i ( 1 .. $number_of_biblios_to_insert ) { my $biblio = MARC::Record->new(); - my $title = 'test biblio '.$i; + my $title = 'test biblio ' . $i; if ( C4::Context->preference('marcflavour') eq 'UNIMARC' ) { $biblio->append_fields( - MARC::Field->new('200', ' ', ' ', a => 'test biblio '.$i), - MARC::Field->new('200', ' ', ' ', f => 'test author '.$i), - MARC::Field->new('200', ' ', ' ', b => $itemtype->{itemtype}), + MARC::Field->new( '200', ' ', ' ', a => 'test biblio ' . $i ), + MARC::Field->new( '200', ' ', ' ', f => 'test author ' . $i ), + MARC::Field->new( '200', ' ', ' ', b => $itemtype->{itemtype} ), ); } else { $biblio->append_fields( - MARC::Field->new('245', ' ', ' ', a => 'test biblio '.$i), - MARC::Field->new('100', ' ', ' ', a => 'test author '.$i), - MARC::Field->new('942', ' ', ' ', c => $itemtype->{itemtype}), + MARC::Field->new( '245', ' ', ' ', a => 'test biblio ' . $i ), + MARC::Field->new( '100', ' ', ' ', a => 'test author ' . $i ), + MARC::Field->new( '942', ' ', ' ', c => $itemtype->{itemtype} ), ); } - my ($biblionumber, $biblioitemnumber) = AddBiblio($biblio, ''); + my ( $biblionumber, $biblioitemnumber ) = AddBiblio( $biblio, '' ); push @biblionumbers, $biblionumber; } @@ -163,7 +165,7 @@ SKIP: { categorycode => $issuing_rules->{categorycode}, itemtype => $issuing_rules->{itemtype}, branchcode => $issuing_rules->{branchcode}, - rules => { + rules => { maxissueqty => $issuing_rules->{maxissueqty}, issuelength => $issuing_rules->{issuelength}, lengthunit => $issuing_rules->{lengthunit}, @@ -172,18 +174,21 @@ SKIP: { onshelfholds => $issuing_rules->{onshelfholds}, opacitemholds => $issuing_rules->{opacitemholds}, - } + } } ); - - for my $biblionumber ( @biblionumbers ) { - $driver->get($base_url."/cataloguing/additem.pl?biblionumber=$biblionumber"); + for my $biblionumber (@biblionumbers) { + $driver->get( $base_url . "/cataloguing/additem.pl?biblionumber=$biblionumber" ); like( $driver->get_title(), qr(test biblio \d+ by test author), ); my $form = $driver->find_element('//form[@name="f"]'); + # select the text inputs that don't have display:none - my $inputs = $driver->find_child_elements($form, '/.//*[not(self::node()[contains(@style,"display:none")])]/*[@type="text"]'); - for my $input ( @$inputs ) { + my $inputs = $driver->find_child_elements( + $form, + '/.//*[not(self::node()[contains(@style,"display:none")])]/*[@type="text"]' + ); + for my $input (@$inputs) { my $id = $input->get_attribute('id'); next unless $id =~ m|^tag_952_subfield|; @@ -191,75 +196,80 @@ SKIP: { my $v; # FIXME This is based on default values - if ( $id =~ m|^tag_952_subfield_g| # price - or $id =~ m|^tag_952_subfield_v| ) # replacementprice + if ( + $id =~ m|^tag_952_subfield_g| # price + or $id =~ m|^tag_952_subfield_v| + ) # replacementprice + { + $v = '42'; # It's a price + } elsif ( + $id =~ m|^tag_952_subfield_f| #tag_952_subfield_g + ) { - $v = '42'; # It's a price - } - elsif ( - $id =~ m|^tag_952_subfield_f| #tag_952_subfield_g - ) { # It's a varchar(10) $v = 't_value_x'; - } - elsif ( - $id =~ m|^tag_952_subfield_w| # replacementpricedate - ) { - next; # The input has been prefilled with %Y-%m-%d already - } - elsif ( - $id =~ m|^tag_952_subfield_y| # itemtype - ) { - next; # auto-filled - } - elsif ( - $id =~ m|^tag_952_subfield_d| # dateaccessioned - ) { - next; # The input has been prefilled with %Y-%m-%d already - } - elsif ( - $id =~ m|^tag_952_subfield_3| # materials - ) { - $v = ""; # We don't want the checkin/checkout to need confirmation if CircConfirmItemParts is on - } - else { + } elsif ( + $id =~ m|^tag_952_subfield_w| # replacementpricedate + ) + { + next; # The input has been prefilled with %Y-%m-%d already + } elsif ( + $id =~ m|^tag_952_subfield_y| # itemtype + ) + { + next; # auto-filled + } elsif ( + $id =~ m|^tag_952_subfield_d| # dateaccessioned + ) + { + next; # The input has been prefilled with %Y-%m-%d already + } elsif ( + $id =~ m|^tag_952_subfield_3| # materials + ) + { + $v = ""; # We don't want the checkin/checkout to need confirmation if CircConfirmItemParts is on + } else { $v = 't_value_bib' . $biblionumber; } - $effective_input->send_keys( $v ); + $effective_input->send_keys($v); } # Find itemtype select2 and open it my $itype_select = $driver->find_element('//*[@id="subfield952y"]/span[1]'); $itype_select->click; + # Select an itemtype - my $options = $driver->find_elements('.select2-results__option', 'css'); + my $options = $driver->find_elements( '.select2-results__option', 'css' ); @$options[0]->click; $driver->find_element('//input[@name="add_submit"]')->click; like( $driver->get_title(), qr(Items.*Record #$biblionumber) ); - $dbh->do(q|UPDATE items SET notforloan=0 WHERE biblionumber=?|, {}, $biblionumber ); - $dbh->do(q|UPDATE biblioitems SET itemtype=? WHERE biblionumber=?|, {}, $itemtype->{itemtype}, $biblionumber); - $dbh->do(q|UPDATE items SET itype=? WHERE biblionumber=?|, {}, $itemtype->{itemtype}, $biblionumber); + $dbh->do( q|UPDATE items SET notforloan=0 WHERE biblionumber=?|, {}, $biblionumber ); + $dbh->do( q|UPDATE biblioitems SET itemtype=? WHERE biblionumber=?|, {}, $itemtype->{itemtype}, $biblionumber ); + $dbh->do( q|UPDATE items SET itype=? WHERE biblionumber=?|, {}, $itemtype->{itemtype}, $biblionumber ); } time_diff("add items"); my $nb_of_checkouts = 0; - for my $biblionumber ( @biblionumbers ) { - $driver->get($base_url."/circ/circulation.pl?borrowernumber=".$borrowernumber); - $driver->find_element('//input[@id="barcode"]')->send_keys('t_value_bib'.$biblionumber); + for my $biblionumber (@biblionumbers) { + $driver->get( $base_url . "/circ/circulation.pl?borrowernumber=" . $borrowernumber ); + $driver->find_element('//input[@id="barcode"]')->send_keys( 't_value_bib' . $biblionumber ); $driver->find_element('//fieldset[@id="circ_circulation_issue"]/button[@type="submit"]')->click; $nb_of_checkouts++; like( $driver->get_title(), qr(Checking out to $sample_data->{patron}{surname}) ); - like( $driver->find_element('//a[@href="#checkouts_panel"]')->get_attribute('text'), qr/Checkouts \($nb_of_checkouts\)/ ); + like( + $driver->find_element('//a[@href="#checkouts_panel"]')->get_attribute('text'), + qr/Checkouts \($nb_of_checkouts\)/ + ); } time_diff("checkout"); - for my $biblionumber ( @biblionumbers ) { - $driver->get($base_url."/circ/returns.pl"); - $driver->find_element('//input[@id="barcode"]')->send_keys('t_value_bib'.$biblionumber); + for my $biblionumber (@biblionumbers) { + $driver->get( $base_url . "/circ/returns.pl" ); + $driver->find_element('//input[@id="barcode"]')->send_keys( 't_value_bib' . $biblionumber ); $driver->find_element('//*[@id="circ_returns_checkin"]//button[@type="submit"]')->click; like( $driver->get_title(), qr(Check in test biblio \d+) ); } @@ -267,14 +277,16 @@ SKIP: { time_diff("checkin"); #Place holds - $driver->get($base_url."/reserve/request.pl?borrowernumber=$borrowernumber&biblionumber=".$biblionumbers[0]); - $driver->find_element('//form[@id="hold-request-form"]//button[@type="submit"]')->click; # Biblio level - $driver->pause(1000); # This seems wrong, since bug 19618 the hold is created async with an AJAX call. Not sure what is happening here but the next statements are exectuted before the hold is created and the count is wrong (still 0) + $driver->get( $base_url . "/reserve/request.pl?borrowernumber=$borrowernumber&biblionumber=" . $biblionumbers[0] ); + $driver->find_element('//form[@id="hold-request-form"]//button[@type="submit"]')->click; # Biblio level + $driver->pause(1000) + ; # This seems wrong, since bug 19618 the hold is created async with an AJAX call. Not sure what is happening here but the next statements are exectuted before the hold is created and the count is wrong (still 0) my $patron = Koha::Patrons->find($borrowernumber); is( $patron->holds->count, 1, ); - $driver->get($base_url."/reserve/request.pl?borrowernumber=$borrowernumber&biblionumber=".$biblionumbers[1]); - $driver->find_element('//form[@id="hold-request-form"]//input[@type="radio"]')->click; # Item level, there is only 1 item per bib so we are safe + $driver->get( $base_url . "/reserve/request.pl?borrowernumber=$borrowernumber&biblionumber=" . $biblionumbers[1] ); + $driver->find_element('//form[@id="hold-request-form"]//input[@type="radio"]') + ->click; # Item level, there is only 1 item per bib so we are safe $driver->find_element('//form[@id="hold-request-form"]//button[@type="submit"]')->click; $driver->pause(1000); is( $patron->holds->count, 2, ); @@ -283,31 +295,37 @@ SKIP: { close $fh; $driver->quit(); -}; +} END { cleanup() if $cleanup_needed; -}; +} sub cleanup { my $dbh = C4::Context->dbh; - $dbh->do(q|DELETE FROM issues where borrowernumber=?|, {}, $borrowernumber); - $dbh->do(q|DELETE FROM old_issues where borrowernumber=?|, {}, $borrowernumber); + $dbh->do( q|DELETE FROM issues where borrowernumber=?|, {}, $borrowernumber ); + $dbh->do( q|DELETE FROM old_issues where borrowernumber=?|, {}, $borrowernumber ); for my $i ( 1 .. $number_of_biblios_to_insert ) { - $dbh->do(qq|DELETE items, biblio FROM biblio INNER JOIN items ON biblio.biblionumber = items.biblionumber WHERE biblio.title = "test biblio$i"|); - }; - $dbh->do(q|DELETE FROM borrowers WHERE userid = ?|, {}, $sample_data->{patron}{userid}); - $dbh->do(q|DELETE FROM categories WHERE categorycode = ?|, {}, $sample_data->{category}{categorycode}); + $dbh->do( + qq|DELETE items, biblio FROM biblio INNER JOIN items ON biblio.biblionumber = items.biblionumber WHERE biblio.title = "test biblio$i"| + ); + } + $dbh->do( q|DELETE FROM borrowers WHERE userid = ?|, {}, $sample_data->{patron}{userid} ); + $dbh->do( q|DELETE FROM categories WHERE categorycode = ?|, {}, $sample_data->{category}{categorycode} ); for my $i ( 1 .. $number_of_biblios_to_insert ) { $dbh->do(qq|DELETE FROM biblio WHERE title = "test biblio $i"|); - }; - $dbh->do(q|DELETE FROM itemtypes WHERE itemtype=?|, undef, $sample_data->{itemtype}{itemtype}); - $dbh->do(q|DELETE FROM circulation_rules WHERE categorycode=? AND itemtype=? AND branchcode=?|, undef, $sample_data->{issuingrule}{categorycode}, $sample_data->{issuingrule}{itemtype}, $sample_data->{issuingrule}{branchcode}); + } + $dbh->do( q|DELETE FROM itemtypes WHERE itemtype=?|, undef, $sample_data->{itemtype}{itemtype} ); + $dbh->do( + q|DELETE FROM circulation_rules WHERE categorycode=? AND itemtype=? AND branchcode=?|, undef, + $sample_data->{issuingrule}{categorycode}, $sample_data->{issuingrule}{itemtype}, + $sample_data->{issuingrule}{branchcode} + ); } sub time_diff { my $lib = shift; my $now = gettimeofday; - warn "CP $lib = " . sprintf("%.2f", $now - $prev_time ) . "\n"; + warn "CP $lib = " . sprintf( "%.2f", $now - $prev_time ) . "\n"; $prev_time = $now; } diff --git a/t/db_dependent/selenium/batch_item_modification.t b/t/db_dependent/selenium/batch_item_modification.t index acb5cac3eb..32c62f1516 100755 --- a/t/db_dependent/selenium/batch_item_modification.t +++ b/t/db_dependent/selenium/batch_item_modification.t @@ -36,9 +36,9 @@ SKIP: { eval { require Selenium::Remote::Driver; }; skip "Selenium::Remote::Driver is needed for selenium tests.", 2 if $@; - my $s = t::lib::Selenium->new; - my $driver = $s->driver; - $driver->set_window_size(3840,1080); + my $s = t::lib::Selenium->new; + my $driver = $s->driver; + $driver->set_window_size( 3840, 1080 ); my $mainpage = $s->base_url . q|mainpage.pl|; $driver->get($mainpage); like( $driver->get_title(), qr(Log in to Koha), ); @@ -48,19 +48,16 @@ SKIP: { my $item = $builder->build_sample_item; # Navigate to the batch item mod tool - $s->click( - { href => '/cataloguing/cataloging-home.pl', main => 'container-main' } - ); - $s->click( - { href => 'tools/batchMod.pl', main_class => 'main container-fluid' } ); - $driver->find_element('//textarea[@id="barcodelist"]')->send_keys($item->barcode); + $s->click( { href => '/cataloguing/cataloging-home.pl', main => 'container-main' } ); + $s->click( { href => 'tools/batchMod.pl', main_class => 'main container-fluid' } ); + $driver->find_element('//textarea[@id="barcodelist"]')->send_keys( $item->barcode ); $s->submit_form; my $itemnotes = q{✔ ❤ ★}; - $driver->find_element('//input[@name="items.itemnotes"]') - ->send_keys($itemnotes); + $driver->find_element('//input[@name="items.itemnotes"]')->send_keys($itemnotes); $s->submit_form; - my $view_detail_link = $driver->find_element('//a[contains(@href, "/cgi-bin/koha/admin/background_jobs.pl?op=view&id=")]'); + my $view_detail_link = + $driver->find_element('//a[contains(@href, "/cgi-bin/koha/admin/background_jobs.pl?op=view&id=")]'); my $href = $view_detail_link->get_attribute('href'); my $job_id; if ( $href =~ m{id=(\d+)} ) { @@ -72,9 +69,9 @@ SKIP: { sleep(1); last if ++$i > 10; } - is ( $job->status, 'finished', 'job is finished' ); + is( $job->status, 'finished', 'job is finished' ); - is( Koha::Items->find($item->itemnumber)->itemnotes, $itemnotes ); + is( Koha::Items->find( $item->itemnumber )->itemnotes, $itemnotes ); push @cleanup, $item, $item->biblio; }; @@ -84,4 +81,4 @@ SKIP: { END { $_->delete for @cleanup; -}; +} diff --git a/t/db_dependent/selenium/patrons_search.t b/t/db_dependent/selenium/patrons_search.t index b1a1bf7cf1..e76505711f 100755 --- a/t/db_dependent/selenium/patrons_search.t +++ b/t/db_dependent/selenium/patrons_search.t @@ -38,7 +38,7 @@ use t::lib::Selenium; use t::lib::TestBuilder; eval { require Selenium::Remote::Driver; }; -if ( $@ ) { +if ($@) { plan skip_all => "Selenium::Remote::Driver is needed for selenium tests."; } else { plan tests => 2; @@ -51,7 +51,7 @@ my $base_url = $s->base_url; my $builder = t::lib::TestBuilder->new; my $schema = Koha::Database->schema; -if ( Koha::Patrons->search({surname => {-like => "test_patron_%"}})->count ) { +if ( Koha::Patrons->search( { surname => { -like => "test_patron_%" } } )->count ) { BAIL_OUT("Cannot run this test, data we need to create already exist in the DB"); } @@ -66,6 +66,7 @@ my ( $attribute_type, $attribute_type_searchable_1, $attribute_type_searchable_2, $attribute_type_searchable_not_default, $patron_category, $library ); + sub setup { $patron_category = $builder->build_object( { @@ -81,14 +82,14 @@ sub setup { my @patrons; for my $i ( 1 .. 25 ) { push @patrons, - $builder->build_object( + $builder->build_object( { class => 'Koha::Patrons', value => { surname => "test_patron_" . $i++, firstname => $firstname, preferred_name => $firstname, - middle_name => q{}, # We don't want to copy the logic from patron_to_html + middle_name => q{}, # We don't want to copy the logic from patron_to_html othernames => q{}, categorycode => $patron_category->categorycode, branchcode => $library->branchcode, @@ -97,7 +98,7 @@ sub setup { email => $email, } } - ); + ); } push @patrons, $builder->build_object( @@ -105,9 +106,9 @@ sub setup { class => 'Koha::Patrons', value => { surname => "test", - firstname => "not_p_a_t_r_o_n", # won't match 'patron' + firstname => "not_p_a_t_r_o_n", # won't match 'patron' preferred_name => "not_p_a_t_r_o_n", - middle_name => q{}, # We don't want to copy the logic from patron_to_html + middle_name => q{}, # We don't want to copy the logic from patron_to_html othernames => q{}, categorycode => $patron_category->categorycode, branchcode => $library->branchcode, @@ -120,20 +121,18 @@ sub setup { unshift @cleanup, $_ for @patrons; - my $library_2 = $builder->build_object( - { class => 'Koha::Libraries', value => { branchname => 'X' . $branchname } } - ); + my $library_2 = + $builder->build_object( { class => 'Koha::Libraries', value => { branchname => 'X' . $branchname } } ); push @cleanup, $library_2; - my $patron_27 = - $builder->build_object( + my $patron_27 = $builder->build_object( { class => 'Koha::Patrons', value => { surname => "test_patron_27", firstname => $firstname, preferred_name => $firstname, - middle_name => q{}, # We don't want to copy the logic from patron_to_html + middle_name => q{}, # We don't want to copy the logic from patron_to_html othernames => q{}, categorycode => $patron_category->categorycode, branchcode => $library_2->branchcode, @@ -143,7 +142,7 @@ sub setup { dateofbirth => '1980-06-17', } } - ); + ); unshift @cleanup, $patron_27; my $patron_28 = $builder->build_object( @@ -162,54 +161,59 @@ sub setup { $attribute_type = Koha::Patron::Attribute::Type->new( { - code => 'my code1', - description => 'my description1', - staff_searchable => 0, + code => 'my code1', + description => 'my description1', + staff_searchable => 0, searched_by_default => 0 } )->store; $attribute_type_searchable_1 = Koha::Patron::Attribute::Type->new( { - code => 'my code2', - description => 'my description2', - opac_display => 1, - staff_searchable => 1, + code => 'my code2', + description => 'my description2', + opac_display => 1, + staff_searchable => 1, searched_by_default => 1 } )->store; $attribute_type_searchable_2 = Koha::Patron::Attribute::Type->new( { - code => 'my code3', - description => 'my description3', - opac_display => 1, - staff_searchable => 1, + code => 'my code3', + description => 'my description3', + opac_display => 1, + staff_searchable => 1, searched_by_default => 1 } )->store; $attribute_type_searchable_not_default = Koha::Patron::Attribute::Type->new( { - code => 'mycode4', - description => 'my description4', - opac_display => 1, - staff_searchable => 1, + code => 'mycode4', + description => 'my description4', + opac_display => 1, + staff_searchable => 1, searched_by_default => 0 } )->store; - push @cleanup, $attribute_type, $attribute_type_searchable_1, $attribute_type_searchable_2, $attribute_type_searchable_not_default; + push @cleanup, $attribute_type, $attribute_type_searchable_1, $attribute_type_searchable_2, + $attribute_type_searchable_not_default; - $patrons[0]->extended_attributes([ - { code => $attribute_type->code, attribute => 'test_attr_1' }, - { code => $attribute_type_searchable_1->code, attribute => 'test_attr_2'}, - { code => $attribute_type_searchable_2->code, attribute => 'test_attr_3'}, - { code => $attribute_type_searchable_not_default->code, attribute => 'test_attr_4'}, - ]); - $patrons[1]->extended_attributes([ - { code => $attribute_type->code, attribute => 'test_attr_1' }, - { code => $attribute_type_searchable_1->code, attribute => 'test_attr_2'}, - { code => $attribute_type_searchable_2->code, attribute => 'test_attr_3'}, - { code => $attribute_type_searchable_not_default->code, attribute => 'test_attr_4'}, - ]); - C4::Context->set_preference('PatronsPerPage', $PatronsPerPage); + $patrons[0]->extended_attributes( + [ + { code => $attribute_type->code, attribute => 'test_attr_1' }, + { code => $attribute_type_searchable_1->code, attribute => 'test_attr_2' }, + { code => $attribute_type_searchable_2->code, attribute => 'test_attr_3' }, + { code => $attribute_type_searchable_not_default->code, attribute => 'test_attr_4' }, + ] + ); + $patrons[1]->extended_attributes( + [ + { code => $attribute_type->code, attribute => 'test_attr_1' }, + { code => $attribute_type_searchable_1->code, attribute => 'test_attr_2' }, + { code => $attribute_type_searchable_2->code, attribute => 'test_attr_3' }, + { code => $attribute_type_searchable_not_default->code, attribute => 'test_attr_4' }, + ] + ); + C4::Context->set_preference( 'PatronsPerPage', $PatronsPerPage ); } sub teardown { @@ -226,63 +230,89 @@ subtest 'Search patrons' => sub { setup(); my $total_number_of_patrons = Koha::Patrons->search->count; - my $table_id = "memberresultst"; + my $table_id = "memberresultst"; $s->auth; - C4::Context->set_preference('DefaultPatronSearchFields',""); - C4::Context->set_preference('DefaultPatronSearchMethod',"contains"); - my $searchable_attributes = Koha::Patron::Attribute::Types->search({ staff_searchable => 1 })->count(); - my $nb_standard_fields = 14 + $searchable_attributes; # Standard fields, plus one searchable attribute + C4::Context->set_preference( 'DefaultPatronSearchFields', "" ); + C4::Context->set_preference( 'DefaultPatronSearchMethod', "contains" ); + my $searchable_attributes = Koha::Patron::Attribute::Types->search( { staff_searchable => 1 } )->count(); + my $nb_standard_fields = 14 + $searchable_attributes; # Standard fields, plus one searchable attribute $driver->get( $base_url . "/members/members-home.pl" ); my @adv_options = $driver->find_elements('//select[@id="searchfieldstype"]/option'); - is( scalar @adv_options, $nb_standard_fields + 1, 'All standard fields are searchable if DefaultPatronSearchFields not set. middle_name is there.'); - is( $adv_options[0]->get_value(), 'standard', 'Standard search uses value "standard"'); + is( + scalar @adv_options, $nb_standard_fields + 1, + 'All standard fields are searchable if DefaultPatronSearchFields not set. middle_name is there.' + ); + is( $adv_options[0]->get_value(), 'standard', 'Standard search uses value "standard"' ); my @filter_options = $driver->find_elements('//select[@class="searchfieldstype_filter"]/option'); - is( scalar @filter_options, $nb_standard_fields + 1, 'All standard fields + middle_name are searchable by filter if DefaultPatronSearchFields not set'); - is( $filter_options[0]->get_value(), 'standard', 'Standard filter uses hard coded value "standard" DefaultPatronSearchFields not set'); - C4::Context->set_preference('DefaultPatronSearchFields',"firstname|initials"); + is( + scalar @filter_options, $nb_standard_fields + 1, + 'All standard fields + middle_name are searchable by filter if DefaultPatronSearchFields not set' + ); + is( + $filter_options[0]->get_value(), 'standard', + 'Standard filter uses hard coded value "standard" DefaultPatronSearchFields not set' + ); + C4::Context->set_preference( 'DefaultPatronSearchFields', "firstname|initials" ); $driver->get( $base_url . "/members/members-home.pl" ); @adv_options = $driver->find_elements('//select[@id="searchfieldstype"]/option'); - is( scalar @adv_options, $nb_standard_fields - 1, 'New option added when DefaultPatronSearchFields is populated with a field. Note that middle_name and preferred_name disappears, we do not want it if not part of DefaultPatronSearchFields'); - is( $adv_options[0]->get_value(), 'standard', 'Standard search uses value "standard"'); + is( + scalar @adv_options, $nb_standard_fields - 1, + 'New option added when DefaultPatronSearchFields is populated with a field. Note that middle_name and preferred_name disappears, we do not want it if not part of DefaultPatronSearchFields' + ); + is( $adv_options[0]->get_value(), 'standard', 'Standard search uses value "standard"' ); @filter_options = $driver->find_elements('//select[@class="searchfieldstype_filter"]/option'); - is( scalar @filter_options, $nb_standard_fields - 1, 'New filter option added when DefaultPatronSearchFields is populated with a field'); - is( $filter_options[0]->get_value(), 'standard', 'Standard filter uses value "standard"'); + is( + scalar @filter_options, $nb_standard_fields - 1, + 'New filter option added when DefaultPatronSearchFields is populated with a field' + ); + is( $filter_options[0]->get_value(), 'standard', 'Standard filter uses value "standard"' ); $driver->get( $base_url . "/members/members-home.pl" ); - @adv_options = $driver->find_elements('//select[@id="searchfieldstype"]/option'); + @adv_options = $driver->find_elements('//select[@id="searchfieldstype"]/option'); @filter_options = $driver->find_elements('//select[@class="searchfieldstype_filter"]/option'); - is( scalar @adv_options, $nb_standard_fields - 1, 'Invalid option not added when DefaultPatronSearchFields is populated with an invalid field'); - is( scalar @filter_options, $nb_standard_fields - 1, 'Invalid filter option not added when DefaultPatronSearchFields is populated with an invalid field'); + is( + scalar @adv_options, $nb_standard_fields - 1, + 'Invalid option not added when DefaultPatronSearchFields is populated with an invalid field' + ); + is( + scalar @filter_options, $nb_standard_fields - 1, + 'Invalid filter option not added when DefaultPatronSearchFields is populated with an invalid field' + ); # NOTE: We should probably ensure the bad field is removed from 'standard' search here, else searches are broken - C4::Context->set_preference('DefaultPatronSearchFields',""); + C4::Context->set_preference( 'DefaultPatronSearchFields', "" ); $driver->get( $base_url . "/members/members-home.pl" ); $s->fill_form( { 'search_patron_filter' => 'test_patron' } ); $s->submit_form; my $first_patron = Koha::Patrons->search( { surname => { like => 'test_patron_%' } } )->next; sleep $DT_delay && $s->wait_for_ajax; - my @td = $driver->find_elements('//table[@id="'.$table_id.'"]/tbody/tr/td'); - like ($td[2]->get_text, qr[\Q$firstname\E], + my @td = $driver->find_elements( '//table[@id="' . $table_id . '"]/tbody/tr/td' ); + like( + $td[2]->get_text, qr[\Q$firstname\E], 'Column "Name" should be the 3rd and contain the firstname correctly filtered' ); - like ($td[2]->get_text, qr[\Q$address\E], + like( + $td[2]->get_text, qr[\Q$address\E], 'Column "Name" should be the 3rd and contain the address correctly filtered' ); - like ($td[2]->get_text, qr[\Q$email\E], + like( + $td[2]->get_text, qr[\Q$email\E], 'Column "Name" should be the 3rd and contain the email address correctly filtered' ); - is( $td[4]->get_text, $branchname, + is( + $td[4]->get_text, $branchname, 'Column "Library" should be the 6th and contain the html tags - they have been html filtered' ); - is( $td[9]->get_text, $borrowernotes_displayed, + is( + $td[9]->get_text, $borrowernotes_displayed, 'Column "Circ note" should be the 10th and not contain the html tags - they have not been html filtered' ); $driver->find_element( - '//a[@href="/cgi-bin/koha/members/memberentry.pl?op=edit_form&destination=circ&borrowernumber=' - . $first_patron->borrowernumber - . '"]' )->click; + '//a[@href="/cgi-bin/koha/members/memberentry.pl?op=edit_form&destination=circ&borrowernumber=' + . $first_patron->borrowernumber + . '"]' )->click; is( $driver->get_title, sprintf( @@ -299,25 +329,54 @@ subtest 'Search patrons' => sub { sleep $DT_delay && $s->wait_for_ajax; clear_filters(); - $s->driver->find_element('//*[@id="'.$table_id.'_wrapper"]//input[@class="dt-input"]')->send_keys('test_patron'); + $s->driver->find_element( '//*[@id="' . $table_id . '_wrapper"]//input[@class="dt-input"]' ) + ->send_keys('test_patron'); sleep $DT_delay && $s->wait_for_ajax; - is( $driver->find_element('//div[@id="'.$table_id.'_wrapper"]//div[@class="dt-info"]')->get_text, sprintf('Showing 1 to %s of %s entries (filtered from %s total entries)', $PatronsPerPage, 26, $total_number_of_patrons), 'Searching in standard brings back correct results' ); + is( + $driver->find_element( '//div[@id="' . $table_id . '_wrapper"]//div[@class="dt-info"]' )->get_text, + sprintf( + 'Showing 1 to %s of %s entries (filtered from %s total entries)', $PatronsPerPage, 26, + $total_number_of_patrons + ), + 'Searching in standard brings back correct results' + ); - $s->driver->find_element('//table[@id="'.$table_id.'"]//th[@data-filter="libraries"]/select/option[@value="'.$first_patron->library->branchcode.'"]')->click; + $s->driver->find_element( '//table[@id="' + . $table_id + . '"]//th[@data-filter="libraries"]/select/option[@value="' + . $first_patron->library->branchcode + . '"]' )->click; sleep $DT_delay && $s->wait_for_ajax; - is( $driver->find_element('//div[@id="'.$table_id.'_wrapper"]//div[@class="dt-info"]')->get_text, sprintf('Showing 1 to %s of %s entries (filtered from %s total entries)', $PatronsPerPage, 25, $total_number_of_patrons), 'Filtering on library works in combination with main search' ); + is( + $driver->find_element( '//div[@id="' . $table_id . '_wrapper"]//div[@class="dt-info"]' )->get_text, + sprintf( + 'Showing 1 to %s of %s entries (filtered from %s total entries)', $PatronsPerPage, 25, + $total_number_of_patrons + ), + 'Filtering on library works in combination with main search' + ); clear_filters(); # And make sure all the patrons are present - is( $driver->find_element('//div[@id="'.$table_id.'_wrapper"]//div[@class="dt-info"]')->get_text, sprintf('Showing 1 to %s of %s entries', $PatronsPerPage, $total_number_of_patrons), 'Resetting filters works as expected' ); + is( + $driver->find_element( '//div[@id="' . $table_id . '_wrapper"]//div[@class="dt-info"]' )->get_text, + sprintf( 'Showing 1 to %s of %s entries', $PatronsPerPage, $total_number_of_patrons ), + 'Resetting filters works as expected' + ); # Pattern terms must be split $s->fill_form( { 'search_patron_filter' => 'test patron' } ); $s->submit_form; sleep $DT_delay && $s->wait_for_ajax; - is( $driver->find_element('//div[@id="'.$table_id.'_wrapper"]//div[@class="dt-info"]')->get_text, sprintf('Showing 1 to %s of %s entries (filtered from %s total entries)', $PatronsPerPage, 27, $total_number_of_patrons) ); + is( + $driver->find_element( '//div[@id="' . $table_id . '_wrapper"]//div[@class="dt-info"]' )->get_text, + sprintf( + 'Showing 1 to %s of %s entries (filtered from %s total entries)', $PatronsPerPage, 27, + $total_number_of_patrons + ) + ); $driver->find_element('//form[@class="patron_search_form"]//*[@class="btn btn-default clear_search"]')->click(); $s->submit_form; sleep $DT_delay && $s->wait_for_ajax; @@ -327,7 +386,11 @@ subtest 'Search patrons' => sub { $s->submit_form; sleep $DT_delay && $s->wait_for_ajax; - is( $driver->find_element('//div[@id="'.$table_id.'_wrapper"]//div[@class="dt-info"]')->get_text, sprintf('No entries to show (filtered from %s total entries)', $total_number_of_patrons), 'Searching on a non-searchable attribute returns no results' ); + is( + $driver->find_element( '//div[@id="' . $table_id . '_wrapper"]//div[@class="dt-info"]' )->get_text, + sprintf( 'No entries to show (filtered from %s total entries)', $total_number_of_patrons ), + 'Searching on a non-searchable attribute returns no results' + ); clear_filters(); @@ -336,37 +399,62 @@ subtest 'Search patrons' => sub { $s->submit_form; sleep $DT_delay && $s->wait_for_ajax; - is( $driver->find_element('//div[@id="'.$table_id.'_wrapper"]//div[@class="dt-info"]')->get_text, sprintf('Showing 1 to %s of %s entries (filtered from %s total entries)', 2, 2, $total_number_of_patrons), 'Searching on a searchable attribute returns correct results' ); + is( + $driver->find_element( '//div[@id="' . $table_id . '_wrapper"]//div[@class="dt-info"]' )->get_text, + sprintf( 'Showing 1 to %s of %s entries (filtered from %s total entries)', 2, 2, $total_number_of_patrons ), + 'Searching on a searchable attribute returns correct results' + ); clear_filters(); - $s->fill_form( { 'search_patron_filter' => 'test_attr_3' } ); # Terms must be split + $s->fill_form( { 'search_patron_filter' => 'test_attr_3' } ); # Terms must be split $s->submit_form; sleep $DT_delay && $s->wait_for_ajax; - is( $driver->find_element('//div[@id="'.$table_id.'_wrapper"]//div[@class="dt-info"]')->get_text, sprintf('Showing 1 to %s of %s entries (filtered from %s total entries)', 2, 2, $total_number_of_patrons), 'Searching on a searchable attribute returns correct results' ); + is( + $driver->find_element( '//div[@id="' . $table_id . '_wrapper"]//div[@class="dt-info"]' )->get_text, + sprintf( 'Showing 1 to %s of %s entries (filtered from %s total entries)', 2, 2, $total_number_of_patrons ), + 'Searching on a searchable attribute returns correct results' + ); clear_filters(); # Search on searchable attribute as specific field, we expect 2 patrons $s->fill_form( { 'search_patron_filter' => 'test_attr_4' } ); - $driver->find_element('//form[@class="patron_search_form"]//*[@class="searchfieldstype_filter"]//option[@value="_ATTR_'.$attribute_type_searchable_not_default->code.'"]')->click(); + $driver->find_element( + '//form[@class="patron_search_form"]//*[@class="searchfieldstype_filter"]//option[@value="_ATTR_' + . $attribute_type_searchable_not_default->code + . '"]' )->click(); $s->submit_form; sleep $DT_delay && $s->wait_for_ajax; - is( $driver->find_element('//div[@id="'.$table_id.'_wrapper"]//div[@class="dt-info"]')->get_text, sprintf('Showing 1 to %s of %s entries (filtered from %s total entries)', 2, 2, $total_number_of_patrons), 'Searching on a searchable attribute as a specific field returns correct results' ); + is( + $driver->find_element( '//div[@id="' . $table_id . '_wrapper"]//div[@class="dt-info"]' )->get_text, + sprintf( 'Showing 1 to %s of %s entries (filtered from %s total entries)', 2, 2, $total_number_of_patrons ), + 'Searching on a searchable attribute as a specific field returns correct results' + ); # Refine search and search for test_patron in all the data using the DT global search # No change in result expected, still 2 patrons - $s->driver->find_element('//*[@id="'.$table_id.'_wrapper"]//input[@class="dt-input"]')->send_keys('test_patron'); + $s->driver->find_element( '//*[@id="' . $table_id . '_wrapper"]//input[@class="dt-input"]' ) + ->send_keys('test_patron'); sleep $DT_delay && $s->wait_for_ajax; - is( $driver->find_element('//div[@id="'.$table_id.'_wrapper"]//div[@class="dt-info"]')->get_text, sprintf('Showing 1 to %s of %s entries (filtered from %s total entries)', 2, 2, $total_number_of_patrons), 'Refining with DataTables search works to further filter the original query' ); + is( + $driver->find_element( '//div[@id="' . $table_id . '_wrapper"]//div[@class="dt-info"]' )->get_text, + sprintf( 'Showing 1 to %s of %s entries (filtered from %s total entries)', 2, 2, $total_number_of_patrons ), + 'Refining with DataTables search works to further filter the original query' + ); # Adding the surname of the first patron in the "Name" column # We expect only 1 result - $s->driver->find_element('//table[@id="'.$table_id.'"]//input[@placeholder="Name search"]')->send_keys($first_patron->surname); + $s->driver->find_element( '//table[@id="' . $table_id . '"]//input[@placeholder="Name search"]' ) + ->send_keys( $first_patron->surname ); sleep $DT_delay && $s->wait_for_ajax; - is( $driver->find_element('//div[@id="'.$table_id.'_wrapper"]//div[@class="dt-info"]')->get_text, sprintf('Showing 1 to %s of %s entries (filtered from %s total entries)', 1, 1, $total_number_of_patrons), 'Refining with header filters works to further filter the original query' ); + is( + $driver->find_element( '//div[@id="' . $table_id . '_wrapper"]//div[@class="dt-info"]' )->get_text, + sprintf( 'Showing 1 to %s of %s entries (filtered from %s total entries)', 1, 1, $total_number_of_patrons ), + 'Refining with header filters works to further filter the original query' + ); subtest 'limited categories' => sub { @@ -403,8 +491,7 @@ subtest 'Search patrons' => sub { my $patron_selected_text = $driver->find_element('//div[@id="table_search_selections"]/span')->get_text; is( $patron_selected_text, "", "Patrons selected is not displayed" ); - my @checkboxes = $driver->find_elements( - '//input[@type="checkbox"][@name="borrowernumber"]'); + my @checkboxes = $driver->find_elements('//input[@type="checkbox"][@name="borrowernumber"]'); $checkboxes[2]->click; $patron_selected_text = $driver->find_element('//div[@id="table_search_selections"]/span')->get_text; is( $patron_selected_text, "Patrons selected: 1", "One patron selected" ); @@ -415,8 +502,7 @@ subtest 'Search patrons' => sub { $driver->find_element('//*[@id="memberresultst_wrapper"]//button[@class="dt-paging-button next"]')->click; sleep $DT_delay && $s->wait_for_ajax; - @checkboxes = $driver->find_elements( - '//input[@type="checkbox"][@name="borrowernumber"]'); + @checkboxes = $driver->find_elements('//input[@type="checkbox"][@name="borrowernumber"]'); $checkboxes[0]->click; $patron_selected_text = $driver->find_element('//div[@id="table_search_selections"]/span')->get_text; is( $patron_selected_text, "Patrons selected: 3", "Three patrons are selected" ); @@ -437,8 +523,11 @@ subtest 'Search patrons' => sub { $driver->find_element('//button[@id="add_to_patron_list_submit"]')->click; sleep $DT_delay && $s->wait_for_ajax; is( $driver->find_element('//*[@id="patron_list_dialog"]')->get_text, "Added 3 patrons to $patron_list_name." ); - my $patron_list = $schema->resultset('PatronList')->search({ name => $patron_list_name })->next; - is( $schema->resultset('PatronListPatron')->search({ patron_list_id => $patron_list->patron_list_id })->count, 3 ); + my $patron_list = $schema->resultset('PatronList')->search( { name => $patron_list_name } )->next; + is( + $schema->resultset('PatronListPatron')->search( { patron_list_id => $patron_list->patron_list_id } )->count, + 3 + ); $patron_list->delete; }; @@ -449,7 +538,8 @@ subtest 'Search patrons' => sub { C4::Context->set_preference( 'dateformat', 'metric' ); sub get_dob_search_filter { - return $s->driver->find_element( '//table[@id="' . shift . '"]//th[@aria-label="Date of birth: Activate to sort"]/input' ); + return $s->driver->find_element( + '//table[@id="' . shift . '"]//th[@aria-label="Date of birth: Activate to sort"]/input' ); } # We have a patron with date of birth=1980-06-17 => formatted as 17/06/1980 @@ -582,7 +672,7 @@ subtest 'Search patrons in modal' => sub { my $table_id = "memberresultst"; my $mainpage = $s->base_url . q|mainpage.pl|; - $driver->get($mainpage . q|?logout.x=1|); + $driver->get( $mainpage . q|?logout.x=1| ); $s->auth; # Go to the add patron form @@ -622,8 +712,8 @@ subtest 'Search patrons in modal' => sub { is( $driver->find_element('//div[@id="patron_preview_modal"]//h1')->get_text(), sprintf( - "%s %s %s (%s)", $patron->title, $patron->firstname, - $patron->surname, $patron->cardnumber + "%s %s %s (%s)", $patron->title, $patron->firstname, + $patron->surname, $patron->cardnumber ), 'Patron preview modal has correct content' ); @@ -661,13 +751,16 @@ subtest 'Search patrons in modal' => sub { my $table_id = "patron_search_modal_owner_table"; my $mainpage = $s->base_url . q|mainpage.pl|; - $driver->get($mainpage . q|?logout.x=1|); + $driver->get( $mainpage . q|?logout.x=1| ); $s->auth; # Go to the add patron form my $fund = $builder->build_object( { class => 'Koha::Acquisition::Funds' } ); push @cleanup, $fund->budget, $fund; - $driver->get( $base_url . sprintf "/admin/aqbudgets.pl?op=add_form&budget_id=%s&budget_period_id=%s", $fund->budget_id, $fund->budget_period_id ); + $driver->get( + $base_url . sprintf "/admin/aqbudgets.pl?op=add_form&budget_id=%s&budget_period_id=%s", + $fund->budget_id, $fund->budget_period_id + ); # Click "Select owner" $driver->find_element('//a[@href="#patron_search_modal_owner"]')->click(); @@ -773,8 +866,8 @@ subtest 'Search patrons in modal' => sub { is( $driver->find_element('//div[@id="patron_preview_modal"]//h1')->get_text(), sprintf( - "%s %s %s (%s)", $patron->title, $patron->firstname, - $patron->surname, $patron->cardnumber + "%s %s %s (%s)", $patron->title, $patron->firstname, + $patron->surname, $patron->cardnumber ) ); diff --git a/t/db_dependent/selenium/regressions.t b/t/db_dependent/selenium/regressions.t index 6c7fed8b0e..4b47effe86 100755 --- a/t/db_dependent/selenium/regressions.t +++ b/t/db_dependent/selenium/regressions.t @@ -24,7 +24,7 @@ use Test::More; use Test::MockModule; use C4::Context; -use C4::Biblio qw( AddBiblio ); +use C4::Biblio qw( AddBiblio ); use C4::Circulation qw( AddIssue ); use Koha::AuthUtils; use t::lib::Mocks; @@ -33,7 +33,7 @@ use t::lib::TestBuilder; use t::lib::Mocks; eval { require Selenium::Remote::Driver; }; -if ( $@ ) { +if ($@) { plan skip_all => "Selenium::Remote::Driver is needed for selenium tests."; } else { plan tests => 9; @@ -41,17 +41,17 @@ if ( $@ ) { my $s = t::lib::Selenium->new; -my $driver = $s->driver; +my $driver = $s->driver; my $opac_base_url = $s->opac_base_url; -my $base_url = $s->base_url; -my $builder = t::lib::TestBuilder->new; +my $base_url = $s->base_url; +my $builder = t::lib::TestBuilder->new; # It seems that we do not have enough records indexed with ES my $SearchEngine_value = C4::Context->preference('SearchEngine'); -C4::Context->set_preference('SearchEngine', 'Zebra'); +C4::Context->set_preference( 'SearchEngine', 'Zebra' ); my $AudioAlerts_value = C4::Context->preference('AudioAlerts'); -C4::Context->set_preference('AudioAlerts', '1'); +C4::Context->set_preference( 'AudioAlerts', '1' ); our @cleanup; @@ -96,23 +96,26 @@ subtest 'SCI can load error pages' => sub { subtest 'OPAC - borrowernumber, branchcode and categorycode as html attributes' => sub { plan tests => 3; - my $patron = $builder->build_object( - { class => 'Koha::Patrons', value => { flags => 1 } } ); - my $password = Koha::AuthUtils::generate_password($patron->category); + my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { flags => 1 } } ); + my $password = Koha::AuthUtils::generate_password( $patron->category ); t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 ); - $patron->set_password({ password => $password }); + $patron->set_password( { password => $password } ); $s->opac_auth( $patron->userid, $password ); my $elt = $driver->find_element('//span[@class="loggedinusername"]'); - is( $elt->get_attribute('data-branchcode', 1), $patron->library->branchcode, + is( + $elt->get_attribute( 'data-branchcode', 1 ), $patron->library->branchcode, "Since bug 20921 span.loggedinusername should contain data-branchcode" - # No idea why we need the second param of get_attribute(). As - # data-branchcode is still there after page finished loading. + + # No idea why we need the second param of get_attribute(). As + # data-branchcode is still there after page finished loading. ); - is( $elt->get_attribute('data-borrowernumber', 1), $patron->borrowernumber, -"Since bug 20921 span.loggedinusername should contain data-borrowernumber" + is( + $elt->get_attribute( 'data-borrowernumber', 1 ), $patron->borrowernumber, + "Since bug 20921 span.loggedinusername should contain data-borrowernumber" ); - is( $elt->get_attribute('data-categorycode', 1), $patron->categorycode, -"Since bug 26847 span.loggedinusername should contain data-categorycode" + is( + $elt->get_attribute( 'data-categorycode', 1 ), $patron->categorycode, + "Since bug 26847 span.loggedinusername should contain data-categorycode" ); push @cleanup, $patron, $patron->category, $patron->library; }; @@ -128,8 +131,10 @@ subtest 'OPAC - Bibliographic record detail page must contain the data-biblionum $driver->get( $opac_base_url . "opac-detail.pl?biblionumber=$biblionumber" ); my $elt = $driver->find_element('//div[@id="catalogue_detail_biblio"]'); - is( $elt->get_attribute( 'data-biblionumber', 1 ), - $biblionumber, "#catalogue_detail_biblio contains data-biblionumber" ); + is( + $elt->get_attribute( 'data-biblionumber', 1 ), + $biblionumber, "#catalogue_detail_biblio contains data-biblionumber" + ); push @cleanup, $biblio; }; @@ -138,10 +143,10 @@ subtest 'Bibliographic record detail page must not explode even with invalid met plan tests => 2; my $builder = t::lib::TestBuilder->new; - my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => 0 }}); + my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { flags => 0 } } ); my $mainpage = $s->base_url . q|mainpage.pl|; - $driver->get($mainpage . q|?logout.x=1|); + $driver->get( $mainpage . q|?logout.x=1| ); like( $driver->get_title(), qr(Log in to Koha), ); $s->auth; @@ -164,24 +169,25 @@ subtest 'Bibliographic record detail page must not explode even with invalid met $driver->get( $base_url . "/catalogue/detail.pl?biblionumber=$biblionumber" ); my $biberror = $driver->find_element('//p[@class="biberror"]')->get_text(); - is( $biberror, "There is at least one encoding error with this bibliographic record, the view may be degraded."); + is( $biberror, "There is at least one encoding error with this bibliographic record, the view may be degraded." ); push @cleanup, $biblio; }; subtest 'Play sound on the circulation page' => sub { plan tests => 1; - my $builder = t::lib::TestBuilder->new; - my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => 0 }}); + my $builder = t::lib::TestBuilder->new; + my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { flags => 0 } } ); my $mainpage = $s->base_url . q|mainpage.pl|; - $driver->get($mainpage . q|?logout.x=1|); + $driver->get( $mainpage . q|?logout.x=1| ); like( $driver->get_title(), qr(Log in to Koha), ); $s->auth; $driver->get( $base_url . "/circ/circulation.pl?borrowernumber=" . $patron->borrowernumber ); - my $audio_node = $driver->find_element('//span[@id="audio-alert"]/audio[@src="/intranet-tmpl/prog/sound/beep.ogg"]'); + my $audio_node = + $driver->find_element('//span[@id="audio-alert"]/audio[@src="/intranet-tmpl/prog/sound/beep.ogg"]'); push @cleanup, $patron, $patron->category, $patron->library; }; @@ -199,8 +205,8 @@ subtest 'Display circulation table correctly' => sub { ); my ( $biblionumber, $biblioitemnumber ) = add_biblio(); - my $item_type = $builder->build_object({ class => 'Koha::ItemTypes' }); - my $item = $builder->build_sample_item( + my $item_type = $builder->build_object( { class => 'Koha::ItemTypes' } ); + my $item = $builder->build_sample_item( { biblionumber => $biblionumber, library => $library->branchcode, @@ -218,42 +224,40 @@ subtest 'Display circulation table correctly' => sub { C4::Circulation::AddIssue( $patron, $item->barcode ); my $mainpage = $s->base_url . q|mainpage.pl|; - $driver->get($mainpage . q|?logout.x=1|); + $driver->get( $mainpage . q|?logout.x=1| ); $s->auth; - $driver->get( $base_url - . "/circ/circulation.pl?borrowernumber=" - . $patron->borrowernumber ); + $driver->get( $base_url . "/circ/circulation.pl?borrowernumber=" . $patron->borrowernumber ); # Display the table clicking on the "Show checkouts" button $driver->find_element('//a[@id="issues-table-load-now-button"]')->click; - my @thead_th = $driver->find_elements('//table[@id="issues-table"]/thead/tr/th'); + my @thead_th = $driver->find_elements('//table[@id="issues-table"]/thead/tr/th'); my $thead_length = 0; - $thead_length += $_->get_attribute('colspan', 1) || 0 for @thead_th; + $thead_length += $_->get_attribute( 'colspan', 1 ) || 0 for @thead_th; - my @tfoot_td = $driver->find_elements('//table[@id="issues-table"]/tfoot/tr/td'); + my @tfoot_td = $driver->find_elements('//table[@id="issues-table"]/tfoot/tr/td'); my $tfoot_length = 0; - $tfoot_length += $_->get_attribute('colspan', 1) || 0 for @tfoot_td; + $tfoot_length += $_->get_attribute( 'colspan', 1 ) || 0 for @tfoot_td; - my @tbody_td = $driver->find_elements('//table[@id="issues-table"]/tbody/tr[2]/td'); + my @tbody_td = $driver->find_elements('//table[@id="issues-table"]/tbody/tr[2]/td'); my $tbody_length = 0; $tbody_length += 1 for @tbody_td; - is( $thead_length == $tfoot_length && $tfoot_length == $tbody_length, - 1, "Checkouts table must be correctly aligned" ) - or diag( - "thead: $thead_length ; tfoot: $tfoot_length ; tbody: $tbody_length"); + is( + $thead_length == $tfoot_length && $tfoot_length == $tbody_length, + 1, "Checkouts table must be correctly aligned" + ) or diag("thead: $thead_length ; tfoot: $tfoot_length ; tbody: $tbody_length"); push @cleanup, $patron->checkouts, $item, $item->biblio, $patron, - $patron->category, $library; + $patron->category, $library; }; subtest 'XSS vulnerabilities in pagination' => sub { plan tests => 3; - my $patron = $builder->build_object({ class => 'Koha::Patrons' }); - for ( 1 .. 30 ) { # We want the pagination to be displayed + my $patron = $builder->build_object( { class => 'Koha::Patrons' } ); + for ( 1 .. 30 ) { # We want the pagination to be displayed push @cleanup, $builder->build_object( { class => 'Koha::Virtualshelves', @@ -267,9 +271,9 @@ subtest 'XSS vulnerabilities in pagination' => sub { ); } - my $password = Koha::AuthUtils::generate_password($patron->category); + my $password = Koha::AuthUtils::generate_password( $patron->category ); t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 ); - $patron->set_password({ password => $password }); + $patron->set_password( { password => $password } ); $s->opac_auth( $patron->userid, $password ); my $public_lists = $s->opac_base_url . q|opac-shelves.pl?op=list&public=1|; @@ -290,7 +294,10 @@ subtest 'XSS vulnerabilities in pagination' => sub { is( $alert_text, undef, 'No alert box displayed, even if evil intent' ); my $second_page = $driver->find_element('//div[@class="pages"]/span[@class="currentPage"]/following-sibling::a'); - like( $second_page->get_attribute('href'), qr{(?|&)public=1(&|$)}, 'The second page should display category without the invalid value' ); + like( + $second_page->get_attribute('href'), qr{(?|&)public=1(&|$)}, + 'The second page should display category without the invalid value' + ); push @cleanup, $patron, $patron->category, $patron->library; @@ -309,7 +316,7 @@ subtest 'Encoding in session variables' => sub { ); my $biblio = $builder->build_sample_biblio; - my $item = $builder->build_sample_item( + my $item = $builder->build_sample_item( { biblionumber => $biblio->biblionumber, library => $library->branchcode, @@ -317,11 +324,10 @@ subtest 'Encoding in session variables' => sub { ); my $original_SessionStorage = C4::Context->preference('SessionStorage'); - for my $SessionStorage ( qw( memcached mysql tmp ) ) { + for my $SessionStorage (qw( memcached mysql tmp )) { C4::Context->set_preference( 'SessionStorage', $SessionStorage ); for my $branchname (qw( Test1 Test2❤️ Test3ä )) { - my $library = - Koha::Libraries->find($branchname) || $builder->build_object( + my $library = Koha::Libraries->find($branchname) || $builder->build_object( { class => 'Koha::Libraries', value => { @@ -329,50 +335,52 @@ subtest 'Encoding in session variables' => sub { branchname => $branchname, } } - ); + ); + # Make sure we are logged in $driver->get( $base_url . q|mainpage.pl?logout.x=1| ); $s->auth; + # Switch to the new library $driver->get( $base_url . 'circ/set-library.pl' ); $s->fill_form( { 'set-library-branch' => $branchname } ); $s->submit_form; + # Check an item out - $driver->get( $base_url - . 'circ/circulation.pl?borrowernumber=' - . $patron->borrowernumber ); + $driver->get( $base_url . 'circ/circulation.pl?borrowernumber=' . $patron->borrowernumber ); + # We must have the logged-in-branch-name displayed, or we got a 500 is( - $driver->find_element( '//span[@class="logged-in-branch-name"]')->get_text(), + $driver->find_element('//span[@class="logged-in-branch-name"]')->get_text(), $branchname, - sprintf( "logged-in-branch-name set - SessionStorage=%s, branchname=%s", $SessionStorage, $branchname - ) + sprintf( "logged-in-branch-name set - SessionStorage=%s, branchname=%s", $SessionStorage, $branchname ) ); $driver->find_element('//input[@id="barcode"]')->send_keys( $item->barcode ); $driver->find_element('//fieldset[@id="circ_circulation_issue"]/button[@type="submit"]')->click; # Display the table clicking on the "Show checkouts" button - $driver->find_element('//a[@id="issues-table-load-now-button"]') - ->click; + $driver->find_element('//a[@id="issues-table-load-now-button"]')->click; - my @tds = $driver->find_elements( - '//table[@id="issues-table"]/tbody/tr[2]/td'); + my @tds = $driver->find_elements('//table[@id="issues-table"]/tbody/tr[2]/td'); # Select the td for "Checked out from" (FIXME this is not robust and could be improved my $td_checked_out_from = $tds[8]; is( $td_checked_out_from->get_text(), $branchname, - sprintf( "'Checked out from' column should contain the branchname - SessionStorage=%s, branchname=%s", $SessionStorage, $branchname ) + sprintf( + "'Checked out from' column should contain the branchname - SessionStorage=%s, branchname=%s", + $SessionStorage, $branchname + ) ); # Remove the check in - Koha::Checkouts->find({ itemnumber => $item->itemnumber })->delete; + Koha::Checkouts->find( { itemnumber => $item->itemnumber } )->delete; } } - C4::Context->set_preference('SessionStorage', $original_SessionStorage); + C4::Context->set_preference( 'SessionStorage', $original_SessionStorage ); push @cleanup, $item, $biblio, $patron, $patron->category, $patron->library; push @cleanup, Koha::Libraries->find($_) for qw( Test1 Test2❤️ Test3ä ); @@ -383,7 +391,7 @@ subtest 'OPAC - Suggest for purchase' => sub { my $builder = t::lib::TestBuilder->new; - my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { flags => 1 } } ); + my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { flags => 1 } } ); my $password = Koha::AuthUtils::generate_password( $patron->category ); t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 ); $patron->set_password( { password => $password } ); @@ -393,10 +401,12 @@ subtest 'OPAC - Suggest for purchase' => sub { my $biblio = Koha::Biblios->find($biblionumber); $driver->get( $opac_base_url . "opac-detail.pl?biblionumber=$biblionumber" ); - $s->click({ href => '/opac-suggestions.pl?op=add_form&biblionumber=' . $biblionumber }); - is( $driver->find_element('//a[@id="title"]')->get_text(), + $s->click( { href => '/opac-suggestions.pl?op=add_form&biblionumber=' . $biblionumber } ); + is( + $driver->find_element('//a[@id="title"]')->get_text(), $biblio->title, - "Suggestion's title correctly filled in with biblio's title" ); + "Suggestion's title correctly filled in with biblio's title" + ); $driver->find_element('//textarea[@id="note"]')->send_keys('some notes'); $s->submit_form; @@ -405,22 +415,21 @@ subtest 'OPAC - Suggest for purchase' => sub { is( $suggestions->count, 1, 'Suggestion created' ); my $suggestion = $suggestions->next; is( $suggestion->title, $biblio->title, q{suggestion's title has biblio's title} ); - is( $suggestion->note, 'some notes', q{suggestion's note correctly saved} ); + is( $suggestion->note, 'some notes', q{suggestion's note correctly saved} ); push @cleanup, $biblio, $suggestion; }; - $driver->quit(); END { - C4::Context->set_preference('SearchEngine', $SearchEngine_value); - C4::Context->set_preference('AudioAlerts', $AudioAlerts_value); + C4::Context->set_preference( 'SearchEngine', $SearchEngine_value ); + C4::Context->set_preference( 'AudioAlerts', $AudioAlerts_value ); $_->delete for @cleanup; -}; +} sub add_biblio { - my ($title, $author) = @_; + my ( $title, $author ) = @_; my $marcflavour = C4::Context->preference('marcflavour'); @@ -428,13 +437,13 @@ sub add_biblio { my ( $tag, $code ); $tag = $marcflavour eq 'UNIMARC' ? '200' : '245'; $biblio->append_fields( - MARC::Field->new($tag, ' ', ' ', a => $title || 'a title'), + MARC::Field->new( $tag, ' ', ' ', a => $title || 'a title' ), ); - ($tag, $code) = $marcflavour eq 'UNIMARC' ? (200, 'f') : (100, 'a'); + ( $tag, $code ) = $marcflavour eq 'UNIMARC' ? ( 200, 'f' ) : ( 100, 'a' ); $biblio->append_fields( - MARC::Field->new($tag, ' ', ' ', $code => $author || 'an author'), + MARC::Field->new( $tag, ' ', ' ', $code => $author || 'an author' ), ); - return C4::Biblio::AddBiblio($biblio, ''); + return C4::Biblio::AddBiblio( $biblio, '' ); } diff --git a/t/db_dependent/selenium/remove_from_cart.t b/t/db_dependent/selenium/remove_from_cart.t index f477e99f63..6424da0da6 100755 --- a/t/db_dependent/selenium/remove_from_cart.t +++ b/t/db_dependent/selenium/remove_from_cart.t @@ -30,7 +30,7 @@ use t::lib::Mocks; use t::lib::Mocks::Zebra; eval { require Selenium::Remote::Driver; }; -if ( $@ ) { +if ($@) { plan skip_all => "Selenium::Remote::Driver is needed for selenium tests."; } else { plan tests => 1; @@ -38,15 +38,15 @@ if ( $@ ) { my $s = t::lib::Selenium->new; -my $driver = $s->driver; +my $driver = $s->driver; my $opac_base_url = $s->opac_base_url; -my $base_url = $s->base_url; -my $builder = t::lib::TestBuilder->new; +my $base_url = $s->base_url; +my $builder = t::lib::TestBuilder->new; my $marcflavour = C4::Context->preference('marcflavour') || 'MARC21'; my $SearchEngine_value = C4::Context->preference('SearchEngine'); -C4::Context->set_preference('SearchEngine', 'Zebra'); +C4::Context->set_preference( 'SearchEngine', 'Zebra' ); my $mock_zebra = t::lib::Mocks::Zebra->new( { @@ -61,49 +61,56 @@ subtest 'OPAC - Remove from cart' => sub { my $sourcedir = dirname(__FILE__) . "/../data"; $mock_zebra->load_records( sprintf( "%s/%s/zebraexport/biblio", $sourcedir, lc($marcflavour) ), - 'iso2709', 'biblios', 1 ); + 'iso2709', 'biblios', 1 + ); $mock_zebra->launch_zebra; # We need to prevent scrolling to prevent the floating toolbar from overlapping buttons we are testing my $window_size = $driver->get_window_size(); - $driver->set_window_size(1920,10800); + $driver->set_window_size( 1920, 10800 ); $driver->get( $opac_base_url . "opac-search.pl?q=d" ); # A better way to do that would be to modify the way we display the basket count # We should show/hide the count instead or recreate the node my @basket_count_elts = $driver->find_elements('//span[@id="basketcount"]/span'); - is( scalar(@basket_count_elts), 0, 'Basket should be empty'); + is( scalar(@basket_count_elts), 0, 'Basket should be empty' ); # This will fail if nothing is indexed, but at this point we should have everything setup correctly - my @checkboxes = $driver->find_elements('//input[@type="checkbox"][@name="biblionumber"]'); + my @checkboxes = $driver->find_elements('//input[@type="checkbox"][@name="biblionumber"]'); my $biblionumber1 = $checkboxes[0]->get_value(); my $biblionumber3 = $checkboxes[2]->get_value(); my $biblionumber5 = $checkboxes[4]->get_value(); - $driver->find_element('//a[@class="btn btn-link btn-sm addtocart cart cart'.$biblionumber1.'"]')->click; + $driver->find_element( '//a[@class="btn btn-link btn-sm addtocart cart cart' . $biblionumber1 . '"]' )->click; my $basket_count_elt = $driver->find_element('//span[@id="basketcount"]/span'); - is( $basket_count_elt->get_text(), - 1, 'One element should have been added to the cart' ); + is( + $basket_count_elt->get_text(), + 1, 'One element should have been added to the cart' + ); - $driver->find_element('//a[@class="btn btn-link btn-sm addtocart cart cart'.$biblionumber3.'"]')->click; - $driver->find_element('//a[@class="btn btn-link btn-sm addtocart cart cart'.$biblionumber5.'"]')->click; + $driver->find_element( '//a[@class="btn btn-link btn-sm addtocart cart cart' . $biblionumber3 . '"]' )->click; + $driver->find_element( '//a[@class="btn btn-link btn-sm addtocart cart cart' . $biblionumber5 . '"]' )->click; $basket_count_elt = $driver->find_element('//span[@id="basketcount"]/span'); - is( $basket_count_elt->get_text(), - 3, '3 elements should have been added to the cart' ); + is( + $basket_count_elt->get_text(), + 3, '3 elements should have been added to the cart' + ); - $driver->find_element('//a[@class="btn btn-link btn-sm remove cartRemove cartR'.$biblionumber3.'"]')->click; + $driver->find_element( '//a[@class="btn btn-link btn-sm remove cartRemove cartR' . $biblionumber3 . '"]' )->click; $basket_count_elt = $driver->find_element('//span[@id="basketcount"]/span'); - is( $basket_count_elt->get_text(), - 2, '1 element should have been removed from the cart' ); + is( + $basket_count_elt->get_text(), + 2, '1 element should have been removed from the cart' + ); # Reset window size - $driver->set_window_size($window_size->{'height'}, $window_size->{'width'}); + $driver->set_window_size( $window_size->{'height'}, $window_size->{'width'} ); $mock_zebra->cleanup; }; END { - C4::Context->set_preference('SearchEngine', $SearchEngine_value); + C4::Context->set_preference( 'SearchEngine', $SearchEngine_value ); $mock_zebra->cleanup if $mock_zebra; -}; +} diff --git a/t/db_dependent/selenium/self_registration.t b/t/db_dependent/selenium/self_registration.t index 3a1b0e7929..93998a1df6 100755 --- a/t/db_dependent/selenium/self_registration.t +++ b/t/db_dependent/selenium/self_registration.t @@ -30,7 +30,7 @@ use t::lib::TestBuilder; use t::lib::Mocks; eval { require Selenium::Remote::Driver; }; -if ( $@ ) { +if ($@) { plan skip_all => "Selenium::Remote::Driver is needed for selenium tests."; } else { plan tests => 2; @@ -38,12 +38,12 @@ if ( $@ ) { my $s = t::lib::Selenium->new; -my $driver = $s->driver; +my $driver = $s->driver; my $opac_base_url = $s->opac_base_url; -my $builder = t::lib::TestBuilder->new; +my $builder = t::lib::TestBuilder->new; my $PatronSelfRegistration_value = C4::Context->preference('PatronSelfRegistration'); -C4::Context->set_preference('PatronSelfRegistration', '1'); +C4::Context->set_preference( 'PatronSelfRegistration', '1' ); my $PatronSelfRegistrationDefaultCategory_value = C4::Context->preference('PatronSelfRegistrationDefaultCategory'); @@ -62,7 +62,7 @@ subtest 'Set flags' => sub { my $default_category = $builder->build_object( { class => 'Koha::Patron::Categories' } ); C4::Context->set_preference( 'PatronSelfRegistrationDefaultCategory', $default_category->categorycode ); - $driver->get($opac_base_url . 'opac-memberentry.pl'); + $driver->get( $opac_base_url . 'opac-memberentry.pl' ); like( $driver->get_title(), qr(Register a new account), ); $driver->find_element('//*[@id="borrower_surname"]')->send_keys("a surname"); @@ -73,17 +73,16 @@ subtest 'Set flags' => sub { $driver->find_element('//*[@id="captcha"]')->send_keys($captcha); $s->submit_form; - my $patron = Koha::Patrons->search({ surname => "a surname" })->next; + my $patron = Koha::Patrons->search( { surname => "a surname" } )->next; is( $patron->flags, undef, 'flags must be undef even if user tried to pass it' ); push @cleanup, $patron; push @cleanup, $default_category; }; - $driver->quit(); END { - C4::Context->set_preference('PatronSelfRegistration', $PatronSelfRegistration_value); - C4::Context->set_preference('PatronSelfRegistration', $PatronSelfRegistrationDefaultCategory_value); + C4::Context->set_preference( 'PatronSelfRegistration', $PatronSelfRegistration_value ); + C4::Context->set_preference( 'PatronSelfRegistration', $PatronSelfRegistrationDefaultCategory_value ); $_->delete for @cleanup; -}; +} diff --git a/t/db_dependent/selenium/system_preferences_search.t b/t/db_dependent/selenium/system_preferences_search.t index 70b8960fe8..b759333c69 100755 --- a/t/db_dependent/selenium/system_preferences_search.t +++ b/t/db_dependent/selenium/system_preferences_search.t @@ -23,7 +23,7 @@ use t::lib::Selenium; use t::lib::TestBuilder; eval { require Selenium::Remote::Driver; }; -if ( $@ ) { +if ($@) { plan skip_all => "Selenium::Remote::Driver is needed for Selenium tests."; } else { plan tests => 1; @@ -40,7 +40,7 @@ my $base_url = $s->base_url; # Adjust the height and width of the generated screenshots #$driver->set_window_size( 2160, 991 ); # Height, then Width -my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { flags => 1 } } ); +my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { flags => 1 } } ); my $password = Koha::AuthUtils::generate_password( $patron->category ); t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 ); $patron->set_password( { password => $password } ); @@ -49,48 +49,73 @@ push @cleanup, $patron, $patron->category, $patron->library; $s->auth( $patron->userid, $password ); -subtest 'Perform a system preferences search for "log", and try to expand/collapse both "Policy" sections that appear' => sub { +subtest + 'Perform a system preferences search for "log", and try to expand/collapse both "Policy" sections that appear' => + sub { plan tests => 6; $driver->get( $base_url . 'admin/preferences.pl?tab=&op=search&searchfield=log' ); + #$driver->capture_screenshot( 'Selenium_00.png' ); my $xpath_v1_expr1 = '//h3[@id="accounting_Policy"]'; # The first "Policy" section should be under the "Accounting" preferences top-level section and be initially expanded - my $first_policy_section_toggle_elt = $driver->find_element( $xpath_v1_expr1 ); - is( $first_policy_section_toggle_elt->get_attribute( 'class' , 1 ), 'expanded', 'The first "Policy" section (under "Accounting") is currently expanded' ); + my $first_policy_section_toggle_elt = $driver->find_element($xpath_v1_expr1); + is( + $first_policy_section_toggle_elt->get_attribute( 'class', 1 ), 'expanded', + 'The first "Policy" section (under "Accounting") is currently expanded' + ); # Clicking on the expand/collapse button should collapse this section $first_policy_section_toggle_elt->click; + #$driver->capture_screenshot( 'Selenium_01.png' ); - is( $first_policy_section_toggle_elt->get_attribute( 'class' , 1 ), 'collapsed', 'The first "Policy" section (under "Accounting") is now collapsed' ); + is( + $first_policy_section_toggle_elt->get_attribute( 'class', 1 ), 'collapsed', + 'The first "Policy" section (under "Accounting") is now collapsed' + ); # Clicking on the expand/collapse button once more should expand this section back to its original state $first_policy_section_toggle_elt->click; + #$driver->capture_screenshot( 'Selenium_02.png' ); - is( $first_policy_section_toggle_elt->get_attribute( 'class' , 1 ), 'expanded', 'The first "Policy" section (under "Accounting") is back to the expanded state' ); + is( + $first_policy_section_toggle_elt->get_attribute( 'class', 1 ), 'expanded', + 'The first "Policy" section (under "Accounting") is back to the expanded state' + ); my $xpath_v1_expr2 = '//h3[@id="acquisitions_Policy"]'; # The second "Policy" section should be under the "Acquisitions" preferences top-level section and be initially expanded - my $second_policy_section_toggle_elt = $driver->find_element( $xpath_v1_expr2 ); - is( $second_policy_section_toggle_elt->get_attribute( 'class' , 1 ), 'expanded', 'The second "Policy" section (under "Acquisitions") is currently expanded' ); + my $second_policy_section_toggle_elt = $driver->find_element($xpath_v1_expr2); + is( + $second_policy_section_toggle_elt->get_attribute( 'class', 1 ), 'expanded', + 'The second "Policy" section (under "Acquisitions") is currently expanded' + ); # Clicking on the expand/collapse button should collapse this section $second_policy_section_toggle_elt->click; + #$driver->capture_screenshot( 'Selenium_03.png' ); - is( $second_policy_section_toggle_elt->get_attribute( 'class' , 1 ), 'collapsed', 'The second "Policy" section (under "Acquisitions") is now collapsed' ); + is( + $second_policy_section_toggle_elt->get_attribute( 'class', 1 ), 'collapsed', + 'The second "Policy" section (under "Acquisitions") is now collapsed' + ); # Clicking on the expand/collapse button once more should expand this section back to its original state $second_policy_section_toggle_elt->click; - #$driver->capture_screenshot( 'Selenium_04.png' ); - is( $second_policy_section_toggle_elt->get_attribute( 'class' , 1 ), 'expanded', 'The second "Policy" section (under "Acquisitions") is back to the expanded state' ); -}; + #$driver->capture_screenshot( 'Selenium_04.png' ); + is( + $second_policy_section_toggle_elt->get_attribute( 'class', 1 ), 'expanded', + 'The second "Policy" section (under "Acquisitions") is back to the expanded state' + ); + + }; # Delete the test patron END { $_->delete for @cleanup; -}; +} diff --git a/t/db_dependent/selenium/update_child_to_adult.t b/t/db_dependent/selenium/update_child_to_adult.t index 8a218e3d3d..96a06be29f 100755 --- a/t/db_dependent/selenium/update_child_to_adult.t +++ b/t/db_dependent/selenium/update_child_to_adult.t @@ -29,7 +29,7 @@ use t::lib::Selenium; use t::lib::TestBuilder; eval { require Selenium::Remote::Driver; }; -if ( $@ ) { +if ($@) { plan skip_all => "Selenium::Remote::Driver is needed for selenium tests."; } else { plan tests => 1; @@ -44,6 +44,7 @@ my $builder = t::lib::TestBuilder->new; our @cleanup; subtest 'Update child to patron' => sub { plan tests => 3; + # We are going to test 3 scénarios: # 1. There are no adults in the DB => no "Update child" link appear # 2. There are at least 2 adults in the DB => a window popup is displayed, letting the librarian choosing the adult category they want @@ -52,8 +53,8 @@ subtest 'Update child to patron' => sub { $s->auth; # Creating the child - my $patron_category_C = $builder->build_object( - { class => 'Koha::Patron::Categories', value => { category_type => 'C' } } ); + my $patron_category_C = + $builder->build_object( { class => 'Koha::Patron::Categories', value => { category_type => 'C' } } ); my $child = $builder->build_object( { @@ -69,26 +70,28 @@ subtest 'Update child to patron' => sub { plan tests => 1; # That's pretty ugly, but we need 0 adult in the DB to really test the whole behaviorà - Koha::Patron::Categories->search({ category_type => 'A' })->update({ category_type => 'Z' }); + Koha::Patron::Categories->search( { category_type => 'A' } )->update( { category_type => 'Z' } ); $driver->get( $base_url . "/members/moremember.pl?borrowernumber=" . $child_borrowernumber ); + # Find the "More" button group, it's the last one # Do not use "More" to select the button, to make it works even when translated $driver->find_element('//div[@id="toolbar"]/div[@class="btn-group"][last()]')->click; $s->remove_error_handler; + # Why ->id is needed to make it fail? # We should expect ->find_element to return 0, but it returns a WebElement (??) my $update_link_id = eval { $driver->find_element('//a[@id="updatechild"]')->id; }; $s->add_error_handler; - is ( $update_link_id, undef, 'No update link should be displayed' ); + is( $update_link_id, undef, 'No update link should be displayed' ); # Resetting the patrons to adult - Koha::Patron::Categories->search({ category_type => 'Z' })->update({ category_type => 'A' }); + Koha::Patron::Categories->search( { category_type => 'Z' } )->update( { category_type => 'A' } ); }; - my $patron_category_A = $builder->build_object( - { class => 'Koha::Patron::Categories', value => { category_type => 'A' } } ); + my $patron_category_A = + $builder->build_object( { class => 'Koha::Patron::Categories', value => { category_type => 'A' } } ); my $adult_1 = $builder->build_object( { class => 'Koha::Patrons', @@ -97,7 +100,7 @@ subtest 'Update child to patron' => sub { } } ); - my $adult_2 = $builder->build_object( # We want at least 2 adults to display the popup window + my $adult_2 = $builder->build_object( # We want at least 2 adults to display the popup window { class => 'Koha::Patrons', value => { @@ -110,25 +113,34 @@ subtest 'Update child to patron' => sub { subtest 'Update child to adult' => sub { plan tests => 3; $driver->get( $base_url . "/members/moremember.pl?borrowernumber=" . $child_borrowernumber ); - $driver->find_element('//div[@id="toolbar"]/div[@class="btn-group"][last()]')->click; # More button group + $driver->find_element('//div[@id="toolbar"]/div[@class="btn-group"][last()]')->click; # More button group my $update_link = $driver->find_element('//a[@id="updatechild"]'); - is($update_link->get_attribute('data-bs-toggle'), undef, 'The update link should not have a data-bs-toggle attribute => not a tooltip and can be clickable'); + is( + $update_link->get_attribute('data-bs-toggle'), undef, + 'The update link should not have a data-bs-toggle attribute => not a tooltip and can be clickable' + ); $update_link->click; - like( $driver->get_current_url, qr{/members/moremember\.pl\?borrowernumber=$child_borrowernumber\#$}, 'Current window has a "#" in the URL, event has been triggered'); + like( + $driver->get_current_url, qr{/members/moremember\.pl\?borrowernumber=$child_borrowernumber\#$}, + 'Current window has a "#" in the URL, event has been triggered' + ); # Switch to the popup window # Note that if there is only 1 adult in the DB the popup does not appears, but an alert instead. Not tested so far. my $handles = $driver->get_window_handles; - $driver->switch_to_window($handles->[1]); - $driver->find_element('//input[@id="catcode'.$patron_category_A->categorycode.'"]')->click; - $driver->set_window_size(1024, 768); + $driver->switch_to_window( $handles->[1] ); + $driver->find_element( '//input[@id="catcode' . $patron_category_A->categorycode . '"]' )->click; + $driver->set_window_size( 1024, 768 ); $s->submit_form; - is( $child->get_from_storage->categorycode, $patron_category_A->categorycode, 'The child should now be an adult!' ); + is( + $child->get_from_storage->categorycode, $patron_category_A->categorycode, + 'The child should now be an adult!' + ); # Switching back to the main window - $driver->switch_to_window($handles->[0]); + $driver->switch_to_window( $handles->[0] ); }; subtest 'Cannot update an adult' => sub { @@ -136,25 +148,30 @@ subtest 'Update child to patron' => sub { # Go to the adult detail view $driver->get( $base_url . "/members/moremember.pl?borrowernumber=$adult_borrowernumber" ); - $driver->find_element('//div[@id="toolbar"]/div[@class="btn-group"][last()]')->click; # More button group + $driver->find_element('//div[@id="toolbar"]/div[@class="btn-group"][last()]')->click; # More button group my $update_li = $driver->find_element('//a[@id="updatechild"]/..'); - is($update_li->get_attribute('data-bs-toggle', 1), 'tooltip', q|The parent of the update link should have a data-bs-toggle attribute => it's a tooltip, not clickable|); + is( + $update_li->get_attribute( 'data-bs-toggle', 1 ), 'tooltip', + q|The parent of the update link should have a data-bs-toggle attribute => it's a tooltip, not clickable| + ); $update_li->click; - like( $driver->get_current_url, qr{/members/moremember\.pl\?borrowernumber=$adult_borrowernumber$}, 'After clicking the link, nothing happens, no # in the URL'); + like( + $driver->get_current_url, qr{/members/moremember\.pl\?borrowernumber=$adult_borrowernumber$}, + 'After clicking the link, nothing happens, no # in the URL' + ); }; my @patrons = ( $adult_1, $adult_2, $child ); - push @cleanup, $_, $_->library, for @patrons; + push @cleanup, $_, $_->library, for @patrons; push @cleanup, $patron_category_A, $patron_category_C; - $driver->quit(); }; END { # Resetting the patrons to adult, in case it has not been done earlier (if failures happened) - Koha::Patron::Categories->search({ category_type => 'Z' })->update({ category_type => 'A' }); + Koha::Patron::Categories->search( { category_type => 'Z' } )->update( { category_type => 'A' } ); $_->delete for @cleanup; } diff --git a/t/db_dependent/sysprefs.t b/t/db_dependent/sysprefs.t index f214bc7719..9f8f5a786b 100755 --- a/t/db_dependent/sysprefs.t +++ b/t/db_dependent/sysprefs.t @@ -34,7 +34,7 @@ C4::Context->set_preference( 'URLLINKTEXT', $newURLLinkText ); is( C4::Context->preference('URLLinkText'), $newURLLinkText, 'The pref should have been set correctly' ); C4::Context->set_preference( 'URLLinkText', $URLLinkText ); -is( C4::Context->preference('URLLINKTEXT'), $URLLinkText, 'A pref name should be case insensitive'); +is( C4::Context->preference('URLLINKTEXT'), $URLLinkText, 'A pref name should be case insensitive' ); $ENV{OVERRIDE_SYSPREF_URLLinkText} = 'this is an override'; C4::Context->clear_syspref_cache(); @@ -44,14 +44,14 @@ is( 'system preference value overridden from environment' ); -is( C4::Context->preference('IDoNotExist'), undef, 'Get a non-existent system preference should return undef'); +is( C4::Context->preference('IDoNotExist'), undef, 'Get a non-existent system preference should return undef' ); C4::Context->set_preference( 'IDoNotExist', 'NonExistent' ); is( C4::Context->preference('IDoNotExist'), 'NonExistent', 'Test creation of non-existent system preference' ); -C4::Context->set_preference('testpreference', 'abc'); +C4::Context->set_preference( 'testpreference', 'abc' ); C4::Context->delete_preference('testpreference'); -is(C4::Context->preference('testpreference'), undef, 'deleting preferences'); +is( C4::Context->preference('testpreference'), undef, 'deleting preferences' ); # Test delete_preference, check cache; we need an example here with MIXED case ! C4::Context->enable_syspref_cache; diff --git a/t/db_dependent/www/auth_values_input_www.t b/t/db_dependent/www/auth_values_input_www.t index 5933658ced..2a93f7aff9 100755 --- a/t/db_dependent/www/auth_values_input_www.t +++ b/t/db_dependent/www/auth_values_input_www.t @@ -18,7 +18,7 @@ use Modern::Perl; use utf8; -use Test::More; #See plan tests => \d+ below +use Test::More; #See plan tests => \d+ below use Test::WWW::Mechanize; use XML::Simple; use JSON; @@ -39,16 +39,12 @@ my $user = $ENV{KOHA_USER} || $xml->{config}->{user}; my $password = $ENV{KOHA_PASS} || $xml->{config}->{pass}; my $intranet = $ENV{KOHA_INTRANET_URL}; -eval{ - use C4::Context; -}; +eval { use C4::Context; }; if ($@) { plan skip_all => "Tests skip. You must have a working Context\n"; -} -elsif (not defined $intranet) { +} elsif ( not defined $intranet ) { plan skip_all => "Tests skip. You must set env. variable KOHA_INTRANET_URL to do tests\n"; -} -else { +} else { plan tests => 30; } @@ -57,94 +53,103 @@ my $dbh = C4::Context->dbh; $intranet =~ s#/$##; my $agent = Test::WWW::Mechanize->new( autocheck => 1 ); -my ($category, $expected_base, $add_form_link_exists); +my ( $category, $expected_base, $add_form_link_exists ); # -------------------------------------------------- LOGIN - $agent->get_ok( "$intranet/cgi-bin/koha/mainpage.pl", 'connect to intranet' ); $agent->form_name('loginform'); $agent->field( 'login_password', $password ); $agent->field( 'login_userid', $user ); -$agent->field( 'branch', '' ); +$agent->field( 'branch', '' ); $agent->click_ok( '', 'login to staff interface' ); $agent->get_ok( "$intranet/cgi-bin/koha/mainpage.pl", 'load main page' ); #---------------------------------------- Test with corean, greek and emoji chars $category = '学協会μμ😀'; -$dbh->do(q|DELETE FROM authorised_values WHERE category = ?|, undef, $category); -$dbh->do(q|DELETE FROM authorised_value_categories WHERE category_name = ?|, undef, $category); +$dbh->do( q|DELETE FROM authorised_values WHERE category = ?|, undef, $category ); +$dbh->do( q|DELETE FROM authorised_value_categories WHERE category_name = ?|, undef, $category ); $expected_base = q|authorised_values.pl|; -$agent->get_ok( "$intranet/cgi-bin/koha/admin/authorised_values.pl", 'Connect to Authorized values page' ); +$agent->get_ok( "$intranet/cgi-bin/koha/admin/authorised_values.pl", 'Connect to Authorized values page' ); $agent->get_ok( "$intranet/cgi-bin/koha/admin/authorised_values.pl?op=add_form", 'Open to create a new category' ); $agent->form_name('Aform'); -$agent->field('category', $category); +$agent->field( 'category', $category ); $agent->click_ok( '', "Create new AV category " ); -$agent->base_like(qr|$expected_base|, "check base"); +$agent->base_like( qr|$expected_base|, "check base" ); $add_form_link_exists = 0; for my $link ( $agent->links() ) { if ( $link->url =~ m|authorised_values.pl\?op=add_form&category=| . uri_escape_utf8($category) ) { $add_form_link_exists = 1; } } -is( $add_form_link_exists, 1, 'Add a new category button should be displayed'); -$agent->get_ok( "$intranet/cgi-bin/koha/admin/authorised_values.pl?op=add_form&category=" . uri_escape_utf8($category), 'Open to create a new AV for this category' ); +is( $add_form_link_exists, 1, 'Add a new category button should be displayed' ); +$agent->get_ok( + "$intranet/cgi-bin/koha/admin/authorised_values.pl?op=add_form&category=" . uri_escape_utf8($category), + 'Open to create a new AV for this category' +); $agent->form_name('Aform'); -$agent->field('authorised_value', 'επιμεq'); -$agent->field('lib_opac', 'autdesc2'); -$agent->field('lib', 'desc1'); -$agent->field('branches', ''); +$agent->field( 'authorised_value', 'επιμεq' ); +$agent->field( 'lib_opac', 'autdesc2' ); +$agent->field( 'lib', 'desc1' ); +$agent->field( 'branches', '' ); $agent->click_ok( '', "Create a new value for the category" ); -$agent->base_like(qr|$expected_base|, "check base"); +$agent->base_like( qr|$expected_base|, "check base" ); $add_form_link_exists = 0; -my $add_form_re = q|authorised_values.pl\?op=add_form&category=| . uri_escape_utf8($category); +my $add_form_re = q|authorised_values.pl\?op=add_form&category=| . uri_escape_utf8($category); for my $link ( $agent->links() ) { if ( $link->url =~ qr|$add_form_re| ) { $add_form_link_exists = 1; } } -is( $add_form_link_exists, 1, 'Add a new category button should be displayed'); +is( $add_form_link_exists, 1, 'Add a new category button should be displayed' ); $agent->get_ok( "$intranet/cgi-bin/koha/admin/authorised_values.pl", 'Return to Authorized values page' ); -$agent->get_ok( "$intranet/cgi-bin/koha/admin/authorised_values.pl?searchfield=" . uri_escape_utf8($category) . "&offset=0", 'Search the values inserted' ); -my $text = $agent->text() ; -#Tests on UTF-8 -ok ( ( length(Encode::encode('UTF-8', $text)) != length($text) ) , 'UTF-8 are multi-byte. Good') ; -ok ($text =~ m/学協会μμ/, 'UTF-8 (Asia) chars are correctly present. Good'); -ok ($text =~ m/επιμεq/, 'UTF-8 (Greek) chars are correctly present. Good'); -ok ($text =~ m/😀/, 'UTF-8 (emoji) chars are correctly present. Good'); +$agent->get_ok( + "$intranet/cgi-bin/koha/admin/authorised_values.pl?searchfield=" . uri_escape_utf8($category) . "&offset=0", + 'Search the values inserted' +); +my $text = $agent->text(); -Koha::AuthorisedValueCategories->find($category)->delete; # Clean up +#Tests on UTF-8 +ok( ( length( Encode::encode( 'UTF-8', $text ) ) != length($text) ), 'UTF-8 are multi-byte. Good' ); +ok( $text =~ m/学協会μμ/, 'UTF-8 (Asia) chars are correctly present. Good' ); +ok( $text =~ m/επιμεq/, 'UTF-8 (Greek) chars are correctly present. Good' ); +ok( $text =~ m/😀/, 'UTF-8 (emoji) chars are correctly present. Good' ); + +Koha::AuthorisedValueCategories->find($category)->delete; # Clean up #---------------------------------------- Test with only latin utf-8 (could be taken as Latin-1/ISO 8859-1) $category = 'tòmas'; -$dbh->do(q|DELETE FROM authorised_values WHERE category = ?|, undef, $category); -$dbh->do(q|DELETE FROM authorised_value_categories WHERE category_name = ?|, undef, $category); +$dbh->do( q|DELETE FROM authorised_values WHERE category = ?|, undef, $category ); +$dbh->do( q|DELETE FROM authorised_value_categories WHERE category_name = ?|, undef, $category ); -$agent->get_ok( "$intranet/cgi-bin/koha/admin/authorised_values.pl", 'Connect to Authorized values page' ); +$agent->get_ok( "$intranet/cgi-bin/koha/admin/authorised_values.pl", 'Connect to Authorized values page' ); $agent->get_ok( "$intranet/cgi-bin/koha/admin/authorised_values.pl?op=add_form", 'Open to create a new category' ); $agent->form_name('Aform'); -$agent->field('category', $category); +$agent->field( 'category', $category ); $agent->click_ok( '', "Create new AV category" ); -$agent->get_ok( "$intranet/cgi-bin/koha/admin/authorised_values.pl?op=add_form&category=$category", 'Open to create a new AV for this category' ); +$agent->get_ok( + "$intranet/cgi-bin/koha/admin/authorised_values.pl?op=add_form&category=$category", + 'Open to create a new AV for this category' +); $agent->form_name('Aform'); -$agent->field('authorised_value', 'ràmen'); -$agent->field('lib_opac', 'autdesc2'); -$agent->field('lib', 'desc1'); -$agent->field('branches', ''); +$agent->field( 'authorised_value', 'ràmen' ); +$agent->field( 'lib_opac', 'autdesc2' ); +$agent->field( 'lib', 'desc1' ); +$agent->field( 'branches', '' ); $agent->click_ok( '', "Create a new value for the category" ); $expected_base = q|authorised_values.pl|; -$agent->base_like(qr|$expected_base|, "check base"); +$agent->base_like( qr|$expected_base|, "check base" ); $add_form_link_exists = 0; -$add_form_re = q|authorised_values.pl\?op=add_form&category=| . uri_escape_utf8($category); +$add_form_re = q|authorised_values.pl\?op=add_form&category=| . uri_escape_utf8($category); for my $link ( $agent->links() ) { if ( $link->url =~ qr|$add_form_re| ) { $add_form_link_exists = 1; @@ -153,11 +158,15 @@ for my $link ( $agent->links() ) { is( $add_form_link_exists, 1, ); $agent->get_ok( "$intranet/cgi-bin/koha/admin/authorised_values.pl", 'Return to Authorized values page' ); -$agent->get_ok( "$intranet/cgi-bin/koha/admin/authorised_values.pl?searchfield=tòmas&offset=0", 'Search the values inserted' ); -my $text2 = $agent->text() ; -#Tests on UTF-8 -ok ( ( length(Encode::encode('UTF-8', $text)) != length($text) ) , 'UTF-8 are multi-byte. Good') ; -ok ($text2 =~ m/tòmas/, 'UTF-8 not Latin-1 first test is OK. Good'); -ok ($text2=~ m/ràmen/, 'UTF-8 not Latin-1 second test is OK. Good'); +$agent->get_ok( + "$intranet/cgi-bin/koha/admin/authorised_values.pl?searchfield=tòmas&offset=0", + 'Search the values inserted' +); +my $text2 = $agent->text(); -Koha::AuthorisedValueCategories->find($category)->delete; # Clean up +#Tests on UTF-8 +ok( ( length( Encode::encode( 'UTF-8', $text ) ) != length($text) ), 'UTF-8 are multi-byte. Good' ); +ok( $text2 =~ m/tòmas/, 'UTF-8 not Latin-1 first test is OK. Good' ); +ok( $text2 =~ m/ràmen/, 'UTF-8 not Latin-1 second test is OK. Good' ); + +Koha::AuthorisedValueCategories->find($category)->delete; # Clean up diff --git a/t/db_dependent/www/batch.t b/t/db_dependent/www/batch.t index 103d043323..73a41cbb92 100755 --- a/t/db_dependent/www/batch.t +++ b/t/db_dependent/www/batch.t @@ -19,7 +19,7 @@ use Modern::Perl; use utf8; -use Test::More; #See plan tests => \d+ below +use Test::More; #See plan tests => \d+ below use Test::WWW::Mechanize; use XML::Simple; use JSON; @@ -38,22 +38,20 @@ use C4::Context; my $marcflavour = C4::Context->preference('marcflavour') || 'MARC21'; my $file = - $marcflavour eq 'UNIMARC' - ? "$testdir/data/unimarcrecord.mrc" - : "$testdir/data/marc21record.mrc"; + $marcflavour eq 'UNIMARC' + ? "$testdir/data/unimarcrecord.mrc" + : "$testdir/data/marc21record.mrc"; my $user = $ENV{KOHA_USER} || $xml->{config}->{user}; my $password = $ENV{KOHA_PASS} || $xml->{config}->{pass}; my $intranet = $ENV{KOHA_INTRANET_URL}; -if (not defined $intranet) { - plan skip_all => - "You must set the environment variable KOHA_INTRANET_URL to ". - "point this test to your staff interface. If you do not have ". - "KOHA_CONF set, you must also set KOHA_USER and KOHA_PASS for ". - "your username and password"; -} -else { +if ( not defined $intranet ) { + plan skip_all => "You must set the environment variable KOHA_INTRANET_URL to " + . "point this test to your staff interface. If you do not have " + . "KOHA_CONF set, you must also set KOHA_USER and KOHA_PASS for " + . "your username and password"; +} else { plan tests => 24; } @@ -71,8 +69,7 @@ my $import_batch_id = $mock_zebra->load_records_ui($file); my $bookdescription; if ( $marcflavour eq 'UNIMARC' ) { $bookdescription = 'Jeffrey Esakov et Tom Weiss'; -} -else { +} else { $bookdescription = 'Data structures'; } @@ -81,7 +78,7 @@ $agent->get_ok( "$intranet/cgi-bin/koha/mainpage.pl", 'connect to intranet' ); $agent->form_name('loginform'); $agent->field( 'login_password', $password ); $agent->field( 'login_userid', $user ); -$agent->field( 'branch', '' ); +$agent->field( 'branch', '' ); $agent->click_ok( '', 'login to staff interface' ); # Get datatable for the batch id @@ -95,29 +92,36 @@ my $biblionumber = $jsonresponse->{data}[0]->{matched}; $agent->get_ok( "$intranet/cgi-bin/koha/catalogue/detail.pl?biblionumber=$biblionumber", - 'getting imported bib' ); -$agent->content_contains( 'Details for ' . $bookdescription, - 'bib is imported' ); + 'getting imported bib' +); +$agent->content_contains( + 'Details for ' . $bookdescription, + 'bib is imported' +); $agent->get("$intranet/cgi-bin/koha/tools/manage-marc-import.pl?import_batch_id=$import_batch_id"); $agent->form_number(5); $agent->click_ok( 'mainformsubmit', "revert import" ); sleep(1); + # FIXME - This if fragile and can fail if there is a race condition -my $job = Koha::BackgroundJobs->search({ type => 'marc_import_revert_batch' })->last; +my $job = Koha::BackgroundJobs->search( { type => 'marc_import_revert_batch' } )->last; my $i; while ( $job->discard_changes->status ne 'finished' ) { sleep(1); last if ++$i > 10; } -is ( $job->status, 'finished', 'job is finished' ); +is( $job->status, 'finished', 'job is finished' ); $agent->get_ok( "$intranet/cgi-bin/koha/catalogue/detail.pl?biblionumber=$biblionumber", - 'getting reverted bib' ); -$agent->content_contains( 'The record you requested does not exist', - 'bib is gone' ); + 'getting reverted bib' +); +$agent->content_contains( + 'The record you requested does not exist', + 'bib is gone' +); $agent->get("$intranet/cgi-bin/koha/tools/batch_records_ajax.pl?import_batch_id=$import_batch_id"); $jsonresponse = decode_json $agent->content; diff --git a/t/db_dependent/www/history.t b/t/db_dependent/www/history.t index 2204723c63..af83692647 100755 --- a/t/db_dependent/www/history.t +++ b/t/db_dependent/www/history.t @@ -21,7 +21,7 @@ use utf8; use XML::Simple; use Encode; -use Test::More; #See plan tests => \d+ below +use Test::More; #See plan tests => \d+ below use Test::WWW::Mechanize; my $koha_conf = $ENV{KOHA_CONF}; @@ -31,21 +31,15 @@ my $user = $ENV{KOHA_USER} || $xml->{config}->{user}; my $password = $ENV{KOHA_PASS} || $xml->{config}->{pass}; my $intranet = $ENV{KOHA_INTRANET_URL}; - -eval{ - use C4::Context; -}; +eval { use C4::Context; }; if ($@) { plan skip_all => "Tests skip. You must have a working Context\n"; -} -elsif (not defined $intranet) { +} elsif ( not defined $intranet ) { plan skip_all => "Tests skip. You must set env. variable KOHA_INTRANET_URL to do tests\n"; -} -else { +} else { plan tests => 4; } - $intranet =~ s#/$##; my $agent = Test::WWW::Mechanize->new( autocheck => 1 ); @@ -55,15 +49,18 @@ $agent->get_ok( "$intranet/cgi-bin/koha/mainpage.pl", 'Load the intranet login p $agent->form_name('loginform'); $agent->field( 'login_password', $password ); $agent->field( 'login_userid', $user ); -$agent->field( 'branch', '' ); +$agent->field( 'branch', '' ); $agent->click( '', 'Login to the intranet' ); $agent->get_ok( "$intranet/cgi-bin/koha/about.pl?tab=team", 'Load the about page' ); # Test about > timeline is correctly encoded -my $encoded_latin_name = Encode::encode('UTF-8', 'Frédéric Demians'); -my $encoded_cyrillic_name = Encode::encode('UTF-8', 'Сергій Дубик'); -my $history_page = Encode::encode('UTF-8', $agent->text()); +my $encoded_latin_name = Encode::encode( 'UTF-8', 'Frédéric Demians' ); +my $encoded_cyrillic_name = Encode::encode( 'UTF-8', 'Сергій Дубик' ); +my $history_page = Encode::encode( 'UTF-8', $agent->text() ); like( $history_page, qr/$encoded_latin_name/, "Latin characters with umlauts show correctly on the history page." ); -like( $history_page, qr/$encoded_cyrillic_name/, "Cyrillic characters with umlauts show correctly on the history page." ); +like( + $history_page, qr/$encoded_cyrillic_name/, + "Cyrillic characters with umlauts show correctly on the history page." +); diff --git a/t/db_dependent/www/regressions.t b/t/db_dependent/www/regressions.t index 8b9c77b07b..767ad36172 100755 --- a/t/db_dependent/www/regressions.t +++ b/t/db_dependent/www/regressions.t @@ -30,11 +30,10 @@ use Koha::Caches; use MARC::Field; -my $intranet = - $ENV{KOHA_INTRANET_URL} || C4::Context->preference("staffClientBaseURL"); -my $opac = $ENV{KOHA_OPAC_URL} || C4::Context->preference("OPACBaseURL"); +my $intranet = $ENV{KOHA_INTRANET_URL} || C4::Context->preference("staffClientBaseURL"); +my $opac = $ENV{KOHA_OPAC_URL} || C4::Context->preference("OPACBaseURL"); -my $context = C4::Context->new(); +my $context = C4::Context->new(); my $db_name = $context->config("database"); my $db_host = $context->config("hostname"); my $db_port = $context->config("port") || ''; @@ -56,90 +55,63 @@ subtest 'open redirection vulnerabilities in tracklinks' => sub { # Incorrect URI at Biblio level $biblio = $builder->build_sample_biblio(); my $biblionumber2 = $biblio->biblionumber; - my $record = $biblio->metadata->record; - my $new856 = MARC::Field->new( '856', '', '', u => "www.bing.com" ); + my $record = $biblio->metadata->record; + my $new856 = MARC::Field->new( '856', '', '', u => "www.bing.com" ); $record->insert_fields_ordered($new856); C4::Biblio::ModBiblio( $record, $biblionumber2 ); # URI at Biblio level $biblio = $builder->build_sample_biblio(); my $biblionumber3 = $biblio->biblionumber; - $record = $biblio->metadata->record; + $record = $biblio->metadata->record; $new856 = MARC::Field->new( '856', '', '', u => "http://www.google.com" ); $record->insert_fields_ordered($new856); C4::Biblio::ModBiblio( $record, $biblionumber3 ); # URI at Item level - my $item = $builder->build_sample_item( { uri => 'http://www.google.com' } ); + my $item = $builder->build_sample_item( { uri => 'http://www.google.com' } ); my $itemnumber1 = $item->itemnumber; # Incorrect URI at Item level $item = $builder->build_sample_item( { uri => 'www.bing.com ' } ); my $itemnumber2 = $item->itemnumber; - my $no_biblionumber = - '/cgi-bin/koha/tracklinks.pl?uri=http://www.google.com'; - my $bad_biblionumber1 = - '/cgi-bin/koha/tracklinks.pl?uri=http://www.google.com&biblionumber=' - . $biblionumber1; - my $bad_biblionumber2 = - '/cgi-bin/koha/tracklinks.pl?uri=http://www.google.com&biblionumber=' - . $biblionumber2; - my $good_biblionumber = - '/cgi-bin/koha/tracklinks.pl?uri=http://www.google.com&biblionumber=' - . $biblionumber3; - my $bad_itemnumber = - '/cgi-bin/koha/tracklinks.pl?uri=http://www.google.com&itemnumber=' - . $itemnumber2; - my $good_itemnumber = - '/cgi-bin/koha/tracklinks.pl?uri=http://www.google.com&itemnumber=' - . $itemnumber1; + my $no_biblionumber = '/cgi-bin/koha/tracklinks.pl?uri=http://www.google.com'; + my $bad_biblionumber1 = '/cgi-bin/koha/tracklinks.pl?uri=http://www.google.com&biblionumber=' . $biblionumber1; + my $bad_biblionumber2 = '/cgi-bin/koha/tracklinks.pl?uri=http://www.google.com&biblionumber=' . $biblionumber2; + my $good_biblionumber = '/cgi-bin/koha/tracklinks.pl?uri=http://www.google.com&biblionumber=' . $biblionumber3; + my $bad_itemnumber = '/cgi-bin/koha/tracklinks.pl?uri=http://www.google.com&itemnumber=' . $itemnumber2; + my $good_itemnumber = '/cgi-bin/koha/tracklinks.pl?uri=http://www.google.com&itemnumber=' . $itemnumber1; Koha::Caches->flush_L1_caches; + # Don't Track C4::Context->set_preference( 'TrackClicks', '' ); - $t->get_ok( $opac . $no_biblionumber ) - ->status_is( 404, "404 for no biblionumber" ); - $t->get_ok( $opac . $bad_biblionumber1 ) - ->status_is( 404, "404 for biblionumber containing no URI - pref off" ); + $t->get_ok( $opac . $no_biblionumber )->status_is( 404, "404 for no biblionumber" ); + $t->get_ok( $opac . $bad_biblionumber1 )->status_is( 404, "404 for biblionumber containing no URI - pref off" ); $t->get_ok( $opac . $bad_biblionumber2 ) - ->status_is( 404, "404 for biblionumber containing different URI - pref off" ); - $t->get_ok( $opac . $good_biblionumber ) - ->status_is( 404, "404 for biblionumber with matching URI - pref off" ); - $t->get_ok( $opac . $bad_itemnumber ) - ->status_is( 404, "404 for itemnumber containing different URI- pref off" ); - $t->get_ok( $opac . $good_itemnumber ) - ->status_is( 404, "404 for itemnumber with matching URI - pref off" ); + ->status_is( 404, "404 for biblionumber containing different URI - pref off" ); + $t->get_ok( $opac . $good_biblionumber )->status_is( 404, "404 for biblionumber with matching URI - pref off" ); + $t->get_ok( $opac . $bad_itemnumber )->status_is( 404, "404 for itemnumber containing different URI- pref off" ); + $t->get_ok( $opac . $good_itemnumber )->status_is( 404, "404 for itemnumber with matching URI - pref off" ); # Track C4::Context->set_preference( 'TrackClicks', 'track' ); - $t->get_ok( $opac . $no_biblionumber ) - ->status_is( 404, "404 for no biblionumber" ); - $t->get_ok( $opac . $bad_biblionumber1 ) - ->status_is( 404, "404 for biblionumber containing no URI" ); - $t->get_ok( $opac . $bad_biblionumber2 ) - ->status_is( 404, "404 for biblionumber containing different URI" ); - $t->get_ok( $opac . $good_biblionumber ) - ->status_is( 302, "302 for biblionumber with matching URI" ); - $t->get_ok( $opac . $bad_itemnumber ) - ->status_is( 404, "404 for itemnumber containing different URI" ); - $t->get_ok( $opac . $good_itemnumber ) - ->status_is( 302, "302 for itemnumber with matching URI" ); + $t->get_ok( $opac . $no_biblionumber )->status_is( 404, "404 for no biblionumber" ); + $t->get_ok( $opac . $bad_biblionumber1 )->status_is( 404, "404 for biblionumber containing no URI" ); + $t->get_ok( $opac . $bad_biblionumber2 )->status_is( 404, "404 for biblionumber containing different URI" ); + $t->get_ok( $opac . $good_biblionumber )->status_is( 302, "302 for biblionumber with matching URI" ); + $t->get_ok( $opac . $bad_itemnumber )->status_is( 404, "404 for itemnumber containing different URI" ); + $t->get_ok( $opac . $good_itemnumber )->status_is( 302, "302 for itemnumber with matching URI" ); # Track Anonymous C4::Context->set_preference( 'TrackClicks', 'anonymous' ); - $t->get_ok( $opac . $no_biblionumber ) - ->status_is( 404, "404 for no biblionumber" ); - $t->get_ok( $opac . $bad_biblionumber1 ) - ->status_is( 404, "404 for biblionumber containing no URI" ); - $t->get_ok( $opac . $bad_biblionumber2 ) - ->status_is( 404, "404 for biblionumber containing different URI" ); - $t->get_ok( $opac . $good_biblionumber ) - ->status_is( 302, "302 for biblionumber with matching URI" ); - $t->get_ok( $opac . $bad_itemnumber ) - ->status_is( 404, "404 for itemnumber containing different URI" ); - $t->get_ok( $opac . $good_itemnumber ) - ->status_is( 302, "302 for itemnumber with matching URI" ); + $t->get_ok( $opac . $no_biblionumber )->status_is( 404, "404 for no biblionumber" ); + $t->get_ok( $opac . $bad_biblionumber1 )->status_is( 404, "404 for biblionumber containing no URI" ); + $t->get_ok( $opac . $bad_biblionumber2 )->status_is( 404, "404 for biblionumber containing different URI" ); + $t->get_ok( $opac . $good_biblionumber )->status_is( 302, "302 for biblionumber with matching URI" ); + $t->get_ok( $opac . $bad_itemnumber )->status_is( 404, "404 for itemnumber containing different URI" ); + $t->get_ok( $opac . $good_itemnumber )->status_is( 302, "302 for itemnumber with matching URI" ); }; `mysql -u $db_user --password="$db_passwd" -h $db_host -P $db_port --database="$db_name" < dumpfile.sql`; diff --git a/t/db_dependent/www/rest_api.t b/t/db_dependent/www/rest_api.t index 3f2fdebfb2..1a0e538b49 100755 --- a/t/db_dependent/www/rest_api.t +++ b/t/db_dependent/www/rest_api.t @@ -17,21 +17,17 @@ use Modern::Perl; -use Test::More; #See plan tests => \d+ below +use Test::More; #See plan tests => \d+ below use LWP::UserAgent; my $intranet = $ENV{KOHA_INTRANET_URL}; -eval{ - use C4::Context; -}; +eval { use C4::Context; }; if ($@) { plan skip_all => "Tests skip. You must have a working Context\n"; -} -elsif (not defined $intranet) { +} elsif ( not defined $intranet ) { plan skip_all => "Tests skip. You must set env. variable KOHA_INTRANET_URL to do tests\n"; -} -else { +} else { plan tests => 1; } @@ -40,6 +36,6 @@ $intranet =~ s#/$##; my $api_base_url = "$intranet/api/v1"; subtest 'non-existent routes' => sub { plan tests => 1; - my $response = LWP::UserAgent->new->get($api_base_url . "/does_not_exist"); + my $response = LWP::UserAgent->new->get( $api_base_url . "/does_not_exist" ); is( $response->code, 404, "REST API should return 404 on non-existent routes" ); }; diff --git a/t/db_dependent/www/search_utf8.t b/t/db_dependent/www/search_utf8.t index efd16fe544..3295eedc87 100755 --- a/t/db_dependent/www/search_utf8.t +++ b/t/db_dependent/www/search_utf8.t @@ -18,7 +18,7 @@ use Modern::Perl; use utf8; -use Test::More; #See plan tests => \d+ below +use Test::More; #See plan tests => \d+ below use Test::WWW::Mechanize; use Data::Dumper; use XML::Simple; @@ -32,37 +32,38 @@ use C4::Context; use t::lib::Mocks::Zebra; my $testdir = File::Spec->rel2abs( dirname(__FILE__) ); + # global variables that will be used when forking my $marcflavour = C4::Context->preference('marcflavour') || 'MARC21'; my $file1 = - $marcflavour eq 'UNIMARC' - ? "$testdir/data/unimarcutf8record.mrc" - : "$testdir/data/marc21utf8record.mrc"; + $marcflavour eq 'UNIMARC' + ? "$testdir/data/unimarcutf8record.mrc" + : "$testdir/data/marc21utf8record.mrc"; my $file2 = - $marcflavour eq 'UNIMARC' - ? "$testdir/data/unimarclatin1utf8rec.mrc" - : "$testdir/data/marc21latin1utf8rec.mrc"; + $marcflavour eq 'UNIMARC' + ? "$testdir/data/unimarclatin1utf8rec.mrc" + : "$testdir/data/marc21latin1utf8rec.mrc"; my $file3 = - $marcflavour eq 'UNIMARC' - ? "$testdir/data/unimarcutf8supprec.mrc" - : "$testdir/data/marc21utf8supprec.mrc"; + $marcflavour eq 'UNIMARC' + ? "$testdir/data/unimarcutf8supprec.mrc" + : "$testdir/data/marc21utf8supprec.mrc"; our $intranet = $ENV{KOHA_INTRANET_URL}; our $opac = $ENV{KOHA_OPAC_URL}; # test KOHA_INTRANET_URL is set if ( not $intranet ) { - plan skip_all => "Tests skip. You must set env. variable KOHA_INTRANET_URL to do tests\n"; + plan skip_all => "Tests skip. You must set env. variable KOHA_INTRANET_URL to do tests\n"; } + # test KOHA_OPAC_URL is set elsif ( not $opac ) { - plan skip_all => "Tests skip. You must set env. variable KOHA_OPAC_URL to do tests\n"; -} -else { + plan skip_all => "Tests skip. You must set env. variable KOHA_OPAC_URL to do tests\n"; +} else { plan tests => 80; } @@ -83,6 +84,7 @@ $mock_zebra->launch_zebra; if ( not defined $mock_zebra->{zebra_pid} ) { plan skip_all => "Tests skip. Error starting Zebra Server to do those tests\n"; } + # launch the zebra index process $mock_zebra->launch_indexer; if ( not defined $mock_zebra->{indexer_pid} ) { @@ -92,14 +94,14 @@ if ( not defined $mock_zebra->{indexer_pid} ) { our $agent = Test::WWW::Mechanize->new( autocheck => 1 ); $agent->get_ok( "$intranet/cgi-bin/koha/mainpage.pl", 'connect to intranet' ); $agent->form_name('loginform'); -$agent->field( 'login_userid', $ENV{KOHA_PASS} ); +$agent->field( 'login_userid', $ENV{KOHA_PASS} ); $agent->field( 'login_password', $ENV{KOHA_USER} ); -$agent->field( 'branch', '' ); +$agent->field( 'branch', '' ); $agent->click_ok( '', 'login to staff interface' ); -my $batch_id = $mock_zebra->load_records_ui($file1); +my $batch_id = $mock_zebra->load_records_ui($file1); my $utf8_reg1 = qr/学協会. μμ/; -test_search('Αθήνα', 'deuteros', $utf8_reg1); +test_search( 'Αθήνα', 'deuteros', $utf8_reg1 ); $mock_zebra->clean_records($batch_id); $mock_zebra->cleanup; @@ -114,7 +116,7 @@ if ( not defined $mock_zebra->{indexer_pid} ) { } $batch_id = $mock_zebra->load_records_ui($file2); my $utf8_reg2 = qr/Tòmas/; -test_search('Ramòn', 'Tòmas',$utf8_reg2); +test_search( 'Ramòn', 'Tòmas', $utf8_reg2 ); $mock_zebra->clean_records($batch_id); $mock_zebra->cleanup; @@ -129,62 +131,64 @@ if ( not defined $mock_zebra->{indexer_pid} ) { } $batch_id = $mock_zebra->load_records_ui($file3); my $utf8_reg3 = qr/😀/; -test_search("𠻺tomasito𠻺", 'A tiny record', $utf8_reg3); +test_search( "𠻺tomasito𠻺", 'A tiny record', $utf8_reg3 ); $mock_zebra->clean_records($batch_id); $mock_zebra->cleanup; -sub test_search{ +sub test_search { my ( $publisher, $search_key, $utf8_reg ) = @_; # --------------------------------- TEST INTRANET SEARCH - $agent->get_ok( "$intranet/cgi-bin/koha/catalogue/search.pl" , "got search on intranet"); + $agent->get_ok( "$intranet/cgi-bin/koha/catalogue/search.pl", "got search on intranet" ); $agent->form_number(5); - $agent->field('idx', 'kw'); - $agent->field('q', $search_key); + $agent->field( 'idx', 'kw' ); + $agent->field( 'q', $search_key ); $agent->click(); - my $intra_text = $agent->text() ; + my $intra_text = $agent->text(); - $agent->get_ok( "$intranet/cgi-bin/koha/catalogue/search.pl" , "got search on intranet"); + $agent->get_ok( "$intranet/cgi-bin/koha/catalogue/search.pl", "got search on intranet" ); $agent->form_number(5); - $agent->field('idx', 'kw'); - $agent->field('q', $publisher); + $agent->field( 'idx', 'kw' ); + $agent->field( 'q', $publisher ); $agent->click(); $intra_text = $agent->text(); - my $expected_base = q|search.pl\?advsearch=1&idx=kw&q=| . uri_escape_utf8( $publisher ); - $agent->base_like(qr|$expected_base|, ); + my $expected_base = q|search.pl\?advsearch=1&idx=kw&q=| . uri_escape_utf8($publisher); + $agent->base_like( qr|$expected_base|, ); + + ok( ( length( Encode::encode( 'UTF-8', $intra_text ) ) != length($intra_text) ), 'UTF-8 are multi-byte. Good' ); + ok( $intra_text =~ $utf8_reg, 'UTF-8 chars are correctly present. Good' ); - ok ( ( length(Encode::encode('UTF-8', $intra_text)) != length($intra_text) ) , 'UTF-8 are multi-byte. Good') ; - ok ($intra_text =~ $utf8_reg, 'UTF-8 chars are correctly present. Good'); # -------------------------------------------------- TEST ON OPAC - $agent->get_ok( "$opac" , "got opac"); + $agent->get_ok( "$opac", "got opac" ); $agent->form_name('searchform'); $agent->field( 'q', $search_key ); - $agent->field( 'idx', '' ); - $agent->click( ); - my $opac_text = $agent->text() ; + $agent->field( 'idx', '' ); + $agent->click(); + my $opac_text = $agent->text(); - $agent->get_ok( "$opac" , "got opac"); + $agent->get_ok( "$opac", "got opac" ); $agent->form_name('searchform'); - $agent->field('q', $publisher); - $agent->field( 'idx', '' ); + $agent->field( 'q', $publisher ); + $agent->field( 'idx', '' ); $agent->click(); $opac_text = $agent->text(); - $expected_base = q|opac-search.pl\?(idx=&)?q=| . uri_escape_utf8( $publisher ); - $agent->base_like(qr|$expected_base|, ); + $expected_base = q|opac-search.pl\?(idx=&)?q=| . uri_escape_utf8($publisher); + $agent->base_like( qr|$expected_base|, ); + # Test added on BZ 14909 in addition to making the empty idx= optional # in the previous regex $agent->base_unlike( qr|idx=\w+|, 'Base does not contain an idx' ); - ok ( ( length(Encode::encode('UTF-8', $opac_text)) != length($opac_text) ) , 'UTF-8 are multi-byte. Good') ; - ok ($opac_text =~ $utf8_reg, 'UTF-8 chars are correctly present. Good'); + ok( ( length( Encode::encode( 'UTF-8', $opac_text ) ) != length($opac_text) ), 'UTF-8 are multi-byte. Good' ); + ok( $opac_text =~ $utf8_reg, 'UTF-8 chars are correctly present. Good' ); } END { $mock_zebra->cleanup; -}; +} diff --git a/t/db_dependent/yaml.t b/t/db_dependent/yaml.t index 586c053ca0..6770fe355b 100755 --- a/t/db_dependent/yaml.t +++ b/t/db_dependent/yaml.t @@ -12,7 +12,7 @@ my $vars; my $output; $template->process( 't/db_dependent/data/syspref.pref', $vars, \$output ); -my $yaml = YAML::XS::Load( Encode::encode_utf8( $output ) ); +my $yaml = YAML::XS::Load( Encode::encode_utf8($output) ); my $syspref_1 = $yaml->{Test}->{Testing}->[0]; my $syspref_2 = $yaml->{Test}->{Testing}->[1]; my $syspref_3 = $yaml->{Test}->{Testing}->[2]; diff --git a/t/db_dependent/zebra_config.pl b/t/db_dependent/zebra_config.pl index 169c51e55e..cd550d725e 100755 --- a/t/db_dependent/zebra_config.pl +++ b/t/db_dependent/zebra_config.pl @@ -2,23 +2,23 @@ use Modern::Perl; -use File::Copy qw( copy ); -use File::Path qw( make_path ); -use File::Find qw( find ); +use File::Copy qw( copy ); +use File::Path qw( make_path ); +use File::Find qw( find ); use File::Basename qw( dirname ); use File::Spec; use C4::Context; -my $source = File::Spec->rel2abs('.'); -my $destination = $ARGV[0]; -my $marc_type = $ARGV[1] || 'marc21'; +my $source = File::Spec->rel2abs('.'); +my $destination = $ARGV[0]; +my $marc_type = $ARGV[1] || 'marc21'; my $indexing_mode = $ARGV[2] || 'dom'; -$ENV{__ZEBRA_MARC_FORMAT__} = $marc_type; -$ENV{__ZEBRA_BIB_CFG__} = 'zebra-biblios-dom.cfg'; -$ENV{__BIB_RETRIEVAL_CFG__} = 'retrieval-info-bib-dom.xml'; -$ENV{__ZEBRA_AUTH_CFG__} = 'zebra-authorities-dom.cfg'; +$ENV{__ZEBRA_MARC_FORMAT__} = $marc_type; +$ENV{__ZEBRA_BIB_CFG__} = 'zebra-biblios-dom.cfg'; +$ENV{__BIB_RETRIEVAL_CFG__} = 'retrieval-info-bib-dom.xml'; +$ENV{__ZEBRA_AUTH_CFG__} = 'zebra-authorities-dom.cfg'; $ENV{__AUTH_RETRIEVAL_CFG__} = 'retrieval-info-auth-dom.xml'; make_path("$destination/var/lock/zebradb"); @@ -39,7 +39,7 @@ make_path("$destination/var/lib/zebradb/authorities/tmp"); make_path("$destination/var/log/koha"); make_path("$destination/var/run/zebradb"); -$ENV{'INSTALL_BASE'} = $destination; +$ENV{'INSTALL_BASE'} = $destination; $ENV{'__INSTALL_BASE__'} = $destination; $ENV{'__DB_TYPE__'} = C4::Context->config('db_scheme') // 'mysql'; @@ -56,7 +56,7 @@ my @files = ( "$source/etc/log4perl.conf", ); -find(sub { push @files, $File::Find::name if ( -f $File::Find::name ); }, "$source/etc/zebradb"); +find( sub { push @files, $File::Find::name if ( -f $File::Find::name ); }, "$source/etc/zebradb" ); foreach my $file (@files) { my $target = "$file"; @@ -64,16 +64,16 @@ foreach my $file (@files) { $target =~ s#etc/zebradb#etc/koha/zebradb#; $target =~ s#etc/log4perl\.conf#etc/koha/log4perl.conf#; unlink($target); - make_path(dirname($target)); - copy("$file", "$target"); + make_path( dirname($target) ); + copy( "$file", "$target" ); system("perl $source/rewrite-config.PL $target"); - if ($file =~ m/xml/) { - replace("$target", "$destination/intranet/templates", "$source/koha-tmpl/intranet-tmpl"); + + if ( $file =~ m/xml/ ) { + replace( "$target", "$destination/intranet/templates", "$source/koha-tmpl/intranet-tmpl" ); } } - sub replace { - my ($file, $pattern, $replacement) = @_; + my ( $file, $pattern, $replacement ) = @_; system("sed -i -e 's#$pattern#$replacement#' $file"); } diff --git a/t/etc/schema.pl b/t/etc/schema.pl index 52eccbe8fa..76ddb5dff7 100755 --- a/t/etc/schema.pl +++ b/t/etc/schema.pl @@ -2,8 +2,9 @@ use Modern::Perl; return { schema_class => 'Koha::Schema', -# This is the default option when nothing is defined -# connect_info => ['dbi:SQLite:dbname=:memory:','',''], - connect_opts => { name_sep => '.', quote_char => '`', sqlite_unicode => 1 }, + + # This is the default option when nothing is defined + # connect_info => ['dbi:SQLite:dbname=:memory:','',''], + connect_opts => { name_sep => '.', quote_char => '`', sqlite_unicode => 1 }, fixture_class => '::Populate', }; diff --git a/t/lib/Bootstrap.pm b/t/lib/Bootstrap.pm index dd749149d8..524c9b2d9e 100644 --- a/t/lib/Bootstrap.pm +++ b/t/lib/Bootstrap.pm @@ -7,8 +7,9 @@ use File::Temp qw( tempfile ); use XML::LibXML; our ( $database, $database_test ); + sub import { - my ($self, %args) = @_; + my ( $self, %args ) = @_; require C4::Context; C4::Context->import; @@ -16,16 +17,20 @@ sub import { my $host = C4::Context->config('hostname'); my $port = C4::Context->config('port'); $database_test = C4::Context->config("database_test") or die "Config entry 'database_test' does not exist"; - $database = C4::Context->config('database'); + $database = C4::Context->config('database'); die "Entries 'database_test' and 'database' have the same value in your config" if $database_test eq $database; my $user = C4::Context->config('user'); my $pass = C4::Context->config('pass'); - my $dbh = DBI->connect("dbi:mysql:;host=$host;port=$port", $user, $pass, { - RaiseError => 1, - PrintError => 0, - }); + my $dbh = DBI->connect( + "dbi:mysql:;host=$host;port=$port", + $user, $pass, + { + RaiseError => 1, + PrintError => 0, + } + ); $dbh->do("DROP DATABASE IF EXISTS $database_test"); $dbh->do("CREATE DATABASE $database_test"); @@ -35,9 +40,9 @@ sub import { END { my $dbh = C4::Context->dbh; $dbh->do("DROP DATABASE IF EXISTS $database_test") - if $database_test && $database_test ne $database; + if $database_test && $database_test ne $database; Koha::Caches->get_instance()->flush_all; Koha::Caches->get_instance('config')->flush_all; -}; +} 1; diff --git a/t/lib/Dates.pm b/t/lib/Dates.pm index 5340099881..a0cf5576fe 100644 --- a/t/lib/Dates.pm +++ b/t/lib/Dates.pm @@ -23,7 +23,7 @@ sub compare { my ( $got, $expected ) = @_; my $dt_got = dt_from_string($got); my $dt_expected = dt_from_string($expected); - my $diff = $dt_got->epoch - $dt_expected->epoch; + my $diff = $dt_got->epoch - $dt_expected->epoch; if ( abs($diff) <= 5 ) { return 0 } return $diff > 0 ? 1 : -1; } diff --git a/t/lib/IdP/ExternalIdP.pm b/t/lib/IdP/ExternalIdP.pm index 21bd3a9f27..5e187b71ee 100644 --- a/t/lib/IdP/ExternalIdP.pm +++ b/t/lib/IdP/ExternalIdP.pm @@ -8,159 +8,177 @@ use Mojo::Server::Daemon; print "Configure idp routes\n"; any '/idp/test/authorization_endpoint' => sub { - my $c = shift; - print "pasa por acá\n"; - return $c->render(json => {error => 'invalid_request'}, status => 500) - unless (3 == grep { $c->param($_) } qw(response_type redirect_uri client_id)) - && $c->param('response_type') eq 'code'; + my $c = shift; + print "pasa por acá\n"; + return $c->render( json => { error => 'invalid_request' }, status => 500 ) + unless ( 3 == grep { $c->param($_) } qw(response_type redirect_uri client_id) ) + && $c->param('response_type') eq 'code'; - my $url = Mojo::URL->new($c->param('redirect_uri')); - $url->query({code => 'authorize-code', state => $c->param('state')}); - return $c->redirect_to($url); + my $url = Mojo::URL->new( $c->param('redirect_uri') ); + $url->query( { code => 'authorize-code', state => $c->param('state') } ); + return $c->redirect_to($url); }; any '/idp/test/token_endpoint/with_id_token/with_email' => sub { - my $c = shift; - return $c->render(json => {error => 'invalid_request'}, status => 500) - unless (4 == grep { $c->param($_) } qw(client_id client_secret redirect_uri code)) - && $c->param('code') eq 'authorize-code'; + my $c = shift; + return $c->render( json => { error => 'invalid_request' }, status => 500 ) + unless ( 4 == grep { $c->param($_) } qw(client_id client_secret redirect_uri code) ) + && $c->param('code') eq 'authorize-code'; - my $claims = { - aud => $c->param('client_id'), - email => 'test.user@some.library.com', - iss => $c->url_for('/idp/test')->to_abs, - given_name => 'test', - family_name => 'user', - preferred_username => 'test.user@some.library.com', - sub => 'test.user' - }; + my $claims = { + aud => $c->param('client_id'), + email => 'test.user@some.library.com', + iss => $c->url_for('/idp/test')->to_abs, + given_name => 'test', + family_name => 'user', + preferred_username => 'test.user@some.library.com', + sub => 'test.user' + }; - my $rsa = Crypt::OpenSSL::RSA->generate_key(2048); + my $rsa = Crypt::OpenSSL::RSA->generate_key(2048); - my $id_token = Mojo::JWT->new( - algorithm => 'RS256', - secret => $rsa->get_private_key_string, - set_iat => 1, - claims => $claims, - header => {kid => 'TEST_SIGNING_KEY'} - ); + my $id_token = Mojo::JWT->new( + algorithm => 'RS256', + secret => $rsa->get_private_key_string, + set_iat => 1, + claims => $claims, + header => { kid => 'TEST_SIGNING_KEY' } + ); - $c->render(status => 200, json => { - access_token => 'access', - expires_in => 3599, - ext_expires_in => 3599, - id_token => $id_token, - refresh_token => 'refresh-token', - scope => 'openid', - token_type => 'Bearer' - }); + $c->render( + status => 200, + json => { + access_token => 'access', + expires_in => 3599, + ext_expires_in => 3599, + id_token => $id_token, + refresh_token => 'refresh-token', + scope => 'openid', + token_type => 'Bearer' + } + ); }; any '/idp/test/token_endpoint/with_id_token/without_email' => sub { - my $c = shift; - return $c->render(json => {error => 'invalid_request'}, status => 500) - unless (4 == grep { $c->param($_) } qw(client_id client_secret redirect_uri code)) - && $c->param('code') eq 'authorize-code'; + my $c = shift; + return $c->render( json => { error => 'invalid_request' }, status => 500 ) + unless ( 4 == grep { $c->param($_) } qw(client_id client_secret redirect_uri code) ) + && $c->param('code') eq 'authorize-code'; - my $claims = { - aud => $c->param('client_id'), - iss => $c->url_for('/idp/test')->to_abs, - given_name => 'test', - family_name => 'user', - preferred_username => 'test.user', - sub => 'test.user' - }; + my $claims = { + aud => $c->param('client_id'), + iss => $c->url_for('/idp/test')->to_abs, + given_name => 'test', + family_name => 'user', + preferred_username => 'test.user', + sub => 'test.user' + }; - my $rsa = Crypt::OpenSSL::RSA->generate_key(2048); + my $rsa = Crypt::OpenSSL::RSA->generate_key(2048); - my $id_token = Mojo::JWT->new( - algorithm => 'RS256', - secret => $rsa->get_private_key_string, - set_iat => 1, - claims => $claims, - header => {kid => 'TEST_SIGNING_KEY'} - ); + my $id_token = Mojo::JWT->new( + algorithm => 'RS256', + secret => $rsa->get_private_key_string, + set_iat => 1, + claims => $claims, + header => { kid => 'TEST_SIGNING_KEY' } + ); - $c->render(status => 200, json => { - access_token => 'access', - expires_in => 3599, - ext_expires_in => 3599, - id_token => $id_token, - refresh_token => 'refresh-token', - scope => 'openid', - token_type => 'Bearer' - }); + $c->render( + status => 200, + json => { + access_token => 'access', + expires_in => 3599, + ext_expires_in => 3599, + id_token => $id_token, + refresh_token => 'refresh-token', + scope => 'openid', + token_type => 'Bearer' + } + ); }; any '/idp/test/token_endpoint/without_id_token' => sub { - my $c = shift; - return $c->render(json => {error => 'invalid_request'}, status => 500) - unless (4 == grep { $c->param($_) } qw(client_id client_secret redirect_uri code)) - && $c->param('code') eq 'authorize-code'; + my $c = shift; + return $c->render( json => { error => 'invalid_request' }, status => 500 ) + unless ( 4 == grep { $c->param($_) } qw(client_id client_secret redirect_uri code) ) + && $c->param('code') eq 'authorize-code'; - $c->render(status => 200, json => { - access_token => 'access', - expires_in => 3599, - ext_expires_in => 3599, - refresh_token => 'refresh-token', - scope => 'some list of scopes', - token_type => 'Bearer' - }); + $c->render( + status => 200, + json => { + access_token => 'access', + expires_in => 3599, + ext_expires_in => 3599, + refresh_token => 'refresh-token', + scope => 'some list of scopes', + token_type => 'Bearer' + } + ); }; any '/idp/test/userinfo_endpoint' => sub { - my $c = shift; - return $c->render(text => 'Unauthorized', status => 401) - unless $c->req->headers->authorization eq 'Bearer access'; + my $c = shift; + return $c->render( text => 'Unauthorized', status => 401 ) + unless $c->req->headers->authorization eq 'Bearer access'; - $c->render(status => 200, json => { - users => [ - { - email => 'test.user@some.library.com', - custom_name => 'test', - custom_surname => 'user', - id => 'test.user', - last_login => 'a long time ago' - } - ] - }); + $c->render( + status => 200, + json => { + users => [ + { + email => 'test.user@some.library.com', + custom_name => 'test', + custom_surname => 'user', + id => 'test.user', + last_login => 'a long time ago' + } + ] + } + ); }; any '/idp/test/with_email/.well_known' => sub { - my $c = shift; + my $c = shift; - $c->render(status => 200, json => { - authorization_endpoint => $c->url_for('/idp/test/authorization_endpoint')->to_abs, - token_endpoint => $c->url_for('/idp/test/token_endpoint/with_id_token/with_email')->to_abs, - userinfo_endpoint => $c->url_for('/idp/test/userinfo_endpoint')->to_abs, - }); + $c->render( + status => 200, + json => { + authorization_endpoint => $c->url_for('/idp/test/authorization_endpoint')->to_abs, + token_endpoint => $c->url_for('/idp/test/token_endpoint/with_id_token/with_email')->to_abs, + userinfo_endpoint => $c->url_for('/idp/test/userinfo_endpoint')->to_abs, + } + ); }; any '/idp/test/without_email/.well_known' => sub { - my $c = shift; + my $c = shift; - $c->render(status => 200, json => { - authorization_endpoint => $c->url_for('/idp/test/authorization_endpoint')->to_abs, - token_endpoint => $c->url_for('/idp/test/token_endpoint/with_id_token/without_email')->to_abs, - userinfo_endpoint => $c->url_for('/idp/test/userinfo_endpoint')->to_abs, - }); + $c->render( + status => 200, + json => { + authorization_endpoint => $c->url_for('/idp/test/authorization_endpoint')->to_abs, + token_endpoint => $c->url_for('/idp/test/token_endpoint/with_id_token/without_email')->to_abs, + userinfo_endpoint => $c->url_for('/idp/test/userinfo_endpoint')->to_abs, + } + ); }; my $port = Mojo::IOLoop::Server->generate_port; my $daemon = Mojo::Server::Daemon->new( - app => app, - listen => ["http://*:$port"] + app => app, + listen => ["http://*:$port"] ); sub start { - print "Run daemon\n"; - $daemon->start; - Mojo::IOLoop->start unless Mojo::IOLoop->is_running; - return $port; + print "Run daemon\n"; + $daemon->start; + Mojo::IOLoop->start unless Mojo::IOLoop->is_running; + return $port; } sub stop { - $daemon->stop; + $daemon->stop; } -1; \ No newline at end of file +1; diff --git a/t/lib/Koha/BackgroundJob/BatchTest.pm b/t/lib/Koha/BackgroundJob/BatchTest.pm index 1ae84ef4e9..5ff35c29f2 100644 --- a/t/lib/Koha/BackgroundJob/BatchTest.pm +++ b/t/lib/Koha/BackgroundJob/BatchTest.pm @@ -31,13 +31,10 @@ sub process { # FIXME: This should happen when $self->SUPER::process is called instead return - unless $self->status ne 'cancelled'; + unless $self->status ne 'cancelled'; my $job_progress = 0; - $self->started_on(dt_from_string) - ->progress($job_progress) - ->status('started') - ->store; + $self->started_on(dt_from_string)->progress($job_progress)->status('started')->store; my $report = { total_records => $self->size, @@ -50,29 +47,30 @@ sub process { push @messages, { type => 'success', - i => $i, + i => $i, }; $report->{total_success}++; $self->progress( ++$job_progress )->store; } - my $job_data = $self->json->decode($self->data); + my $job_data = $self->json->decode( $self->data ); $job_data->{messages} = \@messages; - $job_data->{report} = $report; + $job_data->{report} = $report; - $self->ended_on(dt_from_string) - ->data( $self->json->encode($job_data) ); + $self->ended_on(dt_from_string)->data( $self->json->encode($job_data) ); $self->status('finished') if $self->status ne 'cancelled'; $self->store; } sub enqueue { - my ( $self, $args) = @_; + my ( $self, $args ) = @_; - $self->SUPER::enqueue({ - job_size => $args->{size}, - job_args => {a => $args->{a}, b => $args->{b}} - }); + $self->SUPER::enqueue( + { + job_size => $args->{size}, + job_args => { a => $args->{a}, b => $args->{b} } + } + ); } 1; diff --git a/t/lib/Mocks.pm b/t/lib/Mocks.pm index 843ee9bc53..8bac8793c0 100644 --- a/t/lib/Mocks.pm +++ b/t/lib/Mocks.pm @@ -49,15 +49,18 @@ sub mock_config { my ( $config_entry, $value ) = @_; my $koha_config = Test::MockModule->new('Koha::Config'); $configs{$config_entry} = $value; - $koha_config->mock('get', sub { - my ( $self, $key, $section ) = @_; - $section ||= 'config'; - if( $section eq 'config' && exists $configs{$key} ) { - return $configs{$key}; + $koha_config->mock( + 'get', + sub { + my ( $self, $key, $section ) = @_; + $section ||= 'config'; + if ( $section eq 'config' && exists $configs{$key} ) { + return $configs{$key}; + } + my $method = $koha_config->original('get'); + return $method->( $self, $key, $section ); } - my $method = $koha_config->original('get'); - return $method->( $self, $key, $section ); - }); + ); } my %preferences; @@ -73,19 +76,22 @@ Mock the I<$preference> with the specified I<value>. sub mock_preference { my ( $pref, $value ) = @_; - $preferences{lc($pref)} = $value; + $preferences{ lc($pref) } = $value; my $context = Test::MockModule->new('C4::Context'); - $context->mock('preference', sub { - my ( $self, $pref ) = @_; - $pref = lc($pref); - if ( exists $preferences{$pref} ) { - return $preferences{$pref} - } else { - my $method = $context->original('preference'); - return $method->($self, $pref); + $context->mock( + 'preference', + sub { + my ( $self, $pref ) = @_; + $pref = lc($pref); + if ( exists $preferences{$pref} ) { + return $preferences{$pref}; + } else { + my $method = $context->original('preference'); + return $method->( $self, $pref ); + } } - }); + ); } =head3 mock_userenv @@ -117,28 +123,28 @@ Also, some sane defaults are set if no parameters are passed. =cut sub mock_userenv { - my ( $params ) = @_; + my ($params) = @_; my $userenv; if ( $params and my $patron = $params->{patron} ) { - $userenv = $patron->unblessed; + $userenv = $patron->unblessed; $userenv->{branchcode} = $params->{branchcode} || $patron->library->branchcode; $userenv->{branchname} = $params->{branchname} || $patron->library->branchname; } - my $usernum = $params->{borrowernumber} || $userenv->{borrowernumber} || 51; - my $userid = $params->{userid} || $userenv->{userid} || 'userid4tests'; - my $cardnumber = $params->{cardnumber} || $userenv->{cardnumber}; - my $firstname = $params->{firstname} || $userenv->{firstname} || 'firstname'; - my $surname = $params->{surname} || $userenv->{surname} || 'surname'; - my $branchcode = $params->{branchcode} || $userenv->{branchcode} || 'Branch4T'; - my $branchname = $params->{branchname} || $userenv->{branchname}; - my $flags = $params->{flags} || $userenv->{flags} || 0; - my $emailaddress = $params->{emailaddress} || $userenv->{email}; - my $desk_id = $params->{desk_id} || $userenv->{desk_id}; - my $desk_name = $params->{desk_name} || $userenv->{desk_name}; - my $register_id = $params->{register_id} || $userenv->{register_id}; - my $register_name = $params->{register_name} || $userenv->{register_name}; - my ( $shibboleth ); + my $usernum = $params->{borrowernumber} || $userenv->{borrowernumber} || 51; + my $userid = $params->{userid} || $userenv->{userid} || 'userid4tests'; + my $cardnumber = $params->{cardnumber} || $userenv->{cardnumber}; + my $firstname = $params->{firstname} || $userenv->{firstname} || 'firstname'; + my $surname = $params->{surname} || $userenv->{surname} || 'surname'; + my $branchcode = $params->{branchcode} || $userenv->{branchcode} || 'Branch4T'; + my $branchname = $params->{branchname} || $userenv->{branchname}; + my $flags = $params->{flags} || $userenv->{flags} || 0; + my $emailaddress = $params->{emailaddress} || $userenv->{email}; + my $desk_id = $params->{desk_id} || $userenv->{desk_id}; + my $desk_name = $params->{desk_name} || $userenv->{desk_name}; + my $register_id = $params->{register_id} || $userenv->{register_id}; + my $register_name = $params->{register_name} || $userenv->{register_name}; + my ($shibboleth); C4::Context->set_userenv( $usernum, $userid, $cardnumber, $firstname, diff --git a/t/lib/Mocks/Logger.pm b/t/lib/Mocks/Logger.pm index 22c967a58c..edbfab9325 100644 --- a/t/lib/Mocks/Logger.pm +++ b/t/lib/Mocks/Logger.pm @@ -46,7 +46,7 @@ sub new { my ( $class, $params ) = @_; my $mocked_logger_class = Test::MockModule->new("Koha::Logger"); - my $mocked_logger = Test::MockObject->new(); + my $mocked_logger = Test::MockObject->new(); $mocked_logger_class->mock( 'get', @@ -56,7 +56,8 @@ sub new { ); my $self = $class->SUPER::new( - { logger => $mocked_logger_class, + { + logger => $mocked_logger_class, debug => [], error => [], info => [], @@ -67,7 +68,7 @@ sub new { ); bless $self, $class; - foreach my $level (levels()) { + foreach my $level ( levels() ) { $mocked_logger->mock( $level, sub { @@ -90,7 +91,9 @@ Method for testing a message was written to the 'debug' log level. =cut sub debug_is { - my ( $self, $expect, $name ) = @_; $self->generic_is( 'debug', $expect, $name ); return $self; + my ( $self, $expect, $name ) = @_; + $self->generic_is( 'debug', $expect, $name ); + return $self; } =head3 error_is @@ -102,7 +105,9 @@ Method for testing a message was written to the 'error' log level. =cut sub error_is { - my ( $self, $expect, $name ) = @_; $self->generic_is( 'error', $expect, $name ); return $self; + my ( $self, $expect, $name ) = @_; + $self->generic_is( 'error', $expect, $name ); + return $self; } =head3 fatal_is @@ -114,7 +119,9 @@ Method for testing a message was written to the 'fatal' log level. =cut sub fatal_is { - my ( $self, $expect, $name ) = @_; $self->generic_is( 'fatal', $expect, $name ); return $self; + my ( $self, $expect, $name ) = @_; + $self->generic_is( 'fatal', $expect, $name ); + return $self; } =head3 info_is @@ -126,7 +133,9 @@ Method for testing a message was written to the 'info' log level. =cut sub info_is { - my ( $self, $expect, $name ) = @_; $self->generic_is( 'info', $expect, $name ); return $self; + my ( $self, $expect, $name ) = @_; + $self->generic_is( 'info', $expect, $name ); + return $self; } =head3 trace_is @@ -138,7 +147,9 @@ Method for testing a message was written to the 'trace' log level. =cut sub trace_is { - my ( $self, $expect, $name ) = @_; $self->generic_is( 'trace', $expect, $name ); return $self; + my ( $self, $expect, $name ) = @_; + $self->generic_is( 'trace', $expect, $name ); + return $self; } =head3 warn_is @@ -150,7 +161,9 @@ Method for testing a message was written to the 'warn' log level. =cut sub warn_is { - my ( $self, $expect, $name ) = @_; $self->generic_is( 'warn', $expect, $name ); return $self; + my ( $self, $expect, $name ) = @_; + $self->generic_is( 'warn', $expect, $name ); + return $self; } =head3 debug_like @@ -162,7 +175,9 @@ Method for testing a message matching a regex was written to the 'debug' log lev =cut sub debug_like { - my ( $self, $expect, $name ) = @_; $self->generic_like( 'debug', $expect, $name ); return $self; + my ( $self, $expect, $name ) = @_; + $self->generic_like( 'debug', $expect, $name ); + return $self; } =head3 error_like @@ -174,7 +189,9 @@ Method for testing a message matching a regex was written to the 'error' log lev =cut sub error_like { - my ( $self, $expect, $name ) = @_; $self->generic_like( 'error', $expect, $name ); return $self; + my ( $self, $expect, $name ) = @_; + $self->generic_like( 'error', $expect, $name ); + return $self; } =head3 fatal_like @@ -186,7 +203,9 @@ Method for testing a message matching a regex was written to the 'fatal' log lev =cut sub fatal_like { - my ( $self, $expect, $name ) = @_; $self->generic_like( 'fatal', $expect, $name ); return $self; + my ( $self, $expect, $name ) = @_; + $self->generic_like( 'fatal', $expect, $name ); + return $self; } =head3 info_like @@ -198,7 +217,9 @@ Method for testing a message matching a regex was written to the 'info' log leve =cut sub info_like { - my ( $self, $expect, $name ) = @_; $self->generic_like( 'info', $expect, $name ); return $self; + my ( $self, $expect, $name ) = @_; + $self->generic_like( 'info', $expect, $name ); + return $self; } =head3 trace_like @@ -210,7 +231,9 @@ Method for testing a message matching a regex was written to the 'trace' log lev =cut sub trace_like { - my ( $self, $expect, $name ) = @_; $self->generic_like( 'trace', $expect, $name ); return $self; + my ( $self, $expect, $name ) = @_; + $self->generic_like( 'trace', $expect, $name ); + return $self; } =head3 warn_like @@ -222,7 +245,9 @@ Method for testing a message matching a regex was written to the 'warn' log leve =cut sub warn_like { - my ( $self, $expect, $name ) = @_; $self->generic_like( 'warn', $expect, $name ); return $self; + my ( $self, $expect, $name ) = @_; + $self->generic_like( 'warn', $expect, $name ); + return $self; } =head3 count @@ -237,10 +262,10 @@ can be passed to restrict the count to the passed level. sub count { my ( $self, $level ) = @_; - unless ( $level ) { + unless ($level) { my $sum = 0; - map { $sum += scalar @{$self->{$_}} } levels(); + map { $sum += scalar @{ $self->{$_} } } levels(); return $sum; } @@ -262,11 +287,10 @@ pollution. sub clear { my ( $self, $level ) = @_; - if ( $level ) { + if ($level) { $self->{$level} = []; - } - else { - foreach my $l (levels()) { + } else { + foreach my $l ( levels() ) { $self->{$l} = []; } } @@ -290,7 +314,7 @@ sub generic_is { my $string = shift @{ $self->{$level} }; $string //= ''; my $tb = $CLASS->builder; - return $tb->is_eq( $string, $expect, $name); + return $tb->is_eq( $string, $expect, $name ); } =head3 generic_like @@ -307,7 +331,7 @@ sub generic_like { my $string = shift @{ $self->{$level} }; $string //= ''; my $tb = $CLASS->builder; - return $tb->like( $string, $expect, $name); + return $tb->like( $string, $expect, $name ); } =head3 levels diff --git a/t/lib/Mocks/Zebra.pm b/t/lib/Mocks/Zebra.pm index ef27d36ec7..b5e307cb18 100644 --- a/t/lib/Mocks/Zebra.pm +++ b/t/lib/Mocks/Zebra.pm @@ -18,9 +18,9 @@ package t::lib::Mocks::Zebra; use Modern::Perl; use Test::More; use File::Basename qw(dirname ); -use File::Temp qw( tempdir ); -use File::Path qw( rmtree ); -use JSON qw( decode_json ); +use File::Temp qw( tempdir ); +use File::Path qw( rmtree ); +use JSON qw( decode_json ); use C4::ImportBatch; use Koha::BackgroundJobs; use Koha::Token; @@ -39,17 +39,16 @@ and the usual zebra db will not be affected. However you must pass $ENV{KOHA_CON =cut - sub new { my ( $class, $params ) = @_; - my $marcflavour = $params->{marcflavour} ? lc($params->{marcflavour}) : 'marc21'; - my $koha_conf = $params->{koha_conf}; + my $marcflavour = $params->{marcflavour} ? lc( $params->{marcflavour} ) : 'marc21'; + my $koha_conf = $params->{koha_conf}; my $datadir = tempdir(); my $zebra_db_dir; - unless ( $koha_conf ) { - system(dirname(__FILE__) . "/../../db_dependent/zebra_config.pl $datadir $marcflavour"); + unless ($koha_conf) { + system( dirname(__FILE__) . "/../../db_dependent/zebra_config.pl $datadir $marcflavour" ); Koha::Caches->get_instance('config')->flush_all; $koha_conf = "$datadir/etc/koha-conf.xml"; @@ -57,16 +56,16 @@ sub new { $context->set_context(); $zebra_db_dir = "$datadir/etc/koha/zebradb/"; } else { - $koha_conf = $ENV{KOHA_CONF}; + $koha_conf = $ENV{KOHA_CONF}; $zebra_db_dir = dirname($koha_conf); } my $self = { - datadir => $datadir, - koha_conf => $koha_conf, + datadir => $datadir, + koha_conf => $koha_conf, zebra_db_dir => $zebra_db_dir, - intranet => $params->{intranet}, - opac => $params->{opac} + intranet => $params->{intranet}, + opac => $params->{opac} }; return bless $self, $class; @@ -74,9 +73,9 @@ sub new { # function that launches the zebra daemon sub launch_zebra { - my ( $self ) = @_; + my ($self) = @_; - my $datadir = $self->{datadir}; + my $datadir = $self->{datadir}; my $koha_conf = $self->{koha_conf}; unlink("$datadir/zebra.log"); @@ -85,12 +84,12 @@ sub launch_zebra { exec("zebrasrv -f $koha_conf -v none,request -l $datadir/zebra.log"); exit; } - sleep( 1 ); + sleep(1); $self->{zebra_pid} = $zebra_pid; } sub launch_indexer { - my ($self) = @_; + my ($self) = @_; my $rootdir = dirname(__FILE__) . '/../../../'; my $rebuild_zebra = "$rootdir/misc/migration_tools/rebuild_zebra.pl"; @@ -100,25 +99,27 @@ sub launch_indexer { exec("$rebuild_zebra -daemon -sleep 5"); exit; } - sleep( 1 ); + sleep(1); $self->{indexer_pid} = $indexer_pid; } sub load_records { my ( $self, $marc_dir, $marc_format, $record_type, $init ) = @_; - my $datadir = $self->{datadir}; + my $datadir = $self->{datadir}; my $zebra_cfg = $self->{zebra_db_dir} - . ( $record_type eq 'biblios' + . ( + $record_type eq 'biblios' ? '/zebra-biblios-dom.cfg' - : '/zebra-authorities-dom.cfg' ); + : '/zebra-authorities-dom.cfg' + ); my @cmds; push @cmds, "zebraidx -c $zebra_cfg -v none,fatal -g $marc_format -d $record_type init" if $init; push @cmds, "zebraidx -c $zebra_cfg -v none,fatal -g $marc_format -d $record_type update $marc_dir"; push @cmds, "zebraidx -c $zebra_cfg -v none,fatal -g $marc_format -d $record_type commit"; - for my $cmd ( @cmds ) { + for my $cmd (@cmds) { system($cmd); } } @@ -131,19 +132,21 @@ sub load_records_ui { our $agent = Test::WWW::Mechanize->new( autocheck => 1 ); $agent->get_ok( "$cgi_root/mainpage.pl", 'connect to intranet' ); $agent->form_name('loginform'); - $agent->field( 'login_userid', $ENV{KOHA_PASS} ); + $agent->field( 'login_userid', $ENV{KOHA_PASS} ); $agent->field( 'login_password', $ENV{KOHA_USER} ); - $agent->field( 'branch', '' ); + $agent->field( 'branch', '' ); $agent->click_ok( '', 'login to staff interface' ); $agent->get_ok( "$cgi_root/mainpage.pl", 'load main page' ); $agent->follow_link_ok( { url_regex => qr/cataloging-home/i }, 'open caaloging module' ); - $agent->follow_link_ok( { text => 'Stage records for import' }, - 'go to stage MARC' ); + $agent->follow_link_ok( + { text => 'Stage records for import' }, + 'go to stage MARC' + ); my $session_id = $agent->cookie_jar->get_cookies( $self->{intranet} )->{CGISESSID}; - my $csrf_token = Koha::Token->new->generate_csrf({session_id => $session_id}); + my $csrf_token = Koha::Token->new->generate_csrf( { session_id => $session_id } ); $agent->post( "$cgi_root/tools/upload-file.pl?temp=1", [ 'fileToUpload' => [$file], csrf_token => $csrf_token ], @@ -155,37 +158,40 @@ sub load_records_ui { is( $jsonresponse->{'status'}, 'done', 'upload succeeded' ); my $fileid = $jsonresponse->{'fileid'}; - $agent->get_ok( "$cgi_root/tools/stage-marc-import.pl", - 'reopen stage MARC page' ); + $agent->get_ok( + "$cgi_root/tools/stage-marc-import.pl", + 'reopen stage MARC page' + ); $agent->submit_form_ok( { form_id => 'processfile', - fields => { - 'uploadedfileid' => $fileid, - 'nomatch_action' => 'create_new', - 'overlay_action' => 'replace', - 'item_action' => 'always_add', - 'matcher' => '', - 'comments' => '', - 'encoding' => 'utf8', - 'parse_items' => '1', - 'record_type' => 'biblio', - op => 'cud-stage', - csrf_token => $csrf_token, # TODO May need to retrieve another token if we invalid them at some point + fields => { + 'uploadedfileid' => $fileid, + 'nomatch_action' => 'create_new', + 'overlay_action' => 'replace', + 'item_action' => 'always_add', + 'matcher' => '', + 'comments' => '', + 'encoding' => 'utf8', + 'parse_items' => '1', + 'record_type' => 'biblio', + op => 'cud-stage', + csrf_token => $csrf_token, # TODO May need to retrieve another token if we invalid them at some point } }, 'stage MARC' ); sleep(1); + # FIXME - This if fragile and can fail if there is a race condition - my $job = Koha::BackgroundJobs->search({ type => 'stage_marc_for_import' })->last; + my $job = Koha::BackgroundJobs->search( { type => 'stage_marc_for_import' } )->last; my $i; while ( $job->discard_changes->status ne 'finished' ) { sleep(1); last if ++$i > 10; } - is ( $job->status, 'finished', 'job is finished' ); + is( $job->status, 'finished', 'job is finished' ); $job->discard_changes; my $import_batch_id = $job->report->{import_batch_id}; @@ -208,25 +214,28 @@ sub load_records_ui { sub clean_records { my ( $self, $batch_id ) = @_; - my $agent = Test::WWW::Mechanize->new( autocheck => 1 ); + my $agent = Test::WWW::Mechanize->new( autocheck => 1 ); my $cgi_root = $self->{intranet} . '/cgi-bin/koha'; - my $data = C4::ImportBatch::GetImportRecordsRange($batch_id, '', '', undef, - { order_by => 'import_record_id', order_by_direction => 'DESC' }); + my $data = C4::ImportBatch::GetImportRecordsRange( + $batch_id, '', '', undef, + { order_by => 'import_record_id', order_by_direction => 'DESC' } + ); my $biblionumber = $data->[0]->{'matched_biblionumber'}; $agent->get_ok( "$cgi_root/tools/manage-marc-import.pl", 'view and clean batch' ); - $agent->form_name('clean_batch_'.$batch_id); + $agent->form_name( 'clean_batch_' . $batch_id ); $agent->click(); - $agent->get_ok( "$cgi_root/catalogue/detail.pl?biblionumber=$biblionumber", 'biblio on intranet' ); + $agent->get_ok( "$cgi_root/catalogue/detail.pl?biblionumber=$biblionumber", 'biblio on intranet' ); $agent->get_ok( "$cgi_root/cataloguing/addbiblio.pl?op=delete&biblionumber=$biblionumber", 'biblio deleted' ); } sub cleanup { - my ( $self ) = @_; + my ($self) = @_; kill 9, $self->{zebra_pid} if defined $self->{zebra_pid}; kill 9, $self->{indexer_pid} if defined $self->{indexer_pid}; + # Clean up the Zebra files since the child process was just shot rmtree $self->{datadir}; } diff --git a/t/lib/QA/TemplateFilters.pm b/t/lib/QA/TemplateFilters.pm index 4f3825fbcc..142527e9e1 100644 --- a/t/lib/QA/TemplateFilters.pm +++ b/t/lib/QA/TemplateFilters.pm @@ -35,11 +35,11 @@ our @tt_methods = ( ); sub fix_filters { - return _process_tt_content( @_ )->{new_content}; + return _process_tt_content(@_)->{new_content}; } sub missing_filters { - return @{_process_tt_content( @_ )->{errors}}; + return @{ _process_tt_content(@_)->{errors} }; } @@ -62,11 +62,11 @@ sub _process_tt_content { # Do we have Asset without the raw filter? if ( $line =~ m{^\s*\[% Asset} && $line !~ m{\|\s*\$raw} ) { push @errors, - { + { error => 'asset_must_be_raw', line => $line, line_number => $line_number - }; + }; $new_line =~ s/\)\s*%]/) | \$raw %]/; $use_raw = 1; push @new_lines, $new_line; @@ -74,7 +74,7 @@ sub _process_tt_content { } $has_use_raw++ - if $line =~ m{\[%(\s|-|~)*USE raw(\s|-|~)*%\]}; # Does [% Use raw %] exist? + if $line =~ m{\[%(\s|-|~)*USE raw(\s|-|~)*%\]}; # Does [% Use raw %] exist? my $e; while ( $line =~ m{<a href="([^"]+)}g ) { @@ -86,9 +86,9 @@ sub _process_tt_content { (?<tt_block>[^%\-~]+) (?<post_chomp>(\s|\-|~)*) %\]}gmxs - ) + ) { - ( $new_line, $e ) = process_tt_block($new_line, { %+, filter => 'uri' }); + ( $new_line, $e ) = process_tt_block( $new_line, { %+, filter => 'uri' } ); push @errors, { line => $line, line_number => $line_number, error => $e } if $e; } } @@ -101,15 +101,14 @@ sub _process_tt_content { (?<tt_block>[^%\-~]+) (?<post_chomp>(\s|\-|~)*) %\]}gmxs - ) + ) { - ( $new_line, $e ) = process_tt_block($new_line, \%+); + ( $new_line, $e ) = process_tt_block( $new_line, \%+ ); push @errors, { line => $line, line_number => $line_number, error => $e } if $e; } push @new_lines, $new_line; - } - else { + } else { push @new_lines, $new_line; } @@ -117,7 +116,7 @@ sub _process_tt_content { # Adding [% USE raw %] on top if the filter is used @new_lines = ( '[% USE raw %]', @new_lines ) - if $use_raw and not $has_use_raw; + if $use_raw and not $has_use_raw; my $new_content = join "\n", @new_lines; return { errors => \@errors, new_content => $new_content }; @@ -132,6 +131,7 @@ sub process_tt_block { my $error; return ( $line, $error ) if + # It's a TT directive, no filters needed grep { $tt_block =~ $_ } @tt_directives @@ -165,33 +165,29 @@ sub process_tt_block { or $tt_block =~ m{\|\s?safe_url} # Specific for [% foo UNLESS bar %] - or $tt_block =~ m{^(?<before>\S+)\s+UNLESS\s+(?<after>\S+)} - ; + or $tt_block =~ m{^(?<before>\S+)\s+UNLESS\s+(?<after>\S+)}; $pre_chomp = - $pre_chomp - ? $pre_chomp =~ m|-| - ? q|- | - : $pre_chomp =~ m|~| - ? q|~ | - : q| | - : q| |; + $pre_chomp + ? $pre_chomp =~ m|-| + ? q|- | + : $pre_chomp =~ m|~| ? q|~ | + : q| | + : q| |; $post_chomp = - $post_chomp - ? $post_chomp =~ m|-| - ? q| -| - : $post_chomp =~ m|~| - ? q| ~| - : q| | - : q| |; + $post_chomp + ? $post_chomp =~ m|-| + ? q| -| + : $post_chomp =~ m|~| ? q| ~| + : q| | + : q| |; if ( $tt_block =~ m{\s?\|\s?\$KohaDates[^\|]*\|.*$} or $tt_block =~ m{\s?\|\s?\$Price[^\|]*\|.*$} - or $tt_block =~ m{\s?\|\s?\$HtmlTags[^\|]*\|.*$} - ) { - $tt_block =~ - s/\s*\|\s*(uri|url|html)\s*$//; # Could be another filter... - $line =~ s{ + or $tt_block =~ m{\s?\|\s?\$HtmlTags[^\|]*\|.*$} ) + { + $tt_block =~ s/\s*\|\s*(uri|url|html)\s*$//; # Could be another filter... + $line =~ s{ \[% \s*$pre_chomp\s* \Q$tt_block\E\s*\|\s*(uri|url|html) @@ -205,16 +201,14 @@ sub process_tt_block { if ( # Use the uri filter is needed # If html filtered or not filtered - $filter ne 'html' - and ( - $tt_block !~ m{\|} - or ($tt_block =~ m{\|\s?html} and not $tt_block =~ m{\|\s?html_entity}) - or $tt_block !~ m{\s*|\s*(uri|url)} - ) - ) { - $tt_block =~ s/^\s*|\s*$//g; # trim + $filter ne 'html' and ( $tt_block !~ m{\|} + or ( $tt_block =~ m{\|\s?html} and not $tt_block =~ m{\|\s?html_entity} ) + or $tt_block !~ m{\s*|\s*(uri|url)} ) + ) + { + $tt_block =~ s/^\s*|\s*$//g; # trim $tt_block =~ s/\s*\|\s*html\s*//; - $line =~ s{ + $line =~ s{ \[% \s*$pre_chomp\s* \Q$tt_block\E(\s*\|\s*html)? @@ -223,13 +217,12 @@ sub process_tt_block { }{[%$pre_chomp$tt_block | uri$post_chomp%]}xms; $error = 'wrong_html_filter'; - } - elsif ( - $tt_block !~ m{\|\s?html} # already has html filter - ) + } elsif ( + $tt_block !~ m{\|\s?html} # already has html filter + ) { - $tt_block =~ s/^\s*|\s*$//g; # trim - $line =~ s{ + $tt_block =~ s/^\s*|\s*$//g; # trim + $line =~ s{ \[% \s*$pre_chomp\s* \Q$tt_block\E diff --git a/t/lib/Selenium.pm b/t/lib/Selenium.pm index 18b9f3d050..f236d344be 100644 --- a/t/lib/Selenium.pm +++ b/t/lib/Selenium.pm @@ -15,7 +15,6 @@ package t::lib::Selenium; # You should have received a copy of the GNU General Public License # along with Koha; if not, see <http://www.gnu.org/licenses>. - use Modern::Perl; use Carp qw( croak ); @@ -35,13 +34,13 @@ sub new { my ( $class, $params ) = @_; my $self = {}; my $config = $class->config; - $self->{login} = $params->{login} || $config->{login}; - $self->{password} = $params->{password} || $config->{password}; - $self->{base_url} = $params->{base_url} || $config->{base_url}; + $self->{login} = $params->{login} || $config->{login}; + $self->{password} = $params->{password} || $config->{password}; + $self->{base_url} = $params->{base_url} || $config->{base_url}; $self->{opac_base_url} = $params->{opac_base_url} || $config->{opac_base_url}; $self->{selenium_addr} = $params->{selenium_addr} || $config->{selenium_addr}; $self->{selenium_port} = $params->{selenium_port} || $config->{selenium_port}; - $self->{driver} = Selenium::Remote::Driver->new( + $self->{driver} = Selenium::Remote::Driver->new( port => $self->{selenium_port}, remote_server_addr => $self->{selenium_addr}, ); @@ -52,17 +51,17 @@ sub new { } sub add_error_handler { - my ( $self ) = @_; + my ($self) = @_; $self->{driver}->error_handler( sub { my ( $driver, $selenium_error ) = @_; print STDERR "\nSTRACE:"; my $i = 1; - while ( (my @call_details = (caller($i++))) ){ - print STDERR "\t" . $call_details[1]. ":" . $call_details[2] . " in " . $call_details[3]."\n"; + while ( ( my @call_details = ( caller( $i++ ) ) ) ) { + print STDERR "\t" . $call_details[1] . ":" . $call_details[2] . " in " . $call_details[3] . "\n"; } print STDERR "\n"; - $self->capture( $driver ); + $self->capture($driver); $driver->quit(); croak $selenium_error; } @@ -70,8 +69,8 @@ sub add_error_handler { } sub remove_error_handler { - my ( $self ) = @_; - $self->{driver}->error_handler( sub {} ); + my ($self) = @_; + $self->{driver}->error_handler( sub { } ); } sub config { @@ -88,7 +87,7 @@ sub config { sub auth { my ( $self, $login, $password ) = @_; - $login ||= $self->login; + $login ||= $self->login; $password ||= $self->password; my $mainpage = $self->base_url . 'mainpage.pl'; @@ -101,11 +100,11 @@ sub auth { sub opac_auth { my ( $self, $login, $password ) = @_; - $login ||= $self->login; + $login ||= $self->login; $password ||= $self->password; my $mainpage = $self->opac_base_url . 'opac-main.pl'; - $self->driver->get($mainpage . q|?logout.x=1|); # Logout before, to make sure we will see the login form + $self->driver->get( $mainpage . q|?logout.x=1| ); # Logout before, to make sure we will see the login form $self->driver->get($mainpage); $self->fill_form( { userid => $login, password => $password } ); $self->submit_form; @@ -131,7 +130,7 @@ sub fill_form { } sub submit_form { - my ( $self ) = @_; + my ($self) = @_; # If there is only one submit element on the page we use it my @submit_elements = $self->driver->find_elements('//input[@type="submit"]'); @@ -141,7 +140,8 @@ sub submit_form { } my $default_submit_selector = '//fieldset[@class="action"]/input[@type="submit"]'; - my @elts = map { my $size = $_->get_size; ( $size->{height} && $size->{width} ) ? $_ : () } $self->driver->find_elements($default_submit_selector); + my @elts = map { my $size = $_->get_size; ( $size->{height} && $size->{width} ) ? $_ : () } + $self->driver->find_elements($default_submit_selector); die "Too many forms are displayed. Cannot submit." if @elts > 1; @@ -152,43 +152,49 @@ sub click { my ( $self, $params ) = @_; my $xpath_selector; if ( exists $params->{main} ) { - $xpath_selector = '//div[@id="'.$params->{main}.'"]'; + $xpath_selector = '//div[@id="' . $params->{main} . '"]'; } elsif ( exists $params->{main_class} ) { - $xpath_selector = '//div[@class="'.$params->{main_class}.'"]'; + $xpath_selector = '//div[@class="' . $params->{main_class} . '"]'; } if ( exists $params->{href} ) { if ( ref( $params->{href} ) ) { for my $k ( keys %{ $params->{href} } ) { if ( $k eq 'ends-with' ) { + # ends-with version for xpath version 1 my $ends_with = $params->{href}{"ends-with"}; - $xpath_selector .= '//a[substring(@href, string-length(@href) - string-length("'.$ends_with.'") + 1 ) = "'.$ends_with.'"]'; + $xpath_selector .= + '//a[substring(@href, string-length(@href) - string-length("' + . $ends_with + . '") + 1 ) = "' + . $ends_with . '"]'; + # ends-with version for xpath version 2 #$xpath_selector .= '//a[ends-with(@href, "'.$ends_with.'") ]'; - } else { + } else { die "Only ends-with is supported so far ($k)"; } } } else { - $xpath_selector .= '//a[contains(@href, "'.$params->{href}.'")]'; + $xpath_selector .= '//a[contains(@href, "' . $params->{href} . '")]'; } } if ( exists $params->{id} ) { - $xpath_selector .= '//*[@id="'.$params->{id}.'"]'; + $xpath_selector .= '//*[@id="' . $params->{id} . '"]'; } - $self->driver->find_element($xpath_selector)->click + $self->driver->find_element($xpath_selector)->click; } sub wait_for_element_visible { my ( $self, $xpath_selector ) = @_; - my ($visible, $elt); + my ( $visible, $elt ); $self->remove_error_handler; my $max_retries = $self->max_retries; my $i; while ( not $visible ) { - $elt = eval {$self->driver->find_element($xpath_selector) }; + $elt = eval { $self->driver->find_element($xpath_selector) }; $visible = $elt && $elt->is_displayed; $self->driver->pause(1000) unless $visible; @@ -222,7 +228,7 @@ sub wait_for_element_hidden { } sub wait_for_ajax { - my ( $self ) = @_; + my ($self) = @_; my $is_ready; my $max_retries = $self->max_retries; @@ -232,12 +238,12 @@ sub wait_for_ajax { $self->driver->pause(1000) unless $is_ready; die "Cannot wait more for jQuery to be active (wait_for_ajax)" - if $max_retries <= ++$i + if $max_retries <= ++$i; } } sub get_next_alert_text { - my ( $self ) = @_; + my ($self) = @_; my $alert_text; my $max_retries = $self->max_retries; @@ -248,7 +254,7 @@ sub get_next_alert_text { $self->driver->pause(1000) unless $alert_text; die "Cannot wait more for next alert (get_next_alert)" - if $max_retries <= ++$i; + if $max_retries <= ++$i; } $self->add_error_handler; return $alert_text; @@ -257,14 +263,12 @@ sub get_next_alert_text { sub show_all_entries { my ( $self, $xpath_selector ) = @_; - $self->driver->find_element( $xpath_selector - . '//div[@class="dt-length"]/label/select/option[@value="-1"]' - )->click; - my ($all_displayed, $i); + $self->driver->find_element( $xpath_selector . '//div[@class="dt-length"]/label/select/option[@value="-1"]' ) + ->click; + my ( $all_displayed, $i ); my $max_retries = $self->max_retries; while ( not $all_displayed ) { - my $dt_infos = $self->driver->get_text( - $xpath_selector . '//div[@class="dt-info"]' ); + my $dt_infos = $self->driver->get_text( $xpath_selector . '//div[@class="dt-info"]' ); if ( $dt_infos =~ m|Showing 1 to (\d+) of (\d+) entries| ) { $all_displayed = 1 if $1 == $2; @@ -273,14 +277,14 @@ sub show_all_entries { $self->driver->pause(1000) unless $all_displayed; die "Cannot show all entries from table $xpath_selector" - if $max_retries <= ++$i + if $max_retries <= ++$i; } } sub click_when_visible { my ( $self, $xpath_selector ) = @_; - my $elt = $self->wait_for_element_visible( $xpath_selector ); + my $elt = $self->wait_for_element_visible($xpath_selector); my $clicked; $self->remove_error_handler; @@ -290,7 +294,7 @@ sub click_when_visible { $self->driver->pause(1000) unless $clicked; } $self->add_error_handler; - $elt->click unless $clicked; # finally Raise the error + $elt->click unless $clicked; # finally Raise the error } sub max_retries { 10 } diff --git a/t/lib/TestBuilder.pm b/t/lib/TestBuilder.pm index ec618ebffa..bf48b718e6 100644 --- a/t/lib/TestBuilder.pm +++ b/t/lib/TestBuilder.pm @@ -2,20 +2,20 @@ package t::lib::TestBuilder; use Modern::Perl; -use Koha::Database qw( schema ); -use C4::Biblio qw( AddBiblio ); -use Koha::Biblios qw( _type ); -use Koha::Items qw( _type ); +use Koha::Database qw( schema ); +use C4::Biblio qw( AddBiblio ); +use Koha::Biblios qw( _type ); +use Koha::Items qw( _type ); use Koha::DateUtils qw( dt_from_string ); use Bytes::Random::Secure; -use Carp qw( carp ); +use Carp qw( carp ); use Module::Load qw( load ); use String::Random; use Array::Utils qw( array_minus ); use constant { - SIZE_BARCODE => 20, # Not perfect but avoid to fetch the value when creating a new item + SIZE_BARCODE => 20, # Not perfect but avoid to fetch the value when creating a new item }; sub new { @@ -26,15 +26,15 @@ sub new { $self->schema( Koha::Database->new()->schema ); $self->schema->storage->sql_maker->quote_char('`'); - $self->{gen_type} = _gen_type(); + $self->{gen_type} = _gen_type(); $self->{default_values} = _gen_default_values(); return $self; } sub schema { - my ($self, $schema) = @_; + my ( $self, $schema ) = @_; - if( defined( $schema ) ) { + if ( defined($schema) ) { $self->{schema} = $schema; } return $self->{schema}; @@ -45,18 +45,20 @@ sub schema { sub delete { my ( $self, $params ) = @_; my $source = $params->{source} || return; - my @recs = ref( $params->{records} ) eq 'ARRAY'? - @{$params->{records}}: ( $params->{records} // () ); + my @recs = ref( $params->{records} ) eq 'ARRAY' ? @{ $params->{records} } : ( $params->{records} // () ); + # tables without PK are not supported - my @pk = $self->schema->source( $source )->primary_columns; + my @pk = $self->schema->source($source)->primary_columns; return if !@pk; my $rv = 0; - foreach my $rec ( @recs ) { - # delete only works when you supply full primary key values - # $cond does not include searches for undef (not allowed in PK) - my $cond = { map { defined $rec->{$_}? ($_, $rec->{$_}): (); } @pk }; + foreach my $rec (@recs) { + + # delete only works when you supply full primary key values + # $cond does not include searches for undef (not allowed in PK) + my $cond = { map { defined $rec->{$_} ? ( $_, $rec->{$_} ) : (); } @pk }; next if keys %$cond < @pk; - $self->schema->resultset( $source )->search( $cond )->delete; + $self->schema->resultset($source)->search($cond)->delete; + # we clear the pk columns in the supplied hash # this indirectly signals at least an attempt to delete map { delete $rec->{$_}; } @pk; @@ -76,96 +78,102 @@ sub build_object { return; } - my @unknowns = grep( !/^(class|value)$/, keys %{ $params }); + my @unknowns = grep( !/^(class|value)$/, keys %{$params} ); carp "Unknown parameter(s): ", join( ', ', @unknowns ) if scalar @unknowns; load $class; my $source = $class->_type; - my $hashref = $self->build({ source => $source, value => $value }); + my $hashref = $self->build( { source => $source, value => $value } ); my $object; if ( $class eq 'Koha::Old::Patrons' ) { - $object = $class->search({ borrowernumber => $hashref->{borrowernumber} })->next; + $object = $class->search( { borrowernumber => $hashref->{borrowernumber} } )->next; } elsif ( $class eq 'Koha::Statistics' ) { - $object = $class->search({ datetime => $hashref->{datetime} })->next; + $object = $class->search( { datetime => $hashref->{datetime} } )->next; } else { my @ids; my @pks = $self->schema->source( $class->_type )->primary_columns; - foreach my $pk ( @pks ) { - push @ids, $hashref->{ $pk }; + foreach my $pk (@pks) { + push @ids, $hashref->{$pk}; } - $object = $class->find( @ids ); + $object = $class->find(@ids); } return $object; } sub build { -# build returns a hash of column values for a created record, or undef -# build does NOT update a record, or pass back values of an existing record - my ($self, $params) = @_; - my $source = $params->{source}; - if( !$source ) { + + # build returns a hash of column values for a created record, or undef + # build does NOT update a record, or pass back values of an existing record + my ( $self, $params ) = @_; + my $source = $params->{source}; + if ( !$source ) { carp "Source parameter not specified!"; return; } - my $value = $params->{value}; + my $value = $params->{value}; - my @unknowns = grep( !/^(source|value)$/, keys %{ $params }); + my @unknowns = grep( !/^(source|value)$/, keys %{$params} ); carp "Unknown parameter(s): ", join( ', ', @unknowns ) if scalar @unknowns; - my $col_values = $self->_buildColumnValues({ - source => $source, - value => $value, - }); - return if !$col_values; # did not meet unique constraints? + my $col_values = $self->_buildColumnValues( + { + source => $source, + value => $value, + } + ); + return if !$col_values; # did not meet unique constraints? # loop thru all fk and create linked records if needed # fills remaining entries in $col_values my $foreign_keys = $self->_getForeignKeys( { source => $source } ); - my $col_names = {}; - for my $fk ( @$foreign_keys ) { + my $col_names = {}; + for my $fk (@$foreign_keys) { + # skip when FK points to itself: e.g. borrowers:guarantorid next if $fk->{source} eq $source; # If we have more than one FK on the same column, we only generate values for the first one next - if scalar @{ $fk->{keys} } == 1 - && exists $col_names->{ $fk->{keys}->[0]->{col_name} }; + if scalar @{ $fk->{keys} } == 1 + && exists $col_names->{ $fk->{keys}->[0]->{col_name} }; my $keys = $fk->{keys}; - my $tbl = $fk->{source}; - my $res = $self->_create_links( $tbl, $keys, $col_values, $value ); - return if !$res; # failed: no need to go further - foreach( keys %$res ) { # save new values + my $tbl = $fk->{source}; + my $res = $self->_create_links( $tbl, $keys, $col_values, $value ); + return if !$res; # failed: no need to go further + foreach ( keys %$res ) { # save new values $col_values->{$_} = $res->{$_}; } $col_names->{ $fk->{keys}->[0]->{col_name} } = 1 - if scalar @{ $fk->{keys} } == 1 + if scalar @{ $fk->{keys} } == 1; } # store this record and return hashref - return $self->_storeColumnValues({ - source => $source, - values => $col_values, - }); + return $self->_storeColumnValues( + { + source => $source, + values => $col_values, + } + ); } sub build_sample_biblio { my ( $self, $args ) = @_; - my $title = $args->{title} || 'Some boring read'; - my $author = $args->{author} || 'Some boring author'; + my $title = $args->{title} || 'Some boring read'; + my $author = $args->{author} || 'Some boring author'; my $frameworkcode = $args->{frameworkcode} || ''; - my $itemtype = $args->{itemtype} - || $self->build_object( { class => 'Koha::ItemTypes' } )->itemtype; + my $itemtype = $args->{itemtype} + || $self->build_object( { class => 'Koha::ItemTypes' } )->itemtype; my $marcflavour = C4::Context->preference('marcflavour'); my $record = MARC::Record->new(); - $record->encoding( 'UTF-8' ); + $record->encoding('UTF-8'); my ( $tag, $subfield ) = $marcflavour eq 'UNIMARC' ? ( 200, 'a' ) : ( 245, 'a' ); $record->append_fields( @@ -178,9 +186,7 @@ sub build_sample_biblio { ); ( $tag, $subfield ) = $marcflavour eq 'UNIMARC' ? ( '099', 't' ) : ( 942, 'c' ); - $record->append_fields( - MARC::Field->new( $tag, ' ', ' ', $subfield => $itemtype ) - ); + $record->append_fields( MARC::Field->new( $tag, ' ', ' ', $subfield => $itemtype ) ); my ($biblio_id) = C4::Biblio::AddBiblio( $record, $frameworkcode ); return Koha::Biblios->find($biblio_id); @@ -189,15 +195,14 @@ sub build_sample_biblio { sub build_sample_item { my ( $self, $args ) = @_; - my $biblionumber = - delete $args->{biblionumber} || $self->build_sample_biblio->biblionumber; - my $library = delete $args->{library} - || $self->build_object( { class => 'Koha::Libraries' } )->branchcode; + my $biblionumber = delete $args->{biblionumber} || $self->build_sample_biblio->biblionumber; + my $library = delete $args->{library} + || $self->build_object( { class => 'Koha::Libraries' } )->branchcode; # If itype is not passed it will be picked from the biblio (see Koha::Item->store) my $barcode = delete $args->{barcode} - || $self->_gen_text( { info => { size => SIZE_BARCODE } } ); + || $self->_gen_text( { info => { size => SIZE_BARCODE } } ); return Koha::Item->new( { @@ -229,55 +234,60 @@ sub build_sample_ill_request { # Internal helper routines sub _create_links { -# returns undef for failure to create linked records -# otherwise returns hashref containing new column values for parent record + + # returns undef for failure to create linked records + # otherwise returns hashref containing new column values for parent record my ( $self, $linked_tbl, $keys, $col_values, $value ) = @_; my $fk_value = {}; my ( $cnt_scalar, $cnt_null ) = ( 0, 0 ); # First, collect all values for creating a linked record (if needed) - foreach my $fk ( @$keys ) { + foreach my $fk (@$keys) { my ( $col, $destcol ) = ( $fk->{col_name}, $fk->{col_fk_name} ); - if( ref( $value->{$col} ) eq 'HASH' ) { + if ( ref( $value->{$col} ) eq 'HASH' ) { + # add all keys from the FK hash $fk_value = { %{ $value->{$col} }, %$fk_value }; } - if( exists $col_values->{$col} ) { + if ( exists $col_values->{$col} ) { + # add specific value (this does not necessarily exclude some # values from the hash in the preceding if) - $fk_value->{ $destcol } = $col_values->{ $col }; + $fk_value->{$destcol} = $col_values->{$col}; $cnt_scalar++; $cnt_null++ if !defined( $col_values->{$col} ); } } # If we saw all FK columns, first run the following checks - if( $cnt_scalar == @$keys ) { + if ( $cnt_scalar == @$keys ) { + # if one or more fk cols are null, the FK constraint will not be forced return {} if $cnt_null > 0; # does the record exist already? - my @pks = $self->schema->source( $linked_tbl )->primary_columns; + my @pks = $self->schema->source($linked_tbl)->primary_columns; my %fk_pk_value; for (@pks) { $fk_pk_value{$_} = $fk_value->{$_} if defined $fk_value->{$_}; } - return {} if !(keys %fk_pk_value); + return {} if !( keys %fk_pk_value ); return {} if $self->schema->resultset($linked_tbl)->find( \%fk_pk_value ); } + # create record with a recursive build call - my $row = $self->build({ source => $linked_tbl, value => $fk_value }); - return if !$row; # failure + my $row = $self->build( { source => $linked_tbl, value => $fk_value } ); + return if !$row; # failure # Finally, only return the new values my $rv = {}; - foreach my $fk ( @$keys ) { + foreach my $fk (@$keys) { my ( $col, $destcol ) = ( $fk->{col_name}, $fk->{col_fk_name} ); - next if exists $col_values->{ $col }; - $rv->{ $col } = $row->{ $destcol }; + next if exists $col_values->{$col}; + $rv->{$col} = $row->{$destcol}; } - return $rv; # success + return $rv; # success } sub _formatSource { @@ -288,63 +298,66 @@ sub _formatSource { } sub _buildColumnValues { - my ($self, $params) = @_; - my $source = _formatSource( $params ) || return; + my ( $self, $params ) = @_; + my $source = _formatSource($params) || return; my $original_value = $params->{value}; - my $col_values = {}; - my @columns = $self->schema->source($source)->columns; + my $col_values = {}; + my @columns = $self->schema->source($source)->columns; my %unique_constraints = $self->schema->source($source)->unique_constraints(); - my @passed_keys = grep { ref($original_value->{$_}) ne 'HASH' } keys %$original_value; - my @minus = array_minus( @passed_keys, @columns ); - die "Error: value hash contains unrecognized columns: ". (join ',', @minus) if @minus; + my @passed_keys = grep { ref( $original_value->{$_} ) ne 'HASH' } keys %$original_value; + my @minus = array_minus( @passed_keys, @columns ); + die "Error: value hash contains unrecognized columns: " . ( join ',', @minus ) if @minus; my $build_value = 5; + # we try max $build_value times if there are unique constraints - BUILD_VALUE: while ( $build_value ) { +BUILD_VALUE: while ($build_value) { + # generate random values for all columns - for my $col_name( @columns ) { - my $valref = $self->_buildColumnValue({ - source => $source, - column_name => $col_name, - value => $original_value, - }); - return if !$valref; # failure - if( @$valref ) { # could be empty - # there will be only one value, but it could be undef + for my $col_name (@columns) { + my $valref = $self->_buildColumnValue( + { + source => $source, + column_name => $col_name, + value => $original_value, + } + ); + return if !$valref; # failure + if (@$valref) { # could be empty + # there will be only one value, but it could be undef $col_values->{$col_name} = $valref->[0]; } } # verify the data would respect each unique constraint # note that this is INCOMPLETE since not all col_values are filled - CONSTRAINTS: foreach my $constraint (keys %unique_constraints) { + CONSTRAINTS: foreach my $constraint ( keys %unique_constraints ) { - my $condition; - my $constraint_columns = $unique_constraints{$constraint}; - # loop through all constraint columns and build the condition - foreach my $constraint_column ( @$constraint_columns ) { - # build the filter - # if one column does not exist or is undef, skip it - # an insert with a null will not trigger the constraint - next CONSTRAINTS - if !exists $col_values->{ $constraint_column } || - !defined $col_values->{ $constraint_column }; - $condition->{ $constraint_column } = - $col_values->{ $constraint_column }; - } - my $count = $self->schema - ->resultset( $source ) - ->search( $condition ) - ->count(); - if ( $count > 0 ) { - # no point checking more stuff, exit the loop - $build_value--; - next BUILD_VALUE; - } + my $condition; + my $constraint_columns = $unique_constraints{$constraint}; + + # loop through all constraint columns and build the condition + foreach my $constraint_column (@$constraint_columns) { + + # build the filter + # if one column does not exist or is undef, skip it + # an insert with a null will not trigger the constraint + next CONSTRAINTS + if !exists $col_values->{$constraint_column} + || !defined $col_values->{$constraint_column}; + $condition->{$constraint_column} = $col_values->{$constraint_column}; + } + my $count = $self->schema->resultset($source)->search($condition)->count(); + if ( $count > 0 ) { + + # no point checking more stuff, exit the loop + $build_value--; + next BUILD_VALUE; + } } - last; # you passed all tests + last; # you passed all tests } return $col_values if $build_value > 0; @@ -355,23 +368,23 @@ sub _buildColumnValues { sub _getForeignKeys { -# Returns the following arrayref -# [ [ source => name, keys => [ col_name => A, col_fk_name => B ] ], ... ] -# The array gives source name and keys for each FK constraint + # Returns the following arrayref + # [ [ source => name, keys => [ col_name => A, col_fk_name => B ] ], ... ] + # The array gives source name and keys for each FK constraint - my ($self, $params) = @_; + my ( $self, $params ) = @_; my $source = $self->schema->source( $params->{source} ); my ( @foreign_keys, $check_dupl ); my @relationships = $source->relationships; - for my $rel_name( @relationships ) { + for my $rel_name (@relationships) { my $rel_info = $source->relationship_info($rel_name); - if( $rel_info->{attrs}->{is_foreign_key_constraint} ) { + if ( $rel_info->{attrs}->{is_foreign_key_constraint} ) { $rel_info->{source} =~ s/^.*:://g; my $rel = { source => $rel_info->{source} }; my @keys; - while( my ($col_fk_name, $col_name) = each(%{$rel_info->{cond}}) ) { + while ( my ( $col_fk_name, $col_name ) = each( %{ $rel_info->{cond} } ) ) { $col_name =~ s|self.(\w+)|$1|; $col_fk_name =~ s|foreign.(\w+)|$1|; push @keys, { @@ -379,10 +392,10 @@ sub _getForeignKeys { col_fk_name => $col_fk_name, }; } + # check if the combination table and keys is unique # so skip double belongs_to relations (as in Biblioitem) - my $tag = $rel->{source}. ':'. - join ',', sort map { $_->{col_name} } @keys; + my $tag = $rel->{source} . ':' . join ',', sort map { $_->{col_name} } @keys; next if $check_dupl->{$tag}; $check_dupl->{$tag} = 1; $rel->{keys} = \@keys; @@ -393,54 +406,61 @@ sub _getForeignKeys { } sub _storeColumnValues { - my ($self, $params) = @_; - my $source = $params->{source}; - my $col_values = $params->{values}; - my $new_row = $self->schema->resultset( $source )->create( $col_values ); - return $new_row? { $new_row->get_columns }: {}; + my ( $self, $params ) = @_; + my $source = $params->{source}; + my $col_values = $params->{values}; + my $new_row = $self->schema->resultset($source)->create($col_values); + return $new_row ? { $new_row->get_columns } : {}; } sub _buildColumnValue { -# returns an arrayref if all goes well -# an empty arrayref typically means: auto_incr column or fk column -# undef means failure - my ($self, $params) = @_; - my $source = $params->{source}; - my $value = $params->{value}; - my $col_name = $params->{column_name}; - my $col_info = $self->schema->source($source)->column_info($col_name); + # returns an arrayref if all goes well + # an empty arrayref typically means: auto_incr column or fk column + # undef means failure + my ( $self, $params ) = @_; + my $source = $params->{source}; + my $value = $params->{value}; + my $col_name = $params->{column_name}; + + my $col_info = $self->schema->source($source)->column_info($col_name); my $retvalue = []; - if( $col_info->{is_auto_increment} ) { - if( exists $value->{$col_name} ) { + if ( $col_info->{is_auto_increment} ) { + if ( exists $value->{$col_name} ) { warn "Value not allowed for auto_incr $col_name in $source"; return; } + # otherwise: no need to assign a value - } elsif( !exists $value->{$col_name} - && exists $self->{default_values}{$source}{$col_name} ) { + } elsif ( !exists $value->{$col_name} + && exists $self->{default_values}{$source}{$col_name} ) + { my $v = $self->{default_values}{$source}{$col_name}; $v = &$v() if ref($v) eq 'CODE'; push @$retvalue, $v; - } elsif( $col_info->{is_foreign_key} || _should_be_fk($source,$col_name) ) { - if( exists $value->{$col_name} ) { - if( !defined $value->{$col_name} && !$col_info->{is_nullable} ) { + } elsif ( $col_info->{is_foreign_key} || _should_be_fk( $source, $col_name ) ) { + if ( exists $value->{$col_name} ) { + if ( !defined $value->{$col_name} && !$col_info->{is_nullable} ) { + # This explicit undef is not allowed warn "Null value for $col_name in $source not allowed"; return; } - if( ref( $value->{$col_name} ) ne 'HASH' ) { + if ( ref( $value->{$col_name} ) ne 'HASH' ) { push @$retvalue, $value->{$col_name}; } + # sub build will handle a passed hash value later on } - } elsif( ref( $value->{$col_name} ) eq 'HASH' ) { + } elsif ( ref( $value->{$col_name} ) eq 'HASH' ) { + # this is not allowed for a column that is not a FK warn "Hash not allowed for $col_name in $source"; return; - } elsif( exists $value->{$col_name} ) { - if( !defined $value->{$col_name} && !$col_info->{is_nullable} ) { + } elsif ( exists $value->{$col_name} ) { + if ( !defined $value->{$col_name} && !$col_info->{is_nullable} ) { + # This explicit undef is not allowed warn "Null value for $col_name in $source not allowed"; return; @@ -449,7 +469,7 @@ sub _buildColumnValue { } else { my $data_type = $col_info->{data_type}; $data_type =~ s| |_|; - if( my $hdlr = $self->{gen_type}->{$data_type} ) { + if ( my $hdlr = $self->{gen_type}->{$data_type} ) { push @$retvalue, &$hdlr( $self, { info => $col_info } ); } else { warn "Unknown type $data_type for $col_name in $source"; @@ -460,14 +480,15 @@ sub _buildColumnValue { } sub _should_be_fk { -# This sub is only needed for inconsistencies in the schema -# A column is not marked as FK, but a belongs_to relation is defined + + # This sub is only needed for inconsistencies in the schema + # A column is not marked as FK, but a belongs_to relation is defined my ( $source, $column ) = @_; my $inconsistencies = { - 'Item.biblionumber' => 1, #FIXME: Please remove me when I become FK - 'CheckoutRenewal.checkout_id' => 1, #FIXME: Please remove when issues and old_issues are merged + 'Item.biblionumber' => 1, #FIXME: Please remove me when I become FK + 'CheckoutRenewal.checkout_id' => 1, #FIXME: Please remove when issues and old_issues are merged }; - return $inconsistencies->{ "$source.$column" }; + return $inconsistencies->{"$source.$column"}; } sub _gen_type { @@ -502,53 +523,49 @@ sub _gen_type { blob => \&_gen_blob, longblob => \&_gen_blob, }; -}; +} sub _gen_bool { - my ($self, $params) = @_; + my ( $self, $params ) = @_; return int( rand(2) ); } sub _gen_int { - my ($self, $params) = @_; + my ( $self, $params ) = @_; my $data_type = $params->{info}->{data_type}; my $max = 1; - if( $data_type eq 'tinyint' ) { + if ( $data_type eq 'tinyint' ) { $max = 127; - } - elsif( $data_type eq 'smallint' ) { + } elsif ( $data_type eq 'smallint' ) { $max = 32767; - } - elsif( $data_type eq 'mediumint' ) { + } elsif ( $data_type eq 'mediumint' ) { $max = 8388607; - } - elsif( $data_type eq 'integer' ) { + } elsif ( $data_type eq 'integer' ) { $max = 2147483647; - } - elsif( $data_type eq 'bigint' ) { + } elsif ( $data_type eq 'bigint' ) { $max = 9223372036854775807; } - return int( rand($max+1) ); + return int( rand( $max + 1 ) ); } sub _gen_real { - my ($self, $params) = @_; - my $max = 10 ** 38; - if( defined( $params->{info}->{size} ) ) { - $max = 10 ** ($params->{info}->{size}->[0] - $params->{info}->{size}->[1]); + my ( $self, $params ) = @_; + my $max = 10**38; + if ( defined( $params->{info}->{size} ) ) { + $max = 10**( $params->{info}->{size}->[0] - $params->{info}->{size}->[1] ); } - $max = 10 ** 5 if $max > 10 ** 5; - return sprintf("%.2f", rand($max-0.1)); + $max = 10**5 if $max > 10**5; + return sprintf( "%.2f", rand( $max - 0.1 ) ); } sub _gen_date { - my ($self, $params) = @_; - return $self->schema->storage->datetime_parser->format_date(dt_from_string) + my ( $self, $params ) = @_; + return $self->schema->storage->datetime_parser->format_date(dt_from_string); } sub _gen_datetime { - my ($self, $params) = @_; + my ( $self, $params ) = @_; return $self->schema->storage->datetime_parser->format_datetime(dt_from_string); } @@ -558,32 +575,35 @@ sub _gen_time { } sub _gen_text { - my ($self, $params) = @_; + my ( $self, $params ) = @_; + # From perldoc String::Random my $size = $params->{info}{size} // 10; - $size -= alt_rand(0.5 * $size); - my $regex = $size > 1 - ? '[A-Za-z][A-Za-z0-9_]{'.($size-1).'}' + $size -= alt_rand( 0.5 * $size ); + my $regex = + $size > 1 + ? '[A-Za-z][A-Za-z0-9_]{' . ( $size - 1 ) . '}' : '[A-Za-z]'; my $random = String::Random->new( rand_gen => \&alt_rand ); + # rand_gen is only supported from 0.27 onward return $random->randregex($regex); } -sub alt_rand { #Alternative randomizer - my ($max) = @_; +sub alt_rand { #Alternative randomizer + my ($max) = @_; my $random = Bytes::Random::Secure->new( NonBlocking => 1 ); - my $r = $random->irand / 2**32; + my $r = $random->irand / 2**32; return int( $r * $max ); } sub _gen_set_enum { - my ($self, $params) = @_; + my ( $self, $params ) = @_; return $params->{info}->{extra}->{list}->[0]; } sub _gen_blob { - my ($self, $params) = @_;; + my ( $self, $params ) = @_; return 'b'; } @@ -593,10 +613,8 @@ sub _gen_default_values { AuthorisedValueCategory => { is_integer_only => 0, }, - BackgroundJob => { - context => '{}' - }, - Borrower => { + BackgroundJob => { context => '{}' }, + Borrower => { login_attempts => 0, gonenoaddress => undef, lost => undef, @@ -632,9 +650,10 @@ sub _gen_default_values { Category => { enrolmentfee => 0, reservefee => 0, + # Not X, used for statistics - category_type => sub { return [ qw( A C S I P ) ]->[int(rand(5))] }, - min_password_length => undef, + category_type => sub { return [qw( A C S I P )]->[ int( rand(5) ) ] }, + min_password_length => undef, require_strong_password => undef, }, Branch => { @@ -664,7 +683,7 @@ sub _gen_default_values { Aqbookseller => { tax_rate => 0, discount => 0, - url => undef, + url => undef, }, Aqbudget => { sort1_authcat => undef, @@ -682,15 +701,15 @@ sub _gen_default_values { STATUS => 'ASKED' }, ReturnClaim => { - issue_id => undef, # It should be a FK but we removed it - # We don't want to generate a random value + issue_id => undef, # It should be a FK but we removed it + # We don't want to generate a random value }, ImportItem => { - status => 'staged', + status => 'staged', import_error => undef }, SearchFilter => { - opac => 1, + opac => 1, staff_client => 1 }, ErmAgreement => { @@ -698,7 +717,7 @@ sub _gen_default_values { closure_reason => undef, renewal_priority => undef, vendor_id => undef, - }, + }, }; } diff --git a/t/lib/bad_plugins/Koha/Plugin/BrokenInstall.pm b/t/lib/bad_plugins/Koha/Plugin/BrokenInstall.pm index 86146ba2df..fa7e847600 100644 --- a/t/lib/bad_plugins/Koha/Plugin/BrokenInstall.pm +++ b/t/lib/bad_plugins/Koha/Plugin/BrokenInstall.pm @@ -4,7 +4,7 @@ use Modern::Perl; use base qw(Koha::Plugins::Base); -our $VERSION = 1.01; +our $VERSION = 1.01; our $metadata = { name => 'Broken install plugin', author => 'Kyle M Hall', diff --git a/t/lib/bad_plugins/Koha/Plugin/BrokenUpgrade.pm b/t/lib/bad_plugins/Koha/Plugin/BrokenUpgrade.pm index bdf5f04018..f40ab22031 100644 --- a/t/lib/bad_plugins/Koha/Plugin/BrokenUpgrade.pm +++ b/t/lib/bad_plugins/Koha/Plugin/BrokenUpgrade.pm @@ -4,7 +4,7 @@ use Modern::Perl; use base qw(Koha::Plugins::Base); -our $VERSION = 1.01; +our $VERSION = 1.01; our $metadata = { name => 'Broken upgrade plugin', author => 'Kyle M Hall', diff --git a/t/lib/plugins/Koha/Plugin/BadAPIRoute.pm b/t/lib/plugins/Koha/Plugin/BadAPIRoute.pm index 66a1417a3d..6127cb53c7 100644 --- a/t/lib/plugins/Koha/Plugin/BadAPIRoute.pm +++ b/t/lib/plugins/Koha/Plugin/BadAPIRoute.pm @@ -6,7 +6,7 @@ use Mojo::JSON qw( decode_json ); use base qw(Koha::Plugins::Base); -our $VERSION = 0.01; +our $VERSION = 0.01; our $metadata = { name => 'Bad API Route Plugin', author => 'John Doe', diff --git a/t/lib/plugins/Koha/Plugin/MarcFieldValues.pm b/t/lib/plugins/Koha/Plugin/MarcFieldValues.pm index ee763b8838..2bd6fcffaf 100644 --- a/t/lib/plugins/Koha/Plugin/MarcFieldValues.pm +++ b/t/lib/plugins/Koha/Plugin/MarcFieldValues.pm @@ -6,7 +6,7 @@ use MARC::Record; use base qw(Koha::Plugins::Base); -our $VERSION = 1.00; +our $VERSION = 1.00; our $metadata = { name => 'MarcFieldValues', author => 'M. de Rooy', @@ -49,15 +49,17 @@ sub new { sub to_marc { my ( $self, $args ) = @_; + # $args->{data} contains text to convert to MARC - my $retval = ''; + my $retval = ''; my @records = split /\r?\n\r?\n/, $args->{data}; - foreach my $rec ( @records ) { - my @lines = split /\r?\n/, $rec; - my $marc = MARC::Record->new; - my $inds = {}; + foreach my $rec (@records) { + my @lines = split /\r?\n/, $rec; + my $marc = MARC::Record->new; + my $inds = {}; my $fldcount = 0; - foreach my $line ( @lines ) { + foreach my $line (@lines) { + # each line is of the form field [,ind1|,ind2|,subcode] = value my @temp = split /\s*=\s*/, $line, 2; next if @temp < 2; @@ -65,18 +67,26 @@ sub to_marc { $temp[1] =~ s/\s*$//; my $value = $temp[1]; @temp = split /\s*,\s*/, $temp[0]; - if( @temp > 1 && $temp[1] =~ /ind[12]/ ) { - $inds->{$temp[0]}->{$temp[1]} = substr($value, 0, 1); + if ( @temp > 1 && $temp[1] =~ /ind[12]/ ) { + $inds->{ $temp[0] }->{ $temp[1] } = substr( $value, 0, 1 ); next; } $fldcount++; - $marc->append_fields( MARC::Field->new( - $temp[0], - $temp[0] < 10 + $marc->append_fields( + MARC::Field->new( + $temp[0], + $temp[0] < 10 ? () - : ( ( $inds->{$temp[0]} ? $inds->{$temp[0]}->{ind1} // '' : '', $inds->{$temp[0]} ? $inds->{$temp[0]}->{ind2} // '' : ''), substr( $temp[1], 0, 1 ) ), - $value, - )); + : ( + ( + $inds->{ $temp[0] } ? $inds->{ $temp[0] }->{ind1} // '' : '', + $inds->{ $temp[0] } ? $inds->{ $temp[0] }->{ind2} // '' : '' + ), + substr( $temp[1], 0, 1 ) + ), + $value, + ) + ); } $retval .= $marc->as_usmarc if $fldcount; } diff --git a/t/lib/plugins/Koha/Plugin/Test.pm b/t/lib/plugins/Koha/Plugin/Test.pm index 7472928fff..970c4ec7b6 100644 --- a/t/lib/plugins/Koha/Plugin/Test.pm +++ b/t/lib/plugins/Koha/Plugin/Test.pm @@ -14,7 +14,7 @@ use t::lib::TestBuilder; ## Required for all plugins use base qw(Koha::Plugins::Base); -our $VERSION = "v1.01"; +our $VERSION = "v1.01"; our $metadata = { name => 'Test Plugin', author => 'Kyle M Hall', @@ -100,8 +100,8 @@ sub intranet_js { sub item_barcode_transform { my ( $self, $barcode ) = @_; my $param = $$barcode; - if ( Scalar::Util::looks_like_number( $$barcode ) ) { - $$barcode = $$barcode * 2 + if ( Scalar::Util::looks_like_number($$barcode) ) { + $$barcode = $$barcode * 2; } Koha::Exception->throw("item_barcode_transform called with parameter: $param"); } @@ -133,13 +133,13 @@ sub uninstall { } sub test_output { - my ( $self ) = @_; + my ($self) = @_; $self->output( '¡Hola output!', 'json' ); } sub test_output_html { - my ( $self ) = @_; - $self->output_html( '¡Hola output_html!' ); + my ($self) = @_; + $self->output_html('¡Hola output_html!'); } sub api_namespace { @@ -148,7 +148,7 @@ sub api_namespace { sub after_hold_create { my ( $self, $param ) = @_; - Koha::Exception->throw("after_hold_create called with parameter " . ref($param) ); + Koha::Exception->throw( "after_hold_create called with parameter " . ref($param) ); } sub before_send_messages { @@ -181,9 +181,8 @@ sub after_biblio_action { my $biblio_id = $params->{biblio_id}; if ( $action ne 'delete' ) { - Koha::Exception->throw("after_biblio_action called with action: $action, ref: " . ref($biblio) ); - } - else { + Koha::Exception->throw( "after_biblio_action called with action: $action, ref: " . ref($biblio) ); + } else { Koha::Exception->throw("after_biblio_action called with action: $action, id: $biblio_id") if $biblio_id; } } @@ -195,21 +194,21 @@ sub after_item_action { my $item_id = $params->{item_id}; if ( $action ne 'delete' ) { - my $itemnumber_defined = (defined $item->itemnumber) ? 'yes' : 'no'; - my $item_id_defined = (defined $item_id) ? 'yes' : 'no'; - Koha::Exception->throw("after_item_action called with action: $action, ref: " . ref($item) . " ". - "item_id defined: $item_id_defined ". - "itemnumber defined: $itemnumber_defined" ); - } - else { - Koha::Exception->throw("after_item_action called with action: $action, id: $item_id" ) if $item_id; + my $itemnumber_defined = ( defined $item->itemnumber ) ? 'yes' : 'no'; + my $item_id_defined = ( defined $item_id ) ? 'yes' : 'no'; + Koha::Exception->throw( "after_item_action called with action: $action, ref: " + . ref($item) . " " + . "item_id defined: $item_id_defined " + . "itemnumber defined: $itemnumber_defined" ); + } else { + Koha::Exception->throw("after_item_action called with action: $action, id: $item_id") if $item_id; } } sub after_authority_action { my ( $self, $params ) = @_; - my $action = $params->{action} // q{}; - my $id = $params->{authority_id} // 0; + my $action = $params->{action} // q{}; + my $id = $params->{authority_id} // 0; Koha::Exception->throw("after_authority_action called with action: $action, id: $id"); } @@ -223,13 +222,12 @@ sub after_circ_action { my $type = $payload->{type}; if ( $action eq 'renewal' ) { - Koha::Exception->throw("after_circ_action called with action: $action, ref: " . ref($checkout)); - } - elsif ( $action eq 'checkout') { - Koha::Exception->throw("after_circ_action called with action: $action, ref: " . ref($checkout) . " type: $type"); - } - elsif ( $action eq 'checkin' ) { - Koha::Exception->throw("after_circ_action called with action: $action, ref: " . ref($checkout)); + Koha::Exception->throw( "after_circ_action called with action: $action, ref: " . ref($checkout) ); + } elsif ( $action eq 'checkout' ) { + Koha::Exception->throw( + "after_circ_action called with action: $action, ref: " . ref($checkout) . " type: $type" ); + } elsif ( $action eq 'checkin' ) { + Koha::Exception->throw( "after_circ_action called with action: $action, ref: " . ref($checkout) ); } } @@ -239,8 +237,7 @@ sub after_hold_action { my $action = $params->{action}; my $hold = $params->{payload}->{hold}; - Koha::Exception->throw( - "after_hold_action called with action: $action, ref: " . ref($hold) ); + Koha::Exception->throw( "after_hold_action called with action: $action, ref: " . ref($hold) ); } sub api_routes { @@ -337,8 +334,7 @@ sub check_password { my $password = $args->{'password'}; if ( $password && $password =~ m/^\d{4}$/ ) { return { error => 0 }; - } - else { + } else { return { error => 1, msg => "PIN should be four digits" @@ -349,20 +345,20 @@ sub check_password { sub intranet_catalog_biblio_tab { my @tabs; push @tabs, - Koha::Plugins::Tab->new( + Koha::Plugins::Tab->new( { title => 'Tab 1', content => 'This is content for tab 1' } - ); + ); push @tabs, - Koha::Plugins::Tab->new( + Koha::Plugins::Tab->new( { title => 'Tab 2', content => 'This is content for tab 2' } - ); + ); return @tabs; } @@ -381,18 +377,16 @@ sub after_account_action { my $line = $params->{payload}->{line}; my $type = $params->{payload}->{type}; - Koha::Exception->throw( - "after_account_action called with action: $action, type: $type, ref: " . ref($line) ); + Koha::Exception->throw( "after_account_action called with action: $action, type: $type, ref: " . ref($line) ); } sub after_recall_action { my ( $self, $params ) = @_; my $action = $params->{action}; - my $recall = $params->{payload}->{recall}; + my $recall = $params->{payload}->{recall}; - Koha::Exception->throw( - "after_recall_action called with action: $action, ref: " . ref($recall) ); + Koha::Exception->throw( "after_recall_action called with action: $action, ref: " . ref($recall) ); } sub template_include_paths { diff --git a/t/lib/plugins/Koha/Plugin/TestItemBarcodeTransform.pm b/t/lib/plugins/Koha/Plugin/TestItemBarcodeTransform.pm index 220f130e20..7870288c64 100644 --- a/t/lib/plugins/Koha/Plugin/TestItemBarcodeTransform.pm +++ b/t/lib/plugins/Koha/Plugin/TestItemBarcodeTransform.pm @@ -11,7 +11,7 @@ use Mojo::JSON qw( decode_json ); ## Required for all plugins use base qw(Koha::Plugins::Base); -our $VERSION = 1.01; +our $VERSION = 1.01; our $metadata = { name => 'Test Plugin for item_barcode_transform', author => 'Kyle M Hall', @@ -35,8 +35,8 @@ sub new { sub item_barcode_transform { my ( $self, $barcode ) = @_; my $param = $$barcode; - if ( Scalar::Util::looks_like_number( $$barcode ) ) { - $$barcode = $$barcode * 4 + if ( Scalar::Util::looks_like_number($$barcode) ) { + $$barcode = $$barcode * 4; } Koha::Exception->throw("item_barcode_transform called with parameter: $param"); } diff --git a/t/mock_templates/intranet-tmpl/prog/en/includes/accounts.inc b/t/mock_templates/intranet-tmpl/prog/en/includes/accounts.inc index 50742d5b29..781a7f7969 100644 --- a/t/mock_templates/intranet-tmpl/prog/en/includes/accounts.inc +++ b/t/mock_templates/intranet-tmpl/prog/en/includes/accounts.inc @@ -9,53 +9,94 @@ [%- BLOCK debit_type_description -%] [%- SWITCH debit_type.code -%] - [%- CASE 'ACCOUNT' -%]<span>Account creation fee</span> - [%- CASE 'ACCOUNT_RENEW' -%]<span>Account renewal fee</span> - [%- CASE 'ARTICLE_REQUEST' -%]<span>Article request fee</span> - [%- CASE 'LOST' -%]<span>Lost item</span> - [%- CASE 'MANUAL' -%]<span>Manual fee</span> - [%- CASE 'NEW_CARD' -%]<span>New card</span> - [%- CASE 'OVERDUE' -%]<span>Fine</span> - [%- CASE 'PROCESSING' -%]<span>Lost item processing fee</span> - [%- CASE 'RENT' -%]<span>Rental fee</span> - [%- CASE 'RENT_DAILY' -%]<span>Daily rental fee</span> - [%- CASE 'RENT_RENEW' -%]<span>Renewal of rental item</span> - [%- CASE 'RENT_DAILY_RENEW' -%]<span>Renewal of daily rental item</span> - [%- CASE 'RESERVE' -%]<span>Hold fee</span> - [%- CASE 'RESERVE_EXPIRED' -%]<span>Hold waiting too long</span> - [%- CASE 'PAYOUT' -%]<span>Payment from library to patron</span> - [%- CASE 'VOID' -%]<span>Credit has been voided</span> - [%- CASE -%]<span>[% debit_type.description | html %]</span> + + [%- CASE 'ACCOUNT' -%] + <span>Account creation fee</span> + [%- CASE 'ACCOUNT_RENEW' -%] + <span>Account renewal fee</span> + [%- CASE 'ARTICLE_REQUEST' -%] + <span>Article request fee</span> + [%- CASE 'LOST' -%] + <span>Lost item</span> + [%- CASE 'MANUAL' -%] + <span>Manual fee</span> + [%- CASE 'NEW_CARD' -%] + <span>New card</span> + [%- CASE 'OVERDUE' -%] + <span>Fine</span> + [%- CASE 'PROCESSING' -%] + <span>Lost item processing fee</span> + [%- CASE 'RENT' -%] + <span>Rental fee</span> + [%- CASE 'RENT_DAILY' -%] + <span>Daily rental fee</span> + [%- CASE 'RENT_RENEW' -%] + <span>Renewal of rental item</span> + [%- CASE 'RENT_DAILY_RENEW' -%] + <span>Renewal of daily rental item</span> + [%- CASE 'RESERVE' -%] + <span>Hold fee</span> + [%- CASE 'RESERVE_EXPIRED' -%] + <span>Hold waiting too long</span> + [%- CASE 'PAYOUT' -%] + <span>Payment from library to patron</span> + [%- CASE 'VOID' -%] + <span>Credit has been voided</span> + [%- CASE -%] + <span>[% debit_type.description | html %]</span> [%- END -%] [%- END -%] [%- BLOCK credit_type_description -%] [%- SWITCH credit_type.code -%] - [%- CASE 'CANCELLATION' -%]<span>Cancelled charge</span> - [%- CASE 'CREDIT' -%]<span>Credit</span> - [%- CASE 'DISCOUNT' -%]<span>Discount</span> - [%- CASE 'FORGIVEN' -%]<span>Forgiven</span> - [%- CASE 'LOST_FOUND' -%]<span>Lost item fee refund</span> - [%- CASE 'OVERPAYMENT' -%]<span>Overpayment refund</span> - [%- CASE 'PAYMENT' -%]<span>Payment</span> - [%- CASE 'PROCESSING_FOUND' -%]<span>Lost item processing fee refund</span> - [%- CASE 'PURCHASE' -%]<span>Purchase</span> - [%- CASE 'REFUND' -%]<span>Refund</span> - [%- CASE 'WRITEOFF' -%]<span>Writeoff</span> - [%- CASE -%]<span>[% credit_type.description | html %]</span> + + [%- CASE 'CANCELLATION' -%] + <span>Cancelled charge</span> + [%- CASE 'CREDIT' -%] + <span>Credit</span> + [%- CASE 'DISCOUNT' -%] + <span>Discount</span> + [%- CASE 'FORGIVEN' -%] + <span>Forgiven</span> + [%- CASE 'LOST_FOUND' -%] + <span>Lost item fee refund</span> + [%- CASE 'OVERPAYMENT' -%] + <span>Overpayment refund</span> + [%- CASE 'PAYMENT' -%] + <span>Payment</span> + [%- CASE 'PROCESSING_FOUND' -%] + <span>Lost item processing fee refund</span> + [%- CASE 'PURCHASE' -%] + <span>Purchase</span> + [%- CASE 'REFUND' -%] + <span>Refund</span> + [%- CASE 'WRITEOFF' -%] + <span>Writeoff</span> + [%- CASE -%] + <span>[% credit_type.description | html %]</span> [%- END -%] [%- END -%] [%- BLOCK account_status_description -%] [%- SWITCH account.status -%] - [%- CASE 'UNRETURNED' -%]<span> (Accruing)</span> - [%- CASE 'RETURNED' -%]<span> (Returned)</span> - [%- CASE 'REPLACED' -%]<span> (Replaced)</span> - [%- CASE 'REFUNDED' -%]<span> (Refunded)</span> - [%- CASE 'FORGIVEN' -%]<span> (Forgiven)</span> - [%- CASE 'VOID' -%]<span> (Voided)</span> - [%- CASE 'LOST' -%]<span> (Lost)</span> - [%- CASE 'CANCELLED' -%]<span> (Cancelled)</span> - [%- CASE -%] + + [%- CASE 'UNRETURNED' -%] + <span> (Accruing)</span> + [%- CASE 'RETURNED' -%] + <span> (Returned)</span> + [%- CASE 'REPLACED' -%] + <span> (Replaced)</span> + [%- CASE 'REFUNDED' -%] + <span> (Refunded)</span> + [%- CASE 'FORGIVEN' -%] + <span> (Forgiven)</span> + [%- CASE 'VOID' -%] + <span> (Voided)</span> + [%- CASE 'LOST' -%] + <span> (Lost)</span> + [%- CASE 'CANCELLED' -%] + <span> (Cancelled)</span> + [%- CASE -%] + [%- END -%] [%- END -%] diff --git a/t/mock_templates/intranet-tmpl/prog/en/modules/about.tt b/t/mock_templates/intranet-tmpl/prog/en/modules/about.tt index 00d1b37094..88b37b60e5 100644 --- a/t/mock_templates/intranet-tmpl/prog/en/modules/about.tt +++ b/t/mock_templates/intranet-tmpl/prog/en/modules/about.tt @@ -6,10 +6,12 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -<title>[% FILTER collapse %] - [% t("About Koha") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("About Koha") | html %] + › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -33,1290 +35,1181 @@ [% WRAPPER tabs id= "abouttabs" %] [% WRAPPER tabs_nav %] - [% WRAPPER tab_item linktab = 1 tabname = "about" bt_active = tab == "about" %] Server information [% END %] - [% WRAPPER tab_item linktab = 1 tabname = "perl" bt_active = tab == "perl" %] Perl modules [% END %] - [% WRAPPER tab_item linktab = 1 tabname = "sysinfo" bt_active = tab == "sysinfo" %] System information [% END %] - [% WRAPPER tab_item linktab = 1 tabname = "team" bt_active = tab == "team" %] Koha team [% END %] - [% WRAPPER tab_item linktab = 1 tabname = "licenses" bt_active = tab == "licenses" %] Licenses [% END %] - [% WRAPPER tab_item linktab = 1 tabname = "translations" bt_active = tab == "translations" %] Translations [% END %] - [% WRAPPER tab_item linktab = 1 tabname = "history" bt_active = tab == "history" %] Timeline [% END %] - [% WRAPPER tab_item linktab = 1 tabname = "dedications" bt_active = tab == "dedications" %] Dedications [% END %] + [% WRAPPER tab_item linktab = 1 tabname = "about" bt_active = tab == "about" %]Server information[% END %] + [% WRAPPER tab_item linktab = 1 tabname = "perl" bt_active = tab == "perl" %]Perl modules[% END %] + [% WRAPPER tab_item linktab = 1 tabname = "sysinfo" bt_active = tab == "sysinfo" %]System information[% END %] + [% WRAPPER tab_item linktab = 1 tabname = "team" bt_active = tab == "team" %]Koha team[% END %] + [% WRAPPER tab_item linktab = 1 tabname = "licenses" bt_active = tab == "licenses" %]Licenses[% END %] + [% WRAPPER tab_item linktab = 1 tabname = "translations" bt_active = tab == "translations" %]Translations[% END %] + [% WRAPPER tab_item linktab = 1 tabname = "history" bt_active = tab == "history" %]Timeline[% END %] + [% WRAPPER tab_item linktab = 1 tabname = "dedications" bt_active = tab == "dedications" %]Dedications[% END %] [% END %] [% WRAPPER tab_panels %] [% SWITCH tab %] - [% CASE 'about' %] [% PROCESS about_panel %] - [% CASE 'perl' %] [% PROCESS perl_panel %] - [% CASE 'sysinfo' %] [% PROCESS sysinfo_panel %] - [% CASE 'team' %] [% PROCESS team_panel %] - [% CASE 'licenses' %] [% PROCESS licenses_panel %] - [% CASE 'translations' %] [% PROCESS translations_panel %] - [% CASE 'history' %] [% PROCESS history_panel %] - [% CASE 'dedications' %] [% PROCESS dedications_panel %] - [% CASE %] [% PROCESS about_panel %] + [% CASE 'about' %] + [% PROCESS about_panel %] + [% CASE 'perl' %] + [% PROCESS perl_panel %] + [% CASE 'sysinfo' %] + [% PROCESS sysinfo_panel %] + [% CASE 'team' %] + [% PROCESS team_panel %] + [% CASE 'licenses' %] + [% PROCESS licenses_panel %] + [% CASE 'translations' %] + [% PROCESS translations_panel %] + [% CASE 'history' %] + [% PROCESS history_panel %] + [% CASE 'dedications' %] + [% PROCESS dedications_panel %] + [% CASE %] + [% PROCESS about_panel %] [% END %] [% END %] [% END # /WRAPPER abouttabs %] -
            -
            - -[% INCLUDE 'intranet-bottom.inc' %] +
            + + + + + [% INCLUDE 'intranet-bottom.inc' %] -[% BLOCK about_panel %] - [% WRAPPER tab_panel tabname= "about" bt_active = 1 %] - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - [% IF (is_psgi) %] + [% BLOCK about_panel %] + [% WRAPPER tab_panel tabname= "about" bt_active = 1 %] +
            Server information
            Koha version: [% kohaVersion | html %][% IF kohaCodename %] [% kohaCodename | html %][% END %]
            OS version ('uname -a'): [% osVersion | html %]
            Perl interpreter: [% perlPath | html %]
            Perl version: [% perlVersion | html %]
            Perl @INC: - [% FOREACH perlIncPat IN perlIncPath %] - [% perlIncPat.perlinc | html %]
            - [% END %] -
            MySQL version: [% mysqlVersion | html %]
            Apache version: [% apacheVersion | html %]
            + - - + + - [% END %] - [% IF Koha.Preference('SearchEngine') == 'Elasticsearch' %] - - [% IF elasticsearch_fatal_config_error %] - - [% ELSE %] - + + + + + + + + + + + + + + + + + + + + + + + [% IF (is_psgi) %] + + + + + [% END %] + [% IF Koha.Preference('SearchEngine') == 'Elasticsearch' %] + + + [% IF elasticsearch_fatal_config_error %] + + [% ELSE %] + + [% END # /IF elasticsearch_fatal_config_error %] + + [% END %] + + + - [% END # /IF elasticsearch_fatal_config_error %] - - [% END %] - - - - - - - - - - - [% IF (errZebraConnection == 10000) %] - - [% ELSIF (errZebraConnection) %] - - [% ELSE %] - - [% END %] - - - - [% IF warnConnectBroker %] - - [% ELSE %] - - [% END %] - - - - - - - [% timezone_config_class = (time_zone.config_invalid) ? 'bg-warning' : '' %] - [% timezone_env_class = (time_zone.env_invalid) ? 'bg-warning' : '' %] - - - -
            Server information
            PSGI: [% psgi_server | html %]Koha version: [% kohaVersion | html %][% IF kohaCodename %][% kohaCodename | html %][% END %]
            Elasticsearch: [% elasticsearch_fatal_config_error | html %] - Version: - [% elasticsearch_status.version | html %] - | - Nodes: - [% elasticsearch_status.nodes.join(' / ') | html %] - | - Status: - [% IF elasticsearch_status.running %] - running - | - Indices: - [% FOREACH index IN elasticsearch_status.indexes %] - [% index.index_name | html %] - (count: [% index.index_count | html %]) - [% UNLESS loop.last %], [% END %] + OS version ('uname -a'): [% osVersion | html %]
            Perl interpreter: [% perlPath | html %]
            Perl version: [% perlVersion | html %]
            Perl @INC: + [% FOREACH perlIncPat IN perlIncPath %] + [% perlIncPat.perlinc | html %]
            + [% END %] +
            MySQL version: [% mysqlVersion | html %]
            Apache version: [% apacheVersion | html %]
            PSGI: [% psgi_server | html %]
            Elasticsearch: [% elasticsearch_fatal_config_error | html %] + Version: + [% elasticsearch_status.version | html %] + | + Nodes: + [% elasticsearch_status.nodes.join(' / ') | html %] + | + Status: + [% IF elasticsearch_status.running %] + running + | + Indices: + [% FOREACH index IN elasticsearch_status.indexes %] + [% index.index_name | html %] + (count: [% index.index_count | html %]) [% UNLESS loop.last %],[% END %] + [% END %] + [% ELSE %] + not running + [% END %] +
            Memcached: + Servers: + [% IF memcached_servers %] + [% memcached_servers | html %] + [% ELSE %] + undefined + [% END %] + | + Namespace: + [% IF memcached_namespace %] + [% memcached_namespace | html %] + [% ELSE %] + undefined + [% END %] + | + Status: + [% IF memcached_servers %] + [% IF memcached_running and is_memcached_still_active %] + running. + [% ELSE %] + not running. + [% IF is_psgi %] + Remember memcached needs to be started before Plack. + [% END %] [% END %] [% ELSE %] - not running + unknown [% END %] -
            Memcached: - Servers: - [% IF memcached_servers %] - [% memcached_servers | html %] - [% ELSE %] - undefined - [% END %] | - Namespace: - [% IF memcached_namespace %] - [% memcached_namespace | html %] - [% ELSE %] - undefined - [% END %] | - Status: - [% IF memcached_servers %] - [% IF memcached_running and is_memcached_still_active %] - running. - [% ELSE %] - not running. - [% IF is_psgi %] - Remember memcached needs to be started before Plack. - [% END %] - [% END %] - [% ELSE %] - unknown - [% END %] | - Config read from: - [% SWITCH where_is_memcached_config %] + | + Config read from: + [% SWITCH where_is_memcached_config %] [% CASE 'config_only' %] koha-conf.xml [% CASE 'ENV_only' %] ENV Note that the right place to define the memcached config is in your $KOHA_CONF file [% CASE 'both' %] - ENV and koha-conf.xml Note that the right place to define the memcached config is in your $KOHA_CONF file. To avoid any misunderstanding you should not export the memcached config from ENV. + ENV and koha-conf.xml + Note that the right place to define the memcached config is in your $KOHA_CONF file. To avoid any misunderstanding you should not export the memcached config from ENV. [% CASE # nowhere %] Nowhere Note that the right place to define the memcached config is in your $KOHA_CONF file. Currently you do not have a valid memcached configuration defined. - [% END %] - [% IF effective_caching_method != 'Cache::Memcached::Fast::Safe' %] - | Effective caching method: [% effective_caching_method | html %] - [% END %] -
            Zebra version: [% zebraVersion | html %]
            Zebra status: Zebra server seems not to be available. Is it started?Error message from Zebra: [% ( errZebraConnection ) | html %]Running
            Message broker: Using SQL pollingUsing RabbitMQ
            Date and time: [% current_date_and_time | $KohaDates with_hours => 1 %]
            Time zone: - Used: [% time_zone.actual | html %] - [% IF time_zone.actual_bad_tz_fallback %] - (This is a fallback value due to a bad configuration) - [% END %] - | - Config: - [% IF time_zone.config != '' %] - [% time_zone.config | html %] - [% ELSE %] - Undefined - [% END %] | - Environment (TZ): - [% IF time_zone.environment != '' %] - [% time_zone.environment | html %] - [% ELSE %] - Undefined - [% END %] -
            - [% END # tab=about %] -[% END %] - -[% BLOCK perl_panel %] - [% WRAPPER tab_panel tabname= "perl" bt_active = 1 %] - - - [% FOREACH tabl IN table %] - - [% FOREACH ro IN tabl.row %] - [% IF ( ro.require ) %] - [% SET th_font_weight = "bold" %] - [% ELSE %] - [% SET th_font_weight = "normal" %] [% END %] - [% IF ( ro.current ) %] - [% SET th_title = t("Module current") %] - [% ELSIF ( ro.upgrade ) %] - [% SET th_background_color = "#FFCB2F" %] - [% SET th_title = t("Module upgrade needed") %] - [% ELSE %] - [% IF ( ro.require ) %] - [% SET th_background_color = "#FF8A8A" %] - [% SET th_title = t("Required module missing") %] - [% ELSIF ( ro.name != '' ) %] - [% SET th_background_color = "#FF8A8A" %] - [% SET th_title = t("Optional module missing") %] - [% END %] - [% END # /IF ro.current %] - - [% IF ( ro.name == '' ) %] - - [% ELSIF ( ro.version ) %] - - [% ELSE %] - - [% END %] - [% END # /FOREACH ro %] + - [% END # /FOREACH tabl %] -
            Perl modules
            - [% IF ( ro.name ) %] - [% ro.name | html %] - - ([% ro.reqversion | html %] - [% IF ro.maxversion %] - [% ro.maxversion | html %][% END %] - [% IF ro.excversion %][% FOR v IN ro.excversion %], ![% v | html %][% END %][% END %]) - + [% IF effective_caching_method != 'Cache::Memcached::Fast::Safe' %] + | Effective caching method: [% effective_caching_method | html %] [% END %] - [% ro.version | html %]Not Installed
            - [% END # tab=perl %] -[% END %] - -[% BLOCK sysinfo_panel %] - [% IF Asset.css("css/staff-global.css") == "" || Asset.js("js/vue/dist/erm.js") == "" %] - [% SET warnMissingCompiledFiles = 1 %] - [% END %] - [% WRAPPER tab_panel tabname= "sysinfo" bt_active = 1 %] - [% IF weasyprint_missing || warnPrefRequireChoosingExistingAuthority || warnPrefEasyAnalyticalRecords || warnPrefAnonymousPatronOPACPrivacy || warnPrefAnonymousPatronAnonSuggestions || warnPrefAnonymousPatronOPACPrivacy_PatronDoesNotExist || warnPrefAnonymousPatronAnonSuggestions_PatronDoesNotExist || warnPrefKohaAdminEmailAddress || warnPrefOpacHiddenItems || warnPrefPatronSelfRegistrationDefaultCategory || invalid_yesno.count || warnNoActiveCurrency || warnIsRootUser || xml_config_warnings.size || warnI18nMissing || AutoSelfCheckPatronDoesNotHaveSelfCheckPerm || AutoSelfCheckPatronHasTooManyPerm || warnStatisticsFieldsError || warnNoTemplateCaching || warnILLConfiguration || has_ai_issues || oauth2_missing_deps || bad_yaml_prefs || warnRelationships || log4perl_errors || config_bcrypt_settings_no_set || warnHiddenBiblionumbers.size || warnConnectBroker || elasticsearch_has_missing || warnMissingCompiledFiles || warnDbRowFormat %] - [% IF ( warnDbRowFormat ) %] -

            Database row format incorrect

            -

            Database tables with a row format other than 'DYNAMIC': [% warnDbRowFormat | html %]

            -

            You may experience problems upgrading to newer versions of Koha unless you update the row format for your database tables.

            -

            To know how to avoid this problem see the related wiki page: - Database row format -

            - [% END %] - - [% IF (warnIsRootUser) %] -

            Warning regarding current user

            -

            You are logged in as the database administrative user. This is not recommended because some parts of Koha will not function as expected when using this account.

            -

            Please log in instead with a regular staff account. To create a staff account, create a library, a patron category 'Staff' and add a new patron. Then give this patron permissions from 'More' in the toolbar.

            - [% END # /IF warnIsRootUser %] - - [% IF has_ai_issues %] -

            Data problems

            -

            - Some of your tables have problems with their auto_increment values which may lead to data loss. -

            -

            - You should not ignore this warning. -

            -

            - The problem is that InnoDB does not keep auto_increment across SQL server restarts (it is only set in memory). So on server startup the auto_increment values are set to max(table.id)+1. -

            -

            To know how to avoid this problem see the related wiki page: - DBMS auto increment fix -

            - -

            Problems found

            - [% IF ai_patrons %] -

            Patrons

            -

            The following IDs exist in both tables [% "borrowers" | $HtmlTags tag="strong" %] and [% "deletedborrowers" | $HtmlTags tag="strong" %]:

            -

            - [% FOR p IN ai_patrons %] - [% p.borrowernumber | html %] - [% UNLESS loop.last %], [% END %] - [% END %] -

            - [% END %] - [% IF ai_biblios %] -

            Bibliographic records

            -

            The following IDs exist in both tables [% "biblio" | $HtmlTags tag="strong" %] and [% "deletedbiblio" | $HtmlTags tag="strong" %]:

            -

            - [% FOR b IN ai_biblios %] - [% b.biblionumber | html %] - [% UNLESS loop.last %], [% END %] - [% END %] -

            - [% END %] - [% IF ai_biblioitems %] -

            Bibliographic records

            -

            The following IDs exist in both tables [% "biblio" | $HtmlTags tag="strong" %] and [% "deletedbiblioitems" | $HtmlTags tag="strong" %]:

            -

            - [% FOR b IN ai_biblioitems %] - [% b.biblioitemnumber | html %] - [% UNLESS loop.last %], [% END %] - [% END %] -

            - [% END %] - [% IF ai_items %] -

            Items

            -

            The following IDs exist in both tables [% "items" | $HtmlTags tag="strong" %] and [% "deleteditems" | $HtmlTags tag="strong" %]:

            -

            - [% FOR i IN ai_items %] - [% i.itemnumber | html %] - [% UNLESS loop.last %], [% END %] - [% END %] -

            - [% END %] - [% IF ai_checkouts %] -

            Checkouts

            -

            The following IDs exist in both tables [% "issues" | $HtmlTags tag="strong" %] and [% "old_issues" | $HtmlTags tag="strong" %]:

            -

            - [% FOR c IN ai_checkouts %] - [% c.issue_id | html %] - [% UNLESS loop.last %], [% END %] - [% END %] -

            - [% END %] - [% IF ai_holds %] -

            Holds

            -

            The following IDs exist in both tables [% "reserves" | $HtmlTags tag="strong" %] and [% "old_reserves" | $HtmlTags tag="strong" %]:

            -

            - [% FOR h IN ai_holds %] - [% h.reserve_id | html %] - [% UNLESS loop.last %], [% END %] - [% END %] -

            - [% END %] -
            - [% END # /IF has_ai_issues %] - - [% IF warnRelationships %] -

            Patron relationship problems

            - [% IF bad_relationships_count %] -

            Your database contained guarantee/guarantor pairs with no defined relationship. They have been set the value '_bad_data' in the [% "borrowers.relationship" | $HtmlTags tag="strong" %] and/or [% "borrower_relationships.relationship" | $HtmlTags tag="strong" %] columns. Fix them manually by recreating those relationships, or have your system's administrator correct the values.

            - [% END # /IF bad_relationships_count %] - - [% IF wrong_relationships %] -

            The following values have been used for guarantee/guarantor relationships, but do not exist in the 'borrowerRelationship' system preference:

            -
              - [% FOR rel IN wrong_relationships %] -
            • [% rel.0 | html %]
            • - [% END %] -
            -

            If the relationship is one you want, please add it to the 'borrowerRelationship' system preference, otherwise have your system's administrator correct the values in [% "borrowers.relationship" | $HtmlTags tag="strong" %] and/or [% "borrower_relationships.relationship" | $HtmlTags tag="strong" %] in the database.

            - [% END # /IF wrong_relationships %] - [% END # /IF warnRelationships %] - - [% IF log4perl_errors %] -

            Logging system does not behave correctly

            - [% FOR e IN log4perl_errors %] - [% SWITCH e %] - [% CASE 'missing_config_entry' %]There is no 'log4perl_conf' entry in the config file. - [% CASE 'cannot_read_config_file' %]The log4perl config file cannot be opened. - [% CASE 'logfile_not_writable' %]One of the logfiles listed in the config file is not writable. - [% CASE 'cannot_init_module' %]The Koha::Logger module cannot be initiated correctly (check the log file). - [% CASE %]Unknown error '[% e | html %]'. - [% END %] - [% END # /FOR e %] - [% END # /IF log4perl_errors %] - - [% IF warnConnectBroker %] -

            Impossible to connect to the message broker

            - There is an error when trying to connect to the message broker (RabbitMQ), check the Koha log files. -
            - Maybe it is not installed and configured correctly? -
            - Contact your system administrator. - [% END # /IF warnConnectBroker %] - - [% IF weasyprint_missing || warnPrefRequireChoosingExistingAuthority || warnPrefEasyAnalyticalRecords || warnPrefAnonymousPatronOPACPrivacy || warnPrefAnonymousPatronAnonSuggestions || warnPrefAnonymousPatronOPACPrivacy_PatronDoesNotExist || warnPrefAnonymousPatronAnonSuggestions_PatronDoesNotExist || warnPrefKohaAdminEmailAddress || warnPrefOpacHiddenItems || warnPrefPatronSelfRegistrationDefaultCategory || invalid_yesno.count || warnNoActiveCurrency || AutoSelfCheckPatronDoesNotHaveSelfCheckPerm || AutoSelfCheckPatronHasTooManyPerm || warnStatisticsFieldsError || warnNoTemplateCaching || warnILLConfiguration || warnXSLT || oauth2_missing_deps || bad_yaml_prefs || warnIssuingRules || config_bcrypt_settings_no_set || warnHiddenBiblionumbers.size || warnFastCataloging %] -

            Warnings regarding the system configuration

            - - - [% IF (warnFastCataloging) %] - - - - - [% END %] - [% IF (warnPrefRequireChoosingExistingAuthority) %] - - - - - [% END %] - [% IF (warnPrefEasyAnalyticalRecords) %] - - - - - [% END %] - [% IF warnPrefAnonymousPatronOPACPrivacy %] - - - - - [% END %] - [% IF warnPrefAnonymousPatronAnonSuggestions %] - - - - - [% END %] - [% IF warnPrefAnonymousPatronOPACPrivacy_PatronDoesNotExist %] - - - - - [% END %] - [% IF warnPrefAnonymousPatronAnonSuggestions_PatronDoesNotExist %] - - - - - [% END %] - [% IF warnPrefKohaAdminEmailAddress %] - - - - - [% END %] - [% IF warnPrefOpacHiddenItems %] - - - - [% END %] - [% IF warnPrefPatronSelfRegistrationDefaultCategory %] - - [% END %] - [% IF warnXSLT %] - [% FOR p IN warnXSLT %] - - - - [% END %] - [% END %] - [% IF invalid_yesno.count %] - [% FOR p IN invalid_yesno %] - - - - - [% END %] - [% END %] - [% IF warnNoActiveCurrency %] - - - - - [% END %] - [% IF warnStatisticsFieldsError %] - - - - - [% END %] - [% IF AutoSelfCheckPatronDoesNotHaveSelfCheckPerm %] - - - - - [% END %] - [% IF AutoSelfCheckPatronHasTooManyPerm %] - - - - - [% END %] - [% IF warnNoTemplateCaching %] - - - - - [% END %] - [% IF warnI18nMissing %] - - - - - [% END %] - [% IF warnILLConfiguration %] - [% IF no_ill_backends %] - - - - - [% END %] - [% IF ill_partner_code_not_defined %] - - - - - [% END %] - [% IF ill_partner_code_no_patrons %] - - - - - [% END %] - [% IF ill_branch_not_defined %] - - - - - [% END %] - [% IF ill_partner_code_doesnt_exist %] - - - - - [% END %] - [% END %] - - [% IF weasyprint_missing %] - - [% END %] - - [% IF oauth2_missing_deps %] - - - - - [% END %] - [% IF bad_yaml_prefs %] - - - - - [% END %] - [% IF config_bcrypt_settings_no_set %] - - - - - [% END %] - [% IF warnHiddenBiblionumbers.size %] - - - - - [% END %] - [% IF Koha.Preference('SearchEngine') == 'Elasticsearch' && elasticsearch_status.version.substr(0,1) < 6 %] - - - - - [% END %] -
            Preferences and parameters
            Warning There is no "Fast add" (FA) framework defined in administration->MARC frameworks. This disables the 'Fast cataloging' feature in cataloging/circulation.
            Warning System preference 'RequireChoosingExistingAuthority' is disabled, but needs 'AutoCreateAuthorities' enabled. Otherwise catalogers can add headings that will not be linked to authorities.
            Warning System preference 'EasyAnalyticalRecords' set, but UseControlNumber preference is set to 'Use'. Set it to 'Don't use' or else the 'Show analytics' links in the staff interface and the OPAC will be broken.
            Error System preference 'OPACPrivacy' set, but AnonymousPatron preference is set to '0'. Set it to a valid borrower number or checkins for these patrons will fail.
            Warning System preference 'AnonSuggestions' set, but AnonymousPatron preference is set to '0'. Set it to a valid borrower number if you want that this feature works correctly.
            Error Some patrons have requested privacy after their items are checked in, but the AnonymousPatron preference is not set correctly. Set it to a valid borrower number or checkins for these patrons will fail.
            Warning System preference 'AnonSuggestions' set, but AnonymousPatron preference is not set correctly. Set it to a valid borrower number if you want that this feature works correctly.
            Warning System preference 'KohaAdminEmailAddress' does not contain a valid email address. Emails will not be sent.
            Warning System preference 'OpacHiddenItems' generates a warning and will produce unexpected behaviors: [% warnPrefOpacHiddenItems | html %]
            Warning System preference 'PatronSelfRegistration' is set, but 'PatronSelfRegistrationDefaultCategory' does not contain a valid patron category code. Patron self-registration is disabled.
            Warning System preference '[% p.syspref | html %]' is '[% p.value | html %]', but the file '[% p.filename | html %]' does not exist.
            Warning System preference '[% p.variable | html %]' must be '0' or '1', but is [% IF p.value.defined %]'[% p.value | html%]'[% ELSE %]NULL[% END %].
            Warning No active currency is defined. Please go to Administration > Currencies and exchange rates and mark one currency as active.
            Warning System preference 'StatisticsFields' contains field names not belonging to the items database table: [% warnStatisticsFieldsError | html %]
            Warning - The patron used for the self checkout module at the OPAC does not have the self_check => self_checkout_module permission. -
            Warning - The patron used for the self checkout module at the OPAC has too many permissions. They should only have self_check => self_checkout_module. -
            Warning - You are missing the <template_cache_dir> entry in your koha-conf.xml file. - That will bring a performance boost to enable it. -
            Warning - The PO directory has not been found. See the dedicated wiki page for more information. -
            Warning - The ILL module is enabled, but there are no backends available. -
            Warning - The ILL module is enabled, but ILLPartnerCode system preference is empty. Falling back to the hardcoded 'IL'. -
            Warning - The ILL module is enabled and ILLPartnerCode system preference configured, but there are no patrons in [% ill_partner_code_no_patrons | html %] category. -
            Warning - The ILL module is enabled, but no 'branch' block is defined in koha-conf.xml. You must define this block before use. -
            Warning - The ILL module is enabled, but the configured ILLPartnerCode ([% ill_partner_code_doesnt_exist | html %]) is not defined on the system. -
            Warning - The weasyprint tool is not installed. -
            Warning - System preference 'RESTOAuth2ClientCredentials' is set, but the required Net::OAuth2::AuthorizationServer dependency is missing. The feature is disabled. -
            Warning - Some system preferences have badly formatted YAML content: [% bad_yaml_prefs.join(', ') | html %] -
            Warning - System preference 'Pseudonymization' is set, but there is not 'bcrypt_settings' entry defined in the $KOHA_CONF file. -
            Warning - [% FOR w IN warnHiddenBiblionumbers %] - Bibliographic framework "[% w.frameworkcode | html %]" has the biblionumber field hidden at the interface [% w.interface | html %]
            - [% END %] -
            Deprecation warning - Elasticsearch version 5.x is not supported in Koha 20.11 and greater. Please upgrade your Elasticsearch cluster -
            - [% END # /IF warnPrefRequireChoosingExistingAuthority %] - - [% IF xml_config_warnings.size %] - - - [% FOREACH config_entry IN xml_config_warnings %] - [% IF config_entry.error == 'zebra_bib_index_mode_is_grs1' %] - - - - - [% ELSIF config_entry.error == 'zebra_auth_index_mode_is_grs1' %] - - - - - [% ELSIF config_entry.error == 'use_zebra_facets_entry_missing' %] - - - - - [% ELSIF config_entry.error == 'log4perl_entry_missing' %] - - - - - [% ELSIF config_entry.error == 'lockdir_entry_missing' %] - - - - - [% ELSIF config_entry.error == 'lockdir_not_writable' %] - - - - - [% ELSIF config_entry.error == 'uploadpath_entry_missing' %] - - - - - [% ELSIF config_entry.error == 'uploadpath_and_opacbaseurl_entry_missing' %] - - - - - [% ELSIF config_entry.error == 'tmp_path_missing' %] - - - - - [% ELSIF config_entry.error == 'encryption_key_missing' %] - - - - - [% END # /IF config_entry.error %] - [% END # /FOREACH config_entry %] -
            XML configuration file
            Warning - The <zebra_bib_index_mode> entry set to 'grs1', which is no longer supported. - Please use DOM instead. To switch follow this page of wiki: - Switching to dom indexing -
            Warning - The <zebra_auth_index_mode> entry set to 'grs1', which is no longer supported. - Please use DOM instead. To switch follow this page of wiki: - Switching to dom indexing -
            Warning - The <use_zebra_facets> entry is missing in your configuration file. Falling back - to legacy facet calculation. -
            Warning - You are missing the <log4perl_conf> entry in your koha-conf.xml file. Please - add it, pointing to the log4perl.conf file for your Koha instance. -
            Warning - You are missing the <lockdir> entry in your koha-conf.xml file. Please - add it, pointing to your Koha instance's lock dir. -
            Warning - The configured <lockdir> entry in your koha-conf.xml file points to a - non-writable directory ([% config_entry.lockdir | html %]). -
            Warning - You are missing the <upload_path> entry in your koha-conf.xml file. Please - add it, pointing to the configured file upload directory for your Koha instance. -
            Warning - You are missing the <upload_path> entry in your koha-conf.xml file. Please - add it, pointing to the configured file upload directory for your Koha instance. - Also note that you need to properly set the OPACBaseURL preference for the file upload plugin to work. -
            Warning - You are missing the <tmp_path> entry in your koha-conf.xml file. Please - add it, pointing to the configured temporary directory for your Koha instance. - The effective temporary directory is '[% config_entry.effective_tmp_dir | html %]'. -
            Warning - You are missing the <encryption_key> entry in your koha-conf.xml file. - Please generate a key. We recommend one of at least 32 bytes. (You might use 'pwgen 32' to do so.) -
            - [% END # /IF xml_config_warnings.size %] - - [% IF warnIssuingRules %] - - - [% FOREACH unit IN ir_units %] - - - - - [% END # /FOREACH unit %] -
            Issuing rules
            Warning - The [% unit.branchcode || 'branchcode=default' | html %], [% unit.categorycode || 'categorycode=default' | html %], [% unit.itemtype || 'itemtype=default' | html %]issuingrule will fallback to 'days' for 'lengthunit' as it is incorrectly defined as [% unit.rule_value | html %]. -
            - [% END # /IF warnIssuingRules %] - - [% IF elasticsearch_has_missing %] - - - [% FOREACH index IN elasticsearch_status.indexes %] - [% IF index.missing_count %] - - - - - [% END %] - [% END %] -
            Records are not indexed in Elasticsearch
            Warning - [% index.missing_count | html %] record(s) missing on a total of [% index.index_count | html %] in index [% index.index_name | html %]. -
            - [% END # /IF elasticsearch_has_missing %] - - [% IF warnMissingCompiledFiles %] - Error - Compiled CSS and/or JS files are not present. Please run `yarn build` to generate them. - - [% END # /IF warnMissingCompiledFiles %] - - [% ELSE %] -

            No warnings.

            - [% END # /IF warnRequireChoosingExistingAuthority... %] - [% END # tab=sysinfo %] -[% END %] - -[% BLOCK team_panel %] - [% WRAPPER tab_panel tabname= "team" bt_active = 1 %] -

            Special thanks to the following organizations

            - - -

            Koha release teams

            - [% IF maintenance_team %] -
            -
            -

            Koha [% short_version | html %][% IF kohaCodename %] ([% kohaCodename | html %])[% END %] release team

            - [% IF development_version %] -

            You are running a development version of Koha

            + + Zebra version: + [% zebraVersion | html %] + + + Zebra status: + [% IF (errZebraConnection == 10000) %] + Zebra server seems not to be available. Is it started? + [% ELSIF (errZebraConnection) %] + Error message from Zebra: [% ( errZebraConnection ) | html %] [% ELSE %] - [% INCLUDE team t=release_team v='release' %] + Running [% END %] -
            - -
            -

            Current maintenance team

            - [% INCLUDE team t=maintenance_team v=short_version %] - [% IF development_version %] -
          • Release maintainers: -
              - [% FOREACH m IN maintenance_team.maintainer %] -
            • [% m.version | html %] - [% INCLUDE person p=m %]
            • - [% IF maintenance_team.maintainer_assistants %] - [% FOREACH ma IN maintenance_team.maintainer_assistants %] - [% IF ma.version == ( m.version ) %] -
              • Assistant: [% INCLUDE person p=ma %]
              - [% END %] - [% END %] - [% END %] - - [% IF maintenance_team.maintainer_mentors %] - [% FOREACH mm IN maintenance_team.maintainer_mentors %] - [% IF m.version == ( mm.version ) %] -
              • Mentor: [% INCLUDE person p=mm %]
              - [% END %] - [% END %] - [% END %] - [% END %] -
            -
          • + + + Message broker: + [% IF warnConnectBroker %] + Using SQL polling + [% ELSE %] + Using RabbitMQ [% END %] -
            -
            - [% ELSE %] -
            - Could not read the teams.yaml file. Please make sure <docdir> is correctly defined in koha-conf.xml. -
            - [% END # /maintenance_team %] - -

            Koha development team

            - [% IF contributors.size %] -
              - [% FOREACH contributor IN contributors %] -
            • [% INCLUDE person p=contributor %][% INCLUDE contributions p=contributor %]
            • - [% END %] -
            - [% ELSE %] -
            - Could not read the contributors.yaml file. Please make sure <docdir> is correctly defined in koha-conf.xml. -
            - [% END # /IF contributors.size %] -
            - -

            Contributing companies and institutions

            -
              -
            • Allen Ginsberg Library, USA
            • -
            • Alingsås Public Library, Sweden
            • -
            • American Numismatic Society, USA
            • -
            • Arcadia Public Library, USA
            • -
            • Athens County Public Libraries, USA
            • -
            • BdP de la Meuse, France
            • -
            • BibLibre, France
            • -
            • Biblioteca Provincial Fr. Mamerto Esquiú (Provincia Franciscana de la Asunción), Argentina
            • -
            • Bibliotheksservice-Zentrum Baden-Württemberg (BSZ), Germany
            • -
            • Briar Cliff University, USA
            • -
            • Brimbank City Council, Australia
            • -
            • Brooklyn Law School Library, USA
            • -
            • Bibliothèque Universitaire des Langues et Civilisations (BULAC), France
            • -
            • ByWater Solutions, USA
            • -
            • California College of the Arts, USA
            • -
            • Camden County, USA
            • -
            • Carnegie Stout Library, USA
            • -
            • Calyx, Australia
            • -
            • Catalyst IT, New Zealand
            • -
            • Central Kansas Library System (CKLS), USA
            • -
            • Centre collégial des services regroupés (CCSR), Canada
            • -
            • Cheshire Libraries, United Kingdom
            • -
            • Coeur d'Alene Public Library, USA
            • -
            • Corpus Christi Public Libraries, USA
            • -
            • C & P Bibliography Services, USA
            • -
            • Dataly Tech, Greece
            • -
            • Devinim, Turkey
            • -
            • Do Space, USA
            • -
            • DoverNet, USA
            • -
            • doXulting
            • -
            • Duchesne County Library, USA
            • -
            • Escuela de Orientacion Lacaniana, Argentina
            • -
            • Fenway Library Organization, USA
            • -
            • Fargo Public Library, USA
            • -
            • Farmington Public Library, USA
            • -
            • FIT
            • -
            • Foundations Bible College & Seminary, USA
            • -
            • Goethe-Institut, Germany
            • -
            • Gothenburg University Library, Sweden
            • -
            • Halland County Library, Sweden
            • -
            • Harrison Carmel Public Library, USA
            • -
            • Hauraki District Libraries, New Zealand
            • -
            • Higher Education Libraries of Massachusetts, USA
            • -
            • Hochschule für Gesundheit (hsg), Germany
            • -
            • Hotchkiss School, USA
            • -
            • Katipo Communications, New Zealand
            • -
            • KEEP SOLUTIONS, Portugal
            • -
            • KohaAloha, New Zealand
            • -
            • Koha-Suomi Oy, Finland
            • -
            • LibLime, USA
            • -
            • Library of the Józef Piłsudski Institute of America, USA
            • -
            • Libriotech, Norway
            • -
            • Los Gatos Public Library, USA
            • -
            • Lund University Library, Sweden
            • -
            • MassCat, USA
            • -
            • Middletown Township Public Library, USA
            • -
            • National Library of Finland, Finland
            • -
            • Newcastle City Council, United Kingdom
            • -
            • New Zealand Central Agencies Library, New Zealand
            • -
            • New Zealand Ministry of Education Library, New Zealand
            • -
            • North Central Regional Library (NCRL), USA
            • -
            • Northeast Kansas Library System (NEKLS), USA
            • -
            • OPUS
            • -
            • Orex Digital, Spain
            • -
            • Oslo Public Library, Norway
            • -
            • Plano Independent School, USA
            • -
            • Plant and Food Research Limited, New Zealand
            • -
            • Prosentient Systems, Australia
            • -
            • PTFS, Maryland, USA
            • -
            • PTFS Europe Ltd, United Kingdom
            • -
            • Rijksmuseum, Amsterdam, The Netherlands
            • -
            • Rolling Hills Consolidated Libraries, USA
            • -
            • Round Rock Public Library, USA
            • -
            • SAN-Ouest Provence, France
            • -
            • Sefton Council, United Kingdom
            • -
            • software.coop, United Kingdom
            • -
            • South-East Kansas Library System (SEKLS), USA
            • -
            • South Taranaki District Council, New Zealand
            • -
            • Stockholm University Library, Sweden
            • -
            • SWITCH Library Consortium, USA
            • -
            • Talking Tech, Global
            • -
            • Tamil, France
            • -
            • Theke Solutions, Argentina
            • -
            • Tulong Aklatan, Philippines
            • -
            • Uintah Library System, USA
            • -
            • Universidad de El Salvador, El Salvador
            • -
            • Universidad Empresarial Siglo 21, Argentina
            • -
            • Universidad Nacional de Córdoba, Argentina
            • -
            • Universidad ORT Uruguay
            • -
            • Université d'Aix-Marseille, France
            • -
            • Université de Lyon 3, France
            • -
            • Université de Rennes 2, France
            • -
            • Université de St Etienne, France
            • -
            • University of the Arts London, United Kingdom
            • -
            • Vaara-kirjastot, Finland
            • -
            • Vanier College, Canada
            • -
            • Vermont Organization of Koha Automated Libraries (VOKAL), USA
            • -
            • Ville de Victoriaville, Canada
            • -
            • Virginia Tech, USA
            • -
            • Washoe County Library System, USA
            • -
            • Xercode, Spain
            • -
            - -

            Additional thanks to...

            -
              -
            • Irma Birchall
            • -
            • Rachel Hamilton-Williams (Kaitiaki from 2004 to present)
            • -
            • Stephen Hedges (early Documentation Manager)
            • -
            • Brooke Johnson
            • -
            • Jo Ransom
            • -
            • Nicholas Rosasco (Documentation Compiler)
            • -
            • Regula Sebastiao
            • -
            - [% END # tab=team %] -[% END %] - -[% BLOCK licenses_panel %] - [% WRAPPER tab_panel tabname= "licenses" bt_active = 1 %] -

            Koha

            -

            - This program 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 3 of the License, or (at your option) any later version. -

            - -

            Bootstrap

            -

            - Bootstrap, Glyphicons Free: MIT License -

            - -

            Bootstrap Icons

            -

            - Bootstrap Icons: MIT License -

            - -

            Bridge Material Type Icon Set

            -

            - Bridge Material Type Icons Project: Creative Commons Attribution-ShareAlike 2.5 License -

            - -

            Chocolat.js

            -

            - Chocolat.js v1.1.2: GNU General Public License v3.0 -

            - -

            CodeMirror

            -

            - CodeMirror v5.40.2: MIT License -

            - -

            C3.js

            -

            - C3.js D3-based reusable chart library v0.4.11: MIT Licence -

            - -

            CSSLint

            -

            - CSSLint v0.9.8: License -

            - -

            D3

            -

            - D3 JavaScript library for visualizing data v3.5.17: ISC Licence -

            - -

            DataTables

            -

            - DataTables v.1.10.18: MIT Licence -

            - -

            Day.js

            -

            - Day.js v1.11.2: MIT License -

            - -

            Enquire.js

            -

            - Enquire.js v2.1.6: MIT License -

            - -

            FamFamFam icons

            -

            - FamFamFam Silk icons: Creative Commons Attribution 2.5 License -

            - -

            FileSaver.js

            -

            - FileSaver.js v2.0.4: MIT License - -

            Flatpicker

            -

            - Flatpickr v4.6.9: MIT License -

            - -

            Font Awesome

            -

            - Font Awesome v6.3.0: Creative Commons Attribution 4.0 International License, SIL Open Font License Version 1.1, MIT License -

            - -

            Font Face Observer

            -

            - Font Face Observer JavaScript library v2.3.0: BSD 2-Clause "Simplified" License -

            - -

            GreyBox

            -

            - GreyBox JavaScript Library v5.54: GNU Lesser General Public License, version 2.1 -

            - -

            Highlight

            -

            - Highlight jQuery Plugin v5.0: MIT License -

            - -

            HTMLHint

            -

            - HTMLHint v0.9.12: MIT License -

            - -

            Humanized Messages

            -

            - Humanized Messages v1.0: Apache License, Version 2.0 -

            - -

            JavaScript Cookie

            -

            - JavaScript Cookie v3.0.1: MIT License -

            - -

            JavaScript Diff Algorithm

            -

            - JavaScript Diff Algorithm: MIT License -

            - -

            jQuery, jQuery Migrate, and jQuery UI

            -

            - jQuery v3.6.0, jQuery Migrate, jQuery UI v1.13.2: MIT License -

            - -

            jQuery Bar Rating Plugin

            -

            - jQuery Bar Rating plugin v1.2.2: MIT License -

            - -

            jQuery Emojiarea Plugin

            -

            - Emojiarea plugin for jQuery: Apache License, Version 2.0 -

            - -

            jQuery insertAtCaret Plugin

            -

            - jQuery insertAtCaret Plugin v1.0 by the phpMyAdmin development team: GNU General Public License -

            - -

            jQuery jsTree Plugin

            -

            - jQuery jsTree Plugin v3.3.12: MIT License -

            - -

            jQuery Multiple Select Plugin

            -

            - jQuery Multiple Select plugin v1.6.0: MIT License -

            - -

            jQuery TableDnD Plugin

            -

            - Table drag and drop JQuery plugin: MIT License -

            - -

            jQuery Treetable Plugin

            -

            - jQuery Treetable Plugin 3.1.0: GNU General Public License v2.0, MIT License -

            - -

            jQuery Validation Plugin

            -

            - jQuery Validation Plugin v1.19.3: MIT License -

            - -

            JS-YAML

            -

            - JS-YAML v3.13.1: MIT License -

            - -

            JSHint

            -

            - JSHint v2.9.7: MIT License -

            - -

            JSZip

            -

            - JSZip JavaScript library v3.1.3: MIT License, GNU General Public License v3.0 -

            - -

            kjua

            -

            - kjua JavaScript library v0.6.0: MIT License -

            - -

            Leaflet

            -

            - Leaflet JavaScript library v1.0.3: BSD License -

            - -

            Noto fonts

            -

            - Noto: SIL Open Font License Version 1.1 -

            - -

            OAI XSLT stylesheet

            -

            - Adapted from the DSpace project: BSD License -

            - -

            OpenAPI 2.0 schema

            -

            - JSON Schema for Swagger 2.0 API: Apache License, Version 2.0, OpenAPI Initiative (OAI) -

            - -

            OpenJS Keyboard Shortcuts Library

            -

            - OpenJS keyboard shortcuts library: BSD License -

            - -

            RequireJS

            -

            - RequireJS JavaScript file and module loader v2.1.8: BSD License or MIT License -

            - -

            Select2

            -

            - Select2 library v4.0.13: Apache License, Version 2.0 or GNU General Public License v2.0 -

            - -

            Sortable

            -

            - Sortable JavaScript Library v1.15.0: MIT Licence -

            - -

            TinyMCE WYSIWYG Editor

            -

            - TinyMCE WYSIWYG editor v5.9.2: GNU Lesser General Public License v2.1 -

            - -

            Verovio

            -

            - Verovio: GNU General Public License v3.0, GNU Lesser General Public License v3.0 -

            - -

            Virtual Keyboard

            -

            - Virtual Keyboard v1.30.1: MIT Licence -

            - - [% END # tab=licenses %] -[% END %] - -[% BLOCK translations_panel %] - [% WRAPPER tab_panel tabname= "translations" bt_active = 1 %] -

            Translation

            -
              -
            • العربية (Arabic) Version 3.2 to 3.4, 3.16 & 3.18 by KnowledgeWare Technologies; Versions 3.6 to 3.14 by Arabic Koha support team: Karam Qubsi, Kouider Bounama, Sham Bajaa, Ghofran Alshami, Chrestian Aboud, Fatema Salem and Duaa Bazzazi. -
            • አማርኛ (Amharic) Getway II Ethiopia Co. (Yohannes Mulugeta (Team Leader), Tegene Assefa, Abiyot Bayou)
            • -
            • Armenian Tigran Zargaryan
            • -
            • Български (Bulgarian) Radoslav Kolev
            • -
            • euskara (Basque) Fernando Berrizbeitia, the librarians of Eima Katalogoa, Tabakalera International Contemporary Culture Centre, and Nere Erkiaga
            • -
            • বাংলা (Bengali) Parthasarathi Mukhopadhyay
            • -
            • 中文 (Chinese)
            • -
            • Hrvatski (Croatian)
            • -
            • čeština (Czech)
            • -
            • Dænsk (Danish)
            • -
            • Nederlands-Nederland (Dutch-The Netherlands) Ronald Wijlens, Saxion University
            • -
            • Nederlands-België (Dutch-Belgium)
            • -
            • English
            • -
            • suomi, suomen kieli (Finnish) Pasi Korkalo
            • -
            • Français (French) Kohala, Pascale Nalon (ENSMP), and many more
            • -
            • Galego (Galician) Ignacio Javier
            • -
            • Deutsch (German) Friedrich zur Hellen, Robert Hillig, Katrin Fischer, Beda Szukics, Mirko Tietgen and Marc Véron
            • -
            • ελληνικά (Greek, Modern [1453- ]) Koha Hellenic Users' Group (Georgia Katsarou, Dimitris Antonakis, Eugenios Papadopoulos), Theodoros Theodoropoulos, Panoraia Gaitanou and Kiriaki Roditi
            • -
            • עברית (Hebrew)
            • -
            • हिन्दी (Hindi)
            • -
            • Magyar (Hungarian)Agnes Imecs
            • -
            • Norsk Bokmål (Norwegian) Axel Bojer and Thomas Gramstad
            • -
            • Norsk Nynorsk (Norwegian) Unni Knutsen and Marit Kristine Ådland
            • -
            • (Indonesian)
            • -
            • Italiano (Italian) for 3.2: Zeno Tajoli, Pietro Gozzetti and Paolo Pozzan; for 3.4 and more: Zeno Tajoli, Stefano Bargioni, Paolo Bizzarri
            • -
            • 日本語 (Japanese)
            • -
            • 한국어 (Korean)
            • -
            • ಕನ್ನಡ (kannaḍa)
            • -
            • Latina (Latin)
            • -
            • Lao Anousak Anthony Souphavanh
            • -
            • Māori
            • -
            • മലയാളം (Malayalam)
            • -
            • فارسى (Persian)
            • -
            • ଓଡ଼ିଆ (ōṛiyā)
            • -
            • Polski (Polish)
            • -
            • Português (Portuguese)
            • -
            • Română (Romanian)
            • -
            • Русский (Russian) Victor Titarchuk and Serhij Dubyk
            • -
            • Español (Spanish) Bernardo González Kriegel, Héctor Castro and Tomás Cohen Arazi, with the help of the koha-es community.
            • -
            • Svenska (Swedish)
            • -
            • Tetun (Tetum) Karen Myers
            • -
            • ภาษาไทย (Thai)
            • -
            • Türkçe (Turkish) pre-3.8: Selma Aslan; for 3.8+, Suleyman Demirel University (Ugur Bulgan, Onur Erdem, Kemal Caner Bayrakci, and Alper Tutunsatar)
            • -
            • اردو(Urdu) Ata ur Rehman
            • -
            • Українська (Ukrainian) Victor Titarchuk and Serhij Dubyk
            • -
            - [% END #tab=translations %] -[% END %] - -[% BLOCK history_panel %] - [% WRAPPER tab_panel tabname= "history" bt_active = 1 %] -

            Koha history timeline

            - [% IF ! timeline_read_error %] - - - - - - - - [% FOREACH tabl IN table2 %] - - [% FOREACH ro IN tabl.row2 %] - - + + + + + + + [% timezone_config_class = (time_zone.config_invalid) ? 'bg-warning' : '' %] + [% timezone_env_class = (time_zone.env_invalid) ? 'bg-warning' : '' %] + + - [% END %] + | + Config: + [% IF time_zone.config != '' %] + [% time_zone.config | html %] + [% ELSE %] + Undefined + [% END %] + | + Environment (TZ): + [% IF time_zone.environment != '' %] + [% time_zone.environment | html %] + [% ELSE %] + Undefined + [% END %] + +
            DateDescription
            [% ro.date | html %][% ro.desc | html %]
            Date and time: [% current_date_and_time | $KohaDates with_hours => 1 %]
            Time zone: + Used: [% time_zone.actual | html %] + [% IF time_zone.actual_bad_tz_fallback %] + (This is a fallback value due to a bad configuration) [% END %] -
            - [% ELSE %] -
            - Could not read the history.txt file. Please make sure <docdir> is correctly defined in koha-conf.xml. -
            + [% END # tab=about %] + [% END %] + + [% BLOCK perl_panel %] + [% WRAPPER tab_panel tabname= "perl" bt_active = 1 %] + + + [% FOREACH tabl IN table %] + + [% FOREACH ro IN tabl.row %] + [% IF ( ro.require ) %] + [% SET th_font_weight = "bold" %] + [% ELSE %] + [% SET th_font_weight = "normal" %] + [% END %] + [% IF ( ro.current ) %] + [% SET th_title = t("Module current") %] + [% ELSIF ( ro.upgrade ) %] + [% SET th_background_color = "#FFCB2F" %] + [% SET th_title = t("Module upgrade needed") %] + [% ELSE %] + [% IF ( ro.require ) %] + [% SET th_background_color = "#FF8A8A" %] + [% SET th_title = t("Required module missing") %] + [% ELSIF ( ro.name != '' ) %] + [% SET th_background_color = "#FF8A8A" %] + [% SET th_title = t("Optional module missing") %] + [% END %] + [% END # /IF ro.current %] + + [% IF ( ro.name == '' ) %] + + [% ELSIF ( ro.version ) %] + + [% ELSE %] + + [% END %] + [% END # /FOREACH ro %] + + [% END # /FOREACH tabl %] +
            Perl modules
            + [% IF ( ro.name ) %] + [% ro.name | html %] + + ([% ro.reqversion | html %] + [% IF ro.maxversion %]- [% ro.maxversion | html %][% END %] + [% IF ro.excversion %][% FOR v IN ro.excversion %], ![% v | html %][% END %][% END %]) + + [% END %] + [% ro.version | html %]Not Installed
            + [% END # tab=perl %] + [% END %] + + [% BLOCK sysinfo_panel %] + [% IF Asset.css("css/staff-global.css") == "" || Asset.js("js/vue/dist/erm.js") == "" %] + [% SET warnMissingCompiledFiles = 1 %] + [% END %] + [% WRAPPER tab_panel tabname= "sysinfo" bt_active = 1 %] + [% IF weasyprint_missing || warnPrefRequireChoosingExistingAuthority || warnPrefEasyAnalyticalRecords || warnPrefAnonymousPatronOPACPrivacy || warnPrefAnonymousPatronAnonSuggestions || warnPrefAnonymousPatronOPACPrivacy_PatronDoesNotExist || warnPrefAnonymousPatronAnonSuggestions_PatronDoesNotExist || warnPrefKohaAdminEmailAddress || warnPrefOpacHiddenItems || warnPrefPatronSelfRegistrationDefaultCategory || invalid_yesno.count || warnNoActiveCurrency || warnIsRootUser || xml_config_warnings.size || warnI18nMissing || AutoSelfCheckPatronDoesNotHaveSelfCheckPerm || AutoSelfCheckPatronHasTooManyPerm || warnStatisticsFieldsError || warnNoTemplateCaching || warnILLConfiguration || has_ai_issues || oauth2_missing_deps || bad_yaml_prefs || warnRelationships || log4perl_errors || config_bcrypt_settings_no_set || warnHiddenBiblionumbers.size || warnConnectBroker || elasticsearch_has_missing || warnMissingCompiledFiles || warnDbRowFormat %] + [% IF ( warnDbRowFormat ) %] +

            Database row format incorrect

            +

            Database tables with a row format other than 'DYNAMIC': [% warnDbRowFormat | html %]

            +

            You may experience problems upgrading to newer versions of Koha unless you update the row format for your database tables.

            +

            To know how to avoid this problem see the related wiki page: + Database row format +

            + [% END %] + + [% IF (warnIsRootUser) %] +

            Warning regarding current user

            +

            You are logged in as the database administrative user. This is not recommended because some parts of Koha will not function as expected when using this account.

            +

            Please log in instead with a regular staff account. To create a staff account, create a library, a patron category 'Staff' and add a new patron. Then give this patron permissions from 'More' in the toolbar.

            + [% END # /IF warnIsRootUser %] + + [% IF has_ai_issues %] +

            Data problems

            +

            Some of your tables have problems with their auto_increment values which may lead to data loss.

            +

            + You should not ignore this warning. +

            +

            The problem is that InnoDB does not keep auto_increment across SQL server restarts (it is only set in memory). So on server startup the auto_increment values are set to max(table.id)+1.

            +

            To know how to avoid this problem see the related wiki page: + DBMS auto increment fix +

            + +

            Problems found

            + [% IF ai_patrons %] +

            Patrons

            +

            The following IDs exist in both tables [% "borrowers" | $HtmlTags tag="strong" %] and [% "deletedborrowers" | $HtmlTags tag="strong" %]:

            +

            + [% FOR p IN ai_patrons %] + [% p.borrowernumber | html %] + [% UNLESS loop.last %],[% END %] + [% END %] +

            + [% END %] + [% IF ai_biblios %] +

            Bibliographic records

            +

            The following IDs exist in both tables [% "biblio" | $HtmlTags tag="strong" %] and [% "deletedbiblio" | $HtmlTags tag="strong" %]:

            +

            + [% FOR b IN ai_biblios %] + [% b.biblionumber | html %] + [% UNLESS loop.last %],[% END %] + [% END %] +

            + [% END %] + [% IF ai_biblioitems %] +

            Bibliographic records

            +

            The following IDs exist in both tables [% "biblio" | $HtmlTags tag="strong" %] and [% "deletedbiblioitems" | $HtmlTags tag="strong" %]:

            +

            + [% FOR b IN ai_biblioitems %] + [% b.biblioitemnumber | html %] + [% UNLESS loop.last %],[% END %] + [% END %] +

            + [% END %] + [% IF ai_items %] +

            Items

            +

            The following IDs exist in both tables [% "items" | $HtmlTags tag="strong" %] and [% "deleteditems" | $HtmlTags tag="strong" %]:

            +

            + [% FOR i IN ai_items %] + [% i.itemnumber | html %] + [% UNLESS loop.last %],[% END %] + [% END %] +

            + [% END %] + [% IF ai_checkouts %] +

            Checkouts

            +

            The following IDs exist in both tables [% "issues" | $HtmlTags tag="strong" %] and [% "old_issues" | $HtmlTags tag="strong" %]:

            +

            + [% FOR c IN ai_checkouts %] + [% c.issue_id | html %] + [% UNLESS loop.last %],[% END %] + [% END %] +

            + [% END %] + [% IF ai_holds %] +

            Holds

            +

            The following IDs exist in both tables [% "reserves" | $HtmlTags tag="strong" %] and [% "old_reserves" | $HtmlTags tag="strong" %]:

            +

            + [% FOR h IN ai_holds %] + [% h.reserve_id | html %] + [% UNLESS loop.last %],[% END %] + [% END %] +

            + [% END %] +
            + [% END # /IF has_ai_issues %] + + [% IF warnRelationships %] +

            Patron relationship problems

            + [% IF bad_relationships_count %] +

            Your database contained guarantee/guarantor pairs with no defined relationship. They have been set the value '_bad_data' in the [% "borrowers.relationship" | $HtmlTags tag="strong" %] and/or + [% "borrower_relationships.relationship" | $HtmlTags tag="strong" %] columns. Fix them manually by recreating those relationships, or have your system's administrator correct the values.

            + [% END # /IF bad_relationships_count %] + + [% IF wrong_relationships %] +

            The following values have been used for guarantee/guarantor relationships, but do not exist in the 'borrowerRelationship' system preference:

            +
              + [% FOR rel IN wrong_relationships %] +
            • [% rel.0 | html %]
            • + [% END %] +
            +

            If the relationship is one you want, please add it to the 'borrowerRelationship' system preference, otherwise have your system's administrator correct the values in + [% "borrowers.relationship" | $HtmlTags tag="strong" %] and/or [% "borrower_relationships.relationship" | $HtmlTags tag="strong" %] in the database.

            + [% END # /IF wrong_relationships %] + [% END # /IF warnRelationships %] + + [% IF log4perl_errors %] +

            Logging system does not behave correctly

            + [% FOR e IN log4perl_errors %] + [% SWITCH e %] + [% CASE 'missing_config_entry' %] + There is no 'log4perl_conf' entry in the config file. + [% CASE 'cannot_read_config_file' %] + The log4perl config file cannot be opened. + [% CASE 'logfile_not_writable' %] + One of the logfiles listed in the config file is not writable. + [% CASE 'cannot_init_module' %] + The Koha::Logger module cannot be initiated correctly (check the log file). + [% CASE %] + Unknown error '[% e | html %]'. + [% END %] + [% END # /FOR e %] + [% END # /IF log4perl_errors %] + + [% IF warnConnectBroker %] +

            Impossible to connect to the message broker

            + There is an error when trying to connect to the message broker (RabbitMQ), check the Koha log files. +
            + Maybe it is not installed and configured correctly? +
            + Contact your system administrator. + [% END # /IF warnConnectBroker %] + + [% IF weasyprint_missing || warnPrefRequireChoosingExistingAuthority || warnPrefEasyAnalyticalRecords || warnPrefAnonymousPatronOPACPrivacy || warnPrefAnonymousPatronAnonSuggestions || warnPrefAnonymousPatronOPACPrivacy_PatronDoesNotExist || warnPrefAnonymousPatronAnonSuggestions_PatronDoesNotExist || warnPrefKohaAdminEmailAddress || warnPrefOpacHiddenItems || warnPrefPatronSelfRegistrationDefaultCategory || invalid_yesno.count || warnNoActiveCurrency || AutoSelfCheckPatronDoesNotHaveSelfCheckPerm || AutoSelfCheckPatronHasTooManyPerm || warnStatisticsFieldsError || warnNoTemplateCaching || warnILLConfiguration || warnXSLT || oauth2_missing_deps || bad_yaml_prefs || warnIssuingRules || config_bcrypt_settings_no_set || warnHiddenBiblionumbers.size || warnFastCataloging %] +

            Warnings regarding the system configuration

            + + + [% IF (warnFastCataloging) %] + + + + + [% END %] + [% IF (warnPrefRequireChoosingExistingAuthority) %] + + + + + [% END %] + [% IF (warnPrefEasyAnalyticalRecords) %] + + + + + [% END %] + [% IF warnPrefAnonymousPatronOPACPrivacy %] + + + + + [% END %] + [% IF warnPrefAnonymousPatronAnonSuggestions %] + + + + + [% END %] + [% IF warnPrefAnonymousPatronOPACPrivacy_PatronDoesNotExist %] + + + + + [% END %] + [% IF warnPrefAnonymousPatronAnonSuggestions_PatronDoesNotExist %] + + + + + [% END %] + [% IF warnPrefKohaAdminEmailAddress %] + + + + + [% END %] + [% IF warnPrefOpacHiddenItems %] + + + + [% END %] + [% IF warnPrefPatronSelfRegistrationDefaultCategory %] + + [% END %] + [% IF warnXSLT %] + [% FOR p IN warnXSLT %] + + + + [% END %] + [% END %] + [% IF invalid_yesno.count %] + [% FOR p IN invalid_yesno %] + + + + + [% END %] + [% END %] + [% IF warnNoActiveCurrency %] + + + + + [% END %] + [% IF warnStatisticsFieldsError %] + + + + + [% END %] + [% IF AutoSelfCheckPatronDoesNotHaveSelfCheckPerm %] + + + + + [% END %] + [% IF AutoSelfCheckPatronHasTooManyPerm %] + + + + + [% END %] + [% IF warnNoTemplateCaching %] + + + + + [% END %] + [% IF warnI18nMissing %] + + + + + [% END %] + [% IF warnILLConfiguration %] + [% IF no_ill_backends %] + + + + + [% END %] + [% IF ill_partner_code_not_defined %] + + + + + [% END %] + [% IF ill_partner_code_no_patrons %] + + + + + [% END %] + [% IF ill_branch_not_defined %] + + + + + [% END %] + [% IF ill_partner_code_doesnt_exist %] + + + + + [% END %] + [% END %] + + [% IF weasyprint_missing %] + + [% END %] + + [% IF oauth2_missing_deps %] + + + + + [% END %] + [% IF bad_yaml_prefs %] + + + + + [% END %] + [% IF config_bcrypt_settings_no_set %] + + + + + [% END %] + [% IF warnHiddenBiblionumbers.size %] + + + + + [% END %] + [% IF Koha.Preference('SearchEngine') == 'Elasticsearch' && elasticsearch_status.version.substr(0,1) < 6 %] + + + + + [% END %] +
            Preferences and parameters
            Warning There is no "Fast add" (FA) framework defined in administration->MARC frameworks. This disables the 'Fast cataloging' feature in cataloging/circulation.
            Warning System preference 'RequireChoosingExistingAuthority' is disabled, but needs 'AutoCreateAuthorities' enabled. Otherwise catalogers can add headings that will not be linked to authorities.
            Warning System preference 'EasyAnalyticalRecords' set, but UseControlNumber preference is set to 'Use'. Set it to 'Don't use' or else the 'Show analytics' links in the staff interface and the OPAC will be + broken.
            Error System preference 'OPACPrivacy' set, but AnonymousPatron preference is set to '0'. Set it to a valid borrower number or checkins for these patrons will fail.
            Warning System preference 'AnonSuggestions' set, but AnonymousPatron preference is set to '0'. Set it to a valid borrower number if you want that this feature works correctly.
            Error Some patrons have requested privacy after their items are checked in, but the AnonymousPatron preference is not set correctly. Set it to a valid borrower number or checkins for these patrons will + fail.
            Warning System preference 'AnonSuggestions' set, but AnonymousPatron preference is not set correctly. Set it to a valid borrower number if you want that this feature works correctly.
            Warning System preference 'KohaAdminEmailAddress' does not contain a valid email address. Emails will not be sent.
            Warning System preference 'OpacHiddenItems' generates a warning and will produce unexpected behaviors: [% warnPrefOpacHiddenItems | html %]
            Warning System preference 'PatronSelfRegistration' is set, but 'PatronSelfRegistrationDefaultCategory' does not contain a valid patron category code. Patron self-registration is disabled.
            Warning System preference '[% p.syspref | html %]' is '[% p.value | html %]', but the file '[% p.filename | html %]' does not exist.
            Warning System preference '[% p.variable | html %]' must be '0' or '1', but is [% IF p.value.defined %]'[% p.value | html %]'[% ELSE %]NULL[% END %].
            Warning No active currency is defined. Please go to Administration > Currencies and exchange rates and mark one currency as active.
            Warning System preference 'StatisticsFields' contains field names not belonging to the items database table: [% warnStatisticsFieldsError | html %]
            Warning The patron used for the self checkout module at the OPAC does not have the self_check => self_checkout_module permission.
            Warning The patron used for the self checkout module at the OPAC has too many permissions. They should only have self_check => self_checkout_module.
            Warning You are missing the <template_cache_dir> entry in your koha-conf.xml file. That will bring a performance boost to enable it.
            Warning The PO directory has not been found. See the dedicated wiki page for more information.
            Warning The ILL module is enabled, but there are no backends available.
            Warning The ILL module is enabled, but ILLPartnerCode system preference is empty. Falling back to the hardcoded 'IL'.
            Warning The ILL module is enabled and ILLPartnerCode system preference configured, but there are no patrons in [% ill_partner_code_no_patrons | html %] category.
            Warning The ILL module is enabled, but no 'branch' block is defined in koha-conf.xml. You must define this block before use.
            Warning The ILL module is enabled, but the configured ILLPartnerCode ([% ill_partner_code_doesnt_exist | html %]) is not defined on the system.
            Warning The weasyprint tool is not installed.
            Warning System preference 'RESTOAuth2ClientCredentials' is set, but the required Net::OAuth2::AuthorizationServer dependency is missing. The feature is disabled.
            Warning Some system preferences have badly formatted YAML content: [% bad_yaml_prefs.join(', ') | html %]
            Warning System preference 'Pseudonymization' is set, but there is not 'bcrypt_settings' entry defined in the $KOHA_CONF file.
            Warning + [% FOR w IN warnHiddenBiblionumbers %] + Bibliographic framework "[% w.frameworkcode | html %]" has the biblionumber field hidden at the interface [% w.interface | html %]
            + [% END %] +
            Deprecation warning Elasticsearch version 5.x is not supported in Koha 20.11 and greater. Please upgrade your Elasticsearch cluster
            + [% END # /IF warnPrefRequireChoosingExistingAuthority %] + + [% IF xml_config_warnings.size %] + + + [% FOREACH config_entry IN xml_config_warnings %] + [% IF config_entry.error == 'zebra_bib_index_mode_is_grs1' %] + + + + + [% ELSIF config_entry.error == 'zebra_auth_index_mode_is_grs1' %] + + + + + [% ELSIF config_entry.error == 'use_zebra_facets_entry_missing' %] + + + + + [% ELSIF config_entry.error == 'log4perl_entry_missing' %] + + + + + [% ELSIF config_entry.error == 'lockdir_entry_missing' %] + + + + + [% ELSIF config_entry.error == 'lockdir_not_writable' %] + + + + + [% ELSIF config_entry.error == 'uploadpath_entry_missing' %] + + + + + [% ELSIF config_entry.error == 'uploadpath_and_opacbaseurl_entry_missing' %] + + + + + [% ELSIF config_entry.error == 'tmp_path_missing' %] + + + + + [% ELSIF config_entry.error == 'encryption_key_missing' %] + + + + + [% END # /IF config_entry.error %] + [% END # /FOREACH config_entry %] +
            XML configuration file
            Warning + The <zebra_bib_index_mode> entry set to 'grs1', which is no longer supported. Please use DOM instead. To switch follow this page of wiki: + Switching to dom indexing +
            Warning + The <zebra_auth_index_mode> entry set to 'grs1', which is no longer supported. Please use DOM instead. To switch follow this page of wiki: + Switching to dom indexing +
            Warning The <use_zebra_facets> entry is missing in your configuration file. Falling back to legacy facet calculation.
            Warning You are missing the <log4perl_conf> entry in your koha-conf.xml file. Please add it, pointing to the log4perl.conf file for your Koha instance.
            Warning You are missing the <lockdir> entry in your koha-conf.xml file. Please add it, pointing to your Koha instance's lock dir.
            Warning The configured <lockdir> entry in your koha-conf.xml file points to a non-writable directory ([% config_entry.lockdir | html %]).
            Warning You are missing the <upload_path> entry in your koha-conf.xml file. Please add it, pointing to the configured file upload directory for your Koha instance.
            Warning + You are missing the <upload_path> entry in your koha-conf.xml file. Please add it, pointing to the configured file upload directory for your Koha instance. Also note that you need to properly + set the OPACBaseURL preference for the file upload plugin to work. +
            Warning + You are missing the <tmp_path> entry in your koha-conf.xml file. Please add it, pointing to the configured temporary directory for your Koha instance. The effective temporary directory is + '[% config_entry.effective_tmp_dir | html %]'. +
            Warning You are missing the <encryption_key> entry in your koha-conf.xml file. Please generate a key. We recommend one of at least 32 bytes. (You might use 'pwgen 32' to do so.)
            + [% END # /IF xml_config_warnings.size %] + + [% IF warnIssuingRules %] + + + [% FOREACH unit IN ir_units %] + + + + + [% END # /FOREACH unit %] +
            Issuing rules
            Warning + The [% unit.branchcode || 'branchcode=default' | html %], [% unit.categorycode || 'categorycode=default' | html %], [% unit.itemtype || 'itemtype=default' | html %]issuingrule will fallback to 'days' for + 'lengthunit' as it is incorrectly defined as [% unit.rule_value | html %]. +
            + [% END # /IF warnIssuingRules %] + + [% IF elasticsearch_has_missing %] + + + [% FOREACH index IN elasticsearch_status.indexes %] + [% IF index.missing_count %] + + + + + [% END %] + [% END %] +
            Records are not indexed in Elasticsearch
            Warning [% index.missing_count | html %] record(s) missing on a total of [% index.index_count | html %] in index [% index.index_name | html %].
            + [% END # /IF elasticsearch_has_missing %] + + [% IF warnMissingCompiledFiles %] + Error Compiled CSS and/or JS files are not present. Please run `yarn build` to generate them. + [% END # /IF warnMissingCompiledFiles %] + [% ELSE %] +

            No warnings.

            + [% END # /IF warnRequireChoosingExistingAuthority... %] + [% END # tab=sysinfo %] + [% END %] + + [% BLOCK team_panel %] + [% WRAPPER tab_panel tabname= "team" bt_active = 1 %] +

            Special thanks to the following organizations

            + + +

            Koha release teams

            + [% IF maintenance_team %] +
            +
            +

            Koha [% short_version | html %][% IF kohaCodename %]([% kohaCodename | html %])[% END %] release team

            + [% IF development_version %] +

            You are running a development version of Koha

            + [% ELSE %] + [% INCLUDE team t=release_team v='release' %] + [% END %] +
            + +
            +

            Current maintenance team

            + [% INCLUDE team t=maintenance_team v=short_version %] + [% IF development_version %] +
          • Release maintainers: +
              + [% FOREACH m IN maintenance_team.maintainer %] +
            • [% m.version | html %] - [% INCLUDE person p=m %]
            • + [% IF maintenance_team.maintainer_assistants %] + [% FOREACH ma IN maintenance_team.maintainer_assistants %] + [% IF ma.version == ( m.version ) %] +
              • Assistant: [% INCLUDE person p=ma %]
              + [% END %] + [% END %] + [% END %] + + [% IF maintenance_team.maintainer_mentors %] + [% FOREACH mm IN maintenance_team.maintainer_mentors %] + [% IF m.version == ( mm.version ) %] +
              • Mentor: [% INCLUDE person p=mm %]
              + [% END %] + [% END %] + [% END %] + [% END %] +
            +
          • + [% END %] +
            +
            + [% ELSE %] +
            Could not read the teams.yaml file. Please make sure <docdir> is correctly defined in koha-conf.xml.
            + [% END # /maintenance_team %] + +

            Koha development team

            + [% IF contributors.size %] +
              + [% FOREACH contributor IN contributors %] +
            • [% INCLUDE person p=contributor %][% INCLUDE contributions p=contributor %]
            • + [% END %] +
            + [% ELSE %] +
            Could not read the contributors.yaml file. Please make sure <docdir> is correctly defined in koha-conf.xml.
            + [% END # /IF contributors.size %] +
            + +

            Contributing companies and institutions

            +
              +
            • Allen Ginsberg Library, USA
            • +
            • Alingsås Public Library, Sweden
            • +
            • American Numismatic Society, USA
            • +
            • Arcadia Public Library, USA
            • +
            • Athens County Public Libraries, USA
            • +
            • BdP de la Meuse, France
            • +
            • BibLibre, France
            • +
            • Biblioteca Provincial Fr. Mamerto Esquiú (Provincia Franciscana de la Asunción), Argentina
            • +
            • Bibliotheksservice-Zentrum Baden-Württemberg (BSZ), Germany
            • +
            • Briar Cliff University, USA
            • +
            • Brimbank City Council, Australia
            • +
            • Brooklyn Law School Library, USA
            • +
            • Bibliothèque Universitaire des Langues et Civilisations (BULAC), France
            • +
            • ByWater Solutions, USA
            • +
            • California College of the Arts, USA
            • +
            • Camden County, USA
            • +
            • Carnegie Stout Library, USA
            • +
            • Calyx, Australia
            • +
            • Catalyst IT, New Zealand
            • +
            • Central Kansas Library System (CKLS), USA
            • +
            • Centre collégial des services regroupés (CCSR), Canada
            • +
            • Cheshire Libraries, United Kingdom
            • +
            • Coeur d'Alene Public Library, USA
            • +
            • Corpus Christi Public Libraries, USA
            • +
            • C & P Bibliography Services, USA
            • +
            • Dataly Tech, Greece
            • +
            • Devinim, Turkey
            • +
            • Do Space, USA
            • +
            • DoverNet, USA
            • +
            • doXulting
            • +
            • Duchesne County Library, USA
            • +
            • Escuela de Orientacion Lacaniana, Argentina
            • +
            • Fenway Library Organization, USA
            • +
            • Fargo Public Library, USA
            • +
            • Farmington Public Library, USA
            • +
            • FIT
            • +
            • Foundations Bible College & Seminary, USA
            • +
            • Goethe-Institut, Germany
            • +
            • Gothenburg University Library, Sweden
            • +
            • Halland County Library, Sweden
            • +
            • Harrison Carmel Public Library, USA
            • +
            • Hauraki District Libraries, New Zealand
            • +
            • Higher Education Libraries of Massachusetts, USA
            • +
            • Hochschule für Gesundheit (hsg), Germany
            • +
            • Hotchkiss School, USA
            • +
            • Katipo Communications, New Zealand
            • +
            • KEEP SOLUTIONS, Portugal
            • +
            • KohaAloha, New Zealand
            • +
            • Koha-Suomi Oy, Finland
            • +
            • LibLime, USA
            • +
            • Library of the Józef Piłsudski Institute of America, USA
            • +
            • Libriotech, Norway
            • +
            • Los Gatos Public Library, USA
            • +
            • Lund University Library, Sweden
            • +
            • MassCat, USA
            • +
            • Middletown Township Public Library, USA
            • +
            • National Library of Finland, Finland
            • +
            • Newcastle City Council, United Kingdom
            • +
            • New Zealand Central Agencies Library, New Zealand
            • +
            • New Zealand Ministry of Education Library, New Zealand
            • +
            • North Central Regional Library (NCRL), USA
            • +
            • Northeast Kansas Library System (NEKLS), USA
            • +
            • OPUS
            • +
            • Orex Digital, Spain
            • +
            • Oslo Public Library, Norway
            • +
            • Plano Independent School, USA
            • +
            • Plant and Food Research Limited, New Zealand
            • +
            • Prosentient Systems, Australia
            • +
            • PTFS, Maryland, USA
            • +
            • PTFS Europe Ltd, United Kingdom
            • +
            • Rijksmuseum, Amsterdam, The Netherlands
            • +
            • Rolling Hills Consolidated Libraries, USA
            • +
            • Round Rock Public Library, USA
            • +
            • SAN-Ouest Provence, France
            • +
            • Sefton Council, United Kingdom
            • +
            • software.coop, United Kingdom
            • +
            • South-East Kansas Library System (SEKLS), USA
            • +
            • South Taranaki District Council, New Zealand
            • +
            • Stockholm University Library, Sweden
            • +
            • SWITCH Library Consortium, USA
            • +
            • Talking Tech, Global
            • +
            • Tamil, France
            • +
            • Theke Solutions, Argentina
            • +
            • Tulong Aklatan, Philippines
            • +
            • Uintah Library System, USA
            • +
            • Universidad de El Salvador, El Salvador
            • +
            • Universidad Empresarial Siglo 21, Argentina
            • +
            • Universidad Nacional de Córdoba, Argentina
            • +
            • Universidad ORT Uruguay
            • +
            • Université d'Aix-Marseille, France
            • +
            • Université de Lyon 3, France
            • +
            • Université de Rennes 2, France
            • +
            • Université de St Etienne, France
            • +
            • University of the Arts London, United Kingdom
            • +
            • Vaara-kirjastot, Finland
            • +
            • Vanier College, Canada
            • +
            • Vermont Organization of Koha Automated Libraries (VOKAL), USA
            • +
            • Ville de Victoriaville, Canada
            • +
            • Virginia Tech, USA
            • +
            • Washoe County Library System, USA
            • +
            • Xercode, Spain
            • +
            + +

            Additional thanks to...

            +
              +
            • Irma Birchall
            • +
            • Rachel Hamilton-Williams (Kaitiaki from 2004 to present)
            • +
            • Stephen Hedges (early Documentation Manager)
            • +
            • Brooke Johnson
            • +
            • Jo Ransom
            • +
            • Nicholas Rosasco (Documentation Compiler)
            • +
            • Regula Sebastiao
            • +
            + [% END # tab=team %] + [% END %] + + [% BLOCK licenses_panel %] + [% WRAPPER tab_panel tabname= "licenses" bt_active = 1 %] +

            Koha

            +

            + This program 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 3 of the License, or (at your option) any later version. +

            + +

            Bootstrap

            +

            Bootstrap, Glyphicons Free: MIT License

            + +

            Bootstrap Icons

            +

            Bootstrap Icons: MIT License

            + +

            Bridge Material Type Icon Set

            +

            Bridge Material Type Icons Project: Creative Commons Attribution-ShareAlike 2.5 License

            + +

            Chocolat.js

            +

            Chocolat.js v1.1.2: GNU General Public License v3.0

            + +

            CodeMirror

            +

            CodeMirror v5.40.2: MIT License

            + +

            C3.js

            +

            C3.js D3-based reusable chart library v0.4.11: MIT Licence

            + +

            CSSLint

            +

            CSSLint v0.9.8: License

            + +

            D3

            +

            D3 JavaScript library for visualizing data v3.5.17: ISC Licence

            + +

            DataTables

            +

            DataTables v.1.10.18: MIT Licence

            + +

            Day.js

            +

            Day.js v1.11.2: MIT License

            + +

            Enquire.js

            +

            Enquire.js v2.1.6: MIT License

            + +

            FamFamFam icons

            +

            FamFamFam Silk icons: Creative Commons Attribution 2.5 License

            + +

            FileSaver.js

            +

            FileSaver.js v2.0.4: MIT License

            Flatpicker

            +

            Flatpickr v4.6.9: MIT License

            + +

            Font Awesome

            +

            + Font Awesome v6.3.0: + Creative Commons Attribution 4.0 International License, SIL Open Font License Version 1.1, MIT License +

            + +

            Font Face Observer

            +

            Font Face Observer JavaScript library v2.3.0: BSD 2-Clause "Simplified" License

            + +

            GreyBox

            +

            + GreyBox JavaScript Library v5.54: + GNU Lesser General Public License, version 2.1 +

            + +

            Highlight

            +

            Highlight jQuery Plugin v5.0: MIT License

            + +

            HTMLHint

            +

            HTMLHint v0.9.12: MIT License

            + +

            Humanized Messages

            +

            Humanized Messages v1.0: Apache License, Version 2.0

            + +

            JavaScript Cookie

            +

            JavaScript Cookie v3.0.1: MIT License

            + +

            JavaScript Diff Algorithm

            +

            JavaScript Diff Algorithm: MIT License

            + +

            jQuery, jQuery Migrate, and jQuery UI

            +

            + jQuery v3.6.0, jQuery Migrate, jQuery UI v1.13.2: + MIT License +

            + +

            jQuery Bar Rating Plugin

            +

            jQuery Bar Rating plugin v1.2.2: MIT License

            + +

            jQuery Emojiarea Plugin

            +

            Emojiarea plugin for jQuery: Apache License, Version 2.0

            + +

            jQuery insertAtCaret Plugin

            +

            jQuery insertAtCaret Plugin v1.0 by the phpMyAdmin development team: GNU General Public License

            + +

            jQuery jsTree Plugin

            +

            jQuery jsTree Plugin v3.3.12: MIT License

            + +

            jQuery Multiple Select Plugin

            +

            jQuery Multiple Select plugin v1.6.0: MIT License

            + +

            jQuery TableDnD Plugin

            +

            Table drag and drop JQuery plugin: MIT License

            + +

            jQuery Treetable Plugin

            +

            + jQuery Treetable Plugin 3.1.0: GNU General Public License v2.0, + MIT License +

            + +

            jQuery Validation Plugin

            +

            jQuery Validation Plugin v1.19.3: MIT License

            + +

            JS-YAML

            +

            JS-YAML v3.13.1: MIT License

            + +

            JSHint

            +

            JSHint v2.9.7: MIT License

            + +

            JSZip

            +

            JSZip JavaScript library v3.1.3: MIT License, GNU General Public License v3.0

            + +

            kjua

            +

            kjua JavaScript library v0.6.0: MIT License

            + +

            Leaflet

            +

            Leaflet JavaScript library v1.0.3: BSD License

            + +

            Noto fonts

            +

            Noto: SIL Open Font License Version 1.1

            + +

            OAI XSLT stylesheet

            +

            Adapted from the DSpace project: BSD License

            + +

            OpenAPI 2.0 schema

            +

            + JSON Schema for Swagger 2.0 API: + Apache License, Version 2.0, OpenAPI Initiative (OAI) +

            + +

            OpenJS Keyboard Shortcuts Library

            +

            OpenJS keyboard shortcuts library: BSD License

            + +

            RequireJS

            +

            RequireJS JavaScript file and module loader v2.1.8: BSD License or MIT License

            + +

            Select2

            +

            Select2 library v4.0.13: Apache License, Version 2.0 or GNU General Public License v2.0

            + +

            Sortable

            +

            Sortable JavaScript Library v1.15.0: MIT Licence

            + +

            TinyMCE WYSIWYG Editor

            +

            TinyMCE WYSIWYG editor v5.9.2: GNU Lesser General Public License v2.1

            + +

            Verovio

            +

            + Verovio: GNU General Public License v3.0, + GNU Lesser General Public License v3.0 +

            + +

            Virtual Keyboard

            +

            Virtual Keyboard v1.30.1: MIT Licence

            + [% END # tab=licenses %] + [% END %] + + [% BLOCK translations_panel %] + [% WRAPPER tab_panel tabname= "translations" bt_active = 1 %] +

            Translation

            +
              +
            • العربية (Arabic) Version 3.2 to 3.4, 3.16 & 3.18 by KnowledgeWare Technologies; Versions 3.6 to 3.14 by Arabic Koha support team: Karam Qubsi, Kouider Bounama, Sham Bajaa, Ghofran Alshami, Chrestian Aboud, Fatema Salem + and Duaa Bazzazi.
            • አማርኛ (Amharic) Getway II Ethiopia Co. (Yohannes Mulugeta (Team Leader), Tegene Assefa, Abiyot Bayou)
            • +
            • Armenian Tigran Zargaryan
            • +
            • Български (Bulgarian) Radoslav Kolev
            • +
            • euskara (Basque) Fernando Berrizbeitia, the librarians of Eima Katalogoa, Tabakalera International Contemporary Culture Centre, and Nere Erkiaga
            • +
            • বাংলা (Bengali) Parthasarathi Mukhopadhyay
            • +
            • 中文 (Chinese)
            • +
            • Hrvatski (Croatian)
            • +
            • čeština (Czech)
            • +
            • Dænsk (Danish)
            • +
            • Nederlands-Nederland (Dutch-The Netherlands) Ronald Wijlens, Saxion University
            • +
            • Nederlands-België (Dutch-Belgium)
            • +
            • English
            • +
            • suomi, suomen kieli (Finnish) Pasi Korkalo
            • +
            • Français (French) Kohala, Pascale Nalon (ENSMP), and many more
            • +
            • Galego (Galician) Ignacio Javier
            • +
            • Deutsch (German) Friedrich zur Hellen, Robert Hillig, Katrin Fischer, Beda Szukics, Mirko Tietgen and Marc Véron
            • +
            • ελληνικά (Greek, Modern [1453- ]) Koha Hellenic Users' Group (Georgia Katsarou, Dimitris Antonakis, Eugenios Papadopoulos), Theodoros Theodoropoulos, Panoraia Gaitanou and Kiriaki + Roditi
            • +
            • עברית (Hebrew)
            • +
            • हिन्दी (Hindi)
            • +
            • Magyar (Hungarian)Agnes Imecs
            • +
            • Norsk Bokmål (Norwegian) Axel Bojer and Thomas Gramstad
            • +
            • Norsk Nynorsk (Norwegian) Unni Knutsen and Marit Kristine Ådland
            • +
            • (Indonesian)
            • +
            • Italiano (Italian) for 3.2: Zeno Tajoli, Pietro Gozzetti and Paolo Pozzan; for 3.4 and more: Zeno Tajoli, Stefano Bargioni, Paolo Bizzarri
            • +
            • 日本語 (Japanese)
            • +
            • 한국어 (Korean)
            • +
            • ಕನ್ನಡ (kannaḍa)
            • +
            • Latina (Latin)
            • +
            • Lao Anousak Anthony Souphavanh
            • +
            • Māori
            • +
            • മലയാളം (Malayalam)
            • +
            • فارسى (Persian)
            • +
            • ଓଡ଼ିଆ (ōṛiyā)
            • +
            • Polski (Polish)
            • +
            • Português (Portuguese)
            • +
            • Română (Romanian)
            • +
            • Русский (Russian) Victor Titarchuk and Serhij Dubyk
            • +
            • Español (Spanish) Bernardo González Kriegel, Héctor Castro and Tomás Cohen Arazi, with the help of the koha-es community.
            • +
            • Svenska (Swedish)
            • +
            • Tetun (Tetum) Karen Myers
            • +
            • ภาษาไทย (Thai)
            • +
            • Türkçe (Turkish) pre-3.8: Selma Aslan; for 3.8+, Suleyman Demirel University (Ugur Bulgan, Onur Erdem, Kemal Caner Bayrakci, and Alper Tutunsatar)
            • +
            • اردو(Urdu) Ata ur Rehman
            • +
            • Українська (Ukrainian) Victor Titarchuk and Serhij Dubyk
            • +
            + [% END #tab=translations %] + [% END %] + + [% BLOCK history_panel %] + [% WRAPPER tab_panel tabname= "history" bt_active = 1 %] +

            Koha history timeline

            + [% IF ! timeline_read_error %] + + + + + + + + [% FOREACH tabl IN table2 %] + + [% FOREACH ro IN tabl.row2 %] + + + [% END %] + + [% END %] +
            DateDescription
            [% ro.date | html %][% ro.desc | html %]
            + [% ELSE %] +
            Could not read the history.txt file. Please make sure <docdir> is correctly defined in koha-conf.xml.
            + [% END %] [% END %] [% END %] -[% END %] -[% BLOCK dedications_panel %] - [% WRAPPER tab_panel tabname= "dedications" bt_active = 1 %] -

            22.11

            -

            - The Koha Community would like to dedicate the release of Koha 22.11 to Rosalie Blake. -

            -

            - Rosalie was the Head Librarian at Horowhenua Library Trust when Koha was started and without her Koha - would not exist. She was an inspiring leader and innovator and took the risk of her career entrusting - Chris, Joanne, Rachel and Simon to deliver the original project that became the international sensation - we all know and love. -

            -

            - She was also a practicing Justice of the Peace, a stalwart of the Levin Pottery Club and much loved - mother of Simon and Jeremy, and grandmother of Ben, Toby, Anna, Charlotte and Billy. -

            - [% END # tab=dedications %] -[% END %] + [% BLOCK dedications_panel %] + [% WRAPPER tab_panel tabname= "dedications" bt_active = 1 %] +

            22.11

            +

            The Koha Community would like to dedicate the release of Koha 22.11 to Rosalie Blake.

            +

            + Rosalie was the Head Librarian at Horowhenua Library Trust when Koha was started and without her Koha would not exist. She was an inspiring leader and innovator and took the risk of her career entrusting Chris, Joanne, + Rachel and Simon to deliver the original project that became the international sensation we all know and love. +

            +

            She was also a practicing Justice of the Peace, a stalwart of the Levin Pottery Club and much loved mother of Simon and Jeremy, and grandmother of Ben, Toby, Anna, Charlotte and Billy.

            + [% END # tab=dedications %] + [% END %] + diff --git a/t/mock_templates/intranet-tmpl/prog/fr-CA/includes/accounts.inc b/t/mock_templates/intranet-tmpl/prog/fr-CA/includes/accounts.inc index b8376d3032..6c71cc99e4 100644 --- a/t/mock_templates/intranet-tmpl/prog/fr-CA/includes/accounts.inc +++ b/t/mock_templates/intranet-tmpl/prog/fr-CA/includes/accounts.inc @@ -1,61 +1,102 @@ [%- BLOCK account_type_description -%] - [%- IF account.credit_type_code -%] - [%- PROCESS credit_type_description credit_type = account.credit_type -%] - [%- ELSIF account.debit_type_code -%] - [%- PROCESS debit_type_description debit_type = account.debit_type -%] - [%- END -%] - [%- PROCESS account_status_description account=account -%] + [%- IF account.credit_type_code -%] + [%- PROCESS credit_type_description credit_type = account.credit_type -%] + [%- ELSIF account.debit_type_code -%] + [%- PROCESS debit_type_description debit_type = account.debit_type -%] + [%- END -%] + [%- PROCESS account_status_description account=account -%] [%- END -%] [%- BLOCK debit_type_description -%] - [%- SWITCH debit_type.code -%] - [%- CASE 'ACCOUNT' -%]Frais d'abonnement - [%- CASE 'ACCOUNT_RENEW' -%]Frais de renouvellement d'abonnement - [%- CASE 'ARTICLE_REQUEST' -%]Frais de demande d'article - [%- CASE 'LOST' -%]Document perdu - [%- CASE 'MANUAL' -%]Frais manuel - [%- CASE 'NEW_CARD' -%]Nouvelle carte - [%- CASE 'OVERDUE' -%]Amende - [%- CASE 'PROCESSING' -%]Frais de traitement pour exemplaire perdu - [%- CASE 'RENT' -%]Frais de location - [%- CASE 'RENT_DAILY' -%]Frais quotidien de location - [%- CASE 'RENT_RENEW' -%]Renouvellement d'une location - [%- CASE 'RENT_DAILY_RENEW' -%]Renouvellement d'une location quotidienne - [%- CASE 'RESERVE' -%]Frais de réservation - [%- CASE 'RESERVE_EXPIRED' -%]Réservation en attente depuis trop longtemps - [%- CASE 'PAYOUT' -%]Paiement de la bibliothèque à l'utilisateur - [%- CASE 'VOID' -%]Le crédit a été annulé - [%- CASE -%][% debit_type.description | html %] - [%- END -%] + [%- SWITCH debit_type.code -%] + + [%- CASE 'ACCOUNT' -%] + Frais d'abonnement + [%- CASE 'ACCOUNT_RENEW' -%] + Frais de renouvellement d'abonnement + [%- CASE 'ARTICLE_REQUEST' -%] + Frais de demande d'article + [%- CASE 'LOST' -%] + Document perdu + [%- CASE 'MANUAL' -%] + Frais manuel + [%- CASE 'NEW_CARD' -%] + Nouvelle carte + [%- CASE 'OVERDUE' -%] + Amende + [%- CASE 'PROCESSING' -%] + Frais de traitement pour exemplaire perdu + [%- CASE 'RENT' -%] + Frais de location + [%- CASE 'RENT_DAILY' -%] + Frais quotidien de location + [%- CASE 'RENT_RENEW' -%] + Renouvellement d'une location + [%- CASE 'RENT_DAILY_RENEW' -%] + Renouvellement d'une location quotidienne + [%- CASE 'RESERVE' -%] + Frais de réservation + [%- CASE 'RESERVE_EXPIRED' -%] + Réservation en attente depuis trop longtemps + [%- CASE 'PAYOUT' -%] + Paiement de la bibliothèque à l'utilisateur + [%- CASE 'VOID' -%] + Le crédit a été annulé + [%- CASE -%] + [% debit_type.description | html %] + [%- END -%] [%- END -%] [%- BLOCK credit_type_description -%] - [%- SWITCH credit_type.code -%] - [%- CASE 'CANCELLATION' -%]Frais annulé - [%- CASE 'CREDIT' -%]Crédit - [%- CASE 'DISCOUNT' -%]Rabais - [%- CASE 'FORGIVEN' -%]Amnistié - [%- CASE 'LOST_FOUND' -%]Remboursement de frais d'exemplaire perdu - [%- CASE 'OVERPAYMENT' -%]Remboursement pour paiement en trop - [%- CASE 'PAYMENT' -%]Paiement - [%- CASE 'PROCESSING_FOUND' -%]Remboursement de frais d'administration pour document perdu - [%- CASE 'PURCHASE' -%]Achat - [%- CASE 'REFUND' -%]Remboursement - [%- CASE 'WRITEOFF' -%]Amnistie - [%- CASE -%][% credit_type.description | html %] - [%- END -%] + [%- SWITCH credit_type.code -%] + + [%- CASE 'CANCELLATION' -%] + Frais annulé + [%- CASE 'CREDIT' -%] + Crédit + [%- CASE 'DISCOUNT' -%] + Rabais + [%- CASE 'FORGIVEN' -%] + Amnistié + [%- CASE 'LOST_FOUND' -%] + Remboursement de frais d'exemplaire perdu + [%- CASE 'OVERPAYMENT' -%] + Remboursement pour paiement en trop + [%- CASE 'PAYMENT' -%] + Paiement + [%- CASE 'PROCESSING_FOUND' -%] + Remboursement de frais d'administration pour document perdu + [%- CASE 'PURCHASE' -%] + Achat + [%- CASE 'REFUND' -%] + Remboursement + [%- CASE 'WRITEOFF' -%] + Amnistie + [%- CASE -%] + [% credit_type.description | html %] + [%- END -%] [%- END -%] [%- BLOCK account_status_description -%] - [%- SWITCH account.status -%] - [%- CASE 'UNRETURNED' -%] (En accumulation) - [%- CASE 'RETURNED' -%] (Retourné) - [%- CASE 'REPLACED' -%] (Remplacé) - [%- CASE 'REFUNDED' -%] (Remboursé) - [%- CASE 'FORGIVEN' -%] (Amnistié) - [%- CASE 'VOID' -%] (Annulé) - [%- CASE 'LOST' -%] (Perdu) - [%- CASE 'CANCELLED' -%] (Annulé) - [%- CASE -%] - [%- END -%] + [%- SWITCH account.status -%] + + [%- CASE 'UNRETURNED' -%] + (En accumulation) + [%- CASE 'RETURNED' -%] + (Retourné) + [%- CASE 'REPLACED' -%] + (Remplacé) + [%- CASE 'REFUNDED' -%] + (Remboursé) + [%- CASE 'FORGIVEN' -%] + (Amnistié) + [%- CASE 'VOID' -%] + (Annulé) + [%- CASE 'LOST' -%] + (Perdu) + [%- CASE 'CANCELLED' -%] + (Annulé) + [%- CASE -%] + + [%- END -%] [%- END -%] diff --git a/t/mock_templates/intranet-tmpl/prog/fr-CA/modules/about.tt b/t/mock_templates/intranet-tmpl/prog/fr-CA/modules/about.tt index c364ebcdb8..ef18afbe05 100644 --- a/t/mock_templates/intranet-tmpl/prog/fr-CA/modules/about.tt +++ b/t/mock_templates/intranet-tmpl/prog/fr-CA/modules/about.tt @@ -6,10 +6,12 @@ [% PROCESS 'i18n.inc' %] [% SET footerjs = 1 %] [% INCLUDE 'doc-head-open.inc' %] -[% FILTER collapse %] - [% t("About Koha") | html %] › - [% t("Koha") | html %] -[% END %] +[% FILTER collapse %] + [% t("About Koha") | html %] + › [% t("Koha") | html %] + [% END %] [% INCLUDE 'doc-head-close.inc' %] @@ -33,1300 +35,1187 @@ [% WRAPPER tabs id= "abouttabs" %] [% WRAPPER tabs_nav %] - [% WRAPPER tab_item linktab = 1 tabname = "about" bt_active = tab == "about" %] Server information [% END %] - [% WRAPPER tab_item linktab = 1 tabname = "perl" bt_active = tab == "perl" %] Perl modules [% END %] - [% WRAPPER tab_item linktab = 1 tabname = "sysinfo" bt_active = tab == "sysinfo" %] System information [% END %] - [% WRAPPER tab_item linktab = 1 tabname = "team" bt_active = tab == "team" %] Koha team [% END %] - [% WRAPPER tab_item linktab = 1 tabname = "licenses" bt_active = tab == "licenses" %] Licenses [% END %] - [% WRAPPER tab_item linktab = 1 tabname = "translations" bt_active = tab == "translations" %] Translations [% END %] - [% WRAPPER tab_item linktab = 1 tabname = "history" bt_active = tab == "history" %] Timeline [% END %] - [% WRAPPER tab_item linktab = 1 tabname = "dedications" bt_active = tab == "dedications" %] Dedications [% END %] + [% WRAPPER tab_item linktab = 1 tabname = "about" bt_active = tab == "about" %]Server information[% END %] + [% WRAPPER tab_item linktab = 1 tabname = "perl" bt_active = tab == "perl" %]Perl modules[% END %] + [% WRAPPER tab_item linktab = 1 tabname = "sysinfo" bt_active = tab == "sysinfo" %]System information[% END %] + [% WRAPPER tab_item linktab = 1 tabname = "team" bt_active = tab == "team" %]Koha team[% END %] + [% WRAPPER tab_item linktab = 1 tabname = "licenses" bt_active = tab == "licenses" %]Licenses[% END %] + [% WRAPPER tab_item linktab = 1 tabname = "translations" bt_active = tab == "translations" %]Translations[% END %] + [% WRAPPER tab_item linktab = 1 tabname = "history" bt_active = tab == "history" %]Timeline[% END %] + [% WRAPPER tab_item linktab = 1 tabname = "dedications" bt_active = tab == "dedications" %]Dedications[% END %] [% END %] [% WRAPPER tab_panels %] [% SWITCH tab %] - [% CASE 'about' %] [% PROCESS about_panel %] - [% CASE 'perl' %] [% PROCESS perl_panel %] - [% CASE 'sysinfo' %] [% PROCESS sysinfo_panel %] - [% CASE 'team' %] [% PROCESS team_panel %] - [% CASE 'licenses' %] [% PROCESS licenses_panel %] - [% CASE 'translations' %] [% PROCESS translations_panel %] - [% CASE 'history' %] [% PROCESS history_panel %] - [% CASE 'dedications' %] [% PROCESS dedications_panel %] - [% CASE %] [% PROCESS about_panel %] + [% CASE 'about' %] + [% PROCESS about_panel %] + [% CASE 'perl' %] + [% PROCESS perl_panel %] + [% CASE 'sysinfo' %] + [% PROCESS sysinfo_panel %] + [% CASE 'team' %] + [% PROCESS team_panel %] + [% CASE 'licenses' %] + [% PROCESS licenses_panel %] + [% CASE 'translations' %] + [% PROCESS translations_panel %] + [% CASE 'history' %] + [% PROCESS history_panel %] + [% CASE 'dedications' %] + [% PROCESS dedications_panel %] + [% CASE %] + [% PROCESS about_panel %] [% END %] [% END %] [% END # /WRAPPER abouttabs %] - - - -[% INCLUDE 'intranet-bottom.inc' %] + + + + + + [% INCLUDE 'intranet-bottom.inc' %] -[% BLOCK about_panel %] - [% WRAPPER tab_panel tabname= "about" bt_active = 1 %] - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - [% IF (is_psgi) %] + [% BLOCK about_panel %] + [% WRAPPER tab_panel tabname= "about" bt_active = 1 %] +
            Server information
            Koha version: [% kohaVersion | html %][% IF kohaCodename %] [% kohaCodename | html %][% END %]
            OS version ('uname -a'): [% osVersion | html %]
            Perl interpreter: [% perlPath | html %]
            Perl version: [% perlVersion | html %]
            Perl @INC: - [% FOREACH perlIncPat IN perlIncPath %] - [% perlIncPat.perlinc | html %]
            - [% END %] -
            MySQL version: [% mysqlVersion | html %]
            Apache version: [% apacheVersion | html %]
            + - - + + - [% END %] - [% IF Koha.Preference('SearchEngine') == 'Elasticsearch' %] - - [% IF elasticsearch_fatal_config_error %] - - [% ELSE %] - + + + + + + + + + + + + + + + + + + + + + + + [% IF (is_psgi) %] + + + + + [% END %] + [% IF Koha.Preference('SearchEngine') == 'Elasticsearch' %] + + + [% IF elasticsearch_fatal_config_error %] + + [% ELSE %] + + [% END # /IF elasticsearch_fatal_config_error %] + + [% END %] + + + - [% END # /IF elasticsearch_fatal_config_error %] - - [% END %] - - - - - - - - - - - [% IF (errZebraConnection == 10000) %] - - [% ELSIF (errZebraConnection) %] - - [% ELSE %] - - [% END %] - - - - [% IF warnConnectBroker %] - - [% ELSE %] - - [% END %] - - - - - - - [% timezone_config_class = (time_zone.config_invalid) ? 'bg-warning' : '' %] - [% timezone_env_class = (time_zone.env_invalid) ? 'bg-warning' : '' %] - - - -
            Server information
            PSGI: [% psgi_server | html %]Koha version: [% kohaVersion | html %][% IF kohaCodename %][% kohaCodename | html %][% END %]
            Elasticsearch: [% elasticsearch_fatal_config_error | html %] - Version: - [% elasticsearch_status.version | html %] - | - Nodes: - [% elasticsearch_status.nodes.join(' / ') | html %] - | - Status: - [% IF elasticsearch_status.running %] - running - | - Indices: - [% FOREACH index IN elasticsearch_status.indexes %] - [% index.index_name | html %] - (count: [% index.index_count | html %]) - [% UNLESS loop.last %], [% END %] + OS version ('uname -a'): [% osVersion | html %]
            Perl interpreter: [% perlPath | html %]
            Perl version: [% perlVersion | html %]
            Perl @INC: + [% FOREACH perlIncPat IN perlIncPath %] + [% perlIncPat.perlinc | html %]
            + [% END %] +
            MySQL version: [% mysqlVersion | html %]
            Apache version: [% apacheVersion | html %]
            PSGI: [% psgi_server | html %]
            Elasticsearch: [% elasticsearch_fatal_config_error | html %] + Version: + [% elasticsearch_status.version | html %] + | + Nodes: + [% elasticsearch_status.nodes.join(' / ') | html %] + | + Status: + [% IF elasticsearch_status.running %] + running + | + Indices: + [% FOREACH index IN elasticsearch_status.indexes %] + [% index.index_name | html %] + (count: [% index.index_count | html %]) [% UNLESS loop.last %],[% END %] + [% END %] + [% ELSE %] + not running + [% END %] +
            Memcached: + Servers: + [% IF memcached_servers %] + [% memcached_servers | html %] + [% ELSE %] + undefined + [% END %] + | + Namespace: + [% IF memcached_namespace %] + [% memcached_namespace | html %] + [% ELSE %] + undefined + [% END %] + | + Status: + [% IF memcached_servers %] + [% IF memcached_running and is_memcached_still_active %] + running. + [% ELSE %] + not running. + [% IF is_psgi %] + Remember memcached needs to be started before Plack. + [% END %] [% END %] [% ELSE %] - not running + unknown [% END %] -
            Memcached: - Servers: - [% IF memcached_servers %] - [% memcached_servers | html %] - [% ELSE %] - undefined - [% END %] | - Namespace: - [% IF memcached_namespace %] - [% memcached_namespace | html %] - [% ELSE %] - undefined - [% END %] | - Status: - [% IF memcached_servers %] - [% IF memcached_running and is_memcached_still_active %] - running. - [% ELSE %] - not running. - [% IF is_psgi %] - Remember memcached needs to be started before Plack. - [% END %] - [% END %] - [% ELSE %] - unknown - [% END %] | - Config read from: - [% SWITCH where_is_memcached_config %] + | + Config read from: + [% SWITCH where_is_memcached_config %] [% CASE 'config_only' %] koha-conf.xml [% CASE 'ENV_only' %] ENV Note that the right place to define the memcached config is in your $KOHA_CONF file [% CASE 'both' %] - ENV and koha-conf.xml Note that the right place to define the memcached config is in your $KOHA_CONF file. To avoid any misunderstanding you should not export the memcached config from ENV. + ENV and koha-conf.xml + Note that the right place to define the memcached config is in your $KOHA_CONF file. To avoid any misunderstanding you should not export the memcached config from ENV. [% CASE # nowhere %] Nowhere Note that the right place to define the memcached config is in your $KOHA_CONF file. Currently you do not have a valid memcached configuration defined. - [% END %] - [% IF effective_caching_method != 'Cache::Memcached::Fast::Safe' %] - | Effective caching method: [% effective_caching_method | html %] - [% END %] -
            Zebra version: [% zebraVersion | html %]
            Zebra status: Zebra server seems not to be available. Is it started?Error message from Zebra: [% ( errZebraConnection ) | html %]Running
            Message broker: Using SQL pollingUsing RabbitMQ
            Date and time: [% current_date_and_time | $KohaDates with_hours => 1 %]
            Time zone: - Used: [% time_zone.actual | html %] - [% IF time_zone.actual_bad_tz_fallback %] - (This is a fallback value due to a bad configuration) - [% END %] - | - Config: - [% IF time_zone.config != '' %] - [% time_zone.config | html %] - [% ELSE %] - Undefined - [% END %] | - Environment (TZ): - [% IF time_zone.environment != '' %] - [% time_zone.environment | html %] - [% ELSE %] - Undefined - [% END %] -
            - [% END # tab=about %] -[% END %] - -[% BLOCK perl_panel %] - [% WRAPPER tab_panel tabname= "perl" bt_active = 1 %] - - - [% FOREACH tabl IN table %] - - [% FOREACH ro IN tabl.row %] - [% IF ( ro.require ) %] - [% SET th_font_weight = "bold" %] - [% ELSE %] - [% SET th_font_weight = "normal" %] [% END %] - [% IF ( ro.current ) %] - [% SET th_title = t("Module current") %] - [% ELSIF ( ro.upgrade ) %] - [% SET th_background_color = "#FFCB2F" %] - [% SET th_title = t("Module upgrade needed") %] - [% ELSE %] - [% IF ( ro.require ) %] - [% SET th_background_color = "#FF8A8A" %] - [% SET th_title = t("Required module missing") %] - [% ELSIF ( ro.name != '' ) %] - [% SET th_background_color = "#FF8A8A" %] - [% SET th_title = t("Optional module missing") %] - [% END %] - [% END # /IF ro.current %] - - [% IF ( ro.name == '' ) %] - - [% ELSIF ( ro.version ) %] - - [% ELSE %] - - [% END %] - [% END # /FOREACH ro %] + - [% END # /FOREACH tabl %] -
            Perl modules
            - [% IF ( ro.name ) %] - [% ro.name | html %] - - ([% ro.reqversion | html %] - [% IF ro.maxversion %] - [% ro.maxversion | html %][% END %] - [% IF ro.excversion %][% FOR v IN ro.excversion %], ![% v | html %][% END %][% END %]) - + [% IF effective_caching_method != 'Cache::Memcached::Fast::Safe' %] + | Effective caching method: [% effective_caching_method | html %] [% END %] - [% ro.version | html %]Not Installed
            - [% END # tab=perl %] -[% END %] - -[% BLOCK sysinfo_panel %] - [% IF Asset.css("css/staff-global.css") == "" || Asset.js("js/vue/dist/erm.js") == "" %] - [% SET warnMissingCompiledFiles = 1 %] - [% END %] - [% WRAPPER tab_panel tabname= "sysinfo" bt_active = 1 %] - [% IF weasyprint_missing || warnPrefRequireChoosingExistingAuthority || warnPrefEasyAnalyticalRecords || warnPrefAnonymousPatronOPACPrivacy || warnPrefAnonymousPatronAnonSuggestions || warnPrefAnonymousPatronOPACPrivacy_PatronDoesNotExist || warnPrefAnonymousPatronAnonSuggestions_PatronDoesNotExist || warnPrefKohaAdminEmailAddress || warnPrefOpacHiddenItems || warnPrefPatronSelfRegistrationDefaultCategory || invalid_yesno.count || warnNoActiveCurrency || warnIsRootUser || xml_config_warnings.size || warnI18nMissing || AutoSelfCheckPatronDoesNotHaveSelfCheckPerm || AutoSelfCheckPatronHasTooManyPerm || warnStatisticsFieldsError || warnNoTemplateCaching || warnILLConfiguration || has_ai_issues || oauth2_missing_deps || bad_yaml_prefs || warnRelationships || log4perl_errors || config_bcrypt_settings_no_set || warnHiddenBiblionumbers.size || warnConnectBroker || elasticsearch_has_missing || warnMissingCompiledFiles || warnDbRowFormat %] - [% IF ( warnDbRowFormat ) %] -

            Database row format incorrect

            -

            Database tables with a row format other than 'DYNAMIC': [% warnDbRowFormat | html %]

            -

            You may experience problems upgrading to newer versions of Koha unless you update the row format for your database tables.

            -

            To know how to avoid this problem see the related wiki page: - Database row format -

            - [% END %] - - [% IF (warnIsRootUser) %] -

            Warning regarding current user

            -

            You are logged in as the database administrative user. This is not recommended because some parts of Koha will not function as expected when using this account.

            -

            Please log in instead with a regular staff account. To create a staff account, create a library, a patron category 'Staff' and add a new patron. Then give this patron permissions from 'More' in the toolbar.

            - [% END # /IF warnIsRootUser %] - - [% IF has_ai_issues %] -

            Data problems

            -

            - Some of your tables have problems with their auto_increment values which may lead to data loss. -

            -

            - You should not ignore this warning. -

            -

            - The problem is that InnoDB does not keep auto_increment across SQL server restarts (it is only set in memory). So on server startup the auto_increment values are set to max(table.id)+1. -

            -

            To know how to avoid this problem see the related wiki page: - DBMS auto increment fix -

            - -

            Problems found

            - [% IF ai_patrons %] -

            Patrons

            -

            The following IDs exist in both tables [% "borrowers" | $HtmlTags tag="strong" %] and [% "deletedborrowers" | $HtmlTags tag="strong" %]:

            -

            - [% FOR p IN ai_patrons %] - [% p.borrowernumber | html %] - [% UNLESS loop.last %], [% END %] - [% END %] -

            - [% END %] - [% IF ai_biblios %] -

            Bibliographic records

            -

            The following IDs exist in both tables [% "biblio" | $HtmlTags tag="strong" %] and [% "deletedbiblio" | $HtmlTags tag="strong" %]:

            -

            - [% FOR b IN ai_biblios %] - [% b.biblionumber | html %] - [% UNLESS loop.last %], [% END %] - [% END %] -

            - [% END %] - [% IF ai_biblioitems %] -

            Bibliographic records

            -

            The following IDs exist in both tables [% "biblio" | $HtmlTags tag="strong" %] and [% "deletedbiblioitems" | $HtmlTags tag="strong" %]:

            -

            - [% FOR b IN ai_biblioitems %] - [% b.biblioitemnumber | html %] - [% UNLESS loop.last %], [% END %] - [% END %] -

            - [% END %] - [% IF ai_items %] -

            Items

            -

            The following IDs exist in both tables [% "items" | $HtmlTags tag="strong" %] and [% "deleteditems" | $HtmlTags tag="strong" %]:

            -

            - [% FOR i IN ai_items %] - [% i.itemnumber | html %] - [% UNLESS loop.last %], [% END %] - [% END %] -

            - [% END %] - [% IF ai_checkouts %] -

            Checkouts

            -

            The following IDs exist in both tables [% "issues" | $HtmlTags tag="strong" %] and [% "old_issues" | $HtmlTags tag="strong" %]:

            -

            - [% FOR c IN ai_checkouts %] - [% c.issue_id | html %] - [% UNLESS loop.last %], [% END %] - [% END %] -

            - [% END %] - [% IF ai_holds %] -

            Holds

            -

            The following IDs exist in both tables [% "reserves" | $HtmlTags tag="strong" %] and [% "old_reserves" | $HtmlTags tag="strong" %]:

            -

            - [% FOR h IN ai_holds %] - [% h.reserve_id | html %] - [% UNLESS loop.last %], [% END %] - [% END %] -

            - [% END %] -
            - [% END # /IF has_ai_issues %] - - [% IF warnRelationships %] -

            Patron relationship problems

            - [% IF bad_relationships_count %] -

            Your database contained guarantee/guarantor pairs with no defined relationship. They have been set the value '_bad_data' in the [% "borrowers.relationship" | $HtmlTags tag="strong" %] and/or [% "borrower_relationships.relationship" | $HtmlTags tag="strong" %] columns. Fix them manually by recreating those relationships, or have your system's administrator correct the values.

            - [% END # /IF bad_relationships_count %] - - [% IF wrong_relationships %] -

            The following values have been used for guarantee/guarantor relationships, but do not exist in the 'borrowerRelationship' system preference:

            -
              - [% FOR rel IN wrong_relationships %] -
            • [% rel.0 | html %]
            • - [% END %] -
            -

            If the relationship is one you want, please add it to the 'borrowerRelationship' system preference, otherwise have your system's administrator correct the values in [% "borrowers.relationship" | $HtmlTags tag="strong" %] and/or [% "borrower_relationships.relationship" | $HtmlTags tag="strong" %] in the database.

            - [% END # /IF wrong_relationships %] - [% END # /IF warnRelationships %] - - [% IF log4perl_errors %] -

            Logging system does not behave correctly

            - [% FOR e IN log4perl_errors %] - [% SWITCH e %] - [% CASE 'missing_config_entry' %]There is no 'log4perl_conf' entry in the config file. - [% CASE 'cannot_read_config_file' %]The log4perl config file cannot be opened. - [% CASE 'logfile_not_writable' %]One of the logfiles listed in the config file is not writable. - [% CASE 'cannot_init_module' %]The Koha::Logger module cannot be initiated correctly (check the log file). - [% CASE %]Unknown error '[% e | html %]'. - [% END %] - [% END # /FOR e %] - [% END # /IF log4perl_errors %] - - [% IF warnConnectBroker %] -

            Impossible to connect to the message broker

            - There is an error when trying to connect to the message broker (RabbitMQ), check the Koha log files. -
            - Maybe it is not installed and configured correctly? -
            - Contact your system administrator. - [% END # /IF warnConnectBroker %] - - [% IF weasyprint_missing || warnPrefRequireChoosingExistingAuthority || warnPrefEasyAnalyticalRecords || warnPrefAnonymousPatronOPACPrivacy || warnPrefAnonymousPatronAnonSuggestions || warnPrefAnonymousPatronOPACPrivacy_PatronDoesNotExist || warnPrefAnonymousPatronAnonSuggestions_PatronDoesNotExist || warnPrefKohaAdminEmailAddress || warnPrefOpacHiddenItems || warnPrefPatronSelfRegistrationDefaultCategory || invalid_yesno.count || warnNoActiveCurrency || AutoSelfCheckPatronDoesNotHaveSelfCheckPerm || AutoSelfCheckPatronHasTooManyPerm || warnStatisticsFieldsError || warnNoTemplateCaching || warnILLConfiguration || warnXSLT || oauth2_missing_deps || bad_yaml_prefs || warnIssuingRules || config_bcrypt_settings_no_set || warnHiddenBiblionumbers.size || warnFastCataloging %] -

            Warnings regarding the system configuration

            - - - [% IF (warnFastCataloging) %] - - - - - [% END %] - [% IF (warnPrefRequireChoosingExistingAuthority) %] - - - - - [% END %] - [% IF (warnPrefEasyAnalyticalRecords) %] - - - - - [% END %] - [% IF warnPrefAnonymousPatronOPACPrivacy %] - - - - - [% END %] - [% IF warnPrefAnonymousPatronAnonSuggestions %] - - - - - [% END %] - [% IF warnPrefAnonymousPatronOPACPrivacy_PatronDoesNotExist %] - - - - - [% END %] - [% IF warnPrefAnonymousPatronAnonSuggestions_PatronDoesNotExist %] - - - - - [% END %] - [% IF warnPrefKohaAdminEmailAddress %] - - - - - [% END %] - [% IF warnPrefOpacHiddenItems %] - - - - [% END %] - [% IF warnPrefPatronSelfRegistrationDefaultCategory %] - - [% END %] - [% IF warnXSLT %] - [% FOR p IN warnXSLT %] - - - - [% END %] - [% END %] - [% IF invalid_yesno.count %] - [% FOR p IN invalid_yesno %] - - - - - [% END %] - [% END %] - [% IF warnNoActiveCurrency %] - - - - - [% END %] - [% IF warnStatisticsFieldsError %] - - - - - [% END %] - [% IF AutoSelfCheckPatronDoesNotHaveSelfCheckPerm %] - - - - - [% END %] - [% IF AutoSelfCheckPatronHasTooManyPerm %] - - - - - [% END %] - [% IF warnNoTemplateCaching %] - - - - - [% END %] - [% IF warnI18nMissing %] - - - - - [% END %] - [% IF warnILLConfiguration %] - [% IF no_ill_backends %] - - - - - [% END %] - [% IF ill_partner_code_not_defined %] - - - - - [% END %] - [% IF ill_partner_code_no_patrons %] - - - - - [% END %] - [% IF ill_branch_not_defined %] - - - - - [% END %] - [% IF ill_partner_code_doesnt_exist %] - - - - - [% END %] - [% END %] - - [% IF weasyprint_missing %] - - [% END %] - - [% IF oauth2_missing_deps %] - - - - - [% END %] - [% IF bad_yaml_prefs %] - - - - - [% END %] - [% IF config_bcrypt_settings_no_set %] - - - - - [% END %] - [% IF warnHiddenBiblionumbers.size %] - - - - - [% END %] - [% IF Koha.Preference('SearchEngine') == 'Elasticsearch' && elasticsearch_status.version.substr(0,1) < 6 %] - - - - - [% END %] -
            Preferences and parameters
            Warning There is no "Fast add" (FA) framework defined in administration->MARC frameworks. This disables the 'Fast cataloging' feature in cataloging/circulation.
            Warning System preference 'RequireChoosingExistingAuthority' is disabled, but needs 'AutoCreateAuthorities' enabled. Otherwise catalogers can add headings that will not be linked to authorities.
            Warning System preference 'EasyAnalyticalRecords' set, but UseControlNumber preference is set to 'Use'. Set it to 'Don't use' or else the 'Show analytics' links in the staff interface and the OPAC will be broken.
            Error System preference 'OPACPrivacy' set, but AnonymousPatron preference is set to '0'. Set it to a valid borrower number or checkins for these patrons will fail.
            Warning System preference 'AnonSuggestions' set, but AnonymousPatron preference is set to '0'. Set it to a valid borrower number if you want that this feature works correctly.
            Error Some patrons have requested privacy after their items are checked in, but the AnonymousPatron preference is not set correctly. Set it to a valid borrower number or checkins for these patrons will fail.
            Warning System preference 'AnonSuggestions' set, but AnonymousPatron preference is not set correctly. Set it to a valid borrower number if you want that this feature works correctly.
            Warning System preference 'KohaAdminEmailAddress' does not contain a valid email address. Emails will not be sent.
            Warning System preference 'OpacHiddenItems' generates a warning and will produce unexpected behaviors: [% warnPrefOpacHiddenItems | html %]
            Warning System preference 'PatronSelfRegistration' is set, but 'PatronSelfRegistrationDefaultCategory' does not contain a valid patron category code. Patron self-registration is disabled.
            Warning System preference '[% p.syspref | html %]' is '[% p.value | html %]', but the file '[% p.filename | html %]' does not exist.
            Warning System preference '[% p.variable | html %]' must be '0' or '1', but is [% IF p.value.defined %]'[% p.value | html%]'[% ELSE %]NULL[% END %].
            Warning No active currency is defined. Please go to Administration > Currencies and exchange rates and mark one currency as active.
            Warning System preference 'StatisticsFields' contains field names not belonging to the items database table: [% warnStatisticsFieldsError | html %]
            Warning - The patron used for the self checkout module at the OPAC does not have the self_check => self_checkout_module permission. -
            Warning - The patron used for the self checkout module at the OPAC has too many permissions. They should only have self_check => self_checkout_module. -
            Warning - You are missing the <template_cache_dir> entry in your koha-conf.xml file. - That will bring a performance boost to enable it. -
            Warning - The PO directory has not been found. See the dedicated wiki page for more information. -
            Warning - The ILL module is enabled, but there are no backends available. -
            Warning - The ILL module is enabled, but ILLPartnerCode system preference is empty. Falling back to the hardcoded 'IL'. -
            Warning - The ILL module is enabled and ILLPartnerCode system preference configured, but there are no patrons in [% ill_partner_code_no_patrons | html %] category. -
            Warning - The ILL module is enabled, but no 'branch' block is defined in koha-conf.xml. You must define this block before use. -
            Warning - The ILL module is enabled, but the configured ILLPartnerCode ([% ill_partner_code_doesnt_exist | html %]) is not defined on the system. -
            Warning - The weasyprint tool is not installed. -
            Warning - System preference 'RESTOAuth2ClientCredentials' is set, but the required Net::OAuth2::AuthorizationServer dependency is missing. The feature is disabled. -
            Warning - Some system preferences have badly formatted YAML content: [% bad_yaml_prefs.join(', ') | html %] -
            Warning - System preference 'Pseudonymization' is set, but there is not 'bcrypt_settings' entry defined in the $KOHA_CONF file. -
            Warning - [% FOR w IN warnHiddenBiblionumbers %] - Bibliographic framework "[% w.frameworkcode | html %]" has the biblionumber field hidden at the interface [% w.interface | html %]
            - [% END %] -
            Deprecation warning - Elasticsearch version 5.x is not supported in Koha 20.11 and greater. Please upgrade your Elasticsearch cluster -
            - [% END # /IF warnPrefRequireChoosingExistingAuthority %] - - [% IF xml_config_warnings.size %] - - - [% FOREACH config_entry IN xml_config_warnings %] - [% IF config_entry.error == 'zebra_bib_index_mode_is_grs1' %] - - - - - [% ELSIF config_entry.error == 'zebra_auth_index_mode_is_grs1' %] - - - - - [% ELSIF config_entry.error == 'use_zebra_facets_entry_missing' %] - - - - - [% ELSIF config_entry.error == 'log4perl_entry_missing' %] - - - - - [% ELSIF config_entry.error == 'lockdir_entry_missing' %] - - - - - [% ELSIF config_entry.error == 'lockdir_not_writable' %] - - - - - [% ELSIF config_entry.error == 'uploadpath_entry_missing' %] - - - - - [% ELSIF config_entry.error == 'uploadpath_and_opacbaseurl_entry_missing' %] - - - - - [% ELSIF config_entry.error == 'tmp_path_missing' %] - - - - - [% ELSIF config_entry.error == 'encryption_key_missing' %] - - - - - [% END # /IF config_entry.error %] - [% END # /FOREACH config_entry %] -
            XML configuration file
            Warning - The <zebra_bib_index_mode> entry set to 'grs1', which is no longer supported. - Please use DOM instead. To switch follow this page of wiki: - Switching to dom indexing -
            Warning - The <zebra_auth_index_mode> entry set to 'grs1', which is no longer supported. - Please use DOM instead. To switch follow this page of wiki: - Switching to dom indexing -
            Warning - The <use_zebra_facets> entry is missing in your configuration file. Falling back - to legacy facet calculation. -
            Warning - You are missing the <log4perl_conf> entry in your koha-conf.xml file. Please - add it, pointing to the log4perl.conf file for your Koha instance. -
            Warning - You are missing the <lockdir> entry in your koha-conf.xml file. Please - add it, pointing to your Koha instance's lock dir. -
            Warning - The configured <lockdir> entry in your koha-conf.xml file points to a - non-writable directory ([% config_entry.lockdir | html %]). -
            Warning - You are missing the <upload_path> entry in your koha-conf.xml file. Please - add it, pointing to the configured file upload directory for your Koha instance. -
            Warning - You are missing the <upload_path> entry in your koha-conf.xml file. Please - add it, pointing to the configured file upload directory for your Koha instance. - Also note that you need to properly set the OPACBaseURL preference for the file upload plugin to work. -
            Warning - You are missing the <tmp_path> entry in your koha-conf.xml file. Please - add it, pointing to the configured temporary directory for your Koha instance. - The effective temporary directory is '[% config_entry.effective_tmp_dir | html %]'. -
            Warning - You are missing the <encryption_key> entry in your koha-conf.xml file. - Please generate a key. We recommend one of at least 32 bytes. (You might use 'pwgen 32' to do so.) -
            - [% END # /IF xml_config_warnings.size %] - - [% IF warnIssuingRules %] - - - [% FOREACH unit IN ir_units %] - - - - - [% END # /FOREACH unit %] -
            Issuing rules
            Warning - The [% unit.branchcode || 'branchcode=default' | html %], [% unit.categorycode || 'categorycode=default' | html %], [% unit.itemtype || 'itemtype=default' | html %]issuingrule will fallback to 'days' for 'lengthunit' as it is incorrectly defined as [% unit.rule_value | html %]. -
            - [% END # /IF warnIssuingRules %] - - [% IF elasticsearch_has_missing %] - - - [% FOREACH index IN elasticsearch_status.indexes %] - [% IF index.missing_count %] - - - - - [% END %] - [% END %] -
            Records are not indexed in Elasticsearch
            Warning - [% index.missing_count | html %] record(s) missing on a total of [% index.index_count | html %] in index [% index.index_name | html %]. -
            - [% END # /IF elasticsearch_has_missing %] - - [% IF warnMissingCompiledFiles %] - Error - Compiled CSS and/or JS files are not present. Please run `yarn build` to generate them. - - [% END # /IF warnMissingCompiledFiles %] - - [% ELSE %] -

            No warnings.

            - [% END # /IF warnRequireChoosingExistingAuthority... %] - [% END # tab=sysinfo %] -[% END %] - -[% BLOCK team_panel %] - [% WRAPPER tab_panel tabname= "team" bt_active = 1 %] -

            Special thanks to the following organizations

            - - -

            Koha release teams

            - [% IF maintenance_team %] -
            -
            -

            Koha [% short_version | html %][% IF kohaCodename %] ([% kohaCodename | html %])[% END %] release team

            - [% IF development_version %] -

            You are running a development version of Koha

            + + Zebra version: + [% zebraVersion | html %] + + + Zebra status: + [% IF (errZebraConnection == 10000) %] + Zebra server seems not to be available. Is it started? + [% ELSIF (errZebraConnection) %] + Error message from Zebra: [% ( errZebraConnection ) | html %] [% ELSE %] - [% INCLUDE team t=release_team v='release' %] + Running [% END %] -
            - -
            -

            Current maintenance team

            - [% INCLUDE team t=maintenance_team v=short_version %] - [% IF development_version %] -
          • Release maintainers: -
              - [% FOREACH m IN maintenance_team.maintainer %] -
            • [% m.version | html %] - [% INCLUDE person p=m %]
            • - [% IF maintenance_team.maintainer_assistants %] - [% FOREACH ma IN maintenance_team.maintainer_assistants %] - [% IF ma.version == ( m.version ) %] -
              • Assistant: [% INCLUDE person p=ma %]
              - [% END %] - [% END %] - [% END %] - - [% IF maintenance_team.maintainer_mentors %] - [% FOREACH mm IN maintenance_team.maintainer_mentors %] - [% IF m.version == ( mm.version ) %] -
              • Mentor: [% INCLUDE person p=mm %]
              - [% END %] - [% END %] - [% END %] - [% END %] -
            -
          • + + + Message broker: + [% IF warnConnectBroker %] + Using SQL polling + [% ELSE %] + Using RabbitMQ [% END %] -
            -
            - [% ELSE %] -
            - Could not read the teams.yaml file. Please make sure <docdir> is correctly defined in koha-conf.xml. -
            - [% END # /maintenance_team %] - -

            Koha development team

            - [% IF contributors.size %] -
              - [% FOREACH contributor IN contributors %] -
            • [% INCLUDE person p=contributor %][% INCLUDE contributions p=contributor %]
            • - [% END %] -
            - [% ELSE %] -
            - Could not read the contributors.yaml file. Please make sure <docdir> is correctly defined in koha-conf.xml. -
            - [% END # /IF contributors.size %] -
            - -

            Contributing companies and institutions

            -
              -
            • Allen Ginsberg Library, USA
            • -
            • Alingsås Public Library, Sweden
            • -
            • American Numismatic Society, USA
            • -
            • Arcadia Public Library, USA
            • -
            • Athens County Public Libraries, USA
            • -
            • BdP de la Meuse, France
            • -
            • BibLibre, France
            • -
            • Biblioteca Provincial Fr. Mamerto Esquiú (Provincia Franciscana de la Asunción), Argentina
            • -
            • Bibliotheksservice-Zentrum Baden-Württemberg (BSZ), Germany
            • -
            • Briar Cliff University, USA
            • -
            • Brimbank City Council, Australia
            • -
            • Brooklyn Law School Library, USA
            • -
            • Bibliothèque Universitaire des Langues et Civilisations (BULAC), France
            • -
            • ByWater Solutions, USA
            • -
            • California College of the Arts, USA
            • -
            • Camden County, USA
            • -
            • Carnegie Stout Library, USA
            • -
            • Calyx, Australia
            • -
            • Catalyst IT, New Zealand
            • -
            • Central Kansas Library System (CKLS), USA
            • -
            • Centre collégial des services regroupés (CCSR), Canada
            • -
            • Cheshire Libraries, United Kingdom
            • -
            • Coeur d'Alene Public Library, USA
            • -
            • Corpus Christi Public Libraries, USA
            • -
            • C & P Bibliography Services, USA
            • -
            • Dataly Tech, Greece
            • -
            • Devinim, Turkey
            • -
            • Do Space, USA
            • -
            • DoverNet, USA
            • -
            • doXulting
            • -
            • Duchesne County Library, USA
            • -
            • Escuela de Orientacion Lacaniana, Argentina
            • -
            • Fenway Library Organization, USA
            • -
            • Fargo Public Library, USA
            • -
            • Farmington Public Library, USA
            • -
            • FIT
            • -
            • Foundations Bible College & Seminary, USA
            • -
            • Goethe-Institut, Germany
            • -
            • Gothenburg University Library, Sweden
            • -
            • Halland County Library, Sweden
            • -
            • Harrison Carmel Public Library, USA
            • -
            • Hauraki District Libraries, New Zealand
            • -
            • Higher Education Libraries of Massachusetts, USA
            • -
            • Hochschule für Gesundheit (hsg), Germany
            • -
            • Hotchkiss School, USA
            • -
            • Katipo Communications, New Zealand
            • -
            • KEEP SOLUTIONS, Portugal
            • -
            • KohaAloha, New Zealand
            • -
            • Koha-Suomi Oy, Finland
            • -
            • LibLime, USA
            • -
            • Library of the Józef Piłsudski Institute of America, USA
            • -
            • Libriotech, Norway
            • -
            • Los Gatos Public Library, USA
            • -
            • Lund University Library, Sweden
            • -
            • MassCat, USA
            • -
            • Middletown Township Public Library, USA
            • -
            • National Library of Finland, Finland
            • -
            • Newcastle City Council, United Kingdom
            • -
            • New Zealand Central Agencies Library, New Zealand
            • -
            • New Zealand Ministry of Education Library, New Zealand
            • -
            • North Central Regional Library (NCRL), USA
            • -
            • Northeast Kansas Library System (NEKLS), USA
            • -
            • OPUS
            • -
            • Orex Digital, Spain
            • -
            • Oslo Public Library, Norway
            • -
            • Plano Independent School, USA
            • -
            • Plant and Food Research Limited, New Zealand
            • -
            • Prosentient Systems, Australia
            • -
            • PTFS, Maryland, USA
            • -
            • PTFS Europe Ltd, United Kingdom
            • -
            • Rijksmuseum, Amsterdam, The Netherlands
            • -
            • Rolling Hills Consolidated Libraries, USA
            • -
            • Round Rock Public Library, USA
            • -
            • SAN-Ouest Provence, France
            • -
            • Sefton Council, United Kingdom
            • -
            • software.coop, United Kingdom
            • -
            • South-East Kansas Library System (SEKLS), USA
            • -
            • South Taranaki District Council, New Zealand
            • -
            • Stockholm University Library, Sweden
            • -
            • SWITCH Library Consortium, USA
            • -
            • Talking Tech, Global
            • -
            • Tamil, France
            • -
            • Theke Solutions, Argentina
            • -
            • Tulong Aklatan, Philippines
            • -
            • Uintah Library System, USA
            • -
            • Universidad de El Salvador, El Salvador
            • -
            • Universidad Empresarial Siglo 21, Argentina
            • -
            • Universidad Nacional de Córdoba, Argentina
            • -
            • Universidad ORT Uruguay
            • -
            • Université d'Aix-Marseille, France
            • -
            • Université de Lyon 3, France
            • -
            • Université de Rennes 2, France
            • -
            • Université de St Etienne, France
            • -
            • University of the Arts London, United Kingdom
            • -
            • Vaara-kirjastot, Finland
            • -
            • Vanier College, Canada
            • -
            • Vermont Organization of Koha Automated Libraries (VOKAL), USA
            • -
            • Ville de Victoriaville, Canada
            • -
            • Virginia Tech, USA
            • -
            • Washoe County Library System, USA
            • -
            • Xercode, Spain
            • -
            - -

            Additional thanks to...

            -
              -
            • Irma Birchall
            • -
            • Rachel Hamilton-Williams (Kaitiaki from 2004 to present)
            • -
            • Stephen Hedges (early Documentation Manager)
            • -
            • Brooke Johnson
            • -
            • Jo Ransom
            • -
            • Nicholas Rosasco (Documentation Compiler)
            • -
            • Regula Sebastiao
            • -
            - [% END # tab=team %] -[% END %] - -[% BLOCK licenses_panel %] - [% WRAPPER tab_panel tabname= "licenses" bt_active = 1 %] -

            Koha

            -

            - This program 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 3 of the License, or (at your option) any later version. -

            - -

            Bootstrap

            -

            - Bootstrap, Glyphicons Free: MIT License -

            - -

            Bootstrap Icons

            -

            - Bootstrap Icons: MIT License -

            - -

            Bridge Material Type Icon Set

            -

            - Bridge Material Type Icons Project: Creative Commons Attribution-ShareAlike 2.5 License -

            - -

            Chocolat.js

            -

            - Chocolat.js v1.1.2: GNU General Public License v3.0 -

            - -

            CodeMirror

            -

            - CodeMirror v5.40.2: MIT License -

            - -

            C3.js

            -

            - C3.js D3-based reusable chart library v0.4.11: MIT Licence -

            - -

            CSSLint

            -

            - CSSLint v0.9.8: License -

            - -

            D3

            -

            - D3 JavaScript library for visualizing data v3.5.17: ISC Licence -

            - -

            DataTables

            -

            - DataTables v.1.10.18: MIT Licence -

            - -

            Day.js

            -

            - Day.js v1.11.2: MIT License -

            - -

            Enquire.js

            -

            - Enquire.js v2.1.6: MIT License -

            - -

            FamFamFam icons

            -

            - FamFamFam Silk icons: Creative Commons Attribution 2.5 License -

            - -

            FileSaver.js

            -

            - FileSaver.js v2.0.4: MIT License - -

            Flatpicker

            -

            - Flatpickr v4.6.9: MIT License -

            - -

            Font Awesome

            -

            - Font Awesome v6.3.0: Creative Commons Attribution 4.0 International License, SIL Open Font License Version 1.1, MIT License -

            - -

            Font Face Observer

            -

            - Font Face Observer JavaScript library v2.3.0: BSD 2-Clause "Simplified" License -

            - -

            GreyBox

            -

            - GreyBox JavaScript Library v5.54: GNU Lesser General Public License, version 2.1 -

            - -

            HC Sticky

            -

            - HC Sticky JavaScript library v2.2.7: MIT License -

            - -

            Highlight

            -

            - Highlight jQuery Plugin v5.0: MIT License -

            - -

            HTMLHint

            -

            - HTMLHint v0.9.12: MIT License -

            - -

            Humanized Messages

            -

            - Humanized Messages v1.0: Apache License, Version 2.0 -

            - -

            JavaScript Cookie

            -

            - JavaScript Cookie v3.0.1: MIT License -

            - -

            JavaScript Diff Algorithm

            -

            - JavaScript Diff Algorithm: MIT License -

            - -

            jQuery, jQuery Migrate, and jQuery UI

            -

            - jQuery v3.6.0, jQuery Migrate, jQuery UI v1.13.2: MIT License -

            - -

            jQuery Bar Rating Plugin

            -

            - jQuery Bar Rating plugin v1.2.2: MIT License -

            - -

            jQuery Emojiarea Plugin

            -

            - Emojiarea plugin for jQuery: Apache License, Version 2.0 -

            - -

            jQuery insertAtCaret Plugin

            -

            - jQuery insertAtCaret Plugin v1.0 by the phpMyAdmin development team: GNU General Public License -

            - -

            jQuery jEditable

            -

            - jQuery jEditable: MIT Licence -

            - -

            jQuery jsTree Plugin

            -

            - jQuery jsTree Plugin v3.3.12: MIT License -

            - -

            jQuery Multiple Select Plugin

            -

            - jQuery Multiple Select plugin v1.6.0: MIT License -

            - -

            jQuery TableDnD Plugin

            -

            - Table drag and drop JQuery plugin: MIT License -

            - -

            jQuery Treetable Plugin

            -

            - jQuery Treetable Plugin 3.1.0: GNU General Public License v2.0, MIT License -

            - -

            jQuery Validation Plugin

            -

            - jQuery Validation Plugin v1.19.3: MIT License -

            - -

            JS-YAML

            -

            - JS-YAML v3.13.1: MIT License -

            - -

            JSHint

            -

            - JSHint v2.9.7: MIT License -

            - -

            JSZip

            -

            - JSZip JavaScript library v3.1.3: MIT License, GNU General Public License v3.0 -

            - -

            kjua

            -

            - kjua JavaScript library v0.6.0: MIT License -

            - -

            Leaflet

            -

            - Leaflet JavaScript library v1.0.3: BSD License -

            - -

            Noto fonts

            -

            - Noto: SIL Open Font License Version 1.1 -

            - -

            OAI XSLT stylesheet

            -

            - Adapted from the DSpace project: BSD License -

            - -

            OpenAPI 2.0 schema

            -

            - JSON Schema for Swagger 2.0 API: Apache License, Version 2.0, OpenAPI Initiative (OAI) -

            - -

            OpenJS Keyboard Shortcuts Library

            -

            - OpenJS keyboard shortcuts library: BSD License -

            - -

            RequireJS

            -

            - RequireJS JavaScript file and module loader v2.1.8: BSD License or MIT License -

            - -

            Select2

            -

            - Select2 library v4.0.13: Apache License, Version 2.0 or GNU General Public License v2.0 -

            - -

            Sortable

            -

            - Sortable JavaScript Library v1.15.0: MIT Licence -

            - -

            TinyMCE WYSIWYG Editor

            -

            - TinyMCE WYSIWYG editor v5.9.2: GNU Lesser General Public License v2.1 -

            - -

            Verovio

            -

            - Verovio: GNU General Public License v3.0, GNU Lesser General Public License v3.0 -

            - -

            Virtual Keyboard

            -

            - Virtual Keyboard v1.30.1: MIT Licence -

            - - [% END # tab=licenses %] -[% END %] - -[% BLOCK translations_panel %] - [% WRAPPER tab_panel tabname= "translations" bt_active = 1 %] -

            Translation

            -
              -
            • العربية (Arabic) Version 3.2 to 3.4, 3.16 & 3.18 by KnowledgeWare Technologies; Versions 3.6 to 3.14 by Arabic Koha support team: Karam Qubsi, Kouider Bounama, Sham Bajaa, Ghofran Alshami, Chrestian Aboud, Fatema Salem and Duaa Bazzazi. -
            • አማርኛ (Amharic) Getway II Ethiopia Co. (Yohannes Mulugeta (Team Leader), Tegene Assefa, Abiyot Bayou)
            • -
            • Armenian Tigran Zargaryan
            • -
            • Български (Bulgarian) Radoslav Kolev
            • -
            • euskara (Basque) Fernando Berrizbeitia, the librarians of Eima Katalogoa, Tabakalera International Contemporary Culture Centre, and Nere Erkiaga
            • -
            • বাংলা (Bengali) Parthasarathi Mukhopadhyay
            • -
            • 中文 (Chinese)
            • -
            • Hrvatski (Croatian)
            • -
            • čeština (Czech)
            • -
            • Dænsk (Danish)
            • -
            • Nederlands-Nederland (Dutch-The Netherlands) Ronald Wijlens, Saxion University
            • -
            • Nederlands-België (Dutch-Belgium)
            • -
            • English
            • -
            • suomi, suomen kieli (Finnish) Pasi Korkalo
            • -
            • Français (French) Kohala, Pascale Nalon (ENSMP), and many more
            • -
            • Galego (Galician) Ignacio Javier
            • -
            • Deutsch (German) Friedrich zur Hellen, Robert Hillig, Katrin Fischer, Beda Szukics, Mirko Tietgen and Marc Véron
            • -
            • ελληνικά (Greek, Modern [1453- ]) Koha Hellenic Users' Group (Georgia Katsarou, Dimitris Antonakis, Eugenios Papadopoulos), Theodoros Theodoropoulos, Panoraia Gaitanou and Kiriaki Roditi
            • -
            • עברית (Hebrew)
            • -
            • हिन्दी (Hindi)
            • -
            • Magyar (Hungarian)Agnes Imecs
            • -
            • Norsk Bokmål (Norwegian) Axel Bojer and Thomas Gramstad
            • -
            • Norsk Nynorsk (Norwegian) Unni Knutsen and Marit Kristine Ådland
            • -
            • (Indonesian)
            • -
            • Italiano (Italian) for 3.2: Zeno Tajoli, Pietro Gozzetti and Paolo Pozzan; for 3.4 and more: Zeno Tajoli, Stefano Bargioni, Paolo Bizzarri
            • -
            • 日本語 (Japanese)
            • -
            • 한국어 (Korean)
            • -
            • ಕನ್ನಡ (kannaḍa)
            • -
            • Latina (Latin)
            • -
            • Lao Anousak Anthony Souphavanh
            • -
            • Māori
            • -
            • മലയാളം (Malayalam)
            • -
            • فارسى (Persian)
            • -
            • ଓଡ଼ିଆ (ōṛiyā)
            • -
            • Polski (Polish)
            • -
            • Português (Portuguese)
            • -
            • Română (Romanian)
            • -
            • Русский (Russian) Victor Titarchuk and Serhij Dubyk
            • -
            • Español (Spanish) Bernardo González Kriegel, Héctor Castro and Tomás Cohen Arazi, with the help of the koha-es community.
            • -
            • Svenska (Swedish)
            • -
            • Tetun (Tetum) Karen Myers
            • -
            • ภาษาไทย (Thai)
            • -
            • Türkçe (Turkish) pre-3.8: Selma Aslan; for 3.8+, Suleyman Demirel University (Ugur Bulgan, Onur Erdem, Kemal Caner Bayrakci, and Alper Tutunsatar)
            • -
            • اردو(Urdu) Ata ur Rehman
            • -
            • Українська (Ukrainian) Victor Titarchuk and Serhij Dubyk
            • -
            - [% END #tab=translations %] -[% END %] - -[% BLOCK history_panel %] - [% WRAPPER tab_panel tabname= "history" bt_active = 1 %] -

            Koha history timeline

            - [% IF ! timeline_read_error %] - - - - - - - - [% FOREACH tabl IN table2 %] - - [% FOREACH ro IN tabl.row2 %] - - + + + + + + + [% timezone_config_class = (time_zone.config_invalid) ? 'bg-warning' : '' %] + [% timezone_env_class = (time_zone.env_invalid) ? 'bg-warning' : '' %] + + - [% END %] + | + Config: + [% IF time_zone.config != '' %] + [% time_zone.config | html %] + [% ELSE %] + Undefined + [% END %] + | + Environment (TZ): + [% IF time_zone.environment != '' %] + [% time_zone.environment | html %] + [% ELSE %] + Undefined + [% END %] + +
            DateDescription
            [% ro.date | html %][% ro.desc | html %]
            Date and time: [% current_date_and_time | $KohaDates with_hours => 1 %]
            Time zone: + Used: [% time_zone.actual | html %] + [% IF time_zone.actual_bad_tz_fallback %] + (This is a fallback value due to a bad configuration) [% END %] -
            - [% ELSE %] -
            - Could not read the history.txt file. Please make sure <docdir> is correctly defined in koha-conf.xml. -
            + [% END # tab=about %] + [% END %] + + [% BLOCK perl_panel %] + [% WRAPPER tab_panel tabname= "perl" bt_active = 1 %] + + + [% FOREACH tabl IN table %] + + [% FOREACH ro IN tabl.row %] + [% IF ( ro.require ) %] + [% SET th_font_weight = "bold" %] + [% ELSE %] + [% SET th_font_weight = "normal" %] + [% END %] + [% IF ( ro.current ) %] + [% SET th_title = t("Module current") %] + [% ELSIF ( ro.upgrade ) %] + [% SET th_background_color = "#FFCB2F" %] + [% SET th_title = t("Module upgrade needed") %] + [% ELSE %] + [% IF ( ro.require ) %] + [% SET th_background_color = "#FF8A8A" %] + [% SET th_title = t("Required module missing") %] + [% ELSIF ( ro.name != '' ) %] + [% SET th_background_color = "#FF8A8A" %] + [% SET th_title = t("Optional module missing") %] + [% END %] + [% END # /IF ro.current %] + + [% IF ( ro.name == '' ) %] + + [% ELSIF ( ro.version ) %] + + [% ELSE %] + + [% END %] + [% END # /FOREACH ro %] + + [% END # /FOREACH tabl %] +
            Perl modules
            + [% IF ( ro.name ) %] + [% ro.name | html %] + + ([% ro.reqversion | html %] + [% IF ro.maxversion %]- [% ro.maxversion | html %][% END %] + [% IF ro.excversion %][% FOR v IN ro.excversion %], ![% v | html %][% END %][% END %]) + + [% END %] + [% ro.version | html %]Not Installed
            + [% END # tab=perl %] + [% END %] + + [% BLOCK sysinfo_panel %] + [% IF Asset.css("css/staff-global.css") == "" || Asset.js("js/vue/dist/erm.js") == "" %] + [% SET warnMissingCompiledFiles = 1 %] + [% END %] + [% WRAPPER tab_panel tabname= "sysinfo" bt_active = 1 %] + [% IF weasyprint_missing || warnPrefRequireChoosingExistingAuthority || warnPrefEasyAnalyticalRecords || warnPrefAnonymousPatronOPACPrivacy || warnPrefAnonymousPatronAnonSuggestions || warnPrefAnonymousPatronOPACPrivacy_PatronDoesNotExist || warnPrefAnonymousPatronAnonSuggestions_PatronDoesNotExist || warnPrefKohaAdminEmailAddress || warnPrefOpacHiddenItems || warnPrefPatronSelfRegistrationDefaultCategory || invalid_yesno.count || warnNoActiveCurrency || warnIsRootUser || xml_config_warnings.size || warnI18nMissing || AutoSelfCheckPatronDoesNotHaveSelfCheckPerm || AutoSelfCheckPatronHasTooManyPerm || warnStatisticsFieldsError || warnNoTemplateCaching || warnILLConfiguration || has_ai_issues || oauth2_missing_deps || bad_yaml_prefs || warnRelationships || log4perl_errors || config_bcrypt_settings_no_set || warnHiddenBiblionumbers.size || warnConnectBroker || elasticsearch_has_missing || warnMissingCompiledFiles || warnDbRowFormat %] + [% IF ( warnDbRowFormat ) %] +

            Database row format incorrect

            +

            Database tables with a row format other than 'DYNAMIC': [% warnDbRowFormat | html %]

            +

            You may experience problems upgrading to newer versions of Koha unless you update the row format for your database tables.

            +

            To know how to avoid this problem see the related wiki page: + Database row format +

            + [% END %] + + [% IF (warnIsRootUser) %] +

            Warning regarding current user

            +

            You are logged in as the database administrative user. This is not recommended because some parts of Koha will not function as expected when using this account.

            +

            Please log in instead with a regular staff account. To create a staff account, create a library, a patron category 'Staff' and add a new patron. Then give this patron permissions from 'More' in the toolbar.

            + [% END # /IF warnIsRootUser %] + + [% IF has_ai_issues %] +

            Data problems

            +

            Some of your tables have problems with their auto_increment values which may lead to data loss.

            +

            + You should not ignore this warning. +

            +

            The problem is that InnoDB does not keep auto_increment across SQL server restarts (it is only set in memory). So on server startup the auto_increment values are set to max(table.id)+1.

            +

            To know how to avoid this problem see the related wiki page: + DBMS auto increment fix +

            + +

            Problems found

            + [% IF ai_patrons %] +

            Patrons

            +

            The following IDs exist in both tables [% "borrowers" | $HtmlTags tag="strong" %] and [% "deletedborrowers" | $HtmlTags tag="strong" %]:

            +

            + [% FOR p IN ai_patrons %] + [% p.borrowernumber | html %] + [% UNLESS loop.last %],[% END %] + [% END %] +

            + [% END %] + [% IF ai_biblios %] +

            Bibliographic records

            +

            The following IDs exist in both tables [% "biblio" | $HtmlTags tag="strong" %] and [% "deletedbiblio" | $HtmlTags tag="strong" %]:

            +

            + [% FOR b IN ai_biblios %] + [% b.biblionumber | html %] + [% UNLESS loop.last %],[% END %] + [% END %] +

            + [% END %] + [% IF ai_biblioitems %] +

            Bibliographic records

            +

            The following IDs exist in both tables [% "biblio" | $HtmlTags tag="strong" %] and [% "deletedbiblioitems" | $HtmlTags tag="strong" %]:

            +

            + [% FOR b IN ai_biblioitems %] + [% b.biblioitemnumber | html %] + [% UNLESS loop.last %],[% END %] + [% END %] +

            + [% END %] + [% IF ai_items %] +

            Items

            +

            The following IDs exist in both tables [% "items" | $HtmlTags tag="strong" %] and [% "deleteditems" | $HtmlTags tag="strong" %]:

            +

            + [% FOR i IN ai_items %] + [% i.itemnumber | html %] + [% UNLESS loop.last %],[% END %] + [% END %] +

            + [% END %] + [% IF ai_checkouts %] +

            Checkouts

            +

            The following IDs exist in both tables [% "issues" | $HtmlTags tag="strong" %] and [% "old_issues" | $HtmlTags tag="strong" %]:

            +

            + [% FOR c IN ai_checkouts %] + [% c.issue_id | html %] + [% UNLESS loop.last %],[% END %] + [% END %] +

            + [% END %] + [% IF ai_holds %] +

            Holds

            +

            The following IDs exist in both tables [% "reserves" | $HtmlTags tag="strong" %] and [% "old_reserves" | $HtmlTags tag="strong" %]:

            +

            + [% FOR h IN ai_holds %] + [% h.reserve_id | html %] + [% UNLESS loop.last %],[% END %] + [% END %] +

            + [% END %] +
            + [% END # /IF has_ai_issues %] + + [% IF warnRelationships %] +

            Patron relationship problems

            + [% IF bad_relationships_count %] +

            Your database contained guarantee/guarantor pairs with no defined relationship. They have been set the value '_bad_data' in the [% "borrowers.relationship" | $HtmlTags tag="strong" %] and/or + [% "borrower_relationships.relationship" | $HtmlTags tag="strong" %] columns. Fix them manually by recreating those relationships, or have your system's administrator correct the values.

            + [% END # /IF bad_relationships_count %] + + [% IF wrong_relationships %] +

            The following values have been used for guarantee/guarantor relationships, but do not exist in the 'borrowerRelationship' system preference:

            +
              + [% FOR rel IN wrong_relationships %] +
            • [% rel.0 | html %]
            • + [% END %] +
            +

            If the relationship is one you want, please add it to the 'borrowerRelationship' system preference, otherwise have your system's administrator correct the values in + [% "borrowers.relationship" | $HtmlTags tag="strong" %] and/or [% "borrower_relationships.relationship" | $HtmlTags tag="strong" %] in the database.

            + [% END # /IF wrong_relationships %] + [% END # /IF warnRelationships %] + + [% IF log4perl_errors %] +

            Logging system does not behave correctly

            + [% FOR e IN log4perl_errors %] + [% SWITCH e %] + [% CASE 'missing_config_entry' %] + There is no 'log4perl_conf' entry in the config file. + [% CASE 'cannot_read_config_file' %] + The log4perl config file cannot be opened. + [% CASE 'logfile_not_writable' %] + One of the logfiles listed in the config file is not writable. + [% CASE 'cannot_init_module' %] + The Koha::Logger module cannot be initiated correctly (check the log file). + [% CASE %] + Unknown error '[% e | html %]'. + [% END %] + [% END # /FOR e %] + [% END # /IF log4perl_errors %] + + [% IF warnConnectBroker %] +

            Impossible to connect to the message broker

            + There is an error when trying to connect to the message broker (RabbitMQ), check the Koha log files. +
            + Maybe it is not installed and configured correctly? +
            + Contact your system administrator. + [% END # /IF warnConnectBroker %] + + [% IF weasyprint_missing || warnPrefRequireChoosingExistingAuthority || warnPrefEasyAnalyticalRecords || warnPrefAnonymousPatronOPACPrivacy || warnPrefAnonymousPatronAnonSuggestions || warnPrefAnonymousPatronOPACPrivacy_PatronDoesNotExist || warnPrefAnonymousPatronAnonSuggestions_PatronDoesNotExist || warnPrefKohaAdminEmailAddress || warnPrefOpacHiddenItems || warnPrefPatronSelfRegistrationDefaultCategory || invalid_yesno.count || warnNoActiveCurrency || AutoSelfCheckPatronDoesNotHaveSelfCheckPerm || AutoSelfCheckPatronHasTooManyPerm || warnStatisticsFieldsError || warnNoTemplateCaching || warnILLConfiguration || warnXSLT || oauth2_missing_deps || bad_yaml_prefs || warnIssuingRules || config_bcrypt_settings_no_set || warnHiddenBiblionumbers.size || warnFastCataloging %] +

            Warnings regarding the system configuration

            + + + [% IF (warnFastCataloging) %] + + + + + [% END %] + [% IF (warnPrefRequireChoosingExistingAuthority) %] + + + + + [% END %] + [% IF (warnPrefEasyAnalyticalRecords) %] + + + + + [% END %] + [% IF warnPrefAnonymousPatronOPACPrivacy %] + + + + + [% END %] + [% IF warnPrefAnonymousPatronAnonSuggestions %] + + + + + [% END %] + [% IF warnPrefAnonymousPatronOPACPrivacy_PatronDoesNotExist %] + + + + + [% END %] + [% IF warnPrefAnonymousPatronAnonSuggestions_PatronDoesNotExist %] + + + + + [% END %] + [% IF warnPrefKohaAdminEmailAddress %] + + + + + [% END %] + [% IF warnPrefOpacHiddenItems %] + + + + [% END %] + [% IF warnPrefPatronSelfRegistrationDefaultCategory %] + + [% END %] + [% IF warnXSLT %] + [% FOR p IN warnXSLT %] + + + + [% END %] + [% END %] + [% IF invalid_yesno.count %] + [% FOR p IN invalid_yesno %] + + + + + [% END %] + [% END %] + [% IF warnNoActiveCurrency %] + + + + + [% END %] + [% IF warnStatisticsFieldsError %] + + + + + [% END %] + [% IF AutoSelfCheckPatronDoesNotHaveSelfCheckPerm %] + + + + + [% END %] + [% IF AutoSelfCheckPatronHasTooManyPerm %] + + + + + [% END %] + [% IF warnNoTemplateCaching %] + + + + + [% END %] + [% IF warnI18nMissing %] + + + + + [% END %] + [% IF warnILLConfiguration %] + [% IF no_ill_backends %] + + + + + [% END %] + [% IF ill_partner_code_not_defined %] + + + + + [% END %] + [% IF ill_partner_code_no_patrons %] + + + + + [% END %] + [% IF ill_branch_not_defined %] + + + + + [% END %] + [% IF ill_partner_code_doesnt_exist %] + + + + + [% END %] + [% END %] + + [% IF weasyprint_missing %] + + [% END %] + + [% IF oauth2_missing_deps %] + + + + + [% END %] + [% IF bad_yaml_prefs %] + + + + + [% END %] + [% IF config_bcrypt_settings_no_set %] + + + + + [% END %] + [% IF warnHiddenBiblionumbers.size %] + + + + + [% END %] + [% IF Koha.Preference('SearchEngine') == 'Elasticsearch' && elasticsearch_status.version.substr(0,1) < 6 %] + + + + + [% END %] +
            Preferences and parameters
            Warning There is no "Fast add" (FA) framework defined in administration->MARC frameworks. This disables the 'Fast cataloging' feature in cataloging/circulation.
            Warning System preference 'RequireChoosingExistingAuthority' is disabled, but needs 'AutoCreateAuthorities' enabled. Otherwise catalogers can add headings that will not be linked to authorities.
            Warning System preference 'EasyAnalyticalRecords' set, but UseControlNumber preference is set to 'Use'. Set it to 'Don't use' or else the 'Show analytics' links in the staff interface and the OPAC will be + broken.
            Error System preference 'OPACPrivacy' set, but AnonymousPatron preference is set to '0'. Set it to a valid borrower number or checkins for these patrons will fail.
            Warning System preference 'AnonSuggestions' set, but AnonymousPatron preference is set to '0'. Set it to a valid borrower number if you want that this feature works correctly.
            Error Some patrons have requested privacy after their items are checked in, but the AnonymousPatron preference is not set correctly. Set it to a valid borrower number or checkins for these patrons will + fail.
            Warning System preference 'AnonSuggestions' set, but AnonymousPatron preference is not set correctly. Set it to a valid borrower number if you want that this feature works correctly.
            Warning System preference 'KohaAdminEmailAddress' does not contain a valid email address. Emails will not be sent.
            Warning System preference 'OpacHiddenItems' generates a warning and will produce unexpected behaviors: [% warnPrefOpacHiddenItems | html %]
            Warning System preference 'PatronSelfRegistration' is set, but 'PatronSelfRegistrationDefaultCategory' does not contain a valid patron category code. Patron self-registration is disabled.
            Warning System preference '[% p.syspref | html %]' is '[% p.value | html %]', but the file '[% p.filename | html %]' does not exist.
            Warning System preference '[% p.variable | html %]' must be '0' or '1', but is [% IF p.value.defined %]'[% p.value | html %]'[% ELSE %]NULL[% END %].
            Warning No active currency is defined. Please go to Administration > Currencies and exchange rates and mark one currency as active.
            Warning System preference 'StatisticsFields' contains field names not belonging to the items database table: [% warnStatisticsFieldsError | html %]
            Warning The patron used for the self checkout module at the OPAC does not have the self_check => self_checkout_module permission.
            Warning The patron used for the self checkout module at the OPAC has too many permissions. They should only have self_check => self_checkout_module.
            Warning You are missing the <template_cache_dir> entry in your koha-conf.xml file. That will bring a performance boost to enable it.
            Warning The PO directory has not been found. See the dedicated wiki page for more information.
            Warning The ILL module is enabled, but there are no backends available.
            Warning The ILL module is enabled, but ILLPartnerCode system preference is empty. Falling back to the hardcoded 'IL'.
            Warning The ILL module is enabled and ILLPartnerCode system preference configured, but there are no patrons in [% ill_partner_code_no_patrons | html %] category.
            Warning The ILL module is enabled, but no 'branch' block is defined in koha-conf.xml. You must define this block before use.
            Warning The ILL module is enabled, but the configured ILLPartnerCode ([% ill_partner_code_doesnt_exist | html %]) is not defined on the system.
            Warning The weasyprint tool is not installed.
            Warning System preference 'RESTOAuth2ClientCredentials' is set, but the required Net::OAuth2::AuthorizationServer dependency is missing. The feature is disabled.
            Warning Some system preferences have badly formatted YAML content: [% bad_yaml_prefs.join(', ') | html %]
            Warning System preference 'Pseudonymization' is set, but there is not 'bcrypt_settings' entry defined in the $KOHA_CONF file.
            Warning + [% FOR w IN warnHiddenBiblionumbers %] + Bibliographic framework "[% w.frameworkcode | html %]" has the biblionumber field hidden at the interface [% w.interface | html %]
            + [% END %] +
            Deprecation warning Elasticsearch version 5.x is not supported in Koha 20.11 and greater. Please upgrade your Elasticsearch cluster
            + [% END # /IF warnPrefRequireChoosingExistingAuthority %] + + [% IF xml_config_warnings.size %] + + + [% FOREACH config_entry IN xml_config_warnings %] + [% IF config_entry.error == 'zebra_bib_index_mode_is_grs1' %] + + + + + [% ELSIF config_entry.error == 'zebra_auth_index_mode_is_grs1' %] + + + + + [% ELSIF config_entry.error == 'use_zebra_facets_entry_missing' %] + + + + + [% ELSIF config_entry.error == 'log4perl_entry_missing' %] + + + + + [% ELSIF config_entry.error == 'lockdir_entry_missing' %] + + + + + [% ELSIF config_entry.error == 'lockdir_not_writable' %] + + + + + [% ELSIF config_entry.error == 'uploadpath_entry_missing' %] + + + + + [% ELSIF config_entry.error == 'uploadpath_and_opacbaseurl_entry_missing' %] + + + + + [% ELSIF config_entry.error == 'tmp_path_missing' %] + + + + + [% ELSIF config_entry.error == 'encryption_key_missing' %] + + + + + [% END # /IF config_entry.error %] + [% END # /FOREACH config_entry %] +
            XML configuration file
            Warning + The <zebra_bib_index_mode> entry set to 'grs1', which is no longer supported. Please use DOM instead. To switch follow this page of wiki: + Switching to dom indexing +
            Warning + The <zebra_auth_index_mode> entry set to 'grs1', which is no longer supported. Please use DOM instead. To switch follow this page of wiki: + Switching to dom indexing +
            Warning The <use_zebra_facets> entry is missing in your configuration file. Falling back to legacy facet calculation.
            Warning You are missing the <log4perl_conf> entry in your koha-conf.xml file. Please add it, pointing to the log4perl.conf file for your Koha instance.
            Warning You are missing the <lockdir> entry in your koha-conf.xml file. Please add it, pointing to your Koha instance's lock dir.
            Warning The configured <lockdir> entry in your koha-conf.xml file points to a non-writable directory ([% config_entry.lockdir | html %]).
            Warning You are missing the <upload_path> entry in your koha-conf.xml file. Please add it, pointing to the configured file upload directory for your Koha instance.
            Warning + You are missing the <upload_path> entry in your koha-conf.xml file. Please add it, pointing to the configured file upload directory for your Koha instance. Also note that you need to properly + set the OPACBaseURL preference for the file upload plugin to work. +
            Warning + You are missing the <tmp_path> entry in your koha-conf.xml file. Please add it, pointing to the configured temporary directory for your Koha instance. The effective temporary directory is + '[% config_entry.effective_tmp_dir | html %]'. +
            Warning You are missing the <encryption_key> entry in your koha-conf.xml file. Please generate a key. We recommend one of at least 32 bytes. (You might use 'pwgen 32' to do so.)
            + [% END # /IF xml_config_warnings.size %] + + [% IF warnIssuingRules %] + + + [% FOREACH unit IN ir_units %] + + + + + [% END # /FOREACH unit %] +
            Issuing rules
            Warning + The [% unit.branchcode || 'branchcode=default' | html %], [% unit.categorycode || 'categorycode=default' | html %], [% unit.itemtype || 'itemtype=default' | html %]issuingrule will fallback to 'days' for + 'lengthunit' as it is incorrectly defined as [% unit.rule_value | html %]. +
            + [% END # /IF warnIssuingRules %] + + [% IF elasticsearch_has_missing %] + + + [% FOREACH index IN elasticsearch_status.indexes %] + [% IF index.missing_count %] + + + + + [% END %] + [% END %] +
            Records are not indexed in Elasticsearch
            Warning [% index.missing_count | html %] record(s) missing on a total of [% index.index_count | html %] in index [% index.index_name | html %].
            + [% END # /IF elasticsearch_has_missing %] + + [% IF warnMissingCompiledFiles %] + Error Compiled CSS and/or JS files are not present. Please run `yarn build` to generate them. + [% END # /IF warnMissingCompiledFiles %] + [% ELSE %] +

            No warnings.

            + [% END # /IF warnRequireChoosingExistingAuthority... %] + [% END # tab=sysinfo %] + [% END %] + + [% BLOCK team_panel %] + [% WRAPPER tab_panel tabname= "team" bt_active = 1 %] +

            Special thanks to the following organizations

            + + +

            Koha release teams

            + [% IF maintenance_team %] +
            +
            +

            Koha [% short_version | html %][% IF kohaCodename %]([% kohaCodename | html %])[% END %] release team

            + [% IF development_version %] +

            You are running a development version of Koha

            + [% ELSE %] + [% INCLUDE team t=release_team v='release' %] + [% END %] +
            + +
            +

            Current maintenance team

            + [% INCLUDE team t=maintenance_team v=short_version %] + [% IF development_version %] +
          • Release maintainers: +
              + [% FOREACH m IN maintenance_team.maintainer %] +
            • [% m.version | html %] - [% INCLUDE person p=m %]
            • + [% IF maintenance_team.maintainer_assistants %] + [% FOREACH ma IN maintenance_team.maintainer_assistants %] + [% IF ma.version == ( m.version ) %] +
              • Assistant: [% INCLUDE person p=ma %]
              + [% END %] + [% END %] + [% END %] + + [% IF maintenance_team.maintainer_mentors %] + [% FOREACH mm IN maintenance_team.maintainer_mentors %] + [% IF m.version == ( mm.version ) %] +
              • Mentor: [% INCLUDE person p=mm %]
              + [% END %] + [% END %] + [% END %] + [% END %] +
            +
          • + [% END %] +
            +
            + [% ELSE %] +
            Could not read the teams.yaml file. Please make sure <docdir> is correctly defined in koha-conf.xml.
            + [% END # /maintenance_team %] + +

            Koha development team

            + [% IF contributors.size %] +
              + [% FOREACH contributor IN contributors %] +
            • [% INCLUDE person p=contributor %][% INCLUDE contributions p=contributor %]
            • + [% END %] +
            + [% ELSE %] +
            Could not read the contributors.yaml file. Please make sure <docdir> is correctly defined in koha-conf.xml.
            + [% END # /IF contributors.size %] +
            + +

            Contributing companies and institutions

            +
              +
            • Allen Ginsberg Library, USA
            • +
            • Alingsås Public Library, Sweden
            • +
            • American Numismatic Society, USA
            • +
            • Arcadia Public Library, USA
            • +
            • Athens County Public Libraries, USA
            • +
            • BdP de la Meuse, France
            • +
            • BibLibre, France
            • +
            • Biblioteca Provincial Fr. Mamerto Esquiú (Provincia Franciscana de la Asunción), Argentina
            • +
            • Bibliotheksservice-Zentrum Baden-Württemberg (BSZ), Germany
            • +
            • Briar Cliff University, USA
            • +
            • Brimbank City Council, Australia
            • +
            • Brooklyn Law School Library, USA
            • +
            • Bibliothèque Universitaire des Langues et Civilisations (BULAC), France
            • +
            • ByWater Solutions, USA
            • +
            • California College of the Arts, USA
            • +
            • Camden County, USA
            • +
            • Carnegie Stout Library, USA
            • +
            • Calyx, Australia
            • +
            • Catalyst IT, New Zealand
            • +
            • Central Kansas Library System (CKLS), USA
            • +
            • Centre collégial des services regroupés (CCSR), Canada
            • +
            • Cheshire Libraries, United Kingdom
            • +
            • Coeur d'Alene Public Library, USA
            • +
            • Corpus Christi Public Libraries, USA
            • +
            • C & P Bibliography Services, USA
            • +
            • Dataly Tech, Greece
            • +
            • Devinim, Turkey
            • +
            • Do Space, USA
            • +
            • DoverNet, USA
            • +
            • doXulting
            • +
            • Duchesne County Library, USA
            • +
            • Escuela de Orientacion Lacaniana, Argentina
            • +
            • Fenway Library Organization, USA
            • +
            • Fargo Public Library, USA
            • +
            • Farmington Public Library, USA
            • +
            • FIT
            • +
            • Foundations Bible College & Seminary, USA
            • +
            • Goethe-Institut, Germany
            • +
            • Gothenburg University Library, Sweden
            • +
            • Halland County Library, Sweden
            • +
            • Harrison Carmel Public Library, USA
            • +
            • Hauraki District Libraries, New Zealand
            • +
            • Higher Education Libraries of Massachusetts, USA
            • +
            • Hochschule für Gesundheit (hsg), Germany
            • +
            • Hotchkiss School, USA
            • +
            • Katipo Communications, New Zealand
            • +
            • KEEP SOLUTIONS, Portugal
            • +
            • KohaAloha, New Zealand
            • +
            • Koha-Suomi Oy, Finland
            • +
            • LibLime, USA
            • +
            • Library of the Józef Piłsudski Institute of America, USA
            • +
            • Libriotech, Norway
            • +
            • Los Gatos Public Library, USA
            • +
            • Lund University Library, Sweden
            • +
            • MassCat, USA
            • +
            • Middletown Township Public Library, USA
            • +
            • National Library of Finland, Finland
            • +
            • Newcastle City Council, United Kingdom
            • +
            • New Zealand Central Agencies Library, New Zealand
            • +
            • New Zealand Ministry of Education Library, New Zealand
            • +
            • North Central Regional Library (NCRL), USA
            • +
            • Northeast Kansas Library System (NEKLS), USA
            • +
            • OPUS
            • +
            • Orex Digital, Spain
            • +
            • Oslo Public Library, Norway
            • +
            • Plano Independent School, USA
            • +
            • Plant and Food Research Limited, New Zealand
            • +
            • Prosentient Systems, Australia
            • +
            • PTFS, Maryland, USA
            • +
            • PTFS Europe Ltd, United Kingdom
            • +
            • Rijksmuseum, Amsterdam, The Netherlands
            • +
            • Rolling Hills Consolidated Libraries, USA
            • +
            • Round Rock Public Library, USA
            • +
            • SAN-Ouest Provence, France
            • +
            • Sefton Council, United Kingdom
            • +
            • software.coop, United Kingdom
            • +
            • South-East Kansas Library System (SEKLS), USA
            • +
            • South Taranaki District Council, New Zealand
            • +
            • Stockholm University Library, Sweden
            • +
            • SWITCH Library Consortium, USA
            • +
            • Talking Tech, Global
            • +
            • Tamil, France
            • +
            • Theke Solutions, Argentina
            • +
            • Tulong Aklatan, Philippines
            • +
            • Uintah Library System, USA
            • +
            • Universidad de El Salvador, El Salvador
            • +
            • Universidad Empresarial Siglo 21, Argentina
            • +
            • Universidad Nacional de Córdoba, Argentina
            • +
            • Universidad ORT Uruguay
            • +
            • Université d'Aix-Marseille, France
            • +
            • Université de Lyon 3, France
            • +
            • Université de Rennes 2, France
            • +
            • Université de St Etienne, France
            • +
            • University of the Arts London, United Kingdom
            • +
            • Vaara-kirjastot, Finland
            • +
            • Vanier College, Canada
            • +
            • Vermont Organization of Koha Automated Libraries (VOKAL), USA
            • +
            • Ville de Victoriaville, Canada
            • +
            • Virginia Tech, USA
            • +
            • Washoe County Library System, USA
            • +
            • Xercode, Spain
            • +
            + +

            Additional thanks to...

            +
              +
            • Irma Birchall
            • +
            • Rachel Hamilton-Williams (Kaitiaki from 2004 to present)
            • +
            • Stephen Hedges (early Documentation Manager)
            • +
            • Brooke Johnson
            • +
            • Jo Ransom
            • +
            • Nicholas Rosasco (Documentation Compiler)
            • +
            • Regula Sebastiao
            • +
            + [% END # tab=team %] + [% END %] + + [% BLOCK licenses_panel %] + [% WRAPPER tab_panel tabname= "licenses" bt_active = 1 %] +

            Koha

            +

            + This program 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 3 of the License, or (at your option) any later version. +

            + +

            Bootstrap

            +

            Bootstrap, Glyphicons Free: MIT License

            + +

            Bootstrap Icons

            +

            Bootstrap Icons: MIT License

            + +

            Bridge Material Type Icon Set

            +

            Bridge Material Type Icons Project: Creative Commons Attribution-ShareAlike 2.5 License

            + +

            Chocolat.js

            +

            Chocolat.js v1.1.2: GNU General Public License v3.0

            + +

            CodeMirror

            +

            CodeMirror v5.40.2: MIT License

            + +

            C3.js

            +

            C3.js D3-based reusable chart library v0.4.11: MIT Licence

            + +

            CSSLint

            +

            CSSLint v0.9.8: License

            + +

            D3

            +

            D3 JavaScript library for visualizing data v3.5.17: ISC Licence

            + +

            DataTables

            +

            DataTables v.1.10.18: MIT Licence

            + +

            Day.js

            +

            Day.js v1.11.2: MIT License

            + +

            Enquire.js

            +

            Enquire.js v2.1.6: MIT License

            + +

            FamFamFam icons

            +

            FamFamFam Silk icons: Creative Commons Attribution 2.5 License

            + +

            FileSaver.js

            +

            FileSaver.js v2.0.4: MIT License

            Flatpicker

            +

            Flatpickr v4.6.9: MIT License

            + +

            Font Awesome

            +

            + Font Awesome v6.3.0: + Creative Commons Attribution 4.0 International License, SIL Open Font License Version 1.1, MIT License +

            + +

            Font Face Observer

            +

            Font Face Observer JavaScript library v2.3.0: BSD 2-Clause "Simplified" License

            + +

            GreyBox

            +

            + GreyBox JavaScript Library v5.54: + GNU Lesser General Public License, version 2.1 +

            + +

            HC Sticky

            +

            HC Sticky JavaScript library v2.2.7: MIT License

            + +

            Highlight

            +

            Highlight jQuery Plugin v5.0: MIT License

            + +

            HTMLHint

            +

            HTMLHint v0.9.12: MIT License

            + +

            Humanized Messages

            +

            Humanized Messages v1.0: Apache License, Version 2.0

            + +

            JavaScript Cookie

            +

            JavaScript Cookie v3.0.1: MIT License

            + +

            JavaScript Diff Algorithm

            +

            JavaScript Diff Algorithm: MIT License

            + +

            jQuery, jQuery Migrate, and jQuery UI

            +

            + jQuery v3.6.0, jQuery Migrate, jQuery UI v1.13.2: + MIT License +

            + +

            jQuery Bar Rating Plugin

            +

            jQuery Bar Rating plugin v1.2.2: MIT License

            + +

            jQuery Emojiarea Plugin

            +

            Emojiarea plugin for jQuery: Apache License, Version 2.0

            + +

            jQuery insertAtCaret Plugin

            +

            jQuery insertAtCaret Plugin v1.0 by the phpMyAdmin development team: GNU General Public License

            + +

            jQuery jEditable

            +

            jQuery jEditable: MIT Licence

            + +

            jQuery jsTree Plugin

            +

            jQuery jsTree Plugin v3.3.12: MIT License

            + +

            jQuery Multiple Select Plugin

            +

            jQuery Multiple Select plugin v1.6.0: MIT License

            + +

            jQuery TableDnD Plugin

            +

            Table drag and drop JQuery plugin: MIT License

            + +

            jQuery Treetable Plugin

            +

            + jQuery Treetable Plugin 3.1.0: GNU General Public License v2.0, + MIT License +

            + +

            jQuery Validation Plugin

            +

            jQuery Validation Plugin v1.19.3: MIT License

            + +

            JS-YAML

            +

            JS-YAML v3.13.1: MIT License

            + +

            JSHint

            +

            JSHint v2.9.7: MIT License

            + +

            JSZip

            +

            JSZip JavaScript library v3.1.3: MIT License, GNU General Public License v3.0

            + +

            kjua

            +

            kjua JavaScript library v0.6.0: MIT License

            + +

            Leaflet

            +

            Leaflet JavaScript library v1.0.3: BSD License

            + +

            Noto fonts

            +

            Noto: SIL Open Font License Version 1.1

            + +

            OAI XSLT stylesheet

            +

            Adapted from the DSpace project: BSD License

            + +

            OpenAPI 2.0 schema

            +

            + JSON Schema for Swagger 2.0 API: + Apache License, Version 2.0, OpenAPI Initiative (OAI) +

            + +

            OpenJS Keyboard Shortcuts Library

            +

            OpenJS keyboard shortcuts library: BSD License

            + +

            RequireJS

            +

            RequireJS JavaScript file and module loader v2.1.8: BSD License or MIT License

            + +

            Select2

            +

            Select2 library v4.0.13: Apache License, Version 2.0 or GNU General Public License v2.0

            + +

            Sortable

            +

            Sortable JavaScript Library v1.15.0: MIT Licence

            + +

            TinyMCE WYSIWYG Editor

            +

            TinyMCE WYSIWYG editor v5.9.2: GNU Lesser General Public License v2.1

            + +

            Verovio

            +

            + Verovio: GNU General Public License v3.0, + GNU Lesser General Public License v3.0 +

            + +

            Virtual Keyboard

            +

            Virtual Keyboard v1.30.1: MIT Licence

            + [% END # tab=licenses %] + [% END %] + + [% BLOCK translations_panel %] + [% WRAPPER tab_panel tabname= "translations" bt_active = 1 %] +

            Translation

            +
              +
            • العربية (Arabic) Version 3.2 to 3.4, 3.16 & 3.18 by KnowledgeWare Technologies; Versions 3.6 to 3.14 by Arabic Koha support team: Karam Qubsi, Kouider Bounama, Sham Bajaa, Ghofran Alshami, Chrestian Aboud, Fatema Salem + and Duaa Bazzazi.
            • አማርኛ (Amharic) Getway II Ethiopia Co. (Yohannes Mulugeta (Team Leader), Tegene Assefa, Abiyot Bayou)
            • +
            • Armenian Tigran Zargaryan
            • +
            • Български (Bulgarian) Radoslav Kolev
            • +
            • euskara (Basque) Fernando Berrizbeitia, the librarians of Eima Katalogoa, Tabakalera International Contemporary Culture Centre, and Nere Erkiaga
            • +
            • বাংলা (Bengali) Parthasarathi Mukhopadhyay
            • +
            • 中文 (Chinese)
            • +
            • Hrvatski (Croatian)
            • +
            • čeština (Czech)
            • +
            • Dænsk (Danish)
            • +
            • Nederlands-Nederland (Dutch-The Netherlands) Ronald Wijlens, Saxion University
            • +
            • Nederlands-België (Dutch-Belgium)
            • +
            • English
            • +
            • suomi, suomen kieli (Finnish) Pasi Korkalo
            • +
            • Français (French) Kohala, Pascale Nalon (ENSMP), and many more
            • +
            • Galego (Galician) Ignacio Javier
            • +
            • Deutsch (German) Friedrich zur Hellen, Robert Hillig, Katrin Fischer, Beda Szukics, Mirko Tietgen and Marc Véron
            • +
            • ελληνικά (Greek, Modern [1453- ]) Koha Hellenic Users' Group (Georgia Katsarou, Dimitris Antonakis, Eugenios Papadopoulos), Theodoros Theodoropoulos, Panoraia Gaitanou and Kiriaki + Roditi
            • +
            • עברית (Hebrew)
            • +
            • हिन्दी (Hindi)
            • +
            • Magyar (Hungarian)Agnes Imecs
            • +
            • Norsk Bokmål (Norwegian) Axel Bojer and Thomas Gramstad
            • +
            • Norsk Nynorsk (Norwegian) Unni Knutsen and Marit Kristine Ådland
            • +
            • (Indonesian)
            • +
            • Italiano (Italian) for 3.2: Zeno Tajoli, Pietro Gozzetti and Paolo Pozzan; for 3.4 and more: Zeno Tajoli, Stefano Bargioni, Paolo Bizzarri
            • +
            • 日本語 (Japanese)
            • +
            • 한국어 (Korean)
            • +
            • ಕನ್ನಡ (kannaḍa)
            • +
            • Latina (Latin)
            • +
            • Lao Anousak Anthony Souphavanh
            • +
            • Māori
            • +
            • മലയാളം (Malayalam)
            • +
            • فارسى (Persian)
            • +
            • ଓଡ଼ିଆ (ōṛiyā)
            • +
            • Polski (Polish)
            • +
            • Português (Portuguese)
            • +
            • Română (Romanian)
            • +
            • Русский (Russian) Victor Titarchuk and Serhij Dubyk
            • +
            • Español (Spanish) Bernardo González Kriegel, Héctor Castro and Tomás Cohen Arazi, with the help of the koha-es community.
            • +
            • Svenska (Swedish)
            • +
            • Tetun (Tetum) Karen Myers
            • +
            • ภาษาไทย (Thai)
            • +
            • Türkçe (Turkish) pre-3.8: Selma Aslan; for 3.8+, Suleyman Demirel University (Ugur Bulgan, Onur Erdem, Kemal Caner Bayrakci, and Alper Tutunsatar)
            • +
            • اردو(Urdu) Ata ur Rehman
            • +
            • Українська (Ukrainian) Victor Titarchuk and Serhij Dubyk
            • +
            + [% END #tab=translations %] + [% END %] + + [% BLOCK history_panel %] + [% WRAPPER tab_panel tabname= "history" bt_active = 1 %] +

            Koha history timeline

            + [% IF ! timeline_read_error %] + + + + + + + + [% FOREACH tabl IN table2 %] + + [% FOREACH ro IN tabl.row2 %] + + + [% END %] + + [% END %] +
            DateDescription
            [% ro.date | html %][% ro.desc | html %]
            + [% ELSE %] +
            Could not read the history.txt file. Please make sure <docdir> is correctly defined in koha-conf.xml.
            + [% END %] [% END %] [% END %] -[% END %] -[% BLOCK dedications_panel %] - [% WRAPPER tab_panel tabname= "dedications" bt_active = 1 %] -

            22.11

            -

            - The Koha Community would like to dedicate the release of Koha 22.11 to Rosalie Blake. -

            -

            - Rosalie was the Head Librarian at Horowhenua Library Trust when Koha was started and without her Koha - would not exist. She was an inspiring leader and innovator and took the risk of her career entrusting - Chris, Joanne, Rachel and Simon to deliver the original project that became the international sensation - we all know and love. -

            -

            - She was also a practicing Justice of the Peace, a stalwart of the Levin Pottery Club and much loved - mother of Simon and Jeremy, and grandmother of Ben, Toby, Anna, Charlotte and Billy. -

            - [% END # tab=dedications %] -[% END %] + [% BLOCK dedications_panel %] + [% WRAPPER tab_panel tabname= "dedications" bt_active = 1 %] +

            22.11

            +

            The Koha Community would like to dedicate the release of Koha 22.11 to Rosalie Blake.

            +

            + Rosalie was the Head Librarian at Horowhenua Library Trust when Koha was started and without her Koha would not exist. She was an inspiring leader and innovator and took the risk of her career entrusting Chris, Joanne, + Rachel and Simon to deliver the original project that became the international sensation we all know and love. +

            +

            She was also a practicing Justice of the Peace, a stalwart of the Levin Pottery Club and much loved mother of Simon and Jeremy, and grandmother of Ben, Toby, Anna, Charlotte and Billy.

            + [% END # tab=dedications %] + [% END %] + diff --git a/t/template_filters.t b/t/template_filters.t index 0a24be6982..6b1bb10bd0 100755 --- a/t/template_filters.t +++ b/t/template_filters.t @@ -82,29 +82,30 @@ EXPECTED my @missing_filters = t::lib::QA::TemplateFilters::missing_filters($input); is_deeply( \@missing_filters, - [{ - error => "missing_filter", - line => " [% just_a_var %]", + [ + { + error => "missing_filter", + line => " [% just_a_var %]", line_number => 3, }, { - error => "missing_filter", - line => " [% just_a_var %] A N D [% another_one_on_same_line %]", + error => "missing_filter", + line => " [% just_a_var %] A N D [% another_one_on_same_line %]", line_number => 4, }, { - error => "missing_filter", - line => " [% just_a_var %] A N D [% another_one_on_same_line %]", + error => "missing_filter", + line => " [% just_a_var %] A N D [% another_one_on_same_line %]", line_number => 4, }, { - error => "missing_filter", - line => " [% IF ( patron.othernames ) %]“[% patron.othernames %]”[% END %]", + error => "missing_filter", + line => " [% IF ( patron.othernames ) %]“[% patron.othernames %]”[% END %]", line_number => 6, }, { - error => "missing_filter", - line => "[% patron_message.get_column('manager_surname') %]", + error => "missing_filter", + line => "[% patron_message.get_column('manager_surname') %]", line_number => 8 } ], @@ -164,8 +165,7 @@ EXPECTED my $new_content = t::lib::QA::TemplateFilters::fix_filters($input); is( $new_content . "\n", $expected, ); my @missing_filters = t::lib::QA::TemplateFilters::missing_filters($input); - is_deeply( - \@missing_filters,[],); + is_deeply( \@missing_filters, [], ); }; subtest 'Preserve pre/post chomps' => sub { @@ -239,9 +239,8 @@ INPUT \@missing_filters, [ { - error => "wrong_html_filter", - line => - '[% var | html %]', + error => "wrong_html_filter", + line => '[% var | html %]', line_number => 1 } @@ -257,8 +256,8 @@ INPUT [ { error => "wrong_html_filter", - line => - '[% var | html %][% var | html %]', + line => + '[% var | html %][% var | html %]', line_number => 1 } @@ -301,7 +300,6 @@ EXPECTED my $new_content = t::lib::QA::TemplateFilters::fix_filters($input); is( $new_content . "\n", $expected, ); - my @missing_filters = t::lib::QA::TemplateFilters::missing_filters($input); is_deeply( \@missing_filters, @@ -335,7 +333,6 @@ EXPECTED my $new_content = t::lib::QA::TemplateFilters::fix_filters($input); is( $new_content . "\n", $expected, ); - my @missing_filters = t::lib::QA::TemplateFilters::missing_filters($input); - is_deeply(\@missing_filters, []); + is_deeply( \@missing_filters, [] ); }; diff --git a/t/timezones.t b/t/timezones.t index 64b13b78a9..c83514865c 100755 --- a/t/timezones.t +++ b/t/timezones.t @@ -10,8 +10,10 @@ use t::lib::Mocks; $ENV{TZ} = q{}; t::lib::Mocks::mock_config( 'timezone', q{} ); my $config = Koha::Config->get_instance; -is( $config->timezone, 'local', - 'Got local timezone with no env or config timezone set' ); +is( + $config->timezone, 'local', + 'Got local timezone with no env or config timezone set' +); $ENV{TZ} = 'Antarctica/Macquarie'; is( @@ -29,6 +31,7 @@ is( t::lib::Mocks::mock_config( 'timezone', 'Your/Timezone' ); warning_is { - is( $config->timezone, 'local', 'Invalid timezone falls back to local' ); } - 'Invalid timezone in koha-conf.xml (Your/Timezone)', + is( $config->timezone, 'local', 'Invalid timezone falls back to local' ); +} +'Invalid timezone in koha-conf.xml (Your/Timezone)', 'Invalid timezone raises a warning'; diff --git a/tags/list.pl b/tags/list.pl index 62111e0f7e..59858acc0d 100755 --- a/tags/list.pl +++ b/tags/list.pl @@ -20,16 +20,15 @@ use Modern::Perl; use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Biblio qw( GetBiblioData ); use C4::Context; -use C4::Tags qw( get_tag_rows get_tags remove_tag ); +use C4::Tags qw( get_tag_rows get_tags remove_tag ); use C4::Output qw( output_html_with_http_headers ); use Koha::Biblios; -my $needed_flags = { tools => 'moderate_tags' -}; # FIXME: replace when more specific permission is created. +my $needed_flags = { tools => 'moderate_tags' }; # FIXME: replace when more specific permission is created. my $query = CGI->new; my $op = $query->param('op') || ''; @@ -39,18 +38,17 @@ my $tag_id = $query->param('tag_id'); my ( $template, $borrowernumber, $cookie ) = get_template_and_user( { - template_name => "tags/list.tt", - query => $query, - type => "intranet", - flagsrequired => $needed_flags, + template_name => "tags/list.tt", + query => $query, + type => "intranet", + flagsrequired => $needed_flags, } ); if ( $op eq "cud-del" ) { remove_tag($tag_id); print $query->redirect("/cgi-bin/koha/tags/list.pl?tag=$tag"); -} -else { +} else { my $marcflavour = C4::Context->preference('marcflavour'); my @results; @@ -58,9 +56,10 @@ else { if ($tag) { my $taglist = get_tag_rows( { term => $tag } ); for ( @{$taglist} ) { + # FIXME We should use Koha::Biblio here - my $dat = &GetBiblioData( $_->{biblionumber} ); - my $items = Koha::Items->search_ordered({ 'me.biblionumber' => $dat->{biblionumber} }); + my $dat = &GetBiblioData( $_->{biblionumber} ); + my $items = Koha::Items->search_ordered( { 'me.biblionumber' => $dat->{biblionumber} } ); $dat->{biblionumber} = $_->{biblionumber}; $dat->{tag_id} = $_->{tag_id}; $dat->{items} = $items; diff --git a/tags/review.pl b/tags/review.pl index 019ec62fe9..82b82ace28 100755 --- a/tags/review.pl +++ b/tags/review.pl @@ -21,13 +21,13 @@ use Modern::Perl; use POSIX qw( ceil ); -use CGI qw ( -utf8 ); -use CGI::Cookie; # need to check cookies before having CGI parse the POST request +use CGI qw ( -utf8 ); +use CGI::Cookie; # need to check cookies before having CGI parse the POST request use URI::Escape qw( uri_escape_utf8 ); -use C4::Auth qw( check_cookie_auth get_template_and_user ); +use C4::Auth qw( check_cookie_auth get_template_and_user ); use C4::Context; use C4::Output qw( output_with_http_headers is_ajax pagination_bar output_html_with_http_headers ); -use C4::Tags qw( +use C4::Tags qw( approval_counts blacklist get_approval_rows @@ -35,39 +35,42 @@ use C4::Tags qw( whitelist ); -my $script_name = "/cgi-bin/koha/tags/review.pl"; -my $needed_flags = { tools => 'moderate_tags' }; # FIXME: replace when more specific permission is created. +my $script_name = "/cgi-bin/koha/tags/review.pl"; +my $needed_flags = { tools => 'moderate_tags' }; # FIXME: replace when more specific permission is created. -sub ajax_auth_cgi { # returns CGI object - my $needed_flags = shift; - my %cookies = CGI::Cookie->fetch; - my $input = CGI->new; - my $sessid = $cookies{'CGISESSID'}->value; - my ($auth_status) = check_cookie_auth($sessid, $needed_flags); - if ($auth_status ne "ok") { +sub ajax_auth_cgi { # returns CGI object + my $needed_flags = shift; + my %cookies = CGI::Cookie->fetch; + my $input = CGI->new; + my $sessid = $cookies{'CGISESSID'}->value; + my ($auth_status) = check_cookie_auth( $sessid, $needed_flags ); + if ( $auth_status ne "ok" ) { output_with_http_headers $input, undef, - "window.alert('Your CGI session cookie ($sessid) is not current. " . - "Please refresh the page and try again.');\n", 'js'; + "window.alert('Your CGI session cookie ($sessid) is not current. " + . "Please refresh the page and try again.');\n", 'js'; exit 0; } return $input; } -if (is_ajax()) { - my $input = &ajax_auth_cgi($needed_flags); - my $operator = C4::Context->userenv->{'number'}; # must occur AFTER auth +if ( is_ajax() ) { + my $input = &ajax_auth_cgi($needed_flags); + my $operator = C4::Context->userenv->{'number'}; # must occur AFTER auth my $js_reply; - my $op = $input->param('op') || q{}; + my $op = $input->param('op') || q{}; my $tag = $input->param('tag'); - if ($op eq 'test') { + if ( $op eq 'test' ) { my $check = is_approved($tag); - $js_reply = ( $check >= 1 ? 'success' : $check <= -1 ? 'failure' : 'indeterminate' ) . "_test('".uri_escape_utf8($tag)."');\n"; - } - elsif ($op eq 'cud-approve') { - $js_reply = ( whitelist($operator,$tag) ? 'success' : 'failure') . "_approve('".uri_escape_utf8($tag)."');\n"; - } - elsif ($op eq 'cud-reject') { - $js_reply = ( blacklist($operator,$tag) ? 'success' : 'failure') . "_reject('".uri_escape_utf8($tag)."');\n"; + $js_reply = + ( $check >= 1 ? 'success' : $check <= -1 ? 'failure' : 'indeterminate' ) + . "_test('" + . uri_escape_utf8($tag) . "');\n"; + } elsif ( $op eq 'cud-approve' ) { + $js_reply = + ( whitelist( $operator, $tag ) ? 'success' : 'failure' ) . "_approve('" . uri_escape_utf8($tag) . "');\n"; + } elsif ( $op eq 'cud-reject' ) { + $js_reply = + ( blacklist( $operator, $tag ) ? 'success' : 'failure' ) . "_reject('" . uri_escape_utf8($tag) . "');\n"; } output_with_http_headers $input, undef, $js_reply, 'js'; exit; @@ -76,87 +79,92 @@ if (is_ajax()) { ### Below is the sad, boring, necessary non-AJAX HTML code. my $input = CGI->new; -my ($template, $borrowernumber, $cookie) = get_template_and_user( +my ( $template, $borrowernumber, $cookie ) = get_template_and_user( { - template_name => "tags/review.tt", - query => $input, - type => "intranet", - flagsrequired => $needed_flags, + template_name => "tags/review.tt", + query => $input, + type => "intranet", + flagsrequired => $needed_flags, } ); -my (@errors, @tags); +my ( @errors, @tags ); my $op = $input->param('op') || q{}; @tags = $input->multi_param('tags'); -if ($op eq 'cud-approve') { +if ( $op eq 'cud-approve' ) { foreach (@tags) { - whitelist($borrowernumber,$_) or push @errors, {failed_ok=>$_}; + whitelist( $borrowernumber, $_ ) or push @errors, { failed_ok => $_ }; } -} elsif ($op eq 'cud-reject' ) { +} elsif ( $op eq 'cud-reject' ) { foreach (@tags) { - blacklist($borrowernumber,$_) or push @errors, {failed_rej=>$_}; + blacklist( $borrowernumber, $_ ) or push @errors, { failed_rej => $_ }; } -} elsif ($op eq 'test' ) { +} elsif ( $op eq 'test' ) { my $tag = $input->param('test'); push @tags, $tag; my $check = is_approved($tag); $template->param( test_term => $tag, - ( $check >= 1 ? 'verdict_ok' : - $check <= -1 ? 'verdict_rej' : 'verdict_indeterminate' ) => 1, - ); + ( + $check >= 1 ? 'verdict_ok' + : $check <= -1 ? 'verdict_rej' + : 'verdict_indeterminate' + ) => 1, + ); } my $counts = &approval_counts; -foreach (keys %$counts) { - $template->param($_ => $counts->{$_}); +foreach ( keys %$counts ) { + $template->param( $_ => $counts->{$_} ); } sub pagination_calc { - my $query = shift or return; - my $hardlimit = (@_) ? shift : 100; # hardcoded, could be another syspref - my $pagesize = $query->param('limit' ) || $hardlimit; - my $page = $query->param('page' ) || 1; - my $offset = $query->param('offset') || 0; - ($pagesize <= $hardlimit) or $pagesize = $hardlimit; - if ($page > 1) { - $offset = ($page-1)*$pagesize; + my $query = shift or return; + my $hardlimit = (@_) ? shift : 100; # hardcoded, could be another syspref + my $pagesize = $query->param('limit') || $hardlimit; + my $page = $query->param('page') || 1; + my $offset = $query->param('offset') || 0; + ( $pagesize <= $hardlimit ) or $pagesize = $hardlimit; + if ( $page > 1 ) { + $offset = ( $page - 1 ) * $pagesize; } else { $page = 1; } - return ($pagesize,$page,$offset); + return ( $pagesize, $page, $offset ); } -my ($pagesize,$page,$offset) = pagination_calc($input,100); +my ( $pagesize, $page, $offset ) = pagination_calc( $input, 100 ); my %filters = ( limit => $offset ? "$offset,$pagesize" : $pagesize, - sort => 'approved,-weight_total,+term', + sort => 'approved,-weight_total,+term', ); -my ($filter,$date_from,$date_to); -if (defined $input->param('approved')) { # 0 is valid value, must check defined +my ( $filter, $date_from, $date_to ); +if ( defined $input->param('approved') ) { # 0 is valid value, must check defined $filter = $input->param('approved'); } else { $filter = 0; } -if ($filter eq 'all') { - $template->param(filter_approved_all => 1); -} elsif ($filter =~ /-?[01]/) { +if ( $filter eq 'all' ) { + $template->param( filter_approved_all => 1 ); +} elsif ( $filter =~ /-?[01]/ ) { $filters{approved} = $filter; $template->param( - ($filter == 1 ? 'filter_approved_ok' : - $filter == 0 ? 'filter_approved_pending' : - $filter == -1 ? 'filter_approved_rej' : - 'filter_approved') => 1 + ( + $filter == 1 ? 'filter_approved_ok' + : $filter == 0 ? 'filter_approved_pending' + : $filter == -1 ? 'filter_approved_rej' + : 'filter_approved' + ) => 1 ); } # my $q_count = get_approval_rows({limit=>$pagesize, sort=>'approved,-weight_total,+term', count=>1}); -if ($filter = $input->param('tag')) { - $template->param(filter_tag=>$filter); +if ( $filter = $input->param('tag') ) { + $template->param( filter_tag => $filter ); $filters{term} = $filter; } if ( $filter = $input->param('from') ) { @@ -169,39 +177,40 @@ if ( $filter = $input->param('to') ) { $template->param( filter_date_approved_to => $filter ); $filters{date_approved} = "<=$date_to"; } -if ($filter = $input->param('approver')) { # name (or borrowernumber) from input box - if ($filter =~ /^\d+$/ and $filter > 0) { +if ( $filter = $input->param('approver') ) { # name (or borrowernumber) from input box + if ( $filter =~ /^\d+$/ and $filter > 0 ) { + # $filter=get borrowernumber from name # FIXME: get borrowernumber from name not implemented. - $template->param(filter_approver=>$filter); + $template->param( filter_approver => $filter ); $filters{approved_by} = $filter; } else { - push @errors, {approver=>$filter}; + push @errors, { approver => $filter }; } } -if ($filter = $input->param('approved_by')) { # borrowernumber from link - if ($filter =~ /^\d+$/ and $filter > 0) { - $template->param(filter_approver=>$filter); +if ( $filter = $input->param('approved_by') ) { # borrowernumber from link + if ( $filter =~ /^\d+$/ and $filter > 0 ) { + $template->param( filter_approver => $filter ); $filters{approved_by} = $filter; } else { - push @errors, {approved_by=>$filter}; + push @errors, { approved_by => $filter }; } } -my $tagloop = get_approval_rows(\%filters); +my $tagloop = get_approval_rows( \%filters ); my $qstring = $input->query_string; -$qstring =~ s/([&;])*\blimit=\d+//; # remove pagination var -$qstring =~ s/^;+//; # remove leading delims -$qstring = "limit=$pagesize" . ($qstring ? '&' . $qstring : ''); -(scalar @errors) and $template->param(message_loop=>\@errors); +$qstring =~ s/([&;])*\blimit=\d+//; # remove pagination var +$qstring =~ s/^;+//; # remove leading delims +$qstring = "limit=$pagesize" . ( $qstring ? '&' . $qstring : '' ); +( scalar @errors ) and $template->param( message_loop => \@errors ); $template->param( - offset => $offset, # req'd for EXPR - op => $op, - op_count => scalar(@tags), - approved => 0, # dummy value (also EXPR) - tagloop => $tagloop, + offset => $offset, # req'd for EXPR + op => $op, + op_count => scalar(@tags), + approved => 0, # dummy value (also EXPR) + tagloop => $tagloop, pagination_bar => pagination_bar( "$script_name?$qstring\&", - ceil($counts->{approved_total}/$pagesize), # $page, 'page' + ceil( $counts->{approved_total} / $pagesize ), # $page, 'page' ) ); diff --git a/tools/access_files.pl b/tools/access_files.pl index 85420bd602..9df638ff64 100755 --- a/tools/access_files.pl +++ b/tools/access_files.pl @@ -26,95 +26,107 @@ use Modern::Perl; use C4::Auth qw( get_template_and_user ); use CGI; use C4::Context; -use C4::Output qw( output_html_with_http_headers ); -use File::stat qw( stat ); +use C4::Output qw( output_html_with_http_headers ); +use File::stat qw( stat ); use Digest::MD5 qw( md5_hex ); -use Encode qw( decode ); +use Encode qw( decode ); -my $input = CGI->new; -my $file_id = $input->param("id"); +my $input = CGI->new; +my $file_id = $input->param("id"); my $access_dirs = C4::Context->config('access_dirs'); my @directories; -if ($access_dirs){ - if (ref $access_dirs->{access_dir} ){ - @directories = @{$access_dirs->{access_dir}}; +if ($access_dirs) { + if ( ref $access_dirs->{access_dir} ) { + @directories = @{ $access_dirs->{access_dir} }; } else { - @directories =($access_dirs->{access_dir}); + @directories = ( $access_dirs->{access_dir} ); } } else { @directories = (); } -my ($template, $borrowernumber, $cookie) - = get_template_and_user({template_name => "tools/access_files.tt", - query => $input, - type => "intranet", - flagsrequired => { tools => 'access_files' }, - }); +my ( $template, $borrowernumber, $cookie ) = get_template_and_user( + { + template_name => "tools/access_files.tt", + query => $input, + type => "intranet", + flagsrequired => { tools => 'access_files' }, + } +); + +unless (@directories) { + $template->param( error_no_dir => 1 ); +} else { -unless(@directories) { - $template->param(error_no_dir => 1); -} -else { #Get the files list my @files_list; - foreach my $dir(@directories){ + foreach my $dir (@directories) { my $dir_h; - opendir($dir_h, $dir); - foreach my $filename (readdir($dir_h)) { + opendir( $dir_h, $dir ); + foreach my $filename ( readdir($dir_h) ) { my $full_path = "$dir/$filename"; - my $id = md5_hex($full_path); - next if ($filename =~ /^\./ or -d $full_path); + my $id = md5_hex($full_path); + next if ( $filename =~ /^\./ or -d $full_path ); # Make sure the filename is unicode-friendly - my $decoded_filename = decode('utf8', $filename); - my $st = stat("$dir/$decoded_filename"); + my $decoded_filename = decode( 'utf8', $filename ); + my $st = stat("$dir/$decoded_filename"); - my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =localtime($st->mtime); - my $dt=DateTime->new(year => $year + 1900, - month => $mon + 1, - day => $mday, - hour => $hour, - minute => $min, - ); - push(@files_list, {name => $decoded_filename, - access_dir => $dir, - date =>$dt, - size => $st->size, - id => $id}); + my ( $sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst ) = localtime( $st->mtime ); + my $dt = DateTime->new( + year => $year + 1900, + month => $mon + 1, + day => $mday, + hour => $hour, + minute => $min, + ); + push( + @files_list, + { + name => $decoded_filename, + access_dir => $dir, + date => $dt, + size => $st->size, + id => $id + } + ); } closedir($dir_h); } my %files_hash = map { $_->{id} => $_ } @files_list; + # If we received a file_id and it is valid, send the file to the browser - if(defined $file_id and exists $files_hash{$file_id} ){ + if ( defined $file_id and exists $files_hash{$file_id} ) { my $filename = $files_hash{$file_id}->{name}; - my $dir = $files_hash{$file_id}->{access_dir}; + my $dir = $files_hash{$file_id}->{access_dir}; binmode STDOUT; + # Open the selected file and send it to the browser - print $input->header(-type => 'application/x-download', - -name => "$filename", - -Content_length => -s "$dir/$filename", - -attachment => "$filename"); + print $input->header( + -type => 'application/x-download', + -name => "$filename", + -Content_length => -s "$dir/$filename", + -attachment => "$filename" + ); my $fh; open $fh, "<:encoding(UTF-8)", "$dir/$filename"; binmode $fh; my $buf; - while(read($fh, $buf, 65536)) { + while ( read( $fh, $buf, 65536 ) ) { print $buf; } close $fh; exit(0); - } - else{ + } else { + # Send the file list to the template - $template->param(files_loop => \@files_list); + $template->param( files_loop => \@files_list ); } } diff --git a/tools/additional-contents.pl b/tools/additional-contents.pl index e9f5ee0269..89dacf9589 100755 --- a/tools/additional-contents.pl +++ b/tools/additional-contents.pl @@ -26,26 +26,26 @@ use Modern::Perl; use CGI qw ( -utf8 ); use Try::Tiny; use Array::Utils qw( array_minus ); -use C4::Auth qw(get_template_and_user); +use C4::Auth qw(get_template_and_user); use C4::Koha; use C4::Context; -use C4::Log qw( logaction ); -use C4::Output qw(output_html_with_http_headers output_and_exit_if_error); -use C4::Languages qw(getTranslatedLanguages); +use C4::Log qw( logaction ); +use C4::Output qw(output_html_with_http_headers output_and_exit_if_error); +use C4::Languages qw(getTranslatedLanguages); use Koha::DateUtils qw( dt_from_string output_pref ); use Koha::AdditionalContents; my $cgi = CGI->new; -my $op = $cgi->param('op') || 'list'; -my $id = $cgi->param('id'); -my $category = $cgi->param('category') || 'news'; +my $op = $cgi->param('op') || 'list'; +my $id = $cgi->param('id'); +my $category = $cgi->param('category') || 'news'; my $wysiwyg; -my $redirect = $cgi->param('redirect'); +my $redirect = $cgi->param('redirect'); my $editmode; -if( $cgi->param('editmode') ){ +if ( $cgi->param('editmode') ) { $wysiwyg = $cgi->param('editmode') eq "wysiwyg" ? 1 : 0; } else { $wysiwyg = C4::Context->preference("AdditionalContentsEditor") eq "tinymce" ? 1 : 0; @@ -55,10 +55,10 @@ $editmode = $wysiwyg eq 1 ? "wysiwyg" : "text"; my ( $template, $borrowernumber, $cookie ) = get_template_and_user( { - template_name => "tools/additional-contents.tt", - query => $cgi, - type => "intranet", - flagsrequired => { tools => 'edit_additional_contents' }, + template_name => "tools/additional-contents.tt", + query => $cgi, + type => "intranet", + flagsrequired => { tools => 'edit_additional_contents' }, } ); @@ -72,21 +72,20 @@ if ( $op eq 'add_form' ) { $category = $additional_content->category; } $template->param( - additional_content => $additional_content, + additional_content => $additional_content, translated_contents => $translated_contents, ); -} -elsif ( $op eq 'cud-add_validate' ) { +} elsif ( $op eq 'cud-add_validate' ) { output_and_exit_if_error( $cgi, $cookie, $template, { check => 'csrf_token' } ); my $location = $cgi->param('location'); my $code = $cgi->param('code'); my $branchcode = $cgi->param('branchcode') || undef; - my @lang = $cgi->multi_param('lang'); + my @lang = $cgi->multi_param('lang'); my $expirationdate = $cgi->param('expirationdate'); - my $published_on = $cgi->param('published_on'); - my $number = $cgi->param('number'); + my $published_on = $cgi->param('published_on'); + my $number = $cgi->param('number'); try { Koha::Database->new->schema->txn_do( @@ -181,28 +180,33 @@ elsif ( $op eq 'cud-add_validate' ) { } }; - if( $redirect eq "just_save" ){ - print $cgi->redirect("/cgi-bin/koha/tools/additional-contents.pl?op=add_form&id=$id&category=$category&editmode=$editmode&redirect=done"); + if ( $redirect eq "just_save" ) { + print $cgi->redirect( + "/cgi-bin/koha/tools/additional-contents.pl?op=add_form&id=$id&category=$category&editmode=$editmode&redirect=done" + ); exit; } else { $op = 'list'; } -} -elsif ( $op eq 'cud-delete_confirmed' ) { - output_and_exit_if_error($cgi, $cookie, $template, { check => 'csrf_token' }); +} elsif ( $op eq 'cud-delete_confirmed' ) { + output_and_exit_if_error( $cgi, $cookie, $template, { check => 'csrf_token' } ); my @ids = $cgi->multi_param('ids'); try { Koha::Database->new->schema->txn_do( sub { - my $contents = - Koha::AdditionalContents->search( { id => \@ids } ); + my $contents = Koha::AdditionalContents->search( { id => \@ids } ); if ( C4::Context->preference("NewsLog") ) { while ( my $c = $contents->next ) { my $translated_contents = $c->translated_contents; while ( my $translated_content = $translated_contents->next ) { - logaction('NEWS', 'DELETE' , undef, sprintf("%s|%s|%s|%s", $c->code, $translated_content->lang, $translated_content->content)); + logaction( + 'NEWS', 'DELETE', undef, + sprintf( + "%s|%s|%s|%s", $c->code, $translated_content->lang, $translated_content->content + ) + ); } } } @@ -220,7 +224,7 @@ elsif ( $op eq 'cud-delete_confirmed' ) { if ( $op eq 'list' ) { my $additional_contents = Koha::AdditionalContents->search( - { category => $category, 'additional_contents_localizations.lang' => 'default' }, + { category => $category, 'additional_contents_localizations.lang' => 'default' }, { order_by => { -desc => 'published_on' }, join => 'additional_contents_localizations' } ); $template->param( additional_contents => $additional_contents ); @@ -232,24 +236,22 @@ for my $language (@$translated_languages) { for my $sublanguage ( @{ $language->{sublanguages_loop} } ) { if ( $language->{plural} ) { push @languages, - { + { lang => $sublanguage->{rfc4646_subtag}, description => $sublanguage->{native_description} . ' ' - . $sublanguage->{region_description} . ' (' - . $sublanguage->{rfc4646_subtag} . ')', - }; - } - else { + . $sublanguage->{region_description} . ' (' + . $sublanguage->{rfc4646_subtag} . ')', + }; + } else { push @languages, - { + { lang => $sublanguage->{rfc4646_subtag}, - description => $sublanguage->{native_description} . ' (' - . $sublanguage->{rfc4646_subtag} . ')', - }; + description => $sublanguage->{native_description} . ' (' . $sublanguage->{rfc4646_subtag} . ')', + }; } } } -unshift @languages, {lang => 'default'} if @languages; +unshift @languages, { lang => 'default' } if @languages; $template->param( op => $op, diff --git a/tools/ajax-inventory.pl b/tools/ajax-inventory.pl index 7d35497a76..b929fcf509 100755 --- a/tools/ajax-inventory.pl +++ b/tools/ajax-inventory.pl @@ -1,15 +1,15 @@ #!/usr/bin/perl use Modern::Perl; -use CGI qw ( -utf8 ); -use C4::Auth qw( check_api_auth ); +use CGI qw ( -utf8 ); +use C4::Auth qw( check_api_auth ); use C4::Items qw( ModDateLastSeen ); my $input = CGI->new; # Authentication -my ($status, $cookie, $sessionId) = C4::Auth::check_api_auth($input, { tools => 'inventory' }); -exit unless ($status eq "ok"); +my ( $status, $cookie, $sessionId ) = C4::Auth::check_api_auth( $input, { tools => 'inventory' } ); +exit unless ( $status eq "ok" ); my $op = $input->param('op') // q{}; diff --git a/tools/automatic_item_modification_by_age.pl b/tools/automatic_item_modification_by_age.pl index 9015e051e9..c443862f46 100755 --- a/tools/automatic_item_modification_by_age.pl +++ b/tools/automatic_item_modification_by_age.pl @@ -49,10 +49,10 @@ my $cgi = CGI->new; # open template my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "tools/automatic_item_modification_by_age.tt", - query => $cgi, - type => "intranet", - flagsrequired => { tools => 'items_batchmod' }, + template_name => "tools/automatic_item_modification_by_age.tt", + query => $cgi, + type => "intranet", + flagsrequired => { tools => 'items_batchmod' }, } ); @@ -62,24 +62,24 @@ my $syspref_name = q|automatic_item_modification_by_age_configuration|; if ( $op eq 'cud-update' ) { my @rules; my @unique_ids = $cgi->multi_param('unique_id'); - for my $unique_id ( @unique_ids ) { + for my $unique_id (@unique_ids) { my @substitution_fields = $cgi->multi_param("substitution_field_$unique_id"); my @substitution_values = $cgi->multi_param("substitution_value_$unique_id"); - my @condition_fields = $cgi->multi_param("condition_field_$unique_id"); - my @condition_values = $cgi->multi_param("condition_value_$unique_id"); - my @age_fields = $cgi->multi_param("agefield_$unique_id"); - my $rule = { + my @condition_fields = $cgi->multi_param("condition_field_$unique_id"); + my @condition_values = $cgi->multi_param("condition_value_$unique_id"); + my @age_fields = $cgi->multi_param("agefield_$unique_id"); + my $rule = { substitutions => [], - conditions => [], + conditions => [], }; - for my $value ( @substitution_values ) { + for my $value (@substitution_values) { my $field = shift @substitution_fields; last unless $field; push @{ $rule->{substitutions} }, { field => $field, value => $value }; } push @{ $rule->{substitutions} }, {} unless @{ $rule->{substitutions} }; - for my $value ( @condition_values ) { + for my $value (@condition_values) { my $field = shift @condition_fields; last unless $field; push @{ $rule->{conditions} }, { field => $field, value => $value }; @@ -88,13 +88,13 @@ if ( $op eq 'cud-update' ) { unless @{ $rule->{conditions} }; $rule->{age} = $cgi->param("age_$unique_id"); - for my $age_field ( @age_fields ) { + for my $age_field (@age_fields) { $rule->{agefield} = $age_field ? $age_field : "items.dateaccessioned"; } push @rules, $rule; } my $syspref_content = to_json( \@rules ); - C4::Context->set_preference($syspref_name, $syspref_content); + C4::Context->set_preference( $syspref_name, $syspref_content ); $op = 'show'; } @@ -102,9 +102,9 @@ if ( $op eq 'cud-update' ) { my @messages; my $syspref_content = C4::Context->preference($syspref_name); my $rules; -$rules = eval { JSON::from_json( $syspref_content ) } +$rules = eval { JSON::from_json($syspref_content) } if $syspref_content; -if ( $@ ) { +if ($@) { push @messages, { type => 'error', code => 'unable_to_load_configuration' diff --git a/tools/batchMod.pl b/tools/batchMod.pl index d6367b48a1..92f19d2929 100755 --- a/tools/batchMod.pl +++ b/tools/batchMod.pl @@ -1,6 +1,5 @@ #!/usr/bin/perl - # Copyright 2000-2002 Katipo Communications # # This file is part of Koha. @@ -22,13 +21,13 @@ use CGI qw ( -utf8 ); use Modern::Perl; use Try::Tiny qw( catch try ); -use C4::Auth qw( get_template_and_user haspermission ); -use C4::Output qw( output_html_with_http_headers ); +use C4::Auth qw( get_template_and_user haspermission ); +use C4::Output qw( output_html_with_http_headers ); use C4::Circulation qw( barcodedecode ); use C4::Context; use MARC::File::XML; use List::MoreUtils qw( uniq ); -use Encode qw( encode_utf8 ); +use Encode qw( encode_utf8 ); use Koha::Database; use Koha::Exception; @@ -41,47 +40,50 @@ use Koha::BackgroundJob::BatchUpdateItem; use Koha::UI::Form::Builder::Item; use Koha::UI::Table::Builder::Items; -my $input = CGI->new; -my $dbh = C4::Context->dbh; -my $error = $input->param('error'); -my @itemnumbers = $input->multi_param('itemnumber'); -my $biblionumber = $input->param('biblionumber'); -my $op = $input->param('op'); -my $del = $input->param('del'); -my $del_records = $input->param('del_records'); -my $src = $input->param('src'); -my $use_default_values = $input->param('use_default_values'); +my $input = CGI->new; +my $dbh = C4::Context->dbh; +my $error = $input->param('error'); +my @itemnumbers = $input->multi_param('itemnumber'); +my $biblionumber = $input->param('biblionumber'); +my $op = $input->param('op'); +my $del = $input->param('del'); +my $del_records = $input->param('del_records'); +my $src = $input->param('src'); +my $use_default_values = $input->param('use_default_values'); my $exclude_from_local_holds_priority = $input->param('exclude_from_local_holds_priority'); -my $mark_items_returned = $input->param('mark_items_returned'); +my $mark_items_returned = $input->param('mark_items_returned'); my $template_name; my $template_flag; -if (!defined $op) { +if ( !defined $op ) { $template_name = "tools/batchMod.tt"; $template_flag = { tools => '*' }; - $op = q{}; + $op = q{}; } else { - $template_name = ($del) ? "tools/batchMod-del.tt" : "tools/batchMod-edit.tt"; - $template_flag = ($del) ? { tools => 'items_batchdel' } : { tools => 'items_batchmod' }; + $template_name = ($del) ? "tools/batchMod-del.tt" : "tools/batchMod-edit.tt"; + $template_flag = ($del) ? { tools => 'items_batchdel' } : { tools => 'items_batchmod' }; } -my ($template, $loggedinuser, $cookie) - = get_template_and_user({template_name => $template_name, - query => $input, - type => "intranet", - flagsrequired => $template_flag, - }); +my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => $template_name, + query => $input, + type => "intranet", + flagsrequired => $template_flag, + } +); $template->param( searchid => scalar $input->param('searchid'), ); # Does the user have a restricted item edition permission? -my $patron = Koha::Patrons->find( $loggedinuser ); -my $uid = $loggedinuser ? $patron->userid : undef; -my $restrictededition = $uid ? haspermission($uid, {'tools' => 'items_batchmod_restricted'}) : undef; -# In case user is a superlibrarian, edition is not restricted -$restrictededition = 0 if ($restrictededition != 0 && C4::Context->IsSuperLibrarian()); +my $patron = Koha::Patrons->find($loggedinuser); +my $uid = $loggedinuser ? $patron->userid : undef; +my $restrictededition = $uid ? haspermission( $uid, { 'tools' => 'items_batchmod_restricted' } ) : undef; -my $nextop=""; +# In case user is a superlibrarian, edition is not restricted +$restrictededition = 0 if ( $restrictededition != 0 && C4::Context->IsSuperLibrarian() ); + +my $nextop = ""; my $display_items; my @messages; @@ -94,31 +96,28 @@ if ( $op eq "cud-action" ) { record_ids => \@itemnumbers, delete_biblios => $del_records, }; - my $job_id = - Koha::BackgroundJob::BatchDeleteItem->new->enqueue($params); + my $job_id = Koha::BackgroundJob::BatchDeleteItem->new->enqueue($params); $nextop = 'enqueued'; $template->param( job_id => $job_id, ); - } - catch { + } catch { warn $_; push @messages, - { + { type => 'error', code => 'cannot_enqueue_job', error => $_, - }; + }; $template->param( view => 'errors' ); }; - } - else { # modification + } else { # modification my @item_columns = Koha::Items->columns; my $new_item_data; - my ( $columns_with_regex ); + my ($columns_with_regex); my @subfields_to_blank = $input->multi_param('disable_input'); - my @more_subfields = $input->multi_param("items.more_subfields_xml"); + my @more_subfields = $input->multi_param("items.more_subfields_xml"); for my $item_column (@item_columns) { my @attributes = ($item_column); my $cgi_param_prefix = 'items.'; @@ -132,28 +131,22 @@ if ( $op eq "cud-action" ) { for my $attr (@attributes) { - my $cgi_var_name = $cgi_param_prefix - . encode_utf8($attr) - ; # We need to deal correctly with encoding on subfield codes + my $cgi_var_name = + $cgi_param_prefix . encode_utf8($attr); # We need to deal correctly with encoding on subfield codes if ( grep { $cgi_var_name eq $_ } @subfields_to_blank ) { + # Empty this column $new_item_data->{$attr} = undef; - } - elsif ( my $regex_search = - $input->param( $cgi_var_name . '_regex_search' ) ) - { + } elsif ( my $regex_search = $input->param( $cgi_var_name . '_regex_search' ) ) { $columns_with_regex->{$attr} = { - search => $regex_search, - replace => - $input->param( $cgi_var_name . '_regex_replace' ), - modifiers => - $input->param( $cgi_var_name . '_regex_modifiers' ) + search => $regex_search, + replace => $input->param( $cgi_var_name . '_regex_replace' ), + modifiers => $input->param( $cgi_var_name . '_regex_modifiers' ) }; - } - else { + } else { my @v = - grep { $_ ne "" } uniq $input->multi_param($cgi_var_name); + grep { $_ ne "" } uniq $input->multi_param($cgi_var_name); next unless @v; @@ -166,32 +159,26 @@ if ( $op eq "cud-action" ) { record_ids => \@itemnumbers, regex_mod => $columns_with_regex, new_values => $new_item_data, - exclude_from_local_holds_priority => ( - defined $exclude_from_local_holds_priority - && $exclude_from_local_holds_priority ne "" - ) + exclude_from_local_holds_priority => + ( defined $exclude_from_local_holds_priority && $exclude_from_local_holds_priority ne "" ) ? $exclude_from_local_holds_priority : undef, - mark_items_returned => ( - defined $mark_items_returned - && $mark_items_returned ne "" - ) - ? $mark_items_returned : undef, + mark_items_returned => ( defined $mark_items_returned && $mark_items_returned ne "" ) + ? $mark_items_returned + : undef, }; try { - my $job_id = - Koha::BackgroundJob::BatchUpdateItem->new->enqueue($params); + my $job_id = Koha::BackgroundJob::BatchUpdateItem->new->enqueue($params); $nextop = 'enqueued'; $template->param( job_id => $job_id, ); - } - catch { + } catch { push @messages, - { + { type => 'error', code => 'cannot_enqueue_job', error => $_, - }; + }; $template->param( view => 'errors' ); }; } @@ -206,37 +193,43 @@ $template->param( # build screen with existing items. and "new" one #------------------------------------------------------------------------------- -if ($op eq "cud-show" || $op eq "show"){ - my $filefh = $input->upload('uploadfile'); +if ( $op eq "cud-show" || $op eq "show" ) { + my $filefh = $input->upload('uploadfile'); my $filecontent = $input->param('filecontent'); - my ( @notfoundbarcodes, @notfounditemnumbers); + my ( @notfoundbarcodes, @notfounditemnumbers ); my $split_chars = C4::Context->preference('BarcodeSeparators'); - if ($filefh){ + if ($filefh) { binmode $filefh, ':encoding(UTF-8)'; my @contentlist; - while (my $content=<$filefh>){ + while ( my $content = <$filefh> ) { $content =~ s/[\r\n]*$//; push @contentlist, $content if $content; } - if ($filecontent eq 'barcode_file') { + if ( $filecontent eq 'barcode_file' ) { @contentlist = grep /\S/, ( map { split /[$split_chars]/ } @contentlist ); @contentlist = uniq @contentlist; @contentlist = map { barcodedecode($_) } @contentlist; + # Note: adding lc for case insensitivity - my %itemdata = map { lc($_->{barcode}) => $_->{itemnumber} } @{ Koha::Items->search({ barcode => { -in => \@contentlist } }, { columns => [ 'itemnumber', 'barcode' ] } )->unblessed }; - @itemnumbers = map { exists $itemdata{lc $_} ? $itemdata{lc $_} : () } @contentlist; - @notfoundbarcodes = grep { !exists $itemdata{lc $_} } @contentlist; - } - elsif ( $filecontent eq 'itemid_file') { + my %itemdata = map { lc( $_->{barcode} ) => $_->{itemnumber} } @{ Koha::Items->search( + { barcode => { -in => \@contentlist } }, { columns => [ 'itemnumber', 'barcode' ] } + )->unblessed + }; + @itemnumbers = map { exists $itemdata{ lc $_ } ? $itemdata{ lc $_ } : () } @contentlist; + @notfoundbarcodes = grep { !exists $itemdata{ lc $_ } } @contentlist; + } elsif ( $filecontent eq 'itemid_file' ) { @contentlist = uniq @contentlist; - my %itemdata = map { $_->{itemnumber} => 1 } @{ Koha::Items->search({ itemnumber => { -in => \@contentlist } }, { columns => [ 'itemnumber' ] } )->unblessed }; - @itemnumbers = grep { exists $itemdata{$_} } @contentlist; + my %itemdata = + map { $_->{itemnumber} => 1 } + @{ Koha::Items->search( { itemnumber => { -in => \@contentlist } }, { columns => ['itemnumber'] } ) + ->unblessed }; + @itemnumbers = grep { exists $itemdata{$_} } @contentlist; @notfounditemnumbers = grep { !exists $itemdata{$_} } @contentlist; } } else { - if (defined $biblionumber && !@itemnumbers){ + if ( defined $biblionumber && !@itemnumbers ) { my $biblio = Koha::Biblios->find($biblionumber); @itemnumbers = $biblio ? $biblio->items->get_column('itemnumber') : (); } @@ -244,36 +237,47 @@ if ($op eq "cud-show" || $op eq "show"){ my @barcodelist = grep /\S/, ( split /[$split_chars]/, $list ); @barcodelist = uniq @barcodelist; - @barcodelist = map { barcodedecode( $_ ) } @barcodelist; + @barcodelist = map { barcodedecode($_) } @barcodelist; # Note: adding lc for case insensitivity - my %itemdata = map { lc($_->{barcode}) => $_->{itemnumber} } @{ Koha::Items->search({ barcode => { -in => \@barcodelist } }, { columns => [ 'itemnumber', 'barcode' ] } )->unblessed }; - @itemnumbers = map { exists $itemdata{lc $_} ? $itemdata{lc $_} : () } @barcodelist; - @notfoundbarcodes = grep { !exists $itemdata{lc $_} } @barcodelist; + my %itemdata = map { lc( $_->{barcode} ) => $_->{itemnumber} } @{ Koha::Items->search( + { barcode => { -in => \@barcodelist } }, { columns => [ 'itemnumber', 'barcode' ] } + )->unblessed + }; + @itemnumbers = map { exists $itemdata{ lc $_ } ? $itemdata{ lc $_ } : () } @barcodelist; + @notfoundbarcodes = grep { !exists $itemdata{ lc $_ } } @barcodelist; } } # Flag to tell the template there are valid results, hidden or not - if(scalar(@itemnumbers) > 0){ $template->param("itemresults" => 1); } + if ( scalar(@itemnumbers) > 0 ) { $template->param( "itemresults" => 1 ); } + # Only display the items if there are no more than pref MaxItemsToProcessForBatchMod or MaxItemsToDisplayForBatchDel - my $max_display_items = $del + my $max_display_items = + $del ? C4::Context->preference("MaxItemsToDisplayForBatchDel") : C4::Context->preference("MaxItemsToDisplayForBatchMod"); - $template->param("too_many_items_process" => scalar(@itemnumbers)) if !$del && scalar(@itemnumbers) > C4::Context->preference("MaxItemsToProcessForBatchMod"); - if (scalar(@itemnumbers) <= ( $max_display_items // 1000 ) ) { + $template->param( "too_many_items_process" => scalar(@itemnumbers) ) + if !$del && scalar(@itemnumbers) > C4::Context->preference("MaxItemsToProcessForBatchMod"); + if ( scalar(@itemnumbers) <= ( $max_display_items // 1000 ) ) { $display_items = 1; } else { - $template->param("too_many_items_display" => scalar(@itemnumbers)); + $template->param( "too_many_items_display" => scalar(@itemnumbers) ); + # Even if we do not display the items, we need the itemnumbers - $template->param(itemnumbers_array => \@itemnumbers); + $template->param( itemnumbers_array => \@itemnumbers ); } # now, build the item form for entering a new item # Getting list of subfields to keep when restricted batchmod edit is enabled - my @subfields_to_allow = $restrictededition ? split ' ', C4::Context->preference('SubfieldsToAllowForRestrictedBatchmod') : (); + my @subfields_to_allow = + $restrictededition + ? split ' ', C4::Context->preference('SubfieldsToAllowForRestrictedBatchmod') + : (); - my $subfields = Koha::UI::Form::Builder::Item->new->edit_form( # NOTE: We are not passing a biblionumber intentionally ! + my $subfields = + Koha::UI::Form::Builder::Item->new->edit_form( # NOTE: We are not passing a biblionumber intentionally ! { restricted_editition => $restrictededition, ( @@ -287,7 +291,7 @@ if ($op eq "cud-show" || $op eq "show"){ branch_limit => C4::Context->userenv->{"branch"}, default_branches_empty => 1, } - ); + ); # what's the next op ? it's what we are not in : an add if we're editing, otherwise, and edit. $template->param( @@ -295,16 +299,15 @@ if ($op eq "cud-show" || $op eq "show"){ notfoundbarcodes => \@notfoundbarcodes, notfounditemnumbers => \@notfounditemnumbers ); - $nextop="cud-action"; + $nextop = "cud-action"; $template->param( show => 1 ); -} # -- End action="cud-show" +} # -- End action="cud-show" -if ( $display_items ) { +if ($display_items) { my $items_table = - Koha::UI::Table::Builder::Items->new( { itemnumbers => \@itemnumbers } ) - ->build_table( { patron => $patron } );; + Koha::UI::Table::Builder::Items->new( { itemnumbers => \@itemnumbers } )->build_table( { patron => $patron } ); $template->param( - items => $items_table->{items}, + items => $items_table->{items}, item_header_loop => $items_table->{headers}, ); } diff --git a/tools/batch_delete_records.pl b/tools/batch_delete_records.pl index ea4a5a9ba4..b5fec31cce 100755 --- a/tools/batch_delete_records.pl +++ b/tools/batch_delete_records.pl @@ -24,9 +24,9 @@ use CGI; use List::MoreUtils qw( uniq ); use Try::Tiny; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Biblio; use C4::AuthoritiesMarc; use Koha::Acquisition::Orders; @@ -39,23 +39,26 @@ use Koha::BackgroundJob::BatchDeleteBiblio; use Koha::BackgroundJob::BatchDeleteAuthority; my $input = CGI->new; -my $op = $input->param('op') // q|form|; -my $recordtype = $input->param('recordtype') // 'biblio'; +my $op = $input->param('op') // q|form|; +my $recordtype = $input->param('recordtype') // 'biblio'; my $skip_open_orders = $input->param('skip_open_orders') // 0; -my ($template, $loggedinuser, $cookie) = get_template_and_user({ +my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { template_name => 'tools/batch_delete_records.tt', - query => $input, - type => "intranet", + query => $input, + type => "intranet", flagsrequired => { tools => 'records_batchdel' }, -}); + } +); my @records; my @messages; if ( $op eq 'form' ) { + # Display the form $template->param( - op => 'form', + op => 'form', lists => Koha::Virtualshelves->search( [ { public => 0, owner => $loggedinuser }, @@ -64,13 +67,16 @@ if ( $op eq 'form' ) { ) ); } elsif ( $op eq 'cud-list' ) { + # List all records to process my @record_ids; if ( my $bib_list = $input->param('bib_list') ) { + # Come from the basket @record_ids = split /\//, $bib_list; $recordtype = 'biblio'; } elsif ( my $uploadfile = $input->param('uploadfile') ) { + # A file of id is given binmode $uploadfile, ':encoding(UTF-8)'; while ( my $content = <$uploadfile> ) { @@ -79,34 +85,37 @@ if ( $op eq 'form' ) { push @record_ids, $content if $content; } } elsif ( my $shelf_number = $input->param('shelf_number') ) { - my $shelf = Koha::Virtualshelves->find($shelf_number); + my $shelf = Koha::Virtualshelves->find($shelf_number); my $contents = $shelf->get_contents; while ( my $content = $contents->next ) { my $biblionumber = $content->biblionumber; push @record_ids, $biblionumber; } } else { + # The user enters manually the list of id push @record_ids, split( /\s\n/, scalar $input->param('recordnumber_list') ); } for my $record_id ( uniq @record_ids ) { if ( $recordtype eq 'biblio' ) { + # Retrieve biblio information - my $biblio_object = Koha::Biblios->find( $record_id ); - unless ( $biblio_object ) { + my $biblio_object = Koha::Biblios->find($record_id); + unless ($biblio_object) { push @messages, { - type => 'warning', - code => 'biblio_not_exists', + type => 'warning', + code => 'biblio_not_exists', biblionumber => $record_id, }; next; } my $biblio = $biblio_object->unblessed; my $record = $biblio_object->metadata->record; - $biblio->{itemnumbers} = [Koha::Items->search({ biblionumber => $record_id })->get_column('itemnumber')]; - $biblio->{holds_count} = $biblio_object->holds->count; - $biblio->{issues_count} = C4::Biblio::CountItemsIssued( $record_id ); + $biblio->{itemnumbers} = + [ Koha::Items->search( { biblionumber => $record_id } )->get_column('itemnumber') ]; + $biblio->{holds_count} = $biblio_object->holds->count; + $biblio->{issues_count} = C4::Biblio::CountItemsIssued($record_id); $biblio->{subscriptions_count} = $biblio_object->subscriptions->count; # Respect skip_open_orders @@ -117,51 +126,53 @@ if ( $op eq 'form' ) { push @records, $biblio; } else { + # Retrieve authority information - my $authority = C4::AuthoritiesMarc::GetAuthority( $record_id ); - unless ( $authority ) { + my $authority = C4::AuthoritiesMarc::GetAuthority($record_id); + unless ($authority) { push @messages, { - type => 'warning', - code => 'authority_not_exists', + type => 'warning', + code => 'authority_not_exists', authid => $record_id, }; next; } $authority = { - authid => $record_id, - summary => C4::AuthoritiesMarc::BuildSummary( $authority, $record_id ), - count_usage => Koha::Authorities->get_usage_count({ authid => $record_id }), + authid => $record_id, + summary => C4::AuthoritiesMarc::BuildSummary( $authority, $record_id ), + count_usage => Koha::Authorities->get_usage_count( { authid => $record_id } ), }; push @records, $authority; } } $template->param( records => \@records, - op => 'list', + op => 'list', ); } elsif ( $op eq 'cud-delete' ) { + # We want to delete selected records! my @record_ids = $input->multi_param('record_id'); try { my $params = { - record_ids => \@record_ids, + record_ids => \@record_ids, }; my $job_id = - $recordtype eq 'biblio' - ? Koha::BackgroundJob::BatchDeleteBiblio->new->enqueue($params) - : Koha::BackgroundJob::BatchDeleteAuthority->new->enqueue($params); + $recordtype eq 'biblio' + ? Koha::BackgroundJob::BatchDeleteBiblio->new->enqueue($params) + : Koha::BackgroundJob::BatchDeleteAuthority->new->enqueue($params); $template->param( - op => 'enqueued', + op => 'enqueued', job_id => $job_id, ); } catch { push @messages, { - type => 'error', - code => 'cannot_enqueue_job', + type => 'error', + code => 'cannot_enqueue_job', error => $_, }; $template->param( view => 'errors' ); @@ -169,7 +180,7 @@ if ( $op eq 'form' ) { } $template->param( - messages => \@messages, + messages => \@messages, recordtype => $recordtype, ); diff --git a/tools/batch_extend_due_dates.pl b/tools/batch_extend_due_dates.pl index 42bff8b46c..abc504288a 100755 --- a/tools/batch_extend_due_dates.pl +++ b/tools/batch_extend_due_dates.pl @@ -22,22 +22,22 @@ use Modern::Perl; use CGI; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use Koha::Checkouts; use Koha::DateUtils qw( dt_from_string ); use Koha::Items; -my $input = CGI->new; -my $op = $input->param('op') // q|form|; +my $input = CGI->new; +my $op = $input->param('op') // q|form|; my $preview_results = $input->param('preview_results'); my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => 'tools/batch_extend_due_dates.tt', - query => $input, - type => "intranet", - flagsrequired => { tools => 'batch_extend_due_dates' }, + template_name => 'tools/batch_extend_due_dates.tt', + query => $input, + type => "intranet", + flagsrequired => { tools => 'batch_extend_due_dates' }, } ); @@ -45,8 +45,7 @@ my @issue_ids; if ( $op eq 'form' ) { $template->param( view => 'form', ); -} -elsif ( $op eq 'cud-list' ) { +} elsif ( $op eq 'cud-list' ) { my @categorycodes = $input->multi_param('categorycodes'); my @itemtypecodes = $input->multi_param('itemtypecodes'); @@ -75,40 +74,34 @@ elsif ( $op eq 'cud-list' ) { if ( $from_due_date and $to_due_date ) { my $to_due_date_endday = dt_from_string($to_due_date); - $to_due_date_endday - ->set( # We set last second of day to see all checkouts from that day + $to_due_date_endday->set( # We set last second of day to see all checkouts from that day hour => 23, minute => 59, second => 59 - ); + ); $search_params->{'me.date_due'} = { -between => [ $dtf->format_datetime( dt_from_string($from_due_date) ), $dtf->format_datetime($to_due_date_endday), ] }; - } - elsif ($from_due_date) { + } elsif ($from_due_date) { $search_params->{'me.date_due'} = - { '>=' => $dtf->format_datetime( dt_from_string($from_due_date) ) }; - } - elsif ($to_due_date) { + { '>=' => $dtf->format_datetime( dt_from_string($from_due_date) ) }; + } elsif ($to_due_date) { my $to_due_date_endday = dt_from_string($to_due_date); - $to_due_date_endday - ->set( # We set last second of day to see all checkouts from that day + $to_due_date_endday->set( # We set last second of day to see all checkouts from that day hour => 23, minute => 59, second => 59 - ); + ); $search_params->{'me.date_due'} = - { '<=' => $dtf->format_datetime($to_due_date_endday) }; + { '<=' => $dtf->format_datetime($to_due_date_endday) }; } my $checkouts = Koha::Checkouts->search( $search_params, - { - join => [ 'item', 'patron' ] - } + { join => [ 'item', 'patron' ] } ); my @new_due_dates; @@ -118,7 +111,7 @@ elsif ( $op eq 'cud-list' ) { @new_due_dates, calc_new_due_date( { - due_date => dt_from_string( $checkout->date_due ), + due_date => dt_from_string( $checkout->date_due ), new_hard_due_date => $new_hard_due_date, add_days => $due_date_days } @@ -129,13 +122,13 @@ elsif ( $op eq 'cud-list' ) { } } - if ( $preview_results ) { + if ($preview_results) { $template->param( checkouts => $checkouts, new_hard_due_date => $new_hard_due_date, - due_date_days => $due_date_days, - new_due_dates => \@new_due_dates, - view => 'list', + due_date_days => $due_date_days, + new_due_dates => \@new_due_dates, + view => 'list', ); } else { $op = 'cud-modify'; @@ -153,11 +146,11 @@ if ( $op eq 'cud-modify' ) { $new_hard_due_date &&= dt_from_string($new_hard_due_date); my $checkouts = - Koha::Checkouts->search( { issue_id => { -in => \@issue_ids } } ); + Koha::Checkouts->search( { issue_id => { -in => \@issue_ids } } ); while ( my $checkout = $checkouts->next ) { my $new_due_date = calc_new_due_date( { - due_date => dt_from_string($checkout->date_due), + due_date => dt_from_string( $checkout->date_due ), new_hard_due_date => $new_hard_due_date, add_days => $due_date_days } @@ -183,16 +176,16 @@ sub calc_new_due_date { my $add_days = $params->{add_days}; my $new; - if ( $new_hard_due_date ) { - $new = $new_hard_due_date->clone->set( - hour => $due_date->hour, - minute => $due_date->minute, - second => $due_date->second, - ) - } else { - $new = $due_date->clone->add( days => $add_days ); - } - return $new; + if ($new_hard_due_date) { + $new = $new_hard_due_date->clone->set( + hour => $due_date->hour, + minute => $due_date->minute, + second => $due_date->second, + ); + } else { + $new = $due_date->clone->add( days => $add_days ); + } + return $new; } output_html_with_http_headers $input, $cookie, $template->output; diff --git a/tools/batch_record_modification.pl b/tools/batch_record_modification.pl index b89f67294e..115fdc7553 100755 --- a/tools/batch_record_modification.pl +++ b/tools/batch_record_modification.pl @@ -22,11 +22,11 @@ use Modern::Perl; use CGI; use List::MoreUtils qw( uniq ); -use Try::Tiny qw( catch try ); +use Try::Tiny qw( catch try ); -use C4::Auth qw( get_template_and_user ); -use C4::Output qw( output_html_with_http_headers ); -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); +use C4::Output qw( output_html_with_http_headers ); +use C4::Auth qw( get_template_and_user ); use C4::MarcModificationTemplates qw( GetModificationTemplateActions GetModificationTemplates @@ -40,48 +40,51 @@ use Koha::Virtualshelves; my $input = CGI->new; our $dbh = C4::Context->dbh; -my $op = $input->param('op') // q|form|; +my $op = $input->param('op') // q|form|; my $recordtype = $input->param('recordtype') // 'biblio'; -my $mmtid = $input->param('marc_modification_template_id'); +my $mmtid = $input->param('marc_modification_template_id'); -my ( @messages ); +my (@messages); -my ( $template, $loggedinuser, $cookie ) = get_template_and_user({ +my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { template_name => 'tools/batch_record_modification.tt', - query => $input, - type => "intranet", + query => $input, + type => "intranet", flagsrequired => { tools => 'records_batchmod' }, -}); + } +); my $sessionID = $input->cookie("CGISESSID"); -my @templates = GetModificationTemplates( $mmtid ); -unless ( @templates ) { +my @templates = GetModificationTemplates($mmtid); +unless (@templates) { $op = 'error'; $template->param( - view => 'errors', + view => 'errors', errors => ['no_template_defined'], ); output_html_with_http_headers $input, $cookie, $template->output; exit; } -if ( $mmtid ) { - my @actions = GetModificationTemplateActions( $mmtid ); - unless ( @actions ) { +if ($mmtid) { + my @actions = GetModificationTemplateActions($mmtid); + unless (@actions) { $op = 'form'; push @messages, { - type => 'error', - code => 'no_action_defined_for_the_template', + type => 'error', + code => 'no_action_defined_for_the_template', mmtid => $mmtid, }; } } if ( $op eq 'form' ) { + # Display the form $template->param( - view => 'form', + view => 'form', lists => Koha::Virtualshelves->search( [ { public => 0, owner => $loggedinuser }, @@ -90,13 +93,16 @@ if ( $op eq 'form' ) { ) ); } elsif ( $op eq 'cud-list' ) { + # List all records to process my ( @records, @record_ids ); if ( my $bib_list = $input->param('bib_list') ) { + # Come from the basket @record_ids = split /\//, $bib_list; $recordtype = 'biblio'; } elsif ( my $uploadfile = $input->param('uploadfile') ) { + # A file of id is given binmode $uploadfile, ':encoding(UTF-8)'; while ( my $content = <$uploadfile> ) { @@ -105,59 +111,63 @@ if ( $op eq 'form' ) { push @record_ids, $content if $content; } } elsif ( my $shelf_number = $input->param('shelf_number') ) { - my $shelf = Koha::Virtualshelves->find($shelf_number); + my $shelf = Koha::Virtualshelves->find($shelf_number); my $contents = $shelf->get_contents; while ( my $content = $contents->next ) { my $biblionumber = $content->biblionumber; push @record_ids, $biblionumber; } } else { + # The user enters manually the list of id push @record_ids, split( /\s\n/, scalar $input->param('recordnumber_list') ); } for my $record_id ( uniq @record_ids ) { if ( $recordtype eq 'biblio' ) { + # Retrieve biblio information - my $biblio = Koha::Biblios->find( $record_id ); - unless ( $biblio ) { + my $biblio = Koha::Biblios->find($record_id); + unless ($biblio) { push @messages, { - type => 'warning', - code => 'biblio_not_exists', + type => 'warning', + code => 'biblio_not_exists', biblionumber => $record_id, }; next; } push @records, $biblio; } else { + # Retrieve authority information - my $authority = Koha::MetadataRecord::Authority->get_from_authid( $record_id ); - unless ( $authority ) { + my $authority = Koha::MetadataRecord::Authority->get_from_authid($record_id); + unless ($authority) { push @messages, { - type => 'warning', - code => 'authority_not_exists', + type => 'warning', + code => 'authority_not_exists', authid => $record_id, }; next; } push @records, { - authid => $record_id, + authid => $record_id, summary => C4::AuthoritiesMarc::BuildSummary( $authority->record, $record_id ), }; } } $template->param( records => \@records, - mmtid => $mmtid, - view => 'list', + mmtid => $mmtid, + view => 'list', ); } elsif ( $op eq 'cud-modify' ) { + # We want to modify selected records! my @record_ids = $input->multi_param('record_id'); try { - my $patron = Koha::Patrons->find( $loggedinuser ); + my $patron = Koha::Patrons->find($loggedinuser); my $params = { mmtid => $mmtid, record_ids => \@record_ids, @@ -169,18 +179,18 @@ if ( $op eq 'form' ) { }; my $job_id = - $recordtype eq 'biblio' - ? Koha::BackgroundJob::BatchUpdateBiblio->new->enqueue($params) - : Koha::BackgroundJob::BatchUpdateAuthority->new->enqueue($params); + $recordtype eq 'biblio' + ? Koha::BackgroundJob::BatchUpdateBiblio->new->enqueue($params) + : Koha::BackgroundJob::BatchUpdateAuthority->new->enqueue($params); $template->param( - view => 'enqueued', + view => 'enqueued', job_id => $job_id, ); } catch { push @messages, { - type => 'error', - code => 'cannot_enqueue_job', + type => 'error', + code => 'cannot_enqueue_job', error => $_, }; $template->param( view => 'errors' ); @@ -188,8 +198,8 @@ if ( $op eq 'form' ) { } $template->param( - messages => \@messages, - recordtype => $recordtype, + messages => \@messages, + recordtype => $recordtype, MarcModificationTemplatesLoop => \@templates, ); diff --git a/tools/batch_records_ajax.pl b/tools/batch_records_ajax.pl index bcf97e06bd..1a7130a54a 100755 --- a/tools/batch_records_ajax.pl +++ b/tools/batch_records_ajax.pl @@ -31,21 +31,21 @@ the records from an import batch. use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use JSON qw( to_json ); use C4::Context; -use C4::Auth qw( check_cookie_auth ); +use C4::Auth qw( check_cookie_auth ); use C4::ImportBatch qw( GetImportBatch GetImportRecordsRange GetImportRecordMatches ); my $input = CGI->new; -my @sort_columns = - qw/import_record_id title status overlay_status overlay_status/; +my @sort_columns = qw/import_record_id title status overlay_status overlay_status/; + +my $import_batch_id = $input->param('import_batch_id'); +my $offset = $input->param('start'); +my $results_per_page = $input->param('length'); -my $import_batch_id = $input->param('import_batch_id'); -my $offset = $input->param('start'); -my $results_per_page = $input->param('length'); # FIXME We handle sorting on one column only! my $sorting_column = $sort_columns[ $input->param('order[0][column]') // 0 ]; my $sorting_direction = $input->param('order[0][dir]'); @@ -55,16 +55,17 @@ $results_per_page = undef if $results_per_page && $results_per_page == -1; binmode STDOUT, ":encoding(UTF-8)"; print $input->header( -type => 'text/plain', -charset => 'UTF-8' ); -my ( $auth_status ) = - check_cookie_auth( $input->cookie('CGISESSID'), { tools => 'manage_staged_marc' } ); +my ($auth_status) = + check_cookie_auth( $input->cookie('CGISESSID'), { tools => 'manage_staged_marc' } ); if ( $auth_status ne "ok" ) { exit 0; } -my $batch = GetImportBatch($import_batch_id); -my $records = - GetImportRecordsRange( $import_batch_id, $offset, $results_per_page, undef, - { order_by => $sorting_column, order_by_direction => $sorting_direction } ); +my $batch = GetImportBatch($import_batch_id); +my $records = GetImportRecordsRange( + $import_batch_id, $offset, $results_per_page, undef, + { order_by => $sorting_column, order_by_direction => $sorting_direction } +); my @list = (); foreach my $record (@$records) { my $citation = $record->{'title'} || $record->{'authorized_heading'}; @@ -72,16 +73,15 @@ foreach my $record (@$records) { my $matches = GetImportRecordMatches( $record->{'import_record_id'} ); my $match_id; if ( scalar @$matches > 0 ) { - foreach my $match (@$matches){ - my $match_citation = ''; + foreach my $match (@$matches) { + my $match_citation = ''; if ( $match->{'record_type'} eq 'biblio' ) { $match_citation .= $match->{'title'} - if defined( $match->{'title'} ); + if defined( $match->{'title'} ); $match_citation .= ' ' . $match->{'author'} - if defined( $match->{'author'} ); + if defined( $match->{'author'} ); $match->{'match_citation'} = $match_citation; - } - elsif ( $match->{'record_type'} eq 'auth' ) { + } elsif ( $match->{'record_type'} eq 'auth' ) { if ( defined( $match->{'authorized_heading'} ) ) { $match_citation .= $match->{'authorized_heading'}; $match->{'match_citation'} = $match_citation; @@ -91,22 +91,24 @@ foreach my $record (@$records) { } push @list, - { - DT_RowId => $record->{'import_record_id'}, + { + DT_RowId => $record->{'import_record_id'}, import_record_id => $record->{'import_record_id'}, - citation => $citation, - author => $record->{'author'}, - issn => $record->{'issn'}, - isbn => $record->{'isbn'}, - status => $record->{'status'}, - overlay_status => $record->{'overlay_status'}, - matched => $record->{'matched_biblionumber'} - || $record->{'matched_authid'} - || q{}, - score => scalar @$matches > 0 ? $matches->[0]->{'score'} : 0, - matches => $matches, - diff_url => $match_id ? "/cgi-bin/koha/tools/showdiffmarc.pl?batchid=$import_batch_id&importid=$record->{import_record_id}&id=$match_id&type=$record->{record_type}" : undef - }; + citation => $citation, + author => $record->{'author'}, + issn => $record->{'issn'}, + isbn => $record->{'isbn'}, + status => $record->{'status'}, + overlay_status => $record->{'overlay_status'}, + matched => $record->{'matched_biblionumber'} + || $record->{'matched_authid'} + || q{}, + score => scalar @$matches > 0 ? $matches->[0]->{'score'} : 0, + matches => $matches, + diff_url => $match_id + ? "/cgi-bin/koha/tools/showdiffmarc.pl?batchid=$import_batch_id&importid=$record->{import_record_id}&id=$match_id&type=$record->{record_type}" + : undef + }; } my $data = { diff --git a/tools/cleanborrowers.pl b/tools/cleanborrowers.pl index 2da6fbca0f..40cfb71847 100755 --- a/tools/cleanborrowers.pl +++ b/tools/cleanborrowers.pl @@ -33,9 +33,9 @@ This script allows to do 2 things. use Modern::Perl; -use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); -use C4::Output qw( output_html_with_http_headers ); +use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); +use C4::Output qw( output_html_with_http_headers ); use C4::Members qw( GetBorrowersToExpunge ); use Koha::DateUtils qw( dt_from_string ); @@ -55,27 +55,28 @@ my $params = $cgi->Vars; my $step = $params->{step} || 1; my $not_borrowed_since = # the date which filter on issue history. - $params->{not_borrowed_since}; -my $last_issue_date = # the date which filter on borrowers last issue. - $params->{last_issue_date}; -my $patron_list_id = $params->{patron_list_id}; + $params->{not_borrowed_since}; +my $last_issue_date = # the date which filter on borrowers last issue. + $params->{last_issue_date}; +my $patron_list_id = $params->{patron_list_id}; my $borrower_dateexpiry = $params->{borrower_dateexpiry}; -my $borrower_lastseen = $params->{borrower_lastseen}; +my $borrower_lastseen = $params->{borrower_lastseen}; my $borrower_categorycode = $params->{'borrower_categorycode'} || q{}; # getting the template my ( $template, $loggedinuser, $cookie ) = get_template_and_user( - { template_name => "tools/cleanborrowers.tt", - query => $cgi, - type => "intranet", - flagsrequired => { tools => 'delete_anonymize_patrons', catalogue => 1 }, + { + template_name => "tools/cleanborrowers.tt", + query => $cgi, + type => "intranet", + flagsrequired => { tools => 'delete_anonymize_patrons', catalogue => 1 }, } ); -my $branch = $params->{ branch } || '*'; +my $branch = $params->{branch} || '*'; $template->param( current_branch => $branch ); -$template->param( OnlyMine => C4::Context->only_my_library ); +$template->param( OnlyMine => C4::Context->only_my_library ); if ( $step == 2 ) { @@ -84,33 +85,32 @@ if ( $step == 2 ) { my $patrons_to_delete; if ( $checkboxes{borrower} ) { $patrons_to_delete = GetBorrowersToExpunge( - _get_selection_params( - $not_borrowed_since, - $borrower_dateexpiry, - $borrower_lastseen, - $borrower_categorycode, - $patron_list_id, - $branch - ) + _get_selection_params( + $not_borrowed_since, + $borrower_dateexpiry, + $borrower_lastseen, + $borrower_categorycode, + $patron_list_id, + $branch + ) ); } _skip_borrowers_with_nonzero_balance($patrons_to_delete); my $patrons_to_anonymize = - $checkboxes{issue} - ? $branch eq '*' - ? Koha::Patrons->search_patrons_to_anonymise( { before => $last_issue_date } ) - : Koha::Patrons->search_patrons_to_anonymise( { before => $last_issue_date, library => $branch } ) - : undef; + $checkboxes{issue} + ? $branch eq '*' + ? Koha::Patrons->search_patrons_to_anonymise( { before => $last_issue_date } ) + : Koha::Patrons->search_patrons_to_anonymise( { before => $last_issue_date, library => $branch } ) + : undef; $template->param( patrons_to_delete => $patrons_to_delete, patrons_to_anonymize => $patrons_to_anonymize, patron_list_id => $patron_list_id, ); -} -elsif ( $op eq 'cud-delete' && $step == 3 ) { +} elsif ( $op eq 'cud-delete' && $step == 3 ) { my $do_delete = $params->{'do_delete'}; my $do_anonym = $params->{'do_anonym'}; @@ -119,15 +119,15 @@ elsif ( $op eq 'cud-delete' && $step == 3 ) { # delete members if ($do_delete) { my $patrons_to_delete = GetBorrowersToExpunge( - _get_selection_params( - $not_borrowed_since, - $borrower_dateexpiry, - $borrower_lastseen, - $borrower_categorycode, - $patron_list_id, - $branch - ) - ); + _get_selection_params( + $not_borrowed_since, + $borrower_dateexpiry, + $borrower_lastseen, + $borrower_categorycode, + $patron_list_id, + $branch + ) + ); _skip_borrowers_with_nonzero_balance($patrons_to_delete); $totalDel = scalar(@$patrons_to_delete); @@ -135,7 +135,7 @@ elsif ( $op eq 'cud-delete' && $step == 3 ) { for ( my $i = 0 ; $i < $totalDel ; $i++ ) { $radio eq 'testrun' && last; my $borrowernumber = $patrons_to_delete->[$i]->{'borrowernumber'}; - my $patron = Koha::Patrons->find($borrowernumber); + my $patron = Koha::Patrons->find($borrowernumber); $radio eq 'trash' && $patron->move_to_deleted; $patron->delete; } @@ -147,37 +147,35 @@ elsif ( $op eq 'cud-delete' && $step == 3 ) { # Anonymising all members if ($do_anonym) { + #FIXME: anonymisation errors are not handled - my $rows = Koha::Old::Checkouts - ->filter_by_anonymizable - ->filter_by_last_update({ - to => dt_from_string($last_issue_date), timestamp_column_name => 'returndate' }) - ->anonymize; + my $rows = Koha::Old::Checkouts->filter_by_anonymizable->filter_by_last_update( + { to => dt_from_string($last_issue_date), timestamp_column_name => 'returndate' } )->anonymize; $template->param( - do_anonym => $rows, + do_anonym => $rows, ); } $template->param( - trash => ( $radio eq "trash" ) ? (1) : (0), - testrun => ( $radio eq "testrun" ) ? 1: 0, + trash => ( $radio eq "trash" ) ? (1) : (0), + testrun => ( $radio eq "testrun" ) ? 1 : 0, ); -} else { # $step == 1 +} else { # $step == 1 my @all_lists = GetPatronLists(); my @non_empty_lists; - foreach my $list (@all_lists){ - my @patrons = $list->patron_list_patrons(); - if( scalar @patrons ) { push(@non_empty_lists,$list) } + foreach my $list (@all_lists) { + my @patrons = $list->patron_list_patrons(); + if ( scalar @patrons ) { push( @non_empty_lists, $list ) } } - $template->param( patron_lists => [ @non_empty_lists ] ); + $template->param( patron_lists => [@non_empty_lists] ); } -my $patron_categories = Koha::Patron::Categories->search_with_library_limits({}, {order_by => ['description']}); +my $patron_categories = Koha::Patron::Categories->search_with_library_limits( {}, { order_by => ['description'] } ); $template->param( step => $step, - not_borrowed_since => $not_borrowed_since, + not_borrowed_since => $not_borrowed_since, borrower_dateexpiry => $borrower_dateexpiry, borrower_lastseen => $borrower_lastseen, last_issue_date => $last_issue_date, @@ -192,26 +190,28 @@ sub _skip_borrowers_with_nonzero_balance { my $borrowers = shift; my $balance; @$borrowers = map { - my $patron = Koha::Patrons->find( $_->{borrowernumber} ); + my $patron = Koha::Patrons->find( $_->{borrowernumber} ); my $balance = $patron->account->balance; - (defined $balance && $balance != 0) ? (): ($_); + ( defined $balance && $balance != 0 ) ? () : ($_); } @$borrowers; } sub _get_selection_params { - my ($not_borrowed_since, $borrower_dateexpiry, $borrower_lastseen, - $borrower_categorycode, $patron_list_id, $branch) = @_; + my ( + $not_borrowed_since, $borrower_dateexpiry, $borrower_lastseen, + $borrower_categorycode, $patron_list_id, $branch + ) = @_; my $params = {}; $params->{not_borrowed_since} = $not_borrowed_since; - $params->{expired_before} = $borrower_dateexpiry; - $params->{last_seen} = $borrower_lastseen; - $params->{category_code} = $borrower_categorycode if $borrower_categorycode; - $params->{patron_list_id} = $patron_list_id if $patron_list_id; + $params->{expired_before} = $borrower_dateexpiry; + $params->{last_seen} = $borrower_lastseen; + $params->{category_code} = $borrower_categorycode if $borrower_categorycode; + $params->{patron_list_id} = $patron_list_id if $patron_list_id; if ( defined $branch and $branch ne '*' ) { - $params->{ branchcode } = $branch; + $params->{branchcode} = $branch; } return $params; -}; +} diff --git a/tools/copy-holidays.pl b/tools/copy-holidays.pl index e77449e12d..ffdb659f02 100755 --- a/tools/copy-holidays.pl +++ b/tools/copy-holidays.pl @@ -24,20 +24,19 @@ use CGI qw ( -utf8 ); use C4::Auth qw( checkauth ); use C4::Output; - use C4::Calendar; -my $input = CGI->new; -my $op = $input->param('op') // q{}; -my $dbh = C4::Context->dbh(); +my $input = CGI->new; +my $op = $input->param('op') // q{}; +my $dbh = C4::Context->dbh(); -checkauth($input, 0, {tools=> 'edit_calendar'}, 'intranet'); +checkauth( $input, 0, { tools => 'edit_calendar' }, 'intranet' ); -my $branchcode = $input->param('branchcode'); -my $from_branchcode = $input->param('from_branchcode'); +my $branchcode = $input->param('branchcode'); +my $from_branchcode = $input->param('from_branchcode'); if ( $op eq 'cud-copy' ) { C4::Calendar->new( branchcode => $from_branchcode )->copy_to_branch($branchcode) if $from_branchcode && $branchcode; } -print $input->redirect("/cgi-bin/koha/tools/holidays.pl?branch=".($branchcode || $from_branchcode)); +print $input->redirect( "/cgi-bin/koha/tools/holidays.pl?branch=" . ( $branchcode || $from_branchcode ) ); diff --git a/tools/csv-profiles.pl b/tools/csv-profiles.pl index 12344f5a3e..420a811c7f 100755 --- a/tools/csv-profiles.pl +++ b/tools/csv-profiles.pl @@ -40,7 +40,7 @@ use Encode; use C4::Auth qw( get_template_and_user ); use C4::Context; use C4::Output qw( output_html_with_http_headers ); -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use Koha::CsvProfiles; my $input = CGI->new; @@ -49,10 +49,11 @@ my $op = $input->param('op') || 'list'; my @messages; my ( $template, $loggedinuser, $cookie ) = get_template_and_user( - { template_name => "tools/csv-profiles.tt", - query => $input, - type => "intranet", - flagsrequired => { tools => 'manage_csv_profiles' }, + { + template_name => "tools/csv-profiles.tt", + query => $input, + type => "intranet", + flagsrequired => { tools => 'manage_csv_profiles' }, } ); @@ -69,14 +70,14 @@ if ( $op eq 'add_form' ) { my $profile = $input->param("profile"); my $description = $input->param("description"); my $type = $input->param("type"); - my $used_for = - $type eq "marc" - ? $input->param("used_for_marc") - : $input->param("used_for_sql"); + my $used_for = + $type eq "marc" + ? $input->param("used_for_marc") + : $input->param("used_for_sql"); my $content = - $type eq "marc" - ? $input->param("marc_content") - : $input->param("sql_content"); + $type eq "marc" + ? $input->param("marc_content") + : $input->param("sql_content"); my $csv_separator = $input->param("csv_separator"); my $field_separator = $input->param("field_separator"); my $subfield_separator = $input->param("subfield_separator"); @@ -105,7 +106,8 @@ if ( $op eq 'add_form' ) { } } else { my $csv_profile = Koha::CsvProfile->new( - { profile => $profile, + { + profile => $profile, description => $description, content => $content, csv_separator => $csv_separator, @@ -130,7 +132,7 @@ if ( $op eq 'add_form' ) { $template->param( csv_profile => $csv_profile, ); } elsif ( $op eq 'cud-delete_confirmed' ) { my $csv_profile = Koha::CsvProfiles->find($export_format_id); - my $deleted = eval { $csv_profile->delete; }; + my $deleted = eval { $csv_profile->delete; }; if ( $@ or not $deleted ) { push @messages, { type => 'error', code => 'error_on_delete' }; diff --git a/tools/exceptionHolidays.pl b/tools/exceptionHolidays.pl index f538638c45..e00b26bc8d 100755 --- a/tools/exceptionHolidays.pl +++ b/tools/exceptionHolidays.pl @@ -15,78 +15,83 @@ my $input = CGI->new; my $op = $input->param('op') // q{}; my $dbh = C4::Context->dbh(); -checkauth($input, 0, {tools=> 'edit_calendar'}, 'intranet'); - +checkauth( $input, 0, { tools => 'edit_calendar' }, 'intranet' ); our $branchcode = $input->param('showBranchName'); -my $originalbranchcode = $branchcode; -our $weekday = $input->param('showWeekday'); -our $day = $input->param('showDay'); -our $month = $input->param('showMonth'); -our $year = $input->param('showYear'); -our $title = $input->param('showTitle'); +my $originalbranchcode = $branchcode; +our $weekday = $input->param('showWeekday'); +our $day = $input->param('showDay'); +our $month = $input->param('showMonth'); +our $year = $input->param('showYear'); +our $title = $input->param('showTitle'); our $description = $input->param('showDescription'); our $holidaytype = $input->param('showHolidayType'); my $datecancelrange_dt = eval { dt_from_string( scalar $input->param('datecancelrange') ) }; -my $calendardate = sprintf("%04d-%02d-%02d", $year, $month, $day); +my $calendardate = sprintf( "%04d-%02d-%02d", $year, $month, $day ); our $showoperation = $input->param('showOperation'); my $allbranches = $input->param('allBranches'); -$title || ($title = ''); +$title || ( $title = '' ); if ($description) { $description =~ s/\r/\\r/g; $description =~ s/\n/\\n/g; } else { $description = ''; -} +} # We make an array with holiday's days our @holiday_list; -if ($datecancelrange_dt){ - my $first_dt = DateTime->new(year => $year, month => $month, day => $day); +if ($datecancelrange_dt) { + my $first_dt = DateTime->new( year => $year, month => $month, day => $day ); - for (my $dt = $first_dt->clone(); - $dt <= $datecancelrange_dt; - $dt->add(days => 1) ) - { - push @holiday_list, $dt->clone(); - } + for ( my $dt = $first_dt->clone() ; $dt <= $datecancelrange_dt ; $dt->add( days => 1 ) ) { + push @holiday_list, $dt->clone(); + } } if ( $op eq 'cud-edit' && $allbranches ) { my $libraries = Koha::Libraries->search; while ( my $library = $libraries->next ) { - edit_holiday($showoperation, $library->branchcode, $weekday, $day, $month, $year, $title, $description, $holidaytype, @holiday_list); + edit_holiday( + $showoperation, $library->branchcode, $weekday, $day, $month, $year, $title, $description, + $holidaytype, @holiday_list + ); } -} elsif( $op eq 'cud-edit' ) { - edit_holiday($showoperation, $branchcode, $weekday, $day, $month, $year, $title, $description, $holidaytype, @holiday_list); +} elsif ( $op eq 'cud-edit' ) { + edit_holiday( + $showoperation, $branchcode, $weekday, $day, $month, $year, $title, $description, $holidaytype, + @holiday_list + ); } print $input->redirect("/cgi-bin/koha/tools/holidays.pl?branch=$originalbranchcode&calendardate=$calendardate"); sub edit_holiday { - ($showoperation, $branchcode, $weekday, $day, $month, $year, $title, $description, $holidaytype, @holiday_list) = @_; - my $calendar = C4::Calendar->new(branchcode => $branchcode); + ( $showoperation, $branchcode, $weekday, $day, $month, $year, $title, $description, $holidaytype, @holiday_list ) = + @_; + my $calendar = C4::Calendar->new( branchcode => $branchcode ); - if ($showoperation eq 'exception') { - $calendar->insert_exception_holiday(day => $day, - month => $month, - year => $year, - title => $title, - description => $description); - } elsif ($showoperation eq 'exceptionrange' ) { - if (@holiday_list){ - foreach my $date (@holiday_list){ - $calendar->insert_exception_holiday( - day => $date->{local_c}->{day}, - month => $date->{local_c}->{month}, - year => $date->{local_c}->{year}, - title => $title, - description => $description - ); - } + if ( $showoperation eq 'exception' ) { + $calendar->insert_exception_holiday( + day => $day, + month => $month, + year => $year, + title => $title, + description => $description + ); + } elsif ( $showoperation eq 'exceptionrange' ) { + if (@holiday_list) { + foreach my $date (@holiday_list) { + $calendar->insert_exception_holiday( + day => $date->{local_c}->{day}, + month => $date->{local_c}->{month}, + year => $date->{local_c}->{year}, + title => $title, + description => $description + ); } - } elsif ($showoperation eq 'cud-edit') { + } + } elsif ( $showoperation eq 'cud-edit' ) { if ( $holidaytype eq 'weekday' ) { my $isHoliday = $calendar->isHoliday( $day, $month, $year ); if ($isHoliday) { @@ -95,16 +100,14 @@ sub edit_holiday { title => $title, description => $description ); - } - else { + } else { $calendar->insert_week_day_holiday( weekday => $weekday, title => $title, description => $description ); } - } - elsif ( $holidaytype eq 'daymonth' ) { + } elsif ( $holidaytype eq 'daymonth' ) { my $isHoliday = $calendar->isHoliday( $day, $month, $year ); if ($isHoliday) { $calendar->ModDaymonthholiday( @@ -113,8 +116,7 @@ sub edit_holiday { title => $title, description => $description ); - } - else { + } else { $calendar->insert_day_month_holiday( day => $day, month => $month, @@ -122,8 +124,7 @@ sub edit_holiday { description => $description ); } - } - elsif ( $holidaytype eq 'ymd' ) { + } elsif ( $holidaytype eq 'ymd' ) { my $isHoliday = $calendar->isHoliday( $day, $month, $year ); if ($isHoliday) { $calendar->ModSingleholiday( @@ -133,8 +134,7 @@ sub edit_holiday { title => $title, description => $description ); - } - else { + } else { $calendar->insert_single_holiday( day => $day, month => $month, @@ -143,8 +143,7 @@ sub edit_holiday { description => $description ); } - } - elsif ( $holidaytype eq 'exception' ) { + } elsif ( $holidaytype eq 'exception' ) { my $isHoliday = $calendar->isHoliday( $day, $month, $year ); if ($isHoliday) { $calendar->ModExceptionholiday( @@ -154,8 +153,7 @@ sub edit_holiday { title => $title, description => $description ); - } - else { + } else { $calendar->insert_exception_holiday( day => $day, month => $month, @@ -165,35 +163,43 @@ sub edit_holiday { ); } } - } elsif ($showoperation eq 'cud-delete') { - $calendar->delete_holiday(weekday => $weekday, - day => $day, - month => $month, - year => $year); - }elsif ($showoperation eq 'deleterange') { - if (@holiday_list){ - foreach my $date (@holiday_list){ - $calendar->delete_holiday_range(weekday => $weekday, - day => $date->{local_c}->{day}, - month => $date->{local_c}->{month}, - year => $date->{local_c}->{year}); - } - } - }elsif ($showoperation eq 'deleterangerepeat') { - if (@holiday_list){ - foreach my $date (@holiday_list){ - $calendar->delete_holiday_range_repeatable(weekday => $weekday, - day => $date->{local_c}->{day}, - month => $date->{local_c}->{month}); + } elsif ( $showoperation eq 'cud-delete' ) { + $calendar->delete_holiday( + weekday => $weekday, + day => $day, + month => $month, + year => $year + ); + } elsif ( $showoperation eq 'deleterange' ) { + if (@holiday_list) { + foreach my $date (@holiday_list) { + $calendar->delete_holiday_range( + weekday => $weekday, + day => $date->{local_c}->{day}, + month => $date->{local_c}->{month}, + year => $date->{local_c}->{year} + ); } } - }elsif ($showoperation eq 'deleterangerepeatexcept') { - if (@holiday_list){ - foreach my $date (@holiday_list){ - $calendar->delete_exception_holiday_range(weekday => $weekday, - day => $date->{local_c}->{day}, - month => $date->{local_c}->{month}, - year => $date->{local_c}->{year}); + } elsif ( $showoperation eq 'deleterangerepeat' ) { + if (@holiday_list) { + foreach my $date (@holiday_list) { + $calendar->delete_holiday_range_repeatable( + weekday => $weekday, + day => $date->{local_c}->{day}, + month => $date->{local_c}->{month} + ); + } + } + } elsif ( $showoperation eq 'deleterangerepeatexcept' ) { + if (@holiday_list) { + foreach my $date (@holiday_list) { + $calendar->delete_exception_holiday_range( + weekday => $weekday, + day => $date->{local_c}->{day}, + month => $date->{local_c}->{month}, + year => $date->{local_c}->{year} + ); } } } diff --git a/tools/export.pl b/tools/export.pl index 0c1a8fc184..922e9b2185 100755 --- a/tools/export.pl +++ b/tools/export.pl @@ -20,8 +20,8 @@ use Modern::Perl; use CGI qw ( -utf8 ); use MARC::File::XML; use List::MoreUtils qw( uniq ); -use C4::Auth qw( get_template_and_user ); -use C4::Output qw( output_html_with_http_headers ); +use C4::Auth qw( get_template_and_user ); +use C4::Output qw( output_html_with_http_headers ); use Koha::Authority::Types; use Koha::Biblioitems; @@ -36,7 +36,7 @@ my $query = CGI->new; my $dont_export_items = $query->param("dont_export_item") || 0; my $record_type = $query->param("record_type"); -my $op = $query->param("op") || ''; +my $op = $query->param("op") || ''; my $output_format = $query->param("format") || $query->param("output_format") || 'iso2709'; my $backupdir = C4::Context->config('backupdir'); my $filename; @@ -50,23 +50,25 @@ $filename =~ s/(\r|\n)//; my $dbh = C4::Context->dbh; my @record_ids; + # biblionumbers is sent from circulation.pl only if ( $query->param("biblionumbers") ) { $record_type = 'bibs'; - @record_ids = $query->multi_param("biblionumbers"); + @record_ids = $query->multi_param("biblionumbers"); } # Default value for output_format is 'iso2709' $output_format ||= 'iso2709'; + # Retrocompatibility for the format parameter $output_format = 'iso2709' if $output_format eq 'marc'; my ( $template, $loggedinuser, $cookie, $flags ) = get_template_and_user( { - template_name => "tools/export.tt", - query => $query, - type => "intranet", - flagsrequired => { tools => 'export_catalog' }, + template_name => "tools/export.tt", + query => $query, + type => "intranet", + flagsrequired => { tools => 'export_catalog' }, } ); @@ -75,8 +77,8 @@ my @branch = $query->multi_param("branch"); my @messages; if ( $op eq 'cud-export' ) { my $filename = $query->param('id_list_file'); - if ( $filename ) { - my $mimetype = $query->uploadInfo($filename)->{'Content-Type'}; + if ($filename) { + my $mimetype = $query->uploadInfo($filename)->{'Content-Type'}; my @valid_mimetypes = qw( application/octet-stream text/csv text/plain application/vnd.ms-excel ); unless ( grep { $_ eq $mimetype } @valid_mimetypes ) { push @messages, { type => 'alert', code => 'invalid_mimetype' }; @@ -87,102 +89,104 @@ if ( $op eq 'cud-export' ) { if ( $op eq "cud-export" ) { - my $export_remove_fields = $query->param("export_remove_fields") || q||; - my @biblionumbers = $query->multi_param("biblionumbers"); - my @itemnumbers = $query->multi_param("itemnumbers"); - my $strip_items_not_from_libraries = $query->param('strip_items_not_from_libraries'); + my $export_remove_fields = $query->param("export_remove_fields") || q||; + my @biblionumbers = $query->multi_param("biblionumbers"); + my @itemnumbers = $query->multi_param("itemnumbers"); + my $strip_items_not_from_libraries = $query->param('strip_items_not_from_libraries'); - my $libraries = Koha::Libraries->search_filtered->unblessed; + my $libraries = Koha::Libraries->search_filtered->unblessed; my $only_export_items_for_branches = $strip_items_not_from_libraries ? \@branch : undef; my @branchcodes; - for my $branchcode ( @branch ) { + for my $branchcode (@branch) { if ( grep { $_->{branchcode} eq $branchcode } @$libraries ) { push @branchcodes, $branchcode; } } if ( $record_type eq 'bibs' or $record_type eq 'auths' ) { + # No need to retrieve the record_ids if we already get them - unless ( @record_ids ) { + unless (@record_ids) { if ( $record_type eq 'bibs' ) { my %it_map = map { $_->itemtype => 1 } Koha::ItemTypes->search->as_list; - my @itemtypes = map { $it_map{$_} ? $_ : () } $query->multi_param('itemtype'); #Validate inputs against map + my @itemtypes = + map { $it_map{$_} ? $_ : () } $query->multi_param('itemtype'); #Validate inputs against map my $starting_biblionumber = $query->param("StartingBiblionumber"); my $ending_biblionumber = $query->param("EndingBiblionumber"); - my $start_callnumber = $query->param("start_callnumber"); - my $end_callnumber = $query->param("end_callnumber"); + my $start_callnumber = $query->param("start_callnumber"); + my $end_callnumber = $query->param("end_callnumber"); my $start_accession = - ( $query->param("start_accession") ) - ? dt_from_string( scalar $query->param("start_accession") ) - : ''; + ( $query->param("start_accession") ) + ? dt_from_string( scalar $query->param("start_accession") ) + : ''; my $end_accession = - ( $query->param("end_accession") ) - ? dt_from_string( scalar $query->param("end_accession") ) - : ''; - + ( $query->param("end_accession") ) + ? dt_from_string( scalar $query->param("end_accession") ) + : ''; my $conditions = { ( $starting_biblionumber or $ending_biblionumber ) - ? ( - "me.biblionumber" => { - ( $starting_biblionumber ? ( '>=' => $starting_biblionumber ) : () ), - ( $ending_biblionumber ? ( '<=' => $ending_biblionumber ) : () ), - } + ? ( + "me.biblionumber" => { + ( $starting_biblionumber ? ( '>=' => $starting_biblionumber ) : () ), + ( $ending_biblionumber ? ( '<=' => $ending_biblionumber ) : () ), + } ) - : (), + : (), ( $start_callnumber or $end_callnumber ) - ? ( - 'items.itemcallnumber' => { - ( $start_callnumber ? ( '>=' => $start_callnumber ) : () ), - ( $end_callnumber ? ( '<=' => $end_callnumber ) : () ), - } + ? ( + 'items.itemcallnumber' => { + ( $start_callnumber ? ( '>=' => $start_callnumber ) : () ), + ( $end_callnumber ? ( '<=' => $end_callnumber ) : () ), + } ) - : (), + : (), ( $start_accession or $end_accession ) - ? ( - 'items.dateaccessioned' => { - ( $start_accession ? ( '>=' => $start_accession ) : () ), - ( $end_accession ? ( '<=' => $end_accession ) : () ), - } + ? ( + 'items.dateaccessioned' => { + ( $start_accession ? ( '>=' => $start_accession ) : () ), + ( $end_accession ? ( '<=' => $end_accession ) : () ), + } ) - : (), + : (), ( @branchcodes ? ( 'items.homebranch' => { in => \@branchcodes } ) : () ), - ( @itemtypes - ? - C4::Context->preference('item-level_itypes') - ? ( 'items.itype' => { in => \@itemtypes } ) - : ( 'me.itemtype' => { in => \@itemtypes } ) + ( + @itemtypes + ? C4::Context->preference('item-level_itypes') + ? ( 'items.itype' => { in => \@itemtypes } ) + : ( 'me.itemtype' => { in => \@itemtypes } ) : () ), }; - my $biblioitems = Koha::Biblioitems->search( $conditions, { join => 'items', columns => 'biblionumber' } ); + my $biblioitems = + Koha::Biblioitems->search( $conditions, { join => 'items', columns => 'biblionumber' } ); while ( my $biblioitem = $biblioitems->next ) { push @record_ids, $biblioitem->biblionumber; } - } - elsif ( $record_type eq 'auths' ) { + } elsif ( $record_type eq 'auths' ) { my $starting_authid = $query->param('starting_authid'); my $ending_authid = $query->param('ending_authid'); my $authtype = $query->param('authtype'); my $conditions = { ( $starting_authid or $ending_authid ) - ? ( - authid => { - ( $starting_authid ? ( '>=' => $starting_authid ) : () ), - ( $ending_authid ? ( '<=' => $ending_authid ) : () ), - } + ? ( + authid => { + ( $starting_authid ? ( '>=' => $starting_authid ) : () ), + ( $ending_authid ? ( '<=' => $ending_authid ) : () ), + } ) - : (), + : (), ( $authtype ? ( authtypecode => $authtype ) : () ), }; + # Koha::MetadataRecord::Authority is not a Koha::Object... - my $authorities = Koha::Database->new->schema->resultset('AuthHeader')->search( $conditions ); + my $authorities = Koha::Database->new->schema->resultset('AuthHeader')->search($conditions); @record_ids = map { $_->authid } $authorities->all; } } @@ -191,21 +195,22 @@ if ( $op eq "cud-export" ) { if ( @record_ids and my $filefh = $query->upload("id_list_file") ) { my @filter_record_ids = <$filefh>; @filter_record_ids = map { my $id = $_; $id =~ s/[\r\n]*$//; $id } @filter_record_ids; + # intersection my %record_ids = map { $_ => 1 } @record_ids; @record_ids = grep $record_ids{$_}, @filter_record_ids; } my $export_items_bundle_contents = $query->param('export_items_bundle_contents'); - if ($export_items_bundle_contents and $record_type eq 'bibs') { - my $schema = Koha::Database->new->schema; + if ( $export_items_bundle_contents and $record_type eq 'bibs' ) { + my $schema = Koha::Database->new->schema; my $items_bundle_rs = $schema->resultset('ItemBundle'); foreach my $itemnumber (@itemnumbers) { - my @item_bundle_items = $items_bundle_rs->search({ host => $itemnumber }); + my @item_bundle_items = $items_bundle_rs->search( { host => $itemnumber } ); foreach my $item_bundle_item (@item_bundle_items) { my $biblionumber = $item_bundle_item->item->get_column('biblionumber'); - my $itemnumber = $item_bundle_item->get_column('item'); - push @record_ids, $biblionumber; + my $itemnumber = $item_bundle_item->get_column('item'); + push @record_ids, $biblionumber; push @itemnumbers, $itemnumber; } } @@ -220,28 +225,27 @@ if ( $op eq "cud-export" ) { my $csv_profile_id = $query->param('csv_profile_id'); Koha::Exporter::Record::export( - { record_type => $record_type, - record_ids => \@record_ids, - format => $output_format, - filename => $filename, - itemnumbers => \@itemnumbers, - dont_export_fields => $export_remove_fields, - csv_profile_id => $csv_profile_id, - export_items => (not $dont_export_items), + { + record_type => $record_type, + record_ids => \@record_ids, + format => $output_format, + filename => $filename, + itemnumbers => \@itemnumbers, + dont_export_fields => $export_remove_fields, + csv_profile_id => $csv_profile_id, + export_items => ( not $dont_export_items ), only_export_items_for_branches => $only_export_items_for_branches, } ); - } - elsif ( $record_type eq 'db' or $record_type eq 'conf' ) { + } elsif ( $record_type eq 'db' or $record_type eq 'conf' ) { my $successful_export; - if ( $flags->{superlibrarian} - and ( - $record_type eq 'db' and C4::Context->config('backup_db_via_tools') - or - $record_type eq 'conf' and C4::Context->config('backup_conf_via_tools') + if ( + $flags->{superlibrarian} + and ( $record_type eq 'db' and C4::Context->config('backup_db_via_tools') + or $record_type eq 'conf' and C4::Context->config('backup_conf_via_tools') ) ) - ) { + { binmode STDOUT, ':encoding(UTF-8)'; my $charset = 'utf-8'; @@ -250,8 +254,7 @@ if ( $op eq "cud-export" ) { $mimetype = 'application/x-gzip'; $charset = ''; binmode STDOUT; - } - elsif ( $filename =~ m/\.bz2$/ ) { + } elsif ( $filename =~ m/\.bz2$/ ) { $mimetype = 'application/x-bzip2'; binmode STDOUT; $charset = ''; @@ -274,24 +277,24 @@ if ( $op eq "cud-export" ) { unless ($successful_export) { my $remotehost = $query->remote_host(); $remotehost =~ s/(\n|\r)//; - warn - "A suspicious attempt was made to download the " . ( $record_type eq 'db' ? 'db' : 'configuration' ) . "at '$filename' by someone at " - . $remotehost . "\n"; + warn "A suspicious attempt was made to download the " + . ( $record_type eq 'db' ? 'db' : 'configuration' ) + . "at '$filename' by someone at " + . $remotehost . "\n"; } } } exit; -} -else { +} else { my $itemtypes = Koha::ItemTypes->search_with_localization; my $authority_types = Koha::Authority::Types->search( {}, { order_by => ['authtypecode'] } ); - my $libraries = Koha::Libraries->search_filtered({}, { order_by => ['branchname'] })->unblessed; - for my $library ( @$libraries ) { + my $libraries = Koha::Libraries->search_filtered( {}, { order_by => ['branchname'] } )->unblessed; + for my $library (@$libraries) { $library->{selected} = 1 if grep { $library->{branchcode} eq $_ } @branch; } @@ -301,8 +304,7 @@ else { && -d $backupdir ) { $template->{VARS}->{'allow_db_export'} = 1; - $template->{VARS}->{'dbfiles'} = getbackupfilelist( - { directory => "$backupdir", extension => 'sql' } ); + $template->{VARS}->{'dbfiles'} = getbackupfilelist( { directory => "$backupdir", extension => 'sql' } ); } if ( $flags->{superlibrarian} @@ -311,17 +313,16 @@ else { && -d $backupdir ) { $template->{VARS}->{'allow_conf_export'} = 1; - $template->{VARS}->{'conffiles'} = getbackupfilelist( - { directory => "$backupdir", extension => 'tar' } ); + $template->{VARS}->{'conffiles'} = getbackupfilelist( { directory => "$backupdir", extension => 'tar' } ); } $template->param( - libraries => $libraries, - itemtypes => $itemtypes, - authority_types => $authority_types, - export_remove_fields => C4::Context->preference("ExportRemoveFields"), - csv_profiles => [ Koha::CsvProfiles->search({ type => 'marc', used_for => 'export_records' })->as_list ], - messages => \@messages, + libraries => $libraries, + itemtypes => $itemtypes, + authority_types => $authority_types, + export_remove_fields => C4::Context->preference("ExportRemoveFields"), + csv_profiles => [ Koha::CsvProfiles->search( { type => 'marc', used_for => 'export_records' } )->as_list ], + messages => \@messages, ); output_html_with_http_headers $query, $cookie, $template->output; @@ -337,7 +338,7 @@ sub getbackupfilelist { while ( my $file = readdir($dir) ) { next unless ( $file =~ m/\.$extension(\.(gz|bz2|xz))?/ ); push @files, $file - if ( -f "$directory/$file" && -r "$directory/$file" ); + if ( -f "$directory/$file" && -r "$directory/$file" ); } closedir($dir); } diff --git a/tools/holidays.pl b/tools/holidays.pl index 49bd19915f..feac8e8abf 100755 --- a/tools/holidays.pl +++ b/tools/holidays.pl @@ -20,7 +20,7 @@ use Modern::Perl; use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use C4::Calendar; @@ -29,102 +29,115 @@ use Koha::DateUtils qw( dt_from_string output_pref ); my $input = CGI->new; my $dbh = C4::Context->dbh(); + # Get the template to use -my ($template, $loggedinuser, $cookie) - = get_template_and_user({template_name => "tools/holidays.tt", - type => "intranet", - query => $input, - flagsrequired => {tools => 'edit_calendar'}, - }); +my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "tools/holidays.tt", + type => "intranet", + query => $input, + flagsrequired => { tools => 'edit_calendar' }, + } +); # calendardate - date passed in url for human readability (syspref) # if the url has an invalid date default to 'now.' # FIXME There is something to improve in the date handling here my $calendarinput_dt = eval { dt_from_string( scalar $input->param('calendardate') ); } || dt_from_string; -my $calendardate = output_pref( { dt => $calendarinput_dt, dateonly => 1 } ); +my $calendardate = output_pref( { dt => $calendarinput_dt, dateonly => 1 } ); # keydate - date passed to calendar.js. calendar.js does not process dashes within a date. my $keydate = output_pref( { dt => $calendarinput_dt, dateonly => 1, dateformat => 'iso' } ); $keydate =~ s/-/\//g; -my $branch= $input->param('branch') || C4::Context->userenv->{'branch'}; +my $branch = $input->param('branch') || C4::Context->userenv->{'branch'}; # Get all the holidays -my $calendar = C4::Calendar->new(branchcode => $branch); +my $calendar = C4::Calendar->new( branchcode => $branch ); my $week_days_holidays = $calendar->get_week_days_holidays(); my @week_days; -foreach my $weekday (keys %$week_days_holidays) { -# warn "WEEK DAY : $weekday"; +foreach my $weekday ( keys %$week_days_holidays ) { + + # warn "WEEK DAY : $weekday"; my %week_day; - %week_day = (KEY => $weekday, - TITLE => $week_days_holidays->{$weekday}{title}, - DESCRIPTION => $week_days_holidays->{$weekday}{description}); + %week_day = ( + KEY => $weekday, + TITLE => $week_days_holidays->{$weekday}{title}, + DESCRIPTION => $week_days_holidays->{$weekday}{description} + ); push @week_days, \%week_day; } my $day_month_holidays = $calendar->get_day_month_holidays(); my @day_month_holidays; -foreach my $monthDay (keys %$day_month_holidays) { +foreach my $monthDay ( keys %$day_month_holidays ) { + # Determine date format on month and day. my $day_monthdate; my $day_monthdate_sort; - if (C4::Context->preference("dateformat") eq "metric") { - $day_monthdate_sort = "$day_month_holidays->{$monthDay}{month}-$day_month_holidays->{$monthDay}{day}"; - $day_monthdate = "$day_month_holidays->{$monthDay}{day}/$day_month_holidays->{$monthDay}{month}"; - } elsif (C4::Context->preference("dateformat") eq "dmydot") { - $day_monthdate_sort = "$day_month_holidays->{$monthDay}{month}.$day_month_holidays->{$monthDay}{day}"; - $day_monthdate = "$day_month_holidays->{$monthDay}{day}.$day_month_holidays->{$monthDay}{month}"; - }elsif (C4::Context->preference("dateformat") eq "us") { - $day_monthdate = "$day_month_holidays->{$monthDay}{month}/$day_month_holidays->{$monthDay}{day}"; - $day_monthdate_sort = $day_monthdate; + if ( C4::Context->preference("dateformat") eq "metric" ) { + $day_monthdate_sort = "$day_month_holidays->{$monthDay}{month}-$day_month_holidays->{$monthDay}{day}"; + $day_monthdate = "$day_month_holidays->{$monthDay}{day}/$day_month_holidays->{$monthDay}{month}"; + } elsif ( C4::Context->preference("dateformat") eq "dmydot" ) { + $day_monthdate_sort = "$day_month_holidays->{$monthDay}{month}.$day_month_holidays->{$monthDay}{day}"; + $day_monthdate = "$day_month_holidays->{$monthDay}{day}.$day_month_holidays->{$monthDay}{month}"; + } elsif ( C4::Context->preference("dateformat") eq "us" ) { + $day_monthdate = "$day_month_holidays->{$monthDay}{month}/$day_month_holidays->{$monthDay}{day}"; + $day_monthdate_sort = $day_monthdate; } else { - $day_monthdate = "$day_month_holidays->{$monthDay}{month}-$day_month_holidays->{$monthDay}{day}"; - $day_monthdate_sort = $day_monthdate; + $day_monthdate = "$day_month_holidays->{$monthDay}{month}-$day_month_holidays->{$monthDay}{day}"; + $day_monthdate_sort = $day_monthdate; } my %day_month; - %day_month = (KEY => $monthDay, - DATE_SORT => $day_monthdate_sort, - DATE => $day_monthdate, - TITLE => $day_month_holidays->{$monthDay}{title}, - DESCRIPTION => $day_month_holidays->{$monthDay}{description}); + %day_month = ( + KEY => $monthDay, + DATE_SORT => $day_monthdate_sort, + DATE => $day_monthdate, + TITLE => $day_month_holidays->{$monthDay}{title}, + DESCRIPTION => $day_month_holidays->{$monthDay}{description} + ); push @day_month_holidays, \%day_month; } my $exception_holidays = $calendar->get_exception_holidays(); my @exception_holidays; -foreach my $yearMonthDay (keys %$exception_holidays) { +foreach my $yearMonthDay ( keys %$exception_holidays ) { my $exceptiondate = eval { dt_from_string( $exception_holidays->{$yearMonthDay}{date} ) }; my %exception_holiday; - %exception_holiday = (KEY => $yearMonthDay, - DATE_SORT => $exception_holidays->{$yearMonthDay}{date}, - DATE => output_pref( { dt => $exceptiondate, dateonly => 1 } ), - TITLE => $exception_holidays->{$yearMonthDay}{title}, - DESCRIPTION => $exception_holidays->{$yearMonthDay}{description}); + %exception_holiday = ( + KEY => $yearMonthDay, + DATE_SORT => $exception_holidays->{$yearMonthDay}{date}, + DATE => output_pref( { dt => $exceptiondate, dateonly => 1 } ), + TITLE => $exception_holidays->{$yearMonthDay}{title}, + DESCRIPTION => $exception_holidays->{$yearMonthDay}{description} + ); push @exception_holidays, \%exception_holiday; } my $single_holidays = $calendar->get_single_holidays(); my @holidays; -foreach my $yearMonthDay (keys %$single_holidays) { +foreach my $yearMonthDay ( keys %$single_holidays ) { my $holidaydate_dt = eval { dt_from_string( $single_holidays->{$yearMonthDay}{date} ) }; my %holiday; - %holiday = (KEY => $yearMonthDay, - DATE_SORT => $single_holidays->{$yearMonthDay}{date}, - DATE => output_pref( { dt => $holidaydate_dt, dateonly => 1 } ), - TITLE => $single_holidays->{$yearMonthDay}{title}, - DESCRIPTION => $single_holidays->{$yearMonthDay}{description}); + %holiday = ( + KEY => $yearMonthDay, + DATE_SORT => $single_holidays->{$yearMonthDay}{date}, + DATE => output_pref( { dt => $holidaydate_dt, dateonly => 1 } ), + TITLE => $single_holidays->{$yearMonthDay}{title}, + DESCRIPTION => $single_holidays->{$yearMonthDay}{description} + ); push @holidays, \%holiday; } $template->param( - WEEK_DAYS_LOOP => \@week_days, - HOLIDAYS_LOOP => \@holidays, - EXCEPTION_HOLIDAYS_LOOP => \@exception_holidays, - DAY_MONTH_HOLIDAYS_LOOP => \@day_month_holidays, - calendardate => $calendardate, - keydate => $keydate, - branch => $branch, + WEEK_DAYS_LOOP => \@week_days, + HOLIDAYS_LOOP => \@holidays, + EXCEPTION_HOLIDAYS_LOOP => \@exception_holidays, + DAY_MONTH_HOLIDAYS_LOOP => \@day_month_holidays, + calendardate => $calendardate, + keydate => $keydate, + branch => $branch, ); # Shows the template with the real values replaced diff --git a/tools/import_borrowers.pl b/tools/import_borrowers.pl index 3b091d17b3..38a20ca486 100755 --- a/tools/import_borrowers.pl +++ b/tools/import_borrowers.pl @@ -36,7 +36,7 @@ use Modern::Perl; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_and_exit output_html_with_http_headers ); use Koha::Database::Columns; use Koha::Patrons; @@ -65,22 +65,23 @@ my $op = $input->param('op') // q{}; my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "tools/import_borrowers.tt", - query => $input, - type => "intranet", - flagsrequired => { tools => 'import_patrons' }, + template_name => "tools/import_borrowers.tt", + query => $input, + type => "intranet", + flagsrequired => { tools => 'import_patrons' }, } ); # get the patron categories and pass them to the template -my @patron_categories = Koha::Patron::Categories->search_with_library_limits({}, {order_by => ['description']})->as_list; -$template->param( categories => \@patron_categories ); +my @patron_categories = + Koha::Patron::Categories->search_with_library_limits( {}, { order_by => ['description'] } )->as_list; +$template->param( categories => \@patron_categories ); $template->param( borrower_fields => Koha::Database::Columns->columns->{borrowers} ); if ( $input->param('sample') ) { our $csv = Text::CSV->new( { binary => 1, formula => 'empty' } ); # binary needed for non-ASCII Unicode print $input->header( - -type => 'application/vnd.sun.xml.calc', # 'application/vnd.ms-excel' ? + -type => 'application/vnd.sun.xml.calc', # 'application/vnd.ms-excel' ? -attachment => 'patron_import.csv', ); $csv->combine(@columnkeys); @@ -99,17 +100,17 @@ if ($matchpoint) { #create a patronlist my $createpatronlist = $input->param('createpatronlist') || 0; -my $dt = dt_from_string(); -my $timestamp = $dt->ymd('-').' '.$dt->hms(':'); -my $patronlistname = $uploadborrowers . ' (' . $timestamp .')'; +my $dt = dt_from_string(); +my $timestamp = $dt->ymd('-') . ' ' . $dt->hms(':'); +my $patronlistname = $uploadborrowers . ' (' . $timestamp . ')'; if ( $op eq 'cud-import' && $uploadborrowers && length($uploadborrowers) > 0 ) { - my $handle = $input->upload('uploadborrowers'); - my %defaults = $input->Vars; + my $handle = $input->upload('uploadborrowers'); + my %defaults = $input->Vars; my $overwrite_passwords = defined $input->param('overwrite_passwords') ? 1 : 0; - my $update_dateexpiry = $input->param('update_dateexpiry'); - my $return = $Import->import_patrons( + my $update_dateexpiry = $input->param('update_dateexpiry'); + my $return = $Import->import_patrons( { file => $handle, defaults => \%defaults, @@ -118,25 +119,25 @@ if ( $op eq 'cud-import' && $uploadborrowers && length($uploadborrowers) > 0 ) { overwrite_passwords => $overwrite_passwords, preserve_extended_attributes => scalar $input->param('ext_preserve') || 0, preserve_fields => \@preserve_fields, - update_dateexpiry => $update_dateexpiry ? 1 : 0, - update_dateexpiry_from_today => $update_dateexpiry eq "now" ? 1 : 0, + update_dateexpiry => $update_dateexpiry ? 1 : 0, + update_dateexpiry_from_today => $update_dateexpiry eq "now" ? 1 : 0, update_dateexpiry_from_existing => $update_dateexpiry eq "dateexpiry" ? 1 : 0, send_welcome => $welcome_new, } ); - my $feedback = $return->{feedback}; - my $errors = $return->{errors}; - my $imported = $return->{imported}; - my $overwritten = $return->{overwritten}; - my $alreadyindb = $return->{already_in_db}; - my $invalid = $return->{invalid}; + my $feedback = $return->{feedback}; + my $errors = $return->{errors}; + my $imported = $return->{imported}; + my $overwritten = $return->{overwritten}; + my $alreadyindb = $return->{already_in_db}; + my $invalid = $return->{invalid}; my $imported_borrowers = $return->{imported_borrowers}; if ( $imported && $createpatronlist ) { - my $patronlist = AddPatronList({ name => $patronlistname }); - AddPatronsToList({ list => $patronlist, borrowernumbers => $imported_borrowers }); - $template->param('patronlistname' => $patronlistname); + my $patronlist = AddPatronList( { name => $patronlistname } ); + AddPatronsToList( { list => $patronlist, borrowernumbers => $imported_borrowers } ); + $template->param( 'patronlistname' => $patronlistname ); } my $uploadinfo = $input->uploadInfo($uploadborrowers); @@ -159,13 +160,13 @@ if ( $op eq 'cud-import' && $uploadborrowers && length($uploadborrowers) > 0 ) { } else { if ($extended) { - my @matchpoints = (); + my @matchpoints = (); my $attribute_types = Koha::Patron::Attribute::Types->search; while ( my $attr_type = $attribute_types->next ) { if ( $attr_type->unique_id() ) { push @matchpoints, - { code => "patron_attribute_" . $attr_type->code(), description => $attr_type->description() }; + { code => "patron_attribute_" . $attr_type->code(), description => $attr_type->description() }; } } $template->param( matchpoints => \@matchpoints ); diff --git a/tools/inventory.pl b/tools/inventory.pl index 05511dd10a..8e735d40e4 100755 --- a/tools/inventory.pl +++ b/tools/inventory.pl @@ -22,18 +22,18 @@ use Modern::Perl; #need to open cgi and get the fh before anything else opens a new cgi context (see C4::Auth) use CGI qw ( -utf8 ); -my $input = CGI->new; +my $input = CGI->new; my $uploadbarcodes = $input->param('uploadbarcodes'); -my $barcodelist = $input->param('barcodelist'); +my $barcodelist = $input->param('barcodelist'); use C4::Auth qw( get_template_and_user ); use C4::Context; -use C4::Output qw( output_html_with_http_headers ); -use C4::Items qw( GetItemsForInventory ); -use C4::Koha qw( GetAuthorisedValues ); -use C4::Circulation qw( barcodedecode AddReturn ); +use C4::Output qw( output_html_with_http_headers ); +use C4::Items qw( GetItemsForInventory ); +use C4::Koha qw( GetAuthorisedValues ); +use C4::Circulation qw( barcodedecode AddReturn ); use C4::Reports::Guided qw( ); -use C4::Charset qw( NormalizeString ); +use C4::Charset qw( NormalizeString ); use Koha::Biblios; use Koha::DateUtils qw( dt_from_string ); @@ -45,66 +45,79 @@ use Koha::Items; use List::MoreUtils qw( none ); -my $minlocation=$input->param('minlocation') || ''; -my $maxlocation=$input->param('maxlocation'); -my $class_source=$input->param('class_source'); -$maxlocation=$minlocation.'Z' unless ( $maxlocation || ! $minlocation ); -my $location=$input->param('location') || ''; -my $ignoreissued=$input->param('ignoreissued'); +my $minlocation = $input->param('minlocation') || ''; +my $maxlocation = $input->param('maxlocation'); +my $class_source = $input->param('class_source'); +$maxlocation = $minlocation . 'Z' unless ( $maxlocation || !$minlocation ); +my $location = $input->param('location') || ''; +my $ignoreissued = $input->param('ignoreissued'); my $ignore_waiting_holds = $input->param('ignore_waiting_holds'); -my $datelastseen = $input->param('datelastseen'); # last inventory date -my $branchcode = $input->param('branchcode') || ''; -my $branch = $input->param('branch'); -my $op = $input->param('op') // q{}; -my $compareinv2barcd = $input->param('compareinv2barcd'); -my $dont_checkin = $input->param('dont_checkin'); -my $out_of_order = $input->param('out_of_order'); -my $ccode = $input->param('ccode'); +my $datelastseen = $input->param('datelastseen'); # last inventory date +my $branchcode = $input->param('branchcode') || ''; +my $branch = $input->param('branch'); +my $op = $input->param('op') // q{}; +my $compareinv2barcd = $input->param('compareinv2barcd'); +my $dont_checkin = $input->param('dont_checkin'); +my $out_of_order = $input->param('out_of_order'); +my $ccode = $input->param('ccode'); my ( $template, $borrowernumber, $cookie ) = get_template_and_user( - { template_name => "tools/inventory.tt", - query => $input, - type => "intranet", - flagsrequired => { tools => 'inventory' }, + { + template_name => "tools/inventory.tt", + query => $input, + type => "intranet", + flagsrequired => { tools => 'inventory' }, } ); my @authorised_value_list; my $authorisedvalue_categories = ''; -my $frameworks = Koha::BiblioFrameworks->search({}, { order_by => ['frameworktext'] })->unblessed; +my $frameworks = Koha::BiblioFrameworks->search( {}, { order_by => ['frameworktext'] } )->unblessed; unshift @$frameworks, { frameworkcode => '' }; -my @collections = (); +my @collections = (); my @collection_codes = (); -for my $fwk ( @$frameworks ){ - my $fwkcode = $fwk->{frameworkcode}; - my $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => $fwkcode, kohafield => 'items.location', authorised_value => [ -and => {'!=' => undef }, {'!=' => ''}] }); - my $authcode = $mss->count ? $mss->next->authorised_value : undef; - if ($authcode && $authorisedvalue_categories!~/\b$authcode\W/){ - $authorisedvalue_categories.="$authcode "; - my $data=GetAuthorisedValues($authcode); - foreach my $value (@$data){ - $value->{selected}=1 if ($value->{authorised_value} eq ($location)); - } - push @authorised_value_list,@$data; +for my $fwk (@$frameworks) { + my $fwkcode = $fwk->{frameworkcode}; + my $mss = Koha::MarcSubfieldStructures->search( + { + frameworkcode => $fwkcode, kohafield => 'items.location', + authorised_value => [ -and => { '!=' => undef }, { '!=' => '' } ] + } + ); + my $authcode = $mss->count ? $mss->next->authorised_value : undef; + if ( $authcode && $authorisedvalue_categories !~ /\b$authcode\W/ ) { + $authorisedvalue_categories .= "$authcode "; + my $data = GetAuthorisedValues($authcode); + foreach my $value (@$data) { + $value->{selected} = 1 if ( $value->{authorised_value} eq ($location) ); + } + push @authorised_value_list, @$data; } } my $statuses = []; my @notforloans; -for my $statfield (qw/items.notforloan items.itemlost items.withdrawn items.damaged/){ +for my $statfield (qw/items.notforloan items.itemlost items.withdrawn items.damaged/) { my $hash = {}; $hash->{fieldname} = $statfield; - my $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => '', kohafield => $statfield, authorised_value => [ -and => {'!=' => undef }, {'!=' => ''}] }); + my $mss = Koha::MarcSubfieldStructures->search( + { + frameworkcode => '', kohafield => $statfield, + authorised_value => [ -and => { '!=' => undef }, { '!=' => '' } ] + } + ); $hash->{authcode} = $mss->count ? $mss->next->authorised_value : undef; - if ($hash->{authcode}){ - my $arr = GetAuthorisedValues($hash->{authcode}); - if ( $statfield eq 'items.notforloan') { + if ( $hash->{authcode} ) { + my $arr = GetAuthorisedValues( $hash->{authcode} ); + if ( $statfield eq 'items.notforloan' ) { + # Add notforloan == 0 to the list of possible notforloan statuses # The lib value is replaced in the template - push @$arr, { authorised_value => 0, id => 'stat0' , lib => '__IGNORE__' } if ! grep { $_->{authorised_value} eq '0' } @$arr; + push @$arr, { authorised_value => 0, id => 'stat0', lib => '__IGNORE__' } + if !grep { $_->{authorised_value} eq '0' } @$arr; @notforloans = map { $_->{'authorised_value'} } @$arr; } $hash->{values} = $arr; @@ -113,12 +126,14 @@ for my $statfield (qw/items.notforloan items.itemlost items.withdrawn items.dama } $template->param( statuses => $statuses ); -my $staton = {}; #authorized values that are ticked +my $staton = {}; #authorized values that are ticked for my $authvfield (@$statuses) { - $staton->{$authvfield->{fieldname}} = []; - for my $authval (@{$authvfield->{values}}){ - if ( defined $input->param('status-' . $authvfield->{fieldname} . '-' . $authval->{authorised_value}) && $input->param('status-' . $authvfield->{fieldname} . '-' . $authval->{authorised_value}) eq 'on' ){ - push @{$staton->{$authvfield->{fieldname}}}, $authval->{authorised_value}; + $staton->{ $authvfield->{fieldname} } = []; + for my $authval ( @{ $authvfield->{values} } ) { + if ( defined $input->param( 'status-' . $authvfield->{fieldname} . '-' . $authval->{authorised_value} ) + && $input->param( 'status-' . $authvfield->{fieldname} . '-' . $authval->{authorised_value} ) eq 'on' ) + { + push @{ $staton->{ $authvfield->{fieldname} } }, $authval->{authorised_value}; } } } @@ -135,36 +150,37 @@ if ( defined $input->param('ReportItemsWithoutProblem') && $input->param('Report # if there's a list of not for loans types selected use it rather than # the full set. -@notforloans = @{$staton->{'items.notforloan'}} if defined $staton->{'items.notforloan'} and scalar @{$staton->{'items.notforloan'}} > 0; +@notforloans = @{ $staton->{'items.notforloan'} } + if defined $staton->{'items.notforloan'} and scalar @{ $staton->{'items.notforloan'} } > 0; -my @class_sources = Koha::ClassSources->search({ used => 1 })->as_list; -my $pref_class = C4::Context->preference("DefaultClassificationSource"); +my @class_sources = Koha::ClassSources->search( { used => 1 } )->as_list; +my $pref_class = C4::Context->preference("DefaultClassificationSource"); my @itemtypes = Koha::ItemTypes->search->as_list; my @selected_itemtypes; -foreach my $itemtype ( @itemtypes ) { - if ( defined $input->param('itemtype-' . $itemtype->itemtype) ) { +foreach my $itemtype (@itemtypes) { + if ( defined $input->param( 'itemtype-' . $itemtype->itemtype ) ) { push @selected_itemtypes, "'" . $itemtype->itemtype . "'"; } } $template->param( - authorised_values => \@authorised_value_list, - today => dt_from_string, - minlocation => $minlocation, - maxlocation => $maxlocation, - location => $location, - ignoreissued => $ignoreissued, - branchcode => $branchcode, - branch => $branch, - datelastseen => $datelastseen, - compareinv2barcd => $compareinv2barcd, - uploadedbarcodesflag => ($uploadbarcodes || $barcodelist) ? 1 : 0, - ignore_waiting_holds => $ignore_waiting_holds, - class_sources => \@class_sources, - pref_class => $pref_class, - itemtypes => \@itemtypes, - ccode => $ccode, + authorised_values => \@authorised_value_list, + today => dt_from_string, + minlocation => $minlocation, + maxlocation => $maxlocation, + location => $location, + ignoreissued => $ignoreissued, + branchcode => $branchcode, + branch => $branch, + datelastseen => $datelastseen, + compareinv2barcd => $compareinv2barcd, + uploadedbarcodesflag => ( $uploadbarcodes || $barcodelist ) ? 1 : 0, + ignore_waiting_holds => $ignore_waiting_holds, + class_sources => \@class_sources, + pref_class => $pref_class, + itemtypes => \@itemtypes, + ccode => $ccode, ); # Walk through uploaded barcodes, report errors, mark as seen, check in @@ -176,27 +192,27 @@ my @lost_items; if ( $op eq 'cud-inventory' && ( ( $uploadbarcodes && length($uploadbarcodes) > 0 ) || ( $barcodelist && length($barcodelist) > 0 ) ) ) { - my $dbh = C4::Context->dbh; - my $date = $input->param('setdate'); + my $dbh = C4::Context->dbh; + my $date = $input->param('setdate'); my $date_dt = dt_from_string($date); my @barcodes; my @uploadedbarcodes; - my $sth = $dbh->column_info(undef,undef,"items","barcode"); - my $barcode_def = $sth->fetchall_hashref('COLUMN_NAME'); + my $sth = $dbh->column_info( undef, undef, "items", "barcode" ); + my $barcode_def = $sth->fetchall_hashref('COLUMN_NAME'); my $barcode_size = $barcode_def->{barcode}->{COLUMN_SIZE}; - my $err_length=0; - my $err_data=0; - my $lines_read=0; - if ($uploadbarcodes && length($uploadbarcodes) > 0) { - binmode($uploadbarcodes, ":encoding(UTF-8)"); - while (my $barcode=<$uploadbarcodes>) { + my $err_length = 0; + my $err_data = 0; + my $lines_read = 0; + if ( $uploadbarcodes && length($uploadbarcodes) > 0 ) { + binmode( $uploadbarcodes, ":encoding(UTF-8)" ); + while ( my $barcode = <$uploadbarcodes> ) { my $split_chars = C4::Context->preference('BarcodeSeparators'); push @uploadedbarcodes, grep { /\S/ } split( /[$split_chars]/, $barcode ); } } else { - push @uploadedbarcodes, split(/\s\n/, scalar $input->param('barcodelist') ); + push @uploadedbarcodes, split( /\s\n/, scalar $input->param('barcodelist') ); $uploadbarcodes = $barcodelist; } for my $barcode (@uploadedbarcodes) { @@ -205,49 +221,52 @@ if ( $op eq 'cud-inventory' $barcode = barcodedecode($barcode); ++$lines_read; - if (length($barcode)>$barcode_size) { + if ( length($barcode) > $barcode_size ) { $err_length += 1; } my $check_barcode = $barcode; $check_barcode =~ s/\p{Print}//g; - if (length($check_barcode)>0) { # Only printable unicode characters allowed. + if ( length($check_barcode) > 0 ) { # Only printable unicode characters allowed. $err_data += 1; } - next if length($barcode)>$barcode_size; - next if ( length($check_barcode)>0 ); - push @barcodes,$barcode; + next if length($barcode) > $barcode_size; + next if ( length($check_barcode) > 0 ); + push @barcodes, $barcode; } $template->param( LinesRead => $lines_read ); - if (! @barcodes) { - push @errorloop, {'barcode'=>'No valid barcodes!'}; - $op=''; # force the initial inventory screen again. - } - else { - $template->param( err_length => $err_length, - err_data => $err_data ); + if ( !@barcodes ) { + push @errorloop, { 'barcode' => 'No valid barcodes!' }; + $op = ''; # force the initial inventory screen again. + } else { + $template->param( + err_length => $err_length, + err_data => $err_data + ); } my @items = Koha::Items->search( { barcode => { -in => \@barcodes } } )->as_list; - my %items = map { lc($_->barcode) => $_ } @items; + my %items = map { lc( $_->barcode ) => $_ } @items; foreach my $barcode (@barcodes) { my $item = $items{ lc($barcode) }; - if ( $item ) { + if ($item) { if ( $item->withdrawn ) { push @errorloop, { 'barcode' => $barcode, 'ERR_WTHDRAWN' => 1 }; next; } + # Modify date last seen for scanned items, remove lost status if ( $item->unblessed->{itemlost} ) { push @lost_items, $barcode; } - $item->set({ itemlost => 0, datelastseen => $date_dt })->store; + $item->set( { itemlost => 0, datelastseen => $date_dt } )->store; my $item_unblessed = $item->unblessed; $moddatecount++; - unless ( $dont_checkin ) { - if ( $item->onloan ){ + unless ($dont_checkin) { + if ( $item->onloan ) { + #TODO Assuming item homebranch for return here. Might allow current branch too? - my ($doreturn, $messages, $iteminformation, $borrower) = AddReturn($barcode, $item->homebranch); - if( $doreturn ) { - $item_unblessed->{onloan} = undef; + my ( $doreturn, $messages, $iteminformation, $borrower ) = AddReturn( $barcode, $item->homebranch ); + if ($doreturn) { + $item_unblessed->{onloan} = undef; $item_unblessed->{datelastseen} = dt_from_string; } else { push @errorloop, { barcode => $barcode, ERR_ONLOAN_NOT_RET => 1 }; @@ -259,65 +278,70 @@ if ( $op eq 'cud-inventory' push @errorloop, { barcode => $barcode, ERR_BARCODE => 1 }; } } - $template->param( date => $date ); + $template->param( date => $date ); $template->param( errorloop => \@errorloop ) if (@errorloop); } # Build inventorylist: used as result list when you do not pass barcodes # This list is also used when you want to compare with barcodes my ( $inventorylist, $rightplacelist ); -if ( $op eq 'cud-inventory' && ( !$uploadbarcodes || $compareinv2barcd )) { - ( $inventorylist ) = GetItemsForInventory({ - minlocation => $minlocation, - maxlocation => $maxlocation, - class_source => $class_source, - location => $location, - ignoreissued => $ignoreissued, - datelastseen => $datelastseen, - branchcode => $branchcode, - branch => $branch, - offset => 0, - statushash => $staton, - ccode => $ccode, - ignore_waiting_holds => $ignore_waiting_holds, - itemtypes => \@selected_itemtypes, - }); +if ( $op eq 'cud-inventory' && ( !$uploadbarcodes || $compareinv2barcd ) ) { + ($inventorylist) = GetItemsForInventory( + { + minlocation => $minlocation, + maxlocation => $maxlocation, + class_source => $class_source, + location => $location, + ignoreissued => $ignoreissued, + datelastseen => $datelastseen, + branchcode => $branchcode, + branch => $branch, + offset => 0, + statushash => $staton, + ccode => $ccode, + ignore_waiting_holds => $ignore_waiting_holds, + itemtypes => \@selected_itemtypes, + } + ); } + # Build rightplacelist used to check if a scanned item is in the right place. -if( @scanned_items ) { +if (@scanned_items) { + # For the items that may be marked as "wrong place", we only check the location (callnumbers, location, ccode and branch) - ( $rightplacelist ) = GetItemsForInventory({ - minlocation => $minlocation, - maxlocation => $maxlocation, - class_source => $class_source, - location => $location, - ignoreissued => undef, - datelastseen => undef, - branchcode => $branchcode, - branch => $branch, - offset => 0, - statushash => undef, - ignore_waiting_holds => $ignore_waiting_holds, - itemtypes => \@selected_itemtypes, - ccode => $ccode, - }); + ($rightplacelist) = GetItemsForInventory( + { + minlocation => $minlocation, + maxlocation => $maxlocation, + class_source => $class_source, + location => $location, + ignoreissued => undef, + datelastseen => undef, + branchcode => $branchcode, + branch => $branch, + offset => 0, + statushash => undef, + ignore_waiting_holds => $ignore_waiting_holds, + itemtypes => \@selected_itemtypes, + ccode => $ccode, + } + ); + # Convert the structure to a hash on barcode - $rightplacelist = { - map { $_->{barcode} ? ( $_->{barcode}, $_ ) : (); } @$rightplacelist - }; + $rightplacelist = { map { $_->{barcode} ? ( $_->{barcode}, $_ ) : (); } @$rightplacelist }; } # Report scanned items that are on the wrong place, or have a wrong notforloan # status, or are still checked out. -for ( my $i = 0; $i < @scanned_items; $i++ ) { +for ( my $i = 0 ; $i < @scanned_items ; $i++ ) { my $item = $scanned_items[$i]; - $item->{notforloancode} = $item->{notforloan}; # save for later use + $item->{notforloancode} = $item->{notforloan}; # save for later use # If we have scanned items with a non-matching notforloan value - if( none { $item->{'notforloancode'} eq $_ } @notforloans ) { + if ( none { $item->{'notforloancode'} eq $_ } @notforloans ) { $item->{problems}->{changestatus} = 1; additemtoresults( $item, $results ); } @@ -341,11 +365,11 @@ for ( my $i = 0; $i < @scanned_items; $i++ ) { } # Report an item that is checked out (unusual!) or wrongly placed - if( $item->{onloan} ) { + if ( $item->{onloan} ) { $item->{problems}->{checkedout} = 1; additemtoresults( $item, $results ); - next; # do not modify item - } elsif( !exists $rightplacelist->{ $item->{barcode} } ) { + next; # do not modify item + } elsif ( !exists $rightplacelist->{ $item->{barcode} } ) { $item->{problems}->{wrongplace} = 1; additemtoresults( $item, $results ); } @@ -363,11 +387,11 @@ for ( my $i = 0; $i < @scanned_items; $i++ ) { # Compare barcodes with inventory list, report no_barcode and not_scanned. # not_scanned can be interpreted as missing -if ( $compareinv2barcd ) { - my @scanned_barcodes = map {$_->{barcode}} @scanned_items; - for my $item ( @$inventorylist ) { +if ($compareinv2barcd) { + my @scanned_barcodes = map { $_->{barcode} } @scanned_items; + for my $item (@$inventorylist) { my $barcode = $item->{barcode}; - if( !$barcode ) { + if ( !$barcode ) { $item->{problems}->{no_barcode} = 1; } elsif ( grep { $_ eq $barcode } @scanned_barcodes ) { next; @@ -379,12 +403,13 @@ if ( $compareinv2barcd ) { } # Construct final results, add biblio information -my $loop = $uploadbarcodes +my $loop = + $uploadbarcodes ? [ map { $results->{$_} } keys %$results ] : $inventorylist // []; -for my $item ( @$loop ) { +for my $item (@$loop) { my $biblio = Koha::Biblios->find( $item->{biblionumber} ); - $item->{title} = $biblio->title; + $item->{title} = $biblio->title; $item->{author} = $biblio->author; } @@ -395,7 +420,7 @@ $template->param( ); # Export to csv -if (defined $input->param('CSVexport') && $input->param('CSVexport') eq 'on'){ +if ( defined $input->param('CSVexport') && $input->param('CSVexport') eq 'on' ) { eval { use Text::CSV (); }; my $csv = Text::CSV->new( { formula => 'empty' } ) or die Text::CSV->error_diag(); @@ -407,40 +432,44 @@ if (defined $input->param('CSVexport') && $input->param('CSVexport') eq 'on'){ my $columns = Koha::Database::Columns->columns; my @translated_keys; - for my $key (qw / biblioitems.title biblio.author - items.barcode items.itemnumber - items.homebranch items.location items.ccode - items.itemcallnumber items.notforloan - items.itemlost items.damaged - items.withdrawn items.stocknumber - / ) { + for my $key ( + qw / biblioitems.title biblio.author + items.barcode items.itemnumber + items.homebranch items.location items.ccode + items.itemcallnumber items.notforloan + items.itemlost items.damaged + items.withdrawn items.stocknumber + / + ) + { my ( $table, $column ) = split '\.', $key; - push @translated_keys, NormalizeString($columns->{$table}->{$column} // ''); + push @translated_keys, NormalizeString( $columns->{$table}->{$column} // '' ); } push @translated_keys, 'Problem' if $uploadbarcodes; $csv->combine(@translated_keys); print $csv->string, "\n"; - my @keys = qw/ title author barcode itemnumber homebranch location ccode itemcallnumber notforloan itemlost damaged withdrawn stocknumber /; - for my $item ( @$loop ) { + my @keys = + qw/ title author barcode itemnumber homebranch location ccode itemcallnumber notforloan itemlost damaged withdrawn stocknumber /; + for my $item (@$loop) { my @line; for my $key (@keys) { push @line, $item->{$key}; } my $errstr = ''; - foreach my $key ( keys %{$item->{problems}} ) { - if( $key eq 'wrongplace' ) { + foreach my $key ( keys %{ $item->{problems} } ) { + if ( $key eq 'wrongplace' ) { $errstr .= "wrong place,"; - } elsif( $key eq 'changestatus' ) { + } elsif ( $key eq 'changestatus' ) { $errstr .= "unselected notforloan status $item->{notforloan},"; - } elsif( $key eq 'not_scanned' ) { + } elsif ( $key eq 'not_scanned' ) { $errstr .= "missing,"; - } elsif( $key eq 'no_barcode' ) { + } elsif ( $key eq 'no_barcode' ) { $errstr .= "no barcode,"; - } elsif( $key eq 'checkedout' ) { + } elsif ( $key eq 'checkedout' ) { $errstr .= "checked out,"; - } elsif( $key eq 'out_of_order' ) { + } elsif ( $key eq 'out_of_order' ) { $errstr .= "shelved out of order,"; } elsif ( $key eq 'lost' ) { $errstr .= "item was lost"; @@ -452,11 +481,12 @@ if (defined $input->param('CSVexport') && $input->param('CSVexport') eq 'on'){ $csv->combine(@line); print $csv->string, "\n"; } + # Adding not found barcodes foreach my $error (@errorloop) { my @line; - if ($error->{'ERR_BARCODE'}) { - push @line, map { $_ eq 'barcode' ? $error->{'barcode'} : ''} @keys; + if ( $error->{'ERR_BARCODE'} ) { + push @line, map { $_ eq 'barcode' ? $error->{'barcode'} : '' } @keys; push @line, "barcode not found"; $csv->combine(@line); print $csv->string, "\n"; diff --git a/tools/letter.pl b/tools/letter.pl index bb552d2cd9..0d409850b9 100755 --- a/tools/letter.pl +++ b/tools/letter.pl @@ -46,46 +46,49 @@ use Try::Tiny; use C4::Auth qw( get_template_and_user ); use C4::Context; -use C4::Output qw( output_html_with_http_headers ); +use C4::Output qw( output_html_with_http_headers ); use C4::Letters qw( GetMessageTransportTypes ); -use C4::Log qw( logaction ); +use C4::Log qw( logaction ); use Koha::Notice::Templates; use Koha::Patron::Attribute::Types; # $protected_letters = protected_letters() # - return a hashref of letter_codes representing letters that should never be deleted sub protected_letters { - my $dbh = C4::Context->dbh; + my $dbh = C4::Context->dbh; my $codes = $dbh->selectall_arrayref(q{SELECT DISTINCT letter_code FROM message_transports}); return { map { $_->[0] => 1 } @{$codes} }; } -our $input = CGI->new; +our $input = CGI->new; my $searchfield = $input->param('searchfield'); -our $branchcode = $input->param('branchcode'); +our $branchcode = $input->param('branchcode'); $branchcode = '' if defined $branchcode and $branchcode eq '*'; -my $code = $input->param('code'); -my $module = $input->param('module') || ''; -my $content = $input->param('content'); -my $op = $input->param('op') || ''; -my $redirect = $input->param('redirect'); -my $section = $input->param('section'); -my $langtab = $input->param('langtab'); +my $code = $input->param('code'); +my $module = $input->param('module') || ''; +my $content = $input->param('content'); +my $op = $input->param('op') || ''; +my $redirect = $input->param('redirect'); +my $section = $input->param('section'); +my $langtab = $input->param('langtab'); my $dbh = C4::Context->dbh; our ( $template, $borrowernumber, $cookie, $staffflags ) = get_template_and_user( { - template_name => 'tools/letter.tt', - query => $input, - type => 'intranet', - flagsrequired => { tools => 'edit_notices' }, + template_name => 'tools/letter.tt', + query => $input, + type => 'intranet', + flagsrequired => { tools => 'edit_notices' }, } ); -our $my_branch = C4::Context->preference("IndependentBranches") && !$staffflags->{'superlibrarian'} - ? C4::Context->userenv()->{'branch'} - : undef; +our $my_branch = + C4::Context->preference("IndependentBranches") + && !$staffflags->{'superlibrarian'} + ? C4::Context->userenv()->{'branch'} + : undef; + # we show only the TMPL_VAR names $op $template->param( @@ -98,51 +101,50 @@ $template->param( if ( $op eq 'cud-add_validate' or $op eq 'cud-copy_validate' ) { add_validate(); - if( $redirect eq "just_save" ){ - print $input->redirect("/cgi-bin/koha/tools/letter.pl?op=add_form&branchcode=$branchcode&module=$module&code=$code&redirect=done§ion=$section&langtab=$langtab"); + if ( $redirect eq "just_save" ) { + print $input->redirect( + "/cgi-bin/koha/tools/letter.pl?op=add_form&branchcode=$branchcode&module=$module&code=$code&redirect=done§ion=$section&langtab=$langtab" + ); exit; } else { - $op = q{}; # we return to the default screen for the next operation + $op = q{}; # we return to the default screen for the next operation } } -if ($op eq 'cud-copy_form') { +if ( $op eq 'cud-copy_form' ) { my $oldbranchcode = $input->param('oldbranchcode') || q||; - my $branchcode = $input->param('branchcode'); - add_form($oldbranchcode, $module, $code); + my $branchcode = $input->param('branchcode'); + add_form( $oldbranchcode, $module, $code ); $template->param( oldbranchcode => $oldbranchcode, - branchcode => $branchcode, - copy_form => 1, - modify => 0, + branchcode => $branchcode, + copy_form => 1, + modify => 0, ); -} -elsif ( $op eq 'add_form' ) { - add_form($branchcode, $module, $code); -} -elsif ( $op eq 'delete_confirm' ) { - delete_confirm($branchcode, $module, $code); -} -elsif ( $op eq 'cud-delete_confirmed' ) { - delete_confirmed($branchcode, $module, $code); - $op = q{}; # next operation is to return to default screen -} -else { - default_display($branchcode,$searchfield); +} elsif ( $op eq 'add_form' ) { + add_form( $branchcode, $module, $code ); +} elsif ( $op eq 'delete_confirm' ) { + delete_confirm( $branchcode, $module, $code ); +} elsif ( $op eq 'cud-delete_confirmed' ) { + delete_confirmed( $branchcode, $module, $code ); + $op = q{}; # next operation is to return to default screen +} else { + default_display( $branchcode, $searchfield ); } # Do this last as delete_confirmed resets if ($op) { - $template->param($op => 1); + $template->param( $op => 1 ); } else { - $template->param(no_op_set => 1); + $template->param( no_op_set => 1 ); } output_html_with_http_headers $input, $cookie, $template->output; sub add_form { - my ( $branchcode,$module, $code ) = @_; + my ( $branchcode, $module, $code ) = @_; my $letters; + # if code has been passed we can identify letter and its an update action if ($code) { $letters = C4::Letters::GetLetterTemplates( @@ -155,8 +157,8 @@ sub add_form { } my $message_transport_types = GetMessageTransportTypes(); - my $templates = { map { $_ => { message_transport_type => $_ } } sort @$message_transport_types }; - my %letters = ( default => { templates => {%$templates} } ); + my $templates = { map { $_ => { message_transport_type => $_ } } sort @$message_transport_types }; + my %letters = ( default => { templates => {%$templates} } ); my $translated_languages = C4::Languages::getTranslatedLanguages( 'opac', @@ -299,13 +301,13 @@ sub add_form { my $preview_is_available = 0; if ($code) { - $preview_is_available = grep {$_ eq $code } qw( CHECKIN CHECKOUT HOLD_SLIP ); + $preview_is_available = grep { $_ eq $code } qw( CHECKIN CHECKOUT HOLD_SLIP ); } $template->param( - module => $module, - SQLfieldnames => $field_selection, - branchcode => $branchcode, + module => $module, + SQLfieldnames => $field_selection, + branchcode => $branchcode, preview_is_available => $preview_is_available, ); return; @@ -313,16 +315,17 @@ sub add_form { sub add_validate { my $dbh = C4::Context->dbh; - my $branchcode = $input->param('branchcode'); - my $module = $input->param('module'); - my $oldmodule = $input->param('oldmodule'); - my $code = $input->param('code'); - my $name = $input->param('name'); - my @mtt = $input->multi_param('message_transport_type'); - my @title = $input->multi_param('title'); - my @content = $input->multi_param('content'); - my @lang = $input->multi_param('lang'); - for my $mtt ( @mtt ) { + my $branchcode = $input->param('branchcode'); + my $module = $input->param('module'); + my $oldmodule = $input->param('oldmodule'); + my $code = $input->param('code'); + my $name = $input->param('name'); + my @mtt = $input->multi_param('message_transport_type'); + my @title = $input->multi_param('title'); + my @content = $input->multi_param('content'); + my @lang = $input->multi_param('lang'); + + for my $mtt (@mtt) { my $lang = shift @lang; my $style = $input->param("style_$lang"); my $format_all = $input->param("format_all_$lang"); @@ -335,7 +338,7 @@ sub add_validate { my $is_html = $input->param("is_html_$mtt\_$lang"); my $title = shift @title; my $content = shift @content; - my $letter = Koha::Notice::Templates->find( + my $letter = Koha::Notice::Templates->find( { module => $oldmodule, code => $code, @@ -346,14 +349,16 @@ sub add_validate { ); unless ( $title and $content ) { + # Delete this mtt if no title or content given delete_confirmed( $branchcode, $oldmodule, $code, $mtt, $lang ); next; - } - elsif ( $letter ) { - logaction( 'NOTICES', 'MODIFY', $letter->id, $content, - 'Intranet' ) - if ( C4::Context->preference("NoticesLog") + } elsif ($letter) { + logaction( + 'NOTICES', 'MODIFY', $letter->id, $content, + 'Intranet' + ) + if ( C4::Context->preference("NoticesLog") && $content ne $letter->content ); $letter->set( @@ -384,21 +389,22 @@ sub add_validate { style => $style } )->store; - logaction( 'NOTICES', 'CREATE', $letter->id, $letter->content, - 'Intranet' ) - if C4::Context->preference("NoticesLog"); + logaction( + 'NOTICES', 'CREATE', $letter->id, $letter->content, + 'Intranet' + ) if C4::Context->preference("NoticesLog"); } } + # set up default display default_display($branchcode); return 1; } sub delete_confirm { - my ($branchcode, $module, $code) = @_; - my $dbh = C4::Context->dbh; - my $letter = Koha::Notice::Templates->search( - { module => $module, code => $code, branchcode => $branchcode } ); + my ( $branchcode, $module, $code ) = @_; + my $dbh = C4::Context->dbh; + my $letter = Koha::Notice::Templates->search( { module => $module, code => $code, branchcode => $branchcode } ); $template->param( letter => $letter ? $letter->next : undef, ); @@ -412,14 +418,15 @@ sub delete_confirmed { branchcode => $branchcode || '', module => $module, code => $code, - ( $mtt ? ( message_transport_type => $mtt ) : () ), - ( $lang ? ( lang => $lang ) : () ), + ( $mtt ? ( message_transport_type => $mtt ) : () ), + ( $lang ? ( lang => $lang ) : () ), } ); while ( my $letter = $letters->next ) { - logaction( 'NOTICES', 'DELETE', $letter->id, $letter->content, - 'Intranet' ) - if C4::Context->preference("NoticesLog"); + logaction( + 'NOTICES', 'DELETE', $letter->id, $letter->content, + 'Intranet' + ) if C4::Context->preference("NoticesLog"); $letter->delete; } @@ -429,40 +436,38 @@ sub delete_confirmed { } sub retrieve_letters { - my ($branchcode, $searchstring) = @_; + my ( $branchcode, $searchstring ) = @_; $branchcode = $my_branch if $branchcode && $my_branch; my $dbh = C4::Context->dbh; - my ($sql, @where, @args); + my ( $sql, @where, @args ); $sql = "SELECT branchcode, module, code, name, branchname, MAX(updated_on) as updated_on FROM letter LEFT OUTER JOIN branches USING (branchcode) "; - if ($searchstring && $searchstring=~m/(\S+)/) { + if ( $searchstring && $searchstring =~ m/(\S+)/ ) { $searchstring = $1 . q{%}; push @where, 'code LIKE ?'; - push @args, $searchstring; - } - elsif ($branchcode) { + push @args, $searchstring; + } elsif ($branchcode) { push @where, 'branchcode = ?'; - push @args, $branchcode || ''; - } - elsif ($my_branch) { + push @args, $branchcode || ''; + } elsif ($my_branch) { push @where, "(branchcode = ? OR branchcode = '')"; - push @args, $my_branch; + push @args, $my_branch; } - $sql .= " WHERE ".join(" AND ", @where) if @where; + $sql .= " WHERE " . join( " AND ", @where ) if @where; $sql .= " GROUP BY branchcode,module,code,name,branchname"; $sql .= " ORDER BY module, code, branchcode"; - return $dbh->selectall_arrayref($sql, { Slice => {} }, @args); + return $dbh->selectall_arrayref( $sql, { Slice => {} }, @args ); } sub default_display { - my ($branchcode, $searchfield) = @_; + my ( $branchcode, $searchfield ) = @_; unless ( defined $branchcode ) { if ( C4::Context->preference('DefaultToLoggedInLibraryNoticesSlips') ) { @@ -470,22 +475,22 @@ sub default_display { } } - if ( $searchfield ) { - $template->param( search => 1 ); + if ($searchfield) { + $template->param( search => 1 ); } - my $results = retrieve_letters($branchcode,$searchfield); + my $results = retrieve_letters( $branchcode, $searchfield ); - my $loop_data = []; + my $loop_data = []; my $protected_letters = protected_letters(); - foreach my $row (@{$results}) { + foreach my $row ( @{$results} ) { $row->{protected} = !$row->{branchcode} && $protected_letters->{ $row->{code} }; push @{$loop_data}, $row; } $template->param( - letter => $loop_data, + letter => $loop_data, branchcode => $branchcode, ); } @@ -503,7 +508,8 @@ sub add_fields { sub get_columns_for { my $table = shift; -# FIXME untranslatable + + # FIXME untranslatable my %column_map = ( aqbooksellers => '---BOOKSELLERS---', aqorders => '---ORDERS---', @@ -512,33 +518,36 @@ sub get_columns_for { suggestions => '---SUGGESTIONS---', ); my @fields = (); - if (exists $column_map{$table} ) { + if ( exists $column_map{$table} ) { push @fields, { value => q{}, - text => $column_map{$table} , + text => $column_map{$table}, }; - } - else { + } else { my $tlabel = '---' . uc $table; - $tlabel.= '---'; + $tlabel .= '---'; push @fields, { value => q{}, text => $tlabel, }; } - my $sql = "SHOW COLUMNS FROM $table";# TODO not db agnostic + my $sql = "SHOW COLUMNS FROM $table"; # TODO not db agnostic my $table_prefix = $table . q|.|; - my $rows = C4::Context->dbh->selectall_arrayref($sql, { Slice => {} }); - for my $row (@{$rows}) { - next if $row->{'Field'} eq 'timestamp'; # this is really an irrelevant field and there may be other common fields that should be excluded from the list - next if $row->{'Field'} eq 'password'; # passwords can no longer be shown in notices so the password field should be removed as a template option + my $rows = C4::Context->dbh->selectall_arrayref( $sql, { Slice => {} } ); + for my $row ( @{$rows} ) { + next + if $row->{'Field'} eq 'timestamp' + ; # this is really an irrelevant field and there may be other common fields that should be excluded from the list + next + if $row->{'Field'} eq 'password' + ; # passwords can no longer be shown in notices so the password field should be removed as a template option push @fields, { value => $table_prefix . $row->{Field}, text => $table_prefix . $row->{Field}, - } + }; } - if ($table eq 'borrowers') { + if ( $table eq 'borrowers' ) { my $attribute_types = Koha::Patron::Attribute::Types->search( {}, { order_by => 'code' }, @@ -547,7 +556,7 @@ sub get_columns_for { push @fields, { value => "borrower-attribute:" . $at->code, text => "attribute:" . $at->code, - } + }; } } return @fields; diff --git a/tools/manage-marc-import.pl b/tools/manage-marc-import.pl index c36c7cb0f8..38f0426168 100755 --- a/tools/manage-marc-import.pl +++ b/tools/manage-marc-import.pl @@ -28,9 +28,10 @@ use Try::Tiny; # Koha modules used use C4::Context; use C4::Koha; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); -use C4::ImportBatch qw( CleanBatch DeleteBatch GetImportBatch GetImportBatchOverlayAction GetImportBatchNoMatchAction GetImportBatchItemAction SetImportBatchOverlayAction SetImportBatchNoMatchAction SetImportBatchItemAction BatchFindDuplicates SetImportBatchMatcher GetItemNumbersFromImportBatch GetImportBatchRangeDesc GetNumberOfNonZ3950ImportBatches BatchCommitRecords BatchRevertRecords ); +use C4::ImportBatch + qw( CleanBatch DeleteBatch GetImportBatch GetImportBatchOverlayAction GetImportBatchNoMatchAction GetImportBatchItemAction SetImportBatchOverlayAction SetImportBatchNoMatchAction SetImportBatchItemAction BatchFindDuplicates SetImportBatchMatcher GetItemNumbersFromImportBatch GetImportBatchRangeDesc GetNumberOfNonZ3950ImportBatches BatchCommitRecords BatchRevertRecords ); use C4::Matcher; use C4::Labels::Batch; use Koha::BiblioFrameworks; @@ -39,304 +40,322 @@ use Koha::BackgroundJob::MARCImportRevertBatch; use Koha::Logger; - -my $input = CGI->new; -my $op = $input->param('op') || ''; +my $input = CGI->new; +my $op = $input->param('op') || ''; my $import_batch_id = $input->param('import_batch_id') || ''; my @messages; # record list displays -my $offset = $input->param('offset') || 0; -my $results_per_page = $input->param('results_per_page') || 25; +my $offset = $input->param('offset') || 0; +my $results_per_page = $input->param('results_per_page') || 25; -my ($template, $loggedinuser, $cookie) - = get_template_and_user({template_name => "tools/manage-marc-import.tt", - query => $input, - type => "intranet", - flagsrequired => {tools => 'manage_staged_marc'}, - }); +my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "tools/manage-marc-import.tt", + query => $input, + type => "intranet", + flagsrequired => { tools => 'manage_staged_marc' }, + } +); -my $frameworks = Koha::BiblioFrameworks->search({ tagfield => { 'not' => undef } }, { join => 'marc_tag_structure', distinct => 'frameworkcode', order_by => ['frameworktext'] }); +my $frameworks = Koha::BiblioFrameworks->search( + { tagfield => { 'not' => undef } }, + { join => 'marc_tag_structure', distinct => 'frameworkcode', order_by => ['frameworktext'] } +); $template->param( frameworks => $frameworks ); -if ($op eq "create_labels") { - #create a batch of labels, then lose $op & $import_batch_id so we get back to import batch list. - my $label_batch_id = create_labelbatch_from_importbatch($import_batch_id); - if ($label_batch_id == -1) { - $template->param( label_batch_msg => "error", - message_type => 'alert', - ); - } - else { - $template->param( label_batch_msg => $label_batch_id, - message_type => 'dialog', - ); - } - $op=''; - $import_batch_id=''; +if ( $op eq "create_labels" ) { + + #create a batch of labels, then lose $op & $import_batch_id so we get back to import batch list. + my $label_batch_id = create_labelbatch_from_importbatch($import_batch_id); + if ( $label_batch_id == -1 ) { + $template->param( + label_batch_msg => "error", + message_type => 'alert', + ); + } else { + $template->param( + label_batch_msg => $label_batch_id, + message_type => 'dialog', + ); + } + $op = ''; + $import_batch_id = ''; } if ($op) { - $template->param($op => 1); + $template->param( $op => 1 ); } -if ($op eq "") { +if ( $op eq "" ) { + # displaying a list - if ($import_batch_id eq '') { - import_batches_list($template, $offset, $results_per_page); + if ( $import_batch_id eq '' ) { + import_batches_list( $template, $offset, $results_per_page ); } else { - import_records_list($template, $import_batch_id, $offset, $results_per_page); + import_records_list( $template, $import_batch_id, $offset, $results_per_page ); } -} elsif ($op eq "cud-commit-batch") { - my $frameworkcode = $input->param('framework'); +} elsif ( $op eq "cud-commit-batch" ) { + my $frameworkcode = $input->param('framework'); my $overlay_framework = $input->param('overlay_framework'); $overlay_framework = undef if $overlay_framework eq '_USE_ORIG_'; try { my $job_id = Koha::BackgroundJob::MARCImportCommitBatch->new->enqueue( { - import_batch_id => $import_batch_id, - frameworkcode => $frameworkcode, + import_batch_id => $import_batch_id, + frameworkcode => $frameworkcode, overlay_framework => $overlay_framework } ); if ($job_id) { $template->param( job_enqueued => 1, - job_id => $job_id, + job_id => $job_id, ); } - } - catch { + } catch { warn $_; push @messages, - { + { type => 'error', code => 'cannot_enqueue_job', error => $_, - }; + }; }; -} elsif ($op eq "cud-revert-batch") { +} elsif ( $op eq "cud-revert-batch" ) { try { - my $job_id = Koha::BackgroundJob::MARCImportRevertBatch->new->enqueue( - { import_batch_id => $import_batch_id } ); + my $job_id = + Koha::BackgroundJob::MARCImportRevertBatch->new->enqueue( { import_batch_id => $import_batch_id } ); if ($job_id) { $template->param( job_enqueued => 1, - job_id => $job_id, + job_id => $job_id, ); } - } - catch { + } catch { warn $_; push @messages, - { + { type => 'error', code => 'cannot_enqueue_job', error => $_, - }; + }; }; -} elsif ($op eq "cud-clean-batch") { +} elsif ( $op eq "cud-clean-batch" ) { CleanBatch($import_batch_id); - import_batches_list($template, $offset, $results_per_page); - $template->param( + import_batches_list( $template, $offset, $results_per_page ); + $template->param( did_clean => 1, import_batch_id => $import_batch_id, ); -} elsif ($op eq "cud-delete-batch") { +} elsif ( $op eq "cud-delete-batch" ) { DeleteBatch($import_batch_id); - import_batches_list($template, $offset, $results_per_page); + import_batches_list( $template, $offset, $results_per_page ); $template->param( - did_delete => 1, + did_delete => 1, ); -} elsif ($op eq "cud-redo-matching") { - my $new_matcher_id = $input->param('new_matcher_id'); +} elsif ( $op eq "cud-redo-matching" ) { + my $new_matcher_id = $input->param('new_matcher_id'); my $current_matcher_id = $input->param('current_matcher_id'); - my $overlay_action = $input->param('overlay_action'); - my $nomatch_action = $input->param('nomatch_action'); - my $item_action = $input->param('item_action'); - redo_matching($template, $import_batch_id, $new_matcher_id, $current_matcher_id, - $overlay_action, $nomatch_action, $item_action); - import_records_list($template, $import_batch_id, $offset, $results_per_page); -} + my $overlay_action = $input->param('overlay_action'); + my $nomatch_action = $input->param('nomatch_action'); + my $item_action = $input->param('item_action'); + redo_matching( + $template, $import_batch_id, $new_matcher_id, $current_matcher_id, + $overlay_action, $nomatch_action, $item_action + ); + import_records_list( $template, $import_batch_id, $offset, $results_per_page ); +} output_html_with_http_headers $input, $cookie, $template->output; exit 0; sub redo_matching { - my ($template, $import_batch_id, $new_matcher_id, $current_matcher_id, $overlay_action, $nomatch_action, $item_action) = @_; + my ( + $template, $import_batch_id, $new_matcher_id, $current_matcher_id, $overlay_action, $nomatch_action, + $item_action + ) = @_; my $rematch_failed = 0; return if not defined $new_matcher_id and not defined $current_matcher_id; my $old_overlay_action = GetImportBatchOverlayAction($import_batch_id); my $old_nomatch_action = GetImportBatchNoMatchAction($import_batch_id); - my $old_item_action = GetImportBatchItemAction($import_batch_id); - return if $new_matcher_id eq $current_matcher_id and - $old_overlay_action eq $overlay_action and - $old_nomatch_action eq $nomatch_action and - $old_item_action eq $item_action; - - if ($old_overlay_action ne $overlay_action) { - SetImportBatchOverlayAction($import_batch_id, $overlay_action); - $template->param('changed_overlay_action' => 1); + my $old_item_action = GetImportBatchItemAction($import_batch_id); + return + if $new_matcher_id eq $current_matcher_id + and $old_overlay_action eq $overlay_action + and $old_nomatch_action eq $nomatch_action + and $old_item_action eq $item_action; + + if ( $old_overlay_action ne $overlay_action ) { + SetImportBatchOverlayAction( $import_batch_id, $overlay_action ); + $template->param( 'changed_overlay_action' => 1 ); } - if ($old_nomatch_action ne $nomatch_action) { - SetImportBatchNoMatchAction($import_batch_id, $nomatch_action); - $template->param('changed_nomatch_action' => 1); + if ( $old_nomatch_action ne $nomatch_action ) { + SetImportBatchNoMatchAction( $import_batch_id, $nomatch_action ); + $template->param( 'changed_nomatch_action' => 1 ); } - if ($old_item_action ne $item_action) { - SetImportBatchItemAction($import_batch_id, $item_action); - $template->param('changed_item_action' => 1); + if ( $old_item_action ne $item_action ) { + SetImportBatchItemAction( $import_batch_id, $item_action ); + $template->param( 'changed_item_action' => 1 ); } my $num_with_matches = 0; - if (defined $new_matcher_id and $new_matcher_id ne "") { + if ( defined $new_matcher_id and $new_matcher_id ne "" ) { my $matcher = C4::Matcher->fetch($new_matcher_id); - if (defined $matcher) { - $num_with_matches = BatchFindDuplicates($import_batch_id, $matcher); - SetImportBatchMatcher($import_batch_id, $new_matcher_id); + if ( defined $matcher ) { + $num_with_matches = BatchFindDuplicates( $import_batch_id, $matcher ); + SetImportBatchMatcher( $import_batch_id, $new_matcher_id ); } else { $rematch_failed = 1; } } else { - $num_with_matches = BatchFindDuplicates($import_batch_id, undef); - SetImportBatchMatcher($import_batch_id, undef); + $num_with_matches = BatchFindDuplicates( $import_batch_id, undef ); + SetImportBatchMatcher( $import_batch_id, undef ); SetImportBatchOverlayAction('create_new'); } - $template->param(rematch_failed => $rematch_failed); - $template->param(rematch_attempted => 1); - $template->param(num_with_matches => $num_with_matches); + $template->param( rematch_failed => $rematch_failed ); + $template->param( rematch_attempted => 1 ); + $template->param( num_with_matches => $num_with_matches ); } sub create_labelbatch_from_importbatch { - my ($batch_id) = @_; - my $err = undef; - my $branch_code = C4::Context->userenv->{'branch'}; - my $batch = C4::Labels::Batch->new(branch_code => $branch_code); - my @items = GetItemNumbersFromImportBatch($batch_id); - if (grep{$_ == 0} @items) { - warn sprintf('create_labelbatch_from_importbatch() : Call to C4::ImportBatch::GetItemNumbersFromImportBatch returned no item number(s) from import batch #%s.', $batch_id); + my ($batch_id) = @_; + my $err = undef; + my $branch_code = C4::Context->userenv->{'branch'}; + my $batch = C4::Labels::Batch->new( branch_code => $branch_code ); + my @items = GetItemNumbersFromImportBatch($batch_id); + if ( grep { $_ == 0 } @items ) { + warn sprintf( + 'create_labelbatch_from_importbatch() : Call to C4::ImportBatch::GetItemNumbersFromImportBatch returned no item number(s) from import batch #%s.', + $batch_id + ); + return -1; + } + foreach my $item_number (@items) { + $err = $batch->add_item($item_number); + if ( $err == -1 ) { + warn sprintf( + 'create_labelbatch_from_importbatch() : Error attempting to add item #%s of import batch #%s to label batch.', + $item_number, $batch_id + ); return -1; } - foreach my $item_number (@items) { - $err = $batch->add_item($item_number); - if ($err == -1) { - warn sprintf('create_labelbatch_from_importbatch() : Error attempting to add item #%s of import batch #%s to label batch.', $item_number, $batch_id); - return -1; - } - } - return $batch->get_attr('batch_id'); + } + return $batch->get_attr('batch_id'); } sub import_batches_list { - my ($template, $offset, $results_per_page) = @_; - my $batches = GetImportBatchRangeDesc($offset, $results_per_page); + my ( $template, $offset, $results_per_page ) = @_; + my $batches = GetImportBatchRangeDesc( $offset, $results_per_page ); my @list = (); foreach my $batch (@$batches) { push @list, { - import_batch_id => $batch->{'import_batch_id'}, - num_records => $batch->{'num_records'}, - num_items => $batch->{'num_items'}, + import_batch_id => $batch->{'import_batch_id'}, + num_records => $batch->{'num_records'}, + num_items => $batch->{'num_items'}, upload_timestamp => $batch->{'upload_timestamp'}, - import_status => $batch->{'import_status'}, - file_name => $batch->{'file_name'} || "($batch->{'batch_type'})", - comments => $batch->{'comments'}, - can_clean => ($batch->{'import_status'} ne 'cleaned') ? 1 : 0, - record_type => $batch->{'record_type'}, - profile => $batch->{'profile'}, + import_status => $batch->{'import_status'}, + file_name => $batch->{'file_name'} || "($batch->{'batch_type'})", + comments => $batch->{'comments'}, + can_clean => ( $batch->{'import_status'} ne 'cleaned' ) ? 1 : 0, + record_type => $batch->{'record_type'}, + profile => $batch->{'profile'}, }; } - $template->param(batch_list => \@list); + $template->param( batch_list => \@list ); my $num_batches = GetNumberOfNonZ3950ImportBatches(); - add_page_numbers($template, $offset, $results_per_page, $num_batches); - $template->param(offset => $offset); - $template->param(range_top => $offset + $results_per_page - 1); - $template->param(num_results => $num_batches); - $template->param(results_per_page => $results_per_page); + add_page_numbers( $template, $offset, $results_per_page, $num_batches ); + $template->param( offset => $offset ); + $template->param( range_top => $offset + $results_per_page - 1 ); + $template->param( num_results => $num_batches ); + $template->param( results_per_page => $results_per_page ); } sub import_records_list { - my ($template, $import_batch_id, $offset, $results_per_page) = @_; + my ( $template, $import_batch_id, $offset, $results_per_page ) = @_; my $batch = GetImportBatch($import_batch_id); - $template->param(import_batch_id => $import_batch_id); + $template->param( import_batch_id => $import_batch_id ); my $overlay_action = GetImportBatchOverlayAction($import_batch_id); - $template->param("overlay_action_${overlay_action}" => 1); - $template->param(overlay_action => $overlay_action); + $template->param( "overlay_action_${overlay_action}" => 1 ); + $template->param( overlay_action => $overlay_action ); my $nomatch_action = GetImportBatchNoMatchAction($import_batch_id); - $template->param("nomatch_action_${nomatch_action}" => 1); - $template->param(nomatch_action => $nomatch_action); + $template->param( "nomatch_action_${nomatch_action}" => 1 ); + $template->param( nomatch_action => $nomatch_action ); my $item_action = GetImportBatchItemAction($import_batch_id); - $template->param("item_action_${item_action}" => 1); - $template->param(item_action => $item_action); + $template->param( "item_action_${item_action}" => 1 ); + $template->param( item_action => $item_action ); + + batch_info( $template, $batch ); - batch_info($template, $batch); - } sub batch_info { - my ($template, $batch) = @_; - $template->param(batch_info => 1); - $template->param(file_name => $batch->{'file_name'}); - $template->param(profile => $batch->{'profile'}); - $template->param(comments => $batch->{'comments'}); - $template->param(import_status => $batch->{'import_status'}); - $template->param(upload_timestamp => $batch->{'upload_timestamp'}); + my ( $template, $batch ) = @_; + $template->param( batch_info => 1 ); + $template->param( file_name => $batch->{'file_name'} ); + $template->param( profile => $batch->{'profile'} ); + $template->param( comments => $batch->{'comments'} ); + $template->param( import_status => $batch->{'import_status'} ); + $template->param( upload_timestamp => $batch->{'upload_timestamp'} ); $template->{VARS}->{'record_type'} = $batch->{'record_type'}; - $template->param(num_records => $batch->{'num_records'}); - $template->param(num_items => $batch->{'num_items'}); - if ($batch->{'import_status'} ne 'cleaned') { - $template->param(can_clean => 1); + $template->param( num_records => $batch->{'num_records'} ); + $template->param( num_items => $batch->{'num_items'} ); + + if ( $batch->{'import_status'} ne 'cleaned' ) { + $template->param( can_clean => 1 ); } - if ($batch->{'num_records'} > 0) { - if ($batch->{'import_status'} eq 'staged' or $batch->{'import_status'} eq 'reverted') { - $template->param(can_commit => 1); + if ( $batch->{'num_records'} > 0 ) { + if ( $batch->{'import_status'} eq 'staged' or $batch->{'import_status'} eq 'reverted' ) { + $template->param( can_commit => 1 ); } - if ($batch->{'import_status'} eq 'imported') { - $template->param(can_revert => 1); + if ( $batch->{'import_status'} eq 'imported' ) { + $template->param( can_revert => 1 ); } } - if (defined $batch->{'matcher_id'}) { - my $matcher = C4::Matcher->fetch($batch->{'matcher_id'}); - if (defined $matcher) { - $template->param('current_matcher_id' => $batch->{'matcher_id'}); - $template->param('current_matcher_code' => $matcher->code()); - $template->param('current_matcher_description' => $matcher->description()); + if ( defined $batch->{'matcher_id'} ) { + my $matcher = C4::Matcher->fetch( $batch->{'matcher_id'} ); + if ( defined $matcher ) { + $template->param( 'current_matcher_id' => $batch->{'matcher_id'} ); + $template->param( 'current_matcher_code' => $matcher->code() ); + $template->param( 'current_matcher_description' => $matcher->description() ); } } - add_matcher_list($template,$batch->{'matcher_id'}); + add_matcher_list( $template, $batch->{'matcher_id'} ); } sub add_matcher_list { - my ($template,$current_matcher_id) = @_; + my ( $template, $current_matcher_id ) = @_; my @matchers = C4::Matcher::GetMatcherList(); - if (defined $current_matcher_id) { - for (my $i = 0; $i <= $#matchers; $i++) { - if ($matchers[$i]->{'matcher_id'} eq $current_matcher_id) { + if ( defined $current_matcher_id ) { + for ( my $i = 0 ; $i <= $#matchers ; $i++ ) { + if ( $matchers[$i]->{'matcher_id'} eq $current_matcher_id ) { $matchers[$i]->{'selected'} = 1; } } } - $template->param(available_matchers => \@matchers); + $template->param( available_matchers => \@matchers ); } sub add_page_numbers { - my ($template, $offset, $results_per_page, $total_results) = @_; - my $max_pages = POSIX::ceil($total_results / $results_per_page); + my ( $template, $offset, $results_per_page, $total_results ) = @_; + my $max_pages = POSIX::ceil( $total_results / $results_per_page ); return if $max_pages < 2; - my $current_page = int($offset / $results_per_page) + 1; - my @pages = (); - for (my $i = 1; $i <= $max_pages; $i++) { + my $current_page = int( $offset / $results_per_page ) + 1; + my @pages = (); + for ( my $i = 1 ; $i <= $max_pages ; $i++ ) { push @pages, { - page_number => $i, - current_page => ($current_page == $i) ? 1 : 0, - offset => ($i - 1) * $results_per_page - } + page_number => $i, + current_page => ( $current_page == $i ) ? 1 : 0, + offset => ( $i - 1 ) * $results_per_page + }; } - $template->param(pages => \@pages); + $template->param( pages => \@pages ); } diff --git a/tools/marc_modification_templates.pl b/tools/marc_modification_templates.pl index 6105d74c15..6bf4c63747 100755 --- a/tools/marc_modification_templates.pl +++ b/tools/marc_modification_templates.pl @@ -20,8 +20,8 @@ use Modern::Perl; use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); -use C4::Output qw( output_html_with_http_headers ); +use C4::Auth qw( get_template_and_user ); +use C4::Output qw( output_html_with_http_headers ); use C4::MarcModificationTemplates qw( AddModificationTemplate AddModificationTemplateAction @@ -35,46 +35,47 @@ use C4::MarcModificationTemplates qw( my $cgi = CGI->new; -my $op = $cgi->param('op') || q{}; +my $op = $cgi->param('op') || q{}; my $template_id = $cgi->param('template_id'); -my ($template, $loggedinuser, $cookie) - = get_template_and_user({ - template_name => "tools/marc_modification_templates.tt", - query => $cgi, - type => "intranet", - flagsrequired => { tools => 'marc_modification_templates' }, - }); +my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "tools/marc_modification_templates.tt", + query => $cgi, + type => "intranet", + flagsrequired => { tools => 'marc_modification_templates' }, + } +); if ( $op eq "cud-create_template" ) { - $template_id = '' unless $cgi->param('duplicate_current_template'); - $template_id = AddModificationTemplate( scalar $cgi->param('template_name'), $template_id ); + $template_id = '' unless $cgi->param('duplicate_current_template'); + $template_id = AddModificationTemplate( scalar $cgi->param('template_name'), $template_id ); } elsif ( $op eq "cud-delete_template" ) { - DelModificationTemplate( $template_id ); - $template_id = ''; + DelModificationTemplate($template_id); + $template_id = ''; } elsif ( $op eq "cud-add_action" ) { - my $mmta_id = $cgi->param('mmta_id'); - my $action = $cgi->param('action'); - my $field_number = $cgi->param('field_number'); - my $from_field = $cgi->param('from_field'); - my $from_subfield = $cgi->param('from_subfield'); - my $field_value = $cgi->param('field_value'); - my $to_field = $cgi->param('to_field'); - my $to_subfield = $cgi->param('to_subfield'); - my $to_regex_search = $cgi->param('to_regex_search'); - my $to_regex_replace = $cgi->param('to_regex_replace'); - my $to_regex_modifiers = $cgi->param('to_regex_modifiers'); - my $conditional = $cgi->param('conditional'); - my $conditional_field = $cgi->param('conditional_field'); - my $conditional_subfield = $cgi->param('conditional_subfield'); - my $conditional_comparison = $cgi->param('conditional_comparison'); - my $conditional_value = $cgi->param('conditional_value'); - my $conditional_regex = ( $cgi->param('conditional_regex') eq 'on' ) ? 1 : 0; - my $description = $cgi->param('description'); + my $mmta_id = $cgi->param('mmta_id'); + my $action = $cgi->param('action'); + my $field_number = $cgi->param('field_number'); + my $from_field = $cgi->param('from_field'); + my $from_subfield = $cgi->param('from_subfield'); + my $field_value = $cgi->param('field_value'); + my $to_field = $cgi->param('to_field'); + my $to_subfield = $cgi->param('to_subfield'); + my $to_regex_search = $cgi->param('to_regex_search'); + my $to_regex_replace = $cgi->param('to_regex_replace'); + my $to_regex_modifiers = $cgi->param('to_regex_modifiers'); + my $conditional = $cgi->param('conditional'); + my $conditional_field = $cgi->param('conditional_field'); + my $conditional_subfield = $cgi->param('conditional_subfield'); + my $conditional_comparison = $cgi->param('conditional_comparison'); + my $conditional_value = $cgi->param('conditional_value'); + my $conditional_regex = ( $cgi->param('conditional_regex') eq 'on' ) ? 1 : 0; + my $description = $cgi->param('description'); if ($from_field) { unless ($mmta_id) { @@ -89,8 +90,7 @@ if ( $op eq "cud-create_template" ) { $conditional_comparison, $conditional_value, $conditional_regex, $description ); - } - else { + } else { ModModificationTemplateAction( $mmta_id, $action, $field_number, $from_field, @@ -103,49 +103,48 @@ if ( $op eq "cud-create_template" ) { $conditional_regex, $description ); } - } - else { + } else { $template->param( error => 'no_from_field' ); } } elsif ( $op eq "cud-delete_action" ) { - DelModificationTemplateAction( scalar $cgi->param('mmta_id') ); + DelModificationTemplateAction( scalar $cgi->param('mmta_id') ); } elsif ( $op eq "move_action" ) { - MoveModificationTemplateAction( scalar $cgi->param('mmta_id'), scalar $cgi->param('where') ); + MoveModificationTemplateAction( scalar $cgi->param('mmta_id'), scalar $cgi->param('where') ); } -my @templates = GetModificationTemplates( $template_id ); +my @templates = GetModificationTemplates($template_id); -my @actions = GetModificationTemplateActions( $template_id ); -foreach my $action ( @actions ) { - $action->{'action_delete_field'} = ( $action->{'action'} eq 'delete_field' ); - $action->{'action_add_field'} = ( $action->{'action'} eq 'add_field' ); - $action->{'action_update_field'} = ( $action->{'action'} eq 'update_field' ); - $action->{'action_move_field'} = ( $action->{'action'} eq 'move_field' ); - $action->{'action_copy_field'} = ( $action->{'action'} eq 'copy_field' ); - $action->{'action_copy_and_replace_field'} = ( $action->{'action'} eq 'copy_and_replace_field' ); +my @actions = GetModificationTemplateActions($template_id); +foreach my $action (@actions) { + $action->{'action_delete_field'} = ( $action->{'action'} eq 'delete_field' ); + $action->{'action_add_field'} = ( $action->{'action'} eq 'add_field' ); + $action->{'action_update_field'} = ( $action->{'action'} eq 'update_field' ); + $action->{'action_move_field'} = ( $action->{'action'} eq 'move_field' ); + $action->{'action_copy_field'} = ( $action->{'action'} eq 'copy_field' ); + $action->{'action_copy_and_replace_field'} = ( $action->{'action'} eq 'copy_and_replace_field' ); - if( defined $action->{'conditional'} ){ - $action->{'conditional_if'} = ( $action->{'conditional'} eq 'if' ); - $action->{'conditional_unless'} = ( $action->{'conditional'} eq 'unless' ); - } + if ( defined $action->{'conditional'} ) { + $action->{'conditional_if'} = ( $action->{'conditional'} eq 'if' ); + $action->{'conditional_unless'} = ( $action->{'conditional'} eq 'unless' ); + } - if( defined $action->{'conditional_comparison'} ){ - $action->{'conditional_comparison_exists'} = ( $action->{'conditional_comparison'} eq 'exists' ); - $action->{'conditional_comparison_not_exists'} = ( $action->{'conditional_comparison'} eq 'not_exists' ); - $action->{'conditional_comparison_equals'} = ( $action->{'conditional_comparison'} eq 'equals' ); - $action->{'conditional_comparison_not_equals'} = ( $action->{'conditional_comparison'} eq 'not_equals' ); - } + if ( defined $action->{'conditional_comparison'} ) { + $action->{'conditional_comparison_exists'} = ( $action->{'conditional_comparison'} eq 'exists' ); + $action->{'conditional_comparison_not_exists'} = ( $action->{'conditional_comparison'} eq 'not_exists' ); + $action->{'conditional_comparison_equals'} = ( $action->{'conditional_comparison'} eq 'equals' ); + $action->{'conditional_comparison_not_equals'} = ( $action->{'conditional_comparison'} eq 'not_equals' ); + } } $template->param( - TemplatesLoop => \@templates, - ActionsLoop => \@actions, + TemplatesLoop => \@templates, + ActionsLoop => \@actions, - template_id => $template_id, + template_id => $template_id, ); output_html_with_http_headers $cgi, $cookie, $template->output; diff --git a/tools/newHolidays.pl b/tools/newHolidays.pl index 91d233b95f..9cca4a9bc9 100755 --- a/tools/newHolidays.pl +++ b/tools/newHolidays.pl @@ -16,7 +16,6 @@ # You should have received a copy of the GNU General Public Lic# along with Koha; if not, see . # along with Koha; if not, see . - use Modern::Perl; use CGI qw ( -utf8 ); @@ -28,45 +27,41 @@ use C4::Calendar; use DateTime; use Koha::DateUtils qw( dt_from_string output_pref ); -my $input = CGI->new; -my $op = $input->param('op') // q{}; -my $dbh = C4::Context->dbh(); +my $input = CGI->new; +my $op = $input->param('op') // q{}; +my $dbh = C4::Context->dbh(); -checkauth($input, 0, {tools=> 'edit_calendar'}, 'intranet'); +checkauth( $input, 0, { tools => 'edit_calendar' }, 'intranet' ); -our $branchcode = $input->param('newBranchName'); -my $originalbranchcode = $branchcode; -our $weekday = $input->param('newWeekday'); -our $day = $input->param('newDay'); -our $month = $input->param('newMonth'); -our $year = $input->param('newYear'); -my $dateofrange = $input->param('dateofrange'); -our $title = $input->param('newTitle'); -our $description = $input->param('newDescription'); -our $newoperation = $input->param('newOperation'); -my $allbranches = $input->param('allBranches'); +our $branchcode = $input->param('newBranchName'); +my $originalbranchcode = $branchcode; +our $weekday = $input->param('newWeekday'); +our $day = $input->param('newDay'); +our $month = $input->param('newMonth'); +our $year = $input->param('newYear'); +my $dateofrange = $input->param('dateofrange'); +our $title = $input->param('newTitle'); +our $description = $input->param('newDescription'); +our $newoperation = $input->param('newOperation'); +my $allbranches = $input->param('allBranches'); - -my $first_dt = DateTime->new(year => $year, month => $month, day => $day); -my $end_dt = eval { dt_from_string( $dateofrange ); }; +my $first_dt = DateTime->new( year => $year, month => $month, day => $day ); +my $end_dt = eval { dt_from_string($dateofrange); }; my $calendardate = output_pref( { dt => $first_dt, dateonly => 1, dateformat => 'iso' } ); -$title || ($title = ''); +$title || ( $title = '' ); if ($description) { - $description =~ s/\r/\\r/g; - $description =~ s/\n/\\n/g; + $description =~ s/\r/\\r/g; + $description =~ s/\n/\\n/g; } else { - $description = ''; + $description = ''; } # We make an array with holiday's days our @holiday_list = (); -if ($end_dt){ - for (my $dt = $first_dt->clone(); - $dt <= $end_dt; - $dt->add(days => 1) ) - { +if ($end_dt) { + for ( my $dt = $first_dt->clone() ; $dt <= $end_dt ; $dt->add( days => 1 ) ) { push @holiday_list, $dt->clone(); } } @@ -74,50 +69,62 @@ if ($end_dt){ if ( $op eq 'cud-add' && $allbranches ) { my $libraries = Koha::Libraries->search; while ( my $library = $libraries->next ) { - add_holiday($newoperation, $library->branchcode, $weekday, $day, $month, $year, $title, $description); + add_holiday( $newoperation, $library->branchcode, $weekday, $day, $month, $year, $title, $description ); } } elsif ( $op eq 'cud-add' ) { - add_holiday($newoperation, $branchcode, $weekday, $day, $month, $year, $title, $description); + add_holiday( $newoperation, $branchcode, $weekday, $day, $month, $year, $title, $description ); } print $input->redirect("/cgi-bin/koha/tools/holidays.pl?branch=$originalbranchcode&calendardate=$calendardate"); #FIXME: move add_holiday() to a better place sub add_holiday { - ($newoperation, $branchcode, $weekday, $day, $month, $year, $title, $description) = @_; - my $calendar = C4::Calendar->new(branchcode => $branchcode); + ( $newoperation, $branchcode, $weekday, $day, $month, $year, $title, $description ) = @_; + my $calendar = C4::Calendar->new( branchcode => $branchcode ); - if ($newoperation eq 'weekday') { - unless ( $weekday && ($weekday ne '') ) { - # was dow calculated by javascript? original code implies it was supposed to be. - # if not, we need it. - $weekday = &Date::Calc::Day_of_Week($year, $month, $day) % 7 unless($weekday); - } - unless($calendar->isHoliday($day, $month, $year)) { - $calendar->insert_week_day_holiday(weekday => $weekday, - title => $title, - description => $description); - } - } elsif ($newoperation eq 'repeatable') { - unless($calendar->isHoliday($day, $month, $year)) { - $calendar->insert_day_month_holiday(day => $day, - month => $month, - title => $title, - description => $description); - } - } elsif ($newoperation eq 'holiday') { - unless($calendar->isHoliday($day, $month, $year)) { - $calendar->insert_single_holiday(day => $day, - month => $month, - year => $year, - title => $title, - description => $description); - } + if ( $newoperation eq 'weekday' ) { + unless ( $weekday && ( $weekday ne '' ) ) { - } elsif ( $newoperation eq 'holidayrange' ) { - if (@holiday_list){ - foreach my $date (@holiday_list){ - unless ( $calendar->isHoliday( $date->{local_c}->{day}, $date->{local_c}->{month}, $date->{local_c}->{year} ) ) { + # was dow calculated by javascript? original code implies it was supposed to be. + # if not, we need it. + $weekday = &Date::Calc::Day_of_Week( $year, $month, $day ) % 7 unless ($weekday); + } + unless ( $calendar->isHoliday( $day, $month, $year ) ) { + $calendar->insert_week_day_holiday( + weekday => $weekday, + title => $title, + description => $description + ); + } + } elsif ( $newoperation eq 'repeatable' ) { + unless ( $calendar->isHoliday( $day, $month, $year ) ) { + $calendar->insert_day_month_holiday( + day => $day, + month => $month, + title => $title, + description => $description + ); + } + } elsif ( $newoperation eq 'holiday' ) { + unless ( $calendar->isHoliday( $day, $month, $year ) ) { + $calendar->insert_single_holiday( + day => $day, + month => $month, + year => $year, + title => $title, + description => $description + ); + } + + } elsif ( $newoperation eq 'holidayrange' ) { + if (@holiday_list) { + foreach my $date (@holiday_list) { + unless ( + $calendar->isHoliday( + $date->{local_c}->{day}, $date->{local_c}->{month}, $date->{local_c}->{year} + ) + ) + { $calendar->insert_single_holiday( day => $date->{local_c}->{day}, month => $date->{local_c}->{month}, @@ -129,9 +136,14 @@ sub add_holiday { } } } elsif ( $newoperation eq 'holidayrangerepeat' ) { - if (@holiday_list){ - foreach my $date (@holiday_list){ - unless ( $calendar->isHoliday( $date->{local_c}->{day}, $date->{local_c}->{month}, $date->{local_c}->{year} ) ) { + if (@holiday_list) { + foreach my $date (@holiday_list) { + unless ( + $calendar->isHoliday( + $date->{local_c}->{day}, $date->{local_c}->{month}, $date->{local_c}->{year} + ) + ) + { $calendar->insert_day_month_holiday( day => $date->{local_c}->{day}, month => $date->{local_c}->{month}, diff --git a/tools/overduerules.pl b/tools/overduerules.pl index 4ebc6d44f5..7d0c462696 100755 --- a/tools/overduerules.pl +++ b/tools/overduerules.pl @@ -21,7 +21,7 @@ use Modern::Perl; use CGI qw ( -utf8 ); use C4::Context; use C4::Output qw( output_html_with_http_headers ); -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Letters; use C4::Members; use C4::Overdues qw( GetOverdueMessageTransportTypes ); @@ -33,18 +33,18 @@ our $input = CGI->new; my $dbh = C4::Context->dbh; my @patron_categories = Koha::Patron::Categories->search( { overduenoticerequired => { '>' => 0 } } )->as_list; -my @category_codes = map { $_->categorycode } @patron_categories; -our @rule_params = qw(delay letter debarred); +my @category_codes = map { $_->categorycode } @patron_categories; +our @rule_params = qw(delay letter debarred); # blank_row($category_code) - return true if the entire row is blank. sub blank_row { my ($category_code) = @_; for my $rp (@rule_params) { - for my $n (1 .. 3) { - my $key = "${rp}${n}-$category_code"; + for my $n ( 1 .. 3 ) { + my $key = "${rp}${n}-$category_code"; - if (utf8::is_utf8($key)) { - utf8::encode($key); + if ( utf8::is_utf8($key) ) { + utf8::encode($key); } my $value = $input->param($key); @@ -58,10 +58,10 @@ sub blank_row { my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "tools/overduerules.tt", - query => $input, - type => "intranet", - flagsrequired => { tools => 'edit_notice_status_triggers' }, + template_name => "tools/overduerules.tt", + query => $input, + type => "intranet", + flagsrequired => { tools => 'edit_notice_status_triggers' }, } ); @@ -69,138 +69,154 @@ my $type = $input->param('type'); my $branch = $input->param('branch'); $branch = - defined $branch ? $branch - : C4::Context->preference('DefaultToLoggedInLibraryOverdueTriggers') ? C4::Context::mybranch() - : Koha::Libraries->search->count() == 1 ? undef - : undef; + defined $branch ? $branch + : C4::Context->preference('DefaultToLoggedInLibraryOverdueTriggers') ? C4::Context::mybranch() + : Koha::Libraries->search->count() == 1 ? undef + : undef; $branch ||= q{}; my $op = $input->param('op'); $op ||= q{}; -my $err=0; +my $err = 0; # save the values entered into tables my %temphash; my $input_saved = 0; -if ($op eq 'cud-save') { - my @names=$input->multi_param(); +if ( $op eq 'cud-save' ) { + my @names = $input->multi_param(); my $sth_search = $dbh->prepare("SELECT count(*) AS total FROM overduerules WHERE branchcode=? AND categorycode=?"); - my $sth_insert = $dbh->prepare("INSERT INTO overduerules (branchcode,categorycode, delay1,letter1,debarred1, delay2,letter2,debarred2, delay3,letter3,debarred3) VALUES (?,?,?,?,?,?,?,?,?,?,?)"); - my $sth_update=$dbh->prepare("UPDATE overduerules SET delay1=?, letter1=?, debarred1=?, delay2=?, letter2=?, debarred2=?, delay3=?, letter3=?, debarred3=? WHERE branchcode=? AND categorycode=?"); - my $sth_delete=$dbh->prepare("DELETE FROM overduerules WHERE branchcode=? AND categorycode=?"); - my $sth_insert_mtt = $dbh->prepare(" + my $sth_insert = $dbh->prepare( + "INSERT INTO overduerules (branchcode,categorycode, delay1,letter1,debarred1, delay2,letter2,debarred2, delay3,letter3,debarred3) VALUES (?,?,?,?,?,?,?,?,?,?,?)" + ); + my $sth_update = $dbh->prepare( + "UPDATE overduerules SET delay1=?, letter1=?, debarred1=?, delay2=?, letter2=?, debarred2=?, delay3=?, letter3=?, debarred3=? WHERE branchcode=? AND categorycode=?" + ); + my $sth_delete = $dbh->prepare("DELETE FROM overduerules WHERE branchcode=? AND categorycode=?"); + my $sth_insert_mtt = $dbh->prepare( " INSERT INTO overduerules_transport_types( overduerules_id, letternumber, message_transport_type ) VALUES ( (SELECT overduerules_id FROM overduerules WHERE branchcode = ? AND categorycode = ?), ?, ? ) - "); - my $sth_delete_mtt = $dbh->prepare(" + " ); + my $sth_delete_mtt = $dbh->prepare( " DELETE FROM overduerules_transport_types WHERE overduerules_id = (SELECT overduerules_id FROM overduerules WHERE branchcode = ? AND categorycode = ?) - "); + " ); - foreach my $key (@names){ - # ISSUES - if ($key =~ /(delay|letter|debarred)([1-3])-(.*)/) { - my $type = $1; # data type - my $num = $2; # From 1 to 3 - my $bor = $3; # borrower category - my $value = $input->param($key); - if ($type eq 'delay') { - $temphash{$bor}->{"$type$num"} = ($value =~ /^\d+$/ && int($value) > 0) ? int($value) : ''; - } else { - # type is letter - $temphash{$bor}->{"$type$num"} = $value if $value ne ''; - } + foreach my $key (@names) { + + # ISSUES + if ( $key =~ /(delay|letter|debarred)([1-3])-(.*)/ ) { + my $type = $1; # data type + my $num = $2; # From 1 to 3 + my $bor = $3; # borrower category + my $value = $input->param($key); + if ( $type eq 'delay' ) { + $temphash{$bor}->{"$type$num"} = ( $value =~ /^\d+$/ && int($value) > 0 ) ? int($value) : ''; + } else { + + # type is letter + $temphash{$bor}->{"$type$num"} = $value if $value ne ''; } + } } # figure out which rows need to be deleted my @rows_to_delete = grep { blank_row($_) } @category_codes; - foreach my $bor (keys %temphash){ + foreach my $bor ( keys %temphash ) { + # get category name if we need it for an error message - my $bor_category = Koha::Patron::Categories->find($bor); + my $bor_category = Koha::Patron::Categories->find($bor); my $bor_category_name = $bor_category ? $bor_category->description : $bor; # Do some Checking here : delay1 < delay2 {delay1}=~/[^0-9]/ and $temphash{$bor}->{delay1} ne ""){ - $template->param("ERROR"=>1,"ERRORDELAY"=>"delay1","BORERR"=>$bor_category_name); - $err=1; - } elsif ($temphash{$bor}->{delay2}=~/[^0-9]/ and $temphash{$bor}->{delay2} ne ""){ - $template->param("ERROR"=>1,"ERRORDELAY"=>"delay2","BORERR"=>$bor_category_name); - $err=1; - } elsif ($temphash{$bor}->{delay3}=~/[^0-9]/ and $temphash{$bor}->{delay3} ne ""){ - $template->param("ERROR"=>1,"ERRORDELAY"=>"delay3","BORERR"=>$bor_category_name); - $err=1; - } elsif ($temphash{$bor}->{delay1} and not ($temphash{$bor}->{"letter1"} or $temphash{$bor}->{"debarred1"})) { - $template->param("ERROR"=>1,"ERRORUSELESSDELAY"=>"delay1","BORERR"=>$bor_category_name); - $err=1; - } elsif ($temphash{$bor}->{delay2} and not ($temphash{$bor}->{"letter2"} or $temphash{$bor}->{"debarred2"})) { - $template->param("ERROR"=>1,"ERRORUSELESSDELAY"=>"delay2","BORERR"=>$bor_category_name); - $err=1; - } elsif ($temphash{$bor}->{delay3} and not ($temphash{$bor}->{"letter3"} or $temphash{$bor}->{"debarred3"})) { - $template->param("ERROR"=>1,"ERRORUSELESSDELAY"=>"delay3","BORERR"=>$bor_category_name); - $err=1; - }elsif ($temphash{$bor}->{delay3} and - ($temphash{$bor}->{delay3}<=$temphash{$bor}->{delay2} or $temphash{$bor}->{delay3}<=$temphash{$bor}->{delay1}) - or $temphash{$bor}->{delay2} and ($temphash{$bor}->{delay2}<=$temphash{$bor}->{delay1})){ - $template->param("ERROR"=>1,"ERRORORDER"=>1,"BORERR"=>$bor_category_name); - $err=1; + if ( $temphash{$bor}->{delay1} =~ /[^0-9]/ and $temphash{$bor}->{delay1} ne "" ) { + $template->param( "ERROR" => 1, "ERRORDELAY" => "delay1", "BORERR" => $bor_category_name ); + $err = 1; + } elsif ( $temphash{$bor}->{delay2} =~ /[^0-9]/ and $temphash{$bor}->{delay2} ne "" ) { + $template->param( "ERROR" => 1, "ERRORDELAY" => "delay2", "BORERR" => $bor_category_name ); + $err = 1; + } elsif ( $temphash{$bor}->{delay3} =~ /[^0-9]/ and $temphash{$bor}->{delay3} ne "" ) { + $template->param( "ERROR" => 1, "ERRORDELAY" => "delay3", "BORERR" => $bor_category_name ); + $err = 1; + } elsif ( $temphash{$bor}->{delay1} and not( $temphash{$bor}->{"letter1"} or $temphash{$bor}->{"debarred1"} ) ) + { + $template->param( "ERROR" => 1, "ERRORUSELESSDELAY" => "delay1", "BORERR" => $bor_category_name ); + $err = 1; + } elsif ( $temphash{$bor}->{delay2} and not( $temphash{$bor}->{"letter2"} or $temphash{$bor}->{"debarred2"} ) ) + { + $template->param( "ERROR" => 1, "ERRORUSELESSDELAY" => "delay2", "BORERR" => $bor_category_name ); + $err = 1; + } elsif ( $temphash{$bor}->{delay3} and not( $temphash{$bor}->{"letter3"} or $temphash{$bor}->{"debarred3"} ) ) + { + $template->param( "ERROR" => 1, "ERRORUSELESSDELAY" => "delay3", "BORERR" => $bor_category_name ); + $err = 1; + } elsif ( + $temphash{$bor}->{delay3} and ( $temphash{$bor}->{delay3} <= $temphash{$bor}->{delay2} + or $temphash{$bor}->{delay3} <= $temphash{$bor}->{delay1} ) + or $temphash{$bor}->{delay2} and ( $temphash{$bor}->{delay2} <= $temphash{$bor}->{delay1} ) + ) + { + $template->param( "ERROR" => 1, "ERRORORDER" => 1, "BORERR" => $bor_category_name ); + $err = 1; } - unless ($err){ - if (($temphash{$bor}->{delay1} and ($temphash{$bor}->{"letter1"} or $temphash{$bor}->{"debarred1"})) - or ($temphash{$bor}->{delay2} and ($temphash{$bor}->{"letter2"} or $temphash{$bor}->{"debarred2"})) - or ($temphash{$bor}->{delay3} and ($temphash{$bor}->{"letter3"} or $temphash{$bor}->{"debarred3"}))) { - $sth_search->execute($branch,$bor); - my $res = $sth_search->fetchrow_hashref(); - if ($res->{'total'}>0) { - $sth_update->execute( - ($temphash{$bor}->{"delay1"}?$temphash{$bor}->{"delay1"}:undef), - ($temphash{$bor}->{"letter1"}?$temphash{$bor}->{"letter1"}:""), - ($temphash{$bor}->{"debarred1"}?$temphash{$bor}->{"debarred1"}:0), - ($temphash{$bor}->{"delay2"}?$temphash{$bor}->{"delay2"}:undef), - ($temphash{$bor}->{"letter2"}?$temphash{$bor}->{"letter2"}:""), - ($temphash{$bor}->{"debarred2"}?$temphash{$bor}->{"debarred2"}:0), - ($temphash{$bor}->{"delay3"}?$temphash{$bor}->{"delay3"}:undef), - ($temphash{$bor}->{"letter3"}?$temphash{$bor}->{"letter3"}:""), - ($temphash{$bor}->{"debarred3"}?$temphash{$bor}->{"debarred3"}:0), - $branch ,$bor - ); - } else { - $sth_insert->execute($branch,$bor, - ($temphash{$bor}->{"delay1"}?$temphash{$bor}->{"delay1"}:0), - ($temphash{$bor}->{"letter1"}?$temphash{$bor}->{"letter1"}:""), - ($temphash{$bor}->{"debarred1"}?$temphash{$bor}->{"debarred1"}:0), - ($temphash{$bor}->{"delay2"}?$temphash{$bor}->{"delay2"}:0), - ($temphash{$bor}->{"letter2"}?$temphash{$bor}->{"letter2"}:""), - ($temphash{$bor}->{"debarred2"}?$temphash{$bor}->{"debarred2"}:0), - ($temphash{$bor}->{"delay3"}?$temphash{$bor}->{"delay3"}:0), - ($temphash{$bor}->{"letter3"}?$temphash{$bor}->{"letter3"}:""), - ($temphash{$bor}->{"debarred3"}?$temphash{$bor}->{"debarred3"}:0) - ); - } + unless ($err) { + if ( ( $temphash{$bor}->{delay1} and ( $temphash{$bor}->{"letter1"} or $temphash{$bor}->{"debarred1"} ) ) + or ( $temphash{$bor}->{delay2} and ( $temphash{$bor}->{"letter2"} or $temphash{$bor}->{"debarred2"} ) ) + or ( $temphash{$bor}->{delay3} and ( $temphash{$bor}->{"letter3"} or $temphash{$bor}->{"debarred3"} ) ) + ) + { + $sth_search->execute( $branch, $bor ); + my $res = $sth_search->fetchrow_hashref(); + if ( $res->{'total'} > 0 ) { + $sth_update->execute( + ( $temphash{$bor}->{"delay1"} ? $temphash{$bor}->{"delay1"} : undef ), + ( $temphash{$bor}->{"letter1"} ? $temphash{$bor}->{"letter1"} : "" ), + ( $temphash{$bor}->{"debarred1"} ? $temphash{$bor}->{"debarred1"} : 0 ), + ( $temphash{$bor}->{"delay2"} ? $temphash{$bor}->{"delay2"} : undef ), + ( $temphash{$bor}->{"letter2"} ? $temphash{$bor}->{"letter2"} : "" ), + ( $temphash{$bor}->{"debarred2"} ? $temphash{$bor}->{"debarred2"} : 0 ), + ( $temphash{$bor}->{"delay3"} ? $temphash{$bor}->{"delay3"} : undef ), + ( $temphash{$bor}->{"letter3"} ? $temphash{$bor}->{"letter3"} : "" ), + ( $temphash{$bor}->{"debarred3"} ? $temphash{$bor}->{"debarred3"} : 0 ), + $branch, $bor + ); + } else { + $sth_insert->execute( + $branch, $bor, + ( $temphash{$bor}->{"delay1"} ? $temphash{$bor}->{"delay1"} : 0 ), + ( $temphash{$bor}->{"letter1"} ? $temphash{$bor}->{"letter1"} : "" ), + ( $temphash{$bor}->{"debarred1"} ? $temphash{$bor}->{"debarred1"} : 0 ), + ( $temphash{$bor}->{"delay2"} ? $temphash{$bor}->{"delay2"} : 0 ), + ( $temphash{$bor}->{"letter2"} ? $temphash{$bor}->{"letter2"} : "" ), + ( $temphash{$bor}->{"debarred2"} ? $temphash{$bor}->{"debarred2"} : 0 ), + ( $temphash{$bor}->{"delay3"} ? $temphash{$bor}->{"delay3"} : 0 ), + ( $temphash{$bor}->{"letter3"} ? $temphash{$bor}->{"letter3"} : "" ), + ( $temphash{$bor}->{"debarred3"} ? $temphash{$bor}->{"debarred3"} : 0 ) + ); + } - $sth_delete_mtt->execute( $branch, $bor ); - for my $letternumber ( 1..3 ) { - my @mtt = $input->multi_param( "mtt${letternumber}-$bor" ); - next unless @mtt; - for my $mtt ( @mtt ) { - $sth_insert_mtt->execute( $branch, $bor, $letternumber, $mtt); - } + $sth_delete_mtt->execute( $branch, $bor ); + for my $letternumber ( 1 .. 3 ) { + my @mtt = $input->multi_param("mtt${letternumber}-$bor"); + next unless @mtt; + for my $mtt (@mtt) { + $sth_insert_mtt->execute( $branch, $bor, $letternumber, $mtt ); } } + } } } unless ($err) { for my $category_code (@rows_to_delete) { - $sth_delete->execute($branch, $category_code); + $sth_delete->execute( $branch, $category_code ); } - $template->param(datasaved => 1); + $template->param( datasaved => 1 ); $input_saved = 1; } } @@ -208,33 +224,34 @@ if ($op eq 'cud-save') { my $letters = C4::Letters::GetLettersAvailableForALibrary( { branchcode => $branch, - module => "circulation", + module => "circulation", } ); my $message_transport_types = C4::Letters::GetMessageTransportTypes(); my ( @first, @second, @third ); for my $patron_category (@patron_categories) { - if (%temphash and not $input_saved){ + if ( %temphash and not $input_saved ) { + # if we managed to save the form submission, don't # reuse %temphash, but take the values from the # database - this makes it easier to identify # bugs where the form submission was not correctly saved - for my $i ( 1..3 ){ + for my $i ( 1 .. 3 ) { my %row = ( overduename => $patron_category->categorycode, line => $patron_category->description, ); - $row{delay}=$temphash{$patron_category->categorycode}->{"delay$i"}; - $row{debarred}=$temphash{$patron_category->categorycode}->{"debarred$i"}; + $row{delay} = $temphash{ $patron_category->categorycode }->{"delay$i"}; + $row{debarred} = $temphash{ $patron_category->categorycode }->{"debarred$i"}; $row{selected_lettercode} = $temphash{ $patron_category->categorycode }->{"letter$i"}; - my @selected_mtts = @{ GetOverdueMessageTransportTypes( $branch, $patron_category->categorycode, $i) }; + my @selected_mtts = @{ GetOverdueMessageTransportTypes( $branch, $patron_category->categorycode, $i ) }; my @mtts; - for my $mtt ( @$message_transport_types ) { + for my $mtt (@$message_transport_types) { push @mtts, { - value => $mtt, - selected => ( grep {/$mtt/} @selected_mtts ) ? 1 : 0 , - } + value => $mtt, + selected => ( grep { /$mtt/ } @selected_mtts ) ? 1 : 0, + }; } $row{message_transport_types} = \@mtts; if ( $i == 1 ) { @@ -246,11 +263,12 @@ for my $patron_category (@patron_categories) { } } } else { - #getting values from table - my $sth2=$dbh->prepare("SELECT * from overduerules WHERE branchcode=? AND categorycode=?"); - $sth2->execute($branch,$patron_category->categorycode); - my $dat=$sth2->fetchrow_hashref; - for my $i ( 1..3 ){ + + #getting values from table + my $sth2 = $dbh->prepare("SELECT * from overduerules WHERE branchcode=? AND categorycode=?"); + $sth2->execute( $branch, $patron_category->categorycode ); + my $dat = $sth2->fetchrow_hashref; + for my $i ( 1 .. 3 ) { my %row = ( overduename => $patron_category->categorycode, line => $patron_category->description, @@ -258,15 +276,15 @@ for my $patron_category (@patron_categories) { $row{selected_lettercode} = $dat->{"letter$i"}; - if ($dat->{"delay$i"}){$row{delay}=$dat->{"delay$i"};} - if ($dat->{"debarred$i"}){$row{debarred}=$dat->{"debarred$i"};} - my @selected_mtts = @{ GetOverdueMessageTransportTypes( $branch, $patron_category->categorycode, $i) }; + if ( $dat->{"delay$i"} ) { $row{delay} = $dat->{"delay$i"}; } + if ( $dat->{"debarred$i"} ) { $row{debarred} = $dat->{"debarred$i"}; } + my @selected_mtts = @{ GetOverdueMessageTransportTypes( $branch, $patron_category->categorycode, $i ) }; my @mtts; - for my $mtt ( @$message_transport_types ) { + for my $mtt (@$message_transport_types) { push @mtts, { - value => $mtt, - selected => ( grep {/$mtt/} @selected_mtts ) ? 1 : 0 , - } + value => $mtt, + selected => ( grep { /$mtt/ } @selected_mtts ) ? 1 : 0, + }; } $row{message_transport_types} = \@mtts; if ( $i == 1 ) { @@ -283,27 +301,27 @@ for my $patron_category (@patron_categories) { my @tabs = ( { - id => 'first', + id => 'first', number => 1, values => \@first, }, { - id => 'second', + id => 'second', number => 2, values => \@second, }, { - id => 'third', + id => 'third', number => 3, values => \@third, }, ); $template->param( - table => ( @first or @second or @third ? 1 : 0 ), - branch => $branch, - tabs => \@tabs, + table => ( @first or @second or @third ? 1 : 0 ), + branch => $branch, + tabs => \@tabs, message_transport_types => $message_transport_types, - letters => $letters, + letters => $letters, ); output_html_with_http_headers $input, $cookie, $template->output; diff --git a/tools/page.pl b/tools/page.pl index 34d42fd763..a3c8936cc5 100755 --- a/tools/page.pl +++ b/tools/page.pl @@ -17,18 +17,18 @@ use Modern::Perl; -use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use Koha::AdditionalContents; my $query = CGI->new; my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "tools/page.tt", - query => $query, - type => "intranet", - flagsrequired => { catalogue => 1 }, + template_name => "tools/page.tt", + query => $query, + type => "intranet", + flagsrequired => { catalogue => 1 }, } ); @@ -38,7 +38,11 @@ my $branch = C4::Context->userenv->{'branch'}; my $page = Koha::AdditionalContents->find($page_id); -if ( !$page || $page->category ne 'pages' || $page->branchcode && $page->branchcode != $branch || $page->location ne 'staff_only' && $page->location ne 'staff_and_opac' ) { +if ( !$page + || $page->category ne 'pages' + || $page->branchcode && $page->branchcode != $branch + || $page->location ne 'staff_only' && $page->location ne 'staff_and_opac' ) +{ print $query->redirect('/cgi-bin/koha/errors/404.pl'); exit; } diff --git a/tools/picture-upload.pl b/tools/picture-upload.pl index 809657dc63..ec39cf3ed1 100755 --- a/tools/picture-upload.pl +++ b/tools/picture-upload.pl @@ -28,7 +28,7 @@ use MIME::Base64; use Cwd; use C4::Context; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_and_exit output_html_with_http_headers ); use C4::Members; @@ -39,21 +39,24 @@ use Koha::Token; my $input = CGI->new; -unless (C4::Context->preference('patronimages')) { +unless ( C4::Context->preference('patronimages') ) { + # redirect to intranet home if patronimages is not enabled print $input->redirect("/cgi-bin/koha/mainpage.pl"); exit; } -my ($template, $loggedinuser, $cookie) - = get_template_and_user({template_name => "tools/picture-upload.tt", - query => $input, - type => "intranet", - flagsrequired => { tools => 'batch_upload_patron_images'}, - }); +my ( $template, $loggedinuser, $cookie ) = get_template_and_user( + { + template_name => "tools/picture-upload.tt", + query => $input, + type => "intranet", + flagsrequired => { tools => 'batch_upload_patron_images' }, + } +); -our $filetype = $input->param('filetype') || ''; -my $cardnumber = $input->param('cardnumber'); +our $filetype = $input->param('filetype') || ''; +my $cardnumber = $input->param('cardnumber'); our $uploadfilename = $input->param('uploadfile') || $input->param('uploadfilename') || ''; my $uploadfiletext = $input->param('uploadfiletext') || ''; my $uploadfile = $input->upload('uploadfile'); @@ -65,7 +68,9 @@ my $op = $input->param('op') || ''; # coded. -fbcit our $logger = Koha::Logger->get; -$logger->debug("Params are: filetype=$filetype, cardnumber=$cardnumber, borrowernumber=$borrowernumber, uploadfile=$uploadfilename"); +$logger->debug( + "Params are: filetype=$filetype, cardnumber=$cardnumber, borrowernumber=$borrowernumber, uploadfile=$uploadfilename" +); =head1 NAME @@ -87,7 +92,7 @@ our @counts = (); our %errors = (); # Case is important in these operational values as the template must use case to be visually pleasing! -if ( ( $op eq 'cud-Upload' ) && ($uploadfile || $uploadfiletext) ) { +if ( ( $op eq 'cud-Upload' ) && ( $uploadfile || $uploadfiletext ) ) { my $dirname = File::Temp::tempdir( CLEANUP => 1 ); my $filesuffix; @@ -95,14 +100,13 @@ if ( ( $op eq 'cud-Upload' ) && ($uploadfile || $uploadfiletext) ) { if ( $uploadfilename =~ m/(\..+)$/i ) { $filesuffix = $1; } - ( $tfh, $tempfile ) = - File::Temp::tempfile( SUFFIX => $filesuffix, UNLINK => 1 ); + ( $tfh, $tempfile ) = File::Temp::tempfile( SUFFIX => $filesuffix, UNLINK => 1 ); my ( @directories, $results ); $errors{'NOWRITETEMP'} = 1 unless ( -w $dirname ); if ( length($uploadfiletext) == 0 ) { $errors{'NOTZIP'} = 1 - if ( $uploadfilename !~ /\.zip$/i && $filetype =~ m/zip/i ); + if ( $uploadfilename !~ /\.zip$/i && $filetype =~ m/zip/i ); $errors{'EMPTYUPLOAD'} = 1 unless ( length($uploadfile) > 0 ); } @@ -117,6 +121,7 @@ if ( ( $op eq 'cud-Upload' ) && ($uploadfile || $uploadfiletext) ) { print $tfh $_; } } else { + # data type controlled in toDataURL() in template if ( $uploadfiletext =~ /data:image\/jpeg;base64,(.*)/ ) { my $encoded_picture = $1; @@ -136,6 +141,7 @@ if ( ( $op eq 'cud-Upload' ) && ($uploadfile || $uploadfiletext) ) { unless ( $exit_code == 0 ) { $errors{'UZIPFAIL'} = $uploadfilename; $template->param( ERRORS => [ \%errors ] ); + # This error is fatal to the import, so bail out here output_html_with_http_headers $input, $cookie, $template->output; exit; @@ -146,7 +152,7 @@ if ( ( $op eq 'cud-Upload' ) && ($uploadfile || $uploadfiletext) ) { opendir $recdir_h, $recursive_dir; while ( my $entry = readdir $recdir_h ) { push @directories, "$recursive_dir/$entry" - if ( -d "$recursive_dir/$entry" and $entry !~ /^\./ ); + if ( -d "$recursive_dir/$entry" and $entry !~ /^\./ ); } closedir $recdir_h; } @@ -155,19 +161,20 @@ if ( ( $op eq 'cud-Upload' ) && ($uploadfile || $uploadfiletext) ) { $handled++ if $results == 1; } $total = scalar @directories; - } - else { + } else { + #if ($filetype eq 'zip' ) - $results = handle_dir( $dirname, $filesuffix, $template, $cardnumber, - $tempfile ); + $results = handle_dir( + $dirname, $filesuffix, $template, $cardnumber, + $tempfile + ); $handled++ if $results == 1; - $total = 1; + $total = 1; } - if ( $results!=1 || %errors ) { + if ( $results != 1 || %errors ) { $template->param( ERRORS => [$results] ); - } - else { + } else { my $filecount; map { $filecount += $_->{count} } @counts; $logger->debug("Total directories processed: $total"); @@ -179,27 +186,21 @@ if ( ( $op eq 'cud-Upload' ) && ($uploadfile || $uploadfiletext) ) { TCOUNTS => ( $filecount > 0 ? $filecount : undef ), ); $template->param( borrowernumber => $borrowernumber ) - if $borrowernumber; + if $borrowernumber; } -} -elsif ( ( $op eq 'cud-Upload' ) && !$uploadfile ) { +} elsif ( ( $op eq 'cud-Upload' ) && !$uploadfile ) { warn "Problem uploading file or no file uploaded."; $template->param( cardnumber => $cardnumber ); $template->param( filetype => $filetype ); -} -elsif ( $op eq 'cud-Delete' ) { - my $deleted = eval { - Koha::Patron::Images->find( $borrowernumber )->delete; - }; +} elsif ( $op eq 'cud-Delete' ) { + my $deleted = eval { Koha::Patron::Images->find($borrowernumber)->delete; }; if ( $@ or not $deleted ) { warn "Image for patron '$borrowernumber' has not been deleted"; } } if ( $borrowernumber && !%errors && !$template->param('ERRORS') ) { - print $input->redirect( - "/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber"); -} -else { + print $input->redirect("/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber"); +} else { output_html_with_http_headers $input, $cookie, $template->output; } @@ -208,6 +209,7 @@ sub handle_dir { my ( %counts, %direrrors ); $logger->debug("Entering sub handle_dir; passed \$dir=$dir, \$suffix=$suffix"); if ( $suffix =~ m/zip/i ) { + # If we were sent a zip file, process any included data/idlink.txt files my ( $file, $filename ); undef $cardnumber; @@ -225,6 +227,7 @@ sub handle_dir { unless ( open( $fh, '<', $file ) ) { warn "Opening $file failed!"; $direrrors{'OPNLINK'} = $file; + # This error is fatal to the import of this directory contents # so bail and return the error to the caller return \%direrrors; @@ -239,14 +242,16 @@ sub handle_dir { my $delim = ( $line =~ /\t/ ) ? "\t" : ( $line =~ /,/ ) ? "," : ""; $logger->debug("Delimeter is \'$delim\'"); unless ( $delim eq "," || $delim eq "\t" ) { - warn "Unrecognized or missing field delimeter. Please verify that you are using either a ',' or a 'tab'"; + warn + "Unrecognized or missing field delimeter. Please verify that you are using either a ',' or a 'tab'"; $direrrors{'DELERR'} = 1; + # This error is fatal to the import of this directory contents # so bail and return the error to the caller return \%direrrors; } ( $cardnumber, $filename ) = split $delim, $line; - $cardnumber =~ s/[\"\r\n]//g; # remove offensive characters + $cardnumber =~ s/[\"\r\n]//g; # remove offensive characters $filename =~ s/[\"\r\n\s]//g; $logger->debug("Cardnumber: $cardnumber Filename: $filename"); $source = Cwd::abs_path("$dir/$filename"); @@ -258,8 +263,7 @@ sub handle_dir { %counts = handle_file( $cardnumber, $source, $template, %counts ); } closedir $dir_h; - } - else { + } else { %counts = handle_file( $cardnumber, $source, $template, %counts ); } push @counts, \%counts; @@ -271,30 +275,32 @@ sub handle_file { $logger->debug("Entering sub handle_file; passed \$cardnumber=$cardnumber, \$source=$source"); $count{filenames} = () if !$count{filenames}; $count{source} = $source if !$count{source}; - $count{count} = 0 unless exists $count{count}; + $count{count} = 0 unless exists $count{count}; my %filerrors; my $filename; if ( $filetype eq 'image' ) { $filename = $uploadfilename; - } - else { + } else { $filename = $1 if ( $source && $source =~ /\/([^\/]+)$/ ); } if ( $cardnumber && $source ) { + # Now process any imagefiles $logger->debug("Source: $source"); my $size = ( stat($source) )[7]; if ( $size > 2097152 ) { + # This check is necessary even with image resizing to avoid possible security/performance issues... $filerrors{'OVRSIZ'} = 1; push my @filerrors, \%filerrors; push @{ $count{filenames} }, - { + { filerrors => \@filerrors, source => $filename, cardnumber => $cardnumber - }; + }; $template->param( ERRORS => 1 ); + # this one is fatal so bail here... return %count; } @@ -305,139 +311,142 @@ sub handle_file { if ( defined $srcimage ) { my $imgfile; my $mimetype = 'image/png'; + # GD autodetects three basic image formats: PNG, JPEG, XPM # we will convert all to PNG which is lossless... # Check the pixel size of the image we are about to import... my ( $width, $height ) = $srcimage->getBounds(); $logger->debug("$filename is $width pix X $height pix."); if ( $width > 200 || $height > 300 ) { + # MAX pixel dims are 200 X 300... $logger->debug("$filename exceeds the maximum pixel dimensions of 200 X 300. Resizing..."); + # Percent we will reduce the image dimensions by... my $percent_reduce; if ( $width > 200 ) { + # If the width is oversize, scale based on width overage... $percent_reduce = sprintf( "%.5f", ( 140 / $width ) ); - } - else { + } else { + # otherwise scale based on height overage. $percent_reduce = sprintf( "%.5f", ( 200 / $height ) ); } - my $width_reduce = - sprintf( "%.0f", ( $width * $percent_reduce ) ); - my $height_reduce = - sprintf( "%.0f", ( $height * $percent_reduce ) ); - $logger->debug("Reducing $filename by " - . ( $percent_reduce * 100 ) - . "\% or to $width_reduce pix X $height_reduce pix"); + my $width_reduce = sprintf( "%.0f", ( $width * $percent_reduce ) ); + my $height_reduce = sprintf( "%.0f", ( $height * $percent_reduce ) ); + $logger->debug( "Reducing $filename by " + . ( $percent_reduce * 100 ) + . "\% or to $width_reduce pix X $height_reduce pix" ); + #'1' creates true color image... $image = GD::Image->new( $width_reduce, $height_reduce, 1 ); - $image->copyResampled( $srcimage, 0, 0, 0, 0, $width_reduce, - $height_reduce, $width, $height ); + $image->copyResampled( + $srcimage, 0, 0, 0, 0, $width_reduce, + $height_reduce, $width, $height + ); $imgfile = $image->png(); - $logger->debug("$filename is " - . length($imgfile) - . " bytes after resizing."); + $logger->debug( "$filename is " . length($imgfile) . " bytes after resizing." ); undef $image; - undef $srcimage; # This object can get big... - } - else { + undef $srcimage; # This object can get big... + } else { $image = $srcimage; $imgfile = $image->png(); - $logger->debug("$filename is " . length($imgfile) . " bytes."); + $logger->debug( "$filename is " . length($imgfile) . " bytes." ); undef $image; - undef $srcimage; # This object can get big... + undef $srcimage; # This object can get big... } $logger->debug("Image is of mimetype $mimetype"); if ($mimetype) { - my $patron = Koha::Patrons->find({ cardnumber => $cardnumber }); - if ( $patron ) { + my $patron = Koha::Patrons->find( { cardnumber => $cardnumber } ); + if ($patron) { my $image = $patron->image; - $image ||= Koha::Patron::Image->new({ borrowernumber => $patron->borrowernumber }); - $image->set({ - mimetype => $mimetype, - imagefile => $imgfile, - }); + $image ||= Koha::Patron::Image->new( { borrowernumber => $patron->borrowernumber } ); + $image->set( + { + mimetype => $mimetype, + imagefile => $imgfile, + } + ); eval { $image->store }; - if ( $@ ) { + if ($@) { + # Errors from here on are fatal only to the import of a particular image #so don't bail, just note the error and keep going warn "Database returned error: $@"; $filerrors{'DBERR'} = 1; push my @filerrors, \%filerrors; push @{ $count{filenames} }, - { + { filerrors => \@filerrors, source => $filename, cardnumber => $cardnumber - }; + }; $template->param( ERRORS => 1 ); } else { $count{count}++; push @{ $count{filenames} }, - { source => $filename, cardnumber => $cardnumber }; + { source => $filename, cardnumber => $cardnumber }; } } else { warn "Patron with the cardnumber '$cardnumber' does not exist"; $filerrors{'CARDNUMBER_DOES_NOT_EXIST'} = 1; push my @filerrors, \%filerrors; push @{ $count{filenames} }, - { + { filerrors => \@filerrors, source => $filename, cardnumber => $cardnumber - }; + }; $template->param( ERRORS => 1 ); } - } - else { + } else { warn "Unable to determine mime type of $filename. Please verify mimetype."; $filerrors{'MIMERR'} = 1; push my @filerrors, \%filerrors; push @{ $count{filenames} }, - { + { filerrors => \@filerrors, source => $filename, cardnumber => $cardnumber - }; + }; $template->param( ERRORS => 1 ); } - } - else { + } else { warn "Contents of $filename corrupted!"; + #$count{count}--; $filerrors{'CORERR'} = 1; push my @filerrors, \%filerrors; push @{ $count{filenames} }, - { + { filerrors => \@filerrors, source => $filename, cardnumber => $cardnumber - }; + }; $template->param( ERRORS => 1 ); } - } - else { + } else { warn "Opening $source failed!"; $filerrors{'OPNERR'} = 1; push my @filerrors, \%filerrors; push @{ $count{filenames} }, - { + { filerrors => \@filerrors, source => $filename, cardnumber => $cardnumber - }; + }; $template->param( ERRORS => 1 ); } - } - else { + } else { + # The need for this seems a bit unlikely, however, to maximize error trapping it is included warn "Missing " - . ( + . ( $cardnumber ? "filename" : ( $filename ? "cardnumber" : "cardnumber and filename" ) - ); + ); $filerrors{'CRDFIL'} = ( $cardnumber ? "filename" @@ -445,11 +454,11 @@ sub handle_file { ); push my @filerrors, \%filerrors; push @{ $count{filenames} }, - { + { filerrors => \@filerrors, source => $filename, cardnumber => $cardnumber - }; + }; $template->param( ERRORS => 1 ); } return (%count); diff --git a/tools/problem-reports.pl b/tools/problem-reports.pl index 2615db4429..ced44a5de3 100755 --- a/tools/problem-reports.pl +++ b/tools/problem-reports.pl @@ -22,7 +22,7 @@ use Modern::Perl; use CGI qw ( -utf8 ); use C4::Context; use C4::Output qw( output_html_with_http_headers ); -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use Koha::ProblemReports; my $query = CGI->new; @@ -42,20 +42,20 @@ my $action = $query->param("op") || 'none'; my @report_ids = $query->multi_param('report_ids'); if ( $action eq 'cud-mark_selected-viewed' ) { - foreach my $report_id ( @report_ids ) { + foreach my $report_id (@report_ids) { my $report = Koha::ProblemReports->find($report_id); - $report->set({ status => 'Viewed' })->store; - } + $report->set( { status => 'Viewed' } )->store; + } } elsif ( $action eq 'cud-mark_selected-closed' ) { - foreach my $report_id ( @report_ids ) { + foreach my $report_id (@report_ids) { my $report = Koha::ProblemReports->find($report_id); - $report->set({ status => 'Closed' })->store; + $report->set( { status => 'Closed' } )->store; } } elsif ( $action eq 'cud-mark_selected-new' ) { - foreach my $report_id ( @report_ids ) { + foreach my $report_id (@report_ids) { my $report = Koha::ProblemReports->find($report_id); - $report->set({ status => 'New' })->store; + $report->set( { status => 'New' } )->store; } } diff --git a/tools/quotes-upload.pl b/tools/quotes-upload.pl index 6efb6da313..09f74298d8 100755 --- a/tools/quotes-upload.pl +++ b/tools/quotes-upload.pl @@ -30,10 +30,10 @@ my $cgi = CGI->new; my ( $template, $borrowernumber, $cookie ) = get_template_and_user( { - template_name => "tools/quotes-upload.tt", - query => $cgi, - type => "intranet", - flagsrequired => { tools => 'edit_quotes' }, + template_name => "tools/quotes-upload.tt", + query => $cgi, + type => "intranet", + flagsrequired => { tools => 'edit_quotes' }, } ); diff --git a/tools/quotes.pl b/tools/quotes.pl index e6c83d51b2..d5cad5d483 100755 --- a/tools/quotes.pl +++ b/tools/quotes.pl @@ -17,7 +17,7 @@ use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use Try::Tiny qw( catch try ); use C4::Auth qw( get_template_and_user ); @@ -42,11 +42,10 @@ my @messages; if ( $op eq 'add_form' ) { $template->param( quote => Koha::Quotes->find($id), ); -} -elsif ( $op eq 'cud-add_validate' ) { +} elsif ( $op eq 'cud-add_validate' ) { my @fields = qw( - source - text + source + text ); if ($id) { @@ -58,12 +57,10 @@ elsif ( $op eq 'cud-add_validate' ) { try { $quote->store; push @messages, { type => 'message', code => 'success_on_update' }; - } - catch { + } catch { push @messages, { type => 'alert', code => 'error_on_update' }; } - } - else { + } else { my $quote = Koha::Quote->new( { id => $id, @@ -74,19 +71,17 @@ elsif ( $op eq 'cud-add_validate' ) { try { $quote->store; push @messages, { type => 'message', code => 'success_on_insert' }; - } - catch { + } catch { push @messages, { type => 'alert', code => 'error_on_insert' }; }; } $op = 'list'; -} -else { +} else { $op = 'list'; } $template->param( quotes_count => Koha::Quotes->search->count ) - if $op eq 'list'; + if $op eq 'list'; $template->param( messages => \@messages, diff --git a/tools/scheduler.pl b/tools/scheduler.pl index cbeefc11db..3a7b03915d 100755 --- a/tools/scheduler.pl +++ b/tools/scheduler.pl @@ -19,12 +19,12 @@ use Modern::Perl; use C4::Context; -use C4::Scheduler qw( add_at_job get_jobs remove_at_job ); +use C4::Scheduler qw( add_at_job get_jobs remove_at_job ); use C4::Reports::Guided qw( get_saved_reports ); -use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); -use C4::Output qw( output_html_with_http_headers ); -use Koha::DateUtils qw( dt_from_string );; +use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); +use C4::Output qw( output_html_with_http_headers ); +use Koha::DateUtils qw( dt_from_string ); use Koha::Reports; use Koha::Email; @@ -32,20 +32,19 @@ my $input = CGI->new; my $base; if ( C4::Context->config('supportdir') ) { - $base = C4::Context->config('supportdir'); -} -else { - $base = "/usr/share/koha/bin"; + $base = C4::Context->config('supportdir'); +} else { + $base = "/usr/share/koha/bin"; } my $CONFIG_NAME = $ENV{'KOHA_CONF'}; my ( $template, $borrowernumber, $cookie ) = get_template_and_user( { - template_name => "tools/scheduler.tt", - query => $input, - type => "intranet", - flagsrequired => { tools => 'schedule_tasks' }, + template_name => "tools/scheduler.tt", + query => $input, + type => "intranet", + flagsrequired => { tools => 'schedule_tasks' }, } ); @@ -57,7 +56,7 @@ if ( $op eq 'cud-add' ) { my $startdate = dt_from_string( scalar $input->param('startdate'), 'iso' )->ymd; # Formatting it for Schedule::At - $startdate = join('', (split /-/, $startdate)); + $startdate = join( '', ( split /-/, $startdate ) ); my $starttime = $input->param('starttime'); $starttime =~ s/\://g; my $start = $startdate . $starttime; @@ -96,8 +95,7 @@ if ( $op eq 'cud-add' ) { unless ( add_at_job( $start, $command ) ) { $template->param( job_add_failed => 1 ); } - } - else { + } else { $template->param( job_add_failed => 1 ); } } elsif ( $op eq 'cud-delete' ) { diff --git a/tools/showdiffmarc.pl b/tools/showdiffmarc.pl index 4729b3abe5..92b3217b24 100755 --- a/tools/showdiffmarc.pl +++ b/tools/showdiffmarc.pl @@ -26,21 +26,21 @@ use CGI qw(:standard -utf8); # Koha modules used use C4::Context; -use C4::Output qw( output_html_with_http_headers ); -use C4::Auth qw( get_template_and_user ); -use C4::Auth qw( get_template_and_user ); -use C4::ImportBatch qw( GetImportBiblios ); +use C4::Output qw( output_html_with_http_headers ); +use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); +use C4::ImportBatch qw( GetImportBiblios ); use C4::AuthoritiesMarc qw( GetAuthority ); use Koha::Biblios; use Koha::Import::Records; # Input params -my $input = CGI->new; +my $input = CGI->new; my $recordid = $input->param('id'); -my $importid = $input->param('importid'); -my $batchid = $input->param('batchid'); -my $type = $input->param('type'); +my $importid = $input->param('importid'); +my $batchid = $input->param('batchid'); +my $type = $input->param('type'); if ( not $recordid or not $importid ) { print $input->redirect("/cgi-bin/koha/errors/404.pl"); @@ -48,35 +48,37 @@ if ( not $recordid or not $importid ) { } # Init vars -my ($record, $recordImportid, $recordTitle, $importTitle, $formatted1, $formatted2, $errorFormatted1, $errorFormatted2); +my ( + $record, $recordImportid, $recordTitle, $importTitle, $formatted1, $formatted2, $errorFormatted1, + $errorFormatted2 +); # Prepare template my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "tools/showdiffmarc.tt", - query => $input, - type => "intranet", - flagsrequired => { tools => 'manage_staged_marc' }, + template_name => "tools/showdiffmarc.tt", + query => $input, + type => "intranet", + flagsrequired => { tools => 'manage_staged_marc' }, } ); if ( $type eq 'biblio' ) { - my $biblio = Koha::Biblios->find( $recordid ); - $record = $biblio->metadata_record( { embed_items => 1 } ); + my $biblio = Koha::Biblios->find($recordid); + $record = $biblio->metadata_record( { embed_items => 1 } ); $recordTitle = $biblio->title; +} elsif ( $type eq 'auth' ) { + $record = GetAuthority($recordid); + $recordTitle = "Authority number " . $recordid; #FIXME we should get the main heading } -elsif ( $type eq 'auth' ) { - $record = GetAuthority( $recordid ); - $recordTitle = "Authority number " . $recordid; #FIXME we should get the main heading -} -if( $record ) { +if ($record) { $formatted1 = $record->as_formatted; } else { $errorFormatted1 = 1; } -if( $importid ) { - my $import_record = Koha::Import::Records->find($importid); +if ($importid) { + my $import_record = Koha::Import::Records->find($importid); my $recordImportid = $import_record->get_marc_record(); $formatted2 = $recordImportid->as_formatted; my $biblio = GetImportBiblios($importid); diff --git a/tools/stage-marc-import.pl b/tools/stage-marc-import.pl index 736a5223db..a990d72fe3 100755 --- a/tools/stage-marc-import.pl +++ b/tools/stage-marc-import.pl @@ -34,7 +34,7 @@ use Try::Tiny; # Koha modules used use C4::Context; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use C4::Matcher; use Koha::UploadedFiles; @@ -55,7 +55,7 @@ my $item_action = $input->param('item_action'); my $comments = $input->param('comments'); my $record_type = $input->param('record_type'); my $encoding = $input->param('encoding') || 'UTF-8'; -my $format = $input->param('format') || 'ISO2709'; +my $format = $input->param('format') || 'ISO2709'; my $marc_modification_template = $input->param('marc_modification_template_id'); my $basketno = $input->param('basketno'); my $booksellerid = $input->param('booksellerid'); @@ -64,10 +64,10 @@ my @messages; my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "tools/stage-marc-import.tt", - query => $input, - type => "intranet", - flagsrequired => { tools => 'stage_marc_import' }, + template_name => "tools/stage-marc-import.tt", + query => $input, + type => "intranet", + flagsrequired => { tools => 'stage_marc_import' }, } ); @@ -77,7 +77,7 @@ $template->param( ); if ( $op eq 'cud-stage' && $fileID ) { - my $upload = Koha::UploadedFiles->find( $fileID ); + my $upload = Koha::UploadedFiles->find($fileID); my $filepath = $upload->full_path; my $filename = $upload->filename; @@ -99,25 +99,25 @@ if ( $op eq 'cud-stage' && $fileID ) { profile_id => $profile_id, }; try { - my $job_id = Koha::BackgroundJob::StageMARCForImport->new->enqueue( $params ); + my $job_id = Koha::BackgroundJob::StageMARCForImport->new->enqueue($params); if ($job_id) { $template->param( job_enqueued => 1, - job_id => $job_id, + job_id => $job_id, ); } - } - catch { + } catch { warn $_; push @messages, - { + { type => 'error', code => 'cannot_enqueue_job', error => $_, - }; + }; }; } else { + # initial form if ( C4::Context->preference("marcflavour") eq "UNIMARC" ) { $template->param( "UNIMARC" => 1 ); @@ -130,9 +130,11 @@ if ( $op eq 'cud-stage' && $fileID ) { if ( C4::Context->config('enable_plugins') ) { - my @plugins = Koha::Plugins->new()->GetPlugins({ - method => 'to_marc', - }); + my @plugins = Koha::Plugins->new()->GetPlugins( + { + method => 'to_marc', + } + ); $template->param( plugins => \@plugins ); } } diff --git a/tools/stockrotation.pl b/tools/stockrotation.pl index b818a38f7d..f8329b97cb 100755 --- a/tools/stockrotation.pl +++ b/tools/stockrotation.pl @@ -36,11 +36,13 @@ use Koha::StockRotationRotas; use Koha::StockRotationItems; use Koha::StockRotationStages; use Koha::Item; -use Koha::Util::StockRotation qw( get_branches get_stages move_to_next_stage toggle_indemand remove_from_stage add_items_to_rota get_barcodes_status ); +use Koha::Util::StockRotation + qw( get_branches get_stages move_to_next_stage toggle_indemand remove_from_stage add_items_to_rota get_barcodes_status ); my $input = CGI->new; -unless (C4::Context->preference('StockRotation')) { +unless ( C4::Context->preference('StockRotation') ) { + # redirect to Intranet home if self-check is not enabled print $input->redirect("/cgi-bin/koha/mainpage.pl"); exit; @@ -48,11 +50,11 @@ unless (C4::Context->preference('StockRotation')) { my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => 'tools/stockrotation.tt', - query => $input, - type => 'intranet', - flagsrequired => { - tools => '*', + template_name => 'tools/stockrotation.tt', + query => $input, + type => 'intranet', + flagsrequired => { + tools => '*', stockrotation => '*', }, } @@ -65,14 +67,12 @@ our %params = $input->Vars(); my $op = $params{op}; -if (!defined $op) { +if ( !defined $op ) { # No operation is supplied, we're just displaying the list of rotas my $rotas = Koha::StockRotationRotas->search( undef, - { - order_by => { -asc => 'title' } - } + { order_by => { -asc => 'title' } } )->as_list; $template->param( @@ -80,20 +80,18 @@ if (!defined $op) { no_op_set => 1 ); -} elsif ($op eq 'create_edit_rota') { +} elsif ( $op eq 'create_edit_rota' ) { # Edit an existing rota or define a new one my $rota_id = $params{rota_id}; my $rota = {}; - if (!defined $rota_id) { + if ( !defined $rota_id ) { # No ID supplied, we're creating a new rota # Create a shell rota hashref - $rota = { - cyclical => 1 - }; + $rota = { cyclical => 1 }; } else { @@ -107,30 +105,30 @@ if (!defined $op) { op => $op ); -} elsif ($op eq 'cud-toggle_rota') { +} elsif ( $op eq 'cud-toggle_rota' ) { # Find and update the active status of the rota - my $rota = Koha::StockRotationRotas->find($params{rota_id}); + my $rota = Koha::StockRotationRotas->find( $params{rota_id} ); - my $new_active = ($rota->active == 1) ? 0 : 1; + my $new_active = ( $rota->active == 1 ) ? 0 : 1; $rota->active($new_active)->store; # Return to rotas page print $input->redirect('stockrotation.pl'); -} elsif ($op eq 'cud-process_rota') { +} elsif ( $op eq 'cud-process_rota' ) { # Get a hashref of the submitted rota data my $rota = get_rota_from_form(); - if (!process_rota($rota)) { + if ( !process_rota($rota) ) { # The submitted rota was invalid $template->param( error => 'invalid_form', - rota => $rota, - op => 'create_edit_rota' + rota => $rota, + op => 'create_edit_rota' ); } else { @@ -140,9 +138,9 @@ if (!defined $op) { } -} elsif ($op eq 'manage_stages') { +} elsif ( $op eq 'manage_stages' ) { - my $rota = Koha::StockRotationRotas->find($params{rota_id}); + my $rota = Koha::StockRotationRotas->find( $params{rota_id} ); $template->param( rota => $rota, @@ -152,16 +150,17 @@ if (!defined $op) { op => $op ); -} elsif ($op eq 'create_edit_stage') { +} elsif ( $op eq 'create_edit_stage' ) { # Edit an existing stage or define a new one my $stage_id = $params{stage_id}; my $rota_id = $params{rota_id}; - if (!defined $stage_id) { + if ( !defined $stage_id ) { my $rota = Koha::StockRotationRotas->find($rota_id); + # No ID supplied, we're creating a new stage $template->param( branches => get_branches(), @@ -187,7 +186,7 @@ if (!defined $op) { } -} elsif ($op eq 'confirm_remove_from_rota') { +} elsif ( $op eq 'confirm_remove_from_rota' ) { # Get the stage we're deleting $template->param( @@ -197,56 +196,48 @@ if (!defined $op) { item_id => $params{item_id} ); -} elsif ($op eq 'confirm_delete_rota') { +} elsif ( $op eq 'confirm_delete_rota' ) { # Get the rota we're deleting - my $rota = Koha::StockRotationRotas->find($params{rota_id}); + my $rota = Koha::StockRotationRotas->find( $params{rota_id} ); # Get all items on this rota, for each prefetch their # stage and biblio objects my $sritems = Koha::StockRotationItems->search( { 'stage.rota_id' => $params{rota_id} }, - { - prefetch => { - stage => { - 'stockrotationitems' => { - 'itemnumber' => 'biblionumber' - } - } - } - } + { prefetch => { stage => { 'stockrotationitems' => { 'itemnumber' => 'biblionumber' } } } } ); $template->param( - rota_id => $params{rota_id}, - sritemstotal => $sritems->count, - op => $op + rota_id => $params{rota_id}, + sritemstotal => $sritems->count, + op => $op ); -} elsif ($op eq 'cud-delete_rota') { +} elsif ( $op eq 'cud-delete_rota' ) { # Get the rota we're deleting - my $rota = Koha::StockRotationRotas->find($params{rota_id}); + my $rota = Koha::StockRotationRotas->find( $params{rota_id} ); $rota->delete; # Return to the rotas list print $input->redirect("/cgi-bin/koha/tools/stockrotation.pl"); -} elsif ($op eq 'confirm_delete_stage') { +} elsif ( $op eq 'confirm_delete_stage' ) { # Get the stage we're deleting - my $stage = Koha::StockRotationStages->find($params{stage_id}); + my $stage = Koha::StockRotationStages->find( $params{stage_id} ); $template->param( op => $op, stage => $stage ); -} elsif ($op eq 'cud-delete_stage') { +} elsif ( $op eq 'cud-delete_stage' ) { # Get the stage we're deleting - my $stage = Koha::StockRotationStages->find($params{stage_id}); + my $stage = Koha::StockRotationStages->find( $params{stage_id} ); # Get the ID of the rota with which this stage is associated # (so we can return to the "Manage stages" page after deletion) @@ -257,7 +248,7 @@ if (!defined $op) { # Return to the stages list print $input->redirect("?op=manage_stages&rota_id=$rota_id"); -} elsif ($op eq 'cud-process_stage') { +} elsif ( $op eq 'cud-process_stage' ) { # Get a hashref of the submitted stage data my $stage = get_stage_from_form(); @@ -265,7 +256,7 @@ if (!defined $op) { # The rota we're managing my $rota_id = $params{rota_id}; - if (!process_stage($stage, $rota_id)) { + if ( !process_stage( $stage, $rota_id ) ) { # The submitted stage was invalid # Get all branches @@ -286,23 +277,15 @@ if (!defined $op) { } -} elsif ($op eq 'manage_items') { +} elsif ( $op eq 'manage_items' ) { - my $rota = Koha::StockRotationRotas->find($params{rota_id}); + my $rota = Koha::StockRotationRotas->find( $params{rota_id} ); # Get all items on this rota, for each prefetch their # stage and biblio objects my $sritems = Koha::StockRotationItems->search( { 'stage.rota_id' => $params{rota_id} }, - { - prefetch => { - stage => { - 'stockrotationitems' => { - 'itemnumber' => 'biblionumber' - } - } - } - } + { prefetch => { stage => { 'stockrotationitems' => { 'itemnumber' => 'biblionumber' } } } } ); $template->param( @@ -315,30 +298,30 @@ if (!defined $op) { op => $op ); -} elsif ($op eq 'cud-move_to_next_stage') { +} elsif ( $op eq 'cud-move_to_next_stage' ) { - move_to_next_stage($params{item_id}, $params{stage_id}); + move_to_next_stage( $params{item_id}, $params{stage_id} ); # Return to the items list - print $input->redirect("?op=manage_items&rota_id=" . $params{rota_id}); + print $input->redirect( "?op=manage_items&rota_id=" . $params{rota_id} ); -} elsif ($op eq 'cud-toggle_in_demand') { +} elsif ( $op eq 'cud-toggle_in_demand' ) { # Toggle the item's in_demand - toggle_indemand($params{item_id}, $params{stage_id}); + toggle_indemand( $params{item_id}, $params{stage_id} ); # Return to the items list - print $input->redirect("?op=manage_items&rota_id=".$params{rota_id}); + print $input->redirect( "?op=manage_items&rota_id=" . $params{rota_id} ); -} elsif ($op eq 'cud-remove_item_from_stage') { +} elsif ( $op eq 'cud-remove_item_from_stage' ) { # Remove the item from the stage - remove_from_stage($params{item_id}, $params{stage_id}); + remove_from_stage( $params{item_id}, $params{stage_id} ); # Return to the items list - print $input->redirect("?op=manage_items&rota_id=".$params{rota_id}); + print $input->redirect( "?op=manage_items&rota_id=" . $params{rota_id} ); -} elsif ($op eq 'cud-add_items_to_rota') { +} elsif ( $op eq 'cud-add_items_to_rota' ) { # The item's barcode, # which we may or may not have been passed @@ -364,12 +347,13 @@ if (!defined $op) { # Call binmode on the filehandle as we want to set a # UTF-8 layer on it - binmode($barcode_file, ":encoding(UTF-8)"); + binmode( $barcode_file, ":encoding(UTF-8)" ); + # Parse the file into an array of barcodes - while (my $barcode = <$barcode_file>) { + while ( my $barcode = <$barcode_file> ) { $barcode =~ s/\r/\n/g; $barcode =~ s/\n+/\n/g; - my @data = split(/\n/, $barcode); + my @data = split( /\n/, $barcode ); push @barcodes, @data; } @@ -384,22 +368,22 @@ if (!defined $op) { }; # If we have something to work with, do it - get_barcodes_status($rota_id, \@barcodes, $barcode_status) if (@barcodes); + get_barcodes_status( $rota_id, \@barcodes, $barcode_status ) if (@barcodes); # Now we know the status of each barcode, add those that # need it - if (scalar @{$barcode_status->{ok}} > 0) { + if ( scalar @{ $barcode_status->{ok} } > 0 ) { - add_items_to_rota($rota_id, $barcode_status->{ok}); + add_items_to_rota( $rota_id, $barcode_status->{ok} ); } + # If we were only passed one barcode and it was successfully # added, redirect back to ourselves, we don't want to display # a report, redirect also if we were passed no barcodes - if ( - scalar @barcodes == 0 || - (scalar @barcodes == 1 && scalar @{$barcode_status->{ok}} == 1) - ) { + if ( scalar @barcodes == 0 + || ( scalar @barcodes == 1 && scalar @{ $barcode_status->{ok} } == 1 ) ) + { print $input->redirect("?op=manage_items&rota_id=$rota_id"); @@ -415,23 +399,23 @@ if (!defined $op) { } -} elsif ($op eq 'cud-move_items_to_rota') { +} elsif ( $op eq 'cud-move_items_to_rota' ) { # The barcodes of the items we're moving my @move = $input->multi_param('move_item'); - foreach my $item(@move) { + foreach my $item (@move) { # The item we're moving my $item = Koha::Items->find($item); # Move it to the new rota - $item->add_to_rota($params{rota_id}); + $item->add_to_rota( $params{rota_id} ); } # Return to the items list - print $input->redirect("?op=manage_items&rota_id=".$params{rota_id}); + print $input->redirect( "?op=manage_items&rota_id=" . $params{rota_id} ); } @@ -450,9 +434,9 @@ sub get_rota_from_form { sub get_stage_from_form { return { - stage_id => $params{stage_id}, - branchcode => $params{branchcode}, - duration => $params{duration} + stage_id => $params{stage_id}, + branchcode => $params{branchcode}, + duration => $params{duration} }; } @@ -461,18 +445,18 @@ sub process_rota { my $sub_rota = shift; # Fields we require - my @required = ('title','cyclical'); + my @required = ( 'title', 'cyclical' ); # Count of the number of required fields we have my $valid = 0; # Ensure we have everything we require - foreach my $req(@required) { + foreach my $req (@required) { - if (exists $sub_rota->{$req}) { + if ( exists $sub_rota->{$req} ) { - chomp(my $value = $sub_rota->{$req}); - if (length $value > 0) { + chomp( my $value = $sub_rota->{$req} ); + if ( length $value > 0 ) { $valid++; } @@ -485,26 +469,23 @@ sub process_rota { # Passed validation # Find the rota we're updating - my $rota = Koha::StockRotationRotas->find($sub_rota->{id}); + my $rota = Koha::StockRotationRotas->find( $sub_rota->{id} ); if ($rota) { - $rota->title( - $sub_rota->{title} - )->cyclical( - $sub_rota->{cyclical} - )->description( - $sub_rota->{description} - )->store; + $rota->title( $sub_rota->{title} )->cyclical( $sub_rota->{cyclical} )->description( $sub_rota->{description} ) + ->store; } else { - $rota = Koha::StockRotationRota->new({ - title => $sub_rota->{title}, - cyclical => $sub_rota->{cyclical}, - active => 0, - description => $sub_rota->{description} - })->store; + $rota = Koha::StockRotationRota->new( + { + title => $sub_rota->{title}, + cyclical => $sub_rota->{cyclical}, + active => 0, + description => $sub_rota->{description} + } + )->store; } @@ -513,21 +494,21 @@ sub process_rota { sub process_stage { - my ($sub_stage, $rota_id) = @_; + my ( $sub_stage, $rota_id ) = @_; # Fields we require - my @required = ('branchcode','duration'); + my @required = ( 'branchcode', 'duration' ); # Count of the number of required fields we have my $valid = 0; # Ensure we have everything we require - foreach my $req(@required) { + foreach my $req (@required) { - if (exists $sub_stage->{$req}) { + if ( exists $sub_stage->{$req} ) { - chomp(my $value = $sub_stage->{$req}); - if (length $value > 0) { + chomp( my $value = $sub_stage->{$req} ); + if ( length $value > 0 ) { $valid++; } @@ -540,25 +521,23 @@ sub process_stage { # Passed validation # Find the stage we're updating - my $stage = Koha::StockRotationStages->find($sub_stage->{stage_id}); + my $stage = Koha::StockRotationStages->find( $sub_stage->{stage_id} ); if ($stage) { # Updating an existing stage - $stage->branchcode_id( - $sub_stage->{branchcode} - )->duration( - $sub_stage->{duration} - )->store; + $stage->branchcode_id( $sub_stage->{branchcode} )->duration( $sub_stage->{duration} )->store; } else { # Creating a new stage - $stage = Koha::StockRotationStage->new({ - branchcode_id => $sub_stage->{branchcode}, - rota_id => $rota_id, - duration => $sub_stage->{duration} - })->store; + $stage = Koha::StockRotationStage->new( + { + branchcode_id => $sub_stage->{branchcode}, + rota_id => $rota_id, + duration => $sub_stage->{duration} + } + )->store; } diff --git a/tools/tools-home.pl b/tools/tools-home.pl index ed7f823485..5ea390c53f 100755 --- a/tools/tools-home.pl +++ b/tools/tools-home.pl @@ -17,24 +17,24 @@ use Modern::Perl; -use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); +use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); -use C4::Tags qw( get_count_by_tag_status ); +use C4::Tags qw( get_count_by_tag_status ); use Koha::Reviews; my $query = CGI->new; my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "tools/tools-home.tt", - query => $query, - type => "intranet", - flagsrequired => [ { tools => '*' }, { clubs => '*' } ], + template_name => "tools/tools-home.tt", + query => $query, + type => "intranet", + flagsrequired => [ { tools => '*' }, { clubs => '*' } ], } ); -my $pendingcomments = Koha::Reviews->search_limited({ approved => 0 })->count; -my $pendingtags = get_count_by_tag_status(0); +my $pendingcomments = Koha::Reviews->search_limited( { approved => 0 } )->count; +my $pendingtags = get_count_by_tag_status(0); $template->param( pendingcomments => $pendingcomments, @@ -42,9 +42,11 @@ $template->param( ); if ( C4::Context->config('enable_plugins') ) { - my @tool_plugins = Koha::Plugins->new()->GetPlugins({ - method => 'tool', - }); + my @tool_plugins = Koha::Plugins->new()->GetPlugins( + { + method => 'tool', + } + ); $template->param( tool_plugins => \@tool_plugins ); } diff --git a/tools/upload-cover-image.pl b/tools/upload-cover-image.pl index e78f360947..d7cff847dc 100755 --- a/tools/upload-cover-image.pl +++ b/tools/upload-cover-image.pl @@ -44,7 +44,7 @@ use File::Temp; use CGI qw ( -utf8 ); use GD; use C4::Context; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use Koha::Biblios; use Koha::CoverImages; @@ -57,17 +57,17 @@ my $input = CGI->new; my $fileID = $input->param('uploadedfileid'); my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "tools/upload-images.tt", - query => $input, - type => "intranet", - flagsrequired => { tools => 'upload_local_cover_images' }, + template_name => "tools/upload-images.tt", + query => $input, + type => "intranet", + flagsrequired => { tools => 'upload_local_cover_images' }, } ); -my $filetype = $input->param('filetype'); -my $biblionumber = $input->param('biblionumber'); -my $itemnumber = $input->param('itemnumber'); -my $replace = !C4::Context->preference("AllowMultipleCovers") +my $filetype = $input->param('filetype'); +my $biblionumber = $input->param('biblionumber'); +my $itemnumber = $input->param('itemnumber'); +my $replace = !C4::Context->preference("AllowMultipleCovers") || $input->param('replace'); my $op = $input->param('op') // q{}; @@ -77,13 +77,13 @@ my $biblio; my $cover_images; my $item; -if ( $itemnumber ) { - $item = Koha::Items->find($itemnumber); +if ($itemnumber) { + $item = Koha::Items->find($itemnumber); $biblionumber = $item->biblionumber; - $biblio = Koha::Biblios->find( $biblionumber ); + $biblio = Koha::Biblios->find($biblionumber); $cover_images = $item->cover_images->as_list; -} elsif ( $biblionumber ){ - $biblio = Koha::Biblios->find( $biblionumber ); +} elsif ($biblionumber) { + $biblio = Koha::Biblios->find($biblionumber); $cover_images = $biblio->cover_images->as_list; } @@ -99,18 +99,18 @@ my $total = 0; my @results; if ( $op eq 'cud-process' && $fileID ) { - my $upload = Koha::UploadedFiles->find( $fileID ); + my $upload = Koha::UploadedFiles->find($fileID); if ( $filetype eq 'image' ) { my $fh = $upload->file_handle; my $srcimage = GD::Image->new($fh); $fh->close if $fh; if ( defined $srcimage ) { eval { - if ( $replace ) { - if ( $itemnumber ) { + if ($replace) { + if ($itemnumber) { Koha::Items->find($itemnumber)->cover_images->delete; - } elsif ( $biblionumber ) { - Koha::Biblios->find($biblionumber)->cover_images->search({ itemnumber => undef })->delete; + } elsif ($biblionumber) { + Koha::Biblios->find($biblionumber)->cover_images->search( { itemnumber => undef } )->delete; } } @@ -126,25 +126,21 @@ if ( $op eq 'cud-process' && $fileID ) { if ($@) { warn $@; $error = 'DBERR'; - } - else { + } else { $total = 1; } - } - else { + } else { $error = 'OPNIMG'; } undef $srcimage; - } - else { + } else { my $filename = $upload->full_path; - my $dirname = File::Temp::tempdir( CLEANUP => 1 ); + my $dirname = File::Temp::tempdir( CLEANUP => 1 ); qx/unzip $filename -d $dirname/; my $exit_code = $?; unless ( $exit_code == 0 ) { $error = 'UZIPFAIL'; - } - else { + } else { my @directories; push @directories, "$dirname"; foreach my $recursive_dir (@directories) { @@ -152,7 +148,7 @@ if ( $op eq 'cud-process' && $fileID ) { opendir $dir, $recursive_dir; while ( my $entry = readdir $dir ) { push @directories, "$recursive_dir/$entry" - if ( -d "$recursive_dir/$entry" and $entry !~ /^[._]/ ); + if ( -d "$recursive_dir/$entry" and $entry !~ /^[._]/ ); } closedir $dir; } @@ -164,32 +160,31 @@ if ( $op eq 'cud-process' && $fileID ) { $file = $idlink; } elsif ( -e $datalink && !-l $datalink ) { $file = $datalink; - } - else { + } else { next; } if ( open( my $fh, '<', $file ) ) { while ( my $line = <$fh> ) { my $delim = - ( $line =~ /\t/ ) ? "\t" - : ( $line =~ /,/ ) ? "," - : ""; + ( $line =~ /\t/ ) ? "\t" + : ( $line =~ /,/ ) ? "," + : ""; unless ( $delim eq "," || $delim eq "\t" ) { - warn "Unrecognized or missing field delimeter. Please verify that you are using either a ',' or a 'tab'"; + warn + "Unrecognized or missing field delimeter. Please verify that you are using either a ',' or a 'tab'"; $error = 'DELERR'; next; - } - else { + } else { ( $biblionumber, $filename ) = split $delim, $line, 2; - $biblionumber =~ - s/[\"\r\n]//g; # remove offensive characters - $filename =~ s/[\"\r\n]//g; - $filename =~ s/^\s+//; - $filename =~ s/\s+$//; - my $full_filename = Cwd::abs_path("$dir/$filename"); #Resolve any relative filepath references + $biblionumber =~ s/[\"\r\n]//g; # remove offensive characters + $filename =~ s/[\"\r\n]//g; + $filename =~ s/^\s+//; + $filename =~ s/\s+$//; + my $full_filename = + Cwd::abs_path("$dir/$filename"); #Resolve any relative filepath references my $srcimage; - if ( $full_filename =~ /^\Q$dir\E/ ){ + if ( $full_filename =~ /^\Q$dir\E/ ) { $srcimage = GD::Image->new($full_filename); } my $biblio; @@ -197,20 +192,20 @@ if ( $op eq 'cud-process' && $fileID ) { if ( defined $srcimage ) { $total++; eval { - if ( $replace ) { - if ( $biblionumber ) { - $biblio = Koha::Biblios->find( $biblionumber ); + if ($replace) { + if ($biblionumber) { + $biblio = Koha::Biblios->find($biblionumber); $biblio->cover_images->delete; - } elsif ( $itemnumber ) { + } elsif ($itemnumber) { $item = Koha::Items->find($itemnumber); $item->cover_images->delete; $biblio = Koha::Biblios->find( $item->{biblionumber} ); } } else { - if( $biblionumber ){ - $biblio = Koha::Biblios->find( $biblionumber ); - } elsif ( $itemnumber ){ - $item = Koha::Items->find($itemnumber); + if ($biblionumber) { + $biblio = Koha::Biblios->find($biblionumber); + } elsif ($itemnumber) { + $item = Koha::Items->find($itemnumber); $biblio = Koha::Biblios->find( $item->{biblionumber} ); } else { warn "Problem."; @@ -219,8 +214,8 @@ if ( $op eq 'cud-process' && $fileID ) { push @results, { biblionumber => $biblionumber, - itemnumber => $itemnumber, - title => $biblio->title + itemnumber => $itemnumber, + title => $biblio->title }; Koha::CoverImage->new( @@ -235,8 +230,7 @@ if ( $op eq 'cud-process' && $fileID ) { if ($@) { $error = 'DBERR'; } - } - else { + } else { $error = 'OPNIMG'; } undef $srcimage; @@ -248,14 +242,13 @@ if ( $op eq 'cud-process' && $fileID ) { } } close($fh); - } - else { + } else { $error = 'OPNLINK'; } } } } - if( $error ){ + if ($error) { $template->param( total => $total, uploadimage => 1, @@ -263,14 +256,15 @@ if ( $op eq 'cud-process' && $fileID ) { biblionumber => $biblionumber || Koha::Items->find($itemnumber)->biblionumber, itemnumber => $itemnumber, ); - } elsif ( @results ){ + } elsif (@results) { $template->param( - total => $total, - uploadimage => 1, - results => \@results + total => $total, + uploadimage => 1, + results => \@results ); } else { - print $input->redirect("/cgi-bin/koha/tools/upload-cover-image.pl?biblionumber=$biblionumber&itemnumber=$itemnumber"); + print $input->redirect( + "/cgi-bin/koha/tools/upload-cover-image.pl?biblionumber=$biblionumber&itemnumber=$itemnumber"); } } diff --git a/tools/upload-file.pl b/tools/upload-file.pl index 125e7cb611..cc22e721fb 100755 --- a/tools/upload-file.pl +++ b/tools/upload-file.pl @@ -37,22 +37,24 @@ use Koha::Uploader; # requires that the session cookie already # has been created. -my %cookies = CGI::Cookie->fetch; -my $sid = $cookies{'CGISESSID'}->value; -my ( $auth_status ) = check_cookie_auth( $sid ); -my $uid = C4::Auth::get_session($sid)->param('id'); -my $allowed = Koha::Uploader->allows_add_by( $uid ); +my %cookies = CGI::Cookie->fetch; +my $sid = $cookies{'CGISESSID'}->value; +my ($auth_status) = check_cookie_auth($sid); +my $uid = C4::Auth::get_session($sid)->param('id'); +my $allowed = Koha::Uploader->allows_add_by($uid); -if( $auth_status ne 'ok' || !$allowed ) { - send_reply( 'denied' ); +if ( $auth_status ne 'ok' || !$allowed ) { + send_reply('denied'); exit 0; } -my $upload = Koha::Uploader->new( upload_pars($ENV{QUERY_STRING}) ); -if( !$upload || !$upload->cgi || !$upload->count ) { +my $upload = Koha::Uploader->new( upload_pars( $ENV{QUERY_STRING} ) ); +if ( !$upload || !$upload->cgi || !$upload->count ) { + # not one upload succeeded - send_reply( 'failed', undef, $upload? $upload->err: undef ); + send_reply( 'failed', undef, $upload ? $upload->err : undef ); } else { + # in case of multiple uploads, at least one got through send_reply( 'done', $upload->result, $upload->err ); } @@ -62,21 +64,24 @@ sub send_reply { # response will be sent back as JSON my ( $upload_status, $data, $error ) = @_; my $reply = CGI->new(""); print $reply->header( -type => 'text/html', -charset => 'UTF-8' ); - print JSON::encode_json({ - status => $upload_status, - fileid => $data, - errors => $error, - }); + print JSON::encode_json( + { + status => $upload_status, + fileid => $data, + errors => $error, + } + ); } -sub upload_pars { # this sub parses QUERY_STRING in order to build the - # parameter hash for Koha::Uploader - my ( $qstr ) = @_; - $qstr = Encode::decode_utf8( uri_unescape( $qstr ) ); +sub upload_pars { # this sub parses QUERY_STRING in order to build the + # parameter hash for Koha::Uploader + my ($qstr) = @_; + $qstr = Encode::decode_utf8( uri_unescape($qstr) ); + # category could include a utf8 character my $rv = {}; - foreach my $p ( qw[public category temp] ) { - if( $qstr =~ /(^|&)$p=(\w+)(&|$)/ ) { + foreach my $p (qw[public category temp]) { + if ( $qstr =~ /(^|&)$p=(\w+)(&|$)/ ) { $rv->{$p} = $2; } } diff --git a/tools/upload.pl b/tools/upload.pl index 214f7776a4..a8c1c8f2a1 100755 --- a/tools/upload.pl +++ b/tools/upload.pl @@ -21,35 +21,36 @@ use Modern::Perl; use CGI qw/-utf8/; use JSON; -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use Koha::UploadedFiles; use constant ERR_READING => 'UPLERR_FILE_NOT_READ'; -use constant ALERT_DELETED => 'UPL_FILE_DELETED'; # alert, no error +use constant ALERT_DELETED => 'UPL_FILE_DELETED'; # alert, no error use constant ERR_NOT_DELETED => 'UPLERR_FILE_NOT_DELETED'; -my $input = CGI::->new; -my $op = $input->param('op') // 'new'; -my $plugin = $input->param('plugin'); -my $index = $input->param('index'); # MARC editor input field id -my $term = $input->param('term'); -my $id = $input->param('id'); -my $msg = $input->param('msg'); +my $input = CGI::->new; +my $op = $input->param('op') // 'new'; +my $plugin = $input->param('plugin'); +my $index = $input->param('index'); # MARC editor input field id +my $term = $input->param('term'); +my $id = $input->param('id'); +my $msg = $input->param('msg'); my $browsecategory = $input->param('browsecategory'); my ( $template, $loggedinuser, $cookie ) = get_template_and_user( - { template_name => "tools/upload.tt", - query => $input, - type => "intranet", - flagsrequired => { tools => 'upload_general_files' }, + { + template_name => "tools/upload.tt", + query => $input, + type => "intranet", + flagsrequired => { tools => 'upload_general_files' }, } ); $template->param( - index => $index, - owner => $loggedinuser, - plugin => $plugin, + index => $index, + owner => $loggedinuser, + plugin => $plugin, uploadcategories => Koha::UploadedFiles->getCategories, ); @@ -61,11 +62,13 @@ if ( $op eq 'new' ) { } elsif ( $op eq 'browse' ) { my $uploads; - if ($browsecategory){ - $uploads = Koha::UploadedFiles->search({ - uploadcategorycode => $browsecategory, - $plugin? ( public => 1 ): (), - })->unblessed; + if ($browsecategory) { + $uploads = Koha::UploadedFiles->search( + { + uploadcategorycode => $browsecategory, + $plugin ? ( public => 1 ) : (), + } + )->unblessed; } $template->param( @@ -78,19 +81,22 @@ if ( $op eq 'new' ) { } elsif ( $op eq 'search' ) { my $uploads; - if( $id ) { # might be a comma separated list + if ($id) { # might be a comma separated list my @id = split /,/, $id; foreach my $recid (@id) { - my $rec = Koha::UploadedFiles->find( $recid ); + my $rec = Koha::UploadedFiles->find($recid); push @$uploads, $rec->unblessed if $rec && ( $rec->public || !$plugin ); - # Do not show private uploads in the plugin mode (:editor) + + # Do not show private uploads in the plugin mode (:editor) } } else { - $uploads = Koha::UploadedFiles->search_term({ - term => $term, - $plugin? (): ( include_private => 1 ), - })->unblessed; + $uploads = Koha::UploadedFiles->search_term( + { + term => $term, + $plugin ? () : ( include_private => 1 ), + } + )->unblessed; } $template->param( @@ -101,31 +107,32 @@ if ( $op eq 'new' ) { output_html_with_http_headers $input, $cookie, $template->output; } elsif ( $op eq 'cud-delete' ) { + # delete only takes the id parameter my $rec = Koha::UploadedFiles->find($id); undef $rec if $rec && $plugin && !$rec->public; - my $fn = $rec ? $rec->filename : ''; - my $delete = $rec ? $rec->delete : undef; + my $fn = $rec ? $rec->filename : ''; + my $delete = $rec ? $rec->delete : undef; + #TODO Improve error handling - my $msg = $delete - ? JSON::to_json({ $fn => { code => ALERT_DELETED }}) - : $id - ? JSON::to_json({ $fn || $id, { code => ERR_NOT_DELETED }}) - : ''; + my $msg = + $delete ? JSON::to_json( { $fn => { code => ALERT_DELETED } } ) + : $id ? JSON::to_json( { $fn || $id, { code => ERR_NOT_DELETED } } ) + : ''; $template->param( - op => 'new', - msg => $msg, + op => 'new', + msg => $msg, ); output_html_with_http_headers $input, $cookie, $template->output; } elsif ( $op eq 'download' ) { - my $rec = Koha::UploadedFiles->find( $id ); + my $rec = Koha::UploadedFiles->find($id); undef $rec if $rec && $plugin && !$rec->public; - my $fh = $rec? $rec->file_handle: undef; + my $fh = $rec ? $rec->file_handle : undef; if ( !$rec || !$fh ) { $template->param( - op => 'new', - msg => JSON::to_json({ $id => { code => ERR_READING }}), + op => 'new', + msg => JSON::to_json( { $id => { code => ERR_READING } } ), ); output_html_with_http_headers $input, $cookie, $template->output; } else { diff --git a/tools/viewlog.pl b/tools/viewlog.pl index b1c27b0c52..21157e94f3 100755 --- a/tools/viewlog.pl +++ b/tools/viewlog.pl @@ -21,12 +21,12 @@ use Modern::Perl; use C4::Auth qw( get_template_and_user ); -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use Text::CSV::Encoded; use C4::Context; -use C4::Output qw( output_html_with_http_headers ); +use C4::Output qw( output_html_with_http_headers ); use C4::Serials qw( CountSubscriptionFromBiblionumber ); -use C4::Search qw( enabled_staff_search_views ); +use C4::Search qw( enabled_staff_search_views ); use Koha::ActionLogs; use Koha::Database; @@ -35,7 +35,6 @@ use Koha::Items; use Koha::Patrons; use Koha::Recalls; - =head1 viewlog.pl plugin that shows stats @@ -44,36 +43,36 @@ plugin that shows stats my $input = CGI->new; -my $do_it = $input->param('do_it'); # no op: just viewing, downloading etc -my @modules = $input->multi_param("modules"); -my $user = $input->param("user") // ''; -my @actions = $input->multi_param("actions"); +my $do_it = $input->param('do_it'); # no op: just viewing, downloading etc +my @modules = $input->multi_param("modules"); +my $user = $input->param("user") // ''; +my @actions = $input->multi_param("actions"); my @interfaces = $input->multi_param("interfaces"); -my $object = $input->param("object"); +my $object = $input->param("object"); my $object_type = $input->param("object_type") // ''; -my $info = $input->param("info"); -my $datefrom = $input->param("from"); -my $dateto = $input->param("to"); -my $basename = $input->param("basename"); -my $output = $input->param("output") || "screen"; -my $src = $input->param("src") || ""; # this param allows us to be told where we were called from -fbcit +my $info = $input->param("info"); +my $datefrom = $input->param("from"); +my $dateto = $input->param("to"); +my $basename = $input->param("basename"); +my $output = $input->param("output") || "screen"; +my $src = $input->param("src") || ""; # this param allows us to be told where we were called from -fbcit my ( $template, $borrowernumber, $cookie ) = get_template_and_user( { - template_name => "tools/viewlog.tt", - query => $input, - type => "intranet", - flagsrequired => { tools => 'view_system_logs' }, + template_name => "tools/viewlog.tt", + query => $input, + type => "intranet", + flagsrequired => { tools => 'view_system_logs' }, } ); if ( $src eq 'circ' ) { my $borrowernumber = $object; - my $patron = Koha::Patrons->find( $borrowernumber ); - my $circ_info = 1; - unless ( $patron ) { - $circ_info = 0; + my $patron = Koha::Patrons->find($borrowernumber); + my $circ_info = 1; + unless ($patron) { + $circ_info = 0; } $template->param( @@ -85,72 +84,73 @@ if ( $src eq 'circ' ) { $template->param( C4::Search::enabled_staff_search_views, subscriptionsnumber => ( $object ? CountSubscriptionFromBiblionumber($object) : 0 ), - object => $object, + object => $object, ); if ($do_it) { my $dtf = Koha::Database->new->schema->storage->datetime_parser; my %search_params; - if ($datefrom and $dateto ) { + if ( $datefrom and $dateto ) { my $dateto_endday = dt_from_string($dateto); - $dateto_endday->set( # We set last second of day to see all log from that day - hour => 23, + $dateto_endday->set( # We set last second of day to see all log from that day + hour => 23, minute => 59, second => 59 ); $search_params{'timestamp'} = { -between => [ $dtf->format_datetime( dt_from_string($datefrom) ), - $dtf->format_datetime( $dateto_endday ), + $dtf->format_datetime($dateto_endday), ] }; } elsif ($datefrom) { - $search_params{'timestamp'} = { - '>=' => $dtf->format_datetime( dt_from_string($datefrom) ) - }; + $search_params{'timestamp'} = { '>=' => $dtf->format_datetime( dt_from_string($datefrom) ) }; } elsif ($dateto) { my $dateto_endday = dt_from_string($dateto); - $dateto_endday->set( # We set last second of day to see all log from that day - hour => 23, + $dateto_endday->set( # We set last second of day to see all log from that day + hour => 23, minute => 59, second => 59 ); - $search_params{'timestamp'} = { - '<=' => $dtf->format_datetime( $dateto_endday ) - }; + $search_params{'timestamp'} = { '<=' => $dtf->format_datetime($dateto_endday) }; } - # Circulation uses RENEWAL, but Patrons uses RENEW, this helps to find both - if ( grep { $_ eq 'RENEW'} @actions ) { push @actions, 'RENEWAL' }; - $search_params{user} = $user if $user; - $search_params{module} = { -in => [ @modules ] } if ( defined $modules[0] and $modules[0] ne '' ) ; - $search_params{action} = { -in => [ @actions ] } if ( defined $actions[0] && $actions[0] ne '' ); - $search_params{interface} = { -in => [ @interfaces ] } if ( defined $interfaces[0] && $interfaces[0] ne '' ); + # Circulation uses RENEWAL, but Patrons uses RENEW, this helps to find both + if ( grep { $_ eq 'RENEW' } @actions ) { + push @actions, 'RENEWAL'; + } + + $search_params{user} = $user if $user; + $search_params{module} = { -in => [@modules] } if ( defined $modules[0] and $modules[0] ne '' ); + $search_params{action} = { -in => [@actions] } if ( defined $actions[0] && $actions[0] ne '' ); + $search_params{interface} = { -in => [@interfaces] } if ( defined $interfaces[0] && $interfaces[0] ne '' ); if ( @modules == 1 && $object_type eq 'biblio' ) { + # Handle 'Modification log' from cataloguing - my $biblio = Koha::Biblios->find( $object ); + my $biblio = Koha::Biblios->find($object); my @itemnumbers = $biblio->items->get_column('itemnumber'); $search_params{'-or'} = [ - { -and => { object => $object, info => { -like => 'biblio%' }}}, - { -and => { object => \@itemnumbers, info => { -like => 'item%' }}}, + { -and => { object => $object, info => { -like => 'biblio%' } } }, + { -and => { object => \@itemnumbers, info => { -like => 'item%' } } }, ]; $template->param( biblio => $biblio ); } else { - $search_params{info} = { -like => '%' . $info . '%' } if $info; - $search_params{object} = $object if $object; + $search_params{info} = { -like => '%' . $info . '%' } if $info; + $search_params{object} = $object if $object; } - my @logs = Koha::ActionLogs->search(\%search_params)->as_list; + my @logs = Koha::ActionLogs->search( \%search_params )->as_list; my @data; foreach my $log (@logs) { my $result = $log->unblessed; + # Init additional columns for CSV export - $result->{'biblionumber'} = q{}; - $result->{'biblioitemnumber'} = q{}; - $result->{'barcode'} = q{}; + $result->{'biblionumber'} = q{}; + $result->{'biblioitemnumber'} = q{}; + $result->{'barcode'} = q{}; if ( substr( $log->info, 0, 4 ) eq 'item' || $log->module eq "CIRCULATION" ) { @@ -169,7 +169,7 @@ if ($do_it) { #always add firstname and surname for librarian/user if ( $log->user ) { my $patron = Koha::Patrons->find( $log->user ); - if ($patron && $output eq 'screen') { + if ( $patron && $output eq 'screen' ) { $result->{librarian} = $patron; } } @@ -178,7 +178,7 @@ if ($do_it) { if ( $log->module eq "CIRCULATION" || $log->module eq "MEMBERS" || $log->module eq "FINES" ) { if ( $log->object ) { my $patron = Koha::Patrons->find( $log->object ); - if ($patron && $output eq 'screen') { + if ( $patron && $output eq 'screen' ) { $result->{patron} = $patron; } } @@ -187,7 +187,7 @@ if ($do_it) { if ( $log->module eq 'NOTICES' ) { if ( $log->object ) { my $notice = Koha::Notice::Templates->find( { id => $log->object } ); - if ($notice && $output eq 'screen') { + if ( $notice && $output eq 'screen' ) { $result->{notice} = $notice->unblessed; } } @@ -208,17 +208,17 @@ if ($do_it) { # Printing results to screen $template->param( - logview => 1, - total => scalar @data, - looprow => \@data, - do_it => 1, - datefrom => $datefrom, - dateto => $dateto, - user => $user, - info => $info, - src => $src, - modules => \@modules, - actions => \@actions, + logview => 1, + total => scalar @data, + looprow => \@data, + do_it => 1, + datefrom => $datefrom, + dateto => $dateto, + user => $user, + info => $info, + src => $src, + modules => \@modules, + actions => \@actions, interfaces => \@interfaces ); @@ -227,8 +227,7 @@ if ($do_it) { $template->param( $module => 1 ); } output_html_with_http_headers $input, $cookie, $template->output; - } - else { + } else { # Printing to a csv file my $content = q{}; @@ -239,7 +238,7 @@ if ($do_it) { # First line with heading # Exporting bd id seems useless - my @headings = grep { $_ ne 'action_id' } sort keys %{$data[0]}; + my @headings = grep { $_ ne 'action_id' } sort keys %{ $data[0] }; if ( $csv->combine(@headings) ) { $content .= $csv->string() . "\n"; } @@ -261,7 +260,6 @@ if ($do_it) { print $content; } exit; -} -else { +} else { output_html_with_http_headers $input, $cookie, $template->output; } diff --git a/virtualshelves/addbybiblionumber.pl b/virtualshelves/addbybiblionumber.pl index 69483d5dc1..1d77b41187 100755 --- a/virtualshelves/addbybiblionumber.pl +++ b/virtualshelves/addbybiblionumber.pl @@ -18,7 +18,6 @@ # You should have received a copy of the GNU General Public License # along with Koha; if not, see . - =head1 NAME addbybiblionumber.pl @@ -58,9 +57,9 @@ addbybiblionumber.pl use Modern::Perl; -use CGI qw ( -utf8 ); +use CGI qw ( -utf8 ); use C4::Output qw( output_html_with_http_headers ); -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use Koha::Biblios; use Koha::Virtualshelves; @@ -84,10 +83,11 @@ if ( @biblionumbers == 0 && $query->param('biblionumbers') ) { } my ( $template, $loggedinuser, $cookie ) = get_template_and_user( - { template_name => "virtualshelves/addbybiblionumber.tt", - query => $query, - type => "intranet", - flagsrequired => { catalogue => 1 }, + { + template_name => "virtualshelves/addbybiblionumber.tt", + query => $query, + type => "intranet", + flagsrequired => { catalogue => 1 }, } ); @@ -115,7 +115,8 @@ if ( $op && $op !~ /^cud-/ ) { #Reload the page where you came from print $query->header; - print ""; + print + ""; exit; } @@ -152,25 +153,28 @@ if ( $op && $op !~ /^cud-/ ) { } else { my $private_shelves = Koha::Virtualshelves->search( - { public => 0, + { + public => 0, owner => $loggedinuser, allow_change_from_owner => 1, }, { order_by => 'shelfname' } ); my $shelves_shared_with_me = Koha::Virtualshelves->search( - { public => 0, + { + public => 0, 'virtualshelfshares.borrowernumber' => $loggedinuser, allow_change_from_others => 1, }, { join => 'virtualshelfshares', } ); my $public_shelves = Koha::Virtualshelves->search( - { public => 1, - -or => [ + { + public => 1, + -or => [ -and => { allow_change_from_owner => 1, - owner => $loggedinuser, + owner => $loggedinuser, }, allow_change_from_others => 1, allow_change_from_staff => 1, @@ -188,10 +192,11 @@ if ( $op && $op !~ /^cud-/ ) { my @biblios; for my $biblionumber (@biblionumbers) { - my $biblio = Koha::Biblios->find( $biblionumber ); + my $biblio = Koha::Biblios->find($biblionumber); push( @biblios, - { biblionumber => $biblionumber, + { + biblionumber => $biblionumber, title => $biblio->title, author => $biblio->author, } @@ -204,7 +209,7 @@ $template->param( ); $template->param( - newshelf => $newshelf || 0, + newshelf => $newshelf || 0, authorized => $authorized, errcode => $errcode, ); diff --git a/virtualshelves/downloadshelf.pl b/virtualshelves/downloadshelf.pl index a81338ac66..9e03782b19 100755 --- a/virtualshelves/downloadshelf.pl +++ b/virtualshelves/downloadshelf.pl @@ -21,7 +21,7 @@ use Modern::Perl; use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Output qw( output_html_with_http_headers ); use C4::Record; use C4::Ris qw( marc2ris ); @@ -33,12 +33,12 @@ use Koha::Virtualshelves; use utf8; my $query = CGI->new; -my ( $template, $loggedinuser, $cookie ) = get_template_and_user ( +my ( $template, $loggedinuser, $cookie ) = get_template_and_user( { - template_name => "virtualshelves/downloadshelf.tt", - query => $query, - type => "intranet", - flagsrequired => { catalogue => 1 }, + template_name => "virtualshelves/downloadshelf.tt", + query => $query, + type => "intranet", + flagsrequired => { catalogue => 1 }, } ); @@ -47,48 +47,47 @@ my $format = $query->param('format'); my $dbh = C4::Context->dbh; my @messages; -if ($shelfid && $format) { +if ( $shelfid && $format ) { - my $marcflavour = C4::Context->preference('marcflavour'); - my $output=''; + my $marcflavour = C4::Context->preference('marcflavour'); + my $output = ''; my $shelf = Koha::Virtualshelves->find($shelfid); - if ( $shelf ) { - if ( $shelf->can_be_viewed( $loggedinuser ) ) { + if ($shelf) { + if ( $shelf->can_be_viewed($loggedinuser) ) { my $contents = $shelf->get_contents; + # CSV - if ($format =~ /^\d+$/) { + if ( $format =~ /^\d+$/ ) { my @biblios; while ( my $content = $contents->next ) { push @biblios, $content->biblionumber; } - $output = marc2csv(\@biblios, $format); - } - else { #Other formats + $output = marc2csv( \@biblios, $format ); + } else { #Other formats while ( my $content = $contents->next ) { my $biblionumber = $content->biblionumber; - my $biblio = Koha::Biblios->find($biblionumber); - my $record = $biblio->metadata_record( { embed_items => 1 } ); - if ($format eq 'iso2709') { + my $biblio = Koha::Biblios->find($biblionumber); + my $record = $biblio->metadata_record( { embed_items => 1 } ); + if ( $format eq 'iso2709' ) { $output .= $record->as_usmarc(); - } - elsif ($format eq 'ris') { + } elsif ( $format eq 'ris' ) { $output .= marc2ris($record); - } - elsif ($format eq 'bibtex') { - $output .= marc2bibtex($record, $biblionumber); + } elsif ( $format eq 'bibtex' ) { + $output .= marc2bibtex( $record, $biblionumber ); } } } # If it was a CSV export we change the format after the export so the file extension is fine - $format = "csv" if ($format =~ m/^\d+$/); + $format = "csv" if ( $format =~ m/^\d+$/ ); print $query->header( - -type => 'application/octet-stream', - -'Content-Transfer-Encoding' => 'binary', - -attachment=>"shelf.$format"); + -type => 'application/octet-stream', + -'Content-Transfer-Encoding' => 'binary', + -attachment => "shelf.$format" + ); print $output; exit; } else { @@ -97,10 +96,10 @@ if ($shelfid && $format) { } else { push @messages, { type => 'error', code => 'does_not_exist' }; } -} -else { - $template->param(csv_profiles => [ Koha::CsvProfiles->search({ type => 'marc', used_for => 'export_records' })->as_list ]); - $template->param(shelfid => $shelfid); +} else { + $template->param( + csv_profiles => [ Koha::CsvProfiles->search( { type => 'marc', used_for => 'export_records' } )->as_list ] ); + $template->param( shelfid => $shelfid ); } $template->param( messages => \@messages ); output_html_with_http_headers $query, $cookie, $template->output; diff --git a/virtualshelves/sendshelf.pl b/virtualshelves/sendshelf.pl index 84e7ca401e..20a7789652 100755 --- a/virtualshelves/sendshelf.pl +++ b/virtualshelves/sendshelf.pl @@ -21,17 +21,17 @@ use Modern::Perl; use CGI qw ( -utf8 ); use Encode; -use Carp qw( carp ); +use Carp qw( carp ); use Try::Tiny qw( catch try ); -use C4::Auth qw( get_template_and_user ); +use C4::Auth qw( get_template_and_user ); use C4::Biblio qw( - GetMarcISBN - GetMarcSubjects + GetMarcISBN + GetMarcSubjects ); use C4::Output qw( - output_html_with_http_headers - output_and_exit + output_html_with_http_headers + output_and_exit ); use Koha::Biblios; @@ -56,7 +56,7 @@ my $to_address = $query->param('email'); my $shelf = Koha::Virtualshelves->find($shelfid); output_and_exit( $query, $cookie, $template, 'insufficient_permission' ) - if $shelf && !$shelf->can_be_viewed($borrowernumber); + if $shelf && !$shelf->can_be_viewed($borrowernumber); if ( $to_address && $op eq 'cud-send' ) { my $comment = $query->param('comment'); @@ -76,12 +76,10 @@ if ( $to_address && $op eq 'cud-send' ) { if ( !defined $iso2709 ) { carp "Error sending mail: empty basket"; $template->param( error => 1 ); - } - elsif ( !defined $user_email or $user_email eq '' ) { + } elsif ( !defined $user_email or $user_email eq '' ) { carp "Error sending mail: sender's email address is invalid"; $template->param( error => 1 ); - } - else { + } else { my %loops = ( biblio => \@biblionumbers, ); my %substitute = ( @@ -126,8 +124,7 @@ if ( $to_address && $op eq 'cud-send' ) { $template->param( email => $to_address ); output_html_with_http_headers $query, $cookie, $template->output; -} -else { +} else { $template->param( shelfid => $shelfid, url => "/cgi-bin/koha/virtualshelves/sendshelf.pl", diff --git a/virtualshelves/shelves.pl b/virtualshelves/shelves.pl index c60038fddd..760e228dbd 100755 --- a/virtualshelves/shelves.pl +++ b/virtualshelves/shelves.pl @@ -18,8 +18,8 @@ # along with Koha; if not, see . use Modern::Perl; -use CGI qw ( -utf8 ); -use C4::Auth qw( get_template_and_user haspermission ); +use CGI qw ( -utf8 ); +use C4::Auth qw( get_template_and_user haspermission ); use C4::Circulation qw( barcodedecode ); use C4::Context; use C4::Koha qw( @@ -30,7 +30,7 @@ use C4::Koha qw( ); use C4::Members; use C4::Output qw( pagination_bar output_html_with_http_headers output_and_exit_if_error ); -use C4::XSLT qw( XSLTParse4Display ); +use C4::XSLT qw( XSLTParse4Display ); use Koha::Biblios; use Koha::Biblioitems; @@ -47,10 +47,11 @@ use constant PERMITTED => 4; my $query = CGI->new; my ( $template, $loggedinuser, $cookie ) = get_template_and_user( - { template_name => "virtualshelves/shelves.tt", - query => $query, - type => "intranet", - flagsrequired => { catalogue => 1 }, + { + template_name => "virtualshelves/shelves.tt", + query => $query, + type => "intranet", + flagsrequired => { catalogue => 1 }, } ); @@ -68,17 +69,18 @@ $public = ( $query->param('public') == 1 && $allow_create_public_lists == 1 ) ? # PART1: Perform a few actions if ( $op eq 'add_form' ) { + # Only pass default $shelf = { allow_change_from_owner => 1 }; } elsif ( $op eq 'edit_form' ) { $shelfnumber = $query->param('shelfnumber'); $shelf = Koha::Virtualshelves->find($shelfnumber); - if ( $shelf ) { + if ($shelf) { $public = $shelf->public; my $patron = Koha::Patrons->find( $shelf->owner )->unblessed; $template->param( owner => $patron, ); - unless ( $shelf->can_be_managed( $loggedinuser ) ) { + unless ( $shelf->can_be_managed($loggedinuser) ) { push @messages, { type => 'alert', code => 'unauthorized_on_update' }; $op = 'list'; } @@ -86,18 +88,19 @@ if ( $op eq 'add_form' ) { push @messages, { type => 'alert', code => 'does_not_exist' }; } } elsif ( $op eq 'cud-add' ) { - output_and_exit_if_error($query, $cookie, $template, { check => 'csrf_token' }); + output_and_exit_if_error( $query, $cookie, $template, { check => 'csrf_token' } ); my $allow_changes_from = $query->param('allow_changes_from'); eval { $shelf = Koha::Virtualshelf->new( - { shelfname => scalar $query->param('shelfname'), - sortfield => scalar $query->param('sortfield'), - public => $public, + { + shelfname => scalar $query->param('shelfname'), + sortfield => scalar $query->param('sortfield'), + public => $public, allow_change_from_owner => $allow_changes_from > 0, allow_change_from_others => $allow_changes_from == ANYONE, allow_change_from_staff => $allow_changes_from == STAFF, allow_change_from_permitted_staff => $allow_changes_from == PERMITTED, - owner => scalar $query->param('owner'), + owner => scalar $query->param('owner'), } ); $shelf->store; @@ -113,17 +116,17 @@ if ( $op eq 'add_form' ) { $op = 'view'; } } elsif ( $op eq 'cud-edit' ) { - output_and_exit_if_error($query, $cookie, $template, { check => 'csrf_token' }); + output_and_exit_if_error( $query, $cookie, $template, { check => 'csrf_token' } ); $shelfnumber = $query->param('shelfnumber'); $shelf = Koha::Virtualshelves->find($shelfnumber); - if ( $shelf ) { + if ($shelf) { $op = $referer; my $sortfield = $query->param('sortfield'); $sortfield = 'title' unless grep { $_ eq $sortfield } qw( title author copyrightdate itemcallnumber dateadded ); - if ( $shelf->can_be_managed( $loggedinuser ) ) { + if ( $shelf->can_be_managed($loggedinuser) ) { $shelf->shelfname( scalar $query->param('shelfname') ); - $shelf->sortfield( $sortfield ); + $shelf->sortfield($sortfield); my $allow_changes_from = $query->param('allow_changes_from'); $shelf->allow_change_from_owner( $allow_changes_from > 0 ); $shelf->allow_change_from_others( $allow_changes_from == ANYONE ); @@ -145,11 +148,11 @@ if ( $op eq 'add_form' ) { push @messages, { type => 'alert', code => 'does_not_exist' }; } } elsif ( $op eq 'cud-delete' ) { - output_and_exit_if_error($query, $cookie, $template, { check => 'csrf_token' }); + output_and_exit_if_error( $query, $cookie, $template, { check => 'csrf_token' } ); $shelfnumber = $query->param('shelfnumber'); $shelf = Koha::Virtualshelves->find($shelfnumber); if ($shelf) { - if ( $shelf->can_be_deleted( $loggedinuser ) ) { + if ( $shelf->can_be_deleted($loggedinuser) ) { eval { $shelf->delete; }; if ($@) { push @messages, { type => 'alert', code => ref($@), msg => $@ }; @@ -164,25 +167,27 @@ if ( $op eq 'add_form' ) { } $op = 'list'; } elsif ( $op eq 'cud-add_biblio' ) { - output_and_exit_if_error($query, $cookie, $template, { check => 'csrf_token' }); + output_and_exit_if_error( $query, $cookie, $template, { check => 'csrf_token' } ); $shelfnumber = $query->param('shelfnumber'); - $shelf = Koha::Virtualshelves->find($shelfnumber); + $shelf = Koha::Virtualshelves->find($shelfnumber); if ($shelf) { - if( my $barcodes = $query->param('barcodes') ) { - if ( $shelf->can_biblios_be_added( $loggedinuser ) ) { - my @barcodes = split /\n/, $barcodes; # Entries are effectively passed in as a separated list - foreach my $barcode (@barcodes){ - $barcode = barcodedecode( $barcode ) if $barcode; - next if $barcode eq ''; - my $item = Koha::Items->find({barcode => $barcode}); - if ( $item ) { + if ( my $barcodes = $query->param('barcodes') ) { + if ( $shelf->can_biblios_be_added($loggedinuser) ) { + my @barcodes = split /\n/, $barcodes; # Entries are effectively passed in as a separated list + foreach my $barcode (@barcodes) { + $barcode = barcodedecode($barcode) if $barcode; + next if $barcode eq ''; + my $item = Koha::Items->find( { barcode => $barcode } ); + if ($item) { my $added = eval { $shelf->add_biblio( $item->biblionumber, $loggedinuser ); }; if ($@) { push @messages, { item_barcode => $barcode, type => 'alert', code => ref($@), msg => $@ }; - } elsif ( $added ) { - push @messages, { item_barcode => $barcode, type => 'message', code => 'success_on_add_biblio' }; + } elsif ($added) { + push @messages, + { item_barcode => $barcode, type => 'message', code => 'success_on_add_biblio' }; } else { - push @messages, { item_barcode => $barcode, type => 'message', code => 'error_on_add_biblio' }; + push @messages, + { item_barcode => $barcode, type => 'message', code => 'error_on_add_biblio' }; } } else { push @messages, { item_barcode => $barcode, type => 'alert', code => 'item_does_not_exist' }; @@ -193,20 +198,22 @@ if ( $op eq 'add_form' ) { } } if ( my $biblionumbers = $query->param('biblionumbers') ) { - if ( $shelf->can_biblios_be_added( $loggedinuser ) ) { + if ( $shelf->can_biblios_be_added($loggedinuser) ) { my @biblionumbers = split /\n/, $biblionumbers; foreach my $biblionumber (@biblionumbers) { - $biblionumber =~ s/\r$//; # strip any naughty return chars + $biblionumber =~ s/\r$//; # strip any naughty return chars next if $biblionumber eq ''; my $biblio = Koha::Biblios->find($biblionumber); - if (defined $biblio) { + if ( defined $biblio ) { my $added = eval { $shelf->add_biblio( $biblionumber, $loggedinuser ); }; if ($@) { push @messages, { bibnum => $biblionumber, type => 'alert', code => ref($@), msg => $@ }; - } elsif ( $added ) { - push @messages, { bibnum => $biblionumber, type => 'message', code => 'success_on_add_biblio' }; + } elsif ($added) { + push @messages, + { bibnum => $biblionumber, type => 'message', code => 'success_on_add_biblio' }; } else { - push @messages, { bibnum => $biblionumber, type => 'message', code => 'error_on_add_biblio' }; + push @messages, + { bibnum => $biblionumber, type => 'message', code => 'error_on_add_biblio' }; } } else { push @messages, { bibnum => $biblionumber, type => 'alert', code => 'item_does_not_exist' }; @@ -221,23 +228,23 @@ if ( $op eq 'add_form' ) { } $op = $referer; } elsif ( $op eq 'cud-remove_biblios' ) { - output_and_exit_if_error($query, $cookie, $template, { check => 'csrf_token' }); + output_and_exit_if_error( $query, $cookie, $template, { check => 'csrf_token' } ); $shelfnumber = $query->param('shelfnumber'); - $shelf = Koha::Virtualshelves->find($shelfnumber); + $shelf = Koha::Virtualshelves->find($shelfnumber); my @biblionumbers = $query->multi_param('biblionumber'); if ($shelf) { - if ( $shelf->can_biblios_be_removed( $loggedinuser ) ) { + if ( $shelf->can_biblios_be_removed($loggedinuser) ) { my $number_of_biblios_removed = eval { $shelf->remove_biblios( { - biblionumbers => \@biblionumbers, + biblionumbers => \@biblionumbers, borrowernumber => $loggedinuser, } ); }; if ($@) { push @messages, { type => 'alert', code => ref($@), msg => $@ }; - } elsif ( $number_of_biblios_removed ) { + } elsif ($number_of_biblios_removed) { push @messages, { type => 'message', code => 'success_on_remove_biblios' }; } else { push @messages, { type => 'alert', code => 'no_biblio_removed' }; @@ -251,18 +258,20 @@ if ( $op eq 'add_form' ) { $op = $referer; } elsif ( $op eq 'transfer' ) { $shelfnumber = $query->param('shelfnumber'); - $shelf = Koha::Virtualshelves->find($shelfnumber) if $shelfnumber; + $shelf = Koha::Virtualshelves->find($shelfnumber) if $shelfnumber; } elsif ( $op eq 'cud-transfer' ) { $shelfnumber = $query->param('shelfnumber'); - $shelf = Koha::Virtualshelves->find($shelfnumber) if $shelfnumber; - my $new_owner = $query->param('new_owner'); # is a borrowernumber - my $error_code = $shelf - ? $shelf->cannot_be_transferred({ by => $loggedinuser, to => $new_owner, interface => 'intranet' }) + $shelf = Koha::Virtualshelves->find($shelfnumber) if $shelfnumber; + my $new_owner = $query->param('new_owner'); # is a borrowernumber + my $error_code = + $shelf + ? $shelf->cannot_be_transferred( { by => $loggedinuser, to => $new_owner, interface => 'intranet' } ) : 'does_not_exist'; - if( !$new_owner && $error_code eq 'missing_to_parameter' ) { + if ( !$new_owner && $error_code eq 'missing_to_parameter' ) { + # show form - } elsif( $error_code ) { + } elsif ($error_code) { push @messages, { type => 'error', code => $error_code }; $op = 'list'; } else { @@ -275,10 +284,14 @@ if ( $op eq 'add_form' ) { if ( $op eq 'view' ) { $shelfnumber ||= $query->param('shelfnumber'); $shelf = Koha::Virtualshelves->find($shelfnumber); - if ( $shelf ) { - if ( $shelf->can_be_viewed( $loggedinuser ) ) { - my $sortfield = $query->param('sortfield') || $shelf->sortfield || 'title'; # Passed in sorting overrides default sorting - $sortfield = 'title' unless grep { $_ eq $sortfield } qw( title author copyrightdate itemcallnumber dateadded ); + if ($shelf) { + if ( $shelf->can_be_viewed($loggedinuser) ) { + my $sortfield = + $query->param('sortfield') + || $shelf->sortfield + || 'title'; # Passed in sorting overrides default sorting + $sortfield = 'title' + unless grep { $_ eq $sortfield } qw( title author copyrightdate itemcallnumber dateadded ); my $direction = $query->param('direction') || 'asc'; $direction = 'asc' if $direction ne 'asc' and $direction ne 'desc'; my $rows; @@ -317,17 +330,19 @@ if ( $op eq 'view' ) { ); my $marcflavour = C4::Context->preference("marcflavour"); - my $itemtype = Koha::Biblioitems->search({ biblionumber => $content->biblionumber })->next->itemtype; - $itemtype = Koha::ItemTypes->find( $itemtype ); - $this_item->{title} = $biblio->title; - $this_item->{subtitle} = $biblio->subtitle; - $this_item->{medium} = $biblio->medium; - $this_item->{part_number} = $biblio->part_number; - $this_item->{part_name} = $biblio->part_name; - $this_item->{author} = $biblio->author; - $this_item->{dateadded} = $content->dateadded; - $this_item->{imageurl} = $itemtype ? C4::Koha::getitemtypeimagelocation( 'intranet', $itemtype->imageurl ) : q{}; - $this_item->{description} = $itemtype ? $itemtype->description : q{}; #FIXME Should this be translated_description ? + my $itemtype = Koha::Biblioitems->search( { biblionumber => $content->biblionumber } )->next->itemtype; + $itemtype = Koha::ItemTypes->find($itemtype); + $this_item->{title} = $biblio->title; + $this_item->{subtitle} = $biblio->subtitle; + $this_item->{medium} = $biblio->medium; + $this_item->{part_number} = $biblio->part_number; + $this_item->{part_name} = $biblio->part_name; + $this_item->{author} = $biblio->author; + $this_item->{dateadded} = $content->dateadded; + $this_item->{imageurl} = + $itemtype ? C4::Koha::getitemtypeimagelocation( 'intranet', $itemtype->imageurl ) : q{}; + $this_item->{description} = + $itemtype ? $itemtype->description : q{}; #FIXME Should this be translated_description ? $this_item->{notforloan} = $itemtype->notforloan if $itemtype; $this_item->{'coins'} = $biblio->get_coins; $this_item->{'normalized_upc'} = GetNormalizedUPC( $record, $marcflavour ); @@ -344,7 +359,7 @@ if ( $op eq 'view' ) { # Getting items infos for location display my $items = $biblio->items; $this_item->{'ITEM_RESULTS'} = $items; - $this_item->{biblionumber} = $biblionumber; + $this_item->{biblionumber} = $biblionumber; push @items, $this_item; } @@ -366,21 +381,25 @@ if ( $op eq 'view' ) { $template->param( add_to_some_private_shelves => $some_private_shelves, add_to_some_public_shelves => $some_public_shelves, - can_manage_shelf => $shelf->can_be_managed($loggedinuser), - can_remove_shelf => $shelf->can_be_deleted($loggedinuser), - can_remove_biblios => $shelf->can_biblios_be_removed($loggedinuser), - can_add_biblios => $shelf->can_biblios_be_added($loggedinuser), - sortfield => $sortfield, - itemsloop => \@items, - sortfield => $sortfield, - direction => $direction, + can_manage_shelf => $shelf->can_be_managed($loggedinuser), + can_remove_shelf => $shelf->can_be_deleted($loggedinuser), + can_remove_biblios => $shelf->can_biblios_be_removed($loggedinuser), + can_add_biblios => $shelf->can_biblios_be_added($loggedinuser), + sortfield => $sortfield, + itemsloop => \@items, + sortfield => $sortfield, + direction => $direction, ); - if ( $page ) { + if ($page) { my $pager = $contents->pager; $template->param( pagination_bar => pagination_bar( - q||, $pager->last_page - $pager->first_page + 1, - $page, "page", { op => 'view', shelfnumber => $shelf->shelfnumber, sortfield => $sortfield, direction => $direction, } + q||, $pager->last_page - $pager->first_page + 1, + $page, "page", + { + op => 'view', shelfnumber => $shelf->shelfnumber, sortfield => $sortfield, + direction => $direction, + } ), ); } @@ -391,19 +410,20 @@ if ( $op eq 'view' ) { } else { push @messages, { type => 'alert', code => 'does_not_exist' }; } -} elsif( $op eq 'list' ) { +} elsif ( $op eq 'list' ) { $allow_transfer = haspermission( C4::Context->userenv->{id}, { lists => 'edit_public_lists' } ) ? 1 : 0; - # this check only serves for button display + + # this check only serves for button display } $template->param( - op => $op, - referer => $referer, - shelf => $shelf, - messages => \@messages, - public => $public, - print => scalar $query->param('print') || 0, - csv_profiles => [ Koha::CsvProfiles->search({ type => 'marc', used_for => 'export_records' })->as_list ], + op => $op, + referer => $referer, + shelf => $shelf, + messages => \@messages, + public => $public, + print => scalar $query->param('print') || 0, + csv_profiles => [ Koha::CsvProfiles->search( { type => 'marc', used_for => 'export_records' } )->as_list ], allow_transfer => $allow_transfer, allow_create_public_lists => $allow_create_public_lists, ); diff --git a/webpack.config.js b/webpack.config.js index ae87653c24..09d210be79 100644 --- a/webpack.config.js +++ b/webpack.config.js @@ -1,45 +1,50 @@ const { VueLoaderPlugin } = require("vue-loader"); const autoprefixer = require("autoprefixer"); const path = require("path"); -const webpack = require('webpack'); +const webpack = require("webpack"); module.exports = { - entry: { - erm: "./koha-tmpl/intranet-tmpl/prog/js/vue/modules/erm.ts", - preservation: "./koha-tmpl/intranet-tmpl/prog/js/vue/modules/preservation.ts", - "admin/record_sources": "./koha-tmpl/intranet-tmpl/prog/js/vue/modules/admin/record_sources.ts", - }, - output: { - filename: "[name].js", - path: path.resolve(__dirname, "koha-tmpl/intranet-tmpl/prog/js/vue/dist/"), - chunkFilename: "[name].js", - }, - module: { - rules: [ - { - test: /\.vue$/, - loader: "vue-loader", - exclude: [path.resolve(__dirname, "t/cypress/")], - }, - { - test: /\.ts$/, - loader: 'ts-loader', - options: { - appendTsSuffixTo: [/\.vue$/] - }, - exclude: [path.resolve(__dirname, "t/cypress/")], - }, - { - test: /\.css$/, - use: ['style-loader', 'css-loader'], - } + entry: { + erm: "./koha-tmpl/intranet-tmpl/prog/js/vue/modules/erm.ts", + preservation: + "./koha-tmpl/intranet-tmpl/prog/js/vue/modules/preservation.ts", + "admin/record_sources": + "./koha-tmpl/intranet-tmpl/prog/js/vue/modules/admin/record_sources.ts", + }, + output: { + filename: "[name].js", + path: path.resolve( + __dirname, + "koha-tmpl/intranet-tmpl/prog/js/vue/dist/" + ), + chunkFilename: "[name].js", + }, + module: { + rules: [ + { + test: /\.vue$/, + loader: "vue-loader", + exclude: [path.resolve(__dirname, "t/cypress/")], + }, + { + test: /\.ts$/, + loader: "ts-loader", + options: { + appendTsSuffixTo: [/\.vue$/], + }, + exclude: [path.resolve(__dirname, "t/cypress/")], + }, + { + test: /\.css$/, + use: ["style-loader", "css-loader"], + }, + ], + }, + plugins: [ + new VueLoaderPlugin(), + new webpack.DefinePlugin({ + __VUE_OPTIONS_API__: true, + __VUE_PROD_DEVTOOLS__: false, + }), ], - }, - plugins: [ - new VueLoaderPlugin(), - new webpack.DefinePlugin({ - __VUE_OPTIONS_API__: true, - __VUE_PROD_DEVTOOLS__: false, - }), - ], }; diff --git a/xt/api.t b/xt/api.t index 6faebdca9e..78cf588c24 100755 --- a/xt/api.t +++ b/xt/api.t @@ -22,7 +22,7 @@ use Data::Dumper; use FindBin(); use IPC::Cmd qw(can_run); use List::MoreUtils qw(any); -use File::Slurp qw(read_file); +use File::Slurp qw(read_file); my $t = Test::Mojo->new('Koha::REST::V1'); my $spec = $t->get_ok( '/api/v1/', 'Correctly fetched the spec' )->tx->res->json; @@ -184,10 +184,10 @@ subtest 'POST (201) have location header' => sub { my $content = read_file($file); if ( grep { $file eq $_ } @exceptions ) { pass("$file is skipped - exception"); - } - elsif ( $content !~ /status\s*=>\s*201/s ) { + } elsif ( $content !~ /status\s*=>\s*201/s ) { pass("$file does not seem to have a POST endpoint"); - } elsif ( $content =~ /\$c->res->headers->location\(.*?\);\s*return\s+\$c->render\s*\(\s*status\s*=>\s*201,/s ) { + } elsif ( $content =~ /\$c->res->headers->location\(.*?\);\s*return\s+\$c->render\s*\(\s*status\s*=>\s*201,/s ) + { pass("$file contains the location header"); } else { fail("$file does not contain the location header"); diff --git a/xt/author/Text_CSV_Various.t b/xt/author/Text_CSV_Various.t index 539234aefb..4de03771b4 100755 --- a/xt/author/Text_CSV_Various.t +++ b/xt/author/Text_CSV_Various.t @@ -21,7 +21,7 @@ #necessary to test your Koha installation. use Modern::Perl; -use open OUT=>':encoding(UTF-8)', ':std'; +use open OUT => ':encoding(UTF-8)', ':std'; use utf8; use Test::More tests => 21; @@ -29,56 +29,64 @@ use Text::CSV; use Text::CSV_XS; sub pretty_line { - my $max = 54; - (@_) or return "#" x $max . "\n"; - my $phrase = " " . shift() . " "; - my $half = "#" x (($max - length($phrase))/2); - return $half . $phrase . $half . "\n"; + my $max = 54; + (@_) or return "#" x $max . "\n"; + my $phrase = " " . shift() . " "; + my $half = "#" x ( ( $max - length($phrase) ) / 2 ); + return $half . $phrase . $half . "\n"; } -my ($csv, $bin, %parsers); +my ( $csv, $bin, %parsers ); -foreach( qw( Text::CSV Text::CSV_XS )) { - ok($csv = $_->new(), $_ . '->new()'); - ok($bin = $_->new({binary=>1}), $_ . '->new({binary=>1})'); +foreach (qw( Text::CSV Text::CSV_XS )) { + ok( $csv = $_->new(), $_ . '->new()' ); + ok( $bin = $_->new( { binary => 1 } ), $_ . '->new({binary=>1})' ); $csv and $parsers{$_} = $csv; - $bin and $parsers{$_ . " (binary)"} = $bin; + $bin and $parsers{ $_ . " (binary)" } = $bin; } my $lines = [ - {description=>"010D: LATIN SMALL LETTER C WITH CARON", character=>'č', line=>'field1,second field,field3,do_we_have_a_č_problem?, f!fth field ,lastfield'}, - {description=>"0117: LATIN SMALL LETTER E WITH DOT ABOVE", character=>'ė', line=>'field1,second field,field3,do_we_have_a_ė_problem?, f!fth field ,lastfield'}, + { + description => "010D: LATIN SMALL LETTER C WITH CARON", character => 'č', + line => 'field1,second field,field3,do_we_have_a_č_problem?, f!fth field ,lastfield' + }, + { + description => "0117: LATIN SMALL LETTER E WITH DOT ABOVE", character => 'ė', + line => 'field1,second field,field3,do_we_have_a_ė_problem?, f!fth field ,lastfield' + }, ]; -ok( scalar(keys %parsers)>0 && scalar(@$lines)>0, +ok( + scalar( keys %parsers ) > 0 && scalar(@$lines) > 0, sprintf "Testing %d lines with %d parsers.", - scalar(@$lines), scalar(keys %parsers) ); + scalar(@$lines), scalar( keys %parsers ) +); -foreach my $key (sort keys %parsers) { +foreach my $key ( sort keys %parsers ) { my $parser = $parsers{$key}; - print "Testing parser $key version " . ($parser->version||'?') . "\n"; + print "Testing parser $key version " . ( $parser->version || '?' ) . "\n"; } my $i = 0; foreach my $line (@$lines) { - print pretty_line("Line " . ++$i); - print pretty_line($line->{description} . ': ' . $line->{character}); - foreach my $key (sort keys %parsers) { + print pretty_line( "Line " . ++$i ); + print pretty_line( $line->{description} . ': ' . $line->{character} ); + foreach my $key ( sort keys %parsers ) { my $parser = $parsers{$key}; - my ($status, $count, @fields); + my ( $status, $count, @fields ); $status = $parser->parse( $line->{line} ); - if( $status ) { - ok($status, "parse ($key)"); + if ($status) { + ok( $status, "parse ($key)" ); @fields = $parser->fields; - $count = scalar(@fields); - is( $count, 6, "Number of fields ($count of 6)"); + $count = scalar(@fields); + is( $count, 6, "Number of fields ($count of 6)" ); my $j = 0; foreach my $f (@fields) { $j++; print "\t field $j: $f\n"; } } else { - ok(! $status, "parse ($key) fails as expected"); #FIXME We never hit this line + ok( !$status, "parse ($key) fails as expected" ); #FIXME We never hit this line } } } diff --git a/xt/author/icondirectories.t b/xt/author/icondirectories.t index d10a0ed26c..64fb7156c0 100755 --- a/xt/author/icondirectories.t +++ b/xt/author/icondirectories.t @@ -41,52 +41,54 @@ my $opac_dir = 'koha-tmpl/opac-tmpl'; my $staff_dir = 'koha-tmpl/intranet-tmpl'; # Find OPAC themes -opendir ( my $dh, $opac_dir ) or die "can't opendir $opac_dir: $!"; +opendir( my $dh, $opac_dir ) or die "can't opendir $opac_dir: $!"; my @opac_themes = grep { not /^\.|lib|js|xslt/ } readdir($dh); close $dh; # Find STAFF themes -opendir ( $dh, $staff_dir ) or die "can't opendir $staff_dir: $!"; +opendir( $dh, $staff_dir ) or die "can't opendir $staff_dir: $!"; my @staff_themes = grep { not /^\.|lib|js/ } readdir($dh); close $dh; # Check existence of OPAC icon dirs -for my $theme ( @opac_themes ) { +for my $theme (@opac_themes) { my $test_dir = "$opac_dir/$theme/itemtypeimg"; ok( -d $test_dir, "opac_icon_directory: $test_dir exists" ); } # Check existence of STAFF icon dirs -for my $theme ( @staff_themes ) { +for my $theme (@staff_themes) { my $test_dir = "$staff_dir/$theme/img/itemtypeimg"; ok( -d $test_dir, "staff_icon_directory: $test_dir exists" ); } # Check for same contents on STAFF and OPAC icondirs # foreach STAFF theme -for my $staff_theme ( @staff_themes ) { - my $staff_icons; # hashref of filenames to sizes +for my $staff_theme (@staff_themes) { + my $staff_icons; # hashref of filenames to sizes my $staff_icon_directory = "$staff_dir/$staff_theme/img/itemtypeimg"; - my $staff_wanted = sub { + my $staff_wanted = sub { my $file = $File::Find::name; $file =~ s/^$staff_icon_directory//; - $staff_icons->{ $file } = -s $_; + $staff_icons->{$file} = -s $_; }; find( { wanted => $staff_wanted }, $staff_icon_directory ); # foreach OPAC theme - for my $opac_theme ( @opac_themes ) { - next if ( $opac_theme =~ /ccsr/ ); # FIXME: skip CCSR opac theme, it fails and there is no point to fix it - my $opac_icons; # hashref of filenames to sizes - my $opac_icon_directory = "$opac_dir/$opac_theme/itemtypeimg"; - my $opac_wanted = sub { + for my $opac_theme (@opac_themes) { + next if ( $opac_theme =~ /ccsr/ ); # FIXME: skip CCSR opac theme, it fails and there is no point to fix it + my $opac_icons; # hashref of filenames to sizes + my $opac_icon_directory = "$opac_dir/$opac_theme/itemtypeimg"; + my $opac_wanted = sub { my $file = $File::Find::name; $file =~ s/^$opac_icon_directory//; - $opac_icons->{ $file } = -s $_; + $opac_icons->{$file} = -s $_; }; find( { wanted => $opac_wanted }, $opac_icon_directory ); - is_deeply( $opac_icons, $staff_icons, "STAFF $staff_theme and OPAC $opac_theme icon directories have same contents" ) - or diag( Data::Dumper->Dump( [ $opac_icons ], [ 'opac_icons' ] ) ); + is_deeply( + $opac_icons, $staff_icons, + "STAFF $staff_theme and OPAC $opac_theme icon directories have same contents" + ) or diag( Data::Dumper->Dump( [$opac_icons], ['opac_icons'] ) ); } } diff --git a/xt/author/podcorrectness.t b/xt/author/podcorrectness.t index c1f1caa78e..f1baf333fe 100755 --- a/xt/author/podcorrectness.t +++ b/xt/author/podcorrectness.t @@ -1,5 +1,6 @@ #!/usr/bin/env perl use Modern::Perl; + =head2 podcorrectness.t This test file checks all perl modules in the C4 directory for POD @@ -18,5 +19,5 @@ use Test::More; eval "use Test::Pod 1.00"; plan skip_all => "Test::Pod 1.00 required for testing POD" if $@; my @poddirs = qw( C4 Koha ); -all_pod_files_ok( all_pod_files( @poddirs ) ); +all_pod_files_ok( all_pod_files(@poddirs) ); diff --git a/xt/author/show-template-structure.pl b/xt/author/show-template-structure.pl index ad496db474..2934e775a6 100755 --- a/xt/author/show-template-structure.pl +++ b/xt/author/show-template-structure.pl @@ -1,7 +1,7 @@ #!/usr/bin/perl # Copyright (C) 2010 Galen Charlton -# +# # This file is part of Koha. # # Koha is free software; you can redistribute it and/or modify it @@ -104,7 +104,9 @@ while (<$fh>) { unless ( exists $valid_tmpl_tags{$tmpl_tag} ) { print "ERROR (line $lineno): $tmpl_tag is not a valid HTML::Template::Pro tag\n"; } - next unless exists $tmpl_structure_tags{$tmpl_tag}; # only care about tags that affect loop or conditional structure + next + unless exists $tmpl_structure_tags{$tmpl_tag} + ; # only care about tags that affect loop or conditional structure if ( $tmpl_structure_tags{$tmpl_tag} ) { # we'll either be pushing or popping the tag stack @@ -117,8 +119,8 @@ while (<$fh>) { } else { my ( $popped_tag, $target, $popped_lineno ) = @{ pop @tag_stack }; if ( $tmpl_tag ne $popped_tag ) { - print "\nERROR (line $lineno): got /$tmpl_tag but expected /$popped_tag to", - " match $popped_tag from line $popped_lineno\n"; + print "\nERROR (line $lineno): got /$tmpl_tag but expected /$popped_tag to", + " match $popped_tag from line $popped_lineno\n"; } else { print " # $target from $popped_lineno\n"; } @@ -140,7 +142,8 @@ while (<$fh>) { } else { my ( $peeked_tag, $target, $peeked_lineno ) = @{ $tag_stack[0] }; if ( $peeked_tag ne "tmpl_if" and $peeked_tag ne "tmpl_unless" ) { - print "ERROR: found $tmpl_tag, but it does not appear to match a tmpl_if. Top of stack is $peeked_tag.\n"; + print + "ERROR: found $tmpl_tag, but it does not appear to match a tmpl_if. Top of stack is $peeked_tag.\n"; } } } @@ -150,12 +153,12 @@ while (<$fh>) { close $fh; # anything left in the stack? -if (scalar @tag_stack > 0) { +if ( scalar @tag_stack > 0 ) { print "ERROR: tag stack is not empty - the following template structures have not been closed:\n"; my $i = 0; - while (my $entry = pop @tag_stack) { + while ( my $entry = pop @tag_stack ) { $i++; - my ( $popped_tag, $target, $popped_lineno ) = @{ $entry }; + my ( $popped_tag, $target, $popped_lineno ) = @{$entry}; print "$i: $popped_tag $target (line $popped_lineno)\n"; } } diff --git a/xt/author/valid-templates.t b/xt/author/valid-templates.t index 3724d03575..44b316ecc7 100755 --- a/xt/author/valid-templates.t +++ b/xt/author/valid-templates.t @@ -33,7 +33,6 @@ This test checks all staff and OPAC templates and includes for syntax errors =cut - use File::Find; use File::Spec; use Template; @@ -42,55 +41,55 @@ use Test::More; my @themes; # OPAC themes -my $opac_dir = 'koha-tmpl/opac-tmpl'; -opendir ( my $dh, $opac_dir ) or die "can't opendir $opac_dir: $!"; +my $opac_dir = 'koha-tmpl/opac-tmpl'; +opendir( my $dh, $opac_dir ) or die "can't opendir $opac_dir: $!"; for my $theme ( grep { not /^\.|lib|js|xslt/ } readdir($dh) ) { push @themes, { type => "opac", theme => $theme, modules => "$opac_dir/$theme/en/modules", includes => "$opac_dir/$theme/en/includes", - } + }; } close $dh; # STAFF themes my $staff_dir = 'koha-tmpl/intranet-tmpl'; -opendir ( $dh, $staff_dir ) or die "can't opendir $staff_dir: $!"; +opendir( $dh, $staff_dir ) or die "can't opendir $staff_dir: $!"; for my $theme ( grep { not /^\.|lib|js/ } readdir($dh) ) { push @themes, { type => "staff", theme => $theme, modules => "$staff_dir/$theme/en/modules", includes => "$staff_dir/$theme/en/includes", - } + }; } close $dh; my $ncpu; if ( $ENV{KOHA_PROVE_CPUS} ) { - $ncpu = $ENV{KOHA_PROVE_CPUS} ; # set number of cpus to use + $ncpu = $ENV{KOHA_PROVE_CPUS}; # set number of cpus to use } else { $ncpu = Sys::CPU::cpu_count(); } -my $pm = Parallel::ForkManager->new($ncpu); +my $pm = Parallel::ForkManager->new($ncpu); # Tests -foreach my $theme ( @themes ) { - $pm->start and next; # do the fork +foreach my $theme (@themes) { + $pm->start and next; # do the fork print "Testing $theme->{'type'} $theme->{'theme'} templates\n"; if ( $theme->{'theme'} eq 'bootstrap' ) { run_template_test( $theme->{'modules'}, $theme->{'includes'}, + # templates to exclude from testing because # they cannot stand alone 'doc-head-close.inc', 'opac-bottom.inc', ); - } - else { + } else { run_template_test( $theme->{'modules'}, $theme->{'includes'}, @@ -106,20 +105,22 @@ done_testing(); sub run_template_test { my $template_path = shift; my $include_path = shift; - my @exclusions = @_; + my @exclusions = @_; my $template_dir = File::Spec->rel2abs($template_path); my $include_dir = File::Spec->rel2abs($include_path); - my $template_test = create_template_test($include_dir, @exclusions); - find( { wanted => $template_test, no_chdir => 1 }, - $template_dir, $include_dir ); + my $template_test = create_template_test( $include_dir, @exclusions ); + find( + { wanted => $template_test, no_chdir => 1 }, + $template_dir, $include_dir + ); } sub create_template_test { - my $includes = shift; + my $includes = shift; my @exclusions = @_; my $interface = $includes =~ s|^.*/([^/]*-tmpl).*$|$1|r; - my $theme = ($interface =~ /opac/) ? 'bootstrap' : 'prog'; + my $theme = ( $interface =~ /opac/ ) ? 'bootstrap' : 'prog'; return sub { my $tt = Template->new( @@ -130,14 +131,14 @@ sub create_template_test { } ); foreach my $exclusion (@exclusions) { - if ($_ =~ /${exclusion}$/) { + if ( $_ =~ /${exclusion}$/ ) { diag("excluding template $_ because it cannot stand on its own"); return; } } my $vars = { interface => $interface, theme => $theme }; my $output; - if ( ! -d $_ ) { # skip dirs + if ( !-d $_ ) { # skip dirs if ( !ok( $tt->process( $_, $vars, \$output ), $_ ) ) { diag( $tt->error ); } diff --git a/xt/check_makefile.t b/xt/check_makefile.t index 91235bfa14..9a9c07bae4 100755 --- a/xt/check_makefile.t +++ b/xt/check_makefile.t @@ -25,13 +25,13 @@ use File::Spec; use File::Slurp qw( read_file ); use Data::Dumper; -my $curdir = File::Spec->curdir(); -my @dirs = `git ls-tree -d --name-only HEAD`; +my $curdir = File::Spec->curdir(); +my @dirs = `git ls-tree -d --name-only HEAD`; my $makefile = read_file("$curdir/Makefile.PL"); my @missing; for my $d ( sort @dirs ) { chomp $d; - next if $d =~ /^debian$/; + next if $d =~ /^debian$/; next if $makefile =~ m{'\./$d('|\/)}xms; push @missing, $d; } diff --git a/xt/find-license-problems.t b/xt/find-license-problems.t index 50e607edea..5f93516aa5 100755 --- a/xt/find-license-problems.t +++ b/xt/find-license-problems.t @@ -30,27 +30,30 @@ use File::Spec; use File::Find; my @files; + sub wanted { my $name = $File::Find::name; push @files, $name - unless $name =~ /\/(\.git|koha-tmpl|node_modules|swagger-ui)(\/.*)?$/ || - $name =~ /\.(gif|jpg|odt|ogg|pdf|png|po|psd|svg|swf|zip|patch)$/ || - $name =~ m[(xt/find-license-problems|xt/fix-old-fsf-address|misc/translator/po2json)] || - ! -f $name; + unless $name =~ /\/(\.git|koha-tmpl|node_modules|swagger-ui)(\/.*)?$/ + || $name =~ /\.(gif|jpg|odt|ogg|pdf|png|po|psd|svg|swf|zip|patch)$/ + || $name =~ m[(xt/find-license-problems|xt/fix-old-fsf-address|misc/translator/po2json)] + || !-f $name; } -find({ wanted => \&wanted, no_chdir => 1 }, File::Spec->curdir()); +find( { wanted => \&wanted, no_chdir => 1 }, File::Spec->curdir() ); foreach my $name (@files) { open( my $fh, '<', $name ) || die "cannot open file $name $!"; - my ( $hascopyright, $hasgpl, $hasv3, $hasorlater, $haslinktolicense, - $hasfranklinst, $is_not_us ) = (0)x7; + my ( + $hascopyright, $hasgpl, $hasv3, $hasorlater, $haslinktolicense, + $hasfranklinst, $is_not_us + ) = (0) x 7; while ( my $line = <$fh> ) { $hascopyright = 1 if ( $line =~ /^(#|--)?\s*Copyright.*\d\d/ ); $hasgpl = 1 if ( $line =~ /GNU General Public License/ ); $hasv3 = 1 if ( $line =~ /either version 3/ ); $hasorlater = 1 - if ( $line =~ /any later version/ + if ( $line =~ /any later version/ || $line =~ /at your option/ ); $haslinktolicense = 1 if $line =~ m|http://www\.gnu\.org/licenses|; $hasfranklinst = 1 if ( $line =~ /51 Franklin Street/ ); @@ -59,10 +62,11 @@ foreach my $name (@files) { close $fh; next unless $hascopyright; next if $is_not_us; - is( $hasgpl - && $hasv3 - && $hasorlater - && $haslinktolicense - && !$hasfranklinst, 1 ) or diag(sprintf "File %s has wrong copyright: hasgpl=%s, hasv3=%s, hasorlater=%s, haslinktolicense=%s, hasfranklinst=%s", $name, $hasgpl, $hasv3, $hasorlater, $haslinktolicense, $hasfranklinst); + is( $hasgpl && $hasv3 && $hasorlater && $haslinktolicense && !$hasfranklinst, 1 ) + or diag( + sprintf + "File %s has wrong copyright: hasgpl=%s, hasv3=%s, hasorlater=%s, haslinktolicense=%s, hasfranklinst=%s", + $name, $hasgpl, $hasv3, $hasorlater, $haslinktolicense, $hasfranklinst + ); } done_testing; diff --git a/xt/find-misplaced-executables.t b/xt/find-misplaced-executables.t index 74c6e6f18e..f0cc340eca 100755 --- a/xt/find-misplaced-executables.t +++ b/xt/find-misplaced-executables.t @@ -26,12 +26,15 @@ use Data::Dumper; use Test::More tests => 1; my @files; + sub wanted { my $name = $File::Find::name; + # Ignore files in .git, blib and node_modules return if $name =~ m[^\./(.git|blib|node_modules)]; + # Ignore directories - return if -d $name; # Skip dir + return if -d $name; # Skip dir # Search for missing x in svc, xt and t if ( $name =~ m[^\./(svc|xt)] && $name !~ m[\./xt/(perltidyrc|fix-old-fsf-address\.exclude)] @@ -50,5 +53,5 @@ sub wanted { push @files, $name if -x $name; } } -find({ wanted => \&wanted, no_chdir => 1}, '.' ); -is(@files, 0) or diag(Dumper @files) ; +find( { wanted => \&wanted, no_chdir => 1 }, '.' ); +is( @files, 0 ) or diag( Dumper @files ); diff --git a/xt/find-missing-csrf.t b/xt/find-missing-csrf.t index 95cbe07a5e..c4d559043b 100755 --- a/xt/find-missing-csrf.t +++ b/xt/find-missing-csrf.t @@ -32,25 +32,24 @@ push @files, `git ls-files 'koha-tmpl/opac-tmpl/bootstrap/en/*.inc'`; push @files, `git ls-files 'koha-tmpl/intranet-tmpl/prog/en/*.tt'`; push @files, `git ls-files 'koha-tmpl/intranet-tmpl/prog/en/*.inc'`; - my @errors; -for my $file ( @files ) { +for my $file (@files) { chomp $file; my @e = check_csrf_in_forms($file); - push @errors, sprintf "%s:%s", $file, join (",", @e) if @e; + push @errors, sprintf "%s:%s", $file, join( ",", @e ) if @e; } is( @errors, 0, "The
            in the following files are missing it's corresponding csrf_token include (see bug 22990)" ) - or diag(Dumper @errors); + or diag( Dumper @errors ); sub check_csrf_in_forms { - my ( $file ) = @_; + my ($file) = @_; my @lines = read_file($file); my @errors; return @errors unless grep { $_ =~ m| $file, errors => \@e } if @e; } is( @errors, 0, "Template variables should be correctly escaped" ) - or diag(Dumper @errors); + or diag( Dumper @errors ); diff --git a/xt/find-missing-op-in-forms.t b/xt/find-missing-op-in-forms.t index 483601f8e3..772f82c9e3 100755 --- a/xt/find-missing-op-in-forms.t +++ b/xt/find-missing-op-in-forms.t @@ -33,10 +33,10 @@ push @files, `git ls-files 'koha-tmpl/intranet-tmpl/prog/en/*.tt'`; push @files, `git ls-files 'koha-tmpl/intranet-tmpl/prog/en/*.inc'`; my @errors; -for my $file ( @files ) { +for my $file (@files) { chomp $file; my @e = catch_missing_op($file); - push @errors, sprintf "%s:%s", $file, join (",", @e) if @e; + push @errors, sprintf "%s:%s", $file, join( ",", @e ) if @e; } is( @@ -72,7 +72,7 @@ sub catch_missing_op { } else { push @errors, $line_open_form; } - $has_op = 0; + $has_op = 0; $in_form = 0; } } diff --git a/xt/single_quotes.t b/xt/single_quotes.t index 2c88d78c33..feda36ba59 100755 --- a/xt/single_quotes.t +++ b/xt/single_quotes.t @@ -32,15 +32,17 @@ push @files, `git ls-files 'koha-tmpl/intranet-tmpl/prog/en/*.tt'`; push @files, `git ls-files 'koha-tmpl/intranet-tmpl/prog/en/*.inc'`; my @errors; -for my $file ( @files ) { +for my $file (@files) { chomp $file; my @lines = sort grep /\_\(\'/, read_file($file); push @errors, { name => $file, lines => \@lines } if @lines; } ok( !@errors, "Files do not contain single quotes _(' " ) - or diag( + or diag( "Files list: \n", - join( "\n", - map { $_->{name} . ': ' . join( ', ', @{ $_->{lines} } ) } @errors ) - ); + join( + "\n", + map { $_->{name} . ': ' . join( ', ', @{ $_->{lines} } ) } @errors + ) + ); diff --git a/xt/verify-debian-docbook.t b/xt/verify-debian-docbook.t index 97c8e948ad..db6e85e469 100755 --- a/xt/verify-debian-docbook.t +++ b/xt/verify-debian-docbook.t @@ -23,10 +23,10 @@ use Modern::Perl; use Test::More qw(no_plan); -my $doc_dir = 'debian/docs'; -my @doc_files = glob($doc_dir . '/*.xml'); -my @command = qw(xmllint --noout); +my $doc_dir = 'debian/docs'; +my @doc_files = glob( $doc_dir . '/*.xml' ); +my @command = qw(xmllint --noout); foreach my $file (@doc_files) { - ok(system(@command, $file) == 0, "XML validation for $file"); + ok( system( @command, $file ) == 0, "XML validation for $file" ); } diff --git a/xt/verify_bib1.att.t b/xt/verify_bib1.att.t index aca317670d..c9ad13117a 100755 --- a/xt/verify_bib1.att.t +++ b/xt/verify_bib1.att.t @@ -19,7 +19,7 @@ use Modern::Perl; use Test::More tests => 2; -foreach my $record_type ( qw( biblios authorities ) ) { +foreach my $record_type (qw( biblios authorities )) { subtest "bib1.att tests for $record_type" => sub { @@ -38,7 +38,7 @@ foreach my $record_type ( qw( biblios authorities ) ) { } } - foreach my $code (keys %{$att_codes}) { + foreach my $code ( keys %{$att_codes} ) { is( $att_codes->{$code}, 1, "Only one occurrence for code ($code)" ); } }; diff --git a/xt/yaml_valid.pl b/xt/yaml_valid.pl index 59e303a4f5..24f9c67921 100755 --- a/xt/yaml_valid.pl +++ b/xt/yaml_valid.pl @@ -42,8 +42,7 @@ say "Testing file: $file"; eval { YAML::XS::LoadFile($file); }; if ($@) { print "KO!\n$@\n"; -} -else { +} else { print "Loading and Syntax OK\n"; } diff --git a/xt/yaml_valid.t b/xt/yaml_valid.t index b60d89c6db..d8b128498a 100755 --- a/xt/yaml_valid.t +++ b/xt/yaml_valid.t @@ -27,12 +27,13 @@ use Test::More; my $filebase = "$FindBin::Bin/../koha-tmpl/intranet-tmpl/prog/en/modules/admin/preferences"; my @files; + sub wanted { my $name = $File::Find::name; push @files, $name if $name =~ /\.pref/; } -find({ wanted => \&wanted, no_chdir => 1 }, $filebase); +find( { wanted => \&wanted, no_chdir => 1 }, $filebase ); plan tests => scalar @files; @@ -41,7 +42,6 @@ foreach my $f (@files) { yaml_file_ok( $f, "$f is YAML" ); } - =head1 NAME yaml_valid.t